text:
{-# LANGUAGE DataKinds            #-}
{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE LambdaCase           #-}
{-# LANGUAGE QuasiQuotes          #-}
{-# LANGUAGE RankNTypes           #-}
{-# LANGUAGE TypeFamilies         #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns         #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Cardano.Wallet.API.V1.Swagger where

import           Universum hiding (get, put)

import           Cardano.Wallet.API.Indices (ParamNames)
import           Cardano.Wallet.API.Request.Filter
import           Cardano.Wallet.API.Request.Pagination
import           Cardano.Wallet.API.Request.Sort
import           Cardano.Wallet.API.Response
import           Cardano.Wallet.API.V1.Generic (gconsName)
import           Cardano.Wallet.API.V1.Parameters
import           Cardano.Wallet.API.V1.Swagger.Example
import           Cardano.Wallet.API.V1.Types
import           Cardano.Wallet.TypeLits (KnownSymbols (..))

import           Pos.Chain.Update (SoftwareVersion (svNumber))
import           Pos.Core.NetworkMagic (NetworkMagic (..))
import           Pos.Util.CompileInfo (CompileTimeInfo, ctiGitRevision)
import           Pos.Util.Servant (LoggingApi)

import           Control.Lens (At, Index, IxValue, at, (?~))
import           Data.Aeson (encode)
import           Data.Aeson.Encode.Pretty
import           Data.Map (Map)
import           Data.Swagger hiding (Example)
import           Data.Typeable
import           Formatting (build, sformat)
import           NeatInterpolation
import           Servant (Handler, ServantErr (..), Server, StdMethod (..))
import           Servant.API.Sub
import           Servant.Swagger
import           Servant.Swagger.UI (SwaggerSchemaUI')
import           Servant.Swagger.UI.Core (swaggerSchemaUIServerImpl)
import           Servant.Swagger.UI.ReDoc (redocFiles)

import qualified Data.ByteString.Lazy as BL
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Pos.Core as Core
import qualified Pos.Core.Attributes as Core
import qualified Pos.Crypto.Hashing as Crypto

--
-- Helper functions
--

-- | Surround a Text with another
surroundedBy :: Text -> Text -> Text
surroundedBy wrap context = wrap <> context <> wrap

-- | Display a multi-line code-block inline (e.g. in tables)
inlineCodeBlock :: Text -> Text
inlineCodeBlock txt = "
" <> replaceNewLines (replaceWhiteSpaces txt) <> "
"
  where
    replaceNewLines    = T.replace "\n" "
"
    replaceWhiteSpaces = T.replace " " " "

-- | Drill in the 'Swagger' file in an unsafe way to modify a specific operation
-- identified by a tuple (verb, path). The function looks a bit scary to use
-- but is actually rather simple (see example below).
--
-- Note that if the identified path doesn't exist, the function will throw
-- at runtime when trying to read the underlying swagger structure!
--
-- Example:
--
--     swagger
--       & paths %~ (POST, "/api/v1/wallets") `alterOperation` (description ?~ "foo")
--       & paths %~ (GET, "/api/v1/wallets/{walletId}") `alterOperation` (description ?~ "bar")
--
alterOperation ::
    ( IxValue m ~ item
    , Index m ~ FilePath
    , At m
    , HasGet item (Maybe Operation)
    , HasPut item (Maybe Operation)
    , HasPatch item (Maybe Operation)
    , HasPost item (Maybe Operation)
    , HasDelete item (Maybe Operation)
    )
    => (StdMethod, FilePath)
    -> (Operation -> Operation)
    -> m
    -> m
alterOperation (verb, path) alter =
    at path %~ (Just . unsafeAlterItem)
  where
    errUnreachableEndpoint :: Text
    errUnreachableEndpoint =
        "Unreachable endpoint: " <> show verb <> " " <> show path

    errUnsupportedVerb :: Text
    errUnsupportedVerb =
        "Used unsupported verb to identify an endpoint: " <> show verb

    unsafeAlterItem ::
        ( HasGet item (Maybe Operation)
        , HasPut item (Maybe Operation)
        , HasPatch item (Maybe Operation)
        , HasPost item (Maybe Operation)
        , HasDelete item (Maybe Operation)
        )
        => Maybe item
        -> item
    unsafeAlterItem = maybe
        (error errUnreachableEndpoint)
        (unsafeLensFor verb %~ (Just . unsafeAlterOperation))

    unsafeAlterOperation :: Maybe Operation -> Operation
    unsafeAlterOperation = maybe
        (error errUnreachableEndpoint)
        alter

    unsafeLensFor ::
        ( Functor f
        , HasGet item (Maybe Operation)
        , HasPut item (Maybe Operation)
        , HasPatch item (Maybe Operation)
        , HasPost item (Maybe Operation)
        , HasDelete item (Maybe Operation)
        )
        => StdMethod
        -> (Maybe Operation -> f (Maybe Operation))
        -> item
        -> f item
    unsafeLensFor = \case
        GET    -> get
        PUT    -> put
        PATCH  -> patch
        POST   -> post
        DELETE -> delete
        _      -> error errUnsupportedVerb

-- | A combinator to modify the description of an operation, using
-- 'alterOperation' under the hood.
--
--
-- Example:
--
--     swagger
--       & paths %~ (POST, "/api/v1/wallets") `setDescription` "foo"
--       & paths %~ (GET, "/api/v1/wallets/{walletId}") `setDescription` "bar"
setDescription
    :: (IxValue m ~ PathItem, Index m ~ FilePath, At m)
    => (StdMethod, FilePath)
    -> Text
    -> m
    -> m
setDescription endpoint str =
    endpoint `alterOperation` (description ?~ str)

--
-- Instances
--

instance HasSwagger a => HasSwagger (LoggingApi config a) where
    toSwagger _ = toSwagger (Proxy @a)

instance
    ( Typeable res
    , KnownSymbols syms
    , HasSwagger subApi
    , syms ~ ParamNames res params
    ) => HasSwagger (FilterBy params res :> subApi) where
    toSwagger _ =
        let swgr       = toSwagger (Proxy @subApi)
            allOps     = map toText $ symbolVals (Proxy @syms)
        in swgr & over (operationsOf swgr . parameters) (addFilterOperations allOps)
          where
            addFilterOperations :: [Text] -> [Referenced Param] -> [Referenced Param]
            addFilterOperations ops xs = map (Inline . newParam) ops <> xs

            newParam :: Text -> Param
            newParam opName =
                let typeOfRes = fromString $ show $ typeRep (Proxy @ res)
                in Param {
                  _paramName = opName
                , _paramRequired = Nothing
                , _paramDescription = Just $ filterDescription typeOfRes
                , _paramSchema = ParamOther ParamOtherSchema {
                         _paramOtherSchemaIn = ParamQuery
                       , _paramOtherSchemaAllowEmptyValue = Nothing
                       , _paramOtherSchemaParamSchema = mempty
                       }
                }

filterDescription :: Text -> Text
filterDescription typeOfRes = mconcat
    [ "A **FILTER** operation on a " <> typeOfRes <> ". "
    , "Filters support a variety of queries on the resource. "
    , "These are: \n\n"
    , "- `EQ[value]`    : only allow values equal to `value`\n"
    , "- `LT[value]`    : allow resource with attribute less than the `value`\n"
    , "- `GT[value]`    : allow objects with an attribute greater than the `value`\n"
    , "- `GTE[value]`   : allow objects with an attribute at least the `value`\n"
    , "- `LTE[value]`   : allow objects with an attribute at most the `value`\n"
    , "- `RANGE[lo,hi]` : allow objects with the attribute in the range between `lo` and `hi`\n"
    , "- `IN[a,b,c,d]`  : allow objects with the attribute belonging to one provided.\n\n"
    ]

instance
    ( Typeable res
    , KnownSymbols syms
    , syms ~ ParamNames res params
    , HasSwagger subApi
    ) => HasSwagger (SortBy params res :> subApi) where
    toSwagger _ =
        let swgr       = toSwagger (Proxy @subApi)
        in swgr & over (operationsOf swgr . parameters) addSortOperation
          where
            addSortOperation :: [Referenced Param] -> [Referenced Param]
            addSortOperation xs = Inline newParam : xs

            newParam :: Param
            newParam =
                let typeOfRes = fromString $ show $ typeRep (Proxy @ res)
                    allowedKeys = T.intercalate "," (map toText $ symbolVals (Proxy @syms))
                in Param {
                  _paramName = "sort_by"
                , _paramRequired = Just False
                , _paramDescription = Just (sortDescription typeOfRes allowedKeys)
                , _paramSchema = ParamOther ParamOtherSchema {
                         _paramOtherSchemaIn = ParamQuery
                       , _paramOtherSchemaAllowEmptyValue = Just True
                       , _paramOtherSchemaParamSchema = mempty
                       }
                }

instance (HasSwagger subApi) => HasSwagger (WalletRequestParams :> subApi) where
    toSwagger _ =
        let swgr       = toSwagger (Proxy @(WithWalletRequestParams subApi))
        in swgr & over (operationsOf swgr . parameters) (map toDescription)
          where
            toDescription :: Referenced Param -> Referenced Param
            toDescription (Inline p@(_paramName -> pName)) =
                case M.lookup pName requestParameterToDescription of
                    Nothing -> Inline p
                    Just d  -> Inline (p & description .~ Just d)
            toDescription x = x

instance ToParamSchema WalletId

instance ToSchema Core.Address where
    declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions

instance ToParamSchema Core.Address where
  toParamSchema _ = mempty
    & type_ ?~ SwaggerString

instance ToParamSchema (V1 Core.Address) where
  toParamSchema _ = toParamSchema (Proxy @Core.Address)

--
-- Descriptions
--

customQueryFlagToDescription :: Map T.Text T.Text
customQueryFlagToDescription = M.fromList [
    ("force_ntp_check", forceNtpCheckDescription)
  ]

requestParameterToDescription :: Map T.Text T.Text
requestParameterToDescription = M.fromList [
    ("page", pageDescription)
  , ("per_page", perPageDescription (fromString $ show maxPerPageEntries) (fromString $ show defaultPerPageEntries))
  ]

forceNtpCheckDescription :: T.Text
forceNtpCheckDescription = [text|
In some cases, API Clients need to force a new NTP check as a previous result gets cached. A typical use-case is after asking a user to fix its system clock. If this flag is set, request will block until NTP server responds or it will timeout if NTP server is not available within a short delay.
|]

pageDescription :: T.Text
pageDescription = [text|
The page number to fetch for this request. The minimum is **1**.  If nothing is specified, **this value defaults to 1** and always shows the first entries in the requested collection.
|]

perPageDescription :: T.Text -> T.Text -> T.Text
perPageDescription maxValue defaultValue = [text|
The number of entries to display for each page. The minimum is **1**, whereas the maximum is **$maxValue**. If nothing is specified, **this value defaults to $defaultValue**.
|]

sortDescription :: Text -> Text -> Text
sortDescription resource allowedKeys = [text|
A **SORT** operation on this $resource. Allowed keys: `$allowedKeys`.
|]

errorsDescription :: Text
errorsDescription = [text|
Error Name / Description | HTTP Error code | Example
-------------------------|-----------------|---------
$errors
|] where
  errors = T.intercalate "\n" rows
  rows =
    -- 'WalletError'
    [ mkRow fmtErr $ NotEnoughMoney (ErrAvailableBalanceIsInsufficient 1400)
    , mkRow fmtErr $ OutputIsRedeem sampleAddress
    , mkRow fmtErr $ UnknownError "Unexpected internal error."
    , mkRow fmtErr $ InvalidAddressFormat "Provided address format is not valid."
    , mkRow fmtErr WalletNotFound
    , mkRow fmtErr $ WalletAlreadyExists exampleWalletId
    , mkRow fmtErr AddressNotFound
    , mkRow fmtErr $ InvalidPublicKey "Extended public key (for external wallet) is invalid."
    , mkRow fmtErr UnsignedTxCreationError
    , mkRow fmtErr $ SignedTxSubmitError "Unable to submit externally-signed transaction."
    , mkRow fmtErr TooBigTransaction
    , mkRow fmtErr TxFailedToStabilize
    , mkRow fmtErr TxRedemptionDepleted
    , mkRow fmtErr $ TxSafeSignerNotFound sampleAddress
    , mkRow fmtErr $ MissingRequiredParams (("wallet_id", "walletId") :| [])
    , mkRow fmtErr $ WalletIsNotReadyToProcessPayments genExample
    , mkRow fmtErr $ NodeIsStillSyncing genExample
    , mkRow fmtErr $ CannotCreateAddress "Cannot create derivation path for new address in external wallet."
    , mkRow fmtErr $ RequestThrottled 42

    -- 'JSONValidationError'
    , mkRow fmtErr $ JSONValidationFailed "Expected String, found Null."

    -- 'UnsupportedMimeTypeError'
    , mkRow fmtErr $ UnsupportedMimeTypePresent "Expected Content-Type's main MIME-type to be 'application/json'."
    , mkRow fmtErr $ UtxoNotEnoughFragmented (ErrUtxoNotEnoughFragmented 1 msgUtxoNotEnoughFragmented)
    -- TODO 'MnemonicError' ?
    ]
  mkRow fmt err = T.intercalate "|" (fmt err)
  fmtErr err =
    [ surroundedBy "`" (gconsName err) <> "
" <> toText (sformat build err)
    , show $ errHTTPCode $ toServantError err
    , inlineCodeBlock (T.decodeUtf8 $ BL.toStrict $ encodePretty err)
    ]

  sampleAddress = V1 Core.Address
      { Core.addrRoot =
          Crypto.unsafeAbstractHash ("asdfasdf" :: String)
      , Core.addrAttributes =
          Core.mkAttributes $ Core.AddrAttributes Nothing Core.BootstrapEraDistr NetworkMainOrStage
      , Core.addrType =
          Core.ATPubKey
      }

-- | Shorter version of the doc below, only for Dev & V0 documentations
highLevelShortDescription :: DescriptionEnvironment -> T.Text
highLevelShortDescription DescriptionEnvironment{..} = [text|
This is the specification for the Cardano Wallet API, automatically generated as a [Swagger](https://swagger.io/) spec from the [Servant](http://haskell-servant.readthedocs.io/en/stable/) API of [Cardano](https://github.com/input-output-hk/cardano-sl).

Protocol Version   | Git Revision
-------------------|-------------------
$deSoftwareVersion | $deGitRevision
|]

-- | Provide additional insights on V1 documentation
highLevelDescription :: DescriptionEnvironment -> T.Text
highLevelDescription DescriptionEnvironment{..} = [text|
This is the specification for the Cardano Wallet API, automatically generated as a [Swagger](https://swagger.io/) spec from the [Servant](http://haskell-servant.readthedocs.io/en/stable/) API of [Cardano](https://github.com/input-output-hk/cardano-sl).

Protocol Version   | Git Revision
-------------------|-------------------
$deSoftwareVersion | $deGitRevision

Getting Started
===============

In the following examples, we will use *curl* to illustrate request to an API running on the default port **8090**.

Please note that wallet web API uses TLS for secure communication. Requests to the API need to
send a client CA certificate that was used when launching the node and identifies the client as
being permitted to invoke the server API.

Creating a New Wallet
---------------------

You can create your first wallet using the [`POST /api/v1/wallets`](#tag/Wallets%2Fpaths%2F~1api~1v1~1wallets%2Fpost) endpoint as follow:

```
curl -X POST https://localhost:8090/api/v1/wallets \
  -H "Accept: application/json; charset=utf-8" \
  -H "Content-Type: application/json; charset=utf-8" \
  --cert ./scripts/tls-files/client.pem \
  --cacert ./scripts/tls-files/ca.crt \
  -d '{
  "operation": "create",
  "backupPhrase": $deMnemonicExample,
  "assuranceLevel": "normal",
  "name": "MyFirstWallet",
  "spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```

> **Warning**: Those 12 mnemonic words given for the backup phrase act as an example. **Do
> not** use them on a production system. See the section below about mnemonic codes for more
> information.

The `spendingPassword` is optional but highly recommended. It a string of 32
characters, encoded in base 16, yielding to an hexadecimal sequence of 64 bytes.
This passphrase is required for sensitive operations on the wallet and adds
an extra security layer to it.

To generate a valid `spendingPassword`, please follow the following steps:

- Pick a long sentence using a wide variety of characters (uppercase, lowercase,
  whitespace, punctuation, etc). Using a computer to randomly generate
  a passphrase is best, as humans aren't a good source of randomness.

- Compute an appropriate hash of this passphrase. You'll need to use an
  algorithm that yields a 32-byte long string (e.g. *SHA256* or *BLAKE2b*).

- Hex-encode the 32-byte hash into a 64-byte sequence of bytes.

As a response, the API provides you with a unique wallet `id` to be used in subsequent
requests. Make sure to store it / write it down. Note that every API response is
[jsend-compliant](https://labs.omniti.com/labs/jsend); Cardano also augments responses with
meta-data specific to pagination. More details in the section below about [Pagination](#section/Pagination)

```json
$createWallet
```

You have just created your first wallet. Information about this wallet can be retrieved using the [`GET /api/v1/wallets/{walletId}`](#tag/Wallets%2Fpaths%2F~1api~1v1~1wallets~1{walletId}%2Fget)
endpoint as follows:

```
curl -X GET https://localhost:8090/api/v1/wallets/{{walletId}} \
     -H "Accept: application/json; charset=utf-8" \
     --cacert ./scripts/tls-files/ca.crt \
     --cert ./scripts/tls-files/client.pem
```

Receiving ADA
-------------

To receive _ADA_ from other users you should provide your address. This address can be obtained
from an account. Each wallet contains at least one account. An account is like a pocket inside
of your wallet. Vew all existing accounts of a wallet by using the [`GET /api/v1/wallets/{{walletId}}/accounts`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts%2Fget)
endpoint:

```
curl -X GET https://localhost:8090/api/v1/wallets/{{walletId}}/accounts?page=1&per_page=10 \
  -H "Accept: application/json; charset=utf-8" \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

Since you have, for now, only a single wallet, you'll see something like this:

```json
$readAccounts
```

All the wallet's accounts are listed under the `addresses` field. You can communicate one of
these addresses to receive _ADA_ on the associated account.

Sending ADA
-----------

In order to send _ADA_ from one of your accounts to another address, you must create a new
payment transaction using the [`POST /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fpost)
endpoint as follows:

```
curl -X POST https://localhost:8090/api/v1/transactions \
  -H "Accept: application/json; charset=utf-8" \
  -H "Content-Type: application/json; charset=utf-8" \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem \
  -d '{
  "destinations": [{
    "amount": 14,
    "address": "A7k5bz1QR2...Tx561NNmfF"
  }],
  "source": {
    "accountIndex": 0,
    "walletId": "Ae2tdPwUPE...8V3AVTnqGZ"
  },
  "spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```

Note that, in order to perform a transaction, you need to have enough existing _ADA_ on the
source account! The Cardano API is designed to accomodate multiple recipients payments
out-of-the-box; notice how `destinations` is a list of addresses (and corresponding amounts).

When the transaction succeeds, funds are no longer available in the sources addresses, and are
soon made available to the destinations within a short delay. Note that, you can at any time see
the status of your wallets by using the [`GET /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fget)
endpoint as follows:

```
curl -X GET https://localhost:8090/api/v1/transactions?wallet_id=Ae2tdPwUPE...8V3AVTnqGZ\
     -H "Accept: application/json; charset=utf-8" \
     --cacert ./scripts/tls-files/ca.crt \
     --cert ./scripts/tls-files/client.pem
```

Here we constrained the request to a specific account. After our previous transaction the output
should look roughly similar to this:

```json
$readTransactions
```

In addition, and because it is not possible to _preview_ a transaction, one can lookup a
transaction's fees using the [`POST /api/v1/transactions/fees`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions~1fees%2Fpost)
endpoint to get an estimation of those fees.
See [Estimating Transaction Fees](#section/Common-Use-Cases/Estimating-Transaction-Fees) for more details.

Pagination
==========

**All GET requests of the API are paginated by default**. Whilst this can be a source of
surprise, is the best way of ensuring the performance of GET requests is not affected by the
size of the data storage.

Version `V1` introduced a different way of requesting information to the API. In particular,
GET requests which returns a _collection_ (i.e. typically a JSON array of resources) lists
extra parameters which can be used to modify the shape of the response. In particular, those
are:

* `page`: (Default value: **1**).
* `per_page`: (Default value: **$deDefaultPerPage**)

For a more accurate description, see the section `Parameters` of each GET request, but as a
brief overview the first two control how many results and which results to access in a
paginated request.

Filtering and Sorting
=====================

`GET` endpoints which list collection of resources supports filters & sort operations, which
are clearly marked in the swagger docs with the `FILTER` or `SORT` labels. The query format is
quite simple, and it goes this way:

Filter Operators
----------------

| Operator | Description                                                               | Example                |
|----------|---------------------------------------------------------------------------|------------------------|
| -        | If **no operator** is passed, this is equivalent to `EQ` (see below).     | `balance=10`           |
| `EQ`     | Retrieves the resources with index _equal_ to the one provided.           | `balance=EQ[10]`       |
| `LT`     | Retrieves the resources with index _less than_ the one provided.          | `balance=LT[10]`       |
| `LTE`    | Retrieves the resources with index _less than equal_ the one provided.    | `balance=LTE[10]`      |
| `GT`     | Retrieves the resources with index _greater than_ the one provided.       | `balance=GT[10]`       |
| `GTE`    | Retrieves the resources with index _greater than equal_ the one provided. | `balance=GTE[10]`      |
| `RANGE`  | Retrieves the resources with index _within the inclusive range_ [k,k].    | `balance=RANGE[10,20]` |

Sort Operators
--------------

| Operator | Description                                                               | Example                |
|----------|---------------------------------------------------------------------------|------------------------|
| `ASC`    | Sorts the resources with the given index in _ascending_ order.            | `sort_by=ASC[balance]` |
| `DES`    | Sorts the resources with the given index in _descending_ order.           | `sort_by=DES[balance]` |
| -        | If **no operator** is passed, this is equivalent to `DES` (see above).    | `sort_by=balance`      |

Errors
======

In case a request cannot be served by the API, a non-2xx HTTP response will be issued, together
with a [JSend-compliant](https://labs.omniti.com/labs/jsend) JSON Object describing the error
in detail together with a numeric error code which can be used by API consumers to implement
proper error handling in their application. For example, here's a typical error which might be
issued:

``` json
$deErrorExample
```

Existing Wallet Errors
----------------------

$deWalletErrorTable

Monetary Denomination & Units
=============================

Cardano's currency is called _ADA_ ( ₳ ). _ADA_ has up to **6** decimal places; hence the
smallest monetary unit that can be represented in the Cardano's blockhain is: 0.000001₳. This
is also called a _Lovelace_ (Cardano's currency is named after the mathematician and computer
scientist [Ada Lovelace](https://en.wikipedia.org/wiki/Ada_Lovelace)). Put in another way, one
_ADA_ is equal to one million _Lovelace_.

ADA        | Lovelace
-----------|----------
`1`        | `1 000 000`
`.000 001` | `1`

> **Warning**: All amounts manipulated in the API are given and expected in Lovelace.

Mnemonic Codes
==============

The full list of accepted mnemonic codes to secure a wallet is defined by the [BIP-39
specifications](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). Note that
picking up 12 random words from the list **is not enough** and leads to poor security. Make
sure to carefully follow the steps described in the protocol when you generate words for a new
wallet.

Versioning & Legacy
===================

The API is **versioned**, meaning that is possible to access different versions of the API by adding the _version number_ in the URL.

**For the sake of backward compatibility, we expose the legacy version of the API, available simply as unversioned endpoints.**

This means that _omitting_ the version number would call the old version of the API. Deprecated
endpoints are currently grouped under an appropriate section; they would be removed in upcoming
released, if you're starting a new integration with Cardano-SL, please ignore these.

Note that Compatibility between major versions is not _guaranteed_, i.e. the request & response formats might differ.

Disable TLS (Not Recommended)
-----------------------------

If needed, you can disable TLS by providing the `--no-tls` flag to the wallet or by running a wallet in debug mode with `--wallet-debug` turned on.

Common Use-Cases
================

Sending Money to Multiple Recipients
------------------------------------

As seen in [Sending ADA](#section/Getting-Started/Sending-ADA), you can send _ADA_ to
another party using the [`POST /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fpost) endpoint.
Important to notice is the type of the field `destinations`: it's a list, enabling you to provide more
than one destination. Each destination is composed of:

- An address
- A corresponding amount

The overall transaction corresponds to the sum of each outputs. For instance, to send money to
two parties simultaneously:

```
curl -X POST https://localhost:8090/api/v1/transactions \
  -H "Accept: application/json; charset=utf-8" \
  -H "Content-Type: application/json; charset=utf-8" \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem \
  -d '{
  "destinations": [
    {
      "amount": 14,
      "address": "A7k5bz1QR2...Tx561NNmfF"
    },
    {
      "amount": 42,
      "address": "B56n78WKE8...jXAa34NUFz"
    }
  ],
  "source": {
    "accountIndex": 0,
    "walletId": "Ae2tdPwUPE...8V3AVTnqGZ"
  },
  "spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```

About UTXO Fragmentation
------------------------

As described in [Sending Money to Multiple Recipients](#section/Common-Use-Cases/Sending-Money-to-Multiple-Recipients), it is possible to send ada to more than one destination. Cardano only allows a given UTXO to cover at most one single transaction output. As a result,
when the number of transaction outputs is greater than the number the API returns a `UtxoNotEnoughFragmented` error which
looks like the following
```
{
    "status": "error",
    "diagnostic": {
        "details": {
            "help": "Utxo is not enough fragmented to handle the number of outputs of this transaction. Query /api/v1/wallets/{walletId}/statistics/utxos endpoint for more information",
            "missingUtxos": 1
        }
    },
    "message": "UtxoNotEnoughFragmented"
}
```

To make sure the source account has a sufficient level of UTXO fragmentation (i.e. number of UTXOs),
please monitor the state of the UTXOs as described in [Getting UTXO Statistics](#section/Common-Use-Cases/Getting-Utxo-Statistics). The
number of wallet UTXOs should be no less than the transaction outputs, and the sum of all UTXOs should be enough to cover the total
transaction amount, including fees.

Contrary to a classic accounting model, there's no such thing as spending _part of a UTXO_, and one has to wait for a transaction to be included in a
block before spending the remaining change. This is very similar to using bank notes: one can't spend a USD 20 bill at two different shops at the same time,
even if it is enough to cover both purchases — one has to wait for change from the first transaction before making the second one.
There's no "ideal" level of fragmentation; it depends on one's needs. However, the more UTXOs that are available, the higher the concurrency capacity
of one's wallet, allowing multiple transactions to be made at the same time.

Similarly, there's no practical maximum number of UTXOs, but there is nevertheless a maximum transaction size. By having many small UTXOs,
one is taking the risk of hitting that restriction, should too many inputs be selected to fill a transaction. The only way to
work around this is to make multiple smaller transactions.

Estimating Transaction Fees
---------------------------

When you submit a transaction to the network, some fees apply depending on, but not only, the
selected grouping policy and the available inputs on the source wallet. There's actually a
trade-off between fees, cryptographic security, throughput and privacy. The more inputs are
selected, the bigger is the payload, the bigger are the fees.

The API lets you estimate fees for a given transaction via the [`POST /api/v1/transaction/fees`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions~1fees%2Fpost)
endpoint. The request payload is identical to the one you would make to create a transaction:

```
curl -X POST https://localhost:8090/api/v1/transactions/fees \
  -H "Accept: application/json; charset=utf-8" \
  -H "Content-Type: application/json; charset=utf-8" \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem \
  -d '{
  "destinations": [{
      "amount": 14,
      "address": "A7k5bz1QR2...Tx561NNmfF"
  }],
  "source": {
    "accountIndex": 0,
    "walletId": "Ae2tdPwUPE...8V3AVTnqGZ"
  }
}'
```

The API resolves with an estimated amount in _ADA_. This estimation highly depends on the
current state of the ledger and diverges with time.

```json
$readFees
```

Managing Accounts
-----------------

A wallet isn't limited to one account. It can actually be useful to have more than one account
in order to separate business activities. With the API, you can retrieve a specific account,
create new ones, list all existing accounts of a wallet or edit a few things on an existing
account. By default, your wallet comes with a provided account. Let's see how to create a fresh
new account on a wallet using [`POST /api/v1/wallets/{{walletId}}/accounts`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts%2Fpost):

```
curl -X POST \
  https://localhost:8090/api/v1/Ae2tdPwUPE...8V3AVTnqGZ/accounts \
  -H 'Content-Type: application/json;charset=utf-8' \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem \
  -d '{
  "name": "MyOtherAccount",
  "spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```

Note that the `spendingPassword` here should match the one provided earlier in [Creating a
New Wallet](#section/Getting-Started/Creating-a-New-Wallet).

```json
$createAccount
```

You can always retrieve this account description later if needed via [`GET /api/v1/wallets/{{walletId}}/accounts/{{accountId}}`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts~1{accountId}%2Fget).

For example:

```
curl -X GET \
  https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/accounts/2902829384 \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

For a broader view, the full list of accounts of a given wallet can be retrieved using [`GET /api/v1/wallets/{{walletId}}/accounts`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts%2Fget)
```
curl -X GET \
  https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/accounts \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

```json
$readAccounts
```

Partial Representations
-----------------------

The previous endpoint gives you a list of full representations. However, in some cases, it might be interesting to retrieve only a partial representation of an account (e.g. only the balance). There are two extra endpoints one could use to either fetch a given account's balance, and another to retrieve the list of addresses associated to a specific account.

[`GET /api/v1/wallets/{{walletId}}/accounts/{{accountId}}/addresses`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1%7BwalletId%7D~1accounts~1%7BaccountId%7D~1addresses%2Fget)

```json
$readAccountAddresses
```

Note that this endpoint is paginated and allow basic filtering and sorting on
addresses. Similarly, you can retrieve only the account balance with:

[`GET /api/v1/wallets/{{walletId}}/accounts/{{accountId}}/amount`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1%7BwalletId%7D~1accounts~1%7BaccountId%7D~1amount%2Fget)

```json
$readAccountBalance
```

Managing Addresses
------------------

By default, wallets you create are provided with an account which has one default address. It
is possible (and recommended) for an account to manage multiple addresses. Address reuse
actually reduces privacy for it tights more transactions to a small set of addresses.

When paying, the wallet makes many of these choices for you. Addresses are
selected from a wallet's account based on several different strategies and
policies.

To create a new address, use the [`POST /api/v1/addresses`](#tag/Addresses%2Fpaths%2F~1api~1v1~1addresses%2Fpost)
endpoint:

```
curl -X POST \
  https://localhost:8090/api/v1/addresses \
  -H 'Content-Type: application/json;charset=utf-8' \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem \
  -d '{
        "walletId": "Ae2tdPwUPE...V3AVTnqGZ4",
        "accountIndex": 2147483648
}'
```

```json
$createAddress
```

If your wallet is protected with a password, this password is also required in order to create
new addresses for that wallet. In such case, the field `spendingPassword` should match the one
defined earlier to protect your wallet.

Addresses generated as just described are always valid. When the API encounters
an invalid address however (e.g. when provided by another party), it will fail with a
client error.

You can always view all your available addresses across all your wallets by using
[`GET /api/v1/addresses`](#tag/Addresses%2Fpaths%2F~1api~1v1~1addresses%2Fget):

```
curl -X GET https://localhost:8090/api/v1/addresses \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

```json
$readAddresses
```

Checking Synchronization Progress
---------------------------------

You can control the synchronization progress of the underlying node hosting the wallet's server
via [`GET /api/v1/node-info`](#tag/Info%2Fpaths%2F~1api~1v1~1node-info%2Fget). The output is
rather verbose and gives real-time progress updates about the current node.

```
curl -X GET https://localhost:8090/api/v1/node-info \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

```json
$readNodeInfo
```

Retrieving Transaction History
------------------------------

If needed, applications may regularly poll the wallet's backend to retrieve the history of
transactions of a given wallet. Using the [`GET /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fget)
endpoint, you can view the status of all transactions that ever sent or took money from the
wallet.

The following table sums up the available filters (also detailed in the endpoint documentation details):

Filter On                   | Corresponding Query Parameter(s)
----------------------------| ------------------------------
Wallet                      | `wallet_id`
Wallet's account            | `account_index` + `wallet_id`
Address                     | `address`
Transaction's creation time | `created_at`
Transaction's id            | `id`

For example, in order to retrieve the last 50 transactions of a particular account,
ordered by descending date:

```
curl -X GET https://127.0.0.1:8090/api/v1/transactions?wallet_id=Ae2tdPwU...3AVTnqGZ&account_index=2902829384&sort_by=DES\[created_at\]&per_page=50' \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```
For example, in order to retrieve the last 50 transactions, ordered by descending date:

```
curl -X GET 'https://127.0.0.1:8090/api/v1/transactions?wallet_id=Ae2tdPwU...3AVTnqGZ &sort_by=DES\[created_at\]&per_page=50' \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

Another example, if you were to look for all transactions made since the 1st of January 2018:

```
curl -X GET 'https://127.0.0.1:8090/api/v1/transactions?wallet_id=Ae2tdPwU...3AVTnqGZ&created_at=GT\[2018-01-01T00:00:00.00000\]' \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

Getting Utxo statistics
---------------------------------

You can get Utxo statistics of a given wallet using
 [`GET /api/v1/wallets/{{walletId}}/statistics/utxos`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1statistics~1utxos%2Fget)

```
curl -X GET \
  https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/statistics/utxos \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem
```

```json
$readUtxoStatistics
```
Make sure to carefully read the section about [Pagination](#section/Pagination) to fully
leverage the API capabilities.

Importing (Unused) Addresses From a Previous Node (or Version)
--------------------------------------------------------------

When restoring a wallet, only the information available on the blockchain can
be retrieved. Some pieces of information aren't stored on
the blockchain and are only defined as _Metadata_ of the wallet backend. This
includes:

- The wallet's name
- The wallet's assurance level
- The wallet's spending password
- The wallet's unused addresses

Unused addresses are not recorded on the blockchain and, in the case of random
derivation, it is unlikely that the same addresses will be generated on two
different node instances. However, some API users may wish to preserve unused
addresses between different instances of the wallet backend.

To enable this, the wallet backend provides an endpoint ([`POST /api/v1/wallets/{{walletId}}/addresses`](#tag/Addresses%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1addresses%2Fpost))
to import a list of addresses into a given account. Note that this endpoint is
quite lenient when it comes to errors: it tries to import all provided addresses
one by one, and ignores any that can't be imported for whatever reason. The
server will respond with the total number of successes and, if any, a list of
addresses that failed to be imported. Trying to import an address that is already
present will behave as a no-op.

For example:

```
curl -X POST \
  https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/addresses \
  -H 'Accept: application/json;charset=utf-8' \
  --cacert ./scripts/tls-files/ca.crt \
  --cert ./scripts/tls-files/client.pem \
  -d '[
    "Ae2tdPwUPE...8V3AVTnqGZ",
    "Ae2odDwvbA...b6V104CTV8"
  ]'
```

> **IMPORTANT**: This feature is experimental and performance is
> not guaranteed. Users are advised to import small batches only.

|]
  where
    createAccount        = decodeUtf8 $ encodePretty $ genExample @(APIResponse Account)
    createAddress        = decodeUtf8 $ encodePretty $ genExample @(APIResponse WalletAddress)
    createWallet         = decodeUtf8 $ encodePretty $ genExample @(APIResponse Wallet)
    readAccounts         = decodeUtf8 $ encodePretty $ genExample @(APIResponse [Account])
    readAccountBalance   = decodeUtf8 $ encodePretty $ genExample @(APIResponse AccountBalance)
    readAccountAddresses = decodeUtf8 $ encodePretty $ genExample @(APIResponse AccountAddresses)
    readAddresses        = decodeUtf8 $ encodePretty $ genExample @(APIResponse [Address])
    readFees             = decodeUtf8 $ encodePretty $ genExample @(APIResponse EstimatedFees)
    readNodeInfo         = decodeUtf8 $ encodePretty $ genExample @(APIResponse NodeInfo)
    readTransactions     = decodeUtf8 $ encodePretty $ genExample @(APIResponse [Transaction])
    readUtxoStatistics   = decodeUtf8 $ encodePretty $ genExample @(APIResponse UtxoStatistics)

-- | Provide an alternative UI (ReDoc) for rendering Swagger documentation.
swaggerSchemaUIServer
    :: (Server api ~ Handler Swagger)
    => Swagger -> Server (SwaggerSchemaUI' dir api)
swaggerSchemaUIServer =
    swaggerSchemaUIServerImpl redocIndexTemplate redocFiles
  where
    redocIndexTemplate :: Text
    redocIndexTemplate = [text|
<!doctype html>

    <title>ReDoc</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <redoc spec-url="../SERVANT_SWAGGER_UI_SCHEMA"></redoc>

|]

applyUpdateDescription :: Text
applyUpdateDescription = [text|
Apply the next available update proposal from the blockchain. Note that this
will immediately shutdown the node and makes it unavailable for a short while.
|]

postponeUpdateDescription :: Text
postponeUpdateDescription = [text|
Discard the next available update from the node's local state. Yet, this doesn't
reject the update which will still be applied as soon as the node is restarted.
|]

resetWalletStateDescription :: Text
resetWalletStateDescription = [text|
Wipe-out the node's local state entirely. The only intended use-case for this
endpoint is during API integration testing. Note also that this will fail by
default unless the node is running in debug mode.
|]

estimateFeesDescription :: Text
estimateFeesDescription = [text|
Estimate the fees which would incur from the input payment. This endpoint
**does not** require a _spending password_ to be supplied as it generates
under the hood an unsigned transaction.
|]

getAddressDescription :: Text
getAddressDescription = [text|
The previous version of this endpoint failed with an HTTP error when the given
address was unknown to the wallet.

This was misleading since an address that is unknown to the wallet may still
belong to the wallet (since it could be part of a pending transaction in
another instance of the same wallet).

To reflect this, the V1 endpoint does not fail when an address is not recognised
and returns a new field which indicates the address' ownership status, from the
node point of view.
|]

--
-- The API
--

data DescriptionEnvironment = DescriptionEnvironment
  { deErrorExample     :: !T.Text
  , deDefaultPerPage   :: !T.Text
  , deWalletErrorTable :: !T.Text
  , deGitRevision      :: !T.Text
  , deSoftwareVersion  :: !T.Text
  , deMnemonicExample  :: !T.Text
  }

api :: HasSwagger a
    => (CompileTimeInfo, SoftwareVersion)
    -> Proxy a
    -> (DescriptionEnvironment -> T.Text)
    -> Swagger
api (compileInfo, curSoftwareVersion) walletAPI mkDescription = toSwagger walletAPI
  & info.title   .~ "Cardano Wallet API"
  & info.version .~ fromString (show curSoftwareVersion)
  & host ?~ "127.0.0.1:8090"
  & info.description ?~ mkDescription DescriptionEnvironment
    { deErrorExample          = decodeUtf8 $ encodePretty WalletNotFound
    , deMnemonicExample       = decodeUtf8 $ encode (genExample @BackupPhrase)
    , deDefaultPerPage        = fromString (show defaultPerPageEntries)
    , deWalletErrorTable      = errorsDescription
    , deGitRevision           = ctiGitRevision compileInfo
    , deSoftwareVersion       = fromString $ show (svNumber curSoftwareVersion)
    }
  & info.license ?~ ("MIT" & url ?~ URL "https://raw.githubusercontent.com/input-output-hk/cardano-sl/develop/lib/LICENSE")
  & paths %~ (POST,   "/api/internal/apply-update")       `setDescription` applyUpdateDescription
  & paths %~ (POST,   "/api/internal/postpone-update")    `setDescription` postponeUpdateDescription
  & paths %~ (DELETE, "/api/internal/reset-wallet-state") `setDescription` resetWalletStateDescription
  & paths %~ (POST,   "/api/v1/transactions/fees")        `setDescription` estimateFeesDescription
  & paths %~ (GET,    "/api/v1/addresses/{address}")      `setDescription` getAddressDescription


text:
/*
 * This software is licensed under the Apache License, Version 2.0
 * (the "License") agreement; you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.force66.aws.utils;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.amazonaws.services.lambda.runtime.Context;

/**
 * Generic utilities for handling AWS Context
 * @author Derek C. Ashmore
 *
 */
public class ContextUtils {

	public static String toString(Context context) {
		if (context == null)  {
			return null;
		}

		return ToStringBuilder.reflectionToString(context);
	}

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * 属性文件读取工具类
 * @author yuhaisheng
 */
package org.custom.utils;

import java.io.InputStream;
import java.util.Properties;

public final class PropertyUtils {

    private PropertyUtils() {
    }

    public static String getPropertyValue(String _propertiesName, String key) {
        String value = "";
        Properties properties = new Properties();
        InputStream inputStream = PropertyUtils.class
                .getResourceAsStream(_propertiesName);
//         通过类加载器读取
//        properties.load(new FileReader(_propertiesName));
//        通过类加载器的路径来读取配置文件
//        properties.load(PropertyUtils.class
//                .getResourceAsStream(_propertiesName));
        try {
            properties.load(inputStream);
//            // 读取属性
//            properties.getProperty(key);
//            properties.getProperty(key, defaultValue);
//            // 修改属性
//            properties.setProperty(key, value);
            if (properties.getProperty(key) != null
                    && !"".equals(properties.getProperty(key))) {
                value = properties.getProperty(key).trim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                properties.clear();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return value;
    }

}


text:
<?php
$attributes = ['id' => 'emma_edit_user_status_form'];
echo form_open($action_url, $attributes);

    $this->table->add_row([
            lang('Status', 'emma_user_status'),
            form_dropdown('emma_user_status', ['a' => lang('Active'), 'e' => lang('Error'), 'o' => lang('Opt-Out')], $user_status),
        ]);

    echo $this->table->generate();

?>

    <?=form_submit(['name' => 'submit', 'value' => lang('submit'), 'class' => 'submit'])?>

<?=form_close();


text:
package org.uberfire.client.menu;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import com.github.gwtbootstrap.client.ui.Dropdown;
import com.github.gwtbootstrap.client.ui.NavLink;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.client.mvp.SplashScreenActivity;
import org.uberfire.client.workbench.events.NewSplashScreenActiveEvent;

@ApplicationScoped
public class MenuSplashList extends Composite {

    @Inject
    private PlaceManager placeManager;

    final Dropdown content = new Dropdown() {{
        trigger.setCaret( false );
        setRightDropdown( true );
        setIcon( IconType.QUESTION_SIGN );
    }};

    public MenuSplashList() {
        initWidget( content );
    }

    void onNewSplash( @Observes NewSplashScreenActiveEvent event ) {
        content.clear();
        for ( final SplashScreenActivity active : placeManager.getActiveSplashScreens() ) {
            content.add( new NavLink( active.getTitle() ) {{
                addClickHandler( new ClickHandler() {
                    @Override
                    public void onClick( ClickEvent event ) {
                        active.forceShow();
                    }
                } );
            }} );
        }
        if ( content.getMenuWiget().getWidgetCount() == 0 ) {
            content.add( new NavLink( "-- none --" ) {{
                setDisabled( true );
            }} );
        }
    }
}


text:
@interface JVFloatLabeledTextField (ZX)

- (void)defaultConfigurationWithPlaceHolder:(NSString *)placeHolder;

@end


text:
module Tronkell.Network.Websockets where

import qualified Network.WebSockets as WS
import qualified Network.Wai.Handler.Warp as Warp
import qualified Network.Wai.Handler.WebSockets as WaiWS
import qualified Network.Wai.Application.Static as Static
import qualified Network.Wai
import qualified Control.Concurrent as Con
import qualified Data.Aeson as A
import Data.ByteString.Lazy.Char8
import Control.Exception (handle, SomeException(..))
import Control.Monad (forever, when)
import Debug.Trace

import qualified Tronkell.Server.Types as ST
import qualified Tronkell.Data.Parse as TP
import qualified Tronkell.Network.Utils as NU (nextUserID)

start :: Con.MVar ST.UserID -> ST.NetworkChans -> Con.Chan ST.OutMessage -> IO ()
start uIdGen chans outChan = Warp.runSettings
  (Warp.setPort 8331 Warp.defaultSettings)
  $ WaiWS.websocketsOr WS.defaultConnectionOptions (websocketHandler uIdGen chans outChan) staticApp

staticApp :: Network.Wai.Application
staticApp = Static.staticApp . Static.defaultWebAppSettings $ "ui/public"

websocketHandler :: Con.MVar ST.UserID -> ST.NetworkChans -> Con.Chan ST.OutMessage -> WS.ServerApp
websocketHandler uIdGen (inChan, clientSpecificOutChan) outChan pendingConnection = do
  conn <- WS.acceptRequest pendingConnection
  WS.forkPingThread conn 30
  -- duplicate the channels to read.
  dupOutChan <- Con.dupChan outChan
  dupClientSpecificOutChan <- Con.dupChan clientSpecificOutChan

  -- get from some mvar passed from server to here.
  userId <- NU.nextUserID uIdGen
  Con.writeChan inChan $ ST.PlayerJoined userId

  writeThread <- Con.forkIO $ forever $ do
    msg <- Con.readChan dupOutChan
    WS.sendDataMessage conn . WS.Text . A.encode $ msg

  clientSpecificWriteThread <- Con.forkIO $ forever $ do
    (uId, msg) <- Con.readChan dupClientSpecificOutChan
    when (uId == userId) $ WS.sendDataMessage conn . WS.Text . A.encode $ msg

  handle (\(SomeException _) -> return ()) $ forever $ do
    json <- toByteString <$> WS.receiveDataMessage conn
    let msg = A.eitherDecode' json
    case msg :: Either String TP.JsonInMessage of
      Left e  -> traceShow e $ return ()
      Right m -> Con.writeChan inChan (m userId)

  Con.writeChan inChan $ ST.UserExit userId
  Con.killThread writeThread
  Con.killThread clientSpecificWriteThread

toByteString :: WS.DataMessage -> ByteString
toByteString d = case d of
  WS.Binary b -> b
  WS.Text   t -> t


text:
#pragma once
#define DEBUG

#ifdef DEBUG
extern int _debug;
#define DPRINTF(level, ...)                             \
	do {                                            \
		if (_debug >= level)                    \
			printf(__VA_ARGS__);            \
	} while(0)
#else
#define DPRINTF(...) do {} while(0)
#endif

struct filename {
	char *path;
	int used;
};

int append(struct filename *fn, const char *fmt, ...);
int append_esc(struct filename *fn, const char *fmt, ...);


text:
require File.dirname(__FILE__) + '/../../../../spec/spec_helper'

include ActionView::Helpers::OpenFlashChartLazyHelper
describe ActionView::Helpers::OpenFlashChartLazyHelper do
  it "should respond to swf_object and return the javascript code with the route" do
    swf_object("my_graph",{:route=>"/my_route"}).should == "swfobject.embedSWF('/open-flash-chart.swf','my_graph','300','150','9.0.0','expressInstall.swf',{'data-file':'/my_route'});"
  end
  it "should respond to swf_object and return the javascript code without the route" do
    swf_object("my_graph").should == "swfobject.embedSWF('/open-flash-chart.swf','my_graph','300','150','9.0.0','expressInstall.swf');"
  end
end


text:
layout: page
title: Maps 3
---

Test test test

#### Links

#### Assignments for Nov. 11

Read:
Read:
Read:

#### Exercise 1

#### Exercise 2


text:
package scott.com.workhard.widget;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService.RemoteViewsFactory;

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

import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;
import scott.com.workhard.R;
import scott.com.workhard.app.App;
import scott.com.workhard.app.ui.init.launch.LaunchActivity;
import scott.com.workhard.data.Injection;
import scott.com.workhard.entities.Workout;

public class WorkoutsRemoteViewsFactory implements RemoteViewsFactory
{
    private static final String TAG = WorkoutsRemoteViewsFactory.class.getSimpleName();
    private List<Workout> items = new ArrayList<>();
    private Context mContext;
    private int mAppWidgetId;
    private CompositeSubscription subscription = new CompositeSubscription();

    public WorkoutsRemoteViewsFactory(Context context, Intent intent) {
        mContext = context;
        mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }

    private void updateData() {
        subscription.add(Injection.provideWorkoutsRepository().findHistoriesWorkouts()
                .subscribe(new Subscriber<List<Workout>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<Workout> workouts) {
                        items.clear();
                        items.addAll(workouts);
                        WorkoutsRemoteViewsFactory.this.getCount();
                    }
                }));
    }

    public void onDestroy() {
        items.clear();
    }

    public int getCount() {
        return items.size();
    }

    public RemoteViews getViewAt(int position) {
        Workout workout = items.get(position);
        RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_collection_item);
        rv.setTextViewText(R.id.tVWidgetWorkoutName, workout.getName());
        String srounds = "Rounds " + String.valueOf(workout.getRounds());
        rv.setTextViewText(R.id.tVWidgetWorkoutRounds, srounds);

        Intent clickIntentTemplate = new Intent(mContext, LaunchActivity.class);
        rv.setOnClickFillInIntent(R.id.lLWidget, clickIntentTemplate);
        return rv;
    }

    public RemoteViews getLoadingView() {
        return null;
    }

    public int getViewTypeCount() {
        return 1;
    }

    public long getItemId(int position) {
        return position;
    }

    public boolean hasStableIds() {
        return true;
    }

    @Override
    public void onCreate() {
        updateData();
    }

    @Override
    public void onDataSetChanged() {

    }

}


text:
package org.ralasafe.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.ralasafe.util.DBUtil;

public class EmployeeManager {
	private static final String INSERT_SQL="INSERT INTO demouser(loginName,name,password," +
			"departmentId,companyId,isManager) values(?,?,?,?,?,?)";
	private static final String UPDATE_SQL="UPDATE demouser SET loginName=?,name=?, " +
			"password=?,departmentId=?,companyId=?,isManager=?" +
			" WHERE id=?";
	private static final String DELETE_SQL="DELETE FROM demouser WHERE id=?";
	private static final String SELECT_SQL="SELECT loginName,name,password," +
			"departmentId,companyId,isManager,id FROM demoUSER where id=?";

	public void addEmployee( Employee emp ) {
		Connection conn=null;
		PreparedStatement pstmt=null;

		try {
			conn=DemoUtil.getConnection();
			pstmt=conn.prepareStatement( INSERT_SQL );
			pstmt.setString( 1, emp.getLoginName() );
			pstmt.setString( 2, emp.getName() );
			pstmt.setString( 3, emp.getPassword() );
			pstmt.setInt( 4, emp.getDepartmentId() );
			pstmt.setInt( 5, emp.getCompanyId() );
			pstmt.setInt( 6, emp.getIsManager() );
			pstmt.execute();
		} catch( SQLException e ) {
			e.printStackTrace();
		} finally {
			DBUtil.close( pstmt, conn );
		}
	}

	public void updateEmployee( Employee emp ) {
		Connection conn=null;
		PreparedStatement pstmt=null;

		try {
			conn=DemoUtil.getConnection();
			pstmt=conn.prepareStatement( UPDATE_SQL );
			pstmt.setString( 1, emp.getLoginName() );
			pstmt.setString( 2, emp.getName() );
			pstmt.setString( 3, emp.getPassword() );
			pstmt.setInt( 4, emp.getDepartmentId() );
			pstmt.setInt( 5, emp.getCompanyId() );
			pstmt.setInt( 6, emp.getIsManager() );
			pstmt.setInt( 7, emp.getId() );
			pstmt.execute();
		} catch( SQLException e ) {
			e.printStackTrace();
		} finally {
			DBUtil.close( pstmt, conn );
		}
	}

	public void deleteEmployee( int deptId ) {
		Connection conn=null;
		PreparedStatement pstmt=null;

		try {
			conn=DemoUtil.getConnection();
			pstmt=conn.prepareStatement( DELETE_SQL );
			pstmt.setInt( 1, deptId );
			pstmt.execute();
		} catch( SQLException e ) {
			e.printStackTrace();
		} finally {
			DBUtil.close( pstmt, conn );
		}
	}

	public Employee getEmployee( int customerId ) {
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		try {
			conn=DemoUtil.getConnection();
			pstmt=conn.prepareStatement( SELECT_SQL );
			pstmt.setInt( 1, customerId );
			rs=pstmt.executeQuery();

			Employee employee=null;
			if( rs.next() ) {
				employee=new Employee();
				employee.setLoginName( rs.getString(1) );
				employee.setName( rs.getString(2) );
				employee.setPassword( rs.getString(3) );
				employee.setDepartmentId( rs.getInt(4) );
				employee.setCompanyId( rs.getInt(5) );
				employee.setIsManager( rs.getInt(6) );
				employee.setId( rs.getInt(7) );
			}

			return employee;
		} catch( SQLException e ) {
			e.printStackTrace();
			return null;
		} finally {
			DBUtil.close(rs);
			DBUtil.close( pstmt, conn );
		}
	}
}


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

	/* return an array of specs to be run */
	return {
		specs: ['spec/collections/spots.js',
		'spec/models/search.js',
		'spec/models/spot.js',
		'spec/views/formView.js',
		'spec/views/mapView.js',
		'spec/views/toolView.js'
		]
	};
});


text:
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NoRebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}

module Duckling.AmountOfMoney.Types where

import Control.DeepSeq
import Data.Aeson
import Data.Hashable
import Data.Text (Text)
import GHC.Generics
import Prelude
import qualified Data.HashMap.Strict as H

import Duckling.Resolve (Resolve(..), Options(..))

data Currency
  -- ambiguous
  = Cent
  | Dinar
  | Dirham
  | Dollar
  | Pound
  | Rial
  | Riyal
  | Unnamed -- e.g. bucks
  -- unambiguous
  | AED
  | AUD
  | BGN
  | BRL
  | BYN
  | CAD
  | CHF
  | CNY
  | CZK
  | DKK
  | EGP
  | EUR
  | GBP
  | HKD
  | HRK
  | IDR
  | ILS
  | INR
  | IQD
  | JMD
  | JOD
  | JPY
  | GEL
  | KRW
  | KWD
  | LBP
  | MAD
  | MNT
  | MYR
  | NOK
  | NZD
  | PKR
  | PLN
  | PTS
  | QAR
  | RON
  | RUB
  | SAR
  | SEK
  | SGD
  | THB
  | TTD
  | USD
  | VND
  | ZAR
  | UAH
  | TRY
  deriving (Eq, Generic, Hashable, Show, Ord, NFData)

instance ToJSON Currency where
  toJSON Cent    = "cent"
  toJSON Dollar  = "$"
  toJSON Pound   = "\x00a3"
  toJSON Dinar   = "dinar"
  toJSON Dirham  = "dirham"
  toJSON Rial    = "rial"
  toJSON Riyal   = "riyal"
  toJSON Unnamed = "unknown"
  toJSON AED     = "AED"
  toJSON AUD     = "AUD"
  toJSON BGN     = "BGN"
  toJSON BRL     = "BRL"
  toJSON BYN     = "BYN"
  toJSON CAD     = "CAD"
  toJSON CHF     = "CHF"
  toJSON CNY     = "CNY"
  toJSON CZK     = "CZK"
  toJSON DKK     = "DKK"
  toJSON EGP     = "EGP"
  toJSON EUR     = "EUR"
  toJSON GBP     = "GBP"
  toJSON HKD     = "HKD"
  toJSON HRK     = "HRK"
  toJSON IDR     = "IDR"
  toJSON ILS     = "ILS"
  toJSON IQD     = "IQD"
  toJSON INR     = "INR"
  toJSON JMD     = "JMD"
  toJSON JOD     = "JOD"
  toJSON JPY     = "JPY"
  toJSON GEL     = "GEL"
  toJSON KRW     = "KRW"
  toJSON KWD     = "KWD"
  toJSON LBP     = "LBP"
  toJSON MAD     = "MAD"
  toJSON MNT     = "MNT"
  toJSON MYR     = "MYR"
  toJSON NOK     = "NOK"
  toJSON NZD     = "NZD"
  toJSON PTS     = "PTS"
  toJSON PKR     = "PKR"
  toJSON PLN     = "PLN"
  toJSON QAR     = "QAR"
  toJSON RON     = "RON"
  toJSON RUB     = "RUB"
  toJSON SAR     = "SAR"
  toJSON SEK     = "SEK"
  toJSON SGD     = "SGD"
  toJSON THB     = "THB"
  toJSON TTD     = "TTD"
  toJSON USD     = "USD"
  toJSON VND     = "VND"
  toJSON ZAR     = "ZAR"
  toJSON UAH     = "UAH"
  toJSON TRY     = "TRY"

data AmountOfMoneyData = AmountOfMoneyData
  { value    :: Maybe Double
  , currency :: Currency
  , minValue :: Maybe Double
  , maxValue :: Maybe Double
  , latent   :: Bool
  }
  deriving (Eq, Generic, Hashable, Show, Ord, NFData)

instance Resolve AmountOfMoneyData where
  type ResolvedValue AmountOfMoneyData = AmountOfMoneyValue
  resolve _ Options {withLatent = False} AmountOfMoneyData {latent = True} =
    Nothing
  resolve _ _ AmountOfMoneyData {value = Nothing, minValue = Nothing
                              , maxValue = Nothing} =
    Nothing
  resolve _ _ AmountOfMoneyData {value = Just value, currency, latent} =
    Just (simple currency value, latent)
  resolve _ _ AmountOfMoneyData {value = Nothing, currency = c
                              , minValue = Just from, maxValue = Just to
                              , latent} =
    Just (between c (from, to), latent)
  resolve _ _ AmountOfMoneyData {value = Nothing, currency = c
                              , minValue = Just v, maxValue = Nothing
                              , latent} =
    Just (above c v, latent)
  resolve _ _ AmountOfMoneyData {value = Nothing, currency = c
                              , minValue = Nothing, maxValue = Just v
                              , latent} =
    Just (under c v, latent)

amountOfMoneyData' :: AmountOfMoneyData
amountOfMoneyData' = AmountOfMoneyData
  { value = Nothing
  , currency = Unnamed
  , minValue = Nothing
  , maxValue = Nothing
  , latent = False
  }

data IntervalDirection = Above | Under
  deriving (Eq, Generic, Hashable, Ord, Show, NFData)

data SingleValue = SingleValue
  { vCurrency :: Currency
  , vValue    :: Double
  }
  deriving (Eq, Show)

instance ToJSON SingleValue where
  toJSON SingleValue {vCurrency, vValue} = object
    [ "value" .= vValue
    , "unit"  .= vCurrency
    ]

data AmountOfMoneyValue
  = SimpleValue SingleValue
  | IntervalValue (SingleValue, SingleValue)
  | OpenIntervalValue (SingleValue, IntervalDirection)
  deriving (Show, Eq)

instance ToJSON AmountOfMoneyValue where
  toJSON (SimpleValue value) = case toJSON value of
    Object o -> Object $ H.insert "type" (toJSON ("value" :: Text)) o
    _ -> Object H.empty
  toJSON (IntervalValue (from, to)) = object
    [ "type" .= ("interval" :: Text)
    , "from" .= toJSON from
    , "to" .= toJSON to
    ]
  toJSON (OpenIntervalValue (from, Above)) = object
    [ "type" .= ("interval" :: Text)
    , "from" .= toJSON from
    ]
  toJSON (OpenIntervalValue (to, Under)) = object
    [ "type" .= ("interval" :: Text)
    , "to" .= toJSON to
    ]

-- -----------------------------------------------------------------
-- Value helpers

simple :: Currency -> Double -> AmountOfMoneyValue
simple c v = SimpleValue $ single c v

between :: Currency -> (Double, Double) -> AmountOfMoneyValue
between c (from, to) = IntervalValue (single c from, single c to)

above :: Currency -> Double -> AmountOfMoneyValue
above = openInterval Above

under :: Currency -> Double -> AmountOfMoneyValue
under = openInterval Under

openInterval :: IntervalDirection -> Currency -> Double -> AmountOfMoneyValue
openInterval direction c v = OpenIntervalValue (single c v, direction)

single :: Currency -> Double -> SingleValue
single c v = SingleValue {vCurrency = c, vValue = v}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RobotBumFoundationCore;

namespace RobotBumLibCore.Map
{
    public class CheckPoint
    {
        public string Name { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public string Region { get; set; }
        [JsonIgnoreAttribute]
        private static List<CheckPoint> listCheckPoints { get; set; }
        [JsonIgnoreAttribute]
        public static List<CheckPoint> ListCheckPoints
        {
            get
            {
                if (listCheckPoints == null)
                    LoadCheckPoints();

                return listCheckPoints;
            }
        }

        public static CheckPoint GetCheckPoint(string name)
        {
            return ListCheckPoints.Where(s => s.Name == name).FirstOrDefault();
        }

        public static void LoadCheckPoints()
        {
            try
            {
                listCheckPoints = new List<CheckPoint>();

                StreamReader file = File.OpenText(MultiOSFileSupport.ResourcesFolder + "checkpoints.json");

                StringBuilder jsonstring = new StringBuilder();

                while (file.Peek() >= 0)
                {

                    jsonstring.Append(file.ReadLine());
                }

                var listCountires = JsonConvert.DeserializeObject<IDictionary<string, IDictionary<string, string>>>(jsonstring.ToString());

                foreach (var item in listCountires)
                {
                    listCheckPoints.Add(new CheckPoint()
                    {
                        Name = item.Key,
                        Latitude = Convert.ToDouble(item.Value["Latitude"]),
                        Longitude = Convert.ToDouble(item.Value["Longitude"]),
                        Region = item.Value["Region"],
                    });
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException(MultiOSFileSupport.ResourcesFolder + "checkpoints.json");
            }

        }

        public override string ToString()
        {
            return this.Name;
        }

    }
}


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

    Jakarta Bean Validation TCK

    License: Apache License, Version 2.0
    See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>jakarta.validation</groupId>
        <artifactId>beanvalidation-tck-parent</artifactId>
        <version>3.0.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>beanvalidation-standalone-container-adapter</artifactId>
    <packaging>jar</packaging>

    <name>Jakarta Bean Validation TCK Container Adapter</name>
    <description>Jakarta Bean Validation TCK Arquillian Standalone Container Adapter</description>

    <properties>
        <beanvalidation-tck-parent.basedir>${project.parent.basedir}</beanvalidation-tck-parent.basedir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian.testng</groupId>
            <artifactId>arquillian-testng-container</artifactId>
        </dependency>
    </dependencies>
</project>


text:
import serial, serial.tools.list_ports, time
from ctypes import c_ushort
from bglib import BGLib

__author__    = 'Kazuyuki TAKASE'
__copyright__ = 'PLEN Project Company Ltd., and all authors.'
__license__   = 'The MIT License'

class Core:
	def __init__(self, device_map, mac = ''):
		self._serial       = None
		self._bglib        = BGLib()
		self._bglib_result = False
		self._DEVICE_MAP   = device_map
		self._values     = [ 0 for x in range(24) ]

		if (mac != ''):
			import re
			regexp = '^\d\d:\d\d:\d\d:\d\d:\d\d:\d\d$'

			if re.compile(regexp).match(mac) != None:
				mac_addr = list(map(lambda h: int(h, 16), mac.split(':')))
				mac_addr.reverse()
			else:
				mac = ''

		def ble_evt_gap_scan_response(sender, args):
			if mac != '':
				if args["sender"] == mac_addr:
					self._bglib.send_command(self._serial, self._bglib.ble_cmd_gap_connect_direct(args["sender"], 0, 60, 76, 100, 0))
			else:
				self._bglib.send_command(self._serial, self._bglib.ble_cmd_gap_connect_direct(args["sender"], 0, 60, 76, 100, 0))

		def ble_evt_connection_status(sender, args):
			if (args["flags"] == 0x05):
				self._bglib_result = True
			else:
				self._bglib_result = False

		self._bglib.ble_evt_gap_scan_response += ble_evt_gap_scan_response
		self._bglib.ble_evt_connection_status += ble_evt_connection_status

	def apply(self, device, value):
		if self._serial == None:
			return False

		cmd = "$AN%02x%03x" % (self._DEVICE_MAP[device], (c_ushort(value).value & 0xFFF))

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def applyDiff(self, device, value):
		if self._serial == None:
			return False

		cmd = "$AD%02x%03x" % (self._DEVICE_MAP[device], (c_ushort(value).value & 0xFFF))

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def setMin(self, device, value):
		if self._serial == None:
			return False

		cmd = ">MI%02x%03x" % (self._DEVICE_MAP[device], (c_ushort(value).value & 0xFFF))

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def setMax(self, device, value):
		if self._serial == None:
			return False

		cmd = ">MA%02x%03x" % (self._DEVICE_MAP[device], (c_ushort(value).value & 0xFFF))

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def setHome(self, device, value):
		if self._serial == None:
			return False

		cmd = ">HO%02x%03x" % (self._DEVICE_MAP[device], (c_ushort(value).value & 0xFFF))

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def play(self, slot):
		if self._serial == None:
			return False

		cmd = "$PM%02x" % slot

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def stop(self):
		if self._serial == None:
			return False

		cmd = "$SM"

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def install(self, json):
		if self._serial == None:
			return False

		# コマンドの指定
		cmd = ">IN"

		# スロット番号の指定
		cmd += "%02x" % (json["slot"])

		# モーション名の指定
		if len(json["name"]) < 20:
			cmd += json["name"].ljust(20)
		else:
			cmd += json["name"][:19]

		# 制御機能の指定
		if (len(json["codes"]) != 0):
			for code in json["codes"]:
				if (code["func"] == "loop"):
					cmd += "01%02x%02x" % (code["args"][0], code["args"][1])
					break

				if (code["func"] == "jump"):
					cmd += "02%02x00" % (code["args"][0])
					break
		else:
			cmd += "000000"

		# フレーム数の指定
		cmd += "%02x" % (len(json["frames"]))

		# フレーム構成要素の指定
		for frame in json["frames"]:
			# 遷移時間の指定
			cmd += "%04x" % (frame["transition_time_ms"])

			for output in frame["outputs"]:
				self._values[self._DEVICE_MAP[output["device"]]] = c_ushort(output["value"]).value

			for value in self._values:
				cmd += "%04x" % value

		# Divide command length by ble-payload size.
		block   = len(cmd) // 20
		surplus = len(cmd) % 20

		for index in range(block):
			self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd[20 * index: 20 * (index + 1)]))))
			self._bglib.check_activity(self._serial, 1)
			self._bglib.check_activity(self._serial, 1)

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_attclient_attribute_write(0, 31, list(map(ord, cmd[-surplus:]))))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		return True

	def connect(self):
		com = None

		for device in list(serial.tools.list_ports.comports()):
			if "Bluegiga" in device[1]:
				com = device[0]

		if com == None:
			return False

		if self._serial != None:
			self._serial.close()
			self._serial = None

		if self._serial == None:
			self._serial = serial.Serial(port = com, baudrate = 2000000, timeout = 1)
			self._serial.flushInput()
			self._serial.flushOutput()

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_connection_disconnect(0))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_gap_set_mode(0, 0))
		self._bglib.check_activity(self._serial, 1)

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_gap_end_procedure())
		self._bglib.check_activity(self._serial, 1)

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_gap_discover(1))
		self._bglib.check_activity(self._serial, 1)

		self._bglib_result = False
		while (not self._bglib_result):
			self._bglib.check_activity(self._serial)
			time.sleep(0.01)

		return True

	def disconnect(self):
		if self._serial == None:
			return False

		self._bglib.send_command(self._serial, self._bglib.ble_cmd_connection_disconnect(0))
		self._bglib.check_activity(self._serial, 1)
		self._bglib.check_activity(self._serial, 1)
		self._bglib_result = False

		self._serial.close()
		self._serial = None

		return True


text:
using DriverInterfaceWrapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UserDriverStaticImage
{
    static class Program
    {
        [MTAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!DriverInterface.Init())
            {
                MessageBox.Show("Unable to init DriverInterface!");

                return;
            }

            Thread sta = new Thread(new ThreadStart(() =>
            {
                Application.Run(new MainForm());
            }));

            sta.SetApartmentState(ApartmentState.STA);
            sta.Start();
            sta.Join();

            DriverInterface.Free();
        }
    }
}


text:
/* interface declaration for display messages */
/* This is a small subset of the interface from display.c that
   just contains the calls for displaying messages.  Do not include
   this and display.h at the same time. */

#ifndef _MESSAGE_H
#define _MESSAGE_H

void error_message(char *msgfmt, ...);
void clear_message();

#endif /* _MESSAGE_H_ */


text:
import { JwtService } from '@nestjs/jwt';
import { Injectable } from '@nestjs/common';
import { JwtPayload } from './dto/jwt-payload.dto';
import { UserService } from '../../graph/user/user.service';
import { Config } from '../config';
import { User } from '../../graph/user/user.model';
import { TokenUserDto } from '../../graph/user/dto/token-user.dto';
import { Response } from 'express';

/**
 *
 */
@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UserService,
    private readonly config: Config,
    private readonly jwtService: JwtService) { }

  signOut(req): any {
    req.logout();
  }

  signIn(res: Response, user: User): TokenUserDto {
    const token = this.createToken(user);
    res.set('Authorization', token.accessToken);
    res.set('expiresIn', '' + token.expiresIn);
    return {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      clubId: user.clubId
    }
  }

  /**
   * Used during login, this creates a JWT bearer token for this user.
   *
   * @returns a token if the user credentials are verified
   */
  createToken(user: User) {
    const expiresIn = this.config.get('JWT_EXPIRATION') || 3600;
    const accessToken = this.jwtService.sign({
      // These properties will be encoded into the token
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role,
      clubId: user.clubId
    }, { expiresIn: expiresIn });
    return { expiresIn, accessToken };
  }

  /**
   *
   * @param payload The deserialized JWT bearer token
   */
  async validateToken(payload: JwtPayload): Promise<User> {
    return await this.usersService.findOneById(payload.id);
  }
}


text:
<?php
/**
 * This file is part of the Ray.RoleModule
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace Ray\RoleModule;

use Doctrine\Common\Annotations\Reader;
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
use Ray\RoleModule\Annotation\RequiresRoles;
use Ray\RoleModule\Exception\RequiredRolesException;
use Zend\Permissions\Acl\AclInterface;
use Zend\Permissions\Acl\Resource\GenericResource;

class RequiredRolesInterceptor implements MethodInterceptor
{
    private $reader;

    /**
     * @var AclInterface
     */
    private $acl;

    private $roleProvider;

    public function __construct(Reader $reader, AclInterface $acl, RoleProviderInterface $roleProvider)
    {
        $this->reader = $reader;
        $this->acl = $acl;
        $this->roleProvider = $roleProvider;
    }

    /**
     * {@inheritdoc}
     */
    public function invoke(MethodInvocation $invocation)
    {
        /** @var $annotation RequiresRoles */
        $annotation = $this->reader->getMethodAnnotation($invocation->getMethod(), RequiresRoles::class);
        if (! $annotation) {
            $class = new \ReflectionClass($invocation->getThis());
            $annotation = $this->reader->getClassAnnotation($class, RequiresRoles::class);
        }
        $target = get_class($invocation->getThis());
        $this->acl->addResource(new GenericResource($target));
        foreach ($annotation->value as $role) {
            $this->acl->allow($role, $target);
        }
        $role = $this->roleProvider->get();
        $isAllowed = $this->acl->isAllowed($role, $target);
        if ($isAllowed) {
            return $invocation->proceed();
        }
        $msg = sprintf("%s for %s", $role, $target);
        $e = new RequiredRolesException($msg);
        $e->setMethodInvocation($invocation);

        throw $e;
    }
}


text:
package com.amazonaws.services.identitymanagement.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.identitymanagement.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * PolicyUser StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PolicyUserStaxUnmarshaller implements Unmarshaller<PolicyUser, StaxUnmarshallerContext> {

    public PolicyUser unmarshall(StaxUnmarshallerContext context) throws Exception {
        PolicyUser policyUser = new PolicyUser();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return policyUser;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("UserName", targetDepth)) {
                    policyUser.setUserName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("UserId", targetDepth)) {
                    policyUser.setUserId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return policyUser;
                }
            }
        }
    }

    private static PolicyUserStaxUnmarshaller instance;

    public static PolicyUserStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new PolicyUserStaxUnmarshaller();
        return instance;
    }
}


text:
SDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )";

CONF_BASE_PATH="$HOME/.config/proxpn";
CONF_FILE="proxpn.ovpn";
configFilePath="$SDIR/$CONF_FILE"
systemConfigFilePath="$CONF_BASE_PATH/$CONF_FILE";
executableFileName="proxpn";
executableFilePath="$SDIR/$executableFileName";
systemInstallPath="/usr/local/bin";
executableSystemInstallPath="$systemInstallPath/$executableFileName";
CREDS_FILE="login.conf";
systemCredsFilePath="$CONF_BASE_PATH/$CREDS_FILE";
configOnly="false"

# Source: https://gist.github.com/hoylen/6607180
PROG="$(basename "$0")";
VERSION="0.2";

#----------------------------------------------------------------
# Process command line options

HELP_TEXT="Usage: $PROG [options]
Options:
  -f | --force          Allow overwriting existing files on system if they already exist.  Useful for at least updating login info, and for also restoring program defaults.
  -s | --symlink        Install the main program executable as a link to the original contained within this project, rather than copying it over into the system directory.  This may allow for simply updating the main project via source control, but be aware that changing its location may break the symlink, and would require re-installation.
  -c | --configuration  Skip adding the script to the user's PATH and just create proxpn configuration files.
  -h | --help           show this help message";

while [ $# -gt 0 ]; do
    case "$1" in
        -h | --help)
          echo "$HELP_TEXT";
          exit 0;
          ;;
        -c | --configuration)
          configOnly="true"
          ;;
        -s | --symlink)
          symlinkToMainExecutable="true";
          ;;
        -f | --force)
          overwriteFiles="true";
          ;;
        --)
          shift;
          break;
          ;; # end of options
    esac
    shift
