text:
package windows

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"unsafe"

	"github.com/Microsoft/go-winio"
	"github.com/Microsoft/go-winio/archive/tar"
	"github.com/Microsoft/go-winio/backuptar"
	"github.com/Microsoft/hcsshim"
	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/daemon/graphdriver"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/idtools"
	"github.com/docker/docker/pkg/ioutils"
	"github.com/docker/docker/pkg/longpath"
	"github.com/docker/docker/pkg/reexec"
	"github.com/docker/go-units"
)

// filterDriver is an HCSShim driver type for the Windows Filter driver.
const filterDriver = 1

var (
	// mutatedFiles is a list of files that are mutated by the import process
	// and must be backed up and restored.
	mutatedFiles = map[string]string{
		"UtilityVM/Files/EFI/Microsoft/Boot/BCD":      "bcd.bak",
		"UtilityVM/Files/EFI/Microsoft/Boot/BCD.LOG":  "bcd.log.bak",
		"UtilityVM/Files/EFI/Microsoft/Boot/BCD.LOG1": "bcd.log1.bak",
		"UtilityVM/Files/EFI/Microsoft/Boot/BCD.LOG2": "bcd.log2.bak",
	}
)

// init registers the windows graph drivers to the register.
func init() {
	graphdriver.Register("windowsfilter", InitFilter)
	reexec.Register("docker-windows-write-layer", writeLayer)
}

type checker struct {
}

func (c *checker) IsMounted(path string) bool {
	return false
}

// Driver represents a windows graph driver.
type Driver struct {
	// info stores the shim driver information
	info hcsshim.DriverInfo
	ctr  *graphdriver.RefCounter
	// it is safe for windows to use a cache here because it does not support
	// restoring containers when the daemon dies.
	cacheMu sync.Mutex
	cache   map[string]string
}

// InitFilter returns a new Windows storage filter driver.
func InitFilter(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
	logrus.Debugf("WindowsGraphDriver InitFilter at %s", home)

	fsType, err := getFileSystemType(string(home[0]))
	if err != nil {
		return nil, err
	}
	if strings.ToLower(fsType) == "refs" {
		return nil, fmt.Errorf("%s is on an ReFS volume - ReFS volumes are not supported", home)
	}

	d := &Driver{
		info: hcsshim.DriverInfo{
			HomeDir: home,
			Flavour: filterDriver,
		},
		cache: make(map[string]string),
		ctr:   graphdriver.NewRefCounter(&checker{}),
	}
	return d, nil
}

// win32FromHresult is a helper function to get the win32 error code from an HRESULT
func win32FromHresult(hr uintptr) uintptr {
	if hr&0x1fff0000 == 0x00070000 {
		return hr & 0xffff
	}
	return hr
}

