text:
module Main where

import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Lens
import Control.Monad
import Control.Monad.Identity
import Control.Monad.State.Strict
import Control.Monad.Trans
import Data.Array.IO
import Data.Word
import Graphics.UI.SDL as SDL
import Text.Printf
import System.Clock
import System.IO
import System.Environment
import System.Random

import HChip.CPU
import HChip.Debug
import HChip.Loader
import HChip.Machine
import HChip.Ops
import HChip.Sound
import HChip.Util

main = do
  fs <- getArgs
  case fs of
    [ f ] -> main' f
    _ -> putStrLn "Usage: hchip <rom>"

main' f = do
  rom <- BSL.readFile f
  case loadAssembly rom of
    Left e -> putStrLn ("Problem parsing ROM: " ++ e)
    Right a -> do
      ( fb, bb ) <- initSDL
      s <- initState a fb bb
      evalStateT (runEmu mainLoop) s
      liftIO $ putStrLn ""
      quit

initSDL :: IO ( Surface, Surface )
initSDL = do
  SDL.init [ InitVideo, InitAudio ]
  fb <- setVideoMode 320 240 32 [ HWSurface ]
  bb <- createRGBSurface [ SWSurface ] 320 240 8 0xFF 0xFF 0xFF 0xFF
  setColors bb defaultPalette 0
  return ( fb, bb )

setPad :: Bool -> Keysym -> Emu ()
setPad s (Keysym k _ _) = let l = case k of {
  ; SDLK_UP -> Just padUp
  ; SDLK_RIGHT -> Just padRight
  ; SDLK_DOWN -> Just padDown
  ; SDLK_LEFT -> Just padLeft
  ; SDLK_q -> Just padStart
  ; SDLK_w -> Just padSelect
  ; SDLK_x -> Just padB
  ; SDLK_z -> Just padA
  ; _ -> Nothing
  }
  in case l of
    Nothing -> return ()
    Just l -> do
      m <- gets memory
      p <- liftIO $ readArray m 0xFFF0
      liftIO $ writeArray m 0xFFF0 (p & l .~ s)

processEvents :: Emu Bool
processEvents = do
  e <- liftIO pollEvent
  ( q, l ) <- case e of
    Quit -> return ( True, False )
    NoEvent -> return ( False, False )
    KeyDown k -> setPad True k >> return ( False, True )
    KeyUp k -> setPad False k >> return ( False, True )
    _ -> return ( False, True )
  if l then processEvents else return q

mainLoop :: Emu ()
mainLoop = do
  q <- processEvents
  unless q (frame >> mainLoop)

frame :: Emu ()
frame = do
  fb <- gets frontBuffer
  bb <- gets backBuffer
  d <- use delayTime
  t1 <- liftIO time
  replicateM_ 16667 cpuStep
  liftIO $ do
    unlockSurface bb
    blitSurface bb Nothing fb Nothing
    SDL.flip fb
    lockSurface bb
    when (d > 0) (threadDelay d)
  t2 <- liftIO time
  let elapsed = t2 - t1
  let delayError = 1000000 `div` 60 - fromIntegral (elapsed `div` 1000)
  delayTime .= max 0 (d + delayError `div` 80)
  liftIO $ printf "\r%.2f FPS" ((1 :: Double) / (fromIntegral elapsed / 1e9))
  liftIO $ hFlush stdout
  vblank .= True

initState :: Assembly -> Surface -> Surface -> IO EmuState
initState Assembly { rom = rom, start = start } fb bb = do
  regs <- newArray (0x0, 0xf) 0
  mem <- newListArray (0x0000, 0xFFFF) (BS.unpack rom ++ replicate (0x10000 - BS.length rom) 0)
  ot <- genOps
  sd <- initSound
  prng <- getStdGen

  return EmuState
    { _pc = start
    , _sp = 0xFDF0
    , _flags = 0x0
    , _spriteFlip = ( False, False )
    , _spriteSize = ( 0, 0 )
    , _bgc = 0
    , _vblank = False
    , _palette = defaultPalette
    , sound = sd
    , _tone = Simple
    , frontBuffer = fb
    , backBuffer = bb
    , regs = regs
    , memory = mem
    , opTable = ot
    , _prng = prng
    , _delayTime = 8000
    }

cpuStep = {-# SCC "cpuStep" #-} do
  p <- use pc
  pc .= p + 4
  (oc : ib) <- forM [0..3] (\o -> load8 (Mem (p + o)))
  ot <- gets opTable
  i <- liftIO (readArray ot oc)
  case i of
    Nothing -> debug $ printf "<unimplemented %02x>" oc
    Just (Instruction { parser = p, exec = e, printer = pr }) -> do
      let as = p ib
--      liftIO $ putStrLn $ runIdentity $ pr as
      e as

defaultPalette = map toColor (
  [ 0x000000 -- (Black, Transparent in foreground layer)
  , 0x000000 -- (Black)
  , 0x888888 -- (Gray)
  , 0xBF3932 -- (Red)
  , 0xDE7AAE -- (Pink)
  , 0x4C3D21 -- (Dark brown)
  , 0x905F25 -- (Brown)
  , 0xE49452 -- (Orange)
  , 0xEAD979 -- (Yellow)
  , 0x537A3B -- (Green)
  , 0xABD54A -- (Light green)
  , 0x252E38 -- (Dark blue)
  , 0x00467F -- (Blue)
  , 0x68ABCC -- (Light blue)
  , 0xBCDEE4 -- (Sky blue)
  , 0xFFFFFF -- (White)
  ] :: [ Word32 ]) where
    toColor x = Color (byte 2 x) (byte 1 x) (byte 0 x)


text:
<?php

namespace Jordo\ProjectBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Jordo\ProjectBundle\Entity\Document
 *
 * @ORM\Table(name="project_document")
 * @ORM\Entity
 */
class Document
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime $dateCreated
     *
     * @ORM\Column(name="date_created", type="datetime")
     */
    private $dateCreated;

    /**
     * @ORM\ManyToOne(targetEntity="\Jordo\UserBundle\Entity\User", inversedBy="user")
     */
    protected $user;

    /**
     * @ORM\ManyToOne(targetEntity="\Jordo\ProjectBundle\Entity\DocumentType", inversedBy="doc")
     */
    protected $doctype;

    /**
     * @ORM\ManyToOne(targetEntity="\Jordo\DocumentBundle\Entity\Document", inversedBy="document")
     */
    protected $document;

    /**
     * @ORM\ManyToOne(targetEntity="\Jordo\ProjectBundle\Entity\Project", inversedBy="documents")
     */
    protected $project;

    public function __construct()
    {
        $this->dateCreated = $this->dateCreated ?: new \DateTime();
    }

    public function __toString()
    {
        return (string) $this->getDocument()->getTitle();
    }

    public function getState()
    {
        /*//$list = array('ok', 'progress', 'warning', 'error');

        foreach( $this->getComments() as $comment )
            if( $comment->getState() )
                return $comment->getState();

        return null;*/
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set dateCreated
     *
     * @param \DateTime $dateCreated
     * @return Document
     */
    public function setDateCreated($dateCreated)
    {
        $this->dateCreated = $dateCreated;

        return $this;
    }

    /**
     * Get dateCreated
     *
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->dateCreated;
    }

    /**
     * Set user
     *
     * @param Jordo\UserBundle\Entity\User $user
     * @return Document
     */
    public function setUser(\Jordo\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return Jordo\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set doctype
     *
     * @param Jordo\ProjectBundle\Entity\DocumentType $doctype
     * @return Document
     */
    public function setDoctype(\Jordo\ProjectBundle\Entity\DocumentType $doctype = null)
    {
        $this->doctype = $doctype;

        return $this;
    }

    /**
     * Get doctype
     *
     * @return Jordo\ProjectBundle\Entity\DocumentType
     */
    public function getDoctype()
    {
        return $this->doctype;
    }

    /**
     * Set project
     *
     * @param Jordo\ProjectBundle\Entity\Project $project
     * @return Document
     */
    public function setProject(\Jordo\ProjectBundle\Entity\Project $project = null)
    {
        $this->project = $project;

        return $this;
    }

    /**
     * Get project
     *
     * @return Jordo\ProjectBundle\Entity\Project
     */
    public function getProject()
    {
        return $this->project;
    }

    /**
     * Set document
     *
     * @param Jordo\DocumentBundle\Entity\Document $document
     * @return Document
     */
    public function setDocument(\Jordo\DocumentBundle\Entity\Document $document = null)
    {
        $this->document = $document;

        return $this;
    }

    /**
     * Get document
     *
     * @return Jordo\DocumentBundle\Entity\Document
     */
    public function getDocument()
    {
        return $this->document;
    }
}

redpajama_set_name: RedPajamaGithub


text:
.class public Lcom/htc/weather/animations/Anim03;
.super Lcom/htc/weather/animations/WeatherAnimationData;
.source "Anim03.java"

# instance fields
.field private cloud01:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

.field private cloud03:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

.field private sun:Lcom/htc/weather/animations/Sun;

# direct methods
.method public constructor <init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;)V
    .locals 2
    .parameter "context"
    .parameter "env"

    .prologue
    .line 24
    invoke-direct {p0, p1, p2}, Lcom/htc/weather/animations/WeatherAnimationData;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;)V

    .line 47
    new-instance v0, Lcom/htc/weather/animations/Anim03$1;

    invoke-direct {v0, p0}, Lcom/htc/weather/animations/Anim03$1;-><init>(Lcom/htc/weather/animations/Anim03;)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim03;->cloud03:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 152
    new-instance v0, Lcom/htc/weather/animations/Anim03$2;

    invoke-direct {v0, p0}, Lcom/htc/weather/animations/Anim03$2;-><init>(Lcom/htc/weather/animations/Anim03;)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim03;->cloud01:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 25
    new-instance v0, Lcom/htc/weather/animations/Sun;

    iget-object v1, p0, Lcom/htc/weather/animations/WeatherAnimationData;->mContext:Landroid/content/Context;

    invoke-direct {v0, v1, p2}, Lcom/htc/weather/animations/Sun;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim03;->sun:Lcom/htc/weather/animations/Sun;

    .line 26
    return-void
.end method

