text:
namespace spvtest {

// RAII for spv_context.
struct ScopedContext {
  ScopedContext(spv_target_env env = SPV_ENV_UNIVERSAL_1_0)
      : context(spvContextCreate(env)) {}
  ~ScopedContext() { spvContextDestroy(context); }
  spv_context context;
};

// Common setup for TextToBinary tests. SetText() should be called to populate
// the actual test text.
template <typename T>
class TextToBinaryTestBase : public T {
 public:
  // Shorthand for SPIR-V compilation result.
  using SpirvVector = std::vector<uint32_t>;

  // Offset into a SpirvVector at which the first instruction starts.
  static const SpirvVector::size_type kFirstInstruction = 5;

  TextToBinaryTestBase() : diagnostic(nullptr), text(), binary(nullptr) {
    char textStr[] = "substitute the text member variable with your test";
    text = {textStr, strlen(textStr)};
  }

  ~TextToBinaryTestBase() override {
    DestroyBinary();
    if (diagnostic) spvDiagnosticDestroy(diagnostic);
  }

  // Returns subvector v[from:end).
  SpirvVector Subvector(const SpirvVector& v, SpirvVector::size_type from) {
    assert(from <= v.size());
    return SpirvVector(v.begin() + from, v.end());
  }

  // Compiles SPIR-V text in the given assembly syntax format, asserting
  // compilation success. Returns the compiled code.
  SpirvVector CompileSuccessfully(const std::string& txt,
                                  spv_target_env env = SPV_ENV_UNIVERSAL_1_0) {
    DestroyBinary();
    DestroyDiagnostic();
    spv_result_t status =
        spvTextToBinary(ScopedContext(env).context, txt.c_str(), txt.size(),
                        &binary, &diagnostic);
    EXPECT_EQ(SPV_SUCCESS, status) << txt;
    SpirvVector code_copy;
    if (status == SPV_SUCCESS) {
      code_copy = SpirvVector(binary->code, binary->code + binary->wordCount);
      DestroyBinary();
    } else {
      spvDiagnosticPrint(diagnostic);
    }
    return code_copy;
  }

  // Compiles SPIR-V text with the given format, asserting compilation failure.
  // Returns the error message(s).
  std::string CompileFailure(const std::string& txt,
                             spv_target_env env = SPV_ENV_UNIVERSAL_1_0) {
    DestroyBinary();
    DestroyDiagnostic();
    EXPECT_NE(SPV_SUCCESS,
              spvTextToBinary(ScopedContext(env).context, txt.c_str(),
                              txt.size(), &binary, &diagnostic))
        << txt;
    DestroyBinary();
    return diagnostic->error;
  }

  // Potentially flip the words in the binary representation to the other
  // endianness
  template <class It>
  void MaybeFlipWords(bool flip_words, It begin, It end) {
    SCOPED_TRACE(flip_words ? "Flipped Endianness" : "Normal Endianness");
    if (flip_words) {
      std::transform(begin, end, begin, [](const uint32_t raw_word) {
        return spvFixWord(raw_word, I32_ENDIAN_HOST == I32_ENDIAN_BIG
                                        ? SPV_ENDIANNESS_LITTLE
                                        : SPV_ENDIANNESS_BIG);
      });
    }
  }

  // Encodes SPIR-V text into binary and then decodes the binary using
  // given options. Returns the decoded text.
  std::string EncodeAndDecodeSuccessfully(
      const std::string& txt,
      uint32_t disassemble_options = SPV_BINARY_TO_TEXT_OPTION_NONE,
      spv_target_env env = SPV_ENV_UNIVERSAL_1_0, bool flip_words = false) {
    DestroyBinary();
    DestroyDiagnostic();
    ScopedContext context(env);
    disassemble_options |= SPV_BINARY_TO_TEXT_OPTION_NO_HEADER;
    spv_result_t error = spvTextToBinary(context.context, txt.c_str(),
                                         txt.size(), &binary, &diagnostic);
    if (error) {
      spvDiagnosticPrint(diagnostic);
      spvDiagnosticDestroy(diagnostic);
    }
    EXPECT_EQ(SPV_SUCCESS, error);
    if (!binary) return "";

    MaybeFlipWords(flip_words, binary->code, binary->code + binary->wordCount);

    spv_text decoded_text;
    error = spvBinaryToText(context.context, binary->code, binary->wordCount,
                            disassemble_options, &decoded_text, &diagnostic);
    if (error) {
      spvDiagnosticPrint(diagnostic);
      spvDiagnosticDestroy(diagnostic);
    }
    EXPECT_EQ(SPV_SUCCESS, error) << txt;

    const std::string decoded_string = decoded_text->str;
    spvTextDestroy(decoded_text);

    return decoded_string;
  }

  // Encodes SPIR-V text into binary. This is expected to succeed.
  // The given words are then appended to the binary, and the result
  // is then decoded. This is expected to fail.
  // Returns the error message.
  std::string EncodeSuccessfullyDecodeFailed(
      const std::string& txt, const SpirvVector& words_to_append) {
    DestroyBinary();
    DestroyDiagnostic();
    SpirvVector code =
        spvtest::Concatenate({CompileSuccessfully(txt), words_to_append});

    spv_text decoded_text;
    EXPECT_NE(SPV_SUCCESS,
              spvBinaryToText(ScopedContext().context, code.data(), code.size(),
                              SPV_BINARY_TO_TEXT_OPTION_NONE, &decoded_text,
                              &diagnostic));
    if (diagnostic) {
      std::string error_message = diagnostic->error;
      spvDiagnosticDestroy(diagnostic);
      diagnostic = nullptr;
      return error_message;
    }
    return "";
  }

  // Compiles SPIR-V text, asserts success, and returns the words representing
  // the instructions.  In particular, skip the words in the SPIR-V header.
  SpirvVector CompiledInstructions(const std::string& txt,
                                   spv_target_env env = SPV_ENV_UNIVERSAL_1_0) {
    const SpirvVector code = CompileSuccessfully(txt, env);
    SpirvVector result;
    // Extract just the instructions.
    // If the code fails to compile, then return the empty vector.
    // In any case, don't crash or invoke undefined behaviour.
    if (code.size() >= kFirstInstruction)
      result = Subvector(code, kFirstInstruction);
    return result;
  }

  void SetText(const std::string& code) {
    textString = code;
    text.str = textString.c_str();
    text.length = textString.size();
  }

  // Destroys the binary, if it exists.
  void DestroyBinary() {
    spvBinaryDestroy(binary);
    binary = nullptr;
  }

  // Destroys the diagnostic, if it exists.
  void DestroyDiagnostic() {
    spvDiagnosticDestroy(diagnostic);
    diagnostic = nullptr;
  }

  spv_diagnostic diagnostic;

  std::string textString;
  spv_text_t text;
  spv_binary binary;
};

using TextToBinaryTest = TextToBinaryTestBase<::testing::Test>;
}  // namespace spvtest

using RoundTripTest =
    spvtest::TextToBinaryTestBase<::testing::TestWithParam<std::string>>;

#endif  // TEST_TEST_FIXTURE_H_


