text:
require 'spec_helper'

shared_examples_for Restforce::AbstractClient do
  describe '.list_sobjects' do
    requests :sobjects, fixture: 'sobject/describe_sobjects_success_response'

    subject { client.list_sobjects }
    it { should be_an Array }
    it { should eq ['Account'] }
  end

  describe '.describe' do
    context 'with no arguments' do
      requests :sobjects, fixture: 'sobject/describe_sobjects_success_response'

      subject { client.describe }
      it { should be_an Array }
    end

    context 'with an argument' do
      requests 'sobjects/Whizbang/describe',
               fixture: 'sobject/sobject_describe_success_response'

      subject { client.describe('Whizbang') }
      its(['name']) { should eq 'Whizbang' }
    end
  end

  describe '.query' do
    requests 'query\?q=SELECT%20some,%20fields%20FROM%20object',
             fixture: 'sobject/query_success_response'

    subject { client.query('SELECT some, fields FROM object') }
    it { should be_an Enumerable }
  end

  describe '.get_updated' do
    let(:start_date) { Time.new(2015, 8, 17, 0, 0, 0, "+02:00") }
    let(:end_date) { Time.new(2016, 8, 19, 0, 0, 0, "+02:00") }
    end_string = '2016-08-18T22:00:00Z'
    start_string = '2015-08-16T22:00:00Z'
    requests "sobjects/Whizbang/updated/\\?end=#{end_string}&start=#{start_string}",
             fixture: 'sobject/get_updated_success_response'
    subject { client.get_updated('Whizbang', start_date, end_date) }
    it { should be_an Enumerable }
  end

  describe '.get_deleted' do
    let(:start_date) { Time.new(2015, 8, 17, 0, 0, 0, "+02:00") }
    let(:end_date) { Time.new(2016, 8, 19, 0, 0, 0, "+02:00") }
    end_string = '2016-08-18T22:00:00Z'
    start_string = '2015-08-16T22:00:00Z'
    requests "sobjects/Whizbang/deleted/\\?end=#{end_string}&start=#{start_string}",
             fixture: 'sobject/get_deleted_success_response'
    subject { client.get_deleted('Whizbang', start_date, end_date) }
    it { should be_an Enumerable }
  end

  describe '.search' do
    requests 'search\?q=FIND%20%7Bbar%7D', fixture: 'sobject/search_success_response'

    subject { client.search('FIND {bar}') }
    it { should be_an Array }
    its(:size) { should eq 2 }
  end

  describe '.org_id' do
    requests 'query\?q=select%20id%20from%20Organization',
             fixture: 'sobject/org_query_response'

    subject { client.org_id }
    it { should eq '00Dx0000000BV7z' }
  end

  describe '.create' do
    context 'without multipart' do
      requests 'sobjects/Account',
               method: :post,
               with_body: "{\"Name\":\"Foobar\"}",
               fixture: 'sobject/create_success_response'

      subject { client.create('Account', Name: 'Foobar') }
      it { should eq 'some_id' }
    end

    context 'with multipart' do
      # rubocop:disable Layout/LineLength
      requests 'sobjects/Account',
               method: :post,
               with_body: %r(----boundary_string\r\nContent-Disposition: form-data; name="entity_content"\r\nContent-Type: application/json\r\n\r\n{"Name":"Foobar"}\r\n----boundary_string\r\nContent-Disposition: form-data; name="Blob"; filename="blob.jpg"\r\nContent-Length: 42171\r\nContent-Type: image/jpeg\r\nContent-Transfer-Encoding: binary),
               fixture: 'sobject/create_success_response'
      # rubocop:enable Layout/LineLength

      subject do
        client.create('Account', Name: 'Foobar',
                                 Blob: Restforce::FilePart.new(
                                   File.expand_path('../fixtures/blob.jpg', __dir__),
                                   'image/jpeg'
                                 ))
      end

      it { should eq 'some_id' }

      context 'with deprecated UploadIO' do
        subject do
          client.create('Account', Name: 'Foobar',
                        Blob: Restforce::UploadIO.new(
                          File.expand_path('../fixtures/blob.jpg', __dir__),
                          'image/jpeg'
                        ))
        end

        it { should eq 'some_id' }
      end
    end
  end

  describe '.update!' do
    context 'with invalid Id' do
      requests 'sobjects/Account/001D000000INjVe',
               method: :patch,
               with_body: "{\"Name\":\"Foobar\"}",
               status: 404,
               fixture: 'sobject/delete_error_response'

      let(:error) do
        JSON.parse(fixture('sobject/delete_error_response'))
      end

      subject do
        lambda do
          client.update!('Account', Id: '001D000000INjVe', Name: 'Foobar')
        end
      end

      it {
        should raise_error(
          Faraday::ResourceNotFound,
          "#{error.first['errorCode']}: #{error.first['message']}"
        )
      }
    end
  end

  describe '.update' do
    context 'with missing Id' do
      subject { lambda { client.update('Account', Name: 'Foobar') } }
      it { should raise_error ArgumentError, 'ID field missing from provided attributes' }
    end

    context 'with invalid Id' do
      requests 'sobjects/Account/001D000000INjVe',
               method: :patch,
               with_body: "{\"Name\":\"Foobar\"}",
               status: 404,
               fixture: 'sobject/delete_error_response'

      subject { client.update('Account', Id: '001D000000INjVe', Name: 'Foobar') }
      it { should be_false }
    end

    context 'with success' do
      requests 'sobjects/Account/001D000000INjVe',
               method: :patch,
               with_body: "{\"Name\":\"Foobar\"}"

      [:Id, :id, 'Id', 'id'].each do |key|
        context "with #{key.inspect} as the key" do
          subject do
            client.update('Account', key => '001D000000INjVe', :Name => 'Foobar')
          end

          it { should be_true }
        end
      end
    end
  end

  describe '.upsert!' do
    context 'when updated' do
      requests 'sobjects/Account/External__c/foobar',
               method: :patch,
               with_body: "{\"Name\":\"Foobar\"}",
               fixture: "sobject/upsert_updated_success_response"

      context 'with symbol external Id key' do
        subject do
          client.upsert!('Account', 'External__c', External__c: 'foobar',
                                                   Name: 'Foobar')
        end

        it { should be_true }
      end

      context 'with string external Id key' do
        subject do
          client.upsert!('Account', 'External__c', 'External__c' => 'foobar',
                                                   'Name' => 'Foobar')
        end

        it { should be_true }
      end
    end

    context 'when created' do
      requests 'sobjects/Account/External__c/foobar',
               method: :patch,
               with_body: "{\"Name\":\"Foobar\"}",
               fixture: 'sobject/upsert_created_success_response'

      [:External__c, 'External__c', :external__c, 'external__c'].each do |key|
        context "with #{key.inspect} as the external id" do
          subject do
            client.upsert!('Account', 'External__c', key => 'foobar',
                                                     :Name => 'Foobar')
          end

          it { should eq 'foo' }
        end
      end
    end

    context 'when created with a space in the id' do
      requests 'sobjects/Account/External__c/foo%20bar',
               method: :patch,
               with_body: "{\"Name\":\"Foobar\"}",
               fixture: 'sobject/upsert_created_success_response'

      [:External__c, 'External__c', :external__c, 'external__c'].each do |key|
        context "with #{key.inspect} as the external id" do
          subject do
            client.upsert!('Account', 'External__c', key => 'foo bar',
                                                     :Name => 'Foobar')
          end

          it { should eq 'foo' }
        end
      end
    end
  end

  describe '.destroy!' do
    subject(:destroy!) { client.destroy!('Account', '001D000000INjVe') }

    context 'with invalid Id' do
      requests 'sobjects/Account/001D000000INjVe',
               fixture: 'sobject/delete_error_response',
               method: :delete,
               status: 404

      subject { lambda { destroy! } }
      it { should raise_error Faraday::ResourceNotFound }
    end

    context 'with success' do
      requests 'sobjects/Account/001D000000INjVe', method: :delete

      it { should be_true }
    end

    context 'with a space in the id' do
      subject(:destroy!) { client.destroy!('Account', '001D000000 INjVe') }
      requests 'sobjects/Account/001D000000%20INjVe', method: :delete

      it { should be_true }
    end
  end

  describe '.destroy' do
    subject { client.destroy('Account', '001D000000INjVe') }

    context 'with invalid Id' do
      requests 'sobjects/Account/001D000000INjVe',
               fixture: 'sobject/delete_error_response',
               method: :delete,
               status: 404

      it { should be_false }
    end

    context 'with success' do
      requests 'sobjects/Account/001D000000INjVe', method: :delete

      it { should be_true }
    end
  end

  describe '.find' do
    context 'with no external id passed' do
      requests 'sobjects/Account/001D000000INjVe',
               fixture: 'sobject/sobject_find_success_response'

      subject { client.find('Account', '001D000000INjVe') }
      it { should be_a Hash }
    end

    context 'when an external id is passed' do
      requests 'sobjects/Account/External_Field__c/1234',
               fixture: 'sobject/sobject_find_success_response'

      subject { client.find('Account', '1234', 'External_Field__c') }
      it { should be_a Hash }
    end

    context 'with a space in an external id' do
      requests 'sobjects/Account/External_Field__c/12%2034',
               fixture: 'sobject/sobject_find_success_response'

      subject { client.find('Account', '12 34', 'External_Field__c') }
      it { should be_a Hash }
    end
  end

  describe '.select' do
    context 'when no external id is specified' do
      context 'when no select list is specified' do
        requests 'sobjects/Account/1234',
                 fixture: 'sobject/sobject_select_success_response'

        subject { client.select('Account', '1234', nil, nil) }
        it { should be_a Hash }
      end
      context 'when select list is specified' do
        requests 'sobjects/Account/1234\?fields=External_Field__c',
                 fixture: 'sobject/sobject_select_success_response'

        subject { client.select('Account', '1234', ['External_Field__c']) }
        it { should be_a Hash }
      end

      context 'with a space in the id' do
        requests 'sobjects/Account/12%2034',
                 fixture: 'sobject/sobject_select_success_response'

        subject { client.select('Account', '12 34', nil, nil) }
        it { should be_a Hash }
      end
    end

    context 'when an external id is specified' do
      context 'when no select list is specified' do
        requests 'sobjects/Account/External_Field__c/1234',
                 fixture: 'sobject/sobject_select_success_response'

        subject { client.select('Account', '1234', nil, 'External_Field__c') }
        it { should be_a Hash }
      end

      context 'when select list is specified' do
        requests 'sobjects/Account/External_Field__c/1234\?fields=External_Field__c',
                 fixture: 'sobject/sobject_select_success_response'

        subject do
          client.select('Account', '1234', ['External_Field__c'], 'External_Field__c')
        end

        it { should be_a Hash }
      end
    end
  end

  describe '.authenticate!' do
    subject(:authenticate!) { client.authenticate! }

    context 'when successful' do
      before do
        @request = stub_login_request(
          with_body: "grant_type=password&client_id=client_id" \
                        "&client_secret=client_secret&username=foo" \
                        "&password=barsecurity_token"
        ).to_return(status: 200, body: fixture(:auth_success_response))
      end

      after do
        expect(@request).to have_been_requested
      end

      it { should be_a Hash }
    end

    context 'when no authentication middleware is present' do
      before do
        client.stub(:authentication_middleware).and_return(nil)
      end

      it "raises an error" do
        expect { authenticate! }.to raise_error Restforce::AuthenticationError,
                                                'No authentication middleware present'
      end
    end
  end

  describe '.without_caching' do
    let(:cache) { MockCache.new }

    it 'deletes the cached value before querying the API' do
      stub = stub_api_request(
        'query\?q=SELECT%20some,%20fields%20FROM%20object',
        fixture: 'sobject/query_success_response'
      )
      client.query('SELECT some, fields FROM object')

      expect(cache).to receive(:delete).and_call_original.ordered
      expect(cache).to receive(:read).and_call_original.ordered
      client.without_caching { client.query('SELECT some, fields FROM object') }
      expect(stub).to have_been_requested.twice
    end
  end

  describe 'authentication retries' do
    context 'when retries reaches 0' do
      before do
        @auth_request = stub_api_request(
          'query\?q=SELECT%20some,%20fields%20FROM%20object',
          status: 401,
          fixture: 'expired_session_response'
        )

        @query_request = stub_login_request(
          with_body: "grant_type=password&client_id=client_id" \
                        "&client_secret=client_secret&username=foo&" \
                        "password=barsecurity_token"
        ).to_return(status: 200, body: fixture(:auth_success_response))
      end

      subject { lambda { client.query('SELECT some, fields FROM object') } }
      it { should raise_error Restforce::UnauthorizedError }
    end
  end

  describe '.query with caching' do
    let(:cache) { MockCache.new }

    before do
      @query = stub_api_request('query\?q=SELECT%20some,%20fields%20FROM%20object').
               with(headers: { 'Authorization' => "OAuth #{oauth_token}" }).
               to_return(status: 401,
                  body: fixture('expired_session_response'),
                  headers: { 'Content-Type' => 'application/json' }).then.
               to_return(status: 200,
                  body: fixture('sobject/query_success_response'),
                  headers: { 'Content-Type' => 'application/json' })

      @login = stub_login_request(
        with_body: "grant_type=password&client_id=client_id&client_secret=" \
                      "client_secret&username=foo&password=barsecurity_token"
      ).to_return(status: 200, body: fixture(:auth_success_response))
    end

    after do
      expect(@query).to have_been_made.times(2)
      expect(@login).to have_been_made
    end

    subject { client.query('SELECT some, fields FROM object') }
    it { should be_an Enumerable }
  end
