text:
/* Automatically generated nanopb header */
/* Generated by nanopb-0.3.9.8 */

#ifndef PB_GOOGLE_FIRESTORE_V1_QUERY_NANOPB_H_INCLUDED
#define PB_GOOGLE_FIRESTORE_V1_QUERY_NANOPB_H_INCLUDED
#include <pb.h>

#include "google/firestore/v1/document.nanopb.h"

#include "google/protobuf/wrappers.nanopb.h"

#include <string>

namespace firebase {
namespace firestore {

/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif

/* Enum definitions */
typedef enum _google_firestore_v1_StructuredQuery_Direction {
    google_firestore_v1_StructuredQuery_Direction_DIRECTION_UNSPECIFIED = 0,
    google_firestore_v1_StructuredQuery_Direction_ASCENDING = 1,
    google_firestore_v1_StructuredQuery_Direction_DESCENDING = 2
} google_firestore_v1_StructuredQuery_Direction;
#define _google_firestore_v1_StructuredQuery_Direction_MIN google_firestore_v1_StructuredQuery_Direction_DIRECTION_UNSPECIFIED
#define _google_firestore_v1_StructuredQuery_Direction_MAX google_firestore_v1_StructuredQuery_Direction_DESCENDING
#define _google_firestore_v1_StructuredQuery_Direction_ARRAYSIZE ((google_firestore_v1_StructuredQuery_Direction)(google_firestore_v1_StructuredQuery_Direction_DESCENDING+1))

typedef enum _google_firestore_v1_StructuredQuery_CompositeFilter_Operator {
    google_firestore_v1_StructuredQuery_CompositeFilter_Operator_OPERATOR_UNSPECIFIED = 0,
    google_firestore_v1_StructuredQuery_CompositeFilter_Operator_AND = 1,
    google_firestore_v1_StructuredQuery_CompositeFilter_Operator_OR = 2
} google_firestore_v1_StructuredQuery_CompositeFilter_Operator;
#define _google_firestore_v1_StructuredQuery_CompositeFilter_Operator_MIN google_firestore_v1_StructuredQuery_CompositeFilter_Operator_OPERATOR_UNSPECIFIED
#define _google_firestore_v1_StructuredQuery_CompositeFilter_Operator_MAX google_firestore_v1_StructuredQuery_CompositeFilter_Operator_OR
#define _google_firestore_v1_StructuredQuery_CompositeFilter_Operator_ARRAYSIZE ((google_firestore_v1_StructuredQuery_CompositeFilter_Operator)(google_firestore_v1_StructuredQuery_CompositeFilter_Operator_OR+1))

typedef enum _google_firestore_v1_StructuredQuery_FieldFilter_Operator {
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_OPERATOR_UNSPECIFIED = 0,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_LESS_THAN = 1,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_LESS_THAN_OR_EQUAL = 2,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_GREATER_THAN = 3,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_GREATER_THAN_OR_EQUAL = 4,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_EQUAL = 5,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_NOT_EQUAL = 6,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_ARRAY_CONTAINS = 7,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_IN = 8,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_ARRAY_CONTAINS_ANY = 9,
    google_firestore_v1_StructuredQuery_FieldFilter_Operator_NOT_IN = 10
} google_firestore_v1_StructuredQuery_FieldFilter_Operator;
#define _google_firestore_v1_StructuredQuery_FieldFilter_Operator_MIN google_firestore_v1_StructuredQuery_FieldFilter_Operator_OPERATOR_UNSPECIFIED
#define _google_firestore_v1_StructuredQuery_FieldFilter_Operator_MAX google_firestore_v1_StructuredQuery_FieldFilter_Operator_NOT_IN
#define _google_firestore_v1_StructuredQuery_FieldFilter_Operator_ARRAYSIZE ((google_firestore_v1_StructuredQuery_FieldFilter_Operator)(google_firestore_v1_StructuredQuery_FieldFilter_Operator_NOT_IN+1))

typedef enum _google_firestore_v1_StructuredQuery_UnaryFilter_Operator {
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator_OPERATOR_UNSPECIFIED = 0,
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator_IS_NAN = 2,
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator_IS_NULL = 3,
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator_IS_NOT_NAN = 4,
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator_IS_NOT_NULL = 5
} google_firestore_v1_StructuredQuery_UnaryFilter_Operator;
#define _google_firestore_v1_StructuredQuery_UnaryFilter_Operator_MIN google_firestore_v1_StructuredQuery_UnaryFilter_Operator_OPERATOR_UNSPECIFIED
#define _google_firestore_v1_StructuredQuery_UnaryFilter_Operator_MAX google_firestore_v1_StructuredQuery_UnaryFilter_Operator_IS_NOT_NULL
#define _google_firestore_v1_StructuredQuery_UnaryFilter_Operator_ARRAYSIZE ((google_firestore_v1_StructuredQuery_UnaryFilter_Operator)(google_firestore_v1_StructuredQuery_UnaryFilter_Operator_IS_NOT_NULL+1))

/* Struct definitions */
typedef struct _google_firestore_v1_StructuredQuery_FieldReference {
    pb_bytes_array_t *field_path;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_FieldReference) */
} google_firestore_v1_StructuredQuery_FieldReference;

typedef struct _google_firestore_v1_StructuredQuery_Projection {
    pb_size_t fields_count;
    struct _google_firestore_v1_StructuredQuery_FieldReference *fields;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_Projection) */
} google_firestore_v1_StructuredQuery_Projection;

typedef struct _google_firestore_v1_Cursor {
    pb_size_t values_count;
    struct _google_firestore_v1_Value *values;
    bool before;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_Cursor) */
} google_firestore_v1_Cursor;

typedef struct _google_firestore_v1_StructuredAggregationQuery_Aggregation_Count {
    google_protobuf_Int64Value up_to;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredAggregationQuery_Aggregation_Count) */
} google_firestore_v1_StructuredAggregationQuery_Aggregation_Count;

typedef struct _google_firestore_v1_StructuredQuery_CollectionSelector {
    pb_bytes_array_t *collection_id;
    bool all_descendants;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_CollectionSelector) */
} google_firestore_v1_StructuredQuery_CollectionSelector;

typedef struct _google_firestore_v1_StructuredQuery_CompositeFilter {
    google_firestore_v1_StructuredQuery_CompositeFilter_Operator op;
    pb_size_t filters_count;
    struct _google_firestore_v1_StructuredQuery_Filter *filters;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_CompositeFilter) */
} google_firestore_v1_StructuredQuery_CompositeFilter;

typedef struct _google_firestore_v1_StructuredQuery_FieldFilter {
    google_firestore_v1_StructuredQuery_FieldReference field;
    google_firestore_v1_StructuredQuery_FieldFilter_Operator op;
    google_firestore_v1_Value value;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_FieldFilter) */
} google_firestore_v1_StructuredQuery_FieldFilter;

typedef struct _google_firestore_v1_StructuredQuery_Order {
    google_firestore_v1_StructuredQuery_FieldReference field;
    google_firestore_v1_StructuredQuery_Direction direction;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_Order) */
} google_firestore_v1_StructuredQuery_Order;

typedef struct _google_firestore_v1_StructuredQuery_UnaryFilter {
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator op;
    pb_size_t which_operand_type;
    union {
        google_firestore_v1_StructuredQuery_FieldReference field;
    };

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_UnaryFilter) */
} google_firestore_v1_StructuredQuery_UnaryFilter;

typedef struct _google_firestore_v1_StructuredAggregationQuery_Aggregation {
    pb_size_t which_operator;
    union {
        google_firestore_v1_StructuredAggregationQuery_Aggregation_Count count;
    };
    pb_bytes_array_t *alias;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredAggregationQuery_Aggregation) */
} google_firestore_v1_StructuredAggregationQuery_Aggregation;

typedef struct _google_firestore_v1_StructuredQuery_Filter {
    pb_size_t which_filter_type;
    union {
        google_firestore_v1_StructuredQuery_CompositeFilter composite_filter;
        google_firestore_v1_StructuredQuery_FieldFilter field_filter;
        google_firestore_v1_StructuredQuery_UnaryFilter unary_filter;
    };

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery_Filter) */
} google_firestore_v1_StructuredQuery_Filter;

typedef struct _google_firestore_v1_StructuredQuery {
    google_firestore_v1_StructuredQuery_Projection select;
    pb_size_t from_count;
    struct _google_firestore_v1_StructuredQuery_CollectionSelector *from;
    google_firestore_v1_StructuredQuery_Filter where;
    pb_size_t order_by_count;
    struct _google_firestore_v1_StructuredQuery_Order *order_by;
    bool has_limit;
    google_protobuf_Int32Value limit;
    int32_t offset;
    google_firestore_v1_Cursor start_at;
    google_firestore_v1_Cursor end_at;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredQuery) */
} google_firestore_v1_StructuredQuery;

typedef struct _google_firestore_v1_StructuredAggregationQuery {
    pb_size_t which_query_type;
    union {
        google_firestore_v1_StructuredQuery structured_query;
    };
    pb_size_t aggregations_count;
    struct _google_firestore_v1_StructuredAggregationQuery_Aggregation *aggregations;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_firestore_v1_StructuredAggregationQuery) */
} google_firestore_v1_StructuredAggregationQuery;

/* Default values for struct fields */

