text:
package ddl

import (
	"context"
	"strings"
	"sync/atomic"
	"time"

	"github.com/pingcap/errors"
	"github.com/pingcap/failpoint"
	"github.com/pingcap/kvproto/pkg/kvrpcpb"
	"github.com/pingcap/tidb/config"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/meta"
	"github.com/pingcap/tidb/meta/autoid"
	"github.com/pingcap/tidb/metrics"
	"github.com/pingcap/tidb/parser/ast"
	"github.com/pingcap/tidb/parser/charset"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/parser/mysql"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/table"
	"github.com/pingcap/tidb/table/tables"
	"github.com/pingcap/tidb/tablecodec"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util"
	"github.com/pingcap/tidb/util/logutil"
	decoder "github.com/pingcap/tidb/util/rowDecoder"
	"github.com/pingcap/tidb/util/timeutil"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/tikv/client-go/v2/oracle"
	"github.com/tikv/client-go/v2/tikv"
	"go.uber.org/zap"
)

const (
	// MaxCommentLength is exported for testing.
	MaxCommentLength = 1024
)

func buildIndexColumns(columns []*model.ColumnInfo, indexPartSpecifications []*ast.IndexPartSpecification) ([]*model.IndexColumn, error) {
	// Build offsets.
	idxParts := make([]*model.IndexColumn, 0, len(indexPartSpecifications))
	var col *model.ColumnInfo

	// The sum of length of all index columns.
	sumLength := 0
	for _, ip := range indexPartSpecifications {
		col = model.FindColumnInfo(columns, ip.Column.Name.L)
		if col == nil {
			return nil, errKeyColumnDoesNotExits.GenWithStack("column does not exist: %s", ip.Column.Name)
		}

		if err := checkIndexColumn(col, ip.Length); err != nil {
			return nil, err
		}

		indexColumnLength, err := getIndexColumnLength(col, ip.Length)
		if err != nil {
			return nil, err
		}
		sumLength += indexColumnLength

		// The sum of all lengths must be shorter than the max length for prefix.
		if sumLength > config.GetGlobalConfig().MaxIndexLength {
			return nil, errTooLongKey.GenWithStackByArgs(config.GetGlobalConfig().MaxIndexLength)
		}

		idxParts = append(idxParts, &model.IndexColumn{
			Name:   col.Name,
			Offset: col.Offset,
			Length: ip.Length,
		})
	}

	return idxParts, nil
}

func checkPKOnGeneratedColumn(tblInfo *model.TableInfo, indexPartSpecifications []*ast.IndexPartSpecification) (*model.ColumnInfo, error) {
	var lastCol *model.ColumnInfo
	for _, colName := range indexPartSpecifications {
		lastCol = getColumnInfoByName(tblInfo, colName.Column.Name.L)
		if lastCol == nil {
			return nil, errKeyColumnDoesNotExits.GenWithStackByArgs(colName.Column.Name)
		}
		// Virtual columns cannot be used in primary key.
		if lastCol.IsGenerated() && !lastCol.GeneratedStored {
			if lastCol.Hidden {
				return nil, ErrFunctionalIndexPrimaryKey
			}
			return nil, ErrUnsupportedOnGeneratedColumn.GenWithStackByArgs("Defining a virtual generated column as primary key")
		}
	}

	return lastCol, nil
}

func checkIndexPrefixLength(columns []*model.ColumnInfo, idxColumns []*model.IndexColumn, pkLenAppendToKey int) error {
	idxLen, err := indexColumnsLen(columns, idxColumns)
	if err != nil {
		return err
	}
	if idxLen+pkLenAppendToKey > config.GetGlobalConfig().MaxIndexLength {
		return errTooLongKey.GenWithStackByArgs(config.GetGlobalConfig().MaxIndexLength)
	}
	return nil
}

func checkIndexColumn(col *model.ColumnInfo, indexColumnLen int) error {
	if col.Flen == 0 && (types.IsTypeChar(col.FieldType.Tp) || types.IsTypeVarchar(col.FieldType.Tp)) {
		if col.Hidden {
			return errors.Trace(errWrongKeyColumnFunctionalIndex.GenWithStackByArgs(col.GeneratedExprString))
		}
		return errors.Trace(errWrongKeyColumn.GenWithStackByArgs(col.Name))
	}

	// JSON column cannot index.
	if col.FieldType.Tp == mysql.TypeJSON {
		if col.Hidden {
			return errFunctionalIndexOnJSONOrGeometryFunction
		}
		return errors.Trace(errJSONUsedAsKey.GenWithStackByArgs(col.Name.O))
	}

	// Length must be specified and non-zero for BLOB and TEXT column indexes.
	if types.IsTypeBlob(col.FieldType.Tp) {
		if indexColumnLen == types.UnspecifiedLength {
			if col.Hidden {
				return errFunctionalIndexOnBlob
			}
			return errors.Trace(errBlobKeyWithoutLength.GenWithStackByArgs(col.Name.O))
		}
		if indexColumnLen == types.ErrorLength {
			return errors.Trace(errKeyPart0.GenWithStackByArgs(col.Name.O))
		}
	}

	// Length can only be specified for specifiable types.
	if indexColumnLen != types.UnspecifiedLength && !types.IsTypePrefixable(col.FieldType.Tp) {
		return errors.Trace(errIncorrectPrefixKey)
	}

	// Key length must be shorter or equal to the column length.
	if indexColumnLen != types.UnspecifiedLength &&
		types.IsTypeChar(col.FieldType.Tp) {
		if col.Flen < indexColumnLen {
			return errors.Trace(errIncorrectPrefixKey)
		}
		// Length must be non-zero for char.
		if indexColumnLen == types.ErrorLength {
			return errors.Trace(errKeyPart0.GenWithStackByArgs(col.Name.O))
		}
	}

	if types.IsString(col.FieldType.Tp) {
		desc, err := charset.GetCharsetInfo(col.Charset)
		if err != nil {
			return err
		}
		indexColumnLen *= desc.Maxlen
	}
	// Specified length must be shorter than the max length for prefix.
	if indexColumnLen > config.GetGlobalConfig().MaxIndexLength {
		return errTooLongKey.GenWithStackByArgs(config.GetGlobalConfig().MaxIndexLength)
	}
	return nil
}

// getIndexColumnLength calculate the bytes number required in an index column.
func getIndexColumnLength(col *model.ColumnInfo, colLen int) (int, error) {
	length := types.UnspecifiedLength
	if colLen != types.UnspecifiedLength {
		length = colLen
	} else if col.Flen != types.UnspecifiedLength {
		length = col.Flen
	}

	switch col.Tp {
	case mysql.TypeBit:
		return (length + 7) >> 3, nil
	case mysql.TypeVarchar, mysql.TypeString, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeBlob, mysql.TypeLongBlob:
		// Different charsets occupy different numbers of bytes on each character.
		desc, err := charset.GetCharsetInfo(col.Charset)
		if err != nil {
			return 0, errUnsupportedCharset.GenWithStackByArgs(col.Charset, col.Collate)
		}
		return desc.Maxlen * length, nil
	case mysql.TypeTiny, mysql.TypeInt24, mysql.TypeLong, mysql.TypeLonglong, mysql.TypeDouble, mysql.TypeShort:
		return mysql.DefaultLengthOfMysqlTypes[col.Tp], nil
	case mysql.TypeFloat:
		if length <= mysql.MaxFloatPrecisionLength {
			return mysql.DefaultLengthOfMysqlTypes[mysql.TypeFloat], nil
		}
		return mysql.DefaultLengthOfMysqlTypes[mysql.TypeDouble], nil
	case mysql.TypeNewDecimal:
		return calcBytesLengthForDecimal(length), nil
	case mysql.TypeYear, mysql.TypeDate, mysql.TypeDuration, mysql.TypeDatetime, mysql.TypeTimestamp:
		return mysql.DefaultLengthOfMysqlTypes[col.Tp], nil
	default:
		return length, nil
	}
}

// Decimal using a binary format that packs nine decimal (base 10) digits into four bytes.
func calcBytesLengthForDecimal(m int) int {
	return (m / 9 * 4) + ((m%9)+1)/2
}

func buildIndexInfo(tblInfo *model.TableInfo, indexName model.CIStr, indexPartSpecifications []*ast.IndexPartSpecification, state model.SchemaState) (*model.IndexInfo, error) {
	if err := checkTooLongIndex(indexName); err != nil {
		return nil, errors.Trace(err)
	}

	idxColumns, err := buildIndexColumns(tblInfo.Columns, indexPartSpecifications)
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Create index info.
	idxInfo := &model.IndexInfo{
		Name:    indexName,
		Columns: idxColumns,
		State:   state,
	}
	return idxInfo, nil
}

func addIndexColumnFlag(tblInfo *model.TableInfo, indexInfo *model.IndexInfo) {
	if indexInfo.Primary {
		for _, col := range indexInfo.Columns {
			tblInfo.Columns[col.Offset].Flag |= mysql.PriKeyFlag
		}
		return
	}

	col := indexInfo.Columns[0]
	if indexInfo.Unique && len(indexInfo.Columns) == 1 {
		tblInfo.Columns[col.Offset].Flag |= mysql.UniqueKeyFlag
	} else {
		tblInfo.Columns[col.Offset].Flag |= mysql.MultipleKeyFlag
	}
}

func dropIndexColumnFlag(tblInfo *model.TableInfo, indexInfo *model.IndexInfo) {
	if indexInfo.Primary {
		for _, col := range indexInfo.Columns {
			tblInfo.Columns[col.Offset].Flag &= ^mysql.PriKeyFlag
		}
	} else if indexInfo.Unique && len(indexInfo.Columns) == 1 {
		tblInfo.Columns[indexInfo.Columns[0].Offset].Flag &= ^mysql.UniqueKeyFlag
	} else {
		tblInfo.Columns[indexInfo.Columns[0].Offset].Flag &= ^mysql.MultipleKeyFlag
	}

	col := indexInfo.Columns[0]
	// other index may still cover this col
	for _, index := range tblInfo.Indices {
		if index.Name.L == indexInfo.Name.L {
			continue
		}

		if index.Columns[0].Name.L != col.Name.L {
			continue
		}

		addIndexColumnFlag(tblInfo, index)
	}
}

func validateRenameIndex(from, to model.CIStr, tbl *model.TableInfo) (ignore bool, err error) {
	if fromIdx := tbl.FindIndexByName(from.L); fromIdx == nil {
		return false, errors.Trace(infoschema.ErrKeyNotExists.GenWithStackByArgs(from.O, tbl.Name))
	}
	// Take case-sensitivity into account, if `FromKey` and  `ToKey` are the same, nothing need to be changed
	if from.O == to.O {
		return true, nil
	}
	// If spec.FromKey.L == spec.ToKey.L, we operate on the same index(case-insensitive) and change its name (case-sensitive)
	// e.g: from `inDex` to `IndEX`. Otherwise, we try to rename an index to another different index which already exists,
	// that's illegal by rule.
	if toIdx := tbl.FindIndexByName(to.L); toIdx != nil && from.L != to.L {
		return false, errors.Trace(infoschema.ErrKeyNameDuplicate.GenWithStackByArgs(toIdx.Name.O))
	}
	return false, nil
}

func onRenameIndex(t *meta.Meta, job *model.Job) (ver int64, _ error) {
	tblInfo, from, to, err := checkRenameIndex(t, job)
	if err != nil || tblInfo == nil {
		return ver, errors.Trace(err)
	}

	idx := tblInfo.FindIndexByName(from.L)
	idx.Name = to
	if ver, err = updateVersionAndTableInfo(t, job, tblInfo, true); err != nil {
		job.State = model.JobStateCancelled
		return ver, errors.Trace(err)
	}
	job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tblInfo)
	return ver, nil
}

