text:
{-# LANGUAGE FlexibleContexts, OverloadedStrings, RecordWildCards, RankNTypes #-}
{-# OPTIONS_GHC  -fno-warn-name-shadowing  #-}

module HIndent.Styles.Gibiansky where

import           Data.Foldable
import           Control.Applicative ((<$>))
import           Data.Maybe
import           Data.List (unfoldr, isPrefixOf)
import           Control.Monad.Trans.Maybe
import           Data.Functor.Identity
import           Control.Monad.State.Strict hiding (state, State, forM_, sequence_)
import           Data.Typeable

import           HIndent.Pretty
import           HIndent.Types

import           Language.Haskell.Exts.Annotated.Syntax
import           Language.Haskell.Exts.SrcLoc
import           Language.Haskell.Exts.Pretty (prettyPrint)
import           Language.Haskell.Exts.Comments
import           Prelude hiding (exp, all, mapM_, minimum, and, maximum, concatMap, or, any, sequence_)

-- | Empty state.
data State = State { gibianskyForceSingleLine :: Bool, gibianskyLetBind :: Bool }

userGets :: (State -> a) -> Printer State a
userGets f = gets (f . psUserState)

userModify :: (State -> State) -> Printer State ()
userModify f = modify (\s -> s { psUserState = f (psUserState s) })

-- | The printer style.
gibiansky :: Style
gibiansky = Style { styleName = "gibiansky"
                  , styleAuthor = "Andrew Gibiansky"
                  , styleDescription = "Andrew Gibiansky's style"
                  , styleInitialState = State { gibianskyForceSingleLine = False, gibianskyLetBind = False }
                  , styleExtenders = [ Extender imp
                                     , Extender modl
                                     , Extender context
                                     , Extender derivings
                                     , Extender typ
                                     , Extender exprs
                                     , Extender rhss
                                     , Extender guardedRhs
                                     , Extender decls
                                     , Extender stmts
                                     , Extender condecls
                                     , Extender alt
                                     , Extender moduleHead
                                     , Extender exportList
                                     , Extender fieldUpdate
                                     , Extender pragmas
                                     , Extender pat
                                     , Extender qualConDecl
                                     ]
                  , styleDefConfig = defaultConfig { configMaxColumns = 100
                                                   , configIndentSpaces = indentSpaces
                                                   , configClearEmptyLines = True
                                                   }
                  , styleCommentPreprocessor = commentPreprocessor
                  }

-- Field accessor for Comment.
commentContent :: Comment -> String
commentContent (Comment _ _ content) = content

-- Field accessor for Comment.
commentSrcSpan :: Comment -> SrcSpan
commentSrcSpan (Comment _ srcSpan _) = srcSpan

commentPreprocessor :: MonadState (PrintState s) m => [Comment] -> m [Comment]
commentPreprocessor cs = do
  config <- gets psConfig
  col <- getColumn
  return $ go (fromIntegral col) config cs

  where
   go currentColumn config = concatMap mergeGroup . groupComments Nothing []
    where
      -- Group comments into blocks.
      -- A comment block is the list of comments that are on consecutive lines,
      -- and do not have an empty comment in between them. Empty comments are those with only whitespace.
      -- Empty comments are in their own group.
      groupComments :: Maybe Int -> [Comment] -> [Comment] -> [[Comment]]
      groupComments nextLine accum (comment@(Comment multiline srcSpan str):comments)
        | separateCommentCondition = useAsSeparateCommentGroup
        | beginningOfUnprocessed str =
            let (unprocessedLines, postUnprocessed) = span unprocessed comments
                (endingLine, remLines) = case postUnprocessed of
                    x:xs -> ([x], xs)
                    [] -> ([], [])
                separateCommentGroups = comment : unprocessedLines ++ endingLine
            in currentGroupAsList ++ map (: []) separateCommentGroups ++ groupComments Nothing [] remLines
        | isNothing nextLine || Just (srcSpanStartLine srcSpan) == nextLine = groupComments nextLine' (comment:accum) comments
        | otherwise = currentGroupAsList ++ groupComments (Just $ srcSpanStartLine srcSpan + 1) [comment] comments
        where
          separateCommentCondition = or [multiline, isWhitespace str, "  " `isPrefixOf` str, " >" `isPrefixOf` str]
          useAsSeparateCommentGroup = currentGroupAsList ++ [comment] : groupComments nextLine' [] comments
          nextCommentStartLine = srcSpanStartLine $ commentSrcSpan $ head comments
          currentGroupAsList | null accum = []
                            | otherwise = [reverse accum]
          nextLine' =
            case nextLine of
              Just x -> Just (x + 1)
              Nothing -> Just nextCommentStartLine
      groupComments _ [] [] = []
      groupComments _ accum [] = [reverse accum]

      beginningOfUnprocessed :: String -> Bool
      beginningOfUnprocessed str = any (`isPrefixOf` str) ["@", " @", "  @"]

      unprocessed :: Comment -> Bool
      unprocessed (Comment True _ _) = False
      unprocessed (Comment _ _ str) = not $ beginningOfUnprocessed str

      isWhitespace :: String -> Bool
      isWhitespace = all (\x -> x == ' ' || x == '\t')

      commentLen :: Int
      commentLen = length ("--" :: String)

      -- Merge a group of comments into one comment.
      mergeGroup :: [Comment] -> [Comment]
      mergeGroup [] = error "Empty comment group"
      mergeGroup comments@[Comment True _ _] = comments
      mergeGroup comments =
        let
            firstSrcSpan = commentSrcSpan $ head comments
            firstLine = srcSpanStartLine firstSrcSpan
            firstCol = srcSpanStartColumn firstSrcSpan

            columnDelta = firstCol - currentColumn
            maxStartColumn = maximum (map (srcSpanStartColumn . commentSrcSpan) comments)

            lineLen = fromIntegral (configMaxColumns config) - maxStartColumn - commentLen + columnDelta
            content = breakCommentLines lineLen $ unlines (map commentContent comments)
            srcSpanLines = map (firstLine +) [0 .. length content - 1]
            srcSpans = map (\linum -> firstSrcSpan { srcSpanStartLine = linum, srcSpanEndLine = linum, srcSpanStartColumn = maxStartColumn }) srcSpanLines
        in zipWith (Comment False) srcSpans content

-- | Break a comment string into lines of a maximum character length.
-- Each line starts with a space, mirroring the traditional way of writing comments:
--
--   -- Hello
--   -- Note the space after the '-'
breakCommentLines :: Int -> String -> [String]
breakCommentLines maxLen str
  -- If there's no way to do this formatting, just give up
  | any ((maxLen <) . length) (words str) = [str]

  -- If we already have a line of the appropriate length, leave it alone. This allows us to format
  -- stuff ourselves in some cases.
  | length (lines str) == 1 && length str <= maxLen = [dropTrailingNewlines str]

  | otherwise = unfoldr unfolder (words str)
  where
    -- Generate successive lines, consuming the words iteratively.
    unfolder :: [String] -> Maybe (String, [String])
    unfolder [] = Nothing
    unfolder ws = Just $ go maxLen [] ws
      where
        go :: Int                -- Characters remaining on the line to be used
           -> [String]           -- Accumulator: The words used so far on this line
           -> [String]           -- Unused words
           -> (String, [String]) -- (Generated line, remaining words)
        go remainingLen taken remainingWords =
          case remainingWords of
            -- If no more words remain, we're done
            [] -> (generatedLine, [])
            word:remWords ->
              -- If the next word doesn't fit on this line, line break
              let nextRemaining = remainingLen - length word - 1
              in if nextRemaining < 0
                   then (generatedLine, remainingWords)
                   else go nextRemaining (word : taken) remWords
          where
            generatedLine = ' ' : unwords (reverse taken)

dropTrailingNewlines :: String -> String
dropTrailingNewlines = reverse . dropWhile (== '\n') . reverse

-- | Number of spaces to indent by.
indentSpaces :: Integral a => a
indentSpaces = 2

-- | Printer to indent one level.
indentOnce :: Printer s ()
indentOnce = replicateM_ indentSpaces space

-- | How many exports to format in a single line.
-- If an export list has more than this, it will be formatted as multiple lines.
maxSingleLineExports :: Integral a => a
maxSingleLineExports = 4

attemptSingleLine :: Printer State a -> Printer State a -> Printer State a
attemptSingleLine single multiple = do
  prevState <- get
  if gibianskyForceSingleLine $ psUserState prevState
    then single
    else do
      -- Try printing on one line.
      modifyState $ \st -> st { gibianskyForceSingleLine = True }
      result <- single
      modifyState $ \st -> st { gibianskyForceSingleLine = False }

      --  If it doesn't fit, reprint on multiple lines.
      col <- getColumn
      maxColumns <- configMaxColumns <$> gets psConfig
      if col > maxColumns
        then do
          put prevState
          multiple
        else return result

--------------------------------------------------------------------------------
-- Extenders
type Extend f = f NodeInfo -> Printer State ()

-- | Format whole modules.
modl :: Extend Module
modl (Module _ mayModHead pragmas imps decls) = do
  onSeparateLines pragmas
  unless (null pragmas) $
    unless (null imps && null decls && isNothing mayModHead) $
      newline >> newline

  forM_ mayModHead $ \modHead -> do
    pretty modHead
    unless (null imps && null decls) (newline >> newline)

  onSeparateLines imps
  unless (null imps || null decls) (newline >> newline)

  unless (null decls) $ do
    forM_ (init decls) $ \decl -> do
      pretty decl
      newline
      unless (skipFollowingNewline decl) newline
    pretty (last decls)
modl m = prettyNoExt m

skipFollowingNewline :: Decl l -> Bool
skipFollowingNewline TypeSig{} = True
skipFollowingNewline InlineSig{} = True
skipFollowingNewline AnnPragma{} = True
skipFollowingNewline MinimalPragma{} = True
skipFollowingNewline _ = False

-- | Format pragmas differently (language pragmas).
pragmas :: Extend ModulePragma
pragmas (LanguagePragma _ names) = do
  write "{-# LANGUAGE "
  inter (write ", ") $ map pretty names
  write " #-}"
pragmas (OptionsPragma _ mtool opt) = do
  write "{-# OPTIONS"
  forM_ mtool $ \tool -> do
    write "_"
    string $ prettyPrint tool
  string opt
  write "#-}"
pragmas p = prettyNoExt p

-- | Format patterns.
pat :: Extend Pat
pat (PTuple _ boxed pats) = writeTuple boxed pats
pat (PList _ pats) = singleLineList pats
pat (PRec _ name fields) = recUpdateExpr fields (pretty name) (map prettyCommentCallbacks fields)
pat p = prettyNoExt p

-- | Format import statements.
imp :: Extend ImportDecl
imp ImportDecl{..} = do
  write "import "
  write $ if importQualified
            then "qualified "
            else "          "
  pretty importModule

  forM_ importAs $ \name -> do
    write " as "
    pretty name

  forM_ importSpecs $ \(ImportSpecList _ importHiding specs) -> do
    space
    when importHiding $ write "hiding "
    depend (write "(") $ do
      case specs of
        [] -> return ()
        x:xs -> do
          pretty x
          forM_ xs $ \spec -> do
            write ","
            col <- getColumn
            len <- prettyColLength spec
            maxColumns <- configMaxColumns <$> gets psConfig
            if col + len > maxColumns
              then newline
              else space

            pretty spec
      write ")"

-- | Return the number of columns between the start and end of a printer.
-- Note that if it breaks lines, the line break is not counted; only column is used.
-- So you probably only want to use this for single-line printers.
prettyColLength :: (Integral a, Pretty ast) => ast NodeInfo -> Printer State a
prettyColLength x = fst <$> sandbox (do
  col <- getColumn
  pretty x
  col' <- getColumn
  return $ fromIntegral $ max (col' - col) 0)

-- | Format contexts with spaces and commas between class constraints.
context :: Extend Context
context (CxTuple _ asserts) =
  parens $ inter (comma >> space) $ map pretty asserts
context ctx = prettyNoExt ctx

-- | Format deriving clauses with spaces and commas between class constraints.
derivings :: Extend Deriving
derivings (Deriving _ instHeads) = do
  write "deriving "
  go instHeads

  where
    go insts
      | length insts == 1 = pretty $ head insts
      | otherwise = parens $ inter (comma >> space) $ map pretty insts

-- | Format function type declarations.
typ :: Extend Type
-- For contexts, check whether the context and all following function types
-- are on the same line. If they are, print them on the same line; otherwise
-- print the context and each argument to the function on separate lines.
typ (TyForall _ mforall (Just ctx) rest) = do
  forM_ mforall $ \forallVars -> do
    write "forall "
    spaced $ map pretty forallVars
    write ". "
  if all (sameLine ctx) $ collectTypes rest
    then do
      pretty ctx
      write " => "
      pretty rest
    else do
      col <- getColumn
      pretty ctx
      column (col - 3) $ do
        newline
        write "=> "
        indented 3 $ pretty rest
typ (TyTuple _ boxed types) = writeTuple boxed types
typ ty@(TyFun _ from to) =
  -- If the function argument types are on the same line,
  -- put the entire function type on the same line.
  if all (sameLine from) $ collectTypes ty
    then do
      pretty from
      write " -> "
      pretty to
    else do
      -- If the function argument types are on different lines,
      -- write one argument type per line.
      col <- getColumn
      pretty from
      column (col - 3) $ do
        newline
        write "-> "
        indented 3 $ pretty to
typ t = prettyNoExt t

writeTuple :: Pretty ast => Boxed -> [ast NodeInfo] -> Printer State ()
writeTuple boxed vals = parens $ do
  boxed'
  inter (write ", ") $ map pretty vals
  boxed'
  where
    boxed' =
      case boxed of
        Boxed   -> return ()
        Unboxed -> write "#"

sameLine :: (Annotated ast, Annotated ast') => ast NodeInfo -> ast' NodeInfo -> Bool
sameLine x y = line x == line y
  where
    line :: Annotated ast => ast NodeInfo -> Int
    line = startLine . nodeInfoSpan . ann

collectTypes :: Type l -> [Type l]
collectTypes (TyFun _ from to) = from : collectTypes to
collectTypes ty = [ty]

exprs :: Extend Exp
exprs exp@Let{} = letExpr exp
exprs exp@App{} = appExpr exp
exprs exp@Do{} = doExpr exp
exprs exp@List{} = listExpr exp
exprs exp@(InfixApp _ _ (QVarOp _ (UnQual _ (Symbol _ "$"))) _) = dollarExpr exp
exprs exp@(InfixApp _ _ (QVarOp _ (UnQual _ (Symbol _ "<*>"))) _) = applicativeExpr exp
exprs exp@InfixApp{} = opExpr exp
exprs exp@Lambda{} = lambdaExpr exp
exprs exp@Case{} = caseExpr exp
exprs exp@LCase{} = lambdaCaseExpr exp
exprs exp@If{} = ifExpr exp
exprs exp@MultiIf{} = multiIfExpr exp
exprs (RecUpdate _ exp updates) = recUpdateExpr updates (pretty exp) (map prettyCommentCallbacks updates)
exprs (RecConstr _ qname updates) = recUpdateExpr updates (pretty qname) (map prettyCommentCallbacks updates)
exprs (Tuple _ _ exps) = parens $ inter (write ", ") $ map pretty exps
exprs exp = prettyNoExt exp

multiIfExpr :: Exp NodeInfo -> Printer State ()
multiIfExpr (MultiIf _ alts) =
  withCaseContext True $
    depend (write "if ") $
      onSeparateLines' (depend (write "|") . pretty) alts
multiIfExpr _ = error "Not a multi if"

letExpr :: Exp NodeInfo -> Printer State ()
letExpr (Let _ binds result) = do
  cols <- depend (write "let ") $ do
            col <- getColumn

            oldLetBind <- userGets gibianskyLetBind
            userModify (\s -> s { gibianskyLetBind = True })
            writeWhereBinds binds
            userModify (\s -> s { gibianskyLetBind = oldLetBind })

            return $ col - 4
  column cols $ do
    newline
    write "in "
    pretty result
letExpr _ = error "Not a let"

keepingColumn :: Printer State () -> Printer State ()
keepingColumn printer = do
  eol <- gets psEolComment
  when eol newline
  col <- getColumn
  ind <- gets psIndentLevel
  column (max col ind) printer

appExpr :: Exp NodeInfo -> Printer State ()
appExpr app@(App _ f x) = do
  prevState <- get
  prevLine <- getLineNum
  attemptSingleLine singleLine multiLine
  curLine <- getLineNum

  -- If the multiline version takes more than two lines,
  -- print everything with one argument per line.
  when (curLine - prevLine > 1) $ do
    -- Restore to before printing.
    put prevState

    allArgsSeparate <- not <$> canSingleLine (pretty f)
    if allArgsSeparate
      then separateArgs app
      else keepingColumn $ do
        pretty f
        newline
        indented indentSpaces $ pretty x

  where
    singleLine = spaced [pretty f, pretty x]
    multiLine = keepingColumn $ do
      pretty f
      newline
      indentOnce
      pretty x

    canSingleLine :: Printer State a -> Printer State Bool
    canSingleLine printer = do
      st <- get
      prevLine <- getLineNum
      _ <- printer
      curLine <- getLineNum
      put st
      return $ prevLine == curLine

    -- Separate a function application into the function
    -- and all of its arguments. Arguments are returned in reverse order.
    collectArgs :: Exp NodeInfo -> (Exp NodeInfo, [Exp NodeInfo])
    collectArgs (App _ g y) =
      let (fun, args) = collectArgs g
      in (fun, y : args)
    collectArgs nonApp = (nonApp, [])

    separateArgs :: Exp NodeInfo -> Printer State ()
    separateArgs expr =
      let (fun, args) = collectArgs expr
      in keepingColumn $ do
        pretty fun
        newline
        indented indentSpaces $ lined $ map pretty $ reverse args
appExpr _ = error "Not an app"

doExpr :: Exp NodeInfo -> Printer State ()
doExpr (Do _ stmts) = do
  write "do"
  newline
  indented indentSpaces $ onSeparateLines stmts
doExpr _ = error "Not a do"

listExpr :: Exp NodeInfo -> Printer State ()
listExpr (List _ els) = attemptSingleLine (singleLineList els) (multiLineList els)
listExpr _ = error "Not a list"

singleLineList :: Pretty a => [a NodeInfo] -> Printer State ()
singleLineList exps = do
  write "["
  inter (write ", ") $ map pretty exps
  write "]"

multiLineList :: [Exp NodeInfo] -> Printer State ()
multiLineList [] = write "[]"
multiLineList (first:exps) = keepingColumn $ do
  write "[ "
  pretty first
  forM_ exps $ \el -> do
    newline
    write ", "
    pretty el
  newline
  write "]"

dollarExpr :: Exp NodeInfo -> Printer State ()
dollarExpr (InfixApp _ left op right) = do
  pretty left
  space
  pretty op
  if needsNewline right
    then do
      newline
      col <- getColumn
      ind <- gets psIndentLevel
      column (max col ind + indentSpaces) $ pretty right
    else do
      space
      pretty right

  where
    needsNewline Case{} = True
    needsNewline exp = lineDelta exp op > 0
dollarExpr _ = error "Not an application"

applicativeExpr :: Exp NodeInfo -> Printer State ()
applicativeExpr exp@InfixApp{} =
  case applicativeArgs of
    Just (first:second:rest) ->
      attemptSingleLine (singleLine first second rest) (multiLine first second rest)
    _ -> prettyNoExt exp
  where
    singleLine :: Exp NodeInfo -> Exp NodeInfo -> [Exp NodeInfo] -> Printer State ()
    singleLine first second rest = spaced
                                     [ pretty first
                                     , write "<$>"
                                     , pretty second
                                     , write "<*>"
                                     , inter (write " <*> ") $ map pretty rest
                                     ]

    multiLine :: Exp NodeInfo -> Exp NodeInfo -> [Exp NodeInfo] -> Printer State ()
    multiLine first second rest = do
      pretty first
      depend space $ do
        write "<$> "
        pretty second
        forM_ rest $ \val -> do
          newline
          write "<*> "
          pretty val

    applicativeArgs :: Maybe [Exp NodeInfo]
    applicativeArgs = collectApplicativeExps exp

    collectApplicativeExps :: Exp NodeInfo -> Maybe [Exp NodeInfo]
    collectApplicativeExps (InfixApp _ left op right)
      | isFmap op = return [left, right]
      | isAp op = do
          start <- collectApplicativeExps left
          return $ start ++ [right]
      | otherwise = Nothing
    collectApplicativeExps _ = Nothing

    isFmap :: QOp NodeInfo -> Bool
    isFmap (QVarOp _ (UnQual _ (Symbol _ "<$>"))) = True
    isFmap _ = False

    isAp :: QOp NodeInfo -> Bool
    isAp (QVarOp _ (UnQual _ (Symbol _ "<*>"))) = True
    isAp _ = False
applicativeExpr _ = error "Not an application"

opExpr :: Exp NodeInfo -> Printer State ()
opExpr expr@(InfixApp _ left op right) = keepingColumn $ do
  let deltaLeft = lineDelta op left
      deltaRight = lineDelta right op

  -- If this starts out as a single line expression, try to keep it as a single line expression. Break
  -- it up over multiple lines if it doesn't fit using operator columns, but only when all the
  -- operators are the same.
  if deltaLeft == 0 && deltaRight == 0 && numOperatorUses op expr >= 2
    then attemptSingleLine opSingle opMulti
    else userSpecified deltaLeft deltaRight
  where
    -- Use user-specified spacing for the newlines in the operator
    userSpecified deltaLeft deltaRight = do
      pretty left

      if deltaLeft == 0
        then space
        else replicateM_ deltaLeft newline

      pretty op

      if deltaRight == 0
        then space
        else replicateM_ deltaRight newline

      pretty right

    -- Write the entire infix expression on one line.
    opSingle = sequence_ [pretty left, space, pretty op, space, pretty right]

    -- Use operator column layout.
    opMulti = do
      let opArguments = collectOpArguments op expr
      forM_ (init opArguments) $ \arg -> do
        pretty arg
        space
        pretty op
        newline
      pretty (last opArguments)

    -- Count the number of times an infix operator is used in a row.
    numOperatorUses op e = length (collectOpArguments op e) - 1

    -- Collect all arguments to an infix operator.
    collectOpArguments op expr'@(InfixApp _ left' op' right')
      | void op == void op' = collectOpArguments op left' ++ collectOpArguments op right'
      | otherwise = [expr']
    collectOpArguments _ expr' = [expr']
opExpr exp = prettyNoExt exp

lambdaExpr :: Exp NodeInfo -> Printer State ()
lambdaExpr (Lambda _ pats exp) = do
  write "\\"
  spaced $ map pretty pats
  write " ->"
  if any isBefore $ nodeInfoComments $ ann exp
    then multi
    else attemptSingleLine (space >> pretty exp) multi

  where multi = do
         newline
         indented indentSpaces $ pretty exp

        isBefore com = comInfoLocation com == Just Before
lambdaExpr _ = error "Not a lambda"

caseExpr :: Exp NodeInfo -> Printer State ()
caseExpr (Case _ exp alts) = do
  depend (write "case ") $ do
    pretty exp
    write " of"
  newline

  writeCaseAlts alts
caseExpr _ = error "Not a case"

lambdaCaseExpr :: Exp NodeInfo -> Printer State ()
lambdaCaseExpr (LCase _ alts) = do
  write "\\case"
  newline
  writeCaseAlts alts
lambdaCaseExpr _ = error "Not a lambda case"

ifExpr :: Exp NodeInfo -> Printer State ()
ifExpr (If _ cond thenExpr elseExpr) =
  depend (write "if") $ do
    space
    pretty cond
    newline
    write "then "
    pretty thenExpr
    newline
    write "else "
    pretty elseExpr
ifExpr _ = error "Not an if statement"

writeCaseAlts :: [Alt NodeInfo] -> Printer State ()
writeCaseAlts alts = do
  allSingle <- and <$> mapM isSingle alts
  withCaseContext True $ indented indentSpaces $ do
    prettyPr <- if allSingle
                then do
                  maxPatLen <- maximum <$> mapM (patternLen . altPattern) alts
                  return $ prettyCase (Just maxPatLen)
                else return $ prettyCase Nothing

    case alts of
      [] -> return ()
      first:rest -> do
        printComments Before first
        prettyPr first
        printComments After first
        forM_ (zip alts rest) $ \(prev, cur) -> do
          replicateM_ (max 1 $ lineDelta cur prev) newline
          printComments Before cur
          prettyPr cur
          printComments After cur

  where
    isSingle :: Alt NodeInfo -> Printer State Bool
    isSingle alt' = fst <$> sandbox
                              (do
                                 line <- gets psLine
                                 pretty alt'
                                 line' <- gets psLine
                                 return $ not (isGuarded (altRhs alt')) && line == line')

    altPattern :: Alt l -> Pat l
    altPattern (Alt _ p _ _) = p

    altRhs :: Alt l -> Rhs l
    altRhs (Alt _ _ r _) = r

    isGuarded :: Rhs l -> Bool
    isGuarded GuardedRhss{} = True
    isGuarded UnGuardedRhs{} = False

    patternLen :: Pat NodeInfo -> Printer State Int
    patternLen pat = fromIntegral <$> fst <$> sandbox
                                                (do
                                                   col <- getColumn
                                                   pretty pat
                                                   col' <- getColumn
                                                   return $ col' - col)

    prettyCase :: Maybe Int -> Alt NodeInfo -> Printer State ()
    prettyCase mpatlen (Alt _ p galts mbinds) = do
      -- Padded pattern
      case mpatlen of
        Just patlen -> do
          col <- getColumn
          pretty p
          col' <- getColumn
          replicateM_ (patlen - fromIntegral (col' - col)) space
        Nothing -> pretty p

      case galts of
        UnGuardedRhs{} -> pretty galts
        GuardedRhss{}  -> do
          newline
          indented indentSpaces $ pretty galts

      --  Optional where clause!
      forM_ mbinds $ \binds -> do
        newline
        indented indentSpaces $ depend (write "where ") (pretty binds)

prettyCommentCallbacks :: (Pretty ast,MonadState (PrintState s) m) => ast NodeInfo -> (ComInfoLocation -> m ()) -> m ()
prettyCommentCallbacks a f =
  do st <- get
     case st of
       PrintState{psExtenders = es,psUserState = s} ->
         do
           printComments Before a
           f Before
           depend
             (case listToMaybe (mapMaybe (makePrinter s) es) of
                Just (Printer m) ->
                  modify (\s' ->
                            fromMaybe s'
                                      (runIdentity (runMaybeT (execStateT m s'))))
                Nothing -> prettyNoExt a)
             (f After >> printComments After a)
  where makePrinter _ (Extender f) =
          case cast a of
            Just v -> Just (f v)
            Nothing -> Nothing
        makePrinter s (CatchAll f) = f s a

recUpdateExpr :: Foldable f => [f NodeInfo] -> Printer State () -> [(ComInfoLocation -> Printer State ()) -> Printer State ()] -> Printer State ()
recUpdateExpr ast expWriter updates
  | null updates = do
      expWriter
      write "{}"
  | any hasComments ast = mult
  | otherwise = attemptSingleLine single mult

  where
    single = do
      expWriter
      write " { "
      inter (write ", ") updates'
      write " }"
    mult = do
      expWriter
      newline
      indented indentSpaces $ keepingColumn $ do
        write "{ "
        head updates'
        forM_ (tail updates) $ \update -> do
          newline
          update commaAfterComment
        newline
        write "}"

    updates' = map ($ const $ return ()) updates

commaAfterComment :: ComInfoLocation -> Printer State ()
commaAfterComment loc = case loc of
  Before -> write ", "
  After -> return ()

rhss :: Extend Rhs
rhss (UnGuardedRhs rhsLoc exp) = do
  letBind <- userGets gibianskyLetBind
  let exp'
        | lineBreakAfterRhs rhsLoc exp =
            indented indentSpaces $ do
              newline
              pretty exp
        | letBind =
            depend space (pretty exp)
        | otherwise = space >> pretty exp
  if letBind
    then depend (space >> rhsSeparator) exp'
    else space >> rhsSeparator >> exp'
rhss (GuardedRhss _ rs) =
  flip onSeparateLines' rs $ \a@(GuardedRhs rhsLoc stmts exp) -> do
    let manyStmts = length stmts > 1
        remainder = do
          if manyStmts then newline else space
          rhsSeparator
          if not manyStmts && lineBreakAfterRhs rhsLoc exp
            then newline >> indented indentSpaces (pretty exp)
            else space >> pretty exp
        writeStmts =
          case stmts of
            x:xs -> do
              pretty x
              forM_ xs $ \x -> write "," >> newline >> pretty x
            [] -> return ()

    printComments Before a
    if manyStmts
      then do
        depend (write "| ") writeStmts
        remainder
      else
        depend (write "| ") $ writeStmts >> remainder
    printComments After a

lineBreakAfterRhs :: NodeInfo -> Exp NodeInfo -> Bool
lineBreakAfterRhs rhsLoc exp = onNextLine exp
  where
    -- Cannot use lineDelta because we need to look at rhs start line, not end line
    prevLine = srcSpanStartLine . srcInfoSpan . nodeInfoSpan $ rhsLoc
    curLine = astStartLine exp
    emptyLines = curLine - prevLine

    onNextLine Let{} = True
    onNextLine Case{} = True
    onNextLine _ = emptyLines > 0

guardedRhs :: Extend GuardedRhs
guardedRhs (GuardedRhs _ stmts exp) = do
  indented 1 $ prefixedLined "," (map (\p -> space >> pretty p) stmts)
  space
  rhsRest exp

rhsRest :: Pretty ast => ast NodeInfo -> Printer State ()
rhsRest exp = do
  rhsSeparator
  space
  pretty exp

stmts :: Extend Stmt
stmts (LetStmt _ binds) = depend (write "let ") (writeWhereBinds binds)
stmts stmt = prettyNoExt stmt

decls :: Extend Decl
decls (DataDecl _ dataOrNew Nothing declHead constructors mayDeriving) = do
  depend (pretty dataOrNew >> space) $ do
    pretty declHead
    case constructors of
      [] -> return ()
      [x] -> do
        write " ="
        pretty x
      (x:xs) ->
        depend space $ do
          write "="
          pretty x
          forM_ xs $ \constructor -> do
            newline
            write "|"
            pretty constructor

  forM_ mayDeriving $ \deriv -> do
    newline
    indented indentSpaces $ pretty deriv
decls (PatBind _ pat rhs mbinds) = funBody [pat] rhs mbinds
decls (FunBind _ matches) =
  flip onSeparateLines' matches $ \match -> do
    printComments Before match
    (writeName, pat, rhs, mbinds) <- case match of
                                  Match _ name pat rhs mbinds -> return (pretty name, pat, rhs, mbinds)
                                  InfixMatch _ left name pat rhs mbinds -> do
                                    pretty left
                                    space
                                    let writeName = case name of
                                          Symbol _ name' -> string name'
                                          Ident _ name' -> do
                                            write "`"
                                            string name'
                                            write "`"
                                    return (writeName, pat, rhs, mbinds)
    writeName
    space
    funBody pat rhs mbinds
    printComments After match
decls (ClassDecl _ ctx dhead fundeps mayDecls) = do
  let decls = fromMaybe [] mayDecls
      noDecls = null decls

  -- Header
  depend (write "class ") $
    depend (maybeCtx ctx) $
      depend (pretty dhead >> space) $
        depend (unless (null fundeps) (write " | " >> commas (map pretty fundeps))) $
          unless noDecls (write "where")

  -- Class method declarations
  unless noDecls $ do
    newline
    indentSpaces <- getIndentSpaces
    indented indentSpaces (onSeparateLines decls)
decls decl = prettyNoExt decl

qualConDecl :: Extend QualConDecl
qualConDecl (QualConDecl _ tyvars ctx d) =
  depend (unless (null (fromMaybe [] tyvars))
                  (do write " forall "
                      spaced (map pretty (fromMaybe [] tyvars))
                      write ". "))
          (depend (maybeCtx' ctx)
                  (pretty d))
  where
    maybeCtx' = maybe (return ())
                      (\p ->
                        pretty p >>
                        write " =>")

funBody :: [Pat NodeInfo] -> Rhs NodeInfo -> Maybe (Binds NodeInfo) -> Printer State ()
funBody pat rhs mbinds = do
  spaced $ map pretty pat

  withCaseContext False $
    case rhs of
      UnGuardedRhs{} -> pretty rhs
      GuardedRhss{} -> do
        newline
        indented indentSpaces $ pretty rhs

  -- Process the binding group, if it exists.
  forM_ mbinds $ \binds -> do
    newline
    -- Add an extra newline after do blocks.
    when (isDoBlock rhs) newline
    indented indentSpaces $ do
      write "where"
      newline
      indented indentSpaces $ writeWhereBinds binds

writeWhereBinds :: Binds NodeInfo -> Printer State ()
writeWhereBinds ds@(BDecls _ binds) = do
  printComments Before ds
  onSeparateLines binds
  printComments After ds
writeWhereBinds binds = prettyNoExt binds

-- Print all the ASTs on separate lines, respecting user spacing.
onSeparateLines :: (Pretty ast, Annotated ast) => [ast NodeInfo] -> Printer State ()
onSeparateLines = onSeparateLines' pretty

onSeparateLines' :: Annotated ast => (ast NodeInfo -> Printer State ()) -> [ast NodeInfo] -> Printer State ()
onSeparateLines' _ [] = return ()
onSeparateLines' pretty' vals = do
  let vals' = map (amap fixSpans) vals
      (first:rest) = vals'

  pretty' first
  forM_ (zip vals' rest) $ \(prev, cur) -> do
    replicateM_ (max 1 $ lineDelta cur prev) newline
    pretty' cur

fixSpans :: NodeInfo -> NodeInfo
fixSpans info =
  let infoSpan = nodeInfoSpan info
      srcSpan = srcInfoSpan infoSpan

      points = srcInfoPoints infoSpan
      lastPt = last points

      prevLastPt = last (init points)
      prevPtEnd = (srcSpanEndLine prevLastPt, srcSpanEndColumn prevLastPt)

      lastPtEndLoc = (srcSpanEndLine lastPt, srcSpanEndColumn lastPt)
      invalidLastPt = srcSpanStartLine lastPt == srcSpanEndLine lastPt &&
                      srcSpanStartColumn lastPt > srcSpanEndColumn lastPt

      infoEndLoc = (srcSpanEndLine srcSpan, srcSpanEndColumn srcSpan)
  in if length points > 1 && lastPtEndLoc == infoEndLoc && invalidLastPt
       then info { nodeInfoSpan = infoSpan { srcInfoSpan = setEnd srcSpan prevPtEnd } }
       else info
  where
    setEnd (SrcSpan fname startL startC _ _) (endL, endC) = SrcSpan fname startL startC endL endC

astStartLine :: Annotated ast => ast NodeInfo -> Int
astStartLine decl =
  let info = ann decl
      comments = nodeInfoComments info
      befores = filter ((== Just Before) . comInfoLocation) comments
      commentStartLine (Comment _ sp _) = srcSpanStartLine sp
  in if null befores
       then startLine $ nodeInfoSpan info
       else minimum $ map (commentStartLine . comInfoComment) befores

isDoBlock :: Rhs l -> Bool
isDoBlock (UnGuardedRhs _ Do{}) = True
isDoBlock _ = False

condecls :: Extend ConDecl
condecls (ConDecl _ name bangty) =
  depend (space >> pretty name) $
    forM_ bangty $ \ty -> space >> pretty ty
condecls decl@(RecDecl _ name fields) = if hasComments decl
                                        then multiRec
                                        else attemptSingleLine singleRec multiRec
  where
    singleRec = space >> depend (pretty name >> space) recBody
    multiRec = do
      newline
      indented indentSpaces $ keepingColumn $ do
        pretty name
        newline
        indented indentSpaces recBody

    recBody = do
      write "{ "
      writeFields fields
      write "}"

    writeFields [] = return ()
    writeFields [x] = do
      pretty x
      eol <- gets psEolComment
      unless eol space
    writeFields (first:rest) = do
        singleLine <- gets (gibianskyForceSingleLine . psUserState)

        pretty first
        unless singleLine newline
        forM_ rest $ \field -> do
          prettyCommentCallbacks field commaAfterComment
          unless singleLine newline

        when singleLine space
condecls other = prettyNoExt other

hasComments :: Foldable ast => ast NodeInfo -> Bool
hasComments = any (not . null . nodeInfoComments)

alt :: Extend Alt
alt (Alt _ p rhs mbinds) = do
  pretty p
  case rhs of
    UnGuardedRhs{} -> pretty rhs
    GuardedRhss{}  -> indented indentSpaces $ pretty rhs
  forM_ mbinds $ \binds -> do
    newline
    indented indentSpaces $
      depend (write "where ") (pretty binds)

moduleHead :: Extend ModuleHead
moduleHead (ModuleHead _ name mwarn mexports) = do
  forM_ mwarn pretty
  write "module "
  pretty name
  forM_ mexports $ \exports -> do
    space
    pretty exports
  write " where"

exportList :: Extend ExportSpecList
exportList (ExportSpecList _ exports) = do
  write "("
  if length exports <= maxSingleLineExports
    then do
      inter (write ", ") $ map pretty exports
      write ")"
    else indented indentSpaces' $ do
      -- First export
      let first:rest = exports
      newline
      pretty first
      write ","

      forM_ (zip rest exports) $ \(cur, prev) -> do
        replicateM_ (max 1 $ lineDelta cur prev) newline
        pretty cur
        write ","
      newline
      write ")"

  where
    indentSpaces' = 2 * indentSpaces

lineDelta :: (Annotated ast1, Annotated ast2) => ast1 NodeInfo -> ast2 NodeInfo -> Int
lineDelta cur prev = emptyLines
  where
    prevLine = srcSpanEndLine . srcInfoSpan . nodeInfoSpan . ann $ prev
    curLine = astStartLine cur
    emptyLines = curLine - prevLine

fieldUpdate :: Extend FieldUpdate
fieldUpdate (FieldUpdate _ name val) = do
  pretty name
  write " = "
  pretty val
fieldUpdate upd = prettyNoExt upd


text:
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.call.FeedbackSummary;

import java.time.LocalDate;

public class Example {
  // Get your Account SID and Auth Token from https://twilio.com/console
  // To set up environment variables, see http://twil.io/secure
  public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
  public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    FeedbackSummary summary = FeedbackSummary
        .creator(LocalDate.of(2014, 6, 1), LocalDate.of(2014, 6, 30))
        .setIncludeSubaccounts(true).setStatusCallback("http://www.example.com/feedback").create();

    System.out.println(summary.getStatus());
  }
}

redpajama_set_name: RedPajamaGithub


text:
set :runner, VirtualMonkey::Runner::PhpChef

clean_start do
  @runner.stop_all
end

before do
  @runner.set_master_db_dnsname
  @runner.set_variation_http_only
  @runner.launch_all
  @runner.wait_for_all("operational")
end

#
## Unified Application on 8000
#

test "run_unified_application_checks" do
  @runner.run_unified_application_checks(:app_servers, 8000)
end

test "reboot_operations" do
  @runner.run_reboot_operations
end

test "monitoring" do
  @runner.check_monitoring
end

#
## ATTACHMENT GROUP
#

test "attach_all" do
  @runner.test_attach_all
  @runner.frontend_checks(80)
end

test "attach_request" do
  @runner.test_attach_request
  @runner.frontend_checks(80)
end

after "attach_all", "attach_request" do
  @runner.test_detach
end


text:
static VALUE wrap_Zeta_real_zeta2(VALUE self, VALUE x_value, VALUE y_value)
{
  double x = NUM2DBL(x_value);
  double y = NUM2DBL(y_value);
  double retval = real_zeta2(x, y);

  return rb_float_new(retval);
}

static VALUE wrap_Zeta_imag_zeta2(VALUE self, VALUE x_value, VALUE y_value)
{
  double x = NUM2DBL(x_value);
  double y = NUM2DBL(y_value);
  double retval = imag_zeta2(x, y);

  return rb_float_new(retval);
}

static VALUE wrap_Zeta_sin(VALUE self, VALUE x_value, VALUE y_value)
{
  double x = NUM2DBL(x_value);
  double y = NUM2DBL(y_value);
  double retval = abs_sin2(x, y);

  return rb_float_new(retval);
}

static VALUE wrap_Zeta_zeta(VALUE self, VALUE x_value, VALUE y_value)
{
  double x = NUM2DBL(x_value);
  double y = NUM2DBL(y_value);
  double retval = abs_zeta2(x, y);

  return rb_float_new(retval);
}

static VALUE wrap_Zeta_gamma(VALUE self, VALUE x_value, VALUE y_value)
{
  double x = NUM2DBL(x_value);
  double y = NUM2DBL(y_value);
  double retval = abs_gamma2(x, y);

  return rb_float_new(retval);
}

extern "C" void Init_zeta()
{
  VALUE c = rb_define_class("Zeta", rb_cObject);

  rb_define_method(c, "real_zeta2", RUBY_METHOD_FUNC(wrap_Zeta_real_zeta2), 2);
  rb_define_method(c, "imag_zeta2", RUBY_METHOD_FUNC(wrap_Zeta_imag_zeta2), 2);

  rb_define_method(c, "abs_zeta2", RUBY_METHOD_FUNC(wrap_Zeta_zeta), 2);
  rb_define_method(c, "abs_gamma2", RUBY_METHOD_FUNC(wrap_Zeta_gamma), 2);
  rb_define_method(c, "abs_sin2", RUBY_METHOD_FUNC(wrap_Zeta_sin), 2);
}


text:
/**
 * HTTP stream connector.
 */
package org.apache.edgent.connectors.http;


text:
layout: master
title: Blank Page
url: "/page/blank.html"
---

{% include foot.html %}


text:
<?php

namespace RawPHP\Http\Factory;

use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;

/**
 * Class ResponseFactory
 *
 * @package RawPHP\Http\Factory
 */
class ResponseFactory implements IResponseFactory
{
    /**
     * @param int    $code
     * @param string $body
     * @param array  $headers
     *
     * @return ResponseInterface
     */
    public function create($code, $body, array $headers = [])
    {
        return new Response($code, $headers, $body);
    }
}


text:
[cmdletbinding()]
param()

# Arrange.
. $PSScriptRoot\..\..\lib\Initialize-Test.ps1
Register-Mock Get-LocalizedString { $OFS = " " ; "$args" }
Register-Mock Get-TaskVariable

. $PSScriptRoot\..\..\..\Tasks\VsTestV1\Helpers.ps1

$cpuCount="1"
$temptestsettingsfile = [io.path]::ChangeExtension([io.path]::GetTempFileName(),"xml")
$testsettings = @('<?xml version="1.0" encoding="utf-8"?>
<TestSettings name="Empty Test Settings">
  <Description>Empty testsettings</Description>
</TestSettings>
')
Set-Content -Value $testsettings -Path $temptestsettingsfile

$returnedFilePath = SetupRunSettingsFileForParallel "true" $temptestsettingsfile $cpuCount

$fileExists = Test-Path $returnedFilePath
Assert-AreEqual $true $fileExists

Assert-AreNotEqual $temptestsettingsfile $returnedFilePath

$readRunSettingsFile=[System.Xml.XmlDocument](Get-Content $returnedFilePath)
Assert-AreEqual $cpuCount $readRunSettingsFile.RunSettings.RunConfiguration.MaxCpuCount

#cleanup
if($fileExists){
	Remove-Item $returnedFilePath
}
if(Test-Path $temptestsettingsfile){
	Remove-Item $temptestsettingsfile
}


text:
package ch.tkuhn.nanolytics;

import java.util.List;

import org.openrdf.model.URI;

public class ProvTrail implements Comparable<ProvTrail> {

	private URI[] uris;

	public ProvTrail(URI... uris) {
		this.uris = uris;
	}

	public ProvTrail(List<URI> uris) {
		this.uris = uris.toArray(new URI[uris.size()]);
	}

	public int getLength() {
		return uris.length;
	}

	public URI getUri(int position) {
		return uris[position];
	}

	@Override
	public int compareTo(ProvTrail other) {
		if (this.getLength() != other.getLength()) {
			return this.getLength() - other.getLength();
		}
		int i = this.getLength();
		while (i > 0) {
			i--;
			URI thisUri = this.getUri(i);
			URI otherUri = other.getUri(i);
			if (thisUri == null && otherUri == null) continue;
			if (thisUri == null) return 1;
			if (otherUri == null) return -1;
			int c = this.getUri(i).toString().compareTo(other.getUri(i).toString());
			if (c != 0) return c;
		}
		return 0;
	}

	@Override
	public String toString() {
		String s = "";
		for (URI uri : uris) {
			if (!s.isEmpty()) s += " ";
			s += uri.toString();
		}
		return s;
	}

}


text:
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Grid from 'material-ui/Grid';
import Result from './result';
import Feedback from '../../../../applications/feedback/feedbackContainer';
import { selectPartnerApplicationDetails } from '../../../../../store';
import AgencyResults from './agencyResults/resultsContainer';
import { ROLES } from '../../../../../helpers/constants';

const Results = (props) => {
  const { role, params: { id }, application } = props;
  if (role === ROLES.PARTNER) {
    return (
      <Grid container direction="row" spacing={24}>
        <Grid item xs={12} sm={4}>
          <Result cfeiId={id} application={application} />
        </Grid>
        <Grid item xs={12} sm={8}>
          <Feedback applicationId={application.id} />
        </Grid>
      </Grid>
    );
  }
  return <AgencyResults id={id} />;
};

Results.propTypes = {
  role: PropTypes.string,
  params: PropTypes.object,
  application: PropTypes.object,
};

const mapStateToProps = (state, ownProps) => ({
  role: state.session.role,
  application: selectPartnerApplicationDetails(state, ownProps.params.id),
});

export default connect(mapStateToProps)(Results);


text:
import drawBot

def imageBox(im, box, fit="fill", clip=False, center=None, alpha=1):
    """
    Draw an image object in a given rectangle.
    """
    # if given a string, make an image object
    if isinstance(im, str):
        im = ImageObject(im)
    boxX, boxY, boxW, boxH = box
    # get the image dimensions
    imW, imH = im.size()
    imX, imY = boxX, boxY
    # if a center is not provided, use the center of the image
    if center is None:
        center = imW/2, imH/2
    # get the relative scale of image to box in both directions
    fitScaleX = boxW/imW
    fitScaleY = boxH/imH
    # make the transformations
    with savedState():
        translate(boxX, boxY)
        # if fit is "cover", make a clipping path
        if clip or (fit == "cover" and clip is None):
            b = BezierPath()
            b.rect(0, 0, boxW, boxH)
            clipPath(b)
        # use the center of the box as a starting point
        offsetX = boxW/2
        offsetY = boxH/2
        # the scale we will actually use
        scaleX = 1
        scaleY = 1
        # if fit is "cover", use the maximum fit
        if fit == 'cover':
            scaleX = scaleY = max(fitScaleX, fitScaleY)
        # if fit is "contain", use the minimum fit
        elif fit == "contain":
            scaleX = scaleY = min(fitScaleX, fitScaleY)
        elif fit == "scale-down":
            contain = min(fitScaleX, fitScaleY)
            scaleX = scaleY = min(contain, 1)
        # if fit is "none", do nothing
        elif fit == "none":
            pass
        else:
            # by default, fit in both directions
            scaleX = fitScaleX
            scaleY = fitScaleY
        # move to the center
        translate(offsetX, offsetY)
        # scale depending on fit
        scale(scaleX, scaleY)
        # draw the image centered on the center point
        image(im, (-center[0], -center[1]), alpha=alpha)
    # draw the center point
    DEBUG = False
    if DEBUG:
        with savedState():
            fill(0, 1, 0)
            oval(boxX+offsetX-5, boxY+offsetY-5, 10, 10)

def pathBox(path, box, fit="fill", clip=False, center=None):
    """
    Draw a BezierPath in a given rectangle.
    """
    boxX, boxY, boxW, boxH = box
    # get the image dimensions
    xMin, yMin, xMax, yMax = path.bounds()
    imW = xMax - xMin
    imH = yMax - yMin
    imX, imY = xMin, yMin
    # if a center is not provided, use the center of the image
    if center is None:
        center = imW/2, imH/2
    # get the relative scale of image to box in both directions
    fitScaleX = boxW/imW
    fitScaleY = boxH/imH
    # make the transormations
    with savedState():
        translate(boxX, boxY)
        # if fit is "cover", make a clipping path
        if clip:
            b = BezierPath()
            b.rect(0, 0, boxW, boxH)
            clipPath(b)
        # use the center of the box as a starting point
        offsetX = boxW/2
        offsetY = boxH/2
        # the scale we will actually use
        scaleX = 1
        scaleY = 1
        # if fit is "cover", use the maximum fit
        if fit == 'cover':
            scaleX = scaleY = max(fitScaleX, fitScaleY)
        # if fit is "contain", use the minimum fit
        elif fit == "contain":
            scaleX = scaleY = min(fitScaleX, fitScaleY)
        elif fit == "scale-down":
            contain = min(fitScaleX, fitScaleY)
            scaleX = scaleY = min(contain, 1)
        # if fit is "none", do nothing
        elif fit == "none":
            pass
        else:
            # by default, fit in both directions
            scaleX = fitScaleX
            scaleY = fitScaleY
        # move to the center
        translate(offsetX, offsetY)
        # scale depending on fit
        scale(scaleX, scaleY)
        # draw the image centered on the center point
        translate(-imX-center[0], -imY-center[1])
        drawPath(path)
    DEBUG = False
    if DEBUG:
        with savedState():
            fill(0, 1, 0)
            oval(boxX+offsetX-5, boxY+offsetY-5, 10, 10)

if __name__ == "__main__":
    path = "image.png"
    for fit in ['fill', 'contain', 'scale-down', 'cover', 'none']:
        newPage(1000, 500)
        r = (200, 125, 200, 200)
        im = ImageObject(path)
        imageBox(im, r, fit=fit)
        with savedState():
            fill(None)
            stroke(1, 0, 0)
            strokeWidth(2)
            rect(*r)
        r = (600, 125, 200, 200)
        fs = FormattedString('a', fontSize=800, font='Condor Variable')
        b = BezierPath()
        b.text(fs)
        fill(0, 1, 0)
        pathBox(b, r, fit=fit)
        with savedState():
            fill(None)
            stroke(1, 0, 0)
            strokeWidth(2)
            rect(*r)
        fontSize(30)
        fill(0)
        text(fit, (width()/2, 380), align="center")


text:
package com.psclistens.example.domain;

import java.math.BigDecimal;

import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

/**
 * @author LYNCHNF
 */
@StaticMetamodel(Customer.class)
public abstract class Customer_ {
    public static volatile SingularAttribute<Customer, Long> id;
    public static volatile SingularAttribute<Customer, Integer> version;
    public static volatile SingularAttribute<Customer, String> name;
    public static volatile SingularAttribute<Customer, BigDecimal> discount;
}


text:
<title>Woops, rabbit hole alert!</title>

Wrong link perhaps.

Either somebody give you a wrong link or you try to get files directory, either way it is the wrong rabbit hole. May perhaps back to homepage i presume?


text:
<?php

namespace collections;

/**
 * Get the size of an array or \Countable object. Or get the number of properties
 * an object has.
 *
 * **Usage**
 *
 * ```php
 * __::size(null)                    // false
 * __::size("true")                  // false; a string is not a collection
 * __::size([1, 2, 3])               // 3
 * __::size((object)[1, 2])          // 2
 * __::size(new ArrayIterator(5, 4)) // 2
 * ```
 *
 * @since 0.2.0
 *
 * @param mixed $value
 *
 * @return int|false False when the given object does not support getting its
 *     size.
 */
function size($value)
{
    if (\__::isArray($value) || $value instanceof \stdClass) {
        return count((array)$value);
    }

    if ($value instanceof \Countable) {
        return count($value);
    }

    try {
        $itr = \__::getIterator($value);

        return iterator_count($itr);
    } catch (\InvalidArgumentException $e) {
    }

    return false;
}


text:
import java.util.*;

public class SortInputs {
  Scanner sc;
  ArrayList<Integer> inList;

  /**
   * Basic constructor for SortInputs
   */
  public SortInputs()
  {
	  sc=new Scanner(System.in);
  }

  /**
   * insertionSort(ArrayList<Integer> A,int lastSpot) will sort
   * ArrayList<Integer> A using the insertion algorithm. This means,
   * first look at the element at position 1. If it is smaller than
   * the one at position 0, then make the element at 1 what used to
   * be at 0, and make the one at 0 what used to be at 1. Then let
   * i=2. Find the first place less than 2 (if any) where the element
   * at position 2 is smaller than that element, move that element and
   * the others after that up and put the thing that used to be at 2
   * into that spot. Continue until you have looked at all elements
   * from 0 to lastSpot-1. At this point, the elements from 0 to
   * lastSpot-1 should be sorted.
   */
  public void insertionSort(ArrayList<Integer> A,int lastSpot) {
    int j;
    int temp;
    for(int i=1;i<lastSpot;i++) {
      temp=A.get(i);
      j=i;
      while((j>0) && (temp<A.get(j-1))) {
        A.set(j,A.get(j-1));
        j=j-1;
      }
      A.set(j,temp);
    }
  }

  /**
   * run() reads in the input numbers, sorts them, and, then,
   * outputs them in sorted order.
   */
  public void run() {
    inList=new ArrayList<Integer>();
    while(sc.hasNextInt()) {
      inList.add(sc.nextInt());
    }
    insertionSort(inList,inList.size());
    for(int i=0;i<inList.size();i++) {
      System.out.println(inList.get(i));
    }
  }
}


text:
package sri.relay.network

import sri.relay.external.Deferred
import sri.relay.query.RelayQueryRoot
import sri.relay.tools.QueryResult

import scala.scalajs.js

@js.native
trait RelayQueryRequest extends Deferred[QueryResult, js.Error] with RelayRequest {

  /**
    *
    * Gets a unique identifier for this query. These identifiers are useful for
    * assigning response payloads to their corresponding queries when sent in a
    * single GraphQL request.
    */
  def getID: String = js.native

  /**
    * unstable
    */
  def getQuery: RelayQueryRoot = js.native
}


text:
let UserModel = require('./../models/User').User
let encryption = require('./../utilities/encryption')

let getUsers = (req, res) => {
    UserModel.find((err, users) => {
        if (err) res.send(err)

        res.json(users)
    })
}

let createUser = (req, res) => {
    let User = req.body
    let userExists;
    UserModel.findOne({ username: req.body.username }, function(err, user) {
        if (user) {
            res.status(409).send({
                message: 'User exists!'
            });
        } else if (User.password && User.username && User.role) {
            User.salt = encryption.generateSalt()
            User.hashedPwd = encryption.generateHashedPassword(User.salt, User.password)
            UserModel
                .create(User)
                .then(user => logUserIn(user, req, res))
        } else {
            res.status(400).send({
                message: 'Not a proper request!'
            });
        }
    })
}

let authenticate = (req, res) => {
    let userCred = req.body
    UserModel
        .findOne({ username: userCred.username }, function(err, user) {
            if (!user || !user.authenticate(userCred.password)) {
                res.status(404).send({
                    message: 'Non-existing user!'
                });
                return;
            } else {
                logUserIn(user, req, res)
            }
        })
}

let logout = (req, res) => {
    req.logout()
    res.redirect('/')
}

// Private functions
let logUserIn = (user, req, res) => {
    let userRole = user.role,
        username = user.username,
        msgOnSuccess = 'Authentication passed. User found.';

    req.login(user, (err, user) => {
        if (err) {
            res.status(500).send({
                message: 'Cannot log in current user!'
            });
            return;
        } else {
            res.send({
                success: true,
                user: username,
                role: userRole,
                msg: msgOnSuccess
            })
        }
    })
}

module.exports = {
    getUsers: getUsers,
    create: createUser,
    authenticate: authenticate,
    logout: logout
}


text:
<?php defined('SYSPATH') or die('No direct script access.'); ?>

2011-08-25 08:16:14 --- ERROR: ErrorException [ 8 ]: Undefined offset: 0 ~ APPPATH\classes\controller\hojaruta.php [ 65 ]


text:
/**********************************************************************************************************************
* Change Control:	24/06/2014 - Sorin Oboroceanu - Gets the data used to generate the Arvato batch file header.
**********************************************************************************************************************/
CREATE PROCEDURE [dbo].[h3giArvatoBatchFile_GetHeaderData]
(
	@BatchId INT
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @SimTypeAttributeId INT
    SET @SimTypeAttributeId = dbo.fn_GetAttributeByName('SimType');

	-- CONSUMER ---------------------------------------------------
	DECLARE @ConsumerUpgradeOrdersNoSim INT,
			@ConsumerKittedProducts INT,
			@ConsumerAccessoryProducts INT,
			@ConsumerSimProducts INT

	DECLARE @ConsumerBatchOrders TABLE
	(
		orderRef INT PRIMARY KEY
	);
	INSERT INTO @ConsumerBatchOrders(orderRef)
	SELECT bo.OrderRef
	FROM h3giBatchOrder bo
	INNER JOIN h3giOrderheader head ON bo.OrderRef = head.orderref
	WHERE bo.BatchID = @BatchId

	-- Count the number of consumer upgrade order that don't require a SIM (the customer kept his SIM).
	SELECT @ConsumerUpgradeOrdersNoSim = ISNULL(COUNT(h.orderref), 0)
	FROM @ConsumerBatchOrders b
	INNER JOIN h3giOrderheader h ON b.orderRef = h.orderref
	INNER JOIN h3giUpgrade u ON u.UpgradeId = h.UpgradeID
	INNER JOIN b4nAttributeProductFamily a ON a.productFamilyId = h.phoneProductCode AND a.attributeId = @SimTypeAttributeId
	WHERE u.simType = a.attributeValue
	AND h.orderType IN (2, 3)

	--Count the number of  kitted products so that we can
	--subtract this amount from the "Segments" in the header row
	SELECT @ConsumerKittedProducts = COUNT(*)
	FROM h3giOrderHeader HOH
	INNER JOIN viewOrderPhone  VOP ON VOP.OrderRef = HOH.OrderRef
	WHERE HOH.OrderRef IN (SELECT OrderRef FROM @ConsumerBatchOrders)
	AND VOP.Kitted = 1

	--Count the number of accessory products so
	--we can subtract the amount from the "Segments" in the header row
	SELECT @ConsumerAccessoryProducts = COUNT(*)
	FROM h3giOrderheader h3gi
	 INNER JOIN @ConsumerBatchOrders b
	 ON h3gi.orderref = b.orderRef
	WHERE h3gi.orderType = 4

	--Count the number of SIM orders and subtract that from the Segments in the header
	--we no longer want to add a SIM row to the file for SIM only orders
	SELECT @ConsumerSimProducts = COUNT(*)
	FROM @ConsumerBatchOrders b
	INNER JOIN h3giOrderheader h3gi
		ON b.orderRef = h3gi.orderref
	INNER JOIN h3giProductCatalogue cat
		ON h3gi.catalogueVersionID = cat.catalogueVersionID
		AND h3gi.phoneProductCode = cat.productFamilyId
	INNER JOIN h3giProductAttributeValue pav
		ON pav.catalogueProductId = cat.catalogueProductID
	INNER JOIN h3giProductAttribute att
		ON att.attributeId = pav.attributeId
	WHERE att.attributeName = 'SIM'

	-- BUSINESS------------------------------------------------------
	DECLARE	@BusinessUpgradeOrdersNoSim INT,
			@BusinessUpgradeKittedProducts INT

	DECLARE @BusinessUpgradeBatchOrders TABLE
	(
		orderRef INT PRIMARY KEY
	);
	INSERT INTO @BusinessUpgradeBatchOrders(orderRef)
	SELECT bo.OrderRef
	FROM h3giBatchOrder bo
	INNER JOIN threeOrderUpgradeHeader head	ON bo.OrderRef = head.orderref
	WHERE bo.BatchID = @BatchId

	--Count the number of orders that don't require SIMs so that we can
	--subtract this amount from the "Segments" in the header row
	SELECT @BusinessUpgradeOrdersNoSim = ISNULL(COUNT(head.orderref), 0)
	FROM @BusinessUpgradeBatchOrders b
	INNER JOIN threeOrderUpgradeHeader head ON b.orderRef = head.orderref
	INNER JOIN threeUpgrade upg ON upg.UpgradeId = head.UpgradeID
	INNER JOIN h3giProductCatalogue cat	ON head.deviceId = cat.catalogueProductID AND head.catalogueVersionId = cat.catalogueVersionID
	INNER JOIN b4nAttributeProductFamily a ON a.productFamilyId = cat.productFamilyId AND a.attributeId = @SimTypeAttributeId
	WHERE upg.simType = a.attributeValue

	--Count the number of  kitted products so that we can
	--subtract this amount from the "Segments" in the header row
	SELECT @BusinessUpgradeKittedProducts = COUNT(*)
	FROM threeOrderUpgradeHeader head
	INNER JOIN h3giProductCatalogue cat ON head.deviceId = cat.catalogueProductID AND head.catalogueVersionId = cat.catalogueVersionID
	WHERE cat.Kitted = 1
	--------------------------------------------------------------

	SELECT	'H1' AS SegmentId,
			BatchId,
			b4nClassCodes.b4nClassCode AS CarrierCode,
			Courier AS CarrierName,
			'SearchProduct:' + CAST(SearchProduct AS VARCHAR(10)) + ';' +
			'SearchDateFrom:' + CAST(ISNULL(SearchDateFrom, '') AS VARCHAR (20))+ ';' +
			'SearchDateTo:' + CAST(ISNULL(SearchDateTo, '') AS VARCHAR (20)) + ';' +
			'SearchOutOfStock:' + CAST(SearchOutOfStock AS VARCHAR(1)) + ';' AS FilterCriteria,
			CreateDate,
			(SELECT COUNT(OrderRef) FROM @ConsumerBatchOrders) AS ConsumerTransactions,
			((((SELECT COUNT(OrderRef) FROM @ConsumerBatchOrders) * 3) + 1) - @ConsumerUpgradeOrdersNoSim - @ConsumerKittedProducts - @ConsumerAccessoryProducts - @ConsumerSimProducts) AS ConsumerSegments,
			(SELECT	COUNT(orderRef) FROM @BusinessUpgradeBatchOrders) AS BusinessUpgradeTransactions,
			(SELECT ((COUNT (orderRef) * 3) - @BusinessUpgradeOrdersNoSim - @BusinessUpgradeKittedProducts) FROM @BusinessUpgradeBatchOrders) AS BusinessUpgradeSegments
	FROM h3giBatch
	INNER JOIN b4nClassCodes ON b4nClassCodes.b4nClassDesc = h3giBatch.Courier AND b4nClassCodes.b4nClassSysID = 'SONO_CARRIER'
	WHERE BatchID = @BatchId
END
GRANT EXECUTE ON h3giArvatoBatchFile_GetHeaderData TO b4nuser
GO


text:
package game.controller.optionState;

import constants.Constants;
import game.controller.AbstractBattleMode;

/**
 * State presented after the player loses a wild region battle
 * @author Team Rocket
 *
 */
public class UserLostWildBattleCompleteState extends AbstractWildBattleCompleteState {

    public UserLostWildBattleCompleteState (AbstractBattleMode mode) {
        super(mode, Constants.YOU_LOST);
    }

    @Override
    protected void onInteract () {
        super.onInteract();
        //let's keep it simple. the player's monsters are all revived with no consequence
        myMode.getController().getModel().getPlayer().healAllMonsters();
        myMode.getController().getModel().getPlayer().goToLastSavedLoc();
    }

}


text:
using System;
using System.Globalization;
using System.Web.Routing;
using Grand.Core;
using Grand.Core.Domain.Shipping;
using Grand.Core.Plugins;
using Grand.Services.Configuration;
using Grand.Services.Localization;
using Grand.Services.Logging;
using Grand.Services.Shipping;
using Grand.Services.Shipping.Tracking;
using NopBrasil.Plugin.Shipping.Correios.Domain;
using NopBrasil.Plugin.Shipping.Correios.Service;
using Grand.Core.Domain.Orders;
using System.Collections.Generic;

namespace NopBrasil.Plugin.Shipping.Correios
{
    public class CorreiosComputationMethod : BasePlugin, IShippingRateComputationMethod
    {
        private readonly ISettingService _settingService;
        private readonly CorreiosSettings _correiosSettings;
        private readonly ILogger _logger;
        private readonly ILocalizationService _localizationService;
        private readonly ICorreiosService _correiosService;

        public CorreiosComputationMethod(ISettingService settingService,
            CorreiosSettings correiosSettings, ILogger logger,
            ILocalizationService localizationService, ICorreiosService correiosService)
        {
            this._settingService = settingService;
            this._correiosSettings = correiosSettings;
            this._logger = logger;
            this._localizationService = localizationService;
            this._correiosService = correiosService;
        }

        private bool ValidateRequest(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse response)
        {
            if (getShippingOptionRequest.Items == null)
            {
                response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.NoShipmentItems"));
                return false;
            }
            if (getShippingOptionRequest.ShippingAddress == null)
            {
                response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.AddressNotSet"));
                return false;
            }
            if (string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId))
            {
                response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.CountryNotSet"));
                return false;
            }
            if (string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.StateProvinceId))
            {
                response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.StateNotSet"));
                return false;
            }
            if (getShippingOptionRequest.ShippingAddress.ZipPostalCode == null)
            {
                response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.PostalCodeNotSet"));
                return false;
            }
            return true;
        }

        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
                throw new ArgumentNullException("getShippingOptionRequest");

            var response = new GetShippingOptionResponse();

            if (!ValidateRequest(getShippingOptionRequest, response))
                return response;

            try
            {
                WSCorreiosCalcPrecoPrazo.cResultado wsResult = _correiosService.RequestCorreios(getShippingOptionRequest);
                foreach (WSCorreiosCalcPrecoPrazo.cServico serv in wsResult?.Servicos)
                {
                    try
                    {
                        ValidateWSResult(serv);
                        response.ShippingOptions.Add(GetShippingOption(ApplyAdditionalFee(Convert.ToDecimal(serv.Valor, new CultureInfo("pt-BR"))), CorreiosServiceType.GetServiceName(serv.Codigo.ToString()), CalcPrazoEntrega(serv)));
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e.Message, e);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message, e);
            }

            if (response.ShippingOptions.Count <= 0)
                response.ShippingOptions.Add(GetShippingOption(_correiosSettings.ShippingRateDefault, _correiosSettings.ServiceNameDefault, _correiosSettings.QtdDaysForDeliveryDefault));

            return response;
        }

        private decimal ApplyAdditionalFee(decimal rate) => _correiosSettings.PercentageShippingFee > 0.0M ? rate * _correiosSettings.PercentageShippingFee : rate;

        private ShippingOption GetShippingOption(decimal rate, string serviceName, int prazo) => new ShippingOption() { Rate = _correiosService.GetConvertedRateToPrimaryCurrency(rate), Name = $"{serviceName} - {prazo} dia(s)" };

        private int CalcPrazoEntrega(WSCorreiosCalcPrecoPrazo.cServico serv)
        {
            int prazo = Convert.ToInt32(serv.PrazoEntrega);
            if (_correiosSettings.AddDaysForDelivery > 0)
                prazo += _correiosSettings.AddDaysForDelivery;
            return prazo;
        }

        private void ValidateWSResult(WSCorreiosCalcPrecoPrazo.cServico wsServico)
        {
            if (string.IsNullOrEmpty(wsServico.Erro))
                throw new GrandException(wsServico.Erro + " - " + wsServico.MsgErro);

            if (Convert.ToInt32(wsServico.PrazoEntrega) <= 0)
                throw new GrandException(_localizationService.GetResource("Plugins.Shipping.Correios.Message.DeliveryUninformed"));

            if (Convert.ToDecimal(wsServico.Valor, new CultureInfo("pt-BR")) <= 0)
                throw new GrandException(_localizationService.GetResource("Plugins.Shipping.Correios.Message.InvalidValueDelivery"));
        }

        public decimal? GetFixedRate(GetShippingOptionRequest getShippingOptionRequest) => null;

        public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
        {
            actionName = "Configure";
            controllerName = "ShippingCorreios";
            routeValues = new RouteValueDictionary() { { "Namespaces", "NopBrasil.Plugin.Shipping.Correios.Controllers" }, { "area", null } };
        }

        public override void Install()
        {
            var settings = new CorreiosSettings()
            {
                Url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx",
                PostalCodeFrom = "",
                CompanyCode = "",
                Password = "",
                AddDaysForDelivery = 0,
                PercentageShippingFee = 1.0M
            };
            _settingService.SaveSetting(settings);

            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.Url", "URL");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.Url.Hint", "Specify Correios URL.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.PostalCodeFrom", "Postal Code From");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.PostalCodeFrom.Hint", "Specify From Postal Code.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.CompanyCode", "Company Code");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.CompanyCode.Hint", "Specify Your Company Code.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.Password", "Password");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.Password.Hint", "Specify Your Password.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.AddDaysForDelivery", "Additional Days For Delivery");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.AddDaysForDelivery.Hint", "Set The Amount Of Additional Days For Delivery.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.AvailableCarrierServices", "Available Carrier Services");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.AvailableCarrierServices.Hint", "Set Available Carrier Services.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.ServiceNameDefault", "Service Name Default");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.ServiceNameDefault.Hint", "Service Name Used When The Correios Does Not Return Value.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.ShippingRateDefault", "Shipping Rate Default");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.ShippingRateDefault.Hint", "Shipping Rate Used When The Correios Does Not Return Value.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.QtdDaysForDeliveryDefault", "Number Of Days For Delivery Default");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.QtdDaysForDeliveryDefault.Hint", "Number Of Days For Delivery Used When The Correios Does Not Return Value.");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.PercentageShippingFee", "Additional percentage shipping fee");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Fields.PercentageShippingFee.Hint", "Set the additional percentage shipping rate.");

            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.NoShipmentItems", "No shipment items");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.AddressNotSet", "Shipping address is not set");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.CountryNotSet", "Shipping country is not set");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.StateNotSet", "Shipping state is not set");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.PostalCodeNotSet", "Shipping zip postal code is not set");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.DeliveryUninformed", "Delivery uninformed");
            this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.Correios.Message.InvalidValueDelivery", "Invalid value delivery");

            base.Install();
        }

        public override void Uninstall()
        {
            _settingService.DeleteSetting<CorreiosSettings>();

            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.Url");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.Url.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.PostalCodeFrom");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.PostalCodeFrom.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.CompanyCode");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.CompanyCode.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.Password");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.Password.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.AddDaysForDelivery");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.AddDaysForDelivery.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.AvailableCarrierServices");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.AvailableCarrierServices.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.ServiceNameDefault");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.ServiceNameDefault.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.ShippingRateDefault");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.ShippingRateDefault.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.QtdDaysForDeliveryDefault");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.QtdDaysForDeliveryDefault.Hint");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.PercentageShippingFee");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Fields.PercentageShippingFee.Hint");

            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.NoShipmentItems");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.AddressNotSet");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.CountryNotSet");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.StateNotSet");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.PostalCodeNotSet");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.DeliveryUninformed");
            this.DeletePluginLocaleResource("Plugins.Shipping.Correios.Message.InvalidValueDelivery");

            base.Uninstall();
        }

        public bool HideShipmentMethods(IList<ShoppingCartItem> cart) => false;

        public Type GetControllerType() => typeof(Controllers.ShippingCorreiosController);

        public ShippingRateComputationMethodType ShippingRateComputationMethodType => ShippingRateComputationMethodType.Realtime;

        public IShipmentTracker ShipmentTracker => new CorreiosShipmentTracker(_correiosSettings);
    }
}


