text:
void resourcemanager::deleteResource(std::string filename)
{
	std::cout << "deleting resource: " << filename << std::endl;
	delete resourceList.find(filename)->second; // delete the object
	resourceList.erase(filename); // remove it from the list
}

void resourcemanager::clearResources()
{
	std::cout << "deleting resources" << std::endl;
	for (std::map<std::string, resource *>::iterator resourceList_iter = resourceList.begin(); resourceList_iter != resourceList.end(); ++resourceList_iter)
	{
		// loop through the list
		std::cout << "deleting: " << resourceList_iter->first << std::endl;
		delete resourceList_iter->second; // delete the object
	}
	resourceList.clear(); // clear the list
}

redpajama_set_name: RedPajamaGithub


text:
Epitech
=======

Some projects made during my studies at Epitech


text:
package org.apache.flink.table.planner.plan.nodes.physical

import org.apache.flink.api.common.io.InputFormat
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.dag.Transformation
import org.apache.flink.core.io.InputSplit
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment
import org.apache.flink.table.planner.plan.schema.TableSourceTable
import org.apache.flink.table.runtime.types.TypeInfoDataTypeConverter.fromDataTypeToTypeInfo
import org.apache.flink.table.sources.{InputFormatTableSource, StreamTableSource, TableSource}

import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel.RelWriter
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.TableScan

import scala.collection.JavaConverters._

/**
  * Base physical RelNode to read data from an external source defined by a [[TableSource]].
  */
abstract class PhysicalTableSourceScan(
    cluster: RelOptCluster,
    traitSet: RelTraitSet,
    relOptTable: TableSourceTable[_])
  extends TableScan(cluster, traitSet, relOptTable) {

  // cache table source transformation.
  protected var sourceTransform: Transformation[_] = _

  protected val tableSourceTable: TableSourceTable[_] =
    relOptTable.unwrap(classOf[TableSourceTable[_]])

  protected[flink] val tableSource: TableSource[_] = tableSourceTable.tableSource

  override def deriveRowType(): RelDataType = {
    // TableScan row type should always keep same with its
    // interval RelOptTable's row type.
    relOptTable.getRowType
  }

  override def explainTerms(pw: RelWriter): RelWriter = {
    super.explainTerms(pw)
      .item("fields", getRowType.getFieldNames.asScala.mkString(", "))
  }

  def createInput[IN](
      env: StreamExecutionEnvironment,
      format: InputFormat[IN, _ <: InputSplit],
      t: TypeInformation[IN]): Transformation[IN]

  def getSourceTransformation(env: StreamExecutionEnvironment): Transformation[_] = {
    if (sourceTransform == null) {
      sourceTransform = tableSource match {
        case format: InputFormatTableSource[_] =>
          // we don't use InputFormatTableSource.getDataStream, because in here we use planner
          // type conversion to support precision of Varchar and something else.
          val typeInfo = fromDataTypeToTypeInfo(format.getProducedDataType)
              .asInstanceOf[TypeInformation[Any]]
          createInput(
            env,
            format.getInputFormat.asInstanceOf[InputFormat[Any, _ <: InputSplit]],
            typeInfo.asInstanceOf[TypeInformation[Any]])
        case s: StreamTableSource[_] => s.getDataStream(env).getTransformation
      }
    }
    sourceTransform
  }
}


text:
package alt.beanmapper.compile.converter;

import alt.beanmapper.compile.MapperClassCompiler;
import alt.beanmapper.compile.options.PropertyOptions;
import alt.beanmapper.compile.property.PropertyAccessor;
import alt.beanmapper.converter.Converter;
import alt.beanmapper.converter.DummyConverter;

/**
 *
 * @author Albert Shift
 *
 */
public final class PropertyConverterFactory {

	private final MapperClassCompiler mapperClassCompiler;

	public PropertyConverterFactory(MapperClassCompiler mapperClassCompiler) {
		this.mapperClassCompiler = mapperClassCompiler;
	}

	public PropertyConverter createPropertyConverter(PropertyAccessor srcPropertyAccessor,
			PropertyAccessor destPropertyAccessor, PropertyOptions propertyOptions) {
		if (srcPropertyAccessor.getPropertyClass().isArray() && destPropertyAccessor.getPropertyClass().isArray()) {
			return new ArrayToArrayPropertyConverter(srcPropertyAccessor, destPropertyAccessor);
		}
		if (srcPropertyAccessor.getPropertyClass() != destPropertyAccessor.getPropertyClass()) {

			Class<? extends Converter<?, ?>> converterClass = propertyOptions.getConverterClass();

			if (converterClass != null && converterClass != DummyConverter.class) {
				return new CustomObjectToObjectPropertyConverter(mapperClassCompiler, srcPropertyAccessor,
						destPropertyAccessor, converterClass);
			} else {
				return new ObjectToObjectPropertyConverter(srcPropertyAccessor, destPropertyAccessor,
						propertyOptions.getTypeCastStrategy());
			}

		}
		return null;
	}

}


text:
TODO
====

