text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_PRIMITIVES_TRANSACTION_H
#define BITCOIN_PRIMITIVES_TRANSACTION_H

#include "amount.h"
#include "script/script.h"
#include "serialize.h"
#include "uint256.h"

static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
static const int SERIALIZE_BITCOIN_BLOCK_OR_TX = 0x20000000;

static const int WITNESS_SCALE_FACTOR = 4;

static const CFeeRate withdrawLockTxFee = CFeeRate(5460);

/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
    uint256 hash;
    uint32_t n;

    COutPoint() { SetNull(); }
    COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        READWRITE(hash);
        READWRITE(n);
    }

    void SetNull() { hash.SetNull(); n = (uint32_t) -1; }
    bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }

    friend bool operator<(const COutPoint& a, const COutPoint& b)
    {
        int cmp = a.hash.Compare(b.hash);
        return cmp < 0 || (cmp == 0 && a.n < b.n);
    }

    friend bool operator==(const COutPoint& a, const COutPoint& b)
    {
        return (a.hash == b.hash && a.n == b.n);
    }

    friend bool operator!=(const COutPoint& a, const COutPoint& b)
    {
        return !(a == b);
    }

    std::string ToString() const;
};

/** An input of a transaction.  It contains the location of the previous
 * transaction's output that it claims and a signature that matches the
 * output's public key.
 */
class CTxIn
{
public:
    COutPoint prevout;
    CScript scriptSig;
    uint32_t nSequence;

    /* Setting nSequence to this value for every input in a transaction
     * disables nLockTime. */
    static const uint32_t SEQUENCE_FINAL = 0xffffffff;

    /* Below flags apply in the context of BIP 68*/
    /* If this flag set, CTxIn::nSequence is NOT interpreted as a
     * relative lock-time. */
    static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);

    /* If CTxIn::nSequence encodes a relative lock-time and this flag
     * is set, the relative lock-time has units of 512 seconds,
     * otherwise it specifies blocks with a granularity of 1. */
    static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);

    /* If CTxIn::nSequence encodes a relative lock-time, this mask is
     * applied to extract that lock-time from the sequence field. */
    static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;

    /* In order to use the same number of bits to encode roughly the
     * same wall-clock duration, and because blocks are naturally
     * limited to occur every 600s on average, the minimum granularity
     * for time-based relative lock-time is fixed at 512 seconds.
     * Converting from CTxIn::nSequence to seconds is performed by
     * multiplying by 512 = 2^9, or equivalently shifting up by
     * 9 bits. */
    static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;

    CTxIn()
    {
        nSequence = SEQUENCE_FINAL;
    }

    explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
    CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        READWRITE(prevout);
        READWRITE(*(CScriptBase*)(&scriptSig));
        READWRITE(nSequence);
    }

    friend bool operator==(const CTxIn& a, const CTxIn& b)
    {
        return (a.prevout   == b.prevout &&
                a.scriptSig == b.scriptSig &&
                a.nSequence == b.nSequence);
    }

    friend bool operator!=(const CTxIn& a, const CTxIn& b)
    {
        return !(a == b);
    }

    std::string ToString() const;
};

class CTxOutValue
{
public:
    static const size_t nCommitmentSize = 33;

    std::vector<unsigned char> vchCommitment;
    std::vector<unsigned char> vchRangeproof;
    std::vector<unsigned char> vchNonceCommitment;

    CTxOutValue();
    CTxOutValue(CAmount);
    CTxOutValue(const std::vector<unsigned char>& vchValueCommitment, const std::vector<unsigned char>& vchRangeproofIn);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        if ((nVersion & SERIALIZE_BITCOIN_BLOCK_OR_TX) || IsInBitcoinTransaction()) {
            CAmount nAmount = 0;
            if (!ser_action.ForRead())
                nAmount = GetAmount();
            READWRITE(nAmount);
            if (ser_action.ForRead())
                SetToBitcoinAmount(nAmount);
        } else {
            // We only serialize the value commitment here.
            // The ECDH key and range proof are serialized through CTxOutWitnessSerializer.
            READWRITE(REF(CFlatData(&vchCommitment[0], &vchCommitment[nCommitmentSize])));
        }
    }

    bool IsValid() const;
    bool IsNull() const;
    bool IsAmount() const; // True for both native Amounts and "Bitcoin amounts"

    CAmount GetAmount() const;

    friend bool operator==(const CTxOutValue& a, const CTxOutValue& b);
    friend bool operator!=(const CTxOutValue& a, const CTxOutValue& b);

private: // "Bitcoin amounts" can only be set by deserializing with SERIALIZE_BITCOIN_BLOCK_OR_TX
    void SetToBitcoinAmount(const CAmount nAmount);
    bool IsInBitcoinTransaction() const;
    void SetToAmount(const CAmount nAmount);
};

/** An output of a transaction.  It contains the public key that the next input
 * must be able to sign with to claim it.
 */
class CTxOut
{
public:
    CTxOutValue nValue;
    CScript scriptPubKey;

    CTxOut()
    {
        SetNull();
    }

    CTxOut(const CTxOutValue& nValueIn, CScript scriptPubKeyIn);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        READWRITE(nValue);
        READWRITE(*(CScriptBase*)(&scriptPubKey));
    }

    void SetNull()
    {
        nValue = CTxOutValue();
        scriptPubKey.clear();
    }

    bool IsNull() const
    {
        return nValue.IsNull() && scriptPubKey.empty();
    }

    CAmount GetDustThreshold(const CFeeRate &minRelayTxFee) const
    {
        // "Dust" is defined in terms of CTransaction::minRelayTxFee,
        // which has units satoshis-per-kilobyte.
        // If you'd pay more than 1/3 in fees
        // to spend something, then we consider it dust.
        // A typical spendable non-segwit txout is 34 bytes big, and will
        // need a CTxIn of at least 148 bytes to spend:
        // so dust is a spendable txout less than
        // 546*minRelayTxFee/1000 (in satoshis).
        // A typical spendable segwit txout is 31 bytes big, and will
        // need a CTxIn of at least 67 bytes to spend:
        // so dust is a spendable txout less than
        // 294*minRelayTxFee/1000 (in satoshis).
        if (scriptPubKey.IsUnspendable())
            return 0;

        size_t nSize = GetSerializeSize(SER_DISK, 0);
        int witnessversion = 0;
        std::vector<unsigned char> witnessprogram;

        if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
            // sum the sizes of the parts of a transaction input
            // with 75% segwit discount applied to the script size.
            nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
        } else {
            nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
        }

        return 3 * minRelayTxFee.GetFee(nSize);
    }

    bool IsDust(const CFeeRate &minRelayTxFee) const
    {
        if (!nValue.IsAmount())
            return false; // FIXME
        //Withdrawlocks are evaluated at a higher, static feerate
        //to ensure peg-outs are IsStandard on mainchain
        if (scriptPubKey.IsWithdrawLock() && nValue.GetAmount() < GetDustThreshold(withdrawLockTxFee))
            return true;
        return (nValue.GetAmount() < GetDustThreshold(minRelayTxFee));
    }

    friend bool operator==(const CTxOut& a, const CTxOut& b)
    {
        return (a.nValue       == b.nValue &&
                a.scriptPubKey == b.scriptPubKey);
    }

    friend bool operator!=(const CTxOut& a, const CTxOut& b)
    {
        return !(a == b);
    }

    std::string ToString() const;
};

class CTxOutWitnessSerializer
{
    CTxOut& ref;

public:
    CTxOutWitnessSerializer(CTxOut& ref_) : ref(ref_) {}

    ADD_SERIALIZE_METHODS;

    bool IsNull() const {
        return ref.nValue.vchRangeproof.empty() && ref.nValue.vchNonceCommitment.empty();
    }

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        if (!(nVersion & SERIALIZE_BITCOIN_BLOCK_OR_TX)) {
            READWRITE(ref.nValue.vchRangeproof);
            READWRITE(ref.nValue.vchNonceCommitment);
        }
    }

    void SetNull() {
        std::vector<unsigned char>().swap(ref.nValue.vchRangeproof);
        std::vector<unsigned char>().swap(ref.nValue.vchNonceCommitment);
    }
};

class CTxInWitness
{
public:
    CScriptWitness scriptWitness;

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        READWRITE(scriptWitness.stack);
    }

    bool IsNull() const { return scriptWitness.IsNull(); }

    CTxInWitness() { }
};

class CTxWitness
{
public:
    /** In case vtxinwit is missing, all entries are treated as if they were empty CTxInWitnesses */
    std::vector<CTxInWitness> vtxinwit;

    ADD_SERIALIZE_METHODS;

    bool IsEmpty() const { return vtxinwit.empty(); }

    bool IsNull() const
    {
        for (size_t n = 0; n < vtxinwit.size(); n++) {
            if (!vtxinwit[n].IsNull()) {
                return false;
            }
        }
        return true;
    }

    void SetNull()
    {
        vtxinwit.clear();
    }

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        for (size_t n = 0; n < vtxinwit.size(); n++) {
            READWRITE(vtxinwit[n]);
        }
        if (IsNull()) {
            /* It's illegal to encode a witness when all vtxinwit entries are empty. */
            throw std::ios_base::failure("Superfluous witness record");
        }
    }
};

struct CMutableTransaction;

/**
 * Basic transaction serialization format:
 * - int32_t nVersion
 * - int32_t nTxFee
 * - std::vector<CTxIn> vin
 * - std::vector<CTxOut> vout
 * - uint32_t nLockTime
 *
 * Extended transaction serialization format:
 * - int32_t nVersion
 * - int32_t nTxFee
 * - unsigned char dummy = 0x00
 * - unsigned char flags (!= 0)
 * - std::vector<CTxIn> vin
 * - std::vector<CTxOut> vout
 * - if (flags & 1):
 *   - CTxWitness wit;
 * - if (flags & 2):
 *   - CTxOutWitness witout;
 * - uint32_t nLockTime
 */