text:
package org.apache.carbondata.view

import java.util.concurrent.locks.ReentrantReadWriteLock

import scala.collection.JavaConverters._

import org.apache.log4j.Logger
import org.apache.spark.sql.{CarbonToSparkAdapter, DataFrame, SparkSession}
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, SubqueryAlias}
import org.apache.spark.sql.execution.datasources.FindDataSourceTable
import org.apache.spark.sql.parser.MVQueryParser

import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.metadata.schema.table.RelationIdentifier
import org.apache.carbondata.core.view.{MVCatalog, MVSchema}
import org.apache.carbondata.mv.plans.modular.{Flags, ModularPlan, ModularRelation, Select, SimpleModularizer}
import org.apache.carbondata.mv.plans.util.BirdcageOptimizer

case class MVCatalogInSpark(session: SparkSession)
  extends MVCatalog[MVSchemaWrapper] {

  @transient
  private val logger = MVCatalogInSpark.LOGGER

  @transient
  private val lock = new ReentrantReadWriteLock

  @transient
  private val viewSchemas = new scala.collection.mutable.ArrayBuffer[MVSchemaWrapper]

  @transient
  private val viewManager = MVManagerInSpark.get(session)

  /** Acquires a read lock on the catalog for the duration of `f`. */
  private def withReadLock[A](f: => A): A = {
    val readLock = lock.readLock()
    readLock.lock()
    try f finally {
      readLock.unlock()
    }
  }

  /** Acquires a write lock on the catalog for the duration of `f`. */
  private def withWriteLock[A](function: => A): A = {
    val writeLock = lock.writeLock()
    writeLock.lock()
    try function finally {
      writeLock.unlock()
    }
  }

  override def getValidSchemas: Array[MVSchemaWrapper] = {
    val enabledStatusDetails = viewManager.getEnabledStatusDetails.asScala
    // Only select the enabled mvs for the query.
    val enabledSchemas = viewSchemas.filter {
      enabledSchema =>
        enabledStatusDetails.exists(
          statusDetail =>
            statusDetail.getIdentifier.getDatabaseName.equalsIgnoreCase(
              enabledSchema.viewSchema.getIdentifier.getDatabaseName) &&
            statusDetail.getIdentifier.getTableName.equalsIgnoreCase(
              enabledSchema.viewSchema.getIdentifier.getTableName))
    }
    enabledSchemas.toArray
  }

  def getAllSchemas: Array[MVSchemaWrapper] = {
    viewSchemas.toArray
  }

  def isMVInSync(mvSchema: MVSchema): Boolean = {
    viewManager.isMVInSyncWithParentTables(mvSchema)
  }

  /**
   * Registers the data produced by the logical representation of the given [[DataFrame]]. Unlike
   * `RDD.cache()`, the default storage level is set to be `MEMORY_AND_DISK` because recomputing
   * the in-memory columnar representation of the underlying table is expensive.
   */
  def registerSchema(mvSchema: MVSchema): Unit = {
    withWriteLock {
      val currentDatabase = session.catalog.currentDatabase
      val logicalPlan = try {
        // This is required because mv schemas are across databases, so while loading the
        // catalog, if the mv is in database other than sparkSession.currentDataBase(), then it
        // fails to register, so set the database present in the mvSchema Object
        session.catalog.setCurrentDatabase(mvSchema.getIdentifier.getDatabaseName)
        MVHelper.dropDummyFunction(MVQueryParser.getQueryPlan(mvSchema.getQuery, session))
      } finally {
        // here setting back to current database of current session, because if the actual query
        // contains db name in query like, select db1.column1 from table and current database is
        // default and if we drop the db1, still the session has current db as db1.
        // So setting back to current database.
        session.catalog.setCurrentDatabase(currentDatabase)
      }
      // The MV query is modified by replacing avg with sum and count columns.
      // Here, create modifiedLogicalPlan from modified query, so that even though MV is not created
      // with sum or count columns, we could still derive the columns.
      // For example, Consider MV creation statement:
      // create materialized view mv1 as select empname, avg(salary) from source group by empname;
      // and here if user queries:
      // Select empname, sum(salary) from source group by empname;
      // we can use modifiedLogicalPlan for query matching and rewrite steps.
      val modifiedLogicalPlan = if (mvSchema.getModifiedQuery != null &&
                                    !mvSchema.getModifiedQuery
                                      .equalsIgnoreCase(mvSchema.getQuery)) {
        try {
          session.catalog.setCurrentDatabase(mvSchema.getIdentifier.getDatabaseName)
          MVHelper.dropDummyFunction(MVQueryParser.getQueryPlan(mvSchema.getModifiedQuery, session))
        } finally {
          session.catalog.setCurrentDatabase(currentDatabase)
        }
      } else {
        logicalPlan
      }
      val mvSignature = SimpleModularizer.modularize(
        BirdcageOptimizer.execute(logicalPlan)).next().semiHarmonized.signature
      val mvIdentifier = mvSchema.getIdentifier
      val mvTableIdentifier =
        TableIdentifier(mvIdentifier.getTableName, Some(mvIdentifier.getDatabaseName))
      val plan = new FindDataSourceTable(session)
        .apply(session.sessionState.catalog.lookupRelation(mvTableIdentifier))
      val output = plan match {
        case alias: SubqueryAlias =>
          CarbonToSparkAdapter.getOutput(alias)
        case _ =>
          plan.output
      }
      val relation = ModularRelation(mvIdentifier.getDatabaseName,
        mvIdentifier.getTableName,
        output,
        Flags.NoFlags,
        Seq.empty)
      val modularPlan = Select(relation.outputList,
        relation.outputList,
        Seq.empty,
        Seq((0, mvIdentifier.getTableName)).toMap,
        Seq.empty,
        Seq(relation),
        Flags.NoFlags,
        Seq.empty,
        Seq.empty,
        None)
      viewSchemas += MVSchemaWrapper(
        mvSignature,
        mvSchema,
        logicalPlan,
        modifiedLogicalPlan,
        MVPlanWrapper(modularPlan, mvSchema))
    }
  }

  /** Removes the given [[DataFrame]] from the catalog */
  def deregisterSchema(mvIdentifier: RelationIdentifier): Unit = {
    withWriteLock {
      val mvIndex = viewSchemas.indexWhere(_.viewSchema.getIdentifier.equals(mvIdentifier))
      require(mvIndex >= 0, s"MV $mvIdentifier is not registered.")
      viewSchemas.remove(mvIndex)
    }
  }

  /**
   * API for test only
   *
   * Registers the data produced by the logical representation of the given [[DataFrame]]. Unlike
   * `RDD.cache()`, the default storage level is set to be `MEMORY_AND_DISK` because recomputing
   * the in-memory columnar representation of the underlying table is expensive.
   */
  def registerSchema(query: DataFrame, tableName: Option[String] = None): Unit = {
    withWriteLock {
      val logicalPlan = query.queryExecution.analyzed
      if (lookupSchema(logicalPlan).nonEmpty) {
        logger.error(s"Asked to register already registered.")
      } else {
        val modularPlan = SimpleModularizer.modularize(
            BirdcageOptimizer.execute(logicalPlan)).next().semiHarmonized
        val signature = modularPlan.signature
        viewSchemas += MVSchemaWrapper(signature, null, logicalPlan, logicalPlan, null)
      }
    }
  }

  /**
   * Check and return mv having same query already present in the catalog
   */
  def getMVWithSameQueryPresent(query: LogicalPlan): Option[MVSchemaWrapper] = {
    lookupSchema(query)
  }

  /** Returns feasible registered mv schemas for processing the given ModularPlan. */
  private def lookupSchema(plan: LogicalPlan): Option[MVSchemaWrapper] = {
    withReadLock {
      viewSchemas.find(mvSchema => plan.sameResult(mvSchema.logicalPlan))
    }
  }

  /** Returns feasible registered mv schemas for processing the given ModularPlan. */
  def lookupFeasibleSchemas(plan: ModularPlan): Seq[MVSchemaWrapper] = {
    withReadLock {
      val signature = plan.signature
      val enableStatusDetails = viewManager.getEnabledStatusDetails.asScala
      // Only select the enabled mvs for the query.
      val enabledSchemas = viewSchemas.filter {
        viewSchema =>
          enableStatusDetails.exists(
            _.getIdentifier.getTableName.equalsIgnoreCase(
              viewSchema.viewSchema.getIdentifier.getTableName))
      }
      // Heuristics: more tables involved in a mv schema set => higher query reduction factor
      enabledSchemas.filter {
        enabledSchema => (enabledSchema.viewSignature, signature) match {
          case (Some(signature1), Some(signature2)) =>
            if (signature1.groupby && signature2.groupby &&
                signature1.datasets.subsetOf(signature2.datasets)) {
              true
            } else if (!signature1.groupby && !signature2.groupby &&
                       signature1.datasets.subsetOf(signature2.datasets)) {
              true
            } else {
              false
            }
          case _ => false
        }
      }
      .sortWith(_.viewSignature.get.datasets.size > _.viewSignature.get.datasets.size)
    }
  }

}

