Ejemplo n.º 1
0
func selectItems(ncase int, targetCredit int, items []*Product) string {
	for i, v := range items {
		for _, x := range items[i+1:] {
			if v.cost+x.cost == targetCredit {
				temp := []*Product{v, x}
				sortutil.AscByField(temp, "id")
				return "Case #" + strconv.Itoa(ncase) + ": " + strconv.Itoa(temp[0].id) + " " + strconv.Itoa(temp[1].id) + "\n"
			}
		}
	}
	return ""
}
Ejemplo n.º 2
0
func testsort() {
	slice := make([]Thing, 0)
	for i := 0; i < 19; i++ {
		thing := Thing{Field1: i, Field2: time.Now().Unix()}
		slice = append(slice, thing)
		//time.Sleep(1001 * time.Millisecond)
	}

	//print in order
	sortutil.AscByField(slice, "Field1")
	for i := 0; i < len(slice); i++ {
		fmt.Printf("thing: %+v\n", slice[i])
	}
}
Ejemplo n.º 3
0
func main() {
	prefix := "A-large"
	text := ""
	bs, err := ioutil.ReadFile(prefix + "-practice.in")
	if err != nil {
		return
	}

	filename := prefix + "-practice.out"

	str := string(bs)
	lines := strings.Split(str, "\n")

	fmt.Println("lines: ", len(lines))
	// number of cases
	n, err2 := strconv.Atoi(lines[0])
	if err2 != nil {
	}
	c := 1
	for i := 1; i <= n; i++ {
		credit, err3 := strconv.Atoi(lines[c])
		if err3 != nil {
		}
		//numItems, err4 := strconv.Atoi(lines[c+1])
		//if err4 != nil {}

		tempItems := strings.Split(lines[c+2], " ")
		allItems := make([]*Product, 0)
		for j, k := range tempItems {
			temp, err5 := strconv.Atoi(k)
			if err5 != nil {
			}
			if temp <= credit {
				prod := &Product{id: j + 1, cost: temp}
				allItems = append(allItems, prod)
			}
		}
		sortutil.AscByField(allItems, "cost")
		text += selectItems(i, credit, allItems)
		c += 3
	}
	err4 := ioutil.WriteFile(filename, []byte(text), 0777)
	if err4 != nil {
		panic(err4)
	}
}
Ejemplo n.º 4
0
func paint(user *dht.User) {

	// clear space
	for j := 1; j < 100; j++ {
		fmt.Println("")
	}

	// new messages?
	usersWithPendingMessages := make([]string, 0)
	for peer, _ := range user.MessageHistory {
		areNew, _ := user.AreNewMessagesFrom(peer)
		if areNew {
			usersWithPendingMessages = append(usersWithPendingMessages, peer)
		}
	}

	// print users with pending messages
	for _, peer := range usersWithPendingMessages {
		fmt.Printf("New message(s) from `%s`!\n", peer)
	}
	fmt.Printf("\n\n========================================\n")

	// are we current chatting?
	if user.Current != "" {
		fmt.Printf("Conversation with `%s`:\n\n", user.Current)

		newMessages := user.AllMessagesFromUser(user.Current)

		messages := make([]dht.SendMessageArgs, 0)
		for _, msg := range newMessages {
			messages = append(messages, *msg)
		}

		sortutil.AscByField(messages, "Timestamp")
		for i := 0; i < len(messages); i++ {
			msg := messages[i]
			fmt.Printf("%s> %s\n", msg.FromUsername, msg.Content)
		}
	}

	fmt.Printf("=========================================\n")
	fmt.Printf("me> ")
}
Ejemplo n.º 5
0
func (user *User) AreNewMessagesFrom(other string) (bool, []SendMessageArgs) {

	areNew := false
	newMessages := make([]SendMessageArgs, 0)
	mostRecent := int64(0)
	if recent, ok := user.LastSeenMap[other]; ok {
		mostRecent = recent
	}

	// get messages in this conversation, and traverse
	// messages in the conversation in order of timing
	messagePointers := user.MessageHistory[other]

	messages := make([]SendMessageArgs, 0)
	for _, msg := range messagePointers {
		messages = append(messages, *msg)
	}

	sortutil.AscByField(messages, "Timestamp")
	for i := 0; i < len(messages); i++ {
		message := messages[i]
		stamp := message.Timestamp

		// http://golang.org/src/pkg/time/time.go?s=2447:2479#L50
		if stamp > mostRecent && message.FromUsername != user.Name {
			areNew = true
		}

		if areNew {
			newMessages = append(newMessages, message)
		}
	}

	// update the most recent to be the last one we've seen
	if len(messages) > 0 {
		user.LastSeenMap[other] = messages[len(messages)-1].Timestamp
	}

	return areNew, newMessages
}
Ejemplo n.º 6
0
func (this *Redis) runPing(zkzone *zk.ZkZone) {
	var wg sync.WaitGroup
	allRedis := zkzone.AllRedis()
	this.topInfos = make([]redisTopInfo, 0, len(allRedis))

	for _, hostPort := range allRedis {
		host, port, err := net.SplitHostPort(hostPort)
		if err != nil {
			this.Ui.Error(hostPort)
			continue
		}

		nport, err := strconv.Atoi(port)
		if err != nil || nport < 0 {
			this.Ui.Error(hostPort)
			continue
		}

		wg.Add(1)
		go func(wg *sync.WaitGroup, host string, port int) {
			defer wg.Done()

			t0 := time.Now()

			spec := redis.DefaultSpec().Host(host).Port(port)
			client, err := redis.NewSynchClientWithSpec(spec)
			if err != nil {
				this.Ui.Error(fmt.Sprintf("[%s:%d] %v", host, port, err))
				return
			}
			defer client.Quit()

			if err := client.Ping(); err != nil {
				this.Ui.Error(fmt.Sprintf("[%s:%d] %v", host, port, err))
				return
			}

			latency := time.Since(t0)

			this.mu.Lock()
			this.topInfos = append(this.topInfos, redisTopInfo{
				host:    host,
				port:    port,
				t0:      t0,
				latency: latency,
			})
			this.mu.Unlock()
		}(&wg, host, nport)
	}
	wg.Wait()

	latency := metrics.NewRegisteredHistogram("redis.latency", metrics.DefaultRegistry, metrics.NewExpDecaySample(1028, 0.015))

	sortutil.AscByField(this.topInfos, "latency")
	lines := []string{"#|Host|Port|latency"}
	if this.debug {
		lines = []string{"#|Host|Port|StartedAt|latency"}
	}
	for i, info := range this.topInfos {
		latency.Update(info.latency.Nanoseconds() / 1e6)

		if this.debug {
			lines = append(lines, fmt.Sprintf("%4d|%s|%d|%s|%s",
				i+1, info.host, info.port, info.t0, info.latency))
		} else {
			lines = append(lines, fmt.Sprintf("%4d|%s|%d|%s",
				i+1, info.host, info.port, info.latency))
		}

	}
	this.Ui.Output(columnize.SimpleFormat(lines))

	// summary
	ps := latency.Percentiles([]float64{0.7, 0.90, 0.95, 0.99, 0.999})
	this.Ui.Info(fmt.Sprintf("N:%d Min:%dms Max:%dms Mean:%.1fms 70%%:%1.fms 90%%:%.1fms 95%%:%.1fms 99%%:%.1fms",
		latency.Count(), latency.Min(), latency.Max(), latency.Mean(), ps[0], ps[1], ps[2], ps[3]))
}
Ejemplo n.º 7
0
func (this *Redis) render() {
	if !this.batchMode {
		termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	}

	this.mu.Lock()
	defer this.mu.Unlock()

	if this.topOrderAsc {
		sortutil.AscByField(this.topInfos, this.topOrderCols[this.topOrderColIdx])
	} else {
		sortutil.DescByField(this.topInfos, this.topOrderCols[this.topOrderColIdx])
	}
	sortCols := make([]string, len(this.topOrderCols))
	copy(sortCols, this.topOrderCols)
	for i, col := range sortCols {
		if col == this.selectedCol() {
			if this.topOrderAsc {
				sortCols[i] += " >"
			} else {
				sortCols[i] += " <"
			}
		}
	}

	var (
		lines = []string{fmt.Sprintf("Host|Port|%s", strings.Join(sortCols, "|"))}

		sumDbsize, sumConns, sumOps, sumMem, sumRx, sumTx, sumMaxMem int64
	)
	for i := 0; i < len(this.topInfos); i++ {
		info := this.topInfos[i]

		sumDbsize += info.dbsize
		sumConns += info.conns
		sumOps += info.ops
		sumMem += info.mem
		sumMaxMem += info.maxmem
		sumRx += info.rx * 1024 / 8
		sumTx += info.tx * 1024 / 8

		if info.ops >= this.beep {
			this.warnPorts[strconv.Itoa(info.port)] = struct{}{}
		}

		this.maxDbSize = max(this.maxDbSize, info.dbsize)
		this.maxConns = max(this.maxConns, info.conns)
		this.maxOps = max(this.maxOps, info.ops)
		this.maxMem = max(this.maxMem, info.mem)
		this.maxMaxMem = max(this.maxMaxMem, info.maxmem)
		this.maxRx = max(this.maxRx, info.rx*1024/8)
		this.maxTx = max(this.maxTx, info.tx*1024/8)
		if info.memp > this.maxMemp {
			this.maxMemp = info.memp
		}
		if info.trp > this.maxTrp {
			this.maxTrp = info.trp
		}

		if i >= min(this.rows, len(this.topInfos)) {
			continue
		}

		l := fmt.Sprintf("%s|%d|%s|%s|%s|%s|%s|%6.1f|%s|%s|%8.1f",
			info.host, info.port,
			gofmt.Comma(info.dbsize), gofmt.Comma(info.conns), gofmt.Comma(info.ops),
			gofmt.ByteSize(info.mem), gofmt.ByteSize(info.maxmem),
			100.*info.memp,
			gofmt.ByteSize(info.rx*1024/8), gofmt.ByteSize(info.tx*1024/8),
			info.trp)
		if this.beep > 0 {
			var val int64
			switch this.selectedCol() {
			case "conns":
				val = info.conns
			case "rx":
				val = info.rx
			case "tx":
				val = info.tx
			case "dbsize":
				val = info.dbsize
			case "ops":
				val = info.ops
			case "mem":
				val = info.mem
			case "maxm":
				val = info.maxmem

			}

			if val > this.beep {
				//l += "\a"
			}
		}
		lines = append(lines, l)
	}
	lines = append(lines, fmt.Sprintf("-MAX-|%d|%s|%s|%s|%s|%s|%6.1f|%s|%s|%8.1f",
		len(this.topInfos),
		gofmt.Comma(this.maxDbSize), gofmt.Comma(this.maxConns), gofmt.Comma(this.maxOps),
		gofmt.ByteSize(this.maxMem), gofmt.ByteSize(this.maxMaxMem),
		100.*this.maxMemp,
		gofmt.ByteSize(this.maxRx), gofmt.ByteSize(this.maxTx),
		this.maxTrp))
	lines = append(lines, fmt.Sprintf("-TOTAL-|%d|%s|%s|%s|%s|%s|%6.1f|%s|%s|%8.1f",
		len(this.topInfos),
		gofmt.Comma(sumDbsize), gofmt.Comma(sumConns), gofmt.Comma(sumOps),
		gofmt.ByteSize(sumMem), gofmt.ByteSize(sumMaxMem),
		100.*float64(sumMem)/float64(sumMaxMem),
		gofmt.ByteSize(sumRx), gofmt.ByteSize(sumTx),
		float64(sumTx)/float64(sumRx)))

	for row, line := range lines {
		if row == 0 {
			// header
			this.drawRow(line, row, termbox.ColorDefault, termbox.ColorBlue)
		} else if row == len(lines)-2 {
			// max line
			this.drawRow(line, row, termbox.ColorMagenta, termbox.ColorDefault)
		} else if row == len(lines)-1 {
			// total line
			this.drawRow(line, row, termbox.ColorYellow, termbox.ColorDefault)
		} else {
			tuples := strings.Split(line, "|")
			if _, present := this.selectedPorts[tuples[1]]; present {
				this.drawRow(line, row, termbox.ColorBlack, termbox.ColorCyan)
			} else if _, present := this.warnPorts[tuples[1]]; !present {
				this.drawRow(line, row, termbox.ColorDefault, termbox.ColorDefault)
			} else {
				this.drawRow(line, row, termbox.ColorDefault, termbox.ColorRed)
			}
		}
	}

	if !this.batchMode {
		termbox.Flush()
	}
}
Ejemplo n.º 8
0
func (this *Segment) printSummary() {
	segments := make(map[string]map[int]map[int]int64) // dir:day:hour:size
	err := filepath.Walk(this.rootPath, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() || !this.isKafkaLogSegment(f.Name()) {
			return nil
		}

		dir := filepath.Base(filepath.Dir(path))
		if _, present := segments[dir]; !present {
			segments[dir] = make(map[int]map[int]int64)
		}
		if _, present := segments[dir][f.ModTime().Day()]; !present {
			segments[dir][f.ModTime().Day()] = make(map[int]int64)
		}
		segments[dir][f.ModTime().Day()][f.ModTime().Hour()] += f.Size()
		return nil
	})
	if err != nil {
		this.Ui.Error(err.Error())
	}

	partitions := make([]string, 0, len(segments))
	for dir, _ := range segments {
		partitions = append(partitions, dir)
	}
	sort.Strings(partitions)

	type segment struct {
		partition string
		day       int
		hour      int
		size      int64
	}

	var maxSegment segment
	var totalSize int64
	for _, p := range partitions {
		summary := make([]segment, 0)
		for day, hourSize := range segments[p] {
			for hour, size := range hourSize {
				summary = append(summary, segment{
					partition: p,
					day:       day,
					hour:      hour,
					size:      size,
				})
			}
		}
		sortutil.AscByField(summary, "size")
		if this.limit > 0 && len(summary) > this.limit {
			summary = summary[:this.limit]
		}

		for _, s := range summary {
			if s.size > maxSegment.size {
				maxSegment = s
			}

			totalSize += s.size
			this.Ui.Output(fmt.Sprintf("%50s day:%2d hour:%2d size:%s", p,
				s.day, s.hour, gofmt.ByteSize(s.size)))
		}

	}

	this.Ui.Output(fmt.Sprintf("%50s day:%2d hour:%2d size:%s", "MAX-"+maxSegment.partition,
		maxSegment.day, maxSegment.hour, gofmt.ByteSize(maxSegment.size)))
	this.Ui.Output(fmt.Sprintf("%50s %s", "-TOTAL-", gofmt.ByteSize(totalSize)))

	return
}
Ejemplo n.º 9
0
// Status prints out all of the non-utility services and their running jobs
func (s *SStatus) Status(env *models.Environment, services *[]models.Service) error {
	w := &tabwriter.Writer{}
	w.Init(os.Stdout, 0, 8, 4, '\t', 0)

	fmt.Fprintln(w, env.Name+" (environment ID = "+env.ID+"):")
	fmt.Fprintln(w, "Label\tStatus\tCreated At")

	sortutil.AscByField(*services, "Label")

	for _, service := range *services {
		if service.Type != "" {
			jobs, err := s.Jobs.RetrieveByStatus(service.ID, "running")
			if err != nil {
				return err
			}
			for _, job := range *jobs {
				displayType := service.Label
				if job.Type != "deploy" {
					displayType = fmt.Sprintf("%s (%s)", service.Label, job.Type)
					if job.Type == "worker" {
						// fetch the worker separately to get the procfile target run
						workerJob, err := s.Jobs.Retrieve(job.ID, service.ID, true)
						if err != nil {
							return err
						}
						if workerJob.Spec != nil && workerJob.Spec.Payload != nil && workerJob.Spec.Payload.Environment != nil {
							if target, contains := workerJob.Spec.Payload.Environment["PROCFILE_TARGET"]; contains {
								displayType = fmt.Sprintf("%s (%s: target=%s)", service.Label, job.Type, target)
							}
						}
					}
				} else if len(service.ReleaseVersion) > 0 {
					displayType = fmt.Sprintf("%s (%s)", service.Label, service.ReleaseVersion)
				} else {
					displayType = fmt.Sprintf("%s", service.Label)
				}

				const dateForm = "2006-01-02T15:04:05"
				t, _ := time.Parse(dateForm, job.CreatedAt)
				fmt.Fprintln(w, displayType+"\t"+job.Status+"\t"+t.Local().Format(time.Stamp))
			}
			if service.Type == "code" {
				latestBuildJobs, err := s.Jobs.RetrieveByType(service.ID, "build", 1, 1)
				if err != nil {
					return err
				}
				for _, latestBuildJob := range *latestBuildJobs {
					if latestBuildJob.ID == "" {
						fmt.Fprintln(w, "--------"+"\t"+service.Label+"\t"+"-------"+"\t"+"---------------")
					} else if latestBuildJob.ID != "" {
						const dateForm = "2006-01-02T15:04:05"
						t, _ := time.Parse(dateForm, latestBuildJob.CreatedAt)
						displayType := service.Label
						displayType = fmt.Sprintf("%s (%s)", displayType, latestBuildJob.Type)
						fmt.Fprintln(w, displayType+"\t"+latestBuildJob.Status+"\t"+t.Local().Format(time.Stamp))
					}
				}
			}
		}
	}
	w.Flush()
	return nil
}
Ejemplo n.º 10
0
func (r *RecipeBook) SortByType(type_ string) {
	sortutil.AscByField(r.recipes, "type_")
}