text:
package main

import (
	"bufio"
	"crypto/sha1"
	"errors"
	"flag"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"camlistore.org/pkg/blobref"
	"camlistore.org/pkg/blobserver"
	"camlistore.org/pkg/client"
	"camlistore.org/pkg/cmdmain"
	"camlistore.org/pkg/schema"
)

type fileCmd struct {
	title string
	tag   string

	makePermanode  bool // make new, unique permanode of the root (dir or file)
	filePermanodes bool // make planned permanodes for each file (based on their digest)
	vivify         bool
	exifTime       bool // use metadata (such as in EXIF) to find the creation time of the file
	diskUsage      bool // show "du" disk usage only (dry run mode), don't actually upload
	argsFromInput  bool // Android mode: filenames piped into stdin, one at a time.

	havecache, statcache bool

	// Go into in-memory stats mode only; doesn't actually upload.
	memstats bool
	histo    string // optional histogram output filename
}

var flagUseSQLiteChildCache bool // Use sqlite for the statcache and havecache.

func init() {
	cmdmain.RegisterCommand("file", func(flags *flag.FlagSet) cmdmain.CommandRunner {
		cmd := new(fileCmd)
		flags.BoolVar(&cmd.makePermanode, "permanode", false, "Create an associate a new permanode for the uploaded file or directory.")
		flags.BoolVar(&cmd.filePermanodes, "filenodes", false, "Create (if necessary) content-based permanodes for each uploaded file.")
		flags.BoolVar(&cmd.vivify, "vivify", false,
			"If true, ask the server to create and sign permanode(s) associated with each uploaded"+
				" file. This permits the server to have your signing key. Used mostly with untrusted"+
				" or at-risk clients, such as phones.")
		flags.BoolVar(&cmd.exifTime, "exiftime", false, "Try to use metadata (such as EXIF) to get a stable creation time. If found, used as the replacement for the modtime. Mainly useful with vivify or filenodes.")
		flags.StringVar(&cmd.title, "title", "", "Optional title attribute to set on permanode when using -permanode.")
		flags.StringVar(&cmd.tag, "tag", "", "Optional tag(s) to set on permanode when using -permanode or -filenodes. Single value or comma separated.")

		flags.BoolVar(&cmd.diskUsage, "du", false, "Dry run mode: only show disk usage information, without upload or statting dest. Used for testing skipDirs configs, mostly.")

		if debug, _ := strconv.ParseBool(os.Getenv("CAMLI_DEBUG")); debug {
			flags.BoolVar(&cmd.statcache, "statcache", true, "Use the stat cache, assuming unchanged files already uploaded in the past are still there. Fast, but potentially dangerous.")
			flags.BoolVar(&cmd.havecache, "havecache", true, "Use the 'have cache', a cache keeping track of what blobs the remote server should already have from previous uploads.")
			flags.BoolVar(&cmd.memstats, "debug-memstats", false, "Enter debug in-memory mode; collecting stats only. Doesn't upload anything.")
			flags.StringVar(&cmd.histo, "debug-histogram-file", "", "Optional file to create and write the blob size for each file uploaded.  For use with GNU R and hist(read.table(\"filename\")$V1). Requires debug-memstats.")
			flags.BoolVar(&flagUseSQLiteChildCache, "sqlitecache", false, "Use sqlite for the statcache and havecache instead of a flat cache.")
		} else {
			cmd.havecache = true
			cmd.statcache = true
		}
		if client.AndroidOutput() {
			flags.BoolVar(&cmd.argsFromInput, "stdinargs", false, "If true, filenames to upload are sent one-per-line on stdin. EOF means to quit the process with exit status 0.")
		}
		flagCacheLog = flags.Bool("logcache", false, "log caching details")

		return cmd
	})
}

func (c *fileCmd) Describe() string {
	return "Upload file(s)."
}

func (c *fileCmd) Usage() {
	fmt.Fprintf(cmdmain.Stderr, "Usage: camput [globalopts] file [fileopts] <file/director(ies)>\n")
}

func (c *fileCmd) Examples() []string {
	return []string{
		"[opts] <file(s)/director(ies)",
		"--permanode --title='Homedir backup' --tag=backup,homedir $HOME",
		"--filenodes /mnt/camera/DCIM",
	}
}

func (c *fileCmd) RunCommand(args []string) error {
	if c.vivify {
		if c.makePermanode || c.filePermanodes || c.tag != "" || c.title != "" {
			return cmdmain.UsageError("--vivify excludes any other option")
		}
	}
	if c.title != "" && !c.makePermanode {
		return cmdmain.UsageError("Can't set title without using --permanode")
	}
	if c.tag != "" && !c.makePermanode && !c.filePermanodes {
		return cmdmain.UsageError("Can't set tag without using --permanode or --filenodes")
	}
	if c.histo != "" && !c.memstats {
		return cmdmain.UsageError("Can't use histo without memstats")
	}
	up := getUploader()
	if c.memstats {
		sr := new(statsStatReceiver)
		up.altStatReceiver = sr
		defer func() { sr.DumpStats(c.histo) }()
	}
	c.initCaches(up)

	if c.makePermanode || c.filePermanodes {
		testSigBlobRef := up.Client.SignerPublicKeyBlobref()
		if testSigBlobRef == nil {
			return cmdmain.UsageError("A GPG key is needed to create permanodes; configure one or use vivify mode.")
		}
	}
	up.fileOpts = &fileOptions{
		permanode: c.filePermanodes,
		tag:       c.tag,
		vivify:    c.vivify,
		exifTime:  c.exifTime,
	}

	var (
		permaNode *client.PutResult
		lastPut   *client.PutResult
		err       error
	)
	if c.makePermanode {
		if len(args) != 1 {
			return fmt.Errorf("The --permanode flag can only be used with exactly one file or directory argument")
		}
		permaNode, err = up.UploadNewPermanode()
		if err != nil {
			return fmt.Errorf("Uploading permanode: %v", err)
		}
	}
	if c.diskUsage {
		if len(args) != 1 {
			return fmt.Errorf("The --du flag can only be used with exactly one directory argument")
		}
		dir := args[0]
		fi, err := up.stat(dir)
		if err != nil {
			return err
		}
		if !fi.IsDir() {
			return fmt.Errorf("%q is not a directory.", dir)
		}
		t := up.NewTreeUpload(dir)
		t.DiskUsageMode = true
		t.Start()
		pr, err := t.Wait()
		if err != nil {
			return err
		}
		handleResult("tree-upload", pr, err)
		return nil
	}
	if c.argsFromInput {
		if len(args) > 0 {
			return errors.New("args not supported with -argsfrominput")
		}
		tu := up.NewRootlessTreeUpload()
		tu.Start()
		br := bufio.NewReader(os.Stdin)
		for {
			path, err := br.ReadString('\n')
			if path = strings.TrimSpace(path); path != "" {
				tu.Enqueue(path)
			}
			if err == io.EOF {
				os.Exit(0)
			}
			if err != nil {
				log.Fatal(err)
			}
		}
	}

	if len(args) == 0 {
		return cmdmain.UsageError("No files or directories given.")
	}
	for _, filename := range args {
		fi, err := os.Stat(filename)
		if err != nil {
			return err
		}
		if fi.IsDir() {
			if up.fileOpts.wantVivify() {
				vlog.Printf("Directories not supported in vivify mode; skipping %v\n", filename)
				continue
			}
			t := up.NewTreeUpload(filename)
			t.Start()
			lastPut, err = t.Wait()
		} else {
			lastPut, err = up.UploadFile(filename)
		}
		if handleResult("file", lastPut, err) != nil {
			return err
		}
	}

	if permaNode != nil {
		put, err := up.UploadAndSignBlob(schema.NewSetAttributeClaim(permaNode.BlobRef, "camliContent", lastPut.BlobRef.String()))
		if handleResult("claim-permanode-content", put, err) != nil {
			return err
		}
		if c.title != "" {
			put, err := up.UploadAndSignBlob(schema.NewSetAttributeClaim(permaNode.BlobRef, "title", c.title))
			handleResult("claim-permanode-title", put, err)
		}
		if c.tag != "" {
			tags := strings.Split(c.tag, ",")
			m := schema.NewSetAttributeClaim(permaNode.BlobRef, "tag", tags[0])
			for _, tag := range tags {
				m = schema.NewAddAttributeClaim(permaNode.BlobRef, "tag", tag)
				put, err := up.UploadAndSignBlob(m)
				handleResult("claim-permanode-tag", put, err)
			}
		}
		handleResult("permanode", permaNode, nil)
	}
	return nil
}

func (c *fileCmd) initCaches(up *Uploader) {
	if !c.statcache && !c.havecache {
		return
	}
	gen, err := up.StorageGeneration()
	if err != nil {
		log.Printf("WARNING: not using local caches; failed to retrieve server's storage generation: %v", err)
		return
	}
	if c.statcache {
		var cache UploadCache
		if flagUseSQLiteChildCache {
			cache = NewSQLiteStatCache(gen)
		} else {
			cache = NewFlatStatCache(gen)
		}
		up.statCache = cache
	}
	if c.havecache {
		var cache HaveCache
		if flagUseSQLiteChildCache {
			cache = NewSQLiteHaveCache(gen)
		} else {
			cache = NewFlatHaveCache(gen)
		}
		up.haveCache = cache
		up.Client.SetHaveCache(cache)
	}
}

// statsStatReceiver is a dummy blobserver.StatReceiver that doesn't store anything;
// it just collects statistics.
type statsStatReceiver struct {
	mu   sync.Mutex
	have map[string]int64
}

func (sr *statsStatReceiver) ReceiveBlob(blob *blobref.BlobRef, source io.Reader) (sb blobref.SizedBlobRef, err error) {
	n, err := io.Copy(ioutil.Discard, source)
	if err != nil {
		return
	}
	sr.mu.Lock()
	defer sr.mu.Unlock()
	if sr.have == nil {
		sr.have = make(map[string]int64)
	}
	sr.have[blob.String()] = n
	return blobref.SizedBlobRef{blob, n}, nil
}

func (sr *statsStatReceiver) StatBlobs(dest chan<- blobref.SizedBlobRef, blobs []*blobref.BlobRef, _ time.Duration) error {
	sr.mu.Lock()
	defer sr.mu.Unlock()
	for _, br := range blobs {
		if size, ok := sr.have[br.String()]; ok {
			dest <- blobref.SizedBlobRef{br, size}
		}
	}
	return nil
}

// DumpStats creates the destFile and writes a line per received blob,
// with its blob size.
func (sr *statsStatReceiver) DumpStats(destFile string) {
	sr.mu.Lock()
	defer sr.mu.Unlock()

	f, err := os.Create(destFile)
	if err != nil {
		log.Fatal(err)
	}

	var sum int64
	for _, size := range sr.have {
		fmt.Fprintf(f, "%d\n", size)
	}
	fmt.Printf("In-memory blob stats: %d blobs, %d bytes\n", len(sr.have), sum)

	err = f.Close()
	if err != nil {
		log.Fatal(err)
	}
}

type stats struct {
	files, bytes int64
}

func (s *stats) incr(n *node) {
	s.files++
	if !n.fi.IsDir() {
		s.bytes += n.fi.Size()
	}
}

func (up *Uploader) lstat(path string) (os.FileInfo, error) {
	// TODO(bradfitz): use VFS
	return os.Lstat(path)
}

func (up *Uploader) stat(path string) (os.FileInfo, error) {
	if up.fs == nil {
		return os.Stat(path)
	}
	f, err := up.fs.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return f.Stat()
}

