text:
There are two forms of methods within Ion: array methods, and string methods. Array methods are
methods which return arrays, and string methods are methods which return strings. The distinction
is made between the two by the sigil that is invoked when calling a method. For example, if the
method is denoted by the `$` sigil, then it is a string method. Otherwise, if it is denoted by the
`@` sigil, then it is an array method. Example as follows:

```ion
echo $method_name(variable)
for elem in @method_name(variable); echo $elem; end
```

Methods are executed at the same time as other expansions, so this leads to a performance
optimization when combining methods with other methods or expansions. Ion includes a number of these
methods for common use cases, but it is possible to create and/or install new methods to enhance the
functionality of Ion. Just ensure that systems executing your Ion scripts that require those plugins
are equipped with and have those plugins enabled. If you have ideas for useful methods that would
be worth including in Ion by default, feel free to open a feature request to discuss the idea.

## Methods Support Inline Expressions

So we heard that you like methods, so we put methods in your methods. Ion methods accept taking
expressions as their arguments -- both for the input parameter, and any supplied arguments to
control the behavior of the method.

```ion
echo $method($(cmd...), arg)

let string_var = "value in variable"
echo $method(string_var)

echo $method("actual value", arg)
```

## Overloaded Methods

Some methods may also perform different actions when supplied a different type. The `$len()` method,
for example, will report the number of graphemes within a string, or the number of elements within
an array. Ion is able to determine which of the two were provided based on the first character
in the expression. Quoted expressions, and expressions with start with `$`, are strings; whereas
expressions that start with either `[` or `@` are treated as arrays.

```ion
echo $len("a string")
echo $len([1 2 3 4 5])
```

## Method Arguments

Some methods may have their behavior tweaked by supplying some additional arguments. The `@split()`
method, for example, may be optionally supplied a pattern for splitting. At the moment, a comma
is used to specify that arguments are to follow the input, but each argument supplied after that
is space-delimited.

```ion
for elem in @split("some space-delimited values"); echo $elem; end
for elem in @split("some, comma-separated, values", ", "); echo $elem; end
```

## String Methods

The following are the currently-supported string methods:

