text:
layout: default
description: AQL offers some bit manipulation and interpretation functions for bitwise arithmetic
title: AQL Bit Functions
---
Bit functions
=============

Introduced in: v3.7.7

AQL offers some bit manipulation and interpretation functions for bitwise
arithmetic.

These functions can operate on numeric integer values in the range between 0
and 4294967295 (232 - 1), both included. This allows treating numbers as
bitsets of up to 32 members. Using any of the bit functions on numbers outside
the supported range will make the function return `null` and register a warning.

The value range for the bit functions is conservatively small, so that no
precision loss or rounding errors should occur when the input/output values of
bit functions are passed around or sent over the wire to client applications
with unknown precision number types.

BIT_AND()
---------

`BIT_AND(numbersArray) → result`

And-combines the numeric values in *numbersArray* into a single numeric result
value.

- **numbersArray** (array): array with numeric input values
- returns **result** (number\|null): and-combined result

The function expects an array with numeric values as its input. The values in
the array must be numbers, which must not be negative. The maximum supported
input number value is 232 - 1. Input number values outside the allowed
range will make the function return `null` and produce a warning. Any `null`
values in the input array are ignored.

---

`BIT_AND(value1, value2) → result`

If two numbers are passed as individual function parameters to `BIT_AND()`, it
will return the bitwise and value of its two operands. Only numbers in the
range 0 to 232 - 1 are allowed as input values.

- **value1** (number): first operand
- **value2** (number): second operand
- returns **result** (number\|null): and-combined result

```aql
BIT_AND([1, 4, 8, 16]) // 0
BIT_AND([3, 7, 63]) // 3
BIT_AND([255, 127, null, 63]) // 63
BIT_AND(127, 255) // 127
BIT_AND("foo") // null
```

BIT_CONSTRUCT()
---------------

`BIT_CONSTRUCT(positionsArray) → result`

Construct a number value with its bits set at the positions given in the array.

- **positionArray** (array): array with bit positions to set (zero-based)
- returns **result** (number\|null): the generated number

The function expects an array with numeric values as its input. The values in
the array must be numbers, which must not be negative. The maximum supported
input number value is 31. Input number values outside the allowed range will
make the function return `null` and produce a warning.

```aql
BIT_CONSTRUCT([1, 2, 3]) // 14
BIT_CONSTRUCT([0, 4, 8]) // 273
BIT_CONSTRUCT([0, 1, 10, 31]) // 2147484675
```

BIT_DECONSTRUCT()
-----------------

`BIT_DECONSTRUCT(number) → positionsArray`

Deconstruct a number value into an array with the positions of its set bits.

- **number** (number): the input value to deconstruct
- returns **positionArray** (array\|null): array with bit positions set (zero-based)

The function turns a numeric value into an array with the positions of all its
set bits. The positions in the output array are zero-based.
The input value must be a number between 0 and 232 - 1 (including).
The function will return `null` for any other inputs and produce a warning.

```aql
BIT_DECONSTRUCT(14) // [1, 2, 3]
BIT_DECONSTRUCT(273) // [0, 4, 8]
BIT_DECONSTRUCT(2147484675) // [0, 1, 10, 31]
```

BIT_FROM_STRING()
-----------------

`BIT_FROM_STRING(bitstring) → number`

Converts a bitstring (consisting of digits `0` and `1`) into a number.

