text:
package kubernetes

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"net/http"
	"strings"
	"time"

	"github.com/dexidp/dex/pkg/log"
	"github.com/dexidp/dex/storage"
	"github.com/dexidp/dex/storage/kubernetes/k8sapi"
)

const (
	kindAuthCode        = "AuthCode"
	kindAuthRequest     = "AuthRequest"
	kindClient          = "OAuth2Client"
	kindRefreshToken    = "RefreshToken"
	kindKeys            = "SigningKey"
	kindPassword        = "Password"
	kindOfflineSessions = "OfflineSessions"
	kindConnector       = "Connector"
	kindDeviceRequest   = "DeviceRequest"
	kindDeviceToken     = "DeviceToken"
)

const (
	resourceAuthCode        = "authcodes"
	resourceAuthRequest     = "authrequests"
	resourceClient          = "oauth2clients"
	resourceRefreshToken    = "refreshtokens"
	resourceKeys            = "signingkeies" // Kubernetes attempts to pluralize.
	resourcePassword        = "passwords"
	resourceOfflineSessions = "offlinesessionses" // Again attempts to pluralize.
	resourceConnector       = "connectors"
	resourceDeviceRequest   = "devicerequests"
	resourceDeviceToken     = "devicetokens"
)

// Config values for the Kubernetes storage type.
type Config struct {
	InCluster      bool   `json:"inCluster"`
	KubeConfigFile string `json:"kubeConfigFile"`
}

// Open returns a storage using Kubernetes third party resource.
func (c *Config) Open(logger log.Logger) (storage.Storage, error) {
	cli, err := c.open(logger, false)
	if err != nil {
		return nil, err
	}
	return cli, nil
}

// open returns a kubernetes client, initializing the third party resources used
// by dex.
//
// waitForResources controls if errors creating the resources cause this method to return
// immediately (used during testing), or if the client will asynchronously retry.
func (c *Config) open(logger log.Logger, waitForResources bool) (*client, error) {
	if c.InCluster && (c.KubeConfigFile != "") {
		return nil, errors.New("cannot specify both 'inCluster' and 'kubeConfigFile'")
	}
	if !c.InCluster && (c.KubeConfigFile == "") {
		return nil, errors.New("must specify either 'inCluster' or 'kubeConfigFile'")
	}

	var (
		cluster   k8sapi.Cluster
		user      k8sapi.AuthInfo
		namespace string
		err       error
	)
	if c.InCluster {
		cluster, user, namespace, err = inClusterConfig()
	} else {
		cluster, user, namespace, err = loadKubeConfig(c.KubeConfigFile)
	}
	if err != nil {
		return nil, err
	}

	cli, err := newClient(cluster, user, namespace, logger)
	if err != nil {
		return nil, fmt.Errorf("create client: %v", err)
	}

	ctx, cancel := context.WithCancel(context.Background())

	logger.Info("creating custom Kubernetes resources")
	if !cli.registerCustomResources() {
		if waitForResources {
			cancel()
			return nil, fmt.Errorf("failed creating custom resources")
		}

		// Try to synchronously create the custom resources once. This doesn't mean
		// they'll immediately be available, but ensures that the client will actually try
		// once.
		logger.Errorf("failed creating custom resources: %v", err)
		go func() {
			for {
				if cli.registerCustomResources() {
					return
				}

				select {
				case <-ctx.Done():
					return
				case <-time.After(30 * time.Second):
				}
			}
		}()
	}

	if waitForResources {
		if err := cli.waitForCRDs(ctx); err != nil {
			cancel()
			return nil, err
		}
	}

	// If the client is closed, stop trying to create resources.
	cli.cancel = cancel
	return cli, nil
}

// registerCustomResources attempts to create the custom resources dex
// requires or identifies that they're already enabled. This function creates
// custom resource definitions(CRDs)
// It logs all errors, returning true if the resources were created successfully.
//
// Creating a custom resource does not mean that they'll be immediately available.
func (cli *client) registerCustomResources() (ok bool) {
	ok = true
	length := len(customResourceDefinitions)
	for i := 0; i < length; i++ {
		var err error
		var resourceName string

		r := customResourceDefinitions[i]
		var i interface{}
		cli.logger.Infof("checking if custom resource %s has been created already...", r.ObjectMeta.Name)
		if err := cli.list(r.Spec.Names.Plural, &i); err == nil {
			cli.logger.Infof("The custom resource %s already available, skipping create", r.ObjectMeta.Name)
			continue
		} else {
			cli.logger.Infof("failed to list custom resource %s, attempting to create: %v", r.ObjectMeta.Name, err)
		}
		err = cli.postResource("apiextensions.k8s.io/v1beta1", "", "customresourcedefinitions", r)
		resourceName = r.ObjectMeta.Name

		if err != nil {
			switch err {
			case storage.ErrAlreadyExists:
				cli.logger.Infof("custom resource already created %s", resourceName)
			case storage.ErrNotFound:
				cli.logger.Errorf("custom resources not found, please enable the respective API group")
				ok = false
			default:
				cli.logger.Errorf("creating custom resource %s: %v", resourceName, err)
				ok = false
			}
			continue
		}
		cli.logger.Errorf("create custom resource %s", resourceName)
	}
	return ok
}

// waitForCRDs waits for all CRDs to be in a ready state, and is used
// by the tests to synchronize before running conformance.
func (cli *client) waitForCRDs(ctx context.Context) error {
	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	for _, crd := range customResourceDefinitions {
		for {
			err := cli.isCRDReady(crd.Name)
			if err == nil {
				break
			}

			cli.logger.Errorf("checking CRD: %v", err)

			select {
			case <-ctx.Done():
				return errors.New("timed out waiting for CRDs to be available")
			case <-time.After(time.Millisecond * 100):
			}
		}
	}
	return nil
}

// isCRDReady determines if a CRD is ready by inspecting its conditions.
func (cli *client) isCRDReady(name string) error {
	var r k8sapi.CustomResourceDefinition
	err := cli.getResource("apiextensions.k8s.io/v1beta1", "", "customresourcedefinitions", name, &r)
	if err != nil {
		return fmt.Errorf("get crd %s: %v", name, err)
	}

	conds := make(map[string]string) // For debugging, keep the conditions around.
	for _, c := range r.Status.Conditions {
		if c.Type == k8sapi.Established && c.Status == k8sapi.ConditionTrue {
			return nil
		}
		conds[string(c.Type)] = string(c.Status)
	}
	return fmt.Errorf("crd %s not ready %#v", name, conds)
}

func (cli *client) Close() error {
	if cli.cancel != nil {
		cli.cancel()
	}
	return nil
}

func (cli *client) CreateAuthRequest(a storage.AuthRequest) error {
	return cli.post(resourceAuthRequest, cli.fromStorageAuthRequest(a))
}

func (cli *client) CreateClient(c storage.Client) error {
	return cli.post(resourceClient, cli.fromStorageClient(c))
}

func (cli *client) CreateAuthCode(c storage.AuthCode) error {
	return cli.post(resourceAuthCode, cli.fromStorageAuthCode(c))
}

func (cli *client) CreatePassword(p storage.Password) error {
	return cli.post(resourcePassword, cli.fromStoragePassword(p))
}

func (cli *client) CreateRefresh(r storage.RefreshToken) error {
	return cli.post(resourceRefreshToken, cli.fromStorageRefreshToken(r))
}

func (cli *client) CreateOfflineSessions(o storage.OfflineSessions) error {
	return cli.post(resourceOfflineSessions, cli.fromStorageOfflineSessions(o))
}

func (cli *client) CreateConnector(c storage.Connector) error {
	return cli.post(resourceConnector, cli.fromStorageConnector(c))
}

func (cli *client) GetAuthRequest(id string) (storage.AuthRequest, error) {
	var req AuthRequest
	if err := cli.get(resourceAuthRequest, id, &req); err != nil {
		return storage.AuthRequest{}, err
	}
	return toStorageAuthRequest(req), nil
}

func (cli *client) GetAuthCode(id string) (storage.AuthCode, error) {
	var code AuthCode
	if err := cli.get(resourceAuthCode, id, &code); err != nil {
		return storage.AuthCode{}, err
	}
	return toStorageAuthCode(code), nil
}

func (cli *client) GetClient(id string) (storage.Client, error) {
	c, err := cli.getClient(id)
	if err != nil {
		return storage.Client{}, err
	}
	return toStorageClient(c), nil
}

func (cli *client) getClient(id string) (Client, error) {
	var c Client
	name := cli.idToName(id)
	if err := cli.get(resourceClient, name, &c); err != nil {
		return Client{}, err
	}
	if c.ID != id {
		return Client{}, fmt.Errorf("get client: ID %q mapped to client with ID %q", id, c.ID)
	}
	return c, nil
}

func (cli *client) GetPassword(email string) (storage.Password, error) {
	p, err := cli.getPassword(email)
	if err != nil {
		return storage.Password{}, err
	}
	return toStoragePassword(p), nil
}

func (cli *client) getPassword(email string) (Password, error) {
	// TODO(ericchiang): Figure out whose job it is to lowercase emails.
	email = strings.ToLower(email)
	var p Password
	name := cli.idToName(email)
	if err := cli.get(resourcePassword, name, &p); err != nil {
		return Password{}, err
	}
	if email != p.Email {
		return Password{}, fmt.Errorf("get email: email %q mapped to password with email %q", email, p.Email)
	}
	return p, nil
}

func (cli *client) GetKeys() (storage.Keys, error) {
	var keys Keys
	if err := cli.get(resourceKeys, keysName, &keys); err != nil {
		return storage.Keys{}, err
	}
	return toStorageKeys(keys), nil
}

func (cli *client) GetRefresh(id string) (storage.RefreshToken, error) {
	r, err := cli.getRefreshToken(id)
	if err != nil {
		return storage.RefreshToken{}, err
	}
	return toStorageRefreshToken(r), nil
}

func (cli *client) getRefreshToken(id string) (r RefreshToken, err error) {
	err = cli.get(resourceRefreshToken, id, &r)
	return
}

func (cli *client) GetOfflineSessions(userID string, connID string) (storage.OfflineSessions, error) {
	o, err := cli.getOfflineSessions(userID, connID)
	if err != nil {
		return storage.OfflineSessions{}, err
	}
	return toStorageOfflineSessions(o), nil
}

func (cli *client) getOfflineSessions(userID string, connID string) (o OfflineSessions, err error) {
	name := cli.offlineTokenName(userID, connID)
	if err = cli.get(resourceOfflineSessions, name, &o); err != nil {
		return OfflineSessions{}, err
	}
	if userID != o.UserID || connID != o.ConnID {
		return OfflineSessions{}, fmt.Errorf("get offline session: wrong session retrieved")
	}
	return o, nil
}

func (cli *client) GetConnector(id string) (storage.Connector, error) {
	var c Connector
	if err := cli.get(resourceConnector, id, &c); err != nil {
		return storage.Connector{}, err
	}
	return toStorageConnector(c), nil
}

func (cli *client) ListClients() ([]storage.Client, error) {
	return nil, errors.New("not implemented")
}

func (cli *client) ListRefreshTokens() ([]storage.RefreshToken, error) {
	return nil, errors.New("not implemented")
}

func (cli *client) ListPasswords() (passwords []storage.Password, err error) {
	var passwordList PasswordList
	if err = cli.list(resourcePassword, &passwordList); err != nil {
		return passwords, fmt.Errorf("failed to list passwords: %v", err)
	}

	for _, password := range passwordList.Passwords {
		p := storage.Password{
			Email:    password.Email,
			Hash:     password.Hash,
			Username: password.Username,
			UserID:   password.UserID,
		}
		passwords = append(passwords, p)
	}

	return
}

func (cli *client) ListConnectors() (connectors []storage.Connector, err error) {
	var connectorList ConnectorList
	if err = cli.list(resourceConnector, &connectorList); err != nil {
		return connectors, fmt.Errorf("failed to list connectors: %v", err)
	}

	connectors = make([]storage.Connector, len(connectorList.Connectors))
	for i, connector := range connectorList.Connectors {
		connectors[i] = toStorageConnector(connector)
	}

	return
}