/* Initializer values for message structs */
#define google_firestore_v1_StructuredQuery_init_default {google_firestore_v1_StructuredQuery_Projection_init_default, 0, NULL, google_firestore_v1_StructuredQuery_Filter_init_default, 0, NULL, false, google_protobuf_Int32Value_init_default, 0, google_firestore_v1_Cursor_init_default, google_firestore_v1_Cursor_init_default}
#define google_firestore_v1_StructuredQuery_CollectionSelector_init_default {NULL, 0}
#define google_firestore_v1_StructuredQuery_Filter_init_default {0, {google_firestore_v1_StructuredQuery_CompositeFilter_init_default}}
#define google_firestore_v1_StructuredQuery_CompositeFilter_init_default {_google_firestore_v1_StructuredQuery_CompositeFilter_Operator_MIN, 0, NULL}
#define google_firestore_v1_StructuredQuery_FieldFilter_init_default {google_firestore_v1_StructuredQuery_FieldReference_init_default, _google_firestore_v1_StructuredQuery_FieldFilter_Operator_MIN, google_firestore_v1_Value_init_default}
#define google_firestore_v1_StructuredQuery_UnaryFilter_init_default {_google_firestore_v1_StructuredQuery_UnaryFilter_Operator_MIN, 0, {google_firestore_v1_StructuredQuery_FieldReference_init_default}}
#define google_firestore_v1_StructuredQuery_Order_init_default {google_firestore_v1_StructuredQuery_FieldReference_init_default, _google_firestore_v1_StructuredQuery_Direction_MIN}
#define google_firestore_v1_StructuredQuery_FieldReference_init_default {NULL}
#define google_firestore_v1_StructuredQuery_Projection_init_default {0, NULL}
#define google_firestore_v1_StructuredAggregationQuery_init_default {0, {google_firestore_v1_StructuredQuery_init_default}, 0, NULL}
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_init_default {0, {google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_init_default}, NULL}
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_init_default {google_protobuf_Int64Value_init_default}
#define google_firestore_v1_Cursor_init_default  {0, NULL, 0}
#define google_firestore_v1_StructuredQuery_init_zero {google_firestore_v1_StructuredQuery_Projection_init_zero, 0, NULL, google_firestore_v1_StructuredQuery_Filter_init_zero, 0, NULL, false, google_protobuf_Int32Value_init_zero, 0, google_firestore_v1_Cursor_init_zero, google_firestore_v1_Cursor_init_zero}
#define google_firestore_v1_StructuredQuery_CollectionSelector_init_zero {NULL, 0}
#define google_firestore_v1_StructuredQuery_Filter_init_zero {0, {google_firestore_v1_StructuredQuery_CompositeFilter_init_zero}}
#define google_firestore_v1_StructuredQuery_CompositeFilter_init_zero {_google_firestore_v1_StructuredQuery_CompositeFilter_Operator_MIN, 0, NULL}
#define google_firestore_v1_StructuredQuery_FieldFilter_init_zero {google_firestore_v1_StructuredQuery_FieldReference_init_zero, _google_firestore_v1_StructuredQuery_FieldFilter_Operator_MIN, google_firestore_v1_Value_init_zero}
#define google_firestore_v1_StructuredQuery_UnaryFilter_init_zero {_google_firestore_v1_StructuredQuery_UnaryFilter_Operator_MIN, 0, {google_firestore_v1_StructuredQuery_FieldReference_init_zero}}
#define google_firestore_v1_StructuredQuery_Order_init_zero {google_firestore_v1_StructuredQuery_FieldReference_init_zero, _google_firestore_v1_StructuredQuery_Direction_MIN}
#define google_firestore_v1_StructuredQuery_FieldReference_init_zero {NULL}
#define google_firestore_v1_StructuredQuery_Projection_init_zero {0, NULL}
#define google_firestore_v1_StructuredAggregationQuery_init_zero {0, {google_firestore_v1_StructuredQuery_init_zero}, 0, NULL}
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_init_zero {0, {google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_init_zero}, NULL}
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_init_zero {google_protobuf_Int64Value_init_zero}
#define google_firestore_v1_Cursor_init_zero     {0, NULL, 0}

/* Field tags (for use in manual encoding/decoding) */
#define google_firestore_v1_StructuredQuery_FieldReference_field_path_tag 2
#define google_firestore_v1_StructuredQuery_Projection_fields_tag 2
#define google_firestore_v1_Cursor_values_tag    1
#define google_firestore_v1_Cursor_before_tag    2
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_up_to_tag 1
#define google_firestore_v1_StructuredQuery_CollectionSelector_collection_id_tag 2
#define google_firestore_v1_StructuredQuery_CollectionSelector_all_descendants_tag 3
#define google_firestore_v1_StructuredQuery_CompositeFilter_op_tag 1
#define google_firestore_v1_StructuredQuery_CompositeFilter_filters_tag 2
#define google_firestore_v1_StructuredQuery_FieldFilter_field_tag 1
#define google_firestore_v1_StructuredQuery_FieldFilter_op_tag 2
#define google_firestore_v1_StructuredQuery_FieldFilter_value_tag 3
#define google_firestore_v1_StructuredQuery_Order_field_tag 1
#define google_firestore_v1_StructuredQuery_Order_direction_tag 2
#define google_firestore_v1_StructuredQuery_UnaryFilter_field_tag 2
#define google_firestore_v1_StructuredQuery_UnaryFilter_op_tag 1
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_count_tag 1
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_alias_tag 7
#define google_firestore_v1_StructuredQuery_Filter_composite_filter_tag 1
#define google_firestore_v1_StructuredQuery_Filter_field_filter_tag 2
#define google_firestore_v1_StructuredQuery_Filter_unary_filter_tag 3
#define google_firestore_v1_StructuredQuery_select_tag 1
#define google_firestore_v1_StructuredQuery_from_tag 2
#define google_firestore_v1_StructuredQuery_where_tag 3
#define google_firestore_v1_StructuredQuery_order_by_tag 4
#define google_firestore_v1_StructuredQuery_start_at_tag 7
#define google_firestore_v1_StructuredQuery_end_at_tag 8
#define google_firestore_v1_StructuredQuery_offset_tag 6
#define google_firestore_v1_StructuredQuery_limit_tag 5
#define google_firestore_v1_StructuredAggregationQuery_structured_query_tag 1
#define google_firestore_v1_StructuredAggregationQuery_aggregations_tag 3

/* Struct field encoding specification for nanopb */
extern const pb_field_t google_firestore_v1_StructuredQuery_fields[9];
extern const pb_field_t google_firestore_v1_StructuredQuery_CollectionSelector_fields[3];
extern const pb_field_t google_firestore_v1_StructuredQuery_Filter_fields[4];
extern const pb_field_t google_firestore_v1_StructuredQuery_CompositeFilter_fields[3];
extern const pb_field_t google_firestore_v1_StructuredQuery_FieldFilter_fields[4];
extern const pb_field_t google_firestore_v1_StructuredQuery_UnaryFilter_fields[3];
extern const pb_field_t google_firestore_v1_StructuredQuery_Order_fields[3];
extern const pb_field_t google_firestore_v1_StructuredQuery_FieldReference_fields[2];
extern const pb_field_t google_firestore_v1_StructuredQuery_Projection_fields[2];
extern const pb_field_t google_firestore_v1_StructuredAggregationQuery_fields[3];
extern const pb_field_t google_firestore_v1_StructuredAggregationQuery_Aggregation_fields[3];
extern const pb_field_t google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_fields[2];
extern const pb_field_t google_firestore_v1_Cursor_fields[3];

/* Maximum encoded size of messages (where known) */
/* google_firestore_v1_StructuredQuery_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_CollectionSelector_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_Filter_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_CompositeFilter_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_FieldFilter_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_UnaryFilter_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_Order_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_FieldReference_size depends on runtime parameters */
/* google_firestore_v1_StructuredQuery_Projection_size depends on runtime parameters */
/* google_firestore_v1_StructuredAggregationQuery_size depends on runtime parameters */
/* google_firestore_v1_StructuredAggregationQuery_Aggregation_size depends on runtime parameters */
#define google_firestore_v1_StructuredAggregationQuery_Aggregation_Count_size 13
/* google_firestore_v1_Cursor_size depends on runtime parameters */

/* Message IDs (where set with "msgid" option) */
#ifdef PB_MSGID

#define QUERY_MESSAGES \

#endif

const char* EnumToString(google_firestore_v1_StructuredQuery_Direction value);
const char* EnumToString(
    google_firestore_v1_StructuredQuery_CompositeFilter_Operator value);
const char* EnumToString(
    google_firestore_v1_StructuredQuery_FieldFilter_Operator value);
const char* EnumToString(
    google_firestore_v1_StructuredQuery_UnaryFilter_Operator value);
}  // namespace firestore
}  // namespace firebase

/* @@protoc_insertion_point(eof) */

#endif