* [ ] Fix Ubuntu `15.04` support in the `postfix-full` cookbook.
* [ ] Add ChefSpec tests to check attribute values.
* [ ] [DSPAM](http://dspam.nuclearelephant.com/) support.
* [ ] [ClamAV](http://www.clamav.net/) support.
* [ ] Webmail.
* [ ] Spam learning.


text: google-site-verification: googledb04b13a9e55b15d.html


text:
import React from 'react';
import LoginPage from './Components/Login/LoginPage';
import ChatPage from './Components/Chat/ChatPage';
import ChatServerActionCreators from './Actions/ChatServerActionCreators';
import ChatMessageActionCreators from './Actions/ChatMessageActionCreators';
import ws from './Utils/SimpleWebSocket';

function _checkServerStatus() {
    this.status = null;

    ws.on('open', () => {
        this.status = true;

        ChatServerActionCreators.receiveServerStatus({status: this.status});
    });

    // Catch disconnect
    setTimeout(() => {
        if (this.status === null || this.status === false) {
            this.status = false;

            ChatServerActionCreators.receiveServerStatus({status: false});
        }
    }, 2000);
}

ws.on('message', (event) => {
    let result = JSON.parse(event.data);

    if(result.type === 'presence') {
        ChatServerActionCreators.receiveUsers(result);
    } else if (result.type === 'message') {
        ChatServerActionCreators.receiveMessages(result);
    }
});

_checkServerStatus();

class Application extends React.Component {
    constructor(props) {
        super(props);

        this.state = {};
    }

    componentWillMount() {
        this.state.currentPage = <LoginPage handleLogin={this._handleLogin.bind(this)} onChangePage={this._handleChangePage} onRefresh={this._handleRefreshStatus.bind(this)} />;
    }

    componentDidMount() {
        ipc.send('application-mounted');
    }

    render() {
        return (

Electron versie is {process.versions['electron']}

                {this.state.currentPage}

        );
    }

    _handleLogin(login) {
        ChatMessageActionCreators.getUsername(login);

        ws.send(JSON.stringify({type: 'presence', message: login}), (error) => {
            console.log(error);
        });

        // Electron does not use URL's so can't use a proper router
        this.setState({
            currentPage: <ChatPage handleSendMessage={this._handleSendMessage.bind(this)} />
        });
    }

    _handleSendMessage(data) {
        ws.send(JSON.stringify({type: 'message', message: data}), (error) => {
            console.log(error);
        });
    }

    _handleRefreshStatus() {
        _checkServerStatus();
    }
};

React.render(<Application />, document.body);


text:
using namespace acmacs::argv;

struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    option<bool> verbose{*this, 'v'};

    argument<str> filename{*this, arg_name{"file.json"}, mandatory};
    argument<str> name{*this, arg_name{"name-to-apply"}, mandatory};
};

int main(int argc, char* argv[])
{
    Options opt(argc, argv);
    if (opt.verbose)
        acmacs::log::enable(acmacs::log::settings);

    acmacs::settings::v3::TestData data;
    data.load(opt.filename);
    data.apply(opt.name);

    return 0;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:


text:
package api

func ReportData(itemId string) (map[string]interface{}, error) {
	p := map[string]interface{}{
		"itemId":     itemId, // required for platform versions < 2.14
		"treenodeId": itemId, // required for platform versions >= 2.14
	}
	v, err := sendRequest("KeenEye.GetReportData", p)
	if err != nil {
		return nil, err
	}
	return v.(map[string]interface{}), nil
}


text:
{% include 'header.html' %}
		<h1> Bienvenue  </h1>
		<form class="pure-form" action="{{routing}}" method="post">
			<fieldset>
				<label for="password">Entrer votre mot de passe :</label>
				<input class="pure-input-1-2" type="password" name="password"/>
				<input class="pure-button pure-button-primary" type="submit">
			</fieldset>
		</form>
{% include 'footer.html' %}


text:
ActionController::Routing::Routes.draw do |map|
  map.test '/test', :controller => 'test', :action => 'test'
  Mephisto::Routing.connect_with map

end


text:
package wire

import (
	"context"
	"errors"
	"fmt"
	"go/ast"
	"go/token"
	"go/types"
	"os"
	"reflect"
	"strconv"
	"strings"

	"golang.org/x/tools/go/ast/astutil"
	"golang.org/x/tools/go/packages"
	"golang.org/x/tools/go/types/typeutil"
)

// A providerSetSrc captures the source for a type provided by a ProviderSet.
// Exactly one of the fields will be set.
type providerSetSrc struct {
	Provider    *Provider
	Binding     *IfaceBinding
	Value       *Value
	Import      *ProviderSet
	InjectorArg *InjectorArg
	Field       *Field
}

// description returns a string describing the source of p, including line numbers.
func (p *providerSetSrc) description(fset *token.FileSet, typ types.Type) string {
	quoted := func(s string) string {
		if s == "" {
			return ""
		}
		return fmt.Sprintf("%q ", s)
	}
	switch {
	case p.Provider != nil:
		kind := "provider"
		if p.Provider.IsStruct {
			kind = "struct provider"
		}
		return fmt.Sprintf("%s %s(%s)", kind, quoted(p.Provider.Name), fset.Position(p.Provider.Pos))
	case p.Binding != nil:
		return fmt.Sprintf("wire.Bind (%s)", fset.Position(p.Binding.Pos))
	case p.Value != nil:
		return fmt.Sprintf("wire.Value (%s)", fset.Position(p.Value.Pos))
	case p.Import != nil:
		return fmt.Sprintf("provider set %s(%s)", quoted(p.Import.VarName), fset.Position(p.Import.Pos))
	case p.InjectorArg != nil:
		args := p.InjectorArg.Args
		return fmt.Sprintf("argument %s to injector function %s (%s)", args.Tuple.At(p.InjectorArg.Index).Name(), args.Name, fset.Position(args.Pos))
	case p.Field != nil:
		return fmt.Sprintf("wire.FieldsOf (%s)", fset.Position(p.Field.Pos))
	}
	panic("providerSetSrc with no fields set")
}

// trace returns a slice of strings describing the (possibly recursive) source
// of p, including line numbers.
func (p *providerSetSrc) trace(fset *token.FileSet, typ types.Type) []string {
	var retval []string
	// Only Imports need recursion.
	if p.Import != nil {
		if parent := p.Import.srcMap.At(typ); parent != nil {
			retval = append(retval, parent.(*providerSetSrc).trace(fset, typ)...)
		}
	}
	retval = append(retval, p.description(fset, typ))
	return retval
}

// A ProviderSet describes a set of providers.  The zero value is an empty
// ProviderSet.
type ProviderSet struct {
	// Pos is the position of the call to wire.NewSet or wire.Build that
	// created the set.
	Pos token.Pos
	// PkgPath is the import path of the package that declared this set.
	PkgPath string
	// VarName is the variable name of the set, if it came from a package
	// variable.
	VarName string

	Providers []*Provider
	Bindings  []*IfaceBinding
	Values    []*Value
	Fields    []*Field
	Imports   []*ProviderSet
	// InjectorArgs is only filled in for wire.Build.
	InjectorArgs *InjectorArgs

	// providerMap maps from provided type to a *ProvidedType.
	// It includes all of the imported types.
	providerMap *typeutil.Map

	// srcMap maps from provided type to a *providerSetSrc capturing the
	// Provider, Binding, Value, or Import that provided the type.
	srcMap *typeutil.Map
}

// Outputs returns a new slice containing the set of possible types the
// provider set can produce. The order is unspecified.
func (set *ProviderSet) Outputs() []types.Type {
	return set.providerMap.Keys()
}

// For returns a ProvidedType for the given type, or the zero ProvidedType.
func (set *ProviderSet) For(t types.Type) ProvidedType {
	pt := set.providerMap.At(t)
	if pt == nil {
		return ProvidedType{}
	}
	return *pt.(*ProvidedType)
}

// An IfaceBinding declares that a type should be used to satisfy inputs
// of the given interface type.
type IfaceBinding struct {
	// Iface is the interface type, which is what can be injected.
	Iface types.Type

	// Provided is always a type that is assignable to Iface.
	Provided types.Type

	// Pos is the position where the binding was declared.
	Pos token.Pos
}

// Provider records the signature of a provider. A provider is a
// single Go object, either a function or a named struct type.
type Provider struct {
	// Pkg is the package that the Go object resides in.
	Pkg *types.Package

	// Name is the name of the Go object.
	Name string

	// Pos is the source position of the func keyword or type spec
	// defining this provider.
	Pos token.Pos

	// Args is the list of data dependencies this provider has.
	Args []ProviderInput

	// Varargs is true if the provider function is variadic.
	Varargs bool

	// IsStruct is true if this provider is a named struct type.
	// Otherwise it's a function.
	IsStruct bool

	// Out is the set of types this provider produces. It will always
	// contain at least one type.
	Out []types.Type

	// HasCleanup reports whether the provider function returns a cleanup
	// function.  (Always false for structs.)
	HasCleanup bool

	// HasErr reports whether the provider function can return an error.
	// (Always false for structs.)
	HasErr bool
}

// ProviderInput describes an incoming edge in the provider graph.
type ProviderInput struct {
	Type types.Type

	// If the provider is a struct, FieldName will be the field name to set.
	FieldName string
}

// Value describes a value expression.
type Value struct {
	// Pos is the source position of the expression defining this value.
	Pos token.Pos

	// Out is the type this value produces.
	Out types.Type

	// expr is the expression passed to wire.Value.
	expr ast.Expr

	// info is the type info for the expression.
	info *types.Info
}

// InjectorArg describes a specific argument passed to an injector function.
type InjectorArg struct {
	// Args is the full set of arguments.
	Args *InjectorArgs
	// Index is the index into Args.Tuple for this argument.
	Index int
}

// InjectorArgs describes the arguments passed to an injector function.
type InjectorArgs struct {
	// Name is the name of the injector function.
	Name string
	// Tuple represents the arguments.
	Tuple *types.Tuple
	// Pos is the source position of the injector function.
	Pos token.Pos
}

// Field describes a specific field selected from a struct.
type Field struct {
	// Parent is the struct or pointer to the struct that the field belongs to.
	Parent types.Type
	// Name is the field name.
	Name string
	// Pkg is the package that the struct resides in.
	Pkg *types.Package
	// Pos is the source position of the field declaration.
	// defining these fields.
	Pos token.Pos
	// Out is the field's provided types. The first element provides the
	// field type. If the field is coming from a pointer to a struct,
	// there will be a second element providing a pointer to the field.
	Out []types.Type
}

// Load finds all the provider sets in the packages that match the given
// patterns, as well as the provider sets' transitive dependencies. It
// may return both errors and Info. The patterns are defined by the
// underlying build system. For the go tool, this is described at
// https://golang.org/cmd/go/#hdr-Package_lists_and_patterns
//
// wd is the working directory and env is the set of environment
// variables to use when loading the packages specified by patterns. If
// env is nil or empty, it is interpreted as an empty set of variables.
// In case of duplicate environment variables, the last one in the list
// takes precedence.
func Load(ctx context.Context, wd string, env []string, patterns []string) (*Info, []error) {
	pkgs, errs := load(ctx, wd, env, patterns)
	if len(errs) > 0 {
		return nil, errs
	}
	if len(pkgs) == 0 {
		return new(Info), nil
	}
	fset := pkgs[0].Fset
	info := &Info{
		Fset: fset,
		Sets: make(map[ProviderSetID]*ProviderSet),
	}
	oc := newObjectCache(pkgs)
	ec := new(errorCollector)
	for _, pkg := range pkgs {
		if isWireImport(pkg.PkgPath) {
			// The marker function package confuses analysis.
			continue
		}
		scope := pkg.Types.Scope()
		for _, name := range scope.Names() {
			obj := scope.Lookup(name)
			if !isProviderSetType(obj.Type()) {
				continue
			}
			item, errs := oc.get(obj)
			if len(errs) > 0 {
				ec.add(notePositionAll(fset.Position(obj.Pos()), errs)...)
				continue
			}
			pset := item.(*ProviderSet)
			// pset.Name may not equal name, since it could be an alias to
			// another provider set.
			id := ProviderSetID{ImportPath: pset.PkgPath, VarName: name}
			info.Sets[id] = pset
		}
		for _, f := range pkg.Syntax {
			for _, decl := range f.Decls {
				fn, ok := decl.(*ast.FuncDecl)
				if !ok {
					continue
				}
				buildCall, err := findInjectorBuild(pkg.TypesInfo, fn)
				if err != nil {
					ec.add(notePosition(fset.Position(fn.Pos()), fmt.Errorf("inject %s: %v", fn.Name.Name, err)))
					continue
				}
				if buildCall == nil {
					continue
				}
				sig := pkg.TypesInfo.ObjectOf(fn.Name).Type().(*types.Signature)
				ins, out, err := injectorFuncSignature(sig)
				if err != nil {
					if w, ok := err.(*wireErr); ok {
						ec.add(notePosition(w.position, fmt.Errorf("inject %s: %v", fn.Name.Name, w.error)))
					} else {
						ec.add(notePosition(fset.Position(fn.Pos()), fmt.Errorf("inject %s: %v", fn.Name.Name, err)))
					}
					continue
				}
				injectorArgs := &InjectorArgs{
					Name:  fn.Name.Name,
					Tuple: ins,
					Pos:   fn.Pos(),
				}
				set, errs := oc.processNewSet(pkg.TypesInfo, pkg.PkgPath, buildCall, injectorArgs, "")
				if len(errs) > 0 {
					ec.add(notePositionAll(fset.Position(fn.Pos()), errs)...)
					continue
				}
				_, errs = solve(fset, out.out, ins, set)
				if len(errs) > 0 {
					ec.add(mapErrors(errs, func(e error) error {
						if w, ok := e.(*wireErr); ok {
							return notePosition(w.position, fmt.Errorf("inject %s: %v", fn.Name.Name, w.error))
						}
						return notePosition(fset.Position(fn.Pos()), fmt.Errorf("inject %s: %v", fn.Name.Name, e))
					})...)
					continue
				}
				info.Injectors = append(info.Injectors, &Injector{
					ImportPath: pkg.PkgPath,
					FuncName:   fn.Name.Name,
				})
			}
		}
	}
	return info, ec.errors
}

// load typechecks the packages that match the given patterns and
// includes source for all transitive dependencies. The patterns are
// defined by the underlying build system. For the go tool, this is
// described at https://golang.org/cmd/go/#hdr-Package_lists_and_patterns
//
// wd is the working directory and env is the set of environment
// variables to use when loading the packages specified by patterns. If
// env is nil or empty, it is interpreted as an empty set of variables.
// In case of duplicate environment variables, the last one in the list
// takes precedence.
func load(ctx context.Context, wd string, env []string, patterns []string) ([]*packages.Package, []error) {
	cfg := &packages.Config{
		Context:    ctx,
		Mode:       packages.LoadAllSyntax,
		Dir:        wd,
		Env:        env,
		BuildFlags: []string{"-tags=wireinject"},
		// TODO(light): Use ParseFile to skip function bodies and comments in indirect packages.
	}
	escaped := make([]string, len(patterns))
	for i := range patterns {
		escaped[i] = "pattern=" + patterns[i]
	}
	pkgs, err := packages.Load(cfg, escaped...)
	if err != nil {
		return nil, []error{err}
	}
	var errs []error
	for _, p := range pkgs {
		for _, e := range p.Errors {
			errs = append(errs, e)
		}
	}
	if len(errs) > 0 {
		return nil, errs
	}
	return pkgs, nil
}

// Info holds the result of Load.
type Info struct {
	Fset *token.FileSet

	// Sets contains all the provider sets in the initial packages.
	Sets map[ProviderSetID]*ProviderSet

	// Injectors contains all the injector functions in the initial packages.
	// The order is undefined.
	Injectors []*Injector
}

// A ProviderSetID identifies a named provider set.
type ProviderSetID struct {
	ImportPath string
	VarName    string
}

// String returns the ID as ""path/to/pkg".Foo".
func (id ProviderSetID) String() string {
	return strconv.Quote(id.ImportPath) + "." + id.VarName
}

// An Injector describes an injector function.
type Injector struct {
	ImportPath string
	FuncName   string
}

// String returns the injector name as ""path/to/pkg".Foo".
func (in *Injector) String() string {
	return strconv.Quote(in.ImportPath) + "." + in.FuncName
}

// objectCache is a lazily evaluated mapping of objects to Wire structures.
type objectCache struct {
	fset     *token.FileSet
	packages map[string]*packages.Package
	objects  map[objRef]objCacheEntry
	hasher   typeutil.Hasher
}

type objRef struct {
	importPath string
	name       string
}

type objCacheEntry struct {
	val  interface{} // *Provider, *ProviderSet, *IfaceBinding, or *Value
	errs []error
}

func newObjectCache(pkgs []*packages.Package) *objectCache {
	if len(pkgs) == 0 {
		panic("object cache must have packages to draw from")
	}
	oc := &objectCache{
		fset:     pkgs[0].Fset,
		packages: make(map[string]*packages.Package),
		objects:  make(map[objRef]objCacheEntry),
		hasher:   typeutil.MakeHasher(),
	}
	// Depth-first search of all dependencies to gather import path to
	// packages.Package mapping. go/packages guarantees that for a single
	// call to packages.Load and an import path X, there will exist only
	// one *packages.Package value with PkgPath X.
	stk := append([]*packages.Package(nil), pkgs...)
	for len(stk) > 0 {
		p := stk[len(stk)-1]
		stk = stk[:len(stk)-1]
		if oc.packages[p.PkgPath] != nil {
			continue
		}
		oc.packages[p.PkgPath] = p
		for _, imp := range p.Imports {
			stk = append(stk, imp)
		}
	}
	return oc
}

// get converts a Go object into a Wire structure. It may return a *Provider, an
// *IfaceBinding, a *ProviderSet, a *Value, or a []*Field.
func (oc *objectCache) get(obj types.Object) (val interface{}, errs []error) {
	ref := objRef{
		importPath: obj.Pkg().Path(),
		name:       obj.Name(),
	}
	if ent, cached := oc.objects[ref]; cached {
		return ent.val, append([]error(nil), ent.errs...)
	}
	defer func() {
		oc.objects[ref] = objCacheEntry{
			val:  val,
			errs: append([]error(nil), errs...),
		}
	}()
	switch obj := obj.(type) {
	case *types.Var:
		spec := oc.varDecl(obj)
		if spec == nil || len(spec.Values) == 0 {
			return nil, []error{fmt.Errorf("%v is not a provider or a provider set", obj)}
		}
		var i int
		for i = range spec.Names {
			if spec.Names[i].Name == obj.Name() {
				break
			}
		}
		pkgPath := obj.Pkg().Path()
		return oc.processExpr(oc.packages[pkgPath].TypesInfo, pkgPath, spec.Values[i], obj.Name())
	case *types.Func:
		return processFuncProvider(oc.fset, obj)
	default:
		return nil, []error{fmt.Errorf("%v is not a provider or a provider set", obj)}
	}
}

// varDecl finds the declaration that defines the given variable.
func (oc *objectCache) varDecl(obj *types.Var) *ast.ValueSpec {
	// TODO(light): Walk files to build object -> declaration mapping, if more performant.
	// Recommended by https://golang.org/s/types-tutorial
	pkg := oc.packages[obj.Pkg().Path()]
	pos := obj.Pos()
	for _, f := range pkg.Syntax {
		tokenFile := oc.fset.File(f.Pos())
		if base := tokenFile.Base(); base <= int(pos) && int(pos) < base+tokenFile.Size() {
			path, _ := astutil.PathEnclosingInterval(f, pos, pos)
			for _, node := range path {
				if spec, ok := node.(*ast.ValueSpec); ok {
					return spec
				}
			}
		}
	}
	return nil
}

// processExpr converts an expression into a Wire structure. It may return a
// *Provider, an *IfaceBinding, a *ProviderSet, a *Value or a []*Field.
func (oc *objectCache) processExpr(info *types.Info, pkgPath string, expr ast.Expr, varName string) (interface{}, []error) {
	exprPos := oc.fset.Position(expr.Pos())
	expr = astutil.Unparen(expr)
	if obj := qualifiedIdentObject(info, expr); obj != nil {
		item, errs := oc.get(obj)
		return item, mapErrors(errs, func(err error) error {
			return notePosition(exprPos, err)
		})
	}
	if call, ok := expr.(*ast.CallExpr); ok {
		fnObj := qualifiedIdentObject(info, call.Fun)
		if fnObj == nil || !isWireImport(fnObj.Pkg().Path()) {
			return nil, []error{notePosition(exprPos, errors.New("unknown pattern"))}
		}
		switch fnObj.Name() {
		case "NewSet":
			pset, errs := oc.processNewSet(info, pkgPath, call, nil, varName)
			return pset, notePositionAll(exprPos, errs)
		case "Bind":
			b, err := processBind(oc.fset, info, call)
			if err != nil {
				return nil, []error{notePosition(exprPos, err)}
			}
			return b, nil
		case "Value":
			v, err := processValue(oc.fset, info, call)
			if err != nil {
				return nil, []error{notePosition(exprPos, err)}
			}
			return v, nil
		case "InterfaceValue":
			v, err := processInterfaceValue(oc.fset, info, call)
			if err != nil {
				return nil, []error{notePosition(exprPos, err)}
			}
			return v, nil
		case "Struct":
			s, err := processStructProvider(oc.fset, info, call)
			if err != nil {
				return nil, []error{notePosition(exprPos, err)}
			}
			return s, nil
		case "FieldsOf":
			v, err := processFieldsOf(oc.fset, info, call)
			if err != nil {
				return nil, []error{notePosition(exprPos, err)}
			}
			return v, nil
		default:
			return nil, []error{notePosition(exprPos, errors.New("unknown pattern"))}
		}
	}
	if tn := structArgType(info, expr); tn != nil {
		p, errs := processStructLiteralProvider(oc.fset, tn)
		if len(errs) > 0 {
			return nil, notePositionAll(exprPos, errs)
		}
		return p, nil
	}
	return nil, []error{notePosition(exprPos, errors.New("unknown pattern"))}
}

func (oc *objectCache) processNewSet(info *types.Info, pkgPath string, call *ast.CallExpr, args *InjectorArgs, varName string) (*ProviderSet, []error) {
	// Assumes that call.Fun is wire.NewSet or wire.Build.

	pset := &ProviderSet{
		Pos:          call.Pos(),
		InjectorArgs: args,
		PkgPath:      pkgPath,
		VarName:      varName,
	}
	ec := new(errorCollector)
	for _, arg := range call.Args {
		item, errs := oc.processExpr(info, pkgPath, arg, "")
		if len(errs) > 0 {
			ec.add(errs...)
			continue
		}
		switch item := item.(type) {
		case *Provider:
			pset.Providers = append(pset.Providers, item)
		case *ProviderSet:
			pset.Imports = append(pset.Imports, item)
		case *IfaceBinding:
			pset.Bindings = append(pset.Bindings, item)
		case *Value:
			pset.Values = append(pset.Values, item)
		case []*Field:
			pset.Fields = append(pset.Fields, item...)
		default:
			panic("unknown item type")
		}
	}
	if len(ec.errors) > 0 {
		return nil, ec.errors
	}
	var errs []error
	pset.providerMap, pset.srcMap, errs = buildProviderMap(oc.fset, oc.hasher, pset)
	if len(errs) > 0 {
		return nil, errs
	}
	if errs := verifyAcyclic(pset.providerMap, oc.hasher); len(errs) > 0 {
		return nil, errs
	}
	return pset, nil
}

// structArgType attempts to interpret an expression as a simple struct type.
// It assumes any parentheses have been stripped.
func structArgType(info *types.Info, expr ast.Expr) *types.TypeName {
	lit, ok := expr.(*ast.CompositeLit)
	if !ok {
		return nil
	}
	tn, ok := qualifiedIdentObject(info, lit.Type).(*types.TypeName)
	if !ok {
		return nil
	}
	if _, isStruct := tn.Type().Underlying().(*types.Struct); !isStruct {
		return nil
	}
	return tn
}

// qualifiedIdentObject finds the object for an identifier or a
// qualified identifier, or nil if the object could not be found.
func qualifiedIdentObject(info *types.Info, expr ast.Expr) types.Object {
	switch expr := expr.(type) {
	case *ast.Ident:
		return info.ObjectOf(expr)
	case *ast.SelectorExpr:
		pkgName, ok := expr.X.(*ast.Ident)
		if !ok {
			return nil
		}
		if _, ok := info.ObjectOf(pkgName).(*types.PkgName); !ok {
			return nil
		}
		return info.ObjectOf(expr.Sel)
	default:
		return nil
	}
}

// processFuncProvider creates a provider for a function declaration.
func processFuncProvider(fset *token.FileSet, fn *types.Func) (*Provider, []error) {
	sig := fn.Type().(*types.Signature)
	fpos := fn.Pos()
	providerSig, err := funcOutput(sig)
	if err != nil {
		return nil, []error{notePosition(fset.Position(fpos), fmt.Errorf("wrong signature for provider %s: %v", fn.Name(), err))}
	}
	params := sig.Params()
	provider := &Provider{
		Pkg:        fn.Pkg(),
		Name:       fn.Name(),
		Pos:        fn.Pos(),
		Args:       make([]ProviderInput, params.Len()),
		Varargs:    sig.Variadic(),
		Out:        []types.Type{providerSig.out},
		HasCleanup: providerSig.cleanup,
		HasErr:     providerSig.err,
	}
	for i := 0; i < params.Len(); i++ {
		provider.Args[i] = ProviderInput{
			Type: params.At(i).Type(),
		}
		for j := 0; j < i; j++ {
			if types.Identical(provider.Args[i].Type, provider.Args[j].Type) {
				return nil, []error{notePosition(fset.Position(fpos), fmt.Errorf("provider has multiple parameters of type %s", types.TypeString(provider.Args[j].Type, nil)))}
			}
		}
	}
	return provider, nil
}

func injectorFuncSignature(sig *types.Signature) (*types.Tuple, outputSignature, error) {
	out, err := funcOutput(sig)
	if err != nil {
		return nil, outputSignature{}, err
	}
	return sig.Params(), out, nil
}

type outputSignature struct {
	out     types.Type
	cleanup bool
	err     bool
}

// funcOutput validates an injector or provider function's return signature.
func funcOutput(sig *types.Signature) (outputSignature, error) {
	results := sig.Results()
	switch results.Len() {
	case 0:
		return outputSignature{}, errors.New("no return values")
	case 1:
		return outputSignature{out: results.At(0).Type()}, nil
	case 2:
		out := results.At(0).Type()
		switch t := results.At(1).Type(); {
		case types.Identical(t, errorType):
			return outputSignature{out: out, err: true}, nil
		case types.Identical(t, cleanupType):
			return outputSignature{out: out, cleanup: true}, nil
		default:
			return outputSignature{}, fmt.Errorf("second return type is %s; must be error or func()", types.TypeString(t, nil))
		}
	case 3:
		if t := results.At(1).Type(); !types.Identical(t, cleanupType) {
			return outputSignature{}, fmt.Errorf("second return type is %s; must be func()", types.TypeString(t, nil))
		}
		if t := results.At(2).Type(); !types.Identical(t, errorType) {
			return outputSignature{}, fmt.Errorf("third return type is %s; must be error", types.TypeString(t, nil))
		}
		return outputSignature{
			out:     results.At(0).Type(),
			cleanup: true,
			err:     true,
		}, nil
	default:
		return outputSignature{}, errors.New("too many return values")
	}
}

// processStructLiteralProvider creates a provider for a named struct type.
// It produces pointer and non-pointer variants via two values in Out.
//
// This is a copy of the old processStructProvider, which is deprecated now.
// It will not support any new feature introduced after v0.2. Please use the new
// wire.Struct syntax for those.
func processStructLiteralProvider(fset *token.FileSet, typeName *types.TypeName) (*Provider, []error) {
	out := typeName.Type()
	st, ok := out.Underlying().(*types.Struct)
	if !ok {
		return nil, []error{fmt.Errorf("%v does not name a struct", typeName)}
	}

	pos := typeName.Pos()
	fmt.Fprintf(os.Stderr,
		"Warning: %v, see https://godoc.org/github.com/google/wire#Struct for more information.\n",
		notePosition(fset.Position(pos),
			fmt.Errorf("using struct literal to inject %s is deprecated and will be removed in the next release; use wire.Struct instead",
				typeName.Type())))
	provider := &Provider{
		Pkg:      typeName.Pkg(),
		Name:     typeName.Name(),
		Pos:      pos,
		Args:     make([]ProviderInput, st.NumFields()),
		IsStruct: true,
		Out:      []types.Type{out, types.NewPointer(out)},
	}
	for i := 0; i < st.NumFields(); i++ {
		f := st.Field(i)
		provider.Args[i] = ProviderInput{
			Type:      f.Type(),
			FieldName: f.Name(),
		}
		for j := 0; j < i; j++ {
			if types.Identical(provider.Args[i].Type, provider.Args[j].Type) {
				return nil, []error{notePosition(fset.Position(pos), fmt.Errorf("provider struct has multiple fields of type %s", types.TypeString(provider.Args[j].Type, nil)))}
			}
		}
	}
	return provider, nil
}

// processStructProvider creates a provider for a named struct type.
// It produces pointer and non-pointer variants via two values in Out.
func processStructProvider(fset *token.FileSet, info *types.Info, call *ast.CallExpr) (*Provider, error) {
	// Assumes that call.Fun is wire.Struct.

	if len(call.Args) < 1 {
		return nil, notePosition(fset.Position(call.Pos()),
			errors.New("call to Struct must specify the struct to be injected"))
	}
	const firstArgReqFormat = "first argument to Struct must be a pointer to a named struct; found %s"
	structType := info.TypeOf(call.Args[0])
	structPtr, ok := structType.(*types.Pointer)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf(firstArgReqFormat, types.TypeString(structType, nil)))
	}

	st, ok := structPtr.Elem().Underlying().(*types.Struct)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf(firstArgReqFormat, types.TypeString(structPtr, nil)))
	}

	stExpr := call.Args[0].(*ast.CallExpr)
	typeName := qualifiedIdentObject(info, stExpr.Args[0]) // should be either an identifier or selector
	provider := &Provider{
		Pkg:      typeName.Pkg(),
		Name:     typeName.Name(),
		Pos:      typeName.Pos(),
		IsStruct: true,
		Out:      []types.Type{structPtr.Elem(), structPtr},
	}
	if allFields(call) {
		for i := 0; i < st.NumFields(); i++ {
			if isPrevented(st.Tag(i)) {
				continue
			}
			f := st.Field(i)
			provider.Args = append(provider.Args, ProviderInput{
				Type:      f.Type(),
				FieldName: f.Name(),
			})
		}
	} else {
		provider.Args = make([]ProviderInput, len(call.Args)-1)
		for i := 1; i < len(call.Args); i++ {
			v, err := checkField(call.Args[i], st)
			if err != nil {
				return nil, notePosition(fset.Position(call.Pos()), err)
			}
			provider.Args[i-1] = ProviderInput{
				Type:      v.Type(),
				FieldName: v.Name(),
			}
		}
	}
	for i := 0; i < len(provider.Args); i++ {
		for j := 0; j < i; j++ {
			if types.Identical(provider.Args[i].Type, provider.Args[j].Type) {
				f := st.Field(j)
				return nil, notePosition(fset.Position(f.Pos()), fmt.Errorf("provider struct has multiple fields of type %s", types.TypeString(provider.Args[j].Type, nil)))
			}
		}
	}
	return provider, nil
}

