本文整理汇总了Golang中sort.Stable函数的典型用法代码示例。如果您正苦于以下问题:Golang Stable函数的具体用法?Golang Stable怎么用?Golang Stable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Stable函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: writeNetworkInterfaces
func (net UbuntuNetManager) writeNetworkInterfaces(dhcpConfigs DHCPInterfaceConfigurations, staticConfigs StaticInterfaceConfigurations, dnsServers []string) (bool, error) {
sort.Stable(dhcpConfigs)
sort.Stable(staticConfigs)
networkInterfaceValues := networkInterfaceConfig{
DHCPConfigs: dhcpConfigs,
StaticConfigs: staticConfigs,
HasDNSNameServers: true,
DNSServers: dnsServers,
}
buffer := bytes.NewBuffer([]byte{})
t := template.Must(template.New("network-interfaces").Parse(networkInterfacesTemplate))
err := t.Execute(buffer, networkInterfaceValues)
if err != nil {
return false, bosherr.WrapError(err, "Generating config from template")
}
changed, err := net.fs.ConvergeFileContents("/etc/network/interfaces", buffer.Bytes())
if err != nil {
return changed, bosherr.WrapError(err, "Writing to /etc/network/interfaces")
}
return changed, nil
}
示例2: buildHuffman
// buildHuffman builds a Huffman tree using useCounts as a frequency table.
func buildHuffman(useCounts [129]int) (root *huffmanNode) {
numNonZero := 0
for _, count := range useCounts {
if count != 0 {
numNonZero++
}
}
nodes := nodeList(make([]*huffmanNode, 0, numNonZero))
for char, count := range useCounts {
if count != 0 {
nodes = append(nodes, &huffmanNode{rune(char), count, nil, nil})
}
}
if len(nodes) < 2 {
panic("cannot build a tree with a single node")
}
sort.Stable(nodes)
for len(nodes) > 1 {
parent := &huffmanNode{0, nodes[0].count + nodes[1].count, nodes[0], nodes[1]}
nodes = nodes[1:]
nodes[0] = parent
sort.Stable(nodes)
}
return nodes[0]
}
开发者ID:slamacchia,项目名称:transport-security-state-generate,代码行数:32,代码来源:transport_security_state_static_generate.go
示例3: BenchmarkStableSortRepeat
func BenchmarkStableSortRepeat(b *testing.B) {
for n := 0; n < b.N; n++ {
s := newData()
sort.Stable(customSort{s, func(x, y *Track) bool {
if x.Title != y.Title {
return x.Title < y.Title
}
return false
}})
sort.Stable(customSort{s, func(x, y *Track) bool {
if x.Artist != y.Artist {
return x.Artist < y.Artist
}
return false
}})
sort.Stable(customSort{s, func(x, y *Track) bool {
if x.Album != y.Album {
return x.Album < y.Album
}
return false
}})
sort.Stable(customSort{s, func(x, y *Track) bool {
if x.Year != y.Year {
return x.Year < y.Year
}
return false
}})
}
}
示例4: jpfSortBy
func jpfSortBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return arr, nil
} else if len(arr) == 1 {
return arr, nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
if _, ok := start.(float64); ok {
sortable := &byExprFloat{intr, node, arr, false}
sort.Stable(sortable)
if sortable.hasError {
return nil, errors.New("error in sort_by comparison")
}
return arr, nil
} else if _, ok := start.(string); ok {
sortable := &byExprString{intr, node, arr, false}
sort.Stable(sortable)
if sortable.hasError {
return nil, errors.New("error in sort_by comparison")
}
return arr, nil
} else {
return nil, errors.New("invalid type, must be number of string")
}
}
示例5: Benchmark_words_load
func Benchmark_words_load(t *testing.B) {
// wordlist was downloaded from http://www-personal.umich.edu/~jlawler/wordlist
f, err := os.Open("d:\\wordlist.txt")
if err != nil {
t.Skip()
return
}
defer f.Close()
s := bufio.NewScanner(f)
words := make([]string, 0, 80000)
for s.Scan() {
txt := s.Text()
words = append(words, txt)
}
sort.Stable(byStringLengthDesc(words))
tree := NewPrefixedTree("")
for i := range words {
tree.Put(words[i], i)
}
of, err := os.Create("d:\\wordlist.json")
panicif(err)
defer of.Close()
of.WriteString(tree.String())
t.Log("Nodes: ", tree.NodeCount())
t.Log("Max fanout: ", tree.root.MaxFanout())
histogram := make(map[int]int)
tree.root.visit(func(n *Node) bool {
count := len(n.Nodes)
histogram[count] += 1
return true
})
kvs := make([]kv, len(histogram))
i := 0
for k, v := range histogram {
kvs[i] = kv{k, v}
i++
}
sort.Stable(byFanout(kvs))
for i := range kvs {
t.Logf("%+v", kvs[i])
}
t.Logf("=====")
sort.Stable(byCount(kvs))
for i := range kvs {
t.Logf("%+v", kvs[i])
}
tree.root.Walk("abating", func(path string, h int) bool {
t.Logf("%d(%s): %s ", h, path, words[h])
return true
})
}
示例6: SortIcons
func SortIcons(icons []Icon, sizeDescending bool) {
// Order after sorting: (width/height, bytes, url)
sort.Stable(byURL(icons))
sort.Stable(byBytes(icons))
if sizeDescending {
sort.Stable(sort.Reverse(byWidthHeight(icons)))
} else {
sort.Stable(byWidthHeight(icons))
}
}
示例7: Sort
func Sort(e *State, T miniprofiler.Timer, series *Results, order string) (*Results, error) {
// Sort by groupname first to make the search deterministic
sort.Sort(ResultSliceByGroup(series.Results))
switch order {
case "desc":
sort.Stable(sort.Reverse(ResultSliceByValue(series.Results)))
case "asc":
sort.Stable(ResultSliceByValue(series.Results))
default:
return nil, fmt.Errorf("second argument of order() must be asc or desc")
}
return series, nil
}
示例8: sortGroups
func sortGroups(groups [][]*assets.Group) (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
// Sort each group list by priority
for _, v := range groups {
sort.Stable(groupsByPriority(v))
}
// Sort the list of all groups by priority
sort.Stable(groupListByPriority(groups))
return
}
示例9: prettyPrintCerts
// Given a list of Ceritifcates in order of listing preference, pretty-prints
// the cert common name, fingerprint, and expiry
func prettyPrintCerts(certs []*x509.Certificate, writer io.Writer) {
if len(certs) == 0 {
writer.Write([]byte("\nNo trusted root certificates present.\n\n"))
return
}
sort.Stable(certSorter(certs))
table := getTable([]string{
"GUN", "Fingerprint of Trusted Root Certificate", "Expires In"}, writer)
for _, c := range certs {
days := math.Floor(c.NotAfter.Sub(time.Now()).Hours() / 24)
expiryString := "< 1 day"
if days == 1 {
expiryString = "1 day"
} else if days > 1 {
expiryString = fmt.Sprintf("%d days", int(days))
}
certID, err := trustmanager.FingerprintCert(c)
if err != nil {
fatalf("Could not fingerprint certificate: %v", err)
}
table.Append([]string{c.Subject.CommonName, certID, expiryString})
}
table.Render()
}
示例10: TestRequestSorting
func TestRequestSorting(t *testing.T) {
sampleRequests := []request.Request{
request.Request{
Timestamp: "012400",
Description: "Fourth",
},
request.Request{
Timestamp: "012400",
Description: "Fifth",
},
request.Request{
Timestamp: "012346",
Description: "Second",
},
request.Request{
Timestamp: "012345",
Description: "First",
},
request.Request{
Timestamp: "012347",
Description: "Third",
},
}
sort.Stable(requestsByTimestamp(sampleRequests))
descriptions := []string{}
for _, r := range sampleRequests {
descriptions = append(descriptions, r.Description)
}
if !(descriptions[0] == "First" && descriptions[1] == "Second" && descriptions[2] == "Third" && descriptions[3] == "Fourth" && descriptions[4] == "Fifth") {
t.Fatalf("Review request ordering failed. Got %v", sampleRequests)
}
}
示例11: Fetch
// Fetch queries the Consul API defined by the given client and returns a slice
// of Node objects
func (d *CatalogNodes) Fetch(clients *ClientSet, opts *QueryOptions) (interface{}, *ResponseMetadata, error) {
d.Lock()
if d.stopped {
defer d.Unlock()
return nil, nil, ErrStopped
}
d.Unlock()
if opts == nil {
opts = &QueryOptions{}
}
consulOpts := opts.consulQueryOptions()
if d.DataCenter != "" {
consulOpts.Datacenter = d.DataCenter
}
consul, err := clients.Consul()
if err != nil {
return nil, nil, fmt.Errorf("catalog nodes: error getting client: %s", err)
}
var n []*api.Node
var qm *api.QueryMeta
dataCh := make(chan struct{})
go func() {
log.Printf("[DEBUG] (%s) querying Consul with %+v", d.Display(), consulOpts)
n, qm, err = consul.Catalog().Nodes(consulOpts)
close(dataCh)
}()
select {
case <-d.stopCh:
return nil, nil, ErrStopped
case <-dataCh:
}
if err != nil {
return nil, nil, fmt.Errorf("catalog nodes: error fetching: %s", err)
}
log.Printf("[DEBUG] (%s) Consul returned %d nodes", d.Display(), len(n))
nodes := make([]*Node, 0, len(n))
for _, node := range n {
nodes = append(nodes, &Node{
Node: node.Node,
Address: node.Address,
TaggedAddresses: node.TaggedAddresses,
})
}
sort.Stable(NodeList(nodes))
rm := &ResponseMetadata{
LastIndex: qm.LastIndex,
LastContact: qm.LastContact,
}
return nodes, rm, nil
}
示例12: Compress
// Compress merges any unmerged data into the summary
func (digest *MergingDigest) Compress() {
if len(digest.unmerged) == 0 {
return
}
sort.Stable(sortByMean(digest.unmerged))
sum := int64(0)
m := 0
i := 0
j := 0
digest.merged = digest.merged[:0]
for i < len(digest.summary) && j < len(digest.unmerged) {
if digest.summary[i].Mean <= digest.unmerged[j].Mean {
sum, m = digest.collapse(sum, m, digest.summary[i])
i++
} else {
sum, m = digest.collapse(sum, m, digest.unmerged[j])
j++
}
}
for i < len(digest.summary) {
sum, m = digest.collapse(sum, m, digest.summary[i])
i++
}
for j < len(digest.unmerged) {
sum, m = digest.collapse(sum, m, digest.unmerged[j])
j++
}
digest.merged, digest.summary = digest.summary, digest.merged
digest.unmerged = digest.unmerged[:0]
}
示例13: joinKVs
func (h *LogrusHandler) joinKVs(skipUnchanged bool, sep string) []string {
kv := make([]string, 0, len(h.Fields))
for k, v := range h.Fields {
if !h.Opts.shouldShowKey(k) {
continue
}
if skipUnchanged {
if lastV, ok := h.last[k]; ok && lastV == v {
continue
}
}
kstr := rgbterm.FgString(k, h.Opts.KeyRGB.R, h.Opts.KeyRGB.G, h.Opts.KeyRGB.B)
var vstr string
if h.Opts.Truncates && len(v) > h.Opts.TruncateLength {
vstr = v[:h.Opts.TruncateLength] + "..."
} else {
vstr = v
}
vstr = rgbterm.FgString(vstr, h.Opts.ValRGB.R, h.Opts.ValRGB.G, h.Opts.ValRGB.B)
kv = append(kv, kstr+sep+vstr)
}
sort.Strings(kv)
if h.Opts.SortLongest {
sort.Stable(byLongest(kv))
}
return kv
}
示例14: prettyPrintTargets
// Given a list of KeyStores in order of listing preference, pretty-prints the
// root keys and then the signing keys.
func prettyPrintTargets(ts []*notaryclient.Target, writer io.Writer) {
if len(ts) == 0 {
writer.Write([]byte("\nNo targets present in this repository.\n\n"))
return
}
sort.Stable(targetsSorter(ts))
table := tablewriter.NewWriter(writer)
table.SetHeader([]string{"Name", "Digest", "Size (bytes)"})
table.SetBorder(false)
table.SetColumnSeparator(" ")
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetCenterSeparator("-")
table.SetAutoWrapText(false)
for _, t := range ts {
table.Append([]string{
t.Name,
hex.EncodeToString(t.Hashes["sha256"]),
fmt.Sprintf("%d", t.Length),
})
}
table.Render()
}
示例15: Sort
// Sort stable sorts the pages given the receiver's sort order.
func (by pageBy) Sort(pages Pages) {
ps := &pageSorter{
pages: pages,
by: by, // The Sort method's receiver is the function (closure) that defines the sort order.
}
sort.Stable(ps)
}