text:
package walk

import (
	"fmt"
	"io"
	"strings"
	"sync"
	"testing"

	"github.com/ncw/rclone/fs"
	"github.com/ncw/rclone/fs/filter"
	"github.com/ncw/rclone/fstest/mockdir"
	"github.com/ncw/rclone/fstest/mockfs"
	"github.com/ncw/rclone/fstest/mockobject"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type (
	listResult struct {
		entries fs.DirEntries
		err     error
	}

	listResults map[string]listResult

	errorMap map[string]error

	listDirs struct {
		mu          sync.Mutex
		t           *testing.T
		fs          fs.Fs
		includeAll  bool
		results     listResults
		walkResults listResults
		walkErrors  errorMap
		finalError  error
		checkMaps   bool
		maxLevel    int
	}
)

func newListDirs(t *testing.T, f fs.Fs, includeAll bool, results listResults, walkErrors errorMap, finalError error) *listDirs {
	return &listDirs{
		t:           t,
		fs:          f,
		includeAll:  includeAll,
		results:     results,
		walkErrors:  walkErrors,
		walkResults: listResults{},
		finalError:  finalError,
		checkMaps:   true,
		maxLevel:    -1,
	}
}

// NoCheckMaps marks the maps as to be ignored at the end
func (ls *listDirs) NoCheckMaps() *listDirs {
	ls.checkMaps = false
	return ls
}

// SetLevel(1) turns off recursion
func (ls *listDirs) SetLevel(maxLevel int) *listDirs {
	ls.maxLevel = maxLevel
	return ls
}

// ListDir returns the expected listing for the directory
func (ls *listDirs) ListDir(f fs.Fs, includeAll bool, dir string) (entries fs.DirEntries, err error) {
	ls.mu.Lock()
	defer ls.mu.Unlock()
	assert.Equal(ls.t, ls.fs, f)
	assert.Equal(ls.t, ls.includeAll, includeAll)

	// Fetch results for this path
	result, ok := ls.results[dir]
	if !ok {
		ls.t.Errorf("Unexpected list of %q", dir)
		return nil, errors.New("unexpected list")
	}
	delete(ls.results, dir)

	// Put expected results for call of WalkFn
	ls.walkResults[dir] = result

	return result.entries, result.err
}

// ListR returns the expected listing for the directory using ListR
func (ls *listDirs) ListR(dir string, callback fs.ListRCallback) (err error) {
	ls.mu.Lock()
	defer ls.mu.Unlock()

	var errorReturn error
	for dirPath, result := range ls.results {
		// Put expected results for call of WalkFn
		// Note that we don't call the function at all if we got an error
		if result.err != nil {
			errorReturn = result.err
		}
		if errorReturn == nil {
			err = callback(result.entries)
			require.NoError(ls.t, err)
			ls.walkResults[dirPath] = result
		}
	}
	ls.results = listResults{}
	return errorReturn
}

// IsFinished checks everything expected was used up
func (ls *listDirs) IsFinished() {
	if ls.checkMaps {
		assert.Equal(ls.t, errorMap{}, ls.walkErrors)
		assert.Equal(ls.t, listResults{}, ls.results)
		assert.Equal(ls.t, listResults{}, ls.walkResults)
	}
}

// WalkFn is called by the walk to test the expectations
func (ls *listDirs) WalkFn(dir string, entries fs.DirEntries, err error) error {
	ls.mu.Lock()
	defer ls.mu.Unlock()
	// ls.t.Logf("WalkFn(%q, %v, %q)", dir, entries, err)

	// Fetch expected entries and err
	result, ok := ls.walkResults[dir]
	if !ok {
		ls.t.Errorf("Unexpected walk of %q (result not found)", dir)
		return errors.New("result not found")
	}
	delete(ls.walkResults, dir)

	// Check arguments are as expected
	assert.Equal(ls.t, result.entries, entries)
	assert.Equal(ls.t, result.err, err)

	// Fetch return value
	returnErr, ok := ls.walkErrors[dir]
	if !ok {
		ls.t.Errorf("Unexpected walk of %q (error not found)", dir)
		return errors.New("error not found")
	}
	delete(ls.walkErrors, dir)

	return returnErr
}

// Walk does the walk and tests the expectations
func (ls *listDirs) Walk() {
	err := walk(nil, "", ls.includeAll, ls.maxLevel, ls.WalkFn, ls.ListDir)
	assert.Equal(ls.t, ls.finalError, err)
	ls.IsFinished()
}

// WalkR does the walkR and tests the expectations
func (ls *listDirs) WalkR() {
	err := walkR(nil, "", ls.includeAll, ls.maxLevel, ls.WalkFn, ls.ListR)
	assert.Equal(ls.t, ls.finalError, err)
	if ls.finalError == nil {
		ls.IsFinished()
	}
}

func testWalkEmpty(t *testing.T) *listDirs {
	return newListDirs(t, nil, false,
		listResults{
			"": {entries: fs.DirEntries{}, err: nil},
		},
		errorMap{
			"": nil,
		},
		nil,
	)
}
func TestWalkEmpty(t *testing.T)  { testWalkEmpty(t).Walk() }
func TestWalkREmpty(t *testing.T) { testWalkEmpty(t).WalkR() }

func testWalkEmptySkip(t *testing.T) *listDirs {
	return newListDirs(t, nil, true,
		listResults{
			"": {entries: fs.DirEntries{}, err: nil},
		},
		errorMap{
			"": ErrorSkipDir,
		},
		nil,
	)
}
func TestWalkEmptySkip(t *testing.T)  { testWalkEmptySkip(t).Walk() }
func TestWalkREmptySkip(t *testing.T) { testWalkEmptySkip(t).WalkR() }

func testWalkNotFound(t *testing.T) *listDirs {
	return newListDirs(t, nil, true,
		listResults{
			"": {err: fs.ErrorDirNotFound},
		},
		errorMap{
			"": fs.ErrorDirNotFound,
		},
		fs.ErrorDirNotFound,
	)
}
func TestWalkNotFound(t *testing.T)  { testWalkNotFound(t).Walk() }
func TestWalkRNotFound(t *testing.T) { testWalkNotFound(t).WalkR() }

func TestWalkNotFoundMaskError(t *testing.T) {
	// this doesn't work for WalkR
	newListDirs(t, nil, true,
		listResults{
			"": {err: fs.ErrorDirNotFound},
		},
		errorMap{
			"": nil,
		},
		nil,
	).Walk()
}

func TestWalkNotFoundSkipkError(t *testing.T) {
	// this doesn't work for WalkR
	newListDirs(t, nil, true,
		listResults{
			"": {err: fs.ErrorDirNotFound},
		},
		errorMap{
			"": ErrorSkipDir,
		},
		nil,
	).Walk()
}

func testWalkLevels(t *testing.T, maxLevel int) *listDirs {
	da := mockdir.New("a")
	oA := mockobject.Object("A")
	db := mockdir.New("a/b")
	oB := mockobject.Object("a/B")
	dc := mockdir.New("a/b/c")
	oC := mockobject.Object("a/b/C")
	dd := mockdir.New("a/b/c/d")
	oD := mockobject.Object("a/b/c/D")
	return newListDirs(t, nil, false,
		listResults{
			"":        {entries: fs.DirEntries{oA, da}, err: nil},
			"a":       {entries: fs.DirEntries{oB, db}, err: nil},
			"a/b":     {entries: fs.DirEntries{oC, dc}, err: nil},
			"a/b/c":   {entries: fs.DirEntries{oD, dd}, err: nil},
			"a/b/c/d": {entries: fs.DirEntries{}, err: nil},
		},
		errorMap{
			"":        nil,
			"a":       nil,
			"a/b":     nil,
			"a/b/c":   nil,
			"a/b/c/d": nil,
		},
		nil,
	).SetLevel(maxLevel)
}
func TestWalkLevels(t *testing.T)               { testWalkLevels(t, -1).Walk() }
func TestWalkRLevels(t *testing.T)              { testWalkLevels(t, -1).WalkR() }
func TestWalkLevelsNoRecursive10(t *testing.T)  { testWalkLevels(t, 10).Walk() }
func TestWalkRLevelsNoRecursive10(t *testing.T) { testWalkLevels(t, 10).WalkR() }

func TestWalkNDirTree(t *testing.T) {
	ls := testWalkLevels(t, -1)
	entries, err := walkNDirTree(nil, "", ls.includeAll, ls.maxLevel, ls.ListDir)
	require.NoError(t, err)
	assert.Equal(t, `/
  A
  a/
a/
  B
  b/
a/b/
  C
  c/
a/b/c/
  D
  d/
a/b/c/d/
`, entries.String())
}

func testWalkLevelsNoRecursive(t *testing.T) *listDirs {
	da := mockdir.New("a")
	oA := mockobject.Object("A")
	return newListDirs(t, nil, false,
		listResults{
			"": {entries: fs.DirEntries{oA, da}, err: nil},
		},
		errorMap{
			"": nil,
		},
		nil,
	).SetLevel(1)
}
func TestWalkLevelsNoRecursive(t *testing.T)  { testWalkLevelsNoRecursive(t).Walk() }
func TestWalkRLevelsNoRecursive(t *testing.T) { testWalkLevelsNoRecursive(t).WalkR() }

func testWalkLevels2(t *testing.T) *listDirs {
	da := mockdir.New("a")
	oA := mockobject.Object("A")
	db := mockdir.New("a/b")
	oB := mockobject.Object("a/B")
	return newListDirs(t, nil, false,
		listResults{
			"":  {entries: fs.DirEntries{oA, da}, err: nil},
			"a": {entries: fs.DirEntries{oB, db}, err: nil},
		},
		errorMap{
			"":  nil,
			"a": nil,
		},
		nil,
	).SetLevel(2)
}
func TestWalkLevels2(t *testing.T)  { testWalkLevels2(t).Walk() }
func TestWalkRLevels2(t *testing.T) { testWalkLevels2(t).WalkR() }

func testWalkSkip(t *testing.T) *listDirs {
	da := mockdir.New("a")
	db := mockdir.New("a/b")
	dc := mockdir.New("a/b/c")
	return newListDirs(t, nil, false,
		listResults{
			"":    {entries: fs.DirEntries{da}, err: nil},
			"a":   {entries: fs.DirEntries{db}, err: nil},
			"a/b": {entries: fs.DirEntries{dc}, err: nil},
		},
		errorMap{
			"":    nil,
			"a":   nil,
			"a/b": ErrorSkipDir,
		},
		nil,
	)
}
func TestWalkSkip(t *testing.T)  { testWalkSkip(t).Walk() }
func TestWalkRSkip(t *testing.T) { testWalkSkip(t).WalkR() }

func testWalkErrors(t *testing.T) *listDirs {
	lr := listResults{}
	em := errorMap{}
	de := make(fs.DirEntries, 10)
	for i := range de {
		path := string('0' + i)
		de[i] = mockdir.New(path)
		lr[path] = listResult{entries: nil, err: fs.ErrorDirNotFound}
		em[path] = fs.ErrorDirNotFound
	}
	lr[""] = listResult{entries: de, err: nil}
	em[""] = nil
	return newListDirs(t, nil, true,
		lr,
		em,
		fs.ErrorDirNotFound,
	).NoCheckMaps()
}
func TestWalkErrors(t *testing.T)  { testWalkErrors(t).Walk() }
func TestWalkRErrors(t *testing.T) { testWalkErrors(t).WalkR() }

var errorBoom = errors.New("boom")

func makeTree(level int, terminalErrors bool) (listResults, errorMap) {
	lr := listResults{}
	em := errorMap{}
	var fill func(path string, level int)
	fill = func(path string, level int) {
		de := fs.DirEntries{}
		if level > 0 {
			for _, a := range "0123456789" {
				subPath := string(a)
				if path != "" {
					subPath = path + "/" + subPath
				}
				de = append(de, mockdir.New(subPath))
				fill(subPath, level-1)
			}
		}
		lr[path] = listResult{entries: de, err: nil}
		em[path] = nil
		if level == 0 && terminalErrors {
			em[path] = errorBoom
		}
	}
	fill("", level)
	return lr, em
}

func testWalkMulti(t *testing.T) *listDirs {
	lr, em := makeTree(3, false)
	return newListDirs(t, nil, true,
		lr,
		em,
		nil,
	)
}
func TestWalkMulti(t *testing.T)  { testWalkMulti(t).Walk() }
func TestWalkRMulti(t *testing.T) { testWalkMulti(t).WalkR() }

func testWalkMultiErrors(t *testing.T) *listDirs {
	lr, em := makeTree(3, true)
	return newListDirs(t, nil, true,
		lr,
		em,
		errorBoom,
	).NoCheckMaps()
}
func TestWalkMultiErrors(t *testing.T)  { testWalkMultiErrors(t).Walk() }
func TestWalkRMultiErrors(t *testing.T) { testWalkMultiErrors(t).Walk() }

// a very simple listRcallback function
func makeListRCallback(entries fs.DirEntries, err error) fs.ListRFn {
	return func(dir string, callback fs.ListRCallback) error {
		if err == nil {
			err = callback(entries)
		}
		return err
	}
}

func TestWalkRDirTree(t *testing.T) {
	for _, test := range []struct {
		entries fs.DirEntries
		want    string
		err     error
		root    string
		level   int
	}{
		{fs.DirEntries{}, "/\n", nil, "", -1},
		{fs.DirEntries{mockobject.Object("a")}, `/
  a
`, nil, "", -1},
		{fs.DirEntries{mockobject.Object("a/b")}, `/
  a/
a/
  b
`, nil, "", -1},
		{fs.DirEntries{mockobject.Object("a/b/c/d")}, `/
  a/
a/
  b/
a/b/
  c/
a/b/c/
  d
`, nil, "", -1},
		{fs.DirEntries{mockobject.Object("a")}, "", errorBoom, "", -1},
		{fs.DirEntries{
			mockobject.Object("0/1/2/3"),
			mockobject.Object("4/5/6/7"),
			mockobject.Object("8/9/a/b"),
			mockobject.Object("c/d/e/f"),
			mockobject.Object("g/h/i/j"),
			mockobject.Object("k/l/m/n"),
			mockobject.Object("o/p/q/r"),
			mockobject.Object("s/t/u/v"),
			mockobject.Object("w/x/y/z"),
		}, `/
  0/
  4/
  8/
  c/
  g/
  k/
  o/
  s/
  w/
0/
  1/
0/1/
  2/
0/1/2/
  3
4/
  5/
4/5/
  6/
4/5/6/
  7
8/
  9/
8/9/
  a/
8/9/a/
  b
c/
  d/
c/d/
  e/
c/d/e/
  f
g/
  h/
g/h/
  i/
g/h/i/
  j
k/
  l/
k/l/
  m/
k/l/m/
  n
o/
  p/
o/p/
  q/
o/p/q/
  r
s/
  t/
s/t/
  u/
s/t/u/
  v
w/
  x/
w/x/
  y/
w/x/y/
  z
`, nil, "", -1},
		{fs.DirEntries{
			mockobject.Object("a/b/c/d/e/f1"),
			mockobject.Object("a/b/c/d/e/f2"),
			mockobject.Object("a/b/c/d/e/f3"),
		}, `a/b/c/
  d/
a/b/c/d/
  e/
a/b/c/d/e/
  f1
  f2
  f3
`, nil, "a/b/c", -1},
		{fs.DirEntries{
			mockobject.Object("A"),
			mockobject.Object("a/B"),
			mockobject.Object("a/b/C"),
			mockobject.Object("a/b/c/D"),
			mockobject.Object("a/b/c/d/E"),
		}, `/
  A
  a/
a/
  B
  b/
`, nil, "", 2},
		{fs.DirEntries{
			mockobject.Object("a/b/c"),
			mockobject.Object("a/b/c/d/e"),
		}, `/
  a/
a/
  b/
`, nil, "", 2},
	} {
		r, err := walkRDirTree(nil, test.root, true, test.level, makeListRCallback(test.entries, test.err))
		assert.Equal(t, test.err, err, fmt.Sprintf("%+v", test))
		assert.Equal(t, test.want, r.String(), fmt.Sprintf("%+v", test))
	}
}

func TestWalkRDirTreeExclude(t *testing.T) {
	for _, test := range []struct {
		entries     fs.DirEntries
		want        string
		err         error
		root        string
		level       int
		excludeFile string
		includeAll  bool
	}{
		{fs.DirEntries{mockobject.Object("a"), mockobject.Object("ignore")}, "", nil, "", -1, "ignore", false},
		{fs.DirEntries{mockobject.Object("a")}, `/
  a
`, nil, "", -1, "ignore", false},
		{fs.DirEntries{
			mockobject.Object("a"),
			mockobject.Object("b/b"),
			mockobject.Object("b/.ignore"),
		}, `/
  a
`, nil, "", -1, ".ignore", false},
		{fs.DirEntries{
			mockobject.Object("a"),
			mockobject.Object("b/.ignore"),
			mockobject.Object("b/b"),
		}, `/
  a
  b/
b/
  .ignore
  b
`, nil, "", -1, ".ignore", true},
		{fs.DirEntries{
			mockobject.Object("a"),
			mockobject.Object("b/b"),
			mockobject.Object("b/c/d/e"),
			mockobject.Object("b/c/ign"),
			mockobject.Object("b/c/x"),
		}, `/
  a
  b/
b/
  b
`, nil, "", -1, "ign", false},
		{fs.DirEntries{
			mockobject.Object("a"),
			mockobject.Object("b/b"),
			mockobject.Object("b/c/d/e"),
			mockobject.Object("b/c/ign"),
			mockobject.Object("b/c/x"),
		}, `/
  a
  b/
b/
  b
  c/
b/c/
  d/
  ign
  x
b/c/d/
  e
`, nil, "", -1, "ign", true},
	} {
		filter.Active.Opt.ExcludeFile = test.excludeFile
		r, err := walkRDirTree(nil, test.root, test.includeAll, test.level, makeListRCallback(test.entries, test.err))
		assert.Equal(t, test.err, err, fmt.Sprintf("%+v", test))
		assert.Equal(t, test.want, r.String(), fmt.Sprintf("%+v", test))
	}
	// Set to default value, to avoid side effects
	filter.Active.Opt.ExcludeFile = ""
}

func TestListType(t *testing.T) {
	assert.Equal(t, true, ListObjects.Objects())
	assert.Equal(t, false, ListObjects.Dirs())
	assert.Equal(t, false, ListDirs.Objects())
	assert.Equal(t, true, ListDirs.Dirs())
	assert.Equal(t, true, ListAll.Objects())
	assert.Equal(t, true, ListAll.Dirs())

	var (
		a           = mockobject.Object("a")
		b           = mockobject.Object("b")
		dir         = mockdir.New("dir")
		adir        = mockobject.Object("dir/a")
		dir2        = mockdir.New("dir2")
		origEntries = fs.DirEntries{
			a, b, dir, adir, dir2,
		}
		dirEntries = fs.DirEntries{
			dir, dir2,
		}
		objEntries = fs.DirEntries{
			a, b, adir,
		}
	)
	copyOrigEntries := func() (out fs.DirEntries) {
		out = make(fs.DirEntries, len(origEntries))
		copy(out, origEntries)
		return out
	}

	got := copyOrigEntries()
	ListAll.Filter(&got)
	assert.Equal(t, origEntries, got)

	got = copyOrigEntries()
	ListObjects.Filter(&got)
	assert.Equal(t, objEntries, got)

	got = copyOrigEntries()
	ListDirs.Filter(&got)
	assert.Equal(t, dirEntries, got)
}

func TestListR(t *testing.T) {
	objects := fs.DirEntries{
		mockobject.Object("a"),
		mockobject.Object("b"),
		mockdir.New("dir"),
		mockobject.Object("dir/a"),
		mockobject.Object("dir/b"),
		mockobject.Object("dir/c"),
	}
	f := mockfs.NewFs("mock", "/")
	var got []string
	clearCallback := func() {
		got = nil
	}
	callback := func(entries fs.DirEntries) error {
		for _, entry := range entries {
			got = append(got, entry.Remote())
		}
		return nil
	}
	doListR := func(dir string, callback fs.ListRCallback) error {
		var os fs.DirEntries
		for _, o := range objects {
			if dir == "" || strings.HasPrefix(o.Remote(), dir+"/") {
				os = append(os, o)
			}
		}
		return callback(os)
	}

	// Setup filter
	oldFilter := filter.Active
	defer func() {
		filter.Active = oldFilter
	}()

	var err error
	filter.Active, err = filter.NewFilter(nil)
	require.NoError(t, err)
	require.NoError(t, filter.Active.AddRule("+ b"))
	require.NoError(t, filter.Active.AddRule("- *"))

	// Base case
	clearCallback()
	err = listR(f, "", true, ListAll, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"a", "b", "dir", "dir/a", "dir/b", "dir/c"}, got)

	// Base case - with Objects
	clearCallback()
	err = listR(f, "", true, ListObjects, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"a", "b", "dir/a", "dir/b", "dir/c"}, got)

	// Base case - with Dirs
	clearCallback()
	err = listR(f, "", true, ListDirs, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"dir"}, got)

	// With filter
	clearCallback()
	err = listR(f, "", false, ListAll, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"b", "dir", "dir/b"}, got)

	// With filter - with Objects
	clearCallback()
	err = listR(f, "", false, ListObjects, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"b", "dir/b"}, got)

	// With filter - with Dir
	clearCallback()
	err = listR(f, "", false, ListDirs, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"dir"}, got)

	// With filter and subdir
	clearCallback()
	err = listR(f, "dir", false, ListAll, callback, doListR, false)
	require.NoError(t, err)
	require.Equal(t, []string{"dir/b"}, got)

	// Now bucket based
	objects = fs.DirEntries{
		mockobject.Object("a"),
		mockobject.Object("b"),
		mockobject.Object("dir/a"),
		mockobject.Object("dir/b"),
		mockobject.Object("dir/subdir/c"),
		mockdir.New("dir/subdir"),
	}

	// Base case
	clearCallback()
	err = listR(f, "", true, ListAll, callback, doListR, true)
	require.NoError(t, err)
	require.Equal(t, []string{"a", "b", "dir/a", "dir/b", "dir/subdir/c", "dir/subdir", "dir"}, got)

	// With filter
	clearCallback()
	err = listR(f, "", false, ListAll, callback, doListR, true)
	require.NoError(t, err)
	require.Equal(t, []string{"b", "dir/b", "dir/subdir", "dir"}, got)

	// With filter and subdir
	clearCallback()
	err = listR(f, "dir", false, ListAll, callback, doListR, true)
	require.NoError(t, err)
	require.Equal(t, []string{"dir/b", "dir/subdir"}, got)

	// With filter and subdir - with Objects
	clearCallback()
	err = listR(f, "dir", false, ListObjects, callback, doListR, true)
	require.NoError(t, err)
	require.Equal(t, []string{"dir/b"}, got)

	// With filter and subdir - with Dirs
	clearCallback()
	err = listR(f, "dir", false, ListDirs, callback, doListR, true)
	require.NoError(t, err)
	require.Equal(t, []string{"dir/subdir"}, got)
}