func allFields(call *ast.CallExpr) bool {
	if len(call.Args) != 2 {
		return false
	}
	b, ok := call.Args[1].(*ast.BasicLit)
	if !ok {
		return false
	}
	return strings.EqualFold(strconv.Quote("*"), b.Value)
}

// isPrevented checks whether field i is prevented by tag "-".
// Since this is the only tag used by wire, we can do string comparison
// without using reflect.
func isPrevented(tag string) bool {
	return reflect.StructTag(tag).Get("wire") == "-"
}

// processBind creates an interface binding from a wire.Bind call.
func processBind(fset *token.FileSet, info *types.Info, call *ast.CallExpr) (*IfaceBinding, error) {
	// Assumes that call.Fun is wire.Bind.

	if len(call.Args) != 2 {
		return nil, notePosition(fset.Position(call.Pos()),
			errors.New("call to Bind takes exactly two arguments"))
	}
	// TODO(light): Verify that arguments are simple expressions.
	ifaceArgType := info.TypeOf(call.Args[0])
	ifacePtr, ok := ifaceArgType.(*types.Pointer)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf("first argument to Bind must be a pointer to an interface type; found %s", types.TypeString(ifaceArgType, nil)))
	}
	iface := ifacePtr.Elem()
	methodSet, ok := iface.Underlying().(*types.Interface)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf("first argument to Bind must be a pointer to an interface type; found %s", types.TypeString(ifaceArgType, nil)))
	}

	provided := info.TypeOf(call.Args[1])
	if bindShouldUsePointer(info, call) {
		providedPtr, ok := provided.(*types.Pointer)
		if !ok {
			return nil, notePosition(fset.Position(call.Args[0].Pos()),
				fmt.Errorf("second argument to Bind must be a pointer or a pointer to a pointer; found %s", types.TypeString(provided, nil)))
		}
		provided = providedPtr.Elem()
	}
	if types.Identical(iface, provided) {
		return nil, notePosition(fset.Position(call.Pos()),
			errors.New("cannot bind interface to itself"))
	}
	if !types.Implements(provided, methodSet) {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf("%s does not implement %s", types.TypeString(provided, nil), types.TypeString(iface, nil)))
	}
	return &IfaceBinding{
		Pos:      call.Pos(),
		Iface:    iface,
		Provided: provided,
	}, nil
}

