text:
package backup

import (
	"archive/tar"
	"compress/gzip"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	kubeerrs "k8s.io/apimachinery/pkg/util/errors"

	velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
	"github.com/vmware-tanzu/velero/pkg/client"
	"github.com/vmware-tanzu/velero/pkg/discovery"
	velerov1client "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/typed/velero/v1"
	"github.com/vmware-tanzu/velero/pkg/kuberesource"
	"github.com/vmware-tanzu/velero/pkg/plugin/velero"
	"github.com/vmware-tanzu/velero/pkg/podexec"
	"github.com/vmware-tanzu/velero/pkg/restic"
	"github.com/vmware-tanzu/velero/pkg/util/collections"
)

// BackupVersion is the current backup major version for Velero.
// Deprecated, use BackupFormatVersion
const BackupVersion = 1

// BackupFormatVersion is the current backup version for Velero, including major, minor, and patch.
const BackupFormatVersion = "1.1.0"

// Backupper performs backups.
type Backupper interface {
	// Backup takes a backup using the specification in the velerov1api.Backup and writes backup and log data
	// to the given writers.
	Backup(logger logrus.FieldLogger, backup *Request, backupFile io.Writer, actions []velero.BackupItemAction, volumeSnapshotterGetter VolumeSnapshotterGetter) error
}

// kubernetesBackupper implements Backupper.
type kubernetesBackupper struct {
	backupClient           velerov1client.BackupsGetter
	dynamicFactory         client.DynamicFactory
	discoveryHelper        discovery.Helper
	podCommandExecutor     podexec.PodCommandExecutor
	resticBackupperFactory restic.BackupperFactory
	resticTimeout          time.Duration
	defaultVolumesToRestic bool
}

type resolvedAction struct {
	velero.BackupItemAction

	resourceIncludesExcludes  *collections.IncludesExcludes
	namespaceIncludesExcludes *collections.IncludesExcludes
	selector                  labels.Selector
}

func (i *itemKey) String() string {
	return fmt.Sprintf("resource=%s,namespace=%s,name=%s", i.resource, i.namespace, i.name)
}

func cohabitatingResources() map[string]*cohabitatingResource {
	return map[string]*cohabitatingResource{
		"deployments":     newCohabitatingResource("deployments", "extensions", "apps"),
		"daemonsets":      newCohabitatingResource("daemonsets", "extensions", "apps"),
		"replicasets":     newCohabitatingResource("replicasets", "extensions", "apps"),
		"networkpolicies": newCohabitatingResource("networkpolicies", "extensions", "networking.k8s.io"),
		"events":          newCohabitatingResource("events", "", "events.k8s.io"),
	}
}

// NewKubernetesBackupper creates a new kubernetesBackupper.
func NewKubernetesBackupper(
	backupClient velerov1client.BackupsGetter,
	discoveryHelper discovery.Helper,
	dynamicFactory client.DynamicFactory,
	podCommandExecutor podexec.PodCommandExecutor,
	resticBackupperFactory restic.BackupperFactory,
	resticTimeout time.Duration,
	defaultVolumesToRestic bool,
) (Backupper, error) {
	return &kubernetesBackupper{
		backupClient:           backupClient,
		discoveryHelper:        discoveryHelper,
		dynamicFactory:         dynamicFactory,
		podCommandExecutor:     podCommandExecutor,
		resticBackupperFactory: resticBackupperFactory,
		resticTimeout:          resticTimeout,
		defaultVolumesToRestic: defaultVolumesToRestic,
	}, nil
}

func resolveActions(actions []velero.BackupItemAction, helper discovery.Helper) ([]resolvedAction, error) {
	var resolved []resolvedAction

	for _, action := range actions {
		resourceSelector, err := action.AppliesTo()
		if err != nil {
			return nil, err
		}

		resources := getResourceIncludesExcludes(helper, resourceSelector.IncludedResources, resourceSelector.ExcludedResources)
		namespaces := collections.NewIncludesExcludes().Includes(resourceSelector.IncludedNamespaces...).Excludes(resourceSelector.ExcludedNamespaces...)

		selector := labels.Everything()
		if resourceSelector.LabelSelector != "" {
			if selector, err = labels.Parse(resourceSelector.LabelSelector); err != nil {
				return nil, err
			}
		}

		res := resolvedAction{
			BackupItemAction:          action,
			resourceIncludesExcludes:  resources,
			namespaceIncludesExcludes: namespaces,
			selector:                  selector,
		}

		resolved = append(resolved, res)
	}

	return resolved, nil
}

// getResourceIncludesExcludes takes the lists of resources to include and exclude, uses the
// discovery helper to resolve them to fully-qualified group-resource names, and returns an
// IncludesExcludes list.
func getResourceIncludesExcludes(helper discovery.Helper, includes, excludes []string) *collections.IncludesExcludes {
	resources := collections.GenerateIncludesExcludes(
		includes,
		excludes,
		func(item string) string {
			gvr, _, err := helper.ResourceFor(schema.ParseGroupResource(item).WithVersion(""))
			if err != nil {
				// If we can't resolve it, return it as-is. This prevents the generated
				// includes-excludes list from including *everything*, if none of the includes
				// can be resolved. ref. https://github.com/vmware-tanzu/velero/issues/2461
				return item
			}

			gr := gvr.GroupResource()
			return gr.String()
		},
	)

	return resources
}

// getNamespaceIncludesExcludes returns an IncludesExcludes list containing which namespaces to
// include and exclude from the backup.
func getNamespaceIncludesExcludes(backup *velerov1api.Backup) *collections.IncludesExcludes {
	return collections.NewIncludesExcludes().Includes(backup.Spec.IncludedNamespaces...).Excludes(backup.Spec.ExcludedNamespaces...)
}

func getResourceHooks(hookSpecs []velerov1api.BackupResourceHookSpec, discoveryHelper discovery.Helper) ([]resourceHook, error) {
	resourceHooks := make([]resourceHook, 0, len(hookSpecs))

	for _, s := range hookSpecs {
		h, err := getResourceHook(s, discoveryHelper)
		if err != nil {
			return []resourceHook{}, err
		}

		resourceHooks = append(resourceHooks, h)
	}

	return resourceHooks, nil
}

func getResourceHook(hookSpec velerov1api.BackupResourceHookSpec, discoveryHelper discovery.Helper) (resourceHook, error) {
	h := resourceHook{
		name:       hookSpec.Name,
		namespaces: collections.NewIncludesExcludes().Includes(hookSpec.IncludedNamespaces...).Excludes(hookSpec.ExcludedNamespaces...),
		resources:  getResourceIncludesExcludes(discoveryHelper, hookSpec.IncludedResources, hookSpec.ExcludedResources),
		pre:        hookSpec.PreHooks,
		post:       hookSpec.PostHooks,
	}

	if hookSpec.LabelSelector != nil {
		labelSelector, err := metav1.LabelSelectorAsSelector(hookSpec.LabelSelector)
		if err != nil {
			return resourceHook{}, errors.WithStack(err)
		}
		h.labelSelector = labelSelector
	}

	return h, nil
}

type VolumeSnapshotterGetter interface {
	GetVolumeSnapshotter(name string) (velero.VolumeSnapshotter, error)
}

