本文整理汇总了Golang中github.com/bradfitz/slice.Sort函数的典型用法代码示例。如果您正苦于以下问题:Golang Sort函数的具体用法?Golang Sort怎么用?Golang Sort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Sort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Sort
// Sort chronologically sorts a resume's work and volunteer experience items.
func (rsm *Resume) Sort() {
slice.Sort(rsm.Work, func(i, j int) bool {
return rsm.Work[i].StartDate.Before(rsm.Work[j].StartDate.Time)
})
slice.Sort(rsm.Volunteer, func(i, j int) bool {
return rsm.Volunteer[i].StartDate.Before(rsm.Volunteer[j].StartDate.Time)
})
}
示例2: GetNotification
func GetNotification(c web.C, w http.ResponseWriter, r *http.Request) {
var token = r.FormValue("token")
var userId int
//init my empty struct who contains an array string for login user
notifs := Notifications{}
//check if token exist
if CheckToken(token, w) == false {
return
}
//check if token matches with an user Id
if userId = GetUserIdWithToken(token, w); userId == -1 {
return
}
a := MyAppend(GetMessageNotification(userId), GetLikeNotification(userId))
notifs.Notif = MyAppend(a, GetVisiteNotification(userId))
slice.Sort(notifs.Notif[:], func(i, j int) bool {
if strings.Compare(notifs.Notif[i].CreateAt, notifs.Notif[j].CreateAt) > 0 {
return true
} else {
return false
}
})
notifs.Status = "OK"
go MakeNotifAsRead(userId)
RenderJSON(w, notifs, http.StatusOK)
}
示例3: makeChart
func makeChart(r opentsdb.ResponseSet, m_units map[string]string) ([]*chartSeries, error) {
var series []*chartSeries
for _, resp := range r {
dps := make([][2]float64, 0)
for k, v := range resp.DPS {
ki, err := strconv.ParseInt(k, 10, 64)
if err != nil {
return nil, err
}
dps = append(dps, [2]float64{float64(ki), float64(v)})
}
if len(dps) > 0 {
slice.Sort(dps, func(i, j int) bool {
return dps[i][0] < dps[j][0]
})
name := resp.Metric
if len(resp.Tags) > 0 {
name += resp.Tags.String()
}
series = append(series, &chartSeries{
Name: name,
Metric: resp.Metric,
Tags: resp.Tags,
Data: dps,
Unit: m_units[resp.Metric],
})
}
}
return series, nil
}
示例4: SortByCounter
// SortByCounter sorts the list by the counter of the word
func (digester *Digester) SortByCounter(order string) {
data := digester.GetData()
slice.Sort(data, func(i, j int) bool {
if order == "ASC" {
return data[i].GetCounter() <= data[j].GetCounter()
}
return data[i].GetCounter() > data[j].GetCounter()
})
}
示例5: BenchmarkIntSlice
func BenchmarkIntSlice(b *testing.B) {
s := make([]int, len(intdata))
b.ResetTimer()
for i := 0; i < b.N; i++ {
copy(s, intdata)
slice.Sort(s, func(i, j int) bool {
return s[i] > s[j]
})
}
}
示例6: BenchmarkStringSlice
func BenchmarkStringSlice(b *testing.B) {
s := make([]string, len(strdata))
b.ResetTimer()
for i := 0; i < b.N; i++ {
copy(s, strdata)
slice.Sort(s, func(i, j int) bool {
return s[i] > s[j]
})
}
}
示例7: String
func (r Route) String() string {
rt := []string{}
for _, part := range r.parts {
rt = append(rt, part.String())
}
slice.Sort(rt, func(i, j int) bool {
return rt[i] < rt[j]
})
return fmt.Sprintf("Route(%s)", strings.Join(rt, " && "))
}
示例8: getLastNotification
func (notification *Notification) getLastNotification() SimpleNotificationList {
v := GroupedList{}
ret := SimpleNotificationList{}
lastWeek := time.Now().AddDate(0, 0, -7)
//Get from database all notification between now and a week ago, we group them by type and IdLink
curs, _ := r.Table("notifications").
Filter(r.Row.Field("UserId").Eq(notification.user.Id)).
Filter(r.Row.Field("CreatedAt").Gt(lastWeek)).
OrderBy("-CreatedAt").
Group("Type", "IdLink").
Run(api.Sess)
curs.All(&v.List)
//We sort all notification to avoid had identic notifications.
var arraySimpleNotification []SimpleNotification
for _, group := range v.List {
simple := SimpleNotification{
Type: group.Group[0].(string),
IdLink: group.Group[1].(string),
Read: true,
}
var create time.Time
var index = -1
for j, notif := range group.Reduction {
if notif.Read == false {
simple.Read = false
}
if create.Before(notif.CreatedAt) == true {
create = notif.CreatedAt
index = j
}
}
simple.CreatedAt = create
simple.Name = group.Reduction[index].Name
simple.Others = len(group.Reduction) - 1
arraySimpleNotification = append(arraySimpleNotification, simple)
}
//Sort by createDate
slice.Sort(arraySimpleNotification[:], func(i, j int) bool {
return arraySimpleNotification[i].CreatedAt.After(arraySimpleNotification[j].CreatedAt)
})
ret.List = arraySimpleNotification
return ret
}
示例9: cmdSummary
func cmdSummary(d db.DB, periodS, firstDayS string) {
period, err := datetime.ParsePeriod(periodS)
if err != nil {
fatal(err)
}
firstDay, err := datetime.ParseWeekday(firstDayS)
if err != nil {
fatal(err)
}
categories, err := d.Categories()
if err != nil {
fatal(err)
}
itr, err := NewSummaryIterator(d, period, firstDay, time.Now())
if err != nil {
fatal(err)
}
defer itr.Close()
for {
if summary, err := itr.Next(); err == io.EOF {
break
} else if err != nil {
fatal(err)
} else {
fmt.Printf("%s\n\n", PeriodHeadline(summary.From, summary.To, period))
names := make(map[string]string)
order := make([]string, 0, len(summary.Categories))
for id, _ := range summary.Categories {
names[id] = FormatCategory(categories.Path(id))
order = append(order, id)
}
slice.Sort(order, func(i, j int) bool {
return summary.Categories[order[i]] > summary.Categories[order[j]]
})
t := table.New().Padding(" ")
for _, id := range order {
d := FormatDuration(summary.Categories[id])
t.Add(table.String(names[id]), table.String(d).Align(table.Right))
}
fmt.Printf("%s\n", Indent(t.String(), " "))
}
}
}
示例10: Available
// Available return the migrations in the environment's directory sorted in
// ascending lexicographic order.
func (s Service) Available() ([]*Migration, error) {
files, _ := filepath.Glob(filepath.Join(s.env.Directory, "*.sql")) // The only possible error here is a pattern error
var migrations []*Migration
for _, file := range files {
migration, err := NewMigration(file)
if err != nil {
return nil, err
}
migrations = append(migrations, migration)
}
slice.Sort(migrations, func(i, j int) bool {
return migrations[i].Name < migrations[j].Name
})
return migrations, nil
}
示例11: Root
// Tree returns the root node of the category tree.
func (c CategoryMap) Root() *CategoryNode {
index := map[string]*CategoryNode{"": &CategoryNode{}}
for _, category := range c {
parent := index[category.ParentID]
if parent == nil {
parent = &CategoryNode{}
index[category.ParentID] = parent
}
node := index[category.ID]
if node == nil {
node = &CategoryNode{}
index[category.ID] = node
}
node.Category = category
parent.Children = append(parent.Children, node)
slice.Sort(parent.Children, func(i, j int) bool {
return parent.Children[i].Name < parent.Children[j].Name
})
}
return index[""]
}
示例12: ExprGraph
func (s *Schedule) ExprGraph(t miniprofiler.Timer, unit string, res []*expr.Result) (chart.Chart, error) {
c := chart.ScatterChart{
Key: chart.Key{Pos: "itl"},
YRange: chart.Range{Label: unit},
}
c.XRange.Time = true
for ri, r := range res {
rv := r.Value.(expr.Series)
pts := make([]chart.EPoint, len(rv))
idx := 0
for k, v := range rv {
pts[idx].X = float64(k.Unix())
pts[idx].Y = v
idx++
}
slice.Sort(pts, func(i, j int) bool {
return pts[i].X < pts[j].X
})
c.AddData(r.Group.String(), pts, chart.PlotStyleLinesPoints, Autostyle(ri))
}
return &c, nil
}
示例13: Applied
// Applied return the migrations in the environment's directory that are marked
// as applied in the database sorted in ascending lexicographic order.
func (s Service) Applied() ([]*Migration, error) {
files, err := s.conn.GetApplied()
if err != nil {
return nil, err
}
var migrations []*Migration
for _, file := range files {
migration, err := NewMigration(filepath.Join(s.env.Directory, file))
if err != nil {
return nil, err
}
migrations = append(migrations, migration)
}
slice.Sort(migrations, func(i, j int) bool {
return migrations[i].Name < migrations[j].Name
})
return migrations, nil
}
示例14: getNearestPoints
// GET /points/nearest?lat=*&lng=*&dist=_
func getNearestPoints(w http.ResponseWriter, r *http.Request) {
badRequestError := Response{"error", 400, "Bad Request", nil}
params := r.URL.Query()
lat, err1 := strconv.ParseFloat(params.Get("lat"), 64)
lng, err2 := strconv.ParseFloat(params.Get("lng"), 64)
if err1 != nil || err2 != nil {
routes.ServeJson(w, badRequestError)
return
}
maxDistance := float64(50)
if d, err := strconv.ParseFloat(params.Get("dist"), 32); err == nil {
maxDistance = d
}
currentPoint := geo.NewPoint(lat, lng)
var p Point
result := make([]distanceRecord, 0)
iter := Points.Find(bson.M{}).Iter()
for iter.Next(&p) {
lat, _ := strconv.ParseFloat(p.Latitude, 64)
lng, _ := strconv.ParseFloat(p.Longitude, 64)
point := geo.NewPoint(lat, lng)
distance := currentPoint.GreatCircleDistance(point) * 1000
if distance <= maxDistance {
result = append(result, distanceRecord{p.Id, distance})
}
}
slice.Sort(result, func(i, j int) bool {
return result[i].Distance < result[j].Distance
})
routes.ServeJson(w, result)
}
示例15: GatherStats
func GatherStats(config models.Configuration) (stats []models.Status) {
stats = []models.Status{}
for _, server := range config.Servers {
pingSuccess := testPing(server.Hostname, false, config)
var httpSuccess bool
if server.Url != "" {
httpSuccess = testHttp(server.Url, config)
}
status := models.Status{
Name: server.Name,
HttpPresent: server.Url != "",
HttpSuccess: httpSuccess,
PingSuccess: pingSuccess,
Created: time.Now(),
}
stats = append(stats, status)
}
slice.Sort(stats[:], func(i, j int) bool {
return stats[i].Name < stats[j].Name
})
return stats
}