static const CAmount TX_FEE_BITCOIN_TX_FLAG = -42;
template<typename Stream, typename Operation, typename TxType>
inline void SerializeTransaction(TxType& tx, Stream& s, Operation ser_action, int nType, int nVersion) {
    const bool fAllowWitness = !(nVersion & SERIALIZE_TRANSACTION_NO_WITNESS);
    const bool fIsBitcoinTx = (nVersion & SERIALIZE_BITCOIN_BLOCK_OR_TX);
    READWRITE(*const_cast<int32_t*>(&tx.nVersion));
    if ((ser_action.ForRead() || (!ser_action.ForRead() && tx.nTxFee != TX_FEE_BITCOIN_TX_FLAG)) && !fIsBitcoinTx)
        READWRITE(*const_cast<CAmount*>(&tx.nTxFee));
    else if (ser_action.ForRead())
        const_cast<CAmount&>(tx.nTxFee) = TX_FEE_BITCOIN_TX_FLAG;
    unsigned char flags = 0;
    if (ser_action.ForRead()) {
        const_cast<std::vector<CTxIn>*>(&tx.vin)->clear();
        const_cast<std::vector<CTxOut>*>(&tx.vout)->clear();
        const_cast<CTxWitness*>(&tx.wit)->SetNull();
        /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
        READWRITE(*const_cast<std::vector<CTxIn>*>(&tx.vin));
        if (tx.vin.size() == 0 && !(nVersion & SERIALIZE_TRANSACTION_NO_WITNESS)) {
            /* We read a dummy or an empty vin. */
            READWRITE(flags);
            if (flags != 0) {
                READWRITE(*const_cast<std::vector<CTxIn>*>(&tx.vin));
                READWRITE(*const_cast<std::vector<CTxOut>*>(&tx.vout));
            }
        } else {
            /* We read a non-empty vin. Assume a normal vout follows. */
            READWRITE(*const_cast<std::vector<CTxOut>*>(&tx.vout));
        }
        if ((flags & 1) && !(nVersion & SERIALIZE_TRANSACTION_NO_WITNESS)) {
            /* The witness flag is present, and we support witnesses. */
            flags ^= 1;
            const_cast<CTxWitness*>(&tx.wit)->vtxinwit.resize(tx.vin.size());
            READWRITE(tx.wit);
        }
        if ((flags & 2) && fAllowWitness && !fIsBitcoinTx) {
            /* The witness output flag is present, and we support witnesses. */
            flags ^= 2;
            bool fHadOutputWitness = false;
            for (size_t i = 0; i < tx.vout.size(); i++) {
                CTxOutWitnessSerializer witser(REF(tx.vout[i]));
                READWRITE(witser);
                if (!witser.IsNull()) {
                    fHadOutputWitness = true;
                }
            }
            if (!fHadOutputWitness) {
                throw std::ios_base::failure("Superfluous output witness record");
            }
        }
        if (flags) {
            /* Unknown flag in the serialization */
            throw std::ios_base::failure("Unknown transaction optional data");
        }
    } else {
        // Consistency check
        assert(tx.wit.vtxinwit.size() <= tx.vin.size());
        if (!(nVersion & SERIALIZE_TRANSACTION_NO_WITNESS)) {
            /* Check whether witnesses need to be serialized. */
            if (!tx.wit.IsNull()) {
                flags |= 1;
            }
            if (!fIsBitcoinTx) {
                for (size_t i = 0; i < tx.vout.size(); i++) {
                    if (!CTxOutWitnessSerializer(*const_cast<CTxOut*>(&tx.vout[i])).IsNull()) {
                        flags |= 2;
                        break;
                    }
                }
            }
        }
        if (flags) {
            /* Use extended format in case witnesses are to be serialized. */
            std::vector<CTxIn> vinDummy;
            READWRITE(vinDummy);
            READWRITE(flags);
        }
        READWRITE(*const_cast<std::vector<CTxIn>*>(&tx.vin));
        READWRITE(*const_cast<std::vector<CTxOut>*>(&tx.vout));
        if (flags & 1) {
            const_cast<CTxWitness*>(&tx.wit)->vtxinwit.resize(tx.vin.size());
            READWRITE(tx.wit);
        }
        if (flags & 2) {
            for (size_t i = 0; i < tx.vout.size(); i++) {
                CTxOutWitnessSerializer witser(*const_cast<CTxOut*>(&tx.vout[i]));
                READWRITE(witser);
            }
        }
    }
    READWRITE(*const_cast<uint32_t*>(&tx.nLockTime));
}

/** The basic transaction that is broadcasted on the network and contained in
 * blocks.  A transaction can contain multiple inputs and outputs.
 */
class CTransaction
{
private:
    /** Memory only. */
    const uint256 hash;

public:
    // Default transaction version.
    static const int32_t CURRENT_VERSION=1;

    // Changing the default transaction version requires a two step process: first
    // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date
    // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and
    // MAX_STANDARD_VERSION will be equal.
    static const int32_t MAX_STANDARD_VERSION=2;

    // The local variables are made const to prevent unintended modification
    // without updating the cached hash value. However, CTransaction is not
    // actually immutable; deserialization and assignment are implemented,
    // and bypass the constness. This is safe, as they update the entire
    // structure, including the hash.
    const int32_t nVersion;
    const CAmount nTxFee;
    const std::vector<CTxIn> vin;
    const std::vector<CTxOut> vout;
    CTxWitness wit; // Not const: can change without invalidating the txid cache
    const uint32_t nLockTime;

    /** Construct a CTransaction that qualifies as IsNull() */
    CTransaction();

    /** Convert a CMutableTransaction into a CTransaction. */
    CTransaction(const CMutableTransaction &tx);

    CTransaction& operator=(const CTransaction& tx);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        SerializeTransaction(*this, s, ser_action, nType, nVersion);
        if (ser_action.ForRead()) {
            UpdateHash();
        }
    }

    bool IsNull() const {
        return vin.empty() && vout.empty();
    }

    const uint256& GetHash() const {
        return hash;
    }

    // Compute a hash that includes both transaction and witness data
    uint256 GetWitnessHash() const;

    // Compute priority, given priority of inputs and (optionally) tx size
    double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;

    // Compute modified tx size for priority calculation (optionally given tx size)
    unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const;

    bool IsCoinBase() const
    {
        return (vin.size() == 1 && vin[0].prevout.IsNull());
    }

    friend bool operator==(const CTransaction& a, const CTransaction& b)
    {
        return a.hash == b.hash;
    }

    friend bool operator!=(const CTransaction& a, const CTransaction& b)
    {
        return a.hash != b.hash;
    }

    std::string ToString() const;

    void UpdateHash() const;
};

/** A mutable version of CTransaction. */
struct CMutableTransaction
{
    int32_t nVersion;
    CAmount nTxFee;
    std::vector<CTxIn> vin;
    std::vector<CTxOut> vout;
    CTxWitness wit;
    uint32_t nLockTime;

    CMutableTransaction();
    CMutableTransaction(const CTransaction& tx);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        SerializeTransaction(*this, s, ser_action, nType, nVersion);
    }

    /** Compute the hash of this CMutableTransaction. This is computed on the
     * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
     */
    uint256 GetHash() const;
};

/** Compute the weight of a transaction, as defined by BIP 141 */
int64_t GetTransactionWeight(const CTransaction &tx);

#endif // BITCOIN_PRIMITIVES_TRANSACTION_H


text:
Custom Arcade

    This is about the arcade software on my github page.

    The idea was to have one consolidated place to play all emulated games (ROMS).  I own and collect all sorts of real game cartridges, but sometimes it is
    just easier to play it emulated.  I wanted to have one custom interface for all emulated games regardless if it was for Nintedo, Sega, or anything else.

    More information coming soon, this is still under construction.

redpajama_set_name: RedPajamaGithub


text:
ecm-extender-api
================

Documentation: http://www.everit.org/ecm/index.html#ecm-extender-api


text:
using System;
using System.Linq;
using System.Reflection;
using SIS.HTTP.Enums;
using SIS.HTTP.Responses;
using SIS.MvcFramework.Attributes;
using SIS.MvcFramework.Attributes.Action;
using SIS.MvcFramework.Attributes.Security;
using SIS.MvcFramework.Result;
using SIS.WebServer;
using SIS.WebServer.Routing;

namespace SIS.MvcFramework
{
    public static class WebHost
    {
        public static void Start(IMvcApplication application)
        {
            IServerRoutingTable serverRoutingTable = new ServerRoutingTable();
            AutoRegisterRoutes(application, serverRoutingTable);
            application.ConfigureServices();
            application.Configure(serverRoutingTable);
            var server = new Server(8000, serverRoutingTable);
            server.Run();
        }

        private static void AutoRegisterRoutes(
            IMvcApplication application, IServerRoutingTable serverRoutingTable)
        {
            var controllers = application.GetType().Assembly.GetTypes()
                .Where(type => type.IsClass && !type.IsAbstract
                    && typeof(Controller).IsAssignableFrom(type));
            // TODO: RemoveToString from InfoController
            foreach (var controller in controllers)
            {
                var actions = controller
                    .GetMethods(BindingFlags.DeclaredOnly
                    | BindingFlags.Public
                    | BindingFlags.Instance)
                    .Where(x => !x.IsSpecialName && x.DeclaringType == controller)
                    .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute)));

