text:
// Copyright (c) 2009-2012 Bitcoin Developers
// Copyright (c) 2012-2013 The Peercoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

//#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>

#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include "main.h"
#include "db.h"
#include "wallet.h"

#include <boost/lexical_cast.hpp>

#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"

#define printf OutputDebugStringF

// using namespace boost::asio;
using namespace json_spirit;
using namespace std;

extern Object JSONRPCError(int code, const string& message);

class CTxDump
{
public:
    CBlockIndex *pindex;
    int64 nValue;
    bool fSpent;
    CWalletTx* ptx;
    int nOut;
    CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
    {
        pindex = NULL;
        nValue = 0;
        fSpent = false;
        this->ptx = ptx;
        this->nOut = nOut;
    }
};

Value importpassphrase(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "importpassphrase \"<passphrase>\" [label]\n"
            "Adds a private key into your wallet.");
    string strSecret = params[0].get_str();
    uint256 pass = sha256((const u8int*)strSecret.c_str(), strSecret.length());
    CSecret passSecret;
    passSecret.resize(32);
    for (int i = 0; i < 32; i++) {
        passSecret[i] = (pass.begin())[i];
    }

    string strLabel = "";
    if(params.size() > 1)
        strLabel = params[1].get_str();

    CBitcoinSecret vchSecret;
    bool fCompressed = true;
    vchSecret.SetSecret( passSecret , fCompressed );

    //if (!fGood) throw JSONRPCError(-5, "Invalid private key");
    if (pwalletMain->IsLocked())
        throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
    if (fWalletUnlockMintOnly) // slimcoin: no importprivkey in mint-only mode
        throw JSONRPCError(-102, "Wallet is unlocked for minting only.");

    CKey key;
    CSecret secret = vchSecret.GetSecret(fCompressed);
    key.SetSecret(secret, fCompressed);
    /* FIXME: sanity check required */
    CBitcoinAddress vchAddress = CBitcoinAddress(key.GetPubKey().GetID());

    {
        LOCK2(cs_main, pwalletMain->cs_wallet);

        pwalletMain->MarkDirty();
        pwalletMain->SetAddressBookName(CTxDestination(vchAddress.Get()), strLabel);

        if (!pwalletMain->AddKey(key))
            throw JSONRPCError(-4,"Error adding key to wallet");

        pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
        pwalletMain->ReacceptWalletTransactions();
    }

    MainFrameRepaint();
    Object obj;
    obj.push_back(Pair("Secret",        CBitcoinSecret( passSecret, fCompressed ).ToString() ));
    obj.push_back(Pair("Address",       vchAddress.ToString()));
    obj.push_back(Pair("Hash",          pass.GetHex()));
    obj.push_back(Pair("Phrase",        strSecret));
    obj.push_back(Pair("Length",   (int)strSecret.length()));
    return obj;
    // return Value::null;
}

Value importprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 3)
        throw runtime_error(
            "importprivkey <slimcoinprivkey> [label] [rescan=false]\n"
            "Adds a private key (as returned by dumpprivkey) to your wallet.");

    string strSecret = params[0].get_str();
    string strLabel = "";
    if (params.size() > 1)
        strLabel = params[1].get_str();
    CBitcoinSecret vchSecret;
    bool fGood = vchSecret.SetString(strSecret);

    // Whether to perform rescan after import
    bool fRescan = false;
    if (params.size() > 2)
        fRescan = params[2].get_bool();

    if (!fGood) throw JSONRPCError(-5,"Invalid private key");
    if (pwalletMain->IsLocked())
        throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
    if (fWalletUnlockMintOnly) // slimcoin: no importprivkey in mint-only mode
        throw JSONRPCError(-102, "Wallet is unlocked for minting only.");

    CKey key;
    bool fCompressed;
    CSecret secret = vchSecret.GetSecret(fCompressed);
    key.SetSecret(secret, fCompressed);
    CKeyID vchAddress = key.GetPubKey().GetID();
    {
        LOCK2(cs_main, pwalletMain->cs_wallet);

        pwalletMain->MarkDirty();
        pwalletMain->SetAddressBookName(vchAddress, strLabel);

        if (!pwalletMain->AddKey(key))
            throw JSONRPCError(-4,"Error adding key to wallet");

        if (fRescan) {
          pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
          pwalletMain->ReacceptWalletTransactions();
        }
    }

    MainFrameRepaint();

    return Value::null;
}

Value dumpprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
      "dumpprivkey <slimcoinaddress>\n"
      "Reveals the private key corresponding to <slimcoinaddress>.");

    string strAddress = params[0].get_str();
    CBitcoinAddress address;
    if (!address.SetString(strAddress))
        throw JSONRPCError(-5, "Invalid slimcoin address");
    if (pwalletMain->IsLocked())
        throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
    if (fWalletUnlockMintOnly) // slimcoin: no dumpprivkey in mint-only mode
        throw JSONRPCError(-102, "Wallet is unlocked for minting only.");
    CKeyID keyID;
    if (!address.GetKeyID(keyID))
        throw JSONRPCError(-3, "Address does not refer to a key");
    CSecret vchSecret;
    bool fCompressed;
    if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
        throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known");
    return CBitcoinSecret(vchSecret, fCompressed).ToString();
}

// Return average network hashes per second based on the last 'lookup' blocks,
// or from the last difficulty change if 'lookup' is nonpositive.
// If 'height' is nonnegative, compute the estimate at the time when a given block was found.
/*
Value GetNetworkHashPS(int lookup, int height) {
    CBlockIndex *pb = pindexBest;

    if (height >= 0 && height < nBestHeight)
        pb = FindBlockByHeight(height);

    if (pb == NULL || !pb->nHeight)
        return 0;

    // If lookup is -1, then use blocks since last difficulty change.
    if (lookup <= 0)
        lookup = pb->nHeight % 2016 + 1;

    // If lookup is larger than chain, then set it to chain length.
    if (lookup > pb->nHeight)
        lookup = pb->nHeight;

    CBlockIndex *pb0 = pb;
    int64 minTime = pb0->GetBlockTime();
    int64 maxTime = minTime;
    for (int i = 0; i < lookup; i++) {
        pb0 = pb0->pprev;
        int64 time = pb0->GetBlockTime();
        minTime = std::min(time, minTime);
        maxTime = std::max(time, maxTime);
    }

    // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
    if (minTime == maxTime)
        return 0;

    // uint256 workDiff = pb->nChainWork - pb0->nChainWork;
    CBigNum workDiff = pb->bnChainTrust - pb0->bnChainTrust;
    int64 timeDiff = maxTime - minTime;

    return (boost::int64_t)(workDiff.getuint64() / timeDiff);
}

Value getnetworkhashps(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getnetworkhashps [blocks] [height]\n"
            "Returns the estimated network hashes per second based on the last 120 blocks.\n"
            "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
            "Pass in [height] to estimate the network speed at the time when a certain block was found.");

    return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
}
*/


text:
package org.apache.nifi.processors.standard;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Paths;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import org.apache.commons.codec.binary.Hex;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.security.util.EncryptionMethod;
import org.apache.nifi.security.util.KeyDerivationFunction;
import org.apache.nifi.security.util.crypto.CipherUtility;
import org.apache.nifi.security.util.crypto.PasswordBasedEncryptor;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.MockProcessContext;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.bouncycastle.bcpg.BCPGInputStream;
import org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.bouncycastle.openpgp.PGPUtil.getDecoderStream;
import static org.junit.Assert.fail;

public class TestEncryptContent {

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

    private static AllowableValue[] getPGPCipherList() {
        try{
            Method method = EncryptContent.class.getDeclaredMethod("buildPGPSymmetricCipherAllowableValues");
            method.setAccessible(true);
            return ((AllowableValue[]) method.invoke(null));
        } catch (Exception e){
            logger.error("Cannot access buildPGPSymmetricCipherAllowableValues", e);
            fail("Cannot access buildPGPSymmetricCipherAllowableValues");
        }
        return null;
    }

    @Before
    public void setUp() {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Test
    public void testRoundTrip() throws IOException {
        final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
        testRunner.setProperty(EncryptContent.PASSWORD, "short");
        testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NIFI_LEGACY.name());
        // Must be allowed or short password will cause validation errors
        testRunner.setProperty(EncryptContent.ALLOW_WEAK_CRYPTO, "allowed");

        for (final EncryptionMethod encryptionMethod : EncryptionMethod.values()) {
            if (encryptionMethod.isUnlimitedStrength()) {
                continue;   // cannot test unlimited strength in unit tests because it's not enabled by the JVM by default.
            }

            // KeyedCiphers tested in TestEncryptContentGroovy.groovy
            if (encryptionMethod.isKeyedCipher()) {
                continue;
            }

            logger.info("Attempting {}", encryptionMethod.name());
            testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, encryptionMethod.name());
            testRunner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);

            testRunner.enqueue(Paths.get("src/test/resources/hello.txt"));
            testRunner.clearTransferState();
            testRunner.run();

            testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);

            MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
            testRunner.assertQueueEmpty();

            testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
            testRunner.enqueue(flowFile);
            testRunner.clearTransferState();
            testRunner.run();
            testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);

            logger.info("Successfully decrypted {}", encryptionMethod.name());

            flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
            flowFile.assertContentEquals(new File("src/test/resources/hello.txt"));
        }
    }

    @Test
    public void testPGPCiphersRoundTrip() {
        final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
        testRunner.setProperty(EncryptContent.PASSWORD, "passwordpassword"); // a >=16 characters password
        testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NONE.name());

        List<String> pgpAlgorithms = new ArrayList<>();
        pgpAlgorithms.add("PGP");
        pgpAlgorithms.add("PGP_ASCII_ARMOR");

        for (String algorithm : pgpAlgorithms) {
            testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, algorithm);
            for (AllowableValue cipher : Objects.requireNonNull(getPGPCipherList())) {
                testRunner.setProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER, cipher.getValue());
                testRunner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);

                testRunner.enqueue("A cool plaintext!");
                testRunner.clearTransferState();
                testRunner.run();

                testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);

                MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
                testRunner.assertQueueEmpty();

                testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
                // Encryption cipher is inferred from ciphertext, this property deliberately set a fixed cipher to prove
                // the output will still be correct
                testRunner.setProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER, "1");

                testRunner.enqueue(flowFile);
                testRunner.clearTransferState();
                testRunner.run();
                testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);

                flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
                flowFile.assertContentEquals("A cool plaintext!");
            }
        }
    }

    @Test
    public void testPGPCiphers() throws Exception {
        final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
        testRunner.setProperty(EncryptContent.PASSWORD, "passwordpassword"); // a >= 16 characters password
        testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NONE.name());

        List<String> pgpAlgorithms = new ArrayList<>();
        pgpAlgorithms.add("PGP");
        pgpAlgorithms.add("PGP_ASCII_ARMOR");

        for (String algorithm : pgpAlgorithms) {

            testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, algorithm);
            for (AllowableValue cipher : Objects.requireNonNull(getPGPCipherList())) {
                testRunner.setProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER, cipher.getValue());
                testRunner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);

                testRunner.enqueue("A cool plaintext!");
                testRunner.clearTransferState();
                testRunner.run();

                testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);

                MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
                testRunner.assertQueueEmpty();

                // Other than the round trip, checks that the provided cipher is actually used, inferring it from the ciphertext
                InputStream ciphertext = new ByteArrayInputStream(flowFile.toByteArray());
                BCPGInputStream pgpin = new BCPGInputStream(getDecoderStream(ciphertext));
                assert pgpin.nextPacketTag() == 3;
                assert ((SymmetricKeyEncSessionPacket) pgpin.readPacket()).getEncAlgorithm() == Integer.valueOf(cipher.getValue());
                pgpin.close();
            }
        }
    }

    @Test
    public void testShouldDetermineMaxKeySizeForAlgorithms() throws IOException {
        // Arrange
        final String AES_ALGORITHM = EncryptionMethod.MD5_256AES.getAlgorithm();
        final String DES_ALGORITHM = EncryptionMethod.MD5_DES.getAlgorithm();

        final int AES_MAX_LENGTH = PasswordBasedEncryptor.supportsUnlimitedStrength() ? Integer.MAX_VALUE : 128;
        final int DES_MAX_LENGTH = PasswordBasedEncryptor.supportsUnlimitedStrength() ? Integer.MAX_VALUE : 64;

        // Act
        int determinedAESMaxLength = PasswordBasedEncryptor.getMaxAllowedKeyLength(AES_ALGORITHM);
        int determinedTDESMaxLength = PasswordBasedEncryptor.getMaxAllowedKeyLength(DES_ALGORITHM);

        // Assert
        assert determinedAESMaxLength == AES_MAX_LENGTH;
        assert determinedTDESMaxLength == DES_MAX_LENGTH;
    }

    @Test
    public void testShouldDecryptOpenSSLRawSalted() throws IOException {
        // Arrange
        Assume.assumeTrue("Test is being skipped due to this JVM lacking JCE Unlimited Strength Jurisdiction Policy file.",
                PasswordBasedEncryptor.supportsUnlimitedStrength());

        final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());

        final String password = "thisIsABadPassword";
        final EncryptionMethod method = EncryptionMethod.MD5_256AES;
        final KeyDerivationFunction kdf = KeyDerivationFunction.OPENSSL_EVP_BYTES_TO_KEY;

        testRunner.setProperty(EncryptContent.PASSWORD, password);
        testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, kdf.name());
        testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, method.name());
        testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);

        // Act
        testRunner.enqueue(Paths.get("src/test/resources/TestEncryptContent/salted_raw.enc"));
        testRunner.clearTransferState();
        testRunner.run();

        // Assert
        testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
        testRunner.assertQueueEmpty();

        MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
        logger.info("Decrypted contents (hex): {}", Hex.encodeHexString(flowFile.toByteArray()));
        logger.info("Decrypted contents: {}", new String(flowFile.toByteArray(), "UTF-8"));

        // Assert
        flowFile.assertContentEquals(new File("src/test/resources/TestEncryptContent/plain.txt"));
    }

    @Test
    public void testShouldDecryptOpenSSLRawUnsalted() throws IOException {
        // Arrange
        Assume.assumeTrue("Test is being skipped due to this JVM lacking JCE Unlimited Strength Jurisdiction Policy file.",
                PasswordBasedEncryptor.supportsUnlimitedStrength());

        final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());

        final String password = "thisIsABadPassword";
        final EncryptionMethod method = EncryptionMethod.MD5_256AES;
        final KeyDerivationFunction kdf = KeyDerivationFunction.OPENSSL_EVP_BYTES_TO_KEY;

        testRunner.setProperty(EncryptContent.PASSWORD, password);
        testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, kdf.name());
        testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, method.name());
        testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);

        // Act
        testRunner.enqueue(Paths.get("src/test/resources/TestEncryptContent/unsalted_raw.enc"));
        testRunner.clearTransferState();
        testRunner.run();

        // Assert
        testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
        testRunner.assertQueueEmpty();

        MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
        logger.info("Decrypted contents (hex): {}", Hex.encodeHexString(flowFile.toByteArray()));
        logger.info("Decrypted contents: {}", new String(flowFile.toByteArray(), "UTF-8"));

        // Assert
        flowFile.assertContentEquals(new File("src/test/resources/TestEncryptContent/plain.txt"));
    }

    @Test
    public void testDecryptShouldDefaultToBcrypt() throws IOException {
        // Arrange
        final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());

        // Assert
        Assert.assertEquals("Decrypt should default to Legacy KDF", testRunner.getProcessor().getPropertyDescriptor(EncryptContent.KEY_DERIVATION_FUNCTION
                .getName()).getDefaultValue(), KeyDerivationFunction.BCRYPT.name());
    }

    @Test
    public void testDecryptSmallerThanSaltSize() {
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        runner.setProperty(EncryptContent.PASSWORD, "Hello, World!");
        runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
        runner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NIFI_LEGACY.name());
        runner.enqueue(new byte[4]);
        runner.run();
        runner.assertAllFlowFilesTransferred(EncryptContent.REL_FAILURE, 1);
    }

    @Test
    public void testPGPDecrypt() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP_ASCII_ARMOR.name());
        runner.setProperty(EncryptContent.PASSWORD, "Hello, World!");

        runner.enqueue(Paths.get("src/test/resources/TestEncryptContent/text.txt.asc"));
        runner.run();

        runner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
        final MockFlowFile flowFile = runner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/TestEncryptContent/text.txt"));
    }

    @Test
    public void testShouldValidatePGPPublicKeyringRequiresUserId() {
        // Arrange
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        Collection<ValidationResult> results;
        MockProcessContext pc;

        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
        runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();

        // Act
        results = pc.validate();

        // Assert
        Assert.assertEquals(1, results.size());
        ValidationResult vr = (ValidationResult) results.toArray()[0];
        String expectedResult = " encryption without a " + EncryptContent.PASSWORD.getDisplayName() + " requires both "
                + EncryptContent.PUBLIC_KEYRING.getDisplayName() + " and "
                + EncryptContent.PUBLIC_KEY_USERID.getDisplayName();
        String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
        Assert.assertTrue(message, vr.toString().contains(expectedResult));
    }

    @Test
    public void testShouldValidatePGPPublicKeyringExists() {
        // Arrange
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        Collection<ValidationResult> results;
        MockProcessContext pc;

        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
        runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg.missing");
        runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "USERID");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();

        // Act
        results = pc.validate();

        // Assert
        Assert.assertEquals(1, results.size());
        ValidationResult vr = (ValidationResult) results.toArray()[0];
        String expectedResult = "java.io.FileNotFoundException";
        String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
        Assert.assertTrue(message, vr.toString().contains(expectedResult));
    }

    @Test
    public void testShouldValidatePGPPublicKeyringIsProperFormat() {
        // Arrange
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        Collection<ValidationResult> results;
        MockProcessContext pc;

        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
        runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/text.txt");
        runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "USERID");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();

        // Act
        results = pc.validate();

        // Assert
        Assert.assertEquals(1, results.size());
        ValidationResult vr = (ValidationResult) results.toArray()[0];
        String expectedResult = " java.io.IOException: invalid header encountered";
        String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
        Assert.assertTrue(message, vr.toString().contains(expectedResult));
    }

    @Test
    public void testShouldValidatePGPPublicKeyringContainsUserId() {
        // Arrange
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        Collection<ValidationResult> results;
        MockProcessContext pc;

        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
        runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg");
        runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "USERID");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();

        // Act
        results = pc.validate();

        // Assert
        Assert.assertEquals(1, results.size());
        ValidationResult vr = (ValidationResult) results.toArray()[0];
        String expectedResult = "PGPException: Could not find a public key with the given userId";
        String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
        Assert.assertTrue(message, vr.toString().contains(expectedResult));
    }

    @Test
    public void testShouldExtractPGPPublicKeyFromKeyring() {
        // Arrange
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        Collection<ValidationResult> results;
        MockProcessContext pc;

        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
        runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg");
        runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "NiFi PGP Test Key (Short test key for NiFi PGP unit tests) <alopresto.apache+test@gmail.com>");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();

        // Act
        results = pc.validate();

        // Assert
        Assert.assertEquals(0, results.size());
    }

    @Test
    public void testValidation() {
        final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
        Collection<ValidationResult> results;
        MockProcessContext pc;

        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();
        results = pc.validate();
        Assert.assertEquals(results.toString(), 1, results.size());
        for (final ValidationResult vr : results) {
            Assert.assertTrue(vr.toString()
                    .contains(EncryptContent.PASSWORD.getDisplayName() + " is required when using algorithm"));
        }

        runner.enqueue(new byte[0]);
        final EncryptionMethod encryptionMethod = EncryptionMethod.MD5_128AES;
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, encryptionMethod.name());
        runner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NIFI_LEGACY.name());
        runner.setProperty(EncryptContent.PASSWORD, "ThisIsAPasswordThatIsLongerThanSixteenCharacters");
        pc = (MockProcessContext) runner.getProcessContext();
        results = pc.validate();
        if (!PasswordBasedEncryptor.supportsUnlimitedStrength()) {
            logger.info(results.toString());
            Assert.assertEquals(1, results.size());
            for (final ValidationResult vr : results) {
                Assert.assertTrue(
                        "Did not successfully catch validation error of a long password in a non-JCE Unlimited Strength environment",
                        vr.toString().contains("Password length greater than " + CipherUtility.getMaximumPasswordLengthForAlgorithmOnLimitedStrengthCrypto(encryptionMethod)
                                + " characters is not supported by this JVM due to lacking JCE Unlimited Strength Jurisdiction Policy files."));
            }
        } else {
            Assert.assertEquals(results.toString(), 0, results.size());
        }
        runner.removeProperty(EncryptContent.PASSWORD);

        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
        runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/text.txt");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();
        results = pc.validate();
        Assert.assertEquals(1, results.size());
        for (final ValidationResult vr : results) {
            Assert.assertTrue(vr.toString().contains(
                    " encryption without a " + EncryptContent.PASSWORD.getDisplayName() + " requires both "
                            + EncryptContent.PUBLIC_KEYRING.getDisplayName() + " and "
                            + EncryptContent.PUBLIC_KEY_USERID.getDisplayName()));
        }

        // Legacy tests moved to individual tests to comply with new library

        // TODO: Move secring tests out to individual as well

        runner.removeProperty(EncryptContent.PUBLIC_KEYRING);
        runner.removeProperty(EncryptContent.PUBLIC_KEY_USERID);

        runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
        runner.setProperty(EncryptContent.PRIVATE_KEYRING, "src/test/resources/TestEncryptContent/secring.gpg");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();
        results = pc.validate();
        Assert.assertEquals(1, results.size());
        for (final ValidationResult vr : results) {
            Assert.assertTrue(vr.toString().contains(
                    " decryption without a " + EncryptContent.PASSWORD.getDisplayName() + " requires both "
                            + EncryptContent.PRIVATE_KEYRING.getDisplayName() + " and "
                            + EncryptContent.PRIVATE_KEYRING_PASSPHRASE.getDisplayName()));

        }

        runner.setProperty(EncryptContent.PRIVATE_KEYRING_PASSPHRASE, "PASSWORD");
        runner.enqueue(new byte[0]);
        pc = (MockProcessContext) runner.getProcessContext();
        results = pc.validate();
        Assert.assertEquals(1, results.size());
        for (final ValidationResult vr : results) {
            Assert.assertTrue(vr.toString().contains(
                    " could not be opened with the provided " + EncryptContent.PRIVATE_KEYRING_PASSPHRASE.getDisplayName()));

        }
        runner.removeProperty(EncryptContent.PRIVATE_KEYRING_PASSPHRASE);

        // This configuration is invalid because PGP_SYMMETRIC_ENCRYPTION_CIPHER is outside the allowed [1-13] interval
        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, "PGP");
        runner.setProperty(EncryptContent.PASSWORD, "PASSWORD");
        runner.setProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER, "256");
        runner.assertNotValid();

        // This configuration is invalid because PGP_SYMMETRIC_ENCRYPTION_CIPHER points to SAFER cipher which is unsupported
        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, "PGP");
        runner.setProperty(EncryptContent.PASSWORD, "PASSWORD");
        runner.setProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER, "5");
        runner.assertNotValid();

        // This configuration is valid
        runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, "PGP");
        runner.setProperty(EncryptContent.PASSWORD, "PASSWORD");
        runner.removeProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER);
        runner.assertValid();

        // This configuration is valid because the default value will be used for PGP_SYMMETRIC_ENCRYPTION_CIPHER
        runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
        runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, "PGP");
        runner.setProperty(EncryptContent.PASSWORD, "PASSWORD");
        runner.removeProperty(EncryptContent.PGP_SYMMETRIC_ENCRYPTION_CIPHER);
        runner.assertValid();
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Check that available RPM packages match the required versions."""

from openshift_checks import OpenShiftCheck
from openshift_checks.mixins import NotContainerizedMixin

class PackageVersion(NotContainerizedMixin, OpenShiftCheck):
    """Check that available RPM packages match the required versions."""

    name = "package_version"
    tags = ["preflight"]

    def is_active(self):
        """Skip hosts that do not have package requirements."""
        group_names = self.get_var("group_names", default=[])
        master_or_node = 'oo_masters_to_config' in group_names or 'oo_nodes_to_config' in group_names
        return super(PackageVersion, self).is_active() and master_or_node

    def run(self):
        rpm_prefix = self.get_var("openshift_service_type")
        if self._templar is not None:
            rpm_prefix = self._templar.template(rpm_prefix)
        openshift_release = self.get_var("openshift_release", default='')
        deployment_type = self.get_var("openshift_deployment_type")
        check_multi_minor_release = deployment_type in ['openshift-enterprise']

        args = {
            "package_mgr": self.get_var("ansible_pkg_mgr"),
            "package_list": [
                {
                    "name": "{}".format(rpm_prefix),
                    "version": openshift_release,
                    "check_multi": check_multi_minor_release,
                },
                {
                    "name": "{}-master".format(rpm_prefix),
                    "version": openshift_release,
                    "check_multi": check_multi_minor_release,
                },
                {
                    "name": "{}-node".format(rpm_prefix),
                    "version": openshift_release,
                    "check_multi": check_multi_minor_release,
                },
            ],
        }

        return self.execute_module_with_retries("aos_version", args)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>one-player</title>

    <link rel="stylesheet" href="../../node_modules/weatherstar-switch/dist/switch.css">

    <link rel="stylesheet" href="./css/popup.css"/>
    <link rel="stylesheet" href="./css/font.css"/>

                    <input id="lrc-check" type="checkbox" />

-

加载中...


text:
title: stream
type: example
layout: example
web_bundle_url: ../js/examples/stream.web.js
---

```html
<template>
  <div class="wrapper">
    <div class="group">
      <text class="title">Weex Star :</text>
      <text class="count">{{weexStar}}</text>
    </div>
    <div class="group">
      <text class="title">Vue Star :</text>
      <text class="count">{{vueStar}}</text>
    </div>
  </div>
</template>

<script>
  var stream = weex.requireModule('stream')
  export default {
    data () {
      return {
        weexStar: 'unknown',
        vueStar: 'unknown'
      }
    },

    methods: {
      getStarCount (repo, callback) {
        return stream.fetch({
          method: 'GET',
          type: 'json',
          url: 'https://api.github.com/repos/' + repo
        }, callback)
      }
    },
    created () {
      this.getStarCount('alibaba/weex', res => {
        this.weexStar = res.ok ? res.data.stargazers_count : '(network error)'
      })
      this.getStarCount('vuejs/vue', res => {
        this.vueStar = res.ok ? res.data.stargazers_count : '(network error)'
      })
    }
  }
</script>

<style scoped>
  .wrapper {
    flex-direction: column;
    justify-content: center;
  }
  .group {
    flex-direction: row;
    justify-content: center;
    margin-bottom: 40px;
  }
  .title {
    font-size: 45px;
    color: #888888;
  }
  .count {
    font-size: 45px;
    font-weight: bold;
    margin-left: 12px;
    color: #41B883;
  }
</style>
```


text:
/**
 * Spring Social's Service API for LinkedIn
 */
package org.springframework.social.linkedin.api;


text:
package org.apache.fineract.accounting.provisioning.domain;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Table(name = "m_provisioning_history")
public class ProvisioningEntry extends AbstractPersistable<Long> {

    @Column(name = "journal_entry_created")
    private Boolean isJournalEntryCreated;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", orphanRemoval = true, fetch=FetchType.EAGER)
    Set<LoanProductProvisioningEntry> provisioningEntries = new HashSet<>();

    @OneToOne
    @JoinColumn(name = "createdby_id")
    private AppUser createdBy;

    @Column(name = "created_date")
    @Temporal(TemporalType.DATE)
    private Date createdDate;

    @OneToOne
    @JoinColumn(name = "lastmodifiedby_id")
    private AppUser lastModifiedBy;

    @Column(name = "lastmodified_date")
    @Temporal(TemporalType.DATE)
    private Date lastModifiedDate;

    protected ProvisioningEntry() {

    }

    public ProvisioningEntry(AppUser createdBy, Date createdDate, AppUser lastModifiedBy, Date lastModifiedDate, Set<LoanProductProvisioningEntry> provisioningEntries ) {
        this.provisioningEntries = provisioningEntries ;
        this.createdBy = createdBy ;
        this.createdDate = createdDate ;
        this.lastModifiedBy = lastModifiedBy ;
        this.lastModifiedDate = lastModifiedDate ;
    }

    public void setProvisioningEntries(Collection<LoanProductProvisioningEntry> provisioningEntries) {
        if(this.provisioningEntries == null) this.provisioningEntries = new HashSet<>();
        this.provisioningEntries.addAll(provisioningEntries) ;
    }

    public Collection<LoanProductProvisioningEntry> getLoanProductProvisioningEntries() {
        return this.provisioningEntries ;
    }

    public void setJournalEntryCreated(Boolean bool) {
        this.isJournalEntryCreated = bool ;
    }

    public Date getCreatedDate() {
        return this.createdDate ;
    }

}


text: Hello World Mean Project


text:
# angular-enforcer
Command line script to lint style rules in Angular templates and automatically correct them.
Can be used on any HTML file, not just Angular templates.

## Corrects missing end-tags
from:
```html
<div>
    <div>
        <span>
            <img>
```
to:
```html
<div>
    <div>
        <span>
            <img>
        </span>
    </div>
</div>
```

## Corrects inconsistent text case
from:
```html
<B>BOLD TEXT</B>
```
to:
```html
<b>
    BOLD TEXT
</b>
```

## Installation
`npm install angular-enforcer -g`

## Usage
### On a specific file
`enforce [file path] [options]`
where [file path] is a path to a file to enforce

### On STDIN
`cat [file path] | enforce -i`
Simply pipe some file into the enforce command

### On a glob
`enforce -g [glob string] [options]`
where [glob string] [node-glob](https://github.com/isaacs/node-glob) is a string to search for files using
Ex: `enforce -g src/folder/**/*.tpl`

### On every html file in this folder and all child folders
`enforce -g [options]`
This will run the angular-enforcer program on every html file in this folder and all child folders

### From node
You can also import angular-enforcer and use it as you want.

```js
import ngEnforcer from 'angular-enforcer';
import 'fs';
const file = fs.readFileSync('file');
const output = ngEnforcer(file, {
    lineLength: 150
});
```

The ngEnforce function takes a string of HTML and options and returns formatted HTML.
Linting is not available when using this method.

## Options

**Formatting options:**
--tab-length : the number of spaces to consider a tab. Default is 4.
--spaces : If true (default), converts spaces to tabs, using the specified tab length. Otherwise it does the reverse, converting tabs to spaces.
--line-length : max line length. Default is 100.
--closing-slash : if true, convert
 to
. Default is false.
--short-tags : comma separated list of additional tags that have no associated end tag
--expr-padding : add a space before and after angular expressions (and a space after the "::" in one-time binded expressions). Default is true.
--attr-newline : If an html start tag is over the specified line-length, start each attribute on it's own line, indenting by one. Default is true.
--empty-tag-same-line : Empty DOM nodes will end their tags on the same line if it's within the max line length.
--short-text-nodes : DOM nodes with just text that can fit on one line will do so. Default is true. If this is false, the text nodes will be indented.
--attr-obj-indent: Indent JS objects inside attributes, ex: inside ng-class. True by default.
--double-quotes : If true, use double quotes for attributes, otherwise use single quotes.
--reorder-attrs : If true, alphabetize HTML attributes in each tag
--block-spacing : If true, add an empty line in between each HTML block
--text-wrap : If true, break long text nodes so that indentation + length of text <= line-length. Defaults to true.
--wrap-ignored-tags : comma separated list of tags to ignore long text nodes inside
--remove-comments : if true, enforcer will remove all HTML comments

**CLI-only options:**
--config -c : path to the formatting config file. Default is .enforcer.json
--save -S : report and correct all problems, overwriting all affected files
--glob -g : Glob strings to look for files
--stdin -i : read from STDIN instead of giving a file path.
--verbose -v : more verbose reporting, including locations of problems.
--quite -q : silences all output, even when using --diff or --verbose.
--diff -d : print a colored diff of the changes

## .enforcer.json JSON file
All options can be specified in an .enforcer.json file. All options are in camelCase.

```json
{
     "tabLength": 2,
     "lineLength": 120
}
```

### Option load order:
1. command line options
2. .enforcer.json file in current directory (if it exists)
3. .enforcer.json file in home directory (if it exists)

## TODO
- specify file extension to look for
- add a -s option to save files, disable by default
- add linting features
     - lint when using HTML tags in an invalid way
- add formatter options
     - tab length
     - option to start new attributes lined up with the first attribute:
     ```html
     <input class="foobar"
            bar="baz">
     ```
     - max line length
     - Angular expression spaces
     - attribute spacing
     - attribute value formatting
     - self-closing tags
     - new line between code blocks
     - encoding of characters
     - better parsing of angular attributes:
          https://github.com/peerigon/angular-expressions
     - order attributes
          - build in angular directive's preferred order
- unit tests


text:
/**
 *
 */
package com.coderspp.schedulepredict.service.impl;

import java.io.IOException;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.coderspp.schedulepredict.dao.FlightDao;
import com.coderspp.schedulepredict.model.Flight;
import com.coderspp.schedulepredict.service.FlightService;

/**
 * @author Deepak
 *
 */
@Service
public class FlightServiceImpl implements FlightService {
	private String googleQuery = "http://www.google.com/search?q=";
	Document googleResponse;
	private String resetString = "http://www.google.com/search?q=";

	@Autowired
	private FlightDao flightDao;

	/*
	 * (non-Javadoc)
	 *
	 * @see com.coderspp.schedulepredict.service.FlightService#addNewFlight(com.
	 * coderspp.schedulepredict.model.Flight)
	 */
	@Override
	public Flight addNewFlight(Flight flight) {

		return flightDao.saveAndFlush(flight);
	}

	@Override
	public Flight getFlightByIdentifier(String identifier) {
		List<Flight> flights = flightDao.getFlightByIdentifier(identifier);
		Flight flight = null;
		if (flights == null || flights.size() == 0) {
			this.googleQuery += identifier;
			flight = new Flight();
			Element div;
			String route[], departure, arrival;

			try {
				this.googleResponse = Jsoup.connect(this.googleQuery)
						.userAgent(
								"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36")
						.referrer("http://www.google.com").get();

				Elements eles = googleResponse.getElementsByClass("vk_sh");
				div = eles.first();
				System.out.println(div);
				if (div == null) {
					flight.setArrivalAirportIATO(null);
					flight.setDepartureAirportIATO(null);
					return flight;
				}
				route = div.attr("data-route").split("-");
				departure = route[0];
				arrival = route[1];
				flight.setIdentifiedBy(identifier);
				flight.setArrivalAirportIATO(arrival);
				flight.setDepartureAirportIATO(departure);

				flight = flightDao.saveAndFlush(flight);
				return flight;

			} catch (IOException e) {

				e.printStackTrace();
			} finally {
				googleQuery = resetString;
			}
		} else {
			flight = flights.get(0);
		}
		return flight;
	}

}


text:
namespace SpaceTraderGui {

class STGUI_API Named {
private:
	std::string name;
public:
	Named();
	virtual ~Named();

	inline void setName(const std::string& name) {
		this->name = name;
	}

	inline const std::string& getName() const {
		return name;
	}
};

}


text:
package org.immutables.fixture.with;

import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.immutables.value.Value;
import org.immutables.value.Value.Style.ImplementationVisibility;

@Value.Immutable
@Value.Style(visibility = ImplementationVisibility.PACKAGE)
public abstract class Copied implements WithCopied {

  public abstract int attr();

  public abstract @Nullable Void voids();

  public abstract String[] arr();

  public abstract Map<String, Integer> map();

  public abstract List<Boolean> list();

  public static class Builder extends ImmutableCopied.Builder {}

  @SuppressWarnings("CheckReturnValue")
  static void use() {
    new Copied.Builder()
        .attr(1)
        .build()
        .withList(true, false);
  }
}


text:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;

namespace UMA.Editors
{
	[CustomPropertyDrawer(typeof(DNAEvaluatorList), true)]
	public class DNAEvaluatorListPropertyDrawer : PropertyDrawer
	{

		private const string DNAEVALUATORSPROPERTY = "_dnaEvaluators";
		private const string AGGREGATIONMETHODPROPERTY = "_aggregationMethod";

		private SerializedProperty _property;

		private GUIContent _propertyLabel;

		private float _padding = EditorGUIUtility.standardVerticalSpacing;

		private ReorderableList _dnaEvaluatorList;

		private DNAEvaluatorPropertyDrawer _dnaEvaluatorDrawer = new DNAEvaluatorPropertyDrawer();

		//private bool _drawAsReorderableList = true;

		private DNAEvaluatorList.ConfigAttribute.LabelOptions _labelOption = DNAEvaluatorList.ConfigAttribute.LabelOptions.drawLabelAsFoldout;

		private DNAEvaluationGraph _defaultGraph = null;

		private bool _manuallyConfigured = false;

		private GUIStyle _aggregationLabelStyle;

		ReorderableList.Defaults ROLDefaults;

		bool initialized = false;

		//If the list aggregationMode is 'Cumulative' draw the calc options
		private bool drawCalcOption = false;

		public DNAEvaluatorList.ConfigAttribute.LabelOptions LabelOption
		{
			get { return _labelOption; }
			set {
				_labelOption = value;
				_manuallyConfigured = true;
			}
		}
		//TODO Impliment this
		/// <summary>
		/// Not Implimented
		/// </summary>
		public DNAEvaluationGraph DefaultGraph
		{
			get { return _defaultGraph; }
			set {
				_defaultGraph = value;
				if (_defaultGraph != null)
					_manuallyConfigured = true;
			}
		}

		private void Init()
		{
			if (initialized)
				return;

			if (!_manuallyConfigured)
			{
				if (this.fieldInfo != null)
				{
					var attrib = this.fieldInfo.GetCustomAttributes(typeof(DNAEvaluatorList.ConfigAttribute), true).FirstOrDefault() as DNAEvaluatorList.ConfigAttribute;
					if (attrib != null)
					{
						_labelOption = attrib.labelOption;
						_defaultGraph = attrib.defaultGraph;
					}
				}
			}
			_aggregationLabelStyle = new GUIStyle(EditorStyles.label);
			_aggregationLabelStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel);
			_aggregationLabelStyle.alignment = TextAnchor.MiddleLeft;

			if (ROLDefaults == null)
				ROLDefaults = new ReorderableList.Defaults();

			initialized = true;

		}

		public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
		{
			Init();

			if (property.isExpanded
				|| _labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedNoLabel
				|| _labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedWithLabel)
			{
				var dnaEvalListProp = property.FindPropertyRelative(DNAEVALUATORSPROPERTY);
				float h = 0f;

				if(_labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedWithLabel
					|| _labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawLabelAsFoldout)
					h = (EditorGUIUtility.singleLineHeight + (_padding)) * 3;

				if (dnaEvalListProp.arraySize > 0)
				{
					//we only show the aggregation method if there is more than one and that makes the footer higher
					if(dnaEvalListProp.arraySize > 1)
					{
						h += _padding * 3;
					}
					for (int i = 0; i < dnaEvalListProp.arraySize; i++)
						h += EditorGUIUtility.singleLineHeight + (_padding * 2)+1f;
				}
				else
				{
					h += EditorGUIUtility.singleLineHeight + (_padding);
				}
				return h;
			}
			else
			{
				return EditorGUI.GetPropertyHeight(property, true);
			}
		}

		public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
		{

			_propertyLabel = label = EditorGUI.BeginProperty(position, label, property);

			_property = property;

			Init();

			var aggregationProp = property.FindPropertyRelative(AGGREGATIONMETHODPROPERTY);
			if (aggregationProp.enumValueIndex == 1)//Cumulative
				drawCalcOption = true;
			else
				drawCalcOption = false;

			DrawReorderableList(position, property, label);

			EditorGUI.EndProperty();
		}

		private void DrawReorderableList(Rect position, SerializedProperty property, GUIContent label)
		{
			var labelRect = new Rect(position.xMin, position.yMin, position.width, 0f);
			if (_labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawLabelAsFoldout)
			{
				labelRect = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
				property.isExpanded = EditorGUI.Foldout(labelRect, property.isExpanded, label);
			}
			else if(_labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedWithLabel)
			{
				labelRect = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
				EditorGUI.LabelField(labelRect, label);
			}
			if (property.isExpanded || _labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedWithLabel || _labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedNoLabel)
			{
				var contentRect = EditorGUI.IndentedRect(position);
				contentRect.yMin = labelRect.yMax + _padding;
				contentRect.height = contentRect.height - labelRect.height;

				var dnaEvalListProp = property.FindPropertyRelative(DNAEVALUATORSPROPERTY);

				_dnaEvaluatorList = CachedReorderableList.GetListDrawer(dnaEvalListProp, DrawHeaderCallback, null, DrawElementCallback, DrawFooterCallback);

				_dnaEvaluatorList.DoList(contentRect);
			}
		}

		private void DrawHeaderCallback(Rect rect)
		{
			_dnaEvaluatorDrawer.DrawLabels = false;
			_dnaEvaluatorDrawer.DrawCalcOption = _dnaEvaluatorList.count > 1 ? drawCalcOption : false;
			if (_labelOption == DNAEvaluatorList.ConfigAttribute.LabelOptions.drawExpandedNoLabel)
			{
				_dnaEvaluatorDrawer.DoLabelsInline(rect, _propertyLabel);
			}
			else
			{
				_dnaEvaluatorDrawer.DoLabelsInline(rect);
			}
		}

		private void DrawFooterCallback(Rect rect)
		{
			float xMax = rect.xMax;
			float availWidth = xMax - 60f;
			//if the view is wide this only needs to be XMax - 300 else its Xmin
			float bgXmin = rect.xMax - 300f > rect.xMin ? rect.xMax - 300f : rect.xMin;
			Rect bgRect = new Rect(bgXmin, rect.yMin, rect.width, rect.height);
			bgRect.xMax = rect.xMax;
			float agWidthMod = 0f;
			//If the list count is greater than 1 we need to draw the background for the aggregation controls
			if (_dnaEvaluatorList.count > 1)
			{
				agWidthMod = 4f;
			}
			rect = new Rect(availWidth, rect.y, xMax - availWidth - agWidthMod, rect.height);
			Rect rect2 = new Rect(availWidth + 4f, rect.y - 3f, 25f, 13f);
			Rect rect3 = new Rect(xMax - 33f, rect.y - 3f, 25f, 13f);
			Rect agRect = new Rect(bgRect.xMin + 8f, bgRect.yMin, (bgRect.width - rect.width) -16f, bgRect.height);
			if (Event.current.type == EventType.Repaint)
			{
				var prevFooterFixedHeight = ROLDefaults.footerBackground.fixedHeight;
				var addMinusHeight = prevFooterFixedHeight;
				//If the list count is greater than 1 we need to draw the background for the aggregation controls
				if (_dnaEvaluatorList.count > 1)
				{
					//usually 13f but we need it higher to hold aggregation controls
					ROLDefaults.footerBackground.fixedHeight = 13f + (EditorGUIUtility.standardVerticalSpacing * 3);
					ROLDefaults.footerBackground.Draw(bgRect, false, false, false, false);
					addMinusHeight += 2f;
				}
				//now draw the standard background for the +/- controls
				ROLDefaults.footerBackground.fixedHeight = addMinusHeight;
				ROLDefaults.footerBackground.Draw(rect, false, false, false, false);
				ROLDefaults.footerBackground.fixedHeight = prevFooterFixedHeight;
			}
			if (GUI.Button(rect2, ROLDefaults.iconToolbarPlus, ROLDefaults.preButton))
			{
				ROLDefaults.DoAddButton(_dnaEvaluatorList);
			}
			using (new EditorGUI.DisabledScope(_dnaEvaluatorList.index < 0 || _dnaEvaluatorList.index >= _dnaEvaluatorList.count))
			{
				if (GUI.Button(rect3, ROLDefaults.iconToolbarMinus, ROLDefaults.preButton))
				{
					ROLDefaults.DoRemoveButton(_dnaEvaluatorList);
				}
			}
			var prevIndentLevel = EditorGUI.indentLevel;
			EditorGUI.indentLevel = 0;
			//If the list count is greater than 1 we need to draw the background for the aggregation controls
			if (_dnaEvaluatorList.count > 1)
			{
				DrawAggregationMethod(agRect, _property);
			}
			EditorGUI.indentLevel = prevIndentLevel;
		}

		//GetArrayElementAtIndex is slow, we need to cache the results the same way DNAPluginsDrawerer does
		private void DrawElementCallback(Rect rect, int index, bool isActive, bool isFocused)
		{
			_dnaEvaluatorDrawer.DrawLabels = false;
			var dnaEvalListProp = _dnaEvaluatorList.serializedProperty;
			var entryRect = new Rect(rect.xMin, rect.yMin + _padding, rect.width, rect.height );
			_dnaEvaluatorDrawer.DrawCalcOption = _dnaEvaluatorList.count > 1 ? drawCalcOption : false;
			_dnaEvaluatorDrawer.DoFieldsInline(entryRect, dnaEvalListProp.GetArrayElementAtIndex(index));
		}

		private Rect DrawAggregationMethod(Rect position, SerializedProperty property)
		{
			var labelRectMinWidth = 110f;
			var popupMinWidth = 60f;
			var aggregationProp = property.FindPropertyRelative(AGGREGATIONMETHODPROPERTY);
			var aggregationRect = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
			var labelRectWidth = aggregationRect.width - labelRectMinWidth < popupMinWidth ? aggregationRect.width / 2f : labelRectMinWidth;
			var popupRectWidth = aggregationRect.width - labelRectMinWidth < popupMinWidth ? aggregationRect.width / 2f : aggregationRect.width - labelRectWidth;
			var labelRect = new Rect(aggregationRect.xMin, aggregationRect.yMin, labelRectWidth, aggregationRect.height);
			var popupRect = new Rect(labelRect.xMax, aggregationRect.yMin, popupRectWidth, aggregationRect.height);

			var label = EditorGUI.BeginProperty(labelRect, new GUIContent(aggregationProp.displayName), aggregationProp);
			EditorGUI.LabelField(labelRect, label, _aggregationLabelStyle);
			EditorGUI.PropertyField(popupRect, aggregationProp, GUIContent.none);
			EditorGUI.EndProperty();

			var retRect = new Rect(position.xMin, aggregationRect.yMax + _padding, position.width, position.height - (EditorGUIUtility.singleLineHeight + _padding));
			return retRect;
		}
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Varenko Oleg
 * Date: 13.06.2016
 * Time: 10:34
 */
namespace app\models;

use yii\db\ActiveRecord;

class UserInfo extends ActiveRecord {

    public static function tableName() {
        return 'santeh_user_dopinfo';
    }
}


text:
class ReimportHessenPapersPDFJob < ActiveJob::Base
  queue_as :meta

  DISTANCE = 14.days

  def perform
    body = Body.find_by_state('HE')
    papers = Paper.where(body: body).where(['pdf_last_modified < ?', Date.today - DISTANCE]).where(contents: nil)

    papers.find_each do |paper|
      logger.info "Adding reimport of Paper [#{paper.body.state} #{paper.full_reference}] to queue"
      StorePaperPDFJob.perform_later(paper, force: true)
    end
  end
end


text:
package de.swoeste.infinitum.fw.core.bl.svn.indexer;

import de.swoeste.infinitum.fw.core.bl.svn.indexer.config.SVNIndexContext;
import de.swoeste.infinitum.fw.core.bl.svn.indexer.config.SVNIndexSearch;
import de.swoeste.infinitum.fw.core.bl.svn.indexer.model.ISVNIndexEntry;
import de.swoeste.infinitum.fw.core.bl.svn.indexer.model.ISVNIndexSearchResult;

/**
 * @author swoeste
 */
public interface ISVNIndexFacade {

    /**
     * Create a new or update an existing index based on the given configuration. This method might be called multiple
     * times but is only executing if it is not already running.
     *
     * @param configuration
     *            a configuration
     */
    void createOrUpdateIndex(final SVNIndexContext configuration);

    /**
     * Search the index with the given search criteria.
     *
     * @param search
     *            a search
     * @return a list of {@link ISVNIndexEntry} which match the search criteria, may be empty but never null.
     */
    ISVNIndexSearchResult searchIndex(final SVNIndexSearch search);

}


text:
if(!dojo._hasResource["dojox.timing"]){
dojo._hasResource["dojox.timing"]=true;
dojo.provide("dojox.timing");
dojo.require("dojox.timing._base");
}


text:
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'underscore', 'backbone', 'strophe'], function ($, _, Backbone, wrapper) {
            // Also create a global in case some scripts
            // that are loaded still are looking for
            // a global even when an AMD loader is in use.
            return factory($, _, Backbone, wrapper.Strophe, wrapper.$build, wrapper.$iq);
        });
    } else {
        // Browser globals
        factory(root.$, root._, root.Backbone, root.Strophe, root.$build, root.$iq);
    }
}(this,function ($, _, Backbone, Strophe, $build, $iq) {

    // Add the **PubSub** plugin to Strophe
    Strophe.addConnectionPlugin('PubSub', {

        _connection: null,
        service: null,
        events: {},

        // **init** adds the various namespaces we use and extends the component
        // from **Backbone.Events**.
        init: function (connection) {
            this._connection = connection;
            Strophe.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
            Strophe.addNamespace('PUBSUB_EVENT', Strophe.NS.PUBSUB + '#event');
            Strophe.addNamespace('PUBSUB_OWNER', Strophe.NS.PUBSUB + '#owner');
            Strophe.addNamespace('PUBSUB_NODE_CONFIG', Strophe.NS.PUBSUB + '#node_config');
            Strophe.addNamespace('ATOM', 'http://www.w3.org/2005/Atom');
            Strophe.addNamespace('DELAY', 'urn:xmpp:delay');
            Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
            _.extend(this, Backbone.Events);
        },

        // Register to PEP events when connected
        statusChanged: function (status, condition) {
            if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
                this.service =  'pubsub.' + Strophe.getDomainFromJid(this._connection.jid);
                this._connection.addHandler(this._onReceivePEPEvent.bind(this), null, 'message', null, null, this.service);
            }
        },

        // Handle PEP events and trigger own events.
        _onReceivePEPEvent: function (ev) {
            var self = this,
                delay = $('delay', ev).attr('stamp');
            $('item', ev).each(function (idx, item) {
                var node = $(item).parent().attr('node'),
                    id = $(item).attr('id'),
                    entry = $('entry', item).filter(':first');
                if (entry.length) {
                    entry = entry[0];
                } else {
                    entry = null;
                }

                if (delay) {
                    // PEP event for the last-published item on a node.
                    self.trigger('xmpp:pubsub:last-published-item', {
                        node: node,
                        id: id,
                        entry: entry,
                        timestamp: delay
                    });
                    self.trigger('xmpp:pubsub:last-published-item:' + node, {
                        id: id,
                        entry: entry,
                        timestamp: delay
                    });
                } else {
                    // PEP event for an item newly published on a node.
                    self.trigger('xmpp:pubsub:item-published', {
                        node: node,
                        id: id,
                        entry: entry
                    });
                    self.trigger('xmpp:pubsub:item-published:' + node, {
                        id: id,
                        entry: entry
                    });
                }
            });

            // PEP event for the item deleted from a node.
            $('retract', ev).each(function (idx, item) {
                var node = $(item).parent().attr('node'),
                    id = $(item).attr('id');
                self.trigger('xmpp:pubsub:item-deleted', {node: node, id: id});
                self.trigger('xmpp:pubsub:item-deleted:' + node, {id: id});
            });

            return true;
        },

        // **createNode** creates a PubSub node with id `node` with configuration options defined by `options`.
        // See [http://xmpp.org/extensions/xep-0060.html#owner-create](http://xmpp.org/extensions/xep-0060.html#owner-create)
        createNode: function (node, options) {
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'set', id: this._connection.getUniqueId('pubsub')})
                    .c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                    .c('create', {node: node}),
                fields = [],
                option,
                form;

            if (options) {
                fields.push(new Strophe.x.Field({'var': 'FORM_TYPE', type: 'hidden', value: Strophe.NS.PUBSUB_NODE_CONFIG}));
                _.each(options, function (value, option) {
                    fields.push(new Strophe.x.Field({'var': option, value: value}));
                });
                form = new Strophe.x.Form({type: 'submit', fields: fields});
                iq.up().c('configure').cnode(form.toXML());
            }
            this._connection.sendIQ(iq.tree(), d.resolve, d.reject);
            return d.promise();
        },

        // **deleteNode** deletes the PubSub node with id `node`.
        // See [http://xmpp.org/extensions/xep-0060.html#owner-delete](http://xmpp.org/extensions/xep-0060.html#owner-delete)
        deleteNode: function (node) {
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'set', id: this._connection.getUniqueId('pubsub')})
                .c('pubsub', {xmlns: Strophe.NS.PUBSUB_OWNER})
                .c('delete', {node: node});

            this._connection.sendIQ(iq.tree(), d.resolve, d.reject);
            return d.promise();
        },

        // **getNodeConfig** returns the node's with id `node` configuration options in JSON format.
        // See [http://xmpp.org/extensions/xep-0060.html#owner-configure](http://xmpp.org/extensions/xep-0060.html#owner-configure)
        getNodeConfig: function (node) {
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'get', id: this._connection.getUniqueId('pubsub')})
                    .c('pubsub', {xmlns: Strophe.NS.PUBSUB_OWNER})
                    .c('configure', {node: node}),
                form;
            this._connection.sendIQ(iq.tree(), function (result) {
                form = Strophe.x.Form.fromXML($('x', result));
                d.resolve(form.toJSON().fields);
            }, d.reject);
            return d.promise();
        },

        // **discoverNodes** returns the nodes of a *Collection* node with id `node`.
        // If `node` is not passed, the nodes of the root node on the service are returned instead.
        // See [http://xmpp.org/extensions/xep-0060.html#entity-nodes](http://xmpp.org/extensions/xep-0060.html#entity-nodes)
        discoverNodes: function (node) {
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'get', id: this._connection.getUniqueId('pubsub')});

            if (node) {
                iq.c('query', {xmlns: Strophe.NS.DISCO_ITEMS, node: node});
            } else {
                iq.c('query', {xmlns: Strophe.NS.DISCO_ITEMS});
            }
            this._connection.sendIQ(iq.tree(),
                function (result) {
                    d.resolve($.map($('item', result), function (item, idx) { return $(item).attr('node'); }));
                }, d.reject);
            return d.promise();
        },

        // **publish** publishes `item`, an XML tree typically built with **$build** to the node specific by `node`.
        // Optionally, takes `item_id` as the desired id of the item.
        // Resolves on success to the id of the item on the node.
        // See [http://xmpp.org/extensions/xep-0060.html#publisher-publish](http://xmpp.org/extensions/xep-0060.html#publisher-publish)
        publish: function (node, item, item_id) {
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'set', id: this._connection.getUniqueId('pubsub')})
                    .c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                    .c('publish', {node: node})
                    .c('item', item_id ? {id: item_id} : {})
                    .cnode(item);
            this._connection.sendIQ(iq.tree(),
                function (result) {
                    d.resolve($('item', result).attr('id'));
                }, d.reject);
            return d.promise();
        },

        // **publishAtom** publishes a JSON object as an ATOM entry.
        publishAtom: function (node, json, item_id) {
            json.updated = json.updated || (this._ISODateString(new Date()));
            return this.publish(node, this._JsonToAtom(json), item_id);
        },

        // **deleteItem** deletes the item with id `item_id` from the node with id `node`.
        // `notify` specifies whether the service should notify all subscribers with a PEP event.
        // See [http://xmpp.org/extensions/xep-0060.html#publisher-delete](http://xmpp.org/extensions/xep-0060.html#publisher-delete)
        deleteItem: function(node, item_id, notify) {
            notify = notify || true;
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'set', id: this._connection.getUniqueId('pubsub')})
                .c('pubsub', {xmlns: Strophe.NS.PUBSUB })
                .c('retract', notify ? {node: node, notify: "true"} : {node: node})
                .c('item', {id: item_id});
            this._connection.sendIQ(iq.tree(), d.resolve, d.reject);
            return d.promise();
        },

        // **items** retrieves the items from the node with id `node`.
        // Optionally, you can specify `max_items` to retrieve a maximum number of items,
        // or a list of item ids with `item_ids` in `options` parameters.
        // See [http://xmpp.org/extensions/xep-0060.html#subscriber-retrieve](http://xmpp.org/extensions/xep-0060.html#subscriber-retrieve)
        // Resolves with an array of items.
        // Also if your server supports [Result Set Management](http://xmpp.org/extensions/xep-0059.html)
        // on PubSub nodes, you can pass in options an `rsm` object literal with `before`, `after`, `max` parameters.
        // You cannot specify both `rsm` and `max_items` or `items_ids`.
        // Requesting with `rsm` will resolve with an object literal with `items` providing a list of the items retrieved,
        //and `rsm` with `last`, `first`, `count` properties.

        items: function (node, options) {
            var d = $.Deferred(),
                iq = $iq({to: this.service, type: 'get'})
                .c('pubsub', {xmlns: Strophe.NS.PUBSUB })
                .c('items', {node: node});

            options = options || {};

            if (options.rsm) {
                var rsm = $build('set', {xmlns: Strophe.NS.RSM});
                _.each(options.rsm, function (val, key) { rsm.c(key, {}, val); });
                iq.up();
                iq.cnode(rsm.tree());
            } else if (options.max_items) {
                iq.attrs({max_items: options.max_items});
            } else if (options.item_ids) {
                _.each(options.item_ids, function (id) {
                    iq.c('item', {id: id}).up();
                });
            }

            this._connection.sendIQ(iq.tree(),
                function (res) {
                    var items = _.map($('item', res), function (item) {
                            return item.cloneNode(true);
                        });

                    if (options.rsm && $('set', res).length) {
                        d.resolve({
                            items: items,
                            rsm: {
                                count: parseInt($('set > count', res).text(), 10),
                                first: $('set >first', res).text(),
                                last: $('set > last', res).text()
                            }
                        });
                    } else {
                        d.resolve(items);
                    }

                }, d.reject);
            return d.promise();
        },

        // **subscribe** subscribes the user's bare JID to the node with id `node`.
        // See [http://xmpp.org/extensions/xep-0060.html#subscriber-subscribe](http://xmpp.org/extensions/xep-0060.html#subscriber-subscribe)
        subscribe: function (node) {
            var d = $.Deferred();
            var iq = $iq({to: this.service, type: 'set', id: this._connection.getUniqueId('pubsub')})
                .c('pubsub', {xmlns: Strophe.NS.PUBSUB })
                .c('subscribe', {node: node, jid: Strophe.getBareJidFromJid(this._connection.jid)});
            this._connection.sendIQ(iq, d.resolve, d.reject);
            return d.promise();
        },

        // **unsubscribe** unsubscribes the user's bare JID from the node with id `node`. If managing multiple
        // subscriptions it is possible to optionally specify the `subid`.
        // See [http://xmpp.org/extensions/xep-0060.html#subscriber-unsubscribe](http://xmpp.org/extensions/xep-0060.html#subscriber-unsubscribe)
        unsubscribe: function (node, subid) {
            var d = $.Deferred();
            var iq = $iq({to: this.service, type: 'set', id: this._connection.getUniqueId('pubsub')})
                .c('pubsub', {xmlns: Strophe.NS.PUBSUB })
                .c('unsubscribe', {node: node, jid: Strophe.getBareJidFromJid(this._connection.jid)});
            if (subid) iq.attrs({subid: subid});
            this._connection.sendIQ(iq, d.resolve, d.reject);
            return d.promise();
        },

        // **getSubscriptions** retrieves the subscriptions of the user's bare JID to the service.
        // See [http://xmpp.org/extensions/xep-0060.html#entity-subscriptions](http://xmpp.org/extensions/xep-0060.html#entity-subscriptions)
        getSubscriptions: function () {
            var d = $.Deferred();
            var iq = $iq({to: this.service, type: 'get', id: this._connection.getUniqueId('pubsub')})
                .c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('subscriptions'),
                $item;

            this._connection.sendIQ(iq.tree(),
                function (res) {
                    d.resolve(_.map($('subscription', res), function (item) {
                        $item = $(item);
                        return {
                            node: $item.attr('node'),
                            jid: $item.attr('jid'),
                            subid: $item.attr('subid'),
                            subscription: $item.attr('subscription')
                        };
                    }));
                }, d.reject);
            return d.promise();
        },

        // Private utility functions

        // **_ISODateString** converts a date to an ISO-formatted string.
        _ISODateString: function (d) {
            function pad(n) {
                return n < 10 ? '0' + n : n;
            }
            return d.getUTCFullYear() + '-' +
                pad(d.getUTCMonth() + 1) + '-' +
                pad(d.getUTCDate()) + 'T' +
                pad(d.getUTCHours()) + ':' +
                pad(d.getUTCMinutes()) + ':' +
                pad(d.getUTCSeconds()) + 'Z';
        },

        // **_JsonToAtom** produces an atom-format XML tree from a JSON object.
        _JsonToAtom: function (obj, tag) {
            var builder;

            if (!tag) {
                builder = $build('entry', {xmlns: Strophe.NS.ATOM});
            } else {
                builder = $build(tag);
            }
            _.each(obj, function (value, key) {
                if (typeof value === 'string') {
                    builder.c(key, {}, value);
                } else if (typeof value === 'number') {
                    builder.c(key, {}, value.toString());
                } else if (typeof value === 'boolean') {
                    builder.c(key, {}, value.toString());
                } else if (typeof value === 'object' && 'toUTCString' in value) {
                    builder.c(key, {}, this._ISODateString(value));
                } else if (typeof value === 'object') {
                    builder.cnode(this._JsonToAtom(value, key)).up();
                } else {
                    this.c(key).up();
                }
            }, this);
            return builder.tree();
        },

        // **_AtomToJson** produces a JSON object from an atom-formatted XML tree.
        _AtomToJson: function (xml) {
            var json = {},
                self = this,
                jqEl,
                val;

            $(xml).children().each(function (idx, el) {
                jqEl = $(el);
                if (jqEl.children().length === 0) {
                    val = jqEl.text();
                    if ($.isNumeric(val)) {
                        val = Number(val);
                    }
                    json[el.nodeName.toLowerCase()] = val;
                } else {
                    json[el.nodeName.toLowerCase()] = self._AtomToJson(el);
                }
            });
            return json;
        }

    });
}));


text:
#include "sky/engine/config.h"
#include "sky/engine/core/dom/DocumentInit.h"

#include "gen/sky/platform/RuntimeEnabledFeatures.h"
#include "sky/engine/core/dom/Document.h"
#include "sky/engine/core/dom/custom/custom_element_registry.h"
#include "sky/engine/core/frame/LocalFrame.h"
#include "sky/engine/core/html/imports/HTMLImportsController.h"

namespace blink {

DocumentInit::DocumentInit(const KURL& url, LocalFrame* frame, WeakPtr<Document> contextDocument, HTMLImportsController* importsController)
    : m_url(url)
    , m_frame(frame)
    , m_contextDocument(contextDocument)
    , m_importsController(importsController)
{
}

DocumentInit::DocumentInit(const DocumentInit& other)
    : m_url(other.m_url)
    , m_frame(other.m_frame)
    , m_contextDocument(other.m_contextDocument)
    , m_importsController(other.m_importsController)
    , m_elementRegistry(other.m_elementRegistry)
{
}

DocumentInit::~DocumentInit()
{
}

bool DocumentInit::shouldSetURL() const
{
    return !m_url.isEmpty();
}

LocalFrame* DocumentInit::frameForSecurityContext() const
{
    if (m_frame)
        return m_frame;
    if (m_importsController)
        return m_importsController->master()->frame();
    return 0;
}

Settings* DocumentInit::settings() const
{
    ASSERT(frameForSecurityContext());
    return frameForSecurityContext()->settings();
}

DocumentInit& DocumentInit::withElementRegistry(CustomElementRegistry& elementregistry)
{
    ASSERT(!m_elementRegistry);
    m_elementRegistry = &elementregistry;
    return *this;
}

WeakPtr<Document> DocumentInit::contextDocument() const
{
    return m_contextDocument;
}

DocumentInit DocumentInit::fromContext(WeakPtr<Document> contextDocument, const KURL& url)
{
    return DocumentInit(url, 0, contextDocument, 0);
}

} // namespace blink


text:
import xml.etree.cElementTree as ET
import pprint
import re
"""
Your task is to explore the data a bit more.
Before you process the data and add it into your database, you should check the
"k" value for each "<tag>" and see if there are any potential problems.
We have provided you with 3 regular expressions to check for certain patterns
in the tags. As we saw in the quiz earlier, we would like to change the data
model and expand the "addr:street" type of keys to a dictionary like this:
{"address": {"street": "Some value"}}
So, we have to see if we have such tags, and if we have any tags with
problematic characters.
Please complete the function 'key_type', such that we have a count of each of
four tag categories in a dictionary:
  "lower", for tags that contain only lowercase letters and are valid,
  "lower_colon", for otherwise valid tags with a colon in their names,
  "problemchars", for tags with problematic characters, and
  "other", for other tags that do not fall into the other three categories.