end

describe Restforce::AbstractClient do
  describe 'with mashify' do
    it_behaves_like Restforce::AbstractClient

    describe '.query' do
      context 'with pagination' do
        subject { client.query('SELECT some, fields FROM object').next_page }

        requests 'query\?q', fixture: 'sobject/query_paginated_first_page_response'
        requests 'query/01gD', fixture: 'sobject/query_paginated_last_page_response'

        it { should be_a Restforce::Collection }
        its('first.Text_Label') { should eq 'Last Page' }
      end
    end
  end

  describe 'without mashify', mashify: false do
    it_behaves_like Restforce::AbstractClient
  end
end


text:
module Haddock.Options (
  parseHaddockOpts,
  Flag(..),
  getUsage,
  optTitle,
  outputDir,
  optContentsUrl,
  optIndexUrl,
  optCssFile,
  optSourceCssFile,
  sourceUrls,
  wikiUrls,
  optDumpInterfaceFile,
  optShowInterfaceFile,
  optLaTeXStyle,
  optMathjax,
  qualification,
  verbosity,
  ghcFlags,
  reexportFlags,
  readIfaceArgs,
  optPackageName,
  optPackageVersion
) where

import qualified Data.Char as Char
import           Data.Version
import           Distribution.Verbosity
import           FastString
import           Haddock.Types
import           Haddock.Utils
import           Packages
import           System.Console.GetOpt
import qualified Text.ParserCombinators.ReadP as RP

data Flag
  = Flag_BuiltInThemes
  | Flag_CSS String
--  | Flag_DocBook
  | Flag_ReadInterface String
  | Flag_DumpInterface String
  | Flag_ShowInterface String
  | Flag_Heading String
  | Flag_Html
  | Flag_Hoogle
  | Flag_Lib String
  | Flag_OutputDir FilePath
  | Flag_Prologue FilePath
  | Flag_SourceBaseURL    String
  | Flag_SourceModuleURL  String
  | Flag_SourceEntityURL  String
  | Flag_SourceLEntityURL String
  | Flag_WikiBaseURL   String
  | Flag_WikiModuleURL String
  | Flag_WikiEntityURL String
  | Flag_LaTeX
  | Flag_LaTeXStyle String
  | Flag_QuickJumpIndex
  | Flag_HyperlinkedSource
  | Flag_SourceCss String
  | Flag_Mathjax String
  | Flag_Help
  | Flag_Verbosity String
  | Flag_Version
  | Flag_CompatibleInterfaceVersions
  | Flag_InterfaceVersion
  | Flag_UseContents String
  | Flag_GenContents
  | Flag_UseIndex String
  | Flag_GenIndex
  | Flag_IgnoreAllExports
  | Flag_HideModule String
  | Flag_ShowExtensions String
  | Flag_OptGhc String
  | Flag_GhcLibDir String
  | Flag_GhcVersion
  | Flag_PrintGhcPath
  | Flag_PrintGhcLibDir
  | Flag_NoWarnings
  | Flag_UseUnicode
  | Flag_NoTmpCompDir
  | Flag_Qualification String
  | Flag_PrettyHtml
  | Flag_NoPrintMissingDocs
  | Flag_PackageName String
  | Flag_PackageVersion String
  | Flag_Reexport String
  deriving (Eq, Show)