                foreach (var action in actions)
                {
                    var path = $"/{controller.Name.Replace("Controller", string.Empty)}/{action.Name}";
                    var attribute = action.GetCustomAttributes().Where(
                        x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))).LastOrDefault() as BaseHttpAttribute;
                    var httpMethod = HttpRequestMethod.Get;
                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controller.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path, request =>
                    {
                        // request => new UsersController().Login(request)
                        var controllerInstance = Activator.CreateInstance(controller);
                        ((Controller)controllerInstance).Request = request;

                        // Security Authorization - TODO: Refactor this
                        var controllerPrincipal = ((Controller)controllerInstance).User;
                        var authorizeAttribute = action.GetCustomAttributes()
                            .LastOrDefault(a => a.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute;

                        if (authorizeAttribute != null && !authorizeAttribute.IsInAuthority(controllerPrincipal))
                        {
                            // TODO: Redirect to configured URL
                            return new HttpResponse(HttpResponseStatusCode.Forbidden);
                        }

                        var response = action.Invoke(controllerInstance, new object[0]) as ActionResult;
                        return response;
                    });

                    Console.WriteLine(httpMethod + " " + path);
                }
            }
            // Reflection
            // Assembly
            // typeof(Server).GetMethods()
            // sb.GetType().GetMethods();
            // Activator.CreateInstance(typeof(Server))
            var sb = DateTime.UtcNow;

        }
    }
}


text:
export default function clearUndefinedProperties(obj) {
  if (!obj) {
    return obj;
  }

  const newObj = {};

  Object.keys(obj).forEach((propertyName) => {
    const value = obj[propertyName];
    if (value !== undefined) {
      newObj[propertyName] = value;
    }
  });

  return newObj;
}


text:
<!doctype html>

Get Random User

		<form ng-submit="vm.login(vm.username, vm.password)">
			Username: <input type="text" ng-model="vm.username" />
			Password: <input type="password" ng-model="vm.password" />
			<button type="submit">Login</button>
		</form>

Welcome {{vm.user.username}}

		<button ng-click="vm.logout()">Logout</button>

		<button ng-click="vm.getRandomUser()">Get User</button>


text:
ZeroDivisionError
SyntaxError
IndexError
KeyError
IOError
AttributeError
ValueError
SystemExit
KeyboardInterrupt
def test():
    try:
        print foo
    except NameError as e:
        pass

if __name__ == '__main__':
    test()


text:
package org.graphwalker.core.model;

import org.graphwalker.core.common.Objects;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Nils Olsson
 */
public class Classification extends CachedBuilder<Classification, Classification.RuntimeClassification> {

  private final List<Classification> classifications = new ArrayList<>();

  public Classification addClassification(Classification classification) {
    this.classifications.add(classification);
    invalidateCache();
    return this;
  }

  public List<Classification> getClassifications() {
    return classifications;
  }

  @Override
  protected RuntimeClassification createCache() {
    return new RuntimeClassification(this);
  }

  public static class RuntimeClassification extends RuntimeBase {

    private final List<RuntimeClassification> classifications;

    private RuntimeClassification(Classification classification) {
      super(classification.getId(), classification.getName());
      this.classifications = BuilderFactory.build(classification.getClassifications());
    }

    public List<RuntimeClassification> getClassifications() {
      return classifications;
    }

    @Override
    public void accept(ElementVisitor visitor) {
      visitor.visit(this);
    }

    @Override
    public boolean equals(Object o) {
      if (!super.equals(o)) {
        return false;
      }
      RuntimeClassification that = (RuntimeClassification) o;
      return Objects.equals(classifications, that.classifications);
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), classifications);
    }

    @Override
    public String toString() {
      return getName();
    }
  }
}


text:
package com.xym.factory.model.api.account;

import com.xym.factory.model.db.User;

/**
 * Created by xym on 2017/8/20.
 */

public class AccountRspModel {
    // 用户基本信息
    private User user;
    // 当前登录的账号
    private String account;
    // 当前登录成功后获取的Token,
    // 可以通过Token获取用户的所有信息
    private String token;
    // 标示是否已经绑定到了设备PushId
    private boolean isBind;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public boolean isBind() {
        return isBind;
    }

    public void setBind(boolean bind) {
        isBind = bind;
    }

}


text:
begin
  require 'puppet_x/voxpupuli/corosync/provider/pcs'
rescue LoadError
  require 'pathname' # WORKAROUND #14073, #7788 and SERVER-973
  corosync = Puppet::Module.find('corosync')
  raise(LoadError, "Unable to find corosync module in modulepath #{Puppet[:basemodulepath] || Puppet[:modulepath]}") unless corosync
  require File.join corosync.path, 'lib/puppet_x/voxpupuli/corosync/provider/pcs'
end

Puppet::Type.type(:cs_order).provide(:pcs, parent: PuppetX::Voxpupuli::Corosync::Provider::Pcs) do
  desc 'Specific provider for a rather specific type since I currently have no plan to
        abstract corosync/pacemaker vs. keepalived. This provider will check the state
        of current primitive start orders on the system; add, delete, or adjust various
        aspects.'

  defaultfor operatingsystem: [:fedora, :centos, :redhat]

  has_feature :kindness

  # Path to the pcs binary for interacting with the cluster configuration.
  commands pcs: 'pcs'

  mk_resource_methods

  def self.instances
    block_until_ready

    instances = []

    cmd = [command(:pcs), 'cluster', 'cib']
    raw, = run_command_in_cib(cmd)
    doc = REXML::Document.new(raw)

    constraints = doc.root.elements['configuration'].elements['constraints']
    unless constraints.nil?
      constraints.each_element('rsc_order') do |e|
        items = e.attributes

        first = if items['first-action']
                  "#{items['first']}:#{items['first-action']}"
                else
                  items['first']
                end

        second = if items['then-action']
                   "#{items['then']}:#{items['then-action']}"
                 else
                   items['then']
                 end
        kind = if items['kind']
                 items['kind']
               else
                 'Mandatory'
               end

        symmetrical = if items['symmetrical']
                        (items['symmetrical'] == 'true')
                      else
                        # Default: symmetrical is true unless explicitly defined.
                        true
                      end

        order_instance = {
          name:        items['id'],
          ensure:      :present,
          first:       first,
          second:      second,
          kind:        kind,
          symmetrical: symmetrical,
          provider:    name,
          new:         false
        }
        instances << new(order_instance)
      end
    end
    instances
  end

  # Create just adds our resource to the property_hash and flush will take care
  # of actually doing the work.
  def create
    @property_hash = {
      name:        @resource[:name],
      ensure:      :present,
      first:       @resource[:first],
      second:      @resource[:second],
      kind:        @resource[:kind],
      symmetrical: @resource[:symmetrical],
      new:         true
    }
  end

  # Unlike create we actually immediately delete the item.
  def destroy
    debug('Removing order directive')
    cmd = [command(:pcs), 'constraint', 'remove', @resource[:name]]
    self.class.run_command_in_cib(cmd, @resource[:cib])
    @property_hash.clear
  end

  # Flush is triggered on anything that has been detected as being
  # modified in the property_hash.  It generates a temporary file with
  # the updates that need to be made.  The temporary file is then used
  # as stdin for the pcs command.
  def flush
    return if @property_hash.empty?

    if @property_hash[:new] == false
      debug('Removing order directive')
      cmd = [command(:pcs), 'constraint', 'remove', @resource[:name]]
      self.class.run_command_in_cib(cmd, @resource[:cib])
    end

    cmd = [command(:pcs), 'constraint', 'order']
    items = @property_hash[:first].split(':')
    cmd << items[1]
    cmd << items[0]
    cmd << 'then'
    items = @property_hash[:second].split(':')
    cmd << items[1]
    cmd << items[0]
    cmd << "kind=#{@property_hash[:kind]}"
    cmd << "id=#{@property_hash[:name]}"
    cmd << "symmetrical=#{@property_hash[:symmetrical]}"
    self.class.run_command_in_cib(cmd, @resource[:cib])
  end
end


text:
package org.dependencytrack.model;

import alpine.validation.RegexSequence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Index;
import javax.jdo.annotations.Order;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Unique;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Collection;
import java.util.UUID;

/**
 * Model class for Common Platform Enumeration (CPE).
 *
 * @author Steve Springett
 * @since 3.6.0
 */