func validateAlterIndexVisibility(indexName model.CIStr, invisible bool, tbl *model.TableInfo) (bool, error) {
	if idx := tbl.FindIndexByName(indexName.L); idx == nil {
		return false, errors.Trace(infoschema.ErrKeyNotExists.GenWithStackByArgs(indexName.O, tbl.Name))
	} else if idx.Invisible == invisible {
		return true, nil
	}
	return false, nil
}

func onAlterIndexVisibility(t *meta.Meta, job *model.Job) (ver int64, _ error) {
	tblInfo, from, invisible, err := checkAlterIndexVisibility(t, job)
	if err != nil || tblInfo == nil {
		return ver, errors.Trace(err)
	}
	idx := tblInfo.FindIndexByName(from.L)
	idx.Invisible = invisible
	if ver, err = updateVersionAndTableInfoWithCheck(t, job, tblInfo, true); err != nil {
		job.State = model.JobStateCancelled
		return ver, errors.Trace(err)
	}
	job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tblInfo)
	return ver, nil
}

func getNullColInfos(tblInfo *model.TableInfo, indexInfo *model.IndexInfo) ([]*model.ColumnInfo, error) {
	nullCols := make([]*model.ColumnInfo, 0, len(indexInfo.Columns))
	for _, colName := range indexInfo.Columns {
		col := model.FindColumnInfo(tblInfo.Columns, colName.Name.L)
		if !mysql.HasNotNullFlag(col.Flag) || mysql.HasPreventNullInsertFlag(col.Flag) {
			nullCols = append(nullCols, col)
		}
	}
	return nullCols, nil
}

func checkPrimaryKeyNotNull(w *worker, sqlMode mysql.SQLMode, t *meta.Meta, job *model.Job,
	tblInfo *model.TableInfo, indexInfo *model.IndexInfo) (warnings []string, err error) {
	if !indexInfo.Primary {
		return nil, nil
	}

	dbInfo, err := checkSchemaExistAndCancelNotExistJob(t, job)
	if err != nil {
		return nil, err
	}
	nullCols, err := getNullColInfos(tblInfo, indexInfo)
	if err != nil {
		return nil, err
	}
	if len(nullCols) == 0 {
		return nil, nil
	}

	err = modifyColsFromNull2NotNull(w, dbInfo, tblInfo, nullCols, model.NewCIStr(""), false)
	if err == nil {
		return nil, nil
	}
	_, err = convertAddIdxJob2RollbackJob(t, job, tblInfo, indexInfo, err)
	// TODO: Support non-strict mode.
	// warnings = append(warnings, ErrWarnDataTruncated.GenWithStackByArgs(oldCol.Name.L, 0).Error())
	return nil, err
}

func updateHiddenColumns(tblInfo *model.TableInfo, idxInfo *model.IndexInfo, state model.SchemaState) {
	for _, col := range idxInfo.Columns {
		if tblInfo.Columns[col.Offset].Hidden {
			tblInfo.Columns[col.Offset].State = state
		}
	}
}

func (w *worker) onCreateIndex(d *ddlCtx, t *meta.Meta, job *model.Job, isPK bool) (ver int64, err error) {
	// Handle the rolling back job.
	if job.IsRollingback() {
		ver, err = onDropIndex(t, job)
		if err != nil {
			return ver, errors.Trace(err)
		}
		return ver, nil
	}

	// Handle normal job.
	schemaID := job.SchemaID
	tblInfo, err := getTableInfoAndCancelFaultJob(t, job, schemaID)
	if err != nil {
		return ver, errors.Trace(err)
	}

	var (
		unique                  bool
		global                  bool
		indexName               model.CIStr
		indexPartSpecifications []*ast.IndexPartSpecification
		indexOption             *ast.IndexOption
		sqlMode                 mysql.SQLMode
		warnings                []string
		hiddenCols              []*model.ColumnInfo
	)
	if isPK {
		// Notice: sqlMode and warnings is used to support non-strict mode.
		err = job.DecodeArgs(&unique, &indexName, &indexPartSpecifications, &indexOption, &sqlMode, &warnings, &global)
	} else {
		err = job.DecodeArgs(&unique, &indexName, &indexPartSpecifications, &indexOption, &hiddenCols, &global)
	}
	if err != nil {
		job.State = model.JobStateCancelled
		return ver, errors.Trace(err)
	}

	indexInfo := tblInfo.FindIndexByName(indexName.L)
	if indexInfo != nil && indexInfo.State == model.StatePublic {
		job.State = model.JobStateCancelled
		err = ErrDupKeyName.GenWithStack("index already exist %s", indexName)
		if isPK {
			err = infoschema.ErrMultiplePriKey
		}
		return ver, err
	}

	if indexInfo == nil {
		for _, hiddenCol := range hiddenCols {
			columnInfo := model.FindColumnInfo(tblInfo.Columns, hiddenCol.Name.L)
			if columnInfo != nil && columnInfo.State == model.StatePublic {
				// We already have a column with the same column name.
				job.State = model.JobStateCancelled
				// TODO: refine the error message
				return ver, infoschema.ErrColumnExists.GenWithStackByArgs(hiddenCol.Name)
			}
		}
	}

	if indexInfo == nil {
		if len(hiddenCols) > 0 {
			pos := &ast.ColumnPosition{Tp: ast.ColumnPositionNone}
			for _, hiddenCol := range hiddenCols {
				_, _, _, err = createColumnInfo(tblInfo, hiddenCol, pos)
				if err != nil {
					job.State = model.JobStateCancelled
					return ver, errors.Trace(err)
				}
			}
		}
		if err = checkAddColumnTooManyColumns(len(tblInfo.Columns)); err != nil {
			job.State = model.JobStateCancelled
			return ver, errors.Trace(err)
		}
		indexInfo, err = buildIndexInfo(tblInfo, indexName, indexPartSpecifications, model.StateNone)
		if err != nil {
			job.State = model.JobStateCancelled
			return ver, errors.Trace(err)
		}
		if indexOption != nil {
			indexInfo.Comment = indexOption.Comment
			if indexOption.Visibility == ast.IndexVisibilityInvisible {
				indexInfo.Invisible = true
			}
			if indexOption.Tp == model.IndexTypeInvalid {
				// Use btree as default index type.
				indexInfo.Tp = model.IndexTypeBtree
			} else {
				indexInfo.Tp = indexOption.Tp
			}
		} else {
			// Use btree as default index type.
			indexInfo.Tp = model.IndexTypeBtree
		}
		indexInfo.Primary = false
		if isPK {
			if _, err = checkPKOnGeneratedColumn(tblInfo, indexPartSpecifications); err != nil {
				job.State = model.JobStateCancelled
				return ver, err
			}
			indexInfo.Primary = true
		}
		indexInfo.Unique = unique
		indexInfo.Global = global
		indexInfo.ID = allocateIndexID(tblInfo)
		tblInfo.Indices = append(tblInfo.Indices, indexInfo)
		if err = checkTooManyIndexes(tblInfo.Indices); err != nil {
			job.State = model.JobStateCancelled
			return ver, errors.Trace(err)
		}
		// Here we need do this check before set state to `DeleteOnly`,
		// because if hidden columns has been set to `DeleteOnly`,
		// the `DeleteOnly` columns are missing when we do this check.
		if err := checkInvisibleIndexOnPK(tblInfo); err != nil {
			job.State = model.JobStateCancelled
			return ver, err
		}
		logutil.BgLogger().Info("[ddl] run add index job", zap.String("job", job.String()), zap.Reflect("indexInfo", indexInfo))
	}
	originalState := indexInfo.State
	switch indexInfo.State {
	case model.StateNone:
		// none -> delete only
		indexInfo.State = model.StateDeleteOnly
		updateHiddenColumns(tblInfo, indexInfo, model.StatePublic)
		ver, err = updateVersionAndTableInfoWithCheck(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, err
		}
		job.SchemaState = model.StateDeleteOnly
		metrics.GetBackfillProgressByLabel(metrics.LblAddIndex).Set(0)
	case model.StateDeleteOnly:
		// delete only -> write only
		indexInfo.State = model.StateWriteOnly
		_, err = checkPrimaryKeyNotNull(w, sqlMode, t, job, tblInfo, indexInfo)
		if err != nil {
			break
		}
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, err
		}
		job.SchemaState = model.StateWriteOnly
	case model.StateWriteOnly:
		// write only -> reorganization
		indexInfo.State = model.StateWriteReorganization
		_, err = checkPrimaryKeyNotNull(w, sqlMode, t, job, tblInfo, indexInfo)
		if err != nil {
			break
		}
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, err
		}
		// Initialize SnapshotVer to 0 for later reorganization check.
		job.SnapshotVer = 0
		job.SchemaState = model.StateWriteReorganization
	case model.StateWriteReorganization:
		// reorganization -> public
		tbl, err := getTable(d.store, schemaID, tblInfo)
		if err != nil {
			return ver, errors.Trace(err)
		}

		elements := []*meta.Element{{ID: indexInfo.ID, TypeKey: meta.IndexElementKey}}
		reorgInfo, err := getReorgInfo(d, t, job, tbl, elements)
		if err != nil || reorgInfo.first {
			// If we run reorg firstly, we should update the job snapshot version
			// and then run the reorg next time.
			return ver, errors.Trace(err)
		}

		err = w.runReorgJob(t, reorgInfo, tbl.Meta(), d.lease, func() (addIndexErr error) {
			defer util.Recover(metrics.LabelDDL, "onCreateIndex",
				func() {
					addIndexErr = errCancelledDDLJob.GenWithStack("add table `%v` index `%v` panic", tblInfo.Name, indexInfo.Name)
				}, false)
			return w.addTableIndex(tbl, indexInfo, reorgInfo)
		})
		if err != nil {
			if errWaitReorgTimeout.Equal(err) {
				// if timeout, we should return, check for the owner and re-wait job done.
				return ver, nil
			}
			if kv.ErrKeyExists.Equal(err) || errCancelledDDLJob.Equal(err) || errCantDecodeRecord.Equal(err) {
				logutil.BgLogger().Warn("[ddl] run add index job failed, convert job to rollback", zap.String("job", job.String()), zap.Error(err))
				ver, err = convertAddIdxJob2RollbackJob(t, job, tblInfo, indexInfo, err)
				if err1 := t.RemoveDDLReorgHandle(job, reorgInfo.elements); err1 != nil {
					logutil.BgLogger().Warn("[ddl] run add index job failed, convert job to rollback, RemoveDDLReorgHandle failed", zap.String("job", job.String()), zap.Error(err1))
				}
			}
			// Clean up the channel of notifyCancelReorgJob. Make sure it can't affect other jobs.
			w.reorgCtx.cleanNotifyReorgCancel()
			return ver, errors.Trace(err)
		}
		// Clean up the channel of notifyCancelReorgJob. Make sure it can't affect other jobs.
		w.reorgCtx.cleanNotifyReorgCancel()

		indexInfo.State = model.StatePublic
		// Set column index flag.
		addIndexColumnFlag(tblInfo, indexInfo)
		if isPK {
			if err = updateColsNull2NotNull(tblInfo, indexInfo); err != nil {
				return ver, errors.Trace(err)
			}
		}
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		// Finish this job.
		job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tblInfo)
	default:
		err = ErrInvalidDDLState.GenWithStackByArgs("index", tblInfo.State)
	}

	return ver, errors.Trace(err)
}

