text:
unless defined? SimpleDelegator
  require "delegate"
end

module Definitions
  using Stupidedi::Refinements

  class FunctionalGroupDelegator < SimpleDelegator
    def empty
      Stupidedi::Values::FunctionalGroupVal.new(self, [])
    end

    def segment_dict
      SegmentDefs
    end
  end

  # Define a new header Table
  def Header(*args)
    Stupidedi::Schema::TableDef.header(*args)
  end

  # Define a new detail Table
  def Detail(*args)
    Stupidedi::Schema::TableDef.detail(*args)
  end

  # Define a new summary Table
  def Summary(*args)
    Stupidedi::Schema::TableDef.summary(*args)
  end

  # Define a new loop
  def Loop(*args)
    Stupidedi::Schema::LoopDef.build(*args)
  end

  # Declare that a segment is used (eg, in a Loop or Table)
  def Segment(position, segment, *args)
    case segment
    when Symbol
      Stupidedi::Versions::FiftyTen::SegmentDefs.const_get(segment).use(position, *args)
    when Stupidedi::Schema::SegmentDef
      segment.use(position, *args)
    else
      raise ArgumentError,
        "second argument must be a Symbol or a Stupidedi::Schema::SegmentDef"
    end
  end

  def Segment_(position, segment_id, name, requirement, repeat, *args)
    Stupidedi::Schema::SegmentDef.build(segment_id, name, "", *args).use(position, requirement, repeat)
  end

  def Element(element, *args)
    case element
    when Symbol
      Stupidedi::Versions::FiftyTen::ElementDefs.const_get(id).simple_use(*args)
    when Stupidedi::Schema::AbstractElementDef
      element.simple_use(*args)
    end
  end

  def CodeList(*args)
    Stupidedi::Schema::CodeList.internal(*args)
  end

  RepeatCount   = Stupidedi::Schema::RepeatCount
  ElementReqs   = Stupidedi::Versions::Common::ElementReqs
  SegmentReqs   = Stupidedi::Versions::Common::SegmentReqs
  ElementReqs_  = Stupidedi::TransactionSets::Common::Implementations::ElementReqs
  SegmentReqs_  = Stupidedi::TransactionSets::Common::Implementations::SegmentReqs
  SyntaxNotes   = Stupidedi::Versions::FiftyTen::SyntaxNotes

  # Use this within `Segment` to declare "if any element specified in the relation
  # is present, then all elements must be present"
  def P(*args)
    SyntaxNotes::P.build(*args)
  end

  # Use this within `Segment` to declare "at least one of the elements specified
  # in this relation are required"
  def R(*args)
    SyntaxNotes::R.build(*args)
  end

  # Use this within `Segment` to declare "not more than one of the elements in
  # this relation may be present"
  def E(*args)
    SyntaxNotes::E.build(*args)
  end

  # Use this within `Segment` to declare "if the first element in the relation
  # is present, then all others must be present"
  def C(*args)
    SyntaxNotes::C.build(*args)
  end

  # Use this within `Segment` to declare "if the first element in the relation
  # is present, then at least one other must be present"
  def L(*args)
    SyntaxNotes::L.build(*args)
  end

  # Repetition designator for Loops, Segments, and Elements
  def bounded(n)
    RepeatCount.bounded(n)
  end

  # Repetition designator for Loops, Segments, and Elements
  def unbounded
    RepeatCount.unbounded
  end

  # Requirement designator for Segments (not Elements!)
  def s_mandatory
    SegmentReqs::Mandatory
  end

  # Requirement designator for Segments (not Elements!)
  def s_optional
    SegmentReqs::Optional
  end

  # Requirement designator for Segments (not Elements!)
  def s_required
    SegmentReqs_::Required
  end

  # Requirement designator for Segments (not Elements!)
  def s_situational
    SegmentReqs_::Situational
  end

  # Requirement designator for Elements (not Segments!)
  def e_mandatory
    ElementReqs::Mandatory
  end

  # Requirement designator for Elements (not Segments!)
  def e_relational
    ElementReqs::Relational
  end

  # Requirement designator for Elements (not Segments!)
  def e_optional
    ElementReqs::Optional
  end

  # Requirement designator for Elements (not Segments!)
  def e_required
    ElementReqs_::Required
  end

  # Requirement designator for Elements (not Segments!)
  def e_situational
    ElementReqs_::Situational
  end

  # Requirement designator for Elements (not Segments!)
  def e_not_used
    ElementReqs_::NotUsed
  end

  module ElementDefs
    DE_ID   = Stupidedi::Versions::Common::ElementTypes::ID.new(:DE1, "DE1 (ID)",   1,  1,
      Stupidedi::Schema::CodeList.internal(Hash[("A".."Z").map{|x| [x, "Meaning of #{x}"]}]))
    DE_AN   = Stupidedi::Versions::Common::ElementTypes::AN.new(:DE2, "DE2 (AN)",   1, 10)
    DE_DT6  = Stupidedi::Versions::Common::ElementTypes::DT.new(:DE3, "DE3 (DT/6)", 6,  6)
    DE_DT8  = Stupidedi::Versions::Common::ElementTypes::DT.new(:DE4, "DE4 (DT/8)", 8,  8)
    DE_TM   = Stupidedi::Versions::Common::ElementTypes::TM.new(:DE5, "DE5 (TM)",   4,  8)
    DE_R    = Stupidedi::Versions::Common::ElementTypes:: R.new(:DE6, "DE6 (R)",    1,  6)
    DE_N0   = Stupidedi::Versions::Common::ElementTypes::Nn.new(:DE7, "DE7 (N0)",   1,  6, 0)
    DE_N1   = Stupidedi::Versions::Common::ElementTypes::Nn.new(:DE8, "DE8 (N1)",   1,  6, 1)
    DE_N2   = Stupidedi::Versions::Common::ElementTypes::Nn.new(:DE9, "DE9 (N2)",   1,  6, 2)
    DE_CON  = Stupidedi::Schema::CompositeElementDef.build(:DE_CON, "CE NNN", "",
      DE_N0.component_use(ElementReqs::Mandatory),
      DE_N0.component_use(ElementReqs::Mandatory),
      DE_N0.component_use(ElementReqs::Optional))
    DE_COI  = Stupidedi::Schema::CompositeElementDef.build(:DE_COI, "CE COI", "",
      DE_ID.component_use(ElementReqs::Optional))
  end

  def de_ID ; ElementDefs::DE_ID  end
  def de_AN ; ElementDefs::DE_AN  end
  def de_DT6; ElementDefs::DE_DT6 end
  def de_DT8; ElementDefs::DE_DT8 end
  def de_TM ; ElementDefs::DE_TM  end
  def de_R  ; ElementDefs::DE_R   end
  def de_N0 ; ElementDefs::DE_N0  end
  def de_N1 ; ElementDefs::DE_N1  end
  def de_N2 ; ElementDefs::DE_N2  end
  def de_CON; ElementDefs::DE_CON end
  def de_COI; ElementDefs::DE_COI end

  module SegmentDefs
    ANA =
      Stupidedi::Schema::SegmentDef.build(:ANA, "Example Segment", "",
        ElementDefs::DE_AN.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    ANB =
      Stupidedi::Schema::SegmentDef.build(:ANB, "Example Segment", "",
        ElementDefs::DE_AN.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    IDA =
      Stupidedi::Schema::SegmentDef.build(:IDA, "Example Segment", "",
        ElementDefs::DE_ID.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)),
        ElementDefs::DE_N0.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    IDB =
      Stupidedi::Schema::SegmentDef.build(:IDB, "Example Segment", "",
        ElementDefs::DE_ID.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)),
        ElementDefs::DE_N0.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    IDC =
      Stupidedi::Schema::SegmentDef.build(:IDC, "Example Segment", "",
        ElementDefs::DE_ID.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)),
        ElementDefs::DE_N0.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    NNA =
      Stupidedi::Schema::SegmentDef.build(:NNA, "Example Segment", "",
        ElementDefs::DE_N0.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    NNB =
      Stupidedi::Schema::SegmentDef.build(:NNB, "Example Segment", "",
        ElementDefs::DE_N0.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)),
        ElementDefs::DE_AN.simple_use(ElementReqs::Optional,  RepeatCount.bounded(1)))

    COM =
      Stupidedi::Schema::SegmentDef.build(:COM, "Example Segment", "",
        ElementDefs::DE_CON.simple_use(ElementReqs::Optional, RepeatCount.bounded(1)))

    COI =
      Stupidedi::Schema::SegmentDef.build(:COI, "Example Segment", "",
        ElementDefs::DE_COI.simple_use(ElementReqs::Optional, RepeatCount.bounded(1)))

    COJ =
      Stupidedi::Schema::SegmentDef.build(:COJ, "Example Segment", "",
        ElementDefs::DE_COI.simple_use(ElementReqs::Optional, RepeatCount.bounded(1)))

    COK =
      Stupidedi::Schema::SegmentDef.build(:COK, "Example Segment", "",
        ElementDefs::DE_COI.simple_use(ElementReqs::Optional, RepeatCount.bounded(1)))

    COR =
      Stupidedi::Schema::SegmentDef.build(:COR, "Example Segment", "",
        ElementDefs::DE_CON.simple_use(ElementReqs::Optional, RepeatCount.bounded(3)))

    COS =
      Stupidedi::Schema::SegmentDef.build(:COS, "Example Segment", "",
        ElementDefs::DE_CON.simple_use(ElementReqs::Mandatory, RepeatCount.bounded(1)))

    REP =
      Stupidedi::Schema::SegmentDef.build(:REP, "Example Segment", "",
        ElementDefs::DE_N0.simple_use(ElementReqs::Optional, RepeatCount.bounded(3)))
  end

  def NNA; SegmentDefs::NNA end
  def NNB; SegmentDefs::NNB end
  def COM; SegmentDefs::COM end
  def COR; SegmentDefs::COR end
  def COS; SegmentDefs::COS end
  def REP; SegmentDefs::REP end

  def ANA(*args) AN_(SegmentDefs::ANA, *args) end
  def ANB(*args) AN_(SegmentDefs::ANB, *args) end
  def AN_(segment_def, changes = {})
    segment_def.bind do |s|
      return s if changes.empty?
      s.copy(:element_uses => s.element_uses.map{|u| u.copy(:definition => u.definition.copy(changes))})
    end
  end

  def IDA(*args) ID_(SegmentDefs::IDA, *args) end
  def IDB(*args) ID_(SegmentDefs::IDB, *args) end
  def IDC(*args) ID_(SegmentDefs::IDC, *args) end
  def ID_(segment_def, allowed_values = [], name = nil)
    segment_def.bind do |s|
      return s if allowed_values.empty? and name.nil?
      s.copy(
        :name         => name || s.name,
        :element_uses => s.element_uses.head.bind do |u|
          u.copy(:allowed_values => u.allowed_values.replace(allowed_values))
        end.cons(s.element_uses.tail))
    end
  end

  def COI(*args) CO_(SegmentDefs::COI, *args) end
  def COJ(*args) CO_(SegmentDefs::COJ, *args) end
  def COK(*args) CO_(SegmentDefs::COK, *args) end
  def CO_(segment_def, allowed_values = [], name = nil)
    segment_def.bind do |s|
      return s if allowed_values.empty? and name.nil?
      s.copy(
        :name         => name || s.name,
        :element_uses => s.element_uses.head.bind do |u|
          u.copy(:definition => u.definition.bind do |c|
            c.copy(:component_uses => c.component_uses.head.bind do |x|
              x.copy(:allowed_values => x.allowed_values.replace(allowed_values))
            end.cons(c.component_uses.tail))
          end)
        end.cons(s.element_uses.tail))
    end
  end