@PersistenceCapable
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Cpe implements ICpe, Serializable {

    private static final long serialVersionUID = 1598287997098587015L;

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.NATIVE)
    @JsonIgnore
    private long id;

    @Persistent
    @Column(name = "CPE22", jdbcType = "VARCHAR")
    @Index(name = "CPE_CPE22_IDX")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The cpe22 may only contain printable characters")
    private String cpe22;

    @Persistent
    @Column(name = "CPE23", jdbcType = "VARCHAR", allowsNull = "false")
    @Index(name = "CPE_CPE23_IDX", unique = "true")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The cpe23 may only contain printable characters")
    private String cpe23;

    @Persistent
    @Column(name = "TITLE", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The title may only contain printable characters")
    private String title;

    @Persistent
    @Column(name = "PART", jdbcType = "VARCHAR")
    @Size(max = 1)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The part may only contain printable characters")
    private String part;

    @Persistent
    @Column(name = "VENDOR", jdbcType = "VARCHAR")
    @Index(name = "CPE_VENDOR_IDX")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The vendor may only contain printable characters")
    private String vendor;

    @Persistent
    @Column(name = "PRODUCT", jdbcType = "VARCHAR")
    @Index(name = "CPE_PRODUCT_IDX")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The product may only contain printable characters")
    private String product;

    @Persistent
    @Column(name = "VERSION", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The version may only contain printable characters")
    private String version;

    @Persistent
    @Column(name = "UPDATE", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The update may only contain printable characters")
    private String update;

    @Persistent
    @Column(name = "EDITION", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The edition may only contain printable characters")
    private String edition;

    @Persistent
    @Column(name = "LANGUAGE", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The language may only contain printable characters")
    private String language;

    @Persistent
    @Column(name = "SWEDITION", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The swEdition may only contain printable characters")
    private String swEdition;

    @Persistent
    @Column(name = "TARGETSW", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The targetSw may only contain printable characters")
    private String targetSw;

    @Persistent
    @Column(name = "TARGETHW", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The targetHw may only contain printable characters")
    private String targetHw;

    @Persistent
    @Column(name = "OTHER", jdbcType = "VARCHAR")
    @Size(max = 255)
    @Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The other may only contain printable characters")
    private String other;

    @Persistent(mappedBy = "cpe")
    @Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
    private Collection<CpeReference> references;

    @Persistent(defaultFetchGroup = "true", customValueStrategy = "uuid")
    @Unique(name = "CPE_UUID_IDX")
    @Column(name = "UUID", jdbcType = "VARCHAR", length = 36, allowsNull = "false")
    @NotNull
    private UUID uuid;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCpe22() {
        return cpe22;
    }

    public void setCpe22(String cpe22) {
        this.cpe22 = cpe22;
    }

    public String getCpe23() {
        return cpe23;
    }

    public void setCpe23(String cpe23) {
        this.cpe23 = cpe23;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPart() {
        return part;
    }

    public void setPart(String part) {
        this.part = part;
    }

    public String getVendor() {
        return vendor;
    }

    public void setVendor(String vendor) {
        this.vendor = vendor;
    }

    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getUpdate() {
        return update;
    }

    public void setUpdate(String update) {
        this.update = update;
    }

    public String getEdition() {
        return edition;
    }

    public void setEdition(String edition) {
        this.edition = edition;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getSwEdition() {
        return swEdition;
    }

    public void setSwEdition(String swEdition) {
        this.swEdition = swEdition;
    }

    public String getTargetSw() {
        return targetSw;
    }

    public void setTargetSw(String targetSw) {
        this.targetSw = targetSw;
    }

    public String getTargetHw() {
        return targetHw;
    }

    public void setTargetHw(String targetHw) {
        this.targetHw = targetHw;
    }

    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }

    public Collection<CpeReference> getReferences() {
        return references;
    }

    public void setReferences(Collection<CpeReference> references) {
        this.references = references;
    }

    public UUID getUuid() {
        return uuid;
    }

    public void setUuid(UUID uuid) {
        this.uuid = uuid;
    }
}


text:
package com.grumoon.pulllistview.sample;

import android.os.Bundle;
import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class AppMain extends ActionBarActivity {

    private Toolbar toolbar;
    private DrawerLayout dlMain;
    private ActionBarDrawerToggle drawerToggle;

    private Button btnAutoGetMore;
    private Button btnClickGetMore;
    private Button btnAddExtraHeader1;
    private Button btnAddExtraHeader2;

    private Fragment autoGetMoreFragment;
    private Fragment clickGetMoreFragment;
    private Fragment addExtraHeaderFragment1;
    private Fragment addExtraHeaderFragment2;

    private FragmentManager fm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_main);
        initView();
    }

    private void initView() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        dlMain = (DrawerLayout) findViewById(R.id.dl_main);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        drawerToggle = new ActionBarDrawerToggle(this, dlMain, toolbar, 0, 0);
        drawerToggle.syncState();
        dlMain.setDrawerListener(drawerToggle);

        btnAutoGetMore = (Button) findViewById(R.id.btn_auto_get_more);
        btnClickGetMore = (Button) findViewById(R.id.btn_click_get_more);
        btnAddExtraHeader1 = (Button) findViewById(R.id.btn_add_extra_header1);
        btnAddExtraHeader2 = (Button) findViewById(R.id.btn_add_extra_header2);

        autoGetMoreFragment = new AutoGetMoreFragment();
        clickGetMoreFragment = new ClickGetMoreFragment();
        addExtraHeaderFragment1 = new AddExtraHeaderFragment1();
        addExtraHeaderFragment2 = new AddExtraHeaderFragment2();

        fm = getSupportFragmentManager();
        fm.beginTransaction().add(R.id.dl_container, autoGetMoreFragment).commit();

        btnAutoGetMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().replace(R.id.dl_container, autoGetMoreFragment).commit();
                dlMain.closeDrawers();
            }
        });

        btnClickGetMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().replace(R.id.dl_container, clickGetMoreFragment).commit();
                dlMain.closeDrawers();
            }
        });

        btnAddExtraHeader1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().replace(R.id.dl_container, addExtraHeaderFragment1).commit();
                dlMain.closeDrawers();
            }
        });

        btnAddExtraHeader2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().replace(R.id.dl_container, addExtraHeaderFragment2).commit();
                dlMain.closeDrawers();
            }
        });

    }

}


text:
package com.mck.icndbclient;

import android.app.Activity;
import android.content.ContentValues;
import android.content.SharedPreferences;

import com.mck.icndbclient.provider.JokeProviderContract;

/**
 * Created by mike on 4/26/2015.
 */
public class JokeDataHandler implements JokeRetriever.JokeResponder {

    private final Activity activity;
    private JokeRetriever jokeRetriever;

    public JokeDataHandler(Activity activity){
        this.activity = activity;
        jokeRetriever = new JokeRetriever();
    }

    public void setJokeRetriever(JokeRetriever jokeRetriever){
        this.jokeRetriever = jokeRetriever;
    }

    public void requestJoke(){
        // get names from resources
        SharedPreferences preferences = activity.getPreferences(Activity.MODE_PRIVATE);
        String firstName = activity.getResources().getString(R.string.default_first_name);
        String lastName = activity.getResources().getString(R.string.default_last_name);
        jokeRetriever.getJoke(firstName, lastName, this);
    }

    public void requestJoke(JokeRetriever.JokeResponder responder) {
        // get names from resources
        SharedPreferences preferences = activity.getPreferences(Activity.MODE_PRIVATE);
        String firstName = activity.getResources().getString(R.string.default_first_name);
        String lastName = activity.getResources().getString(R.string.default_last_name);

        jokeRetriever.getJoke(firstName, lastName, responder);
    }

    @Override
    public void onJokeResponse(Joke joke) {
        // create content values from the joke
        ContentValues values = new ContentValues();
        values.put(JokeProviderContract.JokesTable.type, joke.type);
        values.put(JokeProviderContract.JokesTable.joke_id, joke.value.id);
        values.put(JokeProviderContract.JokesTable.joke, joke.getJoke());
        if (joke.value.categories !=null) {
            String categories = "";
            for (String category : joke.value.categories) {
                categories += category + " ";
            } // trim? ok.
            values.put(JokeProviderContract.JokesTable.categories, categories.trim());
        }
        activity.getContentResolver().insert(JokeProviderContract.JokesTable.URI, values);
    }

}


text:
from jax.scipy.stats import bernoulli as bernoulli
from jax.scipy.stats import beta as beta
from jax.scipy.stats import cauchy as cauchy
from jax.scipy.stats import dirichlet as dirichlet
from jax.scipy.stats import expon as expon
from jax.scipy.stats import gamma as gamma
from jax.scipy.stats import geom as geom
from jax.scipy.stats import laplace as laplace
from jax.scipy.stats import logistic as logistic
from jax.scipy.stats import multinomial as multinomial
from jax.scipy.stats import multivariate_normal as multivariate_normal
from jax.scipy.stats import nbinom as nbinom
from jax.scipy.stats import norm as norm
from jax.scipy.stats import pareto as pareto
from jax.scipy.stats import poisson as poisson
from jax.scipy.stats import t as t
from jax.scipy.stats import uniform as uniform
from jax.scipy.stats import chi2 as chi2
from jax.scipy.stats import betabinom as betabinom
from jax.scipy.stats import gennorm as gennorm
from jax.scipy.stats import truncnorm as truncnorm
from jax._src.scipy.stats.kde import gaussian_kde as gaussian_kde
from jax._src.scipy.stats._core import mode as mode


text:
from __future__ import unicode_literals
import codecs
import datetime
import email
import logging
import os

import six

from eulxml import xmlmap
from eulxml.utils.compat import u

logger = logging.getLogger(__name__)

# CERP is described at http://siarchives.si.edu/cerp/ . XML spec available at
# http://www.records.ncdcr.gov/emailpreservation/mail-account/mail-account_docs.html
# schema resolves but appears to be empty as of April 2016
# Current schema : http://www.history.ncdcr.gov/SHRAB/ar/emailpreservation/mail-account/mail-account.xsd
# internally-reused and general-utility objects
#

class _BaseCerp(xmlmap.XmlObject):
    'Common CERP namespace declarations'
    ROOT_NS = 'http://www.archives.ncdcr.gov/mail-account'
    ROOT_NAMESPACES = { 'xm': ROOT_NS }

class Parameter(_BaseCerp):
    ROOT_NAME = 'Parameter'
    name = xmlmap.StringField('xm:Name')
    value = xmlmap.StringField('xm:Value')

    def __str__(self):
        return '%s=%s' % (self.name, self.value)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, str(self))

class Header(_BaseCerp):
    ROOT_NAME = 'Header'
    name = xmlmap.StringField('xm:Name')
    value = xmlmap.StringField('xm:Value')
    comments = xmlmap.StringListField('xm:Comments')

    def __str__(self):
        return '%s: %s' % (self.name, self.value)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.name)

