• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang proto.Float32函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/golang/protobuf/proto.Float32函数的典型用法代码示例。如果您正苦于以下问题:Golang Float32函数的具体用法?Golang Float32怎么用?Golang Float32使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Float32函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: host_to_rpc

func host_to_rpc(host *graph.Host, states []state.HostState, metrics map[string][]metric.MetricValue) *rpc.Node {
	node := &rpc.Node{
		Id:         proto.Int32(int32(host.Id)),
		Name:       proto.String(host.Name),
		Address:    proto.String(host.Address),
		Model:      proto.String(host.Model),
		MacAddress: proto.String(host.MACAddress),
		Comment:    proto.String(host.Comment),
		Serial:     proto.String(host.Serial),
		Ip4:        proto.Uint32(ipv4_to_uint32(host.IP)),
		Ip6:        []byte(host.IP6.To16()),
		DbId:       proto.Int32(int32(host.DBImportSwitchId)),
		IcingaName: proto.String(host.IcingaName),
		Type:       rpc.Node_NodeType(host.Type).Enum(),
	}
	if len(states) > 0 {
		node.States = make([]*rpc.NodeState, len(states))
		for index, s := range states {
			n_state := &rpc.NodeState{
				Rtt:                 proto.Float32(s.RTT),
				Loss:                proto.Float32(s.Loss),
				State:               rpc.NodeState_State(s.State).Enum(),
				HardState:           rpc.NodeState_State(s.HardState).Enum(),
				DescriptiveState:    rpc.NodeState_DescState(s.EffectiveState).Enum(),
				IsHardState:         proto.Bool(s.IsHardState),
				IsFlapping:          proto.Bool(s.IsFlapping),
				IsReachable:         proto.Bool(s.IsReachable),
				IsExecuting:         proto.Bool(s.IsExecuting),
				Time:                proto.Uint64(uint64(s.Time.Unix())),
				Source:              proto.String(s.Source),
				Output:              proto.String(s.Output),
				NumServices:         proto.Int32(s.NumServices),
				NumServicesOk:       proto.Int32(s.NumServicesOk),
				NumServicesCritical: proto.Int32(s.NumServicesCritical),
				NumServicesWarning:  proto.Int32(s.NumServicesWarning),
				NumServicesPending:  proto.Int32(s.NumServicesPending),
				NumServicesUnknown:  proto.Int32(s.NumServicesUnknown),
				Notes:               proto.String(s.Notes),
				HasBeenChecked:      proto.Bool(s.HasBeenChecked),
				IsDuplicate:         proto.Bool(s.IsDuplicate),
			}
			node.States[index] = n_state
		}
	}
	node.LastMetricValues = make(map[string]*rpc.MetricValCollection)
	for key := range metrics {
		values, _ := metrics[key]
		if len(values) == 0 {
			continue
		}
		collection := &rpc.MetricValCollection{}
		collection.Name = proto.String(key)
		collection.Values = make([]*rpc.MetricVal, len(values))
		for index, value := range values {
			collection.Values[index], _ = metric_value_to_rpc(value)
		}
		node.LastMetricValues[key] = collection
	}
	return node
}
开发者ID:netassist-ua,项目名称:netgraphz2-gpl,代码行数:60,代码来源:rpc_formater.go


示例2: Float32P

