text:
Imports DevDefined.OAuth.Storage.Basic
Imports DevDefined.OAuth.Logging
Imports DevDefined.OAuth.Consumer
Imports XeroApi.OAuth
Imports DevDefined.OAuth.Framework

Public Class PublicApplicationRunner

    Const UserAgent As String = "Xero.API.ScreenCast v1.0 (Public App Testing)"
    Const ConsumerKey As String = "ZGIXM2M1Y2RIZJGYNGY1Y2EWZGYZMW"
    Const ConsumerSecret As String = "RZRCMBRPK57EAG6GRO4GPLYDH9REPX"

    Public Shared Function CreateRepository() As Repository

        Dim consumerSession As IOAuthSession = New XeroApiPublicSession(UserAgent, ConsumerKey, ConsumerSecret, New InMemoryTokenRepository())

        consumerSession.MessageLogger = New DebugMessageLogger()

        ' 1. Get a request token
        Dim requestToken As RequestToken = consumerSession.GetRequestToken()

        Console.WriteLine("Request Token Key: {0}", requestToken.Token)
        Console.WriteLine("Request Token Secret: {0}", requestToken.TokenSecret)

        ' 2. Get the user to log into Xero using the request token in the querystring
        Dim authorisationUrl As String = consumerSession.GetUserAuthorizationUrl()
        Process.Start(authorisationUrl)

        ' 3. Get the use to enter the authorisation code from Xero (4-7 digit number)
        Console.WriteLine("Please input the code you were given in Xero:")
        Dim verificationCode As String = Console.ReadLine()

        If (String.IsNullOrEmpty(verificationCode)) Then

            Console.WriteLine("You didn't type a verification code!")
            Return Nothing

        End If

        ' 4. Use the request token and verification code to get an access token
        Dim accessToken As AccessToken

        Try
            accessToken = consumerSession.ExchangeRequestTokenForAccessToken(verificationCode.Trim())

        Catch ex As OAuthException

            Console.WriteLine("An OAuthException was caught:")
            Console.WriteLine(ex.Report)
            Return Nothing

        End Try

        Console.WriteLine("Access Token Key: {0}", accessToken.Token)
        Console.WriteLine("Access Token Secret: {0}", accessToken.TokenSecret)
        Console.WriteLine("Access Token Lasts for: {0}", accessToken.TokenTimespan)

        ' Wrap the authenticated consumerSession in the repository...
        Return New Repository(consumerSession)

    End Function

End Class


text:
layout: docs
title: "Row Extraction"
section: "c21"
---
```tut:invisible
import com.datastax.driver.core.{Cluster, Session}
import com.weather.scalacass.ScalaSession
import com.datastax.driver.core.Row
import com.weather.scalacass.scsession.SCStatement.RightBiasedEither

implicit val cluster = Cluster.builder.addContactPoint("localhost").build()
implicit val session: Session = cluster.connect()

val sSession: ScalaSession = ScalaSession("mykeyspace")
sSession.createKeyspace("replication = {'class':'SimpleStrategy', 'replication_factor' : 1}").execute()

case class MyTable(s: String, i: Int, l: List[Long])
val createStatement = sSession.createTable[MyTable]("mytable", 1, 0)
createStatement.execute()

val insertStatement = sSession.insert("mytable", MyTable("a str", 1234, List(5678L)))
insertStatement.execute()
```
# Row Extraction

Cassandra's `Row` holds the response from a statement. Using the driver, conversion into a useful Scala data type is
cumbersome both in extracting a value from the Row, and converting it from the Java type. Scala-Cass handles all of that
under the hood.

As an example, start with a `Row` retrieved from Cassandra table. Let's say this table has a definition of

```tut
case class MyRow(s: String, i: Int, l: List[Long]) // s varchar, i int, l bigint
```
Then we select a row using a `ScalaSession` (see more of `select` [here](/cass3/scalasession/select.html))

```tut
case class Select(s: String)
val rowRes = sSession.selectOneStar("mytable", Select("a str")).execute()
val row: Row = rowRes.toOption.flatten.get
```

First, let's extract into `MyRow` using the regular driver

```tut
import scala.collection.JavaConverters._
val driverDerivedRow = MyRow(row.getString("s"), row.getInt("i"), row.getList("l", classOf[java.lang.Long]).asScala.toList.map(Long.unbox))
```

Especially for the `List[Long]`, it is unnecessarily verbose, since we already have the necessary type information. In
addition, we don't know if any of these values came back as `null`, so in truth, we would need null checks as well

We can hide all of this boilerplate using the ScalaCass library. First, we need to import the syntax,
`com.weather.scalacass.syntax`. Then let's mirror that extraction from above

```tut
import com.weather.scalacass.syntax._
val scalaCassDerivedRow = MyRow(row.as[String]("s"), row.as[Int]("i"), row.as[List[Long]]("l"))
```