func (up *Uploader) open(path string) (http.File, error) {
	if up.fs == nil {
		return os.Open(path)
	}
	return up.fs.Open(path)
}

func (up *Uploader) uploadNode(n *node) (*client.PutResult, error) {
	fi := n.fi
	mode := fi.Mode()
	if mode&os.ModeType == 0 {
		return up.uploadNodeRegularFile(n)
	}
	bb := schema.NewCommonFileMap(n.fullPath, fi)
	switch {
	case mode&os.ModeSymlink != 0:
		// TODO(bradfitz): use VFS here; not os.Readlink
		target, err := os.Readlink(n.fullPath)
		if err != nil {
			return nil, err
		}
		bb.SetSymlinkTarget(target)
	case mode&os.ModeDevice != 0:
		// including mode & os.ModeCharDevice
		fallthrough
	case mode&os.ModeSocket != 0:
		fallthrough
	case mode&os.ModeNamedPipe != 0: // FIFO
		fallthrough
	default:
		return nil, fmt.Errorf("camput.files: unsupported file type %v for file %v", mode, n.fullPath)
	case fi.IsDir():
		ss := new(schema.StaticSet)
		for _, c := range n.children {
			pr, err := c.PutResult()
			if err != nil {
				return nil, fmt.Errorf("Error populating directory static set for child %q: %v", c.fullPath, err)
			}
			ss.Add(pr.BlobRef)
		}
		sspr, err := up.UploadBlob(ss)
		if err != nil {
			return nil, err
		}
		bb.PopulateDirectoryMap(sspr.BlobRef)
	}

	mappr, err := up.UploadBlob(bb)
	if err == nil {
		if !mappr.Skipped {
			vlog.Printf("Uploaded %q, %s for %s", bb.Type(), mappr.BlobRef, n.fullPath)
		}
	} else {
		vlog.Printf("Error uploading map for %s (%s, %s): %v", n.fullPath, bb.Type(), bb.Blob().BlobRef(), err)
	}
	return mappr, err

}

// statReceiver returns the StatReceiver used for checking for and uploading blobs.
//
// The optional provided node is only used for conditionally printing out status info to stdout.
func (up *Uploader) statReceiver(n *node) blobserver.StatReceiver {
	statReceiver := up.altStatReceiver
	if statReceiver == nil {
		// TODO(mpl): simplify the altStatReceiver situation as well,
		// see TODO in cmd/camput/uploader.go
		statReceiver = up.Client
	}
	if client.AndroidOutput() && n != nil && n.fi.Mode()&os.ModeType == 0 {
		return client.AndroidStatusReceiver{Sr: statReceiver, Path: n.fullPath}
	}
	return statReceiver
}

var atomicDigestOps int64 // number of files digested

// wholeFileDigest returns the sha1 digest of the regular file's absolute
// path given in fullPath.
func (up *Uploader) wholeFileDigest(fullPath string) (*blobref.BlobRef, error) {
	// TODO(bradfitz): cache this.
	file, err := up.open(fullPath)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	td := &trackDigestReader{r: file}
	// Warning: the struct in the following line exists to hide
	// ioutil.Discard's ReadFrom from io.Copy, since ReadFrom uses
	// an intentionally-racy buffer that's passed to the reader,
	// which was causing SHA-1 calculation corruption.
	_, err = io.Copy(struct{ io.Writer }{ioutil.Discard}, td)
	atomic.AddInt64(&atomicDigestOps, 1)
	if err != nil {
		return nil, err
	}
	return blobref.MustParse(td.Sum()), nil
}

var noDupSearch = os.Getenv("CAMLI_NO_FILE_DUP_SEARCH") == "1"

// fileMapFromDuplicate queries the server's search interface for an
// existing file with an entire contents of sum (a blobref string).
// If the server has it, it's validated, and then fileMap (which must
// already be partially populated) has its "parts" field populated,
// and then fileMap is uploaded (if necessary) and a PutResult with
// its blobref is returned. If there's any problem, or a dup doesn't
// exist, ok is false.
// If required, Vivify is also done here.
func (up *Uploader) fileMapFromDuplicate(bs blobserver.StatReceiver, fileMap *schema.Builder, sum string) (pr *client.PutResult, ok bool) {
	if noDupSearch {
		return
	}
	_, err := up.Client.SearchRoot()
	if err != nil {
		return
	}
	dupFileRef, err := up.Client.SearchExistingFileSchema(blobref.MustParse(sum))
	if err != nil {
		log.Printf("Warning: error searching for already-uploaded copy of %s: %v", sum, err)
		return nil, false
	}
	if dupFileRef == nil {
		return nil, false
	}
	if *cmdmain.FlagVerbose {
		log.Printf("Found dup of contents %s in file schema %s", sum, dupFileRef)
	}
	dupMap, err := up.Client.FetchSchemaBlob(dupFileRef)
	if err != nil {
		log.Printf("Warning: error fetching %v: %v", dupFileRef, err)
		return nil, false
	}

	fileMap.PopulateParts(dupMap.PartsSize(), dupMap.ByteParts())

	json, err := fileMap.JSON()
	if err != nil {
		return nil, false
	}
	uh := client.NewUploadHandleFromString(json)
	if up.fileOpts.wantVivify() {
		uh.Vivify = true
	}
	if !uh.Vivify && uh.BlobRef.Equal(dupFileRef) {
		// Unchanged (same filename, modtime, JSON serialization, etc)
		return &client.PutResult{BlobRef: dupFileRef, Size: int64(len(json)), Skipped: true}, true
	}
	pr, err = up.Upload(uh)
	if err != nil {
		log.Printf("Warning: error uploading file map after finding server dup of %v: %v", sum, err)
		return nil, false
	}
	return pr, true
}

func (up *Uploader) uploadNodeRegularFile(n *node) (*client.PutResult, error) {
	filebb := schema.NewCommonFileMap(n.fullPath, n.fi)
	filebb.SetType("file")
	file, err := up.open(n.fullPath)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	if up.fileOpts.exifTime {
		ra, ok := file.(io.ReaderAt)
		if !ok {
			return nil, errors.New("Error asserting local file to io.ReaderAt")
		}
		modtime, err := schema.FileTime(ra)
		if err != nil {
			log.Printf("warning: getting time from EXIF failed for %v: %v", n.fullPath, err)
		} else {
			filebb.SetModTime(modtime)
		}
	}

	var (
		size                           = n.fi.Size()
		fileContents io.Reader         = io.LimitReader(file, size)
		br           *blobref.BlobRef  // of file schemaref
		sum          string            // sha1 hashsum of the file to upload
		pr           *client.PutResult // of the final "file" schema blob
	)

	const dupCheckThreshold = 256 << 10
	if size > dupCheckThreshold {
		sumRef, err := up.wholeFileDigest(n.fullPath)
		if err == nil {
			sum = sumRef.String()
			ok := false
			pr, ok = up.fileMapFromDuplicate(up.statReceiver(n), filebb, sum)
			if ok {
				br = pr.BlobRef
				client.NoteFileUploaded(n.fullPath, !pr.Skipped)
				if up.fileOpts.wantVivify() {
					// we can return early in that case, because the other options
					// are disallowed in the vivify case.
					return pr, nil
				}
			}
		}
	}

	if up.fileOpts.wantVivify() {
		// If vivify wasn't already done in fileMapFromDuplicate.
		err := schema.WriteFileChunks(up.statReceiver(n), filebb, fileContents)
		if err != nil {
			return nil, err
		}
		json, err := filebb.JSON()
		if err != nil {
			return nil, err
		}
		br = blobref.SHA1FromString(json)
		h := &client.UploadHandle{
			BlobRef:  br,
			Size:     int64(len(json)),
			Contents: strings.NewReader(json),
			Vivify:   true,
		}
		pr, err = up.Upload(h)
		if err != nil {
			return nil, err
		}
		client.NoteFileUploaded(n.fullPath, true)
		return pr, nil
	}

	if br == nil {
		// br still nil means fileMapFromDuplicate did not find the file on the server,
		// and the file has not just been uploaded subsequently to a vivify request.
		// So we do the full file + file schema upload here.
		if sum == "" && up.fileOpts.wantFilePermanode() {
			fileContents = &trackDigestReader{r: fileContents}
		}
		br, err = schema.WriteFileMap(up.statReceiver(n), filebb, fileContents)
		if err != nil {
			return nil, err
		}
	}

	// TODO(mpl): test that none of these claims get uploaded if they've already been done
	if up.fileOpts.wantFilePermanode() {
		if td, ok := fileContents.(*trackDigestReader); ok {
			sum = td.Sum()
		}
		// claimTime is both the time of the "claimDate" in the
		// JSON claim, as well as the date in the OpenPGP
		// header.
		// TODO(bradfitz): this is a little clumsy to do by hand.
		// There should probably be a method on *Uploader to do this
		// from an unsigned schema map. Maybe ditch the schema.Claimer
		// type and just have the Uploader override the claimDate.
		claimTime, ok := filebb.ModTime()
		if !ok {
			return nil, fmt.Errorf("couldn't get modtime for file %v", n.fullPath)
		}
		err = up.uploadFilePermanode(sum, br, claimTime)
		if err != nil {
			return nil, fmt.Errorf("Error uploading permanode for node %v: %v", n, err)
		}
	}

	// TODO(bradfitz): faking a PutResult here to return
	// is kinda gross.  should instead make a
	// blobserver.Storage wrapper type (wrapping
	// statReceiver) that can track some of this?  or make
	// schemaWriteFileMap return it?
	json, _ := filebb.JSON()
	pr = &client.PutResult{BlobRef: br, Size: int64(len(json)), Skipped: false}
	return pr, nil
}

// uploadFilePermanode creates and uploads the planned permanode (with sum as a
// fixed key) associated with the file blobref fileRef.
// It also sets the optional tags for this permanode.
func (up *Uploader) uploadFilePermanode(sum string, fileRef *blobref.BlobRef, claimTime time.Time) error {
	// Use a fixed time value for signing; not using modtime
	// so two identical files don't have different modtimes?
	// TODO(bradfitz): consider this more?
	permaNodeSigTime := time.Unix(0, 0)
	permaNode, err := up.UploadPlannedPermanode(sum, permaNodeSigTime)
	if err != nil {
		return fmt.Errorf("Error uploading planned permanode: %v", err)
	}
	handleResult("node-permanode", permaNode, nil)

	contentAttr := schema.NewSetAttributeClaim(permaNode.BlobRef, "camliContent", fileRef.String())
	contentAttr.SetClaimDate(claimTime)
	signed, err := up.SignBlob(contentAttr, claimTime)
	if err != nil {
		return fmt.Errorf("Failed to sign content claim: %v", err)
	}
	put, err := up.uploadString(signed)
	if err != nil {
		return fmt.Errorf("Error uploading permanode's attribute: %v", err)
	}

	handleResult("node-permanode-contentattr", put, nil)
	if tags := up.fileOpts.tags(); len(tags) > 0 {
		errch := make(chan error)
		for _, tag := range tags {
			go func(tag string) {
				m := schema.NewAddAttributeClaim(permaNode.BlobRef, "tag", tag)
				m.SetClaimDate(claimTime)
				signed, err := up.SignBlob(m, claimTime)
				if err != nil {
					errch <- fmt.Errorf("Failed to sign tag claim: %v", err)
					return
				}
				put, err := up.uploadString(signed)
				if err != nil {
					errch <- fmt.Errorf("Error uploading permanode's tag attribute %v: %v", tag, err)
					return
				}
				handleResult("node-permanode-tag", put, nil)
				errch <- nil
			}(tag)
		}

		for _ = range tags {
			if e := <-errch; e != nil && err == nil {
				err = e
			}
		}
		if err != nil {
			return err
		}
	}
	return nil
}

