text:
package codescan

import (
	"encoding/json"
	"fmt"
	"go/ast"
	"regexp"
	"strconv"
	"strings"

	"github.com/go-openapi/loads/fmts"
	"github.com/go-openapi/spec"
	"github.com/pkg/errors"
	"gopkg.in/yaml.v2"
)

func shouldAcceptTag(tags []string, includeTags map[string]bool, excludeTags map[string]bool) bool {
	for _, tag := range tags {
		if len(includeTags) > 0 {
			if includeTags[tag] {
				return true
			}
		} else if len(excludeTags) > 0 {
			if excludeTags[tag] {
				return false
			}
		}
	}
	return len(includeTags) == 0
}

func shouldAcceptPkg(path string, includePkgs, excludePkgs []string) bool {
	if len(includePkgs) == 0 && len(excludePkgs) == 0 {
		return true
	}
	for _, pkgName := range includePkgs {
		matched, _ := regexp.MatchString(pkgName, path)
		if matched {
			return true
		}
	}
	for _, pkgName := range excludePkgs {
		matched, _ := regexp.MatchString(pkgName, path)
		if matched {
			return false
		}
	}
	return len(includePkgs) == 0
}

// Many thanks go to https://github.com/yvasiyarov/swagger
// this is loosely based on that implementation but for swagger 2.0

func joinDropLast(lines []string) string {
	l := len(lines)
	lns := lines
	if l > 0 && len(strings.TrimSpace(lines[l-1])) == 0 {
		lns = lines[:l-1]
	}
	return strings.Join(lns, "\n")
}

func removeEmptyLines(lines []string) (notEmpty []string) {
	for _, l := range lines {
		if len(strings.TrimSpace(l)) > 0 {
			notEmpty = append(notEmpty, l)
		}
	}
	return
}

func rxf(rxp, ar string) *regexp.Regexp {
	return regexp.MustCompile(fmt.Sprintf(rxp, ar))
}

func allOfMember(comments *ast.CommentGroup) bool {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				if rxAllOf.MatchString(ln) {
					return true
				}
			}
		}
	}
	return false
}

func fileParam(comments *ast.CommentGroup) bool {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				if rxFileUpload.MatchString(ln) {
					return true
				}
			}
		}
	}
	return false
}

func strfmtName(comments *ast.CommentGroup) (string, bool) {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				matches := rxStrFmt.FindStringSubmatch(ln)
				if len(matches) > 1 && len(strings.TrimSpace(matches[1])) > 0 {
					return strings.TrimSpace(matches[1]), true
				}
			}
		}
	}
	return "", false
}

func ignored(comments *ast.CommentGroup) bool {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				if rxIgnoreOverride.MatchString(ln) {
					return true
				}
			}
		}
	}
	return false
}

func enumName(comments *ast.CommentGroup) (string, bool) {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				matches := rxEnum.FindStringSubmatch(ln)
				if len(matches) > 1 && len(strings.TrimSpace(matches[1])) > 0 {
					return strings.TrimSpace(matches[1]), true
				}
			}
		}
	}
	return "", false
}

func aliasParam(comments *ast.CommentGroup) bool {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				if rxAlias.MatchString(ln) {
					return true
				}
			}
		}
	}
	return false
}

func isAliasParam(prop swaggerTypable) bool {
	var isParam bool
	if param, ok := prop.(paramTypable); ok {
		isParam = param.param.In == "query" ||
			param.param.In == "path" ||
			param.param.In == "formData"
	}
	return isParam
}

func defaultName(comments *ast.CommentGroup) (string, bool) {
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				matches := rxDefault.FindStringSubmatch(ln)
				if len(matches) > 1 && len(strings.TrimSpace(matches[1])) > 0 {
					return strings.TrimSpace(matches[1]), true
				}
			}
		}
	}
	return "", false
}

func typeName(comments *ast.CommentGroup) (string, bool) {
	var typ string
	if comments != nil {
		for _, cmt := range comments.List {
			for _, ln := range strings.Split(cmt.Text, "\n") {
				matches := rxType.FindStringSubmatch(ln)
				if len(matches) > 1 && len(strings.TrimSpace(matches[1])) > 0 {
					typ = strings.TrimSpace(matches[1])
					return typ, true
				}
			}
		}
	}
	return "", false
}

type swaggerTypable interface {
	Typed(string, string)
	SetRef(spec.Ref)
	Items() swaggerTypable
	Schema() *spec.Schema
	Level() int
	AddExtension(key string, value interface{})
	WithEnum(...interface{})
}

// Map all Go builtin types that have Json representation to Swagger/Json types.
// See https://golang.org/pkg/builtin/ and http://swagger.io/specification/
func swaggerSchemaForType(typeName string, prop swaggerTypable) error {
	switch typeName {
	case "bool":
		prop.Typed("boolean", "")
	case "byte":
		prop.Typed("integer", "uint8")
	case "complex128", "complex64":
		return fmt.Errorf("unsupported builtin %q (no JSON marshaller)", typeName)
	case "error":
		// TODO: error is often marshalled into a string but not always (e.g. errors package creates
		// errors that are marshalled into an empty object), this could be handled the same way
		// custom JSON marshallers are handled (in future)
		prop.Typed("string", "")
	case "float32":
		prop.Typed("number", "float")
	case "float64":
		prop.Typed("number", "double")
	case "int":
		prop.Typed("integer", "int64")
	case "int16":
		prop.Typed("integer", "int16")
	case "int32":
		prop.Typed("integer", "int32")
	case "int64":
		prop.Typed("integer", "int64")
	case "int8":
		prop.Typed("integer", "int8")
	case "rune":
		prop.Typed("integer", "int32")
	case "string":
		prop.Typed("string", "")
	case "uint":
		prop.Typed("integer", "uint64")
	case "uint16":
		prop.Typed("integer", "uint16")
	case "uint32":
		prop.Typed("integer", "uint32")
	case "uint64":
		prop.Typed("integer", "uint64")
	case "uint8":
		prop.Typed("integer", "uint8")
	case "uintptr":
		prop.Typed("integer", "uint64")
	default:
		return fmt.Errorf("unsupported type %q", typeName)
	}
	return nil
}

func newMultiLineTagParser(name string, parser valueParser, skipCleanUp bool) tagParser {
	return tagParser{
		Name:        name,
		MultiLine:   true,
		SkipCleanUp: skipCleanUp,
		Parser:      parser,
	}
}

func newSingleLineTagParser(name string, parser valueParser) tagParser {
	return tagParser{
		Name:        name,
		MultiLine:   false,
		SkipCleanUp: false,
		Parser:      parser,
	}
}

type tagParser struct {
	Name        string
	MultiLine   bool
	SkipCleanUp bool
	Lines       []string
	Parser      valueParser
}

func (st *tagParser) Matches(line string) bool {
	return st.Parser.Matches(line)
}

func (st *tagParser) Parse(lines []string) error {
	return st.Parser.Parse(lines)
}

func newYamlParser(rx *regexp.Regexp, setter func(json.RawMessage) error) valueParser {
	return &yamlParser{
		set: setter,
		rx:  rx,
	}
}

type yamlParser struct {
	set func(json.RawMessage) error
	rx  *regexp.Regexp
}

func (y *yamlParser) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}

	var uncommented []string
	uncommented = append(uncommented, removeYamlIndent(lines)...)

	yamlContent := strings.Join(uncommented, "\n")
	var yamlValue interface{}
	err := yaml.Unmarshal([]byte(yamlContent), &yamlValue)
	if err != nil {
		return err
	}

	var jsonValue json.RawMessage
	jsonValue, err = fmts.YAMLToJSON(yamlValue)
	if err != nil {
		return err
	}

	return y.set(jsonValue)
}

func (y *yamlParser) Matches(line string) bool {
	return y.rx.MatchString(line)
}

// aggregates lines in header until it sees `---`,
// the beginning of a YAML spec
type yamlSpecScanner struct {
	header         []string
	yamlSpec       []string
	setTitle       func([]string)
	setDescription func([]string)
	workedOutTitle bool
	title          []string
	skipHeader     bool
}

func cleanupScannerLines(lines []string, ur *regexp.Regexp, yamlBlock *regexp.Regexp) []string {
	// bail early when there is nothing to parse
	if len(lines) == 0 {
		return lines
	}
	seenLine := -1
	var lastContent int
	var uncommented []string
	var startBlock bool
	var yamlLines []string
	for i, v := range lines {
		if yamlBlock != nil && yamlBlock.MatchString(v) && !startBlock {
			startBlock = true
			if seenLine < 0 {
				seenLine = i
			}
			continue
		}
		if startBlock {
			if yamlBlock != nil && yamlBlock.MatchString(v) {
				startBlock = false
				uncommented = append(uncommented, removeIndent(yamlLines)...)
				continue
			}
			yamlLines = append(yamlLines, v)
			if v != "" {
				if seenLine < 0 {
					seenLine = i
				}
				lastContent = i
			}
			continue
		}
		str := ur.ReplaceAllString(v, "")
		uncommented = append(uncommented, str)
		if str != "" {
			if seenLine < 0 {
				seenLine = i
			}
			lastContent = i
		}
	}

	// fixes issue #50
	if seenLine == -1 {
		return nil
	}
	return uncommented[seenLine : lastContent+1]
}

// a shared function that can be used to split given headers
// into a title and description
func collectScannerTitleDescription(headers []string) (title, desc []string) {
	hdrs := cleanupScannerLines(headers, rxUncommentHeaders, nil)

	idx := -1
	for i, line := range hdrs {
		if strings.TrimSpace(line) == "" {
			idx = i
			break
		}
	}

	if idx > -1 {
		title = hdrs[:idx]
		if len(hdrs) > idx+1 {
			desc = hdrs[idx+1:]
		} else {
			desc = nil
		}
		return
	}

	if len(hdrs) > 0 {
		line := hdrs[0]
		if rxPunctuationEnd.MatchString(line) {
			title = []string{line}
			desc = hdrs[1:]
		} else {
			desc = hdrs
		}
	}

	return
}

func (sp *yamlSpecScanner) collectTitleDescription() {
	if sp.workedOutTitle {
		return
	}
	if sp.setTitle == nil {
		sp.header = cleanupScannerLines(sp.header, rxUncommentHeaders, nil)
		return
	}

	sp.workedOutTitle = true
	sp.title, sp.header = collectScannerTitleDescription(sp.header)
}

func (sp *yamlSpecScanner) Title() []string {
	sp.collectTitleDescription()
	return sp.title
}

func (sp *yamlSpecScanner) Description() []string {
	sp.collectTitleDescription()
	return sp.header
}