// Backup backs up the items specified in the Backup, placing them in a gzip-compressed tar file
// written to backupFile. The finalized velerov1api.Backup is written to metadata. Any error that represents
// a complete backup failure is returned. Errors that constitute partial failures (i.e. failures to
// back up individual resources that don't prevent the backup from continuing to be processed) are logged
// to the backup log.
func (kb *kubernetesBackupper) Backup(log logrus.FieldLogger, backupRequest *Request, backupFile io.Writer, actions []velero.BackupItemAction, volumeSnapshotterGetter VolumeSnapshotterGetter) error {
	gzippedData := gzip.NewWriter(backupFile)
	defer gzippedData.Close()

	tw := tar.NewWriter(gzippedData)
	defer tw.Close()

	log.Info("Writing backup version file")
	if err := kb.writeBackupVersion(tw); err != nil {
		return errors.WithStack(err)
	}

	backupRequest.NamespaceIncludesExcludes = getNamespaceIncludesExcludes(backupRequest.Backup)
	log.Infof("Including namespaces: %s", backupRequest.NamespaceIncludesExcludes.IncludesString())
	log.Infof("Excluding namespaces: %s", backupRequest.NamespaceIncludesExcludes.ExcludesString())

	backupRequest.ResourceIncludesExcludes = getResourceIncludesExcludes(kb.discoveryHelper, backupRequest.Spec.IncludedResources, backupRequest.Spec.ExcludedResources)
	log.Infof("Including resources: %s", backupRequest.ResourceIncludesExcludes.IncludesString())
	log.Infof("Excluding resources: %s", backupRequest.ResourceIncludesExcludes.ExcludesString())
	log.Infof("Backing up all pod volumes using restic: %t", *backupRequest.Backup.Spec.DefaultVolumesToRestic)

	var err error
	backupRequest.ResourceHooks, err = getResourceHooks(backupRequest.Spec.Hooks.Resources, kb.discoveryHelper)
	if err != nil {
		return err
	}

	backupRequest.ResolvedActions, err = resolveActions(actions, kb.discoveryHelper)
	if err != nil {
		return err
	}

	backupRequest.BackedUpItems = map[itemKey]struct{}{}

	podVolumeTimeout := kb.resticTimeout
	if val := backupRequest.Annotations[velerov1api.PodVolumeOperationTimeoutAnnotation]; val != "" {
		parsed, err := time.ParseDuration(val)
		if err != nil {
			log.WithError(errors.WithStack(err)).Errorf("Unable to parse pod volume timeout annotation %s, using server value.", val)
		} else {
			podVolumeTimeout = parsed
		}
	}

	ctx, cancelFunc := context.WithTimeout(context.Background(), podVolumeTimeout)
	defer cancelFunc()

	var resticBackupper restic.Backupper
	if kb.resticBackupperFactory != nil {
		resticBackupper, err = kb.resticBackupperFactory.NewBackupper(ctx, backupRequest.Backup)
		if err != nil {
			return errors.WithStack(err)
		}
	}

	// set up a temp dir for the itemCollector to use to temporarily
	// store items as they're scraped from the API.
	tempDir, err := ioutil.TempDir("", "")
	if err != nil {
		return errors.Wrap(err, "error creating temp dir for backup")
	}
	defer os.RemoveAll(tempDir)

	collector := &itemCollector{
		log:                   log,
		backupRequest:         backupRequest,
		discoveryHelper:       kb.discoveryHelper,
		dynamicFactory:        kb.dynamicFactory,
		cohabitatingResources: cohabitatingResources(),
		dir:                   tempDir,
	}

	items := collector.getAllItems()
	log.WithField("progress", "").Infof("Collected %d items matching the backup spec from the Kubernetes API (actual number of items backed up may be more or less depending on velero.io/exclude-from-backup annotation, plugins returning additional related items to back up, etc.)", len(items))

	backupRequest.Status.Progress = &velerov1api.BackupProgress{TotalItems: len(items)}
	patch := fmt.Sprintf(`{"status":{"progress":{"totalItems":%d}}}`, len(items))
	if _, err := kb.backupClient.Backups(backupRequest.Namespace).Patch(context.TODO(), backupRequest.Name, types.MergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil {
		log.WithError(errors.WithStack((err))).Warn("Got error trying to update backup's status.progress.totalItems")
	}

	itemBackupper := &itemBackupper{
		backupRequest:           backupRequest,
		tarWriter:               tw,
		dynamicFactory:          kb.dynamicFactory,
		discoveryHelper:         kb.discoveryHelper,
		resticBackupper:         resticBackupper,
		resticSnapshotTracker:   newPVCSnapshotTracker(),
		volumeSnapshotterGetter: volumeSnapshotterGetter,
		itemHookHandler: &defaultItemHookHandler{
			podCommandExecutor: kb.podCommandExecutor,
		},
	}

	// helper struct to send current progress between the main
	// backup loop and the gouroutine that periodically patches
	// the backup CR with progress updates
	type progressUpdate struct {
		totalItems, itemsBackedUp int
	}

	// the main backup process will send on this channel once
	// for every item it processes.
	update := make(chan progressUpdate)

	// the main backup process will send on this channel when
	// it's done sending progress updates
	quit := make(chan struct{})

	// This is the progress updater goroutine that receives
	// progress updates on the 'update' channel. It patches
	// the backup CR with progress updates at most every second,
	// but it will not issue a patch if it hasn't received a new
	// update since the previous patch. This goroutine exits
	// when it receives on the 'quit' channel.
	go func() {
		ticker := time.NewTicker(1 * time.Second)
		var lastUpdate *progressUpdate
		for {
			select {
			case <-quit:
				ticker.Stop()
				return
			case val := <-update:
				lastUpdate = &val
			case <-ticker.C:
				if lastUpdate != nil {
					backupRequest.Status.Progress.TotalItems = lastUpdate.totalItems
					backupRequest.Status.Progress.ItemsBackedUp = lastUpdate.itemsBackedUp

					patch := fmt.Sprintf(`{"status":{"progress":{"totalItems":%d,"itemsBackedUp":%d}}}`, lastUpdate.totalItems, lastUpdate.itemsBackedUp)
					if _, err := kb.backupClient.Backups(backupRequest.Namespace).Patch(context.TODO(), backupRequest.Name, types.MergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil {
						log.WithError(errors.WithStack((err))).Warn("Got error trying to update backup's status.progress")
					}
					lastUpdate = nil
				}
			}
		}
	}()

	backedUpGroupResources := map[schema.GroupResource]bool{}
	totalItems := len(items)

	for i, item := range items {
		log.WithFields(map[string]interface{}{
			"progress":  "",
			"resource":  item.groupResource.String(),
			"namespace": item.namespace,
			"name":      item.name,
		}).Infof("Processing item")

		// use an anonymous func so we can defer-close/remove the file
		// as soon as we're done with it
		func() {
			var unstructured unstructured.Unstructured

			f, err := os.Open(item.path)
			if err != nil {
				log.WithError(errors.WithStack(err)).Error("Error opening file containing item")
				return
			}
			defer f.Close()
			defer os.Remove(f.Name())

			if err := json.NewDecoder(f).Decode(&unstructured); err != nil {
				log.WithError(errors.WithStack(err)).Error("Error decoding JSON from file")
				return
			}

			if backedUp := kb.backupItem(log, item.groupResource, itemBackupper, &unstructured, item.preferredGVR); backedUp {
				backedUpGroupResources[item.groupResource] = true
			}
		}()

		// updated total is computed as "how many items we've backed up so far, plus
		// how many items we know of that are remaining"
		totalItems = len(backupRequest.BackedUpItems) + (len(items) - (i + 1))

		// send a progress update
		update <- progressUpdate{
			totalItems:    totalItems,
			itemsBackedUp: len(backupRequest.BackedUpItems),
		}

		log.WithFields(map[string]interface{}{
			"progress":  "",
			"resource":  item.groupResource.String(),
			"namespace": item.namespace,
			"name":      item.name,
		}).Infof("Backed up %d items out of an estimated total of %d (estimate will change throughout the backup)", len(backupRequest.BackedUpItems), totalItems)
	}

	// no more progress updates will be sent on the 'update' channel
	quit <- struct{}{}

	// back up CRD for resource if found. We should only need to do this if we've backed up at least
	// one item for the resource and IncludeClusterResources is nil. If IncludeClusterResources is false
	// we don't want to back it up, and if it's true it will already be included.
	if backupRequest.Spec.IncludeClusterResources == nil {
		for gr := range backedUpGroupResources {
			kb.backupCRD(log, gr, itemBackupper)
		}
	}

	// do a final update on progress since we may have just added some CRDs and may not have updated
	// for the last few processed items.
	backupRequest.Status.Progress.TotalItems = len(backupRequest.BackedUpItems)
	backupRequest.Status.Progress.ItemsBackedUp = len(backupRequest.BackedUpItems)

	patch = fmt.Sprintf(`{"status":{"progress":{"totalItems":%d,"itemsBackedUp":%d}}}`, len(backupRequest.BackedUpItems), len(backupRequest.BackedUpItems))
	if _, err := kb.backupClient.Backups(backupRequest.Namespace).Patch(context.TODO(), backupRequest.Name, types.MergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil {
		log.WithError(errors.WithStack((err))).Warn("Got error trying to update backup's status.progress")
	}

	log.WithField("progress", "").Infof("Backed up a total of %d items", len(backupRequest.BackedUpItems))

	return nil
}

func (kb *kubernetesBackupper) backupItem(log logrus.FieldLogger, gr schema.GroupResource, itemBackupper *itemBackupper, unstructured *unstructured.Unstructured, preferredGVR schema.GroupVersionResource) bool {
	backedUpItem, err := itemBackupper.backupItem(log, unstructured, gr, preferredGVR)
	if aggregate, ok := err.(kubeerrs.Aggregate); ok {
		log.WithField("name", unstructured.GetName()).Infof("%d errors encountered backup up item", len(aggregate.Errors()))
		// log each error separately so we get error location info in the log, and an
		// accurate count of errors
		for _, err = range aggregate.Errors() {
			log.WithError(err).WithField("name", unstructured.GetName()).Error("Error backing up item")
		}

		return false
	}
	if err != nil {
		log.WithError(err).WithField("name", unstructured.GetName()).Error("Error backing up item")
		return false
	}
	return backedUpItem
}

// backupCRD checks if the resource is a custom resource, and if so, backs up the custom resource definition
// associated with it.
func (kb *kubernetesBackupper) backupCRD(log logrus.FieldLogger, gr schema.GroupResource, itemBackupper *itemBackupper) {
	crdGroupResource := kuberesource.CustomResourceDefinitions

	log.Debugf("Getting server preferred API version for %s", crdGroupResource)
	gvr, apiResource, err := kb.discoveryHelper.ResourceFor(crdGroupResource.WithVersion(""))
	if err != nil {
		log.WithError(errors.WithStack(err)).Errorf("Error getting resolved resource for %s", crdGroupResource)
		return
	}
	log.Debugf("Got server preferred API version %s for %s", gvr.Version, crdGroupResource)

	log.Debugf("Getting dynamic client for %s", gvr.String())
	crdClient, err := kb.dynamicFactory.ClientForGroupVersionResource(gvr.GroupVersion(), apiResource, "")
	if err != nil {
		log.WithError(errors.WithStack(err)).Errorf("Error getting dynamic client for %s", crdGroupResource)
		return
	}
	log.Debugf("Got dynamic client for %s", gvr.String())

	// try to get a CRD whose name matches the provided GroupResource
	unstructured, err := crdClient.Get(gr.String(), metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		// not found: this means the GroupResource provided was not a
		// custom resource, so there's no CRD to back up.
		log.Debugf("No CRD found for GroupResource %s", gr.String())
		return
	}
	if err != nil {
		log.WithError(errors.WithStack(err)).Errorf("Error getting CRD %s", gr.String())
		return
	}
	log.Infof("Found associated CRD %s to add to backup", gr.String())

	kb.backupItem(log, gvr.GroupResource(), itemBackupper, unstructured, gvr)
}

func (kb *kubernetesBackupper) writeBackupVersion(tw *tar.Writer) error {
	versionFile := filepath.Join(velerov1api.MetadataDir, "version")
	versionString := fmt.Sprintf("%s\n", BackupFormatVersion)

	hdr := &tar.Header{
		Name:     versionFile,
		Size:     int64(len(versionString)),
		Typeflag: tar.TypeReg,
		Mode:     0755,
		ModTime:  time.Now(),
	}
	if err := tw.WriteHeader(hdr); err != nil {
		return errors.WithStack(err)
	}
	if _, err := tw.Write([]byte(versionString)); err != nil {
		return errors.WithStack(err)
	}
	return nil
}

type tarWriter interface {
	io.Closer
	Write([]byte) (int, error)
	WriteHeader(*tar.Header) error
}


text:
Imports System.IO
Module ActionsLib

    Function ActionEquateDisplay(ByVal ActionName As String, ByVal ActionArguments As String) As String
        Dim Returnable As String = String.Empty
        For Each Y As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action")
            If Y.StartsWith("DISPLAY ") Then Returnable = Y.Substring(8) : Exit For
        Next
        If Returnable.Length = 0 Then Return ActionName
        For Each Y As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action")
            For Z = 0 To HowManyChar(ActionArguments, ";")
                Dim Argument As String = iGet(ActionArguments, Z, ";")
                Dim StringThing As String = Argument
                If StringThing = "1" Then StringThing = "true"
                If StringThing = "0" Then StringThing = "false"
                If StringThing = "<" Or StringThing = ">" Or StringThing = ">=" Or StringThing = "<=" Or StringThing = "==" Then
                    StringThing = ComparativeToString(StringThing)
                End If
                Dim ScreenThing As String = Argument
                If ScreenThing = "1" Then ScreenThing = "Top Screen"
                If ScreenThing = "0" Then ScreenThing = "Bottom Screen"
                Returnable = Returnable.Replace("$" + (Z + 1).ToString + "$", StringThing)
                Returnable = Returnable.Replace("%" + (Z + 1).ToString + "%", ScreenThing)
                Returnable = Returnable.Replace("!" + (Z + 1).ToString + "!", Argument)
            Next
        Next
        Returnable = Returnable.Replace("<com>", ",")
        Return Returnable
    End Function

    Function ActionIsConditional(ByVal ActionName) As Boolean
        For Each X As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action")
            If X.StartsWith("CONDITION ") Then
                X = X.Substring(("CONDITION").Length + 1)
                Return (X = "1")
            End If
        Next
        Return False
    End Function

    Function ActionGetIconPath(ByVal ActionName As String, ByVal UseFullPath As Boolean) As String
        Dim Returnable As String = "Empty.png"
        For Each X As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action")
            If X.StartsWith("ICON ") Then Returnable = X.Substring(5)
        Next
        If Not File.Exists(AppPath + "ActionIcons\" + Returnable) Then Returnable = "Empty.png"
        If UseFullPath Then Returnable = AppPath + "ActionIcons\" + Returnable
        Return Returnable
    End Function

    Function ActionGetIcon(ByVal ActionName As String) As Bitmap
        Dim TBMP As New Bitmap(32, 32)
        Dim TBMPGFX As Graphics = Graphics.FromImage(TBMP)
        Dim TIcon As Bitmap = PathToImage(ActionGetIconPath(ActionName, True))
        If TIcon.Width = 32 Then
            TBMPGFX.DrawImageUnscaled(My.Resources.ActionBacker, 0, 0)
            TBMPGFX.DrawImageUnscaled(TIcon, New Point(0, 0))
        Else
            If ActionIsConditional(ActionName) Then
                TBMPGFX.DrawImageUnscaled(ActionConditionalBG, 0, 0)
            Else
                TBMPGFX.DrawImageUnscaled(ActionBG, 0, 0)
            End If
            TBMPGFX.DrawImageUnscaled(TIcon, New Point(8, 8))
        End If
        TBMPGFX.Dispose()
        TIcon.Dispose()
        Return TBMP
    End Function

End Module

redpajama_set_name: RedPajamaGithub


text:
//   Copyright 2017 Ansersion
//
//   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.
//

#ifndef BC_TYPE_H
#define BC_TYPE_H

#include <beecomint.h>
#include <bc.h>

typedef enum BC_ModID {
	BC_MOD_DEFAULT=0,
	BC_MOD_DATAHUB,
	BC_MOD_WIFI,
	BC_MOD_PHONE_APP,
	BC_MOD_ZIGBEE,
	BC_MOD_BLUETOOTH,
	BC_MOD_NET_SERVER,
	BC_MOD_TERMINAL,
	/* indicate the queue msg from IRQ */
	BC_MOD_IRQ,
	/* BC_MOD_ANONYMITY:
	   1. as source ID: means not to response
	   2. as destionation ID: means the message would be droped*/
	BC_MOD_ANONYMITY,
	/* invalid mod, to define the limit */
	BC_MOD_INVALID,
}BC_ModID;

typedef struct BC_QueueElement {
	uint8_t 	u8SrcID;
	uint8_t 	u8DstID;
	uint16_t 	u16MsgLen;
	uint8_t 	pText[BC_CONFIG_QUEUE_ELEMENT_BUF_SIZE];
}BC_QueueElement;

typedef struct BC_MsgDirMap {
	uint8_t 				u8SrcID;
	uint8_t 				u8DstID1;
	uint8_t 				u8DstID2;
	uint8_t 				u8DstID3;
	struct BC_MsgDirMap * 	pExtDst;
}BC_MsgDirMap;

#define BC_ASSERT_MOD_ID_VALID(ID) ((ID) < BC_MOD_INVALID)

/************************************
  Push a queue element into the queue
*************************************/
#define BC_Enqueue 	 	xQueueSend

/************************************
  Extract a queue element from the queue
*************************************/
#define BC_Dequeue 	xQueueReceive

/************************************
  Push a queue element into the queue
  in IRQ context
*************************************/
#define BC_EnqueueISR 	xQueueSendFromISR

/************************************
  Extract a queue element from the queue
  in IRQ context
*************************************/
#define BC_DequeueISR 	xQueueReceiveFromISR

#endif


text:
package com.epam.ta.reportportal.entity.oauth;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@Entity
@Table(name = "oauth_registration_restriction", schema = "public")
public class OAuthRegistrationRestriction implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private Long id;

	@ManyToOne
	@JoinColumn(name = "oauth_registration_fk")
	private OAuthRegistration registration;

	@Column(name = "type")
	private String type;

	@Column(name = "value")
	private String value;

	public Long getId() {
		return id;
	}

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

	public OAuthRegistration getRegistration() {
		return registration;
	}

	public void setRegistration(OAuthRegistration registration) {
		this.registration = registration;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getValue() {
		return value;
	}

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

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		OAuthRegistrationRestriction that = (OAuthRegistrationRestriction) o;
		return Objects.equals(type, that.type) && Objects.equals(value, that.value);
	}

	@Override
	public int hashCode() {
		return Objects.hash(type, value);
	}
}


text:
package flags

const protoLegacy = true


text:
package metrics

import (
	"github.com/prometheus/client_golang/prometheus"
)

// Metrics for the GC worker.
var (
	GCWorkerCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_worker_actions_total",
			Help:      "Counter of gc worker actions.",
		}, []string{"type"})

	GCHistogram = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_seconds",
			Help:      "Bucketed histogram of gc duration.",
			Buckets:   prometheus.ExponentialBuckets(1, 2, 20), // 1s ~ 12days
		}, []string{"stage"})

	GCConfigGauge = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_config",
			Help:      "Gauge of GC configs.",
		}, []string{"type"})

	GCJobFailureCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_failure",
			Help:      "Counter of gc job failure.",
		}, []string{"type"})

	GCActionRegionResultCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_action_result",
			Help:      "Counter of gc action result on region level.",
		}, []string{"type"})

	GCRegionTooManyLocksCounter = prometheus.NewCounter(
		prometheus.CounterOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_region_too_many_locks",
			Help:      "Counter of gc scan lock request more than once in the same region.",
		})

	GCUnsafeDestroyRangeFailuresCounterVec = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "tidb",
			Subsystem: "tikvclient",
			Name:      "gc_unsafe_destroy_range_failures",
			Help:      "Counter of unsafe destroyrange failures",
		}, []string{"type"})
)