options :: Bool -> [OptDescr Flag]
options backwardsCompat =
  [
    Option ['B']  []     (ReqArg Flag_GhcLibDir "DIR")
      "path to a GHC lib dir, to override the default path",
    Option ['o']  ["odir"]     (ReqArg Flag_OutputDir "DIR")
      "directory in which to put the output files",
    Option ['l']  ["lib"]         (ReqArg Flag_Lib "DIR")
      "location of Haddock's auxiliary files",
    Option ['i'] ["read-interface"] (ReqArg Flag_ReadInterface "FILE")
      "read an interface from FILE",
    Option ['D']  ["dump-interface"] (ReqArg Flag_DumpInterface "FILE")
      "write the resulting interface to FILE",
    Option []     ["show-interface"] (ReqArg Flag_ShowInterface "FILE")
      "print the interface in a human readable form",
--    Option ['S']  ["docbook"]  (NoArg Flag_DocBook)
--  "output in DocBook XML",
    Option ['h']  ["html"]     (NoArg Flag_Html)
      "output in HTML (XHTML 1.0)",
    Option []  ["latex"]  (NoArg Flag_LaTeX) "use experimental LaTeX rendering",
    Option []  ["latex-style"]  (ReqArg Flag_LaTeXStyle "FILE") "provide your own LaTeX style in FILE",
    Option []  ["mathjax"]  (ReqArg Flag_Mathjax "URL") "URL FOR mathjax",
    Option ['U'] ["use-unicode"] (NoArg Flag_UseUnicode) "use Unicode in HTML output",
    Option []  ["hoogle"]     (NoArg Flag_Hoogle)
      "output for Hoogle; you may want --package-name and --package-version too",
    Option [] ["quickjump"] (NoArg Flag_QuickJumpIndex)
      "generate an index for interactive documentation navigation",
    Option [] ["hyperlinked-source"] (NoArg Flag_HyperlinkedSource)
      "generate highlighted and hyperlinked source code (for use with --html)",
    Option [] ["source-css"] (ReqArg Flag_SourceCss "FILE")
      "use custom CSS file instead of default one in hyperlinked source",
    Option []  ["source-base"]   (ReqArg Flag_SourceBaseURL "URL")
      "URL for a source code link on the contents\nand index pages",
    Option ['s'] (if backwardsCompat then ["source", "source-module"] else ["source-module"])
      (ReqArg Flag_SourceModuleURL "URL")
      "URL for a source code link for each module\n(using the %{FILE} or %{MODULE} vars)",
    Option []  ["source-entity"]  (ReqArg Flag_SourceEntityURL "URL")
      "URL for a source code link for each entity\n(using the %{FILE}, %{MODULE}, %{NAME},\n%{KIND} or %{LINE} vars)",
    Option []  ["source-entity-line"] (ReqArg Flag_SourceLEntityURL "URL")
      "URL for a source code link for each entity.\nUsed if name links are unavailable, eg. for TH splices.",
    Option []  ["comments-base"]   (ReqArg Flag_WikiBaseURL "URL")
      "URL for a comments link on the contents\nand index pages",
    Option []  ["comments-module"]  (ReqArg Flag_WikiModuleURL "URL")
      "URL for a comments link for each module\n(using the %{MODULE} var)",
    Option []  ["comments-entity"]  (ReqArg Flag_WikiEntityURL "URL")
      "URL for a comments link for each entity\n(using the %{FILE}, %{MODULE}, %{NAME},\n%{KIND} or %{LINE} vars)",
    Option ['c']  ["css", "theme"] (ReqArg Flag_CSS "PATH")
      "the CSS file or theme directory to use for HTML output",
    Option []  ["built-in-themes"] (NoArg Flag_BuiltInThemes)
      "include all the built-in haddock themes",
    Option ['p']  ["prologue"] (ReqArg Flag_Prologue "FILE")
      "file containing prologue text",
    Option ['t']  ["title"]    (ReqArg Flag_Heading "TITLE")
      "page heading",
    Option ['q']  ["qual"] (ReqArg Flag_Qualification "QUAL")
      "qualification of names, one of \n'none' (default), 'full', 'local'\n'relative' or 'aliased'",
    Option ['?']  ["help"]  (NoArg Flag_Help)
      "display this help and exit",
    Option ['V']  ["version"]  (NoArg Flag_Version)
      "output version information and exit",
    Option []  ["compatible-interface-versions"]  (NoArg Flag_CompatibleInterfaceVersions)
      "output compatible interface file versions and exit",
    Option []  ["interface-version"]  (NoArg Flag_InterfaceVersion)
      "output interface file version and exit",
    Option ['v']  ["verbosity"]  (ReqArg Flag_Verbosity "VERBOSITY")
      "set verbosity level",
    Option [] ["use-contents"] (ReqArg Flag_UseContents "URL")
      "use a separately-generated HTML contents page",
    Option [] ["gen-contents"] (NoArg Flag_GenContents)
      "generate an HTML contents from specified\ninterfaces",
    Option [] ["use-index"] (ReqArg Flag_UseIndex "URL")
      "use a separately-generated HTML index",
    Option [] ["gen-index"] (NoArg Flag_GenIndex)
      "generate an HTML index from specified\ninterfaces",
    Option [] ["ignore-all-exports"] (NoArg Flag_IgnoreAllExports)
      "behave as if all modules have the\nignore-exports atribute",
    Option [] ["hide"] (ReqArg Flag_HideModule "MODULE")
      "behave as if MODULE has the hide attribute",
    Option [] ["show-extensions"] (ReqArg Flag_ShowExtensions "MODULE")
      "behave as if MODULE has the show-extensions attribute",
    Option [] ["optghc"] (ReqArg Flag_OptGhc "OPTION")
      "option to be forwarded to GHC",
    Option []  ["ghc-version"]  (NoArg Flag_GhcVersion)
      "output GHC version in numeric format",
    Option []  ["print-ghc-path"]  (NoArg Flag_PrintGhcPath)
      "output path to GHC binary",
    Option []  ["print-ghc-libdir"]  (NoArg Flag_PrintGhcLibDir)
      "output GHC lib dir",
    Option ['w'] ["no-warnings"] (NoArg Flag_NoWarnings) "turn off all warnings",
    Option [] ["no-tmp-comp-dir"] (NoArg Flag_NoTmpCompDir)
      "do not re-direct compilation output to a temporary directory",
    Option [] ["pretty-html"] (NoArg Flag_PrettyHtml)
      "generate html with newlines and indenting (for use with --html)",
    Option [] ["no-print-missing-docs"] (NoArg Flag_NoPrintMissingDocs)
      "don't print information about any undocumented entities",
    Option []  ["reexport"] (ReqArg Flag_Reexport "MOD")
      "reexport the module MOD, adding it to the index",
    Option [] ["package-name"] (ReqArg Flag_PackageName "NAME")
      "name of the package being documented",
    Option [] ["package-version"] (ReqArg Flag_PackageVersion "VERSION")
      "version of the package being documented in usual x.y.z.w format"
  ]

getUsage :: IO String
getUsage = do
  prog <- getProgramName
  return $ usageInfo (usageHeader prog) (options False)
  where
    usageHeader :: String -> String
    usageHeader prog = "Usage: " ++ prog ++ " [OPTION...] file...\n"

parseHaddockOpts :: [String] -> IO ([Flag], [String])
parseHaddockOpts params =
  case getOpt Permute (options True) params  of
    (flags, args, []) -> return (flags, args)
    (_, _, errors)    -> do
      usage <- getUsage
      throwE (concat errors ++ usage)

optPackageVersion :: [Flag] -> Maybe Data.Version.Version
optPackageVersion flags =
  let ver = optLast [ v | Flag_PackageVersion v <- flags ]
  in ver >>= fmap fst . optLast . RP.readP_to_S parseVersion

optPackageName :: [Flag] -> Maybe PackageName
optPackageName flags =
  optLast [ PackageName $ mkFastString n | Flag_PackageName n <- flags ]

optTitle :: [Flag] -> Maybe String
optTitle flags =
  case [str | Flag_Heading str <- flags] of
    [] -> Nothing
    (t:_) -> Just t

outputDir :: [Flag] -> FilePath
outputDir flags =
  case [ path | Flag_OutputDir path <- flags ] of
    []    -> "."
    paths -> last paths

optContentsUrl :: [Flag] -> Maybe String
optContentsUrl flags = optLast [ url | Flag_UseContents url <- flags ]

optIndexUrl :: [Flag] -> Maybe String
optIndexUrl flags = optLast [ url | Flag_UseIndex url <- flags ]

optCssFile :: [Flag] -> Maybe FilePath
optCssFile flags = optLast [ str | Flag_CSS str <- flags ]

optSourceCssFile :: [Flag] -> Maybe FilePath
optSourceCssFile flags = optLast [ str | Flag_SourceCss str <- flags ]

sourceUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String, Maybe String)
sourceUrls flags =
  (optLast [str | Flag_SourceBaseURL    str <- flags]
  ,optLast [str | Flag_SourceModuleURL  str <- flags]
  ,optLast [str | Flag_SourceEntityURL  str <- flags]
  ,optLast [str | Flag_SourceLEntityURL str <- flags])

wikiUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String)
wikiUrls flags =
  (optLast [str | Flag_WikiBaseURL   str <- flags]
  ,optLast [str | Flag_WikiModuleURL str <- flags]
  ,optLast [str | Flag_WikiEntityURL str <- flags])

optDumpInterfaceFile :: [Flag] -> Maybe FilePath
optDumpInterfaceFile flags = optLast [ str | Flag_DumpInterface str <- flags ]

optShowInterfaceFile :: [Flag] -> Maybe FilePath
optShowInterfaceFile flags = optLast [ str | Flag_ShowInterface str <- flags ]

optLaTeXStyle :: [Flag] -> Maybe String
optLaTeXStyle flags = optLast [ str | Flag_LaTeXStyle str <- flags ]

optMathjax :: [Flag] -> Maybe String
optMathjax flags = optLast [ str | Flag_Mathjax str <- flags ]

qualification :: [Flag] -> Either String QualOption
qualification flags =
  case map (map Char.toLower) [ str | Flag_Qualification str <- flags ] of
      []             -> Right OptNoQual
      ["none"]       -> Right OptNoQual
      ["full"]       -> Right OptFullQual
      ["local"]      -> Right OptLocalQual
      ["relative"]   -> Right OptRelativeQual
      ["aliased"]    -> Right OptAliasedQual
      [arg]          -> Left $ "unknown qualification type " ++ show arg
      _:_            -> Left "qualification option given multiple times"

verbosity :: [Flag] -> Verbosity
verbosity flags =
  case [ str | Flag_Verbosity str <- flags ] of
    []  -> normal
    x:_ -> case parseVerbosity x of
      Left e -> throwE e
      Right v -> v

ghcFlags :: [Flag] -> [String]
ghcFlags flags = [ option | Flag_OptGhc option <- flags ]

reexportFlags :: [Flag] -> [String]
reexportFlags flags = [ option | Flag_Reexport option <- flags ]

readIfaceArgs :: [Flag] -> [(DocPaths, FilePath)]
readIfaceArgs flags = [ parseIfaceOption s | Flag_ReadInterface s <- flags ]
  where
    parseIfaceOption :: String -> (DocPaths, FilePath)
    parseIfaceOption str =
      case break (==',') str of
        (fpath, ',':rest) ->
          case break (==',') rest of
            (src, ',':file) -> ((fpath, Just src), file)
            (file, _) -> ((fpath, Nothing), file)
        (file, _) -> (("", Nothing), file)

-- | Like 'listToMaybe' but returns the last element instead of the first.
optLast :: [a] -> Maybe a
optLast [] = Nothing
optLast xs = Just (last xs)

redpajama_set_name: RedPajamaGithub


text:
package layers;

public class GraphCreationTest50 extends GraphCreationTest {

	public GraphCreationTest50() throws Exception {
		super();

		setRepeat(50);
	}
}


text:
<?php

namespace spec\Sylius\Bundle\PromotionBundle\Form\Type\Action;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\PromotionBundle\Form\Type\Action\FixedDiscountConfigurationType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
final class FixedDiscountConfigurationTypeSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(FixedDiscountConfigurationType::class);
    }

    function it_is_a_form_type()
    {
        $this->shouldHaveType(AbstractType::class);
    }

    function it_builds_a_form_with_count_field_and_equal_checkbox(FormBuilderInterface $builder)
    {
        $builder
            ->add('amount', 'sylius_money', Argument::any())
            ->willReturn($builder)
        ;

        $this->buildForm($builder, []);
    }
}