text:
//------------------------------------------------------------------------------
// <copyright file="ColorMapType.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Drawing.Imaging {

    using System.Diagnostics;

    using System.Drawing;
    using System;

    /**
     * Color Map type constants
     */
    /// <include file='doc\ColorMapType.uex' path='docs/doc[@for="ColorMapType"]/*' />
    /// <devdoc>
    ///    Specifies the types of color maps.
    /// </devdoc>
    public enum ColorMapType
    {
        /// <include file='doc\ColorMapType.uex' path='docs/doc[@for="ColorMapType.Default"]/*' />
        /// <devdoc>
        ///    A default color map.
        /// </devdoc>
        Default = 0,
        /// <include file='doc\ColorMapType.uex' path='docs/doc[@for="ColorMapType.Brush"]/*' />
        /// <devdoc>
        ///    Specifies a color map for a <see cref='System.Drawing.Brush'/>.
        /// </devdoc>
        Brush
    }
}

redpajama_set_name: RedPajamaGithub


text:
package gudusoft.gsqlparser.sql2xml.model;

public class time_zone
{

}


text:
#pragma once
#include <aws/codecommit/CodeCommit_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/codecommit/model/RepositoryTrigger.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CodeCommit
{
namespace Model
{
  /**
   *
Represents the output of a get repository triggers operation.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_CODECOMMIT_API GetRepositoryTriggersResult
  {
  public:
    GetRepositoryTriggersResult();
    GetRepositoryTriggersResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetRepositoryTriggersResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline const Aws::String& GetConfigurationId() const{ return m_configurationId; }

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline void SetConfigurationId(const Aws::String& value) { m_configurationId = value; }

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline void SetConfigurationId(Aws::String&& value) { m_configurationId = std::move(value); }

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline void SetConfigurationId(const char* value) { m_configurationId.assign(value); }

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline GetRepositoryTriggersResult& WithConfigurationId(const Aws::String& value) { SetConfigurationId(value); return *this;}

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline GetRepositoryTriggersResult& WithConfigurationId(Aws::String&& value) { SetConfigurationId(std::move(value)); return *this;}

    /**
     *
The system-generated unique ID for the trigger.

     */
    inline GetRepositoryTriggersResult& WithConfigurationId(const char* value) { SetConfigurationId(value); return *this;}

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline const Aws::Vector<RepositoryTrigger>& GetTriggers() const{ return m_triggers; }

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline void SetTriggers(const Aws::Vector<RepositoryTrigger>& value) { m_triggers = value; }

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline void SetTriggers(Aws::Vector<RepositoryTrigger>&& value) { m_triggers = std::move(value); }

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline GetRepositoryTriggersResult& WithTriggers(const Aws::Vector<RepositoryTrigger>& value) { SetTriggers(value); return *this;}

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline GetRepositoryTriggersResult& WithTriggers(Aws::Vector<RepositoryTrigger>&& value) { SetTriggers(std::move(value)); return *this;}

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline GetRepositoryTriggersResult& AddTriggers(const RepositoryTrigger& value) { m_triggers.push_back(value); return *this; }

    /**
     *
The JSON block of configuration information for each trigger.

     */
    inline GetRepositoryTriggersResult& AddTriggers(RepositoryTrigger&& value) { m_triggers.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_configurationId;

    Aws::Vector<RepositoryTrigger> m_triggers;
  };

} // namespace Model
} // namespace CodeCommit
} // namespace Aws


text:
import os
import sys
import transaction

from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )

from pyramid.scripts.common import parse_vars

from ..models.meta import Base
from ..models import (
    get_engine,
    get_session_factory,
    get_tm_session,
    )

from python_learning_journal.models.entries import Entry
from python_learning_journal.entry.data import JOURNAL_ENTRIES
from datetime import datetime

def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\n'
          '(example: "%s development.ini")' % (cmd, cmd))
    sys.exit(1)

def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL')

    engine = get_engine(settings)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
# ==== The below is not needed but will get your server running ====
    session_factory = get_session_factory(engine)

    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)

        models = []
        for item in JOURNAL_ENTRIES:
            new_entry = Entry(
                title=item['title'],
                entry=item["entry"],
                creation_date=datetime.now(),
            )
            models.append(new_entry)
        dbsession.add_all(models)


text:
package com.justplay1.shoppist.interactor.category;

import com.justplay1.shoppist.executor.PostExecutionThread;
import com.justplay1.shoppist.executor.ThreadExecutor;
import com.justplay1.shoppist.repository.CategoryRepository;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Collections;

import rx.Observable;

import static com.justplay1.shoppist.ModelUtil.createFakeCategoryModel;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

public class GetCategoryListTest {

    private GetCategoryList useCase;

    @Mock private ThreadExecutor mockThreadExecutor;
    @Mock private PostExecutionThread mockPostExecutionThread;
    @Mock private CategoryRepository mockCategoryRepository;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        useCase = new GetCategoryList(mockCategoryRepository, mockThreadExecutor,
                mockPostExecutionThread);
    }

    @Test
    public void getCategoryListUseCase_HappyCase() {
        when(useCase.buildUseCaseObservable()).thenReturn(Observable.just(Collections.singletonList(createFakeCategoryModel())));
        useCase.buildUseCaseObservable();

        verify(mockCategoryRepository).getItems();
        verifyNoMoreInteractions(mockCategoryRepository);
        verifyZeroInteractions(mockThreadExecutor);
        verifyZeroInteractions(mockPostExecutionThread);
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.LIBRADOS_CMPXATTR_OP_LT.html">

Redirecting to constant.LIBRADOS_CMPXATTR_OP_LT.html...


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.ruslan.towncare.LoginActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/createAccountTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="@string/create_account"
        android:textAlignment="center"
        android:textSize="40sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:labelFor="@+id/createAccountUserEmail"
            android:text="@string/login_user_email"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/createAccountUserEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="textEmailAddress" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:labelFor="@+id/createAccountPassword"
            android:text="@string/login_password"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/createAccountPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="textPassword" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:labelFor="@+id/createAccountId"
            android:text="@string/Id"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/createAccountId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="number" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:labelFor="@+id/createAccountTown"
            android:text="@string/town"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/createAccountTown"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="text" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:labelFor="@+id/createAccountPhone"
            android:text="@string/phone"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/createAccountPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="phone" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"

            android:orientation="horizontal">

            <Button
                android:id="@+id/createAccountRegisterButton"
                android:layout_width="1dp"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@string/register" />

            <Button
                android:id="@+id/createAccountCancelButton"
                android:layout_width="1dp"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@string/cancel" />

        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
package com.talent.nio.communicate.handler.intf;

import com.talent.nio.api.Packet;
import com.talent.nio.communicate.ChannelContext;

/**
 *
 * @author 谭耀武
 * @date 2011-12-27
 *
 */
public interface PacketHandlerIntf
{
    /**
     *
     * 在发送消息前,将消息序列化(如果没有特殊需求,一般不需要实现此方法,直接return null即可。)
     *
     * @param packet
     * @return
     * @throws Exception
     */
    byte[] onSend(Packet packet, ChannelContext channelContext) throws Exception;

    /**
     *
     * 处理接收到的消息
     *
     * @param packet
     * @throws Exception
     */
    void onReceived(Packet packet, ChannelContext channelContext) throws Exception;
}


text:
require 'spec_helper'

describe SubclassedPagesController do

  render_views

  describe "on GET to /subclassed_pages/also_exists" do
    before { get :show, :id => 'also_exists' }

    it "should respond with success and render template" do
      response.should be_success
      response.should render_template('also_exists')
    end

    it "should use the custom configured layout" do
      response.should_not render_template("layouts/application")
      response.should render_template('layouts/alternate')
    end
  end

  describe "on GET to /subclassed_pages/also_dir/nested" do
    before { get :show, :id => 'also_dir/also_nested' }

    it "should respond with success and render template" do
      response.should be_success
      response.should render_template('other_pages/also_dir/also_nested')
    end
  end

  it "should raise a routing error for an invalid page" do
    lambda { get :show, :id => "invalid" }.should raise_error(ActionController::RoutingError)
  end

  it "should raise a routing error for a page in another directory" do
    lambda { get :show, :id => "../other/wrong" }.should raise_error(ActionController::RoutingError)
  end

  it "should raise missing template error for valid page with invalid partial" do
    lambda { get :show, :id => "also_exists_but_references_nonexistent_partial" }.should raise_error(ActionView::MissingTemplate)
  end
end


text:
import { AppPage } from './app.po';

describe('dependency-injection App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!');
  });
});


