text:
use std::io::{Read, Write};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

/// Use a [`tokio::io::AsyncRead`] synchronously as a [`std::io::Read`] or
/// a [`tokio::io::AsyncWrite`] as a [`std::io::Write`].
#[derive(Debug)]
pub struct SyncIoBridge<T> {
    src: T,
    rt: tokio::runtime::Handle,
}

impl<T: AsyncRead + Unpin> Read for SyncIoBridge<T> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let src = &mut self.src;
        self.rt.block_on(AsyncReadExt::read(src, buf))
    }

    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> std::io::Result<usize> {
        let src = &mut self.src;
        self.rt.block_on(src.read_to_end(buf))
    }

    fn read_to_string(&mut self, buf: &mut String) -> std::io::Result<usize> {
        let src = &mut self.src;
        self.rt.block_on(src.read_to_string(buf))
    }

    fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
        let src = &mut self.src;
        // The AsyncRead trait returns the count, synchronous doesn't.
        let _n = self.rt.block_on(src.read_exact(buf))?;
        Ok(())
    }
}

impl<T: AsyncWrite + Unpin> Write for SyncIoBridge<T> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let src = &mut self.src;
        self.rt.block_on(src.write(buf))
    }

    fn flush(&mut self) -> std::io::Result<()> {
        let src = &mut self.src;
        self.rt.block_on(src.flush())
    }

    fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
        let src = &mut self.src;
        self.rt.block_on(src.write_all(buf))
    }

    fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
        let src = &mut self.src;
        self.rt.block_on(src.write_vectored(bufs))
    }
}

// Because https://doc.rust-lang.org/std/io/trait.Write.html#method.is_write_vectored is at the time
// of this writing still unstable, we expose this as part of a standalone method.
impl<T: AsyncWrite> SyncIoBridge<T> {
    /// Determines if the underlying [`tokio::io::AsyncWrite`] target supports efficient vectored writes.
    ///
    /// See [`tokio::io::AsyncWrite::is_write_vectored`].
    pub fn is_write_vectored(&self) -> bool {
        self.src.is_write_vectored()
    }
}

impl<T: AsyncWrite + Unpin> SyncIoBridge<T> {
    /// Shutdown this writer. This method provides a way to call the [`AsyncWriteExt::shutdown`]
    /// function of the inner [`tokio::io::AsyncWrite`] instance.
    ///
    /// # Errors
    ///
    /// This method returns the same errors as [`AsyncWriteExt::shutdown`].
    ///
    /// [`AsyncWriteExt::shutdown`]: tokio::io::AsyncWriteExt::shutdown
    pub fn shutdown(&mut self) -> std::io::Result<()> {
        let src = &mut self.src;
        self.rt.block_on(src.shutdown())
    }
}

impl<T: Unpin> SyncIoBridge<T> {
    /// Use a [`tokio::io::AsyncRead`] synchronously as a [`std::io::Read`] or
    /// a [`tokio::io::AsyncWrite`] as a [`std::io::Write`].
    ///
    /// When this struct is created, it captures a handle to the current thread's runtime with [`tokio::runtime::Handle::current`].
    /// It is hence OK to move this struct into a separate thread outside the runtime, as created
    /// by e.g. [`tokio::task::spawn_blocking`].
    ///
    /// Stated even more strongly: to make use of this bridge, you *must* move
    /// it into a separate thread outside the runtime.  The synchronous I/O will use the
    /// underlying handle to block on the backing asynchronous source, via
    /// [`tokio::runtime::Handle::block_on`].  As noted in the documentation for that
    /// function, an attempt to `block_on` from an asynchronous execution context
    /// will panic.
    ///
    /// # Wrapping `!Unpin` types
    ///
    /// Use e.g. `SyncIoBridge::new(Box::pin(src))`.
    ///
    /// # Panics
    ///
    /// This will panic if called outside the context of a Tokio runtime.
    #[track_caller]
    pub fn new(src: T) -> Self {
        Self::new_with_handle(src, tokio::runtime::Handle::current())
    }

    /// Use a [`tokio::io::AsyncRead`] synchronously as a [`std::io::Read`] or
    /// a [`tokio::io::AsyncWrite`] as a [`std::io::Write`].
    ///
    /// This is the same as [`SyncIoBridge::new`], but allows passing an arbitrary handle and hence may
    /// be initially invoked outside of an asynchronous context.
    pub fn new_with_handle(src: T, rt: tokio::runtime::Handle) -> Self {
        Self { src, rt }
    }
}


text:
import {h, Component} from 'preact'
import classNames from 'classnames'
import {Command} from '@sabaki/gtp'

import sabaki from '../../modules/sabaki.js'
import ContentDisplay from '../ContentDisplay.js'
import TextSpinner from '../TextSpinner.js'
import {noop, popupMenu} from '../../modules/helper.js'
import i18n from '../../i18n.js'

class ConsoleCommandEntry extends Component {
  shouldComponentUpdate({sign, name, command}) {
    return (
      sign !== this.props.sign ||
      name !== this.props.name ||
      command !== this.props.command
    )
  }

  render({sign, name, command}) {
    if (command == null) command = {name: ''}
    if (sign == null) sign = 0

    return h(
      'li',
      {class: 'command'},
      h(
        'pre',
        {},
        h('span', {class: 'engine'}, `${['● ', '', '○ '][sign + 1]}${name}>`),
        ' ',

        command.id != null && [h('span', {class: 'id'}, command.id), ' '],
        command.name,
        ' ',

        h(ContentDisplay, {
          tag: 'span',
          content: (command.args || []).join(' ')
        })
      )
    )
  }
}

class ConsoleResponseEntry extends Component {
  shouldComponentUpdate({response, waiting}) {
    return waiting !== this.props.waiting || response !== this.props.response
  }

  render({response, waiting}) {
    return h(
      'li',
      {class: classNames({response: true, waiting})},
      response != null
        ? h(
            'pre',
            {},
            !response.internal && [
              h(
                'span',
                {
                  class: response.error ? 'error' : 'success'
                },
                response.error ? '?' : '='
              )
            ],

            response.id != null && [h('span', {class: 'id'}, response.id)],

            !response.internal && ' ',

            typeof response.content === 'string'
              ? h(ContentDisplay, {
                  tag: 'span',
                  class: response.internal ? 'internal' : '',
                  content: response.content.replace(
                    /(^info move.*\s*)+/gm,
                    'info move (…)\n'
                  )
                })
              : response.content,

            waiting && h('div', {class: 'internal'}, h(TextSpinner))
          )
        : h('pre', {}, h('span', {class: 'internal'}, h(TextSpinner)))
    )
  }
}

class ConsoleInput extends Component {
  constructor(props) {
    super(props)

    this.state = {
      commandInputText: ''
    }

    this.handleInputChange = evt => {
      this.setState({commandInputText: evt.currentTarget.value})
    }

    this.handleKeyDown = evt => {
      if (evt.key === 'Enter') {
        evt.preventDefault()

        let {onSubmit = noop} = this.props
        let {commandInputText} = this.state

        if (commandInputText.trim() === '') return

        onSubmit({
          command: Command.fromString(commandInputText)
        })

        this.inputPointer = null
        this.setState({commandInputText: ''})
      } else if (['ArrowUp', 'ArrowDown'].includes(evt.key) && !evt.ctrlKey) {
        evt.preventDefault()

        let {consoleLog} = this.props
        let sign = evt.key === 'ArrowUp' ? -1 : 1

        if (this.inputPointer == null) this.inputPointer = consoleLog.length

        while (true) {
          this.inputPointer += sign

          if (this.inputPointer < 0 || this.inputPointer >= consoleLog.length) {
            this.inputPointer = Math.max(
              -1,
              Math.min(consoleLog.length, this.inputPointer)
            )
            this.setState({commandInputText: ''})
            break
          }

          let {command} = consoleLog[this.inputPointer]

          if (command != null) {
            let text = Command.toString(command)

            this.setState({commandInputText: text})

            break
          }
        }
      } else if (['ArrowUp', 'ArrowDown'].includes(evt.key) && evt.ctrlKey) {
        let {onControlStep = noop} = this.props
        let step = evt.key === 'ArrowUp' ? -1 : 1

        onControlStep({step})
      } else if (evt.key === 'Tab') {
        evt.preventDefault()

        if (this.autocompleteText !== '') {
          this.setState({commandInputText: this.autocompleteText})
        }
      }

      this.setState({}, () => {
        if (['Enter', 'ArrowUp', 'ArrowDown', 'Tab'].includes(evt.key)) {
          this.inputElement.scrollLeft = this.inputElement.scrollWidth
          this.inputElement.selectionStart = this.inputElement.value.length
          this.inputElement.selectionEnd = this.inputElement.value.length
        }

        setTimeout(() => {
          if (
            this.inputAutocompleteElement.scrollLeft !==
            this.inputElement.scrollLeft
          ) {
            this.inputAutocompleteElement.scrollLeft = this.inputElement.scrollLeft
          }
        }, 0)
      })
    }
  }

  get autocompleteText() {
    let {attachedEngine} = this.props
    let {commandInputText} = this.state

    if (attachedEngine && commandInputText.length > 0) {
      return (
        attachedEngine.commands.find(x => x.indexOf(commandInputText) === 0) ||
        ''
      )
    }

    return ''
  }

  render({attachedEngine}, {commandInputText}) {
    let disabled = attachedEngine == null

    return h(
      'form',
      {class: 'input'},
      h('input', {
        ref: el => (this.inputElement = el),
        class: 'command',
        disabled,
        type: 'text',
        value: commandInputText,
        placeholder: attachedEngine != null ? `${attachedEngine.name}>` : '',

        onInput: this.handleInputChange,
        onKeyDown: this.handleKeyDown
      }),

      h('input', {
        ref: el => (this.inputAutocompleteElement = el),
        class: 'autocomplete',
        disabled,
        type: 'text',
        value: this.autocompleteText
      })
    )
  }
}

export default class GtpConsole extends Component {
  constructor() {
    super()

    this.scrollToBottom = true

    this.handleContextMenu = evt => {
      let t = i18n.context('menu.engines')

      popupMenu(
        [
          {
            label: t('&Clear Console'),
            click: () => sabaki.clearConsole()
          }
        ],
        evt.clientX,
        evt.clientY
      )
    }
  }

  componentWillReceiveProps({consoleLog}) {
    this.inputPointer = consoleLog.length
  }

  componentWillUpdate() {
    let {scrollTop, scrollHeight, offsetHeight} = this.scrollElement

    this.scrollToBottom = scrollTop >= scrollHeight - offsetHeight
  }