text:
package eu.bcvsolutions.idm.core.workflow.model.dto;

public class IdentityLinkDto {

	String type;
	String userId;
	String groupId;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getGroupId() {
		return groupId;
	}

	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}
}


text:
package fi.vrk.xroad.catalog.collector.actors;

import fi.vrk.xroad.catalog.collector.util.ClientTypeUtil;
import fi.vrk.xroad.catalog.collector.util.MethodListUtil;
import fi.vrk.xroad.catalog.collector.util.XRoadClient;
import fi.vrk.xroad.catalog.collector.util.XRoadRestServiceIdentifierType;
import fi.vrk.xroad.catalog.collector.wsimport.ClientType;
import fi.vrk.xroad.catalog.collector.wsimport.XRoadObjectType;
import fi.vrk.xroad.catalog.collector.wsimport.XRoadServiceIdentifierType;
import fi.vrk.xroad.catalog.persistence.CatalogService;
import fi.vrk.xroad.catalog.persistence.entity.Member;
import fi.vrk.xroad.catalog.persistence.entity.Service;
import fi.vrk.xroad.catalog.persistence.entity.Subsystem;
import akka.actor.ActorRef;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Scope("prototype")
@Slf4j
public class ListMethodsActor extends XRoadCatalogActor {

    private static AtomicInteger methodCounter = new AtomicInteger(0);

    private boolean organizationsFetched = false;

    private static final String SERVICE_TYPE_REST = "REST";

    @Value("${xroad-catalog.security-server-host}")
    private String xroadSecurityServerHost;

    @Value("${xroad-catalog.xroad-instance}")
    private String xroadInstance;

    @Value("${xroad-catalog.member-code}")
    private String memberCode;

    @Value("${xroad-catalog.member-class}")
    private String memberClass;

    @Value("${xroad-catalog.subsystem-code}")
    private String subsystemCode;

    @Value("${xroad-catalog.webservices-endpoint}")
    private String webservicesEndpoint;

    @Value("${xroad-catalog.fetch-companies-time-after-hour}")
    private Integer fetchCompaniesTimeAfterHour;

    @Value("${xroad-catalog.fetch-companies-time-before-hour}")
    private Integer fetchCompaniesTimeBeforeHour;

    @Value("${xroad-catalog.fetch-companies-run-unlimited}")
    private Boolean fetchCompaniesUnlimited;

    @Value("${xroad-catalog.error-log-length-in-days}")
    private Integer errorLogLengthInDays;

    @Value("${xroad-catalog.flush-log-time-after-hour}")
    private Integer flushLogTimeAfterHour;

    @Value("${xroad-catalog.flush-log-time-before-hour}")
    private Integer flushLogTimeBeforeHour;

    @Autowired
    protected CatalogService catalogService;

    // supervisor-created pool of list methods actors
    private ActorRef fetchWsdlPoolRef;
    private ActorRef fetchOpenApiPoolRef;

    private ActorRef fetchRestPoolRef;
    private ActorRef fetchOrganizationsPoolRef;
    private ActorRef fetchCompaniesPoolRef;
    private XRoadClient xroadClient;

    public ListMethodsActor(ActorRef fetchWsdlPoolRef,
                            ActorRef fetchOpenApiPoolRef,
                            ActorRef fetchRestPoolRef,
                            ActorRef fetchOrganizationsPoolRef,
                            ActorRef fetchCompaniesPoolRef) {
        this.fetchWsdlPoolRef = fetchWsdlPoolRef;
        this.fetchOpenApiPoolRef = fetchOpenApiPoolRef;
        this.fetchRestPoolRef = fetchRestPoolRef;
        this.fetchOrganizationsPoolRef = fetchOrganizationsPoolRef;
        this.fetchCompaniesPoolRef = fetchCompaniesPoolRef;
    }

    @Override
    public void preStart() throws Exception {
        xroadClient = new XRoadClient(
                ClientTypeUtil.toSubsystem(xroadInstance, memberClass, memberCode, subsystemCode),
                new URL(webservicesEndpoint));
    }

    @Override
    protected boolean handleMessage(Object message) {
        if (message instanceof ClientType) {
            log.info("{} onReceive {}", methodCounter.addAndGet(1), this.hashCode());
            ClientType clientType = (ClientType) message;
            fetchOrganizations(clientType);
            fetchCompanies(clientType);
            flushErrorLogs();
            if (XRoadObjectType.SUBSYSTEM.equals(clientType.getId().getObjectType())) {
                saveSubsystemsAndServices(clientType);
            }
            return true;
        } else {
            return false;
        }
    }

    private void fetchOrganizations(ClientType clientType) {
        if (Boolean.FALSE.equals(organizationsFetched)) {
            fetchOrganizationsPoolRef.tell(clientType, getSelf());
            organizationsFetched = true;
        }
    }

    private void fetchCompanies(ClientType clientType) {
        if (MethodListUtil.shouldFetchCompanies(fetchCompaniesUnlimited, fetchCompaniesTimeAfterHour, fetchCompaniesTimeBeforeHour)) {
            fetchCompaniesPoolRef.tell(clientType, getSelf());
        }
    }

    private void flushErrorLogs() {
        if (MethodListUtil.shouldFlushLogEntries(flushLogTimeAfterHour, flushLogTimeBeforeHour)) {
            catalogService.deleteOldErrorLogEntries(errorLogLengthInDays);
        }
    }