object MVCatalogInSpark {

  val LOGGER: Logger =
    LogServiceFactory.getLogService(classOf[MVCatalogInSpark].getCanonicalName)

}


text:
namespace Halide {
namespace Internal {

class EliminateBoolVectors : public IRMutator2 {
private:
    using IRMutator2::visit;

    Scope<Type> lets;

    Expr visit(const Variable *op) override {
        if (lets.contains(op->name)) {
            return Variable::make(lets.get(op->name), op->name);
        } else {
            return op;
        }
    }

    template <typename T>
    Expr visit_comparison(const T* op) {
        Expr a = mutate(op->a);
        Expr b = mutate(op->b);
        Type t = a.type();

        // Ensure both a and b have the same type (if this is a vector
        // comparison). This should only be necessary if the operands are
        // integer vectors (promoted from bool vectors).
        if (t.lanes() > 1 && t.bits() != b.type().bits()) {
            internal_assert(t.is_int() && b.type().is_int());

            t = t.with_bits(std::max(t.bits(), b.type().bits()));
            if (t != a.type()) {
                a = Call::make(t, Call::cast_mask, {a}, Call::PureIntrinsic);
            }
            if (t != b.type()) {
                b = Call::make(t, Call::cast_mask, {b}, Call::PureIntrinsic);
            }
        }

        Expr expr;
        if (!a.same_as(op->a) || !b.same_as(op->b)) {
            expr = T::make(a, b);
        } else {
            expr = op;
        }

        if (t.lanes() > 1) {
            // To represent bool vectors, OpenCL uses vectors of signed
            // integers with the same width as the types being compared.
            expr = Call::make(t.with_code(Type::Int), Call::bool_to_mask, {expr}, Call::PureIntrinsic);
        }
        return expr;
    }

