text:
package nxt;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import nxt.crypto.Crypto;
import nxt.peer.Peer;
import nxt.peer.Peer.State;
import nxt.peer.Peers;
import nxt.util.Convert;
import nxt.util.DbIterator;
import nxt.util.JSON;
import nxt.util.Listener;
import nxt.util.Listeners;
import nxt.util.Logger;
import nxt.util.ThreadPool;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;

final class BlockchainProcessorImpl
  implements BlockchainProcessor
{
  private static final byte[] CHECKSUM_TRANSPARENT_FORGING = { 27, -54, -59, -98, 49, -42, 48, -68, -112, 49, 41, 94, -41, 78, -84, 27, -87, -22, -28, 36, -34, -90, 112, -50, -9, 5, 89, -35, 80, -121, -128, 112 };
  private static final BlockchainProcessorImpl instance = new BlockchainProcessorImpl();

  static BlockchainProcessorImpl getInstance()
  {
    return instance;
  }

  private final BlockchainImpl blockchain = BlockchainImpl.getInstance();
  private final TransactionProcessorImpl transactionProcessor = TransactionProcessorImpl.getInstance();
  private final Listeners<Block, BlockchainProcessor.Event> blockListeners = new Listeners();
  private volatile Peer lastBlockchainFeeder;
  private final Runnable getMoreBlocksThread = new Runnable()
  {
    private final JSONStreamAware getCumulativeDifficultyRequest;
    private boolean peerHasMore;

    public void run()
    {
      try
      {
        try
        {
          this.peerHasMore = true;
          Peer localPeer = Peers.getAnyPeer(Peer.State.CONNECTED, true);
          if (localPeer == null) {
            return;
          }
          BlockchainProcessorImpl.this.lastBlockchainFeeder = localPeer;
          JSONObject localJSONObject1 = localPeer.send(this.getCumulativeDifficultyRequest);
          if (localJSONObject1 == null) {
            return;
          }
          BigInteger localBigInteger1 = BlockchainProcessorImpl.this.blockchain.getLastBlock().getCumulativeDifficulty();
          String str = (String)localJSONObject1.get("cumulativeDifficulty");
          if (str == null) {
            return;
          }
          BigInteger localBigInteger2 = new BigInteger(str);
          if (localBigInteger2.compareTo(localBigInteger1) <= 0) {
            return;
          }
          Long localLong1 = Genesis.GENESIS_BLOCK_ID;
          if (!BlockchainProcessorImpl.this.blockchain.getLastBlock().getId().equals(Genesis.GENESIS_BLOCK_ID)) {
            localLong1 = getCommonMilestoneBlockId(localPeer);
          }
          if ((localLong1 == null) || (!this.peerHasMore)) {
            return;
          }
          localLong1 = getCommonBlockId(localPeer, localLong1);
          if ((localLong1 == null) || (!this.peerHasMore)) {
            return;
          }
          BlockImpl localBlockImpl1 = BlockDb.findBlock(localLong1);
          if (BlockchainProcessorImpl.this.blockchain.getLastBlock().getHeight() - localBlockImpl1.getHeight() >= 720) {
            return;
          }
          Long localLong2 = localLong1;
          ArrayList localArrayList = new ArrayList();
          for (;;)
          {
            JSONArray localJSONArray = getNextBlocks(localPeer, localLong2);
            if ((localJSONArray == null) || (localJSONArray.size() == 0)) {
              break;
            }
            synchronized (BlockchainProcessorImpl.this.blockchain)
            {
              for (Object localObject1 : localJSONArray)
              {
                JSONObject localJSONObject2 = (JSONObject)localObject1;
                BlockImpl localBlockImpl2;
                try
                {
                  localBlockImpl2 = BlockchainProcessorImpl.this.parseBlock(localJSONObject2);
                }
                catch (NxtException.ValidationException localValidationException)
                {
                  localPeer.blacklist(localValidationException);
                  return;
                }
                localLong2 = localBlockImpl2.getId();
                if (BlockchainProcessorImpl.this.blockchain.getLastBlock().getId().equals(localBlockImpl2.getPreviousBlockId())) {
                  try
                  {
                    BlockchainProcessorImpl.this.pushBlock(localBlockImpl2);
                  }
                  catch (BlockchainProcessor.BlockNotAcceptedException localBlockNotAcceptedException)
                  {
                    localPeer.blacklist(localBlockNotAcceptedException);
                    return;
                  }
                } else if (!BlockDb.hasBlock(localBlockImpl2.getId())) {
                  localArrayList.add(localBlockImpl2);
                }
              }
            }
          }
          if ((!localArrayList.isEmpty()) && (BlockchainProcessorImpl.this.blockchain.getLastBlock().getHeight() - localBlockImpl1.getHeight() < 720)) {
            processFork(localPeer, localArrayList, localBlockImpl1);
          }
        }
        catch (Exception localException)
        {
          Logger.logDebugMessage("Error in milestone blocks processing thread", localException);
        }
      }
      catch (Throwable localThrowable)
      {
        Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + localThrowable.toString());
        localThrowable.printStackTrace();
        System.exit(1);
      }
    }

    private Long getCommonMilestoneBlockId(Peer paramAnonymousPeer)
    {
      Object localObject1 = null;
      JSONArray localJSONArray;
      for (;;)
      {
        JSONObject localJSONObject1 = new JSONObject();
        localJSONObject1.put("requestType", "getMilestoneBlockIds");
        if (localObject1 == null) {
          localJSONObject1.put("lastBlockId", BlockchainProcessorImpl.this.blockchain.getLastBlock().getStringId());
        } else {
          localJSONObject1.put("lastMilestoneBlockId", localObject1);
        }
        JSONObject localJSONObject2 = paramAnonymousPeer.send(JSON.prepareRequest(localJSONObject1));
        if (localJSONObject2 == null) {
          return null;
        }
        localJSONArray = (JSONArray)localJSONObject2.get("milestoneBlockIds");
        if (localJSONArray == null) {
          return null;
        }
        if (localJSONArray.isEmpty()) {
          return Genesis.GENESIS_BLOCK_ID;
        }
        if (localJSONArray.size() > 20)
        {
          Logger.logDebugMessage("Obsolete or rogue peer " + paramAnonymousPeer.getPeerAddress() + " sends too many milestoneBlockIds, blacklisting");
          paramAnonymousPeer.blacklist();
          return null;
        }
        if (Boolean.TRUE.equals(localJSONObject2.get("last"))) {
          this.peerHasMore = false;
        }
        for (Object localObject2 : localJSONArray)
        {
          Long localLong = Convert.parseUnsignedLong((String)localObject2);
          if (BlockDb.hasBlock(localLong))
          {
            if ((localObject1 == null) && (localJSONArray.size() > 1)) {
              this.peerHasMore = false;
            }
            return localLong;
          }
          localObject1 = (String)localObject2;
        }
      }
    }

    private Long getCommonBlockId(Peer paramAnonymousPeer, Long paramAnonymousLong)
    {
      for (;;)
      {
        JSONObject localJSONObject1 = new JSONObject();
        localJSONObject1.put("requestType", "getNextBlockIds");
        localJSONObject1.put("blockId", Convert.toUnsignedLong(paramAnonymousLong));
        JSONObject localJSONObject2 = paramAnonymousPeer.send(JSON.prepareRequest(localJSONObject1));
        if (localJSONObject2 == null) {
          return null;
        }
        JSONArray localJSONArray = (JSONArray)localJSONObject2.get("nextBlockIds");
        if ((localJSONArray == null) || (localJSONArray.size() == 0)) {
          return null;
        }
        if (localJSONArray.size() > 1440)
        {
          Logger.logDebugMessage("Obsolete or rogue peer " + paramAnonymousPeer.getPeerAddress() + " sends too many nextBlockIds, blacklisting");
          paramAnonymousPeer.blacklist();
          return null;
        }
        for (Object localObject : localJSONArray)
        {
          Long localLong = Convert.parseUnsignedLong((String)localObject);
          if (!BlockDb.hasBlock(localLong)) {
            return paramAnonymousLong;
          }
          paramAnonymousLong = localLong;
        }
      }
    }

    private JSONArray getNextBlocks(Peer paramAnonymousPeer, Long paramAnonymousLong)
    {
      JSONObject localJSONObject1 = new JSONObject();
      localJSONObject1.put("requestType", "getNextBlocks");
      localJSONObject1.put("blockId", Convert.toUnsignedLong(paramAnonymousLong));
      JSONObject localJSONObject2 = paramAnonymousPeer.send(JSON.prepareRequest(localJSONObject1));
      if (localJSONObject2 == null) {
        return null;
      }
      JSONArray localJSONArray = (JSONArray)localJSONObject2.get("nextBlocks");
      if (localJSONArray == null) {
        return null;
      }
      if (localJSONArray.size() > 1440)
      {
        Logger.logDebugMessage("Obsolete or rogue peer " + paramAnonymousPeer.getPeerAddress() + " sends too many nextBlocks, blacklisting");
        paramAnonymousPeer.blacklist();
        return null;
      }
      return localJSONArray;
    }

    private void processFork(Peer paramAnonymousPeer, List<BlockImpl> paramAnonymousList, Block paramAnonymousBlock)
    {
      synchronized (BlockchainProcessorImpl.this.blockchain)
      {
        BigInteger localBigInteger = BlockchainProcessorImpl.this.blockchain.getLastBlock().getCumulativeDifficulty();
        int i;
        try
        {
          while ((!BlockchainProcessorImpl.this.blockchain.getLastBlock().getId().equals(paramAnonymousBlock.getId())) && (BlockchainProcessorImpl.this.popLastBlock())) {}
          if (BlockchainProcessorImpl.this.blockchain.getLastBlock().getId().equals(paramAnonymousBlock.getId())) {
            for (BlockImpl localBlockImpl : paramAnonymousList) {
              if (BlockchainProcessorImpl.this.blockchain.getLastBlock().getId().equals(localBlockImpl.getPreviousBlockId())) {
                try
                {
                  BlockchainProcessorImpl.this.pushBlock(localBlockImpl);
                }
                catch (BlockchainProcessor.BlockNotAcceptedException localBlockNotAcceptedException)
                {
                  paramAnonymousPeer.blacklist(localBlockNotAcceptedException);
                  break;
                }
              }
            }
          }
          i = BlockchainProcessorImpl.this.blockchain.getLastBlock().getCumulativeDifficulty().compareTo(localBigInteger) < 0 ? 1 : 0;
          if (i != 0)
          {
            Logger.logDebugMessage("Rescan caused by peer " + paramAnonymousPeer.getPeerAddress() + ", blacklisting");
            paramAnonymousPeer.blacklist();
          }
        }
        catch (TransactionType.UndoNotSupportedException localUndoNotSupportedException)
        {
          Logger.logDebugMessage(localUndoNotSupportedException.getMessage());
          Logger.logDebugMessage("Popping off last block not possible, will do a rescan");
          i = 1;
        }
        if (i != 0)
        {
          if (paramAnonymousBlock.getNextBlockId() != null)
          {
            Logger.logDebugMessage("Last block is " + BlockchainProcessorImpl.this.blockchain.getLastBlock().getStringId() + " at " + BlockchainProcessorImpl.this.blockchain.getLastBlock().getHeight());
            Logger.logDebugMessage("Deleting blocks after height " + paramAnonymousBlock.getHeight());
            BlockDb.deleteBlock(paramAnonymousBlock.getNextBlockId());
          }
          Logger.logMessage("Will do a re-scan");
          BlockchainProcessorImpl.this.blockListeners.notify(paramAnonymousBlock, BlockchainProcessor.Event.RESCAN_BEGIN);
          BlockchainProcessorImpl.this.scan();
          BlockchainProcessorImpl.this.blockListeners.notify(paramAnonymousBlock, BlockchainProcessor.Event.RESCAN_END);
          Logger.logDebugMessage("Last block is " + BlockchainProcessorImpl.this.blockchain.getLastBlock().getStringId() + " at " + BlockchainProcessorImpl.this.blockchain.getLastBlock().getHeight());
        }
      }
    }
  };

  private BlockchainProcessorImpl()
  {
    this.blockListeners.addListener(new Listener()
    {
      public void notify(Block paramAnonymousBlock)
      {
        if (paramAnonymousBlock.getHeight() % 5000 == 0) {
          Logger.logDebugMessage("processed block " + paramAnonymousBlock.getHeight());
        }
      }
    }, BlockchainProcessor.Event.BLOCK_SCANNED);

    ThreadPool.runBeforeStart(new Runnable()
    {
      public void run()
      {
        BlockchainProcessorImpl.this.addGenesisBlock();
        BlockchainProcessorImpl.this.scan();
      }
    });
    ThreadPool.scheduleThread(this.getMoreBlocksThread, 1);
  }

  public boolean addListener(Listener<Block> paramListener, BlockchainProcessor.Event paramEvent)
  {
    return this.blockListeners.addListener(paramListener, paramEvent);
  }

  public boolean removeListener(Listener<Block> paramListener, BlockchainProcessor.Event paramEvent)
  {
    return this.blockListeners.removeListener(paramListener, paramEvent);
  }

  public Peer getLastBlockchainFeeder()
  {
    return this.lastBlockchainFeeder;
  }

  public void processPeerBlock(JSONObject paramJSONObject)
    throws NxtException
  {
    BlockImpl localBlockImpl = parseBlock(paramJSONObject);
    pushBlock(localBlockImpl);
  }

  public void fullReset()
  {
    synchronized (this.blockchain)
    {
      Logger.logMessage("Deleting blockchain...");

      BlockDb.deleteAll();
      addGenesisBlock();
      scan();
    }
  }

  private void addBlock(BlockImpl paramBlockImpl)
  {
    try
    {
      Connection localConnection = Db.getConnection();Object localObject1 = null;
      try
      {
        try
        {
          BlockDb.saveBlock(localConnection, paramBlockImpl);
          this.blockchain.setLastBlock(paramBlockImpl);
          localConnection.commit();
        }
        catch (SQLException localSQLException2)
        {
          localConnection.rollback();
          throw localSQLException2;
        }
      }
      catch (Throwable localThrowable2)
      {
        localObject1 = localThrowable2;throw localThrowable2;
      }
      finally
      {
        if (localConnection != null) {
          if (localObject1 != null) {
            try
            {
              localConnection.close();
            }
            catch (Throwable localThrowable3)
            {
              localObject1.addSuppressed(localThrowable3);
            }
          } else {
            localConnection.close();
          }
        }
      }
    }
    catch (SQLException localSQLException1)
    {
      throw new RuntimeException(localSQLException1.toString(), localSQLException1);
    }
  }

  private void addGenesisBlock()
  {
    if (BlockDb.hasBlock(Genesis.GENESIS_BLOCK_ID))
    {
      Logger.logMessage("Genesis block already in database");
      return;
    }
    Logger.logMessage("Genesis block not in database, starting from scratch");
    try
    {
      TreeMap localTreeMap = new TreeMap();
      for (int i = 0; i < Genesis.GENESIS_RECIPIENTS.length; i++)
      {
        localObject = this.transactionProcessor.newTransaction(0, (short)0, Genesis.CREATOR_PUBLIC_KEY, Genesis.GENESIS_RECIPIENTS[i], Genesis.GENESIS_AMOUNTS[i], 0, null, Genesis.GENESIS_SIGNATURES[i]);

        localTreeMap.put(((TransactionImpl)localObject).getId(), localObject);
      }
      MessageDigest localMessageDigest = Crypto.sha256();
      for (Object localObject = localTreeMap.values().iterator(); ((Iterator)localObject).hasNext();)
      {
        Transaction localTransaction = (Transaction)((Iterator)localObject).next();
        localMessageDigest.update(localTransaction.getBytes());
      }
      localObject = new BlockImpl(-1, 0, null, 1000000000, 0, localTreeMap.size() * 128, localMessageDigest.digest(), Genesis.CREATOR_PUBLIC_KEY, new byte[64], Genesis.GENESIS_BLOCK_SIGNATURE, null, new ArrayList(localTreeMap.values()));

      ((BlockImpl)localObject).setPrevious(null);

      addBlock((BlockImpl)localObject);
    }
    catch (NxtException.ValidationException localValidationException)
    {
      Logger.logMessage(localValidationException.getMessage());
      throw new RuntimeException(localValidationException.toString(), localValidationException);
    }
  }

  private byte[] calculateTransactionsChecksum()
  {
    PriorityQueue localPriorityQueue = new PriorityQueue(this.blockchain.getTransactionCount(), new Comparator()
    {
      public int compare(Transaction paramAnonymousTransaction1, Transaction paramAnonymousTransaction2)
      {
        long l1 = paramAnonymousTransaction1.getId().longValue();
        long l2 = paramAnonymousTransaction2.getId().longValue();
        return paramAnonymousTransaction1.getTimestamp() > paramAnonymousTransaction2.getTimestamp() ? 1 : paramAnonymousTransaction1.getTimestamp() < paramAnonymousTransaction2.getTimestamp() ? -1 : l1 > l2 ? 1 : l1 < l2 ? -1 : 0;
      }
    });
    Object localObject1 = this.blockchain.getAllTransactions();Object localObject2 = null;
    try
    {
      while (((DbIterator)localObject1).hasNext()) {
        localPriorityQueue.add(((DbIterator)localObject1).next());
      }
    }
    catch (Throwable localThrowable2)
    {
      localObject2 = localThrowable2;throw localThrowable2;
    }
    finally
    {
      if (localObject1 != null) {
        if (localObject2 != null) {
          try
          {
            ((DbIterator)localObject1).close();
          }
          catch (Throwable localThrowable3)
          {
            localObject2.addSuppressed(localThrowable3);
          }
        } else {
          ((DbIterator)localObject1).close();
        }
      }
    }
    localObject1 = Crypto.sha256();
    while (!localPriorityQueue.isEmpty()) {
      ((MessageDigest)localObject1).update(((Transaction)localPriorityQueue.poll()).getBytes());
    }
    return ((MessageDigest)localObject1).digest();
  }

  private void pushBlock(BlockImpl paramBlockImpl)
    throws BlockchainProcessor.BlockNotAcceptedException
  {
    int i = Convert.getEpochTime();
    synchronized (this.blockchain)
    {
      try
      {
        BlockImpl localBlockImpl = this.blockchain.getLastBlock();
        if (!localBlockImpl.getId().equals(paramBlockImpl.getPreviousBlockId())) {
          throw new BlockchainProcessor.BlockOutOfOrderException("Previous block id doesn't match");
        }
        if (paramBlockImpl.getVersion() != (localBlockImpl.getHeight() < 30000 ? 1 : 2)) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Invalid version " + paramBlockImpl.getVersion());
        }
        if (localBlockImpl.getHeight() == 30000)
        {
          localObject1 = calculateTransactionsChecksum();
          if (CHECKSUM_TRANSPARENT_FORGING == null)
          {
            Logger.logMessage("Checksum calculated:\n" + Arrays.toString((byte[])localObject1));
          }
          else
          {
            if (!Arrays.equals((byte[])localObject1, CHECKSUM_TRANSPARENT_FORGING))
            {
              Logger.logMessage("Checksum failed at block 30000");
              throw new BlockchainProcessor.BlockNotAcceptedException("Checksum failed");
            }
            Logger.logMessage("Checksum passed at block 30000");
          }
        }
        if ((paramBlockImpl.getVersion() != 1) && (!Arrays.equals(Crypto.sha256().digest(localBlockImpl.getBytes()), paramBlockImpl.getPreviousBlockHash()))) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Previous block hash doesn't match");
        }
        if ((paramBlockImpl.getTimestamp() > i + 15) || (paramBlockImpl.getTimestamp() <= localBlockImpl.getTimestamp())) {
          throw new BlockchainProcessor.BlockOutOfOrderException("Invalid timestamp: " + paramBlockImpl.getTimestamp() + " current time is " + i + ", previous block timestamp is " + localBlockImpl.getTimestamp());
        }
        if ((paramBlockImpl.getId().equals(Long.valueOf(0L))) || (BlockDb.hasBlock(paramBlockImpl.getId()))) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Duplicate block or invalid id");
        }
        if ((!paramBlockImpl.verifyGenerationSignature()) || (!paramBlockImpl.verifyBlockSignature())) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Signature verification failed");
        }
        Object localObject1 = new HashMap();
        HashMap localHashMap1 = new HashMap();
        HashMap localHashMap2 = new HashMap();
        int j = 0;int k = 0;
        MessageDigest localMessageDigest = Crypto.sha256();
        for (Object localObject2 = paramBlockImpl.getTransactions().iterator(); ((Iterator)localObject2).hasNext();)
        {
          localObject3 = (TransactionImpl)((Iterator)localObject2).next();
          if ((((TransactionImpl)localObject3).getTimestamp() > i + 15) || (((TransactionImpl)localObject3).getTimestamp() > paramBlockImpl.getTimestamp() + 15) || ((((TransactionImpl)localObject3).getExpiration() < paramBlockImpl.getTimestamp()) && (localBlockImpl.getHeight() != 303))) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Invalid transaction timestamp " + ((TransactionImpl)localObject3).getTimestamp() + " for transaction " + ((TransactionImpl)localObject3).getStringId() + ", current time is " + i + ", block timestamp is " + paramBlockImpl.getTimestamp());
          }
          if (TransactionDb.hasTransaction(((TransactionImpl)localObject3).getId())) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Transaction " + ((TransactionImpl)localObject3).getStringId() + " is already in the blockchain");
          }
          if ((((TransactionImpl)localObject3).getReferencedTransactionId() != null) && (!TransactionDb.hasTransaction(((TransactionImpl)localObject3).getReferencedTransactionId())) && (Collections.binarySearch(paramBlockImpl.getTransactionIds(), ((TransactionImpl)localObject3).getReferencedTransactionId()) < 0)) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Missing referenced transaction " + Convert.toUnsignedLong(((TransactionImpl)localObject3).getReferencedTransactionId()) + " for transaction " + ((TransactionImpl)localObject3).getStringId());
          }
          if ((this.transactionProcessor.getUnconfirmedTransaction(((TransactionImpl)localObject3).getId()) != null) && (!((TransactionImpl)localObject3).verify())) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Signature verification failed for transaction " + ((TransactionImpl)localObject3).getStringId());
          }
          if (((TransactionImpl)localObject3).getId().equals(Long.valueOf(0L))) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Invalid transaction id");
          }
          if (((TransactionImpl)localObject3).isDuplicate((Map)localObject1)) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Transaction is a duplicate: " + ((TransactionImpl)localObject3).getStringId());
          }
          try
          {
            ((TransactionImpl)localObject3).validateAttachment();
          }
          catch (NxtException.ValidationException localValidationException)
          {
            throw new BlockchainProcessor.BlockNotAcceptedException(localValidationException.getMessage());
          }
          j += ((TransactionImpl)localObject3).getAmount();

          ((TransactionImpl)localObject3).updateTotals(localHashMap1, localHashMap2);

          k += ((TransactionImpl)localObject3).getFee();

          localMessageDigest.update(((TransactionImpl)localObject3).getBytes());
        }
        Object localObject3;
        if ((j != paramBlockImpl.getTotalAmount()) || (k != paramBlockImpl.getTotalFee())) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Total amount or fee don't match transaction totals");
        }
        if (!Arrays.equals(localMessageDigest.digest(), paramBlockImpl.getPayloadHash())) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Payload hash doesn't match");
        }
        for (localObject2 = localHashMap1.entrySet().iterator(); ((Iterator)localObject2).hasNext();)
        {
          localObject3 = (Map.Entry)((Iterator)localObject2).next();
          localAccount = Account.getAccount((Long)((Map.Entry)localObject3).getKey());
          if (localAccount.getBalance() < ((Long)((Map.Entry)localObject3).getValue()).longValue()) {
            throw new BlockchainProcessor.BlockNotAcceptedException("Not enough funds in sender account: " + Convert.toUnsignedLong(localAccount.getId()));
          }
        }
        Account localAccount;
        for (localObject2 = localHashMap2.entrySet().iterator(); ((Iterator)localObject2).hasNext();)
        {
          localObject3 = (Map.Entry)((Iterator)localObject2).next();
          localAccount = Account.getAccount((Long)((Map.Entry)localObject3).getKey());
          for (Map.Entry localEntry : ((Map)((Map.Entry)localObject3).getValue()).entrySet())
          {
            Long localLong1 = (Long)localEntry.getKey();
            Long localLong2 = (Long)localEntry.getValue();
            if (localAccount.getAssetBalance(localLong1) < localLong2.longValue()) {
              throw new BlockchainProcessor.BlockNotAcceptedException("Asset balance not sufficient in sender account " + Convert.toUnsignedLong(localAccount.getId()));
            }
          }
        }
        paramBlockImpl.setPrevious(localBlockImpl);

        localObject2 = this.transactionProcessor.checkTransactionHashes(paramBlockImpl);
        if (localObject2 != null) {
          throw new BlockchainProcessor.BlockNotAcceptedException("Duplicate hash of transaction " + ((Transaction)localObject2).getStringId());
        }
        addBlock(paramBlockImpl);

        this.transactionProcessor.apply(paramBlockImpl);
      }
      catch (RuntimeException localRuntimeException)
      {
        Logger.logMessage("Error pushing block", localRuntimeException);
        throw new BlockchainProcessor.BlockNotAcceptedException(localRuntimeException.toString());
      }
      this.blockListeners.notify(paramBlockImpl, BlockchainProcessor.Event.BLOCK_PUSHED);

      this.transactionProcessor.updateUnconfirmedTransactions(paramBlockImpl);
    }
    if (paramBlockImpl.getTimestamp() >= Convert.getEpochTime() - 15)
    {
      ??? = paramBlockImpl.getJSONObject();
      ((JSONObject)???).put("requestType", "processBlock");
      Peers.sendToSomePeers((JSONObject)???);
    }
  }

  private boolean popLastBlock()
    throws TransactionType.UndoNotSupportedException
  {
    try
    {
      BlockImpl localBlockImpl1;
      synchronized (this.blockchain)
      {
        localBlockImpl1 = this.blockchain.getLastBlock();
        Logger.logDebugMessage("Will pop block " + localBlockImpl1.getStringId() + " at height " + localBlockImpl1.getHeight());
        if (localBlockImpl1.getId().equals(Genesis.GENESIS_BLOCK_ID)) {
          return false;
        }
        BlockImpl localBlockImpl2 = BlockDb.findBlock(localBlockImpl1.getPreviousBlockId());
        if (localBlockImpl2 == null)
        {
          Logger.logMessage("Previous block is null");
          throw new IllegalStateException();
        }
        this.blockchain.setLastBlock(localBlockImpl1, localBlockImpl2);
        Account localAccount = Account.getAccount(localBlockImpl1.getGeneratorId());
        localAccount.undo(localBlockImpl1.getHeight());
        localAccount.addToBalanceAndUnconfirmedBalance(-localBlockImpl1.getTotalFee() * 100L);
        this.transactionProcessor.undo(localBlockImpl1);
        BlockDb.deleteBlock(localBlockImpl1.getId());
      }
      this.blockListeners.notify(localBlockImpl1, BlockchainProcessor.Event.BLOCK_POPPED);
    }
    catch (RuntimeException localRuntimeException)
    {
      Logger.logMessage("Error popping last block", localRuntimeException);
      return false;
    }
    return true;
  }

  void generateBlock(String paramString)
  {
    TreeSet localTreeSet = new TreeSet();
    for (Object localObject1 = this.transactionProcessor.getAllUnconfirmedTransactions().iterator(); ((Iterator)localObject1).hasNext();)
    {
      localObject2 = (TransactionImpl)((Iterator)localObject1).next();
      if ((((TransactionImpl)localObject2).getReferencedTransactionId() == null) || (TransactionDb.hasTransaction(((TransactionImpl)localObject2).getReferencedTransactionId()))) {
        localTreeSet.add(localObject2);
      }
    }
    localObject1 = new TreeMap();
    Object localObject2 = new HashMap();
    HashMap localHashMap = new HashMap();

    int i = 0;
    int j = 0;
    int k = 0;

    int m = Convert.getEpochTime();
    Object localObject7;
    while (k <= 32640)
    {
      int n = ((SortedMap)localObject1).size();
      for (localObject3 = localTreeSet.iterator(); ((Iterator)localObject3).hasNext();)
      {
        localObject4 = (TransactionImpl)((Iterator)localObject3).next();

        int i1 = ((TransactionImpl)localObject4).getSize();
        if ((((SortedMap)localObject1).get(((TransactionImpl)localObject4).getId()) == null) && (k + i1 <= 32640))
        {
          localObject6 = ((TransactionImpl)localObject4).getSenderId();
          localObject7 = (Long)localHashMap.get(localObject6);
          if (localObject7 == null) {
            localObject7 = Long.valueOf(0L);
          }
          long l = (((TransactionImpl)localObject4).getAmount() + ((TransactionImpl)localObject4).getFee()) * 100L;
          if (((Long)localObject7).longValue() + l <= Account.getAccount((Long)localObject6).getBalance()) {
            if ((((TransactionImpl)localObject4).getTimestamp() <= m + 15) && (((TransactionImpl)localObject4).getExpiration() >= m) &&

              (!((TransactionImpl)localObject4).isDuplicate((Map)localObject2)))
            {
              try
              {
                ((TransactionImpl)localObject4).validateAttachment();
              }
              catch (NxtException.ValidationException localValidationException1) {}
              continue;

              localHashMap.put(localObject6, Long.valueOf(((Long)localObject7).longValue() + l));

              ((SortedMap)localObject1).put(((TransactionImpl)localObject4).getId(), localObject4);
              k += i1;
              i += ((TransactionImpl)localObject4).getAmount();
              j += ((TransactionImpl)localObject4).getFee();
            }
          }
        }
      }
      if (((SortedMap)localObject1).size() == n) {
        break;
      }
    }
    byte[] arrayOfByte1 = Crypto.getPublicKey(paramString);

    Object localObject3 = Crypto.sha256();
    for (Object localObject4 = ((SortedMap)localObject1).values().iterator(); ((Iterator)localObject4).hasNext();)
    {
      localObject5 = (Transaction)((Iterator)localObject4).next();
      ((MessageDigest)localObject3).update(((Transaction)localObject5).getBytes());
    }
    Object localObject5;
    localObject4 = ((MessageDigest)localObject3).digest();

    Object localObject6 = this.blockchain.getLastBlock();
    if (((BlockImpl)localObject6).getHeight() < 30000)
    {
      localObject5 = Crypto.sign(((BlockImpl)localObject6).getGenerationSignature(), paramString);
    }
    else
    {
      ((MessageDigest)localObject3).update(((BlockImpl)localObject6).getGenerationSignature());
      localObject5 = ((MessageDigest)localObject3).digest(arrayOfByte1);
    }
    int i2 = ((BlockImpl)localObject6).getHeight() < 30000 ? 1 : 2;
    byte[] arrayOfByte2 = i2 == 1 ? null : Crypto.sha256().digest(((BlockImpl)localObject6).getBytes());
    try
    {
      localObject7 = new BlockImpl(i2, m, ((BlockImpl)localObject6).getId(), i, j, k, (byte[])localObject4, arrayOfByte1, (byte[])localObject5, null, arrayOfByte2, new ArrayList(((SortedMap)localObject1).values()));
    }
    catch (NxtException.ValidationException localValidationException2)
    {
      Logger.logMessage("Error generating block", localValidationException2);
      return;
    }
    ((BlockImpl)localObject7).sign(paramString);

    ((BlockImpl)localObject7).setPrevious((BlockImpl)localObject6);
    try
    {
      if ((((BlockImpl)localObject7).verifyBlockSignature()) && (((BlockImpl)localObject7).verifyGenerationSignature()))
      {
        pushBlock((BlockImpl)localObject7);
        this.blockListeners.notify(localObject7, BlockchainProcessor.Event.BLOCK_GENERATED);
        Logger.logDebugMessage("Account " + Convert.toUnsignedLong(((BlockImpl)localObject7).getGeneratorId()) + " generated block " + ((BlockImpl)localObject7).getStringId());
      }
      else
      {
        Logger.logDebugMessage("Account " + Convert.toUnsignedLong(((BlockImpl)localObject7).getGeneratorId()) + " generated an incorrect block.");
      }
    }
    catch (BlockchainProcessor.BlockNotAcceptedException localBlockNotAcceptedException)
    {
      Logger.logDebugMessage("Generate block failed: " + localBlockNotAcceptedException.getMessage());
    }
  }

  private BlockImpl parseBlock(JSONObject paramJSONObject)
    throws NxtException.ValidationException
  {
    try
    {
      int i = ((Long)paramJSONObject.get("version")).intValue();
      int j = ((Long)paramJSONObject.get("timestamp")).intValue();
      Long localLong = Convert.parseUnsignedLong((String)paramJSONObject.get("previousBlock"));
      int k = ((Long)paramJSONObject.get("totalAmount")).intValue();
      int m = ((Long)paramJSONObject.get("totalFee")).intValue();
      int n = ((Long)paramJSONObject.get("payloadLength")).intValue();
      byte[] arrayOfByte1 = Convert.parseHexString((String)paramJSONObject.get("payloadHash"));
      byte[] arrayOfByte2 = Convert.parseHexString((String)paramJSONObject.get("generatorPublicKey"));
      byte[] arrayOfByte3 = Convert.parseHexString((String)paramJSONObject.get("generationSignature"));
      byte[] arrayOfByte4 = Convert.parseHexString((String)paramJSONObject.get("blockSignature"));
      byte[] arrayOfByte5 = i == 1 ? null : Convert.parseHexString((String)paramJSONObject.get("previousBlockHash"));

      TreeMap localTreeMap = new TreeMap();
      JSONArray localJSONArray = (JSONArray)paramJSONObject.get("transactions");
      for (Object localObject : localJSONArray)
      {
        TransactionImpl localTransactionImpl = this.transactionProcessor.parseTransaction((JSONObject)localObject);
        if (localTreeMap.put(localTransactionImpl.getId(), localTransactionImpl) != null) {
          throw new NxtException.ValidationException("Block contains duplicate transactions: " + localTransactionImpl.getStringId());
        }
      }
      return new BlockImpl(i, j, localLong, k, m, n, arrayOfByte1, arrayOfByte2, arrayOfByte3, arrayOfByte4, arrayOfByte5, new ArrayList(localTreeMap.values()));
    }
    catch (RuntimeException localRuntimeException)
    {
      throw new NxtException.ValidationException(localRuntimeException.toString(), localRuntimeException);
    }
  }

  private void scan()
  {
    synchronized (this.blockchain)
    {
      Logger.logMessage("Scanning blockchain...");
      Account.clear();
      Alias.clear();
      Asset.clear();
      Order.clear();
      Poll.clear();
      Trade.clear();
      Vote.clear();
      this.transactionProcessor.clear();
      try
      {
        Connection localConnection = Db.getConnection();Object localObject1 = null;
        try
        {
          PreparedStatement localPreparedStatement = localConnection.prepareStatement("SELECT * FROM block ORDER BY db_id ASC");Object localObject2 = null;
          try
          {
            Long localLong = Genesis.GENESIS_BLOCK_ID;

            ResultSet localResultSet = localPreparedStatement.executeQuery();
            while (localResultSet.next())
            {
              BlockImpl localBlockImpl = BlockDb.findBlock(localConnection, localResultSet);
              if (!localBlockImpl.getId().equals(localLong)) {
                throw new NxtException.ValidationException("Database blocks in the wrong order!");
              }
              this.blockchain.setLastBlock(localBlockImpl);
              this.transactionProcessor.apply(localBlockImpl);
              this.blockListeners.notify(localBlockImpl, BlockchainProcessor.Event.BLOCK_SCANNED);
              localLong = localBlockImpl.getNextBlockId();
            }
          }
          catch (Throwable localThrowable4)
          {
            localObject2 = localThrowable4;throw localThrowable4;
          }
          finally {}
        }
        catch (Throwable localThrowable2)
        {
          localObject1 = localThrowable2;throw localThrowable2;
        }
        finally
        {
          if (localConnection != null) {
            if (localObject1 != null) {
              try
              {
                localConnection.close();
              }
              catch (Throwable localThrowable6)
              {
                localObject1.addSuppressed(localThrowable6);
              }
            } else {
              localConnection.close();
            }
          }
        }
      }
      catch (NxtException.ValidationException|SQLException localValidationException)
      {
        throw new RuntimeException(localValidationException.toString(), localValidationException);
      }
      Logger.logMessage("...done");
    }
  }
}