text:
module TicksyAPI
  class Ticket < OpenStruct
    def comments
      Comment.from_hash(ticket_comments) unless ticket_comments.nil?
    end
  end
end


text:
package org.tensorflow.demo;

import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.Image.Plane;
import android.media.ImageReader;
import android.media.ImageReader.OnImageAvailableListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Trace;
import android.util.Size;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;
import java.nio.ByteBuffer;

import org.tensorflow.demo.env.ImageUtils;
import org.tensorflow.demo.env.Logger;

// Explicit import needed for internal Google builds.
import org.tensorflow.demo.R;

public abstract class CameraActivity extends Activity implements OnImageAvailableListener, Camera.
        PreviewCallback {
  private static final Logger LOGGER = new Logger();

  private static final int PERMISSIONS_REQUEST = 1;

  private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
  private static final String PERMISSION_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;

  private boolean debug = false;

  private Handler handler;
  private HandlerThread handlerThread;
  private boolean useCamera2API;
  protected Bitmap rgbFrameBitmap = null;
  private int[] rgbBytes = null;
  protected int previewWidth = 0;
  protected int previewHeight = 0;
  protected Bitmap croppedBitmap = null;
  protected static final boolean SAVE_PREVIEW_BITMAP = false;
  protected long lastProcessingTimeMs;
  protected Bitmap cropCopyBitmap;
  protected ResultsView resultsView;
  protected boolean computing = false;
  protected Runnable postInferenceCallback;
  protected byte[][] yuvBytes=new byte[3][];
  protected int yRowStride;

  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    LOGGER.d("onCreate " + this);
    super.onCreate(null);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.activity_camera);

    if (hasPermission()) {
      setFragment();
    } else {
      requestPermission();
    }
  }

  /**
   * Callback for android.hardware.Camera API
   */
  @Override
  public void onPreviewFrame(final byte[] bytes, final Camera camera) {
    if (computing) {
      return;
    }
    computing = true;
    yuvBytes[0] = bytes;
    try {
      // Initialize the storage bitmaps once when the resolution is known.
      if (rgbBytes == null) {
        Camera.Size previewSize = camera.getParameters().getPreviewSize();
        previewHeight = previewSize.height;
        previewWidth = previewSize.width;
        rgbBytes = new int[previewWidth * previewHeight];
        onPreviewSizeChosen(new Size(previewSize.width, previewSize.height), 90);
      }
      ImageUtils.convertYUV420SPToARGB8888(bytes, rgbBytes, previewWidth, previewHeight, false);
    } catch (final Exception e) {
      LOGGER.e(e, "Exception!");
      return;
    }
    postInferenceCallback = new Runnable() {
      @Override
      public void run() {
        camera.addCallbackBuffer(bytes);
      }
    };
    processImageRGBbytes(rgbBytes);
  }

  /**
   * Callback for Camera2 API
   */
  @Override
  public void onImageAvailable(final ImageReader reader) {
    Image image = null;
    //We need wait until we have some size from onPreviewSizeChosen
    if (previewWidth == 0 || previewHeight == 0) {
      return;
    }
    rgbBytes = new int[previewWidth * previewHeight];
    try {
      image = reader.acquireLatestImage();

      if (image == null) {
        return;
      }

      if (computing) {
        image.close();
        return;
      }
      computing = true;
      Trace.beginSection("imageAvailable");
      final Plane[] planes = image.getPlanes();
      fillBytes(planes, yuvBytes);
      yRowStride = planes[0].getRowStride();
      final int uvRowStride = planes[1].getRowStride();
      final int uvPixelStride = planes[1].getPixelStride();
      ImageUtils.convertYUV420ToARGB8888(
          yuvBytes[0],
          yuvBytes[1],
          yuvBytes[2],
          rgbBytes,
          previewWidth,
          previewHeight,
          yRowStride,
          uvRowStride,
          uvPixelStride,
          false);
      image.close();

    } catch (final Exception e) {
      if (image != null) {
        image.close();
      }
      LOGGER.e(e, "Exception!");
      Trace.endSection();
      return;
    }
    processImageRGBbytes(rgbBytes);
    Trace.endSection();
  }

  @Override
  public synchronized void onStart() {
    LOGGER.d("onStart " + this);
    super.onStart();
  }

  @Override
  public synchronized void onResume() {
    LOGGER.d("onResume " + this);
    super.onResume();

    handlerThread = new HandlerThread("inference");
    handlerThread.start();
    handler = new Handler(handlerThread.getLooper());
  }

  @Override
  public synchronized void onPause() {
    LOGGER.d("onPause " + this);

    if (!isFinishing()) {
      LOGGER.d("Requesting finish");
      finish();
    }

    handlerThread.quitSafely();
    try {
      handlerThread.join();
      handlerThread = null;
      handler = null;
    } catch (final InterruptedException e) {
      LOGGER.e(e, "Exception!");
    }

    super.onPause();
  }

  @Override
  public synchronized void onStop() {
    LOGGER.d("onStop " + this);
    super.onStop();
  }

  @Override
  public synchronized void onDestroy() {
    LOGGER.d("onDestroy " + this);
    super.onDestroy();
  }

  protected synchronized void runInBackground(final Runnable r) {
    if (handler != null) {
      handler.post(r);
    }
  }

  @Override
  public void onRequestPermissionsResult(
      final int requestCode, final String[] permissions, final int[] grantResults) {
    switch (requestCode) {
      case PERMISSIONS_REQUEST: {
        if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED
            && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
          setFragment();
        } else {
          requestPermission();
        }
      }
    }
  }

  private boolean hasPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      return checkSelfPermission(PERMISSION_CAMERA) == PackageManager.PERMISSION_GRANTED &&
          checkSelfPermission(PERMISSION_STORAGE) == PackageManager.PERMISSION_GRANTED;
    } else {
      return true;
    }
  }

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if (shouldShowRequestPermissionRationale(PERMISSION_CAMERA) ||
          shouldShowRequestPermissionRationale(PERMISSION_STORAGE)) {
        Toast.makeText(CameraActivity.this,
            "Camera AND storage permission are required for this demo", Toast.LENGTH_LONG).show();
      }
      requestPermissions(new String[] {PERMISSION_CAMERA, PERMISSION_STORAGE}, PERMISSIONS_REQUEST);
    }
  }

  // Returns true if the device supports the required hardware level, or better.
  boolean isHardwareLevelSupported(CameraCharacteristics characteristics, int requiredLevel) {
    int deviceLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
    if (deviceLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
      return requiredLevel == deviceLevel;
    }
    // deviceLevel is not LEGACY, can use numerical sort
    return requiredLevel <= deviceLevel;
  }

  private String chooseCamera() {
    final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
      for (final String cameraId : manager.getCameraIdList()) {
        final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        // We don't use a front facing camera in this sample.
        final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
        if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
          continue;
        }

        final StreamConfigurationMap map =
            characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

        if (map == null) {
          continue;
        }

        useCamera2API = isHardwareLevelSupported(characteristics,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
        LOGGER.i("Camera API lv2?: %s", useCamera2API);
        return cameraId;
      }
    } catch (CameraAccessException e) {
      LOGGER.e(e, "Not allowed to access camera");
    }

    return null;
  }

  protected void setFragment() {
    String cameraId = chooseCamera();

    Fragment fragment;
    if (useCamera2API) {
      CameraConnectionFragment camera2Fragment =
          CameraConnectionFragment.newInstance(
              new CameraConnectionFragment.ConnectionCallback() {
                @Override
                public void onPreviewSizeChosen(final Size size, final int rotation) {
                  previewHeight = size.getHeight();
                  previewWidth = size.getWidth();
                  CameraActivity.this.onPreviewSizeChosen(size, rotation);
                }
              },
              this,
              getLayoutId(),
              getDesiredPreviewFrameSize());

      camera2Fragment.setCamera(cameraId);
      fragment = camera2Fragment;
    } else {
      fragment = new LegacyCameraConnectionFragment(this, getLayoutId());
    }

    getFragmentManager()
        .beginTransaction()
        .replace(R.id.container, fragment)
        .commit();
  }

  protected void fillBytes(final Plane[] planes, final byte[][] yuvBytes) {
    // Because of the variable row stride it's not possible to know in
    // advance the actual necessary dimensions of the yuv planes.
    for (int i = 0; i < planes.length; ++i) {
      final ByteBuffer buffer = planes[i].getBuffer();
      if (yuvBytes[i] == null) {
        LOGGER.d("Initializing buffer %d at size %d", i, buffer.capacity());
        yuvBytes[i] = new byte[buffer.capacity()];
      }
      buffer.get(yuvBytes[i]);
    }
  }

  public boolean isDebug() {
    return debug;
  }

  public void requestRender() {
    final OverlayView overlay = (OverlayView) findViewById(R.id.debug_overlay);
    if (overlay != null) {
      overlay.postInvalidate();
    }
  }

  public void addCallback(final OverlayView.DrawCallback callback) {
    final OverlayView overlay = (OverlayView) findViewById(R.id.debug_overlay);
    if (overlay != null) {
      overlay.addCallback(callback);
    }
  }

  public void onSetDebug(final boolean debug) {}

  @Override
  public boolean onKeyDown(final int keyCode, final KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
      debug = !debug;
      requestRender();
      onSetDebug(debug);
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  protected abstract void processImageRGBbytes(int[] rgbBytes ) ;
  protected abstract void onPreviewSizeChosen(final Size size, final int rotation);
  protected abstract int getLayoutId();
  protected abstract Size getDesiredPreviewFrameSize();
}