text:
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash #-}
{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  Control.Exception.Base
-- Copyright   :  (c) The University of Glasgow 2001
-- License     :  BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer  :  libraries@haskell.org
-- Stability   :  experimental
-- Portability :  non-portable (extended exceptions)
--
-- Extensible exceptions, except for multiple handlers.
--
-----------------------------------------------------------------------------

module Control.Exception.Base (

        -- * The Exception type
        SomeException(..),
        Exception(..),
        IOException,
        ArithException(..),
        ArrayException(..),
        AssertionFailed(..),
        SomeAsyncException(..), AsyncException(..),
        asyncExceptionToException, asyncExceptionFromException,
        NonTermination(..),
        NestedAtomically(..),
        BlockedIndefinitelyOnMVar(..),
        BlockedIndefinitelyOnSTM(..),
        AllocationLimitExceeded(..),
        Deadlock(..),
        NoMethodError(..),
        PatternMatchFail(..),
        RecConError(..),
        RecSelError(..),
        RecUpdError(..),
        ErrorCall(..),

        -- * Throwing exceptions
        throwIO,
        throw,
        ioError,
        throwTo,

        -- * Catching Exceptions

        -- ** The @catch@ functions
        catch,
        catchJust,

        -- ** The @handle@ functions
        handle,
        handleJust,

        -- ** The @try@ functions
        try,
        tryJust,
        onException,

        -- ** The @evaluate@ function
        evaluate,

        -- ** The @mapException@ function
        mapException,

        -- * Asynchronous Exceptions

        -- ** Asynchronous exception control
        mask,
        mask_,
        uninterruptibleMask,
        uninterruptibleMask_,
        MaskingState(..),
        getMaskingState,

        -- * Assertions

        assert,

        -- * Utilities

        bracket,
        bracket_,
        bracketOnError,

        finally,

        -- * Calls for GHC runtime
        recSelError, recConError, irrefutPatError, runtimeError,
        nonExhaustiveGuardsError, patError, noMethodBindingError,
        absentError,
        nonTermination, nestedAtomically,
  ) where

import GHC.Base
import GHC.IO hiding (bracket,finally,onException)
import GHC.IO.Exception
import {-# SOURCE #-} GHC.Exception
import GHC.Show
-- import GHC.Exception hiding ( Exception )
import GHC.Conc.Sync

import Data.Dynamic
import Data.Either

-----------------------------------------------------------------------------
-- Catching exceptions

-- |This is the simplest of the exception-catching functions.  It
-- takes a single argument, runs it, and if an exception is raised
-- the \"handler\" is executed, with the value of the exception passed as an
-- argument.  Otherwise, the result is returned as normal.  For example:
--
-- >   catch (readFile f)
-- >         (\e -> do let err = show (e :: IOException)
-- >                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
-- >                   return "")
--
-- Note that we have to give a type signature to @e@, or the program
-- will not typecheck as the type is ambiguous. While it is possible
-- to catch exceptions of any type, see the section \"Catching all
-- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
--
-- For catching exceptions in pure (non-'IO') expressions, see the
-- function 'evaluate'.
--
-- Note that due to Haskell\'s unspecified evaluation order, an
-- expression may throw one of several possible exceptions: consider
-- the expression @(error \"urk\") + (1 \`div\` 0)@.  Does
-- the expression throw
-- @ErrorCall \"urk\"@, or @DivideByZero@?
--
-- The answer is \"it might throw either\"; the choice is
-- non-deterministic. If you are catching any type of exception then you
-- might catch either. If you are calling @catch@ with type
-- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
-- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
-- exception may be propogated further up. If you call it again, you
-- might get a the opposite behaviour. This is ok, because 'catch' is an
-- 'IO' computation.
--
catch   :: Exception e
        => IO a         -- ^ The computation to run
        -> (e -> IO a)  -- ^ Handler to invoke if an exception is raised
        -> IO a
catch = catchException

-- | The function 'catchJust' is like 'catch', but it takes an extra
-- argument which is an /exception predicate/, a function which
-- selects which type of exceptions we\'re interested in.
--
-- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- >           (readFile f)
-- >           (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- >                     return "")
--
-- Any other exceptions which are not matched by the predicate
-- are re-raised, and may be caught by an enclosing
-- 'catch', 'catchJust', etc.
catchJust
        :: Exception e
        => (e -> Maybe b)         -- ^ Predicate to select exceptions
        -> IO a                   -- ^ Computation to run
        -> (b -> IO a)            -- ^ Handler
        -> IO a
catchJust p a handler = catch a handler'
  where handler' e = case p e of
                        Nothing -> throwIO e
                        Just b  -> handler b

-- | A version of 'catch' with the arguments swapped around; useful in
-- situations where the code for the handler is shorter.  For example:
--
-- >   do handle (\NonTermination -> exitWith (ExitFailure 1)) $
-- >      ...
handle     :: Exception e => (e -> IO a) -> IO a -> IO a
handle     =  flip catch

-- | A version of 'catchJust' with the arguments swapped around (see
-- 'handle').
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p =  flip (catchJust p)

-----------------------------------------------------------------------------
-- 'mapException'

-- | This function maps one exception into another as proposed in the
-- paper \"A semantics for imprecise exceptions\".

-- Notice that the usage of 'unsafePerformIO' is safe here.

mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
                                          (\x -> throwIO (f x)))

-----------------------------------------------------------------------------
-- 'try' and variations.

-- | Similar to 'catch', but returns an 'Either' result which is
-- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@
-- if an exception of type @e@ was raised and its value is @ex@.
-- If any other type of exception is raised than it will be propogated
-- up to the next enclosing exception handler.
--
-- >  try a = catch (Right `liftM` a) (return . Left)

try :: Exception e => IO a -> IO (Either e a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))

-- | A variant of 'try' that takes an exception predicate to select
-- which exceptions are caught (c.f. 'catchJust').  If the exception
-- does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
  r <- try a
  case r of
        Right v -> return (Right v)
        Left  e -> case p e of
                        Nothing -> throwIO e
                        Just b  -> return (Left b)

-- | Like 'finally', but only performs the final action if there was an
-- exception raised by the computation.
onException :: IO a -> IO b -> IO a
onException io what = io `catch` \e -> do _ <- what
                                          throwIO (e :: SomeException)

-----------------------------------------------------------------------------
-- Some Useful Functions

-- | When you want to acquire a resource, do some work with it, and
-- then release the resource, it is a good idea to use 'bracket',
-- because 'bracket' will install the necessary exception handler to
-- release the resource in the event that an exception is raised
-- during the computation.  If an exception is raised, then 'bracket' will
-- re-raise the exception (after performing the release).
--
-- A common example is opening a file:
--
-- > bracket
-- >   (openFile "filename" ReadMode)
-- >   (hClose)
-- >   (\fileHandle -> do { ... })
--
-- The arguments to 'bracket' are in this order so that we can partially apply
-- it, e.g.:
--
-- > withFile name mode = bracket (openFile name mode) hClose
--
bracket
        :: IO a         -- ^ computation to run first (\"acquire resource\")
        -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
        -> (a -> IO c)  -- ^ computation to run in-between
        -> IO c         -- returns the value from the in-between computation
bracket before after thing =
  mask $ \restore -> do
    a <- before
    r <- restore (thing a) `onException` after a
    _ <- after a
    return r

-- | A specialised variant of 'bracket' with just a computation to run
-- afterward.
--
finally :: IO a         -- ^ computation to run first
        -> IO b         -- ^ computation to run afterward (even if an exception
                        -- was raised)
        -> IO a         -- returns the value from the first computation
a `finally` sequel =
  mask $ \restore -> do
    r <- restore a `onException` sequel
    _ <- sequel
    return r

-- | A variant of 'bracket' where the return value from the first computation
-- is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)

-- | Like 'bracket', but only performs the final action if there was an
-- exception raised by the in-between computation.
bracketOnError
        :: IO a         -- ^ computation to run first (\"acquire resource\")
        -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
        -> (a -> IO c)  -- ^ computation to run in-between
        -> IO c         -- returns the value from the in-between computation
bracketOnError before after thing =
  mask $ \restore -> do
    a <- before
    restore (thing a) `onException` after a

-----

-- |A pattern match failed. The @String@ gives information about the
-- source location of the pattern.
data PatternMatchFail = PatternMatchFail String deriving Typeable

instance Show PatternMatchFail where
    showsPrec _ (PatternMatchFail err) = showString err

instance Exception PatternMatchFail

-----

-- |A record selector was applied to a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record selector.
data RecSelError = RecSelError String deriving Typeable

instance Show RecSelError where
    showsPrec _ (RecSelError err) = showString err

instance Exception RecSelError

-----

-- |An uninitialised record field was used. The @String@ gives
-- information about the source location where the record was
-- constructed.
data RecConError = RecConError String deriving Typeable

instance Show RecConError where
    showsPrec _ (RecConError err) = showString err

instance Exception RecConError

-----

-- |A record update was performed on a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record update.
data RecUpdError = RecUpdError String deriving Typeable

instance Show RecUpdError where
    showsPrec _ (RecUpdError err) = showString err

instance Exception RecUpdError

-----

-- |A class method without a definition (neither a default definition,
-- nor a definition in the appropriate instance) was called. The
-- @String@ gives information about which method it was.
data NoMethodError = NoMethodError String deriving Typeable

instance Show NoMethodError where
    showsPrec _ (NoMethodError err) = showString err

instance Exception NoMethodError

-----

-- |Thrown when the runtime system detects that the computation is
-- guaranteed not to terminate. Note that there is no guarantee that
-- the runtime system will notice whether any given computation is
-- guaranteed to terminate or not.
data NonTermination = NonTermination deriving Typeable

instance Show NonTermination where
    showsPrec _ NonTermination = showString "<<loop>>"

instance Exception NonTermination

-----

-- |Thrown when the program attempts to call @atomically@, from the @stm@
-- package, inside another call to @atomically@.
data NestedAtomically = NestedAtomically deriving Typeable

instance Show NestedAtomically where
    showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"

instance Exception NestedAtomically

-----

recSelError, recConError, irrefutPatError, runtimeError,
  nonExhaustiveGuardsError, patError, noMethodBindingError,
  absentError
        :: Addr# -> a   -- All take a UTF8-encoded C string

recSelError              s = throw (RecSelError ("No match in record selector "
                                                 ++ unpackCStringUtf8# s))  -- No location info unfortunately
runtimeError             s = error (unpackCStringUtf8# s)                   -- No location info unfortunately
absentError              s = error ("Oops!  Entered absent arg " ++ unpackCStringUtf8# s)

nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
irrefutPatError          s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
recConError              s = throw (RecConError      (untangle s "Missing field in record construction"))
noMethodBindingError     s = throw (NoMethodError    (untangle s "No instance nor default method for class operation"))
patError                 s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))

-- GHC's RTS calls this
nonTermination :: SomeException
nonTermination = toException NonTermination

-- GHC's RTS calls this
nestedAtomically :: SomeException
nestedAtomically = toException NestedAtomically

redpajama_set_name: RedPajamaGithub


text:
new line: two spaces + enter at the end of the line

    a line that's indented

* bullet or
- bullet
    + indent (tab)

1. or ordered
    1. indent

* [ ] checklist
* [x] clicked

---

**bold** or __bold__

*italic* or _italic_

underline

~~strike through~~

hightlight

fontsubscript orsuperscript

***

[text as link](link)

clickable: <user@gmail.com> or <http://homepage.com>

insert image: ![(image name)](link)
or:

math: <math> <mn>1</mn> <mo>+</mo> <mi>a</mi> </math>

`show as it is`

```
a section of codes
```

~~~python
codes
~~~

    or simply start with a tab

>quote with `>`
>>indented

Table header | left aligned | centered | right aligned
--- | :--- |:---:| ---:
content | content | content | content


text:
const DrawCard = require('../../../drawcard.js');

class TakeTheBlack extends DrawCard {
    canPlay(player, card) {
        if(player !== this.controller || this !== card) {
            return false;
        }

        if(this.game.currentPhase !== 'dominance') {
            return false;
        }

        return true;
    }

    play(player) {
        if(!this.canPlay(player, this)) {
            return;
        }

        this.game.promptForSelect(player, {
            activePromptTitle: 'Select a character',
            waitingPromptTitle: 'Waiting for opponent to use ' + this.name,
            cardCondition: card => this.cardCondition(card),
            onSelect: (player, card) => this.onCardClicked(player, card)
        });
    }

    cardCondition(card) {
        if(card.controller === this.choosingPlayer || card.getType() !== 'character' || card.isUnique() || card.getCost() > 6) {
            return false;
        }

        return true;
    }

    onCardClicked(player, card) {
        this.game.takeControl(player, card);

        this.game.addMessage('{0} uses {1} to take control of {2}', player, this, card);

        return true;
    }
}

TakeTheBlack.code = '01139';

module.exports = TakeTheBlack;


text:
<?php
/**
 * @name         View Owner
 * @version      0.1
 * @author       Akila Ravihansa Perera <ravihansa3000@gmail.com>
 * @about        Developed in whole or part by the U.S. National Library of Medicine
 * @link         https://pl.nlm.nih.gov/about
 * @link         http://sahanafoundation.org
 * @license	 http://www.gnu.org/licenses/lgpl-2.1.html GNU Lesser General Public License (LGPL)
 * @lastModified 2013.0811
 */

require_once(realpath(dirname(__FILE__).'/../').'/lib/main.inc.php');
require_once($global['portable.approot'].'/lib/lib_portableconfig.php');
require_once($global['portable.approot'].'/lib/lib_uuid.php');
require_once($global['portable.approot']."/www/theme/head.php");
require_once($global['portable.approot']."/www/theme/body.php");
require_once($global['portable.approot']."/www/theme/footer.php");

// First check whether Vesuvius Portable is registered
if (file_exists($global['portable.conf_file'])){
	shn_theme_head();
	shn_theme_body_view_owner();
	shn_theme_footer();
	exit();
}else{ // if not display blocked message
	shn_theme_head();
	shn_theme_body_block();
	shn_theme_footer();
	exit();
}


text:
void f1(const char*, ...) __attribute__((format(printf, 1, 2)));
void f2(const char*) __attribute__((nonnull));
void f3(const char*, ...) __attribute__((sentinel));

void f()
{
  f1("%p", nullptr);
  f2(nullptr); // { dg-warning "null argument where non-null required " }
  f3("x", "y", __null); // { dg-warning "missing sentinel in function call" }
  f3("x", "y", nullptr);
  decltype(nullptr) mynull = 0;
  f1("%p", mynull);
  f2(mynull); // { dg-warning "null argument where non-null required " }
  f3("x", "y", mynull);
}


text:
require 'thread'
require 'timeout'

class ConnectionPool::PoolShuttingDownError < RuntimeError; end

class ConnectionPool::TimedStack

  def initialize(size = 0, &block)
    @create_block = block
    @created = 0
    @que = []
    @max = size
    @mutex = Mutex.new
    @resource = ConditionVariable.new
    @shutdown_block = nil
  end

  def push(obj)
    @mutex.synchronize do
      if @shutdown_block
        @shutdown_block.call(obj)
      else
        @que.push obj
      end

      @resource.broadcast
    end
  end
  alias_method :<<, :push

  def pop(timeout=0.5)
    deadline = Time.now + timeout
    @mutex.synchronize do
      loop do
        raise ConnectionPool::PoolShuttingDownError if @shutdown_block
        return @que.pop unless @que.empty?
        unless @created == @max
          @created += 1
          return @create_block.call
        end
        to_wait = deadline - Time.now
        raise Timeout::Error, "Waited #{timeout} sec" if to_wait <= 0
        @resource.wait(@mutex, to_wait)
      end
    end
  end

  def shutdown(&block)
    raise ArgumentError, "shutdown must receive a block" unless block_given?

    @mutex.synchronize do
      @shutdown_block = block
      @resource.broadcast

      @que.size.times do
        conn = @que.pop
        block.call(conn)
      end
    end
  end

  def empty?
    (@created - @que.length) >= @max
  end

  def length
    @max - @created + @que.length
  end
end


text:
import os
from setuptools import setup, find_packages

from sopa import VERSION

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

requirements = []

setup(
    name = "django-sopa",
    version = ".".join(map(str, VERSION)),
    description = "A django app for all your censoring needs.",
    long_description = read('README.rst'),
    url = 'https://github.com/fcurella/django-sopa',
    license = 'MIT',
    author = 'Flavio Curella',
    author_email = 'flavio.curella@gmail.com',
    packages = find_packages(exclude=['tests']),
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
    install_requires = requirements,
    tests_require = ["unittest2",],
)


text:
<?php

namespace Tests\AppBundle\Controller\Report;

use AppBundle\Entity\Report\MoneyTransactionShort;
use AppBundle\Entity\Report\MoneyTransactionShortIn;
use AppBundle\Entity\Report\MoneyTransactionShortOut;
use AppBundle\Entity\Report\Report;
use Tests\AppBundle\Controller\AbstractTestController;

class MoneyTransactionShortControllerTest extends AbstractTestController
{
    private static $deputy1;
    private static $transaction1;
    private static $transaction3;
    private static $report1;
    private static $deputy2;
    private static $report2;
    private static $tokenAdmin = null;
    private static $tokenDeputy = null;

    public static function setUpBeforeClass()
    {
        parent::setUpBeforeClass();

        self::$deputy1 = self::fixtures()->getRepo('User')->findOneByEmail('deputy@example.org');

        $client1 = self::fixtures()->createClient(self::$deputy1);
        self::fixtures()->flush();

        self::$report1 = self::fixtures()->createReport($client1);

        // deputy 2
        self::$deputy2 = self::fixtures()->createUser();
        $client2 = self::fixtures()->createClient(self::$deputy2);
        self::$report2 = self::fixtures()->createReport($client2);

        // transactions. 2 in, 1 out. one out for report 2
        self::$transaction1 = $t1 = new MoneyTransactionShortIn(self::$report1);
        $t1->setAmount(123.45)->setDescription('d1')->setDate(new \DateTime('2015-12-31'));
        $t2 = new MoneyTransactionShortIn(self::$report1);
        $t2->setAmount(789.12)->setDescription('d2');
        self::$transaction3 = $t3 = new MoneyTransactionShortOut(self::$report1);
        $t3->setAmount(5000.59)->setDescription('d3');
        $t4 = new MoneyTransactionShortIn(self::$report2);
        $t4->setAmount(123)->setDescription('belongs to report2');
        self::fixtures()->persist($t1, $t2, $t3, $t4);

        self::fixtures()->flush()->clear();
    }

    /**
     * clear fixtures.
     */
    public static function tearDownAfterClass()
    {
        parent::tearDownAfterClass();

        self::fixtures()->clear();
    }

    public function setUp()
    {
        if (null === self::$tokenAdmin) {
            self::$tokenAdmin = $this->loginAsAdmin();
            self::$tokenDeputy = $this->loginAsDeputy();
        }
    }

    public function testGetTransactions()
    {
        $url = '/report/' . self::$report1->getId()
            . '?' . http_build_query(['groups' => ['moneyTransactionsShortIn', 'moneyTransactionsShortOut']]);

        // assert data is retrieved
        $data = $this->assertJsonRequest('GET', $url, [
            'mustSucceed' => true,
            'AuthToken' => self::$tokenDeputy,
        ])['data'];

        // in
        $this->assertCount(2, $data['money_transactions_short_in']);
        $this->assertArrayHasKey('id', $data['money_transactions_short_in'][0]);
        $this->assertEquals('123.45', $data['money_transactions_short_in'][0]['amount']);
        $this->assertEquals('d1', $data['money_transactions_short_in'][0]['description']);
        $this->assertEquals('2015-12-31', $data['money_transactions_short_in'][0]['date']);
        // out
        $this->assertCount(1, $data['money_transactions_short_out']);
        $this->assertArrayHasKey('id', $data['money_transactions_short_out'][2]);
        $this->assertEquals('d3', $data['money_transactions_short_out'][2]['description']);
        $this->assertEquals('5000.59', $data['money_transactions_short_out'][2]['amount']);
    }

    public function testAddEditTransaction()
    {
        $url = '/report/' . self::$report1->getId() . '/money-transaction-short';
        $url2 = '/report/' . self::$report2->getId() . '/money-transaction-short';

        $this->assertEndpointNeedsAuth('POST', $url);
        $this->assertEndpointNotAllowedFor('POST', $url, self::$tokenAdmin);
        $this->assertEndpointNotAllowedFor('POST', $url2, self::$tokenDeputy);

        $data = $this->assertJsonRequest('POST', $url, [
            'mustSucceed' => true,
            'AuthToken' => self::$tokenDeputy,
            'data' => [
                'type' => 'in',
                'amount' => 123.45,
                'description' => 'd',
                'date' => '2014-04-05',
            ],
        ])['data'];

        self::fixtures()->clear();

        $this->assertArrayHasKey('state', self::fixtures()->getReportFreshSectionStatus(self::$report1, Report::SECTION_MONEY_IN_SHORT));

        $t = self::fixtures()->getRepo('Report\MoneyTransactionShortIn')->find($data); /* @var $t MoneyTransactionShortIn */
        $this->assertEquals(123.45, $t->getAmount());
        $this->assertEquals('d', $t->getDescription());
        $this->assertEquals('2014-04-05', $t->getDate()->format('Y-m-d'));

        return $t->getId();
    }

    /**
     * @depends testAddEditTransaction
     */
    public function testEditTransaction($transactionId)
    {
        $url = '/report/' . self::$report1->getId() . '/money-transaction-short/' . $transactionId;
        $url2 = '/report/' . self::$report2->getId() . '/money-transaction-short/' . $transactionId;

        $this->assertEndpointNeedsAuth('PUT', $url);
        $this->assertEndpointNotAllowedFor('PUT', $url, self::$tokenAdmin);
        $this->assertEndpointNotAllowedFor('PUT', $url2, self::$tokenDeputy);

        $data = $this->assertJsonRequest('PUT', $url, [
            'mustSucceed' => true,
            'AuthToken' => self::$tokenDeputy,
            'data' => [
                'amount' => 124.46,
                'description' => 'd-changed',
                'date' => '2014-04-06',
            ],
        ])['data'];

        self::fixtures()->clear();

        $t = self::fixtures()->getRepo('Report\MoneyTransactionShort')->find($data); /* @var $t MoneyTransactionShort */
        $this->assertEquals(124.46, $t->getAmount());
        $this->assertEquals('d-changed', $t->getDescription());
        $this->assertEquals('2014-04-06', $t->getDate()->format('Y-m-d'));
    }

    public function testDelete()
    {
        $url = '/report/' . self::$report1->getId() . '/money-transaction-short/' . self::$transaction3->getId();
        $url2 = '/report/' . self::$report2->getId() . '/money-transfers/99';

        $this->assertEquals('yes', self::$report1->getMoneyTransactionsShortOutExist());

        $this->assertEndpointNeedsAuth('DELETE', $url);
        $this->assertEndpointNotAllowedFor('DELETE', $url, self::$tokenAdmin);
        $this->assertEndpointNotAllowedFor('DELETE', $url2, self::$tokenDeputy);

        $this->assertJsonRequest('DELETE', $url, [
            'mustSucceed' => true,
            'AuthToken' => self::$tokenDeputy,
        ]);

        self::fixtures()->clear();
        self::$report1 = self::fixtures()->getReportById(self::$report1->getId());

        $t = self::fixtures()->getRepo('Report\MoneyTransactionShort')->find(self::$transaction3->getId());
        $this->assertTrue(null === $t);
        $this->assertCount(0, self::$report1->getMoneyTransactionsShortOut());
        $this->assertEquals('no', self::$report1->getMoneyTransactionsShortOutExist());
    }

    public function testExist()
    {
        $report = self::fixtures()->getReportById(self::$report1->getId());
        $this->assertTrue(count($report->getMoneyTransactionsShortIn()) > 0);
        $this->assertEquals('yes', $report->getMoneyTransactionsShortInExist());

        $url = '/report/' . self::$report1->getId() ;
        $this->assertJsonRequest('PUT', $url, [
            'mustSucceed' => true,
            'AuthToken'   => self::$tokenDeputy,
            'data' => [
                'money_transactions_short_in_exist' => 'no'
            ]
        ]);

        self::fixtures()->clear();
        $report = self::fixtures()->getReportById(self::$report1->getId());
        $this->assertEquals('no', $report->getMoneyTransactionsShortInExist());
        $this->assertCount(0, $report->getMoneyTransactionsShortIn());
    }
}


text:
import merge from 'lodash.merge';
import Colors from './colors';
import ColorManipulator from '../utils/color-manipulator';
import autoPrefix from './auto-prefix';
import lightBaseTheme from './baseThemes/lightBaseTheme';
import zIndex from './zIndex';
import {autoprefixer, callOnce, rtl} from './transformers';
import compose from 'lodash.flowright';

/**
 * Get the MUI theme corresponding to a base theme.
 * It's possible to override the computed theme values
 * by providing a second argument. The calculated
 * theme will be deeply merged with the second argument.
 */
export default function getMuiTheme(baseTheme, muiTheme) {
  baseTheme = merge({}, lightBaseTheme, baseTheme);
  const {
    palette,
    spacing,
  } = baseTheme;

  muiTheme = merge({
    isRtl: false,
    userAgent: undefined,
    zIndex,
    baseTheme,
    rawTheme: baseTheme, // To provide backward compatibility.
    appBar: {
      color: palette.primary1Color,
      textColor: palette.alternateTextColor,
      height: spacing.desktopKeylineIncrement,
    },
    avatar: {
      borderColor: 'rgba(0, 0, 0, 0.08)',
    },
    badge: {
      color: palette.alternateTextColor,
      textColor: palette.textColor,
      primaryColor: palette.accent1Color,
      primaryTextColor: palette.alternateTextColor,
      secondaryColor: palette.primary1Color,
      secondaryTextColor: palette.alternateTextColor,
    },
    button: {
      height: 36,
      minWidth: 88,
      iconButtonSize: spacing.iconSize * 2,
    },
    cardText: {
      textColor: palette.textColor,
    },
    checkbox: {
      boxColor: palette.textColor,
      checkedColor: palette.primary1Color,
      requiredColor: palette.primary1Color,
      disabledColor: palette.disabledColor,
      labelColor: palette.textColor,
      labelDisabledColor: palette.disabledColor,
    },
    datePicker: {
      color: palette.primary1Color,
      textColor: palette.alternateTextColor,
      calendarTextColor: palette.textColor,
      selectColor: palette.primary2Color,
      selectTextColor: palette.alternateTextColor,
    },
    dropDownMenu: {
      accentColor: palette.borderColor,
    },
    flatButton: {
      color: Colors.transparent,
      buttonFilterColor: '#999999',
      disabledTextColor: ColorManipulator.fade(palette.textColor, 0.3),
      textColor: palette.textColor,
      primaryTextColor: palette.accent1Color,
      secondaryTextColor: palette.primary1Color,
    },
    floatingActionButton: {
      buttonSize: 56,
      miniSize: 40,
      color: palette.accent1Color,
      iconColor: palette.alternateTextColor,
      secondaryColor: palette.primary1Color,
      secondaryIconColor: palette.alternateTextColor,
      disabledTextColor: palette.disabledColor,
    },
    gridTile: {
      textColor: Colors.white,
    },
    inkBar: {
      backgroundColor: palette.accent1Color,
    },
    leftNav: {
      width: spacing.desktopKeylineIncrement * 4,
      color: palette.canvasColor,
    },
    listItem: {
      nestedLevelDepth: 18,
    },
    menu: {
      backgroundColor: palette.canvasColor,
      containerBackgroundColor: palette.canvasColor,
    },
    menuItem: {
      dataHeight: 32,
      height: 48,
      hoverColor: 'rgba(0, 0, 0, .035)',
      padding: spacing.desktopGutter,
      selectedTextColor: palette.accent1Color,
    },
    menuSubheader: {
      padding: spacing.desktopGutter,
      borderColor: palette.borderColor,
      textColor: palette.primary1Color,
    },
    paper: {
      backgroundColor: palette.canvasColor,
      zDepthShadows: [
        [1, 6, 0.12, 1, 4, 0.12],
        [3, 10, 0.16, 3, 10, 0.23],
        [10, 30, 0.19, 6, 10, 0.23],
        [14, 45, 0.25, 10, 18, 0.22],
        [19, 60, 0.30, 15, 20, 0.22],
      ].map(d => (
        `0 ${d[0]}px ${d[1]}px ${ColorManipulator.fade(palette.shadowColor, d[2])},
         0 ${d[3]}px ${d[4]}px ${ColorManipulator.fade(palette.shadowColor, d[5])}`
      )),
    },
    radioButton: {
      borderColor: palette.textColor,
      backgroundColor: palette.alternateTextColor,
      checkedColor: palette.primary1Color,
      requiredColor: palette.primary1Color,
      disabledColor: palette.disabledColor,
      size: 24,
      labelColor: palette.textColor,
      labelDisabledColor: palette.disabledColor,
    },
    raisedButton: {
      color: palette.alternateTextColor,
      textColor: palette.textColor,
      primaryColor: palette.accent1Color,
      primaryTextColor: palette.alternateTextColor,
      secondaryColor: palette.primary1Color,
      secondaryTextColor: palette.alternateTextColor,
      disabledColor: ColorManipulator.darken(palette.alternateTextColor, 0.1),
      disabledTextColor: ColorManipulator.fade(palette.textColor, 0.3),
    },
    refreshIndicator: {
      strokeColor: palette.borderColor,
      loadingStrokeColor: palette.primary1Color,
    },
    slider: {
      trackSize: 2,
      trackColor: palette.primary3Color,
      trackColorSelected: palette.accent3Color,
      handleSize: 12,
      handleSizeDisabled: 8,
      handleSizeActive: 18,
      handleColorZero: palette.primary3Color,
      handleFillColor: palette.alternateTextColor,
      selectionColor: palette.primary1Color,
      rippleColor: palette.primary1Color,
    },
    snackbar: {
      textColor: palette.alternateTextColor,
      backgroundColor: palette.textColor,
      actionColor: palette.accent1Color,
    },
    table: {
      backgroundColor: palette.canvasColor,
    },
    tableHeader: {
      borderColor: palette.borderColor,
    },
    tableHeaderColumn: {
      textColor: palette.accent3Color,
      height: 56,
      spacing: 24,
    },
    tableFooter: {
      borderColor: palette.borderColor,
      textColor: palette.accent3Color,
    },
    tableRow: {
      hoverColor: palette.accent2Color,
      stripeColor: ColorManipulator.lighten(palette.primary1Color, 0.55),
      selectedColor: palette.borderColor,
      textColor: palette.textColor,
      borderColor: palette.borderColor,
      height: 48,
    },
    tableRowColumn: {
      height: 48,
      spacing: 24,
    },
    timePicker: {
      color: palette.alternateTextColor,
      textColor: palette.accent3Color,
      accentColor: palette.primary1Color,
      clockColor: palette.textColor,
      clockCircleColor: palette.clockCircleColor,
      headerColor: palette.pickerHeaderColor || palette.primary1Color,
      selectColor: palette.primary2Color,
      selectTextColor: palette.alternateTextColor,
    },
    toggle: {
      thumbOnColor: palette.primary1Color,
      thumbOffColor: palette.accent2Color,
      thumbDisabledColor: palette.borderColor,
      thumbRequiredColor: palette.primary1Color,
      trackOnColor: ColorManipulator.fade(palette.primary1Color, 0.5),
      trackOffColor: palette.primary3Color,
      trackDisabledColor: palette.primary3Color,
      labelColor: palette.textColor,
      labelDisabledColor: palette.disabledColor,
      trackRequiredColor: ColorManipulator.fade(palette.primary1Color, 0.5),
    },
    toolbar: {
      backgroundColor: ColorManipulator.darken(palette.accent2Color, 0.05),
      height: 56,
      titleFontSize: 20,
      iconColor: 'rgba(0, 0, 0, .40)',
      separatorColor: 'rgba(0, 0, 0, .175)',
      menuHoverColor: 'rgba(0, 0, 0, .10)',
    },
    tabs: {
      backgroundColor: palette.primary1Color,
      textColor: ColorManipulator.fade(palette.alternateTextColor, 0.7),
      selectedTextColor: palette.alternateTextColor,
    },
    textField: {
      textColor: palette.textColor,
      hintColor: palette.disabledColor,
      floatingLabelColor: palette.textColor,
      disabledTextColor: palette.disabledColor,
      errorColor: Colors.red500,
      focusColor: palette.primary1Color,
      backgroundColor: 'transparent',
      borderColor: palette.borderColor,
    },
  }, muiTheme);

  const transformers = [autoprefixer, rtl, callOnce].map(t => t(muiTheme)).filter(t => t);
  muiTheme.prefix = autoPrefix.getTransform(muiTheme.userAgent);
  muiTheme.prepareStyles = compose(...transformers);

  return muiTheme;
}


text:
package nl.gridline.free.taalserver.writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.WritableComparable;

/**
 * word frequency tuple
 *

 * Project hadoop-freetaalserver

 * WordCount.java created Sep 12, 2011
 *

 * Copyright, all rights reserved 2011 GridLine Amsterdam
 * @author Job
 * @version $Revision:$, $Date:$
 */
public class WordCount implements WritableComparable<WordCount>, Cloneable
{

	private String word;
	private int count;
	private transient int hash;

	public WordCount(String word, int count)
	{
		this.word = word;
		this.count = count;
		hash = getHash();
	}

	public WordCount()
	{
		hash = getHash();
	}

	public String getWord()
	{
		return word;
	}

	public int getCount()
	{
		return count;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.hadoop.io.Writable#write(java.io.DataOutput)
	 */
	@Override
	public void write(DataOutput out) throws IOException
	{
		out.writeInt(count);
		out.writeUTF(word);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.hadoop.io.Writable#readFields(java.io.DataInput)
	 */
	@Override
	public void readFields(DataInput in) throws IOException
	{
		count = in.readInt();
		word = in.readUTF();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#clone()
	 */
	@Override
	public Object clone() throws CloneNotSupportedException
	{
		return new WordCount(word, count);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(WordCount o)
	{
		if (o == null)
		{
			throw new NullPointerException("cannot compare to null");
		}
		int r = word.compareTo(o.word);
		if (r == 0)
		{
			return count - o.count;
		}
		return r;

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode()
	{
		return hash;
	}

	/**
	 * cache the hash
	 * @return
	 */
	private int getHash()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + count;
		result = prime * result + ((word == null) ? 0 : word.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null)
		{
			return false;
		}
		if (getClass() != obj.getClass())
		{
			return false;
		}
		WordCount other = (WordCount) obj;
		if (word == null)
		{
			if (other.word != null)
			{
				return false;
			}
		}
		else if (!word.equals(other.word))
		{
			return false;
		}

		if (count != other.count)
		{
			return false;
		}

		return true;
	}

}


text:
//
//  UIDevice+YZTLAddition.h
//  loan
//
//  Created by ChenYanping on 11/23/15.
//  Copyright © 2015 renxin. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIDevice (YZTLAddition)

+ (NSInteger)yztl_osMainVersion;

/*设备ID**/
- (NSString *)yztl_deviceId;

+ (UIImage *)appGetAppIcon;
@end


text:
using System;
using System.Linq;
using System.Threading;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Features.PoA.Voting;
using Stratis.Bitcoin.Tests.Common;
using Stratis.Bitcoin.Utilities;
using Xunit;

namespace Stratis.Bitcoin.Features.PoA.Tests
{
    public class PollsRepositoryTests
    {
        private readonly PollsRepository repository;

        public PollsRepositoryTests()
        {
            string dir = TestBase.CreateTestDir(this);

            this.repository = new PollsRepository(dir, new ExtendedLoggerFactory(), new DBreezeSerializer(new TestPoANetwork()));
            this.repository.Initialize();
        }

        [Fact]
        public void CantAddOrRemovePollsOutOfOrder()
        {
            Assert.Equal(-1, this.repository.GetHighestPollId());

            this.repository.AddPolls(new Poll() { Id = 0 });
            this.repository.AddPolls(new Poll() { Id = 1 });
            this.repository.AddPolls(new Poll() { Id = 2 });
            Assert.Throws<ArgumentException>(() => this.repository.AddPolls(new Poll() {Id = 5}));
            this.repository.AddPolls(new Poll() { Id = 3 });

            Assert.Equal(3, this.repository.GetHighestPollId());

            this.repository.RemovePolls(3);

            Assert.Throws<ArgumentException>(() => this.repository.RemovePolls(6));
            Assert.Throws<ArgumentException>(() => this.repository.RemovePolls(3));

            this.repository.RemovePolls(2);
            this.repository.RemovePolls(1);
            this.repository.RemovePolls(0);

            this.repository.Dispose();
        }

        [Fact]
        public void SavesHighestPollId()
        {
            this.repository.AddPolls(new Poll() { Id = 0 });
            this.repository.AddPolls(new Poll() { Id = 1 });
            this.repository.AddPolls(new Poll() { Id = 2 });

            this.repository.Initialize();

            Assert.Equal(2, this.repository.GetHighestPollId());
        }

        [Fact]
        public void CanLoadPolls()
        {
            this.repository.AddPolls(new Poll() { Id = 0 });
            this.repository.AddPolls(new Poll() { Id = 1 });
            this.repository.AddPolls(new Poll() { Id = 2 });

            Assert.True(this.repository.GetPolls(0, 1, 2).Count == 3);
            Assert.True(this.repository.GetAllPolls().Count == 3);

            Assert.Throws<ArgumentException>(() => this.repository.GetPolls(-1));
            Assert.Throws<ArgumentException>(() => this.repository.GetPolls(9));
        }

        [Fact]
        public void CanUpdatePolls()
        {
            var poll = new Poll() {Id = 0, VotingData = new VotingData() {Key = VoteKey.AddFederationMember}};
            this.repository.AddPolls(poll);

            poll.VotingData.Key = VoteKey.KickFederationMember;
            this.repository.UpdatePoll(poll);

            Assert.Equal(VoteKey.KickFederationMember, this.repository.GetPolls(poll.Id).First().VotingData.Key);
        }
    }
}


text:
package xyz.julianpeters.timedlists.helpers;

import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;

import xyz.julianpeters.timedlists.activities.main.ItemActivity;
import xyz.julianpeters.timedlists.activities.main.ListActivitySub;
import xyz.julianpeters.timedlists.activities.popup.SetTimePopUp;
import xyz.julianpeters.timedlists.providers.helpers.Item;

/**
 * Created by julian on 15.05.17.
 */

public class Helper {

    public static Intent whichActivity(Context context, boolean isList) {
        if (isList) {
            return new Intent(context, ListActivitySub.class);
        } else {
            return new Intent(context, ItemActivity.class);
        }
    }

    public static void launchIntent(Context context, String _id) {
        Cursor c = context.getContentResolver().query(Item.Items.getIdUri(_id), new String[]{Item.Items.IS_LIST}, null, null, null);
        boolean isList = false;
        if (c != null) {
            c.moveToFirst();
            isList = c.getInt(0) > 0;
        }
        Intent launchActivity = whichActivity(context, isList);
        launchActivity.putExtra("_id", _id);
        context.startActivity(launchActivity);
    }

    public static void launchTimeSetting(Context context, String _id) {
        Intent spinner = new Intent(context, SetTimePopUp.class);
        spinner.putExtra("_id", _id);
        context.startActivity(spinner);
    }
}


text:
import sys
import chardet
from chardet.universaldetector import UniversalDetector

def guess_encoding_incremental(data):
    sys.stderr.write("running incremental chardet\n")
    detector = UniversalDetector()
    for line in data.split("\n"):
        detector.feed(line)
        if detector.done:
            break
    detector.close()
    encoding = detector.result
    return encoding["encoding"]

def guess_encoding(data):
    sys.stderr.write("running full chardet\n")
    encoding = chardet.detect(data)
    return encoding["encoding"]

def convert_to_utf8(data, force_chardet=False):
    encoding = "utf-8"
    try:
        if force_chardet:
            raise
        data = data.decode(encoding)
    except:
        encoding = guess_encoding_incremental(data)
        try:
            data = data.decode(encoding)
        except:
            encoding = guess_encoding(data)
            try:
                data = data.decode(encoding)
            except:
                sys.stderr.write("Fallback: ignoring errors.\n")
                return data.decode("utf-8", errors='ignore')
    sys.stderr.write("Detected encoding: %s\n"
                     % encoding)
    return data

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type=argparse.FileType('r'),
                        help='input file')
    parser.add_argument('outfile', type=argparse.FileType('w'),
                        help='output file')
    parser.add_argument('-chardet', action='store_true',
                        help='force chardet detection (slow)')
    args = parser.parse_args()

    data = args.infile.read()
    data = convert_to_utf8(data, args.chardet)
    args.outfile.write(data.encode("utf-8"))


text:
@interface RYWebController : UIViewController

@end


text:
if [[ $( ls /conf/jmxremote.* 2> /dev/null ) ]]
then
  # JMX auth files would be mounted as a symbolic link (read-only mode)
  # with `root` privileges by the k8s secret.
  cp -rL /conf/jmxremote.* /home/owuser
  rm -f /conf/jmxremote.* 2>/dev/null || true

  # The owner must be `owuser` and the file only have read permission.
  chmod 600 /home/owuser/jmxremote.*
fi


text:
import * as vs from "vscode";
import { DartCapabilities } from "../../shared/capabilities/dart";
import { stagehandInstallationInstructionsUrl } from "../../shared/constants";
import { LogCategory } from "../../shared/enums";
import { DartProjectTemplate, DartSdks, Logger } from "../../shared/interfaces";
import { logProcess } from "../../shared/logging";
import { getPubExecutionInfo } from "../../shared/processes";
import { cleanPubOutput } from "../../shared/pub/utils";
import { safeToolSpawn } from "../utils/processes";
import { PubGlobal } from "./global";

const packageName = "Stagehand";
const packageID = "stagehand";

export class Stagehand {
	constructor(private logger: Logger, private dartCapabilities: DartCapabilities, private sdks: DartSdks, private pubGlobal: PubGlobal) { }

	public installIfRequired() {
		return this.pubGlobal.installIfRequired({ packageName, packageID, moreInfoLink: stagehandInstallationInstructionsUrl, requiredVersion: "3.3.0" });
	}

	public async getTemplates(): Promise<DartProjectTemplate[]> {
		const json = await this.getTemplateJson();
		return JSON.parse(json);
	}

	private async getTemplateJson(): Promise<string> {
		return cleanPubOutput(await this.runCommandWithProgress("Fetching Stagehand templates...", ["global", "run", "stagehand", "--machine"]));
	}

	private runCommandWithProgress(title: string, args: string[]): Thenable<string> {
		return vs.window.withProgress({
			location: vs.ProgressLocation.Notification,
			title,
		}, () => this.runCommand(args));
	}

	private runCommand(args: string[]): Thenable<string> {
		const pubExecution = getPubExecutionInfo(this.dartCapabilities, this.sdks.dart, args);

		return new Promise((resolve, reject) => {
			const proc = safeToolSpawn(undefined, pubExecution.executable, pubExecution.args);
			logProcess(this.logger, LogCategory.CommandProcesses, proc);

			const stdout: string[] = [];
			const stderr: string[] = [];
			proc.stdout.on("data", (data: Buffer | string) => stdout.push(data.toString()));
			proc.stderr.on("data", (data: Buffer | string) => stderr.push(data.toString()));
			proc.on("close", (code) => {
				if (!code) {
					resolve(stdout.join(""));
				} else {
					reject(`Stagehand exited with code ${code}.\n\n${stdout.join("")}\n\n${stderr.join("")}`);
				}
			});
		});
	}
}


text:
class cMainGame
{
public:
	cMainGame();
	~cMainGame();

	void init();
	void update(float);
	void render();
private:

	ID3D11VertexShader	*pVS;		    // the vertex shader
	ID3D11PixelShader	*pPS;			// the pixel shader
	ID3D11Buffer		*pVBuffer;		// buffer

	ID3D11InputLayout *pLayout; // layout

	std::vector<ST_VERTEX1> m_vecdata;
};


text:
package com.expedia.dsp.data.squeeze.impl;

import com.expedia.dsp.data.squeeze.CompactionManagerFactory;
import com.expedia.dsp.data.squeeze.models.CompactionCriteria;
import com.expedia.dsp.data.squeeze.models.CompactionResponse;
import com.expedia.dsp.data.squeeze.models.FilePaths;
import com.expedia.dsp.data.squeeze.models.FileType;
import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicMatch;
import org.apache.commons.math3.util.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.orc.OrcFile;
import org.apache.orc.Reader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.powermock.api.mockito.PowerMockito.*;

/**
 * Tests for {@link CompactionManagerImpl}
 *
 * @author Yashraj R. Sontakke
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({CompactionManagerImpl.class, CompactionManagerInPlaceImpl.class, FileSystem.class, FSDataInputStream.class, OrcFile.class, Reader.class, Job.class
        , Magic.class, MagicMatch.class, UUID.class})
public class CompactionManagerInPlaceImplTest {

    private final Configuration configuration = mock(Configuration.class);
    private final FileSystem fileSystem = mock(FileSystem.class);
    private final CompactionManagerImpl compactionManagerImpl = PowerMockito.mock(CompactionManagerImpl.class);
    private final FileManager fileManager = mock(FileManager.class);
    private final List<Path> filePaths1 = new ArrayList<Path>();
    private final Path path = new Path("/source/path/file");
    private final Path path2 = new Path("/source/path/dir");
    final String sourcePath = "/source/path";
    final String s3SourcePath = "s3/source/path";
    private final FilePaths filePaths = mock(FilePaths.class);

    @Test(expected = NullPointerException.class)
    public void testNullConfiguration() {
        final CompactionCriteria criteria = new CompactionCriteria(null, "target/path", null, null);
        new CompactionManagerInPlaceImpl(null, criteria);
    }

    @Test(expected = NullPointerException.class)
    public void testNullCriteria() throws Exception {
        new CompactionManagerInPlaceImpl(configuration, null);
    }

    @Test(expected = NullPointerException.class)
    public void testNullSourcePath() {
        final CompactionCriteria criteria = new CompactionCriteria(null, null, null, null);
        new CompactionManagerImpl(null, criteria);
    }

    /*@Test(expected = NullPointerException.class)
    public void testNullTempPath() {
        final CompactionCriteria criteria = new CompactionCriteria("/source/path", null, null, null, false, null);
        new CompactionManagerImpl(null, criteria);
    }*/

    @Test(expected = NullPointerException.class)
    public void testCompactSameSourceAndPathTarget() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(sourcePath, sourcePath, null, null);

        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        compactionManager.compact();
    }

    @Before
    public void setup() throws Exception {

        PowerMockito.mockStatic(FileSystem.class);
        when(FileSystem.get(configuration)).thenReturn(fileSystem);
        when(FileSystem.get(any(URI.class), any(Configuration.class))).thenReturn(fileSystem);
        CompactionManagerFactory.DEFAULT_THRESHOLD_IN_BYTES = 1234L;
        when(fileSystem.exists(path)).thenReturn(true);
        when(fileSystem.exists(path2)).thenReturn(true);
        when(fileSystem.exists(new Path(sourcePath))).thenReturn(true);
        when(fileSystem.exists(new Path(s3SourcePath))).thenReturn(true);
        when(fileSystem.rename(new Path(sourcePath), new Path("target/path"))).thenReturn(true);
        when(fileSystem.rename(new Path(s3SourcePath), new Path("target/path"))).thenReturn(true);
        whenNew(FileManager.class).withArguments(fileSystem).thenReturn(fileManager);
        filePaths1.add(path2);
        when(fileManager.getAllFilePaths(new Path(sourcePath))).thenReturn(filePaths);
        when(fileManager.getAllFilePaths(new Path(s3SourcePath))).thenReturn(filePaths);
        when(fileManager.getFileType(filePaths1)).thenReturn(FileType.TEXT);
        when(filePaths.getAllFilePaths()).thenReturn(filePaths1);
    }

    @Test(expected = IllegalStateException.class)
    public void testSourcePathDoesNotExist() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(sourcePath, "target/path", null, null);
        when(fileSystem.exists(new Path(sourcePath))).thenReturn(false);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        compactionManager.compact();
    }

    @Test(expected = NullPointerException.class)
    public void testTargetPathAlreadyExists() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(sourcePath, "target/path", null, null);
        when(fileSystem.exists(new Path("target/path"))).thenReturn(true);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        compactionManager.compact();
    }

    @Test(expected = NullPointerException.class)
    public void testNoSourceFilesToCompact() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(sourcePath, "target/path", null, null);
        Pair<Long, List<Path>> filePathsWithBytes = new Pair(10000L, filePaths);
        when(fileManager.getAllFilePaths(new Path(sourcePath))).thenReturn(filePaths);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        compactionManager.compact();
    }

    @Test
    public void testCompactOnPrem() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(sourcePath, "target/path", null, null);
        final CompactionResponse compactionResponse = new CompactionResponse(true, "/source/path", FileType.TEXT);
        whenNew(CompactionManagerImpl.class).withArguments(any(Configuration.class), any(CompactionCriteria.class)).thenReturn(compactionManagerImpl);
        when(compactionManagerImpl.compact()).thenReturn(compactionResponse);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        final CompactionResponse response = compactionManager.compact();
        assertResponse(true, FileType.TEXT, criteria.getSourcePath(), response);
    }

    @Test
    public void testCompactOnS3() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(s3SourcePath, "target/path", null, null);
        final CompactionResponse compactionResponse = new CompactionResponse(true, "s3/source/path", FileType.TEXT);
        whenNew(CompactionManagerImpl.class).withArguments(any(Configuration.class), any(CompactionCriteria.class)).thenReturn(compactionManagerImpl);
        when(compactionManagerImpl.compact()).thenReturn(compactionResponse);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        final CompactionResponse response = compactionManager.compact();
        assertResponse(true, FileType.TEXT, criteria.getSourcePath(), response);
    }

    @Test
    public void testCompactRetainTempFiles() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria("s3/source/path", "target/path", null, null);
        final CompactionResponse compactionResponse = new CompactionResponse(true, "s3/source/path", FileType.TEXT);
        whenNew(CompactionManagerImpl.class).withArguments(any(Configuration.class), any(CompactionCriteria.class)).thenReturn(compactionManagerImpl);
        when(compactionManagerImpl.compact()).thenReturn(compactionResponse);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        final CompactionResponse response = compactionManager.compact();
        assertResponse(true, FileType.TEXT, criteria.getSourcePath(), response);
    }

    @Test
    public void testCompactWithThreshold() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria("s3/source/path", "target/path", 10L, null);
        final CompactionResponse compactionResponse = new CompactionResponse(true, "s3/source/path", FileType.TEXT);
        whenNew(CompactionManagerImpl.class).withArguments(any(Configuration.class), any(CompactionCriteria.class)).thenReturn(compactionManagerImpl);
        when(compactionManagerImpl.compact()).thenReturn(compactionResponse);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        final CompactionResponse response = compactionManager.compact();
        assertResponse(true, FileType.TEXT, criteria.getSourcePath(), response);
    }

    @Test
    public void testCompactWithMaxReducers() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria("s3/source/path", "target/path", null, null);
        final CompactionResponse compactionResponse = new CompactionResponse(true, "s3/source/path", FileType.TEXT);
        whenNew(CompactionManagerImpl.class).withArguments(any(Configuration.class), any(CompactionCriteria.class)).thenReturn(compactionManagerImpl);
        when(compactionManagerImpl.compact()).thenReturn(compactionResponse);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        final CompactionResponse response = compactionManager.compact();
        assertResponse(true, FileType.TEXT, criteria.getSourcePath(), response);
    }

    @Test
    public void testCompactFailure() throws Exception {
        final CompactionCriteria criteria = new CompactionCriteria(sourcePath,  "target/path", null, null);
        final CompactionResponse compactionResponse = new CompactionResponse(false, sourcePath, FileType.TEXT);
        whenNew(CompactionManagerImpl.class).withArguments(any(Configuration.class), any(CompactionCriteria.class)).thenReturn(compactionManagerImpl);
        when(compactionManagerImpl.compact()).thenReturn(compactionResponse);
        final CompactionManagerInPlaceImpl compactionManager = new CompactionManagerInPlaceImpl(configuration, criteria);
        final CompactionResponse response = compactionManager.compact();
        assertResponse(false, FileType.TEXT, criteria.getSourcePath(), response);
    }

    private void assertResponse(final boolean isSuccessful, final FileType fileType, final String targetPath,
                                final CompactionResponse actualResponse) {
        assertEquals(isSuccessful, actualResponse.isSuccessful());
        assertEquals(fileType, actualResponse.getTargetFileType());
        assertEquals(targetPath, actualResponse.getTargetPath());
    }
}


text:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

namespace Fungus
{
	[CommandInfo("Flow",
	             "While",
	             "Continuously loop through a block of commands while the condition is true. Use the Break command to force the loop to terminate immediately.")]
	[AddComponentMenu("")]
	public class While : If
	{
		public override void OnEnter()
		{
			bool execute = true;
			if (variable != null)
			{
				execute = EvaluateCondition();
			}

			// Find next End statement at same indent level
			End endCommand = null;
			for (int i = commandIndex + 1; i < parentBlock.commandList.Count; ++i)
			{
				End command = parentBlock.commandList[i] as End;

				if (command != null &&
				    command.indentLevel == indentLevel)
				{
					endCommand = command;
					break;
				}
			}

			if (execute)
			{
				// Tell the following end command to loop back
				endCommand.loop = true;
				Continue();
			}
			else
			{
				// Continue at next command after End
				Continue (endCommand.commandIndex + 1);
			}
		}

		public override bool OpenBlock()
		{
			return true;
		}

		public override Color GetButtonColor()
		{
			return new Color32(253, 253, 150, 255);
		}
	}

}


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

<!---   http://www.apache.org/licenses/LICENSE-2.0 -->

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

# Hexagon IDL libraries

This directory hosts IDL files and their implementations to offload TVM kernels to Hexagon via FastRPC. The implementations can be used to generate stub and skel libraries.