text:
Example Sketches for Fragment: http://www.syedrezaali.com/store/fragment-win-app

## Instructions

1. Copy Shaders in the Common Folder to /Fragment/assets/Shaders/Common
2. In Fragment, LOAD (Apple + o) any one of the sketches
3. Keep in mind Fragment will take care of copying the sketch to /Fragment/assets/Shaders/* so please edit these shaders not the original ones in the sketches folder.
4. Have fun! Make awesome.

## Contributing

1. Fork the Repo
2. Add your sketch (Folder that is outputted by Fragment and an Image for the Sketch ( 1000 px by 1000 px ) )
3. Submit a pull request
4. Bask in glory

redpajama_set_name: RedPajamaGithub


text:
<?php

$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_STYLES][] = 'bootstrap';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_STYLES][] = '%SITE_NAME%';

$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = 'lib:jquery/jquery-3.1.1.min.js';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = 'lib:bootstrap/js/bootstrap.min.js';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = 'angular.min';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = 'toobasic_asset';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = 'toobasic_rest_asset';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = '%SITE_NAME%';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = '%SITE_NAME%-nav';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = '%SITE_NAME%-main-contents';
$Defaults[GC_DEFAULTS_HTMLASSETS][GC_DEFAULTS_HTMLASSETS_SCRIPTS][] = '%SITE_NAME%-side-bar';


text:
import Adapter from './Adapter'

interface TuxContext {
  isEditing: boolean
  editModel: (model: any) => Promise<boolean>
  adapter: Adapter
}

export default TuxContext


text:
import logging
from sqlalchemy import schema, util, exc
from sqlalchemy.dialects.postgresql.base import PGDDLCompiler
from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
from sqlalchemy.engine import reflection
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import BindParameter, Executable, ClauseElement
from sqlalchemy.types import VARCHAR, NullType, BigInteger, Integer

class RedShiftDDLCompiler(PGDDLCompiler):
    ''' Handles Redshift specific create table syntax.

    Users can specify the DISTSTYLE, DISTKEY, SORTKEY and ENCODE properties per
    table and per column.

    Table level properties can be set using the dialect specific syntax. For
    example, to specify a distkey and style you apply the following ::

        table = Table(metadata,
                      Column('id', Integer, primary_key=True),
                      Column('name', String),
                      redshift_diststyle="KEY",
                      redshift_distkey="id"
                      redshift_sortkey=["id", "name"]
                      )

    A single sortkey can be applied without a wrapping list ::

        table = Table(metadata,
                      Column('id', Integer, primary_key=True),
                      Column('name', String),
                      redshift_sortkey="id"
                      )

    Column level special syntax can also be applied using the column info
    dictionary. For example, we can specify the encode for a column ::

        table = Table(metadata,
                      Column('id', Integer, primary_key=True),
                      Column('name', String, info={"encode":"lzo"})
                      )

    We can also specify the distkey and sortkey options ::

        table = Table(metadata,
                      Column('id', Integer, primary_key=True),
                      Column('name', String,
                             info={"distkey":True, "sortkey":True})
                      )

    '''

    def post_create_table(self, table):
        text = ""
        info = table.dialect_options['redshift']
        diststyle = info.get('diststyle', None)
        if diststyle:
            diststyle = diststyle.upper()
            if diststyle not in ('EVEN', 'KEY', 'ALL'):
                raise exc.CompileError(
                               u"diststyle {0} is invalid".format(diststyle))
            text += " DISTSTYLE " + diststyle

        distkey = info.get('distkey', None)
        if distkey:
            text += " DISTKEY ({0})".format(distkey)

        sortkey = info.get('sortkey', None)
        if sortkey:
            if isinstance(sortkey, str):
                keys = (sortkey,)
            else:
                keys = sortkey
            text += " SORTKEY ({0})".format(", ".join(keys))
        return text

    def get_column_specification(self, column, **kwargs):
        colspec = self.preparer.format_column(column)

        colspec += " " + self.dialect.type_compiler.process(column.type)

        default = self.get_column_default_string(column)
        if default is not None:
            colspec += " DEFAULT " + default

        colspec += self._fetch_redshift_column_attributes(column)

        if not column.nullable:
            colspec += " NOT NULL"
        return colspec

    def _fetch_redshift_column_attributes(self, column):
        text = ""
        if not hasattr(column, 'info'):
            return text
        info = column.info
        identity = info.get('identity', None)
        if identity:
            text += " IDENTITY({0},{1})".format(identity[0], identity[1])

        encode = info.get('encode', None)
        if encode:
            text += " ENCODE " + encode

        distkey = info.get('distkey', None)
        if distkey:
            text += " DISTKEY"

        sortkey = info.get('sortkey', None)
        if sortkey:
            text += " SORTKEY"
        return text

class RedshiftDialect(PGDialect_psycopg2):
    name = 'redshift'
    ddl_compiler = RedShiftDDLCompiler

    construct_arguments = [
                            (schema.Index, {
                                "using": False,
                                "where": None,
                                "ops": {}
                            }),
                            (schema.Table, {
                                "ignore_search_path": False,
                                'diststyle': None,
                                'distkey': None,
                                'sortkey': None
                            }),
                           ]

    @reflection.cache
    def get_pk_constraint(self, connection, table_name, schema=None, **kw):
        """
        Constraints in redshift are informational only. This allows reflection to work
        """
        return {'constrained_columns': [], 'name': ''}

    @reflection.cache
    def get_indexes(self, connection, table_name, schema, **kw):
        """
        Redshift does not use traditional indexes.
        """
        return []

    #def set_isolation_level(self, connection, level):
    #    from psycopg2 import extensions
    #    connection.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)

    @util.memoized_property
    def _isolation_lookup(self):
        extensions = __import__('psycopg2.extensions').extensions
        return {
            'READ COMMITTED': extensions.ISOLATION_LEVEL_READ_COMMITTED,
            'READ UNCOMMITTED': extensions.ISOLATION_LEVEL_READ_UNCOMMITTED,
            'REPEATABLE READ': extensions.ISOLATION_LEVEL_REPEATABLE_READ,
            'SERIALIZABLE': extensions.ISOLATION_LEVEL_SERIALIZABLE,
            'AUTOCOMMIT': extensions.ISOLATION_LEVEL_AUTOCOMMIT
        }

    def set_isolation_level(self, connection, level):
        try:
            level = self._isolation_lookup[level.replace('_', ' ')]
        except KeyError:
            raise exc.ArgumentError(
                "Invalid value '%s' for isolation_level. "
                "Valid isolation levels for %s are %s" %
                (level, self.name, ", ".join(self._isolation_lookup))
            )

        connection.set_isolation_level(level)

    def _get_column_info(self, name, format_type, default,
                         notnull, domains, enums, schema):
        column_info = super(RedshiftDialect, self)._get_column_info(name, format_type, default,
                                                                    notnull, domains,
                                                                    enums, schema, comment=None)
        if isinstance(column_info['type'], VARCHAR) and column_info['type'].length is None:
            column_info['type'] = NullType()
        return column_info

class UnloadFromSelect(Executable, ClauseElement):
    ''' Prepares a RedShift unload statement to drop a query to Amazon S3
    http://docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD_command_examples.html
    '''
    def __init__(self, select, unload_location, access_key, secret_key, session_token='', options={}):
        ''' Initializes an UnloadFromSelect instance

        Args:
            self: An instance of UnloadFromSelect
            select: The select statement to be unloaded
            unload_location: The Amazon S3 bucket where the result will be stored
            access_key - AWS Access Key (required)
            secret_key - AWS Secret Key (required)
            session_token - AWS STS Session Token (optional)
            options - Set of optional parameters to modify the UNLOAD sql
                parallel: If 'ON' the result will be written to multiple files. If
                    'OFF' the result will write to one (1) file up to 6.2GB before
                    splitting
                gzip - Boolean value denoting whether output should be gzipped (.gz)
                escape - Boolean value denoting whether special characters should be escaped; defaults to False
                add_quotes: Boolean value for ADDQUOTES; defaults to True
                null_as: optional string that represents a null value in unload output
                delimiter - File delimiter. Defaults to ','
        '''
        self.select = select
        self.unload_location = unload_location
        self.access_key = access_key
        self.secret_key = secret_key
        self.session_token = session_token
        self.options = options

@compiles(UnloadFromSelect)
def visit_unload_from_select(element, compiler, **kw):
    ''' Returns the actual sql query for the UnloadFromSelect class

    '''
    return """
           UNLOAD ('%(query)s') TO '%(unload_location)s'
           CREDENTIALS 'aws_access_key_id=%(access_key)s;aws_secret_access_key=%(secret_key)s%(session_token)s'
           DELIMITER '%(delimiter)s'
           %(add_quotes)s
           %(null_as)s
           %(gzip)s
           %(escape)s
           ALLOWOVERWRITE
           PARALLEL %(parallel)s;
           """ % \
           {'query': compiler.process(element.select, unload_select=True, literal_binds=True),
            'unload_location': element.unload_location,
            'access_key': element.access_key,
            'secret_key': element.secret_key,
            'session_token': ';token=%s' % element.session_token if element.session_token else '',
            'gzip': 'GZIP' if bool(element.options.get('gzip', False)) else '',
            'escape': 'ESCAPE' if bool(element.options.get('escape', False)) else '',
            'add_quotes': 'ADDQUOTES' if bool(element.options.get('add_quotes', True)) else '',
            'null_as': ("NULL '%s'" % element.options.get('null_as')) if element.options.get('null_as') else '',
            'delimiter': element.options.get('delimiter', ','),
            'parallel': element.options.get('parallel', 'ON')}

class CopyCommand(Executable, ClauseElement):
    ''' Prepares a RedShift COPY statement
    '''
    def __init__(self, schema_name, table_name, data_location, access_key, secret_key, session_token='', options={}):
        ''' Initializes a CopyCommand instance

        Args:
            self: An instance of CopyCommand
            schema_name - Schema associated with the table_name
            table_name: The table to copy the data into
            data_location The Amazon S3 location from where to copy - or a manifest file if 'manifest' option is used
            access_key - AWS Access Key (required)
            secret_key - AWS Secret Key (required)
            session_token - AWS STS Session Token (optional)
            options - Set of optional parameters to modify the COPY sql
                delimiter - File delimiter; defaults to ','
                ignore_header - Integer value of number of lines to skip at the start of each file
                null - Optional string value denoting what to interpret as a NULL value from the file
                gzip - Boolean value denoting whether input data is gzipped (.gz); defaults to False
                escape - Boolean value denoting whether the backslash is treated as escape character; defaults to False
                remove_quotes - Boolean value denoting whether to remove surrounding quotation; defaults to False
                manifest - Boolean value denoting whether data_location is a manifest file; defaults to False
                empty_as_null - Boolean value denoting whether to load VARCHAR fields with
                                empty values as NULL instead of empty string; defaults to True
                blanks_as_null - Boolean value denoting whether to load VARCHAR fields with
                                 whitespace only values as NULL instead of whitespace; defaults to True
        '''
        self.schema_name = schema_name
        self.table_name = table_name
        self.data_location = data_location
        self.access_key = access_key
        self.secret_key = secret_key
        self.session_token = session_token
        self.options = options

@compiles(CopyCommand)
def visit_copy_command(element, compiler, **kw):
    ''' Returns the actual sql query for the CopyCommand class
    '''
    opts = element.options
    #"TRUNCATECOLUMNS EMPTYASNULL BLANKSASNULL DELIMITER ',' IGNOREHEADER 0 ;").strip()
    session_token = element.session_token
    copy_cmd_str = """
           COPY %(schema_name)s.%(table_name)s FROM '%(data_location)s'
           CREDENTIALS 'aws_access_key_id=%(access_key)s;aws_secret_access_key=%(secret_key)s%(session_token)s'
           CSV
           TRUNCATECOLUMNS
           %(empty_as_null)s
           %(blanks_as_null)s
           DELIMITER '%(delimiter)s'
           IGNOREHEADER %(ignore_header)s
           %(null)s
           %(gzip)s
           %(escape)s
           %(remove_quotes)s
           %(manifest)s;
           """ % \
           {'schema_name': element.schema_name,
            'table_name': element.table_name,
            'data_location': element.data_location,
            'access_key': element.access_key,
            'secret_key': element.secret_key,
            'session_token': ';token=%s' % session_token if session_token else '',
            'null': ("NULL '%s'" % opts.get('null')) if opts.get('null') else '',
            'delimiter': opts.get('delimiter', ','),
            'ignore_header': opts.get('ignore_header', 0),
            'gzip': 'GZIP' if opts.get('gzip', False) else '',
            'escape': 'ESCAPE' if opts.get('escape', False) else '',
            'remove_quotes': 'REMOVEQUOTES' if opts.get('remove_quotes', False) else '',
            'manifest': 'MANIFEST' if opts.get('manifest', False) else '',
            'empty_as_null': 'EMPTYASNULL' if opts.get('empty_as_null', True) else '',
            'blanks_as_null': 'BLANKSASNULL' if opts.get('blanks_as_null', True) else ''}
    return copy_cmd_str

@compiles(BindParameter)
def visit_bindparam(bindparam, compiler, **kw):
    #print bindparam
    res = compiler.visit_bindparam(bindparam, **kw)
    return res.replace("'", "\\'").replace('%', '%%') if 'unload_select' in kw else res


text:
<title>Z80 Syntax - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Z80_002dDependent.html#Z80_002dDependent" title="Z80-Dependent">
<link rel="prev" href="Z80-Options.html#Z80-Options" title="Z80 Options">
<link rel="next" href="Z80-Floating-Point.html#Z80-Floating-Point" title="Z80 Floating Point">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Z80 Floating Point,
Previous: Z80 Options,
Up: Z80-Dependent

9.55.2 Syntax

The assembler syntax closely follows the 'Z80 family CPU User Manual' by
Zilog.
In expressions a single ‘<samp>=</samp>’ may be used as “is equal to”
comparison operator.

Suffices can be used to indicate the radix of integer constants;
‘<samp>H</samp>’ or ‘<samp>h</samp>’ for hexadecimal, ‘<samp>D</samp>’ or ‘<samp>d</samp>’ for decimal,
‘<samp>Q</samp>’, ‘<samp>O</samp>’, ‘<samp>q</samp>’ or ‘<samp>o</samp>’ for octal, and ‘<samp>B</samp>’ for
binary.

The suffix ‘<samp>b</samp>’ denotes a backreference to local label.

Z80-Chars:                 Special Characters

Z80-Regs:                  Register Names

Z80-Case:                  Case Sensitivity


text:
using namespace std;

Date::Date(const int year, const int month, const int day) : Year(year), Month(month), Day(day) {}

ostream& operator<<(ostream& out, const Date& date) {
    out << setfill('0')
        << setw(4) << date.Year << '-'
        << setw(2) << date.Month << '-'
        << setw(2) << date.Day;
    return out;
}

bool operator<(const Date& left, const Date& right) {
    return (left.Year * 12 * 31 + left.Month * 31 + left.Day)
           < (right.Year * 12 * 31 + right.Month * 31 + right.Day);
}

bool operator==(const Date& left, const Date& right) {
    return (left.Year * 12 * 31 + left.Month * 31 + left.Day)
           == (right.Year * 12 * 31 + right.Month * 31 + right.Day);
}

bool operator<=(const Date& left, const Date& right) {
    return (left < right) || (left == right);
}

bool operator!=(const Date& left, const Date& right) {
    return !(left == right);
}

bool operator>(const Date& left, const Date& right) {
    return !(left <= right);
}

bool operator>=(const Date& left, const Date& right) {
    return (left > right) || (left == right);
}

Date ParseDate(istream& is) {
    string str_date;
    is >> str_date;

    stringstream ss(str_date);

    int y, m, d;
    ss >> y;
    ss.ignore(1);
    ss >> m;
    ss.ignore(1);
    ss >> d;

    return Date(y, m, d);
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-52.js
 * @description Object.defineProperties - desc.value and P.value are two boolean values with different values (8.12.9 step 6)
 */