// processValue creates a value from a wire.Value call.
func processValue(fset *token.FileSet, info *types.Info, call *ast.CallExpr) (*Value, error) {
	// Assumes that call.Fun is wire.Value.

	if len(call.Args) != 1 {
		return nil, notePosition(fset.Position(call.Pos()), errors.New("call to Value takes exactly one argument"))
	}
	ok := true
	ast.Inspect(call.Args[0], func(node ast.Node) bool {
		switch expr := node.(type) {
		case nil, *ast.ArrayType, *ast.BasicLit, *ast.BinaryExpr, *ast.ChanType, *ast.CompositeLit, *ast.FuncType, *ast.Ident, *ast.IndexExpr, *ast.InterfaceType, *ast.KeyValueExpr, *ast.MapType, *ast.ParenExpr, *ast.SelectorExpr, *ast.SliceExpr, *ast.StarExpr, *ast.StructType, *ast.TypeAssertExpr:
			// Good!
		case *ast.UnaryExpr:
			if expr.Op == token.ARROW {
				ok = false
				return false
			}
		case *ast.CallExpr:
			// Only acceptable if it's a type conversion.
			if _, isFunc := info.TypeOf(expr.Fun).(*types.Signature); isFunc {
				ok = false
				return false
			}
		default:
			ok = false
			return false
		}
		return true
	})
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()), errors.New("argument to Value is too complex"))
	}
	// Result type can't be an interface type; use wire.InterfaceValue for that.
	argType := info.TypeOf(call.Args[0])
	if _, isInterfaceType := argType.Underlying().(*types.Interface); isInterfaceType {
		return nil, notePosition(fset.Position(call.Pos()), fmt.Errorf("argument to Value may not be an interface value (found %s); use InterfaceValue instead", types.TypeString(argType, nil)))
	}
	return &Value{
		Pos:  call.Args[0].Pos(),
		Out:  info.TypeOf(call.Args[0]),
		expr: call.Args[0],
		info: info,
	}, nil
}

// processInterfaceValue creates a value from a wire.InterfaceValue call.
func processInterfaceValue(fset *token.FileSet, info *types.Info, call *ast.CallExpr) (*Value, error) {
	// Assumes that call.Fun is wire.InterfaceValue.

	if len(call.Args) != 2 {
		return nil, notePosition(fset.Position(call.Pos()), errors.New("call to InterfaceValue takes exactly two arguments"))
	}
	ifaceArgType := info.TypeOf(call.Args[0])
	ifacePtr, ok := ifaceArgType.(*types.Pointer)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()), fmt.Errorf("first argument to InterfaceValue must be a pointer to an interface type; found %s", types.TypeString(ifaceArgType, nil)))
	}
	iface := ifacePtr.Elem()
	methodSet, ok := iface.Underlying().(*types.Interface)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()), fmt.Errorf("first argument to InterfaceValue must be a pointer to an interface type; found %s", types.TypeString(ifaceArgType, nil)))
	}
	provided := info.TypeOf(call.Args[1])
	if !types.Implements(provided, methodSet) {
		return nil, notePosition(fset.Position(call.Pos()), fmt.Errorf("%s does not implement %s", types.TypeString(provided, nil), types.TypeString(iface, nil)))
	}
	return &Value{
		Pos:  call.Args[1].Pos(),
		Out:  iface,
		expr: call.Args[1],
		info: info,
	}, nil
}

// processFieldsOf creates a slice of fields from a wire.FieldsOf call.
func processFieldsOf(fset *token.FileSet, info *types.Info, call *ast.CallExpr) ([]*Field, error) {
	// Assumes that call.Fun is wire.FieldsOf.

	if len(call.Args) < 2 {
		return nil, notePosition(fset.Position(call.Pos()),
			errors.New("call to FieldsOf must specify fields to be extracted"))
	}
	const firstArgReqFormat = "first argument to FieldsOf must be a pointer to a struct or a pointer to a pointer to a struct; found %s"
	structType := info.TypeOf(call.Args[0])
	structPtr, ok := structType.(*types.Pointer)
	if !ok {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf(firstArgReqFormat, types.TypeString(structType, nil)))
	}

	var struc *types.Struct
	isPtrToStruct := false
	switch t := structPtr.Elem().Underlying().(type) {
	case *types.Pointer:
		struc, ok = t.Elem().Underlying().(*types.Struct)
		if !ok {
			return nil, notePosition(fset.Position(call.Pos()),
				fmt.Errorf(firstArgReqFormat, types.TypeString(struc, nil)))
		}
		isPtrToStruct = true
	case *types.Struct:
		struc = t
	default:
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf(firstArgReqFormat, types.TypeString(t, nil)))
	}
	if struc.NumFields() < len(call.Args)-1 {
		return nil, notePosition(fset.Position(call.Pos()),
			fmt.Errorf("fields number exceeds the number available in the struct which has %d fields", struc.NumFields()))
	}

	fields := make([]*Field, 0, len(call.Args)-1)
	for i := 1; i < len(call.Args); i++ {
		v, err := checkField(call.Args[i], struc)
		if err != nil {
			return nil, notePosition(fset.Position(call.Pos()), err)
		}
		out := []types.Type{v.Type()}
		if isPtrToStruct {
			// If the field is from a pointer to a struct, then
			// wire.Fields also provides a pointer to the field.
			out = append(out, types.NewPointer(v.Type()))
		}
		fields = append(fields, &Field{
			Parent: structPtr.Elem(),
			Name:   v.Name(),
			Pkg:    v.Pkg(),
			Pos:    v.Pos(),
			Out:    out,
		})
	}
	return fields, nil
}

// checkField reports whether f is a field of st. f should be a string with the
// field name.
func checkField(f ast.Expr, st *types.Struct) (*types.Var, error) {
	b, ok := f.(*ast.BasicLit)
	if !ok {
		return nil, fmt.Errorf("%v must be a string with the field name", f)
	}
	for i := 0; i < st.NumFields(); i++ {
		if strings.EqualFold(strconv.Quote(st.Field(i).Name()), b.Value) {
			if isPrevented(st.Tag(i)) {
				return nil, fmt.Errorf("%s is prevented from injecting by wire", b.Value)
			}
			return st.Field(i), nil
		}
	}
	return nil, fmt.Errorf("%s is not a field of %s", b.Value, st.String())
}