  componentDidUpdate(prevProps) {
    if ((!prevProps.show && this.props.show) || this.scrollToBottom) {
      this.scrollElement.scrollTop = this.scrollElement.scrollHeight
    }
  }

  getSign(command) {
    if (!command) return 0

    for (let arg of command.args) {
      if (['b', 'black'].includes(arg.toLowerCase())) {
        return 1
      } else if (['w', 'white'].includes(arg.toLowerCase())) {
        return -1
      }
    }

    return 0
  }

  render({consoleLog, attachedEngine}) {
    return h(
      'section',
      {class: 'gtp-console'},

      h(
        'ol',
        {
          ref: el => (this.scrollElement = el),
          class: 'log',
          onContextMenu: this.handleContextMenu
        },

        consoleLog.map(({name, command, response, waiting}, i) => {
          let sign = this.getSign(command)

          return [
            command ||
            i === 0 ||
            consoleLog[i - 1].name !== name ||
            (sign !== 0 && consoleLog[i - 1].sign !== sign)
              ? h(ConsoleCommandEntry, {sign, name, command})
              : null,

            h(ConsoleResponseEntry, {
              response,
              waiting: response == null || waiting
            })
          ]
        })
      ),

      h(ConsoleInput, {
        ref: component =>
          (this.inputElement =
            component == null ? null : component.inputElement),

        consoleLog,
        attachedEngine,

        onSubmit: this.props.onSubmit,
        onControlStep: this.props.onControlStep
      })
    )
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.alibaba.druid.bvt.sql.oracle;

import java.util.List;

import org.junit.Assert;

import com.alibaba.druid.sql.OracleTest;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor;

public class OracleSelectTest20 extends OracleTest {

    public void test_0() throws Exception {
        String sql = //
        "BEGIN" + //
                "   sys.dbms_stats.gather_table_stats(" + //
                "       ownname => 'ESCROW',tabname => 'HT_TASK_TRADE_HISTORY',estimate_percent=>0.5, cascade => TRUE" + //
                "       ,method_opt=>'FOR ALL COLUMNS SIZE 1',no_invalidate => false); " + //
                "END; "; //

        OracleStatementParser parser = new OracleStatementParser(sql);
        List<SQLStatement> statementList = parser.parseStatementList();
        SQLStatement statemen = statementList.get(0);
        print(statementList);

        Assert.assertEquals(1, statementList.size());

        OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
        statemen.accept(visitor);

        System.out.println("Tables : " + visitor.getTables());
        System.out.println("fields : " + visitor.getColumns());
        System.out.println("coditions : " + visitor.getConditions());
        System.out.println("relationships : " + visitor.getRelationships());
        System.out.println("orderBy : " + visitor.getOrderByColumns());

        Assert.assertEquals(0, visitor.getTables().size());

//        Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("\"DUAL\"")));

        Assert.assertEquals(0, visitor.getColumns().size());

        // Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*")));
        // Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR")));
        // Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode")));
    }
}


text:
<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\HttpFoundation\File\File as FileObject;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FileValidator extends ConstraintValidator
{
    public const KB_BYTES = 1000;
    public const MB_BYTES = 1000000;
    public const KIB_BYTES = 1024;
    public const MIB_BYTES = 1048576;

    private const SUFFICES = [
        1 => 'bytes',
        self::KB_BYTES => 'kB',
        self::MB_BYTES => 'MB',
        self::KIB_BYTES => 'KiB',
        self::MIB_BYTES => 'MiB',
    ];

    public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof File) {
            throw new UnexpectedTypeException($constraint, File::class);
        }

        if (null === $value || '' === $value) {
            return;
        }

        if ($value instanceof UploadedFile && !$value->isValid()) {
            switch ($value->getError()) {
                case \UPLOAD_ERR_INI_SIZE:
                    $iniLimitSize = UploadedFile::getMaxFilesize();
                    if ($constraint->maxSize && $constraint->maxSize < $iniLimitSize) {
                        $limitInBytes = $constraint->maxSize;
                        $binaryFormat = $constraint->binaryFormat;
                    } else {
                        $limitInBytes = $iniLimitSize;
                        $binaryFormat = $constraint->binaryFormat ?? true;
                    }

                    [, $limitAsString, $suffix] = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
                    $this->context->buildViolation($constraint->uploadIniSizeErrorMessage)
                        ->setParameter('{{ limit }}', $limitAsString)
                        ->setParameter('{{ suffix }}', $suffix)
                        ->setCode((string) \UPLOAD_ERR_INI_SIZE)
                        ->addViolation();

                    return;
                case \UPLOAD_ERR_FORM_SIZE:
                    $this->context->buildViolation($constraint->uploadFormSizeErrorMessage)
                        ->setCode((string) \UPLOAD_ERR_FORM_SIZE)
                        ->addViolation();

                    return;
                case \UPLOAD_ERR_PARTIAL:
                    $this->context->buildViolation($constraint->uploadPartialErrorMessage)
                        ->setCode((string) \UPLOAD_ERR_PARTIAL)
                        ->addViolation();

                    return;
                case \UPLOAD_ERR_NO_FILE:
                    $this->context->buildViolation($constraint->uploadNoFileErrorMessage)
                        ->setCode((string) \UPLOAD_ERR_NO_FILE)
                        ->addViolation();

                    return;
                case \UPLOAD_ERR_NO_TMP_DIR:
                    $this->context->buildViolation($constraint->uploadNoTmpDirErrorMessage)
                        ->setCode((string) \UPLOAD_ERR_NO_TMP_DIR)
                        ->addViolation();

                    return;
                case \UPLOAD_ERR_CANT_WRITE:
                    $this->context->buildViolation($constraint->uploadCantWriteErrorMessage)
                        ->setCode((string) \UPLOAD_ERR_CANT_WRITE)
                        ->addViolation();

                    return;
                case \UPLOAD_ERR_EXTENSION:
                    $this->context->buildViolation($constraint->uploadExtensionErrorMessage)
                        ->setCode((string) \UPLOAD_ERR_EXTENSION)
                        ->addViolation();

                    return;
                default:
                    $this->context->buildViolation($constraint->uploadErrorMessage)
                        ->setCode((string) $value->getError())
                        ->addViolation();

                    return;
            }
        }

        if (!\is_scalar($value) && !$value instanceof FileObject && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $path = $value instanceof FileObject ? $value->getPathname() : (string) $value;

        if (!is_file($path)) {
            $this->context->buildViolation($constraint->notFoundMessage)
                ->setParameter('{{ file }}', $this->formatValue($path))
                ->setCode(File::NOT_FOUND_ERROR)
                ->addViolation();

            return;
        }

        if (!is_readable($path)) {
            $this->context->buildViolation($constraint->notReadableMessage)
                ->setParameter('{{ file }}', $this->formatValue($path))
                ->setCode(File::NOT_READABLE_ERROR)
                ->addViolation();

            return;
        }

        $sizeInBytes = filesize($path);
        $basename = $value instanceof UploadedFile ? $value->getClientOriginalName() : basename($path);

        if (0 === $sizeInBytes) {
            $this->context->buildViolation($constraint->disallowEmptyMessage)
                ->setParameter('{{ file }}', $this->formatValue($path))
                ->setParameter('{{ name }}', $this->formatValue($basename))
                ->setCode(File::EMPTY_ERROR)
                ->addViolation();

            return;
        }

        if ($constraint->maxSize) {
            $limitInBytes = $constraint->maxSize;

            if ($sizeInBytes > $limitInBytes) {
                [$sizeAsString, $limitAsString, $suffix] = $this->factorizeSizes($sizeInBytes, $limitInBytes, $constraint->binaryFormat);
                $this->context->buildViolation($constraint->maxSizeMessage)
                    ->setParameter('{{ file }}', $this->formatValue($path))
                    ->setParameter('{{ size }}', $sizeAsString)
                    ->setParameter('{{ limit }}', $limitAsString)
                    ->setParameter('{{ suffix }}', $suffix)
                    ->setParameter('{{ name }}', $this->formatValue($basename))
                    ->setCode(File::TOO_LARGE_ERROR)
                    ->addViolation();

                return;
            }
        }

        $mimeTypes = (array) $constraint->mimeTypes;

        if ($constraint->extensions) {
            $fileExtension = pathinfo($basename, \PATHINFO_EXTENSION);

            $found = false;
            $normalizedExtensions = [];
            foreach ((array) $constraint->extensions as $k => $v) {
                if (!\is_string($k)) {
                    $k = $v;
                    $v = null;
                }

                $normalizedExtensions[] = $k;

                if ($fileExtension !== $k) {
                    continue;
                }

                $found = true;
                if (null === $v) {
                    if (!class_exists(MimeTypes::class)) {
                        throw new LogicException('You cannot validate the mime-type of files as the Mime component is not installed. Try running "composer require symfony/mime".');
                    }

                    $mimeTypesHelper = MimeTypes::getDefault();
                    $v = $mimeTypesHelper->getMimeTypes($k);
                }

                $mimeTypes = $mimeTypes ? array_intersect($v, $mimeTypes) : (array) $v;
                break;
            }

            if (!$found) {
                $this->context->buildViolation($constraint->extensionsMessage)
                    ->setParameter('{{ file }}', $this->formatValue($path))
                    ->setParameter('{{ extension }}', $this->formatValue($fileExtension))
                    ->setParameter('{{ extensions }}', $this->formatValues($normalizedExtensions))
                    ->setParameter('{{ name }}', $this->formatValue($basename))
                    ->setCode(File::INVALID_EXTENSION_ERROR)
                    ->addViolation();
            }
        }

        if ($mimeTypes) {
            if ($value instanceof FileObject) {
                $mime = $value->getMimeType();
            } elseif (isset($mimeTypesHelper) || class_exists(MimeTypes::class)) {
                $mime = ($mimeTypesHelper ?? MimeTypes::getDefault())->guessMimeType($path);
            } elseif (!class_exists(FileObject::class)) {
                throw new LogicException('You cannot validate the mime-type of files as the Mime component is not installed. Try running "composer require symfony/mime".');
            } else {
                $mime = (new FileObject($value))->getMimeType();
            }

            foreach ($mimeTypes as $mimeType) {
                if ($mimeType === $mime) {
                    return;
                }

                if ($discrete = strstr($mimeType, '/*', true)) {
                    if (strstr($mime, '/', true) === $discrete) {
                        return;
                    }
                }
            }

            $this->context->buildViolation($constraint->mimeTypesMessage)
                ->setParameter('{{ file }}', $this->formatValue($path))
                ->setParameter('{{ type }}', $this->formatValue($mime))
                ->setParameter('{{ types }}', $this->formatValues($mimeTypes))
                ->setParameter('{{ name }}', $this->formatValue($basename))
                ->setCode(File::INVALID_MIME_TYPE_ERROR)
                ->addViolation();
        }
    }

    private static function moreDecimalsThan(string $double, int $numberOfDecimals): bool
    {
        return \strlen($double) > \strlen(round($double, $numberOfDecimals));
    }

    /**
     * Convert the limit to the smallest possible number
     * (i.e. try "MB", then "kB", then "bytes").
     */
    private function factorizeSizes(int $size, int|float $limit, bool $binaryFormat): array
    {
        if ($binaryFormat) {
            $coef = self::MIB_BYTES;
            $coefFactor = self::KIB_BYTES;
        } else {
            $coef = self::MB_BYTES;
            $coefFactor = self::KB_BYTES;
        }

        // If $limit < $coef, $limitAsString could be < 1 with less than 3 decimals.
        // In this case, we would end up displaying an allowed size < 1 (eg: 0.1 MB).
        // It looks better to keep on factorizing (to display 100 kB for example).
        while ($limit < $coef) {
            $coef /= $coefFactor;
        }

        $limitAsString = (string) ($limit / $coef);

        // Restrict the limit to 2 decimals (without rounding! we
        // need the precise value)
        while (self::moreDecimalsThan($limitAsString, 2)) {
            $coef /= $coefFactor;
            $limitAsString = (string) ($limit / $coef);
        }

        // Convert size to the same measure, but round to 2 decimals
        $sizeAsString = (string) round($size / $coef, 2);

        // If the size and limit produce the same string output
        // (due to rounding), reduce the coefficient
        while ($sizeAsString === $limitAsString) {
            $coef /= $coefFactor;
            $limitAsString = (string) ($limit / $coef);
            $sizeAsString = (string) round($size / $coef, 2);
        }

        return [$sizeAsString, $limitAsString, self::SUFFICES[$coef]];
    }
}


text:
Simple Layout