done

if [ $EUID != 0 -a $configOnly != true ]; then
  echo "This script must be run as root in order to copy the script to $systemInstallPath."
  echo "Falling back to configuration only mode. You must re-run this script with sudo or manually copy the proxpn script into your PATH before using the proxpn command."
  echo
  configOnly="true"
fi

[[ -z "$overwriteFiles" ]] && overwriteFiles="false";
[[ -z "$symlinkToMainExecutable" ]] && symlinkToMainExecutable="false";

#----------------------------------------------------------------

if [[ ! -d "$CONF_BASE_PATH" ]]; then
  mkdir -p "$CONF_BASE_PATH";
fi

## Install system-wide configuration, if not already installed.
if [[ -f "$systemConfigFilePath" && ! "$overwriteFiles" == "true" ]]; then
  echo "System-wide configuration file already exists; continuing installation...";
elif [[ -f "$configFilePath" ]]; then
  if cp "$configFilePath" "$systemConfigFilePath"; then
    echo "Successfully installed system-wide configuration file.";
  else
    echo "Error: Not able to install system-wide configuration file; exiting...";
    exit 1;
  fi
else
  echo "Error: OpenVPN configuration file not found in project: \"$SDIR/$CONF_FILE\"";
  echo "Exiting...";
  exit 1;