// findInjectorBuild returns the wire.Build call if fn is an injector template.
// It returns nil if the function is not an injector template.
func findInjectorBuild(info *types.Info, fn *ast.FuncDecl) (*ast.CallExpr, error) {
	if fn.Body == nil {
		return nil, nil
	}
	numStatements := 0
	invalid := false
	var wireBuildCall *ast.CallExpr
	for _, stmt := range fn.Body.List {
		switch stmt := stmt.(type) {
		case *ast.ExprStmt:
			numStatements++
			if numStatements > 1 {
				invalid = true
			}
			call, ok := stmt.X.(*ast.CallExpr)
			if !ok {
				continue
			}
			if qualifiedIdentObject(info, call.Fun) == types.Universe.Lookup("panic") {
				if len(call.Args) != 1 {
					continue
				}
				call, ok = call.Args[0].(*ast.CallExpr)
				if !ok {
					continue
				}
			}
			buildObj := qualifiedIdentObject(info, call.Fun)
			if buildObj == nil || buildObj.Pkg() == nil || !isWireImport(buildObj.Pkg().Path()) || buildObj.Name() != "Build" {
				continue
			}
			wireBuildCall = call
		case *ast.EmptyStmt:
			// Do nothing.
		case *ast.ReturnStmt:
			// Allow the function to end in a return.
			if numStatements == 0 {
				return nil, nil
			}
		default:
			invalid = true
		}

	}
	if wireBuildCall == nil {
		return nil, nil
	}
	if invalid {
		return nil, errors.New("a call to wire.Build indicates that this function is an injector, but injectors must consist of only the wire.Build call and an optional return")
	}
	return wireBuildCall, nil
}

func isWireImport(path string) bool {
	// TODO(light): This is depending on details of the current loader.
	const vendorPart = "vendor/"
	if i := strings.LastIndex(path, vendorPart); i != -1 && (i == 0 || path[i-1] == '/') {
		path = path[i+len(vendorPart):]
	}
	return path == "github.com/google/wire"
}

func isProviderSetType(t types.Type) bool {
	n, ok := t.(*types.Named)
	if !ok {
		return false
	}
	obj := n.Obj()
	return obj.Pkg() != nil && isWireImport(obj.Pkg().Path()) && obj.Name() == "ProviderSet"
}

// ProvidedType represents a type provided from a source. The source
// can be a *Provider (a provider function), a *Value (wire.Value), or an
// *InjectorArgs (arguments to the injector function). The zero value has
// none of the above, and returns true for IsNil.
type ProvidedType struct {
	// t is the provided concrete type.
	t types.Type
	p *Provider
	v *Value
	a *InjectorArg
	f *Field
}

// IsNil reports whether pt is the zero value.
func (pt ProvidedType) IsNil() bool {
	return pt.p == nil && pt.v == nil && pt.a == nil && pt.f == nil
}

// Type returns the output type.
//
//   - For a function provider, this is the first return value type.
//   - For a struct provider, this is either the struct type or the pointer type
// 	   whose element type is the struct type.
// 	 - For a value, this is the type of the expression.
// 	 - For an argument, this is the type of the argument.
func (pt ProvidedType) Type() types.Type {
	return pt.t
}

// IsProvider reports whether pt points to a Provider.
func (pt ProvidedType) IsProvider() bool {
	return pt.p != nil
}

// IsValue reports whether pt points to a Value.
func (pt ProvidedType) IsValue() bool {
	return pt.v != nil
}

// IsArg reports whether pt points to an injector argument.
func (pt ProvidedType) IsArg() bool {
	return pt.a != nil
}

// IsField reports whether pt points to a Fields.
func (pt ProvidedType) IsField() bool {
	return pt.f != nil
}

// Provider returns pt as a Provider pointer. It panics if pt does not point
// to a Provider.
func (pt ProvidedType) Provider() *Provider {
	if pt.p == nil {
		panic("ProvidedType does not hold a Provider")
	}
	return pt.p
}

// Value returns pt as a Value pointer. It panics if pt does not point
// to a Value.
func (pt ProvidedType) Value() *Value {
	if pt.v == nil {
		panic("ProvidedType does not hold a Value")
	}
	return pt.v
}

// Arg returns pt as an *InjectorArg representing an injector argument. It
// panics if pt does not point to an arg.
func (pt ProvidedType) Arg() *InjectorArg {
	if pt.a == nil {
		panic("ProvidedType does not hold an Arg")
	}
	return pt.a
}

// Field returns pt as a Field pointer. It panics if pt does not point to a
// struct Field.
func (pt ProvidedType) Field() *Field {
	if pt.f == nil {
		panic("ProvidedType does not hold a Field")
	}
	return pt.f
}

// bindShouldUsePointer loads the wire package the user is importing from their
// injector. The call is a wire marker function call.
func bindShouldUsePointer(info *types.Info, call *ast.CallExpr) bool {
	// These type assertions should not fail, otherwise panic.
	fun := call.Fun.(*ast.SelectorExpr)                 // wire.Bind
	pkgName := fun.X.(*ast.Ident)                       // wire
	wireName := info.ObjectOf(pkgName).(*types.PkgName) // wire package
	return wireName.Imported().Scope().Lookup("bindToUsePointer") != nil
}


text:
github.com/markbates/errx does not try to reinvent the wheel! Instead, it uses the already great wheels developed by the Go community and puts them all together in the best way possible. Without these giants, this project would not be possible. Please make sure to check them out and thank them for all of their hard work.

Thank you to the following **GIANTS**:


text:
package it.cure.core.implem.timecontroller.message.base;

import it.cure.core.implem.timecontroller.base.Node;
import it.cure.core.implem.timecontroller.message.bean.AbstractMessage;
import it.cure.core.implem.timecontroller.tcmanage.TcDataController;
import it.cure.core.interfaces.model.ISimulationModel;
import it.cure.core.interfaces.model.ISimulationParameter;

import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * Client sending HB and SIG to the server:
 *
 * - it sends the HB(challenge) to the server and receives the HB(response) from the server, so:
 * 		1) the client authenticates the server ==> AUTHENTICATION
 * 		2) the client is sure that server has received the HB ==> RESILIENCY
 *
 */
public abstract class AbstractMessageClient implements ISimulationParameter{

	protected Node server;
	protected Node sender;
	protected TcDataController tcContext;
	protected ISimulationModel[] simulationModel;

	/**
	 * Constructor
	 *
	 * @param tcContext
	 * @param sender
	 * @param server
	 */
	public AbstractMessageClient(TcDataController tcContext, Node sender, Node server) {
		this.server = server;
		this.sender = sender;
		this.tcContext = tcContext;
	}

	/**
	 * Send a message
	 *
	 * @param message
	 * @throws UnknownHostException
	 * @throws SocketException
	 */
	abstract public void send(AbstractMessage message) throws UnknownHostException, SocketException;

	@Override
	public void setSimulationModel(ISimulationModel[] simulationModel) {
		this.simulationModel = simulationModel;
	}

}


text:
(function ($) {
    "use strict";

    $.fn.fileinputThemes.fas = {
        fileActionSettings: {
            removeIcon: '',
            uploadIcon: '',
            uploadRetryIcon: '',
            downloadIcon: '',
            zoomIcon: '',
            dragIcon: '',
            indicatorNew: '',
            indicatorSuccess: '',
            indicatorError: '',
            indicatorLoading: ''
        },
        layoutTemplates: {
            fileIcon: ' '
        },
        previewZoomButtonIcons: {
            prev: '',
            next: '',
            toggleheader: '',
            fullscreen: '',
            borderless: '',
            close: ''
        },
        previewFileIcon: '',
        browseIcon: '',
        removeIcon: '',
        cancelIcon: '',
        uploadIcon: '',
        msgValidationErrorIcon: ' '
    };
})(window.jQuery);


text:
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Xaml.Interactivity;

namespace Avalonia.Xaml.Interactions.Custom
{
    /// <summary>
    /// Focuses the <see cref="Behavior.AssociatedObject"/> on <see cref="InputElement.PointerMoved"/> event.
    /// </summary>
    public sealed class FocusOnPointerMovedBehavior : Behavior<Control>
    {
        /// <summary>
        /// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PointerMoved += PointerMoved;
        }

        /// <summary>
        /// Called when the behavior is being detached from its <see cref="Behavior.AssociatedObject"/>.
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PointerMoved -= PointerMoved;
        }

        private void PointerMoved(object sender, PointerEventArgs args)
        {
            AssociatedObject.Focus();
        }
    }
}


text:
package util

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"strconv"

	"github.com/golang/glog"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"golang.org/x/crypto/ssh/terminal"
	minikubeConfig "k8s.io/minikube/cmd/minikube/cmd/config"
	"k8s.io/minikube/pkg/minikube/config"
	"k8s.io/minikube/pkg/minikube/constants"
	"k8s.io/minikube/pkg/version"
)

type ServiceContext struct {
	Service string `json:"service"`
	Version string `json:"version"`
}

type Message struct {
	Message        string `json:"message"`
	ServiceContext `json:"serviceContext"`
}

type LookPath func(filename string) (string, error)

var lookPath LookPath

func init() {
	lookPath = exec.LookPath
}

func ReportError(err error, url string) error {
	errMsg, err := FormatError(err)
	if err != nil {
		return errors.Wrap(err, "Error formatting error message")
	}
	jsonErrorMsg, err := MarshallError(errMsg, "default", version.GetVersion())
	if err != nil {
		return errors.Wrap(err, "Error marshalling error message to JSON")
	}
	err = UploadError(jsonErrorMsg, url)
	if err != nil {
		return errors.Wrap(err, "Error uploading error message")
	}
	return nil
}

func FormatError(err error) (string, error) {
	if err == nil {
		return "", errors.New("Error: ReportError was called with nil error value")
	}

	type stackTracer interface {
		StackTrace() errors.StackTrace
	}

	errOutput := []string{}
	errOutput = append(errOutput, err.Error())

	if err, ok := err.(stackTracer); ok {
		for _, f := range err.StackTrace() {
			errOutput = append(errOutput, fmt.Sprintf("\tat %n(%v)", f, f))
		}
	} else {
		return "", errors.New("Error msg with no stack trace cannot be reported")
	}
	return strings.Join(errOutput, "\n"), nil
}

func MarshallError(errMsg, service, version string) ([]byte, error) {
	m := Message{errMsg, ServiceContext{service, version}}
	b, err := json.Marshal(m)
	if err != nil {
		return nil, errors.Wrap(err, "")
	}
	return b, nil
}

func UploadError(b []byte, url string) error {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
	if err != nil {
		return errors.Wrap(err, "")
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return errors.Wrap(err, "")
	} else if resp.StatusCode != 200 {
		return errors.Errorf("Error sending error report to %s, got response code %d", url, resp.StatusCode)
	}
	return nil
}

func MaybeReportErrorAndExit(errToReport error) {
	MaybeReportErrorAndExitWithCode(errToReport, 1)
}

func MaybeReportErrorAndExitWithCode(errToReport error, returnCode int) {
	var err error
	if viper.GetBool(config.WantReportError) {
		err = ReportError(errToReport, constants.ReportingURL)
	} else if viper.GetBool(config.WantReportErrorPrompt) {
		fmt.Println(
			`================================================================================
An error has occurred. Would you like to opt in to sending anonymized crash
information to minikube to help prevent future errors?
To opt out of these messages, run the command:
	minikube config set WantReportErrorPrompt false
================================================================================`)
		if PromptUserForAccept(os.Stdin) {
			minikubeConfig.Set(config.WantReportError, "true")
			err = ReportError(errToReport, constants.ReportingURL)
		}
	}
	if err != nil {
		glog.Errorf(err.Error())
	}
	os.Exit(returnCode)
}

func getInput(input chan string, r io.Reader) {
	reader := bufio.NewReader(r)
	fmt.Print("Please enter your response [Y/n]: \n")
	response, err := reader.ReadString('\n')
	if err != nil {
		glog.Errorf(err.Error())
	}
	input <- response
}