func (up *Uploader) UploadFile(filename string) (*client.PutResult, error) {
	fullPath, err := filepath.Abs(filename)
	if err != nil {
		return nil, err
	}
	fi, err := up.lstat(fullPath)
	if err != nil {
		return nil, err
	}

	if fi.IsDir() {
		panic("must use UploadTree now for directories")
	}
	n := &node{
		fullPath: fullPath,
		fi:       fi,
	}

	if up.statCache != nil && !up.fileOpts.wantVivify() {
		// Note: ignoring cache hits if wantVivify, otherwise
		// a non-vivify put followed by a vivify one wouldn't
		// end up doing the vivify.
		if cachedRes, err := up.statCache.CachedPutResult(up.pwd, n.fullPath, n.fi); err == nil {
			return cachedRes, nil
		}
	}

	pr, err := up.uploadNode(n)
	if err == nil && up.statCache != nil {
		up.statCache.AddCachedPutResult(up.pwd, n.fullPath, n.fi, pr)
	}

	return pr, err
}

// NewTreeUpload returns a TreeUpload. It doesn't begin uploading any files until a
// call to Start
func (up *Uploader) NewTreeUpload(dir string) *TreeUpload {
	tu := up.NewRootlessTreeUpload()
	tu.rootless = false
	tu.base = dir
	return tu
}

func (up *Uploader) NewRootlessTreeUpload() *TreeUpload {
	return &TreeUpload{
		rootless: true,
		base:     "",
		up:       up,
		donec:    make(chan bool, 1),
		errc:     make(chan error, 1),
		stattedc: make(chan *node, buffered),
	}
}

func (t *TreeUpload) Start() {
	go t.run()
}

type node struct {
	tu       *TreeUpload // nil if not doing a tree upload
	fullPath string
	fi       os.FileInfo
	children []*node

	// cond (and its &mu Lock) guard err and res.
	cond sync.Cond // with L being &mu
	mu   sync.Mutex
	err  error
	res  *client.PutResult

	sumBytes int64 // cached value, if non-zero. also guarded by mu.
}

func (n *node) String() string {
	if n == nil {
		return "<nil *node>"
	}
	return fmt.Sprintf("[node %s, isDir=%v, nchild=%d]", n.fullPath, n.fi.IsDir(), len(n.children))
}

func (n *node) SetPutResult(res *client.PutResult, err error) {
	n.mu.Lock()
	defer n.mu.Unlock()
	n.res, n.err = res, err
	n.cond.Signal()
}

func (n *node) PutResult() (*client.PutResult, error) {
	n.mu.Lock()
	defer n.mu.Unlock()
	for n.err == nil && n.res == nil {
		n.cond.Wait()
	}
	return n.res, n.err
}

func (n *node) SumBytes() (v int64) {
	n.mu.Lock()
	defer n.mu.Unlock()
	if n.sumBytes != 0 {
		return n.sumBytes
	}
	for _, c := range n.children {
		v += c.SumBytes()
	}
	if n.fi.Mode()&os.ModeType == 0 {
		v += n.fi.Size()
	}
	n.sumBytes = v
	return
}

/*
A TreeUpload holds the state of an ongoing recursive directory tree
upload.  Call Wait to get the final result.

Uploading a directory tree involves several concurrent processes, each
which may involve multiple goroutines:

1) one process stats all files and walks all directories as fast as possible
   to calculate how much total work there will be.  this goroutine also
   filters out directories to be skipped. (caches, temp files, skipDirs, etc)

 2) one process works though the files that were discovered and checks
    the statcache to see what actually needs to be uploaded.
    The statcache is
        full path => {last os.FileInfo signature, put result from last time}
    and is used to avoid re-reading/digesting the file even locally,
    trusting that it's already on the server.

 3) one process uploads files & metadata.  This process checks the "havecache"
    to see which blobs are already on the server.  For awhile the local havecache
    (if configured) and the remote blobserver "stat" RPC are raced to determine
    if the local havecache is even faster. If not, it's not consulted. But if the
    latency of remote stats is high enough, checking locally is preferred.
*/
type TreeUpload struct {
	// If DiskUsageMode is set true before Start, only
	// per-directory disk usage stats are output, like the "du"
	// command.
	DiskUsageMode bool

	// Immutable:
	rootless bool   // if true, "base" will be empty.
	base     string // base directory
	up       *Uploader
	stattedc chan *node // from stat-the-world goroutine to run()

	donec chan bool // closed when run() finishes
	err   error
	errc  chan error // with 1 buffer item

	// Owned by run goroutine:
	total    stats // total bytes on disk
	skipped  stats // not even tried to upload (trusting stat cache)
	uploaded stats // uploaded (even if server said it already had it and bytes weren't sent)

	finalPutRes *client.PutResult // set after run() returns
}

// Enqueue starts uploading path (a file, directory, etc).
func (t *TreeUpload) Enqueue(path string) {
	t.statPath(path, nil)
}

// fi is optional (will be statted if nil)
func (t *TreeUpload) statPath(fullPath string, fi os.FileInfo) (nod *node, err error) {
	defer func() {
		if err == nil && nod != nil {
			t.stattedc <- nod
		}
	}()
	if fi == nil {
		fi, err = t.up.lstat(fullPath)
		if err != nil {
			return nil, err
		}
	}
	n := &node{
		tu:       t,
		fullPath: fullPath,
		fi:       fi,
	}
	n.cond.L = &n.mu

	if !fi.IsDir() {
		return n, nil
	}
	f, err := t.up.open(fullPath)
	if err != nil {
		return nil, err
	}
	fis, err := f.Readdir(-1)
	f.Close()
	if err != nil {
		return nil, err
	}
	sort.Sort(byFileName(fis))
	for _, fi := range fis {
		depn, err := t.statPath(filepath.Join(fullPath, filepath.Base(fi.Name())), fi)
		if err != nil {
			return nil, err
		}
		n.children = append(n.children, depn)
	}
	return n, nil
}

const uploadWorkers = 5

func (t *TreeUpload) run() {
	defer close(t.donec)

	// Kick off scanning all files, eventually learning the root
	// node (which references all its children).
	var root *node // nil until received and set in loop below.
	rootc := make(chan *node, 1)
	if !t.rootless {
		go func() {
			n, err := t.statPath(t.base, nil)
			if err != nil {
				log.Fatalf("Error scanning files under %s: %v", t.base, err)
			}
			close(t.stattedc)
			rootc <- n
		}()
	}

	var lastStat, lastUpload string
	dumpStats := func() {
		if client.AndroidOutput() {
			printAndroidCamputStatus(t)
			return
		}
		statStatus := ""
		if root == nil {
			statStatus = fmt.Sprintf("last stat: %s", lastStat)
		}
		blobStats := t.up.Stats()
		log.Printf("FILES: Total: %+v Skipped: %+v Uploaded: %+v %s BLOBS: %s Digested: %d last upload: %s",
			t.total, t.skipped, t.uploaded,
			statStatus,
			blobStats.String(),
			atomic.LoadInt64(&atomicDigestOps),
			lastUpload)
	}

	// Channels for stats & progress bars. These are never closed:
	uploadedc := make(chan *node) // at least tried to upload; server might have had blob
	skippedc := make(chan *node)  // didn't even hit blobserver; trusted our stat cache

	uploadsdonec := make(chan bool)
	var upload chan<- *node
	if t.DiskUsageMode {
		upload = NewNodeWorker(1, func(n *node, ok bool) {
			if !ok {
				uploadsdonec <- true
				return
			}
			if n.fi.IsDir() {
				fmt.Printf("%d\t%s\n", n.SumBytes()>>10, n.fullPath)
			}
		})
	} else {
		upload = NewNodeWorker(uploadWorkers, func(n *node, ok bool) {
			if !ok {
				log.Printf("done with all uploads.")
				uploadsdonec <- true
				return
			}
			put, err := t.up.uploadNode(n)
			if err != nil {
				log.Fatalf("Error uploading %s: %v", n.fullPath, err)
			}
			n.SetPutResult(put, nil)
			if c := t.up.statCache; c != nil && !n.fi.IsDir() {
				c.AddCachedPutResult(t.up.pwd, n.fullPath, n.fi, put)
			}
			uploadedc <- n
		})
	}

	checkStatCache := NewNodeWorker(10, func(n *node, ok bool) {
		if !ok {
			if t.up.statCache != nil {
				log.Printf("done checking stat cache")
			}
			close(upload)
			return
		}
		if t.DiskUsageMode || t.up.statCache == nil {
			upload <- n
			return
		}
		if !n.fi.IsDir() {
			cachedRes, err := t.up.statCache.CachedPutResult(t.up.pwd, n.fullPath, n.fi)
			if err == nil {
				n.SetPutResult(cachedRes, nil)
				cachelog.Printf("Cache HIT on %q -> %v", n.fullPath, cachedRes)
				client.NoteFileUploaded(n.fullPath, false)
				skippedc <- n
				return
			}
		}
		upload <- n
	})

	ticker := time.NewTicker(500 * time.Millisecond)
	defer ticker.Stop()

	stattedc := t.stattedc
Loop:
	for {
		select {
		case <-uploadsdonec:
			break Loop
		case n := <-rootc:
			root = n
		case n := <-uploadedc:
			t.uploaded.incr(n)
			lastUpload = n.fullPath
		case n := <-skippedc:
			t.skipped.incr(n)
		case n, ok := <-stattedc:
			if !ok {
				log.Printf("done stattting:")
				dumpStats()
				close(checkStatCache)
				stattedc = nil
				continue
			}
			lastStat = n.fullPath
			t.total.incr(n)
			checkStatCache <- n
		case <-ticker.C:
			dumpStats()
		}
	}

	log.Printf("tree upload finished. final stats:")
	dumpStats()

	if root == nil {
		panic("unexpected nil root node")
	}
	var err error
	log.Printf("Waiting on root node %q", root.fullPath)
	t.finalPutRes, err = root.PutResult()
	log.Printf("Waited on root node %q: %v", root.fullPath, t.finalPutRes)
	if err != nil {
		t.err = err
	}
}

func (t *TreeUpload) Wait() (*client.PutResult, error) {
	<-t.donec
	// If an error is waiting and we don't otherwise have one, use it:
	if t.err == nil {
		select {
		case t.err = <-t.errc:
		default:
		}
	}
	if t.err == nil && t.finalPutRes == nil {
		panic("Nothing ever set t.finalPutRes, but no error set")
	}
	return t.finalPutRes, t.err
}

type byFileName []os.FileInfo

