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

<title>NativeSurface (NativeWindow API -- 2.1 Specification)</title>
<meta name="date" content="2014-01-31">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.media.nativewindow

Interface NativeSurface

All Superinterfaces:

SurfaceUpdatedListener

All Known Subinterfaces:

MutableSurface, NativeWindow, ProxySurface

public interface NativeSurface
extends SurfaceUpdatedListener

Provides low-level information required for
    hardware-accelerated rendering using a surface in a platform-independent manner.

    A NativeSurface created for a particular on- or offscreen component is
    expected to have the same lifetime as that component. As long as
    the component is alive and realized/visible, NativeSurface must be able
    provide information such as the surface handle while it is locked.

Field Summary

Fields

Modifier and Type
Field and Description

static int
LOCK_SUCCESS

Returned by lockSurface() if the surface is locked, and is unchanged.

static int
LOCK_SURFACE_CHANGED

Returned by lockSurface() if the surface is locked, but has changed.

static int
LOCK_SURFACE_NOT_READY

Returned by lockSurface() if the surface is not ready to be locked.

static int
LOCK_SURFACE_UNLOCKED

Unlocked state

Method Summary

Methods

Modifier and Type
Method and Description

void
addSurfaceUpdatedListener(int index,
                         SurfaceUpdatedListener l)

Inserts the given SurfaceUpdatedListener at the
 specified position in the list.

void
addSurfaceUpdatedListener(SurfaceUpdatedListener l)

Appends the given SurfaceUpdatedListener to the end of the list.

long
getDisplayHandle()

Convenience: Get display handle from
   AbstractGraphicsConfiguration .

AbstractGraphicsConfiguration
getGraphicsConfiguration()

Returns the graphics configuration corresponding to this window.

int
getHeight()

Returns the height of the client area excluding insets (window decorations).

int
getScreenIndex()

Convenience: Get display handle from
   AbstractGraphicsConfiguration .

long
getSurfaceHandle()

Returns the handle to the surface for this NativeSurface.

Thread
getSurfaceLockOwner()

Return the locking owner's Thread, or null if not locked.

int
getWidth()

Returns the width of the client area excluding insets (window decorations).

boolean
isSurfaceLockedByOtherThread()

Query if surface is locked by another thread, i.e.

int
lockSurface()

Lock the surface of this native window.

void
removeSurfaceUpdatedListener(SurfaceUpdatedListener l)

Remove the specified SurfaceUpdatedListener from the list.

boolean
surfaceSwap()

Provide a mechanism to utilize custom (pre-) swap surface
 code.

void
unlockSurface()

Unlock the surface of this native window

 Shall not modify the surface handle, see lockSurface()

Methods inherited from interface javax.media.nativewindow.SurfaceUpdatedListener

surfaceUpdated

Field Detail

LOCK_SURFACE_UNLOCKED

static final int LOCK_SURFACE_UNLOCKED

Unlocked state

See Also:

Constant Field Values

LOCK_SURFACE_NOT_READY

static final int LOCK_SURFACE_NOT_READY

Returned by lockSurface() if the surface is not ready to be locked.

See Also:

Constant Field Values

LOCK_SURFACE_CHANGED

static final int LOCK_SURFACE_CHANGED

Returned by lockSurface() if the surface is locked, but has changed.

See Also:

Constant Field Values

LOCK_SUCCESS

static final int LOCK_SUCCESS

Returned by lockSurface() if the surface is locked, and is unchanged.

See Also:

Constant Field Values

Method Detail

lockSurface

int lockSurface()
                throws NativeWindowException,
                       RuntimeException

Lock the surface of this native window.

 The surface handle shall be valid after a successfull call,
 ie return a value other than LOCK_SURFACE_UNLOCKED and LOCK_SURFACE_NOT_READY,
 which is

    boolean ok = LOCK_SURFACE_NOT_READY < lockSurface();

 The caller may need to take care of the result LOCK_SURFACE_CHANGED,
 where the surface handle is valid but has changed.

 This call is blocking until the surface has been locked
 or a timeout is reached. The latter will throw a runtime exception.

 This call allows recursion from the same thread.

 The implementation may want to aquire the
 application level RecursiveLock
 first before proceeding with a native surface lock.

 The implementation shall also invoke AbstractGraphicsDevice.lock()
 for the initial lock (recursive count zero).

Returns:

LOCK_SUCCESS, LOCK_SURFACE_CHANGED or LOCK_SURFACE_NOT_READY.

Throws:

RuntimeException - after timeout when waiting for the surface lock

NativeWindowException - if native locking failed, maybe platform related

See Also:

RecursiveLock

unlockSurface

void unlockSurface()

Unlock the surface of this native window

 Shall not modify the surface handle, see lockSurface()

 The implementation shall also invoke AbstractGraphicsDevice.unlock()
 for the final unlock (recursive count zero).

 The implementation shall be fail safe, i.e. tolerant in case the native resources
 are already released / unlocked. In this case the implementation shall simply ignore the call.

See Also:

lockSurface(),
RecursiveLock

isSurfaceLockedByOtherThread

boolean isSurfaceLockedByOtherThread()

Query if surface is locked by another thread, i.e. not the current one.

 Convenient shortcut for:

   final Thread o = getSurfaceLockOwner();
   if( null != o && Thread.currentThread() != o ) { .. }

getSurfaceLockOwner

Thread getSurfaceLockOwner()

Return the locking owner's Thread, or null if not locked.

surfaceSwap

boolean surfaceSwap()

Provide a mechanism to utilize custom (pre-) swap surface
 code. This method is called before the render toolkit (e.g. JOGL)
 swaps the buffer/surface if double buffering is enabled.

 The implementation may itself apply the swapping,
 in which case true shall be returned.

Returns:

true if this method completed swapping the surface,
         otherwise false, in which case eg the GLDrawable
         implementation has to swap the code.

addSurfaceUpdatedListener

void addSurfaceUpdatedListener(SurfaceUpdatedListener l)

Appends the given SurfaceUpdatedListener to the end of the list.

addSurfaceUpdatedListener

void addSurfaceUpdatedListener(int index,
                             SurfaceUpdatedListener l)
                               throws IndexOutOfBoundsException

Inserts the given SurfaceUpdatedListener at the
 specified position in the list.

Parameters:

index - Position where the listener will be inserted.
 Should be within (0 <= index && index <= size()).
 An index value of -1 is interpreted as the end of the list, size().

l - The listener object to be inserted

Throws:

IndexOutOfBoundsException - If the index is not within (0 <= index && index <= size()), or -1

removeSurfaceUpdatedListener

void removeSurfaceUpdatedListener(SurfaceUpdatedListener l)

Remove the specified SurfaceUpdatedListener from the list.

getSurfaceHandle

long getSurfaceHandle()

Returns the handle to the surface for this NativeSurface.

 The surface handle should be set/update by lockSurface(),
 where unlockSurface() is not allowed to modify it.
 After unlockSurface() it is no more guaranteed
 that the surface handle is still valid.

 The surface handle shall reflect the platform one
 for all drawable surface operations, e.g. opengl, swap-buffer.

 On X11 this returns an entity of type Window,
 since there is no differentiation of surface and window there.

 On Microsoft Windows this returns an entity of type HDC.

getWidth

int getWidth()

Returns the width of the client area excluding insets (window decorations).

Returns:

width of the client area

getHeight

int getHeight()

Returns the height of the client area excluding insets (window decorations).

Returns:

height of the client area

getGraphicsConfiguration

AbstractGraphicsConfiguration getGraphicsConfiguration()

Returns the graphics configuration corresponding to this window.

 In case the implementation utilizes a delegation pattern to wrap abstract toolkits,
 this method shall return the native AbstractGraphicsConfiguration via AbstractGraphicsConfiguration.getNativeGraphicsConfiguration().

See Also:

AbstractGraphicsConfiguration.getNativeGraphicsConfiguration(),
javax.media.nativewindow.GraphicsConfigurationFactory#chooseGraphicsConfiguration(Capabilities, CapabilitiesChooser, AbstractGraphicsScreen)

getDisplayHandle

long getDisplayHandle()

Convenience: Get display handle from
   AbstractGraphicsConfiguration . AbstractGraphicsScreen . AbstractGraphicsDevice

getScreenIndex

int getScreenIndex()

Convenience: Get display handle from
   AbstractGraphicsConfiguration . AbstractGraphicsScreen

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright 2010 JogAmp Community.


text:
/**
 *
 */
package com.vaadin.client.ui.dd;

import java.util.HashSet;

import com.vaadin.client.UIDL;
import com.vaadin.shared.ui.dd.AcceptCriterion;
import com.vaadin.ui.Table;
import com.vaadin.ui.Tree;

/**
 *
 */
public class VLazyInitItemIdentifiers extends VAcceptCriterion {
    private boolean loaded = false;
    private HashSet<String> hashSet;
    private VDragEvent lastDragEvent;

    @AcceptCriterion(Table.TableDropCriterion.class)
    final public static class VTableLazyInitItemIdentifiers extends
            VLazyInitItemIdentifiers {
        // all logic in superclass
    }

    @AcceptCriterion(Tree.TreeDropCriterion.class)
    final public static class VTreeLazyInitItemIdentifiers extends
            VLazyInitItemIdentifiers {
        // all logic in superclass
    }

    @Override
    public void accept(final VDragEvent drag, UIDL configuration,
            final VAcceptCallback callback) {
        if (lastDragEvent == null || lastDragEvent != drag) {
            loaded = false;
            lastDragEvent = drag;
        }
        if (loaded) {
            Object object = drag.getDropDetails().get("itemIdOver");
            if (hashSet.contains(object)) {
                callback.accepted(drag);
            }
        } else {

            VDragEventServerCallback acceptCallback = new VDragEventServerCallback() {

                @Override
                public void handleResponse(boolean accepted, UIDL response) {
                    hashSet = new HashSet<String>();
                    String[] stringArrayAttribute = response
                            .getStringArrayAttribute("allowedIds");
                    for (int i = 0; i < stringArrayAttribute.length; i++) {
                        hashSet.add(stringArrayAttribute[i]);
                    }
                    loaded = true;
                    if (accepted) {
                        callback.accepted(drag);
                    }
                }
            };

            VDragAndDropManager.get().visitServer(acceptCallback);
        }

    }

    @Override
    public boolean needsServerSideCheck(VDragEvent drag, UIDL criterioUIDL) {
        return loaded;
    }