### Prerequisites

1. Android NDK version r19c or later.
2. Hexagon SDK version 3.5.0 or later.

Android NDK can be downloaded from https://developer.android.com/ndk.
Hexagon SDK is available at //developer.qualcomm.com/software/hexagon-dsp-sdk.

### Configuring

Skel and stub libraries need to be configured and built separately. Please use different subdirectories for each. Otherwise the cmake cache from one configuration can interfere with the next.

For skel libraries, set
```
FASTRPC_LIBS=SKEL
HEXAGON_SDK_ROOT=/path/to/sdk
CMAKE_C_COMPILER=hexagon-clang
CMAKE_CXX_COMPILER=hexagon-clang++
HEXAGON_ARCH= one of v60, v62, v65, v66
```

Please note that support for older versions of the Hexagon processor may be removed from the future versions of the Hexagon toolchain.

For stub libraries, set
```
FASTRPC_LIBS=STUB
HEXAGON_SDK_ROOT=/path/to/sdk
CMAKE_C_COMPILER=aarch64-linux-android28-clang      # or later
CMAKE_CXX_COMPILER=aarch64-linux-android28-clang++  # or later
```

### Building

In each instance, simple `make` command will create header files `fastrpc/include/tvm_remote.h` and `fastrpc/include/tvm_remote_nd.h`. These headers are needed to compile the TVM runtime for Android (and the stub/skel libraries themselves).