class _BaseBody(_BaseCerp):
    '''Common email header elements'''
    content_type_list = xmlmap.StringListField('xm:ContentType')
    charset_list = xmlmap.StringListField('xm:Charset')
    content_name_list = xmlmap.StringListField('xm:ContentName')
    content_type_comments_list = xmlmap.StringListField('xm:ContentTypeComments')
    content_type_param_list = xmlmap.NodeListField('xm:ContentTypeParam', Parameter)
    transfer_encoding_list = xmlmap.StringListField('xm:TransferEncoding')
    transfer_encoding_comments_list = xmlmap.StringListField('xm:TransferEncodingComments')
    content_id_list = xmlmap.StringListField('xm:ContentId')
    content_id_comments_list = xmlmap.StringListField('xm:ContentIdComments')
    description_list = xmlmap.StringListField('xm:Description')
    description_comments_list = xmlmap.StringListField('xm:DescriptionComments')
    disposition_list = xmlmap.StringListField('xm:Disposition')
    disposition_file_name_list = xmlmap.StringListField('xm:DispositionFileName')
    disposition_comments_list = xmlmap.StringListField('xm:DispositionComments')

    disposition_params = xmlmap.NodeListField('xm:DispositionParams', Parameter)
    other_mime_headers = xmlmap.NodeListField('xm:OtherMimeHeader', Header)

class Hash(_BaseCerp):
    ROOT_NAME = 'Hash'
    HASH_FUNCTION_CHOICES = [ 'MD5', 'WHIRLPOOL', 'SHA1', 'SHA224',
                              'SHA256', 'SHA384', 'SHA512', 'RIPEMD160']

    value = xmlmap.StringField('xm:Value')
    function = xmlmap.StringField('xm:Function',
            choices=HASH_FUNCTION_CHOICES)

    def __str__(self):
        return self.value

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.function)

class _BaseExternal(_BaseCerp):
    '''Common external entity reference elements'''
    EOL_CHOICES = [ 'CR', 'LF', 'CRLF' ]

    rel_path = xmlmap.StringField('xm:RelPath')
    eol = xmlmap.StringField('xm:Eol', choices=EOL_CHOICES)
    hash = xmlmap.NodeField('xm:Hash', Hash)

class _BaseContent(_BaseCerp):
    '''Common content encoding elements'''
    charset_list = xmlmap.StringListField('xm:CharSet')
    transfer_encoding_list = xmlmap.StringListField('xm:TransferEncoding')

#
# messages and bodies
#

class BodyContent(_BaseContent):
    ROOT_NAME = 'BodyContent'
    content = xmlmap.StringField('xm:Content')

class ExtBodyContent(_BaseExternal, _BaseContent):
    ROOT_NAME = 'ExtBodyContent'
    local_id = xmlmap.IntegerField('xm:LocalId')
    xml_wrapped = xmlmap.SimpleBooleanField('xm:XMLWrapped',
            true='1', false='0')

class SingleBody(_BaseBody):
    ROOT_NAME = 'SingleBody'

    body_content = xmlmap.NodeField('xm:BodyContent', BodyContent)
    ext_body_content = xmlmap.NodeField('xm:ExtBodyContent', ExtBodyContent)
    child_message = xmlmap.NodeField('xm:ChildMessage', None) # this will be fixed below
    @property
    def content(self):
        return self.body_content or \
               self.ext_body_content or \
               self.child_message

    phantom_body = xmlmap.StringField('xm:PhantomBody')

class MultiBody(_BaseCerp):
    ROOT_NAME = 'MultiBody'
    preamble = xmlmap.StringField('xm:Preamble')
    epilogue = xmlmap.StringField('xm:Epilogue')

    single_body = xmlmap.NodeField('xm:SingleBody', SingleBody)
    multi_body = xmlmap.NodeField('xm:MultiBody', 'self')
    @property
    def body(self):
        return self.single_body or self.multi_body

class Incomplete(_BaseCerp):
    ROOT_NAME = 'Incomplete'
    error_type = xmlmap.StringField('xm:ErrorType')
    error_location = xmlmap.StringField('xm:ErrorLocation')

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.error_type)

class _BaseMessage(_BaseCerp):
    '''Common message elements'''
    local_id = xmlmap.IntegerField('xm:LocalId')
    message_id = xmlmap.StringField('xm:MessageId')
    message_id_supplied = xmlmap.SimpleBooleanField('xm:MessageId/@Supplied',
            true='1', false=None)
    mime_version = xmlmap.StringField('xm:MimeVersion')
    orig_date_list = xmlmap.StringListField('xm:OrigDate') # FIXME: really datetime
    # NOTE: eulxml.xmlmap.DateTimeField supports specifying format,
    # but we might need additional work since %z only works with
    # strftime, not strptime
    from_list = xmlmap.StringListField('xm:From')
    sender_list = xmlmap.StringListField('xm:Sender')
    to_list = xmlmap.StringListField('xm:To')
    cc_list = xmlmap.StringListField('xm:Cc')
    bcc_list = xmlmap.StringListField('xm:Bcc')
    in_reply_to_list = xmlmap.StringListField('xm:InReplyTo')
    references_list = xmlmap.StringListField('xm:References')
    subject_list = xmlmap.StringListField('xm:Subject')
    comments_list = xmlmap.StringListField('xm:Comments')
    keywords_list = xmlmap.StringListField('xm:Keywords')
    headers = xmlmap.NodeListField('xm:Header', Header)

    single_body = xmlmap.NodeField('xm:SingleBody', SingleBody)
    multi_body = xmlmap.NodeField('xm:MultiBody', MultiBody)
    @property
    def body(self):
        return self.single_body or self.multi_body

    incomplete_list = xmlmap.NodeField('xm:Incomplete', Incomplete)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__,
                self.message_id or self.local_id or '(no id)')

class Message(_BaseMessage, _BaseExternal):
    """A single email message in a :class:`Folder`."""

    ROOT_NAME = 'Message'
    STATUS_FLAG_CHOICES = [ 'Seen', 'Answered', 'Flagged', 'Deleted',
                            'Draft', 'Recent']
    status_flags = xmlmap.StringListField('xm:StatusFlag',
            choices=STATUS_FLAG_CHOICES)

    @classmethod
    def from_email_message(cls, message, local_id=None):
        '''
        Convert an :class:`email.message.Message` or compatible message
        object into a CERP XML :class:`eulxml.xmlmap.cerp.Message`. If an
        id is specified, it will be stored in the Message <LocalId>.

        :param message: `email.message.Message` object
        :param id: optional message id to be set as `local_id`

        :returns: :class:`eulxml.xmlmap.cerp.Message` instance populated
    	    with message information

        '''
        result = cls()
        if local_id is not None:
            result.local_id = id

        message_id = message.get('Message-Id')
        if message_id:
            result.message_id_supplied = True
            result.message_id = message_id

        result.mime_version = message.get('MIME-Version')

        dates = message.get_all('Date', [])
        result.orig_date_list.extend([parse_mail_date(d) for d in dates])

        result.from_list.extend(message.get_all('From', []))
        result.sender_list.extend(message.get_all('From', []))
        try:
            result.to_list.extend(message.get_all('To', []))
        except UnicodeError:
            print(repr(message['To']))
            raise
        result.cc_list.extend(message.get_all('Cc', []))
        result.bcc_list.extend(message.get_all('Bcc', []))
        result.in_reply_to_list.extend(message.get_all('In-Reply-To', []))
        result.references_list.extend(message.get_all('References', []))
        result.subject_list.extend(message.get_all('Subject', []))
        result.comments_list.extend(message.get_all('Comments', []))
        result.keywords_list.extend(message.get_all('Keywords', []))

        headers = [ Header(name=key, value=val) for key, val in message.items() ]
        result.headers.extend(headers)

        # FIXME: skip multipart messages for now
        if not message.is_multipart():
            result.create_single_body()

            # FIXME: this is a small subset of the actual elements CERP allows.
            # we should add the rest of them, too.

            # message.get_content_type() always returns something. only
            # put it in the CERP if a Content-Type was explicitly specified.
            if message['Content-Type']:
                result.single_body.content_type_list.append(message.get_content_type())
            if message.get_content_charset():
                result.single_body.charset_list.append(message.get_content_charset())
            if message.get_filename():
                result.single_body.content_name_list.append(message.get_filename())

            # FIXME: attaching the body_content only makes sense for text
            # content types. we'll eventually need a better solution for
            # non-text messages
            result.single_body.create_body_content()
            payload = message.get_payload(decode=False)

            # if not unicode, attempt to convert
            if isinstance(payload, six.binary_type):
                charset = message.get_charset()
                # decode according to the specified character set, if any
                if charset is not None:
                    charset_decoder = codecs.getdecoder(str(charset))
                    payload, length = charset_decoder(payload)

                # otherwise, just try to convert
                else:
                    payload = u(payload)

            # remove any control characters not allowed in XML
            control_char_map = dict.fromkeys(range(32))
            for i in [9, 10, 13]: # preserve horizontal tab, line feed, carriage return
                del control_char_map[i]

            payload = u(payload).translate(control_char_map)

            result.single_body.body_content.content = payload

        else:
            # TODO: handle multipart
            logger.warn('CERP conversion does not yet handle multipart')

        # assume we've normalized newlines:
        result.eol = EOLMAP[os.linesep]

        return result

class ChildMessage(_BaseMessage):
    ROOT_NAME = 'ChildMessage'
    # no additional elements

# Patch-up from above. FIXME: This is necessary because of recursive
# NodeFields. eulxml.xmlmap.NodeField doesn't currently support these
SingleBody.child_message.node_class = ChildMessage

#
# accounts and folders
#

class Mbox(_BaseExternal):
    ROOT_NAME = 'Mbox'
    # no additional fields

class Folder(_BaseCerp):
    """A single email folder in an :class:`Account`, composed of multiple
    :class:`Message` objects and associated metadata."""

    ROOT_NAME = 'Folder'

    name = xmlmap.StringField('xm:Name')
    messages = xmlmap.NodeListField('xm:Message', Message)
    subfolders = xmlmap.NodeListField('xm:Folder', 'self')
    mboxes = xmlmap.NodeListField('xm:Mbox', Mbox)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.name)

