Debian Codegraph @

utils/utils.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package utils
5
6 import (
7 "fmt"
8 "math"
9 "os"
10 "strings"
11 "time"
12
13 "github.com/etix/mirrorbits/core"
14 )
15
16 const (
17 // DegToRad is a constant to convert degrees to radians
18 DegToRad = 0.017453292519943295769236907684886127134428718885417 // N[Pi/180, 50]
19 // RadToDeg is a constant to convert radians to degrees
20 RadToDeg = 57.295779513082320876798154814105170332405472466564 // N[180/Pi, 50]
21 )
22
23 // HasAnyPrefix reports whether the string s begins with any of the prefixes
24 func HasAnyPrefix(s string, prefixes ...string) bool {
25 for _, p := range prefixes {
26 if strings.HasPrefix(s, p) {
27 return true
28 }
29 }
30 return false
31 }
32
33 // NormalizeURL adds a trailing slash to the URL
34 func NormalizeURL(url string) string {
35 if url != "" && !strings.HasSuffix(url, "/") {
36 url += "/"
37 }
38 return url
39 }
40
41 // GetDistanceKm returns the distance in km between two coordinates
42 func GetDistanceKm(lat1, lon1, lat2, lon2 float32) float32 {
43 var R float32 = 6371 // radius of the earth in Km
44 dLat := (lat2 - lat1) * float32(DegToRad)
45 dLon := (lon2 - lon1) * float32(DegToRad)
46 a := math.Sin(float64(dLat/2))*math.Sin(float64(dLat/2)) + math.Cos(float64(lat1*DegToRad))*math.Cos(float64(lat2*DegToRad))*math.Sin(float64(dLon/2))*math.Sin(float64(dLon/2))
47
48 c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
49 return R * float32(c)
50 }
51
52 // Min returns the smallest of the two values
53 func Min(v1, v2 int) int {
54 if v1 < v2 {
55 return v1
56 }
57 return v2
58 }
59
60 // Max returns the highest of the two values
61 func Max(v1, v2 int) int {
62 if v1 > v2 {
63 return v1
64 }
65 return v2
66 }
67
68 // Add does a simple addition
69 func Add(x, y int) int {
70 return x + y
71 }
72
73 // Version returns the version as a string
74 func Version() string {
75 return core.VERSION
76 }
77
78 // Hostname return the host name as a string
79 func Hostname() string {
80 hostname, _ := os.Hostname()
81 return hostname
82 }
83
84 // IsInSlice returns true is `a` is contained in `list`
85 // Warning: this is slow, don't use it for long datasets
86 func IsInSlice(a string, list []string) bool {
87 for _, b := range list {
88 if b == a {
89 return true
90 }
91 }
92 return false
93 }
94
95 // IsStopped returns true if a stop has been requested
96 func IsStopped(stop <-chan struct{}) bool {
97 select {
98 case <-stop:
99 return true
100 default:
101 return false
102 }
103 }
104
105 // ReadableSize returns a file size in a human readable form
106 func ReadableSize(value int64) string {
107 units := []string{"bytes", "KiB", "MiB", "GiB", "TiB"}
108
109 v := float64(value)
110
111 for _, u := range units {
112 if v < 1024 || u == "TiB" {
113 return fmt.Sprintf("%3.1f %s", v, u)
114 }
115 v /= 1024
116 }
117 return ""
118 }
119
120 // ElapsedSec returns true if lastTimestamp + elapsed time is in the past
121 func ElapsedSec(lastTimestamp int64, elapsedTime int64) bool {
122 if lastTimestamp+elapsedTime < time.Now().UTC().Unix() {
123 return true
124 }
125 return false
126 }
127
128 // Plural returns a single 's' if there are more than one value
129 func Plural(value any) string {
130 n, ok := value.(int)
131 if ok && n > 1 || n < -1 {
132 return "s"
133 }
134 return ""
135 }
136
137 // ConcatURL concatenate the url and path
138 func ConcatURL(url, path string) string {
139 if strings.HasSuffix(url, "/") && strings.HasPrefix(path, "/") {
140 return url[:len(url)-1] + path
141 }
142 if !strings.HasSuffix(url, "/") && !strings.HasPrefix(path, "/") {
143 return url + "/" + path
144 }
145 return url + path
146 }
147
148 // FormattedDateUTC returns the date formatted as RFC1123
149 func FormattedDateUTC(t time.Time) string {
150 return t.UTC().Format(time.RFC1123)
151 }
152
153 // IsZero returns whether the date represents the zero time instant
154 func IsZero(t time.Time) bool {
155 return t.IsZero()
156 }
157
158 // TimeKeyCoverage returns a slice of strings covering the date range
159 // used in the redis backend.
160 func TimeKeyCoverage(start, end time.Time) (dates []string) {
161 if start.Day() == end.Day() && start.Month() == end.Month() && start.Year() == end.Year() {
162 dates = append(dates, start.Format("2006_01_02"))
163 return
164 }
165
166 if start.Day() != 1 {
167 month := start.Month()
168 for {
169 if start.Month() != month || start.Equal(end) {
170 break
171 }
172 dates = append(dates, start.Format("2006_01_02"))
173 start = start.AddDate(0, 0, 1)
174 }
175 }
176
177 for {
178 tmpyear := time.Date(start.Year()+1, 1, 1, 0, 0, 0, 0, start.Location())
179 tmpmonth := time.Date(start.Year(), start.Month()+1, 1, 0, 0, 0, 0, start.Location())
180 if start.Day() == 1 && start.Month() == 1 && (tmpyear.Before(end) || tmpyear.Equal(end)) {
181 dates = append(dates, start.Format("2006"))
182 start = tmpyear
183 } else if tmpmonth.Before(end) || tmpmonth.Equal(end) {
184 dates = append(dates, start.Format("2006_01"))
185 start = tmpmonth
186 } else {
187 break
188 }
189 }
190
191 for {
192 if start.AddDate(0, 0, 1).After(end) {
193 break
194 }
195 dates = append(dates, start.Format("2006_01_02"))
196 start = start.AddDate(0, 0, 1)
197 }
198
199 return
200 }
201
202 // FuzzyTimeStr returns the duration as fuzzy time
203 func FuzzyTimeStr(duration time.Duration) string {
204 hours := duration.Hours()
205 minutes := duration.Minutes()
206
207 if int(minutes) == 0 {
208 return "up-to-date"
209 }
210
211 if minutes < 0 {
212 return "in the future"
213 }
214
215 if hours < 1 {
216 return fmt.Sprintf("%d minute%s ago", int(duration.Minutes()), Plural(int(duration.Minutes())))
217 }
218
219 if hours/24 < 1 {
220 return fmt.Sprintf("%d hour%s ago", int(hours), Plural(int(hours)))
221 }
222
223 if hours/24/365 > 1 {
224 return fmt.Sprintf("%d year%s ago", int(hours/24/365), Plural(int(hours/24/365)))
225 }
226
227 return fmt.Sprintf("%d day%s ago", int(hours/24), Plural(int(hours/24)))
228 }
229
230 // SanitizeLocationCodes sanitizes the given location codes
231 func SanitizeLocationCodes(input string) string {
232 input = strings.Replace(input, ",", " ", -1)
233 ccodes := strings.Fields(input)
234 output := ""
235 for _, c := range ccodes {
236 output += strings.ToUpper(c) + " "
237 }
238 return strings.TrimRight(output, " ")
239 }