text:
/**
 */
package br.com.levysiqueira.textualusecase.impl;

import br.com.levysiqueira.textualusecase.Actor;
import br.com.levysiqueira.textualusecase.TextualUseCasePackage;
import br.com.levysiqueira.textualusecase.UseCase;
import br.com.levysiqueira.textualusecase.UseCaseModel;

import java.util.Collection;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * An implementation of the model object 'Actor'.
 *
 *

 * The following features are implemented:
 *

 *
{@link br.com.levysiqueira.textualusecase.impl.ActorImpl#getUseCaseModel Use Case Model}

 *
{@link br.com.levysiqueira.textualusecase.impl.ActorImpl#getUseCase Use Case}

 *

 *

 *
 * @generated
 */
public class ActorImpl extends AgentImpl implements Actor {
	/**
	 * The cached value of the '{@link #getUseCase() Use Case}' reference list.
	 *
	 *
	 * @see #getUseCase()
	 * @generated
	 * @ordered
	 */
	protected EList<UseCase> useCase;

	/**
	 *
	 *
	 * @generated
	 */
	protected ActorImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return TextualUseCasePackage.Literals.ACTOR;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public UseCaseModel getUseCaseModel() {
		if (eContainerFeatureID() != TextualUseCasePackage.ACTOR__USE_CASE_MODEL) return null;
		return (UseCaseModel)eInternalContainer();
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetUseCaseModel(UseCaseModel newUseCaseModel, NotificationChain msgs) {
		msgs = eBasicSetContainer((InternalEObject)newUseCaseModel, TextualUseCasePackage.ACTOR__USE_CASE_MODEL, msgs);
		return msgs;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setUseCaseModel(UseCaseModel newUseCaseModel) {
		if (newUseCaseModel != eInternalContainer() || (eContainerFeatureID() != TextualUseCasePackage.ACTOR__USE_CASE_MODEL && newUseCaseModel != null)) {
			if (EcoreUtil.isAncestor(this, newUseCaseModel))
				throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
			NotificationChain msgs = null;
			if (eInternalContainer() != null)
				msgs = eBasicRemoveFromContainer(msgs);
			if (newUseCaseModel != null)
				msgs = ((InternalEObject)newUseCaseModel).eInverseAdd(this, TextualUseCasePackage.USE_CASE_MODEL__ACTOR, UseCaseModel.class, msgs);
			msgs = basicSetUseCaseModel(newUseCaseModel, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, TextualUseCasePackage.ACTOR__USE_CASE_MODEL, newUseCaseModel, newUseCaseModel));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EList<UseCase> getUseCase() {
		if (useCase == null) {
			useCase = new EObjectWithInverseResolvingEList.ManyInverse<UseCase>(UseCase.class, this, TextualUseCasePackage.ACTOR__USE_CASE, TextualUseCasePackage.USE_CASE__ACTOR);
		}
		return useCase;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				if (eInternalContainer() != null)
					msgs = eBasicRemoveFromContainer(msgs);
				return basicSetUseCaseModel((UseCaseModel)otherEnd, msgs);
			case TextualUseCasePackage.ACTOR__USE_CASE:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getUseCase()).basicAdd(otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				return basicSetUseCaseModel(null, msgs);
			case TextualUseCasePackage.ACTOR__USE_CASE:
				return ((InternalEList<?>)getUseCase()).basicRemove(otherEnd, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
		switch (eContainerFeatureID()) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				return eInternalContainer().eInverseRemove(this, TextualUseCasePackage.USE_CASE_MODEL__ACTOR, UseCaseModel.class, msgs);
		}
		return super.eBasicRemoveFromContainerFeature(msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				return getUseCaseModel();
			case TextualUseCasePackage.ACTOR__USE_CASE:
				return getUseCase();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				setUseCaseModel((UseCaseModel)newValue);
				return;
			case TextualUseCasePackage.ACTOR__USE_CASE:
				getUseCase().clear();
				getUseCase().addAll((Collection<? extends UseCase>)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				setUseCaseModel((UseCaseModel)null);
				return;
			case TextualUseCasePackage.ACTOR__USE_CASE:
				getUseCase().clear();
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case TextualUseCasePackage.ACTOR__USE_CASE_MODEL:
				return getUseCaseModel() != null;
			case TextualUseCasePackage.ACTOR__USE_CASE:
				return useCase != null && !useCase.isEmpty();
		}
		return super.eIsSet(featureID);
	}

} //ActorImpl


text:
package com.eaglesakura.lib.android.game.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/**
 * File関連の便利メソッドを提供する
 *
 * @author TAKESHI YAMASHITA
 */
public class FileUtil {

    /**
     * 指定箇所へファイルをコピーする。
     */
    public static final void copy(File src, File dst) throws IOException {
        mkdir(dst.getParentFile());
        InputStream srcStream = new FileInputStream(src);
        OutputStream dstStream = new FileOutputStream(dst);

        //! 適当なバッファサイズを決める。
        byte[] buffer = new byte[128 * 1024];
        int readed = 0;

        //! 読めなくなるまで読み込みを続ける
        while ((readed = srcStream.read(buffer)) > 0) {
            dstStream.write(buffer, 0, readed);
        }

        srcStream.close();
        dstStream.close();

        //! 最終変更日を修正する
        dst.setLastModified(src.lastModified());
    }

    /**
     * コピー先が存在しない、もしくはMD5が一致しない場合のみコピーを行い、それ以外はコピーを行わない
     */
    public static final void copyOrUpdate(File src, File dst) throws IOException {
        if (!dst.isFile()) {
            // ファイルが存在しないからコピーする
            copy(src, dst);
            return;
        }

        String srcSHA1 = genSHA1(src);
        String dstSHA1 = genSHA1(dst);

        // 2つのSHA1が一致しないため、コピーする
        if (!srcSHA1.equals(dstSHA1)) {
            copy(src, dst);
        }
    }

    /**
     * ファイルからMD5を求める。
     */
    public static String genMD5(File file) {
        try {

            FileInputStream is = new FileInputStream(file);
            final MessageDigest md = MessageDigest.getInstance("MD5");
            {
                byte[] buffer = new byte[128 * 1024];
                int readed = 0;

                while ((readed = is.read(buffer)) > 0) {
                    md.update(buffer, 0, readed);
                }
            }
            is.close();
            byte[] digest = md.digest();

            StringBuffer sBuffer = new StringBuffer(digest.length * 2);
            for (byte b : digest) {
                String s = Integer.toHexString(((int) b) & 0xff);

                if (s.length() == 1) {
                    sBuffer.append('0');
                }
                sBuffer.append(s);
            }
            return sBuffer.toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 末尾・先端のバイト列を用いた単純なハッシュを生成する
     * ファイルフォーマットによっては衝突の可能性が非常に高いため、利用する場合は十分に検討を行うこと。
     */
    public static String genShortHash(File file, int checkLength) {
        if (!file.isFile()) {
            return null;
        }

        // 十分に小さいファイルの場合は検証を行わずに返す
        if (file.length() < (checkLength * 2)) {
            return FileUtil.genSHA1(file);
        }

        try {
            String start = null;
            String end = null;
            // 先頭の任意バイトを読み込む
            {
                byte[] buffer = new byte[checkLength];
                FileInputStream is = new FileInputStream(file);
                is.read(buffer);
                is.close();
                start = EncodeUtil.genMD5(buffer);
            }
            // 末尾の任意バイトを読み込む
            {
                byte[] buffer = new byte[checkLength];
                FileInputStream is = new FileInputStream(file);
                is.skip(file.length() - checkLength);
                is.read(buffer);
                is.close();
                end = EncodeUtil.genMD5(buffer);
            }

            return start + end;

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * ファイルからMD5を求める。
     */
    public static String genSHA1(File file) {
        try {

            FileInputStream is = new FileInputStream(file);
            final MessageDigest md = MessageDigest.getInstance("SHA-1");
            {
                byte[] buffer = new byte[128 * 1024];
                int readed = 0;

                while ((readed = is.read(buffer)) > 0) {
                    md.update(buffer, 0, readed);
                }
            }
            is.close();
            byte[] digest = md.digest();

            StringBuffer sBuffer = new StringBuffer(digest.length * 2);
            for (byte b : digest) {
                String s = Integer.toHexString(((int) b) & 0xff);

                if (s.length() == 1) {
                    sBuffer.append('0');
                }
                sBuffer.append(s);
            }
            return sBuffer.toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * ディレクトリを再帰的に削除する。
     */
    public static void delete(File root) {
        if (root.isFile()) {
            root.delete();
            return;
        }
        File[] files = root.listFiles();
        if (files != null) {
            for (File file : files) {
                delete(file);
            }
        }
        root.delete();
    }

    /**
     * ファイル拡張子を取得する。
     */
    public static String getFileExt(String fileName) {
        if (fileName == null)
            return "";
        int point = fileName.lastIndexOf('.');
        if (point != -1) {
            return fileName.substring(point + 1);
        } else {
            // fileName = "";
            return "";
        }
    }

    /**
     * 拡張子付のファイル名からファイル名のみを抜き出す
     *
     * @param fileName ファイル名
     * @return 拡張子を取り除いたファイル名
     */
    public static String getFileName(final String fileName) {
        if (fileName == null)
            return "";
        int point = fileName.lastIndexOf('.');
        if (point != -1) {
            return fileName.substring(0, point);
        } else {
            // fileName = "";
            return "";
        }
    }

    /**
     * ファイルパスからSHA1を得る。
     */
    public static String genPathSHA1(final File file) {
        String path = file.getAbsolutePath();
        path = normalizeFileName(path);
        return EncodeUtil.genSHA1(path.getBytes());
    }

    /**
     * カレントディレクトリのパスを取得する。
     */
    public static String getCurrentDirectoryPath() {
        return (new File(".").getAbsoluteFile().getParent());
    }

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

    /**
     * ファイルを名前順にソートする。
     * inの中身がソートされるため、戻り値は同じ参照となる。
     */
    public static File[] sort(File[] files) {
        if (files == null) {
            return null;
        }
        List<File> temp = new ArrayList<File>();
        for (File f : files) {
            temp.add(f);
        }

        Collections.sort(temp, new Comparator<File>() {
            @Override
            public int compare(File object1, File object2) {
                String f0 = object1.getAbsolutePath();
                String f1 = object2.getAbsolutePath();
                return GameUtil.compareString(f0, f1);
            }
        });

        for (int i = 0; i < files.length; ++i) {
            files[i] = temp.get(i);
        }

        return files;
    }

    /**
     * 比較等の処理を行うために文字列を正規化する
     */
    public static String normalizeFileName(String origin) {
        origin = GameUtil.zenkakuEngToHankakuEng(origin);
        origin = GameUtil.macStringToWinString(origin);

        while (origin.indexOf('?') >= 0) {
            origin = origin.replace('?', '?');
        }
        return origin;
    }

    /**
     * そこまでの道を含めてディレクトリを作成する。
     */
    public static File mkdir(File dir) {
        // 作成済みだったら何もしない
        if (dir.isDirectory()) {
            return dir;
        }
        File parent = dir.getAbsoluteFile().getParentFile();
        if (parent.isDirectory()) {
            dir.mkdir();
        } else {
            // 親が作られてなかったら作る
            mkdir(parent);
        }

        return dir;
    }

    /**
     * parentからtargetに到達するまでの全てのファイルを取得する。
     * 戻り値にtargetとparentも含まれる。
     * 階層が上にあるFileがindexの0に近くなる。
     */
    public static List<File> getDirectoryRoute(File target, File parent) {
        List<File> result = new LinkedList<File>();
        File current = target;
        while (!equals(current, parent)) {
            result.add(0, current);
            current = current.getParentFile();
        }
        result.add(0, parent);
        return result;
    }

    /**
     * ディレクトリの中身を完全削除する。
     * dirフォルダ自体は残る。
     */
    public static File cleanDirectory(File dir) {
        if (dir.isFile()) {
            return null;
        }
        delete(dir);
        mkdir(dir);
        return dir;
    }

    /**
     * 同じ内容を指していた場合はtrue
     */
    public static boolean equals(File a, File b) {
        if (a == null || b == null) {
            return false;
        }
        return a.getAbsolutePath().equals(b.getAbsolutePath());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ql

import (
	"bytes"
	"fmt"
	"log"
	"strings"
	"sync"
)

// NOTE: all stmt implementations must be safe for concurrent use by multiple
// goroutines.  If the exec method requires any execution domain local data,
// they must be held out of the implementing instance.
var (
	_ stmt = (*alterTableAddStmt)(nil)
	_ stmt = (*alterTableDropColumnStmt)(nil)
	_ stmt = (*createIndexStmt)(nil)
	_ stmt = (*createTableStmt)(nil)
	_ stmt = (*deleteStmt)(nil) //TODO use indices (need dlist)
	_ stmt = (*dropIndexStmt)(nil)
	_ stmt = (*dropTableStmt)(nil)
	_ stmt = (*insertIntoStmt)(nil)
	_ stmt = (*selectStmt)(nil)
	_ stmt = (*truncateTableStmt)(nil)
	_ stmt = (*updateStmt)(nil) //TODO use indices
	_ stmt = beginTransactionStmt{}
	_ stmt = commitStmt{}
	_ stmt = rollbackStmt{}

	exprCache   = map[string]expression{}
	exprCacheMu sync.Mutex
)

type stmt interface {
	// never invoked for
	// - beginTransactionStmt
	// - commitStmt
	// - rollbackStmt
	exec(ctx *execCtx) (Recordset, error)

	// return value ignored for
	// - beginTransactionStmt
	// - commitStmt
	// - rollbackStmt
	isUpdating() bool
	String() string
}

type execCtx struct { //LATER +shared temp
	db  *DB
	arg []interface{}
}

type updateStmt struct {
	tableName string
	list      []assignment
	where     expression
}

func str2expr(expr string) (expression, error) {
	exprCacheMu.Lock()
	e := exprCache[expr]
	exprCacheMu.Unlock()
	if e != nil {
		return e, nil
	}

	src := "select " + expr + " from t"
	l, err := Compile(src)
	if err != nil {
		return nil, err
	}

	e = l.l[0].(*selectStmt).flds[0].expr
	exprCacheMu.Lock()
	exprCache[expr] = e
	exprCacheMu.Unlock()
	return e, nil
}

func (s *updateStmt) String() string {
	u := fmt.Sprintf("UPDATE %s", s.tableName)
	a := make([]string, len(s.list))
	for i, v := range s.list {
		a[i] = v.String()
	}
	w := ""
	if s.where != nil {
		w = fmt.Sprintf(" WHERE %s", s.where)
	}
	return fmt.Sprintf("%s %s%s;", u, strings.Join(a, ", "), w)
}

func (s *updateStmt) exec(ctx *execCtx) (_ Recordset, err error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("UPDATE: table %s does not exist", s.tableName)
	}

	tcols := make([]*col, len(s.list))
	for i, asgn := range s.list {
		col := findCol(t.cols, asgn.colName)
		if col == nil {
			return nil, fmt.Errorf("UPDATE: unknown column %s", asgn.colName)
		}
		tcols[i] = col
	}

	constraints, defaults, err := constraintsAndDefaults(ctx, s.tableName)
	if err != nil {
		return nil, err
	}

	m := map[interface{}]interface{}{}
	var nh int64
	expr := s.where
	blobCols := t.blobCols()
	cc := ctx.db.cc
	var old []interface{}
	var touched []bool
	if t.hasIndices() {
		old = make([]interface{}, len(t.cols0))
		touched = make([]bool, len(t.cols0))
	}
	for h := t.head; h != 0; h = nh {
		// Read can return lazily expanded chunks
		data, err := t.store.Read(nil, h, t.cols...)
		if err != nil {
			return nil, err
		}

		nh = data[0].(int64)
		for _, col := range t.cols {
			m[col.name] = data[2+col.index]
		}
		m["$id"] = data[1]
		if expr != nil {
			val, err := s.where.eval(ctx, m, ctx.arg)
			if err != nil {
				return nil, err
			}

			if val == nil {
				continue
			}

			x, ok := val.(bool)
			if !ok {
				return nil, fmt.Errorf("invalid WHERE expression %s (value of type %T)", val, val)
			}

			if !x {
				continue
			}
		}

		// hit
		for i, asgn := range s.list {
			val, err := asgn.expr.eval(ctx, m, ctx.arg)
			if err != nil {
				return nil, err
			}

			colIndex := tcols[i].index
			if t.hasIndices() {
				old[colIndex] = data[2+colIndex]
				touched[colIndex] = true
			}
			data[2+colIndex] = val
		}
		if err = typeCheck(data[2:], t.cols); err != nil {
			return nil, err
		}

		if len(constraints) != 0 { // => len(defaults) != 0 as well
			if err = checkConstraintsAndDefaults(ctx, data[2:], t.cols, m, constraints, defaults); err != nil {
				return nil, err
			}
		}

		for i, v := range t.indices {
			if i == 0 { // id() N/A
				continue
			}

			if v == nil || !touched[i-1] {
				continue
			}

			if err = v.x.Delete(old[i-1], h); err != nil {
				return nil, err
			}
		}

		if err = t.store.UpdateRow(h, blobCols, data...); err != nil { //LATER detect which blobs are actually affected
			return nil, err
		}

		for i, v := range t.indices {
			if i == 0 { // id() N/A
				continue
			}

			if v == nil || !touched[i-1] {
				continue
			}

			if err = v.x.Create(data[2+i-1], h); err != nil {
				return nil, err
			}
		}
		cc.RowsAffected++
	}
	return
}

func (s *updateStmt) isUpdating() bool { return true }

type deleteStmt struct {
	tableName string
	where     expression
}

func (s *deleteStmt) String() string {
	switch {
	case s.where == nil:
		return fmt.Sprintf("DELETE FROM %s;", s.tableName)
	default:
		return fmt.Sprintf("DELETE FROM %s WHERE %s;", s.tableName, s.where)
	}
}

func (s *deleteStmt) exec(ctx *execCtx) (_ Recordset, err error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("DELETE FROM: table %s does not exist", s.tableName)
	}

	m := map[interface{}]interface{}{}
	var ph, h, nh int64
	var data []interface{}
	blobCols := t.blobCols()
	cc := ctx.db.cc
	for h = t.head; h != 0; ph, h = h, nh {
		for i, v := range data {
			c, ok := v.(chunk)
			if !ok {
				continue
			}

			data[i] = c.b
		}
		// Read can return lazily expanded chunks
		data, err = t.store.Read(nil, h, t.cols...)
		if err != nil {
			return nil, err
		}

		nh = data[0].(int64)
		for _, col := range t.cols {
			m[col.name] = data[2+col.index]
		}
		m["$id"] = data[1]
		val, err := s.where.eval(ctx, m, ctx.arg)
		if err != nil {
			return nil, err
		}

		if val == nil {
			continue
		}

		x, ok := val.(bool)
		if !ok {
			return nil, fmt.Errorf("invalid WHERE expression %s (value of type %T)", val, val)
		}

		if !x {
			continue
		}

		// hit
		for i, v := range t.indices {
			if v == nil {
				continue
			}

			// overflow chunks left in place
			if err = v.x.Delete(data[i+1], h); err != nil {
				return nil, err
			}
		}

		// overflow chunks freed here
		if err = t.store.Delete(h, blobCols...); err != nil {
			return nil, err
		}

		cc.RowsAffected++
		switch {
		case ph == 0 && nh == 0: // "only"
			fallthrough
		case ph == 0 && nh != 0: // "first"
			if err = t.store.Update(t.hhead, nh); err != nil {
				return nil, err
			}

			t.head, h = nh, 0
		case ph != 0 && nh == 0: // "last"
			fallthrough
		case ph != 0 && nh != 0: // "inner"
			pdata, err := t.store.Read(nil, ph, t.cols...)
			if err != nil {
				return nil, err
			}

			for i, v := range pdata {
				if x, ok := v.(chunk); ok {
					pdata[i] = x.b
				}
			}
			pdata[0] = nh
			if err = t.store.Update(ph, pdata...); err != nil {
				return nil, err
			}

			h = ph
		}
	}

	return
}

func (s *deleteStmt) isUpdating() bool { return true }

type truncateTableStmt struct {
	tableName string
}

func (s *truncateTableStmt) String() string { return fmt.Sprintf("TRUNCATE TABLE %s;", s.tableName) }

func (s *truncateTableStmt) exec(ctx *execCtx) (Recordset, error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("TRUNCATE TABLE: table %s does not exist", s.tableName)
	}

	return nil, t.truncate()
}

func (s *truncateTableStmt) isUpdating() bool { return true }

type dropIndexStmt struct {
	ifExists  bool
	indexName string
}

func (s *dropIndexStmt) String() string { return fmt.Sprintf("DROP INDEX %s;", s.indexName) }

func (s *dropIndexStmt) exec(ctx *execCtx) (Recordset, error) {
	t, x := ctx.db.root.findIndexByName(s.indexName)
	if x == nil {
		if s.ifExists {
			return nil, nil
		}

		return nil, fmt.Errorf("DROP INDEX: index %s does not exist", s.indexName)
	}

	for i, v := range t.indices {
		if v == nil {
			continue
		}

		return nil, t.dropIndex(i)
	}

	panic("internal error 058")
}

func (s *dropIndexStmt) isUpdating() bool { return true }

type dropTableStmt struct {
	ifExists  bool
	tableName string
}

func (s *dropTableStmt) String() string { return fmt.Sprintf("DROP TABLE %s;", s.tableName) }

func (s *dropTableStmt) exec(ctx *execCtx) (Recordset, error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		if s.ifExists {
			return nil, nil
		}

		return nil, fmt.Errorf("DROP TABLE: table %s does not exist", s.tableName)
	}

	return nil, ctx.db.root.dropTable(t)
}

func (s *dropTableStmt) isUpdating() bool { return true }

type alterTableDropColumnStmt struct {
	tableName, colName string
}

func (s *alterTableDropColumnStmt) String() string {
	return fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s;", s.tableName, s.colName)
}

var (
	deleteColumn2 = mustCompile(`
		delete from __Column2
		where TableName == $1 && Name == $2
	`)
)

func (s *alterTableDropColumnStmt) exec(ctx *execCtx) (Recordset, error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("ALTER TABLE: table %s does not exist", s.tableName)
	}

	cols := t.cols
	for _, c := range cols {
		if c.name == s.colName {
			if len(cols) == 1 {
				return nil, fmt.Errorf("ALTER TABLE %s DROP COLUMN: cannot drop the only column: %s", s.tableName, s.colName)
			}

			if _, ok := ctx.db.root.tables["__Column2"]; ok {
				if _, err := deleteColumn2.l[0].exec(&execCtx{db: ctx.db, arg: []interface{}{s.tableName, c.name}}); err != nil {
					return nil, err
				}
			}

			c.name = ""
			t.cols0[c.index].name = ""
			if t.hasIndices() {
				if v := t.indices[c.index+1]; v != nil {
					if err := t.dropIndex(c.index + 1); err != nil {
						return nil, err
					}
				}
			}
			return nil, t.updated()
		}
	}

	return nil, fmt.Errorf("ALTER TABLE %s DROP COLUMN: column %s does not exist", s.tableName, s.colName)
}

func (s *alterTableDropColumnStmt) isUpdating() bool { return true }

type alterTableAddStmt struct {
	tableName string
	c         *col
}

func (s *alterTableAddStmt) String() string {
	r := fmt.Sprintf("ALTER TABLE %s ADD %s %s", s.tableName, s.c.name, typeStr(s.c.typ))
	c := s.c
	if x := c.constraint; x != nil { //TODO add (*col).String()
		switch e := x.expr; {
		case e != nil:
			r += " " + e.String()
		default:
			r += " NOT NULL"
		}
	}
	if x := c.dflt; x != nil {
		r += " DEFAULT " + x.String()
	}
	return r + ";"
}

func (s *alterTableAddStmt) exec(ctx *execCtx) (Recordset, error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("ALTER TABLE: table %s does not exist", s.tableName)
	}

	hasRecords := t.head != 0
	c := s.c
	if c.constraint != nil && hasRecords {
		return nil, fmt.Errorf("ALTER TABLE %s ADD %s: cannot add constrained column to table with existing data", s.tableName, c.name)
	}

	cols := t.cols
	for _, c := range cols {
		nm := c.name
		if nm == s.c.name {
			return nil, fmt.Errorf("ALTER TABLE %s ADD: column %s exists", s.tableName, nm)
		}
	}

	if t.hasIndices() {
		t.indices = append(t.indices, nil)
		t.xroots = append(t.xroots, 0)
		if err := t.store.Update(t.hxroots, t.xroots...); err != nil {
			return nil, err
		}
	}

	if c.constraint != nil || c.dflt != nil {
		for _, s := range createColumn2.l {
			_, err := s.exec(&execCtx{db: ctx.db})
			if err != nil {
				return nil, err
			}
		}
		notNull := c.constraint != nil && c.constraint.expr == nil
		var co, d string
		if c.constraint != nil && c.constraint.expr != nil {
			co = c.constraint.expr.String()
		}
		if e := c.dflt; e != nil {
			d = e.String()
		}
		if _, err := insertColumn2.l[0].exec(&execCtx{db: ctx.db, arg: []interface{}{s.tableName, c.name, notNull, co, d}}); err != nil {
			return nil, err
		}
	}

	t.cols0 = append(t.cols0, s.c)
	return nil, t.updated()
}

func (s *alterTableAddStmt) isUpdating() bool { return true }

type selectStmt struct {
	distinct      bool
	flds          []*fld
	from          *crossJoinRset
	outer         *outerJoinRset
	group         *groupByRset
	hasAggregates bool
	limit         *limitRset
	mu            sync.Mutex
	offset        *offsetRset
	order         *orderByRset
	where         *whereRset
}

func (s *selectStmt) String() string {
	var b bytes.Buffer
	b.WriteString("SELECT")
	if s.distinct {
		b.WriteString(" DISTINCT")
	}
	switch {
	case len(s.flds) == 0:
		b.WriteString(" *")
	default:
		a := make([]string, len(s.flds))
		for i, v := range s.flds {
			s := v.expr.String()
			if v.name != "" && v.name != s {
				s += " AS " + v.name
			}
			a[i] = s
		}
		b.WriteString(" " + strings.Join(a, ", "))
	}
	b.WriteString(" FROM ")
	b.WriteString(s.from.String())
	if o := s.outer; o != nil {
		switch o.typ {
		case leftJoin:
			b.WriteString(" LEFT")
		case rightJoin:
			b.WriteString(" RIGHT")
		case fullJoin:
			b.WriteString(" FULL")
		}
		b.WriteString(" OUTER JOIN ")
		switch x := o.source[0].(type) {
		case string:
			b.WriteString(x)
		case *selectStmt:
			b.WriteString("(")
			b.WriteString(x.String())
			b.WriteString(")")
		default:
			panic("internal error")
		}
		if s := o.source[1].(string); s != "" {
			b.WriteString(" AS " + s)
		}
		b.WriteString(" ON ")
		b.WriteString(o.on.String())
	}
	if s.where != nil {
		b.WriteString(" WHERE ")
		b.WriteString(s.where.expr.String())
	}
	if s.group != nil {
		b.WriteString(" GROUP BY ")
		b.WriteString(strings.Join(s.group.colNames, ", "))
	}
	if s.order != nil {
		b.WriteString(" ORDER BY ")
		b.WriteString(s.order.String())
	}
	if s.limit != nil {
		b.WriteString(" LIMIT ")
		b.WriteString(s.limit.expr.String())
	}
	if s.offset != nil {
		b.WriteString(" OFFSET ")
		b.WriteString(s.offset.expr.String())
	}
	b.WriteRune(';')
	return b.String()
}

func (s *selectStmt) do(ctx *execCtx, onlyNames bool, f func(id interface{}, data []interface{}) (more bool, err error)) (err error) {
	return s.exec0().do(ctx, onlyNames, f)
}

func (s *selectStmt) exec0() (r rset) { //LATER overlapping goroutines/pipelines
	s.mu.Lock()
	defer s.mu.Unlock()
	r = rset(s.from)
	if w := s.where; w != nil {
		switch ok, list := isPossiblyRewriteableCrossJoinWhereExpression(w.expr); ok && len(s.from.sources) > 1 {
		case true:
			//dbg("====(in, %d)\n%s\n----", len(list), s)
			tables := s.from.tables()
			if len(list) != len(tables) {
				r = &whereRset{expr: w.expr, src: r}
				break
			}

			m := map[string]int{}
			for i, v := range tables {
				m[v.name] = i
			}
			list2 := make([]int, len(list))
			for i, v := range list {
				itab, ok := m[v.table]
				if !ok {
					break
				}

				delete(m, v.table)
				list2[i] = itab
				if i == len(list)-1 { // last cycle
					if len(m) != 0 { // all tabs "consumed" exactly once
						break
					}

					// Can rewrite
					crs := s.from
					for i, v := range list {
						sel := &selectStmt{
							flds:  []*fld{}, // SELECT *
							from:  &crossJoinRset{sources: []interface{}{[]interface{}{v.table, ""}}},
							where: &whereRset{expr: v.expr},
						}
						info := tables[list2[i]]
						crs.sources[info.i] = []interface{}{sel, info.rename}
					}
					r = rset(crs)
					s.where = nil
					//dbg("====(out)\n%s\n----", s)
				}
			}
			if s.where == nil {
				break
			}

			fallthrough
		default:
			r = &whereRset{expr: w.expr, src: r}
		}
	}
	if o := s.outer; o != nil {
		o.crossJoin = r.(*crossJoinRset)
		r = o
	}
	switch {
	case !s.hasAggregates && s.group == nil: // nop
	case !s.hasAggregates && s.group != nil:
		r = &groupByRset{colNames: s.group.colNames, src: r}
	case s.hasAggregates && s.group == nil:
		r = &groupByRset{src: r}
	case s.hasAggregates && s.group != nil:
		r = &groupByRset{colNames: s.group.colNames, src: r}
	}
	r = &selectRset{flds: s.flds, src: r}
	if s.distinct {
		r = &distinctRset{src: r}
	}
	if s := s.order; s != nil {
		r = &orderByRset{asc: s.asc, by: s.by, src: r}
	}
	if s := s.offset; s != nil {
		r = &offsetRset{s.expr, r}
	}
	if s := s.limit; s != nil {
		r = &limitRset{s.expr, r}
	}
	return
}

func (s *selectStmt) exec(ctx *execCtx) (rs Recordset, err error) {
	return recordset{ctx, s.exec0(), nil}, nil
}

func (s *selectStmt) isUpdating() bool { return false }

type insertIntoStmt struct {
	colNames  []string
	lists     [][]expression
	sel       *selectStmt
	tableName string
}

func (s *insertIntoStmt) String() string {
	cn := ""
	if len(s.colNames) != 0 {
		cn = fmt.Sprintf(" (%s)", strings.Join(s.colNames, ", "))
	}
	switch {
	case s.sel != nil:
		return fmt.Sprintf("INSERT INTO %s%s %s;", s.tableName, cn, s.sel)
	default:
		a := make([]string, len(s.lists))
		for i, v := range s.lists {
			b := make([]string, len(v))
			for i, v := range v {
				b[i] = v.String()
			}
			a[i] = fmt.Sprintf("(%s)", strings.Join(b, ", "))
		}
		return fmt.Sprintf("INSERT INTO %s%s VALUES %s;", s.tableName, cn, strings.Join(a, ", "))
	}
}

func (s *insertIntoStmt) execSelect(t *table, cols []*col, ctx *execCtx, constraints []*constraint, defaults []expression) (_ Recordset, err error) {
	r := s.sel.exec0()
	ok := false
	h := t.head
	data0 := make([]interface{}, len(t.cols0)+2)
	cc := ctx.db.cc
	m := map[interface{}]interface{}{}
	if err = r.do(ctx, false, func(id interface{}, data []interface{}) (more bool, err error) {
		if ok {
			for i, d := range data {
				data0[cols[i].index+2] = d
			}
			if err = typeCheck(data0[2:], cols); err != nil {
				return
			}

			if len(constraints) != 0 { // => len(defaults) != 0 as well
				if err = checkConstraintsAndDefaults(ctx, data0[2:], t.cols, m, constraints, defaults); err != nil {
					return false, err
				}
			}

			id, err := t.store.ID()
			if err != nil {
				return false, err
			}

			data0[0] = h
			data0[1] = id

			// Any overflow chunks are written here.
			if h, err = t.store.Create(data0...); err != nil {
				return false, err
			}

			for i, v := range t.indices {
				if v == nil {
					continue
				}

				// Any overflow chunks are shared with the BTree key
				if err = v.x.Create(data0[i+1], h); err != nil {
					return false, err
				}
			}

			cc.RowsAffected++
			ctx.db.root.lastInsertID = id
			return true, nil
		}

		ok = true
		flds := data[0].([]*fld)
		if g, e := len(flds), len(cols); g != e {
			return false, fmt.Errorf("INSERT INTO SELECT: mismatched column counts, have %d, need %d", g, e)
		}

		return true, nil
	}); err != nil {
		return
	}

	if err = t.store.Update(t.hhead, h); err != nil {
		return
	}

	t.head = h
	return
}

var (
	selectColumn2 = MustCompile(`
		select Name, NotNull, ConstraintExpr, DefaultExpr
		from __Column2
		where TableName == $1
	`)
)

func constraintsAndDefaults(ctx *execCtx, table string) (constraints []*constraint, defaults []expression, _ error) {
	if isSystemName[table] {
		return nil, nil, nil
	}

	_, ok := ctx.db.root.tables["__Column2"]
	if !ok {
		return nil, nil, nil
	}

	t, ok := ctx.db.root.tables[table]
	if !ok {
		return nil, nil, fmt.Errorf("table %q does not exist", table)
	}

	cols := t.cols
	constraints = make([]*constraint, len(cols))
	defaults = make([]expression, len(cols))
	arg := []interface{}{table}
	rs, err := selectColumn2.l[0].exec(&execCtx{db: ctx.db})
	if err != nil {
		return nil, nil, err
	}

	var rows [][]interface{}
	ok = false
	if err := rs.(recordset).do(
		&execCtx{db: ctx.db, arg: arg},
		false,
		func(id interface{}, data []interface{}) (more bool, err error) {
			if ok {
				rows = append(rows, data)
				return true, nil
			}

			ok = true
			return true, nil
		},
	); err != nil {
		return nil, nil, err
	}

	for _, row := range rows {
		nm := row[0].(string)
		nonNull := row[1].(bool)
		cexpr := row[2].(string)
		dexpr := row[3].(string)
		for i, c := range cols {
			if c.name == nm {
				var co *constraint
				if nonNull || cexpr != "" {
					co = &constraint{}
					if cexpr != "" {
						if co.expr, err = str2expr(cexpr); err != nil {
							return nil, nil, fmt.Errorf("constraint %q: %v", cexpr, err)
						}
					}
				}
				constraints[i] = co
				if dexpr != "" {
					if defaults[i], err = str2expr(dexpr); err != nil {
						return nil, nil, fmt.Errorf("constraint %q: %v", dexpr, err)
					}
				}
			}
		}
	}
	return constraints, defaults, nil
}

func checkConstraintsAndDefaults(
	ctx *execCtx,
	row []interface{},
	cols []*col,
	m map[interface{}]interface{},
	constraints []*constraint,
	defaults []expression) error {

	// 1.
	for _, c := range cols {
		m[c.name] = row[c.index]
	}

	// 2.
	for i, c := range cols {
		val := row[c.index]
		expr := defaults[i]
		if val != nil || expr == nil {
			continue
		}

		dval, err := expr.eval(ctx, m, ctx.arg)
		if err != nil {
			return err
		}

		row[c.index] = dval
		if err = typeCheck(row, []*col{c}); err != nil {
			return err
		}
	}

	// 3.
	for _, c := range cols {
		m[c.name] = row[c.index]
	}

	// 4.
	for i, c := range cols {
		constraint := constraints[i]
		if constraint == nil {
			continue
		}

		val := row[c.index]
		expr := constraint.expr
		if expr == nil { // Constraint: NOT NULL
			if val == nil {
				return fmt.Errorf("column %s: constraint violation: NOT NULL", c.name)
			}

			continue
		}

		// Constraint is an expression
		cval, err := expr.eval(ctx, m, ctx.arg)
		if err != nil {
			return err
		}

		if cval == nil {
			return fmt.Errorf("column %s: constraint violation: %s", c.name, expr)
		}

		bval, ok := cval.(bool)
		if !ok {
			return fmt.Errorf("column %s: non bool constraint expression: %s", c.name, expr)
		}

		if !bval {
			return fmt.Errorf("column %s: constraint violation: %s", c.name, expr)
		}
	}

	return nil
}

func (s *insertIntoStmt) exec(ctx *execCtx) (_ Recordset, err error) {
	t, ok := ctx.db.root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("INSERT INTO %s: table does not exist", s.tableName)
	}

	var cols []*col
	switch len(s.colNames) {
	case 0:
		cols = t.cols
	default:
		for _, colName := range s.colNames {
			if col := findCol(t.cols, colName); col != nil {
				cols = append(cols, col)
				continue
			}

			return nil, fmt.Errorf("INSERT INTO %s: unknown column %s", s.tableName, colName)
		}
	}

	constraints, defaults, err := constraintsAndDefaults(ctx, s.tableName)
	if err != nil {
		return nil, err
	}

	if s.sel != nil {
		return s.execSelect(t, cols, ctx, constraints, defaults)
	}

	for _, list := range s.lists {
		if g, e := len(list), len(cols); g != e {
			return nil, fmt.Errorf("INSERT INTO %s: expected %d value(s), have %d", s.tableName, e, g)
		}
	}

	arg := ctx.arg
	root := ctx.db.root
	cc := ctx.db.cc
	r := make([]interface{}, len(t.cols0))
	m := map[interface{}]interface{}{}
	for _, list := range s.lists {
		for i, expr := range list {
			val, err := expr.eval(ctx, m, arg)
			if err != nil {
				return nil, err
			}

			r[cols[i].index] = val
		}
		if err = typeCheck(r, cols); err != nil {
			return
		}

		if len(constraints) != 0 { // => len(defaults) != 0 as well
			if err = checkConstraintsAndDefaults(ctx, r, t.cols, m, constraints, defaults); err != nil {
				return nil, err
			}
		}

		id, err := t.addRecord(r)
		if err != nil {
			return nil, err
		}

		cc.RowsAffected++
		root.lastInsertID = id
	}
	return
}

func (s *insertIntoStmt) isUpdating() bool { return true }

type beginTransactionStmt struct{}

func (beginTransactionStmt) String() string { return "BEGIN TRANSACTION;" }
func (beginTransactionStmt) exec(*execCtx) (Recordset, error) {
	log.Panic("internal error 059")
	panic("unreachable")
}
func (beginTransactionStmt) isUpdating() bool {
	log.Panic("internal error 060")
	panic("unreachable")
}

type commitStmt struct{}

func (commitStmt) String() string { return "COMMIT;" }
func (commitStmt) exec(*execCtx) (Recordset, error) {
	log.Panic("internal error 061")
	panic("unreachable")
}
func (commitStmt) isUpdating() bool {
	log.Panic("internal error 062")
	panic("unreachable")
}

type rollbackStmt struct{}

func (rollbackStmt) String() string { return "ROLLBACK;" }
func (rollbackStmt) exec(*execCtx) (Recordset, error) {
	log.Panic("internal error 063")
	panic("unreachable")
}
func (rollbackStmt) isUpdating() bool {
	log.Panic("internal error 064")
	panic("unreachable")
}

type createIndexStmt struct {
	colName     string // alt. "id()" for index on id()
	ifNotExists bool
	indexName   string
	tableName   string
	unique      bool
}

func (s *createIndexStmt) String() string {
	u := ""
	if s.unique {
		u = "UNIQUE "
	}
	e := ""
	if s.ifNotExists {
		e = "IF NOT EXISTS "
	}
	return fmt.Sprintf("CREATE %sINDEX %s%s ON %s (%s);", u, e, s.indexName, s.tableName, s.colName)
}

func (s *createIndexStmt) exec(ctx *execCtx) (Recordset, error) {
	root := ctx.db.root
	if t, i := root.findIndexByName(s.indexName); i != nil {
		if s.ifNotExists {
			return nil, nil
		}

		return nil, fmt.Errorf("CREATE INDEX: table %s already has an index named %s", t.name, i.name)
	}

	if root.tables[s.indexName] != nil {
		return nil, fmt.Errorf("CREATE INDEX: index name collision with existing table: %s", s.indexName)
	}

	t, ok := root.tables[s.tableName]
	if !ok {
		return nil, fmt.Errorf("CREATE INDEX: table does not exist %s", s.tableName)
	}

	if findCol(t.cols, s.indexName) != nil {
		return nil, fmt.Errorf("CREATE INDEX: index name collision with existing column: %s", s.indexName)
	}

	if s.colName == "id()" {
		if err := t.addIndex(s.unique, s.indexName, -1); err != nil {
			return nil, fmt.Errorf("CREATE INDEX: %v", err)
		}

		return nil, t.updated()
	}

	c := findCol(t.cols, s.colName)
	if c == nil {
		return nil, fmt.Errorf("CREATE INDEX: column does not exist: %s", s.colName)
	}

	if err := t.addIndex(s.unique, s.indexName, c.index); err != nil {
		return nil, fmt.Errorf("CREATE INDEX: %v", err)
	}

	return nil, t.updated()
}

func (s *createIndexStmt) isUpdating() bool { return true }

type createTableStmt struct {
	ifNotExists bool
	tableName   string
	cols        []*col
}

func (s *createTableStmt) String() string {
	a := make([]string, len(s.cols))
	for i, v := range s.cols {
		var c, d string
		if x := v.constraint; x != nil {
			switch e := x.expr; {
			case e != nil:
				c = " " + e.String()
			default:
				c = " NOT NULL"
			}
		}
		if x := v.dflt; x != nil {
			d = " DEFAULT " + x.String()
		}
		a[i] = fmt.Sprintf("%s %s%s%s", v.name, typeStr(v.typ), c, d)
	}
	e := ""
	if s.ifNotExists {
		e = "IF NOT EXISTS "
	}
	return fmt.Sprintf("CREATE TABLE %s%s (%s);", e, s.tableName, strings.Join(a, ", "))
}

var (
	createColumn2 = mustCompile(`
		create table if not exists __Column2 (
			TableName string,
			Name string,
			NotNull bool,
			ConstraintExpr string,
			DefaultExpr string,
		);
		create index if not exists __Column2TableName on __Column2(TableName);
	`)
	insertColumn2 = mustCompile(`insert into __Column2 values($1, $2, $3, $4, $5)`)
)

func (s *createTableStmt) exec(ctx *execCtx) (_ Recordset, err error) {
	root := ctx.db.root
	if _, ok := root.tables[s.tableName]; ok {
		if s.ifNotExists {
			return nil, nil
		}

		return nil, fmt.Errorf("CREATE TABLE: table exists %s", s.tableName)
	}

	if t, x := root.findIndexByName(s.tableName); x != nil {
		return nil, fmt.Errorf("CREATE TABLE: table %s has index %s", t.name, s.tableName)
	}

	m := map[string]bool{}
	mustCreateColumn2 := true
	for i, c := range s.cols {
		nm := c.name
		if m[nm] {
			return nil, fmt.Errorf("CREATE TABLE: duplicate column %s", nm)
		}

		m[nm] = true
		c.index = i
		if c.constraint != nil || c.dflt != nil {
			if mustCreateColumn2 {
				for _, s := range createColumn2.l {
					_, err := s.exec(&execCtx{db: ctx.db})
					if err != nil {
						return nil, err
					}
				}
			}

			mustCreateColumn2 = false
			notNull := c.constraint != nil && c.constraint.expr == nil
			var co, d string
			if c.constraint != nil && c.constraint.expr != nil {
				co = c.constraint.expr.String()
			}
			if e := c.dflt; e != nil {
				d = e.String()
			}
			if _, err := insertColumn2.l[0].exec(&execCtx{db: ctx.db, arg: []interface{}{s.tableName, c.name, notNull, co, d}}); err != nil {
				return nil, err
			}
		}
	}
	_, err = root.createTable(s.tableName, s.cols)
	return
}

func (s *createTableStmt) isUpdating() bool { return true }


text:
module Dbox
  class Syncer
    MIN_BYTES_TO_STREAM_DOWNLOAD = 1024 * 100 # 100kB

    include Loggable

    def self.create(remote_path, local_path)
      api.create_dir(remote_path)
      clone(remote_path, local_path)
    end

    def self.clone(remote_path, local_path)
      api.metadata(remote_path) # ensure remote exists
      database = Database.create(remote_path, local_path)
      Pull.new(database, api).execute
    end

    def self.pull(local_path)
      database = Database.load(local_path)
      Pull.new(database, api).execute
    end

    def self.push(local_path)
      database = Database.load(local_path)
      Push.new(database, api).execute
    end

    def self.move(new_remote_path, local_path)
      database = Database.load(local_path)
      api.move(database.metadata[:remote_path], new_remote_path)
      database.update_metadata(:remote_path => new_remote_path)
    end

    def self.api
      @@_api ||= API.connect
    end

    class Operation
      include Loggable
      include Utils

      attr_reader :database

      def initialize(database, api)
        @database = database
        @api = api
      end

      def api
        @api
      end

      def metadata
        @_metadata ||= database.metadata
      end

      def local_path
        metadata[:local_path]
      end

      def remote_path
        metadata[:remote_path]
      end

      def remove_dotfiles(contents)
        contents.reject {|c| File.basename(c[:path]).start_with?(".") }
      end

      def current_dir_entries_as_hash(dir)
        if dir[:id]
          out = InsensitiveHash.new
          database.contents(dir[:id]).each {|e| out[e[:path]] = e }
          out
        else
          {}
        end
      end

      def lookup_id_by_path(path)
        @_ids ||= {}
        @_ids[path] ||= database.find_by_path(path)[:id]
      end

      def saving_timestamp(path)
        mtime = File.mtime(path)
        res = yield
        File.utime(Time.now, mtime, path)
        res
      end

      def saving_parent_timestamp(entry, &proc)
        parent = File.dirname(entry[:local_path])
        saving_timestamp(parent, &proc)
      end

      def update_file_timestamp(entry)
        begin
          File.utime(Time.now, entry[:modified], entry[:local_path])
        rescue Errno::ENOENT
          nil
        end
      end

      def gather_remote_info(entry)
        res = api.metadata(entry[:remote_path], entry[:remote_hash])
        case res
        when Hash
          out = process_basic_remote_props(res)
          out[:id] = entry[:id] if entry[:id]
          if res[:contents]
            out[:contents] = remove_dotfiles(res[:contents]).map do |c|
              o = process_basic_remote_props(c)
              o[:parent_id] = entry[:id] if entry[:id]
              o[:parent_path] = entry[:path]
              o
            end
          end
          out
        when :not_modified
          :not_modified
        else
          raise(RuntimeError, "Invalid result from server: #{res.inspect}")
        end
      end

      def process_basic_remote_props(res)
        out = {}
        out[:path]        = remote_to_relative_path(res[:path])
        out[:local_path]  = relative_to_local_path(out[:path])
        out[:remote_path] = relative_to_remote_path(out[:path])
        out[:modified]    = parse_time(res[:modified])
        out[:is_dir]      = res[:is_dir]
        out[:remote_hash] = res[:hash] if res[:hash]
        out[:revision]    = res[:rev] if res[:rev]
        out[:size]        = res[:bytes] if res[:bytes]
        out
      end

      def generate_tmpfilename(path)
        out = File.join(local_path, ".#{path.gsub(/\W/, '-')}.part")
        if File.exists?(out)
          generate_tmpfilename("path#{rand(1000)}")
        else
          out
        end
      end

      def remove_tmpfiles
        Dir["#{local_path}/.*.part"].each {|f| FileUtils.rm(f) }
      end

      def sort_changelist(changelist)
        changelist.keys.each do |k|
          case k
          when :conflicts
            changelist[k].sort! {|c1, c2| c1[:original] <=> c2[:original] }
          when :failed
            changelist[k].sort! {|c1, c2| c1[:path] <=> c2[:path] }
          else
            changelist[k].sort!
          end
        end
        changelist
      end
    end

    class Pull < Operation
      def initialize(database, api)
        super(database, api)
      end

      def practice
        dir = database.root_dir
        changes = calculate_changes(dir)
        log.debug "Changes that would be executed:\n" + changes.map {|c| c.inspect }.join("\n")
      end

      def execute
        remove_tmpfiles
        dir = database.root_dir
        changes = calculate_changes(dir)
        log.debug "Executing changes:\n" + changes.map {|c| c.inspect }.join("\n")
        parent_ids_of_failed_entries = []
        changelist = { :created => [], :deleted => [], :updated => [], :failed => [] }

        changes.each do |op, c|
          case op
          when :create
            c[:parent_id] ||= lookup_id_by_path(c[:parent_path])
            if c[:is_dir]
              # create the local directory
              create_dir(c)
              database.add_entry(c[:path], true, c[:parent_id], c[:modified], c[:revision], c[:remote_hash], nil)
              changelist[:created] << c[:path]
            else
              # download the new file
              begin
                res = create_file(c)
                local_hash = calculate_hash(c[:local_path])
                database.add_entry(c[:path], false, c[:parent_id], c[:modified], c[:revision], c[:remote_hash], local_hash)
                changelist[:created] << c[:path]
                if res.kind_of?(Array) && res[0] == :conflict
                  changelist[:conflicts] ||= []
                  changelist[:conflicts] << res[1]
                end
              rescue => e
                log.error "Error while downloading #{c[:path]}: #{e.inspect}\n#{e.backtrace.join("\n")}"
                parent_ids_of_failed_entries << c[:parent_id]
                changelist[:failed] << { :operation => :create, :path => c[:path], :error => e }
              end
            end
          when :update
            if c[:is_dir]
              # update the local directory
              update_dir(c)
              database.update_entry_by_path(c[:path], :modified => c[:modified], :revision => c[:revision], :remote_hash => c[:remote_hash])
              changelist[:updated] << c[:path]
            else
              # download updates to the file
              begin
                res = update_file(c)
                local_hash = calculate_hash(c[:local_path])
                database.update_entry_by_path(c[:path], :modified => c[:modified], :revision => c[:revision], :remote_hash => c[:remote_hash], :local_hash => local_hash)
                changelist[:updated] << c[:path]
                if res.kind_of?(Array) && res[0] == :conflict
                  changelist[:conflicts] ||= []
                  changelist[:conflicts] << res[1]
                end
              rescue => e
                log.error "Error while downloading #{c[:path]}: #{e.inspect}\n#{e.backtrace.join("\n")}"
                parent_ids_of_failed_entries << c[:parent_id]
                changelist[:failed] << { :operation => :create, :path => c[:path], :error => e }
              end
            end
          when :delete
            # delete the local directory/file
            c[:is_dir] ? delete_dir(c) : delete_file(c)
            database.delete_entry_by_path(c[:path])
            changelist[:deleted] << c[:path]
          when :failed
            parent_ids_of_failed_entries << c[:parent_id]
            changelist[:failed] << { :operation => c[:operation], :path => c[:path], :error => c[:error] }
          else
            raise(RuntimeError, "Unknown operation type: #{op}")
          end
        end

        # clear hashes on any dirs with children that failed so that
        # they are processed again on next pull
        parent_ids_of_failed_entries.uniq.each do |id|
          database.update_entry_by_id(id, :remote_hash => nil)
        end

        # sort & return output
        sort_changelist(changelist)
      end

      def calculate_changes(dir, operation = :update)
        raise(ArgumentError, "Not a directory: #{dir.inspect}") unless dir[:is_dir]

        out = []
        recur_dirs = []

        # grab the metadata for the current dir (either off the filesystem or from Dropbox)
        res = gather_remote_info(dir)
        if res == :not_modified
          # directory itself was not modified, but we still need to
          # recur on subdirectories
          recur_dirs += database.subdirs(dir[:id]).map {|d| [:update, d] }
        else
          raise(ArgumentError, "Not a directory: #{res.inspect}") unless res[:is_dir]

          # dir may have changed -- calculate changes on contents
          contents = res.delete(:contents)
          if operation == :create || modified?(dir, res)
            res[:parent_id] = dir[:parent_id] if dir[:parent_id]
            res[:parent_path] = dir[:parent_path] if dir[:parent_path]
            out << [operation, res]
          end
          found_paths = []
          existing_entries = current_dir_entries_as_hash(dir)

          # process each entry that came back from dropbox/filesystem
          contents.each do |c|
            found_paths << c[:path]
            if entry = existing_entries[c[:path]]
              c[:id] = entry[:id]
              c[:modified] = parse_time(c[:modified])
              if c[:is_dir]
                # queue dir for later
                c[:remote_hash] = entry[:remote_hash]
                recur_dirs << [:update, c]
              else
                # update iff modified
                out << [:update, c] if modified?(entry, c)
              end
            else
              # create
              c[:modified] = parse_time(c[:modified])
              if c[:is_dir]
                # queue dir for later
                recur_dirs << [:create, c]
              else
                out << [:create, c]
              end
            end
          end

          # add any deletions
          out += case_insensitive_difference(existing_entries.keys, found_paths).map do |p|
            [:delete, existing_entries[p]]
          end
        end

        # recursively process new & existing subdirectories in parallel
        recur_dirs.each do |operation, dir|
          begin
            out += calculate_changes(dir, operation)
          rescue => e
            log.error "Error while caclulating changes for #{operation} on #{dir[:path]}: #{e.inspect}\n#{e.backtrace.join("\n")}"
            out += [[:failed, dir.merge({ :operation => operation, :error => e })]]
          end
        end

        out
      end

      def modified?(entry, res)
        out = (entry[:revision] != res[:revision]) ||
              !times_equal?(entry[:modified], res[:modified])
        out ||= (entry[:remote_hash] != res[:remote_hash]) if res.has_key?(:remote_hash)
        log.debug "#{entry[:path]} modified? r#{entry[:revision]} vs. r#{res[:revision]}, h#{entry[:remote_hash]} vs. h#{res[:remote_hash]}, t#{time_to_s(entry[:modified])} vs. t#{time_to_s(res[:modified])} => #{out}"
        out
      end

      def create_dir(dir)
        local_path = dir[:local_path]
        log.info "Creating #{local_path}"
        saving_parent_timestamp(dir) do
          FileUtils.mkdir_p(local_path)
          update_file_timestamp(dir)
        end
      end

      def update_dir(dir)
        update_file_timestamp(dir)
      end

      def delete_dir(dir)
        local_path = dir[:local_path]
        log.info "Deleting #{local_path}"
        saving_parent_timestamp(dir) do
          FileUtils.rm_r(local_path)
        end
      end

      def create_file(file)
        saving_parent_timestamp(file) do
          download_file(file)
        end
      end

      def update_file(file)
        download_file(file)
      end

      def delete_file(file)
        local_path = file[:local_path]
        log.info "Deleting file: #{local_path}"
        saving_parent_timestamp(file) do
          FileUtils.rm_rf(local_path)
        end
      end

      def download_file(file)
        local_path = file[:local_path]
        remote_path = file[:remote_path]

        # check to ensure we aren't overwriting an untracked file or a
        # file with local modifications
        clobbering = false
        if entry = database.find_by_path(file[:path])
          clobbering = calculate_hash(local_path) != entry[:local_hash]
        else
          clobbering = File.exists?(local_path)
        end

        # stream files larger than the minimum
        stream = file[:size] && file[:size] > MIN_BYTES_TO_STREAM_DOWNLOAD

        # download to temp file
        tmp = generate_tmpfilename(file[:path])
        File.open(tmp, "wb") do |f|
          api.get_file(remote_path, f, stream)
        end

        # rename old file if clobbering
        if clobbering && File.exists?(local_path)
          backup_path = find_nonconflicting_path(local_path)
          FileUtils.mv(local_path, backup_path)
          backup_relpath = local_to_relative_path(backup_path)
          log.warn "#{file[:path]} had a conflict and the existing copy was renamed to #{backup_relpath} locally"
        end

        # atomic move over to the real file, and update the timestamp
        FileUtils.mv(tmp, local_path)
        update_file_timestamp(file)

        if backup_relpath
          [:conflict, { :original => file[:path], :renamed => backup_relpath }]
        else
          true
        end
      end

    end

    class Push < Operation
      def initialize(database, api)
        super(database, api)
      end

      def practice
        dir = database.root_dir
        changes = calculate_changes(dir)
        log.debug "Changes that would be executed:\n" + changes.map {|c| c.inspect }.join("\n")
      end

      def execute
        dir = database.root_dir
        changes = calculate_changes(dir)
        log.debug "Executing changes:\n" + changes.map {|c| c.inspect }.join("\n")
        changelist = { :created => [], :deleted => [], :updated => [], :failed => [] }

        changes.each do |op, c|
          case op
          when :create
            c[:parent_id] ||= lookup_id_by_path(c[:parent_path])

            if c[:is_dir]
              # create the remote directiory
              create_dir(c)
              database.add_entry(c[:path], true, c[:parent_id], nil, nil, nil, nil)
              force_metadata_update_from_server(c)
              changelist[:created] << c[:path]
            else
              # upload a new file
              begin
                local_hash = calculate_hash(c[:local_path])
                res = upload_file(c)
                database.add_entry(c[:path], false, c[:parent_id], nil, nil, nil, local_hash)
                if case_insensitive_equal(c[:path], res[:path])
                  force_metadata_update_from_server(c)
                  changelist[:created] << c[:path]
                else
                  log.warn "#{c[:path]} had a conflict and was renamed to #{res[:path]} on the server"
                  changelist[:conflicts] ||= []
                  changelist[:conflicts] << { :original => c[:path], :renamed => res[:path] }
                end
              rescue => e
                log.error "Error while uploading #{c[:path]}: #{e.inspect}\n#{e.backtrace.join("\n")}"
                changelist[:failed] << { :operation => :create, :path => c[:path], :error => e }
              end
            end
          when :update
            existing = database.find_by_path(c[:path])
            unless existing[:is_dir] == c[:is_dir]
              raise(RuntimeError, "Mode on #{c[:path]} changed between file and dir -- not supported yet")
            end

            # only update files -- nothing to do to update a dir
            if !c[:is_dir]
              # upload changes to a file
              begin
                local_hash = calculate_hash(c[:local_path])
                res = upload_file(c)
                database.update_entry_by_path(c[:path], :local_hash => local_hash)
                if case_insensitive_equal(c[:path], res[:path])
                  force_metadata_update_from_server(c)
                  changelist[:updated] << c[:path]
                else
                  log.warn "#{c[:path]} had a conflict and was renamed to #{res[:path]} on the server"
                  changelist[:conflicts] ||= []
                  changelist[:conflicts] << { :original => c[:path], :renamed => res[:path] }
                end
              rescue => e
                log.error "Error while uploading #{c[:path]}: #{e.inspect}\n#{e.backtrace.join("\n")}"
                changelist[:failed] << { :operation => :update, :path => c[:path], :error => e }
              end
            end
          when :delete
            # delete a remote file/directory
            begin
              begin
                if c[:is_dir]
                  delete_dir(c)
                else
                  delete_file(c)
                end
              rescue Dbox::RemoteMissing
                # safe to delete even if remote is already gone
              end
              database.delete_entry_by_path(c[:path])
              changelist[:deleted] << c[:path]
            rescue => e
              log.error "Error while deleting #{c[:path]}: #{e.inspect}\n#{e.backtrace.join("\n")}"
              changelist[:failed] << { :operation => :delete, :path => c[:path], :error => e }
            end
          when :failed
            changelist[:failed] << { :operation => c[:operation], :path => c[:path], :error => c[:error] }
          else
            raise(RuntimeError, "Unknown operation type: #{op}")
          end
        end

        # sort & return output
        sort_changelist(changelist)
      end

      def calculate_changes(dir)
        raise(ArgumentError, "Not a directory: #{dir.inspect}") unless dir[:is_dir]

        out = []
        recur_dirs = []

        existing_entries = current_dir_entries_as_hash(dir)
        child_paths = list_contents(dir).sort

        child_paths.each do |p|
          local_path = relative_to_local_path(p)
          remote_path = relative_to_remote_path(p)
          c = {
            :path => p,
            :local_path => local_path,
            :remote_path => remote_path,
            :modified => mtime(local_path),
            :is_dir => is_dir(local_path),
            :parent_path => dir[:path],
            :local_hash => calculate_hash(local_path)
          }
          if entry = existing_entries[p]
            c[:id] = entry[:id]
            recur_dirs << c if c[:is_dir] # queue dir for later
            out << [:update, c] if modified?(entry, c) # update iff modified
          else
            # create
            out << [:create, c]
            recur_dirs << c if c[:is_dir]
          end
        end

        # add any deletions
        out += case_insensitive_difference(existing_entries.keys, child_paths).map do |p|
          [:delete, existing_entries[p]]
        end

        # recursively process new & existing subdirectories
        recur_dirs.each do |dir|
          out += calculate_changes(dir)
        end

        out
      end

      def mtime(path)
        File.mtime(path)
      end

      def is_dir(path)
        File.directory?(path)
      end

      def modified?(entry, res)
        out = true
        if entry[:is_dir]
          out = !times_equal?(entry[:modified], res[:modified])
          log.debug "#{entry[:path]} modified? t#{time_to_s(entry[:modified])} vs. t#{time_to_s(res[:modified])} => #{out}"
        else
          eh = entry[:local_hash]
          rh = res[:local_hash]
          out = !(eh && rh && eh == rh)
          log.debug "#{entry[:path]} modified? #{eh} vs. #{rh} => #{out}"
        end
        out
      end

      def list_contents(dir)
        local_path = dir[:local_path]
        paths = Dir.entries(local_path).reject {|s| s == "." || s == ".." || s.start_with?(".") }
        paths.map {|p| local_to_relative_path(File.join(local_path, p)) }
      end

      def create_dir(dir)
        remote_path = dir[:remote_path]
        log.info "Creating #{remote_path}"
        api.create_dir(remote_path)
      end

      def delete_dir(dir)
        remote_path = dir[:remote_path]
        api.delete_dir(remote_path)
      end

      def delete_file(file)
        remote_path = file[:remote_path]
        api.delete_file(remote_path)
      end

      def upload_file(file)
        local_path = file[:local_path]
        remote_path = file[:remote_path]
        db_entry = database.find_by_path(file[:path])
        last_revision = db_entry ? db_entry[:revision] : nil
        res = api.put_file(remote_path, local_path, last_revision)
        process_basic_remote_props(res)
      end

      def force_metadata_update_from_server(entry)
        res = gather_remote_info(entry)
        unless res == :not_modified
          database.update_entry_by_path(entry[:path], :modified => res[:modified], :revision => res[:revision], :remote_hash => res[:remote_hash])
        end
        update_file_timestamp(database.find_by_path(entry[:path]))
      end
    end
  end
end


text:
package in.koyad.piston.common.enums;

public enum PageType {
	SIMPLE, PORTAL
}


text:
/**
 * Created by 李 on 2017/3/28.
 */
import {AfterViewInit, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {TaskService} from "../../service/task.service";

@Component({
  moduleId: module.id,
  selector: 'one-task',
  templateUrl: 'one-task.component.html',
  providers: [TaskService]
})
export class OneTaskComponent implements OnInit, AfterViewInit {
  @Input() task: any
  @Input() type: string
  @Output() _notify_task = new EventEmitter<any>()
  @Output() updateListByType = new EventEmitter<string>()

  delete_flag: boolean

  constructor(private taskService: TaskService) {
  }

  ngOnInit() {
    this.checkTask()
  }

  ngAfterViewInit() {
    if (this.task.status === 1) {
      let dom = <any>document.getElementById("y$" + this.task.task_id)
      dom.checked = true
    }
  }

  //阻止冒泡
  stopBubble = (e) => {
    window.event ? e.cancelBubble = true : e.stopPropagation();
  }

  notifyTask = () => {
    this._notify_task.emit(this.task)
  }

  //判断该任务是否完成
  checkTask = () => {
    if (this.task.status === 1) {
      this.delete_flag = true

    }
  }
  doneOneTask = (e) => {
    this.stopBubble(e)

    let obj = {
      task_id: this.task.task_id,
      status: 1,
      user_id: this.task.t_user_task.user_id
    }
    this.taskService.updateTaskStatus(obj)
      .subscribe(data => {
        if (data.success) {
          this.delete_flag = true
          setTimeout(() => {
            this.updateListByType.emit(this.type)
          }, 200)
        }
      })

  }
}


text:
namespace web_app {

MockFileUtilsWrapper::MockFileUtilsWrapper() = default;
MockFileUtilsWrapper::~MockFileUtilsWrapper() = default;

}  // namespace web_app


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- From: file:/Users/encima/Development/android/S4C/S4CRadioReaderProject/S4CRadioReader/src/main/res/values-sw720dp-land/dimens.xml -->
    <dimen name="activity_horizontal_margin">128dp</dimen>

</resources>


text:
/**
 * Enum defining the different states of a game board cell.
 */
const Cell = Object.freeze({
  BLANK: 0,
  RED: 1,
  WHITE: 2,
});

module.exports = {
  Cell,
};


text:
<!DOCTYPE html>

        <meta charset="utf-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name=viewport content="width=device-width, initial-scale=1">

        <meta name="description" content="css library, is website you can find  web UI elements Examples and complete UI kits coded with HTML5, CSS3">

        <meta name="url" content="http://www.csslibrary.cf/">

        <meta property="og:title" content="CSS Library">
        <meta property="og:type" content="UI Kit Website">
        <meta property="og:url" content="http://www.csslibrary.cf/">
        <meta property="og:description" content="css library, is website you can find  web UI elements Examples and complete UI kits coded with HTML5, CSS3">
        <meta property="og:image" content="http://i.imgur.com/chD7fo3.png">
        <meta property="og:site_name" content="csslibrary">

        <meta name="twitter:title" content="CSS Library">
        <meta name="twitter:url" content="http://www.csslibrary.cf/">
        <meta name="twitter:description" content="css library, is website you can find  web UI elements Examples and complete UI kits coded with HTML5, CSS3">
        <meta name="twitter:image" content="http://i.imgur.com/chD7fo3.png">
        <meta name="twitter:site" content="csslibrary">

        <title>csslibrary | forms</title>

        <link rel="icon" type="image/png" href="../images/favicon.ico"/>
        <link rel="stylesheet" href="../css/normalize.css">
        <link rel="stylesheet" href="../css/ui.css">

                            CSS Library

Home

About

CSS Library, UI kits For Web Developers.

We offer user interface kits,to make your work easiest.

UI styles

                            <input type="checkbox" id="checkbox1">
                            Option One
                            <input type="checkbox" id="checkbox2">
                            Option Two
                            <input type="checkbox" id="checkbox3">
                            Option Three
                            <input type="checkbox" id="checkbox4">
                            Option Four

                        Code

                          <form>
                            <input type="radio" id="radio1" name="radio-group">
                            Option One
                            <input type="radio" id="radio2" name="radio-group">
                            Option Two
                            <input type="radio" id="radio3" name="radio-group">
                            Option Three
                            <input type="radio" id="radio4" name="radio-group">
                            Option Four
                          </form>

                        Code

                        <input class="search" type="text" placeholder="Search" />
                        Code

                        <form class="search-form">
                                <input type="text"
                                       class="search-field" placeholder="Search ..." />
                                <input type="submit"
                                       class="btn" value="Search"/>
                        </form>
                        Code

                        <form  class="search-form3">
                            <input type="text"
                                   class="search3" placeholder="Search..."/>
                            <input type="submit" class="btn3"  value="Search"/>
                        </form>
                        Code

                        <input type="range" min="0" max="50" value="5" class="range" />
                        Code

                        <input type="range" min="0" max="50" value="5" class="range2" />
                        Code

© 2016-2017 CSS library


text:
package com.spun.util.tests.multitest;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class MultiDemo extends TestSuite implements UseCaseTester<String>
{
  /** This test is suppose to Fail 3 times when run.
   *  The idea is to continue to run despite failures.
   *  line 16 is there to allow the full suite to pass.
   */
  public static Test suite() throws Exception
  {
    //return UseCaseTesting.all(new MultiDemo(), new String[]{"a", "2", "3", "b", "6", "9a"});
    return UseCaseTesting.all(new MultiDemo(), new String[]{ "2", "3"});
  }
  public void testUseCase(String string)
  {
    TestCase.assertNotNull(Integer.parseInt(string));
  }
}


text:
package org.apache.aries.util.filesystem.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.apache.aries.util.IORuntimeException;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.filesystem.IFile;

/**
 * An implementation of IFile that represents a file entry in a zip.
 */
public class ZipFileImpl implements IFile
{
  /** The name of the file */
  private String name;
  /** The size of the file */
  private final long size;
  /** The last time the file was updated */
  private final long lastModified;
  /** The zip file this is contained in */
  protected final File zip;
  /** The entry in the zip this IFile represents */
  protected final ZipEntry entry;
  /** The parent directory */
  private final IDirectory parent;
  /** The URL of the zip file we are looking inside of */
  private final String url;
  /** The path of the zip archive to the VFS root */
  private final String zipPathToRoot;
  /** The closeable directory that caches the open ZipFile */
  protected final ZipCloseableDirectory cache;

  /**
   * This constructor is used to create a file entry within the zip.
   *
   * @param zip1    the zip file the entry is in.
   * @param entry1  the entry this IFile represents.
   * @param parent1 the parent directory.
   */
  public ZipFileImpl(File zip1, ZipEntry entry1, ZipDirectory parent1, ZipCloseableDirectory cache)
  {
    this.zip = zip1;
    this.entry = entry1;

    this.zipPathToRoot = parent1.getZipPathToRoot();

    name = zipPathToRoot + entry1.getName();

    if (entry1.isDirectory()) name = name.substring(0, name.length() - 1);

    lastModified = entry1.getTime();
    size = entry1.getSize();

    url = ((ZipFileImpl)parent1).url;

    this.parent = parent1;
    this.cache = cache;
  }

  /**
   * This is called to construct the root directory of the zip.
   *
   * @param zip1 the zip file this represents.
   * @param fs   the file on the fs.
   * @param rootName the name of this zipfile relative to the IFile filesystem root
   * @throws MalformedURLException
   */
  protected ZipFileImpl(File zip1, IDirectory parent) throws MalformedURLException
  {
    this.zip = zip1;
    this.entry = null;

    if (parent == null) {
        name = "";
        zipPathToRoot = "";
        this.parent = null;
    } else {
    	this.parent = parent;
    	name = parent.getName() + "/" + zip1.getName();
    	zipPathToRoot = name+"/";
    }

    lastModified = zip1.lastModified();
    size = zip1.length();
    url = zip1.toURI().toURL().toExternalForm();
    this.cache = null;
  }

  public ZipFileImpl(ZipFileImpl other, ZipCloseableDirectory cache) {
	  name = other.name;
	  size = other.size;
	  lastModified = other.lastModified;
	  zip = other.zip;
	  entry = other.entry;
	  parent = other.parent;
	  url = other.url;
	  zipPathToRoot = other.zipPathToRoot;
	  this.cache = cache;
  }

  /**
   * Obtain the path of the zip file to the VFS root
   */
  public String getZipPathToRoot() {
	  return zipPathToRoot;
  }

  public IDirectory convert()
  {
    return null;
  }

  public IDirectory convertNested() {
	  if (isDirectory()) return convert();
	  else if (FileSystemImpl.isValidZip(this)) return new NestedZipDirectory(this);
	  else return null;
  }

  public long getLastModified()
  {
    return lastModified;
  }

  public String getName()
  {
    return name;
  }

  public String getNameInZip()
  {
	  if (entry == null) return "";
	  else {
		  String name = entry.getName();
		  if (isDirectory()) return name.substring(0, name.length()-1);
		  else return name;
	  }
  }

  public IDirectory getParent()
  {
    return parent;
  }

  public long getSize()
  {
    return size;
  }

  public boolean isDirectory()
  {
    return false;
  }

  public boolean isFile()
  {
    return true;
  }

  public InputStream open() throws IOException
  {
    InputStream is = new SpecialZipInputStream(entry);
    return is;
  }

  public IDirectory getRoot()
  {
    return parent.getRoot();
  }

  public URL toURL() throws MalformedURLException
  {
    URL result;

    if(name.equals(zipPathToRoot))
      result = new URL(url);
    else {

      String entryURL = "jar:" + url + "!/";
      if(entry != null)
        entryURL += entry.getName();
      else {
        entryURL += name.substring(zipPathToRoot.length());
      }
      result = new URL(entryURL);
    }

    return result;
  }

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

    if (obj.getClass() == getClass()) {
      return toString().equals(obj.toString());
    }

    return false;
  }

  @Override
  public int hashCode()
  {
    return toString().hashCode();
  }

  @Override
  public String toString()
  {
	  if (name != null && name.length() != 0) return url.substring(5)+ "/" + name;
	  else return url.substring(5);
  }

  ZipFile openZipFile(){
    ZipFile z = null;

    if (cache != null && !!!cache.isClosed()) {
    	z = cache.getZipFile();
    } else {
	    try {
	      z = new ZipFile(zip);
	    } catch (IOException e) {
	      throw new IORuntimeException("IOException in ZipFileImpl.openZipFile", e);
	    }
    }
    return z;
  }

  void closeZipFile(ZipFile z){
	  if (cache != null && cache.getZipFile() == z) {
		  // do nothing
	  } else {
		  try{
			  z.close();
		  }
		  catch (IOException e) {
			  throw new IORuntimeException("IOException in ZipFileImpl.closeZipFile", e);
		  }
	  }
  }

  /**
   * A simple class to delegate to the InputStream of the constructor
   * and to call close on the zipFile when we close the stream.
   *
   */
  private class SpecialZipInputStream extends InputStream{

    private ZipFile zipFile;
    private InputStream is;

    public SpecialZipInputStream(ZipEntry anEntry){
      try{
      this.zipFile = openZipFile();
      this.is = zipFile.getInputStream(anEntry);
      }
      catch (ZipException e) {
        throw new IORuntimeException("ZipException in SpecialZipInputStream()", e);
      } catch (IOException e) {
        throw new IORuntimeException("IOException in SpecialZipInputStream()", e);
      }
    }

    @Override
    public int read(byte[] b) throws IOException {
      return is.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
      return is.read(b, off, len);
    }

    @Override
    public int read() throws IOException
    {
      return is.read();
    }

    @Override
    public void close() throws IOException{
        //call close on the input stream, probably does nothing
        is.close();
        //call close on the zip file, important for tidying up
        closeZipFile(zipFile);
    }

  }

}


text:
SimpSoon is animation responsive coming soon page

## Live preview
1. [Background Image](http://demo.forward-web.com/simpsoon)
2. [Background animated gradient](http://demo.forward-web.com/index-animation-bg.html)

## Description
Simpsoon template is a simple coming soon page with awesome jquery animation effect and countdown timer.

## How to use
1.  **Edit counter date** : to edit counter date search for "$COUNTER"
    and under this you will fined (div) named (counter)
    then edit (timer) attribute like (Month Day, Year Hours:Minutes:Seconds).
```html
<!-- 4.$COUNTER ====================================================================

COUNTER

-->
<div class="counter" timer="12 25, 2017 12:00:0">
  <div class="container">
    <div class="row">

      <div class="col-md-3 col-sm-6 days wow bounceIn" data-wow-delay="1.3s">
        <div class='count-round'></div>
      </div>

      <div class="col-md-3 col-sm-6 hours wow bounceIn" data-wow-delay="1.6s">
        <div class='count-round'></div>
      </div>

      <div class="col-md-3 col-sm-6 min wow bounceIn" data-wow-delay="1.9s">
        <div class='count-round'></div>
      </div>

      <div class="col-md-3 col-sm-6 sec wow bounceIn" data-wow-delay="2.1s">
        <div class="count-round animated jello"></div>
      </div>

    </div>
  </div>
</div>
```

2.  **change message text** : to change message text go to (assets/js/simpsoon) file
    and go to line number (36) and edit this ["first message", "second message"]
    and if you need to add more messages just add (,) between messages.
```javascript
// typed function
$(function(){
    $(".text span").typed({
      strings: ["WE WILL BE ONLINE AFTER.", "Visit us after this time."],
      typeSpeed: 40,
      startDelay: 3000,
      backDelay: 3000,
      loop: true
    });
});
```

## Credits
1. [Typed.js](http://www.mattboldt.com/demos/typed-js/)
2. [Wow.js](http://mynameismatthieu.com/WOW/)
3. [Bootstrap v3.3.5](http://getbootstrap.com)
4. [animate.css](https://daneden.github.io/animate.css/)


text:
# dmeanpw

> Calculate the [arithmetic mean][arithmetic-mean] of a double-precision floating-point strided array using pairwise summation.

The [arithmetic mean][arithmetic-mean] is defined as

## Usage

```javascript
var dmeanpw = require( '@stdlib/stats/base/dmeanpw' );
```

#### dmeanpw( N, x, stride )

Computes the [arithmetic mean][arithmetic-mean] of a double-precision floating-point strided array `x` using pairwise summation.

```javascript
var Float64Array = require( '@stdlib/array/float64' );

var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
var N = x.length;

var v = dmeanpw( N, x, 1 );
// returns ~0.3333
```

The function has the following parameters:

-   **N**: number of indexed elements.
-   **x**: input [`Float64Array`][@stdlib/array/float64].
-   **stride**: index increment for `x`.

The `N` and `stride` parameters determine which elements in `x` are accessed at runtime. For example, to compute the [arithmetic mean][arithmetic-mean] of every other element in `x`,

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var floor = require( '@stdlib/math/base/special/floor' );

var x = new Float64Array( [ 1.0, 2.0, 2.0, -7.0, -2.0, 3.0, 4.0, 2.0 ] );
var N = floor( x.length / 2 );

var v = dmeanpw( N, x, 2 );
// returns 1.25
```

Note that indexing is relative to the first index. To introduce an offset, use [`typed array`][mdn-typed-array] views.

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var floor = require( '@stdlib/math/base/special/floor' );

var x0 = new Float64Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
var x1 = new Float64Array( x0.buffer, x0.BYTES_PER_ELEMENT*1 ); // start at 2nd element

var N = floor( x0.length / 2 );

var v = dmeanpw( N, x1, 2 );
// returns 1.25
```

#### dmeanpw.ndarray( N, x, stride, offset )

Computes the [arithmetic mean][arithmetic-mean] of a double-precision floating-point strided array using pairwise summation and alternative indexing semantics.

```javascript
var Float64Array = require( '@stdlib/array/float64' );

var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
var N = x.length;

var v = dmeanpw.ndarray( N, x, 1, 0 );
// returns ~0.33333
```

The function has the following additional parameters:

-   **offset**: starting index for `x`.

While [`typed array`][mdn-typed-array] views mandate a view offset based on the underlying `buffer`, the `offset` parameter supports indexing semantics based on a starting index. For example, to calculate the [arithmetic mean][arithmetic-mean] for every other value in `x` starting from the second value

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var floor = require( '@stdlib/math/base/special/floor' );

var x = new Float64Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
var N = floor( x.length / 2 );

var v = dmeanpw.ndarray( N, x, 2, 1 );
// returns 1.25
```

## Notes

-   If `N <= 0`, both functions return `NaN`.
-   In general, pairwise summation is more numerically stable than ordinary recursive summation (i.e., "simple" summation), with slightly worse performance. While not the most numerically stable summation technique (e.g., compensated summation techniques such as the Kahan–Babuška-Neumaier algorithm are generally more numerically stable), pairwise summation strikes a reasonable balance between numerical stability and performance. If either numerical stability or performance is more desirable for your use case, consider alternative summation techniques.

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var round = require( '@stdlib/math/base/special/round' );
var Float64Array = require( '@stdlib/array/float64' );
var dmeanpw = require( '@stdlib/stats/base/dmeanpw' );

var x;
var i;

x = new Float64Array( 10 );
for ( i = 0; i < x.length; i++ ) {
    x[ i ] = round( (randu()*100.0) - 50.0 );
}
console.log( x );

var v = dmeanpw( x.length, x, 1 );
console.log( v );
```

* * *

## References

-   Higham, Nicholas J. 1993. "The Accuracy of Floating Point Summation." _SIAM Journal on Scientific Computing_ 14 (4): 783–99. doi:[10.1137/0914050][@higham:1993a].

* * *

## See Also

-   [`@stdlib/stats/base/dmean`][@stdlib/stats/base/dmean]: calculate the arithmetic mean of a double-precision floating-point strided array.
-   [`@stdlib/stats/base/dnanmeanpw`][@stdlib/stats/base/dnanmeanpw]: calculate the arithmetic mean of a double-precision floating-point strided array, ignoring NaN values and using pairwise summation.
-   [`@stdlib/stats/base/meanpw`][@stdlib/stats/base/meanpw]: calculate the arithmetic mean of a strided array using pairwise summation.
-   [`@stdlib/stats/base/smeanpw`][@stdlib/stats/base/smeanpw]: calculate the arithmetic mean of a single-precision floating-point strided array using pairwise summation.

[arithmetic-mean]: https://en.wikipedia.org/wiki/Arithmetic_mean

[@stdlib/array/float64]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array/float64

[mdn-typed-array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

[@higham:1993a]: https://doi.org/10.1137/0914050

[@stdlib/stats/base/dmean]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/base/dmean

[@stdlib/stats/base/dnanmeanpw]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/base/dnanmeanpw

[@stdlib/stats/base/meanpw]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/base/meanpw

[@stdlib/stats/base/smeanpw]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/base/smeanpw


text:
using System;
using System.Xml.Serialization;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// AlipayMarketingCashvoucherTemplateCreateResponse.
    /// </summary>
    public class AlipayMarketingCashvoucherTemplateCreateResponse : AopResponse
    {
        /// <summary>
        /// 模板支付确认链接
        /// </summary>
        [XmlElement("confirm_uri")]
        public string ConfirmUri { get; set; }

        /// <summary>
        /// 资金订单号,模板支付时需要
        /// </summary>
        [XmlElement("fund_order_no")]
        public string FundOrderNo { get; set; }

        /// <summary>
        /// 券模板ID
        /// </summary>
        [XmlElement("template_id")]
        public string TemplateId { get; set; }
    }
}


text:
template <typename T>
class BufferView2D
{
private:
	T *data; // Start of original 2D array.
	int width, height; // Dimensions of original 2D array.
	int viewX, viewY; // View coordinates.
	int viewWidth, viewHeight; // View dimensions.

	int getIndex(int x, int y) const
	{
		DebugAssert(x >= 0);
		DebugAssert(y >= 0);
		DebugAssert(x < this->viewWidth);
		DebugAssert(y < this->viewHeight);
		return (viewX + x) + ((viewY + y) * this->width);
	}
public:
	BufferView2D()
	{
		this->reset();
	}

	// View across a subset of a 2D range of data. The original 2D range's dimensions are required
	// for proper look-up (and bounds-checking).
	BufferView2D(T *data, int width, int height, int viewX, int viewY, int viewWidth, int viewHeight)
	{
		this->init(data, width, height, viewX, viewY, viewWidth, viewHeight);
	}

	// View across a 2D range of data.
	BufferView2D(T *data, int width, int height)
	{
		this->init(data, width, height);
	}

	void init(T *data, int width, int height, int viewX, int viewY, int viewWidth, int viewHeight)
	{
		DebugAssert(width >= 0);
		DebugAssert(height >= 0);
		DebugAssert(viewX >= 0);
		DebugAssert(viewY >= 0);
		DebugAssert(viewWidth >= 0);
		DebugAssert(viewHeight >= 0);
		DebugAssert((viewX + viewWidth) <= width);
		DebugAssert((viewY + viewHeight) <= height);
		this->data = data;
		this->width = width;
		this->height = height;
		this->viewX = viewX;
		this->viewY = viewY;
		this->viewWidth = viewWidth;
		this->viewHeight = viewHeight;
	}

	void init(T *data, int width, int height)
	{
		this->init(data, width, height, 0, 0, width, height);
	}

	bool isValid() const
	{
		return this->data != nullptr;
	}

	bool isSlice() const
	{
		return (this->viewWidth < this->width) || (this->viewHeight < this->height);
	}

	T *get()
	{
		DebugAssert(!this->isSlice());
		return this->data;
	}

	const T *get() const
	{
		DebugAssert(!this->isSlice());
		return this->data;
	}

	T &get(int x, int y)
	{
		DebugAssert(this->isValid());
		const int index = this->getIndex(x, y);
		return this->data[index];
	}

	const T &get(int x, int y) const
	{
		DebugAssert(this->isValid());
		const int index = this->getIndex(x, y);
		return this->data[index];
	}

	T *end()
	{
		DebugAssert(!this->isSlice());
		return (this->data != nullptr) ? (this->data + (this->width * this->height)) : nullptr;
	}

	const T *end() const
	{
		DebugAssert(!this->isSlice());
		return (this->data != nullptr) ? (this->data + (this->width * this->height)) : nullptr;
	}

	int getWidth() const
	{
		return this->viewWidth;
	}

	int getHeight() const
	{
		return this->viewHeight;
	}

	void set(int x, int y, const T &value)
	{
		static_assert(!std::is_const_v<T>, "Cannot change const data.");

		DebugAssert(this->isValid());
		const int index = this->getIndex(x, y);
		this->data[index] = value;
	}

	void set(int x, int y, T &&value)
	{
		static_assert(!std::is_const_v<T>, "Cannot change const data.");

		DebugAssert(this->isValid());
		const int index = this->getIndex(x, y);
		this->data[index] = std::move(value);
	}

	void fill(const T &value)
	{
		static_assert(!std::is_const_v<T>, "Cannot change const data.");

		DebugAssert(this->isValid());

		for (int y = 0; y < this->viewHeight; y++)
		{
			// Elements in a row are adjacent in memory.
			T *startPtr = this->data + this->getIndex(0, y);
			T *endPtr = startPtr + this->viewWidth;
			std::fill(startPtr, endPtr, value);
		}
	}

	void reset()
	{
		this->data = nullptr;
		this->width = 0;
		this->height = 0;
		this->viewX = 0;
		this->viewY = 0;
		this->viewWidth = 0;
		this->viewHeight = 0;
	}
};

#endif


text:
package org.apache.hadoop.hbase.util;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.zip.Checksum;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Checksum types. The Checksum type is a one byte number
 * that stores a representation of the checksum algorithm
 * used to encode a hfile. The ordinal of these cannot
 * change or else you risk breaking all existing HFiles out there.
 */
public enum ChecksumType {

  NULL((byte)0) {
    @Override
    public String getName() {
      return "NULL";
    }
    @Override
    public void initialize() {
      // do nothing
    }
    @Override
    public Checksum getChecksumObject() throws IOException {
      return null; // checksums not used
    }
  },

  CRC32((byte)1) {
    private volatile Constructor<?> ctor;

    @Override
    public String getName() {
      return "CRC32";
    }

    @Override
    public void initialize() {
      final String PURECRC32 = "org.apache.hadoop.util.PureJavaCrc32";
      final String JDKCRC = "java.util.zip.CRC32";
      LOG = LogFactory.getLog(ChecksumType.class);

      // check if hadoop library is available
      try {
        ctor = ChecksumFactory.newConstructor(PURECRC32);
        LOG.info("Checksum using " + PURECRC32);
      } catch (Exception e) {
        LOG.trace(PURECRC32 + " not available.");
      }
      try {
        // The default checksum class name is java.util.zip.CRC32.
        // This is available on all JVMs.
        if (ctor == null) {
          ctor = ChecksumFactory.newConstructor(JDKCRC);
          LOG.info("Checksum can use " + JDKCRC);
        }
      } catch (Exception e) {
        LOG.trace(JDKCRC + " not available.");
      }
    }

    @Override
    public Checksum getChecksumObject() throws IOException {
      if (ctor == null) {
        throw new IOException("Bad constructor for " + getName());
      }
      try {
        return (Checksum)ctor.newInstance();
      } catch (Exception e) {
        throw new IOException(e);
      }
    }
  },

  CRC32C((byte)2) {
    private transient Constructor<?> ctor;

    @Override
    public String getName() {
      return "CRC32C";
    }

    @Override
    public void initialize() {
      final String PURECRC32C = "org.apache.hadoop.util.PureJavaCrc32C";
      LOG = LogFactory.getLog(ChecksumType.class);
      try {
        ctor = ChecksumFactory.newConstructor(PURECRC32C);
        LOG.info("Checksum can use " + PURECRC32C);
      } catch (Exception e) {
        LOG.trace(PURECRC32C + " not available.");
      }
    }

    @Override
    public Checksum getChecksumObject() throws IOException {
      if (ctor == null) {
        throw new IOException("Bad constructor for " + getName());
      }
      try {
        return (Checksum)ctor.newInstance();
      } catch (Exception e) {
        throw new IOException(e);
      }
    }
  };

  private final byte code;
  protected Log LOG;

  /** initializes the relevant checksum class object */
  abstract void initialize();

  /** returns the name of this checksum type */
  public abstract String getName();

  private ChecksumType(final byte c) {
    this.code = c;
    initialize();
  }

  /** returns a object that can be used to generate/validate checksums */
  public abstract Checksum getChecksumObject() throws IOException;

  public byte getCode() {
    return this.code;
  }

  /**
   * Cannot rely on enum ordinals . They change if item is removed or moved.
   * Do our own codes.
   * @param b
   * @return Type associated with passed code.
   */
  public static ChecksumType codeToType(final byte b) {
    for (ChecksumType t : ChecksumType.values()) {
      if (t.getCode() == b) {
        return t;
      }
    }
    throw new RuntimeException("Unknown checksum type code " + b);
  }

  /**
   * Map a checksum name to a specific type.
   * Do our own names.
   * @param name
   * @return Type associated with passed code.
   */
  public static ChecksumType nameToType(final String name) {
    for (ChecksumType t : ChecksumType.values()) {
      if (t.getName().equals(name)) {
        return t;
      }
    }
    throw new RuntimeException("Unknown checksum type name " + name);
  }
}


text:
A simple reviewer for 23 design patterns.

# Dependency
Please install colorama.
For example, on Debian/Ubuntu:
```
$ sudo apt-get install python-pip
$ sudo pip install colorama
```

or

```
cd ./dependency/colorama-0.3.3
$ sudo python setup.py install
```