text:
/*global rg2:false */
/*global rg2Config:false */
// handle drawing of a new route
(function () {
  function Draw() {
    this.trackColor = '#ff0000';
    this.hasResults = false;
    this.routeToDelete = null;
    this.initialiseDrawing();
  }

  Draw.prototype = {
    Constructor : Draw,

    gpsFileLoaded : function () {
      return this.gpstrack.fileLoaded;
    },

    autofitGPSTrack : function () {
      this.gpstrack.autofitTrack();
    },

    adjustOffset : function (offset) {
      this.gpstrack.adjustOffset(offset);
    },

    uploadGPS : function (evt) {
      this.gpstrack.uploadGPS(evt);
    },

    getControlXY : function () {
      return {x: this.controlx, y: this.controly};
    },

    mouseUp : function (x, y, button) {
      // console.log(x, y);
      var i, trk, len, delta, handle, active;
      // called after a click at (x, y)
      active = $("#rg2-info-panel").tabs("option", "active");
      delta = 3;
      if (active !== rg2.config.TAB_DRAW) {
        return;
      }
      trk = this.gpstrack;
      if (trk.fileLoaded) {
        handle = trk.handles.getHandleClicked({x: x, y: y});
        if (handle !== undefined) {
          // delete or unlock if not first or last entry
          if ((button === rg2.config.RIGHT_CLICK) && (handle.index !== 0) && (handle.index !== trk.handles.length)) {
            if (handle.locked) {
              // unlock, don't delete
              trk.handles.unlockHandle(handle.index);
            } else {
              // delete handle
              trk.handles.deleteHandle(handle.index);
            }
          } else {
            // clicked in a handle area so toggle state
            if (handle.locked) {
              trk.handles.unlockHandle(handle.index);
            } else {
              trk.handles.lockHandle(handle.index);
            }
          }
        } else {
          // not an existing handle so read through track to look for x,y
          len = trk.baseX.length;
          for (i = 0; i < len; i += 1) {
            if ((trk.baseX[i] + delta >= x) && (trk.baseX[i] - delta <= x) && (trk.baseY[i] + delta >= y) && (trk.baseY[i] - delta <= y)) {
              // found on track so add new handle
              trk.handles.addHandle(x, y, i);
              break;
            }
          }
        }
      } else {
        // drawing new track
        // only allow drawing if we have valid name and course
        if ((trk.routeData.resultid !== null) && (trk.routeData.courseid !== null)) {
          this.addNewPoint(x, y);
        } else {
          rg2.utils.showWarningDialog('No course/name', 'Please select course, name and time before you start drawing a route or upload a file.');
        }
      }
    },

    dragEnded : function () {
      var trk;
      if (this.gpstrack.fileLoaded) {
        trk = this.gpstrack;
        // rebaseline GPS track
        trk.savedBaseX = trk.baseX.slice(0);
        trk.savedBaseY = trk.baseY.slice(0);
        trk.baseX = trk.routeData.x.slice(0);
        trk.baseY = trk.routeData.y.slice(0);
        trk.handles.saveForUndo();
        trk.handles.rebaselineXY();
        $("#btn-undo-gps-adjust").button("enable");
      }
    },

    initialiseDrawing : function () {
      this.gpstrack = new rg2.GPSTrack();
      this.gpstrack.routeData = new rg2.RouteData();
      this.pendingCourseID = null;
      // the RouteData versions of these have the start control removed for saving
      this.controlx = [];
      this.controly = [];
      this.angles = [];
      this.nextControl = 0;
      this.previousValidControlIndex = 0;
      this.isScoreCourse = false;
      this.gpstrack.initialiseGPS();
      this.hasResults = rg2.events.hasResults();
      this.initialiseUI();
      rg2.redraw(false);
    },

    initialiseUI : function () {
      rg2.courses.updateCourseDropdown();
      if (this.hasResults) {
        $("#rg2-select-name").show();
        $("#rg2-enter-name").hide();
      } else {
        $("#rg2-select-name").hide();
        $("#rg2-enter-name").show();
      }
      $("#rg2-name-select").prop('disabled', true);
      $("#rg2-undo").prop('disabled', true);
      $("#btn-reset-drawing").button("enable");
      rg2.utils.setButtonState("disable", ["#btn-save-route", "#btn-save-gps-route", "#btn-undo", "#btn-three-seconds", "#rg2-load-gps-file", "#rg2-autofit-gps"]);
      $("#rg2-name-select").empty();
      $("#rg2-new-comments").empty().val(rg2.t(rg2.config.DEFAULT_NEW_COMMENT));
      $("#rg2-event-comments").empty().val(rg2.t(rg2.config.DEFAULT_EVENT_COMMENT));
      $("#btn-move-all").prop('checked', false);
      $("#rg2-name-entry").empty().val('');
      $("#rg2-time-entry").empty().val('');
      $("#rg2-name").removeClass('valid');
      $("#rg2-time").removeClass('valid');
    },

    setCourse : function (courseid) {
      if (!isNaN(courseid)) {
        if (this.gpstrack.routeData.courseid !== null) {
          // already have a course so we are trying to change it
          if (this.gpstrack.routeData.x.length > 1) {
            // drawing started so ask to confirm change
            this.pendingCourseid = courseid;
            this.confirmCourseChange();
          } else {
            // nothing done yet so just change course
            if (this.gpstrack.routeData.resultid !== null) {
              rg2.results.putScoreCourseOnDisplay(this.gpstrack.routeData.resultid, false);
            }
            rg2.courses.removeFromDisplay(this.gpstrack.routeData.courseid);
            this.initialiseCourse(courseid);
          }
        } else {
          // first time course has been selected
          this.initialiseCourse(courseid);
        }
      }
    },

    initialiseCourse : function (courseid) {
      var course;
      this.gpstrack.routeData.eventid = rg2.events.getKartatEventID();
      this.gpstrack.routeData.courseid = courseid;
      course = rg2.courses.getCourseDetails(courseid);
      this.isScoreCourse = course.isScoreCourse;
      // save details for normal courses
      // can't do this here for score courses since you need to know the
      // variant for a given runner
      if (!this.isScoreCourse) {
        rg2.courses.putOnDisplay(courseid);
        this.gpstrack.routeData.coursename = course.name;
        this.controlx = course.x;
        this.controly = course.y;
        this.gpstrack.routeData.x.length = 0;
        this.gpstrack.routeData.y.length = 0;
        this.gpstrack.routeData.x[0] = this.controlx[0];
        this.gpstrack.routeData.y[0] = this.controly[0];
        this.gpstrack.routeData.controlx = this.controlx;
        this.gpstrack.routeData.controly = this.controly;
        this.angles = course.angle;
      }
      rg2.results.createNameDropdown(courseid);
      $("#rg2-name-select").prop('disabled', false);
      //MaB reset controls
      //TODO clear GPS selections
      $("#rg2-load-gps-file").val('').button("disable");
      $("#btn-autofit-gps").button("disable");
      this.gpstrack.autofitOffset = null;
      $("#spn-offset").spinner("value", 0).spinner("disable");
      $("#btn-undo-gps-adjust").button("disable");
      rg2.redraw(false);
    },

    doDrawingReset : function () {
      $('#rg2-drawing-reset-dialog').dialog("destroy");
      if (this.gpstrack.routeData.courseid !== null) {
        rg2.courses.removeFromDisplay(this.gpstrack.routeData.courseid);
      }
      if (this.gpstrack.routeData.resultid !== null) {
        rg2.results.putScoreCourseOnDisplay(this.gpstrack.routeData.resultid, false);
      }
      this.pendingCourseid = null;
      this.initialiseDrawing();
    },

    doCancelDrawingReset : function () {
      $('#rg2-drawing-reset-dialog').dialog("destroy");
    },

    confirmCourseChange : function () {
      var dlg;
      dlg = {};
      dlg.selector = "
The route you have started to draw will be discarded. Are you sure you want to change the course?
";
      dlg.title = "Confirm course change";
      dlg.classes = "rg2-confirm-change-course";
      dlg.doText = "Change course";
      dlg.onDo = this.doChangeCourse.bind(this);
      dlg.onCancel = this.doCancelChangeCourse.bind(this);
      rg2.utils.createModalDialog(dlg);
    },

    resetDrawing : function () {
      var dlg;
      dlg = {};
      dlg.selector = "
All information you have entered will be removed. Are you sure you want to reset?
";
      dlg.title = "Confirm reset";
      dlg.classes = "rg2-confirm-drawing-reset";
      dlg.doText = "Reset";
      dlg.onDo = this.doDrawingReset.bind(this);
      dlg.onCancel = this.doCancelDrawingReset.bind(this);
      rg2.utils.createModalDialog(dlg);
    },

    doChangeCourse : function () {
      $('#rg2-course-change-dialog').dialog("destroy");
      rg2.courses.removeFromDisplay(this.gpstrack.routeData.courseid);
      if (this.gpstrack.routeData.resultid !== null) {
        rg2.results.putScoreCourseOnDisplay(this.gpstrack.routeData.resultid, false);
      }
      this.doDrawingReset();
      this.initialiseCourse(this.pendingCourseid);
    },

    doCancelChangeCourse : function () {
      // reset course dropdown
      $("#rg2-course-select").val(this.gpstrack.routeData.courseid);
      this.pendingCourseid = null;
      $('#rg2-course-change-dialog').dialog("destroy");
    },

    showCourseInProgress : function () {
      if (this.gpstrack.routeData.courseid !== null) {
        if (this.isScoreCourse) {
          rg2.results.putScoreCourseOnDisplay(this.gpstrack.routeData.resultid, true);
        } else {
          rg2.courses.putOnDisplay(this.gpstrack.routeData.courseid);
        }
      }
    },

    setName : function (resultid) {
      // callback from select box when we have results
      var res, msg;
      if (!isNaN(resultid)) {
        res = rg2.results.getFullResult(resultid);
        if (res.hasValidTrack) {
          msg = rg2.t("If you draw a new route it will overwrite the old route for this runner.") + " " + rg2.t("GPS routes are saved separately and will not be overwritten.");
          rg2.utils.showWarningDialog(rg2.t("Route already drawn"), msg);
        }
        // remove old course from display just in case we missed it somewhere else
        if (this.gpstrack.routeData.resultid !== null) {
          rg2.results.putScoreCourseOnDisplay(this.gpstrack.routeData.resultid, false);
        }
        this.gpstrack.routeData.resultid = res.resultid;
        this.gpstrack.routeData.name = res.name;
        this.gpstrack.routeData.splits = res.splits;
        // set up individual course if this is a score event
        if (this.isScoreCourse) {
          rg2.results.putScoreCourseOnDisplay(res.resultid, true);
          this.controlx = res.scorex;
          this.controly = res.scorey;
          this.gpstrack.routeData.x.length = 0;
          this.gpstrack.routeData.y.length = 0;
          this.gpstrack.routeData.x[0] = this.controlx[0];
          this.gpstrack.routeData.y[0] = this.controly[0];
          this.gpstrack.routeData.controlx = this.controlx;
          this.gpstrack.routeData.controly = this.controly;
          this.nextControl = 1;
          rg2.redraw(false);
        } else {
          this.nextControl = this.getNextValidControl(0);
          this.previousValidControlIndex = 0;
        }
        // resetting it here avoids trying to start drawing before selecting
        // a name, which is always what happened when testing the prototype
        this.alignMapToAngle(0);
        this.startDrawing();
      }
    },

    setNameAndTime : function () {
      // callback for an entered name when no results available
      var time, name, distanceSoFar, length, splits, i;
      name = $("#rg2-name-entry").val();
      if (name) {
        $("#rg2-name").addClass('valid');
      } else {
        $("#rg2-name").removeClass('valid');
      }
      time = $("#rg2-time-entry").val();
      // matches something like 0:00 to 999:59
      if (time.match(/\d+[:.][0-5]\d$/)) {
        $("#rg2-time").addClass('valid');
      } else {
        $("#rg2-time").removeClass('valid');
        time = null;
      }
      if (name && time) {
        time = time.replace(".", ":");
        this.gpstrack.routeData.name = name;
        this.gpstrack.routeData.resultid = 0;
        this.gpstrack.routeData.totaltime = time;
        this.gpstrack.routeData.startsecs = 0;
        this.gpstrack.routeData.time[0] = rg2.utils.getSecsFromHHMMSS(time);
        this.gpstrack.routeData.totalsecs = rg2.utils.getSecsFromHHMMSS(time);
        this.nextControl = 1;
        distanceSoFar = rg2.courses.getCourseLegLengths(this.gpstrack.routeData.courseid);
        length = distanceSoFar[distanceSoFar.length - 1];
        // generate pro rata splits
        splits = [];
        for (i = 0; i < distanceSoFar.length; i = i + 1) {
          splits[i] = parseInt((distanceSoFar[i] / length * this.gpstrack.routeData.totalsecs), 10);
        }
        this.gpstrack.routeData.splits = splits;
        this.previousValidControlIndex = 0;
        rg2.redraw(false);
        this.startDrawing();
      }
    },

    startDrawing : function () {
      $("#btn-three-seconds").button('enable');
      // setting value to null allows you to open the same file again if needed
      $("#rg2-load-gps-file").val(null).button('enable');
      rg2.redraw(false);
    },

    alignMapToAngle : function (control) {
      var angle;
      if (rg2.options.alignMap) {
        // don't adjust after we have got to the finish
        if (control < (this.controlx.length - 1)) {
          if (this.isScoreCourse) {
            // need to calculate this here since score courses use variants for
            // each person, not single courses
            angle = rg2.utils.getAngle(this.controlx[control], this.controly[control],
              this.controlx[control + 1], this.controly[control + 1]);
          } else {
            angle = this.angles[control];
          }
          // course angles are based on horizontal as 0: need to reset to north
          rg2.alignMap(angle  + (Math.PI / 2), this.controlx[control], this.controly[control]);
        } else {
          //MaB reset map
          rg2.resetMapState();
        }
      }
    },

    addNewPoint : function (x, y) {
      if (this.closeEnough(x, y)) {
        this.addRouteDataPoint(this.controlx[this.nextControl], this.controly[this.nextControl]);
        // angles will be wrong for missing splits since we don't know angles between non-consecutive controls and I
        // don't intend to start calculating them now...
        this.alignMapToAngle(this.nextControl);
        this.previousValidControlIndex = this.nextControl;
        this.nextControl = this.getNextValidControl(this.nextControl);
        if (this.nextControl === this.controlx.length) {
          $("#btn-save-route").button("enable");
        }
      } else {
        this.addRouteDataPoint(Math.round(x), Math.round(y));
      }
      $("#btn-undo").button("enable");
      rg2.redraw(false);
    },

    getNextValidControl : function (thisControl) {
      // look through splits to find next control which has a split time
      // to allow drawing for missed controls where the split time is 0
      var i, splits;
      splits = this.gpstrack.routeData.splits;
      // allow for events with no results: splits will be a start and finish time only
      // in this case just move to next control
      if (splits.length === 2) {
        return thisControl + 1;
      }
      for (i = thisControl + 1; i < splits.length; i += 1) {
        if (splits[i] !== splits[i - 1]) {
          return i;
        }
      }
      // implies we have no finish time which is unlikely but anyway...
      return splits.length;
    },

    getPreviousValidControl : function (thisControl) {
      // look through splits to find previous control which has a split time
      // to allow drawing for missed controls where the split time is 0
      var i, splits;
      splits = this.gpstrack.routeData.splits;
      // allow for events with no results: splits will be a start and finish time only
      // in this case just move to previous control
      if (splits.length === 2) {
        return thisControl - 1;
      }
      for (i = thisControl - 1; i > 0; i -= 1) {
        if (splits[i] !== splits[i - 1]) {
          return i;
        }
      }
      // go back to start...
      return 0;
    },

    addRouteDataPoint : function (x, y) {
      this.gpstrack.routeData.x.push(x);
      this.gpstrack.routeData.y.push(y);
    },

    undoGPSAdjust : function () {
      // restore route from before last adjust operation
      var trk;
      trk = this.gpstrack;
      trk.baseX = trk.savedBaseX.slice(0);
      trk.baseY = trk.savedBaseY.slice(0);
      trk.routeData.x = trk.savedBaseX.slice(0);
      trk.routeData.y = trk.savedBaseY.slice(0);
      trk.handles.undo();
      //MaB enable button
      $("#btn-autofit-gps").button("enable");
      //this.gpstrack.autofitOffset = null;
      //$("#spn-offset").spinner("value", 0).spinner("disable");
      $("#btn-undo-gps-adjust").button("disable");
      rg2.redraw(false);
    },

    undoLastPoint : function () {
      // remove last point if we have one
      var points = this.gpstrack.routeData.x.length;
      if (points > 1) {
        // are we undoing from previous control?
        if ((this.controlx[this.previousValidControlIndex] === this.gpstrack.routeData.x[points - 1]) && (this.controly[this.previousValidControlIndex] === this.gpstrack.routeData.y[points - 1])) {
          // are we undoing from the finish?
          if (this.nextControl === this.controlx.length) {
            $("#btn-save-route").button("disable");
          }
          this.nextControl = this.previousValidControlIndex;
          this.previousValidControlIndex = this.getPreviousValidControl(this.nextControl);
          this.alignMapToAngle(this.nextControl - 1);
        }
        this.gpstrack.routeData.x.pop();
        this.gpstrack.routeData.y.pop();
      }
      // note that array length has changed so can't use points
      if (this.gpstrack.routeData.x.length > 1) {
        $("#btn-undo").button("enable");
      } else {
        $("#btn-undo").button("disable");
      }
      rg2.redraw(false);
    },

    saveGPSRoute : function () {
      // called to save GPS file route
      // tidy up route details
      //MaB improved GPS offset calculations
      var i, l, t, date, offset, text, autofitOffset, fitOffset, courseData, splitTime, routeLength;

      // set start time by auto fit offset
      autofitOffset = this.gpstrack.autofitOffset;
      if (autofitOffset === undefined || autofitOffset === null) {
        autofitOffset = 0;
      }
      if (autofitOffset < 0) {
        // calculate time offset from autofit position
        fitOffset = this.gpstrack.routeData.time[0] + autofitOffset;
      } else {
        fitOffset = this.gpstrack.routeData.time[autofitOffset];
      }

      // GPS uses UTC: adjust to local time based on local user setting
      // only affects replay in real time
      date = new Date();
      // returns offset in minutes, so convert to seconds
      offset = date.getTimezoneOffset() * 60;
      //MaB
      this.gpstrack.routeData.startsecs = fitOffset - offset;
      courseData = rg2.courses.getCourseDetails(this.gpstrack.routeData.courseid);
      if (autofitOffset > 0) {
        // delete auto fit amount from the begining of the route data
        this.gpstrack.routeData.x.splice(0, autofitOffset);
        this.gpstrack.routeData.y.splice(0, autofitOffset);
        this.gpstrack.routeData.time.splice(0, autofitOffset);
      } else if (autofitOffset < 0) {
        // add start point from course data and calculated start time to route data
        this.gpstrack.routeData.x.unshift(courseData.x[0]);
        this.gpstrack.routeData.y.unshift(courseData.y[0]);
        // convert real time seconds to offset seconds from start time
        this.gpstrack.routeData.time.unshift(fitOffset); // zero for most of the rases
      }

      // loop thru routedata and round values + times
      /* Help
      points: 20-30 -> idx +20
      l: = 30 - 20 = 10
      i: 0 -> 10
      routeData: move 20-30 -> 0-10, delete 10-30
      */
      splitTime = this.gpstrack.routeData.splits[this.gpstrack.routeData.splits.length - 1];
      routeLength = this.gpstrack.routeData.x.length;
      if (splitTime === 0) {
        //MaB show full GPS route for disqualified and non competing results
        splitTime = Math.min(routeLength, rg2.config.TIME_NOT_FOUND);
      }
      //l = Math.min(splitTime, routeLength - 1);  // -1 for index to time conversion
      //for (i = 0; i < routeLength; i += 1) {
      i = 0;
      l = 0;
      while (i < routeLength && l < splitTime) {
        this.gpstrack.routeData.x[i] = Math.round(this.gpstrack.routeData.x[i]);
        this.gpstrack.routeData.y[i] = Math.round(this.gpstrack.routeData.y[i]);
        // convert real time seconds to offset seconds from start time
        this.gpstrack.routeData.time[i] = this.gpstrack.routeData.time[i] - fitOffset;
        l = this.gpstrack.routeData.time[i];
        i = i + 1;
      }
      if (i < routeLength) {
        // delete the end of the overlength route
        this.gpstrack.routeData.x.splice(i);
        this.gpstrack.routeData.y.splice(i);
        this.gpstrack.routeData.time.splice(i);
      } else if (l < splitTime) {
        i = courseData.x.length - 1;
        // add missing end part to route data by finnish control point from course data and split time
        this.gpstrack.routeData.x.push(courseData.x[i]);
        this.gpstrack.routeData.y.push(courseData.y[i]);
        this.gpstrack.routeData.time.push(splitTime);
      }

      // store route time
      t = this.gpstrack.routeData.time[this.gpstrack.routeData.time.length - 1];
      this.gpstrack.routeData.totaltime = rg2.utils.formatSecsAsMMSS(t);

      // allow for already having a GPS route for this runner
      this.gpstrack.routeData.resultid += rg2.config.GPS_RESULT_OFFSET;
      while (rg2.results.resultIDExists(this.gpstrack.routeData.resultid)) {
        this.gpstrack.routeData.resultid += rg2.config.GPS_RESULT_OFFSET;
        // add marker(s) to name to show it is a duplicate
        this.gpstrack.routeData.name += '*';
      }
      //MaB ignore default comments
      text = $("#rg2-new-comments").val();
      if (text === rg2.t(rg2.config.DEFAULT_NEW_COMMENT)) {
        this.gpstrack.routeData.comments = "";
      } else {
        this.gpstrack.routeData.comments = text;
      }

      $("#btn-undo-gps-adjust").button("disable");
      this.setDeltas();
      this.postRoute();
    },

    saveRoute : function () {
      var text;
      // called to save manually entered route
      //MaB ignore default comments
      text = $("#rg2-new-comments").val();
      if (text === rg2.t(rg2.config.DEFAULT_NEW_COMMENT)) {
        this.gpstrack.routeData.comments = "";
      } else {
        this.gpstrack.routeData.comments = text;
      }
      this.gpstrack.routeData.controlx = this.controlx;
      this.gpstrack.routeData.controly = this.controly;
      // don't need start control so remove it
      this.gpstrack.routeData.controlx.splice(0, 1);
      this.gpstrack.routeData.controly.splice(0, 1);
      this.setDeltas();
      this.postRoute();
      // delete start split of this is a result being added
      // we created an array with a 0 split for the start to make the drawing work, but the back end doesn't want it
      if ((this.gpstrack.routeData.resultid === 0) || (this.gpstrack.routeData.resultid ==  rg2.GPS_RESULT_OFFSET)) {
        this.gpstrack.routeData.splits.splice(0, 1);
      }
    },

    setDeltas : function () {
      var i;
      // send as differences rather than absolute values: provides almost 50% reduction in size of json file
      for (i = this.gpstrack.routeData.x.length - 1; i > 0; i -= 1) {
        this.gpstrack.routeData.x[i] = this.gpstrack.routeData.x[i] - this.gpstrack.routeData.x[i - 1];
        this.gpstrack.routeData.y[i] = this.gpstrack.routeData.y[i] - this.gpstrack.routeData.y[i - 1];
      }
      // in theory time is same length as x and y but why take the risk...
      for (i = this.gpstrack.routeData.time.length - 1; i > 0; i -= 1) {
        this.gpstrack.routeData.time[i] = this.gpstrack.routeData.time[i] - this.gpstrack.routeData.time[i - 1];
      }
    },

    postRoute : function () {
      var $url, json, self;
      $url = rg2Config.json_url + '?type=addroute&id=' + this.gpstrack.routeData.eventid;
      // create JSON data
      json = JSON.stringify(this.gpstrack.routeData);
      self = this;
      document.getElementById("rg2-container").style.cursor = "wait";
      $.ajax({
        data : json,
        type : 'POST',
        url : $url,
        dataType : 'json',
        success : function (data) {
          if (data.ok) {
            self.routeSaved(data);
          } else {
            rg2.utils.showWarningDialog(self.gpstrack.routeData.name, rg2.t('Your route was not saved. Please try again'));
          }
        },
        error : function () {
          rg2.utils.showWarningDialog(self.gpstrack.routeData.name, rg2.t('Your route was not saved. Please try again'));
        },
        complete : function () {
          document.getElementById("rg2-container").style.cursor = "default";
        }
      });
    },

    routeSaved : function (data) {
      rg2.utils.showShareDialog(this.gpstrack.routeData.name, data.newid, rg2.t('Your route has been saved') + '.');
      rg2.saveDrawnRouteDetails({eventid: parseInt(data.eventid, 10), id: data.newid, token: data.token});
      rg2.loadEvent(rg2.events.getActiveEventID());
    },

    confirmDeleteRoute : function (id) {
      var dlg;
      this.routeToDelete = id;
      dlg = {};
      dlg.selector = "
This route will be permanently deleted. Are you sure?
";
      dlg.title = "Confirm route delete";
      dlg.classes = "rg2-confirm-route-delete-dialog";
      dlg.doText = "Delete route";
      dlg.onDo = this.doDeleteRoute.bind(this);
      dlg.onCancel = this.doCancelDeleteRoute.bind(this);
      rg2.utils.createModalDialog(dlg);
    },

    doCancelDeleteRoute : function () {
      $("#route-delete-dialog").dialog("destroy");
    },

    doDeleteRoute : function () {
      var $url, json, info;
      $("#route-delete-dialog").dialog("destroy");
      info = rg2.results.getDeletionInfo(this.routeToDelete);
      $url = rg2Config.json_url + "?type=deletemyroute&id=" + rg2.events.getKartatEventID() + "&routeid=" + info.id;
      json = JSON.stringify({token: info.token});
      $.ajax({
        data : json,
        type : "POST",
        url : $url,
        dataType : "json",
        success : function (data) {
          if (data.ok) {
            rg2.utils.showWarningDialog(rg2.t("Route deleted"), rg2.t("Route has been deleted"));
            rg2.removeDrawnRouteDetails({eventid: parseInt(data.eventid, 10), id: parseInt(data.routeid, 10)});
            rg2.getEvents();
          } else {
            rg2.utils.showWarningDialog(rg2.t("Delete failed"), rg2.t("Delete failed"));
          }
        },
        error : function (jqXHR, textStatus) {
          /*jslint unparam:true*/
          /* jshint unused:vars */
          rg2.utils.showWarningDialog(rg2.t("Delete failed"), rg2.t("Delete failed"));
        }
      });
    },

    waitThreeSeconds : function () {
      // insert a new point in the same place as the last point
      this.addRouteDataPoint(this.gpstrack.routeData.x[this.gpstrack.routeData.x.length - 1], this.gpstrack.routeData.y[this.gpstrack.routeData.y.length - 1]);
      rg2.redraw(false);
    },

    // snapto: test if drawn route is close enough to control
    closeEnough : function (x, y) {
      var range;
      if (rg2.options.snap) {
        range = 8;
      } else {
        range = 2;
      }
      if (Math.abs(x - this.controlx[this.nextControl]) < range) {
        if (Math.abs(y - this.controly[this.nextControl]) < range) {
          return true;
        }
      }
      return false;
    },

    adjustTrack : function (p1, p2, button) {
      // called whilst dragging a GPS track
      var trk, handle, earliest, latest;
      //console.log("adjustTrack ", p1.x, p1.y, p2.x, p2.y);
      // check if background is locked or right click
      if ($('#btn-move-all').prop('checked') || button === rg2.config.RIGHT_CLICK) {
        rg2.ctx.translate(p2.x - p1.x, p2.y - p1.y);
      } else {
        trk = this.gpstrack;
        if (trk.handles.handlesLocked() > 0) {
          if (trk.handles.handlesLocked() === 1) {
            this.scaleRotateAroundSingleLockedPoint(p1, p2, trk.handles.getSingleLockedHandle(), trk.handles.getStartHandle().time, trk.handles.getFinishHandle().time);
          } else {
            // check if start of drag is on a handle
            handle = trk.handles.getHandleClicked(p1);
            // we already know we have at least two points locked: cases to deal with from here
            // 1: drag point not on a handle: exit
            // 2: drag point on a locked handle: exit
            // 3: drag point between start and a locked handle: scale and rotate around single point
            // 4: drag point between locked handle and end: scale and rotate around single handle
            // 5: drag point between two locked handles: shear around two fixed handles
            //case 1
            if (handle === undefined) {
              return;
            }
            // case 2
            if (handle.locked) {
              return;
            }
            earliest = trk.handles.getEarliestLockedHandle();
            latest = trk.handles.getLatestLockedHandle();

            if (earliest.time >= handle.time) {
              // case 3: drag point between start and a locked handle
              this.scaleRotateAroundSingleLockedPoint(p1, p2, earliest, trk.handles.getStartHandle().time, earliest.time);
            } else if (latest.time < handle.time) {
              // case 4: drag point between locked handle and end
              this.scaleRotateAroundSingleLockedPoint(p1, p2, latest, latest.time, trk.handles.getFinishHandle().time);
            } else {
              // case 5: adjust between two locked points
              this.adjustBetweenTwoLockedPoints(p1, p2, handle);
            }
          }
        } else {
          // nothing locked so drag track
          this.dragTrack((p2.x - p1.x), (p2.y - p1.y));
        }
      }
    },

    adjustBetweenTwoLockedPoints : function (p1, p2, handle) {
      // case 5: adjust between two locked points
      // see, there is an easier way
      var previousHandle, nextHandle;
      //console.log("Point (", p1.x, ", ", p1.y, ") for handle ", handle.index, handle.basex, handle.basey);
      previousHandle = this.gpstrack.handles.getPreviousLockedHandle(handle);
      nextHandle = this.gpstrack.handles.getNextLockedHandle(handle);
      // adjust route between previous locked handle and dragged point
      this.scaleRotateAroundSingleLockedPoint(p1, p2, previousHandle, previousHandle.time, handle.time);
      // adjust route between dragged point and next locked handle
      this.scaleRotateAroundSingleLockedPoint(p1, p2, nextHandle, handle.time, nextHandle.time);
    },

    scaleRotateAroundSingleLockedPoint : function (p1, p2, p3, fromTime, toTime) {
      // rotate p1 to p2 around p3
      var i, scale, angle, pt;
      // scale and rotate track around single locked point
      scale = rg2.utils.getDistanceBetweenPoints(p2.x, p2.y, p3.x, p3.y) / rg2.utils.getDistanceBetweenPoints(p1.x, p1.y, p3.x, p3.y);
      angle = rg2.utils.getAngle(p2.x, p2.y, p3.x, p3.y) - rg2.utils.getAngle(p1.x, p1.y, p3.x, p3.y);
      //console.log (p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, scale, angle, fromTime, toTime);
      for (i = fromTime; i <= toTime; i += 1) {
        pt = rg2.utils.rotatePoint(this.gpstrack.baseX[i] - p3.x, this.gpstrack.baseY[i] - p3.y, angle);
        this.gpstrack.routeData.x[i] = (pt.x * scale) + p3.x;
        this.gpstrack.routeData.y[i] = (pt.y * scale) + p3.y;
      }
      this.gpstrack.handles.alignHandles(this.gpstrack.routeData);
    },

    dragTrack : function (dx, dy) {
      var i, trk;
      trk = this.gpstrack;
      for (i = 0; i < trk.baseX.length; i += 1) {
        trk.routeData.x[i] = trk.baseX[i] + dx;
        trk.routeData.y[i] = trk.baseY[i] + dy;
      }
      trk.handles.dragHandles(dx, dy);
    },

    drawNewTrack : function () {
      var opt;
      opt = rg2.getOverprintDetails();
      rg2.ctx.lineWidth = opt.overprintWidth;
      rg2.ctx.strokeStyle = rg2.config.RED;
      rg2.ctx.fillStyle = rg2.config.RED_30;
      // highlight next control if we have a course selected
      if ((this.nextControl > 0) && (!this.gpstrack.fileLoaded)) {
        rg2.ctx.beginPath();
        if (this.nextControl < (this.controlx.length - 1)) {
          // normal control
          this.drawCircle(opt.controlRadius);
        } else {
          // finish
          this.drawCircle(opt.finishInnerRadius);
          rg2.ctx.stroke();
          rg2.ctx.beginPath();
          this.drawCircle(opt.finishOuterRadius);
        }
        // dot at centre of control circle
        rg2.ctx.fillRect(this.controlx[this.nextControl] - 1, this.controly[this.nextControl] - 1, 3, 3);
        rg2.ctx.stroke();
      }
      //MaB round brush
      rg2.ctx.lineCap = "round";
      rg2.ctx.lineJoin = "round";
      rg2.ctx.strokeStyle = this.trackColor;
      rg2.ctx.fillStyle = this.trackColour;
      rg2.ctx.font = '10pt Arial';
      rg2.ctx.textAlign = "left";
      rg2.ctx.globalAlpha = 0.6;
      this.drawRoute();
      this.gpstrack.handles.drawHandles();
    },

    drawCircle : function (radius) {
      rg2.ctx.arc(this.controlx[this.nextControl], this.controly[this.nextControl], radius, 0, 2 * Math.PI, false);
      // fill in with transparent colour to highlight control better
      rg2.ctx.fill();
    },

    drawRoute : function () {
      var i, l;
      if (this.gpstrack.routeData.x.length > 1) {
        rg2.ctx.beginPath();
        rg2.ctx.moveTo(this.gpstrack.routeData.x[0], this.gpstrack.routeData.y[0]);
        // don't bother with +3 second displays in GPS adjustment
        l = this.gpstrack.routeData.x.length;
        for (i = 1; i < l; i += 1) {
          rg2.ctx.lineTo(this.gpstrack.routeData.x[i], this.gpstrack.routeData.y[i]);
        }
        rg2.ctx.stroke();
      }
    }
  };
  rg2.Draw = Draw;
}());