func onDropIndex(t *meta.Meta, job *model.Job) (ver int64, _ error) {
	tblInfo, indexInfo, err := checkDropIndex(t, job)
	if err != nil {
		return ver, errors.Trace(err)
	}

	dependentHiddenCols := make([]*model.ColumnInfo, 0)
	for _, indexColumn := range indexInfo.Columns {
		if tblInfo.Columns[indexColumn.Offset].Hidden {
			dependentHiddenCols = append(dependentHiddenCols, tblInfo.Columns[indexColumn.Offset])
		}
	}

	originalState := indexInfo.State
	switch indexInfo.State {
	case model.StatePublic:
		// public -> write only
		indexInfo.State = model.StateWriteOnly
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		job.SchemaState = model.StateWriteOnly
	case model.StateWriteOnly:
		// write only -> delete only
		indexInfo.State = model.StateDeleteOnly
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		job.SchemaState = model.StateDeleteOnly
	case model.StateDeleteOnly:
		// delete only -> reorganization
		indexInfo.State = model.StateDeleteReorganization
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		job.SchemaState = model.StateDeleteReorganization
	case model.StateDeleteReorganization:
		// reorganization -> absent
		if len(dependentHiddenCols) > 0 {
			firstHiddenOffset := dependentHiddenCols[0].Offset
			for i := 0; i < len(dependentHiddenCols); i++ {
				// Set this column's offset to the last and reset all following columns' offsets.
				adjustColumnInfoInDropColumn(tblInfo, firstHiddenOffset)
			}
		}

		newIndices := make([]*model.IndexInfo, 0, len(tblInfo.Indices))
		for _, idx := range tblInfo.Indices {
			if idx.Name.L != indexInfo.Name.L {
				newIndices = append(newIndices, idx)
			}
		}
		tblInfo.Indices = newIndices
		// Set column index flag.
		dropIndexColumnFlag(tblInfo, indexInfo)

		tblInfo.Columns = tblInfo.Columns[:len(tblInfo.Columns)-len(dependentHiddenCols)]
		failpoint.Inject("mockExceedErrorLimit", func(val failpoint.Value) {
			if val.(bool) {
				panic("panic test in cancelling add index")
			}
		})

		ver, err = updateVersionAndTableInfoWithCheck(t, job, tblInfo, originalState != model.StateNone)
		if err != nil {
			return ver, errors.Trace(err)
		}

		// Finish this job.
		if job.IsRollingback() {
			job.FinishTableJob(model.JobStateRollbackDone, model.StateNone, ver, tblInfo)
			job.Args[0] = indexInfo.ID
			// the partition ids were append by convertAddIdxJob2RollbackJob, it is weird, but for the compatibility,
			// we should keep appending the partitions in the convertAddIdxJob2RollbackJob.
		} else {
			job.FinishTableJob(model.JobStateDone, model.StateNone, ver, tblInfo)
			job.Args = append(job.Args, indexInfo.ID, getPartitionIDs(tblInfo))
		}
	default:
		err = ErrInvalidDDLState.GenWithStackByArgs("index", indexInfo.State)
	}
	return ver, errors.Trace(err)
}

func checkDropIndex(t *meta.Meta, job *model.Job) (*model.TableInfo, *model.IndexInfo, error) {
	schemaID := job.SchemaID
	tblInfo, err := getTableInfoAndCancelFaultJob(t, job, schemaID)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	var indexName model.CIStr
	if err = job.DecodeArgs(&indexName); err != nil {
		job.State = model.JobStateCancelled
		return nil, nil, errors.Trace(err)
	}

	indexInfo := tblInfo.FindIndexByName(indexName.L)
	if indexInfo == nil {
		job.State = model.JobStateCancelled
		return nil, nil, ErrCantDropFieldOrKey.GenWithStack("index %s doesn't exist", indexName)
	}

	// Double check for drop index on auto_increment column.
	err = checkDropIndexOnAutoIncrementColumn(tblInfo, indexInfo)
	if err != nil {
		job.State = model.JobStateCancelled
		return nil, nil, autoid.ErrWrongAutoKey
	}

	// Check that drop primary index will not cause invisible implicit primary index.
	if err := checkInvisibleIndexesOnPK(tblInfo, []*model.IndexInfo{indexInfo}, job); err != nil {
		return nil, nil, errors.Trace(err)
	}

	return tblInfo, indexInfo, nil
}

func onDropIndexes(t *meta.Meta, job *model.Job) (ver int64, _ error) {
	tblInfo, indexNames, ifExists, err := getSchemaInfos(t, job)
	if err != nil {
		return ver, errors.Trace(err)
	}

	indexInfos, err := checkDropIndexes(tblInfo, job, indexNames, ifExists)
	if err != nil {
		return ver, errors.Trace(err)
	}

	if len(indexInfos) == 0 {
		job.State = model.JobStateCancelled
		return ver, nil
	}

	dependentHiddenCols := make([]*model.ColumnInfo, 0)
	for _, indexInfo := range indexInfos {
		for _, indexColumn := range indexInfo.Columns {
			if tblInfo.Columns[indexColumn.Offset].Hidden {
				dependentHiddenCols = append(dependentHiddenCols, tblInfo.Columns[indexColumn.Offset])
			}
		}
	}

	originalState := indexInfos[0].State
	switch indexInfos[0].State {
	case model.StatePublic:
		// public -> write only
		setIndicesState(indexInfos, model.StateWriteOnly)
		setColumnsState(dependentHiddenCols, model.StateWriteOnly)
		for _, colInfo := range dependentHiddenCols {
			adjustColumnInfoInDropColumn(tblInfo, colInfo.Offset)
		}
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfos[0].State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		job.SchemaState = model.StateWriteOnly
	case model.StateWriteOnly:
		// write only -> delete only
		setIndicesState(indexInfos, model.StateDeleteOnly)
		setColumnsState(dependentHiddenCols, model.StateDeleteOnly)
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfos[0].State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		job.SchemaState = model.StateDeleteOnly
	case model.StateDeleteOnly:
		// delete only -> reorganization
		setIndicesState(indexInfos, model.StateDeleteReorganization)
		setColumnsState(dependentHiddenCols, model.StateDeleteReorganization)
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfos[0].State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		job.SchemaState = model.StateDeleteReorganization
	case model.StateDeleteReorganization:
		// reorganization -> absent
		indexIDs := make([]int64, 0, len(indexInfos))
		indexNames := make(map[string]bool, len(indexInfos))
		for _, indexInfo := range indexInfos {
			indexNames[indexInfo.Name.L] = true
			indexIDs = append(indexIDs, indexInfo.ID)
		}

		newIndices := make([]*model.IndexInfo, 0, len(tblInfo.Indices))
		for _, idx := range tblInfo.Indices {
			if _, ok := indexNames[idx.Name.L]; !ok {
				newIndices = append(newIndices, idx)
			}
		}
		tblInfo.Indices = newIndices

		// Set column index flag.
		for _, indexInfo := range indexInfos {
			dropIndexColumnFlag(tblInfo, indexInfo)
		}

		tblInfo.Columns = tblInfo.Columns[:len(tblInfo.Columns)-len(dependentHiddenCols)]

		ver, err = updateVersionAndTableInfoWithCheck(t, job, tblInfo, originalState != model.StateNone)
		if err != nil {
			return ver, errors.Trace(err)
		}

		job.FinishTableJob(model.JobStateDone, model.StateNone, ver, tblInfo)
		job.Args = append(job.Args, indexIDs, getPartitionIDs(tblInfo))
	default:
		err = ErrInvalidDDLState.GenWithStackByArgs("index", indexInfos[0].State)
	}

	return ver, errors.Trace(err)
}

func getSchemaInfos(t *meta.Meta, job *model.Job) (*model.TableInfo, []model.CIStr, []bool, error) {
	schemaID := job.SchemaID
	tblInfo, err := getTableInfoAndCancelFaultJob(t, job, schemaID)
	if err != nil {
		return nil, nil, nil, errors.Trace(err)
	}

	var indexNames []model.CIStr
	var ifExists []bool
	if err = job.DecodeArgs(&indexNames, &ifExists); err != nil {
		return nil, nil, nil, errors.Trace(err)
	}

	return tblInfo, indexNames, ifExists, nil
}

func checkDropIndexes(tblInfo *model.TableInfo, job *model.Job, indexNames []model.CIStr, ifExists []bool) ([]*model.IndexInfo, error) {
	var warnings []*errors.Error
	indexInfos := make([]*model.IndexInfo, 0, len(indexNames))
	UniqueIndexNames := make(map[model.CIStr]bool, len(indexNames))
	for i, indexName := range indexNames {
		// Double check the index is exists.
		indexInfo := tblInfo.FindIndexByName(indexName.L)
		if indexInfo == nil {
			if ifExists[i] {
				warnings = append(warnings, toTError(ErrCantDropFieldOrKey.GenWithStack("index %s doesn't exist", indexName)))
				continue
			}
			job.State = model.JobStateCancelled
			return nil, ErrCantDropFieldOrKey.GenWithStack("index %s doesn't exist", indexName)
		}

		// Double check for drop index on auto_increment column.
		if err := checkDropIndexOnAutoIncrementColumn(tblInfo, indexInfo); err != nil {
			job.State = model.JobStateCancelled
			return nil, autoid.ErrWrongAutoKey
		}

		// Check for dropping duplicate indexes.
		if UniqueIndexNames[indexName] {
			if !ifExists[i] {
				job.State = model.JobStateCancelled
				return nil, ErrCantDropFieldOrKey.GenWithStack("index %s doesn't exist", indexName)
			}
			warnings = append(warnings, toTError(ErrCantDropFieldOrKey.GenWithStack("index %s doesn't exist", indexName)))
		}
		UniqueIndexNames[indexName] = true

		indexInfos = append(indexInfos, indexInfo)
	}

	// Check that drop primary index will not cause invisible implicit primary index.
	if err := checkInvisibleIndexesOnPK(tblInfo, indexInfos, job); err != nil {
		return nil, errors.Trace(err)
	}

	job.MultiSchemaInfo = &model.MultiSchemaInfo{Warnings: warnings}

	return indexInfos, nil
}

func checkInvisibleIndexesOnPK(tblInfo *model.TableInfo, indexInfos []*model.IndexInfo, job *model.Job) error {
	newIndices := make([]*model.IndexInfo, 0, len(tblInfo.Indices))
	for _, oidx := range tblInfo.Indices {
		needAppend := true
		for _, idx := range indexInfos {
			if idx.Name.L == oidx.Name.L {
				needAppend = false
				break
			}
		}
		if needAppend {
			newIndices = append(newIndices, oidx)
		}
	}
	newTbl := tblInfo.Clone()
	newTbl.Indices = newIndices
	if err := checkInvisibleIndexOnPK(newTbl); err != nil {
		job.State = model.JobStateCancelled
		return err
	}

	return nil
}

func checkDropIndexOnAutoIncrementColumn(tblInfo *model.TableInfo, indexInfo *model.IndexInfo) error {
	cols := tblInfo.Columns
	for _, idxCol := range indexInfo.Columns {
		flag := cols[idxCol.Offset].Flag
		if !mysql.HasAutoIncrementFlag(flag) {
			continue
		}
		// check the count of index on auto_increment column.
		count := 0
		for _, idx := range tblInfo.Indices {
			for _, c := range idx.Columns {
				if c.Name.L == idxCol.Name.L {
					count++
					break
				}
			}
		}
		if tblInfo.PKIsHandle && mysql.HasPriKeyFlag(flag) {
			count++
		}
		if count < 2 {
			return autoid.ErrWrongAutoKey
		}
	}
	return nil
}

func checkRenameIndex(t *meta.Meta, job *model.Job) (*model.TableInfo, model.CIStr, model.CIStr, error) {
	var from, to model.CIStr
	schemaID := job.SchemaID
	tblInfo, err := getTableInfoAndCancelFaultJob(t, job, schemaID)
	if err != nil {
		return nil, from, to, errors.Trace(err)
	}

	if err := job.DecodeArgs(&from, &to); err != nil {
		job.State = model.JobStateCancelled
		return nil, from, to, errors.Trace(err)
	}

	// Double check. See function `RenameIndex` in ddl_api.go
	duplicate, err := validateRenameIndex(from, to, tblInfo)
	if duplicate {
		return nil, from, to, nil
	}
	if err != nil {
		job.State = model.JobStateCancelled
		return nil, from, to, errors.Trace(err)
	}
	return tblInfo, from, to, errors.Trace(err)
}