fi

## Install system-wide program link, if not already installed.
if [[ -f "$executableSystemInstallPath" && ! "$overwriteFiles" == "true" ]]; then
  echo "System-wide program link already exists; continuing installation...";
elif [ $configOnly == "true" ]; then
  echo "Operating in configuration only mode. Skipping system-wide progam linking..."
elif [[ -f "$executableFilePath" ]]; then
  if [[ -f "$executableSystemInstallPath" ]]; then
    rm "$executableSystemInstallPath";
  fi
  if [[ "$symlinkToMainExecutable" == "true" ]]; then
    if ln -s "$executableFilePath" "$executableSystemInstallPath"; then
      echo "Successfully installed system-wide program link.";
    else
      echo "Error: Not able to install system-wide program link; exiting...";
      exit 1;
    fi
  else
    if cp "$executableFilePath" "$executableSystemInstallPath"; then
      echo "Successfully installed system-wide program file.";
    else
      echo "Error: Not able to install system-wide program file; exiting...";
      exit 1;
    fi
  fi
else
  echo "Error: Main executable file not found in project: \"$executableFilePath\"";
  echo "Exiting...";
  exit 1;
fi

## Install system-wide credentials file, if not already installed.
if [[ -f "$systemCredsFilePath" && ! "$overwriteFiles" == "true" ]]; then
  echo "System-wide credentials file already exists; continuing installation...";