text:
package com.ivan.utils.options;

public class OptionsTest {
	private static final class Options {
		public static final Option<String> NAME = Option.createOptional();
		public static final Option<Integer> MAX = Option.createRequired(5);
		public static final Option<Boolean> ENABLED = Option.createRequired(true);
	}

	private static final OptionSet options = new OptionSet();

	public static void main(final String[] args) {
		System.out.println(options.get(Options.NAME));
		options.set(Options.NAME, "name");
		System.out.println(options.get(Options.NAME));
		options.reset(Options.NAME);
		System.out.println(options.get(Options.NAME));

		options.set(Options.MAX, 15);
		options.set(Options.ENABLED, false);

		System.out.println();
		System.out.println(options.get(Options.NAME));
		System.out.println(options.get(Options.MAX));
		System.out.println(options.get(Options.ENABLED));

		options.reset();
		System.out.println();
		System.out.println(options.get(Options.NAME));
		System.out.println(options.get(Options.MAX));
		System.out.println(options.get(Options.ENABLED));

		System.out.println();
		options.set(Options.NAME, null);
		try {
			options.set(Options.MAX, null);
		} catch (final IllegalArgumentException e) {
			System.out.println("max cannot be null");
		}
		try {
			options.set(Options.ENABLED, null);
		} catch (final IllegalArgumentException e) {
			System.out.println("enabled cannot be null");
		}

		System.out.println();
		System.out.println(options.get(Options.NAME));
		System.out.println(options.get(Options.MAX));
		System.out.println(options.get(Options.ENABLED));
	}
}