To convert a number into a bitstring, see [BIT_TO_STRING()](#bit_to_string).

- **bitstring** (string): string sequence consisting of `0` and `1` characters
- returns **number** (number\|null): the parsed number

The input value must be a bitstring, consisting only of `0` and `1` characters.
The bitstring can contain up to 32 significant bits, including any leading zeros.
Note that the bitstring must not start with `0b`.
If the bitstring has an invalid format, this function returns `null` and produces
a warning.

```aql
BIT_FROM_STRING("0111") // 7
BIT_FROM_STRING("000000000000010") // 2
BIT_FROM_STRING("11010111011101") // 13789
BIT_FROM_STRING("100000000000000000000") // 1048756
```

BIT_NEGATE()
------------

`BIT_NEGATE(number, bits) → result`

Bitwise-negates the bits in **number**, and keeps up to **bits** bits in the
result.

- **number** (number): the number to negate
- **bits** (number): number of bits to keep in the result (0 to 32)
- returns **result** (number\|null): the resulting number, with up to **bits**
  significant bits

The input value must be a number between 0 and 232 - 1 (including).
The number of bits must be between 0 and 32. The function will return `null` for
any other inputs and produce a warning.

```aql
BIT_NEGATE(0, 8) // 255
BIT_NEGATE(0, 10) // 1023
BIT_NEGATE(3, 4) // 12
BIT_NEGATE(446359921, 32) // 3848607374
```

BIT_OR()
--------

`BIT_OR(numbersArray) → result`

Or-combines the numeric values in *numbersArray* into a single numeric result
value.

- **numbersArray** (array): array with numeric input values
- returns **result** (number\|null): or-combined result

The function expects an array with numeric values as its input. The values in
the array must be numbers, which must not be negative. The maximum supported
input number value is 232 - 1. Input number values outside the
allowed range will make the function return `null` and produce a warning.
Any `null` values in the input array are ignored.

---

`BIT_OR(value1, value2) → result`

If two numbers are passed as individual function parameters to `BIT_OR()`, it
will return the bitwise or value of its two operands. Only numbers in the range
0 to 232 - 1 are allowed as input values.

- **value1** (number): first operand
- **value2** (number): second operand
- returns **result** (number\|null): or-combined result

```aql
BIT_OR([1, 4, 8, 16]) // 29
BIT_OR([3, 7, 63]) // 63
BIT_OR([255, 127, null, 63]) // 255
BIT_OR(255, 127) // 255
BIT_OR("foo") // null
```

BIT_POPCOUNT()
--------------

`BIT_POPCOUNT(number) → result`

Counts the number of bits set in the input value.

- **number** (number): array with numeric input values
- returns **result** (number\|null): number of bits set in the input value

The input value must be a number between 0 and 232 - 1 (including).
The function will return `null` for any other inputs and produce a warning.

```aql
BIT_POPCOUNT(0) // 0
BIT_POPCOUNT(255) // 8
BIT_POPCOUNT(69399252) // 12
BIT_POPCOUNT("foo") // null
```

BIT_SHIFT_LEFT()
----------------

`BIT_SHIFT_LEFT(number, shift, bits) → result`

Bitwise-shifts the bits in **number** to the left, and keeps up to **bits**
bits in the result. When bits overflow due to the shift, they are discarded.

- **number** (number): the number to shift
- **shift** (number): number of bits to shift (0 to 32)
- **bits** (number): number of bits to keep in the result (0 to 32)
- returns **result** (number\|null): the resulting number, with up to **bits**
  significant bits

The input value must be a number between 0 and 232 - 1 (including).
The number of bits must be between 0 and 32. The function will return `null` for
any other inputs and produce a warning.

```aql
BIT_SHIFT_LEFT(0, 1, 8) // 0
BIT_SHIFT_LEFT(7, 1, 16) // 14
BIT_SHIFT_LEFT(2, 10, 16) // 2048
BIT_SHIFT_LEFT(878836, 16, 32) // 1760821248
```

BIT_SHIFT_RIGHT()
-----------------

`BIT_SHIFT_RIGHT(number, shift, bits) → result`

Bitwise-shifts the bits in **number** to the right, and keeps up to **bits**
bits in the result. When bits overflow due to the shift, they are discarded.

- **number** (number): the number to shift
- **shift** (number): number of bits to shift (0 to 32)
- **bits** (number): number of bits to keep in the result (0 to 32)
- returns **result** (number\|null): the resulting number, with up to **bits**
  significant bits

The input value must be a number between 0 and 232 - 1 (including).
The number of bits must be between 0 and 32. The function will return `null` for
any other inputs and produce a warning.

```aql
BIT_SHIFT_RIGHT(0, 1, 8) // 0
BIT_SHIFT_RIGHT(33, 1, 16) // 16
BIT_SHIFT_RIGHT(65536, 13, 16) // 8
BIT_SHIFT_RIGHT(878836, 4, 32) // 54927
```

BIT_TEST()
----------

`BIT_TEST(number, index) → result`

Tests if the at position *index* is set in **number**.

- **number** (number): the number to test
- **index** (number): index of the bit to test (0 to 31)
- returns **result** (boolean\|null): whether or not the bit was set

The input value must be a number between 0 and 232 - 1 (including).
The **index** must be between 0 and 31. The function will return `null` for any
other inputs and produce a warning.

```aql
BIT_TEST(0, 3) // false
BIT_TEST(255, 0) // true
BIT_TEST(7, 2) // true
BIT_TEST(255, 8) // false
```

BIT_TO_STRING()
---------------

`BIT_TO_STRING(number) → bitstring`

Converts a numeric input value into a bitstring, consisting of `0` and `1`.

To convert a bitstring into a number, see [BIT_FROM_STRING()](#bit_from_string).

- **number** (number): the number to stringify
- returns **bitstring** (string\|null): bitstring generated from the input value

The input value must be a number between 0 and 232 - 1 (including).
The function will return `null` for any other inputs and produce a warning.

```aql
BIT_TO_STRING(7, 4) // "0111"
BIT_TO_STRING(255, 8) // "11111111"
BIT_TO_STRING(60, 8) // "00011110"
BIT_TO_STRING(1048576, 32) // "00000000000100000000000000000000"
```

BIT_XOR()
---------

`BIT_XOR(numbersArray) → result`

Exclusive-or-combines the numeric values in *numbersArray* into a single
numeric result value.

- **numbersArray** (array): array with numeric input values
- returns **result** (number\|null): xor-combined result

The function expects an array with numeric values as its input. The values in
the array must be numbers, which must not be negative. The maximum supported
input number value is 232 - 1. Input number values outside the
allowed range will make the function return `null` and produce a warning.
Any `null` values in the input array are ignored.

---

`BIT_XOR(value1, value2) → result`

If two numbers are passed as individual function parameters to `BIT_XOR()`, it
will return the bitwise exclusive or value of its two operands. Only numbers in
the range 0 to 232 - 1 are allowed as input values.

- **value1** (number): first operand
- **value2** (number): second operand
- returns **result** (number\|null): xor-combined result

```aql
BIT_XOR([1, 4, 8, 16]) // 29
BIT_XOR([3, 7, 63]) // 59
BIT_XOR([255, 127, null, 63]) // 191
BIT_XOR(255, 257) // 510
BIT_XOR("foo") // null
```


text:
<?php

/*
 * Specify Namespace
 */
namespace Console;

/**
 * Properties Test
 *
 * @category   Console
 * @package    BURP
 * @author     Matthew Sirocki <mattsirocki@gmail.com>
 * @copyright  2012, Matthew Sirocki
 * @license    MIT License (http://www.opensource.org/licenses/mit-license.html)
 * @version    Release ${project.version}
 * @since      Class available since Initial Release.
 */
class PropertiesTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Properties Instance
     *
     * @var \Console\BURP\Properties
     */
    public $properties;

    /**
     * @covers \Console\BURP\Properties::__construct
     * @group \Console
     * @group \Console\BURP
     * @group \Console\BURP\Properties
     *
     * @since Test available since Initial Release.
     */
    public function testConstructor()
    {
        $this->properties = new \Console\BURP\Properties();
        $this->assertTrue($this->properties instanceof \Console\BURP\Properties);
    }

    /**
     * @covers \Console\BURP\Properties::get
     * @depends testConstructor
     * @group \Console
     * @group \Console\BURP
     * @group \Console\BURP\Properties
     *
     * @since Test available since Initial Release.
     */
    public function testPropertyGetKeyNotString()
    {
        try
        {
            $this->properties->get(true);
        }
        catch (\Console\BURP\Exception $e)
        {
            $this->assertEquals('PropertyKeyNotString', $e->getKey());
        }
    }

    /**
     * @covers \Console\BURP\Properties::set
     * @depends testConstructor
     * @group \Console
     * @group \Console\BURP
     * @group \Console\BURP\Properties
     *
     * @since Test available since Initial Release.
     */
    public function testPropertySetKeyNotSet()
    {
        try
        {
            $this->properties->set(true, 'string');
        }
        catch (\Console\BURP\Exception $e)
        {
            $this->assertEquals('PropertyKeyNotString', $e->getKey());
        }
    }

    /**
     * @covers \Console\BURP\Properties::set
     * @depends testConstructor
     * @group \Console
     * @group \Console\BURP
     * @group \Console\BURP\Properties
     *
     * @since Test available since Initial Release.
     */
    public function testPropertySetValueNotString()
    {
        try
        {
            $this->properties->get('string', true);
        }
        catch (\Console\BURP\Exception $e)
        {
            $this->assertEquals('PropertyKeyNotString', $e->getKey());
        }
    }

    /**
     * @covers \Console\BURP\Properties::set
     * @depends testConstructor
     * @group \Console
     * @group \Console\BURP
     * @group \Console\BURP\Properties
     *
     * @since Test available since Initial Release.
     */
    public function testPropertySet()
    {
        $this->properties->set('user.name', 'Matthew Sirocki');
        $this->properties->set('user.last', 'Sirocki');
    }

    /**
     * @covers \Console\BURP\Properties::get
     * @depends testConstructor
     * @group \Console
     * @group \Console\BURP
     * @group \Console\BURP\Properties
     *
     * @since Test available since Initial Release.
     */
    public function testPropertyGet()
    {
        $this->assertEquals('Matthew Sirocki', $this->properties->get('user.name'));
        $this->assertEquals('Sirocki', $this->properties->get('user.last'));
    }
}

?>

redpajama_set_name: RedPajamaGithub


text:
package gitbucket.core.controller

import gitbucket.core.settings.html
import gitbucket.core.model.WebHook
import gitbucket.core.service.{RepositoryService, AccountService, WebHookService}
import gitbucket.core.service.WebHookService._
import gitbucket.core.util._
import gitbucket.core.util.JGitUtil._
import gitbucket.core.util.ControlUtil._
import gitbucket.core.util.Implicits._
import gitbucket.core.util.Directory._
import jp.sf.amateras.scalatra.forms._
import org.apache.commons.io.FileUtils
import org.scalatra.i18n.Messages
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Constants
import scala.util.{Success, Failure}
import org.eclipse.jgit.lib.ObjectId

class RepositorySettingsController extends RepositorySettingsControllerBase
  with RepositoryService with AccountService with WebHookService
  with OwnerAuthenticator with UsersAuthenticator

trait RepositorySettingsControllerBase extends ControllerBase {
  self: RepositoryService with AccountService with WebHookService
    with OwnerAuthenticator with UsersAuthenticator =>

  // for repository options
  case class OptionsForm(repositoryName: String, description: Option[String], defaultBranch: String, isPrivate: Boolean)

  val optionsForm = mapping(
    "repositoryName" -> trim(label("Repository Name", text(required, maxlength(40), identifier, renameRepositoryName))),
    "description"    -> trim(label("Description"    , optional(text()))),
    "defaultBranch"  -> trim(label("Default Branch" , text(required, maxlength(100)))),
    "isPrivate"      -> trim(label("Repository Type", boolean()))
  )(OptionsForm.apply)

  // for collaborator addition
  case class CollaboratorForm(userName: String)

  val collaboratorForm = mapping(
    "userName" -> trim(label("Username", text(required, collaborator)))
  )(CollaboratorForm.apply)

  // for web hook url addition
  case class WebHookForm(url: String, events: Set[WebHook.Event])

  def webHookForm(update:Boolean) = mapping(
    "url"    -> trim(label("url", text(required, webHook(update)))),
    "events" -> webhookEvents
  )(WebHookForm.apply)

  // for transfer ownership
  case class TransferOwnerShipForm(newOwner: String)

  val transferForm = mapping(
    "newOwner" -> trim(label("New owner", text(required, transferUser)))
  )(TransferOwnerShipForm.apply)

  /**
   * Redirect to the Options page.
   */
  get("/:owner/:repository/settings")(ownerOnly { repository =>
    redirect(s"/${repository.owner}/${repository.name}/settings/options")
  })

  /**
   * Display the Options page.
   */
  get("/:owner/:repository/settings/options")(ownerOnly {
    html.options(_, flash.get("info"))
  })

  /**
   * Save the repository options.
   */
  post("/:owner/:repository/settings/options", optionsForm)(ownerOnly { (form, repository) =>
    val defaultBranch = if(repository.branchList.isEmpty) "master" else form.defaultBranch
    saveRepositoryOptions(
      repository.owner,
      repository.name,
      form.description,
      defaultBranch,
      repository.repository.parentUserName.map { _ =>
        repository.repository.isPrivate
      } getOrElse form.isPrivate
    )
    // Change repository name
    if(repository.name != form.repositoryName){
      // Update database
      renameRepository(repository.owner, repository.name, repository.owner, form.repositoryName)
      // Move git repository
      defining(getRepositoryDir(repository.owner, repository.name)){ dir =>
        FileUtils.moveDirectory(dir, getRepositoryDir(repository.owner, form.repositoryName))
      }
      // Move wiki repository
      defining(getWikiRepositoryDir(repository.owner, repository.name)){ dir =>
        FileUtils.moveDirectory(dir, getWikiRepositoryDir(repository.owner, form.repositoryName))
      }
    }
    // Change repository HEAD
    using(Git.open(getRepositoryDir(repository.owner, form.repositoryName))) { git =>
      git.getRepository.updateRef(Constants.HEAD, true).link(Constants.R_HEADS + defaultBranch)
    }
    flash += "info" -> "Repository settings has been updated."
    redirect(s"/${repository.owner}/${form.repositoryName}/settings/options")
  })

  /**
   * Display the Collaborators page.
   */
  get("/:owner/:repository/settings/collaborators")(ownerOnly { repository =>
    html.collaborators(
      getCollaborators(repository.owner, repository.name),
      getAccountByUserName(repository.owner).get.isGroupAccount,
      repository)
  })

  /**
   * Add the collaborator.
   */
  post("/:owner/:repository/settings/collaborators/add", collaboratorForm)(ownerOnly { (form, repository) =>
    if(!getAccountByUserName(repository.owner).get.isGroupAccount){
      addCollaborator(repository.owner, repository.name, form.userName)
    }
    redirect(s"/${repository.owner}/${repository.name}/settings/collaborators")
  })

  /**
   * Add the collaborator.
   */
  get("/:owner/:repository/settings/collaborators/remove")(ownerOnly { repository =>
    if(!getAccountByUserName(repository.owner).get.isGroupAccount){
      removeCollaborator(repository.owner, repository.name, params("name"))
    }
    redirect(s"/${repository.owner}/${repository.name}/settings/collaborators")
  })

  /**
   * Display the web hook page.
   */
  get("/:owner/:repository/settings/hooks")(ownerOnly { repository =>
    html.hooks(getWebHooks(repository.owner, repository.name), repository, flash.get("info"))
  })

  /**
   * Display the web hook edit page.
   */
  get("/:owner/:repository/settings/hooks/new")(ownerOnly { repository =>
    val webhook = WebHook(repository.owner, repository.name, "")
    html.edithooks(webhook, Set(WebHook.Push), repository, flash.get("info"), true)
  })

  /**
   * Add the web hook URL.
   */
  post("/:owner/:repository/settings/hooks/new", webHookForm(false))(ownerOnly { (form, repository) =>
    addWebHook(repository.owner, repository.name, form.url, form.events)
    flash += "info" -> s"Webhook ${form.url} created"
    redirect(s"/${repository.owner}/${repository.name}/settings/hooks")
  })

  /**
   * Delete the web hook URL.
   */
  get("/:owner/:repository/settings/hooks/delete")(ownerOnly { repository =>
    deleteWebHook(repository.owner, repository.name, params("url"))
    flash += "info" -> s"Webhook ${params("url")} deleted"
    redirect(s"/${repository.owner}/${repository.name}/settings/hooks")
  })

  /**
   * Send the test request to registered web hook URLs.
   */
  ajaxPost("/:owner/:repository/settings/hooks/test")(ownerOnly { repository =>
    using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
      import scala.collection.JavaConverters._
      import scala.concurrent.duration._
      import scala.concurrent._
      import scala.util.control.NonFatal
      import org.apache.http.util.EntityUtils
      import scala.concurrent.ExecutionContext.Implicits.global

      val url = params("url")
      val dummyPayload = {
        val ownerAccount = getAccountByUserName(repository.owner).get
        val commits = if(repository.commitCount == 0) List.empty else git.log
          .add(git.getRepository.resolve(repository.repository.defaultBranch))
          .setMaxCount(4)
          .call.iterator.asScala.map(new CommitInfo(_)).toList
        val pushedCommit = commits.drop(1)
        WebHookPushPayload(git, ownerAccount, "refs/heads/" + repository.repository.defaultBranch, repository, pushedCommit, ownerAccount,
                           oldId = commits.lastOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()),
                           newId = commits.headOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()))
      }
      val dummyWebHookInfo = WebHook(repository.owner, repository.name, url)

      val (webHook, json, reqFuture, resFuture) = callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload).head

      def headers(h: Array[org.apache.http.Header]): Array[Array[String]] = h.map{ h => Array(h.getName, h.getValue) }
      val toErrorMap:PartialFunction[Throwable, Map[String,String]] = {
        case e:java.net.UnknownHostException => Map("error"-> ("Unknown host "+ e.getMessage))
        case e:java.lang.IllegalArgumentException => Map("error"-> ("invalid url"))
        case e:org.apache.http.client.ClientProtocolException => Map("error"-> ("invalid url"))
        case NonFatal(e) => Map("error"-> (e.getClass + " "+ e.getMessage))
      }
      contentType = formats("json")
      var result = Map(
        "url" -> url,
        "request"  -> Await.result(reqFuture.map(req => Map(
          "headers"   -> headers(req.getAllHeaders),
          "payload"   -> json
        )).recover(toErrorMap), 20 seconds),
        "responce" -> Await.result(resFuture.map(res => Map(
            "status"  -> res.getStatusLine(),
            "body"    -> EntityUtils.toString(res.getEntity()),
            "headers" -> headers(res.getAllHeaders())
        )).recover(toErrorMap), 20 seconds))
      org.json4s.jackson.Serialization.write(result)
    }
  })

  /**
   * Display the web hook edit page.
   */
  get("/:owner/:repository/settings/hooks/edit/:url")(ownerOnly { repository =>
    getWebHook(repository.owner, repository.name, params("url")).map{ case (webhook, events) =>
      html.edithooks(webhook, events, repository, flash.get("info"), false)
    } getOrElse NotFound
  })

  /**
   * Update web hook settings.
   */
  post("/:owner/:repository/settings/hooks/edit/:url", webHookForm(true))(ownerOnly { (form, repository) =>
    updateWebHook(repository.owner, repository.name, form.url, form.events)
    flash += "info" -> s"webhook ${form.url} updated"
    redirect(s"/${repository.owner}/${repository.name}/settings/hooks")
  })

  /**
   * Display the danger zone.
   */
  get("/:owner/:repository/settings/danger")(ownerOnly {
    html.danger(_)
  })

  /**
   * Transfer repository ownership.
   */
  post("/:owner/:repository/settings/transfer", transferForm)(ownerOnly { (form, repository) =>
    // Change repository owner
    if(repository.owner != form.newOwner){
      LockUtil.lock(s"${repository.owner}/${repository.name}"){
        // Update database
        renameRepository(repository.owner, repository.name, form.newOwner, repository.name)
        // Move git repository
        defining(getRepositoryDir(repository.owner, repository.name)){ dir =>
          FileUtils.moveDirectory(dir, getRepositoryDir(form.newOwner, repository.name))
        }
        // Move wiki repository
        defining(getWikiRepositoryDir(repository.owner, repository.name)){ dir =>
          FileUtils.moveDirectory(dir, getWikiRepositoryDir(form.newOwner, repository.name))
        }
      }
    }
    redirect(s"/${form.newOwner}/${repository.name}")
  })

  /**
   * Delete the repository.
   */
  post("/:owner/:repository/settings/delete")(ownerOnly { repository =>
    LockUtil.lock(s"${repository.owner}/${repository.name}"){
      deleteRepository(repository.owner, repository.name)

      FileUtils.deleteDirectory(getRepositoryDir(repository.owner, repository.name))
      FileUtils.deleteDirectory(getWikiRepositoryDir(repository.owner, repository.name))
      FileUtils.deleteDirectory(getTemporaryDir(repository.owner, repository.name))
    }
    redirect(s"/${repository.owner}")
  })

  /**
   * Provides duplication check for web hook url.
   */
  private def webHook(needExists: Boolean): Constraint = new Constraint(){
    override def validate(name: String, value: String, messages: Messages): Option[String] =
      if(getWebHook(params("owner"), params("repository"), value).isDefined != needExists){
        Some(if(needExists){
          "URL had not been registered yet."
        } else {
          "URL had been registered already."
        })
      } else {
        None
      }
  }

  private def webhookEvents = new ValueType[Set[WebHook.Event]]{
    def convert(name: String, params: Map[String, String], messages: Messages): Set[WebHook.Event] = {
      WebHook.Event.values.flatMap { t =>
        params.get(name + "." + t.name).map(_ => t)
      }.toSet
    }
    def validate(name: String, params: Map[String, String], messages: Messages): Seq[(String, String)] = if(convert(name,params,messages).isEmpty){
      Seq(name -> messages("error.required").format(name))
    } else {
      Nil
    }
  }

  /**
   * Provides Constraint to validate the collaborator name.
   */
  private def collaborator: Constraint = new Constraint(){
    override def validate(name: String, value: String, messages: Messages): Option[String] =
      getAccountByUserName(value) match {
        case None => Some("User does not exist.")
        case Some(x) if(x.isGroupAccount)
                  => Some("User does not exist.")
        case Some(x) if(x.userName == params("owner") || getCollaborators(params("owner"), params("repository")).contains(x.userName))
                  => Some("User can access this repository already.")
        case _    => None
      }
  }

  /**
   * Duplicate check for the rename repository name.
   */
  private def renameRepositoryName: Constraint = new Constraint(){
    override def validate(name: String, value: String, params: Map[String, String], messages: Messages): Option[String] =
      params.get("repository").filter(_ != value).flatMap { _ =>
        params.get("owner").flatMap { userName =>
          getRepositoryNamesOfUser(userName).find(_ == value).map(_ => "Repository already exists.")
        }
      }
  }

  /**
   * Provides Constraint to validate the repository transfer user.
   */
  private def transferUser: Constraint = new Constraint(){
    override def validate(name: String, value: String, messages: Messages): Option[String] =
      getAccountByUserName(value) match {
        case None    => Some("User does not exist.")
        case Some(x) => if(x.userName == params("owner")){
          Some("This is current repository owner.")
        } else {
          params.get("repository").flatMap { repositoryName =>
            getRepositoryNamesOfUser(x.userName).find(_ == repositoryName).map{ _ => "User already has same repository." }
          }
        }
      }
  }
}