text:
// BSD License (http://www.galagosearch.org/license)
package org.galagosearch.tupleflow;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.logging.Logger;
import org.galagosearch.tupleflow.execution.Step;

/**
 * Lots of static methods here that have broad use.
 *
 * @author trevor
 */
public class Utility {
    /**
     *
If the parent directories for this file don't exist, this function creates them.

     *
     *
Often we want to create a file, but we don't yet know if the parent path has been
     * created yet.  Call this function immediately before opening a file for writing to
     * make sure those directories have been created.

     *
     * @param filename A filename that will soon be opened for writing.
     */
    public static void makeParentDirectories(String filename) {
        File parent = new File(filename).getParentFile();
        if (parent != null) {
            parent.mkdirs();
        }
    }
    /**
     * Builds a simple Sorter step that can be added to a TupleFlow stage.
     *
     * @param sortOrder An order object representing how and what to sort.
     * @return a Step object that can be added to a TupleFlow Stage.
     */
    public static Step getSorter(Order sortOrder) {
        return getSorter(sortOrder, null);
    }

    /**
     * Builds a Sorter step with a reducer that can be added to a TupleFlow stage.
     *
     * @param sortOrder An order object representing how and what to sort.
     * @param reducerClass The class of a reducer object that can reduce this data.
     * @return a Step object that can be added to a TupleFlow Stage.
     */

    public static Step getSorter(Order sortOrder, Class reducerClass) {
        Parameters p = new Parameters();
        p.add("class", sortOrder.getOrderedClass().getName());
        p.add("order", Utility.join(sortOrder.getOrderSpec()));
        if (reducerClass != null) {
            try {
                reducerClass.asSubclass(Reducer.class);
            } catch (ClassCastException e) {
                throw new IllegalArgumentException("getSorter called with a reducerClass argument " +
                                                   "which is not actually a reducer: " +
                                                   reducerClass.getName());
            }
            p.add("reducer", reducerClass.getName());
        }
        return new Step(Sorter.class, p);
    }

    /**
     * Finds a free port to listen on.  Useful for starting up internal web servers.
     * (copied from chaoticjava.com)
     */
    public static int getFreePort() throws IOException {
      ServerSocket server = new ServerSocket(0);
      int port = server.getLocalPort();
      server.close();
      return port;
    }

    public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String wrap(String t) {
        int start = 0;
        StringBuilder result = new StringBuilder();

        while (t.length() > start + 50) {
            int end = t.indexOf(" ", start + 50);

            if (end < 0) {
                break;
            }
            result.append(t, start, end);
            result.append('\n');
            start = end + 1;
        }

        result.append(t.substring(start));
        return result.toString();
    }

