text:
package org.apache.spark.sql

import java.sql.{Date, Timestamp}

import org.apache.spark.sql.catalyst.plans.logical.Union
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.{ExamplePoint, ExamplePointUDT, SharedSQLContext}
import org.apache.spark.sql.test.SQLTestData.NullStrings
import org.apache.spark.sql.types._

class DataFrameSetOperationsSuite extends QueryTest with SharedSQLContext {
  import testImplicits._

  test("except") {
    checkAnswer(
      lowerCaseData.except(upperCaseData),
      Row(1, "a") ::
        Row(2, "b") ::
        Row(3, "c") ::
        Row(4, "d") :: Nil)
    checkAnswer(lowerCaseData.except(lowerCaseData), Nil)
    checkAnswer(upperCaseData.except(upperCaseData), Nil)

    // check null equality
    checkAnswer(
      nullInts.except(nullInts.filter("0 = 1")),
      nullInts)
    checkAnswer(
      nullInts.except(nullInts),
      Nil)

    // check if values are de-duplicated
    checkAnswer(
      allNulls.except(allNulls.filter("0 = 1")),
      Row(null) :: Nil)
    checkAnswer(
      allNulls.except(allNulls),
      Nil)

    // check if values are de-duplicated
    val df = Seq(("id1", 1), ("id1", 1), ("id", 1), ("id1", 2)).toDF("id", "value")
    checkAnswer(
      df.except(df.filter("0 = 1")),
      Row("id1", 1) ::
        Row("id", 1) ::
        Row("id1", 2) :: Nil)

    // check if the empty set on the left side works
    checkAnswer(
      allNulls.filter("0 = 1").except(allNulls),
      Nil)
  }

  test("SPARK-23274: except between two projects without references used in filter") {
    val df = Seq((1, 2, 4), (1, 3, 5), (2, 2, 3), (2, 4, 5)).toDF("a", "b", "c")
    val df1 = df.filter($"a" === 1)
    val df2 = df.filter($"a" === 2)
    checkAnswer(df1.select("b").except(df2.select("b")), Row(3) :: Nil)
    checkAnswer(df1.select("b").except(df2.select("c")), Row(2) :: Nil)
  }

  test("except distinct - SQL compliance") {
    val df_left = Seq(1, 2, 2, 3, 3, 4).toDF("id")
    val df_right = Seq(1, 3).toDF("id")

    checkAnswer(
      df_left.except(df_right),
      Row(2) :: Row(4) :: Nil
    )
  }

  test("except - nullability") {
    val nonNullableInts = Seq(Tuple1(11), Tuple1(3)).toDF()
    assert(nonNullableInts.schema.forall(!_.nullable))

    val df1 = nonNullableInts.except(nullInts)
    checkAnswer(df1, Row(11) :: Nil)
    assert(df1.schema.forall(!_.nullable))

    val df2 = nullInts.except(nonNullableInts)
    checkAnswer(df2, Row(1) :: Row(2) :: Row(null) :: Nil)
    assert(df2.schema.forall(_.nullable))

    val df3 = nullInts.except(nullInts)
    checkAnswer(df3, Nil)
    assert(df3.schema.forall(_.nullable))

    val df4 = nonNullableInts.except(nonNullableInts)
    checkAnswer(df4, Nil)
    assert(df4.schema.forall(!_.nullable))
  }

  test("except all") {
    checkAnswer(
      lowerCaseData.exceptAll(upperCaseData),
      Row(1, "a") ::
        Row(2, "b") ::
        Row(3, "c") ::
        Row(4, "d") :: Nil)
    checkAnswer(lowerCaseData.exceptAll(lowerCaseData), Nil)
    checkAnswer(upperCaseData.exceptAll(upperCaseData), Nil)

    // check null equality
    checkAnswer(
      nullInts.exceptAll(nullInts.filter("0 = 1")),
      nullInts)
    checkAnswer(
      nullInts.exceptAll(nullInts),
      Nil)

    // check that duplicate values are preserved
    checkAnswer(
      allNulls.exceptAll(allNulls.filter("0 = 1")),
      Row(null) :: Row(null) :: Row(null) :: Row(null) :: Nil)
    checkAnswer(
      allNulls.exceptAll(allNulls.limit(2)),
      Row(null) :: Row(null) :: Nil)

    // check that duplicates are retained.
    val df = spark.sparkContext.parallelize(
      NullStrings(1, "id1") ::
        NullStrings(1, "id1") ::
        NullStrings(2, "id1") ::
        NullStrings(3, null) :: Nil).toDF("id", "value")

    checkAnswer(
      df.exceptAll(df.filter("0 = 1")),
      Row(1, "id1") ::
        Row(1, "id1") ::
        Row(2, "id1") ::
        Row(3, null) :: Nil)

    // check if the empty set on the left side works
    checkAnswer(
      allNulls.filter("0 = 1").exceptAll(allNulls),
      Nil)

  }

  test("exceptAll - nullability") {
    val nonNullableInts = Seq(Tuple1(11), Tuple1(3)).toDF()
    assert(nonNullableInts.schema.forall(!_.nullable))

    val df1 = nonNullableInts.exceptAll(nullInts)
    checkAnswer(df1, Row(11) :: Nil)
    assert(df1.schema.forall(!_.nullable))

    val df2 = nullInts.exceptAll(nonNullableInts)
    checkAnswer(df2, Row(1) :: Row(2) :: Row(null) :: Nil)
    assert(df2.schema.forall(_.nullable))

    val df3 = nullInts.exceptAll(nullInts)
    checkAnswer(df3, Nil)
    assert(df3.schema.forall(_.nullable))

    val df4 = nonNullableInts.exceptAll(nonNullableInts)
    checkAnswer(df4, Nil)
    assert(df4.schema.forall(!_.nullable))
  }

  test("intersect") {
    checkAnswer(
      lowerCaseData.intersect(lowerCaseData),
      Row(1, "a") ::
        Row(2, "b") ::
        Row(3, "c") ::
        Row(4, "d") :: Nil)
    checkAnswer(lowerCaseData.intersect(upperCaseData), Nil)

    // check null equality
    checkAnswer(
      nullInts.intersect(nullInts),
      Row(1) ::
        Row(2) ::
        Row(3) ::
        Row(null) :: Nil)

    // check if values are de-duplicated
    checkAnswer(
      allNulls.intersect(allNulls),
      Row(null) :: Nil)

    // check if values are de-duplicated
    val df = Seq(("id1", 1), ("id1", 1), ("id", 1), ("id1", 2)).toDF("id", "value")
    checkAnswer(
      df.intersect(df),
      Row("id1", 1) ::
        Row("id", 1) ::
        Row("id1", 2) :: Nil)
  }

  test("intersect - nullability") {
    val nonNullableInts = Seq(Tuple1(1), Tuple1(3)).toDF()
    assert(nonNullableInts.schema.forall(!_.nullable))

    val df1 = nonNullableInts.intersect(nullInts)
    checkAnswer(df1, Row(1) :: Row(3) :: Nil)
    assert(df1.schema.forall(!_.nullable))

    val df2 = nullInts.intersect(nonNullableInts)
    checkAnswer(df2, Row(1) :: Row(3) :: Nil)
    assert(df2.schema.forall(!_.nullable))

    val df3 = nullInts.intersect(nullInts)
    checkAnswer(df3, Row(1) :: Row(2) :: Row(3) :: Row(null) :: Nil)
    assert(df3.schema.forall(_.nullable))

    val df4 = nonNullableInts.intersect(nonNullableInts)
    checkAnswer(df4, Row(1) :: Row(3) :: Nil)
    assert(df4.schema.forall(!_.nullable))
  }

  test("intersectAll") {
    checkAnswer(
      lowerCaseDataWithDuplicates.intersectAll(lowerCaseDataWithDuplicates),
      Row(1, "a") ::
        Row(2, "b") ::
        Row(2, "b") ::
        Row(3, "c") ::
        Row(3, "c") ::
        Row(3, "c") ::
        Row(4, "d") :: Nil)
    checkAnswer(lowerCaseData.intersectAll(upperCaseData), Nil)

    // check null equality
    checkAnswer(
      nullInts.intersectAll(nullInts),
      Row(1) ::
        Row(2) ::
        Row(3) ::
        Row(null) :: Nil)

    // Duplicate nulls are preserved.
    checkAnswer(
      allNulls.intersectAll(allNulls),
      Row(null) :: Row(null) :: Row(null) :: Row(null) :: Nil)

    val df_left = Seq(1, 2, 2, 3, 3, 4).toDF("id")
    val df_right = Seq(1, 2, 2, 3).toDF("id")

    checkAnswer(
      df_left.intersectAll(df_right),
      Row(1) :: Row(2) :: Row(2) :: Row(3) :: Nil)
  }

  test("intersectAll - nullability") {
    val nonNullableInts = Seq(Tuple1(1), Tuple1(3)).toDF()
    assert(nonNullableInts.schema.forall(!_.nullable))

    val df1 = nonNullableInts.intersectAll(nullInts)
    checkAnswer(df1, Row(1) :: Row(3) :: Nil)
    assert(df1.schema.forall(!_.nullable))

    val df2 = nullInts.intersectAll(nonNullableInts)
    checkAnswer(df2, Row(1) :: Row(3) :: Nil)
    assert(df2.schema.forall(!_.nullable))

    val df3 = nullInts.intersectAll(nullInts)
    checkAnswer(df3, Row(1) :: Row(2) :: Row(3) :: Row(null) :: Nil)
    assert(df3.schema.forall(_.nullable))

    val df4 = nonNullableInts.intersectAll(nonNullableInts)
    checkAnswer(df4, Row(1) :: Row(3) :: Nil)
    assert(df4.schema.forall(!_.nullable))
  }

  test("SPARK-10539: Project should not be pushed down through Intersect or Except") {
    val df1 = (1 to 100).map(Tuple1.apply).toDF("i")
    val df2 = (1 to 30).map(Tuple1.apply).toDF("i")
    val intersect = df1.intersect(df2)
    val except = df1.except(df2)
    assert(intersect.count() === 30)
    assert(except.count() === 70)
  }