func (sp *yamlSpecScanner) Parse(doc *ast.CommentGroup) error {
	if doc == nil {
		return nil
	}
	var startedYAMLSpec bool
COMMENTS:
	for _, c := range doc.List {
		for _, line := range strings.Split(c.Text, "\n") {
			if rxSwaggerAnnotation.MatchString(line) {
				break COMMENTS // a new swagger: annotation terminates this parser
			}

			if !startedYAMLSpec {
				if rxBeginYAMLSpec.MatchString(line) {
					startedYAMLSpec = true
					sp.yamlSpec = append(sp.yamlSpec, line)
					continue
				}

				if !sp.skipHeader {
					sp.header = append(sp.header, line)
				}

				// no YAML spec yet, moving on
				continue
			}

			sp.yamlSpec = append(sp.yamlSpec, line)
		}
	}
	if sp.setTitle != nil {
		sp.setTitle(sp.Title())
	}
	if sp.setDescription != nil {
		sp.setDescription(sp.Description())
	}
	return nil
}

func (sp *yamlSpecScanner) UnmarshalSpec(u func([]byte) error) (err error) {
	specYaml := cleanupScannerLines(sp.yamlSpec, rxUncommentYAML, nil)
	if len(specYaml) == 0 {
		return errors.New("no spec available to unmarshal")
	}

	if !strings.Contains(specYaml[0], "---") {
		return errors.New("yaml spec has to start with `---`")
	}

	// remove indentation
	specYaml = removeIndent(specYaml)

	// 1. parse yaml lines
	yamlValue := make(map[interface{}]interface{})

	yamlContent := strings.Join(specYaml, "\n")
	err = yaml.Unmarshal([]byte(yamlContent), &yamlValue)
	if err != nil {
		return
	}

	// 2. convert to json
	var jsonValue json.RawMessage
	jsonValue, err = fmts.YAMLToJSON(yamlValue)
	if err != nil {
		return
	}

	// 3. unmarshal the json into an interface
	var data []byte
	data, err = jsonValue.MarshalJSON()
	if err != nil {
		return
	}
	err = u(data)
	if err != nil {
		return
	}

	// all parsed, returning...
	sp.yamlSpec = nil // spec is now consumed, so let's erase the parsed lines
	return
}

// removes indent base on the first line
func removeIndent(spec []string) []string {
	loc := rxIndent.FindStringIndex(spec[0])
	if loc[1] == 0 {
		return spec
	}
	for i := range spec {
		if len(spec[i]) >= loc[1] {
			spec[i] = spec[i][loc[1]-1:]
		}
	}
	return spec
}

// removes indent base on the first line
func removeYamlIndent(spec []string) []string {
	loc := rxIndent.FindStringIndex(spec[0])
	if loc[1] == 0 {
		return nil
	}
	var s []string
	for i := range spec {
		if len(spec[i]) >= loc[1] {
			s = append(s, spec[i][loc[1]-1:])
		}
	}
	return s
}

// aggregates lines in header until it sees a tag.
type sectionedParser struct {
	header     []string
	matched    map[string]tagParser
	annotation valueParser

	seenTag        bool
	skipHeader     bool
	setTitle       func([]string)
	setDescription func([]string)
	workedOutTitle bool
	taggers        []tagParser
	currentTagger  *tagParser
	title          []string
	ignored        bool
}

func (st *sectionedParser) collectTitleDescription() {
	if st.workedOutTitle {
		return
	}
	if st.setTitle == nil {
		st.header = cleanupScannerLines(st.header, rxUncommentHeaders, nil)
		return
	}

	st.workedOutTitle = true
	st.title, st.header = collectScannerTitleDescription(st.header)
}

func (st *sectionedParser) Title() []string {
	st.collectTitleDescription()
	return st.title
}

func (st *sectionedParser) Description() []string {
	st.collectTitleDescription()
	return st.header
}

func (st *sectionedParser) Parse(doc *ast.CommentGroup) error {
	if doc == nil {
		return nil
	}
COMMENTS:
	for _, c := range doc.List {
		for _, line := range strings.Split(c.Text, "\n") {
			if rxSwaggerAnnotation.MatchString(line) {
				if rxIgnoreOverride.MatchString(line) {
					st.ignored = true
					break COMMENTS // an explicit ignore terminates this parser
				}
				if st.annotation == nil || !st.annotation.Matches(line) {
					break COMMENTS // a new swagger: annotation terminates this parser
				}

				_ = st.annotation.Parse([]string{line})
				if len(st.header) > 0 {
					st.seenTag = true
				}
				continue
			}

			var matched bool
			for _, tagger := range st.taggers {
				if tagger.Matches(line) {
					st.seenTag = true
					st.currentTagger = &tagger
					matched = true
					break
				}
			}

			if st.currentTagger == nil {
				if !st.skipHeader && !st.seenTag {
					st.header = append(st.header, line)
				}
				// didn't match a tag, moving on
				continue
			}

			if st.currentTagger.MultiLine && matched {
				// the first line of a multiline tagger doesn't count
				continue
			}

			ts, ok := st.matched[st.currentTagger.Name]
			if !ok {
				ts = *st.currentTagger
			}
			ts.Lines = append(ts.Lines, line)
			if st.matched == nil {
				st.matched = make(map[string]tagParser)
			}
			st.matched[st.currentTagger.Name] = ts

			if !st.currentTagger.MultiLine {
				st.currentTagger = nil
			}
		}
	}
	if st.setTitle != nil {
		st.setTitle(st.Title())
	}
	if st.setDescription != nil {
		st.setDescription(st.Description())
	}
	for _, mt := range st.matched {
		if !mt.SkipCleanUp {
			mt.Lines = cleanupScannerLines(mt.Lines, rxUncommentHeaders, nil)
		}
		if err := mt.Parse(mt.Lines); err != nil {
			return err
		}
	}
	return nil
}

type validationBuilder interface {
	SetMaximum(float64, bool)
	SetMinimum(float64, bool)
	SetMultipleOf(float64)

	SetMinItems(int64)
	SetMaxItems(int64)

	SetMinLength(int64)
	SetMaxLength(int64)
	SetPattern(string)

	SetUnique(bool)
	SetEnum(string)
	SetDefault(interface{})
	SetExample(interface{})
}

type valueParser interface {
	Parse([]string) error
	Matches(string) bool
}

type operationValidationBuilder interface {
	validationBuilder
	SetCollectionFormat(string)
}

type setMaximum struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMaximum) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 2 && len(matches[2]) > 0 {
		max, err := strconv.ParseFloat(matches[2], 64)
		if err != nil {
			return err
		}
		sm.builder.SetMaximum(max, matches[1] == "<")
	}
	return nil
}

func (sm *setMaximum) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

type setMinimum struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMinimum) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

func (sm *setMinimum) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 2 && len(matches[2]) > 0 {
		min, err := strconv.ParseFloat(matches[2], 64)
		if err != nil {
			return err
		}
		sm.builder.SetMinimum(min, matches[1] == ">")
	}
	return nil
}

type setMultipleOf struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMultipleOf) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

func (sm *setMultipleOf) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 2 && len(matches[1]) > 0 {
		multipleOf, err := strconv.ParseFloat(matches[1], 64)
		if err != nil {
			return err
		}
		sm.builder.SetMultipleOf(multipleOf)
	}
	return nil
}

type setMaxItems struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMaxItems) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

func (sm *setMaxItems) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		maxItems, err := strconv.ParseInt(matches[1], 10, 64)
		if err != nil {
			return err
		}
		sm.builder.SetMaxItems(maxItems)
	}
	return nil
}

type setMinItems struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMinItems) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

func (sm *setMinItems) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		minItems, err := strconv.ParseInt(matches[1], 10, 64)
		if err != nil {
			return err
		}
		sm.builder.SetMinItems(minItems)
	}
	return nil
}

type setMaxLength struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMaxLength) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		maxLength, err := strconv.ParseInt(matches[1], 10, 64)
		if err != nil {
			return err
		}
		sm.builder.SetMaxLength(maxLength)
	}
	return nil
}

func (sm *setMaxLength) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

type setMinLength struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setMinLength) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		minLength, err := strconv.ParseInt(matches[1], 10, 64)
		if err != nil {
			return err
		}
		sm.builder.SetMinLength(minLength)
	}
	return nil
}

func (sm *setMinLength) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

type setPattern struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sm *setPattern) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		sm.builder.SetPattern(matches[1])
	}
	return nil
}

func (sm *setPattern) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

type setCollectionFormat struct {
	builder operationValidationBuilder
	rx      *regexp.Regexp
}

func (sm *setCollectionFormat) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sm.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		sm.builder.SetCollectionFormat(matches[1])
	}
	return nil
}

func (sm *setCollectionFormat) Matches(line string) bool {
	return sm.rx.MatchString(line)
}

type setUnique struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (su *setUnique) Matches(line string) bool {
	return su.rx.MatchString(line)
}

func (su *setUnique) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := su.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		req, err := strconv.ParseBool(matches[1])
		if err != nil {
			return err
		}
		su.builder.SetUnique(req)
	}
	return nil
}

type setEnum struct {
	builder validationBuilder
	rx      *regexp.Regexp
}

func (se *setEnum) Matches(line string) bool {
	return se.rx.MatchString(line)
}

func (se *setEnum) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := se.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		se.builder.SetEnum(matches[1])
	}
	return nil
}

func parseValueFromSchema(s string, schema *spec.SimpleSchema) (interface{}, error) {
	if schema != nil {
		switch strings.Trim(schema.TypeName(), "\"") {
		case "integer", "int", "int64", "int32", "int16":
			return strconv.Atoi(s)
		case "bool", "boolean":
			return strconv.ParseBool(s)
		case "number", "float64", "float32":
			return strconv.ParseFloat(s, 64)
		case "object":
			var obj map[string]interface{}
			if err := json.Unmarshal([]byte(s), &obj); err != nil {
				// If we can't parse it, just return the string.
				return s, nil
			}
			return obj, nil
		case "array":
			var slice []interface{}
			if err := json.Unmarshal([]byte(s), &slice); err != nil {
				// If we can't parse it, just return the string.
				return s, nil
			}
			return slice, nil
		default:
			return s, nil
		}
	} else {
		return s, nil
	}
}

type setDefault struct {
	scheme  *spec.SimpleSchema
	builder validationBuilder
	rx      *regexp.Regexp
}

func (sd *setDefault) Matches(line string) bool {
	return sd.rx.MatchString(line)
}

func (sd *setDefault) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := sd.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		d, err := parseValueFromSchema(matches[1], sd.scheme)
		if err != nil {
			return err
		}
		sd.builder.SetDefault(d)
	}
	return nil
}

type setExample struct {
	scheme  *spec.SimpleSchema
	builder validationBuilder
	rx      *regexp.Regexp
}

func (se *setExample) Matches(line string) bool {
	return se.rx.MatchString(line)
}

func (se *setExample) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := se.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		d, err := parseValueFromSchema(matches[1], se.scheme)
		if err != nil {
			return err
		}
		se.builder.SetExample(d)
	}
	return nil
}