end

class << Definitions
  using Stupidedi::Refinements

  # @return [Array<String, InterchangeDef>]
  def interchange_defs(root = Stupidedi::Interchanges)
    select(Stupidedi::Schema::InterchangeDef, root)
  end

  # @return [Array<String, FunctionalGroupDef>]
  def functional_group_defs(root = Stupidedi::Versions)
    select(Stupidedi::Schema::FunctionalGroupDef, root)
  end

  # @return [Array<String, TransactionSetDef, Exception>]
  def transaction_set_defs(root = Stupidedi::TransactionSets)
    collect(root) do |name, value, error, visited, recurse|
      case error
      when Stupidedi::Exceptions::InvalidSchemaError
        [[name, value, error]]
      when Exception
        error.backtrace.reject!{|x| x =~ %r{spec/}}
        error.print(name: name)
        []
      else
        case value
        when Module
          collect(value, visited, &recurse)
        when Stupidedi::Schema::TransactionSetDef
          [[name, value, error]]
        else
          []
        end
      end
    end
  end

  # @return [Array<String, SegmentDef>]
  def segment_defs(root = Stupidedi)
    select(Stupidedi::Schema::SegmentDef, root)
  end

  # @return [Array<String, AbstractElementDef>]
  def element_defs(root = Stupidedi)
    select(Stupidedi::Schema::AbstractElementDef, root)
  end

private

  def collect(namespace, visited = Set.new, &block)
    namespace.constants.flat_map do |name|
      child = [namespace, name].join("::")

      if visited.include?(child)
        []
      else
        visited.add(child)

        value, error =
          begin
            [namespace.const_get(name), nil]
          rescue => error
            [nil, error]
          end

        block.call(child, value, error, visited, block)
      end
    end
  end

  # @return [Array<String, type>]
  def select(type, namespace, visited = Set.new, &block)
    collect(namespace, visited) do |name, value, error, visited_, recurse|
      case error
      when Exception
        []
      else
        if value.is_a?(Module)
          select(type, value, visited_, &recurse)
        elsif value.is_a?(type)
          [[name, value]]
        else
          []
        end
      end
    end
  end
end


text:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -Wall #-}

-- | Abstract types of performance measurement.
module Perf.Types
  ( Measure (..),
    repeated,
    StepMeasure (..),
    toMeasure,
    toMeasureN,
    step,
    stepM,
    multi,
    multiM,

    -- * function application
    fap,
    afap,
    ffap,
    fan,
    fam,
    (|$|),
    ($|),
    (|+|),

    -- * PerfT monad
    PerfT (..),
    Perf,
    runPerfT,
    evalPerfT,
    execPerfT,
    outer,
    slop,
    slops,
  )
where

import Control.DeepSeq
import Control.Monad.State.Lazy
import Data.Bifunctor
import Data.Functor.Identity
import qualified Data.Map.Strict as Map
import Data.String
import Data.Text (Text)
import Prelude

-- | Abstraction of a performance measurement within a monadic context.
--
-- - measure applies a function to a value, returning a tuple of the performance measure, and the computation result.
-- - measureM evaluates a monadic value and returns a performance-result tuple.
data Measure m t = Measure
  { measure :: forall a b. (a -> b) -> a -> m (t, b),
    measureM :: forall a. m a -> m (t, a)
  }

instance (Functor m) => Functor (Measure m) where
  fmap f (Measure m n) =
    Measure
      (\f' a' -> fmap (first f) (m f' a'))
      (fmap (first f) . n)

-- | An inefficient application that runs the inner action twice.
instance (Applicative m) => Applicative (Measure m) where
  pure t = Measure (\f a -> pure (t, f a)) (\a -> (t,) <$> a)
  (Measure mf nf) <*> (Measure mt nt) =
    Measure
      (\f a -> (\(nf', fa') (t', _) -> (nf' t', fa')) <$> mf f a <*> mt f a)
      (\a -> (\(nf', a') (t', _) -> (nf' t', a')) <$> nf a <*> nt a)