        This simple layout below has 3 panels, none of them are resizable. Layouts can be completely transparent, however, in the
        example below I have define border and background to see its structure.
        The layout listens window resize event and resizes itself when window is resized. Try to resize the window and
        see how layout picks up the new size.


text:
import config from '../config';

import gulp from 'gulp';

gulp.task('clean', function(cb) {
    require('del')([config.build], {
        force: true
    }, cb);
});


text:
* Offer new class-based API and object-based arguments
* Version 0.11

## Oct 23, 2013

* Support for parent selection via `^`
* Access current path via `@path` in test statements
* Allowing for multi-statement evals
* Performance improvements
* Version 0.10

## Mar 28, 2012

* Support a sandbox arg to eval
* Use vm.runInNewContext in place of eval
* Version 0.9.0


text:
We are proud to be part of the Open Knowledge and Open Source movement.
We have been using Open Source Software throughout our career and want to contribute back.
We believe that developers and operators should not have to fiddle with hard to understand configuration files,
runtime and installation. Our vision is to enhance the developer and operator ecosystem with easy to use
and secure Open Source Software, and we need your help to achieve that!

Support ORY's Open Source Software on [patreon](https://patreon.com/user?u=4298803)!

## Patrons

1. Wayne Robinson @waynerobinson


text:
            Profile

                {{vm.savedUser.username}}

                        Follow

                    <form action="/api/project/uploadProfile"   method="post" enctype="multipart/form-data">
                        <input  name="myFile"    type="file"  class="form-control"/>
                        <input  name="userId"  value="{{vm.userId}}"  style="display: none"/>
                        <input  name="width"     value="100%" style="display: none"/>
                        <button type="submit"    class="btn btn-block btn-primary">Upload Profile Image</button>
                    </form>

                Logout

                            About

                            Following

                            Followers

                            Reps

                            Edit

                            Account Settings

                                    {{info.label}}

                                    {{info.value}}

{{user.username}}

                                        You are not currently following any users.

                                        This user is not following anyone.

{{user.username}}

                                        No users are currently following you.

                                        This user has no followers.

{{rep.name}}

                                        You are not currently following any representatives.

                                        This user is not following anyone.

                                    {{vm.message}}

                                    {{vm.errorMessage}}

                            <form novalidate name="vm.editForm" ng-submit="vm.update()">

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

                                        Email
                                        <input type="email"
                                               class="form-control"
                                               id="email"
                                               name="email"
                                               ng-model="vm.user.email"
                                               placeholder="alice@wonderland.com">

                                        Emails must have an @ sign

                                        First Name
                                        <input type="text"
                                               class="form-control"
                                               id="first-name"
                                               name="firstName"
                                               ng-model="vm.user.firstName"
                                               placeholder="Alice">

                                        Last Name
                                        <input type="text"
                                               class="form-control"
                                               id="last-name"
                                               name="lastName"
                                               ng-model="vm.user.lastName"
                                               placeholder="Wonderland">

                                        Phone Number
                                        <input type="tel"
                                               class="form-control"
                                               id="phone"
                                               ng-minlength="12"
                                               name="phone"
                                               ng-model="vm.user.phone"
                                               placeholder="203-451-1233">

                                            Phone numbers should be in the form XXX-XXX-XXXX

                                <input class="btn btn-success btn-block"
                                       type="submit"
                                       id="submit"
                                       value="Update" />
                            </form>

                                {{vm.updatePasswordSuccess}}

                                    Old Password
                                    <input type="password"
                                           class="form-control"
                                           id="old-password"
                                           ng-model="vm.password.old"
                                           placeholder="Old Password">

                                    {{vm.invalidOldPassword}}

                                    New Password
                                    <input type="password"
                                           class="form-control"
                                           id="new-password"
                                           ng-model="vm.password.new"
                                           placeholder="New Password">

                                    Verify Password
                                    <input type="password"
                                           class="form-control"
                                           id="verify-password"
                                           ng-model="vm.password.verify"
                                           placeholder="Verify Password">

                                      {{vm.updatePasswordFailed}}

                                Update


text:
<?php

class Google_Service_Appengine_RepairApplicationRequest extends Google_Model
{
}


text:
extern int verbosity;

void debug_log(const char* fmt, ...)
	__attribute__((format(printf, 1, 2)));

struct pal {
	// Brightness of panels from 1-8
	int panel_brightness;

	// Frame buffer for effects
	char* treads_buf; // Length: NUM_TREADS
	char* barrel_buf; // Length: NUM_BARREL
	char* panels_buf; // Length: NUM_PANELS

	// Wheel encoder: dereference to get the current values
	volatile unsigned int* enc_timer; // Number of ADC reads
	volatile unsigned int* enc_raw;   // Raw ADC value
	volatile unsigned int* enc_min;   // Min value for current half-tick
	volatile unsigned int* enc_max;   // Max value for current half-tick
	volatile unsigned int* enc_ticks; // Number of encoder ticks
	volatile unsigned int* enc_speed; // Width of last encoder tick
};

struct settings {
	long                brightness;
	long                manual_tick;
	long                idle_interval;
	long                alpha;
	long                manual_toggle;
	long                screen_saver_toggle;
};

extern struct settings settings;

struct pal* pal_init(unsigned int enc_thresh, unsigned int enc_delay, unsigned int ema_pow);

void pal_treads_write();
void pal_barrel_write();
void pal_panels_write();

void pal_destroy();

int pal_clock_gettime(struct timespec* tv);

int settings_load();


text:
module Molecular
  class Mailer < ActionMailer::Base
    def campaign_email(id, campaign, recipient)
      mail(headers_for(campaign, recipient)) do |format|
        format.text { render plain: campaign.body }
        format.html { render html: campaign.body.html_safe }
      end

      custom_args = {
        subscription_id: id
      }

      # Mandrill custom headers
      headers['X-MC-Metadata'] = custom_args.to_json

      # Sendgrid custom headers
      headers['X-SMTPAPI'] = {unique_args: custom_args}.to_json
    end

    private
      def headers_for(campaign, recipient)
        {
          to: recipient.email,
          subject: campaign.subject,
          from: mailer_sender(campaign),
          reply_to: campaign.from
        }
      end

      def mailer_sender(campaign)
        if Molecular.mailer_sender.is_a?(Proc)
          Molecular.mailer_sender.call(campaign)
        else
          Molecular.mailer_sender
        end
      end
  end
end


text:
using System;
using System.IO;
using System.Linq;

namespace Shared.Helper.Test
{
    public static class FileHelper
    {
        public static string GetTestFilePath(string relativeFolder, string testFile)
        {
            var startupPath = AppDomain.CurrentDomain.BaseDirectory;
            var pathItems = startupPath.Split(Path.DirectorySeparatorChar);
            var projectPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathItems.Take(pathItems.Length - 3));
            return Path.Combine(projectPath, relativeFolder, testFile);
        }

        public static byte[] GetTestFileBytes(string testFile)
        {
            return File.ReadAllBytes(GetTestFilePath("TestFiles", testFile));
        }

        public static byte[] GetEmailTestFileBytes(string testFile)
        {
            return File.ReadAllBytes(GetTestFilePath(@"TestFiles\EmailtestFiles", testFile));
        }
    }
}


text:
try:
    from urllib import parse
except ImportError:  # above is available in py3+, below is py2.7
    import urlparse as parse

from selenium import __version__
from selenium.webdriver.remote.remote_connection import (
    RemoteConnection,
)

def test_get_remote_connection_headers_defaults():
    url = 'http://remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
    assert 'Authorization' not in headers.keys()
    assert 'Connection' not in headers.keys()
    assert headers.get('Accept') == 'application/json'
    assert headers.get('Content-Type') == 'application/json;charset=UTF-8'
    assert headers.get('User-Agent').startswith("selenium/%s (python " % __version__)
    assert headers.get('User-Agent').split(' ')[-1] in {'windows)', 'mac)', 'linux)'}

def test_get_remote_connection_headers_adds_auth_header_if_pass():
    url = 'http://user:pass@remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
    assert headers.get('Authorization') == 'Basic dXNlcjpwYXNz'

def test_get_remote_connection_headers_adds_keep_alive_if_requested():
    url = 'http://remote'
    headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url), keep_alive=True)
    assert headers.get('Connection') == 'keep-alive'

class MockResponse:
    code = 200
    headers = []

    def read(self):
        return b"{}"

    def close(self):
        pass

    def getheader(self, *args, **kwargs):
        pass