    private void saveSubsystemsAndServices(ClientType clientType) {
        Subsystem subsystem = new Subsystem(
                new Member(clientType.getId().getXRoadInstance(), clientType.getId().getMemberClass(),
                        clientType.getId().getMemberCode(), clientType.getName()),
                clientType.getId().getSubsystemCode());

        log.info("{} Handling subsystem {} ", methodCounter, subsystem);

        List<XRoadRestServiceIdentifierType> restServices = MethodListUtil.methodListFromResponse(clientType,
                xroadSecurityServerHost, catalogService);
        log.info("Received all REST methods for client {} ", ClientTypeUtil.toString(clientType));

        List<XRoadServiceIdentifierType> soapServices = xroadClient.getMethods(clientType.getId(), catalogService);
        log.info("Received all SOAP methods for client {} ", ClientTypeUtil.toString(clientType));

        List<Service> services = new ArrayList<>();
        for (XRoadRestServiceIdentifierType service : restServices) {
            services.add(new Service(subsystem, service.getServiceCode(), service.getServiceVersion()));
        }
        for (XRoadServiceIdentifierType service : soapServices) {
            services.add(new Service(subsystem, service.getServiceCode(), service.getServiceVersion()));
        }

        catalogService.saveServices(subsystem.createKey(), services);

        for (XRoadServiceIdentifierType service : soapServices) {
            fetchWsdlPoolRef.tell(service, getSender());
        }

        for (XRoadRestServiceIdentifierType service : restServices) {
            if (service.getServiceType().equalsIgnoreCase(SERVICE_TYPE_REST)) {
                fetchRestPoolRef.tell(service, getSender());
            } else {
                fetchOpenApiPoolRef.tell(service, getSender());
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
HandlingInstructionInfo (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.commerce.order.purchase

Class HandlingInstructionInfo

java.lang.Object
  atg.commerce.order.purchase.HandlingInstructionInfo

All Implemented Interfaces:
java.io.Serializable

public class HandlingInstructionInfo
extends java.lang.Object
implements java.io.Serializable

This class is used to store handling instruction information for a commerce item on the CommerceItemShippingInfo.
 Each CommerceItemShippingInfo object contains a List of these objects for detailing the item's handling instructions within
 shipping group referenced by the CommerceItemShippingInfo.

 Objects of this type are generated by CommerceItemShippingInfoTools when creating CommerceItemShippingInfo objects
 for the CommerceItemShippingInfoContainer.

 These objects are used to split and merge the handling instructions along with their associated commerce item.

See Also:
CommerceItemShippingInfoTools,
Serialized Form

Field Summary

static java.lang.String
CLASS_VERSION

Constructor Summary

HandlingInstructionInfo()

          Creates a new HandlingInstructionInfo instance.

HandlingInstructionInfo(HandlingInstruction pHandlingInstruction)

          Creates a new HandlingInstructionInfo instance.

Method Summary

 HandlingInstruction
getHandlingInstruction()

          Return the HandlingInstruction property.

 long
getQuantity()

          Return the Quantity property.

 void
setHandlingInstruction(HandlingInstruction pHandlingInstruction)

          Set the HandlingInstruction property.

 void
setQuantity(long pQuantity)

          Set the Quantity property.

 java.lang.String
toString()

          Method that renders the general order information in a readable string format

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

CLASS_VERSION

public static java.lang.String CLASS_VERSION

Constructor Detail

HandlingInstructionInfo

public HandlingInstructionInfo()

Creates a new HandlingInstructionInfo instance.

HandlingInstructionInfo

public HandlingInstructionInfo(HandlingInstruction pHandlingInstruction)

Creates a new HandlingInstructionInfo instance.

Method Detail

setHandlingInstruction

public void setHandlingInstruction(HandlingInstruction pHandlingInstruction)

Set the HandlingInstruction property.

Parameters:
HandlingInstruction - a HandlingInstruction value

getHandlingInstruction

public HandlingInstruction getHandlingInstruction()

Return the HandlingInstruction property.

Returns:
a CommerceItem value

setQuantity

public void setQuantity(long pQuantity)

Set the Quantity property.

Parameters:
pQuantity - a long value

getQuantity

public long getQuantity()

Return the Quantity property.

Returns:
a long value

toString

public java.lang.String toString()

Method that renders the general order information in a readable string format

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
'''
Python mapping for the AppKit framework.

This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
'''
import sys
import objc
import Foundation

from AppKit import _metadata
from AppKit._inlines import _inline_list_

def NSDictionaryOfVariableBindings(*names):
    """
    Return a dictionary with the given names and there values.
    """
    import sys
    variables = sys._getframe(1).f_locals

    return {
        nm: variables[nm]
        for nm in names
    }

sys.modules['AppKit'] = mod = objc.ObjCLazyModule('AppKit',
        "com.apple.AppKit", objc.pathForFramework("/System/Library/Frameworks/AppKit.framework"),
        _metadata.__dict__, _inline_list_, {
            '__doc__': __doc__,
            'objc': objc,
            'NSDictionaryOfVariableBindings': NSDictionaryOfVariableBindings,
            '__path__': __path__,
        }, (Foundation,))

# NSApp is a global variable that can be changed in ObjC,
# somewhat emulate that (it is *not* possible to assign to
# NSApp in Python)
from AppKit._nsapp import NSApp
mod.NSApp = NSApp

# Manually written wrappers:
import AppKit._AppKit
for nm in dir(AppKit._AppKit):
    setattr(mod, nm, getattr(AppKit._AppKit, nm))

# Fix types for a number of character constants
try:
    unichr
except NameError:
    unichr = chr
mod.NSEnterCharacter = unichr(mod.NSEnterCharacter)
mod.NSBackspaceCharacter = unichr(mod.NSBackspaceCharacter)
mod.NSTabCharacter = unichr(mod.NSTabCharacter)
mod.NSNewlineCharacter = unichr(mod.NSNewlineCharacter)
mod.NSFormFeedCharacter = unichr(mod.NSFormFeedCharacter)
mod.NSCarriageReturnCharacter = unichr(mod.NSCarriageReturnCharacter)
mod.NSBackTabCharacter = unichr(mod.NSBackTabCharacter)
mod.NSDeleteCharacter = unichr(mod.NSDeleteCharacter)
mod.NSLineSeparatorCharacter = unichr(mod.NSLineSeparatorCharacter)
mod.NSParagraphSeparatorCharacter = unichr(mod.NSParagraphSeparatorCharacter)

for nm in [
   "NSUpArrowFunctionKey",
   "NSDownArrowFunctionKey",
   "NSLeftArrowFunctionKey",
   "NSRightArrowFunctionKey",
   "NSF1FunctionKey",
   "NSF2FunctionKey",
   "NSF3FunctionKey",
   "NSF4FunctionKey",
   "NSF5FunctionKey",
   "NSF6FunctionKey",
   "NSF7FunctionKey",
   "NSF8FunctionKey",
   "NSF9FunctionKey",
   "NSF10FunctionKey",
   "NSF11FunctionKey",
   "NSF12FunctionKey",
   "NSF13FunctionKey",
   "NSF14FunctionKey",
   "NSF15FunctionKey",
   "NSF16FunctionKey",
   "NSF17FunctionKey",
   "NSF18FunctionKey",
   "NSF19FunctionKey",
   "NSF20FunctionKey",
   "NSF21FunctionKey",
   "NSF22FunctionKey",
   "NSF23FunctionKey",
   "NSF24FunctionKey",
   "NSF25FunctionKey",
   "NSF26FunctionKey",
   "NSF27FunctionKey",
   "NSF28FunctionKey",
   "NSF29FunctionKey",
   "NSF30FunctionKey",
   "NSF31FunctionKey",
   "NSF32FunctionKey",
   "NSF33FunctionKey",
   "NSF34FunctionKey",
   "NSF35FunctionKey",
   "NSInsertFunctionKey",
   "NSDeleteFunctionKey",
   "NSHomeFunctionKey",
   "NSBeginFunctionKey",
   "NSEndFunctionKey",
   "NSPageUpFunctionKey",
   "NSPageDownFunctionKey",
   "NSPrintScreenFunctionKey",
   "NSScrollLockFunctionKey",
   "NSPauseFunctionKey",
   "NSSysReqFunctionKey",
   "NSBreakFunctionKey",
   "NSResetFunctionKey",
   "NSStopFunctionKey",
   "NSMenuFunctionKey",
   "NSUserFunctionKey",
   "NSSystemFunctionKey",
   "NSPrintFunctionKey",
   "NSClearLineFunctionKey",
   "NSClearDisplayFunctionKey",
   "NSInsertLineFunctionKey",
   "NSDeleteLineFunctionKey",
   "NSInsertCharFunctionKey",
   "NSDeleteCharFunctionKey",
   "NSPrevFunctionKey",
   "NSNextFunctionKey",
   "NSSelectFunctionKey",
   "NSExecuteFunctionKey",
   "NSUndoFunctionKey",
   "NSRedoFunctionKey",
   "NSFindFunctionKey",
   "NSHelpFunctionKey",
   "NSModeSwitchFunctionKey",
   ]:
    try:
        setattr(mod, nm, unichr(getattr(mod, nm)))
    except AttributeError:
        pass

try:
    mod.NSImageNameApplicationIcon
except AttributeError:
    mod.NSImageNameApplicationIcon = "NSApplicationIcon"


text:
#ifndef SimTK_SIMMATH_VERLET_INTEGRATOR_REP_H_
#define SimTK_SIMMATH_VERLET_INTEGRATOR_REP_H_

#include "AbstractIntegratorRep.h"

namespace SimTK {

class VerletIntegratorRep : public AbstractIntegratorRep {
public:
    VerletIntegratorRep(Integrator* handle, const System& sys);
protected:
    bool attemptDAEStep
       (Real t1, Vector& yErrEst, int& errOrder, int& numIterations);
};

} // namespace SimTK

#endif // SimTK_SIMMATH_VERLET_INTEGRATOR_REP_H_


text:
class CreateMarks < ActiveRecord::Migration
  extend MigrationHelpers
  def self.up
    create_table :marks do |t|
      t.integer :result_id
      t.integer :criterion_id
      t.integer :mark

      t.timestamps
    end

     foreign_key :marks, :result_id,  :results

  end

  def self.down
    drop_table :marks
  end
end


text:
C++ = g++ #default version of fedorq14: 4.5.1

CFLAGS = -DBits64_ -m64 -DUNIX -D_BOOL -DLINUX -DFUNCPROTO -D_GNU_SOURCE -DLINUX_64 -fPIC \
         -fno-strict-aliasing -DREQUIRE_IOSTREAM -Wno-deprecated -O3 -Wall \
         -Wno-multichar -Wno-comment -Wno-sign-compare -funsigned-char \
         -Wno-reorder -fno-gnu-keywords -ftemplate-depth-25 -pthread -fopenmp

C++FLAGS = $(CFLAGS) -Wno-deprecated -fno-gnu-keywords

# Maya installed path and version
MAYA_LOCATION = /usr/autodesk/maya2013-x64
MAYA_VERSION = 2013

# SeExpr binary path where you installed
SEEXPR_LOCATION = /usr/local

INCLUDES = -I$(MAYA_LOCATION)/include -I$(SEEXPR_LOCATION)/include
LFLAGS   = -Wl,-Bsymbolic -shared
LIBS     = -L$(MAYA_LOCATION)/lib -ldl -lOpenMaya -lOpenMayaAnim -lFoundation
EXT      = so

ALL_CPP_FILES = SeExprMeshCmd.cpp SeExprMeshNode.cpp ClosestPointFunc.cpp pluginMain.cpp
OBJS = SeExprMeshCmd.o SeExprMeshNode.o ClosestPointFunc.o pluginMain.o $(SEEXPR_LOCATION)/lib64/libSeExpr.a

OUT_DIR = ../build/$(MAYA_VERSION)

### You have to change here where you want ###
INSTALL_DIR = /home/username/foo/bar

TARGET = SeExprMesh.$(EXT)

all: build $(TARGET)

$(TARGET): $(OBJS)
	$(C++) -o $(OUT_DIR)/$@ $(INCLUDES) $(C++FLAGS) $(OBJS) $(LFLAGS) $(LIBS)
	chmod -x $(OUT_DIR)/$@

preprocess: seExprMeshNode.cpp
	$(C++) -E -o $<_prepro.cpp $(INCLUDES) $(C++FLAGS) $<

depend:
	makedepend -- $(C++FLAGS) -- $(ALL_CPP_FILES)

build: $(ALL_CPP_FILES)
	mkdir -p $(OUT_DIR)
.PHONY: build

install: installAE
	mkdir -p $(INSTALL_DIR)/plug-ins
	cp -f $(OUT_DIR)/$(TARGET) $(INSTALL_DIR)/plug-ins
.PHONY: install

installAE:
	mkdir -p $(INSTALL_DIR)/scripts
	cp -f ../scripts/AEseExprMeshTemplate.mel $(INSTALL_DIR)/scripts
.PHONY: installAE

clean:
	rm -f *.o
.PHONY: clean

.cpp.o:
	$(C++) -o $@ -c $(INCLUDES) $(C++FLAGS) $<


text:
/*
 *  This contains basic declarations, should be included everywhere one way or another
 */

#include <v8.h>
#include <node.h>
#include <doublefann.h>

using namespace v8;
using namespace node;

const char TRAIN_PREFIX[]  = "FANN_TRAIN_";
const char FANN_PREFIX[]  = "FANN_";
const char NETTYPE_PREFIX[]  = "FANN_NETTYPE_";
const char STOPFUNC_PREFIX[]  = "FANN_STOPFUNC_";
const char ERRORFUNC_PREFIX[]  = "FANN_ERRORFUNC_";

Handle<Value> NormalizeName(const char* origname, const char* prefix, int prefix_len);
int _SeekCharArray(Local<String> value, const char* const* array, int size, const char* prefix);
char* strncpy_lower(char *dest, const char *src, size_t n);
Handle<Value> VException(const char *msg);

Handle<Value> GetTrainingAlgorithmList(const Arguments &args);
Handle<Value> GetActivationFunctionList(const Arguments &args);
Handle<Value> GetErrorFuncList(const Arguments &args);
Handle<Value> GetStopFuncList(const Arguments &args);
Handle<Value> GetNetworkTypeList(const Arguments &args);


text:
#ifndef _lucene_index_Term_
#define _lucene_index_Term_

CL_NS_DEF(index)

/**
A Term represents a word from text.  This is the unit of search.  It is
composed of two elements, the text of the word, as a string, and the name of
the field that the text occured in, an interned string.

Note that terms may represent more than words from text fields, but also
things like dates, email addresses, urls, etc.

IMPORTANT NOTE:
Term inherits from the template class LUCENE_REFBASE which tries to do
some garbage collection by counting the references an instance has. As a result
of this construction you MUST use _CLDECDELETE(obj) when you want to delete an
of Term!

ABOUT intrn

intrn indicates if field and text are interned or not. Interning of Strings is the process of
converting duplicated strings to shared ones.

*/
class CLUCENE_EXPORT Term:LUCENE_REFBASE {
private:
  size_t cachedHashCode;
	const TCHAR* _field;
	//CLStringIntern::iterator fielditr;
#ifdef LUCENE_TERM_TEXT_LENGTH
	TCHAR _text[LUCENE_TERM_TEXT_LENGTH+1];
#else
	TCHAR* _text;
	size_t textLenBuf; //a cache of text len, this allows for a preliminary comparison of text lengths
	//bool    dupT;    //Indicates if Term Text is duplicated (and therefore must be deleted).
#endif
	size_t textLen; //a cache of text len, this allows for a preliminary comparison of text lengths
	bool    internF; //Indicates if Term Field is interned(and therefore must be uninternd).
public:

	//uses the specified fieldTerm's field. this saves on intern'ing time.
  /** Constructs a Term with the given field and text.
   *
Note that a null field or null text value results in undefined
   * behavior for most Lucene APIs that accept a Term parameter.
  */
	Term(const Term* fieldTerm, const TCHAR* txt);

	/** Constructs a blank term */
	Term();

  /** Constructs a Term with the given field and text.
   *
Note that a null field or null text value results in undefined
   * behavior for most Lucene APIs that accept a Term parameter.
  */
	Term(const TCHAR* fld, const TCHAR* txt, bool internField);

	/**
	* Constructor. Constructs a Term with the given field and text. Field and text are not copied
	* Field and text are deleted in destructor only if intern is false.
	*
Note that a null field or null text value results in undefined
	* behavior for most Lucene APIs that accept a Term parameter.
	*/
	Term(const TCHAR* fld, const TCHAR* txt);

	///Destructor.
	~Term();

	///Returns the field of this term, an interned string. The field indicates
	///the part of a document which this term came from.
	const TCHAR* field() const; ///<returns reference

	///Returns the text of this term.  In the case of words, this is simply the
	///text of the word.  In the case of dates and other types, this is an
	///encoding of the object as a string.
	const TCHAR* text() const; ///<returns reference

	///Resets the field and text of a Term.
	inline void set(const TCHAR* fld, const TCHAR* txt){
		set(fld,txt,true);
	}

	/**
	* Optimized set of Term by reusing same field as this Term
	* - avoids field.intern() overhead
	* @param text The text of the new term (field is implicitly same as this Term instance)
	*/
	void set(const Term* term, const TCHAR* txt);

	void set(const TCHAR* fld, const TCHAR* txt, const bool internField);

	/** Compares two terms, returning a negative integer if this
	term belongs before the argument, zero if this term is equal to the
	argument, and a positive integer if this term belongs after the argument.

	The ordering of terms is first by field, then by text.*/
	int32_t compareTo(const Term* other) const;

	/** Compares two terms, returning a negative integer if this
	term belongs before the argument, zero if this term is equal to the
	argument, and a positive integer if this term belongs after the argument.

	The ordering of terms is purely on the hashCode, so is not a logical ordering, but is repeatable.
	Note: can't be const because call the to hashCode is not const
	*/
	int32_t hashedCompareTo(Term* other);

	bool equals(const Term* other) const;

	size_t textLength() const;

	///Forms the contents of Field and term in some kind of tuple notation
	///<field:text>
	TCHAR* toString() const;

	size_t hashCode();
};

class Term_UnorderedCompare:LUCENE_BASE, public CL_NS(util)::Compare::_base //<Term*>
{
public:
	bool operator()( Term* t1, Term* t2 ) const{
		return ( t1->hashedCompareTo(t2) < 0 );
	}
	size_t operator()( Term* t ) const{
		return t->hashCode();
	}
};

CL_NS_END
#endif


text:
package tld.testmod;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.*;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import tld.testmod.common.CommonProxy;
import tld.testmod.common.animation.*;
import tld.testmod.common.entity.EntityPull;
import tld.testmod.common.entity.living.EntityGoldenSkeleton;
import tld.testmod.common.entity.living.EntityTimpani;
import tld.testmod.common.handlers.GUIHandler;
import tld.testmod.common.handlers.SpawnHandler;
import tld.testmod.common.storage.FileHelper;
import tld.testmod.common.storage.ServerDataManager;
import tld.testmod.common.storage.capability.MusicDBCapability;
import tld.testmod.common.world.chunk.ModChunkCapability;
import tld.testmod.init.ModBlocks;
import tld.testmod.network.PacketDispatcher;

@Mod(
        modid = Main.MOD_ID, version = Main.VERSION,
        name = Main.MOD_NAME, dependencies = Main.DEPENDENCIES,
        certificateFingerprint = "999640c365a8443393a1a21df2c0ede9488400e9"
)
public class Main
{
    public static final String MOD_ID = "testmod";
    static final String MOD_NAME = "Test Mod";
    public static final String VERSION = "{@VERSION}";
    public static final String DEPENDENCIES = "required-after:forge@[14.23.5.2768,);";
    private static int modEntityId = 0;

    @Mod.Instance(MOD_ID)
    public static Main instance;

    @SidedProxy(clientSide = "tld.testmod.client.ClientProxy", serverSide = "tld.testmod.common.CommonProxy")
    public static CommonProxy proxy;

    public static final CreativeTabs MOD_TAB = new ModTab();

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
        ModLogger.setLogger(event.getModLog());
        PacketDispatcher.registerPackets();
        ModChunkCapability.register();
        MusicDBCapability.register();
        proxy.preInit();
        ModBlocks.registerTileEntities();
        MinecraftForge.EVENT_BUS.register(SpawnHandler.INSTANCE);
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        proxy.init();
        NetworkRegistry.INSTANCE.registerGuiHandler(instance, GUIHandler.getInstance());
        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "test_skeleton"), EntityGoldenSkeleton.class, "test_skeleton", getNextModEntityId(), this, 64, 1, true, 0x000000, 0xE6BA50);
        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "mob_timpani"), EntityTimpani.class, "mob_timpani", getNextModEntityId(), this, 64, 1, true, 0x000000, 0xFF5121);

        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "entity_forge_anim_test"), ForgeAnimEntity.class, "entity_forge_anim_test", getNextModEntityId(), this, 64, 20, true);
        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "entity_forge_spin_test"), ForgeSpinEntity.class, "entity_forge_spin_test", getNextModEntityId(), this, 64, 20, true);
        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "entity_edgar_allen_block_lever"), EdgarAllenAnimEntity.class, "entity_edgar_allen_block_lever", getNextModEntityId(), this, 64, 20, true);
        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "entity_one_shot"), OneShotEntity.class, "entity_one_shot", getNextModEntityId(), this, 64, 20, true);
        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "entity_test_anim"), TestAnimEntity.class, "entity_test_anim", getNextModEntityId(), this, 64, 20, true);

        EntityRegistry.registerModEntity(new ResourceLocation(MOD_ID, "entity_pull"), EntityPull.class, "entity_pull", getNextModEntityId(), this, 64, 20, true);
    }

    @EventHandler
    public void postInit(FMLPostInitializationEvent event)
    {
        proxy.postInit();
    }

    @Mod.EventHandler
    public void onEvent(FMLServerStartingEvent event)
    {
        FileHelper.initServerStorage();
        ServerDataManager.start();
    }

    @Mod.EventHandler
    public void onEvent(FMLServerStoppingEvent event)
    {
        ServerDataManager.shutdown();
    }

    private int getNextModEntityId()
    {
        return modEntityId++;
    }

    public static String prependModID(String name)
    {
        return MOD_ID + ":" + name;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Csla.Serialization;

#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif

namespace Csla.Test.IO
{
  [TestClass]
  public class DPMethodOverloadTests
  {
    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void CreateNoCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.NewNoCriteria();
      Assert.IsNotNull(obj, "Failed to get object with no criteria");
      Assert.AreEqual("No criteria", Csla.ApplicationContext.GlobalContext["Create"], "No criteria expected");
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void CreateWithCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.NewCriteria();
      Assert.IsNotNull(obj, "Failed to get object with criteria");
      Assert.AreEqual("Criteria", Csla.ApplicationContext.GlobalContext["Create"], "Criteria expected");
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void CreateWithOtherCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.NewOtherCriteria();
      Assert.IsNotNull(obj, "Failed to get object with other criteria");
      Assert.AreEqual("Other criteria", Csla.ApplicationContext.GlobalContext["Create"], "Other criteria expected");
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void FetchNullCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.GetNullCriteria();
      Assert.IsNotNull(obj, "Failed to get object with null criteria");
      Assert.AreEqual("Null criteria", Csla.ApplicationContext.GlobalContext["Fetch"], "Null criteria expected");
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void FetchNoCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.GetNoCriteria();
      Assert.IsNotNull(obj, "Failed to get object with no criteria");
      Assert.AreEqual("No criteria", Csla.ApplicationContext.GlobalContext["Fetch"], "No criteria expected");
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void FetchWithCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.GetCriteria();
      Assert.IsNotNull(obj, "Failed to get object with criteria");
      Assert.AreEqual("Criteria", Csla.ApplicationContext.GlobalContext["Fetch"], "Criteria expected");
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void FetchWithOtherCriteria()
    {
      Csla.ApplicationContext.GlobalContext.Clear();

      TestBizObj obj;

      obj = TestBizObj.GetOtherCriteria();
      Assert.IsNotNull(obj, "Failed to get object with other criteria");
      Assert.AreEqual("Other criteria", Csla.ApplicationContext.GlobalContext["Fetch"], "Other criteria expected");
    }
  }

  [Serializable]
  public class TestBizObj : Csla.BusinessBase<TestBizObj>
  {
    protected override object GetIdValue()
    {
      return 0;
    }

    public static TestBizObj NewNoCriteria()
    {
      return Csla.DataPortal.Create<TestBizObj>();
    }

    public static TestBizObj NewCriteria()
    {
      return Csla.DataPortal.Create<TestBizObj>(new Criteria());
    }

    public static TestBizObj NewOtherCriteria()
    {
      return Csla.DataPortal.Create<TestBizObj>(new OtherCriteria());
    }

    public static TestBizObj GetNoCriteria()
    {
      return Csla.DataPortal.Fetch<TestBizObj>();
    }

    public static TestBizObj GetNullCriteria()
    {
      return Csla.DataPortal.Fetch<TestBizObj>(null);
    }

    public static TestBizObj GetCriteria()
    {
      return Csla.DataPortal.Fetch<TestBizObj>(new Criteria());
    }

    public static TestBizObj GetOtherCriteria()
    {
      return Csla.DataPortal.Fetch<TestBizObj>(new OtherCriteria());
    }

    [Serializable]
    private class Criteria
    {
    }

    [Serializable]
    private class OtherCriteria
    {
    }

    protected override void DataPortal_Create()
    {
      Csla.ApplicationContext.GlobalContext["Create"] = "No criteria";
    }

    private void DataPortal_Create(object criteria)
    {
      if (criteria == null)
        Csla.ApplicationContext.GlobalContext["Create"] = "null criteria";
      else
        Csla.ApplicationContext.GlobalContext["Create"] = "Other criteria";
    }

    private void DataPortal_Create(Criteria criteria)
    {
      Csla.ApplicationContext.GlobalContext["Create"] = "Criteria";
    }

    private void DataPortal_Fetch()
    {
      Csla.ApplicationContext.GlobalContext["Fetch"] = "No criteria";
    }

    protected void DataPortal_Fetch(object criteria)
    {
      if (criteria == null)
        Csla.ApplicationContext.GlobalContext["Fetch"] = "Null criteria";
      else
        Csla.ApplicationContext.GlobalContext["Fetch"] = "Other criteria";
    }

    private void DataPortal_Fetch(Criteria criteria)
    {
      Csla.ApplicationContext.GlobalContext["Fetch"] = "Criteria";
    }
  }
}


text:
'use strict';

var BaseNode = require('./Base');

function MultiplicativeExpressionNode(operator, left, right) {
  for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
    args[_key - 3] = arguments[_key];
  }

  BaseNode.call(this, Object.assign.apply(Object, [{}, { type: 'MultiplicativeExpression' }].concat(args)));
  this.operator = operator;
  this.left = left;
  this.right = right;
}