text:
#ifndef USERFAVORITESREQUEST_H
#define USERFAVORITESREQUEST_H

#include "config.h"
#include "UserFavorites.h"
#include "Request.h"
#include "StringTable.h"

class UserFavoritesRequestPacket;
class UserFavoritesReplyPacket;

/**
 *  UserFavoritesRequest, used to sync/retrieve/add/delete favorites for a
 *  certain user.
 *
 */
class UserFavoritesRequest : public RequestWithStatus
{
   public:

      /**
       *    Create a UserFavoritesRequest
       *    @param reqID      The unique request ID for this request.
       *    @param UIN        The user id associated with the favorites
       */
      UserFavoritesRequest(uint16 reqID, uint32 UIN);

      /**
       *    Delete this request, including allocated packet.
       */
      virtual ~UserFavoritesRequest();

      /**
       *   Add favorite ID to sync list
       *   @param favID The ID of the favorite
       */
      void addFavSync(const uint32 favID);

      /**
       *   Add favorite ID to delete list
       *   @param favID The ID of the favorite
       */
      void addFavDelete(const uint32 favID);

      /**
       *   Add new favorite to add list
       *   @param lat         The latitude
       *   @param lon         The longitude
       *   @param name        String containing the name
       *   @param shortName   String containing the short name
       *   @param description String containing the description
       *   @param category    String containing the category
       *   @param mapIconName String containing map icon name
       *   @param infoStr     The id-key-values in a string.
       */
      void addFavNew( const int32 lat, const int32 lon,
                      const char* name, const char* shortName,
                      const char* description, const char* category,
                      const char* mapIconName,
                      const char* infoStr );

      /**
       * Add new favorite to add list
       *
       * @param userFav The favorite to add, is now owned by this class.
       */
      void addFavNew( UserFavorite* userFav );

      /**
       *    Get the status of the request, returns stringcodes as defined
       *    in <tt>class StringTable</tt>. StringTable::OK indicates a
       *    successfull transaction. StringTable::UNKNOWN will be returned
       *    before the request placket has been sent/reply packet has been
       *    received.
       *    @return status code
       */
      StringTable::stringCode getStatus() const;

      /**
       *   Reset the getAddFav() and getDelFav() functions.
       */
      void reset();

      /**
       *   Get the next favorite to add.
       *   @return Pointer to the next favorite, NULL if no more
       */
      const UserFavorite* getAddFav();

      /**
       *   Get the next favorite to delete.
       *   @return Pointer to the next favorite, NULL if no more
       */
      const UserFavorite* getDelFav();

      /**
       *   If called the request wont perform any syncing, only add/del
       *   for the user.
       */
      void setNoSync();

      /**
       *    Return a packet container with the next packet that should
       *    be processed by the modules.
       *    @return  A packet container with the next packet that should
       *             be processed by the modules.
       */
      PacketContainer* getNextPacket();

      /**
       *    Returns NULL in this request, all packet handling is internal.
       *    Use getxxxx() to find out the status of the request.
       *    @return NULL pointer
       */
      PacketContainer* getAnswer();

      /**
       *    Take care of one packet that is processed by the modules.
       *    @param pack A packet container with a packet that have
       *                been processed by the modules.
       */
      void processPacket(PacketContainer* pack);

   private:

      /// add request list
      UserFavoritesList m_addReqList;

      /// delete request list
      UserFavoritesList m_deleteReqList;

      /// sync request list
      UserFavoritesList m_syncReqList;

      /// add reply list
      UserFavoritesList m_addReplyList;

      /// delete reply list
      UserFavoritesList m_deleteReplyList;

      /// iterator for m_addReplyList
      UserFavoritesList::iterator m_addIter;

      /// iterator for m_deleteReplyList
      UserFavoritesList::iterator m_deleteIter;

      /// our single request packet
      UserFavoritesRequestPacket* m_reqPacket;

      /// our single reply packet
      UserFavoritesReplyPacket* m_replyPacket;

      /// our single reply packet container to hold on to and delete later
      PacketContainer* m_replyPacketContainer;

      /// the internal states
      enum state_t {
          INIT,
          WAITING_FOR_REPLY,
          OK,
          ERROR
      };

      /// internal state variable
      state_t m_state;
};

#endif // USERFAVORITESREQUEST_H


text:
// https://github.com/barberboy/dom-elements
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.domElements=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
// as it is a circular dependency, we need to keep `module.exports` on top.
module.exports = Elements;

var pushUniq = _dereq_('../utils/pushuniq');
var elementsPrototype = Elements.prototype = [];
var methods = _dereq_('../methods');

function Elements() {}

// Elements.queryAll(selector);
elementsPrototype.queryAll = function (selector) {
  var pusher = pushUniq();
  return this.reduce(function(results, element){
    return pusher(methods.queryAll.call(element, selector));
  }, null);
};