def test_remote_connection_adds_connection_headers_from_get_remote_connection_headers(mocker):
    test_headers = {'FOO': 'bar', 'Content-Type': 'json'}
    expected_request_headers = {'Foo': 'bar', 'Content-type': 'json'}

    # Stub out the get_remote_connection_headers method to return something testable
    mocker.patch(
        'selenium.webdriver.remote.remote_connection.RemoteConnection.get_remote_connection_headers'
    ).return_value = test_headers

    # Stub out response
    try:
        mock_open = mocker.patch('urllib.request.OpenerDirector.open')
    except ImportError:
        mock_open = mocker.patch('urllib2.OpenerDirector.open')

    def assert_header_added(request, timeout):
        assert request.headers == expected_request_headers
        return MockResponse()

    mock_open.side_effect = assert_header_added

    RemoteConnection('http://remote', resolve_ip=False).execute('status', {})


text:
using System.Diagnostics.Contracts;

class A
{
  public void Foo([JetBrains.Annotations.CanBeNull]string s)
  {
    Contract.Requires(s != null);
  }
}


text:
from __future__ import unicode_literals

from django.contrib.auth.models import User
from django.db import models
import uuid

# Create your models here.

class Account(models.Model):

    displayName = models.CharField(blank=False, max_length=255)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    username = models.CharField(max_length=255, blank=False)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facebook = models.CharField(max_length=255, blank=False)

    def __str__(self):
        return self.user.username


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>connect</title>
</head>
<body>
    <img src="1.jpg" alt="" />
</body>
</html>


text:
package desmoj.core.simulator;

import java.util.LinkedList;
import java.util.List;

public class Schedulable extends ModelComponent {

    /**
     * A list containing all scheduled entries for this Schedulable in future.
     */
    protected List<EventNote> _schedule;

	/**
	 * Constructs a Schedulable object with the given name. Note that to
	 * identify the multiple objects that can be created of one type of
	 * Schedulable, each has a unique number added to its name as a suffix. The
	 * numbers represent the amount of objects being created with the same name.
	 *
	 * @param name
	 *            java.lang.String : The name of the new Schedulable object
	 * @param owner
	 *            Model : The owner of this Schedulable object
	 */
	public Schedulable(Model owner, String name, boolean showInTrace) {

		// create modelcomponent with the checked and registered name
		super(owner, owner.getExperiment().getNameCatalog()
				.registeredName(name), showInTrace);
		this._schedule = new LinkedList<EventNote>();
	}

    /**
     * Removes all events scheduled for this entity from the event-list.
     * The Entity will not become active until scheduled again.
     */
    public void cancel()
    {
        if (!isScheduled()) {
            sendWarning("Can't cancel Schedulable! Command ignored.",
                    "Schedulable : " + getName() + " Method: void cancel()",
                    "The Schedulable to be canceled is not scheduled.",
                    "Use method isSchedule() to test if the Schedulable "
                            + "is scheduled and thus can be canceled or not.");
            return; // was already scheduled
        }

        // removes all scheduled events for this entity by using global event-list
        while(!_schedule.isEmpty())
        {
            //EventNote firstNote = this.getModel().getExperiment().getScheduler().evList.firstNote();
            EventNote firstNote = _schedule.get(0);

            if (currentlySendTraceNotes()) {
                TimeInstant time = firstNote.getTime();
                if (this == current()) {
                    if (time == presentTime())
                        sendTraceNote("cancels scheduled Event " + firstNote.getEvent() + " for itself, which was scheduled now");
                    else
                        sendTraceNote("cancels scheduled Event " + firstNote.getEvent() + " for itself, which was scheduled at " + time);
                } else {
                    if (time == presentTime())
                        sendTraceNote("cancels scheduled Event " + firstNote.getEvent() + " for " + this.getName() + ", which was scheduled now");
                    else
                        sendTraceNote("cancels scheduled Event " + firstNote.getEvent() + " for " + this.getName() + ", which was scheduled at " + time);
                }
            }
            this.getModel().getExperiment().getScheduler().evList.remove(firstNote);
        }
    }

    /**
     * Returns a list of EventNote associated to this Entity object. If the
     * Entity object is not currently scheduled, null will be
     * returned. Remind that all different Event classes can be included.
     *
     * @return List<EventNote> : The event-notes associated to the entity or
     *         null if Entity is not currently scheduled
     */
    List<EventNote> getEventNotes()
    {
        return _schedule;

    }

	/**
	 * Shows if this Schedulable is the currently active object.
	 *
	 * @return boolean :true if this Schedulable is the currently
	 *         active, false otherwise
	 */
	public boolean isCurrent() {

		return this.equals(getModel().getExperiment().getScheduler()
				.getCurrentSchedulable());

	}

    /**
     * Tests if this entity has already been scheduled.
     *
     * @return boolean :true if already scheduled,
     *         false otherwise
     */
    public boolean isScheduled() {

        // Not associated to EventNote if not scheduled
        return (!_schedule.isEmpty());

    }

    /**
     * Removes an event-note from the internal list
     *
     * * @param note
     *            EventNote : The EventNote to be removed
     */
    void removeEventNote(EventNote note)
    {
        _schedule.remove(note); // only removes Event in local list

    }

	/**
	 * Allows to rename a Schedulable object while keeping its internally added
	 * serial number to keep track of the individual object. Note that invalid
	 * string parameters will result in renaming the Schedulable to 'unnamed'.
	 *
	 * @param newName
	 *            java.lang.String : The Schedulable's new name
	 */
	public void rename(String newName) {

		super.rename(getModel().getExperiment().getNameCatalog()
				.registeredName(newName));

	}

    /**
     * Re-schedules the Schedulable by shifting all EventNote by a specified
     * TimeSpan.
     *
     * @param dt
     *            TimeSpan : The offset to the current simulation time at which
     *            this Schedulable is to be re-scheduled
     */
    public void reSchedule(TimeSpan dt)
    {
        if (dt == null) {
            sendWarning("Can't reSchedule Schedulable! Command ingnored.",
                    "Schedulable : " + getName()
                            + " Method: reSchedule(TimeSpan dt)",
                    "The simulation time given as parameter is a null "
                            + "reference.",
                    "Be sure to have a valid TimeSpan reference before calling "
                            + "this method.");
            return; // no proper parameter
        }

        if (!isScheduled()) {
            sendWarning("Can't reSchedule Schedulable! Command ingnored.",
                    "Schedulable : " + getName()
                            + " Method: reSchedule(TimeSpan dt)",
                    "The Schedulable is not scheduled, thus unable to be "
                            + "reScheduled..",
                    "Be sure that the Schedulable is currently scheduled "
                            + "before calling this method.");
            return; // no proper parameter
        }

        // create list with new events and remove old events
        EventNote newNote = null;
        List<EventNote> oldNotes = new LinkedList<EventNote>(_schedule);
        List<EventNote> newNotes = new LinkedList<EventNote>();
        for (EventNote oldNote : oldNotes)
        {
            newNote = oldNote.copy(current()); // copy EventNote
            newNote.setTime(TimeOperations.add(oldNote.getTime(), dt)); // shift it
            newNotes.add(newNote); // save it to new list
            this.getModel().getExperiment().getScheduler().evList.remove(oldNote); // remove original event-note local and global

            if (currentlySendTraceNotes()) {
                    TimeInstant timeOld = oldNote.getTime();
                    TimeInstant timeNew = newNote.getTime();
                    if (this == current()) {
                        if (timeOld == presentTime())
                            sendTraceNote("reschedules " + newNote.getEvent() + " for itself, which was scheduled now, to " + timeNew);
                        else
                            sendTraceNote("reschedules " + newNote.getEvent() + " for itself, which was scheduled at " + timeOld + ", to " + timeNew);
                    } else {
                        if (timeOld == presentTime())
                            sendTraceNote("reschedules " + newNote.getEvent() + " for " + this.getName() + ", which was scheduled now, to " + timeNew);
                        else
                            sendTraceNote("reschedules " + newNote.getEvent() + " for " + this.getName() + ", which was scheduled at " + timeOld + ", to " + timeNew);
                    }
             }

        }

        //insert temp to schedule
        for (EventNote ev : newNotes)
        {
            // insert to GLOBAL list, which inserts to local one
            this.getModel().getExperiment().getScheduler().evList.insert(ev);
        }

    }

    /**
     * Re-schedules the Schedulable to some other point in simulation time
     * (which should be different form the instant at which is a scheduled
     * at the moment).
     *
     * @param time
     *            TimeInstant : The simulation time at which
     *            this entity is to be re-scheduled
     */
    public void reSchedule(TimeInstant time) {

        if (time == null) {
            sendWarning("Can't reSchedule enitty! Command ingnored.",
                    "Entity : " + getName()
                            + " Method: reSchedule(TimeInstant time)",
                    "The simulation time given as parameter is a null "
                            + "reference.",
                    "Be sure to have a valid TimeSpan reference before calling "
                            + "this method.");
            return; // no proper parameter
        }

        if (!isScheduled()) {
            sendWarning("Can't reSchedule Schedulable! Command ingnored.",
                    "Entity : " + getName()
                            + " Method: reSchedule(TimeInstant time)",
                    "The Entity is not scheduled, thus unable to be "
                            + "reScheduled.",
                    "Be sure that the entity is currently scheduled "
                            + "before calling this method.");
            return; // no proper parameter
        }

        if (_schedule.size()>1) {
            sendWarning("Can't reSchedule Entity! Command ingnored.",
                    "Entity : " + getName()
                            + " Method: reSchedule(TimeInstant time)",
                    "The Entity is scheduled more then once, thus unable to be "
                            + "reScheduled.",
                    "Be sure that the entity is only scheduled once"
                            + "before calling this method.");
            return; // no proper parameter
        }

        if (TimeInstant.isBefore(time, this.presentTime())) {
                    sendWarning(
                            "Can't reschedule Entity at given time! "
                                    + "Command ignored.",
                            "Entity : "
                                    + getName()
                                    + " Method: reSchedule(TimeInstant time)",
                            "The instant given is in the past.",
                            "To reschedule an entity, use a TimeInstant no earlier than the present time. "
                                    + "The present time can be obtained using the "
                                    + "presentTime() method");
            return;
            // I can't be rescheduled, TimeInstant has already passed.
        }

        if (currentlySendTraceNotes()) {
            if (this == current()) {
                if (time == presentTime())
                    sendTraceNote("reschedules itself now");
                else
                    sendTraceNote("reschedules itself at "
                            + time);
            } else {
                if (time == presentTime())
                    sendTraceNote("reschedules '" + getName() + "' now");
                else
                    sendTraceNote("reschedules '" + getName() + "' at "
                            + time);
            }
        }

        getModel().getExperiment().getScheduler().reSchedule(this, time);

        if (currentlySendDebugNotes()) {
            sendDebugNote("reschedules on EventList
"
                    + getModel().getExperiment().getScheduler().toString());
        }

    }

	/**
     * @deprecated Use reSchedule(TimeSpan dt).
     * Re-schedules the Schedulable at some other point in simulation time than
     * it already had been scheduled before.
     *
     * @param dt
     *            TimeSpan : The offset to the current simulation time at which
     *            this Schedulable is to be re-scheduled
     */
    public void reSchedule(SimTime dt) {

        reSchedule(SimTime.toTimeSpan(dt));

    }

    /**
     * @deprecated Returns the point of simulation time this Schedulable is scheduled at.
     * Returns null, if the entity has not been scheduled and thus can not return an
     * appropriate point of simulation time.
     *
     * Use scheduleNext() for next TimeInstant where an event-note lists this entity.
     *
     * @return TimeInstant : The point of simulation time this Schedulable is
     *         scheduled at or null otherwise
     */
    public TimeInstant scheduledAt() {

        return scheduledNext(); //use scheduleNext()

    }

    /**
     * Returns the next point of time this entity is scheduled.
     *
     * @return TimeInstant : The point of simulation time the next Entity
     * is schedule or null otherwise
     */
    public TimeInstant scheduledNext()
    {
        if (!isScheduled())
        {
            return null; // if not scheduled, there is no point of time
        }
        else
        {
            return _schedule.get(0).getTime();
        }
    }

    /**
     * Adds an event-note to the Schedulable.
     */
    void addEventNote(EventNote note)
    {
        if (!_schedule.contains(note)) {
            _schedule.add(note);
            java.util.Collections.sort(_schedule);
        }
    }

    /**
     * Creates and returns a copy of this Schedulable.
     * Note that subclasses have to implement the interface
     * java.lang.Cloneable to actually use this method as
     * otherwise, a CloneNotSupportedException will be thrown.
     *
     * @return Schedulable : A copy of this Schedulable.
     */
    protected Schedulable clone() throws CloneNotSupportedException {
        Schedulable c = (Schedulable) super.clone();
        NameCatalog nc = this.getModel().getExperiment().getNameCatalog();
        c.rename(nc.getNameWithoutSuffix(this.getName()));
        c._schedule = new LinkedList<EventNote>();
        return c;
    }
}


text:
<resources>
    <style name="Button">
        <item name="android:layout_margin">8dp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:backgroundTint">?attr/colorAccent</item>
    </style>
</resources>


text:
package org.eclipse.rdf4j.testsuite.repository.optimistic;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.common.transaction.IsolationLevel;
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.base.CoreDatatype;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.UnknownTransactionStateException;
import org.eclipse.rdf4j.testsuite.repository.OptimisticIsolationTest;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test that the Repository correctly supports claimed isolation levels.
 *
 * @author James Leigh
 */
public class IsolationLevelTest {

	@BeforeClass
	public static void setUpClass() throws Exception {
		System.setProperty("org.eclipse.rdf4j.repository.debug", "true");
	}

	@AfterClass
	public static void afterClass() throws Exception {
		System.setProperty("org.eclipse.rdf4j.repository.debug", "false");
	}

	private final Logger logger = LoggerFactory.getLogger(IsolationLevelTest.class);

	/*-----------*
	 * Variables *
	 *-----------*/

	protected Repository store;

	private String failedMessage;

	private Throwable failed;

	/*---------*
	 * Methods *
	 *---------*/

	@Before
	public void setUp() throws Exception {
		store = OptimisticIsolationTest.getEmptyInitializedRepository(IsolationLevelTest.class);
		failed = null;
	}

	@After
	public void tearDown() throws Exception {
		store.shutDown();
	}

	protected boolean isSupported(IsolationLevels level) throws RepositoryException {
		try (RepositoryConnection con = store.getConnection()) {
			try {
				con.begin(level);
				return true;
			} finally {
				con.rollback();
			}
		} catch (UnknownTransactionStateException e) {
			return false;
		}
	}

	@Test
	public void testNone() throws Exception {
		readPending(IsolationLevels.NONE);
	}

	@Test
	public void testReadUncommitted() throws Exception {
		rollbackTriple(IsolationLevels.READ_UNCOMMITTED);
		readPending(IsolationLevels.READ_UNCOMMITTED);
	}

	@Test
	public void testReadCommitted() throws Exception {
		readCommitted(IsolationLevels.READ_COMMITTED);
		rollbackTriple(IsolationLevels.READ_COMMITTED);
		readPending(IsolationLevels.READ_COMMITTED);
	}

	@Test
	public void testSnapshotRead() throws Exception {
		if (isSupported(IsolationLevels.SNAPSHOT_READ)) {
			snapshotRead(IsolationLevels.SNAPSHOT_READ);
			readCommitted(IsolationLevels.SNAPSHOT_READ);
			rollbackTriple(IsolationLevels.SNAPSHOT_READ);
			readPending(IsolationLevels.SNAPSHOT_READ);
		} else {
			logger.warn("{} does not support {}", store, IsolationLevels.SNAPSHOT_READ);
		}
	}

	@Test
	public void testSnapshot() throws Exception {
		if (isSupported(IsolationLevels.SNAPSHOT)) {
			snapshot(IsolationLevels.SNAPSHOT);
			snapshotRead(IsolationLevels.SNAPSHOT);
			repeatableRead(IsolationLevels.SNAPSHOT);
			readCommitted(IsolationLevels.SNAPSHOT);
			rollbackTriple(IsolationLevels.SNAPSHOT);
			readPending(IsolationLevels.SNAPSHOT);
		} else {
			logger.warn("{} does not support {}", store, IsolationLevels.SNAPSHOT);
		}
	}

	@Test
	public void testSerializable() throws Exception {

		if (isSupported(IsolationLevels.SERIALIZABLE)) {
			serializable(IsolationLevels.SERIALIZABLE);
			snapshot(IsolationLevels.SERIALIZABLE);
			snapshotRead(IsolationLevels.SERIALIZABLE);
			repeatableRead(IsolationLevels.SERIALIZABLE);
			readCommitted(IsolationLevels.SERIALIZABLE);
			rollbackTriple(IsolationLevels.SERIALIZABLE);
			readPending(IsolationLevels.SERIALIZABLE);
		} else {
			logger.warn("{} does not support {}", store, IsolationLevels.SERIALIZABLE);
		}
	}

	/**
	 * Every connection must support reading it own changes
	 */
	private void readPending(IsolationLevel level) throws RepositoryException {
		clear(store);
		try (RepositoryConnection con = store.getConnection()) {
			con.begin(level);
			con.add(RDF.NIL, RDF.TYPE, RDF.LIST);
			assertEquals(1, count(con, RDF.NIL, RDF.TYPE, RDF.LIST, false));
			con.remove(RDF.NIL, RDF.TYPE, RDF.LIST);
			con.commit();
		}
	}

	/**
	 * Supports rolling back added triples
	 */
	private void rollbackTriple(IsolationLevel level) throws RepositoryException {
		clear(store);
		try (RepositoryConnection con = store.getConnection()) {
			con.begin(level);
			con.add(RDF.NIL, RDF.TYPE, RDF.LIST);
			con.rollback();
			assertEquals(0, count(con, RDF.NIL, RDF.TYPE, RDF.LIST, false));
		}
	}

	/**
	 * Read operations must not see uncommitted changes
	 */
	private void readCommitted(final IsolationLevel level) throws Exception {
		clear(store);
		final CountDownLatch start = new CountDownLatch(2);
		final CountDownLatch begin = new CountDownLatch(1);
		final CountDownLatch uncommitted = new CountDownLatch(1);
		Thread writer = new Thread(() -> {
			try (RepositoryConnection write = store.getConnection()) {
				start.countDown();
				start.await();
				write.begin(level);
				write.add(RDF.NIL, RDF.TYPE, RDF.LIST);
				begin.countDown();
				uncommitted.await(1, TimeUnit.SECONDS);
				write.rollback();
			} catch (Throwable e) {
				fail("Writer failed", e);
			}
		});
		Thread reader = new Thread(() -> {
			try (RepositoryConnection read = store.getConnection()) {
				start.countDown();
				start.await();
				begin.await();
				read.begin(level);
				// must not read uncommitted changes
				long counted = count(read, RDF.NIL, RDF.TYPE, RDF.LIST, false);
				uncommitted.countDown();
				try {
					read.commit();
				} catch (RepositoryException e) {
					// it is okay to abort after a dirty read
					// e.printStackTrace();
					return;
				}
				// not read if transaction is consistent
				assertEquals(0, counted);
			} catch (Throwable e) {
				fail("Reader failed", e);
			}
		});
		reader.start();
		writer.start();
		reader.join();
		writer.join();
		assertNotFailed();
	}

	/**
	 * Any statement read in a transaction must remain present until the transaction is over
	 */
	private void repeatableRead(final IsolationLevels level) throws Exception {
		clear(store);
		final CountDownLatch start = new CountDownLatch(2);
		final CountDownLatch begin = new CountDownLatch(1);
		final CountDownLatch observed = new CountDownLatch(1);
		final CountDownLatch changed = new CountDownLatch(1);
		Thread writer = new Thread(() -> {
			try (RepositoryConnection write = store.getConnection()) {
				start.countDown();
				start.await();
				write.begin(level);
				write.add(RDF.NIL, RDF.TYPE, RDF.LIST);
				write.commit();

				begin.countDown();
				observed.await();

				write.begin(level);
				write.remove(RDF.NIL, RDF.TYPE, RDF.LIST);
				write.commit();
				changed.countDown();
			} catch (Throwable e) {
				fail("Writer failed", e);
			}
		});
		Thread reader = new Thread(() -> {
			try (RepositoryConnection read = store.getConnection()) {
				start.countDown();
				start.await();
				begin.await();
				read.begin(level);
				long first = count(read, RDF.NIL, RDF.TYPE, RDF.LIST, false);
				assertEquals(1, first);
				observed.countDown();
				changed.await(1, TimeUnit.SECONDS);
				// observed statements must continue to exist
				long second = count(read, RDF.NIL, RDF.TYPE, RDF.LIST, false);
				try {
					read.commit();
				} catch (RepositoryException e) {
					// it is okay to abort on inconsistency
					// e.printStackTrace();
					read.rollback();
					return;
				}
				// statement must continue to exist if transaction consistent
				assertEquals(first, second);
			} catch (Throwable e) {
				fail("Reader failed", e);
			}
		});
		reader.start();
		writer.start();
		reader.join();
		writer.join();
		assertNotFailed();
	}

	/**
	 * Query results must not include statements added after the first result is read
	 */
	private void snapshotRead(IsolationLevel level) throws RepositoryException {
		clear(store);
		try (RepositoryConnection con = store.getConnection()) {
			con.begin(level);
			int size = 1;
			for (int i = 0; i < size; i++) {
				insertTestStatement(con, i);
			}
			int counter = 0;
			try (CloseableIteration<? extends Statement, RepositoryException> stmts = con.getStatements(null, null,
					null, false)) {
				while (stmts.hasNext()) {
					Statement st = stmts.next();
					counter++;
					if (counter < size) {
						// remove observed statement to force new state
						con.remove(st.getSubject(), st.getPredicate(), st.getObject(), st.getContext());
						insertTestStatement(con, size + counter);
						insertTestStatement(con, size + size + counter);
					}
				}
			}
			try {
				con.commit();
			} catch (RepositoryException e) {
				// it is okay to abort after a dirty read
				e.printStackTrace();
				return;
			}
			assertEquals(size, counter);
		}
	}

	/**
	 * Reader observes the complete state of the store and ensure that does not change
	 */
	private void snapshot(final IsolationLevels level) throws Exception {
		clear(store);
		final CountDownLatch start = new CountDownLatch(2);
		final CountDownLatch begin = new CountDownLatch(1);
		final CountDownLatch observed = new CountDownLatch(1);
		final CountDownLatch changed = new CountDownLatch(1);
		Thread writer = new Thread(() -> {
			try {
				try (RepositoryConnection write = store.getConnection()) {
					start.countDown();
					start.await();
					write.begin(level);
					insertTestStatement(write, 1);
					write.commit();

					begin.countDown();
					observed.await(1, TimeUnit.SECONDS);

					write.begin(level);
					insertTestStatement(write, 2);
					write.commit();
					changed.countDown();
				}
			} catch (Throwable e) {
				fail("Writer failed", e);
			}
		});
		Thread reader = new Thread(() -> {
			try (RepositoryConnection read = store.getConnection()) {
				start.countDown();
				start.await();
				begin.await();
				read.begin(level);
				long first = count(read, null, null, null, false);
				observed.countDown();
				changed.await(1, TimeUnit.SECONDS);
				// new statements must not be observed
				long second = count(read, null, null, null, false);
				try {
					read.commit();
				} catch (RepositoryException e) {
					// it is okay to abort on inconsistency
					// e.printStackTrace();
					read.rollback();
					return;
				}
				// store must not change if transaction consistent
				assertEquals(first, second);
			} catch (Throwable e) {
				fail("Reader failed", e);
			}
		});
		reader.start();
		writer.start();
		reader.join();
		writer.join();
		assertNotFailed();
	}

	/**
	 * Two transactions read a value and replace it
	 */
	private void serializable(final IsolationLevels level) throws Exception {
		clear(store);
		final ValueFactory vf = store.getValueFactory();
		final IRI subj = vf.createIRI("http://test#s");
		final IRI pred = vf.createIRI("http://test#p");
		try (RepositoryConnection prep = store.getConnection()) {
			prep.begin(level);
			prep.add(subj, pred, vf.createLiteral(1));
			prep.commit();
		}
		final CountDownLatch start = new CountDownLatch(2);
		final CountDownLatch observed = new CountDownLatch(2);
		Thread t1 = incrementBy(start, observed, level, vf, subj, pred, 3);
		Thread t2 = incrementBy(start, observed, level, vf, subj, pred, 5);
		t2.start();
		t1.start();
		t2.join();
		t1.join();
		assertNotFailed();
		try (RepositoryConnection check = store.getConnection()) {
			check.begin(level);
			Literal lit = readLiteral(check, subj, pred);
			int val = lit.intValue();
			// val could be 4 or 6 if one transaction was aborted
			if (val != 4 && val != 6) {
				assertEquals(9, val);
			}
			check.commit();
		}
	}

	protected Thread incrementBy(final CountDownLatch start, final CountDownLatch observed, final IsolationLevels level,
			final ValueFactory vf, final IRI subj, final IRI pred, final int by) {
		return new Thread(() -> {
			try (RepositoryConnection con = store.getConnection()) {
				start.countDown();
				start.await();
				con.begin(level);
				Literal o1 = readLiteral(con, subj, pred);
				observed.countDown();
				observed.await(1, TimeUnit.SECONDS);
				con.remove(subj, pred, o1);
				con.add(subj, pred, vf.createLiteral(o1.intValue() + by));
				try {
					con.commit();
				} catch (RepositoryException e) {
					// it is okay to abort on conflict
					// e.printStackTrace();
					con.rollback();
				}
			} catch (Throwable e) {
				fail("Increment " + by + " failed", e);
			}
		});
	}

	private void clear(Repository store) throws RepositoryException {
		try (RepositoryConnection con = store.getConnection()) {
			con.begin();
			con.clear();
			con.commit();
		}
	}

	protected long count(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean includeInferred,
			Resource... contexts) throws RepositoryException {
		try (CloseableIteration<Statement, RepositoryException> stmts = con.getStatements(subj, pred, obj,
				includeInferred, contexts)) {
			long counter = 0;
			while (stmts.hasNext()) {
				stmts.next();
				counter++;
			}
			return counter;
		}
	}

	protected Literal readLiteral(RepositoryConnection con, final IRI subj, final IRI pred) throws RepositoryException {
		try (CloseableIteration<? extends Statement, RepositoryException> stmts = con.getStatements(subj, pred, null,
				false)) {
			if (!stmts.hasNext()) {
				return null;
			}
			Value obj = stmts.next().getObject();
			if (stmts.hasNext()) {
				org.junit.Assert.fail("multiple literals: " + obj + " and " + stmts.next());
			}
			return (Literal) obj;
		}
	}

	protected void insertTestStatement(RepositoryConnection connection, int i) throws RepositoryException {
		ValueFactory vf = connection.getValueFactory();
		Literal lit = vf.createLiteral(Integer.toString(i), CoreDatatype.XSD.INTEGER);
		connection.add(vf.createIRI("http://test#s" + i), vf.createIRI("http://test#p"), lit,
				vf.createIRI("http://test#context_" + i));
	}

	protected synchronized void fail(String message, Throwable t) {
		failedMessage = message;
		failed = t;
	}

	protected synchronized void assertNotFailed() {
		if (failed != null) {
			throw (AssertionError) new AssertionError(failedMessage).initCause(failed);
		}
	}

}


text:
@import url("../main.css");

/* outgoing */

.outgoingItem .timeStamp {
	color:#b3cf77;
}

.outgoingItem .myBubble .indicator {
	background:url("../images/greenIndicator.png") no-repeat top left;
}

.outgoingItem .tableBubble .tl {
	background:url("../images/greenCurves.png") no-repeat top left;
}

.outgoingItem .tableBubble .tr {
	background:url("../images/greenCurves.png") no-repeat top right;
}

.outgoingItem .tableBubble .head {
	background:url("../images/greenCurves.png") no-repeat -10px 0;
}

.outgoingItem .tableBubble .message {
	background:url("../images/greenBackground.png") repeat-y top left;
}

.outgoingItem .tableBubble .messageRight {
	background:url("../images/greenBackground.png") repeat-y top right;
}

.outgoingItem .tableBubble .bl {
	background:url("../images/greenCurves.png") no-repeat bottom left;
}

.outgoingItem .tableBubble .br {
	background:url("../images/greenCurves.png") no-repeat bottom right;
}

.outgoingItem .followUp {
	background-color:#e2efc4;
	border-bottom:1px solid #fff;
}

/*incoming */

.incomingItem .timeStamp {
	color:#d2d2d2;
}

.incomingItem .myBubble .indicator {
	background:url("../images/steelIndicator.png") no-repeat top left;
}

.incomingItem .tableBubble .tl {
	background:url("../images/steelCurves.png") no-repeat top left;
}

.incomingItem .tableBubble .tr {
	background:url("../images/steelCurves.png") no-repeat top right;
}

.incomingItem .tableBubble .head {
	background:url("../images/steelCurves.png") no-repeat -10px 0;
}

.incomingItem .tableBubble .message {
	background:url("../images/steelBackground.png") repeat-y top left;
}

.incomingItem .tableBubble .messageRight {
	background:url("../images/steelBackground.png") repeat-y top right;
}

.incomingItem .tableBubble .bl {
	background:url("../images/steelCurves.png") no-repeat bottom left;
}

.incomingItem .tableBubble .br {
	background:url("../images/steelCurves.png") no-repeat bottom right;
}

.incomingItem .followUp {
	background-color:#ececec;
	border-bottom:1px solid #fff;
}


text:
package mf.org.apache.xerces.parsers;

import mf.org.apache.xerces.impl.Constants;
import mf.org.apache.xerces.util.SymbolTable;
import mf.org.apache.xerces.xinclude.XIncludeHandler;
import mf.org.apache.xerces.xinclude.XIncludeNamespaceSupport;
import mf.org.apache.xerces.xni.XMLDocumentHandler;
import mf.org.apache.xerces.xni.grammars.XMLGrammarPool;
import mf.org.apache.xerces.xni.parser.XMLComponentManager;
import mf.org.apache.xerces.xni.parser.XMLConfigurationException;
import mf.org.apache.xerces.xni.parser.XMLDocumentSource;

/**
 * This parser configuration includes an XIncludeHandler in the pipeline
 * before the schema validator, or as the last component in the pipeline if there is
 * no schema validator.  Using this pipeline will enable processing according to the
 * XML Inclusions specification, to the conformance level described in
 * XIncludeHandler.
 *
 * @author Peter McCracken, IBM
 * @see mf.org.apache.xerces.xinclude.XIncludeHandler
 */
public class XIncludeParserConfiguration extends XML11Configuration {

    private XIncludeHandler fXIncludeHandler;

    /** Feature identifier: allow notation and unparsed entity events to be sent out of order. */
    protected static final String ALLOW_UE_AND_NOTATION_EVENTS =
        Constants.SAX_FEATURE_PREFIX + Constants.ALLOW_DTD_EVENTS_AFTER_ENDDTD_FEATURE;

    /** Feature identifier: fixup base URIs. */
    protected static final String XINCLUDE_FIXUP_BASE_URIS =
        Constants.XERCES_FEATURE_PREFIX + Constants.XINCLUDE_FIXUP_BASE_URIS_FEATURE;

    /** Feature identifier: fixup language. */
    protected static final String XINCLUDE_FIXUP_LANGUAGE =
        Constants.XERCES_FEATURE_PREFIX + Constants.XINCLUDE_FIXUP_LANGUAGE_FEATURE;

    /** Property identifier: error reporter. */
    protected static final String XINCLUDE_HANDLER =
        Constants.XERCES_PROPERTY_PREFIX + Constants.XINCLUDE_HANDLER_PROPERTY;

    /** Property identifier: error reporter. */
    protected static final String NAMESPACE_CONTEXT =
        Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_CONTEXT_PROPERTY;

    /** Default constructor. */
    public XIncludeParserConfiguration() {
        this(null, null, null);
    } // <init>()

    /**
     * Constructs a parser configuration using the specified symbol table.
     *
     * @param symbolTable The symbol table to use.
     */
    public XIncludeParserConfiguration(SymbolTable symbolTable) {
        this(symbolTable, null, null);
    } // <init>(SymbolTable)

    /**
     * Constructs a parser configuration using the specified symbol table and
     * grammar pool.
     *

     *
     * @param symbolTable The symbol table to use.
     * @param grammarPool The grammar pool to use.
     */
    public XIncludeParserConfiguration(
        SymbolTable symbolTable,
        XMLGrammarPool grammarPool) {
        this(symbolTable, grammarPool, null);
    } // <init>(SymbolTable,XMLGrammarPool)

    /**
     * Constructs a parser configuration using the specified symbol table,
     * grammar pool, and parent settings.
     *

     *
     * @param symbolTable    The symbol table to use.
     * @param grammarPool    The grammar pool to use.
     * @param parentSettings The parent settings.
     */
    public XIncludeParserConfiguration(
        SymbolTable symbolTable,
        XMLGrammarPool grammarPool,
        XMLComponentManager parentSettings) {
        super(symbolTable, grammarPool, parentSettings);

        fXIncludeHandler = new XIncludeHandler();
        addCommonComponent(fXIncludeHandler);

        final String[] recognizedFeatures = {
            ALLOW_UE_AND_NOTATION_EVENTS,
            XINCLUDE_FIXUP_BASE_URIS,
            XINCLUDE_FIXUP_LANGUAGE
        };
        addRecognizedFeatures(recognizedFeatures);

        // add default recognized properties
        final String[] recognizedProperties =
            { XINCLUDE_HANDLER, NAMESPACE_CONTEXT };
        addRecognizedProperties(recognizedProperties);

        setFeature(ALLOW_UE_AND_NOTATION_EVENTS, true);
        setFeature(XINCLUDE_FIXUP_BASE_URIS, true);
        setFeature(XINCLUDE_FIXUP_LANGUAGE, true);

        setProperty(XINCLUDE_HANDLER, fXIncludeHandler);
        setProperty(NAMESPACE_CONTEXT, new XIncludeNamespaceSupport());
    } // <init>(SymbolTable,XMLGrammarPool)}

	/** Configures the pipeline. */
    protected void configurePipeline() {
        super.configurePipeline();

        //configure DTD pipeline
        fDTDScanner.setDTDHandler(fDTDProcessor);
        fDTDProcessor.setDTDSource(fDTDScanner);
        fDTDProcessor.setDTDHandler(fXIncludeHandler);
        fXIncludeHandler.setDTDSource(fDTDProcessor);
		fXIncludeHandler.setDTDHandler(fDTDHandler);
        if (fDTDHandler != null) {
            fDTDHandler.setDTDSource(fXIncludeHandler);
        }

        // configure XML document pipeline: insert after DTDValidator and
        // before XML Schema validator
        XMLDocumentSource prev = null;
        if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) {
            // we don't have to worry about fSchemaValidator being null, since
            // super.configurePipeline() instantiated it if the feature was set
            prev = fSchemaValidator.getDocumentSource();
        }
        // Otherwise, insert after the last component in the pipeline
        else {
            prev = fLastComponent;
            fLastComponent = fXIncludeHandler;
        }

        XMLDocumentHandler next = prev.getDocumentHandler();
		prev.setDocumentHandler(fXIncludeHandler);
		fXIncludeHandler.setDocumentSource(prev);
        if (next != null) {
            fXIncludeHandler.setDocumentHandler(next);
            next.setDocumentSource(fXIncludeHandler);
        }

    } // configurePipeline()

	protected void configureXML11Pipeline() {
		super.configureXML11Pipeline();

        // configure XML 1.1. DTD pipeline
		fXML11DTDScanner.setDTDHandler(fXML11DTDProcessor);
		fXML11DTDProcessor.setDTDSource(fXML11DTDScanner);
		fXML11DTDProcessor.setDTDHandler(fXIncludeHandler);
		fXIncludeHandler.setDTDSource(fXML11DTDProcessor);
		fXIncludeHandler.setDTDHandler(fDTDHandler);
		if (fDTDHandler != null) {
			fDTDHandler.setDTDSource(fXIncludeHandler);
		}

		// configure XML document pipeline: insert after DTDValidator and
		// before XML Schema validator
		XMLDocumentSource prev = null;
		if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) {
			// we don't have to worry about fSchemaValidator being null, since
			// super.configurePipeline() instantiated it if the feature was set
			prev = fSchemaValidator.getDocumentSource();
		}
		// Otherwise, insert after the last component in the pipeline
		else {
			prev = fLastComponent;
			fLastComponent = fXIncludeHandler;
		}

		XMLDocumentHandler next = prev.getDocumentHandler();
		prev.setDocumentHandler(fXIncludeHandler);
		fXIncludeHandler.setDocumentSource(prev);
		if (next != null) {
			fXIncludeHandler.setDocumentHandler(next);
			next.setDocumentSource(fXIncludeHandler);
		}

	} // configureXML11Pipeline()

    public void setProperty(String propertyId, Object value)
        throws XMLConfigurationException {

        if (propertyId.equals(XINCLUDE_HANDLER)) {
        }

        super.setProperty(propertyId, value);
    } // setProperty(String,Object)
}


text:
package net.automatalib;

import java.io.File;
import java.net.URL;

import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

/**
 * @author frohme
 */
public class AutomataLibSettingsTest {

    @BeforeSuite
    public static void setUp() {
        final URL resource = AutomataLibSettingsTest.class.getResource("/automatalib.properties");
        assert resource != null;
        final File properties = new File(resource.getFile());
        System.setProperty("automatalib.properties", properties.getAbsolutePath());
        System.setProperty(AutomataLibProperty.WORD_EMPTY_REP.getPropertyKey(), "OVERRIDDEN");
    }

    @Test
    public void testProperties() {
        AutomataLibSettings settings = AutomataLibSettings.getInstance();

        for (AutomataLibProperty p : AutomataLibProperty.values()) {
            switch (p) {
                case DOT_EXE_DIR:
                    Assert.assertEquals("dot", settings.getProperty(AutomataLibProperty.DOT_EXE_DIR));
                    break;
                case DOT_EXE_NAME:
                    Assert.assertEquals("dot.exe", settings.getProperty(AutomataLibProperty.DOT_EXE_NAME));
                    break;
                case LTSMIN_PATH:
                    Assert.assertEquals("ltsmin", settings.getProperty(AutomataLibProperty.LTSMIN_PATH));
                    break;
                case LTSMIN_VERBOSE:
                    Assert.assertEquals("false", settings.getProperty(AutomataLibProperty.LTSMIN_VERBOSE));
                    break;
                case VISUALIZATION_PROVIDER:
                    Assert.assertEquals("provider", settings.getProperty(AutomataLibProperty.VISUALIZATION_PROVIDER));
                    break;
                case WORD_DELIM_LEFT:
                    Assert.assertEquals("delim_left", settings.getProperty(AutomataLibProperty.WORD_DELIM_LEFT));
                    break;
                case WORD_DELIM_RIGHT:
                    Assert.assertEquals("delim_right", settings.getProperty(AutomataLibProperty.WORD_DELIM_RIGHT));
                    break;
                case WORD_EMPTY_REP:
                    Assert.assertEquals("OVERRIDDEN", settings.getProperty(AutomataLibProperty.WORD_EMPTY_REP));
                    break;
                case WORD_SYMBOL_DELIM_LEFT:
                    Assert.assertEquals("symbol_delim_left",
                                        settings.getProperty(AutomataLibProperty.WORD_SYMBOL_DELIM_LEFT));
                    break;
                case WORD_SYMBOL_DELIM_RIGHT:
                    Assert.assertEquals("symbol_delim_right",
                                        settings.getProperty(AutomataLibProperty.WORD_SYMBOL_DELIM_RIGHT));
                    break;
                case WORD_SYMBOL_SEPARATOR:
                    Assert.assertEquals("symbol_sep", settings.getProperty(AutomataLibProperty.WORD_SYMBOL_SEPARATOR));
                    break;
                default:
                    throw new IllegalStateException("Unhandled property " + p);

            }
        }

    }
}


text:
// Generated from XMLParser.g4 by ANTLR 4.5.3

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;

/**
 * This class provides an empty implementation of {@link XMLParserListener},
 * which can be extended to create a listener which only needs to handle a subset
 * of the available methods.
 */