exports.MultiplicativeExpressionNode = MultiplicativeExpressionNode;


text:
// Type definitions for PhoneGap 2.3
// Project: http://phonegap.com
// Definitions by: Boris Yankov <https://github.com/borisyankov>, Dick van den Brink <https://github.com/DickvdBrink>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

interface GeolocationError {
    code: number;
    message: string;
}

interface Acceleration {
    x: number;
    y: number;
    z: number;
    timestamp: number; //DOMTimeStamp;
}
declare var Acceleration: {
    new(): Acceleration;
}

interface AccelerometerOptions {
    frequency?: number;
}

interface Accelerometer {
    getCurrentAcceleration(accelerometerSuccess: (acceleration: Acceleration) => void , accelerometerError: () => void ): void;
    watchAcceleration(accelerometerSuccess: (acceleration: Acceleration) => void , accelerometerError: () => void , accelerometerOptions?: AccelerometerOptions): void;
    clearWatch(watchID: number): void;
}

interface CameraPopoverOptions {
    x?: number;
    y?: number;
    width?: number;
    height?: number;
    arrowDir?: number;
}
declare var CameraPopoverOptions: {
    new(x: number, y: number, width: number, height: number, arrowDir: number): CameraPopoverOptions;
}

interface CameraOptions {
    quality?: number;
    destinationType?: number;
    sourceType?: number;
    allowEdit?: boolean;
    encodingType?: number;
    targetWidth?: number;
    targetHeight?: number;
    mediaType?: number;
    correctOrientation?: boolean;
    saveToPhotoAlbum?: boolean;
    popoverOptions?: CameraPopoverOptions;
}