    public static String escape(String raw) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < raw.length(); i++) {
            char c = raw.charAt(i);

            if (c == '"') {
                builder.append(""");
            } else if (c == '&') {
                builder.append("&");
            } else if (c == '<') {
                builder.append(">");
            } else if (c == '>') {
                builder.append("<");
            } else if (c <= 127) {
                builder.append(c);
            } else {
                int unsigned = ((int) c) & 0xFFFF;

                builder.append("&#");
                builder.append(unsigned);
                builder.append(";");
            }
        }

        return builder.toString();
    }

    public static String strip(String source, String suffix) {
        if (source.endsWith(suffix)) {
            return source.substring(0, source.length() - suffix.length());
        }

        return null;
    }

    public static String makeString(byte[] word) {
        try {
            return new String(word, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is not supported by your Java Virtual Machine.");
        }
    }

    public static byte[] makeBytes(String word) {
        try {
            return word.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is not supported by your Java Virtual Machine.");
        }
    }

    /**
     *
Splits args into an array of flags and an array of parameters.

     *
     *
This method assumes that args is an array of strings, where some of those
     * strings are flags (they start with '-') and the others are non-flag arguments.
     * This splits those into two arrays so they can be processed separately.

     *
     * @param args
     * @return An array of length 2, where the first element is an array of flags
     *         and the second is an array of arguments.
     */

    public static String[][] filterFlags(String[] args) {
        ArrayList<String> flags = new ArrayList<String>();
        ArrayList<String> nonFlags = new ArrayList<String>();

        for (String arg : args) {
            if (arg.startsWith("-")) {
                flags.add(arg);
            } else {
                nonFlags.add(arg);
            }
        }

        String[][] twoArrays = new String[2][];
        twoArrays[0] = flags.toArray(new String[0]);
        twoArrays[1] = nonFlags.toArray(new String[0]);

        return twoArrays;
    }

    /**
     * For an array master, returns
     * an array containing the last master.length-index elements.
     */
    public static String[] subarray(String[] master, int index) {
        if (master.length <= index) {
            return new String[0];
        } else {
            String[] sub = new String[master.length - index];
            System.arraycopy(master, index, sub, 0, sub.length);
            return sub;
        }
    }

    /**
     * Returns a string containing all the elements of args, space delimited.
     */
    public static String join(String[] args, String delimiter) {
        String output = "";
        StringBuilder builder = new StringBuilder();

        for (String arg : args) {
            if (builder.length() > 0) {
                builder.append(delimiter);
            }
            builder.append(arg);
        }

        return builder.toString();
    }

    public static String join(String[] args) {
        return join(args, " ");
    }

    public static String caps(String input) {
        if (input.length() == 0) {
            return input;
        }
        char first = Character.toUpperCase(input.charAt(0));
        return "" + first + input.substring(1);
    }

    public static String plural(String input) {
        return input + "s";
    }

    public static int compare(int one, int two) {
        return one - two;
    }

    public static int compare(long one, long two) {
        long result = one - two;

        if (result > 0) {
            return 1;
        }
        if (result < 0) {
            return -1;
        }
        return 0;
    }

    public static int compare(double one, double two) {
        double result = one - two;

        if (result > 0) {
            return 1;
        }
        if (result < 0) {
            return -1;
        }
        return 0;
    }

    public static int compare(float one, float two) {
        float result = one - two;

        if (result > 0) {
            return 1;
        }
        if (result < 0) {
            return -1;
        }
        return 0;
    }

    public static int compare(String one, String two) {
        return one.compareTo(two);
    }

    public static int compare(byte[] one, byte[] two) {
        int sharedLength = Math.min(one.length, two.length);

        for (int i = 0; i < sharedLength; i++) {
            int a = ((int) one[i]) & 0xFF;
            int b = ((int) two[i]) & 0xFF;
            int result = a - b;

            if (result < 0) {
                return -1;
            }
            if (result > 0) {
                return 1;
            }
        }

        return one.length - two.length;
    }

    public static int hash(byte b) {
        return ((int) b) & 0xFF;
    }

    public static int hash(int i) {
        return i;
    }

    public static int hash(long l) {
        return (int) l;
    }

    public static int hash(double d) {
        return (int) (d * 100000);
    }

    public static int hash(float f) {
        return (int) (f * 100000);
    }

    public static int hash(String s) {
        return s.hashCode();
    }

    public static int hash(byte[] b) {
        int h = 0;
        for (int i = 0; i < b.length; i++) {
            h += 7 * h + b[i];
        }
        return h;
    }

    public static void deleteDirectory(File directory) throws IOException {
        for (File sub : directory.listFiles()) {
            if (sub.isDirectory()) {
                deleteDirectory(sub);
            } else {
                sub.delete();
            }
        }

        directory.delete();
    }

    public static File createTemporary() throws IOException {
        return createTemporary(1024 * 1024 * 1024);
    }

    public static long getUnixFreeSpace(String pathname) throws IOException {
        try {
            // BUGBUG: will not work on windows
            String[] command = {"df", "-Pk", pathname};
            Process process = Runtime.getRuntime().exec(command);
            InputStream procOutput = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(procOutput));

            // skip the first line
            reader.readLine();
            String line = reader.readLine();
            String[] fields = line.split("\\s+");
            reader.close();

            process.getErrorStream().close();
            process.getInputStream().close();
            process.getOutputStream().close();
            process.waitFor();

            long freeSpace = Long.parseLong(fields[3]) * 1024;
            return freeSpace;
        } catch (InterruptedException ex) {
            return 0;
        }
    }

    public static long getFreeSpace(String pathname) throws IOException {
        try {
            // this will only work in Java 1.6 or later
            Method m = File.class.getMethod("getUsableSpace");
            Long result = (Long) m.invoke(new File(pathname));
            return (long) result;
        } catch (Exception e) {
            try {
                return getUnixFreeSpace(pathname);
            } catch(Exception ex) {
                return 1024*1024*1024; // 1GB
            }
        }
    }

    public static File createTemporary(long requiredSpace) throws IOException {
        // try to find a prefs file for this
        String homeDirectory = System.getProperty("user.home");
        File prefsFile = new File(homeDirectory + "/" + ".galagotmp");
        ArrayList<String> roots = new ArrayList<String>();
        File temporary = null;

        if (prefsFile.exists()) {
            BufferedReader reader = new BufferedReader(new FileReader(prefsFile));
            String line;

            while ((line = reader.readLine()) != null) {
                roots.add(line.trim());
            }

            reader.close();
        }

        for (String root : roots) {
            long freeSpace = getFreeSpace(root);

            if (freeSpace < requiredSpace) {
                continue;
            }
            String logString = String.format("Found %6.3fMB >= %6.3fMB left on %s",
                                             freeSpace / 1048576.0, requiredSpace / 1048576.0, root);
            Logger.getLogger(Utility.class.toString()).info(logString);
            temporary = File.createTempFile("tupleflow", "", new File(root));
            break;
        }

        if (temporary == null) {
            temporary = File.createTempFile("tupleflow", "");
        }

        return temporary;
    }

    /**
     * Copies data from the input stream to the output stream.
     * @param input The input stream.
     * @param output The output stream.
     * @throws java.io.IOException
     */
    public static void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] data = new byte[65536];
        while (true) {
            int bytesRead = input.read(data);
            if (bytesRead < 0) {
                break;
            }
            output.write(data, 0, bytesRead);
        }
    }

    /**
     * Copies the data from file into the stream.  Note that this method
     * does not close the stream (in case you want to put more in it).
     *
     * @param file
     * @param stream
     * @throws java.io.IOException
     */
    public static void copyFileToStream(File file, OutputStream stream) throws IOException {
        FileInputStream input = new FileInputStream(file);
        long longLength = file.length();
        final int fiveMegabytes = 5 * 1024 * 1024;

        while (longLength > 0) {
            int chunk = (int) Math.min(longLength, fiveMegabytes);
            byte[] data = new byte[chunk];
            input.read(data, 0, chunk);
            stream.write(data, 0, chunk);
            longLength -= chunk;
        }

        input.close();
    }

    /**
     * Copies the data from the InputStream to a file, then closes both when
     * finished.
     *
     * @param stream
     * @param file
     * @throws java.io.IOException
     */
    public static void copyStreamToFile(InputStream stream, File file) throws IOException {
        FileOutputStream output = new FileOutputStream(file);
        final int oneMegabyte = 1 * 1024 * 1024;
        byte[] data = new byte[oneMegabyte];

        while (true) {
            int bytesRead = stream.read(data);

            if (bytesRead < 0) {
                break;
            }
            output.write(data, 0, bytesRead);
        }

        stream.close();
        output.close();
    }

    /**
     * Copies the data from the string s to the file.
     *
     * @param s
     * @param file
     * @throws java.io.IOException
     */
    public static void copyStringToFile(String s, File file) throws IOException {
        InputStream stream = new ByteArrayInputStream(Utility.makeBytes(s));
        Utility.copyStreamToFile(stream, file);
    }

    public static void calculateMessageDigest(File file, MessageDigest instance) throws IOException {
        FileInputStream input = new FileInputStream(file);
        final int oneMegabyte = 1024 * 1024;
        byte[] data = new byte[oneMegabyte];

        while (true) {
            int bytesRead = input.read(data);

            if (bytesRead < 0) {
                break;
            }
            instance.update(data, 0, bytesRead);
        }

        input.close();
    }

    public static HashSet<String> readFileToStringSet(File file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        HashSet<String> set = new HashSet<String>();
        String line;

        while ((line = reader.readLine()) != null) {
            set.add(line.trim());
        }

        reader.close();
        return set;
    }
}


text:
package br.odb.myshare;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import br.odb.myshare.datamodel.BarAccount;
import br.odb.myshare.datamodel.Person;

public class RegisterPeopleActivity extends Activity implements OnClickListener {

	public class PersonSpinAdapter extends ArrayAdapter<Person> {

		public PersonSpinAdapter(Context context, int textViewResourceId,
				Person[] values) {
			super(context, textViewResourceId, values);

		}
	}

	Spinner spnPeople;
	private Button btnAdd;
	private Button btnDelete;
	private Button btnNext;

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

		Intent intent = new Intent(this, ShowCreditsActivity.class);
		startActivity(intent);
		return true;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_register_people);

		spnPeople = (Spinner) findViewById(R.id.spnPerson);

		btnAdd = (Button) findViewById(R.id.btnAddPerson);
		btnAdd.setOnClickListener(this);

		btnDelete = (Button) findViewById(R.id.btnDeletePerson);
		btnDelete.setOnClickListener(this);

		btnNext = (Button) findViewById(R.id.btnGoProducts);
		btnNext.setOnClickListener(this);

		updateUI();
	}

	public void updateUI() {

		List<Person> people = BarAccount.getCurrentBarAccount().getPeople();
		Person[] persons = new Person[people.size()];
		persons = people.toArray(persons);

		spnPeople.setAdapter(new PersonSpinAdapter(this,
				android.R.layout.simple_spinner_dropdown_item, persons));

		btnDelete.setEnabled( ( spnPeople.getCount() > 0 ) );
		btnNext.setEnabled(  ( spnPeople.getCount() > 0 )  );

		if ( spnPeople.getCount() > 0 ) {

			spnPeople.setSelection( spnPeople.getCount() - 1, true );
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.register_people, menu);
		return true;
	}

	@Override
	protected void onDestroy() {

		BarAccount.getCurrentBarAccount().saveAccount( this );

		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if ( BarAccount.getCurrentBarAccount() != null )
			BarAccount.getCurrentBarAccount().saveAccount( this );

		super.onPause();
	}

	public void onClick(View v) {

		Person person;
		EditText edtPerson;

		edtPerson = (EditText) findViewById(R.id.edtPerson);

		switch (v.getId()) {

			case R.id.btnAddPerson:

				if ( edtPerson.getText().toString().length() > 0 ) {

					person = new Person(edtPerson.getText().toString());
					BarAccount.getCurrentBarAccount().addNewPerson(person);
					edtPerson.setText("");

					updateUI();

				}
				break;

			case R.id.btnDeletePerson:

				person = (Person) spnPeople.getSelectedItem();
				BarAccount.getCurrentBarAccount().removePerson(person);

				updateUI();
				break;

			case R.id.btnGoProducts:

				Intent intent = new Intent(this, RegisterProductActivity.class);
				startActivity(intent);
				break;
		}

	}
}


text:
<!DOCTYPE html>
<title>Layout Instability: parent/child moved together</title>
<link rel="help" href="https://wicg.github.io/layout-instability/" />


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ctrip.zeus.dao.mapper.WafInstallFileMapper">
  <resultMap id="BaseResultMap" type="com.ctrip.zeus.dao.entity.WafInstallFile">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="version" jdbcType="BIGINT" property="version" />
    <result column="DataChange_LastTime" jdbcType="TIMESTAMP" property="datachangeLasttime" />
  </resultMap>
  <resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="com.ctrip.zeus.dao.entity.WafInstallFile">
    <result column="file" jdbcType="LONGVARBINARY" property="file" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    id, version, DataChange_LastTime
  </sql>
  <sql id="Blob_Column_List">
    file
  </sql>
  <select id="selectByExampleWithBLOBs" parameterType="com.ctrip.zeus.dao.entity.WafInstallFileExample" resultMap="ResultMapWithBLOBs">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from waf_install_file
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    <if test="rows != null">
      <if test="offset != null">
        limit ${offset}, ${rows}
      </if>
      <if test="offset == null">
        limit ${rows}
      </if>
    </if>
  </select>
  <select id="selectByExample" parameterType="com.ctrip.zeus.dao.entity.WafInstallFileExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from waf_install_file
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    <if test="rows != null">
      <if test="offset != null">
        limit ${offset}, ${rows}
      </if>
      <if test="offset == null">
        limit ${rows}
      </if>
    </if>
  </select>
  <select id="selectByExampleSelective" parameterType="map" resultMap="ResultMapWithBLOBs">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    select
    <if test="example.distinct">
      distinct
    </if>
    <choose>
      <when test="selective != null and selective.length > 0">
        <foreach collection="selective" item="column" separator=",">
          ${column.escapedColumnName}
        </foreach>
      </when>
      <otherwise>
        id, version, DataChange_LastTime, file
      </otherwise>
    </choose>
    from waf_install_file
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
    <if test="example.orderByClause != null">
      order by ${example.orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="ResultMapWithBLOBs">
    select
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from waf_install_file
    where id = #{id,jdbcType=BIGINT}
  </select>
  <select id="selectByPrimaryKeySelective" parameterType="map" resultMap="ResultMapWithBLOBs">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    select
    <choose>
      <when test="selective != null and selective.length > 0">
        <foreach collection="selective" item="column" separator=",">
          ${column.escapedColumnName}
        </foreach>
      </when>
      <otherwise>
        id, version, DataChange_LastTime, file
      </otherwise>
    </choose>
    from waf_install_file
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from waf_install_file
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.ctrip.zeus.dao.entity.WafInstallFileExample">
    delete from waf_install_file
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into waf_install_file (version, DataChange_LastTime, file
      )
    values (#{version,jdbcType=BIGINT}, #{datachangeLasttime,jdbcType=TIMESTAMP}, #{file,jdbcType=LONGVARBINARY}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into waf_install_file
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="version != null">
        version,
      </if>
      <if test="datachangeLasttime != null">
        DataChange_LastTime,
      </if>
      <if test="file != null">
        file,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="version != null">
        #{version,jdbcType=BIGINT},
      </if>
      <if test="datachangeLasttime != null">
        #{datachangeLasttime,jdbcType=TIMESTAMP},
      </if>
      <if test="file != null">
        #{file,jdbcType=LONGVARBINARY},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.ctrip.zeus.dao.entity.WafInstallFileExample" resultType="java.lang.Long">
    select count(*) from waf_install_file
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update waf_install_file
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.version != null">
        version = #{record.version,jdbcType=BIGINT},
      </if>
      <if test="record.datachangeLasttime != null">
        DataChange_LastTime = #{record.datachangeLasttime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.file != null">
        file = #{record.file,jdbcType=LONGVARBINARY},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExampleWithBLOBs" parameterType="map">
    update waf_install_file
    set id = #{record.id,jdbcType=BIGINT},
      version = #{record.version,jdbcType=BIGINT},
      DataChange_LastTime = #{record.datachangeLasttime,jdbcType=TIMESTAMP},
      file = #{record.file,jdbcType=LONGVARBINARY}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update waf_install_file
    set id = #{record.id,jdbcType=BIGINT},
      version = #{record.version,jdbcType=BIGINT},
      DataChange_LastTime = #{record.datachangeLasttime,jdbcType=TIMESTAMP}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile">
    update waf_install_file
    <set>
      <if test="version != null">
        version = #{version,jdbcType=BIGINT},
      </if>
      <if test="datachangeLasttime != null">
        DataChange_LastTime = #{datachangeLasttime,jdbcType=TIMESTAMP},
      </if>
      <if test="file != null">
        file = #{file,jdbcType=LONGVARBINARY},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile">
    update waf_install_file
    set version = #{version,jdbcType=BIGINT},
      DataChange_LastTime = #{datachangeLasttime,jdbcType=TIMESTAMP},
      file = #{file,jdbcType=LONGVARBINARY}
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile">
    update waf_install_file
    set version = #{version,jdbcType=BIGINT},
      DataChange_LastTime = #{datachangeLasttime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>
  <select id="selectOneByExample" parameterType="com.ctrip.zeus.dao.entity.WafInstallFileExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    select
    <include refid="Base_Column_List" />
    from waf_install_file
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    limit 1
  </select>
  <select id="selectOneByExampleWithBLOBs" parameterType="com.ctrip.zeus.dao.entity.WafInstallFileExample" resultMap="ResultMapWithBLOBs">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    select
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from waf_install_file
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    limit 1
  </select>
  <select id="selectOneByExampleSelective" parameterType="map" resultMap="ResultMapWithBLOBs">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    select
    <choose>
      <when test="selective != null and selective.length > 0">
        <foreach collection="selective" item="column" separator=",">
          ${column.escapedColumnName}
        </foreach>
      </when>
      <otherwise>
        id, version, DataChange_LastTime, file
      </otherwise>
    </choose>
    from waf_install_file
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
    <if test="example.orderByClause != null">
      order by ${example.orderByClause}
    </if>
    limit 1
  </select>
  <insert id="upsertSelective" keyColumn="id" keyProperty="record.id" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile" useGeneratedKeys="true">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    insert into waf_install_file
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="version != null">
        version,
      </if>
      <if test="datachangeLasttime != null">
        DataChange_LastTime,
      </if>
      <if test="file != null">
        file,
      </if>
    </trim>
    values
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="version != null">
        #{version,jdbcType=BIGINT},
      </if>
      <if test="datachangeLasttime != null">
        #{datachangeLasttime,jdbcType=TIMESTAMP},
      </if>
      <if test="file != null">
        #{file,jdbcType=LONGVARBINARY},
      </if>
    </trim>
    on duplicate key update
    <trim suffixOverrides=",">
      <if test="id != null">
        id = #{id,jdbcType=BIGINT},
      </if>
      <if test="version != null">
        version = #{version,jdbcType=BIGINT},
      </if>
      <if test="datachangeLasttime != null">
        DataChange_LastTime = #{datachangeLasttime,jdbcType=TIMESTAMP},
      </if>
      <if test="file != null">
        file = #{file,jdbcType=LONGVARBINARY},
      </if>
    </trim>
  </insert>
  <insert id="upsert" keyColumn="id" keyProperty="id" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile" useGeneratedKeys="true">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    insert into waf_install_file
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      version,
      DataChange_LastTime,
    </trim>
    values
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      #{version,jdbcType=BIGINT},
      #{datachangeLasttime,jdbcType=TIMESTAMP},
    </trim>
    on duplicate key update
    <trim suffixOverrides=",">
      <if test="id != null">
        id = #{id,jdbcType=BIGINT},
      </if>
      version = #{version,jdbcType=BIGINT},
      DataChange_LastTime = #{datachangeLasttime,jdbcType=TIMESTAMP},
    </trim>
  </insert>
  <insert id="upsertWithBLOBs" keyColumn="id" keyProperty="id" parameterType="com.ctrip.zeus.dao.entity.WafInstallFile" useGeneratedKeys="true">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      @project https://github.com/itfsw/mybatis-generator-plugin
    -->
    insert into waf_install_file
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      version,
      DataChange_LastTime,
      file,
    </trim>
    values
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      #{version,jdbcType=BIGINT},
      #{datachangeLasttime,jdbcType=TIMESTAMP},
      #{file,jdbcType=LONGVARBINARY},
    </trim>
    on duplicate key update
    <trim suffixOverrides=",">
      <if test="id != null">
        id = #{id,jdbcType=BIGINT},
      </if>
      version = #{version,jdbcType=BIGINT},
      DataChange_LastTime = #{datachangeLasttime,jdbcType=TIMESTAMP},
      file = #{file,jdbcType=LONGVARBINARY},
    </trim>
  </insert>
</mapper>


text:
supervised_learning = False

doc = dict(
    __class__="""
Builds an Extended Isolation Forest model. Extended Isolation Forest generalizes its predecessor algorithm,
Isolation Forest. The original Isolation Forest algorithm suffers from bias due to tree branching. Extension of the
algorithm mitigates the bias by adjusting the branching, and the original algorithm becomes just a special case.
Extended Isolation Forest's attribute "extension_level" allows leveraging the generalization. The minimum value is 0 and
means the Isolation Forest's behavior. Maximum value is (numCols - 1) and stands for full extension. The rest of the
algorithm is analogical to the Isolation Forest algorithm. Each iteration builds a tree that partitions the sample
observations' space until it isolates observation. The length of the path from root to a leaf node of the resulting tree
is used to calculate the anomaly score. Anomalies are easier to isolate, and their average
tree path is expected to be shorter than paths of regular observations. Anomaly score is a number between 0 and 1.
A number closer to 0 is a normal point, and a number closer to 1 is a more anomalous point.
"""
)

examples = dict(
    categorical_encoding="""
>>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
>>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
...               "DayOfWeek", "Month", "Distance", "FlightNum"]
>>> encoding = "one_hot_explicit"
>>> airlines_eif = H2OExtendedIsolationForestEstimator(categorical_encoding = encoding,
...                                                    seed = 1234)
>>> airlines_eif.train(x = predictors,
...                   training_frame = airlines)
>>> airlines_eif.model_performance()
""",
    ignore_const_cols="""
>>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
>>> predictors = ["displacement","power","weight","acceleration","year","const_1","const_2"]
>>> cars["const_1"] = 6
>>> cars["const_2"] = 7
>>> train, valid = cars.split_frame(ratios = [.8], seed = 1234)
>>> cars_eif = H2OExtendedIsolationForestEstimator(seed = 1234,
...                                                ignore_const_cols = True)
>>> cars_eif.train(x = predictors,
...               training_frame = cars)
>>> cars_eif.model_performance()
""",
    ntrees="""
>>> titanic = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/titanic.csv")
>>> predictors = titanic.columns
>>> tree_num = [20, 50, 80, 110, 140, 170, 200]
>>> label = ["20", "50", "80", "110", "140", "170", "200"]
>>> for key, num in enumerate(tree_num):
...     titanic_eif = H2OExtendedIsolationForestEstimator(ntrees = num,
...                                                       seed = 1234,
...                                                       extension_level = titanic.dim[1] - 1)
...     titanic_eif.train(x = predictors,
...                      training_frame = titanic)
""",
    sample_size="""
>>> train = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/anomaly/ecg_discord_train.csv")
>>> eif_model = H2OExtendedIsolationForestEstimator(sample_size = 5,
...                                                 ntrees=7)
>>> eif_model.train(training_frame = train)
>>> print(eif_model)
""",
    extension_level="""
>>> train = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/anomaly/single_blob.csv")
>>> eif_model = H2OExtendedIsolationForestEstimator(extension_level = 1,
...                                                 ntrees=7)
>>> eif_model.train(training_frame = train)
>>> print(eif_model)
""",
    seed="""
>>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
>>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
...               "DayOfWeek", "Month", "Distance", "FlightNum"]
>>> eif_w_seed = H2OExtendedIsolationForestEstimator(seed = 1234)
>>> eif_w_seed.train(x = predictors,
...                        training_frame = airlines)
>>> eif_wo_seed = H2OExtendedIsolationForestEstimator()
>>> eif_wo_seed.train(x = predictors,
...                         training_frame = airlines)
>>> print(eif_w_seed)
>>> print(eif_wo_seed)
""",
    training_frame="""
>>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
>>> predictors = ["displacement","power","weight","acceleration","year"]
>>> cars_eif = H2OExtendedIsolationForestEstimator(seed = 1234,
...                                                sample_size = 256,
...                                                extension_level = cars.dim[1] - 1)
>>> cars_eif.train(x = predictors,
...                training_frame = cars)
>>> print(cars_eif)
"""
)


text:
package evg.tests.tests;

import evg.tests.model.ContactData1;
import evg.tests.model.ContactData2;
import org.testng.annotations.Test;

public class ContactCreationTests extends TestBase {

  @Test
  public void testContactCreation() {
    app.getNavigationHelper().gotoHomePage();
    app.getNavigationHelper().gotoContactCreation();
    app.getContactHelper().fillContactForm(new ContactData1("Тестов"));
    app.getContactHelper().initNextPageContactCreation();
    app.getContactHelper().fillContactForm2 (new ContactData2("hello", "привет", "middle", "nick", "address", "test1"), true);
    app.getContactHelper().initSubmitContactCreation();
    app.getNavigationHelper().gotoHomePage();
  }
}


text:
package com.asakusafw.dmdl.directio.util;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Utilities about charset and encoding.
 * @since 0.10.3
 */
public final class CharsetUtil {

    private static final Pattern PATTERN_ASCII_NOT_COMPAT = Pattern.compile("\\bUTF-(16|32)(BE|LE)?\\b"); //$NON-NLS-1$

    private static final Set<Charset> KNOWN_ASCII_NOT_COMPAT;
    static {
        KNOWN_ASCII_NOT_COMPAT = Charset.availableCharsets().values().stream()
                .filter(s -> PATTERN_ASCII_NOT_COMPAT.matcher(s.name()).find())
                .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
    }

    private CharsetUtil() {
        return;
    }

    /**
     * returns whether or not the given charset encoding is compatible with ASCII.
     * @param cs the target charset encoding
     * @return {@code true} if it is compatible, otherwise {@code false}
     */
    public static boolean isAsciiCompatible(Charset cs) {
        return !KNOWN_ASCII_NOT_COMPAT.contains(cs);
    }
}


text:
package org.github.sguzman.scala.game.scalebra.mvc.view

import org.lwjgl.Sys

/**
  * @author Salvador Guzman - sguzman
  * @group Scalebra
  * @version org.github.sguzman.scala.game.scalebra.mvc.view
  * @note This class holds all functionality needed to compute the FPS
  * @since 5/7/16 8:38 PM
  */
object FPS {
  /** time at last frame */
  var lastFrame: Long = 0L
  /** frames per second */
  var fps: Int = 0
  /** last fps time */
  var lastFPS: Long = 0L

  /**
    * Initialize FPS subsystem
    */
  def init(): Unit = {
    getDelta
    lastFPS = getTime
  }

  /**
    * Get the accurate system time
    *
    * @return The system time in milliseconds
    */
  def getTime: Long = {
    (Sys.getTime * 1000) / Sys.getTimerResolution
  }

  /**
    * Calculate the FPS and set it in the title bar
    */
  def updateFPS(): Unit = {
    if (getTime - lastFPS > 1000) {

      View.title("FPS: " + fps)
      fps = 0
      lastFPS += 1000
    }
    fps += 1
  }

  /**
    * Calculate how many milliseconds have passed
    * since last frame.
    *
    * @return milliseconds passed since last frame
    */
  def getDelta: Int = {
    val time: Long = getTime
    val delta: Int = (time - lastFrame).toInt
    lastFrame = time
    delta
  }

}


text:
/**
 */
package substationStandard.Enumerations;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

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

/**
 *
 * A representation of the literals of the enumeration 'Fault Loop Kind',
 * and utility methods for working with them.
 *
 * @see substationStandard.Enumerations.EnumerationsPackage#getFaultLoopKind()
 * @model
 * @generated
 */
public enum FaultLoopKind implements Enumerator {
	/**
	 * The 'Ph ATo Ground' literal object.
	 *
	 *
	 * @see #PH_ATO_GROUND_VALUE
	 * @generated
	 * @ordered
	 */
	PH_ATO_GROUND(0, "phAToGround", "phAToGround"),

	/**
	 * The 'Ph BTo Ground' literal object.
	 *
	 *
	 * @see #PH_BTO_GROUND_VALUE
	 * @generated
	 * @ordered
	 */
	PH_BTO_GROUND(0, "phBToGround", "phBToGround"),

	/**
	 * The 'Ph CTo Ground' literal object.
	 *
	 *
	 * @see #PH_CTO_GROUND_VALUE
	 * @generated
	 * @ordered
	 */
	PH_CTO_GROUND(0, "phCToGround", "phCToGround"),

	/**
	 * The 'Ph ATo Ph B' literal object.
	 *
	 *
	 * @see #PH_ATO_PH_B_VALUE
	 * @generated
	 * @ordered
	 */
	PH_ATO_PH_B(0, "phAToPhB", "phAToPhB"),

	/**
	 * The 'Ph BTo Ph C' literal object.
	 *
	 *
	 * @see #PH_BTO_PH_C_VALUE
	 * @generated
	 * @ordered
	 */
	PH_BTO_PH_C(0, "phBToPhC", "phBToPhC"),

	/**
	 * The 'Ph CTo Ph A' literal object.
	 *
	 *
	 * @see #PH_CTO_PH_A_VALUE
	 * @generated
	 * @ordered
	 */
	PH_CTO_PH_A(0, "phCToPhA", "phCToPhA"),

	/**
	 * The 'Other' literal object.
	 *
	 *
	 * @see #OTHER_VALUE
	 * @generated
	 * @ordered
	 */
	OTHER(0, "other", "other");

	/**
	 * The 'Ph ATo Ground' literal value.
	 *
	 *

	 * If the meaning of 'Ph ATo Ground' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PH_ATO_GROUND
	 * @model name="phAToGround"
	 * @generated
	 * @ordered
	 */
	public static final int PH_ATO_GROUND_VALUE = 0;

	/**
	 * The 'Ph BTo Ground' literal value.
	 *
	 *

	 * If the meaning of 'Ph BTo Ground' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PH_BTO_GROUND
	 * @model name="phBToGround"
	 * @generated
	 * @ordered
	 */
	public static final int PH_BTO_GROUND_VALUE = 0;

	/**
	 * The 'Ph CTo Ground' literal value.
	 *
	 *

	 * If the meaning of 'Ph CTo Ground' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PH_CTO_GROUND
	 * @model name="phCToGround"
	 * @generated
	 * @ordered
	 */
	public static final int PH_CTO_GROUND_VALUE = 0;

	/**
	 * The 'Ph ATo Ph B' literal value.
	 *
	 *

	 * If the meaning of 'Ph ATo Ph B' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PH_ATO_PH_B
	 * @model name="phAToPhB"
	 * @generated
	 * @ordered
	 */
	public static final int PH_ATO_PH_B_VALUE = 0;

	/**
	 * The 'Ph BTo Ph C' literal value.
	 *
	 *

	 * If the meaning of 'Ph BTo Ph C' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PH_BTO_PH_C
	 * @model name="phBToPhC"
	 * @generated
	 * @ordered
	 */
	public static final int PH_BTO_PH_C_VALUE = 0;

	/**
	 * The 'Ph CTo Ph A' literal value.
	 *
	 *

	 * If the meaning of 'Ph CTo Ph A' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PH_CTO_PH_A
	 * @model name="phCToPhA"
	 * @generated
	 * @ordered
	 */
	public static final int PH_CTO_PH_A_VALUE = 0;

	/**
	 * The 'Other' literal value.
	 *
	 *

	 * If the meaning of 'Other' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #OTHER
	 * @model name="other"
	 * @generated
	 * @ordered
	 */
	public static final int OTHER_VALUE = 0;

	/**
	 * An array of all the 'Fault Loop Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final FaultLoopKind[] VALUES_ARRAY =
		new FaultLoopKind[] {
			PH_ATO_GROUND,
			PH_BTO_GROUND,
			PH_CTO_GROUND,
			PH_ATO_PH_B,
			PH_BTO_PH_C,
			PH_CTO_PH_A,
			OTHER,
		};

	/**
	 * A public read-only list of all the 'Fault Loop Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<FaultLoopKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'Fault Loop Kind' literal with the specified literal value.
	 *
	 *
	 * @param literal the literal.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static FaultLoopKind get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			FaultLoopKind result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Fault Loop Kind' literal with the specified name.
	 *
	 *
	 * @param name the name.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static FaultLoopKind getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			FaultLoopKind result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Fault Loop Kind' literal with the specified integer value.
	 *
	 *
	 * @param value the integer value.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static FaultLoopKind get(int value) {
		switch (value) {
			case PH_ATO_GROUND_VALUE: return PH_ATO_GROUND;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private FaultLoopKind(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //FaultLoopKind


text:
<html>
<body>
<script src="/inspector-protocol/resources/dummy.js"></script>
</body>
</html>


text:
require 'spec_helper'

describe 'routes' do
  routes { Dummy::Application.routes }

  it 'routes to #index' do
    expect(get: '/hemmingway/pages').to route_to(action: 'index', controller: 'hemmingway/pages')
  end

  it 'routes to #index' do
    expect(get: '/hemmingway/').to route_to(action: 'index', controller: 'hemmingway/pages')
  end

  it 'routes to #show' do
    expect(get: '/hemmingway/pages/about-us').to route_to(action: 'show', controller: 'hemmingway/pages', id: 'about-us')
  end

  it 'routes to #new' do
    expect(get: '/hemmingway/pages/new').to route_to(action: 'new', controller: 'hemmingway/pages')
  end

  it 'routes to #create' do
    expect(post: '/hemmingway/pages', page: {html: 'none'}).to route_to(action: 'create', controller: 'hemmingway/pages')
  end

  it 'routes to #preview via post' do
    expect(post: '/hemmingway/pages/preview', page: {html: 'none'}).to route_to(action: 'preview', controller: 'hemmingway/pages')
  end

  it 'routes to #preview via put' do
    expect(put: '/hemmingway/pages/preview', page: {html: 'none'}).to route_to(action: 'preview', controller: 'hemmingway/pages')
  end

  it 'routes to #preview via patch' do
    expect(patch: '/hemmingway/pages/preview', page: {html: 'none'}).to route_to(action: 'preview', controller: 'hemmingway/pages')
  end

  it 'routes to #edit' do
    expect(get: '/hemmingway/pages/about-us/edit').to route_to(action: 'edit', controller: 'hemmingway/pages', id: 'about-us')
  end

  it 'routes to #update via patch' do
    expect(patch: '/hemmingway/pages/about-us').to route_to(action: 'update', controller: 'hemmingway/pages', id: 'about-us')
  end

  it 'routes to #update via put' do
    expect(put: '/hemmingway/pages/about-us').to route_to(action: 'update', controller: 'hemmingway/pages', id: 'about-us')
  end

  it 'routes to #destroy' do
    expect(delete: '/hemmingway/pages/about-us').to route_to(action: 'destroy', controller: 'hemmingway/pages', id: 'about-us')
  end

end


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Encel.Logging;

namespace Encel.Messaging
{
    public class Channel : IChannel
    {
        private readonly ICollection<object> _consumers = new Collection<object>();

        public void Send<TCommand>(TCommand message) where TCommand : ICommand
        {
            var logger = LogManager.GetLogger();

            logger.Trace(() => "Channel received command " + message.GetType().Name);

            foreach (var consumer in _consumers.OfType<IConsumer<TCommand>>())
            {
                consumer.Consume(message);

                logger.Trace(() => "Channel ran consumer " + consumer.GetType().Name);
            }
        }

        public void RegisterConsumer<TCommand>(IConsumer<TCommand> consumer) where TCommand : ICommand
        {
            if (!_consumers.Contains(consumer))
            {
                _consumers.Add(consumer);
            }
        }
    }
}


text:
package ch.ethz.inf.vs.californium.coap;

import java.util.Scanner;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * This class implements attributes of the CoRE Link Format.
 *
 * @author Matthias Kovatsch
 */
public class LinkAttribute implements Comparable<LinkAttribute> {

// Logging /////////////////////////////////////////////////////////////////////

	protected static final Logger LOG = Logger.getLogger(LinkFormat.class.getName());

// Constants ///////////////////////////////////////////////////////////////////

	public static final Pattern SEPARATOR      = Pattern.compile("\\s*;+\\s*");
	public static final Pattern ATTRIBUTE_NAME = Pattern.compile("\\w+");
	public static final Pattern QUOTED_STRING  = Pattern.compile("\\G\".*?\"");
	public static final Pattern CARDINAL       = Pattern.compile("\\G\\d+");

// Members /////////////////////////////////////////////////////////////////////

	private String name;
	private Object value;

// Constructors ////////////////////////////////////////////////////////////////

	public LinkAttribute() {

	}

	public LinkAttribute(String name, Object value) {
		this.name = name;
		this.value = value;
	}
	public LinkAttribute(String name, String value) {
		this.name = name;
		this.value = value;
	}
	public LinkAttribute(String name, int value) {
		this.name = name;
		this.value = Integer.valueOf(value);
	}
	public LinkAttribute(String name) {
		this.name = name;
		this.value = Boolean.valueOf(true);
	}

// Serialization ///////////////////////////////////////////////////////////////

	public static LinkAttribute parse(String str) {
		return parse(new Scanner(str));
	}

	public static LinkAttribute parse(Scanner scanner) {

		String name = scanner.findInLine(ATTRIBUTE_NAME);
		if (name != null) {

			LOG.finest(String.format("Parsed link attribute: %s", name));

			LinkAttribute attr = new LinkAttribute();
			attr.name = name;

			// check for name-value-pair
			if (scanner.findWithinHorizon("=", 1) != null) {

				String value = null;
				if ((value = scanner.findInLine(QUOTED_STRING)) != null) {
					attr.value = value.substring(1, value.length()-1); // trim " "
				} else if ((value = scanner.findInLine(CARDINAL)) != null) {
					attr.value = Integer.parseInt(value);
				} else if (scanner.hasNext()){
					attr.value = scanner.next();
				} else {
					attr.value = null;
				}

			} else {
				// flag attribute
				attr.value = Boolean.valueOf(true);
			}

			return attr;
		}
		return null;
	}

	public String serialize() {

		StringBuilder builder = new StringBuilder();

		// check if there's something to write
		if (name != null && value != null) {

			LOG.finest(String.format("Serializing link attribute: %s", name));

			if (value instanceof Boolean) {

				// flag attribute
				if ((Boolean)value) {
					builder.append(name);
				}

			} else {

				// name-value-pair
				builder.append(name);
				builder.append('=');

				if (value instanceof String) {
					builder.append('"');
					builder.append((String)value);
					builder.append('"');
				} else if (value instanceof Integer) {
					builder.append(((Integer)value));
				} else {
					LOG.severe(String.format("Attribute has unexpected value type: %s=%s (%s)",name, value, value.getClass().getName()));
				}
			}
		}

		return builder.toString();
	}

	public String getName() {
		return name;
	}

	public Object getValue() {
		return value;
	}

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

	public int getIntValue() {
		if (value instanceof Integer) {
			return (Integer)value;
		}
		return -1;
	}

	public String getStringValue() {
		if (value instanceof String) {
			return (String)value;
		}
		return null;
	}

	@Override
	public int compareTo(LinkAttribute o) {
		int ret = this.name.compareTo(o.getName());
		if (ret==0) {
			if (value instanceof String) {
				return this.getStringValue().compareTo(o.getStringValue());
			} else if (value instanceof Integer) {
				return this.getIntValue() - o.getIntValue();
			} else {
				return 0;
			}
		} else {
			return ret;
		}
	}
}


text:
package "clamav-daemon"
package "clamav-freshclam"

service "clamav-daemon" do
  action [:enable, :start]
  supports :status => true, :restart => true
end

service "clamav-freshclam" do
  action [:enable, :start]
  supports :status => true, :restart => true
end