func PromptUserForAccept(r io.Reader) bool {
	if !terminal.IsTerminal(int(os.Stdout.Fd())) {
		return false
	}
	input := make(chan string, 1)
	go getInput(input, r)
	select {
	case response := <-input:
		response = strings.ToLower(strings.TrimSpace(response))
		if response == "y" || response == "yes" || response == "" {
			return true
		} else if response == "n" || response == "no" {
			return false
		} else {
			fmt.Println("Invalid response, error reporting remains disabled. Must be in form [Y/n]")
			return false
		}
	case <-time.After(30 * time.Second):
		return false
	}
}

func MaybePrintKubectlDownloadMsg(goos string, out io.Writer) {
	if !viper.GetBool(config.WantKubectlDownloadMsg) {
		return
	}

	verb := "run"
	installInstructions := "curl -Lo kubectl https://storage.googleapis.com/kubernetes-release/release/%s/bin/%s/%s/kubectl && chmod +x kubectl && sudo mv kubectl /usr/local/bin/"
	if goos == "windows" {
		verb = "do"
		installInstructions = `download kubectl from:
https://storage.googleapis.com/kubernetes-release/release/%s/bin/%s/%s/kubectl.exe
Add kubectl to your system PATH`
	}

	_, err := lookPath("kubectl")
	if err != nil && goos == "windows" {
		_, err = lookPath("kubectl.exe")
	}
	if err != nil {
		fmt.Fprintf(out,
			`========================================
kubectl could not be found on your path. kubectl is a requirement for using minikube
To install kubectl, please %s the following:

%s

To disable this message, run the following:

minikube config set WantKubectlDownloadMsg false
========================================
`,
			verb, fmt.Sprintf(installInstructions, constants.DefaultKubernetesVersion, goos, runtime.GOARCH))
	}
}

// Ask the kernel for a free open port that is ready to use
func GetPort() (string, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		panic(err)
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return "", errors.Errorf("Error accessing port %d", addr.Port)
	}
	defer l.Close()
	return strconv.Itoa(l.Addr().(*net.TCPAddr).Port), nil
}

func KillMountProcess() error {
	out, err := ioutil.ReadFile(filepath.Join(constants.GetMinipath(), constants.MountProcessFileName))
	if err != nil {
		return nil // no mount process to kill
	}
	pid, err := strconv.Atoi(string(out))
	if err != nil {
		return errors.Wrap(err, "error converting mount string to pid")
	}
	mountProc, err := os.FindProcess(pid)
	if err != nil {
		return errors.Wrap(err, "error converting mount string to pid")
	}
	return mountProc.Kill()
}

func GetKubeConfigPath() string {
	kubeConfigEnv := os.Getenv(constants.KubeconfigEnvVar)
	if kubeConfigEnv == "" {
		return constants.KubeconfigPath
	}
	return filepath.SplitList(kubeConfigEnv)[0]
}


text:
package org.geometerplus.fbreader.formats.xhtml;

import org.geometerplus.fbreader.bookmodel.BookReader;
import org.geometerplus.fbreader.bookmodel.FBTextKind;
import org.geometerplus.zlibrary.core.xml.ZLStringMap;

class XHTMLTagParagraphWithControlAction extends XHTMLTagAction {
	final byte myControl;

	XHTMLTagParagraphWithControlAction(byte control) {
		myControl = control;
	}

	protected void doAtStart(XHTMLReader reader, ZLStringMap xmlattributes) {
		final BookReader modelReader = reader.getModelReader();
		switch (myControl) {
			case FBTextKind.TITLE:
			case FBTextKind.H1:
			case FBTextKind.H2:
				if (modelReader.Model.BookTextModel.getParagraphsNumber() > 1) {
					modelReader.insertEndOfSectionParagraph();
				}
				modelReader.enterTitle();
				break;
		}
		modelReader.pushKind(myControl);
		modelReader.beginParagraph();
	}

	protected void doAtEnd(XHTMLReader reader) {
		final BookReader modelReader = reader.getModelReader();
		modelReader.endParagraph();
		modelReader.popKind();
		switch (myControl) {
			case FBTextKind.TITLE:
			case FBTextKind.H1:
			case FBTextKind.H2:
				modelReader.exitTitle();
				break;
		}
	}
}
/*
void XHTMLTagParagraphWithControlAction::doAtStart(XHTMLReader &reader, const char**) {
	if ((myControl == TITLE) && (bookReader(reader).model().bookTextModel()->paragraphsNumber() > 1)) {
		bookReader(reader).insertEndOfSectionParagraph();
	}
	bookReader(reader).pushKind(myControl);
	bookReader(reader).beginParagraph();
}
*/


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

   <meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta name="description" content="Storm is a distributed and fault-tolerant realtime computation system. Similar to how Hadoop provides a set of general primitives for doing batch processing, Storm provides a set of general primitives for doing realtime computation. Storm is simple, can be used with any programming language, and is a lot of fun to use!" />
	<meta name="keywords" content="storm, hadoop, realtime, stream, mapreduce, java, computation, scalability, clojure, scala, jvm, processing" />
	<title>Storm Documentation</title>
	<link rel="stylesheet" type="text/css" href="/css/style.css" media="screen" />

Storm

Distributed and fault-tolerant realtime computation

about

documentation

blog

downloads

community

Documentation Home

Rationale

Tutorial

Manual

Javadoc

FAQ

Contributing

Storm provides hooks with which you can insert custom code to run on any number of events within Storm. You create a hook by extending the BaseTaskHook class and overriding the appropriate method for the event you want to catch. There are two ways to register your hook:

In the open method of your spout or prepare method of your bolt using the TopologyContext#addTaskHook method.

Through the Storm configuration using the "topology.auto.task.hooks" config. These hooks are automatically registered in every spout or bolt, and are useful for doing things like integrating with a custom monitoring system.

	  Apache Storm is an effort undergoing incubation at The Apache Software Foundation.


text:
<https://mathiasbynens.github.io/jquery-placeholder/>

## Example Usage

### HTML

```html
<input type="text" name="name" placeholder="e.g. John Doe">
<input type="email" name="email" placeholder="e.g. address@example.ext">
<input type="url" name="url" placeholder="e.g. https://mathiasbynens.be/">
<input type="tel" name="tel" placeholder="e.g. +32 472 77 69 88">
<input type="password" name="password" placeholder="e.g. h4x0rpr00fz">
<input type="search" name="search" placeholder="Search this site…">
<textarea name="message" placeholder="Your message goes here"></textarea>
```

### jQuery

Use the plugin as follows:

```js
$('input, textarea').placeholder();
```

By default, `.placeholder` css class will be added. You can override default by passing the `customClass` option:
```js
$('input, textarea').placeholder({ customClass: 'my-placeholder' });
```

You'll still be able to use `jQuery#val()` to get and set the input values. If the element is currently showing a placeholder, `.val()` will return an empty string instead of the placeholder text, just like it does in browsers with a native `@placeholder` implementation. Calling `.val('')` to set an element's value to the empty string will result in the placeholder text (re)appearing.

### CSS

The plugin automatically adds `class="placeholder"` to the elements who are currently showing their placeholder text. You can use this to style placeholder text differently:

```css
input, textarea { color: #000; }
.placeholder { color: #aaa; }
```