interface CameraPictureSourceTypeObject {
    CAMERA: number;
    PHOTOLIBRARY: number;
    SAVEDPHOTOALBUM: number;
}

interface CameraDestinationTypeObject {
    FILE_URI: number;
    DATA_URL: number;
}

interface CameraEncodingTypeObject {
    JPEG: number;
    PNG: number;
}

interface CameraMediaTypeObject {
    PICTURE: number;
    VIDEO: number;
    ALLMEDIA: number;
}

interface CameraPopoverArrowDirectionObject {
    ARROW_UP: number;
    ARROW_DOWN: number;
    ARROW_LEFT: number;
    ARROW_RIGHT: number;
    ARROW_ANY: number;
}

interface Camera {
    sourceType: any;
    PictureSourceType: CameraPictureSourceTypeObject;
    DestinationType: CameraDestinationTypeObject;
    EncodingType: CameraEncodingTypeObject;
    MediaType: CameraMediaTypeObject;
    PopoverArrowDirection: CameraPopoverArrowDirectionObject;
    getPicture(cameraSuccess: (imageData: string) => void , cameraError: (message: string) => void , cameraOptions?: CameraOptions): void;
    cleanup(cameraSuccess: (imageData: string) => void , cameraError: (message: string) => void ): void;
}

interface CaptureAudioOptions {
    limit?: number;
    duration?: number;
    mode?: number;
}

interface CaptureImageOptions {
    limit?: number;
    mode?: number;
}

interface MediaFile {
    name: string;
    fullPath: string;
    type: string;
    lastModifiedDate: Date;
    size: number;

    getFormatData(successCallback: Function, errorCallback?: Function): void;
}

interface CaptureError {
    code: number;
    message: string;
}

interface Capture {
    captureAudio(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureAudioOptions): void;
    captureImage(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions): void;
    captureVideo(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions): void;
}

interface Connection {
    UNKNOWN: number;
    ETHERNET: number;
    WIFI: number;
    CELL_2G: number;
    CELL_3G: number;
    CELL_4G: number;
    NONE: number;
}
declare var Connection: Connection;

interface CompassOptions {
    frequency?: number;
    filter?: number;
}

interface CompassHeading {
    magneticHeading?: number;
    trueHeading?: number;
    headingAccuracy?: number;
    timestamp?: number;
}

interface CompassError {
    code: number;
}

declare var CompassError: {
    COMPASS_INTERNAL_ERR: number;
    COMPASS_NOT_SUPPORTED: number;
}

interface Compass {
    getCurrentHeading(compassSuccess: (heading: CompassHeading) => void , compassError: (error: CompassError) => void , compassOptions?: CompassOptions): void;
    watchHeading(compassSuccess: (heading: CompassHeading) => void , compassError: (error: CompassError) => void , compassOptions?: CompassOptions): void;
    clearWatch(watchID: number): void;
}

interface Connection {
    type: number;
}

interface ContactAddress {
    pref: boolean;
    type: string;
    formatted: string;
    streetAddress: string;
    locality: string;
    region: string;
    postalCode: string;
    country: string;
}

interface ContactField {
    type: string;
    value: string;
    pref: boolean;
}
declare var ContactField: {
    new(type: string, calue: string, perf: boolean): ContactField;
}

interface Contact {
    id: string;
    displayName: string;
    name: ContactName;
    nickname: string;
    phoneNumbers: ContactField[];
    emails: ContactField[];
    addresses: ContactAddress[];
    ims: ContactField[];
    organizations: ContactOrganization[];
    birthday: Date;
    note: string;
    photos: ContactField[];
    categories: ContactField[];
    urls: ContactField[];

    save(onSuccess?: (contacts: Contacts) => void, onError?: (contactError: ContactError) => void): void;
    remove(onSuccess?: (contacts: Contacts) => void, onError?: (contactError: ContactError) => void): void;
    clone(): Contact;
}

interface ContactFindOptions {
    filter?: string;
    multiple?: boolean;
}
declare var ContactFindOptions : {
    new(): ContactFindOptions;
}

interface ContactName {
    formatted: string;
    familyName: string;
    givenName: string;
    middleName: string;
    honorificPrefix: string;
    honorificSuffix: string;
}
declare var ContactName: {
    new(): ContactName;
}

interface ContactOrganization {
    pref: boolean;
    type: string;
    name: string;
    department: string;
    title: string;
}

interface ContactError {
    code: number;
}

declare var ContactError: {
    UNKNOWN_ERROR: number;
    INVALID_ARGUMENT_ERROR: number;
    TIMEOUT_ERROR: number;
    PENDING_OPERATION_ERROR: number;
    IO_ERROR: number;
    NOT_SUPPORTED_ERROR: number;
    PERMISSION_DENIED_ERROR: number;
}

interface Contacts {
    create(properties?: any): Contact;
    find(contactFields: string[], contactSuccess: (contacts: Contact[]) => void , contactError: (error: ContactError) => void , contactFindOptions?: ContactFindOptions): void;
}

interface Device {
    available: boolean;
    name: string;
    cordova: string;
    platform: string;
    uuid: string;
    version: string;
    model: string;
    capture: Capture;
}

/* Defined in lib.d.ts
interface File {
    fullPath: string;
    type: string;
    size: number;
}
*/