    Expr visit(const EQ *op) override { return visit_comparison(op); }
    Expr visit(const NE *op) override { return visit_comparison(op); }
    Expr visit(const LT *op) override { return visit_comparison(op); }
    Expr visit(const LE *op) override { return visit_comparison(op); }
    Expr visit(const GT *op) override { return visit_comparison(op); }
    Expr visit(const GE *op) override { return visit_comparison(op); }

    template <typename T>
    Expr visit_logical_binop(const T* op, const std::string& bitwise_op) {
        Expr a = mutate(op->a);
        Expr b = mutate(op->b);

        Type ta = a.type();
        Type tb = b.type();
        if (ta.lanes() > 1) {
            // Ensure that both a and b have the same type.
            Type t = ta.with_bits(std::max(ta.bits(), tb.bits()));
            if (t != a.type()) {
                a = Call::make(t, Call::cast_mask, {a}, Call::PureIntrinsic);
            }
            if (t != b.type()) {
                b = Call::make(t, Call::cast_mask, {b}, Call::PureIntrinsic);
            }
            // Replace logical operation with bitwise operation.
            return Call::make(t, bitwise_op, {a, b}, Call::PureIntrinsic);
        } else if (!a.same_as(op->a) || !b.same_as(op->b)) {
            return T::make(a, b);
        } else {
            return op;
        }
    }