// Elements.query(selector);
elementsPrototype.query = function (selector) {
  return elementsPrototype.queryAll.call(this, selector)[0] || null;
};

},{"../methods":5,"../utils/pushuniq":11}],2:[function(_dereq_,module,exports){
var methods = _dereq_('./methods');
var isNative = _dereq_('./utils/is-native');
var array = [];

if (
  typeof Document === 'undefined' ||
  !('map' in array) ||
  !('reduce' in array) ||
  !('querySelectorAll' in document)
) {
  throw new TypeError('Missing browser features to initiantiate dom-elements');
}

if('Element' in window) {
  if(!isNative(Element.prototype, 'query')) {
    Element.prototype.query = methods.query;
  }
  if(!isNative(Element.prototype, 'queryAll')) {
    Element.prototype.queryAll = methods.queryAll;
  }
}

['Document', 'DocumentFragment'].forEach(function (ParentNode) {
  var prototype;
  // Don't throw errors if these globals don't exist — just move on.
  if (!(ParentNode in window)) {
    return;
  }
  prototype = window[ParentNode].prototype;
  if (!isNative(prototype, 'query')) {
    prototype.query = methods.queryWrapper;
  }
  if (!isNative(prototype, 'queryAll')) {
    prototype.queryAll = methods.queryAllWrapper;
  }
});

},{"./methods":5,"./utils/is-native":10}],3:[function(_dereq_,module,exports){
var attributeName = _dereq_('./attribute-name');

module.exports = function (attributeValue) {
  return function (item){
    return '[' + attributeName + '="' + attributeValue + '"] ' + item;
  };
};

},{"./attribute-name":4}],4:[function(_dereq_,module,exports){
module.exports = 'data-dom-elements-id-' + _dereq_('../utils/expando');

},{"../utils/expando":9}],5:[function(_dereq_,module,exports){
var scope = _dereq_('../scope');
var supportsScoped = _dereq_('../scope/support');
var methods = module.exports = {};
var Elements = _dereq_('../elements');
var toArray = _dereq_('../utils/to-array');
var attributeName = _dereq_('./attribute-name');
var scopeSelector = _dereq_('./scope-selector');
var absolutizeSelector = _dereq_('./absolutize-selector');
var unique = -1;

methods.query = function(selector){
  return methods.queryAll.call(this, selector)[0] || null;
};

methods.queryAll = function(sourceSelector){
  var element = this;
  var elements;
  var selector;
  var result;
  if(!supportsScoped) {
    element.setAttribute(attributeName, ++unique);
  }
  selector = supportsScoped ?
    scope(sourceSelector, scopeSelector) :
    scope(sourceSelector, absolutizeSelector(unique));
  elements = element.querySelectorAll(selector);
  if (!supportsScoped) {
    element.removeAttribute(attributeName);
  }
  result = new Elements();
  result.push.apply(result, toArray(elements));
  return result;
};

methods.queryAllWrapper = function(selector){
  var elements = this.querySelectorAll(selector);
  var result = new Elements();
  result.push.apply(result, toArray(elements));
  return result;
};

methods.queryWrapper = function(selector){
  return this.querySelector(selector);
};

},{"../elements":1,"../scope":7,"../scope/support":8,"../utils/to-array":13,"./absolutize-selector":3,"./attribute-name":4,"./scope-selector":6}],6:[function(_dereq_,module,exports){
module.exports = function (item) {
  return ':scoped ' + item;
};

},{}],7:[function(_dereq_,module,exports){
var separateSelector = _dereq_('../utils/separate-selector');

module.exports = function(selector, method){
  var selectors = separateSelector(selector);
  var scopedSelectors = selectors.map(method);
  return scopedSelectors.join();
};

},{"../utils/separate-selector":12}],8:[function(_dereq_,module,exports){
try {
  document.createElement('i').querySelector(':scoped *');
  module.exports = true;
} catch (e) {
  module.exports = false;
}

},{}],9:[function(_dereq_,module,exports){
module.exports = String(Math.random()).replace(/\D/g, '');

},{}],10:[function(_dereq_,module,exports){
var nativeToString = Function.prototype.toString;
var nativeQuerySelector = nativeToString.call(document.querySelector);
var nameRE = /\bquerySelector\b/g;

module.exports = function(context, name){
  if (!context[name]) {
    return false;
  }
  return (
    nativeToString.call(context[name]) ===
    nativeQuerySelector.replace(nameRE, name)
  );
};

},{}],11:[function(_dereq_,module,exports){
var Elements = _dereq_('../elements');
var expando = _dereq_('./expando');
var propertyName = 'domElementsId' + expando;
var id = -1;

/**
 * pushUniq
 *
 * returns a function that pushes elements not yet in `target`.
 * as the internal API only uses it before making the array
 * available, we can use a `map` cache to store the elements
 * already in the newly built array, letting us prevent extensive looping.
 */
module.exports = function (original) {
  var target = new Elements();
  var map = {};

  function pusher(source) {
    var index = -1;
    var length = source.length;
    var item;
    while (++index < length) {
      item = source[index];
      if (!item || item.nodeType !== 1) {
        continue;
      }
      if (propertyName in item && map.hasOwnProperty(item[propertyName])) {
        continue;
      }
      item[propertyName] = ++id;
      map[id] = 1;
      target.push(item);
    }
    return target;
  }

  if(arguments.length) {
    pusher(original);
  }

  return pusher;
};

},{"../elements":1,"./expando":9}],12:[function(_dereq_,module,exports){
module.exports = function(selector){
  return selector.split(/\s*,\s*/);
};

},{}],13:[function(_dereq_,module,exports){
module.exports = function(nodeList){
  var index = -1;
  var length = nodeList.length;
  var array = Array(length);
  while (++index < length) {
    array[index] = nodeList[index];
  }
  return array;
};

},{}]},{},[2])
(2)
});


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'description': 'route log events from TCP to websocket for streaming log events on a web page.',
    'author': 'Jonathan Strong',
    'url': 'https://github.com/jonathanstrong/log-viewer',
    'download_url':'https://github.com/jonathanstrong/log-viewer',
    'author_email': 'jonathan.strong@gmail.com',
    'version': '0.1',
    'install_requires': ['tornado'],
    'packages': ['iolog'],
    'scripts': [],
    'name': 'iolog'
}

setup(**config)


text:
module RgGen
  module Builder
    class ComponentEntry
      class << self
        private

        def rggen_class_setter(class_type)
          variable_name = class_type.variablize
          define_method(class_type) do |base_class = nil, options = {}, &body|
            if base_class && !instance_variable_defined?(variable_name)
              klass = define_rggen_class(base_class, options, body)
              instance_variable_set(variable_name, klass)
            end
            instance_variable_get(variable_name)
          end
        end
      end

      rggen_class_setter :component_class
      rggen_class_setter :component_factory
      rggen_class_setter :item_base
      rggen_class_setter :item_factory

      def item_store
        return nil unless item_base && item_factory
        @item_store ||= ItemStore.new(item_base, item_factory)
      end

      def build_factory
        component_factory.new.tap do |f|
          f.target_component  = component_class
          f.item_factories    = item_store.build_factories if item_store
        end
      end

      private

      def define_rggen_class(base_class, options, body)
        if options.key?(:include) || body
          Class.new(base_class) do
            include(*Array(options[:include])) if options.key?(:include)
            class_exec(&body) if body
          end
        else
          base_class
        end
      end
    end
  end
end


text:
import unittest
import guava

class MyController(guava.controller.Controller):

    def index(self):
        pass

class TestController(unittest.TestCase):

    def setUp(self):
        pass

    def test_controller(self):
        c = MyController()

        self.assertTrue(c.set_header != None)
        self.assertTrue(c.write != None)
        self.assertTrue(c.set_status_code != None)
        self.assertTrue(c.redirect != None)
        self.assertTrue(c.before_action != None)
        self.assertTrue(c.after_action != None)
        self.assertTrue(c.set_cookie != None)

        self.assertEqual(c.GET, {})

if __name__ == '__main__':
    unittest.main()


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Execute vlan-create or vlan-delete command.
      # VLANs are used to isolate network traffic at Layer 2.The VLAN identifiers 0 and 4095 are reserved and cannot be used per the IEEE 802.1Q standard. The range of configurable VLAN identifiers is 2 through 4092.
      class Pn_vlan < Base
        # @return [Object, nil] Provide login username if user is not root.
        attribute :pn_cliusername

        # @return [Object, nil] Provide login password if user is not root.
        attribute :pn_clipassword

        # @return [Object, nil] Target switch(es) to run the cli on.
        attribute :pn_cliswitch

        # @return [:present, :absent] State the action to perform. Use 'present' to create vlan and 'absent' to delete vlan.
        attribute :state
        validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}

        # @return [Integer] Specify a VLAN identifier for the VLAN. This is a value between 2 and 4092.
        attribute :pn_vlanid
        validates :pn_vlanid, presence: true, type: Integer

        # @return [:fabric, :local, nil] Specify a scope for the VLAN.,Required for vlan-create.
        attribute :pn_scope
        validates :pn_scope, expression_inclusion: {:in=>[:fabric, :local], :message=>"%{value} needs to be :fabric, :local"}, allow_nil: true

        # @return [Object, nil] Specify a description for the VLAN.
        attribute :pn_description

        # @return [Object, nil] Specify if you want to collect statistics for a VLAN. Statistic collection is enabled by default.
        attribute :pn_stats

        # @return [Object, nil] Specifies the switch network data port number, list of ports, or range of ports. Port numbers must ne in the range of 1 to 64.
        attribute :pn_ports

        # @return [Object, nil] Specifies the ports that should have untagged packets mapped to the VLAN. Untagged packets are packets that do not contain IEEE 802.1Q VLAN tags.
        attribute :pn_untagged_ports
      end
    end
  end
end


text:
BASEDIR="avogadro/"	# root of translatable sources
PROJECT="avogadrolibs"	# project name
PACKAGE="Avogadro"  # user-readable package name
# user-readable version
MAJORVERSION=`grep 'set(AvogadroLibs_VERSION_MAJOR' CMakeLists.txt | cut -f 2 -d '"'`
MINORVERSION=`grep 'set(AvogadroLibs_VERSION_MINOR' CMakeLists.txt | cut -f 2 -d '"'`
PATCHVERSION=`grep 'set(AvogadroLibs_VERSION_PATCH' CMakeLists.txt | cut -f 2 -d '"'`
VERSION="${MAJORVERSION}.${MINORVERSION}.${PATCHVERSION}"
BUGADDR="avogadro-devel@lists.sourceforge.net"	# MSGID-Bugs
WDIR=`pwd`		# working dir
I18NDIR="i18n/"          # i18n dir

echo "Preparing rc files"
cd ${BASEDIR}
# we use simple sorting to make sure the lines do not jump around too much from system to system
find . -name '*.rc' -o -name '*.ui' -o -name '*.kcfg' | grep -v 'test' | grep -v 'example' | sort > ${WDIR}/rcfiles.list
cat ${WDIR}/rcfiles.list | xargs ${WDIR}/scripts/extractrc.sh > ${WDIR}/rc.cpp
# additional string for KAboutData
echo 'i18nc("NAME OF TRANSLATORS","Your names");' >> ${WDIR}/rc.cpp
echo 'i18nc("EMAIL OF TRANSLATORS","Your emails");' >> ${WDIR}/rc.cpp
cd ${WDIR}
echo "Done preparing rc files"

echo "Extracting messages"
cd ${BASEDIR}
# see above on sorting
find . -name '*.cpp' -o -name '*.h' -o -name '*.c' | grep -v 'test' | grep -v "example" | sort > ${WDIR}/infiles.list
echo "rc.cpp" >> ${WDIR}/infiles.list
cd ${WDIR}
xgettext --from-code=UTF-8 -C -T --qt -kde -ci18n -ki18n:1 -ki18nc:1c,2 -ki18np:1,2 -ki18ncp:1c,2,3 -ktr2i18n:1 \
	-kI18N_NOOP:1 -kI18N_NOOP2:1c,2 -kaliasLocale -kki18n:1 -kki18nc:1c,2 -kki18np:1,2 -kki18ncp:1c,2,3 \
  -ktrUtf8:1,2c -ktr:1,1t -ktr:1,2c,2t -ktr:1,1,2c,3t -ktrUtf8:1 \
  --package-name=${PACKAGE} --package-version=${VERSION} \
	--msgid-bugs-address="${BUGADDR}" --foreign-user --copyright-holder="The Avogadro Project" \
	--files-from=infiles.list -D ${BASEDIR} -D ${WDIR} -o ${PROJECT}.pot || { echo "error while calling xgettext. aborting."; exit 1; }
echo "Done extracting messages"

# Replace some boilerplate strings
sed -e "s/SOME DESCRIPTIVE TITLE/Translations for the Avogadro molecular builder/" <${PROJECT}.pot >${PROJECT}.new
mv ${PROJECT}.new ${PROJECT}.pot
year=`date "+%Y"`
sed -e "s/Copyright (C) YEAR/Copyright (C) 2006-$year/" <${PROJECT}.pot >${PROJECT}.new
mv ${PROJECT}.new ${PROJECT}.pot
sed -e 's/as the PACKAGE package/as the Avogadro package/' <${PROJECT}.pot >${PROJECT}.new
mv ${PROJECT}.new ${PROJECT}.pot
sed -e 's/^#. i18n: .\//#: /' <${PROJECT}.pot >${PROJECT}.new
mv ${PROJECT}.new ${PROJECT}.pot
sed -e '/^#: rc.cpp/ d' <${PROJECT}.pot >${PROJECT}.new
mv ${PROJECT}.new ${PROJECT}.pot
sed -e 's/rc\.cpp//' <${PROJECT}.pot >${PROJECT}.new
mv ${PROJECT}.new ${PROJECT}.pot

mv ${PROJECT}.pot ${I18NDIR}