// getFileSystemType obtains the type of a file system through GetVolumeInformation
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx
func getFileSystemType(drive string) (fsType string, hr error) {
	var (
		modkernel32              = syscall.NewLazyDLL("kernel32.dll")
		procGetVolumeInformation = modkernel32.NewProc("GetVolumeInformationW")
		buf                      = make([]uint16, 255)
		size                     = syscall.MAX_PATH + 1
	)
	if len(drive) != 1 {
		hr = errors.New("getFileSystemType must be called with a drive letter")
		return
	}
	drive += `:\`
	n := uintptr(unsafe.Pointer(nil))
	r0, _, _ := syscall.Syscall9(procGetVolumeInformation.Addr(), 8, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(drive))), n, n, n, n, n, uintptr(unsafe.Pointer(&buf[0])), uintptr(size), 0)
	if int32(r0) < 0 {
		hr = syscall.Errno(win32FromHresult(r0))
	}
	fsType = syscall.UTF16ToString(buf)
	return
}

// String returns the string representation of a driver. This should match
// the name the graph driver has been registered with.
func (d *Driver) String() string {
	return "windowsfilter"
}

// Status returns the status of the driver.
func (d *Driver) Status() [][2]string {
	return [][2]string{
		{"Windows", ""},
	}
}

// Exists returns true if the given id is registered with this driver.
func (d *Driver) Exists(id string) bool {
	rID, err := d.resolveID(id)
	if err != nil {
		return false
	}
	result, err := hcsshim.LayerExists(d.info, rID)
	if err != nil {
		return false
	}
	return result
}

// CreateReadWrite creates a layer that is writable for use as a container
// file system.
func (d *Driver) CreateReadWrite(id, parent, mountLabel string, storageOpt map[string]string) error {
	return d.create(id, parent, mountLabel, false, storageOpt)
}

// Create creates a new read-only layer with the given id.
func (d *Driver) Create(id, parent, mountLabel string, storageOpt map[string]string) error {
	return d.create(id, parent, mountLabel, true, storageOpt)
}

func (d *Driver) create(id, parent, mountLabel string, readOnly bool, storageOpt map[string]string) error {
	rPId, err := d.resolveID(parent)
	if err != nil {
		return err
	}

	parentChain, err := d.getLayerChain(rPId)
	if err != nil {
		return err
	}

	var layerChain []string

	if rPId != "" {
		parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId)
		if err != nil {
			return err
		}
		if _, err := os.Stat(filepath.Join(parentPath, "Files")); err == nil {
			// This is a legitimate parent layer (not the empty "-init" layer),
			// so include it in the layer chain.
			layerChain = []string{parentPath}
		}
	}

	layerChain = append(layerChain, parentChain...)

	if readOnly {
		if err := hcsshim.CreateLayer(d.info, id, rPId); err != nil {
			return err
		}
	} else {
		var parentPath string
		if len(layerChain) != 0 {
			parentPath = layerChain[0]
		}

		if err := hcsshim.CreateSandboxLayer(d.info, id, parentPath, layerChain); err != nil {
			return err
		}

		storageOptions, err := parseStorageOpt(storageOpt)
		if err != nil {
			return fmt.Errorf("Failed to parse storage options - %s", err)
		}

		if storageOptions.size != 0 {
			if err := hcsshim.ExpandSandboxSize(d.info, id, storageOptions.size); err != nil {
				return err
			}
		}
	}

	if _, err := os.Lstat(d.dir(parent)); err != nil {
		if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil {
			logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2)
		}
		return fmt.Errorf("Cannot create layer with missing parent %s: %s", parent, err)
	}

	if err := d.setLayerChain(id, layerChain); err != nil {
		if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil {
			logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2)
		}
		return err
	}

	return nil
}

// dir returns the absolute path to the layer.
func (d *Driver) dir(id string) string {
	return filepath.Join(d.info.HomeDir, filepath.Base(id))
}

// Remove unmounts and removes the dir information.
func (d *Driver) Remove(id string) error {
	rID, err := d.resolveID(id)
	if err != nil {
		return err
	}
	os.RemoveAll(filepath.Join(d.info.HomeDir, "sysfile-backups", rID)) // ok to fail
	return hcsshim.DestroyLayer(d.info, rID)
}

// Get returns the rootfs path for the id. This will mount the dir at its given path.
func (d *Driver) Get(id, mountLabel string) (string, error) {
	logrus.Debugf("WindowsGraphDriver Get() id %s mountLabel %s", id, mountLabel)
	var dir string

	rID, err := d.resolveID(id)
	if err != nil {
		return "", err
	}
	if count := d.ctr.Increment(rID); count > 1 {
		return d.cache[rID], nil
	}

	// Getting the layer paths must be done outside of the lock.
	layerChain, err := d.getLayerChain(rID)
	if err != nil {
		d.ctr.Decrement(rID)
		return "", err
	}

	if err := hcsshim.ActivateLayer(d.info, rID); err != nil {
		d.ctr.Decrement(rID)
		return "", err
	}
	if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil {
		d.ctr.Decrement(rID)
		if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
			logrus.Warnf("Failed to Deactivate %s: %s", id, err)
		}
		return "", err
	}

	mountPath, err := hcsshim.GetLayerMountPath(d.info, rID)
	if err != nil {
		d.ctr.Decrement(rID)
		if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
			logrus.Warnf("Failed to Deactivate %s: %s", id, err)
		}
		return "", err
	}
	d.cacheMu.Lock()
	d.cache[rID] = mountPath
	d.cacheMu.Unlock()

	// If the layer has a mount path, use that. Otherwise, use the
	// folder path.
	if mountPath != "" {
		dir = mountPath
	} else {
		dir = d.dir(id)
	}

	return dir, nil
}

// Put adds a new layer to the driver.
func (d *Driver) Put(id string) error {
	logrus.Debugf("WindowsGraphDriver Put() id %s", id)

	rID, err := d.resolveID(id)
	if err != nil {
		return err
	}
	if count := d.ctr.Decrement(rID); count > 0 {
		return nil
	}
	d.cacheMu.Lock()
	delete(d.cache, rID)
	d.cacheMu.Unlock()

	if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
		return err
	}
	return hcsshim.DeactivateLayer(d.info, rID)
}

// Cleanup ensures the information the driver stores is properly removed.
func (d *Driver) Cleanup() error {
	return nil
}

// Diff produces an archive of the changes between the specified
// layer and its parent layer which may be "".
// The layer should be mounted when calling this function
func (d *Driver) Diff(id, parent string) (_ io.ReadCloser, err error) {
	rID, err := d.resolveID(id)
	if err != nil {
		return
	}

	layerChain, err := d.getLayerChain(rID)
	if err != nil {
		return
	}

	// this is assuming that the layer is unmounted
	if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
		return nil, err
	}
	prepare := func() {
		if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil {
			logrus.Warnf("Failed to Deactivate %s: %s", rID, err)
		}
	}

	arch, err := d.exportLayer(rID, layerChain)
	if err != nil {
		prepare()
		return
	}
	return ioutils.NewReadCloserWrapper(arch, func() error {
		err := arch.Close()
		prepare()
		return err
	}), nil
}

// Changes produces a list of changes between the specified layer
// and its parent layer. If parent is "", then all changes will be ADD changes.
// The layer should be mounted when calling this function
func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
	rID, err := d.resolveID(id)
	if err != nil {
		return nil, err
	}
	parentChain, err := d.getLayerChain(rID)
	if err != nil {
		return nil, err
	}

	// this is assuming that the layer is unmounted
	if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
		return nil, err
	}
	defer func() {
		if err := hcsshim.PrepareLayer(d.info, rID, parentChain); err != nil {
			logrus.Warnf("Failed to Deactivate %s: %s", rID, err)
		}
	}()

	var changes []archive.Change
	err = winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error {
		r, err := hcsshim.NewLayerReader(d.info, id, parentChain)
		if err != nil {
			return err
		}
		defer r.Close()

		for {
			name, _, fileInfo, err := r.Next()
			if err == io.EOF {
				return nil
			}
			if err != nil {
				return err
			}
			name = filepath.ToSlash(name)
			if fileInfo == nil {
				changes = append(changes, archive.Change{Path: name, Kind: archive.ChangeDelete})
			} else {
				// Currently there is no way to tell between an add and a modify.
				changes = append(changes, archive.Change{Path: name, Kind: archive.ChangeModify})
			}
		}
	})
	if err != nil {
		return nil, err
	}

	return changes, nil
}

// ApplyDiff extracts the changeset from the given diff into the
// layer with the specified id and parent, returning the size of the
// new layer in bytes.
// The layer should not be mounted when calling this function
func (d *Driver) ApplyDiff(id, parent string, diff io.Reader) (int64, error) {
	var layerChain []string
	if parent != "" {
		rPId, err := d.resolveID(parent)
		if err != nil {
			return 0, err
		}
		parentChain, err := d.getLayerChain(rPId)
		if err != nil {
			return 0, err
		}
		parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId)
		if err != nil {
			return 0, err
		}
		layerChain = append(layerChain, parentPath)
		layerChain = append(layerChain, parentChain...)
	}

	size, err := d.importLayer(id, diff, layerChain)
	if err != nil {
		return 0, err
	}

	if err = d.setLayerChain(id, layerChain); err != nil {
		return 0, err
	}

	return size, nil
}

// DiffSize calculates the changes between the specified layer
// and its parent and returns the size in bytes of the changes
// relative to its base filesystem directory.
func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
	rPId, err := d.resolveID(parent)
	if err != nil {
		return
	}

	changes, err := d.Changes(id, rPId)
	if err != nil {
		return
	}

	layerFs, err := d.Get(id, "")
	if err != nil {
		return
	}
	defer d.Put(id)

	return archive.ChangesSize(layerFs, changes), nil
}

// GetMetadata returns custom driver information.
func (d *Driver) GetMetadata(id string) (map[string]string, error) {
	m := make(map[string]string)
	m["dir"] = d.dir(id)
	return m, nil
}

func writeTarFromLayer(r hcsshim.LayerReader, w io.Writer) error {
	t := tar.NewWriter(w)
	for {
		name, size, fileInfo, err := r.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
		if fileInfo == nil {
			// Write a whiteout file.
			hdr := &tar.Header{
				Name: filepath.ToSlash(filepath.Join(filepath.Dir(name), archive.WhiteoutPrefix+filepath.Base(name))),
			}
			err := t.WriteHeader(hdr)
			if err != nil {
				return err
			}
		} else {
			err = backuptar.WriteTarFileFromBackupStream(t, r, name, size, fileInfo)
			if err != nil {
				return err
			}
		}
	}
	return t.Close()
}

// exportLayer generates an archive from a layer based on the given ID.
func (d *Driver) exportLayer(id string, parentLayerPaths []string) (io.ReadCloser, error) {
	archive, w := io.Pipe()
	go func() {
		err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error {
			r, err := hcsshim.NewLayerReader(d.info, id, parentLayerPaths)
			if err != nil {
				return err
			}

			err = writeTarFromLayer(r, w)
			cerr := r.Close()
			if err == nil {
				err = cerr
			}
			return err
		})
		w.CloseWithError(err)
	}()

	return archive, nil
}

// writeBackupStreamFromTarAndSaveMutatedFiles reads data from a tar stream and
// writes it to a backup stream, and also saves any files that will be mutated
// by the import layer process to a backup location.
func writeBackupStreamFromTarAndSaveMutatedFiles(buf *bufio.Writer, w io.Writer, t *tar.Reader, hdr *tar.Header, root string) (nextHdr *tar.Header, err error) {
	var bcdBackup *os.File
	var bcdBackupWriter *winio.BackupFileWriter
	if backupPath, ok := mutatedFiles[hdr.Name]; ok {
		bcdBackup, err = os.Create(filepath.Join(root, backupPath))
		if err != nil {
			return nil, err
		}
		defer func() {
			cerr := bcdBackup.Close()
			if err == nil {
				err = cerr
			}
		}()

		bcdBackupWriter = winio.NewBackupFileWriter(bcdBackup, false)
		defer func() {
			cerr := bcdBackupWriter.Close()
			if err == nil {
				err = cerr
			}
		}()

		buf.Reset(io.MultiWriter(w, bcdBackupWriter))
	} else {
		buf.Reset(w)
	}

	defer func() {
		ferr := buf.Flush()
		if err == nil {
			err = ferr
		}
	}()

	return backuptar.WriteBackupStreamFromTarFile(buf, t, hdr)
}

func writeLayerFromTar(r io.Reader, w hcsshim.LayerWriter, root string) (int64, error) {
	t := tar.NewReader(r)
	hdr, err := t.Next()
	totalSize := int64(0)
	buf := bufio.NewWriter(nil)
	for err == nil {
		base := path.Base(hdr.Name)
		if strings.HasPrefix(base, archive.WhiteoutPrefix) {
			name := path.Join(path.Dir(hdr.Name), base[len(archive.WhiteoutPrefix):])
			err = w.Remove(filepath.FromSlash(name))
			if err != nil {
				return 0, err
			}
			hdr, err = t.Next()
		} else if hdr.Typeflag == tar.TypeLink {
			err = w.AddLink(filepath.FromSlash(hdr.Name), filepath.FromSlash(hdr.Linkname))
			if err != nil {
				return 0, err
			}
			hdr, err = t.Next()
		} else {
			var (
				name     string
				size     int64
				fileInfo *winio.FileBasicInfo
			)
			name, size, fileInfo, err = backuptar.FileInfoFromHeader(hdr)
			if err != nil {
				return 0, err
			}
			err = w.Add(filepath.FromSlash(name), fileInfo)
			if err != nil {
				return 0, err
			}
			hdr, err = writeBackupStreamFromTarAndSaveMutatedFiles(buf, w, t, hdr, root)
			totalSize += size
		}
	}
	if err != io.EOF {
		return 0, err
	}
	return totalSize, nil
}

// importLayer adds a new layer to the tag and graph store based on the given data.
func (d *Driver) importLayer(id string, layerData io.Reader, parentLayerPaths []string) (size int64, err error) {
	cmd := reexec.Command(append([]string{"docker-windows-write-layer", d.info.HomeDir, id}, parentLayerPaths...)...)
	output := bytes.NewBuffer(nil)
	cmd.Stdin = layerData
	cmd.Stdout = output
	cmd.Stderr = output

	if err = cmd.Start(); err != nil {
		return
	}

	if err = cmd.Wait(); err != nil {
		return 0, fmt.Errorf("re-exec error: %v: output: %s", err, output)
	}

	return strconv.ParseInt(output.String(), 10, 64)
}

// writeLayer is the re-exec entry point for writing a layer from a tar file
func writeLayer() {
	home := os.Args[1]
	id := os.Args[2]
	parentLayerPaths := os.Args[3:]

	err := func() error {
		err := winio.EnableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege})
		if err != nil {
			return err
		}

		info := hcsshim.DriverInfo{
			Flavour: filterDriver,
			HomeDir: home,
		}

		w, err := hcsshim.NewLayerWriter(info, id, parentLayerPaths)
		if err != nil {
			return err
		}

		size, err := writeLayerFromTar(os.Stdin, w, filepath.Join(home, id))
		if err != nil {
			return err
		}

		err = w.Close()
		if err != nil {
			return err
		}

		fmt.Fprint(os.Stdout, size)
		return nil
	}()

	if err != nil {
		fmt.Fprint(os.Stderr, err)
		os.Exit(1)
	}
}

// resolveID computes the layerID information based on the given id.
func (d *Driver) resolveID(id string) (string, error) {
	content, err := ioutil.ReadFile(filepath.Join(d.dir(id), "layerID"))
	if os.IsNotExist(err) {
		return id, nil
	} else if err != nil {
		return "", err
	}
	return string(content), nil
}

// setID stores the layerId in disk.
func (d *Driver) setID(id, altID string) error {
	err := ioutil.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0600)
	if err != nil {
		return err
	}
	return nil
}

// getLayerChain returns the layer chain information.
func (d *Driver) getLayerChain(id string) ([]string, error) {
	jPath := filepath.Join(d.dir(id), "layerchain.json")
	content, err := ioutil.ReadFile(jPath)
	if os.IsNotExist(err) {
		return nil, nil
	} else if err != nil {
		return nil, fmt.Errorf("Unable to read layerchain file - %s", err)
	}

	var layerChain []string
	err = json.Unmarshal(content, &layerChain)
	if err != nil {
		return nil, fmt.Errorf("Failed to unmarshall layerchain json - %s", err)
	}

	return layerChain, nil
}

// setLayerChain stores the layer chain information in disk.
func (d *Driver) setLayerChain(id string, chain []string) error {
	content, err := json.Marshal(&chain)
	if err != nil {
		return fmt.Errorf("Failed to marshall layerchain json - %s", err)
	}

	jPath := filepath.Join(d.dir(id), "layerchain.json")
	err = ioutil.WriteFile(jPath, content, 0600)
	if err != nil {
		return fmt.Errorf("Unable to write layerchain file - %s", err)
	}

	return nil
}

type fileGetCloserWithBackupPrivileges struct {
	path string
}

func (fg *fileGetCloserWithBackupPrivileges) Get(filename string) (io.ReadCloser, error) {
	if backupPath, ok := mutatedFiles[filename]; ok {
		return os.Open(filepath.Join(fg.path, backupPath))
	}

	var f *os.File
	// Open the file while holding the Windows backup privilege. This ensures that the
	// file can be opened even if the caller does not actually have access to it according
	// to the security descriptor.
	err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error {
		path := longpath.AddPrefix(filepath.Join(fg.path, filename))
		p, err := syscall.UTF16FromString(path)
		if err != nil {
			return err
		}
		h, err := syscall.CreateFile(&p[0], syscall.GENERIC_READ, syscall.FILE_SHARE_READ, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
		if err != nil {
			return &os.PathError{Op: "open", Path: path, Err: err}
		}
		f = os.NewFile(uintptr(h), path)
		return nil
	})
	return f, err
}

func (fg *fileGetCloserWithBackupPrivileges) Close() error {
	return nil
}

// DiffGetter returns a FileGetCloser that can read files from the directory that
// contains files for the layer differences. Used for direct access for tar-split.
func (d *Driver) DiffGetter(id string) (graphdriver.FileGetCloser, error) {
	id, err := d.resolveID(id)
	if err != nil {
		return nil, err
	}

	return &fileGetCloserWithBackupPrivileges{d.dir(id)}, nil
}

type storageOptions struct {
	size uint64
}

func parseStorageOpt(storageOpt map[string]string) (*storageOptions, error) {
	options := storageOptions{}

	// Read size to change the block device size per container.
	for key, val := range storageOpt {
		key := strings.ToLower(key)
		switch key {
		case "size":
			size, err := units.RAMInBytes(val)
			if err != nil {
				return nil, err
			}
			options.size = uint64(size)
		default:
			return nil, fmt.Errorf("Unknown storage option: %s", key)
		}
	}
	return &options, nil
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace gView.Cmd.ClipCompactTilecache
{
    public class BundleIndex
    {
        public BundleIndex(string filename)
        {
            this.Filename = filename;
        }

        public string Filename { get; private set; }

        public bool Exists
        {
            get
            {
                return new FileInfo(this.Filename).Exists;
            }
        }

        public int TilePosition(int row, int col, out int tileLength)
        {
            if (row < 0 || row > 128 || col < 0 || col > 128)
                throw new ArgumentException("Compact Tile Index out of range");

            int indexPosition = ((row * 128) + col) * 8;

            using (FileStream fs = new FileStream(this.Filename, FileMode.Open, FileAccess.Read))
            {
                byte[] data = new byte[8];
                fs.Position = indexPosition;
                fs.Read(data, 0, 8);

                int position = BitConverter.ToInt32(data, 0);
                tileLength = BitConverter.ToInt32(data, 4);

                return position;
            }
        }
    }

    public class Bundle
    {
        public Bundle(string filename)
        {
            this.Filename = filename;

            this.Index = new BundleIndex(filename.Substring(0, filename.Length - ".tilebundle".Length) + ".tilebundlx");
        }

        public string Filename { get; private set; }
        public BundleIndex Index { get; private set; }

        public byte[] ImageData(int pos, int length)
        {
            using (FileStream fs = new FileStream(this.Filename, FileMode.Open, FileAccess.Read))
            {
                byte[] data = new byte[length];
                fs.Position = pos;
                fs.Read(data, 0, data.Length);

                return data;
            }
        }

        public int StartRow
        {
            get
            {
                string fileTitle = (new FileInfo(this.Filename)).Name;

                string rHex = fileTitle.Substring(1, 8);
                int row = int.Parse(rHex, System.Globalization.NumberStyles.HexNumber);

                return row;
            }
        }

        public int StartCol
        {
            get
            {
                string fileTitle = (new FileInfo(this.Filename)).Name;

                string cHex = fileTitle.Substring(10, 8);
                int col = int.Parse(cHex, System.Globalization.NumberStyles.HexNumber);

                return col;
            }
        }
    }

    public class CompactTilesIndexBuilder
    {
        private int[] _index = new int[128 * 128 * 2];

        public CompactTilesIndexBuilder()
        {
            InitIndex();
        }

        private void InitIndex()
        {
            for (int i = 0; i < _index.Length; i++)
                _index[i] = -1;
        }

        public void SetValue(int row, int col, int position, int length)
        {
            if (row < 0 || row > 128 || col < 0 || col > 128)
                throw new ArgumentException("Compact Tile Index out of range");

            int indexPosition = ((row * 128) + col) * 2;
            if (indexPosition > _index.Length - 2)
                throw new AggregateException("Index!!!");

            _index[indexPosition] = position;
            _index[indexPosition + 1] = length;
        }

        public void Save(string filename)
        {
            try { File.Delete(filename); }
            catch { }

            using (var stream = new FileStream(filename, FileMode.Create))
            {
                for (int i = 0; i < _index.Length; i++)
                {
                    byte[] data = BitConverter.GetBytes(_index[i]);
                    stream.Write(data, 0, data.Length);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.compute;

import com.google.api.services.compute.model.Image;
import com.google.common.base.MoreObjects;

import java.io.Serializable;
import java.util.Objects;

/**
 * Base class for Google Compute Engine image configuration. Use {@link DiskImageConfiguration} to
 * create an image from an existing Google Compute Engine disk. Use
 * {@link StorageImageConfiguration} to create an image from a file stored in Google Cloud Storage.
 */
public abstract class ImageConfiguration implements Serializable {

  private static final long serialVersionUID = -9154332316597745316L;

  private final Type type;
  private final SourceType sourceType;
  private final Long archiveSizeBytes;

  /**
   * Type of a Google Compute Engine image.
   */
  public enum Type {
    /**
     * A Google Compute Engine image created from a Google Compute Engine disk.
     */
    DISK,

    /**
     * A Google Compute Engine image created from a file saved in Google Cloud Storage.
     */
    STORAGE
  }

  /**
   * Image source type. The only admissible value is {@code RAW}.
   */
  public enum SourceType {
    RAW
  }

  /**
   * Base builder for image configurations.
   *
   * @param <T> the image configuration class
   * @param <B> the image configuration builder
   */
  public abstract static class Builder<T extends ImageConfiguration, B extends Builder<T, B>> {

    private Type type;
    private SourceType sourceType;
    private Long archiveSizeBytes;

    Builder(Type type) {
      this.type = type;
    }

    Builder(ImageConfiguration imageConfiguration) {
      this.type = imageConfiguration.type;
      this.sourceType = imageConfiguration.sourceType;
      this.archiveSizeBytes = imageConfiguration.archiveSizeBytes;
    }

    Builder(Type type, Image imagePb) {
      this.type = type;
      if (imagePb.getSourceType() != null) {
        this.sourceType = SourceType.valueOf(imagePb.getSourceType());
      }
      this.archiveSizeBytes = imagePb.getArchiveSizeBytes();
    }

    @SuppressWarnings("unchecked")
    B self() {
      return (B) this;
    }

    B setType(Type type) {
      this.type = type;
      return self();
    }

    B setSourceType(SourceType sourceType) {
      this.sourceType = sourceType;
      return self();
    }

    B setArchiveSizeBytes(Long archiveSizeBytes) {
      this.archiveSizeBytes = archiveSizeBytes;
      return self();
    }

    /**
     * Creates a configuration object.
     */
    public abstract T build();
  }

  ImageConfiguration(Builder builder) {
    this.type = builder.type;
    this.sourceType = builder.sourceType;
    this.archiveSizeBytes = builder.archiveSizeBytes;
  }

  /**
   * Returns the image's type. This method returns {@link Type#DISK} if this image was created from
   * an existing disk. This method returns {@link Type#STORAGE} if this image was created from a
   * file in Google Cloud Storage.
   */
  @Deprecated
  public Type type() {
    return getType();
  }

  /**
   * Returns the image's type. This method returns {@link Type#DISK} if this image was created from
   * an existing disk. This method returns {@link Type#STORAGE} if this image was created from a
   * file in Google Cloud Storage.
   */
  public Type getType() {
    return type;
  }

  /**
   * Returns the source type of the disk. The default and only value is {@link SourceType#RAW}.
   */
  @Deprecated
  public SourceType sourceType() {
    return getSourceType();
  }

  /**
   * Returns the source type of the disk. The default and only value is {@link SourceType#RAW}.
   */
  public SourceType getSourceType() {
    return sourceType;
  }

  /**
   * Returns the size of the image archive stored in Google Cloud Storage (in bytes).
   */
  @Deprecated
  public Long archiveSizeBytes() {
    return getArchiveSizeBytes();
  }

  /**
   * Returns the size of the image archive stored in Google Cloud Storage (in bytes).
   */
  public Long getArchiveSizeBytes() {
    return archiveSizeBytes;
  }

  /**
   * Returns a builder for the object.
   */
  public abstract Builder toBuilder();

  MoreObjects.ToStringHelper toStringHelper() {
    return MoreObjects.toStringHelper(this)
        .add("type", type)
        .add("sourceType", sourceType)
        .add("archiveSizeBytes", archiveSizeBytes);
  }

  @Override
  public String toString() {
    return toStringHelper().toString();
  }

  final int baseHashCode() {
    return Objects.hash(type, sourceType, archiveSizeBytes);
  }

  final boolean baseEquals(ImageConfiguration imageConfiguration) {
    return imageConfiguration != null
        && getClass().equals(imageConfiguration.getClass())
        && Objects.equals(toPb(), imageConfiguration.toPb());
  }

  abstract ImageConfiguration setProjectId(String projectId);

  Image toPb() {
    Image imagePb = new Image();
    if (sourceType != null) {
      imagePb.setSourceType(sourceType.name());
    }
    imagePb.setArchiveSizeBytes(archiveSizeBytes);
    return imagePb;
  }

  @SuppressWarnings("unchecked")
  static <T extends ImageConfiguration> T fromPb(Image imagePb) {
    if (imagePb.getSourceDisk() != null) {
      return (T) DiskImageConfiguration.fromPb(imagePb);
    }
    return (T) StorageImageConfiguration.fromPb(imagePb);
  }
}


text:
<!DOCTYPE html>
<html>
<head>

<script>

function boom()
{
  document.execCommand("inserthtml", false, "ABC ");
  document.execCommand("delete", false, null);
  document.execCommand("inserthtml", false, "<style>");
}

</script>
</head>

<body onload="setTimeout(boom, 0);" contenteditable="true"></body>
</html>


text:
<!DOCTYPE html>

    <title>Tipsops</title>


text:
"""rptk class loader test cases."""

from __future__ import print_function
from __future__ import unicode_literals

from helpers import default_format_classes, default_query_classes

import pytest

from rptk.base import BaseObject

class_sets = (
    default_query_classes().items(),
    default_format_classes().items(),
)

class TestClassLoader(object):
    """Test cases for rptk class loader classes."""

    @pytest.mark.parametrize("class_set", class_sets)
    def test_class_loader(self, class_set):
        """Test rptk class loader."""
        from rptk.load import ClassLoader
        loader = ClassLoader(items=class_set)
        assert isinstance(loader.class_names, list)
        for name, path in class_set:
            assert name in loader.class_names
            assert name in loader.class_info
            assert loader.class_info[name]
            assert issubclass(loader.get_class(name=name), BaseObject)
        assert isinstance(loader.classes, list)
        for cls in loader.classes:
            assert isinstance(cls, type)


text:
{% extends "admin/base.html" %}

{% block title %}Listado de especialidades{% endblock %}

{% block head %}
    {% if perms.auth.puede_eliminar_especialidad %}

    {% endif %}
{% endblock %}
{% block article %}

 Inicio

Especialidades

    {% if perms.auth.puede_agregar_especialidad %}

             Agregar especialidad

    {% endif %}
    {% if perms.auth.puede_eliminar_especialidad %}

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 Eliminar especialidad

                    ¿Está seguro que desea eliminar esta especialidad?

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                    <button id="btnDel" type="button" class="btn btn-danger">Eliminar</button>

    {% endif %}

                    Nombre

                    Carga semanal

                    Carga diaria

                    Color

                    Acciones

        {% if especialidades %}

                {% for especialidad in especialidades %}

                            {{ especialidad.nombre }}

                            {{ especialidad.carga_horaria_semanal }}

                            {{ especialidad.max_horas_diaria }}

                                {% if perms.auth.puede_editar_especialidad %}

                                {% endif %}
                                {% if perms.auth.puede_eliminar_especialidad %}

                                {% endif %}

                {% endfor %}

        {% else %}

                    No hay especialidades cargadas.

        {% endif %}

            {% if especialidades.has_previous %}

 Anterior

            {% endif %}

            {% if especialidades.has_next %}

Siguiente
            {% endif %}

{% endblock %}


text:
title: Hey... we all screw up - Part 1

----

date: 2006-10-29 20:05

----

text:

Last week was hell. At my work I'm responsible for the design, implementation, testing and sending of all email marketing communications sent to customers and prospects.  Although the average size of send is small due to list segmentation and targeting, a send can range anywhere from 10 to 100,000 contacts.  As I've already sent dozens of email blasts and communications in the past, that day last week was was no different - except that I was clearly overtired, overworked, had my mind elsewhere, and quite frankly a bit bored.

----

tags: Email Marketing, email marketing mistakes

----

categories: Email Marketing


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Neues Jb. Geol. Paläont. Abh. 106: 410.

#### Original name
null

### Remarks
null


text:
package com.mailosaur.models;

import com.google.api.client.util.DateTime;
import com.google.api.client.util.Key;

/**
 * Mailosaur virtual security device.
 */
public class OtpResult {
    /**
     * The current one-time password.
     */
	@Key
    private String code;

    /**
     * The expiry date/time of the current one-time password.
     */
    @Key
    private DateTime expires;

    /**
     * Gets the current one-time password.
     *
     * @return The current one-time password.
     */
    public String code() {
        return this.code;
    }

    /**
     * Gets the expiry date/time of the current one-time password.
     *
     * @return The expiry date/time of the current one-time password.
     */
    public DateTime expires() {
        return this.expires;
    }
}


text:
package javahibernate;

import java.util.List;
import javax.persistence.*;

/**
 * Java Persistence API (JPA)
 *
 * @author Anton Skshidlevsky
 */
public class JavaHibernate {

    private static EntityManager em = null;

    static {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaHibernatePU");
        em = emf.createEntityManager();
    }

    /**
     * Добавить нового пользователя в БД
     * @param user пользователь
     */
    public static void addUser(Users user) {
        em.getTransaction().begin();
        em.persist(user);
        em.getTransaction().commit();
    }

    /**
     * Изменить пользователя в БД
     * @param user пользователь
     */
    public static void updateUser(Users user) {
        em.getTransaction().begin();
        em.merge(user);
        em.getTransaction().commit();
    }

    /**
     * Удалить пользователя из БД
     * @param id идентификатор пользователя
     */
    public static void deleteUser(Long id) {
        em.getTransaction().begin();
        Users u = (Users) em.find(Users.class, id);
        em.remove(u);
        em.getTransaction().commit();
    }

    /**
     * Найти пользователя по его ID
     * @param id
     * @return идентификатор пользователя
     */
    public static Users findByPrimaryKey(Long id) {
        em.getTransaction().begin();
        Users gs = (Users) em.find(Users.class, id);
        em.getTransaction().commit();
        return gs;
    }

    /**
     * Получить списко всех пользователей
     * @return список пользователей
     */
    public static List<Users> findAll() {
        em.getTransaction().begin();
        Query queryResult = em.createQuery("from Users");
        List<Users> allSummaries = queryResult.getResultList();
        em.getTransaction().commit();
        return allSummaries;
    }

    /**
     * @param args не используется
     */
    public static void main(String[] args) {
        Users user;

        // Добавить нового пользователя
        user = new Users();
        user.setName("Legolas");
        user.setPasswd(MD5("secret1"));
        addUser(user);

        // Изменить существующего пользователя
        user = new Users();
        user.setId(1l);
        user.setName("Gandalf");
        user.setPasswd(MD5("secret2"));
        updateUser(user);

        // Удалить пользователя с идентификатором 2
        deleteUser(2l);

        // Получить список всех записей
        for (Users u: findAll()) {
            System.out.println(u.getName());
        }
    }

    /**
     * Перевод строки в MD5 хеш
     * @param s строка
     * @return MD5 хеш
     */
    private static String MD5(String s) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(s.getBytes());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            // ignore
        }
        return null;
    }
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {type LocalizedString} from './UIString.js';

/**
 * Represents an error that might become visible to the user. Where errors
 * might be surfaced to the user (such as by displaying the message to the
 * console), this class should be used to enforce that the message is
 * localized on the way in.
 */
export class UserVisibleError extends Error {
  readonly message: LocalizedString;

  constructor(message: LocalizedString) {
    super(message);
    this.message = message;
  }
}

export function isUserVisibleError(error: unknown): error is UserVisibleError {
  if (typeof error === 'object' && error !== null) {
    return error instanceof UserVisibleError;
  }

  return false;
}


text:
package gryizabawy;

public class NieudanyPsikusException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

}


text:
package org.apache.maven.plugins.shade.relocation;

import junit.framework.TestCase;

import java.util.Collections;

public class SimpleRelocatorParameterTest
    extends TestCase
{

    protected void setUp()
        throws Exception
    {
        super.setUp();
    }

    public void testThatNullPatternInConstructorShouldNotThrowNullPointerException()
    {
        constructThenFailOnNullPointerException( null, "" );
    }

    public void testThatNullShadedPatternInConstructorShouldNotThrowNullPointerException()
    {
        constructThenFailOnNullPointerException( "", null );
    }

    private void constructThenFailOnNullPointerException( String pattern, String shadedPattern )
    {
        try
        {
            new SimpleRelocator( pattern, shadedPattern, Collections.<String> emptyList(), Collections.<String> emptyList() );
        }
        catch ( NullPointerException e )
        {
            fail( "Constructor should not throw null pointer exceptions" );
        }
    }
}


text:
/**
 * Base classes for template Auto-configuration.
 */
package org.springframework.boot.autoconfigure.template;


text:
#include <hx/Native.h>
#include <api/HaxeObject.h>
#include <api/HaxeApi.h>

struct MyStruct
{
   hx::Ref<api::HaxeObject *> haxeRef;
};

extern void __hxcpp_collect(bool inMajor);

int main(int argc, char **argv)
{
   MyStruct *myStruct = new MyStruct();

   const char *err = hx::Init();
   if (err)
   {
      printf("Could not initialize library: %s\n", err);
      return -1;
   }
   else
   {
      hx::NativeAttach autoAttach;

      api::HaxeObject *obj = api::HaxeApi::createBase();
      obj->setName("child");

      myStruct->haxeRef = obj;
      obj->setName("Name");

      api::HaxeObject *child = obj->createChild();
   }

   {
      hx::NativeAttach autoAttach;
      __hxcpp_collect(true);
   }

   {
      hx::NativeAttach autoAttach;
      if (myStruct->haxeRef->getName()!="Name")
      {
         printf("Could not get value back (%s)\n", myStruct->haxeRef->getName().c_str() );
         return -1;
      }
   }

   {
      hx::NativeAttach autoAttach0;
      hx::NativeAttach autoAttach1;
      hx::NativeAttach autoAttach2;
      hx::NativeAttach autoAttach3;
      if (hx::GcGetThreadAttachedCount()!=4)
      {
         printf("Bad attach count\n");
         return -1;
      }
   }
   if (hx::GcGetThreadAttachedCount()!=0)
   {
      printf("Bad clear attach count\n");
      return -1;
   }

   printf("all good\n");
   return 0;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>cmput301f17t26.smores.all_models</title>
<meta name="date" content="2017-11-25">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

cmput301f17t26.smores.all_models

Classes

Feed

Habit

HabitEvent

Pair

Request

User


text:
module TallWheel where

import qualified XMonad.StackSet as W

import Imports

-- | Identical to XMonad's builtin tiling mode, 'Tall', except that the
-- order is reversed for the left hand stack. This makes it feel like
-- you're rotating through a wheel of windows, rather than manipulating
-- stacks. Supports 'Shrink', 'Expand' and 'IncMasterN'.
data TallWheel a = TallWheel
  { tallWheelNMaster :: !Int
  -- ^ The default number of windows in the master pane (default: 1)
  , tallWheelRatioIncrement :: !Rational
  -- ^ Percent of screen to increment by when resizing panes (default: 3/100)
  , tallWheelRatio :: !Rational
  -- ^ Default proportion of screen occupied by master pane (default: 1/2)
  }
  deriving (Show, Read)

instance LayoutClass TallWheel a where
    pureLayout (TallWheel nmaster _ frac) r s = zip ws rs
      where ws = W.integrate s
            rs = tileWheel frac r nmaster (length ws)

    pureMessage (TallWheel nmaster delta frac) m =
            msum [fmap resize     (fromMessage m)
                 ,fmap incmastern (fromMessage m)]

      where resize Shrink = TallWheel nmaster delta (max 0 $ frac-delta)
            resize Expand = TallWheel nmaster delta (min 1 $ frac+delta)
            incmastern (IncMasterN d) = TallWheel (max 0 (nmaster+d)) delta frac

    description _ = "TallWheel"

-- | Compute the positions for windows using the default two-pane tiling
-- algorithm.
--
-- The screen is divided into two panes. All clients are
-- then partioned between these two panes. One pane, the master, by
-- convention has the least number of windows in it.
tileWheel
    :: Rational  -- ^ @frac@, what proportion of the screen to devote to the master area
    -> Rectangle -- ^ @r@, the rectangle representing the screen
    -> Int       -- ^ @nmaster@, the number of windows in the master pane
    -> Int       -- ^ @n@, the total number of windows to tile
    -> [Rectangle]
tileWheel f r nmaster n = if n <= nmaster || nmaster == 0
    then splitVertically n r
    else reverse (splitVertically nmaster r1) ++
         splitVertically (n-nmaster) r2
  where (r1,r2) = splitHorizontallyBy f r


text:
package org.gearvrf.x3d.node;

import org.gearvrf.x3d.data_types.SFColor;
import org.gearvrf.x3d.data_types.SFFloat;

public class Material extends X3DNode implements Cloneable
{

    private static final String TAG = Material.class.getSimpleName();
    private static float AMBIENTINTENSITY_DEFAULT_VALUE = 0.2f;
    private static float[] DIFFUSECOLOR_DEFAULT_VALUE = {0.8f, 0.8f, 0.8f};
    private static float[] EMISSIVECOLOR_DEFAULT_VALUE = {0.0f, 0.0f, 0.0f};
    private static float SHININESS_DEFAULT_VALUE = 0.2f;
    private static float[] SPECULARCOLOR_DEFAULT_VALUE = {0.0f, 0.0f, 0.0f};
    private static float TRANSPARENCY_DEFAULT_VALUE = 0.0f;

    SFFloat ambientIntensity = new SFFloat( AMBIENTINTENSITY_DEFAULT_VALUE );
    SFColor diffuseColor = new SFColor(DIFFUSECOLOR_DEFAULT_VALUE[0], DIFFUSECOLOR_DEFAULT_VALUE[1],  DIFFUSECOLOR_DEFAULT_VALUE[2]  );
    SFColor emissiveColor = new SFColor(EMISSIVECOLOR_DEFAULT_VALUE[0], EMISSIVECOLOR_DEFAULT_VALUE[1], EMISSIVECOLOR_DEFAULT_VALUE[2] );
    SFFloat shininess = new SFFloat( SHININESS_DEFAULT_VALUE );
    SFColor specularColor = new SFColor(SPECULARCOLOR_DEFAULT_VALUE[0], SPECULARCOLOR_DEFAULT_VALUE[1], SPECULARCOLOR_DEFAULT_VALUE[2] );
    SFFloat transparency = new SFFloat( TRANSPARENCY_DEFAULT_VALUE );

    public Material() {
    }

    public Material(float ambientIntensity, float[] diffuseColor, float[] emissiveColor,
                    float shininess, float[] specularColor, float transparency) {
        setAmbientIntensity( ambientIntensity );
        setDiffuseColor( diffuseColor );
        setEmissiveColor( emissiveColor );
        setShininess( shininess );
        setSpecularColor( specularColor );
        setTransparency( transparency );
    }

    public Material(float ambientIntensity, float[] diffuseColor, float[] emissiveColor,
                    float shininess, float[] specularColor, float transparency, String DEF) {
        setAmbientIntensity( ambientIntensity );
        setDiffuseColor( diffuseColor );
        setEmissiveColor( emissiveColor );
        setShininess( shininess );
        setSpecularColor( specularColor );
        setTransparency( transparency );
        setDEF( DEF );
    }

    public Material clone() throws
            CloneNotSupportedException
    {
        try {
            Material cloneObj = (Material) super.clone();
            cloneObj.ambientIntensity = this.ambientIntensity.clone();
            cloneObj.diffuseColor = this.diffuseColor.clone();
            cloneObj.emissiveColor = this.emissiveColor.clone();
            cloneObj.shininess = this.shininess.clone();
            cloneObj.specularColor = this.specularColor.clone();
            cloneObj.transparency = this.transparency.clone();
            return cloneObj;
        }
        catch (CloneNotSupportedException e) {
        }
        return null;
    }

    /**
     * Provide float value within allowed range of [0,1] from inputOutput SFFloat field named ambientIntensity.
     * @return
     */
    public float getAmbientIntensity() {
        return ambientIntensity.getValue();
    }

    /**
     * Provide array of 3-tuple float results using RGB values [0..1] using RGB values [0..1] from inputOutput SFColor field named diffuseColor.
     * @return
     */
    public float[] getDiffuseColor() {
        float[] _diffuseColor = {this.diffuseColor.getRed(), this.diffuseColor.getGreen(), this.diffuseColor.getBlue()};
        return _diffuseColor;
    }

    /**
     * Provide array of 3-tuple float results using RGB values [0..1] using RGB values [0..1] from inputOutput SFColor field named emissiveColor.
     * @return
     */
    public float[] getEmissiveColor() {
        float[] _emissiveColor = {this.emissiveColor.getRed(), this.emissiveColor.getGreen(), this.emissiveColor.getBlue()};
        return _emissiveColor;
    }

    /**
     * Provide float value within allowed range of [0,1] from inputOutput SFFloat field named shininess.
     * @return
     */
    public float getShininess() {
        return shininess.getValue();
    }

    /**
     * Provide array of 3-tuple float results using RGB values [0..1] using RGB values [0..1] from inputOutput SFColor field named specularColor.
     * @return
     */
    public float[] getSpecularColor() {
        float[] _specularColor = {this.specularColor.getRed(), this.specularColor.getGreen(), this.specularColor.getBlue()};
        return _specularColor;
    }

    /**
     * Provide float value within allowed range of [0,1] from inputOutput SFFloat field named transparency.
     * @return
     */
    public float getTransparency() {
        return transparency.getValue();
    }

    /**
     * Assign float value within allowed range of [0,1] to inputOutput SFFloat field named ambientIntensity.
     * @param newValue
     */
    public void setAmbientIntensity(float newValue) {
        this.ambientIntensity.setValue( newValue );
    }

    /**
     * Assign 3-tuple float array using RGB values [0..1] using RGB values [0..1] to inputOutput SFColor field named diffuseColor.
     * @param newValue
     */
    public void setDiffuseColor(float[] newValue) {
        this.diffuseColor.setValue( newValue[0], newValue[1], newValue[2]);
    }

    /**
     * Assign 3-tuple float array using RGB values [0..1] using RGB values [0..1] to inputOutput SFColor field named emissiveColor.
     * @param newValue
     */
    public void setEmissiveColor(float[] newValue) {
        this.emissiveColor.setValue( newValue[0], newValue[1], newValue[2]);
    }

    /**
     * Assign float value within allowed range of [0,1] to inputOutput SFFloat field named shininess.
     * @param newValue
     */
    public void setShininess(float newValue) {
        this.shininess.setValue( newValue );
    }

    /**
     * Assign 3-tuple float array using RGB values [0..1] using RGB values [0..1] to inputOutput SFColor field named specularColor.
     * @param newValue
     */
    public void setSpecularColor(float[] newValue) {
        this.specularColor.setValue( newValue[0], newValue[1], newValue[2]);
    }

    /**
     * Assign float value within allowed range of [0,1] to inputOutput SFFloat field named transparency.
     * @param newValue
     */
    public void setTransparency(float newValue) {
        this.transparency.setValue( newValue );
    }

    /**
     * Assign String value to inputOutput SFString field named DEF.
     * @param newValue
     */
    public void setDEF(String newValue) {
        super.setDEF(newValue);
    }

    /**
     * Assign String value to inputOutput SFString field named USE.
     * @param newValue
     */
    public void setUSE(String newValue) {
        super.setUSE(newValue);
    }

    //TODO: the following methods are not implemented
    // getMetadata()
    // setCssClass(java.lang.String newValue)
    // setMetadata(X3DMetadataObject newValue)

} // end Material


text:
<?php

namespace Youwe\FileManagerBundle;

/**
 * Class YouweFileManagerEvents
 * @package Youwe\FileManagerEvents
 */
final class YouweFileManagerEvents
{
    const AFTER_FILE_UPLOADED = 'after.file.uploaded';
    const AFTER_FILE_MOVED = 'after.file.moved';
    const AFTER_FILE_RENAMED = 'after.file.renamed';
    const AFTER_FILE_DELETED = 'after.file.deleted';
    const AFTER_FILE_PASTED = 'after.file.pasted';
    const AFTER_FILE_EXTRACTED = 'after.file.extracted';

    const BEFORE_FILE_UPLOADED = 'before.file.uploaded';
    const BEFORE_FILE_MOVED = 'before.file.moved';
    const BEFORE_FILE_RENAMED = 'before.file.renamed';
    const BEFORE_FILE_DELETED = 'before.file.deleted';
    const BEFORE_FILE_PASTED = 'before.file.pasted';
    const BEFORE_FILE_EXTRACTED = 'before.file.extracted';

    const BEFORE_FILE_DIR_CREATED = 'before.file.dir.created';
    const AFTER_FILE_DIR_CREATED = 'after.file.dir.created';
}


text:
module Ricordami
  Error                   = Class.new(StandardError)
  NotFound                = Class.new(Error)
  AttributeNotSupported   = Class.new(Error)
  ReadOnlyAttribute       = Class.new(Error)
  InvalidIndexDefinition  = Class.new(Error)
  ModelHasBeenDeleted     = Class.new(Error)
  TypeNotSupported        = Class.new(Error)
  MissingIndex            = Class.new(Error)
  LockTimeout             = Class.new(Error)
  EventNotSupported       = Class.new(Error)
  OptionValueInvalid      = Class.new(Error)
  MissingMandatoryArgs    = Class.new(Error)
  OptionNotAllowed        = Class.new(Error)
end


text:
alter table ContextMappingInfo add column OWNER_ID varchar(255);
update ContextMappingInfo set OWNER_ID = (select externalId from ProcessInstanceLog where processInstanceId = cast(CONTEXT_ID as DECIMAL(19,0)));

create table AuditTaskImpl (
        id bigint not null auto_increment,
        activationTime date,
        actualOwner varchar(255),
        createdBy varchar(255),
        createdOn date,
        deploymentId varchar(255),
        description varchar(255),
        dueDate date,
        name varchar(255),
        parentId bigint not null,
        priority integer not null,
        processId varchar(255),
        processInstanceId bigint not null,
        processSessionId integer not null,
        status varchar(255),
        taskId bigint,
        primary key (id)
) ENGINE=InnoDB;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:id="@+id/rowLayout"
    android:orientation="horizontal">
    <com.android.volley.toolbox.NetworkImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/SrowIcon"
        android:paddingLeft="6dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="4dp"
        android:textColor="@color/primary_text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/SrowText"
        android:text="@string/search_text"/>
</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace TraktSharp.Entities {

	/// A summary of user ratings for an item
	[Serializable]
	public class TraktRatings {

		/// The average rating
		[JsonProperty(PropertyName = "rating")]
		public decimal? Rating { get; set; }

		/// The number of votes cast to arrive at the average rating
		[JsonProperty(PropertyName = "votes")]
		public int Votes { get; set; }

		/// The distribution of votes
		[JsonProperty(PropertyName = "distribution")]
		public Dictionary<string, int> Distribution { get; set; }

	}

}


text:
<?php

class Mock_Database_Drivers_Sqlite extends Mock_Database_DB_Driver
{

    /**
     * Instantiate the database driver
     *
     * @param
     *            string DB Driver class name
     * @param
     *            array DB configuration to set
     * @return void
     */
    public function __construct($config = array())
    {
        parent::__construct('CI_DB_sqlite3_driver', $config);
    }
}


text:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- The main content view -->

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->

    <LinearLayout
        android:id="@+id/drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:orientation="vertical"
        android:background="#00000000"
       >

        <ListView
            android:id="@+id/drawer_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="15dp"
            android:choiceMode="singleChoice"
            android:listSelector="#80333333"
            android:dividerHeight="0dp"
            android:textColor="@android:color/white"
            />
    </LinearLayout>

</android.support.v4.widget.DrawerLayout>


text:
package org.codegist.common.log;

import android.util.Log;

import java.io.Serializable;

import static java.lang.String.format;

/**
 * @author laurent.gilles@codegist.org
 */
public class LogCatLogger extends AbstractLogger implements Serializable {

    static final String LOGGER_TAG = LogCatLogger.class.getName() + ".TAG";
    private static final String TAG = System.getProperty(LOGGER_TAG, "CodeGist");
    private final String name;

    public LogCatLogger(String name) {
        this.name = name;
    }

    private String msg(Object o){
        return format("%s: %s", name , o);
    }

    @Override
    protected void logError(Object message, Throwable e) {
        Log.e(TAG, msg(message), e);
    }

    @Override
    protected void logError(Object message) {
        Log.e(TAG, msg(message));
    }

    @Override
    protected void logWarn(Object message, Throwable e) {
        Log.w(TAG, msg(message), e);
    }

    @Override
    protected void logWarn(Object message) {
        Log.w(TAG, msg(message));
    }

    @Override
    protected void logInfo(Object message, Throwable e) {
        Log.i(TAG, msg(message), e);
    }

    @Override
    protected void logInfo(Object message) {
        Log.i(TAG, msg(message));
    }

    @Override
    protected void logDebug(Object message, Throwable e) {
        Log.d(TAG, msg(message), e);
    }

    @Override
    protected void logDebug(Object message) {
        Log.d(TAG, msg(message));
    }

    @Override
    protected void logTrace(Object message, Throwable e) {
        Log.v(TAG, msg(message), e);
    }

    @Override
    protected void logTrace(Object message) {
        Log.v(TAG, msg(message));
    }

    @Override
    public boolean isErrorOn() {
        return Log.isLoggable(TAG, Log.ERROR);
    }

    @Override
    public boolean isWarnOn() {
        return Log.isLoggable(TAG, Log.WARN);
    }

    @Override
    public boolean isInfoOn() {
        return Log.isLoggable(TAG, Log.INFO);
    }

    @Override
    public boolean isDebugOn() {
        return Log.isLoggable(TAG, Log.DEBUG);
    }

    @Override
    public boolean isTraceOn() {
        return Log.isLoggable(TAG, Log.VERBOSE);
    }
}


text:
SCRIPTDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
EXAMPLESDIR=$SCRIPTDIR/../../examples
TCPAPPDIR=$SCRIPTDIR/../apps/tcp
A8_TEST_SUITE=$1
if [ "$A8_TEST_SUITE" == "examples" ]; then
    PRODUCTPAGE_V1_OUTPUT="productpage_v1.html"
    PRODUCTPAGE_V2_OUTPUT="productpage_v2.html"
    PRODUCTPAGE_V3_OUTPUT="productpage_v3.html"
    PRODUCTPAGE_RULEMATCH="productpage_rulematch.html"
    RULESDIR=$EXAMPLESDIR
else
    PRODUCTPAGE_V1_OUTPUT="productpage_v1.json"
    PRODUCTPAGE_V2_OUTPUT="productpage_v2.json"
    PRODUCTPAGE_V3_OUTPUT="productpage_v3.json"
    PRODUCTPAGE_RULEMATCH="productpage_rulematch.json"
    TCPHELLOWORLD_OUTPUT="tcphelloworld_output"
    RULESDIR=$SCRIPTDIR
fi
# docker or k8s
if [ -z "$A8_CONTAINER_ENV" ]; then
    A8_CONTAINER_ENV="docker"
fi
ENV=$A8_CONTAINER_ENV

dump_debug() {
    if [ "$ENV" == "k8s" ]; then
        kubectl get pods
        kubectl get routingrule
        kubectl get routingrule -o json
        GATEWAY_PODNAME=$(kubectl get pods | grep gateway | awk '{print $1}')
        kubectl logs $GATEWAY_PODNAME
        kubectl exec -it $GATEWAY_PODNAME cat /etc/envoy/envoy.json
        kubectl exec -it $GATEWAY_PODNAME tail /var/log/a8_access.log
        kubectl exec -it $GATEWAY_PODNAME curl localhost:6500/v1/clusters/blah/blah
        kubectl exec -it $GATEWAY_PODNAME curl localhost:6500/v1/routes/blah/blah/blah
        PRODUCTPAGE_PODNAME=$(kubectl get pods | grep productpage | awk '{print $1}')
        kubectl logs $PRODUCTPAGE_PODNAME -c productpage
        kubectl logs $PRODUCTPAGE_PODNAME -c serviceproxy
        RULES_PODNAME=$(kubectl get pods | grep rules | awk '{print $1}')
        kubectl logs $RULES_PODNAME
    fi
}

jsondiff() {
    # Sort JSON fields, or fallback to original text
    file1=$(jq -S . $1 2> /dev/null) || file1=$(cat $1)
    file2=$(jq -S . $2 2> /dev/null) || file2=$(cat $2)

    # Diff, but ignore all whitespace since
    diff -Ewb <(echo $file1) <(echo $file2) &>/dev/null
}

check_output_equality() {
    REF_OUTPUT_FILE="$1"
    ACTUAL_OUTPUT_FILE="$2"
    if [ "$A8_TEST_SUITE" == "examples" ]; then
	    diff $REF_OUTPUT_FILE $ACTUAL_OUTPUT_FILE > /dev/null
    else
	    jsondiff $REF_OUTPUT_FILE $ACTUAL_OUTPUT_FILE > /dev/null
    fi

    if [ $? -gt 0 ]; then
        return 1
    fi
    return 0
}

# Call the specified endpoint and compare against expected output
# Ensure the % falls within the expected range
check_routing_rules() {
    COMMAND_INPUT="$1"
    EXPECTED_OUTPUT1="$2"
    EXPECTED_OUTPUT2="$3"
    EXPECTED_PERCENT="$4"
    MAX_LOOP=5
    routing_retry_count=1
    COMMAND_INPUT="${COMMAND_INPUT} >/tmp/routing.tmp"

    while [  $routing_retry_count -le $((MAX_LOOP)) ]; do
        v1_count=0
        v2_count=0
        for count in {1..100}
        do
            temp_var1=$(eval $COMMAND_INPUT)
            check_output_equality $EXPECTED_OUTPUT1 "/tmp/routing.tmp"
            if [ $? -eq 0 ]; then
                (( v1_count=v1_count+1 ))
            else
                check_output_equality $EXPECTED_OUTPUT2 "/tmp/routing.tmp"
                if [ $? -eq 0 ]; then
                    (( v2_count=v2_count+1 ))
                fi
            fi
        done
        echo "    v1 was hit: "$v1_count" times"
        echo "    v2 was hit: "$v2_count" times"
        echo ""

        EXPECTED_V1_PERCENT=$((100-$EXPECTED_PERCENT))
        ADJUST=5
        if [ $v1_count -lt $(($EXPECTED_V1_PERCENT-$ADJUST)) ] || [  $v1_count -gt $(($EXPECTED_V1_PERCENT+$ADJUST)) ]; then
            echo "  The routing did not meet the rule that was set, try again."
            (( routing_retry_count=routing_retry_count+1 ))
        else
            # Test passed, time to exit the loop
            routing_retry_count=100
        fi

        if [ $routing_retry_count -eq $((MAX_LOOP+1)) ]; then
            echo "  Test failed"
            echo ""
            return 1
        elif [ $routing_retry_count -eq 100 ]; then
            echo "  Passed test"
            echo ""
        fi
    done
    return 0
}

A8CLI=$SCRIPTDIR/../../bin/a8ctl-linux

. $SCRIPTDIR/testing-common.sh

cleanup_all_rules
sleep 30

######Verify services have default route#######
echo "testing default route behavior.."
MAX_LOOP=5
retry_count=1
while [  $retry_count -le $((MAX_LOOP)) ]; do
    response=$(curl --write-out %{http_code} --silent --output /dev/null http://localhost:32000/productpage/productpage)
    if [ $response -ne 200 ]; then
        (( retry_count=retry_count+1 ))
        if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
            exit 1
        fi
        echo "failed, retrying"
        echo "Prior to creating any rules, services are unreachable."
        sleep 10
    else
        break
    fi
done
echo "works!"

############Test TCP Bridge in Envoy##############
# Only supported in Docker environment currently
if [ "$ENV" == "docker" ] && [ "$A8_TEST_ENV" == "testing" ]; then
    echo "testing tcp bridge in envoy..."
    retry_count=1
    while [  $retry_count -le $((MAX_LOOP)) ]; do
        echo  "Sending a message to tcphelloworld, expecting same words echoing back..."
        curl -s localhost:32000/productpage/tcp > /tmp/$TCPHELLOWORLD_OUTPUT
        diff $SCRIPTDIR/$TCPHELLOWORLD_OUTPUT /tmp/$TCPHELLOWORL_OUTPUT

        if [ $? -gt 0 ]; then
            echo "failed."
	    echo "The message received does not match the message sent to service"
	    exit 1
        else
	    break
        fi
    done
    echo "works!"
fi
######Version Routing##############
echo "testing version routing.."
MAX_LOOP=5
retry_count=1

create_rule $RULESDIR/bookinfo-default-route-details.yaml
create_rule $RULESDIR/bookinfo-default-route-productpage.yaml
create_rule $RULESDIR/bookinfo-default-route-ratings.yaml
create_rule $RULESDIR/bookinfo-default-route-reviews.yaml
create_rule $RULESDIR/bookinfo-jason-reviews-v2-route-rules.yaml

sleep 30

while [  $retry_count -le $((MAX_LOOP)) ]; do
    echo -n "injecting traffic for user=shriram, expecting productpage_v1.."
    curl -s -b 'foo=bar;user=shriram;x' http://localhost:32000/productpage/productpage >/tmp/$PRODUCTPAGE_V1_OUTPUT

    if [ "$A8_TEST_SUITE" == "examples" ]; then
	    diff $SCRIPTDIR/$PRODUCTPAGE_V1_OUTPUT /tmp/$PRODUCTPAGE_V1_OUTPUT
    else
	    jsondiff $SCRIPTDIR/$PRODUCTPAGE_V1_OUTPUT /tmp/$PRODUCTPAGE_V1_OUTPUT
    fi

    if [ $? -gt 0 ]; then
        (( retry_count=retry_count+1 ))
        if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
            exit 1
        fi
        echo "failed, retrying"
        echo "Productpage not match productpage_v1 after setting route to reviews:v2 for user=shriram in version routing test phase"
	dump_debug
	sleep 10
    else
        break
    fi
done
echo "works!"

retry_count=1
while [  $retry_count -le $((MAX_LOOP)) ]; do
    echo -n "injecting traffic for user=jason, expecting productpage_v2.."
    curl -s -b 'foo=bar;user=jason;ding=dong;x' http://localhost:32000/productpage/productpage >/tmp/$PRODUCTPAGE_V2_OUTPUT

    if [ "$A8_TEST_SUITE" == "examples" ]; then
	diff $SCRIPTDIR/$PRODUCTPAGE_V2_OUTPUT /tmp/$PRODUCTPAGE_V2_OUTPUT
    else
	jsondiff $SCRIPTDIR/$PRODUCTPAGE_V2_OUTPUT /tmp/$PRODUCTPAGE_V2_OUTPUT
    fi

    if [ $? -gt 0 ]; then
        (( retry_count=retry_count+1 ))
        if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
            exit 1
        fi
        echo "failed, retrying"
        echo "Productpage does not match productpage_v2 after setting route to reviews:v2 for user=jason in version routing test phase"
	sleep 10
    else
        break
    fi
done
echo "works!"

########Fault injection
echo "testing fault injection.."
output=$(create_rule $RULESDIR/bookinfo-jason-7s-delay.yaml)
fault_rule_id=$( tr -d ' \t\n\r' <<< "$output" | sed -e 's/\({"ids":\["\)//g' -e 's/\("\]}\)//g' )

sleep 20

retry_count=1
while [  $retry_count -le $((MAX_LOOP)) ]; do
    ###For shriram
    echo -n "injecting traffic for user=shriram, expecting productpage_v1 in less than 2s.."
    before=$(date +"%s")
    curl -s -b 'foo=bar;user=shriram;x' http://localhost:32000/productpage/productpage >/tmp/$PRODUCTPAGE_V1_OUTPUT
    after=$(date +"%s")

    delta=$(($after-$before))
    if [ $delta -gt 2 ]; then
        (( retry_count=retry_count+1 ))
        if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
            exit 1
        fi
        echo "failed, retrying"
        echo "Productpage took more $delta seconds to respond (expected 2s) for user=shriram in fault injection phase"
        continue
    fi

    if [ "$A8_TEST_SUITE" == "examples" ]; then
        diff $SCRIPTDIR/$PRODUCTPAGE_V1_OUTPUT /tmp/$PRODUCTPAGE_V1_OUTPUT
    else
        jsondiff $SCRIPTDIR/$PRODUCTPAGE_V1_OUTPUT /tmp/$PRODUCTPAGE_V1_OUTPUT
    fi

    if [ $? -gt 0 ]; then
        echo "failed"
        echo "Productpage does not match productpage_v1 after injecting fault rule for user=shriram in fault injection test phase"
        exit 1
    else
        break
    fi
done
echo "works!"

retry_count=1
while [  $retry_count -le $((MAX_LOOP)) ]; do
    ####For jason
    echo -n "injecting traffic for user=jason, expecting 'reviews unavailable' message in approx 7s.."
    before=$(date +"%s")
    curl -s -b 'foo=bar;user=jason;x' http://localhost:32000/productpage/productpage >/tmp/$PRODUCTPAGE_RULEMATCH
    after=$(date +"%s")

    delta=$(($after-$before))
    if [ $delta -gt 8 -o $delta -lt 5 ]; then
        (( retry_count=retry_count+1 ))
        if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
            exit 1
        fi
        echo "failed, retrying"
        echo "Productpage took more $delta seconds to respond (expected <8s && >5s) for user=jason in fault injection phase"
        continue
    fi

    if [ "$A8_TEST_SUITE" == "examples" ]; then
        diff $SCRIPTDIR/$PRODUCTPAGE_RULEMATCH /tmp/$PRODUCTPAGE_RULEMATCH
    else
        jsondiff $SCRIPTDIR/$PRODUCTPAGE_RULEMATCH /tmp/$PRODUCTPAGE_RULEMATCH
    fi

    if [ $? -gt 0 ]; then
        echo "failed"
        echo "Productpage does not match productpage_rulematch.json after injecting fault rule for user=jason in fault injection test phase"
        exit 1
    else
        break
    fi
done
echo "works!"

#####Clear rules and check
echo "clearing fault injection rule.."
delete_rule $fault_rule_id
sleep 15

retry_count=1
while [  $retry_count -le $((MAX_LOOP)) ]; do
    echo -n "Testing app again for user=jason, expecting productpage_v2 in less than 2s.."
    before=$(date +"%s")
    curl -s -b 'foo=bar;user=jason;x' http://localhost:32000/productpage/productpage >/tmp/$PRODUCTPAGE_V2_OUTPUT
    after=$(date +"%s")

    delta=$(($after-$before))
    if [ $delta -gt 2 ]; then
        (( retry_count=retry_count+1 ))
        if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
            exit 1
        fi
        echo "failed, retrying"
        echo "Productpage took more $delta seconds to respond (expected <2s) after clearing rules for user=jason in fault injection phase"
        continue
    fi

    if [ "$A8_TEST_SUITE" == "examples" ]; then
        diff $SCRIPTDIR/$PRODUCTPAGE_V2_OUTPUT /tmp/$PRODUCTPAGE_V2_OUTPUT
    else
        jsondiff $SCRIPTDIR/$PRODUCTPAGE_V2_OUTPUT /tmp/$PRODUCTPAGE_V2_OUTPUT
    fi

    if [ $? -gt 0 ]; then
        echo "failed"
        echo "Productpage does not match productpage_v2.json after clearing fault rules for user=jason in fault injection test phase"
        exit 1
    else
        break
    fi
done
echo "works!"

#######Gradually migrate traffic to reviews:v3 for all users
cleanup_all_rules

# Quiet things down a bit
set +x

MAX_LOOP=5
retry_count=1
SLEEP_TIME=15
GATEWAY_URL=localhost:32000
COMMAND_INPUT="curl -s -b 'foo=bar;user=shriram;x' http://localhost:32000/productpage/productpage"
EXPECTED_OUTPUT1="$SCRIPTDIR/$PRODUCTPAGE_V1_OUTPUT"
EXPECTED_OUTPUT2="$SCRIPTDIR/$PRODUCTPAGE_V3_OUTPUT"

MAX_LOOP=5
retry_count=1
echo "Percentage based routing. 25% to v1 and 75% to v3."

create_rule $RULESDIR/bookinfo-reviews-routing.yaml

while [  $retry_count -le $((MAX_LOOP)) ]; do
	# Give it a bit to process the request
	sleep $SLEEP_TIME

	# Validate that 25% of traffic is routing to v1
	# Curl the health check and check the version cookie
	check_routing_rules "$COMMAND_INPUT" "$EXPECTED_OUTPUT2" "$EXPECTED_OUTPUT1" 25
	if [ $? -gt 0 ]; then
		(( retry_count=retry_count+1 ))
		if [ $retry_count -eq $((MAX_LOOP+1)) ]; then
			echo "Exiting"
			exit 1
		fi
		echo "Retrying..."
	else
		break
	fi
done

echo "done"


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>"Cellmodeller4": BiofilmLineage Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

"Cellmodeller4"

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Namespace List

Namespace Members

Functions |
Variables

BiofilmLineage Namespace Reference

Functions

def 	setup (sim)

def 	init (cell)

def 	numSignals ()

def 	numSpecies ()

def 	update (cells)

def 	divide (parent, d1, d2)

Variables

float 	rodlen = 3.5

int 	max_cells = 400000

tuple 	cell_colors = numpy.random.uniform(0,1,(9,3))

Function Documentation

          def BiofilmLineage.divide
          (

          parent,

          d1,

          d2

          )

Definition at line 74 of file BiofilmLineage.py.

   74 def divide(parent, d1, d2):

   75     d1.targetVol = rodlen + random.uniform(0.0,rodlen/7.0)

   76     d2.targetVol = rodlen + random.uniform(0.0,rodlen/7.0)

   77     d1.volume = parent.volume*0.5

   78     d2.volume = parent.volume*0.5

   79     d1.prevlen = parent.prevlen*0.5

   80     d2.prevlen = parent.prevlen*0.5

   81

   82

BiofilmLineage.divide

def divide(parent, d1, d2)

Definition: BiofilmLineage.py:74

          def BiofilmLineage.init
          (

          cell	)

Definition at line 52 of file BiofilmLineage.py.

   52 def init(cell):

   53     cell.targetVol = rodlen + random.uniform(0.0,rodlen/7.0)

   54     cell.growthRate = 1.0

   55     cell.prevlen = 0

   56

BiofilmLineage.init

def init(cell)

Definition: BiofilmLineage.py:52

          def BiofilmLineage.numSignals
          (
          	)

Definition at line 57 of file BiofilmLineage.py.

   57 def numSignals():

   58     return 0

   59

BiofilmLineage.numSignals

def numSignals()

Definition: BiofilmLineage.py:57

          def BiofilmLineage.numSpecies
          (
          	)

Definition at line 60 of file BiofilmLineage.py.

   60 def numSpecies():

   61     return 0

   62

BiofilmLineage.numSpecies

def numSpecies()

Definition: BiofilmLineage.py:60

          def BiofilmLineage.setup
          (

          sim	)

Definition at line 19 of file BiofilmLineage.py.

   19 def setup(sim):

   20     # Set biophysics, signalling, and regulation models

   21     biophys = CLBacterium(sim, max_substeps=8, max_cells=max_cells, max_contacts=32, max_sqs=192**2, jitter_z=False, reg_param=0.04, gamma=25)

   22     #biophys.addPlane((0,0,-0.5), (0,0,1), 1.0)

   23     #biophys.addPlane((0,0,0.5), (0,0,-1), math.sqrt(7.5e-4))

   24

   25

   26     regul = ModuleRegulator(sim, __file__)  # use this file for reg too

   27     # Only biophys and regulation

   28     sim.init(biophys, regul, None, None)

   29

   30     sim.addCell(cellType=0, len=rodlen, pos=(0,0,0))

   31

   32     #sim.addCell(cellType=0, pos=(0,-10.0,0))

   33     #sim.addCell(cellType=1, pos=(0,10.0,0))

   34

   35     #sim.addCell(cellType=0, pos=(16,16,0))

   36     #sim.addCell(cellType=1, pos=(0,16,0))

   37     #sim.addCell(cellType=2, pos=(-16,16,0))

   38     #sim.addCell(cellType=3, pos=(16,0,0))

   39     #sim.addCell(cellType=4, pos=(0,0,0))

   40     #sim.addCell(cellType=5, pos=(-16,0,0))

   41     #sim.addCell(cellType=6, pos=(16,-16,0))

   42     #sim.addCell(cellType=7, pos=(0,-16,0))

   43     #sim.addCell(cellType=8, pos=(-16,-16,0))

   44

   45

   46     # Add some objects to draw the models

   47     therenderer = Renderers.GLBacteriumRenderer(sim)

   48     sim.addRenderer(therenderer)

   49     sim.savePickle = True

   50     sim.pickleSteps = 20

   51

CellModeller.Biophysics.BacterialModels.CLBacterium.CLBacterium

Definition: CLBacterium.py:14

BiofilmLineage.setup

def setup(sim)

Definition: BiofilmLineage.py:19

CellModeller.Regulation.ModuleRegulator.ModuleRegulator

Definition: ModuleRegulator.py:5

          def BiofilmLineage.update
          (

          cells	)

Definition at line 63 of file BiofilmLineage.py.

   63 def update(cells):

   64     for (id, cell) in cells.iteritems():

   65         dl = cell.volume - cell.prevlen

   66         strain = dl/cell.volume

   67         cell.color = [strain*10,0,0] #cell_colors[cell.cellType]

   68         if cell.volume > cell.targetVol:

   69             cell.asymm = [1,1]

   70             cell.divideFlag = True

   71         else:

   72             cell.prevlen = cell.volume

   73

BiofilmLineage.update

def update(cells)

Definition: BiofilmLineage.py:63

Variable Documentation

          tuple BiofilmLineage.cell_colors = numpy.random.uniform(0,1,(9,3))

Definition at line 16 of file BiofilmLineage.py.

          int BiofilmLineage.max_cells = 400000

Definition at line 10 of file BiofilmLineage.py.

          float BiofilmLineage.rodlen = 3.5

Definition at line 8 of file BiofilmLineage.py.

BiofilmLineage

Generated on Sat Mar 14 2015 18:01:03 for "Cellmodeller4" by

     1.8.9.1


text:
<?php
/**
 * GetTaxResult.class.php
 */

/**
 * Result data returned from {@link TaxServiceSoap#getTax}.
 *
 * @see GetTaxRequest
 *
 * @author    Avalara
 * @copyright � 2004 - 2011 Avalara, Inc.  All rights reserved.
 * @package   Tax
 */

namespace AvaTax;

class GetTaxResult implements JsonSerializable// extends BaseResult
{
	private $DocCode;	//string
	private $DocDate;			//date
	private $Timestamp;		//dateTime
	private $TotalAmount;		//decimal
	private $TotalDiscount;	//decimal
	private $TotalExemption;	//decimal
	private $TotalTaxable;	//decimal
	private $TotalTax;		//decimal
	private $TotalTaxCalculated;		//decimal
	private $TaxDate;		//date
 	private $TaxLines;	//ArrayOfTaxLine
	private $TaxSummary;		//ArrayOfTaxDetail
	private $TaxAddresses;		//ArrayOfAddress

	public function __construct( $resultCode, $messages, $docCode, $docDate, $timestamp, $totalAmount, $totalDiscount, $totalExemption, $totalTaxable, $totalTax, $totalTaxCalculated,
			$taxDate, $taxLines, $taxSummary, $taxAddresses)
	{
		$this->ResultCode = $resultCode;
		$this->Messages = $messages;
		$this->DocCode = $docCode ;
		$this->DocDate = $docDate ;
		$this->Timestamp = $timestamp ;
		$this->TotalAmount = $totalAmount ;
		$this->TotalDiscount = $totalDiscount ;
		$this->TotalExemption = $totalExemption ;
		$this->TotalTaxable = $totalTaxable ;
		$this->TotalTax = $totalTax ;
		$this->TotalTaxCalculated = $totalTaxCalculated ;
		$this->TaxDate = $taxDate ;
		$this->TaxLines = $taxLines ;
		$this->TaxSummary = $taxSummary ;
		$this->TaxAddresses = $taxAddresses ;

	}

    //Helper function to decode result objects from Json responses to specific objects.
	public static function parseResult($jsonString)
	{
		$object = json_decode($jsonString);
		$taxlines = array();
		$taxsummary = array();
		$taxaddresses = array();
		$messages = array();
		$resultcode= null;
		$doccode= null;
		$docdate= null;
		$timestamp= null;
		$totalamount= null;
		$totaldiscount= null;
		$totalexemption= null;
		$totaltaxable= null;
		$totaltax= null;
		$totaltaxcalculated= null;
		$taxdate= null;

		if( property_exists($object,"ResultCode")) $resultcode = $object->ResultCode;
		if( property_exists($object,"DocCode")) $doccode = $object->DocCode;
		if( property_exists($object,"DocDate")) $docdate = $object->DocDate;
		if( property_exists($object,"Timestamp")) $timestamp = $object->Timestamp;
		if( property_exists($object,"TotalAmount")) $totalamount = $object->TotalAmount;
		if( property_exists($object,"TotalDiscount")) $totaldiscount = $object->TotalDiscount;
		if( property_exists($object,"TotalExemption")) $totalexemption = $object->TotalExemption;
		if( property_exists($object,"TotalTaxable")) $totaltaxable = $object->TotalTaxable;
		if( property_exists($object,"TotalTax")) $totaltax = $object->TotalTax;
		if( property_exists($object,"TotalTaxCalculated")) $totaltaxcalculated = $object->TotalTaxCalculated;
		if( property_exists($object,"TaxDate")) $taxdate = $object->TaxDate;

		if(property_exists($object, "TaxLines"))
			$taxlines = TaxLine::parseTaxLines("{\"TaxLines\": ".json_encode($object->TaxLines)."}");
		if(property_exists($object, "TaxSummary"))
			$taxsummary = TaxDetail::parseTaxDetails("{\"TaxDetails\": ".json_encode($object->TaxSummary)."}");
		if(property_exists($object, "TaxAddresses"))
			$taxaddresses = Address::parseAddress("{\"TaxAddresses\": ".json_encode($object->TaxAddresses)."}");
		if(property_exists($object, "Messages"))
			$messages = Message::parseMessages("{\"Messages\": ".json_encode($object->Messages)."}");

		return new self( $resultcode , $messages, $doccode, $docdate,
		$timestamp, $totalamount, $totaldiscount,
		$totalexemption, $totaltaxable, $totaltax, $totaltaxcalculated,
		$taxdate, $taxlines, $taxsummary, $taxaddresses );
	}

	public function jsonSerialize(){
		return array(
			'DocCode' =>  $this->getDocCode(),
			'DocDate' =>  $this->getDocDate(),
			'Timestamp' =>  $this->getTimestamp(),
			'TotalAmount' =>  $this->getTotalAmount(),
			'TotalDiscount' =>  $this->getTotalDiscount(),
			'TotalExemption' =>  $this->getTotalExemption(),
			'TotalTaxable' =>  $this->getTotalTaxable(),
			'TotalTax' =>  $this->getTotalTax(),
			'TotalTaxCalculated' =>  $this->getTotalTaxCalculated(),
			'TaxDate' =>  $this->getTaxDate(),
		 	'TaxLines' =>  $this->getTaxLines(),
			'TaxSummary' =>  $this->getTaxSummary(),
			'TaxAddresses' =>  $this->getTaxAddresses(),
			'ResultCode'=> $this->getResultCode(),
			'Messages' => $this->getMessages()
		);
	}

	public function getDocCode() { return $this->DocCode; }
	public function getDocDate() { return $this->DocDate; }
	public function getTimestamp() { return $this->Timestamp; }
	public function getTotalAmount() { return $this->TotalAmount; }
	public function getTotalDiscount() { return $this->TotalDiscount; }
	public function getTotalExemption() { return $this->TotalExemption; }
	public function getTotalTaxable() { return $this->TotalTaxable; }
	public function getTotalTax() { return $this->TotalTax; }
	public function getTotalTaxCalculated() { return $this->TotalTaxCalculated; }
	public function getTaxDate() { return $this->TaxDate; }
 	public function getTaxLines() { return $this->TaxLines; }
	public function getTaxSummary() { return $this->TaxSummary; }
	public function getTaxAddresses() { return $this->TaxAddresses; }

	public function setDocCode($value) {  $this->DocCode= $value; }
	public function setDocDate($value) {  $this->DocDate= $value; }
	public function setTimestamp($value) {  $this->Timestamp= $value; }
	public function setTotalAmount($value) {  $this->TotalAmount= $value; }
	public function setTotalDiscount($value) {  $this->TotalDiscount= $value; }
	public function setTotalExemption($value) {  $this->TotalExemption= $value; }
	public function setTotalTaxable($value) {  $this->TotalTaxable= $value; }
	public function setTotalTax($value) {  $this->TotalTax= $value; }
	public function setTotalTaxCalculated($value) {  $this->TotalTaxCalculated= $value; }
	public function setTaxDate($value) {  $this->TaxDate= $value; }
 	public function setTaxLines($value) {  $this->TaxLines= $value; }
	public function setTaxSummary($value) {  $this->TaxSummary= $value; }
	public function setTaxAddresses($value) {  $this->TaxAddresses= $value; }

	//Allows for direct reference to and lookup of lines by line number.
	public function getTaxLine($lineNo)
	{
		if($this->getTaxLines() != null)
		{
			foreach($this->getTaxLines() as $taxLine)
			{
				if($lineNo == $taxLine->getLineNo())
				{
					return $taxLine;
				}

			}
		}
	}

	/////////////////////////////////////////////PHP bug requires this copy from BaseResult ///////////
	/**
	* @var string must be one of the values defined in {@link SeverityLevel}.
	*/
    private $ResultCode = 'Success';
	/**
	* @var array of Message.
	*/
    private $Messages = array();

	/**
	* Accessor
	* @return string
	*/
    public function getResultCode() { return $this->ResultCode; }
	/**
	* Accessor
	* @return array
	*/
    public function getMessages() { return $this->Messages; }

}

?>


text:
using NUnit.Framework;
using NLog;
using System.Diagnostics;
using LVCore.ExtensionMethods;

namespace LVCore.Test
{
    [TestFixture]
    public class TLVLogging
    {
        [Test]
        public void Logging_BaseTests()
        {
            LVLogManager.Instance.SetDebug();

            Logger logger = LVLogManager.Instance.GetLogger("TLVLogging_BaseTests");
            logger.LogLevelTest();
            LVLogManager.Instance.Dispose();

            Assert.IsTrue(LVLogManager.Instance.IsDisposed);
            Process.Start(logger.GetFilePath());
        }
    }
}


text:
(async function() {
  TestRunner.addResult('Tests the signed exchange information are available when the prefetch failed.\n');
  await TestRunner.loadTestModule('network_test_runner');
  await TestRunner.loadLegacyModule('console'); await TestRunner.loadTestModule('console_test_runner');
  await TestRunner.showPanel('network');
  NetworkTestRunner.networkLog().reset();

  const promise = new Promise(resolve => {
    TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFailed', loadingFailed, true);
    function loadingFailed(requestId, time, localizedDescription, canceled) {
      var request = NetworkTestRunner.networkLog().requestByManagerAndId(
          TestRunner.networkManager, requestId);
      if (/sxg-invalid-validity-url\.sxg/.exec(request.url()))
        resolve();
    }
  });

  TestRunner.evaluateInPage(`
    (function () {
      const link = document.createElement('link');
      link.rel = 'prefetch';
      link.href = '/loading/sxg/resources/sxg-invalid-validity-url.sxg';
      document.body.appendChild(link);
    })()
  `);
  await promise;
  NetworkTestRunner.dumpNetworkRequestsWithSignedExchangeInfo();
  TestRunner.completeTest();
})();


text:
.. Copyright (C) 2004-2009 The Trustees of Indiana University.
   Use, modification and distribution is subject to the Boost Software
   License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
   http://www.boost.org/LICENSE_1_0.txt)

===========================
|Logo| s-t Connectivity
===========================

::

  namespace graph { namespace distributed {
    template<typename DistributedGraph, typename ColorMap>
    inline bool
    st_connected(const DistributedGraph& g,
                 typename graph_traits<DistributedGraph>::vertex_descriptor s,
                 typename graph_traits<DistributedGraph>::vertex_descriptor t,
                 ColorMap color)

    template<typename DistributedGraph>
    inline bool
    st_connected(const DistributedGraph& g,
                 typename graph_traits<DistributedGraph>::vertex_descriptor s,
                 typename graph_traits<DistributedGraph>::vertex_descriptor t)

    template<typename DistributedGraph, typename ColorMap, typename OwnerMap>
    bool
    st_connected(const DistributedGraph& g,
                 typename graph_traits<DistributedGraph>::vertex_descriptor s,
                 typename graph_traits<DistributedGraph>::vertex_descriptor t,
                 ColorMap color, OwnerMap owner)
  } }

The ``st_connected()`` function determines whether there exists a path
from ``s`` to ``t`` in a graph ``g``.  If a path exists the function
returns ``true``, otherwise it returns ``false``.

This algorithm is currently *level-synchronized*, meaning that all
vertices in a given level of the search tree will be processed
(potentially in parallel) before any vertices from a successive level
in the tree are processed.  This is not necessary for the correctness
of the algorithm but rather is an implementation detail.  This
algorithm could be rewritten fully-asynchronously using triggers which
would remove the level-synchronized behavior.

.. contents::

Where Defined
-------------
<``boost/graph/distributed/st_connected.hpp``>

Parameters
----------

IN:  ``const DistributedGraph& g``
  The graph type must be a model of `Distributed Graph`_.  The graph
  type must also model the `Incidence Graph`_.

IN:  ``vertex_descriptor s``

IN:  ``vertex_descriptor t``

UTIL/OUT: ``color_map(ColorMap color)``
  The color map must be a `Distributed Property Map`_ with the same
  process group as the graph ``g`` whose colors must monotonically
  darken (white -> gray/green -> black). The default value is a
  distributed ``two_bit_color_map``.

IN:  ``OwnerMap owner``
  The owner map must map from vertices to the process that owns them
  as described in the `GlobalDescriptor`_ concept.

OUT:  ``bool``
  The algorithm returns ``true`` if a path from ``s`` to ``t`` is
  found, and false otherwise.

Complexity
----------

This algorithm performs *O(V + E)* work in *d/2 + 1* BSP supersteps,
where *d* is the shortest distance from ``s`` to ``t``. Over all
supersteps, *O(E)* messages of constant size will be transmitted.

Algorithm Description
---------------------

The algorithm consists of two simultaneous breadth-first traversals
from ``s`` and ``t`` respectively.  The algorithm utilizes a single
queue for both traversals with the traversal from ``s`` being denoted
by a ``gray`` entry in the color map and the traversal from ``t``
being denoted by a ``green`` entry.  The traversal method is similar
to breadth-first search except that no visitor event points are
called.  When any process detects a collision in the two traversals
(by attempting to set a ``gray`` vertex to ``green`` or vice-versa),
it signals all processes to terminate on the next superstep and all
processes return ``true``.  If the queues on all processes are empty
and no collision is detected then all processes terminate and return
``false``.

-----------------------------------------------------------------------------

Copyright (C) 2009 The Trustees of Indiana University.

Authors: Nick Edmonds and Andrew Lumsdaine

.. |Logo| image:: pbgl-logo.png
            :align: middle
            :alt: Parallel BGL
            :target: http://www.osl.iu.edu/research/pbgl

.. _Distributed Graph: DistributedGraph.html
.. _Incidence Graph: http://www.boost.org/libs/graph/doc/IncidenceGraph.html
.. _Distributed Property Map: distributed_property_map.html
.. _GlobalDescriptor: GlobalDescriptor.html


text:
package org.openntf.xrest.xsp.exec.convertor.datatypes;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.openntf.xrest.xsp.exec.Context;

import com.ibm.commons.util.io.json.JsonObject;

import lotus.domino.DateTime;
import lotus.domino.Item;
import lotus.domino.NotesException;

public class DateOnlyMapJsonTypeProcessor extends AbstractMapJsonTypeProcessor {

	@Override
	public void processItemToJsonObject(final Item item, final JsonObject jo, final String jsonPropertyName, Context context) throws NotesException {
		DateTime dtCurrent = item.getDateTimeValue();
		if (dtCurrent != null) {
			Date javaDate = dtCurrent.toJavaDate();
			jo.putJsonProperty(jsonPropertyName, buildISO8601DateOnly(javaDate));
			dtCurrent.recycle();
		}
	}

	@Override
	public void processValuesToJsonObject(final List<?> values, final JsonObject jo, final String jsonPropertyName, Context context) throws NotesException {
		if (values != null && !values.isEmpty()) {
			Object value = values.get(0);
			if (value instanceof DateTime) {
				Date dtCurrent = ((DateTime) value).toJavaDate();
				jo.putJsonProperty(jsonPropertyName, buildISO8601DateOnly(dtCurrent));
			}
		}
	}

	public String buildISO8601DateOnly(final Date javaDate) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		return df.format(javaDate);

	}

	public static Date parse(String input) throws java.text.ParseException {

		// NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
		// things a bit. Before we go on we have to repair this.
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

		// this is zero time so we need to add that TZ indicator for
		if (input.endsWith("Z")) {
			input = input.substring(0, input.length() - 1) + "GMT-00:00";
		} else {
			int inset = 6;

			String s0 = input.substring(0, input.length() - inset);
			String s1 = input.substring(input.length() - inset, input.length());

			input = s0 + "GMT" + s1;
		}

		return df.parse(input);

	}

	@Override
	public void processColumnValueToJsonObject(final Object clmnValue, final JsonObject jo, final String jsonPropertyName, Context context)
			throws NotesException {
	}
}


text:
class ViewSettingGeneralPage;
class ViewSettingAccountPage;
class ViewSettingAboutPage;
class AccountList;
class Preference;

namespace Ui {
class ViewSetting;
}

class SettingPageDocument
    : public PageSelectorDocument
{
    Q_OBJECT

public:
    SettingPageDocument(QObject* parent = nullptr);

private:
};

class ViewSetting
        : public PageSelectorView
{
    Q_OBJECT

public:
    explicit ViewSetting(QWidget *parent = 0);
    ~ViewSetting();

    void setAccountList(AccountList *accountList);

    void setPreference(Preference *preference);

protected:
    void initToolbar();

private slots:

private:
    Ui::ViewSetting *ui;
    AccountList *m_accountList;
    Preference *m_preference;
    PageSelectorDocument *settings;
    ViewSettingGeneralPage *generalPage;
    ViewSettingAccountPage *accountPage;
    ViewSettingAboutPage *aboutPage;
};

#endif // VIEWSETTING_H


text:
package it.cavallium.warppi.desktop;

public class DesktopGpio implements it.cavallium.warppi.Platform.Gpio {

	@Override
	public int valueOutput() {
		return 4;
	}

	@Override
	public int valuePwmOutput() {
		return 3;
	}

	@Override
	public int valueInput() {
		return 2;
	}

	@Override
	public int valueHigh() {
		return 1;
	}

	@Override
	public int valueLow() {
		return 0;
	}

	@Override
	public Object valueUnknownBoardType() {
		return new Object();
	}

	@Override
	public void wiringPiSetupPhys() {}

	@Override
	public void pinMode(final int i, final int type) {

	}

	@Override
	public void digitalWrite(final int pin, final int val) {}

	@Override
	public void digitalWrite(final int pin, final boolean val) {}

	@Override
	public void pwmWrite(final int pin, final int val) {}

	@Override
	public void delayMicroseconds(final int t) {}

	@Override
	public int digitalRead(final int pin) {
		return 0;
	}

	@Override
	public Object getBoardType() {
		return new Object();
	}

}


text:
require 'pandora/models/base'

module Pandora
  module Models
    class User < Pandora::Models::Base
      enum genders: [:male, :female, :unknow]
      enum statuses: [:normal, :black]
      validates :gender, inclusion: {in: genders.keys}
      validates :status, inclusion: {in: statuses.keys}
      validates :phone_number, :uniqueness => true, :format => {:with => /\A[\d]{11}\z/}
      has_many :twitters, class_name: "Pandora::Models::Twitter", foreign_key: :author_id, dependent: :destroy
      has_many :messages, dependent: :destroy
      has_many :favorite_images, dependent: :destroy
      has_many :favorite_designers, dependent: :destroy
      has_many :favorited_images, through: :favorite_images, dependent: :destroy
      has_many :favorited_designers, through: :favorite_designers, dependent: :destroy
      has_one :designer, dependent: :destroy
      has_one :account, dependent: :destroy
      has_one :login_user, dependent: :destroy
      belongs_to :avatar, class_name: "Pandora::Models::Image", foreign_key: :image_id, dependent: :destroy

      def attributes
        {
            id: id,
            name: name,
            avatar: avatar && avatar.attributes
        }
      end
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. int. Acad. Sci. Lett. Cracovie, Cl. sci. math. nat. Sér. B, sci. nat. 1: 902 (1906)

#### Original name
Epichloë kyllingae Racib.

### Remarks
null


text:
#import <Foundation/Foundation.h>

#import "ABI42_0_0ARTBrush.h"
#import "ABI42_0_0ARTCGFloatArray.h"
#import "ABI42_0_0ARTNode.h"

@interface ABI42_0_0ARTRenderable : ABI42_0_0ARTNode

@property (nonatomic, strong) ABI42_0_0ARTBrush *fill;
@property (nonatomic, assign) CGColorRef stroke;
@property (nonatomic, assign) CGFloat strokeWidth;
@property (nonatomic, assign) CGLineCap strokeCap;
@property (nonatomic, assign) CGLineJoin strokeJoin;
@property (nonatomic, assign) ABI42_0_0ARTCGFloatArray strokeDash;

@end


text:
namespace Xtricate.DocSet
{
    public interface IStorageOptions
    {
        string ConnectionString { get; set; }

        string DataSource { get; set; }

        string DatabaseName { get; set; }

        string SchemaName { get; set; }

        bool BufferedLoad { get; set; }

        string TableName { get; set; }

        string TableNamePrefix { get; set; }

        string TableNameSuffix { get; set; }

        bool UseTransactions { get; set; }

        string GetTableName<T>(string suffix = null);

        int DefaultTakeSize { get; set; }

        int MaxTakeSize { get; set; }

        bool EnableLogging { get; set; }

        SortColumn DefaultSortColumn { get; set; }
    }

    public enum SortColumn
    {
        Id,
        IdDescending,
        Key,
        KeyDescending,
        Timestamp,
        TimestampDescending
    }
}


text:
#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
/* method declaration */
- (int)add:(int)num1 andNum2:(int)num2;
- (int)sub:(int)num1 andNum2:(int)num2;
- (int)mul:(int)num1 andNum2:(int)num2;
- (double)div:(int)num1 andNum2:(int)num2;
@end

@implementation SampleClass

/* method returning the add of two numbers */
- (int)add:(int)num1 andNum2:(int)num2 {

   /* local variable declaration */
   int result;

   result = num1 + num2;

   return result;
}

/* method returning the sub of two numbers */
- (int)sub:(int)num1 andNum2:(int)num2 {

   /* local variable declaration */
   int result;

   result = num1 - num2;

   return result;
}

/* method returning the mul of two numbers */
- (int)mul:(int)num1 andNum2:(int)num2 {

   /* local variable declaration */
   int result;

   result = num1 * num2;

   return result;
}

/* method returning the div of two numbers */
- (double)div:(int)num1 andNum2:(int)num2 {

   /* local variable declaration */
   double result;
   if(num2 != 0){
      result = num1 / num2;
   }else{
      result = 0;
   }

   return result;
}

@end

int main () {

   /* local variable definition */
   int a = 400;
   int b = 20;
   int ret1;
   int ret2;
   int ret3;
   double ret4;

   printf("first:\n");
   scanf("%d", &a);
   printf("second:\n");
   scanf("%d", &b);
   SampleClass *sampleClass = [[SampleClass alloc]init];

   /* calling methods to get results */
   ret1 = [sampleClass add:a andNum2:b];
   ret2 = [sampleClass sub:a andNum2:b];
   ret3 = [sampleClass mul:a andNum2:b];
   ret4 = [sampleClass div:a andNum2:b];

   NSLog(@"add value is : %d\n", ret1 );
   NSLog(@"sub value is : %d\n", ret2 );
   NSLog(@"mul value is : %d\n", ret3 );
   NSLog(@"div value is : %.2f\n", ret4 );
   return 0;
}