-- | Convert a Measure into a multi measure.
repeated :: (Applicative m) => Int -> Measure m t -> Measure m [t]
repeated n (Measure p m) =
  Measure
    (\f a -> fmap (\xs -> (fmap fst xs, snd (head xs))) (replicateM n (p f a)))
    (fmap (\xs -> (fmap fst xs, snd (head xs))) . replicateM n . m)
{-# INLINEABLE repeated #-}

-- | Abstraction of a performance measurement with a pre and a post step wrapping the computation.
data StepMeasure m t = forall i. StepMeasure {pre :: m i, post :: i -> m t}

instance (Functor m) => Functor (StepMeasure m) where
  fmap f (StepMeasure start stop) = StepMeasure start (fmap f . stop)

instance (Applicative m) => Applicative (StepMeasure m) where
  pure t = StepMeasure (pure ()) (const (pure t))
  (<*>) (StepMeasure fstart fstop) (StepMeasure start stop) =
    StepMeasure ((,) <$> fstart <*> start) (\(fi, i) -> fstop fi <*> stop i)

-- | Convert a StepMeasure into a Measure
toMeasure :: (Monad m) => StepMeasure m t -> Measure m t
toMeasure (StepMeasure pre' post') = Measure (step pre' post') (stepM pre' post')
{-# INLINEABLE toMeasure #-}

-- | Convert a StepMeasure into a Measure running the computation multiple times.
toMeasureN :: (Monad m) => Int -> StepMeasure m t -> Measure m [t]
toMeasureN n (StepMeasure pre' post') = Measure (multi (step pre' post') n) (multiM (stepM pre' post') n)
{-# INLINEABLE toMeasureN #-}

-- | A single step measurement.
step :: Monad m => m i -> (i -> m t) -> (a -> b) -> a -> m (t, b)
step pre' post' !f !a = do
  !p <- pre'
  !b <- pure $! f a
  !t <- post' p
  pure (t, b)
{-# INLINEABLE step #-}

-- | A single step measurement.
stepM :: Monad m => m i -> (i -> m t) -> m a -> m (t, a)
stepM pre' post' a = do
  !p <- pre'
  !ma <- a
  !t <- post' p
  pure (t, ma)
{-# INLINEABLE stepM #-}

-- | Multiple measurement
multi :: Monad m => ((a -> b) -> a -> m (t, b)) -> Int -> (a -> b) -> a -> m ([t], b)
multi action n !f !a =
  fmap (\xs -> (fmap fst xs, snd (head xs))) (replicateM n (action f a))
{-# INLINEABLE multi #-}

-- | Multiple measurements
multiM :: Monad m => (m a -> m (t, a)) -> Int -> m a -> m ([t], a)
multiM action n a =
  fmap (\xs -> (fmap fst xs, snd (head xs))) (replicateM n (action a))
{-# INLINEABLE multiM #-}

-- | Performance measurement transformer storing a 'Measure' and a map of named results.
newtype PerfT m t a = PerfT
  { measurePerf :: StateT (Measure m t, Map.Map Text t) m a
  }
  deriving (Functor, Applicative, Monad)

-- | The transformer over Identity
type Perf t a = PerfT Identity t a

instance (MonadIO m) => MonadIO (PerfT m t) where
  liftIO = PerfT . liftIO

-- | Lift an application to a PerfT m, providing a label and a 'Measure'.
--
-- Measurements with the same label will be mappended
fap :: (MonadIO m, Semigroup t) => Text -> (a -> b) -> a -> PerfT m t b
fap label f a =
  PerfT $ do
    m <- fst <$> get
    (t, fa) <- lift $ measure m f a
    modify $ second (Map.insertWith (<>) label t)
    return fa
{-# INLINEABLE fap #-}

-- | Lift an application to a PerfT m, forcing the argument.
afap :: (NFData a, MonadIO m, Semigroup t) => Text -> (a -> b) -> a -> PerfT m t b
afap label f a = fap label f (force a)
{-# INLINEABLE afap #-}

-- | Lift an application to a PerfT m, forcing argument and result.
ffap :: (NFData a, NFData b, MonadIO m, Semigroup t) => Text -> (a -> b) -> a -> PerfT m t b
ffap label f a = fap label (force . f) (force a)
{-# INLINEABLE ffap #-}

-- | Lift a number to a PerfT m, providing a label, function, and input.
--
-- Measurements with the same label will be added
fan :: (MonadIO m, Num t) => Text -> (a -> b) -> a -> PerfT m t b
fan label f a =
  PerfT $ do
    m <- fst <$> get
    (t, fa) <- lift $ measure m f a
    modify $ second (Map.insertWith (+) label t)
    return fa
{-# INLINEABLE fan #-}

-- | Lift a monadic value to a PerfT m, providing a label and a 'Measure'.
--
-- Measurements with the same label will be added
fam :: (MonadIO m, Semigroup t) => Text -> m a -> PerfT m t a
fam label a =
  PerfT $ do
    m <- fst <$> get
    (t, ma) <- lift $ measureM m a
    modify $ second (Map.insertWith (<>) label t)
    return ma
{-# INLINEABLE fam #-}

-- | lift a pure, unnamed function application to PerfT
(|$|) :: (Semigroup t) => (a -> b) -> a -> PerfT IO t b
(|$|) f a = fap "" f a
{-# INLINEABLE (|$|) #-}

-- | lift a monadic, unnamed function application to PerfT
($|) :: (Semigroup t) => IO a -> PerfT IO t a
($|) a = fam "" a
{-# INLINEABLE ($|) #-}

-- | lift an unnamed numeric measure to PerfT
(|+|) :: (Num t) => (a -> b) -> a -> PerfT IO t b
(|+|) f a = fan "" f a
{-# INLINEABLE (|+|) #-}

-- | Run the performance measure, returning (computational result, measurement).
runPerfT :: (Functor m) => Measure m t -> PerfT m t a -> m (a, Map.Map Text t)
runPerfT m p = fmap (second snd) <$> flip runStateT (m, Map.empty) $ measurePerf p
{-# INLINEABLE runPerfT #-}

-- | Consume the PerfT layer and return the original monadic result.
-- Fingers crossed, PerfT structure should be completely compiled away.
evalPerfT :: Monad m => Measure m t -> PerfT m t a -> m a
evalPerfT m p = fmap fst <$> flip runStateT (m, Map.empty) $ measurePerf p
{-# INLINEABLE evalPerfT #-}

-- | Consume a PerfT layer and return the measurement.
execPerfT :: Monad m => Measure m t -> PerfT m t a -> m (Map.Map Text t)
execPerfT m p = fmap snd <$> flip execStateT (m, Map.empty) $ measurePerf p
{-# INLINEABLE execPerfT #-}

-- | run a PerfT and also calculate performance over the entire computation
outer :: (MonadIO m, Semigroup s) => Text -> Measure m s -> Measure m t -> PerfT m t a -> m (a, (Map.Map Text s, Map.Map Text t))
outer label outerm meas p =
  (\((a, m), m') -> (a, (m', m)))
    <$> runPerfT
      outerm
      ( fam label (runPerfT meas p)
      )

-- | run a PerfT and calculate excess performance over the entire computation
slop :: (MonadIO m, Num t, Semigroup t) => Text -> Measure m t -> PerfT m t a -> m (a, Map.Map Text t)
slop l meas p =
  (\((a, m), m') -> (a, m <> Map.insert "slop" (m' Map.! l - Map.foldl' (+) 0 m) m'))
    <$> runPerfT
      meas
      ( fam l (runPerfT meas p)
      )

-- | run a multi PerfT and calculate excess performance over the entire computation
slops :: (MonadIO m, Num t, Semigroup t) => Int -> Measure m t -> PerfT m [t] a -> m (a, (Map.Map Text t, Map.Map Text [t]))
slops n meas p =
  (\((a, ms), m') -> (a, (Map.insert "slop" (m' Map.! "outer" - Map.foldl' (+) 0 (fmap sum ms)) m', ms)))
    <$> runPerfT
      meas
      ( fam "outer" (runPerfT (repeated n meas) p)
      )

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "bindings/core/v8/V8Window.h"

#include "bindings/core/v8/BindingSecurity.h"
#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/ScriptSourceCode.h"
#include "bindings/core/v8/SerializedScriptValue.h"
#include "bindings/core/v8/SerializedScriptValueFactory.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8EventListener.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8HTMLCollection.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8Node.h"
#include "core/dom/DOMArrayBuffer.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/MessagePort.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/html/HTMLCollection.h"
#include "core/html/HTMLDocument.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
#include "platform/PlatformScreen.h"
#include "wtf/Assertions.h"
#include "wtf/OwnPtr.h"

namespace blink {

void V8Window::eventAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info)
{
    LocalFrame* frame = toLocalDOMWindow(V8Window::toImpl(info.Holder()))->frame();
    ExceptionState exceptionState(ExceptionState::GetterContext, "event", "Window", info.Holder(), info.GetIsolate());
    if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), frame, exceptionState)) {
        exceptionState.throwIfNeeded();
        return;
    }

    ASSERT(frame);
    // This is a fast path to retrieve info.Holder()->CreationContext().
    v8::Local<v8::Context> context = toV8Context(frame, DOMWrapperWorld::current(info.GetIsolate()));
    if (context.IsEmpty())
        return;

    v8::Handle<v8::Value> jsEvent = V8HiddenValue::getHiddenValue(info.GetIsolate(), context->Global(), V8HiddenValue::event(info.GetIsolate()));
    if (jsEvent.IsEmpty())
        return;
    v8SetReturnValue(info, jsEvent);
}

void V8Window::eventAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    LocalFrame* frame = toLocalDOMWindow(V8Window::toImpl(info.Holder()))->frame();
    ExceptionState exceptionState(ExceptionState::SetterContext, "event", "Window", info.Holder(), info.GetIsolate());
    if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), frame, exceptionState)) {
        exceptionState.throwIfNeeded();
        return;
    }

    ASSERT(frame);
    // This is a fast path to retrieve info.Holder()->CreationContext().
    v8::Local<v8::Context> context = toV8Context(frame, DOMWrapperWorld::current(info.GetIsolate()));
    if (context.IsEmpty())
        return;

    V8HiddenValue::setHiddenValue(info.GetIsolate(), context->Global(), V8HiddenValue::event(info.GetIsolate()), value);
}

void V8Window::frameElementAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info)
{
    LocalDOMWindow* impl = toLocalDOMWindow(V8Window::toImpl(info.Holder()));
    ExceptionState exceptionState(ExceptionState::GetterContext, "frame", "Window", info.Holder(), info.GetIsolate());
    if (!BindingSecurity::shouldAllowAccessToNode(info.GetIsolate(), impl->frameElement(), exceptionState)) {
        v8SetReturnValueNull(info);
        exceptionState.throwIfNeeded();
        return;
    }

    // The wrapper for an <iframe> should get its prototype from the context of the frame it's in, rather than its own frame.
    // So, use its containing document as the creation context when wrapping.
    v8::Handle<v8::Value> creationContext = toV8(&impl->frameElement()->document(), info.Holder(), info.GetIsolate());
    RELEASE_ASSERT(!creationContext.IsEmpty());
    v8::Handle<v8::Value> wrapper = toV8(impl->frameElement(), v8::Handle<v8::Object>::Cast(creationContext), info.GetIsolate());
    v8SetReturnValue(info, wrapper);
}

void V8Window::openerAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    LocalDOMWindow* impl = toLocalDOMWindow(V8Window::toImpl(info.Holder()));
    ExceptionState exceptionState(ExceptionState::SetterContext, "opener", "Window", info.Holder(), info.GetIsolate());
    if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState)) {
        exceptionState.throwIfNeeded();
        return;
    }

    // Opener can be shadowed if it is in the same domain.
    // Have a special handling of null value to behave
    // like Firefox. See bug http://b/1224887 & http://b/791706.
    if (value->IsNull()) {
        // impl->frame() cannot be null,
        // otherwise, SameOrigin check would have failed.
        ASSERT(impl->frame());
        impl->frame()->loader().setOpener(0);
    }

    // Delete the accessor from this object.
    info.Holder()->Delete(v8AtomicString(info.GetIsolate(), "opener"));

    // Put property on the front (this) object.
    if (info.This()->IsObject())
        v8::Handle<v8::Object>::Cast(info.This())->Set(v8AtomicString(info.GetIsolate(), "opener"), value);
}

static bool isLegacyTargetOriginDesignation(v8::Handle<v8::Value> value)
{
    if (value->IsString() || value->IsStringObject())
        return true;
    return false;
}

void V8Window::postMessageMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    // None of these need to be RefPtr because info and context are guaranteed
    // to hold on to them.
    DOMWindow* window = V8Window::toImpl(info.Holder());
    LocalDOMWindow* source = callingDOMWindow(info.GetIsolate());

    ASSERT(window);
    UseCounter::countIfNotPrivateScript(info.GetIsolate(), window->frame(), UseCounter::WindowPostMessage);

    ExceptionState exceptionState(ExceptionState::ExecutionContext, "postMessage", "Window", info.Holder(), info.GetIsolate());

    // If called directly by WebCore we don't have a calling context.
    if (!source) {
        exceptionState.throwTypeError("No active calling context exists.");
        exceptionState.throwIfNeeded();
        return;
    }

    // This function has variable arguments and can be:
    // Per current spec:
    //   postMessage(message, targetOrigin)
    //   postMessage(message, targetOrigin, {sequence of transferrables})
    // Legacy non-standard implementations in webkit allowed:
    //   postMessage(message, {sequence of transferrables}, targetOrigin);
    MessagePortArray portArray;
    ArrayBufferArray arrayBufferArray;
    int targetOriginArgIndex = 1;
    if (info.Length() > 2) {
        int transferablesArgIndex = 2;
        if (isLegacyTargetOriginDesignation(info[2])) {
            UseCounter::countIfNotPrivateScript(info.GetIsolate(), window->frame(), UseCounter::WindowPostMessageWithLegacyTargetOriginArgument);
            targetOriginArgIndex = 2;
            transferablesArgIndex = 1;
        }
        if (!SerializedScriptValue::extractTransferables(info.GetIsolate(), info[transferablesArgIndex], transferablesArgIndex, portArray, arrayBufferArray, exceptionState)) {
            exceptionState.throwIfNeeded();
            return;
        }
    }
    TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, targetOrigin, info[targetOriginArgIndex]);

    RefPtr<SerializedScriptValue> message = SerializedScriptValueFactory::instance().create(info[0], &portArray, &arrayBufferArray, exceptionState, info.GetIsolate());
    if (exceptionState.throwIfNeeded())
        return;

    window->postMessage(message.release(), &portArray, targetOrigin, source, exceptionState);
    exceptionState.throwIfNeeded();
}

// FIXME(fqian): returning string is cheating, and we should
// fix this by calling toString function on the receiver.
// However, V8 implements toString in JavaScript, which requires
// switching context of receiver. I consider it is dangerous.
void V8Window::toStringMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Handle<v8::Object> domWrapper = V8Window::findInstanceInPrototypeChain(info.This(), info.GetIsolate());
    if (domWrapper.IsEmpty()) {
        v8SetReturnValue(info, info.This()->ObjectProtoToString());
        return;
    }
    v8SetReturnValue(info, domWrapper->ObjectProtoToString());
}

void V8Window::openMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    LocalDOMWindow* impl = toLocalDOMWindow(V8Window::toImpl(info.Holder()));
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "open", "Window", info.Holder(), info.GetIsolate());
    if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState)) {
        exceptionState.throwIfNeeded();
        return;
    }

    TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, urlString, info[0]);
    AtomicString frameName;
    if (info[1]->IsUndefined() || info[1]->IsNull()) {
        frameName = "_blank";
    } else {
        TOSTRING_VOID(V8StringResource<>, frameNameResource, info[1]);
        frameName = frameNameResource;
    }
    TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, windowFeaturesString, info[2]);

    RefPtrWillBeRawPtr<DOMWindow> openedWindow = impl->open(urlString, frameName, windowFeaturesString, callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()));
    if (!openedWindow)
        return;

    v8SetReturnValueFast(info, openedWindow.release(), impl);
}