public class XMLParserBaseListener implements XMLParserListener {
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterDocument(XMLParser.DocumentContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitDocument(XMLParser.DocumentContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterProlog(XMLParser.PrologContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitProlog(XMLParser.PrologContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterContent(XMLParser.ContentContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitContent(XMLParser.ContentContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterElement(XMLParser.ElementContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitElement(XMLParser.ElementContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterReference(XMLParser.ReferenceContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitReference(XMLParser.ReferenceContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterAttribute(XMLParser.AttributeContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitAttribute(XMLParser.AttributeContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterChardata(XMLParser.ChardataContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitChardata(XMLParser.ChardataContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterMisc(XMLParser.MiscContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitMisc(XMLParser.MiscContext ctx) { }

	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterEveryRule(ParserRuleContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitEveryRule(ParserRuleContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void visitTerminal(TerminalNode node) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void visitErrorNode(ErrorNode node) { }
}


text:
package cn.edu.hhu.reg.common;

import cn.edu.hhu.reg.R;
import android.app.Dialog;
import android.content.Context;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomProgressDialog extends Dialog {
	final TextView tv_msg;
	final ImageView iv_progress;
	final Context mContext;
	Animation hyperspaceJumpAnimation;

	public CustomProgressDialog(Context context) {
		this(context, "加载中!", R.style.loading_dialog);
	}
	public CustomProgressDialog(Context context, String message) {
		this(context, message, R.style.loading_dialog);
	}
	public CustomProgressDialog(Context context, String message, int theme) {
		super(context, theme);
		mContext = context;
		this.setContentView(R.layout.widget_progress_dialog);
		this.setCanceledOnTouchOutside(false);
		tv_msg = (TextView) findViewById(R.id.tv_coustomprogress_loadingmsg);
		iv_progress = (ImageView)findViewById(R.id.iv_coustomprogress);
		tv_msg.setText(message);
	}

	public void setMessage(String str){
		tv_msg.setText(str);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (!hasFocus) {
			dismiss();
		}
	}

	@Override
	public void show() {
		if (hyperspaceJumpAnimation == null
				|| !hyperspaceJumpAnimation.isInitialized()) {
			// 加载动画
			hyperspaceJumpAnimation = AnimationUtils.loadAnimation(mContext,
					R.anim.loading_anim);
			// 使用ImageView显示动画
		} else {
			hyperspaceJumpAnimation.reset();
		}
		iv_progress.startAnimation(hyperspaceJumpAnimation);
		super.show();
	}

	@Override
	public void hide() {
		hyperspaceJumpAnimation.cancel();
		super.hide();
	}
}


text:
/**
 * Comparators related to the EPGM data model.
 */
package org.gradoop.flink.model.impl.comparators;


text:
package org.durid.sql.ast.statement;

public class SQLIndexDefinition {

}


text:
use std::collections::{BinaryHeap, HashSet};
use std::cmp::Ordering;

#[derive(Serialize, Deserialize)]
struct ScheduleEntry<T> {
    value: T,
    abs_time: u64,
    rel_time: u64,
    seq: u64,
}

impl<T> ScheduleEntry<T> {
    fn new(value: T, abs_time: u64, rel_time: u64, seq: u64) -> Self {
        ScheduleEntry {
            value: value,
            abs_time: abs_time,
            rel_time: rel_time,
            seq: seq,
        }
    }
}

impl<T> Ord for ScheduleEntry<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        let abs_time_ord = other.abs_time.cmp(&self.abs_time);
        if abs_time_ord == Ordering::Equal {
            other.seq.cmp(&self.seq)
        } else {
            abs_time_ord
        }
    }
}

impl<T> PartialOrd for ScheduleEntry<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> PartialEq for ScheduleEntry<T> {
    fn eq(&self, other: &Self) -> bool {
        self.abs_time == other.abs_time && self.seq == other.seq
    }
}

impl<T> Eq for ScheduleEntry<T> {}

#[derive(Debug)]
pub struct ScheduleEvent<T> {
    pub event: T,
    pub time_delta: u64,
    pub time_queued: u64,
    pub absolute_time: u64,
}

impl<T> ScheduleEvent<T> {
    fn new(event: T, time_delta: u64, time_queued: u64, absolute_time: u64) -> Self {
        ScheduleEvent {
            event: event,
            time_delta: time_delta,
            time_queued: time_queued,
            absolute_time: absolute_time,
        }
    }
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ScheduleTicket {
    seq: u64,
}

pub struct Schedule<T> {
    heap: BinaryHeap<ScheduleEntry<T>>,
    invalid: HashSet<u64>,
    abs_time: u64,
    seq: u64,
}

#[derive(Serialize, Deserialize)]
pub struct SerializableSchedule<T> {
    entries: Vec<ScheduleEntry<T>>,
    invalid: HashSet<u64>,
    abs_time: u64,
    seq: u64,
}

impl<T> From<Schedule<T>> for SerializableSchedule<T> {
    fn from(schedule: Schedule<T>) -> Self {
        let Schedule {
            heap,
            invalid,
            abs_time,
            seq,
        } = schedule;

        SerializableSchedule {
            entries: heap.into_vec(),
            invalid: invalid,
            abs_time: abs_time,
            seq: seq,
        }
    }
}

impl<T> From<SerializableSchedule<T>> for Schedule<T> {
    fn from(schedule: SerializableSchedule<T>) -> Self {
        let SerializableSchedule {
            entries,
            invalid,
            abs_time,
            seq,
        } = schedule;

        Schedule {
            heap: BinaryHeap::from(entries),
            invalid: invalid,
            abs_time: abs_time,
            seq: seq,
        }
    }
}

impl<T> Schedule<T> {
    pub fn new() -> Self {
        Schedule {
            heap: BinaryHeap::new(),
            invalid: HashSet::new(),
            abs_time: 0,
            seq: 0,
        }
    }

    pub fn insert(&mut self, value: T, rel_time: u64) -> ScheduleTicket {
        let seq = self.seq;
        let abs_time = self.abs_time + rel_time;

        let entry = ScheduleEntry::new(value, abs_time, rel_time, seq);
        self.heap.push(entry);
        self.seq += 1;

        ScheduleTicket {
            seq: seq,
        }
    }

    pub fn insert_with_ticket(&mut self, value: T, rel_time: u64, ticket: ScheduleTicket) -> ScheduleTicket {

        // it must be a ticket we've given out in the past
        assert!(ticket.seq < self.seq, "Invalid schedule ticket");

        let abs_time = self.abs_time + rel_time;
        let entry = ScheduleEntry::new(value, abs_time, rel_time, ticket.seq);
        self.heap.push(entry);

        ScheduleTicket {
            seq: ticket.seq,
        }
    }

    pub fn next(&mut self) -> Option<ScheduleEvent<T>> {

        while let Some(entry) = self.heap.pop() {
            if self.invalid.remove(&entry.seq) {
                continue;
            }

            let time_delta = entry.abs_time - self.abs_time;
            self.abs_time = entry.abs_time;

            return Some(ScheduleEvent::new(entry.value, time_delta, entry.rel_time, entry.abs_time));
        }

        None
    }

    pub fn reset(&mut self) {
        self.heap.clear();
        self.abs_time = 0;
        self.seq = 0;
    }

    pub fn time(&self) -> u64 {
        self.abs_time
    }

    pub fn invalidate(&mut self, ticket: ScheduleTicket) {
        self.invalid.insert(ticket.seq);
    }

    pub fn len(&self) -> usize {
        self.heap.len()
    }
}


text:
package njensen.tools;

import java.util.Scanner;

/**
 * This prompt the user with a message / question,
 * then returns the enteredText.
 *
 * @author Nicholas Jensen on 05/27/2017.
 */
public class UserInput {

    // text entered by the user
    private String enteredText = "";

    /**
     * This displays a message to the user,
     * then stores in for retrieval.
     *
     * @param message A message that will be prompted to the user.
     * @param newLine Specify whether to use a new line or same line.
     */
    public void getInputFromUser(String message, boolean newLine) {

        Scanner scanner = new Scanner(System.in);

        if (newLine == true) {
            systemOutNewLine(message);
        } else {
            systemOut(message);
        }
        this.enteredText = scanner.nextLine();

    }

    /**
     * This returns the enteredText from the user.
     *
     * @return The enteredText from the user.
     */
    public String getEnteredText() {
        return this.enteredText;
    }

    /**
     * This returns the enteredText from the user,
     * in uppercase.
     *
     * @param trimString Trim whitespace from the user enteredText?
     * @return The enteredText from the user, in uppercase.
     */
    public String getEnteredTextUppercase(boolean trimString) {
        if (trimString == true)
            return this.enteredText.toUpperCase().trim();
        return this.enteredText.toUpperCase();
    }

    /**
     * This returns the enteredText from the user,
     * in lowercase.
     *
     * @param trimString Trim whitespace from the user enteredText?
     * @return The enteredText from the user, in lowercase.
     */
    public String getEnteredTextLowercase(boolean trimString) {
        if (trimString == true)
            return this.enteredText.toLowerCase().trim();
        return this.enteredText.toLowerCase();
    }

    /**
     * Print text in the console.
     *
     * @param message The message to print.
     */
    private void systemOut(String message) {
        if (message != null)
            if (message.trim().length() > 0)
                System.out.print(message);
    }

    /**
     * Print text in the console, new line.
     *
     * @param message The message to print.
     */
    private void systemOutNewLine(String message) {
        if (message != null)
            if (message.trim().length() > 0)
                System.out.println(message);
    }

}


text:
package org.cidrz.project.zeprs.valueobject.lims.impl;

import java.sql.Date;

import org.cidrz.project.zeprs.valueobject.lims.ObservationMetaData;

/**
 * @author ckelley
 * The classes in this package are for connecting to the SQL Server instance
 * which stores data from the LIMS lab system.
 */

/**
 * ---fixme-hibernate.class table="PatientInformation"
 * lazy="true"
 * mutable="true"
 */
public class PatientInformation implements ObservationMetaData {

	private String id;
	private String natID;
	private String firstName;
	private String surname;
	private String clinic;
	private String study;
	private Date dob;
	private String sex;
	private Date collection;
	private Date reception;
	private String observationRequest;

	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getId()
	 */
	public String getId() {
		return id;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setId(java.lang.Long)
	 */
	public void setId(String id) {
		this.id = id;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getNatID()
	 */
	public String getNatID() {
		return natID;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setNatID(java.lang.String)
	 */
	public void setNatID(String natID) {
		this.natID = natID;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getFirstName()
	 */
	public String getFirstName() {
		return firstName;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setFirstName(java.lang.String)
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getSurname()
	 */
	public String getSurname() {
		return surname;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setSurname(java.lang.String)
	 */
	public void setSurname(String surname) {
		this.surname = surname;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getClinic()
	 */
	public String getClinic() {
		return clinic;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setClinic(java.lang.String)
	 */
	public void setClinic(String clinic) {
		this.clinic = clinic;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getStudy()
	 */
	public String getStudy() {
		return study;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setStudy(java.lang.String)
	 */
	public void setStudy(String study) {
		this.study = study;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getDob()
	 */
	public Date getDob() {
		return dob;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setDob(java.sql.Date)
	 */
	public void setDob(Date dob) {
		this.dob = dob;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getSex()
	 */
	public String getSex() {
		return sex;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setSex(java.lang.String)
	 */
	public void setSex(String sex) {
		this.sex = sex;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getCollection()
	 */
	public Date getCollection() {
		return collection;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setCollection(java.sql.Date)
	 */
	public void setCollection(Date collection) {
		this.collection = collection;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getReception()
	 */
	public Date getReception() {
		return reception;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setReception(java.sql.Date)
	 */
	public void setReception(Date reception) {
		this.reception = reception;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#getObservationRequest()
	 */
	public String getObservationRequest() {
		return observationRequest;
	}
	/* (non-Javadoc)
	 * @see org.cidrz.project.zeprs.valueobject.lims.LimsMetaData#setObservationRequest(java.lang.String)
	 */
	public void setObservationRequest(String observationRequest) {
		this.observationRequest = observationRequest;
	}

}


text:
import base64

# TODO: These tests should be merged with python/ql/test/experimental/dataflow/tainttracking/defaultAdditionalTaintStep-py3/test_string.py
base64.a85decode(payload)  # $ decodeInput=payload decodeOutput=base64.a85decode(..) decodeFormat=Ascii85
base64.b85decode(payload)  # $ decodeInput=payload decodeOutput=base64.b85decode(..) decodeFormat=Base85
base64.decodebytes(payload)  # $ decodeInput=payload decodeOutput=base64.decodebytes(..) decodeFormat=Base64