#cd ${I18NDIR}
#echo "Merging translations"
#catalogs=`find . -name '*.po'`
#for cat in $catalogs; do
#  # remove any \r escapes
#  sed -e 's/\\r//' <$cat >$cat.new
#  mv $cat.new $cat
#  echo $cat
#  msgmerge -o $cat.new $cat ${PROJECT}.pot
#  mv $cat.new $cat
#  msgmerge -U $cat ${PROJECT}.pot
#done
#echo "Done merging translations"

echo "Cleaning up"
cd ${WDIR}
rm rcfiles.list
rm infiles.list
rm rc.cpp
echo "Done"


text:
package telegraf

import "time"

// Accumulator is an interface for "accumulating" metrics from plugin(s).
// The metrics are sent down a channel shared between all plugins.
type Accumulator interface {
	// AddFields adds a metric to the accumulator with the given measurement
	// name, fields, and tags (and timestamp). If a timestamp is not provided,
	// then the accumulator sets it to "now".
	// Create a point with a value, decorating it with tags
	// NOTE: tags is expected to be owned by the caller, don't mutate
	// it after passing to Add.
	AddFields(measurement string,
		fields map[string]interface{},
		tags map[string]string,
		t ...time.Time)

	// AddGauge is the same as AddFields, but will add the metric as a "Gauge" type
	AddGauge(measurement string,
		fields map[string]interface{},
		tags map[string]string,
		t ...time.Time)

	// AddCounter is the same as AddFields, but will add the metric as a "Counter" type
	AddCounter(measurement string,
		fields map[string]interface{},
		tags map[string]string,
		t ...time.Time)

	// AddSummary is the same as AddFields, but will add the metric as a "Summary" type
	AddSummary(measurement string,
		fields map[string]interface{},
		tags map[string]string,
		t ...time.Time)

	// AddHistogram is the same as AddFields, but will add the metric as a "Histogram" type
	AddHistogram(measurement string,
		fields map[string]interface{},
		tags map[string]string,
		t ...time.Time)

	SetPrecision(precision, interval time.Duration)

	AddError(err error)
}


text:
require 'spec_helper'

describe Spree::Admin::WarehousesController do

  before do
    controller.stub :current_user => Factory(:admin_user)
  end

  describe "GET :index	" do
    it "should be successful" do
      get :index, :use_route => :spree
      response.should be_success
    end
  end

   it "should create warehouse" do
    spree_get :new
    response.should render_template("admin/warehouses/new")
   end

  context "destroying a warehouse" do
    let(:warehouse) do
      warehouse = create(:warehouse)
    end

    it "marks deleted the warehouse" do
      spree_delete :destroy, :id => warehouse
      warehouse.reload.deleted_at.should_not be_nil
    end
  end

end


text:
/**
 * WordPress Administration Navigation Menu
 * Interface JS functions
 *
 * @version 2.0.0
 *
 * @package WordPress
 * @subpackage Administration
 */

var wpNavMenu;

