_id
stringlengths
40
40
text
stringlengths
81
2.19k
title
stringclasses
1 value
1de3392374d9324fe3f9aefb32b7c61d6fe684c4
--- +++ @@ -12,7 +12,7 @@ file, err := sourceFromCPath(path) - if err != nil { + if file == nil || err != nil { fmt.Printf("Error opening path: %s", err.Error()) return C.MovieInfo{} }
28ccd9b63abf673cb565e143297a3a45f4233202
--- +++ @@ -32,7 +32,7 @@ var ds directives for _, comment := range doc.List { if strings.HasPrefix(comment.Text, prefix) { - ds = append(ds, strings.TrimPrefix(comment.Text, prefix)) + ds = append(ds, strings.TrimSpace(strings.TrimPrefix(comment.Text, prefix))) } } return ds
ac23b7e90b207a9c0edbcce11782b86e57ebcfcf
--- +++ @@ -1 +1,34 @@ package namecheap + +import ( + "net/url" + "testing" +) + +func TestNewClient(t *testing.T) { + c := NewClient("anApiUser", "anToken", "anUser") + + if c.BaseURL != defaultBaseURL { + t.Errorf("NewClient BaseURL = %v, want %v", c.BaseURL, defaultBaseURL) + } +} + +// Verify that the MakeRequest function assembles the correct API URL +func TestMakeRequest(t *testing.T) { + c := NewClient("anApiUser", "anToken", "anUser") + c.BaseURL = "https://fake-api-server/" + requestInfo := ApiRequest{ + method: "GET", + command: "namecheap.domains.getList", + params: url.Values{}, + } + req, _ := c.makeRequest(requestInfo, nil) + + // correctly assembled URL + outURL := "https://fake-api-server/?ApiKey=anToken&ApiUser=anApiUser&ClientIp=127.0.0.1&Command=namecheap.domains.getList&UserName=anUser" + + // test that URL was correctly assembled + if req.URL.String() != outURL { + t.Errorf("NewRequest() URL = %v, want %v", req.URL, outURL) + } +}
295dcb8ae51ee9d2a1395b16a18036aa7ba48d51
--- +++ @@ -1,7 +1,7 @@ package main // Shifts all the values in xs by one and puts x at the beginning. -func Shift(xs []float64, x float64) { +func Shift(xs []Vector, x Vector) { for i := len(xs) - 1; i > 0; i-- { @@ -11,13 +11,13 @@ xs[0] = x } -type Integrator func(xs, vs []float64, a, dt float64) +type Integrator func(xs, vs []Vector, a Vector, dt float64) // Performs a step of an Euler integration -func Euler(xs, vs []float64, a, dt float64) { +func Euler(xs, vs []Vector, a Vector, dt float64) { - v := vs[0] + dt*a - x := xs[0] + dt*v + v := vs[0].Plus(a.Scale(dt)) + x := xs[0].Plus(v.Scale(dt)) Shift(vs, v) Shift(xs, x) @@ -26,12 +26,12 @@ // Performs a step of a Verlet integrator // // Note that v[0] will not be calculated until the next step -func Verlet(xs, vs []float64, a, dt float64) { +func Verlet(xs, vs []Vector, a Vector, dt float64) { - xNext := 2*xs[0] - xs[1] + dt*dt*a - v[0] = (xNext - xs[1]) / (2 * dt) + xNext := xs[0].Scale(2).Minus(xs[1]).Plus(a.Scale(dt * dt)) + vs[0] = xNext.Minus(xs[1]).Scale(1 / (2 * dt)) - Shift(vs, 0) + Shift(vs, NewZeroVector()) Shift(xs, xNext) }
fee5fd857d523feecb657dcf93153708fac48ea6
--- +++ @@ -32,6 +32,9 @@ a3 := ops.NewAttr(in, "status:active") q := ops.NewIntersection(ops.NewUnion(a1, a2), a3) q.Add(a3) + + fmt.Printf("%v\n", in.Header()) + var d *index.IbDoc for true { d = q.NextDoc(d)
a74865de5f131954256681125261ae21ba9673f1
--- +++ @@ -25,7 +25,7 @@ This command groups subcommands for interacting with Nomad's Autopilot subsystem. Autopilot provides automatic, operator-friendly management of Nomad servers. The command can be used to view or modify the current Autopilot - configuration. + configuration. For a full guide see: https://www.nomadproject.io/guides/autopilot.html Get the current Autopilot configuration:
53c9e890a2ae8790c801a7435758b1dedd2304d0
--- +++ @@ -40,7 +40,7 @@ } func (fs *Filesystem) Translate(src string) (dest string, err error) { - return filepath.Join(fs.PublishDir, src), nil + return filepath.Join(fs.PublishDir, filepath.FromSlash(src)), nil } func (fs *Filesystem) extension(ext string) string {
7457b3668b9902d4f90fde9e171c3dd4b23792c8
--- +++ @@ -10,9 +10,10 @@ func (e *Executor) PrintTasksHelp() { tasks := e.tasksWithDesc() if len(tasks) == 0 { + e.outf("task: No tasks with description available") return } - e.outf("Available tasks for this project:") + e.outf("task: Available tasks for this project:") // Format in tab-separated columns with a tab stop of 8. w := tabwriter.NewWriter(e.Stdout, 0, 8, 0, '\t', 0)
19483c59c12b2208dd919209b6e481c205713e0c
--- +++ @@ -1,8 +1,10 @@ package main import ( + "context" "fmt" "os" + "time" "strings" @@ -32,7 +34,11 @@ } c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"])) - project, _, err := c.GetProject("pypi", "cookiecutter") + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + project, _, err := c.GetProject(ctx, "pypi", "cookiecutter") if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err)
027a290a2d885cf93d296769570a840a78b2981d
--- +++ @@ -2,7 +2,7 @@ import ( "fmt" - "io" + //"io" //"io/ioutil" "log" "net/http" @@ -11,7 +11,12 @@ ) func receive(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Hello world!") + + wholeurl := r.URL.String() + body := r.URL.Query()["Body"] + phone := r.URL.Query()["From"] + + fmt.Printf("wholeurl:\n%s\n\nPhone: %s\nBody: %s,\n\n", wholeurl, phone, body) } func main() { @@ -21,13 +26,15 @@ // log.Fatal(err) //} //port := strings.TrimSpace(string(fileContents)) + if len(os.Args) != 2 { log.Fatal("usage: server.go port") } + port := ":" + os.Args[1] // Start the server. fmt.Printf("Starting TxtRoulette server on port %s...\n", port) - http.HandleFunc("/receive", receive) + http.HandleFunc("/receive/", receive) log.Fatal(http.ListenAndServe(port, nil)) }
4a9e5b8400456fdb397ec1e737c47ca3d861d804
--- +++ @@ -9,7 +9,6 @@ ) func main() { - router, err := rest.MakeRouter( &rest.Route{"GET", "/stream", StreamThings}, ) @@ -19,10 +18,7 @@ api := rest.NewApi(router) api.Use(&rest.AccessLogApacheMiddleware{}) - api.Use(&rest.TimerMiddleware{}) - api.Use(&rest.RecorderMiddleware{}) - api.Use(&rest.RecoverMiddleware{}) - + api.Use(rest.DefaultCommonStack...) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
40809336d676a25237a2619bb7fb94849213a529
--- +++ @@ -46,3 +46,8 @@ func Unauthorized(err error) error { return APIError{err, http.StatusUnauthorized} } + +// ServerError represents http error with 500 code +func ServerError(err error) error { + return APIError{err, http.StatusInternalServerError} +}
1d12f0c27539db3aebfff890e21259f57dff6ae8
--- +++ @@ -18,7 +18,7 @@ } case string: out[prefix[1:]] = vv - case int: + case float64: out[prefix[1:]] = vv case bool: out[prefix[1:]] = vv
3e46977ec15093ff8fcf84bf5d3e339c17a06630
--- +++ @@ -1,6 +1,9 @@ package stacktrace -import "testing" +import ( + "strings" + "testing" +) func captureFunc() Stacktrace { return Capture(0) @@ -18,7 +21,8 @@ if expected := "captureFunc"; frame.Function != expected { t.Fatalf("expteced function %q but recevied %q", expected, frame.Function) } - if expected := "github.com/opencontainers/runc/libcontainer/stacktrace"; frame.Package != expected { + expected := "github.com/opencontainers/runc/libcontainer/stacktrace" + if !strings.HasSuffix(frame.Package, expected) { t.Fatalf("expected package %q but received %q", expected, frame.Package) } if expected := "capture_test.go"; frame.File != expected {
e8e795c97378e6bd4cf6d693c23e6d8e90429a4e
--- +++ @@ -31,15 +31,10 @@ assertEqual(2, addOne(1)) } -func testPerf() { +func main() { start := time.Now() - fib(10) + testMath() + testFunctions() + fmt.Print("Pass!") fmt.Println("Took ", time.Since(start)) } - -func main() { - testMath() - testFunctions() - testPerf() - fmt.Print("Pass!") -}
06c0856961c3def11f2af425f41717e1bf7388cc
--- +++ @@ -13,3 +13,10 @@ } return session } + +// RSessionErr always returns a nil err. It will panic if it cannot +// get a db session. This function is meant to be used with the +// databaseSessionFilter for unit testing. +func RSessionErr() (*r.Session, error) { + return RSession(), nil +}
adedb81854fbe6263e409bb510947b39331d39a0
--- +++ @@ -7,9 +7,9 @@ "github.com/aviddiviner/tricks" ) -var animals = []string{"dog", "cat", "bear", "cow", "bull", "pig", "iguana"} +func ExampleSlice() { + animals := []string{"dog", "cat", "bear", "cow", "bull", "pig", "iguana"} -func ExampleSlice() { bearCow := tricks.Slice(animals). Map(strings.ToUpper). Last(5). @@ -17,26 +17,27 @@ Value().([]string) fmt.Println(bearCow) - // Output: [BEAR COW] -} - -func ExampleSlice_groupBy() { - byLength := tricks.Slice(animals). - Copy().Sort(). - GroupBy(func(s string) int { return len(s) }). - Value().(map[int][]string) - - fmt.Println(byLength[3]) - - // Output: [cat cow dog pig] } func ExampleSlice_strings() { password := tricks.Slice([]rune("abracadabra")).Reverse().Value().([]rune) fmt.Println(string(password)) - // Output: arbadacarba } // TODO: Add variadic example. + +func ExampleTrickSlice_GroupBy() { + animals := []string{"dog", "cat", "bear", "cow", "bull", "pig", "iguana"} + + byLength := tricks.Slice(animals). + Copy(). + Sort(). + Reverse(). + GroupBy(func(s string) int { return len(s) }). + Value().(map[int][]string) + + fmt.Println(byLength[3]) + // Output: [pig dog cow cat] +}
b38a3185dda1d8c820d604e186de0008343182b3
--- +++ @@ -10,10 +10,5 @@ return true } - httpClone, _ := git.Config("--bool hub.http-clone") - if httpClone == "true" { - return true - } - return false }
2a1d3b6d6408df98f095497c8555bd111d60e1d8
--- +++ @@ -1,10 +1,16 @@ package main import ( + "flag" + "github.com/datamaglia/gimbal/spinner" ) +var filename = flag.String("f", "", "Read the config from a file") + func main() { - config := spinner.LoadJsonConfig("test.json") + flag.Parse() + + config := spinner.LoadJsonConfig(*filename) spinner.ExecuteTestConfig(config) }
41f48b4306e50a2f3d42169b5a7f97a8b91fec01
--- +++ @@ -9,18 +9,27 @@ GetSbomsEndpoint = "v1/project/getSBOMs" ) +// SBOMMetadata contains various piece of metadata about a particular SBOM +type SBOMMetadata struct { + EntryCount int `json:"entry_count"` + ResolvedEntryCount int `json:"resolved_entry_count"` + PartiallyResolvedEntryCount int `json:"partially_resolved_entry_count"` + UnresolvedEntryCount int `json:"unresolved_entry_count"` +} + // SBOM represents a software list containing zero or more SBOMEntry objects. type SBOM struct { - ID string `json:"id"` - Name string `json:"sbom_name"` - Version string `json:"sbom_version"` - Supplier string `json:"supplier_name"` - SbomStatus string `json:"sbom_status"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - EntryCount int `json:"entry_count"` - Entries []SBOMEntry `json:"entries"` - TeamID string `json:"team_id"` - OrgID string `json:"org_id"` - RulesetID string `json:"ruleset_id"` + ID string `json:"id"` + Name string `json:"sbom_name"` + Version string `json:"sbom_version"` + Supplier string `json:"supplier_name"` + SbomStatus string `json:"sbom_status"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + EntryCount int `json:"entry_count"` + Metadata SBOMMetadata `json:"metadata"` + Entries []SBOMEntry `json:"entries"` + TeamID string `json:"team_id"` + OrgID string `json:"org_id"` + RulesetID string `json:"ruleset_id"` }
d88c143068752c24375a23ed48434604499b2422
--- +++ @@ -35,13 +35,3 @@ y := `{"ok":false,"error":"not_authed","revoked":false}` CheckResponse(t, x, y) } - -func TestAuthTest(t *testing.T) { - s := New() - x, err := s.AuthTest() - if err != nil { - t.Fatal(err) - } - y := `{"ok":false,"error":"not_authed","team":"","team_id":"","url":"","user":"","user_id":""}` - CheckResponse(t, x, y) -}
18d63456bc4be5f5d7c8aac402b8758a73e23b38
--- +++ @@ -24,21 +24,7 @@ out := numerics.Sequence() const expectedCount = 100 - actualArea := numerics.Area() - - if expectedCount != actualArea { - t.Error("Expected area of", expectedCount, - "but received", actualArea) - } - - members := make([]base.PixelMember, actualArea) - - i := 0 - for point := range out { - members[i] = point - i++ - } - actualCount := len(members) + actualCount := len(out) if expectedCount != actualCount { t.Error("Expected", expectedCount, "members but there were", actualCount)
9386b77427804d675a125c69c7f33f7224bf9642
--- +++ @@ -1,6 +1,8 @@ package main import ( + "bytes" + "encoding/json" "flag" "path" @@ -35,5 +37,15 @@ if err != nil { glog.Fatal(err) } - glog.Infof("Build: %s\n%v", build.Url, build) + + // Pretty print the build. + b, err := json.Marshal(build) + if err != nil { + glog.Fatal(err) + } + var out bytes.Buffer + if err := json.Indent(&out, b, "", "\t"); err != nil { + glog.Fatal(err) + } + glog.Infof("Build: %s\n%s", build.Url, out.String()) }
833a93918a9e19ccdd50e4a12bc7ebfc80d8c27b
--- +++ @@ -4,6 +4,7 @@ "bytes" "log" "os/exec" + "strings" "github.com/shizeeg/xmpp" ) @@ -16,8 +17,8 @@ return } lang := "-lang=en" - if len(message.Lang) > 0 { - lang = "-lang=" + message.Lang + if len(message.Lang) >= 2 { + lang = "-lang=" + message.Lang[:2] } plugin := exec.Command(filename, lang) plugin.Args = append(plugin.Args, params...) @@ -28,5 +29,5 @@ log.Println(err) return } - s.Say(stanza, out.String(), tonick, false) + s.Say(stanza, strings.TrimSpace(out.String()), tonick, false) }
75e1284b2c13a1ab3423964c804df1688c9a6dbe
--- +++ @@ -1,6 +1,7 @@ package messages import ( + "encoding/json" "code.google.com/p/go-uuid/uuid" "github.com/qp/go/utils" ) @@ -27,3 +28,9 @@ func (m *Message) HasError() bool { return m.Err != nil } + +// String provides a pretty JSON string representation of the message +func (m *Message) String() string { + bytes, _ := json.MarshalIndent(m, "", " ") + return string(bytes) +}
af819e8db4e198b56639025a9efee24fbff50faa
--- +++ @@ -1,14 +1,23 @@ package assets import ( + "io" + "os/exec" + "gnd.la/log" - "io" +) + +var ( + cleanCSSPath, _ = exec.LookPath("cleancss") ) type cssBundler struct { } func (c *cssBundler) Bundle(w io.Writer, r io.Reader, opts Options) error { + if cleanCSSPath != "" { + return command(cleanCSSPath, []string{"--s0"}, w, r, opts) + } p, n, err := reducer("css", w, r) if err != nil { return err
7da39310819a84ec9b983beffcaa4bda8cd739aa
--- +++ @@ -13,4 +13,18 @@ // limitations under the License. // Package mview adds materialized views via events on the MySQL binary log. +// +// +// https://de.slideshare.net/MySQLGeek/flexviews-materialized-views-for-my-sql +// https://github.com/greenlion/swanhart-tools +// +// https://hashrocket.com/blog/posts/materialized-view-strategies-using-postgresql +// Queries returning aggregate, summary, and computed data are frequently used +// in application development. Sometimes these queries are not fast enough. +// Caching query results using Memcached or Redis is a common approach for +// resolving these performance issues. However, these bring their own +// challenges. Before reaching for an external tool it is worth examining what +// techniques PostgreSQL offers for caching query results. +// +// http://www.eschrade.com/page/indexing-in-magento-or-the-wonderful-world-of-materialized-views/ package mview
37bb7e70b0002d30171272ff4c454829c762a79e
--- +++ @@ -16,7 +16,7 @@ // Read reads data into p. It returns the number of bytes read into p. It reads // till it encounters a `!` byte. -func (p1 *P1) Read(p []byte) (n int, err error) { +func (p1 P1) Read(p []byte) (n int, err error) { b, err := p1.rd.ReadBytes('!') p = append(p, b...)
50284cdfda2142263ff7ba33c6c3bff46f26bea4
--- +++ @@ -1,6 +1,5 @@ // +build windows -// Package config wraps xdgdir.Config to allow for OS-independent configuration. package config import ( @@ -10,9 +9,9 @@ ) func Open(filename string) (*os.File, error) { - dir := os.Getenv("USERPROFILE") + dir := os.Getenv("LOCALAPPDATA") if dir == "" { - return nil, fmt.Errorf("Could not find %%USERPROFILE%% envar") + return nil, fmt.Errorf("Could not find %%LOCALAPPDATA%% envar") } f, err := os.Open(filepath.Join(dir, filename))
032b2913a2229596905e937c5bfaf4ae541c9a07
--- +++ @@ -1,4 +1,4 @@ -package main +package goperrin import "fmt" @@ -36,14 +36,3 @@ return a } } - -func main() { - - p := perrin_max(100) - for i := 3; i < 10000; i = p() { - fmt.Println(i) - if i == 119 { - break - } - } -}
c986e37d3f5d5d8c918e2a1a52bba58162ba3b4d
--- +++ @@ -30,6 +30,6 @@ // Enable revoking of tokens // see: https://github.com/ory/hydra/blob/master/pkg/fosite_storer.go - //RevokeRefreshToken(ctx context.Context, requestID string) error - //RevokeAccessToken(ctx context.Context, requestID string) error + RevokeRefreshToken(ctx context.Context, requestID string) error + RevokeAccessToken(ctx context.Context, requestID string) error }
b8b3602976fd85e310d7cb718c6654617a1b4c94
--- +++ @@ -2,6 +2,7 @@ import ( "encoding/json" + "fmt" "os" "strings" "syscall" @@ -10,7 +11,7 @@ ) type imageMetadata struct { - User string `json:"user"` + User string `json:"user,omitempty"` Env []string `json:"env"` } @@ -19,8 +20,13 @@ } func main() { - err := json.NewEncoder(os.Stdout).Encode(imageMetadata{ - User: username(), + username, err := username() + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to determine username, will not be included in metadata") + } + + err = json.NewEncoder(os.Stdout).Encode(imageMetadata{ + User: username, Env: env(), }) if err != nil { @@ -28,18 +34,18 @@ } } -func username() string { +func username() (string, error) { users, err := passwd.ReadUsers("/etc/passwd") if err != nil { - panic(err) + return "", err } name, found := users.NameForID(syscall.Getuid()) if !found { - panic("could not find user in /etc/passwd") + return "", fmt.Errorf("could not find user in /etc/passwd") } - return name + return name, nil } func env() []string {
5e3d457f28f7d1ecbc60cdb60ff0d1b0b3f89493
--- +++ @@ -15,6 +15,10 @@ // Implementing json.Marshaler interface func (d Dot) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil +} + +func (d Dot) Hash() string { + return string([]byte{d.X, d.Y}) } func (d Dot) String() string {
d0046e18c7a22762460465eeb57f163dfc1d6297
--- +++ @@ -12,6 +12,9 @@ Channels = flag.String("chan", "#tad", "Channels to join") Ssl = flag.Bool("ssl", false, "Use SSL/TLS") Listen = flag.Bool("listenChannel", false, "Listen for command on public channels") + HostInfo = flag.String("hostInfo", "./data/va_host_info_report.json", "Path to host info report") + Promises = flag.String("promises", "./data/promises.csv", "Path to promises report") + Classes = flag.String("classes", "./data/classes.txt", "Path to classes report") ) const (
318da23a464cc6509b98f8bf7b92bfa57d9681f9
--- +++ @@ -1,22 +1,15 @@ package fetcher -import ( - "fmt" - "testing" +// func TestGetMessage(t *testing.T) { +// lg.InitLogger(true) - "github.com/drkaka/lg" -) +// jCmd := fmt.Sprintf("journalctl -u hooks -o json -n 20") +// results, err := GetMessages("hooks", "ssh", "leeq@192.168.1.201", jCmd) +// if err != nil { +// t.Fatal(err) +// } -func TestGetMessage(t *testing.T) { - lg.InitLogger(true) - - jCmd := fmt.Sprintf("journalctl -u hooks -o json -n 20") - results, err := GetMessages("hooks", "ssh", "leeq@192.168.1.201", jCmd) - if err != nil { - t.Fatal(err) - } - - for _, one := range results { - fmt.Println("Message: ", string(one.Message)) - } -} +// for _, one := range results { +// fmt.Println("Message: ", string(one.Message)) +// } +// }
997aa4adb9f4ab91833efad688e0a62077eb66f6
--- +++ @@ -13,7 +13,7 @@ if query == nil { w.WriteHeader(400) } else { - query.Execute() + go query.Execute() w.WriteHeader(200) } }
87ee43de38b82be1a5e5e21b8930cfb70620275e
--- +++ @@ -17,12 +17,15 @@ func (fs filesystemState) setupJunctions(t *testing.T) { for _, link := range fs.links { - p := link.path.prepend(fs.root) + from := link.path.prepend(fs.root) + to := fsPath{link.to}.prepend(fs.root) // There is no way to make junctions in the standard library, so we'll just // do what the stdlib's os tests do: run mklink. - output, err := exec.Command("cmd", "/c", "mklink", "/J", p.String(), link.to).CombinedOutput() + // + // Also, all junctions must point to absolute paths. + output, err := exec.Command("cmd", "/c", "mklink", "/J", from.String(), to.String()).CombinedOutput() if err != nil { - t.Fatalf("failed to run mklink %v %v: %v %q", p.String(), link.to, err, output) + t.Fatalf("failed to run mklink %v %v: %v %q", from.String(), to.String(), err, output) } } }
78ebc2e8d3e078b6c29cd65f300c2b447bc4679b
--- +++ @@ -2,15 +2,31 @@ import ( "log" + "os" + "os/signal" + "syscall" + "time" ) func main() { - res, err := ping("google.com", 5) - if err != nil { - log.Fatal(err) - } - log.Printf("Min: %f ms\n", res.Min) - log.Printf("Avg: %f ms\n", res.Avg) - log.Printf("Max: %f ms\n", res.Max) - log.Printf("Mdev: %f ms\n", res.Mdev) + ticker := time.NewTicker(10 * time.Second) + go func() { + for _ = range ticker.C { + log.Println("ping google.com -c 5") + res, err := ping("google.com", 5) + if err != nil { + log.Fatal(err) + } + log.Printf("Min: %f ms\n", res.Min) + log.Printf("Avg: %f ms\n", res.Avg) + log.Printf("Max: %f ms\n", res.Max) + log.Printf("Mdev: %f ms\n", res.Mdev) + } + }() + + ch := make(chan os.Signal) + signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) + log.Printf("Received signal: %v\n", <-ch) + log.Println("Shutting down") + ticker.Stop() }
09bb70a91fca004f8266151bdfcb2f8a7abed691
--- +++ @@ -19,7 +19,10 @@ if err != nil { return err } - proc, err := os.StartProcess(path, []string{path, "/C", "start", strings.Replace(url, "&", "^&", -1)}, &attr) + // so on windows when you're using cmd you have to escape ampersands with the ^ character. + // ¯\(º_o)/¯ + url = strings.Replace(url, "&", "^&", -1) + proc, err := os.StartProcess(path, []string{path, "/C", "start", url }, &attr) if err != nil { return err
fdc24bdec520bdf017881e1144d9a933c2792981
--- +++ @@ -21,19 +21,19 @@ Expect(createUser().ApiUrl).To(Equal("http://FAKE_API.example.com")) }) - It("sets UserContext.name", func() { + It("sets UserContext.Username", func() { Expect(createUser().Username).To(Equal("FAKE_USERNAME")) }) - It("sets UserContext.password", func() { + It("sets UserContext.Password", func() { Expect(createUser().Password).To(Equal("FAKE_PASSWORD")) }) - It("sets UserContext.org", func() { + It("sets UserContext.Org", func() { Expect(createUser().Org).To(Equal("FAKE_ORG")) }) - It("sets UserContext.space", func() { + It("sets UserContext.Space", func() { Expect(createUser().Space).To(Equal("FAKE_SPACE")) }) })
979e7db1754e9080cc14c0f3c5e805ba7d53835a
--- +++ @@ -5,13 +5,11 @@ Logger "./logger" "os" "os/signal" - redis "gopkg.in/redis.v5" "github.com/Jeffail/gabs" ) var ( config *gabs.Container - rcli *redis.Client ) func main() { @@ -20,20 +18,16 @@ // Read config config = GetConfig("config.json") +/* // Connect to DB - rcli = redis.NewClient(&redis.Options{ - Addr: config.Path("redis").Data().(string), - DB: 0, - }) - - _, err := rcli.Ping().Result() - if err != nil { - Logger.ERR("Cannot connect to redis!") - os.Exit(1) - } + ConnectDB( + config.Path("mongo.url").Data().(string), + config.Path("mongo.db").Data().(string), + ) +*/ // Connect and add event handlers - discord, err := discordgo.New(config.Path("discord.token").Data().(string)) + discord, err := discordgo.New("Bot " + config.Path("discord.token").Data().(string)) if err != nil { panic(err) }
d7c29acdf0691d2cd6d8b9ce13c485f524c6747c
--- +++ @@ -4,6 +4,7 @@ "flag" "github.com/phss/fcal/calendar" "log" + "strings" "time" ) @@ -14,11 +15,17 @@ } func parseOptions() time.Time { + format := "2006-01-02" + var dateStr string - flag.StringVar(&dateStr, "d", time.Now().Format("2006-01-02"), "ISO date of the day or month to be displayed") + flag.StringVar(&dateStr, "d", time.Now().Format(format), "ISO date of the day or month to be displayed") flag.Parse() - date, err := time.Parse("2006-01-02", dateStr) + if strings.Count(dateStr, "-") == 1 { + format = "2006-01" + } + + date, err := time.Parse(format, dateStr) if err != nil { log.Fatal(err)
e9c1f8c005129e9a882689da4c16c23406e5b2e5
--- +++ @@ -5,8 +5,8 @@ // a simple djb2 implementation func Djb2(s string) int { hash := 5381 - for c := range s { - hash += (hash * 33) + c + for _, c := range s { + hash += (hash * 33) + int(c) } return hash
9d5a3cdf1fa4223c0f8da2b74ab0dd3b35df7fda
--- +++ @@ -25,7 +25,7 @@ // even though 2^32-1 doesn't divide evenly here, the probabilities // are small enough that all 10,000 numbers are equally likely. a.password = fmt.Sprintf("%04d", binary.LittleEndian.Uint32(b)%10000) - logger.Infof("Generated new passcode:", a.password) + logger.Infof("Generated new passcode: %s", a.password) } func (a *OneTimeAuthHandler) GetUsername() string {
7505cfa0538d05a52c70ebb7a8f844d9887ac9dc
--- +++ @@ -6,12 +6,10 @@ package main -export Vector; - type Element interface { } -type Vector struct { +export type Vector struct { } func (v *Vector) Insert(i int, e Element) {
270b034de1e7039194fead11f7d0b7b92500e7bc
--- +++ @@ -5,7 +5,7 @@ "github.com/Masterminds/glide/msg" ) -// ImportGodep imports a GPM file. +// ImportGodep imports a Godep file. func ImportGodep(dest string) { base := "." config := EnsureConfig()
1f8de67efed99d3e94f689b83a897f9af6d70529
--- +++ @@ -32,5 +32,8 @@ if c.Tenant != "" { m["tenant"] = c.Tenant } + if c.TeamID != "" { + m["team_id"] = c.TeamID + } return m }
c392f6dac2ce7f6a429fdc41365a45e708c06d2d
--- +++ @@ -1,9 +1,36 @@ package celery import ( + "bytes" "fmt" "time" ) + +const CELERY_FORMAT = "2006-01-02T15:04:05.999999999" + +type celeryTime struct { + time.Time +} + +var null = []byte("null") + +func (ct *celeryTime) UnmarshalJSON(data []byte) (err error) { + if bytes.Equal(data, null) { + return + } + t, err := time.Parse(`"`+CELERY_FORMAT+`"`, string(data)) + if err == nil { + *ct = celeryTime{t} + } + return +} + +func (ct *celeryTime) MarshalJSON() (data []byte, err error) { + if ct.IsZero() { + return null, nil + } + return []byte(ct.Format(`"`+CELERY_FORMAT+`"`)), nil +} type Receipt interface { Reply(string, interface{}) @@ -13,14 +40,14 @@ } type Task struct { - Task string - Id string - Args []interface{} - Kwargs map[string]interface{} - Retries int - Eta string - Expires string - Receipt Receipt + Task string `json:"task"` + Id string `json:"id"` + Args []interface{} `json:"args"` + Kwargs map[string]interface{} `json:"kwargs"` + Retries int `json:"retries"` + Eta celeryTime `json:"eta"` + Expires celeryTime `json:"expires"` + Receipt Receipt `json:"-"` } func (t *Task) Ack(result interface{}) {
38fdbf5b5a1ab56cb8bcd76f129e0dae2900b3de
--- +++ @@ -7,7 +7,7 @@ validity := vat.Validate("NL123456789B01") Get VAT rate that is currently in effect for a given country - c, _ := GetCountryRates("NL") + c, _ := vat.GetCountryRates("NL") r, _ := c.Rate("standard") */ package vat
2909ffee3945d714a9a028f45066ae2f9a0b4761
--- +++ @@ -1,7 +1,7 @@ package xbmc import ( - "github.com/streamboat/xbmc_jsonrpc" + "github.com/StreamBoat/xbmc_jsonrpc" . "github.com/pdf/xbmc-callback-daemon/log" )
92e39cdb0505fd8edffd2491a0c913f16a64fb63
--- +++ @@ -39,3 +39,9 @@ } } + +func BenchmarkSumOfPrimesBelow2M(b *testing.B) { + for i := 0; i < b.N; i++ { + sumOfPrimesBelow(2000000) + } +}
65a77154929c1ab41755121e92264cdddefd7788
--- +++ @@ -8,12 +8,13 @@ // UserInfo holds the parameters returned by the backends. // This information will be serialized to build the JWT token contents. type UserInfo struct { - Sub string `json:"sub"` - Picture string `json:"picture,omitempty"` - Name string `json:"name,omitempty"` - Email string `json:"email,omitempty"` - Origin string `json:"origin,omitempty"` - Expiry int64 `json:"exp,omitempty"` + Sub string `json:"sub"` + Picture string `json:"picture,omitempty"` + Name string `json:"name,omitempty"` + Email string `json:"email,omitempty"` + Origin string `json:"origin,omitempty"` + Expiry int64 `json:"exp,omitempty"` + Refreshes int `json:"refs,omitempty"` } // Valid lets us use the user info as Claim for jwt-go.
ce762577cbd55b7431607a3031cd4a9a1460248f
--- +++ @@ -18,10 +18,11 @@ # Comment line 1 # Comment line 2 +,,,,,, # Commas are insignificant type Hello { -world: String! + world: String! }`, - expected: "Comment line 1\nComment line 2", + expected: "Comment line 1\nComment line 2\nCommas are insignificant", }} func TestConsume(t *testing.T) { @@ -35,7 +36,7 @@ } if test.expected != lex.DescComment() { - t.Errorf("wanted: %q\ngot: %q", test.expected, lex.DescComment()) + t.Errorf("wrong description value:\nwant: %q\ngot : %q", test.expected, lex.DescComment()) } }) }
be3ca4d050d41ba9e24d9814ca4b77c2a006235a
--- +++ @@ -10,7 +10,7 @@ func TestRootNames(t *testing.T) { // NOTE: will fail if there are newlines in /*. - want, err := exec.Command("ls", "/").Output() + want, err := exec.Command("ls", "-A", "/").Output() mustOK(err) wantNames := strings.Split(strings.Trim(string(want), "\n"), "\n") for i := range wantNames {
1bce3acd3c0fcfdf7334c9e4e47ca23d772d4280
--- +++ @@ -30,8 +30,39 @@ } } +func GetHelpers(modules ...string) template.FuncMap { + tf := template.FuncMap{} + getFuncs(tf, coreFuncs) + for _, module := range modules { + switch module { + case "all": + getFuncs(tf, formTagFuncs) + getFuncs(tf, selectTagFuncs) + getFuncs(tf, generalFuncs) + getFuncs(tf, linkFuncs) + getFuncs(tf, assetFuncs) + case "forms": + getFuncs(tf, formTagFuncs) + getFuncs(tf, selectTagFuncs) + case "general": + getFuncs(tf, generalFuncs) + case "link": + getFuncs(tf, linkFuncs) + case "asset": + getFuncs(tf, assetFuncs) + } + } + return tf +} + func loadFuncs(tf template.FuncMap) { for k, f := range tf { multitemplate.LoadedFuncs[k] = f } } + +func getFuncs(host, source template.FuncMap) { + for k, f := range source { + host[k] = f + } +}
6e8965f3d3bc78e86d747ec57b40702c684111f8
--- +++ @@ -7,16 +7,16 @@ "github.com/yuuki/dynamond/log" ) -func JSON(w http.ResponseWriter, status int, v interface{}) error { +func JSON(w http.ResponseWriter, status int, v interface{}) { res, err := json.Marshal(v) if err != nil { - return err + ServerError(w, err.Error()) + return } w.WriteHeader(status) w.Header().Set("Content-Type", "application/json") w.Write(res) - return nil } func BadRequest(w http.ResponseWriter, msg string) {
ab6c05839f3fb72bec5b0ec3cc2fdac275bc41ed
--- +++ @@ -7,7 +7,7 @@ . "github.com/onsi/gomega" ) -const previousKismaticVersion = "v1.2.0" +const previousKismaticVersion = "v1.3.0" // Test a specific released version of Kismatic var _ = Describe("Installing with previous version of Kismatic", func() {
1d315088c82360946b127712b38ce28da7b2ee16
--- +++ @@ -25,8 +25,8 @@ // loggly client work. // TODO: Add a "level" key for info, error..., proper timestamp etc // Buffers the message for async send - lmsg := loggly.Message{"type": msg} - if err := w.c.Send(lmsg); err != nil { + // TODO - Stat for the bytes written return? + if _, err := w.c.Write([]byte(msg)); err != nil { // TODO: What is best todo here as if we log it will loop? fmt.Println("loggly send error: %s", err.Error()) }
681abb201b6cccdd740804f5a7926fd630c711bb
--- +++ @@ -1,11 +1,6 @@ package regressiontests -import ( - "reflect" - "testing" -) - -type Empty struct{} +import "testing" func TestStructcheck(t *testing.T) { t.Parallel() @@ -15,9 +10,8 @@ unused int } ` - pkgName := reflect.TypeOf(Empty{}).PkgPath() expected := Issues{ - {Linter: "structcheck", Severity: "warning", Path: "test.go", Line: 4, Col: 2, Message: "unused struct field " + pkgName + "/.test.unused"}, + {Linter: "structcheck", Severity: "warning", Path: "test.go", Line: 4, Col: 2, Message: "unused struct field github.com/alecthomas/gometalinter/regressiontests/.test.unused"}, } ExpectIssues(t, "structcheck", source, expected) }
2f411b9a125577812a1696af899c7ba7fedbf372
--- +++ @@ -1,11 +1,13 @@ package core_test import ( + "github.com/pivotal-cf-experimental/destiny/core" + "github.com/pivotal-cf-experimental/gomegamatchers" + + "gopkg.in/yaml.v2" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/pivotal-cf-experimental/destiny/core" - . "github.com/pivotal-cf-experimental/gomegamatchers" - "gopkg.in/yaml.v2" ) var _ = Describe("Manifest", func() { @@ -21,7 +23,7 @@ }) Expect(err).NotTo(HaveOccurred()) - Expect(actualYAML).To(MatchYAML(expectedYAML)) + Expect(actualYAML).To(gomegamatchers.MatchYAML(expectedYAML)) }) })
8be6da3b9e29bc5701fad75f3253a30805f28cf4
--- +++ @@ -8,11 +8,12 @@ ) // unsafe cast string as []byte -func unsafestr(b string) []byte { - l := len(b) - return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ - Len: l, - Cap: l, - Data: (*reflect.StringHeader)(unsafe.Pointer(&b)).Data, - })) +func unsafestr(s string) []byte { + var b []byte + sHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) + bHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) + bHdr.Data = sHdr.Data + bHdr.Len = sHdr.Len + bHdr.Cap = sHdr.Len + return b }
18e7e70ecc692ddb6ea481b1aac0835bb288d596
--- +++ @@ -18,11 +18,18 @@ func Futex(uaddr *int32, op int32, val int32, timeout *Timespec, uaddr2 *int32, val3 int32) (ret int32) { - // For now, akaros futexes don't support timeout, uaddr2 or val3, so we + // For now, akaros futexes don't support uaddr2 or val3, so we // just 0 them out. - timeout = nil - uaddr2 = nil - val3 = 0 + uaddr2 = nil; + val3 = 0; + // Also, the minimum timout is 1ms, so up it to that if it's too small + if (timeout != nil) { + if (timeout.tv_sec == 0) { + if (timeout.tv_nsec < 1000000) { + timeout.tv_nsec = 1000000; + } + } + } return int32(C.futex((*C.int)(unsafe.Pointer(uaddr)), C.int(op), C.int(val), (*C.struct_timespec)(unsafe.Pointer(timeout)),
00297b35c0c433e7caf3502c5402343e2812482b
--- +++ @@ -1,12 +1,26 @@ package main import ( + "flag" + "fmt" "log" "net/http" + "strconv" ) func main() { router := NewRouter() - log.Fatal(http.ListenAndServe(":80", router)) + port := flag.Int("port", 8080, "Port to run on") + flag.Parse() + + if *port < 1 || *port > 65536 { + log.Fatal(string(*port) + " is not a valid port number. Exiting.") + } + + portString := ":" + strconv.Itoa(*port) + + fmt.Printf("Starting server on port %s", portString) + + log.Fatal(http.ListenAndServe(portString, router)) }
11126a81a179dd0d40b081da8cd02d696cdc6c92
--- +++ @@ -4,15 +4,22 @@ func Max(_less interface{}, vals ...interface{}) interface{} { ret := reflect.ValueOf(vals[0]) + retType := ret.Type() less := reflect.ValueOf(_less) for _, _v := range vals[1:] { - v := reflect.ValueOf(_v) + v := reflect.ValueOf(_v).Convert(retType) out := less.Call([]reflect.Value{ret, v}) if out[0].Bool() { ret = v } } return ret.Interface() +} + +func MaxInt(first int64, rest ...interface{}) int64 { + return Max(func(l, r interface{}) bool { + return l.(int64) < r.(int64) + }, append([]interface{}{first}, rest...)...).(int64) } func MinInt(first interface{}, rest ...interface{}) int64 {
9a812ba6d411ef10b32c14d83b852be9c1688f34
--- +++ @@ -12,7 +12,7 @@ // NewStack returns a new stack func NewStack() *Stack { return &Stack{ - stack: make([]*Matrix, 0, 100), + stack: make([]*Matrix, 0, 10), } }
a46d7149f8c866d75f0161df3788c1e9331e2dcf
--- +++ @@ -1,3 +1,8 @@ +//Command to run test version: +//goapp serve app.yaml +//Command to deploy/update application: +//goapp deploy -application golangnode0 -version 0 + package main import ( @@ -35,5 +40,3 @@ http.ListenAndServe(":80", nil) } */ -//goapp serve app.yaml -//goapp deploy -application golangnode0 -version 0
c7071dcb6fe8e95bf56f235a6945f19f53f763d8
--- +++ @@ -30,6 +30,8 @@ } switch os.Args[1] { + case "build": + baja.Compile(cwd) case "clean": clean() case "serve", "server":
22c48f61fb3b859f51afb0351094ea8537f186f9
--- +++ @@ -1,6 +1,7 @@ package main import ( + "fmt" "gopkg.in/urfave/cli.v1" "os" ) @@ -23,5 +24,8 @@ recordCommand, reportCommand, } - app.Run(os.Args) + if err := app.Run(os.Args); err != nil { + fmt.Fprintf(os.Stderr, "error: %v\n", err) + os.Exit(1) + } }
f10c846ab60d234aa449c042068ce461b2f6ed9a
--- +++ @@ -5,6 +5,7 @@ import ( "fmt" + "strings" "github.com/google/mtail/internal/vm/position" "github.com/pkg/errors" @@ -40,11 +41,11 @@ case 1: return p[0].Error() } - var r string + var r strings.Builder for _, e := range p { - r = r + fmt.Sprintf("%s\n", e) + r.WriteString(fmt.Sprintf("%s\n", e)) } - return r[:len(r)-1] + return r.String() } func Errorf(format string, args ...interface{}) error {
103d3d0a018556293bd7542436b9c7fa9d161e7f
--- +++ @@ -10,7 +10,7 @@ viper.SetDefault("letsencrypt_email", "") viper.SetDefault("db_path", "db/") viper.SetDefault("backup_path", "db/backups/") - viper.SetDefault("esi_baseurl", "https://esi.tech.ccp.is/latest") + viper.SetDefault("esi_baseurl", "http://esi.evetech.net/latest") viper.SetDefault("newrelic_app-name", "Evepraisal") viper.SetDefault("newrelic_license-key", "") viper.SetDefault("management_addr", "127.0.0.1:8090")
efbe9b05d89b33e8296e163fa84ffcf43152f3bf
--- +++ @@ -11,7 +11,7 @@ t.Fatal("findPackage didn't find the existing package") } if !hasGoPathPrefix(path) { - t.Fatal("%q is not in GOPATH, but must be", path) + t.Fatalf("%q is not in GOPATH, but must be", path) } }
35246bbbee0d65e0b83977d785b0f6be886e572e
--- +++ @@ -5,7 +5,29 @@ package main import ( + "flag" "fmt" + "time" +) + +var ( + err error + secret string // The hex or base32 secret + // otp string // If a value is supplied for varification + + //// Flags + // common flags add in flagParse method + // base32 = flag.Bool("b", false, "Use base32 encoding instead of hex") + // digits = flag.Int("d", 6, "The number of digits in the OTP") + // window = flag.Int("w", 1, "Window of counter values to test when validating OTPs") + + hFlag = flag.NewFlagSet("hotp", flag.ContinueOnError) + counter = hFlag.Int64("c", 0, "HOTP counter Value") + + tFlag = flag.NewFlagSet("totp", flag.ContinueOnError) + now = tFlag.Int64("N", time.Now().UTC().Unix(), "Use this time as current time for TOTP") + step = tFlag.Int64("s", 30, "The time-step duration") + epoch = tFlag.String("S", "1970−01−01 00:00:00 UTC", "When to start counting time-steps for TOTP") ) func main() {
383dced28708b4a1c0e93b8e85bf4832bf75ec96
--- +++ @@ -2,12 +2,24 @@ import ( "bufio" + "fmt" "os" "github.com/calebthompson/ftree/tree" ) +const ( + version = "v0.1.0" + help = `Pipe output from some command that lists a single file per line to ftree. + find . | ftree + git ls-files {app,spec}/models | ftree + lsrc | cut -d : -f 1 | ftree +` +) + func main() { + handleArguments() + r := bufio.NewScanner(os.Stdin) lines := []string{} for r.Scan() { @@ -17,3 +29,19 @@ t := tree.Tree(lines, "/") t.Print(0, nil) } + +func handleArguments() { + for _, a := range os.Args[1:] { + switch a { + case "--version", "-v": + fmt.Printf("ftree %s\n", version) + os.Exit(0) + case "--help", "-h": + fmt.Print(help) + os.Exit(0) + default: + fmt.Fprintf(os.Stderr, "No such argument: %v\n", a) + os.Exit(1) + } + } +}
a4cffbaf359a022748413daa22da03f5b4119265
--- +++ @@ -17,6 +17,10 @@ "hmsa", "hms", }, + "Lawndale High School": []string{ + "lawndale", + "lawndale high", + }, "North High School": []string{ "north high", "north", @@ -32,6 +36,9 @@ "samohi", "smhs", }, + "South High School": []string{ + "south high school", + }, "South Pasadena High School": []string{ "sphs", "south pasadena high school",
66306253961fbff152d00755910bb1327368055b
--- +++ @@ -1,4 +1,6 @@ package dna + +import "fmt" // Histogram is a mapping from nucleotide to its count in given DNA. type Histogram map[rune]int @@ -8,6 +10,9 @@ // Counts generates a histogram of valid nucleotides in the given DNA. // Returns an error if d contains an invalid nucleotide. func (d DNA) Counts() (Histogram, error) { + if !d.isValid() { + return Histogram{}, fmt.Errorf("DNA stand %s contains invalid nucleotides", d) + } h := Histogram{ 'A': 0, 'C': 0, @@ -19,3 +24,14 @@ } return h, nil } + +func (d DNA) isValid() bool { + for _, r := range d { + if r == 'A' || r == 'C' || r == 'G' || r == 'T' { + continue + } else { + return false + } + } + return true +}
949b59607ba26cdf2ab1d740265005d1d02b42ad
--- +++ @@ -14,7 +14,7 @@ func CommandHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.application+json; charset=UTF-8") w.WriteHeader(http.StatusOK) - c := models.Command{"say"} + c := models.Command{Name: "say"} commands.CommandList = append(commands.CommandList, c) commands.Collection = "name"
46383ae27d51da084fe7aa34637fc094d09d4149
--- +++ @@ -10,8 +10,8 @@ ) var ( - sizeInt int64 = 15351 - sizeBytes = []byte{0, 0, 0x77, 0x77} + sizeInt int = 15351 + sizeBytes = []byte{0, 0, 0x77, 0x77} ) func TestParseSize(t *testing.T) { @@ -19,7 +19,7 @@ if err != nil { t.Error(err) } - if size != sizeInt { + if size != int64(sizeInt) { t.Errorf("Expected: %v, got: %v", sizeInt, size) } }
a5c5f5dad4cfca91c53d043bfc26b0b248a7b28f
--- +++ @@ -18,9 +18,18 @@ sites := strings.Split(string(data), "\n") + validSites := make([]string, 0) + + for _, site := range sites { + t := strings.TrimSpace(site) + if t != "" { + validSites = append(validSites, t) + } + } + done := make(chan bool) - for _, site := range sites { + for _, site := range validSites { go func(site string) { crawler := crawler.NewCrawler(site) crawler.Crawl()
fd6982c0c6c53d66e35658aa4beb8cb2c1de74a2
--- +++ @@ -17,8 +17,8 @@ minutesInHour = 60 ) -func ParseDuration(duration int) (seconds, minutes, hours int) { - seconds = duration / millisecondsInSecond +func ParseDuration(milliseconds int) (seconds, minutes, hours int) { + seconds = milliseconds / millisecondsInSecond if seconds >= secondsInMinute { minutes = seconds / secondsInMinute seconds -= minutes * secondsInMinute
084999949e1504601ea290927f65ee4bddc94a28
--- +++ @@ -25,8 +25,8 @@ // VolumeResizeOptions is used to change the size of a volume type VolumeResizeOptions struct { - From int - To int + From int `json:"from"` + To int `json:"to"` } // ResizeVolume changes the size of a volume
41f272498df15bce6bf8c0e5857d5b4ecc8673db
--- +++ @@ -1,6 +1,7 @@ package util import ( + "fmt" "net/http" "sync" ) @@ -17,12 +18,14 @@ } func (sg *StatusGroup) Done(status int, err error) { + if status == 0 { + // An early exit. + status = http.StatusInternalServerError + err = fmt.Errorf("Unkown errors occur in an goroutine.") + } + sg.Lock() if sg.Err == nil && err != nil { - if status == 0 { - // Usually caused by an early exit. - status = http.StatusInternalServerError - } sg.Status = status sg.Err = err }
4be8c98cf87aaadd3c8f8ce81dc69e43e5a29446
--- +++ @@ -3,7 +3,7 @@ import ( "bytes" - "github.com/deckarep/gosx-notifier" + "github.com/haklop/gnotifier" ) import "text/template" @@ -21,8 +21,6 @@ // Run notifications a line to the terminal func (d NotificationDriver) Run(args RunArgs) error { - // FIXME: handle non OS X hosts - var buff bytes.Buffer tmpl, err := template.New("notification").Parse(d.line + "\n") if err != nil { @@ -33,8 +31,9 @@ return err } - note := gosxnotifier.NewNotification(buff.String()) - note.Title = "SSH" - note.Sound = gosxnotifier.Basso - return note.Push() + notification := gnotifier.Notification("ASSH", buff.String()) + notification.GetConfig().Expiration = 3000 + notification.GetConfig().ApplicationName = "assh" + + return notification.Push() }
661bcd3e4d95e6d55f42b3bedbc18c6f8b8e5793
--- +++ @@ -2,12 +2,36 @@ package containerd +import ( + "runtime" +) + const ( defaultRoot = "/var/lib/containerd-test" defaultAddress = "/run/containerd-test/containerd.sock" - testImage = "docker.io/library/alpine:latest" +) + +var ( + testImage string ) func platformTestSetup(client *Client) error { return nil } + +func init() { + switch runtime.GOARCH { + case "386": + testImage = "docker.io/i386/alpine:latest" + case "arm": + testImage = "docker.io/arm32v6/alpine:latest" + case "arm64": + testImage = "docker.io/arm64v8/alpine:latest" + case "ppc64le": + testImage = "docker.io/ppc64le/alpine:latest" + case "s390x": + testImage = "docker.io/s390x/alpine:latest" + default: + testImage = "docker.io/library/alpine:latest" + } +}
4781b2c2ffbb021f7a1b7311c23dfe4d76320f00
--- +++ @@ -1,11 +1,14 @@ package read + +import ( + "github.com/mtso/syllables" +) // Fk scores the Flesch-Kincaid Grade Level. // See https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests. func Fk(text string) float64 { - sylCnt := float64(CntSyls(text)) + syllableCount := float64(syllables.In(text)) wordCnt := float64(CntWords(text)) sentCnt := float64(CntSents(text)) - return 0.39*(wordCnt/sentCnt) + 11.8*(sylCnt/wordCnt) - 15.59 - + return 0.39*(wordCnt/sentCnt) + 11.8*(syllableCount/wordCnt) - 15.59 }
42d12c834deedf68eb52614eec751311376279e2
--- +++ @@ -7,12 +7,31 @@ ) func TestFindOrCreateTagByNameShouldCreateTag(t *testing.T) { - tag, _, err := FindOrCreateTagByName(db, "my-tag") + tag, created, err := FindOrCreateTagByName(db, "my-tag") assert.Nil(t, err) assert.NotNil(t, tag) + assert.True(t, created) assert.Equal(t, "my-tag", tag.Name) var check Tag db.Where("name = ?", "my-tag").First(&check) assert.Equal(t, "my-tag", check.Name) } + +func TestFindOrCreateTagShouldNotCreateDuplicateNames(t *testing.T) { + tag, created, err := FindOrCreateTagByName(db, "foo") + assert.Nil(t, err) + assert.NotNil(t, tag) + assert.True(t, created) + assert.Equal(t, "foo", tag.Name) + + tag, created, err = FindOrCreateTagByName(db, "foo") + assert.Nil(t, err) + assert.NotNil(t, tag) + assert.False(t, created) + assert.Equal(t, "foo", tag.Name) + + var tags []Tag + db.Where("name = ?", "foo").Find(&tags) + assert.Equal(t, 1, len(tags)) +}
663e01e49cf03fff20eb9a8cf6781c002299027c
--- +++ @@ -31,7 +31,10 @@ err = cmd.Wait() // go generate command will fail when no generate command find. - // if err != nil { - // log.Fatal(os.Stderr, "Error waiting for Cmd", err) - // } + if err != nil { + if err.Error() != "exit status 1" { + log.Println(err) + } + // log.Fatal(os.Stderr, "Error waiting for Cmd", err) + } }
4d75c3fa4eea1087574072efa9edadb3c3daa390
--- +++ @@ -21,9 +21,7 @@ ) func UrlForFunction(m *Metadata) string { - // TODO this assumes the router's namespace is the same as whatever is hitting - // this url -- so e.g. kubewatcher will have to run in the same ns as router. - prefix := "http://router/fission-function" + prefix := "/fission-function" if len(m.Uid) > 0 { return fmt.Sprintf("%v/%v/%v", prefix, m.Name, m.Uid) } else {
30c0200fb35e73377c62888fafb6702bac1df343
--- +++ @@ -1,5 +1,8 @@ +// Package goNessus provides a Golang based interface to Nessus 6 package goNessus +// Nessus struct is used to contain information about a Nessus scanner. This +// will be used to connect to the scanner and make API requests. type Nessus struct { Ip string Port string
3a5cbb599dde6cba4bd05e4e217bab702d74b27d
--- +++ @@ -2,13 +2,14 @@ import "time" +// Sensor has common fields for any sensors type Sensor struct { Name string `json:"name"` Type string `json:"type"` GenTime time.Time `json:"gen_time"` } -// Struct for Gyro Sensor +// GyroSensor produces x-y-z axes angle velocity values type GyroSensor struct { Sensor AngleVelocityX float32 `json:"x_axis_angle_velocity"` @@ -16,7 +17,7 @@ AngleVelocityZ float32 `json:"z_axis_angle_velocity"` } -// Struct for Accelerometer Sensor +// AccelSensor produces x-y-z axes gravity acceleration values type AccelSensor struct { Sensor GravityAccX float32 `json:"x_axis_gravity_acceleration"` @@ -24,7 +25,7 @@ GravityAccZ float32 `json:"z_axis_grativy_acceleration"` } -// Struct for Temperature Sensor +// TempSensor produces temperature and humidity values type TempSensor struct { Sensor Temperature float32 `json:"temperature"`
e5dc220fb707651888fec980944f7b739b59fc02
--- +++ @@ -9,15 +9,17 @@ log "github.com/sirupsen/logrus" ) +var flagJsonOutput bool + func main() { flag.Usage = usage + flag.BoolVar(&flagJsonOutput, "json-output", false, "specifies if the logging format is json or not") + flag.Parse() - if flag.NArg() != 1 { - flag.Usage() - os.Exit(1) - } - configurationDirectory := os.Args[1] + initializeLogger() + + configurationDirectory := flag.Args()[0] if stat, err := os.Stat(configurationDirectory); err == nil && stat.IsDir() { runServer(configurationDirectory) } else { @@ -37,3 +39,9 @@ log.Printf("Usage: %s configuration-directory \n", os.Args[0]) flag.PrintDefaults() } + +func initializeLogger() { + if flagJsonOutput { + log.SetFormatter(&log.JSONFormatter{}) + } +}
adc9f58df221cdfb8aae7a3f5af3c3a878d76dba
--- +++ @@ -14,10 +14,8 @@ } func LE24(data []byte, index int) int { - threebytes := data[index : index+3] - onebyte := []byte{0x00} - threebytes = append(onebyte, threebytes...) - return int(binary.LittleEndian.Uint32(threebytes)) + fourbytes := []byte{data[index], data[index+1], data[index+2], 0x00} + return int(binary.LittleEndian.Uint32(fourbytes)) } func BE16(data []byte, index int) int {
5ebe5070d9fc59595d56319977a87d36389f89c3
--- +++ @@ -17,4 +17,9 @@ // Add User Identity Tables g.AddTableWithName(Identity{}, "dispatch_identity").SetKeys(true, "IdentityId") + + // Add MailServer Tables + g.AddTableWithName(Message{}, "dispatch_messages").SetKeys(true, "MessageId") + g.AddTableWithName(Alert{}, "dispatch_alerts").SetKeys(true, "AlertId") + g.AddTableWithName(Component{}, "dispatch_components").SetKeys(true, "ComponentId") }
9daa63cc652970e5d8255a895ffc010c946b1c8d
--- +++ @@ -14,6 +14,8 @@ package cmd import ( + "context" + "github.com/spf13/cobra" "github.com/swarmdotmarket/perigord/migration" @@ -23,7 +25,7 @@ var migrateCmd = &cobra.Command{ Use: "migrate", Run: func(cmd *cobra.Command, args []string) { - if err := migration.RunMigrations(); err != nil { + if err := migration.RunMigrations(context.Background()); err != nil { perigord.Fatal(err) } },
8fd5942722b0287026049d3e6547532ff553d262
--- +++ @@ -5,6 +5,7 @@ var ( _ Unmarshaler = &Bytes{} _ Marshaler = &Bytes{} + _ Marshaler = Bytes{} ) func (me *Bytes) UnmarshalBencode(b []byte) error { @@ -12,6 +13,6 @@ return nil } -func (me *Bytes) MarshalBencode() ([]byte, error) { - return *me, nil +func (me Bytes) MarshalBencode() ([]byte, error) { + return me, nil }
fb8e2d8392fde635513db46c9848c59a733cdb79
--- +++ @@ -1,7 +1,6 @@ package main import ( - "fmt" "log" "os" @@ -13,16 +12,17 @@ func main() { var exit chan struct{} + if len(os.Args) < 2 { + log.Fatalln("Usage:", os.Args[0], "<config-file.json>") + } config, err := config.ReadConfig(os.Args[1]) if err != nil { - fmt.Println("Error reading configuration from", os.Args[1], "error:", err.Error()) - os.Exit(1) + log.Fatalln("Error reading configuration from", os.Args[1], "error:", err.Error()) } logfile, err := os.OpenFile(config.Logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { - fmt.Println("Error opening", config.Logpath, "for writing, error:", err.Error()) - os.Exit(1) + log.Fatalln("Error opening", config.Logpath, "for writing, error:", err.Error()) } log.SetOutput(logfile)
eef92a73ccb3337c2b89b21e44846bd12414ebc6
--- +++ @@ -3,6 +3,7 @@ import ( "io/ioutil" "net/http" + "net/url" ) type LinodeClient struct { @@ -19,9 +20,8 @@ } } -func (c *LinodeClient) ListLinodes() ([]byte, error) { - response, err := http.Get(API_ENDPOINT + "/?api_key=" + c.APIKey + - "&api_action=linode.list") +func (c *LinodeClient) APICall(query string) ([]byte, error) { + response, err := http.Get(API_ENDPOINT + "/?" + query) if err != nil { return nil, err } @@ -32,3 +32,10 @@ } return body, nil } + +func (c *LinodeClient) ListLinodes() ([]byte, error) { + params := url.Values{} + params.Add("api_key", c.APIKey) + params.Add("api_action", "linode.list") + return c.APICall(query) +}
5b9e03b89e1c77c3130b9e6fce1f40bc889a51ba
--- +++ @@ -27,7 +27,7 @@ apiEndpoints.PUT("/finish", finishGame) } - r.Use(static.Serve("/", static.LocalFile("static", false))) + r.Use(static.Serve("/", static.LocalFile("frontend/dist", false))) if error := r.Run(listen); error != nil { log.Fatal(error)
48b2b60608a101d56c6835dfa5aa1d08deda0910
--- +++ @@ -8,7 +8,6 @@ func TestTemplateRender(t *testing.T) { uc := UserContact{} - Convey("Daily email", t, func() { Convey("Should load a correct config", func() { @@ -23,6 +22,7 @@ err := tp.validateTemplateParser() So(err, ShouldBeNil) + Convey("Should be able to inline css from style.css", func() { base := "<html><head></head><body><a href='test'>test</a></body></html>" html := tp.inlineCss(base) @@ -31,6 +31,16 @@ So(html, ShouldNotEqual, base) So(html, ShouldContainSubstring, "style=") }) + + + Convey("Should be able to inline css from style.css", func() { + var containers []*MailerContainer + html, err := tp.RenderDailyTemplate(containers) + + So(err, ShouldBeNil) + So(html, ShouldNotBeNil) + So(html, ShouldContainSubstring, "style=") + }) }) }) })
68e8a57429c4221defb6c24b04aafec4108a4d4a
--- +++ @@ -3,6 +3,10 @@ package logrusx import ( + "fmt" + "runtime" + "strings" + log "github.com/Sirupsen/logrus" ) @@ -17,6 +21,7 @@ FieldError struct { Error error Message string + Stack []string } ) @@ -25,8 +30,33 @@ func (f *MistifyFormatter) Format(entry *log.Entry) ([]byte, error) { for k, v := range entry.Data { if err, ok := v.(error); ok { - entry.Data[k] = FieldError{err, err.Error()} + // Get the call stack and remove this function call from it + stack := f.callStack()[1:] + + entry.Data[k] = FieldError{ + Error: err, + Message: err.Error(), + Stack: stack, + } } } return f.JSONFormatter.Format(entry) } + +func (f *MistifyFormatter) callStack() []string { + stack := make([]string, 0, 4) + for i := 1; ; i++ { + pc, file, line, ok := runtime.Caller(i) + if !ok { + break + } + // Look up the function name (package.FnName) + fnName := runtime.FuncForPC(pc).Name() + // Add the line to the stack, skipping anything from within the logrus + // package so it starts at the log caller + if !strings.HasPrefix(fnName, "github.com/Sirupsen/logrus.") { + stack = append(stack, fmt.Sprintf("%s:%d (%s)", file, line, fnName)) + } + } + return stack +}
5eae7957e545c730709673dc68647941f4870a14
--- +++ @@ -3,6 +3,9 @@ import ( "flag" "math/rand" + "os" + "os/signal" + "syscall" "time" "github.com/Shopify/toxiproxy" @@ -26,5 +29,14 @@ if len(config) > 0 { server.PopulateConfig(config) } + + // Handle SIGTERM to exit cleanly + signals := make(chan os.Signal) + signal.Notify(signals, syscall.SIGTERM) + go func() { + <-signals + os.Exit(0) + }() + server.Listen(host, port) }