All we need to specify is the type that we
want[*](#type-mappings), and the library handles the rest.
If one of these values came back null, the driver will throw an exception since we do not want to introduce null values
into our code.

If you do need to handle null types, use the `Option` type to extract values, as this will return `None` instead of
null

```tut
row.as[Option[String]]("s")
```

There are 2 convenience functions around this, `getAs` and `getOrElse`, that retrieves an Optional response of the type,
and, in the case of `getOrElse`, provides a default in the case it gets back a `None`

```tut:invisible
case class DeleteColumn(i: Int)
sSession.delete[DeleteColumn]("mytable", Select("a str")).execute()
```
```tut
row.getAs[Int]("i")
row.getOrElse[Int]("i", -12345)
```
```tut:invisible
insertStatement.execute()
```

If you want to handle the exception yourself, there is a way to simply attempt the extraction and return either the
success or the failure

```tut
row.attemptAs[Int]("i")
```

## Case Classes

We already have a conveniently defined `MyRow` with all of the type information we want, so the Scala-Cass library (with
the help of the [Shapeless library](https://github.com/milessabin/shapeless)) can automatically use the case class
directly for extraction

```tut
row.as[MyRow]
row.getAs[MyRow]
row.getOrElse[MyRow](MyRow("default row", -12345, List(-5678L)))
row.attemptAs[MyRow]
```

Note that no arguments (aside from the type parameter) are passed when extracting to a case class because you are acting
 on the entire row.

##### For performance characteristics of these extractions, [see the performance page](/cass3/performance.html)

##### For a full list of type mappings between the Cassandra types and Scala types, [see the type mappings page](/cass3/type-mappings.html)
```tut:invisible
sSession.dropKeyspace.execute()
sSession.close()
cluster.close()
```

redpajama_set_name: RedPajamaGithub


text:
describe Gnc::DataSource do
  subject { Gnc::DataSource }

  describe ".fetch" do
    subject { Gnc::DataSource.fetch }
    it "returns data source information from GN resolver" do
      expect(subject).to be_kind_of Array
    end

    it "sorts results by title" do
      sorted_titles = subject.map(&:title).sort
      expect(subject.map(&:title)).to eq sorted_titles
    end
  end

  describe ".find" do
    it "returns data source by id" do
      expect(subject.find(1)).to be_kind_of OpenStruct
    end
  end
end


text:
module DPLA::MAP
  module Controlled
    class Language < DPLA::MAP::Concept
      configure :base_uri => "http://lexvo.org/id/iso639-3/",
                :rdf_label => RDF::SKOS.prefLabel,
                :type => RDF::DC.LinguisticSystem
    end
  end
end


text:
package com.atlassian.maven.plugins.jira;

import com.atlassian.maven.plugins.amps.PluginInformation;
import org.apache.maven.plugin.MojoExecutionException;
import org.jfrog.maven.annomojo.annotations.MojoGoal;
import org.jfrog.maven.annomojo.annotations.MojoRequiresProject;

@MojoGoal ("create_v4")
@MojoRequiresProject (false)
public class JiraCreateV4Mojo extends JiraCreateMojo
{
    private static final String JIRA4 = "jira4";

    @Override
    protected String getDefaultProductId() throws MojoExecutionException
    {
        return JIRA4;
    }

    @Override
    protected PluginInformation getPluginInformation()
    {
        return new PluginInformation(JIRA4, super.getPluginInformation().getVersion());
    }
}


text:
<component name="libraryTable">
  <library name="library-1.1.2">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.timqi.collapsibletextview/library/1.1.2/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.timqi.collapsibletextview/library/1.1.2/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://D:/Program Files/Android/gradl/.gradle/caches/modules-2/files-2.1/com.timqi.collapsibletextview/library/1.1.2/de5c55398f534f547a14ce097e9cb183ade9dbb1/library-1.1.2-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
namespace XenAdmin.TabPages
{
    partial class VMStoragePage
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            // Deregister listeners.
            VM = null;

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VMStoragePage));
            this.AddButton = new System.Windows.Forms.Button();
            this.EditButton = new System.Windows.Forms.Button();
            this.AttachButton = new System.Windows.Forms.Button();
            this.RightButtonSeparator = new System.Windows.Forms.Panel();
            this.LeftButtonSeparator = new System.Windows.Forms.Panel();
            this.panel1 = new System.Windows.Forms.Panel();
            this.panel2 = new System.Windows.Forms.Panel();
            this.dataGridViewStorage = new System.Windows.Forms.DataGridView();
            this.ColumnDevicePosition = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnSR = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnSRVolume = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnReadOnly = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnPriority = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnActive = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnDevicePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
            this.DeactivateButtonContainer = new XenAdmin.Controls.ToolTipContainer();
            this.DeactivateButton = new System.Windows.Forms.Button();
            this.MoveButtonContainer = new XenAdmin.Controls.ToolTipContainer();
            this.MoveButton = new System.Windows.Forms.Button();
            this.DeleteButtonContainer = new XenAdmin.Controls.ToolTipContainer();
            this.DeleteDriveButton = new System.Windows.Forms.Button();
            this.DetachButtonContainer = new XenAdmin.Controls.ToolTipContainer();
            this.DetachDriveButton = new System.Windows.Forms.Button();
            this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList();
            this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.gradientPanel1 = new XenAdmin.Controls.GradientPanel.GradientPanel();
            this.TitleLabel = new System.Windows.Forms.Label();
            this.panel1.SuspendLayout();
            this.panel2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).BeginInit();
            this.flowLayoutPanel1.SuspendLayout();
            this.DeactivateButtonContainer.SuspendLayout();
            this.MoveButtonContainer.SuspendLayout();
            this.DeleteButtonContainer.SuspendLayout();
            this.DetachButtonContainer.SuspendLayout();
            this.gradientPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // AddButton
            //
            resources.ApplyResources(this.AddButton, "AddButton");
            this.AddButton.Name = "AddButton";
            this.AddButton.UseVisualStyleBackColor = true;
            this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
            //
            // EditButton
            //
            resources.ApplyResources(this.EditButton, "EditButton");
            this.EditButton.Name = "EditButton";
            this.EditButton.UseVisualStyleBackColor = true;
            this.EditButton.Click += new System.EventHandler(this.EditButton_Click);
            //
            // AttachButton
            //
            resources.ApplyResources(this.AttachButton, "AttachButton");
            this.AttachButton.Name = "AttachButton";
            this.AttachButton.UseVisualStyleBackColor = true;
            this.AttachButton.Click += new System.EventHandler(this.AttachButton_Click);
            //
            // RightButtonSeparator
            //
            this.RightButtonSeparator.BackColor = System.Drawing.SystemColors.ControlDarkDark;
            resources.ApplyResources(this.RightButtonSeparator, "RightButtonSeparator");
            this.RightButtonSeparator.Name = "RightButtonSeparator";
            //
            // LeftButtonSeparator
            //
            this.LeftButtonSeparator.BackColor = System.Drawing.SystemColors.ControlDarkDark;
            resources.ApplyResources(this.LeftButtonSeparator, "LeftButtonSeparator");
            this.LeftButtonSeparator.Name = "LeftButtonSeparator";
            //
            // panel1
            //
            this.panel1.Controls.Add(this.panel2);
            this.panel1.Controls.Add(this.multipleDvdIsoList1);
            resources.ApplyResources(this.panel1, "panel1");
            this.panel1.Name = "panel1";
            //
            // panel2
            //
            resources.ApplyResources(this.panel2, "panel2");
            this.panel2.Controls.Add(this.dataGridViewStorage);
            this.panel2.Controls.Add(this.flowLayoutPanel1);
            this.panel2.MaximumSize = new System.Drawing.Size(900, 400);
            this.panel2.Name = "panel2";
            //
            // dataGridViewStorage
            //
            this.dataGridViewStorage.AllowUserToAddRows = false;
            this.dataGridViewStorage.AllowUserToDeleteRows = false;
            this.dataGridViewStorage.AllowUserToResizeRows = false;
            this.dataGridViewStorage.BackgroundColor = System.Drawing.SystemColors.Window;
            this.dataGridViewStorage.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
            this.dataGridViewStorage.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dataGridViewStorage.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.ColumnDevicePosition,
            this.ColumnName,
            this.ColumnDesc,
            this.ColumnSR,
            this.ColumnSRVolume,
            this.ColumnSize,
            this.ColumnReadOnly,
            this.ColumnPriority,
            this.ColumnActive,
            this.ColumnDevicePath});
            resources.ApplyResources(this.dataGridViewStorage, "dataGridViewStorage");
            this.dataGridViewStorage.Name = "dataGridViewStorage";
            this.dataGridViewStorage.ReadOnly = true;
            this.dataGridViewStorage.RowHeadersVisible = false;
            this.dataGridViewStorage.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dataGridViewStorage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.TheHeaderListBox_DataGridView_MouseUp);
            this.dataGridViewStorage.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.TheHeaderListBox_CellMouseDoubleClick);
            this.dataGridViewStorage.SelectionChanged += new System.EventHandler(this.TheHeaderListBox_SelectedIndexChanged);
            //
            // ColumnDevicePosition
            //
            this.ColumnDevicePosition.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnDevicePosition, "ColumnDevicePosition");
            this.ColumnDevicePosition.Name = "ColumnDevicePosition";
            this.ColumnDevicePosition.ReadOnly = true;
            //
            // ColumnName
            //
            this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnName, "ColumnName");
            this.ColumnName.Name = "ColumnName";
            this.ColumnName.ReadOnly = true;
            //
            // ColumnDesc
            //
            this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnDesc, "ColumnDesc");
            this.ColumnDesc.Name = "ColumnDesc";
            this.ColumnDesc.ReadOnly = true;
            //
            // ColumnSR
            //
            this.ColumnSR.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnSR, "ColumnSR");
            this.ColumnSR.Name = "ColumnSR";
            this.ColumnSR.ReadOnly = true;
            //
            // ColumnSRVolume
            //
            this.ColumnSRVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnSRVolume, "ColumnSRVolume");
            this.ColumnSRVolume.Name = "ColumnSRVolume";
            this.ColumnSRVolume.ReadOnly = true;
            //
            // ColumnSize
            //
            this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnSize, "ColumnSize");
            this.ColumnSize.Name = "ColumnSize";
            this.ColumnSize.ReadOnly = true;
            //
            // ColumnReadOnly
            //
            this.ColumnReadOnly.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnReadOnly, "ColumnReadOnly");
            this.ColumnReadOnly.Name = "ColumnReadOnly";
            this.ColumnReadOnly.ReadOnly = true;
            //
            // ColumnPriority
            //
            this.ColumnPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnPriority, "ColumnPriority");
            this.ColumnPriority.Name = "ColumnPriority";
            this.ColumnPriority.ReadOnly = true;
            //
            // ColumnActive
            //
            this.ColumnActive.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.ColumnActive, "ColumnActive");
            this.ColumnActive.Name = "ColumnActive";
            this.ColumnActive.ReadOnly = true;
            //
            // ColumnDevicePath
            //
            this.ColumnDevicePath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.ColumnDevicePath, "ColumnDevicePath");
            this.ColumnDevicePath.Name = "ColumnDevicePath";
            this.ColumnDevicePath.ReadOnly = true;
            //
            // flowLayoutPanel1
            //
            this.flowLayoutPanel1.Controls.Add(this.AddButton);
            this.flowLayoutPanel1.Controls.Add(this.AttachButton);
            this.flowLayoutPanel1.Controls.Add(this.RightButtonSeparator);
            this.flowLayoutPanel1.Controls.Add(this.DeactivateButtonContainer);
            this.flowLayoutPanel1.Controls.Add(this.MoveButtonContainer);
            this.flowLayoutPanel1.Controls.Add(this.EditButton);
            this.flowLayoutPanel1.Controls.Add(this.LeftButtonSeparator);
            this.flowLayoutPanel1.Controls.Add(this.DeleteButtonContainer);
            this.flowLayoutPanel1.Controls.Add(this.DetachButtonContainer);
            resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
            this.flowLayoutPanel1.MaximumSize = new System.Drawing.Size(900, 35);
            this.flowLayoutPanel1.Name = "flowLayoutPanel1";
            //
            // DeactivateButtonContainer
            //
            this.DeactivateButtonContainer.Controls.Add(this.DeactivateButton);
            resources.ApplyResources(this.DeactivateButtonContainer, "DeactivateButtonContainer");
            this.DeactivateButtonContainer.Name = "DeactivateButtonContainer";
            //
            // DeactivateButton
            //
            resources.ApplyResources(this.DeactivateButton, "DeactivateButton");
            this.DeactivateButton.Name = "DeactivateButton";
            this.DeactivateButton.UseVisualStyleBackColor = true;
            this.DeactivateButton.Click += new System.EventHandler(this.DeactivateButton_Click);
            //
            // MoveButtonContainer
            //
            this.MoveButtonContainer.Controls.Add(this.MoveButton);
            resources.ApplyResources(this.MoveButtonContainer, "MoveButtonContainer");
            this.MoveButtonContainer.Name = "MoveButtonContainer";
            //
            // MoveButton
            //
            resources.ApplyResources(this.MoveButton, "MoveButton");
            this.MoveButton.Name = "MoveButton";
            this.MoveButton.UseVisualStyleBackColor = true;
            this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click);
            //
            // DeleteButtonContainer
            //
            this.DeleteButtonContainer.Controls.Add(this.DeleteDriveButton);
            resources.ApplyResources(this.DeleteButtonContainer, "DeleteButtonContainer");
            this.DeleteButtonContainer.Name = "DeleteButtonContainer";
            //
            // DeleteDriveButton
            //
            resources.ApplyResources(this.DeleteDriveButton, "DeleteDriveButton");
            this.DeleteDriveButton.Name = "DeleteDriveButton";
            this.DeleteDriveButton.UseVisualStyleBackColor = true;
            this.DeleteDriveButton.Click += new System.EventHandler(this.DeleteDriveButton_Click);
            //
            // DetachButtonContainer
            //
            this.DetachButtonContainer.Controls.Add(this.DetachDriveButton);
            resources.ApplyResources(this.DetachButtonContainer, "DetachButtonContainer");
            this.DetachButtonContainer.Name = "DetachButtonContainer";
            //
            // DetachDriveButton
            //
            resources.ApplyResources(this.DetachDriveButton, "DetachDriveButton");
            this.DetachDriveButton.Name = "DetachDriveButton";
            this.DetachDriveButton.UseVisualStyleBackColor = true;
            this.DetachDriveButton.Click += new System.EventHandler(this.DetachButton_Click);
            //
            // multipleDvdIsoList1
            //
            resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1");
            this.multipleDvdIsoList1.MaximumSize = new System.Drawing.Size(900, 36);
            this.multipleDvdIsoList1.Name = "multipleDvdIsoList1";
            this.multipleDvdIsoList1.VM = null;
            //
            // dataGridViewTextBoxColumn1
            //
            this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1");
            this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
            this.dataGridViewTextBoxColumn1.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn2
            //
            this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2");
            this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
            this.dataGridViewTextBoxColumn2.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn3
            //
            this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3");
            this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
            this.dataGridViewTextBoxColumn3.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn4
            //
            this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4");
            this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
            this.dataGridViewTextBoxColumn4.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn5
            //
            this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5");
            this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
            this.dataGridViewTextBoxColumn5.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn6
            //
            this.dataGridViewTextBoxColumn6.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn6, "dataGridViewTextBoxColumn6");
            this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6";
            this.dataGridViewTextBoxColumn6.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn7
            //
            this.dataGridViewTextBoxColumn7.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn7, "dataGridViewTextBoxColumn7");
            this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7";
            this.dataGridViewTextBoxColumn7.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn8
            //
            this.dataGridViewTextBoxColumn8.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
            resources.ApplyResources(this.dataGridViewTextBoxColumn8, "dataGridViewTextBoxColumn8");
            this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8";
            this.dataGridViewTextBoxColumn8.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn9
            //
            this.dataGridViewTextBoxColumn9.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn9, "dataGridViewTextBoxColumn9");
            this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9";
            this.dataGridViewTextBoxColumn9.ReadOnly = true;
            //
            // dataGridViewTextBoxColumn10
            //
            this.dataGridViewTextBoxColumn10.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.dataGridViewTextBoxColumn10, "dataGridViewTextBoxColumn10");
            this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10";
            this.dataGridViewTextBoxColumn10.ReadOnly = true;
            //
            // gradientPanel1
            //
            this.gradientPanel1.Controls.Add(this.TitleLabel);
            resources.ApplyResources(this.gradientPanel1, "gradientPanel1");
            this.gradientPanel1.Name = "gradientPanel1";
            this.gradientPanel1.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Tab;
            //
            // TitleLabel
            //
            resources.ApplyResources(this.TitleLabel, "TitleLabel");
            this.TitleLabel.AutoEllipsis = true;
            this.TitleLabel.ForeColor = System.Drawing.Color.White;
            this.TitleLabel.Name = "TitleLabel";
            //
            // VMStoragePage
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.BackColor = System.Drawing.Color.Transparent;
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.gradientPanel1);
            this.DoubleBuffered = true;
            this.Name = "VMStoragePage";
            this.panel1.ResumeLayout(false);
            this.panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).EndInit();
            this.flowLayoutPanel1.ResumeLayout(false);
            this.DeactivateButtonContainer.ResumeLayout(false);
            this.MoveButtonContainer.ResumeLayout(false);
            this.DeleteButtonContainer.ResumeLayout(false);
            this.DetachButtonContainer.ResumeLayout(false);
            this.gradientPanel1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        public System.Windows.Forms.Button AttachButton;
        public System.Windows.Forms.Button AddButton;
        private System.Windows.Forms.Button EditButton;
        public System.Windows.Forms.Button DetachDriveButton;
        public System.Windows.Forms.Button DeleteDriveButton;
        private System.Windows.Forms.Label TitleLabel;
        private XenAdmin.Controls.ToolTipContainer DetachButtonContainer;
        private XenAdmin.Controls.ToolTipContainer DeleteButtonContainer;
        private System.Windows.Forms.Panel RightButtonSeparator;
        private System.Windows.Forms.Panel LeftButtonSeparator;
        private XenAdmin.Controls.ToolTipContainer DeactivateButtonContainer;
        private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel1;
        public System.Windows.Forms.Button DeactivateButton;
        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
        private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1;
        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.DataGridView dataGridViewStorage;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9;
		private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePosition;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSR;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSRVolume;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnReadOnly;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPriority;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnActive;
		private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePath;
        private XenAdmin.Controls.ToolTipContainer MoveButtonContainer;
        private System.Windows.Forms.Button MoveButton;
    }
}