(function($) {

	var api = wpNavMenu = {

		options : {
			menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
			globalMaxDepth : 11
		},

		menuList : undefined,	// Set in init.
		targetList : undefined, // Set in init.
		menusChanged : false,
		isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
		negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,

		// Functions that run on init.
		init : function() {
			api.menuList = $('#menu-to-edit');
			api.targetList = api.menuList;

			this.jQueryExtensions();

			this.attachMenuEditListeners();

			this.setupInputWithDefaultTitle();
			this.attachQuickSearchListeners();
			this.attachThemeLocationsListeners();

			this.attachTabsPanelListeners();

			this.attachUnsavedChangesListener();

			if( api.menuList.length ) // If no menu, we're in the + tab.
				this.initSortables();

			this.initToggles();

			this.initTabManager();
		},

		jQueryExtensions : function() {
			// jQuery extensions
			$.fn.extend({
				menuItemDepth : function() {
					var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
					return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
				},
				updateDepthClass : function(current, prev) {
					return this.each(function(){
						var t = $(this);
						prev = prev || t.menuItemDepth();
						$(this).removeClass('menu-item-depth-'+ prev )
							.addClass('menu-item-depth-'+ current );
					});
				},
				shiftDepthClass : function(change) {
					return this.each(function(){
						var t = $(this),
							depth = t.menuItemDepth();
						$(this).removeClass('menu-item-depth-'+ depth )
							.addClass('menu-item-depth-'+ (depth + change) );
					});
				},
				childMenuItems : function() {
					var result = $();
					this.each(function(){
						var t = $(this), depth = t.menuItemDepth(), next = t.next();
						while( next.length && next.menuItemDepth() > depth ) {
							result = result.add( next );
							next = next.next();
						}
					});
					return result;
				},
				updateParentMenuItemDBId : function() {
					return this.each(function(){
						var item = $(this),
							input = item.find('.menu-item-data-parent-id'),
							depth = item.menuItemDepth(),
							parent = item.prev();

						if( depth == 0 ) { // Item is on the top level, has no parent
							input.val(0);
						} else { // Find the parent item, and retrieve its object id.
							while( ! parent[0] || ! parent[0].className || -1 == parent[0].className.indexOf('menu-item') || ( parent.menuItemDepth() != depth - 1 ) )
								parent = parent.prev();
							input.val( parent.find('.menu-item-data-db-id').val() );
						}
					});
				},
				hideAdvancedMenuItemFields : function() {
					return this.each(function(){
						var that = $(this);
						$('.hide-column-tog').not(':checked').each(function(){
							that.find('.field-' + $(this).val() ).addClass('hidden-field');
						});
					});
				},
				/**
				 * Adds selected menu items to the menu.
				 *
				 * @param jQuery metabox The metabox jQuery object.
				 */
				addSelectedToMenu : function(processMethod) {
					if ( 0 == $('#menu-to-edit').length ) {
						return false;
					}

					return this.each(function() {
						var t = $(this), menuItems = {},
							checkboxes = t.find('.tabs-panel-active .categorychecklist li input:checked'),
							re = new RegExp('menu-item\\[(\[^\\]\]*)');

						processMethod = processMethod || api.addMenuItemToBottom;

						// If no items are checked, bail.
						if ( !checkboxes.length )
							return false;

						// Show the ajax spinner
						t.find('img.waiting').show();

						// Retrieve menu item data
						$(checkboxes).each(function(){
							var t = $(this),
								listItemDBIDMatch = re.exec( t.attr('name') ),
								listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
							if ( this.className && -1 != this.className.indexOf('add-to-top') )
								processMethod = api.addMenuItemToTop;
							menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
						});

						// Add the items
						api.addItemToMenu(menuItems, processMethod, function(){
							// Deselect the items and hide the ajax spinner
							checkboxes.removeAttr('checked');
							t.find('img.waiting').hide();
						});
					});
				},
				getItemData : function( itemType, id ) {
					itemType = itemType || 'menu-item';

					var itemData = {}, i,
					fields = [
						'menu-item-db-id',
						'menu-item-object-id',
						'menu-item-object',
						'menu-item-parent-id',
						'menu-item-position',
						'menu-item-type',
						'menu-item-title',
						'menu-item-url',
						'menu-item-description',
						'menu-item-attr-title',
						'menu-item-target',
						'menu-item-classes',
						'menu-item-xfn'
					];

					if( !id && itemType == 'menu-item' ) {
						id = this.find('.menu-item-data-db-id').val();
					}

					if( !id ) return itemData;

					this.find('input').each(function() {
						var field;
						i = fields.length;
						while ( i-- ) {
							if( itemType == 'menu-item' )
								field = fields[i] + '[' + id + ']';
							else if( itemType == 'add-menu-item' )
								field = 'menu-item[' + id + '][' + fields[i] + ']';

							if (
								this.name &&
								field == this.name
							) {
								itemData[fields[i]] = this.value;
							}
						}
					});

					return itemData;
				},
				setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
					itemType = itemType || 'menu-item';

					if( !id && itemType == 'menu-item' ) {
						id = $('.menu-item-data-db-id', this).val();
					}

					if( !id ) return this;

					this.find('input').each(function() {
						var t = $(this), field;
						$.each( itemData, function( attr, val ) {
							if( itemType == 'menu-item' )
								field = attr + '[' + id + ']';
							else if( itemType == 'add-menu-item' )
								field = 'menu-item[' + id + '][' + attr + ']';

							if ( field == t.attr('name') ) {
								t.val( val );
							}
						});
					});
					return this;
				}
			});
		},

		initToggles : function() {
			// init postboxes
			postboxes.add_postbox_toggles('nav-menus');

			// adjust columns functions for menus UI
			columns.useCheckboxesForHidden();
			columns.checked = function(field) {
				$('.field-' + field).removeClass('hidden-field');
			}
			columns.unchecked = function(field) {
				$('.field-' + field).addClass('hidden-field');
			}
			// hide fields
			api.menuList.hideAdvancedMenuItemFields();
		},

		initSortables : function() {
			var currentDepth = 0, originalDepth, minDepth, maxDepth,
				prev, next, prevBottom, nextThreshold, helperHeight, transport,
				menuEdge = api.menuList.offset().left,
				body = $('body'), maxChildDepth,
				menuMaxDepth = initialMenuMaxDepth();

			// Use the right edge if RTL.
			menuEdge += api.isRTL ? api.menuList.width() : 0;

			api.menuList.sortable({
				handle: '.menu-item-handle',
				placeholder: 'sortable-placeholder',
				start: function(e, ui) {
					var height, width, parent, children, tempHolder;

					// handle placement for rtl orientation
					if ( api.isRTL )
						ui.item[0].style.right = 'auto';

					transport = ui.item.children('.menu-item-transport');

					// Set depths. currentDepth must be set before children are located.
					originalDepth = ui.item.menuItemDepth();
					updateCurrentDepth(ui, originalDepth);

					// Attach child elements to parent
					// Skip the placeholder
					parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
					children = parent.childMenuItems();
					transport.append( children );

					// Update the height of the placeholder to match the moving item.
					height = transport.outerHeight();
					// If there are children, account for distance between top of children and parent
					height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
					height += ui.helper.outerHeight();
					helperHeight = height;
					height -= 2; // Subtract 2 for borders
					ui.placeholder.height(height);

					// Update the width of the placeholder to match the moving item.
					maxChildDepth = originalDepth;
					children.each(function(){
						var depth = $(this).menuItemDepth();
						maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
					});
					width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
					width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
					width -= 2; // Subtract 2 for borders
					ui.placeholder.width(width);

					// Update the list of menu items.
					tempHolder = ui.placeholder.next();
					tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
					ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
					$(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know.
					ui.item.after( ui.placeholder ); // reattach the placeholder.
					tempHolder.css('margin-top', 0); // reset the margin

					// Now that the element is complete, we can update...
					updateSharedVars(ui);
				},
				stop: function(e, ui) {
					var children, depthChange = currentDepth - originalDepth;

					// Return child elements to the list
					children = transport.children().insertAfter(ui.item);

					// Update depth classes
					if( depthChange != 0 ) {
						ui.item.updateDepthClass( currentDepth );
						children.shiftDepthClass( depthChange );
						updateMenuMaxDepth( depthChange );
					}
					// Register a change
					api.registerChange();
					// Update the item data.
					ui.item.updateParentMenuItemDBId();

					// address sortable's incorrectly-calculated top in opera
					ui.item[0].style.top = 0;

					// handle drop placement for rtl orientation
					if ( api.isRTL ) {
						ui.item[0].style.left = 'auto';
						ui.item[0].style.right = 0;
					}

					// The width of the tab bar might have changed. Just in case.
					api.refreshMenuTabs( true );
				},
				change: function(e, ui) {
					// Make sure the placeholder is inside the menu.
					// Otherwise fix it, or we're in trouble.
					if( ! ui.placeholder.parent().hasClass('menu') )
						(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );

					updateSharedVars(ui);
				},
				sort: function(e, ui) {
					var offset = ui.helper.offset(),
						edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
						depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
					// Check and correct if depth is not within range.
					// Also, if the dragged element is dragged upwards over
					// an item, shift the placeholder to a child position.
					if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
					else if ( depth < minDepth ) depth = minDepth;

					if( depth != currentDepth )
						updateCurrentDepth(ui, depth);

					// If we overlap the next element, manually shift downwards
					if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
						next.after( ui.placeholder );
						updateSharedVars( ui );
						$(this).sortable( "refreshPositions" );
					}
				}
			});

			function updateSharedVars(ui) {
				var depth;

				prev = ui.placeholder.prev();
				next = ui.placeholder.next();

				// Make sure we don't select the moving item.
				if( prev[0] == ui.item[0] ) prev = prev.prev();
				if( next[0] == ui.item[0] ) next = next.next();

				prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
				nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
				minDepth = (next.length) ? next.menuItemDepth() : 0;

				if( prev.length )
					maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
				else
					maxDepth = 0;
			}

			function updateCurrentDepth(ui, depth) {
				ui.placeholder.updateDepthClass( depth, currentDepth );
				currentDepth = depth;
			}

			function initialMenuMaxDepth() {
				if( ! body[0].className ) return 0;
				var match = body[0].className.match(/menu-max-depth-(\d+)/);
				return match && match[1] ? parseInt(match[1]) : 0;
			}

			function updateMenuMaxDepth( depthChange ) {
				var depth, newDepth = menuMaxDepth;
				if ( depthChange === 0 ) {
					return;
				} else if ( depthChange > 0 ) {
					depth = maxChildDepth + depthChange;
					if( depth > menuMaxDepth )
						newDepth = depth;
				} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
					while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
						newDepth--;
				}
				// Update the depth class.
				body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
				menuMaxDepth = newDepth;
			}
		},

		attachMenuEditListeners : function() {
			var that = this;
			$('#update-nav-menu').bind('click', function(e) {
				if ( e.target && e.target.className ) {
					if ( -1 != e.target.className.indexOf('item-edit') ) {
						return that.eventOnClickEditLink(e.target);
					} else if ( -1 != e.target.className.indexOf('menu-save') ) {
						return that.eventOnClickMenuSave(e.target);
					} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
						return that.eventOnClickMenuDelete(e.target);
					} else if ( -1 != e.target.className.indexOf('item-delete') ) {
						return that.eventOnClickMenuItemDelete(e.target);
					} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
						return that.eventOnClickCancelLink(e.target);
					}
				}
			});
			$('#add-custom-links input[type="text"]').keypress(function(e){
				if ( e.keyCode === 13 ) {
					e.preventDefault();
					$("#submit-customlinkdiv").click();
				}
			});
		},

		/**
		 * An interface for managing default values for input elements
		 * that is both JS and accessibility-friendly.
		 *
		 * Input elements that add the class 'input-with-default-title'
		 * will have their values set to the provided HTML title when empty.
		 */
		setupInputWithDefaultTitle : function() {
			var name = 'input-with-default-title';

			$('.' + name).each( function(){
				var $t = $(this), title = $t.attr('title'), val = $t.val();
				$t.data( name, title );

				if( '' == val ) $t.val( title );
				else if ( title == val ) return;
				else $t.removeClass( name );
			}).focus( function(){
				var $t = $(this);
				if( $t.val() == $t.data(name) )
					$t.val('').removeClass( name );
			}).blur( function(){
				var $t = $(this);
				if( '' == $t.val() )
					$t.addClass( name ).val( $t.data(name) );
			});
		},

		attachThemeLocationsListeners : function() {
			var loc = $('#nav-menu-theme-locations'), params = {};
			params['action'] = 'menu-locations-save';
			params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
			loc.find('input[type="submit"]').click(function() {
				loc.find('select').each(function() {
					params[this.name] = $(this).val();
				});
				loc.find('.waiting').show();
				$.post( ajaxurl, params, function(r) {
					loc.find('.waiting').hide();
				});
				return false;
			});
		},

		attachQuickSearchListeners : function() {
			var searchTimer;

			$('.quick-search').keypress(function(e){
				var t = $(this);

				if( 13 == e.which ) {
					api.updateQuickSearchResults( t );
					return false;
				}

				if( searchTimer ) clearTimeout(searchTimer);

				searchTimer = setTimeout(function(){
					api.updateQuickSearchResults( t );
				}, 400);
			}).attr('autocomplete','off');
		},

		updateQuickSearchResults : function(input) {
			var panel, params,
			minSearchLength = 2,
			q = input.val();

			if( q.length < minSearchLength ) return;

			panel = input.parents('.tabs-panel');
			params = {
				'action': 'menu-quick-search',
				'response-format': 'markup',
				'menu': $('#menu').val(),
				'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
				'q': q,
				'type': input.attr('name')
			};

			$('img.waiting', panel).show();

			$.post( ajaxurl, params, function(menuMarkup) {
				api.processQuickSearchQueryResponse(menuMarkup, params, panel);
			});
		},

		addCustomLink : function( processMethod ) {
			var url = $('#custom-menu-item-url').val(),
				label = $('#custom-menu-item-name').val();

			processMethod = processMethod || api.addMenuItemToBottom;

			if ( '' == url || 'http://' == url )
				return false;

			// Show the ajax spinner
			$('.customlinkdiv img.waiting').show();
			this.addLinkToMenu( url, label, processMethod, function() {
				// Remove the ajax spinner
				$('.customlinkdiv img.waiting').hide();
				// Set custom link form back to defaults
				$('#custom-menu-item-name').val('').blur();
				$('#custom-menu-item-url').val('http://');
			});
		},

		addLinkToMenu : function(url, label, processMethod, callback) {
			processMethod = processMethod || api.addMenuItemToBottom;
			callback = callback || function(){};

			api.addItemToMenu({
				'-1': {
					'menu-item-type': 'custom',
					'menu-item-url': url,
					'menu-item-title': label
				}
			}, processMethod, callback);
		},

		addItemToMenu : function(menuItem, processMethod, callback) {
			var menu = $('#menu').val(),
				nonce = $('#menu-settings-column-nonce').val();

			processMethod = processMethod || function(){};
			callback = callback || function(){};

			params = {
				'action': 'add-menu-item',
				'menu': menu,
				'menu-settings-column-nonce': nonce,
				'menu-item': menuItem
			};

			$.post( ajaxurl, params, function(menuMarkup) {
				var ins = $('#menu-instructions');
				processMethod(menuMarkup, params);
				if( ! ins.hasClass('menu-instructions-inactive') && ins.siblings().length )
					ins.addClass('menu-instructions-inactive');
				callback();
			});
		},

		/**
		 * Process the add menu item request response into menu list item.
		 *
		 * @param string menuMarkup The text server response of menu item markup.
		 * @param object req The request arguments.
		 */
		addMenuItemToBottom : function( menuMarkup, req ) {
			$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
		},

		addMenuItemToTop : function( menuMarkup, req ) {
			$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
		},

		attachUnsavedChangesListener : function() {
			$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea').change(function(){
				api.registerChange();
			});

			if ( 0 != $('#menu-to-edit').length ) {
				window.onbeforeunload = function(){
					if ( api.menusChanged )
						return navMenuL10n.saveAlert;
				};
			} else {
				// Make the post boxes read-only, as they can't be used yet
				$('#menu-settings-column').find('input,select').prop('disabled', true).end().find('a').attr('href', '#').unbind('click');
			}
		},

		registerChange : function() {
			api.menusChanged = true;
		},

		attachTabsPanelListeners : function() {
			$('#menu-settings-column').bind('click', function(e) {
				var selectAreaMatch, panelId, wrapper, items,
					target = $(e.target);

				if ( target.hasClass('nav-tab-link') ) {
					panelId = /#(.*)$/.exec(e.target.href);
					if ( panelId && panelId[1] )
						panelId = panelId[1]
					else
						return false;

					wrapper = target.parents('.inside').first();

					// upon changing tabs, we want to uncheck all checkboxes
					$('input', wrapper).removeAttr('checked');

					$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
					$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');

					$('.tabs', wrapper).removeClass('tabs');
					target.parent().addClass('tabs');

					// select the search bar
					$('.quick-search', wrapper).focus();

					return false;
				} else if ( target.hasClass('select-all') ) {
					selectAreaMatch = /#(.*)$/.exec(e.target.href);
					if ( selectAreaMatch && selectAreaMatch[1] ) {
						items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
						if( items.length === items.filter(':checked').length )
							items.removeAttr('checked');
						else
							items.prop('checked', true);
						return false;
					}
				} else if ( target.hasClass('submit-add-to-menu') ) {
					api.registerChange();

					if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
						api.addCustomLink( api.addMenuItemToBottom );
					else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
						$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
					return false;
				} else if ( target.hasClass('page-numbers') ) {
					$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
						function( resp ) {
							if ( -1 == resp.indexOf('replace-id') )
								return;

							var metaBoxData = $.parseJSON(resp),
							toReplace = document.getElementById(metaBoxData['replace-id']),
							placeholder = document.createElement('div'),
							wrap = document.createElement('div');

							if ( ! metaBoxData['markup'] || ! toReplace )
								return;

							wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : '';

							toReplace.parentNode.insertBefore( placeholder, toReplace );
							placeholder.parentNode.removeChild( toReplace );

							placeholder.parentNode.insertBefore( wrap, placeholder );

							placeholder.parentNode.removeChild( placeholder );

						}
					);

					return false;
				}
			});
		},

		initTabManager : function() {
			var fixed = $('.nav-tabs-wrapper'),
				fluid = fixed.children('.nav-tabs'),
				active = fluid.children('.nav-tab-active'),
				tabs = fluid.children('.nav-tab'),
				tabsWidth = 0,
				fixedRight, fixedLeft,
				arrowLeft, arrowRight, resizeTimer, css = {},
				marginFluid = api.isRTL ? 'margin-right' : 'margin-left',
				marginFixed = api.isRTL ? 'margin-left' : 'margin-right',
				msPerPx = 2;

			/**
			 * Refreshes the menu tabs.
			 * Will show and hide arrows where necessary.
			 * Scrolls to the active tab by default.
			 *
			 * @param savePosition {boolean} Optional. Prevents scrolling so
			 * 		  that the current position is maintained. Default false.
			 **/
			api.refreshMenuTabs = function( savePosition ) {
				var fixedWidth = fixed.width(),
					margin = 0, css = {};
				fixedLeft = fixed.offset().left;
				fixedRight = fixedLeft + fixedWidth;

				if( !savePosition )
					active.makeTabVisible();

				// Prevent space from building up next to the last tab if there's more to show
				if( tabs.last().isTabVisible() ) {
					margin = fixed.width() - tabsWidth;
					margin = margin > 0 ? 0 : margin;
					css[marginFluid] = margin + 'px';
					fluid.animate( css, 100, "linear" );
				}

				// Show the arrows only when necessary
				if( fixedWidth > tabsWidth )
					arrowLeft.add( arrowRight ).hide();
				else
					arrowLeft.add( arrowRight ).show();
			}

			$.fn.extend({
				makeTabVisible : function() {
					var t = this.eq(0), left, right, css = {}, shift = 0;

					if( ! t.length ) return this;

					left = t.offset().left;
					right = left + t.outerWidth();

					if( right > fixedRight )
						shift = fixedRight - right;
					else if ( left < fixedLeft )
						shift = fixedLeft - left;

					if( ! shift ) return this;

					css[marginFluid] = "+=" + api.negateIfRTL * shift + 'px';
					fluid.animate( css, Math.abs( shift ) * msPerPx, "linear" );
					return this;
				},
				isTabVisible : function() {
					var t = this.eq(0),
						left = t.offset().left,
						right = left + t.outerWidth();
					return ( right <= fixedRight && left >= fixedLeft ) ? true : false;
				}
			});

			// Find the width of all tabs
			tabs.each(function(){
				tabsWidth += $(this).outerWidth(true);
			});

			// Set up fixed margin for overflow, unset padding
			css['padding'] = 0;
			css[marginFixed] = (-1 * tabsWidth) + 'px';
			fluid.css( css );

			// Build tab navigation
			arrowLeft = $('<div class="nav-tabs-arrow nav-tabs-arrow-left"><a>«</a></div>');
			arrowRight = $('<div class="nav-tabs-arrow nav-tabs-arrow-right"><a>»</a></div>');
			// Attach to the document
			fixed.wrap('<div class="nav-tabs-nav"/>').parent().prepend( arrowLeft ).append( arrowRight );

			// Set the menu tabs
			api.refreshMenuTabs();
			// Make sure the tabs reset on resize
			$(window).resize(function() {
				if( resizeTimer ) clearTimeout(resizeTimer);
				resizeTimer = setTimeout( api.refreshMenuTabs, 200);
			});

			// Build arrow functions
			$.each([{
					arrow : arrowLeft,
					next : "next",
					last : "first",
					operator : "+="
				},{
					arrow : arrowRight,
					next : "prev",
					last : "last",
					operator : "-="
				}], function(){
				var that = this;
				this.arrow.mousedown(function(){
					var marginFluidVal = Math.abs( parseInt( fluid.css(marginFluid) ) ),
						shift = marginFluidVal,
						css = {};

					if( "-=" == that.operator )
						shift = Math.abs( tabsWidth - fixed.width() ) - marginFluidVal;

					if( ! shift ) return;

					css[marginFluid] = that.operator + shift + 'px';
					fluid.animate( css, shift * msPerPx, "linear" );
				}).mouseup(function(){
					var tab, next;
					fluid.stop(true);
					tab = tabs[that.last]();
					while( (next = tab[that.next]()) && next.length && ! next.isTabVisible() ) {
						tab = next;
					}
					tab.makeTabVisible();
				});
			});
		},

		eventOnClickEditLink : function(clickedEl) {
			var settings, item,
			matchedSection = /#(.*)$/.exec(clickedEl.href);
			if ( matchedSection && matchedSection[1] ) {
				settings = $('#'+matchedSection[1]);
				item = settings.parent();
				if( 0 != item.length ) {
					if( item.hasClass('menu-item-edit-inactive') ) {
						if( ! settings.data('menu-item-data') ) {
							settings.data( 'menu-item-data', settings.getItemData() );
						}
						settings.slideDown('fast');
						item.removeClass('menu-item-edit-inactive')
							.addClass('menu-item-edit-active');
					} else {
						settings.slideUp('fast');
						item.removeClass('menu-item-edit-active')
							.addClass('menu-item-edit-inactive');
					}
					return false;
				}
			}
		},

		eventOnClickCancelLink : function(clickedEl) {
			var settings = $(clickedEl).closest('.menu-item-settings');
			settings.setItemData( settings.data('menu-item-data') );
			return false;
		},

		eventOnClickMenuSave : function(clickedEl) {
			var locs = '',
			menuName = $('#menu-name'),
			menuNameVal = menuName.val();
			// Cancel and warn if invalid menu name
			if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
				menuName.parent().addClass('form-invalid');
				return false;
			}
			// Copy menu theme locations
			$('#nav-menu-theme-locations select').each(function() {
				locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
			});
			$('#update-nav-menu').append( locs );
			// Update menu item position data
			api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
			window.onbeforeunload = null;

			return true;
		},

		eventOnClickMenuDelete : function(clickedEl) {
			// Delete warning AYS
			if ( confirm( navMenuL10n.warnDeleteMenu ) ) {
				window.onbeforeunload = null;
				return true;
			}
			return false;
		},

		eventOnClickMenuItemDelete : function(clickedEl) {
			var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
			api.removeMenuItem( $('#menu-item-' + itemID) );
			api.registerChange();
			return false;
		},

		/**
		 * Process the quick search response into a search result
		 *
		 * @param string resp The server response to the query.
		 * @param object req The request arguments.
		 * @param jQuery panel The tabs panel we're searching in.
		 */
		processQuickSearchQueryResponse : function(resp, req, panel) {
			var matched, newID,
			takenIDs = {},
			form = document.getElementById('nav-menu-meta'),
			pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'),
			$items = $('<div>').html(resp).find('li'),
			$item;

			if( ! $items.length ) {
				$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
				$('img.waiting', panel).hide();
				return;
			}

			$items.each(function(){
				$item = $(this);

				// make a unique DB ID number
				matched = pattern.exec($item.html());

				if ( matched && matched[1] ) {
					newID = matched[1];
					while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
						newID--;
					}

					takenIDs[newID] = true;
					if ( newID != matched[1] ) {
						$item.html( $item.html().replace(new RegExp(
							'menu-item\\[' + matched[1] + '\\]', 'g'),
							'menu-item[' + newID + ']'
						) );
					}
				}
			});

			$('.categorychecklist', panel).html( $items );
			$('img.waiting', panel).hide();
		},

		removeMenuItem : function(el) {
			var children = el.childMenuItems();

			el.addClass('deleting').animate({
					opacity : 0,
					height: 0
				}, 350, function() {
					var ins = $('#menu-instructions');
					el.remove();
					children.shiftDepthClass(-1).updateParentMenuItemDBId();
					if( ! ins.siblings().length )
						ins.removeClass('menu-instructions-inactive');
				});
		},

		depthToPx : function(depth) {
			return depth * api.options.menuItemDepthPerLevel;
		},

		pxToDepth : function(px) {
			return Math.floor(px / api.options.menuItemDepthPerLevel);
		}

	};

	$(document).ready(function(){ wpNavMenu.init(); });

})(jQuery);