else
  while [[ "$storeCredentialsChoice" != "y" && "$storeCredentialsChoice" != "n" ]]; do
    read -p "Do you want to enter and store your credentials? (y/n): " storeCredentialsChoice;
  done
  if [[ "$storeCredentialsChoice" == "y" ]]; then
    read -p "Username: " username;
    read -s -p "Password: " password;
    if echo -e "$username\n$password" > "$systemCredsFilePath"; then
      echo "Successfully installed system-wide credentials file.";
      unset username;
      unset password;
    else
      echo "Error: Not able to install system-wide credentials file; exiting...";
      unset username;
      unset password;
      exit 1;
    fi
  else
    if [[ -f "$systemCredsFilePath" ]]; then
      echo "Choosing to not overwrite permanently stored credentials.  Using existing information on system.";
    else
      echo "Choosing to not permanently store credentials.  They will have to be entered upon successive executions of the main script.";
    fi
  fi
fi


text:
<?php

class Userdeviceinfo extends ModelBase
{

    /**
     *
     * @var integer
     */
    protected $ID;

    /**
     *
     * @var integer
     */
    protected $userid;

    /**
     *
     * @var integer
     */
    protected $channeltype;

    /**
     *
     * @var string
     */
    protected $channeluserid;

    /**
     *
     * @var string
     */
    protected $IDFA;

    /**
     *
     * @var string
     */
    protected $IDFV;

    /**
     *
     * @var string
     */
    protected $APPstoreaccount;

    /**
     *
     * @var string
     */
    protected $IMEI;

    /**
     *
     * @var string
     */
    protected $carrieroperator;

    /**
     *
     * @var string
     */
    protected $phonetype;

    /**
     *
     * @var string
     */
    protected $sysversion;

    /**
     *
     * @var string
     */
    protected $ip;

    /**
     *
     * @var integer
     */
    protected $addtime;
    /**
     *
     * @var string
     */
    protected $network;
    /**
     *
     * @var string
     */
    protected $nettype;

    /**
     *
     * @var string
     */
    protected $macaddress;
    /**
     * Method to set the value of field ID
     *
     * @param integer $ID
     * @return $this
     */
    public function setId($ID)
    {
        $this->ID = $ID;

        return $this;
    }

    /**
     * Method to set the value of field userid
     *
     * @param integer $userid
     * @return $this
     */
    public function setUserid($userid)
    {
        $this->userid = $userid;

        return $this;
    }

    /**
     * Method to set the value of field channeltype
     *
     * @param integer $channeltype
     * @return $this
     */
    public function setChanneltype($channeltype)
    {
        $this->channeltype = $channeltype;

        return $this;
    }

