text:
#ifndef __TT_OSC_SOCKET_H__
#define __TT_OSC_SOCKET_H__

#include "TTFoundationAPI.h"

#include "OscPacketListener.h"
#include "UdpSocket.h"
#include "OscOutboundPacketStream.h"

/** ...
 @param anArgument		a TTOscSocket pointer
 @return				NULL */
TTPtr       TTOscSocketListenerCreate(TTPtr anArgument);

/** ...
 @param anArgument		a TTOscSocket pointer
 @return				NO if the Osc listener should abort or YES if it should continue */
TTBoolean   TTOscSocketListenerRun(TTPtr anArgument);

/** \ingroup enums
    Connection flag used to know if the OSC socket manage to connect to a port
 */
enum TTOscSocketConnectionFlag {
	kOscSocketConnectionTrying = 0,         ///< this flag means the OSC socket is trying to connect
	kOscSocketConnectionSucceeded = 1,      ///< this flag means the OSC socket connection succeeded
    kOscSocketConnectionFailed = 2,         ///< this flag means the OSC socket failed to connect
};

/**	TTOscSocket is ...
 */
class TTOscSocket : public osc::OscPacketListener
{

private:

	TTObjectBasePtr				mOwner;							///< The object that instantiated this socket and will receive notifications.

	TTString					mAddress;
	TTUInt16					mPort;

	UdpListeningReceiveSocket*	mSocketListener;
	UdpTransmitSocket*			mSocketTransmitter;

	TTThreadPtr					mSocketListenerThread;			/// for receiving data

    TTOscSocketConnectionFlag   mSocketListenerStatus;

public:

	/**	Create a socket to receive osc messages.
		@param	owner		the TTObjectBase to notify
		@param	port		the port number
	 */
	TTOscSocket(const TTObjectBasePtr owner, const TTUInt16 port);

	/**	Create a socket to send osc messages.
	 @param	address		the ip address
	 @param	port		the port number
	 */
	TTOscSocket(const TTString& address, const TTUInt16 port);

	virtual ~TTOscSocket();

	TTErr		SendMessage(TTSymbol& message, const TTValue& arguments);

    TTOscSocketConnectionFlag	getSocketListenerStatus();

private:
	// internal helper method
	TTUInt32	computeMessageSize(TTSymbol& message, const TTValue& arguments);

protected:

	virtual void ProcessMessage(const osc::ReceivedMessage&m, const IpEndpointName& remoteEndPoint);

	friend TTPtr TTOscSocketListenerCreate(TTPtr anArgument);
    friend TTBoolean TTOscSocketListenerRun(TTPtr anArgument);
};
typedef TTOscSocket* TTOscSocketPtr;

#endif // __TT_OSC_SOCKET_H__

redpajama_set_name: RedPajamaGithub


text:
package expression

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"math"
	"net"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/google/uuid"
	"github.com/pingcap/errors"
	"github.com/pingcap/tidb/parser/mysql"
	"github.com/pingcap/tidb/parser/terror"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/chunk"
	"github.com/pingcap/tidb/util/vitess"
	"github.com/pingcap/tipb/go-tipb"
)

var (
	_ functionClass = &sleepFunctionClass{}
	_ functionClass = &lockFunctionClass{}
	_ functionClass = &releaseLockFunctionClass{}
	_ functionClass = &anyValueFunctionClass{}
	_ functionClass = &defaultFunctionClass{}
	_ functionClass = &inetAtonFunctionClass{}
	_ functionClass = &inetNtoaFunctionClass{}
	_ functionClass = &inet6AtonFunctionClass{}
	_ functionClass = &inet6NtoaFunctionClass{}
	_ functionClass = &isFreeLockFunctionClass{}
	_ functionClass = &isIPv4FunctionClass{}
	_ functionClass = &isIPv4CompatFunctionClass{}
	_ functionClass = &isIPv4MappedFunctionClass{}
	_ functionClass = &isIPv6FunctionClass{}
	_ functionClass = &isUsedLockFunctionClass{}
	_ functionClass = &masterPosWaitFunctionClass{}
	_ functionClass = &nameConstFunctionClass{}
	_ functionClass = &releaseAllLocksFunctionClass{}
	_ functionClass = &uuidFunctionClass{}
	_ functionClass = &uuidShortFunctionClass{}
	_ functionClass = &vitessHashFunctionClass{}
	_ functionClass = &uuidToBinFunctionClass{}
	_ functionClass = &binToUUIDFunctionClass{}
	_ functionClass = &isUUIDFunctionClass{}
	_ functionClass = &tidbShardFunctionClass{}
)

var (
	_ builtinFunc = &builtinSleepSig{}
	_ builtinFunc = &builtinLockSig{}
	_ builtinFunc = &builtinReleaseLockSig{}
	_ builtinFunc = &builtinReleaseAllLocksSig{}
	_ builtinFunc = &builtinDecimalAnyValueSig{}
	_ builtinFunc = &builtinDurationAnyValueSig{}
	_ builtinFunc = &builtinIntAnyValueSig{}
	_ builtinFunc = &builtinJSONAnyValueSig{}
	_ builtinFunc = &builtinRealAnyValueSig{}
	_ builtinFunc = &builtinStringAnyValueSig{}
	_ builtinFunc = &builtinTimeAnyValueSig{}
	_ builtinFunc = &builtinInetAtonSig{}
	_ builtinFunc = &builtinInetNtoaSig{}
	_ builtinFunc = &builtinInet6AtonSig{}
	_ builtinFunc = &builtinInet6NtoaSig{}
	_ builtinFunc = &builtinIsIPv4Sig{}
	_ builtinFunc = &builtinIsIPv4CompatSig{}
	_ builtinFunc = &builtinIsIPv4MappedSig{}
	_ builtinFunc = &builtinIsIPv6Sig{}
	_ builtinFunc = &builtinIsUUIDSig{}
	_ builtinFunc = &builtinUUIDSig{}
	_ builtinFunc = &builtinVitessHashSig{}
	_ builtinFunc = &builtinUUIDToBinSig{}
	_ builtinFunc = &builtinBinToUUIDSig{}

	_ builtinFunc = &builtinNameConstIntSig{}
	_ builtinFunc = &builtinNameConstRealSig{}
	_ builtinFunc = &builtinNameConstDecimalSig{}
	_ builtinFunc = &builtinNameConstTimeSig{}
	_ builtinFunc = &builtinNameConstDurationSig{}
	_ builtinFunc = &builtinNameConstStringSig{}
	_ builtinFunc = &builtinNameConstJSONSig{}
	_ builtinFunc = &builtinTidbShardSig{}
)

const (
	tidbShardBucketCount = 256
)

type sleepFunctionClass struct {
	baseFunctionClass
}

func (c *sleepFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETReal)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(21)
	sig := &builtinSleepSig{bf}
	return sig, nil
}

type builtinSleepSig struct {
	baseBuiltinFunc
}

func (b *builtinSleepSig) Clone() builtinFunc {
	newSig := &builtinSleepSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinSleepSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_sleep
func (b *builtinSleepSig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalReal(b.ctx, row)
	if err != nil {
		return 0, isNull, err
	}

	sessVars := b.ctx.GetSessionVars()
	if isNull || val < 0 {
		// for insert ignore stmt, the StrictSQLMode and ignoreErr should both be considered.
		if !sessVars.StmtCtx.BadNullAsWarning {
			return 0, false, errIncorrectArgs.GenWithStackByArgs("sleep")
		}
		err := errIncorrectArgs.GenWithStackByArgs("sleep")
		sessVars.StmtCtx.AppendWarning(err)
		return 0, false, nil
	}

	if val > math.MaxFloat64/float64(time.Second.Nanoseconds()) {
		return 0, false, errIncorrectArgs.GenWithStackByArgs("sleep")
	}

	if isKilled := doSleep(val, sessVars); isKilled {
		return 1, false, nil
	}

	return 0, false, nil
}

type lockFunctionClass struct {
	baseFunctionClass
}

func (c *lockFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString, types.ETInt)
	if err != nil {
		return nil, err
	}
	sig := &builtinLockSig{bf}
	bf.tp.SetFlen(1)
	return sig, nil
}

type builtinLockSig struct {
	baseBuiltinFunc
}