func (cli *client) DeleteAuthRequest(id string) error {
	return cli.delete(resourceAuthRequest, id)
}

func (cli *client) DeleteAuthCode(code string) error {
	return cli.delete(resourceAuthCode, code)
}

func (cli *client) DeleteClient(id string) error {
	// Check for hash collision.
	c, err := cli.getClient(id)
	if err != nil {
		return err
	}
	return cli.delete(resourceClient, c.ObjectMeta.Name)
}

func (cli *client) DeleteRefresh(id string) error {
	return cli.delete(resourceRefreshToken, id)
}

func (cli *client) DeletePassword(email string) error {
	// Check for hash collision.
	p, err := cli.getPassword(email)
	if err != nil {
		return err
	}
	return cli.delete(resourcePassword, p.ObjectMeta.Name)
}

func (cli *client) DeleteOfflineSessions(userID string, connID string) error {
	// Check for hash collision.
	o, err := cli.getOfflineSessions(userID, connID)
	if err != nil {
		return err
	}
	return cli.delete(resourceOfflineSessions, o.ObjectMeta.Name)
}

func (cli *client) DeleteConnector(id string) error {
	return cli.delete(resourceConnector, id)
}

func (cli *client) UpdateRefreshToken(id string, updater func(old storage.RefreshToken) (storage.RefreshToken, error)) error {
	return retryOnConflict(context.TODO(), func() error {
		r, err := cli.getRefreshToken(id)
		if err != nil {
			return err
		}
		updated, err := updater(toStorageRefreshToken(r))
		if err != nil {
			return err
		}
		updated.ID = id

		newToken := cli.fromStorageRefreshToken(updated)
		newToken.ObjectMeta = r.ObjectMeta
		return cli.put(resourceRefreshToken, r.ObjectMeta.Name, newToken)
	})
}

func (cli *client) UpdateClient(id string, updater func(old storage.Client) (storage.Client, error)) error {
	c, err := cli.getClient(id)
	if err != nil {
		return err
	}

	updated, err := updater(toStorageClient(c))
	if err != nil {
		return err
	}
	updated.ID = c.ID

	newClient := cli.fromStorageClient(updated)
	newClient.ObjectMeta = c.ObjectMeta
	return cli.put(resourceClient, c.ObjectMeta.Name, newClient)
}

func (cli *client) UpdatePassword(email string, updater func(old storage.Password) (storage.Password, error)) error {
	p, err := cli.getPassword(email)
	if err != nil {
		return err
	}

	updated, err := updater(toStoragePassword(p))
	if err != nil {
		return err
	}
	updated.Email = p.Email

	newPassword := cli.fromStoragePassword(updated)
	newPassword.ObjectMeta = p.ObjectMeta
	return cli.put(resourcePassword, p.ObjectMeta.Name, newPassword)
}

func (cli *client) UpdateOfflineSessions(userID string, connID string, updater func(old storage.OfflineSessions) (storage.OfflineSessions, error)) error {
	return retryOnConflict(context.TODO(), func() error {
		o, err := cli.getOfflineSessions(userID, connID)
		if err != nil {
			return err
		}

		updated, err := updater(toStorageOfflineSessions(o))
		if err != nil {
			return err
		}

		newOfflineSessions := cli.fromStorageOfflineSessions(updated)
		newOfflineSessions.ObjectMeta = o.ObjectMeta
		return cli.put(resourceOfflineSessions, o.ObjectMeta.Name, newOfflineSessions)
	})
}

func (cli *client) UpdateKeys(updater func(old storage.Keys) (storage.Keys, error)) error {
	firstUpdate := false
	var keys Keys
	if err := cli.get(resourceKeys, keysName, &keys); err != nil {
		if err != storage.ErrNotFound {
			return err
		}
		firstUpdate = true
	}

	var oldKeys storage.Keys
	if !firstUpdate {
		oldKeys = toStorageKeys(keys)
	}

	updated, err := updater(oldKeys)
	if err != nil {
		return err
	}

	newKeys := cli.fromStorageKeys(updated)
	if firstUpdate {
		err = cli.post(resourceKeys, newKeys)
		if err != nil && errors.Is(err, storage.ErrAlreadyExists) {
			// We need to tolerate conflicts here in case of HA mode.
			cli.logger.Debugf("Keys creation failed: %v. It is possible that keys have already been created by another dex instance.", err)
			return errors.New("keys already created by another server instance")
		}

		return err
	}

	newKeys.ObjectMeta = keys.ObjectMeta

	err = cli.put(resourceKeys, keysName, newKeys)
	if isKubernetesAPIConflictError(err) {
		// We need to tolerate conflicts here in case of HA mode.
		// Dex instances run keys rotation at the same time because they use SigningKey.nextRotation CR field as a trigger.
		cli.logger.Debugf("Keys rotation failed: %v. It is possible that keys have already been rotated by another dex instance.", err)
		return errors.New("keys already rotated by another server instance")
	}

	return err
}

func (cli *client) UpdateAuthRequest(id string, updater func(a storage.AuthRequest) (storage.AuthRequest, error)) error {
	var req AuthRequest
	err := cli.get(resourceAuthRequest, id, &req)
	if err != nil {
		return err
	}

	updated, err := updater(toStorageAuthRequest(req))
	if err != nil {
		return err
	}

	newReq := cli.fromStorageAuthRequest(updated)
	newReq.ObjectMeta = req.ObjectMeta
	return cli.put(resourceAuthRequest, id, newReq)
}

func (cli *client) UpdateConnector(id string, updater func(a storage.Connector) (storage.Connector, error)) error {
	return retryOnConflict(context.TODO(), func() error {
		var c Connector
		err := cli.get(resourceConnector, id, &c)
		if err != nil {
			return err
		}

		updated, err := updater(toStorageConnector(c))
		if err != nil {
			return err
		}

		newConn := cli.fromStorageConnector(updated)
		newConn.ObjectMeta = c.ObjectMeta
		return cli.put(resourceConnector, id, newConn)
	})
}

func (cli *client) GarbageCollect(now time.Time) (result storage.GCResult, err error) {
	var authRequests AuthRequestList
	if err := cli.list(resourceAuthRequest, &authRequests); err != nil {
		return result, fmt.Errorf("failed to list auth requests: %v", err)
	}

	var delErr error
	for _, authRequest := range authRequests.AuthRequests {
		if now.After(authRequest.Expiry) {
			if err := cli.delete(resourceAuthRequest, authRequest.ObjectMeta.Name); err != nil {
				cli.logger.Errorf("failed to delete auth request: %v", err)
				delErr = fmt.Errorf("failed to delete auth request: %v", err)
			}
			result.AuthRequests++
		}
	}
	if delErr != nil {
		return result, delErr
	}

	var authCodes AuthCodeList
	if err := cli.list(resourceAuthCode, &authCodes); err != nil {
		return result, fmt.Errorf("failed to list auth codes: %v", err)
	}

	for _, authCode := range authCodes.AuthCodes {
		if now.After(authCode.Expiry) {
			if err := cli.delete(resourceAuthCode, authCode.ObjectMeta.Name); err != nil {
				cli.logger.Errorf("failed to delete auth code %v", err)
				delErr = fmt.Errorf("failed to delete auth code: %v", err)
			}
			result.AuthCodes++
		}
	}

	var deviceRequests DeviceRequestList
	if err := cli.list(resourceDeviceRequest, &deviceRequests); err != nil {
		return result, fmt.Errorf("failed to list device requests: %v", err)
	}

	for _, deviceRequest := range deviceRequests.DeviceRequests {
		if now.After(deviceRequest.Expiry) {
			if err := cli.delete(resourceDeviceRequest, deviceRequest.ObjectMeta.Name); err != nil {
				cli.logger.Errorf("failed to delete device request: %v", err)
				delErr = fmt.Errorf("failed to delete device request: %v", err)
			}
			result.DeviceRequests++
		}
	}

	var deviceTokens DeviceTokenList
	if err := cli.list(resourceDeviceToken, &deviceTokens); err != nil {
		return result, fmt.Errorf("failed to list device tokens: %v", err)
	}

	for _, deviceToken := range deviceTokens.DeviceTokens {
		if now.After(deviceToken.Expiry) {
			if err := cli.delete(resourceDeviceToken, deviceToken.ObjectMeta.Name); err != nil {
				cli.logger.Errorf("failed to delete device token: %v", err)
				delErr = fmt.Errorf("failed to delete device token: %v", err)
			}
			result.DeviceTokens++
		}
	}

	if delErr != nil {
		return result, delErr
	}
	return result, delErr
}

func (cli *client) CreateDeviceRequest(d storage.DeviceRequest) error {
	return cli.post(resourceDeviceRequest, cli.fromStorageDeviceRequest(d))
}

func (cli *client) GetDeviceRequest(userCode string) (storage.DeviceRequest, error) {
	var req DeviceRequest
	if err := cli.get(resourceDeviceRequest, strings.ToLower(userCode), &req); err != nil {
		return storage.DeviceRequest{}, err
	}
	return toStorageDeviceRequest(req), nil
}

func (cli *client) CreateDeviceToken(t storage.DeviceToken) error {
	return cli.post(resourceDeviceToken, cli.fromStorageDeviceToken(t))
}

func (cli *client) GetDeviceToken(deviceCode string) (storage.DeviceToken, error) {
	var token DeviceToken
	if err := cli.get(resourceDeviceToken, deviceCode, &token); err != nil {
		return storage.DeviceToken{}, err
	}
	return toStorageDeviceToken(token), nil
}

func (cli *client) getDeviceToken(deviceCode string) (t DeviceToken, err error) {
	err = cli.get(resourceDeviceToken, deviceCode, &t)
	return
}

func (cli *client) UpdateDeviceToken(deviceCode string, updater func(old storage.DeviceToken) (storage.DeviceToken, error)) error {
	return retryOnConflict(context.TODO(), func() error {
		r, err := cli.getDeviceToken(deviceCode)
		if err != nil {
			return err
		}
		updated, err := updater(toStorageDeviceToken(r))
		if err != nil {
			return err
		}
		updated.DeviceCode = deviceCode

		newToken := cli.fromStorageDeviceToken(updated)
		newToken.ObjectMeta = r.ObjectMeta
		return cli.put(resourceDeviceToken, r.ObjectMeta.Name, newToken)
	})
}

func isKubernetesAPIConflictError(err error) bool {
	if httpErr, ok := err.(httpError); ok {
		if httpErr.StatusCode() == http.StatusConflict {
			return true
		}
	}
	return false
}

func retryOnConflict(ctx context.Context, action func() error) error {
	policy := []int{10, 20, 100, 300, 600}

	attempts := 0
	getNextStep := func() time.Duration {
		step := policy[attempts]
		return time.Duration(step*5+rand.Intn(step)) * time.Microsecond
	}

	if err := action(); err == nil || !isKubernetesAPIConflictError(err) {
		return err
	}

	for {
		select {
		case <-time.After(getNextStep()):
			if err := action(); err == nil || !isKubernetesAPIConflictError(err) {
				return err
			}

			attempts++
			if attempts >= 4 {
				return errors.New("maximum timeout reached while retrying a conflicted request")
			}
		case <-ctx.Done():
			return errors.New("canceled")
		}
	}
}


text:
package networking;

import chord.RemoteNode;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class contains hte methods for receiving Files. The methods use
 * TCP for sending files and create new thread for this purpose.
 *@author Ntanasis Periklis and Chatzipetros Mike
 */
public class FileReceiver implements Runnable{

    private ServerSocket serversocket;
    private Socket socket;
    private String destination;
    private Thread runner;
    private int port;
    private boolean echo = true;
    private boolean status = false;
    private RemoteNode node = null;
    private final int BYTE_BUFFER_SIZE = 65536;
    private byte[] buffer;