I'd suggest sticking to the `#aaa` color for placeholder text, as it's the default in most browsers that support `@placeholder`. If you really want to, though, you can [style the placeholder text in some of the browsers that natively support it](https://stackoverflow.com/a/2610741/96656).

## Installation

You can install jquery-placeholder by using [Bower](http://bower.io/).

```bash
bower install jquery-placeholder
```

Or you can install it through [npm](https://www.npmjs.com/):

```
npm install --save jquery-placeholder
```

Contributors should install the »dev dependencies« after forking and cloning via [npm](https://www.npmjs.com/).

```bash
npm install
```

## Notes

* Requires jQuery 1.6+. For an older version of this plugin that works under jQuery 1.4.2+, see [v1.8.7](https://github.com/mathiasbynens/jquery-placeholder/tree/v1.8.7).
* Works in all A-grade browsers, including IE6.
* Automatically checks if the browser natively supports the HTML5 `placeholder` attribute for `input` and `textarea` elements. If this is the case, the plugin won't do anything. If `@placeholder` is only supported for `input` elements, the plugin will leave those alone and apply to `textarea`s exclusively. (This is the case for Safari 4, Opera 11.00, and possibly other browsers.)
* Caches the results of its two feature tests in `jQuery.fn.placeholder.input` and `jQuery.fn.placeholder.textarea`. For example, if `@placeholder` is natively supported for `input` elements, `jQuery.fn.placeholder.input` will be `true`. After loading the plugin, you can re-use these properties in your own code.
* Makes sure it never causes duplicate IDs in your DOM, even in browsers that need an extra `input` element to fake `@placeholder` for password inputs. This means you can safely do stuff like:

    ```html
    <label for="bar">Example label</label>
    <input type="password" placeholder="foo" id="bar">
    ```

    And the `<label>` will always point to the `<input>` element you'd expect. Also, all CSS styles based on the ID will just work™.

## License

This plugin is available under [the MIT license](http://mths.be/mit).

## Thanks to…

* [Paul Irish](http://paulirish.com/) for his inspiring snippet in [jQuery 1.4 Hawtness #1](http://jquery14.com/day-05/jquery-1-4-hawtness-1-with-paul-irish)
* everyone from [#jquery](http://webchat.freenode.net/?channels=jquery) for the tips, ideas and patches
* temp01 for his major contributions
* anyone who [contributed a patch](https://github.com/mathiasbynens/jquery-placeholder/contributors) or [made a helpful suggestion](https://github.com/mathiasbynens/jquery-placeholder/issues)

_– [Mathias](http://mathiasbynens.be/)_


text:
define([
  'intern!object',
  'intern/chai!expect',
  '../helper/fixtures/custom.fixture',
  '../helper/supports',
  'ally/is/valid-tabindex',
], function(registerSuite, expect, customFixture, supports, isValidTabindex) {

  registerSuite(function() {
    var fixture;

    return {
      name: 'is/valid-tabindex',

      beforeEach: function() {
        fixture = customFixture([
          '

',
          '

',
          '

',
          '

',
          '

',
          '

',
          '

',
          '

',
        ]);
      },
      afterEach: function() {
        fixture.remove();
        fixture = null;
      },

      invalid: function() {
        expect(function() {
          isValidTabindex(null);
        }).to.throw(TypeError, 'is/valid-tabindex requires an argument of type Element');
      },
      'non-tabindex': function() {
        var element = document.getElementById('non-tabindex');
        // expect(element.tabIndex).to.equal(-1);
        // IE: 0, rest: -1
        expect(isValidTabindex(element)).to.equal(false);
      },
      'tabindex "-1"': function() {
        var element = document.getElementById('tabindex--1');
        expect(element.tabIndex).to.equal(-1);
        expect(isValidTabindex(element)).to.equal(true);
      },
      'tabindex "0"': function() {
        var element = document.getElementById('tabindex-0');
        expect(element.tabIndex).to.equal(0);
        expect(isValidTabindex(element)).to.equal(true);
      },
      'tabindex "0 " (trailing space)': function() {
        var element = document.getElementById('tabindex-0-space');
        expect(element.tabIndex).to.equal(0);
        expect(isValidTabindex(element)).to.equal(true);
      },
      'tabindex "0char" (trailing non-numeric characters)': function() {
        var element = document.getElementById('tabindex-0-char');
        expect(element.tabIndex).to.equal(0);
        expect(isValidTabindex(element)).to.equal(supports.allowsTrailingCharacters);
      },
      'tabindex "1"': function() {
        var element = document.getElementById('tabindex-1');
        expect(element.tabIndex).to.equal(1);
        expect(isValidTabindex(element)).to.equal(true);
      },
      'tabindex "bad"': function() {
        var element = document.getElementById('tabindex-bad');
        // expect(element.tabIndex).to.equal(-1);
        // IE: 0, rest: -1
        expect(isValidTabindex(element)).to.equal(supports.canFocusInvalidTabindex);
      },
      'tabindex ""': function() {
        var element = document.getElementById('tabindex-empty');
        // expect(element.tabIndex).to.equal(-1);
        // IE: 0, rest: -1
        expect(isValidTabindex(element)).to.equal(supports.canFocusInvalidTabindex);
      },
    };
  });
});


text:
@interface FMWModel ()<AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate, AVAssetWriteManagerDelegate>

@property (nonatomic, weak) UIView *superView;

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) dispatch_queue_t videoQueue;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewlayer;
@property (nonatomic, strong) AVCaptureDeviceInput *videoInput;
@property (nonatomic, strong) AVCaptureDeviceInput *audioInput;

@property (nonatomic, strong) AVCaptureVideoDataOutput *videoOutput;
@property (nonatomic, strong) AVCaptureAudioDataOutput *audioOutput;

@property (nonatomic, strong)AVAssetWriteManager *writeManager;

@property (nonatomic, strong, readwrite) NSURL *videoUrl;

@property (nonatomic, assign) FMFlashState flashState;
@property (nonatomic, assign) FMVideoViewType viewType;
@end

@implementation FMWModel

- (instancetype)initWithFMVideoViewType:(FMVideoViewType)type superView:(UIView *)superView
{
    self = [super init];
    if (self) {
        _superView = superView;
        _viewType = type;
        [self setUpWithType:type];
    }
    return self;
}

#pragma mark - lazy load
- (AVCaptureSession *)session
{
    // 录制5秒钟视频 高画质10M,压缩成中画质 0.5M
    // 录制5秒钟视频 中画质0.5M,压缩成中画质 0.5M
    // 录制5秒钟视频 低画质0.1M,压缩成中画质 0.1M
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];
        if ([_session canSetSessionPreset:AVCaptureSessionPresetHigh]) {//设置分辨率
            _session.sessionPreset=AVCaptureSessionPresetHigh;
        }
    }
    return _session;
}

- (dispatch_queue_t)videoQueue
{
    if (!_videoQueue) {
        _videoQueue = dispatch_queue_create("com.5miles", DISPATCH_QUEUE_SERIAL);
    }
    return _videoQueue;
}
- (AVCaptureVideoPreviewLayer *)previewlayer
{
    if (!_previewlayer) {
        _previewlayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        _previewlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    return _previewlayer;
}

- (void)setRecordState:(FMRecordState)recordState
{
    if (_recordState != recordState) {
        _recordState = recordState;
        if (self.delegate && [self.delegate respondsToSelector:@selector(updateRecordState:)]) {
            [self.delegate updateRecordState:_recordState];
        }
    }
}

#pragma mark - setup
- (void)setUpWithType:(FMVideoViewType )type
{
    ///1. 初始化捕捉会话,数据的采集都在会话中处理
    [self setUpInit];
    ///2. 设置视频的输入输出
    [self setUpVideo];

    ///3. 设置音频的输入输出
    [self setUpAudio];

    ///4. 视频的预览层
    [self setUpPreviewLayerWithType:type];

    ///5. 开始采集画面
    [self.session startRunning];

    /// 6. 初始化writer, 用writer 把数据写入文件
    [self setUpWriter];

}

- (void)setUpVideo
{
    // 2.1 获取视频输入设备(摄像头)
    AVCaptureDevice *videoCaptureDevice=[self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];//取得后置摄像头
    // 2.2 创建视频输入源
    NSError *error=nil;
    self.videoInput= [[AVCaptureDeviceInput alloc] initWithDevice:videoCaptureDevice error:&error];
    // 2.3 将视频输入源添加到会话
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }

    self.videoOutput = [[AVCaptureVideoDataOutput alloc] init];
    self.videoOutput.alwaysDiscardsLateVideoFrames = YES; //立即丢弃旧帧,节省内存,默认YES
    [self.videoOutput setSampleBufferDelegate:self queue:self.videoQueue];
    if ([self.session canAddOutput:self.videoOutput]) {
        [self.session addOutput:self.videoOutput];
    }

}
- (void)setUpAudio
{
    // 2.2 获取音频输入设备
    AVCaptureDevice *audioCaptureDevice=[[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
    NSError *error=nil;
    // 2.4 创建音频输入源
    self.audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioCaptureDevice error:&error];
    // 2.6 将音频输入源添加到会话
    if ([self.session canAddInput:self.audioInput]) {
        [self.session addInput:self.audioInput];
    }

    self.audioOutput = [[AVCaptureAudioDataOutput alloc] init];
    [self.audioOutput setSampleBufferDelegate:self queue:self.videoQueue];
    if([self.session canAddOutput:self.audioOutput]) {
        [self.session addOutput:self.audioOutput];
    }

}

- (void)setUpPreviewLayerWithType:(FMVideoViewType )type
{
    CGRect rect = CGRectZero;
    switch (type) {
        case Type1X1:
            rect = CGRectMake(0, 0, kScreenWidth, kScreenWidth);
            break;
        case Type4X3:
            rect = CGRectMake(0, 0, kScreenWidth, kScreenWidth*4/3);
            break;
        case TypeFullScreen:
            rect = [UIScreen mainScreen].bounds;
            break;
        default:
            rect = [UIScreen mainScreen].bounds;
            break;
    }

    self.previewlayer.frame = rect;
    [_superView.layer insertSublayer:self.previewlayer atIndex:0];
}

- (void)setUpWriter
{
    self.videoUrl = [[NSURL alloc] initFileURLWithPath:[self createVideoFilePath]];
    self.writeManager = [[AVAssetWriteManager alloc] initWithURL:self.videoUrl viewType:_viewType];
    self.writeManager.delegate = self;

}
#pragma mark - public method
//切换摄像头
- (void)turnCameraAction
{
    [self.session stopRunning];
    // 1. 获取当前摄像头
    AVCaptureDevicePosition position = self.videoInput.device.position;

    //2. 获取当前需要展示的摄像头
    if (position == AVCaptureDevicePositionBack) {
        position = AVCaptureDevicePositionFront;
    } else {
        position = AVCaptureDevicePositionBack;
    }

    // 3. 根据当前摄像头创建新的device
    AVCaptureDevice *device = [self getCameraDeviceWithPosition:position];

    // 4. 根据新的device创建input
    AVCaptureDeviceInput *newInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

    //5. 在session中切换input
    [self.session beginConfiguration];
    [self.session removeInput:self.videoInput];
    [self.session addInput:newInput];
    [self.session commitConfiguration];
    self.videoInput = newInput;

    [self.session startRunning];

}

- (void)switchflash
{
    if(_flashState == FMFlashClose){
        if ([self.videoInput.device hasTorch]) {
            [self.videoInput.device lockForConfiguration:nil];
            [self.videoInput.device setTorchMode:AVCaptureTorchModeOn];
            [self.videoInput.device unlockForConfiguration];
            _flashState = FMFlashOpen;
        }
    }else if(_flashState == FMFlashOpen){
        if ([self.videoInput.device hasTorch]) {
            [self.videoInput.device lockForConfiguration:nil];
            [self.videoInput.device setTorchMode:AVCaptureTorchModeAuto];
            [self.videoInput.device unlockForConfiguration];
            _flashState = FMFlashAuto;
        }
    }else if(_flashState == FMFlashAuto){
        if ([self.videoInput.device hasTorch]) {
            [self.videoInput.device lockForConfiguration:nil];
            [self.videoInput.device setTorchMode:AVCaptureTorchModeOff];
            [self.videoInput.device unlockForConfiguration];
            _flashState = FMFlashClose;
        }
    };
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateFlashState:)]) {
        [self.delegate updateFlashState:_flashState];
    }

}

- (void)startRecord
{
    if (self.recordState == FMRecordStateInit) {
        [self.writeManager startWrite];
        self.recordState = FMRecordStateRecording;
    }
}

- (void)stopRecord
{

    [self.writeManager stopWrite];
    [self.session stopRunning];
    self.recordState = FMRecordStateFinish;

}

- (void)reset
{
    self.recordState = FMRecordStateInit;
    [self.session startRunning];
    [self setUpWriter];

}

#pragma mark - private method
//初始化设置
- (void)setUpInit
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBack) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationWillEnterForegroundNotification object:nil];
    [self clearFile];
    _recordState = FMRecordStateInit;
}
//存放视频的文件夹
- (NSString *)videoFolder
{
    NSString *cacheDir = [XCFileManager cachesDir];
    NSString *direc = [cacheDir stringByAppendingPathComponent:VIDEO_FOLDER];
    if (![XCFileManager isExistsAtPath:direc]) {
        [XCFileManager createDirectoryAtPath:direc];
    }
    return direc;
}
//清空文件夹
- (void)clearFile
{
    [XCFileManager removeItemAtPath:[self videoFolder]];

}
//写入的视频路径
- (NSString *)createVideoFilePath
{
    NSString *videoName = [NSString stringWithFormat:@"%@.mp4", [NSUUID UUID].UUIDString];
    NSString *path = [[self videoFolder] stringByAppendingPathComponent:videoName];
    return path;

}

#pragma mark - 获取摄像头
-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position] == position) {
            return camera;
        }
    }
    return nil;
}

#pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate AVCaptureAudioDataOutputSampleBufferDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    @autoreleasepool {

        //视频
        if (connection == [self.videoOutput connectionWithMediaType:AVMediaTypeVideo]) {

            if (!self.writeManager.outputVideoFormatDescription) {
                @synchronized(self) {
                    CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
                    self.writeManager.outputVideoFormatDescription = formatDescription;
                }
            } else {
                @synchronized(self) {
                    if (self.writeManager.writeState == FMRecordStateRecording) {
                        [self.writeManager appendSampleBuffer:sampleBuffer ofMediaType:AVMediaTypeVideo];
                    }

                }
            }

        }

        //音频
        if (connection == [self.audioOutput connectionWithMediaType:AVMediaTypeAudio]) {
            if (!self.writeManager.outputAudioFormatDescription) {
                @synchronized(self) {
                    CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
                    self.writeManager.outputAudioFormatDescription = formatDescription;
                }
            }
            @synchronized(self) {

                if (self.writeManager.writeState == FMRecordStateRecording) {
                    [self.writeManager appendSampleBuffer:sampleBuffer ofMediaType:AVMediaTypeAudio];
                }

            }

        }
    }

}

#pragma mark - AVAssetWriteManagerDelegate
- (void)updateWritingProgress:(CGFloat)progress
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateRecordingProgress:)]) {
        [self.delegate updateRecordingProgress:progress];
    }
}

- (void)finishWriting
{
    [self.session stopRunning];
    self.recordState = FMRecordStateFinish;
}
#pragma mark - notification
- (void)enterBack
{
    self.videoUrl = nil;
    [self.session stopRunning];
    [self.writeManager destroyWrite];

}

- (void)becomeActive
{
    [self reset];
}