    /**
     * Method to set the value of field channeluserid
     *
     * @param string $channeluserid
     * @return $this
     */
    public function setChanneluserid($channeluserid)
    {
        $this->channeluserid = $channeluserid;

        return $this;
    }

    /**
     * Method to set the value of field IDFA
     *
     * @param string $IDFA
     * @return $this
     */
    public function setIdfa($IDFA)
    {
        $this->IDFA = $IDFA;

        return $this;
    }

    /**
     * Method to set the value of field nettype
     *
     * @param string $nettype
     * @return $this
     */
    public function setNettype($nettype)
    {
        $this->nettype = $nettype;

        return $this;
    }
    /**
     * Method to set the value of field macaddress
     *
     * @param string $macaddress
     * @return $this
     */
    public function setMacaddress($macaddress)
    {
        $this->macaddress = $macaddress;

        return $this;
    }

    /**
     * Method to set the value of field network
     *
     * @param string $network
     * @return $this
     */
    public function setNetwork($network)
    {
        $this->network = $network;

        return $this;
    }

    /**
     * Method to set the value of field IDFV
     *
     * @param string $IDFV
     * @return $this
     */
    public function setIdfv($IDFV)
    {
        $this->IDFV = $IDFV;

        return $this;
    }

    /**
     * Method to set the value of field APPstoreaccount
     *
     * @param string $APPstoreaccount
     * @return $this
     */
    public function setAppstoreaccount($APPstoreaccount)
    {
        $this->APPstoreaccount = $APPstoreaccount;

        return $this;
    }