text:
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..') unless $SETUP_LOADED
require 'unittests/setup'

class Lists_Tests < Watir::TestCase

  def setup
    goto_page 'lists.html'
  end

  def test_list_items_exist
    assert(browser.li(:id, 'list1').exists?)
    assert(browser.li(:id, 'list2').exists?)
    assert(browser.li(:id, 'list3').exists?)
    assert(browser.li(:id, 'ordered1').exists?)
    assert_equal('Coffee', browser.li(:index, 0).text)
  end

  def test_list_item_exists_by_name
    assert(browser.li(:name, 'x1').exists?)
    assert ! (browser.li(:name, 'maptest02').exists?)
  end

  def test_li_length
    assert_equal(6, browser.lis.length)
  end

  def test_multiple_attributes
    assert_equal('Phil', browser.li(:id => 'ordered1', :name => 'x1').text)
  end

end


text:
/**
 */
package com.specmate.model.testspecification;

import com.specmate.model.base.IContainer;
import com.specmate.model.base.IExternal;

/**
 *
 * A representation of the model object 'Test Procedure'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link com.specmate.model.testspecification.TestProcedure#isIsRegressionTest Is Regression Test}

 *

 *
 * @see com.specmate.model.testspecification.TestspecificationPackage#getTestProcedure()
 * @model
 * @generated
 */