    Expr visit(const Or *op) override {
        return visit_logical_binop(op, Call::bitwise_or);
    }

    Expr visit(const And *op) override {
        return visit_logical_binop(op, Call::bitwise_and);
    }

    Expr visit(const Not *op) override {
        Expr a = mutate(op->a);
        if (a.type().lanes() > 1) {
            // Replace logical operation with bitwise operation.
            return Call::make(a.type(), Call::bitwise_not, {a}, Call::PureIntrinsic);
        } else if (!a.same_as(op->a)) {
            return Not::make(a);
        } else {
            return op;
        }
    }

    Expr visit(const Cast *op) override {
        if (op->value.type().is_bool() && op->value.type().is_vector()) {
            // Casting from bool
            return mutate(Select::make(op->value,
                                       make_one(op->type),
                                       make_zero(op->type)));
        } else if (op->type.is_bool() && op->type.is_vector()) {
            // Cast to bool
            return mutate(op->value != make_zero(op->value.type()));
        } else {
            return IRMutator2::visit(op);
        }
    }

    Stmt visit(const Store *op) override {
        Expr predicate = mutate(op->predicate);
        Expr value = op->value;
        if (op->value.type().is_bool()) {
            Type ty = UInt(8, op->value.type().lanes());
            value = Select::make(value,
                                 make_one(ty),
                                 make_zero(ty));
        }
        value = mutate(value);
        Expr index = mutate(op->index);

        if (predicate.same_as(op->predicate) && value.same_as(op->value) && index.same_as(op->index)) {
            return op;
        } else {
            return Store::make(op->name, value, index, op->param, predicate);
        }
    }