    /**
     * Is invoked by start().
     */
    public void run()
    {
        int bytecounter = 0;
        try
        {
            buffer = new byte[BYTE_BUFFER_SIZE];
            serversocket = new ServerSocket(port);
            socket = serversocket.accept();
            FileOutputStream out = null;
            InputStream in = socket.getInputStream();
            try
            {
                out = new FileOutputStream(destination);
            }
            catch (FileNotFoundException ex)
            {
                boolean success = (new File("remote_files")).mkdir();
                if (success)
                {
                    basic.Logger.inf("\"remote_files\" folder was created!");
                    out = new FileOutputStream(destination);
                }

            }
            int currentbyte=0;
            long startTime = System.currentTimeMillis();
            while(true)
            {
                currentbyte = in.read(buffer);
                if(currentbyte == -1)
                {
                    status = true;
                    break;
                }
                bytecounter+=currentbyte;
                out.write(buffer,0,currentbyte);
            }
            long endTime = System.currentTimeMillis();
            if (echo)
            {
                basic.Logger.appendln("File was successfully received in "+((endTime-startTime)/1000D)+" sec:\n" +
                        "\tSize:\t"+bytecounter  +" bytes"+
                        "\n\tSender address:\t"+socket.getLocalSocketAddress());
                basic.Logger.inf("File was successfully received in: "+destination);
            }/*if(node!=null)
            {
            node.unsetPortBusy(port);
            }*/
            in.close();
            out.close();
            socket.close();
            serversocket.close();
        }
        catch (IOException ex)
        {
            Logger.getLogger(FileReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     *
     * @param port The port that we will use.
     * @param destination The destination folder.
     */
    public FileReceiver(int port,String destination) throws IOException
    {
        this.port = port;
        this.destination = destination;
    }

    /**
     *
     * @param port
     * @param destination
     * @param node The node that will receive the files.
     * @throws IOException
     */
    public FileReceiver(int port,String destination,RemoteNode node) throws IOException
    {
        this.node = node;
        this.port = port;
        this.destination = destination;
    }

    /**
     *
     * @param echo Prints extra messages.
     */
    public FileReceiver(int port,String destination,boolean echo)
    {
        this.port = port;
        this.destination = destination;
        this.echo = echo;
    }

    /**
     * Starts the execution of the thread.
     */
    public void start()
    {
        if (runner == null)
        {
            runner = new Thread(this);
            runner.setDaemon(true);
            runner.start();
        }
    }

    /**
     * Stops the execution of the thread.
     */
    public void stop()
    {
        try
        {
            socket.close();
        }
        catch (IOException ex)
        {
            Logger.getLogger(FileReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
        runner.interrupt();
        runner = null;
    }

    /**
     * Returns true if file is received.
     */
    public boolean getstatus()
    {
        return status;
    }

    /**
     * Return this thread in case of join.
     * @return This thread.
     */
    public Thread getThread()
    {
        return this.runner;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!--
  Copyright 2016 Google Inc. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<project>
  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>
  <version>1.0</version>

  <groupId>com.google.appengine.demos</groupId>
  <artifactId>appengine-try-java</artifactId>

  <!-- Parent POM defines common plugins and properties. -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.0.1</version>
   </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.7</maven.compiler.target>
    <maven.compiler.source>1.7</maven.compiler.source>

    <appengine.app.version>1</appengine.app.version>
    <appengine.target.version>1.9.54</appengine.target.version>
    <appengine-maven-plugin-version>1.3.1</appengine-maven-plugin-version>
  </properties>

  <dependencies>
    <!-- Compile/runtime dependencies -->
    <dependency>
      <groupId>com.google.appengine</groupId>
      <artifactId>appengine-api-1.0-sdk</artifactId>
      <version>${appengine.target.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- Test Dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.appengine</groupId>
      <artifactId>appengine-testing</artifactId>
      <version>${appengine.target.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.appengine</groupId>
      <artifactId>appengine-api-stubs</artifactId>
      <version>${appengine.target.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <outputDirectory>target/${project.artifactId}/WEB-INF/classes</outputDirectory>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <archiveClasses>true</archiveClasses>
          <webResources>
            <!-- in order to interpolate version from pom into appengine-web.xml -->
            <resource>
              <directory>${basedir}/src/main/webapp/WEB-INF</directory>
              <filtering>true</filtering>
              <targetPath>WEB-INF</targetPath>
            </resource>
          </webResources>
        </configuration>
      </plugin>
      <plugin>
        <groupId>com.google.cloud.tools</groupId>
        <artifactId>appengine-maven-plugin</artifactId>
        <version>${appengine-maven-plugin-version}</version>
      </plugin>
    </plugins>
  </build>
</project>


text:
<phpunit bootstrap="vendor/autoload.php"
         colors="true">
    <testsuites>
        <testsuite name="DeezerApi">
            <directory sufix="Test.php">tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>


text: from .annotator import *


text:
// Basic Forward
/*
function shade(env) {
    return diffuse(new Vec3(1), env.normal);
}
 */
function shade(env) {
    return Shade.diffuse(new Vec3(1), env.normal);
}


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner v2.4.1</title>

  <link rel="shortcut icon" type="image/png" href="/jasmine/lib/jasmine-2.4.1/jasmine_favicon.png">
  <link rel="stylesheet" href="/jasmine/lib/jasmine-2.4.1/jasmine.css">

  <script src="/jasmine/lib/jasmine-2.4.1/jasmine.js"></script>
  <script src="/jasmine/lib/jasmine-2.4.1/jasmine-html.js"></script>
  <script src="/jasmine/lib/jasmine-2.4.1/boot.js"></script>

  <script src="parameters.js"></script>

  <!-- include re-use-funciton files here... -->
  <script src="functions/Login.js"></script>
  <script src="functions/OData.js"></script>

  <!-- include spec files here... -->
  <script src="spec/Setup.js"></script>
  <script src="spec/Login.js"></script>
  <script src="spec/Organizer.js"></script>
  <script src="spec/CoOrganizer.js"></script>
  <script src="spec/Participant.js"></script>
  <script src="spec/CoOrganizerReadParticipants.js"></script>
  <script src="spec/ParticipantConfirmedForSmallEvent.js"></script>
  <script src="spec/CoOrganizerAgainForSmallEvent.js"></script>
  <script src="spec/Receptionist.js"></script>
  <script src="spec/Public.js"></script>
  <script src="spec/Teardown.js"></script>
</head>

<body>
</body>
</html>


text:
<eqm-container class="screen" [enabled]="enabled" [style.font-size.px]="fontSize" [style.width.px]="fontSize * 4" [style.height.px]="fontSize * 1.4">
  <eqm-label [fontSize]="fontSize">
    <ng-content></ng-content>
  </eqm-label>
</eqm-container>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2020 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/permission_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <ImageView
          android:id="@+id/tab_line"
          android:layout_width="match_parent"
          style="@style/TabBarShadow"
          android:importantForAccessibility="no"/>

      <org.chromium.ui.widget.ChromeImageView
          android:id="@+id/camera_icon"
          android:layout_marginTop="112dp"
          android:layout_gravity="center_horizontal"
          android:layout_width="150dp"
          android:layout_height="150dp"
          android:scaleType="center"
          android:importantForAccessibility="no"
          app:srcCompat="@drawable/camera_img" />

      <TextView
          android:id="@+id/qrcode_permission_image"
          android:layout_width="200dp"
          android:layout_height="wrap_content"
          android:layout_marginTop="40dp"
          android:drawablePadding="24dp"
          android:gravity="center_horizontal"
          android:textAppearance="@style/TextAppearance.TextLarge.Primary"
          android:lineHeight="20dp"
          android:layout_gravity="center_horizontal"
          android:text="@string/qr_code_open_settings_description"/>

      <org.chromium.ui.widget.ButtonCompat
          android:id="@+id/open_settings_button"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center_horizontal"
          android:layout_marginTop="30dp"
          android:text="@string/qr_code_open_settings_label"
          style="@style/TextButton"/>
  </LinearLayout>
</ScrollView>


text:
#pragma once

// Persistent storage keys
#define STORAGE_TIMER_START 2
#define STORAGE_SETTINGS 1
#define STORAGE_TEST 0


text:
FOUNDATION_EXPORT double Pods_SQProgressView_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SQProgressView_ExampleVersionString[];


text:
#include "XPathExpression.h"

#include "StringUtility.h"
#include "DeleteHelpers.h"
#include "XMLTool.h"

namespace XMLTool {
namespace XPath {

Expression::Expression( const MC2String& expression,
                        const MC2String& nspace ):
   m_expression( expression ),
   m_root( false ),
   m_attribute( false ),
   m_nbrHits( -1 ),
   m_backStr( XMLUtility::transcodetoucs( ".." ) ) {
   // determine if the expression is a root expression
   // by checking first character for '/'
   size_t pos = expression.find_first_not_of(' ');
   if ( pos != MC2String::npos ) {
      m_root = expression[ pos ] == '/';
   }
   // parse to MC2Strings and then make them XMLCh* string
   vector<MC2String> nodeNames;
   StringUtility::tokenListToVector( nodeNames,
                                     expression, '/' );
   // append namespace to each string
   if ( ! nspace.empty() ) {
      MC2String newNspace = nspace + ":";
      for ( uint32 nodeIt = 0; nodeIt < nodeNames.size(); ++nodeIt ) {
         // add namespace to all nodes except for attributes
         if ( ! nodeNames[ nodeIt ].empty() &&
              nodeNames[ nodeIt ][ 0 ] != '@' ) {
            nodeNames[ nodeIt ].insert( 0, newNspace );
         }
      }
   }

   if ( !nodeNames.empty() ) {
      // find multiplier
      size_t startPos = nodeNames.back().find_last_of('*');
      // if multiplier found then we take all node we can find
      if ( startPos != MC2String::npos ) {
         // strip the last * from the string
         nodeNames.back().erase( nodeNames.back().size() - 1 );
      } else {
         // only one hit is enough
         m_nbrHits = 1;
      }

      // determine if leaf node is an attribute
      // '@' indicates attribute
      m_attribute = ( nodeNames.back()[ 0 ] == '@' );
      if ( m_attribute ) {
         nodeNames.back().erase( 0, 1 );
      }

      // transcode to XMLCh, which is faster once we compare strings
      // in the evaluation

      m_nodeNames.resize( nodeNames.size() );
      for ( uint32 i = 0; i < m_nodeNames.size(); ++i ) {
         m_nodeNames[ i ] =  XMLUtility::transcodetoucs( nodeNames[ i ] );
      }
      // recreate original expression, if needed.
      if ( ! nspace.empty() ) {
         if ( m_root ) {
            m_expression = "/";
         } else {
            m_expression.clear();
         }

         // skip loop if only one item in names
         if ( nodeNames.size() > 1 ) {
            // add all names except the last one
            for ( uint32 i = 0; i < nodeNames.size() - 1; ++i ) {
               m_expression += nodeNames[ i ] + "/";
            }
         }

         // add the last expression
         if ( m_attribute ) {
            m_expression += "@";
         }

         m_expression += nodeNames.back();

         if ( m_nbrHits != 1 ) {
            m_expression += "*";
         }
      }
   }

}

Expression::~Expression() {
   for ( uint32 i = 0; i < m_nodeNames.size(); ++i ) {
      delete [] m_nodeNames[ i ];
   }

   delete [] m_backStr;
}

MC2String Expression::getExpression() const {
   return m_expression;
}

void Expression::evaluate( const DOMNode* parent,
                           const DOMNode* nodeIn,
                           vector<const DOMNode*>& nodes,
                           uint32 depth,
                           int32& nbrHits ) const {

   if ( m_attribute && depth + 1 == m_nodeNames.size() ) {
      // only search for attrib if we have a parent
      if ( parent ) {
         const DOMNode* attribNode =
            findAttribConst( parent,
                             XMLUtility::
                             transcodefrom( m_nodeNames[ depth ] ).c_str(),
                             false ); // ignore case

         if ( attribNode != NULL ) {
            nodes.push_back( attribNode );
         }
      }

      return;
   }

   if ( nodeIn == NULL || depth == m_nodeNames.size() ) {
      return;
   }

   // go back one step if ".."
   if ( XMLString::compareString( m_nodeNames[ depth ], m_backStr ) == 0 ) {
      evaluate( parent ? parent->getParentNode() : NULL,
                parent, nodes, depth + 1, nbrHits );
      return;
   }

   for ( const DOMNode* node = nodeIn;
         node != NULL;
         node = node->getNextSibling() ) {

      mc2dbg8 << node->getNodeName() << endl;

      // only interested in element nodes and
      // the nodes that matches name in the correct depth
      if ( node->getNodeType() != DOMNode::ELEMENT_NODE ||
           XMLString::compareIString( node->getNodeName(),
                                      m_nodeNames[ depth ] ) != 0 ) {
         continue;
      }

      // final depth? then add this node
      // and try to find some more hits
      if ( depth == m_nodeNames.size() - 1 ) {

         nodes.push_back( node );
         if ( nbrHits >= 0 ) {
            nbrHits--;
         }
         // we are done once we got all hits
         if ( nbrHits == 0 ) {
            return;
         }

      } else {
         // else go deeper in this node
         evaluate( node, node->getFirstChild(),
                   nodes, depth + 1, nbrHits );
      }
   }

}

vector<const DOMNode*> Expression::evaluate( const DOMNode* node ) const {
   vector<const DOMNode*> nodes;
   if ( m_root ) {
      // get first root node
      // not yet implemented
   }

   int32 nbrHits = m_nbrHits;
   evaluate( node->getParentNode(), node, nodes, 0, nbrHits );

   return nodes;
}

} // XPath

} // XMLTool


text:
<?php
if (defined('YII_DEBUG') && YII_DEBUG) {
    $params = array_merge(
        require(__DIR__ . '/../../config/params.php'),
        require(__DIR__ . '/params.php'),
        require(__DIR__ . '/../../config/params-local.php'),
        require(__DIR__ . '/params-local.php')
    );
} else {
    $params = array_merge(
        require(__DIR__ . '/../../config/params.php'),
        require(__DIR__ . '/params.php')
    );
}

return [
    'id' => 'console',
    'basePath' => dirname(__DIR__),
    'runtimePath' => BASE_PATH . '/runtime/console',
    'controllerNamespace' => 'console\controllers',
    'controllerMap' => [
        'migrate' => [
            'class' => \console\migrate\MigrateBase::class,
        ],
    ],
    'components' => [],
    'params' => $params,
];


text:
cover: false
chapter: What's a
layout: slide
tags: ['branch-np']
---


text: This is an example of mixed HTML templates using both pure .html files, .tpl.inc files ...


text:
/**
*============================================================================
*  Copyright The Ohio State University Research Foundation, The University of Chicago -
*	Argonne National Laboratory, Emory University, SemanticBits LLC, and
*	Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
/**
 *
 */
package org.cagrid.installer.steps.options;

/**
 * @author Joshua Phillips
 *
 */
public class FilePropertyConfigurationOption extends
		TextPropertyConfigurationOption {

	private String[] extensions = new String[0];
	private String browseLabel;
	private boolean directoriesOnly;

	public boolean isDirectoriesOnly() {
		return directoriesOnly;
	}

	public void setDirectoriesOnly(boolean directoriesOnly) {
		this.directoriesOnly = directoriesOnly;
	}

	/**
	 *
	 */
	public FilePropertyConfigurationOption() {

	}

	/**
	 * @param name
	 * @param description
	 * @param defaultValue
	 */
	public FilePropertyConfigurationOption(String name, String description,
			String defaultValue) {
		this(name, description, defaultValue, false);

	}

	/**
	 * @param name
	 * @param description
	 * @param defaultValue
	 * @param required
	 */
	public FilePropertyConfigurationOption(String name, String description,
			String defaultValue, boolean required) {
		super(name, description, defaultValue, required);

	}

	public String[] getExtensions() {
		return extensions;
	}

	public void setExtensions(String[] extensions) {
		this.extensions = extensions;
	}

	public String getBrowseLabel() {
		return browseLabel;
	}

	public void setBrowseLabel(String browseLabel) {
		this.browseLabel = browseLabel;
	}

}


text:
package co.cask.cdap.data.stream;

import co.cask.cdap.common.io.BinaryDecoder;
import co.cask.cdap.common.io.ByteBuffers;
import co.cask.cdap.common.io.Decoder;
import co.cask.cdap.common.io.SeekableInputStream;
import co.cask.cdap.common.stream.StreamEventDataCodec;
import co.cask.cdap.data.file.ReadFilter;
import co.cask.common.io.ByteBufferInputStream;

import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import javax.annotation.concurrent.NotThreadSafe;

/**
 * A buffer for holding encoded stream events. It is used by {@link StreamDataFileReader} for holding
 * encoded stream events in each data block.
 */
@NotThreadSafe
final class StreamEventBuffer {

  private final ByteBufferInputStream bufferInput;
  private final Decoder decoder;

  private ByteBuffer buffer;
  private long basePosition;

  StreamEventBuffer() {
    this.buffer = ByteBuffers.EMPTY_BUFFER;
    this.bufferInput = new ByteBufferInputStream(buffer);
    this.decoder = new BinaryDecoder(bufferInput);
    this.basePosition = -1L;
  }

  /**
   * Fills the internal buffer by reading from the given input stream.
   *
   * @param input input stream to read from
   * @param size number of bytes to read
   * @throws IOException if failed to read from the stream
   * @throws EOFException if failed to read the given number of bytes from the input
   */
  void fillBuffer(SeekableInputStream input, int size) throws IOException {
    buffer.clear();
    buffer = ensureCapacity(buffer, size);

    try {
      basePosition = input.getPos();
      int bytesRead = 0;
      while (bytesRead != size) {
        int len = input.read(buffer.array(), bytesRead, size - bytesRead);
        if (len < 0) {
          throw new EOFException("Expected to read " + size + ", but only " + bytesRead + " was read");
        }
        bytesRead += len;
      }
      buffer.limit(size);
      bufferInput.reset(buffer);
    } catch (IOException e) {
      // Make the buffer has nothing to read
      buffer.position(buffer.limit());
      basePosition = -1L;
      throw e;
    }
  }

  /**
   * Returns {@code true} if there are events in the buffer, {@code false} otherwise.
   */
  boolean hasEvent() {
    return buffer.hasRemaining();
  }

  /**
   * Returns the position in the stream that this buffer is currently at or {@code -1} if nothing has been
   * read from the stream.
   */
  long getPosition() {
    return basePosition >= 0 ? basePosition + buffer.position() : -1L;
  }

  /**
   * Returns the position in the stream that represents the end of this buffer or {@code -1} if nothing has
   * been read from the stream.
   */
  long getEndPosition() {
    return basePosition >= 0 ? basePosition + buffer.limit() : -1L;
  }

  /**
   * Decodes a stream event from the buffer.
   *
   * @param timestamp timestamp of the {@link PositionStreamEvent} created
   * @param defaultHeaders the set of headers that will used as the default for the stream event
   * @param filter filter to apply to decide reading or skipping event
   * @return A {@link PositionStreamEvent} if the filter accept it, or {@code null} if rejected by the filter
   * @throws IOException if fails to decode event from the buffer
   */
  PositionStreamEvent nextEvent(long timestamp,
                                Map<String, String> defaultHeaders, ReadFilter filter) throws IOException {
    if (!hasEvent()) {
      throw new IOException("No more event in the buffer");
    }

    long eventPos = basePosition + buffer.position();
    if (filter.acceptOffset(eventPos)) {
      return new PositionStreamEvent(StreamEventDataCodec.decode(decoder, defaultHeaders), timestamp, eventPos);
    }
    StreamEventDataCodec.skip(decoder);
    return null;
  }

  /**
   * Ensures that the given {@link ByteBuffer} is of sufficient size.
   *
   * @param buffer The buffer to check for capacity
   * @param size Capacity needed
   * @return The given buffer if it is of sufficient size; otherwise, a new buffer of the given size will be returned.
   */
  private ByteBuffer ensureCapacity(ByteBuffer buffer, int size) {
    return (buffer.remaining() >= size) ? buffer : ByteBuffer.allocate(size);
  }
}


text:
<!DOCTYPE html>

    <title>dc.js - Ordinal Line Transitions</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../css/dc.css"/>

    <button class="btn" onclick="transitionTest.stop()">stop</button>
    <button class="btn" onclick="button1()">left</button>
    <button class="btn" onclick="button2()">right</button>
    <button class="btn" onclick="button3()">middle</button>
    <button class="btn" onclick="button4()">reverse</button>
    <button class="btn" onclick="button5()">backward</button>


text:
import { chai } from 'meteor/practicalmeteor:chai';
import chaiAsPromised from 'chai-as-promised';
import { createDummyUser, userUpdateFieldSucceeds, userUpdateFieldFails, catchGraphQLErrors, assertIsPermissionsFlavoredError } from '../../../testing/utils'

chai.should();
chai.use(chaiAsPromised);

describe('updateUser – ', async () => {
  let graphQLerrors = catchGraphQLErrors(beforeEach, afterEach);
  it("fails when user updates their displayName", async () => {
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:user,
      document:user,
      fieldName:'displayName',
      collectionType:'User',
    })
    assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
  it("fails when user updates their createdAt", async () => {
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:user,
      document:user,
      fieldName:'createdAt',
      collectionType:'User',
      newValue: new Date(),
    })
    // FIXME: This gives an "Unknown field" error instead of a permissions error
    graphQLerrors.getErrors(); // Ignore the wrong-type error
    //assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
  it("fails when sunshineUser updates a user's createdAt", async () => {
    const sunshineUser = await createDummyUser({groups:['sunshineRegiment']})
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:sunshineUser,
      document:user,
      fieldName:'createdAt',
      collectionType:'User',
      newValue: new Date(),
    })
    // FIXME: This gives an "Unknown field" error instead of a permissions error
    graphQLerrors.getErrors(); // Ignore the wrong-type error
    //assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
  it("fails when user updates their nullifyVotes", async () => {
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:user,
      document:user,
      fieldName:'nullifyVotes',
      collectionType:'User',
      newValue: false,
    })
    assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
  it("fails when user updates their voteBanned", async () => {
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:user,
      document:user,
      fieldName:'voteBanned',
      newValue: true,
      collectionType:'User',
    })
    assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
  it("fails when user updates their deleteContent", async () => {
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:user,
      document:user,
      fieldName:'deleteContent',
      newValue: true,
      collectionType:'User',
    })
    assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
  it("fails when user updates their banned", async () => {
    const user = await createDummyUser()
    await userUpdateFieldFails({
      user:user,
      document:user,
      fieldName: 'banned',
      newValue: new Date(),
      collectionType:'User',
    })
    assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
  });
})

describe('updateUser succeeds – ', async () => {
  it("succeeds when user updates their bio", async () => {
    const user = await createDummyUser()
    return userUpdateFieldSucceeds({
      user: user,
      document: user,
      fieldName: 'bio',
      collectionType: 'User',
    })
  });
  it("succeeds when sunshineRegiment user updates their displayName", async () => {
    const user = await createDummyUser({groups:['sunshineRegiment']})
    return userUpdateFieldSucceeds({
      user: user,
      document: user,
      fieldName: 'displayName',
      collectionType: 'User',
    })
  });
  it("succeeds when sunshineRegiment user updates their nullifyVotes", async () => {
    const user = await createDummyUser({groups:['sunshineRegiment']})
    return userUpdateFieldSucceeds({
      user:user,
      document:user,
      fieldName:'nullifyVotes',
      collectionType:'User',
      newValue: true,
    })
  });
  it("succeeds when user updates their voteBanned", async () => {
    const user = await createDummyUser({groups:['sunshineRegiment']})
    return userUpdateFieldSucceeds({
      user:user,
      document:user,
      fieldName:'voteBanned',
      collectionType:'User',
      newValue: true,
    })
  });
  it("succeeds when user updates their deleteContent", async () => {
    const user = await createDummyUser({groups:['sunshineRegiment']})
    return userUpdateFieldSucceeds({
      user:user,
      document:user,
      fieldName:'deleteContent',
      collectionType:'User',
      newValue: true,
    })
  });
})


text:
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    std::vector<QLabel*> *imageVec;
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_selectImageButton_clicked();
    void goFeatureWindow();
    void goSobelWindow();

private:
    Ui::MainWindow *ui;
    FeatureWindow *_fWindow;
    void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE;
    void createActions();
    void createMenus();
    QMenu *fileMenu;
    QAction *featureAction, *sobelAction;
};

#endif // MAINWINDOW_H


text:
CREATE PROCEDURE [sp_del_Receive] (
  @ReceiveID int,
  @PartitionID int
)
AS
  DELETE FROM [dbo].[Receive]
  WHERE
    ([ReceiveID] = @ReceiveID) AND
    ([PartitionID] = @PartitionID)


text:
This site documents reading and learning notes.

### Search

    <gcse:searchbox-only></gcse:searchbox-only>

### TOC

See [Table of Contents](toc.md).

### Books and Materials

See [Books and Materials](books.md).

### Roadmap

See [Roadmap](roadmap/index.md).

### Topics

See [Topics](topics/index.md).


text:
layout: page
permalink: /http/
title: HTTP
---

    {% for post in site.categories.http %}

        {% include post-cards.html %}

    {% endfor %}


text:
package jadx.core.utils;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;

import org.jetbrains.annotations.Nullable;

import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.attributes.nodes.PhiListAttr;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.utils.exceptions.JadxRuntimeException;

public class BlockUtils {

	private BlockUtils() {
	}

	public static BlockNode getBlockByOffset(int offset, Iterable<BlockNode> casesBlocks) {
		for (BlockNode block : casesBlocks) {
			if (block.getStartOffset() == offset) {
				return block;
			}
		}
		throw new JadxRuntimeException("Can't find block by offset: "
				+ InsnUtils.formatOffset(offset)
				+ " in list " + casesBlocks);
	}

	public static BlockNode selectOther(BlockNode node, List<BlockNode> blocks) {
		List<BlockNode> list = blocks;
		if (list.size() > 2) {
			list = cleanBlockList(list);
		}
		if (list.size() != 2) {
			throw new JadxRuntimeException("Incorrect nodes count for selectOther: " + node + " in " + list);
		}
		BlockNode first = list.get(0);
		if (first != node) {
			return first;
		} else {
			return list.get(1);
		}
	}

	public static BlockNode selectOtherSafe(BlockNode node, List<BlockNode> blocks) {
		int size = blocks.size();
		if (size == 1) {
			BlockNode first = blocks.get(0);
			return first != node ? first : null;
		}
		if (size == 2) {
			BlockNode first = blocks.get(0);
			return first != node ? first : blocks.get(1);
		}
		return null;
	}

	public static boolean isExceptionHandlerPath(BlockNode b) {
		if (b.contains(AType.EXC_HANDLER)
				|| b.contains(AFlag.EXC_BOTTOM_SPLITTER)
				|| b.contains(AFlag.REMOVE)) {
			return true;
		}
		if (b.contains(AFlag.SYNTHETIC)) {
			List<BlockNode> s = b.getSuccessors();
			return s.size() == 1 && s.get(0).contains(AType.EXC_HANDLER);
		}
		return false;
	}

	/**
	 * Remove exception handlers from block nodes list
	 */
	private static List<BlockNode> cleanBlockList(List<BlockNode> list) {
		List<BlockNode> ret = new ArrayList<>(list.size());
		for (BlockNode block : list) {
			if (!isExceptionHandlerPath(block)) {
				ret.add(block);
			}
		}
		return ret;
	}

	/**
	 * Remove exception handlers from block nodes bitset
	 */
	public static void cleanBitSet(MethodNode mth, BitSet bs) {
		for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
			BlockNode block = mth.getBasicBlocks().get(i);
			if (isExceptionHandlerPath(block)) {
				bs.clear(i);
			}
		}
	}

	public static boolean isBackEdge(BlockNode from, BlockNode to) {
		if (to == null) {
			return false;
		}
		if (from.getCleanSuccessors().contains(to)) {
			return false; // already checked
		}
		return from.getSuccessors().contains(to);
	}

	public static boolean isFollowBackEdge(BlockNode block) {
		if (block == null) {
			return false;
		}
		if (block.contains(AFlag.LOOP_START)) {
			List<BlockNode> predecessors = block.getPredecessors();
			if (predecessors.size() == 1) {
				BlockNode loopEndBlock = predecessors.get(0);
				if (loopEndBlock.contains(AFlag.LOOP_END)) {
					List<LoopInfo> loops = loopEndBlock.getAll(AType.LOOP);
					for (LoopInfo loop : loops) {
						if (loop.getStart().equals(block) && loop.getEnd().equals(loopEndBlock)) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	/**
	 * Check if instruction contains in block (use == for comparison, not equals)
	 */
	public static boolean blockContains(BlockNode block, InsnNode insn) {
		for (InsnNode bi : block.getInstructions()) {
			if (bi == insn) {
				return true;
			}
		}
		return false;
	}

	public static boolean checkFirstInsn(IBlock block, Predicate<InsnNode> predicate) {
		InsnNode insn = getFirstInsn(block);
		return insn != null && predicate.test(insn);
	}

	public static boolean checkLastInsnType(IBlock block, InsnType expectedType) {
		InsnNode insn = getLastInsn(block);
		return insn != null && insn.getType() == expectedType;
	}

	public static InsnNode getLastInsnWithType(IBlock block, InsnType expectedType) {
		InsnNode insn = getLastInsn(block);
		if (insn != null && insn.getType() == expectedType) {
			return insn;
		}
		return null;
	}

	public static int getFirstSourceLine(IBlock block) {
		for (InsnNode insn : block.getInstructions()) {
			int line = insn.getSourceLine();
			if (line != 0) {
				return line;
			}
		}
		return 0;
	}

	@Nullable
	public static InsnNode getFirstInsn(@Nullable IBlock block) {
		if (block == null) {
			return null;
		}
		List<InsnNode> insns = block.getInstructions();
		if (insns.isEmpty()) {
			return null;
		}
		return insns.get(0);
	}

	@Nullable
	public static InsnNode getLastInsn(@Nullable IBlock block) {
		if (block == null) {
			return null;
		}
		List<InsnNode> insns = block.getInstructions();
		if (insns.isEmpty()) {
			return null;
		}
		return insns.get(insns.size() - 1);
	}

	public static boolean isExitBlock(MethodNode mth, BlockNode block) {
		if (block == mth.getExitBlock()) {
			return true;
		}
		return isExitBlock(block);
	}

	public static boolean isExitBlock(BlockNode block) {
		List<BlockNode> successors = block.getSuccessors();
		if (successors.isEmpty()) {
			return true;
		}
		if (successors.size() == 1) {
			BlockNode next = successors.get(0);
			return next.getSuccessors().isEmpty();
		}
		return false;
	}

	public static boolean containsExitInsn(IBlock block) {
		InsnNode lastInsn = BlockUtils.getLastInsn(block);
		if (lastInsn == null) {
			return false;
		}
		InsnType type = lastInsn.getType();
		return type == InsnType.RETURN
				|| type == InsnType.THROW
				|| type == InsnType.BREAK
				|| type == InsnType.CONTINUE;
	}

	@Nullable
	public static BlockNode getBlockByInsn(MethodNode mth, @Nullable InsnNode insn) {
		if (insn == null) {
			return null;
		}
		if (insn instanceof PhiInsn) {
			return searchBlockWithPhi(mth, (PhiInsn) insn);
		}
		if (insn.contains(AFlag.WRAPPED)) {
			return getBlockByWrappedInsn(mth, insn);
		}
		for (BlockNode bn : mth.getBasicBlocks()) {
			if (blockContains(bn, insn)) {
				return bn;
			}
		}
		return null;
	}

	public static BlockNode searchBlockWithPhi(MethodNode mth, PhiInsn insn) {
		for (BlockNode block : mth.getBasicBlocks()) {
			PhiListAttr phiListAttr = block.get(AType.PHI_LIST);
			if (phiListAttr != null) {
				for (PhiInsn phiInsn : phiListAttr.getList()) {
					if (phiInsn == insn) {
						return block;
					}
				}
			}
		}
		return null;
	}

	private static BlockNode getBlockByWrappedInsn(MethodNode mth, InsnNode insn) {
		for (BlockNode bn : mth.getBasicBlocks()) {
			for (InsnNode bi : bn.getInstructions()) {
				if (bi == insn || foundWrappedInsn(bi, insn) != null) {
					return bn;
				}
			}
		}
		return null;
	}

	public static InsnNode searchInsnParent(MethodNode mth, InsnNode insn) {
		InsnArg insnArg = searchWrappedInsnParent(mth, insn);
		if (insnArg == null) {
			return null;
		}
		return insnArg.getParentInsn();
	}

	public static InsnArg searchWrappedInsnParent(MethodNode mth, InsnNode insn) {
		if (!insn.contains(AFlag.WRAPPED)) {
			return null;
		}
		for (BlockNode bn : mth.getBasicBlocks()) {
			for (InsnNode bi : bn.getInstructions()) {
				InsnArg res = foundWrappedInsn(bi, insn);
				if (res != null) {
					return res;
				}
			}
		}
		return null;
	}

	private static InsnArg foundWrappedInsn(InsnNode container, InsnNode insn) {
		for (InsnArg arg : container.getArguments()) {
			if (arg.isInsnWrap()) {
				InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
				if (wrapInsn == insn) {
					return arg;
				}
				InsnArg res = foundWrappedInsn(wrapInsn, insn);
				if (res != null) {
					return res;
				}
			}
		}
		if (container instanceof TernaryInsn) {
			return foundWrappedInsnInCondition(((TernaryInsn) container).getCondition(), insn);
		}
		return null;
	}

	private static InsnArg foundWrappedInsnInCondition(IfCondition cond, InsnNode insn) {
		if (cond.isCompare()) {
			IfNode cmpInsn = cond.getCompare().getInsn();
			return foundWrappedInsn(cmpInsn, insn);
		}
		for (IfCondition nestedCond : cond.getArgs()) {
			InsnArg res = foundWrappedInsnInCondition(nestedCond, insn);
			if (res != null) {
				return res;
			}
		}
		return null;
	}

	public static BitSet newBlocksBitSet(MethodNode mth) {
		return new BitSet(mth.getBasicBlocks().size());
	}

	public static BitSet copyBlocksBitSet(MethodNode mth, BitSet bitSet) {
		BitSet copy = new BitSet(mth.getBasicBlocks().size());
		if (!bitSet.isEmpty()) {
			copy.or(bitSet);
		}
		return copy;
	}

	public static BitSet blocksToBitSet(MethodNode mth, Collection<BlockNode> blocks) {
		BitSet bs = newBlocksBitSet(mth);
		for (BlockNode block : blocks) {
			bs.set(block.getId());
		}
		return bs;
	}

	@Nullable
	public static BlockNode bitSetToOneBlock(MethodNode mth, BitSet bs) {
		if (bs == null || bs.cardinality() != 1) {
			return null;
		}
		return mth.getBasicBlocks().get(bs.nextSetBit(0));
	}

	public static List<BlockNode> bitSetToBlocks(MethodNode mth, BitSet bs) {
		if (bs == null || bs == EmptyBitSet.EMPTY) {
			return Collections.emptyList();
		}
		int size = bs.cardinality();
		if (size == 0) {
			return Collections.emptyList();
		}
		List<BlockNode> blocks = new ArrayList<>(size);
		for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
			BlockNode block = mth.getBasicBlocks().get(i);
			blocks.add(block);
		}
		return blocks;
	}

	public static void forEachBlockFromBitSet(MethodNode mth, BitSet bs, Consumer<BlockNode> consumer) {
		if (bs == null || bs == EmptyBitSet.EMPTY || bs.isEmpty()) {
			return;
		}
		List<BlockNode> blocks = mth.getBasicBlocks();
		for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
			consumer.accept(blocks.get(i));
		}
	}

	/**
	 * Return first successor which not exception handler and not follow loop back edge
	 */
	@Nullable
	public static BlockNode getNextBlock(BlockNode block) {
		List<BlockNode> s = block.getCleanSuccessors();
		return s.isEmpty() ? null : s.get(0);
	}

	/**
	 * Return successor on path to 'pathEnd' block
	 */
	public static BlockNode getNextBlockToPath(BlockNode block, BlockNode pathEnd) {
		List<BlockNode> successors = block.getCleanSuccessors();
		if (successors.contains(pathEnd)) {
			return pathEnd;
		}
		Set<BlockNode> path = getAllPathsBlocks(block, pathEnd);
		for (BlockNode s : successors) {
			if (path.contains(s)) {
				return s;
			}
		}
		return null;
	}

	/**
	 * Visit blocks on any path from start to end.
	 * Only one path will be visited!
	 */
	public static boolean visitBlocksOnPath(MethodNode mth, BlockNode start, BlockNode end, Consumer<BlockNode> visitor) {
		visitor.accept(start);
		if (start == end) {
			return true;
		}
		if (start.getCleanSuccessors().contains(end)) {
			visitor.accept(end);
			return true;
		}
		// DFS on clean successors
		BitSet visited = newBlocksBitSet(mth);
		Deque<BlockNode> queue = new ArrayDeque<>();
		queue.addLast(start);
		while (true) {
			BlockNode current = queue.peekLast();
			if (current == null) {
				return false;
			}
			boolean added = false;
			for (BlockNode next : current.getCleanSuccessors()) {
				if (next == end) {
					queue.removeFirst(); // start already visited
					queue.addLast(next);
					queue.forEach(visitor);
					return true;
				}
				int id = next.getId();
				if (!visited.get(id)) {
					visited.set(id);
					queue.addLast(next);
					added = true;
					break;
				}
			}
			if (!added) {
				queue.pollLast();
				if (queue.isEmpty()) {
					return false;
				}
			}
		}
	}

	public static void dfsVisit(MethodNode mth, Consumer<BlockNode> visitor) {
		BitSet visited = newBlocksBitSet(mth);
		Deque<BlockNode> queue = new ArrayDeque<>();
		BlockNode enterBlock = mth.getEnterBlock();
		queue.addLast(enterBlock);
		visited.set(mth.getEnterBlock().getId());
		while (true) {
			BlockNode current = queue.pollLast();
			if (current == null) {
				return;
			}
			visitor.accept(current);
			List<BlockNode> successors = current.getSuccessors();
			int count = successors.size();
			for (int i = count - 1; i >= 0; i--) { // to preserve order in queue
				BlockNode next = successors.get(i);
				int nextId = next.getId();
				if (!visited.get(nextId)) {
					queue.addLast(next);
					visited.set(nextId);
				}
			}
		}
	}

	public static List<BlockNode> collectPredecessors(MethodNode mth, BlockNode start, Collection<BlockNode> stopBlocks) {
		BitSet bs = newBlocksBitSet(mth);
		if (!stopBlocks.isEmpty()) {
			bs.or(blocksToBitSet(mth, stopBlocks));
		}
		List<BlockNode> list = new ArrayList<>();
		traversePredecessors(start, bs, list::add);
		return list;
	}

	/**
	 * Up BFS
	 */
	private static void traversePredecessors(BlockNode start, BitSet visited, Consumer<BlockNode> visitor) {
		Queue<BlockNode> queue = new ArrayDeque<>();
		queue.add(start);
		while (true) {
			BlockNode current = queue.poll();
			if (current == null) {
				return;
			}
			visitor.accept(current);
			for (BlockNode next : current.getPredecessors()) {
				int id = next.getId();
				if (!visited.get(id)) {
					visited.set(id);
					queue.add(next);
				}
			}
		}
	}

	/**
	 * Collect blocks from all possible execution paths from 'start' to 'end'
	 */
	public static Set<BlockNode> getAllPathsBlocks(BlockNode start, BlockNode end) {
		Set<BlockNode> set = new HashSet<>();
		set.add(start);
		if (start != end) {
			addPredecessors(set, end, start);
		}
		return set;
	}

	private static void addPredecessors(Set<BlockNode> set, BlockNode from, BlockNode until) {
		set.add(from);
		for (BlockNode pred : from.getPredecessors()) {
			if (pred != until && !set.contains(pred)) {
				addPredecessors(set, pred, until);
			}
		}
	}

	private static boolean traverseSuccessorsUntil(BlockNode from, BlockNode until, BitSet visited, boolean clean) {
		List<BlockNode> nodes = clean ? from.getCleanSuccessors() : from.getSuccessors();
		for (BlockNode s : nodes) {
			if (s == until) {
				return true;
			}
			int id = s.getId();
			if (!visited.get(id)) {
				visited.set(id);
				if (until.isDominator(s)) {
					return true;
				}
				if (traverseSuccessorsUntil(s, until, visited, clean)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Search at least one path from startBlocks to end
	 */
	public static boolean atLeastOnePathExists(Collection<BlockNode> startBlocks, BlockNode end) {
		for (BlockNode startBlock : startBlocks) {
			if (isPathExists(startBlock, end)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Check if exist path from every startBlocks to end
	 */
	public static boolean isAllPathExists(Collection<BlockNode> startBlocks, BlockNode end) {
		for (BlockNode startBlock : startBlocks) {
			if (!isPathExists(startBlock, end)) {
				return false;
			}
		}
		return true;
	}

	public static boolean isPathExists(BlockNode start, BlockNode end) {
		if (start == end
				|| end.isDominator(start)
				|| start.getCleanSuccessors().contains(end)) {
			return true;
		}
		if (start.getPredecessors().contains(end)) {
			return false;
		}
		return traverseSuccessorsUntil(start, end, new BitSet(), true);
	}

	public static boolean isAnyPathExists(BlockNode start, BlockNode end) {
		if (start == end
				|| end.isDominator(start)
				|| start.getSuccessors().contains(end)) {
			return true;
		}
		if (start.getPredecessors().contains(end)) {
			return false;
		}
		return traverseSuccessorsUntil(start, end, new BitSet(), false);
	}

	public static BlockNode getTopBlock(List<BlockNode> blocks) {
		if (blocks.size() == 1) {
			return blocks.get(0);
		}
		for (BlockNode from : blocks) {
			boolean top = true;
			for (BlockNode to : blocks) {
				if (from != to && !isAnyPathExists(from, to)) {
					top = false;
					break;
				}
			}
			if (top) {
				return from;
			}
		}
		return null;
	}

	/**
	 * Search last block in control flow graph from input set.
	 */
	@Nullable
	public static BlockNode getBottomBlock(List<BlockNode> blocks) {
		if (blocks.size() == 1) {
			return blocks.get(0);
		}
		for (BlockNode bottomCandidate : blocks) {
			boolean bottom = true;
			for (BlockNode from : blocks) {
				if (bottomCandidate != from && !isAnyPathExists(from, bottomCandidate)) {
					bottom = false;
					break;
				}
			}
			if (bottom) {
				return bottomCandidate;
			}
		}
		return null;
	}

	public static boolean isOnlyOnePathExists(BlockNode start, BlockNode end) {
		if (start == end) {
			return true;
		}
		if (!end.isDominator(start)) {
			return false;
		}
		BlockNode currentNode = start;
		while (currentNode.getCleanSuccessors().size() == 1) {
			currentNode = currentNode.getCleanSuccessors().get(0);
			if (currentNode == end) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Search for first node which not dominated by dom, starting from start
	 */
	public static BlockNode traverseWhileDominates(BlockNode dom, BlockNode start) {
		for (BlockNode node : start.getCleanSuccessors()) {
			if (!node.isDominator(dom)) {
				return node;
			} else {
				BlockNode out = traverseWhileDominates(dom, node);
				if (out != null) {
					return out;
				}
			}
		}
		return null;
	}

	/**
	 * Search the lowest common ancestor in dominator tree for input set.
	 */
	@Nullable
	public static BlockNode getCommonDominator(MethodNode mth, List<BlockNode> blocks) {
		BitSet doms = newBlocksBitSet(mth);
		// collect all dominators from input set
		doms.set(0, mth.getBasicBlocks().size());
		blocks.forEach(b -> doms.and(b.getDoms()));
		// exclude all dominators of immediate dominator (including self)
		BitSet combine = newBlocksBitSet(mth);
		combine.or(doms);
		forEachBlockFromBitSet(mth, doms, block -> {
			BlockNode idom = block.getIDom();
			if (idom != null) {
				combine.andNot(idom.getDoms());
				combine.clear(idom.getId());
			}
		});
		return bitSetToOneBlock(mth, combine);
	}

	/**
	 * Return common cross block for input set.
	 *
	 * @return null if cross is a method exit block.
	 */
	@Nullable
	public static BlockNode getPathCross(MethodNode mth, Collection<BlockNode> blocks) {
		BitSet domFrontBS = newBlocksBitSet(mth);
		boolean first = true;
		for (BlockNode b : blocks) {
			if (first) {
				domFrontBS.or(b.getDomFrontier());
				first = false;
			} else {
				domFrontBS.and(b.getDomFrontier());
			}
		}
		domFrontBS.clear(mth.getExitBlock().getId());
		if (domFrontBS.isEmpty()) {
			return null;
		}
		BlockNode oneBlock = bitSetToOneBlock(mth, domFrontBS);
		if (oneBlock != null) {
			return oneBlock;
		}
		BitSet excluded = newBlocksBitSet(mth);
		// exclude method exit and loop start blocks
		excluded.set(mth.getExitBlock().getId());
		// exclude loop start blocks
		mth.getLoops().forEach(l -> excluded.set(l.getStart().getId()));
		if (!mth.isNoExceptionHandlers()) {
			// exclude exception handlers paths
			mth.getExceptionHandlers().forEach(h -> mergeExcHandlerDomFrontier(mth, h, excluded));
		}
		domFrontBS.andNot(excluded);
		oneBlock = bitSetToOneBlock(mth, domFrontBS);
		if (oneBlock != null) {
			return oneBlock;
		}
		BitSet combinedDF = newBlocksBitSet(mth);
		int k = mth.getBasicBlocks().size();
		while (true) {
			// collect dom frontier blocks from current set until only one block left
			forEachBlockFromBitSet(mth, domFrontBS, block -> {
				BitSet domFrontier = block.getDomFrontier();
				if (!domFrontier.isEmpty()) {
					combinedDF.or(domFrontier);
					combinedDF.clear(block.getId());
				}
			});
			combinedDF.andNot(excluded);
			int cardinality = combinedDF.cardinality();
			if (cardinality == 1) {
				return bitSetToOneBlock(mth, combinedDF);
			}
			if (cardinality == 0) {
				return null;
			}
			if (k-- < 0) {
				mth.addWarnComment("Path cross not found for " + blocks + ", limit reached: " + mth.getBasicBlocks().size());
				return null;
			}
			// replace domFrontBS with combinedDF
			domFrontBS.clear();
			domFrontBS.or(combinedDF);
			combinedDF.clear();
		}
	}

	private static void mergeExcHandlerDomFrontier(MethodNode mth, ExceptionHandler handler, BitSet set) {
		BlockNode handlerBlock = handler.getHandlerBlock();
		if (handlerBlock == null) {
			mth.addDebugComment("Null handler block in: " + handler);
			return;
		}
		BitSet domFrontier = handlerBlock.getDomFrontier();
		if (domFrontier == null) {
			mth.addDebugComment("Null dom frontier in handler: " + handler);
			return;
		}
		set.or(domFrontier);
	}

	public static BlockNode getPathCross(MethodNode mth, BlockNode b1, BlockNode b2) {
		if (b1 == b2) {
			return b1;
		}
		if (b1 == null || b2 == null) {
			return null;
		}
		return getPathCross(mth, Arrays.asList(b1, b2));
	}

	/**
	 * Collect all block dominated by 'dominator', starting from 'start'
	 */
	public static List<BlockNode> collectBlocksDominatedBy(MethodNode mth, BlockNode dominator, BlockNode start) {
		List<BlockNode> result = new ArrayList<>();
		collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), false);
		return result;
	}

	/**
	 * Collect all block dominated by 'dominator', starting from 'start', including exception handlers
	 */
	public static Set<BlockNode> collectBlocksDominatedByWithExcHandlers(MethodNode mth, BlockNode dominator, BlockNode start) {
		Set<BlockNode> result = new LinkedHashSet<>();
		collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), true);
		return result;
	}

	private static void collectWhileDominates(BlockNode dominator, BlockNode child, Collection<BlockNode> result,
			BitSet visited, boolean includeExcHandlers) {
		if (visited.get(child.getId())) {
			return;
		}
		visited.set(child.getId());
		List<BlockNode> successors = includeExcHandlers ? child.getSuccessors() : child.getCleanSuccessors();
		for (BlockNode node : successors) {
			if (node.isDominator(dominator)) {
				result.add(node);
				collectWhileDominates(dominator, node, result, visited, includeExcHandlers);
			}
		}
	}

	/**
	 * Visit blocks on path without branching or merging paths.
	 */
	public static void visitSinglePath(BlockNode startBlock, Consumer<BlockNode> visitor) {
		if (startBlock == null) {
			return;
		}
		visitor.accept(startBlock);
		BlockNode next = getNextSinglePathBlock(startBlock);
		while (next != null) {
			visitor.accept(next);
			next = getNextSinglePathBlock(next);
		}
	}

	@Nullable
	public static BlockNode getNextSinglePathBlock(BlockNode block) {
		if (block == null || block.getPredecessors().size() > 1) {
			return null;
		}
		List<BlockNode> successors = block.getSuccessors();
		return successors.size() == 1 ? successors.get(0) : null;
	}

	public static List<BlockNode> buildSimplePath(BlockNode block) {
		if (block == null) {
			return Collections.emptyList();
		}
		List<BlockNode> list = new ArrayList<>();
		if (block.getCleanSuccessors().size() >= 2) {
			return Collections.emptyList();
		}
		list.add(block);

		BlockNode currentBlock = getNextBlock(block);
		while (currentBlock != null
				&& currentBlock.getCleanSuccessors().size() < 2
				&& currentBlock.getPredecessors().size() == 1) {
			list.add(currentBlock);
			currentBlock = getNextBlock(currentBlock);
		}
		return list;
	}

	/**
	 * Set 'SKIP' flag for all synthetic predecessors from start block.
	 */
	public static void skipPredSyntheticPaths(BlockNode block) {
		for (BlockNode pred : block.getPredecessors()) {
			if (pred.contains(AFlag.SYNTHETIC)
					&& !pred.contains(AFlag.EXC_TOP_SPLITTER)
					&& !pred.contains(AFlag.EXC_BOTTOM_SPLITTER)
					&& pred.getInstructions().isEmpty()) {
				pred.add(AFlag.DONT_GENERATE);
				skipPredSyntheticPaths(pred);
			}
		}
	}

	/**
	 * Follow empty blocks and return end of path block (first not empty).
	 * Return start block if no such path.
	 */
	public static BlockNode followEmptyPath(BlockNode start) {
		while (true) {
			BlockNode next = getNextBlockOnEmptyPath(start);
			if (next == null) {
				return start;
			}
			start = next;
		}
	}

	public static void visitBlocksOnEmptyPath(BlockNode start, Consumer<BlockNode> visitor) {
		while (true) {
			BlockNode next = getNextBlockOnEmptyPath(start);
			if (next == null) {
				return;
			}
			visitor.accept(next);
			start = next;
		}
	}

	@Nullable
	private static BlockNode getNextBlockOnEmptyPath(BlockNode block) {
		if (!block.getInstructions().isEmpty() || block.getPredecessors().size() > 1) {
			return null;
		}
		List<BlockNode> successors = block.getCleanSuccessors();
		if (successors.size() != 1) {
			return null;
		}
		return successors.get(0);
	}

	/**
	 * Return true if on path from start to end no instructions and no branches.
	 */
	public static boolean isEmptySimplePath(BlockNode start, BlockNode end) {
		if (start == end && start.getInstructions().isEmpty()) {
			return true;
		}
		if (!start.getInstructions().isEmpty() || start.getCleanSuccessors().size() != 1) {
			return false;
		}
		BlockNode block = getNextBlock(start);
		while (block != null
				&& block != end
				&& block.getCleanSuccessors().size() < 2
				&& block.getPredecessors().size() == 1
				&& block.getInstructions().isEmpty()) {
			block = getNextBlock(block);
		}
		return block == end;
	}

	/**
	 * Return predecessor of synthetic block or same block otherwise.
	 */
	public static BlockNode skipSyntheticPredecessor(BlockNode block) {
		if (block.isSynthetic()
				&& block.getInstructions().isEmpty()
				&& block.getPredecessors().size() == 1) {
			return block.getPredecessors().get(0);
		}
		return block;
	}

	public static boolean isAllBlocksEmpty(List<BlockNode> blocks) {
		for (BlockNode block : blocks) {
			if (!block.getInstructions().isEmpty()) {
				return false;
			}
		}
		return true;
	}

	public static List<InsnNode> collectAllInsns(List<BlockNode> blocks) {
		List<InsnNode> insns = new ArrayList<>();
		blocks.forEach(block -> insns.addAll(block.getInstructions()));
		return insns;
	}

	/**
	 * Return limited number of instructions from method.
	 * Return empty list if method contains more than limit.
	 */
	public static List<InsnNode> collectInsnsWithLimit(List<BlockNode> blocks, int limit) {
		List<InsnNode> insns = new ArrayList<>(limit);
		for (BlockNode block : blocks) {
			List<InsnNode> blockInsns = block.getInstructions();
			int blockSize = blockInsns.size();
			if (blockSize == 0) {
				continue;
			}
			if (insns.size() + blockSize > limit) {
				return Collections.emptyList();
			}
			insns.addAll(blockInsns);
		}
		return insns;
	}

	/**
	 * Return insn if it is only one instruction in this method. Return null otherwise.
	 */
	@Nullable
	public static InsnNode getOnlyOneInsnFromMth(MethodNode mth) {
		if (mth.isNoCode()) {
			return null;
		}
		InsnNode insn = null;
		for (BlockNode block : mth.getBasicBlocks()) {
			List<InsnNode> blockInsns = block.getInstructions();
			int blockSize = blockInsns.size();
			if (blockSize == 0) {
				continue;
			}
			if (blockSize > 1) {
				return null;
			}
			if (insn != null) {
				return null;
			}
			insn = blockInsns.get(0);
		}
		return insn;
	}

	public static boolean isFirstInsn(MethodNode mth, InsnNode insn) {
		BlockNode startBlock = followEmptyPath(mth.getEnterBlock());
		if (startBlock != null && !startBlock.getInstructions().isEmpty()) {
			return startBlock.getInstructions().get(0) == insn;
		}
		// handle branching with empty blocks
		BlockNode block = getBlockByInsn(mth, insn);
		if (block == null) {
			throw new JadxRuntimeException("Insn not found in method: " + insn);
		}
		if (block.getInstructions().get(0) != insn) {
			return false;
		}
		Set<BlockNode> allPathsBlocks = getAllPathsBlocks(mth.getEnterBlock(), block);
		for (BlockNode pathBlock : allPathsBlocks) {
			if (!pathBlock.getInstructions().isEmpty() && pathBlock != block) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Replace insn by index i in block,
	 * for proper copy attributes, assume attributes are not overlap
	 */
	public static void replaceInsn(MethodNode mth, BlockNode block, int i, InsnNode insn) {
		InsnNode prevInsn = block.getInstructions().get(i);
		insn.copyAttributesFrom(prevInsn);
		insn.inheritMetadata(prevInsn);
		insn.setOffset(prevInsn.getOffset());
		block.getInstructions().set(i, insn);

		RegisterArg result = insn.getResult();
		RegisterArg prevResult = prevInsn.getResult();
		if (result != null && prevResult != null && result.sameRegAndSVar(prevResult)) {
			// Don't unbind result for same register.
			// Unbind will remove arg from PHI and not add it back on rebind.
			InsnRemover.unbindAllArgs(mth, prevInsn);
		} else {
			InsnRemover.unbindInsn(mth, prevInsn);
		}
		insn.rebindArgs();
	}

	public static boolean replaceInsn(MethodNode mth, BlockNode block, InsnNode oldInsn, InsnNode newInsn) {
		List<InsnNode> instructions = block.getInstructions();
		int size = instructions.size();
		for (int i = 0; i < size; i++) {
			InsnNode instruction = instructions.get(i);
			if (instruction == oldInsn) {
				replaceInsn(mth, block, i, newInsn);
				return true;
			}
		}
		return false;
	}

	public static boolean insertBeforeInsn(BlockNode block, InsnNode insn, InsnNode newInsn) {
		int index = getInsnIndexInBlock(block, insn);
		if (index == -1) {
			return false;
		}
		block.getInstructions().add(index, newInsn);
		return true;
	}

	public static boolean insertAfterInsn(BlockNode block, InsnNode insn, InsnNode newInsn) {
		int index = getInsnIndexInBlock(block, insn);
		if (index == -1) {
			return false;
		}
		block.getInstructions().add(index + 1, newInsn);
		return true;
	}

	public static int getInsnIndexInBlock(BlockNode block, InsnNode insn) {
		List<InsnNode> instructions = block.getInstructions();
		int size = instructions.size();
		for (int i = 0; i < size; i++) {
			if (instructions.get(i) == insn) {
				return i;
			}
		}
		return -1;
	}

	public static boolean replaceInsn(MethodNode mth, InsnNode oldInsn, InsnNode newInsn) {
		for (BlockNode block : mth.getBasicBlocks()) {
			if (replaceInsn(mth, block, oldInsn, newInsn)) {
				return true;
			}
		}
		return false;
	}

	public static Map<BlockNode, BitSet> calcPostDominance(MethodNode mth) {
		return calcPartialPostDominance(mth, mth.getBasicBlocks(), mth.getPreExitBlocks().get(0));
	}

	public static Map<BlockNode, BitSet> calcPartialPostDominance(MethodNode mth, Collection<BlockNode> blockNodes, BlockNode exitBlock) {
		int blocksCount = mth.getBasicBlocks().size();
		Map<BlockNode, BitSet> map = new HashMap<>(blocksCount);

		BitSet initSet = new BitSet(blocksCount);
		for (BlockNode block : blockNodes) {
			initSet.set(block.getId());
		}

		for (BlockNode block : blockNodes) {
			BitSet postDoms = new BitSet(blocksCount);
			postDoms.or(initSet);
			map.put(block, postDoms);
		}
		BitSet exitBitSet = map.get(exitBlock);
		exitBitSet.clear();
		exitBitSet.set(exitBlock.getId());

		BitSet domSet = new BitSet(blocksCount);
		boolean changed;
		do {
			changed = false;
			for (BlockNode block : blockNodes) {
				if (block == exitBlock) {
					continue;
				}
				BitSet d = map.get(block);
				if (!changed) {
					domSet.clear();
					domSet.or(d);
				}
				for (BlockNode scc : block.getSuccessors()) {
					BitSet scPDoms = map.get(scc);
					if (scPDoms != null) {
						d.and(scPDoms);
					}
				}
				d.set(block.getId());
				if (!changed && !d.equals(domSet)) {
					changed = true;
					map.put(block, d);
				}
			}
		} while (changed);

		blockNodes.forEach(block -> {
			BitSet postDoms = map.get(block);
			postDoms.clear(block.getId());
			if (postDoms.isEmpty()) {
				map.put(block, EmptyBitSet.EMPTY);
			}
		});
		return map;
	}

	@Nullable
	public static BlockNode calcImmediatePostDominator(MethodNode mth, BlockNode block) {
		BlockNode oneSuccessor = Utils.getOne(block.getSuccessors());
		if (oneSuccessor != null) {
			return oneSuccessor;
		}
		return calcImmediatePostDominator(mth, block, calcPostDominance(mth));
	}

	@Nullable
	public static BlockNode calcPartialImmediatePostDominator(MethodNode mth, BlockNode block,
			Collection<BlockNode> blockNodes, BlockNode exitBlock) {
		BlockNode oneSuccessor = Utils.getOne(block.getSuccessors());
		if (oneSuccessor != null) {
			return oneSuccessor;
		}
		Map<BlockNode, BitSet> pDomsMap = calcPartialPostDominance(mth, blockNodes, exitBlock);
		return calcImmediatePostDominator(mth, block, pDomsMap);
	}

	@Nullable
	public static BlockNode calcImmediatePostDominator(MethodNode mth, BlockNode block, Map<BlockNode, BitSet> postDomsMap) {
		BlockNode oneSuccessor = Utils.getOne(block.getSuccessors());
		if (oneSuccessor != null) {
			return oneSuccessor;
		}
		List<BlockNode> basicBlocks = mth.getBasicBlocks();
		BitSet postDoms = postDomsMap.get(block);
		BitSet bs = copyBlocksBitSet(mth, postDoms);
		for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
			BlockNode pdomBlock = basicBlocks.get(i);
			BitSet pdoms = postDomsMap.get(pdomBlock);
			if (pdoms != null) {
				bs.andNot(pdoms);
			}
		}
		return bitSetToOneBlock(mth, bs);
	}

	public static BlockNode getTopSplitterForHandler(BlockNode handlerBlock) {
		BlockNode block = getBlockWithFlag(handlerBlock.getPredecessors(), AFlag.EXC_TOP_SPLITTER);
		if (block == null) {
			throw new JadxRuntimeException("Can't find top splitter block for handler:" + handlerBlock);
		}
		return block;
	}

	@Nullable
	public static BlockNode getBlockWithFlag(List<BlockNode> blocks, AFlag flag) {
		for (BlockNode block : blocks) {
			if (block.contains(flag)) {
				return block;
			}
		}
		return null;
	}
}


text:
package org.nd4j.bytebuddy.method.integer;

import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.jar.asm.MethodVisitor;

/**
 * @author Adam Gibson
 */
public class LoadIntParam implements ByteCodeAppender {
    private int offset = -1;

    public LoadIntParam(int offset) {
        this.offset = offset;
    }

    @Override
    public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext,
                    MethodDescription instrumentedMethod) {
        StackManipulation.Size size =
                        MethodVariableAccess.INTEGER.loadOffset(offset).apply(methodVisitor, implementationContext);
        return new Size(size.getMaximalSize(), instrumentedMethod.getStackSize());
    }
}


text:
function post(url, data) {
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  request.send(data)
}

function post_favorite_twaat(twaat) {
  post('favorite_twaat/' + twaat, {})
}

function changeAvatar(e) {
  e.preventDefault()
  var modal = document.getElementById("upload_file");
  modal.className.split().map(function (e) { console.log(e) })
  modal.className += ' is-active'; // Click on the checkbox
}

function closeModal(e) {
  for (x of document.getElementsByClassName('modal')) {
    x.className = "modal";
  }
}

document.getElementById("change_avatar").addEventListener("click", changeAvatar);

/* Looks like getElementsByClassName returns a NODE __ LIST which obviously isnt AN ARRAY but a LIST -_-
  so, cant map it or do nicely anything :c
*/

// for (x of document.getElementsByClassName("modal-background")){
//   x.addEventListener("click", closeModal);
// }
// for (x of document.getElementsByClassName("modal-close")){
//   x.addEventListener("click", closeModal);
// }

document.getElementsByClassName("modal-background")[0].addEventListener("click", closeModal);
if(document.getElementsByClassName("modal-close")[0]){
  document.getElementsByClassName("modal-close")[0].addEventListener("click", closeModal);
}

if(document.getElementsByClassName("modal-close")[0]){
  document.getElementsByClassName("modal-close")[0].addEventListener("click", closeModal);
}

/*
  NO MORE JAVASCRIPT LIBRARIES MEANS NO MORE JAVASCRIPT LIBRARIES INCLUDING JQUERY!
 */
var selector = '.notification > .delete';
var elements = document.querySelectorAll(selector);

Array.prototype.forEach.call(elements, function(el, i){
  el.addEventListener("click", function(e){
    var elParent = el.parentNode;
    var elGrandParent = elParent.parentNode;
    elParent.remove();
    //If container empty, rmeove it.
    //We must go deeper.
    if(!document.querySelectorAll('.section .container .column')[0].length){
      document.querySelectorAll('.section')[0].remove()
    }
  });
});


text:
Kubernetes follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md).

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting
the [Kubernetes Code of Conduct Committee](./committee-code-of-conduct) via <conduct@kubernetes.io>.


text:
```html
<!-- Default Checkbox -->
<ion-checkbox></ion-checkbox>

<!-- Disabled Checkbox -->
<ion-checkbox disabled="true"></ion-checkbox>

<!-- Checked Checkbox -->
<ion-checkbox checked="true"></ion-checkbox>

<!-- Checkbox Colors -->
<ion-checkbox color="primary"></ion-checkbox>
<ion-checkbox color="secondary"></ion-checkbox>
<ion-checkbox color="danger"></ion-checkbox>
<ion-checkbox color="light"></ion-checkbox>
<ion-checkbox color="dark"></ion-checkbox>

<!-- Checkboxes in a List -->
<ion-list>
  <ion-item *ngFor="let entry of form">
    <ion-label>{{entry.val}}</ion-label>
    <ion-checkbox slot="end" [(ngModel)]="entry.isChecked"></ion-checkbox>
  </ion-item>
</ion-list>
```

```typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-page-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage {
  public form = [
      { val: 'Pepperoni', isChecked: true },
      { val: 'Sausage', isChecked: false },
      { val: 'Mushroom', isChecked: false }
    ];
}
```


text:
package org.springframework.social.google.api.drive.impl;

import org.springframework.social.google.api.drive.FileProperty;
import org.springframework.social.google.api.query.ApiList;

/**
 * {@link ApiList} of {@link FileProperty}
 * @author Will Abson
 */
class FilePropertiesList extends ApiList<FileProperty> {

}


text:
package com.amazonaws.services.glue.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.glue.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DynamoDBTarget JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DynamoDBTargetJsonUnmarshaller implements Unmarshaller<DynamoDBTarget, JsonUnmarshallerContext> {

    public DynamoDBTarget unmarshall(JsonUnmarshallerContext context) throws Exception {
        DynamoDBTarget dynamoDBTarget = new DynamoDBTarget();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Path", targetDepth)) {
                    context.nextToken();
                    dynamoDBTarget.setPath(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return dynamoDBTarget;
    }

    private static DynamoDBTargetJsonUnmarshaller instance;

    public static DynamoDBTargetJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DynamoDBTargetJsonUnmarshaller();
        return instance;
    }
}


text:
<?php
abstract class models_methods_Abstract extends PaymentModule  implements models_InterfacePayment
{
    public function __construct()
    {
        $this->tab = 'payments_gateways';
        $this->version = '1.0.0';
        $this->author = 'Checkout.com';
        $this->displayName = 'Checkout.com  (Gateway 3.0)';
        $this->description = $this->l('Receive payment with gateway 3.0');
        parent::__construct();
    }

    public function getCode()
    {
        return $this->_code;
    }

    public function install(){}
    public function uninstall(){}
    public function hookOrderConfirmation(array $params){}
    public function hookBackOfficeHeader(){}
    public function getContent(){}
    public function hookPayment($params){}
    public function hookHeader(){}
    abstract public  function createCharge($config = array(),$cart);

    protected function _createCharge($config)
    {
        $Api = CheckoutApi_Api::getApi(array('mode'=> Configuration::get('CHECKOUTAPI_TEST_MODE')));

        return $Api->createCharge($config);
    }

    protected function _captureConfig()
    {
        $to_return = array (
            'autoCapture' => CheckoutApi_Client_Constant::AUTOCAPUTURE_CAPTURE,
            'autoCapTime' => Configuration::get('CHECKOUTAPI_AUTOCAPTURE_DELAY')
        );

        return $to_return;
    }

    protected function _authorizeConfig()
    {
        $to_return= array (
            'autoCapture' => CheckoutApi_Client_Constant::AUTOCAPUTURE_AUTH,
            'autoCapTime' => 0
        );

        return $to_return;
    }

    public function getContext()
    {
        return $this->context;
    }
}


text:
#import "UGClientResponse.h"

@implementation UGClientResponse

@synthesize transactionID;
@synthesize transactionState;
@synthesize response;
@synthesize rawResponse;

-(id)init
{
    self = [super init];
    if ( self )
    {
        transactionID = -1;
        transactionState = -1;
        response = nil;
        rawResponse = nil;
    }
    return self;
}

@end


text:
'use strict';

const fs = require('fs');
const mkdirp = require('mkdirp');
const archiver = require('archiver');

const result = require('../../pages/result');
const bom = require('../../lib/bom');
const addComments = require('../../lib/add-comments');

const donkey = (obj) => {
    mkdirp(`${global.HELP_CMS.download}/`);

    let res = obj.res;
    let file = obj.file;
    let donkeyData = obj.donkeyData;
    let $ = obj.$;
    let time = obj.time;
    let str = obj.str;
    let index = 0;
    const $html = $('html');
    // donkey template
    let template = $html.prop('outerHTML');
    if ($html.length) {
        template = str;
    }

    // set zipPath
    let zipPath = file.path.replace(`${global.HELP_CMS.upload}/org`, `${global.HELP_CMS.download}/zip`);
    zipPath = zipPath.replace(/\.html$|\.htm$/igm, '.zip');
    let output = fs.createWriteStream(zipPath);
    const archive = archiver('zip', {
        zlib: {
            level: 9
        } // Sets the compression level.
    });
    // listen for all archive data to be written
    output.on('close', function () {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    // good practice to catch this error explicitly
    archive.on('error', function (err) {
        throw err;
    });

    //将打包对象与输出流关联
    archive.pipe(output);

    for (let prop in donkeyData) {
        let html = template;
        if(donkeyData[prop]) {
        // console.log('donkeyData[prop]: ', prop, donkeyData.hasOwnProperty(prop));
        // if(donkeyData[prop].hasOwnProperty('list')) {
            const list = donkeyData[prop].list;
            if (list) {
                // 编译模版的索引
                index++;
                for (let _prop in list) {
                    let regProp = new RegExp(`nodeid="{{${_prop}}}"`, 'ig');
                    let nid = list[_prop].nid;
                    html = html.replace(regProp, `nodeid="${nid}"`);
                }
                html = addComments({
                    'type': `donkey`,
                    'length': list.length,
                    'time': time,
                    'html': html,
                    'name': prop,
                });
                //将被打包文件的流添加进archiver对象中
                archive.append(bom + html, {
                    'name': `${(index < 10) ? '0' + index : index}-${prop}.htm`
                });
            }
        // }
        }
    }

    //打包
    archive.finalize();
    const donkeyResult = {
        type: 'donkey',
        dist: zipPath,
        time: time,
        donkey: {
            index: index,
        }
    };
    obj.res.send(result(donkeyResult));
}

module.exports = donkey;