    @Override
    protected boolean accept(VDragEvent drag, UIDL configuration) {
        return false; // not used is this implementation
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: text/textblock
---
List which types of content formats you'll be managing in your CMS.

Choose a CMS that is scalable and expandable. You should be able to add features and configure them at minimal cost.

Some specific CMS features you may need:
- event calendars
- built-in newsletters
- social media integration
- comments or chat box tools
- online forms


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace webjob_simulate_yanzi_devices.Util
{
    class DatabaseConnection
    {
        private SqlConnection _sqlConnection;

        public DatabaseConnection(string connectionString)
        {
            var scsb = new SqlConnectionStringBuilder(connectionString)
            {
                MultipleActiveResultSets = true
            };

            _sqlConnection = new SqlConnection(scsb.ConnectionString);
        }

        public SqlConnection Connection { get { return _sqlConnection; } }
    }
}


text:
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
module Yesod.Helpers.Types where

import Prelude                              (Read(..))
import ClassyPrelude.Yesod hiding (Proxy)
import qualified Data.Aeson                 as A
import qualified Data.ByteString.Base64.URL as B64U
import qualified Data.ByteString.Char8      as C8
import qualified Data.ByteString.Lazy       as LB
import           Data.Proxy                 (Proxy(..))
import qualified Data.Serialize             as SL

import Language.Haskell.TH.Lift             (deriveLift)
import Data.Time                            (TimeZone, timeZoneOffsetString)
#if MIN_VERSION_time(1,5,0)
import Data.Time                            (parseTimeM)
#else
import System.Locale                        (defaultTimeLocale)
import Data.Time                            (parseTime)
#endif

import Data.SafeCopy
import Data.Binary                          (Binary)
import Data.Binary.Orphans                  ()
import Database.Persist.Sql                 (PersistFieldSql(..))
import Control.DeepSeq                      (NFData(..))
import Control.DeepSeq.Generics             (genericRnf)
import qualified System.FilePath.Glob       as G
import qualified Data.Binary                as Binary
import Text.Parsec
import Yesod.Helpers.Parsec
import Yesod.Helpers.SafeCopy

-- 用 SafeCopy 提供的实现应该使用空间上更优,但迁移时不知道会不会很麻烦
-- 用 deriveSafeCopySimpleEncoded 因为使用的是字串表达,迁移时比较容易做兼容
-- 只是空间使用多一些。
#define USE_SIMPLE_ENCODED_SAFECOPY

#ifdef USE_SIMPLE_ENCODED_SAFECOPY
-- import Yesod.Helpers.SafeCopy               ( deriveSafeCopySimpleEncoded )
#else
import Data.SafeCopy                        ( deriveSafeCopy, base )
#endif

data Gender = Male | Female
            deriving (Show, Read, Eq, Ord, Enum, Bounded, Generic)

instance NFData Gender where rnf = genericRnf

$(derivePersistFieldS "Gender")
$(deriveJsonS "Gender")
$(deriveSimpleStringRepEnumBounded "Gender")

#ifdef USE_SIMPLE_ENCODED_SAFECOPY
$(deriveSafeCopySimpleEncoded ''Gender)
#else
$(deriveSafeCopy 0 'base ''Gender)
#endif

instance SimpleEncode Gender where
    simpleEncode Male   = "male"
    simpleEncode Female = "female"

-- | A URL in Text.
newtype UrlText = UrlText { unUrlText :: Text}
  deriving ( Show, Eq, Ord, Typeable, Generic, Binary, NFData
           , Hashable, PersistField, PersistFieldSql
           , FromJSON, ToJSON
           )
$(deriveLift ''UrlText)

instance SafeCopy UrlText where
    getCopy             = contain $ UrlText <$> safeGet
    putCopy (UrlText x) = contain $ safePut x
    errorTypeName _     = "UrlText"

instance RedirectUrl m UrlText where toTextUrl = toTextUrl . unUrlText

newtype XTimeZone = XTimeZone { unXTimeZone :: TimeZone }
                    deriving (Show, Read, Eq, Ord, Typeable, Generic, Binary)

instance SimpleEncode XTimeZone where
    simpleEncode = timeZoneOffsetString . unXTimeZone

instance SimpleStringRep XTimeZone where
    simpleParser = do
        manyTill anyChar (eof Text.Parsec.<|> void space) >>=
            maybe mzero (return . XTimeZone) .
#if MIN_VERSION_time(1,5,0)
                (parseTimeM False defaultTimeLocale "%z")
#else
                (parseTime defaultTimeLocale "%z")
#endif

$(derivePersistFieldS "XTimeZone")
$(deriveJsonS "XTimeZone")

instance NFData XTimeZone where rnf (XTimeZone x) = rnf x

instance SafeCopy XTimeZone where
    getCopy = getCopySimpleEncoded
    putCopy = putCopySimpleEncoded

data SimpleVersion = SimpleVersion { unSimpleVersion :: [Int] }
                deriving (Show, Read, Eq, Ord, Generic)

instance NFData SimpleVersion
$(derivePersistFieldS "SimpleVersion")
$(deriveJsonS "SimpleVersion")

instance SimpleEncode SimpleVersion where
    simpleEncode (SimpleVersion vs) = concat $ intersperse "." $ map show vs

instance SimpleStringRep SimpleVersion where
    simpleParser = fmap (SimpleVersion . map fromIntegral) $ natural `sepBy1` string "."

instance SafeCopy SimpleVersion where
    getCopy = getCopySimpleEncoded
    putCopy = putCopySimpleEncoded

data VerConstraint = VerWithOrder Ordering SimpleVersion
                    | VerWithOrderN Ordering SimpleVersion
                    | VerWithGlob G.Pattern
                    | VerWithGlobN G.Pattern
                    | VerLogicAnd VerConstraint VerConstraint
                    | VerLogicOr VerConstraint VerConstraint
                    deriving (Show, Eq, Generic)

instance NFData VerConstraint where
    rnf (VerWithOrder o sv)     = o `seq` rnf sv
    rnf (VerWithOrderN o sv)    = o `seq` rnf sv
    rnf (VerWithGlob gp)        = seq gp ()
    rnf (VerWithGlobN gp)       = seq gp ()
    rnf (VerLogicAnd x y)       = rnf x `seq` rnf y
    rnf (VerLogicOr x y)        = rnf x `seq` rnf y

$(derivePersistFieldS "VerConstraint")
$(deriveJsonS "VerConstraint")

instance SafeCopy VerConstraint where
    getCopy = getCopySimpleEncoded
    putCopy = putCopySimpleEncoded

instance SimpleEncode VerConstraint where
    simpleEncode (VerWithOrder GT ver) =
                                concat $ intersperse " " $ [ ">" , simpleEncode ver ]

    simpleEncode (VerWithOrder EQ ver) =
                                concat $ intersperse " " $ [ "==" , simpleEncode ver ]

    simpleEncode (VerWithOrder LT ver) =
                                concat $ intersperse " " $ [ "<" , simpleEncode ver ]

    simpleEncode (VerWithOrderN GT ver) =
                                concat $ intersperse " " $ [ "<=" , simpleEncode ver ]

    simpleEncode (VerWithOrderN EQ ver) =
                                concat $ intersperse " " $ [ "/=" , simpleEncode ver ]

    simpleEncode (VerWithOrderN LT ver) =
                                concat $ intersperse " " $ [ ">=" , simpleEncode ver ]

    simpleEncode (VerWithGlob pat) =
                                concat $ intersperse " " $ [ "==" , G.decompile pat ]

    simpleEncode (VerWithGlobN pat) =
                                concat $ intersperse " " $ [ "/=" , G.decompile pat ]

    simpleEncode (VerLogicAnd c1 c2) =
                                concat $ intersperse " " $
                                    [ "("
                                    , simpleEncode c1
                                    , "&&"
                                    , simpleEncode c2
                                    , ")"
                                    ]

    simpleEncode (VerLogicOr c1 c2) =
                                concat $ intersperse " " $
                                    [ "("
                                    , simpleEncode c1
                                    , "||"
                                    , simpleEncode c2
                                    , ")"
                                    ]

instance SimpleStringRep VerConstraint where
    simpleParser = Text.Parsec.try (parens p) Text.Parsec.<|> p
        where
            p = choice
                [ Text.Parsec.try $ p_ord ">" (VerWithOrder GT)
                , Text.Parsec.try $ p_ord "==" (VerWithOrder EQ)
                , Text.Parsec.try $ p_ord "<" (VerWithOrder LT)
                , Text.Parsec.try $ p_ord ">=" (VerWithOrderN LT)
                , Text.Parsec.try $ p_ord "<=" (VerWithOrderN GT)
                , Text.Parsec.try $ p_ord "/=" (VerWithOrderN EQ)
                , Text.Parsec.try $ p_glob "==" VerWithGlob
                , Text.Parsec.try $ p_glob "/=" VerWithGlobN
                , Text.Parsec.try $ p_and
                , Text.Parsec.try $ p_or
                ]

            p_ord sym ctor = symbol sym >> fmap ctor simpleParser

            p_glob sym ctor = do
                _ <- symbol sym
                s <- manyTill anyChar (eof Text.Parsec.<|> void space)
                either (const mzero) (return . ctor) $
                        G.tryCompileWith G.compDefault s

            p_and = do
                c1 <- simpleParser
                _ <- symbol "&&"
                c2 <- simpleParser
                return $ VerLogicAnd c1 c2

            p_or = do
                c1 <- simpleParser
                _ <- symbol "||"
                c2 <- simpleParser
                return $ VerLogicOr c1 c2

validateSimpleVersion :: VerConstraint -> SimpleVersion -> Bool
validateSimpleVersion (VerWithOrder GT v0) ver = ver > v0
validateSimpleVersion (VerWithOrder LT v0) ver = ver < v0
validateSimpleVersion (VerWithOrder EQ v0) ver = ver == v0
validateSimpleVersion (VerWithOrderN GT v0) ver = ver <= v0
validateSimpleVersion (VerWithOrderN LT v0) ver = ver >= v0
validateSimpleVersion (VerWithOrderN EQ v0) ver = ver /= v0
validateSimpleVersion (VerWithGlob pat) ver = G.match pat $ simpleEncode ver
validateSimpleVersion (VerWithGlobN pat) ver = not $ G.match pat $ simpleEncode ver
validateSimpleVersion (VerLogicAnd c1 c2) ver =
    validateSimpleVersion c1 ver && validateSimpleVersion c2 ver
validateSimpleVersion (VerLogicOr c1 c2) ver =
    validateSimpleVersion c1 ver || validateSimpleVersion c2 ver

-- | 为把一个 bytestring 放到 yesod url 里
newtype B64UByteStringPathPiece = B64UByteStringPathPiece { unB64UByteStringPathPiece :: ByteString }
                                deriving (Eq, Ord, Show, Read, Typeable, Generic, Binary)

instance PathPiece B64UByteStringPathPiece where
    toPathPiece (B64UByteStringPathPiece bs) =
        fromString $ C8.unpack $ B64U.encode bs

    fromPathPiece t = do
        case B64U.decode (encodeUtf8 t) of
            Left _ -> mzero
            Right bs -> return $ B64UByteStringPathPiece bs

instance FromJSON B64UByteStringPathPiece where
    parseJSON v = do
        fmap fromPathPiece (parseJSON v)
            >>= maybe mzero return

instance ToJSON B64UByteStringPathPiece where
    toJSON = toJSON . toPathPiece

-- | A wrapper type to make some instances using base64-url-encoding
newtype B64UByteString a = B64UByteString { unB64UByteString :: a }
                                deriving (Eq, Ord)

instance Binary a => Show (B64UByteString a) where
  show (B64UByteString bs) = C8.unpack $ B64U.encode $ LB.toStrict $ Binary.encode bs

instance Binary a => Read (B64UByteString a) where
  readsPrec d r =
    catMaybes $ map (merge . first dec) $ readsPrec d r
    where
      merge (Left _, _) = Nothing
      merge (Right x, y) = Just (x, y)

      dec s = do
        bs <- B64U.decode s
        (left_bs, _, y) <- either (\(_, _, x) -> Left x) Right $ Binary.decodeOrFail $ LB.fromStrict bs
        if LB.null left_bs
            then return $ B64UByteString y
            else Left "not all input consumed"

instance Binary a => PathPiece (B64UByteString a) where
  toPathPiece = fromString . show

  fromPathPiece t = either (const Nothing) Just $ do
      bs <- B64U.decode (encodeUtf8 t)
      (left_bs, _, y) <- either (\(_, _, x) -> Left x) Right $ Binary.decodeOrFail $ LB.fromStrict bs
      if LB.null left_bs
          then return $ B64UByteString y
          else Left "not all input consumed"

instance Binary a => FromJSON (B64UByteString a) where
    parseJSON v = do
        fmap fromPathPiece (parseJSON v)
            >>= maybe mzero return

instance Binary a => ToJSON (B64UByteString a) where
    toJSON = toJSON . toPathPiece

instance PersistField a => PersistField (B64UByteString a) where
  toPersistValue   = toPersistValue . unB64UByteString
  fromPersistValue = fmap B64UByteString . fromPersistValue

instance PersistFieldSql a => PersistFieldSql (B64UByteString a) where
  sqlType _ = sqlType (Proxy :: Proxy a)

instance Binary a => Binary (B64UByteString a) where
  put = Binary.put . unB64UByteString
  get = B64UByteString <$> Binary.get

-- | A wrapper type to make it store as bytestring in DB, in JSON format.
newtype JsonSerialized a =  JsonSerialized { unJsonSerialized :: a }
                            deriving (Eq, Ord, Show, Read)

instance (ToJSON a, FromJSON a) => PersistField (JsonSerialized a) where
  toPersistValue   = toPersistValue . LB.toStrict . A.encode . unJsonSerialized
  fromPersistValue t = do
    bs <- fromPersistValue t
    either (Left . fromString) (return . JsonSerialized) $ A.eitherDecode $ LB.fromStrict bs

instance (ToJSON a, FromJSON a) => PersistFieldSql (JsonSerialized a) where
  sqlType _ = sqlType (Proxy :: Proxy ByteString)

-- | CAUTION: Put length (32bit, little-endian) before json encoded strings
instance (ToJSON a, FromJSON a) => SL.Serialize (JsonSerialized a) where
  put (JsonSerialized x) = do SL.putWord32le (fromIntegral $ length lbs)
                              SL.putLazyByteString lbs
                           where lbs = A.encode x

  get = do len <- SL.getWord32le
           lbs <- SL.getLazyByteString (fromIntegral len)
           either fail return $ fmap JsonSerialized $ A.eitherDecode lbs

-- | used in URL, represent a url piece
-- that can be
-- * either a DB key
-- * or a text, which can be uniquely identify the DB record
data KeyOrIdent k i = KI_Key k
                    | KI_Ident i

deriving instance (Show k, Show i) => Show (KeyOrIdent k i)
deriving instance (Read k, Read i) => Read (KeyOrIdent k i)
deriving instance (Eq k, Eq i) => Eq (KeyOrIdent k i)
deriving instance (Ord k, Ord i) => Ord (KeyOrIdent k i)

instance (PathPiece k, PathPiece i) => PathPiece (KeyOrIdent k i) where
    toPathPiece (KI_Key k)      = toPathPiece k
    toPathPiece (KI_Ident i)    = toPathPiece i

    fromPathPiece t =
        asum
            [ fmap KI_Key (fromPathPiece t)
            , fmap KI_Ident (fromPathPiece t)
            ]


text:
require 'findi/version'
require 'findi/client'
require 'findi/device'

module Findi
end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const client_options_1 = require("./client-options");
const logger_1 = require("./util/logger");
const timeout_registry_1 = require("./util/timeout-registry");
const timer_registry_1 = require("./util/timer-registry");
const connection_1 = require("./connection/connection");
const socket_factory_1 = require("./connection/socket-factory");
const event_handler_1 = require("./event/event-handler");
const rpc_handler_1 = require("./rpc/rpc-handler");
const record_handler_1 = require("./record/record-handler");
const storage_service_1 = require("./record/storage-service");
const presence_handler_1 = require("./presence/presence-handler");
const EventEmitter = require("component-emitter2");
const noop_storage_service_1 = require("./record/noop-storage-service");
class Client extends EventEmitter {
    constructor(url, options = {}) {
        super();
        this.options = Object.assign({}, client_options_1.DefaultOptions, options);
        // @ts-ignore
        const services = {};
        services.logger = new logger_1.Logger(this);
        services.timerRegistry = new timer_registry_1.TimerRegistry(this.options.timerResolution);
        services.timeoutRegistry = new timeout_registry_1.TimeoutRegistry(services, this.options);
        services.socketFactory = this.options.socketFactory || socket_factory_1.socketFactory;
        services.connection = new connection_1.Connection(services, this.options, url, this);
        if (this.options.offlineEnabled) {
            services.storage = this.options.storage || new storage_service_1.Storage(this.options);
        }
        else {
            services.storage = new noop_storage_service_1.NoopStorage();
        }
        this.services = services;
        this.services.connection.onLost(services.timeoutRegistry.onConnectionLost.bind(services.timeoutRegistry));
        this.event = new event_handler_1.EventHandler(this.services, this.options);
        this.rpc = new rpc_handler_1.RPCHandler(this.services, this.options);
        this.record = new record_handler_1.RecordHandler(this.services, this.options);
        this.presence = new presence_handler_1.PresenceHandler(this.services, this.options);
    }
    login(detailsOrCallback, callback) {
        if (detailsOrCallback && typeof detailsOrCallback === 'object') {
            if (callback) {
                this.services.connection.authenticate(detailsOrCallback, callback);
            }
            else {
                return new Promise((resolve, reject) => {
                    this.services.connection.authenticate(detailsOrCallback, (success, data) => {
                        success ? resolve(data) : reject(data);
                    });
                });
            }
        }
        else {
            if (typeof detailsOrCallback === 'function') {
                this.services.connection.authenticate({}, detailsOrCallback);
            }
            else {
                return new Promise((resolve, reject) => {
                    this.services.connection.authenticate({}, (success, data) => {
                        success ? resolve(data) : reject(data);
                    });
                });
            }
        }
    }
    getConnectionState() {
        return this.services.connection.getConnectionState();
    }
    close() {
        this.services.connection.close();
    }
    pause() {
        this.services.connection.pause();
    }
    resume(callback) {
        if (callback) {
            this.services.connection.resume(callback);
            return;
        }
        return new Promise((resolve, reject) => {
            this.services.connection.resume(error => {
                error ? reject(error) : resolve();
            });
        });
    }
    /**
    * Returns a random string. The first block of characters
    * is a timestamp, in order to allow databases to optimize for semi-
    * sequential numberings
    */
    getUid() {
        const timestamp = (new Date()).getTime().toString(36);
        const randomString = (Math.random() * 10000000000000000).toString(36).replace('.', '');
        return `${timestamp}-${randomString}`;
    }
}
exports.Client = Client;
//# sourceMappingURL=client.js.map


text:
package com.taobao.tddl.group.jdbc;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.taobao.tddl.common.TddlConstants;
import com.taobao.tddl.common.model.DBType;
import com.taobao.tddl.common.model.DataSourceType;
import com.taobao.tddl.common.utils.mbean.TddlMBeanServer;
import com.taobao.tddl.group.config.GroupConfigManager;
import com.taobao.tddl.group.dbselector.DBSelector;
import com.taobao.tddl.group.exception.TGroupDataSourceException;
import com.taobao.tddl.group.listener.DataSourceChangeListener;
import com.taobao.tddl.monitor.Monitor;

/**
 * TGroupDataSource并不是像名字所暗示的那样有一组DataSource,
 * 而是指TGroupDataSource内部包含一组(>=1个)同构的数据库, 这一组数据库的不同个体有不同的读写优先级和权重,
 * 当读写数据时也只是按读写优先级和权重对其中的一个数据库操作, 如果第一个数据库读写失败了,再尝试下一个数据库,
 * 如果第一个数据库读写成功了,直接返回结果给应用层, 其他数据库的同步更新由底层数据库内部完成, TGroupDataSource不负责数据同步。
 * 使用TGroupDataSource的步骤:
 *
 * <pre>
 * TGroupDataSource tGroupDataSource = new TGroupDataSource();
 * tGroupDataSource.setDbGroupKey("myDbGroup");
 * // ......调用其他setter
 * tGroupDataSource.init();
 * tGroupDataSource.getConnection();
 * </pre>
 *
 * @author yangzhu
 * @author linxuan
 */
public class TGroupDataSource implements DataSource {

    public static final String                    VERSION                   = "2.4.1";
    public static final String                    PREFIX                    = "com.taobao.tddl.jdbc.group_V" + VERSION
                                                                              + "_";
    public static final String                    EXTRA_PREFIX              = "com.taobao.tddl.jdbc.extra_config.group_V"
                                                                              + VERSION + "_";
    private GroupConfigManager                    configManager;

    /**
     * 下面三个为一组,支持本地配置
     */
    private String                                dsKeyAndWeightCommaArray;
    private DataSourceFetcher                     dataSourceFetcher;
    private DBType                                dbType                    = DBType.MYSQL;
    private String                                appName;                                                           // app名字
    private String                                unitName;                                                          // 单元化名字
    private String                                dbGroupKey;
    private String                                fullDbGroupKey            = null;                                  // dataId
    private int                                   retryingTimes             = 3;                                     // 默认读写失败时重试3次
    private long                                  configReceiveTimeout      = TddlConstants.DIAMOND_GET_DATA_TIMEOUT; // 取配置信息的默认超时时间为30秒
    // 当运行期间主备发生切换时是否需要查找第一个可写的库
    private boolean                               autoSelectWriteDataSource = false;
    /*
     * ========================================================================
     * 以下是保留当前写操作是在哪个库上执行的, 满足类似日志库插入的场景
     * ======================================================================
     */
    private static ThreadLocal<DataSourceWrapper> targetThreadLocal;

    // 下面两个字段当建立实际的DataSource时必须传递过去
    // jdbc规范: DataSource刚建立时LogWriter为null
    private PrintWriter                           out                       = null;
    // jdbc规范: DataSource刚建立时LoginTimeout为0
    private int                                   seconds                   = 0;

    /**
     * 使用tbdatasource还是druid
     */
    private DataSourceType                        dataSourceType            = DataSourceType.DruidDataSource;

    public TGroupDataSource(){
    }

    public TGroupDataSource(String dbGroupKey, String appName){
        this.dbGroupKey = dbGroupKey;
        this.appName = appName;
    }

    public TGroupDataSource(String dbGroupKey, String appName, DataSourceType dataSourceType){
        this.dbGroupKey = dbGroupKey;
        this.appName = appName;
        this.dataSourceType = dataSourceType;
    }

    /**
     * 基于dbGroupKey、appName来初始化多个TAtomDataSource
     *
     * @throws com.taobao.tddl.jdbc.group.exception.ConfigException
     */
    public void init() {
        if (dsKeyAndWeightCommaArray != null) {
            // 本地配置方式:dsKeyAndWeightCommaArray + dataSourceFetcher + dyType
            DataSourceFetcher wrapper = new DataSourceFetcher() {

                @Override
                public DataSource getDataSource(String key) {
                    return dataSourceFetcher.getDataSource(key);
                }

                @Override
                public DBType getDataSourceDBType(String key) {
                    DBType type = dataSourceFetcher.getDataSourceDBType(key);
                    return type == null ? dbType : type; // 如果dataSourceFetcher没dbType,用tgds的dbType
                }
            };
            List<DataSourceWrapper> dss = GroupConfigManager.buildDataSourceWrapper(dsKeyAndWeightCommaArray, wrapper);
            init(dss);
        } else {
            checkProperties();
            configManager = new GroupConfigManager(this);
            configManager.init();
        }

        Monitor.setAppName(appName);
    }

    public void init(DataSourceWrapper... dataSourceWrappers) {
        init(Arrays.asList(dataSourceWrappers));
    }

    public void init(List<DataSourceWrapper> dataSourceWrappers) {
        configManager = new GroupConfigManager(this);
        configManager.init(dataSourceWrappers);
    }

    public static TGroupDataSource build(String groupKey, String dsWeights, DataSourceFetcher fetcher,
                                         DataSourceType dataSourceType) {
        List<DataSourceWrapper> dss = GroupConfigManager.buildDataSourceWrapper(dsWeights, fetcher);
        TGroupDataSource tGroupDataSource = new TGroupDataSource();
        tGroupDataSource.setDataSourceType(dataSourceType);
        tGroupDataSource.setDbGroupKey(groupKey);
        tGroupDataSource.init(dss);
        return tGroupDataSource;
    }

    /**
     * 如果构造的是TAtomDataSource,必须检查dbGroupKey、appName两个属性的值是否合法
     */
    private void checkProperties() {
        if (dbGroupKey == null) {
            throw new TGroupDataSourceException("dbGroupKey不能为null");
        }
        dbGroupKey = dbGroupKey.trim();
        if (dbGroupKey.length() < 1) {
            throw new TGroupDataSourceException("dbGroupKey的长度要大于0,前导空白和尾部空白不算在内");
        }

        if (appName == null) {
            throw new TGroupDataSourceException("appName不能为null");
        }
        appName = appName.trim();
        if (appName.length() < 1) {
            throw new TGroupDataSourceException("appName的长度要大于0,前导空白和尾部空白不算在内");
        }

        if (dataSourceType == null) {
            throw new TGroupDataSourceException("dataSouceType不能为null");
        }
    }

    /**
     * 危险接口。一般用于测试。应用也可以直接通过该接口重置数据源配置
     */
    public void resetDbGroup(String configInfo) {
        configManager.resetDbGroup(configInfo);
    }

    // 包访问级别,调用者不能缓存,否则会失去动态性
    DBSelector getDBSelector(boolean isRead) {
        return configManager.getDBSelector(isRead, this.autoSelectWriteDataSource);
    }

    /**
     * 通过spring注入或直接调用该方法开启、关闭目标库记录
     */
    public void setTracerWriteTarget(boolean isTraceTarget) {
        if (isTraceTarget) {
            if (targetThreadLocal == null) {
                targetThreadLocal = new ThreadLocal<DataSourceWrapper>();
            }
        } else {
            targetThreadLocal = null;
        }
    }

    /**
     * 在执行完写操作后,调用改方法获得当前线程写操作是在哪个数据源执行的 获取完自动立即清空
     */
    public DataSourceWrapper getCurrentTarget() {
        if (targetThreadLocal == null) {
            return null;
        }
        DataSourceWrapper dsw = targetThreadLocal.get();
        targetThreadLocal.remove();
        return dsw;
    }

    /**
     * 下游调用该方法设置目标库
     */
    void setWriteTarget(DataSourceWrapper dsw) {
        if (targetThreadLocal != null) {
            targetThreadLocal.set(dsw);
        }
    }

    /*
     * ========================================================================
     * 遍历需求API
     * ======================================================================
     */
    // 在ConfigManager中我们将配置信息最终封装为读写DBSelector,要得到从dbKey到DataSource的映射,将DBSelector中的信息方向输出。
    public Map<String, DataSource> getDataSourceMap() {
        Map<String, DataSource> dsMap = new LinkedHashMap<String, DataSource>();
        dsMap.putAll(this.getDBSelector(true).getDataSources());
        dsMap.putAll(this.getDBSelector(false).getDataSources());
        return dsMap;
    }

    public Map<String, DataSource> getDataSourcesMap(boolean isRead) {
        return this.getDBSelector(isRead).getDataSources();
    }

    public void setDataSourceChangeListener(DataSourceChangeListener dataSourceChangeListener) {
        this.configManager.setDataSourceChangeListener(dataSourceChangeListener);
    }

    /*
     * ========================================================================
     * 以下是javax.sql.DataSource的API实现
     * ======================================================================
     */

    @Override
    public TGroupConnection getConnection() throws SQLException {
        return new TGroupConnection(this);
    }

    @Override
    public TGroupConnection getConnection(String username, String password) throws SQLException {
        return new TGroupConnection(this, username, password);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return out;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        this.out = out;
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return seconds;
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        this.seconds = seconds;
    }

    public static void setShutDownMBean(boolean shutDownMBean) {
        TddlMBeanServer.shutDownMBean = shutDownMBean;
    }

    public String getUnitName() {
        return unitName;
    }

    public void setUnitName(String unitName) {
        this.unitName = unitName;
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getDbGroupKey() {
        return dbGroupKey;
    }

    public String getFullDbGroupKey() {
        if (fullDbGroupKey == null) {
            fullDbGroupKey = PREFIX + getDbGroupKey();
        }
        return fullDbGroupKey;
    }

    public String getDbGroupExtraConfigKey() {
        return EXTRA_PREFIX + getDbGroupKey() + "." + getAppName();
    }

    public void setDbGroupKey(String dbGroupKey) {
        this.dbGroupKey = dbGroupKey;
    }

    public int getRetryingTimes() {
        return retryingTimes;
    }

    public void setRetryingTimes(int retryingTimes) {
        this.retryingTimes = retryingTimes;
    }

    public long getConfigReceiveTimeout() {
        return configReceiveTimeout;
    }

    public void setConfigReceiveTimeout(long configReceiveTimeout) {
        this.configReceiveTimeout = configReceiveTimeout;
    }

    public void setDsKeyAndWeightCommaArray(String dsKeyAndWeightCommaArray) {
        this.dsKeyAndWeightCommaArray = dsKeyAndWeightCommaArray;
    }

    public boolean getAutoSelectWriteDataSource() {
        return autoSelectWriteDataSource;
    }

    public void setAutoSelectWriteDataSource(boolean autoSelectWriteDataSource) {
        this.autoSelectWriteDataSource = autoSelectWriteDataSource;
    }

    public void setDataSourceFetcher(DataSourceFetcher dataSourceFetcher) {
        this.dataSourceFetcher = dataSourceFetcher;
    }

    public void setDbType(DBType dbType) {
        this.dbType = dbType;
    }

    public String getDsKeyAndWeightCommaArray() {
        return dsKeyAndWeightCommaArray;
    }

    public static final String getFullDbGroupKey(String dbGroupKey) {
        return PREFIX + dbGroupKey;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return this.getClass().isAssignableFrom(iface);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T unwrap(Class<T> iface) throws SQLException {
        try {
            return (T) this;
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }

    public DataSourceType getDataSourceType() {
        return dataSourceType;
    }

    public void setDataSourceType(DataSourceType dataSourceType) {
        this.dataSourceType = dataSourceType;
    }

    public void setDataSourceType(String dataSourceType) {
        this.dataSourceType = DataSourceType.valueOf(dataSourceType);
    }

    public DBType getDbType() {
        return dbType;
    }

    /**
     * 销毁数据源,慎用
     *
     * @throws Exception
     */
    public void destroyDataSource() throws Exception {
        if (configManager != null) {
            configManager.destroyDataSource();
        }
    }

}


text:
A verified ATM program in Coq.

We try to adapt this [Formal modelling of use cases with X-machines](http://delab.csd.auth.gr/bci1/SEEFM03/seefm03_06.pdf) article in [Coq](https://coq.inria.fr/) using the notion of scenarios, as in [ChickBlog](https://github.com/clarus/coq-chick-blog).


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/rc_text_color_primary_inverse"
              android:orientation="vertical">

	<LinearLayout
		android:layout_width="fill_parent"
		android:layout_height="60dp"
		android:layout_marginTop="5dp"
		android:orientation="horizontal"
		android:weightSum="2">

		<EditText
			android:id="@+id/rc_search_ed"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_gravity="bottom"
			android:layout_marginLeft="16dp"
			android:layout_weight="2"
			android:background="@drawable/rc_ed_public_service_search_selector"
			android:maxLines="1"
			android:textColor="#000000"
			android:textSize="16sp"/>

		<Button
			android:id="@+id/rc_search_btn"
			android:layout_width="wrap_content"
			android:layout_height="32dp"
			android:layout_gravity="bottom"
			android:layout_marginLeft="8dp"
			android:layout_marginRight="14dp"
			android:layout_weight="1"
			android:background="#0195ff"
			android:text="@string/rc_search"
			android:textColor="@color/rc_text_color_primary_inverse"
			android:textSize="15sp"/>

	</LinearLayout>

	<ListView
		android:id="@+id/rc_search_list"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:divider="@color/rc_conversation_list_divider_color"
		android:dividerHeight="0.5dp"/>
</LinearLayout>


text:
INSERT INTO t1 VALUES(5, 6);
SELECT * FROM t1;
pragma lock_status;


text:
package org.mifos.dto.domain;

import java.io.Serializable;

public interface ValueListElement extends Serializable {

    Integer getId();

    void setId(Integer id);

    String getName();

    void setName(String name);

    String getValueKey();

    void setValueKey(String valueKey);

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="lichessClasses">Nastave</string>
  <string name="teachClassesOfChessStudents">Predavaj nastavu razredima učenika šaha sa paketom alata Lichess Nastave.</string>
  <string name="features">Značajke</string>
  <string name="quicklyGenerateSafeUsernames">Brzo stvori sigurno korisničko ime i lozinku za studente</string>
  <string name="trackStudentProgress">Prati napredak studenata u njihovim partijama i šahovskim problematikama</string>
  <string name="messageAllStudents">Obavijesti sve studente o novim nastavnim materijalima</string>
  <string name="freeForAllForever">Potpuno besplatno za sve, zauvijek, i to bez oglasa ili tragača</string>
  <string name="applyToBeLichessTeacher">Prijavi se da postaneš Lichess Nastavnik</string>
  <string name="noClassesYet">Još nema predavanja.</string>
  <string name="teachersX">Nastavnici: %s</string>
  <string name="newClass">Nova nastava</string>
  <string name="closeClass">Zatvori nastavu</string>
  <string name="closedByX">Zatvoren od %s</string>
  <string name="reopen">Ponovno otvori</string>
  <string name="removeStudent">Ukloni studenta</string>
  <string name="removedStudents">Uklonjen</string>
  <string name="inviteTheStudentBack">Pozovi studenta nazad</string>
  <string name="sendAMessage">Pošalji poruku svim studentima.</string>
  <string name="aLinkToTheClassWillBeAdded">Poveznica za nastavu bit će automatski dodana na kraju poruke, tako da je ne moraš sam uključiti.</string>
  <string name="className">Ime nastave</string>
  <string name="classDescription">Opis nastave</string>
  <string name="visibleByBothStudentsAndTeachers">Vidljivo i nastavnicima i studentima razreda</string>
  <string name="teachersOfTheClass">Nastavnici razreda</string>
  <string name="addLichessUsernames">Dodaj Lichess korisnička imena da bi ih pozvao/la kao nastavnike. Jedna po retku.</string>
  <string name="resetPassword">Resetiraj lozinku</string>
  <string name="makeSureToCopy">Obavezno sada kopiraj ili zapiši lozinku. Nećeš je više moći vidjeti!</string>
  <string name="passwordX">Lozinka: %s</string>
  <string name="generateANewPassword">Stvori novu lozinku za studenta</string>
  <string name="invitedToXByY">%2$s te je pozvao u %1$s</string>
  <string name="realName">Pravo ime</string>
  <string name="privateWillNeverBeShown">Privatna. Nikad se neće prikazati izvan nastave. To pomaže da se upamti tko je student.</string>
  <string name="addStudent">Dodaj studenta</string>
  <string name="lichessProfileXCreatedForY">Lichess profil %1$s je napravljen za %2$s.</string>
  <string name="studentCredentials">Student:  %1$s
Korisničko ime: %2$s
Lozinka: %3$s</string>
  <string name="inviteALichessAccount">Pozovi Lichess račun</string>
  <string name="inviteDesc1">Ako učenik već ima Lichess račun, možeš ga pozvati na predavanje.</string>
  <string name="inviteDesc2">Oni će na Lichessu dobiti poruku s linkom kako bi se pridružili predavanju.</string>
  <string name="inviteDesc3">Molimo da pozoveš ljude koje znaš i koji su voljni sudjelovati u ovoj nastavi.</string>
  <string name="inviteDesc4">Nikada nemoj slati neželjene pozive nasumičnim igračima.</string>
  <string name="createANewLichessAccount">Kreiraj novi Lichess račun</string>
  <string name="createDesc1">Ako učenik još nema Lichess račun, možeš ga stvoriti ovdje.</string>
  <string name="createDesc2">Nije potrebna adresa e-pošte. Stvorit će se lozinka i morat ćete ju poslati studentu kako bi se mogao prijaviti.</string>
  <string name="createDesc3">Važno: student ne smije imati više računa.</string>
  <string name="createDesc4">Ako ih već ima, umjesto toga upotrijebi obrazac za poziv.</string>
  <string name="createStudentWarning">Kreiraj račune isključivo za prave učenike. Nemoj koristiti ovu funkcionalnost za izradu višestrukih vlastitih računa. Zabraniti ćemo ti pristup Lichessu.</string>
  <string name="lichessUsername">Lichess korisničko ime</string>
  <string name="generateANewUsername">Stvori novo korisničko ime</string>
  <string name="welcomeToClass">Dobrodošao u tvoj razred: %s. Ovdje je link za pristup predavanju.</string>
  <string name="invitationToClass">Pozvan si pridružiti se razredu \"%s\" kao student.</string>
  <string name="clickToViewInvitation">Klikni na link za otvaranje pozivnice:</string>
  <plurals name="nbPendingInvitations">
    <item quantity="one">Jedna pozivnica na čekanju</item>
    <item quantity="few">%s pozivnice na čekanju</item>
    <item quantity="other">%s pozivnica na čekanju</item>
  </plurals>
  <string name="onlyVisibleToTeachers">Vidljivo samo nastavnicima</string>
  <string name="lastActiveDate">Zadnja aktivnost</string>
  <string name="managed">Vođen</string>
  <string name="thisStudentAccountIsManaged">Ovaj je korisnički račun vođen</string>
  <string name="upgradeFromManaged">Prijeđi iz vođenog u autonomni</string>
  <string name="release">Objavi</string>
  <string name="releaseTheAccount">Objavi račun tako da student može s njime samostalno upravljati.</string>
  <string name="releaseDesc1">Objavljeni račun se ne može ponovno vratiti na upravljanje. Student će imati slobodu uključivanja dječjeg načina rada i resetiranja lozinke.</string>
  <string name="releaseDesc2">Nakon što je račun objavljen, student će ostati u razredu.</string>
  <string name="realUniqueEmail">Stvarna email adresa studenta. Poslat će se potvrdna e-pošta s linkom za objavljivanje računa.</string>
  <string name="closeStudent">Zatvori račun</string>
  <string name="closeTheAccount">Zatvori učenikov račun zauvijek.</string>
  <string name="closeDesc1">Učenik više nikada neće moći koristiti ovaj račun. Zatvaranje je konačno. Pobrinite se da učenik to razumije i da se slaže s time.</string>
  <string name="closeDesc2">Umjesto zatvaranja možda želite dati učeniku kontrolu nad računom tako da ga može nastaviti koristiti.</string>
  <string name="teachers">Nastavnici</string>
  <plurals name="nbTeachers">
    <item quantity="one">%s nastavnik</item>
    <item quantity="few">%s nastavnika</item>
    <item quantity="other">%s nastavnika</item>
  </plurals>
  <plurals name="nbStudents">
    <item quantity="one">Student</item>
    <item quantity="few">%s studenta</item>
    <item quantity="other">%s studenta</item>
  </plurals>
  <string name="students">Studenti</string>
  <string name="progress">Napredak</string>
  <string name="noStudents">Učionica je prazna.</string>
  <string name="noRemovedStudents">Nema uklonjenih studenata.</string>
  <string name="overDays">Tijekom dana</string>
  <string name="timePlaying">Vrijeme igranja</string>
  <string name="variantXOverLastY">%1$s u zadnjih %2$s</string>
  <string name="winrate">Stopa pobjede</string>
  <string name="na">N/A</string>
  <string name="news">Nastavne novosti</string>
  <string name="editNews">Uređivanje vijesti</string>
  <string name="notifyAllStudents">Obavijesti sve studente</string>
  <string name="nothingHere">Još nema ničega ovdje.</string>
  <string name="newsEdit1">Sve nastavne novosti u jednom polju.</string>
  <string name="newsEdit2">Postavi posljednje novosti na vrh. Nemoj obrisati prethodne novosti.</string>
  <string name="newsEdit3">Odvoji novosti sa ---
To će prikazati horizontalnu liniju.</string>
</resources>


text:
@interface coKitNSArrayTests : XCTestCase

@end

@implementation coKitNSArrayTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self tempPath]]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:[self tempPath] withIntermediateDirectories:NO attributes:nil error:nil];
    }
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
    [[NSFileManager defaultManager] removeItemAtPath:[self tempPath] error:nil];
}

- (void)testExample {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
}

- (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
        // Put the code you want to measure the time of here.
    }];
}

- (NSString*)tempPath{
    return [NSTemporaryDirectory() stringByAppendingPathComponent:@"test001"];
}

- (void)testNSArrayInitializeFromFile{

    XCTestExpectation *e = [self expectationWithDescription:@"test"];

    co_launch(^{
        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file_%d", i]];
            [tmpList co_writeToFile:filePath atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSArray *resultList = [[NSArray alloc] co_initWithContentsOfFile:filePath];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file_%d", i]];
            [tmpList co_writeToURL:[NSURL fileURLWithPath:filePath] error:nil];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSArray *resultList = [[NSArray alloc] co_initWithContentsOfURL:[NSURL fileURLWithPath:filePath]];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file_%d", i]];
            [tmpList co_writeToURL:[NSURL fileURLWithPath:filePath] atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSArray *resultList = [NSArray co_arrayWithContentsOfFile:filePath];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file_%d", i]];
            [tmpList co_writeToFile:filePath atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSArray *resultList = [NSArray co_arrayWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        [e fulfill];
    });

    [self waitForExpectations:@[e] timeout:1000];
}

- (void)testNSMutableArrayInitializeFromFile{

    XCTestExpectation *e = [self expectationWithDescription:@"test"];

    co_launch(^{
        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file1_%d", i]];
            [tmpList co_writeToFile:filePath atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSMutableArray *resultList = [[NSMutableArray alloc] co_initWithContentsOfFile:filePath];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file1_%d", i]];
            [tmpList co_writeToFile:filePath atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSMutableArray *resultList = [[NSMutableArray alloc] co_initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file1_%d", i]];
            [tmpList co_writeToFile:filePath atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSMutableArray *resultList = [NSMutableArray co_arrayWithContentsOfFile:filePath];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        for (int i = 0; i < 100; i++) {
            NSMutableArray *list = [[NSMutableArray alloc] init];
            for (int j = 0; j < 10; j++) {
                [list addObject:@(rand() % 1000)];
            }
            NSArray *tmpList = [list copy];
            NSString *filePath = [[self tempPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"file1_%d", i]];
            [tmpList co_writeToFile:filePath atomically:YES];

            XCTAssert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

            NSMutableArray *resultList = [NSMutableArray co_arrayWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];

            XCTAssert(resultList.count == list.count);

            for (int j = 0; j < 10; j++) {
                XCTAssert([list[j] intValue] == [resultList[j] intValue]);
            }

            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        }

        [e fulfill];
    });

    [self waitForExpectations:@[e] timeout:1000];
}

@end


text:
import os
import sys

from .runserver import start_dev_appserver
from django.core.management.base import BaseCommand
from djangoappengine.db.base import destroy_datastore, get_test_datastore_paths

class Command(BaseCommand):
    """Overrides the default Django testserver command.

    Instead of starting the default Django development server this command fires
    up a copy of the full fledged App Engine dev_appserver.

    The appserver is always initialised with a blank datastore with the specified
    fixtures loaded into it.
    """
    help = 'Runs the development server with data from the given fixtures.'

    def run_from_argv(self, argv):
        fixtures = []
        for arg in argv[2:]:
            if arg.startswith('-'):
                break
            fixtures.append(arg)
            argv.remove(arg)

        try:
            index = argv.index('--addrport')
            addrport = argv[index + 1]
            del argv[index:index+2]
            argv = argv[:2] + [addrport] + argv[2:index] + argv[index+1:]
        except:
            pass

        # Ensure an on-disk test datastore is used.
        from django.db import connection
        connection.use_test_datastore = True
        connection.test_datastore_inmemory = False

        # Flush any existing test datastore.
        connection.flush()

        # Load the fixtures.
        from django.core.management import call_command
        call_command('loaddata', 'initial_data')
        if fixtures:
            call_command('loaddata', *fixtures)

        # Build new arguments for dev_appserver.
        argv[1] = 'runserver'
        datastore_path, history_path = get_test_datastore_paths(False)
        argv.extend(['--datastore_path', datastore_path])
        argv.extend(['--history_path', history_path])

        start_dev_appserver(argv)


text:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

/**
 UIApplicationDelegate based class preprared to bypass all the events related to
 the UIApplicationDelegate
 @since 1.0
 */
@interface MCMApplicationDelegate : UIResponder<UIApplicationDelegate> {
}

/**
 IBOutlet for the main window of the application.
 @since 1.0
 */
@property (nonatomic, retain) IBOutlet UIWindow *window;

/**
 IBOutlet for the tabbar used by the application. It's created automatically when MCMConfigModule active and
 no tabbar existis
 @since 1.0
 */
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

@end


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import '//resources/cr_elements/cr_button/cr_button.m.js';
import '//resources/cr_elements/cr_dialog/cr_dialog.m.js';
import '//resources/cr_elements/shared_style_css.m.js';
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import '//resources/cr_components/localized_link/localized_link.js';
import '../os_icons.js';
import '../../settings_shared_css.js';

import {I18nBehavior} from '//resources/js/i18n_behavior.m.js';
import {WebUIListenerBehavior} from '//resources/js/web_ui_listener_behavior.m.js';
import {html, Polymer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {MultiDeviceBrowserProxy, MultiDeviceBrowserProxyImpl} from './multidevice_browser_proxy.js';
import {MultiDeviceFeature} from './multidevice_constants.js';

/**
 * @fileoverview
 * This element provides the Phone Hub notification access setup flow that, when
 * successfully completed, enables the feature that allows a user's phone
 * notifications to be mirrored on their Chromebook.
 */

/**
 * Numerical values should not be changed because they must stay in sync with
 * notification_access_setup_operation.h, with the exception of
 * CONNECTION_REQUESTED.
 * @enum{number}
 */
export const NotificationAccessSetupOperationStatus = {
  CONNECTION_REQUESTED: 0,
  CONNECTING: 1,
  TIMED_OUT_CONNECTING: 2,
  CONNECTION_DISCONNECTED: 3,
  SENT_MESSAGE_TO_PHONE_AND_WAITING_FOR_RESPONSE: 4,
  COMPLETED_SUCCESSFULLY: 5,
  NOTIFICATION_ACCESS_PROHIBITED: 6,
};

Polymer({
  _template: html`{__html_template__}`,
  is: 'settings-multidevice-notification-access-setup-dialog',

  behaviors: [
    I18nBehavior,
    WebUIListenerBehavior,
  ],

  properties: {
    /**
     * A null |setupState_| indicates that the operation has not yet started.
     * @private {?NotificationAccessSetupOperationStatus}
     */
    setupState_: {
      type: Number,
      value: null,
    },

    /** @private */
    title_: {
      type: String,
      computed: 'getTitle_(setupState_)',
    },

    /** @private */
    description_: {
      type: String,
      computed: 'getDescription_(setupState_)',
    },

    /** @private */
    hasNotStartedSetupAttempt_: {
      type: Boolean,
      computed: 'computeHasNotStartedSetupAttempt_(setupState_)',
      reflectToAttribute: true,
    },

    /** @private */
    isSetupAttemptInProgress_: {
      type: Boolean,
      computed: 'computeIsSetupAttemptInProgress_(setupState_)',
      reflectToAttribute: true,
    },

    /** @private */
    didSetupAttemptFail_: {
      type: Boolean,
      computed: 'computeDidSetupAttemptFail_(setupState_)',
      reflectToAttribute: true,
    },

    /** @private */
    hasCompletedSetupSuccessfully_: {
      type: Boolean,
      computed: 'computeHasCompletedSetupSuccessfully_(setupState_)',
      reflectToAttribute: true,
    },

    /** @private */
    isNotificationAccessProhibited_: {
      type: Boolean,
      computed: 'computeIsNotificationAccessProhibited_(setupState_)',
    },

    /** @private */
    shouldShowSetupInstructionsSeparately_: {
      type: Boolean,
      computed: 'computeShouldShowSetupInstructionsSeparately_(' +
          'setupState_)',
      reflectToAttribute: true,
    },
  },

  /** @private {?MultiDeviceBrowserProxy} */
  browserProxy_: null,

  /** @override */
  ready() {
    this.browserProxy_ = MultiDeviceBrowserProxyImpl.getInstance();
  },

  /** @override */
  attached() {
    this.addWebUIListener(
        'settings.onNotificationAccessSetupStatusChanged',
        this.onSetupStateChanged_.bind(this));
    this.$.dialog.showModal();
  },

  /**
   * @param {!NotificationAccessSetupOperationStatus} setupState
   * @private
   */
  onSetupStateChanged_(setupState) {
    this.setupState_ = setupState;
    if (this.setupState_ ===
        NotificationAccessSetupOperationStatus.COMPLETED_SUCCESSFULLY) {
      this.browserProxy_.setFeatureEnabledState(
          MultiDeviceFeature.PHONE_HUB_NOTIFICATIONS, true);
    }
  },

  /**
   * @return {boolean}
   * @private
   */
  computeHasNotStartedSetupAttempt_() {
    return this.setupState_ === null;
  },

  /**
   * @return {boolean}
   * @private
   */
  computeIsSetupAttemptInProgress_() {
    return this.setupState_ ===
        NotificationAccessSetupOperationStatus
            .SENT_MESSAGE_TO_PHONE_AND_WAITING_FOR_RESPONSE ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus.CONNECTING ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus.CONNECTION_REQUESTED;
  },

  /**
   * @return {boolean}
   * @private
   */
  computeHasCompletedSetupSuccessfully_() {
    return this.setupState_ ===
        NotificationAccessSetupOperationStatus.COMPLETED_SUCCESSFULLY;
  },

  /**
   * @return {boolean}
   * @private
   */
  computeIsNotificationAccessProhibited_() {
    return this.setupState_ ===
        NotificationAccessSetupOperationStatus.NOTIFICATION_ACCESS_PROHIBITED;
  },

  /**
   * @return {boolean}
   * @private
   * */
  computeDidSetupAttemptFail_() {
    return this.setupState_ ===
        NotificationAccessSetupOperationStatus.TIMED_OUT_CONNECTING ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus.CONNECTION_DISCONNECTED ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus.NOTIFICATION_ACCESS_PROHIBITED;
  },

  /**
   * @return {boolean} Whether to show setup instructions in its own section.
   * @private
   */
  computeShouldShowSetupInstructionsSeparately_() {
    return this.setupState_ === null ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus.CONNECTION_REQUESTED ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus
            .SENT_MESSAGE_TO_PHONE_AND_WAITING_FOR_RESPONSE ||
        this.setupState_ === NotificationAccessSetupOperationStatus.CONNECTING;
  },

  /** @private */
  attemptNotificationSetup_() {
    this.browserProxy_.attemptNotificationSetup();
    this.setupState_ =
        NotificationAccessSetupOperationStatus.CONNECTION_REQUESTED;
  },

  /** @private */
  onCancelClicked_() {
    this.browserProxy_.cancelNotificationSetup();
    this.$.dialog.close();
  },

  /** @private */
  onDoneOrCloseButtonClicked_() {
    this.$.dialog.close();
  },

  /**
   * @return {string} The title of the dialog.
   * @private
   */
  getTitle_() {
    if (this.setupState_ === null) {
      return this.i18n('multideviceNotificationAccessSetupAckTitle');
    }

    const Status = NotificationAccessSetupOperationStatus;
    switch (this.setupState_) {
      case Status.CONNECTION_REQUESTED:
      case Status.CONNECTING:
        return this.i18n('multideviceNotificationAccessSetupConnectingTitle');
      case Status.SENT_MESSAGE_TO_PHONE_AND_WAITING_FOR_RESPONSE:
        return this.i18n(
            'multideviceNotificationAccessSetupAwaitingResponseTitle');
      case Status.COMPLETED_SUCCESSFULLY:
        return this.i18n('multideviceNotificationAccessSetupCompletedTitle');
      case Status.TIMED_OUT_CONNECTING:
        return this.i18n(
            'multideviceNotificationAccessSetupCouldNotEstablishConnectionTitle');
      case Status.CONNECTION_DISCONNECTED:
        return this.i18n(
            'multideviceNotificationAccessSetupConnectionLostWithPhoneTitle');
      case Status.NOTIFICATION_ACCESS_PROHIBITED:
        return this.i18n(
            'multideviceNotificationAccessSetupAccessProhibitedTitle');
      default:
        return '';
    }
  },

  /**
   * @return {string} A description about the connection attempt state.
   * @private
   */
  getDescription_() {
    if (this.setupState_ === null) {
      return this.i18n('multideviceNotificationAccessSetupAckSummary');
    }

    const Status = NotificationAccessSetupOperationStatus;
    switch (this.setupState_) {
      case Status.COMPLETED_SUCCESSFULLY:
        return this.i18n('multideviceNotificationAccessSetupCompletedSummary');
      case Status.TIMED_OUT_CONNECTING:
        return this.i18n(
            'multideviceNotificationAccessSetupEstablishFailureSummary');
      case Status.CONNECTION_DISCONNECTED:
        return this.i18n(
            'multideviceNotificationAccessSetupMaintainFailureSummary');
      case Status.NOTIFICATION_ACCESS_PROHIBITED:
        return this.i18nAdvanced(
            'multideviceNotificationAccessSetupAccessProhibitedSummary');
      case Status.SENT_MESSAGE_TO_PHONE_AND_WAITING_FOR_RESPONSE:
        return this.i18n(
            'multideviceNotificationAccessSetupAwaitingResponseSummary');

      // Only setup instructions will be shown.
      case Status.CONNECTION_REQUESTED:
      case Status.CONNECTING:
      default:
        return '';
    }
  },

  /**
   * @return {boolean}
   * @private
   */
  shouldShowCancelButton_() {
    return this.setupState_ !==
        NotificationAccessSetupOperationStatus.COMPLETED_SUCCESSFULLY &&
        this.setupState_ !==
        NotificationAccessSetupOperationStatus.NOTIFICATION_ACCESS_PROHIBITED;
  },

  /**
   * @return {boolean}
   * @private
   */
  shouldShowTryAgainButton_() {
    return this.setupState_ ===
        NotificationAccessSetupOperationStatus.TIMED_OUT_CONNECTING ||
        this.setupState_ ===
        NotificationAccessSetupOperationStatus.CONNECTION_DISCONNECTED;
  },
});


text:
"""WPC Geo Products Parser!"""
# Local
from pywwa.workflows.ero_parser import main

if __name__ == "__main__":
    main()


text:
package bech32

import (
	"fmt"
	"strings"
)

const charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"

var gen = []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3}

// Decode decodes a bech32 encoded string, returning the human-readable
// part and the data part excluding the checksum.
func Decode(bech string) (string, []byte, error) {
	// The maximum allowed length for a bech32 string is 90. It must also
	// be at least 8 characters, since it needs a non-empty HRP, a
	// separator, and a 6 character checksum.
	if len(bech) < 8 || len(bech) > 90 {
		return "", nil, fmt.Errorf("invalid bech32 string length %d",
			len(bech))
	}
	// Only	ASCII characters between 33 and 126 are allowed.
	for i := 0; i < len(bech); i++ {
		if bech[i] < 33 || bech[i] > 126 {
			return "", nil, fmt.Errorf("invalid character in "+
				"string: '%c'", bech[i])
		}
	}

	// The characters must be either all lowercase or all uppercase.
	lower := strings.ToLower(bech)
	upper := strings.ToUpper(bech)
	if bech != lower && bech != upper {
		return "", nil, fmt.Errorf("string not all lowercase or all " +
			"uppercase")
	}

	// We'll work with the lowercase string from now on.
	bech = lower

	// The string is invalid if the last '1' is non-existent, it is the
	// first character of the string (no human-readable part) or one of the
	// last 6 characters of the string (since checksum cannot contain '1'),
	// or if the string is more than 90 characters in total.
	one := strings.LastIndexByte(bech, '1')
	if one < 1 || one+7 > len(bech) {
		return "", nil, fmt.Errorf("invalid index of 1")
	}

	// The human-readable part is everything before the last '1'.
	hrp := bech[:one]
	data := bech[one+1:]

	// Each character corresponds to the byte with value of the index in
	// 'charset'.
	decoded, err := toBytes(data)
	if err != nil {
		return "", nil, fmt.Errorf("failed converting data to bytes: "+
			"%v", err)
	}

	if !bech32VerifyChecksum(hrp, decoded) {
		moreInfo := ""
		checksum := bech[len(bech)-6:]
		expected, err := toChars(bech32Checksum(hrp,
			decoded[:len(decoded)-6]))
		if err == nil {
			moreInfo = fmt.Sprintf("Expected %v, got %v.",
				expected, checksum)
		}
		return "", nil, fmt.Errorf("checksum failed. " + moreInfo)
	}

	// We exclude the last 6 bytes, which is the checksum.
	return hrp, decoded[:len(decoded)-6], nil
}

// Encode encodes a byte slice into a bech32 string with the
// human-readable part hrb. Note that the bytes must each encode 5 bits
// (base32).
func Encode(hrp string, data []byte) (string, error) {
	// Calculate the checksum of the data and append it at the end.
	checksum := bech32Checksum(hrp, data)
	combined := append(data, checksum...)

	// The resulting bech32 string is the concatenation of the hrp, the
	// separator 1, data and checksum. Everything after the separator is
	// represented using the specified charset.
	dataChars, err := toChars(combined)
	if err != nil {
		return "", fmt.Errorf("unable to convert data bytes to chars: "+
			"%v", err)
	}
	return hrp + "1" + dataChars, nil
}

// toBytes converts each character in the string 'chars' to the value of the
// index of the correspoding character in 'charset'.
func toBytes(chars string) ([]byte, error) {
	decoded := make([]byte, 0, len(chars))
	for i := 0; i < len(chars); i++ {
		index := strings.IndexByte(charset, chars[i])
		if index < 0 {
			return nil, fmt.Errorf("invalid character not part of "+
				"charset: %v", chars[i])
		}
		decoded = append(decoded, byte(index))
	}
	return decoded, nil
}

// toChars converts the byte slice 'data' to a string where each byte in 'data'
// encodes the index of a character in 'charset'.
func toChars(data []byte) (string, error) {
	result := make([]byte, 0, len(data))
	for _, b := range data {
		if int(b) >= len(charset) {
			return "", fmt.Errorf("invalid data byte: %v", b)
		}
		result = append(result, charset[b])
	}
	return string(result), nil
}

// ConvertBits converts a byte slice where each byte is encoding fromBits bits,
// to a byte slice where each byte is encoding toBits bits.
func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {
	if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 {
		return nil, fmt.Errorf("only bit groups between 1 and 8 allowed")
	}

	// The final bytes, each byte encoding toBits bits.
	var regrouped []byte

	// Keep track of the next byte we create and how many bits we have
	// added to it out of the toBits goal.
	nextByte := byte(0)
	filledBits := uint8(0)

	for _, b := range data {

		// Discard unused bits.
		b = b << (8 - fromBits)

		// How many bits remaining to extract from the input data.
		remFromBits := fromBits
		for remFromBits > 0 {
			// How many bits remaining to be added to the next byte.
			remToBits := toBits - filledBits

			// The number of bytes to next extract is the minimum of
			// remFromBits and remToBits.
			toExtract := remFromBits
			if remToBits < toExtract {
				toExtract = remToBits
			}

			// Add the next bits to nextByte, shifting the already
			// added bits to the left.
			nextByte = (nextByte << toExtract) | (b >> (8 - toExtract))

			// Discard the bits we just extracted and get ready for
			// next iteration.
			b = b << toExtract
			remFromBits -= toExtract
			filledBits += toExtract

			// If the nextByte is completely filled, we add it to
			// our regrouped bytes and start on the next byte.
			if filledBits == toBits {
				regrouped = append(regrouped, nextByte)
				filledBits = 0
				nextByte = 0
			}
		}
	}

	// We pad any unfinished group if specified.
	if pad && filledBits > 0 {
		nextByte = nextByte << (toBits - filledBits)
		regrouped = append(regrouped, nextByte)
		filledBits = 0
		nextByte = 0
	}

	// Any incomplete group must be <= 4 bits, and all zeroes.
	if filledBits > 0 && (filledBits > 4 || nextByte != 0) {
		return nil, fmt.Errorf("invalid incomplete group")
	}

	return regrouped, nil
}

// For more details on the checksum calculation, please refer to BIP 173.
func bech32Checksum(hrp string, data []byte) []byte {
	// Convert the bytes to list of integers, as this is needed for the
	// checksum calculation.
	integers := make([]int, len(data))
	for i, b := range data {
		integers[i] = int(b)
	}
	values := append(bech32HrpExpand(hrp), integers...)
	values = append(values, []int{0, 0, 0, 0, 0, 0}...)
	polymod := bech32Polymod(values) ^ 1
	var res []byte
	for i := 0; i < 6; i++ {
		res = append(res, byte((polymod>>uint(5*(5-i)))&31))
	}
	return res
}

// For more details on the polymod calculation, please refer to BIP 173.
func bech32Polymod(values []int) int {
	chk := 1
	for _, v := range values {
		b := chk >> 25
		chk = (chk&0x1ffffff)<<5 ^ v
		for i := 0; i < 5; i++ {
			if (b>>uint(i))&1 == 1 {
				chk ^= gen[i]
			}
		}
	}
	return chk
}

// For more details on HRP expansion, please refer to BIP 173.
func bech32HrpExpand(hrp string) []int {
	v := make([]int, 0, len(hrp)*2+1)
	for i := 0; i < len(hrp); i++ {
		v = append(v, int(hrp[i]>>5))
	}
	v = append(v, 0)
	for i := 0; i < len(hrp); i++ {
		v = append(v, int(hrp[i]&31))
	}
	return v
}

// For more details on the checksum verification, please refer to BIP 173.
func bech32VerifyChecksum(hrp string, data []byte) bool {
	integers := make([]int, len(data))
	for i, b := range data {
		integers[i] = int(b)
	}
	concat := append(bech32HrpExpand(hrp), integers...)
	return bech32Polymod(concat) == 1
}


text:
package com.assylias.jbloomberg;

import org.testng.annotations.Test;

import java.time.OffsetDateTime;

import static org.testng.Assert.assertEquals;

@Test(groups = "unit")
public class AbstractIntradayRequestBuilderTest {

    private static final OffsetDateTime NOW = OffsetDateTime.now();

    @Test(expectedExceptions = NullPointerException.class)
    public void testConstructor_NullTicker() {
        new Impl(null, NOW, NOW);
    }

    @Test(expectedExceptions = IllegalArgumentException.class,
    expectedExceptionsMessageRegExp = ".*empty.*")
    public void testConstructor_EmptyTicker() {
        new Impl("", NOW, NOW);
    }

    @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*null.*")
    public void testConstructor_NullType() {
        new Impl("ABC", null, NOW, NOW);
    }

    @Test(expectedExceptions = NullPointerException.class,
    expectedExceptionsMessageRegExp = ".*start.*")
    public void testConstructor_NullStartDate() {
        new Impl("ABC", null, NOW);
    }

    @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*end.*")
    public void testConstructor_NullEndDate() {
        new Impl("ABC", NOW, null);
    }

    @Test(expectedExceptions = IllegalArgumentException.class,
    expectedExceptionsMessageRegExp = ".*date.*")
    public void testConstructor_EndBeforeStart() {
        new Impl("ABC", NOW, NOW.minusDays(1));
    }

    @Test
    public void testConstructor_AllOk() {
        new Impl("ABC", "TRADE", NOW, NOW);
    }

    @Test
    public void testServiceType() {
        assertEquals(new IntradayBarRequestBuilder("ABC", NOW, NOW).getServiceType(),
                BloombergServiceType.REFERENCE_DATA);
    }

    private static class Impl extends AbstractIntradayRequestBuilder<IntradayBarData> {
        public Impl(String ticker, OffsetDateTime startDateTime, OffsetDateTime endDateTime) {
            this(ticker, "TRADE", startDateTime, endDateTime);
        }
        public Impl(String ticker, String eventType, OffsetDateTime startDateTime, OffsetDateTime endDateTime) {
            super(ticker, eventType, startDateTime, endDateTime);
        }
        @Override
        public BloombergRequestType getRequestType() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        @Override
        public ResultParser<IntradayBarData> getResultParser() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}


text:
function insertGraph(hostName, serviceName, graphName, interval) {
	var graphAlreadyInTable = 0;
	for (var count = 0; count < top.topFrame.graphHolderArray.length; count++) {
		graphArray = top.topFrame.graphHolderArray[count];
		if (hostName == graphArray[0] && serviceName == graphArray[1] && graphName == graphArray[2]) {
			graphAlreadyInTable = 1;
			if (interval == 'hourly') {
				top.topFrame.graphHolderArray[count][3] = 1;
			} else if (interval == 'daily') {
				top.topFrame.graphHolderArray[count][4] = 1;
			} else if (interval == 'weekly') {
				top.topFrame.graphHolderArray[count][5] = 1;
			} else if (interval == 'monthly') {
				top.topFrame.graphHolderArray[count][6] = 1;
			}
			break;
		}
	}

	if (graphAlreadyInTable == 0) {
		var graphArray = new Array();
		graphArray[0] = hostName;
		graphArray[1] = serviceName;
		graphArray[2] = graphName;
		if (interval == 'hourly') {
			graphArray[3] = 1;
			graphArray[4] = 0;
			graphArray[5] = 0;
			graphArray[6] = 0;
		} else if (interval == 'daily') {
			graphArray[3] = 0;
			graphArray[4] = 1;
			graphArray[5] = 0;
			graphArray[6] = 0;
		} else if (interval == 'weekly') {
			graphArray[3] = 0;
			graphArray[4] = 0;
			graphArray[5] = 1;
			graphArray[6] = 0;
		} else if (interval == 'monthly') {
			graphArray[3] = 0;
			graphArray[4] = 0;
			graphArray[5] = 0;
			graphArray[6] = 1;
		}
		top.topFrame.graphHolderArray.push(graphArray);
	}
	parent.content.displayGraphs();
}


text:
const { saltHashPassword } = require('../store')
exports.up = async function up (knex) {
  await knex.schema.table('user', t => {
    t.string('salt').notNullable()
    t.string('encrypted_password').notNullable()
  })
  const users = await knex('user')
  await Promise.all(users.map(convertPassword))
  await knex.schema.table('user', t => {
    t.dropColumn('password')
  })
  function convertPassword (user) {
    const { salt, hash } = saltHashPassword(user.password)
    return knex('user')
      .where({ id: user.id })
      .update({
        salt,
        encrypted_password: hash
      })
  }
}
exports.down = function down (knex) {
  return knex.schema.table('user', t => {
    t.dropColumn('salt')
    t.dropColumn('encrypted_password')
    t.string('password').notNullable()
  })
}


text:
package org.loopa.element.receiver;

import org.loopa.generic.element.component.ALoopAElementComponent;
import org.loopa.generic.element.component.IMessageManager;

public abstract class AReceiver extends ALoopAElementComponent implements IReceiver {

  protected AReceiver(String id, IMessageManager imm) {
    super(id, imm);
  }

}


text:
/*
  This abstraction presents the Socket.io (and potentially other
  transports) as an EventEmiiter.  It takes care of forwarding
  the messages between the emitter and the message transport.
*/
(function() {
  var MessageManager = function(socket) {
    this.socket = socket;
    var self = this;
    //Apparently socket checks the last variable for a function callback and
    //does magic.  Have to send only the right number of arguments.
    this.onAny(function(data1, data2, data3, data4, data5) {
      if (this.event !== 'newListener') {
        if (data2 === undefined) {
          socket.emit(this.event,data1);
        } else if (data3 === undefined){
          socket.emit(this.event,data1,data2);
        } else if (data4 === undefined){
          socket.emit(this.event,data1,data2,data3);
        } else if (data4 === undefined){
          socket.emit(this.event,data1,data2,data3,data4);
        } else {
          socket.emit(this.event, data1, data2, data3, data4, data5);
        }
      }
    });

    this.withHistory = {
      on: function on(aType, aListener){
            self.socket.withHistory.on(aType,aListener);
          }
    }

    this.on('newListener', function(aType, aListener) {
      if (aType!=='*'){
        socket.on(aType, aListener);
      }
    });
    return this;
  };
  MessageManager.prototype = new EventEmitter2({ newListener: true, wildcard: true });
  MessageManager.prototype.constructor = MessageManager;

  window.MessageManager = MessageManager;
})();


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Metronic | Form Tools</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta content="" name="description"/>
    <meta content="" name="author"/>

    <link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="../../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="../../assets/global/plugins/typeahead/typeahead.css">

    <link href="../../assets/global/css/components-rounded.css" id="style_components" rel="stylesheet" type="text/css">

    <link href="../../assets/admin/layout3/css/custom.css" rel="stylesheet" type="text/css">

    <link rel="shortcut icon" href="favicon.ico"/>

                    Twitter Auto Complete(typeahead.js)

                <form action="javascript:;" id="form-username" class="form-horizontal form-bordered">

                        Basic Auto Complete

                                <input type="text" id="typeahead_example_1" name="typeahead_example_1" class="form-control"/>

                                E.g: metronic, keenthemes.

											Learn more:

                                    http://twitter.github.io/typeahead.js/

                        Country Auto Complete

                                <input type="text" id="typeahead_example_2" name="typeahead_example_2" class="form-control"/>

                                E.g: USA, Malaysia. Prefetch from JSON source

                        Custom Template

                                <input type="text" id="typeahead_example_3" name="typeahead_example_3" class="form-control"/>

                                Uses a precompiled template to customize look of suggestion.

                        Multiple Sections with Headers

                                <input type="text" id="typeahead_example_4" name="typeahead_example_4" class="form-control"/>

                                Two datasets that are prefetched, stored, and searched on the client. Highlighting is enabled.

                        Modal

                                View in Modal

                </form>

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Radio Switch in Modal

                                <form action="javascript:;" class="form-horizontal form-row-seperated">

                                        Basic Auto Complete

                                                <input type="text" id="typeahead_example_modal_1" name="typeahead_example_modal_1" class="form-control"/>

                                                E.g: metronic, keenthemes.

															Learn more:

                                                    http://twitter.github.io/typeahead.js/

                                        Country Auto Complete

                                                <input type="text" id="typeahead_example_modal_2" name="typeahead_example_modal_2" class="form-control"/>

                                                E.g: USA, Malaysia. Prefetch from JSON source

                                        Custom Template

                                                <input type="text" id="typeahead_example_modal_3" name="typeahead_example_modal_3" class="form-control"/>

                                                Uses a precompiled template to customize look of suggestion.

                                        Multiple Sections with Headers

                                                <input type="text" id="typeahead_example_modal_4" name="typeahead_example_modal_4" class="form-control"/>

                                                Two datasets that are prefetched, stored, and searched on the client. Highlighting is enabled.

                                </form>

                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                <button type="button" class="btn btn-primary"> Save changes</button>


text:
package org.achtern.AchternEngine.core.resource.loader;

import java.io.InputStream;

/**
 * A {@link org.achtern.AchternEngine.core.resource.loader.BinaryLoader} is
 *  able to read an Object from an {@link java.io.InputStream}. Technically,
 *  this could also read a text-file, but in this case the {@link org.achtern.AchternEngine.core.resource.loader.AsciiFileLoader}
 *  is better suited.
 *
 * The cached object should be a data object, otherwise the {@link org.achtern.AchternEngine.core.resource.ResourceLoader}
 *  would turn into a singelton container. Caching is still handled in the ResourceLoader
 *
 * @param <T> Type of object which can be loaded by the Loader
 * @param <C> Type of object that is cached.
 */
public abstract class BinaryLoader<T, C> implements Loader<T, InputStream> {

    /**
     * The cached value.
     */
    private C cache;

    /**
     * This method should construct the object from a cached
     * value provided by the ResourceLoader
     * @param value Cache
     * @return Object
     * @throws Exception could be anything (from loading over parsing to memory errors)
     */
    public abstract T fromCache(C value) throws Exception;

    /**
     * Returns the Type of the Cache data.
     * @return data type
     */
    public abstract Class<C> getCacheType();

    /**
     * Returns a generated cache item.
     * This cache value should be set in
     * {@link #get()}
     * @return Cache
     */
    public C getCache() {
        return cache;
    }

    /**
     * Caches the value.
     * Should be called from within {@link #get()}
     * @param cache value to cache
     */
    protected void cache(C cache) {
        this.cache = cache;
    }
}


text:
using UnityEngine;
using System.Collections;

public class BaseMovement : Movement
{
	protected Transform transform;
	protected float speed;
	protected StepType step;
	private bool terrestrial;
	private Vector3 offset;

	protected float duration;
	private float phase;

	public bool Ended {
		get {
			return phase == 1;
		}
	}

	public BaseMovement(Transform transform, float speed, StepType step, bool terrestrial, Vector3? offset)
	{
		this.transform = transform;
		this.speed = speed;
		this.step = step;
		this.terrestrial = terrestrial;
		this.offset = offset == null ? Vector3.zero : (Vector3) offset;

		this.phase = 1; // Movement start ended
	}

	public virtual void Update(Vector3 to)
	{
		phase = 0;
	}

	public virtual void Step()
	{
		phase += Time.deltaTime / duration;
		if (phase > 1) {
			phase = 1;
		}
	}

	protected float getStep()
	{
		return step.GetStep(phase);
	}

	protected Vector3 correctDestination(Vector3 from, Vector3 to)
	{
		to = to + offset;
		return terrestrial ? new Vector3(to.x, from.y, to.z) : to;
	}
}


text:
package org.jbromo.sample.server.services.test.usergroup;

import javax.inject.Inject;

import lombok.AccessLevel;
import lombok.Getter;

import org.jbromo.sample.server.model.src.UserGroup;
import org.jbromo.sample.server.services.src.usergroup.IUserGroupService;
import org.jbromo.sample.server.services.test.AbstractEntityServiceTest;
import org.jbromo.service.Service;

/**
 * Define the UserGroup service test.
 *
 * @author qjafcunuas
 *
 */
public abstract class AbstractUserGroupServiceTestImpl extends
        AbstractEntityServiceTest<UserGroup, Long> {

    /**
     * The service to test.
     */
    @Inject
    @Service
    @Getter(AccessLevel.PROTECTED)
    private IUserGroupService crud;

}


text:
namespace browser_sync {

class TestHttpBridge : public syncer::HttpPostProviderInterface {
 public:
  // Begin syncer::HttpPostProviderInterface implementation:
  void SetExtraRequestHeaders(const char* headers) override {}

  void SetURL(const char* url, int port) override {}

  void SetPostPayload(const char* content_type,
                      int content_length,
                      const char* content) override {}

  bool MakeSynchronousPost(int* error_code, int* response_code) override;

  int GetResponseContentLength() const override;

  const char* GetResponseContent() const override;

  const std::string GetResponseHeaderValue(const std::string&) const override;

  void Abort() override;
  // End syncer::HttpPostProviderInterface implementation.
};

class TestHttpBridgeFactory : public syncer::HttpPostProviderFactory {
 public:
  TestHttpBridgeFactory();
  ~TestHttpBridgeFactory() override;

  // syncer::HttpPostProviderFactory:
  void Init(
      const std::string& user_agent,
      const syncer::BindToTrackerCallback& bind_to_tracker_callback) override;
  syncer::HttpPostProviderInterface* Create() override;
  void Destroy(syncer::HttpPostProviderInterface* http) override;
};

}  // namespace browser_sync

#endif  // COMPONENTS_BROWSER_SYNC_BROWSER_TEST_HTTP_BRIDGE_FACTORY_H_