Example #1
0
func LoadAvg() (s []string) {

	v, err := syscall.Sysctl(sysctl)
	t := time.Now()
	etime := strconv.FormatInt(t.Unix(), 10)

	if err != nil {
		fmt.Println(err)
	}
	b := []byte(v)
	var l loadavg = *(*loadavg)(unsafe.Pointer(&b[0]))

	scale := float64(l.scale)
	c := strconv.FormatFloat(float64(l.ldavg[0])/scale, 'f', 2, 64)
	d := strconv.FormatFloat(float64(l.ldavg[1])/scale, 'f', 2, 64)
	e := strconv.FormatFloat(float64(l.ldavg[2])/scale, 'f', 2, 64)

	// returning as load.load.metric because that's what collectd does
	f := fmt.Sprintf("load.load.shortterm %s %s", c, etime)
	s = append(s, f)
	g := fmt.Sprintf("load.load.midterm %s %s", d, etime)
	s = append(s, g)
	h := fmt.Sprintf("load.load.longterm %s %s", e, etime)
	s = append(s, h)
	return s
}
Example #2
0
func (h C1G2Summary) Execute(report gr.GoReport) {
	report.Font("MPBOLD", 9, "")
	y := 15.0
	report.CellRight(123, y, 20, "Total:")
	report.CellRight(150, y, 20, gr.AddComma(strconv.FormatFloat(
		report.SumWork["g2hrcum"], 'f', 1, 64))+" Hrs")
	report.CellRight(170, y, 26, gr.AddComma(strconv.FormatFloat(
		report.SumWork["g2amtcum"], 'f', 2, 64))+" USD")
	y = 25.0
	report.CellRight(123, y, 20, "Tax:")
	report.CellRight(150, y, 20, "7.75%")
	tax := report.SumWork["g2amtcum"] * 0.0775
	report.CellRight(170, y, 26, gr.AddComma(strconv.FormatFloat(
		tax, 'f', 2, 64))+" USD")
	report.LineType("straight", 0.3)
	report.LineH(170, 33, 199)
	y = 39.0
	report.Font("MPBOLD", 11, "")
	report.CellRight(123, y, 20, "AMOUT DUE:")
	report.CellRight(170, y, 26, gr.AddComma(strconv.FormatFloat(
		report.SumWork["g2amtcum"]+tax, 'f', 2, 64))+" USD")
	report.NewPage(true)
	report.SumWork["g2item"] = 0.0
	report.SumWork["g2hrcum"] = 0.0
	report.SumWork["g2amtcum"] = 0.0
}
func getGoogLocation(address string) OutputAddress {
	client := &http.Client{}
	reqURL := "http://maps.google.com/maps/api/geocode/json?address="
	reqURL += url.QueryEscape(address)
	reqURL += "&sensor=false"
	fmt.Println("URL formed: " + reqURL)
	req, err := http.NewRequest("GET", reqURL, nil)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("error in sending req to google: ", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("error in reading response: ", err)
	}
	var res GoogleResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		fmt.Println("error in unmashalling response: ", err)
	}

	//The func to find google's response

	var ret OutputAddress
	ret.Coordinate.Lat = strconv.FormatFloat(res.Results[0].Geometry.Location.Lat, 'f', 7, 64)
	ret.Coordinate.Lang = strconv.FormatFloat(res.Results[0].Geometry.Location.Lng, 'f', 7, 64)

	return ret
}
Example #4
0
// ToString gets the string representation of the datum.
func (d *Datum) ToString() (string, error) {
	switch d.Kind() {
	case KindInt64:
		return strconv.FormatInt(d.GetInt64(), 10), nil
	case KindUint64:
		return strconv.FormatUint(d.GetUint64(), 10), nil
	case KindFloat32:
		return strconv.FormatFloat(float64(d.GetFloat32()), 'f', -1, 32), nil
	case KindFloat64:
		return strconv.FormatFloat(float64(d.GetFloat64()), 'f', -1, 64), nil
	case KindString:
		return d.GetString(), nil
	case KindBytes:
		return d.GetString(), nil
	case KindMysqlTime:
		return d.GetMysqlTime().String(), nil
	case KindMysqlDuration:
		return d.GetMysqlDuration().String(), nil
	case KindMysqlDecimal:
		return d.GetMysqlDecimal().String(), nil
	case KindMysqlHex:
		return d.GetMysqlHex().ToString(), nil
	case KindMysqlBit:
		return d.GetMysqlBit().ToString(), nil
	case KindMysqlEnum:
		return d.GetMysqlEnum().String(), nil
	case KindMysqlSet:
		return d.GetMysqlSet().String(), nil
	default:
		return "", errors.Errorf("cannot convert %v(type %T) to string", d.GetValue(), d.GetValue())
	}
}
Example #5
0
// Coerce types (string,int,int64, float, []byte) into String type
func CoerceString(v interface{}) (string, error) {
	switch val := v.(type) {
	case string:
		if val == "null" || val == "NULL" {
			return "", nil
		}
		return val, nil
	case int:
		return strconv.Itoa(val), nil
	case int32:
		return strconv.FormatInt(int64(val), 10), nil
	case int64:
		return strconv.FormatInt(val, 10), nil
	case uint32:
		return strconv.FormatUint(uint64(val), 10), nil
	case uint64:
		return strconv.FormatUint(val, 10), nil
	case float32:
		return strconv.FormatFloat(float64(val), 'f', -1, 32), nil
	case float64:
		return strconv.FormatFloat(val, 'f', -1, 64), nil
	case []byte:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	case json.RawMessage:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	}
	return "", fmt.Errorf("Could not coerce to string: %v", v)
}
Example #6
0
//checkResults checks the results between
func checkResults() string {
	for metric, expected := range expectedValues {
		switch m := metric.(type) {
		case *metrics.Counter:
			val, ok := expected.(uint64)
			if !ok {
				return "unexpected type"
			}
			if m.Get() != val {
				return ("unexpected value - got: " +
					strconv.FormatInt(int64(m.Get()), 10) + " but wanted " + strconv.FormatInt(int64(val), 10))
			}
		case *metrics.Gauge:
			val, ok := expected.(float64)
			if !ok {
				return "unexpected type"
			}
			if m.Get() != val {
				return ("unexpected value - got: " +
					strconv.FormatFloat(float64(m.Get()), 'f', 5, 64) + " but wanted " +
					strconv.FormatFloat(float64(val), 'f', 5, 64))
			}
		}
	}
	return ""
}
Example #7
0
// SendLocation sends a location to a chat.
//
// Requires ChatID, Latitude, and Longitude.
// ReplyToMessageID and ReplyMarkup are optional.
func (bot *BotAPI) SendLocation(config LocationConfig) (Message, error) {
	v := url.Values{}
	v.Add("chat_id", strconv.Itoa(config.ChatID))
	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
	if config.ReplyToMessageID != 0 {
		v.Add("reply_to_message_id", strconv.Itoa(config.ReplyToMessageID))
	}
	if config.ReplyMarkup != nil {
		data, err := json.Marshal(config.ReplyMarkup)
		if err != nil {
			return Message{}, err
		}

		v.Add("reply_markup", string(data))
	}

	resp, err := bot.MakeRequest("sendLocation", v)
	if err != nil {
		return Message{}, err
	}

	var message Message
	json.Unmarshal(resp.Result, &message)

	if bot.Debug {
		log.Printf("sendLocation req : %+v\n", v)
		log.Printf("sendLocation resp: %+v\n", message)
	}

	return message, nil
}
Example #8
0
func StreamRun(model_file string, instances []string) (string, error) {
	log := util.GetLogger()
	if !util.FileExists(model_file) || len(instances) == 0 {
		log.Error("[Predictor-StreamRun] Model file or instances error.")
		return fmt.Sprintf(errorjson, "[Predictor-StreamRun] Model file or instances error."), errors.New("[Predictor-StreamRun] Model file or instances error.")
	}

	var rtstr string
	var model solver.LRModel
	model.Initialize(model_file)
	for i := 0; i < len(instances); i++ {
		res, _, x := util.ParseSample(instances[i])
		if res != nil {
			break
		}

		pred := model.Predict(x)
		pred = math.Max(math.Min(pred, 1.-10e-15), 10e-15)
		if i == len(instances)-1 {
			rtstr += strconv.FormatFloat(pred, 'f', 6, 64)
		} else {
			rtstr += strconv.FormatFloat(pred, 'f', 6, 64) + ","
		}
	}

	return fmt.Sprintf(streamjson, rtstr), nil
}
Example #9
0
func ToString(a interface{}) string {

	if v, p := a.(int); p {
		return strconv.Itoa(v)
	}

	if v, p := a.(float64); p {
		return strconv.FormatFloat(v, 'f', -1, 64)
	}

	if v, p := a.(float32); p {
		return strconv.FormatFloat(float64(v), 'f', -1, 32)
	}

	if v, p := a.(int16); p {
		return strconv.Itoa(int(v))
	}
	if v, p := a.(uint); p {
		return strconv.Itoa(int(v))
	}
	if v, p := a.(int32); p {
		return strconv.Itoa(int(v))
	}
	return "wrong"
}
Example #10
0
func appInfoHandler(w rest.ResponseWriter, r *rest.Request) {
	var marathonApps marathon.MarathonAppsGlobalInfoResponse
	fasthttp.JsonReqAndResHandler(goCore.MarathonAppsUrl, nil, &marathonApps, "GET")
	appsCnt := len(marathonApps.Apps)

	// should not code like this: appsGlobalInfos := [appsCnt]entity.AppsGlobalInfo{}
	appsGlobalInfos := make([]dto.AppsGlobalInfoResponse, appsCnt)

	for i, v := range marathonApps.Apps {
		var perApp dto.AppsGlobalInfoResponse
		if strings.LastIndex(v.Id, "/") == -1 {
			perApp.Id = v.Id
		} else {
			perApp.Id = v.Id[strings.LastIndex(v.Id, "/")+1:]
		}
		perApp.Cpus = strconv.FormatFloat(v.Cpus, 'f', 1, 64)
		perApp.CurrentInstances = strconv.Itoa(v.TasksRunning)
		fmt.Println(v)
		if strings.LastIndex(v.Id, "/") <= 0 { // exclude like /zk or zk
			perApp.Group = "No Groups"
		} else {
			perApp.Group = v.Id[0:strings.LastIndex(v.Id, "/")]
		}
		perApp.Instances = strconv.Itoa(v.Instances)
		perApp.Mem = strconv.FormatFloat(v.Mem, 'f', 1, 64)
		if v.TasksHealthy == 0 && v.TasksUnhealthy == 0 { // when no and healthy check
			perApp.Healthy = "100"
		} else {
			perApp.Healthy = strconv.FormatFloat(float64(v.TasksHealthy)/float64(v.TasksHealthy+v.TasksUnhealthy), 'f', 1, 64)
		}
		perApp.FormatStatus(v.TasksStaged)
		appsGlobalInfos[i] = perApp
	}
	w.WriteJson(appsGlobalInfos)
}
Example #11
0
func encodeBasic(v reflect.Value) string {
	t := v.Type()
	switch k := t.Kind(); k {
	case reflect.Bool:
		return strconv.FormatBool(v.Bool())
	case reflect.Int,
		reflect.Int8,
		reflect.Int16,
		reflect.Int32,
		reflect.Int64:
		return strconv.FormatInt(v.Int(), 10)
	case reflect.Uint,
		reflect.Uint8,
		reflect.Uint16,
		reflect.Uint32,
		reflect.Uint64:
		return strconv.FormatUint(v.Uint(), 10)
	case reflect.Float32:
		return strconv.FormatFloat(v.Float(), 'g', -1, 32)
	case reflect.Float64:
		return strconv.FormatFloat(v.Float(), 'g', -1, 64)
	case reflect.Complex64, reflect.Complex128:
		s := fmt.Sprintf("%g", v.Complex())
		return strings.TrimSuffix(strings.TrimPrefix(s, "("), ")")
	case reflect.String:
		return v.String()
	}
	panic(t.String() + " has unsupported kind " + t.Kind().String())
}
Example #12
0
func (b *Balance) SetValue(amount float64) {
	b.Value = amount
	b.Value = utils.Round(b.GetValue(), globalRoundingDecimals, utils.ROUNDING_MIDDLE)
	b.dirty = true

	// publish event
	accountId := ""
	allowNegative := ""
	disabled := ""
	if b.account != nil {
		accountId = b.account.Id
		allowNegative = strconv.FormatBool(b.account.AllowNegative)
		disabled = strconv.FormatBool(b.account.Disabled)
	}
	Publish(CgrEvent{
		"EventName":            utils.EVT_ACCOUNT_BALANCE_MODIFIED,
		"Uuid":                 b.Uuid,
		"Id":                   b.Id,
		"Value":                strconv.FormatFloat(b.Value, 'f', -1, 64),
		"ExpirationDate":       b.ExpirationDate.String(),
		"Weight":               strconv.FormatFloat(b.Weight, 'f', -1, 64),
		"DestinationIds":       b.DestinationIds,
		"RatingSubject":        b.RatingSubject,
		"Category":             b.Category,
		"SharedGroup":          b.SharedGroup,
		"TimingIDs":            b.TimingIDs,
		"Account":              accountId,
		"AccountAllowNegative": allowNegative,
		"AccountDisabled":      disabled,
	})
}
Example #13
0
func (m *floatValueValidation) Validate(value interface{}, obj reflect.Value) *ValidationError {
	var compareValue float64
	switch value := value.(type) {
	case float32:
		compareValue = float64(value)
	case float64:
		compareValue = float64(value)
	default:
		return &ValidationError{
			Key:     m.FieldName(),
			Message: "is not convertible to type float64",
		}
	}

	if m.less {
		if compareValue < m.value {
			return &ValidationError{
				Key:     m.FieldName(),
				Message: "must be greater than or equal to " + strconv.FormatFloat(m.value, 'E', -1, 64),
			}
		}
	} else {
		if compareValue > m.value {
			return &ValidationError{
				Key:     m.FieldName(),
				Message: "must be less than or equal to " + strconv.FormatFloat(m.value, 'E', -1, 64),
			}
		}
	}

	return nil
}
Example #14
0
func GetTimers(request *Request) []string {
	offset := 0
	timers := make([]string, len(request.TimerValue))
	for idx, val := range request.TimerValue {
		var timer bytes.Buffer
		var cputime float64 = 0.0
		if len(request.TimerUtime) == len(request.TimerValue) {
			cputime = float64(request.TimerUtime[idx] + request.TimerStime[idx])
		}

		timer.WriteString("Val: ")
		timer.WriteString(strconv.FormatFloat(float64(val), 'f', 4, 64))
		timer.WriteString(" Hit: ")
		timer.WriteString(strconv.FormatInt(int64(request.TimerHitCount[idx]), 10))
		timer.WriteString(" CPU: ")
		timer.WriteString(strconv.FormatFloat(cputime, 'f', 4, 64))
		timer.WriteString(" Tags: ")

		for k, key_idx := range request.TimerTagName[offset : offset+int(request.TimerTagCount[idx])] {
			val_idx := request.TimerTagValue[int(offset)+k]
			if val_idx >= uint32(len(request.Dictionary)) || key_idx >= uint32(len(request.Dictionary)) {
				continue
			}
			timer.WriteString(" ")
			timer.WriteString(request.Dictionary[key_idx])
			timer.WriteString("=")
			timer.WriteString(request.Dictionary[val_idx])
		}

		timers[idx] = timer.String()
		offset += int(request.TimerTagCount[idx])
	}
	return timers
}
Example #15
0
func (this *Probability) computeProbability(tag string, prob float64, s string) float64 {
	x := prob
	spos := len(s)
	found := true
	var pt float64
	TRACE(4, " suffixes. Tag "+tag+" initial prob="+strconv.FormatFloat(prob, 'f', -1, 64), MOD_PROBABILITY)
	for spos > 0 && found {
		spos--
		is := this.unkSuffS[s[spos:]]
		found = is != nil
		if found {
			pt = is[tag]
			if pt != 0 {
				TRACE(4, "    found prob for suffix -"+s[spos:], MOD_PROBABILITY)
			} else {
				pt = 0
				TRACE(4, "    NO prob found for suffix -"+s[spos:], MOD_PROBABILITY)
			}

			x = (pt + this.theeta*x) / (1 + this.theeta)
		}
	}

	TRACE(4, "      final prob="+strconv.FormatFloat(x, 'f', -1, 64), MOD_PROBABILITY)
	return x
}
Example #16
0
File: cmd.go Project: Endika/tsuru
func (c *autoScaleInfoCmd) render(context *cmd.Context, config *autoScaleConfig, rules []autoScaleRule) error {
	fmt.Fprintf(context.Stdout, "Metadata filter: %s\n\n", config.GroupByMetadata)
	var table cmd.Table
	tableHeader := []string{
		"Filter value",
		"Max container count",
		"Max memory ratio",
		"Scale down ratio",
		"Rebalance on scale",
		"Enabled",
	}
	table.Headers = tableHeader
	for _, rule := range rules {
		table.AddRow([]string{
			rule.MetadataFilter,
			strconv.Itoa(rule.MaxContainerCount),
			strconv.FormatFloat(float64(rule.MaxMemoryRatio), 'f', 4, 32),
			strconv.FormatFloat(float64(rule.ScaleDownRatio), 'f', 4, 32),
			strconv.FormatBool(!rule.PreventRebalance),
			strconv.FormatBool(rule.Enabled),
		})
	}
	fmt.Fprintf(context.Stdout, "Rules:\n%s", table.String())
	return nil
}
Example #17
0
// ToString converts a interface to a string.
func ToString(value interface{}) (string, error) {
	switch v := value.(type) {
	case bool:
		if v {
			return "1", nil
		}
		return "0", nil
	case int:
		return strconv.FormatInt(int64(v), 10), nil
	case int64:
		return strconv.FormatInt(int64(v), 10), nil
	case uint64:
		return strconv.FormatUint(uint64(v), 10), nil
	case float32:
		return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
	case float64:
		return strconv.FormatFloat(float64(v), 'f', -1, 64), nil
	case string:
		return v, nil
	case []byte:
		return string(v), nil
	case mysql.Time:
		return v.String(), nil
	case mysql.Duration:
		return v.String(), nil
	case mysql.Decimal:
		return v.String(), nil
	case mysql.Hex:
		return v.ToString(), nil
	case mysql.Bit:
		return v.ToString(), nil
	default:
		return "", errors.Errorf("cannot convert %v(type %T) to string", value, value)
	}
}
Example #18
0
// Exchange is used to perform an exchange rate conversion.
func (j *JarvisBot) Exchange(msg *message) {
	if len(msg.Args) == 0 {
		so := &telebot.SendOptions{ReplyTo: *msg.Message, ReplyMarkup: telebot.ReplyMarkup{ForceReply: true, Selective: true}}
		j.bot.SendMessage(msg.Chat, "/xchg: Do an exchange rate conversion\nHere are some commands to try: \n* 10 sgd in usd\n* 100 vnd to sgd\n* 21 usd how much arr?\n\n\U0001F4A1 You could also use this format for faster results:\n/x 10 sgd in usd", so)
		return
	}

	amount, fromCurr, toCurr := parseArgs(msg.Args)
	if amount == 0.0 || fromCurr == "" || toCurr == "" {
		j.bot.SendMessage(msg.Chat, "I didn't understand that. Here are some commands to try: \n/xchg 10 sgd in usd\n/xchg 100 vnd to sgd\n/xchg 21 usd how much arr?", nil)
		return
	}

	fromCurrRate, toCurrRate, err := j.getRatesFromDB(fromCurr, toCurr)
	if err != nil {
		j.log.Printf("[%s] problem with retrieving rates: %s", time.Now().Format(time.RFC3339), err)
		return
	}

	res := amount * 1 / fromCurrRate * toCurrRate
	displayRate := 1 / fromCurrRate * toCurrRate

	strDisplayRate := strconv.FormatFloat(displayRate, 'f', 5, 64)
	fmtAmount := strconv.FormatFloat(res, 'f', 2, 64)

	j.bot.SendMessage(msg.Chat, fromCurr+" to "+toCurr+"\nRate: 1.00 : "+strDisplayRate+"\n"+strconv.FormatFloat(amount, 'f', 2, 64)+" "+fromCurr+" = "+fmtAmount+" "+toCurr, nil)
}
Example #19
0
func handleUpdate() error {
	var api string
	flag.StringVar(&api, "api", "", "Binding host:port for http/artifact server. Optional if SM_API env is set.")
	flag.StringVar(&statsd.Config.ProducerProperties, "producer.properties", "", "Producer.properties file name.")
	flag.StringVar(&statsd.Config.Topic, "topic", "", "Topic to produce data to.")
	flag.StringVar(&statsd.Config.Transform, "transform", "", "Transofmation to apply to each metric. none|avro|proto")
	flag.StringVar(&statsd.Config.SchemaRegistryUrl, "schema.registry.url", "", "Avro Schema Registry url for transform=avro")
	flag.Float64Var(&statsd.Config.Cpus, "cpu", 0.1, "CPUs per task")
	flag.Float64Var(&statsd.Config.Mem, "mem", 64, "Mem per task")

	flag.Parse()

	if err := resolveApi(api); err != nil {
		return err
	}

	request := statsd.NewApiRequest(statsd.Config.Api + "/api/update")
	request.AddParam("producer.properties", statsd.Config.ProducerProperties)
	request.AddParam("topic", statsd.Config.Topic)
	request.AddParam("transform", statsd.Config.Transform)
	request.AddParam("schema.registry.url", statsd.Config.SchemaRegistryUrl)
	request.AddParam("cpu", strconv.FormatFloat(statsd.Config.Cpus, 'E', -1, 64))
	request.AddParam("mem", strconv.FormatFloat(statsd.Config.Mem, 'E', -1, 64))
	response := request.Get()

	fmt.Println(response.Message)

	return nil
}
Example #20
0
// 类型转换为字符串
// 返回值:
// string:结果
// bool:是否转换成功
func String(val interface{}) (string, bool) {
	if val == nil {
		return "", false
	}

	switch val.(type) {
	case int:
		return string(val.(int)), true
	case int32:
		return string(val.(int32)), true
	case int64:
		return string(val.(int64)), true
	case int8:
		return string(val.(int8)), true
	case int16:
		return string(val.(int16)), true
	case float32:
		return strconv.FormatFloat(float64(val.(float32)), 'F', 5, 32), true
	case float64:
		return strconv.FormatFloat(val.(float64), 'F', 5, 64), true
	case string:
		return val.(string), true
	}

	return "", false
}
func (pdb *PolicyDB) UpdatePolicy(policy Policy) error {
	q := "UPDATE policies SET "
	if policy.Metric_type != 0 {
		q = q + "metric_type = " + strconv.Itoa(policy.Metric_type) + ", "
	}
	if policy.Upper_threshold != 0 {
		q = q + "upper_threshold = " + strconv.FormatFloat(policy.Upper_threshold, 'f', 6, 64) + ", "
	}
	if policy.Lower_threshold != 0 {
		q = q + "lower_threshold = " + strconv.FormatFloat(policy.Lower_threshold, 'f', 6, 64) + ", "
	}
	if policy.Instances_out != 0 {
		q = q + "instances_out = " + strconv.Itoa(policy.Instances_out) + ", "
	}
	if policy.Instances_in != 0 {
		q = q + "instances_in = " + strconv.Itoa(policy.Instances_in) + ", "
	}
	if policy.Cooldown_period != 0 {
		q = q + "cooldown_period = " + strconv.Itoa(policy.Cooldown_period) + ", "
	}
	if policy.Measurement_period != 0 {
		q = q + "measurement_period = " + strconv.Itoa(policy.Measurement_period) + ", "
	}

	q = q + " deleted = " + strconv.FormatBool(policy.Deleted)
	q = q + " WHERE policy_uuid = '" + policy.Policy_uuid + "'"

	_, err := pdb.db.Exec(q)
	if err != nil {
		return err
	}

	return nil
}
Example #22
0
func main() {
	in := bufio.NewScanner(os.Stdin)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(os.Stdout)
	if in.Scan() {
		t, _ := strconv.Atoi(in.Text())
		p, n, z := 0, 0, 0
		for i := 0; i < t && in.Scan(); i++ {
			x, _ := strconv.Atoi(in.Text())
			if x < 0 {
				n++
			} else if x == 0 {
				z++
			} else {
				p++
			}
		}
		out.WriteString(strconv.FormatFloat(float64(p)/float64(t), 'f', 6, 64))
		out.WriteString("\n")
		out.WriteString(strconv.FormatFloat(float64(n)/float64(t), 'f', 6, 64))
		out.WriteString("\n")
		out.WriteString(strconv.FormatFloat(float64(z)/float64(t), 'f', 6, 64))
	}
	out.Flush()
}
Example #23
0
func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error {
	switch value := r.Interface().(type) {
	case string:
		v.Set(name, value)
	case []byte:
		if !r.IsNil() {
			v.Set(name, base64.StdEncoding.EncodeToString(value))
		}
	case bool:
		v.Set(name, strconv.FormatBool(value))
	case int64:
		v.Set(name, strconv.FormatInt(value, 10))
	case int:
		v.Set(name, strconv.Itoa(value))
	case float64:
		v.Set(name, strconv.FormatFloat(value, 'f', -1, 64))
	case float32:
		v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32))
	case time.Time:
		const ISO8601UTC = "2006-01-02T15:04:05Z"
		v.Set(name, value.UTC().Format(ISO8601UTC))
	default:
		return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name())
	}
	return nil
}
func (so *StockObject) CheckPortfolio(tradeID int, rsp *PortfolioResponseObject) error {

	if objValues, ok := so.StockPF[tradeID]; ok {

		var currentMarketValue float32
		for stockSymbol, so := range objValues.Stocks {

			financeAPIPrice := callYahooAPI(stockSymbol)

			var result string
			if so.PurchasedPrice < financeAPIPrice {
				result = "+$" + strconv.FormatFloat(float64(financeAPIPrice), 'f', 2, 32)
			} else if so.PurchasedPrice > financeAPIPrice {
				result = "-$" + strconv.FormatFloat(float64(financeAPIPrice), 'f', 2, 32)
			} else {
				result = "$" + strconv.FormatFloat(float64(financeAPIPrice), 'f', 2, 32)
			}
			stock := stockSymbol + ":" + strconv.Itoa(so.SharesCount) + ":" + result

			rsp.Stocks = append(rsp.Stocks, stock)

			currentMarketValue += float32(so.SharesCount) * financeAPIPrice
		}
		fmt.Print("Unvested amount zz is", objValues.UnvestedAmount)
		rsp.UnvestedAmount = objValues.UnvestedAmount
		rsp.CurrentMarketValue = currentMarketValue
	} else {
		return errors.New("Trade ID doesnt exist")
	}

	return nil
}
Example #25
0
func statCallback(id string, stat *dockerclient.Stats, ec chan error, args ...interface{}) {

	//fmt.Println("STATS", id, stat)

	// fmt.Println("---")
	// fmt.Println("cpu :", float64(stat.CpuStats.CpuUsage.TotalUsage)/float64(stat.CpuStats.SystemUsage))
	// fmt.Println("ram :", stat.MemoryStats.Usage)

	client := &http.Client{}

	memPercent := float64(stat.MemoryStats.Usage) / float64(stat.MemoryStats.Limit) * 100.0

	var cpuPercent float64 = 0.0

	if preCPUStats, exists := previousCPUStats[id]; exists {

		cpuPercent = calculateCPUPercent(preCPUStats, &stat.CpuStats)

	}

	previousCPUStats[id] = &CPUStats{TotalUsage: stat.CpuStats.CpuUsage.TotalUsage, SystemUsage: stat.CpuStats.SystemUsage}

	data := url.Values{
		"action": {"stats"},
		"id":     {id},
		"cpu":    {strconv.FormatFloat(cpuPercent, 'f', 2, 64) + "%"},
		"ram":    {strconv.FormatFloat(memPercent, 'f', 2, 64) + "%"}}

	MCServerRequest(data, client)
}
Example #26
0
// Create new offer for LEND or LOAN a currency, use LEND or LOAN constants as direction
func (s *OffersService) New(currency string, amount, rate float64, period int64, direction string) (Offer, error) {

	payload := map[string]interface{}{
		"currency":  currency,
		"amount":    strconv.FormatFloat(amount, 'f', -1, 32),
		"rate":      strconv.FormatFloat(rate, 'f', -1, 32),
		"period":    strconv.FormatInt(period, 10),
		"direction": direction,
	}

	req, err := s.client.newAuthenticatedRequest("POST", "offers/new", payload)

	if err != nil {
		return Offer{}, err
	}

	var offer = &Offer{}
	_, err = s.client.do(req, offer)

	if err != nil {
		return Offer{}, err
	}

	return *offer, nil

}
Example #27
0
File: site.go Project: GeoNet/delta
func (s SiteList) encode() [][]string {
	data := [][]string{{
		"Station",
		"Location",
		"Latitude",
		"Longitude",
		"Elevation",
		"Datum",
		"Survey",
		"Start Date",
		"End Date",
	}}
	for _, v := range s {
		data = append(data, []string{
			strings.TrimSpace(v.Station),
			strings.TrimSpace(v.Location),
			strconv.FormatFloat(v.Latitude, 'g', -1, 64),
			strconv.FormatFloat(v.Longitude, 'g', -1, 64),
			strconv.FormatFloat(v.Elevation, 'g', -1, 64),
			strings.TrimSpace(v.Datum),
			strings.TrimSpace(v.Survey),
			v.Start.Format(DateTimeFormat),
			v.End.Format(DateTimeFormat),
		})
	}
	return data
}
Example #28
0
func Format_size(size int64) string {
	//size = 1073741824
	if size >= 1099511627776 {
		if size%1099511627776 == 0 {
			return strconv.FormatInt(size/1099511627776, 10) + " T"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1099511627776), 'f', 2, 64) + " T"
		}

	} else if size >= 1073741824 {
		if size%1073741824 == 0 {
			return strconv.FormatInt(size/1073741824, 10) + " G"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1073741824), 'f', 2, 64) + " G"
		}

	} else if size >= 1048576 {
		if size%1048576 == 0 {
			return strconv.FormatInt(size/1048576, 10) + " M"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1048576), 'f', 2, 64) + " M"
		}

	} else if size >= 1024 {
		if size%1024 == 0 {
			return strconv.FormatInt(size/1024, 10) + " K"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1024), 'f', 2, 64) + " K"
		}

	} else {
		return strconv.FormatInt(size, 10) + " B"
	}

}
func getUberCost(start locationStruct, end locationStruct) (int, int, float64, string) {

	uberURL := strings.Replace(uberRequestURL, startLatitude, strconv.FormatFloat(start.Coordinate.Lat, 'f', -1, 64), -1)
	uberURL = strings.Replace(uberURL, startLongitude, strconv.FormatFloat(start.Coordinate.Lng, 'f', -1, 64), -1)
	uberURL = strings.Replace(uberURL, endLatitude, strconv.FormatFloat(end.Coordinate.Lat, 'f', -1, 64), -1)
	uberURL = strings.Replace(uberURL, endLongitude, strconv.FormatFloat(end.Coordinate.Lng, 'f', -1, 64), -1)

	res, err := http.Get(uberURL)

	if err != nil {

		//w.Write([]byte(`{    "error": "Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75"}`))
		fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75")
		panic(err.Error())
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {

		//w.Write([]byte(`{    "error": "Unable to parse data from Google. body, err := ioutil.ReadAll(res.Body) -- line 84"}`))
		fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 84")
		panic(err.Error())
	}

	var uberResult UberResults
	_ = json.Unmarshal(body, &uberResult)

	return uberResult.Prices[0].LowEstimate, uberResult.Prices[0].Duration, uberResult.Prices[0].Distance, uberResult.Prices[0].ProductID
}
Example #30
0
File: writer.go Project: gwenn/yacr
// WriteValue ensures that value is quoted when needed.
// Value's type/kind is used to encode value to text.
func (w *Writer) WriteValue(value interface{}) bool {
	switch value := value.(type) {
	case nil:
		return w.Write([]byte{})
	case string:
		return w.WriteString(value)
	case int:
		return w.WriteString(strconv.Itoa(value))
	case int32:
		return w.WriteString(strconv.FormatInt(int64(value), 10))
	case int64:
		return w.WriteString(strconv.FormatInt(value, 10))
	case bool:
		return w.WriteString(strconv.FormatBool(value))
	case float32:
		return w.WriteString(strconv.FormatFloat(float64(value), 'f', -1, 32))
	case float64:
		return w.WriteString(strconv.FormatFloat(value, 'f', -1, 64))
	case []byte:
		return w.Write(value)
	case encoding.TextMarshaler: // time.Time
		if text, err := value.MarshalText(); err != nil {
			w.setErr(err)
			w.Write([]byte{}) // TODO Validate: write an empty field
			return false
		} else {
			return w.Write(text) // please, ignore golint
		}
	default:
		return w.writeReflect(value)
	}
}