# virtual methods
.method public getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    .locals 5

    .prologue
    .line 34
    iget-object v3, p0, Lcom/htc/weather/animations/Anim03;->sun:Lcom/htc/weather/animations/Sun;

    invoke-virtual {v3}, Lcom/htc/weather/animations/Sun;->getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    move-result-object v2

    .line 35
    .local v2, sunSets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    array-length v3, v2

    add-int/lit8 v3, v3, 0x2

    new-array v1, v3, [Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 36
    .local v1, sets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    const/4 v0, 0x0

    .line 37
    .local v0, i:I
    const/4 v0, 0x0

    :goto_0
    array-length v3, v2

    if-ge v0, v3, :cond_0

    .line 38
    aget-object v3, v2, v0

    aput-object v3, v1, v0

    .line 37
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 40
    :cond_0
    iget-object v3, p0, Lcom/htc/weather/animations/Anim03;->cloud03:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    aput-object v3, v1, v0

    .line 41
    add-int/lit8 v3, v0, 0x1

    iget-object v4, p0, Lcom/htc/weather/animations/Anim03;->cloud01:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    aput-object v4, v1, v3

    .line 42
    return-object v1
.end method


text:
CREATE TABLE `oligo_probe` (
  `oligo_probe_id` int(11) NOT NULL auto_increment,
  `oligo_array_id` int(11) NOT NULL default '0',
  `probeset` varchar(40) collate latin1_bin default NULL,
  `name` varchar(20) collate latin1_bin default NULL,
  `description` text collate latin1_bin default NULL,
  `length` smallint(5) NOT NULL default '0',
  PRIMARY KEY  (`oligo_probe_id`,`oligo_array_id`),
  KEY `probeset_idx` (`probeset`),
  KEY `array_idx` (`oligo_array_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_bin;


text:
<!DOCTYPE HTML>

	<meta charset="UTF-8">
	<link rel="stylesheet" class="mediaquerydependent"
	      href="standard.css"
	      data-media="screen and (min-width: 600px)" data-href="green.css">
	<link rel="stylesheet" class="mediaquerydependent"
	      data-media="screen and (min-width: 4000px)" data-href="blue.css">
	<title></title>

This document has a light green background - when your browser is more than 600 pixels wide it gets a green background and you'll see an image below. Browsers over 4000 pixels wide have a blue background. Neither the CSS nor the image will be loaded in browsers less than 600 pixels wide.


text:
#region Apache Licensed

#endregion

namespace Demo
{
    /// <summary>
    /// <code>
    ///
    ///
    /// </code>
    /// </summary>
    public class SampleTypeWithCodeWithEmptyLines
    {
    }
}


text:
const express = require('express');
const router = express.Router();

const authHelpers = require('../auth/_helpers');
const routeHelpers = require('./_helpers');
const productQueries = require('../db/queries/products');

router.get('/', (req, res, next) => {
  return productQueries.getAllProducts()
  .then((products) => {
    const renderObject = {
      title: 'all products',
      user: req.user,
      messages: req.flash('messages'),
      products: products
    };
    res.render('products.html', renderObject);
  })
  .catch((err) => {
    return next(err);
  });
});

router.get('/:id', (req, res, next) => {
  const productID = parseInt(req.params.id);
  return productQueries.getSingleProduct(productID)
  .then((product) => {
    const renderObject = {
      title: product.name,
      user: req.user,
      messages: req.flash('messages'),
      product: product
    };
    res.render('product.html', renderObject);
  })
  .catch((err) => {
    return next(err);
  });
});

router.get('/:id/charge', authHelpers.loginRequired, (req, res, next) => {
  const productID = parseInt(req.params.id);
  return productQueries.getSingleProduct(productID)
  .then((product) => {
    const renderObject = {
      title: `buy ${product.name}`,
      user: req.user,
      messages: req.flash('messages'),
      product: product
    };
    res.render('charge.html', renderObject);
  })
  .catch((err) => {
    return next(err);
  });
});

router.post('/:id/stripe', authHelpers.loginRequired, (req, res, next) => {
  const stripeToken = req.body.stripeToken;
  const productID = parseInt(req.body.productID);
  const productAmount = req.body.productAmount;
  const userID = parseInt(req.user.id);
  // validate product
  return routeHelpers.validateProduct(productID, productAmount)
  .then((product) => {
    // create charge
    const charge = {
      amount: productAmount * 100,
      currency: product.currency,
      card: stripeToken
    };
    return routeHelpers.createCharge(charge, productID, userID);
  })
  .then(() => {
    req.flash('messages', {
      status: 'success',
      value: `Thanks for purchasing a ${req.body.productName}!`
    });
    res.redirect('/products');
  })
  .catch((err) => {
    return next(err);
  });
});

router.post('/', authHelpers.adminRequired, (req, res, next) => {
  return productQueries.addProduct(req.body)
  .then((product) => {
    if (!product) { throw new Error('Something went wrong'); }
    req.flash('messages', {
      status: 'success',
      value: 'Product added!'
    });
    return res.redirect('/');
  })
  .catch((err) => { next(err); });
});

module.exports = router;


text:
/**
 * Clase que representa
 * el tipo de personalidad
 * en el front-end.
 */
export class Personalidad{
    nombre: string;
}


text:
namespace System.Drawing.Printing
{
    /// <summary>
    /// Specifies the standard paper sizes.
    /// </summary>
    public enum PaperKind
    {
        /// <summary>
        /// The paper size is defined by the user.
        /// </summary>
        Custom = 0,

        // I got this information from two places: MSDN's writeup of DEVMODE
        // (https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/ns-wingdi-_devicemodea),
        // and the raw C++ header file (wingdi.h).  Beyond that, your guess
        // is as good as mine as to what these members mean.

        /// <summary>
        /// Letter paper (8.5 in. by 11 in.).
        /// </summary>
        Letter = SafeNativeMethods.DMPAPER_LETTER,
        /// <summary>
        /// Legal paper (8.5 in. by 14 in.).
        /// </summary>
        Legal = SafeNativeMethods.DMPAPER_LEGAL,
        /// <summary>
        /// A4 paper (210 mm by 297 mm).
        /// </summary>
        A4 = SafeNativeMethods.DMPAPER_A4,
        /// <summary>
        /// C paper (17 in. by 22 in.).
        /// </summary>
        CSheet = SafeNativeMethods.DMPAPER_CSHEET,
        /// <summary>
        /// D paper (22 in. by 34 in.).
        /// </summary>
        DSheet = SafeNativeMethods.DMPAPER_DSHEET,
        /// <summary>
        /// E paper (34 in. by 44 in.).
        /// </summary>
        ESheet = SafeNativeMethods.DMPAPER_ESHEET,
        /// <summary>
        /// Letter small paper (8.5 in. by 11 in.).
        /// </summary>
        LetterSmall = SafeNativeMethods.DMPAPER_LETTERSMALL,
        /// <summary>
        /// Tabloid paper (11 in. by 17 in.).
        /// </summary>
        Tabloid = SafeNativeMethods.DMPAPER_TABLOID,
        /// <summary>
        /// Ledger paper (17 in. by 11 in.).
        /// </summary>
        Ledger = SafeNativeMethods.DMPAPER_LEDGER,
        /// <summary>
        /// Statement paper (5.5 in. by 8.5 in.).
        /// </summary>
        Statement = SafeNativeMethods.DMPAPER_STATEMENT,
        /// <summary>
        /// Executive paper (7.25 in. by 10.5 in.).
        /// </summary>
        Executive = SafeNativeMethods.DMPAPER_EXECUTIVE,
        /// <summary>
        /// A3 paper (297 mm by 420 mm).
        /// </summary>
        A3 = SafeNativeMethods.DMPAPER_A3,
        /// <summary>
        /// A4 small paper (210 mm by 297 mm).
        /// </summary>
        A4Small = SafeNativeMethods.DMPAPER_A4SMALL,
        /// <summary>
        /// A5 paper (148 mm by 210 mm).
        /// </summary>
        A5 = SafeNativeMethods.DMPAPER_A5,
        /// <summary>
        /// B4 paper (250 mm by 353 mm).
        /// </summary>
        B4 = SafeNativeMethods.DMPAPER_B4,
        /// <summary>
        /// B5 paper (176 mm by 250 mm).
        /// </summary>
        B5 = SafeNativeMethods.DMPAPER_B5,
        /// <summary>
        /// Folio paper (8.5 in. by 13 in.).
        /// </summary>
        Folio = SafeNativeMethods.DMPAPER_FOLIO,
        /// <summary>
        /// Quarto paper (215 mm by 275 mm).
        /// </summary>
        Quarto = SafeNativeMethods.DMPAPER_QUARTO,
        /// <summary>
        /// 10-by-14-inch paper.
        /// </summary>
        Standard10x14 = SafeNativeMethods.DMPAPER_10X14,
        /// <summary>
        /// 11-by-17-inch paper.
        /// </summary>
        Standard11x17 = SafeNativeMethods.DMPAPER_11X17,
        /// <summary>
        /// Note paper (8.5 in. by 11 in.).
        /// </summary>
        Note = SafeNativeMethods.DMPAPER_NOTE,
        /// <summary>
        /// #9 envelope (3.875 in. by 8.875 in.).
        /// </summary>
        Number9Envelope = SafeNativeMethods.DMPAPER_ENV_9,
        /// <summary>
        /// #10 envelope (4.125 in. by 9.5 in.).
        /// </summary>
        Number10Envelope = SafeNativeMethods.DMPAPER_ENV_10,
        /// <summary>
        /// #11 envelope (4.5 in. by 10.375 in.).
        /// </summary>
        Number11Envelope = SafeNativeMethods.DMPAPER_ENV_11,
        /// <summary>
        /// #12 envelope (4.75 in. by 11 in.).
        /// </summary>
        Number12Envelope = SafeNativeMethods.DMPAPER_ENV_12,
        /// <summary>
        /// #14 envelope (5 in. by 11.5 in.).
        /// </summary>
        Number14Envelope = SafeNativeMethods.DMPAPER_ENV_14,
        /// <summary>
        /// DL envelope (110 mm by 220 mm).
        /// </summary>
        DLEnvelope = SafeNativeMethods.DMPAPER_ENV_DL,
        /// <summary>
        /// C5 envelope (162 mm by 229 mm).
        /// </summary>
        C5Envelope = SafeNativeMethods.DMPAPER_ENV_C5,
        /// <summary>
        /// C3 envelope (324 mm by 458 mm).
        /// </summary>
        C3Envelope = SafeNativeMethods.DMPAPER_ENV_C3,
        /// <summary>
        /// C4 envelope (229 mm by 324 mm).
        /// </summary>
        C4Envelope = SafeNativeMethods.DMPAPER_ENV_C4,
        /// <summary>
        /// C6 envelope (114 mm by 162 mm).
        /// </summary>
        C6Envelope = SafeNativeMethods.DMPAPER_ENV_C6,
        /// <summary>
        /// C65 envelope (114 mm by 229 mm).
        /// </summary>
        C65Envelope = SafeNativeMethods.DMPAPER_ENV_C65,
        /// <summary>
        /// B4 envelope (250 mm by 353 mm).
        /// </summary>
        B4Envelope = SafeNativeMethods.DMPAPER_ENV_B4,
        /// <summary>
        /// B5 envelope (176 mm by 250 mm).
        /// </summary>
        B5Envelope = SafeNativeMethods.DMPAPER_ENV_B5,
        /// <summary>
        /// B6 envelope (176 mm by 125 mm).
        /// </summary>
        B6Envelope = SafeNativeMethods.DMPAPER_ENV_B6,
        /// <summary>
        /// Italy envelope (110 mm by 230 mm).
        /// </summary>
        ItalyEnvelope = SafeNativeMethods.DMPAPER_ENV_ITALY,
        /// <summary>
        /// Monarch envelope (3.875 in. by 7.5 in.).
        /// </summary>
        MonarchEnvelope = SafeNativeMethods.DMPAPER_ENV_MONARCH,
        /// <summary>
        /// 6 3/4 envelope (3.625 in. by 6.5 in.).
        /// </summary>
        PersonalEnvelope = SafeNativeMethods.DMPAPER_ENV_PERSONAL,
        /// <summary>
        /// US standard fanfold (14.875 in. by 11 in.).
        /// </summary>
        USStandardFanfold = SafeNativeMethods.DMPAPER_FANFOLD_US,
        /// <summary>
        /// German standard fanfold (8.5 in. by 12 in.).
        /// </summary>
        GermanStandardFanfold = SafeNativeMethods.DMPAPER_FANFOLD_STD_GERMAN,
        /// <summary>
        /// German legal fanfold (8.5 in. by 13 in.).
        /// </summary>
        GermanLegalFanfold = SafeNativeMethods.DMPAPER_FANFOLD_LGL_GERMAN,
        /// <summary>
        /// ISO B4 (250 mm by 353 mm).
        /// </summary>
        IsoB4 = SafeNativeMethods.DMPAPER_ISO_B4,
        /// <summary>
        /// Japanese postcard (100 mm by 148 mm).
        /// </summary>
        JapanesePostcard = SafeNativeMethods.DMPAPER_JAPANESE_POSTCARD,
        /// <summary>
        /// 9-by-11-inch paper.
        /// </summary>
        Standard9x11 = SafeNativeMethods.DMPAPER_9X11,
        /// <summary>
        /// 10-by-11-inch paper.
        /// </summary>
        Standard10x11 = SafeNativeMethods.DMPAPER_10X11,
        /// <summary>
        /// 15-by-11-inch paper.
        /// </summary>
        Standard15x11 = SafeNativeMethods.DMPAPER_15X11,
        /// <summary>
        /// Invite envelope (220 mm by 220 mm).
        /// </summary>
        InviteEnvelope = SafeNativeMethods.DMPAPER_ENV_INVITE,
        /// <summary>
        /// Letter extra paper (9.275 in. by 12 in.).
        /// This value is specific to the PostScript driver and is used only by Linotronic printers in order to conserve paper.
        /// </summary>
        LetterExtra = SafeNativeMethods.DMPAPER_LETTER_EXTRA,
        /// <summary>
        /// Legal extra paper (9.275 in. by 15 in.).
        /// This value is specific to the PostScript driver and is used only by Linotronic printers in order to conserve paper.
        /// </summary>
        LegalExtra = SafeNativeMethods.DMPAPER_LEGAL_EXTRA,
        /// <summary>
        /// Tabloid extra paper (11.69 in. by 18 in.).
        /// This value is specific to the PostScript driver and is used only by Linotronic printers in order to conserve paper.
        /// </summary>
        TabloidExtra = SafeNativeMethods.DMPAPER_TABLOID_EXTRA,
        /// <summary>
        /// A4 extra paper (236 mm by 322 mm).
        /// This value is specific to the PostScript driver and is used only by Linotronic printers in order to conserve paper.
        /// </summary>
        A4Extra = SafeNativeMethods.DMPAPER_A4_EXTRA,
        /// <summary>
        /// Letter transverse paper (8.275 in. by 11 in.).
        /// </summary>
        LetterTransverse = SafeNativeMethods.DMPAPER_LETTER_TRANSVERSE,
        /// <summary>
        /// A4 transverse paper (210 mm by 297 mm).
        /// </summary>
        A4Transverse = SafeNativeMethods.DMPAPER_A4_TRANSVERSE,
        /// <summary>
        /// Letter extra transverse paper (9.275 in. by 12 in.).
        /// </summary>
        LetterExtraTransverse = SafeNativeMethods.DMPAPER_LETTER_EXTRA_TRANSVERSE,
        /// <summary>
        /// SuperA/SuperA/A4 paper (227 mm by 356 mm).
        /// </summary>
        APlus = SafeNativeMethods.DMPAPER_A_PLUS,
        /// <summary>
        /// SuperB/SuperB/A3 paper (305 mm by 487 mm).
        /// </summary>
        BPlus = SafeNativeMethods.DMPAPER_B_PLUS,
        /// <summary>
        /// Letter plus paper (8.5 in. by 12.69 in.).
        /// </summary>
        LetterPlus = SafeNativeMethods.DMPAPER_LETTER_PLUS,
        /// <summary>
        /// A4 plus paper (210 mm by 330 mm).
        /// </summary>
        A4Plus = SafeNativeMethods.DMPAPER_A4_PLUS,
        /// <summary>
        /// A5 transverse paper (148 mm by 210 mm).
        /// </summary>
        A5Transverse = SafeNativeMethods.DMPAPER_A5_TRANSVERSE,
        /// <summary>
        /// JIS B5 transverse paper (182 mm by 257 mm).
        /// </summary>
        B5Transverse = SafeNativeMethods.DMPAPER_B5_TRANSVERSE,
        /// <summary>
        /// A3 extra paper (322 mm by 445 mm).
        /// </summary>
        A3Extra = SafeNativeMethods.DMPAPER_A3_EXTRA,
        /// <summary>
        /// A5 extra paper (174 mm by 235 mm).
        /// </summary>
        A5Extra = SafeNativeMethods.DMPAPER_A5_EXTRA,
        /// <summary>
        /// ISO B5 extra paper (201 mm by 276 mm).
        /// </summary>
        B5Extra = SafeNativeMethods.DMPAPER_B5_EXTRA,
        /// <summary>
        /// A2 paper (420 mm by 594 mm).
        /// </summary>
        A2 = SafeNativeMethods.DMPAPER_A2,
        /// <summary>
        /// A3 transverse paper (297 mm by 420 mm).
        /// </summary>
        A3Transverse = SafeNativeMethods.DMPAPER_A3_TRANSVERSE,
        /// <summary>
        /// A3 extra transverse paper (322 mm by 445 mm).
        /// </summary>
        A3ExtraTransverse = SafeNativeMethods.DMPAPER_A3_EXTRA_TRANSVERSE,
        /// <summary>
        /// Japanese double postcard (200 mm by 148mm).
        /// </summary>
        JapaneseDoublePostcard = SafeNativeMethods.DMPAPER_DBL_JAPANESE_POSTCARD,
        /// <summary>
        /// A6 paper (105 mm by 148 mm).
        /// </summary>
        A6 = SafeNativeMethods.DMPAPER_A6,
        /// <summary>
        /// Japanese Kaku #2 envelope.
        /// </summary>
        JapaneseEnvelopeKakuNumber2 = SafeNativeMethods.DMPAPER_JENV_KAKU2,
        /// <summary>
        /// Japanese Kaku #3 envelope.
        /// </summary>
        JapaneseEnvelopeKakuNumber3 = SafeNativeMethods.DMPAPER_JENV_KAKU3,
        /// <summary>
        /// Japanese Chou #3 envelope.
        /// </summary>
        JapaneseEnvelopeChouNumber3 = SafeNativeMethods.DMPAPER_JENV_CHOU3,
        /// <summary>
        /// Japanese Chou #4 envelope.
        /// </summary>
        JapaneseEnvelopeChouNumber4 = SafeNativeMethods.DMPAPER_JENV_CHOU4,
        /// <summary>
        /// Letter rotated paper (11 in. by 8.5 in.).
        /// </summary>
        LetterRotated = SafeNativeMethods.DMPAPER_LETTER_ROTATED,
        /// <summary>
        /// A3 rotated paper (420mm by 297 mm).
        /// </summary>
        A3Rotated = SafeNativeMethods.DMPAPER_A3_ROTATED,
        /// <summary>
        /// A4 rotated paper (297 mm by 210 mm).
        /// </summary>
        A4Rotated = SafeNativeMethods.DMPAPER_A4_ROTATED,
        /// <summary>
        /// A5 rotated paper (210 mm by 148 mm).
        /// </summary>
        A5Rotated = SafeNativeMethods.DMPAPER_A5_ROTATED,
        /// <summary>
        /// JIS B4 rotated paper (364 mm by 257 mm).
        /// </summary>
        B4JisRotated = SafeNativeMethods.DMPAPER_B4_JIS_ROTATED,
        /// <summary>
        /// JIS B5 rotated paper (257 mm by 182 mm).
        /// </summary>
        B5JisRotated = SafeNativeMethods.DMPAPER_B5_JIS_ROTATED,
        /// <summary>
        /// Japanese rotated postcard (148 mm by 100 mm).
        /// </summary>
        JapanesePostcardRotated = SafeNativeMethods.DMPAPER_JAPANESE_POSTCARD_ROTATED,
        /// <summary>
        /// Japanese rotated double postcard (148 mm by 200 mm).
        /// </summary>
        JapaneseDoublePostcardRotated = SafeNativeMethods.DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED,
        /// <summary>
        /// A6 rotated paper (148 mm by 105 mm).
        /// </summary>
        A6Rotated = SafeNativeMethods.DMPAPER_A6_ROTATED,
        /// <summary>
        /// Japanese rotated Kaku #2 envelope.
        /// </summary>
        JapaneseEnvelopeKakuNumber2Rotated = SafeNativeMethods.DMPAPER_JENV_KAKU2_ROTATED,
        /// <summary>
        /// Japanese rotated Kaku #3 envelope.
        /// </summary>
        JapaneseEnvelopeKakuNumber3Rotated = SafeNativeMethods.DMPAPER_JENV_KAKU3_ROTATED,
        /// <summary>
        /// Japanese rotated Chou #3 envelope.
        /// </summary>
        JapaneseEnvelopeChouNumber3Rotated = SafeNativeMethods.DMPAPER_JENV_CHOU3_ROTATED,
        /// <summary>
        /// Japanese rotated Chou #4 envelope.
        /// </summary>
        JapaneseEnvelopeChouNumber4Rotated = SafeNativeMethods.DMPAPER_JENV_CHOU4_ROTATED,
        /// <summary>
        /// JIS B6 paper (128 mm by 182 mm).
        /// </summary>
        B6Jis = SafeNativeMethods.DMPAPER_B6_JIS,
        /// <summary>
        /// JIS B6 rotated paper (182 mm by 128 mm).
        /// </summary>
        B6JisRotated = SafeNativeMethods.DMPAPER_B6_JIS_ROTATED,
        /// <summary>
        /// 12-by-11-inch paper.
        /// </summary>
        Standard12x11 = SafeNativeMethods.DMPAPER_12X11,
        /// <summary>
        /// Japanese You #4 envelope.
        /// </summary>
        JapaneseEnvelopeYouNumber4 = SafeNativeMethods.DMPAPER_JENV_YOU4,
        /// <summary>
        /// Japanese You #4 rotated envelope.
        /// </summary>
        JapaneseEnvelopeYouNumber4Rotated = SafeNativeMethods.DMPAPER_JENV_YOU4_ROTATED,
        /// <summary>
        /// PRC 16K paper (146 mm by 215 mm).
        /// </summary>
        Prc16K = SafeNativeMethods.DMPAPER_P16K,
        /// <summary>
        /// PRC 32K paper (97 mm by 151 mm).
        /// </summary>
        Prc32K = SafeNativeMethods.DMPAPER_P32K,
        /// <summary>
        /// PRC 32K big paper (97 mm by 151 mm).
        /// </summary>
        Prc32KBig = SafeNativeMethods.DMPAPER_P32KBIG,
        /// <summary>
        /// PRC #1 envelope (102 mm by 165 mm).
        /// </summary>
        PrcEnvelopeNumber1 = SafeNativeMethods.DMPAPER_PENV_1,
        /// <summary>
        /// PRC #2 envelope (102 mm by 176 mm).
        /// </summary>
        PrcEnvelopeNumber2 = SafeNativeMethods.DMPAPER_PENV_2,
        /// <summary>
        /// PRC #3 envelope (125 mm by 176 mm).
        /// </summary>
        PrcEnvelopeNumber3 = SafeNativeMethods.DMPAPER_PENV_3,
        /// <summary>
        /// PRC #4 envelope (110 mm by 208 mm).
        /// </summary>
        PrcEnvelopeNumber4 = SafeNativeMethods.DMPAPER_PENV_4,
        /// <summary>
        /// PRC #5 envelope (110 mm by 220 mm).
        /// </summary>
        PrcEnvelopeNumber5 = SafeNativeMethods.DMPAPER_PENV_5,
        /// <summary>
        /// PRC #6 envelope (120 mm by 230 mm).
        /// </summary>
        PrcEnvelopeNumber6 = SafeNativeMethods.DMPAPER_PENV_6,
        /// <summary>
        /// PRC #7 envelope (160 mm by 230 mm).
        /// </summary>
        PrcEnvelopeNumber7 = SafeNativeMethods.DMPAPER_PENV_7,
        /// <summary>
        /// PRC #8 envelope (120 mm by 309 mm).
        /// </summary>
        PrcEnvelopeNumber8 = SafeNativeMethods.DMPAPER_PENV_8,
        /// <summary>
        /// PRC #9 envelope (229 mm by 324 mm).
        /// </summary>
        PrcEnvelopeNumber9 = SafeNativeMethods.DMPAPER_PENV_9,
        /// <summary>
        /// PRC #10 envelope (324 mm by 458 mm).
        /// </summary>
        PrcEnvelopeNumber10 = SafeNativeMethods.DMPAPER_PENV_10,
        /// <summary>
        /// PRC 16K rotated paper (146 mm by 215 mm).
        /// </summary>
        Prc16KRotated = SafeNativeMethods.DMPAPER_P16K_ROTATED,
        /// <summary>
        /// PRC 32K rotated paper (97 mm by 151 mm).
        /// </summary>
        Prc32KRotated = SafeNativeMethods.DMPAPER_P32K_ROTATED,
        /// <summary>
        /// PRC 32K big rotated paper (97 mm by 151 mm).
        /// </summary>
        Prc32KBigRotated = SafeNativeMethods.DMPAPER_P32KBIG_ROTATED,
        /// <summary>
        /// PRC #1 rotated envelope (165 mm by 102 mm).
        /// </summary>
        PrcEnvelopeNumber1Rotated = SafeNativeMethods.DMPAPER_PENV_1_ROTATED,
        /// <summary>
        /// PRC #2 rotated envelope (176 mm by 102 mm).
        /// </summary>
        PrcEnvelopeNumber2Rotated = SafeNativeMethods.DMPAPER_PENV_2_ROTATED,
        /// <summary>
        /// PRC #3 rotated envelope (176 mm by 125 mm).
        /// </summary>
        PrcEnvelopeNumber3Rotated = SafeNativeMethods.DMPAPER_PENV_3_ROTATED,
        /// <summary>
        /// PRC #4 rotated envelope (208 mm by 110 mm).
        /// </summary>
        PrcEnvelopeNumber4Rotated = SafeNativeMethods.DMPAPER_PENV_4_ROTATED,
        /// <summary>
        /// PRC #5 rotated envelope (220 mm by 110 mm).
        /// </summary>
        PrcEnvelopeNumber5Rotated = SafeNativeMethods.DMPAPER_PENV_5_ROTATED,
        /// <summary>
        /// PRC #6 rotated envelope (230 mm by 120 mm).
        /// </summary>
        PrcEnvelopeNumber6Rotated = SafeNativeMethods.DMPAPER_PENV_6_ROTATED,
        /// <summary>
        /// PRC #7 rotated envelope (230 mm by 160 mm).
        /// </summary>
        PrcEnvelopeNumber7Rotated = SafeNativeMethods.DMPAPER_PENV_7_ROTATED,
        /// <summary>
        /// PRC #8 rotated envelope (309 mm by 120 mm).
        /// </summary>
        PrcEnvelopeNumber8Rotated = SafeNativeMethods.DMPAPER_PENV_8_ROTATED,
        /// <summary>
        /// PRC #9 rotated envelope (324 mm by 229 mm).
        /// </summary>
        PrcEnvelopeNumber9Rotated = SafeNativeMethods.DMPAPER_PENV_9_ROTATED,
        /// <summary>
        /// PRC #10 rotated envelope (458 mm by 324 mm).
        /// </summary>
        PrcEnvelopeNumber10Rotated = SafeNativeMethods.DMPAPER_PENV_10_ROTATED,
    }
}


text:
function Test-Windows {
    <#
        .SYNOPSIS
            Internal tool, used to detect non-Windows platforms

        .DESCRIPTION
            Some things don't work with Windows, this is an easy way to detect

        .EXAMPLE
            if (-not (Test-Windows)) { return }

            The calling function will stop if this function returns true.
    #>
    [CmdletBinding()]
    param (
        [switch]$NoWarn
    )

    if (($PSVersionTable.Keys -contains "Platform") -and $psversiontable.Platform -ne "Win32NT") {
        if (-not $NoWarn) {
            Write-Message -Level Warning -Message "This command is not supported on non-Windows platforms :("
        }
        return $false
    }

    return $true
}


text:
@implementation NSObject (BlurImageView)

//模糊效果
+(UIImageView*)getBlurImageViewWithImage:(UIImage*)image withRect:(CGRect)rect{

    //Background view
    UIImageView *backImageView = [[UIImageView alloc] init];
    backImageView.image = image;
    //模糊渲染
    UIVisualEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    //模糊View
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    visualEffectView.frame = rect;
    visualEffectView.alpha = 1;
    [backImageView addSubview:visualEffectView];
    return backImageView;
}

@end


text:
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse

from common.templates import render_template

def list(request):
    # TODO: implement
    pass

def register(request):
    if 'username' in request.POST:
        User.objects.create_user(request.POST['username'], request.POST['email'],
                                 request.POST['password'])
        template_name = 'users/success.tpl'
        context = {'mode': 'register'}
    else:
        template_name = 'users/register.tpl'
        context = {}
    return HttpResponse(render_template(template_name, request, context))

def connect(request):
    if 'username' in request.POST:
        user = authenticate(username=request.POST['username'],
                            password=request.POST['password'])
        if user is not None:
            if user.is_active:
                login(request, user)
                template_name = 'users/success.tpl'
                context = {'mode': 'connect'}
            else:
                template_name = 'users/fail.tpl'
                context = {'mode': 'connect', 'why': 'disabled'}
        else:
            template_name = 'users/fail.tpl'
            context = {'mode': 'connect', 'why': 'incorrect'}
    else:
        template_name = 'users/connect.tpl'
        context = {}
    return HttpResponse(render_template(template_name, request, context))

def disconnect(request):
    logout(request)
    template_name = 'users/success.tpl'
    context = {'mode': 'disconnect'}
    return HttpResponse(render_template(template_name, request, context))

def profile(request, username):
    # TODO: implement
    pass


text:
@interface ConnectUtil : NSObject

+ (NSString *) urlEncode:(NSString *)input;
+ (NSString *) urlDecode:(NSString *)input;
+ (NSString *) escapedUnicodeForString:(NSString *)input;

+ (NSString *) entityEncode:(NSString *)input
__deprecated_msg("use proper XML libraries instead");
+ (NSString *) entityDecode:(NSString *)input
__deprecated_msg("use proper XML libraries instead");

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<schema
  xmlns="http://www.concrete5.org/doctrine-xml/0.5"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.concrete5.org/doctrine-xml/0.5 http://concrete5.github.io/doctrine-xml/doctrine-xml-0.5.xsd">

  <table name="btYouTube">
    <field name="bID" type="integer">
      <unsigned/>
      <key/>
    </field>
    <field name="title" type="string" size="255"/>
    <field name="videoURL" type="string" size="255"/>
    <field name="vHeight" type="string" size="255"/>
    <field name="vWidth" type="string" size="255"/>
    <field name="sizing" type="string" size="10"/>
    <field name="autoplay" type="boolean">
      <default value="0"/>
      <notnull/>
    </field>
    <field name="color" type="string" size="10"/>
    <field name="controls" type="integer">
      <unsigned/>
    </field>
    <field name="iv_load_policy" type="integer">
      <unsigned/>
    </field>
    <field name="loopEnd" type="boolean">
      <default value="0"/>
      <notnull/>
    </field>
    <field name="modestbranding" type="boolean">
      <default value="0"/>
      <notnull/>
    </field>
    <field name="rel" type="boolean">
      <default value="0"/>
      <notnull/>
    </field>
    <field name="showinfo" type="boolean">
      <default value="0"/>
      <notnull/>
    </field>
  </table>
</schema>


text:
module Fog
  module Identity
    class OpenStack
      class V3
        class Real
          def update_user(id, user)
            request(
                :expects => [200],
                :method => 'PATCH',
                :path => "users/#{id}",
                :body => Fog::JSON.encode(:user => user)
            )
          end
        end

        class Mock
        end
      end
    end
  end
end


text:
Connectez vous avec votre compte de google

Ou avec votre compte

		<form data-ng-submit="signin()" class="signin form-horizontal" autocomplete="off">
			<fieldset>

					Username
					<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">

					Mot de passe
					<input type="password" id="password" name="password" class="form-control"
						   data-ng-model="credentials.password" placeholder="Mot de passe">

					<button type="submit" class="btn btn-primary">Se connecter</button>
					  or
					S'inscrire

					Mot de passe oublié?

			</fieldset>
		</form>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package CRUD.Usuario;

import com.psw.conexao.HibernateUtil;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Juliano
 */
public class UsuarioController {

    public static boolean ListarADM(){
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();

        Criteria query = sessao.createCriteria(Usuario.class);
        List userbusca = query.list();
        transacao.commit();
        Iterator iterador = userbusca.iterator();
        System.out.println("3");
        while (iterador.hasNext()){
            Usuario user = (Usuario) iterador.next();
            String permissoes = user.getPermissoes();
            String[] permlist = permissoes.split(" ");
            if (permlist[3].equals("1")){
                return false;
            }
        }
        return true;
    }

    public static Usuario consultarUsuarioLogin(String login){
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();

        Criteria query = sessao.createCriteria(Usuario.class);
        query.add(Restrictions.eq("login", login));
        Usuario userbusca = (Usuario) query.uniqueResult();
        transacao.commit();
        if (userbusca != null){
            return userbusca;
        }
        return null;
    }

    public static List consultarUsuarioCPF(String cpf){
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();

        Criteria query = sessao.createCriteria(Usuario.class);
        query.add(Restrictions.eq("cpf", cpf));
        List lista = query.list();
        transacao.commit();
        if (lista != null){
            return lista;
        }
        JOptionPane.showMessageDialog(null, "Usuario não encontrado!");
        return null;
    }

    public static void CadastrarUsuario(Usuario user){
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();
        try{
            sessao.save(user);
            transacao.commit();
        } catch (HibernateException e) {
            System.out.println("Não foi possível inserir o contato. Erro: " + e.getMessage());
        } finally {
            try {
                sessao.close();
            } catch (Throwable e) {
                System.out.println("Erro ao fechar operação de inserção, Mensagem: " + e.getMessage());
            }
        }
        JOptionPane.showMessageDialog(null, "Usuario cadastrado com sucesso!");
    }

    public static boolean updateUsuario(Usuario user){

        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();
        try{
            sessao.update(user);
            transacao.commit();
        } catch (HibernateException e) {
            System.out.println("Não foi possível atualizar o contato. Erro: " + e.getMessage());
            return false;
        } finally {
            try {
                sessao.close();
            } catch (Throwable e) {

                System.out.println("Erro ao fechar operação de atualização, Mensagem: " + e.getMessage());
                return false;
            }
        }

        JOptionPane.showMessageDialog(null, "Usuario alterado com sucesso!");
        return true;

    }

    public static boolean deleteUsuario(Usuario user){

        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();
        try{
            sessao.delete(user);
            transacao.commit();
        } catch (HibernateException e) {
            System.out.println("Não foi possível remover o contato. Erro: " + e.getMessage());
            return false;
        } finally {
            try {
                sessao.close();
            } catch (Throwable e) {

                System.out.println("Erro ao fechar operação de remoção, Mensagem: " + e.getMessage());
                return false;
            }
        }

        JOptionPane.showMessageDialog(null, "Usuario removido com sucesso!");
        return true;

    }
}


text:
using System.Diagnostics;

namespace System.Collections.Generic
{
    // LargeArrayBuilder.netcoreapp.cs provides a "LargeArrayBuilder" that's meant to help
    // avoid allocations and copying while building up an array.  But in doing so, it utilizes
    // T[][] to store T[]s, which results in significant size increases for AOT builds. To
    // address that, this minimal wrapper for ArrayBuilder<T> may be used instead; it's a simple
    // passthrough to ArrayBuilder<T>, and thus doesn't incur the size increase due to the T[][]s.

    internal struct LargeArrayBuilder<T>
    {
        private ArrayBuilder<T> _builder; // mutable struct; do not make this readonly

        public LargeArrayBuilder(bool initialize) : this()
        {
            // This is a workaround for C# not having parameterless struct constructors yet.
            // Once it gets them, replace this with a parameterless constructor.
            Debug.Assert(initialize);
        }

        public int Count => _builder.Count;

        public void Add(T item) => _builder.Add(item);

        public void AddRange(IEnumerable<T> items)
        {
            Debug.Assert(items != null);
            foreach (T item in items)
            {
                _builder.Add(item);
            }
        }

        public void SlowAdd(T item) => _builder.Add(item);

        public T[] ToArray() => _builder.ToArray();

        public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count)
        {
            Array.Copy(_builder.Buffer!, position.Column, array, arrayIndex, count);
            return new CopyPosition(0, position.Column + count);
        }
    }
}


text:
package edu.wustl.xipApplication.aim;

import gme.cacore_cacore._3_2.edu_northwestern_radiology.DICOMImageReference;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.Image;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.ImageAnnotation;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.ImageReference;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.ImagingObservation;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.Series;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.Study;
import gme.cacore_cacore._3_2.edu_northwestern_radiology.Annotation.User;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @author Jaroslaw Krych
 *
 */
public class AimParser implements Runnable{
	JAXBContext jc;
	Unmarshaller u;
	Marshaller marshaller;
	File aimFile;
	public AimParser(File aimFile){
		try {
			jc = JAXBContext.newInstance( "gme.cacore_cacore._3_2.edu_northwestern_radiology" );
			u = jc.createUnmarshaller();
			marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		this.aimFile = aimFile;
	}

	public void run() {
		unmarshall(aimFile);
		notifyAimParsed();
	}

	String tumorID;
	String tumorName;
	String raterID;
	String raterName;
	List<String> aimDesc;
	String refSOPInstanceUID;
	String xmlString;
	public void unmarshall(File aimXmlFile){
		aimDesc = new ArrayList<String>();
		try {
			JAXBElement<?> obj = (JAXBElement<?>)u.unmarshal(aimXmlFile);
			ImageAnnotation imageAnnotation = ((ImageAnnotation)obj.getValue());
			tumorID = String.valueOf(imageAnnotation.getId());
			tumorName = imageAnnotation.getName();
			User rater = imageAnnotation.getUser();
			raterID = String.valueOf(rater.getUser().getId());
			raterName = rater.getUser().getName();

			//AIM INFO
			String imageAnnotationType = imageAnnotation.getCodeMeaning();
			aimDesc.add(imageAnnotationType + " " + getTumorName());
			aimDesc.add("Author " + raterName);
			String anatomicRegion = imageAnnotation.getAnatomicEntityCollection().getAnatomicEntity().get(0).getCodeMeaning();
			aimDesc.add("Anatomic Region " + anatomicRegion);
			String calcType = imageAnnotation.getCalculationCollection().getCalculation().get(0).getCodeMeaning();
			double calcTypeValue = imageAnnotation.getCalculationCollection().getCalculation().get(0).getCalculationResultCollection().getCalculationResult().get(0).getDataCollection().getData().get(0).getValue();
			aimDesc.add(calcType + " " + String.valueOf(calcTypeValue));
			List<ImagingObservation> imagingObservationColl = imageAnnotation.getImagingObservationCollection().getImagingObservation();
			for(int i = 0; i < imagingObservationColl.size(); i++){
				ImagingObservation imagingObservation = imagingObservationColl.get(i);
				String str1 = imagingObservation.getCodeMeaning();
				String str2 = imagingObservation.getImagingObservationCharacteristicCollection().getImagingObservationCharacteristic().get(0).getCodeMeaning();
				aimDesc.add(str1 + ": " + str2);
			}
			ImageReference imageReference = imageAnnotation.getImageReferenceCollection().getImageReference().get(0);
			DICOMImageReference ref = (DICOMImageReference) imageReference;
        	Study study = ref.getStudy().getStudy();
        	Series series = study.getSeries().getSeries();
        	Image image = series.getImageCollection().getImage().get(0);
        	refSOPInstanceUID = image.getSopInstanceUID();

        	StringWriter sw = new StringWriter();
			marshaller.marshal(obj, sw);
			xmlString = sw.toString();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getTumorID(){
		return tumorID;
	}
	public String getTumorName(){
		return tumorName;
	}
	public String getRaterID(){
		return raterID;
	}
	public String getRaterName(){
		return raterName;
	}
	public List<String> getAIMDescription(){
		return aimDesc;
	}
	public String getRefSOPInstanceUID(){
		return refSOPInstanceUID;
	}
	public File getAIMFile(){
		return aimFile;
	}
	public String getXMLString(){
		return xmlString;
	}

	AimParseListener listener;
    public void addAimParseListener(AimParseListener l) {
        listener = l;
    }
	void notifyAimParsed(){
		AimParseEvent event = new AimParseEvent(this);
        listener.parsedAimAvailable(event);
	}

	public static void main (String[] atgs){
		File file = new File("C:/OurDocuments/WashUConsulting/Project/AIM/Sample_AIMAnnotations_TCGA_09302009/AIMAnnotations/Baseline/0022BaselineA.xml");
		AimParser aimParser = new AimParser(file);
		aimParser.run();
		List<String> desc = aimParser.getAIMDescription();
		for(int i = 0; i < desc.size(); i++){
			System.out.println(desc.get(i));
		}
		System.out.println("-----------------");
		System.out.println(aimParser.getXMLString());

	}

}


text:
layout: redirect
permalink: /data/bq/quickstart/
title: "BigQuery Quick Start"
page-title: "BigQuery Quick Start"
redirect_to: "https://measurementlab.net/data/docs/bq/quickstart/"
---


text:
	\pretextual

\imprimircapa

\imprimirfolhaderosto*

\imprimirFolhaAprovacao

%Lista de figuras
\pdfbookmark[0]{\listfigurename}{lof}
\listoffigures*
\cleardoublepage

%Lista de tabelas
\pdfbookmark[0]{\listtablename}{lot}
\listoftables*
\cleardoublepage

\input{./siglas.tex} %Lista de siglas

%Sumário
\pdfbookmark[0]{\contentsname}{toc}
\tableofcontents*
\cleardoublepage

\textual


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualScriptIndexGet" inherits="VisualScriptNode" version="4.0">
	<brief_description>
		A Visual Script node for getting a value from an array or a dictionary.
	</brief_description>
	<description>
		[VisualScriptIndexGet] will return the value stored in an array or a dictionary under the given index.
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<constants>
	</constants>
</class>


text:
package jp.natsukishina.orm4j8;

class StringUtils {
	public static String join(Object[] array, String separator) {
		if (array == null) {
			return null;
		}
		return join(array, separator, 0, array.length);
	}

	public static String join(Object[] array, String separator, int startIndex, int endIndex) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = "";
		}
		int noOfItems = endIndex - startIndex;
		if (noOfItems <= 0) {
			return "";
		}
		StringBuilder buf = new StringBuilder(noOfItems * 16);
		for (int i = startIndex; i < endIndex; i++) {
			if (i > startIndex) {
				buf.append(separator);
			}
			if (array[i] != null) {
				buf.append(array[i]);
			}
		}
		return buf.toString();
	}
}


text:
require "pathname"
require "fileutils"
require "uri"
require "json"
require "digest"
require "strscan"

#Gems
require "addressable/uri"
require "naturalsorter"
require "rmagick"

module Mangos
end

require "mangos/decorated_pathname"
require "mangos/processor"
require "mangos/resort_pages_processor"
require "mangos/tag_breaker"
require "mangos/package"
require "mangos/update"
require "mangos/book"
require "mangos/pages_deflater"
require "mangos/pages_inflater"
require "mangos/thumbnailer"
require "mangos/book_updater"


text:
"""Classes pertaining to users and authorization for Roster.

Authorization for specific functions and for specific domain/ip range blocks
is handled in this module.
"""

__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'

import IPy

import constants
import errors
import helpers_lib

class User(object):
  """Representation of a user, with basic manipulation methods.
  Note that is it not necessary to authenticate a user to construct this
  class. This class is mainly responsible for authorization.
  """

  def __init__(self, user_name, db_instance, log_instance):
    """
    Inputs:
      user_name:	user's login
      db_instance:	dbAccess instance to use for user verification

    Raises:
      InvalidInputError: No such user.
    """
    self.user_name = user_name
    self.db_instance = db_instance
    self.log_instance = log_instance
    self.zone_origin_cache = {}

    # pull a pile of authentication info from the database here
    self.user_perms = self.db_instance.GetUserAuthorizationInfo(user_name)
    if( not self.user_perms.has_key('user_name') ):
      raise errors.InvalidInputError("No such user: %s" % user_name)

    # More DB crud
    self.groups = self.user_perms['groups']
    self.forward_zones = self.user_perms['forward_zones']
    self.reverse_ranges = self.user_perms['reverse_ranges']
    self.user_access_level = ual = self.user_perms['user_access_level']

    # Pull zone origins for cache
    self.db_instance.StartTransaction()
    try:
      all_zone_origins = self.db_instance.GetZoneOrigins(None, None)
      for zone in self.forward_zones:
        if( zone['zone_name'] in all_zone_origins ):
          self.zone_origin_cache[
              zone['zone_name']] = all_zone_origins[zone['zone_name']]
    finally:
      self.db_instance.EndTransaction()

    # Build a hash of methods, using the supported_method hash
    self.abilities = {}
    for method in constants.SUPPORTED_METHODS.keys():
      if( constants.SUPPORTED_METHODS[method]['access_level'] <= ual ):
        self.abilities[method] = constants.SUPPORTED_METHODS[method]

  def Authorize(self, method, record_data=None, current_transaction=False):
    """Check to see if the user is authorized to run the given operation.

    Inputs:
      method:	what the user's trying to do
      record_data: dictionary of target, zone_name, view_name, record_type,
                   and record_args_dict for the record that is being modified.
                   {'target': 'test_target',
                    'zone_name': 'test_zone',
                    'view_name': 'test_view',
                    'record_type': 'a',
                    'record_args_dict' : {
                        u'assignment_ip' : '192.168.1.1'
                     }
                   }
      current_transaction: bool of if this function is run from inside a
                           transaction in the db_access class

    Raises:
      MaintenanceError: Roster is currently under maintenance.
      MissingDataTypeError: Incomplete record data provided for access method.
      AuthorizationError: Authorization failure.
    """
    function_name, current_args = helpers_lib.GetFunctionNameAndArgs()

    if( not current_transaction ):
      self.db_instance.StartTransaction()
    try:
      maintenance_mode = self.db_instance.CheckMaintenanceFlag()
      if( record_data and record_data.has_key('zone_name') ):
        if( record_data['zone_name'] ):
          pulled_origin = self.db_instance.GetZoneOrigins(
              record_data['zone_name'], record_data['view_name'])

          #Making sure we pulled something that exists
          if( pulled_origin is not None ):
            self.zone_origin_cache[record_data['zone_name']] = pulled_origin[
                record_data['zone_name']]
          else:
            view_name = record_data['view_name']
            if( view_name.endswith('_dep') ):
              view_name = view_name[:-4] #Strip off '_dep'

            raise errors.UnexpectedDataError('Specified zone-view assignment '
                'does not exist for zone %s view %s' % (
                    record_data['zone_name'], view_name))
    finally:
      if( not current_transaction ):
        self.db_instance.EndTransaction()

    if( maintenance_mode and self.user_perms['user_access_level']
        != constants.ACCESS_LEVELS['dns_admin'] ):
      raise errors.MaintenanceError('Roster is currently under maintenance.')

    if( record_data is not None and record_data.has_key('zone_name') ):
      target_string = ' with %s on %s of type %s' % (record_data['target'],
                                          record_data['zone_name'],
                                          record_data['record_type'])

      user_group_perms = {}
      record_target = record_data['target']

      # Get user group permissions for record zone
      if( record_data['zone_name'] ):
        for origin in self.zone_origin_cache[record_data['zone_name']]:
          user_group_perms[origin] = []
          if( record_target == u'@' ):
            ip_address = helpers_lib.UnReverseIP(origin)
          else:
            ip_address = helpers_lib.UnReverseIP('%s.%s' % (
                record_target,
                origin))

          #Looking for permissions in the forward zones
          for zone in self.user_perms['forward_zones']:
            if( zone['zone_name'] == record_data['zone_name'] ):
              user_group_perms[origin].append(zone['group_permission'])

          #If we haven't found any, look in the reverse ranges
          if( user_group_perms[origin] == [] ):
            validation_instance = self.db_instance.data_validation_instance
            if( validation_instance.isIPv4IPAddress(ip_address) or
                validation_instance.isIPv6IPAddress(ip_address) ):
              for cidr in self.user_perms['reverse_ranges']:
                if( IPy.IP(cidr['cidr_block']).overlaps(ip_address) ):
                  user_group_perms[origin].append(cidr['group_permission'])
    else:
      target_string = ''
    auth_fail_string = ('User %s is not allowed to use %s%s' %
                        (self.user_name, method, target_string))

    #authorizing method
    if( self.abilities.has_key(method) ):
      method_hash = self.abilities[method]
      if( int(self.user_access_level) >= constants.ACCESS_LEVELS['dns_admin'] ):
        return

      if( method_hash['check'] ):
        # Secondary check - ensure the target is in a range delegated to
        # the user
        if( record_data is None ):
          raise errors.MissingDataTypeError(
              'No record data provided for access method '
              '%s' % method)
        elif( not record_data.has_key('zone_name') or
            record_data['zone_name'] is None or
            not record_data.has_key('view_name') or
            record_data['view_name'] is None or
            not record_data.has_key('target') or
            record_data['target'] is None or
            not record_data.has_key('record_type') or
            record_data['record_type'] is None or
            not record_data.has_key('record_args_dict') or
            record_data['record_args_dict'] is None ):
          raise errors.MissingDataTypeError(
              'Incomplete record data provided for access '
              'method %s' % method)
        # If user or less, check permission for zone origin
        elif( int(self.user_access_level) <= constants.ACCESS_LEVELS[
            'unlocked_user'] ):
          user_has_permission = False
          for origin in self.zone_origin_cache[record_data['zone_name']]:
            if( record_data['record_type'] in user_group_perms[origin] ):
              user_has_permission = True

          if( not user_has_permission ):
            raise errors.AuthorizationError(auth_fail_string)

        if( int(self.user_access_level) <
          constants.ACCESS_LEVELS['unlocked_user'] ):

          # if a or aaaa
          if( record_data['record_args_dict'].has_key(u'assignment_ip') ):
            ip = IPy.IP(record_data['record_args_dict'][u'assignment_ip'])
            for reverse_range in self.reverse_ranges:
              if( IPy.IP(reverse_range['cidr_block']).overlaps(ip) ):
                break
            else:
              raise errors.AuthorizationError(auth_fail_string)

          # if cname, mx, ns, or ptr
          elif( record_data['record_args_dict'].has_key(u'assignment_host') or
                record_data['record_args_dict'].has_key(u'mail_server') or
                record_data['record_args_dict'].has_key(u'name_server') ):
            hostname = None
            if( record_data['record_args_dict'].has_key(u'assignment_host') ):
              hostname = record_data['record_args_dict'][u'assignment_host']
            elif( record_data['record_args_dict'].has_key(u'mail_server') ):
              hostname = record_data['record_args_dict'][u'mail_server']
            elif( record_data['record_args_dict'].has_key(u'name_server') ):
              hostname = record_data['record_args_dict'][u'name_server']
            smallest_zone = hostname

            found = False
            while( smallest_zone ):
              for domain in self.zone_origin_cache:
                for origin in self.zone_origin_cache[domain]:
                  if( smallest_zone == origin ):
                    found = True
              if( not found ):
                try:
                  smallest_zone = smallest_zone.split('.', 1)[1]
                except IndexError:
                  break
              else:
                break
            if( not found ):
              raise errors.AuthorizationError(auth_fail_string)

            for zone in self.forward_zones:
              if( self.zone_origin_cache.has_key(zone['zone_name']) ):
                found = False
                for origin in self.zone_origin_cache[zone['zone_name']]:
                  if( smallest_zone == origin ):
                    found = True
                    break
                if( found ):
                  break
            else:
              raise errors.AuthorizationError(auth_fail_string)

        for forward_zone in self.forward_zones:
          if( record_data['zone_name'] == forward_zone['zone_name'] ):
            return

        # Can't find it in forward zones, maybe it's a reverse
        try:
          ip = IPy.IP(ip_address)

          # Good, we have an IP.  See if we hit any delegated ranges.
          for reverse_range in self.reverse_ranges:
            if( IPy.IP(reverse_range['cidr_block']).overlaps(ip) ):
              return

          # fail to find a matching IP range with appropriate perms
          self.log_instance.LogAction(self.user_name, function_name,
                                      current_args, False, current_transaction)
          raise errors.AuthorizationError(auth_fail_string)

        except ValueError:
          # fail to find a matching zone with appropriate perms
          self.log_instance.LogAction(self.user_name, function_name,
                                      current_args, False, current_transaction)
          raise errors.AuthorizationError(auth_fail_string)
      else:
        return
    else:
      # fail to find a matching method
      self.log_instance.LogAction(self.user_name, function_name,
                                  current_args, False, current_transaction)
      raise errors.AuthorizationError(auth_fail_string)

  def GetUserName(self):
    """Return user name for current session.

    Outputs:
      string: user name
    """
    return self.user_perms['user_name']

  def GetPermissions(self):
    """Return permissions and groups for user.

    Outputs:
      dictionary of permissions
        example:
        {'user_access_level': '2',
         'user_name': 'shuey',
         'forward_zones': [
             {'zone_name': 'cs.university.edu', 'group_permission': 'rw'},
             {'zone_name': 'eas.university.edu', 'group_permission': 'r'},
             {'zone_name': 'bio.university.edu', 'group_permission': 'rw'}],
         'groups': ['cs', 'bio'],
         'reverse_ranges': [
             {'cidr_block': '192.168.0.0/24',
              'group_permission': 'rw'},
             {'cidr_block': '192.168.0.0/24',
              'group_permission': 'r'},
             {'cidr_block': '192.168.1.0/24',
              'group_permission': 'rw'}]}
    """
    return self.user_perms

# vi: set ai aw sw=2:


text:
package io.atomix.catalyst.serializer.util;

import io.atomix.catalyst.buffer.BufferInput;
import io.atomix.catalyst.buffer.BufferOutput;
import io.atomix.catalyst.serializer.Serializer;
import io.atomix.catalyst.serializer.TypeSerializer;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * Big decimal serializer.
 *
 * @author Jordan Halterman
 */
public class BigDecimalSerializer implements TypeSerializer<BigDecimal> {

  @Override
  public void write(BigDecimal object, BufferOutput buffer, Serializer serializer) {
    byte[] bytes = object.toPlainString().getBytes(StandardCharsets.UTF_8);
    buffer.writeInt(bytes.length).write(bytes);
  }

  @Override
  public BigDecimal read(Class<BigDecimal> type, BufferInput buffer, Serializer serializer) {
    byte[] bytes = new byte[buffer.readInt()];
    buffer.read(bytes);
    return new BigDecimal(new String(bytes, StandardCharsets.UTF_8));
  }

}


text:
module PartyReportsHelper
end


text:
package org.apache.drill.exec.physical.impl.xsort;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.calcite.rel.RelFieldCollation.Direction;
import org.apache.drill.common.AutoCloseables;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.expression.ErrorCollector;
import org.apache.drill.common.expression.ErrorCollectorImpl;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.logical.data.Order.Ordering;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.compile.sig.GeneratorMapping;
import org.apache.drill.exec.compile.sig.MappingSet;
import org.apache.drill.exec.exception.ClassTransformationException;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.ClassGenerator;
import org.apache.drill.exec.expr.ClassGenerator.HoldingContainer;
import org.apache.drill.exec.expr.CodeGenerator;
import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
import org.apache.drill.exec.expr.TypeHelper;
import org.apache.drill.exec.expr.fn.FunctionGenerationHelper;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.ops.MetricDef;
import org.apache.drill.exec.physical.config.ExternalSort;
import org.apache.drill.exec.physical.impl.sort.RecordBatchData;
import org.apache.drill.exec.physical.impl.sort.SortRecordBatchBuilder;
import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
import org.apache.drill.exec.proto.helper.QueryIdHelper;
import org.apache.drill.exec.record.AbstractRecordBatch;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.record.SchemaUtil;
import org.apache.drill.exec.record.VectorAccessible;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.record.WritableBatch;
import org.apache.drill.exec.record.selection.SelectionVector2;
import org.apache.drill.exec.record.selection.SelectionVector4;
import org.apache.drill.exec.testing.ControlsInjector;
import org.apache.drill.exec.testing.ControlsInjectorFactory;
import org.apache.drill.exec.vector.CopyUtil;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.vector.complex.AbstractContainerVector;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;

import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.sun.codemodel.JConditional;
import com.sun.codemodel.JExpr;

public class ExternalSortBatch extends AbstractRecordBatch<ExternalSort> {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ExternalSortBatch.class);
  private static final ControlsInjector injector = ControlsInjectorFactory.getInjector(ExternalSortBatch.class);

  private static final GeneratorMapping COPIER_MAPPING = new GeneratorMapping("doSetup", "doCopy", null, null);
  private static final MappingSet MAIN_MAPPING = new MappingSet( (String) null, null, ClassGenerator.DEFAULT_SCALAR_MAP, ClassGenerator.DEFAULT_SCALAR_MAP);
  private static final MappingSet LEFT_MAPPING = new MappingSet("leftIndex", null, ClassGenerator.DEFAULT_SCALAR_MAP, ClassGenerator.DEFAULT_SCALAR_MAP);
  private static final MappingSet RIGHT_MAPPING = new MappingSet("rightIndex", null, ClassGenerator.DEFAULT_SCALAR_MAP, ClassGenerator.DEFAULT_SCALAR_MAP);
  private static final MappingSet COPIER_MAPPING_SET = new MappingSet(COPIER_MAPPING, COPIER_MAPPING);

  private final int SPILL_BATCH_GROUP_SIZE;
  private final int SPILL_THRESHOLD;
  private final Iterator<String> dirs;
  private final RecordBatch incoming;
  private final BufferAllocator oAllocator;
  private final BufferAllocator copierAllocator;

  private BatchSchema schema;
  private SingleBatchSorter sorter;
  private SortRecordBatchBuilder builder;
  private MSorter mSorter;
  /**
   * A single PriorityQueueCopier instance is used for 2 purposes:
   * 1. Merge sorted batches before spilling
   * 2. Merge sorted batches when all incoming data fits in memory
   */
  private PriorityQueueCopier copier;
  private LinkedList<BatchGroup> batchGroups = Lists.newLinkedList();
  private LinkedList<BatchGroup> spilledBatchGroups = Lists.newLinkedList();
  private SelectionVector4 sv4;
  private FileSystem fs;
  private int spillCount = 0;
  private int batchesSinceLastSpill = 0;
  private boolean first = true;
  private int targetRecordCount;
  private final String fileName;
  private int firstSpillBatchCount = 0;
  private int peakNumBatches = -1;

  /**
   * The copier uses the COPIER_BATCH_MEM_LIMIT to estimate the target
   * number of records to return in each batch.
   */
  private static final int COPIER_BATCH_MEM_LIMIT = 256 * 1024;

  public static final String INTERRUPTION_AFTER_SORT = "after-sort";
  public static final String INTERRUPTION_AFTER_SETUP = "after-setup";
  public static final String INTERRUPTION_WHILE_SPILLING = "spilling";

  public enum Metric implements MetricDef {
    SPILL_COUNT,            // number of times operator spilled to disk
    PEAK_SIZE_IN_MEMORY,    // peak value for totalSizeInMemory
    PEAK_BATCHES_IN_MEMORY; // maximum number of batches kept in memory

    @Override
    public int metricId() {
      return ordinal();
    }
  }

  public ExternalSortBatch(ExternalSort popConfig, FragmentContext context, RecordBatch incoming) throws OutOfMemoryException {
    super(popConfig, context, true);
    this.incoming = incoming;
    DrillConfig config = context.getConfig();
    Configuration conf = new Configuration();
    conf.set("fs.default.name", config.getString(ExecConstants.EXTERNAL_SORT_SPILL_FILESYSTEM));
    try {
      this.fs = FileSystem.get(conf);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    SPILL_BATCH_GROUP_SIZE = config.getInt(ExecConstants.EXTERNAL_SORT_SPILL_GROUP_SIZE);
    SPILL_THRESHOLD = config.getInt(ExecConstants.EXTERNAL_SORT_SPILL_THRESHOLD);
    dirs = Iterators.cycle(config.getStringList(ExecConstants.EXTERNAL_SORT_SPILL_DIRS));
    oAllocator = oContext.getAllocator();
    copierAllocator = oAllocator.newChildAllocator(oAllocator.getName() + ":copier",
        PriorityQueueCopier.INITIAL_ALLOCATION, PriorityQueueCopier.MAX_ALLOCATION);
    FragmentHandle handle = context.getHandle();
    fileName = String.format("%s/major_fragment_%s/minor_fragment_%s/operator_%s", QueryIdHelper.getQueryId(handle.getQueryId()),
        handle.getMajorFragmentId(), handle.getMinorFragmentId(), popConfig.getOperatorId());
  }

  @Override
  public int getRecordCount() {
    if (sv4 != null) {
      return sv4.getCount();
    }
    return container.getRecordCount();
  }

  @Override
  public SelectionVector4 getSelectionVector4() {
    return sv4;
  }

  private void closeBatchGroups(Collection<BatchGroup> groups) {
    for (BatchGroup group: groups) {
      try {
        group.close();
      } catch (Exception e) {
        // collect all failure and make sure to cleanup all remaining batches
        // Originally we would have thrown a RuntimeException that would propagate to FragmentExecutor.closeOutResources()
        // where it would have been passed to context.fail()
        // passing the exception directly to context.fail(e) will let the cleanup process continue instead of stopping
        // right away, this will also make sure we collect any additional exception we may get while cleaning up
        context.fail(e);
      }
    }
  }

  @Override
  public void close() {
    try {
      if (batchGroups != null) {
        closeBatchGroups(batchGroups);
        batchGroups = null;
      }
      if (spilledBatchGroups != null) {
        closeBatchGroups(spilledBatchGroups);
        spilledBatchGroups = null;
      }
    } finally {
      if (builder != null) {
        builder.clear();
        builder.close();
      }
      if (sv4 != null) {
        sv4.clear();
      }

      try {
        if (copier != null) {
          copier.close();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      } finally {
        copierAllocator.close();
        super.close();

        if (mSorter != null) {
          mSorter.clear();
        }

      }

    }

  }

  @Override
  public void buildSchema() throws SchemaChangeException {
    IterOutcome outcome = next(incoming);
    switch (outcome) {
      case OK:
      case OK_NEW_SCHEMA:
        for (VectorWrapper<?> w : incoming) {
          ValueVector v = container.addOrGet(w.getField());
          if (v instanceof AbstractContainerVector) {
            w.getValueVector().makeTransferPair(v); // Can we remove this hack?
            v.clear();
          }
          v.allocateNew(); // Can we remove this? - SVR fails with NPE (TODO)
        }
        container.buildSchema(SelectionVectorMode.NONE);
        container.setRecordCount(0);
        break;
      case STOP:
        state = BatchState.STOP;
        break;
      case OUT_OF_MEMORY:
        state = BatchState.OUT_OF_MEMORY;
        break;
      case NONE:
        state = BatchState.DONE;
        break;
      default:
        break;
    }
  }

  @Override
  public IterOutcome innerNext() {
    if (schema != null) {
      if (spillCount == 0) {
        return (getSelectionVector4().next()) ? IterOutcome.OK : IterOutcome.NONE;
      } else {
        Stopwatch w = Stopwatch.createStarted();
        int count = copier.next(targetRecordCount);
        if (count > 0) {
          long t = w.elapsed(TimeUnit.MICROSECONDS);
          logger.debug("Took {} us to merge {} records", t, count);
          container.setRecordCount(count);
          return IterOutcome.OK;
        } else {
          logger.debug("copier returned 0 records");
          return IterOutcome.NONE;
        }
      }
    }

    int totalCount = 0;
    int totalBatches = 0; // total number of batches received so far

    try{
      container.clear();
      outer: while (true) {
        IterOutcome upstream;
        if (first) {
          upstream = IterOutcome.OK_NEW_SCHEMA;
        } else {
          upstream = next(incoming);
        }
        if (upstream == IterOutcome.OK && sorter == null) {
          upstream = IterOutcome.OK_NEW_SCHEMA;
        }
        switch (upstream) {
        case NONE:
          if (first) {
            return upstream;
          }
          break outer;
        case NOT_YET:
          throw new UnsupportedOperationException();
        case STOP:
          return upstream;
        case OK_NEW_SCHEMA:
        case OK:
          VectorContainer convertedBatch;
          // only change in the case that the schema truly changes.  Artificial schema changes are ignored.
          if (upstream == IterOutcome.OK_NEW_SCHEMA && !incoming.getSchema().equals(schema)) {
            if (schema != null) {
              if (unionTypeEnabled) {
                this.schema = SchemaUtil.mergeSchemas(schema, incoming.getSchema());
              } else {
                throw new SchemaChangeException("Schema changes not supported in External Sort. Please enable Union type");
              }
            } else {
              schema = incoming.getSchema();
            }
            convertedBatch = SchemaUtil.coerceContainer(incoming, schema, oContext);
            for (BatchGroup b : batchGroups) {
              b.setSchema(schema);
            }
            for (BatchGroup b : spilledBatchGroups) {
              b.setSchema(schema);
            }
            this.sorter = createNewSorter(context, convertedBatch);
          } else {
            convertedBatch = SchemaUtil.coerceContainer(incoming, schema, oContext);
          }
          if (first) {
            first = false;
          }
          if (convertedBatch.getRecordCount() == 0) {
            for (VectorWrapper<?> w : convertedBatch) {
              w.clear();
            }
            break;
          }
          SelectionVector2 sv2;
          if (incoming.getSchema().getSelectionVectorMode() == BatchSchema.SelectionVectorMode.TWO_BYTE) {
            sv2 = incoming.getSelectionVector2().clone();
          } else {
            try {
              sv2 = newSV2();
            } catch(InterruptedException e) {
              return IterOutcome.STOP;
            } catch (OutOfMemoryException e) {
              throw new OutOfMemoryException(e);
            }
          }

          int count = sv2.getCount();
          totalCount += count;
          totalBatches++;
          sorter.setup(context, sv2, convertedBatch);
          sorter.sort(sv2);
          RecordBatchData rbd = new RecordBatchData(convertedBatch, oAllocator);
          boolean success = false;
          try {
            rbd.setSv2(sv2);
            batchGroups.add(new BatchGroup(rbd.getContainer(), rbd.getSv2(), oContext));
            if (peakNumBatches < batchGroups.size()) {
              peakNumBatches = batchGroups.size();
              stats.setLongStat(Metric.PEAK_BATCHES_IN_MEMORY, peakNumBatches);
            }

            batchesSinceLastSpill++;
            if (// If we haven't spilled so far, do we have enough memory for MSorter if this turns out to be the last incoming batch?
                (spillCount == 0 && !hasMemoryForInMemorySort(totalCount)) ||
                // If we haven't spilled so far, make sure we don't exceed the maximum number of batches SV4 can address
                (spillCount == 0 && totalBatches > Character.MAX_VALUE) ||
                // current memory used is more than 95% of memory usage limit of this operator
                (oAllocator.getAllocatedMemory() > .95 * oAllocator.getLimit()) ||
                // Number of incoming batches (BatchGroups) exceed the limit and number of incoming batches accumulated
                // since the last spill exceed the defined limit
                (batchGroups.size() > SPILL_THRESHOLD && batchesSinceLastSpill >= SPILL_BATCH_GROUP_SIZE)) {

              if (firstSpillBatchCount == 0) {
                firstSpillBatchCount = batchGroups.size();
              }

              if (spilledBatchGroups.size() > firstSpillBatchCount / 2) {
                logger.info("Merging spills");
                final BatchGroup merged = mergeAndSpill(spilledBatchGroups);
                if (merged != null) {
                  spilledBatchGroups.addFirst(merged);
                }
              }
              final BatchGroup merged = mergeAndSpill(batchGroups);
              if (merged != null) { // make sure we don't add null to spilledBatchGroups
                spilledBatchGroups.add(merged);
                batchesSinceLastSpill = 0;
              }
            }
            success = true;
          } finally {
            if (!success) {
              rbd.clear();
            }
          }
          break;
        case OUT_OF_MEMORY:
          logger.debug("received OUT_OF_MEMORY, trying to spill");
          if (batchesSinceLastSpill > 2) {
            final BatchGroup merged = mergeAndSpill(batchGroups);
            if (merged != null) {
              spilledBatchGroups.add(merged);
              batchesSinceLastSpill = 0;
            }
          } else {
            logger.debug("not enough batches to spill, sending OUT_OF_MEMORY downstream");
            return IterOutcome.OUT_OF_MEMORY;
          }
          break;
        default:
          throw new UnsupportedOperationException();
        }
      }

      if (totalCount == 0) {
        return IterOutcome.NONE;
      }
      if (spillCount == 0) {

        if (builder != null) {
          builder.clear();
          builder.close();
        }
        builder = new SortRecordBatchBuilder(oAllocator);

        for (BatchGroup group : batchGroups) {
          RecordBatchData rbd = new RecordBatchData(group.getContainer(), oAllocator);
          rbd.setSv2(group.getSv2());
          builder.add(rbd);
        }

        builder.build(context, container);
        sv4 = builder.getSv4();
        mSorter = createNewMSorter();
        mSorter.setup(context, oAllocator, getSelectionVector4(), this.container);

        // For testing memory-leak purpose, inject exception after mSorter finishes setup
        injector.injectUnchecked(context.getExecutionControls(), INTERRUPTION_AFTER_SETUP);
        mSorter.sort(this.container);

        // sort may have prematurely exited due to should continue returning false.
        if (!context.shouldContinue()) {
          return IterOutcome.STOP;
        }

        // For testing memory-leak purpose, inject exception after mSorter finishes sorting
        injector.injectUnchecked(context.getExecutionControls(), INTERRUPTION_AFTER_SORT);
        sv4 = mSorter.getSV4();

        container.buildSchema(SelectionVectorMode.FOUR_BYTE);
      } else { // some batches were spilled
        final BatchGroup merged = mergeAndSpill(batchGroups);
        if (merged != null) {
          spilledBatchGroups.add(merged);
        }
        batchGroups.addAll(spilledBatchGroups);
        spilledBatchGroups = null; // no need to cleanup spilledBatchGroups, all it's batches are in batchGroups now

        logger.warn("Starting to merge. {} batch groups. Current allocated memory: {}", batchGroups.size(), oAllocator.getAllocatedMemory());
        VectorContainer hyperBatch = constructHyperBatch(batchGroups);
        createCopier(hyperBatch, batchGroups, container, false);

        int estimatedRecordSize = 0;
        for (VectorWrapper<?> w : batchGroups.get(0)) {
          try {
            estimatedRecordSize += TypeHelper.getSize(w.getField().getType());
          } catch (UnsupportedOperationException e) {
            estimatedRecordSize += 50;
          }
        }
        targetRecordCount = Math.min(MAX_BATCH_SIZE, Math.max(1, COPIER_BATCH_MEM_LIMIT / estimatedRecordSize));
        int count = copier.next(targetRecordCount);
        container.buildSchema(SelectionVectorMode.NONE);
        container.setRecordCount(count);
      }

      return IterOutcome.OK_NEW_SCHEMA;

    } catch (SchemaChangeException ex) {
      kill(false);
      context.fail(UserException.unsupportedError(ex)
        .message("Sort doesn't currently support sorts with changing schemas").build(logger));
      return IterOutcome.STOP;
    } catch(ClassTransformationException | IOException ex) {
      kill(false);
      context.fail(ex);
      return IterOutcome.STOP;
    } catch (UnsupportedOperationException e) {
      throw new RuntimeException(e);
    }
  }

  private boolean hasMemoryForInMemorySort(int currentRecordCount) {
    long currentlyAvailable =  popConfig.getMaxAllocation() - oAllocator.getAllocatedMemory();

    long neededForInMemorySort = SortRecordBatchBuilder.memoryNeeded(currentRecordCount) +
        MSortTemplate.memoryNeeded(currentRecordCount);

    return currentlyAvailable > neededForInMemorySort;
  }

  public BatchGroup mergeAndSpill(LinkedList<BatchGroup> batchGroups) throws SchemaChangeException {
    logger.debug("Copier allocator current allocation {}", copierAllocator.getAllocatedMemory());
    logger.debug("mergeAndSpill: starting total size in memory = {}", oAllocator.getAllocatedMemory());
    VectorContainer outputContainer = new VectorContainer();
    List<BatchGroup> batchGroupList = Lists.newArrayList();
    int batchCount = batchGroups.size();
    for (int i = 0; i < batchCount / 2; i++) {
      if (batchGroups.size() == 0) {
        break;
      }
      BatchGroup batch = batchGroups.pollLast();
      assert batch != null : "Encountered a null batch during merge and spill operation";
      batchGroupList.add(batch);
    }

    if (batchGroupList.size() == 0) {
      return null;
    }
    int estimatedRecordSize = 0;
    for (VectorWrapper<?> w : batchGroupList.get(0)) {
      try {
        estimatedRecordSize += TypeHelper.getSize(w.getField().getType());
      } catch (UnsupportedOperationException e) {
        estimatedRecordSize += 50;
      }
    }
    int targetRecordCount = Math.max(1, COPIER_BATCH_MEM_LIMIT / estimatedRecordSize);
    VectorContainer hyperBatch = constructHyperBatch(batchGroupList);
    createCopier(hyperBatch, batchGroupList, outputContainer, true);

    int count = copier.next(targetRecordCount);
    assert count > 0;

    logger.debug("mergeAndSpill: estimated record size = {}, target record count = {}", estimatedRecordSize, targetRecordCount);

    // 1 output container is kept in memory, so we want to hold on to it and transferClone
    // allows keeping ownership
    VectorContainer c1 = VectorContainer.getTransferClone(outputContainer, oContext);
    c1.buildSchema(BatchSchema.SelectionVectorMode.NONE);
    c1.setRecordCount(count);

    String outputFile = Joiner.on("/").join(dirs.next(), fileName, spillCount++);
    stats.setLongStat(Metric.SPILL_COUNT, spillCount);
    BatchGroup newGroup = new BatchGroup(c1, fs, outputFile, oContext);
    try (AutoCloseable a = AutoCloseables.all(batchGroupList)) {
      logger.info("Merging and spilling to {}", outputFile);
      while ((count = copier.next(targetRecordCount)) > 0) {
        outputContainer.buildSchema(BatchSchema.SelectionVectorMode.NONE);
        outputContainer.setRecordCount(count);
        // note that addBatch also clears the outputContainer
        newGroup.addBatch(outputContainer);
      }
      injector.injectChecked(context.getExecutionControls(), INTERRUPTION_WHILE_SPILLING, IOException.class);
      newGroup.closeOutputStream();
    } catch (Exception e) {
      // we only need to cleanup newGroup if spill failed
      AutoCloseables.close(e, newGroup);
      throw UserException.resourceError(e)
        .message("External Sort encountered an error while spilling to disk")
        .build(logger);
    } finally {
      hyperBatch.clear();
    }
    logger.debug("mergeAndSpill: final total size in memory = {}", oAllocator.getAllocatedMemory());
    logger.info("Completed spilling to {}", outputFile);
    return newGroup;
  }

  private SelectionVector2 newSV2() throws OutOfMemoryException, InterruptedException {
    SelectionVector2 sv2 = new SelectionVector2(oAllocator);
    if (!sv2.allocateNewSafe(incoming.getRecordCount())) {
      try {
        final BatchGroup merged = mergeAndSpill(batchGroups);
        if (merged != null) {
          spilledBatchGroups.add(merged);
        } else {
          throw UserException.memoryError("Unable to allocate sv2 for %d records, and not enough batchGroups to spill.",
              incoming.getRecordCount())
            .addContext("batchGroups.size", batchGroups.size())
            .addContext("spilledBatchGroups.size", spilledBatchGroups.size())
            .addContext("allocated memory", oAllocator.getAllocatedMemory())
            .addContext("allocator limit", oAllocator.getLimit())
            .build(logger);
        }
      } catch (SchemaChangeException e) {
        throw new RuntimeException(e);
      }
      int waitTime = 1;
      while (true) {
        try {
          Thread.sleep(waitTime * 1000);
        } catch(final InterruptedException e) {
          if (!context.shouldContinue()) {
            throw e;
          }
        }
        waitTime *= 2;
        if (sv2.allocateNewSafe(incoming.getRecordCount())) {
          break;
        }
        if (waitTime >= 32) {
          throw new OutOfMemoryException("Unable to allocate sv2 buffer after repeated attempts");
        }
      }
    }
    for (int i = 0; i < incoming.getRecordCount(); i++) {
      sv2.setIndex(i, (char) i);
    }
    sv2.setRecordCount(incoming.getRecordCount());
    return sv2;
  }

  private VectorContainer constructHyperBatch(List<BatchGroup> batchGroupList) {
    VectorContainer cont = new VectorContainer();
    for (MaterializedField field : schema) {
      ValueVector[] vectors = new ValueVector[batchGroupList.size()];
      int i = 0;
      for (BatchGroup group : batchGroupList) {
        vectors[i++] = group.getValueAccessorById(
            field.getValueClass(),
            group.getValueVectorId(SchemaPath.getSimplePath(field.getPath())).getFieldIds())
            .getValueVector();
      }
      cont.add(vectors);
    }
    cont.buildSchema(BatchSchema.SelectionVectorMode.FOUR_BYTE);
    return cont;
  }

  private MSorter createNewMSorter() throws ClassTransformationException, IOException, SchemaChangeException {
    return createNewMSorter(this.context, this.popConfig.getOrderings(), this, MAIN_MAPPING, LEFT_MAPPING, RIGHT_MAPPING);
  }

  private MSorter createNewMSorter(FragmentContext context, List<Ordering> orderings, VectorAccessible batch, MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping)
          throws ClassTransformationException, IOException, SchemaChangeException{
    CodeGenerator<MSorter> cg = CodeGenerator.get(MSorter.TEMPLATE_DEFINITION, context.getFunctionRegistry());
    ClassGenerator<MSorter> g = cg.getRoot();
    g.setMappingSet(mainMapping);

    for (Ordering od : orderings) {
      // first, we rewrite the evaluation stack for each side of the comparison.
      ErrorCollector collector = new ErrorCollectorImpl();
      final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector, context.getFunctionRegistry());
      if (collector.hasErrors()) {
        throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
      }
      g.setMappingSet(leftMapping);
      HoldingContainer left = g.addExpr(expr, false);
      g.setMappingSet(rightMapping);
      HoldingContainer right = g.addExpr(expr, false);
      g.setMappingSet(mainMapping);

      // next we wrap the two comparison sides and add the expression block for the comparison.
      LogicalExpression fh =
          FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                         context.getFunctionRegistry());
      HoldingContainer out = g.addExpr(fh, false);
      JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      if (od.getDirection() == Direction.ASCENDING) {
        jc._then()._return(out.getValue());
      }else{
        jc._then()._return(out.getValue().minus());
      }
      g.rotateBlock();
    }

    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));

    return context.getImplementationClass(cg);

  }

  public SingleBatchSorter createNewSorter(FragmentContext context, VectorAccessible batch)
          throws ClassTransformationException, IOException, SchemaChangeException{
    CodeGenerator<SingleBatchSorter> cg = CodeGenerator.get(SingleBatchSorter.TEMPLATE_DEFINITION, context.getFunctionRegistry());
    ClassGenerator<SingleBatchSorter> g = cg.getRoot();

    generateComparisons(g, batch);

    return context.getImplementationClass(cg);
  }

  private void generateComparisons(ClassGenerator<?> g, VectorAccessible batch) throws SchemaChangeException {
    g.setMappingSet(MAIN_MAPPING);

    for (Ordering od : popConfig.getOrderings()) {
      // first, we rewrite the evaluation stack for each side of the comparison.
      ErrorCollector collector = new ErrorCollectorImpl();
      final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,context.getFunctionRegistry());
      if (collector.hasErrors()) {
        throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
      }
      g.setMappingSet(LEFT_MAPPING);
      HoldingContainer left = g.addExpr(expr, false);
      g.setMappingSet(RIGHT_MAPPING);
      HoldingContainer right = g.addExpr(expr, false);
      g.setMappingSet(MAIN_MAPPING);

      // next we wrap the two comparison sides and add the expression block for the comparison.
      LogicalExpression fh =
          FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                         context.getFunctionRegistry());
      HoldingContainer out = g.addExpr(fh, false);
      JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      if (od.getDirection() == Direction.ASCENDING) {
        jc._then()._return(out.getValue());
      }else{
        jc._then()._return(out.getValue().minus());
      }
      g.rotateBlock();
    }

    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));
  }

  private void createCopier(VectorAccessible batch, List<BatchGroup> batchGroupList, VectorContainer outputContainer, boolean spilling) throws SchemaChangeException {
    try {
      if (copier == null) {
        CodeGenerator<PriorityQueueCopier> cg = CodeGenerator.get(PriorityQueueCopier.TEMPLATE_DEFINITION, context.getFunctionRegistry());
        ClassGenerator<PriorityQueueCopier> g = cg.getRoot();

        generateComparisons(g, batch);

        g.setMappingSet(COPIER_MAPPING_SET);
        CopyUtil.generateCopies(g, batch, true);
        g.setMappingSet(MAIN_MAPPING);
        copier = context.getImplementationClass(cg);
      } else {
        copier.close();
      }

      BufferAllocator allocator = spilling ? copierAllocator : oAllocator;
      for (VectorWrapper<?> i : batch) {
        ValueVector v = TypeHelper.getNewVector(i.getField(), allocator);
        outputContainer.add(v);
      }
      copier.setup(context, allocator, batch, batchGroupList, outputContainer);
    } catch (ClassTransformationException | IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public WritableBatch getWritableBatch() {
    throw new UnsupportedOperationException("A sort batch is not writable.");
  }

  @Override
  protected void killIncoming(boolean sendUpstream) {
    incoming.kill(sendUpstream);
  }

}


text:
import {TwingEnvironment} from "../../../environment";
import {reverse as reverseHelper} from "../../../helpers/reverse";
import {iteratorToMap} from "../../../helpers/iterator-to-map";

const esrever = require('esrever');

/**
 * Reverses a variable.
 *
 * @param {TwingEnvironment} env
 * @param {string | Map<*, *>} item A traversable instance, or a string
 * @param {boolean} preserveKeys Whether to preserve key or not
 *
 * @returns {Promise<string | Map<any, any>>} The reversed input
 */
export function reverse(env: TwingEnvironment, item: any, preserveKeys: boolean = false): Promise<string | Map<any, any>> {
    if (typeof item === 'string') {
        return Promise.resolve(esrever.reverse(item));
    } else {
        return Promise.resolve(reverseHelper(iteratorToMap(item as Map<any, any>), preserveKeys));
    }
}