function testcase() {

        var obj = {};

        obj.foo = true; // default value of attributes: writable: true, configurable: true, enumerable: true

        Object.defineProperties(obj, {
            foo: {
                value: false
            }
        });
        return dataPropertyAttributesAreCorrect(obj, "foo", false, true, true, true);
    }
runTestCase(testcase);


text:
/**
 * Autogenerated by Thrift Compiler (0.12.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.storm.generated;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.12.0)")
public class ExecutorStats implements org.apache.storm.thrift.TBase<ExecutorStats, ExecutorStats._Fields>, java.io.Serializable, Cloneable, Comparable<ExecutorStats> {
  private static final org.apache.storm.thrift.protocol.TStruct STRUCT_DESC = new org.apache.storm.thrift.protocol.TStruct("ExecutorStats");

  private static final org.apache.storm.thrift.protocol.TField EMITTED_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("emitted", org.apache.storm.thrift.protocol.TType.MAP, (short)1);
  private static final org.apache.storm.thrift.protocol.TField TRANSFERRED_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("transferred", org.apache.storm.thrift.protocol.TType.MAP, (short)2);
  private static final org.apache.storm.thrift.protocol.TField SPECIFIC_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("specific", org.apache.storm.thrift.protocol.TType.STRUCT, (short)3);
  private static final org.apache.storm.thrift.protocol.TField RATE_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("rate", org.apache.storm.thrift.protocol.TType.DOUBLE, (short)4);

  private static final org.apache.storm.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ExecutorStatsStandardSchemeFactory();
  private static final org.apache.storm.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ExecutorStatsTupleSchemeFactory();

  private @org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> emitted; // required
  private @org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> transferred; // required
  private @org.apache.storm.thrift.annotation.Nullable ExecutorSpecificStats specific; // required
  private double rate; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.storm.thrift.TFieldIdEnum {
    EMITTED((short)1, "emitted"),
    TRANSFERRED((short)2, "transferred"),
    SPECIFIC((short)3, "specific"),
    RATE((short)4, "rate");

    private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();

    static {
      for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    @org.apache.storm.thrift.annotation.Nullable
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // EMITTED
          return EMITTED;
        case 2: // TRANSFERRED
          return TRANSFERRED;
        case 3: // SPECIFIC
          return SPECIFIC;
        case 4: // RATE
          return RATE;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    @org.apache.storm.thrift.annotation.Nullable
    public static _Fields findByName(java.lang.String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final java.lang.String _fieldName;

    _Fields(short thriftId, java.lang.String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public java.lang.String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __RATE_ISSET_ID = 0;
  private byte __isset_bitfield = 0;
  public static final java.util.Map<_Fields, org.apache.storm.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    java.util.Map<_Fields, org.apache.storm.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.storm.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.EMITTED, new org.apache.storm.thrift.meta_data.FieldMetaData("emitted", org.apache.storm.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP,
            new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING),
            new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP,
                new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING),
                new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.I64)))));
    tmpMap.put(_Fields.TRANSFERRED, new org.apache.storm.thrift.meta_data.FieldMetaData("transferred", org.apache.storm.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP,
            new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING),
            new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP,
                new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING),
                new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.I64)))));
    tmpMap.put(_Fields.SPECIFIC, new org.apache.storm.thrift.meta_data.FieldMetaData("specific", org.apache.storm.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.storm.thrift.meta_data.StructMetaData(org.apache.storm.thrift.protocol.TType.STRUCT, ExecutorSpecificStats.class)));
    tmpMap.put(_Fields.RATE, new org.apache.storm.thrift.meta_data.FieldMetaData("rate", org.apache.storm.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.DOUBLE)));
    metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
    org.apache.storm.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ExecutorStats.class, metaDataMap);
  }

  public ExecutorStats() {
  }

  public ExecutorStats(
    java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> emitted,
    java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> transferred,
    ExecutorSpecificStats specific,
    double rate)
  {
    this();
    this.emitted = emitted;
    this.transferred = transferred;
    this.specific = specific;
    this.rate = rate;
    set_rate_isSet(true);
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public ExecutorStats(ExecutorStats other) {
    __isset_bitfield = other.__isset_bitfield;
    if (other.is_set_emitted()) {
      java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> __this__emitted = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>(other.emitted.size());
      for (java.util.Map.Entry<java.lang.String, java.util.Map<java.lang.String,java.lang.Long>> other_element : other.emitted.entrySet()) {

        java.lang.String other_element_key = other_element.getKey();
        java.util.Map<java.lang.String,java.lang.Long> other_element_value = other_element.getValue();

        java.lang.String __this__emitted_copy_key = other_element_key;

        java.util.Map<java.lang.String,java.lang.Long> __this__emitted_copy_value = new java.util.HashMap<java.lang.String,java.lang.Long>(other_element_value);

        __this__emitted.put(__this__emitted_copy_key, __this__emitted_copy_value);
      }
      this.emitted = __this__emitted;
    }
    if (other.is_set_transferred()) {
      java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> __this__transferred = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>(other.transferred.size());
      for (java.util.Map.Entry<java.lang.String, java.util.Map<java.lang.String,java.lang.Long>> other_element : other.transferred.entrySet()) {

        java.lang.String other_element_key = other_element.getKey();
        java.util.Map<java.lang.String,java.lang.Long> other_element_value = other_element.getValue();

        java.lang.String __this__transferred_copy_key = other_element_key;

        java.util.Map<java.lang.String,java.lang.Long> __this__transferred_copy_value = new java.util.HashMap<java.lang.String,java.lang.Long>(other_element_value);

        __this__transferred.put(__this__transferred_copy_key, __this__transferred_copy_value);
      }
      this.transferred = __this__transferred;
    }
    if (other.is_set_specific()) {
      this.specific = new ExecutorSpecificStats(other.specific);
    }
    this.rate = other.rate;
  }

  public ExecutorStats deepCopy() {
    return new ExecutorStats(this);
  }

  @Override
  public void clear() {
    this.emitted = null;
    this.transferred = null;
    this.specific = null;
    set_rate_isSet(false);
    this.rate = 0.0;
  }

  public int get_emitted_size() {
    return (this.emitted == null) ? 0 : this.emitted.size();
  }

  public void put_to_emitted(java.lang.String key, java.util.Map<java.lang.String,java.lang.Long> val) {
    if (this.emitted == null) {
      this.emitted = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>();
    }
    this.emitted.put(key, val);
  }

  @org.apache.storm.thrift.annotation.Nullable
  public java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> get_emitted() {
    return this.emitted;
  }

  public void set_emitted(@org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> emitted) {
    this.emitted = emitted;
  }

  public void unset_emitted() {
    this.emitted = null;
  }

  /** Returns true if field emitted is set (has been assigned a value) and false otherwise */
  public boolean is_set_emitted() {
    return this.emitted != null;
  }

  public void set_emitted_isSet(boolean value) {
    if (!value) {
      this.emitted = null;
    }
  }

  public int get_transferred_size() {
    return (this.transferred == null) ? 0 : this.transferred.size();
  }

  public void put_to_transferred(java.lang.String key, java.util.Map<java.lang.String,java.lang.Long> val) {
    if (this.transferred == null) {
      this.transferred = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>();
    }
    this.transferred.put(key, val);
  }

  @org.apache.storm.thrift.annotation.Nullable
  public java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> get_transferred() {
    return this.transferred;
  }

  public void set_transferred(@org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>> transferred) {
    this.transferred = transferred;
  }

  public void unset_transferred() {
    this.transferred = null;
  }

  /** Returns true if field transferred is set (has been assigned a value) and false otherwise */
  public boolean is_set_transferred() {
    return this.transferred != null;
  }

  public void set_transferred_isSet(boolean value) {
    if (!value) {
      this.transferred = null;
    }
  }

  @org.apache.storm.thrift.annotation.Nullable
  public ExecutorSpecificStats get_specific() {
    return this.specific;
  }

  public void set_specific(@org.apache.storm.thrift.annotation.Nullable ExecutorSpecificStats specific) {
    this.specific = specific;
  }

  public void unset_specific() {
    this.specific = null;
  }

  /** Returns true if field specific is set (has been assigned a value) and false otherwise */
  public boolean is_set_specific() {
    return this.specific != null;
  }

  public void set_specific_isSet(boolean value) {
    if (!value) {
      this.specific = null;
    }
  }

  public double get_rate() {
    return this.rate;
  }

  public void set_rate(double rate) {
    this.rate = rate;
    set_rate_isSet(true);
  }

  public void unset_rate() {
    __isset_bitfield = org.apache.storm.thrift.EncodingUtils.clearBit(__isset_bitfield, __RATE_ISSET_ID);
  }

  /** Returns true if field rate is set (has been assigned a value) and false otherwise */
  public boolean is_set_rate() {
    return org.apache.storm.thrift.EncodingUtils.testBit(__isset_bitfield, __RATE_ISSET_ID);
  }

  public void set_rate_isSet(boolean value) {
    __isset_bitfield = org.apache.storm.thrift.EncodingUtils.setBit(__isset_bitfield, __RATE_ISSET_ID, value);
  }

  public void setFieldValue(_Fields field, @org.apache.storm.thrift.annotation.Nullable java.lang.Object value) {
    switch (field) {
    case EMITTED:
      if (value == null) {
        unset_emitted();
      } else {
        set_emitted((java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>)value);
      }
      break;

    case TRANSFERRED:
      if (value == null) {
        unset_transferred();
      } else {
        set_transferred((java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>)value);
      }
      break;

    case SPECIFIC:
      if (value == null) {
        unset_specific();
      } else {
        set_specific((ExecutorSpecificStats)value);
      }
      break;

    case RATE:
      if (value == null) {
        unset_rate();
      } else {
        set_rate((java.lang.Double)value);
      }
      break;

    }
  }

  @org.apache.storm.thrift.annotation.Nullable
  public java.lang.Object getFieldValue(_Fields field) {
    switch (field) {
    case EMITTED:
      return get_emitted();

    case TRANSFERRED:
      return get_transferred();

    case SPECIFIC:
      return get_specific();

    case RATE:
      return get_rate();

    }
    throw new java.lang.IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new java.lang.IllegalArgumentException();
    }

    switch (field) {
    case EMITTED:
      return is_set_emitted();
    case TRANSFERRED:
      return is_set_transferred();
    case SPECIFIC:
      return is_set_specific();
    case RATE:
      return is_set_rate();
    }
    throw new java.lang.IllegalStateException();
  }

  @Override
  public boolean equals(java.lang.Object that) {
    if (that == null)
      return false;
    if (that instanceof ExecutorStats)
      return this.equals((ExecutorStats)that);
    return false;
  }

  public boolean equals(ExecutorStats that) {
    if (that == null)
      return false;
    if (this == that)
      return true;

    boolean this_present_emitted = true && this.is_set_emitted();
    boolean that_present_emitted = true && that.is_set_emitted();
    if (this_present_emitted || that_present_emitted) {
      if (!(this_present_emitted && that_present_emitted))
        return false;
      if (!this.emitted.equals(that.emitted))
        return false;
    }

    boolean this_present_transferred = true && this.is_set_transferred();
    boolean that_present_transferred = true && that.is_set_transferred();
    if (this_present_transferred || that_present_transferred) {
      if (!(this_present_transferred && that_present_transferred))
        return false;
      if (!this.transferred.equals(that.transferred))
        return false;
    }

    boolean this_present_specific = true && this.is_set_specific();
    boolean that_present_specific = true && that.is_set_specific();
    if (this_present_specific || that_present_specific) {
      if (!(this_present_specific && that_present_specific))
        return false;
      if (!this.specific.equals(that.specific))
        return false;
    }

    boolean this_present_rate = true;
    boolean that_present_rate = true;
    if (this_present_rate || that_present_rate) {
      if (!(this_present_rate && that_present_rate))
        return false;
      if (this.rate != that.rate)
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    int hashCode = 1;

    hashCode = hashCode * 8191 + ((is_set_emitted()) ? 131071 : 524287);
    if (is_set_emitted())
      hashCode = hashCode * 8191 + emitted.hashCode();

    hashCode = hashCode * 8191 + ((is_set_transferred()) ? 131071 : 524287);
    if (is_set_transferred())
      hashCode = hashCode * 8191 + transferred.hashCode();

    hashCode = hashCode * 8191 + ((is_set_specific()) ? 131071 : 524287);
    if (is_set_specific())
      hashCode = hashCode * 8191 + specific.hashCode();

    hashCode = hashCode * 8191 + org.apache.storm.thrift.TBaseHelper.hashCode(rate);

    return hashCode;
  }

  @Override
  public int compareTo(ExecutorStats other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = java.lang.Boolean.valueOf(is_set_emitted()).compareTo(other.is_set_emitted());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (is_set_emitted()) {
      lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.emitted, other.emitted);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.valueOf(is_set_transferred()).compareTo(other.is_set_transferred());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (is_set_transferred()) {
      lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.transferred, other.transferred);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.valueOf(is_set_specific()).compareTo(other.is_set_specific());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (is_set_specific()) {
      lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.specific, other.specific);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.valueOf(is_set_rate()).compareTo(other.is_set_rate());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (is_set_rate()) {
      lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.rate, other.rate);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  @org.apache.storm.thrift.annotation.Nullable
  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.storm.thrift.protocol.TProtocol iprot) throws org.apache.storm.thrift.TException {
    scheme(iprot).read(iprot, this);
  }

  public void write(org.apache.storm.thrift.protocol.TProtocol oprot) throws org.apache.storm.thrift.TException {
    scheme(oprot).write(oprot, this);
  }

  @Override
  public java.lang.String toString() {
    java.lang.StringBuilder sb = new java.lang.StringBuilder("ExecutorStats(");
    boolean first = true;

    sb.append("emitted:");
    if (this.emitted == null) {
      sb.append("null");
    } else {
      sb.append(this.emitted);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("transferred:");
    if (this.transferred == null) {
      sb.append("null");
    } else {
      sb.append(this.transferred);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("specific:");
    if (this.specific == null) {
      sb.append("null");
    } else {
      sb.append(this.specific);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("rate:");
    sb.append(this.rate);
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.storm.thrift.TException {
    // check for required fields
    if (!is_set_emitted()) {
      throw new org.apache.storm.thrift.protocol.TProtocolException("Required field 'emitted' is unset! Struct:" + toString());
    }

    if (!is_set_transferred()) {
      throw new org.apache.storm.thrift.protocol.TProtocolException("Required field 'transferred' is unset! Struct:" + toString());
    }

    if (!is_set_specific()) {
      throw new org.apache.storm.thrift.protocol.TProtocolException("Required field 'specific' is unset! Struct:" + toString());
    }

    if (!is_set_rate()) {
      throw new org.apache.storm.thrift.protocol.TProtocolException("Required field 'rate' is unset! Struct:" + toString());
    }

    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.storm.thrift.protocol.TCompactProtocol(new org.apache.storm.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.storm.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.storm.thrift.protocol.TCompactProtocol(new org.apache.storm.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.storm.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class ExecutorStatsStandardSchemeFactory implements org.apache.storm.thrift.scheme.SchemeFactory {
    public ExecutorStatsStandardScheme getScheme() {
      return new ExecutorStatsStandardScheme();
    }
  }

  private static class ExecutorStatsStandardScheme extends org.apache.storm.thrift.scheme.StandardScheme<ExecutorStats> {

    public void read(org.apache.storm.thrift.protocol.TProtocol iprot, ExecutorStats struct) throws org.apache.storm.thrift.TException {
      org.apache.storm.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.storm.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // EMITTED
            if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) {
              {
                org.apache.storm.thrift.protocol.TMap _map320 = iprot.readMapBegin();
                struct.emitted = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>(2*_map320.size);
                @org.apache.storm.thrift.annotation.Nullable java.lang.String _key321;
                @org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.lang.Long> _val322;
                for (int _i323 = 0; _i323 < _map320.size; ++_i323)
                {
                  _key321 = iprot.readString();
                  {
                    org.apache.storm.thrift.protocol.TMap _map324 = iprot.readMapBegin();
                    _val322 = new java.util.HashMap<java.lang.String,java.lang.Long>(2*_map324.size);
                    @org.apache.storm.thrift.annotation.Nullable java.lang.String _key325;
                    long _val326;
                    for (int _i327 = 0; _i327 < _map324.size; ++_i327)
                    {
                      _key325 = iprot.readString();
                      _val326 = iprot.readI64();
                      _val322.put(_key325, _val326);
                    }
                    iprot.readMapEnd();
                  }
                  struct.emitted.put(_key321, _val322);
                }
                iprot.readMapEnd();
              }
              struct.set_emitted_isSet(true);
            } else {
              org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // TRANSFERRED
            if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) {
              {
                org.apache.storm.thrift.protocol.TMap _map328 = iprot.readMapBegin();
                struct.transferred = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>(2*_map328.size);
                @org.apache.storm.thrift.annotation.Nullable java.lang.String _key329;
                @org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.lang.Long> _val330;
                for (int _i331 = 0; _i331 < _map328.size; ++_i331)
                {
                  _key329 = iprot.readString();
                  {
                    org.apache.storm.thrift.protocol.TMap _map332 = iprot.readMapBegin();
                    _val330 = new java.util.HashMap<java.lang.String,java.lang.Long>(2*_map332.size);
                    @org.apache.storm.thrift.annotation.Nullable java.lang.String _key333;
                    long _val334;
                    for (int _i335 = 0; _i335 < _map332.size; ++_i335)
                    {
                      _key333 = iprot.readString();
                      _val334 = iprot.readI64();
                      _val330.put(_key333, _val334);
                    }
                    iprot.readMapEnd();
                  }
                  struct.transferred.put(_key329, _val330);
                }
                iprot.readMapEnd();
              }
              struct.set_transferred_isSet(true);
            } else {
              org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 3: // SPECIFIC
            if (schemeField.type == org.apache.storm.thrift.protocol.TType.STRUCT) {
              struct.specific = new ExecutorSpecificStats();
              struct.specific.read(iprot);
              struct.set_specific_isSet(true);
            } else {
              org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 4: // RATE
            if (schemeField.type == org.apache.storm.thrift.protocol.TType.DOUBLE) {
              struct.rate = iprot.readDouble();
              struct.set_rate_isSet(true);
            } else {
              org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.storm.thrift.protocol.TProtocol oprot, ExecutorStats struct) throws org.apache.storm.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.emitted != null) {
        oprot.writeFieldBegin(EMITTED_FIELD_DESC);
        {
          oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.MAP, struct.emitted.size()));
          for (java.util.Map.Entry<java.lang.String, java.util.Map<java.lang.String,java.lang.Long>> _iter336 : struct.emitted.entrySet())
          {
            oprot.writeString(_iter336.getKey());
            {
              oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.I64, _iter336.getValue().size()));
              for (java.util.Map.Entry<java.lang.String, java.lang.Long> _iter337 : _iter336.getValue().entrySet())
              {
                oprot.writeString(_iter337.getKey());
                oprot.writeI64(_iter337.getValue());
              }
              oprot.writeMapEnd();
            }
          }
          oprot.writeMapEnd();
        }
        oprot.writeFieldEnd();
      }
      if (struct.transferred != null) {
        oprot.writeFieldBegin(TRANSFERRED_FIELD_DESC);
        {
          oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.MAP, struct.transferred.size()));
          for (java.util.Map.Entry<java.lang.String, java.util.Map<java.lang.String,java.lang.Long>> _iter338 : struct.transferred.entrySet())
          {
            oprot.writeString(_iter338.getKey());
            {
              oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.I64, _iter338.getValue().size()));
              for (java.util.Map.Entry<java.lang.String, java.lang.Long> _iter339 : _iter338.getValue().entrySet())
              {
                oprot.writeString(_iter339.getKey());
                oprot.writeI64(_iter339.getValue());
              }
              oprot.writeMapEnd();
            }
          }
          oprot.writeMapEnd();
        }
        oprot.writeFieldEnd();
      }
      if (struct.specific != null) {
        oprot.writeFieldBegin(SPECIFIC_FIELD_DESC);
        struct.specific.write(oprot);
        oprot.writeFieldEnd();
      }
      oprot.writeFieldBegin(RATE_FIELD_DESC);
      oprot.writeDouble(struct.rate);
      oprot.writeFieldEnd();
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class ExecutorStatsTupleSchemeFactory implements org.apache.storm.thrift.scheme.SchemeFactory {
    public ExecutorStatsTupleScheme getScheme() {
      return new ExecutorStatsTupleScheme();
    }
  }

  private static class ExecutorStatsTupleScheme extends org.apache.storm.thrift.scheme.TupleScheme<ExecutorStats> {

    @Override
    public void write(org.apache.storm.thrift.protocol.TProtocol prot, ExecutorStats struct) throws org.apache.storm.thrift.TException {
      org.apache.storm.thrift.protocol.TTupleProtocol oprot = (org.apache.storm.thrift.protocol.TTupleProtocol) prot;
      {
        oprot.writeI32(struct.emitted.size());
        for (java.util.Map.Entry<java.lang.String, java.util.Map<java.lang.String,java.lang.Long>> _iter340 : struct.emitted.entrySet())
        {
          oprot.writeString(_iter340.getKey());
          {
            oprot.writeI32(_iter340.getValue().size());
            for (java.util.Map.Entry<java.lang.String, java.lang.Long> _iter341 : _iter340.getValue().entrySet())
            {
              oprot.writeString(_iter341.getKey());
              oprot.writeI64(_iter341.getValue());
            }
          }
        }
      }
      {
        oprot.writeI32(struct.transferred.size());
        for (java.util.Map.Entry<java.lang.String, java.util.Map<java.lang.String,java.lang.Long>> _iter342 : struct.transferred.entrySet())
        {
          oprot.writeString(_iter342.getKey());
          {
            oprot.writeI32(_iter342.getValue().size());
            for (java.util.Map.Entry<java.lang.String, java.lang.Long> _iter343 : _iter342.getValue().entrySet())
            {
              oprot.writeString(_iter343.getKey());
              oprot.writeI64(_iter343.getValue());
            }
          }
        }
      }
      struct.specific.write(oprot);
      oprot.writeDouble(struct.rate);
    }

    @Override
    public void read(org.apache.storm.thrift.protocol.TProtocol prot, ExecutorStats struct) throws org.apache.storm.thrift.TException {
      org.apache.storm.thrift.protocol.TTupleProtocol iprot = (org.apache.storm.thrift.protocol.TTupleProtocol) prot;
      {
        org.apache.storm.thrift.protocol.TMap _map344 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.MAP, iprot.readI32());
        struct.emitted = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>(2*_map344.size);
        @org.apache.storm.thrift.annotation.Nullable java.lang.String _key345;
        @org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.lang.Long> _val346;
        for (int _i347 = 0; _i347 < _map344.size; ++_i347)
        {
          _key345 = iprot.readString();
          {
            org.apache.storm.thrift.protocol.TMap _map348 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.I64, iprot.readI32());
            _val346 = new java.util.HashMap<java.lang.String,java.lang.Long>(2*_map348.size);
            @org.apache.storm.thrift.annotation.Nullable java.lang.String _key349;
            long _val350;
            for (int _i351 = 0; _i351 < _map348.size; ++_i351)
            {
              _key349 = iprot.readString();
              _val350 = iprot.readI64();
              _val346.put(_key349, _val350);
            }
          }
          struct.emitted.put(_key345, _val346);
        }
      }
      struct.set_emitted_isSet(true);
      {
        org.apache.storm.thrift.protocol.TMap _map352 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.MAP, iprot.readI32());
        struct.transferred = new java.util.HashMap<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>(2*_map352.size);
        @org.apache.storm.thrift.annotation.Nullable java.lang.String _key353;
        @org.apache.storm.thrift.annotation.Nullable java.util.Map<java.lang.String,java.lang.Long> _val354;
        for (int _i355 = 0; _i355 < _map352.size; ++_i355)
        {
          _key353 = iprot.readString();
          {
            org.apache.storm.thrift.protocol.TMap _map356 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.I64, iprot.readI32());
            _val354 = new java.util.HashMap<java.lang.String,java.lang.Long>(2*_map356.size);
            @org.apache.storm.thrift.annotation.Nullable java.lang.String _key357;
            long _val358;
            for (int _i359 = 0; _i359 < _map356.size; ++_i359)
            {
              _key357 = iprot.readString();
              _val358 = iprot.readI64();
              _val354.put(_key357, _val358);
            }
          }
          struct.transferred.put(_key353, _val354);
        }
      }
      struct.set_transferred_isSet(true);
      struct.specific = new ExecutorSpecificStats();
      struct.specific.read(iprot);
      struct.set_specific_isSet(true);
      struct.rate = iprot.readDouble();
      struct.set_rate_isSet(true);
    }
  }

  private static <S extends org.apache.storm.thrift.scheme.IScheme> S scheme(org.apache.storm.thrift.protocol.TProtocol proto) {
    return (org.apache.storm.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
  }
}