// Float32P parses the given string representation of a floating point number,
// and returns a pointer to a float32 whose value is same as the parsed number.
func Float32P(val string) (*float32, error) {
	f, err := Float32(val)
	if err != nil {
		return nil, err
	}
	return proto.Float32(f), nil
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:9,代码来源:proto2_convert.go


示例3: normalizeAppApk

// normalizeAppApk normalizes values in the "apk" section of App.
func normalizeAppApk(p *bspb.BatteryStats_App_Apk, totalTimeHour float64) *bspb.BatteryStats_App_Apk {
	norm := &bspb.BatteryStats_App_Apk{}

	// there's only one wakeups value per apk
	norm.Wakeups = proto.Float32(float32(roundToTwoDecimal(float64(p.GetWakeups()) / totalTimeHour)))
	norm.Service = normalizeRepeatedMessage(p.GetService(), totalTimeHour).Interface().([]*bspb.BatteryStats_App_Apk_Service)
	return norm
}
开发者ID:mike69d,项目名称:battery-historian,代码行数:9,代码来源:checkin_normalize.go


示例4: newTestMessage

func newTestMessage() *pb.MyMessage {
	msg := &pb.MyMessage{
		Count: proto.Int32(42),
		Name:  proto.String("Dave"),
		Quote: proto.String(`"I didn't want to go."`),
		Pet:   []string{"bunny", "kitty", "horsey"},
		Inner: &pb.InnerMessage{
			Host:      proto.String("footrest.syd"),
			Port:      proto.Int32(7001),
			Connected: proto.Bool(true),
		},
		Others: []*pb.OtherMessage{
			{
				Key:   proto.Int64(0xdeadbeef),
				Value: []byte{1, 65, 7, 12},
			},
			{
				Weight: proto.Float32(6.022),
				Inner: &pb.InnerMessage{
					Host: proto.String("lesha.mtv"),
					Port: proto.Int32(8002),
				},
			},
		},
		Bikeshed: pb.MyMessage_BLUE.Enum(),
		Somegroup: &pb.MyMessage_SomeGroup{
			GroupField: proto.Int32(8),
		},
		// One normally wouldn't do this.
		// This is an undeclared tag 13, as a varint (wire type 0) with value 4.
		XXX_unrecognized: []byte{13<<3 | 0, 4},
	}
	ext := &pb.Ext{
		Data: proto.String("Big gobs for big rats"),
	}
	if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil {
		panic(err)
	}
	greetings := []string{"adg", "easy", "cow"}
	if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil {
		panic(err)
	}

	// Add an unknown extension. We marshal a pb.Ext, and fake the ID.
	b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")})
	if err != nil {
		panic(err)
	}
	b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...)
	proto.SetRawExtension(msg, 201, b)

	// Extensions can be plain fields, too, so let's test that.
	b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19)
	proto.SetRawExtension(msg, 202, b)

	return msg
}
开发者ID:undernewmanagement,项目名称:besticon,代码行数:57,代码来源:text_test.go


示例5: subtractSystemBatteryLevel

// subtractSystemBatteryLevel sets start level to the current level of the first proto.
func subtractSystemBatteryLevel(p1, p2 *bspb.BatteryStats_System_BatteryLevel) *bspb.BatteryStats_System_BatteryLevel {
	if p1 == nil && p2 == nil {
		return nil
	}
	if p2 == nil {
		return proto.Clone(p1).(*bspb.BatteryStats_System_BatteryLevel)
	}
	if p1 == nil {
		return proto.Clone(p2).(*bspb.BatteryStats_System_BatteryLevel)

	}
	d := &bspb.BatteryStats_System_BatteryLevel{}

	// CurrentLevel is set as the diff between the current level of the 2 protos.
	d.CurrentLevel = proto.Float32(p1.GetCurrentLevel() - p2.GetCurrentLevel())
	// Startlevel is set to the level of the first proto which is our main proto against which we want to diff the other one
	d.StartLevel = proto.Float32(p1.GetCurrentLevel())
	return d
}
开发者ID:mike69d,项目名称:battery-historian,代码行数:20,代码来源:checkin_delta.go


示例6: InitTermFreqRow

func InitTermFreqRow(tfr *TermFreqRow, field uint16, term []byte, docID []byte, docNum uint64, freq uint64, norm float32, termVectors []*TermVector) *TermFreqRow {
	tfr.field = field
	tfr.term = term
	tfr.docID = docID
	tfr.docNum = docNum
	tfr.value.Freq = proto.Uint64(freq)
	tfr.value.Norm = proto.Float32(norm)
	tfr.value.Vectors = termVectors
	return tfr
}
开发者ID:mitra-varuna,项目名称:bleve,代码行数:10,代码来源:termfreq.go


示例7: createDropoutLayer

func createDropoutLayer(name string, bottom string, top string, ratio float32) *caffe.LayerParameter {
	return &caffe.LayerParameter{
		Name:   proto.String(name),
		Type:   proto.String("Dropout"),
		Bottom: []string{bottom},
		Top:    []string{top},
		DropoutParam: &caffe.DropoutParameter{
			DropoutRatio: proto.Float32(ratio),
		},
		Include: []*caffe.NetStateRule{
			&caffe.NetStateRule{
				Phase: caffe.Phase_TRAIN.Enum(),
			},
		},
	}
}
开发者ID:danieldk,项目名称:dparnn,代码行数:16,代码来源:layer_util.go