func checkAlterIndexVisibility(t *meta.Meta, job *model.Job) (*model.TableInfo, model.CIStr, bool, error) {
	var (
		indexName model.CIStr
		invisible bool
	)

	schemaID := job.SchemaID
	tblInfo, err := getTableInfoAndCancelFaultJob(t, job, schemaID)
	if err != nil {
		return nil, indexName, invisible, errors.Trace(err)
	}

	if err := job.DecodeArgs(&indexName, &invisible); err != nil {
		job.State = model.JobStateCancelled
		return nil, indexName, invisible, errors.Trace(err)
	}

	skip, err := validateAlterIndexVisibility(indexName, invisible, tblInfo)
	if err != nil {
		job.State = model.JobStateCancelled
		return nil, indexName, invisible, errors.Trace(err)
	}
	if skip {
		return nil, indexName, invisible, nil
	}
	return tblInfo, indexName, invisible, nil
}

// indexRecord is the record information of an index.
type indexRecord struct {
	handle kv.Handle
	key    []byte        // It's used to lock a record. Record it to reduce the encoding time.
	vals   []types.Datum // It's the index values.
	rsData []types.Datum // It's the restored data for handle.
	skip   bool          // skip indicates that the index key is already exists, we should not add it.
}

type baseIndexWorker struct {
	*backfillWorker
	indexes []table.Index

	metricCounter prometheus.Counter

	// The following attributes are used to reduce memory allocation.
	defaultVals []types.Datum
	idxRecords  []*indexRecord
	rowMap      map[int64]types.Datum
	rowDecoder  *decoder.RowDecoder

	sqlMode mysql.SQLMode
}

type addIndexWorker struct {
	baseIndexWorker
	index table.Index

	// The following attributes are used to reduce memory allocation.
	idxKeyBufs         [][]byte
	batchCheckKeys     []kv.Key
	distinctCheckFlags []bool
}

func newAddIndexWorker(sessCtx sessionctx.Context, worker *worker, id int, t table.PhysicalTable, indexInfo *model.IndexInfo, decodeColMap map[int64]decoder.Column, sqlMode mysql.SQLMode) *addIndexWorker {
	index := tables.NewIndex(t.GetPhysicalID(), t.Meta(), indexInfo)
	rowDecoder := decoder.NewRowDecoder(t, t.WritableCols(), decodeColMap)
	return &addIndexWorker{
		baseIndexWorker: baseIndexWorker{
			backfillWorker: newBackfillWorker(sessCtx, worker, id, t),
			indexes:        []table.Index{index},
			rowDecoder:     rowDecoder,
			defaultVals:    make([]types.Datum, len(t.WritableCols())),
			rowMap:         make(map[int64]types.Datum, len(decodeColMap)),
			metricCounter:  metrics.BackfillTotalCounter.WithLabelValues("add_idx_speed"),
			sqlMode:        sqlMode,
		},
		index: index,
	}
}

func (w *baseIndexWorker) AddMetricInfo(cnt float64) {
	w.metricCounter.Add(cnt)
}

// mockNotOwnerErrOnce uses to make sure `notOwnerErr` only mock error once.
var mockNotOwnerErrOnce uint32

// getIndexRecord gets index columns values use w.rowDecoder, and generate indexRecord.
func (w *baseIndexWorker) getIndexRecord(idxInfo *model.IndexInfo, handle kv.Handle, recordKey []byte) (*indexRecord, error) {
	cols := w.table.WritableCols()
	sysZone := timeutil.SystemLocation()
	failpoint.Inject("MockGetIndexRecordErr", func(val failpoint.Value) {
		if valStr, ok := val.(string); ok {
			switch valStr {
			case "cantDecodeRecordErr":
				failpoint.Return(nil, errors.Trace(errCantDecodeRecord.GenWithStackByArgs("index",
					errors.New("mock can't decode record error"))))
			case "modifyColumnNotOwnerErr":
				if idxInfo.Name.O == "_Idx$_idx" && handle.IntValue() == 7168 && atomic.CompareAndSwapUint32(&mockNotOwnerErrOnce, 0, 1) {
					failpoint.Return(nil, errors.Trace(errNotOwner))
				}
			case "addIdxNotOwnerErr":
				// For the case of the old TiDB version(do not exist the element information) is upgraded to the new TiDB version.
				// First step, we need to exit "addPhysicalTableIndex".
				if idxInfo.Name.O == "idx2" && handle.IntValue() == 6144 && atomic.CompareAndSwapUint32(&mockNotOwnerErrOnce, 1, 2) {
					failpoint.Return(nil, errors.Trace(errNotOwner))
				}
			}
		}
	})
	idxVal := make([]types.Datum, len(idxInfo.Columns))
	var err error
	for j, v := range idxInfo.Columns {
		col := cols[v.Offset]
		idxColumnVal, ok := w.rowMap[col.ID]
		if ok {
			idxVal[j] = idxColumnVal
			continue
		}
		idxColumnVal, err = tables.GetColDefaultValue(w.sessCtx, col, w.defaultVals)
		if err != nil {
			return nil, errors.Trace(err)
		}

		if idxColumnVal.Kind() == types.KindMysqlTime {
			t := idxColumnVal.GetMysqlTime()
			if t.Type() == mysql.TypeTimestamp && sysZone != time.UTC {
				err := t.ConvertTimeZone(sysZone, time.UTC)
				if err != nil {
					return nil, errors.Trace(err)
				}
				idxColumnVal.SetMysqlTime(t)
			}
		}
		idxVal[j] = idxColumnVal
	}

	rsData := tables.TryGetHandleRestoredDataWrapper(w.table, nil, w.rowMap, idxInfo)
	idxRecord := &indexRecord{handle: handle, key: recordKey, vals: idxVal, rsData: rsData}
	return idxRecord, nil
}

func (w *baseIndexWorker) cleanRowMap() {
	for id := range w.rowMap {
		delete(w.rowMap, id)
	}
}

// getNextKey gets next key of entry that we are going to process.
func (w *baseIndexWorker) getNextKey(taskRange reorgBackfillTask, taskDone bool) (nextKey kv.Key) {
	if !taskDone {
		// The task is not done. So we need to pick the last processed entry's handle and add one.
		lastHandle := w.idxRecords[len(w.idxRecords)-1].handle
		recordKey := tablecodec.EncodeRecordKey(w.table.RecordPrefix(), lastHandle)
		return recordKey.Next()
	}
	return taskRange.endKey.Next()
}

func (w *baseIndexWorker) updateRowDecoder(handle kv.Handle, recordKey []byte, rawRecord []byte) error {
	sysZone := timeutil.SystemLocation()
	_, err := w.rowDecoder.DecodeAndEvalRowWithMap(w.sessCtx, handle, rawRecord, time.UTC, sysZone, w.rowMap)
	if err != nil {
		return errors.Trace(errCantDecodeRecord.GenWithStackByArgs("index", err))
	}
	return nil
}

// fetchRowColVals fetch w.batchCnt count records that need to reorganize indices, and build the corresponding indexRecord slice.
// fetchRowColVals returns:
// 1. The corresponding indexRecord slice.
// 2. Next handle of entry that we need to process.
// 3. Boolean indicates whether the task is done.
// 4. error occurs in fetchRowColVals. nil if no error occurs.
func (w *baseIndexWorker) fetchRowColVals(txn kv.Transaction, taskRange reorgBackfillTask) ([]*indexRecord, kv.Key, bool, error) {
	// TODO: use tableScan to prune columns.
	w.idxRecords = w.idxRecords[:0]
	startTime := time.Now()

	// taskDone means that the reorged handle is out of taskRange.endHandle.
	taskDone := false
	oprStartTime := startTime
	err := iterateSnapshotRows(w.sessCtx.GetStore(), w.priority, w.table, txn.StartTS(), taskRange.startKey, taskRange.endKey,
		func(handle kv.Handle, recordKey kv.Key, rawRow []byte) (bool, error) {
			oprEndTime := time.Now()
			logSlowOperations(oprEndTime.Sub(oprStartTime), "iterateSnapshotRows in baseIndexWorker fetchRowColVals", 0)
			oprStartTime = oprEndTime

			taskDone = recordKey.Cmp(taskRange.endKey) > 0

			if taskDone || len(w.idxRecords) >= w.batchCnt {
				return false, nil
			}

			// Decode one row, generate records of this row.
			err := w.updateRowDecoder(handle, recordKey, rawRow)
			if err != nil {
				return false, err
			}
			for _, index := range w.indexes {
				idxRecord, err1 := w.getIndexRecord(index.Meta(), handle, recordKey)
				if err1 != nil {
					return false, errors.Trace(err1)
				}
				w.idxRecords = append(w.idxRecords, idxRecord)
			}
			// If there are generated column, rowDecoder will use column value that not in idxInfo.Columns to calculate
			// the generated value, so we need to clear up the reusing map.
			w.cleanRowMap()

			if recordKey.Cmp(taskRange.endKey) == 0 {
				// If taskRange.endIncluded == false, we will not reach here when handle == taskRange.endHandle
				taskDone = true
				return false, nil
			}
			return true, nil
		})

	if len(w.idxRecords) == 0 {
		taskDone = true
	}

	logutil.BgLogger().Debug("[ddl] txn fetches handle info", zap.Uint64("txnStartTS", txn.StartTS()),
		zap.String("taskRange", taskRange.String()), zap.Duration("takeTime", time.Since(startTime)))
	return w.idxRecords, w.getNextKey(taskRange, taskDone), taskDone, errors.Trace(err)
}

func (w *addIndexWorker) initBatchCheckBufs(batchCount int) {
	if len(w.idxKeyBufs) < batchCount {
		w.idxKeyBufs = make([][]byte, batchCount)
	}

	w.batchCheckKeys = w.batchCheckKeys[:0]
	w.distinctCheckFlags = w.distinctCheckFlags[:0]
}

func (w *addIndexWorker) checkHandleExists(key kv.Key, value []byte, handle kv.Handle) error {
	idxInfo := w.index.Meta()
	tblInfo := w.table.Meta()
	idxColLen := len(idxInfo.Columns)
	h, err := tablecodec.DecodeIndexHandle(key, value, idxColLen)
	if err != nil {
		return errors.Trace(err)
	}
	hasBeenBackFilled := h.Equal(handle)
	if hasBeenBackFilled {
		return nil
	}
	colInfos := tables.BuildRowcodecColInfoForIndexColumns(idxInfo, tblInfo)
	values, err := tablecodec.DecodeIndexKV(key, value, idxColLen, tablecodec.HandleNotNeeded, colInfos)
	if err != nil {
		return err
	}
	indexName := w.index.Meta().Name.String()
	valueStr := make([]string, 0, idxColLen)
	for i, val := range values[:idxColLen] {
		d, err := tablecodec.DecodeColumnValue(val, colInfos[i].Ft, time.Local)
		if err != nil {
			return kv.ErrKeyExists.FastGenByArgs(key.String(), indexName)
		}
		str, err := d.ToString()
		if err != nil {
			str = string(val)
		}
		valueStr = append(valueStr, str)
	}
	return kv.ErrKeyExists.FastGenByArgs(strings.Join(valueStr, "-"), indexName)
}