text: To run this example, first run `npm install` and then open `index.html` in a browser.


text:
use std::collections::BTreeMap;
use std::env;
use std::fmt::format;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::io::{Error, ErrorKind};
use std::path::Path;
use std::string::*;
// use std::thread;

use std::net::UdpSocket;

// use touchpage::startserver;
use touchpage as tp;
use touchpage::control_nexus as cn;
use touchpage::control_updates as cu;
extern crate touchpage;

#[macro_use]
mod tryopt;
mod stringerror;

extern crate tinyosc;
use tinyosc as osc;

extern crate serde_json;
use serde_json::Value;

fn load_string(file_name: &str) -> Result<String, Box<dyn std::error::Error>> {
  let path = &Path::new(&file_name);
  let mut inf = try!(File::open(path));
  let mut result = String::new();
  try!(inf.read_to_string(&mut result));
  Ok(result)
}

fn write_string(text: &str, file_name: &str) -> Result<(), Box<dyn std::error::Error>> {
  let path = &Path::new(&file_name);
  let mut inf = try!(File::create(path));
  match inf.write(text.as_bytes()) {
    Ok(_) => Ok(()),
    Err(e) => Err(Box::new(e)),
  }
}

fn make_default_prefs(guifile: &str) -> BTreeMap<String, Value> {
  let mut map = BTreeMap::new();
  map.insert(String::from("guifile"), Value::String(guifile.to_string()));
  map.insert(String::from("ip"), Value::String("0.0.0.0".to_string()));
  map.insert(String::from("http-port"), Value::String("3030".to_string()));
  map.insert(
    String::from("websockets-port"),
    Value::String("1234".to_string()),
  );
  map.insert(
    String::from("oscrecvip"),
    Value::String("localhost:9000".to_string()),
  );
  map.insert(
    String::from("oscsendip"),
    Value::String("127.0.0.1:7070".to_string()),
  );

  map
}

fn main() {
  // read in the settings json.
  let args = env::args();
  let mut iter = args.skip(1); // skip the program name
  match iter.next() {
    Some(file_name) => {
      if file_name == "-mkconfigs" {
        let a = iter.next();
        let b = iter.next();
        match (a, b) {
          (Some(prefs_filename), Some(gui_filename)) => {
            let value = Value::Object(make_default_prefs(&gui_filename[..]));

            if let Ok(sv) = serde_json::to_string_pretty(&value) {
              match write_string(&sv[..], &prefs_filename[..]) {
                Ok(()) => println!("wrote example server config to file: {}", prefs_filename),
                Err(e) => println!("error writing default config file: {:?}", e),
              }
              match write_string(touchpage::json::sample_gui_config(), &gui_filename[..]) {
                Ok(()) => println!("wrote example gui config to file: {}", gui_filename),
                Err(e) => println!("error writing default config file: {:?}", e),
              }
            }
          }
          (Some(prefs_filename), _) => {
            let value = Value::Object(make_default_prefs("gui.conf"));

            if let Ok(sv) = serde_json::to_string_pretty(&value) {
              match write_string(&sv[..], &prefs_filename[..]) {
                Ok(()) => println!("wrote server config to file: {}", prefs_filename),
                Err(e) => println!("error writing default config file: {:?}", e),
              }
            }
          }
          _ => println!("no config filenames!"),
        }
      } else {
        match startserver_w_config(&file_name) {
          Err(e) => println!("error starting server: {:?}", e),
          _ => (),
        }
      }
    }
    None => {
      println!("oscpad syntax: ");
      println!("oscpad <json config file>");
      println!("oscpad -mkconfigs <example server config file> <example gui config file>");
    }
  }
}

pub struct SendOscMsg {
  oscsendsocket: UdpSocket,
  oscsendip: String,
}

impl cn::ControlUpdateProcessor for SendOscMsg {
  fn on_update_received(&mut self, update: &cu::UpdateMsg, cn: &mut cn::ControlNexus) -> () {
    println!("on_update_receivedi {:?}", update);
    match cn.ci.lock() {
      Ok(ci) => match ctrl_update_to_osc(update, &ci) {
        Ok(v) => match self.oscsendsocket.send_to(&v, &self.oscsendip[..]) {
          Ok(_) => {
            println!("osc message sent : {:?}, {:?}", v, self.oscsendip);
            ()
          }
          Err(e) => {
            println!("oscsendip: {:?}", self.oscsendip);
            println!("error sending osc message: {:?}", e)
          }
        },
        Err(e) => println!("error building osc message: {:?}", e),
      },
      Err(e) => println!("error with locK: {}", e),
    };

    println!("update callback called! {:?}", update);
  }
}