public interface TestProcedure extends IContainer, IExternal {
	/**
	 * Returns the value of the 'Is Regression Test' attribute.
	 *
	 *

	 * If the meaning of the 'Is Regression Test' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Is Regression Test' attribute.
	 * @see #setIsRegressionTest(boolean)
	 * @see com.specmate.model.testspecification.TestspecificationPackage#getTestProcedure_IsRegressionTest()
	 * @model annotation="http://specmate.com/form_meta shortDesc='Regression Test' type='checkbox' position='3' longDesc=''"
	 * @generated
	 */
	boolean isIsRegressionTest();

	/**
	 * Sets the value of the '{@link com.specmate.model.testspecification.TestProcedure#isIsRegressionTest Is Regression Test}' attribute.
	 *
	 *
	 * @param value the new value of the 'Is Regression Test' attribute.
	 * @see #isIsRegressionTest()
	 * @generated
	 */
	void setIsRegressionTest(boolean value);

} // TestProcedure


text:
package zhenguo.hanxu;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import zhenguo.hanxu.R;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class BluetoothActivity extends ListActivity {
	private	BluetoothAdapter bta;
   	Bluetooth bt=new Bluetooth();
	private List<BluetoothDevice> Adevices = new ArrayList<BluetoothDevice>();
	private Handler _handler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discovery);

        BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
    	System.out.println(_bluetooth.getAddress()+_bluetooth.getName());
    	_bluetooth.startDiscovery();
        Set<BluetoothDevice> devices=_bluetooth .getBondedDevices();
        if(devices.size()>0){
        	Adevices.addAll(devices);
        	showDevices();
        }
    }

	protected void showDevices()
	{
		List<String> list = new ArrayList<String>();
		for (int i = 0, size = Adevices.size(); i < size; ++i)
		{
			StringBuilder b = new StringBuilder();
			BluetoothDevice d = Adevices.get(i);
			b.append(d.getAddress());
			b.append('\n');
			b.append(d.getName());
			String s = b.toString();
			list.add(s);
		}

		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
		_handler.post(new Runnable() {
			public void run()
			{

				setListAdapter(adapter);
			}
		});
	}
	protected void onListItemClick(ListView l, View v, int position, long id)
	{

		Bluetooth bt=new Bluetooth();
		System.out.println(123321);
		System.out.println(Adevices.get(position).getAddress());
//		if(bt.Connect(Adevices.get(position).getAddress())){
		Intent enabler = new Intent(this,TouchpanelActivity.class);
//		Bundle bundle = new Bundle();
//		bundle.putString("address",Adevices.get(position).getAddress());
//		bundle.putSerializable("Buletooth", bt);
		enabler.putExtra("address",Adevices.get(position).getAddress());
		startActivity(enabler);
		finish();
		}

}


