forked from schollz/find
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
executable file
·291 lines (256 loc) · 7.27 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.
// utils.go is a collection of generic functions that are not specific to FIND.
package main
import (
"bytes"
"compress/flate"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"math"
"math/rand"
"net"
"os"
"strings"
"time"
"log"
)
var (
// Trace is a logging handler
Trace *log.Logger
// Info is a logging handler
Info *log.Logger
// Warning is a logging handler
Warning *log.Logger
// Debug is a logging handler
Debug *log.Logger
// Error is a logging handler
Error *log.Logger
)
// Init function for generating the logging handlers
func Init(
traceHandle io.Writer,
infoHandle io.Writer,
debugHandle io.Writer,
warningHandle io.Writer,
errorHandle io.Writer) {
Trace = log.New(traceHandle,
"TRACE : ",
log.Ldate|log.Ltime|log.Lshortfile)
Info = log.New(infoHandle,
"INFO : ",
log.Ldate|log.Ltime|log.Lshortfile)
Debug = log.New(debugHandle,
"DEBUG: ",
log.Ldate|log.Ltime|log.Lshortfile)
Warning = log.New(warningHandle,
"WARN : ",
log.Ldate|log.Ltime|log.Lshortfile)
Error = log.New(errorHandle,
"ERR : ",
log.Ldate|log.Ltime|log.Lshortfile)
}
func init() {
Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stdout, os.Stderr)
// Trace.Println("I have something standard to say")
// Info.Println("Special Information")
// Warning.Println("There is something you need to know about")
// Error.Println("Something has failed")
}
// GetLocalIP returns the local ip address
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "localhost"
}
bestIP := "localhost"
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil && (strings.Contains(ipnet.IP.String(), "192.168.1") || strings.Contains(ipnet.IP.String(), "192.168")) {
return ipnet.IP.String()
}
}
}
return bestIP
}
// stringInSlice returns boolean of whether a string is in a slice.
func stringInSlice(s string, strings []string) bool {
for _, k := range strings {
if s == k {
return true
}
}
return false
}
// timeTrack can be defered to provide function timing.
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
Debug.Println(name, " took ", elapsed)
}
// getMD5Hash returns a md5 hash of string.
func getMD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
// average64 computes the average of a float64 slice.
func average64(vals []float64) float64 {
sum := float64(0)
for _, val := range vals {
sum += float64(val)
}
return sum / float64(len(vals))
}
// standardDeviation64 computes the standard deviation of a float64 slice.
func standardDeviation64(vals []float64) float64 {
meanVal := average64(vals)
sum := float64(0)
for _, val := range vals {
sum += math.Pow(float64(val)-meanVal, 2)
}
sum = sum / (float64(len(vals)) - 1)
sd := math.Sqrt(sum)
return float64(sd)
}
// standardDeviation comptues the standard deviation of a float32 slice.
func standardDeviation(vals []float32) float32 {
sum := float64(0)
for _, val := range vals {
sum += float64(val)
}
meanVal := sum / float64(len(vals))
sum = float64(0)
for _, val := range vals {
sum += math.Pow(float64(val)-meanVal, 2)
}
sum = sum / (float64(len(vals)) - 1)
sd := math.Sqrt(sum)
return float32(sd)
}
// compressByte returns a compressed byte slice.
func compressByte(src []byte) []byte {
compressedData := new(bytes.Buffer)
compress(src, compressedData, 9)
return compressedData.Bytes()
}
// decompressByte returns a decompressed byte slice.
func decompressByte(src []byte) []byte {
compressedData := bytes.NewBuffer(src)
deCompressedData := new(bytes.Buffer)
decompress(compressedData, deCompressedData)
return deCompressedData.Bytes()
}
// compress uses flate to compress a byte slice to a corresponding level
func compress(src []byte, dest io.Writer, level int) {
compressor, _ := flate.NewWriter(dest, level)
compressor.Write(src)
compressor.Close()
}
// compress uses flate to decompress an io.Reader
func decompress(src io.Reader, dest io.Writer) {
decompressor := flate.NewReader(src)
io.Copy(dest, decompressor)
decompressor.Close()
}
// src is seeds the random generator for generating random strings
var src = rand.NewSource(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// RandStringBytesMaskImprSrc prints a random string
func RandStringBytesMaskImprSrc(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// exists returns whether the given file or directory exists or not
// from http://stackoverflow.com/questions/10510691/how-to-check-whether-a-file-or-directory-denoted-by-a-path-exists-in-golang
func exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}
// CopyFile copies a file from src to dst. If src and dst files exist, and are
// the same, then return success. Otherise, attempt to create a hard link
// between the two files. If that fail, copy the file contents from src to dst.
// from http://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
func CopyFile(src, dst string) (err error) {
sfi, err := os.Stat(src)
if err != nil {
return
}
if !sfi.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
return fmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err := os.Stat(dst)
if err != nil {
if !os.IsNotExist(err) {
return
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return
}
}
if err = os.Link(src, dst); err == nil {
return
}
err = copyFileContents(src, dst)
return
}
// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
// from http://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
func copyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}