interface FileWriter {
    readyState: any;
    fileName: string;
    length: number;
    position: number;
    error: FileError;

    onwritestart: Function;
    onprogress: Function;
    onwrite: Function;
    onabort: Function;
    onerror: Function;
    onwriteend: Function;

    abort(): void;
    seek(arg: number): void;
    truncate(arg: number): void;
    write(arg: any): void;
}

interface FileSystem {
    name: string;
    root: DirectoryEntry;
}
declare var DirectoryEntry: {
    new(name: string, root: DirectoryEntry): DirectoryEntry;
}

interface FileSystemEntry {
    isFile: boolean;
    isDirectory: boolean;
    name: string;
    fullPath: string;
    filesystem: FileSystem;

    getMetadata(onSuccess?: (arg: Metadata) => void, onError?: (arg: FileError) => void): void;
    setMetadata(onSuccess?: (arg: Metadata) => void, onError?: (arg: FileError) => void, options?: any): void;
    toURL(): string;
    remove(onSuccess?: () => void, onError?: (arg: FileError) => void): void;
    getParent(onSuccess?: (arg: DirectoryEntry) => void, onError?: (arg: FileError) => void): void;
}

interface FileEntry extends FileSystemEntry {
    moveTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg: DirectoryEntry) => void, onError: (arg: FileError) => void): void;
    copyTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg: DirectoryEntry) => void, onError: (arg: FileError) => void): void;
    createWriter(onSuccess?: (arg: FileWriter) => void, onError?: (arg: FileError) => void): void;
    file(onSuccess?: (arg: File) => void, onError?: (arg: FileError) => void): void;
}

interface DirectoryEntry extends FileSystemEntry {
    createReader(): DirectoryReader;
    getDirectory(path: string, options: Flags, successCallback: (result: DirectoryEntry) => void, errorCallback: (error: FileError) => void): void;
    getFile(path: string, options: Flags, successCallback: (result: FileEntry) => void, errorCallback: (error: FileError) => void): void;
    removeRecursively(successCallback: () => void, errorCallback: (error: FileError) => void): void;
}

interface DirectoryReader {
    readEntries(successCallback: (entries: FileSystemEntry) => void, errorCallback: (error: FileError) => void): void;
}

interface FileTransfer {
    onprogress: Function;

    //upload(filePath: string, server: string, successCallback: (metadata: Metadata) => void , errorCallback: (error: FileError) => void , options?: any): void;
    upload(filePath: string, server: string, successCallback: (result: FileUploadResult) => void , errorCallback: (error: FileError) => void , options?: any): void;
    download(source: string, target: string, successCallback: (fileEntry: FileEntry) => void , errorCallback: (error: FileError) => void, options?: any): void;
    abort(): void;
}
declare var FileTransfer: {
    new(): FileTransfer;
}

interface FileUploadOptions {
    fileKey?: string;
    fileName?: string;
    mimeType?: string;
    params?: any;
    chunkedMode?: boolean;
    headers?: any;
}
declare var FileUploadOptions: {
    new(): FileUploadOptions;
}

interface FileUploadResult {
    bytesSent: number;
    responseCode: number;
    response: string;
}

interface Flags {
    create: boolean;
    exclusive?: boolean;
}

/*
interface LocalFileSystem {
    requestFileSystem: Function;
    resolveLocalFileSystemURI: Function;
}*/

interface LocalFileSystem {
    PERSISTENT: number;
    TEMPORARY: number;
}
declare var LocalFileSystem: LocalFileSystem;

interface Metadata {
    modificationTime: Date;
}

interface FileError {
    code: number;
}
declare var FileError: {
    NOT_FOUND_ERR: number;
    SECURITY_ERR: number;
    ABORT_ERR: number;
    NOT_READABLE_ERR: number;
    ENCODING_ERR: number;
    NO_MODIFICATION_ALLOWED_ERR: number;
    INVALID_STATE_ERR: number;
    SYNTAX_ERR: number;
    INVALID_MODIFICATION_ERR: number;
    QUOTA_EXCEEDED_ERR: number;
    TYPE_MISMATCH_ERR: number;
    PATH_EXISTS_ERR: number;
}

interface FileTransferError {
    code: number;
    source: string;
    target: string;
    http_status: number;
}
declare var FileTransferError: {
    FILE_NOT_FOUND_ERR: number;
    INVALID_URL_ERR: number;
    CONNECTION_ERR: number;
    ABORT_ERR: number;
}

interface GeolocationOptions {
    enableHighAccuracy?: boolean;
    timeout?: number;
    maximumAge?: number;
}

interface GlobalizationError {
    code: number;
    message: string;
}

declare var GlobalizationError: {
    UNKNOWN_ERROR: number;
    FORMATTING_ERROR: number;
    PARSING_ERROR: number;
    PATTERN_ERROR: number;
}

interface GlobalizationDate {
    year: number;
    month: number;
    day: number;
    hour: number;
    minute: number;
    second: number;
    millisecond: number;
}

interface GlobalizationDateOptions {
    formatLength?: string;
    selector?: string;
}

interface GlobalizationDatePattern {
    pattern: string;
    timezone: string;
    utc_offset: number;
    dst_offset: number;
}

interface GlobalizationDateNameOptions {
    type?: string;
    item?: string;
}

interface GlobalizationNumberOptions {
    type?: string;
}

interface GlobalizationNumberPattern {
    pattern: string;
    symbol: string;
    fraction: number;
    rounding: number;
    positive: string;
    negative: string;
    decimal: string;
    grouping: string;
}

interface GlobalizationCurrencyPattern {
    pattern: string;
    code: string;
    fraction: number;
    rounding: number;
    decimal: string;
    grouping: string;
}

interface Globalization {
    getPreferredLanguage(successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void): void;
    getLocaleName(successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void): void;
    dateToString(date: Date, successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void;
    stringToDate(dateString: string, successCallback: (properties: GlobalizationDate) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void;
    getDatePattern(successCallback: (properties: GlobalizationDatePattern) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void;
    getDateNames(successCallback: (properties: {value: string[]}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateNameOptions): void;
    isDayLightSavingsTime(date: Date, successCallback: (properties: {dst: boolean}) => void, errorCallback: (error: GlobalizationError) => void): void;
    getFirstDayOfWeek(successCallback: (properties: {value: number}) => void, errorCallback: (error: GlobalizationError) => void): void;
    numberToString(number: number, successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void;
    stringToNumber(string: string, successCallback: (properties: {value: number}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void;
    getNumberPattern(successCallback: (parameters: GlobalizationNumberPattern) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void;
    getCurrencyPattern(currencyCode: string, successCallback: (parameters: GlobalizationCurrencyPattern) => void, errorCallback: (error: GlobalizationError) => void): void;
}

/*
interface InAppBrowser {
    addEventListener(eventname: string, callback): void;
    removeEventListener(eventname: string, callback): void;
    open(url?: string, target?: string, features?: string, replace?: boolean): Window;
    close(): void;
}
*/

interface Media {
    new (src: string, mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any, mediaStatus?: Function): Media;
    getCurrentPosition(mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any): void;
    getDuration(): any;
    play(): void;
    pause(): void;
    release(): void;
    seekTo(milliseconds: number): void;
    startRecord(): void;
    stopRecord(): void;
    stop(): void;
}
declare var Media: {
    new(src: string, onSuccess: (arg: any) => any, onError: (error: any) => any): Media;
}

interface PhonegapNotification {
    alert(message: string, alertCallback: Function, title?: string, buttonName?: string): void;
    confirm(message: string, confirmCallback: Function, title?: string, buttonLabels?: string): void;
	confirm(message: string, confirmCallback: Function, title?: string, buttonLabels?: string[]): void;
    beep(times: number): void;
    vibrate(milliseconds: number): void;
}

interface Splashscreen {
    show(): void;
    hide(): void;
}

interface Database {
    transaction(populateDB?: (tx: SQLTransaction) => any, errorCB?: (err: any) => any, successCB?: () => any): void;
    changeVersion(var1: string, var2: string): void;
}

interface SQLResultSetRowList {
    length: number;
    item(index: number): any;
}

interface SQLError {
    code: number;
    message: string;
}

interface SQLResultSet {
    insertId: number;
    rowsAffected: number;
    rows: SQLResultSetRowList;
}

interface SQLTransaction {
    executeSql(sql: string): SQLResultSet;
}

/* Defined in lib.d.ts

interface LocalStorage {
    key;
    getItem;
    setItem;
    removeItem;
    clear;
}
*/

interface StatusBar {
    isVisible: boolean;

    overlaysWebView(doOverlay: boolean): void;
    styleDefault(): void;
    styleLightContent(): void;
    styleBlackTranslucent(): void;
    styleBlackOpaque(): void;
    backgroundColorByName(colorname: string): void;
    backgroundColorByHexString(hexString: string): void;
    hide(): void;
    show(): void;
}
declare var StatusBar: StatusBar;

interface Keyboard {
    automaticScrollToTopOnHiding: boolean;
    isVisible: boolean;

    onshow: Function;
    onhide: Function;
    onshowing: Function;
    onhiding: Function;

    disableScrollingInShrinkView(disable: boolean): void;
    hideFormAccessoryBar(hide: boolean): void;
    shrinkView(shrink: boolean): void;
}
declare var Keyboard: Keyboard;

interface /*PhoneGapNavigator extends*/ Navigator {
    accelerometer: Accelerometer;
    camera: Camera;
    capture: Capture;
    compass: Compass;
    connection: Connection;
    contacts: Contacts;
    device: Device;
    globalization: Globalization;
    notification: PhonegapNotification;
    splashscreen: Splashscreen;
}

interface Window {
    requestFileSystem: any;
    openDatabase(database_name: string, database_version: string, database_displayname: string, database_size: number): Database;
}

declare var device: Device;
declare var phoneGapNavigator: Navigator /*PhoneGapNavigator*/;