func TestDirMapAdd(t *testing.T) {
	type add struct {
		dir  string
		sent bool
	}
	for i, test := range []struct {
		root string
		in   []add
		want map[string]bool
	}{
		{
			root: "",
			in: []add{
				{"", true},
			},
			want: map[string]bool{},
		},
		{
			root: "",
			in: []add{
				{"a/b/c", true},
			},
			want: map[string]bool{
				"a/b/c": true,
				"a/b":   false,
				"a":     false,
			},
		},
		{
			root: "",
			in: []add{
				{"a/b/c", true},
				{"a/b", true},
			},
			want: map[string]bool{
				"a/b/c": true,
				"a/b":   true,
				"a":     false,
			},
		},
		{
			root: "",
			in: []add{
				{"a/b", true},
				{"a/b/c", false},
			},
			want: map[string]bool{
				"a/b/c": false,
				"a/b":   true,
				"a":     false,
			},
		},
		{
			root: "root",
			in: []add{
				{"root/a/b", true},
				{"root/a/b/c", false},
			},
			want: map[string]bool{
				"root/a/b/c": false,
				"root/a/b":   true,
				"root/a":     false,
			},
		},
	} {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			dm := newDirMap(test.root)
			for _, item := range test.in {
				dm.add(item.dir, item.sent)
			}
			assert.Equal(t, test.want, dm.m)
		})
	}
}