type matchOnlyParam struct {
	tgt *spec.Parameter
	rx  *regexp.Regexp
}

func (mo *matchOnlyParam) Matches(line string) bool {
	return mo.rx.MatchString(line)
}

func (mo *matchOnlyParam) Parse(lines []string) error {
	return nil
}

type setRequiredParam struct {
	tgt *spec.Parameter
}

func (su *setRequiredParam) Matches(line string) bool {
	return rxRequired.MatchString(line)
}

func (su *setRequiredParam) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := rxRequired.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		req, err := strconv.ParseBool(matches[1])
		if err != nil {
			return err
		}
		su.tgt.Required = req
	}
	return nil
}

type setReadOnlySchema struct {
	tgt *spec.Schema
}

func (su *setReadOnlySchema) Matches(line string) bool {
	return rxReadOnly.MatchString(line)
}

func (su *setReadOnlySchema) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := rxReadOnly.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		req, err := strconv.ParseBool(matches[1])
		if err != nil {
			return err
		}
		su.tgt.ReadOnly = req
	}
	return nil
}

type setDeprecatedOp struct {
	tgt *spec.Operation
}

func (su *setDeprecatedOp) Matches(line string) bool {
	return rxDeprecated.MatchString(line)
}

func (su *setDeprecatedOp) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := rxDeprecated.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		req, err := strconv.ParseBool(matches[1])
		if err != nil {
			return err
		}
		su.tgt.Deprecated = req
	}
	return nil
}

type setDiscriminator struct {
	schema *spec.Schema
	field  string
}

func (su *setDiscriminator) Matches(line string) bool {
	return rxDiscriminator.MatchString(line)
}

func (su *setDiscriminator) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := rxDiscriminator.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		req, err := strconv.ParseBool(matches[1])
		if err != nil {
			return err
		}
		if req {
			su.schema.Discriminator = su.field
		} else if su.schema.Discriminator == su.field {
			su.schema.Discriminator = ""
		}
	}
	return nil
}

type setRequiredSchema struct {
	schema *spec.Schema
	field  string
}

func (su *setRequiredSchema) Matches(line string) bool {
	return rxRequired.MatchString(line)
}

func (su *setRequiredSchema) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := rxRequired.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		req, err := strconv.ParseBool(matches[1])
		if err != nil {
			return err
		}
		midx := -1
		for i, nm := range su.schema.Required {
			if nm == su.field {
				midx = i
				break
			}
		}
		if req {
			if midx < 0 {
				su.schema.Required = append(su.schema.Required, su.field)
			}
		} else if midx >= 0 {
			su.schema.Required = append(su.schema.Required[:midx], su.schema.Required[midx+1:]...)
		}
	}
	return nil
}

func newMultilineDropEmptyParser(rx *regexp.Regexp, set func([]string)) *multiLineDropEmptyParser {
	return &multiLineDropEmptyParser{
		rx:  rx,
		set: set,
	}
}

type multiLineDropEmptyParser struct {
	set func([]string)
	rx  *regexp.Regexp
}

func (m *multiLineDropEmptyParser) Matches(line string) bool {
	return m.rx.MatchString(line)
}

func (m *multiLineDropEmptyParser) Parse(lines []string) error {
	m.set(removeEmptyLines(lines))
	return nil
}

func newSetSchemes(set func([]string)) *setSchemes {
	return &setSchemes{
		set: set,
		rx:  rxSchemes,
	}
}

type setSchemes struct {
	set func([]string)
	rx  *regexp.Regexp
}

func (ss *setSchemes) Matches(line string) bool {
	return ss.rx.MatchString(line)
}

func (ss *setSchemes) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}
	matches := ss.rx.FindStringSubmatch(lines[0])
	if len(matches) > 1 && len(matches[1]) > 0 {
		sch := strings.Split(matches[1], ", ")

		schemes := []string{}
		for _, s := range sch {
			ts := strings.TrimSpace(s)
			if ts != "" {
				schemes = append(schemes, ts)
			}
		}
		ss.set(schemes)
	}
	return nil
}

func newSetSecurity(rx *regexp.Regexp, setter func([]map[string][]string)) *setSecurity {
	return &setSecurity{
		set: setter,
		rx:  rx,
	}
}

type setSecurity struct {
	set func([]map[string][]string)
	rx  *regexp.Regexp
}

func (ss *setSecurity) Matches(line string) bool {
	return ss.rx.MatchString(line)
}

func (ss *setSecurity) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}

	var result []map[string][]string
	for _, line := range lines {
		kv := strings.SplitN(line, ":", 2)
		scopes := []string{}
		var key string

		if len(kv) > 1 {
			scs := strings.Split(kv[1], ",")
			for _, scope := range scs {
				tr := strings.TrimSpace(scope)
				if tr != "" {
					tr = strings.SplitAfter(tr, " ")[0]
					scopes = append(scopes, strings.TrimSpace(tr))
				}
			}

			key = strings.TrimSpace(kv[0])

			result = append(result, map[string][]string{key: scopes})
		}
	}
	ss.set(result)
	return nil
}

func newSetResponses(definitions map[string]spec.Schema, responses map[string]spec.Response, setter func(*spec.Response, map[int]spec.Response)) *setOpResponses {
	return &setOpResponses{
		set:         setter,
		rx:          rxResponses,
		definitions: definitions,
		responses:   responses,
	}
}

type setOpResponses struct {
	set         func(*spec.Response, map[int]spec.Response)
	rx          *regexp.Regexp
	definitions map[string]spec.Schema
	responses   map[string]spec.Response
}

func (ss *setOpResponses) Matches(line string) bool {
	return ss.rx.MatchString(line)
}

//ResponseTag used when specifying a response to point to a defined swagger:response
const ResponseTag = "response"

//BodyTag used when specifying a response to point to a model/schema
const BodyTag = "body"

//DescriptionTag used when specifying a response that gives a description of the response
const DescriptionTag = "description"

func parseTags(line string) (modelOrResponse string, arrays int, isDefinitionRef bool, description string, err error) {
	tags := strings.Split(line, " ")
	parsedModelOrResponse := false

	for i, tagAndValue := range tags {
		tagValList := strings.SplitN(tagAndValue, ":", 2)
		var tag, value string
		if len(tagValList) > 1 {
			tag = tagValList[0]
			value = tagValList[1]
		} else {
			//TODO: Print a warning, and in the long term, do not support not tagged values
			//Add a default tag if none is supplied
			if i == 0 {
				tag = ResponseTag
			} else {
				tag = DescriptionTag
			}
			value = tagValList[0]
		}

		foundModelOrResponse := false
		if !parsedModelOrResponse {
			if tag == BodyTag {
				foundModelOrResponse = true
				isDefinitionRef = true
			}
			if tag == ResponseTag {
				foundModelOrResponse = true
				isDefinitionRef = false
			}
		}
		if foundModelOrResponse {
			//Read the model or response tag
			parsedModelOrResponse = true
			//Check for nested arrays
			arrays = 0
			for strings.HasPrefix(value, "[]") {
				arrays++
				value = value[2:]
			}
			//What's left over is the model name
			modelOrResponse = value
		} else {
			foundDescription := false
			if tag == DescriptionTag {
				foundDescription = true
			}
			if foundDescription {
				//Descriptions are special, they make they read the rest of the line
				descriptionWords := []string{value}
				if i < len(tags)-1 {
					descriptionWords = append(descriptionWords, tags[i+1:]...)
				}
				description = strings.Join(descriptionWords, " ")
				break
			} else {
				if tag == ResponseTag || tag == BodyTag || tag == DescriptionTag {
					err = fmt.Errorf("valid tag %s, but not in a valid position", tag)
				} else {
					err = fmt.Errorf("invalid tag: %s", tag)
				}
				//return error
				return
			}
		}
	}

	//TODO: Maybe do, if !parsedModelOrResponse {return some error}
	return
}

func (ss *setOpResponses) Parse(lines []string) error {
	if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) {
		return nil
	}

	var def *spec.Response
	var scr map[int]spec.Response

	for _, line := range lines {
		kv := strings.SplitN(line, ":", 2)
		var key, value string

		if len(kv) > 1 {
			key = strings.TrimSpace(kv[0])
			if key == "" {
				// this must be some weird empty line
				continue
			}
			value = strings.TrimSpace(kv[1])
			if value == "" {
				var resp spec.Response
				if strings.EqualFold("default", key) {
					if def == nil {
						def = &resp
					}
				} else {
					if sc, err := strconv.Atoi(key); err == nil {
						if scr == nil {
							scr = make(map[int]spec.Response)
						}
						scr[sc] = resp
					}
				}
				continue
			}
			refTarget, arrays, isDefinitionRef, description, err := parseTags(value)
			if err != nil {
				return err
			}
			//A possible exception for having a definition
			if _, ok := ss.responses[refTarget]; !ok {
				if _, ok := ss.definitions[refTarget]; ok {
					isDefinitionRef = true
				}
			}

			var ref spec.Ref
			if isDefinitionRef {
				if description == "" {
					description = refTarget
				}
				ref, err = spec.NewRef("#/definitions/" + refTarget)
			} else {
				ref, err = spec.NewRef("#/responses/" + refTarget)
			}
			if err != nil {
				return err
			}

			// description should used on anyway.
			resp := spec.Response{ResponseProps: spec.ResponseProps{Description: description}}

			if isDefinitionRef {
				resp.Schema = new(spec.Schema)
				resp.Description = description
				if arrays == 0 {
					resp.Schema.Ref = ref
				} else {
					cs := resp.Schema
					for i := 0; i < arrays; i++ {
						cs.Typed("array", "")
						cs.Items = new(spec.SchemaOrArray)
						cs.Items.Schema = new(spec.Schema)
						cs = cs.Items.Schema
					}
					cs.Ref = ref
				}
				// ref. could be empty while use description tag
			} else if len(refTarget) > 0 {
				resp.Ref = ref
			}

			if strings.EqualFold("default", key) {
				if def == nil {
					def = &resp
				}
			} else {
				if sc, err := strconv.Atoi(key); err == nil {
					if scr == nil {
						scr = make(map[int]spec.Response)
					}
					scr[sc] = resp
				}
			}
		}
	}
	ss.set(def, scr)
	return nil
}

func parseEnum(val string, s *spec.SimpleSchema) []interface{} {
	list := strings.Split(val, ",")
	interfaceSlice := make([]interface{}, len(list))
	for i, d := range list {
		v, err := parseValueFromSchema(d, s)
		if err != nil {
			interfaceSlice[i] = d
			continue
		}

		interfaceSlice[i] = v
	}
	return interfaceSlice
}


text:
from diamond import pyglet
from diamond.vault import Vault