void V8Window::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    if (!name->IsString())
        return;

    auto nameString = name.As<v8::String>();
    DOMWindow* window = V8Window::toImpl(info.Holder());
    if (!window)
        return;

    Frame* frame = window->frame();
    // window is detached from a frame.
    if (!frame)
        return;

    // Note that the spec doesn't allow any cross-origin named access to the window object. However,
    // UAs have traditionally allowed named access to named child browsing contexts, even across
    // origins. So first, search child frames for a frame with a matching name.
    AtomicString propName = toCoreAtomicString(nameString);
    Frame* child = frame->tree().scopedChild(propName);
    if (child) {
        v8SetReturnValueFast(info, child->domWindow(), window);
        return;
    }

    // Search IDL functions defined in the prototype
    if (!info.Holder()->GetRealNamedProperty(nameString).IsEmpty())
        return;

    // Frame could have been detached in call to GetRealNamedProperty.
    frame = window->frame();
    // window is detached.
    if (!frame)
        return;

    // If the frame is remote, the caller will never be able to access further named results.
    if (!frame->isLocalFrame())
        return;

    // Search named items in the document.
    Document* doc = toLocalFrame(frame)->document();
    if (!doc || !doc->isHTMLDocument())
        return;

    // This is an AllCanRead interceptor.  Check that the caller has access to the named results.
    if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), frame, DoNotReportSecurityError))
        return;

    if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) {
        RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName);
        if (!items->isEmpty()) {
            if (items->hasExactlyOneItem()) {
                v8SetReturnValueFast(info, items->item(0), window);
                return;
            }
            v8SetReturnValueFast(info, items.release(), window);
            return;
        }
    }
}

static bool securityCheck(v8::Local<v8::Object> host)
{
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    v8::Handle<v8::Object> window = V8Window::findInstanceInPrototypeChain(host, isolate);
    if (window.IsEmpty())
        return false; // the frame is gone.

    DOMWindow* targetWindow = V8Window::toImpl(window);
    ASSERT(targetWindow);
    if (!targetWindow->isLocalDOMWindow())
        return false;

    LocalFrame* target = toLocalDOMWindow(targetWindow)->frame();
    if (!target)
        return false;

    // Notify the loader's client if the initial document has been accessed.
    if (target->loader().stateMachine()->isDisplayingInitialEmptyDocument())
        target->loader().didAccessInitialDocument();

    return BindingSecurity::shouldAllowAccessToFrame(isolate, target, DoNotReportSecurityError);
}

bool V8Window::namedSecurityCheckCustom(v8::Local<v8::Object> host, v8::Local<v8::Value> key, v8::AccessType type, v8::Local<v8::Value>)
{
    return securityCheck(host);
}

bool V8Window::indexedSecurityCheckCustom(v8::Local<v8::Object> host, uint32_t index, v8::AccessType type, v8::Local<v8::Value>)
{
    return securityCheck(host);
}

v8::Handle<v8::Value> toV8(DOMWindow* window, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    // Notice that we explicitly ignore creationContext because the LocalDOMWindow is its own creationContext.

    if (!window)
        return v8::Null(isolate);
    // Initializes environment of a frame, and return the global object
    // of the frame.
    Frame * frame = window->frame();
    if (!frame)
        return v8Undefined();

    v8::Handle<v8::Context> context = toV8Context(frame, DOMWrapperWorld::current(isolate));
    if (context.IsEmpty())
        return v8Undefined();

    v8::Handle<v8::Object> global = context->Global();
    ASSERT(!global.IsEmpty());
    return global;
}

} // namespace blink


text:
class AddIthenticateIdToRevisions < ActiveRecord::Migration
  def change
    add_column :revisions, :ithenticate_id, :integer, default: nil
  end
end


text:
@interface IVVMoneyAmount : NSObject

@property (nonatomic, assign, readonly) IVVCurrencyType currencyType;
@property (nonatomic, strong, readonly) NSDecimalNumber *moneyAmount;

- (instancetype)initWithCurrencyType:(IVVCurrencyType)currencyType
                         moneyAmount:(NSDecimalNumber *)moneyAmount;

@end


text:
var es  = require('../')
  , it  = require('it-is')
  , d   = require('ubelt')

exports ['gate buffers when shut'] = function (test) {

  var hundy = d.map(1,100, d.id)
    , gate = es.pause()
    , ten = 10
  es.connect(
    es.readArray(hundy),
    es.log('after readArray'),
    gate,
    //es.log('after gate'),
    es.map(function (num, next) {
      //stick a map in here to check that gate never emits when open
      it(gate.paused).equal(false)
      console.log('data', num)
      if(!--ten) {
        console.log('PAUSE')
        gate.pause()//.resume()
        d.delay(gate.resume.bind(gate), 10)()
        ten = 10
      }

      next(null, num)
    }),
    es.writeArray(function (err, array) { //just realized that I should remove the error param. errors will be emitted
      console.log('eonuhoenuoecbulc')
      it(array).deepEqual(hundy)
      test.done()
    })
  )

  gate.resume()

}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Web.Mvc.Routing;
using System.Web.Routing;

namespace System.Web.Mvc
{
    internal static class AreaHelpers
    {
        public static string GetAreaName(RouteBase route)
        {
            IRouteWithArea routeWithArea = route as IRouteWithArea;
            if (routeWithArea != null)
            {
                return routeWithArea.Area;
            }

            Route castRoute = route as Route;
            if (castRoute != null && castRoute.DataTokens != null)
            {
                return castRoute.DataTokens[RouteDataTokenKeys.Area] as string;
            }

            return null;
        }

        public static string GetAreaName(RouteData routeData)
        {
            object area;
            if (routeData.DataTokens.TryGetValue(RouteDataTokenKeys.Area, out area))
            {
                return area as string;
            }

            return GetAreaName(routeData.Route);
        }
    }
}


text:
package com.amazonaws.services.applicationdiscovery.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAgentsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     * information about all agents/Connectors associated with your AWS user account.
     *

     */
    private java.util.List<String> agentIds;
    /**
     *

     * You can filter the request using various logical operators and a key-value format. For example:
     *

     *

     * {"key": "collectionStatus", "value": "STARTED"}
     *

     */
    private java.util.List<Filter> filters;
    /**
     *

     * The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     *

     */
    private Integer maxResults;
    /**
     *

     * Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     * DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10, you
     * received a set of 10 results along with a token. Use that token in this query to get the next set of 10.
     *

     */
    private String nextToken;

    /**
     *

     * The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     * information about all agents/Connectors associated with your AWS user account.
     *

     *
     * @return The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     *         information about all agents/Connectors associated with your AWS user account.
     */

    public java.util.List<String> getAgentIds() {
        return agentIds;
    }

    /**
     *

     * The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     * information about all agents/Connectors associated with your AWS user account.
     *

     *
     * @param agentIds
     *        The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     *        information about all agents/Connectors associated with your AWS user account.
     */

    public void setAgentIds(java.util.Collection<String> agentIds) {
        if (agentIds == null) {
            this.agentIds = null;
            return;
        }

        this.agentIds = new java.util.ArrayList<String>(agentIds);
    }

    /**
     *

     * The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     * information about all agents/Connectors associated with your AWS user account.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setAgentIds(java.util.Collection)} or {@link #withAgentIds(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param agentIds
     *        The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     *        information about all agents/Connectors associated with your AWS user account.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAgentsRequest withAgentIds(String... agentIds) {
        if (this.agentIds == null) {
            setAgentIds(new java.util.ArrayList<String>(agentIds.length));
        }
        for (String ele : agentIds) {
            this.agentIds.add(ele);
        }
        return this;
    }

    /**
     *

     * The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     * information about all agents/Connectors associated with your AWS user account.
     *

     *
     * @param agentIds
     *        The agent or the Connector IDs for which you want information. If you specify no IDs, the system returns
     *        information about all agents/Connectors associated with your AWS user account.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAgentsRequest withAgentIds(java.util.Collection<String> agentIds) {
        setAgentIds(agentIds);
        return this;
    }

    /**
     *

     * You can filter the request using various logical operators and a key-value format. For example:
     *

     *

     * {"key": "collectionStatus", "value": "STARTED"}
     *

     *
     * @return You can filter the request using various logical operators and a key-value format. For
     *         example:

     *

     *         {"key": "collectionStatus", "value": "STARTED"}
     */

    public java.util.List<Filter> getFilters() {
        return filters;
    }

    /**
     *

     * You can filter the request using various logical operators and a key-value format. For example:
     *

     *

     * {"key": "collectionStatus", "value": "STARTED"}
     *

     *
     * @param filters
     *        You can filter the request using various logical operators and a key-value format. For
     *        example:

     *

     *        {"key": "collectionStatus", "value": "STARTED"}
     */

    public void setFilters(java.util.Collection<Filter> filters) {
        if (filters == null) {
            this.filters = null;
            return;
        }

        this.filters = new java.util.ArrayList<Filter>(filters);
    }

    /**
     *

     * You can filter the request using various logical operators and a key-value format. For example:
     *

     *

     * {"key": "collectionStatus", "value": "STARTED"}
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setFilters(java.util.Collection)} or {@link #withFilters(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param filters
     *        You can filter the request using various logical operators and a key-value format. For
     *        example:

     *

     *        {"key": "collectionStatus", "value": "STARTED"}
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAgentsRequest withFilters(Filter... filters) {
        if (this.filters == null) {
            setFilters(new java.util.ArrayList<Filter>(filters.length));
        }
        for (Filter ele : filters) {
            this.filters.add(ele);
        }
        return this;
    }

    /**
     *

     * You can filter the request using various logical operators and a key-value format. For example:
     *

     *

     * {"key": "collectionStatus", "value": "STARTED"}
     *

     *
     * @param filters
     *        You can filter the request using various logical operators and a key-value format. For
     *        example:

     *

     *        {"key": "collectionStatus", "value": "STARTED"}
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAgentsRequest withFilters(java.util.Collection<Filter> filters) {
        setFilters(filters);
        return this;
    }

    /**
     *

     * The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     *

     *
     * @param maxResults
     *        The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     *

     *
     * @return The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     *

     *
     * @param maxResults
     *        The total number of agents/Connectors to return in a single page of output. The maximum value is 100.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAgentsRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     * DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10, you
     * received a set of 10 results along with a token. Use that token in this query to get the next set of 10.
     *

     *
     * @param nextToken
     *        Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     *        DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10,
     *        you received a set of 10 results along with a token. Use that token in this query to get the next set of
     *        10.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     * DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10, you
     * received a set of 10 results along with a token. Use that token in this query to get the next set of 10.
     *

     *
     * @return Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     *         DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10,
     *         you received a set of 10 results along with a token. Use that token in this query to get the next set of
     *         10.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     * DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10, you
     * received a set of 10 results along with a token. Use that token in this query to get the next set of 10.
     *

     *
     * @param nextToken
     *        Token to retrieve the next set of results. For example, if you previously specified 100 IDs for
     *        DescribeAgentsRequest$agentIds but set DescribeAgentsRequest$maxResults to 10,
     *        you received a set of 10 results along with a token. Use that token in this query to get the next set of
     *        10.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAgentsRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAgentIds() != null)
            sb.append("AgentIds: ").append(getAgentIds()).append(",");
        if (getFilters() != null)
            sb.append("Filters: ").append(getFilters()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeAgentsRequest == false)
            return false;
        DescribeAgentsRequest other = (DescribeAgentsRequest) obj;
        if (other.getAgentIds() == null ^ this.getAgentIds() == null)
            return false;
        if (other.getAgentIds() != null && other.getAgentIds().equals(this.getAgentIds()) == false)
            return false;
        if (other.getFilters() == null ^ this.getFilters() == null)
            return false;
        if (other.getFilters() != null && other.getFilters().equals(this.getFilters()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAgentIds() == null) ? 0 : getAgentIds().hashCode());
        hashCode = prime * hashCode + ((getFilters() == null) ? 0 : getFilters().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeAgentsRequest clone() {
        return (DescribeAgentsRequest) super.clone();
    }

}


text:
package ynn.mylogo.model.designtime.predefined.impl;

import ynn.mylogo.model.designtime.ArgumentDefinition;
import ynn.mylogo.model.designtime.impl.ActionDefinitionImpl;
import ynn.mylogo.model.designtime.impl.ArgumentDefinitionImpl;
import ynn.mylogo.model.runtime.Action;
import ynn.mylogo.model.runtime.NumericValue;
import ynn.mylogo.model.runtime.predefined.impl.TurnRightActionImpl;

public class TurnRightActionDefinitionImpl extends ActionDefinitionImpl
{

	public TurnRightActionDefinitionImpl()
	{
		super("RT");
		ArgumentDefinition argAngle = new ArgumentDefinitionImpl("A", NumericValue.class);
		getArguments().add(argAngle);
	}

	@Override
	public Action createRuntimeAction()
	{
		return new TurnRightActionImpl(this);
	}

}


text:
({
    /*******************************************************************************************************
    * @description called by the autocomplete component to retrieve the list of sources that matches
    * the criteria the user has typed in.
    */
    provide: function (component, event, helper) {
        var args = event.getParam('arguments');
        if (args && args.keyword && args.callback) {
            var queryAction = component.get('c.getAutocompleteResults');
            var sObjectType = component.get('v.sObjectType');
            queryAction.setParams({
                term: args.keyword,
                sObjectType: sObjectType
            });
            queryAction.setAbortable();
            queryAction.setCallback(
                this,
                function (response) {
                    var state = response.getState();
                    if ('SUCCESS' === state) {
                        args.callback(
                            null,
                            args.idDataCallback,
                            response.getReturnValue()
                        );
                    } else if ('ERROR' === state) {
                        var auraErrors = response.getError();
                        var errors = [];
                        if (auraErrors) {
                            for (var error in auraErrors) {
                                if (error.message) {
                                    errors.push(new Error(error.message));
                                }
                            }
                        }
                        args.callback(
                            errors,
                            args.idDataCallback,
                            []
                        );
                    }
                }
            );
            $A.enqueueAction(queryAction);
        } else {
            args.callback(null, []);
        }
    },
})