func TestDirMapAddEntries(t *testing.T) {
	dm := newDirMap("")
	entries := fs.DirEntries{
		mockobject.Object("dir/a"),
		mockobject.Object("dir/b"),
		mockdir.New("dir"),
		mockobject.Object("dir2/a"),
		mockobject.Object("dir2/b"),
	}
	require.NoError(t, dm.addEntries(entries))
	assert.Equal(t, map[string]bool{"dir": true, "dir2": false}, dm.m)
}

func TestDirMapSendEntries(t *testing.T) {
	var got []string
	clearCallback := func() {
		got = nil
	}
	callback := func(entries fs.DirEntries) error {
		for _, entry := range entries {
			got = append(got, entry.Remote())
		}
		return nil
	}

	// general test
	dm := newDirMap("")
	entries := fs.DirEntries{
		mockobject.Object("dir/a"),
		mockobject.Object("dir/b"),
		mockdir.New("dir"),
		mockobject.Object("dir2/a"),
		mockobject.Object("dir2/b"),
		mockobject.Object("dir1/a"),
		mockobject.Object("dir3/b"),
	}
	require.NoError(t, dm.addEntries(entries))
	clearCallback()
	err := dm.sendEntries(callback)
	require.NoError(t, err)
	assert.Equal(t, []string{
		"dir1",
		"dir2",
		"dir3",
	}, got)

	// return error from callback
	callback2 := func(entries fs.DirEntries) error {
		return io.EOF
	}
	err = dm.sendEntries(callback2)
	require.Equal(t, io.EOF, err)

	// empty
	dm = newDirMap("")
	clearCallback()
	err = dm.sendEntries(callback)
	require.NoError(t, err)
	assert.Equal(t, []string(nil), got)
}


text:
package edu.columbia.slime.service;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Queue;
import java.util.LinkedList;

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

import edu.columbia.slime.Slime;
import edu.columbia.slime.proto.*;
import edu.columbia.slime.conf.ServiceConfigParser;
import edu.columbia.slime.conf.DefaultServiceConfigParser;

public abstract class Service implements Closeable {
	public static final Log LOG = LogFactory.getLog(Slime.class);

	ServiceConfigParser parser = null;

	public void register(Event e) {
		Slime.getInstance().registerEvent(e, this);
	}

	public void unregister(Event e) {
		Slime.getInstance().unregisterEvent(e);
	}

	public void cancel(Event e) {
		Slime.getInstance().cancelEvent(e);
	}

	public abstract String getName();

	public abstract void init() throws IOException;

	public abstract void dispatch(Event e) throws IOException;

	/* inherited from Closeable */
	public abstract void close() throws IOException;

	public ServiceConfigParser getConfigParser() {
		if (parser == null)
			parser = new DefaultServiceConfigParser();
		return parser;
	}