func (b *builtinLockSig) Clone() builtinFunc {
	newSig := &builtinLockSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinLockSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
func (b *builtinLockSig) evalInt(row chunk.Row) (int64, bool, error) {
	lockName, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil {
		return 0, isNull, err
	}
	// Validate that lockName is NOT NULL or empty string
	if isNull {
		return 0, false, errUserLockWrongName.GenWithStackByArgs("NULL")
	}
	if lockName == "" || utf8.RuneCountInString(lockName) > 64 {
		return 0, false, errUserLockWrongName.GenWithStackByArgs(lockName)
	}
	maxTimeout := int64(variable.GetSysVar(variable.InnodbLockWaitTimeout).MaxValue)
	timeout, isNullTimeout, err := b.args[1].EvalInt(b.ctx, row)
	if err != nil {
		return 0, false, err
	}
	if isNullTimeout {
		timeout = 0 // Observed in MySQL, gets converted to 1s in TiDB because of min timeout.
	}
	// A timeout less than zero is expected to be treated as unlimited.
	// Because of our implementation being based on pessimistic locks,
	// We can't have a timeout greater than innodb_lock_wait_timeout.
	// So users are aware, we also attach a warning.
	if timeout < 0 || timeout > maxTimeout {
		err := errTruncatedWrongValue.GenWithStackByArgs("get_lock", strconv.FormatInt(timeout, 10))
		b.ctx.GetSessionVars().StmtCtx.AppendWarning(err)
		timeout = maxTimeout
	}

	// Lock names are case insensitive. Because we can't rely on collations
	// being enabled on the internal table, we have to lower it.
	lockName = strings.ToLower(lockName)
	if utf8.RuneCountInString(lockName) > 64 {
		return 0, false, errIncorrectArgs.GenWithStackByArgs("get_lock")
	}
	err = b.ctx.GetAdvisoryLock(lockName, timeout)
	if err != nil {
		switch errors.Cause(err).(*terror.Error).Code() {
		case mysql.ErrLockWaitTimeout:
			return 0, false, nil // Another user has the lock
		case mysql.ErrLockDeadlock:
			// Currently this code is not reachable because each Advisory Lock
			// Uses a separate session. Deadlock detection does not work across
			// independent sessions.
			return 0, false, errUserLockDeadlock
		default:
			return 0, false, err
		}
	}
	return 1, false, nil
}

type releaseLockFunctionClass struct {
	baseFunctionClass
}

func (c *releaseLockFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	sig := &builtinReleaseLockSig{bf}
	bf.tp.SetFlen(1)
	return sig, nil
}

type builtinReleaseLockSig struct {
	baseBuiltinFunc
}

func (b *builtinReleaseLockSig) Clone() builtinFunc {
	newSig := &builtinReleaseLockSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinReleaseLockSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_release-lock
func (b *builtinReleaseLockSig) evalInt(row chunk.Row) (int64, bool, error) {
	lockName, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil {
		return 0, isNull, err
	}
	// Validate that lockName is NOT NULL or empty string
	if isNull {
		return 0, false, errUserLockWrongName.GenWithStackByArgs("NULL")
	}
	if lockName == "" || utf8.RuneCountInString(lockName) > 64 {
		return 0, false, errUserLockWrongName.GenWithStackByArgs(lockName)
	}
	// Lock names are case insensitive. Because we can't rely on collations
	// being enabled on the internal table, we have to lower it.
	lockName = strings.ToLower(lockName)
	if utf8.RuneCountInString(lockName) > 64 {
		return 0, false, errIncorrectArgs.GenWithStackByArgs("release_lock")
	}
	released := int64(0)
	if b.ctx.ReleaseAdvisoryLock(lockName) {
		released = 1
	}
	return released, false, nil
}

type anyValueFunctionClass struct {
	baseFunctionClass
}

func (c *anyValueFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	argTp := args[0].GetType().EvalType()
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, argTp, argTp)
	if err != nil {
		return nil, err
	}
	ft := args[0].GetType().Clone()
	ft.AddFlag(bf.tp.GetFlag())
	*bf.tp = *ft
	var sig builtinFunc
	switch argTp {
	case types.ETDecimal:
		sig = &builtinDecimalAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_DecimalAnyValue)
	case types.ETDuration:
		sig = &builtinDurationAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_DurationAnyValue)
	case types.ETInt:
		bf.tp.SetDecimal(0)
		sig = &builtinIntAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_IntAnyValue)
	case types.ETJson:
		sig = &builtinJSONAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_JSONAnyValue)
	case types.ETReal:
		sig = &builtinRealAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_RealAnyValue)
	case types.ETString:
		bf.tp.SetDecimal(types.UnspecifiedLength)
		sig = &builtinStringAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_StringAnyValue)
	case types.ETDatetime, types.ETTimestamp:
		bf.tp.SetCharset(mysql.DefaultCharset)
		bf.tp.SetCollate(mysql.DefaultCollationName)
		bf.tp.SetFlag(0)
		sig = &builtinTimeAnyValueSig{bf}
		sig.setPbCode(tipb.ScalarFuncSig_TimeAnyValue)
	default:
		return nil, errIncorrectArgs.GenWithStackByArgs("ANY_VALUE")
	}
	return sig, nil
}

type builtinDecimalAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinDecimalAnyValueSig) Clone() builtinFunc {
	newSig := &builtinDecimalAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalDecimal evals a builtinDecimalAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinDecimalAnyValueSig) evalDecimal(row chunk.Row) (*types.MyDecimal, bool, error) {
	return b.args[0].EvalDecimal(b.ctx, row)
}

type builtinDurationAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinDurationAnyValueSig) Clone() builtinFunc {
	newSig := &builtinDurationAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalDuration evals a builtinDurationAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinDurationAnyValueSig) evalDuration(row chunk.Row) (types.Duration, bool, error) {
	return b.args[0].EvalDuration(b.ctx, row)
}

type builtinIntAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinIntAnyValueSig) Clone() builtinFunc {
	newSig := &builtinIntAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinIntAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinIntAnyValueSig) evalInt(row chunk.Row) (int64, bool, error) {
	return b.args[0].EvalInt(b.ctx, row)
}

type builtinJSONAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinJSONAnyValueSig) Clone() builtinFunc {
	newSig := &builtinJSONAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalJSON evals a builtinJSONAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinJSONAnyValueSig) evalJSON(row chunk.Row) (types.BinaryJSON, bool, error) {
	return b.args[0].EvalJSON(b.ctx, row)
}

type builtinRealAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinRealAnyValueSig) Clone() builtinFunc {
	newSig := &builtinRealAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalReal evals a builtinRealAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinRealAnyValueSig) evalReal(row chunk.Row) (float64, bool, error) {
	return b.args[0].EvalReal(b.ctx, row)
}

type builtinStringAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinStringAnyValueSig) Clone() builtinFunc {
	newSig := &builtinStringAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals a builtinStringAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinStringAnyValueSig) evalString(row chunk.Row) (string, bool, error) {
	return b.args[0].EvalString(b.ctx, row)
}

type builtinTimeAnyValueSig struct {
	baseBuiltinFunc
}

func (b *builtinTimeAnyValueSig) Clone() builtinFunc {
	newSig := &builtinTimeAnyValueSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalTime evals a builtinTimeAnyValueSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
func (b *builtinTimeAnyValueSig) evalTime(row chunk.Row) (types.Time, bool, error) {
	return b.args[0].EvalTime(b.ctx, row)
}

type defaultFunctionClass struct {
	baseFunctionClass
}

func (c *defaultFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", "DEFAULT")
}

type inetAtonFunctionClass struct {
	baseFunctionClass
}

func (c *inetAtonFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(21)
	bf.tp.AddFlag(mysql.UnsignedFlag)
	sig := &builtinInetAtonSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_InetAton)
	return sig, nil
}

type builtinInetAtonSig struct {
	baseBuiltinFunc
}

func (b *builtinInetAtonSig) Clone() builtinFunc {
	newSig := &builtinInetAtonSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinInetAtonSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_inet-aton
func (b *builtinInetAtonSig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return 0, true, err
	}
	// ip address should not end with '.'.
	if len(val) == 0 || val[len(val)-1] == '.' {
		return 0, false, errWrongValueForType.GenWithStackByArgs("string", val, "inet_aton")
	}

	var (
		byteResult, result uint64
		dotCount           int
	)
	for _, c := range val {
		if c >= '0' && c <= '9' {
			digit := uint64(c - '0')
			byteResult = byteResult*10 + digit
			if byteResult > 255 {
				return 0, false, errWrongValueForType.GenWithStackByArgs("string", val, "inet_aton")
			}
		} else if c == '.' {
			dotCount++
			if dotCount > 3 {
				return 0, false, errWrongValueForType.GenWithStackByArgs("string", val, "inet_aton")
			}
			result = (result << 8) + byteResult
			byteResult = 0
		} else {
			return 0, false, errWrongValueForType.GenWithStackByArgs("string", val, "inet_aton")
		}
	}
	// 127 		-> 0.0.0.127
	// 127.255 	-> 127.0.0.255
	// 127.256	-> NULL
	// 127.2.1	-> 127.2.0.1
	switch dotCount {
	case 1:
		result <<= 8
		fallthrough
	case 2:
		result <<= 8
	}
	return int64((result << 8) + byteResult), false, nil
}

type inetNtoaFunctionClass struct {
	baseFunctionClass
}

func (c *inetNtoaFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString, types.ETInt)
	if err != nil {
		return nil, err
	}
	charset, collate := ctx.GetSessionVars().GetCharsetInfo()
	bf.tp.SetCharset(charset)
	bf.tp.SetCollate(collate)
	bf.tp.SetFlen(93)
	bf.tp.SetDecimal(0)
	sig := &builtinInetNtoaSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_InetNtoa)
	return sig, nil
}

type builtinInetNtoaSig struct {
	baseBuiltinFunc
}

func (b *builtinInetNtoaSig) Clone() builtinFunc {
	newSig := &builtinInetNtoaSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals a builtinInetNtoaSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_inet-ntoa
func (b *builtinInetNtoaSig) evalString(row chunk.Row) (string, bool, error) {
	val, isNull, err := b.args[0].EvalInt(b.ctx, row)
	if err != nil || isNull {
		return "", true, err
	}

	if val < 0 || uint64(val) > math.MaxUint32 {
		// not an IPv4 address.
		return "", true, nil
	}
	ip := make(net.IP, net.IPv4len)
	binary.BigEndian.PutUint32(ip, uint32(val))
	ipv4 := ip.To4()
	if ipv4 == nil {
		// Not a vaild ipv4 address.
		return "", true, nil
	}

	return ipv4.String(), false, nil
}

type inet6AtonFunctionClass struct {
	baseFunctionClass
}

func (c *inet6AtonFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(16)
	types.SetBinChsClnFlag(bf.tp)
	bf.tp.SetDecimal(0)
	sig := &builtinInet6AtonSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_Inet6Aton)
	return sig, nil
}

type builtinInet6AtonSig struct {
	baseBuiltinFunc
}

func (b *builtinInet6AtonSig) Clone() builtinFunc {
	newSig := &builtinInet6AtonSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals a builtinInet6AtonSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_inet6-aton
func (b *builtinInet6AtonSig) evalString(row chunk.Row) (string, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return "", true, err
	}

	if len(val) == 0 {
		return "", false, errWrongValueForType.GenWithStackByArgs("string", val, "inet_aton6")
	}

	ip := net.ParseIP(val)
	if ip == nil {
		return "", false, errWrongValueForType.GenWithStackByArgs("string", val, "inet_aton6")
	}

	var isMappedIpv6 bool
	if ip.To4() != nil && strings.Contains(val, ":") {
		// mapped ipv6 address.
		isMappedIpv6 = true
	}

	var result []byte
	if isMappedIpv6 || ip.To4() == nil {
		result = make([]byte, net.IPv6len)
	} else {
		result = make([]byte, net.IPv4len)
	}

	if isMappedIpv6 {
		copy(result[12:], ip.To4())
		result[11] = 0xff
		result[10] = 0xff
	} else if ip.To4() == nil {
		copy(result, ip.To16())
	} else {
		copy(result, ip.To4())
	}

	return string(result), false, nil
}

type inet6NtoaFunctionClass struct {
	baseFunctionClass
}

func (c *inet6NtoaFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString, types.ETString)
	if err != nil {
		return nil, err
	}
	charset, collate := ctx.GetSessionVars().GetCharsetInfo()
	bf.tp.SetCharset(charset)
	bf.tp.SetCollate(collate)
	bf.tp.SetFlen(117)
	bf.tp.SetDecimal(0)
	sig := &builtinInet6NtoaSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_Inet6Ntoa)
	return sig, nil
}

type builtinInet6NtoaSig struct {
	baseBuiltinFunc
}