See the 'process_map' and 'test' functions for examples of the expected format.
"""

lower = re.compile(r'^([a-z]|_)*$')
lower_colon = re.compile(r'^([a-z]|_)*:([a-z]|_)*$')
problemchars = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]')

def key_type(element, keys):
    if element.tag == "tag":
        # for tag in element.iter():
        if lower.match(element.attrib['k']):
            keys['lower'] += 1
        elif lower_colon.match(element.attrib['k']):
            keys['lower_colon'] += 1
        elif problemchars.match(element.attrib['k']):
            keys['problemchars'] += 1
        else:
            keys['other'] += 1
    return keys

def process_map(filename):
    keys = {"lower": 0, "lower_colon": 0, "problemchars": 0, "other": 0}
    for _, element in ET.iterparse(filename):
        keys = key_type(element, keys)

    return keys

def test():
    # You can use another testfile 'map.osm' to look at your solution
    # Note that the assertion below will be incorrect then.
    # Note as well that the test function here is only used in the Test Run;
    # when you submit, your code will be checked against a different dataset.
    keys = process_map('samplefile.osm')
    pprint.pprint(keys)
    assert keys == {'lower': 5, 'lower_colon': 0, 'other': 1, 'problemchars': 1}

if __name__ == "__main__":
    test()


text:
namespace MobileApp.Core.Services.DataService
{
    #region

    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Cirrious.MvvmCross.Plugins.Messenger;

    using MobileApp.Core.Converters;
    using MobileApp.Core.Interfaces;
    using MobileApp.Core.Models.DataContracts;
    using MobileApp.Core.Models.Messages;
    using MobileApp.Core.Services.HttpService;
    using MobileApp.Core.Services.UtilityService.Logger;

    #endregion

    /// <summary>
    /// The data service.
    /// </summary>
    public class ContactsService : UpdatableStorageBase<Contact>, IContactService
    {
        #region Fields

        private readonly IMvxMessenger messenger;

        private Dictionary<string, Contact> deviceDictionary;

        private int isBusy;

        private Contact outherWorldDevice;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Create new contact's collection
        /// </summary>
        /// <param name="logger">Logger</param>
        /// <param name="messenger">messenger</param>
        public ContactsService(ILogger logger, IMvxMessenger messenger)
            : base(typeof(Contact), logger)
        {
            this.messenger = messenger;
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Collection of matches devices and contacts
        /// </summary>
        public Dictionary<string, Contact> DeviceDictionary
        {
            get
            {
                return this.deviceDictionary ?? (this.deviceDictionary = new Dictionary<string, Contact>());
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Check is service busy
        /// </summary>
        protected bool IsBusy
        {
            get
            {
                return this.isBusy > 0;
            }
            set
            {
                if (value)
                {
                    this.isBusy++;
                }
                else
                {
                    this.isBusy--;
                }

                if (this.isBusy == 0)
                {
                    this.messenger.Publish(new SyncMessage(this));
                }
            }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// Get contact data by device name
        /// </summary>
        /// <param name="aliases">device's name</param>
        /// <returns>Contact data</returns>
        public Contact FindByAlias(string[] aliases)
        {
            return (from alias in aliases
                    where !string.IsNullOrWhiteSpace(alias)
                    select PhoneNumberHelper.ToComparable(alias)
                    into key
                    select this.DeviceDictionary.ContainsKey(key) ? this.DeviceDictionary[key] : this.FindByUserId(key)).FirstOrDefault(contact => contact != null);
        }

        /// <summary>
        /// Get contact data by user ID
        /// </summary>
        /// <param name="userName">user's ID</param>
        /// <returns>Contact data</returns>
        public Contact FindByUserId(string userName)
        {
            int id;
            return int.TryParse(userName.ToLower(), out id) ? this.Storage.FirstOrDefault(c => c.Userid.Equals(id)) : null;
        }

        /// <summary>
        /// Set some specific contact to dictionary
        /// </summary>
        /// <param name="contact">some specific contact</param>
        public void SetSpecificContact(Contact contact)
        {
            this.outherWorldDevice = contact;
            foreach (var device in contact.Devices)
            {
                this.deviceDictionary[device] = contact;
            }
        }

        /// <summary>
        /// Sync collection
        /// </summary>
        /// <returns></returns>
        public override void SynchronizeRepository()
        {
            if (this.IsBusy)
            {
                return;
            }

            this.IsBusy = true;

            ApiInteraction.Create(ApiMethodType.GetRegisteredDevices, this.DevicesUpdate, this.ErrorAction);
        }

        #endregion

        #region Methods

        protected override void UpdateStorage(List<Contact> list)
        {
            base.UpdateStorage(list);

            foreach (var contact in this.Storage)
            {
                foreach (var key in contact.Devices.Select(PhoneNumberHelper.ToComparable).Where(key => !this.DeviceDictionary.ContainsKey(key)))
                {
                    this.DeviceDictionary.Add(key, contact);
                }
            }
        }

        private void DevicesUpdate(object obj)
        {
            var list = Responce<string>.ProcessListResponce(obj, this.Logger, this);
            var b = list != null;

            foreach (var contact in this.Storage)
            {
                contact.Registered = b && list.Select(n => Convert.ToInt32(n)).Contains(contact.Userid);
            }

            this.IsBusy = false;
        }

        private void ErrorAction(Exception obj)
        {
            this.IsBusy = false;
        }

        #endregion
    }
}


text:
/* ====================================================================

*/

using System;
using System.Xml;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Oranikle.Report.Engine
{
	///<summary>
	///CustomReportItem describes a report item that is not natively defined in Oranikle.Report.Engine.  The
    /// RdlEngineConfig.xml file (loaded by RdlEngineConfig.cs) contains a list of the
    /// extensions.   RdlCri.dll is a code module that contains the built-in CustomReportItems.
    /// However, the runtime dynamically loads this so RdlCrl.dll is not required for the
    /// report engine to function properly.
	///</summary>
	[Serializable]
	public class CustomReportItem : Rectangle
	{
        static readonly ImageFormat IMAGEFORMAT = ImageFormat.Jpeg;
        string _Type;	// The type of the custom report item. Interpreted by a
						// report design tool or server.
        System.Collections.Generic.List<CustomProperty> _Properties;

		public CustomReportItem(ReportDefn r, ReportLink p, XmlNode xNode):base(r, p, xNode, false)
		{
			_Type=null;
			ReportItems ris=null;
            bool bVersion2 = true;

			// Loop thru all the child nodes
			foreach(XmlNode xNodeLoop in xNode.ChildNodes)
			{
				if (xNodeLoop.NodeType != XmlNodeType.Element)
					continue;
				switch (xNodeLoop.Name)
				{
					case "Type":
						_Type = xNodeLoop.InnerText;
						break;
					case "ReportItems":         // Version 1 of the specification
						ris = new ReportItems(r, this, xNodeLoop);
                        bVersion2 = false;
						break;
                    case "AltReportItem":       // Verstion 2 of the specification
                        ris = new ReportItems(r, this, xNodeLoop);
                        break;
                    case "CustomProperties":
                        _Properties = CustomProperties(xNodeLoop);
                        break;
					default:
						if (ReportItemElement(xNodeLoop))	// try at ReportItem level
							break;
						// don't know this element - log it
						OwnerReport.rl.LogError(4, "Unknown CustomReportItem element " + xNodeLoop.Name + " ignored.");
						break;
				}
			}
			ReportItems = ris;
            if (bVersion2 && ris != null)
            {
			    if (ris.Items.Count != 1)
				    OwnerReport.rl.LogError(8, "Only one element is allowed within an AltReportItem.");
            }

			if (_Type == null)
				OwnerReport.rl.LogError(8, "CustomReportItem requires the Type element.");
		}

        override public void FinalPass()
        {
            base.FinalPass();       // this handles the finalpass of the AltReportItems

            // Handle the final pass for the Custom Properties
            if (_Properties != null)
            {
                foreach (CustomProperty cp in _Properties)
                {
                    cp.Name.FinalPass();
                    cp.Value.FinalPass();
                }
            }

            // Find out whether the type is known
            ICustomReportItem cri = null;
            try
            {
                cri = RdlEngineConfig.CreateCustomReportItem(_Type);
            }
            catch (Exception ex)
            {   // Not an error since we'll simply use the ReportItems
                OwnerReport.rl.LogError(4, string.Format("CustomReportItem load of {0} failed: {1}",
                    _Type, ex.Message));
            }
            finally
            {
                if (cri != null)
                    cri.Dispose();
            }

            return;
        }

        override public void Run(IPresent ip, Row row)
        {
            Report rpt = ip.Report();

            ICustomReportItem cri = null;
            try
            {
                cri = RdlEngineConfig.CreateCustomReportItem(_Type);

            }
            catch (Exception ex)
            {
                rpt.rl.LogError(8, string.Format("Exception in CustomReportItem handling.\n{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                if (cri != null)
                    cri.Dispose();
            }
            return;
        }

        override public void RunPage(Pages pgs, Row row)
        {
            Report rpt = pgs.Report;

            if (IsHidden(pgs.Report, row))
                return;

            SetPagePositionBegin(pgs);

            // Build the Chart bitmap, along with data regions
            Page p = pgs.CurrentPage;
            ICustomReportItem cri = null;
            Bitmap bm = null;
            try
            {
                cri = RdlEngineConfig.CreateCustomReportItem(_Type);
                SetProperties(pgs.Report, row, cri);

                int width = WidthCalc(rpt, pgs.G) -
                    (Style == null? 0 :
                        (Style.EvalPaddingLeftPx(rpt, row) + Style.EvalPaddingRightPx(rpt, row)));
                int height = RSize.PixelsFromPoints(this.HeightOrOwnerHeight) -
                    (Style == null? 0 :
                        (Style.EvalPaddingTopPx(rpt, row) + Style.EvalPaddingBottomPx(rpt, row)));
                bm = new Bitmap(width, height);
                cri.DrawImage(bm);

                MemoryStream ostrm = new MemoryStream();
                // 06122007AJM Changed to use high quality JPEG encoding
                //bm.Save(ostrm, IMAGEFORMAT);	// generate a jpeg   TODO: get png to work with pdf
                System.Drawing.Imaging.ImageCodecInfo[] info;
                info = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encoderParameters;
                encoderParameters = new EncoderParameters(1);
                // 20022008 AJM GJL - Using centralised image quality
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.CustomImageQuality);
                System.Drawing.Imaging.ImageCodecInfo codec = null;
                for (int i = 0; i < info.Length; i++)
                {
                    if (info[i].FormatDescription == "JPEG")
                    {
                        codec = info[i];
                        break;
                    }
                }
                bm.Save(ostrm, codec, encoderParameters);

                byte[] ba = ostrm.ToArray();
                ostrm.Close();
                PageImage pi = new PageImage(IMAGEFORMAT, ba, width, height);	// Create an image
                pi.Sizing = ImageSizingEnum.Clip;
//                RunPageRegionBegin(pgs);

                SetPagePositionAndStyle(rpt, pi, row);

                if (pgs.CurrentPage.YOffset + pi.Y + pi.H >= pgs.BottomOfPage && !pgs.CurrentPage.IsEmpty())
                {	// force page break if it doesn't fit on the page
                    pgs.NextOrNew();
                    pgs.CurrentPage.YOffset = OwnerReport.TopOfPage;
                    if (this.YParents != null)
                        pi.Y = 0;
                }

                p = pgs.CurrentPage;

                p.AddObject(pi);	// Put image onto the current page

  //              RunPageRegionEnd(pgs);

                if (!this.PageBreakAtEnd && !IsTableOrMatrixCell(rpt))
                {
                    float newY = pi.Y + pi.H;
                    p.YOffset += newY;	// bump the y location
                }
                SetPagePositionEnd(pgs, pi.Y + pi.H);
            }
            catch (Exception ex)
            {
                rpt.rl.LogError(8, string.Format("Exception in CustomReportItem handling: {0}", ex.Message));
            }
            finally
            {
                if (cri != null)
                    cri.Dispose();
            }

            return;
        }

        void SetProperties(Report rpt, Row row, ICustomReportItem cri)
        {
            if (_Properties == null || _Properties.Count == 0)  // Any properties specified?
                return;

            System.Collections.Generic.Dictionary<string, object> dict =
                new Dictionary<string, object>(_Properties.Count);
            foreach (CustomProperty cp in _Properties)
            {
                string name = cp.Name.EvaluateString(rpt, row);
                object val = cp.Value.Evaluate(rpt, row);
                try { dict.Add(name, val); }
                catch
                {
                    rpt.rl.LogError(4, string.Format("Property {0} has already been set.  New value {1} ignored.", name, val));
                }
            }
            cri.SetProperties(dict);
        }

		public string Type
		{
			get { return  _Type; }
			set {  _Type = value; }
		}

        List<CustomProperty> CustomProperties(XmlNode xNode)
        {
            if (!xNode.HasChildNodes)
                return null;

            List<CustomProperty> cps = new List<CustomProperty>(xNode.ChildNodes.Count);
            foreach (XmlNode xNodeLoop in xNode.ChildNodes)
            {
                switch (xNodeLoop.Name)
                {
                    case "CustomProperty":
                        CustomProperty cp = CustomProperty(xNodeLoop);
                        if (cp != null)
                            cps.Add(cp);
                        break;
                    default:
                        OwnerReport.rl.LogError(4, "Unknown CustomProperties element " + xNodeLoop.Name + " ignored.");
                        break;
                }
            }
            return cps;
        }
        CustomProperty CustomProperty(XmlNode xNode)
        {
            Expression name=null;
            Expression val=null;
            CustomProperty cp = null;
            foreach (XmlNode xNodeLoop in xNode.ChildNodes)
            {
                switch (xNodeLoop.Name)
                {
                    case "Name":
                        name = new Expression(OwnerReport, this, xNodeLoop, ExpressionType.String);
                        break;
                    case "Value":
                        val = new Expression(OwnerReport, this, xNodeLoop, ExpressionType.Variant);
                        break;
                    default:
                        OwnerReport.rl.LogError(4, "Unknown CustomProperty element " + xNodeLoop.Name + " ignored.");
                        break;
                }
            }
            if (name == null || val == null)
                OwnerReport.rl.LogError(8, "CustomProperty requires the Name and Value element.");
            else
            {
                cp = new CustomProperty(name, val);
            }
            return cp;
        }
	}

    class CustomProperty
    {
        Expression _Name;           // name of the property
        Expression _Value;          // value of the property
        public CustomProperty(Expression name, Expression val)
        {
            _Name = name;
            _Value = val;
        }
        public Expression Name
        {
            get { return _Name; }
        }

        public Expression Value
        {
            get { return _Value; }
        }
    }

}