class ReferencesAccount(_BaseCerp):
    ROOT_NAME = 'ReferencesAccount'
    REF_TYPE_CHOICES = [ 'PreviousContent', 'SubsequentContent',
                         'Supplemental', 'SeeAlso', 'SeeInstead' ]

    href = xmlmap.StringField('xm:Href')
    email_address = xmlmap.StringField('xm:EmailAddress')
    reference_type = xmlmap.StringField('xm:RefType',
            choices=REF_TYPE_CHOICES)

class Account(_BaseCerp):
    """A single email account associated with a single email address and
    composed of multiple :class:`Folder` objects and additional metadata."""

    ROOT_NAME = 'Account'
    XSD_SCHEMA = 'http://www.history.ncdcr.gov/SHRAB/ar/emailpreservation/mail-account/mail-account.xsd'

    email_address = xmlmap.StringField('xm:EmailAddress')
    global_id = xmlmap.StringField('xm:GlobalId')
    references_accounts = xmlmap.NodeListField('xm:ReferencesAccount',
            ReferencesAccount)
    folders = xmlmap.NodeListField('xm:Folder', Folder)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__,
                self.global_id or self.email_address or '(no id)')

def parse_mail_date(datestr):
    '''Helper method used by :meth:`Message.from_email_message` to
    convert dates from rfc822 format to iso 8601.

    :param datestr: string containing a date in rfc822 format
    :returns: string with date in iso 8601 format
    '''

    time_tuple = email.utils.parsedate_tz(datestr)
    if time_tuple is None:
        return datestr
    dt = datetime.datetime.fromtimestamp(email.utils.mktime_tz(time_tuple))
    return dt.isoformat()

EOLMAP = {
    '\r': 'CR',
    '\n': 'LF',
    '\r\n': 'CRLF',
}


text:
package com.chenjishi.u148;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.chenjishi.u148.home.UserInfo;
import com.chenjishi.u148.utils.Constants;

/**
 * Created by jishichen on 2017/4/14.
 */
public class Config {

    private static final long TWO_DAYS = 2 * 24 * 60 * 60 * 1000;

    private static final String CONFIG_FILE_NAME = "u148_config";

    private static final long VERSION_CHECK_INTERVAL = 24 * 60 * 60 * 1000;

    private static final String KEY_NEXT_TOKEN = "next_from";

    public static final String KEY_UPDATE_TIME = "last_update_time";

    public static final String KEY_CHECK_UPDATE_TIME = "last_check_time";

    public static final String KEY_CHECK_VERSION = "check_version";

    public static final String KEY_VIDEO_UPDATE_TIME = "last_update_time";

    private static final String KEY_CACHE_CLEAR_TIME = "cache_clear_time";
    private static final String KEY_CACHE_UPDATE_TIME = "cache_update_time";

    private static final String KEY_REGISTER_TIME = "register_time";

    private static final String KEY_USER_NAME = "user_name";
    private static final String KEY_USER_SEX = "user_sex";
    private static final String KEY_USER_ICON = "user_icon";
    private static final String KEY_USER_TOKEN = "user_token";

    private static final String KEY_THEME_MODE = "theme_mode";
    private static final String SURPRISE_TITLE = "surprise_title";
    private static final String SURPRISE_DESC = "surprise_desc";

    private Config() {
    }

    public static boolean isLogin(Context ctx) {
        return null != getUser(ctx);
    }

    public static int getThemeMode(Context ctx) {
        return getInt(ctx, KEY_THEME_MODE, Constants.MODE_DAY);
    }

    public static void setThemeMode(Context ctx, int mode) {
        putInt(ctx, KEY_THEME_MODE, mode);
    }

    public static void setRegisterTime(Context ctx, long time) {
        putLong(ctx, KEY_REGISTER_TIME, time);
    }

    public static long getRegisterTime(Context ctx) {
        return getLong(ctx, KEY_REGISTER_TIME, -1L);
    }

    public static void setUser(Context ctx, UserInfo user) {
        if (null != user && !TextUtils.isEmpty(user.token)) {
            putString(ctx, KEY_USER_NAME, user.nickname);
            putString(ctx, KEY_USER_SEX, user.sexStr);
            putString(ctx, KEY_USER_ICON, user.icon);
            putString(ctx, KEY_USER_TOKEN, user.token);
        } else {
            putString(ctx, KEY_USER_NAME, "");
            putString(ctx, KEY_USER_SEX, "");
            putString(ctx, KEY_USER_ICON, "");
            putString(ctx, KEY_USER_TOKEN, "");
        }
    }

    public static UserInfo getUser(Context ctx) {
        String token = getString(ctx, KEY_USER_TOKEN, "");

        if (!TextUtils.isEmpty(token)) {
            UserInfo user = new UserInfo();

            user.nickname = getString(ctx, KEY_USER_NAME, "");
            user.sexStr = getString(ctx, KEY_USER_SEX, "");
            user.icon = getString(ctx, KEY_USER_ICON, "");
            user.token = getString(ctx, KEY_USER_TOKEN, "");

            return user;
        } else {
            return null;
        }
    }

    public static void saveSurpriseTitle(Context ctx, String title) {
        putString(ctx, SURPRISE_TITLE, title);
    }

    public static void saveSurpriseDesc(Context ctx, String desc) {
        putString(ctx, SURPRISE_DESC, desc);
    }

    public static String getSurpriseTitle(Context ctx) {
        return getString(ctx, SURPRISE_TITLE, "");
    }

    public static String getSurpriseDesc(Context ctx) {
        return getString(ctx, SURPRISE_DESC, "");
    }

    public static void setClearCacheTime(Context ctx, long t) {
        putLong(ctx, KEY_CACHE_CLEAR_TIME, t + TWO_DAYS);
    }

    public static long getClearCacheTime(Context ctx) {
        return getLong(ctx, KEY_CACHE_CLEAR_TIME, -1L);
    }

    public static int getInt(Context context, String key, int defaultValue) {
        return getPreferences(context).getInt(key, defaultValue);
    }

    public static void putInt(Context context, String key, int value) {
        SharedPreferences.Editor editor = getPreferences(context).edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public static long getLong(Context context, String key, long defaultValue) {
        return getPreferences(context).getLong(key, defaultValue);
    }

    public static void putLong(Context context, String key, long value) {
        SharedPreferences.Editor editor = getPreferences(context).edit();
        editor.putLong(key, value);
        editor.apply();
    }

    public static String getString(Context context, String key, String defaultValue) {
        return getPreferences(context).getString(key, defaultValue);
    }

    public static void putString(Context context, String key, String value) {
        SharedPreferences.Editor editor = getPreferences(context).edit();
        editor.putString(key, value);
        editor.apply();
    }

    private static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
    }
}


text:
using System;
using NUnit.Framework;
using System.Threading.Tasks;
using Nito.AsyncEx;
using Nito.AsyncEx.Synchronous;
using System.Linq;
using System.Threading;
using System.Diagnostics.CodeAnalysis;

namespace Tests
{
    [TestFixture]
    public class AsyncAutoResetEventUnitTests_NET40
    {
        [Test]
        public void WaitAsync_Unset_IsNotCompleted()
        {
            AsyncContext.Run(async () =>
            {
                var are = new AsyncAutoResetEvent();

                var task = are.WaitAsync();

                await AssertEx.NeverCompletesAsync(task);
            });
        }

        [Test]
        public void WaitAsync_AfterSet_CompletesSynchronously()
        {
            var are = new AsyncAutoResetEvent();

            are.Set();
            var task = are.WaitAsync();

            Assert.IsTrue(task.IsCompleted);
        }

        [Test]
        public void WaitAsync_Set_CompletesSynchronously()
        {
            var are = new AsyncAutoResetEvent(true);

            var task = are.WaitAsync();

            Assert.IsTrue(task.IsCompleted);
        }

        [Test]
        public void MultipleWaitAsync_AfterSet_OnlyOneIsCompleted()
        {
            AsyncContext.Run(async () =>
            {

                var are = new AsyncAutoResetEvent();

                are.Set();
                var task1 = are.WaitAsync();
                var task2 = are.WaitAsync();

                Assert.IsTrue(task1.IsCompleted);
                await AssertEx.NeverCompletesAsync(task2);
            });
        }

        [Test]
        public void MultipleWaitAsync_Set_OnlyOneIsCompleted()
        {
            AsyncContext.Run(async () =>
            {
                var are = new AsyncAutoResetEvent(true);

                var task1 = are.WaitAsync();
                var task2 = are.WaitAsync();

                Assert.IsTrue(task1.IsCompleted);
                await AssertEx.NeverCompletesAsync(task2);
            });
        }

        [Test]
        public void MultipleWaitAsync_AfterMultipleSet_OnlyOneIsCompleted()
        {
            AsyncContext.Run(async () =>
            {
                var are = new AsyncAutoResetEvent();

                are.Set();
                are.Set();
                var task1 = are.WaitAsync();
                var task2 = are.WaitAsync();

                Assert.IsTrue(task1.IsCompleted);
                await AssertEx.NeverCompletesAsync(task2);
            });
        }

        [Test]
        public void WaitAsync_PreCancelled_Set_SynchronouslyCompletesWait()
        {
            var are = new AsyncAutoResetEvent(true);
            var token = new CancellationToken(true);

            var task = are.WaitAsync(token);

            Assert.IsTrue(task.IsCompleted);
            Assert.IsFalse(task.IsCanceled);
            Assert.IsFalse(task.IsFaulted);
        }

        [Test]
        public void WaitAsync_Cancelled_DoesNotAutoReset()
        {
            AsyncContext.Run(async () =>
            {
                var are = new AsyncAutoResetEvent();
                var cts = new CancellationTokenSource();

                cts.Cancel();
                var task1 = are.WaitAsync(cts.Token);
                task1.WaitWithoutException();
                are.Set();
                var task2 = are.WaitAsync();

                await task2;
            });
        }