text:
package com.anrisoftware.globalpom.core.mnemonic;

/**
 * Mnemonic service.
 *
 * @author Erwin Mueller, erwin.mueller@deventm.org
 * @since 3.1
 */
public interface MnemonicService extends MnemonicFactory {

}


text:
package v7_test

import (
	"errors"

	"code.cloudfoundry.org/cli/resources"
	"code.cloudfoundry.org/cli/types"

	"code.cloudfoundry.org/cli/actor/actionerror"
	"code.cloudfoundry.org/cli/actor/v7action"
	"code.cloudfoundry.org/cli/command/commandfakes"
	. "code.cloudfoundry.org/cli/command/v7"
	"code.cloudfoundry.org/cli/command/v7/v7fakes"
	"code.cloudfoundry.org/cli/util/configv3"
	"code.cloudfoundry.org/cli/util/ui"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
)

var _ = Describe("domains Command", func() {
	var (
		cmd             DomainsCommand
		testUI          *ui.UI
		fakeConfig      *commandfakes.FakeConfig
		fakeSharedActor *commandfakes.FakeSharedActor
		fakeActor       *v7fakes.FakeActor
		executeErr      error
		args            []string
		binaryName      string
	)

	const tableHeaders = `name\s+availability\s+internal`

	JustBeforeEach(func() {
		executeErr = cmd.Execute(args)
	})

	BeforeEach(func() {
		testUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())
		fakeConfig = new(commandfakes.FakeConfig)
		fakeSharedActor = new(commandfakes.FakeSharedActor)
		fakeActor = new(v7fakes.FakeActor)
		args = nil

		cmd = DomainsCommand{
			BaseCommand: BaseCommand{
				UI:          testUI,
				Config:      fakeConfig,
				SharedActor: fakeSharedActor,
				Actor:       fakeActor,
			},
		}

		binaryName = "faceman"
		fakeConfig.BinaryNameReturns(binaryName)
	})

	When("the environment is not setup correctly", func() {
		When("checking target fails", func() {
			BeforeEach(func() {
				fakeSharedActor.CheckTargetReturns(actionerror.NotLoggedInError{BinaryName: binaryName})
			})

			It("returns an error", func() {
				Expect(executeErr).To(MatchError(actionerror.NotLoggedInError{BinaryName: binaryName}))

				Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
				checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
				Expect(checkTargetedOrg).To(BeTrue())
				Expect(checkTargetedSpace).To(BeFalse())
			})
		})

		When("when there is no org targeted", func() {
			BeforeEach(func() {
				fakeSharedActor.CheckTargetReturns(actionerror.NoOrganizationTargetedError{BinaryName: binaryName})
			})

			It("returns an error", func() {
				Expect(executeErr).To(MatchError(actionerror.NoOrganizationTargetedError{BinaryName: binaryName}))
				checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
				Expect(checkTargetedOrg).To(BeTrue())
				Expect(checkTargetedSpace).To(BeFalse())
			})
		})
	})

	Context("When the environment is setup correctly", func() {
		BeforeEach(func() {
			fakeActor.GetCurrentUserReturns(configv3.User{Name: "banana"}, nil)
		})

		When("DomainsActor returns an error", func() {
			var expectedErr error

			BeforeEach(func() {
				warnings := v7action.Warnings{"warning-1", "warning-2"}
				expectedErr = errors.New("some-error")
				fakeActor.GetOrganizationDomainsReturns(nil, warnings, expectedErr)
			})

			It("prints that error with warnings", func() {
				Expect(executeErr).To(Equal(expectedErr))

				Expect(testUI.Err).To(Say("warning-1"))
				Expect(testUI.Err).To(Say("warning-2"))
				Expect(testUI.Out).ToNot(Say(tableHeaders))
			})
		})

		When("GetDomains returns some domains", func() {
			var domains []resources.Domain

			BeforeEach(func() {
				domains = []resources.Domain{
					{Name: "domain1", GUID: "domain-guid-1", Internal: types.NullBool{IsSet: true, Value: true}, Protocols: []string{"http"}},
					{Name: "domain3", GUID: "domain-guid-3", Internal: types.NullBool{IsSet: false, Value: false}, Protocols: []string{"tcp"}, OrganizationGUID: "owning-org-guid"},
					{Name: "domain2", GUID: "domain-guid-2", Internal: types.NullBool{IsSet: true, Value: false}, Protocols: []string{"http", "tcp"}},
				}

				fakeActor.GetOrganizationDomainsReturns(
					domains,
					v7action.Warnings{"actor-warning-1", "actor-warning-2", "actor-warning-3"},
					nil,
				)

				fakeConfig.TargetedOrganizationReturns(configv3.Organization{
					GUID: "some-org-guid",
					Name: "some-org",
				})
			})

			It("asks the DomainsActor for a list of domains", func() {
				Expect(fakeActor.GetOrganizationDomainsCallCount()).To(Equal(1))
			})

			It("prints warnings", func() {
				Expect(testUI.Err).To(Say("actor-warning-1"))
				Expect(testUI.Err).To(Say("actor-warning-2"))
				Expect(testUI.Err).To(Say("actor-warning-3"))
			})

			It("prints the list of domains in alphabetical order", func() {
				Expect(executeErr).NotTo(HaveOccurred())
				Expect(testUI.Out).To(Say(tableHeaders))
				Expect(testUI.Out).To(Say(`domain1\s+shared\s+true\s+http`))
				Expect(testUI.Out).To(Say(`domain2\s+shared\s+http,tcp`))
				Expect(testUI.Out).To(Say(`domain3\s+private\s+tcp`))
			})

			It("prints the flavor text", func() {
				Expect(testUI.Out).To(Say("Getting domains in org some-org as banana...\n\n"))
			})
		})

		When("GetDomains returns no domains", func() {
			var domains []resources.Domain

			BeforeEach(func() {
				domains = []resources.Domain{}

				fakeActor.GetOrganizationDomainsReturns(
					domains,
					v7action.Warnings{"actor-warning-1", "actor-warning-2", "actor-warning-3"},
					nil,
				)

				fakeConfig.TargetedOrganizationReturns(configv3.Organization{
					GUID: "some-org-guid",
					Name: "some-org",
				})
			})

			It("asks the DomainsActor for a list of domains", func() {
				Expect(fakeActor.GetOrganizationDomainsCallCount()).To(Equal(1))
			})

			It("prints warnings", func() {
				Expect(testUI.Err).To(Say("actor-warning-1"))
				Expect(testUI.Err).To(Say("actor-warning-2"))
				Expect(testUI.Err).To(Say("actor-warning-3"))
			})

			It("does not print table headers", func() {
				Expect(testUI.Out).NotTo(Say(tableHeaders))
			})

			It("prints a message indicating that no domains were found", func() {
				Expect(executeErr).NotTo(HaveOccurred())
				Expect(testUI.Out).To(Say("No domains found."))
			})

			It("prints the flavor text", func() {
				Expect(testUI.Out).To(Say("Getting domains in org some-org as banana...\n\n"))
			})
		})
		Context("when a labels flag is set", func() {
			BeforeEach(func() {
				cmd.Labels = "fish=moose"
			})

			It("passes the flag to the API", func() {
				Expect(fakeActor.GetOrganizationDomainsCallCount()).To(Equal(1))
				_, labelSelector := fakeActor.GetOrganizationDomainsArgsForCall(0)
				Expect(labelSelector).To(Equal("fish=moose"))
			})
		})
	})
})