class Sprite(pyglet.sprite.Sprite):

    def __init__(self, vault, parent_node=None, position=None, name=None, usage='dynamic'):
        self._vault = vault
        self._name = name
        self._action = 'none'
        self._parent_node = parent_node
        self._my_visibility = True
        if parent_node:
            parent_node._child_sprites.append(self)
            group = parent_node._sprite_group
            try:
                batch = parent_node.window._batch
            except AttributeError:
                batch = None
        else:
            batch, group = None, None
        # if position:
        #     self._x_rel, self._y_rel = position
        # else:
        #     self._x_rel, self._y_rel = 0, 0
        self._anim = vault.actions[self._action].animation
        # self._update_real_position()
        x, y = position if position is not None else (0, 0)
        super(Sprite, self).__init__(
            img=self._anim,
            # x=self._x,
            # y=self._y,
            x=x,
            y=y,
            batch=batch,
            group=group,
            usage=usage,
        )

    # def _update_real_position(self):
    #     if self._parent_node:
    #         self._x = self._parent_node._x_real + self._x_rel
    #         self._y = self._parent_node._y_real + self._y_rel
    #     else:
    #         self._x = self._x_rel
    #         self._y = self._y_rel
    #     self._x = self._x_rel
    #     self._y = self._y_rel
    #     if self._vertex_list:
    #         self._update_position()

    # def _set_x(self, x):
    #     if x != self._x_rel:
    #         self._x_rel = x
    #         self._update_real_position()

    # x = property(lambda self: self._x_rel, _set_x)

    # def _set_y(self, y):
    #     if y != self._y_rel:
    #         self._y_rel = y
    #         self._update_real_position()

    # y = property(lambda self: self._y_rel, _set_y)

    # def set_position(self, x, y):
    #     self._x_rel, self._y_rel = x, y
    #     self._update_real_position()

    # position = property(lambda self: (self._x_rel, self._y_rel),
    #                     lambda self, pos: self.set_position(*pos))

    def _update_inherited_visibility(self):
        new_visibility = self._my_visibility and self._parent_node._inherited_visibility
        if new_visibility != self._visible:
            # We reuse pyglets sprite code here.
            self._visible = new_visibility
            self._update_position()

    def _set_visible(self, visible):
        self._my_visibility = visible
        self._update_inherited_visibility()

    visible = property(lambda self: self._visible, _set_visible)

    def set_action(self, name):
        if name != self._action:
            self._action = name
            self._anim = self._vault.actions[name].animation
            self.image = self._anim

    action = property(lambda self: self._action, set_action)

    @classmethod
    def make(cls, vault_module, sprite_name=None, **kwargs):
        '''Factory which creates a vault and returns a proper Sprite object.'''
        if not isinstance(vault_module, Vault):
            vault = Vault.get_instance(vault_module)
        else:
            vault = vault_module
        if sprite_name is not None:
            vault = vault.get_sprite(str(sprite_name))
        else:
            vault = vault.get_sprites().values()[0]
        return cls(vault=vault, **kwargs)

    @classmethod
    def make_many(cls, vault_module, sprite_name=None, amount=1, **kwargs):
        '''Factory which creates a vault and returns x Sprite objects within a list.'''
        if not isinstance(vault_module, Vault):
            vault = Vault.get_instance(vault_module)
        else:
            vault = vault_module
        if sprite_name is not None:
            vault = vault.get_sprite(sprite_name)
        else:
            vault = vault.get_sprites().values()[0]
        return [cls(vault=vault, **kwargs) for count in xrange(0, amount)]

    def add_to(self, node):
        node.add_sprite(self)

    def remove_from_parent(self):
        self._parent_node.remove_sprite(self)

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
  usd: {
    buy: '#ctl00_ContentPlaceHolder1_wucHerramientas1_lblCompraDolar',
    sale: '#ctl00_ContentPlaceHolder1_wucHerramientas1_lblVentaDolar'
  },
  eur: {
    buy: '#ctl00_ContentPlaceHolder1_wucHerramientas1_lblCompraEuro',
    sale: '#ctl00_ContentPlaceHolder1_wucHerramientas1_lblVentaEuro'
  }
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RMUD
{
	[Flags]
	public enum ObjectMatcherSettings
	{
		None = 0,
		UnderstandMe = 1
	}

	public interface IObjectSource
	{
		List<MudObject> GetObjects(PossibleMatch State, MatchContext Context);
	}

    public enum MatchPreference
    {
        VeryUnlikely = -2,
        Unlikely = -1,
        Plausible = 0,
        Likely = 1,
        VeryLikely = 2
    }

    public partial class CommandFactory
    {
        public static CommandTokenMatcher Object(String CaptureName, IObjectSource Source, ObjectMatcherSettings Settings = ObjectMatcherSettings.UnderstandMe)
        {
            return new ObjectMatcher(CaptureName, Source, Settings);
        }

        public static CommandTokenMatcher Object(String CaptureName, IObjectSource Source, Func<Actor, MudObject, MatchPreference> ScoreFunc, ObjectMatcherSettings Settings = ObjectMatcherSettings.UnderstandMe)
        {
            return new ObjectMatcher(CaptureName, Source, ScoreFunc, Settings);
        }

        public static IObjectSource InScope { get { return new InScopeObjectSource(); } }
        public static Func<Actor, MudObject, MatchPreference> PreferHeld { get { return ObjectMatcher.PreferHeld; } }
        public static Func<Actor, MudObject, MatchPreference> PreferWorn { get { return ObjectMatcher.PreferWOrn; } }
    }

    public class ObjectMatcher : CommandTokenMatcher
    {
		public String CaptureName;

		public ObjectMatcherSettings Settings;
		public IObjectSource ObjectSource;
		public Func<Actor, MudObject, MatchPreference> ScoreResults = null;

		public static MatchPreference PreferNotHeld(Actor Actor, MudObject Object)
		{
			if (Actor.Contains(Object, RelativeLocations.Held)) return MatchPreference.Unlikely;
			return MatchPreference.Plausible;
		}

		public static MatchPreference PreferHeld(Actor Actor, MudObject Object)
		{
			if (Actor.Contains(Object, RelativeLocations.Held)) return MatchPreference.Likely;
			return MatchPreference.Plausible;
		}

        public static MatchPreference PreferWOrn(Actor Actor, MudObject Object)
        {
            if (Actor.Contains(Object, RelativeLocations.Worn)) return MatchPreference.Likely;
            return MatchPreference.Plausible;
        }

		public ObjectMatcher(
			String CaptureName,
			IObjectSource ObjectSource,
			ObjectMatcherSettings Settings = ObjectMatcherSettings.UnderstandMe)
		{
			this.CaptureName = CaptureName;
			this.ObjectSource = ObjectSource;
			this.Settings = Settings;
		}

        public ObjectMatcher(
            String CaptureName,
            IObjectSource ObjectSource,
            Func<Actor, MudObject, MatchPreference> ScoreResults,
            ObjectMatcherSettings Settings = ObjectMatcherSettings.UnderstandMe)
        {
            this.CaptureName = CaptureName;
            this.ObjectSource = ObjectSource;
            this.ScoreResults = ScoreResults;
            this.Settings = Settings;
        }

		public List<PossibleMatch> Match(PossibleMatch State, MatchContext Context)
		{
            var useObjectScoring = ScoreResults != null;

			var R = new List<PossibleMatch>();
			if (State.Next == null) return R;

			if ((Settings & ObjectMatcherSettings.UnderstandMe) == ObjectMatcherSettings.UnderstandMe)
			{
				if (State.Next.Value.ToUpper() == "ME")
				{
                    var possibleMatch = State.Advance();
					possibleMatch.Upsert(CaptureName, Context.ExecutingActor);
                    possibleMatch.Upsert(CaptureName + "-SOURCE", "ME");
					R.Add(possibleMatch);
				}
			}

			foreach (var matchableMudObject in ObjectSource.GetObjects(State, Context))
			{
                PossibleMatch possibleMatch = State;
				bool matched = false;
				while (possibleMatch.Next != null && matchableMudObject.Nouns.Match(possibleMatch.Next.Value.ToUpper(), Context.ExecutingActor))
				{
                    if (matched == false) possibleMatch = State.Clone();
					matched = true;
					possibleMatch.Next = possibleMatch.Next.Next;
				}

				if (matched)
				{
					possibleMatch.Upsert(CaptureName, matchableMudObject);

					if (useObjectScoring)
					{
						var score = ScoreResults(Context.ExecutingActor, matchableMudObject);
						possibleMatch.Upsert(CaptureName + "-SCORE", score);

						var insertIndex = 0;
						for (insertIndex = 0; insertIndex < R.Count; ++insertIndex)
						{
							if (score > (R[insertIndex][CaptureName + "-SCORE"] as MatchPreference?).Value) break;
						}

						R.Insert(insertIndex, possibleMatch);
					}
					else
					{
						R.Add(possibleMatch);
					}
				}
			}
			return R;
		}

        public String FindFirstKeyWord() { return null; }
		public String Emit() { return "[OBJECT => '" + CaptureName + "']"; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-integration-tests</artifactId>
		<version>1.4.0.BUILD-SNAPSHOT</version>
	</parent>
	<artifactId>spring-boot-launch-script-tests</artifactId>
	<packaging>jar</packaging>
	<name>Spring Boot Launch Script Integration Tests</name>
	<description>Spring Boot Launch Script Integration Tests</description>
	<url>http://projects.spring.io/spring-boot/</url>
	<organization>
		<name>Pivotal Software, Inc.</name>
		<url>http://www.spring.io</url>
	</organization>
	<properties>
		<main.basedir>${basedir}/../..</main.basedir>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-tomcat</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-undertow</artifactId>
		</dependency>
		<dependency>
			<groupId>com.github.docker-java</groupId>
			<artifactId>docker-java</artifactId>
			<version>2.2.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<profiles>
		<profile>
			<id>docker</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.springframework.boot</groupId>
						<artifactId>spring-boot-maven-plugin</artifactId>
						<configuration>
							<executable>true</executable>
						</configuration>
						<executions>
							<execution>
								<goals>
									<goal>repackage</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-failsafe-plugin</artifactId>
						<executions>
							<execution>
								<goals>
									<goal>integration-test</goal>
									<goal>verify</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Acad. R. Sci. Belg. , Cl. Sci. , sér. 5 18(2): 409 (1851)

#### Original name
Puccinia elymi var. elymi

### Remarks
null


text:
package utils;

import java.util.Random;

import com.google.common.base.Preconditions;

/**
 * This class generates an array of random integers that are useful for testing.
 */
public class RandomStringGenerator {

	private final int size;

	private final int firstAsciCharacter;

	private final int lastAsciCharacter;

	public RandomStringGenerator(int size) {
		this(size, '}', '!');
	}

	public RandomStringGenerator(int size, int lastAsciCharacter) {
		this(size, lastAsciCharacter, '}');
	}

	public RandomStringGenerator(int size, int lastAsciCharacter, int firstAsciCharacter) {
		Preconditions.checkArgument(lastAsciCharacter > firstAsciCharacter,
				"First ASCI character (" + firstAsciCharacter +
						") must be bigger than last (" + lastAsciCharacter
						+ ")");
		Preconditions.checkArgument(firstAsciCharacter >= 0,
				"Last ASCI character must not be negative");
		Preconditions.checkArgument(size >= 0, "Size must not be negative");
		this.size = size;
		this.lastAsciCharacter = lastAsciCharacter;
		this.firstAsciCharacter = firstAsciCharacter;
	}

	public String produceString() {
		char[] data = new char[size];
		for (int i = 0; i < size; i++) {
			int range = lastAsciCharacter - firstAsciCharacter;
			data[i] = (char) (new Random().nextInt(range) + firstAsciCharacter);
		}
		return String.valueOf(data);
	}
}


text:
/*************************************************************************/
/*  physics_server_sw.h                                                  */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef PHYSICS_SERVER_SW
#define PHYSICS_SERVER_SW

#include "joints_sw.h"
#include "servers/physics_server.h"
#include "shape_sw.h"
#include "space_sw.h"
#include "step_sw.h"

class PhysicsServerSW : public PhysicsServer {

	GDCLASS(PhysicsServerSW, PhysicsServer);

	friend class PhysicsDirectSpaceStateSW;
	bool active;
	int iterations;
	bool doing_sync;
	real_t last_step;

	int island_count;
	int active_objects;
	int collision_pairs;

	bool flushing_queries;

	StepSW *stepper;
	Set<const SpaceSW *> active_spaces;

	PhysicsDirectBodyStateSW *direct_state;

	mutable RID_Owner<ShapeSW> shape_owner;
	mutable RID_Owner<SpaceSW> space_owner;
	mutable RID_Owner<AreaSW> area_owner;
	mutable RID_Owner<BodySW> body_owner;
	mutable RID_Owner<JointSW> joint_owner;

	//void _clear_query(QuerySW *p_query);
	friend class CollisionObjectSW;
	SelfList<CollisionObjectSW>::List pending_shape_update_list;
	void _update_shapes();

public:
	static PhysicsServerSW *singleton;

	struct CollCbkData {

		int max;
		int amount;
		Vector3 *ptr;
	};

	static void _shape_col_cbk(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata);

	virtual RID shape_create(ShapeType p_shape);
	virtual void shape_set_data(RID p_shape, const Variant &p_data);
	virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias);

	virtual ShapeType shape_get_type(RID p_shape) const;
	virtual Variant shape_get_data(RID p_shape) const;

	virtual void shape_set_margin(RID p_shape, real_t p_margin);
	virtual real_t shape_get_margin(RID p_shape) const;

	virtual real_t shape_get_custom_solver_bias(RID p_shape) const;

	/* SPACE API */

	virtual RID space_create();
	virtual void space_set_active(RID p_space, bool p_active);
	virtual bool space_is_active(RID p_space) const;

	virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value);
	virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const;

	// this function only works on physics process, errors and returns null otherwise
	virtual PhysicsDirectSpaceState *space_get_direct_state(RID p_space);

	virtual void space_set_debug_contacts(RID p_space, int p_max_contacts);
	virtual Vector<Vector3> space_get_contacts(RID p_space) const;
	virtual int space_get_contact_count(RID p_space) const;

	/* AREA API */

	virtual RID area_create();

	virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode);
	virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const;

	virtual void area_set_space(RID p_area, RID p_space);
	virtual RID area_get_space(RID p_area) const;

	virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false);
	virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape);
	virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform);

	virtual int area_get_shape_count(RID p_area) const;
	virtual RID area_get_shape(RID p_area, int p_shape_idx) const;
	virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const;

	virtual void area_remove_shape(RID p_area, int p_shape_idx);
	virtual void area_clear_shapes(RID p_area);

	virtual void area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled);

	virtual void area_attach_object_instance_id(RID p_area, ObjectID p_ID);
	virtual ObjectID area_get_object_instance_id(RID p_area) const;

	virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value);
	virtual void area_set_transform(RID p_area, const Transform &p_transform);

	virtual Variant area_get_param(RID p_area, AreaParameter p_param) const;
	virtual Transform area_get_transform(RID p_area) const;

	virtual void area_set_ray_pickable(RID p_area, bool p_enable);
	virtual bool area_is_ray_pickable(RID p_area) const;

	virtual void area_set_collision_mask(RID p_area, uint32_t p_mask);
	virtual void area_set_collision_layer(RID p_area, uint32_t p_layer);

	virtual void area_set_monitorable(RID p_area, bool p_monitorable);

	virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method);
	virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method);

	/* BODY API */

	// create a body of a given type
	virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false);

	virtual void body_set_space(RID p_body, RID p_space);
	virtual RID body_get_space(RID p_body) const;

	virtual void body_set_mode(RID p_body, BodyMode p_mode);
	virtual BodyMode body_get_mode(RID p_body) const;

	virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false);
	virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape);
	virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform);

	virtual int body_get_shape_count(RID p_body) const;
	virtual RID body_get_shape(RID p_body, int p_shape_idx) const;
	virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const;

	virtual void body_set_shape_disabled(RID p_body, int p_shape_idx, bool p_disabled);

	virtual void body_remove_shape(RID p_body, int p_shape_idx);
	virtual void body_clear_shapes(RID p_body);

	virtual void body_attach_object_instance_id(RID p_body, uint32_t p_ID);
	virtual uint32_t body_get_object_instance_id(RID p_body) const;

	virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable);
	virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const;

	virtual void body_set_collision_layer(RID p_body, uint32_t p_layer);
	virtual uint32_t body_get_collision_layer(RID p_body) const;

	virtual void body_set_collision_mask(RID p_body, uint32_t p_mask);
	virtual uint32_t body_get_collision_mask(RID p_body) const;

	virtual void body_set_user_flags(RID p_body, uint32_t p_flags);
	virtual uint32_t body_get_user_flags(RID p_body) const;

	virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value);
	virtual real_t body_get_param(RID p_body, BodyParameter p_param) const;

	virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin);
	virtual real_t body_get_kinematic_safe_margin(RID p_body) const;

	virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant);
	virtual Variant body_get_state(RID p_body, BodyState p_state) const;

	virtual void body_set_applied_force(RID p_body, const Vector3 &p_force);
	virtual Vector3 body_get_applied_force(RID p_body) const;

	virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque);
	virtual Vector3 body_get_applied_torque(RID p_body) const;

	virtual void body_add_central_force(RID p_body, const Vector3 &p_force);
	virtual void body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_pos);
	virtual void body_add_torque(RID p_body, const Vector3 &p_torque);

	virtual void body_apply_central_impulse(RID p_body, const Vector3 &p_impulse);
	virtual void body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse);
	virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse);
	virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity);

	virtual void body_set_axis_lock(RID p_body, BodyAxis p_axis, bool p_lock);
	virtual bool body_is_axis_locked(RID p_body, BodyAxis p_axis) const;

	virtual void body_add_collision_exception(RID p_body, RID p_body_b);
	virtual void body_remove_collision_exception(RID p_body, RID p_body_b);
	virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions);

	virtual void body_set_contacts_reported_depth_threshold(RID p_body, real_t p_threshold);
	virtual real_t body_get_contacts_reported_depth_threshold(RID p_body) const;

	virtual void body_set_omit_force_integration(RID p_body, bool p_omit);
	virtual bool body_is_omitting_force_integration(RID p_body) const;

	virtual void body_set_max_contacts_reported(RID p_body, int p_contacts);
	virtual int body_get_max_contacts_reported(RID p_body) const;

	virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant());

	virtual void body_set_ray_pickable(RID p_body, bool p_enable);
	virtual bool body_is_ray_pickable(RID p_body) const;

	virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = NULL, bool p_exclude_raycast_shapes = true);
	virtual int body_test_ray_separation(RID p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, float p_margin = 0.001);

	// this function only works on physics process, errors and returns null otherwise
	virtual PhysicsDirectBodyState *body_get_direct_state(RID p_body);

	/* SOFT BODY */

	virtual RID soft_body_create(bool p_init_sleeping = false) { return RID(); }

	virtual void soft_body_update_visual_server(RID p_body, class SoftBodyVisualServerHandler *p_visual_server_handler) {}

	virtual void soft_body_set_space(RID p_body, RID p_space) {}
	virtual RID soft_body_get_space(RID p_body) const { return RID(); }

	virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer) {}
	virtual uint32_t soft_body_get_collision_layer(RID p_body) const { return 0; }

	virtual void soft_body_set_collision_mask(RID p_body, uint32_t p_mask) {}
	virtual uint32_t soft_body_get_collision_mask(RID p_body) const { return 0; }

	virtual void soft_body_add_collision_exception(RID p_body, RID p_body_b) {}
	virtual void soft_body_remove_collision_exception(RID p_body, RID p_body_b) {}
	virtual void soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) {}

	virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) {}
	virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const { return Variant(); }

	virtual void soft_body_set_transform(RID p_body, const Transform &p_transform) {}
	virtual Vector3 soft_body_get_vertex_position(RID p_body, int vertex_index) const { return Vector3(); }

	virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable) {}
	virtual bool soft_body_is_ray_pickable(RID p_body) const { return false; }

	virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) {}
	virtual int soft_body_get_simulation_precision(RID p_body) { return 0; }

	virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass) {}
	virtual real_t soft_body_get_total_mass(RID p_body) { return 0.; }

	virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) {}
	virtual real_t soft_body_get_linear_stiffness(RID p_body) { return 0.; }

	virtual void soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness) {}
	virtual real_t soft_body_get_areaAngular_stiffness(RID p_body) { return 0.; }

	virtual void soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness) {}
	virtual real_t soft_body_get_volume_stiffness(RID p_body) { return 0.; }

	virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) {}
	virtual real_t soft_body_get_pressure_coefficient(RID p_body) { return 0.; }

	virtual void soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient) {}
	virtual real_t soft_body_get_pose_matching_coefficient(RID p_body) { return 0.; }

	virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) {}
	virtual real_t soft_body_get_damping_coefficient(RID p_body) { return 0.; }

	virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) {}
	virtual real_t soft_body_get_drag_coefficient(RID p_body) { return 0.; }

	virtual void soft_body_set_mesh(RID p_body, const REF &p_mesh) {}

	virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) {}
	virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index) { return Vector3(); }

	virtual Vector3 soft_body_get_point_offset(RID p_body, int p_point_index) const { return Vector3(); }

	virtual void soft_body_remove_all_pinned_points(RID p_body) {}
	virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) {}
	virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index) { return 0; }

	/* JOINT API */

	virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B);

	virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value);
	virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const;

	virtual void pin_joint_set_local_a(RID p_joint, const Vector3 &p_A);
	virtual Vector3 pin_joint_get_local_a(RID p_joint) const;

	virtual void pin_joint_set_local_b(RID p_joint, const Vector3 &p_B);
	virtual Vector3 pin_joint_get_local_b(RID p_joint) const;

	virtual RID joint_create_hinge(RID p_body_A, const Transform &p_frame_A, RID p_body_B, const Transform &p_frame_B);
	virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B);

	virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value);
	virtual real_t hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const;

	virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value);
	virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const;

	virtual RID joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B); //reference frame is A

	virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value);
	virtual real_t slider_joint_get_param(RID p_joint, SliderJointParam p_param) const;

	virtual RID joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B); //reference frame is A

	virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value);
	virtual real_t cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const;

	virtual RID joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B); //reference frame is A

	virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param, real_t p_value);
	virtual real_t generic_6dof_joint_get_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param);

	virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag, bool p_enable);
	virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag);

	virtual void generic_6dof_joint_set_precision(RID p_joint, int precision) {}
	virtual int generic_6dof_joint_get_precision(RID p_joint) { return 0; }

	virtual JointType joint_get_type(RID p_joint) const;

	virtual void joint_set_solver_priority(RID p_joint, int p_priority);
	virtual int joint_get_solver_priority(RID p_joint) const;

	virtual void joint_disable_collisions_between_bodies(RID p_joint, const bool p_disable);
	virtual bool joint_is_disabled_collisions_between_bodies(RID p_joint) const;

	/* MISC */

	virtual void free(RID p_rid);

	virtual void set_active(bool p_active);
	virtual void init();
	virtual void step(real_t p_step);
	virtual void sync();
	virtual void flush_queries();
	virtual void finish();

	virtual bool is_flushing_queries() const { return flushing_queries; }

	int get_process_info(ProcessInfo p_info);

	PhysicsServerSW();
	~PhysicsServerSW();
};

#endif


text:
<html>
<body>
Creates a System.err.println call.
</body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="symfony_application" default="start">
    <property name="root_dir" value="." override="false"/>
    <property name="web_dir" value="../public_html" override="false"/>
    <property name="env" value="dev"/>

    <target name="start" description="Start Release" depends="composer_update,warmup_cache,migrations,create_assets">

    </target>

    <target name="composer_update" description="Installing composer dependencies">
        <composer composer="${root_dir}/composer.phar"  command="self-update" php="php">

        </composer>

        <composer composer="${root_dir}/composer.phar"  command="install" php="php">
            <arg value="--working-dir=${root_dir}"/>
            <arg value="-o"/>
        </composer>
    </target>

    <target name="migrations" description="Applying doctrine migrations">
        <SymfonyConsole console="php ${root_dir}/app/console" command="doctrine:migrations:migrate">

        </SymfonyConsole>
    </target>

    <target name="create_assets" description="Create assets....">
        <SymfonyConsole console="php ${root_dir}/app/console" command="assetic:dump ${web_dir}">
            <arg name="env" value="${env}" />
        </SymfonyConsole>
        <SymfonyConsole console="php ${root_dir}/app/console" command="assets:install ${web_dir}">
            <arg name="env" value="${env}" />
        </SymfonyConsole>
    </target>

    <target name="warmup_cache" description="Warmup cache...">
        <SymfonyConsole console="php ${root_dir}/app/console" command="cache:clear">
            <arg name="env" value="${env}" />
        </SymfonyConsole>
        <SymfonyConsole console="php ${root_dir}/app/console" command="cache:warmup">
            <arg name="env" value="${env}" />
        </SymfonyConsole>
    </target>
</project>


text:
"""
@file
@brief Implements function @see fn run_cmd.
"""
import sys
import os
import pprint
import subprocess
import textwrap
import traceback
import pickle
from multiprocessing import Pool, freeze_support

def execute_script(code, folder=None, filename="_temp_custom_run_script_.py", check=True):
    """
    Executes a :epkg:`python` script in a separate process.

    @param      code        python script
    @param      folder      write the script in a folder then runs it,
                            it None, the function uses a Pool to execute
                            the script
    @param      filename    name of the scrit to write
    @param      check       checks that the output is not empty
    @return                 dictionary with local variables
    """
    addition = textwrap.dedent("""
        loc = locals().copy()
        try:
            data = {'__file__': __file__}
        except NameError:
            data = {}
        import pickle
        for k, v in loc.items():
            if v is None or isinstance(v, (str, int, float, tuple, list, dict, set)):
                try:
                    pickle.dumps(v)
                except Exception:
                    # not pickable
                    continue
                data[k] = v
        __CHECK__
        pkl = pickle.dumps(data)
    """)
    if check:
        checkc = textwrap.dedent("""
        if len(data) == 0:
            import pprint
            raise RuntimeError("data cannot be empty.\\n{}".format(pprint.pformat(loc)))
        """)
    else:
        checkc = ""  # pragma: no cover
    addition = addition.replace("__CHECK__", checkc)
    new_code = "\n".join([code, "", addition])
    if folder is None:
        try:
            obj = compile(new_code, '', 'exec')
        except Exception:
            excs = traceback.format_exc()
            return {'ERROR': excs, 'code': new_code}
        lo = {}
        gl = {}
        try:
            exec(obj, gl, lo)
        except Exception:
            excs = traceback.format_exc()
            return {'ERROR': excs, 'code': new_code}

        pkl = lo['pkl']
        loc = pickle.loads(pkl)
        return loc
    else:
        name = os.path.join(folder, filename)
        data = name + ".pkl"
        new_code = new_code + \
            "\nwith open('{}', 'wb') as f: f.write(pkl)".format(
                data.replace("\\", "/"))
        with open(name, "w", encoding="utf-8") as f:
            f.write(new_code)
        if sys.platform.startswith("win"):
            cmdl = f'{sys.executable} -u "{name}"'
        else:
            cmdl = [sys.executable, '-u', name]
        proc = subprocess.Popen(cmdl, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        _, errs = proc.communicate()
        errs = errs.decode('utf-8', errors="ignore")
        if errs:
            lines = errs.split('\n')
            lines = [
                line for line in lines if "Warning" not in line and line and line[0] != ' ']
            errs2 = "\n".join(lines).strip("\r\n ")
            if errs2:
                return {'ERROR': errs}  # pragma: no cover
        with open(data, "rb") as f:
            loc = pickle.load(f)
        return loc

def execute_script_get_local_variables(script, folder=None,
                                       filename="_temp_custom_run_script_.py",
                                       check=True):
    """
    Executes a script and returns the local variables.

    @param      script      filename or code
    @param      folder      write the script in a folder then runs it,
                            it None, the function uses a Pool to execute
                            the script
    @param      filename    name of the scrit to write
    @param      check       checks that the output is not empty
    @return                 dictionary
    """
    if "\n" not in script and os.path.exists(script):
        with open(script, "r", encoding="utf-8") as f:
            content = f.read()
    else:
        content = script

    if folder is None:
        with Pool(1, None, None, None) as p:
            res = p.map(execute_script, [content])
        if len(res) != 1:
            raise RuntimeError(  # pragma: no cover
                f"Something went wrong with content\n{content}")
        return res[0]
    return execute_script(content, folder, filename, check=check)

def dictionary_as_class(dico):
    """
    Every key of dictionary ``dico`` becomes
    a member of a dummy class.

    @param      dico        dictionary
    @return                 class
    """
    class dummy_class:
        def __init__(self, dico):
            for k, v in dico.items():
                if not isinstance(k, str):
                    raise TypeError(  # pragma: no cover
                        f"Key '{k}' must be a string.")
                setattr(self, k, v)

        def __str__(self):
            data = {k: v for k, v in self.__dict__.items()
                    if not k.startswith("_")}
            return pprint.pformat(data)

        def drop(self, *dr):
            sdr = set(dr)
            data = {k: v for k, v in self.__dict__.items()
                    if not k.startswith("_") and k not in sdr}
            return dummy_class(data)

    du = dummy_class(dico)
    return du

if __name__ == '__main__':  # pragma: no cover
    freeze_support()


text:
<?php

namespace s9e\TextFormatter\Plugins\MediaEmbed\Configurator\TemplateGenerators;

use s9e\TextFormatter\Plugins\MediaEmbed\Configurator\TemplateGenerator;

class Flash extends TemplateGenerator
{
	/**
	* {@inheritdoc}
	*
	* @link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-iframe-element.html#the-object-element
	* @link http://helpx.adobe.com/flash/kb/pass-variables-swfs-flashvars.html
	*/
	protected function getContentTemplate()
	{
		$attributes = [
			'data'          => $this->attributes['src'],
			'style'         => $this->attributes['style'],
			'type'          => 'application/x-shockwave-flash',
			'typemustmatch' => ''
		];

		$flashVarsParam = '';
		if (isset($this->attributes['flashvars']))
		{
			$flashVarsParam = $this->generateParamElement('flashvars', $this->attributes['flashvars']);
		}

		$template = '<object>'
		          . $this->generateAttributes($attributes)
		          . $this->generateParamElement('allowfullscreen', 'true')
		          . $flashVarsParam
		          . '</object>';

		return $template;
	}

	/**
	* Generate a param element to be used inside of an object element
	*
	* @param  string $paramName
	* @param  string $paramValue
	* @return string
	*/
	protected function generateParamElement($paramName, $paramValue)
	{
		return '<param name="' . htmlspecialchars($paramName) . '">' . $this->generateAttributes(['value' => $paramValue]) . '</param>';
	}
}


text:
/* See LICENSE for licensing information */

/**
 * \file test_mainloop.c
 * \brief Tests for functions closely related to the Tor main loop
 */

#define CONFIG_PRIVATE
#define MAINLOOP_PRIVATE
#define STATEFILE_PRIVATE

#include "test/test.h"
#include "test/log_test_helpers.h"

#include "lib/confmgt/confmgt.h"

#include "core/or/or.h"
#include "core/mainloop/connection.h"
#include "core/mainloop/mainloop.h"
#include "core/mainloop/mainloop_state_st.h"
#include "core/mainloop/mainloop_sys.h"
#include "core/mainloop/netstatus.h"

#include "feature/hs/hs_service.h"

#include "app/config/config.h"
#include "app/config/statefile.h"
#include "app/config/or_state_st.h"

#include "app/main/subsysmgr.h"

static const uint64_t BILLION = 1000000000;

static void
test_mainloop_update_time_normal(void *arg)
{
  (void)arg;

  monotime_enable_test_mocking();
  /* This is arbitrary */
  uint64_t mt_now = UINT64_C(7493289274986);
  /* This time is in the past as of when this test was written. */
  time_t now = 1525272090;
  monotime_coarse_set_mock_time_nsec(mt_now);
  reset_uptime();
  update_current_time(now);
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 0);

  update_current_time(now); // Same time as before is a no-op.
  tt_int_op(get_uptime(), OP_EQ, 0);

  now += 1;
  mt_now += BILLION;
  monotime_coarse_set_mock_time_nsec(mt_now);
  update_current_time(now);
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 1);

  now += 2; // two-second jump is unremarkable.
  mt_now += 2*BILLION;
  update_current_time(now);
  monotime_coarse_set_mock_time_nsec(mt_now);
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 3);

  now -= 1; // a one-second hop backwards is also unremarkable.
  update_current_time(now);
  tt_int_op(approx_time(), OP_EQ, now); // it changes the approx time...
  tt_int_op(get_uptime(), OP_EQ, 3); // but it doesn't roll back our uptime

 done:
  monotime_disable_test_mocking();
}

static void
test_mainloop_update_time_jumps(void *arg)
{
  (void)arg;

  monotime_enable_test_mocking();
  /* This is arbitrary */
  uint64_t mt_now = UINT64_C(7493289274986);
  /* This time is in the past as of when this test was written. */
  time_t now = 220897152;
  monotime_coarse_set_mock_time_nsec(mt_now);
  reset_uptime();
  update_current_time(now);
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 0);

  /* Put some uptime on the clock.. */
  now += 3;
  mt_now += 3*BILLION;
  monotime_coarse_set_mock_time_nsec(mt_now);
  update_current_time(now);
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 3);

  /* Now try jumping forward and backward, without updating the monotonic
   * clock.  */
  setup_capture_of_logs(LOG_NOTICE);
  now += 1800;
  update_current_time(now);
  expect_single_log_msg_containing(
               "Your system clock just jumped 1800 seconds forward");
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 3); // no uptime change.
  mock_clean_saved_logs();

  now -= 600;
  update_current_time(now);
  expect_single_log_msg_containing(
               "Your system clock just jumped 600 seconds backward");
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 3); // no uptime change.
  mock_clean_saved_logs();

  /* uptime tracking should go normally now if the clock moves sensibly. */
  now += 2;
  mt_now += 2*BILLION;
  update_current_time(now);
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 5);

  /* If we skip forward by a few minutes but the monotonic clock agrees,
   * we've just been idle: that counts as not worth warning about. */
  now += 1800;
  mt_now += 1800*BILLION;
  monotime_coarse_set_mock_time_nsec(mt_now);
  update_current_time(now);
  expect_no_log_entry();
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 5); // this doesn't count to uptime, though.

  /* If we skip forward by a long time, even if the clock agrees, it's
   * idnless that counts. */
  now += 4000;
  mt_now += 4000*BILLION;
  monotime_coarse_set_mock_time_nsec(mt_now);
  update_current_time(now);
  expect_single_log_msg_containing("Tor has been idle for 4000 seconds");
  tt_int_op(approx_time(), OP_EQ, now);
  tt_int_op(get_uptime(), OP_EQ, 5);

 done:
  teardown_capture_of_logs();
  monotime_disable_test_mocking();
}

static int schedule_rescan_called = 0;
static void
mock_schedule_rescan_periodic_events(void)
{
  ++schedule_rescan_called;
}

static void
test_mainloop_user_activity(void *arg)
{
  (void)arg;
  const time_t start = 1542658829;
  update_approx_time(start);

  MOCK(schedule_rescan_periodic_events, mock_schedule_rescan_periodic_events);

  reset_user_activity(start);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start);

  set_network_participation(false);

  // reset can move backwards and forwards, but does not change network
  // participation.
  reset_user_activity(start-10);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start-10);
  reset_user_activity(start+10);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+10);

  tt_int_op(schedule_rescan_called, OP_EQ, 0);
  tt_int_op(false, OP_EQ, is_participating_on_network());

  // "note" can only move forward.  Calling it from a non-participating
  // state makes us rescan the periodic callbacks and set participation.
  note_user_activity(start+20);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+20);
  tt_int_op(true, OP_EQ, is_participating_on_network());
  tt_int_op(schedule_rescan_called, OP_EQ, 1);

  // Calling it again will move us forward, but not call rescan again.
  note_user_activity(start+25);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+25);
  tt_int_op(true, OP_EQ, is_participating_on_network());
  tt_int_op(schedule_rescan_called, OP_EQ, 1);

  // We won't move backwards.
  note_user_activity(start+20);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+25);
  tt_int_op(true, OP_EQ, is_participating_on_network());
  tt_int_op(schedule_rescan_called, OP_EQ, 1);

  // We _will_ adjust if the clock jumps though.
  netstatus_note_clock_jumped(500);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+525);

  netstatus_note_clock_jumped(-400);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+125);

 done:
  UNMOCK(schedule_rescan_periodic_events);
}

static unsigned int
mock_get_num_services(void)
{
  return 1;
}

static connection_t *
mock_connection_gbtu(int type)
{
  (void) type;
  return (void *)"hello fellow connections";
}

static void
test_mainloop_check_participation(void *arg)
{
  (void)arg;
  or_options_t *options = options_new();
  const time_t start = 1542658829;
  const time_t ONE_DAY = 24*60*60;

  // Suppose we've been idle for a day or two
  reset_user_activity(start - 2*ONE_DAY);
  set_network_participation(true);
  check_network_participation_callback(start, options);
  tt_int_op(is_participating_on_network(), OP_EQ, false);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start-2*ONE_DAY);

  // suppose we've been idle for 2 days... but we are a server.
  reset_user_activity(start - 2*ONE_DAY);
  options->ORPort_set = 1;
  set_network_participation(true);
  check_network_participation_callback(start+2, options);
  tt_int_op(is_participating_on_network(), OP_EQ, true);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+2);
  options->ORPort_set = 0;

  // idle for 2 days, but we have a hidden service.
  reset_user_activity(start - 2*ONE_DAY);
  set_network_participation(true);
  MOCK(hs_service_get_num_services, mock_get_num_services);
  check_network_participation_callback(start+3, options);
  tt_int_op(is_participating_on_network(), OP_EQ, true);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+3);
  UNMOCK(hs_service_get_num_services);

  // idle for 2 days but we have at least one user connection
  MOCK(connection_get_by_type_nonlinked, mock_connection_gbtu);
  reset_user_activity(start - 2*ONE_DAY);
  set_network_participation(true);
  options->DormantTimeoutDisabledByIdleStreams = 1;
  check_network_participation_callback(start+10, options);
  tt_int_op(is_participating_on_network(), OP_EQ, true);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start+10);

  // as above, but DormantTimeoutDisabledByIdleStreams is not set
  reset_user_activity(start - 2*ONE_DAY);
  set_network_participation(true);
  options->DormantTimeoutDisabledByIdleStreams = 0;
  check_network_participation_callback(start+13, options);
  tt_int_op(is_participating_on_network(), OP_EQ, false);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start-2*ONE_DAY);
  UNMOCK(connection_get_by_type_nonlinked);
  options->DormantTimeoutDisabledByIdleStreams = 1;

  // idle for 2 days but DormantClientTimeout is 3 days
  reset_user_activity(start - 2*ONE_DAY);
  set_network_participation(true);
  options->DormantClientTimeout = ONE_DAY * 3;
  check_network_participation_callback(start+30, options);
  tt_int_op(is_participating_on_network(), OP_EQ, true);
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start-2*ONE_DAY);

 done:
  or_options_free(options);
  UNMOCK(hs_service_get_num_services);
  UNMOCK(connection_get_by_type_nonlinked);
}

static void
test_mainloop_dormant_load_state(void *arg)
{
  (void)arg;
  or_state_t *or_state = or_state_new();
  mainloop_state_t *state;
  {
    int idx = subsystems_get_state_idx(&sys_mainloop);
    tor_assert(idx >= 0);
    state = config_mgr_get_obj_mutable(get_state_mgr(), or_state, idx);
  }
  const time_t start = 1543956575;

  reset_user_activity(0);
  set_network_participation(false);

  // When we construct a new state, it starts out in "auto" mode.
  tt_int_op(state->Dormant, OP_EQ, -1);

  // Initializing from "auto" makes us start out (by default) non-Dormant,
  // with activity right now.
  netstatus_load_from_state(state, start);
  tt_assert(is_participating_on_network());
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start);

  // Initializing from dormant clears the last user activity time, and
  // makes us dormant.
  state->Dormant = 1;
  netstatus_load_from_state(state, start);
  tt_assert(! is_participating_on_network());
  tt_i64_op(get_last_user_activity_time(), OP_EQ, 0);

  // Initializing from non-dormant sets the last user activity time, and
  // makes us non-dormant.
  state->Dormant = 0;
  state->MinutesSinceUserActivity = 123;
  netstatus_load_from_state(state, start);
  tt_assert(is_participating_on_network());
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start - 123*60);

  // If we would start dormant, but DormantCanceledByStartup is set, then
  // we start up non-dormant.
  state->Dormant = 1;
  get_options_mutable()->DormantCanceledByStartup = 1;
  netstatus_load_from_state(state, start);
  tt_assert(is_participating_on_network());
  tt_i64_op(get_last_user_activity_time(), OP_EQ, start);

 done:
  or_state_free(or_state);
}

static void
test_mainloop_dormant_save_state(void *arg)
{
  (void)arg;
  mainloop_state_t *state = tor_malloc_zero(sizeof(mainloop_state_t));
  const time_t start = 1543956575;

  // Can we save a non-dormant state correctly?
  reset_user_activity(start - 1000);
  set_network_participation(true);
  netstatus_flush_to_state(state, start);

  tt_int_op(state->Dormant, OP_EQ, 0);
  tt_int_op(state->MinutesSinceUserActivity, OP_EQ, 1000 / 60);

  // Can we save a dormant state correctly?
  set_network_participation(false);
  netstatus_flush_to_state(state, start);

  tt_int_op(state->Dormant, OP_EQ, 1);
  tt_int_op(state->MinutesSinceUserActivity, OP_EQ, 0);

 done:
  tor_free(state);
}

#define MAINLOOP_TEST(name) \
  { #name, test_mainloop_## name , TT_FORK, NULL, NULL }

struct testcase_t mainloop_tests[] = {
  MAINLOOP_TEST(update_time_normal),
  MAINLOOP_TEST(update_time_jumps),
  MAINLOOP_TEST(user_activity),
  MAINLOOP_TEST(check_participation),
  MAINLOOP_TEST(dormant_load_state),
  MAINLOOP_TEST(dormant_save_state),
  END_OF_TESTCASES
};


text:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-application-header',
  templateUrl: './application-header.component.html',
  styleUrls: ['./application-header.component.scss'],
})
export class ApplicationHeaderComponent {
  @Input() title: string;