  test("SPARK-10740: handle nondeterministic expressions correctly for set operations") {
    val df1 = (1 to 20).map(Tuple1.apply).toDF("i")
    val df2 = (1 to 10).map(Tuple1.apply).toDF("i")

    // When generating expected results at here, we need to follow the implementation of
    // Rand expression.
    def expected(df: DataFrame): Seq[Row] = {
      df.rdd.collectPartitions().zipWithIndex.flatMap {
        case (data, index) =>
          val rng = new org.apache.spark.util.random.XORShiftRandom(7 + index)
          data.filter(_.getInt(0) < rng.nextDouble() * 10)
      }
    }

    val union = df1.union(df2)
    checkAnswer(
      union.filter('i < rand(7) * 10),
      expected(union)
    )
    checkAnswer(
      union.select(rand(7)),
      union.rdd.collectPartitions().zipWithIndex.flatMap {
        case (data, index) =>
          val rng = new org.apache.spark.util.random.XORShiftRandom(7 + index)
          data.map(_ => rng.nextDouble()).map(i => Row(i))
      }
    )

    val intersect = df1.intersect(df2)
    checkAnswer(
      intersect.filter('i < rand(7) * 10),
      expected(intersect)
    )

    val except = df1.except(df2)
    checkAnswer(
      except.filter('i < rand(7) * 10),
      expected(except)
    )
  }

  test("SPARK-17123: Performing set operations that combine non-scala native types") {
    val dates = Seq(
      (new Date(0), BigDecimal.valueOf(1), new Timestamp(2)),
      (new Date(3), BigDecimal.valueOf(4), new Timestamp(5))
    ).toDF("date", "timestamp", "decimal")

    val widenTypedRows = Seq(
      (new Timestamp(2), 10.5D, "string")
    ).toDF("date", "timestamp", "decimal")

    dates.union(widenTypedRows).collect()
    dates.except(widenTypedRows).collect()
    dates.intersect(widenTypedRows).collect()
  }

  test("SPARK-19893: cannot run set operations with map type") {
    val df = spark.range(1).select(map(lit("key"), $"id").as("m"))
    val e = intercept[AnalysisException](df.intersect(df))
    assert(e.message.contains(
      "Cannot have map type columns in DataFrame which calls set operations"))
    val e2 = intercept[AnalysisException](df.except(df))
    assert(e2.message.contains(
      "Cannot have map type columns in DataFrame which calls set operations"))
    val e3 = intercept[AnalysisException](df.distinct())
    assert(e3.message.contains(
      "Cannot have map type columns in DataFrame which calls set operations"))
    withTempView("v") {
      df.createOrReplaceTempView("v")
      val e4 = intercept[AnalysisException](sql("SELECT DISTINCT m FROM v"))
      assert(e4.message.contains(
        "Cannot have map type columns in DataFrame which calls set operations"))
    }
  }

  test("union all") {
    val unionDF = testData.union(testData).union(testData)
      .union(testData).union(testData)

    // Before optimizer, Union should be combined.
    assert(unionDF.queryExecution.analyzed.collect {
      case j: Union if j.children.size == 5 => j }.size === 1)

    checkAnswer(
      unionDF.agg(avg('key), max('key), min('key), sum('key)),
      Row(50.5, 100, 1, 25250) :: Nil
    )

    // unionAll is an alias of union
    val unionAllDF = testData.unionAll(testData).unionAll(testData)
      .unionAll(testData).unionAll(testData)

    checkAnswer(unionDF, unionAllDF)
  }

  test("union should union DataFrames with UDTs (SPARK-13410)") {
    val rowRDD1 = sparkContext.parallelize(Seq(Row(1, new ExamplePoint(1.0, 2.0))))
    val schema1 = StructType(Array(StructField("label", IntegerType, false),
      StructField("point", new ExamplePointUDT(), false)))
    val rowRDD2 = sparkContext.parallelize(Seq(Row(2, new ExamplePoint(3.0, 4.0))))
    val schema2 = StructType(Array(StructField("label", IntegerType, false),
      StructField("point", new ExamplePointUDT(), false)))
    val df1 = spark.createDataFrame(rowRDD1, schema1)
    val df2 = spark.createDataFrame(rowRDD2, schema2)

    checkAnswer(
      df1.union(df2).orderBy("label"),
      Seq(Row(1, new ExamplePoint(1.0, 2.0)), Row(2, new ExamplePoint(3.0, 4.0)))
    )
  }

  test("union by name") {
    var df1 = Seq((1, 2, 3)).toDF("a", "b", "c")
    var df2 = Seq((3, 1, 2)).toDF("c", "a", "b")
    val df3 = Seq((2, 3, 1)).toDF("b", "c", "a")
    val unionDf = df1.unionByName(df2.unionByName(df3))
    checkAnswer(unionDf,
      Row(1, 2, 3) :: Row(1, 2, 3) :: Row(1, 2, 3) :: Nil
    )

    // Check if adjacent unions are combined into a single one
    assert(unionDf.queryExecution.optimizedPlan.collect { case u: Union => true }.size == 1)

    // Check failure cases
    df1 = Seq((1, 2)).toDF("a", "c")
    df2 = Seq((3, 4, 5)).toDF("a", "b", "c")
    var errMsg = intercept[AnalysisException] {
      df1.unionByName(df2)
    }.getMessage
    assert(errMsg.contains(
      "Union can only be performed on tables with the same number of columns, " +
        "but the first table has 2 columns and the second table has 3 columns"))

    df1 = Seq((1, 2, 3)).toDF("a", "b", "c")
    df2 = Seq((4, 5, 6)).toDF("a", "c", "d")
    errMsg = intercept[AnalysisException] {
      df1.unionByName(df2)
    }.getMessage
    assert(errMsg.contains("""Cannot resolve column name "b" among (a, c, d)"""))
  }

  test("union by name - type coercion") {
    var df1 = Seq((1, "a")).toDF("c0", "c1")
    var df2 = Seq((3, 1L)).toDF("c1", "c0")
    checkAnswer(df1.unionByName(df2), Row(1L, "a") :: Row(1L, "3") :: Nil)

    df1 = Seq((1, 1.0)).toDF("c0", "c1")
    df2 = Seq((8L, 3.0)).toDF("c1", "c0")
    checkAnswer(df1.unionByName(df2), Row(1.0, 1.0) :: Row(3.0, 8.0) :: Nil)

    df1 = Seq((2.0f, 7.4)).toDF("c0", "c1")
    df2 = Seq(("a", 4.0)).toDF("c1", "c0")
    checkAnswer(df1.unionByName(df2), Row(2.0, "7.4") :: Row(4.0, "a") :: Nil)

    df1 = Seq((1, "a", 3.0)).toDF("c0", "c1", "c2")
    df2 = Seq((1.2, 2, "bc")).toDF("c2", "c0", "c1")
    val df3 = Seq(("def", 1.2, 3)).toDF("c1", "c2", "c0")
    checkAnswer(df1.unionByName(df2.unionByName(df3)),
      Row(1, "a", 3.0) :: Row(2, "bc", 1.2) :: Row(3, "def", 1.2) :: Nil
    )
  }

  test("union by name - check case sensitivity") {
    def checkCaseSensitiveTest(): Unit = {
      val df1 = Seq((1, 2, 3)).toDF("ab", "cd", "ef")
      val df2 = Seq((4, 5, 6)).toDF("cd", "ef", "AB")
      checkAnswer(df1.unionByName(df2), Row(1, 2, 3) :: Row(6, 4, 5) :: Nil)
    }
    withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
      val errMsg2 = intercept[AnalysisException] {
        checkCaseSensitiveTest()
      }.getMessage
      assert(errMsg2.contains("""Cannot resolve column name "ab" among (cd, ef, AB)"""))
    }
    withSQLConf(SQLConf.CASE_SENSITIVE.key -> "false") {
      checkCaseSensitiveTest()
    }
  }

  test("union by name - check name duplication") {
    Seq((true, ("a", "a")), (false, ("aA", "Aa"))).foreach { case (caseSensitive, (c0, c1)) =>
      withSQLConf(SQLConf.CASE_SENSITIVE.key -> caseSensitive.toString) {
        var df1 = Seq((1, 1)).toDF(c0, c1)
        var df2 = Seq((1, 1)).toDF("c0", "c1")
        var errMsg = intercept[AnalysisException] {
          df1.unionByName(df2)
        }.getMessage
        assert(errMsg.contains("Found duplicate column(s) in the left attributes:"))
        df1 = Seq((1, 1)).toDF("c0", "c1")
        df2 = Seq((1, 1)).toDF(c0, c1)
        errMsg = intercept[AnalysisException] {
          df1.unionByName(df2)
        }.getMessage
        assert(errMsg.contains("Found duplicate column(s) in the right attributes:"))
      }
    }
  }

  test("SPARK-25368 Incorrect predicate pushdown returns wrong result") {
    def check(newCol: Column, filter: Column, result: Seq[Row]): Unit = {
      val df1 = spark.createDataFrame(Seq(
        (1, 1)
      )).toDF("a", "b").withColumn("c", newCol)

      val df2 = df1.union(df1).withColumn("d", spark_partition_id).filter(filter)
      checkAnswer(df2, result)
    }

    check(lit(null).cast("int"), $"c".isNull, Seq(Row(1, 1, null, 0), Row(1, 1, null, 1)))
    check(lit(null).cast("int"), $"c".isNotNull, Seq())
    check(lit(2).cast("int"), $"c".isNull, Seq())
    check(lit(2).cast("int"), $"c".isNotNull, Seq(Row(1, 1, 2, 0), Row(1, 1, 2, 1)))
    check(lit(2).cast("int"), $"c" === 2, Seq(Row(1, 1, 2, 0), Row(1, 1, 2, 1)))
    check(lit(2).cast("int"), $"c" =!= 2, Seq())
  }
}


text:
<#############################################################################
The TypePx module adds properties and methods to the most commonly used types
to make common tasks easier. Using these type extensions together can provide
an enhanced syntax in PowerShell that is both easier to read and
self-documenting. TypePx also provides commands to manage type accelerators.
Type acceleration also contributes to making scripting easier and they help
produce more readable scripts, particularly when using a library of .NET
classes that belong to the same namespace.

Copyright 2016 Kirk Munro

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#############################################################################>

<#
.SYNOPSIS
    Adds type accelerators for every exported type in a namespace.
.DESCRIPTION
    The Use-Namespace command adds type accelerators for every exported type in a namespace.

    Type accelerators may be added for namespaces by name or by path. By default, all type accelerators added by this command are permanently added to the session. You may use the ScriptBlock parameter to add the type accelerators for a namespace only for the duration of the invocation of the script block.
.INPUTS
    String,System.IO.File
.OUTPUTS
    None
.EXAMPLE
    PS C:\> Use-TypeAccelerator -Namespace System.Xml

    This command points adds type accelerators for every exported type from the System.Xml namespace.
.EXAMPLE
    PS C:\> Use-Namespace -Namespace System.Windows.Forms -ScriptBlock {
    >> [MessageBox]::Show('Hello world!') > $null
    >> }

    This command points adds type accelerators for every exported type from the System.Xml namespace.
.LINK
    Add-TypeAccelerator
.LINK
    Get-TypeAccelerator
.LINK
    Remove-TypeAccelerator
.LINK
    Set-TypeAccelerator
#>
function Use-Namespace {
    [CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName='byName')]
    [OutputType([System.Void])]
    param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='byPath')]
        [ValidateNotNullOrEmpty()]
        [SupportsWildcards()]
        [System.String[]]
        $Path,

        [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='byLiteralPath')]
        [ValidateNotNullOrEmpty()]
        [Alias('PSPath')]
        [System.String[]]
        $LiteralPath,

        [Parameter(ParameterSetName='byName', Position=0, Mandatory=$true)]
        [Parameter(ParameterSetName='byPath', Position=1)]
        [Parameter(ParameterSetName='byLiteralPath', Position=1)]
        [ValidateNotNullOrEmpty()]
        [System.String[]]
        $Namespace,

        [Parameter(ParameterSetName='byName', Position=1)]
        [Parameter(ParameterSetName='byPath', Position=2)]
        [Parameter(ParameterSetName='byLiteralPath', Position=2)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.ScriptBlock]
        $ScriptBlock,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [Alias('As')]
        [System.String]
        $Alias,

        [Parameter()]
        [System.Management.Automation.SwitchParameter]
        $NoClobber
    )
    begin {
        try {
            #region Load the current type accelerators.

            [System.Collections.Hashtable]$initialTypeAccelerators = $script:TypeAcceleratorsType::Get

            #endregion

            #region Define shared scripts.

            [System.Collections.Hashtable]$sharedScript = @{
                ProcessAssembly = {
                    param(
                        $NamespaceCollection = $null
                    )
                    $assembly.GetExportedTypes() `
                        | Where-Object {
                            $_.IsPublic -or $_.IsNestedPublic
                        } `
                        | ForEach-Object {
                            if ($NamespaceCollection) {
                                $NamespaceCollection = @($NamespaceCollection -replace '^([^,]+),.*$','$1')
                                foreach ($namespaceItem in $NamespaceCollection) {
                                    if (($namespaceItem -notmatch '^System\.') -and ($_.FullName -match "^System\.${namespaceItem}\.")) {
                                        $namespaceItem = "System.${namespaceItem}"
                                    }
                                    if ($_.FullName -match "^${namespaceItem}\.") {
                                        $acceleratorName = $_.Name
                                        if ($_.FullName -ne "${namespaceItem}.${acceleratorName}") {
                                            $acceleratorPrefix = $_.FullName -replace "^${namespaceItem}\.(.+)\.${acceleratorName}`$",'$1'
                                            if ($acceleratorPrefix -ne $_.FullName) {
                                                $acceleratorName = "${acceleratorPrefix}.${acceleratorName}"
                                            }
                                        }
                                        if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Alias')) {
                                            $acceleratorName = "${Alias}.${acceleratorName}"
                                        }
                                        Add-TypeAccelerator -Name $acceleratorName -Type $_
                                        break
                                    }
                                }
                            } else {
                                $acceleratorName = $_.Name
                                if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Alias')) {
                                    $acceleratorName = "${Alias}.${acceleratorName}"
                                }
                                Add-TypeAccelerator -Name $acceleratorName -Type $_
                            }
                        }
                }
            }

            #endregion
        } catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
    process {
        try {
            #region Define the requested type accelerators.

            switch ($PSCmdlet.ParameterSetName) {
                'byName' {
                    #region Define type accelerators for the specified namespace(s).

                    foreach ($item in $Namespace) {
                        if ($item -eq 'System') {
                            continue
                        }
                        [System.Reflection.Assembly]$assembly = $null
                        if ($item -match 'PublicKeyToken') {
                            $assembly = [System.Reflection.Assembly]::Load($item)
                        } else {
                            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($item)
                            if ((-not $assembly) -and
                                ($item -notmatch '^System\.')) {
                                $assembly = [System.Reflection.Assembly]::LoadWithPartialName("System.${item}")
                                if ($assembly) {
                                    $item = "System.${item}"
                                }
                            }
                        }
                        if ($assembly) {
                            & $sharedScript.ProcessAssembly -NamespaceCollection $item
                        } else {
                            $assemblies = [System.AppDomain]::CurrentDomain.GetAssemblies() `
                                | Where-Object {
                                    $_.GetTypes() `
                                        | Where-Object {
                                            $_.Namespace -match "^${item}" -or $_.Namespace -match "^System.${item}"
                                        }
                                }
                            foreach ($assembly in $assemblies) {
                                & $sharedScript.ProcessAssembly -NamespaceCollection $item
                            }
                        }
                    }

                    #endregion
                    break
                }
                default {
                    #region Define type accelerators for the specified file(s) and namespace(s).

                    $getItemParameters = $PSCmdlet.GetSplattableParameters(@('Path','LiteralPath'))
                    foreach ($item in Get-Item @getItemParameters) {
                        if ($item -isnot [System.IO.FileInfo]) {
                            continue
                        }
                        [System.Reflection.Assembly]$assembly = [System.Reflection.Assembly]::LoadFrom($item.FullName)
                        if ($assembly) {
                            $passThruParameters = @{}
                            if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Namespace')) {
                                $passThruParameters['NamespaceCollection'] = $Namespace
                            }
                            & $sharedScript.ProcessAssembly @passThruParameters
                        }
                    }

                    #endregion
                    break
                }
            }

            #endregion

            #region If -ScriptBlock was used, invoke it.

            if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('ScriptBlock')) {
                ForEach-Object -Process $ScriptBlock
            }

            #endregion
        } catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
    end {
        try {
            #region If -ScriptBlock was used, reset the type accelerators back to the previous state.

            if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('ScriptBlock')) {
                foreach ($key in @($script:TypeAcceleratorsType::Get | Select-Object -ExpandProperty Keys)) {
                    $script:TypeAcceleratorsType::Remove($key) > $null
                    if ($initialTypeAccelerators.ContainsKey($key)) {
                        if (Get-Member -InputObject $script:TypeAcceleratorsType -Name AddReplace -Static -ErrorAction Ignore) {
                            $script:TypeAcceleratorsType::AddReplace($key, $initialTypeAccelerators[$key])
                        } else {
                            $script:TypeAcceleratorsType::Add($key,$initialTypeAccelerators[$key])
                        }
                    }
                }
            }

            #endregion
        } catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}