text:
"use strict"

import React from 'react'

import { requireCss } from './themes'
requireCss('checkbox')

export default class Radio extends React.Component {
  static displayName = "Radio"

  static propTypes = {
    checked: React.PropTypes.bool,
    index: React.PropTypes.number,
    onClick: React.PropTypes.func,
    readOnly: React.PropTypes.bool,
    style: React.PropTypes.object,
    text: React.PropTypes.any,
    value: React.PropTypes.any
  }

  handleClick () {
    if (this.props.onClick) {
      this.props.onClick(this.props.value, this.props.index)
    }
  }

  render () {
    return (
      <label style={this.props.style} className="rct-radio">
        <input ref="input"
          type="radio"
          disabled={this.props.readOnly}
          onChange={() => {}}
          onClick={this.handleClick.bind(this)}
          checked={this.props.checked}
          value={this.props.value}
        />
        <span>{this.props.text}</span>
      </label>
    )
  }
}


text:
from django.db import models
from django.core.exceptions import ValidationError

import mozdns
from mozdns.cname.models import CNAME
from mozdns.ip.models import Ip
from mozdns.models import MozdnsRecord, LabelDomainMixin

import reversion
from gettext import gettext as _

class BaseAddressRecord(Ip, LabelDomainMixin, MozdnsRecord):
    """AddressRecord is the class that generates A and AAAA records

        >>> AddressRecord(label=label, domain=domain_object, ip_str=ip_str,
        ... ip_type=ip_type)

    """
    search_fields = ("fqdn", "ip_str")

    class Meta:
        abstract = True

    @property
    def rdtype(self):
        if self.ip_type == '6':
            return 'AAAA'
        return 'A'

    def details(self):
        return (
            ("FQDN", self.fqdn),
            ("Record Type", self.record_type()),
            ("IP", str(self.ip_str)),
        )

    @classmethod
    def get_api_fields(cls):
        return super(BaseAddressRecord, cls).get_api_fields() + ['ip_str',
                                                                 'ip_type']

    def clean(self, *args, **kwargs):
        validate_glue = kwargs.pop("validate_glue", True)
        if validate_glue:
            self.check_glue_status()
        self.clean_ip()
        self.set_fqdn()
        self.check_TLD_condition()
        self.validate_delegation_conditions()
        self.check_no_ns_soa_condition(self.domain)
        self.check_for_cname()

        if not kwargs.pop("ignore_interface", False):
            from core.interface.static_intr.models import StaticInterface
            if StaticInterface.objects.filter(
                    fqdn=self.fqdn, ip_upper=self.ip_upper,
                    ip_lower=self.ip_lower).exists():
                raise ValidationError("A Static Interface has already "
                                      "reserved this A record.")

    def delete(self, *args, **kwargs):
        """Address Records that are glue records or that are pointed to
        by a CNAME should not be removed from the database.
        """
        if kwargs.pop("validate_glue", True):
            if self.nameserver_set.exists():
                raise ValidationError(
                    "Cannot delete the record {0}. It is a glue "
                    "record.".format(self.record_type()))
        if kwargs.pop("check_cname", True):
            if CNAME.objects.filter(target=self.fqdn):
                raise ValidationError(
                    "A CNAME points to this {0} record. Change the CNAME "
                    "before deleting this record.".format(self.record_type()))

        super(BaseAddressRecord, self).delete(*args, **kwargs)

    def validate_delegation_conditions(self):
        """If our domain is delegated then an A record can only have a
        name that is the same as a nameserver in that domain (glue)."""
        if not (self.domain and self.domain.delegated):
            return
        if self.domain.nameserver_set.filter(server=self.fqdn).exists():
            return
        else:
            # Confusing error messege?
            raise ValidationError(
                "You can only create A records in a "
                "delegated domain that have an NS record pointing to them.")

    def check_glue_status(self):
        """If this record is a "glue" record for a Nameserver instance,
        do not allow modifications to this record. The Nameserver will
        need to point to a different record before this record can
        be updated.
        """
        if self.pk is None:
            return
        # First get this object from the database.mozdns and compare it to the
        # nameserver.nameserver.  object about to be saved.
        db_self = AddressRecord.objects.get(pk=self.pk)
        if db_self.label == self.label and db_self.domain == self.domain:
            return
        # The label of the domain changed. Make sure it's not a glue record
        Nameserver = mozdns.nameserver.models.Nameserver
        if Nameserver.objects.filter(addr_glue=self).exists():
            raise ValidationError(
                "This record is a glue record for a"
                "Nameserver. Change the Nameserver to edit this record.")

    def record_type(self):
        # If PTR didn't share this field, we would use 'A' and 'AAAA'
        # instead of '4' and '6'.
        if self.ip_type == '4':
            return 'A'
        else:
            return 'AAAA'

    def __str__(self):
        return "{0} {1} {2}".format(self.fqdn,
                                    self.record_type(), str(self.ip_str))

    def __repr__(self):
        return "<Address Record '{0}'>".format(str(self))

