text:
package com.lukekorth.fivehundredpx;

import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class AccessToken implements Parcelable {

	private String mToken;
	private String mTokenSecret;

	public AccessToken(String token, String tokenSecret) {
		mToken = token;
		mTokenSecret = tokenSecret;
	}

	AccessToken(HttpResponse response) throws FiveHundredException {
		try {
			Uri responseUri = Uri.parse(EntityUtils.toString(response.getEntity()));

            mToken = responseUri.getQueryParameter("oauth_token");
			mTokenSecret = responseUri.getQueryParameter("oauth_token_secret");
		} catch (ParseException | IOException | NullPointerException e) {
            throw new FiveHundredException(e);
        }
    }

	public String getToken() {
		return mToken;
	}

	public String getTokenSecret() {
		return mTokenSecret;
	}

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mToken);
        dest.writeString(mTokenSecret);
    }

    private AccessToken(Parcel in) {
        mToken = in.readString();
        mTokenSecret = in.readString();
    }

    public static final Creator<AccessToken> CREATOR = new Creator<AccessToken>() {
        public AccessToken createFromParcel(Parcel source) {
            return new AccessToken(source);
        }

        public AccessToken[] newArray(int size) {
            return new AccessToken[size];
        }
    };
}


text:
/*
 * MODIFIED by HaenselAMS on 2017-05-22
 */

package com.snowplowanalytics.snowplow.enrich.common
package loaders

// Scala
import scala.util.control.NonFatal

// Scalaz
import scalaz._
import Scalaz._

// Apache Commons
import org.apache.commons.lang3.StringUtils

// Joda-Time
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}

// This project
import utils.ConversionUtils.singleEncodePcts

/**
 * The dedicated loader for events
 * collected by CloudFront.
 *
 * We support the following CloudFront access
 * log formats:
 *
 * 1. Pre-12 Sep 2012
 * 2. 12 Sep 2012 - 21 Oct 2013
 * 3. 21 Oct 2013 - 29 Apr 2014
 * 4. Potential future updates, provided they
 *    are solely additive in nature
 *
 * For more details on this format, please see:
 * http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#LogFileFormat
 */
object CloudfrontLoader extends Loader[String] {

  // The encoding used on CloudFront logs
  private val CollectorEncoding = "UTF-8"

  // The name of this collector
  private val CollectorName = "cloudfront"

  // Define the regular expression for extracting the fields
  // Adapted from Amazon's own cloudfront-loganalyzer.tgz
  private val CfRegex = {
    val w = "[\\s]+"   // Whitespace regex
    val ow = "(?:" + w // Optional whitespace begins

    // Our regex follows
    (   "([\\S]+)"  +   // Date          / date
    w + "([\\S]+)"  +   // Time          / time
    w + "([\\S]+)"  +   // EdgeLocation  / x-edge-location
    w + "([\\S]+)"  +   // BytesSent     / sc-bytes
    w + "([\\S]+)"  +   // IPAddress     / c-ip
    w + "([\\S]+)"  +   // Operation     / cs-method
    w + "([\\S]+)"  +   // Domain        / cs(Host)
    w + "([\\S]+)"  +   // Object        / cs-uri-stem
    w + "([\\S]+)"  +   // HttpStatus    / sc-status
    w + "([\\S]+)"  +   // Referer       / cs(Referer)
    w + "([\\S]+)"  +   // UserAgent     / cs(User Agent)
    w + "([\\S]+)"  +   // Querystring   / cs-uri-query
    ow + "[\\S]*"   +   // CookieHeader  / cs(Cookie)         added 12 Sep 2012 // TODO: why the *?
    w +  "[\\S]+"   +   // ResultType    / x-edge-result-type added 12 Sep 2012
    w +  "[\\S]+)?" +   // X-Amz-Cf-Id   / x-edge-request-id  added 12 Sep 2012
    ow + "[\\S]+"   +   // XHostHeader   / x-host-header      added 21 Oct 2013
    w +  "[\\S]+"   +   // CsProtocol    / cs-protocol        added 21 Oct 2013
    w +  "[\\S]+)?" +   // CsBytes       / cs-bytes           added 21 Oct 2013
    ow + "[\\S]+"   +   // TimeTaken     / time-taken         added 29 Apr 2014
    w +      ".*)?").r  // Anything added in the future by Amazon
  }

  /**
   * Converts the source string into a
   * ValidatedMaybeCollectorPayload.
   *
   * @param line A line of data to convert
   * @return either a set of validation
   *         errors or an Option-boxed
   *         CanonicalInput object, wrapped
   *         in a Scalaz ValidatioNel.
   */
  def toCollectorPayload(line: String): ValidatedMaybeCollectorPayload = line match {

    // 1. Header row
    case h if (h.startsWith("#Version:") || h.startsWith("#Fields:")) =>
      None.success

    // removed request type check (enables processing POST request sent using navigator.sendBeacon with HAMS JS tracker)

    // 4. Row matches CloudFront format
    case CfRegex(date,
                 time,
                 _,
                 _,
                 ip,
                 _,
                 _,
                 objct,
                 _,
                 rfr,
                 ua,
                 qs) => {

      // Validations, and let's strip double-encodings
      val timestamp = toTimestamp(date, time)
      val querystring = {
        val q = toOption(singleEncodePcts(qs))
        parseQuerystring(q, CollectorEncoding)
      }

      // No validation (yet) on the below
      val userAgent  = singleEncodePcts(ua)
      val refr = singleEncodePcts(rfr)
      val referer = toOption(refr) map toCleanUri

      val api = CollectorApi.parse(objct)

      (timestamp.toValidationNel |@| querystring.toValidationNel |@| api.toValidationNel) { (t, q, a) =>
        CollectorPayload(
          q,
          CollectorName,
          CollectorEncoding,
          None, // No hostname for CloudFront
          Some(t),
          toOption(ip),
          toOption(userAgent),
          referer,
          Nil,  // No headers for CloudFront
          None, // No collector-set user ID for CloudFront
          a,    // API vendor/version
          None, // No content type
          None  // No request body
        ).some
      }
    }

    // 3. Row not recognised
    case _ => "Line does not match CloudFront header or data row formats".failNel[Option[CollectorPayload]]
  }

  /**
   * Converts a CloudFront log-format date and
   * a time to a timestamp.
   *
   * @param date The CloudFront log-format date
   * @param time The CloudFront log-format time
   * @return the timestamp as a Joda DateTime
   *         or an error String, all wrapped in
   *         a Scalaz Validation
   */
  def toTimestamp(date: String, time: String): Validation[String, DateTime] =
    try {
      DateTime.parse("%sT%s+00:00".format(date, time)).success // Construct a UTC ISO date from CloudFront date and time
    } catch {
      case NonFatal(e) =>
        "Unexpected exception converting date [%s] and time [%s] to timestamp: [%s]".format(date, time, e.getMessage).fail
    }

  /**
   * Checks whether a String field is a hyphen
   * "-", which is used by CloudFront to signal
   * a null.
   *
   * @param field The field to check
   * @return True if the String was a hyphen "-"
   */
  def toOption(field: String): Option[String] = Option(field) match {
    case Some("-") => None
    case Some("")  => None
    case s => s // Leaves any other Some(x) or None as-is
  }

  /**
   * 'Cleans' a string to make it parsable by
   * URLDecoder.decode.
   *
   * The '%' character seems to be appended to the
   * end of some URLs in the CloudFront logs, causing
   * Exceptions when using URLDecoder.decode. Perhaps
   * a CloudFront bug?
   *
   * @param s The String to clean
   * @return the cleaned string
   */
  private[loaders] def toCleanUri(uri: String): String =
    StringUtils.removeEnd(uri, "%")
}

redpajama_set_name: RedPajamaGithub


text:
bytefmt
=======

Human readable byte formatter

Example:

```go
  bytefmt.ByteSize(100.5*bytefmt.MEGABYTE) // returns "100.5M"
  bytefmt.ByteSize(uint64(1024)) // returns "1K"
```

For documentation, please see http://godoc.org/github.com/pivotal-golang/bytefmt


text:
package env

import (
	"encoding/json"
	"log"
)

const (
	UnspecificError   = -1
	InvalidBucketId   = 101
	InvalidFileId     = 102
	InvalidBucketSize = 103
	InvalidFileSize   = 104
	FileNotFound      = 105
	InvalidDataId     = 106
)

var statusText = map[int]string{
	UnspecificError:   "Unspecific Error",
	InvalidBucketId:   "BucketId is invalid",
	InvalidFileId:     "FileId is invalid",
	InvalidBucketSize: "Bucket size is too large, valid range is [1, 2048]",
	InvalidFileSize:   "File size is too large. the file size should smaller then 4GB",
	FileNotFound:      "File is not found",
	InvalidDataId:     "DataId is invalid",
}

type Error struct {
	Err     int
	Message string
	Detail  string
}

func NewError(errCode int, detail string) *Error {
	message, _ := statusText[errCode]
	return &Error{
		errCode,
		message,
		detail,
	}
}

func (e *Error) Marshal() []byte {
	if v, err := json.Marshal(e); err != nil {
		log.Println(err)
		return []byte(``)
	} else {
		return v
	}
}

func (e Error) Error() string {
	return string(e.Marshal())
}