func (w *addIndexWorker) batchCheckUniqueKey(txn kv.Transaction, idxRecords []*indexRecord) error {
	idxInfo := w.index.Meta()
	if !idxInfo.Unique {
		// non-unique key need not to check, just overwrite it,
		// because in most case, backfilling indices is not exists.
		return nil
	}

	w.initBatchCheckBufs(len(idxRecords))
	stmtCtx := w.sessCtx.GetSessionVars().StmtCtx
	for i, record := range idxRecords {
		idxKey, distinct, err := w.index.GenIndexKey(stmtCtx, record.vals, record.handle, w.idxKeyBufs[i])
		if err != nil {
			return errors.Trace(err)
		}
		// save the buffer to reduce memory allocations.
		w.idxKeyBufs[i] = idxKey

		w.batchCheckKeys = append(w.batchCheckKeys, idxKey)
		w.distinctCheckFlags = append(w.distinctCheckFlags, distinct)
	}

	batchVals, err := txn.BatchGet(context.Background(), w.batchCheckKeys)
	if err != nil {
		return errors.Trace(err)
	}

	// 1. unique-key/primary-key is duplicate and the handle is equal, skip it.
	// 2. unique-key/primary-key is duplicate and the handle is not equal, return duplicate error.
	// 3. non-unique-key is duplicate, skip it.
	for i, key := range w.batchCheckKeys {
		if val, found := batchVals[string(key)]; found {
			if w.distinctCheckFlags[i] {
				if err := w.checkHandleExists(key, val, idxRecords[i].handle); err != nil {
					return errors.Trace(err)
				}
			}
			idxRecords[i].skip = true
		} else if w.distinctCheckFlags[i] {
			// The keys in w.batchCheckKeys also maybe duplicate,
			// so we need to backfill the not found key into `batchVals` map.
			needRsData := tables.NeedRestoredData(w.index.Meta().Columns, w.table.Meta().Columns)
			val, err := tablecodec.GenIndexValuePortal(stmtCtx, w.table.Meta(), w.index.Meta(), needRsData, w.distinctCheckFlags[i], false, idxRecords[i].vals, idxRecords[i].handle, 0, idxRecords[i].rsData)
			if err != nil {
				return errors.Trace(err)
			}
			batchVals[string(key)] = val
		}
	}
	// Constrains is already checked.
	stmtCtx.BatchCheck = true
	return nil
}

// BackfillDataInTxn will backfill table index in a transaction, lock corresponding rowKey, if the value of rowKey is changed,
// indicate that index columns values may changed, index is not allowed to be added, so the txn will rollback and retry.
// BackfillDataInTxn will add w.batchCnt indices once, default value of w.batchCnt is 128.
// TODO: make w.batchCnt can be modified by system variable.
func (w *addIndexWorker) BackfillDataInTxn(handleRange reorgBackfillTask) (taskCtx backfillTaskContext, errInTxn error) {
	failpoint.Inject("errorMockPanic", func(val failpoint.Value) {
		if val.(bool) {
			panic("panic test")
		}
	})

	oprStartTime := time.Now()
	errInTxn = kv.RunInNewTxn(context.Background(), w.sessCtx.GetStore(), true, func(ctx context.Context, txn kv.Transaction) error {
		taskCtx.addedCount = 0
		taskCtx.scanCount = 0
		txn.SetOption(kv.Priority, w.priority)

		idxRecords, nextKey, taskDone, err := w.fetchRowColVals(txn, handleRange)
		if err != nil {
			return errors.Trace(err)
		}
		taskCtx.nextKey = nextKey
		taskCtx.done = taskDone

		err = w.batchCheckUniqueKey(txn, idxRecords)
		if err != nil {
			return errors.Trace(err)
		}

		for _, idxRecord := range idxRecords {
			taskCtx.scanCount++
			// The index is already exists, we skip it, no needs to backfill it.
			// The following update, delete, insert on these rows, TiDB can handle it correctly.
			if idxRecord.skip {
				continue
			}

			// Lock the row key to notify us that someone delete or update the row,
			// then we should not backfill the index of it, otherwise the adding index is redundant.
			err := txn.LockKeys(context.Background(), new(kv.LockCtx), idxRecord.key)
			if err != nil {
				return errors.Trace(err)
			}

			// Create the index.
			handle, err := w.index.Create(w.sessCtx, txn, idxRecord.vals, idxRecord.handle, idxRecord.rsData)
			if err != nil {
				if kv.ErrKeyExists.Equal(err) && idxRecord.handle.Equal(handle) {
					// Index already exists, skip it.
					continue
				}

				return errors.Trace(err)
			}
			taskCtx.addedCount++
		}

		return nil
	})
	logSlowOperations(time.Since(oprStartTime), "AddIndexBackfillDataInTxn", 3000)

	return
}

func (w *worker) addPhysicalTableIndex(t table.PhysicalTable, indexInfo *model.IndexInfo, reorgInfo *reorgInfo) error {
	logutil.BgLogger().Info("[ddl] start to add table index", zap.String("job", reorgInfo.Job.String()), zap.String("reorgInfo", reorgInfo.String()))
	return w.writePhysicalTableRecord(t, typeAddIndexWorker, indexInfo, nil, nil, reorgInfo)
}

// addTableIndex handles the add index reorganization state for a table.
func (w *worker) addTableIndex(t table.Table, idx *model.IndexInfo, reorgInfo *reorgInfo) error {
	var err error
	if tbl, ok := t.(table.PartitionedTable); ok {
		var finish bool
		for !finish {
			p := tbl.GetPartition(reorgInfo.PhysicalTableID)
			if p == nil {
				return errCancelledDDLJob.GenWithStack("Can not find partition id %d for table %d", reorgInfo.PhysicalTableID, t.Meta().ID)
			}
			err = w.addPhysicalTableIndex(p, idx, reorgInfo)
			if err != nil {
				break
			}
			finish, err = w.updateReorgInfo(tbl, reorgInfo)
			if err != nil {
				return errors.Trace(err)
			}
		}
	} else {
		err = w.addPhysicalTableIndex(t.(table.PhysicalTable), idx, reorgInfo)
	}
	return errors.Trace(err)
}

// updateReorgInfo will find the next partition according to current reorgInfo.
// If no more partitions, or table t is not a partitioned table, returns true to
// indicate that the reorganize work is finished.
func (w *worker) updateReorgInfo(t table.PartitionedTable, reorg *reorgInfo) (bool, error) {
	pi := t.Meta().GetPartitionInfo()
	if pi == nil {
		return true, nil
	}

	pid, err := findNextPartitionID(reorg.PhysicalTableID, pi.Definitions)
	if err != nil {
		// Fatal error, should not run here.
		logutil.BgLogger().Error("[ddl] find next partition ID failed", zap.Reflect("table", t), zap.Error(err))
		return false, errors.Trace(err)
	}
	if pid == 0 {
		// Next partition does not exist, all the job done.
		return true, nil
	}

	failpoint.Inject("mockUpdateCachedSafePoint", func(val failpoint.Value) {
		if val.(bool) {
			ts := oracle.GoTimeToTS(time.Now())
			s := reorg.d.store.(tikv.Storage)
			s.UpdateSPCache(ts, time.Now())
			time.Sleep(time.Millisecond * 3)
		}
	})
	currentVer, err := getValidCurrentVersion(reorg.d.store)
	if err != nil {
		return false, errors.Trace(err)
	}
	start, end, err := getTableRange(reorg.d, t.GetPartition(pid), currentVer.Ver, reorg.Job.Priority)
	if err != nil {
		return false, errors.Trace(err)
	}
	reorg.StartKey, reorg.EndKey, reorg.PhysicalTableID = start, end, pid

	// Write the reorg info to store so the whole reorganize process can recover from panic.
	err = reorg.UpdateReorgMeta(start)
	logutil.BgLogger().Info("[ddl] job update reorgInfo",
		zap.Int64("jobID", reorg.Job.ID),
		zap.ByteString("elementType", reorg.currElement.TypeKey),
		zap.Int64("elementID", reorg.currElement.ID),
		zap.Int64("partitionTableID", pid),
		zap.String("startHandle", tryDecodeToHandleString(start)),
		zap.String("endHandle", tryDecodeToHandleString(end)), zap.Error(err))
	return false, errors.Trace(err)
}

// findNextPartitionID finds the next partition ID in the PartitionDefinition array.
// Returns 0 if current partition is already the last one.
func findNextPartitionID(currentPartition int64, defs []model.PartitionDefinition) (int64, error) {
	for i, def := range defs {
		if currentPartition == def.ID {
			if i == len(defs)-1 {
				return 0, nil
			}
			return defs[i+1].ID, nil
		}
	}
	return 0, errors.Errorf("partition id not found %d", currentPartition)
}

func allocateIndexID(tblInfo *model.TableInfo) int64 {
	tblInfo.MaxIndexID++
	return tblInfo.MaxIndexID
}

func getIndexInfoByNameAndColumn(oldTableInfo *model.TableInfo, newOne *model.IndexInfo) *model.IndexInfo {
	for _, oldOne := range oldTableInfo.Indices {
		if newOne.Name.L == oldOne.Name.L && indexColumnSliceEqual(newOne.Columns, oldOne.Columns) {
			return oldOne
		}
	}
	return nil
}

func indexColumnSliceEqual(a, b []*model.IndexColumn) bool {
	if len(a) != len(b) {
		return false
	}
	if len(a) == 0 {
		logutil.BgLogger().Warn("[ddl] admin repair table : index's columns length equal to 0")
		return true
	}
	// Accelerate the compare by eliminate index bound check.
	b = b[:len(a)]
	for i, v := range a {
		if v.Name.L != b[i].Name.L {
			return false
		}
	}
	return true
}

type cleanUpIndexWorker struct {
	baseIndexWorker
}

func newCleanUpIndexWorker(sessCtx sessionctx.Context, worker *worker, id int, t table.PhysicalTable, decodeColMap map[int64]decoder.Column, sqlMode mysql.SQLMode) *cleanUpIndexWorker {
	indexes := make([]table.Index, 0, len(t.Indices()))
	rowDecoder := decoder.NewRowDecoder(t, t.WritableCols(), decodeColMap)
	for _, index := range t.Indices() {
		if index.Meta().Global {
			indexes = append(indexes, index)
		}
	}
	return &cleanUpIndexWorker{
		baseIndexWorker: baseIndexWorker{
			backfillWorker: newBackfillWorker(sessCtx, worker, id, t),
			indexes:        indexes,
			rowDecoder:     rowDecoder,
			defaultVals:    make([]types.Datum, len(t.WritableCols())),
			rowMap:         make(map[int64]types.Datum, len(decodeColMap)),
			metricCounter:  metrics.BackfillTotalCounter.WithLabelValues("clean_up_idx_speed"),
			sqlMode:        sqlMode,
		},
	}
}

func (w *cleanUpIndexWorker) BackfillDataInTxn(handleRange reorgBackfillTask) (taskCtx backfillTaskContext, errInTxn error) {
	failpoint.Inject("errorMockPanic", func(val failpoint.Value) {
		if val.(bool) {
			panic("panic test")
		}
	})

	oprStartTime := time.Now()
	errInTxn = kv.RunInNewTxn(context.Background(), w.sessCtx.GetStore(), true, func(ctx context.Context, txn kv.Transaction) error {
		taskCtx.addedCount = 0
		taskCtx.scanCount = 0
		txn.SetOption(kv.Priority, w.priority)

		idxRecords, nextKey, taskDone, err := w.fetchRowColVals(txn, handleRange)
		if err != nil {
			return errors.Trace(err)
		}
		taskCtx.nextKey = nextKey
		taskCtx.done = taskDone

		txn.SetDiskFullOpt(kvrpcpb.DiskFullOpt_AllowedOnAlmostFull)

		n := len(w.indexes)
		for i, idxRecord := range idxRecords {
			taskCtx.scanCount++
			// we fetch records row by row, so records will belong to
			// index[0], index[1] ... index[n-1], index[0], index[1] ...
			// respectively. So indexes[i%n] is the index of idxRecords[i].
			err := w.indexes[i%n].Delete(w.sessCtx.GetSessionVars().StmtCtx, txn, idxRecord.vals, idxRecord.handle)
			if err != nil {
				return errors.Trace(err)
			}
			taskCtx.addedCount++
		}
		return nil
	})
	logSlowOperations(time.Since(oprStartTime), "cleanUpIndexBackfillDataInTxn", 3000)

	return
}