    /**
     * Method to set the value of field IMEI
     *
     * @param string $IMEI
     * @return $this
     */
    public function setImei($IMEI)
    {
        $this->IMEI = $IMEI;

        return $this;
    }

    /**
     * Method to set the value of field carrieroperator
     *
     * @param string $carrieroperator
     * @return $this
     */
    public function setCarrieroperator($carrieroperator)
    {
        $this->carrieroperator = $carrieroperator;

        return $this;
    }

    /**
     * Method to set the value of field phonetype
     *
     * @param string $phonetype
     * @return $this
     */
    public function setPhonetype($phonetype)
    {
        $this->phonetype = $phonetype;

        return $this;
    }

    /**
     * Method to set the value of field sysversion
     *
     * @param string $sysversion
     * @return $this
     */
    public function setSysversion($sysversion)
    {
        $this->sysversion = $sysversion;

        return $this;
    }

    /**
     * Method to set the value of field addtime
     *
     * @param integer $addtime
     * @return $this
     */
    public function setAddtime($addtime)
    {
        $this->addtime = $addtime;

        return $this;
    }
    /**
     * Method to set the value of field ip
     *
     * @param string $ip
     * @return $this
     */
    public function setIp($ip)
    {
        $this->ip = $ip;

        return $this;
    }
    /**
     * Returns the value of field ID
     *
     * @return integer
     */
    public function getId()
    {
        return $this->ID;
    }