    Expr visit(const Select *op) override {
        Expr cond = mutate(op->condition);
        Expr true_value = mutate(op->true_value);
        Expr false_value = mutate(op->false_value);
        Type cond_ty = cond.type();
        if (cond_ty.is_vector()) {
            // If the condition is a vector, it should be a vector of
            // ints.
            internal_assert(cond_ty.code() == Type::Int);

            // If both true_value and false_value were originally boolean vectors,
            // they might have been promoted to different-sized integer vectors
            // depending on how they were calculated, e.g.
            //
            //    Expr a = float_expr1() < float_expr2();  // promoted to int32xN
            //    Expr b = uint8_expr1() < uint8_expr2();  // promoted to int8xN
            //    Expr c = select(a < b, a, b);            // whoops
            //
            if (true_value.type().bits() != false_value.type().bits() &&
                true_value.type().lanes() == false_value.type().lanes() &&
                true_value.type().is_int() && false_value.type().is_int()) {
                if (true_value.type().bits() > false_value.type().bits()) {
                    false_value = Call::make(true_value.type(), Call::cast_mask, {false_value}, Call::PureIntrinsic);
                } else {
                    true_value = Call::make(false_value.type(), Call::cast_mask, {true_value}, Call::PureIntrinsic);
                }
            }

            // select_mask requires that all 3 operands have the same
            // width.
            internal_assert(true_value.type().bits() == false_value.type().bits());
            if (true_value.type().bits() != cond_ty.bits()) {
                cond_ty = cond_ty.with_bits(true_value.type().bits());
                cond = Call::make(cond_ty, Call::cast_mask, {cond}, Call::PureIntrinsic);
            }

            return Call::make(true_value.type(), Call::select_mask, {cond, true_value, false_value}, Call::PureIntrinsic);
        } else if (!cond.same_as(op->condition) ||
                   !true_value.same_as(op->true_value) ||
                   !false_value.same_as(op->false_value)) {
            return Select::make(cond, true_value, false_value);
        } else {
            return op;
        }
    }