        [Test]
        public void WaitAsync_PreCancelled_Unset_SynchronouslyCancels()
        {
            var are = new AsyncAutoResetEvent(false);
            var token = new CancellationToken(true);

            var task = are.WaitAsync(token);

            Assert.IsTrue(task.IsCompleted);
            Assert.IsTrue(task.IsCanceled);
            Assert.IsFalse(task.IsFaulted);
        }

        [Test]
        public void WaitAsyncFromCustomSynchronizationContext_PreCancelled_Unset_SynchronouslyCancels()
        {
            AsyncContext.Run(() =>
            {
                var are = new AsyncAutoResetEvent(false);
                var token = new CancellationToken(true);

                var task = are.WaitAsync(token);

                Assert.IsTrue(task.IsCompleted);
                Assert.IsTrue(task.IsCanceled);
                Assert.IsFalse(task.IsFaulted);
            });
        }

        [Test]
        public void WaitAsync_Cancelled_ThrowsException()
        {
            AsyncContext.Run(async () =>
            {
                var are = new AsyncAutoResetEvent();
                var cts = new CancellationTokenSource();
                cts.Cancel();
                var task = are.WaitAsync(cts.Token);
                await AssertEx.ThrowsExceptionAsync<OperationCanceledException>(task);
            });
        }

        [Test]
        public void Id_IsNotZero()
        {
            var are = new AsyncAutoResetEvent();
            Assert.AreNotEqual(0, are.Id);
        }
    }
}


text:
  Ourches-sur-Meuse est
       un village
       situé dans le département de Meuse en Lorraine. Elle comptait 191 habitants en 2008.

À proximité de Ourches-sur-Meuse sont situées les communes de
Lay-Saint-Remy à 4 km, 348 habitants,
Chalaines localisée à 6 km, 318 habitants,
Troussey située à 4 km, 390 habitants,
Foug à 6 km, 2 762 habitants,
Pagny-sur-Meuse à 3 km, 961 habitants,
Saint-Germain-sur-Meuse localisée à 1 km, 248 habitants,
 entre autres. De plus, Ourches-sur-Meuse est située à seulement quatorze km de Toul.

Le nombre d'habitations, à Ourches-sur-Meuse, se décomposait en 2011 en sept appartements et 101 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de demenager à Ourches-sur-Meuse, vous pourrez aisément trouver une maison à acheter.


text:
A simple game created to improve my programming skills using C++ and SFML 2.4.1. Any feedback would be appreciated

## Description
The objective of the game is to "double jump" to stay inside the window whilst using the mouse to shoot down the enemies that are chasing you.

## Compiling
The best method would be to use Visual Studio 2015

1. Download the ZIP file and extract the files
2. Open solution file (.sln)
3. [Configure Visual Studio Environment to run SFML](http://www.sfml-dev.org/tutorials/2.4/start-vc.php)
4. Make sure to build solution for 32-bit

## Final Remarks
This project is definitely not perfect, but it is what I consider to be "finished". Despite the fact that there are some small bugs (which is common in any game), the core of the game is fully functioning. This was a small project designed to improve my skills in game programming and programming in general (specifically in C++ and SFML). Overall, I'm quite happy with its current state which means I wont be updating it any further. However, feel free to download and play around with it on your own.


text:
package org.apache.cassandra.net.async;

import java.io.IOException;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;

import com.google.common.annotations.VisibleForTesting;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import io.netty.channel.MessageSizeEstimator;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.utils.CoalescingStrategies;
import org.apache.cassandra.utils.CoalescingStrategies.CoalescingStrategy;

/**
 * Represents a ready and post-handshake channel that can send outbound messages. This class groups a netty channel
 * with any other channel-related information we track and, most importantly, handles the details on when the channel is flushed.
 *
 *
Flushing

 *
 * We don't flush to the socket on every message as it's a bit of a performance drag (making the system call, copying
 * the buffer, sending out a small packet). Thus, by waiting until we have a decent chunk of data (for some definition
 * of 'decent'), we can achieve better efficiency and improved performance (yay!).
 *

 * When to flush mainly depends on whether we use message coalescing or not (see {@link CoalescingStrategies}).
 *

 * Note that the callback functions are invoked on the netty event loop, which is (in almost all cases) different
 * from the thread that will be invoking {@link #write(QueuedMessage, boolean)}.
 *
 *
Flushing without coalescing

 *
 * When no coalescing is in effect, we want to send new message "right away". However, as said above, flushing after
 * every message would be particularly inefficient when there is lots of message in our sending queue, and so in
 * practice we want to flush in 2 cases:
 *  1) After any message if there is no pending message in the send queue.
 *  2) When we've filled up or exceeded the netty outbound buffer (see {@link ChannelOutboundBuffer})
 *

 * The second part is relatively simple and handled generically in {@link MessageOutHandler#write(ChannelHandlerContext, Object, ChannelPromise)} [1].
 * The first part however is made a little more complicated by how netty's event loop executes. It is woken up by
 * external callers to the channel invoking a flush, via either {@link Channel#flush} or one of the {@link Channel#writeAndFlush}
 * methods [2]. So a plain {@link Channel#write} will only queue the message in the channel, and not wake up the event loop.
 *

 * This means we don't want to simply call {@link Channel#write} as we want the message processed immediately. But we
 * also don't want to flush on every message if there is more in the sending queue, so simply calling
 * {@link Channel#writeAndFlush} isn't completely appropriate either. In practice, we handle this by calling
 * {@link Channel#writeAndFlush} (so the netty event loop does wake up), but we override the flush behavior so
 * it actually only flushes if there are no pending messages (see how {@link MessageOutHandler#flush} delegates the flushing
 * decision back to this class through {@link #onTriggeredFlush}, and how {@link SimpleChannelWriter} makes this a no-op;
 * instead {@link SimpleChannelWriter} flushes after any message if there are no more pending ones in
 * {@link #onMessageProcessed}).
 *
 *
Flushing with coalescing

 *
 * The goal of coalescing is to (artificially) delay the flushing of data in order to aggregate even more data before
 * sending a group of packets out. So we don't want to flush after messages even if there is no pending messages in the
 * sending queue, but we rather want to delegate the decision on when to flush to the {@link CoalescingStrategy}. In
 * pratice, when coalescing is enabled we will flush in 2 cases:
 *  1) When the coalescing strategies decides that we should.
 *  2) When we've filled up or exceeded the netty outbound buffer ({@link ChannelOutboundBuffer}), exactly like in the
 *  no coalescing case.
 *

 *  The second part is handled exactly like in the no coalescing case, see above.
 *  The first part is handled by {@link CoalescingChannelWriter#write(QueuedMessage, boolean)}. Whenever a message is sent, we check
 *  if a flush has been already scheduled by the coalescing strategy. If one has, we're done, otherwise we ask the
 *  strategy when the next flush should happen and schedule one.
 *
 *
Message timeouts and retries

 *
 * The main outward-facing method is {@link #write(QueuedMessage, boolean)}, where callers pass a
 * {@link QueuedMessage}. If a message times out, as defined in {@link QueuedMessage#isTimedOut()},
 * the message listener {@link #handleMessageFuture(Future, QueuedMessage, boolean)} is invoked
 * with the cause being a {@link ExpiredException}. The message is not retried and it is dropped on the floor.
 *

 * If there is some {@link IOException} on the socket after the message has been written to the netty channel,
 * the message listener {@link #handleMessageFuture(Future, QueuedMessage, boolean)} is invoked
 * and 1) we check to see if the connection should be re-established, and 2) possibly createRetry the message.
 *
 *
Failures

 *
 *
Failure to make progress sending bytes

 * If we are unable to make progress sending messages, we'll receive a netty notification
 * ({@link IdleStateEvent}) at {@link MessageOutHandler#userEventTriggered(ChannelHandlerContext, Object)}.
 * We then want to close the socket/channel, and purge any messages in {@link OutboundMessagingConnection#backlog}
 * to try to free up memory as quickly as possible. Any messages in the netty pipeline will be marked as fail
 * (as we close the channel), but {@link MessageOutHandler#userEventTriggered(ChannelHandlerContext, Object)} also
 * sets a channel attribute, {@link #PURGE_MESSAGES_CHANNEL_ATTR} to true. This is essentially as special flag
 * that we can look at in the promise handler code ({@link #handleMessageFuture(Future, QueuedMessage, boolean)})
 * to indicate that any backlog should be thrown away.
 *
 *
Notes

 * [1] For those desperately interested, and only after you've read the entire class-level doc: You can register a custom
 * {@link MessageSizeEstimator} with a netty channel. When a message is written to the channel, it will check the
 * message size, and if the max ({@link ChannelOutboundBuffer}) size will be exceeded, a task to signal the "channel
 * writability changed" will be executed in the channel. That task, however, will wake up the event loop.
 * Thus if coalescing is enabled, the event loop will wake up prematurely and process (and possibly flush!) the messages
 * currently in the queue, thus defeating an aspect of coalescing. Hence, we're not using that feature of netty.
 * [2]: The netty event loop is also woken up by it's internal timeout on the epoll_wait() system call.
 */
abstract class ChannelWriter
{
    /**
     * A netty channel {@link Attribute} to indicate, when a channel is closed, any backlogged messages should be purged,
     * as well. See the class-level documentation for more information.
     */
    static final AttributeKey<Boolean> PURGE_MESSAGES_CHANNEL_ATTR = AttributeKey.newInstance("purgeMessages");

    protected final Channel channel;
    private volatile boolean closed;

    /** Number of currently pending messages on this channel. */
    final AtomicLong pendingMessageCount = new AtomicLong(0);

    /**
     * A consuming function that handles the result of each message sent.
     */
    private final Consumer<MessageResult> messageResultConsumer;

    /**
     * A reusable instance to avoid creating garbage on preciessing the result of every message sent.
     * As we have the guarantee that the netty evet loop is single threaded, there should be no contention over this
     * instance, as long as it (not it's state) is shared across threads.
     */
    private final MessageResult messageResult = new MessageResult();

    protected ChannelWriter(Channel channel, Consumer<MessageResult> messageResultConsumer)
    {
        this.channel = channel;
        this.messageResultConsumer = messageResultConsumer;
        channel.attr(PURGE_MESSAGES_CHANNEL_ATTR).set(false);
    }

    /**
     * Creates a new {@link ChannelWriter} using the (assumed properly connected) provided channel, and using coalescing
     * based on the provided strategy.
     */
    static ChannelWriter create(Channel channel, Consumer<MessageResult> messageResultConsumer, Optional<CoalescingStrategy> coalescingStrategy)
    {
        return coalescingStrategy.isPresent()
               ? new CoalescingChannelWriter(channel, messageResultConsumer, coalescingStrategy.get())
               : new SimpleChannelWriter(channel, messageResultConsumer);
    }

    /**
     * Writes a message to this {@link ChannelWriter} if the channel is writable.
     *

     * We always want to write to the channel *unless* it's not writable yet still open.
     * If the channel is closed, the promise will be notifed as a fail (due to channel closed),
     * and let the handler ({@link #handleMessageFuture(Future, QueuedMessage, boolean)})
     * do the reconnect magic/dance. Thus we simplify when to reconnect by not burdening the (concurrent) callers
     * of this method, and instead keep it all in the future handler/event loop (which is single threaded).
     *
     * @param message the message to write/send.
     * @param checkWritability a flag to indicate if the status of the channel should be checked before passing
     * the message on to the {@link #channel}.
     * @return true if the message was written to the channel; else, false.
     */
    boolean write(QueuedMessage message, boolean checkWritability)
    {
        if ( (checkWritability && (channel.isWritable()) || !channel.isOpen()) || !checkWritability)
        {
            write0(message).addListener(f -> handleMessageFuture(f, message, true));
            return true;
        }
        return false;
    }

    /**
     * Handles the future of sending a particular message on this {@link ChannelWriter}.
     *

     * Note: this is called from the netty event loop, so there is no race across multiple execution of this method.
     */
    @VisibleForTesting
    void handleMessageFuture(Future<? super Void> future, QueuedMessage msg, boolean allowReconnect)
    {
        messageResult.setAll(this, msg, future, allowReconnect);
        messageResultConsumer.accept(messageResult);
        messageResult.clearAll();
    }

    boolean shouldPurgeBacklog()
    {
        if (!channel.attr(PURGE_MESSAGES_CHANNEL_ATTR).get())
            return false;

        channel.attr(PURGE_MESSAGES_CHANNEL_ATTR).set(false);
        return true;
    }

    /**
     * Writes a backlog of message to this {@link ChannelWriter}. This is mostly equivalent to calling
     * {@link #write(QueuedMessage, boolean)} for every message of the provided backlog queue, but
     * it ignores any coalescing, triggering a flush only once after all messages have been sent.
     *
     * @param backlog the backlog of message to send.
     * @return the count of items written to the channel from the queue.
     */
    int writeBacklog(Queue<QueuedMessage> backlog, boolean allowReconnect)
    {
        int count = 0;
        while (true)
        {
            if (!channel.isWritable())
                break;

            QueuedMessage msg = backlog.poll();
            if (msg == null)
                break;

            pendingMessageCount.incrementAndGet();
            ChannelFuture future = channel.write(msg);
            future.addListener(f -> handleMessageFuture(f, msg, allowReconnect));
            count++;
        }

        // as this is an infrequent operation, don't bother coordinating with the instance-level flush task
        if (count > 0)
            channel.flush();

        return count;
    }

    void close()
    {
        if (closed)
            return;

        closed = true;
        channel.close();
    }

    long pendingMessageCount()
    {
        return pendingMessageCount.get();
    }

    /**
     * Close the underlying channel but only after having make sure every pending message has been properly sent.
     */
    void softClose()
    {
        if (closed)
            return;

        closed = true;
        channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @VisibleForTesting
    boolean isClosed()
    {
        return closed;
    }

    /**
     * Write the message to the {@link #channel}.
     *

     * Note: this method, in almost all cases, is invoked from an app-level writing thread, not the netty event loop.
     */
    protected abstract ChannelFuture write0(QueuedMessage message);

    /**
     * Invoked after a message has been processed in the pipeline. Should only be used for essential bookkeeping operations.
     *

     * Note: this method is invoked on the netty event loop.
     */
    abstract void onMessageProcessed(ChannelHandlerContext ctx);

    /**
     * Invoked when pipeline receives a flush request.
     *

     * Note: this method is invoked on the netty event loop.
     */
    abstract void onTriggeredFlush(ChannelHandlerContext ctx);

    /**
     * Handles the non-coalescing flush case.
     */
    @VisibleForTesting
    static class SimpleChannelWriter extends ChannelWriter
    {
        private SimpleChannelWriter(Channel channel, Consumer<MessageResult> messageResultConsumer)
        {
            super(channel, messageResultConsumer);
        }

        protected ChannelFuture write0(QueuedMessage message)
        {
            pendingMessageCount.incrementAndGet();
            // We don't truly want to flush on every message but we do want to wake-up the netty event loop for the
            // channel so the message is processed right away, which is why we use writeAndFlush. This won't actually
            // flush, though, because onTriggeredFlush, which MessageOutHandler delegates to, does nothing. We will
            // flush after the message is processed though if there is no pending one due to onMessageProcessed.
            // See the class javadoc for context and much more details.
            return channel.writeAndFlush(message);
        }

        void onMessageProcessed(ChannelHandlerContext ctx)
        {
            if (pendingMessageCount.decrementAndGet() == 0)
                ctx.flush();
        }

        void onTriggeredFlush(ChannelHandlerContext ctx)
        {
            // Don't actually flush on "normal" flush calls to the channel.
        }
    }

    /**
     * Handles the coalescing flush case.
     */
    @VisibleForTesting
    static class CoalescingChannelWriter extends ChannelWriter
    {
        private static final int MIN_MESSAGES_FOR_COALESCE = DatabaseDescriptor.getOtcCoalescingEnoughCoalescedMessages();

        private final CoalescingStrategy strategy;
        private final int minMessagesForCoalesce;

        @VisibleForTesting
        final AtomicBoolean scheduledFlush = new AtomicBoolean(false);

        CoalescingChannelWriter(Channel channel, Consumer<MessageResult> messageResultConsumer, CoalescingStrategy strategy)
        {
            this (channel, messageResultConsumer, strategy, MIN_MESSAGES_FOR_COALESCE);
        }

        @VisibleForTesting
        CoalescingChannelWriter(Channel channel, Consumer<MessageResult> messageResultConsumer, CoalescingStrategy strategy, int minMessagesForCoalesce)
        {
            super(channel, messageResultConsumer);
            this.strategy = strategy;
            this.minMessagesForCoalesce = minMessagesForCoalesce;
        }

        protected ChannelFuture write0(QueuedMessage message)
        {
            long pendingCount = pendingMessageCount.incrementAndGet();
            ChannelFuture future = channel.write(message);
            strategy.newArrival(message);

            // if we lost the race to set the state, simply write to the channel (no flush)
            if (!scheduledFlush.compareAndSet(false, true))
                return future;

            long flushDelayNanos;
            // if we've hit the minimum number of messages for coalescing or we've run out of coalesce time, flush.
            // note: we check the exact count, instead of greater than or equal to, of message here to prevent a flush task
            // for each message (if there's messages coming in on multiple threads). There will be, of course, races
            // with the consumer decrementing the pending counter, but that's still less excessive flushes.
            if (pendingCount == minMessagesForCoalesce || (flushDelayNanos = strategy.currentCoalescingTimeNanos()) <= 0)
            {
                scheduledFlush.set(false);
                channel.flush();
            }
            else
            {
                // calling schedule() on the eventLoop will force it to wake up (if not already executing) and schedule the task
                channel.eventLoop().schedule(() -> {
                    // NOTE: this executes on the event loop
                    scheduledFlush.set(false);
                    // we execute() the flush() as an additional task rather than immediately in-line as there is a
                    // race condition when this task runs (executing on the event loop) and a thread that writes the channel (top of this method).
                    // If this task is picked up but before the scheduledFlush falg is flipped, the other thread writes
                    // and then checks the scheduledFlush (which is still true) and exits.
                    // This task changes the flag and if it calls flush() in-line, and netty flushs everything immediately (that is, what's been serialized)
                    // to the transport as we're on the event loop. The other thread's write became a task that executes *after* this task in the netty queue,
                    // and if there's not a subsequent followup flush scheduled, that write can be orphaned until another write comes in.
                    channel.eventLoop().execute(channel::flush);
                }, flushDelayNanos, TimeUnit.NANOSECONDS);
            }
            return future;
        }

        void onMessageProcessed(ChannelHandlerContext ctx)
        {
            pendingMessageCount.decrementAndGet();
        }

        void onTriggeredFlush(ChannelHandlerContext ctx)
        {
            // When coalescing, obey the flush calls normally
            ctx.flush();
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;

#nullable disable

namespace Microsoft.Build.Tasks.Deployment.Bootstrapper
{
    internal static class NativeMethods
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern IntPtr BeginUpdateResourceW(String fileName, bool deleteExistingResource);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern bool UpdateResourceW(IntPtr hUpdate, IntPtr lpType, String lpName, short wLanguage, byte[] data, int cbData);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);
    }
}