text:
---
subcategory: "Cloud Key Management Service"
page_title: "Google: google_kms_crypto_key_version"
description: |-
 Provides access to KMS key version data with Google Cloud KMS.
---

# google\_kms\_crypto\_key\_version

Provides access to a Google Cloud Platform KMS CryptoKeyVersion. For more information see
[the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version)
and
[API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions).

A CryptoKeyVersion represents an individual cryptographic key, and the associated key material.

## Example Usage

```hcl
data "google_kms_key_ring" "my_key_ring" {
  name     = "my-key-ring"
  location = "us-central1"
}

data "google_kms_crypto_key" "my_crypto_key" {
  name     = "my-crypto-key"
  key_ring = data.google_kms_key_ring.my_key_ring.id
}

data "google_kms_crypto_key_version" "my_crypto_key_version" {
  crypto_key = data.google_kms_crypto_key.my_key.id
}
```

## Argument Reference

The following arguments are supported:

* `crypto_key` - (Required) The `id` of the Google Cloud Platform CryptoKey to which the key version belongs. This is also the `id` field of the
`google_kms_crypto_key` resource/datasource.

* `version` - (Optional) The version number for this CryptoKeyVersion. Defaults to `1`.

## Attributes Reference

In addition to the arguments listed above, the following computed attributes are
exported:

* `id` - an identifier for the resource with format `//cloudkms.googleapis.com/v1/{{crypto_key}}/cryptoKeyVersions/{{version}}`

