func setUpdate(prev []string, v interface{}) []string { m := map[string]bool{} for _, v := range prev { m[v] = true } switch i := v.(type) { case nil: case string: m[i] = true case []interface{}: for _, v := range i { val, ok := v.(string) if ok { m[val] = true } } } rv := sort.StringSlice{} for k := range m { rv = append(rv, k) } rv.Sort() return []string(rv) }
func setUsage(commands map[string]Command) { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage:\n %s [http://cbfs:8484/] cmd [-opts] cmdargs\n", os.Args[0]) fmt.Fprintf(os.Stderr, "\nCommands:\n") ss := sort.StringSlice{} for k := range commands { ss = append(ss, k) } ss.Sort() for _, k := range ss { fmt.Fprintf(os.Stderr, " %s %s\n", k, commands[k].Argstr) } fmt.Fprintf(os.Stderr, "\n---- Subcommand Options ----\n") for _, k := range ss { if commands[k].Flags != nil { fmt.Fprintf(os.Stderr, "\n%s:\n", k) commands[k].Flags.PrintDefaults() } } os.Exit(1) } }
// Returns the code for an ambigious amino acid. func AminoAcidCode(aa string) string { aa = strings.ToUpper(aa) if len(aa) == 1 { return aa } letters := sort.StringSlice{aa[:]} letters.Sort() sorted := strings.Join([]string(letters), "") switch sorted { case "AG": return "R" case "CT": return "Y" case "AC": return "M" case "GT": return "K" case "CG": return "S" case "AT": return "W" case "ACT": return "H" case "CGT": return "B" case "ACG": return "V" case "AGT": return "D" case "ACGT": return "N" } return aa }
func ConfigList(configStore *config.Store, app, env string) error { cfg, err := configStore.GetApp(app, env) if err != nil { return err } if cfg == nil { return fmt.Errorf("unable to list config for %s.", app) } keys := sort.StringSlice{"ENV"} for k, _ := range cfg.Env() { keys = append(keys, k) } keys.Sort() for _, k := range keys { if k == "ENV" { log.Printf("%s=%s\n", k, env) continue } fmt.Printf("%s=%s\n", k, cfg.Env()[k]) } return nil }
// UploadDirTree uploads a local directory and all of its subfolders // localDir -> path to the local folder to upload along with all of its subfolders. // remoteRootDir -> the root folder on the FTP server where to store the localDir tree. // excludedDirs -> a slice of folder names to exclude from the uploaded directory tree. // callback -> a callback function, which is called synchronously. Do remember to collect data in a go routine for instance if you do not want the upload to block. // Returns the number of files uploaded and an error if any. // // The current workding directory is set back to the initial value at the end. func (ftp *FTP) UploadDirTree(localDir string, remoteRootDir string, maxSimultaneousConns int, excludedDirs []string, callback Callback) (n int, err error) { if len(remoteRootDir) == 0 { return n, errors.New("A valid remote root folder with write permission needs specifying.") } var pwd string if pwd, err = ftp.Pwd(); err != nil { return } if _, err = ftp.Cwd(remoteRootDir); err != nil { return n, nil } //go back to original wd defer ftp.Cwd(pwd) //all lower case var exDirs sort.StringSlice if len(excludedDirs) > 0 { exDirs = sort.StringSlice(excludedDirs) for _, v := range exDirs { v = strings.ToLower(v) } exDirs.Sort() } err = ftp.uploadDirTree(localDir, exDirs, callback, &n) if err != nil { ftp.writeInfo(fmt.Sprintf("An error while uploading the folder %s occurred.", localDir)) } return n, err }
// sortFlags returns the flags as a slice in lexicographical sorted order. func sortFlags(flags map[string]*Flag) []*Flag { var list sort.StringSlice for _, f := range flags { if len(f.Names) == 1 { list = append(list, f.Names[0]) continue } found := false fName := strings.TrimPrefix(strings.TrimPrefix(f.Names[0], "#"), "-") for _, name := range list { if name == fName { found = true break } } if !found { list = append(list, fName) } } list.Sort() result := make([]*Flag, len(list)) for i, name := range list { result[i] = flags[name] } return result }
// 校验消息是否是从微信服务器发送过来的. // 使用 buf 能提高一点性能 和 减少一些对 GC 的压力, buf 的长度最好 >=128 func _CheckSignature(signature, timestamp, nonce, token string, buf []byte) bool { const hashsumLen = 40 // sha1 if len(signature) != hashsumLen { return false } bufLen := hashsumLen + len(timestamp) + len(nonce) + len(token) if len(buf) < bufLen { buf = make([]byte, hashsumLen, bufLen) } else { buf = buf[:hashsumLen] } strArray := sort.StringSlice{token, timestamp, nonce} strArray.Sort() buf = append(buf, strArray[0]...) buf = append(buf, strArray[1]...) buf = append(buf, strArray[2]...) hashsumArray := sha1.Sum(buf[hashsumLen:]) // require go1.2+ hashsumHexBytes := buf[:hashsumLen] hex.Encode(hashsumHexBytes, hashsumArray[:]) // 采用 subtle.ConstantTimeCompare 是防止 计时攻击! if rslt := subtle.ConstantTimeCompare(hashsumHexBytes, []byte(signature)); rslt == 1 { return true } return false }
func display(w io.Writer, format string, title string, supportedSites map[string]string) { var urls sort.StringSlice for url := range supportedSites { urls = append(urls, url) } urls.Sort() switch format { case "html": fmt.Fprint(w, "\t\tSupported "+title+":") fmt.Fprint(w, "<br />\n") for _, url := range urls { var s string if strings.Contains(url, "http") { s = "\t\t<a href=\"" + url + "\">" + supportedSites[url] + "</a><br />\n" } else { s = "\t\t<a href=\"http://www." + url + "\">" + supportedSites[url] + "</a><br />\n" } fmt.Fprint(w, s) } default: fmt.Fprint(w, "Supported journals:\n\n") for _, url := range urls { fmt.Fprint(w, supportedSites[url]+"\t\t"+url+"\n") } } }
func (cmdr *Commander) Usage() { fmt.Printf("usage: %s cmd [cmd-flags] [cmd-args]\n", os.Args[0]) var groupNames sort.StringSlice cmdNamesByGroup := map[string]sort.StringSlice{} for _, cmd := range cmdr.Commands { if _, ok := cmdNamesByGroup[cmd.Group]; !ok { groupNames = append(groupNames, cmd.Group) } cmdNamesByGroup[cmd.Group] = append(cmdNamesByGroup[cmd.Group], cmd.Name) } groupNames.Sort() for _, gn := range groupNames { fmt.Printf("\n%s:\n", gn) cmdNamesByGroup[gn].Sort() for _, cn := range cmdNamesByGroup[gn] { cmd := cmdr.Commands[cn] fmt.Printf(" %-18s %s\n", cmd.Name, cmd.Description) } } fmt.Println() }
// computeChecksum computes checksum of all servers in the ring func (r *hashRing) ComputeChecksum() { var addresses sort.StringSlice var buffer bytes.Buffer r.servers.Lock() for address := range r.servers.byAddress { addresses = append(addresses, address) } addresses.Sort() for _, address := range addresses { buffer.WriteString(address) buffer.WriteString(";") } old := r.servers.checksum r.servers.checksum = farm.Fingerprint32(buffer.Bytes()) r.ringpop.ringEvent(RingChecksumEvent{ OldChecksum: old, NewChecksum: r.servers.checksum, }) r.servers.Unlock() }
func (ee EtcdEnvironment) String() (out string) { norm := normalizeSvcEnv(ee) if val, ok := norm["DISCOVERY_URL"]; ok { delete(norm, "DISCOVERY_URL") if _, ok := norm["DISCOVERY"]; !ok { norm["DISCOVERY"] = val } } var sorted sort.StringSlice for k, _ := range norm { sorted = append(sorted, k) } sorted.Sort() out += "[Service]\n" for _, key := range sorted { val := norm[key] out += fmt.Sprintf("Environment=\"ETCD_%s=%s\"\n", key, val) } return }
// findFile finds a file that ends with name.md, ignoring leading digits and dashes (to support blogging and // sorting of .md files a-là jekyll) and returns it's name. It returns an error if no path is found. // Names ending with / are automatically added index to them. If there are multiple paths ending with name.md, // they are sorted lexicographically and the biggest path is returned, so e.g. 2014-01-01-results.md // will have preference over 2013-01-01-results.md func findFile(root, name string) (string, error) { if strings.HasSuffix(name, "/") || name == "" { name += "index" } name += ".md" basename := filepath.Base(name) dirname := filepath.Dir(name) matches, err := filepath.Glob(filepath.Join(root, dirname, "*"+basename)) if err != nil { return "", err } if len(matches) == 0 { return "", fmt.Errorf("no matches for pattern %s", name) } var prefixes sort.StringSlice for _, m := range matches { m = filepath.Base(m) if p := m[:len(m)-len(basename)]; isDigital(p) { prefixes = append(prefixes, p) } } if len(prefixes) == 0 { return "", fmt.Errorf("no matches for pattern %s", name) } prefixes.Sort() return filepath.Join(root, dirname, prefixes[len(prefixes)-1]+basename), nil }
func (d destinations) Less(i, j int) bool { switch d[i].routeFamily { case bgp.RF_FS_IPv4_UC, bgp.RF_FS_IPv6_UC, bgp.RF_FS_IPv4_VPN, bgp.RF_FS_IPv6_VPN, bgp.RF_FS_L2_VPN: var s, t *bgp.FlowSpecNLRI switch d[i].routeFamily { case bgp.RF_FS_IPv4_UC: s = &d[i].nlri.(*bgp.FlowSpecIPv4Unicast).FlowSpecNLRI t = &d[j].nlri.(*bgp.FlowSpecIPv4Unicast).FlowSpecNLRI case bgp.RF_FS_IPv6_UC: s = &d[i].nlri.(*bgp.FlowSpecIPv6Unicast).FlowSpecNLRI t = &d[j].nlri.(*bgp.FlowSpecIPv6Unicast).FlowSpecNLRI case bgp.RF_FS_IPv4_VPN: s = &d[i].nlri.(*bgp.FlowSpecIPv4VPN).FlowSpecNLRI t = &d[j].nlri.(*bgp.FlowSpecIPv4VPN).FlowSpecNLRI case bgp.RF_FS_IPv6_VPN: s = &d[i].nlri.(*bgp.FlowSpecIPv6VPN).FlowSpecNLRI t = &d[j].nlri.(*bgp.FlowSpecIPv6VPN).FlowSpecNLRI case bgp.RF_FS_L2_VPN: s = &d[i].nlri.(*bgp.FlowSpecL2VPN).FlowSpecNLRI t = &d[j].nlri.(*bgp.FlowSpecL2VPN).FlowSpecNLRI } if r, _ := bgp.CompareFlowSpecNLRI(s, t); r >= 0 { return true } else { return false } default: strings := sort.StringSlice{d[i].nlri.String(), d[j].nlri.String()} return strings.Less(0, 1) } }
func SortedStringHas(s sort.StringSlice, x string) bool { index := s.Search(x) if index == len(s) { return false } return s[s.Search(x)] == x }
func generalHelp() { out := tabwriter.NewWriter(os.Stderr, 0, 8, 1, '\t', 0) exe := filepath.Base(os.Args[0]) fmt.Fprintf(out, "USAGE:\n\t%s [global options] <command> [command options] [arguments...]\n\n", exe) fmt.Fprintf(out, "VERSION:\n\t%s\n\n", Version) fmt.Fprintf(out, "COMMANDS:\n") names := sort.StringSlice{} for name, _ := range subcommands { names = append(names, name) } names.Sort() for _, name := range names { cmd := subcommands[name] fmt.Fprintf(out, "\t%s\t%s\n", name, cmd.desc()) } fmt.Fprintln(out) fmt.Fprintf(out, "GLOBAL OPTIONS:\n") flag.VisitAll(func(f *flag.Flag) { prefix := "-" if len(f.Name) > 1 { prefix = "--" } fmt.Fprintf(out, "\t%s%s=%s\t%s\n", prefix, f.Name, f.DefValue, f.Usage) }) fmt.Fprintln(out) fmt.Fprintf(out, "Run \"%s help <command>\" for more details about a command.\n", exe) }
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage:\n%s [opts] template\n\nOptions:\n", os.Args[0]) flag.PrintDefaults() tdoc := map[string]string{ "{{.ID}}": "numeric ID of repo", "{{.Owner.Login}}": "github username of repo owner", "{{.Owner.ID}}": "github numeric id of repo owner", "{{.Name}}": "short name of repo (e.g. gitmirror)", "{{.FullName}}": "full name of repo (e.g. dustin/gitmirror)", "{{.Language}}": "repository language (if detected)", } a := sort.StringSlice{} for k := range tdoc { a = append(a, k) } a.Sort() fmt.Fprintf(os.Stderr, "\nTemplate parameters:\n") tw := tabwriter.NewWriter(os.Stderr, 8, 4, 2, ' ', 0) for _, k := range a { fmt.Fprintf(tw, " %v\t- %v\n", k, tdoc[k]) } tw.Flush() fmt.Fprintf(os.Stderr, "\nExample templates:\n"+ " http://example.com/gitmirror/{{.FullName}}.git\n"+ " http://example.com/gitmirror/{{.Owner.Login}}/{{.Language}}/{{.Name}}.git\n"+ " http://example.com/gitmirror/{{.Name}}.git\n") } }
func sliceData(lineData []byte) sort.StringSlice { var names sort.StringSlice for _, n := range strings.Split(string(lineData), ",") { names = append(names, n) } names.Sort() return names }
func SortedStringsDelete(s sort.StringSlice, x string) sort.StringSlice { index := s.Search(x) if len(s) != index && s[index] == x { s = append(s[:index], s[index+1:]...) } return s }
func (l list) String() string { var lines sort.StringSlice for k, v := range l.entry { lines = append(lines, fmt.Sprintf("%q:%v,\n", k, v)) } lines.Sort() return strings.Join(lines, "") }
// TestListUnitFilesOrder simply checks if "fleetctl list-unit-files" returns // an ordered list of units func TestListUnitFilesOrder(t *testing.T) { cluster, err := platform.NewNspawnCluster("smoke") if err != nil { t.Fatal(err) } defer cluster.Destroy(t) m, err := cluster.CreateMember() if err != nil { t.Fatal(err) } _, err = cluster.WaitForNMachines(m, 1) if err != nil { t.Fatal(err) } // Combine units var units []string for i := 1; i <= 20; i++ { unit := fmt.Sprintf("fixtures/units/hello@%02d.service", i) stdout, stderr, err := cluster.Fleetctl(m, "submit", unit) if err != nil { t.Fatalf("Failed to submit a batch of units: \nstdout: %s\nstder: %s\nerr: %v", stdout, stderr, err) } units = append(units, unit) } // make sure that all unit files will show up _, err = cluster.WaitForNUnitFiles(m, 20) if err != nil { t.Fatal("Failed to run list-unit-files: %v", err) } stdout, _, err := cluster.Fleetctl(m, "list-unit-files", "--no-legend", "--fields", "unit") if err != nil { t.Fatal("Failed to run list-unit-files: %v", err) } outUnits := strings.Split(strings.TrimSpace(stdout), "\n") var sortable sort.StringSlice for _, name := range units { n := path.Base(name) sortable = append(sortable, n) } sortable.Sort() var inUnits []string for _, name := range sortable { inUnits = append(inUnits, name) } if !reflect.DeepEqual(inUnits, outUnits) { t.Fatalf("Failed to get a sorted list of units from list-unit-files") } }
// Units lists all Units stored in the Registry, ordered by name. This includes both global and non-global units. func (r *EtcdRegistry) Units() ([]job.Unit, error) { key := r.prefixed(jobPrefix) opts := &etcd.GetOptions{ Sort: true, Recursive: true, } res, err := r.kAPI.Get(r.ctx(), key, opts) if err != nil { if isEtcdError(err, etcd.ErrorCodeKeyNotFound) { err = nil } return nil, err } // Fetch all units by hash recursively to avoid sending N requests to Etcd. hashToUnit, err := r.getAllUnitsHashMap() if err != nil { log.Errorf("failed fetching all Units from etcd: %v", err) return nil, err } unitHashLookupFunc := func(hash unit.Hash) *unit.UnitFile { stringHash := hash.String() unit, ok := hashToUnit[stringHash] if !ok { log.Errorf("did not find Unit %v in list of all units", stringHash) return nil } return unit } uMap := make(map[string]*job.Unit) for _, dir := range res.Node.Nodes { u, err := r.dirToUnit(dir, unitHashLookupFunc) if err != nil { log.Errorf("Failed to parse Unit from etcd: %v", err) continue } if u == nil { continue } uMap[u.Name] = u } var sortable sort.StringSlice for name, _ := range uMap { sortable = append(sortable, name) } sortable.Sort() units := make([]job.Unit, 0, len(sortable)) for _, name := range sortable { units = append(units, *uMap[name]) } return units, nil }
//Pulls all keys out of a map, sorts them, and returns them as an array. //This alows stable/sorted iteration over maps func sortedKeys(inMap map[string]Param) []string { keys := sort.StringSlice{} for key, _ := range inMap { keys = append(keys, key) } keys.Sort() return keys }
// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter. func (s sortedVoices) Less(i, j int) bool { var strs sort.StringSlice = []string{ s[i].instrument.Name(), s[j].instrument.Name(), } return strs.Less(0, 1) // sort.Strings(a) }
func (p paths) Less(i, j int) bool { if p[i].Nlri.String() == p[j].Nlri.String() { if p[i].Best { return true } } strings := sort.StringSlice{cidr2prefix(p[i].Nlri.String()), cidr2prefix(p[j].Nlri.String())} return strings.Less(0, 1) }
func (gen *modelGenerator) emitHeader(banner string) { imports := make(map[string]string, 0) visited := make(map[rdl.TypeName]rdl.TypeName, 0) for _, t := range gen.schema.Types { gen.requiredImports(t, imports, visited) } gen.emit(generationHeader(banner)) gen.emit("\n\npackage " + generationPackage(gen.schema, gen.ns) + "\n") if len(imports) > 0 { rdlEmitted := false jsonEmitted := false fmtEmitted := false var imp sort.StringSlice for k := range imports { if k == string(gen.schema.Name) { continue } kk := fmt.Sprintf("%q", k) if k == "fmt" { fmtEmitted = true } else if k == "encoding/json" { jsonEmitted = true } n := imports[k] if n != "" { if n == "rdl" { rdlEmitted = true } kk = n + " " + kk } imp = append(imp, kk) } imp.Sort() gen.emit("\nimport (\n") for _, k := range imp { gen.emit("\t" + k + "\n") } gen.emit(")\n") if rdlEmitted { gen.emit("\nvar _ = rdl.Version\n") } if jsonEmitted { if !rdlEmitted { gen.emit("\n") } gen.emit("var _ = json.Marshal\n") } if fmtEmitted { if !jsonEmitted && !rdlEmitted { gen.emit("\n") } gen.emit("var _ = fmt.Printf\n") } } }
func lsCommand(u string, args []string) { client, err := cbfsclient.New(u) cbfstool.MaybeFatal(err, "Error creating client: %v", err) result, err := client.List(lsFlags.Arg(0)) cbfstool.MaybeFatal(err, "Error listing directory: %v", err) dirnames := sort.StringSlice{} filenames := sort.StringSlice{} for k := range result.Dirs { dirnames = append(dirnames, k) } for k := range result.Files { filenames = append(filenames, k) } dirnames.Sort() filenames.Sort() if *lsDashL { totalFiles := 0 totalSize := uint64(0) tw := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0) for i := range dirnames { dn := dirnames[i] di := result.Dirs[dn] fmt.Fprintf(tw, "d %8s\t%s\t(%s descendants)\n", humanize.Bytes(uint64(di.Size)), dn, humanize.Comma(int64(di.Descendants))) totalSize += uint64(di.Size) totalFiles += di.Descendants } for i := range filenames { fn := filenames[i] fi := result.Files[fn] fmt.Fprintf(tw, "f %8s\t%s\t%s\n", humanize.Bytes(uint64(fi.Length)), fn, fi.Headers.Get("Content-Type")) totalSize += uint64(fi.Length) totalFiles++ } fmt.Fprintf(tw, "----------------------------------------\n") fmt.Fprintf(tw, "Tot: %s\t\t%s files\n", humanize.Bytes(totalSize), humanize.Comma(int64(totalFiles))) tw.Flush() } else { allnames := sort.StringSlice{} for i := range dirnames { allnames = append(allnames, dirnames[i]) } for i := range filenames { allnames = append(allnames, filenames[i]) } allnames.Sort() for _, a := range allnames { fmt.Println(a) } } }
func (c *Client) CanonicalizedOSSHeaders() string { var t sort.StringSlice for k, v := range c.Request.Header { k = strings.ToLower(k) if strings.HasPrefix(k, "x-oss-") { t = append(t, k+":"+strings.Join(v, ",")+"\n") } } t.Sort() return strings.Join(t, "") }
// Schedule returns all ScheduledUnits known by fleet, ordered by name func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) { key := r.prefixed(jobPrefix) opts := &etcd.GetOptions{ Sort: true, Recursive: true, Quorum: true, } res, err := r.kAPI.Get(r.ctx(), key, opts) if err != nil { if isEtcdError(err, etcd.ErrorCodeKeyNotFound) { err = nil } return nil, err } heartbeats := make(map[string]string) uMap := make(map[string]*job.ScheduledUnit) for _, dir := range res.Node.Nodes { _, name := path.Split(dir.Key) u := &job.ScheduledUnit{ Name: name, TargetMachineID: dirToTargetMachineID(dir), } heartbeats[name] = dirToHeartbeat(dir) uMap[name] = u } states, err := r.statesByMUSKey() if err != nil { return nil, err } var sortable sort.StringSlice // Determine the JobState of each ScheduledUnit for name, su := range uMap { sortable = append(sortable, name) key := MUSKey{ machID: su.TargetMachineID, name: name, } us := states[key] js := determineJobState(heartbeats[name], su.TargetMachineID, us) su.State = &js } sortable.Sort() units := make([]job.ScheduledUnit, 0, len(sortable)) for _, name := range sortable { units = append(units, *uMap[name]) } return units, nil }
func (m Manifest) EntryNames() []string { var names sort.StringSlice = make([]string, 0) for k, _ := range m { names = append(names, k) } names.Sort() return names }
// Schedule returns all ScheduledUnits known by fleet, ordered by name func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) { req := etcd.Get{ Key: path.Join(r.keyPrefix, jobPrefix), Sorted: true, Recursive: true, } res, err := r.etcd.Do(&req) if err != nil { if isKeyNotFound(err) { err = nil } return nil, err } heartbeats := make(map[string]string) uMap := make(map[string]*job.ScheduledUnit) for _, dir := range res.Node.Nodes { _, name := path.Split(dir.Key) u := &job.ScheduledUnit{ Name: name, TargetMachineID: dirToTargetMachineID(&dir), } heartbeats[name] = dirToHeartbeat(&dir) uMap[name] = u } states, err := r.statesByMUSKey() if err != nil { return nil, err } var sortable sort.StringSlice // Determine the JobState of each ScheduledUnit for name, su := range uMap { sortable = append(sortable, name) key := MUSKey{ machID: su.TargetMachineID, name: name, } us := states[key] js := determineJobState(heartbeats[name], su.TargetMachineID, us) su.State = &js } sortable.Sort() units := make([]job.ScheduledUnit, 0, len(sortable)) for _, name := range sortable { units = append(units, *uMap[name]) } return units, nil }