func (b *builtinInet6NtoaSig) Clone() builtinFunc {
	newSig := &builtinInet6NtoaSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals a builtinInet6NtoaSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_inet6-ntoa
func (b *builtinInet6NtoaSig) evalString(row chunk.Row) (string, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return "", true, err
	}
	ip := net.IP(val).String()
	if len(val) == net.IPv6len && !strings.Contains(ip, ":") {
		ip = fmt.Sprintf("::ffff:%s", ip)
	}

	if net.ParseIP(ip) == nil {
		return "", true, nil
	}

	return ip, false, nil
}

type isFreeLockFunctionClass struct {
	baseFunctionClass
}

func (c *isFreeLockFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", "IS_FREE_LOCK")
}

type isIPv4FunctionClass struct {
	baseFunctionClass
}

func (c *isIPv4FunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(1)
	sig := &builtinIsIPv4Sig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_IsIPv4)
	return sig, nil
}

type builtinIsIPv4Sig struct {
	baseBuiltinFunc
}

func (b *builtinIsIPv4Sig) Clone() builtinFunc {
	newSig := &builtinIsIPv4Sig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinIsIPv4Sig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_is-ipv4
func (b *builtinIsIPv4Sig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return 0, err != nil, err
	}
	if isIPv4(val) {
		return 1, false, nil
	}
	return 0, false, nil
}

// isIPv4 checks IPv4 address which satisfying the format A.B.C.D(0<=A/B/C/D<=255).
// Mapped IPv6 address like '::ffff:1.2.3.4' would return false.
func isIPv4(ip string) bool {
	// acc: keep the decimal value of each segment under check, which should between 0 and 255 for valid IPv4 address.
	// pd: sentinel for '.'
	dots, acc, pd := 0, 0, true
	for _, c := range ip {
		switch {
		case '0' <= c && c <= '9':
			acc = acc*10 + int(c-'0')
			pd = false
		case c == '.':
			dots++
			if dots > 3 || acc > 255 || pd {
				return false
			}
			acc, pd = 0, true
		default:
			return false
		}
	}
	if dots != 3 || acc > 255 || pd {
		return false
	}
	return true
}

type isIPv4CompatFunctionClass struct {
	baseFunctionClass
}

func (c *isIPv4CompatFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(1)
	sig := &builtinIsIPv4CompatSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_IsIPv4Compat)
	return sig, nil
}

type builtinIsIPv4CompatSig struct {
	baseBuiltinFunc
}

func (b *builtinIsIPv4CompatSig) Clone() builtinFunc {
	newSig := &builtinIsIPv4CompatSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals Is_IPv4_Compat
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_is-ipv4-compat
func (b *builtinIsIPv4CompatSig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return 0, err != nil, err
	}

	ipAddress := []byte(val)
	if len(ipAddress) != net.IPv6len {
		// Not an IPv6 address, return false
		return 0, false, nil
	}

	prefixCompat := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
	if !bytes.HasPrefix(ipAddress, prefixCompat) {
		return 0, false, nil
	}
	return 1, false, nil
}

type isIPv4MappedFunctionClass struct {
	baseFunctionClass
}

func (c *isIPv4MappedFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(1)
	sig := &builtinIsIPv4MappedSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_IsIPv4Mapped)
	return sig, nil
}

type builtinIsIPv4MappedSig struct {
	baseBuiltinFunc
}

func (b *builtinIsIPv4MappedSig) Clone() builtinFunc {
	newSig := &builtinIsIPv4MappedSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals Is_IPv4_Mapped
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_is-ipv4-mapped
func (b *builtinIsIPv4MappedSig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return 0, err != nil, err
	}

	ipAddress := []byte(val)
	if len(ipAddress) != net.IPv6len {
		// Not an IPv6 address, return false
		return 0, false, nil
	}

	prefixMapped := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
	if !bytes.HasPrefix(ipAddress, prefixMapped) {
		return 0, false, nil
	}
	return 1, false, nil
}

type isIPv6FunctionClass struct {
	baseFunctionClass
}

func (c *isIPv6FunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(1)
	sig := &builtinIsIPv6Sig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_IsIPv6)
	return sig, nil
}

type builtinIsIPv6Sig struct {
	baseBuiltinFunc
}

func (b *builtinIsIPv6Sig) Clone() builtinFunc {
	newSig := &builtinIsIPv6Sig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinIsIPv6Sig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_is-ipv6
func (b *builtinIsIPv6Sig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return 0, err != nil, err
	}
	ip := net.ParseIP(val)
	if ip != nil && !isIPv4(val) {
		return 1, false, nil
	}
	return 0, false, nil
}

type isUsedLockFunctionClass struct {
	baseFunctionClass
}

func (c *isUsedLockFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", "IS_USED_LOCK")
}

type isUUIDFunctionClass struct {
	baseFunctionClass
}

func (c *isUUIDFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETString)
	if err != nil {
		return nil, err
	}
	bf.tp.SetFlen(1)
	sig := &builtinIsUUIDSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_IsUUID)
	return sig, nil
}

type builtinIsUUIDSig struct {
	baseBuiltinFunc
}

func (b *builtinIsUUIDSig) Clone() builtinFunc {
	newSig := &builtinIsUUIDSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinIsUUIDSig.
// See https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-uuid
func (b *builtinIsUUIDSig) evalInt(row chunk.Row) (int64, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if err != nil || isNull {
		return 0, isNull, err
	}
	if _, err = uuid.Parse(val); err != nil {
		return 0, false, nil
	}
	return 1, false, nil
}

type masterPosWaitFunctionClass struct {
	baseFunctionClass
}

func (c *masterPosWaitFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", "MASTER_POS_WAIT")
}

type nameConstFunctionClass struct {
	baseFunctionClass
}

func (c *nameConstFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	argTp := args[1].GetType().EvalType()
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, argTp, types.ETString, argTp)
	if err != nil {
		return nil, err
	}
	*bf.tp = *args[1].GetType()
	var sig builtinFunc
	switch argTp {
	case types.ETDecimal:
		sig = &builtinNameConstDecimalSig{bf}
	case types.ETDuration:
		sig = &builtinNameConstDurationSig{bf}
	case types.ETInt:
		bf.tp.SetDecimal(0)
		sig = &builtinNameConstIntSig{bf}
	case types.ETJson:
		sig = &builtinNameConstJSONSig{bf}
	case types.ETReal:
		sig = &builtinNameConstRealSig{bf}
	case types.ETString:
		bf.tp.SetDecimal(types.UnspecifiedLength)
		sig = &builtinNameConstStringSig{bf}
	case types.ETDatetime, types.ETTimestamp:
		bf.tp.SetCharset(mysql.DefaultCharset)
		bf.tp.SetCollate(mysql.DefaultCollationName)
		bf.tp.SetFlag(0)
		sig = &builtinNameConstTimeSig{bf}
	default:
		return nil, errIncorrectArgs.GenWithStackByArgs("NAME_CONST")
	}
	return sig, nil
}

type builtinNameConstDecimalSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstDecimalSig) Clone() builtinFunc {
	newSig := &builtinNameConstDecimalSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstDecimalSig) evalDecimal(row chunk.Row) (*types.MyDecimal, bool, error) {
	return b.args[1].EvalDecimal(b.ctx, row)
}

type builtinNameConstIntSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstIntSig) Clone() builtinFunc {
	newSig := &builtinNameConstIntSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstIntSig) evalInt(row chunk.Row) (int64, bool, error) {
	return b.args[1].EvalInt(b.ctx, row)
}

type builtinNameConstRealSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstRealSig) Clone() builtinFunc {
	newSig := &builtinNameConstRealSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstRealSig) evalReal(row chunk.Row) (float64, bool, error) {
	return b.args[1].EvalReal(b.ctx, row)
}

type builtinNameConstStringSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstStringSig) Clone() builtinFunc {
	newSig := &builtinNameConstStringSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstStringSig) evalString(row chunk.Row) (string, bool, error) {
	return b.args[1].EvalString(b.ctx, row)
}

type builtinNameConstJSONSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstJSONSig) Clone() builtinFunc {
	newSig := &builtinNameConstJSONSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstJSONSig) evalJSON(row chunk.Row) (types.BinaryJSON, bool, error) {
	return b.args[1].EvalJSON(b.ctx, row)
}

type builtinNameConstDurationSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstDurationSig) Clone() builtinFunc {
	newSig := &builtinNameConstDurationSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstDurationSig) evalDuration(row chunk.Row) (types.Duration, bool, error) {
	return b.args[1].EvalDuration(b.ctx, row)
}

type builtinNameConstTimeSig struct {
	baseBuiltinFunc
}

func (b *builtinNameConstTimeSig) Clone() builtinFunc {
	newSig := &builtinNameConstTimeSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

func (b *builtinNameConstTimeSig) evalTime(row chunk.Row) (types.Time, bool, error) {
	return b.args[1].EvalTime(b.ctx, row)
}

type releaseAllLocksFunctionClass struct {
	baseFunctionClass
}

func (c *releaseAllLocksFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt)
	if err != nil {
		return nil, err
	}
	sig := &builtinReleaseAllLocksSig{bf}
	bf.tp.SetFlen(1)
	return sig, nil
}

type builtinReleaseAllLocksSig struct {
	baseBuiltinFunc
}

func (b *builtinReleaseAllLocksSig) Clone() builtinFunc {
	newSig := &builtinReleaseAllLocksSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals a builtinReleaseAllLocksSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_release-all-locks
func (b *builtinReleaseAllLocksSig) evalInt(_ chunk.Row) (int64, bool, error) {
	count := b.ctx.ReleaseAllAdvisoryLocks()
	return int64(count), false, nil
}

type uuidFunctionClass struct {
	baseFunctionClass
}

func (c *uuidFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString)
	if err != nil {
		return nil, err
	}
	charset, collate := ctx.GetSessionVars().GetCharsetInfo()
	bf.tp.SetCharset(charset)
	bf.tp.SetCollate(collate)
	bf.tp.SetFlen(36)
	sig := &builtinUUIDSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_UUID)
	return sig, nil
}

type builtinUUIDSig struct {
	baseBuiltinFunc
}