// cleanupPhysicalTableIndex handles the drop partition reorganization state for a non-partitioned table or a partition.
func (w *worker) cleanupPhysicalTableIndex(t table.PhysicalTable, reorgInfo *reorgInfo) error {
	logutil.BgLogger().Info("[ddl] start to clean up index", zap.String("job", reorgInfo.Job.String()), zap.String("reorgInfo", reorgInfo.String()))
	return w.writePhysicalTableRecord(t, typeCleanUpIndexWorker, nil, nil, nil, reorgInfo)
}

// cleanupGlobalIndex handles the drop partition reorganization state to clean up index entries of partitions.
func (w *worker) cleanupGlobalIndexes(tbl table.PartitionedTable, partitionIDs []int64, reorgInfo *reorgInfo) error {
	var err error
	var finish bool
	for !finish {
		p := tbl.GetPartition(reorgInfo.PhysicalTableID)
		if p == nil {
			return errCancelledDDLJob.GenWithStack("Can not find partition id %d for table %d", reorgInfo.PhysicalTableID, tbl.Meta().ID)
		}
		err = w.cleanupPhysicalTableIndex(p, reorgInfo)
		if err != nil {
			break
		}
		finish, err = w.updateReorgInfoForPartitions(tbl, reorgInfo, partitionIDs)
		if err != nil {
			return errors.Trace(err)
		}
	}

	return errors.Trace(err)
}

// updateReorgInfoForPartitions will find the next partition in partitionIDs according to current reorgInfo.
// If no more partitions, or table t is not a partitioned table, returns true to
// indicate that the reorganize work is finished.
func (w *worker) updateReorgInfoForPartitions(t table.PartitionedTable, reorg *reorgInfo, partitionIDs []int64) (bool, error) {
	pi := t.Meta().GetPartitionInfo()
	if pi == nil {
		return true, nil
	}

	var pid int64
	for i, pi := range partitionIDs {
		if pi == reorg.PhysicalTableID {
			if i == len(partitionIDs)-1 {
				return true, nil
			}
		}
		pid = partitionIDs[i+1]
	}

	currentVer, err := getValidCurrentVersion(reorg.d.store)
	if err != nil {
		return false, errors.Trace(err)
	}
	start, end, err := getTableRange(reorg.d, t.GetPartition(pid), currentVer.Ver, reorg.Job.Priority)
	if err != nil {
		return false, errors.Trace(err)
	}
	reorg.StartKey, reorg.EndKey, reorg.PhysicalTableID = start, end, pid

	// Write the reorg info to store so the whole reorganize process can recover from panic.
	err = reorg.UpdateReorgMeta(reorg.StartKey)
	logutil.BgLogger().Info("[ddl] job update reorgInfo", zap.Int64("jobID", reorg.Job.ID),
		zap.ByteString("elementType", reorg.currElement.TypeKey), zap.Int64("elementID", reorg.currElement.ID),
		zap.Int64("partitionTableID", pid), zap.String("startHandle", tryDecodeToHandleString(start)),
		zap.String("endHandle", tryDecodeToHandleString(end)), zap.Error(err))
	return false, errors.Trace(err)
}

func findIndexesByColName(indexes []*model.IndexInfo, colName string) ([]*model.IndexInfo, []int) {
	idxInfos := make([]*model.IndexInfo, 0, len(indexes))
	offsets := make([]int, 0, len(indexes))
	for _, idxInfo := range indexes {
		for i, c := range idxInfo.Columns {
			if strings.EqualFold(colName, c.Name.L) {
				idxInfos = append(idxInfos, idxInfo)
				offsets = append(offsets, i)
				break
			}
		}
	}
	return idxInfos, offsets
}


text:
package me.daniel.sales_taxes_problem;

import static org.junit.Assert.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class CartFileImportTest {

	private List<OrderItem> imported;
	private List<OrderItem> expected;

	public CartFileImportTest(List<OrderItem> imported, List<OrderItem> expected){
		this.imported = imported;
		this.expected = expected;
	}

	@Parameters
	public static Collection<Object[]> data () throws IOException {

		CartImportStrategy importStrategy = new CartFileImporter();
		List<OrderItem> cart1 = new LinkedList<OrderItem>();
		List<OrderItem> cart2 = new LinkedList<OrderItem>();
		List<OrderItem> cart3 = new LinkedList<OrderItem>();

		cart1.add(new OrderItem(1, new Product("book",ProductType.BOOKS, false, new BigDecimal(12.49))));
		cart1.add(new OrderItem(1,new Product("music CD",ProductType.OTHER, false, new BigDecimal(14.99))));
		cart1.add(new OrderItem(1,new Product("chocolate bar",ProductType.FOOD, false, new BigDecimal(0.85))));

		cart2.add(new OrderItem(1,new Product("imported box of chocolates",ProductType.FOOD, true, new BigDecimal(10.00))));
		cart2.add(new OrderItem(1,new Product("imported bottle of perfume",ProductType.OTHER, true, new BigDecimal(47.50))));

		cart3.add(new OrderItem(1,new Product("imported bottle of perfume",ProductType.OTHER, true, new BigDecimal(27.99))));
		cart3.add(new OrderItem(1,new Product("bottle of perfume",ProductType.OTHER, false, new BigDecimal(18.99))));
		cart3.add(new OrderItem(1,new Product("packet of headache pills",ProductType.MEDICAL, false, new BigDecimal(9.75))));
		cart3.add(new OrderItem(1,new Product("box of imported chocolates",ProductType.FOOD, true, new BigDecimal(11.25))));

		return Arrays.asList(new Object[][]	{
			{importStrategy.importCart("files/cart1.txt"), cart1 },
			{importStrategy.importCart("files/cart2.txt"), cart2 },
			{importStrategy.importCart("files/cart3.txt"), cart3 },
			{importStrategy.importCart("files/cart3-bad.txt"), cart3 }
		});
	}

	@Test
	public void test(){
		assertEquals(expected, imported);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.openntf.red.design;

import java.awt.image.BufferedImage;

/**
 * Initial code borrowed from OpenNTF Domino API.

 * @author jgallagher
 *
 */
public interface ImageResource extends AnyFileResource {

	public BufferedImage getImage();
}


text:
This is the demo package for training purpose, it is based on https://github.com/dockerfile/haproxy

    $ docker run -d --name web1 larrycai/tomcat
    $ docker run -d --name web2 larrycai/tomcat
    $ docker run -d -P --link web1:back1 --link web2:back2 larrycai/haproxy

Usage:

* Port 80  : connect to backend 8080
* Port 8080: haproxy stats


text:
package com.vmware.vim25.mo;

import java.rmi.RemoteException;

import com.vmware.vim25.ConcurrentAccess;
import com.vmware.vim25.DuplicateName;
import com.vmware.vim25.FileFault;
import com.vmware.vim25.InsufficientResourcesFault;
import com.vmware.vim25.InvalidDatastore;
import com.vmware.vim25.InvalidName;
import com.vmware.vim25.InvalidPowerState;
import com.vmware.vim25.InvalidState;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.MigrationFault;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.TaskInProgress;
import com.vmware.vim25.VAppCloneSpec;
import com.vmware.vim25.VAppConfigFault;
import com.vmware.vim25.VAppConfigInfo;
import com.vmware.vim25.VAppConfigSpec;
import com.vmware.vim25.VirtualAppLinkInfo;
import com.vmware.vim25.VirtualAppSummary;
import com.vmware.vim25.VmConfigFault;

/**
 * The managed object class corresponding to the one defined in VI SDK API reference.
 * @author Steve JIN (http://www.doublecloud.org)
 */
public class VirtualApp extends ResourcePool
{
  public VirtualApp(ServerConnection sc, ManagedObjectReference mor)
  {
    super(sc, mor);
  }

  /** @since SDK4.1 */
  public VirtualAppLinkInfo[] getChildLink()
  {
    return (VirtualAppLinkInfo[]) getCurrentProperty("childLink");
  }

  public Datastore[] getDatastore()
  {
    return getDatastores("datastore");
  }

  public Network[] getNetwork()
  {
    return getNetworks("network");
  }

  @Override
  public VirtualAppSummary getSummary()
  {
    return (VirtualAppSummary) this.getCurrentProperty("summary");
  }

  public Folder getParentFolder()
  {
    ManagedObjectReference mor = (ManagedObjectReference) getCurrentProperty("parentFolder");
    return new Folder(getServerConnection(), mor);
  }

  /** @since SDK4.1 */
  public ManagedEntity getParentVApp()
  {
    ManagedObjectReference mor = (ManagedObjectReference) getCurrentProperty("parentVApp");
    return new ManagedEntity(getServerConnection(), mor);
  }

  public VAppConfigInfo getVAppConfig()
  {
    return (VAppConfigInfo) getCurrentProperty("vAppConfig");
  }

  public Task cloneVApp_Task(String name, ManagedObjectReference target, VAppCloneSpec spec) throws InvalidState, InvalidDatastore, TaskInProgress, VmConfigFault, FileFault, MigrationFault, InsufficientResourcesFault, RuntimeFault, RemoteException
  {
    ManagedObjectReference taskMor = getVimService().cloneVApp_Task(getMOR(), name, target, spec);
    return new Task(getServerConnection(), taskMor);
  }

  public HttpNfcLease exportVApp() throws InvalidPowerState, TaskInProgress, InvalidState, FileFault, RuntimeFault, RemoteException
  {
    ManagedObjectReference mor = getVimService().exportVApp(getMOR());
    return new HttpNfcLease(getServerConnection(), mor);
  }

  public Task powerOffVApp_Task(boolean force) throws TaskInProgress, InvalidState, VAppConfigFault, RuntimeFault, RemoteException
  {
    ManagedObjectReference taskMor = getVimService().powerOffVApp_Task(getMOR(), force);
    return new Task(getServerConnection(), taskMor);
  }

  /** @since SDK4.1 */
  public Task suspendVApp_Task() throws TaskInProgress, InvalidState, VAppConfigFault, RuntimeFault, RemoteException
  {
    ManagedObjectReference taskMor = getVimService().suspendVApp_Task(getMOR());
    return new Task(getServerConnection(), taskMor);
  }

  public Task powerOnVApp_Task() throws TaskInProgress, InvalidState, InsufficientResourcesFault, VmConfigFault, VAppConfigFault, FileFault, RuntimeFault, RemoteException
  {
    ManagedObjectReference taskMor = getVimService().powerOnVApp_Task(getMOR());
    return new Task(getServerConnection(), taskMor);
  }

  public Task unregisterVApp_Task() throws ConcurrentAccess, InvalidState, RuntimeFault, RemoteException
  {
    ManagedObjectReference taskMor = getVimService().unregisterVApp_Task(getMOR());
    return new Task(getServerConnection(), taskMor);
  }

  /** @since SDK4.1 */
  public void updateLinkedChildren(VirtualAppLinkInfo[] addChangeSet, ManagedObjectReference[] removeSet) throws ConcurrentAccess, RuntimeFault, RemoteException
  {
    getVimService().updateLinkedChildren(getMOR(), addChangeSet, removeSet);
  }

  public void updateVAppConfig(VAppConfigSpec spec) throws TaskInProgress, VmConfigFault, ConcurrentAccess, FileFault, InvalidName, DuplicateName, InvalidState, InsufficientResourcesFault, InvalidDatastore, RuntimeFault, RemoteException
  {
    getVimService().updateVAppConfig(getMOR(), spec);
  }
}


text:
module Darian
  # Common date methods for Time and Date classes.
  module DateMethods
    include Comparable

    attr_reader :year
    attr_reader :month
    attr_reader :sol

    attr_reader :since_epoch
    attr_reader :week_sol
    attr_reader :season
    attr_reader :sol_of_season
    attr_reader :month_of_season

    alias :day      :sol
    alias :week_day :week_sol

    def month_name
      case @month
        when  1 then 'Sagittarius'
        when  2 then 'Dhanus'
        when  3 then 'Capricornus'
        when  4 then 'Makara'
        when  5 then 'Aquarius'
        when  6 then 'Kumbha'
        when  7 then 'Pisces'
        when  8 then 'Mina'
        when  9 then 'Aries'
        when 10 then 'Mesha'
        when 11 then 'Taurus'
        when 12 then 'Rishabha'
        when 13 then 'Gemini'
        when 14 then 'Mithuna'
        when 15 then 'Cancer'
        when 16 then 'Karka'
        when 17 then 'Leo'
        when 18 then 'Simha'
        when 19 then 'Virgo'
        when 20 then 'Kanya'
        when 21 then 'Libra'
        when 22 then 'Tula'
        when 23 then 'Scorpius'
        when 24 then 'Vrishika'
      end
    end

    def week_sol_name
      case @week_sol
        when 1 then 'Sol Solis'
      	when 2 then 'Sol Lunae'
      	when 3 then 'Sol Martis'
      	when 4 then 'Sol Mercurii'
      	when 5 then 'Sol Jovis'
      	when 6 then 'Sol Veneris'
      	when 7 then 'Sol Saturni'
      end
    end
    alias :week_day_name :week_sol_name

    def <=>(another)
      since_epoch <=> another.since_epoch
    end
  end
end


text:
SET(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/ALCheck.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/ALCheck.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/AudioDevice.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/AudioDevice.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/Listener.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/Listener.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/Music.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/Music.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/Sound.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/Sound.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/SoundBuffer.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/SoundBuffer.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/SoundBufferRecorder.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/SoundBufferRecorder.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/SoundFile.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/SoundFile.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/SoundRecorder.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/SoundRecorder.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/SoundSource.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/SoundSource.cpp.o"
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/SoundStream.cpp" "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/Audio/CMakeFiles/sfml-audio.dir/SoundStream.cpp.o"
  )
SET(CMAKE_CXX_COMPILER_ID "GNU")

# Pairs of files generated by the same build rule.
SET(CMAKE_MULTIPLE_OUTPUT_PAIRS
  "/home/adrien/Documents/Stickman-project/SFML-master/lib/libsfml-audio.so" "/home/adrien/Documents/Stickman-project/SFML-master/lib/libsfml-audio.so.2.1"
  "/home/adrien/Documents/Stickman-project/SFML-master/lib/libsfml-audio.so.2" "/home/adrien/Documents/Stickman-project/SFML-master/lib/libsfml-audio.so.2.1"
  )

# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
  "/home/adrien/Documents/Stickman-project/SFML-master/src/SFML/System/CMakeFiles/sfml-system.dir/DependInfo.cmake"
  )

# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
  "include"
  "src"
  "/usr/include/AL"
  )
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})