示例8: convertToProtoSuiteResult

func convertToProtoSuiteResult(suiteResult *suiteResult) *gauge_messages.ProtoSuiteResult {
	protoSuiteResult := &gauge_messages.ProtoSuiteResult{
		PreHookFailure:   suiteResult.preSuite,
		PostHookFailure:  suiteResult.postSuite,
		Failed:           proto.Bool(suiteResult.isFailed),
		SpecsFailedCount: proto.Int32(int32(suiteResult.specsFailedCount)),
		ExecutionTime:    proto.Int64(suiteResult.executionTime),
		SpecResults:      convertToProtoSpecResult(suiteResult.specResults),
		SuccessRate:      proto.Float32(getSuccessRate(len(suiteResult.specResults), suiteResult.specsFailedCount)),
		Environment:      proto.String(suiteResult.environment),
		Tags:             proto.String(suiteResult.tags),
		ProjectName:      proto.String(suiteResult.projectName),
		Timestamp:        proto.String(suiteResult.timestamp),
	}
	return protoSuiteResult
}
开发者ID:Jayasagar,项目名称:gauge,代码行数:16,代码来源:protoConverters.go


示例9: subtractAppApk

// subtractAppApk computes differences of "apk" in App. p2 will be subtracted from p1.
func subtractAppApk(p1, p2 *bspb.BatteryStats_App_Apk) *bspb.BatteryStats_App_Apk {
	d := &bspb.BatteryStats_App_Apk{}
	apkChanged := false
	// there's only one wakeups value per apk, compare wakeups separately
	if diffWakeups := p1.GetWakeups() - p2.GetWakeups(); diffWakeups != 0 {
		apkChanged = true
		d.Wakeups = proto.Float32(diffWakeups)
	}
	if diff := subtractRepeatedMessage(p1.GetService(), p2.GetService()); !diff.IsNil() {
		apkChanged = true
		d.Service = diff.Interface().([]*bspb.BatteryStats_App_Apk_Service)
	}
	if apkChanged {
		return d
	}
	return nil
}
开发者ID:mike69d,项目名称:battery-historian,代码行数:18,代码来源:checkin_delta.go


示例10: metric_value_to_rpc

func metric_value_to_rpc(m metric.MetricValue) (rpc_val *rpc.MetricVal, err error) {
	rpc_val = &rpc.MetricVal{
		Time: proto.Uint64(uint64(m.Time.Unix())),
		Kind: rpc.MetricVal_Kind(m.Kind + 1).Enum(),
		Name: proto.String(m.Name),
		Type: proto.String("host"),
	}
	err = nil
	defer func() {
		if r := recover(); r != nil {
			switch x := r.(type) {
			case string:
				err = errors.New(x)
			case error:
				err = x
			default:
				err = errors.New("Unknown panic")
			}
			log.Printf("Recover metric_value_to_rpc from error: %v\n", err)
		}
	}()
	switch m.Kind {
	case metric.METRIC_GAUGE:
		rpc_val.GaugeValue = proto.Float32(float32(m.Value.(float64)))
	case metric.METRIC_COUNTER:
		rpc_val.CounterValue = proto.Uint64(m.Value.(uint64))
	case metric.METRIC_DERIVE:
		rpc_val.DeriveValue = proto.Int64(m.Value.(int64))
	default:
		buffer := &bytes.Buffer{}
		err := binary.Write(buffer, binary.LittleEndian, m.Value)
		if err != nil {
			log.Printf("Cannot serialize data: %s\n", err)
		} else {
			rpc_val.OtherValue = buffer.Bytes()
		}
	}
	return
}
开发者ID:netassist-ua,项目名称:netgraphz2-gpl,代码行数:39,代码来源:rpc_formater.go


示例11: populateMessage