text:
# If it's not working and you want to know why, set DEBUG to 1 and check the
# logfile.
DEBUG=0
DEBUGLOG="$HOME/.ssh/screen_ssh.log"

set -e
set -u

dbg ()
{
if [ "$DEBUG" -gt 0 ]; then
echo "$(date) :: $*" >> $DEBUGLOG
fi
}

dbg "$0 $*"

# We only care if we are in a terminal
tty -s

# We also only care if we are in screen, which we infer by $TERM starting
# with "screen"
if [ "${TERM:0:6}" != "screen" ]; then
dbg "Not a screen session, ${TERM:0:5} != 'screen'"
exit
fi

# We must be given three arguments - our parent process, a hostname
# (which may be "%n" if we are being called by an older SSH) and a username
if [ $# != "3" ]; then
dbg "Not given enough arguments (must have PPID, hostname and username)"
exit
fi

# We don't want to do anything if BatchMode is on, since it means
# we're not an interactive shell
set +e
grep -a -i "Batchmode yes" /proc/$1/cmdline >/dev/null 2&>1
RETVAL=$?
if [ "$RETVAL" -eq "0" ]; then
dbg "SSH is being used in Batch mode, exiting because this is probably an auto-complete or similar"
exit
fi
set -e

# Use the safer %h and %r variables. %n has a buggy implementation in some versions of OpenSSH
HOST="$2"
USER="$3"

echo $USER"@"$HOST | awk '{ printf ("\033k%s\033\\", $NF) }'

dbg "Done."


text:
{% load i18n %}
{% extends "html/projects/page.html" %}

{% block title %}{{ milestone|htsafe }} | {% trans %}Milestone{% endtrans %} | {% trans %}Project Management{% endtrans %}{% endblock %}

{% block module_title %}{{ milestone }}{% endblock %}

{% block module_subtitle %}{% trans %}Milestone{% endtrans %}{% endblock %}

{% block module_topmenu %}
{% trans %}New Task{% endtrans %}
{% trans %}View{% endtrans %}
{% if user.get_profile().has_permission(milestone, mode='w') %}
{% trans %}Edit{% endtrans %}
{% trans %}Delete{% endtrans %}
{% endif %}
{% endblock %}

{% block module_content %}

<form action="" method="post" class="content-form">
{% csrf_token %}

        {{ htform(form).as_ul()|htsafe }}

        <input type="submit" name="save" value="{% trans %}Save{% endtrans %}" />
		<input type="submit" name="cancel" value="{% trans %}Cancel{% endtrans %}" class="cancel" />

</form>
{% endblock %}