text:
Requests counter for CartoDB
========================

Provides statistics about requests per day made in cartodb boxes.


text:
var ciudadModule = angular.module('ciudad');

// ciudad controller
ciudadModule.controller('ciudadController', [
	'$scope',
	'$http',
	'$routeParams',
	'$location',
	'Authentication',
	'Ciudad',
	'Pais',
	'Notify',
	'$modal',
	'$log',
	function($scope, $http, $routeParams, $location, Authentication, Ciudad, Pais, Notify, $modal, $log) {
	'use strict';
	this.authentication = Authentication;

	    // Find a list of ciudad
	   this.ciudad = Ciudad.query();

    //Open the middleware to open a single ciudad modal.
	 this.modelCreate = function (size) {
		    var modalInstance = $modal.open({
		      templateUrl: 'ciudad/views/create-ciudad.client.view.html',
		      controller: 'modalResutl',
		      size: size
		 });

	 modalInstance.result.then(function (selectedItem) {
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

     //Open the middleware to open a single ciudad modal.
	 this.modelUpdate = function (size, selectedciudad) {
		    var modalInstance = $modal.open({
		      templateUrl: 'ciudad/views/edit-ciudad.client.view.html',
		      controller:  ['$scope', '$modalInstance', 'ciudad', function ($scope, $modalInstance, ciudad) {
                 $scope.ciudad = ciudad;
                 $scope.ciudad.rpais = selectedciudad.pais._id;
                 Notify.sendbroadCast('noError', 'this is a message');
                 $scope.ok = function () {
                  $modalInstance.close($scope.ciudad);
				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };

		      }],
		      size: size,
		      resolve: {
		        ciudad: function () {
		          return selectedciudad;
		        }
		      }
		 });

	 modalInstance.result.then(function (selectedciudad) {
      $scope.selected = selectedciudad;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };
	  // Remove existing Pai
	this.remove = function(ciudad) {
			if( ciudad ) {
				ciudad.$remove();

				for (var i in this.ciudad) {
					if (this.ciudad [i] === ciudad) {
						this.ciudad.splice(i, 1);
					}
				}
			} else {
				this.ciudad.$remove(function() {
				});
			}
		};

	 }
]);

ciudadModule.controller('modalResutl',  function ($scope, $modalInstance) {
  'use strict';

  $scope.ok = function () {
    $modalInstance.close();
   };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

ciudadModule.controller('CiudadCreateController', ['$scope',  'Ciudad', 'Notify', 'Pais',
	function($scope, Ciudad, Notify, Pais) {
	'use strict';

	  this.pais = Pais.query();
	  	// // Create new Pai
	  this.create = function() {
			// Create new Pai object
	   var ciudads = new Ciudad ({
				name: this.name,
				pais: this.Selectedpais
	   });

			// Redirect after save
			ciudads.$save(function(response) {
             Notify.sendMsg('newPis', {'id': response._id});
				// Clear form fields
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

	}
]);

ciudadModule.controller('ciudadUpdateController', ['$scope', 'Authentication', 'Ciudad', 'Pais', 'Notify',
	function($scope, Authentication, Ciudad, Pais, Notify) {
        'use strict';

          this.pais = Pais.query();
	      this.update = function(updateciudad) {

	      var ciudad = new Ciudad ({
	      		_id: updateciudad._id,
				name: updateciudad.name,
				pais: $scope.ciudad.rpais
	       });

		  ciudad.$update(function() {
		  	 Notify.sendMsg('newPis', {'id': 'update'});
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
	   };

	}
]);

ciudadModule.directive('ciudadList', ['Ciudad', 'Notify', function(Ciudad, Notify){
    'use strict';
    return {
    restrict: 'E',
    transclude: true,
    templateUrl: 'ciudad/views/ciudad-list.template.html',
    link: function(scope, element, attr){
           Notify.getMsg('newPis', function(event, data){
            scope.ciudadCtrl.ciudad = Ciudad.query();
         });
    }
  };
}]);


text:
import { TableBody } from "./TableBody";
import { Row } from "../../models/Row";
export declare class ScrollableTableBody extends TableBody {
    mapRowsInBody(rowHeight: string, row: Row, i: number): JSX.Element;
}


text:
namespace network
{
	class cTCPClient
	{
	public:
		cTCPClient(iProtocol *protocol = new cProtocol());
		virtual ~cTCPClient();

		bool Init(const string &ip, const int port,
			const int packetSize = 512, const int maxPacketCount = 10, const int sleepMillis = 30);
		void Send(iProtocol *protocol, BYTE *buff, const int len);
		void Close();
		bool IsConnect() const;

		static unsigned WINAPI TCPClientThreadFunction(void* arg);

	public:
		string m_ip;
		int m_port;
		bool m_isConnect;
		SOCKET m_socket; // server socket
		int m_maxBuffLen;
		iProtocol *m_protocol;
		cPacketQueue m_sendQueue;
		cPacketQueue m_recvQueue;

		std::thread m_thread;
		bool m_threadLoop;
		int m_sleepMillis;
		int m_recvBytes; // debug
		bool m_isLog; // debug
	};

	inline bool cTCPClient::IsConnect() const { return m_isConnect;  }
}


text:
class MatcherType(object):
    """
    Interface for each Matcher functions. All matchers types must be implement get_ratio_match method between two
    objects and return a ratio value.
    """

    def get_ratio_match(self, object_a, object_b):
        pass


text:
<!--
@license
// Copyright (c) 2014 The Polymer Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<link rel="import" href="../polymer/polymer.html">

<dom-module id="tiny-badge">
  <style>
    :host {
      display: inline-block;
      padding: 2px 5px;
      font-size: 13px;
      font-weight: bold;
      line-height: 1;
      color: white;
      background-color: #E91E63;
      border-radius: 20px;
    }
  </style>
  <template>
    <content></content>
  </template>
</dom-module>

<script>
  Polymer({
    is: 'tiny-badge'
  });
</script>


text:
"""Reads vehicle status from BMW connected drive portal."""
import logging

from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN
from homeassistant.const import LENGTH_KILOMETERS

DEPENDENCIES = ['bmw_connected_drive']

_LOGGER = logging.getLogger(__name__)

SENSOR_TYPES = {
    'lids': ['Doors', 'opening'],
    'windows': ['Windows', 'opening'],
    'door_lock_state': ['Door lock state', 'safety'],
    'lights_parking': ['Parking lights', 'light'],
    'condition_based_services': ['Condition based services', 'problem'],
    'check_control_messages': ['Control messages', 'problem']
}

SENSOR_TYPES_ELEC = {
    'charging_status': ['Charging status', 'power'],
    'connection_status': ['Connection status', 'plug']
}

SENSOR_TYPES_ELEC.update(SENSOR_TYPES)

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the BMW sensors."""
    accounts = hass.data[BMW_DOMAIN]
    _LOGGER.debug('Found BMW accounts: %s',
                  ', '.join([a.name for a in accounts]))
    devices = []
    for account in accounts:
        for vehicle in account.account.vehicles:
            if vehicle.has_hv_battery:
                _LOGGER.debug('BMW with a high voltage battery')
                for key, value in sorted(SENSOR_TYPES_ELEC.items()):
                    device = BMWConnectedDriveSensor(
                        account, vehicle, key, value[0], value[1])
                    devices.append(device)
            elif vehicle.has_internal_combustion_engine:
                _LOGGER.debug('BMW with an internal combustion engine')
                for key, value in sorted(SENSOR_TYPES.items()):
                    device = BMWConnectedDriveSensor(
                        account, vehicle, key, value[0], value[1])
                    devices.append(device)
    add_entities(devices, True)

class BMWConnectedDriveSensor(BinarySensorDevice):
    """Representation of a BMW vehicle binary sensor."""

    def __init__(self, account, vehicle, attribute: str, sensor_name,
                 device_class):
        """Constructor."""
        self._account = account
        self._vehicle = vehicle
        self._attribute = attribute
        self._name = '{} {}'.format(self._vehicle.name, self._attribute)
        self._unique_id = '{}-{}'.format(self._vehicle.vin, self._attribute)
        self._sensor_name = sensor_name
        self._device_class = device_class
        self._state = None

    @property
    def should_poll(self) -> bool:
        """Return False.

        Data update is triggered from BMWConnectedDriveEntity.
        """
        return False

    @property
    def unique_id(self):
        """Return the unique ID of the binary sensor."""
        return self._unique_id

    @property
    def name(self):
        """Return the name of the binary sensor."""
        return self._name

    @property
    def device_class(self):
        """Return the class of the binary sensor."""
        return self._device_class

    @property
    def is_on(self):
        """Return the state of the binary sensor."""
        return self._state

    @property
    def device_state_attributes(self):
        """Return the state attributes of the binary sensor."""
        vehicle_state = self._vehicle.state
        result = {
            'car': self._vehicle.name
        }

        if self._attribute == 'lids':
            for lid in vehicle_state.lids:
                result[lid.name] = lid.state.value
        elif self._attribute == 'windows':
            for window in vehicle_state.windows:
                result[window.name] = window.state.value
        elif self._attribute == 'door_lock_state':
            result['door_lock_state'] = vehicle_state.door_lock_state.value
            result['last_update_reason'] = vehicle_state.last_update_reason
        elif self._attribute == 'lights_parking':
            result['lights_parking'] = vehicle_state.parking_lights.value
        elif self._attribute == 'condition_based_services':
            for report in vehicle_state.condition_based_services:
                result.update(
                    self._format_cbs_report(report))
        elif self._attribute == 'check_control_messages':
            check_control_messages = vehicle_state.check_control_messages
            if not check_control_messages:
                result['check_control_messages'] = 'OK'
            else:
                cbs_list = []
                for message in check_control_messages:
                    cbs_list.append(message['ccmDescriptionShort'])
                result['check_control_messages'] = cbs_list
        elif self._attribute == 'charging_status':
            result['charging_status'] = vehicle_state.charging_status.value
            # pylint: disable=protected-access
            result['last_charging_end_result'] = \
                vehicle_state._attributes['lastChargingEndResult']
        if self._attribute == 'connection_status':
            # pylint: disable=protected-access
            result['connection_status'] = \
                vehicle_state._attributes['connectionStatus']

        return sorted(result.items())

    def update(self):
        """Read new state data from the library."""
        from bimmer_connected.state import LockState
        from bimmer_connected.state import ChargingState
        vehicle_state = self._vehicle.state

        # device class opening: On means open, Off means closed
        if self._attribute == 'lids':
            _LOGGER.debug("Status of lid: %s", vehicle_state.all_lids_closed)
            self._state = not vehicle_state.all_lids_closed
        if self._attribute == 'windows':
            self._state = not vehicle_state.all_windows_closed
        # device class safety: On means unsafe, Off means safe
        if self._attribute == 'door_lock_state':
            # Possible values: LOCKED, SECURED, SELECTIVE_LOCKED, UNLOCKED
            self._state = vehicle_state.door_lock_state not in \
                          [LockState.LOCKED, LockState.SECURED]
        # device class light: On means light detected, Off means no light
        if self._attribute == 'lights_parking':
            self._state = vehicle_state.are_parking_lights_on
        # device class problem: On means problem detected, Off means no problem
        if self._attribute == 'condition_based_services':
            self._state = not vehicle_state.are_all_cbs_ok
        if self._attribute == 'check_control_messages':
            self._state = vehicle_state.has_check_control_messages
        # device class power: On means power detected, Off means no power
        if self._attribute == 'charging_status':
            self._state = vehicle_state.charging_status in \
                          [ChargingState.CHARGING]
        # device class plug: On means device is plugged in,
        #                    Off means device is unplugged
        if self._attribute == 'connection_status':
            # pylint: disable=protected-access
            self._state = (vehicle_state._attributes['connectionStatus'] ==
                           'CONNECTED')

    def _format_cbs_report(self, report):
        result = {}
        service_type = report.service_type.lower().replace('_', ' ')
        result['{} status'.format(service_type)] = report.state.value
        if report.due_date is not None:
            result['{} date'.format(service_type)] = \
                report.due_date.strftime('%Y-%m-%d')
        if report.due_distance is not None:
            distance = round(self.hass.config.units.length(
                report.due_distance, LENGTH_KILOMETERS))
            result['{} distance'.format(service_type)] = '{} {}'.format(
                distance, self.hass.config.units.length_unit)
        return result

    def update_callback(self):
        """Schedule a state update."""
        self.schedule_update_ha_state(True)

    async def async_added_to_hass(self):
        """Add callback after being added to hass.

        Show latest data after startup.
        """
        self._account.add_update_listener(self.update_callback)


text:
@protocol XHThumbnailAnnotationDelegate <NSObject>

- (MKAnnotationView *)annotationViewInMap:(MKMapView *)mapView;

@end

@interface XHThumbnailAnnotation : NSObject <MKAnnotation, XHThumbnailAnnotationDelegate>

@property (nonatomic, strong) XHThumbnailAnnotationView *thumbnailAnnotationView;
@property (nonatomic, strong) XHThumbnail *thumbnail;
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;

- (instancetype)initWithThumbnail:(XHThumbnail *)thumbnail;
- (void)updateThumbnail:(XHThumbnail *)thumbnail animated:(BOOL)animated;

@end


text:
<?php

namespace Opifer\EavBundle\ValueProvider;

use Symfony\Component\Form\FormBuilderInterface;

interface ValueProviderInterface
{
    /**
     * Build form
     *
     * @param FormBuilderInterface $builder
     * @param array                $options
     *
     * @return void
     */
    public function buildForm(FormBuilderInterface $builder, array $options);

    /**
     * Get the full entity namespace
     *
     * @return string
     */
    public function getEntity();

    /**
     * Get name
     *
     * @return string
     */
    public function getName();

    /**
     * Get label
     *
     * @return string
     */
    public function getLabel();

    /**
     * Check if the current valueprovider is enabled
     *
     * @return boolean
     */
    public function isEnabled();
}


text:
require File.join(File.dirname(__FILE__),"..","mono_table_helper_methods")

describe Monotable::DiskChunk do
  include MonotableHelperMethods
  it_should_behave_like "monotable api"

  #***************************************
  # helpers
  #***************************************
  def blank_store
    reset_temp_dir
    filename=File.join(temp_dir,"test#{Monotable::CHUNK_EXT}")
    Monotable::MemoryChunk.new().save(filename)
    Monotable::DiskChunk.init(:filename=>filename)
  end

  #***************************************
  # tests
  #***************************************
  it "should be possible to read chunkified directory" do
    file=chunkify_test_data_directory

    chunk = Monotable::DiskChunk.new(:filename=>file)
  end

  it "should be possible to list chunkified directory" do
    file=chunkify_test_data_directory

    chunk = Monotable::DiskChunk.new(:filename=>file)
    chunk.keys.sort.should == %w{0-255.binary 0-65535.words.binary declaration_of_independence.txt plato.jpeg simple.png}
  end

  it "should return nil if key is not in chunk" do
    file=chunkify_test_data_directory

    chunk = Monotable::DiskChunk.new(:filename=>file)
    chunk["not_there"].should == nil
  end

  def test_read(chunk,filename)
    data=chunk[filename]
    data.should_not == nil
    data["file_data"].should == load_test_data(filename)
  end

  it "should be possible to extract values from chunkified directory" do
    file=chunkify_test_data_directory

    chunk = Monotable::DiskChunk.new(:filename=>file)

    test_read(chunk,"declaration_of_independence.txt")
    test_read(chunk,"plato.jpeg")
    test_read(chunk,"0-255.binary")
  end

  it "should work to journal a 'set' to a DiskChunk" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.set("foo",{"bar" => "June"})

    # test get after set with DiskChunk
    chunkfile["foo"].should == {"bar"=>"June"}
  end

  it "should work to 'get' using Monotable::MemoryChunk from a journaled entry" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.set("foo",{"bar" => "June"})
    chunkfile.journal.compact

    # test full loading with MemoryChunk
    chunk = Monotable::MemoryChunk.load(file)
    chunk.keys.sort.should == ["0-255.binary", "0-65535.words.binary", "declaration_of_independence.txt", "plato.jpeg", "simple.png", "foo"].sort
    chunk["foo"].should == {"bar" => "June"}
  end

  it "should work to 'get' after 'set' using Monotable::DiskChunk from a journaled entry" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.set("foo",{"bar" => "June"})
    chunkfile["foo"].should == {"bar" => "June"}

    # compact the chunkfile
    chunkfile.journal.compact

    # test partial loading with DiskChunk
    chunkfile2 = Monotable::DiskChunk.new(:filename=>file)
    chunkfile2["foo"].should =={"bar" => "June"}
  end

  it "should work to 'delete' using Monotable::MemoryChunk and a journaled entry" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.delete("declaration_of_independence.txt")
    chunkfile.journal.compact

    # test partial loading with DiskChunk
    chunkfile2 = Monotable::MemoryChunk.load(file)
    chunkfile2["declaration_of_independence.txt"].should == nil
  end

  it "should work to 'delete' using Monotable::DiskChunk and a journaled entry" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile["declaration_of_independence.txt"]["file_data"].length.should == 407
    chunkfile.delete("declaration_of_independence.txt")
    chunkfile["declaration_of_independence.txt"].should == nil

    # compact the chunkfile
    chunkfile.journal.compact

    # test partial loading with DiskChunk
    chunkfile2 = Monotable::DiskChunk.new(:filename=>file)
    chunkfile2["declaration_of_independence.txt"].should == nil
  end

  it "should work to journal an 'update' to a DiskChunk" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.set("foo",{"bar" => "June", "baz" => "December"})
    chunkfile.journal.compact

    chunk = Monotable::MemoryChunk.load(file)
    chunk["foo"].should == {"bar" => "June", "baz" => "December"}

    chunkfile = Monotable::DiskChunk.new(:filename=>file)
    chunkfile.verify_records
    chunkfile.update("foo",{"baz" => "January"})
    chunkfile.journal.compact

    chunk = Monotable::MemoryChunk.load(file)
    chunk.keys.sort.should == ["0-255.binary", "0-65535.words.binary", "declaration_of_independence.txt", "plato.jpeg", "simple.png", "foo"].sort
    chunk["foo"].should == {"bar" => "June", "baz" => "January"}
  end

  it "should work to journal a 'delete' to a DiskChunk" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.delete("plato.jpeg")
    chunkfile.journal.compact

    chunk = Monotable::MemoryChunk.load(file)

    chunk.keys.sort.should == ["0-255.binary", "0-65535.words.binary", "declaration_of_independence.txt", "simple.png"].sort
    chunk["plato.jpeg"].should == nil
  end

  it "each_key should return valid keys matched to record" do
    file=chunkify_test_data_directory

    chunkfile = Monotable::DiskChunk.new(:filename=>file)

    chunkfile.each_key do |k|
      record=chunkfile.get_record(k)
      record.should_not == nil
    end
  end

  it "each_key should work and records should be fetchable if there data is in the journal" do
    result=setup_store_with_test_keys(5)
    result.each_key do |k|
      record=result.get_record(k)
      record.class.should==Monotable::JournalDiskRecord
      record.should_not == nil
    end
  end

  it "each_key should work and records should be fetchable if their data is in the chunkfile" do
    chunk_store=setup_store_with_test_keys(5)
    chunk_store.journal.compact
    chunk_store.reset
    chunk_store.each_key do |k|
      record=chunk_store.get_record(k)
      record.class.should==Monotable::DiskRecord
      record.keys.should==["data"]
      record.should_not == nil
    end
  end

end


text:
@interface MVITunesSearchResult : NSObject
@property (copy, nonatomic) NSString *appBundleId;
@property (copy, nonatomic) NSString *appId;
@property (copy, nonatomic) NSString *appName;
@property (copy, nonatomic) NSString *appURL;
@property (copy, nonatomic) NSString *iconArtworkSize60URL;
@property (copy, nonatomic) NSString *iconArtworkSize100URL;
@property (copy, nonatomic) NSString *iconArtworkSize512URL;
@property (copy, nonatomic) NSDictionary *result;
@end


text:
import os

import unittest
from tkp.testutil.decorators import requires_database, requires_data, duration
from tkp.testutil.data import DATAPATH

def debug_print(*args):
    return #Comment to switch on debug prints.
    print "**",
    for a in args:
        print a,
    print "**"

testfile1 = '/bin/true'
testfile2 = '/bin/false'
dummypath = '/dummypath/dummypath'

class TestDatabaseDecorators(unittest.TestCase):
    @requires_database()
    def test_requires_database(self):
        debug_print("Database testing enabled.")

class TestDataDecorators(unittest.TestCase):
    def test_datapath_defined(self):
        self.assertNotEqual(DATAPATH, None)
        debug_print("Test data path:", DATAPATH)

    @requires_data(testfile1, testfile2)
    def test_requires_data_decorator(self):
        self.assertTrue(os.path.exists(testfile1))
        self.assertTrue(os.path.exists(testfile2))

    @requires_data(dummypath)
    def test_requires_data_decorator_skips(self):
        self.assertTrue(os.path.exists(dummypath))

    @requires_data(dummypath, testfile1)
    def test_requires_data_decorator_skips_for_partial_miss(self):
        self.assertTrue(os.path.exists(dummypath))

class TestDurationDecorator(unittest.TestCase):
    def test_max_duration_defined(self):
        debug_print("Max_duration:", os.environ.get("TKP_MAXTESTDURATION", False))

    @duration(5)
    def test_short(self):
        debug_print("Will run test duration = 5")
    @duration(25)
    def test_medium(self):
        debug_print("Will run test duration = 25")
    @duration(300)
    def test_long(self):
        debug_print("Will run test duration = 300")


text:
<?php $theme->display('header'); ?>

<div id="maincontent">
	<?php echo $theme->content($post); ?>
</div>

<aside id="sidebar">
	<?php echo $theme->area('sidebar', 'sidebar'); ?>
</aside>

<?php $theme->display('footer'); ?>


text:
require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Wunderlist < OmniAuth::Strategies::OAuth2
      option :name, 'wunderlist'
      option :client_options, {
        site: "https://a.wunderlist.com/api",
        authorize_url: "https://www.wunderlist.com/oauth/authorize",
        token_url: "https://www.wunderlist.com/oauth/access_token",
        connection_opts: {
          headers: {
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
          }
        }
      }

      def request_phase
        super
      end

      uid { raw_info['id'] }

      info do
        {
          email: raw_info['email'],
          name: raw_info['name']
        }
      end

      extra do
        { raw_info: raw_info }
      end

      def raw_info
        access_token.options[:mode] = :query
        @raw_info ||= access_token.get('/api/v1/user', {
          headers: {
            'X-Client-ID' => access_token.client.id,
            'X-Access-Token' => access_token.token
          }
        }).parsed
      end
    end
  end
end


text:
class AddBoardIdToIssueToSectionConnections < ActiveRecord::Migration
  def change
    add_column :issue_to_section_connections, :board_id, :integer

    add_index :issue_to_section_connections, :board_id
  end
end


text:
using System.IO;

namespace QFramework
{
#if UNITY_EDITOR
    [ClassAPI("1.FluentAPI.CSharp", "System.IO", 2)]
    [APIDescriptionCN("针对 System.IO 提供的链式扩展,主要是文件和文件夹的一些 IO 操作")]
    [APIDescriptionEN("IO chain extension for system. IO, mainly file and folder IO operations")]
#endif
    public static class SystemIOExtension
    {
#if UNITY_EDITOR
        // v1 No.10
        [MethodAPI]
        [APIDescriptionCN("创建文件夹,如果存在则不创建")]
        [APIDescriptionEN("Create folder or not if it exists")]
        [APIExampleCode(@"
var testDir = ""Assets/TestFolder"";
testDir.CreateDirIfNotExists();"
        )]
#endif
        public static string CreateDirIfNotExists(this string dirFullPath)
        {
            if (!Directory.Exists(dirFullPath))
            {
                Directory.CreateDirectory(dirFullPath);
            }

            return dirFullPath;
        }

#if UNITY_EDITOR
        // v1 No.11
        [MethodAPI]
        [APIDescriptionCN("删除文件夹,如果存在")]
        [APIDescriptionEN("Delete the folder if it exists")]
        [APIExampleCode(@"
var testDir =""Assets/TestFolder"";
testDir.DeleteDirIfExists();
        ")]
#endif
        public static void DeleteDirIfExists(this string dirFullPath)
        {
            if (Directory.Exists(dirFullPath))
            {
                Directory.Delete(dirFullPath, true);
            }
        }

#if UNITY_EDITOR
        // v1 No.12
        [MethodAPI]
        [APIDescriptionCN("清空 Dir(保留目录),如果存在")]
        [APIDescriptionEN("Clear Dir (reserved directory), if exists")]
        [APIExampleCode(@"
var testDir = ""Assets/TestFolder"";
testDir.EmptyDirIfExists();
        ")]
#endif
        public static void EmptyDirIfExists(this string dirFullPath)
        {
            if (Directory.Exists(dirFullPath))
            {
                Directory.Delete(dirFullPath, true);
            }

            Directory.CreateDirectory(dirFullPath);
        }

#if UNITY_EDITOR
        // v1 No.13
        [MethodAPI]
        [APIDescriptionCN("删除文件 如果存在")]
        [APIDescriptionEN("Delete the file if it exists")]
        [APIExampleCode(@"
var filePath = ""Assets/Test.txt"";
File.Create(""Assets/Test"");
filePath.DeleteFileIfExists();
        ")]
#endif
        public static bool DeleteFileIfExists(this string fileFullPath)
        {
            if (File.Exists(fileFullPath))
            {
                File.Delete(fileFullPath);
                return true;
            }

            return false;
        }

#if UNITY_EDITOR
        // v1 No.14
        [MethodAPI]
        [APIDescriptionCN("合并路径")]
        [APIDescriptionEN("Combine path")]
        [APIExampleCode(@"
var path = Application.dataPath.CombinePath(""Resources"");
Debug.Log(Path)
// projectPath/Assets/Resources
        ")]
#endif
        public static string CombinePath(this string selfPath, string toCombinePath)
        {
            return Path.Combine(selfPath, toCombinePath);
        }

#if UNITY_EDITOR
        // v1 No.15
        [MethodAPI]
        [APIDescriptionCN("根据路径获取文件名")]
        [APIDescriptionEN("get file name by path")]
        [APIExampleCode(@"
var fileName =""/abc/def/b.txt"".GetFileName();
Debug.Log(fileName0);
// b.txt
        ")]
#endif
        public static string GetFileName(this string filePath)
        {
            return Path.GetFileName(filePath);
        }

#if UNITY_EDITOR
        // v1 No.16
        [MethodAPI]
        [APIDescriptionCN("根据路径获取文件名,不包含文件扩展名")]
        [APIDescriptionEN("Get the file name based on the path, excluding the file name extension")]
        [APIExampleCode(@"
var fileName =""/abc/def/b.txt"".GetFileNameWithoutExtend();
Debug.Log(fileName0);
// b
        ")]
#endif

        public static string GetFileNameWithoutExtend(this string filePath)
        {
            return Path.GetFileNameWithoutExtension(filePath);
        }

#if UNITY_EDITOR
        // v1 No.17
        [MethodAPI]
        [APIDescriptionCN("根据路径获取文件扩展名")]
        [APIDescriptionEN("Get the file extension based on the path")]
        [APIExampleCode(@"
var fileName =""/abc/def/b.txt"".GetFileExtendName();
Debug.Log(fileName0);
// .txt
        ")]
#endif
        public static string GetFileExtendName(this string filePath)
        {
            return Path.GetExtension(filePath);
        }

#if UNITY_EDITOR
        // v1 No.156
        [MethodAPI]
        [APIDescriptionCN("获取文件夹路径")]
        [APIDescriptionEN("get filePath's folder path")]
        [APIExampleCode(@"
var folderPath =""/abc/def/b.txt"".GetFolderPath();
Debug.Log(fileName0);
// /abs/def
        ")]
#endif
        public static string GetFolderPath(this string path)
        {
                if (string.IsNullOrEmpty(path))
                {
                        return string.Empty;
                }

                return Path.GetDirectoryName(path);
        }

    }
}


text:
var client = new ApiClient("your access token");
client.GetMerchantPreAuthorizations("merchant id");


text:
'use strict';

lib.dom.ready().then(function () {

    var windows = [],
        files = [
            'dev/jscore.js',
            'dev/jscore-ie9.js',
            'dev/jscore-ie10.js',
            'dev/jscore-polyfill.js',
            'dev/jscore-polyfill-ie9.js',
            'dev/jscore-polyfill-ie10.js',
            'min/jscore.js',
            'min/jscore-ie9.js',
            'min/jscore-ie10.js',
            'min/jscore-polyfill.js',
            'min/jscore-polyfill-ie9.js',
            'min/jscore-polyfill-ie10.js'
        ],
        width = Math.round(screen.availWidth / files.length),
        height = 200,
        top = screen.availHeight - height,
        options = new lib.Template([
            'width={WIDTH}',
            'height={HEIGHT}',
            'left={LEFT}',
            'top={TOP}',
            'scrollbars=no'
        ].join(',')),
        html = new lib.Template([
            '<!DOCTYPE html>',
            '',
            '',

                '<meta charset="UTF-8">',
                '<meta http-equiv="X-UA-Compatible" content="IE=edge">',
                '<title>{JSCORE}</title>',
                '<link rel="shortcut icon" href="favicon.ico">',
                '<link rel="stylesheet" href="test/test.css">',

            '',
            '',

                '
{JSCORE}
',

                '


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Polynomial on Datathings' Blog</title>
    <link>http://datathings.com/blog/tags/polynomial/index.xml</link>
    <description>Recent content in Polynomial on Datathings' Blog</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <atom:link href="http://datathings.com/blog/tags/polynomial/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Time series decomposition over open weather data from Luxembourg</title>
      <link>http://datathings.com/blog/post/weatherlux/</link>
      <pubDate>Wed, 22 Mar 2017 14:29:24 +0100</pubDate>

      <guid>http://datathings.com/blog/post/weatherlux/</guid>
      <description>
Time series decomposition is a powerful statistical method that decomposes a signal into several components (usually a trend, a periodic and a random component).
These components can be used to do forecasting, prediction or extrapolation of missing data.

This topic is relatively old, since the main research paper in the field dates back to 1990.
In R language, one of the most famous function for time series decomposition is the stl function.
More recently, Facebook has released an open source framework written in python called prophet for time series decomposition that is a little bit more advanced than the stl function, since it can take into account anomalies caused by non-periodic rare events.

At DataThings, we are experimenting with a different approach of time series decomposition. Since we aim at enabling live data analytics, we developed our own technology that uses online and live machine learning techniques to decompose time series on the fly. For the trend component we use a live polynomial learning algorithm, and for the periodic component we use a Gaussian Mixture Model (GMM) live profiling. The random component is what is left from signal after we remove the trend and the periodic component.

In order to see the results of the time series decomposition, we will use the open weather dataset of Luxembourg provided by Open Data Luxembourg. The dataset consists of the historical monthly average of temperature records in Luxembourg since January 1947 and can be downloaded for free from here. Here is the plot of the temperature data:

Due to earth periodic nature of the yearly rotation of earth around the sun, it is very hard to see from this graph the temperature trend over the years. Time series decomposition helps extracting the periodic component from the signal.
After passing it through a Gaussian profile, we can detect this periodic component. In January, the temperature average in Luxembourg  is around 0.5 °C, it raises to 17.5 °C in August, then falls down back to 0.5 °C in average for the January of the next year. Here is the result (we only show 2 years here for simplicity):

After filtering out this periodic signal, we can then fit a polynomial curve of the temperature trend over the years.

As you can see from the graph, the temperature trend curve was stable till 1980s, then it increased by 2 degrees the last 36 years.
After removing the periodic and the trend signals from the original data, we are left with the random remainder. Here is what it looks like:

The interesting aspect about the random component is that it has an average value of 0. This is perfectly logical, since the time series decomposition goal is to move the average value of the signal to the periodic and linear trend.

In order to see the benefit of time series decomposition, we consider that our predictive model is the sum of the trend + periodic component. If we plot this predictive model (in orange) vs the real data in (blue) we get the following graph:

Finally, to validate our results, we run the time series decomposition stl function in R and using facebook Prophet, the results are displayed in the figures below.
They both confirm our result of increase in temperature of 2 degrees over the last 36 years. However both processes in R and with facebook prophet took more time to execute than our live approach and require to load the full dataset before learning.

Decomposition in R:

Decomposition using Facebook Prophet:

</description>
    </item>

  </channel>
</rss>


text:
GFXD3D11QueryFence::~GFXD3D11QueryFence()
{
   SAFE_RELEASE(mQuery);
}

void GFXD3D11QueryFence::issue()
{
   PROFILE_START(GFXD3D11QueryFence_issue);

   // Create the query if we need to
   if(mQuery == NULL)
   {
      D3D11_QUERY_DESC QueryDesc;
      QueryDesc.Query = D3D11_QUERY_EVENT;
      QueryDesc.MiscFlags = 0;

      HRESULT hRes = D3D11DEVICE->CreateQuery(&QueryDesc, &mQuery);

      if(FAILED(hRes))
      {
         AssertFatal(false, "Hardware does not support D3D11 Queries, this should be caught before this fence type is created" );
      }

      AssertISV(hRes != E_OUTOFMEMORY, "Out of memory");
   }

   // Issue the query
   D3D11DEVICECONTEXT->End(mQuery);
   PROFILE_END();
}

GFXFence::FenceStatus GFXD3D11QueryFence::getStatus() const
{
   if(mQuery == NULL)
      return GFXFence::Unset;

   HRESULT hRes = D3D11DEVICECONTEXT->GetData(mQuery, NULL, 0, 0);

   return (hRes == S_OK ? GFXFence::Processed : GFXFence::Pending);
}

void GFXD3D11QueryFence::block()
{
   PROFILE_SCOPE(GFXD3D11QueryFence_block);

   // Calling block() before issue() is valid, catch this case
   if( mQuery == NULL )
      return;

   HRESULT hRes;
   while((hRes = D3D11DEVICECONTEXT->GetData(mQuery, NULL, 0, 0)) == S_FALSE); //D3DGETDATA_FLUSH

}

void GFXD3D11QueryFence::zombify()
{
   // Release our query
   SAFE_RELEASE( mQuery );
}

void GFXD3D11QueryFence::resurrect()
{
   // Recreate the query
   if(mQuery == NULL)
   {
      D3D11_QUERY_DESC QueryDesc;
      QueryDesc.Query = D3D11_QUERY_EVENT;
      QueryDesc.MiscFlags = 0;

      HRESULT hRes = D3D11DEVICE->CreateQuery(&QueryDesc, &mQuery);

      if(FAILED(hRes))
      {
         AssertFatal(false, "GFXD3D11QueryFence::resurrect - Hardware does not support D3D11 Queries, this should be caught before this fence type is created");
      }

      AssertISV(hRes != E_OUTOFMEMORY, "GFXD3D11QueryFence::resurrect - Out of memory");
   }
}

const String GFXD3D11QueryFence::describeSelf() const
{
   // We've got nothing
   return String();
}


text:
""" fourch (stylised as 4ch) is an easy-to-implement Python wrapper for
    4chan's JSON API, as provided by moot.

    It uses the documentation of the 4chan API located at:
        https://github.com/4chan/4chan-API

    This is based off of the API last updated Aug 12, 2014.
    (4chan-API commit: 1b2bc7858afc555127b8911b4d760480769872a9)
"""
from ._version import __version__

from .fourch import urls

from .thread import Thread
from .board import Board
from .reply import Reply

import requests

def boards(https=False):
    """ Get a list of all boards on 4chan, in :class:`fourch.board.Board`
        objects.

        :param https: Should we use HTTPS or HTTP?
        :type https: bool
    """
    s = requests.Session()
    s.headers.update({
        "User-Agent": "fourch/{0} (@https://github.com/sysr-q/4ch)".format(
            __version__
        )
    })
    proto = "https://" if https else "http://"
    url = proto + urls['api'] + urls["api_boards"]
    r = s.get(url)
    if r.status_code != requests.codes.ok:
        r.raise_for_status()

    boards = []
    for json_board in r.json()['boards']:
        boards.append(Board(json_board['board'], https=https))
    return boards


text:
const pkgInfo = require('../../../../package.json');
const path = require('path');
const fs = require('fs');

module.exports = (authProviders) => {
  authProviders = authProviders || [];

  let entityData = fs
    .readdirSync(path.resolve(__dirname, '..', '..', '..', 'entities'))
    .map((filename) => path.resolve(__dirname, '..', '..', '..', 'entities', filename))
    .reduce((data, entityPath) => {
      let entityName = path.basename(entityPath, '.js');
      data.schemas[entityName] = require(entityPath).schema;
      let examplesInput = require(entityPath).examples;
      let examples = {};
      let names = Object.keys(examplesInput);
      for(let i of names) {
        let exampleName = i == 'default' ? entityName : entityName + "_" + i;
        examples[exampleName] = examplesInput[i];
      }
      data.examples = {
        ...data.examples,
        ...examples
      };
      return data;
    }, {schemas: {}, examples: {}});

  let securitySchemes = authProviders.reduce((def, provider) => {
      def['oauth_' + provider.name] = {
        type: "oauth2",
        description: "Login via " + provider.name,
        flows: {
          implicit: {
            authorizationUrl: '/auth/' + provider.name,
            scopes: {}
          }
        }
      }
      return def;
    }, {});
  let securitySchemaNames = Object.keys(securitySchemes);
  if(securitySchemaNames.length > 0) {
    securitySchemes.oauth_default = securitySchemes[securitySchemaNames[0]];
  }

  return {
   swaggerDefinition: {
     openapi: '3.0.3',
     info: {
       title: 'JsBattle server API',
       description: 'Internal API of JsBattle ([Swagger File](../api-docs.json))',
       version: pkgInfo.version
     },
     components: {
       securitySchemes: securitySchemes,
       schemas: entityData.schemas,
       examples: entityData.examples,
     }
   },
   apis: [path.resolve(__dirname, 'routing.js')]
 };
};


text:
require 'pedant/rspec/knife_util'
require 'securerandom'

describe 'knife', :knife do
  context 'role' do
    context 'list' do
      include Pedant::RSpec::KnifeUtil
      include Pedant::RSpec::KnifeUtil::Role

      let(:command) { "knife role list -c #{knife_config}" }
      after(:each)  { knife "role delete #{role_name} -c #{knife_config} --yes" }

      context 'as an admin' do
        let(:requestor) { knife_admin }

        it 'should succeed' do
          knife "role create #{role_name} -c #{knife_config} -d #{role_name}"

          # Runs knife role list
          should have_outcome :status => 0, :stdout => /#{role_name}/
        end
      end

    end
  end
end