* `name` - The resource name for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`

* `state` - The current state of the CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs.

* `protection_level` - The ProtectionLevel describing how crypto operations are performed with this CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs.

* `algorithm` - The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports. See the [algorithm reference](https://cloud.google.com/kms/docs/reference/rest/v1/CryptoKeyVersionAlgorithm) for possible outputs.

* `public_key` -  If the enclosing CryptoKey has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block contains details about the public key associated to this CryptoKeyVersion. Structure is [documented below](#nested_public_key).

The `public_key` block, if present, contains:

* `pem` - The public key, encoded in PEM format. For more information, see the RFC 7468 sections for General Considerations and Textual Encoding of Subject Public Key Info.

* `algorithm` - The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports.


text:
package com.example.hoperun.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Administrator on 2015/7/15.
 */
public class DrawView extends View {
    public float currentX = 40;
    public float currnetY = 50;
    //定义并创建画笔
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.RED);
        canvas.drawCircle(currentX,currnetY,15,paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //修改currentX,currentY两个属性
        currentX = event.getX();
        currnetY = event.getY();
        invalidate();

        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using RelhaxModpack.Settings;
using RelhaxModpack.Utilities;
using RelhaxModpack.Utilities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace RelhaxModpack.Windows
{
    /// <summary>
    /// A class definition to specify a window that is a separate sub-function of the application:
    /// It has its own log and settings file, and requires custom loading code
    /// </summary>
    public class RelhaxCustomFeatureWindow : RelhaxWindow
    {
        /// <summary>
        /// Indicates if this editor instance was launched from the MainWindow or from command line
        /// </summary>
        /// <remarks>This changes the behavior of the logging for the editor</remarks>
        public bool LaunchedFromMainWindow { get; set; }

        /// <summary>
        /// The settings definitions class for this window
        /// </summary>
        public ISettingsFile Settings { get; protected set; }

        /// <summary>
        /// Controls is the application will, on startup, run a check to see if it's the latest version
        /// </summary>
        public bool RunStandAloneUpdateCheck { get; set; }

        /// <summary>
        /// Get or (privately) set the log file enumeration to use when writing log messages in this window.
        /// </summary>
        public Logfiles Logfile { get; protected set; }

        /// <summary>
        /// Flag to indicate if the window is performing initialization tasks.
        /// </summary>
        public bool Init { get; protected set; } = true;

        /// <summary>
        /// Creates an instance of the RelhaxCustomFeatureWindow class
        /// </summary>
        public RelhaxCustomFeatureWindow(ModpackSettings modpackSettings, Logfiles logfile) : base(modpackSettings)
        {
            Logfile = logfile;
        }

        /// <summary>
        /// Saves the settings instance used by this application to disk before the window is closed.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            SettingsParser parser = new SettingsParser();
            parser.SaveSettings(Settings);

            if (!LaunchedFromMainWindow)
                Logging.DisposeLogging(Logfile);
        }

        /// <summary>
        /// Loads the settings object with settings values from an xml document specified by the settings object.
        /// </summary>
        protected override void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            SettingsParser parser = new SettingsParser();

            //if it's not launched from the main window, then the ModpackSettings object has not been parsed yet. do that now.
            if (!LaunchedFromMainWindow)
            {
                //use this hook for functions that normally happen in the MainWindow
            }

            //also load the feature window's custom settings file
            parser.LoadSettings(Settings);

            //load base classes method
            base.OnWindowLoaded(sender, e);

            //if not skipping update, and not launched from the main window, then run a stand-alone update check
            if (!LaunchedFromMainWindow && !CommandLineSettings.SkipUpdate && RunStandAloneUpdateCheck)
            {
                Task.Run(async () =>
                {
                    if (!await CommonUtils.IsManagerUptoDate(CommonUtils.GetApplicationVersion(), ModpackSettings.ApplicationDistroVersion))
                    {
                        MessageBox.Show("Your application is out of date. Please launch the application normally to update");
                    }
                });
            }
        }

        /// <summary>
        /// If the default font to apply is null, it is saved from this window's default font.
        /// </summary>
        protected override void ApplyFontToWindow()
        {
            if (DefaultFontFamily == null)
            {
                DefaultFontFamily = this.FontFamily;
                SelectedFontFamily = DefaultFontFamily;
                FontList.Clear();
                FontList.AddRange(Fonts.GetFontFamilies(Environment.GetFolderPath(Environment.SpecialFolder.Fonts)).ToList());
            }

            base.ApplyFontToWindow();
        }
    }
}


text:
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators       #-}

{-|
Module:      Graphics.Blank
Copyright:   (C) 2014-2015, The University of Kansas
License:     BSD-style (see the file LICENSE)
Maintainer:  Andy Gill
Stability:   Beta
Portability: GHC

@blank-canvas@ is a Haskell binding to the complete
<https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API HTML5 Canvas API>.
@blank-canvas@ allows Haskell users to write, in Haskell,
interactive images onto their web browsers. @blank-canvas@ gives
the users a single full-window canvas, and provides many
well-documented functions for rendering images.
-}
module Graphics.Blank
        (
         -- * Starting @blank-canvas@
          blankCanvas
        , Options(..)
          -- ** 'send'ing to the Graphics 'DeviceContext'
        , DeviceContext       -- abstact
        , send
          -- * HTML5 Canvas API
          -- | See <https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API> for the JavaScript
          --   version of this API.
        , Canvas        -- abstract
          -- ** Canvas element
        , height
        , width
        , toDataURL
          -- ** 2D Context
        , save
        , restore
          -- ** Transformation
        , scale
        , rotate
        , translate
        , transform
        , setTransform
          -- ** Image drawing
        , Image -- abstract class
        , drawImage
          -- ** Compositing
        , globalAlpha
        , globalCompositeOperation
          -- ** Line styles
        , lineWidth
        , lineCap
        , lineJoin
        , miterLimit
        , LineEndCap(..)
        , butt
        , square
        , LineJoinCorner(..)
        , bevel
        , miter
          -- ** Colors, styles and shadows
        , strokeStyle
        , fillStyle
        , shadowOffsetX
        , shadowOffsetY
        , shadowBlur
        , shadowColor
        , createLinearGradient
        , createRadialGradient
        , createPattern
        , addColorStop
        , RepeatDirection(..)
        , repeat_
        , repeatX
        , repeatY
        , noRepeat
        , CanvasGradient
        , CanvasPattern
          -- ** Paths
        , beginPath
        , closePath
        , fill
        , stroke
        , clip
        , moveTo
        , lineTo
        , quadraticCurveTo
        , bezierCurveTo
        , arcTo
        , arc
        , rect
        , isPointInPath
          -- ** Text
        , font
        , textAlign
        , textBaseline
        , fillText
        , strokeText
        , measureText
        , TextAnchorAlignment(..)
        , start
        , end
        , center
        , left
        , right
        , TextBaselineAlignment(..)
        , top
        , hanging
        , middle
        , alphabetic
        , ideographic
        , bottom
        , TextMetrics(..)
          -- ** Rectangles
        , clearRect
        , fillRect
        , strokeRect
          -- ** Pixel manipulation
        , getImageData
        , putImageData
        , ImageData(..)
          -- * Type information
        , Alpha
        , Degrees
        , Interval
        , Percentage
        , Radians
        , RoundProperty(..)
        -- * @blank-canvas@ Extensions
	-- ** static (image) data
	, staticURL
	, URL(..)
        , newImage
        -- ** Reading from 'Canvas'
        , CanvasImage -- abstract
          -- ** Audio functionality
{-
        , currentTimeAudio
        , durationAudio -- subject to change
        , indexAudio
        , playAudio
        , pauseAudio
        , setCurrentTimeAudio
        , setLoopAudio
        , setMutedAudio
        , setPlaybackRateAudio
        , setVolumeAudio
        , newAudio
        , CanvasAudio
-}
         -- ** 'DeviceContext' attributes
        , devicePixelRatio
         -- ** 'CanvasContext', and off-screen Canvas.
        , CanvasContext
        , newCanvas
        , with
        , myCanvasContext
        , deviceCanvasContext
         -- ** Syncing
        , sync
         -- ** Debugging
        , console_log
        , eval
        , JSArg(..)
         -- ** Drawing Utilities
        , module Graphics.Blank.Utils
         -- ** Events
        , trigger
        , eventQueue
        , wait
        , flush
        , Event(..)
        , EventName
        , EventQueue
        -- ** Cursor manipulation
        , cursor
        -- ** Middleware
        , local_only
        ) where

import           Control.Concurrent
import           Control.Concurrent.STM
import           Control.Exception
import           Control.Monad.IO.Class

import           Data.Aeson                   (Result (..), fromJSON)
import           Data.Aeson.Types             (parse)
import qualified Data.List                    as L
import qualified Data.Map                     as M (lookup)
import qualified Data.Set                     as S
import qualified Data.Text                    as ST
import           Data.Text.Encoding           (decodeUtf8)
import           Data.Text.Lazy               (Text)
import qualified Data.Text.Lazy               as T
import qualified Data.Text.Lazy               as LT

import           Graphics.Blank.Canvas        hiding (addColorStop, cursor)
import qualified Graphics.Blank.Canvas        as Canvas
import           Graphics.Blank.DeviceContext
import           Graphics.Blank.Events
import           Graphics.Blank.Generated     hiding (fillStyle, font,
                                               shadowColor, strokeStyle, cursor)
import qualified Graphics.Blank.Generated     as Generated
import           Graphics.Blank.JavaScript    hiding (durationAudio, height,
                                               indexAudio, width)
import qualified Graphics.Blank.JavaScript    as JavaScript
import           Graphics.Blank.Types
import           Graphics.Blank.Utils

import           Graphics.Blank.Instr

import qualified Network.HTTP.Types           as H
import           Network.Mime                 (defaultMimeMap,
                                               fileNameExtensions)
import           Network.Wai                  (Middleware, responseLBS)
import           Network.Wai.Handler.Warp
import           Network.Wai.Middleware.Local as Local
import           Network.Wai.Middleware.RequestLogger
import qualified Network.JavaScript as JS

import           Paths_blank_canvas

import           Control.Category
import           Prelude.Compat               hiding (id, (.))

import           System.IO.Unsafe             (unsafePerformIO)

import           Web.Scotty                   (file, get, scottyApp)
import qualified Web.Scotty                   as Scotty
--import qualified Web.Scotty.Comet             as KC

import           Control.Natural
import qualified Control.Natural              as N
--import           Control.Remote.Monad
--import qualified Control.Remote.Packet.Strong as SP
--import qualified Control.Remote.Packet.Weak   as WP

import           Control.Monad.Reader         hiding (local)
import           Control.Monad.State          (evalStateT)
--import qualified Control.Monad.State          as State
--import           Control.Monad.Writer

import           Data.String

-- | 'blankCanvas' is the main entry point into @blank-canvas@.
-- A typical invocation would be
--
-- >{-# LANGUAGE OverloadedStrings #-}
-- >module Main where
-- >
-- >import Graphics.Blank
-- >
-- >main = blankCanvas 3000 $ \ context -> do
-- >        send context $ do
-- >                moveTo(50,50)
-- >                lineTo(200,100)
-- >                lineWidth 10
-- >                strokeStyle "red"
-- >                stroke()
-- >

blankCanvas :: Options -> (DeviceContext -> IO ()) -> IO ()
blankCanvas opts actions = do
   dataDir <- getDataDir

--   kComet <- KC.kCometPlugin

   locals :: TVar (S.Set Text) <- atomically $ newTVar S.empty

--   print dataDir

   app <- scottyApp $ do
--        Scotty.middleware logStdoutDev
        sequence_ [ Scotty.middleware ware
                  | ware <- middleware opts
                  ]

        Scotty.middleware $ JS.start $ \ eng -> do

	  print "Got here"

	  JS.send eng $ sequenceA
	    [ JS.command $ JS.call "register" [ JS.string nm ]
            | nm <- events opts
            ]

	  print "Sent"

          queue <- atomically newTChan

	  _ <- forkIO $ forever $ do
	  	 atomically $ do
		   (val,_) <- JS.readEventChan eng
		   case fromJSON val of
                      Success (event :: Event) -> writeTChan queue event
                      _ -> return ()

	  -- use fake context to get values for real context
	  let cxt0 = DeviceContext eng queue 300 300 1 locals False
	  DeviceAttributes w h dpr <- send cxt0 device

	  -- Build the actual context
	  let cxt1 = cxt0
                { ctx_width = w
                , ctx_height = h
                , ctx_devicePixelRatio = dpr
                , weakRemoteMonad = weak opts
                }

          (actions $ cxt1) `catch` \ (e :: SomeException) -> do
               print ("Exception in blank-canvas application:" :: String)
               print e
               throw e

	  -- and we're done
	  return ()

        get "/"                 $ file $ dataDir ++ "/static/index.html"
        get "/jquery.js"        $ file $ dataDir ++ "/static/jquery.js"
        get "/jquery-json.js"   $ file $ dataDir ++ "/static/jquery-json.js"

        -- There has to be a better way of doing this, using function, perhaps?
        get (Scotty.regex "^/(.*)$") $ do
          fileName :: Text <- Scotty.param "1"
          db <- liftIO $ atomically $ readTVar $ locals
          if fileName `S.member` db
          then do
            let mime = mimeType fileName
            Scotty.setHeader "Content-Type" $ mime
            file $ (root opts ++ "/" ++ T.unpack fileName)
          else do
            Scotty.next

        return ()

   runSettings (setPort (port opts)
               $ setTimeout 100
               $ defaultSettings
               ) app

{-
generalSend :: forall m a . RunMonad m
            => (DeviceContext -> m Prim :~> IO) -> DeviceContext -> Canvas a -> IO a
generalSend f cxt (Canvas c) = do
   error "generalSend"
    -- XXX: Is it ok to hardcode 0 as the start value here?
    -- AJG: No, its not.
   let m0 :: RemoteMonad Prim a
       m0 = evalStateT (runReaderT c (deviceCanvasContext cxt)) 0
   runMonad (f cxt) N.# m0
-}

{-
sendS :: DeviceContext -> Canvas a -> IO a
sendS = generalSend (\cxt -> wrapNT (sendS' cxt))
-}

--sendW :: DeviceContext -> Canvas a -> IO a
--sendW = generalSend (\cxt -> wrapNT (sendW' cxt))

{-
sendS' :: DeviceContext -> SP.StrongPacket Cmd Proc a -> IO a
sendS' cxt sp = evalStateT (go sp) mempty
  where
    go :: SP.StrongPacket Cmd Proc a -> StateT Instr IO a
    go (SP.Command cmd rest) = do
      case cmd of
        Method m canvasCxt -> modify (<> jsCanvasContext canvasCxt <> singleton '.' <> showi m <> singleton ';')
        Canvas.Command _c _ -> modify (<> showi cmd <> singleton ';')
        MethodAudio    _a _ -> modify (<> showi cmd <> singleton ';')
        PseudoProcedure f r c     -> sendFunc f r c
      go rest

    go (SP.Procedure p) =
      case p of
        Query    q c -> sendQuery q c

    go SP.Done = do
      cmds <- State.get
      liftIO $ sendToCanvas cxt cmds
      State.put mempty
      return ()

    sendFunc :: PseudoProcedure a -> a -> CanvasContext -> StateT Instr IO ()
    sendFunc q@(CreateLinearGradient _) r c = sendGradient q r c
    sendFunc q@(CreateRadialGradient _) r c = sendGradient q r c
    sendFunc q@(CreatePattern        _) r c = sendPattern  q r c

    fileQuery :: Text -> IO ()
    fileQuery url = do
        let url' = if "/" `T.isPrefixOf` url then T.tail url else url
        atomically $ do
            db <- readTVar (localFiles cxt)
            writeTVar (localFiles cxt) $ S.insert url' $ db

    -- TODO: See if the query should be added to the end and then
    -- everything sent over in one transmission.
    sendQuery :: Query a -> CanvasContext -> StateT Instr IO a
    sendQuery query c = do
        -- Grab waiting commands and clear the command queue
      prevCmds <- State.get
      State.put mempty

        -- Send actual query
      liftIO $ do
        case query of
          NewImage url -> fileQuery url
          NewAudio url -> fileQuery url
          _            -> return ()

        -- send the com
        uq <- atomically getUniq
        -- The query function returns a function takes the unique port number of the reply.
        sendToCanvas cxt $ prevCmds <> showi query <> singleton '(' <> showi uq <> singleton ',' <> jsCanvasContext c <> ");"
        v <- KC.getReply (theComet cxt) uq
        case parse (parseQueryResult query) v of
          Error msg -> fail msg
          Success a -> return a

    sendGradient :: PseudoProcedure CanvasGradient -> CanvasGradient -> CanvasContext -> StateT Instr IO ()
    sendGradient q (CanvasGradient gId) c = do
      modify (<> "var gradient_"
          <> showi gId     <> " = "   <> jsCanvasContext c
          <> singleton '.' <> showi q <> singleton ';')

    sendPattern :: PseudoProcedure CanvasPattern -> CanvasPattern -> CanvasContext -> StateT Instr IO ()
    sendPattern q (CanvasPattern pId) c = do
      modify (<> "var pattern_"
          <> showi pId     <> " = "   <> jsCanvasContext c
          <> singleton '.' <> showi q <> singleton ';')
-}
{-
sendW' :: DeviceContext -> WP.WeakPacket Prim a -> IO a
sendW' cxt = go mempty
  where
    go :: Instr -> WP.WeakPacket Prim a -> IO a
    go cmds (WP.Primitive p) =
      case knownResult p of
        Just _ ->
          case p of
            Method m canvasCxt -> send' (cmds <> jsCanvasContext canvasCxt <> singleton '.' <> showi m <> singleton ';')
            Canvas.Command _c _ -> send' (cmds <> showi p <> singleton ';')
            MethodAudio _a    _ -> send' (cmds <> showi p <> singleton ';')
            PseudoProcedure f r c -> sendFunc cmds f r c
            _                    -> error "sendW': unsupported Command or Procedure was treated as Command"
        Nothing ->
          case p of
            Query q c -> sendQuery cmds q c
            _         -> error "sendW': Unsupported Procedure or a Command was treated as a Procedure"

    send' :: Instr -> IO ()
    send' = sendToCanvas cxt

    sendFunc :: Instr -> PseudoProcedure a -> a -> CanvasContext -> IO ()
    sendFunc cmds q@(CreateLinearGradient _) r c = sendGradient cmds q r c
    sendFunc cmds q@(CreateRadialGradient _) r c = sendGradient cmds q r c
    sendFunc cmds q@(CreatePattern        _) r c = sendPattern  cmds q r c

    fileQuery :: Text -> IO ()
    fileQuery url = do
        let url' = if "/" `T.isPrefixOf` url then T.tail url else url
        atomically $ do
            db <- readTVar (localFiles cxt)
            writeTVar (localFiles cxt) $ S.insert url' $ db

    sendQuery :: Instr -> Query a -> CanvasContext -> IO a
    sendQuery cmds query c = do
      case query of
        NewImage url -> fileQuery url
        NewAudio url -> fileQuery url
        -- TODO: See if this is possible:
        -- Frame        -> error "Frame not yet implemented for weak send"
        _            -> return ()

      -- send the com
      uq <- atomically getUniq
      -- The query function returns a function takes the unique port number of the reply.
      send' $ cmds <> showi query <> singleton '(' <> showi uq <> singleton ',' <> jsCanvasContext c <> ");"
      v <- KC.getReply (theComet cxt) uq
      case parse (parseQueryResult query) v of
        Error msg -> fail msg
        Success a -> return a

    sendGradient :: Instr -> PseudoProcedure CanvasGradient -> CanvasGradient -> CanvasContext -> IO ()
    sendGradient cmds q (CanvasGradient gId) c = do
      send' $ cmds <> "var gradient_"
          <> showi gId     <> " = "   <> jsCanvasContext c
          <> singleton '.' <> showi q <> singleton ';'

    sendPattern :: Instr -> PseudoProcedure CanvasPattern -> CanvasPattern -> CanvasContext -> IO ()
    sendPattern cmds q (CanvasPattern pId) c = do
      send' $ cmds <> "var pattern_"
          <> showi pId     <> " = "   <> jsCanvasContext c
          <> singleton '.' <> showi q <> singleton ';'
-}

-- | Sends a set of canvas commands to the 'Canvas'. Attempts
-- to common up as many commands as possible. Should not crash.
send :: forall a . DeviceContext -> Canvas a -> IO a
send cxt (Canvas cm) = do
  let m0 :: JS.RemoteMonad a
      m0 = cm (deviceCanvasContext cxt)
  JS.send (theComet cxt) m0

-- | make a static file available to Canvas, via a custom URL.
--
-- >  url <- staticURL cxt "image/png" "image/foo.png"
--
staticURL :: DeviceContext -> ST.Text -> FilePath -> IO URL
staticURL _ txt path = readDataURL txt path

local_only :: Middleware
local_only = Local.local $ responseLBS H.status403 [("Content-Type", "text/plain")] "local access only"

{-# NOINLINE uniqVar #-}
uniqVar :: TVar Int
uniqVar = unsafePerformIO $ newTVarIO 0

getUniq :: STM Int
getUniq = do
    u <- readTVar uniqVar
    writeTVar uniqVar (u + 1)
    return u

mimeType :: Text -> Text
mimeType filePath = LT.fromStrict $ go $ fileNameExtensions $ LT.toStrict filePath
  where
    go [] = error $ "do not understand mime type for : " ++ show filePath
    go (e:es) = case M.lookup e defaultMimeMap of
                     Nothing -> go es
                     Just mt -> decodeUtf8 mt

-------------------------------------------------

-- | Additional @blank-canvas@ settings. The defaults can be used by creating
-- 'Options' as a 'Num'. For example, @'blankCanvas' 3000@ uses the default 'Options'
-- on port 3000.
data Options = Options
        { port       :: Int              -- ^ On which port do we issue @blank-canvas@?
        , events     :: [EventName]      -- ^ To which events does the canvas listen? Default: @[]@
        , debug      :: Bool             -- ^ Turn on debugging. Default: @False@
        , root       :: String           -- ^ Location of the static files. Default: @\".\"@
        , middleware :: [Middleware] -- ^ Extra middleware(s) to be executed. Default: @['local_only']@
        , weak       :: Bool         -- ^ use a weak monad, which may help debugging (default False)
        }

instance Num Options where
    (+) = error "no arithmetic for Blank Canvas Options"
    (-) = error "no arithmetic for Blank Canvas Options"
    (*) = error "no arithmetic for Blank Canvas Options"
    abs = error "no arithmetic for Blank Canvas Options"
    signum = error "no arithmetic for Blank Canvas Options"
    fromInteger n = Options { port = fromInteger n
                            , events = []
                            , debug = False
                            , root = "."
                            , middleware = [local_only]
                            , weak = False
                            }

-------------------------------------------------
-- These are monomorphic versions of functions defined to curb type ambiguity errors.

-- | Sets the color used to fill a drawing (@\"black\"@ by default).
--
-- ==== __Examples__
--
-- @
-- 'fillStyle' \"red\"
-- 'fillStyle' \"#00FF00\"
-- @
fillStyle :: ST.Text -> Canvas ()
fillStyle = Generated.fillStyle . LT.fromStrict

-- | Sets the text context's font properties.
--
-- ==== __Examples__
--
-- @
-- 'font' \"40pt \'Gill Sans Extrabold\'\"
-- 'font' \"80% sans-serif\"
-- 'font' \"bold italic large serif\"
-- @
font :: ST.Text -> Canvas ()
font = Generated.font . LT.fromStrict

-- | Sets the color used for strokes (@\"black\"@ by default).
--
-- ==== __Examples__
--
-- @
-- 'strokeStyle' \"red\"
-- 'strokeStyle' \"#00FF00\"
-- @
strokeStyle :: ST.Text -> Canvas ()
strokeStyle = Generated.strokeStyle . LT.fromStrict

-- | Sets the color used for shadows.
--
-- ==== __Examples__
--
-- @
-- 'shadowColor' \"red\"
-- 'shadowColor' \"#00FF00\"
-- @
shadowColor :: ST.Text -> Canvas ()
shadowColor = Generated.shadowColor . LT.fromStrict

-- | Adds a color and stop position in a 'CanvasGradient'. A stop position is a
-- number between 0.0 and 1.0 that represents the position between start and stop
-- in a gradient.
--
-- ==== __Example__
--
-- @
-- grd <- 'createLinearGradient'(0, 0, 10, 10)
-- grd # 'addColorStop'(0, \"red\")
-- @
addColorStop :: (Interval, ST.Text) -> CanvasGradient -> Canvas ()
addColorStop (i, t) = Canvas.addColorStop (i, LT.fromStrict t)

-- | Change the canvas cursor to the specified URL or keyword.
--
-- ==== __Examples__
--
-- @
-- cursor \"url(image.png), default\"
-- cursor \"crosshair\"
-- @
cursor :: ST.Text -> Canvas ()
cursor = Generated.cursor . LT.fromStrict

-- | The height of an 'Image' in pixels.
height :: (Image image, Num a) => image -> a
height = JavaScript.height

-- | The width of an 'Image' in pixels.
width :: (Image image, Num a) => image -> a
width = JavaScript.width
{-
-- | The total length of the audio file in seconds.
durationAudio :: (Audio a, Fractional b) => a -> b
durationAudio = JavaScript.durationAudio

-- | Returns the index of the given Audio in the array of Audio's in the javascript
indexAudio :: Audio a => a -> Int
indexAudio = JavaScript.indexAudio

-}


text:
/* <![CDATA[ */

settings = {
	// cifras significativas
	cs: 5,
	// Interfaz de Usuario ordenada en Tabs
	tabs: true,
	tab_selected: 1,
	// Cada prueba dentro de un Accordion
	accordion: true
}

// NO TOCAR DE ACA EN ADELANTE
$(document).ready(function() {

	window.settings = settings;

});

/* ]]> */


text:
using System.Collections.Generic;
using System.Fabric;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using BookFast.ServiceFabric;

namespace BookFast.Facility
{
    internal sealed class FacilityService : StatelessService
    {
        public FacilityService(StatelessServiceContext context)
            : base(context)
        { }

        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() =>
            new ServiceInstanceListener[]
            {
                ServiceInstanceListenerFactory.CreateInternalListener(typeof(Startup), (serviceContext, message) => ServiceEventSource.Current.ServiceMessage(serviceContext, message))
            };
    }
}


text:
package org.sakaiproject.component.app.messageforums.exception;

public class AccessDeniedException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public AccessDeniedException() {
        super("Generic Message & Forums Access Denied Exception");
    }

    public AccessDeniedException(String message) {
        super(message);
    }

    public AccessDeniedException(String message, Throwable t) {
        super(message, t);
    }

    public AccessDeniedException(Throwable t) {
        super(t);
    }

}


text:
/*!
 * inferno-component v0.7.23
 * (c) 2016 Dominic Gannaway
 * Released under the MIT License.
 */
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global.InfernoComponent = factory());
}(this, function () { 'use strict';

	var NO_RENDER = 'NO_RENDER';

	// Runs only once in applications lifetime
	var isBrowser = typeof window !== 'undefined' && window.document;

	function isNullOrUndefined(obj) {
		return isUndefined(obj) || isNull(obj);
	}

	function isNull(obj) {
		return obj === null;
	}

	function isUndefined(obj) {
		return obj === undefined;
	}

	function VPlaceholder() {
		this.placeholder = true;
		this.dom = null;
	}

	function createVPlaceholder() {
		return new VPlaceholder();
	}

	var documetBody = isBrowser ? document.body : null;

	function constructDefaults(string, object, value) {
		/* eslint no-return-assign: 0 */
		string.split(',').forEach(function (i) { return object[i] = value; });
	}

	var xlinkNS = 'http://www.w3.org/1999/xlink';
	var xmlNS = 'http://www.w3.org/XML/1998/namespace';
	var strictProps = {};
	var booleanProps = {};
	var namespaces = {};
	var isUnitlessNumber = {};

	constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
	constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
	constructDefaults('volume,value', strictProps, true);
	constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
	constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);

	var screenWidth = isBrowser && window.screen.width;
	var screenHeight = isBrowser && window.screen.height;
	var scrollX = 0;
	var scrollY = 0;
	var lastScrollTime = 0;

	if (isBrowser) {
		window.onscroll = function () {
			scrollX = window.scrollX;
			scrollY = window.scrollY;
			lastScrollTime = performance.now();
		};

		window.resize = function () {
			scrollX = window.scrollX;
			scrollY = window.scrollY;
			screenWidth = window.screen.width;
			screenHeight = window.screen.height;
			lastScrollTime = performance.now();
		};
	}

	function Lifecycle() {
		this._listeners = [];
		this.scrollX = null;
		this.scrollY = null;
		this.screenHeight = screenHeight;
		this.screenWidth = screenWidth;
	}

	Lifecycle.prototype = {
		refresh: function refresh() {
			this.scrollX = isBrowser && window.scrollX;
			this.scrollY = isBrowser && window.scrollY;
		},
		addListener: function addListener(callback) {
			this._listeners.push(callback);
		},
		trigger: function trigger() {
			var this$1 = this;

			for (var i = 0; i < this._listeners.length; i++) {
				this$1._listeners[i]();
			}
		}
	};

	var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';

	// Copy of the util from dom/util, otherwise it makes massive bundles
	function getActiveNode() {
		return document.activeElement;
	}

	// Copy of the util from dom/util, otherwise it makes massive bundles
	function resetActiveNode(activeNode) {
		if (activeNode !== document.body && document.activeElement !== activeNode) {
			activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
		}
	}

	function queueStateChanges(component, newState, callback) {
		for (var stateKey in newState) {
			component._pendingState[stateKey] = newState[stateKey];
		}
		if (!component._pendingSetState) {
			component._pendingSetState = true;
			applyState(component, false, callback);
		} else {
			component.state = Object.assign({}, component.state, component._pendingState);
			component._pendingState = {};
		}
	}

	function applyState(component, force, callback) {
		if ((!component._deferSetState || force) && !component._blockRender) {
			component._pendingSetState = false;
			var pendingState = component._pendingState;
			var prevState = component.state;
			var nextState = Object.assign({}, prevState, pendingState);
			var props = component.props;

			component._pendingState = {};
			var nextNode = component._updateComponent(prevState, nextState, props, props, force);

			if (nextNode === NO_RENDER) {
				nextNode = component._lastNode;
			} else if (isNullOrUndefined(nextNode)) {
				nextNode = createVPlaceholder();
			}
			var lastNode = component._lastNode;
			var parentDom = lastNode.dom.parentNode;
			var activeNode = getActiveNode();
			var subLifecycle = new Lifecycle();

			component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
			component._lastNode = nextNode;
			component._componentToDOMNodeMap.set(component, nextNode.dom);
			component._parentNode.dom = nextNode.dom;
			component.componentDidUpdate(props, prevState);
			subLifecycle.trigger();
			if (!isNullOrUndefined(callback)) {
				callback();
			}
			resetActiveNode(activeNode);
		}
	}

	var Component = function Component(props, context) {
		if ( context === void 0 ) context = {};

		/** @type {object} */
		this.props = props || {};

		/** @type {object} */
		this.state = {};

		/** @type {object} */
		this.refs = {};
		this._blockRender = false;
		this._blockSetState = false;
		this._deferSetState = false;
		this._pendingSetState = false;
		this._pendingState = {};
		this._parentNode = null;
		this._lastNode = null;
		this._unmounted = true;
		this.context = context;
		this._patch = null;
		this._parentComponent = null;
		this._componentToDOMNodeMap = null;
	};

	Component.prototype.render = function render () {
	};

	Component.prototype.forceUpdate = function forceUpdate (callback) {
		if (this._unmounted) {
			throw Error(noOp);
		}
		applyState(this, true, callback);
	};

	Component.prototype.setState = function setState (newState, callback) {
		if (this._unmounted) {
			throw Error(noOp);
		}
		if (this._blockSetState === false) {
			queueStateChanges(this, newState, callback);
		} else {
			throw Error('Inferno Warning: Cannot update state via setState() in componentWillUpdate()');
		}
	};

	Component.prototype.componentDidMount = function componentDidMount () {
	};

	Component.prototype.componentWillMount = function componentWillMount () {
	};

	Component.prototype.componentWillUnmount = function componentWillUnmount () {
	};

	Component.prototype.componentDidUpdate = function componentDidUpdate () {
	};

	Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
		return true;
	};

	Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
	};

	Component.prototype.componentWillUpdate = function componentWillUpdate () {
	};

	Component.prototype.getChildContext = function getChildContext () {
	};

	Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
		if (this._unmounted === true) {
			this._unmounted = false;
			return false;
		}
		if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
			nextProps.children = prevProps.children;
		}
		if (prevProps !== nextProps || prevState !== nextState || force) {
			if (prevProps !== nextProps) {
				this._blockRender = true;
				this.componentWillReceiveProps(nextProps);
				this._blockRender = false;
				if (this._pendingSetState) {
					nextState = Object.assign({}, nextState, this._pendingState);
					this._pendingSetState = false;
					this._pendingState = {};
				}
			}
			var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);

			if (shouldUpdate !== false || force) {
				this._blockSetState = true;
				this.componentWillUpdate(nextProps, nextState);
				this._blockSetState = false;
				this.props = nextProps;
				this.state = nextState;
				return this.render();
			}
		}
		return NO_RENDER;
	};

	return Component;

}));


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="black">#000000</color>
    <color name="red">#E0072B</color>
    <color name="blue">#0715E0</color>
    <color name="grey">#ABABB0</color>
</resources>


text:
package org.optaplanner.core.config.constructionheuristic;

import java.util.List;
import java.util.function.Consumer;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;

import org.optaplanner.core.config.constructionheuristic.decider.forager.ConstructionHeuristicForagerConfig;
import org.optaplanner.core.config.constructionheuristic.placer.EntityPlacerConfig;
import org.optaplanner.core.config.constructionheuristic.placer.PooledEntityPlacerConfig;
import org.optaplanner.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig;
import org.optaplanner.core.config.constructionheuristic.placer.QueuedValuePlacerConfig;
import org.optaplanner.core.config.heuristic.selector.entity.EntitySorterManner;
import org.optaplanner.core.config.heuristic.selector.move.MoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig;
import org.optaplanner.core.config.heuristic.selector.move.factory.MoveListFactoryConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.value.ValueSorterManner;
import org.optaplanner.core.config.phase.PhaseConfig;
import org.optaplanner.core.config.util.ConfigUtils;

@XmlType(propOrder = {
        "constructionHeuristicType",
        "entitySorterManner",
        "valueSorterManner",
        "entityPlacerConfig",
        "moveSelectorConfigList",
        "foragerConfig"
})
public class ConstructionHeuristicPhaseConfig extends PhaseConfig<ConstructionHeuristicPhaseConfig> {

    public static final String XML_ELEMENT_NAME = "constructionHeuristic";

    // Warning: all fields are null (and not defaulted) because they can be inherited
    // and also because the input config file should match the output config file

    protected ConstructionHeuristicType constructionHeuristicType = null;
    protected EntitySorterManner entitySorterManner = null;
    protected ValueSorterManner valueSorterManner = null;

    @XmlElements({
            @XmlElement(name = "queuedEntityPlacer", type = QueuedEntityPlacerConfig.class),
            @XmlElement(name = "queuedValuePlacer", type = QueuedValuePlacerConfig.class),
            @XmlElement(name = "pooledEntityPlacer", type = PooledEntityPlacerConfig.class)
    })
    protected EntityPlacerConfig entityPlacerConfig = null;

    /** Simpler alternative for {@link #entityPlacerConfig}. */
    @XmlElements({
            @XmlElement(name = CartesianProductMoveSelectorConfig.XML_ELEMENT_NAME,
                    type = CartesianProductMoveSelectorConfig.class),
            @XmlElement(name = ChangeMoveSelectorConfig.XML_ELEMENT_NAME, type = ChangeMoveSelectorConfig.class),
            @XmlElement(name = MoveIteratorFactoryConfig.XML_ELEMENT_NAME, type = MoveIteratorFactoryConfig.class),
            @XmlElement(name = MoveListFactoryConfig.XML_ELEMENT_NAME, type = MoveListFactoryConfig.class),
            @XmlElement(name = PillarChangeMoveSelectorConfig.XML_ELEMENT_NAME,
                    type = PillarChangeMoveSelectorConfig.class),
            @XmlElement(name = PillarSwapMoveSelectorConfig.XML_ELEMENT_NAME, type = PillarSwapMoveSelectorConfig.class),
            @XmlElement(name = SubChainChangeMoveSelectorConfig.XML_ELEMENT_NAME,
                    type = SubChainChangeMoveSelectorConfig.class),
            @XmlElement(name = SubChainSwapMoveSelectorConfig.XML_ELEMENT_NAME,
                    type = SubChainSwapMoveSelectorConfig.class),
            @XmlElement(name = SwapMoveSelectorConfig.XML_ELEMENT_NAME, type = SwapMoveSelectorConfig.class),
            @XmlElement(name = TailChainSwapMoveSelectorConfig.XML_ELEMENT_NAME,
                    type = TailChainSwapMoveSelectorConfig.class),
            @XmlElement(name = UnionMoveSelectorConfig.XML_ELEMENT_NAME, type = UnionMoveSelectorConfig.class)
    })
    protected List<MoveSelectorConfig> moveSelectorConfigList = null;

    @XmlElement(name = "forager")
    protected ConstructionHeuristicForagerConfig foragerConfig = null;

    // ************************************************************************
    // Constructors and simple getters/setters
    // ************************************************************************

    public ConstructionHeuristicType getConstructionHeuristicType() {
        return constructionHeuristicType;
    }

    public void setConstructionHeuristicType(ConstructionHeuristicType constructionHeuristicType) {
        this.constructionHeuristicType = constructionHeuristicType;
    }

    public EntitySorterManner getEntitySorterManner() {
        return entitySorterManner;
    }

    public void setEntitySorterManner(EntitySorterManner entitySorterManner) {
        this.entitySorterManner = entitySorterManner;
    }

    public ValueSorterManner getValueSorterManner() {
        return valueSorterManner;
    }

    public void setValueSorterManner(ValueSorterManner valueSorterManner) {
        this.valueSorterManner = valueSorterManner;
    }

    public EntityPlacerConfig getEntityPlacerConfig() {
        return entityPlacerConfig;
    }

    public void setEntityPlacerConfig(EntityPlacerConfig entityPlacerConfig) {
        this.entityPlacerConfig = entityPlacerConfig;
    }

    public List<MoveSelectorConfig> getMoveSelectorConfigList() {
        return moveSelectorConfigList;
    }

    public void setMoveSelectorConfigList(List<MoveSelectorConfig> moveSelectorConfigList) {
        this.moveSelectorConfigList = moveSelectorConfigList;
    }

    public ConstructionHeuristicForagerConfig getForagerConfig() {
        return foragerConfig;
    }

    public void setForagerConfig(ConstructionHeuristicForagerConfig foragerConfig) {
        this.foragerConfig = foragerConfig;
    }

    // ************************************************************************
    // With methods
    // ************************************************************************

    public ConstructionHeuristicPhaseConfig withConstructionHeuristicType(
            ConstructionHeuristicType constructionHeuristicType) {
        this.constructionHeuristicType = constructionHeuristicType;
        return this;
    }

    public ConstructionHeuristicPhaseConfig withEntitySorterManner(EntitySorterManner entitySorterManner) {
        this.entitySorterManner = entitySorterManner;
        return this;
    }

    public ConstructionHeuristicPhaseConfig withValueSorterManner(ValueSorterManner valueSorterManner) {
        this.valueSorterManner = valueSorterManner;
        return this;
    }

    public ConstructionHeuristicPhaseConfig withEntityPlacerConfig(EntityPlacerConfig<?> entityPlacerConfig) {
        this.entityPlacerConfig = entityPlacerConfig;
        return this;
    }

    public ConstructionHeuristicPhaseConfig withMoveSelectorConfigList(List<MoveSelectorConfig> moveSelectorConfigList) {
        this.moveSelectorConfigList = moveSelectorConfigList;
        return this;
    }

    public ConstructionHeuristicPhaseConfig withForagerConfig(ConstructionHeuristicForagerConfig foragerConfig) {
        this.foragerConfig = foragerConfig;
        return this;
    }

    @Override
    public ConstructionHeuristicPhaseConfig inherit(ConstructionHeuristicPhaseConfig inheritedConfig) {
        super.inherit(inheritedConfig);
        constructionHeuristicType = ConfigUtils.inheritOverwritableProperty(constructionHeuristicType,
                inheritedConfig.getConstructionHeuristicType());
        entitySorterManner = ConfigUtils.inheritOverwritableProperty(entitySorterManner,
                inheritedConfig.getEntitySorterManner());
        valueSorterManner = ConfigUtils.inheritOverwritableProperty(valueSorterManner,
                inheritedConfig.getValueSorterManner());
        setEntityPlacerConfig(ConfigUtils.inheritOverwritableProperty(
                getEntityPlacerConfig(), inheritedConfig.getEntityPlacerConfig()));
        moveSelectorConfigList = ConfigUtils.inheritMergeableListConfig(
                moveSelectorConfigList, inheritedConfig.getMoveSelectorConfigList());
        foragerConfig = ConfigUtils.inheritConfig(foragerConfig, inheritedConfig.getForagerConfig());
        return this;
    }

    @Override
    public ConstructionHeuristicPhaseConfig copyConfig() {
        return new ConstructionHeuristicPhaseConfig().inherit(this);
    }

    @Override
    public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
        if (getTerminationConfig() != null) {
            getTerminationConfig().visitReferencedClasses(classVisitor);
        }
        if (entityPlacerConfig != null) {
            entityPlacerConfig.visitReferencedClasses(classVisitor);
        }
        if (moveSelectorConfigList != null) {
            moveSelectorConfigList.forEach(ms -> ms.visitReferencedClasses(classVisitor));
        }
        if (foragerConfig != null) {
            foragerConfig.visitReferencedClasses(classVisitor);
        }
    }

}


text:
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import Button from '../Button';
import { iconArrowLeft, iconArrowRight } from '@wfp/icons';
import settings from '../../globals/js/settings';
const { prefix } = settings;

export default class FormControls extends React.Component {
  static propTypes = {
    /**
     * Specify the text to be read by screen-readers when visiting the <Tabs>
     * component
     */
    className: PropTypes.string,
    onNextClick: PropTypes.func,
    nextDisabled: PropTypes.bool,
    nextIcon: PropTypes.object,
    nextHidden: PropTypes.bool,
    nextText: PropTypes.node,
    onPreviousClick: PropTypes.func,
    previousDisabled: PropTypes.bool,
    previousIcon: PropTypes.object,
    previousHidden: PropTypes.bool,
    previousText: PropTypes.node,
    onSubmitClick: PropTypes.func,
    submitDisabled: PropTypes.bool,
    submitIcon: PropTypes.object,
    submitHidden: PropTypes.bool,
    submitText: PropTypes.node,
  };

  static defaultProps = {
    nextIcon: iconArrowRight,
    nextText: 'Next',
    previousIcon: iconArrowLeft,
    previousText: 'Previous',
    submitText: 'Submit',
  };

  render() {
    const {
      className,
      onNextClick,
      nextDisabled,
      nextIcon,
      nextHidden,
      nextText,
      onPreviousClick,
      previousDisabled,
      previousIcon,
      previousHidden,
      previousText,
      onSubmitClick,
      submitDisabled,
      submitIcon,
      submitHidden,
      submitText,
    } = this.props;

    const formControlsClasses = classNames(
      `${prefix}--form-controls`,
      className
    );

    return (

        <div className={`${prefix}--form-controls__steps`}>
          {!previousHidden && (
            <Button
              disabled={previousDisabled}
              kind="secondary"
              className={`${prefix}--form-controls__prev`}
              icon={previousIcon}
              onClick={onPreviousClick}
            >
              {previousText}
            </Button>
          )}

          {!nextHidden && (
            <Button
              disabled={nextDisabled}
              kind="secondary"
              className={`${prefix}--form-controls__next`}
              icon={nextIcon}
              type="submit"
              onClick={onNextClick}
            >
              {nextText}
            </Button>
          )}
          {!submitHidden && (
            <Button
              disabled={submitDisabled}
              type="submit"
              className="next"
              icon={submitIcon}
              onClick={onSubmitClick}
            >
              {submitText}
            </Button>
          )}

    );
  }
}


text:
This is a python web application working with a Database as a Back-End.
Which is provide a Front-End interface make users make there own catalog with items inside it too.

All person will allowed to browse all catalog and items, and he/she can make their own Catalog and share them among Catalog Item App community.

## File Structure

I organized the project with considerations based on trustful functionality.

```
	templates			(application html files)
	app.py				(application start file)
	database_setup.py	(Database Setup)