fn startserver_w_config(file_name: &String) -> Result<(), Box<dyn std::error::Error>> {
  println!("loading config file: {}", file_name);
  let configstring = try!(load_string(&file_name));

  // read config file as json
  let configval: Value = try!(serde_json::from_str(&configstring[..]));

  let oobj = try_opt_resbox!(configval.as_object(), "config file is not a json object!");
  let obj = oobj.clone();

  let guifilename = try_opt_resbox!(
    try_opt_resbox!(obj.get("guifile"), "'guifile' not found in config file").as_string(),
    "failed to convert to string"
  );
  let guistring = try!(load_string(&guifilename[..]));

  let htmlfilename = match obj.get("htmlfile") {
    Some(val) => {
      println!("loading htmlfile: {:?}", val.as_string());
      val.as_string()
    }
    None => None,
  };

  let ip = String::new()
    + try_opt_resbox!(
      try_opt_resbox!(obj.get("ip"), "'ip' not found!").as_string(),
      "'ip' not a string!"
    );

  let http_port = String::new()
    + try_opt_resbox!(
      try_opt_resbox!(obj.get("http-port"), "'http-port' not found!").as_string(),
      "'http-port' not a string!"
    );

  let mut http_ip = String::from(ip.as_str());
  http_ip.push_str(":");
  http_ip.push_str(&http_port);

  let websockets_port = String::new()
    + try_opt_resbox!(
      try_opt_resbox!(obj.get("websockets-port"), "'websockets-port' not found!").as_string(),
      "'websockets-port' not a string!"
    );

  let oscrecvip = String::new()
    + try_opt_resbox!(
      try_opt_resbox!(obj.get("oscrecvip"), "'oscrecvip' not found!").as_string(),
      "'oscrecvip' not a string!"
    );

  let oscsendip = String::new()
    + try_opt_resbox!(
      try_opt_resbox!(obj.get("oscsendip"), "'oscsendip' not found!").as_string(),
      "'oscsendip' not a string!"
    );

  let oscsocket = try!(UdpSocket::bind(&oscrecvip[..]));

  // for sending, bind to this.  if we bind to localhost, we can't
  // send messages to other machines.

  let oscsendsocket = try!(UdpSocket::bind("0.0.0.0:0"));
  let wsos = try!(oscsendsocket.try_clone());
  let wsoscsendip = oscsendip.clone();

  let cup = Box::new(SendOscMsg {
    oscsendsocket: wsos,
    oscsendip: wsoscsendip,
  });

  println!("websockets port: {}", websockets_port);
  let control_server = try!(tp::websocketserver::start(
    guistring.as_str(),
    cup,
    ip.as_str(),
    websockets_port.as_str(),
    false,
  ));

  //"../touchpage/example/index.html"
  let htmltemplate = match htmlfilename {
    Some(fname) => match load_string(fname) {
      Ok(s) => Some(s),
      Err(_) => {
        println!("no html template, using default.");
        None
      }
    },
    None => None,
  };

  tp::webserver::start(
    "localhost",
    http_port.as_str(),
    websockets_port.as_str(),
    htmltemplate,
    false,
  );

  println!("after startwebserver");
  match oscmain(oscsocket, &control_server) {
    Err(e) => println!("oscmain exited with error: {:?}", e),
    Ok(_) => (),
  };

  Ok(())
}

// TODO:
// how should osc messages be structured?
//  - seperate messages for each control attribute?
//  - named pairs, attrib + amount
//  - positional: <location> <state> <labelval>
//  I'm tending towards the named pairs.  But, look at the client code and
// see if that would be an undue hardship.

fn ctrl_update_to_osc(um: &cu::UpdateMsg, ci: &cn::ControlInfo) -> Result<Vec<u8>, Error> {
  match um {
    &cu::UpdateMsg::Button {
      control_id: ref id,
      label: ref opt_lab,
      state: ref st,
    } => {
      // find the control in the map.
      match ci.get_name(&id) {
        Some(oscname) => {
          let mut args = Vec::new();
          if let &Some(ref state) = st {
            args.push(match state {
              &cu::PressState::Pressed => osc::Argument::s("pressed"),
              &cu::PressState::Unpressed => osc::Argument::s("unpressed"),
            })
          };

          if let &Some(ref lb) = opt_lab {
            args.push(osc::Argument::s("label"));
            args.push(osc::Argument::s(&lb[..]));
          };

          let msg = osc::Message {
            path: oscname.as_str(),
            arguments: args,
          };
          msg.serialize()
        }
        None => Err(Error::new(ErrorKind::NotFound, "osc id not found!")),
      }
    }
    &cu::UpdateMsg::Slider {
      control_id: ref id,
      label: ref lb,
      state: ref st,
      location: ref loc,
    } => match ci.get_name(&id) {
      Some(oscname) => {
        let mut args = Vec::new();
        if let &Some(ref state) = st {
          args.push(match state {
            &cu::PressState::Pressed => osc::Argument::s("pressed"),
            &cu::PressState::Unpressed => osc::Argument::s("unpressed"),
          });
        };
        if let &Some(ref location) = loc {
          let l = *location as f32;
          args.push(osc::Argument::s("location"));
          args.push(osc::Argument::f(l));
        };
        if let &Some(ref label) = lb {
          args.push(osc::Argument::s("label"));
          args.push(osc::Argument::s(&label[..]));
        };

        let msg = osc::Message {
          path: oscname.as_str(),
          arguments: args,
        };
        msg.serialize()
      }
      None => Err(Error::new(ErrorKind::NotFound, "osc id not found!")),
    },
    &cu::UpdateMsg::XY {
      control_id: ref id,
      label: ref lb,
      state: ref st,
      location: ref loc,
    } => match ci.get_name(&id) {
      Some(oscname) => {
        let mut args = Vec::new();
        if let &Some(ref state) = st {
          args.push(match state {
            &cu::PressState::Pressed => osc::Argument::s("pressed"),
            &cu::PressState::Unpressed => osc::Argument::s("unpressed"),
          });
        };
        if let &Some(ref location) = loc {
          let (lx, ly) = *location as (f32, f32);
          args.push(osc::Argument::s("locx"));
          args.push(osc::Argument::f(lx));
          args.push(osc::Argument::s("locy"));
          args.push(osc::Argument::f(ly));
        };
        if let &Some(ref label) = lb {
          args.push(osc::Argument::s("label"));
          args.push(osc::Argument::s(&label[..]));
        };

        let msg = osc::Message {
          path: oscname.as_str(),
          arguments: args,
        };
        msg.serialize()
      }
      None => Err(Error::new(ErrorKind::NotFound, "osc id not found!")),
    },
    &cu::UpdateMsg::Label {
      control_id: ref id,
      label: ref labtext,
    } => match ci.get_name(&id) {
      Some(oscname) => {
        let mut args = Vec::new();
        args.push(osc::Argument::s("label"));
        args.push(osc::Argument::s(&labtext[..]));
        let msg = osc::Message {
          path: oscname.as_str(),
          arguments: args,
        };
        msg.serialize()
      }
      None => Err(Error::new(ErrorKind::NotFound, "osc id not found!")),
    },
  }
}

// TODO: find the control itself and check its type.
// then build an update message based on that type.

// building the update message based on type:
//  - create an update message with all None
//  - make a function that takes the args array and an index.
//  - check for the various things at the index.
//  - recursively call self with updated update message.

// wow this code is hideous!  do not look!
fn parse_osc_control_update(
  om: &osc::Message,
  arg_index: usize,
  update: cu::UpdateMsg,
) -> Result<cu::UpdateMsg, Box<dyn std::error::Error>> {
  if arg_index >= om.arguments.len() {
    Ok(update)
  } else {
    match om.arguments[arg_index] {
      osc::Argument::s("pressed") => {
        let mut newupd = update.clone();
        match newupd {
          cu::UpdateMsg::Button { ref mut state, .. } => {
            *state = Some(cu::PressState::Pressed);
          }
          cu::UpdateMsg::Slider { ref mut state, .. } => {
            *state = Some(cu::PressState::Pressed);
          }
          _ => (),
        };
        parse_osc_control_update(om, arg_index + 1, newupd)
      }
      osc::Argument::s("unpressed") => {
        let mut newupd = update.clone();
        match newupd {
          cu::UpdateMsg::Button { ref mut state, .. } => {
            *state = Some(cu::PressState::Unpressed);
          }
          cu::UpdateMsg::Slider { ref mut state, .. } => {
            *state = Some(cu::PressState::Unpressed);
          }
          _ => (),
        };
        parse_osc_control_update(om, arg_index + 1, newupd)
      }
      osc::Argument::s("location") => {
        if om.arguments.len() <= arg_index + 1 {
          Err(Box::new(Error::new(
            ErrorKind::Other,
            "location should be followed by a number between 0.0 and 1.0!",
          )))
        } else {
          match &om.arguments[arg_index + 1] {
            &osc::Argument::f(loc) => {
              let mut newupd = update.clone();
              match newupd {
                cu::UpdateMsg::Slider {
                  ref mut location, ..
                } => {
                  *location = Some(loc as f64);
                }
                _ => (),
              };
              parse_osc_control_update(om, arg_index + 2, newupd)
            }
            _ => Err(Box::new(Error::new(
              ErrorKind::Other,
              "location should be followed by a number between 0.0 and 1.0!",
            ))),
          }
        }
      }
      osc::Argument::s("label") => {
        if om.arguments.len() <= arg_index + 1 {
          Err(Box::new(Error::new(
            ErrorKind::Other,
            "'label' should be followed by a string!",
          )))
        } else {
          match &om.arguments[arg_index + 1] {
            &osc::Argument::s(txt) => {
              let mut newupd = update.clone();
              match newupd {
                cu::UpdateMsg::Button { ref mut label, .. } => {
                  *label = Some(txt.to_string());
                }
                cu::UpdateMsg::Slider { ref mut label, .. } => {
                  *label = Some(txt.to_string());
                }
                cu::UpdateMsg::XY { ref mut label, .. } => {
                  *label = Some(txt.to_string());
                }
                cu::UpdateMsg::Label { ref mut label, .. } => {
                  *label = txt.to_string();
                }
              };
              parse_osc_control_update(om, arg_index + 2, newupd)
            }
            _ => Err(Box::new(Error::new(
              ErrorKind::Other,
              "location should be followed by a number between 0.0 and 1.0!",
            ))),
          }
        }
      }
      _ => Err(Box::new(Error::new(ErrorKind::Other, "unknown keyword!"))),
    }
  }
}

fn osc_to_ctrl_update(
  om: &osc::Message,
  cserver: &cn::ControlNexus,
) -> Result<cu::UpdateMsg, Box<dyn std::error::Error>> {
  // find the control by name.

  let updmsg = cserver.make_update_msg(om.path);

  match updmsg {
    Some(updmsg_yeah) => parse_osc_control_update(om, 0, updmsg_yeah),
    None => {
      let msg = format(format_args!("failed to update control: {:?}", om.path));
      Err(Box::new(Error::new(ErrorKind::Other, msg)))
    }
  }
}

fn oscmain(
  recvsocket: UdpSocket,
  control_server: &cn::ControlNexus,
) -> Result<String, Box<dyn std::error::Error>> {
  let mut buf = [0; 10000];

  loop {
    let (amt, _) = try!(recvsocket.recv_from(&mut buf));

    match osc::Message::deserialize(&buf[..amt]) {
      Err(e) => println!("invalid osc messsage: {:?}", e),
      Ok(inmsg) => {
        match osc_to_ctrl_update(&inmsg, control_server) {
          Ok(updmsg) => control_server.update(&updmsg),
          Err(e) => {
            if inmsg.path == "guiconfig" && inmsg.arguments.len() > 0 {
              // is this a control config update instead?
              match &inmsg.arguments[0] {
                &osc::Argument::s(guistring) => {
                  println!("new control layout recieved!");
                  match control_server.load_gui_string(guistring) {
                    Ok(()) => (),
                    Err(e) => println!("error loading control layout: {}", e),
                  }
                }
                _ => println!("osc decode error: {:?}", e),
              }
            }
          }
        };

        // print received afterwards, I guess for latency savings?
        println!("osc message received {} {:?}", inmsg.path, inmsg.arguments);
      }
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cystopus mysorensis Thirum. & Safeeulla

### Remarks
null