Beispiel #1
0
func main() {
	fmt.Println("\nQuestion 1 results using my own type methods:")
	studyGroup := people{"Zuno", "Derren", "Jahn", "Albert", "Jenny", "Rachel"}
	sort.Sort(sort.Reverse(studyGroup)) // Using reverse interface
	fmt.Println(studyGroup)
	sort.Sort(studyGroup)
	fmt.Println(studyGroup)

	/*
		(2)
		s := []string{"Zeno", "John", "Al", "Jenny"}
	*/
	fmt.Println("\nQuestion 2 using StringSlice.")
	s := []string{"Zeno", "John", "Al", "Jenny"}
	// sort.Sort(sort.StringSlice(s))
	sort.Strings(s) // Shorthand for above.
	fmt.Println("Sorted:", s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println("Reversed sort:", s)

	/*
	  (3)
	  n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	*/
	fmt.Println("\nQuestion 3, int slice sorting:")
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	sort.Ints(n) // Shorthand for using IntSlice - look at doc.
	fmt.Println("Sorted using Ints, shorthand for IntSlice:", n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println("Reversed Ints:", n)
}
Beispiel #2
0
func main() {
	nums := []int{120, 33, 44, 1, 23, 90, 87, 13, 57, 43, 42}
	//标准库qsort 正序(实际上是qsort结合heapsort,insertsort)
	sort.Ints(nums)
	fmt.Println(nums)
	//反序qsort
	sort.Sort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums)
	//正序bubble
	bubbleSort(sort.IntSlice(nums))
	fmt.Println(nums)
	//反序bubble
	bubbleSort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums)
	//正序insert
	insertSort(sort.IntSlice(nums))
	fmt.Println(nums)
	//反序inert
	insertSort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums)
	//正序select
	selectSort(sort.IntSlice(nums))
	fmt.Println(nums)
	//反序select
	selectSort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums)

}
Beispiel #3
0
func Euler041() int {
	//process 7 digit pandigitals
	p7d := make([]int, 0, 5040) //7!
	for v := range utils.Perm(utils.Numerals[1:8]) {
		n, _ := strconv.Atoi(v)
		p7d = append(p7d, n)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(p7d)))

	for i := 0; i < 5040; i++ {
		if utils.IsPrime(p7d[i]) {
			return p7d[i]
		}
	}

	//process 4 digit pandigitals
	p4d := make([]int, 0, 24) //4!
	for v := range utils.Perm(utils.Numerals[1:5]) {
		n, _ := strconv.Atoi(v)
		p4d = append(p4d, n)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(p4d)))

	for i := 0; i < 5040; i++ {
		if utils.IsPrime(p4d[i]) {
			return p4d[i]
		}
	}

	return -1
}
Beispiel #4
0
// allocateCandidates creates a candidate list of all stores that can used for
// allocating a new replica ordered from the best to the worst. Only stores
// that meet the criteria are included in the list.
func allocateCandidates(
	sl StoreList,
	constraints config.Constraints,
	existing []roachpb.ReplicaDescriptor,
	existingNodeLocalities map[roachpb.NodeID]roachpb.Locality,
	deterministic bool,
) candidateList {
	var candidates candidateList
	for _, s := range sl.stores {
		if !preexistingReplicaCheck(s.Node.NodeID, existing) {
			continue
		}
		constraintsOk, preferredMatched := constraintCheck(s, constraints)
		if !constraintsOk {
			continue
		}
		if !maxCapacityCheck(s) {
			continue
		}

		constraintScore := diversityScore(s, existingNodeLocalities) + float64(preferredMatched)
		candidates = append(candidates, candidate{
			store:      s,
			valid:      true,
			constraint: constraintScore,
			capacity:   capacityScore(s),
		})
	}
	if deterministic {
		sort.Sort(sort.Reverse(byScoreAndID(candidates)))
	} else {
		sort.Sort(sort.Reverse(byScore(candidates)))
	}
	return candidates
}
Beispiel #5
0
// sortList sorts lists (like substitutions) from a string:string map.
func sortList(dict map[string]string) []string {
	output := []string{}

	// Track by number of words.
	track := map[int][]string{}

	// Loop through each item.
	for item, _ := range dict {
		cnt := wordCount(item, true)
		if _, ok := track[cnt]; !ok {
			track[cnt] = []string{}
		}
		track[cnt] = append(track[cnt], item)
	}

	// Sort them by word count, descending.
	sortedCounts := []int{}
	for cnt, _ := range track {
		sortedCounts = append(sortedCounts, cnt)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(sortedCounts)))

	for _, cnt := range sortedCounts {
		// Sort the strings of this word-count by their lengths.
		sortedLengths := track[cnt]
		sort.Sort(sort.Reverse(byLength(sortedLengths)))
		for _, item := range sortedLengths {
			output = append(output, item)
		}
	}

	return output
}
Beispiel #6
0
func formCards(cards []*Card, c Config) []*Card {
	var ranks []Rank
	if c.aceIsLow {
		// sort cards staring w/ king
		sort.Sort(sort.Reverse(byAceLow(cards)))
		// sort ranks starting w/ king
		ranks = allRanks()
		sort.Sort(sort.Reverse(byAceLowRank(ranks)))
	} else {
		// sort cards staring w/ ace
		sort.Sort(sort.Reverse(byAceHigh(cards)))
		// sort ranks starting w/ ace
		ranks = allRanks()
		sort.Sort(sort.Reverse(byAceHighRank(ranks)))
	}

	// form cards starting w/ most paired
	formed := []*Card{}
	for i := 4; i > 0; i-- {
		for _, r := range ranks {
			rCards := cardsForRank(cards, r)
			if len(rCards) == i {
				formed = append(formed, rCards...)
			}
		}
	}

	dif := 5 - len(formed)
	for i := 0; i < dif; i++ {
		s := fmt.Sprintf("?%d", i+1)
		formed = append(formed, &Card{rank: Rank(s), suit: Suit(s)})
	}
	// check for low straight
	return formLowStraight(formed)
}
Beispiel #7
0
func main() {
	// sort people as type
	studyGroup := people{"Zeno", "John", "Al", "Jenny"}

	fmt.Println(studyGroup)
	sort.Sort(studyGroup)
	fmt.Println(studyGroup)
	sort.Sort(sort.Reverse(studyGroup))
	fmt.Println(studyGroup)

	// sort s as string slice
	s := []string{"Zeno", "John", "Al", "Jenny"}
	fmt.Println(s)
	sort.StringSlice(s).Sort()
	fmt.Println(s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println(s)

	// sort n as int slice
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	fmt.Println(n)
	sort.IntSlice(n).Sort()
	fmt.Println(n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println(n)
}
Beispiel #8
0
func main() {

	studyGroup := people{"Zeno", "Ian", "John", "Al", "Jenny"}

	fmt.Println("1: = sorting slice of strings of type people by name:")
	fmt.Println("\to:", studyGroup)
	sort.Strings(studyGroup)
	fmt.Println("\t\t [Strings method]:", studyGroup)
	sort.Sort(sort.StringSlice(studyGroup))
	fmt.Println("\t\t [StringSlice interface conversion]", studyGroup)
	sort.Sort(sort.Reverse(sort.StringSlice(studyGroup)))
	fmt.Println("\t\t [Reverse]", studyGroup)

	fmt.Println("2: = by literal slice of strings")
	s := []string{"Zeno", "John", "Al", "Jenny", "Ben"}
	fmt.Println("\to:", s)
	sort.Strings(s)
	fmt.Println("\t\t [Strings method]:", s)
	sort.Sort(sort.StringSlice(s))
	fmt.Println("\t\t [StringSlice interface conversion]", s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println("\t\t [Reverse]", s)

	fmt.Println("3: = slice of ints")
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	fmt.Println("\to:", n)
	sort.Ints(n)
	fmt.Println("\t\t [Ints method]", n)
	sort.Sort(sort.IntSlice(n))
	fmt.Println("\t\t [IntSlice interface conversion]", n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println("\t\t [Reverse]", n)

}
Beispiel #9
0
// Add sorting method to "Listing"
// it will apply what's in ".Sort" and ".Order"
func (l Listing) applySort() {
	// Check '.Order' to know how to sort
	if l.Order == "desc" {
		switch l.Sort {
		case "name":
			sort.Sort(sort.Reverse(byName(l)))
		case "size":
			sort.Sort(sort.Reverse(bySize(l)))
		case "time":
			sort.Sort(sort.Reverse(byTime(l)))
		default:
			// If not one of the above, do nothing
			return
		}
	} else { // If we had more Orderings we could add them here
		switch l.Sort {
		case "name":
			sort.Sort(byName(l))
		case "size":
			sort.Sort(bySize(l))
		case "time":
			sort.Sort(byTime(l))
		default:
			// If not one of the above, do nothing
			return
		}
	}
}
Beispiel #10
0
func main() {
	s := []*Organ{
		{"spleen", 162},
		{"pacreas", 131},
		{"liver", 1494},
		{"heart", 290},
		{"brain", 1340},
	}
	for _, o := range s {
		fmt.Println(o)
	}

	fmt.Println("before sort", s)

	// sort
	sort.Sort(ByWeight{s})
	fmt.Println("Organs by weight", s)

	sort.Sort(ByName{s})
	fmt.Println("Organs by name", s)

	// reverse
	fmt.Println("before reverse", s)

	sort.Sort(sort.Reverse(ByWeight{s}))
	fmt.Println("Organs by weight", s)

	sort.Sort(sort.Reverse(ByName{s}))
	fmt.Println("Organs by name", s)
}
func main() {
	intList := []int{2, 4, 3, 5, 7, 6, 9, 8, 1, 0}
	float8List := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
	stringList := []string{"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"}
	fmt.Println("------------正序---------------")
	sort.Ints(intList)
	sort.Float64s(float8List)
	sort.Strings(stringList)
	fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList)
	fmt.Println("------------倒序---------------")
	sort.Sort(sort.Reverse(sort.IntSlice(intList)))
	sort.Sort(sort.Reverse(sort.Float64Slice(float8List)))
	sort.Sort(sort.Reverse(sort.StringSlice(stringList)))
	fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList)
	fmt.Println("-------------结构体(特定字段)排序-----------")
	people := []Person{
		{"zhang san", 12},
		{"li si", 30},
		{"wang wu", 52},
		{"zhao liu", 26},
	}
	fmt.Println(people)
	sort.Sort(PersonWrapper{people, func(p, q *Person) bool {
		return q.Age < p.Age //Age 递减排序
	}})
	fmt.Println(people)
	sort.Sort(PersonWrapper{people, func(p, q *Person) bool {
		return p.Name < q.Name //Name 递增排序
	}})
	fmt.Println(people)
}
Beispiel #12
0
func (s PlayerStandings) ByWinnings(oldTieBreak bool) {
	if oldTieBreak {
		sort.Sort(sort.Reverse(ByWinningsOld{s}))
	} else {
		sort.Sort(sort.Reverse(ByWinnings{s}))
	}
}
Beispiel #13
0
/*
sortByWords sorts a set of triggers by word count and overall length.

This is a helper function for sorting the `atomic`, `option`, `alpha`, `number`
and `wild` attributes of the sortTrack and adding them to the running sort
buffer in that specific order. Since attribute lookup by reflection is expensive
in Go, this function is given the relevant sort buffer directly, and the current
running sort buffer to add the results to.

The `triggers` parameter is a map between word counts and the triggers that
fit that number of words.
*/
func sortByWords(running []sortedTriggerEntry, triggers map[int][]sortedTriggerEntry) []sortedTriggerEntry {
	// Sort the triggers by their word counts from greatest to smallest.
	var sortedWords []int
	for wc := range triggers {
		sortedWords = append(sortedWords, wc)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(sortedWords)))

	for _, wc := range sortedWords {
		// Triggers with equal word lengths should be sorted by overall trigger length.
		var sortedPatterns []string
		patternMap := map[string][]sortedTriggerEntry{}

		for _, trig := range triggers[wc] {
			sortedPatterns = append(sortedPatterns, trig.trigger)
			if _, ok := patternMap[trig.trigger]; !ok {
				patternMap[trig.trigger] = []sortedTriggerEntry{}
			}
			patternMap[trig.trigger] = append(patternMap[trig.trigger], trig)
		}
		sort.Sort(sort.Reverse(byLength(sortedPatterns)))

		// Add the triggers to the running triggers bucket.
		for _, pattern := range sortedPatterns {
			running = append(running, patternMap[pattern]...)
		}
	}

	return running
}
Beispiel #14
0
// PrioritizeTags orders a set of image tags with a few conventions:
//
// 1. the "latest" tag, if present, should be first
// 2. any tags that represent a semantic major version ("5", "v5") should be next, in descending order
// 3. any tags that represent a semantic minor version ("5.1", "v5.1") should be next, in descending order
// 4. any tags that represent a full semantic version ("5.1.3-other", "v5.1.3-other") should be next, in descending order
// 5. any remaining tags should be sorted in lexicographic order
//
// The method updates the tags in place.
func PrioritizeTags(tags []string) {
	remaining := tags
	finalTags := make([]string, 0, len(tags))
	for i, tag := range tags {
		if tag == DefaultImageTag {
			tags[0], tags[i] = tags[i], tags[0]
			finalTags = append(finalTags, tags[0])
			remaining = tags[1:]
			break
		}
	}

	exact := make(map[string]string)
	var major, minor, micro semver.Versions
	other := make([]string, 0, len(remaining))
	for _, tag := range remaining {
		short := strings.TrimLeft(tag, "v")
		v, err := semver.Parse(short)
		switch {
		case err == nil:
			exact[v.String()] = tag
			micro = append(micro, v)
			continue
		case reMajorSemantic.MatchString(short):
			if v, err = semver.Parse(short + ".0.0"); err == nil {
				exact[v.String()] = tag
				major = append(major, v)
				continue
			}
		case reMinorSemantic.MatchString(short):
			if v, err = semver.Parse(short + ".0"); err == nil {
				exact[v.String()] = tag
				minor = append(minor, v)
				continue
			}
		}
		other = append(other, tag)
	}
	sort.Sort(sort.Reverse(major))
	sort.Sort(sort.Reverse(minor))
	sort.Sort(sort.Reverse(micro))
	sort.Sort(sort.StringSlice(other))
	for _, v := range major {
		finalTags = append(finalTags, exact[v.String()])
	}
	for _, v := range minor {
		finalTags = append(finalTags, exact[v.String()])
	}
	for _, v := range micro {
		finalTags = append(finalTags, exact[v.String()])
	}
	for _, v := range other {
		finalTags = append(finalTags, v)
	}
	copy(tags, finalTags)
}
Beispiel #15
0
func viterbi(obs []rune, states []byte) (float64, []byte) {
	path := make(map[byte][]byte)
	V := make([]map[byte]float64, len(obs))
	V[0] = make(map[byte]float64)
	for _, y := range states {
		if val, ok := ProbEmit[y][obs[0]]; ok {
			V[0][y] = val + ProbStart[y]
		} else {
			V[0][y] = MIN_FLOAT + ProbStart[y]
		}
		path[y] = []byte{y}
	}

	for t := 1; t < len(obs); t++ {
		newPath := make(map[byte][]byte)
		V[t] = make(map[byte]float64)
		for _, y := range states {
			vs0 := make(Viterbis, 0)
			var em_p float64
			if val, ok := ProbEmit[y][obs[t]]; ok {
				em_p = val
			} else {
				em_p = MIN_FLOAT
			}
			for _, y0 := range PrevStatus[y] {
				var transP float64
				if tp, ok := ProbTrans[y0][y]; ok {
					transP = tp
				} else {
					transP = MIN_FLOAT
				}
				prob0 := V[t-1][y0] + transP + em_p
				vs0 = append(vs0, &Viterbi{prob: prob0, state: y0})
			}
			sort.Sort(sort.Reverse(vs0))
			V[t][y] = vs0[0].prob
			pp := make([]byte, len(path[vs0[0].state]))
			copy(pp, path[vs0[0].state])
			newPath[y] = append(pp, y)
		}
		path = newPath
	}
	vs := make(Viterbis, 0)
	for _, y := range []byte{'E', 'S'} {
		vs = append(vs, &Viterbi{V[len(obs)-1][y], y})
	}
	sort.Sort(sort.Reverse(vs))
	v := vs[0]
	return v.prob, path[v.state]
}
Beispiel #16
0
func viterbi(obs []rune, states []byte) (float64, []byte) {
	path := make(map[byte][]byte)
	V := make([]map[byte]float64, len(obs))
	V[0] = make(map[byte]float64)
	for _, y := range states {
		if val, ok := probEmit[y][obs[0]]; ok {
			V[0][y] = val + probStart[y]
		} else {
			V[0][y] = minFloat + probStart[y]
		}
		path[y] = []byte{y}
	}

	for t := 1; t < len(obs); t++ {
		newPath := make(map[byte][]byte)
		V[t] = make(map[byte]float64)
		for _, y := range states {
			ps0 := make(probStates, 0)
			var emP float64
			if val, ok := probEmit[y][obs[t]]; ok {
				emP = val
			} else {
				emP = minFloat
			}
			for _, y0 := range prevStatus[y] {
				var transP float64
				if tp, ok := probTrans[y0][y]; ok {
					transP = tp
				} else {
					transP = minFloat
				}
				prob0 := V[t-1][y0] + transP + emP
				ps0 = append(ps0, &probState{prob: prob0, state: y0})
			}
			sort.Sort(sort.Reverse(ps0))
			V[t][y] = ps0[0].prob
			pp := make([]byte, len(path[ps0[0].state]))
			copy(pp, path[ps0[0].state])
			newPath[y] = append(pp, y)
		}
		path = newPath
	}
	ps := make(probStates, 0)
	for _, y := range []byte{'E', 'S'} {
		ps = append(ps, &probState{V[len(obs)-1][y], y})
	}
	sort.Sort(sort.Reverse(ps))
	v := ps[0]
	return v.prob, path[v.state]
}
Beispiel #17
0
func main() {

	//var n sort.IntSlice

	n := []int{7, 4, 8, 2, -9, 12, -23, 32, 3}

	sort.Sort(sort.Reverse(sort.IntSlice(n)))

	//sort.Sort(sort.IntSlice(n))
	fmt.Printf("\n %T \n", sort.Reverse(sort.IntSlice(n)))
	fmt.Println(n)

	//fmt.Println(n)

}
Beispiel #18
0
// newHand constructs a new Hand type from the given cards.
// cards is of the form e.g. [AC 8D 8H 3C 2S]
func newHand(cards []string) Hand {
	trans := map[string]int{"A": 14, "K": 13, "Q": 12, "J": 11, "T": 10}

	var ranks []int                  // The ranks field.
	suits := make(map[string]bool)   // The suits field.
	rankToCount := make(map[int]int) // Used to create other fields.
	for _, card := range cards {
		s := string(card[1])
		suits[s] = true
		r, ok := trans[string(card[0])]
		if !ok {
			r, _ = strconv.Atoi(string(card[0]))
		}
		ranks = append(ranks, r)
		rankToCount[r]++
	}
	sort.Sort(sort.Reverse(sort.IntSlice(ranks)))

	// An ace should be played 'low' i.e. with rank 1 if it makes a straight.
	if reflect.DeepEqual(ranks, []int{14, 5, 4, 3, 2}) {
		ranks = []int{5, 4, 3, 2, 1}
	}

	var pattern []int                   // The pattern field.
	countToRanks := make(map[int][]int) // Used to create the groups field.
	for k, v := range rankToCount {
		pattern = append(pattern, v)
		countToRanks[v] = append(countToRanks[v], k)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(pattern)))

	var groups [][]int         // The groups field.
	seen := make(map[int]bool) // Used to ensure no duplicates.
	for _, count := range pattern {
		// For every count in the pattern append to groups a [count rank] pair.
		// groups is ordered by highest count first, then highest rank first.
		if !seen[count] {
			rs := countToRanks[count]
			sort.Sort(sort.Reverse(sort.IntSlice(rs)))
			for _, r := range rs {
				groups = append(groups, []int{count, r})
			}
		}
		seen[count] = true
	}

	return Hand{ranks, suits, groups, pattern}
}
Beispiel #19
0
func (r *reconcile) disjoinTargets() (hostnameTargetMapping map[string]*storage.Target, err error) {
	var targets []*storage.Target

	r.store.VisitTargets(func(t *storage.Target) error {
		targets = append(targets, t)
		return nil
	})

	sort.Stable(sort.Reverse(targetSorter(targets)))

	// Hostname-target mapping.
	hostnameTargetMapping = map[string]*storage.Target{}
	for _, tgt := range targets {
		tgt.Satisfy.ReducedNames = nil
		for _, name := range tgt.Satisfy.Names {
			_, exists := hostnameTargetMapping[name]
			if !exists {
				hostnameTargetMapping[name] = tgt
				tgt.Satisfy.ReducedNames = append(tgt.Satisfy.ReducedNames, name)
			}
		}
	}

	// Debugging information.
	for name, tgt := range hostnameTargetMapping {
		log.Debugf("disjoint hostname mapping: %s -> %v", name, tgt)
	}

	return
}
Beispiel #20
0
// Yay, sorting things is so easy in go
func keysByIntValDesc(m map[string]int) []string {
	// Invert the map
	inv := map[int][]string{}
	for k, v := range m {
		inv[v] = append(inv[v], k)
	}

	// List the unique vals
	vals := []int{}
	for k, _ := range inv {
		vals = append(vals, k)
	}

	// Sort the vals
	sort.Sort(sort.Reverse(sort.IntSlice(vals)))

	// Now list the keys corresponding to each val
	keys := []string{}
	for _, val := range vals {
		for _, key := range inv[val] {
			keys = append(keys, key)
		}
	}

	return keys
}
Beispiel #21
0
func Test_divide(t *testing.T) {
	//Test if dividing the message works
	var keys []int
	for key, _ := range IPs {
		keys = append(keys, key)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))

	fixtures := map[int]map[int]int{
		11:  map[int]int{25: 0, 10: 1, 5: 0, 1: 1},
		100: map[int]int{25: 4, 10: 0, 5: 0, 1: 0},
		107: map[int]int{25: 4, 10: 0, 5: 1, 1: 2},
		4:   map[int]int{25: 0, 10: 0, 5: 0, 1: 4},
	}
	for input, expected := range fixtures {
		result := divide(input, keys)
		failed := false
		for k, v := range expected {
			if result[k] != v {
				failed = true
			}
		}
		if failed {
			t.Error(fmt.Sprintf("Dividing %d expected %v, got %v", input, expected, result))
		}
	}
}
func (l *darwinLauncher) lookForExecutableReleases(basepath, binPath string) (string, error) {
	filesInfo, err := ioutil.ReadDir(basepath)
	if err != nil {
		return "", fmt.Errorf("Could not check for releases: %s", err)
	}

	versions := make([]version, 0, len(filesInfo))
	for _, inf := range filesInfo {
		if inf.IsDir() == false {
			continue
		}
		v, err := newVersion(inf.Name())
		if err != nil {
			return "", err
		}
		versions = append(versions, v)
	}

	sort.Sort(sort.Reverse(versionList(versions)))
	if len(versions) == 0 {
		return "", fmt.Errorf("Could not find a release in %s", basepath)
	}

	res := path.Join(basepath, versions[0].String(), binPath)

	info, err := os.Stat(res)
	if err != nil {
		return "", fmt.Errorf("Could not find binary %s: %s", res, err)
	}
	if info.Mode().Perm()&111 == 111 {
		return "", fmt.Errorf("Wrong persion %v on binary %s", info.Mode().Perm(), res)
	}

	return res, nil
}
Beispiel #23
0
// RemoveAll removes a tree recursively.
func RemoveAll(path string, vfs rwvfs.WalkableFileSystem) error {
	w := fs.WalkFS(path, vfs)

	remove := func(par *parallel.Run, path string) {
		par.Do(func() error { return vfs.Remove(path) })
	}

	var dirs []string // remove dirs after removing all files
	filesPar := parallel.NewRun(20)
	for w.Step() {
		if err := w.Err(); err != nil {
			return err
		}
		if w.Stat().IsDir() {
			dirs = append(dirs, w.Path())
		} else {
			remove(filesPar, w.Path())
		}
	}

	if err := filesPar.Wait(); err != nil {
		return err
	}

	dirsPar := parallel.NewRun(20)
	sort.Sort(sort.Reverse(sort.StringSlice(dirs))) // reverse so we delete leaf dirs first
	for _, dir := range dirs {
		remove(dirsPar, dir)
	}
	return dirsPar.Wait()
}
Beispiel #24
0
func TestSort(t *testing.T) {
	infos := InfoArray{
		{"a", Float64Value(3.0), 0, 0, 0, 0},
		{"b", Float64Value(1.0), 0, 0, 0, 0},
		{"c", Float64Value(2.1), 0, 0, 0, 0},
		{"d", Float64Value(2.0), 0, 0, 0, 0},
		{"e", Float64Value(-1.0), 0, 0, 0, 0},
	}

	// Verify forward sort.
	sort.Sort(infos)
	last := Float64Value(-math.MaxFloat64)
	for _, info := range infos {
		if info.Val.Less(last) {
			t.Errorf("info val %v not increasing", info.Val)
		}
		last = info.Val.(Float64Value)
	}

	// Verify reverse sort.
	sort.Sort(sort.Reverse(infos))
	last = Float64Value(math.MaxFloat64)
	for _, info := range infos {
		if !info.Val.Less(last) {
			t.Errorf("info val %v not decreasing", info.Val)
		}
		last = info.Val.(Float64Value)
	}
}
Beispiel #25
0
// === sortDesc(node model.ValVector) Vector ===
func funcSortDesc(ev *evaluator, args Expressions) model.Value {
	// NaN should sort to the bottom, so take ascending sort with NaN first and
	// reverse it.
	byValueSorter := vectorByValueHeap(ev.evalVector(args[0]))
	sort.Sort(sort.Reverse(byValueSorter))
	return vector(byValueSorter)
}
Beispiel #26
0
func main() {
	// main prints out top 7 frequent words of input file.

	dict := make(map[string]int)
	f, err := os.Open("alice-in-wonderland.txt")
	assertNil(err)

	r := bufio.NewReader(f)
	for {
		switch line, err := r.ReadString('\n'); err {
		case nil:
			dict = dictionary(dict, words(line))
		case io.EOF:
			// convert dict to slice for sorting in O(n) time.
			// maps are horrible for sorting because the go
			// runtime randomizes map iteration order.
			// So we use a different data structure(slice) to maintain order.
			wordFrequencyList := list(dict)

			// sort orders the slice from smallest to biggest
			// sort.reverse ensures an ordering from big to small
			sort.Sort(sort.Reverse(byCount(wordFrequencyList)))

			fmt.Println(first(wordFrequencyList, 7))
			return
		default:
			return
		}
	}

}
Beispiel #27
0
func (us *UnionScanExec) buildAndSortAddedRows(t table.Table, asName *model.CIStr) error {
	us.addedRows = make([]*Row, 0, len(us.dirty.addedRows))
	for h, data := range us.dirty.addedRows {
		for i, field := range us.Src.Fields() {
			field.Expr.SetDatum(data[i])
		}
		if us.condition != nil {
			matched, err := evaluator.EvalBool(us.ctx, us.condition)
			if err != nil {
				return errors.Trace(err)
			}
			if !matched {
				continue
			}
		}
		rowKeyEntry := &RowKeyEntry{Handle: h, Tbl: t, TableAsName: asName}
		row := &Row{Data: data, RowKeys: []*RowKeyEntry{rowKeyEntry}}
		us.addedRows = append(us.addedRows, row)
	}
	if us.desc {
		sort.Sort(sort.Reverse(us))
	} else {
		sort.Sort(us)
	}
	if us.sortErr != nil {
		return errors.Trace(us.sortErr)
	}
	return nil
}
Beispiel #28
0
func runPs(args *docopt.Args, client cluster.Host) error {
	all, err := client.ListJobs()
	if err != nil {
		return fmt.Errorf("could not get local jobs: %s", err)
	}

	jobs := make(sortJobs, 0, len(all))
	for _, job := range all {
		if !args.Bool["-a"] && !args.Bool["--all"] && job.Status != host.StatusStarting && job.Status != host.StatusRunning {
			continue
		}
		jobs = append(jobs, job)
	}
	sort.Sort(sort.Reverse(jobs))

	if args.Bool["-q"] || args.Bool["--quiet"] {
		for _, job := range jobs {
			fmt.Println(job.Job.ID)
		}
		return nil
	}
	w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
	defer w.Flush()
	fmt.Fprintln(w, "JOB ID\tSTATE\tSTARTED\tCONTROLLER APP\tCONTROLLER TYPE")
	for _, job := range jobs {
		fmt.Fprintf(w, "%s\t%s\t%s ago\t%s\t%s\n", job.Job.ID, job.Status, units.HumanDuration(time.Now().UTC().Sub(job.StartedAt)), job.Job.Metadata["flynn-controller.app_name"], job.Job.Metadata["flynn-controller.type"])
	}
	return nil
}
Beispiel #29
0
func main() {
	fmt.Println("Hello, playground")
	tmpl, _ := template.New("haproxy").Parse(haproxyConf)
	response := []byte(`{"kind":"List","apiVersion":"v1","metadata":{},"items":[{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"aa-server-port-80","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/aa-server-port-80","uid":"7defad5e-db41-11e5-9156-12cccd293299","resourceVersion":"133729342","generation":3,"creationTimestamp":"2016-02-24T21:56:43Z"},"spec":{"rules":[{"host":"server-port-default.kube-prod1.vungle.io","http":{"paths":[{"path":"/","backend":{"serviceName":"aa-server-port-80-svc","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"billboard","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/billboard","uid":"900dc71a-cb8b-11e5-b8f7-12cccd293299","resourceVersion":"133703561","generation":2,"creationTimestamp":"2016-02-04T22:06:38Z"},"spec":{"rules":[{"host":"billboard.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"billboard","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"data-api-temp-external","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/data-api-temp-external","uid":"74b4106d-eaef-11e5-a2af-1213d0960275","resourceVersion":"173827720","generation":2,"creationTimestamp":"2016-03-15T20:49:48Z"},"spec":{"rules":[{"host":"data-ext.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"data-api-temp-external","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"dataingestion","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/dataingestion","uid":"521f5616-f533-11e5-8cde-1213d0960275","resourceVersion":"213651089","generation":1,"creationTimestamp":"2016-03-28T22:20:47Z"},"spec":{"rules":[{"host":"ingest.vungle.com","http":{"paths":[{"path":"/eventData","backend":{"serviceName":"dataingestioneventdata","servicePort":80}},{"path":"/api/v1/sdkErrors","backend":{"serviceName":"dataingestionsdk","servicePort":80}},{"path":"/tpat","backend":{"serviceName":"dataingestiontpat","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"docker-registry","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/docker-registry","uid":"43df621c-db34-11e5-9156-12cccd293299","resourceVersion":"130787889","generation":1,"creationTimestamp":"2016-02-24T20:22:02Z"},"spec":{"rules":[{"host":"vungle.io","http":{"paths":[{"path":"/","backend":{"serviceName":"docker-registry","servicePort":5000}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"elasticsearch","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/elasticsearch","uid":"6c37887a-da56-11e5-9156-12cccd293299","resourceVersion":"173837944","generation":2,"creationTimestamp":"2016-02-23T17:54:02Z"},"spec":{"rules":[{"host":"elastikube.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"elasticsearch","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"gor-replay","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/gor-replay","uid":"35bfc8e7-da74-11e5-9156-12cccd293299","resourceVersion":"173839383","generation":2,"creationTimestamp":"2016-02-23T21:27:15Z"},"spec":{"rules":[{"host":"gor-replay.vungle.io","http":{"paths":[{"path":"/","backend":{"serviceName":"gor-replay","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"grafana","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/grafana","uid":"b38792da-db24-11e5-9156-12cccd293299","resourceVersion":"173840297","generation":2,"creationTimestamp":"2016-02-24T18:30:38Z"},"spec":{"rules":[{"host":"shh.vungle.io","http":{"paths":[{"path":"/","backend":{"serviceName":"influx-udp","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"influx-udp","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/influx-udp","uid":"180be6d1-e0cd-11e5-9156-12cccd293299","resourceVersion":"141207774","generation":1,"creationTimestamp":"2016-03-02T23:18:38Z"},"spec":{"rules":[{"host":"influxdb-udp.vungle.io","http":{"paths":[{"path":"/","backend":{"serviceName":"influx-udp","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"jaeger","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/jaeger","uid":"24e29abb-f53b-11e5-8cde-1213d0960275","resourceVersion":"213800874","generation":1,"creationTimestamp":"2016-03-28T23:16:47Z"},"spec":{"rules":[{"host":"api.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"jaeger","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"kubana","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/kubana","uid":"5073116e-d4f6-11e5-9156-12cccd293299","resourceVersion":"133695558","generation":2,"creationTimestamp":"2016-02-16T21:43:28Z"},"spec":{"rules":[{"host":"kubana.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"kibana","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"ltv-data-api","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/ltv-data-api","uid":"13ca6264-d999-11e5-9156-12cccd293299","resourceVersion":"211674600","generation":6,"creationTimestamp":"2016-02-22T19:18:38Z"},"spec":{"rules":[{"host":"ltv-data-api.kube-prod.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"ltv-data-api","servicePort":9000}}]}},{"host":"pie.api.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"ltv-data-api","servicePort":9000}}]}},{"host":"data.vungle.com","http":{"paths":[{"path":"/pie","backend":{"serviceName":"ltv-data-api","servicePort":9000}}]}}]},"status":{"loadBalancer":{}}},{"kind":"Ingress","apiVersion":"extensions/v1beta1","metadata":{"name":"viking-api","namespace":"default","selfLink":"/apis/extensions/v1beta1/namespaces/default/ingresses/viking-api","uid":"7433c964-f065-11e5-8cde-1213d0960275","resourceVersion":"193807800","generation":1,"creationTimestamp":"2016-03-22T19:37:03Z"},"spec":{"rules":[{"host":"viking.vungle.com","http":{"paths":[{"path":"/","backend":{"serviceName":"viking-api","servicePort":80}},{"path":"/.well-known/acme-challenge","backend":{"serviceName":"lets-encrypt","servicePort":80}}]}}]},"status":{"loadBalancer":{}}}]}
`)
	var ingresses Ingress
	json.Unmarshal(response, &ingresses)
	for _, items := range ingresses.Items {
		for _, rule := range items.Spec.Rules {
			ps := make(Paths, 0, len(rule.HTTP.Paths))

			for _, path := range rule.HTTP.Paths {
				ps = append(ps, path)
				//fmt.Println(paths.Path)
			}

			sort.Sort(sort.Reverse(ps))

			for i, _ := range ps {
				rule.HTTP.Paths[i] = ps[i]
			}
		}
	}
	tmpl.Execute(os.Stdout, ingresses)
}
Beispiel #30
0
// Prints top five summary metrics for request types with latency and returns
// number of such request types above threshold.
func HighLatencyRequests(c clientset.Interface) (int, error) {
	metrics, err := readLatencyMetrics(c)
	if err != nil {
		return 0, err
	}
	sort.Sort(sort.Reverse(metrics))
	badMetrics := 0
	top := 5
	for _, metric := range metrics.APICalls {
		isBad := false
		if metric.Latency.Perc99 > apiCallLatencyThreshold {
			badMetrics++
			isBad = true
		}
		if top > 0 || isBad {
			top--
			prefix := ""
			if isBad {
				prefix = "WARNING "
			}
			Logf("%vTop latency metric: %+v", prefix, metric)
		}
	}

	// TODO(random-liu): Remove the log when we migrate to new perfdash
	Logf("API calls latencies: %s", PrettyPrintJSON(metrics))
	// Log perf data
	PrintPerfData(ApiCallToPerfData(metrics))

	return badMetrics, nil
}