    /**
     * Returns the value of field userid
     *
     * @return integer
     */
    public function getUserid()
    {
        return $this->userid;
    }

    /**
     * Returns the value of field channeltype
     *
     * @return integer
     */
    public function getChanneltype()
    {
        return $this->channeltype;
    }

    /**
     * Returns the value of field channeluserid
     *
     * @return string
     */
    public function getChanneluserid()
    {
        return $this->channeluserid;
    }

    /**
     * Returns the value of field IDFA
     *
     * @return string
     */
    public function getIdfa()
    {
        return $this->IDFA;
    }

    /**
     * Returns the value of field network
     *
     * @return string
     */
    public function getNetwork()
    {
        return $this->network;
    }
    /**
     * Returns the value of field macaddress
     *
     * @return string
     */
    public function getMacaddress()
    {
        return $this->macaddress;
    }

    /**
     * Returns the value of field nettype
     *
     * @return string
     */
    public function getNettype()
    {
        return $this->nettype;
    }

    /**
     * Returns the value of field IDFV
     *
     * @return string
     */
    public function getIdfv()
    {
        return $this->IDFV;
    }

    /**
     * Returns the value of field APPstoreaccount
     *
     * @return string
     */
    public function getAppstoreaccount()
    {
        return $this->APPstoreaccount;
    }

    /**
     * Returns the value of field IMEI
     *
     * @return string
     */
    public function getImei()
    {
        return $this->IMEI;
    }

    /**
     * Returns the value of field carrieroperator
     *
     * @return string
     */
    public function getCarrieroperator()
    {
        return $this->carrieroperator;
    }

    /**
     * Returns the value of field phonetype
     *
     * @return string
     */
    public function getPhonetype()
    {
        return $this->phonetype;
    }

    /**
     * Returns the value of field sysversion
     *
     * @return string
     */
    public function getSysversion()
    {
        return $this->sysversion;
    }

    /**
     * Returns the value of field addtime
     *
     * @return integer
     */
    public function getAddtime()
    {
        return $this->addtime;
    }

    /**
     * Returns the value of field ip
     *
     * @return string
     */
    public function getIp()
    {
        return $this->ip;
    }
    /**
     * Independent Column Mapping.
     */
    public function columnMap()
    {
        return array(
            'ID' => 'ID',
            'userid' => 'userid',
            'channeltype' => 'channeltype',
            'channeluserid' => 'channeluserid',
            'IDFA' => 'IDFA',
            'IDFV' => 'IDFV',
            'APPstoreaccount' => 'APPstoreaccount',
            'IMEI' => 'IMEI',
            'carrieroperator' => 'carrieroperator',
            'phonetype' => 'phonetype',
            'sysversion' => 'sysversion',
            'addtime' => 'addtime',
            'ip'=>'ip',
            'nettype'=>'nettype',
            'network'=>'network',
            'macaddress'=>'macaddress'
        );
    }

}


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

<title>TaskGraphVisualizer</title>
<meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

tools

Class TaskGraphVisualizer

java.lang.Object

tools.GMLExporter

tools.TaskGraphVisualizer

public class TaskGraphVisualizer
extends GMLExporter

Task Graph visualizer.
 Suggested workflow:
 - create an instance and invoke exportGML() method
 - use external tool (yEd) to draw the GML file

Author:

"Kostiantyn Kucher"

Constructor Summary

Constructors

Constructor and Description

TaskGraphVisualizer()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
exportGML(java.lang.String baseFilename,
         TaskGraph.START allTaskGraphs)

Exports the visualization of Task Graph to a GML file

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TaskGraphVisualizer

public TaskGraphVisualizer()

Method Detail

exportGML

public void exportGML(java.lang.String baseFilename,
                      TaskGraph.START allTaskGraphs)
               throws java.io.IOException

Exports the visualization of Task Graph to a GML file

Parameters:

baseFilename - exported file name (without extension)

allTaskGraphs - map of unique scope ID to Task Graphs

Throws:

java.io.IOException - if writing to external file has failed

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method