func populateMessage(pb *test_pb.TestAllTypes) {
	pb.OptionalInt32 = proto.Int32(101)
	pb.OptionalInt64 = proto.Int64(102)
	pb.OptionalUint32 = proto.Uint32(103)
	pb.OptionalUint64 = proto.Uint64(104)
	pb.OptionalSint32 = proto.Int32(105)
	pb.OptionalSint64 = proto.Int64(106)
	pb.OptionalFixed32 = proto.Uint32(107)
	pb.OptionalFixed64 = proto.Uint64(108)
	pb.OptionalSfixed32 = proto.Int32(109)
	pb.OptionalSfixed64 = proto.Int64(110)
	pb.OptionalFloat = proto.Float32(111.5)
	pb.OptionalDouble = proto.Float64(112.5)
	pb.OptionalBool = proto.Bool(true)
	pb.OptionalString = proto.String("test")
	pb.OptionalBytes = []byte("abcd")

	group := &test_pb.TestAllTypes_OptionalGroup{}
	group.A = proto.Int32(111)
	pb.Optionalgroup = group

	nestedMessage := &test_pb.TestAllTypes_NestedMessage{}
	nestedMessage.B = proto.Int32(112)
	pb.OptionalNestedMessage = nestedMessage

	pb.OptionalNestedEnum = test_pb.TestAllTypes_FOO.Enum()

	pb.RepeatedInt32 = append(pb.RepeatedInt32, 201)
	pb.RepeatedInt32 = append(pb.RepeatedInt32, 202)

	pb.RepeatedString = append(pb.RepeatedString, "foo")
	pb.RepeatedString = append(pb.RepeatedString, "bar")

	pb.RepeatedNestedEnum = append(pb.RepeatedNestedEnum,
		test_pb.TestAllTypes_FOO)
	pb.RepeatedNestedEnum = append(pb.RepeatedNestedEnum,
		test_pb.TestAllTypes_BAR)
}
开发者ID:sashka,项目名称:protoclosure,代码行数:38,代码来源:protoclosure_test.go


示例12: FillSerializer

// Fills serializer in dt_field
func (pst *PropertySerializerTable) FillSerializer(field *dt_field) {
	// Handle special decoders that need the complete field data here
	switch field.Name {
	case "m_flSimulationTime":
		field.Serializer = &PropertySerializer{decodeSimTime, nil, false, 0, nil, "unkown"}
		return
	case "m_flAnimTime":
		field.Serializer = &PropertySerializer{decodeSimTime, nil, false, 0, nil, "unkown"}
		return
	}

	// Handle special fields in old replays where the low and high values of a
	// quantized float were invalid.
	if field.build < 955 {
		switch field.Name {
		case "m_flMana", "m_flMaxMana":
			field.LowValue = nil
			field.HighValue = proto.Float32(8192.0)
		}

	}

	field.Serializer = pst.GetPropertySerializerByName(field.Type)
}
开发者ID:ruinnight,项目名称:manta,代码行数:25,代码来源:property_serializers.go


示例13:

var (
	marshaler = Marshaler{}

	marshalerAllOptions = Marshaler{
		Indent: "  ",
	}

	simpleObject = &pb.Simple{
		OInt32:  proto.Int32(-32),
		OInt64:  proto.Int64(-6400000000),
		OUint32: proto.Uint32(32),
		OUint64: proto.Uint64(6400000000),
		OSint32: proto.Int32(-13),
		OSint64: proto.Int64(-2600000000),
		OFloat:  proto.Float32(3.14),
		ODouble: proto.Float64(6.02214179e23),
		OBool:   proto.Bool(true),
		OString: proto.String("hello \"there\""),
		OBytes:  []byte("beep boop"),
	}

	simpleObjectJSON = `{` +
		`"o_bool":true,` +
		`"o_int32":-32,` +
		`"o_int64":"-6400000000",` +
		`"o_uint32":32,` +
		`"o_uint64":"6400000000",` +
		`"o_sint32":-13,` +
		`"o_sint64":"-2600000000",` +
		`"o_float":3.14,` +
开发者ID:robinjha,项目名称:clair,代码行数:30,代码来源:jsonpb_test.go


示例14: NewRandomRowFilter

// NewRandomRowFilter is TODO
func NewRandomRowFilter(chance float32) *RandomRowFilter {
	return &RandomRowFilter{
		Chance: proto.Float32(chance),
	}
}
开发者ID:jfrabaute,项目名称:gohbase,代码行数:6,代码来源:filter.go


示例15:

		json string
	}{
		{data: "", json: `""`},
		{data: proto.String(""), json: `""`},
		{data: "foo", json: `"foo"`},
		{data: proto.String("foo"), json: `"foo"`},
		{data: int32(-1), json: "-1"},
		{data: proto.Int32(-1), json: "-1"},
		{data: int64(-1), json: "-1"},
		{data: proto.Int64(-1), json: "-1"},
		{data: uint32(123), json: "123"},
		{data: proto.Uint32(123), json: "123"},
		{data: uint64(123), json: "123"},
		{data: proto.Uint64(123), json: "123"},
		{data: float32(-1.5), json: "-1.5"},
		{data: proto.Float32(-1.5), json: "-1.5"},
		{data: float64(-1.5), json: "-1.5"},
		{data: proto.Float64(-1.5), json: "-1.5"},
		{data: true, json: "true"},
		{data: proto.Bool(true), json: "true"},
		{data: (*string)(nil), json: "null"},
		{data: new(empty.Empty), json: "{}"},
		{data: examplepb.NumericEnum_ONE, json: "1"},
		{
			data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))),
			json: "1",
		},
	}
	builtinKnownErrors = []struct {
		data interface{}
		json string
开发者ID:kubernetes,项目名称:dashboard,代码行数:31,代码来源:marshal_json_test.go


示例16: TestPopulateParameters

func TestPopulateParameters(t *testing.T) {
	for _, spec := range []struct {
		values url.Values
		filter *internal.DoubleArray
		want   proto.Message
	}{
		{
			values: url.Values{
				"float_value":    {"1.5"},
				"double_value":   {"2.5"},
				"int64_value":    {"-1"},
				"int32_value":    {"-2"},
				"uint64_value":   {"3"},
				"uint32_value":   {"4"},
				"bool_value":     {"true"},
				"string_value":   {"str"},
				"repeated_value": {"a", "b", "c"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto3Message{
				FloatValue:    1.5,
				DoubleValue:   2.5,
				Int64Value:    -1,
				Int32Value:    -2,
				Uint64Value:   3,
				Uint32Value:   4,
				BoolValue:     true,
				StringValue:   "str",
				RepeatedValue: []string{"a", "b", "c"},
			},
		},
		{
			values: url.Values{
				"float_value":    {"1.5"},
				"double_value":   {"2.5"},
				"int64_value":    {"-1"},
				"int32_value":    {"-2"},
				"uint64_value":   {"3"},
				"uint32_value":   {"4"},
				"bool_value":     {"true"},
				"string_value":   {"str"},
				"repeated_value": {"a", "b", "c"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto2Message{
				FloatValue:    proto.Float32(1.5),
				DoubleValue:   proto.Float64(2.5),
				Int64Value:    proto.Int64(-1),
				Int32Value:    proto.Int32(-2),
				Uint64Value:   proto.Uint64(3),
				Uint32Value:   proto.Uint32(4),
				BoolValue:     proto.Bool(true),
				StringValue:   proto.String("str"),
				RepeatedValue: []string{"a", "b", "c"},
			},
		},
		{
			values: url.Values{
				"nested.nested.nested.repeated_value": {"a", "b", "c"},
				"nested.nested.nested.string_value":   {"s"},
				"nested.nested.string_value":          {"t"},
				"nested.string_value":                 {"u"},
				"nested_non_null.string_value":        {"v"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto3Message{
				Nested: &proto2Message{
					Nested: &proto3Message{
						Nested: &proto2Message{
							RepeatedValue: []string{"a", "b", "c"},
							StringValue:   proto.String("s"),
						},
						StringValue: "t",
					},
					StringValue: proto.String("u"),
				},
				NestedNonNull: proto2Message{
					StringValue: proto.String("v"),
				},
			},
		},
		{
			values: url.Values{
				"uint64_value": {"1", "2", "3", "4", "5"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto3Message{
				Uint64Value: 1,
			},
		},
	} {
		msg := proto.Clone(spec.want)
		msg.Reset()
		err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter)
		if err != nil {
			t.Errorf("runtime.PoplateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err)
			continue
		}
		if got, want := msg, spec.want; !proto.Equal(got, want) {
			t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want)
//.........这里部分代码省略.........
开发者ID:vvakame,项目名称:grpc-gateway,代码行数:101,代码来源:query_test.go


示例17: handleRequest


//.........这里部分代码省略.........
				}
				attBlob, err = proto.Marshal(arcaneDust)
				check(err)
				respType = 262
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_NOT_SO_MASSIVE_LOGIN {
				notMassive := &hsproto.PegasusUtil_NotSoMassiveLoginReply{}
				attBlob, err = proto.Marshal(notMassive)
				check(err)
				respType = int64(hsproto.PegasusUtil_NotSoMassiveLoginReply_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_REWARD_PROGRESS {
				rewardProgress := &hsproto.PegasusUtil_RewardProgress{
					SeasonEnd: &hsproto.PegasusShared_Date{
						Year:  proto.Int32(2015),
						Month: proto.Int32(4),
						Day:   proto.Int32(30),
						Hours: proto.Int32(22),
						Min:   proto.Int32(0),
						Sec:   proto.Int32(0),
					},
					WinsPerGold:   proto.Int32(3),
					GoldPerReward: proto.Int32(10),
					MaxGoldPerDay: proto.Int32(100),
					SeasonNumber:  proto.Int32(18),
					XpSoloLimit:   proto.Int32(60),
					MaxHeroLevel:  proto.Int32(60),
					NextQuestCancel: &hsproto.PegasusShared_Date{
						Year:  proto.Int32(2015),
						Month: proto.Int32(4),
						Day:   proto.Int32(1),
						Hours: proto.Int32(0),
						Min:   proto.Int32(0),
						Sec:   proto.Int32(0),
					},
					EventTimingMod: proto.Float32(-0.0833333283662796),
				}

				attBlob, err = proto.Marshal(rewardProgress)
				check(err)
				respType = int64(hsproto.PegasusUtil_RewardProgress_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_BOOSTER_TALLY {
				boosterTally := &hsproto.PegasusUtil_BoosterTallyList{}
				attBlob, err = proto.Marshal(boosterTally)
				check(err)
				respType = int64(hsproto.PegasusUtil_BoosterTallyList_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_PLAYER_RECORD {
				playerRecords := &hsproto.PegasusUtil_PlayerRecords{}
				attBlob, err = proto.Marshal(playerRecords)
				check(err)
				respType = int64(hsproto.PegasusUtil_PlayerRecords_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_GOLD_BALANCE {
				goldBalance := &hsproto.PegasusUtil_GoldBalance{
					CappedBalance: proto.Int64(1000),
					BonusBalance:  proto.Int64(0),
					Cap:           proto.Int64(999999),
					CapWarning:    proto.Int64(999999),
				}
				attBlob, err = proto.Marshal(goldBalance)
				check(err)
				respType = int64(hsproto.PegasusUtil_GoldBalance_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_HERO_XP {
				heroXP := &hsproto.PegasusUtil_HeroXP{
					XpInfos: make([]*hsproto.PegasusUtil_HeroXPInfo, 10),
				}
				for i := int32(2); i < 12; i++ {
					heroXP.XpInfos[i-2] = &hsproto.PegasusUtil_HeroXPInfo{
						ClassId: proto.Int32(i),
开发者ID:laiqu,项目名称:stove,代码行数:67,代码来源:bnet.go


示例18: StateToProtocolBuffer

// StateToProtocolBuffer converts a State type to a proto.State
func StateToProtocolBuffer(state *State) (*proto.State, error) {
	if state.Host == "" {
		state.Host, _ = os.Hostname()
	}
	if state.Time == 0 {
		state.Time = time.Now().Unix()
	}

	var e proto.State
	t := reflect.ValueOf(&e).Elem()
	s := reflect.ValueOf(state).Elem()
	typeOfEvent := s.Type()

	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		value := reflect.ValueOf(f.Interface())
		if reflect.Zero(f.Type()) != value && f.Interface() != nil {
			name := typeOfEvent.Field(i).Name
			switch name {
			case "State", "Service", "Host", "Description":
				tmp := reflect.ValueOf(pb.String(value.String()))
				t.FieldByName(name).Set(tmp)
			case "Once":
				tmp := reflect.ValueOf(pb.Bool(bool(value.Bool())))
				t.FieldByName(name).Set(tmp)
			case "Ttl":
				tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
				t.FieldByName(name).Set(tmp)
			case "Time":
				tmp := reflect.ValueOf(pb.Int64(value.Int()))
				t.FieldByName(name).Set(tmp)
			case "Tags":
				tmp := reflect.ValueOf(value.Interface().([]string))
				t.FieldByName(name).Set(tmp)
			case "Metric":
				switch reflect.TypeOf(f.Interface()).Kind() {
				case reflect.Int:
					tmp := reflect.ValueOf(pb.Int64(int64(value.Int())))
					t.FieldByName("MetricSint64").Set(tmp)
				case reflect.Float32:
					tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
					t.FieldByName("MetricF").Set(tmp)
				case reflect.Float64:
					tmp := reflect.ValueOf(pb.Float64(value.Float()))
					t.FieldByName("MetricD").Set(tmp)
				default:
					return nil, fmt.Errorf("Metric of invalid type (type %v)",
						reflect.TypeOf(f.Interface()).Kind())
				}
			case "Attributes":
				var attrs []*proto.Attribute
				for k, v := range value.Interface().(map[string]string) {
					k_, v_ := k, v
					attrs = append(attrs, &proto.Attribute{
						Key:   &k_,
						Value: &v_,
					})
				}
				t.FieldByName(name).Set(reflect.ValueOf(attrs))
			}
		}
	}
	return &e, nil
}
开发者ID:jmartin127,项目名称:heapster,代码行数:65,代码来源:marshal.go


示例19: eventToPbEvent

func eventToPbEvent(event *Event) (*proto.Event, error) {
	var e proto.Event

	if event.Host == "" {
		event.Host, _ = os.Hostname()
	}
	t := reflect.ValueOf(&e).Elem()
	s := reflect.ValueOf(event).Elem()
	typeOfEvent := s.Type()
	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		value := reflect.ValueOf(f.Interface())
		if !isZero(f) {
			name := typeOfEvent.Field(i).Name
			switch name {
			case "State", "Service", "Host", "Description":
				tmp := reflect.ValueOf(pb.String(value.String()))
				t.FieldByName(name).Set(tmp)
			case "Ttl":
				tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
				t.FieldByName(name).Set(tmp)
			case "Time":
				tmp := reflect.ValueOf(pb.Int64(value.Int()))
				t.FieldByName(name).Set(tmp)
			case "Tags":
				tmp := reflect.ValueOf(value.Interface().([]string))
				t.FieldByName(name).Set(tmp)
			case "Metric":
				switch reflect.TypeOf(f.Interface()).Kind() {
				case reflect.Int:
					tmp := reflect.ValueOf(pb.Int64(int64(value.Int())))
					t.FieldByName("MetricSint64").Set(tmp)
				case reflect.Int64:
					tmp := reflect.ValueOf(pb.Int64(int64(value.Int())))
					t.FieldByName("MetricSint64").Set(tmp)
				case reflect.Float32:
					tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
					t.FieldByName("MetricF").Set(tmp)
				case reflect.Float64:
					tmp := reflect.ValueOf(pb.Float64(value.Float()))
					t.FieldByName("MetricD").Set(tmp)
				default:
					return nil, fmt.Errorf("Metric of invalid type (type %v)",
						reflect.TypeOf(f.Interface()).Kind())
				}
			case "Attributes":
				var attrs []*proto.Attribute
				for k, v := range value.Interface().(map[string]string) {
					// Copy k,v so we can take
					// pointers to the new
					// temporaries
					k_, v_ := k, v
					attrs = append(attrs, &proto.Attribute{
						Key:   &k_,
						Value: &v_,
					})
				}
				t.FieldByName(name).Set(reflect.ValueOf(attrs))
			}
		}
	}

	return &e, nil
}
开发者ID:rzagabe,项目名称:telegraf,代码行数:64,代码来源:raidman.go


示例20: main

func main() {
	vars := []proto.Message{
		&pb.M0{F: proto.Int32(0)},
		&pb.M0{F: proto.Int32(-1000000), XXX_unrecognized: []byte{0, 1, 2}},
		&pb.M1{F: proto.Int64(0)},
		&pb.M1{F: proto.Int64(100)},
		&pb.M1{F: proto.Int64(123123123123123123)},
		&pb.M1{F: proto.Int64(-100)},
		&pb.M1{F: proto.Int64(-123123123123123123)},
		&pb.M2{},
		&pb.M2{F: proto.Uint32(123123)},
		&pb.M3{},
		&pb.M3{F: proto.Uint64(123123123123123123)},
		&pb.M4{F: proto.Int32(123123)},
		&pb.M5{F: proto.Int64(123123)},
		&pb.M5{F: proto.Int64(-123123)},
		&pb.M6{XXX_unrecognized: []byte{0, 1, 2}},
		&pb.M6{F: proto.Uint32(123123), XXX_unrecognized: []byte{0, 1, 2}},
		&pb.M7{F: proto.Uint64(123123123123)},
		&pb.M8{F: proto.Int32(-123123)},
		&pb.M9{F: proto.Int64(-123123123123)},
		&pb.M10{F: proto.Float64(123123.123123)},
		&pb.M11{F: proto.Float32(123123.123123)},
		&pb.M12{F: proto.Bool(true)},
		&pb.M13{},
		&pb.M13{F: proto.String("")},
		&pb.M13{F: proto.String("foo")},
		&pb.M13{F: proto.String("&pb.M6{F: proto.Uint32(123123), XXX_unrecognized: []byte{0,1,2}},")},
		&pb.M13{F: proto.String("\x00\x01\x02")},
		&pb.M14{},
		&pb.M14{F: []byte{0, 1, 2}},
		&pb.M14{F: []byte("&pb.M6{F: proto.Uint32(123123), XXX_unrecognized: []byte{0,1,2}},")},
		&pb.M15{F0: proto.Int32(123)},
		&pb.M15{F0: proto.Int32(123), F1: proto.String("foo"), F2: []byte{1, 2, 3}, F4: proto.Bool(false)},
		&pb.M16{},
		&pb.M16{F: pb.Corpus_UNIVERSAL.Enum()},
		&pb.M16{F: pb.Corpus_PRODUCTS.Enum()},
		&pb.M17{F: &pb.M15{F0: proto.Int32(123)}},
		&pb.M17{F: &pb.M15{F0: proto.Int32(123), F1: proto.String("foo"), F2: []byte{1, 2, 3}, F4: proto.Bool(false)}},
		func() proto.Message {
			v := &pb.M18{F0: proto.String("foo")}
			proto.SetExtension(v, pb.E_F1, 42)
			return v
		}(),
		&pb.M19{},
		&pb.M19{F: []int32{0, -123, 500, 123123123}},
		&pb.M20{F: []string{"", "foo", "\x00\x01\x02"}},
		&pb.M21{F: []*pb.M15{&pb.M15{F0: proto.Int32(123)}, &pb.M15{F0: proto.Int32(123), F1: proto.String("foo"), F2: []byte{1, 2, 3}, F4: proto.Bool(false)}}},
		&pb.M22{F: []*pb.M2{&pb.M2{}}},
		&pb.M22{F: []*pb.M2{&pb.M2{}, &pb.M2{F: proto.Uint32(123123)}}},
		&pb.M23{},
		&pb.M23{F: map[int32]string{42: "", 11: "foo", 123123123: "\x00\x01\x02"}},
		&pb.M24{F: map[string]*pb.M2{"": &pb.M2{}, "foo": &pb.M2{}, "\x00\x01\x02": &pb.M2{F: proto.Uint32(123123)}}},
		&pb.M25{},
		&pb.M25{F0: proto.String("")},
		&pb.M25{F0: proto.String("foo")},
		&pb.M25{F1: &pb.M2{}},
		&pb.M25{F1: &pb.M2{F: proto.Uint32(123123)}},
		&pb.M25{F2: pb.Corpus_UNIVERSAL.Enum()},
	}
	for i, v := range vars {
		if false {
			data, err := proto.Marshal(v)
			if err != nil {
				panic(err)
			}
			f, err := os.Create(fmt.Sprintf("/tmp/proto/%v", i))
			if err != nil {
				panic(err)
			}
			f.Write(data)
			f.Close()
		} else {
			f, err := os.Create(fmt.Sprintf("/tmp/proto/%v", i))
			if err != nil {
				panic(err)
			}
			fmt.Printf("%v: %+v\n", i, v)
			err = proto.MarshalText(f, v)
			if err != nil {
				panic(err)
			}
			f.Close()
		}
	}
}
开发者ID:rlmcpherson,项目名称:go-fuzz,代码行数:86,代码来源:gen.go



注:本文中的github.com/golang/protobuf/proto.Float32函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang proto.Float64函数代码示例发布时间:2022-05-23
下一篇:
Golang proto.Equal函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap