本文整理汇总了Golang中fmt.Printf函数的典型用法代码示例。如果您正苦于以下问题:Golang Printf函数的具体用法?Golang Printf怎么用?Golang Printf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Printf函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: processAmqp
// Process messages from the AMQP queues
func processAmqp(username, amqpAddress string) {
// Open the queue and then begin processing messages
// If we drop out of the processing function, wait
// a little while and try again
for {
fmt.Printf("######################################################################################################\n")
fmt.Printf("UTM-API service (%s) REST interface opening %s...\n", globals.LogTag, amqpAddress)
q, err := OpenQueue(username, amqpAddress)
if err == nil {
defer q.Close()
fmt.Printf("%s [server] --> connection opened.\n", globals.LogTag)
downlinkMessages = q.Downlink
// The meat is in here
processDatagrams(q)
} else {
globals.Dbg.PrintfTrace("%s [server] --> error opening AMQP queue (%s).\n", globals.LogTag, err.Error())
}
amqpRetryCount++
globals.Dbg.PrintfTrace("%s [server] --> waiting before trying again...\n", globals.LogTag)
time.Sleep(time.Second * 10)
}
}
开发者ID:mmanjoura,项目名称:utm,代码行数:31,代码来源:server.go
示例2: handlePacket
func handlePacket(buffer []byte) {
parser := rfc5424.NewParser(buffer)
err := parser.Parse()
if err != nil {
fmt.Printf("Error reading syslog message %s", err)
return
}
log := parser.Dump()
log["@timestamp"] = log["timestamp"]
log["facility_label"] = FACILITY_LABELS[(log["facility"]).(int)]
log["severity_label"] = SEVERITY_LABELS[(log["severity"]).(int)]
log["type"] = "syslog"
now := time.Now()
index := "logstash-" + now.Format("2006.01.02")
_, err = elasticSearch.Index(true, index, "logs", "", log)
if err != nil {
fmt.Printf("Error indexing message %s", err)
return
}
fmt.Println("Logged")
}
开发者ID:postfix,项目名称:logflume,代码行数:25,代码来源:logflume.go
示例3: main
func main() {
n := 0
if len(os.Args) > 1 {
n, _ = strconv.Atoi(os.Args[1])
}
minDepth := 4
maxDepth := minDepth + 2
if maxDepth < n {
maxDepth = n
}
stretchDepth := maxDepth + 1
check := create(0, stretchDepth).Check()
fmt.Printf("stretch tree of depth %d\t check: %d\n", stretchDepth, check)
longLivedTree := create(0, maxDepth)
for depth := minDepth; depth <= maxDepth; depth += 2 {
iterations := 1 << uint(maxDepth-depth+minDepth)
check = 0
for i := 1; i <= iterations; i++ {
check += create(i, depth).Check()
check += create(-i, depth).Check()
}
fmt.Printf("%d\t trees of depth %d\t check: %d\n", 2*iterations, depth, check)
}
fmt.Printf("long lived tree of depth %d\t check: %d\n", maxDepth, longLivedTree.Check())
}
开发者ID:MasayukiNagamachi,项目名称:naive-bench,代码行数:30,代码来源:binarytrees.go
示例4: TestCalibrateThreshold
func TestCalibrateThreshold(t *testing.T) {
if !*calibrate {
t.Log("not calibrating, use -calibrate to do so.")
return
}
lower := int(1e3) // math/big is faster at this size.
upper := int(300e3) // FFT is faster at this size.
big, fft := measureMul(lower)
lowerX := float64(big) / float64(fft)
fmt.Printf("speedup at size %d: %.2f\n", lower, lowerX)
big, fft = measureMul(upper)
upperX := float64(big) / float64(fft)
fmt.Printf("speedup at size %d: %.2f\n", upper, upperX)
for {
mid := (lower + upper) / 2
big, fft := measureMul(mid)
X := float64(big) / float64(fft)
fmt.Printf("speedup at size %d: %.2f\n", mid, X)
switch {
case X < 0.98:
lower = mid
lowerX = X
case X > 1.02:
upper = mid
upperX = X
default:
fmt.Printf("speedup at size %d: %.2f\n", lower, lowerX)
fmt.Printf("speedup at size %d: %.2f\n", upper, upperX)
return
}
}
}
开发者ID:remyoudompheng,项目名称:bigfft,代码行数:34,代码来源:calibrate_test.go
示例5: TestChan3
func TestChan3() {
fmt.Println("@@@@@@@@@@@@ TestChan 3")
fmt.Printf("cpu num: %d\n", runtime.NumCPU()) // 8核cpu
// 虽然goroutine是并发执行的,但是它们并不是并行运行的。如果不告诉Go额外的东西,同
// 一时刻只会有一个goroutine执行。利用runtime.GOMAXPROCS(n)可以设置goroutine
// 并行执行的数量。GOMAXPROCS 设置了同时运行的CPU 的最大数量,并返回之前的设置。
val := runtime.GOMAXPROCS(runtime.NumCPU() * 4)
fmt.Printf("last goroutine num: %d\n", val) // 8个
fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 4个goroutine同时运行
var ch1 chan int = make(chan int, 0)
var ch2 chan int = make(chan int, 0)
var ch3 chan int = make(chan int, 0)
go write(ch1, 22)
go write(ch2, 33)
go write(ch3, 44)
go read(ch1)
go read(ch2)
go read(ch3)
fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 10个goroutine同时运行
sleep("TestChan3", 3)
}
开发者ID:47045039,项目名称:GoSnippet,代码行数:27,代码来源:tch.go
示例6: drawFittedTableQLetters
//line fitted_type.got:17
func drawFittedTableQLetters(rSeq, qSeq alphabet.QLetters, index alphabet.Index, table []int, a [][]int) {
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 0, ' ', tabwriter.AlignRight|tabwriter.Debug)
fmt.Printf("rSeq: %s\n", rSeq)
fmt.Printf("qSeq: %s\n", qSeq)
fmt.Fprint(tw, "\tqSeq\t")
for _, l := range qSeq {
fmt.Fprintf(tw, "%c\t", l)
}
fmt.Fprintln(tw)
r, c := rSeq.Len()+1, qSeq.Len()+1
fmt.Fprint(tw, "rSeq\t")
for i := 0; i < r; i++ {
if i != 0 {
fmt.Fprintf(tw, "%c\t", rSeq[i-1].L)
}
for j := 0; j < c; j++ {
p := pointerFittedQLetters(rSeq, qSeq, i, j, table, index, a, c)
if p != "" {
fmt.Fprintf(tw, "%s % 3v\t", p, table[i*c+j])
} else {
fmt.Fprintf(tw, "%v\t", table[i*c+j])
}
}
fmt.Fprintln(tw)
}
tw.Flush()
}
开发者ID:krieg,项目名称:biogo,代码行数:30,代码来源:fitted_qletters.go
示例7: urlShortenerMain
func urlShortenerMain(client *http.Client, argv []string) {
if len(argv) != 1 {
fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx (to look up details)\n")
fmt.Fprintf(os.Stderr, " urlshortener http://example.com/long (to shorten)\n")
return
}
svc, _ := urlshortener.New(client)
urlstr := argv[0]
// short -> long
if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
url, err := svc.Url.Get(urlstr).Do()
if err != nil {
log.Fatalf("URL Get: %v", err)
}
fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
return
}
// long -> short
url, err := svc.Url.Insert(&urlshortener.Url{
Kind: "urlshortener#url", // Not really needed
LongUrl: urlstr,
}).Do()
if err != nil {
log.Fatalf("URL Insert: %v", err)
}
fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
开发者ID:GamerockSA,项目名称:dex,代码行数:30,代码来源:urlshortener.go
示例8: work
func work(c *replicant.Client, C <-chan time.Time, stop chan bool, done chan bool, dl *ygor.DataLogger) {
defer func() {
done <- true
}()
for {
select {
case <-C:
break
case <-stop:
return
}
start := time.Now()
_, err := c.Call("echo", "echo", []byte("hello world"), 0)
end := time.Now()
if err.Status == replicant.SUCCESS {
when := uint64(end.UnixNano())
data := uint64(end.Sub(start).Nanoseconds())
er := dl.Record(1, when, data)
if er != nil {
fmt.Printf("error: %s\n", er)
os.Exit(1)
}
} else {
fmt.Printf("error: %s\n", err)
os.Exit(1)
}
}
}
开发者ID:rescrv,项目名称:Replicant,代码行数:28,代码来源:main.go
示例9: main
func main() {
var f float64
fmt.Printf("Enter value in Fahrenheit : ")
fmt.Scanf("%f", &f)
fmt.Printf("Value in Celcius : %f\n", ftoc.FtoC(f))
}
开发者ID:budhrg,项目名称:intro_to_go,代码行数:7,代码来源:ftoc_demo.go
示例10: transfer
func transfer(dst_name string, src io.Reader) error {
config := goftp.Config{
User: username,
Password: password,
ConnectionsPerHost: 10,
Timeout: 10 * time.Second,
Logger: nil,
}
fmt.Printf("Dialing into %s... ", host)
client, err := goftp.DialConfig(config, host)
if err != nil {
return err
}
fmt.Println("done.")
fmt.Printf("Writing to file %s... ", dst_name)
err = client.Store(dst_name, src)
if err != nil {
return err
}
fmt.Println("done.")
return nil
}
开发者ID:vjeko,项目名称:godrone,代码行数:25,代码来源:deploy.go
示例11: quicksort
func quicksort(low, high int, buf []int) {
pivot := buf[low+(high-low)/2] // ここでは、枢軸は単に buf の中心。
l, r := low, high
fmt.Printf("start: buf = %v, pivot = %d, l(low) =, %d, r(high) = %d\n", buf, pivot, l, r)
for {
for pivot > buf[l] { // 要素 < 枢軸 ならよし。
l++
}
for pivot < buf[r] { // 枢軸 < 要素 ならよし。
r--
}
if l >= r {
fmt.Printf("for break: buf = %v, pivot = %d, l(low) =, %d, r(high) = %d\n", buf, pivot, l, r)
break // 始点と終点が交差したらループを抜ける。
}
// 条件に合致しなければ交換。
buf[l], buf[r] = buf[r], buf[l]
l++
r--
}
// l-1 と r-1 がミソっぽい。
// l-1 と r-1 を境界にして、それぞれのグループに対してさらに quicksort() する。
fmt.Printf("recurrence? buf = %v, low < l - 1 ? %v < %v - 1, high > r + 1 ? %v > %v + 1\n", buf, low, l, high, r)
if low < l-1 {
fmt.Println()
quicksort(low, l-1, buf)
}
if high > r+1 {
fmt.Println()
quicksort(r+1, high, buf)
}
}
开发者ID:yuta-masano,项目名称:abcgo,代码行数:32,代码来源:sample46.go
示例12: decodeStopRecord
func decodeStopRecord() {
jsonStr := `{
"type": "flv",
"stream_event": "flv",
"ori_url": "rtmp://pushyf.hifun.mobi/live/10016593_4VZIi6Cnwxdev",
"domain":"send.a.com",
"app":"live",
"stream":"10016593_4VZIi6Cnwxdev",
"uri":"hls.a.com/live/hls_bew000/hls_bew000_20160707150625_20160707175817.m3u8",
"start_time": 1470306194,
"stop_time": 1470306497,
"duration": 275,
"size":8987799,
"cdn_url": "http://hls.a.com/live/hls_bew000/hls_bew000_20160707150625_20160707175817.m3u8"
}`
rec := YFRecCallback{}
if err := json.Unmarshal([]byte(jsonStr), &rec); err != nil {
fmt.Printf("json unmarshal err:%v\n", err)
} else {
param["liveid"] = rec.Stream
param["url"] = rec.CdnUrl
param["duration"] = strconv.Itoa(int(rec.Duration))
param["size"] = strconv.Itoa(rec.Size)
fmt.Printf("decodeStopRecord rec : %v \n%v \n", rec, param)
}
}
开发者ID:Zerak,项目名称:gonote,代码行数:27,代码来源:record.go
示例13: main
func main() {
origin := "http://localhost:8000/"
url := os.Args[1]
secret := os.Args[2]
clients, _ := strconv.Atoi(os.Args[3])
fmt.Printf("clients: %d\n", clients)
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
token := auth.GenerateClientToken(secret, "test", timestamp, "")
connectMessage := fmt.Sprintf("{\"params\": {\"timestamp\": \"%s\", \"token\": \"%s\", \"user\": \"test\"}, \"method\": \"connect\"}", timestamp, token)
subscribeMessage := "{\"params\": {\"channel\": \"test\"}, \"method\": \"subscribe\"}"
done := make(chan struct{})
for i := 0; i < clients; i += 1 {
chSub := make(chan struct{})
go subscriber(chSub, url, origin, connectMessage, subscribeMessage)
<-chSub
fmt.Printf("\r%d", i+1)
}
// Just run until interrupted keeping connections open.
<-done
}
开发者ID:johnkewforks,项目名称:centrifugo,代码行数:25,代码来源:connections.go
示例14: Output
func Output(ps Profiles, c Config) {
if c.Tsv {
if !c.NoHeaders {
fmt.Printf("Count\tMin\tMax\tSum\tAvg\tP1\tP50\tP99\tStddev\tMin(Body)\tMax(Body)\tSum(Body)\tAvg(Body)\tMethod\tUri")
fmt.Println("")
}
for _, p := range ps {
fmt.Printf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v",
p.Cnt, Round(p.Min), Round(p.Max), Round(p.Sum), Round(p.Avg),
Round(p.P1), Round(p.P50), Round(p.P99), Round(p.Stddev),
Round(p.MinBody), Round(p.MaxBody), Round(p.SumBody), Round(p.AvgBody),
p.Method, p.Uri)
fmt.Println("")
}
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Count", "Min", "Max", "Sum", "Avg",
"P1", "P50", "P99", "Stddev",
"Min(Body)", "Max(Body)", "Sum(Body)", "Avg(Body)",
"Method", "Uri"})
for _, p := range ps {
data := []string{
fmt.Sprint(p.Cnt), Round(p.Min), Round(p.Max), Round(p.Sum), Round(p.Avg),
Round(p.P1), Round(p.P50), Round(p.P99), Round(p.Stddev),
Round(p.MinBody), Round(p.MaxBody), Round(p.SumBody), Round(p.AvgBody),
p.Method, p.Uri}
table.Append(data)
}
table.Render()
}
}
开发者ID:tkuchiki,项目名称:alp,代码行数:32,代码来源:util.go
示例15: main
func main() {
flag.Parse()
b, err := parseFile(fmt.Sprintf("%s/%s.txt", *dir, *month))
if err != nil {
log.Fatal(err)
}
fmt.Println("Total:", b.Total)
fmt.Println("Remaining:", b.Remaining)
mon := *month
year, err := strconv.Atoi(mon[0:4])
if err != nil {
log.Fatal(err)
}
m, err := strconv.Atoi(mon[4:6])
if err != nil {
log.Fatal(err)
}
rpd := b.Remaining / float64(daysIn(time.Month(m), year)-time.Now().Day())
fmt.Printf("Remaining/day: %.2f\n", rpd)
top := map[string]float64{}
for _, t := range b.Transactions {
top[t.Name] += t.Cost
}
fmt.Println("Top costs:")
pl := sortMapByValue(top)
for _, p := range pl {
fmt.Printf("\t%s: %.2f\n", p.Key, p.Value)
}
}
开发者ID:shawnps,项目名称:budget,代码行数:29,代码来源:main.go
示例16: testAccCheckDatadogMetricAlertDestroy
func testAccCheckDatadogMetricAlertDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*datadog.Client)
for _, rs := range s.RootModule().Resources {
for _, v := range strings.Split(rs.Primary.ID, "__") {
if v == "" {
fmt.Printf("Could not parse IDs. %s", v)
return fmt.Errorf("Id not set.")
}
ID, iErr := strconv.Atoi(v)
if iErr != nil {
fmt.Printf("Received error converting string %s", iErr)
return iErr
}
_, err := client.GetMonitor(ID)
if err != nil {
// 404 is what we want, anything else is an error. Sadly our API will return a string like so:
// return errors.New("API error: " + resp.Status)
// For now we'll use unfold :|
if strings.EqualFold(err.Error(), "API error: 404 Not Found") {
continue
} else {
fmt.Errorf("Received an error retrieving monitor %s", err)
}
} else {
fmt.Errorf("Monitor still exists. %s", err)
}
}
}
return nil
}
开发者ID:rgulewich,项目名称:terraform-provider-datadog,代码行数:32,代码来源:resource_datadog_metric_alert_test.go
示例17: Dump
func (loop *SimpleLoop) Dump(indent int) {
for i := 0; i < indent; i++ {
fmt.Printf(" ")
}
// No ? operator ?
fmt.Printf("loop-%d nest: %d depth %d ",
loop.counter, loop.nestingLevel, loop.depthLevel)
if !loop.isReducible {
fmt.Printf("(Irreducible) ")
}
// must have > 0
if len(loop.children) > 0 {
fmt.Printf("Children: ")
for ll, _ := range loop.Children() {
fmt.Printf("loop-%d", ll.Counter())
}
}
if len(loop.basicBlocks) > 0 {
fmt.Printf("(")
for bb, _ := range loop.basicBlocks {
fmt.Printf("BB#%03d ", bb.Name())
if loop.header == bb {
fmt.Printf("*")
}
}
fmt.Printf("\b)")
}
fmt.Printf("\n")
}
开发者ID:kirbyfan64,项目名称:benchmarks,代码行数:31,代码来源:havlak.go
示例18: clockOut
func clockOut(usr user) error {
fmt.Printf("Clocking user Out %s.\n", usr.ID)
//Do other checking?
punch, err := getLastTimepunch(usr.ID)
if err != nil {
return err
}
//If the last punch exists, has an in, but not an out,
//complete the punch.
if (!punch.In.Equal(time.Time{})) && (punch.Out.Equal(time.Time{})) {
punch.Out = time.Now()
punch.Duration = (punch.Out.Sub(punch.In))
err = updatePunch(punch)
if err != nil {
return err
}
} else { //in every other case, we just want to create a new punch.
err = createPunch(timePunch{UID: usr.ID, Out: time.Now()})
if err != nil {
return err
}
}
fmt.Printf("Done.")
return setUserStatus(usr.ID, false)
}
开发者ID:xuther,项目名称:timeclock,代码行数:30,代码来源:helpers.go
示例19: display
func display(r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
width, height := widthAndHeight()
fmt.Print("\033]1337;")
fmt.Printf("File=inline=1")
if width != "" || height != "" {
if width != "" {
fmt.Printf(";width=%s", width)
}
if height != "" {
fmt.Printf(";height=%s", height)
}
}
if *preserveAspectRatio {
fmt.Print("preserveAspectRatio=1")
}
fmt.Print(":")
fmt.Printf("%s", base64.StdEncoding.EncodeToString(data))
fmt.Print("\a\n")
return nil
}
开发者ID:wookay,项目名称:JuliaIntro.jl,代码行数:27,代码来源:imgcat.go
示例20: clockIn
//Return nil if successful, else returns an error.
func clockIn(usr user) error {
fmt.Printf("Clocking user in %s.\n", usr.ID)
status, err := getStatus(usr.ID)
if err != nil {
fmt.Printf("Done. Error %s.\n", err.Error())
return err
}
//Can't clock in if we're already in.
//TODO: Think about this? Do we want to allow users to clock in anyway and
//create a missed punch like thing?
if status {
err := errors.New("Could not clock in, already clocked in.")
fmt.Printf("Done. Error %s.\n", err.Error())
return err
}
err = createPunch(timePunch{UID: usr.ID, In: time.Now()})
if err != nil {
return err
}
//Do other checking?
err = setUserStatus(usr.ID, true)
if err != nil {
return err
}
return nil
}
开发者ID:xuther,项目名称:timeclock,代码行数:31,代码来源:helpers.go
注:本文中的fmt.Printf函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论