text:
import React, { Component, PropTypes } from 'react';
import { Col, Tabs, Tab } from 'react-bootstrap';
import InsertFeature from './InsertFeature';
import InsertSection from './InsertSection';
import styles from './styles/Features.sass';

export default class InsertTabs extends Component {
    render() {
        return (
            <Col sm={10} smPush={1}>
                <Tabs defaultActiveKey={1} animation={false} id="addTabs" className={styles['feature-tabs']}>
                    <Tab eventKey={1} title="Add section">
                        <InsertSection />
                    </Tab>
                    <Tab eventKey={2} title="Add feature">
                        <InsertFeature />
                    </Tab>
                </Tabs>
            </Col>
        )
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Curve" inherits="Resource" category="Core" version="3.2">
	<brief_description>
		A mathematic curve.
	</brief_description>
	<description>
		A curve that can be saved and re-used for other objects. By default it ranges between [code]0[/code] and [code]1[/code] on the y-axis and positions points relative to the [code]0.5[/code] y-position.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="add_point">
			<return type="int">
			</return>
			<argument index="0" name="position" type="Vector2">
			</argument>
			<argument index="1" name="left_tangent" type="float" default="0">
			</argument>
			<argument index="2" name="right_tangent" type="float" default="0">
			</argument>
			<argument index="3" name="left_mode" type="int" enum="Curve.TangentMode" default="0">
			</argument>
			<argument index="4" name="right_mode" type="int" enum="Curve.TangentMode" default="0">
			</argument>
			<description>
				Adds a point to the curve. For each side, if the [code]*_mode[/code] is [code]TANGENT_LINEAR[/code], the [code]*_tangent[/code] angle (in degrees) uses the slope of the curve halfway to the adjacent point. Allows custom assignments to the [code]*_tangent[/code] angle if [code]*_mode[/code] is set to [code]TANGENT_FREE[/code].
			</description>
		</method>
		<method name="bake">
			<return type="void">
			</return>
			<description>
				Recomputes the baked cache of points for the curve.
			</description>
		</method>
		<method name="clean_dupes">
			<return type="void">
			</return>
			<description>
				Removes points that are closer than [code]CMP_EPSILON[/code] (0.00001) units to their neighbor on the curve.
			</description>
		</method>
		<method name="clear_points">
			<return type="void">
			</return>
			<description>
				Removes all points from the curve.
			</description>
		</method>
		<method name="get_point_count" qualifiers="const">
			<return type="int">
			</return>
			<description>
				Returns the number of points describing the curve.
			</description>
		</method>
		<method name="get_point_left_mode" qualifiers="const">
			<return type="int" enum="Curve.TangentMode">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<description>
				Returns the left [code]TangentMode[/code] for the point at [code]index[/code].
			</description>
		</method>
		<method name="get_point_left_tangent" qualifiers="const">
			<return type="float">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<description>
				Returns the left tangent angle (in degrees) for the point at [code]index[/code].
			</description>
		</method>
		<method name="get_point_position" qualifiers="const">
			<return type="Vector2">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<description>
				Returns the curve coordinates for the point at [code]index[/code].
			</description>
		</method>
		<method name="get_point_right_mode" qualifiers="const">
			<return type="int" enum="Curve.TangentMode">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<description>
				Returns the right [code]TangentMode[/code] for the point at [code]index[/code].
			</description>
		</method>
		<method name="get_point_right_tangent" qualifiers="const">
			<return type="float">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<description>
				Returns the right tangent angle (in degrees) for the point at [code]index[/code].
			</description>
		</method>
		<method name="interpolate" qualifiers="const">
			<return type="float">
			</return>
			<argument index="0" name="offset" type="float">
			</argument>
			<description>
				Returns the y value for the point that would exist at x-position [code]offset[/code] along the curve.
			</description>
		</method>
		<method name="interpolate_baked">
			<return type="float">
			</return>
			<argument index="0" name="offset" type="float">
			</argument>
			<description>
				Returns the y value for the point that would exist at x-position [code]offset[/code] along the curve using the baked cache. Bakes the curve's points if not already baked.
			</description>
		</method>
		<method name="remove_point">
			<return type="void">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<description>
				Removes the point at [code]index[/code] from the curve.
			</description>
		</method>
		<method name="set_point_left_mode">
			<return type="void">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<argument index="1" name="mode" type="int" enum="Curve.TangentMode">
			</argument>
			<description>
				Sets the left [code]TangentMode[/code] for the point at [code]index[/code] to [code]mode[/code].
			</description>
		</method>
		<method name="set_point_left_tangent">
			<return type="void">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<argument index="1" name="tangent" type="float">
			</argument>
			<description>
				Sets the left tangent angle for the point at [code]index[/code] to [code]tangent[/code].
			</description>
		</method>
		<method name="set_point_offset">
			<return type="int">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<argument index="1" name="offset" type="float">
			</argument>
			<description>
				Sets the offset from [code]0.5[/code]
			</description>
		</method>
		<method name="set_point_right_mode">
			<return type="void">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<argument index="1" name="mode" type="int" enum="Curve.TangentMode">
			</argument>
			<description>
				Sets the right [code]TangentMode[/code] for the point at [code]index[/code] to [code]mode[/code].
			</description>
		</method>
		<method name="set_point_right_tangent">
			<return type="void">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<argument index="1" name="tangent" type="float">
			</argument>
			<description>
				Sets the right tangent angle for the point at [code]index[/code] to [code]tangent[/code].
			</description>
		</method>
		<method name="set_point_value">
			<return type="void">
			</return>
			<argument index="0" name="index" type="int">
			</argument>
			<argument index="1" name="y" type="float">
			</argument>
			<description>
				Assigns the vertical position [code]y[/code] to the point at [code]index[/code].
			</description>
		</method>
	</methods>
	<members>
		<member name="bake_resolution" type="int" setter="set_bake_resolution" getter="get_bake_resolution">
			The number of points to include in the baked (i.e. cached) curve data.
		</member>
		<member name="max_value" type="float" setter="set_max_value" getter="get_max_value">
			The maximum value the curve can reach. Default value: [code]1[/code].
		</member>
		<member name="min_value" type="float" setter="set_min_value" getter="get_min_value">
			The minimum value the curve can reach. Default value: [code]0[/code].
		</member>
	</members>
	<signals>
		<signal name="range_changed">
			<description>
				Emitted when [member max_value] or [member min_value] is changed.
			</description>
		</signal>
	</signals>
	<constants>
		<constant name="TANGENT_FREE" value="0" enum="TangentMode">
			The tangent on this side of the point is user-defined.
		</constant>
		<constant name="TANGENT_LINEAR" value="1" enum="TangentMode">
			The curve calculates the tangent on this side of the point as the slope halfway towards the adjacent point.
		</constant>
		<constant name="TANGENT_MODE_COUNT" value="2" enum="TangentMode">
			The total number of available tangent modes.
		</constant>
	</constants>
</class>


text:
<?xml version="1.0"?>
<monkeyml version="1.0">
    <io_devices>
    </io_devices>
    <variables>
        <variable tag="counter" full_name="counter" default_value="0" scope="GLOBAL" type="INTEGER" editable="never" logging="when_changed" persistant="NO"/>
        <variable tag="currentTime" full_name="currentTime" default_value="0" scope="GLOBAL" type="INTEGER" editable="never" logging="when_changed" persistant="NO"/>
    </variables>
    <sounds/>
    <stimuli>
        <stimulus tag="background" full_name="background" type="blank_screen" color="0, 0, 0"/>
    </stimuli>
    <experiment tag="TimingTest" full_name="Super Awesome Happy" description="">
        <protocol tag="TimingProtocol" full_name="sup" selection="sequential_ascending" nsamples="1" sampling_method="cycles" description="" interruptible="YES">
            <block tag="block" full_name="supsup" selection="sequential_ascending" nsamples="1" sampling_method="cycles" description="" interruptible="YES">
                <trial tag="trial" full_name="fullname20" selection="sequential_ascending" nsamples="1" sampling_method="cycles" description="" interruptible="YES">
                    <list tag="RSVP_list" selection="sequential_ascending" nsamples="100" sampling_method="samples" description="" interruptible="YES">
                        <task_system tag="task_system21" full_name="fullname21" description="" interruptible="YES">
                            <task_system_state tag="initiation" full_name="initiation" description="" interruptible="YES">
                                <action tag="Set Timebase_1" type="set_timebase" timebase="beginning_of_trial"/>
                                <action tag="report message" full_name="report message" type="report" message="**************TRIAL STARTING**************"/>
                                <action tag="update counter" full_name="update counter" type="assignment" variable="counter" value="0"/>
                                <action tag="update counter" full_name="update counter" type="assignment" variable="currentTime" value="now()"/>
                                <action tag="report message" full_name="report message" type="report" message="* Current Time = $currentTime"/>
                                <action tag="report message" full_name="report message" type="report" message="* counter = $counter"/>
                                <transition tag="go to background on" full_name="go to background on" target="A" type="direct"/>
                            </task_system_state>
                            <task_system_state tag="A" full_name="background on" description="" interruptible="YES">
                                <action tag="update counter" full_name="update counter" type="assignment" variable="counter" value="counter+1"/>
                                <action tag="update counter" full_name="update counter" type="assignment" variable="currentTime" value="now()"/>
                                <action tag="report message" full_name="report message" type="report" message="*A* Current Time = $currentTime"/>
                                <action tag="report message" full_name="report message" type="report" message="*A* counter = $counter"/>
                                <action tag="start stm_timer" full_name="start stm_timer" type="start_timer" timer="stm_timer" duration="33ms" timebase=""/>
                                <transition tag="go to stm on" full_name="go to stm on" target="B" type="timer_expired" timer="stm_timer"/>
                            </task_system_state>
                            <task_system_state tag="B" full_name="stm on" description="" interruptible="YES">
                                <action tag="update counter" full_name="update counter" type="assignment" variable="currentTime" value="now()"/>
                                <action tag="report message" full_name="report message" type="report" message="*B* Current Time = $currentTime"/>
                                <action tag="report message" full_name="report message" type="report" message="*B* counter = $counter"/>
                                <transition tag="go to trial end" full_name="go to trial end" target="trial end" type="conditional" condition="counter==5"/>
                                <transition tag="go to background on" full_name="go to background on" target="A" type="timer_expired" timer="stm_timer"/>
                            </task_system_state>
                            <task_system_state tag="trial end" full_name="trial end" description="" interruptible="YES">
                                <action tag="report message" full_name="report message" type="report" message="**************TRIAL ENDING**************"/>
                                <action tag="update counter" full_name="update counter" type="assignment" variable="currentTime" value="now()"/>
                                <action tag="report message" full_name="report message" type="report" message="**** Current Time = $currentTime"/>
                                <action tag="report message" full_name="report message" type="report" message="**** counter = $counter"/>
                                <transition type="yield" tag="yield" full_name="yield"/>
                            </task_system_state>
                        </task_system>
                    </list>
                </trial>
            </block>
        </protocol>
    </experiment>
</monkeyml>


text:
import os
import subprocess
import time
import urllib2

class DmcaThis(object):
	def __init__(self):
		pass
	def run(self):
		while True:
			if self.is_vpn_running():
				self.when_vpn_up()
			else:
				self.when_vpn_down()
			time.sleep(.5)
	def is_vpn_running(self):
		try:
			ip = urllib2.urlopen('http://icanhazip.com', timeout=1).read().strip()
		except urllib2.URLError:
			return False
		check_endpoint = 'http://' + ip + ':8888/speedtest/'
		try:
			urllib2.urlopen(check_endpoint, timeout=1)
		except urllib2.URLError:
			return False
		return True
	def when_vpn_up(self):
		ps = subprocess.check_output(['ps', 'alx'])
		if 'deluged' not in ps:
			print 'Starting deluged'
			subprocess.call(['deluged'])
		if 'deluge-web' not in ps:
			print 'Starting deluge-web'
			subprocess.Popen(['deluge-web', '-L', 'info', '-l', '/var/log/delugeweb.log'])
	def when_vpn_down(self):
		print 'Uh oh, VPN is down! Starting OpenVPN.'
		# TODO: Try to kill these immediately
		# subprocess.call(['killall', 'deluged'])
		# subprocess.call(['killall', 'deluge-web'])
		subprocess.call(['sudo', '/etc/init.d/openvpn', 'start'])

if __name__ == '__main__':
	DmcaThis().run()


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2014 pengjianbo(pengjianbosoft@gmail.com), Inc.
  ~
  ~ 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.
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="70dp"
    android:layout_height="100dp"
    >

    <com.ez.gallery.widget.GFImageView
        android:id="@+id/iv_photo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_gf_default_photo"
        android:padding="4dp"
        android:layout_margin="4dp"
        android:scaleType="centerCrop"
        />

    <ImageView
        android:id="@+id/iv_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_delete_photo"
        android:layout_alignParentRight="true"
        android:layout_marginTop="4dp"
        />

</RelativeLayout>


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\Throwable\Exception\Generator\Resolver;

/**
 * @covers \Nelmio\Alice\Throwable\Exception\Generator\Resolver\RecursionLimitReachedExceptionFactory
 */
class RecursionLimitReachedExceptionFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testTestCreateNewExceptionWithFactory()
    {
        $exception = RecursionLimitReachedExceptionFactory::create(10, 'foo');

        $this->assertEquals(
            'Recursion limit (10 tries) reached while resolving the parameter "foo"',
            $exception->getMessage()
        );
        $this->assertEquals(0, $exception->getCode());
        $this->assertNull($exception->getPrevious());
    }
}


text:
using System.Collections.Generic;
using CuttingEdge.Conditions;

namespace ZimmerBot.Core.Processors
{
  public class ProcessorOutput
  {
    public string TemplateName { get; protected set; }