text:
$(function(){

  var $root = $('html, body');
  $('a').click(function() {
    $(".navbar-collapse").collapse('hide');
    var href = $.attr(this, 'href');
    $root.animate({
      scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 1000, function () {
      window.location.hash = href;
    });
    return false;
  });

  var $navigationLinks = $(".navbar-nav a");
  $navigationLinks.click(function(event){
    $navigationLinks.parent().removeClass("active");
    $(event.target).parent().addClass("active");
    return false;
  });

  $('#contact_us').append("<input type='hidden' name='antispam' value='check'/>").validate({
    highlight: function(element) {
      $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function(element) {
      element.closest('.form-group').removeClass('has-error').addClass('has-success');
    }
  });

});


text:
package com.bazaarvoice.emodb.sor.delta.impl;

import com.bazaarvoice.emodb.sor.delta.Delete;
import com.bazaarvoice.emodb.sor.delta.DeltaVisitor;

import javax.annotation.Nullable;
import java.io.IOException;

public class DeleteImpl extends AbstractDelta implements Delete {

    public static final Delete INSTANCE = new DeleteImpl();

    private DeleteImpl() {
    }

    @Override
    public <T, V> V visit(DeltaVisitor<T, V> visitor, T context) {
        return visitor.visit(this, context);
    }

    @Override
    public boolean isConstant() {
        return true;
    }

    @Override
    public String toString() {
        return "~";
    }

    @Override
    public void appendTo(Appendable buf) throws IOException {
        buf.append('~');
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        return obj instanceof Delete;
    }

    @Override
    public int hashCode() {
        return 3221;
    }
}


text:
require "test_helper"

class CredentialsTest < Minitest::Test
  test "initializes credentials" do
    credentials = Citrix::Training::Credentials.new(
      oauth_token: "OAUTH_TOKEN",
      organizer_key: "ORGANIZER_KEY",
      account_key: "ACCOUNT_KEY"
    )

    assert_equal "OAUTH_TOKEN", credentials.oauth_token
    assert_equal "ORGANIZER_KEY", credentials.organizer_key
    assert_equal "ACCOUNT_KEY", credentials.account_key
  end

  test "builds a new instance" do
    credentials = Citrix::Training::Credentials.build({})
    assert_kind_of Citrix::Training::Credentials, credentials
  end

  test "builds a new credentials instance" do
    credentials = Citrix::Training::Credentials.new
    new_credentials = Citrix::Training::Credentials.build(credentials)

    assert_equal credentials, new_credentials
  end
end


text:
package com.station42.hopping;

import com.station42.base.Engine;
import com.station42.base.EngineUpdateListener;
import com.station42.base.Entity;
import com.station42.basic.EntitySprite;
import com.station42.faction.EntityFaction;
import com.station42.hacking.Hackable;
import com.station42.hacking.HackingAction;
import com.station42.world.World;

public class HoppingSystem implements EngineUpdateListener {
	@Override
	public void update(Engine engine, float delta) {
		for (Entity hackerEntity : engine.getEntitiesWithComponent(HoppingAction.class)) {
			HoppingAction hackingAction = hackerEntity.getComponent(HoppingAction.class);
			if (hackingAction != null && hackingAction.isTryingToHop()) {
				hackingAction.update(delta);
				if (hackingAction.getCompletionPercent() >= 1) {
					World currentWorld = hackerEntity.getComponent(World.class);
					hackerEntity.setComponent(World.class, currentWorld.nextWorld());
					hackingAction.complete();
				}
			}
		}
	}
}


text:
<?php

/********************************************************************************************/
//	Some vars
/********************************************************************************************/
//	The field name & idz
	$name = $_POST['param']['name'];
	$values = $_POST['param']['values'];
	$valuestype = $_POST['param']['valuestype'];
//	Refine values?
	$refine = (isset($_POST['q'])) ? $_POST['q'] : null;

/********************************************************************************************/
//	Get and process from ajax
/********************************************************************************************/
//	Create a blank field (tweak)
	$param = array(
		'values' => $values,
		'valuestype' => $valuestype,
	);
	$multipleselect = new fieldMultipleselect(null, $param);

//	Get the available values
	$available = $multipleselect->prepare_values($refine);
?>


text:
package org.spleen;

import java.util.HashMap;

import org.spleen.collection.NamespaceInterface;
import org.spleen.collection.NamespaceMap;
import org.spleen.collection.NamespaceMultiThread;
import org.spleen.config.SpleenConfigurator;
import org.spleen.type.CacheObject;
import org.spleen.type.Sizeable;

/**
 * Spleen class.
 *
 * Default spleen cache
 * system main class.
 *
 * @author vallance
 *
 */
public class Spleen implements Sizeable {

	protected HashMap<String, NamespaceInterface> namespacesObjects;

	/**
	 * Default constructor.
	 *
	 * Spleen default constructor.
	 */
	public Spleen() {
		this.namespacesObjects = new HashMap<String, NamespaceInterface>();
	}

	/**
	 * Create a new namespace.
	 *
	 * Create a new simple NamespaceMap
	 * and tell it the configuration.
	 *
	 * @param key		The new namespace identifier.
	 * @param config	The new namespace configuration.
	 */
	public void createNamespace(String key, SpleenConfigurator config){
		if(!this.namespacesObjects.containsKey(key)){
			this.namespacesObjects.put(key, (new NamespaceMap(config)));
		}
	}

	/**
	 * Create a new multi-threaded namespace.
	 *
	 * Create a new multi-threaded
	 * NamespaceMap and tell it the
	 * configuration.
	 *
	 * @param key		The new namespace identifier.
	 * @param config	The new namespace configuration.
	 */
	public void createNamespace(int threadCount, String key, SpleenConfigurator config){
		if(!this.namespacesObjects.containsKey(key)){
			this.namespacesObjects.put(key, (new NamespaceMultiThread(threadCount, config)));
		}
	}

	/**
	 * Remove a namespace.
	 *
	 * Remove a stored namespace.
	 *
	 * @param key	The namespace identifier.
	 */
	public void removeNamespace(String key){
		if(this.namespacesObjects.containsKey(key)){
			this.namespacesObjects.remove(key);
		}
	}

	/**
	 * Get a namespace.
	 *
	 * Get a stored namespace.
	 *
	 * @param key	The namespace identifier.
	 * @return		The namespace.
	 */
	public NamespaceInterface get(String key){
		if(this.namespacesObjects.containsKey(key)){
			return this.namespacesObjects.get(key);
		}else{
			return null;
		}
	}

	/**
	 * Get an object.
	 *
	 * Get an object from a namespace.
	 *
	 * @param namespaceKey	The namespace identifier.
	 * @param key			The cache object identifier.
	 * @return				The object from the namespace or null if isn't exist.
	 */
	public CacheObject get(String namespaceKey, String key){
		if(this.namespacesObjects.containsKey(namespaceKey)){
			return this.namespacesObjects.get(namespaceKey).get(key);
		}else{
			return null;
		}
	}

	/**
	 * Put cache object.
	 *
	 * Insert a new cache object into
	 * a stored namespace.
	 *
	 * @param namespaceKey	The namespace indentifier.
	 * @param key			The namespace cache object identifier to store.
	 * @param obj			The objet to store.
	 */
	public void put(String namespaceKey, String key, CacheObject obj){
		if(this.namespacesObjects.containsKey(namespaceKey)){
			this.namespacesObjects.get(namespaceKey).add(key, obj);
		}
	}

	/**
	 * @see org.spleen.type.Sizeable#getSize()
	 */
	public double getSize() {
		Object[] keys = this.namespacesObjects.keySet().toArray();
		double size = 0;

		for (Object key : keys) {
			size += this.namespacesObjects.get(key).getSize();
		}
		return size;
	}

}


text:
package com.hazelcast.client.impl.protocol.task.management;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.MCPromoteToCPMemberCodec;
import com.hazelcast.client.impl.protocol.codec.MCPromoteToCPMemberCodec.RequestParameters;
import com.hazelcast.client.impl.protocol.task.AbstractAsyncMessageTask;
import com.hazelcast.cp.CPSubsystemManagementService;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.management.ManagementCenterService;
import com.hazelcast.internal.nio.Connection;

import java.security.Permission;
import java.util.concurrent.CompletableFuture;

public class PromoteToCPMemberMessageTask extends AbstractAsyncMessageTask<RequestParameters, Void> {

    public PromoteToCPMemberMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    protected CompletableFuture<Void> processInternal() {
        CPSubsystemManagementService cpService =
                nodeEngine.getHazelcastInstance().getCPSubsystem().getCPSubsystemManagementService();
        return cpService.promoteToCPMember().toCompletableFuture();
    }

    @Override
    protected RequestParameters decodeClientMessage(ClientMessage clientMessage) {
        return MCPromoteToCPMemberCodec.decodeRequest(clientMessage);
    }

    @Override
    protected ClientMessage encodeResponse(Object response) {
        return MCPromoteToCPMemberCodec.encodeResponse();
    }

    @Override
    public String getServiceName() {
        return ManagementCenterService.SERVICE_NAME;
    }

    @Override
    public Permission getRequiredPermission() {
        return null;
    }

    @Override
    public String getDistributedObjectName() {
        return null;
    }

    @Override
    public String getMethodName() {
        return "promoteToCPMember";
    }

    @Override
    public Object[] getParameters() {
        return new Object[0];
    }
}


text:
package com.mossle.bpm;

import java.util.ArrayList;
import java.util.List;

public class FormInfo {
    private String formKey;
    private String processDefinitionId;
    private String taskId;
    private boolean autoCompleteFirstTask;
    private List<String> buttons = new ArrayList<String>();

    public String getFormKey() {
        return formKey;
    }

    public void setFormKey(String formKey) {
        this.formKey = formKey;
    }

    public String getProcessDefinitionId() {
        return processDefinitionId;
    }

    public void setProcessDefinitionId(String processDefinitionId) {
        this.processDefinitionId = processDefinitionId;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public boolean isAutoCompleteFirstTask() {
        return autoCompleteFirstTask;
    }

    public void setAutoCompleteFirstTask(boolean autoCompleteFirstTask) {
        this.autoCompleteFirstTask = autoCompleteFirstTask;
    }

    public String getRelatedId() {
        if (isStartForm()) {
            return processDefinitionId;
        } else {
            return taskId;
        }
    }

    public boolean isTaskForm() {
        return taskId != null;
    }

    public boolean isStartForm() {
        return taskId == null;
    }

    public boolean isFormExists() {
        return formKey != null;
    }

    public List<String> getButtons() {
        return buttons;
    }

    public void setButtons(List<String> buttons) {
        this.buttons = buttons;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Breeze.ContextProvider;
using SharperArchitecture.Common.Events;
using SharperArchitecture.Common.Specifications;

namespace SharperArchitecture.Breeze.Events
{
    public class BreezeAfterFlushAsyncEvent : IAsyncEvent
    {
        public BreezeAfterFlushAsyncEvent(List<EntityInfo> entitiesToPersist)
        {
            EntitiesToPersist = entitiesToPersist;
        }

        public List<EntityInfo> EntitiesToPersist { get; }
    }
}


text:
CREATE DATABASE IF NOT EXISTS monkeydb DEFAULT CHARSET=utf8;

USE monkeydb;
/* This table contains our monkeys. */
DROP TABLE IF EXISTS monkeys;
CREATE TABLE monkeys (
  monkeyId BIGINT NOT NULL AUTO_INCREMENT,
  monkeyName varchar(256) DEFAULT NULL,
	/* birthDate is in seconds since UNIX Epoch */
	birthDate INTEGER UNSIGNED DEFAULT NULL,
  PRIMARY KEY (monkeyId)
);

/* Insert some data into monkeys. */
LOCK TABLES monkeys WRITE;
INSERT INTO monkeys (monkeyName, birthDate) VALUES
  ('Janelle', UNIX_TIMESTAMP('2009-03-15 14:01:43')),
  ('Billy', UNIX_TIMESTAMP('2008-01-15 11:00:15'));
UNLOCK TABLES;


text:
<?php
namespace Album\Form;

use Zend\Form\Form;
use Zend\Form\Element;

class ImageUploadForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('Upload');
        $this->setAttribute('method', 'post');
        $this->setAttribute('enctype', 'multipart/form-data');
        $this->addElements();
    }
    public function addElements()
    {
        $label = new Element('label');
        $label->setLabel('Image Description');
        $label->setAttributes(array(
        		'type'=>'text',
        ));
        $this->add($label);

        $imageupload = new Element('imageUpload');
        $imageupload->setLabel('Image Upload');
        $imageupload->setAttributes(array(
        		'type'=>'file',
        ));
        $this->add($imageupload);

        $submit = new Element('submit');
        $submit->setAttributes(array(
        		'type' => 'submit',
                'value' => 'upload now'
        ));
        $this->add($submit);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>

Setting Child Site Hosting Fee

How set the default hosting fee for child sites in this DNN installation. The cost of hosting is set as a fee for Megabyte space, page quota or user quota. For example, if hosting is allocated by Megabytes the available hosting space is checked whenever a file is uploaded to the site's Digital Asset Management module which is located on the Admin > File Management page. If sufficient space is available, the files are successfully loaded. If there is insufficient space, the Administrator receives a message to contact their hosting provider to purchase additional space. Likewise, the same message is displayed when the Administrator attempts to add more pages or user accounts than allocated. Where more than one option is set, hosting is restricted when the first option reached. Note: Host settings can be modified for individual sites via the Host > Site Management page.

Navigate to  Host >  Host Settings.

Select the Basic Settings tab.

Expand the Payment Settings section.

In the Hosting Fee text box, enter the fee charged for a child site.

At Hosting Currency, select the currency to be used for payment processing.

In the Hosting Space (MB) text box, enter the maximum storage space for files in Megabytes per site. Leave this field blank for unlimited space.

In the Page Quota text box, enter the maximum number of pages allowed for each child site. Leave this field blank for unlimited pages.

In the User Quota text box, enter the maximum number of users allowed for each child site. Leave this field blank for unlimited user accounts.

                Click the Update button.


text:
require 'net/ssh'
require 'stringio'

def sshcmd(command, host: ENV['TESTHOST'], user: 'root', ignore_err: false)
  # Execute a command on the remote server
  # Not passing :password uses systems keys for auth
  out = StringIO.new
  err = StringIO.new
  Net::SSH.start(host, user, paranoid: Net::SSH::Verifiers::Null.new) do |ssh|
    ssh.exec!(command) do |_chan, str, data|
      out << data if str == :stdout
      err << data if str == :stderr
    end
  end
  # smdba print this warning on stderr. Ignore it. It is not an error
  errstring = err.string.gsub('WARNING: Reserved space for the backup is smaller than available disk space. Adjusting.', '')
  errstring.chomp!

  if !errstring.empty? && !ignore_err
    raise "Execute command failed #{command}: #{err.string}"
  end

  { stdout: out.string, stderr: err.string }
end


text:
class LineAnalyzer
  #Implement the following read-only attributes in the LineAnalyzer class.
  #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated)
  #* highest_wf_words - an array of words with the maximum number of occurrences (calculated)
  #* content          - the string analyzed (provided)
  #* line_number      - the line number analyzed (provided)

  attr_reader :highest_wf_count, :highest_wf_words, :content, :line_number

  #Add the following methods in the LineAnalyzer class.
  #* initialize() - taking a line of text (content) and a line number
  #* calculate_word_frequency() - calculates result

  #Implement the initialize() method to:
  #* take in a line of text and line number
  #* initialize the content and line_number attributes
  #* call the calculate_word_frequency() method.

  def initialize(content, line_number)
    @content = content
    @line_number = line_number
    calculate_word_frequency
  end

  #Implement the calculate_word_frequency() method to:
  #* calculate the maximum number of times a single word appears within
  #  provided content and store that in the highest_wf_count attribute.
  #* identify the words that were used the maximum number of times and
  #  store that in the highest_wf_words attribute.

  def calculate_word_frequency
    word_freq = Hash.new(0)
    @content.split.each { |word| word_freq[word.downcase] += 1 }
    @highest_wf_count = word_freq.values.max
    @highest_wf_words = word_freq.reject { |w,c| c < @highest_wf_count }.keys
  end

end

#  Implement a class called Solution.
class Solution

  # Implement the following read-only attributes in the Solution class.
  #* analyzers - an array of LineAnalyzer objects for each line in the file
  #* highest_count_across_lines - a number with the maximum value for highest_wf_words attribute in the analyzers array.
  #* highest_count_words_across_lines - a filtered array of LineAnalyzer objects with the highest_wf_words attribute
  #  equal to the highest_count_across_lines determined previously.

  attr_reader :analyzers, :highest_count_across_lines,
              :highest_count_words_across_lines

  def initialize
    @analyzers = []
  end

  # Implement the following methods in the Solution class.
  #* analyze_file() - processes 'test.txt' intro an array of LineAnalyzers and stores them in analyzers.
  #* calculate_line_with_highest_frequency() - determines the highest_count_across_lines and
  #  highest_count_words_across_lines attribute values
  #* print_highest_word_frequency_across_lines() - prints the values of LineAnalyzer objects in
  #  highest_count_words_across_lines in the specified format

  # Implement the analyze_file() method() to:
  #* Read the 'test.txt' file in lines
  #* Create an array of LineAnalyzers for each line in the file

  def analyze_file
    @analyzers = []
    line_number = 0
    File.open('test.txt') do |f|
      f.each do |line|
        line_number += 1
        @analyzers.push LineAnalyzer.new(line, line_number)
      end
    end
  end

  # Implement the calculate_line_with_highest_frequency() method to:
  #* calculate the maximum value for highest_wf_count contained by the LineAnalyzer objects in analyzers array
  #  and stores this result in the highest_count_across_lines attribute.
  #* identifies the LineAnalyzer objects in the analyzers array that have highest_wf_count equal to highest_count_across_lines
  #  attribute value determined previously and stores them in highest_count_words_across_lines.

  def calculate_line_with_highest_frequency
    max_analyzer = @analyzers.max_by { |a| a.highest_wf_count}
    @highest_count_across_lines = max_analyzer.highest_wf_count
    @highest_count_words_across_lines = @analyzers.select do |fuck|
      fuck.highest_wf_count == @highest_count_across_lines
    end
  end

  #Implement the print_highest_word_frequency_across_lines() method to
  #* print the values of objects in highest_count_words_across_lines in the specified format

  def print_highest_word_frequency_across_lines
    print highest_count_words_across_lines.map(&:highest_wf_words).flatten
  end

end


text: Learning MongoDB by example


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="MainRadioButtonStyle">
        <item name="android:layout_marginTop">8dp</item>
        <!--<item name="android:textColor">@drawable/selector_main_rb_text</item>-->
        <item name="android:drawablePadding">2dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_marginBottom">5dp</item>
        <item name="android:textSize">12sp</item>
        <item name="android:layout_weight">1</item>
        <item name="android:button">@null</item>
        <item name="android:gravity">center</item>
        <item name="android:textColor">@drawable/selector_navigation_text_bg</item>
    </style>
</resources>


text:
<mvc:View controllerName="de.blogspot.openui5.fc.controller.Calendar" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout"
	xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m">
	<Page showHeader="false">
		<l:BlockLayout background="Light">
			<l:BlockLayoutRow>
				<l:BlockLayoutCell width="4" title="Calendar">
					<Text text="Enables applications to use the default calendar."/>
				</l:BlockLayoutCell>
				<l:BlockLayoutCell titleAlignment="Center">
					<core:Icon src="sap-icon://calendar"/>
				</l:BlockLayoutCell>
			</l:BlockLayoutRow>
			<l:BlockLayoutRow>
				<l:BlockLayoutCell title="Event">
					<l:VerticalLayout width="100%">
						<List>
							<InputListItem label="Title">
								<Input value="{ui>/options/title}"/>
							</InputListItem>
							<InputListItem label="Location">
								<Input value="{ui>/options/eventLocation}"/>
							</InputListItem>
							<InputListItem label="From">
								<DateTimePicker
									value="{path:'ui>/options/startDate', type:'sap.ui.model.type.DateTime', formatOptions: { style: 'medium', strictParsing: true}}"/>
							</InputListItem>
							<InputListItem label="To">
								<DateTimePicker
									value="{path:'ui>/options/endDate', type:'sap.ui.model.type.DateTime', formatOptions: { style: 'medium', strictParsing: true}}"/>
							</InputListItem>
							<InputListItem label="Notes">
								<Input value="{ui>/options/notes}"/>
							</InputListItem>
						</List>
						<Button class="sapUiTinyMarginTop" icon="sap-icon://add-activity" text="Add Event" type="Emphasized" enabled="{ui>/isFioriClientAvailable}"
							press="onCalendar"/>
					</l:VerticalLayout>
				</l:BlockLayoutCell>
			</l:BlockLayoutRow>
		</l:BlockLayout>
	</Page>
</mvc:View>


text:
"""Information about FC Barcelona's games."""

from bs4 import BeautifulSoup
import click
import requests
from termcolor import colored, cprint

class RequestHandler:
    """Handles requests for getting the information.

    Gets information from the 'SkySports' website about the latest FCB
    games (recent results, fixtures, and the current league table.

    """

    BASE_URL = "http://www.skysports.com/"

    def show_results(self):
        """Shows recent FCB results."""
        url = self.BASE_URL + "barcelona-results"
        r = requests.get(url)
        soup = BeautifulSoup(r.text, "html.parser")

        teams_box = soup.findAll("span", class_="swap-text__target")
        teams = [team.text.strip() for team in teams_box]
        # Remove extra (unimportant) team names.
        del teams[0]
        while '' in teams:
            teams.remove('')

        scores_box = soup.findAll("span", class_="matches__teamscores-side")
        scores = [score.text.strip() for score in scores_box]

        dates_box = soup.findAll("h4", class_="fixres__header2")
        dates = [date.text.strip() for date in dates_box]

        competitions_box = soup.findAll("h5", class_="fixres__header3")
        competitions = [competition.text.strip()
                        for competition in competitions_box]

        for i in range(0, min(5, len(teams)), 2):
            print("\n", colored(competitions[i // 2].upper(), "cyan", "on_white",
                                attrs=["reverse"]).center(88),
                  "\n", colored(dates[i // 2], "yellow").center(78),
                  "\n", colored(teams[i], "cyan").rjust(40) + "  "
                  + colored(scores[i] + " - " + scores[i + 1],
                            "red", attrs=["reverse"]) + "  "
                  + colored(teams[i + 1], "green") + "\n")

        cprint("\n\n*All dates stated according to BST.\n", "red")

    def show_fixtures(self):
        """Shows recent FCB fixtures."""
        url = self.BASE_URL + "barcelona-fixtures"
        r = requests.get(url)
        soup = BeautifulSoup(r.text, "html.parser")

        teams_box = soup.findAll("span", class_="swap-text__target")
        teams = [team.text.strip() for team in teams_box]
        # Remove extra (unimportant) team names.
        del teams[0]
        while '' in teams:
            teams.remove('')

        dates_box = soup.findAll("h4", class_="fixres__header2")
        dates = [date.text.strip() for date in dates_box]

        competitions_box = soup.findAll("h5", class_="fixres__header3")
        competitions = [competition.text.strip()
                        for competition in competitions_box]

        time_box = soup.findAll("span", class_="matches__date")
        time = [timing.text.strip() for timing in time_box]

        for i in range(0, min(5, len(teams)), 2):
            print("\n", colored(competitions[i // 2].upper(), "cyan", "on_white",
                                attrs=["reverse"]).center(88),
                  "\n", colored(dates[i // 2], "yellow").center(78),
                  "\n", colored(teams[i], "cyan").rjust(40)
                  + f"  {time[i//2]}  "
                  + colored(teams[i + 1], "green") + "\n")

        cprint("\n\n*All dates and kick-off times stated according to"
               " BST.\n", "red")

@click.command()
@click.option("--results", "-r", is_flag=True, help="Show recent results.")
@click.option("--fixtures", "-f", is_flag=True, help="Show upcoming fixtures.")
def main(results, fixtures):
    """FCB match details."""
    x = RequestHandler()

    if results:
        x.show_results()

    elif fixtures:
        x.show_fixtures()

if __name__ == "__main__":
    main()


text:
package be.ana.nmct.multimania.data;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by Astrid on 28/10/2014.
 */
public class TalkLoader extends AsyncTaskLoader<Cursor>{

    private Cursor mData;
    private final int mRoomId;

    private TalkLoader(Context context, int roomId){
        super(context);
        this.mRoomId = roomId;
    }

    /**
     * Loads the talks in a background thread
     */
    @Override
    public Cursor loadInBackground() {

        DbHelper helper = DbHelper.getInstance(getContext());
        SQLiteDatabase database = helper.getReadableDatabase();

        Cursor cursor = database.query(
                MultimaniaContract.TalkEntry.TABLE_NAME,
                new String[]{MultimaniaContract.TalkEntry.TALK_ID,
                            MultimaniaContract.TalkEntry.TITLE,
                            MultimaniaContract.TalkEntry.DATE_FROM,
                            MultimaniaContract.TalkEntry.DATE_UNTIL,
                            MultimaniaContract.TalkEntry.DESCRIPTION,
                            MultimaniaContract.TalkEntry.ROOM_ID,
                            MultimaniaContract.TalkEntry.IS_KEYNOTE},
                "(" + MultimaniaContract.TalkEntry.ROOM_ID + " = ?)",
                new String[]{"" + mRoomId},
                null,
                null,
                MultimaniaContract.TalkEntry.TITLE + " ASC");

        cursor.getCount();
        return cursor;
    }

    @Override
    public void deliverResult(Cursor data) {
        if(isReset()){
            if(data!=null){
                data.close();
            }
            return;
        }
        Cursor oldData = mData;
        mData = data;

        if(isStarted()){
            super.deliverResult(data);
        }

        if(oldData != null && oldData != data && !oldData.isClosed()){
            oldData.close();
        }
    }

    /**
     * Starts loading the talks
     */
    @Override
    protected void onStartLoading() {
        if(mData != null){
            deliverResult(mData);
        }

        if(takeContentChanged() || mData == null){
            forceLoad();
        }
    }

    /**
     * Stop loading the talks
     */
    @Override
    protected void onStopLoading() {
        cancelLoad();
    }

    @Override
    public void onCanceled(Cursor data) {
        if(data != null && !data.isClosed()){
            data.close();
        }
    }

    /**
     * Reset loading off the talks
     */
    @Override
    protected void onReset() {
        super.onReset();

        onStopLoading();

        if(mData != null && !mData.isClosed()){
            mData.close();
        }

        mData = null;
    }
}


text: Automatic build for maxscale


text:
<?php
session_start();
$base_dir  = __DIR__; // Absolute path to your installation, ex: /var/www/mywebsite
$doc_root  = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']); # ex: /var/www
$base_url  = preg_replace("!^${doc_root}!", '', $base_dir); # ex: '' or '/mywebsite'
$protocol  = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$port      = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
$domain    = $_SERVER['SERVER_NAME'];
$base_url  = "${protocol}://${domain}${disp_port}${base_url}/";

if(empty($_SESSION['user'])){
    header("Location: /aws_r53/index.php");
}
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>AWS</title>

    <link href="<?php echo $base_url; ?>assets/css/bootstrap.css" rel="stylesheet">
    <link href="<?php echo $base_url; ?>assets/css/all.css" rel="stylesheet">

Amazon Web Services

Amazon Route 53

Logged in as dropigee

<a href="<?php echo $base_url; ?>logout.php">Logout

                    <a class="btn btn-primary" href="<?php echo $base_url; ?>domain_home.php">Manage Domains

                <form action="<?php echo $base_url; ?>route53.php" method="post">

Already Have a Hosted Zone?

                            <input class="form-control" id="old_domain" name="zone_id" placeholder="Hosted Zone ID"  type="text" required autofocus />

                            <input type="submit" id="old_domain_btn" class="btn btn-primary pull-right" value="Get NS" />

                </form>
                <form action="<?php echo $base_url; ?>create_hosted_zone.php" method="post">

Register New Hosted Zone

                            <input class="form-control" id="domain" name="domain" placeholder="example.com"  type="text" required autofocus />

                            <input type="submit" class="btn btn-primary pull-right" value="Get Served" />

                </form>

                <form action="<?php echo $base_url; ?>health_check_get.php" method="post">

Already have a Health Check?

                            <input class="form-control" id="id" name="id" placeholder="Health check ID"  type="text" required autofocus />

                            <input type="submit" class="btn btn-primary pull-right" value="Check" />

                </form>
                <form action="<?php echo $base_url; ?>health_check_create.php" method="post">

Create Health Check Status

                            <input class="form-control" id="domain" name="domain" placeholder="example.com"  type="text" required autofocus />

                            <input class="form-control" id="domain" name="type" placeholder="Type i.e. TCP, HTTP, HTTPS, HTTP_STR_MATCH, and HTTPS_STR_MATCH"  type="text" required autofocus />

                            <input class="form-control" id="domain" name="ip" placeholder="IP address of instance"  type="text" required autofocus />

                            <input class="form-control" id="domain" name="port" placeholder="Port"  type="number" min="10" max="1000"  required autofocus />

                            <input class="form-control" id="domain" name="RequestInterval" placeholder="Request Interval. 10 or 30" min="10" max="30"  type="number" required autofocus />

                            <input class="form-control" id="domain" name="FailureThreshold" placeholder="Failure Threshold"  type="number" min="1" max="10" required autofocus />

                            <input type="submit" class="btn btn-primary pull-right" value="Create Health check" />

                </form>

 Result:

                            <?php
                            if(isset($_SESSION['health_check']) && !empty($_SESSION['health_check'])){
                                $health_check=$_SESSION['health_check'];
                                if($health_check['status']){
                                    echo "
 Domain: ".$health_check['domain']."
";
                                    echo "
 Helth check ID: ".$health_check['id']."
";
                                    echo "
 IP: ".$health_check['ip']."
";
                                    echo "
 Port: ".$health_check['port']."
";
                                    echo "
 Type: ".$health_check['type']."
";
                                    echo "
 RequestInterval: ".$health_check['RequestInterval']."
";
                                    echo "
 FailureThreshold: ".$health_check['FailureThreshold']."
";
                                }
                                else{
                                 echo "
 Something went wrong!...:(
";
                             }
                             $_SESSION['health_check']="";
                         }
                         elseif (isset($_SESSION['hosted_zone']) && !empty($_SESSION['hosted_zone'])) {
                           $hosted_zone=$_SESSION['hosted_zone'];
                           echo "
 Zone ID: ".$hosted_zone['id']."
";
                           echo "
 Name: ".$hosted_zone['name']."
";
                           foreach ($hosted_zone['ns'] as $key => $value) {
                              echo "
 NS ".$key." : ".$value."
";

                              $_SESSION['hosted_zone']="";
                          }
                      }
                      elseif(isset($_SESSION['health_check_get']) && !empty($_SESSION['health_check_get'])){
                        $health_check=$_SESSION['health_check_get'];
                        if($health_check['status']){
                            echo "
 IP: ".$health_check['ip']."
";
                            echo "
 Status: ".$health_check['health_status']."
";
                        }
                        else{
                           echo "
 Something went wrong!...:(
";
                       }
                       $_SESSION['health_check_get']="";
                   }
                   ?>


text:
;(function($) {
	'use strict';

	jcf.addModule({
		name: 'Range',
		selector: 'input[type="range"]',
		options: {
			realElementClass: 'jcf-real-element',
			fakeStructure: '',
			dataListMark: '',
			dragValueDisplay: '',
			handleSelector: '.jcf-range-handle',
			trackSelector: '.jcf-range-track',
			verticalClass: 'jcf-vertical',
			orientation: 'horizontal',
			dragHandleCenter: true,
			snapToMarks: true,
			snapRadius: 5
		},
		matchElement: function(element) {
			return element.is(this.selector);
		},
		init: function() {
			this.initStructure();
			this.attachEvents();
			this.refresh();
		},
		initStructure: function() {
			this.page = $('html');
			this.realElement = $(this.options.element).addClass(this.options.hiddenClass);
			this.fakeElement = $(this.options.fakeStructure).insertBefore(this.realElement).prepend(this.realElement);
			this.track = this.fakeElement.find(this.options.trackSelector);
			this.handle = this.fakeElement.find(this.options.handleSelector);

			// handle orientation
			this.isVertical = (this.options.orientation === 'vertical');
			this.directionProperty = this.isVertical ? 'top' : 'left';
			this.offsetProperty = this.isVertical ? 'bottom' : 'left';
			this.eventProperty = this.isVertical ? 'pageY' : 'pageX';
			this.sizeMethod = this.isVertical ? 'innerHeight' : 'innerWidth';
			this.fakeElement.css('touchAction', this.isVertical ? 'pan-x' : 'pan-y');
			if (this.isVertical) {
				this.fakeElement.addClass(this.options.verticalClass);
			}

			// set initial values
			this.minValue = parseFloat(this.realElement.attr('min'));
			this.maxValue = parseFloat(this.realElement.attr('max'));
			this.stepValue = parseFloat(this.realElement.attr('step')) || 1;

			// check attribute values
			this.minValue = isNaN(this.minValue) ? 0 : this.minValue;
			this.maxValue = isNaN(this.maxValue) ? 100 : this.maxValue;

			// handle range
			if (this.stepValue !== 1) {
				this.maxValue -= (this.maxValue - this.minValue) % this.stepValue;
			}
			this.stepsCount = (this.maxValue - this.minValue) / this.stepValue + 1;
			this.createDataList();
		},
		attachEvents: function() {
			this.realElement.on({
				focus: this.onFocus
			});
			this.handle.on('jcf-pointerdown', this.onPress);
		},
		createDataList: function() {
			var self = this,
				dataValues = [],
				dataListId = this.realElement.attr('list');

			if (dataListId) {
				$('#' + dataListId).find('option').each(function() {
					var itemValue = parseFloat(this.value || this.innerHTML),
						mark, markOffset;

					if (!isNaN(itemValue)) {
						markOffset = self.valueToOffset(itemValue);
						dataValues.push({
							value: itemValue,
							offset: markOffset
						});
						mark = $(self.options.dataListMark).text(itemValue).attr({
							'data-mark-value': itemValue
						}).css(self.offsetProperty, markOffset + '%').appendTo(self.track);
					}
				});
				if (dataValues.length) {
					self.dataValues = dataValues;
				}
			}
		},
		onPress: function(e) {
			var trackSize, trackOffset, innerOffset;

			e.preventDefault();
			if (!this.realElement.is(':disabled')) {
				trackSize = this.track[this.sizeMethod]();
				trackOffset = this.track.offset()[this.directionProperty];
				innerOffset = this.options.dragHandleCenter ? this.handle[this.sizeMethod]() / 2 : e[this.eventProperty] - this.handle.offset()[this.directionProperty];

				this.dragData = {
					trackSize: trackSize,
					innerOffset: innerOffset,
					trackOffset: trackOffset,
					min: trackOffset,
					max: trackOffset + trackSize
				};
				this.page.on({
					'jcf-pointermove': this.onMove,
					'jcf-pointerup': this.onRelease
				});

				if (e.pointerType === 'mouse') {
					this.realElement.focus();
				}
			}
		},
		onMove: function(e) {
			var self = this,
				newOffset, dragPercent, stepIndex, valuePercent;

			// calculate offset
			if (this.isVertical) {
				newOffset = this.dragData.max + (this.dragData.min - e[this.eventProperty]) - this.dragData.innerOffset;
			} else {
				newOffset = e[this.eventProperty] - this.dragData.innerOffset;
			}

			// fit in range
			if (newOffset < this.dragData.min) {
				newOffset = this.dragData.min;
			} else if (newOffset > this.dragData.max) {
				newOffset = this.dragData.max;
			}

			e.preventDefault();
			if (this.options.snapToMarks && this.dataValues) {
				// snap handle to marks
				var dragOffset = newOffset - this.dragData.trackOffset;
				dragPercent = (newOffset - this.dragData.trackOffset) / this.dragData.trackSize * 100;

				$.each(this.dataValues, function(index, item) {
					var markOffset = item.offset / 100 * self.dragData.trackSize,
						markMin = markOffset - self.options.snapRadius,
						markMax = markOffset + self.options.snapRadius;

					if (dragOffset >= markMin && dragOffset <= markMax) {
						dragPercent = item.offset;
						return false;
					}
				});
			} else {
				// snap handle to steps
				dragPercent = (newOffset - this.dragData.trackOffset) / this.dragData.trackSize * 100;
			}
			stepIndex = Math.round(dragPercent * this.stepsCount / 100);
			valuePercent = stepIndex * (100 / this.stepsCount);

			if (this.dragData.stepIndex !== stepIndex) {
				this.dragData.stepIndex = stepIndex;
				this.dragData.offset = valuePercent;
				this.handle.css(this.offsetProperty, this.dragData.offset + '%');
			}
		},
		onRelease: function() {
			var newValue;
			if (typeof this.dragData.offset === 'number') {
				newValue = this.stepIndexToValue(this.dragData.stepIndex);
				this.realElement.val(newValue).trigger('change');
			}

			this.page.off({
				'jcf-pointermove': this.onMove,
				'jcf-pointerup': this.onRelease
			});
			delete this.dragData;
		},
		onFocus: function() {
			this.fakeElement.addClass(this.options.focusClass);
			this.realElement.on({
				blur: this.onBlur,
				keydown: this.onKeyPress
			});
		},
		onBlur: function() {
			this.fakeElement.removeClass(this.options.focusClass);
			this.realElement.off({
				blur: this.onBlur,
				keydown: this.onKeyPress
			});
		},
		onKeyPress: function(e) {
			var incValue = (e.which === 38 || e.which === 39),
				decValue = (e.which === 37 || e.which === 40);

			if (decValue || incValue) {
				e.preventDefault();
				this.step(incValue ? this.stepValue : -this.stepValue);
			}
		},
		step: function(changeValue) {
			var originalValue = parseFloat(this.realElement.val()),
				newValue = originalValue;

			if (isNaN(originalValue)) {
				newValue = 0;
			}

			newValue += changeValue;

			if (newValue > this.maxValue) {
				newValue = this.maxValue;
			} else if (newValue < this.minValue) {
				newValue = this.minValue;
			}

			if (newValue !== originalValue) {
				this.realElement.val(newValue).trigger('change');
				this.setSliderValue(newValue);
			}
		},
		stepIndexToValue: function(stepIndex) {
			return this.minValue + this.stepValue * stepIndex;
		},
		valueToOffset: function(value) {
			var range = this.maxValue - this.minValue,
				percent = (value - this.minValue) / range;

			return percent * 100;
		},
		setSliderValue: function(value) {
			// set handle position accordion according to value
			this.handle.css(this.offsetProperty, this.valueToOffset(value) + '%');
		},
		refresh: function() {
			// handle disabled state
			var isDisabled = this.realElement.is(':disabled');
			this.fakeElement.toggleClass(this.options.disabledClass, isDisabled);

			// refresh handle position according to current value
			var realValue = parseFloat(this.realElement.val()) || 0;
			this.setSliderValue(realValue);
		},
		destroy: function() {
			this.realElement.removeClass(this.options.hiddenClass).insertBefore(this.fakeElement);
			this.fakeElement.remove();

			this.realElement.off({
				keydown: this.onKeyPress,
				focus: this.onFocus,
				blur: this.onBlur
			});
		}
	});

}(jQuery));


text:
require "benchmark"

$:.unshift "./"
$:.unshift "./lib"

require "lib/moped"

require "perf/helpers"
require "perf/setup"
require "perf/cases"

at_exit do
  Benchmark.bmbm do |x|
    Benchmark.cases.each do |name, block|
      x.report name, &block
    end
  end unless $!
end


text:
package poussecafe.discovery;

import poussecafe.domain.AggregateRepository;
import poussecafe.domain.EntityAttributes;
import poussecafe.testmodule.TestDomainEvent;
import poussecafe.testmodule.TestDomainEvent2;
import poussecafe.testmodule.TestDomainEvent3;

public class RepositoryWithSingleListener
extends AggregateRepository<String, AggregateRootWithSingleListener, EntityAttributes<String>> {

    @MessageListener
    @ProducesEvent(value = TestDomainEvent2.class, required = false)
    @ProducesEvent(TestDomainEvent3.class)
    public void listener(TestDomainEvent event) {

    }
}


text:
//
//  DrawProgreView.m
//  DrawCircle
//
//  Created by Mac on 15-7-19.
//  Copyright (c) 2015年 WZG. All rights reserved.
//

#import "DrawProgreView.h"

@interface DrawProgreView (){

    UIButton         * _goalValue;

    //已完成
    UILabel         * _finishlabel;
    //进度
    UILabel         * _efficiLabel;
    UIBezierPath    * pBezier ;//圆柱
    CGFloat          _line_width;  //线宽
    CGFloat          _innerRadius; //内环半径
    CGFloat         _outRadius;   //外环半径
    CGFloat          _per;
}
@end
@implementation DrawProgreView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.frame = frame;
        self.backgroundColor = [UIColor clearColor];

        _line_width = 20;
        _outRadius = (self.width - 0.5)/2.0;
        _innerRadius = _outRadius - _line_width;
        _per = 0;
        [self _initVews];
    }
    return self;
}

-(void)_initVews{

    //已完成

    NSString * finishstr = @"已完成";
    CGSize  finisize = [MyTool getSizeString:finishstr font:13];
    _finishlabel = [[UILabel alloc] init];
    _finishlabel.bounds  = CGRectMake(0, 0, finisize.width , finisize.height+4);
    CGFloat A = [self getChordX:_finishlabel.width/2.0+4];

    _finishlabel.center = CGPointMake(_outRadius, _outRadius - A +  _finishlabel.height/2.0);
    _finishlabel.text = finishstr;
    _finishlabel.tag = 1;
    _finishlabel.textAlignment = NSTextAlignmentCenter;
    _finishlabel.font = FONT(13);
    [self addSubview:_finishlabel];

    //进度
    _efficiLabel = [[UILabel alloc] init];

    CGFloat  haltHeight = 20;
    _efficiLabel.bounds =  CGRectMake(0, 0, _innerRadius*2, haltHeight*2);
    _efficiLabel.center = CGPointMake(_finishlabel.center.x, _outRadius);
    _efficiLabel.text = @"0%";
    _efficiLabel.textColor = [UIColor colorWithHexString:@"#28cafb"];
    _efficiLabel.tag = 2;
    //    efficiLabel.backgroundColor = [UIColor redColor];
    _efficiLabel.font = FONT(30);
    _efficiLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_efficiLabel];

    //目标
    UILabel  * goal = [[UILabel alloc]  init];
    goal.bounds = CGRectMake(0, 0, 30, 20);
    //    goal.backgroundColor = [UIColor redColor];
    goal.center = CGPointMake(_outRadius  -  goal.width/2.0-5 , _efficiLabel.bottom +  goal.height/2.0 + 8);
    goal.font = FONT(13);
    goal.text = @"目标";
    [self addSubview:goal];

    //目标值
    _goalValue = [[UIButton alloc] init];

    _goalValue.bounds = CGRectMake(0, 0, 60, 20);
    _goalValue.tag = 3;
    _goalValue.center = CGPointMake(goal.right + _goalValue.width/2.0 , goal.center.y);
    [_goalValue setTitle:@"0" forState:UIControlStateNormal];
    [_goalValue setTitleColor:[UIColor colorWithHexString:@"#f78314"] forState:UIControlStateNormal];

    _goalValue.titleLabel.font = FONT(22);
    _goalValue.titleLabel.textAlignment  = NSTextAlignmentCenter;

//    [_goalValue addTarget:self action:@selector(gotoGoalVC:) forControlEvents:UIControlEventTouchUpInside];
//
//    [_goalValue addTarget:self action:@selector(gotoGoalVC:) forControlEvents:UIControlEventTouchUpOutside];
//
//    [_goalValue addTarget:self action:@selector(gotoGoalVC:) forControlEvents:UIControlEventTouchDown];

//    _goalValue.backgroundColor = [UIColor grayColor];

    [self addSubview: _goalValue];

}

-(void)gotoGoalVC:(id)sender{
    DLog(@"TODO: 跳转到设定目标页面");
    DLog(@"TODO: 跳转到设定目标页面");
}

-(void)drawRect:(CGRect)rect{

    [self drawBezier];
}

-(void)drawBezier{

    //圆环
    pBezier = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0) radius:_innerRadius + _line_width/2.0 startAngle:0 endAngle:2*M_PI   clockwise:NO];
    pBezier.lineWidth = _line_width;
    [[UIColor colorWithHexString:@"#f1f1f1"]set];
    [pBezier stroke];

}

-(void)setGoalNum:(CGFloat)goalNum{

    if (goalNum <= 0) {
        goalNum = 0;
    }
    _goalNum = goalNum;

    [_goalValue setTitle:[NSString stringWithFormat:@"%d",(int)goalNum] forState:UIControlStateNormal] ;

    [self doing];
}

-(void)setFinishNum:(CGFloat)finishNum{

    if (finishNum <= 0) {
        finishNum = 0;
    }

    _finishNum = finishNum;

    [self doing];

}

//
-(void) doing{

    //完成度提示
    if (_goalNum <= _finishNum && _goalNum != 0) {
        _finishlabel.text = @"已完成";
    }else{
        _finishlabel.text = @"已完成";
    }

    //判断
    CGFloat  percentage = 0;

    if (_goalNum <= 0) {
        _goalNum = 500;
    }

    percentage =  _finishNum*10 /_goalNum;
    if (percentage > 100) {
        percentage = 100;
    }

    _efficiLabel.text = [NSString stringWithFormat:@"%ld%",(long)percentage];

    _per = percentage/100.0 ;

}

-(void) showCircleView{

    //先清除
    [self removeCircleView];
    //再创建
    [self creatCiecleView];

}
//创建 cirele
-(void)creatCiecleView{

    if (_circleBezierView == nil) {
        _circleBezierView = [[CircleBezierView alloc] initWithFrame:self.frame];
        _circleBezierView.center = CGPointMake(self.width/2.0, self.height/2.0);
        _circleBezierView.line_width = _line_width;
        _circleBezierView.innerRadius = _innerRadius;

        _circleBezierView.angle = _per;
        [self addSubview:_circleBezierView];
    }
}

//清除 cirele
-(void)removeCircleView{

    if (_circleBezierView != nil) {
        [_circleBezierView removeFromSuperview];
        _circleBezierView = nil;
    }
}
//勾股定理
-(CGFloat) getChordX:(CGFloat)B{

    CGFloat A = sqrtf(_innerRadius * _innerRadius - B*B);
    return A;
}

//默认状态下远

-(void) showDefaultCircleView{

    [self removeCircleView];
    [self creatCiecleView];
    _circleBezierView.angle = 0.5;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
import sys
from redis import StrictRedis
import django
if django.VERSION[:2] >= (1, 7):
    django.setup()
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest, logger, STATUS_CODE_TEXT
from django.core.exceptions import PermissionDenied
from django import http
from django.utils.encoding import force_str
from django.utils.importlib import import_module
from django.utils.functional import SimpleLazyObject
from ws4redis import settings as private_settings
from ws4redis.redis_store import RedisMessage
from ws4redis.exceptions import WebSocketError, HandshakeError, UpgradeRequiredError

class WebsocketWSGIServer(object):
    def __init__(self, redis_connection=None):
        """
        redis_connection can be overriden by a mock object.
        """
        comps = str(private_settings.WS4REDIS_SUBSCRIBER).split('.')
        module = import_module('.'.join(comps[:-1]))
        Subscriber = getattr(module, comps[-1])
        self.possible_channels = Subscriber.subscription_channels + Subscriber.publish_channels
        self._redis_connection = redis_connection and redis_connection or StrictRedis(**private_settings.WS4REDIS_CONNECTION)
        self.Subscriber = Subscriber

    def assure_protocol_requirements(self, environ):
        if environ.get('REQUEST_METHOD') != 'GET':
            raise HandshakeError('HTTP method must be a GET')

        if environ.get('SERVER_PROTOCOL') != 'HTTP/1.1':
            raise HandshakeError('HTTP server protocol must be 1.1')

        if environ.get('HTTP_UPGRADE', '').lower() != 'websocket':
            raise HandshakeError('Client does not wish to upgrade to a websocket')

    def process_request(self, request):
        request.session = None
        request.user = None
        if 'django.contrib.sessions.middleware.SessionMiddleware' in settings.MIDDLEWARE_CLASSES:
            engine = import_module(settings.SESSION_ENGINE)
            session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
            if session_key:
                request.session = engine.SessionStore(session_key)
                if 'django.contrib.auth.middleware.AuthenticationMiddleware' in settings.MIDDLEWARE_CLASSES:
                    from django.contrib.auth import get_user
                    request.user = SimpleLazyObject(lambda: get_user(request))

    def process_subscriptions(self, request):
        agreed_channels = []
        echo_message = False
        for qp in request.GET:
            param = qp.strip().lower()
            if param in self.possible_channels:
                agreed_channels.append(param)
            elif param == 'echo':
                echo_message = True
        return agreed_channels, echo_message

    def __call__(self, environ, start_response):
        """ Hijack the main loop from the original thread and listen on events on Redis and Websockets"""
        websocket = None
        subscriber = self.Subscriber(self._redis_connection)
        try:
            self.assure_protocol_requirements(environ)
            request = WSGIRequest(environ)
            self.process_request(request)
            channels, echo_message = self.process_subscriptions(request)
            if callable(private_settings.WS4REDIS_ALLOWED_CHANNELS):
                channels = list(private_settings.WS4REDIS_ALLOWED_CHANNELS(request, channels))
            websocket = self.upgrade_websocket(environ, start_response)
            logger.debug('Subscribed to channels: {0}'.format(', '.join(channels)))
            subscriber.set_pubsub_channels(request, channels)
            websocket_fd = websocket.get_file_descriptor()
            listening_fds = [websocket_fd]
            redis_fd = subscriber.get_file_descriptor()
            if redis_fd:
                listening_fds.append(redis_fd)
            subscriber.send_persited_messages(websocket)
            recvmsg = None
            while websocket and not websocket.closed:
                ready = self.select(listening_fds, [], [], 4.0)[0]
                if not ready:
                    # flush empty socket
                    websocket.flush()
                for fd in ready:
                    if fd == websocket_fd:
                        recvmsg = RedisMessage(websocket.receive())
                        if recvmsg:
                            subscriber.publish_message(recvmsg)
                    elif fd == redis_fd:
                        sendmsg = RedisMessage(subscriber.parse_response())
                        if sendmsg and (echo_message or sendmsg != recvmsg):
                            websocket.send(sendmsg)
                    else:
                        logger.error('Invalid file descriptor: {0}'.format(fd))
                if private_settings.WS4REDIS_HEARTBEAT:
                    websocket.send(private_settings.WS4REDIS_HEARTBEAT)
        except WebSocketError as excpt:
            logger.warning('WebSocketError: ', exc_info=sys.exc_info())
            response = http.HttpResponse(status=1001, content='Websocket Closed')
        except UpgradeRequiredError as excpt:
            logger.info('Websocket upgrade required')
            response = http.HttpResponseBadRequest(status=426, content=excpt)
        except HandshakeError as excpt:
            logger.warning('HandshakeError: ', exc_info=sys.exc_info())
            response = http.HttpResponseBadRequest(content=excpt)
        except PermissionDenied as excpt:
            logger.warning('PermissionDenied: ', exc_info=sys.exc_info())
            response = http.HttpResponseForbidden(content=excpt)
        except Exception as excpt:
            logger.error('Other Exception: ', exc_info=sys.exc_info())
            response = http.HttpResponseServerError(content=excpt)
        else:
            response = http.HttpResponse()
        if websocket:
            websocket.close(code=1001, message='Websocket Closed')
        if hasattr(start_response, 'im_self') and not start_response.im_self.headers_sent:
            logger.warning('Staring late response on websocket')
            status_text = STATUS_CODE_TEXT.get(response.status_code, 'UNKNOWN STATUS CODE')
            status = '{0} {1}'.format(response.status_code, status_text)
            start_response(force_str(status), response._headers.values())
        logger.info('Finish long living response with status code: '.format(response.status_code))
        return response


text:
import { Vector3 } from "three"
import { AttributeTypes, AttributeTypeValue, CodeMapNode, Edge, MarkedPackage, RecursivePartial, Settings } from "./codeCharta.model"

export interface ExportCCFile {
	projectName: string
	apiVersion: string
	fileChecksum: string
	nodes: CodeMapNode[]
	attributeTypes?: AttributeTypes | OldAttributeTypes
	edges?: Edge[]
	markedPackages?: MarkedPackage[]
	blacklist?: ExportBlacklistItem[]
	repoCreationDate?: string
}

export interface ExportWrappedCCFile {
	checksum: string
	data: ExportCCFile
}

export interface ExportBlacklistItem {
	path: string
	type: ExportBlacklistType
}

export enum ExportBlacklistType {
	hide = "hide",
	exclude = "exclude"
}

export enum APIVersions {
	ZERO_POINT_ONE = "0.1",
	ONE_POINT_ZERO = "1.0",
	ONE_POINT_ONE = "1.1",
	ONE_POINT_TWO = "1.2",
	ONE_POINT_THREE = "1.3"
}

export interface ExportScenario {
	name: string
	settings: RecursivePartial<Settings>
	camera?: {
		camera: Vector3
		cameraTarget: Vector3
	}
}

export interface OldAttributeTypes {
	nodes?: [{ [key: string]: AttributeTypeValue }?]
	edges?: [{ [key: string]: AttributeTypeValue }?]
}


text:
import * as stationxml from '../../src/stationxml.js';

test( "_grabFirstEl test", () => {
  const LATITUDE = "Latitude";
  let xml = new DOMParser().parseFromString(rawXML, "text/xml")
    .documentElement;
  let net = stationxml.parseUtil._grabFirstEl(xml, "Network");
  expect(net).toBeDefined();
  let sta = stationxml.parseUtil._grabFirstEl(net, "Station");
  expect(sta).toBeDefined();
  let lat = stationxml.parseUtil._grabFirstEl(sta, LATITUDE);
  expect(lat).toBeDefined();
  if (lat){
    // always true, just for flow
    expect(lat.textContent).toBe("34.2818");
    expect(stationxml.parseUtil._grabFirstElText(sta, LATITUDE)).toBe("34.2818");
    expect(stationxml.parseUtil._grabFirstElFloat(sta, LATITUDE)).toBe(34.2818);
  }
});

const rawXML = `<?xml version="1.0" encoding="ISO-8859-1"?>

<FDSNStationXML xmlns="http://www.fdsn.org/xml/station/1" schemaVersion="1.0" xsi:schemaLocation="http://www.fdsn.org/xml/station/1 http://www.fdsn.org/xml/station/fdsn-station-1.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:iris="http://www.fdsn.org/xml/station/1/iris">
 <Source>IRIS-DMC</Source>
 <Sender>IRIS-DMC</Sender>
 <Module>IRIS WEB SERVICE: fdsnws-station | version: 1.1.33</Module>
 <ModuleURI>http://service.iris.edu/fdsnws/station/1/query?level=station&net=TA%2CCO&sta=109C%2CJSC</ModuleURI>
 <Created>2018-06-01T12:29:16</Created>
 <Network code="CO" startDate="1987-01-01T00:00:00" endDate="2500-12-31T23:59:59" restrictedStatus="open">
  <Description>South Carolina Seismic Network</Description>
  <TotalNumberStations>14</TotalNumberStations>
  <SelectedNumberStations>1</SelectedNumberStations>
  <Station code="JSC" startDate="2009-04-13T00:00:00" endDate="2599-12-31T23:59:59" restrictedStatus="open" iris:alternateNetworkCodes="_CEUSN,.GREG,.CEUSN-CONTRIB,_US-REGIONAL,_REALTIME,.UNRESTRICTED">
   <Latitude>34.2818</Latitude>
   <Longitude>-81.25966</Longitude>
   <Elevation>103.0</Elevation>
   <Site>
    <Name>Jenkinsville, South Carolina</Name>
   </Site>
   <CreationDate>2009-04-13T00:00:00</CreationDate>
   <TotalNumberChannels>78</TotalNumberChannels>
   <SelectedNumberChannels>0</SelectedNumberChannels>
  </Station>
 </Network>
 <Network code="TA" startDate="2003-01-01T00:00:00" endDate="2500-12-31T23:59:59" restrictedStatus="open">
  <Description>USArray Transportable Array (NSF EarthScope Project)</Description>
  <TotalNumberStations>1890</TotalNumberStations>
  <SelectedNumberStations>1</SelectedNumberStations>
  <Station code="109C" startDate="2004-05-04T00:00:00" endDate="2599-12-31T23:59:59" restrictedStatus="open" iris:alternateNetworkCodes="_US-ALL,.EARTHSCOPE,_US-TA,_REALTIME,.UNRESTRICTED">
   <Latitude>32.8889</Latitude>
   <Longitude>-117.1051</Longitude>
   <Elevation>150.0</Elevation>
   <Site>
    <Name>Camp Elliot, Miramar, CA, USA</Name>
   </Site>
   <CreationDate>2004-05-04T00:00:00</CreationDate>
   <TotalNumberChannels>172</TotalNumberChannels>
   <SelectedNumberChannels>0</SelectedNumberChannels>
  </Station>
 </Network>
</FDSNStationXML>`;


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.facebook.react.uiapp"
  android:versionCode="1"
  android:versionName="1.0">

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.VIBRATE"/>

  <uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="22" />

  <application
      android:allowBackup="true"
      android:icon="@drawable/launcher_icon"
      android:label="@string/app_name"
      android:theme="@style/Theme.ReactNative.AppCompat.Light" >
    <activity
        android:name=".UIExplorerActivity"
        android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Accepts URIs that begin with "rnuiexplorer://example" -->
        <data android:scheme="rnuiexplorer" android:host="example" />
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
  </application>

</manifest>