    Expr visit(const Broadcast *op) override {
        Expr value = mutate(op->value);
        if (op->type.bits() == 1) {
            return Broadcast::make(Call::make(Int(8), Call::bool_to_mask, {value}, Call::PureIntrinsic), op->lanes);
        } else if (!value.same_as(op->value)) {
            return Broadcast::make(value, op->lanes);
        } else {
            return op;
        }
    }

    Expr visit(const Shuffle *op) override {
        Expr expr = IRMutator2::visit(op);
        if (op->is_extract_element() && op->type.is_bool()) {
            op = expr.as<Shuffle>();
            internal_assert(op);
            // This is extracting a scalar element of a bool
            // vector. Generate a call to extract_mask_element.
            expr = Call::make(Bool(), Call::extract_mask_element, {Shuffle::make_concat(op->vectors), op->indices[0]}, Call::PureIntrinsic);
        }
        return expr;
    }

    template <typename NodeType, typename LetType>
    NodeType visit_let(const LetType *op) {
        Expr value = mutate(op->value);

        // We changed the type of the let, we need to replace the
        // references to the let in the body. We can't just substitute
        // them, because the types won't match without running the
        // other visitors during the substitution, so we save the
        // types that we changed for later.
        if (value.type() != op->value.type()) {
            lets.push(op->name, value.type());
        }
        auto body = mutate(op->body);
        if (value.type() != op->value.type()) {
            lets.pop(op->name);
        }

        if (!value.same_as(op->value) || !body.same_as(op->body)) {
            return LetType::make(op->name, value, body);
        } else {
            return op;
        }
    }