text:
Given a number, find the sum of all the unique multiples of particular numbers up to but not including that number.

If we list all the natural numbers below 20 that are multiples of 3 or 5, we get 3, 5, 6, 9, 10, 12, 15, and 18.

The sum of these multiples is 78.


text:
        If your job uses the JUnit Realtime Test Reporter Plugin,
        you can display the progress bar while the project is building.

        There are actually 2 progress bars stacked together. One based on the number of tests and the second
        based on the test execution time. A tooltip will display the tests count and the estimated remaining time.
        All the stats are based on the result from the previous build and can change a lot from build to build
        (multiple concurrent jobs can slow down the test execution).


text:
/*
 * Note: this file originally auto-generated by mib2c using
 *  : mib2c.column_defines.conf,v 5.1 2002/05/08 05:42:47 hardaker Exp $
 */
#ifndef NETSNMPHOSTSTABLE_COLUMNS_H
#define NETSNMPHOSTSTABLE_COLUMNS_H

/*
 * column number definitions for table netSnmpHostsTable
 */
#define COLUMN_NETSNMPHOSTNAME		1
#define COLUMN_NETSNMPHOSTADDRESSTYPE		2
#define COLUMN_NETSNMPHOSTADDRESS		3
#define COLUMN_NETSNMPHOSTSTORAGE		4
#define COLUMN_NETSNMPHOSTROWSTATUS		5
#endif                          /* NETSNMPHOSTSTABLE_COLUMNS_H */


text:
require 'js_flasher/version'
require 'js_flasher/configuration'
require 'js_flasher/get_templates'

module JsFlasher
  extend Configuration
  extend GetTemplates
  require 'js_flasher/railtie' if defined?(Rails)
end

class JsFlasherInitable
  # include JsFlasher
  include JsFlasher::Configuration
  include JsFlasher::GetTemplates

  def initialize(config = {})
    reset()

    config.each do |opt, val|
      self.send("#{opt}=",val)
    end
  end

end