// eliminatePhysicalProjection should be called after physical optimization to
// eliminate the redundant projection left after logical projection elimination.
358376
func eliminatePhysicalProjection(p PhysicalPlan) PhysicalPlan {
	oldSchema := p.Schema()
	newRoot := doPhysicalProjectionElimination(p)
	newCols := newRoot.Schema().Columns
	for i, oldCol := range oldSchema.Columns {
		oldCol.Index = newCols[i].Index
		newRoot.Schema().Columns[i] = oldCol
	}
	return newRoot
}
549070
func SanitizeRect(x, y, w, h, r int) (int, int, int, int) {
	if w < 0 {
		x += w
		w = -w
	}
	if h < 0 {
		y += h
		h = -h
	}

	d := (imax(1, r) - 1) / 2
	// TODO: what if w-2D <= 0 ?
	return x + d, y + d, w - 2*d, h - 2*d
}
787049
func (s *NetworkService) GetPhysicalNetworkByName(name string, opts ...OptionFunc) (*PhysicalNetwork, int, error) {
	id, count, err := s.GetPhysicalNetworkID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetPhysicalNetworkByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
792309
func (p *Aggregation) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	planInfo, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if planInfo != nil {
		return planInfo, nil
	}
	limit := prop.limit
	if len(prop.props) == 0 {
		planInfo, err = p.convert2PhysicalPlanHash()
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	streamInfo, err := p.convert2PhysicalPlanStream(removeLimit(prop))
	if planInfo == nil || streamInfo.cost < planInfo.cost {
		planInfo = streamInfo
	}
	planInfo = enforceProperty(limitProperty(limit), planInfo)
	err = p.storePlanInfo(prop, planInfo)
	return planInfo, errors.Trace(err)
}
416104
func (s *VisvalingamSimplifier) Simplify(g orb.Geometry) orb.Geometry {
	return simplify(s, g)
}
904640
func (b *PlanBuilder) buildProjectionForWindow(p LogicalPlan, expr *ast.WindowFuncExpr, aggMap map[*ast.AggregateFuncExpr]int) (LogicalPlan, []property.Item, []property.Item, []expression.Expression, error) {
	b.optFlag |= flagEliminateProjection

	var items []*ast.ByItem
	if expr.Spec.Name.L != "" {
		ref, ok := b.windowSpecs[expr.Spec.Name.L]
		if !ok {
			return nil, nil, nil, nil, ErrWindowNoSuchWindow.GenWithStackByArgs(expr.Spec.Name.O)
		}
		expr.Spec = ref
	}
	spec := expr.Spec
	if spec.Ref.L != "" {
		ref, ok := b.windowSpecs[spec.Ref.L]
		if !ok {
			return nil, nil, nil, nil, ErrWindowNoSuchWindow.GenWithStackByArgs(spec.Ref.O)
		}
		err := mergeWindowSpec(&spec, &ref)
		if err != nil {
			return nil, nil, nil, nil, err
		}
	}

	lenPartition := 0
	if spec.PartitionBy != nil {
		items = append(items, spec.PartitionBy.Items...)
		lenPartition = len(spec.PartitionBy.Items)
	}
	if spec.OrderBy != nil {
		items = append(items, spec.OrderBy.Items...)
	}
	projLen := len(p.Schema().Columns) + len(items) + len(expr.Args)
	proj := LogicalProjection{Exprs: make([]expression.Expression, 0, projLen)}.Init(b.ctx)
	schema := expression.NewSchema(make([]*expression.Column, 0, projLen)...)
	for _, col := range p.Schema().Columns {
		proj.Exprs = append(proj.Exprs, col)
		schema.Append(col)
	}

	transformer := &itemTransformer{}
	propertyItems := make([]property.Item, 0, len(items))
	for _, item := range items {
		newExpr, _ := item.Expr.Accept(transformer)
		item.Expr = newExpr.(ast.ExprNode)
		it, np, err := b.rewrite(item.Expr, p, aggMap, true)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		p = np
		if col, ok := it.(*expression.Column); ok {
			propertyItems = append(propertyItems, property.Item{Col: col, Desc: item.Desc})
			continue
		}
		proj.Exprs = append(proj.Exprs, it)
		col := &expression.Column{
			ColName:  model.NewCIStr(fmt.Sprintf("%d_proj_window_%d", p.ID(), schema.Len())),
			UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
			RetType:  it.GetType(),
		}
		schema.Append(col)
		propertyItems = append(propertyItems, property.Item{Col: col, Desc: item.Desc})
	}

	newArgList := make([]expression.Expression, 0, len(expr.Args))
	for _, arg := range expr.Args {
		newArg, np, err := b.rewrite(arg, p, aggMap, true)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		p = np
		switch newArg.(type) {
		case *expression.Column, *expression.Constant:
			newArgList = append(newArgList, newArg)
			continue
		}
		proj.Exprs = append(proj.Exprs, newArg)
		col := &expression.Column{
			ColName:  model.NewCIStr(fmt.Sprintf("%d_proj_window_%d", p.ID(), schema.Len())),
			UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
			RetType:  newArg.GetType(),
		}
		schema.Append(col)
		newArgList = append(newArgList, col)
	}

	proj.SetSchema(schema)
	proj.SetChildren(p)
	return proj, propertyItems[:lenPartition], propertyItems[lenPartition:], newArgList, nil
}
918931
func (s *StackResourceSummary) SetPhysicalResourceId(v string) *StackResourceSummary {
	s.PhysicalResourceId = &v
	return s
}
500638
func (l *lattice) decompose(k *big.Int) []*big.Int {
	n := len(l.inverse)

	// Calculate closest vector in lattice to <k,0,0,...> with Babai's rounding.
	c := make([]*big.Int, n)
	for i := 0; i < n; i++ {
		c[i] = new(big.Int).Mul(k, l.inverse[i])
		round(c[i], l.det)
	}

	// Transform vectors according to c and subtract <k,0,0,...>.
	out := make([]*big.Int, n)
	temp := new(big.Int)

	for i := 0; i < n; i++ {
		out[i] = new(big.Int)

		for j := 0; j < n; j++ {
			temp.Mul(c[j], l.vectors[j][i])
			out[i].Add(out[i], temp)
		}

		out[i].Neg(out[i])
		out[i].Add(out[i], l.vectors[0][i]).Add(out[i], l.vectors[0][i])
	}
	out[0].Add(out[0], k)

	return out
}
609275
func (g *Geometry) Simplify(tolerance float64) (*Geometry, error) {
	return g.simplify("simplify", cGEOSSimplify, tolerance)
}
975676
func (m *MTTrie) RemoveMetric(mt metricType) {
	a, _ := m.find(mt.Namespace().Strings())
	if a != nil {
		for v, x := range a.mts {
			if mt.Version() == x.Version() {
				// delete this metric from the node
				delete(a.mts, v)
			}
		}
	}
}
709393
func (p *Join) convert2PhysicalPlanSemi(prop *requiredProperty) (*physicalPlanInfo, error) {
	lChild := p.GetChildByIndex(0).(LogicalPlan)
	rChild := p.GetChildByIndex(1).(LogicalPlan)
	allLeft := true
	for _, col := range prop.props {
		if lChild.GetSchema().GetColumnIndex(col.col) == -1 {
			allLeft = false
		}
	}
	join := &PhysicalHashSemiJoin{
		WithAux:         LeftOuterSemiJoin == p.JoinType,
		EqualConditions: p.EqualConditions,
		LeftConditions:  p.LeftConditions,
		RightConditions: p.RightConditions,
		OtherConditions: p.OtherConditions,
		Anti:            p.anti,
	}
	join.ctx = p.ctx
	join.tp = "HashSemiJoin"
	join.allocator = p.allocator
	join.initIDAndContext(p.ctx)
	join.SetSchema(p.schema)
	lProp := prop
	if !allLeft {
		lProp = &requiredProperty{}
	}
	if p.JoinType == SemiJoin {
		lProp = removeLimit(lProp)
	}
	lInfo, err := lChild.convert2PhysicalPlan(lProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	rInfo, err := rChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	if p.JoinType == SemiJoin {
		resultInfo.count = uint64(float64(lInfo.count) * selectionFactor)
	} else {
		resultInfo.count = lInfo.count
	}
	if !allLeft {
		resultInfo = enforceProperty(prop, resultInfo)
	} else if p.JoinType == SemiJoin {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}
677426
func (s *NetworkService) DeletePhysicalNetwork(p *DeletePhysicalNetworkParams) (*DeletePhysicalNetworkResponse, error) {
	resp, err := s.cs.newRequest("deletePhysicalNetwork", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeletePhysicalNetworkResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
678506
func (pe *projectionEliminater) optimize(lp LogicalPlan) (LogicalPlan, error) {
	root := pe.eliminate(lp, make(map[string]*expression.Column), false)
	return root, nil
}
1157355
func ProjectionFromPB(pb *PlanPb, sel *rel.SqlSelect) *Projection {
	m := Projection{
		Proj: rel.ProjectionFromPb(pb.Projection),
	}
	m.Final = pb.Projection.Final
	m.PlanBase = NewPlanBase(pb.Parallel)
	m.Stmt = sel
	return &m
}
1256135
func (s *GlobalSecondaryIndexInfo) SetProjection(v *Projection) *GlobalSecondaryIndexInfo {
	s.Projection = v
	return s
}
514793
func NewProjectionFinal(ctx *Context, p *Select) (*Projection, error) {
	s := &Projection{
		P:        p,
		Stmt:     p.Stmt,
		PlanBase: NewPlanBase(false),
		Final:    true,
	}
	var err error
	if len(p.Stmt.From) == 0 {
		err = s.loadLiteralProjection(ctx)
	} else if len(p.From) == 1 && p.From[0].Proj != nil {
		s.Proj = p.From[0].Proj
	} else {
		err = s.loadFinal(ctx, true)
	}
	if err != nil {
		return nil, err
	}
	return s, nil
}
903334
func validatePhysicalHostForCreation(h *crimson.PhysicalHost) error {
	switch {
	case h == nil:
		return status.Error(codes.InvalidArgument, "physical host specification is required")
	case h.Name == "":
		return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
	case h.Vlan != 0:
		return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead")
	case h.Machine == "":
		return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
	case h.Nic == "":
		return status.Error(codes.InvalidArgument, "NIC is required and must be non-empty")
	case h.MacAddress != "":
		return status.Error(codes.InvalidArgument, "MAC address must not be specified, use NIC instead")
	case h.Os == "":
		return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty")
	case h.VmSlots < 0:
		return status.Error(codes.InvalidArgument, "VM slots must be non-negative")
	default:
		_, err := common.ParseIPv4(h.Ipv4)
		if err != nil {
			return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", h.Ipv4)
		}
		return nil
	}
}