  constructor() {}
}


text: Why doesn't C# have a decent NuGet implementation of https://www.npmjs.com/package/striptags ?


text:
package com.prodyna.pmu.cpa.ejb.impl;

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

import javax.ejb.Local;
import javax.ejb.Stateless;

import org.mongodb.morphia.Datastore;

import com.prodyna.pmu.cpa.domain.Conference;
import com.prodyna.pmu.cpa.ejb.ConferenceServiceBean;
import com.prodyna.pmu.cpa.ejb.domain.ConferenceEntity;

/**
 * EJB service bean implementation of the {@link ConferenceServiceBean} interface.
 *
 * @author pmueller@prodyna.com
 */
@Local @Stateless
public class ConferenceServiceImpl extends AbstractServiceBeanImpl.Listable<Conference, ConferenceEntity>
		implements ConferenceServiceBean {

	private ConferenceEntity create(String name, String description, Date beginDate, Date endDate) {
		ConferenceEntity result = new ConferenceEntity();
		result.setName(name);
		result.setDescription(description);
		result.setBeginDate(beginDate);
		result.setEndDate(endDate);
		return result;
	}

	/**
	 * {@inheritDoc}
	 */
  @Override
  public Iterable<Conference> list() {
  	Datastore ds = getDatastore();
  	if (ds.find(getEntityClass()).countAll() == 0) {
  		// TODO Remove
  		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  		try {
  		ds.save(Arrays.asList(
  				create("Test 1", "Description 1", f.parse("2013-01-01 00:00:00"), f.parse("2013-01-03 00:00:00")),
  				create("Test 2", "Description 2", f.parse("2013-02-01 00:00:00"), f.parse("2013-02-03 00:00:00")),
  				create("Test 3", "Description 3", f.parse("2013-03-01 00:00:00"), f.parse("2013-03-03 00:00:00")),
  				create("Test 4", "Description 4", f.parse("2013-04-01 00:00:00"), f.parse("2013-04-03 00:00:00"))
  		));
  		}
  		catch (ParseException e) {
  			// Ignore
  		}
  	}

	  return super.list();
  }

	/**
	 * {@inheritDoc}
	 */
  @Override
  protected Class<Conference> getTransferClass() {
	  return Conference.class;
  }

	/**
	 * {@inheritDoc}
	 */
  @Override
  protected Class<ConferenceEntity> getEntityClass() {
	  return ConferenceEntity.class;
  }
}


text:
"use strict";

exports.__esModule = true;
exports.default = _default;

var helpers = _interopRequireWildcard(require("@babel/helpers"));

var _generator = _interopRequireDefault(require("@babel/generator"));

var _template = _interopRequireDefault(require("@babel/template"));

var t = _interopRequireWildcard(require("@babel/types"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

var buildUmdWrapper = (0, _template.default)("\n  (function (root, factory) {\n    if (typeof define === \"function\" && define.amd) {\n      define(AMD_ARGUMENTS, factory);\n    } else if (typeof exports === \"object\") {\n      factory(COMMON_ARGUMENTS);\n    } else {\n      factory(BROWSER_ARGUMENTS);\n    }\n  })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n    FACTORY_BODY\n  });\n");

function buildGlobal(whitelist) {
  var namespace = t.identifier("babelHelpers");
  var body = [];
  var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
  var tree = t.program([t.expressionStatement(t.callExpression(container, [t.conditionalExpression(t.binaryExpression("===", t.unaryExpression("typeof", t.identifier("global")), t.stringLiteral("undefined")), t.identifier("self"), t.identifier("global"))]))]);
  body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))]));
  buildHelpers(body, namespace, whitelist);
  return tree;
}

function buildModule(whitelist) {
  var body = [];
  var refs = buildHelpers(body, null, whitelist);
  body.unshift(t.exportNamedDeclaration(null, Object.keys(refs).map(function (name) {
    return t.exportSpecifier(t.cloneNode(refs[name]), t.identifier(name));
  })));
  return t.program(body, [], "module");
}

function buildUmd(whitelist) {
  var namespace = t.identifier("babelHelpers");
  var body = [];
  body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))]));
  buildHelpers(body, namespace, whitelist);
  return t.program([buildUmdWrapper({
    FACTORY_PARAMETERS: t.identifier("global"),
    BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])),
    COMMON_ARGUMENTS: t.identifier("exports"),
    AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
    FACTORY_BODY: body,
    UMD_ROOT: t.identifier("this")
  })]);
}

function buildVar(whitelist) {
  var namespace = t.identifier("babelHelpers");
  var body = [];
  body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))]));
  var tree = t.program(body);
  buildHelpers(body, namespace, whitelist);
  body.push(t.expressionStatement(namespace));
  return tree;
}

function buildHelpers(body, namespace, whitelist) {
  var getHelperReference = function getHelperReference(name) {
    return namespace ? t.memberExpression(namespace, t.identifier(name)) : t.identifier("_" + name);
  };

  var refs = {};
  helpers.list.forEach(function (name) {
    if (whitelist && whitelist.indexOf(name) < 0) return;
    var ref = refs[name] = getHelperReference(name);

    var _helpers$get = helpers.get(name, getHelperReference, ref),
        nodes = _helpers$get.nodes;

    body.push.apply(body, nodes);
  });
  return refs;
}

function _default(whitelist, outputType) {
  if (outputType === void 0) {
    outputType = "global";
  }

  var tree;
  var build = {
    global: buildGlobal,
    module: buildModule,
    umd: buildUmd,
    var: buildVar
  }[outputType];

  if (build) {
    tree = build(whitelist);
  } else {
    throw new Error("Unsupported output type " + outputType);
  }

  return (0, _generator.default)(tree).code;
}


text:
<?php

namespace NilPortugues\SchemaOrg\Properties;

use NilPortugues\SchemaOrg\SchemaProperty;

/**
 * How often one should break from the activity.
 */
class RestPeriodsProperty extends SchemaProperty
{
    const SCHEMA_URL = 'http://schema.org/restPeriods';
    const PROPERTY_NAME = 'restPeriods';

    /**
     * A list of schemas allowed to use this property.
     *
     * @var array
     */
    protected static $allowedSchemas = [
        'http://schema.org/ExercisePlan',
    ];
}


text:
{% extends "layout.html" %}
{% block title %}资产管理{% endblock %}
{% block link %}
    <link href="{{ url_for('static', filename='bootstrap-slider/css/bootstrap-slider.min.css') }}" rel="stylesheet"/>
    <link href="{{ url_for('static', filename='bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css') }}"
          rel="stylesheet"/>
    <link href="{{ url_for('static', filename='sweetalert-1.1.1/dist/sweetalert.css') }}" rel="stylesheet"/>
    <link href="{{ url_for('static', filename='DataTables-1.10.12/media/css/jquery.dataTables.min.css') }}"
          rel="stylesheet"/>

{% endblock %}
{% block nav_asset %}active{% endblock %}
{% block main %}
    <button type="button" class="btn btn-default" data-toggle="modal" data-target="#dialog" data-title="添加资产"
            data-btn-txt="添加" data-url='/asset/create/'>添加资产
    </button>

            SN
            IP(主机名)
            操作系统
            CPU/内存/硬盘
            机房
            使用者(业务)
            采购时间(保修时长)
            型号(供应商)
            操作

        {% for asset in assets %}

                {{ asset['sn'] }}
                {{ asset['ipaddr'] }}({{ asset['hostname'] }})
                {{ asset['os'] }}
                {{ asset['cpu'] }}核/{{ asset['ram'] }}G/{{ asset['disk'] }}G
                {{ idcs.get( asset['idc_id'] ) }}
                {{ asset['admin'] }}({{ asset['business'] }})
                {{ asset['purchase_date'] }}({{ asset['warranty_date'] }}年)
                {{ asset['model'] }}({{ asset['vendor'] }})

                    <button type="button" class="btn btn-xs btn-primary" data-toggle="modal" data-target="#dialog"
                            data-title="修改资产" data-btn-txt="修改"
                            data-url="/asset/modify/?asset_id={{ asset['asset_id'] }}">修改
                    </button>
                    删除

        {% endfor %}

{% endblock %}
{% block dialog %}

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

修改用户

                    新建资产

                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary btn-form-submit">更新</button>

{% endblock %}
{% block script %}

{% endblock %}

{% block js %}

    jQuery(document).ready(function() {
    jQuery('table').DataTable({
    language: {
    "sProcessing": "处理中...",
    "sLengthMenu": "显示 _MENU_ 项结果",
    "sZeroRecords": "没有匹配结果",
    "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
    "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
    "sInfoPostFix": "",
    "sSearch": "搜索:",
    "sUrl": "",
    "sEmptyTable": "表中数据为空",
    "sLoadingRecords": "载入中...",
    "sInfoThousands": ",",
    "oPaginate": {
    "sFirst": "首页",
    "sPrevious": "上页",
    "sNext": "下页",
    "sLast": "末页"
    },
    "oAria": {
    "sSortAscending": ": 以升序排列此列",
    "sSortDescending": ": 以降序排列此列"
    }
    }
    });

    swal({   title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!",
    cancelButtonText:"No, cancel plx!",
    closeOnConfirm: false,   closeOnCancel: false },
    function(isConfirm){   if (isConfirm) {
    swal("Deleted!", "Your imaginary file has been deleted.", "success");   }
    else {     swal("Cancelled", "Your
    imaginary file is safe :)", "error");   } });

    jQuery('#dialog').on('show.bs.modal', function (event) {
    if(!event.relatedTarget) {return;}
    var button = jQuery(event.relatedTarget);
    var title = button.data('title');
    var btn_txt = button.data('btn-txt');
    var url = button.data('url');
    var that = this;
    jQuery(that).find('.modal-title').text(title);
    jQuery(that).find('.btn-form-submit').text(btn_txt);
    jQuery(that).find('.modal-body').load(url);
    /*jQuery.get(url, {}, function(result) {
    jQuery(that).find('.modal-body').html(result);
    });
    */
    });

    jQuery('.btn-form-submit').on('click', function() {
    var _form = jQuery('#dialog').find('form');
    jQuery.post(_form.attr('action'), _form.serializeArray(), function(result) {
    if(result['is_ok']) {
    if(result['success']) {
    alert(result['success']);
    }
    window.location.reload();
    } else {
    var errors = [];
    for(var key in result['errors']) {
    errors.push(result['errors'][key]);
    }
    // alert(errors.join('\n'));

    swal({
    title: "错误信息",
    text: errors.join('\n'),
    type: "Error",
    showCancelButton: false,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "确定",
    cancelButtonText:"关闭",
    closeOnConfirm: false,
    closeOnCancel: false },
    function(isConfirm){
    if (isConfirm) {});
    }
    }, 'json')
    });
    });
{% endblock %}