func (s byFileName) Len() int           { return len(s) }
func (s byFileName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
func (s byFileName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

// trackDigestReader is an io.Reader wrapper which records the digest of what it reads.
type trackDigestReader struct {
	r io.Reader
	h hash.Hash
}

func (t *trackDigestReader) Read(p []byte) (n int, err error) {
	if t.h == nil {
		t.h = sha1.New()
	}
	n, err = t.r.Read(p)
	t.h.Write(p[:n])
	return
}

func (t *trackDigestReader) Sum() string {
	return fmt.Sprintf("sha1-%x", t.h.Sum(nil))
}


text:
enum EventType
{
	KEY,
	MOUSE,
	SCROLL
};

class Event
{
public:
	EventType type;
	int key, scancode, action, mods;
	double x, y;

	Event(int key, int scancode, int action, int mods);
	Event(double xpos, double ypos, bool isScroll = false);
	~Event();
};

redpajama_set_name: RedPajamaGithub


text:
/*jshint strict: false */

////////////////////////////////////////////////////////////////////////////////
/// @brief AQL user functions management
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var arangodb = require("org/arangodb");

var db = arangodb.db;
var ArangoError = arangodb.ArangoError;

// -----------------------------------------------------------------------------
// --SECTION--                               module "org/arangodb/aql/functions"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief return the _aqlfunctions collection
////////////////////////////////////////////////////////////////////////////////

var getStorage = function () {
  'use strict';

  var functions = db._collection("_aqlfunctions");

  if (functions === null) {
    var err = new ArangoError();
    err.errorNum = arangodb.errors.ERROR_ARANGO_COLLECTION_NOT_FOUND.code;
    err.errorMessage = "collection '_aqlfunctions' not found";

    throw err;
  }

  return functions;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief apply a prefix filter on the functions
////////////////////////////////////////////////////////////////////////////////

var getFiltered = function (group) {
  'use strict';

  var result = [ ];

  if (group !== null && group !== undefined && group.length > 0) {
    var prefix = group.toUpperCase();

    if (group.length > 1 && group.substr(group.length - 2, 2) !== '::') {
      prefix += '::';
    }

    getStorage().toArray().forEach(function (f) {
      if (f.name.toUpperCase().substr(0, prefix.length) === prefix) {
        result.push(f);
      }
    });
  }
  else {
    result = getStorage().toArray();
  }

  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief validate a function name
////////////////////////////////////////////////////////////////////////////////

var validateName = function (name) {
  'use strict';

  if (typeof name !== 'string' ||
      ! name.match(/^[a-zA-Z0-9_]+(::[a-zA-Z0-9_]+)+$/) ||
      name.substr(0, 1) === "_") {
    var err = new ArangoError();
    err.errorNum = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_NAME.code;
    err.errorMessage = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_NAME.message;

    throw err;
  }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief validate user function code
////////////////////////////////////////////////////////////////////////////////

var stringifyFunction = function (code, name) {
  'use strict';

  if (typeof code === 'function') {
    code = String(code) + "\n";
  }

  if (typeof code === 'string') {
    code = "(" + code + "\n)";

    if (! internal.parse) {
      // no parsing possible. assume always valid
      return code;
    }

    try {
      if (internal.parse(code, name)) {
        // parsing successful
        return code;
      }
    }
    catch (e) {
    }
  }

  // fall-through intentional

  var err = new ArangoError();
  err.errorNum = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.code;
  err.errorMessage = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.message;

  throw err;
};

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock aqlFunctionsUnregister
/// @brief delete an existing AQL user function
/// `aqlfunctions.unregister(name)`
///
/// Unregisters an existing AQL user function, identified by the fully qualified
/// function name.
///
/// Trying to unregister a function that does not exist will result in an
/// exception.
///
/// @EXAMPLES
///
/// ```js
///   require("org/arangodb/aql/functions").unregister("myfunctions::temperature::celsiustofahrenheit");
/// ```
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

var unregisterFunction = function (name) {
  'use strict';

  var func = null;

  validateName(name);

  try {
    func = getStorage().document(name.toUpperCase());
  }
  catch (err1) {
  }

  if (func === null) {
    var err = new ArangoError();
    err.errorNum = arangodb.errors.ERROR_QUERY_FUNCTION_NOT_FOUND.code;
    err.errorMessage = internal.sprintf(arangodb.errors.ERROR_QUERY_FUNCTION_NOT_FOUND.message, name);

    throw err;
  }

  getStorage().remove(func._id);
  internal.reloadAqlFunctions();

  return true;
};

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock aqlFunctionsUnregisterGroup
/// @brief delete a group of AQL user functions
/// `aqlfunctions.unregisterGroup(prefix)`
///
/// Unregisters a group of AQL user function, identified by a common function
/// group prefix.
///
/// This will return the number of functions unregistered.
///
/// @EXAMPLES
///
/// ```js
///   require("org/arangodb/aql/functions").unregisterGroup("myfunctions::temperature");
///
///   require("org/arangodb/aql/functions").unregisterGroup("myfunctions");
/// ```
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

var unregisterFunctionsGroup = function (group) {
  'use strict';

  if (group.length === 0) {
    var err = new ArangoError();
    err.errorNum = arangodb.errors.ERROR_BAD_PARAMETER.code;
    err.errorMessage = arangodb.errors.ERROR_BAD_PARAMETER.message;

    throw err;
  }

  var deleted = 0;

  getFiltered(group).forEach(function (f) {
    getStorage().remove(f._id);
    deleted++;
  });

  if (deleted > 0) {
    internal.reloadAqlFunctions();
  }

  return deleted;
};

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock aqlFunctionsRegister
/// @brief register an AQL user function
/// `aqlfunctions.register(name, code, isDeterministic)`
///
/// Registers an AQL user function, identified by a fully qualified function
/// name. The function code in *code* must be specified as a JavaScript
/// function or a string representation of a JavaScript function.
/// If the function code in *code* is passed as a string, it is required that
/// the string evaluates to a JavaScript function definition.
///
/// If a function identified by *name* already exists, the previous function
/// definition will be updated. Please also make sure that the function code
/// does not violate the [Conventions](../AqlExtending/Conventions.md) for AQL
/// functions.
///
/// The *isDeterministic* attribute can be used to specify whether the
/// function results are fully deterministic (i.e. depend solely on the input
/// and are the same for repeated calls with the same input values). It is not
/// used at the moment but may be used for optimizations later.
///
/// The registered function is stored in the selected database's system
/// collection *_aqlfunctions*.
///
/// @EXAMPLES
///
/// ```js
///   require("org/arangodb/aql/functions").register("myfunctions::temperature::celsiustofahrenheit",
///   function (celsius) {
///     return celsius * 1.8 + 32;
///   });
/// ```
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

var registerFunction = function (name, code, isDeterministic) {
  // validate input
  validateName(name);

  code = stringifyFunction(code, name);

  var testCode = "(function() { var callback = " + code + "; return callback; })()";
  var err;

  try {
    if (internal && internal.hasOwnProperty("executeScript")) {
      var evalResult = internal.executeScript(testCode, undefined, "(user function " + name + ")");
      if (typeof evalResult !== "function") {
        err = new ArangoError();
        err.errorNum = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.code;
        err.errorMessage = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.message +
                           ": code must be contained in function";
        throw err;
      }
    }
  }
  catch (err1) {
    err = new ArangoError();
    err.errorNum = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.code;
    err.errorMessage = arangodb.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.message;
    throw err;
  }

  var result = db._executeTransaction({
    collections: {
      write: getStorage().name()
    },
    action: function (params) {
      var exists = false;
      var collection = require("internal").db._collection(params.collection);
      var name = params.name;

      try {
        var doc = collection.document(name.toUpperCase());
        if (doc !== null) {
          collection.remove(doc._key);
          exists = true;
        }
      }
      catch (err2) {
      }

      var data = {
        _key: name.toUpperCase(),
        name: name,
        code: params.code,
        isDeterministic: params.isDeterministic || false
      };

      collection.save(data);
      return exists;
    },
    params: {
      name: name,
      code: code,
      isDeterministic: isDeterministic,
      collection: getStorage().name()
    }
  });

  internal.reloadAqlFunctions();

  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock aqlFunctionsToArray
/// @brief list all AQL user functions
/// `aqlfunctions.toArray()`
///
/// Returns all previously registered AQL user functions, with their fully
/// qualified names and function code.
///
/// The result may optionally be restricted to a specified group of functions
/// by specifying a group prefix:
///
/// `aqlfunctions.toArray(prefix)`
///
/// @EXAMPLES
///
/// To list all available user functions:
///
/// ```js
///   require("org/arangodb/aql/functions").toArray();
/// ```
///
/// To list all available user functions in the *myfunctions* namespace:
///
/// ```js
///   require("org/arangodb/aql/functions").toArray("myfunctions");
/// ```
///
/// To list all available user functions in the *myfunctions::temperature* namespace:
///
/// ```js
///   require("org/arangodb/aql/functions").toArray("myfunctions::temperature");
/// ```
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

var toArrayFunctions = function (group) {
  'use strict';

  var result = [ ];

  getFiltered(group).forEach(function (f) {
    result.push({ name: f.name, code: f.code.substr(1, f.code.length - 2).trim() });
  });

  return result;
};

// -----------------------------------------------------------------------------
// --SECTION--                                                    module exports
// -----------------------------------------------------------------------------

exports.unregister      = unregisterFunction;
exports.unregisterGroup = unregisterFunctionsGroup;
exports.register        = registerFunction;
exports.toArray         = toArrayFunctions;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\|/\\*jslint"
// End:


text:
{% extends "base.html" %}
{% block script %}
{% load staticfiles %}
{% endblock script %}
{% block style %}
<link rel="stylesheet" href="{% static "css/bootstrap-responsive.min.css" %}">

{% endblock style %}
{% load widget_tweaks %}
{% block content %}

Free Ideas Spread Faster.

Konkourse is a social network for your school.

Simple course collaboration

Find and connect with friends

Share ideas with others

Now open for popular consumption to students at select universities.

Join the konkourse club.

                <form enctype="multipart/form-data" class="form-horizontal" method="post" action="/register/" autocomplete="off">
                	{% csrf_token %}

                        {{form.first_name}}
                        {{form.first_name.errors}}

                        {{form.last_name}}
                        {{form.last_name.errors}}

                        {{form.email}}

Enter a JMU or VT email address

                        {{form.email.errors}}

                    	{{form.username}}
                    	{{form.username.errors}}

                    	{{form.password}}
                    	{{form.password.errors}}

                    	{{form.password_repeat}}
                    	{{form.password_repeat.errors}}

                   		<button type="submit" class="btn btn-primary" style="float:right; margin-top:4px; margin-bottom:4px; margin-right:2px; width:99%; text-align:center;">Get Started</button>

                </form>

Privacy Policy

General Inquiries

Forgot Password?

{% endblock content %}


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0" is_locked="false">
    <option name="myName" value="Project Default" />
    <option name="myLocal" value="false" />
    <inspection_tool class="CoffeeScriptArgumentsOutsideFunction" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptFunctionSignatures" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptInfiniteLoop" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptLiteralNotFunction" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptSillyAssignment" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptSwitchStatementWithNoDefaultBranch" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptUnnecessaryReturn" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptUnusedLocalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CucumberExamplesColon" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CucumberMissedExamples" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CucumberTableInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CucumberUndefinedStep" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="DartAnalysisServerGlobalInspectionTool" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="DartPathPackageReference" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="EjsUnresolvedInclude" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="GherkinBrokenTableInspection" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="GherkinMisplacedBackground" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="HtmlUnknownAttribute" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="myValues">
        <value>
          <list size="30">
            <item index="0" class="java.lang.String" itemvalue="analytics-event" />
            <item index="1" class="java.lang.String" itemvalue="analytics-category" />
            <item index="2" class="java.lang.String" itemvalue="md-scroll-y" />
            <item index="3" class="java.lang.String" itemvalue="layout-fill" />
            <item index="4" class="java.lang.String" itemvalue="hide-gt-lg" />
            <item index="5" class="java.lang.String" itemvalue="on" />
            <item index="6" class="java.lang.String" itemvalue="target" />
            <item index="7" class="java.lang.String" itemvalue="ng-href" />
            <item index="8" class="java.lang.String" itemvalue="hide-gt-sm" />
            <item index="9" class="java.lang.String" itemvalue="hide-gt-sm" />
            <item index="10" class="java.lang.String" itemvalue="show-gt-sm" />
            <item index="11" class="java.lang.String" itemvalue="show-gt-lg" />
            <item index="12" class="java.lang.String" itemvalue="layout-align" />
            <item index="13" class="java.lang.String" itemvalue="layout-margin" />
            <item index="14" class="java.lang.String" itemvalue="layout-gt-md" />
            <item index="15" class="java.lang.String" itemvalue="src" />
            <item index="16" class="java.lang.String" itemvalue="hide" />
            <item index="17" class="java.lang.String" itemvalue="show-gt-hd" />
            <item index="18" class="java.lang.String" itemvalue="flex-gt-sm" />
            <item index="19" class="java.lang.String" itemvalue="flex-gt-md" />
            <item index="20" class="java.lang.String" itemvalue="quick-repeat-list" />
            <item index="21" class="java.lang.String" itemvalue="layout-padding" />
            <item index="22" class="java.lang.String" itemvalue="flex" />
            <item index="23" class="java.lang.String" itemvalue="layout" />
            <item index="24" class="java.lang.String" itemvalue="layout-wrap" />
            <item index="25" class="java.lang.String" itemvalue="flex-sm" />
            <item index="26" class="java.lang.String" itemvalue="infinite-scroll-distance" />
            <item index="27" class="java.lang.String" itemvalue="infinite-scroll-container" />
            <item index="28" class="java.lang.String" itemvalue="app-animation-no-click" />
            <item index="29" class="java.lang.String" itemvalue="ng-repeat-end" />
          </list>
        </value>
      </option>
      <option name="myCustomValuesEnabled" value="true" />
    </inspection_tool>
    <inspection_tool class="HtmlUnknownTag" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="myValues">
        <value>
          <list size="4">
            <item index="0" class="java.lang.String" itemvalue="md-item-content" />
            <item index="1" class="java.lang.String" itemvalue="md-card-content" />
            <item index="2" class="java.lang.String" itemvalue="md-item" />
            <item index="3" class="java.lang.String" itemvalue="md-dialog-content" />
          </list>
        </value>
      </option>
      <option name="myCustomValuesEnabled" value="true" />
    </inspection_tool>
    <inspection_tool class="MeteorUnresolvedSymbol" enabled="false" level="WARNING" enabled_by_default="false" />
  </profile>
</component>


text:
<?php
include_once(Mage::getBaseDir('lib') . DS . 'Conekta' . DS . 'lib' . DS . 'Conekta.php');
class Conekta_Bank_Model_Observer{
  public function processPayment($event){
    if (!class_exists('Conekta')) {
      error_log("Plugin miss Conekta PHP lib dependency. Clone the repository using 'git clone --recursive git@github.com:conekta/conekta-magento.git'", 0);
      throw new Mage_Payment_Model_Info_Exception("Payment module unavailable. Please contact system administrator.");
    }
    if($event->payment->getMethod() == Mage::getModel('Conekta_Bank_Model_Bank')->getCode()){
      Conekta::setApiKey(Mage::getStoreConfig('payment/bank/privatekey'));
      Conekta::setLocale(Mage::app()->getLocale()->getLocaleCode());
      $billing = $event->payment->getOrder()->getBillingAddress()->getData();
      $email = $event->payment->getOrder()->getCustomerEmail();
      if ($event->payment->getOrder()->getShippingAddress()) {
        $shipping = $event->payment->getOrder()->getShippingAddress()->getData();
      }
      $items = $event->payment->getOrder()->getAllVisibleItems();
      $line_items = array();
      $i = 0;
      foreach ($items as $itemId => $item){
        $name = $item->getName();
        $sku = $item->getSku();
        $price = $item->getPrice();
        $description = $item->getDescription();
        $product_type = $item->getProductType();
        $line_items = array_merge($line_items, array(array(
          'name' => $name,
          'sku' => $sku,
          'unit_price' => $price,
          'description' =>$description,
          'quantity' => 1,
          'type' => $product_type
          ))
        );
        $i = $i + 1;
      }
      $shipp = array();
      if (empty($shipping) != true) {
        $shipp = array(
          #'price' => $shipping['grand_total'],
          'address' => array(
            'street1' => $shipping['street'],
            'city' => $shipping['city'],
            'state' => $shipping['region'],
            'country' => $shipping['country_id'],
            'zip' => $shipping['postcode'],
            'phone' =>$shipping['telephone'],
            'email' =>$email
            )
          );
      }
      $days = $event->payment->getMethodInstance()->getConfigData('my_date');
      $expiry_date=Date('Y-m-d', strtotime("+".$days." days"));
      try {
        $charge = Conekta_Charge::create(array(
          'bank'=>array(
            'type'=>'banorte',
            'expires_at'=>$expiry_date
            ),
          'currency' => Mage::app()->getStore()->getCurrentCurrencyCode(),
          'amount' => intval(((float) $event->payment->getOrder()->grandTotal) * 100),
          'description' => 'Compra en Magento',
          'reference_id' => $event->payment->getOrder()->getIncrementId(),
          'details' => array(
            'name' => preg_replace('!\s+!', ' ', $billing['firstname'] . ' ' . $billing['middlename'] . ' ' . $billing['firstname']),
            'email' => $email,
            'phone' => $billing['telephone'],
            'billing_address' => array(
              'company_name' => $billing['company'],
              'street1' => $billing['street'],
              'city' =>$billing['city'],
              'state' =>$billing['region'],
              'country' =>$billing['country_id'],
              'zip' =>$billing['postcode'],
              'phone' =>$billing['telephone'],
              'email' =>$email
              ),
            'line_items' => $line_items,
            'shipment' => $shipp
            )
          )
        );
      } catch (Conekta_Error $e){
        throw new Mage_Payment_Model_Info_Exception($e->message_to_purchaser);
      }
      $event->payment->setBankExpiryDate($expiry_date);
      $event->payment->setBankServiceName($charge->payment_method->service_name);
      $event->payment->setBankServiceNumber($charge->payment_method->service_number);
      $event->payment->setBankName($charge->payment_method->type);
      $event->payment->setBankReference($charge->payment_method->reference);
      $event->payment->setChargeId($charge->id);

      //Update Quote
      $order = $event->payment->getOrder();
      $quote = $order->getQuote();
      $payment = $quote->getPayment();
      $payment->setBankExpiryDate($expiry_date);
      $payment->setBankServiceName($charge->payment_method->service_name);
      $payment->setBankServiceNumber($charge->payment_method->service_number);
      $payment->setBankName($charge->payment_method->type);
      $payment->setBankReference($charge->payment_method->reference);
      $payment->setChargeId($charge->id);
      $quote->collectTotals();
      $quote->save();
      $order->setQuote($quote);
      $order->save();
    }
    return $event;
  }
}


text:
package DDG::Goodie::Minecraft;
# ABSTRACT: Minecraft crafting recipes.

use strict;
use DDG::Goodie;
use JSON::MaybeXS;

zci answer_type => 'minecraft';
zci is_cached => 1;

# Triggers: words that trigger the IA
triggers startend => "minecraft";

# Get goodie version for image paths
my $goodieVersion = $DDG::GoodieBundle::OpenSourceDuckDuckGo::VERSION // 999;
# Fetch and store recipes in a hash.
my $json = share('crafting-guide.json')->slurp;
#my $json = share('crafting-guide.json')->slurp(iomode => '<:encoding(UTF-8)'); # If description(s) contain(s) unicode
my $decoded = decode_json($json);
my %recipes = map{ lc $_->{'name'} => $_ } (@{ $decoded->{'items'} });
my @recipe_names = sort { length($b) <=> length($a) } keys %recipes;

# Extra words: Words that could be a part of the query, but not part of a recipe
my @extra_words = ('a','an','in','crafting','recipe','how to','make','craft','how do I','for','what is','the','on');

handle remainder => sub {
    my $remainder = $_;
    my $recipe;

    # Find recipe name and regex
    foreach my $recipe_name (@recipe_names) {
        my $regex = $recipes{$recipe_name}->{'regex'} // $recipe_name;

        if ($remainder =~ s/\b$regex\b//i) {
            $recipe = $recipes{$recipe_name};
            last;
       }
    }
    return unless $recipe; # Return if we don't have a valid recipe match

    # Remove the extra words (or phrases)
    foreach my $extra_word (@extra_words) {
        $remainder =~ s/\b$extra_word\b//gi;
    }
    return if $remainder && $remainder !~ m/^\s+$/; # Return if we had leftover unwanted words (not just whitespace)

    # Get image correct path
    my $image;
    my $imageName = $recipe->{'imageName'};
    my $localImage = $recipe->{'localImage'} // "no";

    if ($localImage eq "yes") { # If local image is used
        $image = "/share/goodie/minecraft/$goodieVersion/images/$imageName";
    } else { # If remote image is used
        $image = $imageName;
    }

    # Run an answer
    my $plaintext = 'Minecraft ' . $recipe->{'name'} . ' ingredients: ' . $recipe->{'ingredients'} . '.';

    return $plaintext,
    structured_answer => {
        data => {
            title => $recipe->{'name'},
            subtitle => "Ingredients: " . $recipe->{'ingredients'},
            description => $recipe->{'description'},
            image => $image,
            imageTile => 1
        },
        meta => {
            sourceName => "Minecraft Wiki",
            sourceUrl => "http://minecraft.gamepedia.com/"  . uri_esc( $recipe->{'name'} ) # Not the best way to
        },
        templates => {
            group => 'info',
            options => {
                moreAt => 1
            }
        }
    };
};

1;


text:
import static org.junit.Assert.*;

import org.junit.Test;

/**
 * tests class IntegerRange
 *
 * @author saba
 *
 */
public class IntegerRangeTester {

	@Test
	public void inRangeTest() throws UncorrectRangeException {
		IntegerRange range = new IntegerRange(0, 5);
		assertTrue(range.isInRange(3));
		assertTrue(range.isInRange(4));
		assertTrue(range.isInRange(1));
		assertFalse(range.isInRange(10));
		assertFalse(range.isInRange(-3));
	}

	@Test
	public void criticalPointsInRangeTest() throws UncorrectRangeException {
		IntegerRange range = new IntegerRange(-1, 7);
		assertTrue(range.isInRange(-1));
		assertTrue(range.isInRange(6));
		assertFalse(range.isInRange(7));
		assertFalse(range.isInRange(-2));
	}

	@Test(expected = UncorrectRangeException.class)
	public void uncorrectRangeTest1() throws UncorrectRangeException {
		IntegerRange range2 = new IntegerRange(1, 1);
	}

	@Test(expected = UncorrectRangeException.class)
	public void uncorrectRangeTest2() throws UncorrectRangeException {
		IntegerRange range1 = new IntegerRange(2, 1);
	}

	@Test
	public void intersectWhenOneRangeContainsAnotherTest()
			throws UncorrectRangeException {
		IntegerRange range1 = new IntegerRange(2, 7);
		IntegerRange range2 = new IntegerRange(3, 6);
		IntegerRange range3 = new IntegerRange(2, 5);
		IntegerRange range4 = new IntegerRange(4, 7);
		IntegerRange res1 = range1.intersectWithRange(range2);
		IntegerRange res2 = range1.intersectWithRange(range3);
		IntegerRange res3 = range1.intersectWithRange(range4);
		assertEquals(res1.getBegining(), 3);
		assertEquals(res1.getEnd(), 6);
		assertEquals(res2.getBegining(), 2);
		assertEquals(res2.getEnd(), 5);
		assertEquals(res3.getBegining(), 4);
		assertEquals(res3.getEnd(), 7);

	}

	@Test
	public void intersectingRangesTest() throws UncorrectRangeException {
		IntegerRange range1 = new IntegerRange(2, 7);
		IntegerRange range2 = new IntegerRange(6, 9);
		IntegerRange range3 = new IntegerRange(0, 4);
		IntegerRange res1 = range1.intersectWithRange(range2);
		IntegerRange res2 = range1.intersectWithRange(range3);
		assertEquals(res1.getBegining(), 6);
		assertEquals(res1.getEnd(), 7);
		assertEquals(res2.getBegining(), 2);
		assertEquals(res2.getEnd(), 4);

	}

	@Test(expected = UncorrectRangeException.class)
	public void unIntersectingRangesIntersectTest1()
			throws UncorrectRangeException {
		IntegerRange range1 = new IntegerRange(2, 7);
		IntegerRange range2 = new IntegerRange(7, 9);
		range1.intersectWithRange(range2);
	}

	@Test(expected = UncorrectRangeException.class)
	public void unIntersectingRangesIntersectTest2()
			throws UncorrectRangeException {
		IntegerRange range1 = new IntegerRange(2, 7);
		IntegerRange range2 = new IntegerRange(0, 2);
		range1.intersectWithRange(range2);
	}

	@Test(expected = UncorrectRangeException.class)
	public void unIntersectingRangesIntersectTest3()
			throws UncorrectRangeException {
		IntegerRange range1 = new IntegerRange(2, 7);
		IntegerRange range2 = new IntegerRange(7, 9);
		range1.intersectWithRange(range2);
	}

}


text:
'use strict';
const securityManager = require('./db/SecurityManager');

// checks for padAccess
module.exports = async (req, res) => {
  const {session: {user} = {}} = req;
  const accessObj = await securityManager.checkAccess(
      req.params.pad, req.cookies.sessionID, req.cookies.token, user);

  if (accessObj.accessStatus === 'grant') {
    // there is access, continue
    return true;
  } else {
    // no access
    res.status(403).send("403 - Can't touch this");
    return false;
  }
};


text:
package org.apache.spark.sql.rocketmq

import java.{util => ju}

import org.apache.rocketmq.common.message.MessageQueue
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization

import scala.collection.JavaConverters._
import scala.util.control.NonFatal

/**
  * Utilities for converting RocketMQ related objects to and from json.
  */
private object JsonUtils {

  private implicit val formats = Serialization.formats(NoTypeHints)

  /**
    * Read MessageQueues from json string
    */
  def partitions(str: String): Array[MessageQueue] = {
    try {
      Serialization.read[Map[String, Map[String, Seq[Int]]]](str).flatMap { case (topic, broker) =>
        broker.flatMap { bq =>
          bq._2.map(qid => new MessageQueue(topic, bq._1, qid))
        }
      }.toArray
    } catch {
      case NonFatal(x) =>
        throw new IllegalArgumentException(
          s"""Expected e.g. {"topicA":{"broker1":[0,1],"broker2":[0,1]},"topicB":{"broker3":[0,1]}}, got $str""")
    }
  }

  /**
    * Write MessageQueues as json string
    */
  def partitions(mqs: Iterable[MessageQueue]): String = {
    var result = Map[String, Map[String, List[Int]]]()
    mqs.foreach { q =>
      var brokers = result.getOrElse(q.getTopic, Map.empty)
      var queueIds = brokers.getOrElse(q.getBrokerName, List.empty)
      queueIds = queueIds :+ q.getQueueId
      brokers += q.getBrokerName -> queueIds
      result += q.getTopic -> brokers
    }
    Serialization.write(result)
  }

  /**
    * Read per-MessageQueue offsets from json string
    */
  def partitionOffsets(str: String): Map[MessageQueue, Long] = {
    try {
      Serialization.read[Map[String, Map[String, Map[Int, Long]]]](str).flatMap { case (topic, brokers) =>
        brokers.flatMap { case (broker, queues) =>
          queues.map { case (queue, offset) =>
            new MessageQueue(topic, broker, queue) -> offset
          }
        }
      }.toMap
    } catch {
      case NonFatal(x) =>
        throw new IllegalArgumentException(
          s"""Expected e.g. {"topicA":{"broker1":{"0":23,"1":-1},"broker2":{"0":23}},"topicB":{"broker3":{"0":-2}}}, got $str""")
    }
  }

  /**
    * Write per-MessageQueue offsets as json string
    */
  def partitionOffsets(queueOffsets: Map[MessageQueue, Long]): String = {
    var result = Map[String, Map[String, Map[Int, Long]]]()
    val partitions = queueOffsets.keySet.toSeq.sorted // sort for more determinism
    partitions.foreach { q =>
      val offset = queueOffsets(q)
      var brokers = result.getOrElse(q.getTopic, Map.empty)
      var queues = brokers.getOrElse(q.getBrokerName, Map.empty)
      queues += q.getQueueId -> offset
      brokers += q.getBrokerName -> queues
      result += q.getTopic -> brokers
    }
    Serialization.write(result)
  }

  /**
    * Serialize RocketMQ message properties as json string
    */
  def messageProperties(properties: ju.Map[String, String]): String = {
    Serialization.write(properties.asScala)
  }
}


text:
<?php

/**
 * This is a model for "posts". It provides access
 * to blog posts information, currently with bogus data.
 *
 * @author Calvin Rempel
 */
class Posts extends CI_Model {

    /**
     * Construct the base CI_Model
     */
    public function __construct() {
        parent::__construct();
    }

    public function create($title, $description, $content, $image, $thumbnail, $date) {
        $data = array (
          'title'       => $title,
          'description' => $description,
          'content'     => $content,
          'image'       => $image,
          'thumbnail'   => $thumbnail,
          'date'        => $date
        );

        $this->db->insert('posts', $data);
    }

    public function edit($id, $title, $description, $content, $image, $thumbnail, $date) {
        $data = array (
          'title'       => $title,
          'description' => $description,
          'content'     => $content,
          'image'       => $image,
          'thumbnail'   => $thumbnail,
          'date'        => $date
        );

        $this->db->where('id', $id);
        $this->db->update('posts', $data);
    }

    /**
     * Get the Post with the given ID
     *
     * @param int $id the ID of the Post to get
     * @return Post data
     */
    public function getById($id) {
        $this->db->where('id', $id);
        return (array) $this->db->get('posts')->row();
    }

    /**
     * Get Posts on a certain page with the given number
     * of Posts per page.
     *
     * @param int $page the Page number (1-n) inclusive.
     * @param int $perPage the number of Posts to return per page.
     * @return Post data
     */
    public function getPaginated($page, $perPage) {
        $this->db->limit($perPage, ($page * $perPage) - $perPage);
        $data = $this->db->get('posts')->result();

        return (array) $data;
    }

    /**
     * Get Recent Posts
     *
     * @param int $perPage the number of Posts to return per page.
     * @return Post data
     */
    public function getRecent($perPage) {
        $this->db->limit($perPage, 0);
        $this->db->order_by('id', 'desc');
        $data = $this->db->get('posts')->result();

        return (array) $data;
    }

    /**
     * Get the number of pages required to show all Posts with the given number of
     * Posts per page.
     *
     * @param int $perPage the number of posts per page
     * @return int the number of pages required to show all posts.
     */
    public function getPageCount($perPage)
    {
        return ceil($this->db->count_all('posts') / $perPage);
    }
}


text:
.class public abstract Landroid/telecom/RemoteConference$Callback;
.super Ljava/lang/Object;
.source "RemoteConference.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/telecom/RemoteConference;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "Callback"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 43
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onConferenceableConnectionsChanged(Landroid/telecom/RemoteConference;Ljava/util/List;)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/telecom/RemoteConference;",
            "Ljava/util/List",
            "<",
            "Landroid/telecom/RemoteConnection;",
            ">;)V"
        }
    .end annotation

    .prologue
    .line 53
    .local p2, "conferenceableConnections":Ljava/util/List;, "Ljava/util/List<Landroid/telecom/RemoteConnection;>;"
    return-void
.end method

.method public onConnectionAdded(Landroid/telecom/RemoteConference;Landroid/telecom/RemoteConnection;)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;
    .param p2, "connection"    # Landroid/telecom/RemoteConnection;

    .prologue
    .line 46
    return-void
.end method

.method public onConnectionCapabilitiesChanged(Landroid/telecom/RemoteConference;I)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;
    .param p2, "connectionCapabilities"    # I

    .prologue
    .line 50
    return-void
.end method

.method public onConnectionRemoved(Landroid/telecom/RemoteConference;Landroid/telecom/RemoteConnection;)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;
    .param p2, "connection"    # Landroid/telecom/RemoteConnection;

    .prologue
    .line 47
    return-void
.end method

.method public onDestroyed(Landroid/telecom/RemoteConference;)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;

    .prologue
    .line 54
    return-void
.end method

.method public onDisconnected(Landroid/telecom/RemoteConference;Landroid/telecom/DisconnectCause;)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;
    .param p2, "disconnectCause"    # Landroid/telecom/DisconnectCause;

    .prologue
    .line 45
    return-void
.end method

.method public onStateChanged(Landroid/telecom/RemoteConference;II)V
    .locals 0
    .param p1, "conference"    # Landroid/telecom/RemoteConference;
    .param p2, "oldState"    # I
    .param p3, "newState"    # I

    .prologue
    .line 44
    return-void
.end method


text:
module SimpleCqrs
  module Processor

    def process(command, event_store: [])
      @event_store = event_store
      send(command.command_name, command) if self.respond_to?(command.command_name.to_sym)
    end

    private

    attr_reader :event_store

    def notify(event)
      event_store.append(event)
    end

    def next_id_for(command)
      # TODO: Turn this into a strategy.
      ::SimpleCqrs::CommandId.next(command.class.name)
    end

    attr_reader :events
  end
end


text:
"use strict";

const should = require("should");
const assert = require("node-opcua-assert").assert;
const SequenceNumberGenerator = require("..").SequenceNumberGenerator;
const SecureMessageChunkManager = require("..").SecureMessageChunkManager;
const decompose_message_body_in_chunks = require("../dist/test_helpers").decompose_message_body_in_chunks;

describe("decompose message body in chunks", function () {

    it("should decompose a message body in at least one chunk ", function () {
        const message_body = Buffer.from("At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis");
        const chunks = decompose_message_body_in_chunks(message_body, "MSG", 128);
        chunks.length.should.be.greaterThan(0);
    });
});


text:
namespace ERDashboard.Models
{
    using System;
    using System.Collections.Generic;

    public partial class ChatRole
    {
        public ChatRole()
        {
            this.ChatResponses = new HashSet<ChatRespons>();
        }

        public int ID { get; set; }
        public string Name { get; set; }

        public virtual ICollection<ChatRespons> ChatResponses { get; set; }
    }
}


text:
<?php

class phalconCSSFormPureCSS extends \Phalcon\Forms\Form {

    private $_method = "post";
    private $_enctype = false;
    private $_formAttributes = [];
    private $_fieldsets = [];
    private $_inputElements = [];
    private $_hiddenElements = [];
    private $_currentFieldset = NULL;

    /**
     * Set the method of the form
     * @param string $method
     */
    protected function setMethod($method) {
        $this->_method = $method;
    }

    /**
     * Set if the form will upload files
     * @param bool $upload
     */
    protected function fileUpload($upload) {
        $this->_enctype = $upload;
    }

    /**
     * Set the attributes of the form
     * @param array $attributes
     */
    protected function setAttributes($attributes) {
        $this->_formAttributes = $attributes;
    }

    /**
     * Adds an element to the form
     * @param \Phalcon\Forms\ElementInterface $element
     */
    public function add($element) {
        $type = strtolower(current(array_reverse(explode("\\", get_class($element)))));
        parent::add($element);
        if ($type == "hidden")
            $this->_hiddenElements[] = $element;
        else
            $this->_inputElements[] = [$element, $this->_currentFieldset];
    }

    /**
     * Set the beginning of the fieldset
     * @param string $label
     * @param array $attributes
     */
    public function startFieldset($label, $attributes = []) {
        $this->_fieldsets[] = [
            $label,
            $attributes
        ];
        $this->_currentFieldset = count($this->_fieldsets) - 1;
    }

    /**
     * Set the end of the fieldset
     */
    public function endFieldset() {
        $this->_currentFieldset = NULL;
    }

    /**
     * Render in HTML an element of the form
     * @param string $name
     * @return string
     */
    public function renderElement($name) {
        $element = $this->get($name);
        $type = strtolower(current(array_reverse(explode("\\", get_class($element)))));

        $method = "_render" . ucfirst($type);
        if (method_exists($this, $method))
            $html = $this->$method($element);
        else
            $html = $this->_renderDefault($element);
        return $html;
    }

    /**
     * Render in HTML all the form
     * @return string
     */
    public function renderForm() {
        $enctype = $this->_enctype ? "enctype=\"multipart/form-data\"" : "";
        $elementClasses = "pure-form pure-form-stacked ";
        if (isset($this->_formAttributes["class"])) {
            $elementClasses .= $this->_formAttributes["class"];
            unset($this->_formAttributes["class"]);
        }
        $formAttributes = $this->_renderAttributes($this->_formAttributes);
        $html = "<form action=\"{$this->getAction()}\" method=\"{$this->_method}\" {$enctype} {$formAttributes} class=\"{$elementClasses}\">";
        $currentFieldset = NULL;

        if (count($this->_inputElements)) {
            foreach ($this->_inputElements as $element) {
                if ($element[1] !== NULL) {
                    if ($element[1] !== $currentFieldset) {
                        if ($currentFieldset !== NULL)
                            $html .= "</fieldset>";
                        $fieldset = $this->_fieldsets[$element[1]];
                        $fieldsetAttributes = $this->_renderAttributes($fieldset[1]);
                        $html .= "<fieldset {$fieldsetAttributes}><legend>{$fieldset[0]}</legend>";
                        $currentFieldset = $element[1];
                    }
                } else {
                    if ($currentFieldset !== NULL)
                        $html .= "</fieldset>";
                }
                $html .= $this->renderElement($element[0]->getName());
                $currentFieldset = $element[1];
            }
        }
        if (count($this->_hiddenElements)) {
            foreach ($this->_hiddenElements as $element) {
                $html .= $this->renderElement($element->getName());
            }
        }
        $html .= "</form>";
        return $html;
    }

    /**
     * Render an inline HTML string which contains attributes
     * @param array $attributes
     * @return string
     */
    private function _renderAttributes($attributes) {
        $html = "";
        if (count($attributes)) {
            foreach ($attributes as $attribute => $value) {
                $html .= " {$attribute}=\"{$value}\" ";
            }
        }
        return trim($html);
    }

    /*
     * ---------------------------------------------------
     * Elements
     * ---------------------------------------------------
     */

    /**
     * Render in HTML an element of any type
     * @param \Phalcon\Forms\ElementInterface $element
     * @return string
     */
    function _renderDefault($element) {
        $messages = $this->getMessagesFor($element->getName());
        $hasMessages = count($messages) > 0 ? TRUE : FALSE;

        $html = "
getName()}\">{$element->getLabel()}";
        $html .= $this->render($element->getName());
        $html .= "
";
        if ($hasMessages)
            $html .= "
{$messages[0]}
";
        return $html;
    }

    /**
     * Render in HTML an element of type Checkobx
     * @param \Phalcon\Forms\ElementInterface $element
     * @return string
     */
    function _renderCheck($element) {
        $messages = $this->getMessagesFor($element->getName());
        $hasMessages = count($messages) > 0 ? TRUE : FALSE;

        $html = "
getName()}\">{$this->render($element->getName())} {$element->getLabel()}
";
        if ($hasMessages)
            $html .= "
{$messages[0]}
";
        return $html;
    }

    /**
     * Render in HTML an element of type Radio
     * @param \Phalcon\Forms\ElementInterface $element
     * @return string
     */
    function _renderRadio($element) {
        $messages = $this->getMessagesFor($element->getName());
        $hasMessages = count($messages) > 0 ? TRUE : FALSE;

        $html = "
getName()}\">{$this->render($element->getName())} {$element->getLabel()}
";
        if ($hasMessages)
            $html .= "
{$messages[0]}
";
        return $html;
    }

    /**
     * Render in HTML an element of type Hidden
     * @param \Phalcon\Forms\ElementInterface $element
     * @return string
     */
    function _renderHidden($element) {
        $html = $this->render($element->getName());
        return $html;
    }

    /**
     * Render in HTML an element of type Submit
     * @param \Phalcon\Forms\ElementInterface $element
     * @return string
     */
    function _renderSubmit($element) {
        $elementClasses = "pure-button " . $element->getAttribute("class", "");
        $element->setAttribute("class", $elementClasses);
        $html = $this->render($element->getName());
        return $html;
    }

}


text:
@interface SocketIO (SailsIO)

#pragma mark - Request convenience methods
- (void) get:(NSString *) url withData: (NSDictionary *) data callback:(void (^)(id response)) callback;

- (void) post:(NSString *) url withData: (NSDictionary *) data callback:(void (^)(id response)) callback;

- (void) put:(NSString *) url withData:(NSDictionary *) data callback:(void (^)(id response)) callback;

- (void) delete:(NSString *) url withData:(NSDictionary *) data callback:(void (^)(id response)) callback;

#pragma mark - Method that makes the actual request
- (void) request:(NSString *) url withData:(NSDictionary *) data callback:(void (^)(id response)) callback method:(NSString *)method;

@end


text:
/* \file xtract_types.h: declares specialised variable types used by libxtract */

#ifndef XTRACT_TYPES_H
#define XTRACT_TYPES_H

#ifdef __cplusplus
extern "C" {
#endif

/* \brief Data structure used to store amplitude data between calls to xtract_attack_time and other functions. */
typedef struct _xtract_amp_tracker {
    int count;
    double previous_amp;
} xtract_amp_tracker;

typedef struct _xtract_frame_tracker {
    int frame_count;
    double *previous_frame;
} xtract_frame_tracker;

#ifdef __cplusplus
}
#endif

#endif


text:
require 'rbeapi/api'

##
# Rbeapi toplevel namespace.
module Rbeapi
  ##
  # Api is module namespace for working with the EOS command API.
  module Api
    ##
    # The Aaa class manages Authorization, Authentication and Accounting (AAA)
    # on an EOS node.
    class Aaa < Entity
      ##
      # get returns a hash of all Aaa resources.
      #
      # @example
      #   {
      #     <groups>: {
      #       <name>: {
      #         type: <string>,
      #         servers: <array>
      #       },
      #       <name>: {
      #         type: <string>,
      #         servers: <array>
      #       }
      #     }
      #   }
      #
      # @return [Hash<Symbol, Object>] Returns the Aaa resources as a
      #   Hash. If no Aaa resources are found, an empty hash is returned.
      def get
        response = {}
        response[:groups] = groups.getall
        response
      end

      ##
      # Returns an object node for working with AaaGroups class.
      def groups
        return @groups if @groups
        @groups = AaaGroups.new node
        @groups
      end
    end

    ##
    # The AaaGroups class manages the server groups on an EOS node.
    class AaaGroups < Entity
      DEFAULT_RADIUS_AUTH_PORT = 1812
      DEFAULT_RADIUS_ACCT_PORT = 1813

      # Regular expression that parses the radius servers from the aaa group
      # server radius configuration block.
      RADIUS_GROUP_SERVER = /\s{3}server
                             [ ]([^\s]+)
                             [ ]auth-port[ ](\d+)
                             [ ]acct-port[ ](\d+)/x

      # Regular expression that parses the tacacs servers from the aaa group
      # server tacacs+ configuration block.
      TACACS_GROUP_SERVER = /\s{3}server
                             [ ]([^\s]+)
                             (?:[ ]vrf[ ](\w+))?
                             (?:[ ]port[ ](\d+))?/x

      ##
      # get returns the aaa server group resource hash that describes the
      # current configuration for the specified server group name.
      #
      # @example
      #   {
      #     type: <string>,
      #     servers: <array>
      #   }
      #
      # @param name [String] The server group name to return from the nodes
      #   current running configuration. If the name is not configured a nil
      #   object is returned.
      #
      # @return [nil, Hash<Symbol, Object>] Returns the resource hash for the
      #   specified name. If the name does not exist, a nil object is returned.
      def get(name)
        block = get_block("aaa group server ([^\s]+) #{name}")
        return nil unless block
        response = {}
        response.merge!(parse_type(block))
        response.merge!(parse_servers(block, response[:type]))
        response
      end

      ##
      # getall returns a aaa server groups hash.
      #
      # @example
      #   {
      #     <name>: {
      #       type: <string>,
      #       servers: <array>
      #     },
      #     <name>: {
      #       type: <string>,
      #       servers: <array>
      #     }
      #   }
      #
      # @return [Hash<Symbol, Object>] Returns the resource hashes for
      #   configured aaa groups. If none exist, a nil object is returned.
      def getall
        cfg = config.scan(/aaa group server (?:radius|tacacs\+) (.+)$/)
        cfg.each_with_object({}) do |name, hsh|
          values = get(name.first)
          hsh[name.first] = values if values
        end
      end

      ##
      # parse_type scans the specified configuration block and returns the
      # server group type as either 'tacacs' or 'radius'. The type value is
      # expected to always be present in the config.
      #
      # @api private
      #
      # @param config [String] The aaa server group block configuration for the
      #   group name to parse.
      #
      # @return [Hash<Symbol, Object>] Resource hash attribute.
      def parse_type(config)
        value = config.scan(/aaa group server ([^\s]+)/).first
        { type: value.first }
      end
      private :parse_type

      ##
      # parse_servers scans the specified configuraiton block and returns the
      # list of servers configured for the group. If there are no servers
      # configured for the group the servers value will return an empty array.
      #
      # @api private
      #
      # @see parse_radius_server
      # @see parse_tacacs_server
      #
      # @param config [String] The aaa server group block configuration for the
      #   group name to parse.
      #
      # @param type [String] The aaa server block type. Valid values are
      #   either radius or tacacs+.
      #
      # @return [Hash<Symbol, Object>] Resource hash attribute
      def parse_servers(config, type)
        case type
        when 'radius' then parse_radius_server(config)
        when 'tacacs+' then parse_tacacs_server(config)
        end
      end
      private :parse_servers

      ##
      # parse_radius_server scans the provide configuration block and returns
      # the list of servers configured. The configuration block is expected to
      # be a radius configuration block. If there are no servers configured
      # for the group the servers value will return an empty array.
      #
      # @api private
      #
      # @param config [String] The aaa server group block configuration for the
      #   group name to parse
      #
      # @return [Hash<Symbol, Object>] resource hash attribute
      def parse_radius_server(config)
        values = config.scan(RADIUS_GROUP_SERVER).map do |(name, auth, acct)|
          {
            name: name,
            auth_port: auth || DEFAULT_RADIUS_AUTH_PORT,
            acct_port: acct || DEFAULT_RADIUS_ACCT_PORT
          }
        end
        { servers: values }
      end
      private :parse_radius_server

      ##
      # parse_tacacs_server scans the provided configuration block and returns
      # the list of configured servers. The configuration block is expected to
      # be a tacacs configuration block. If there are no servers configured
      # for the group the servers value will return an empty array.
      #
      # @api private
      #
      # @param config [String] The aaa server group block configuration for the
      #   group name to parse.
      #
      # @return [Hash<Symbol, Object>] Resource hash attribute.
      def parse_tacacs_server(config)
        values = config.scan(TACACS_GROUP_SERVER).map do |(name, vrf, port)|
          {
            name: name,
            vrf: vrf,
            port: port
          }
        end
        { servers: values }
      end
      private :parse_radius_server

      ##
      # find_type is a utility method to find the type of aaa server group for
      # the specified name. This method will scan the current running
      # configuration on the node and return the server group type as either
      # 'radius' or 'tacacs+'. If the server group is not configured, then nil
      # will be returned.
      #
      # @api private
      #
      # @param name [String] The aaa server group name to find in the config
      #   and return the type value for.
      #
      # @return [nil, String] Returns either the type name as 'radius' or
      #   'tacacs+' or nil if the server group is not configured.
      def find_type(name)
        mdata = /aaa group server ([^\s]+) #{name}/.match(config)
        return mdata[1] if mdata
      end
      private :find_type

      ##
      # create adds a new aaa group server to the nodes current configuration.
      # If the specified name and type are already created then this method
      # will return successfully. If the name is configured but the type is
      # different, this method will not return successfully (returns false).
      #
      # @since eos_version 4.13.7M
      #
      # ===Commands
      #   aaa group server <type> <name>
      #
      # @param name [String] The name of the aaa group server to create in the
      #   nodes running configuration
      #
      # @param type [String] The type of aaa group server to create in the
      #   nodes running configuration. Valid values include 'radius' or
      #   'tacacs+'
      #
      # @return [Boolean] returns true if the commands complete successfully
      def create(name, type)
        configure ["aaa group server #{type} #{name}", 'exit']
      end

      ##
      # delete removes a current aaa server group from the nodes current
      # configuration. This method will automatically determine the server
      # group type based on the name. If the name is not configured in the
      # nodes current configuration, this method will return successfully.
      #
      # @since eos_version 4.13.7M
      #
      # ===Commands
      #   no aaa group server [radius | tacacs+] <name>
      #
      # @param name [String] The name of the aaa group server to create in the
      #   nodes running configuration.
      #
      # @return [Boolean] Returns true if the commands complete successfully.
      def delete(name)
        type = find_type(name)
        return true unless type
        configure "no aaa group server #{type} #{name}"
      end

      ##
      # set_servers configures the set of servers for a specified aaa server
      # group. This is an atomic operation that first removes all current
      # servers and then adds the new servers back. If any of the servers
      # failes to be removed or added, this method will return unsuccessfully.
      #
      # @see remove_server
      # @see add_server
      #
      # @param name [String] The name of the aaa group server to add the new
      #   server configuration to.
      #
      # @param servers [String] The IP address or host name of the server to
      #   add to the configuration
      #
      # @return [Boolean] Returns true if the commands complete successfully
      def set_servers(name, servers)
        current = get(name)
        current[:servers].each do |srv|
          return false unless remove_server(name, srv)
        end
        servers.each do |srv|
          hostname = srv[:name]
          return false unless add_server(name, hostname, srv)
        end
        true
      end

      ##
      # add_server adds a new server to the specified aaa server group. If
      # the server is already configured in the list of servers, this method
      # will still return successfully.
      #
      # @see add_radius_server
      # @see add_tacacs_server
      #
      # @param name [String] The name of the aaa group server to add the new
      #   server configuration to.
      #
      # @param server [String] The IP address or host name of the server to
      #   add to the configuration.
      #
      # @param opts [Hash] Optional configuration parameters.
      #
      # @return [Boolean] Returns true if the commands complete successfully.
      def add_server(name, server, opts = {})
        type = find_type(name)
        return false unless type
        case type
        when 'radius' then add_radius_server(name, server, opts)
        when 'tacacs+' then add_tacacs_server(name, server, opts)
        else return false
        end
      end

      ##
      # add_radius_server adds a new radius server to the nodes current
      # configuration.  If the server already exists in the specified group
      # name this method will still return successfully.
      #
      # @since eos_version 4.13.7M
      #
      # commmands
      #   aaa group server radius <name>
      #   server <server> [acct-port <acct_port>] [auth-port <auth_port>]
      #                   [vrf <vrf>]
      #
      # @param name [String] The name of the aaa group server to add the new
      #   server configuration to.
      #
      # @param server [String] The IP address or host name of the server to
      #   add to the configuration.
      #
      # @param opts [Hash] Optional configuration parameters.
      #
      # @return [Boolean] Returns true if the commands complete successfully.
      def add_radius_server(name, server, opts = {})
        # order of command options matter here!
        server = "server #{server} "
        server << "auth-port #{opts[:auth_port]} " if opts[:auth_port]
        server << "acct-port #{opts[:acct_port]} " if opts[:acct_port]
        server << "vrf #{opts[:vrf]}" if opts[:vrf]
        configure ["aaa group server radius #{name}", server, 'exit']
      end

      ##
      # add_tacacs_server adds a new tacacs server to the nodes current
      # configuration. If the server already exists in the specified group
      # name this method will still return successfully.
      #
      # @since eos_version 4.13.7M
      #
      # commmands
      #   aaa group server tacacs+ <name>
      #   server <server> [acct-port <acct_port>] [auth-port <auth_port>]
      #                   [vrf <vrf>]
      #
      # @param name [String] The name of the aaa group server to add the new
      #   server configuration to.
      #
      # @param server [String] The IP address or host name of the server to
      #   add to the configuration.
      #
      # @param opts [Hash] Optional configuration parameters.
      #
      # @return [Boolean] Returns true if the commands complete successfully.
      def add_tacacs_server(name, server, opts = {})
        # order of command options matter here!
        server = "server #{server} "
        server << "vrf #{opts[:vrf]} "    if opts[:vrf]
        server << "port #{opts[:port]} "  if opts[:port]
        configure ["aaa group server tacacs+ #{name}", server, 'exit']
      end

      ##
      # remove_server deletes an existing server from the specified aaa server
      # group. If the specified server is not configured in the specified
      # server group, this method will still return true.
      #
      # eos_version 4.13.7M
      #
      # ===Commands
      #   aaa group server [radius | tacacs+] <name>
      #   no server <server>
      #
      # @param name [String] The name of the aaa group server to remove.
      #
      # @param server [String] The IP address or host name of the server.
      #
      # @param opts [Hash] Optional configuration parameters.
      #
      # @return [Boolean] returns true if the commands complete successfully.
      def remove_server(name, server, opts = {})
        type = find_type(name)
        return false unless type
        server = "no server #{server} "
        server << "vrf #{opts[:vrf]}" if opts[:vrf]
        configure ["aaa group server #{type} #{name}", server, 'exit']
      end
    end
  end
end


text:
/*
 * Decompiled with CFR 0_110.
 *
 * Could not load the following classes:
 *  net.minecraft.block.Block
 *  net.minecraft.block.Block$SoundType
 *  net.minecraft.block.material.Material
 */
package com.hiagg.blocks;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;

import com.hiagg.creativetabs.ModTabs;

public class DEStarBlock extends Block {
    public DEStarBlock() {
        super(Material.rock);
        setBlockName("DEStarBlock");
        setCreativeTab(ModTabs.tabBlocks);
        setBlockTextureName("hiaggium:DEStarBlock");
        setHardness(50.0f);
        setResistance(500.0f);
        setHarvestLevel("pickaxe", 4);
        setStepSound(soundTypeStone);
    }

    public static void mainRegistry() {
    }
}


text:
import logging
from .base import BaseScript

log = logging.getLogger(__name__)

def suggest_job():
    log.warning('login_suggest.py suggest_job')

class LoginSuggest(BaseScript):
    name = "Suggest Login & Password"
    description = "Fetches logins and passwords from DB and tries to login. If it was successful, stores result in DB"

    def work(self):
        log.warning("def work in LoginSuggest in login_suggest.py")


text:
cask 'cornerstone' do
  version '4.1'
  sha256 '0cc7f2cf400aabfd2ab38d230387e836d4071cf9f3fce8a9fd46f1c539a1fc7b'

  url "https://www.zennaware.com/cornerstone/downloads/Cornerstone-#{version}.zip"
  appcast "https://www.zennaware.com/cornerstone/appcast/feed#{version.major}.php"
  name 'Cornerstone'
  homepage 'https://www.zennaware.com/cornerstone/'

  app 'Cornerstone.app'
end


text:
package org.mbari.vars.ui.javafx.cbpanel;

import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import org.mbari.vars.core.EventBus;
import org.mbari.vars.services.ConceptService;
import org.mbari.vars.ui.UIToolBox;
import org.mbari.vars.ui.util.JFXUtilities;

import java.util.ResourceBundle;
import java.util.prefs.Preferences;

/**
 * Highlights the last button pressed
 * @author Brian Schlining
 * @since 2018-12-12T11:17:00
 */
public class ConceptButtonPaneWithHighlightController extends ConceptButtonPaneController {

    private Button lastButtonPressed;
    private static final String STYLE_CLASS = "cbpanel-label-overview";

    private EventHandler<MouseEvent> eventHandler = event -> {
        if (lastButtonPressed != null) {
            JFXUtilities.removeAttention(lastButtonPressed);
        }

        lastButtonPressed = (Button) event.getSource();
        if (lastButtonPressed != null) {
            JFXUtilities.attractAttention(lastButtonPressed);
        }
    };

    public ConceptButtonPaneWithHighlightController(String name,
                                                    UIToolBox toolBox,
                                                    Preferences panePreferences) {
        super(toolBox, panePreferences);
        Label label = new Label(name);
        label.setUnderline(true);
        label.getStyleClass().add(STYLE_CLASS);
        getPane().getChildren().add(0, label);
    }

    /**
     * Change the layout to a VBox. Disable drag and drop
     * @return
     */
    @Override
    public Pane getPane() {
        if (pane == null) {
            pane = new VBox();
            pane.setUserData(this);
            pane.getChildren().addListener((ListChangeListener<Node>) c -> {

                while (c.next()) {
                    c.getAddedSubList()
                            .stream()
                            .filter(node -> node instanceof Button)
                            .map(node -> (Button) node)
                            .forEach(button -> {
                                button.addEventHandler(MouseEvent.MOUSE_CLICKED,
                                        eventHandler);
                            });

                    c.getRemoved()
                            .forEach(node -> node.removeEventHandler(MouseEvent.MOUSE_CLICKED,
                                    eventHandler));
                }
            });
            loadButtonsFromPreferences();
        }
        return pane;
    }
}


text:
'use strict';

moduloTipoempleado.controller('TipoempleadoRemoveController', ['$scope', '$routeParams', 'serverService',
    function ($scope, $routeParams, serverService) {
        $scope.result = "";
        $scope.back = function () {
            window.history.back();
        };
        $scope.ob = 'tipoempleado';
        $scope.id = $routeParams.id;
        $scope.title = "Borrado de un tipo de empleado";
        $scope.icon = "fa-user-secret";
        serverService.getDataFromPromise(serverService.promise_getOne($scope.ob, $scope.id)).then(function (data) {
            $scope.bean = data.message;
        });

        $scope.remove = function () {
            serverService.getDataFromPromise(serverService.promise_removeOne($scope.ob, $scope.id)).then(function (data) {
                $scope.result = data;
            });
        }
        ;
    }]);