Export-ModuleMember -Function Use-Namespace

New-Alias -Name use -Value Use-Namespace -ErrorAction Ignore
if ($?) {
    Export-ModuleMember -Alias use
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "Midnight Sampling"
date:   2016-12-28 15:07:20
categories: [field]
comments: true
author: "John Cristiani"
---
We did a bunch of work in Tsawwassen.  It was cold.

<!--more-->

Let's test some things out.

Let's try to put in an image.

![Snow in the parking lot]({{ site.url }}/img/20161228/night.jpg)

Did it work?


text:
namespace Proxy
{
    class ProxyProgram
    {
        static void Main(string[] args)
        {
           Logic.Apps.Proxy();
        }
    }
}


text:
package com.nanyang.app.main.home.sport.basketball;

import android.content.Context;
import android.view.View;

import com.nanyang.app.BaseToolbarActivity;
import com.nanyang.app.R;
import com.nanyang.app.main.home.sport.main.BallAdapterHelper;
import com.nanyang.app.main.home.sport.model.BettingParPromptBean;
import com.nanyang.app.main.home.sportInterface.BaseMixStyleHandler;
import com.unkonw.testapp.libs.adapter.MyRecyclerViewHolder;
import com.unkonw.testapp.training.ScrollLayout;

/**
 * Created by Administrator on 2017/3/14.
 */

/**
 * {
 * "SocOddsId": 12219288,
 * "Home": "AS摩纳哥",
 * "Away": "曼城",
 * "IsHomeGive": false,
 * "IsBetHome": false,
 * "ParFullTimeId": "12219287",
 * "TransType": "HDP",
 * "IsOddsChange": false,
 * "ParUrl": "http://a8197c.a36588.com/_bet/JRecPanel.aspx?g=2&b=away_par&oId=12219288&odds=19",
 * "BetHdp": "0",
 * "BetOu": "0",
 * "BetOdds": "1.90",
 * "Test2": "testing2"
 * }
 */

public class BasketballAdapterHelper extends BallAdapterHelper<BasketballMixInfo> {

    public BasketballAdapterHelper(Context context) {
        super(context);

    }

    @Override
    public void onConvert(MyRecyclerViewHolder helper, int position, final BasketballMixInfo item) {
        super.onConvert(helper, position, item);
        View tvCollection = helper.getView(R.id.module_match_collection_tv);
        View markAdd = helper.getView(R.id.module_right_mark_tv);
        markAdd.setVisibility(View.GONE);
        tvCollection.setVisibility(View.GONE);
        ScrollLayout sl = helper.getView(R.id.module_center_sl);
        scrollChild(sl.getChildAt(1), false, item, item.getIsHomeGive(), item.getHasX12(), "", item.getHasOE(), "", item.getIsX12New(), "", "", "", item.getX12_1Odds(), item.getX12_2Odds(), "1", "2", "", ""
                , true, false, true, item.getHasOE(), item.getIsOENew(), (item.getOEOdds()!=null&&Float.valueOf(item.getOEOdds())>=1||Float.valueOf(item.getOEOdds())<=-1)?item.getOddOdds():"",
                (item.getOEOdds()!=null&&Float.valueOf(item.getOEOdds())>=1||Float.valueOf(item.getOEOdds())<=-1)?item.getEvenOdds():"", "odd", "even");
        getBaseRecyclerAdapter().getItem(position).setIsX12New("0");
        getBaseRecyclerAdapter().getItem(position).setIsOENew("0");
        BaseMixStyleHandler handler = new BaseMixStyleHandler((BaseToolbarActivity) context);
        String itemFullSocOddsId = item.getSocOddsId();
        BettingParPromptBean.BetParBean mixItem = handler.getMixItem(itemFullSocOddsId);
        if (mixItem != null) {
            if (mixItem.getTransType().equalsIgnoreCase("OE"))
                handler.parseMixBackground(mixItem, 1, sl);
            else {
                handler.parseMixBackground(mixItem, 0, sl);
            }
        } else {
            handler.parseCommonBackground(0, sl);
            handler.parseCommonBackground(1, sl);
        }
    }

}


text:
@interface PodsDummy_RamblerTyphoonUtils : NSObject
@end
@implementation PodsDummy_RamblerTyphoonUtils
@end


text:
package controllers.application

import actors.persistent.DeleteAlerts
import actors.persistent.staffing.GetState
import akka.pattern._
import akka.util.Timeout
import controllers.Application
import drt.shared.Alert
import drt.shared.CrunchApi.MillisSinceEpoch
import org.joda.time.DateTime
import play.api.mvc.{Action, AnyContent}
import uk.gov.homeoffice.drt.auth.Roles.CreateAlerts
import upickle.default.{read, write}

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps

trait WithAlerts {
  self: Application =>

  def getAlerts(createdAfter: MillisSinceEpoch): Action[AnyContent] = Action.async { _ =>
    val eventualAlerts: Future[Seq[Alert]] = for {
      alerts <- (ctrl.alertsActor ? GetState).mapTo[Seq[Alert]]
    } yield alerts.filter(a => a.createdAt > createdAfter)

    eventualAlerts.map(alerts => Ok(write(alerts)))
  }

  def addAlert(): Action[AnyContent] = authByRole(CreateAlerts) {
    Action.async {
      implicit request =>
        log.info(s"Adding an Alert!")
        request.body.asText match {
          case Some(text) =>
            val alert: Alert = read[Alert](text)
            (ctrl.alertsActor ? Alert(alert.title, alert.message, alert.alertClass, alert.expires, createdAt = DateTime.now.getMillis)).mapTo[Alert].map { alert =>
              Ok(s"$alert added!")
            }
            Future(Accepted)
          case None =>
            Future(BadRequest)
        }
    }
  }

  def deleteAlerts(): Action[AnyContent] = authByRole(CreateAlerts) {
    Action.async {
      val futureAlerts = ctrl.alertsActor.ask(DeleteAlerts)(new Timeout(5 second))
      futureAlerts.map(s => {
        log.info(s"Removing all the alerts: $s")
        Ok(s.toString)
      })
    }
  }
}


text:
package com.phloc.commons.state;

/**
 * Very simple interface for an object that has valid/invalid indication.
 *
 * @author Philip Helger
 */
public interface IValidityIndicator
{
  /**
   * @return true if valid and false if invalid.
   */
  boolean isValid ();

  /**
   * @return true if invalid and false if valid.
   */
  boolean isInvalid ();
}


text:
#include "unicode/utypes.h"
#include "unicode/icudataver.h"
#include "unicode/uversion.h"
#include "unicode/ures.h"
#include "uresimp.h" /* for ures_getVersionByKey */
#include "cmemory.h"

/*
 * Determines if icustd is in the data.
 */
static UBool hasICUSTDBundle();

static UBool hasICUSTDBundle() {
    UErrorCode status = U_ZERO_ERROR;
    UBool result = TRUE;

    UResourceBundle *icustdbundle = ures_openDirect(NULL, U_ICU_STD_BUNDLE, &status);
    if (U_SUCCESS(status)) {
        result = TRUE;
    } else {
        result = FALSE;
    }

    ures_close(icustdbundle);

    return result;
}

U_CAPI void U_EXPORT2 u_getDataVersion(UVersionInfo dataVersionFillin, UErrorCode *status) {
    UResourceBundle *icudatares = NULL;

    if (U_FAILURE(*status)) {
        return;
    }

    if (dataVersionFillin != NULL) {
        icudatares = ures_openDirect(NULL, U_ICU_VERSION_BUNDLE , status);
        if (U_SUCCESS(*status)) {
            ures_getVersionByKey(icudatares, U_ICU_DATA_KEY, dataVersionFillin, status);
        }
        ures_close(icudatares);
    }
}

U_CAPI UBool U_EXPORT2 u_isDataOlder(UVersionInfo dataVersionFillin, UBool *isModifiedFillin, UErrorCode *status) {
    UBool result = TRUE;
    UVersionInfo dataVersion;
    UVersionInfo wiredVersion;

    if (U_FAILURE(*status)) {
        return result;
    }

    u_getDataVersion(dataVersion, status);
    if (U_SUCCESS(*status)) {
        u_versionFromString(wiredVersion, U_ICU_DATA_VERSION);

        if (uprv_memcmp(dataVersion, wiredVersion, sizeof(UVersionInfo)) >= 0) {
            result = FALSE;
        }

        if (dataVersionFillin != NULL) {
            uprv_memcpy(dataVersionFillin, dataVersion, sizeof(UVersionInfo));
        }

        if (hasICUSTDBundle()) {
            *isModifiedFillin = FALSE;
        } else {
            *isModifiedFillin = TRUE;
        }
    }

    return result;
}


text:
* [Vanilla example of PocketSphinx](./eg-pocketsphinx.py), not accurate as of now

* [Offline Speech Recognition using PocketSphinx and Python](./offline-speech-recognition-using-pocketsphinx.py), needs more work as not accurate

---


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 4/4/15
 * Time: 12:38 PM
 */
/**
 * @package     Semite LLC avista
 * @version     application.php 4/4/15 root
 * @copyright   Copyright (c) 2014 Semite LLC .
 * @license     http://www.semitepayment.com/license/
 */
/**
 * Description of application.php
 *
 * @author root
 */
// Heading
$_['heading_title']                    = 'Applications';

// Text
$_['text_success']                     = 'Success: You have modified Applications!';
$_['text_list']                        = 'Application List';
$_['text_add']                         = 'Add Application';
$_['text_edit']                        = 'Edit Application';
$_['text_items']                       = 'Items';
$_['text_tax']                         = 'Taxes';
$_['text_account']                     = 'Account';
$_['text_checkout']                    = 'Checkout';
$_['text_stock']                       = 'Stock';
$_['text_shipping']                    = 'Shipping Address';
$_['text_payment']                     = 'Payment Address';

// Column
$_['column_name']                      = 'Application Name';
$_['column_url']	                   = 'Application URL';
$_['column_action']                    = 'Action';

// Entry
$_['entry_url']                        = 'Application URL';
$_['entry_ssl']                        = 'SSL URL';
$_['entry_name']                       = 'Application Name';
$_['entry_owner']                      = 'Application Owner';
$_['entry_address']                    = 'Address';
$_['entry_geocode']                    = 'Geocode';
$_['entry_email']                      = 'E-Mail';
$_['entry_telephone']                  = 'Telephone';
$_['entry_fax']                        = 'Fax';
$_['entry_image']                      = 'Image';
$_['entry_open']                       = 'Opening Times';
$_['entry_comment']                    = 'Comment';
$_['entry_location']                   = 'Application Location';
$_['entry_meta_title']                 = 'Meta Title';
$_['entry_meta_description']           = 'Meta Tag Description';
$_['entry_meta_keyword']               = 'Meta Tag Keywords';
$_['entry_layout']                     = 'Default Layout';
$_['entry_template']                   = 'Template';
$_['entry_country']                    = 'Country';
$_['entry_zone']                       = 'Region / State';
$_['entry_language']                   = 'Language';
$_['entry_currency']                   = 'Currency';
$_['entry_product_limit'] 	           = 'Default Items Per Page (Catalog)';
$_['entry_product_description_length'] = 'List Description Limit (Catalog)';
$_['entry_tax']                        = 'Display Prices With Tax';
$_['entry_tax_default']                = 'Use Application Tax Address';
$_['entry_tax_customer']               = 'Use Customer Tax Address';
$_['entry_customer_group']             = 'Customer Group';
$_['entry_customer_group_display']     = 'Customer Groups';
$_['entry_customer_price']             = 'Login Display Prices';
$_['entry_account']                    = 'Account Terms';
$_['entry_cart_weight']                = 'Display Weight on Cart Page';
$_['entry_checkout_guest']             = 'Guest Checkout';
$_['entry_checkout']                   = 'Checkout Terms';
$_['entry_order_status']               = 'Order Status';
$_['entry_stock_display']              = 'Display Stock';
$_['entry_stock_checkout']             = 'Stock Checkout';
$_['entry_logo']                       = 'Application Logo';
$_['entry_icon']                       = 'Icon';
$_['entry_image_category']             = 'Category Image Size';
$_['entry_image_thumb']                = 'Product Image Thumb Size';
$_['entry_image_popup']                = 'Product Image Popup Size';
$_['entry_image_product']              = 'Product Image List Size';
$_['entry_image_additional']           = 'Additional Product Image Size';
$_['entry_image_related']              = 'Related Product Image Size';
$_['entry_image_compare']              = 'Compare Image Size';
$_['entry_image_wishlist']             = 'Wish List Image Size';
$_['entry_image_cart']                 = 'Cart Image Size';
$_['entry_image_location']             = 'Application Image Size';
$_['entry_width']                      = 'Width';
$_['entry_height']                     = 'Height';
$_['entry_secure']                     = 'Use SSL';

// Help
$_['help_url']                         = 'Include the full URL to your application. Make sure to add \'/\' at the end. Example: http://www.yourdomain.com/path/

Don\'t use directories to create a new application. You should always point another domain or sub domain to your hosting.';
$_['help_ssl']                         = 'SSL URL to your application. Make sure to add \'/\' at the end. Example: http://www.yourdomain.com/path/

Don\'t use directories to create a new application. You should always point another domain or sub domain to your hosting.';
$_['help_geocode']                     = 'Please enter your application location geocode manually.';
$_['help_open']                        = 'Fill in your applications opening times.';
$_['help_comment']                     = 'This field is for any special notes you would like to tell the customer i.e. Application does not accept cheques.';
$_['help_location']                    = 'The different application locations you have that you want displayed on the contact us form.';
$_['help_currency']                    = 'Change the default currency. Clear your browser cache to see the change and reset your existing cookie.';
$_['help_product_limit'] 	           = 'Determines how many catalog items are shown per page (products, categories, etc)';
$_['help_product_description_length']  = 'In the list view, short description character limit (categories, special etc)';
$_['help_tax_default']                 = 'Use the application address to calculate taxes if no one is logged in. You can choose to use the application address for the customers shipping or payment address.';
$_['help_tax_customer']                = 'Use the customers default address when they login to calculate taxes. You can choose to use the default address for the customers shipping or payment address.';
$_['help_customer_group']              = 'Default customer group.';
$_['help_customer_group_display']      = 'Display customer groups that new customers can select to use such as wholesale and business when signing up.';
$_['help_customer_price']              = 'Only show prices when a customer is logged in.';
$_['help_account']                     = 'Forces people to agree to terms before an account can be created.';
$_['help_checkout_guest']              = 'Allow customers to checkout without creating an account. This will not be available when a downloadable product is in the shopping cart.';
$_['help_checkout']                    = 'Forces people to agree to terms before an a customer can checkout.';
$_['help_order_status']                = 'Set the default order status when an order is processed.';
$_['help_stock_display']               = 'Display stock quantity on the product page.';
$_['help_stock_checkout']              = 'Allow customers to still checkout if the products they are ordering are not in stock.';
$_['help_icon']                        = 'The icon should be a PNG that is 16px x 16px.';
$_['help_secure']                      = 'To use SSL check with your host if a SSL certificate is installed.';

// Error
$_['error_warning']                    = 'Warning: Please check the form carefully for errors!';
$_['error_permission']                 = 'Warning: You do not have permission to modify applications!';
$_['error_name']                       = 'Application Name must be between 3 and 32 characters!';
$_['error_owner']                      = 'Application Owner must be between 3 and 64 characters!';
$_['error_address']                    = 'Application Address must be between 10 and 256 characters!';
$_['error_email']                      = 'E-Mail Address does not appear to be valid!';
$_['error_telephone']                  = 'Telephone must be between 3 and 32 characters!';
$_['error_url']                        = 'Application URL required!';
$_['error_meta_title']                 = 'Title must be between 3 and 32 characters!';
$_['error_limit']       	           = 'Limit required!';
$_['error_customer_group_display']     = 'You must include the default customer group if you are going to use this feature!';
$_['error_image_thumb']                = 'Product Image Thumb Size dimensions required!';
$_['error_image_popup']                = 'Product Image Popup Size dimensions required!';
$_['error_image_product']              = 'Product List Size dimensions required!';
$_['error_image_category']             = 'Category List Size dimensions required!';
$_['error_image_additional']           = 'Additional Product Image Size dimensions required!';
$_['error_image_related']              = 'Related Product Image Size dimensions required!';
$_['error_image_compare']              = 'Compare Image Size dimensions required!';
$_['error_image_wishlist']             = 'Wish List Image Size dimensions required!';
$_['error_image_cart']                 = 'Cart Image Size dimensions required!';
$_['error_image_location']             = 'Application Image Size dimensions required!';
$_['error_default']                    = 'Warning: You can not delete your default application!';
$_['error_application']                      = 'Warning: This Application cannot be deleted as it is currently assigned to %s orders!';


text:
require File.dirname(__FILE__) + "/activerecord_spec_helper"

describe 'Amistad friendship model whith custom friend model' do

  before(:all) do
    reload_environment

    Amistad.configure do |config|
      config.friend_model = 'Profile'
    end

    Profile = Class.new(ActiveRecord::Base)
    activate_amistad(Profile)
    create_users(Profile)
  end

  it_should_behave_like "the friendship model"
end


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

use strict;
use warnings;

use SeqStoreConverter::BasicConverter;

package SeqStoreConverter::MusMusculus;

use vars qw(@ISA);

@ISA = qw(SeqStoreConverter::BasicConverter);

sub create_coord_systems {
  my $self = shift;

  $self->debug("MusMusculus Specific: loading assembly data");

  my $target = $self->target();
  my $dbh    = $self->dbh();

  my $ass_def = $self->get_default_assembly();

  my @coords =
    (["chromosome" , $ass_def, "default_version"          ,1    ],
     ["supercontig", undef   , "default_version"          ,2     ],
     ['clone'      , undef   , 'default_version'          ,3     ],
     ["contig"     , undef   , "default_version,sequence_level",4]);

  my @assembly_mappings =  ("chromosome:$ass_def|contig",
                            "supercontig|contig",
                            "clone|contig",
                            "chromosome:$ass_def|contig|clone",
                            "chromosome:$ass_def|contig|supercontig",
                            "supercontig|contig|clone");

  $self->debug("Building coord_system table");

  my $sth = $dbh->prepare("INSERT INTO $target.coord_system " .
                           "(name, version, attrib, rank) VALUES (?,?,?,?)");

  my %coord_system_ids;

  foreach my $cs (@coords) {
    $sth->execute(@$cs);
    $coord_system_ids{$cs->[0]} = $sth->{'mysql_insertid'};
  }
  $sth->finish();

  $self->debug("Adding assembly.mapping entries to meta table");

  $sth = $dbh->prepare("INSERT INTO $target.meta(meta_key, meta_value) " .
                       "VALUES ('assembly.mapping', ?)");

  foreach my $mapping (@assembly_mappings) {
    $sth->execute($mapping);
  }

  $sth->finish();

  return;
}

sub create_seq_regions {
  my $self = shift;

  $self->debug("MusMusculus Specific: creating contig, " .
               "clone, chromosome and supercontig seq_regions");

  $self->contig_to_seq_region();
  $self->clone_to_seq_region();
  $self->chromosome_to_seq_region();
  $self->supercontig_to_seq_region();
}

sub create_assembly {
  my $self = shift;

  $self->debug("MusMusculus Specific: loading assembly data");

  $self->assembly_contig_chromosome();
  $self->assembly_contig_clone();
  $self->assembly_contig_supercontig();
}

#
# Override contig_to_seq_region and clone_to_seq_region to provide
# mouse specific behaviour
#

# sub contig_to_seq_region {
#   my $self = shift;
#   my $target_cs_name = shift;

#   my $target = $self->target();
#   my $source = $self->source();
#   my $dbh     = $self->dbh();

#   $target_cs_name ||= 'contig';

#   $self->debug("MusMusculus Specific: Transforming contigs into " .
#                "$target_cs_name seq_regions");

#   my $cs_id = $self->get_coord_system_id($target_cs_name);

#   #There are two types of contigs in mouse:

#   #
#   # Contigs which form BAC clones
#   #
#   my $sth = $dbh->prepare
#     ("INSERT INTO $target.seq_region " .
#      "SELECT contig_id, name, $cs_id, length " .
#      "FROM $source.contig " .
#      "WHERE  name not like 'C%'");

#   $sth->execute();
#   $sth->finish();

#   #
#   # Contigs which were created from whole genome shotgun
#   #
#   $sth = $dbh->prepare
#     ("INSERT INTO $target.seq_region " .
#      "SELECT ctg.contig_id, cln.name, $cs_id, length " .
#      "FROM   $source.contig ctg, $source.clone cln " .
#      "WHERE  ctg.clone_id = cln.clone_id " .
#      "AND    ctg.name like 'C%'");

#   $sth->execute();
#   $sth->finish();

#   return;
# }

sub clone_to_seq_region {
  my $self = shift;
  my $target_cs_name = shift;

  my $target = $self->target();
  my $source = $self->source();
  my $dbh    = $self->dbh();

  # target coord_system will have a different ID
  $target_cs_name ||= "clone";
  my $cs_id = $self->get_coord_system_id($target_cs_name);

  $self->debug("MusMusculus Specific:Transforming clones " .
               "into $target_cs_name seq_regions");

  #
  # We don't want to make clones out of the WGS contigs, only out of
  # the actual BACs with proper embl accessions
  #
  my $select_sth = $dbh->prepare
    ("SELECT cl.clone_id,
             CONCAT(cl.embl_acc, '.', cl.embl_version),
             MAX(ctg.embl_offset+ctg.length-1)
     FROM   $source.clone cl, $source.contig ctg
		 WHERE  cl.clone_id = ctg.clone_id
     AND    cl.embl_acc not like 'C%'
     GROUP BY ctg.clone_id");

  $select_sth->execute();

  my ($clone_id, $embl_acc, $length);
  $select_sth->bind_columns(\$clone_id, \$embl_acc, \$length);

  my $insert_sth = $dbh->prepare
    ("INSERT INTO $target.seq_region (name, coord_system_id, length) " .
     "VALUES(?,?,?)");

  my $tmp_insert_sth = $dbh->prepare
    ("INSERT INTO $target.tmp_cln_map (old_id, new_id) VALUES (?, ?)");

  while ($select_sth->fetch()) {
    $insert_sth->execute("$embl_acc", $cs_id, $length);

    #store mapping of old -> new ids in temp table
    $tmp_insert_sth->execute($clone_id, $insert_sth->{'mysql_insertid'});
  }

  $select_sth->finish();
  $insert_sth->finish();
  $tmp_insert_sth->finish();

  return;
}

1;


text:
complete(:method=>'config') {
  (Ripl::Shell::OPTIONS.keys + Ripl.config.keys).uniq -
    [:irbrc, :riplrc, :history, :completion, :readline]
}


text:
import {
  Component, View, OnInit, OnDestroy,
  Directive, ViewEncapsulation, Self,
  EventEmitter, ElementRef, ComponentRef,
  DynamicComponentLoader,
  CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle,
  bind, forwardRef, ResolvedBinding, Injector
} from 'angular2/angular2';

import {positionService} from '../position';
import {ISelectivity, IOptionsBehavior} from './selectivity-interfaces';
import {SelectivityItem} from './selectivity-item';
import {SelectivityOptions} from './selectivity-options';

@Component({
  selector: 'selectivity-options-container'
})
@View({
  template: `

    <input (keydown)="inputEvent($event)"
           (keyup)="inputEvent($event, true)"
           type="text"
           class="selectivity-search-input">

    <div *ng-if="items.length <= 0"
         class="selectivity-error">No results for {{inputValue}}

{{i.text}}

      <div *ng-if="items.length <= 0"
         class="selectivity-error">No results for {{inputValue}}

{{i.text}}

{{ii.text}}

  `,
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle],
  encapsulation: ViewEncapsulation.None
})
export class SelectivityOptionsContainer {
  public items:Array<SelectivityItem> = [];
  public active:SelectivityItem;
  private top:string;
  private left:string;
  private width:string;
  private display:string;
  private placement:string;
  private inputValue:string;
  private inputComponent:any;
  private behavior:IOptionsBehavior;

  constructor(public element:ElementRef, public options:SelectivityOptions) {
    Object.assign(this, options);
  }

  public position(hostEl:ElementRef, itemPosition:any = {}) {
    this.items = this.options.container
      .getItemObjects()
      .filter(option => (this.options.selectivity.multiple === false ||
      this.options.selectivity.multiple === true && !this.options.selectivity
        .active
        .find(o => option.text === o.text)));

    if (this.options.container.getItemObjects()[0].hasChildren()) {
      this.behavior = new SelectivityOptionsContainer.ChildrenBehavior(this);
    }

    if (!this.behavior) {
      this.behavior = new SelectivityOptionsContainer.GenericBehavior(this);
    }

    if (this.items.length > 0) {
      this.behavior.first();
    }

    this.display = 'block';
    // todo: adaptive top: in case of options at bottom of the screen
    let parentPosition = positionService.position(hostEl.nativeElement);
    let p = positionService
      .positionElements(hostEl.nativeElement,
        this.element.nativeElement.children[0],
        this.placement, false);

    // will be calculated in case of this container have parent menu
    let topOffset:number = itemPosition ? itemPosition.top + itemPosition.height : 0;
    this.top = (p.top + topOffset) + 'px';
    this.left = p.left + 'px';
    this.width = parentPosition.width + 'px';

    let inputs:Array<any> = [
      this.element.nativeElement.getElementsByClassName('selectivity-search-input'),
      this.element.nativeElement.parentElement.getElementsByClassName('selectivity-multiple-input')
    ];

    for (let i = 0; i < inputs.length; i++) {
      if (inputs[i].length > 0) {
        this.inputComponent = inputs[i][0];
        this.inputComponent.focus();
        break;
      }
    }
  }

  public inputEvent(e:any, isUpMode:boolean = false) {
    /*let resultsEl:any = this.element.nativeElement.children[1].children[3];
     let resultsPosition = positionService.position(resultsEl);*/

    // esc and tab
    if (!isUpMode && (e.keyCode === 27 || e.keyCode === 9)) {
      this.options.container.hide();
      e.preventDefault();
      return;
    }

    // backspace
    if (!isUpMode && e.keyCode === 8) {
      if (!this.inputValue) {
        this.options.selectivity
          .remove(this.options.selectivity.active[this.options.selectivity.active.length - 1]);
      }
    }

    // left
    if (!isUpMode && e.keyCode === 37 && this.items.length > 0) {
      this.behavior.first();
      // resultsEl.scrollTop = 0;

      e.preventDefault();
      return;
    }

    // right
    if (!isUpMode && e.keyCode === 39 && this.items.length > 0) {
      this.behavior.last();
      // resultsEl.scrollTop = resultsEl.scrollHeight;

      e.preventDefault();
      return;
    }

    // up
    if (!isUpMode && e.keyCode === 38) {
      let reverse = this.behavior.prev();

      /*let activeEl:any = resultsEl.getElementsByClassName('highlight');
       let activePosition = positionService.position(activeEl[0]);

       if (reverse) {
       resultsEl.scrollTop = resultsEl.scrollHeight;
       }

       if (!reverse && activePosition.top <= resultsEl.scrollTop) {
       resultsEl.scrollTop = activePosition.top - activePosition.height;
       }*/

      e.preventDefault();
      return;
    }

    // down
    if (!isUpMode && e.keyCode === 40) {
      let reverse = this.behavior.next();

      /*let activeEl:any = resultsEl.getElementsByClassName('highlight');
       let activePosition = positionService.position(activeEl[0]);

       if (reverse) {
       resultsEl.scrollTop = 0;
       }

       if (!reverse && activePosition.top > resultsPosition.height - activePosition.height) {
       resultsEl.scrollTop = activePosition.top + activePosition.height;
       }*/

      e.preventDefault();
      return;
    }

    // enter
    if (!isUpMode && e.keyCode === 13) {
      this.selectActiveMatch();
      e.preventDefault();
      return;
    }

    if (e.srcElement) {
      this.inputValue = e.srcElement.value;
      let query:RegExp = new RegExp(e.srcElement.value, 'ig');
      let {items, isActiveAvailable} = this.behavior.filter(query);
      this.items = items;

      if (this.items.length > 0 && !isActiveAvailable) {
        this.behavior.first();
      }
    }
  }

  private selectActiveMatch() {
    this.selectMatch(this.active);
  }

  private selectMatch(value:SelectivityItem, e:Event = null) {
    if (e) {
      e.stopPropagation();
      e.preventDefault();
    }

    if (this.options.selectivity.multiple === true) {
      if (this.items.length <= 0) {
        return;
      }

      this.options.selectivity.active.push(value);
      this.options.selectivity.data.next(this.options.selectivity.active);
      this.options.selectivity.doEvent('selected', value);
    }

    if (this.options.selectivity.multiple === false) {
      this.options.selectivity.active[0] = value;
      this.options.selectivity.data.next(this.options.selectivity.active[0]);
      this.options.selectivity.doEvent('selected', value);
      // turn back focus to input from options
      this.options.selectivity.element.nativeElement.children[1].children[0].focus();
    }

    // clear user input after option selection from list
    if (this.inputComponent) {
      this.inputComponent.value = '';
    }

    this.options.container.hide();
    this.options.selectivity.hide();
  }

  private selectActive(value:SelectivityItem) {
    this.active = value;
  }

  private isActive(value:SelectivityItem):boolean {
    return this.active.text === value.text;
  }
}

export module SelectivityOptionsContainer {

  function getIndex(a:Array<SelectivityItem>, v:SelectivityItem):number {
    for (let i = 0; i < a.length; i++) {
      if (a[i].id === v.id) {
        return i;
      }
    }

    return -1;
  }

  export class GenericBehavior implements IOptionsBehavior {
    constructor(private actor:SelectivityOptionsContainer) {
    }

    public first() {
      this.actor.active = this.actor.items[0];
    }

    public last() {
      this.actor.active = this.actor.items[this.actor.items.length - 1];
    }

    public prev():boolean {
      let index = this.actor.items.indexOf(this.actor.active);
      let reverse = index - 1 < 0;
      this.actor.active = this.actor.items[reverse ? this.actor.items.length - 1 : index - 1];
      return reverse;
    }

    public next() {
      let index = this.actor.items.indexOf(this.actor.active);
      let reverse = index + 1 > this.actor.items.length - 1;
      this.actor.active = this.actor.items[reverse ? 0 : index + 1];
      return reverse;
    }

    public filter(query:RegExp):any {
      let items:Array<SelectivityItem> = this.actor.options.container.getItemObjects()
        .filter((option:SelectivityItem) => query.test(option.text) &&
        (this.actor.options.selectivity.multiple === false ||
        (this.actor.options.selectivity.multiple === true &&
        this.actor.options.selectivity.active.indexOf(option) < 0)));
      let isActiveAvailable = getIndex(items, this.actor.active);
      return {items, isActiveAvailable};
    }
  }

  export class ChildrenBehavior implements IOptionsBehavior {
    constructor(private actor:SelectivityOptionsContainer) {
    }

    public first() {
      this.actor.active = this.actor.items[0].children[0];
    }

    public last() {
      this.actor.active =
        this.actor
          .items[this.actor.items.length - 1]
          .children[this.actor.items[this.actor.items.length - 1].children.length - 1];
    }

    public prev():boolean {
      let reverse = false;
      let indexParent = getIndex(this.actor.items, this.actor.active.parent);
      let index = getIndex(this.actor.items[indexParent].children, this.actor.active);
      this.actor.active = this.actor.items[indexParent].children[index - 1];

      if (!this.actor.active) {
        if (this.actor.items[indexParent - 1]) {
          this.actor.active = this.actor
            .items[indexParent - 1]
            .children[this.actor.items[indexParent - 1].children.length - 1];
        }
      }

      if (!this.actor.active) {
        this.last();
        reverse = true;
      }

      return reverse;
    }

    public next():boolean {
      let reverse = false;
      let indexParent = getIndex(this.actor.items, this.actor.active.parent);
      let index = getIndex(this.actor.items[indexParent].children, this.actor.active);
      this.actor.active = this.actor.items[indexParent].children[index + 1];

      if (!this.actor.active) {
        if (this.actor.items[indexParent + 1]) {
          this.actor.active = this.actor.items[indexParent + 1].children[0];
        }
      }

      if (!this.actor.active) {
        this.first();
        reverse = true;
      }

      return reverse;
    }

    public filter(query:RegExp):any {
      let items:Array<SelectivityItem> = [];
      let isActiveAvailable = false;

      for (let si of this.actor.options.container.getItemObjects()) {
        let children:Array<SelectivityItem> = si.children.filter(option => query.test(option.text));

        if (children.length > 0) {

          if (getIndex(children, this.actor.active) >= 0) {
            isActiveAvailable = true;
          }

          let newSi = si.getSimilar();
          newSi.children = children;
          items.push(newSi);
        }
      }

      return {items, isActiveAvailable};
    }
  }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Cache Sample </title>
    <link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/css/app.css"/>

New Event

                Key:
                <input id="keyEntry" class="form-control" type="text" ng-model="key"/>

                Value:
                <input id="valueEntry" class="form-control" type="text" ng-model="value"/>

                <button type="button" class="btn btn-sm btn-info" ng-click="addToCache(key, value)">Add To Cache</button>

                Search by Key:
                <input id="keyInput" class="form-control" type="text" ng-model="keyToRead"/>

Value from Cache: {{ readFromCache(keyToRead) }}

Cache Statistics: {{ getCacheStats() }}


text:
// ---------------- JSPLUMB ----------------------------------------

/**
 * Class: jsPlumb
 * The jsPlumb engine, registered as a static object in the window.  This object contains all of the methods you will use to
 * create and maintain Connections and Endpoints.
 */

/*
		* Function: importDefaults
		* Imports all the given defaults into this instance of jsPlumb.
		*/

		/*
		* Function: restoreDefaults
		* Restores the default settings to "factory" values.
		*/

		/*
		 * Function: bind
		 * Bind to an event on jsPlumb.
		 *
		 * Parameters:
		 * 	event - the event to bind.  Available events on jsPlumb are:
		 *         - *jsPlumbConnection* 			: 	notification that a new Connection was established.  jsPlumb passes the new Connection to the callback.
		 *         - *jsPlumbConnectionDetached* 	: 	notification that a Connection was detached.  jsPlumb passes the detached Connection to the callback.
		 *         - *click*						:	notification that a Connection was clicked.  jsPlumb passes the Connection that was clicked to the callback.
		 *         - *dblclick*						:	notification that a Connection was double clicked.  jsPlumb passes the Connection that was double clicked to the callback.
		 *         - *endpointClick*				:	notification that an Endpoint was clicked.  jsPlumb passes the Endpoint that was clicked to the callback.
		 *         - *endpointDblClick*				:	notification that an Endpoint was double clicked.  jsPlumb passes the Endpoint that was double clicked to the callback.
		 *         - *beforeDrop*					: 	notification that a Connection is about to be dropped. Returning false from this method cancels the drop. jsPlumb passes { sourceId, targetId, scope, connection, dropEndpoint } to your callback. For more information, refer to the jsPlumb documentation.
		 *         - *beforeDetach*					: 	notification that a Connection is about to be detached. Returning false from this method cancels the detach. jsPlumb passes the Connection to your callback. For more information, refer to the jsPlumb documentation.
		 *		   - *connectionDrag* 				:   notification that an existing Connection is being dragged. jsPlumb passes the Connection to your callback function.
		 *         - *connectionDragEnd*            :   notification that the drag of an existing Connection has ended.  jsPlumb passes the Connection to your callback function.
		 *
		 *  callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
		 */

		/*
		 * Function: unbind
		 * Clears either all listeners, or listeners for some specific event.
		 *
		 * Parameters:
		 * 	event	-	optional. constrains the clear to just listeners for this event.
		 */

		/*
		* Function: addClass
		* Add class(es) to some element(s).
		*
		* Parameters:
		* 	el			-	element id, dom element, or selector representing the element(s) to add class(es) to.
		* 	clazz		-	string representing the class(es) to add. may contain multiple classes separated by spaces.
		*/

		/*
		* Function: removeClass
		* Remove class from some selement(s).
		*
		* Parameters:
		* 	el			-	element id, dom element, or selector representing the element(s) to remove a class from.
		* 	clazz		-	string representing the class to remove.
		*/

		/*
		* Function: hasClass
		* Checks if an element has some class.
		*
		* Parameters:
		* 	el			-	element id, dom element, or selector representing the element to test. If the selector matches multiple elements, we return the test for the first element in the selector only.
		* 	clazz		-	string representing the class to test for.
		*/
    /*
	 * Property: Anchors.TopCenter
	 * An Anchor that is located at the top center of the element.
	 */
	/*
	 * Property: Anchors.BottomCenter
	 * An Anchor that is located at the bottom center of the element.
	 */
	/*
	 * Property: Anchors.LeftMiddle
	 * An Anchor that is located at the left middle of the element.
	 */
	/*
	 * Property: Anchors.RightMiddle
	 * An Anchor that is located at the right middle of the element.
	 */
	/*
	 * Property: Anchors.Center
	 * An Anchor that is located at the center of the element.
	 */
	/*
	 * Property: Anchors.TopRight
	 * An Anchor that is located at the top right corner of the element.
	 */
	/*
	 * Property: Anchors.BottomRight
	 * An Anchor that is located at the bottom right corner of the element.
	 */
	/*
	 * Property: Anchors.TopLeft
	 * An Anchor that is located at the top left corner of the element.
	 */
	/*
	 * Property: Anchors.BottomLeft
	 * An Anchor that is located at the bototm left corner of the element.
	 */
	/*
	 * Property: Anchors.AutoDefault
	 * Default DynamicAnchors - chooses from TopCenter, RightMiddle, BottomCenter, LeftMiddle.
	 */
	/*
	 * Property: Anchors.Assign
	 * An Anchor whose location is assigned at connection time, through an AnchorPositionFinder. Used in conjunction
	 * with the 'makeTarget' function. jsPlumb has two of these - 'Fixed' and 'Grid', and you can also write your own.
	 */
	/*
	 * Property: Anchors.Continuous
	 * An Anchor that tracks the other element in the connection, choosing the closest face.
	 */
    /*
    * Property: Anchors.ContinuousLeft
    * A continuous anchor that uses only the left edge of the element.
    */
    /*
    * Property: Anchors.ContinuousTop
    * A continuous anchor that uses only the top edge of the element.
    */
    /*
    * Property: Anchors.ContinuousBottom
    * A continuous anchor that uses only the bottom edge of the element.
    */
    /*
    * Property: Anchors.ContinuousRight
    * A continuous anchor that uses only the right edge of the element.
    */
/*
	 * Property: Anchors.Perimeter
	 * An Anchor that tracks the perimeter of some shape, approximating it with a given number of dynamically
	 * positioned locations.
	 *
	 * Parameters:
	 *
	 * anchorCount  -   optional number of anchors to use to approximate the perimeter. default is 60.
	 * shape        -   required. the name of the shape. valid values are 'rectangle', 'square', 'ellipse', 'circle', 'triangle' and 'diamond'
	 * rotation     -   optional rotation, in degrees, to apply.
	 */

// ---------------- ENDPOINT -----------------------------------------------------

/*
 * Class: Endpoint
 *
 * Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
 * to allow unlimited).  Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
 * actually deal with the underlying Endpoint objects.  But if you wish to support drag and drop Connections, one of the ways you
 * do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
 * 'target' Endpoints for Connections.
 *
 *
 */
/*
 * Function: Endpoint
 *
 * Endpoint constructor.
 *
 * Parameters:
 * anchor - definition of the Anchor for the endpoint.  You can include one or more Anchor definitions here; if you include more than one, jsPlumb creates a 'dynamic' Anchor, ie. an Anchor which changes position relative to the other elements in a Connection.  Each Anchor definition can be either a string nominating one of the basic Anchors provided by jsPlumb (eg. "TopCenter"), or a four element array that designates the Anchor's location and orientation (eg, and this is equivalent to TopCenter, [ 0.5, 0, 0, -1 ]).  To provide more than one Anchor definition just put them all in an array. You can mix string definitions with array definitions.
 * endpoint - optional Endpoint definition. This takes the form of either a string nominating one of the basic Endpoints provided by jsPlumb (eg. "Rectangle"), or an array containing [name,params] for those cases where you don't wish to use the default values, eg. [ "Rectangle", { width:5, height:10 } ].
 * enabled - optional, defaults to true. Indicates whether or not the Endpoint should be enabled for mouse events (drag/drop).
 * paintStyle - endpoint style, a js object. may be null.
 * hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
 * cssClass - optional CSS class to set on the display element associated with this Endpoint.
 * hoverClass - optional CSS class to set on the display element associated with this Endpoint when it is in hover state.
 * source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
 * canvas - canvas element to use. may be, and most often is, null.
 * container - optional id or selector instructing jsPlumb where to attach the element it creates for this endpoint.  you should read the documentation for a full discussion of this.
 * connections - optional list of Connections to configure the Endpoint with.
 * isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
 * maxConnections - integer; defaults to 1.  a value of -1 means no upper limit.
 * dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
 * connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
 * connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
 * connector - optional Connector type to use.  Like 'endpoint', this may be either a single string nominating a known Connector type (eg. "Bezier", "Straight"), or an array containing [name, params], eg. [ "Bezier", { curviness:160 } ].
 * connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
 * connectorClass - optional CSS class to set on Connections emanating from this Endpoint.
 * connectorHoverClass - optional CSS class to set on to set on Connections emanating from this Endpoint when they are in hover state.
 * connectionsDetachable - optional, defaults to true. Sets whether connections to/from this Endpoint should be detachable or not.
 * isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
 * dropOptions - if isTarget is set to true, you can supply arguments for the underlying library's drop method with this parameter. Optional; defaults to null.
 * reattach - optional boolean that determines whether or not the Connections reattach after they have been dragged off an Endpoint and left floating. defaults to false: Connections dropped in this way will just be deleted.
 * parameters - Optional JS object containing parameters to set on the Endpoint. These parameters are then available via the getParameter method.  When a connection is made involving this Endpoint, the parameters from this Endpoint are copied into that Connection. Source Endpoint parameters override target Endpoint parameters if they both have a parameter with the same name.
 * connector-pointer-events - Optional. a value for the 'pointer-events' property of any SVG elements that are created to render connections from this endoint.
 */

/*
 * Function: addConnection
 *   Adds a Connection to this Endpoint.
 *
 * Parameters:
 *   connection - the Connection to add.
 */
/*
 * Function: detach
 *   Detaches the given Connection from this Endpoint.
 *
 * Parameters:
 *   connection - the Connection to detach.
 *   ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached.  The default behaviour is to notify the target.
 */
/*
         * Function: detachAll
         *   Detaches all Connections this Endpoint has.
         *
         * Parameters:
         *  fireEvent   -   whether or not to fire the detach event.  defaults to false.
         */
        /*
         * Function: detachFrom
         *   Removes any connections from this Endpoint that are connected to the given target endpoint.
         *
         * Parameters:
         *   targetEndpoint     - Endpoint from which to detach all Connections from this Endpoint.
         *   fireEvent          - whether or not to fire the detach event. defaults to false.
         */
        /*
         * Function: detachFromConnection
         *   Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
         *
         * Parameters:
         *   connection - Connection to detach from.
         */
        /*
         * Function: getElement
         *
         * Returns:
         * 	The DOM element this Endpoint is attached to.
         */
        /*
         * Function: setElement
         * Sets the DOM element this Endpoint is attached to.
         *
         * Parameters:
         * 	el	-	dom element or selector
         * 	container	-	optional, specifies the actual parent element to use as the parent for this Endpoint's visual representation.
         * 	See the jsPlumb documentation for a discussion about this.
         */
        /*
         * Function: getUuid
         *   Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
         */
        /*
         * Function: isConnectedTo
         *   Returns whether or not this endpoint is connected to the given Endpoint.
         *
         * Parameters:
         *   endpoint - Endpoint to test.
         */
        /*
         * Function: isFull
         *   Returns whether or not the Endpoint can accept any more Connections.
         */
        /*
         * Function: setDragAllowedWhenFull
         *   Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
         *   which you're going to provide some other way of breaking connections, if you need to break them at all. This property
         *   is by default true; use it in conjunction with the 'reattach' option on a connect call.
         *
         * Parameters:
         *   allowed - whether drag is allowed or not when the Endpoint is full.
         */
        /*
         * Function: setStyle
         *   Sets the paint style of the Endpoint.  This is a JS object of the same form you supply to a jsPlumb.addEndpoint or jsPlumb.connect call.
         *   TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
         *   setStyle and deprecate it if so.
         *
         * Parameters:
         *   style - Style object to set, for example {fillStyle:"blue"}.
         *
         *  @deprecated use setPaintStyle instead.
         */
        /*
         * Function: paint
         *   Paints the Endpoint, recalculating offset and anchor positions if necessary. This does NOT paint
         *   any of the Endpoint's connections.
         *
         * Parameters:
         *   timestamp - optional timestamp advising the Endpoint of the current paint time; if it has painted already once for this timestamp, it will not paint again.
         *   canvas - optional Canvas to paint on.  Only used internally by jsPlumb in certain obscure situations.
         *   connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
         */
        /*
         * Function: bind
         * Bind to an event on the Endpoint.
         *
         * Parameters:
         * 	event - the event to bind.  Available events on an Endpoint are:
         *         - *click*						:	notification that a Endpoint was clicked.
         *         - *dblclick*						:	notification that a Endpoint was double clicked.
         *         - *mouseenter*					:	notification that the mouse is over a Endpoint.
         *         - *mouseexit*					:	notification that the mouse exited a Endpoint.
         * 		   - *contextmenu*                  :   notification that the user right-clicked on the Endpoint.
         *
         *  callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
         */

         /*
            Function: setEnabled
            Sets whether or not the Endpoint is enabled for drag/drop connections.

            Parameters:
                enabled - whether or not the Endpoint is enabled.
        */

        /*
            Function: isEnabled
            Returns whether or not the Endpoint is enabled for drag/drop connections.
        */

        /*
         * Function: setPaintStyle
         * Sets the Endpoint's paint style and then repaints the Endpoint.
         *
         * Parameters:
         * 	style - Style to use.
         */

         /*
         * Function: getPaintStyle
         * Gets the Endpoint's paint style. This is not necessarily the paint style in use at the time;
         * this is the paint style for the Endpoint when the mouse it not hovering over it.
         */

        /*
         * Function: setHoverPaintStyle
         * Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
         * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
         * it.  This is because people will most likely want to change just one thing when hovering, say the
         * color for example, but leave the rest of the appearance the same.
         *
         * Parameters:
         * 	style - Style to use when the mouse is hovering.
         *  doNotRepaint - if true, the Endpoint will not be repainted.  useful when setting things up initially.
         */

        /*
         * Function: setHover
         * Sets/unsets the hover state of this Endpoint.
         *
         * Parameters:
         * 	hover - hover state boolean
         * 	ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state.  used mostly to avoid infinite loops.
         */

         /*
         * Function: getParameter
         * Gets the named parameter; returns null if no parameter with that name is set. Parameters may have been set on the Endpoint in the 'addEndpoint' call, or they may have been set with the setParameter function.
         *
         * Parameters:
         *   key - Parameter name.
         */

         /*
         * Function: setParameter
         * Sets the named parameter to the given value.
         *
         * Parameters:
         *   key - Parameter name.
         *   value - Parameter value.
         */

         /*
         * Property: canvas
         * The Endpoint's drawing area.
         */
        /*
         * Property: connections
         * List of Connections this Endpoint is attached to.
         */
        /*
         * Property: scope
         * Scope descriptor for this Endpoint.
         */

        /*
         * Property: overlays
         * List of Overlays for this Endpoint.
         */
        /*
         * Function: addOverlay
         * Adds an Overlay to the Endpoint.
         *
         * Parameters:
         * 	overlay - Overlay to add.
         */
        /*
         * Function: getOverlay
         * Gets an overlay, by ID. Note: by ID.  You would pass an 'id' parameter
         * in to the Overlay's constructor arguments, and then use that to retrieve
         * it via this method.
         */
        /*
        * Function: getOverlays
        * Gets all the overlays for this component.
        */
        /*
         * Function: hideOverlay
         * Hides the overlay specified by the given id.
         */
        /*
         * Function: hideOverlays
         * Hides all Overlays
         */
        /*
         * Function: showOverlay
         * Shows the overlay specified by the given id.
         */
        /*
         * Function: showOverlays
         * Shows all Overlays
         */
        /*
         * Function: removeAllOverlays
         * Removes all overlays from the Endpoint, and then repaints.
         */
        /*
         * Function: removeOverlay
         * Removes an overlay by ID.  Note: by ID.  this is a string you set in the overlay spec.
         * Parameters:
         * overlayId - id of the overlay to remove.
         */
        /*
         * Function: removeOverlays
         * Removes a set of overlays by ID.  Note: by ID.  this is a string you set in the overlay spec.
         * Parameters:
         * overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
         */
        /*
         * Function: setLabel
         * Sets the Endpoint's label.
         *
         * Parameters:
         * 	l	- label to set. May be a String, a Function that returns a String, or a params object containing { "label", "labelStyle", "location", "cssClass" }.  Note that this uses innerHTML on the label div, so keep
         * that in mind if you need escaped HTML.
         */
        /*
            Function: getLabel
            Returns the label text for this Endpoint (or a function if you are labelling with a function).
            This does not return the overlay itself; this is a convenience method which is a pair with
            setLabel; together they allow you to add and access a Label Overlay without having to create the
            Overlay object itself.  For access to the underlying label overlay that jsPlumb has created,
            use getLabelOverlay.
        */
        /*
            Function: getLabelOverlay
            Returns the underlying internal label overlay, which will exist if you specified a label on
            an addEndpoint call, or have called setLabel at any stage.
        */
/*
            Function: isVisible
            Returns whether or not the Endpoint is currently visible.
        */
        /*
            Function: setVisible
            Sets whether or not the Endpoint is currently visible.

            Parameters:
                visible - whether or not the Endpoint should be visible.
                doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
                doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
        */

        /*
        	Function: setAnchor
        	Sets the Endpoint's anchor. This takes an anchor in any supported form in a jsPlumb.connect
        	or jsPlumb.addEndpoint call.

        	Parameters:
        		anchorParams - anchor spec
        		doNotRepaint - optional, defaults to false.
        */

// ---------------- / ENDPOINT -----------------------------------------------------

// --------------- CONNECTION ----------------------

    /*
     * Class: Connection
     * The connecting line between two Endpoints.
     */
    /*
     * Function: Connection
     * Connection constructor. You should not ever create one of these directly. If you make a call to jsPlumb.connect, all of
     * the parameters that you pass in to that function will be passed to the Connection constructor; if your UI
     * uses the various Endpoint-centric methods like addEndpoint/makeSource/makeTarget, along with drag and drop,
     * then the parameters you set on those functions are translated and passed in to the Connection constructor. So
     * you should check the documentation for each of those methods.
     *
     * Parameters:
     * 	source 	- either an element id, a selector for an element, or an Endpoint.
     * 	target	- either an element id, a selector for an element, or an Endpoint
     * 	scope	- scope descriptor for this connection. optional.
     *  container - optional id or selector instructing jsPlumb where to attach all the elements it creates for this connection.  you should read the documentation for a full discussion of this.
     *  detachable - optional, defaults to true. Defines whether or not the connection may be detached using the mouse.
     *  reattach	- optional, defaults to false. Defines whether not the connection should be retached if it was dragged off an Endpoint and then dropped in whitespace.
     *  endpoint - Optional. Endpoint definition to use for both ends of the connection.
     *  endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
     *  endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
     *  endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
     *  paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
     *  hoverPaintStyle - Parameters defining the appearance of the Connection when the mouse is hovering over it. Optional; jsPlumb will use the defaults if you supply nothing here (note that the default hoverPaintStyle is null).
     *  cssClass - optional CSS class to set on the display element associated with this Connection.
     *  hoverClass - optional CSS class to set on the display element associated with this Connection when it is in hover state.
     *  overlays - Optional array of Overlay definitions to appear on this Connection.
     *  drawEndpoints - if false, instructs jsPlumb to not draw the endpoints for this Connection.  Be careful with this: it only really works when you tell jsPlumb to attach elements to the document body. Read the documentation for a full discussion of this.
     *  parameters - Optional JS object containing parameters to set on the Connection. These parameters are then available via the getParameter method.
     */

/*
         * Function: bind
         * Bind to an event on the Connection.
         *
         * Parameters:
         * 	event - the event to bind.  Available events on a Connection are:
         *         - *click*						:	notification that a Connection was clicked.
         *         - *dblclick*						:	notification that a Connection was double clicked.
         *         - *mouseenter*					:	notification that the mouse is over a Connection.
         *         - *mouseexit*					:	notification that the mouse exited a Connection.
         * 		   - *contextmenu*                  :   notification that the user right-clicked on the Connection.
         *
         *  callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
         */

        /*
         * Function: setPaintStyle
         * Sets the Connection's paint style and then repaints the Connection.
         *
         * Parameters:
         * 	style - Style to use.
         */

         /*
         * Function: getPaintStyle
         * Gets the Connection's paint style. This is not necessarily the paint style in use at the time;
         * this is the paint style for the connection when the mouse it not hovering over it.
         */

        /*
         * Function: setHoverPaintStyle
         * Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
         * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
         * it.  This is because people will most likely want to change just one thing when hovering, say the
         * color for example, but leave the rest of the appearance the same.
         *
         * Parameters:
         * 	style - Style to use when the mouse is hovering.
         *  doNotRepaint - if true, the Connection will not be repainted.  useful when setting things up initially.
         */

        /*
         * Function: setHover
         * Sets/unsets the hover state of this Connection.
         *
         * Parameters:
         * 	hover - hover state boolean
         * 	ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state.  used mostly to avoid infinite loops.
         */

         /*
         * Function: getParameter
         * Gets the named parameter; returns null if no parameter with that name is set. Parameter values may have been supplied to a 'connect' or 'addEndpoint' call (connections made with the mouse get a copy of all parameters set on each of their Endpoints), or the parameter value may have been set with setParameter.
         *
         * Parameters:
         *   key - Parameter name.
         */

         /*
         * Function: setParameter
         * Sets the named parameter to the given value.
         *
         * Parameters:
         *   key - Parameter name.
         *   value - Parameter value.
         */

         /*
         * Property: connector
         * The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
         */

         /*
         * Property: sourceId
         * Id of the source element in the connection.
         */
        /*
         * Property: targetId
         * Id of the target element in the connection.
         */
        /*
         * Property: scope
         * Optional scope descriptor for the connection.
         */
        /*
         * Property: endpoints
         * Array of [source, target] Endpoint objects.
         */
        /*
         *	Property: source
         *	The source element for this Connection.
         */
        /*
         *	Property: target
         *	The target element for this Connection.
         */
        /*
         * Property: overlays
         * List of Overlays for this component.
         */
        /*
         * Function: addOverlay
         * Adds an Overlay to the Connection.
         *
         * Parameters:
         * 	overlay - Overlay to add.
         */
        /*
         * Function: getOverlay
         * Gets an overlay, by ID. Note: by ID.  You would pass an 'id' parameter
         * in to the Overlay's constructor arguments, and then use that to retrieve
         * it via this method.
         *
         * Parameters:
         * 	overlayId 	-	id of the overlay to retrieve.
         */
        /*
         * Function: getOverlays
         * Gets all the overlays for this component.
         */
        /*
         * Function: hideOverlay
         * Hides the overlay specified by the given id.
         *
         * Parameters:
         * 	overlayId 	-	id of the overlay to hide.
         */
        /*
         * Function: hideOverlays
         * Hides all Overlays
         */
        /*
         * Function: showOverlay
         * Shows the overlay specified by the given id.
         *
         * Parameters:
         * 	overlayId 	-	id of the overlay to show.
         */
        /*
         * Function: showOverlays
         * Shows all Overlays
         */
        /*
         * Function: removeAllOverlays
         * Removes all overlays from the Connection, and then repaints.
         */
        /*
         * Function: removeOverlay
         * Removes an overlay by ID.  Note: by ID.  this is a string you set in the overlay spec.
         *
         * Parameters:
         * 	overlayId - id of the overlay to remove.
         */
        /*
         * Function: removeOverlays
         * Removes a set of overlays by ID.  Note: by ID.  this is a string you set in the overlay spec.
         *
         * Parameters:
         * 	overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
         */
        /*
         * Function: setLabel
         * Sets the Connection's label.
         *
         * Parameters:
         * 	l	- label to set. May be a String, a Function that returns a String, or a params object containing { "label", "labelStyle", "location", "cssClass" }.  Note that this uses innerHTML on the label div, so keep
         * that in mind if you need escaped HTML.
         */
        /*
        * Function: getLabel
        * Returns the label text for this Connection (or a function if you are labelling with a function).
        *
        * This does not return the overlay itself; this is a convenience method which is a pair with
        * setLabel; together they allow you to add and access a Label Overlay without having to create the
        * Overlay object itself.  For access to the underlying label overlay that jsPlumb has created,
        * use getLabelOverlay.
        *
        * See Also:
        * 	<getOverlay>
        */
        /*
        * Function: getLabelOverlay
        * Returns the underlying internal label overlay, which will exist if you specified a label on
        * a connect call, or have called setLabel at any stage.
        */

    /*
        * Function: isVisible
        * Returns whether or not the Connection is currently visible.
        */
        /*
        * Function: setVisible
        * Sets whether or not the Connection should be visible.
        *
        * Parameters:
        *	visible - boolean indicating desired visible state.
        */
    /**
        * Function: setEditable
        * Sets whether or not the Connection is editable. This will only be honoured if
        * the underlying Connector is editable - not all types are.
        */
        /**
        * Function: isEditable
        * Returns whether or not the Connection is editable.
        */
    /*
         * Function: setConnector
         * Sets the Connection's connector (eg "Bezier", "Flowchart", etc).  You pass a Connector definition into this method, the same
         * thing that you would set as the 'connector' property on a jsPlumb.connect call.
         *
         * Parameters:
         * 	connector		-	Connector definition
         */
    /*
        * Function: isDetachable
        * Returns whether or not this connection can be detached from its target/source endpoint.  by default this
        * is false; use it in conjunction with the 'reattach' parameter.
        */
        /*
        * Function: setDetachable
        * Sets whether or not this connection is detachable.
        *
        * Parameters:
        * 	detachable - whether or not to set the Connection to be detachable.
        */
    /*
        * Function: isReattach
        * Returns whether or not this connection will be reattached after having been detached via the mouse and dropped.  by default this
        * is false; use it in conjunction with the 'detachable' parameter.
        */
        /*
        * Function: setReattach
        * Sets whether or not this connection will reattach after having been detached via the mouse and dropped.
        *
        * Parameters:
        * 	reattach	-	whether or not to set the Connection to reattach after drop in whitespace.
        */
        /**
         * implementation of abstract method in jsPlumbUtil.EventGenerator
         * @return list of attached elements. in our case, a list of Endpoints.
         */