    Expr visit(const Let *op) override { return visit_let<Expr>(op); }
    Stmt visit(const LetStmt *op) override { return visit_let<Stmt>(op); }
};

Stmt eliminate_bool_vectors(Stmt s) {
    return EliminateBoolVectors().mutate(s);
}

Expr eliminate_bool_vectors(Expr e) {
    return EliminateBoolVectors().mutate(e);
}

}  // namespace Internal
}  // namespace Halide


text:
namespace net {

// Use DnsConfigService::CreateSystemService to use it outside of tests.
namespace internal {

class NET_EXPORT_PRIVATE DnsConfigServicePosix : public DnsConfigService {
 public:
  DnsConfigServicePosix();
  virtual ~DnsConfigServicePosix();

 protected:
  // DnsConfigService:
  virtual void ReadNow() OVERRIDE;
  virtual bool StartWatching() OVERRIDE;

 private:
  class Watcher;
  class ConfigReader;
  class HostsReader;

  void OnConfigChanged(bool succeeded);
  void OnHostsChanged(bool succeeded);

  scoped_ptr<Watcher> watcher_;
  scoped_refptr<ConfigReader> config_reader_;
  scoped_refptr<HostsReader> hosts_reader_;

  DISALLOW_COPY_AND_ASSIGN(DnsConfigServicePosix);
};

enum ConfigParsePosixResult {
  CONFIG_PARSE_POSIX_OK = 0,
  CONFIG_PARSE_POSIX_RES_INIT_FAILED,
  CONFIG_PARSE_POSIX_RES_INIT_UNSET,
  CONFIG_PARSE_POSIX_BAD_ADDRESS,
  CONFIG_PARSE_POSIX_BAD_EXT_STRUCT,
  CONFIG_PARSE_POSIX_NULL_ADDRESS,
  CONFIG_PARSE_POSIX_NO_NAMESERVERS,
  CONFIG_PARSE_POSIX_MISSING_OPTIONS,
  CONFIG_PARSE_POSIX_UNHANDLED_OPTIONS,
  CONFIG_PARSE_POSIX_NO_DNSINFO,
  CONFIG_PARSE_POSIX_MAX  // Bounding values for enumeration.
};

#if !defined(OS_ANDROID)
// Fills in |dns_config| from |res|.
ConfigParsePosixResult NET_EXPORT_PRIVATE ConvertResStateToDnsConfig(
    const struct __res_state& res, DnsConfig* dns_config);
#endif

}  // namespace internal

}  // namespace net

#endif  // NET_DNS_DNS_CONFIG_SERVICE_POSIX_H_