- [basename](#basename)
- [extension](#extension)
- [filename](#filename)
- [join](#join)
- [len](#len)
- [len_bytes](#len_bytes)
- [parent](#parent)
- [repeat](#repeat)
- [replace](#replace)
- [replacen](#replacen)
- [reverse](#reverse)
- [to_lowercase](#to_lowercase)
- [to_uppercase](#to_uppercase)

### basename

Defaults to string variables. When given a path-like string as input, this will return the
basename (complete filename, extension included). IE: `/parent/filename.ext` -> `filename.ext`

#### Examples

```ion
echo $basename("/parent/filename.ext")
```

#### Output

```
filename.ext
```

### extension

Defaults to string variables. When given a path-like string as input, this will return the
extension of the complete filename. IE: `/parent/filename.ext` -> `ext`.

#### Examples

```ion
echo $extension("/parent/filename.ext")
```

#### Output

```
ext
```

### filename

Defaults to string variables. When given a path-like string as input, this will return the
file name portion of the complete filename. IE: `/parent/filename.ext` -> `filename`.

#### Examples

```ion
echo $filename("/parent/filename.ext")
```

#### Output

```
filename
```

### join

Defaults to array variables. When given an array as input, the join string method will concatenate
each element in the array and return a string. If no argument is given, then those elements will
be joined by a single space. Otherwise, each element will be joined with a given pattern.

#### Examples

```ion
let array = [1 2 3 4 5]
echo $join(array)
echo $join(array, ", ")
```

#### Output

```
1 2 3 4 5
1, 2, 3, 4, 5
```

### len

Defaults to string variables. Counts the number of graphemes in the output. If an array expression
is supplied, it will print the number of elements in the array.

#### Examples

```ion
echo $len("foobar")
echo $len("❤")
echo $len([one two three four])
```

#### Output

```
6
1
4
```

### len_bytes

Defaults to string variables. Similar to the `len` method, but counts the number of actual bytes
in the output, not the number of graphemes.

#### Examples

```ion
echo $len_bytes("foobar")
echo $len_bytes("❤")
```

#### Output

```
6
6
```

### parent

Defaults to string variables. When given a path-like string as input, this will return the
parent directory's name. IE: `/root/parent/filename.ext` -> `/root/parent`

#### Examples

```ion
echo $parent("/root/parent/filename.ext")
```

#### Output

```
/root/parent
```

### repeat

Defaults to string variables. When supplied with a number, it will repeat the input N
amount of times, where N is the supplied number.

#### Examples

```ion
echo $repeat("abc, ", 3)
```

#### Output

```
abc, abc, abc
```

### replace

Defaults to string variables. Given a pattern to match, and a replacement to replace each match
with, a new string will be returned with all matches replaced.

#### Examples

```ion
let input = "one two one two"
echo $replace(input, one 1)
echo $replace($replace(input, one 1), two 2)
```

#### Output

```
1 two 1 two
1 2 1 2
```

### replacen

Defaults to string variables. Equivalent to `replace`, but will only replace the first N amount
of matches.

#### Examples

```ion
let input = "one two one two"
echo $replacen(input, "one" "three" 1)
echo $replacen(input, "two" "three" 2)
```

#### Output

```
three two one two
one three one three
```

### reverse

Defaults to string variables. Simply returns the same string, but with each grapheme displayed
in reverse order.

#### Examples

```ion
echo $reverse("foobar")
```

#### Output

```
raboof
```

### to_lowercase

Defaults to string variables. All given strings have their characters converted to an
lowercase equivalent, if an lowercase equivalent exists.

#### Examples

```ion
echo $to_lowercase("FOOBAR")
```

#### Output

```
foobar
```

### to_uppercase

Defaults to string variables. All given strings have their characters converted to an
uppercase equivalent, if an uppercase equivalent exists.

#### Examples

```ion
echo $to_uppercase("foobar")
```

#### Output

```
FOOBAR
```

## Array Methods

The following are the currently-supported array methods.

- [split](#split)
- [bytes](#bytes)
- [chars](#chars)
- [graphemes](#graphemes)

### split

Defaults to string variables. The supplied string will be split according to a pattern specified
as an argument in the method. If no pattern is supplied, then the input will be split by
whitespace characters. Useful for splitting simple tabular data.

#### Examples

```ion
for data in @split("person, age, some data", ", ")
    echo $data
end

for data in @split("person age data")
    echo $data
end
```

#### Output

```
person
age
some data
person
age
data
```

### bytes

Defaults to string variables. Returns an array where the given input string is split by bytes and
each byte is displayed as their actual 8-bit number.

#### Examples

```ion
echo @bytes("foobar")
```

#### Output

```
102 111 111 98 97 114
```

### chars

Defaults to string variables. Returns an array where the given input string is split by chars.

#### Examples

```ion
for char in @chars("foobar")
    echo $char
end
```

#### Output

```
f
o
o
b
a
r
```

### graphemes

Defaults to string variables. Returns an array where the given input string is split by graphemes.

#### Examples

```ion
for grapheme in @graphemes("foobar")
    echo $grapheme
end
```

#### Output

```
f
o
o
b
a
r
```


text:
.. sandman2 documentation master file, created by
   sphinx-quickstart on Fri Oct 24 08:22:11 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to sandman2's documentation!
====================================

Contents:

.. toctree::
   :maxdepth: 2

   Quickstart <quickstart>
   Interacting With Your sandman2 API <interacting>
   Extending sandman2 <extending>
   Sandman2 Admin <admin>
   API <sandman2>

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

redpajama_set_name: RedPajamaGithub


text:
package org.bouncycastle.jce.provider;

import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.RC2ParameterSpec;
import javax.crypto.spec.RC5ParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoServicesRegistrar;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.DESEngine;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.engines.TwofishEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.modes.CTSBlockCipher;
import org.bouncycastle.crypto.modes.OFBBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.crypto.params.RC2Parameters;
import org.bouncycastle.crypto.params.RC5Parameters;
import org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey;
import org.bouncycastle.util.Strings;

public class BrokenJCEBlockCipher
    implements BrokenPBE
{
    //
    // specs we can handle.
    //
    private Class[]                 availableSpecs =
                                    {
                                        IvParameterSpec.class,
                                        PBEParameterSpec.class,
                                        RC2ParameterSpec.class,
                                        RC5ParameterSpec.class
                                    };

    private BufferedBlockCipher     cipher;
    private ParametersWithIV        ivParam;

    private int                     pbeType = PKCS12;
    private int                     pbeHash = SHA1;
    private int                     pbeKeySize;
    private int                     pbeIvSize;

    private int                     ivLength = 0;

    private AlgorithmParameters     engineParams = null;

    protected BrokenJCEBlockCipher(
        BlockCipher engine)
    {
        cipher = new PaddedBufferedBlockCipher(engine);
    }

    protected BrokenJCEBlockCipher(
        BlockCipher engine,
        int         pbeType,
        int         pbeHash,
        int         pbeKeySize,
        int         pbeIvSize)
    {
        cipher = new PaddedBufferedBlockCipher(engine);

        this.pbeType = pbeType;
        this.pbeHash = pbeHash;
        this.pbeKeySize = pbeKeySize;
        this.pbeIvSize = pbeIvSize;
    }

    protected int engineGetBlockSize()
    {
        return cipher.getBlockSize();
    }

    protected byte[] engineGetIV()
    {
        return (ivParam != null) ? ivParam.getIV() : null;
    }

    protected int engineGetKeySize(
        Key     key)
    {
        return key.getEncoded().length;
    }

    protected int engineGetOutputSize(
        int     inputLen)
    {
        return cipher.getOutputSize(inputLen);
    }

    protected AlgorithmParameters engineGetParameters()
    {
        if (engineParams == null)
        {
            if (ivParam != null)
            {
                String  name = cipher.getUnderlyingCipher().getAlgorithmName();

                if (name.indexOf('/') >= 0)
                {
                    name = name.substring(0, name.indexOf('/'));
                }

                try
                {
                    engineParams = AlgorithmParameters.getInstance(name, BouncyCastleProvider.PROVIDER_NAME);
                    engineParams.init(ivParam.getIV());
                }
                catch (Exception e)
                {
                    throw new RuntimeException(e.toString());
                }
            }
        }

        return engineParams;
    }

    protected void engineSetMode(
        String  mode)
    {
        String  modeName = Strings.toUpperCase(mode);

        if (modeName.equals("ECB"))
        {
            ivLength = 0;
            cipher = new PaddedBufferedBlockCipher(cipher.getUnderlyingCipher());
        }
        else if (modeName.equals("CBC"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            cipher = new PaddedBufferedBlockCipher(
                            new CBCBlockCipher(cipher.getUnderlyingCipher()));
        }
        else if (modeName.startsWith("OFB"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            if (modeName.length() != 3)
            {
                int wordSize = Integer.parseInt(modeName.substring(3));

                cipher = new PaddedBufferedBlockCipher(
                                new OFBBlockCipher(cipher.getUnderlyingCipher(), wordSize));
            }
            else
            {
                cipher = new PaddedBufferedBlockCipher(
                        new OFBBlockCipher(cipher.getUnderlyingCipher(), 8 * cipher.getBlockSize()));
            }
        }
        else if (modeName.startsWith("CFB"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            if (modeName.length() != 3)
            {
                int wordSize = Integer.parseInt(modeName.substring(3));

                cipher = new PaddedBufferedBlockCipher(
                                new CFBBlockCipher(cipher.getUnderlyingCipher(), wordSize));
            }
            else
            {
                cipher = new PaddedBufferedBlockCipher(
                        new CFBBlockCipher(cipher.getUnderlyingCipher(), 8 * cipher.getBlockSize()));
            }
        }
        else
        {
            throw new IllegalArgumentException("can't support mode " + mode);
        }
    }

    protected void engineSetPadding(
        String  padding)
    throws NoSuchPaddingException
    {
        String  paddingName = Strings.toUpperCase(padding);

        if (paddingName.equals("NOPADDING"))
        {
            cipher = new BufferedBlockCipher(cipher.getUnderlyingCipher());
        }
        else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING") || paddingName.equals("ISO10126PADDING"))
        {
            cipher = new PaddedBufferedBlockCipher(cipher.getUnderlyingCipher());
        }
        else if (paddingName.equals("WITHCTS"))
        {
            cipher = new CTSBlockCipher(cipher.getUnderlyingCipher());
        }
        else
        {
            throw new NoSuchPaddingException("Padding " + padding + " unknown.");
        }
    }

    protected void engineInit(
        int                     opmode,
        Key                     key,
        AlgorithmParameterSpec  params,
        SecureRandom            random)
    throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        CipherParameters        param;

        //
        // a note on iv's - if ivLength is zero the IV gets ignored (we don't use it).
        //
        if (key instanceof BCPBEKey)
        {
            param = BrokenPBE.Util.makePBEParameters((BCPBEKey)key, params, pbeType, pbeHash,
                        cipher.getUnderlyingCipher().getAlgorithmName(), pbeKeySize, pbeIvSize);

            if (pbeIvSize != 0)
            {
                ivParam = (ParametersWithIV)param;
            }
        }
        else if (params == null)
        {
            param = new KeyParameter(key.getEncoded());
        }
        else if (params instanceof IvParameterSpec)
        {
            if (ivLength != 0)
            {
                param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec)params).getIV());
                ivParam = (ParametersWithIV)param;
            }
            else
            {
                param = new KeyParameter(key.getEncoded());
            }
        }
        else if (params instanceof RC2ParameterSpec)
        {
            RC2ParameterSpec    rc2Param = (RC2ParameterSpec)params;

            param = new RC2Parameters(key.getEncoded(), ((RC2ParameterSpec)params).getEffectiveKeyBits());

            if (rc2Param.getIV() != null && ivLength != 0)
            {
                param = new ParametersWithIV(param, rc2Param.getIV());
                ivParam = (ParametersWithIV)param;
            }
        }
        else if (params instanceof RC5ParameterSpec)
        {
            RC5ParameterSpec    rc5Param = (RC5ParameterSpec)params;

            param = new RC5Parameters(key.getEncoded(), ((RC5ParameterSpec)params).getRounds());
            if (rc5Param.getWordSize() != 32)
            {
                throw new IllegalArgumentException("can only accept RC5 word size 32 (at the moment...)");
            }
            if ((rc5Param.getIV() != null) && (ivLength != 0))
            {
                param = new ParametersWithIV(param, rc5Param.getIV());
                ivParam = (ParametersWithIV)param;
            }
        }
        else
        {
            throw new InvalidAlgorithmParameterException("unknown parameter type.");
        }

        if ((ivLength != 0) && !(param instanceof ParametersWithIV))
        {
            if (random == null)
            {
                random = CryptoServicesRegistrar.getSecureRandom();
            }

            if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE))
            {
                byte[]  iv = new byte[ivLength];

                random.nextBytes(iv);
                param = new ParametersWithIV(param, iv);
                ivParam = (ParametersWithIV)param;
            }
            else
            {
                throw new InvalidAlgorithmParameterException("no IV set when one expected");
            }
        }

        switch (opmode)
        {
        case Cipher.ENCRYPT_MODE:
        case Cipher.WRAP_MODE:
            cipher.init(true, param);
            break;
        case Cipher.DECRYPT_MODE:
        case Cipher.UNWRAP_MODE:
            cipher.init(false, param);
            break;
        default:
            throw new IllegalArgumentException("unknown opmode: " + opmode);
        }
    }

    protected void engineInit(
        int                 opmode,
        Key                 key,
        AlgorithmParameters params,
        SecureRandom        random)
    throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        AlgorithmParameterSpec  paramSpec = null;

        if (params != null)
        {
            for (int i = 0; i != availableSpecs.length; i++)
            {
                try
                {
                    paramSpec = params.getParameterSpec(availableSpecs[i]);
                    break;
                }
                catch (Exception e)
                {
                    continue;
                }
            }

            if (paramSpec == null)
            {
                throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
            }
        }

        engineParams = params;
        engineInit(opmode, key, paramSpec, random);
    }

    protected void engineInit(
        int                 opmode,
        Key                 key,
        SecureRandom        random)
        throws InvalidKeyException
    {
        try
        {
            engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    protected byte[] engineUpdate(
        byte[]  input,
        int     inputOffset,
        int     inputLen)
    {
        int     length = cipher.getUpdateOutputSize(inputLen);

        if (length > 0)
        {
                byte[]  out = new byte[length];

                cipher.processBytes(input, inputOffset, inputLen, out, 0);
                return out;
        }

        cipher.processBytes(input, inputOffset, inputLen, null, 0);

        return null;
    }

    protected int engineUpdate(
        byte[]  input,
        int     inputOffset,
        int     inputLen,
        byte[]  output,
        int     outputOffset)
    {
        return cipher.processBytes(input, inputOffset, inputLen, output, outputOffset);
    }

    protected byte[] engineDoFinal(
        byte[]  input,
        int     inputOffset,
        int     inputLen)
        throws IllegalBlockSizeException, BadPaddingException
    {
        int     len = 0;
        byte[]  tmp = new byte[engineGetOutputSize(inputLen)];

        if (inputLen != 0)
        {
            len = cipher.processBytes(input, inputOffset, inputLen, tmp, 0);
        }

        try
        {
            len += cipher.doFinal(tmp, len);
        }
        catch (DataLengthException e)
        {
            throw new IllegalBlockSizeException(e.getMessage());
        }
        catch (InvalidCipherTextException e)
        {
            throw new BadPaddingException(e.getMessage());
        }

        byte[]  out = new byte[len];

        System.arraycopy(tmp, 0, out, 0, len);

        return out;
    }

    protected int engineDoFinal(
        byte[]  input,
        int     inputOffset,
        int     inputLen,
        byte[]  output,
        int     outputOffset)
        throws IllegalBlockSizeException, BadPaddingException
    {
        int     len = 0;

        if (inputLen != 0)
        {
                len = cipher.processBytes(input, inputOffset, inputLen, output, outputOffset);
        }

        try
        {
            return len + cipher.doFinal(output, outputOffset + len);
        }
        catch (DataLengthException e)
        {
            throw new IllegalBlockSizeException(e.getMessage());
        }
        catch (InvalidCipherTextException e)
        {
            throw new BadPaddingException(e.getMessage());
        }
    }

    protected byte[] engineWrap(
        Key     key)
    throws IllegalBlockSizeException, java.security.InvalidKeyException
    {
        byte[] encoded = key.getEncoded();
        if (encoded == null)
        {
            throw new InvalidKeyException("Cannot wrap key, null encoding.");
        }

        try
        {
            return engineDoFinal(encoded, 0, encoded.length);
        }
        catch (BadPaddingException e)
        {
            throw new IllegalBlockSizeException(e.getMessage());
        }
    }

    protected Key engineUnwrap(
        byte[]  wrappedKey,
        String  wrappedKeyAlgorithm,
        int     wrappedKeyType)
    throws InvalidKeyException
    {
        byte[] encoded = null;
        try
        {
            encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
        }
        catch (BadPaddingException e)
        {
            throw new InvalidKeyException(e.getMessage());
        }
        catch (IllegalBlockSizeException e2)
        {
            throw new InvalidKeyException(e2.getMessage());
        }

        if (wrappedKeyType == Cipher.SECRET_KEY)
        {
            return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
        }
        else
        {
            try
            {
                KeyFactory kf = KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

                if (wrappedKeyType == Cipher.PUBLIC_KEY)
                {
                    return kf.generatePublic(new X509EncodedKeySpec(encoded));
                }
                else if (wrappedKeyType == Cipher.PRIVATE_KEY)
                {
                    return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
                }
            }
            catch (NoSuchProviderException e)
            {
                throw new InvalidKeyException("Unknown key type " + e.getMessage());
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new InvalidKeyException("Unknown key type " + e.getMessage());
            }
            catch (InvalidKeySpecException e2)
            {
                throw new InvalidKeyException("Unknown key type " + e2.getMessage());
            }

            throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
        }
    }

    /*
     * The ciphers that inherit from us.
     */

    /**
     * PBEWithMD5AndDES
     */
    static public class BrokePBEWithMD5AndDES
        extends BrokenJCEBlockCipher
    {
        public BrokePBEWithMD5AndDES()
        {
            super(new CBCBlockCipher(new DESEngine()), PKCS5S1, MD5, 64, 64);
        }
    }

    /**
     * PBEWithSHA1AndDES
     */
    static public class BrokePBEWithSHA1AndDES
        extends BrokenJCEBlockCipher
    {
        public BrokePBEWithSHA1AndDES()
        {
            super(new CBCBlockCipher(new DESEngine()), PKCS5S1, SHA1, 64, 64);
        }
    }

    /**
     * PBEWithSHAAnd3-KeyTripleDES-CBC
     */
    static public class BrokePBEWithSHAAndDES3Key
        extends BrokenJCEBlockCipher
    {
        public BrokePBEWithSHAAndDES3Key()
        {
            super(new CBCBlockCipher(new DESedeEngine()), PKCS12, SHA1, 192, 64);
        }
    }

    /**
     * OldPBEWithSHAAnd3-KeyTripleDES-CBC
     */
    static public class OldPBEWithSHAAndDES3Key
        extends BrokenJCEBlockCipher
    {
        public OldPBEWithSHAAndDES3Key()
        {
            super(new CBCBlockCipher(new DESedeEngine()), OLD_PKCS12, SHA1, 192, 64);
        }
    }

    /**
     * PBEWithSHAAnd2-KeyTripleDES-CBC
     */
    static public class BrokePBEWithSHAAndDES2Key
        extends BrokenJCEBlockCipher
    {
        public BrokePBEWithSHAAndDES2Key()
        {
            super(new CBCBlockCipher(new DESedeEngine()), PKCS12, SHA1, 128, 64);
        }
    }

    /**
     * OldPBEWithSHAAndTwofish-CBC
     */
    static public class OldPBEWithSHAAndTwofish
        extends BrokenJCEBlockCipher
    {
        public OldPBEWithSHAAndTwofish()
        {
            super(new CBCBlockCipher(new TwofishEngine()), OLD_PKCS12, SHA1, 256, 128);
        }
    }
}


text:
using namespace std;
using namespace storage;

namespace search
{
namespace
{
// Calls |fn| on each node name on the way from |id| to the root of
// the |countries| tree, except the root. Does nothing if there are
// multiple ways from |id| to the |root|.
template <typename Fn>
void GetPathToRoot(storage::TCountryId const & id, storage::TCountryTree const & countries,
                   Fn && fn)
{
  vector<storage::TCountryTree::Node const *> nodes;
  countries.Find(id, nodes);

  if (nodes.empty())
    LOG(LWARNING, ("Can't find node in the countries tree for:", id));

  if (nodes.size() != 1 || nodes[0]->IsRoot())
    return;

  auto const * cur = nodes[0];
  do
  {
    fn(cur->Value().Name());
    cur = &cur->Parent();
  } while (!cur->IsRoot());
}
}  // namespace

void RegionInfoGetter::LoadCountriesTree()
{
  storage::TMappingAffiliations affiliations;
  storage::LoadCountriesFromFile(COUNTRIES_FILE, m_countries, affiliations);
}

void RegionInfoGetter::SetLocale(string const & locale)
{
  m_nameGetter = platform::GetTextByIdFactory(platform::TextSource::Countries, locale);
}

string RegionInfoGetter::GetLocalizedFullName(storage::TCountryId const & id) const
{
  size_t const kMaxNumParts = 2;

  vector<string> parts;
  GetPathToRoot(id, m_countries, [&](storage::TCountryId const & id) {
    parts.push_back(GetLocalizedCountryName(id));
  });

  if (parts.size() > kMaxNumParts)
    parts.erase(parts.begin(), parts.end() - kMaxNumParts);

  base::EraseIf(parts, [&](string const & s) { return s.empty(); });

  if (!parts.empty())
    return strings::JoinStrings(parts, ", ");

  // Tries to get at least localized name for |id|, if |id| is a
  // disputed territory.
  auto name = GetLocalizedCountryName(id);
  if (!name.empty())
    return name;

  // Tries to transform map name to the full name.
  name = id;
  storage::CountryInfo::FileName2FullName(name);
  if (!name.empty())
    return name;

  return {};
}

string RegionInfoGetter::GetLocalizedCountryName(storage::TCountryId const & id) const
{
  if (!m_nameGetter)
    return {};

  auto const shortName = (*m_nameGetter)(id + " Short");
  if (!shortName.empty())
    return shortName;

  auto const officialName = (*m_nameGetter)(id);
  if (!officialName.empty())
    return officialName;

  return {};
}
}  // namespace search


text:
class NullLogger
  def method_missing(*args)
  end
end


text:
namespace task
{

class Mechanics : private xpcc::pt::Protothread, public xpcc::co::NestedCoroutine<>
{
public:
	Mechanics(Leds &leds, Buttons &buttons);

	void
	initialize();

	void
	update();

	xpcc::co::Result<bool>
	calibrateX();

	xpcc::co::Result<bool>
	calibrateZ();

	bool ALWAYS_INLINE
	isCalibrated()
	{ return isCalibratedX && isCalibratedZ; }

	xpcc::co::Result<bool>
	rotateForward();

	xpcc::co::Result<bool>
	rotateBackward();

	void
	stopMotors();

	void
	releaseMotors();

private:
	void
	startMotors();

	bool
	run();

private:
	Leds &leds;
	Buttons &buttons;
	xpcc::Timeout<> timeout;

	bool isCalibratedX;
	bool isCalibratedZ;

	int16_t correctionX;
	int16_t correctionZ;

	Motor< X_Dir, X_Step, 400 * 8 > xMotor;
	Motor< Z_Dir, Z_Step, 400 * 8 > zMotor;
	xpcc::Timeout<> motorTimeout;
};

} // namespace task

#include "task_mechanics_impl.hpp"

#endif // TASK_MECHANICS_HPP


text:
package com.github.phiz71.rxjava.vertx.swagger.router;

import com.github.phiz71.rxjava.vertx.swagger.router.SwaggerRouter;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;

import io.vertx.core.json.JsonArray;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.core.eventbus.EventBus;
import io.vertx.rxjava.core.file.FileSystem;
import io.vertx.rxjava.ext.web.Router;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.nio.charset.Charset;

@RunWith(VertxUnitRunner.class)
public class SwaggerRouterTest {
    private static Vertx vertx;
    private static EventBus eventBus;
    private static JsonArray definitions;

    @BeforeClass
    public static void beforeClass(TestContext context) {
        Async async = context.async();
        vertx = Vertx.vertx();
        eventBus = vertx.eventBus();

        FileSystem vertxFileSystem = vertx.fileSystem();
        vertxFileSystem.readFile("swaggerRouterTest.json", readFile -> {
            try {
                if (readFile.succeeded()) {
                    final Buffer buffer = readFile.result();
                    definitions = new JsonArray(buffer.toString(Charset.forName("utf-8").toString()));
                } else {
                    context.fail(readFile.cause());
                }
            } catch (Throwable cause) {
                context.fail(cause);
            } finally {
                async.complete();
            }
        });
    }

    @Test(expected = IllegalArgumentException.class)
    public void testIllegalPathParameterName() {
        String definition = definitions.getJsonObject(0).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEmptyPathParameterName() {
        String definition = definitions.getJsonObject(1).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNumericPathParameterName() {
        String definition = definitions.getJsonObject(2).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testPathParameterNameStartsWithNumber() {
        String definition = definitions.getJsonObject(3).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test
    public void testAlphaNumericPathParameterName() {
        String definition = definitions.getJsonObject(4).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

}


text:
bool TamlJSONParser::accept( const char* pFilename, TamlVisitor& visitor )
{
    // Debug Profiling.
    PROFILE_SCOPE(TamlJSONParser_Accept);

    // Sanity!
    AssertFatal( pFilename != NULL, "Cannot parse a NULL filename." );

    // Expand the file-path.
    char filenameBuffer[1024];
    Con::expandPath( filenameBuffer, sizeof(filenameBuffer), pFilename );

    FileStream stream;

    // File open for read?
    if ( !stream.open( filenameBuffer, FileStream::Read ) )
    {
        // No, so warn.
        Con::warnf("TamlJSONParser::parse() - Could not open filename '%s' for parse.", filenameBuffer );
        return false;
    }

    // Read JSON file.
    const U32 streamSize = stream.getStreamSize();
    FrameTemp<char> jsonText( streamSize + 1 );
    if ( !stream.read( streamSize, jsonText ) )
    {
        // Warn!
        Con::warnf("TamlJSONParser::parse() - Could not load Taml JSON file from stream.");
        return false;
    }

    // Create JSON document.
    rapidjson::Document inputDocument;
    inputDocument.Parse<0>( jsonText );

    // Close the stream.
    stream.close();

    // Check the document is valid.
    if ( inputDocument.GetType() != rapidjson::kObjectType )
    {
        // Warn!
        Con::warnf("TamlJSONParser::parse() - Load Taml JSON file from stream but was invalid.");
        return false;
    }

    // Set parsing filename.
    setParsingFilename( filenameBuffer );

    // Flag document as not dirty.
    mDocumentDirty = false;

    // Fetch the root.
    rapidjson::Value::MemberIterator rootItr = inputDocument.MemberBegin();

    // Parse root value.
    parseType( rootItr, visitor, true );

    // Reset parsing filename.
    setParsingFilename( StringTable->EmptyString );

    // Finish if the document is not dirty.
    if ( !mDocumentDirty )
        return true;

    // Open for write?
    if ( !stream.open( filenameBuffer, FileStream::Write ) )
    {
        // No, so warn.
        Con::warnf("TamlJSONParser::parse() - Could not open filename '%s' for write.", filenameBuffer );
        return false;
    }

    // Create output document.
    rapidjson::Document outputDocument;
    outputDocument.AddMember( rootItr->name, rootItr->value, outputDocument.GetAllocator() );

    // Write document to stream.
    rapidjson::PrettyWriter<FileStream> jsonStreamWriter( stream );
    outputDocument.Accept( jsonStreamWriter );

    // Close the stream.
    stream.close();

    return true;
}

//-----------------------------------------------------------------------------

inline bool TamlJSONParser::parseType( rapidjson::Value::MemberIterator& memberItr, TamlVisitor& visitor, const bool isRoot )
{
    // Debug Profiling.
    PROFILE_SCOPE(TamlJSONParser_ParseType);

    // Fetch name and value.
    const rapidjson::Value& typeName = memberItr->name;
    rapidjson::Value& typeValue = memberItr->value;

    // Create a visitor property state.
    TamlVisitor::PropertyState propertyState;
    propertyState.setObjectName( typeName.GetString(), isRoot );

    // Parse field members.
    for( rapidjson::Value::MemberIterator fieldMemberItr = typeValue.MemberBegin(); fieldMemberItr != typeValue.MemberEnd(); ++fieldMemberItr )
    {
        // Fetch value.
        const rapidjson::Value& fieldName = fieldMemberItr->name;
        rapidjson::Value& fieldValue = fieldMemberItr->value;

        // Skip if not a field.
        if ( fieldValue.IsObject() )
            continue;

        char valueBuffer[4096];
        if ( !parseStringValue( valueBuffer, sizeof(valueBuffer), fieldValue, fieldName.GetString() ) )
        {
            // Warn.
            Con::warnf( "TamlJSONParser::parseTyoe() - Could not interpret value for field '%s'", fieldName.GetString() );
            continue;
        }

        // Configure property state.
        propertyState.setProperty( fieldName.GetString(), valueBuffer );

        // Visit this attribute.
        const bool visitStatus = visitor.visit( *this, propertyState );

        // Was the property value changed?
        if ( propertyState.getPropertyValueDirty() )
        {
            // Yes, so update the attribute.
            fieldValue.SetString( propertyState.getPropertyValue() );

            // Flag the document as dirty.
            mDocumentDirty = true;
        }

        // Finish if requested.
        if ( !visitStatus )
            return false;
    }

    // Finish if only the root is needed.
    if ( visitor.wantsRootOnly() )
        return false;

    // Parse children and custom node members.
    for( rapidjson::Value::MemberIterator objectMemberItr = typeValue.MemberBegin(); objectMemberItr != typeValue.MemberEnd(); ++objectMemberItr )
    {
        // Fetch name and value.
        const rapidjson::Value& objectValue = objectMemberItr->value;

        // Skip if not an object.
        if ( !objectValue.IsObject() )
            continue;

        // Parse the type.
        if ( !parseType( objectMemberItr, visitor, false ) )
            return false;
    }

    return true;
}

//-----------------------------------------------------------------------------

inline bool TamlJSONParser::parseStringValue( char* pBuffer, const S32 bufferSize, const rapidjson::Value& value, const char* pName )
{
    // Debug Profiling.
    PROFILE_SCOPE(TamlJSONParser_ParseStringValue);

    // Handle field value appropriately.

    if ( value.IsString() )
    {
        dSprintf( pBuffer, bufferSize, "%s", value.GetString() );
        return true;
    }

    if ( value.IsNumber() )
    {
        if ( value.IsInt() )
        {
            dSprintf( pBuffer, bufferSize, "%d", value.GetInt() );
            return true;
        }

        if ( value.IsUint() )
        {
            dSprintf( pBuffer, bufferSize, "%d", value.GetUint() );
            return true;
        }

        if ( value.IsInt64() )
        {
            dSprintf( pBuffer, bufferSize, "%d", value.GetInt64() );
            return true;
        }

        if ( value.IsUint64() )
        {
            dSprintf( pBuffer, bufferSize, "%d", value.GetUint64() );
            return true;
        }

        if ( value.IsDouble() )
        {
            dSprintf( pBuffer, bufferSize, "%f", value.GetDouble() );
            return true;
        }
    }

    if ( value.IsBool() )
    {
        dSprintf( pBuffer, bufferSize, "%d", value.GetBool() );
        return true;
    }

    // Failed to get value type.
    Con::warnf( "Taml: Encountered a field '%s' but its value is an unknown type.", pName );
    return false;
}


text:
.PHONY: all clean texfirst texsecond builddir refs

builddir:
	mkdir -p build

texfirst: ${IMAGES} | builddir
	xelatex -output-directory=build report.tex

refs: texfirst
	bibtex build/report.aux

texsecond: refs
	xelatex -output-directory=build report.tex

clean:
	rm -r build/
	rm -r images/*.pdf

all: texsecond


text:
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <title>Instagram</title>
    <link rel="shortcut icon" href="favicon.ico">
    <script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>
    <link rel="import" href="instagram-timeline.html">
  </head>

  <body unresolved >
    <template id="Demo" is="dom-bind">
      <instagram-timeline id="componentTested" endpoint="http://instagram-timeline.appspot.com/request/instagram" access-token="218613700.6ec4dda.1e5145d02f8944368c24de890c984ad3" language="{{language}}">
      </instagram-timeline>
      <br>
      <button name="es" on-click="changeIdiom">Spanish</button>
      <button name="en" on-click="changeIdiom">English</button>

      <script type="text/javascript">

        Demo.language = "es";
        Demo.changeIdiom = function(event,detail) {
          Demo.language = event.target.getAttribute('name');
        }
      </script>
      </body>
    </html>


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

import BaseChannelNode from './BaseChannelNode';

class ChangeListener {
  constructor() {
    this.connPoint = null;
    this.connectionMessage = null;
  }

  notifyAdd(key, node) {
    this.connPoint.connectNode(node, this.connectionMessage);
    return this;
  }

  notifyUpdate(key, prevNode, node) {
    this.connPoint.disconnectNode(prevNode, this.connectionMessage);
    this.connPoint.connectNode(node, this.connectionMessage);
    return this;
  }

  notifyRemove(key, node) {
    this.connPoint.disconnectNode(node, this.connectionMessage);
    return this;
  }

  notifyKeep(key, node) {
    this.connPoint.keepConnectedNode(node, this.connectionMessage);
    return this;
  }
}

export default defineClass('ConnectionPointNode')
  .includes(BaseChannelNode.prototype)

  .propertyInitializer('changeListener', () => new ChangeListener() )

  .methods({
    setConnectionPoint(connPoint) {
      this.connPoint = connPoint;
      this.changeListener.connPoint = connPoint;
      return this;
    },

    receiveJointChannelMessage(msg, payload) {
      const connectionPointMessage = msg.createNextConnectionPointMessage();
      const connectionMessage =
        this.connPoint.exchangeConnectionPointMessage(connectionPointMessage);

      this.changeListener.connectionMessage = connectionMessage;

      payload.deliver(this);

      connectionMessage.completeUpdateFrom(this);
      this.changeListener.connectionMessage = null;
      return this;
    },
  })
  .buildConstructor();


text:
include Chef::Provider::WindowsFeature::Base
include Chef::Mixin::ShellOut
include Windows::Helper

# Exit codes are listed at http://technet.microsoft.com/en-us/library/cc749128(v=ws.10).aspx

def check_reboot(result, feature)
  if result.exitstatus == 3010 # successful, but needs reboot
    node.run_state[:reboot_requested] = true
    Chef::Log.warn("Require reboot to install #{feature}")
  elsif result.exitstatus == 1001 # failure, but needs reboot before we can do anything else
    node.run_state[:reboot_requested] = true
    Chef::Log.warn("Failed installing #{feature} and need to reboot")
  end
  result.error! # throw for any other bad results. The above results will also get raised, and should cause a reboot via the handler.
end

def install_feature(_name)
  check_reboot(shell_out("#{servermanagercmd} -install #{@new_resource.feature_name}", returns: [0, 42, 127, 1003, 3010]), @new_resource.feature_name)
end

def remove_feature(_name)
  check_reboot(shell_out("#{servermanagercmd} -remove #{@new_resource.feature_name}", returns: [0, 42, 127, 1003, 3010]), @new_resource.feature_name)
end

def installed?
  @installed ||= begin
    cmd = shell_out("#{servermanagercmd} -query", returns: [0, 42, 127, 1003])
    cmd.stderr.empty? && (cmd.stdout =~ /^\s*?\[X\]\s.+?\s\[#{@new_resource.feature_name}\]\s*$/i)
  end
end

private

# account for File System Redirector
# http://msdn.microsoft.com/en-us/library/aa384187(v=vs.85).aspx
def servermanagercmd
  @servermanagercmd ||= begin
    locate_sysnative_cmd('servermanagercmd.exe')
  end
end


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var app = angular.module("BlocItOff", ["firebase", "ui.router", "angularMoment"]);

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
  $urlRouterProvider.otherwise('/');

  $stateProvider.state('home', {
    url: '/',
    views: {
      '': {
        controller: 'TaskCtrl.controller',
        templateUrl: '/templates/home.html'
      },
      'submitTask@home': {
        controller: 'TaskCtrl.controller',
        templateUrl: '/templates/submitTask.html'
      }
    }
  });
  $stateProvider.state('pastTasks', {
    url: '/pastTasks',
    controller: 'TaskCtrl.controller',
    templateUrl: '/templates/pastTasks.html'
  });

  moment.locale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s:  "%d seconds",
        m:  "a minute",
        mm: "%d minutes",
        h:  "an hour",
        hh: "%d hours",
        d:  "a day",
        dd: "%d days",
        M:  "a month",
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
  });
}]);

app.controller("TaskCtrl.controller", ["$scope", "taskListService", "$interval",
  function($scope, taskListService, $interval){
    var ellapsedMilliseconds = 604800000; //TODO: could be converted to a constant

    var status = ["completed", "expired", "active"];

    $scope.priority = "medium";

    $scope.tasks = taskListService.getTasks();

    $interval(function(){
      $scope.timeStamp = +(new Date);
    }, 100);

    //Note: could change the name

    $scope.taskFilter = function(task){
      //console.log(task);
      return (task.status == "completed" || task.status == "expired");
    }

    $scope.addNewTask = function() {
      taskListService.add($scope.task, $scope.priority);
      $scope.task = "";
    };

    $scope.hideTask = function(task) {

      if($scope.taskFilter(task))
        return true; //If task has already been marked completed just return true

      //TODO: possible refactor here...
      if (($scope.timeStamp - task.taskAddTime) >= ellapsedMilliseconds) { //If time has ellapsed by x milliseconds do this
        task.status = "expired";
      //  task.taskCompleted = true;
        taskListService.updateTask(task); //update the task completed flag
        return true;
      }
      else {
        return false;
      }
    }

    $scope.checkMe = function(task){
      task.status = "completed";
    //  task.isSelected = !task.isSelected;  //inverts the boolean, by default all new task will be marked false
      taskListService.updateTask(task);
    }

  }]);
module.exports =app;

},{}],2:[function(require,module,exports){
var app = require('./app.js'); //not normal angular

app.filter('prioritySort', function(){
  function PriorityOrder(item){
    switch(item){
      case "high":
        return 1;
      case "medium":
        return 2;
      case "low":
        return 3;
    }
  }

  return function(items, field) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (PriorityOrder(a.priority) > PriorityOrder(b.priority) ? 1 : -1);
    });
    return filtered;
  };
})

},{"./app.js":1}],3:[function(require,module,exports){
var app = require('./app.js');

app.directive("taskComplete", ['taskListService', function(taskListService){
  return {
    template: '',
    link: function(scope, elem, attr){
      elem.on('click', function(){
        var task = scope.task;
        task.status = "completed";
        taskListService.updateTask(task);
        //scope.$apply();
      });
    }
  };
}]);

},{"./app.js":1}],4:[function(require,module,exports){
var app = require('./app.js');

app.factory("taskListService", ["$firebaseArray",
  function($firebaseArray){

    var taskList = [];
    var ref = new Firebase("https://scorching-torch-4465.firebaseio.com/messages");
    taskList = $firebaseArray(ref);

    var getTasks = function(){
      return taskList;
    }

    var add = function(taskName, taskPriority){

      var now = +(new Date);
      var item = {
        content: taskName,
        status: "active",
        taskAddTime: now,
        priority: taskPriority,
        isSelected: false
      };

      taskList.$add(item)
      /*.then(function(addedTask){
        if(addedTask){
          console.log("Added Task ", addedTask.key())
        }
      }, function(err){
        console.log(err);
      });*/
    };

    var update = function(task){
       taskList.$save(task)
        /*.then(function(updatedTask){
          console.log("Updated Task:", updatedTask.key());
        }, function(err){
          console.log("The hell", err);
        });*/
    };

    return {
      getTasks : getTasks,
      add : add,
      updateTask : update
    }
  }
]);

},{"./app.js":1}]},{},[1,2,3,4]);