func (b *builtinUUIDSig) Clone() builtinFunc {
	newSig := &builtinUUIDSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals a builtinUUIDSig.
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_uuid
func (b *builtinUUIDSig) evalString(_ chunk.Row) (d string, isNull bool, err error) {
	var id uuid.UUID
	id, err = uuid.NewUUID()
	if err != nil {
		return
	}
	d = id.String()
	return
}

type uuidShortFunctionClass struct {
	baseFunctionClass
}

func (c *uuidShortFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", "UUID_SHORT")
}

type vitessHashFunctionClass struct {
	baseFunctionClass
}

func (c *vitessHashFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETInt)
	if err != nil {
		return nil, err
	}

	bf.tp.SetFlen(20) //64 bit unsigned
	bf.tp.AddFlag(mysql.UnsignedFlag)
	types.SetBinChsClnFlag(bf.tp)

	sig := &builtinVitessHashSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_VitessHash)
	return sig, nil
}

type builtinVitessHashSig struct {
	baseBuiltinFunc
}

func (b *builtinVitessHashSig) Clone() builtinFunc {
	newSig := &builtinVitessHashSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals VITESS_HASH(int64).
func (b *builtinVitessHashSig) evalInt(row chunk.Row) (int64, bool, error) {
	shardKeyInt, isNull, err := b.args[0].EvalInt(b.ctx, row)
	if isNull || err != nil {
		return 0, true, err
	}
	var hashed uint64
	if hashed, err = vitess.HashUint64(uint64(shardKeyInt)); err != nil {
		return 0, true, err
	}
	return int64(hashed), false, nil
}

type uuidToBinFunctionClass struct {
	baseFunctionClass
}

func (c *uuidToBinFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	argTps := []types.EvalType{types.ETString}
	if len(args) == 2 {
		argTps = append(argTps, types.ETInt)
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString, argTps...)
	if err != nil {
		return nil, err
	}

	bf.tp.SetFlen(16)
	types.SetBinChsClnFlag(bf.tp)
	bf.tp.SetDecimal(0)
	sig := &builtinUUIDToBinSig{bf}
	return sig, nil
}

type builtinUUIDToBinSig struct {
	baseBuiltinFunc
}

func (b *builtinUUIDToBinSig) Clone() builtinFunc {
	newSig := &builtinUUIDToBinSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals UUID_TO_BIN(string_uuid, swap_flag).
// See https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_uuid-to-bin
func (b *builtinUUIDToBinSig) evalString(row chunk.Row) (string, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if isNull || err != nil {
		return "", isNull, err
	}

	u, err := uuid.Parse(val)
	if err != nil {
		return "", false, errWrongValueForType.GenWithStackByArgs("string", val, "uuid_to_bin")
	}
	bin, err := u.MarshalBinary()
	if err != nil {
		return "", false, errWrongValueForType.GenWithStackByArgs("string", val, "uuid_to_bin")
	}

	flag := int64(0)
	if len(b.args) == 2 {
		flag, isNull, err = b.args[1].EvalInt(b.ctx, row)
		if isNull {
			flag = 0
		}
		if err != nil {
			return "", false, err
		}
	}
	if flag != 0 {
		return swapBinaryUUID(bin), false, nil
	}
	return string(bin), false, nil
}

type binToUUIDFunctionClass struct {
	baseFunctionClass
}

func (c *binToUUIDFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	argTps := []types.EvalType{types.ETString}
	if len(args) == 2 {
		argTps = append(argTps, types.ETInt)
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString, argTps...)
	if err != nil {
		return nil, err
	}

	charset, collate := ctx.GetSessionVars().GetCharsetInfo()
	bf.tp.SetCharset(charset)
	bf.tp.SetCollate(collate)
	bf.tp.SetFlen(32)
	bf.tp.SetDecimal(0)
	sig := &builtinBinToUUIDSig{bf}
	return sig, nil
}

type builtinBinToUUIDSig struct {
	baseBuiltinFunc
}

func (b *builtinBinToUUIDSig) Clone() builtinFunc {
	newSig := &builtinBinToUUIDSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalString evals BIN_TO_UUID(binary_uuid, swap_flag).
// See https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_bin-to-uuid
func (b *builtinBinToUUIDSig) evalString(row chunk.Row) (string, bool, error) {
	val, isNull, err := b.args[0].EvalString(b.ctx, row)
	if isNull || err != nil {
		return "", isNull, err
	}

	var u uuid.UUID
	err = u.UnmarshalBinary([]byte(val))
	if err != nil {
		return "", false, errWrongValueForType.GenWithStackByArgs("string", val, "bin_to_uuid")
	}

	str := u.String()
	flag := int64(0)
	if len(b.args) == 2 {
		flag, isNull, err = b.args[1].EvalInt(b.ctx, row)
		if isNull {
			flag = 0
		}
		if err != nil {
			return "", false, err
		}
	}
	if flag != 0 {
		return swapStringUUID(str), false, nil
	}
	return str, false, nil
}

func swapBinaryUUID(bin []byte) string {
	buf := make([]byte, len(bin))
	copy(buf[0:2], bin[6:8])
	copy(buf[2:4], bin[4:6])
	copy(buf[4:8], bin[0:4])
	copy(buf[8:], bin[8:])
	return string(buf)
}

func swapStringUUID(str string) string {
	buf := make([]byte, len(str))
	copy(buf[0:4], str[9:13])
	copy(buf[4:8], str[14:18])
	copy(buf[8:9], str[8:9])
	copy(buf[9:13], str[4:8])
	copy(buf[13:14], str[13:14])
	copy(buf[14:18], str[0:4])
	copy(buf[18:], str[18:])
	return string(buf)
}

type tidbShardFunctionClass struct {
	baseFunctionClass
}

func (c *tidbShardFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) {
	if err := c.verifyArgs(args); err != nil {
		return nil, err
	}
	bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETInt, types.ETInt)
	if err != nil {
		return nil, err
	}

	bf.tp.SetFlen(4) //64 bit unsigned
	bf.tp.AddFlag(mysql.UnsignedFlag)
	types.SetBinChsClnFlag(bf.tp)

	sig := &builtinTidbShardSig{bf}
	sig.setPbCode(tipb.ScalarFuncSig_TiDBShard)
	return sig, nil
}

type builtinTidbShardSig struct {
	baseBuiltinFunc
}

func (b *builtinTidbShardSig) Clone() builtinFunc {
	newSig := &builtinTidbShardSig{}
	newSig.cloneFrom(&b.baseBuiltinFunc)
	return newSig
}

// evalInt evals tidb_shard(int64).
func (b *builtinTidbShardSig) evalInt(row chunk.Row) (int64, bool, error) {
	shardKeyInt, isNull, err := b.args[0].EvalInt(b.ctx, row)
	if isNull || err != nil {
		return 0, true, err
	}
	var hashed uint64
	if hashed, err = vitess.HashUint64(uint64(shardKeyInt)); err != nil {
		return 0, true, err
	}
	hashed = hashed % tidbShardBucketCount
	return int64(hashed), false, nil
}


text:
/*****************************************************************************************************************
 *    quickfix/hack until they fix this
 *    Created by vegar ringdal
 *
 ****************************************************************************************************************/
import {inject, customAttribute} from 'aurelia-framework';
import {VGrid} from './v-grid';

@customAttribute('v-image-fix')
@inject(Element, VGrid)
export class vGridAttributesImageFix {

  constructor(element, vGrid) {
    this.vGrid = vGrid;
    this.element = element;
  }

  bind(bindingContext, overrideContext) {
    this.bindingContext = bindingContext;
    this.overrideContext = overrideContext;

    let x = this.element.src;
    this.element.src = "";
    this.element.src = x;
  }

  attached() {

  }

}


text:
package it.cavallium.warppi.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.Rational;

import it.cavallium.warppi.Engine;
import it.cavallium.warppi.StaticVars;
import it.cavallium.warppi.gui.graphicengine.BinaryFont;
import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.FunctionOperator;
import it.cavallium.warppi.math.FunctionSingle;
import it.cavallium.warppi.math.functions.Division;
import it.cavallium.warppi.math.functions.Expression;
import it.cavallium.warppi.math.functions.Multiplication;
import it.cavallium.warppi.math.functions.Negative;
import it.cavallium.warppi.math.functions.Number;
import it.cavallium.warppi.math.functions.Subtraction;
import it.cavallium.warppi.math.functions.Sum;
import it.cavallium.warppi.math.functions.SumSubtraction;
import it.cavallium.warppi.math.functions.Variable;
import it.cavallium.warppi.math.functions.equations.Equation;
import it.cavallium.warppi.math.functions.equations.EquationsSystemPart;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;

public class Utils {

	public static final int scale = 24;
	public static final int displayScale = 8;
	public static final BigInteger maxFactor = BigInteger.valueOf(1000000L);

	public static final int scaleMode = BigDecimal.ROUND_HALF_UP;
	public static final RoundingMode scaleMode2 = RoundingMode.HALF_UP;
	public static final int maxAutoFractionDigits = 5;

	public static boolean newtMode = true;

	public static <T> boolean isInArray(final T ch, final T[] a) {
		return Arrays.stream(a).anyMatch(item -> ch.equals(item));
	}

	public static boolean isInArray(final char ch, final char[] a) {
		for (final char c : a) {
			if (c == ch) {
				return true;
			}
		}
		return false;
	}

	private static final String[] regexNormalSymbols = new String[] { "\\", ".", "[", "]", "{", "}", "(", ")", "*", "+", "-", "?", "^", "$", "|" };

	public static String ArrayToRegex(final String[] array) {
		String regex = null;
		for (final String symbol : array) {
			boolean contained = false;
			for (final String smb : Utils.regexNormalSymbols) {
				if (smb.equals(symbol)) {
					contained = true;
					break;
				}
			}
			if (contained) {
				if (regex != null) {
					regex += "|\\" + symbol;
				} else {
					regex = "\\" + symbol;
				}
			} else if (regex != null) {
				regex += "|" + symbol;
			} else {
				regex = symbol;
			}
		}
		return regex;
	}

	public static String ArrayToRegex(final char[] array) {
		String regex = null;
		for (final char symbol : array) {
			boolean contained = false;
			for (final String smb : Utils.regexNormalSymbols) {
				if (smb.equals(symbol + "")) {
					contained = true;
					break;
				}
			}
			if (contained) {
				if (regex != null) {
					regex += "|\\" + symbol;
				} else {
					regex = "\\" + symbol;
				}
			} else if (regex != null) {
				regex += "|" + symbol;
			} else {
				regex = symbol + "";
			}
		}
		return regex;
	}

	public static String[] concat(final String[] a, final String[] b) {
		final int aLen = a.length;
		final int bLen = b.length;
		final String[] c = new String[aLen + bLen];
		System.arraycopy(a, 0, c, 0, aLen);
		System.arraycopy(b, 0, c, aLen, bLen);
		return c;
	}

	public static char[] concat(final char[] a, final char[] b) {
		final int aLen = a.length;
		final int bLen = b.length;
		final char[] c = new char[aLen + bLen];
		System.arraycopy(a, 0, c, 0, aLen);
		System.arraycopy(b, 0, c, aLen, bLen);
		return c;
	}

	public static String[] add(final String[] a, final String b) {
		final int aLen = a.length;
		final String[] c = new String[aLen + 1];
		System.arraycopy(a, 0, c, 0, aLen);
		c[aLen] = b;
		return c;
	}

	public static char[] add(final char[] a, final char b) {
		final int aLen = a.length;
		final char[] c = new char[aLen + 1];
		System.arraycopy(a, 0, c, 0, aLen);
		c[aLen] = b;
		return c;
	}

	public static boolean areThereOnlySettedUpFunctionsSumsEquationsAndSystems(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) {
				if (fl.get(i) instanceof FunctionSingle) {
					if (((FunctionSingle) fl.get(i)).getParameter() == null) {
						return false;
					}
				} else if (fl.get(i) instanceof FunctionOperator) {
					if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) {
						return false;
					}
				} else {
					return false;
				}
			}
		}
		return true;
	}

	public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) {
				if (fl.get(i) instanceof FunctionSingle) {
					if (((FunctionSingle) fl.get(i)).getParameter() == null) {
						return false;
					}
				} else if (fl.get(i) instanceof FunctionOperator) {
					if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) {
						return false;
					}
				} else {
					return false;
				}
			}
		}
		return true;
	}

	public static boolean areThereOnlySettedUpFunctionsEquationsAndSystems(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) {
				if (fl.get(i) instanceof FunctionSingle) {
					if (((FunctionSingle) fl.get(i)).getParameter() == null) {
						return false;
					}
				} else if (fl.get(i) instanceof FunctionOperator) {
					if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) {
						return false;
					}
				} else {
					return false;
				}
			}
		}
		return true;
	}

	public static boolean areThereOnlySettedUpFunctionsAndSystems(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) {
				if (fl.get(i) instanceof FunctionSingle) {
					if (((FunctionSingle) fl.get(i)).getParameter() == null) {
						return false;
					}
				} else if (fl.get(i) instanceof FunctionOperator) {
					if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) {
						return false;
					}
				} else {
					return false;
				}
			}
		}
		return true;
	}

	public static boolean areThereOnlyEmptySNFunctions(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (fl.get(i) instanceof FunctionSingle) {
				if (((FunctionSingle) fl.get(i)).getParameter() == null) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean areThereOnlyEmptyNSNFunctions(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (fl.get(i) instanceof FunctionOperator && !(fl.get(i) instanceof Sum) && !(fl.get(i) instanceof SumSubtraction) && !(fl.get(i) instanceof Subtraction) && !(fl.get(i) instanceof Multiplication) && !(fl.get(i) instanceof Division)) {
				if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean areThereEmptyMultiplications(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (fl.get(i) instanceof Multiplication || fl.get(i) instanceof Division) {
				if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean areThereEmptySums(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction) {
				if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean areThereEmptySystems(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (fl.get(i) instanceof EquationsSystemPart) {
				if (((EquationsSystemPart) fl.get(i)).getParameter() == null) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean areThereOtherSettedUpFunctions(final List<Function> fl) {
		for (int i = 0; i < fl.size(); i++) {
			if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Expression || fl.get(i) instanceof FunctionSingle || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Division)) {
				if (fl.get(i) instanceof FunctionSingle) {
					if (((FunctionSingle) fl.get(i)).getParameter() == null) {
						return true;
					}
				} else if (fl.get(i) instanceof FunctionOperator) {
					if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) {
						return true;
					}
				} else {
					return true;
				}
			}
		}
		return false;
	}

	public static Rational getRational(final BigDecimal str) {
		try {
			return Utils.getRational(str.toString());
		} catch (final Error e) {
			//E' IMPOSSIBILE CHE VENGA THROWATO UN ERRORE
			return new Rational("0");
		}
	}

	public static Rational getRational(String str) throws Error {
		try {
			return new Rational(str);
		} catch (final NumberFormatException ex) {
			if (new BigDecimal(str).compareTo(new BigDecimal(8000.0)) < 0 && new BigDecimal(str).compareTo(new BigDecimal(-8000.0)) > 0) {
				if (str.equals("-")) {
					str = "-1";
				}
				final long bits = Double.doubleToLongBits(Double.parseDouble(str));

				final long sign = bits >>> 63;
				final long exponent = (bits >>> 52 ^ sign << 11) - 1023;
				final long fraction = bits << 12; // bits are "reversed" but that's
				// not a problem

				long a = 1L;
				long b = 1L;

				for (int i = 63; i >= 12; i--) {
					a = a * 2 + (fraction >>> i & 1);
					b *= 2;
				}

				if (exponent > 0) {
					a *= 1 << exponent;
				} else {
					b *= 1 << -exponent;
				}

				if (sign == 1) {
					a *= -1;
				}

				if (b == 0) {
					a = 0;
					b = 1;
				}

				return new Rational(new BigInteger(a + ""), new BigInteger(b + ""));
			} else {
				final BigDecimal original = new BigDecimal(str);

				final BigInteger numerator = original.unscaledValue();

				final BigInteger denominator = BigDecimalMath.pow(BigDecimal.TEN, new BigDecimal(original.scale())).toBigIntegerExact();

				return new Rational(numerator, denominator);
			}
		}
	}

	public static BigDecimal rationalToIrrationalString(final Rational r) {
		return BigDecimalMath.divideRound(new BigDecimal(r.numer()).setScale(Utils.scale, Utils.scaleMode), new BigDecimal(r.denom()).setScale(Utils.scale, Utils.scaleMode));
	}

	public static boolean equalsVariables(final List<Variable> variables, final List<Variable> variables2) {
		if (variables.size() != variables2.size()) {
			return false;
		} else {
			for (final Variable v : variables) {
				if (!variables2.contains(v)) {
					return false;
				}
			}
			return true;
		}
	}

	@Deprecated
	public static void writeSquareRoot(final Function var, final int x, final int y, final boolean small) {
//		var.setSmall(small);
//		final int w1 = var.getWidth();
//		final int h1 = var.getHeight();
//		final int wsegno = 5;
//		final int hsegno = h1 + 2;
//
//		var.draw(x + wsegno, y + (hsegno - h1), null, null);
//
//		Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawLine(x + 1, y + hsegno - 3, x + 1, y + hsegno - 3);
//		Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawLine(x + 2, y + hsegno - 2, x + 2, y + hsegno - 2);
//		Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawLine(x + 3, y + hsegno - 1, x + 3, y + hsegno - 1);
//		Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawLine(x + 3, y + (hsegno - 1) / 2 + 1, x + 3, y + hsegno - 1);
//		Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawLine(x + 4, y, x + 4, y + (hsegno - 1) / 2);
//		Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawLine(x + 4, y, x + 4 + 1 + w1 + 1, y);
	}

	public static final int getFontHeight() {
		return Utils.getFontHeight(false);
	}

	public static final BinaryFont getFont(final boolean small) {
		return Utils.getFont(small, StaticVars.zoomed);
	}

	public static final BinaryFont getFont(final boolean small, final boolean zoomed) {
		return Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[Utils.getFontIndex(small, zoomed)];
	}

	public static final int getFontIndex(final boolean small, final boolean zoomed) {
		if (small) {
			if (zoomed) {
				return 3;
			} else {
				return 1;
			}
		} else if (zoomed) {
			return 2;
		} else {
			return 0;
		}
	}

	public static final int getFontHeight(final boolean small) {
		return Utils.getFontHeight(small, StaticVars.zoomed);
	}

	public static final int getFontHeight(final boolean small, final boolean zoomed) {
		if (small) {
			if (zoomed) {
				return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[3];
			} else {
				return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[1];
			}
		} else if (zoomed) {
			return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[2];
		} else {
			return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[0];
		}
	}

	public static byte[] convertStreamToByteArray(final InputStream stream, final long size) throws IOException {

		// check to ensure that file size is not larger than Integer.MAX_VALUE.
		if (size > Integer.MAX_VALUE) {
			return new byte[0];
		}

		final byte[] buffer = new byte[(int) size];
		final ByteArrayOutputStream os = new ByteArrayOutputStream();

		int line = 0;
		// read bytes from stream, and store them in buffer
		while ((line = stream.read(buffer)) != -1) {
			// Writes bytes from byte array (buffer) into output stream.
			os.write(buffer, 0, line);
		}
		stream.close();
		os.flush();
		os.close();
		return os.toByteArray();
	}

	public static int[] realBytes(final byte[] bytes) {
		final int len = bytes.length;
		final int[] realbytes = new int[len];
		for (int i = 0; i < len; i++) {
			realbytes[i] = bytes[i] & 0xFF;
		}
		return realbytes;
	}

	public static Function[][] joinFunctionsResults(final List<Function> l1, final List<Function> l2) {
		final int size1 = l1.size();
		final int size2 = l2.size();
		int cur1 = 0;
		int cur2 = 0;
		final int total = size1 * size2;
		final Function[][] results = new Function[total][2];
		for (int i = 0; i < total; i++) {
			results[i] = new Function[] { l1.get(cur1), l2.get(cur2) };
			if (i % size2 == 0) {
				cur1 += 1;
			}
			if (i % size1 == 0) {
				cur2 += 1;
			}
			if (cur1 >= size1) {
				cur1 = 0;
			}
			if (cur2 >= size2) {
				cur2 = 0;
			}
		}
		return results;
	}

	public static Function[][] joinFunctionsResults(final ObjectArrayList<ObjectArrayList<Function>> ln) {
		final int[] sizes = new int[ln.size()];
		for (int i = 0; i < ln.size(); i++) {
			sizes[i] = ln.get(i).size();
		}
		final int[] curs = new int[sizes.length];
		int total = 0;
		for (int i = 0; i < ln.size(); i++) {
			if (i == 0) {
				total = sizes[i];
			} else {
				total *= sizes[i];
			}
		}
		final Function[][] results = new Function[total][sizes.length];
		for (int i = 0; i < total; i++) {
			results[i] = new Function[sizes.length];
			for (int j = 0; j < sizes.length; j++) {
				results[i][j] = ln.get(j).get(curs[j]);
			}
			for (int k = 0; k < sizes.length; k++) {
				if (i % sizes[k] == 0) {
					for (int l = 0; l < sizes.length; l++) {
						if (l != k) {
							curs[l] += 1;
						}
					}
				}
			}
			for (int k = 0; k < sizes.length; k++) {
				if (curs[k] >= sizes[k]) {
					curs[k] = 0;
				}
			}
		}
		return results;
	}

	public static boolean isNegative(final Function b) {
		if (b instanceof Negative) {
			return true;
		} else if (b instanceof Number && ((Number) b).getTerm().compareTo(BigDecimal.ZERO) < 0) {
			return true;
		}
		return false;
	}

	public static CharSequence multipleChars(final String string, final int i) {
		String result = "";
		for (int j = 0; j < i; j++) {
			result += string;
		}
		return result;
	}

	public static boolean isIntegerValue(final BigDecimal bd) {
		return bd.signum() == 0 || bd.scale() <= 0 || bd.stripTrailingZeros().scale() <= 0;
	}

	@SafeVarargs
	public static <T> String arrayToString(final T... data) {
		String sdata = "";
		for (final T o : data) {
			sdata += "," + o;
		}
		return sdata.substring(1);
	}

	public static String arrayToString(final boolean... data) {
		String sdata = "";
		for (final boolean o : data) {
			sdata += o ? 1 : 0;
		}
		return sdata;
	}

	public static boolean isWindows() {
		return Engine.getPlatform().getOsName().indexOf("win") >= 0;
	}

	public static <T> ObjectArrayList<T> newArrayList(final T o) {
		final ObjectArrayList<T> t = new ObjectArrayList<>();
		t.add(o);
		return t;
	}

	public static InputStream getResourceStreamSafe(final String string) throws IOException, URISyntaxException {
		try {
			return Engine.getPlatform().getStorageUtils().getResourceStream(string);
		} catch (final Exception ex) {
			return null;
		}
	}

	public static File getJarDirectory() {
		return new File("").getAbsoluteFile();
	}

	public static <T, U> U getOrDefault(final Map<T, U> enginesList, final T key, final U object) {
		if (enginesList.containsKey(key)) {
			return enginesList.get(key);
		} else {
			return object;
		}
	}
}


text:
#pragma once
#include <aws/sns/SNS_EXPORTS.h>
#include <aws/sns/SNSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace SNS
{
namespace Model
{

  /**
   *
Input for SetTopicAttributes action.

See Also:
   AWS
   * API Reference

   */
  class AWS_SNS_API SetTopicAttributesRequest : public SNSRequest
  {
  public:
    SetTopicAttributesRequest();
    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:
    /**
     *
The ARN of the topic to modify.

     */
    inline const Aws::String& GetTopicArn() const{ return m_topicArn; }

    /**
     *
The ARN of the topic to modify.

     */
    inline void SetTopicArn(const Aws::String& value) { m_topicArnHasBeenSet = true; m_topicArn = value; }

    /**
     *
The ARN of the topic to modify.

     */
    inline void SetTopicArn(Aws::String&& value) { m_topicArnHasBeenSet = true; m_topicArn = std::move(value); }

    /**
     *
The ARN of the topic to modify.

     */
    inline void SetTopicArn(const char* value) { m_topicArnHasBeenSet = true; m_topicArn.assign(value); }

    /**
     *
The ARN of the topic to modify.

     */
    inline SetTopicAttributesRequest& WithTopicArn(const Aws::String& value) { SetTopicArn(value); return *this;}

    /**
     *
The ARN of the topic to modify.

     */
    inline SetTopicAttributesRequest& WithTopicArn(Aws::String&& value) { SetTopicArn(std::move(value)); return *this;}

    /**
     *
The ARN of the topic to modify.

     */
    inline SetTopicAttributesRequest& WithTopicArn(const char* value) { SetTopicArn(value); return *this;}

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline const Aws::String& GetAttributeName() const{ return m_attributeName; }

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline void SetAttributeName(const Aws::String& value) { m_attributeNameHasBeenSet = true; m_attributeName = value; }

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline void SetAttributeName(Aws::String&& value) { m_attributeNameHasBeenSet = true; m_attributeName = std::move(value); }

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline void SetAttributeName(const char* value) { m_attributeNameHasBeenSet = true; m_attributeName.assign(value); }

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline SetTopicAttributesRequest& WithAttributeName(const Aws::String& value) { SetAttributeName(value); return *this;}

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline SetTopicAttributesRequest& WithAttributeName(Aws::String&& value) { SetAttributeName(std::move(value)); return *this;}

    /**
     *
The name of the attribute you want to set. Only a subset of the topic's
     * attributes are mutable.

Valid values: Policy |
     * DisplayName | DeliveryPolicy

     */
    inline SetTopicAttributesRequest& WithAttributeName(const char* value) { SetAttributeName(value); return *this;}

    /**
     *
The new value for the attribute.

     */
    inline const Aws::String& GetAttributeValue() const{ return m_attributeValue; }

    /**
     *
The new value for the attribute.

     */
    inline void SetAttributeValue(const Aws::String& value) { m_attributeValueHasBeenSet = true; m_attributeValue = value; }

    /**
     *
The new value for the attribute.

     */
    inline void SetAttributeValue(Aws::String&& value) { m_attributeValueHasBeenSet = true; m_attributeValue = std::move(value); }

    /**
     *
The new value for the attribute.

     */
    inline void SetAttributeValue(const char* value) { m_attributeValueHasBeenSet = true; m_attributeValue.assign(value); }

    /**
     *
The new value for the attribute.

     */
    inline SetTopicAttributesRequest& WithAttributeValue(const Aws::String& value) { SetAttributeValue(value); return *this;}

    /**
     *
The new value for the attribute.

     */
    inline SetTopicAttributesRequest& WithAttributeValue(Aws::String&& value) { SetAttributeValue(std::move(value)); return *this;}

    /**
     *
The new value for the attribute.

     */
    inline SetTopicAttributesRequest& WithAttributeValue(const char* value) { SetAttributeValue(value); return *this;}

  private:
    Aws::String m_topicArn;
    bool m_topicArnHasBeenSet;
    Aws::String m_attributeName;
    bool m_attributeNameHasBeenSet;
    Aws::String m_attributeValue;
    bool m_attributeValueHasBeenSet;
  };

} // namespace Model
} // namespace SNS
} // namespace Aws


text:
package de.deutschepost.rs.gr.eval.springboot.sse.async;

import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import de.deutschepost.rs.gr.eval.springboot.sse.async.model.IAsynchJob;

public class AsyncJobMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

	public boolean supportsReturnType(MethodParameter returnType) {
		return supportsReturnType(returnType.getParameterType());
	}

	private static boolean supportsReturnType(Class<?> returnType) {
		return IAsynchJob.class.isAssignableFrom(returnType);
	}

	@Override public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			return;
		}

		if(!supportsReturnType(returnValue.getClass())) {
			throw new IllegalStateException("Unexpected return value type: " + returnValue);
		}
		IAsynchJob<?> asyncJob= (IAsynchJob)returnValue;

		//String viewName = "hello";
		//String viewName = "async-redirect";
		String viewName= "redirect:/keepalive/1.async";

		mavContainer.setViewName(viewName);
		mavContainer.addAttribute("jobId",asyncJob.getId());
		mavContainer.setRedirectModelScenario(true);

	}

}


text:
package com.amazonaws.services.connect.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * A HistoricalMetricData object than contains a Metric and a Value.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HistoricalMetricData implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * A HistoricalMetric object.
     *

     */
    private HistoricalMetric metric;
    /**
     *

     * The Value of the metric.
     *

     */
    private Double value;

    /**
     *

     * A HistoricalMetric object.
     *

     *
     * @param metric
     *        A HistoricalMetric object.
     */

    public void setMetric(HistoricalMetric metric) {
        this.metric = metric;
    }

    /**
     *

     * A HistoricalMetric object.
     *

     *
     * @return A HistoricalMetric object.
     */

    public HistoricalMetric getMetric() {
        return this.metric;
    }

    /**
     *

     * A HistoricalMetric object.
     *

     *
     * @param metric
     *        A HistoricalMetric object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HistoricalMetricData withMetric(HistoricalMetric metric) {
        setMetric(metric);
        return this;
    }

    /**
     *

     * The Value of the metric.
     *

     *
     * @param value
     *        The Value of the metric.
     */

    public void setValue(Double value) {
        this.value = value;
    }

    /**
     *

     * The Value of the metric.
     *

     *
     * @return The Value of the metric.
     */

    public Double getValue() {
        return this.value;
    }

    /**
     *

     * The Value of the metric.
     *

     *
     * @param value
     *        The Value of the metric.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HistoricalMetricData withValue(Double value) {
        setValue(value);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getMetric() != null)
            sb.append("Metric: ").append(getMetric()).append(",");
        if (getValue() != null)
            sb.append("Value: ").append(getValue());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof HistoricalMetricData == false)
            return false;
        HistoricalMetricData other = (HistoricalMetricData) obj;
        if (other.getMetric() == null ^ this.getMetric() == null)
            return false;
        if (other.getMetric() != null && other.getMetric().equals(this.getMetric()) == false)
            return false;
        if (other.getValue() == null ^ this.getValue() == null)
            return false;
        if (other.getValue() != null && other.getValue().equals(this.getValue()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getMetric() == null) ? 0 : getMetric().hashCode());
        hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode());
        return hashCode;
    }

    @Override
    public HistoricalMetricData clone() {
        try {
            return (HistoricalMetricData) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.connect.model.transform.HistoricalMetricDataMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
#include "ch.h"
#include "test.h"

/**
 * @page test_mbox Mailboxes test
 *
 * File: @ref testmbox.c
 *
 *
Description

 * This module implements the test sequence for the @ref mailboxes subsystem.
 *
 *
Objective

 * Objective of the test module is to cover 100% of the @ref mailboxes
 * subsystem code.

 * Note that the @ref mailboxes subsystem depends on the @ref semaphores
 * subsystem that has to met its testing objectives as well.
 *
 *
Preconditions

 * The module requires the following kernel options:
 * - @p CH_CFG_USE_MAILBOXES
 * .
 * In case some of the required options are not enabled then some or all tests
 * may be skipped.
 *
 *
Test Cases

 * - @subpage test_mbox_001
 * .
 * @file testmbox.c
 * @brief Mailboxes test source file
 * @file testmbox.h
 * @brief Mailboxes header file
 */

#if CH_CFG_USE_MAILBOXES || defined(__DOXYGEN__)

#define ALLOWED_DELAY MS2ST(5)
#define MB_SIZE 5

/*
 * Note, the static initializers are not really required because the
 * variables are explicitly initialized in each test case. It is done in order
 * to test the macros.
 */
static MAILBOX_DECL(mb1, test.wa.T0, MB_SIZE);

/**
 * @page test_mbox_001 Queuing and timeouts
 *
 *
Description

 * Messages are posted/fetched from a mailbox in carefully designed sequences
 * in order to stimulate all the possible code paths inside the mailbox.

 * The test expects to find a consistent mailbox status after each operation.
 */

static void mbox1_setup(void) {

  chMBObjectInit(&mb1, (msg_t *)test.wa.T0, MB_SIZE);
}

static void mbox1_execute(void) {
  msg_t msg1, msg2;
  unsigned i;

  /*
   * Testing initial space.
   */
  test_assert_lock(1, chMBGetFreeCountI(&mb1) == MB_SIZE, "wrong size");

  /*
   * Testing enqueuing and backward circularity.
   */
  for (i = 0; i < MB_SIZE - 1; i++) {
    msg1 = chMBPost(&mb1, 'B' + i, TIME_INFINITE);
    test_assert(2, msg1 == MSG_OK, "wrong wake-up message");
  }
  msg1 = chMBPostAhead(&mb1, 'A', TIME_INFINITE);
  test_assert(3, msg1 == MSG_OK, "wrong wake-up message");

  /*
   * Testing post timeout.
   */
  msg1 = chMBPost(&mb1, 'X', 1);
  test_assert(4, msg1 == MSG_TIMEOUT, "wrong wake-up message");
  chSysLock();
  msg1 = chMBPostI(&mb1, 'X');
  chSysUnlock();
  test_assert(5, msg1 == MSG_TIMEOUT, "wrong wake-up message");
  msg1 = chMBPostAhead(&mb1, 'X', 1);
  test_assert(6, msg1 == MSG_TIMEOUT, "wrong wake-up message");
  chSysLock();
  msg1 = chMBPostAheadI(&mb1, 'X');
  chSysUnlock();
  test_assert(7, msg1 == MSG_TIMEOUT, "wrong wake-up message");

  /*
   * Testing final conditions.
   */
  test_assert_lock(8, chMBGetFreeCountI(&mb1) == 0, "still empty");
  test_assert_lock(9, chMBGetUsedCountI(&mb1) == MB_SIZE, "not full");
  test_assert_lock(10, mb1.mb_rdptr == mb1.mb_wrptr, "pointers not aligned");

  /*
   * Testing dequeuing.
   */
  for (i = 0; i < MB_SIZE; i++) {
    msg1 = chMBFetch(&mb1, &msg2, TIME_INFINITE);
    test_assert(11, msg1 == MSG_OK, "wrong wake-up message");
    test_emit_token(msg2);
  }
  test_assert_sequence(12, "ABCDE");

  /*
   * Testing buffer circularity.
   */
  msg1 = chMBPost(&mb1, 'B' + i, TIME_INFINITE);
  test_assert(13, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBFetch(&mb1, &msg2, TIME_INFINITE);
  test_assert(14, msg1 == MSG_OK, "wrong wake-up message");
  test_assert(15, mb1.mb_buffer == mb1.mb_wrptr, "write pointer not aligned to base");
  test_assert(16, mb1.mb_buffer == mb1.mb_rdptr, "read pointer not aligned to base");

  /*
   * Testing fetch timeout.
   */
  msg1 = chMBFetch(&mb1, &msg2, 1);
  test_assert(17, msg1 == MSG_TIMEOUT, "wrong wake-up message");
  chSysLock();
  msg1 = chMBFetchI(&mb1, &msg2);
  chSysUnlock();
  test_assert(18, msg1 == MSG_TIMEOUT, "wrong wake-up message");

  /*
   * Testing final conditions.
   */
  test_assert_lock(19, chMBGetFreeCountI(&mb1) == MB_SIZE, "not empty");
  test_assert_lock(20, chMBGetUsedCountI(&mb1) == 0, "still full");
  test_assert_lock(21, mb1.mb_rdptr == mb1.mb_wrptr, "pointers not aligned");

  /*
   * Testing I-Class.
   */
  chSysLock();
  msg1 = chMBPostI(&mb1, 'A');
  test_assert(22, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostI(&mb1, 'B');
  test_assert(23, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostI(&mb1, 'C');
  test_assert(24, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostI(&mb1, 'D');
  test_assert(25, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostI(&mb1, 'E');
  chSysUnlock();
  test_assert(26, msg1 == MSG_OK, "wrong wake-up message");
  test_assert(27, mb1.mb_rdptr == mb1.mb_wrptr, "pointers not aligned");
  for (i = 0; i < MB_SIZE; i++) {
    chSysLock();
    msg1 = chMBFetchI(&mb1, &msg2);
    chSysUnlock();
    test_assert(28, msg1 == MSG_OK, "wrong wake-up message");
    test_emit_token(msg2);
  }
  test_assert_sequence(29, "ABCDE");
  test_assert_lock(30, chMBGetFreeCountI(&mb1) == MB_SIZE, "not empty");
  test_assert_lock(31, chMBGetUsedCountI(&mb1) == 0, "still full");
  test_assert(32, mb1.mb_rdptr == mb1.mb_wrptr, "pointers not aligned");

  chSysLock();
  msg1 = chMBPostAheadI(&mb1, 'E');
  test_assert(33, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostAheadI(&mb1, 'D');
  test_assert(34, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostAheadI(&mb1, 'C');
  test_assert(35, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostAheadI(&mb1, 'B');
  test_assert(36, msg1 == MSG_OK, "wrong wake-up message");
  msg1 = chMBPostAheadI(&mb1, 'A');
  chSysUnlock();
  test_assert(37, msg1 == MSG_OK, "wrong wake-up message");
  test_assert(38, mb1.mb_rdptr == mb1.mb_wrptr, "pointers not aligned");
  for (i = 0; i < MB_SIZE; i++) {
    chSysLock();
    msg1 = chMBFetchI(&mb1, &msg2);
    chSysUnlock();
    test_assert(39, msg1 == MSG_OK, "wrong wake-up message");
    test_emit_token(msg2);
  }
  test_assert_sequence(40, "ABCDE");
  test_assert_lock(41, chMBGetFreeCountI(&mb1) == MB_SIZE, "not empty");
  test_assert_lock(42, chMBGetUsedCountI(&mb1) == 0, "still full");
  test_assert(43, mb1.mb_rdptr == mb1.mb_wrptr, "pointers not aligned");

  /*
   * Testing reset.
   */
  chMBReset(&mb1);

  /*
   * Re-testing final conditions.
   */
  test_assert_lock(44, chMBGetFreeCountI(&mb1) == MB_SIZE, "not empty");
  test_assert_lock(45, chMBGetUsedCountI(&mb1) == 0, "still full");
  test_assert_lock(46, mb1.mb_buffer == mb1.mb_wrptr, "write pointer not aligned to base");
  test_assert_lock(47, mb1.mb_buffer == mb1.mb_rdptr, "read pointer not aligned to base");
}

ROMCONST struct testcase testmbox1 = {
  "Mailboxes, queuing and timeouts",
  mbox1_setup,
  NULL,
  mbox1_execute
};

#endif /* CH_CFG_USE_MAILBOXES */

/**
 * @brief   Test sequence for mailboxes.
 */
ROMCONST struct testcase * ROMCONST patternmbox[] = {
#if CH_CFG_USE_MAILBOXES || defined(__DOXYGEN__)
  &testmbox1,
#endif
  NULL
};


text:
namespace Divergent.Shipping.Data.Models
{
    public class ShippingInfo
    {
        public int Id { get; set; }
        public int OrderId { get; internal set; }
        public string Courier { get; internal set; }
        public string Status { get; internal set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2013 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
	<identity>
		<version number="$Revision: 9229 $"/>
		<generation date="$Date: 2013-08-18 23:26:52 -0500 (Sun, 18 Aug 2013) $"/>
		<language type="sr"/>
		<script type="Latn"/>
		<territory type="XK"/>
	</identity>
</ldml>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
	public class Communicate : ICommunicate
	{
		public string Echo(string content)
		{
			return string.Concat("Echo: ", content);
		}
	}
}


text:
var P = require('bluebird'),
	_ = require('lodash');

// plugin used for looping through an entire collection using streams
// it is promise based, resolving once all items in the collection have resolved their item work function
exports.streams = function(schema, options){

	schema.statics.eachStream = function(query, worker){

		return new P(function(resolve, reject){
			var stream = query.stream();

			stream.on('data', function(item){
				stream.pause();
				P.resolve(worker(item)).finally(function(){
					stream.resume();
				});
			}).on('error', function(err){
				reject(err);
			}).on('close', function(){
				resolve();
			});
		});
	};
}


text:
angular.module('ivh.multiSelect')
  .directive('ivhMultiSelectFilter', function() {
    'use strict';
    return {
      restrict: 'A',
      templateUrl: 'src/views/ivh-multi-select-filter.html'
    };
  });


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.ads.googleads.v12.errors",
    marshal="google.ads.googleads.v12",
    manifest={"FeedItemSetErrorEnum",},
)

class FeedItemSetErrorEnum(proto.Message):
    r"""Container for enum describing possible feed item set errors.
    """

    class FeedItemSetError(proto.Enum):
        r"""Enum describing possible feed item set errors."""
        UNSPECIFIED = 0
        UNKNOWN = 1
        FEED_ITEM_SET_REMOVED = 2
        CANNOT_CLEAR_DYNAMIC_FILTER = 3
        CANNOT_CREATE_DYNAMIC_FILTER = 4
        INVALID_FEED_TYPE = 5
        DUPLICATE_NAME = 6
        WRONG_DYNAMIC_FILTER_FOR_FEED_TYPE = 7
        DYNAMIC_FILTER_INVALID_CHAIN_IDS = 8

__all__ = tuple(sorted(__protobuf__.manifest))


text:
It's a very simple way to access *.ini File, the source code is written by C++/MFC

usage:

  // structor/constructor

  	CIniFile(LPCTSTR szFileName);
  	virtual ~CIniFile();

  // Open/Close file.

	BOOL Open(BOOL isReadOnly = FALSE);

	BOOL Close();

  // read/write method

	int GetKeyVal(CString szSectionName, CString szKeyName, int ipDefault);

	CString GetKeyVal(CString szSectionName, CString szKeyName, LPCTSTR szDefault);

 	BOOL WriteValue(LPCTSTR szSection, LPCTSTR szItem, LPCTSTR szValue, LPCTSTR szComment = NULL);


text:
import io
from setuptools import setup, find_packages

from upthor import __version__ as version

try:
    from pypandoc import convert

    def read_md(f):
        return convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")

    def read_md(f):
        return io.open(f, 'r', encoding='utf-8').read()

setup(
    name='django-upthor',
    version=version,
    description='django-upthor provides a django application for simple ajax file uploads.',
    long_description=read_md('README.md'),
    author="Thorgate",
    author_email='info@thorgate.eu',
    url='https://github.com/thorgate/django-upthor',
    packages=find_packages(),
    package_data={'upthor': [
        'static/upthor/css/*',
        'static/upthor/fonts/*',
        'static/upthor/js/*',
    ]},
    include_package_data=True,
    install_requires=[
        'Django',
        'Pillow',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
)


text:
Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wiyonoaten.simplelayerquickstartandroid" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
	<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="22" />
	<!-- Standard permissions -->
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.WAKE_LOCK" />
	<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
	<!-- Signature-only permissions -->
	<permission android:name="com.wiyonoaten.layerquickstartandroid.permission.LAYER_PUSH" android:protectionLevel="signature" />
	<uses-permission android:name="com.wiyonoaten.layerquickstartandroid.permission.LAYER_PUSH" />
	<permission android:name="com.wiyonoaten.layerquickstartandroid.permission.C2D_MESSAGE" android:protectionLevel="signature" />
	<uses-permission android:name="com.wiyonoaten.layerquickstartandroid.permission.C2D_MESSAGE" />
	<!-- LayerClient.sendLogs() permissions -->
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.READ_LOGS" />
	<application android:label="SimpleLayerQuickStartAndroid" android:icon="@drawable/Icon">
		<!-- Your custom "com.layer.sdk.PUSH" notification Receiver -->
		<receiver android:name=".LayerPushReceiver">
			<intent-filter>
				<action android:name="com.layer.sdk.PUSH" />
				<category android:name="com.wiyonoaten.layerquickstartandroid" />
			</intent-filter>
		</receiver>
		<!-- Layer's GCM Receiver and Service -->
		<receiver android:name="com.layer.sdk.services.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
			<intent-filter android:priority="950">
				<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
				<action android:name="com.google.android.c2dm.intent.RECEIVE" />
				<category android:name="com.wiyonoaten.layerquickstartandroid" />
			</intent-filter>
		</receiver>
		<service android:name="com.layer.sdk.services.GcmIntentService" />
	</application>
</manifest>


text:
var async = require("async");
var fs = require("fs");
var path = require("path");
var argv = require("minimist")(process.argv.slice(2));

var lesshint = require("./");
var files = argv._;

if (!files.length) {
    console.log("USAGE: lesshint [file ...] [--reporter module]");
    process.exit(1);
}

var reporter;
if (argv.reporter) {
    // Attempt to require the reporter as specified from the command line
    reporter = require(argv.reporter).reporter;
}

var options = {
    ignore: ["third_party"],
    reporter: reporter,
};

var callbackSeries = [];
files.forEach(function(file) {
    var code = fs.readFileSync(file, "utf-8");

    callbackSeries.push(function(next) {
        // chdir() into the file's directory to make relative @import
        // statements work
        var cwd = process.cwd();
        process.chdir(path.dirname(file));

        // Lint the file, sending a callback that will report the number of
        // errors to `async.series`
        lesshint(file, code, options, function(count) {
            // chdir back to the previous cwd
            process.chdir(cwd);
            next(null, count);
        });
    });
});

async.series(callbackSeries, function(err, counts) {
    var totalErrors = counts.reduce(function(a, b) {
        return a + b;
    }, 0);

    if (totalErrors) {
        process.exit(1);
    } else {
        process.exit(0);
    }
});


text:
Most of this is stock HTML and CSS from the Readme.io website.

For the most part, the only changes you will need to make are in Phoenix_files/custom.scss.

Make sure to install Sass and then run

    sass --watch Phoenix_files/custom.scss

That will make sure to update the css as you are working on it.


text:
package com.benromberg.cordonbleu.service.commit;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import com.benromberg.cordonbleu.data.dao.CommitHighlightCacheDao;
import com.benromberg.cordonbleu.data.model.Comment;
import com.benromberg.cordonbleu.data.model.Commit;
import com.benromberg.cordonbleu.data.model.CommitHighlightCache;
import com.benromberg.cordonbleu.data.model.CommitHighlightCacheFile;
import com.benromberg.cordonbleu.data.model.CommitHighlightCacheText;
import com.benromberg.cordonbleu.data.model.CommitId;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.inject.Inject;

import com.benromberg.cordonbleu.service.coderepository.CodeRepositoryService;
import com.benromberg.cordonbleu.service.coderepository.CommitDetail;
import com.benromberg.cordonbleu.service.coderepository.CommitFile;
import com.benromberg.cordonbleu.service.coderepository.CommitFileState;
import com.benromberg.cordonbleu.service.highlight.SyntaxHighlighter;
import com.benromberg.cordonbleu.service.highlight.TextHighlightResult;
import com.benromberg.cordonbleu.service.highlight.TextHighlightService;

public class CommitHighlightService {
    private static final int VERSION = 1;

    private final CommitHighlightCacheDao highlightCacheDao;
    private final CodeRepositoryService repositoryService;
    private final TextHighlightService textHighlightService;
    private final SyntaxHighlighter syntaxHighlighter;

    @Inject
    public CommitHighlightService(CommitHighlightCacheDao highlightCacheDao, CodeRepositoryService repositoryService,
            TextHighlightService textHighlightService, SyntaxHighlighter syntaxHighlighter) {
        this.highlightCacheDao = highlightCacheDao;
        this.repositoryService = repositoryService;
        this.textHighlightService = textHighlightService;
        this.syntaxHighlighter = syntaxHighlighter;
    }

    public HighlightedCommit highlight(Commit commit) {
        CommitDetail commitDetail = repositoryService.getCommitDetail(commit);
        CommitHighlightCache cachedCommit = highlightCacheDao.findById(commit.getId()).orElseGet(
                () -> cacheCommitHighlight(commitDetail));
        return highlightedCommit(commitDetail, cachedCommit);
    }

    private HighlightedCommit highlightedCommit(CommitDetail commitDetail, CommitHighlightCache cachedCommit) {
        return new HighlightedCommit(commitDetail, cachedCommit);
    }

    private CommitHighlightCache cacheCommitHighlight(CommitDetail commitDetail) {
        CommitHighlightCacheText message = highlightResultToCacheText(textHighlightService.textToHtml(commitDetail
                .getCommit().getMessage()));
        Map<String, CommitHighlightCacheText> comments = commitDetail.getCommit().getComments().stream()
                .collect(toMap(Comment::getId, comment -> toHighlightedText(comment.getText())));
        List<CommitHighlightCacheFile> files = commitDetail.getFiles().stream().map(file -> toHighlightedFile(file))
                .collect(toList());
        CommitHighlightCache commitHighlightCache = new CommitHighlightCache(commitDetail.getCommit().getId(), VERSION,
                files, message, comments);
        highlightCacheDao.insert(commitHighlightCache);
        return commitHighlightCache;
    }

    private CommitHighlightCacheFile toHighlightedFile(CommitFile file) {
        List<String> highlightedBefore = highlightFile(file.getStateBefore());
        List<String> highlightedAfter = highlightFile(file.getStateAfter());
        return new CommitHighlightCacheFile(highlightedBefore, highlightedAfter);
    }

    private List<String> highlightFile(Optional<CommitFileState> fileState) {
        if (!fileState.isPresent()) {
            return Collections.emptyList();
        }
        return syntaxHighlighter.highlight(fileState.get());
    }

    private CommitHighlightCacheText toHighlightedText(String text) {
        return highlightResultToCacheText(textHighlightService.markdownToHtml(text));
    }

    private CommitHighlightCacheText highlightResultToCacheText(TextHighlightResult result) {
        return new CommitHighlightCacheText(result.getText(), result.getReferencedUsers());
    }

    public void updateComment(CommitId commitId, String commentId, String text) {
        highlightCacheDao.updateComment(commitId, commentId, toHighlightedText(text));
    }
}


text:
// Copyright (C) 2010 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.sshd.commands;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.extensions.annotations.RequiresCapability;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.TopLevelResource;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.account.CreateAccount;
import com.google.gerrit.sshd.CommandMetaData;
import com.google.gerrit.sshd.SshCommand;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/** Create a new user account. **/
@RequiresCapability(GlobalCapability.CREATE_ACCOUNT)
@CommandMetaData(name = "create-account", description = "Create a new batch/role account")
final class CreateAccountCommand extends SshCommand {
  @Option(name = "--group", aliases = {"-g"}, metaVar = "GROUP", usage = "groups to add account to")
  private List<AccountGroup.Id> groups = new ArrayList<>();

  @Option(name = "--full-name", metaVar = "NAME", usage = "display name of the account")
  private String fullName;

  @Option(name = "--email", metaVar = "EMAIL", usage = "email address of the account")
  private String email;

  @Option(name = "--ssh-key", metaVar = "-|KEY", usage = "public key for SSH authentication")
  private String sshKey;

  @Option(name = "--http-password", metaVar = "PASSWORD", usage = "password for HTTP authentication")
  private String httpPassword;

  @Argument(index = 0, required = true, metaVar = "USERNAME", usage = "name of the user account")
  private String username;

  @Inject
  private CreateAccount.Factory createAccountFactory;

  @Override
  protected void run() throws OrmException, IOException, UnloggedFailure {
    CreateAccount.Input input = new CreateAccount.Input();
    input.username = username;
    input.email = email;
    input.name = fullName;
    input.sshKey = readSshKey();
    input.httpPassword = httpPassword;
    input.groups = Lists.transform(groups, new Function<AccountGroup.Id, String>() {
      @Override
      public String apply(AccountGroup.Id id) {
        return id.toString();
      }
    });
    try {
      createAccountFactory.create(username).apply(TopLevelResource.INSTANCE, input);
    } catch (RestApiException e) {
      throw die(e.getMessage());
    }
  }

  private String readSshKey() throws IOException {
    if (sshKey == null) {
      return null;
    }
    if ("-".equals(sshKey)) {
      sshKey = "";
      BufferedReader br =
          new BufferedReader(new InputStreamReader(in, UTF_8));
      String line;
      while ((line = br.readLine()) != null) {
        sshKey += line + "\n";
      }
    }
    return sshKey;
  }
}