class AddressRecord(BaseAddressRecord):
    """AddressRecord is the class that generates A and AAAA records

        >>> AddressRecord(label=label, domain=domain_object, ip_str=ip_str,
        ... ip_type=ip_type)

    """
    ############################
    # See Ip for all ip fields #
    ############################
    id = models.AutoField(primary_key=True)

    template = _("{bind_name:$lhs_just} {ttl} {rdclass:$rdclass_just} "
                 "{rdtype:$rdtype_just} {ip_str:$rhs_just}")

    class Meta:
        db_table = "address_record"
        unique_together = ("label", "domain", "fqdn", "ip_upper", "ip_lower",
                           "ip_type")

reversion.register(AddressRecord)


text:
Storm stands for **S** imple **T** ornado **O** bject **R** elational **M** apping.

It uses Mongo DB for the backend, but it should be swappable for any storage by implementing the `storm.db.Database` interface.

This is the result of a few hours of work so I would not recommend using it in production at the moment.

## Usage

```python
from storm.model import Model
from storm.db import Connection
from storm.mongodb import MongoDb
from tornado.gen import coroutine
from tornado.ioloop import IOLoop

class User(Model):
    pass

@coroutine
def main():
    db = MongoDb(Connection(
                    host='localhost',
                    port=27017,
                    database='test'))

    db.connect()

    Model.set_db(db)

    # save a new object
    user = User()
    user.name = 'Craig'
    user.type = 'basic'
    id = yield user.save()

    # find an object
    try:
        user = yield User.find(name='Craig')
        print user.name
        print user.type
    except Exception, e:
        print e

    IOLoop.instance().stop()

main()
IOLoop.instance().start()
```

## Note

This is in no way affiliated with the storm ORM developed by Canonical: http://storm.canonical.com.  I didn't know there was another ORM with the same name until I checked PyPi.


text:
import { gql } from '@apollo/client'

import TwitterAuthCheck from 'v2/components/FindFriends/fragments/twitterAuthCheck'

export default gql`
  query TwitterAuthCheckQuery {
    me {
      ...TwitterAuthCheck
    }
  }
  ${TwitterAuthCheck}
`