```
## Database Structure

```SQL

-- Authentication table

CREATE TABLE person (
	id INTEGER NOT NULL,
	name VARCHAR(250) NOT NULL,
	email VARCHAR(250) NOT NULL,
	password VARCHAR(250) NOT NULL,
	created_at DATETIME,
	PRIMARY KEY (id)
)

-- Catalog table

CREATE TABLE catalog (
	id INTEGER NOT NULL,
	name VARCHAR(250) NOT NULL,
	person_id INTEGER,
	created_at DATETIME,
	PRIMARY KEY (id),
	FOREIGN KEY(person_id) REFERENCES person (id)
)

-- Item Catalog table

CREATE TABLE catalog_item (
	id INTEGER NOT NULL,
	name VARCHAR(80) NOT NULL,
	description VARCHAR(250),
	catalog_id INTEGER,
	person_id INTEGER,
	created_at DATETIME,
	PRIMARY KEY (id),
	FOREIGN KEY(catalog_id) REFERENCES catalog (id),
	FOREIGN KEY(person_id) REFERENCES person (id)
)

```

## Instructions

To Test this application you will need to following those steps:

### Server side

First you need to initialize Database:

```
$ python database_setup.py
```

And Finally, start server by:

```
$ python app.py
```

Then application server will run on port 5000.

### Server side(Vagrant option)
To avoid wrong configuration you can test this system as a Virtual Machine(VM), and I will tell you how in Debian Linux like:

First, install those packages:
```
$ sudo apt-get install virtualbox vagrant
```
Then fire up VM
```
$ vagrant up --provider virtualbox
```
It will take some time to download ubuntu.

Finally, login to your VM and run the app:
```
$ # you should be inside the home folder of the app
$ vagrant ssh
$
$ # Then go to home directory app inside VM:
$ cd /vargant
$
$ # Create database
$ python database_setup.py
$
$ # Finally run application
$ python app.py
```

### Client side

Open your browser with this URL:

```
http://127.0.0.1:5000
```

## Requirements

### Server side

You will need a Python 2.x language installed in your server system with some libraries:

- python-sqlalchemy
- python-flask
- python-requests
- Flask-Login
- oauth2client
- requests

### Client side

To run this Web Application you will need a browser which should be in specific versions that fully supports the JavaScript language, which those browsers and versions are:

- Chrome: 4.0+
- IE(Internet Explorer): 9.0+
- Firefox: 2.0+
- Safari: 3.1+
- Opera: 9.0+

## Licence

It's Completely Free. But, Do whatever you like to do on your own full responsibility;

This licence is known with [MIT License](http://vzool.mit-license.org/) in professional networks.


text:
import datetime
from decimal import Decimal
from typing import Any, Dict

import pytz
from dirtyfields import DirtyFieldsMixin
from django.conf import settings
from django.db import models, transaction
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.forms.models import model_to_dict

def _add_dict_items_if_not_present(
    dict_with_precedence: Dict, dict_to_insert: Dict
) -> Dict:
    for k, v in dict_to_insert.items():
        if k not in dict_with_precedence:
            dict_with_precedence[k] = v
    return dict_with_precedence

class PostSaveActionsMixin(DirtyFieldsMixin):
    """
    If you want to do pre-save signals,
    you can do this so you don't have to use DirtyFieldsMixin:
    http://stackoverflow.com/a/37265149/333294
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.transaction_dirty_fields = {}
        self.new_object = False
        # Create a lambda here so that this function is unique to this object,
        # as required by on_commit_announce_set.
        self.announce_changes_lambda = lambda: self.announce_changes

    def _post_creation_saved(self, *args, **kwargs):
        """
        Implement this with a method to be run when this model is saved for
        the first time - when a new row will be inserted into the database.
        """
        raise NotImplementedError(self._post_creation_saved.__doc__)  # pragma: no cover

    def _post_changes_saved(self, changed_fields, *args, **kwargs):
        """
        Implement this with a method to be run when this model is saved
        and some attributes have changed.
        """
        raise NotImplementedError(self._post_changes_saved.__doc__)  # pragma: no cover

    def _post_no_changes_saved(self, *args, **kwargs):
        """
        Implement this with a method to be run when this model is saved
        but NO attributes have been changed.
        Most of the time you can just `pass`.
        N.B. if foreign keys have data changed, but the FK still points
        to the same FK  (ie, user #2), this method will be called.
        """
        raise NotImplementedError(
            self._post_no_changes_saved.__doc__
        )  # pragma: no cover

    def save(self, *args, **kwargs):
        self.new_object = (
            self.new_object or self.id is None or kwargs.get("force_insert") is True
        )
        self.transaction_dirty_fields = _add_dict_items_if_not_present(
            self.transaction_dirty_fields,
            self.get_dirty_fields(check_relationship=True),
        )
        save_result = super(PostSaveActionsMixin, self).save(*args, **kwargs)

        if not self.on_commit_announce_set():
            transaction.on_commit(self.announce_changes)
        return save_result

    def on_commit_announce_set(self) -> bool:
        return any(
            [
                fun[1] == self.announce_changes_lambda
                for fun in transaction.get_connection().run_on_commit
            ]
        )

    def announce_changes(self):
        if self.new_object:
            self._post_creation_saved()
        elif self.transaction_dirty_fields:
            self._post_changes_saved(self.transaction_dirty_fields)
        else:
            self._post_no_changes_saved()
        self.transaction_dirty_fields = {}
        self.new_object = False


text:
require "parascope/version"

module Parascope
  UndefinedScopeError = Class.new(StandardError)
  GuardViolationError = Class.new(ArgumentError)

  autoload :Query, "parascope/query"

  Query.raise_on_guard_violation true
end


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

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

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

"""

from resource_management.core.logger import Logger
from resource_management.core.exceptions import Fail
from resource_management.core.resources.system import Execute
from resource_management.core import shell
from resource_management.libraries.functions import format
from resource_management.libraries.functions.decorator import retry

def pre_upgrade_shutdown():
  """
  Runs the "shutdownDatanode {ipc_address} upgrade" command to shutdown the
  DataNode in preparation for an upgrade. This will then periodically check
  "getDatanodeInfo" to ensure the DataNode has shutdown correctly.
  This function will obtain the Kerberos ticket if security is enabled.
  :return:
  """
  import params

  Logger.info('DataNode executing "shutdownDatanode" command in preparation for upgrade...')
  if params.security_enabled:
    Execute(params.dn_kinit_cmd, user = params.hdfs_user)

  command = format('hdfs dfsadmin -shutdownDatanode {dfs_dn_ipc_address} upgrade')
  Execute(command, user=params.hdfs_user, tries=1 )

  # verify that the datanode is down
  _check_datanode_shutdown()

def post_upgrade_check():
  """
  Verifies that the DataNode has rejoined the cluster. This function will
  obtain the Kerberos ticket if security is enabled.
  :return:
  """
  import params

  Logger.info("Checking that the DataNode has rejoined the cluster after upgrade...")
  if params.security_enabled:
    Execute(params.dn_kinit_cmd,user = params.hdfs_user)

  # verify that the datanode has started and rejoined the HDFS cluster
  _check_datanode_startup()

@retry(times=12, sleep_time=10, err_class=Fail)
def _check_datanode_shutdown():
  """
  Checks that a DataNode is down by running "hdfs dfsamin getDatanodeInfo"
  several times, pausing in between runs. Once the DataNode stops responding
  this method will return, otherwise it will raise a Fail(...) and retry
  automatically.
  :return:
  """
  import params

  command = format('hdfs dfsadmin -getDatanodeInfo {dfs_dn_ipc_address}')

  try:
    Execute(command, user=params.hdfs_user, tries=1)
  except:
    Logger.info("DataNode has successfully shutdown for upgrade.")
    return

  Logger.info("DataNode has not shutdown.")
  raise Fail('DataNode has not shutdown.')

@retry(times=12, sleep_time=10, err_class=Fail)
def _check_datanode_startup():
  """
  Checks that a DataNode is reported as being alive via the
  "hdfs dfsadmin -report -live" command. Once the DataNode is found to be
  alive this method will return, otherwise it will raise a Fail(...) and retry
  automatically.
  :return:
  """
  import params

  try:
    # 'su - hdfs -c "hdfs dfsadmin -report -live"'
    command = 'hdfs dfsadmin -report -live'
    return_code, hdfs_output = shell.call(command, user=params.hdfs_user)
  except:
    raise Fail('Unable to determine if the DataNode has started after upgrade.')

  if return_code == 0:
    if params.hostname.lower() in hdfs_output.lower():
      Logger.info("DataNode {0} reports that it has rejoined the cluster.".format(params.hostname))
      return
    else:
      raise Fail("DataNode {0} was not found in the list of live DataNodes".format(params.hostname))

  # return_code is not 0, fail
  raise Fail("Unable to determine if the DataNode has started after upgrade (result code {0})".format(str(return_code)))


text:
swoole_socket_coro: writev with eagain
--SKIPIF--
<?php require __DIR__ . '/../include/skipif.inc'; ?>
--FILE--
<?php

use Swoole\Coroutine;
use Swoole\Coroutine\Socket;

use function Swoole\Coroutine\run;

require __DIR__ . '/../include/bootstrap.php';

$totalLength = 0;
$iovector = [];
$packedStr = '';

for ($i = 0; $i < 10; $i++) {
    $iovector[$i] = str_repeat(get_safe_random(1024), 128);
    $totalLength += strlen($iovector[$i]);
    $packedStr .= $iovector[$i];
}

run(function () {
    $server = new Socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    $port = get_one_free_port();

    go(function () use ($server, $port) {
        Assert::assert($server->bind('127.0.0.1', $port));
        Assert::assert($server->listen(512));
        $conn = $server->accept();
        Assert::assert($conn instanceof  Socket);
        Assert::assert($conn->fd > 0);

        global $totalLength, $packedStr;
        Assert::assert($conn instanceof Socket);

        // Let writeVectorAll trigger EAGAIN (verify the correctness of the error returned by writeVectorAll)
        Coroutine::sleep(0.5);
        Assert::eq($conn->recvAll($totalLength), $packedStr);
    });

    go(function () use ($server, $port) {
        global $iovector, $totalLength;

        $conn = new Socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
        Assert::assert($conn->connect('127.0.0.1', $port));
        $ret = $conn->writeVectorAll($iovector);
        Assert::eq($ret, $totalLength);
        $server->close();
    });
});

echo "DONE\n";
?>
--EXPECT--
DONE


text:
package unix

const AT_REMOVEDIR = 0x800
const AT_SYMLINK_NOFOLLOW = 0x200


text:
package rbfs.file;

import java.util.LinkedList;

/**
This class resembles a special type of file which can hold other files/folders
inside (but cannot be opened in the file viewer on its own). Directory
structures made of RBFSFiles and Folders resemble realistic trees with each
folder having a built-in "subfolder" that moves the user up one directory when
opened.

@author	James Hoak
*/

public class RBFSFolder extends RBFSFile {

	private LinkedList<RBFSFile> files;		// The files this folder contains

	/**
	Creates a new Folder with the given metadata.
	@param attrs The file metadata to use for this folder.
	*/
	public RBFSFolder(FileAttributes attrs) {
		super(attrs);
	}

	/**
	Returns the list of Files this folder contains.
	@return The folder's files.
	*/
	public LinkedList<RBFSFile> getFiles() {
		return (LinkedList<RBFSFile>)files.clone();
	}

	/**
	Adds a file to this folder.
	@param file The file to add.
	*/
	public void addFile(RBFSFile file) {
		files.add(file);
		file.setParent(this);
	}

	/**
	Adds a list of files to this folder.
	@param files The files to add.
	*/
	public void addFiles(LinkedList<RBFSFile> files) {
		for (RBFSFile f : files)
			addFile(f);
	}

	/**
	Returns StorageType.FOLDER as this is a Folder, not an individual File.
	@return The enum value StorageType.FOLDER
	*/
	@Override
	public StorageType getStorageType() {
		return StorageType.FOLDER;
	}

	/**
	Constructs a "directory tree" based on the input and returns the root.

	The input String must be formatted as follows, with spaces replaced by \n
	(and with < and >):
		folder Folder1 Author1 64KB 12/1/15 1/1/16 > file F1 Auth 4B 12/1/15 1/2/16 <

	Files are declared one by one in the input String. Each declaration starts
	with the type (folder or file) followed by the file's metadata (name, author,
	size, date created, and date modified). If the type is a folder, this must
	be immediately followed by a >, with zero or more subfiles/subfolders
	declared inside the folder. Then a < character follows, and the folder is
	said to contain all of the files/folders declared within the brackets.

	The top-level declarations (i.e. ones that are NOT made within a folder)
	are used to construct the "root" folder, which is returned upon exiting
	this method.
	@param input The input string to be used in creating the directory.
	@return The root of the newly created virtual directory (not an actual
	directory on the local computer but rather representative of the one
	on the server).
	*/
	public static RBFSFolder makeDirectoryTree(String input) {
		String[] tokens = input.split("\n");
		FileAttributes attrs = new FileAttributes("", "", "", "", "");
		RBFSFolder root = new RBFSFolder(attrs);
		root.addFiles(getFolderContents(tokens, 0, tokens.length - 1));
		root.addParentLinksInTree();
		return root;
	}

	/**
	Using a set of tokens and a range to use (inclusive for the start and end
	points), constructs the contents of a folder with files in the given range
	and returns the contents as a list of RBFSFiles.
	@param tokens The tokens of the input string.
	@param start The start of the range of tokens to use
	@param end The end of the range to use
	@return The list of files and folders defined in the range of tokens.
	@throws IllegalArgumentException If the input string is invalid.
	*/
	private static LinkedList<RBFSFile> getFolderContents(String[] tokens, int start, int end) {
		LinkedList<RBFSFile> contents = new LinkedList<>();
		int index = start;
		// Read declarations until we leave the given range
		while (index <= end) {
			String type = tokens[index],
				   name = tokens[index + 1],
				   auth = tokens[index + 2],
				   size = tokens[index + 3],
				   dateMade = tokens[index + 4],
				   dateModded = tokens[index + 5];
			FileAttributes attrs = new FileAttributes(name, auth, size, dateMade, dateModded);
			index += 6;

			if (type.equals("FOLDER")) {
				/* Parse the rest of the tokens (up until a '<') as the
				contents of a new folder, then make the folder using a
				recursive process and add it to the contents list.   */
				int nextIndex = index;
				RBFSFolder newFolder = new RBFSFolder(attrs);
				int bracketCount = 0;
				while (!tokens[nextIndex].equals("<") || bracketCount != 1) {
					if (tokens[nextIndex].equals("<"))
						bracketCount--;
					else if (tokens[nextIndex].equals(">"))
						bracketCount++;
					nextIndex++;
				}
				// Get the folder contents in the range we found and add them
				// to a new folder
				newFolder.addFiles(getFolderContents(tokens, index + 1, nextIndex - 1));
				contents.add(newFolder);
				index = nextIndex + 1;
			}
			// If we just have a file, then just make the metadata and add the
			// file to the list of contents
			else if (type.equals("FILE")) {
				RBFSFile file = new RBFSFile(attrs);
				contents.add(file);
			}
			else
				throw new IllegalArgumentException("ERROR: Bad input string.");
		}
		return contents;
	}

	/**
	Add subdirectories that link up one directory (so the user can actually
	go back a folder if they go too deep.
	*/
	private void addParentLinksInTree() {
		for (RBFSFile f : files) {
			if (f.getStorageType() == StorageType.FOLDER) {
				RBFSFolder folder = (RBFSFolder)f;

				// Recursively add links for each subfolder
				folder.addParentLinksInTree();
				folder.addParentLink();
			}
		}
	}

	/**
	Adds a subfolder that goes up one directory.
	*/
	private void addParentLink() {
		RBFSFolder parent = getParent();
		String name = parent.getName();

		// First, make the name of the subdirectory obviously a link up the
		// directory (i.e., ".. (parentFolder)").
		String newName;
		if (name.startsWith(".. (") && name.endsWith(")"))
			newName = name;
		else
			newName = ".. (" + name + ")";

		// Make the relevant metadata
		String auth = parent.getAuthor(),
			   size = parent.getSize(),
			   dateMade = parent.getDateMade(),
			   dateModded = parent.getDateModded();
		FileAttributes newAttrs = new FileAttributes(newName, auth, size, dateMade, dateModded);

		// Make the folder with our new metadata, add files to it and add that
		// file to this folder
		RBFSFolder parentLink = new RBFSFolder(newAttrs);
		parentLink.addFiles(parent.getFiles());
		addFile(parentLink);
	}
}


text:
package record

import (
	"go.mau.fi/libsignal/ecc"
	"go.mau.fi/libsignal/keys/identity"
	"go.mau.fi/libsignal/util/bytehelper"
)

// NewPendingKeyExchange will return a new PendingKeyExchange object.
func NewPendingKeyExchange(sequence uint32, localBaseKeyPair, localRatchetKeyPair *ecc.ECKeyPair,
	localIdentityKeyPair *identity.KeyPair) *PendingKeyExchange {

	return &PendingKeyExchange{
		sequence:             sequence,
		localBaseKeyPair:     localBaseKeyPair,
		localRatchetKeyPair:  localRatchetKeyPair,
		localIdentityKeyPair: localIdentityKeyPair,
	}
}

// NewPendingKeyExchangeFromStruct will return a PendingKeyExchange object from
// the given structure. This is used to get a deserialized pending prekey exchange
// fetched from persistent storage.
func NewPendingKeyExchangeFromStruct(structure *PendingKeyExchangeStructure) *PendingKeyExchange {
	// Return nil if no structure was provided.
	if structure == nil {
		return nil
	}

	// Alias the SliceToArray method.
	getArray := bytehelper.SliceToArray

	// Convert the bytes in the given structure to ECC objects.
	localBaseKeyPair := ecc.NewECKeyPair(
		ecc.NewDjbECPublicKey(getArray(structure.LocalBaseKeyPublic)),
		ecc.NewDjbECPrivateKey(getArray(structure.LocalBaseKeyPrivate)),
	)
	localRatchetKeyPair := ecc.NewECKeyPair(
		ecc.NewDjbECPublicKey(getArray(structure.LocalRatchetKeyPublic)),
		ecc.NewDjbECPrivateKey(getArray(structure.LocalRatchetKeyPrivate)),
	)
	localIdentityKeyPair := identity.NewKeyPair(
		identity.NewKey(ecc.NewDjbECPublicKey(getArray(structure.LocalIdentityKeyPublic))),
		ecc.NewDjbECPrivateKey(getArray(structure.LocalIdentityKeyPrivate)),
	)

	// Return the PendingKeyExchange with the deserialized keys.
	return &PendingKeyExchange{
		sequence:             structure.Sequence,
		localBaseKeyPair:     localBaseKeyPair,
		localRatchetKeyPair:  localRatchetKeyPair,
		localIdentityKeyPair: localIdentityKeyPair,
	}
}

// PendingKeyExchangeStructure is a serializable structure for pending
// key exchanges. This structure is used for persistent storage of the
// key exchange state.
type PendingKeyExchangeStructure struct {
	Sequence                uint32
	LocalBaseKeyPublic      []byte
	LocalBaseKeyPrivate     []byte
	LocalRatchetKeyPublic   []byte
	LocalRatchetKeyPrivate  []byte
	LocalIdentityKeyPublic  []byte
	LocalIdentityKeyPrivate []byte
}

// PendingKeyExchange is a structure for storing a pending
// key exchange for a session state.
type PendingKeyExchange struct {
	sequence             uint32
	localBaseKeyPair     *ecc.ECKeyPair
	localRatchetKeyPair  *ecc.ECKeyPair
	localIdentityKeyPair *identity.KeyPair
}

// structre will return a serializable structure of a pending key exchange
// so it can be persistently stored.
func (p *PendingKeyExchange) structure() *PendingKeyExchangeStructure {
	getSlice := bytehelper.ArrayToSlice
	return &PendingKeyExchangeStructure{
		Sequence:                p.sequence,
		LocalBaseKeyPublic:      getSlice(p.localBaseKeyPair.PublicKey().PublicKey()),
		LocalBaseKeyPrivate:     getSlice(p.localBaseKeyPair.PrivateKey().Serialize()),
		LocalRatchetKeyPublic:   getSlice(p.localRatchetKeyPair.PublicKey().PublicKey()),
		LocalRatchetKeyPrivate:  getSlice(p.localRatchetKeyPair.PrivateKey().Serialize()),
		LocalIdentityKeyPublic:  getSlice(p.localIdentityKeyPair.PublicKey().PublicKey().PublicKey()),
		LocalIdentityKeyPrivate: getSlice(p.localIdentityKeyPair.PrivateKey().Serialize()),
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>qesp : QextPortInfo Class Reference</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

Home · All Classes ·

Modules

QextPortInfo

Contents

Detailed Description

QextPortInfo Class Reference

The QextPortInfo class containing port information. More...

    #include <QextPortInfo>

List of all members, including inherited members

Detailed Description

The QextPortInfo class containing port information.

Structure containing port information.

    QString portName;   ///< Port name.
    QString physName;   ///< Physical name.
    QString friendName; ///< Friendly name.
    QString enumName;   ///< Enumerator name.
    int vendorID;       ///< Vendor ID.
    int productID;      ///< Product ID

<address>

Copyright © 2000-2012
QextSerialPort Project

QextSerialPort Manual

</address>


text:
'use strict';

angular.module('mean.ddb').directive('trophyRanking', function () {
    return {
        restrict: 'E',
        scope: {
            trophy: '='
        },
        templateUrl: 'ddb/views/templates/trophy-ranking.html',
        controller: ['$scope', function ($scope) {

        }]
    };
});


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#ifndef TRChartsJNI_Support_ObjectMarshaller_hpp
#define TRChartsJNI_Support_ObjectMarshaller_hpp

#include <TRChartsJNI/Support/Marshaller.hpp>
#include <TRChartsJNI/Support/Handle.hpp>
#include <TRChartsJNI/Support/Utils.hpp>

namespace TRChartsJNI
{
	template <typename T>
	class ObjectMarshaller : public BasicObjectMarshaller<std::shared_ptr<T>, jobject>
	{
	public:
		virtual std::shared_ptr<T> marshall(JNIEnv * env, const jobject & in) const;

		virtual jobject unmarshall(JNIEnv * env, const std::shared_ptr<T> & in) const;
	};

	template <typename T>
	std::shared_ptr<T> ObjectMarshaller<T>::marshall(JNIEnv * const env, const jobject & in) const
	{
		if(in) {
			const Handle * const handle = reinterpret_cast<Handle *>(Utils::getBaseObjectHandle(env, in));
			return handle->getNativeObject<T>(env);
		} else {
			return std::shared_ptr<T>();
		}
	}

	template <typename T>
	jobject ObjectMarshaller<T>::unmarshall(JNIEnv * const env, const std::shared_ptr<T> & in) const
	{
		if(in) {
			const Handle * const handle = static_cast<Handle *>(in->getHandle());
			return handle->getHostObject(env);
		} else {
			return nullptr;
		}
	}
}

#endif


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class jdungeoncrawler.Entity</title>
<meta name="date" content="2016-07-01">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
jdungeoncrawler.Entity

Uses of Entity in jdungeoncrawler

Subclasses of Entity in jdungeoncrawler

Modifier and Type
Class and Description

class
Ally

Ally Entity object.

class
Enemy

Opposing Entity object.

class
Player

Controllable Entity object.

Methods in jdungeoncrawler that return types with arguments of type Entity

Modifier and Type
Method and Description

java.util.ArrayList<Entity>
Sector.getEntities()

Returns the ArrayList of Entities in the Sector.

Methods in jdungeoncrawler with parameters of type Entity

Modifier and Type
Method and Description

void
Sector.addEntity(Entity entity)

Adds an Entity to the Sector (if the ArrayList is no bigger than 10
 elements.

void
Sector.removeEntity(Entity entity)

Remove Entity object from the Sector.

void
XMLHandler.setPlayer(Entity player)

Sets the local Player variable to the Player Entity found by the XML
 Handler.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
module VimColorScheme
  class CommentNode
    # Initializes the comment node with a comment string.
    def initialize comment
      @comment = comment
    end

    # Renders the comment node by splitting the string at newlines and then
    # appending the " comment character at the start of each line and joining
    # the result with newlines.
    def to_s
      @comment.split(/\n/).map { |str| str = '" ' + str }.join("\n") + "\n"
    end
  end
end


text:
package ar.com.quark.mathematic.geometry;

import ar.com.quark.mathematic.MutableVector2f;
import ar.com.quark.mathematic.Vector2f;

/**
 * A representation of a rectangle.
 */
public final class Rectangle {
    private float mX;
    private float mY;
    private float mWidth;
    private float mHeight;

    /**
     *
Constructor from an origin

     *
     * @param width  the width of the rectangle.
     * @param height the height of the rectangle.
     */
    public Rectangle(float width, float height) {
        this(0, 0, width, height);
    }

    /**
     *
Constructor given a position and a size

     *
     * @param position the vector that contains the rectangle position.
     * @param size     the vector that contains the rectangle size.
     */
    public Rectangle(Vector2f position, Vector2f size) {
        this(position.getFloorX(), position.getFloorY(), size.getFloorX(), size.getFloorY());
    }

    /**
     *
Constructor

     *
     * @param x      the x position of the rectangle.
     * @param y      the y position of the rectangle.
     * @param width  the width of the rectangle.
     * @param height the height of the rectangle.
     */
    public Rectangle(float x, float y, float width, float height) {
        mX = x;
        mY = y;
        mWidth = width;
        mHeight = height;
    }

    /**
     *
Change the geometry's dimension

     *
     * @param x      the new x position of the rectangle.
     * @param y      the new y position of the rectangle.
     * @param width  the new width of the rectangle.
     * @param height the new height of the rectangle.
     */
    public void set(float x, float y, float width, float height) {
        mX = x;
        mY = y;
        mWidth = width;
        mHeight = height;
    }

    /**
     *
Get the x position of the rectangle

     *
     * @return the x position of the rectangle
     */
    public float getX() {
        return mX;
    }

    /**
     *
Get the y position of the rectangle

     *
     * @return the y position of the rectangle
     */
    public float getY() {
        return mY;
    }

    /**
     *
Get the width of the rectangle

     *
     * @return the width of the rectangle
     */
    public float getWidth() {
        return mWidth;
    }

    /**
     *
Get the height of the rectangle

     *
     * @return the height of the rectangle
     */
    public float getHeight() {
        return mHeight;
    }

    /**
     *
Get the position of the rectangle

     *
     * @param vector the vector that will contain(s) the position
     *
     * @return the vector
     */
    public MutableVector2f getPosition(MutableVector2f vector) {
        vector.setXY(mX, mY);

        return vector;
    }

    /**
     *
Get the dimension of the rectangle

     *
     * @param vector the vector that will contain(s) the dimension
     *
     * @return the vector
     */
    public MutableVector2f getDimension(MutableVector2f vector) {
        vector.setXY(mWidth, mHeight);

        return vector;
    }

    /**
     *
Get the area of the rectangle

     *
     * @return the area of the rectangle (which is width * height)
     */
    public float getArea() {
        return mWidth * mHeight;
    }

    /**
     *
Get the aspect ratio of the rectangle

     *
     * @return the aspect ratio of the rectangle (which is width / height)
     */
    public float getAspectRatio() {
        return mWidth / mHeight;
    }

    /**
     *
Get the center of the rectangle

     *
     * @param vector the vector that will contain(s) the center
     *
     * @return the vector
     */
    public MutableVector2f getCenter(MutableVector2f vector) {
        vector.setXY(mX + mWidth * 0.5f, mY + mHeight * 0.5f);

        return vector;
    }

    /**
     *
Check if the given rectangle is within this rectangle

     *
     * @param other the other rectangle
     *
     * @return true if the given rectangle is within, false otherwise
     */
    public boolean contain(Rectangle other) {
        return contain(other.mX, other.mY, other.mWidth, other.mHeight);
    }

    /**
     *
Check if the given rectangle is within this rectangle

     *
     * @param x      the x coordinate of the rectangle
     * @param y      the y coordinate of the rectangle
     * @param width  the width of the rectangle
     * @param height the height of the rectangle
     *
     * @return true if the given rectangle is within, false otherwise
     */
    public boolean contain(float x, float y, float width, float height) {
        final float f1 = mX + mWidth;
        final float f2 = x + width;
        final float f3 = mY + mHeight;
        final float f4 = y + height;

        return (x > mX) && (x < f1)
                && (f2 > mX)
                && (f2 < f1)
                && (y > mY)
                && (y < f3)
                && (f4 > mY)
                && (f4 < f3);
    }

    /**
     *
Check if the given point is within this rectangle

     *
     * @param vector a vector that contain(s) the point
     *
     * @return true if the given point is within, false otherwise
     */
    public boolean contain(Vector2f vector) {
        return contain(vector.getX(), vector.getY());
    }

    /**
     *
Check if the given point is within this rectangle

     *
     * @param x the x coordinate of the point
     * @param y the y coordinate of the point
     *
     * @return true if the given point is within, false otherwise
     */
    public boolean contain(float x, float y) {
        return (mX <= x) && (mX + mWidth >= x) && (mY <= y) && (mY + mHeight >= y);
    }

    /**
     *
Check if the given rectangle overlap this rectangle

     *
     * @param other the other rectangle
     *
     * @return true if the given rectangle overlap, false otherwise
     */
    public boolean overlap(Rectangle other) {
        return (mX < other.mX + other.mWidth)
                && (mX + mWidth > other.mX)
                && (mY < other.mY + other.mHeight)
                && (mY + mHeight > other.mY);
    }

    /**
     *
Merge this rectangle with other rectangle

     *
     * @param other the other rectangle
     *
     * @return this rectangle
     */
    public Rectangle merge(Rectangle other) {
        return merge(this, other);
    }

    /**
     *
Merge this rectangle with other rectangle

     *
     * @param destination the destination rectangle
     * @param other       the other rectangle
     *
     * @return destination rectangle
     */
    public Rectangle merge(Rectangle destination, Rectangle other) {
        final float f1 = Math.min(mX, other.mX);
        final float f2 = Math.max(mX + mWidth, other.mX + mWidth);
        final float f3 = Math.min(mY, other.mY);
        final float f4 = Math.max(mY + mHeight, other.mY + mHeight);

        destination.mX = f1;
        destination.mY = f3;
        destination.mWidth = f2 - f1;
        destination.mHeight = f4 - f3;

        return destination;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        int hash = 37;
        hash = 37 * hash + Float.floatToIntBits(mX);
        hash = 37 * hash + Float.floatToIntBits(mY);
        hash = 37 * hash + Float.floatToIntBits(mWidth);
        hash = 37 * hash + Float.floatToIntBits(mHeight);
        return hash;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Rectangle)) {
            return false;
        }
        final Rectangle other = (Rectangle) o;
        return Float.compare(mX, other.mX) != 0
                && Float.compare(mY, other.mY) != 0
                && Float.compare(mWidth, other.mWidth) != 0
                && Float.compare(mHeight, other.mHeight) != 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return "[" + mX + '/' + mY + ", " + mWidth + '/' + mHeight + "]";
    }
}


text:
namespace bp = boost::python;

struct OgreResourceProvider_wrapper : CEGUI::OgreResourceProvider, bp::wrapper< CEGUI::OgreResourceProvider > {

    OgreResourceProvider_wrapper( )
    : CEGUI::OgreResourceProvider( )
      , bp::wrapper< CEGUI::OgreResourceProvider >(){
        // null constructor

    }

    virtual ::size_t getResourceGroupFileNames( ::std::vector< CEGUI::String > & out_vec, ::CEGUI::String const & file_pattern, ::CEGUI::String const & resource_group ) {
        if( bp::override func_getResourceGroupFileNames = this->get_override( "getResourceGroupFileNames" ) )
            return func_getResourceGroupFileNames( boost::ref(out_vec), boost::ref(file_pattern), boost::ref(resource_group) );
        else{
            return this->CEGUI::OgreResourceProvider::getResourceGroupFileNames( boost::ref(out_vec), boost::ref(file_pattern), boost::ref(resource_group) );
        }
    }

    ::size_t default_getResourceGroupFileNames( ::std::vector< CEGUI::String > & out_vec, ::CEGUI::String const & file_pattern, ::CEGUI::String const & resource_group ) {
        return CEGUI::OgreResourceProvider::getResourceGroupFileNames( boost::ref(out_vec), boost::ref(file_pattern), boost::ref(resource_group) );
    }

    virtual void loadRawDataContainer( ::CEGUI::String const & filename, ::CEGUI::RawDataContainer & output, ::CEGUI::String const & resourceGroup ) {
        if( bp::override func_loadRawDataContainer = this->get_override( "loadRawDataContainer" ) )
            func_loadRawDataContainer( boost::ref(filename), boost::ref(output), boost::ref(resourceGroup) );
        else{
            this->CEGUI::OgreResourceProvider::loadRawDataContainer( boost::ref(filename), boost::ref(output), boost::ref(resourceGroup) );
        }
    }

    void default_loadRawDataContainer( ::CEGUI::String const & filename, ::CEGUI::RawDataContainer & output, ::CEGUI::String const & resourceGroup ) {
        CEGUI::OgreResourceProvider::loadRawDataContainer( boost::ref(filename), boost::ref(output), boost::ref(resourceGroup) );
    }

    virtual void unloadRawDataContainer( ::CEGUI::RawDataContainer & output ) {
        if( bp::override func_unloadRawDataContainer = this->get_override( "unloadRawDataContainer" ) )
            func_unloadRawDataContainer( boost::ref(output) );
        else{
            this->CEGUI::OgreResourceProvider::unloadRawDataContainer( boost::ref(output) );
        }
    }

    void default_unloadRawDataContainer( ::CEGUI::RawDataContainer & output ) {
        CEGUI::OgreResourceProvider::unloadRawDataContainer( boost::ref(output) );
    }

};

void register_OgreResourceProvider_class(){

    { //::CEGUI::OgreResourceProvider
        typedef bp::class_< OgreResourceProvider_wrapper, bp::bases< ::CEGUI::ResourceProvider >, boost::noncopyable > OgreResourceProvider_exposer_t;
        OgreResourceProvider_exposer_t OgreResourceProvider_exposer = OgreResourceProvider_exposer_t( "OgreResourceProvider", bp::init< >() );
        bp::scope OgreResourceProvider_scope( OgreResourceProvider_exposer );
        { //::CEGUI::OgreResourceProvider::getResourceGroupFileNames

            typedef ::size_t ( ::CEGUI::OgreResourceProvider::*getResourceGroupFileNames_function_type )( ::std::vector< CEGUI::String > &,::CEGUI::String const &,::CEGUI::String const & ) ;
            typedef ::size_t ( OgreResourceProvider_wrapper::*default_getResourceGroupFileNames_function_type )( ::std::vector< CEGUI::String > &,::CEGUI::String const &,::CEGUI::String const & ) ;

            OgreResourceProvider_exposer.def(
                "getResourceGroupFileNames"
                , getResourceGroupFileNames_function_type(&::CEGUI::OgreResourceProvider::getResourceGroupFileNames)
                , default_getResourceGroupFileNames_function_type(&OgreResourceProvider_wrapper::default_getResourceGroupFileNames)
                , ( bp::arg("out_vec"), bp::arg("file_pattern"), bp::arg("resource_group") ) );

        }
        { //::CEGUI::OgreResourceProvider::loadRawDataContainer

            typedef void ( ::CEGUI::OgreResourceProvider::*loadRawDataContainer_function_type )( ::CEGUI::String const &,::CEGUI::RawDataContainer &,::CEGUI::String const & ) ;
            typedef void ( OgreResourceProvider_wrapper::*default_loadRawDataContainer_function_type )( ::CEGUI::String const &,::CEGUI::RawDataContainer &,::CEGUI::String const & ) ;

            OgreResourceProvider_exposer.def(
                "loadRawDataContainer"
                , loadRawDataContainer_function_type(&::CEGUI::OgreResourceProvider::loadRawDataContainer)
                , default_loadRawDataContainer_function_type(&OgreResourceProvider_wrapper::default_loadRawDataContainer)
                , ( bp::arg("filename"), bp::arg("output"), bp::arg("resourceGroup") ) );

        }
        { //::CEGUI::OgreResourceProvider::unloadRawDataContainer

            typedef void ( ::CEGUI::OgreResourceProvider::*unloadRawDataContainer_function_type )( ::CEGUI::RawDataContainer & ) ;
            typedef void ( OgreResourceProvider_wrapper::*default_unloadRawDataContainer_function_type )( ::CEGUI::RawDataContainer & ) ;

            OgreResourceProvider_exposer.def(
                "unloadRawDataContainer"
                , unloadRawDataContainer_function_type(&::CEGUI::OgreResourceProvider::unloadRawDataContainer)
                , default_unloadRawDataContainer_function_type(&OgreResourceProvider_wrapper::default_unloadRawDataContainer)
                , ( bp::arg("output") ) );

        }
    }

}


text:
package com.marcouberti.f35watchface;

import android.content.Context;

import java.util.HashMap;

public class GradientsUtils {
    static HashMap<String, Integer> map = new HashMap<>();
    static {
        map.put("Blue",0);
        map.put("Violet",1);
        map.put("Yellow",2);
        map.put("Red",3);
        map.put("Dark green",4);
        map.put("Green",5);
        map.put("Aqua",6);
        map.put("Fruit",7);
        map.put("Orange",8);
        map.put("Silver",9);
    }

    public static int getGradients(Context ctx, int colorID) {
        if (colorID == 0) {
            return ctx.getResources().getColor(R.color.col_1);
        }else if (colorID == 1) {
            return ctx.getResources().getColor(R.color.col_2);
        }
        else if (colorID == 2) {
            return ctx.getResources().getColor(R.color.col_3);
        }
        else if (colorID == 3) {
            return ctx.getResources().getColor(R.color.col_4);
        }
        else if (colorID == 4) {
            return ctx.getResources().getColor(R.color.col_5);
        }
        else if (colorID == 5) {
            return ctx.getResources().getColor(R.color.col_6);
        }
        else if (colorID == 6) {
            return ctx.getResources().getColor(R.color.col_7);
        }
        else if (colorID == 7) {
            return ctx.getResources().getColor(R.color.col_8);
        }
        else if (colorID ==8) {
            return ctx.getResources().getColor(R.color.col_9);
        }
        else if (colorID == 9) {
            return ctx.getResources().getColor(R.color.col_10);
        }else {
            return ctx.getResources().getColor(R.color.col_4);
        }
    }

    public static int getGradients(Context ctx, String colorName) {
        if(colorName == null || !map.containsKey(colorName)) return ctx.getResources().getColor(R.color.col_4);
        return getGradients(ctx, map.get(colorName));
    }

    public static int getColorID(String colorName) {
        return map.get(colorName);
    }
}


text:
using Microsoft.Framework.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo08.Localization
{
    public class ExampleStringLocalizerFactory : IStringLocalizerFactory
    {
        public IStringLocalizer Create(Type resourceSource)
        {
            return new ExampleStringLocalizer();
        }

        public IStringLocalizer Create(string baseName, string location)
        {
            return new ExampleStringLocalizer();
        }
    }
}


text:
**Disseny** (http://isardmiralles.com/)

# Barcelona CSS

**BCN CSS** (https://acozar.github.io/bcncss/)

# Jekyll Now

**Jekyll** (https://github.com/jekyll/jekyll)


text:
// KEY LISTENER WIDGET . CLASS . TS

import { filter } from 'rxjs/operators';
import { Subscription } from "rxjs";

import { KeyPressedEvent } from "./events/keypressed.event";
import { EventListener } from "./events/event-listener.class";

export class KeyListenerWidget extends EventListener {

protected commandKeys: string[] = Array();
protected commandPressedSubscription: Subscription;
protected numberPressedSubscription: Subscription;

registerKeyPressedEvents() {

	if (this.areKeyPressedEventsRegistered()) {
		console.error('Trying to register to keypress events when we are already registered');
		return;
	}

	this.commandPressedSubscription = this.register(this.events.service.of<KeyPressedEvent>(KeyPressedEvent)
			.pipe(filter(key => key.isCommand()))
			.subscribe(key => {
				if (this.commandKeys.find( c => c===key.str)!==undefined) {
					this.commandPressedCallback(key.str);
				} else {
					this.commandNotRegisteredCallback(key.str);
				}
			})
	);

	this.numberPressedSubscription = this.register(this.events.service.of<KeyPressedEvent>(KeyPressedEvent)
			.pipe(filter(key => key.isNumber()))
			.subscribe(key => this.numberPressedCallback(key.num))
	);

}

/** This will be called when a key registered in commandKeys is triggered */
commandPressedCallback(command: string) {}

/** This will be called when a key is triggered that is not registered in commandKeys */
commandNotRegisteredCallback(command: string) {}

numberPressedCallback(num: number) {}

unregisterKeyPressedEvents() {

		if (this.commandPressedSubscription) {
			this.unsubscribe(this.commandPressedSubscription);
			this.commandPressedSubscription = undefined;
		}
		if (this.numberPressedSubscription) {
			this.unsubscribe(this.numberPressedSubscription);
			this.numberPressedSubscription = undefined;
		}

}

areKeyPressedEventsRegistered(): boolean {
	return this.commandPressedSubscription!==undefined && this.numberPressedSubscription!==undefined;
}

}

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


text:
import './vuetify'
import './splitpanes'
import './virtualScroller'