- (void)destroy
{
    [self.session stopRunning];
    self.session = nil;
    self.videoQueue = nil;
    self.videoOutput = nil;
    self.videoInput = nil;
    self.audioOutput = nil;
    self.audioInput = nil;
    [self.writeManager destroyWrite];

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc
{
    [self destroy];

}
@end


text:
package ua.stqa.mantis.model;

public class MailMessage {

  public String text;
  public String to;

  public MailMessage(String to, String text) {
    this.to = to;
    this.text = text;
  }
}


text:
- Korrektur: Aktualisierte URL für Mapquest Geokodierung
- Korrektur: Absturz behoben, wenn ein Foto an ein Log angehängt wird
- Änderung: Bessere Fehlermeldung wie eine Captcha-Anforderung beim Login auf geocaching.com aufgelöst werden kann

## Caches
- Korrektur: Verhindert, dass Spoiler-Bilder in der Galerie gedoppelt werden, wenn ein Cache aktualisiert wird

## Variablenrechner
- Neu: TRUNC-Funktion (Abschneiden) um Dezimalwerte zu kürzen
- Neu: Erlaube die Verwendung von eckigen Klammern für Berechnungen. Für Variablenbereiche verwende bitte z.B. \[:1-5\].

## Karte
- Korrektur: Zeige richtige DT-Markierung für D4.0 und D4.5 an


text:
/*
 * Author: doe300
 *
 * See the file "LICENSE" for the full license governing this code.
 */

#ifndef SPIRVOPERATION_H
#define SPIRVOPERATION_H

#include "../Module.h"
#include "../Optional.h"

#include <map>
#include <memory>
#include <vector>

namespace vc4c
{
    namespace intermediate
    {
        enum class InstructionDecorations : uint32_t;
    } // namespace intermediate

    namespace spirv
    {
        static constexpr uint32_t UNDEFINED_ID{0};
        static constexpr uint32_t UNDEFINED_SCALAR{0xFFFFFFFF};

        struct SPIRVMethod
        {
            std::unique_ptr<Method> method;
            std::vector<std::pair<uint32_t, uint32_t>> parameters;
            const uint32_t id;

            SPIRVMethod(uint32_t id, Module& module) : method(new Method(module)), id(id) {}
        };

        using TypeMapping = std::map<uint32_t, DataType>;
        using ConstantMapping = std::map<uint32_t, CompoundConstant>;
        using LocalTypeMapping = std::map<uint32_t, uint32_t>;
        using MethodMapping = std::map<uint32_t, SPIRVMethod>;
        using LocalMapping = std::map<uint32_t, const Local*>;

        class SPIRVOperation
        {
        public:
            SPIRVOperation(uint32_t id, SPIRVMethod& method, intermediate::InstructionDecorations decorations);
            virtual ~SPIRVOperation() noexcept;

            virtual void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) = 0;
            virtual Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const = 0;

        protected:
            const uint32_t id;
            SPIRVMethod& method;
            intermediate::InstructionDecorations decorations;
        };

        static const std::string OP_NEGATE("negate");

        class SPIRVInstruction : public SPIRVOperation
        {
        public:
            SPIRVInstruction(uint32_t id, SPIRVMethod& method, const std::string& opcode, uint32_t resultType,
                std::vector<uint32_t>&& operands, intermediate::InstructionDecorations decorations);
            ~SPIRVInstruction() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        protected:
            uint32_t typeID;
            std::string opcode;
            std::vector<uint32_t> operands;
        };

        class SPIRVComparison final : public SPIRVInstruction
        {
        public:
            SPIRVComparison(uint32_t id, SPIRVMethod& method, const std::string& opcode, uint32_t resultType,
                std::vector<uint32_t>&& operands, intermediate::InstructionDecorations decorations);
            ~SPIRVComparison() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;
        };

        class SPIRVCallSite : public SPIRVOperation
        {
        public:
            SPIRVCallSite(uint32_t id, SPIRVMethod& method, uint32_t methodID, uint32_t resultType,
                std::vector<uint32_t>&& arguments);
            SPIRVCallSite(uint32_t id, SPIRVMethod& method, const std::string& methodName, uint32_t resultType,
                std::vector<uint32_t>&& arguments);
            SPIRVCallSite(SPIRVMethod& method, const std::string& methodName, std::vector<uint32_t>&& arguments);
            ~SPIRVCallSite() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        protected:
            Optional<uint32_t> methodID;
            const uint32_t typeID;
            Optional<std::string> methodName;
            std::vector<uint32_t> arguments;
        };

        // Special call site/method call to handle SPIR-V operations that return (vector of) bool, while the mapped
        // OpenCL C function returns (vector of) int. This also handles the OpenCL C pattern of returning -1 instead of
        // 1 for !false values in vector variants.
        class SPIRVBoolCallSite final : public SPIRVCallSite
        {
        public:
            SPIRVBoolCallSite(uint32_t id, SPIRVMethod& method, uint32_t methodID, uint32_t resultType,
                std::vector<uint32_t>&& arguments);
            SPIRVBoolCallSite(uint32_t id, SPIRVMethod& method, const std::string& methodName, uint32_t resultType,
                std::vector<uint32_t>&& arguments);
            ~SPIRVBoolCallSite() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
        };

        class SPIRVReturn final : public SPIRVOperation
        {
        public:
            explicit SPIRVReturn(SPIRVMethod& method);
            SPIRVReturn(uint32_t returnValue, SPIRVMethod& method);
            ~SPIRVReturn() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            Optional<uint32_t> returnValue;
        };

        class SPIRVBranch final : public SPIRVOperation
        {
        public:
            SPIRVBranch(SPIRVMethod& method, uint32_t labelID);
            SPIRVBranch(SPIRVMethod& method, uint32_t conditionID, uint32_t trueLabelID, uint32_t falseLabelID);
            ~SPIRVBranch() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t defaultLabelID;
            const Optional<uint32_t> conditionID;
            const Optional<uint32_t> falseLabelID;
        };

        class SPIRVLabel final : public SPIRVOperation
        {
        public:
            SPIRVLabel(uint32_t id, SPIRVMethod& method);
            ~SPIRVLabel() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;
        };

        enum class ConversionType : unsigned char
        {
            SIGNED_TO_SIGNED,
            UNSIGNED_TO_UNSIGNED,
            SIGNED_TO_UNSIGNED,
            UNSIGNED_TO_SIGNED,
            FLOATING,
            BITCAST
        };

        class SPIRVConversion final : public SPIRVOperation
        {
        public:
            SPIRVConversion(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t sourceID,
                ConversionType type, intermediate::InstructionDecorations decorations);
            ~SPIRVConversion() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t sourceID;
            const ConversionType type;
        };

        enum class MemoryAccess : unsigned char
        {
            NONE = 0x0,
            READ = 0x1,
            WRITE = 0x2,
            READ_WRITE = 0x3
        };

        class SPIRVCopy final : public SPIRVOperation
        {
        public:
            // copies whole object
            SPIRVCopy(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t sourceID,
                MemoryAccess memoryAccess = MemoryAccess::NONE, uint32_t size = UNDEFINED_ID);
            ~SPIRVCopy() override = default;
            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t sourceID;
            const MemoryAccess memoryAccess;
            const Optional<uint32_t> sizeID;
        };

        class SPIRVInsertionExtraction final : public SPIRVOperation
        {
        public:
            // inserts single element at given index
            SPIRVInsertionExtraction(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t srcContainerId,
                uint32_t srcElementId, std::vector<uint32_t>&& indices, bool literalIndices);
            // extracts single element at given index
            SPIRVInsertionExtraction(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t srcContainerId,
                std::vector<uint32_t>&& indices, bool literalIndices);
            ~SPIRVInsertionExtraction() override = default;
            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t containerId;
            Optional<uint32_t> elementId;
            std::vector<uint32_t> indices;
            bool indicesAreLiteral;
        };

        class SPIRVShuffle final : public SPIRVOperation
        {
        public:
            SPIRVShuffle(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t sourceID0, uint32_t sourceID1,
                std::vector<uint32_t>&& indices);
            SPIRVShuffle(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t sourceID0, uint32_t sourceID1,
                uint32_t compositeIndex);
            ~SPIRVShuffle() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t source0;
            const uint32_t source1;
            const std::vector<uint32_t> indices;
            const bool compositeIndex;
        };

        class SPIRVIndexOf final : public SPIRVOperation
        {
        public:
            SPIRVIndexOf(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t containerID,
                std::vector<uint32_t>&& indices, bool isPtrAcessChain);
            ~SPIRVIndexOf() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t container;
            const std::vector<uint32_t> indices;
            const bool isPtrAcessChain;
        };

        class SPIRVPhi final : public SPIRVOperation
        {
        public:
            SPIRVPhi(uint32_t id, SPIRVMethod& method, uint32_t resultType,
                std::vector<std::pair<uint32_t, uint32_t>>&& sources);
            ~SPIRVPhi() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const std::vector<std::pair<uint32_t, uint32_t>> sources;
        };

        class SPIRVSelect final : public SPIRVOperation
        {
        public:
            SPIRVSelect(uint32_t id, SPIRVMethod& method, uint32_t resultType, uint32_t conditionID, uint32_t trueObj,
                uint32_t falseObj);
            ~SPIRVSelect() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t condID;
            const uint32_t trueID;
            const uint32_t falseID;
        };

        class SPIRVSwitch final : public SPIRVOperation
        {
        public:
            SPIRVSwitch(uint32_t id, SPIRVMethod& method, uint32_t selectorID, uint32_t defaultID,
                std::vector<uint32_t>&& argWords);
            ~SPIRVSwitch() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t selectorID;
            const uint32_t defaultID;
            const std::vector<uint32_t> argumentWords;
        };

        enum class ImageQuery : unsigned char
        {
            CHANNEL_DATA_TYPE,
            CHANNEL_ORDER,
            SIZES,
            SIZES_LOD,
            MIPMAP_LEVELS,
            SAMPLES_PER_TEXEL
        };

        class SPIRVImageQuery final : public SPIRVOperation
        {
        public:
            SPIRVImageQuery(uint32_t id, SPIRVMethod& method, uint32_t resultType, ImageQuery value, uint32_t imageID,
                uint32_t lodOrCoordinate = UNDEFINED_ID);
            ~SPIRVImageQuery() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const ImageQuery valueID;
            const uint32_t imageID;
            const uint32_t lodOrCoordinate;
        };

        class SPIRVMemoryBarrier final : public SPIRVOperation
        {
        public:
            SPIRVMemoryBarrier(SPIRVMethod& method, uint32_t scopeID, uint32_t semanticsID);
            ~SPIRVMemoryBarrier() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t scopeID;
            const uint32_t semanticsID;
        };

        class SPIRVLifetimeInstruction final : public SPIRVOperation
        {
        public:
            SPIRVLifetimeInstruction(uint32_t id, SPIRVMethod& method, uint32_t size, bool lifetimeEnd,
                intermediate::InstructionDecorations decorations);
            ~SPIRVLifetimeInstruction() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t sizeInBytes;
            const bool isLifetimeEnd;
        };

        class SPIRVFoldInstruction final : public SPIRVOperation
        {
        public:
            SPIRVFoldInstruction(uint32_t id, SPIRVMethod& method, uint32_t resultType,
                const std::string& foldOperation, uint32_t sourceID, intermediate::InstructionDecorations decorations);
            ~SPIRVFoldInstruction() override = default;

            void mapInstruction(TypeMapping& types, ConstantMapping& constants, LocalTypeMapping& localTypes,
                MethodMapping& methods, LocalMapping& localMapping) override;
            Optional<Value> precalculate(const TypeMapping& types, const ConstantMapping& constants,
                const LocalMapping& memoryAllocated) const override;

        private:
            const uint32_t typeID;
            const uint32_t sourceID;
            const std::string foldOperation;
        };
    } // namespace spirv
} // namespace vc4c

#endif /* SPIRVOPERATION_H */