	@SuppressWarnings("unchecked")
	public Map<String, String> getDefaultConfig() {
		if (parser instanceof Map)
			return (Map<String, String>) parser;
		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
title: hexo 5.4.0 released
---

## Hexo 5.4.0

### New features

- feat: handle config.root is not exist [@jiangtj] [#4616]

### Breaking change

- fix(excerpt): use span instead of anchor element for better SEO performance @stevenjoezhang] [#4627]

### Fixes

- fix(box): set property awaitWriteFinish for chokidar filewatcher [@stevenjoezhang] [#4633]
- fix(codeblock): match whitespace but not newlines [@stevenjoezhang] [#4625]
- fix(i18n): page.lang is undefined when using the key `language` in front-matter [@stevenjoezhang] [#4614]

### Misc

- github: update actions/setup-node action to v2 [@stevenjoezhang] [#4604]
- chore/ci: migrate from probot/stale to GitHub Actions [@stevenjoezhang] [#4598]

### Dependencies

- chore(deps): bump js-yaml from 3.14.1 to 4.0.0 @dependabot-preview [#4607]

[@jiangtj]: https://github.com/jiangtj
[@stevenjoezhang]: https://github.com/stevenjoezhang

[#4616]: https://github.com/hexojs/hexo/pull/4616
[#4627]: https://github.com/hexojs/hexo/pull/4627
[#4633]: https://github.com/hexojs/hexo/pull/4633
[#4625]: https://github.com/hexojs/hexo/pull/4625
[#4614]: https://github.com/hexojs/hexo/pull/4614
[#4604]: https://github.com/hexojs/hexo/pull/4604
[#4598]: https://github.com/hexojs/hexo/pull/4598


text:
package com.xem.mzbcustomerapp.entity;

import java.io.Serializable;

/**
 * Created by xuebing on 15/10/30.
 */
public class BeautiFilePictureData implements Serializable {
//    pictures:[{ id:1,key:"T区",value:"http://xx/xx.jpeg"}]

    private int id;
    private String key;
    private String value;

    public int getId() {
        return id;
    }

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

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

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


text:
/**
    @module system
    @namespace game
**/
game.module(
    'engine.system'
)
.body(function() {
'use strict';

/**
    @class System
    @extends game.Class
**/
game.System = game.Class.extend({
    /**
        Name of current scene.
        @property {String} currentSceneName
    **/
    currentSceneName: null,
    /**
        Width of the game screen.
        @property {Number} width
    **/
    width: null,
    /**
        Height of the game screen.
        @property {Number} height
    **/
    height: null,
    /**
        Current delta-time.
        @property {Number} delta
    **/
    delta: 0,
    /**
        Main game timer.
        @property {Timer} timer
    **/
    timer: null,
    /**
        Canvas element.
        @property {HTMLCanvasElement} canvas
    **/
    canvas: null,
    /**
        Id of canvas element.
        @property {String} canvasId
        @default canvas
    **/
    canvasId: 'canvas',
    /**
        Is engine paused.
        @property {Boolean} paused
    **/
    paused: false,
    /**
        Is engine in HiRes mode.
        @property {Boolean} hires
    **/
    hires: false,
    /**
        Is engine in Retina mode.
        @property {Boolean} retina
    **/
    retina: false,
    /**
        Is mobile rotate screen visible.
        @property {Boolean} rotateScreenVisible
    **/
    rotateScreenVisible: false,
    /**
        Current id of the game loop.
        @property {Number} gameLoopId
    **/
    gameLoopId: 0,
    /**
        Is WebGL enabled.
        @property {Boolean} webGL
    **/
    webGL: false,
    /**
        Original width.
        @property {Number} originalWidth
    **/
    originalWidth: null,
    /**
        Original height.
        @property {Number} originalHeight
    **/
    originalHeight: null,
    newSceneClass: null,
    running: false,

    init: function(width, height) {
        width = width || game.System.width;
        height = height || game.System.height;
        if (width === 'window') width = window.innerWidth;
        if (height === 'window') height = window.innerHeight;
        this.originalWidth = width;
        this.originalHeight = height;

        for (var i = 2; i <= game.System.hires; i *= 2) {
            if (window.innerWidth >= width * i && window.innerHeight >= height * i) {
                this.hires = true;
                game.scale = i;
            }
        }
        if (this.hires) {
            width *= game.scale;
            height *= game.scale;
        }
        if (game.System.retina && game.device.pixelRatio === 2) {
            // Check if we are already using highest textures
            if (game.scale < game.System.hires) {
                this.retina = true;
                width *= 2;
                height *= 2;
                game.scale *= 2;
            }
        }

        this.width = width;
        this.height = height;
        this.canvasId = game.System.canvasId || this.canvasId;
        this.timer = new game.Timer();

        if (!document.getElementById(this.canvasId)) {
            var canvas = document.createElement((navigator.isCocoonJS && game.System.screenCanvas) ? 'screencanvas' : 'canvas');
            canvas.id = this.canvasId;
            document.body.appendChild(canvas);
        }

        this.initRenderer(width, height);

        game.normalizeVendorAttribute(this.canvas, 'requestFullscreen');
        game.normalizeVendorAttribute(this.canvas, 'requestFullScreen');
        game.normalizeVendorAttribute(navigator, 'vibrate');

        document.body.style.margin = 0;

        if (this.retina) {
            this.canvas.style.width = width / 2 + 'px';
            this.canvas.style.height = height / 2 + 'px';
        }
        else {
            this.canvas.style.width = width + 'px';
            this.canvas.style.height = height + 'px';
        }

        window.addEventListener('devicemotion', function(event) {
            game.accelerometer = game.accel = event.accelerationIncludingGravity;
        }, false);

        game.renderer = this.renderer;

        if (!navigator.isCocoonJS) {
            var visibilityChange;
            if (typeof document.hidden !== 'undefined') {
                visibilityChange = 'visibilitychange';
            }
            else if (typeof document.mozHidden !== 'undefined') {
                visibilityChange = 'mozvisibilitychange';
            }
            else if (typeof document.msHidden !== 'undefined') {
                visibilityChange = 'msvisibilitychange';
            }
            else if (typeof document.webkitHidden !== 'undefined') {
                visibilityChange = 'webkitvisibilitychange';
            }

            document.addEventListener(visibilityChange, function() {
                if (game.System.pauseOnHide) {
                    var hidden = !!game.getVendorAttribute(document, 'hidden');
                    if (hidden) game.system.pause(true);
                    else game.system.resume(true);
                }
            }, false);

            if (game.System.bgColor && !game.System.bgColorMobile) game.System.bgColorMobile = game.System.bgColor;
            if (game.System.bgColorMobile && !game.System.bgColorRotate) game.System.bgColorRotate = game.System.bgColorMobile;

            if (game.System.bgImage && !game.System.bgImageMobile) game.System.bgImageMobile = game.System.bgImage;
            if (game.System.bgImageMobile && !game.System.bgImageRotate) game.System.bgImageRotate = game.System.bgImageMobile;

            if (!game.device.mobile) {
                if (game.System.bgColor) document.body.style.backgroundColor = game.System.bgColor;
                if (game.System.bgImage) document.body.style.backgroundImage = 'url(' + game.getMediaPath(game.System.bgImage) + ')';
            }
            if (game.System.bgPosition) document.body.style.backgroundPosition = game.System.bgPosition;

            this.initResize();
        }
        else {
            this.resizeToFill();
            this.canvas.style.cssText = 'idtkscale:' + game.System.idtkScale + ';';
        }
    },

    initRenderer: function(width, height) {
        game.PIXI.scaleModes.DEFAULT = game.PIXI.scaleModes[game.System.scaleMode.toUpperCase()] || 0;

        if (game.System.webGL) this.renderer = new game.autoDetectRenderer(width, height, {
            view: document.getElementById(this.canvasId),
            transparent: game.System.transparent,
            antialias: game.System.antialias
        });
        else this.renderer = new game.CanvasRenderer(width, height, {
            view: document.getElementById(this.canvasId),
            transparent: game.System.transparent
        });

        this.webGL = !!this.renderer.gl;
        this.canvas = this.renderer.view;
        this.stage = new game.Stage();
    },

    resizeToFill: function() {
        if (!game.System.resizeToFill || !game.device.mobile) return;
        if (this.rotateScreenVisible) return;

        if (this._resizeToFill) return;
        this._resizeToFill = true;

        var gameOrientation = this.width > this.height ? 'landscape' : 'portrait';
        var gameRatio = this.width / this.height;
        var screenOrientation = window.innerWidth > window.innerHeight ? 'landscape' : 'portrait';
        var screenRatio = window.innerWidth / window.innerHeight;

        if (screenRatio !== gameRatio && gameOrientation === screenOrientation) {
            if (gameRatio < screenRatio) {
                // Letterbox left/right
                this.width = Math.round(this.height * (window.innerWidth / window.innerHeight));
            }
            else {
                // Letterbox top/bottom
                this.height = Math.round(this.width * (window.innerHeight / window.innerWidth));
            }
            this.resize(this.width, this.height);
        }
    },

    /**
        Vibrate device.
        @method vibrate
        @param {Number} time Time to vibrate.
    **/
    vibrate: function(time) {
        if (navigator.vibrate) return navigator.vibrate(time);
        return false;
    },

    /**
        Pause game engine.
        @method pause
    **/
    pause: function(onHide) {
        if (this.paused) return;

        if (onHide) this.pausedOnHide = true;
        else this.paused = true;

        if (game.scene) game.scene.pause();
    },

    /**
        Resume paused game engine.
        @method resume
    **/
    resume: function(onHide) {
        if (onHide && this.paused) return;
        if (!onHide && !this.paused) return;

        if (onHide) this.pausedOnHide = false;
        else this.paused = false;

        game.Timer.last = Date.now();
        if (game.scene) game.scene.resume();
    },

    /**
        Change current scene.
        @method setScene
        @param {String} sceneClass
        @param {Boolean} removeAssets
    **/
    setScene: function(sceneClass, removeAssets) {
        this.currentSceneName = sceneClass;
        sceneClass = game['Scene' + sceneClass];
        if (this.running) {
            this.newSceneClass = sceneClass;
            this.removeAssets = removeAssets;
        }
        else this.setSceneNow(sceneClass, removeAssets);
    },

    setSceneNow: function(sceneClass, removeAssets) {
        if (game.scene) game.scene.exit();
        if (game.tweenEngine) game.tweenEngine.tweens.length = 0;
        if (removeAssets) game.removeAssets();
        game.scene = new (sceneClass)();
        if (game.Debug && game.Debug.enabled && !navigator.isCocoonJS && !this.debug) this.debug = new game.Debug();
        this.newSceneClass = null;
        this.startRunLoop();
    },

    startRunLoop: function() {
        if (this.gameLoopId) this.stopRunLoop();
        this.gameLoopId = game.setGameLoop(this.run.bind(this), this.canvas);
        this.running = true;
    },

    stopRunLoop: function() {
        game.clearGameLoop(this.gameLoopId);
        this.running = false;
    },

    run: function() {
        if (this.paused || this.pausedOnHide) return;

        game.Timer.update();
        this.delta = this.timer.delta() / 1000;

        if (this.debug) this.debug.reset();

        game.scene.run();

        if (this.debug) this.debug.update();
        if (this.newSceneClass) this.setSceneNow(this.newSceneClass, this.removeAssets);
    },

    resize: function(width, height) {
        this.width = this.canvas.width = width;
        this.height = this.canvas.height = height;
        this.canvas.style.width = width + 'px';
        this.canvas.style.height = height + 'px';
        this.renderer.resize(this.width, this.height);
    },

    initResize: function() {
        this.ratio = this.width > this.height ? this.width / this.height : this.height / this.width;

        if (game.System.center) this.canvas.style.margin = 'auto';

        if (game.device.mobile) {
            // Mobile position
            if (!game.System.center) {
                this.canvas.style.position = 'absolute';
                this.canvas.style.left = game.System.left + 'px';
                this.canvas.style.top = game.System.top + 'px';
            }

            document.addEventListener('touchstart', function(e) {
                e.preventDefault();
            }, false);

            if (game.System.rotateScreen) {
                var div = document.createElement('div');
                div.innerHTML = game.System.rotateImg ? '' : game.System.rotateMsg;
                div.style.position = 'absolute';
                div.style.height = '12px';
                div.style.textAlign = 'center';
                div.style.left = 0;
                div.style.right = 0;
                div.style.top = 0;
                div.style.bottom = 0;
                div.style.margin = 'auto';
                div.style.display = 'none';
                div.id = 'panda-rotate';
                game.System.rotateDiv = div;
                document.body.appendChild(game.System.rotateDiv);

                if (game.System.rotateImg) {
                    var img = new Image();
                    var me = this;
                    img.onload = function() {
                        div.image = img;
                        div.style.height = img.height + 'px';
                        div.appendChild(img);
                        me.resizeRotateImage();
                    };
                    if (game.System.rotateImg.indexOf('data:') === 0) {
                        img.src = game.System.rotateImg;
                    }
                    else {
                        img.src = game.getMediaPath(game.System.rotateImg);
                    }
                    img.style.position = 'relative';
                    img.style.maxWidth = '100%';
                }
            }
        }
        else {
            // Desktop center
            if (game.System.center || game.System.left || game.System.top) this.canvas.style.position = 'absolute';
            if (game.System.center) {
                this.canvas.style.top = 0;
                this.canvas.style.left = 0;
                this.canvas.style.bottom = 0;
                this.canvas.style.right = 0;
            }
            else if (game.System.left || game.System.top) {
                this.canvas.style.left = game.System.left + 'px';
                this.canvas.style.top = game.System.top + 'px';
            }

            // Desktop scaling
            if (game.System.scale) {
                var minWidth = game.System.minWidth === 'auto' ? this.retina ? this.width / 4 : this.width / 2 : game.System.minWidth;
                var minHeight = game.System.minHeight === 'auto' ? this.retina ? this.height / 4 : this.height / 2 : game.System.minHeight;
                var maxWidth = game.System.maxWidth === 'auto' ? this.retina ? this.width / 2 : this.width : game.System.maxWidth;
                var maxHeight = game.System.maxHeight === 'auto' ? this.retina ? this.height / 2 : this.height : game.System.maxHeight;
                if (game.System.minWidth) this.canvas.style.minWidth = minWidth + 'px';
                if (game.System.minHeight) this.canvas.style.minHeight = minHeight + 'px';
                if (game.System.maxWidth && !game.System.scaleToFit) this.canvas.style.maxWidth = maxWidth + 'px';
                if (game.System.maxHeight && !game.System.scaleToFit) this.canvas.style.maxHeight = maxHeight + 'px';
            }
        }

        if (typeof window.onorientationchange !== 'undefined' && !game.device.android) {
            window.onorientationchange = this.onResize.bind(this);
        }
        else {
            window.onresize = this.onResize.bind(this);
        }

        this.onResize();
    },

    checkOrientation: function() {
        this.orientation = window.innerWidth < window.innerHeight ? 'portrait' : 'landscape';
        if (game.device.android2 && window.innerWidth === 320 && window.innerHeight === 251) {
            // Android 2.3 portrait fix
            this.orientation = 'portrait';
        }

        if (this.width > this.height && this.orientation !== 'landscape') this.rotateScreenVisible = true;
        else if (this.width < this.height && this.orientation !== 'portrait') this.rotateScreenVisible = true;
        else this.rotateScreenVisible = false;

        if (!game.System.rotateScreen) this.rotateScreenVisible = false;

        this.canvas.style.display = this.rotateScreenVisible ? 'none' : 'block';
        if (game.System.rotateDiv) game.System.rotateDiv.style.display = this.rotateScreenVisible ? 'block' : 'none';

        if (this.rotateScreenVisible && game.System.bgColorRotate) document.body.style.backgroundColor = game.System.bgColorRotate;
        if (!this.rotateScreenVisible && game.System.bgColorMobile) document.body.style.backgroundColor = game.System.bgColorMobile;

        if (this.rotateScreenVisible && game.System.bgImageRotate) document.body.style.backgroundImage = 'url(' + game.getMediaPath(game.System.bgImageRotate) + ')';
        if (!this.rotateScreenVisible && game.System.bgImageMobile) document.body.style.backgroundImage = 'url(' + game.getMediaPath(game.System.bgImageMobile) + ')';

        if (this.rotateScreenVisible && game.system && typeof game.system.pause === 'function') game.system.pause();
        if (!this.rotateScreenVisible && game.system && typeof game.system.resume === 'function') game.system.resume();

        if (this.rotateScreenVisible) this.resizeRotateImage();
    },

    resizeRotateImage: function() {
        if (this.rotateScreenVisible && game.System.rotateDiv.image) {
            if (window.innerHeight < game.System.rotateDiv.image.height) {
                game.System.rotateDiv.image.style.height = window.innerHeight + 'px';
                game.System.rotateDiv.image.style.width = 'auto';
                game.System.rotateDiv.style.height = window.innerHeight + 'px';
                game.System.rotateDiv.style.bottom = 'auto';
            }
        }
    },

    onResize: function() {
        // Mobile orientation
        if (game.device.mobile) this.checkOrientation();

        if (!game.System.scale) return;

        if (game.device.mobile) {
            this.ratio = this.orientation === 'landscape' ? this.width / this.height : this.height / this.width;

            this.resizeToFill();

            // Mobile resize
            var width = window.innerWidth;
            var height = window.innerHeight;

            // iOS innerHeight bug fixes
            if (game.device.iOS7 && window.innerHeight === 256) height = 320;
            if (game.device.iOS7 && window.innerHeight === 319) height = 320;
            if (game.device.iOS7 && game.device.pixelRatio === 2 && this.orientation === 'landscape') height += 2;
            if (game.device.iPad && height === 671) height = 672;

            // Landscape game
            if (this.width > this.height) {
                if (this.orientation === 'landscape' && height * this.ratio <= width) {
                    this.canvas.style.height = height + 'px';
                    this.canvas.style.width = height * this.width / this.height + 'px';
                }
                else {
                    this.canvas.style.width = width + 'px';
                    this.canvas.style.height = width * this.height / this.width + 'px';
                }
            }
            // Portrait game
            else {
                if (this.orientation === 'portrait' && width * this.ratio <= height) {
                    this.canvas.style.width = width + 'px';
                    this.canvas.style.height = width * this.height / this.width + 'px';
                }
                else {
                    this.canvas.style.height = height + 'px';
                    this.canvas.style.width = height * this.width / this.height + 'px';
                }
            }

            if (!game.device.ejecta) window.scroll(0, 1);

            if (!this.rotateScreenVisible && game.loader && !game.loader.started) game.loader.start();
        }
        else {
            // Desktop resize
            if (window.innerWidth === 0) return; // Chrome bug
            if (window.innerWidth < this.width || window.innerHeight < this.height || game.System.scaleToFit) {
                if (window.innerWidth / this.width < window.innerHeight / this.height) {
                    this.canvas.style.width = window.innerWidth + 'px';
                    this.canvas.style.height = window.innerWidth * (this.height / this.width) + 'px';
                }
                else {
                    this.canvas.style.height = window.innerHeight + 'px';
                    this.canvas.style.width = window.innerHeight * (this.width / this.height) + 'px';
                }
            }
            else {
                this.canvas.style.width = this.width + 'px';
                this.canvas.style.height = this.height + 'px';
            }
        }
    }
});

/**
    Enable/disable canvas centering.
    @attribute {Boolean} center
    @default true
**/
game.System.center = true;
/**
    Canvas position from left, when centering is disabled.
    @attribute {Number} left
    @default 0
**/
game.System.left = 0;
/**
    Canvas position from top, when centering is disabled.
    @attribute {Number} top
    @default 0
**/
game.System.top = 0;
/**
    Enable/disable canvas scaling.
    @attribute {Boolean} resize
    @default true
**/
game.System.scale = true;
/**
    Minimum width for canvas, when using scaling on desktop.
    @attribute {Number} minWidth
    @default auto
**/
game.System.minWidth = 'auto';
/**
    Minimum height for canvas, when using scaling on desktop.
    @attribute {Number} minHeight
    @default auto
**/
game.System.minHeight = 'auto';
/**
    Maximum width for canvas, when using scaling on desktop.
    @attribute {Number} maxWidth
    @default auto
**/
game.System.maxWidth = 'auto';
/**
    Maximum height for canvas, when using scaling on desktop.
    @attribute {Number} maxHeight
    @default auto
**/
game.System.maxHeight = 'auto';
/**
    Scaling method for CocoonJS.
    @attribute {ScaleToFill|ScaleAspectFit|ScaleAspectFill} idtkScale
    @default ScaleAspectFit
**/
game.System.idtkScale = 'ScaleAspectFit';
/**
    Use ScreenCanvas on CocoonJS.
    http://support.ludei.com/hc/en-us/articles/201810268-ScreenCanvas
    @attribute {Boolean} screenCanvas
    @default true
**/
game.System.screenCanvas = true;
/**
    HiRes mode.
    @attribute {Number} hires
    @default 0
**/
game.System.hires = 0;
/**
    Use Retina mode.
    @attribute {Boolean} retina
    @default false
**/
game.System.retina = false;
/**
    Pause game engine, when page is hidden.
    @attribute {Boolean} pauseOnHide
    @default true
**/
game.System.pauseOnHide = true;
/**
    Use rotate screen on mobile.
    @attribute {Boolean} rotateScreen
    @default true
**/
game.System.rotateScreen = true;
/**
    System width.
    @attribute {Number} width
    @default 1024
**/
game.System.width = 1024;
/**
    System height.
    @attribute {Number} height
    @default 768
**/
game.System.height = 768;
/**
    Body background color.
    @attribute {String} bgColor
    @default null
**/
game.System.bgColor = null;
/**
    Body background color for mobile.
    @attribute {String} bgColorMobile
    @default null
**/
game.System.bgColorMobile = null;
/**
    Body background color for mobile rotate screen.
    @attribute {String} bgColorRotate
    @default null
**/
game.System.bgColorRotate = null;
/**
    Body background image.
    @attribute {String} bgImage
    @default null
**/
game.System.bgImage = null;
/**
    Body background image for mobile.
    @attribute {String} bgImageMobile
    @default null
**/
game.System.bgImageMobile = null;
/**
    Body background image for mobile rotate screen.
    @attribute {String} bgImageRotate
    @default null
**/
game.System.bgImageRotate = null;
/**
    Body background image position.
    @attribute {String} bgPosition
    @default null
**/
game.System.bgPosition = null;
/**
    Rotate message for mobile.
    @attribute {String} rotateMsg
    @default Please rotate your device
**/
game.System.rotateMsg = 'Please rotate your device';
/**
    Rotate image for mobile.
    @attribute {URL} rotateImg
    @default null
**/
game.System.rotateImg = null;
/**
    Enable WebGL renderer.
    @attribute {Boolean} webGL
    @default false
**/
game.System.webGL = false;
/**
    Use transparent renderer.
    @attribute {Boolean} transparent
    @default false
**/
game.System.transparent = false;
/**
    Use antialias (only on WebGL).
    @attribute {Boolean} antialias
    @default false
**/
game.System.antialias = false;
/**
    Resize canvas to fill screen on mobile.
    @attribute {Boolean} resizeToFill
    @default false
**/
game.System.resizeToFill = false;
/**
    Default start scene.
    @attribute {String} startScene
    @default Main
**/
game.System.startScene = 'Main';
/**
    Scale canvas to fit window size on desktop.
    @attribute {Boolean} scaleToFit
    @default false
**/
game.System.scaleToFit = false;
/**
    Canvas id for game.
    @attribute {String} canvasId
    @default null
**/
game.System.canvasId = null;
/**
    Canvas scale mode.
    @attribute {String} scaleMode
    @default linear
**/
game.System.scaleMode = 'linear';

});


text:
title: "RDF4J 3.2.3 released"
date: 2020-07-02
layout: "single"
categories: ["news"]
---
We are pleased to announce the release of RDF4J 3.2.3.  This is a patch release fixing several issues in the Rio Turtle parser and in handling of path expressions in the SPARQL engine.

See the [release notes](/release-notes/3.2.3) for more details.

<!--more-->
### Links

- [Download RDF4J](/download/)


text:
package org.apache.olingo.odata2.core.ep.producer;

import java.util.Map;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.olingo.odata2.api.edm.Edm;
import org.apache.olingo.odata2.api.ep.EntityProviderException;
import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties;
import org.apache.olingo.odata2.core.ep.EntityProviderProducerException;
import org.apache.olingo.odata2.core.ep.aggregator.EntityInfoAggregator;
import org.apache.olingo.odata2.core.ep.util.FormatXml;

/**
 * Provider for writing a single link.
 *
 */
public class XmlLinkEntityProducer {

  private final EntityProviderWriteProperties properties;

  public XmlLinkEntityProducer(final EntityProviderWriteProperties properties) throws EntityProviderException {
    this.properties = properties == null ? EntityProviderWriteProperties.serviceRoot(null).build() : properties;
  }

  public void append(final XMLStreamWriter writer, final EntityInfoAggregator entityInfo,
      final Map<String, Object> data, final boolean isRootElement) throws EntityProviderException {
    try {
      writer.writeStartElement(FormatXml.D_URI);
      if (isRootElement) {
        writer.writeDefaultNamespace(Edm.NAMESPACE_D_2007_08);
      }
      if (properties.getServiceRoot() != null) {
        writer.writeCharacters(properties.getServiceRoot().toASCIIString());
      }
      writer.writeCharacters(AtomEntryEntityProducer.createSelfLink(entityInfo, data, null));
      writer.writeEndElement();
      writer.flush();
    } catch (final XMLStreamException e) {
      throw new EntityProviderProducerException(EntityProviderException.COMMON, e);
    }
  }
}


text:
require('babel-core/register');
require('gulp-task-loader')('gulp');


text:
/*
 * PanelCadastro.java
 *
 * Created on 31 de Maio de 2007, 16:13
 */

package br.com.codigocerto.swing.formularios;

import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;

import br.com.codigocerto.swing.ICCPanel;
import br.com.codigocerto.swing.CCPesquisaCadastro;
import br.com.codigocerto.swing.CCDataField;
import br.com.codigocerto.swing.CCTextNumerico;
import br.com.codigocerto.swing.CCModeloTabela;
import br.com.codigocerto.swing.CCTabela;
import br.com.codigocerto.swing.CCTextoFixo;

/**
 *
 * @author  lis
 */
public class PanelEntradaDados extends javax.swing.JPanel implements ICCPanel, IPanelEntradaDados {

    private boolean _alterado = false;
    private boolean _novo = false;

    /** Creates new form PanelEntradaDados */
    public PanelEntradaDados() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        barra = new br.com.codigocerto.swing.barras.BarraCadastro();
        jPanelPrincipal = new javax.swing.JPanel();
        jPanelRodape = new javax.swing.JPanel();
        jButtonCancelar = new javax.swing.JButton();
        jButtonSalvar = new javax.swing.JButton();
        jPanelMovimento = new javax.swing.JPanel();

        barra.setFloatable(false);

        jButtonCancelar.setText("Cancelar");
        jButtonCancelar.setEnabled(false);
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        jButtonSalvar.setText("Salvar");
        jButtonSalvar.setEnabled(false);
        jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelRodapeLayout = new javax.swing.GroupLayout(jPanelRodape);
        jPanelRodape.setLayout(jPanelRodapeLayout);
        jPanelRodapeLayout.setHorizontalGroup(
            jPanelRodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelRodapeLayout.createSequentialGroup()
                .addContainerGap(402, Short.MAX_VALUE)
                .addComponent(jButtonSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonCancelar))
        );
        jPanelRodapeLayout.setVerticalGroup(
            jPanelRodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelRodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButtonCancelar)
                .addComponent(jButtonSalvar))
        );

        javax.swing.GroupLayout jPanelMovimentoLayout = new javax.swing.GroupLayout(jPanelMovimento);
        jPanelMovimento.setLayout(jPanelMovimentoLayout);
        jPanelMovimentoLayout.setHorizontalGroup(
            jPanelMovimentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 590, Short.MAX_VALUE)
        );
        jPanelMovimentoLayout.setVerticalGroup(
            jPanelMovimentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 81, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanelPrincipalLayout = new javax.swing.GroupLayout(jPanelPrincipal);
        jPanelPrincipal.setLayout(jPanelPrincipalLayout);
        jPanelPrincipalLayout.setHorizontalGroup(
            jPanelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelPrincipalLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanelRodape, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jPanelMovimento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanelPrincipalLayout.setVerticalGroup(
            jPanelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelPrincipalLayout.createSequentialGroup()
                .addComponent(jPanelMovimento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelRodape, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(barra, javax.swing.GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE)
            .addComponent(jPanelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(barra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed

        UIEntradaDados uiEntrada = getOrigem();
        if (uiEntrada != null) {
            if (uiEntrada.salvarDados()) {
                setAlterado(false);
            }
        }
    }//GEN-LAST:event_jButtonSalvarActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed

        UIEntradaDados uiEntrada = getOrigem();
        if (uiEntrada != null) {
            uiEntrada.limparDados();
            if (_novo) {
                setNovo(false);
                eliminarConteudo(getComponents());
            }
            else {
                uiEntrada.exibirDados();
                setAlterado(false);
            }
        }
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    protected UIEntradaDados getOrigem() {
        final int NIVEIS_CONTAINERS = 10;
        UIEntradaDados uiEntrada = null;

        Container cont = getParent();
        int nivel = NIVEIS_CONTAINERS;
        while ( ! (cont instanceof UIEntradaDados) && nivel > 0) {
            cont = cont.getParent();
            nivel--;
        }
        if (nivel > 0) {
            uiEntrada = (UIEntradaDados) cont;
        }

        return uiEntrada;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private br.com.codigocerto.swing.barras.BarraCadastro barra;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonSalvar;
    private javax.swing.JPanel jPanelMovimento;
    private javax.swing.JPanel jPanelPrincipal;
    private javax.swing.JPanel jPanelRodape;
    // End of variables declaration//GEN-END:variables

    /**
     *Configura acao para botao fechar
     *@param acao para fechar formulario
     */
    @Override
    public void setAcaoFechar(ActionListener acao) {
        barra.setAcaoFechar(acao);
    }

    /**
     *Configura acao para botao proximo
     *@param acao para proximo registro
     */
    @Override
    public void setAcaoProximo(ActionListener acao) {
        barra.setAcaoProximo(acao);
    }

    /**
     *Configura acao para botao anterior
     *@param acao para registro anterior
     */
    public void setAcaoAnterior(ActionListener acao) {
        barra.setAcaoAnterior(acao);
    }

    /**
     *Configura acao para botao primeiro
     *@param acao para primeiro registro
     */
    public void setAcaoPrimeiro(ActionListener acao) {
        barra.setAcaoPrimeiro(acao);
    }

    /**
     *Configura acao para botao ultimo
     *@param acao para ultimo registro
     */
    public void setAcaoUltimo(ActionListener acao) {
        barra.setAcaoUltimo(acao);
    }

    /**
     *Configura acao para botao novo
     *@param acao para novo registro
     */
    public void setAcaoNovo(ActionListener acao) {
        barra.setAcaoNovo(acao);
    }

    /**
     *Configura acao para botao excluir
     *@param acao para excluir registro
     */
    public void setAcaoExcluir(ActionListener acao) {
        barra.setAcaoExcluir(acao);
    }

    /**
     *Configura acao para botao pesquisar
     *@param acao para pesquisar cadastro
     */
    public void setAcaoPesquisar(ActionListener acao) {
        barra.setAcaoPesquisar(acao);
    }

    /**
     *Configura estado de alteracao
     *@param boolean com estado
     */
    public void setAlterado(boolean alterado) {
        _alterado = alterado;
        barra.setAlterado(_alterado);
        jButtonCancelar.setEnabled(_alterado);
        jButtonSalvar.setEnabled(_alterado);
        if ( ! _alterado) {
            _novo = false;
        }
    }

    /**
     *Informa estado de alteracao de dados no painel
     *@return boolean com estado
     */
    public boolean getAlterado() {
        return _alterado;
    }

    /**
     *Configura estado de Novo
     *@param boolean com estado
     */
    public void setNovo(boolean novo) {
        _novo = novo;
        _alterado = _novo;
        barra.setAlterado(_alterado);
        jButtonCancelar.setEnabled(_alterado);
        jButtonSalvar.setEnabled(_alterado);
        eliminarConteudo(jPanelPrincipal.getComponents());
    }

    /**
     *Informa estado de alteracao de dados no painel
     *@return boolean com estado
     */
    public boolean getNovo() {
        return _novo;
    }

    /**
     * Configura dica em determinado componente
     *@param nomeComponente string com nome do componente
     *@param dica string com dica
     */
    public void setDica(String nomeComponente, String dica) {

        for (Component comp : jPanelPrincipal.getComponents()) {

            if (comp.getName() != null && comp.getName().equals(nomeComponente)) {
                ((JComponent)comp).setToolTipText(dica);
            }
            else {
                if (comp instanceof JComponent) {
                    JComponent jComp = (JComponent) comp;
                    if (jComp.getComponentCount() > 0) {
                        setDica(jComp, nomeComponente, dica);
                    }
                }
            }
        }
    }

    private void setDica(JComponent componente, String nomeComponente, String dica) {

        for (Component comp : componente.getComponents()) {

            if (comp.getName() != null && comp.getName().equals(nomeComponente)) {
                ((JComponent)comp).setToolTipText(dica);
            }
            else {
                if (comp instanceof JComponent) {
                    JComponent jComp = (JComponent) comp;
                    if (jComp.getComponentCount() > 0) {
                        setDica(jComp, nomeComponente, dica);
                    }
                }
            }
        }
    }

    /**
     *Informa valor setado em determinado componente
     *@return Object valor inserido
     */
    public Object getValor(String nomeComponente) {
        Object valor = null;

        for (Component comp : jPanelPrincipal.getComponents()) {

            if (comp.getName() != null && comp.getName().equals(nomeComponente)) {
                return getValor(comp);
            }
            else {
                if (comp instanceof JComponent) {
                    JComponent jComp = (JComponent) comp;
                    if (jComp.getComponentCount() > 0) {
                        valor = getValor(jComp, nomeComponente);
                        if (valor != null) {
                            return valor;
                        }
                    }
                }
            }
        }

        return valor;
    }

    /**
     * Adiciona painel com objetos da movimentacao
     * @param painel
     */
    public void addPainelMovimento(JPanel painel) {
        GroupLayout layout = (GroupLayout) jPanelMovimento.getLayout();
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                )
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                )
        );
    }

    private Object getValor(JComponent componente, String nomeComponente) {
        Object valor = null;

        for (Component comp : componente.getComponents()) {

            if (comp.getName() != null && comp.getName().equals(nomeComponente)) {
                return getValor(comp);
            }
            else {
                if (comp instanceof JComponent) {
                    JComponent jComp = (JComponent) comp;
                    if (jComp.getComponentCount() > 0) {
                        valor = getValor(jComp, nomeComponente);
                        if (valor != null) {
                            return valor;
                        }
                    }
                }
            }
        }

        return valor;
    }

    private Object getValor(Component comp) {
        Object valor = null;
        if (comp instanceof CCDataField) {
            valor = ((CCDataField)comp).getDate();
        }
            else {
            if (comp instanceof CCTextNumerico) {
                valor = ((CCTextNumerico)comp).getDecimalValue();
            }
            else {
                if (comp instanceof CCPesquisaCadastro) {
                    valor = new Long(((CCPesquisaCadastro)comp).getId());
                }
                else {
                    if (comp instanceof JTextComponent) {
                        valor = ((JTextComponent)comp).getText();
                    }
                    else {
                        if (comp instanceof JCheckBox) {
                            valor = new Boolean(((JCheckBox) comp).isSelected());
                        }
                    }
                }
            }
        }
        return valor;
    }

    /**
     *Focar componente
     *@param String nome do campo associado ao componente
     */
    public void focarCampo(String nomeCampo) {

        for (Component comp : jPanelPrincipal.getComponents()) {

            if (comp.getName() != null && comp.getName().equals(nomeCampo)) {
                comp.requestFocusInWindow();
            }
            else {
                if (comp instanceof JComponent) {
                    JComponent jComp = (JComponent) comp;
                    if (jComp.getComponentCount() > 0) {
                        focarCampo(jComp, nomeCampo);
                    }
                }
            }
        }
    }

    private void focarCampo(JComponent componente, String nomeComponente) {

        for (Component comp : componente.getComponents()) {

            if (comp.getName() != null && comp.getName().equals(nomeComponente)) {
                 comp.requestFocusInWindow();
            }
            else {
                if (comp instanceof JComponent) {
                    JComponent jComp = (JComponent) comp;
                    if (jComp.getComponentCount() > 0) {
                        focarCampo(jComp, nomeComponente);
                    }
                }
            }
        }
    }

    /**
     *Elimina conteudo dos campos
     */
    @Override
    public void limparDados() {
        eliminarConteudo(jPanelPrincipal.getComponents());
    }

    private void eliminarConteudo(Component[] componentes) {
        for (Component comp : componentes) {
            if (comp instanceof CCTabela) {
                TableModel modelo = ((CCTabela)comp).getModel();
                if (modelo instanceof CCModeloTabela) {
                    ((CCModeloTabela)modelo).setConteudo(null);
                }
            } else {
                if (comp instanceof CCTextoFixo) {
                    ((CCTextoFixo)comp).setText(" ");
                } else {
                    if (comp instanceof CCPesquisaCadastro) {
                        ((CCPesquisaCadastro)comp).setId(0L);
                    } else {
                        if (comp instanceof CCDataField) {
                            ((CCDataField) comp).setDate(null);
                        } else {
                            if (comp instanceof JTextComponent) {
                                ((JTextComponent) comp).setText("");
                            } else {
                                if (comp instanceof JCheckBox) {
                                    ((JCheckBox) comp).setSelected(false);
                                } else {
                                    if (comp instanceof JComponent) {
                                        JComponent jComp = (JComponent) comp;
                                        if (jComp.getComponentCount() > 0) {
                                            eliminarConteudo(jComp.getComponents());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    protected void configurar() {
        setAlterado(_alterado);
        configurarAtalhos();
    }

    private void configurarAtalhos() {
        jButtonSalvar.setMnemonic(jButtonSalvar.getText().charAt(0));
        jButtonSalvar.setToolTipText("Salvar <Alt+S>");
        jButtonCancelar.setMnemonic(jButtonCancelar.getText().charAt(0));
        jButtonCancelar.setToolTipText("Cancelar alterações <Alt+C>");
    }

    public void exibirDados() {
        UIEntradaDados uiEntrada = getOrigem();
        if (uiEntrada != null) {
            if (!_novo) {
                uiEntrada.exibirDados();
            }
        }
    }

}


text:
module Nyauth
  class ResetPasswordRequest
    include ActiveModel::Model
    attr_reader :email, :client

    def initialize(service_params = {})
      @email = service_params[:email]
    end

    def save(options = {})
      options.reverse_merge!(as: :user)
      klass = options[:as].to_s.classify.constantize
      @client = klass.with_given_email(@email).last!
      @client.request_reset_password
    rescue
      errors.add(:base, :invalid_email)
    end
  end
end


text:
system = require('system');

if (system.args.length < 2) {
    console.log('Expected a target URL parameter.');
    phantom.exit(1);
}

var page = require('webpage').create();
var url = system.args[1];

page.onConsoleMessage = function (message) {
    console.log("Test console: " + message);
};

console.log("Loading URL: " + url);

page.open(url, function (status) {
    if (status != "success") {
        console.log('Failed to open ' + url);
        phantom.exit(1);
    }

    console.log("Running test.");

    var result = page.evaluate(function() {
        return subpar.test.run();
    });

    // NOTE: PhantomJS 1.4.0 has a bug that prevents the exit codes
    //        below from being returned properly. :(
    //
    // http://code.google.com/p/phantomjs/issues/detail?id=294

    if (result != 0) {
        console.log("*** Test failed! ***");
        phantom.exit(1);
    }

    console.log("Test succeeded.");
    phantom.exit(0);
});


text:
//=============================================================================
//
//  Copyright (c) 2016-2021 Qualcomm Technologies, Inc.
//  All Rights Reserved.
//  Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================

#ifndef _DL_SYSTEM_IUDL_HPP_
#define _DL_SYSTEM_IUDL_HPP_

#include "ZdlExportDefine.hpp"

namespace zdl {
namespace DlSystem {

/**
 * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
 *
 * @brief .
 *
 * Base class user concrete UDL implementation.
 *
 * All functions are marked as:
 *
 * - virtual
 * - noexcept
 *
 * User should make sure no exceptions are propagated outside of
 * their module. Errors can be communicated via return values.
 */
class ZDL_EXPORT IUDL {
public:
   /**
    * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
    *
    * @brief .
    *
    * Destructor
    */
   virtual ~IUDL() = default;

   /**
    * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
    *
    * @brief Sets up the user's environment.
    * This is called by the SNPE framework to allow the user the
    * opportunity to setup anything which is needed for running
    * user defined layers.
    *
    * @param cookie User provided opaque data returned by the SNPE
    *               runtime
    *
    * @param insz How many elements in input size array
    * @param indim Pointer to a buffer that holds input dimension
    *               array
    * @param indimsz Input dimension size  array of the buffer
    *                 'indim'. Corresponds to indim
    *
    * @param outsz How many elements in output size array
    * @param outdim Pointer to a buffer that holds output
    *              dimension array
    * @param outdimsz Output dimension size of the buffer 'oudim'.
    *                  Corresponds to indim
    *
    * @return true on success, false otherwise
    */
   virtual bool setup(void *cookie,
                      size_t insz, const size_t **indim, const size_t *indimsz,
                      size_t outsz, const size_t **outdim, const size_t *outdimsz)  = 0;

   /**
    * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
    *
    * @brief Close the instance. Invoked by the SNPE
    * framework to allow the user the opportunity to release any resources
    * allocated during setup.
    *
    * @param cookie - User provided opaque data returned by the SNPE runtime
    */
   virtual void close(void *cookie) noexcept = 0;

   /**
    * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
    *
    * @brief Execute the user defined layer
    *
    * @param cookie User provided opaque data returned by the SNPE
    *               runtime
    *
    * @param input Const pointer to a float buffer that contains
    *               the input
    *
    * @param output Float pointer to a buffer that would hold
    *                 the user defined layer's output. This buffer
    *                 is allocated and owned by SNPE runtime.
    */
   virtual bool execute(void *cookie, const float **input, float **output)  = 0;
};

} // ns DlSystem

} // ns zdl

#endif // _DL_SYSTEM_IUDL_HPP_


text:
using Prism.Mvvm;
using Prism.Navigation;

namespace CustomizeResolver.ViewModels
{
    public class MainViewModel : BindableBase, INavigationAware
    {
        private string _title;
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public void OnNavigatedFrom(NavigationParameters parameters)
        {

        }

        public void OnNavigatedTo(NavigationParameters parameters)
        {
            if (parameters.ContainsKey("title"))
                Title = (string)parameters["title"] + " and Prism";
        }
    }
}


text:
/**
* @Author: KingZhao
*/

package com.jcommerce.core.dao;

import java.util.List;

import com.jcommerce.core.model.Topic;

public interface TopicDAO extends DAO {
    public List<Topic> getTopicList();

    public Topic getTopic(Long id);

    public void saveTopic(Topic obj);

    public void removeTopic(Long id);
}


text:
<?php

namespace Redmine\Tests\Unit\Api;

use Redmine\Api\IssueCategory;

/**
 * @coversDefaultClass \Redmine\Api\IssueCategory
 *
 * @author     Malte Gerth <mail@malte-gerth.de>
 */
class IssueCategoryTest extends \PHPUnit\Framework\TestCase
{
    /**
     * Test all().
     *
     * @covers ::all
     * @test
     */
    public function testAllReturnsClientGetResponseWithProject()
    {
        // Test values
        $projectId = 5;
        $getResponse = 'API Response';

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('get')
            ->with(
                $this->stringStartsWith('/projects/5/issue_categories.json')
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->all($projectId));
    }

    /**
     * Test all().
     *
     * @covers ::all
     * @test
     */
    public function testAllReturnsClientGetResponseWithParametersAndProject()
    {
        // Test values
        $projectId = 5;
        $parameters = ['not-used'];
        $getResponse = ['API Response'];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->any())
            ->method('get')
            ->with(
                $this->logicalAnd(
                    $this->stringStartsWith('/projects/5/issue_categories.json'),
                    $this->stringContains('not-used')
                )
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->all($projectId, $parameters));
    }

    /**
     * Test listing().
     *
     * @covers ::listing
     * @test
     */
    public function testListingReturnsNameIdArray()
    {
        // Test values
        $getResponse = [
            'issue_categories' => [
                ['id' => 1, 'name' => 'IssueCategory 1'],
                ['id' => 5, 'name' => 'IssueCategory 5'],
            ],
        ];
        $expectedReturn = [
            'IssueCategory 1' => 1,
            'IssueCategory 5' => 5,
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->atLeastOnce())
            ->method('get')
            ->with(
                $this->stringStartsWith('/projects/5/issue_categories')
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($expectedReturn, $api->listing(5));
    }

    /**
     * Test listing().
     *
     * @covers ::listing
     * @test
     */
    public function testListingCallsGetOnlyTheFirstTime()
    {
        // Test values
        $getResponse = [
            'issue_categories' => [
                ['id' => 1, 'name' => 'IssueCategory 1'],
                ['id' => 5, 'name' => 'IssueCategory 5'],
            ],
        ];
        $expectedReturn = [
            'IssueCategory 1' => 1,
            'IssueCategory 5' => 5,
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('get')
            ->with(
                $this->stringStartsWith('/projects/5/issue_categories')
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($expectedReturn, $api->listing(5));
        $this->assertSame($expectedReturn, $api->listing(5));
    }

    /**
     * Test listing().
     *
     * @covers ::listing
     * @test
     */
    public function testListingCallsGetEveryTimeWithForceUpdate()
    {
        // Test values
        $getResponse = [
            'issue_categories' => [
                ['id' => 1, 'name' => 'IssueCategory 1'],
                ['id' => 5, 'name' => 'IssueCategory 5'],
            ],
        ];
        $expectedReturn = [
            'IssueCategory 1' => 1,
            'IssueCategory 5' => 5,
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->exactly(2))
            ->method('get')
            ->with(
                $this->stringStartsWith('/projects/5/issue_categories')
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($expectedReturn, $api->listing(5, true));
        $this->assertSame($expectedReturn, $api->listing(5, true));
    }

    /**
     * Test show().
     *
     * @covers ::get
     * @covers ::show
     * @test
     */
    public function testShowReturnsClientGetResponse()
    {
        // Test values
        $getResponse = 'API Response';

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('get')
            ->with($this->stringStartsWith('/issue_categories/5.json'))
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->show(5));
    }

    /**
     * Test remove().
     *
     * @covers ::delete
     * @covers ::remove
     * @test
     */
    public function testRemoveCallsDelete()
    {
        // Test values
        $getResponse = 'API Response';

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('delete')
            ->with(
                $this->logicalAnd(
                    $this->stringStartsWith('/issue_categories/5'),
                    $this->logicalXor(
                        $this->stringContains('.json?'),
                        $this->stringContains('.xml?')
                    )
                )
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->remove(5));
    }

    /**
     * Test remove().
     *
     * @covers ::delete
     * @covers ::remove
     * @test
     */
    public function testRemoveCallsDeleteWithParameters()
    {
        // Test values
        $getResponse = 'API Response';
        $parameters = ['not-used'];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('delete')
            ->with(
                $this->logicalAnd(
                    $this->stringStartsWith('/issue_categories/5'),
                    $this->logicalXor(
                        $this->stringContains('.json?'),
                        $this->stringContains('.xml?')
                    ),
                    $this->stringContains('not-used')
                )
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->remove(5, $parameters));
    }

    /**
     * Test getIdByName().
     *
     * @covers ::getIdByName
     * @test
     */
    public function testGetIdByNameMakesGetRequest()
    {
        // Test values
        $getResponse = [
            'issue_categories' => [
                ['id' => 5, 'name' => 'IssueCategory 5'],
            ],
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('get')
            ->with(
                $this->stringStartsWith('/projects/5/issue_categories.json')
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertFalse($api->getIdByName(5, 'IssueCategory 1'));
        $this->assertSame(5, $api->getIdByName(5, 'IssueCategory 5'));
    }

    /**
     * Test create().
     *
     * @covers ::post
     * @covers ::create
     * @expectedException \Exception
     * @test
     */
    public function testCreateThrowsExceptionIfNameIsMissing()
    {
        // Test values
        $parameters = [
            'name' => null,
            'assigned_to_id' => 2,
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $api->create(5, $parameters);
    }

    /**
     * Test create().
     *
     * @covers ::post
     * @covers ::create
     * @test
     */
    public function testCreateCallsPost()
    {
        // Test values
        $getResponse = 'API Response';
        $parameters = [
            'name' => 'Test Category',
            'assigned_to_id' => 2,
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('post')
            ->with(
                '/projects/5/issue_categories.xml',
                $this->logicalAnd(
                    $this->stringStartsWith('<?xml version="1.0"?>'."\n".'<issue_category>'),
                    $this->stringEndsWith('</issue_category>'."\n"),
                    $this->stringContains('<name>Test Category</name>'),
                    $this->stringContains('<assigned_to_id>2</assigned_to_id>')
                )
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->create(5, $parameters));
    }

    /**
     * Test update().
     *
     * @covers ::put
     * @covers ::update
     * @test
     */
    public function testUpdateCallsPut()
    {
        // Test values
        $getResponse = 'API Response';
        $parameters = [
            'name' => 'Test Category',
            'assigned_to_id' => 2,
        ];

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('put')
            ->with(
                '/issue_categories/5.xml',
                $this->logicalAnd(
                    $this->stringStartsWith('<?xml version="1.0"?>'."\n".'<issue_category>'),
                    $this->stringEndsWith('</issue_category>'."\n"),
                    $this->stringContains('<name>Test Category</name>'),
                    $this->stringContains('<assigned_to_id>2</assigned_to_id>')
                )
            )
            ->willReturn($getResponse);

        // Create the object under test
        $api = new IssueCategory($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->update(5, $parameters));
    }
}


text:
export const DocsSourcesFormComponent = {
  bindings: {
    transition: '<'
  },
  template: require('./docs-sources-form.html'),
  controller: DocsSourcesFormController
};

function DocsSourcesFormController($state, DocsSources, logger) {
  'ngInject';

  const ctrl = this;

  const id = ctrl.transition && ctrl.transition.params().id;

  ctrl.DocsSources = DocsSources;

  ctrl.loading = true;
  ctrl.saving = false;
  ctrl.isNew = true;
  ctrl.source = null;

  ctrl.createOrUpdate = createOrUpdate;
  ctrl.handleKindChange = handleKindChange;

  init();

  function init() {
    ctrl.isNew = !id;

    if (ctrl.isNew) {
      ctrl.source = initEmptySource();
      ctrl.loading = false;
    } else {
      loadSource();
    }
  }

  function initEmptySource() {
    return {
      config: {}
    };
  }

  function loadSource() {
    ctrl.loading = true;
    ctrl.source = null;

    DocsSources
      .get(id)
      .then(source => {
        ctrl.source = source;
      })
      .finally(() => {
        ctrl.loading = false;
      });
  }

  function createOrUpdate() {
    if (ctrl.sourceForm.$invalid) {
      logger.error('Check the form for issues before saving');
      return;
    }

    ctrl.saving = true;

    if (ctrl.isNew) {
      DocsSources
        .create(ctrl.source)
        .then(source => {
          logger.success('New docs source created');
          $state.go('docs-sources.detail', {id: source.id});
        })
        .finally(() => {
          ctrl.saving = false;
        });
    } else {
      DocsSources
        .update(ctrl.source.id, ctrl.source)
        .then(source => {
          logger.success('Docs source updated');
          $state.go('docs-sources.detail', {id: source.id});
        })
        .finally(() => {
          ctrl.saving = false;
        });
    }
  }

  function handleKindChange() {
    ctrl.source.config = {};
  }
}


text:
function standingBands(standing){
    var cont = $("<span />")
        band(cont,false,standing,"Lower")
    band(cont,true,standing,"Higher")
    return cont;
}
var availableStandings = ["P","C","D"]
function standing(author){
    if(!(author in standings)){
        return "NA"
    }
    var s = standings[author]
    var projectedGrade = "D"
    if(s < 150){
        projectedGrade = "C"
    }
    if(s < 50){
        projectedGrade = "P"
    }
    return projectedGrade;
}


text:
namespace cpp_client
{

namespace chess
{

} // chess

} // cpp_client


text:
package ai.verta.swagger._public.uac.model

import scala.util.Try

import net.liftweb.json._

import ai.verta.swagger._public.uac.model.ModelDBActionEnumModelDBServiceActions._
import ai.verta.swagger._public.uac.model.ModelDBResourceEnumModelDBServiceResourceTypes._
import ai.verta.swagger._public.uac.model.ServiceEnumService._
import ai.verta.swagger.client.objects._

case class UacGetSelfAllowedActionsBatch (
  resources: Option[UacResources] = None
) extends BaseSwagger {
  def toJson(): JValue = UacGetSelfAllowedActionsBatch.toJson(this)
}

object UacGetSelfAllowedActionsBatch {
  def toJson(obj: UacGetSelfAllowedActionsBatch): JObject = {
    new JObject(
      List[Option[JField]](
        obj.resources.map(x => JField("resources", ((x: UacResources) => UacResources.toJson(x))(x)))
      ).flatMap(x => x match {
        case Some(y) => List(y)
        case None => Nil
      })
    )
  }

  def fromJson(value: JValue): UacGetSelfAllowedActionsBatch =
    value match {
      case JObject(fields) => {
        val fieldsMap = fields.map(f => (f.name, f.value)).toMap
        UacGetSelfAllowedActionsBatch(
          // TODO: handle required
          resources = fieldsMap.get("resources").map(UacResources.fromJson)
        )
      }
      case _ => throw new IllegalArgumentException(s"unknown type ${value.getClass.toString}")
    }
}


text:
package pe.fu.common.controller;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import pe.fu.common.utils.StringUtils;

/**
 *
 *
所有controller的基类

 *
 *

 * 封装一些公共的方法
 *

 *
 * @author Huang Chen Jun Fu (请联系我^_^)
 * @since 1.7
 * @version 1.0
 * @date 2017年4月8日
 *
 */
public class BaseController {
	/**
	 * 获取页数
	 *
	 * @param request
	 * @return
	 */
	protected int getPageNumber(HttpServletRequest request) {
		final int defaultValue = 1;
		String page = request.getParameter("page");// page参数easyui的
		return StringUtils.isEmpty(page) ? defaultValue : Integer.parseInt(page);
	};

	/**
	 * 获取页长(每页多少条记录)
	 *
	 * @param request
	 * @return
	 */
	protected int getPageSize(HttpServletRequest request) {
		final int defaultValue = 20;
		String rows = request.getParameter("rows");// rows参数是easyui的
		return StringUtils.isEmpty(rows) ? defaultValue : Integer.parseInt(rows);
	};
	/**
	 * 解决日期转换
	 * @param binder
	 */
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		// binder.registerCustomEditor(String.class, new
		// StringTrimmerEditor(false));
	}
}


text:
@implementation OCTClient (Activity)

- (RACSignal *)hasUserStarredRepository:(OCTRepository *)repository {
	NSParameterAssert(repository != nil);
	if (!self.authenticated) return [RACSignal error:self.class.authenticationRequiredError];

	NSString *path = [NSString stringWithFormat:@"/user/starred/%@/%@", repository.ownerLogin, repository.name];
	NSMutableURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:nil];
	return [[[self
		enqueueRequest:request resultClass:nil]
		reduceEach:^(NSHTTPURLResponse *response, id _) {
			return @(response.statusCode == 204);
		}]
		catch:^RACSignal *(NSError *error) {
			NSNumber *statusCode = error.userInfo[OCTClientErrorHTTPStatusCodeKey];
			if (statusCode.integerValue == 404) {
				return [RACSignal return:@NO];
			} else {
				return [RACSignal error:error];
			}
		}];
}

- (RACSignal *)starRepository:(OCTRepository *)repository {
	NSParameterAssert(repository != nil);
	if (!self.authenticated) return [RACSignal error:self.class.authenticationRequiredError];

	NSString *path = [NSString stringWithFormat:@"/user/starred/%@/%@", repository.ownerLogin, repository.name];
	NSMutableURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:nil];
	return [[self enqueueRequest:request resultClass:nil] ignoreValues];
}

- (RACSignal *)unstarRepository:(OCTRepository *)repository {
	NSParameterAssert(repository != nil);
	if (!self.authenticated) return [RACSignal error:self.class.authenticationRequiredError];

	NSString *path = [NSString stringWithFormat:@"/user/starred/%@/%@", repository.ownerLogin, repository.name];
	NSMutableURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:nil];
	return [[self enqueueRequest:request resultClass:nil] ignoreValues];
}

@end