    public IDictionary<string, object> Value { get; protected set; }

    public ProcessorOutput(IDictionary<string, object> value)
      : this("default", value)
    {
    }

    public ProcessorOutput(string templateName)
      : this(templateName, new Dictionary<string, object>())
    {
    }

    public ProcessorOutput(string templateName, IDictionary<string, object> value)
    {
      Condition.Requires(templateName, nameof(templateName)).IsNotNullOrEmpty();
      TemplateName = templateName;
      Value = value;
    }
  }
}


text:
package com.lsoftware.playdoh.objects.models;

public class Dummy {

    private Integer integerValue;

    private String stringValue;

    private NestedDummy nestedDummy;

    Dummy(int integerValue, String stringValue, NestedDummy nestedDummy) {
        this.integerValue = integerValue;
        this.stringValue = stringValue;
        this.nestedDummy = nestedDummy;
    }

    public Dummy(){}

    public int getIntegerValue() {
        return integerValue;
    }

    public void setIntegerValue(int integerValue) {
        this.integerValue = integerValue;
    }

    public String getStringValue() {
        return stringValue;
    }

    public void setStringValue(String stringValue) {
        this.stringValue = stringValue;
    }

    public NestedDummy getNestedDummy() {
        return nestedDummy;
    }

    public void setNestedDummy(NestedDummy nestedDummy) {
        this.nestedDummy = nestedDummy;
    }

    @Override
    public String toString() {
        return "Dummy{" +
                "integerValue=" + integerValue +
                ", stringValue='" + stringValue + '\'' +
                ", nested=" + nestedDummy +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Dummy)) return false;

        Dummy dummy = (Dummy) o;

        if (integerValue != null ? !integerValue.equals(dummy.integerValue) : dummy.integerValue != null) return false;
        if (stringValue != null ? !stringValue.equals(dummy.stringValue) : dummy.stringValue != null) return false;
        return !(nestedDummy != null ? !nestedDummy.equals(dummy.nestedDummy) : dummy.nestedDummy != null);

    }

    @Override
    public int hashCode() {
        int result = integerValue != null ? integerValue.hashCode() : 0;
        result = 31 * result + (stringValue != null ? stringValue.hashCode() : 0);
        result = 31 * result + (nestedDummy != null ? nestedDummy.hashCode() : 0);
        return result;
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/bigquery/storage/v1beta2/storage.proto

package com.google.cloud.bigquery.storage.v1beta2;

public interface CreateWriteStreamRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Reference to the table to which the stream belongs, in the format
   * of `projects/{project}/datasets/{dataset}/tables/{table}`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. Reference to the table to which the stream belongs, in the format
   * of `projects/{project}/datasets/{dataset}/tables/{table}`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Required. Stream to be created.
   *

   *
   *
   * .google.cloud.bigquery.storage.v1beta2.WriteStream write_stream = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the writeStream field is set.
   */
  boolean hasWriteStream();
  /**
   *
   *
   *

   * Required. Stream to be created.
   *

   *
   *
   * .google.cloud.bigquery.storage.v1beta2.WriteStream write_stream = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The writeStream.
   */
  com.google.cloud.bigquery.storage.v1beta2.WriteStream getWriteStream();
  /**
   *
   *
   *

   * Required. Stream to be created.
   *

   *
   *
   * .google.cloud.bigquery.storage.v1beta2.WriteStream write_stream = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.cloud.bigquery.storage.v1beta2.WriteStreamOrBuilder getWriteStreamOrBuilder();
}


text:
$(document).ready(function() {
	$('.start-new-note').click(function(e) {
		newNote = $('.new-note');
		newNote.show();
		$('textarea', newNote).focus();
		$(this).hide();
	});

	get_preview = function(obj) {
		note = obj.parents('div.new-note');
		frm = $('form', note);
		$.post(frm.attr('action') + '?dryrun', frm.serialize(), function(data, text, request) {
			$('#preview', note).html(data);
			$('#preview pre code', note).addClass('prettyprint');
			prettyPrint();
		});
	};

	$('div.new-note .text .body textarea')
		.bind('paste', function() {obj = $(this); setTimeout(function() {get_preview(obj);}, 0)})
		.typing({delay: 400, stop: function(e, obj) {get_preview(obj);}});

	$('a#undelete').click(function() {
		lnk = $(this);
		frm = lnk.parents('form');
		$.post(frm.attr('action'), frm.serialize(), function(data, text, request) {
			switch(request.status) {
			case 200:
			case 298:
			default:
				lnk.replaceWith($("<span>").text("Unable to undelete: " + data));
				break;
			case 299:
				document.location.reload(true);
				break;
			}
		});
	});
});


text:
import { AccountMap } from './accountMaps';
import { TransferJob } from './transfers';

export enum PersonalDriveMappingJobConventionMatch {
	Account = 'account',
	Container = 'container',
	Ldap = 'ldap'
}

export enum PersonalDriveMappingJobConventionUsers {
	Source = 'source',
	Destination = 'destination',
	Ldap = 'ldap'
}

export interface PersonalDriveMappingConvention {
	account_map?: AccountMap;
	match?: PersonalDriveMappingJobConventionMatch;
	include_matches?: boolean;
	remove_invalid?: boolean;
	users?: PersonalDriveMappingJobConventionUsers;
	search_domain?: string;
}

export interface PersonalDriveMappingJob extends TransferJob {
	convention?: PersonalDriveMappingConvention;
}


text:
class Parser(object):

    def parse(self, toParse):
        result = []
        for num in toParse:
            str_num = str(num)
            if self._is_fizz(num, str_num) and self._is_buzz(num, str_num):
                result.append("fizzbuzz")
            elif self._is_fizz(num, str_num):
                result.append("fizz")
            elif self._is_buzz(num, str_num):
                result.append("buzz")
            else:
                result.append(str_num)
        return result

    def _is_divisible_by(self, num, div):
        return num % div == 0

    def _is_element_of(self, n, seq):
        return n in seq

    def _is_fizz(self, num, char_seq):
        return self._is_divisible_by(num, 3) or self._is_element_of('3', char_seq)

    def _is_buzz(self, num, char_seq):
        return self._is_divisible_by(num, 5) or self._is_element_of('5', char_seq)

import unittest

class FizzBuzzParserTest(unittest.TestCase):

    def setUp(self):
        self.parser = Parser()

    def test_parses_empty_list(self):
        self.assertEqual([], self.parser.parse([]))

    def test_parses_one(self):
        self.assertEqual(["1"], self.parser.parse([1]))

    def test_parses_three(self):
        self.assertEqual(["fizz"], self.parser.parse([3]))

    def test_parses_nine(self):
        self.assertEqual(["fizz"], self.parser.parse([9]))

    def test_parses_thirteen(self):
        self.assertEqual(["fizz"], self.parser.parse([13]))

    def test_parses_five(self):
        self.assertEqual(["buzz"], self.parser.parse([5]))

    def test_parses_ten(self):
        self.assertEqual(["buzz"], self.parser.parse([10]))

    def test_parses_fifty_two(self):
        self.assertEqual(["buzz"], self.parser.parse([52]))

    def test_parses_fifteen(self):
        self.assertEqual(["fizzbuzz"], self.parser.parse([15]))

    def test_parses_fifty_three(self):
        self.assertEqual(["fizzbuzz"], self.parser.parse([53]))