text:
[![Latest Stable Version](https://poser.pugx.org/darkwebdesign/symfony-addon-bundle/v/stable?format=flat)](https://packagist.org/packages/darkwebdesign/symfony-addon-bundle)
[![Total Downloads](https://poser.pugx.org/darkwebdesign/symfony-addon-bundle/downloads?format=flat)](https://packagist.org/packages/darkwebdesign/symfony-addon-bundle)
[![License](https://poser.pugx.org/darkwebdesign/symfony-addon-bundle/license?format=flat)](https://packagist.org/packages/darkwebdesign/symfony-addon-bundle)

[![Build Status](https://app.travis-ci.com/darkwebdesign/symfony-addon-bundle.svg?branch=5.4)](https://app.travis-ci.com/darkwebdesign/symfony-addon-bundle)
[![PHP Version](https://img.shields.io/badge/php-7.2%2B-777BB3.svg)](https://php.net/)
[![Symfony Version](https://img.shields.io/badge/symfony-5.4-93C74B.svg)](https://symfony.com/)

Symfony Add-on Bundle conveniently wraps the [Symfony Add-on Pack](https://github.com/darkwebdesign/symfony-addon-pack) with a Symfony Bundle that you can use
in your Symfony applications.

## Installing via Composer

```bash
composer require darkwebdesign/symfony-addon-bundle
```

```bash
composer install
```

## Enabling the bundle in Symfony

```php
// config/bundles.php
return [
    // ...
    DarkWebDesign\SymfonyAddonBundle\DarkWebDesignSymfonyAddonBundle::class => ['all' => true],
];
```

## License

Symfony Add-on Bundle is licensed under the MIT License - see the `LICENSE` file for details.


text:
class Visit < ActiveRecord::Base
  belongs_to :user
  belongs_to :expedition, :counter_cache=>true
  belongs_to :graveyard

  delegate :county, :county_id, :name, :state_id, :state, to: :graveyard

  before_validation :populate_ordinal

  VISITED='visited'
  TODO='todo'

  STATUS_OPTIONS = {
      VISITED => 'Visited This Place',
      TODO => 'On Your To-Do List'
  }

  VISIBILITY_OPTIONS = {
    1000 => 'Public - Everyone can see this',
    0 => 'Private - Only you can see this'
  }

  def todo?
    status == TODO
  end

  def visited?
    status == VISITED
  end

  # status, nounified
  def what
    todo? ? 'todo' : 'visit'
  end

  # A very brief description for link tooltip text
  def caption
    if status == TODO
      "This is on your To-Do List"
    elsif status == VISITED
      text = "You visited this location"
      text += visited_on ? " on #{visited_on.to_s(:sql)}." : "."
    else
      "unknown status #{status}"
    end
  end

  def visible_to?(user)
    return false unless user

    (user.id == self.user_id) || (user.admin?)
  end

  def populate_ordinal
    if self.visited? && ! self.ordinal && self.user
      max = self.user.visits.visited_with_quality.select('max(ordinal) as ordinal').map(&:ordinal).last.to_i
      count = self.user.visits.visited_with_quality.count

      return self.ordinal = 1 + ((max > count) ? max : count)
    end
    true
  end

  def self.visited_with_quality
    where(:status=> 'visited').where("quality >= 8")
  end

  def self.for_user(u)
    where(user_id: u.id).includes(graveyard: :county)
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Circ. N. Y. St. Mus. 24: 58 (1940)

#### Original name
Cladosporium sarraceniae Dearn. & House

### Remarks
null


text:
.. _installation_guide:

%%%%%%%%%%%%%%%%%%
Installation guide
%%%%%%%%%%%%%%%%%%

This section is divided in two parts. On the one hand, we see how to install the
NUBOMEDIA-VCA filters using the repositories of the project. On the other hand,
we see how to install these filters from the source code.

From repositories
=================

In order to install the latest stable version of the NUBOMEDIA-VCA filters in
your local environment, first of all you need an instance of Kurento Media
Server installed in your machine. To do that, use the following commands:

.. sourcecode:: console

   echo "deb http://ubuntu.kurento.org trusty kms6" | sudo tee /etc/apt/sources.list.d/kurento.list
   wget -O - http://ubuntu.kurento.org/kurento.gpg.key | sudo apt-key add -
   sudo apt-get update
   sudo apt-get install kurento-media-server-6.0

Then you are able to install the NUBOMEDIA-VCA filters. To do that, you have
type the following commands:

.. sourcecode:: console

   sudo apt-get install software-properties-common
   sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F04B5A6F
   sudo add-apt-repository "deb http://repository.nubomedia.eu/ trusty main"
   sudo apt-get update

   # To install ear detector filter
   sudo apt-get install nubo-ear-detector nubo-ear-detector-dev

   # To install eye detector filter
   sudo apt-get install nubo-eye-detector nubo-eye-detector-dev

   # To install face detector filter
   sudo apt-get install nubo-face-detector nubo-face-detector-dev

   # To install mouth detector filter
   sudo apt-get install nubo-mouth-detector nubo-mouth-detector-dev

   # To install nose detector filter
   sudo apt-get install nubo-nose-detector nubo-nose-detector-dev

   # To install tracker filter
   sudo apt-get install nubo-tracker nubo-tracker-dev

From source code
================

In order to install the NUBOMEDIA-VCA from the source code you need the
development packages for Kurento. To install these components use the following
commands:

.. sourcecode:: console

   echo "deb http://ubuntu.kurento.org trusty kms6" | sudo tee /etc/apt/sources.list.d/kurento.list
   wget -O - http://ubuntu.kurento.org/kurento.gpg.key | sudo apt-key add -
   sudo apt-get update
   sudo apt-get install kurento-media-server-6.0 kurento-media-server-6.0-dev
   sudo apt-get install kms-core-6.0 kms-core-6.0-dev
   sudo apt-get install cimg-dev
   sudo apt-get install devscripts

After that, you are able to generate the Debian packages of the NUBOMEDIA-VCA
filters from the source code. To do that, you need to clone the official
repository on `GitHub <https://github.com/nubomedia/NUBOMEDIA-VCA>`__ and the
execute the build script.

.. sourcecode:: console

   git clone https://github.com/nubomedia/NUBOMEDIA-VCA.git
   cd NUBOMEDIA-VCA
   ./build.sh

If everything goes well, a new folder called `output` will be created. Inside
this folder you can find the Debian packages for the different filters. To
install these filters, you need to run the following commands:

.. sourcecode:: console

   cd output

   # To install ear detector filter
   sudo dpkg -i nubo-ear-detector_6.6.0~rc1_amd64.deb nubo-ear-detector-dev_6.6.0~rc1_amd64.deb

   # To install eye detector filter
   sudo dpkg -i nubo-eye-detector_6.6.0~rc1_amd64.deb nubo-eye-detector-dev_6.6.0~rc1_amd64.deb

   # To install face detector filter
   sudo dpkg -i nubo-face-detector_6.6.0~rc1_amd64.deb nubo-face-detector-dev_6.6.0~rc1_amd64.deb

   # To install mouth detector filter
   sudo dpkg -i nubo-mouth-detector_6.6.0~rc1_amd64.deb nubo-mouth-detector-dev_6.6.0~rc1_amd64.deb

   # To install nose detector filter
   sudo dpkg -i nubo-nose-detector_6.6.0~rc1_amd64.deb nubo-nose-detector-dev_6.6.0~rc1_amd64.deb

   # To install tracker filter
   sudo dpkg -i nubo-tracker_6.6.0~rc1_amd64.deb nubo-tracker-dev_6.6.0~rc1_amd64.deb


text:
<template name="_tabsRadio">
  {{#ionTabs style="android" class="tabs-radio"}}
    {{> ionTab title="Timeline" path="tabs.timelineRadio" _id=this._id name=this.name }}
    {{> ionTab title="Enquete" path="tabs.pollsRadio" _id=this._id  name=this.name }}
  {{/ionTabs}}
</template>


text:
// <copyright file="Client.cs" company="YAGNI">
// All rights reserved.
// </copyright>
// <summary>Holds implementation of Book model.</summary>

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using LibrarySystem.Models.Enumerations;

namespace LibrarySystem.Models
{
    /// <summary>
    /// Represent a <see cref="Client"/> entity model.
    /// </summary>
    public class Client
    {
        /// <summary>
        /// Pattern for validation of the PIN of the <see cref="Client"/> entity.
        /// </summary>
        private const string PINPattern = @"^[0-9]{10}$";

        /// <summary>
        /// Pattern for validation of the phone number of the <see cref="Client"/> entity.
        /// </summary>
        private const string PhonePattern = @"^\\+?\\d{10,14}$";

        /// <summary>
        /// Pattern for validation of the email address of the <see cref="Client"/> entity.
        /// </summary>
        private const string EmailPattern = @"^(?(\"")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";

        /// <summary>
        /// Lendings of the <see cref="Client"/> entity.
        /// </summary>
        private ICollection<Lending> lendings;

        /// <summary>
        /// Journals of the <see cref="Client"/> entity.
        /// </summary>
        private ICollection<Journal> journals;

        /// <summary>
        /// Initializes a new instance of the <see cref="Client"/> class.
        /// </summary>
        public Client()
        {
            this.lendings = new HashSet<Lending>();

            this.journals = new HashSet<Journal>();
        }

        /// <summary>
        /// Gets or sets the primary key of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Primary key of the <see cref="Client"/> entity.</value>
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        /// <summary>
        /// Gets or sets the first name of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>First name of the <see cref="Client"/> entity.</value>
        [Required]
        [StringLength(20, ErrorMessage = "Client FirstName Invalid Length", MinimumLength = 1)]
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or sets the last name of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Last name of the <see cref="Client"/> entity.</value>
        [Required]
        [StringLength(20, ErrorMessage = "Client LastName Invalid Length", MinimumLength = 1)]
        public string LastName { get; set; }

        /// <summary>
        /// Gets the full name of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Full name of the <see cref="Client"/> entity.</value>
        [NotMapped]
        public string FullName
        {
            get
            {
                return string.Format("{0} {1}", this.FirstName, this.LastName);
            }
        }

        /// <summary>
        /// Gets or sets the gender type of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Gender type of the <see cref="Client"/> entity.</value>
        public GenderType GenderType { get; set; }

        /// <summary>
        /// Gets or sets the Personal Identification Number of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Personal Identification Number of the <see cref="Client"/> entity.</value>
        [Required]
        [RegularExpression(PINPattern, ErrorMessage = "Client PIN Invalid Length")]
        public string PIN { get; set; }

        /// <summary>
        /// Gets or sets the phone number of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Phone number of the <see cref="Client"/> entity.</value>
        [RegularExpression(PhonePattern, ErrorMessage = "Client Phone Invalid Length")]
        public string Phone { get; set; }

        /// <summary>
        /// Gets or sets the email address of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Email address of the <see cref="Client"/> entity.</value>
        [RegularExpression(EmailPattern, ErrorMessage = "Invalid Client Email")]
        public string Email { get; set; }

        /// <summary>
        /// Gets or sets foreign key of the address of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Primary key of the address of the <see cref="Client"/> entity.</value>
        public int AddressId { get; set; }

        /// <summary>
        /// Gets or sets the the address of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Address of the <see cref="Client"/> entity.</value>
        public virtual Address Address { get; set; }

        /// <summary>
        /// Gets or sets the landings of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Initial collection of landings of the <see cref="Client"/> entity.</value>
        public virtual ICollection<Lending> Lendings
        {
            get
            {
                return this.lendings;
            }

            set
            {
                this.lendings = value;
            }
        }

        /// <summary>
        /// Gets or sets the journals of the <see cref="Client"/> entity.
        /// </summary>
        /// <value>Initial collection of journals of the <see cref="Client"/> entity.</value>
        public virtual ICollection<Journal> Journals
        {
            get
            {
                return this.journals;
            }

            set
            {
                this.journals = value;
            }
        }
    }
}


text:
import React from 'react';
import FeedItem from './feed-item-redux';

class FeedList extends React.Component {

	constructor(props) {
		super(props)
	}

	render() {
		let feeds = [];

		for (let key in this.props.feeds) {
			//feeds.push(<FeedItem onItemClick = {this.props.onItemClick} selected = {this.props.selected} feed = {this.props.feeds[key]} key = {this.props.feeds[key]._id}/>)
			feeds.push(<FeedItem {...this.props} feed = {this.props.feeds[key]} key = {this.props.feeds[key]._id}/>)	//JSX spread attributes
		}

		return (

					{feeds}

		)
	}
}

export default FeedList


text:
<?php

/**
 *
 *
 * @package     sfMediaBrowser
 * @author      Vincent Agnano <vincent.agnano@particul.es>
 *
 * Note :
 * - ***_path = system directory
 * - ***_dir = browser directory
 */
class BasesfMediaBrowserActions extends sfActions
{
  public function preExecute()
  {
    // symfony web path
    $this->web_path = sfConfig::get('sf_web_dir');

    // Configured root dir
    $this->root_dir = sfconfig::get('app_sf_media_browser_root_dir');

    $this->root_path = realpath($this->web_path.'/'.$this->root_dir);
  }

  public function executeList(sfWebRequest $request)
  {
    $requested_dir = urldecode($request->getParameter('dir'));
    $relative_dir = $this->isPathSecured($this->root_path, $this->web_path.'/'.$requested_dir)
                  ? $requested_dir
                  : $this->root_dir;

    // browser dir relative to sf_web_dir
    $this->relative_dir = $relative_dir;
    // User dispay dir
    $this->display_dir = preg_replace('`^('.$this->root_dir.')`', '', $relative_dir);
    // browser parent dir
    $this->parent_dir = $this->relative_dir != $this->root_dir ? dirname($this->relative_dir) : '';
    // system path for current dir
    $this->path = $this->web_path.$relative_dir;

    // list of sub-directories in current dir
    $this->dirs = $this->getDirectories($this->path);
    // list of files in current dir
    $this->files = $this->getFiles($this->path);
    $this->current_route = $this->getContext()->getRouting()->getCurrentRouteName();
    $this->current_params = $request->getGetParameters();

    // forms
    $this->upload_form = new sfMediaBrowserUploadForm(array('directory' => $relative_dir));
    $this->dir_form = new sfMediaBrowserDirectoryForm(array('directory' => $relative_dir));
  }

  public function executeSelect(sfWebRequest $request)
  {
    $this->setLayout(dirname(__FILE__).'/../templates/popupLayout');
    $this->setTemplate('list');
    $this->executeList($request);
  }

  public function executeCreateDirectory(sfWebRequest $request)
  {
    $form = new sfMediaBrowserDirectoryForm();
    $form->bind($request->getParameter('directory'));
    if($form->isValid())
    {
      $real_path = realpath($this->web_path.'/'.$form->getValue('directory'));
      $full_name = $real_path.'/'.$form->getValue('name');
      $created = @mkdir($full_name);
      @chmod($full_name, 0777);
      $this->getUser()->setFlash($created ? 'notice' : 'error', 'directory.create');
    }
    $this->redirect($request->getReferer());
  }

  public function executeDeleteDirectory(sfWebRequest $request)
  {
    $dir = new sfMediaBrowserFileObject(urldecode($request->getParameter('directory')));
    $deleted = sfMediaBrowserUtils::deleteRecursive($dir->getPath());
    $this->getUser()->setFlash($deleted ? 'notice' : 'error', 'directory.delete');
    $this->redirect($request->getReferer());
  }

  public function executeCreateFile(sfWebRequest $request)
  {
    $upload = $request->getParameter('upload');
    $form = new sfMediaBrowserUploadForm();
    $form->setUploadDir($upload['directory']);
    $form->bind($upload, $request->getFiles('upload'));
    if($form->isValid())
    {
      $post_file = $form->getValue('file');
      $filename = $post_file->getOriginalName();
      $name = sfMediaBrowserStringUtils::slugify(pathinfo($filename, PATHINFO_FILENAME));
      $ext = pathinfo($filename, PATHINFO_EXTENSION);
      $fullname = $ext ? $name.'.'.$ext : $name;
      $destination_dir = realpath(sfConfig::get('sf_web_dir').'/'.$upload['directory']);
      // thumbnail
      if(sfConfig::get('app_sf_media_browser_thumbnails_enabled', false) && sfMediaBrowserUtils::getTypeFromExtension($ext) == 'image')
      {
        $this->generateThumbnail($post_file->getTempName(), $fullname, $destination_dir);
      }
      $this->getUser()->setFlash('notice', 'file.create');
      $post_file->save($destination_dir.'/'.$fullname);
    }
    else
    {
      $this->getUser()->setFlash('error', 'file.create');
    }
    $this->redirect($request->getReferer());
  }

  /**
   *@todo Get rid of the purpose of urldecode for 'dir' parameter
   */
  public function executeMove(sfWebRequest $request)
  {
    $file = new sfMediaBrowserFileObject($request->getParameter('file'));
    $dir = new sfMediaBrowserFileObject(urldecode($request->getParameter('dir')));
    $new_name = $dir->getPath().'/'.$file->getName(true);

    $error = null;
    try
    {
      $moved = rename($file->getPath(), $new_name);
    }
    catch(Exception $e)
    {
      $error = $e;
    }

    if($request->isXmlHttpRequest())
    {
      sfContext::getInstance()->getConfiguration()->loadHelpers(array('I18N'));
      if($error)
      {
        $reponse = array('status' => 'error', 'message' => __('Some error occured.'));
      }
      elseif($moved)
      {
        $response = array('status' => 'notice', 'message' => __('The file was successfully moved.'));
      }
      elseif(file_exists($new_name))
      {
        $response = array('status' => 'error', 'message' => __('A file with the same name already exists in this folder.'));
      }
      else
      {
        $response = array('status' => 'error', 'message' => __('Some error occured.'));
      }
      return $this->renderText(json_encode($response));
    }
    $this->redirect($request->getReferer());
  }

  public function executeRename(sfWebRequest $request)
  {
    $file = new sfMediaBrowserFileObject($request->getParameter('file'));
    $name = sfMediaBrowserStringUtils::slugify(pathinfo($request->getParameter('name'), PATHINFO_FILENAME));
    $ext = $file->getExtension();
    $valid_filename = $ext ? $name.'.'.$ext : $name;
    $new_name = dirname($file->getPath()).'/'.$valid_filename;

    $error = null;
    try
    {
      $renamed = rename($file->getPath(), $new_name);
    }
    catch(Exception $e)
    {
      $error = $e;
    }

    if($request->isXmlHttpRequest())
    {
      sfContext::getInstance()->getConfiguration()->loadHelpers(array('I18N'));
      if($error)
      {
        $reponse = array('status' => 'error', 'message' => __('Some error occured.'));
      }
      elseif($renamed)
      {
        $response = array('status' => 'notice', 'message' => __('The file was successfully renamed.'), 'name' => $valid_filename, 'url' => dirname($file->getUrl()).'/'.$valid_filename);
      }
      elseif(file_exists($new_name))
      {
        $response = array('status' => 'error', 'message' => __('A file with the same name already exists in this folder.'));
      }
      else
      {
        $response = array('status' => 'error', 'message' => __('Some error occured.'));
      }
      return $this->renderText(json_encode($response));
    }
    $this->redirect($request->getReferer());
  }

  /**
   * @TODO
   * @param $file
   */
  protected function generateThumbnail($source_file, $destination_name, $destination_dir)
  {
    if(!class_exists('sfImage'))
    {
      throw new sfException('sfImageTransformPlugin must be installed in order to generate thumbnails.');
    }
    $thumb = new sfImage($source_file);
    $thumb->thumbnail(sfConfig::get('app_sf_media_browser_thumbnails_max_width', 64),
                     sfConfig::get('app_sf_media_browser_thumbnails_max_height', 64));
    $destination_dir = $destination_dir.'/'.sfConfig::get('app_sf_media_browser_thumbnails_dir');
    if(!file_exists($destination_dir))
    {
      mkdir($destination_dir);
      chmod($destination_dir, 0777);
    }
    return $thumb->saveAs($destination_dir.'/'.$destination_name);
  }

  public function executeDeleteFile(sfWebRequest $request)
  {
    $file = $this->createFileObject(urldecode($request->getParameter('file')));
    $file->delete();
    $this->getUser()->setFlash('notice', 'file.delete');
    $this->redirect($request->getReferer());
  }

# Protected

  protected function createFileObject($file)
  {
    $class = sfMediaBrowserUtils::getTypeFromExtension(pathinfo($file, PATHINFO_EXTENSION)) == 'image'
            ? 'sfMediaBrowserImageObject'
            : 'sfMediaBrowserFileObject'
            ;
    return new $class($file);
  }

  /**
   *
   * @param string $root_path
   * @param string $dir
   * @return mixed <string, boolean>
   */
  protected function isPathSecured($root_path, $requested_path)
  {
    return preg_match('`^'.realpath($root_path).'`', realpath($requested_path));
  }

  protected function getDirectories($path)
  {
    return sfFinder::type('dir')->
            maxdepth(0)->
            prune('.*')->
            discard(sfConfig::get('app_sf_media_browser_thumbnails_dir'))->
            sort_by_name()->
            relative()->
            in($path)
            ;
  }

  protected function getFiles($path)
  {
    return sfFinder::type('files')->
             maxdepth(0)->
             relative()->
             sort_by_name()->
             in($path)
             ;
  }

}


text:
django-wedding
==============

A wedding site for Django

# Instructions for setup

+ `django-admin.py startproject <project-name>`

## Modify settings.py

+ Add `django-wedding` to INSTALLED_APPS

+ Update ALLOWED_HOSTS: `['127.0.0.1', 'stephandwill.com', 'www.stephandwill.com', 'willandsteph.com', 'www.willandsteph.com']`

+ TIME_ZONE: `'America/New_York'`


text:
package rabbit.zip;

/** GZipState for validating the compression method.
 *
 * @author Robert Olofsson
 */
class CompressionMethodReader implements GZipUnpackState {
    private final GZipUnpackListener listener;
    private static final int GZIP_DEFLATE = 8;

    public CompressionMethodReader (GZipUnpackListener listener) {
	this.listener = listener;
    }

    public void handleCurrentData (GZipUnpacker unpacker) {
	throw new IllegalStateException ("need more input");
    }

    public boolean needsInput () {
	return true;
    }

    public void handleBuffer (GZipUnpacker unpacker, byte[] buf, int off, int len) {
	if (len <= 0)
	    return;
	byte b = buf[off];
	if (b != GZIP_DEFLATE) {
	    String err = "unknown compression method: " + b;
	    Exception e =
		new IllegalArgumentException (err);
	    listener.failed (e);
	}
	GZipUnpackState fr = new FlagReader (listener);
	unpacker.setState (fr);
	fr.handleBuffer (unpacker, buf, off + 1, len - 1);
    }
}


text:
/*

	ractive-events-select2
	======================

	Version <%= pkg.version %>.

	<< description goes here... >>

	==========================

	Troubleshooting: If you're using a module system in your app (AMD or
	something more nodey) then you may need to change the paths below,
	where it says `require( 'ractive' )` or `define([ 'ractive' ]...)`.

	==========================

	Usage: Include this file on your page below Ractive, e.g:

	    <script src='lib/ractive.js'></script>
	    <script src='lib/ractive-events-select2.js'></script>

	Or, if you're using a module loader, require this module:

	    // requiring the plugin will 'activate' it - no need to use
	    // the return value
	    require( 'ractive-events-select2' );

	<< more specific instructions for this plugin go here... >>

*/

(function(global, factory) {

	'use strict';

	// AMD environment
	if (typeof define === 'function' && define.amd) {
		define(['ractive', 'jquery'], factory);
	}

	// Common JS (i.e. node/browserify)
	else if (typeof module !== 'undefined' && module.exports && typeof require === 'function') {
		factory(require('ractive'), require('jquery'));
	}

	// browser global
	else if (global.Ractive && global.jQuery) {
		factory(global.Ractive, global.jQuery);
	} else {
		throw new Error('Could not find Ractive! It must be loaded before the ractive-events-select2 plugin');
	}

}(typeof window !== 'undefined' ? window : this, function(Ractive, $) {

	'use strict';

	/* plugin code goes here */

	/*
		change is fired whenever an option is selected or removed.
		select2:open is fired whenever the dropdown is opened. select2:opening is fired before this and can be prevented.
		select2:close is fired whenever the dropdown is closed. select2:closing is fired before this and can be prevented.
		select2:select is fired whenever a result is selected. select2:selecting is fired before this and can be prevented.
		select2:unselect is fired whenever a result is unselected. select2:unselecting is fired before this and can be prevented.
	*/

	Ractive.events.select2opening = function(node, fire) {
		var select2openingHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:opening', select2openingHandler);

			return {
				teardown: function() {
					$(node).off('select2:opening', select2openingHandler);
				}
			};
		};
	};

	Ractive.events.select2open = function(node, fire) {
		var select2openHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:open', select2openHandler);

			return {
				teardown: function() {
					$(node).off('select2:open', select2openHandler);
				}
			};
		};
	};

	Ractive.events.select2closing = function(node, fire) {
		var select2closingHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:closing', select2closingHandler);

			return {
				teardown: function() {
					$(node).off('select2:closing', select2closingHandler);
				}
			};
		};
	};

	Ractive.events.select2close = function(node, fire) {
		var select2closeHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:close', select2closeHandler);

			return {
				teardown: function() {
					$(node).off('select2:close', select2closeHandler);
				}
			};
		};
	};

	Ractive.events.select2selecting = function(node, fire) {
		var select2selectingHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:selecting', select2selectingHandler);

			return {
				teardown: function() {
					$(node).off('select2:selecting', select2selectingHandler);
				}
			};
		};
	};

	Ractive.events.select2select = function(node, fire) {
		var select2selectHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:select', select2selectHandler);

			return {
				teardown: function() {
					$(node).off('select2:select', select2selectHandler);
				}
			};
		};
	};

	Ractive.events.select2unselecting = function(node, fire) {
		var select2unselectingHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:unselecting', select2unselectingHandler);

			return {
				teardown: function() {
					$(node).off('select2:unselecting', select2unselectingHandler);
				}
			};
		};
	};

	Ractive.events.select2unselect = function(node, fire) {
		var select2unselectHandler = function(event) {
			fire({
				node: node,
				original: event
			});

			$(node).on('select2:unselect', select2unselectHandler);

			return {
				teardown: function() {
					$(node).off('select2:unselect', select2unselectHandler);
				}
			};
		};
	};

}));


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

<?php echo $title;?>

            <form role="form" method="post" action="<?=base_url().'user_profile/edit_experience/'.$experience['id']?>">
            <?=validation_errors()?>

                        Title

                            <input type="text" name="title" class="form-control my-control"  placeholder="Enter title for the experience" value="<?=set_value('title', $experience['title']);?>"/>

                        <?=form_error('title')?>

                        Postition / Designation

                            <input type="text" name="position" class="form-control my-control"  placeholder="Enter Your Position/Designation" value="<?=set_value('position', $experience['position']);?>"/>

                        <?=form_error('position')?>

                        Company Name

                            <input type="text" name="company_name" class="form-control my-control" placeholder="Enter Company Name" value="<?=set_value('company_name', $experience['company_name']);?>"/>

                        <?= form_error('company_name') ?>

                        Start Year

                            <select name="start_year" class="form-control my-control">
                                <option value="">Select Year</option>
                                <?php
                                    for($i=date("Y"); $i>=1900; $i--):
                                ?>
                                <option value="<?=$i?>" <?php if(set_value('start_year', $experience['start_year']) == $i) echo "selected"; ?>><?=$i?></option>
                                <?php
                                    endfor;
                                ?>
                            </select>

                        <?= form_error('start_year') ?>

                        Duration

                            <input type="number" step="1" min="0" max="50" name="duration" class="form-control my-control" placeholder="Enter how long you worked in the company." value="<?=set_value('duration',$experience['duration']);?>"/>
                            <?= form_error('duration') ?>
                            <select name="duration_unit" class="form-control">
                                <option value="1" <?php  if(set_value('duration_unit', $experience['duration_unit'])==1){echo 'selected';}?>>Year</option>
                                <option value="2" <?php  if(set_value('duration_unit', $experience['duration_unit'])==2){echo 'selected';}?>>Month</option>
                            </select>
                        <?= form_error('duration_unit') ?>

                        Description

                            <textarea name="description" rows='5' class="form-control my-control" placeholder="Enter a short description about your experience there."><?=set_value('description', $experience['description']);?></textarea>

                        <?= form_error('duration_unit') ?>

                        <input type="submit" value="Update" class="btn btn-primary btn-sm">

        </form>


text:
import os

# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))

# Demo mode, change to false in a production enviroment
DEMO_MODE = True

# Enable debug mode.
DEBUG = True

# Enable form validation.
CSRF_ENABLED = True

# Secret key for session management. You can generate random strings here:
# http://clsc.net/tools-old/random-string-generator.php
SECRET_KEY = 'A_NICE_STRONG_RANDOM_SECRET_KEY_GOES_HERE'

# Connect to the database
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'database.db')

# Set the root URL for the site
BASE_URL = 'http://0.0.0.0:5000'

# Set the email address for the service (e.g., admin@example.com)
APP_EMAIL = 'admin@example.com'
APP_EMAIL_NAME = 'carlae'  # or None if you don't want to use an name for the address book

# We use Mailgun to send emails, enter credentials here
MAILGUN_DOMAIN = "example.com"
MAILGUN_API_KEY = "APIKEY_GOES_HERE"

# Set the message sent on invitation here
INVITATION_EMAIL_TEMPLATE = u"""
Howdy,

You've been invited to join Carlae, a URL shortening service.

Go ahead and use the link to register & activate your account:

%s

Activation codes eventually expire; request a new one if that's the case.

Welcome!
"""

# Development info
CARLAE_VERSION = ''
CARLAE_BUILD = ''


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class SendSNMPAction extends Action {
}


text:
package com.fionapet.business.repository;

import com.fionapet.business.entity.Pet;
import com.fionapet.business.entity.PetView;
import org.dubbo.x.repository.DaoBase;

import java.util.List;

/**
 * 宠物
* Created by tom on 2016-07-19 10:31:06.
 **/
public interface PetDao extends DaoBase<Pet> {
    List<Pet> findByGestId(String gestId);
}


text: console.log('Hello, World!');


text:
class Curly::Response
  attr_reader :body, :head, :status, :curl_code, :curl_error

  alias_method :code, :status

  alias_method :curl_return_code,   :curl_code
  alias_method :curl_error_message, :curl_error

  def initialize
    @body   = ''
    @head   = ''
    @status = 0
  end

  # returns +true+ if the http status code returned by the server falls within
  # the 2xx range, +false+ otherwise.
  def success?
    @status >= 200 && @status < 300
  end

  def headers
    @headers ||= @head.split(/\r\n/).each_with_object({}) do |line, h|
      key, value = line.split(': ', 2)
      next unless value

      # There may be multiple headers with the same key and different values.
      # for example, Set-Cookie.
      if !h.has_key?(key)
        h[key] = value
      elsif h[key].instance_of?(Array)
        h[key].push(value)
      else
        h[key] = [h[key], value]
      end
    end
  end

end


text:
namespace falconn {
namespace core {

// Computes *SQUARED* Euclidean distance between sparse or dense vectors.

template <typename CoordinateType = float, typename IndexType = int32_t>
struct EuclideanDistanceSparse {
  typedef std::vector<std::pair<IndexType, CoordinateType>> VectorType;

  CoordinateType operator()(const VectorType& p1, const VectorType& p2) {
    CoordinateType res = 0.0;
    IndexType ii1 = 0, ii2 = 0;
    IndexType p1size = p1.size();
    IndexType p2size = p2.size();
    CoordinateType x;

    while (ii1 < p1size || ii2 < p2size) {
      if (ii2 == p2size) {
        x = p1[ii1].second;
        res += x * x;
        ++ii1;
        continue;
      }
      if (ii1 == p1size) {
        x = p2[ii2].second;
        res += x * x;
        ++ii2;
        continue;
      }
      if (p1[ii1].first < p2[ii2].first) {
        x = p1[ii1].second;
        res += x * x;
        ++ii1;
        continue;
      }
      if (p2[ii2].first < p1[ii1].first) {
        x = p2[ii2].second;
        res += x * x;
        ++ii2;
        continue;
      }
      x = p1[ii1].second;
      x -= p2[ii2].second;
      res += x * x;
      ++ii1;
      ++ii2;
    }

    return res;
  }
};

// The Dense functions assume that the data points are stored as dense
// Eigen column vectors.

template <typename CoordinateType = float>
struct EuclideanDistanceDense {
  typedef Eigen::Matrix<CoordinateType, Eigen::Dynamic, 1, Eigen::ColMajor>
      VectorType;

  template <typename Derived1, typename Derived2>
  CoordinateType operator()(const Eigen::MatrixBase<Derived1>& p1,
                            const Eigen::MatrixBase<Derived2>& p2) {
    return (p1 - p2).squaredNorm();
  }
};

}  // namespace core
}  // namespace falconn

#endif


text:
@media print
{
 /**
  * @section basic layout preparation
  * @see     http://www.yaml.de/en/documentation/css-components/layout-for-print-media.html
  */

  /* (en) change font size unit to [pt] - avoiding problems with [px] unit in Gecko based browsers  */
  /* (de) Wechsel der der Schriftgrößen-Maßheinheit zu [pt] - Probleme mit Maßeinheit [px] in Gecko-basierten Browsern vermeiden */
  body { font-size: 10pt; }

  /* (en) Reset Scrollbar-Fix for FF in screenlayout */
  /* (de) Zurücksetzen des Scrollbar-Fix for FF aus dem Screenlayout */
  html { height: auto; margin-bottom: 0; }

  /* (en) Hide unneeded container of the screenlayout in print layout */
  /* (de) Für den Druck nicht benötigte Container des Layouts abschalten */
  #topnav, #nav, #search { display: none; }

  /* (en) Disable background graphics of links  */
  /* (de) Abschalten evlt. vorhandener Hintergrundgrafiken zur Linkkennzeichnung */
  body a[href^="http:"],
  body a[href^="https:"] {
    padding-left: 0;
    background-image: none;
  }

 /**
  * (en) overflow:hidden Bug in print layouts
  * (de) overflow:hidden Bug in Drucklayouts
  *
  * @bugfix
  * @since     3.0
  * @affected  FF2.0, FF3.0, IE7
  * @css-for   all browsers
  * @valid     yes
  */

  .floatbox,
  .subcolumns,
  .subcolums_oldgecko { overflow:visible; display: table; }

  /* (en) Linearising subtemplates */
  /* (de) Linearisierung der Subtemplates */
  .c25l, .c33l, .c38l, .c50l, .c62l, .c66l, .c75l,
  .c25r, .c33r, .c38r, .c50r, .c62r, .c66r, .c75r {
    width: 100%; margin:0; padding: 0; float:none !important; overflow:visible; display:table !important;
  }
  .subc, .subcl, .subcr  { margin: 0; padding: 0; }

  /* (en) make .print class visible */
  /* (de) .print-Klasse sichtbar schalten */
  .print { position: static; left: 0; }

  /* (en) generic class to hide elements for print */
  /* (de) Allgemeine CSS Klasse, um beliebige Elemente in der Druckausgabe auszublenden */
  .noprint { display:none !important; }

  /*------------------------------------------------------------------------------------------------------*/

  /* (en) Avoid page breaks right after headings */
  /* (de) Vermeidung von Seitenumbrüchen direkt nach einer Überschrift */
  h1,h2,h3,h4,h5,h6 { page-break-after:avoid; }

  /*------------------------------------------------------------------------------------------------------*/

  /* (en) Preparation for optional column labels */
  /* (de) optionale Spaltenauszeichnung */

  #col1_content:before, #col2_content:before, #col3_content:before {
    content: "";
    color:#888;
    background:inherit;
    display:block;
    font-weight:bold;
    font-size:1.5em;
  }
}


text:
<?php

namespace randomhost\Alexa\Responder\Intent\Fun;

use randomhost\Alexa\Responder\AbstractResponder;
use randomhost\Alexa\Responder\ResponderInterface;

class Surprise extends AbstractResponder implements ResponderInterface
{
    /**
     * Runs the Responder.
     *
     * @return $this
     */
    public function run()
    {
        $surprises = $this->config->get('response', 'surprise');
        if (is_null($surprises) || empty($surprises)) {
            $this->response
                ->respondSSML(
                    $this->withSound(
                        self::SOUND_ERROR,
                        'Dieser Skill beinhaltet keine Easter Eggs.'
                    )
                )
                ->endSession(true);

            return $this;
        }

        $surprise = $this->randomizeResponseText($surprises);

        if (!empty($surprise['description'])) {
            $this->response->withCard(
                'Überraschung',
                $surprise['description']
            );
        }

        $this->response
            ->respondSSML(
                sprintf(
                    '<speak>%1$s%2$s</speak>',
                    empty($surprise['audio']) ? '' : $this->buildSoundTag($surprise['audio']),
                    empty($surprise['text']) ? '' : $surprise['text']
                )
            )
            ->endSession(true);

        return $this;
    }
}


text:
package org.apache.harmony.luni.tests.java.net;

import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;

import java.io.Serializable;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;

import java.security.Permission;

import org.apache.harmony.luni.tests.java.net.InetAddressTest.MockSecurityManager;
import org.apache.harmony.testframework.serialization.SerializationTest;
import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;

@TestTargetClass(Inet6Address.class)
public class Inet6AddressTest extends junit.framework.TestCase {

    /**
     * @tests java.net.Inet6Address#isMulticastAddress()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isMulticastAddress",
        args = {}
    )
    public void test_isMulticastAddress() {

        String addrName = "";
        InetAddress addr = null;

        try {

            // IP V6 regular multicast and non-multicast tests
            //
            // Create 2 IP v6 addresses and call "isMulticastAddress()"
            // A prefix of "11111111" means that the address is multicast
            // The first one will be one with the prefix the second without

            addrName = "FFFF::42:42"; // 11111111 = FFFF
            addr = Inet6Address.getByName(addrName);
            assertTrue("Multicast address " + addrName + " not detected.", addr
                    .isMulticastAddress());

            addrName = "42::42:42"; // an non-multicast address
            addr = Inet6Address.getByName(addrName);
            assertTrue("Non multicast address " + addrName
                    + " reporting as a multicast address.", !addr
                    .isMulticastAddress());

            // IPv4-compatible IPv6 address tests
            //
            // Now create 2 IP v6 addresses that are IP v4 compatable
            // to IP v6 addresses. The address prefix for a multicast ip v4
            // address is 1110 for the last 16 bits ::d.d.d.d
            // We expect these to be false

            addrName = "::224.42.42.42"; // an ipv4 multicast addr 1110 = 224
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 compatable address " + addrName
                    + " reported incorrectly as multicast.", !addr
                    .isMulticastAddress());

            addrName = "::42.42.42.42"; // an ipv4 non-multicast address
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 compatable address " + addrName
                    + " reported incorrectly as multicast.", !addr
                    .isMulticastAddress());

            // IPv4-mapped IPv6 address tests
            //
            // Now create 2 IP v6 addresses that are IP v4 compatable
            // to IP v6 addresses. The address prefix for a multicast ip v4
            // address is 1110 for the last 16 bits ::FFFF:d.d.d.d

            addrName = "::FFFF:224.42.42.42"; // an ipv4 multicast addr 1110 =
            // 224
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-mapped IPv6 multicast address " + addrName
                    + " not detected.", addr.isMulticastAddress());

            addrName = "::FFFF:42.42.42.42"; // an ipv4 non-multicast address
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-mapped IPv6 non-multicast address " + addrName
                    + " reporting as a multicast address.", !addr
                    .isMulticastAddress());
        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isAnyLocalAddress()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isAnyLocalAddress",
        args = {}
    )
    public void test_isAnyLocalAddress() {

        String addrName = "";
        InetAddress addr = null;

        try {

            // test to ensure that the unspecified address returns tru
            addrName = "::0"; // The unspecified address
            addr = InetAddress.getByName(addrName);
            assertTrue(
                    "The unspecified (also known as wildcard and any local address) "
                            + addrName + " not detected.", addr
                            .isAnyLocalAddress());

            addrName = "::"; // another form of the unspecified address
            addr = InetAddress.getByName(addrName);
            assertTrue(
                    "The unspecified (also known as wildcard and any local address) "
                            + addrName + " not detected.", addr
                            .isAnyLocalAddress());

            addrName = "::1"; // The loopback address
            addr = InetAddress.getByName(addrName);
            assertTrue("The addresses " + addrName
                    + " incorrectly reporting an the unspecified address.",
                    !addr.isAnyLocalAddress());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isLoopbackAddress()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isLoopbackAddress",
        args = {}
    )
    public void test_isLoopbackAddress() {

        String addrName = "";
        try {

            // IP V6 regular address tests for loopback
            // The loopback address for IPv6 is ::1

            addrName = "::1";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 loopback address " + addrName + " not detected.",
                    addr.isLoopbackAddress());

            addrName = "::2";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address incorrectly " + addrName
                    + " detected as a loopback address.", !addr
                    .isLoopbackAddress());

            // a loopback address should be 127.d.d.d
            addrName = "42:42::42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address incorrectly " + addrName
                    + " detected as a loopback address.", !addr
                    .isLoopbackAddress());

            // IPv4-compatible IPv6 address tests
            //
            // Now create 2 IP v6 addresses that are IP v4 compatable
            // to IP v6 addresses. The address prefix for a multicast ip v4
            // address is 1110 for the last 16 bits ::d.d.d.d
            // We expect these to be false, as they are not IPv4 addresses

            // a loopback address should be 127.d.d.d
            addrName = "::127.0.0.0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-compatible IPv6 address " + addrName
                    + " detected incorrectly as a loopback.", !addr
                    .isLoopbackAddress());

            addrName = "::127.42.42.42"; // a loopback address should be
            // 127.d.d.d
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-compatible IPv6 address " + addrName
                    + " detected incorrectly as a loopback.", !addr
                    .isLoopbackAddress());

            // a loopback address should be 127.d.d.d
            addrName = "::42.42.42.42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-compatible IPv6 address " + addrName
                    + " detected incorrectly as a loopback.", !addr
                    .isLoopbackAddress());

            // IPv4-mapped IPv6 address tests
            //
            // Now create 2 IP v6 addresses that are IP v4 compatable
            // to IP v6 addresses. The address prefix for a multicast ip v4
            // address is 1110 for the last 16 bits ::FFFF:d.d.d.d

            // a loopback address should be 127.d.d.d
            addrName = "::FFFF:127.0.0.0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-compatible IPv6 loopback address " + addrName
                    + " not detected.", addr.isLoopbackAddress());

            // a loopback address should be 127.d.d.d
            addrName = "::FFFF:127.42.42.42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-compatible IPv6 loopback address " + addrName
                    + " not detected.", addr.isLoopbackAddress());

            // a loopback address should be 127.d.d.d
            addrName = "::FFFF:42.42.42.42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4-compatible IPv6 address incorrectly " + addrName
                    + " detected as a loopback address.", !addr
                    .isLoopbackAddress());

        } catch (UnknownHostException e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isLinkLocalAddress()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isLinkLocalAddress",
        args = {}
    )
    public void test_isLinkLocalAddress() {

        String addrName = "";
        try {
            // IP V6 regular address tests for link local addresses
            //
            // Link local addresses are FE80:: -
            // FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF

            addrName = "FE80::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 link local address " + addrName + " not detected.",
                    addr.isLinkLocalAddress());

            addrName = "FEBF::FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 link local address " + addrName + " not detected.",
                    addr.isLinkLocalAddress());

            addrName = "FEC0::1";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address " + addrName
                    + " detected incorrectly as a link local address.", !addr
                    .isLinkLocalAddress());

            addrName = "FD80::1:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address " + addrName
                    + " detected incorrectly as a link local address.", !addr
                    .isLinkLocalAddress());

            addrName = "FE7F::FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address " + addrName
                    + " detected incorrectly as a link local address.", !addr
                    .isLinkLocalAddress());
        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }

    }

    /**
     * @tests java.net.Inet6Address#isSiteLocalAddress()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isSiteLocalAddress",
        args = {}
    )
    public void test_isSiteLocalAddress() {
        String addrName = "";
        try {
            // IP V6 regular address tests for link local addresses
            //
            // Link local addresses are FEC0::0 through to
            // FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF

            addrName = "FEC0::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 site local address " + addrName + " not detected.",
                    addr.isSiteLocalAddress());

            addrName = "FEFF::FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 site local address " + addrName + " not detected.",
                    addr.isSiteLocalAddress());

            addrName = "FEBF::FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address " + addrName
                    + " detected incorrectly as a site local address.", !addr
                    .isSiteLocalAddress());

            addrName = "FFC0::0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 address " + addrName
                    + " detected incorrectly as a site local address.", !addr
                    .isSiteLocalAddress());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isMCGlobal()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isMCGlobal",
        args = {}
    )
    public void test_isMCGlobal() {
        String addrName = "";
        try {
            // IP V6 regular address tests for Mulitcase Global addresses
            //
            // Multicast global addresses are FFxE:/112 where x is
            // a set of flags, and the addition 112 bits make up
            // the global address space

            addrName = "FF0E::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 global mutlicast address " + addrName
                    + " not detected.", addr.isMCGlobal());

            addrName = "FF0E:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 global multicast address " + addrName
                    + " not detected.", addr.isMCGlobal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFFE::0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 global mutlicast address " + addrName
                    + " not detected.", addr.isMCGlobal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFFE:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 global multicast address " + addrName
                    + " not detected.", addr.isMCGlobal());

            // a sample MC organizational address
            addrName = "FF08:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast organizational " + addrName
                    + " incorrectly indicated as a global address.", !addr
                    .isMCGlobal());

            // a sample MC site address
            addrName = "FF05:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast site address " + addrName
                    + " incorrectly indicated as a global address.", !addr
                    .isMCGlobal());

            // a sample MC link address
            addrName = "FF02:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast link address " + addrName
                    + " incorrectly indicated as a global address.", !addr
                    .isMCGlobal());

            // a sample MC Node
            addrName = "FF01:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast node address " + addrName
                    + " incorrectly indicated as a global address.", !addr
                    .isMCGlobal());

            // IPv4-mapped IPv6 address tests
            addrName = "::FFFF:224.0.1.0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 global multicast address " + addrName
                    + " not identified as a global multicast address.", addr
                    .isMCGlobal());

            addrName = "::FFFF:238.255.255.255";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 global multicast address " + addrName
                    + " not identified as a global multicast address.", addr
                    .isMCGlobal());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isMCNodeLocal()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isMCNodeLocal",
        args = {}
    )
    public void test_isMCNodeLocal() {
        String addrName = "";
        try {
            // IP V6 regular address tests for Mulitcase node local addresses
            //
            // Multicast node local addresses are FFx1:/112 where x is
            // a set of flags, and the addition 112 bits make up
            // the global address space

            addrName = "FF01::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 node-local mutlicast address " + addrName
                    + " not detected.", addr.isMCNodeLocal());

            addrName = "FF01:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 node-local multicast address " + addrName
                    + " not detected.", addr.isMCNodeLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF1::0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 node-local mutlicast address " + addrName
                    + " not detected.", addr.isMCNodeLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF1:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 node-local multicast address " + addrName
                    + " not detected.", addr.isMCNodeLocal());

            // a sample MC organizational address
            addrName = "FF08:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast organizational address " + addrName
                    + " incorrectly indicated as a node-local address.", !addr
                    .isMCNodeLocal());

            // a sample MC site address
            addrName = "FF05:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast site address " + addrName
                    + " incorrectly indicated as a node-local address.", !addr
                    .isMCNodeLocal());

            // a sample MC link address
            addrName = "FF02:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast link address " + addrName
                    + " incorrectly indicated as a node-local address.", !addr
                    .isMCNodeLocal());

            // a sample MC global address
            addrName = "FF0E:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 mulitcast node address " + addrName
                    + " incorrectly indicated as a node-local address.", !addr
                    .isMCNodeLocal());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isMCLinkLocal()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isMCLinkLocal",
        args = {}
    )
    public void test_isMCLinkLocal() {
        String addrName = "";
        try {
            // IP V6 regular address tests for Mulitcase link local addresses
            //
            // Multicast link local addresses are FFx2:/112 where x is
            // a set of flags, and the addition 112 bits make up
            // the global address space

            addrName = "FF02::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 link local multicast address " + addrName
                    + " not detected.", addr.isMCLinkLocal());

            addrName = "FF02:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 link local multicast address " + addrName
                    + " not detected.", addr.isMCLinkLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF2::0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 link local multicast address " + addrName
                    + " not detected.", addr.isMCLinkLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF2:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 link local multicast address " + addrName
                    + " not detected.", addr.isMCLinkLocal());

            // a sample MC organizational address
            addrName = "FF08:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 organization multicast address "
                            + addrName
                            + " incorrectly indicated as a link-local mulitcast address.",
                    !addr.isMCLinkLocal());

            // a sample MC site address
            addrName = "FF05:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 site-local mulitcast address "
                            + addrName
                            + " incorrectly indicated as a link-local mulitcast address.",
                    !addr.isMCLinkLocal());

            // a sample MC global address
            addrName = "FF0E:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 global multicast address "
                            + addrName
                            + " incorrectly indicated as a link-local mulitcast address.",
                    !addr.isMCLinkLocal());

            // a sample MC Node
            addrName = "FF01:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 mulitcast node address "
                            + addrName
                            + " incorrectly indicated as a link-local mulitcast address.",
                    !addr.isMCLinkLocal());

            // Ipv4-mapped IPv6 addresses

            addrName = "::FFFF:224.0.0.0"; // a multicast addr 1110
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 link-local multicast address " + addrName
                    + " not identified as a link-local multicast address.",
                    addr.isMCLinkLocal());

            addrName = "::FFFF:224.0.0.255"; // a multicast addr 1110
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 link-local multicast address " + addrName
                    + " not identified as a link-local multicast address.",
                    addr.isMCLinkLocal());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isMCSiteLocal()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isMCSiteLocal",
        args = {}
    )
    public void test_isMCSiteLocal() {
        String addrName = "";
        try {
            // IP V6 regular address tests for Multicast site-local addresses
            //
            // Multicast global addresses are FFx5:/112 where x is
            // a set of flags, and the addition 112 bits make up
            // the global address space

            addrName = "FF05::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 site-local mutlicast address " + addrName
                    + " not detected.", addr.isMCSiteLocal());

            addrName = "FF05:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 site-local multicast address " + addrName
                    + " not detected.", addr.isMCSiteLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF5::0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 site-local mutlicast address " + addrName
                    + " not detected.", addr.isMCSiteLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF5:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 site-local multicast address " + addrName
                    + " not detected.", addr.isMCSiteLocal());

            // a sample MC organizational address
            addrName = "FF08:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 organization multicast address "
                            + addrName
                            + " incorrectly indicated as a site-local mulitcast address.",
                    !addr.isMCSiteLocal());

            // a sample MC global address
            addrName = "FF0E:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 global mulitcast address "
                            + addrName
                            + " incorrectly indicated as a site-local mulitcast address.",
                    !addr.isMCSiteLocal());

            // a sample MC link address
            addrName = "FF02:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 link-local multicast address "
                            + addrName
                            + " incorrectly indicated as a site-local mulitcast address.",
                    !addr.isMCSiteLocal());

            // a sample MC Node
            addrName = "FF01:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 mulitcast node address "
                            + addrName
                            + " incorrectly indicated as a site-local mulitcast address.",
                    !addr.isMCSiteLocal());

            // IPv4-mapped IPv6 addresses
            addrName = "::FFFF:239.255.0.0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 site-local multicast address " + addrName
                    + " not identified as a site-local multicast address.",
                    addr.isMCSiteLocal());

            addrName = "::FFFF:239.255.255.255";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 site-local multicast address " + addrName
                    + " not identified as a site-local multicast address.",
                    addr.isMCSiteLocal());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isMCOrgLocal()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isMCOrgLocal",
        args = {}
    )
    public void test_isMCOrgLocal() {
        String addrName = "";
        try {
            // IP V6 regular address tests for Mulitcase organization-local
            // addresses
            //
            // Multicast global addresses are FFxE:/112 where x is
            // a set of flags, and the addition 112 bits make up
            // the global address space

            addrName = "FF08::0";
            InetAddress addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 organization-local mutlicast address " + addrName
                    + " not detected.", addr.isMCOrgLocal());

            addrName = "FF08:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 organization-local multicast address " + addrName
                    + " not detected.", addr.isMCOrgLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF8::0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 organization-local mutlicast address " + addrName
                    + " not detected.", addr.isMCOrgLocal());

            // a currently invalid address as the prefix FFxE
            // is only valid for x = {1,0} as the rest are reserved
            addrName = "FFF8:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv6 organization-local multicast address " + addrName
                    + " not detected.", addr.isMCOrgLocal());

            // a sample MC global address
            addrName = "FF0E:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 global multicast address "
                            + addrName
                            + " incorrectly indicated as an organization-local mulitcast address.",
                    !addr.isMCOrgLocal());

            // a sample MC site address
            addrName = "FF05:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 site-local mulitcast address "
                            + addrName
                            + " incorrectly indicated as an organization-local mulitcast address.",
                    !addr.isMCOrgLocal());

            // a sample MC link address
            addrName = "FF02:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 link-local multicast address "
                            + addrName
                            + " incorrectly indicated as an organization-local mulitcast address.",
                    !addr.isMCOrgLocal());

            // a sample MC Node
            addrName = "FF01:42:42:42:42:42:42:42";
            addr = Inet6Address.getByName(addrName);
            assertTrue(
                    "IPv6 mulitcast node address "
                            + addrName
                            + " incorrectly indicated as an organization-local mulitcast address.",
                    !addr.isMCOrgLocal());

            // IPv4-mapped IPv6 addresses

            addrName = "::FFFF:239.192.0.0";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 org-local multicast address " + addrName
                    + " not identified as a org-local multicast address.", addr
                    .isMCOrgLocal());

            addrName = "::FFFF:239.195.255.255";
            addr = Inet6Address.getByName(addrName);
            assertTrue("IPv4 org-local multicast address " + addrName
                    + " not identified as a org-local multicast address.", addr
                    .isMCOrgLocal());

        } catch (Exception e) {
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#isIPv4CompatibleAddress()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isIPv4CompatibleAddress",
        args = {}
    )
    public void test_isIPv4CompatibleAddress() {
        String addrName = "";
        Inet6Address addr = null;

        try {

            // Tests a number of addresses to see if they are compatable with
            // IPv6 addresses

            addrName = "FFFF::42:42"; // 11111111 = FFFF
            addr = (Inet6Address) InetAddress.getByName(addrName);
            assertTrue("A non-compatable IPv6 address " + addrName
                    + " incorrectly identified as a IPv4 compatable address.",
                    !addr.isIPv4CompatibleAddress());

            // IPv4-compatible IPv6 address tests
            //
            // Now create 2 IP v6 addresses that are IP v4 compatable
            // to IP v6 addresses.

            addrName = "::0.0.0.0";
            addr = (Inet6Address) InetAddress.getByName(addrName);
            assertTrue("IPv4 compatable address " + addrName
                    + " not detected correctly.", addr
                    .isIPv4CompatibleAddress());

            addrName = "::255.255.255.255"; // an ipv4 non-multicast address
            addr = (Inet6Address) InetAddress.getByName(addrName);
            assertTrue("IPv4 compatable address " + addrName
                    + " not detected correctly.", addr
                    .isIPv4CompatibleAddress());

        } catch (Exception e) {
            e.printStackTrace();
            fail("Unknown address : " + addrName);
        }
    }

    /**
     * @tests java.net.Inet6Address#getByName(java.lang.String)
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "",
        method = "getByName",
        args = {java.lang.String.class}
    )
    public void test_getByNameLjava_lang_String() throws Exception {
        // ones to add "::255.255.255.255", "::FFFF:0.0.0.0",
        // "0.0.0.0.0.0::255.255.255.255", "F:F:F:F:F:F:F:F",
        // "[F:F:F:F:F:F:F:F]"
        String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
                "::1", "0", /* jdk1.5 accepts 0 as valid */
                "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
                "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
                "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0" };

        String invalidIPAddresses[] = { "FFFF:FFFF" };

        for (int i = 0; i < validIPAddresses.length; i++) {

            InetAddress.getByName(validIPAddresses[i]);

            //exercise positive cache
            InetAddress.getByName(validIPAddresses[i]);

            if (!validIPAddresses[i].equals("0")) {
                String tempIPAddress = "[" + validIPAddresses[i] + "]";
                InetAddress.getByName(tempIPAddress);
            }
        }

        for (int i = 0; i < invalidIPAddresses.length; i++) {
            try {
                InetAddress.getByName(invalidIPAddresses[i]);
                fail("Invalid IP address incorrectly recognized as valid: "
                        + invalidIPAddresses[i]);
            } catch (Exception e) {
            }

            //exercise negative cache
            try {
                InetAddress.getByName(invalidIPAddresses[i]);
                fail("Invalid IP address incorrectly recognized as valid: "
                        + invalidIPAddresses[i]);
            } catch (Exception e) {
            }
        }
    }

    /**
     * @tests java.net.Inet6Address#getByAddress(String, byte[], int)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getByAddress",
        args = {java.lang.String.class, byte[].class, int.class}
    )
    public void test_getByAddressLString$BI() throws UnknownHostException{
        try {
            Inet6Address.getByAddress("123", null, 0);
            fail("should throw UnknownHostException");
        } catch (UnknownHostException uhe) {
            // expected
        }
        byte[] addr1 = { (byte) 127, 0, 0, 1 };
        try {
            Inet6Address.getByAddress("123", addr1, 0);
            fail("should throw UnknownHostException");
        } catch (UnknownHostException uhe) {
            // expected
        }

        byte[] addr2 = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02,
                0x11, 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
                (byte) 0xB2 };

        // should not throw any exception
        Inet6Address.getByAddress("123", addr2, 3);
        Inet6Address.getByAddress("123", addr2, 0);
        Inet6Address.getByAddress("123", addr2, -1);
    }

    /**
     * @tests java.net.Inet6Address#getByAddress(String, byte[],
     *        NetworkInterface)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getByAddress",
        args = {java.lang.String.class, byte[].class, java.net.NetworkInterface.class}
    )
    public void test_getByAddressLString$BLNetworkInterface()
            throws UnknownHostException {
        NetworkInterface nif = null;
        try {
            Inet6Address.getByAddress("123", null, nif);
            fail("should throw UnknownHostException");
        } catch (UnknownHostException uhe) {
            // expected
        }
        byte[] addr1 = { (byte) 127, 0, 0, 1 };
        try {
            Inet6Address.getByAddress("123", addr1, nif);
            fail("should throw UnknownHostException");
        } catch (UnknownHostException uhe) {
            // expected
        }
        byte[] addr2 = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02,
                0x11, 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte)

                0x7C, (byte) 0xB2 };
        // should not throw any exception
        Inet6Address.getByAddress("123", addr2, nif);
    }

    /**
     * @throws UnknownHostException
     * @tests java.net.Inet6Address#getScopeID()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getScopeId",
        args = {}
    )
    public void test_getScopeID() throws UnknownHostException {
        Inet6Address v6ia;
        byte[] addr = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02, 0x11,
                0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
                (byte) 0xB2 };

        v6ia = Inet6Address.getByAddress("123", addr, 3);
        assertEquals(3, v6ia.getScopeId());

        v6ia = Inet6Address.getByAddress("123", addr, 0);
        assertEquals(0, v6ia.getScopeId());

        v6ia = Inet6Address.getByAddress("123", addr, -1);
        assertEquals(0, v6ia.getScopeId());
    }

    /**
     * @tests java.net.Inet6Address#getScopedInterface()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getScopedInterface",
        args = {}
    )
    public void test_getScopedInterface() throws UnknownHostException {
        byte[] addr = { (byte) 0xFE, (byte) 0x80, (byte) 0x09, (byte) 0xb5,
                (byte) 0x6b, (byte) 0xa4, 0, 0, 0, 0, 0, 0, (byte) 0x09,
                (byte) 0xb5, (byte) 0x6b, (byte) 0xa4 };
        Inet6Address v6Addr;
        v6Addr = Inet6Address.getByAddress("123", addr, null);
        assertNull(v6Addr.getScopedInterface());
    }

    int bytesToInt(byte bytes[], int start) {

        int byteMask = 255;
        int value = ((bytes[start + 3] & byteMask))
                | ((bytes[start + 2] & byteMask) << 8)
                | ((bytes[start + 1] & byteMask) << 16)
                | ((bytes[start] & byteMask) << 24);
        return value;

    }

    String byteArrayToHexString(byte bytes[], boolean leadingZeros) {

        String fullString = "";
        int times = bytes.length / 4;
        int intArray[] = new int[times];
        for (int i = 0; i < times; i++) {
            intArray[i] = bytesToInt(bytes, i * 4);
        }

        return intArrayToHexString(intArray, leadingZeros);
    }

    void intToBytes(int value, byte bytes[], int start) {

        int byteMask = 255;
        bytes[start + 3] = (byte) (value & byteMask);
        bytes[start + 2] = (byte) ((value >> 8) & byteMask);
        bytes[start + 1] = (byte) ((value >> 16) & byteMask);
        bytes[start] = (byte) ((value >> 24) & byteMask);
    }

    String intArrayToHexString(int ints[], boolean leadingZeros) {

        String fullString = "";
        String tempString;
        int intsLength = ints.length;
        for (int i = 0; i < intsLength; i++) {
            tempString = Integer.toHexString(ints[i]);
            while (tempString.length() < 4 && leadingZeros) {
                tempString = "0" + tempString;
            }
            if (i + 1 < intsLength) {
                tempString += ":";
            }
            fullString += tempString;
        }

        return fullString.toUpperCase();
    }

    // comparator for Inet6Address objects
    private static final SerializableAssert COMPARATOR = new SerializableAssert() {
        public void assertDeserialized(Serializable initial,
                Serializable deserialized) {

            Inet6Address initAddr = (Inet6Address) initial;
            Inet6Address desrAddr = (Inet6Address) deserialized;

            byte[] iaAddresss = initAddr.getAddress();
            byte[] deIAAddresss = desrAddr.getAddress();
            for (int i = 0; i < iaAddresss.length; i++) {
                assertEquals(iaAddresss[i], deIAAddresss[i]);
            }
            assertEquals(initAddr.getScopeId(), desrAddr.getScopeId());
            assertEquals(initAddr.getScopedInterface(), desrAddr
                    .getScopedInterface());
        }
    };

    /**
     * @tests serialization/deserialization compatibility.
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "Checks serialization",
        method = "!SerializationSelf",
        args = {}
    )
    public void testSerializationSelf() throws Exception {

        byte[] localv6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };

        SerializationTest.verifySelf(InetAddress.getByAddress(localv6),
                COMPARATOR);
    }

    /**
     * @tests serialization/deserialization compatibility with RI.
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "Checks serialization",
        method = "!SerializationGolden",
        args = {}
    )
    public void testSerializationCompatibility() throws Exception {

        byte[] localv6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };

        Object[] addresses = { InetAddress.getByAddress(localv6),
                // Regression for Harmony-1039: ser-form has
                // null interface name
                InetAddress.getByAddress(localv6) };

        SerializationTest.verifyGolden(this, addresses, COMPARATOR);
    }

    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "equals",
        args = {java.lang.Object.class}
    )
    public void test_equals() throws Exception {
        InetAddress addr = Inet6Address.getByName("239.191.255.255");
        assertTrue(addr.equals(addr));
        InetAddress addr1 = Inet6Address.getByName("127.0.0.1");
        InetAddress addr2 = Inet6Address.getByName("localhost");
        assertTrue(addr1.equals(addr2));
        assertFalse(addr.equals(addr1));

        InetAddress addr3 = Inet6Address.getByName("127.0.0");
        assertFalse(addr1.equals(addr3));
    }

    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getHostAddress",
        args = {}
    )
    public void test_getHostAddress() throws Exception {
        InetAddress aAddr = Inet6Address.getByName("localhost");
        assertEquals("127.0.0.1", aAddr.getHostAddress());

        aAddr = Inet6Address.getByName("127.0.0.1");
        assertEquals("127.0.0.1", aAddr.getHostAddress());

        aAddr = Inet6Address.getByName("224.0.0.0");
        assertEquals("224.0.0.0", aAddr.getHostAddress());

        aAddr = Inet6Address.getByName("1");
        assertEquals("0.0.0.1", aAddr.getHostAddress());

        aAddr = Inet6Address.getByName("1.1");
        assertEquals("1.0.0.1", aAddr.getHostAddress());

        aAddr = Inet6Address.getByName("1.1.1");
        assertEquals("1.1.0.1", aAddr.getHostAddress());

        byte[] bAddr = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02, 0x11,
                0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
                (byte) 0xB2 };
        aAddr = Inet6Address.getByAddress(bAddr);
        String aString = aAddr.getHostAddress();
        assertTrue(aString.equals("fe80:0:0:0:211:25ff:fef8:7cb2") ||
                   aString.equals("fe80::211:25ff:fef8:7cb2"));

        byte[] cAddr = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
                (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
                (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
                (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
        aAddr = Inet6Address.getByAddress(cAddr);
        assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", aAddr.getHostAddress());

        byte[] dAddr = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
        aAddr = Inet6Address.getByAddress(dAddr);
        aString = aAddr.getHostAddress();
        assertTrue(aString.equals("0:0:0:0:0:0:0:0") ||
                   aString.equals("::"));

        byte[] eAddr = { (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
                (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
                (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b,
                (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f};
        aAddr = Inet6Address.getByAddress(eAddr);
        assertEquals("1:203:405:607:809:a0b:c0d:e0f", aAddr.getHostAddress());

        byte[] fAddr = { (byte) 0x00, (byte) 0x10, (byte) 0x20, (byte) 0x30,
                (byte) 0x40, (byte) 0x50, (byte) 0x60, (byte) 0x70,
                (byte) 0x80, (byte) 0x90, (byte) 0xa0, (byte) 0xb0,
                (byte) 0xc0, (byte) 0xd0, (byte) 0xe0, (byte) 0xf0};
        aAddr = Inet6Address.getByAddress(fAddr);
        assertEquals("10:2030:4050:6070:8090:a0b0:c0d0:e0f0", aAddr.getHostAddress());
    }

    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "hashCode",
        args = {}
    )
    public void test_hashCode() throws Exception {
        InetAddress addr1 = Inet6Address.getByName("1.1");
        InetAddress addr2 = Inet6Address.getByName("1.1.1");
        assertFalse(addr1.hashCode() == addr2.hashCode());

        addr2 = Inet6Address.getByName("1.0.0.1");
        assertTrue(addr1.hashCode() == addr2.hashCode());

        addr1 = Inet6Address.getByName("127.0.0.1");
        addr2 = Inet6Address.getByName("localhost");
        assertTrue(addr1.hashCode() == addr2.hashCode());
    }

    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "toString",
        args = {}
    )
    public void test_toString() throws Exception {
        String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
                "::1", "0", /* jdk1.5 accepts 0 as valid */
                "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
                "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
                "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0" };

        String [] resultStrings = {"/0:0:0:0:0:0:102:304", "/0:0:0:0:0:0:0:0",
                "/0:0:0:0:0:0:0:0", "/1:0:0:0:0:0:0:0", "/1:0:0:0:0:0:0:0",
                "/0:0:0:0:0:0:0:1",
                "/0.0.0.0", "/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
                "/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "/0:0:0:0:0:0:0:0",
                "/0:0:0:0:0:0:0:0"};

        for(int i = 0; i < validIPAddresses.length; i++) {
            InetAddress ia = Inet6Address.getByName(validIPAddresses[i]);
            String result = ia.toString();
            assertNotNull(result);
            //assertEquals("toString method returns incorrect value: " +
            //        result, resultStrings[i], result);
        }
    }
}