_id
stringlengths
40
40
text
stringlengths
81
2.19k
title
stringclasses
1 value
241f8379347845280c5ae1d6d8947103ea9abe28
--- +++ @@ -32,3 +32,34 @@ return publicIps, nil } + +// GetAllIps returns a string slice of all IPs. +func GetAllIps() (ips []string, err error) { + ifis, err := net.Interfaces() + if err != nil { + return nil, err + } + + for _, ifi := range ifis { + addrs, err := ifi.Addrs() + if err != nil { + return nil, err + } + + for _, addr := range addrs { + ipNet, ok := addr.(*net.IPNet) + if !ok { + continue + } + + ip4 := ipNet.IP.To4() + if ip4 == nil { + continue + } + + ips = append(ips, ipNet.IP.String()) + } + } + + return ips, nil +}
7d83e25ab4ca4428438f39a50a6474bdf81a7901
--- +++ @@ -2,6 +2,7 @@ import ( "net" + "strings" "testing" ) @@ -10,6 +11,13 @@ _, err := CreateTunInterface(iface) if err != nil { t.Error(err) + } + niface, err := net.InterfaceByName(iface) + if err != nil { + t.Error(err) + } + if !strings.Contains(niface.Flags.String(), "up") { + t.Error("Interface not up") } }
4ce854b81fe1c3731952a4885845f647f425aed9
--- +++ @@ -1,8 +1,10 @@ package gmws import ( + "fmt" "os" + "github.com/kr/pretty" "github.com/svvu/gomws/mwsHttps" ) @@ -43,3 +45,8 @@ return credential } + +// Inspect print out the value in a user friendly way. +func Inspect(value interface{}) { + fmt.Printf("%# v", pretty.Formatter(value)) +}
330114d17efbaa3acf11c6bec6a114c14d660bb6
--- +++ @@ -1,6 +1,6 @@ package main -import "code.google.com/p/gcfg" +import "gopkg.in/gcfg.v1" // Config is config type Config struct { @@ -12,6 +12,6 @@ func getConfig() (Config, error) { var cfg Config - err := gcfg.ReadFileInto(&cfg, "./config.cfg") + err := gcfg.ReadFileInto(&cfg, "/tmp/config.cfg") return cfg, err }
e5bc938a4566443ec30dc3b0a9d738c5eabc2249
--- +++ @@ -1,12 +1,41 @@ package gamq import ( + "bufio" + "bytes" "testing" + + "github.com/onsi/gomega" ) const ( TEST_QUEUE_NAME = "TestQueue" ) + +// Check that messages sent to a queue are eventually sent to consumers +func TestQueue_sendMessage_messageReceivedSuccessfully(t *testing.T) { + // Need gomega for async testing + gomega.RegisterTestingT(t) + + underTest := Queue{Name: TEST_QUEUE_NAME} + testMessage := "Testing!" + + underTest.Initialize() + + writerBuffer := new(bytes.Buffer) + dummyWriter := bufio.NewWriter(writerBuffer) + dummyClient := Client{Name: "Test", Writer: dummyWriter} + + // Add the subscription + underTest.Subscribers <- &dummyClient + + // Queue the message + underTest.Messages <- &testMessage + + gomega.Eventually(func() string { + return writerBuffer.String() + }).Should(gomega.Equal(testMessage)) +} func TestQueue_initialize_completesSuccessfully(t *testing.T) { underTest := Queue{Name: TEST_QUEUE_NAME}
57686db26173e59898a68ac9c1631f51d0dd36be
--- +++ @@ -2,6 +2,7 @@ import ( "fmt" + "strings" "github.com/CiscoCloud/mesos-consul/registry" ) @@ -23,5 +24,22 @@ // Build a Check structure from the Task labels // func (t *Task) GetCheck() *registry.Check { - return registry.DefaultCheck() + c := registry.DefaultCheck() + + for _, l := range t.Labels { + k := strings.ToLower(l.Key) + + switch k { + case "consul_http_check": + c.HTTP = l.Value + case "consul_script_check": + c.Script = l.Value + case "consul_ttl_check": + c.TTL = l.Value + case "consul_check_interval": + c.Interval = l.Value + } + } + + return c }
05e56f036079dd18514b6d317c43c1d83eca5535
--- +++ @@ -4,7 +4,6 @@ import ( "github.com/nitrogen-lang/nitrogen/src/eval" - "github.com/nitrogen-lang/nitrogen/src/moduleutils" "github.com/nitrogen-lang/nitrogen/src/object" "github.com/nitrogen-lang/nitrogen/src/vm" ) @@ -13,8 +12,8 @@ eval.RegisterBuiltin("module", importModule) eval.RegisterBuiltin("modulesSupported", moduleSupport) - vm.RegisterBuiltin("module", moduleutils.VMBuiltinWrapper(importModule)) - vm.RegisterBuiltin("modulesSupported", moduleutils.VMBuiltinWrapper(moduleSupport)) + vm.RegisterBuiltin("module", importModule) + vm.RegisterBuiltin("modulesSupported", moduleSupport) } func importModule(i object.Interpreter, env *object.Environment, args ...object.Object) object.Object {
5a5d6af6ba1d256e8f0d3220dea078736abe4389
--- +++ @@ -16,10 +16,10 @@ panic("Must set $CONFIG to point to an integration config .json file.") } - return LoadPath(path) + return loadConfigJsonFromPath(path) } -func LoadPath(path string) (config IntegrationConfig) { +func loadConfigJsonFromPath(path string) (config IntegrationConfig) { configFile, err := os.Open(path) if err != nil { panic(err)
6436a2abc48e4112ac3c4c5645975e54cd14bd0d
--- +++ @@ -6,7 +6,7 @@ "log" "os" - "github.com/bfontaine/edn" + "gopkg.in/bfontaine/edn.v1" ) func main() {
ef5dbe3c47a240ea1c07331e206e3bab43a9074d
--- +++ @@ -38,7 +38,14 @@ } func (t *ticker) Reset(d time.Duration) { - t.ticker.Reset(d) + ticker, ok := (interface{})(t.ticker).(interface { + Reset(time.Duration) + }) + if !ok { + panic("Ticker.Reset not implemented in this Go version.") + } + + ticker.Reset(d) } func (t *ticker) C() <-chan time.Time {
7c9cc10e47ff4e7cba4c678f12aa079866ad61ab
--- +++ @@ -33,7 +33,7 @@ bp := bufferpool.New(10, 255) dogBuffer := bp.Take() - dogBuffer.writeString("Dog!") + dogBuffer.WriteString("Dog!") bp.Give(dogBuffer) catBuffer := bp.Take() // dogBuffer is reused and reset.
686cf12e54030e5f80e66f125d13e1346e6bf1ac
--- +++ @@ -14,9 +14,36 @@ } func TestParseTime(t *testing.T) { + r := require.New(t) - tt, err := parseTime([]string{"2017-01-01"}) - r.NoError(err) - expected := time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC) - r.Equal(expected, tt) + + testCases := []struct { + input string + expected time.Time + expectErr bool + }{ + { + input: "2017-01-01", + expected: time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC), + expectErr: false, + }, + { + input: "2018-07-13T15:34", + expected: time.Date(2018, time.July, 13, 15, 34, 0, 0, time.UTC), + expectErr: false, + }, + { + input: "2018-20-10T30:15", + expected: time.Time{}, + expectErr: true, + }, + } + + for _, tc := range testCases { + tt, err := parseTime([]string{tc.input}) + if !tc.expectErr { + r.NoError(err) + } + r.Equal(tc.expected, tt) + } }
6657839f8f426d83cb426aca87bc4c7439516242
--- +++ @@ -7,7 +7,7 @@ package yara import ( - "github.com/VirusTotal/go-yara/internal/callbackdata" + "github.com/hillu/go-yara/internal/callbackdata" ) var callbackData = callbackdata.MakePool(256)
c8cb29649076f1215cc0aea696219ff8c88839c6
--- +++ @@ -13,9 +13,10 @@ app.Flags = []cli.Flag{ cli.StringFlag{ - Name: "etcd-endpoints", - Value: "http://127.0.0.1:4001,http://127.0.0.1:2379", - Usage: "a comma-delimited list of etcd endpoints", + Name: "etcd-endpoints", + Value: "http://127.0.0.1:4001,http://127.0.0.1:2379", + Usage: "a comma-delimited list of etcd endpoints", + EnvVar: "ETCDCTL_ENDPOINT", }, cli.StringFlag{ Name: "etcd-prefix",
d3006931ec68b97e671866950af48a9c6de8970c
--- +++ @@ -35,8 +35,8 @@ line, col, err := Pos(r, nt.pos) test.Error(t, err, nt.err) - test.Int(t, line, nt.line, "line") - test.Int(t, col, nt.col, "col") + test.V(t, "line", line, nt.line) + test.V(t, "column", col, nt.col) }) } }
7f956da3f46268dc33006bb3222f8cf1213d2e84
--- +++ @@ -7,17 +7,15 @@ // parseConfigFlags overwrites configuration with set flags func parseConfigFlags(Conf *SplendidConfig) (*SplendidConfig, error) { - // TODO: This should only happen if the flag has been passed - flag.StringVar(&Conf.Workspace, "w", "./splendid-workspace", "Workspace") - flag.IntVar(&Conf.Concurrency, "c", 30, "Number of collector processes") - flag.StringVar(&Conf.SmtpString, "s", "localhost:25", "SMTP server:port") - flag.DurationVar(&Conf.Interval, "interval", 300*time.Second, "Run interval") - flag.DurationVar(&Conf.Timeout, "timeout", 60*time.Second, "Collection timeout") - flag.BoolVar(&Conf.Insecure, "insecure", false, "Allow untrusted SSH keys") - flag.BoolVar(&Conf.GitPush, "push", false, "Git push after commit") - flag.BoolVar(&Conf.HttpEnabled, "web", false, "Run an HTTP status server") - flag.StringVar(&Conf.HttpListen, "listen", "localhost:5000", "Host and port to use for HTTP status server (default: localhost:5000).") - flag.StringVar(&Conf.ConfigFile, "f", "sample.conf", "Config File") + // Set to passed flags, otherwise go with config + flag.IntVar(&Conf.Concurrency, "c", Conf.Concurrency, "Number of collector processes") + flag.StringVar(&Conf.SmtpString, "s", Conf.SmtpString, "SMTP server:port") + flag.DurationVar(&Conf.Interval, "interval", Conf.Interval*time.Second, "Run interval") + flag.DurationVar(&Conf.Timeout, "timeout", Conf.Timeout*time.Second, "Collection timeout") + flag.BoolVar(&Conf.Insecure, "insecure", Conf.Insecure, "Allow untrusted SSH keys") + flag.BoolVar(&Conf.HttpEnabled, "web", Conf.HttpEnabled, "Run an HTTP status server") + flag.StringVar(&Conf.HttpListen, "listen", Conf.HttpListen, "Host and port to use for HTTP status server (default: localhost:5000).") + flag.StringVar(&Conf.ConfigFile, "f", Conf.ConfigFile, "Config File") flag.Parse() return Conf, nil }
b6a4ce4e292367cb9a88e4ca9eab925ab1c49b71
--- +++ @@ -12,9 +12,12 @@ } func fromRequest(r *route, req *http.Request) (*Context, error) { - paths := strings.Split(strings.Trim(req.URL.Path, "/"), "/") + var paths []string + if path := strings.Trim(req.URL.Path, "/"); path != "" { + paths = strings.Split(path, "/") + } + route, params := r.getRoute(paths) - if route != nil { return &Context{params, route}, nil }
66be70de94c668405564be0221c594bbfaded72c
--- +++ @@ -20,7 +20,12 @@ pump.SetError(fmt.Errorf("bolus amount (%d) is too large", amount)) } newer := pump.Family() >= 23 - strokes := int(amount / milliUnitsPerStroke(newer)) + d := milliUnitsPerStroke(newer) + if amount%d != 0 { + pump.SetError(fmt.Errorf("bolus (%d) is not a multiple of %d milliUnits per hour", amount, d)) + return + } + strokes := int(amount / d) n := pump.Retries() defer pump.SetRetries(n) pump.SetRetries(1)
dc7578aff971e84bed156b00bfef33543bf26249
--- +++ @@ -1,6 +1,7 @@ package terraform import ( + "fmt" "log" ) @@ -35,7 +36,7 @@ // Refresh! state, err = provider.Refresh(n.Info, state) if err != nil { - return nil, err + return nil, fmt.Errorf("%s: %s", n.Info.Id, err.Error()) } // Call post-refresh hook
d1f45de88f0c5fe6b27fde59015b156294bda1be
--- +++ @@ -3,6 +3,7 @@ import ( "flag" "fmt" + "log" "os" "os/exec" ) @@ -25,15 +26,14 @@ file, err := os.Open(flag.Arg(0)) if err != nil { - fmt.Printf("Error! %s\n", err) - os.Exit(2) + log.Fatalf("%s\n", err) } defer file.Close() prog := "go" path, err := exec.LookPath(prog) if err != nil { - fmt.Printf("Please, install %s first.", prog) + log.Fatalf("please, install %s first.", prog) } fmt.Printf("%s is available at %s\n", prog, path) @@ -46,10 +46,8 @@ if len(args) == 0 { flag.Usage() - fmt.Printf("Error! The input file is required\n") - - os.Exit(1) + log.Fatalf("the input file not specified\n") } else if len(args) > 1 { - fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:]) + log.Printf("to many positional arguments, ignoring %v\n", args[1:]) } }
a455258a62c81da600b2d15b7cd61493398367ed
--- +++ @@ -32,7 +32,7 @@ if len(mtype) != 0 { res.Header().Set("Content-Type", mtype) } - res.Header().Set("Content-Size", fmt.Sprintf("%d", len(bs))) + res.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs))) res.Header().Set("Last-Modified", modt) res.Write(bs)
71fba5cf9d831f08fb10ba70cc5056e5b73be852
--- +++ @@ -5,27 +5,50 @@ "net/url" ) -type oAuthResponseFull struct { - AccessToken string `json:"access_token"` - Scope string `json:"scope"` +type OAuthResponseIncomingWebhook struct { + URL string `json:"url"` + Channel string `json:"channel"` + ConfigurationURL string `json:"configuration_url"` +} + +type OAuthResponseBot struct { + BotUserID string `json:"bot_user_id"` + BotAccessToken string `json:"bot_access_token"` +} + +type OAuthResponse struct { + AccessToken string `json:"access_token"` + Scope string `json:"scope"` + TeamName string `json:"team_name"` + TeamID string `json:"team_id"` + IncomingWebhook OAuthResponseIncomingWebhook `json:"incoming_webhook"` + Bot OAuthResponseBot `json:"bot"` SlackResponse } // GetOAuthToken retrieves an AccessToken func GetOAuthToken(clientID, clientSecret, code, redirectURI string, debug bool) (accessToken string, scope string, err error) { + response, err := GetOAuthResponse(clientID, clientSecret, code, redirectURI, debug) + if err != nil { + return "", "", err + } + return response.AccessToken, response.Scope, nil +} + +func GetOAuthResponse(clientID, clientSecret, code, redirectURI string, debug bool) (resp *OAuthResponse, err error) { values := url.Values{ "client_id": {clientID}, "client_secret": {clientSecret}, "code": {code}, "redirect_uri": {redirectURI}, } - response := &oAuthResponseFull{} + response := &OAuthResponse{} err = post("oauth.access", values, response, debug) if err != nil { - return "", "", err + return nil, err } if !response.Ok { - return "", "", errors.New(response.Error) + return nil, errors.New(response.Error) } - return response.AccessToken, response.Scope, nil + return response, nil }
5ddef488663eb7557a0a4e1a2c5374cbd7a2ef0c
--- +++ @@ -28,5 +28,9 @@ t := &OIDCToken{} resp, err := c.doRequest(httpReq, t) - return t, resp, err + if err != nil { + return nil, resp, err + } + + return t, resp, nil }
c1c1776768902f26160af59b689f14c17e80068a
--- +++ @@ -1,20 +1,49 @@ package utils import ( - "fmt" "os/exec" - "strings" ) -// GpgDetachedSign signs file with detached signature in ASCII format -func GpgDetachedSign(source string, destination string) error { - fmt.Printf("v = %#v\n", strings.Join([]string{"gpg", "-o", destination, "--armor", "--detach-sign", source}, " ")) - cmd := exec.Command("gpg", "-o", destination, "--armor", "--yes", "--detach-sign", source) +// Signer interface describes facility implementing signing of files +type Signer interface { + SetKey(keyRef string) + DetachedSign(source string, destination string) error + ClearSign(source string, destination string) error +} + +// Test interface +var ( + _ Signer = &GpgSigner{} +) + +// GpgSigner is implementation of Signer interface using gpg +type GpgSigner struct { + keyRef string +} + +// SetKey sets key ID to use when signing files +func (g *GpgSigner) SetKey(keyRef string) { + g.keyRef = keyRef +} + +// DetachedSign signs file with detached signature in ASCII format +func (g *GpgSigner) DetachedSign(source string, destination string) error { + args := []string{"-o", destination, "--armor", "--yes"} + if g.keyRef != "" { + args = append(args, "-u", g.keyRef) + } + args = append(args, "--detach-sign", source) + cmd := exec.Command("gpg", args...) return cmd.Run() } -// GpgClearSign clear-signs the file -func GpgClearSign(source string, destination string) error { - cmd := exec.Command("gpg", "-o", destination, "--yes", "--clearsign", source) +// ClearSign clear-signs the file +func (g *GpgSigner) ClearSign(source string, destination string) error { + args := []string{"-o", destination, "--yes"} + if g.keyRef != "" { + args = append(args, "-u", g.keyRef) + } + args = append(args, "--clearsign", source) + cmd := exec.Command("gpg", args...) return cmd.Run() }
effa489b8a1bf052bc897458d3e7e2528353076c
--- +++ @@ -9,10 +9,6 @@ ) func cmdToot(c *cli.Context) error { - if !c.Args().Present() { - return errors.New("arguments required") - } - var toot string ff := c.String("ff") if ff != "" { @@ -22,6 +18,9 @@ } toot = string(text) } else { + if !c.Args().Present() { + return errors.New("arguments required") + } toot = argstr(c) } client := c.App.Metadata["client"].(*mastodon.Client)
06b4a129a7b0c469553182195721a97cf170e181
--- +++ @@ -11,6 +11,11 @@ Auth struct { AccessKey string SecretKey string + } + + Locations struct { + Source []string + Destination []string } }
df2a903d9538ac5637f46fc3b88320fba4f18277
--- +++ @@ -9,3 +9,33 @@ Draw(emulator emu.Chip8) Close() } + +// Key is the type for identifying a key on the Chip8 keypad. +type Key uint8 + +// The possible values for keys +const ( + KEY_0 Key = iota + KEY_1 + KEY_2 + KEY_3 + KEY_4 + KEY_5 + KEY_6 + KEY_7 + KEY_8 + KEY_9 + KEY_A + KEY_B + KEY_C + KEY_D + KEY_E + KEY_F + KEY_QUIT + KEY_NONE +) + +// Input is an interface for a provider of keypresses. +type Input interface { + Poll() Key +}
fbc019dd4b60a6b81eccc35a9e2f0f357d293d53
--- +++ @@ -18,11 +18,15 @@ if err != nil { t.Error(err) } - fmt.Println("Fill\n", bd) + if testing.Verbose() { + fmt.Println("Fill\n", bd) + } err = bd.Fill(br) if err != nil { t.Error(err) } - fmt.Println("Update\n", bd) - fmt.Println(bd) + if testing.Verbose() { + fmt.Println("Update\n", bd) + fmt.Println(bd) + } }
ff1a208dc8b4cf6dce7d584cc61d1395606d85a5
--- +++ @@ -16,7 +16,7 @@ var DockerRegex = regexp.MustCompile("^\\/v2\\/(.*\\/(tags|manifests|blobs)\\/.*|_catalog$)") func generateDockerv2URI(path string, rec record) (string, int) { - if path != "" { + if path != "/" { regexType := DockerRegex.FindAllStringSubmatch(path, -1)[0] pathRegex, err := regexp.Compile(dockerRegexs[regexType[len(regexType)-1]]) if err != nil {
6b308c5ecde906553352f11821b16d1160a28e90
--- +++ @@ -23,8 +23,7 @@ import "github.com/loadimpact/k6/stats" func sumMetricValues(samples chan stats.SampleContainer, metricName string) (sum float64) { - bufferedSmaples := stats.GetBufferedSamples(samples) - for _, sc := range bufferedSmaples { + for _, sc := range stats.GetBufferedSamples(samples) { samples := sc.GetSamples() for _, s := range samples { if s.Metric.Name == metricName {
dd5457f5ab1f60db3c5e53a1e0a23c3c3817c2b6
--- +++ @@ -26,7 +26,7 @@ c.Check(country, Equals, "US") c.Check(netmask, Equals, 15) - country, netmask = gi.GetCountry("64.235.248.1") + country, netmask = gi.GetCountry("149.20.64.42") c.Check(country, Equals, "US") - c.Check(netmask, Equals, 20) + c.Check(netmask, Equals, 13) }
a1737718dc644e736fd6023d6ba465edea3654ee
--- +++ @@ -38,11 +38,11 @@ return } -func formatNumber(num int) (formated string) { +func formatNumber(num int) (formatted string) { if num < 10 { - formated += "0" + formatted += "0" } - formated += strconv.Itoa(num) + formatted += strconv.Itoa(num) return }
d85d2805568f8ea3af628aa82192c497e4229981
--- +++ @@ -1,10 +1,6 @@ package resources -import ( - "fmt" - - "github.com/aws/aws-sdk-go/service/ec2" -) +import "github.com/aws/aws-sdk-go/service/ec2" type EC2Subnet struct { svc *ec2.EC2 @@ -45,5 +41,5 @@ } func (e *EC2Subnet) String() string { - return fmt.Sprintf("%s in %s", *e.id, *e.region) + return *e.id }
ac7c2234a21aec4cccc98ecebb8cfe22a1c47bb2
--- +++ @@ -18,7 +18,7 @@ SetupConfig = Config{ Assets: Assets{"a/", "a/", "i/", "f/"}, Debug: Debug{"FILTER", "INFO"}, - Screen: Screen{0, 0, 240, 320, 2}, + Screen: Screen{0, 0, 240, 320, 2, 0, 0}, Font: Font{"hint", 20.0, 36.0, "luxisr.ttf", "green"}, FrameRate: 30, DrawFrameRate: 30,
fb4f186e8dbbc88874b3e12bf75e9e6382daa70d
--- +++ @@ -28,10 +28,12 @@ } if !onlyCrashes { for _, item := range c.Errors { - packet := raven.NewPacket(item.Error(), &raven.Message{ - Message: item.Error(), - Params: []interface{}{item.Meta}, - }) + packet := raven.NewPacket(item.Error(), + &raven.Message{ + Message: item.Error(), + Params: []interface{}{item.Meta}, + }, + raven.NewHttp(c.Request)) client.Capture(packet, flags) } }
e626d100ea82a5034a2f0da20781deb543ff9319
--- +++ @@ -31,9 +31,9 @@ func CheckSignature(address string, signature string, message string) (bool, error) { if utilIsTestnet { - return bitsig_go.CheckSignature(address, signature, message, "FLO", &FloTestnetParams) + return bitsig_go.CheckSignature(address, signature, message, "Florincoin", &FloTestnetParams) } - return bitsig_go.CheckSignature(address, signature, message, "FLO", &FloParams) + return bitsig_go.CheckSignature(address, signature, message, "Florincoin", &FloParams) } // reference: Cory LaNou, Mar 2 '14 at 15:21, http://stackoverflow.com/a/22129435/2576956
94ac13fd9f4cdc91c70211f97ff4c2c6a78bda66
--- +++ @@ -7,7 +7,6 @@ import ( "os" "testing" - "time" ) func TestGetMeetupEvents(t *testing.T) { @@ -15,13 +14,7 @@ t.Skip("no meetup API key set, skipping test") } - var l bool - d := time.Now().Weekday().String() - if d == "Thursday" { - l = true - } - - _, err := GetTalkDetails(l) + _, err := GetNextMeetup("chadevs") if err != nil { t.Error(err) }
205cdabcfb9632ea2f8482e13fba3e1e2c8fd60f
--- +++ @@ -10,13 +10,13 @@ out, err := bleed.Heartbleed(os.Args[1], []byte("heartbleed.filippo.io")) if err == bleed.ErrPayloadNotFound { log.Printf("%v - SAFE", os.Args[1]) - os.Exit(1) + os.Exit(0) } else if err != nil { log.Printf("%v - ERROR: %v", os.Args[1], err) os.Exit(2) } else { log.Printf("%v\n", string(out)) log.Printf("%v - VULNERABLE", os.Args[1]) - os.Exit(0) + os.Exit(1) } }
03eaf0db4f57a6f17f875a34ac5de26dc5dea0a0
--- +++ @@ -3,9 +3,9 @@ import ( "github.com/Sirupsen/logrus" "github.com/verath/archipelago/lib" - "golang.org/x/net/context" "os" "os/signal" + "context" ) func main() {
3a4500fa63451b8c7d647d2de6ebeb77b63eda00
--- +++ @@ -6,13 +6,18 @@ "github.com/open-falcon/falcon-plus/cmd" "github.com/spf13/cobra" - flag "github.com/spf13/pflag" ) var versionFlag bool var RootCmd = &cobra.Command{ Use: "open-falcon", + Run: func(cmd *cobra.Command, args []string) { + if versionFlag { + fmt.Printf("Open-Falcon version %s, build %s\n", Version, GitCommit) + os.Exit(0) + } + }, } func init() { @@ -22,17 +27,13 @@ RootCmd.AddCommand(cmd.Check) RootCmd.AddCommand(cmd.Monitor) RootCmd.AddCommand(cmd.Reload) + + RootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "show version") cmd.Start.Flags().BoolVar(&cmd.PreqOrderFlag, "preq-order", false, "start modules in the order of prerequisites") cmd.Start.Flags().BoolVar(&cmd.ConsoleOutputFlag, "console-output", false, "print the module's output to the console") - flag.BoolVarP(&versionFlag, "version", "v", false, "show version") - flag.Parse() } func main() { - if versionFlag { - fmt.Printf("Open-Falcon version %s, build %s\n", Version, GitCommit) - os.Exit(0) - } if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1)
32f7ef7c1ee4cd252a382be5f1d7d990f7940192
--- +++ @@ -4,7 +4,6 @@ "fmt" "html/template" "net/http" - "net/url" ) func RootHandler(w http.ResponseWriter, r *http.Request, processes []*Process) { @@ -31,25 +30,6 @@ http.Error(w, "Error parsing lag", http.StatusInternalServerError) return } - lag, err := getFormValues(&r.Form) - if err != nil { - http.Error(w, "Unable to get form values", http.StatusInternalServerError) - } - // t.Execute(w, userInput) - fmt.Fprintf(w, "Adding %s lag", lag) + fmt.Fprintf(w, "Adding lag") } } - -func getFormValues(form *url.Values) (lag string, err error) { - for key, value := range *form { - switch key { - case "lag": - return value[0], nil - case "processId": - return value[0], nil - default: - return "", fmt.Errorf("Unable to parse form") - } - } - return "", fmt.Errorf("No form values") -}
0e20ab7b104b869fef4160c6c876a8ed47318851
--- +++ @@ -3,6 +3,7 @@ import ( "fmt" "os" + "launchpad.net/goamz/aws" "launchpad.net/goamz/s3" ) @@ -32,7 +33,7 @@ } func (s3Uploader *S3) Upload(destPath, contentType string, f *os.File) error { - writer, err := s3Uploader.Bucket.InitMulti(destPath, contentType, s3.AuthenticatedRead) + writer, err := s3Uploader.Bucket.InitMulti(destPath, contentType, s3.PublicRead) if err != nil { return err }
e0c2c779adf652c65f796e16f33bc41c4c204c18
--- +++ @@ -6,6 +6,7 @@ "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "os" ) var _ = Describe("CF Binary Buildpack", func() { @@ -21,6 +22,7 @@ Describe("deploying a Ruby script", func() { BeforeEach(func() { app = cutlass.New(filepath.Join(bpDir, "fixtures", "webrick_app")) + app.Stack = os.Getenv("CF_STACK") }) Context("when specifying a buildpack", func() {
52188a1213c3ed67e0700fedd3c6630e5dc09902
--- +++ @@ -2,7 +2,7 @@ import ( "bytes" - "github.com/bmizerany/assert" + "github.com/stretchr/testify/assert" "testing" )
78ab1a9809872e77fb00c5863f4e3479d06b54f3
--- +++ @@ -17,10 +17,12 @@ "X-Amz-User-Agent", "X-CSRF-Token", "x-amz-acl", + "x-amz-content-sha256", "x-amz-meta-filename", "x-amz-meta-from", "x-amz-meta-private", "x-amz-meta-to", + "x-amz-security-token", } corsHeadersString = strings.Join(corsHeaders, ", ") ) @@ -34,6 +36,7 @@ w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD") w.Header().Set("Access-Control-Allow-Headers", corsHeadersString) + w.Header().Set("Access-Control-Expose-Headers", "ETag") if r.Method == "OPTIONS" { return
8884885a3d96d79a9f0cfae1d807233f53f32f67
--- +++ @@ -4,12 +4,14 @@ "io/ioutil" "os" "syscall" + + "github.com/zenoss/glog" ) var BASH_SCRIPT = ` DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)" COMMAND="$@" -trap "rm -f ${DIR}/$$.stderr" EXIT +#trap "rm -f ${DIR}/$$.stderr" EXIT for i in {1..10}; do SEEN=0 ${COMMAND} 2> >(tee ${DIR}/$$.stderr >&2) @@ -26,7 +28,7 @@ return err } defer f.Close() - defer os.Remove(f.Name()) + //defer os.Remove(f.Name()) if _, err := f.WriteString(BASH_SCRIPT); err != nil { return err } @@ -35,6 +37,7 @@ } command := []string{f.Name()} command = append(command, cmd...) + glog.V(0).Infof("Here's the command: %s", command) err = syscall.Exec("/bin/bash", command, os.Environ()) return nil }
094bc9c35b9711ea101138af9cd7cc4aa464b1f9
--- +++ @@ -2,11 +2,11 @@ // Configure to start testing var ( - TestCollection = "" + TestCollection = "TestCollection" TestDoc DocTest - TestDbName = "" - TestUsername = "" - TestPassword = "" + TestDbName = "TestDbName" + TestUsername = "TestUsername" + TestPassword = "TestPassword" TestString = "test string" verbose = false TestServer = "http://localhost:8529"
17438fe622bf9f62b0c3ec5bdb2f5291472b0f3f
--- +++ @@ -17,7 +17,7 @@ go func() { l := len(ps.spinRunes) - for _ = range time.Tick(150 * time.Millisecond) { + for _ = range time.Tick(110 * time.Millisecond) { ps.current = (ps.current + 1) % l ps.SetText(string(ps.spinRunes[ps.current])) }
03f02c00edf62b8e44ad3d99a9216fdbbdf90fc5
--- +++ @@ -39,6 +39,10 @@ for _, method := range methods { m.Globals[method.Name] = method } + // Set some module globals + m.Globals["__name__"] = String(name) + m.Globals["__doc__"] = String(doc) + m.Globals["__package__"] = None // Register the module modules[name] = m // Make a note of the builtin module
c42b1214288dd32d6bcfb89ef5a9926f6228889b
--- +++ @@ -3,6 +3,25 @@ // Elvish code for default bindings, assuming the editor ns as the global ns. const defaultBindingsElv = ` insert:binding = (binding-map [ + &Left= $move-left~ + &Right= $move-right~ + + &Ctrl-Left= $move-left-word~ + &Ctrl-Right= $move-right-word~ + &Alt-Left= $move-left-word~ + &Alt-Right= $move-right-word~ + &Alt-b= $move-left-word~ + &Alt-f= $move-right-word~ + + &Home= $move-sol~ + &End= $move-eol~ + + &Backspace= $kill-left~ + &Delete= $kill-right~ + &Ctrl-W= $kill-left-word~ + &Ctrl-U= $kill-sol~ + &Ctrl-K= $kill-eol~ + &Ctrl-D= $commit-eof~ &Default= $insert:default-handler~ ])
1992690eede6e11f7d9a5da9951409b3e8715d27
--- +++ @@ -9,8 +9,6 @@ var runDir = "." var raceBinPath = "." - -const GodogSuiteName = "uat" func TestMain(m *testing.M) { // Run the features tests from the compiled-in location.
eadbe6d5a4a92da8eef924ac9cbe953131ccef73
--- +++ @@ -28,7 +28,7 @@ } func init() { - if usr, err := user.Current(); err != nil { + if usr, err := user.Current(); err == nil { path := filepath.Join(usr.HomeDir, ".config", "gobuster.conf") defaultConfigPaths = append([]string{path}, defaultConfigPaths...) }
471baf3bf6276f77dc4b425961dfd63b8d294e5a
--- +++ @@ -6,6 +6,7 @@ "net/http" "net/http/fcgi" "os" + "time" ) type FastCGIServer struct{} @@ -15,14 +16,20 @@ } func main() { + fmt.Fprintln(os.Stderr, "Server started at ", time.Now().String()) + listener, err := net.Listen("tcp", "127.0.0.1:9000") if err != nil { - fmt.Fprint(os.Stderr, "Failed to open socket 9000: ", err) + fmt.Fprintln(os.Stderr, "Failed to open socket 9000: ", err) + os.Exit(1) } srv := new(FastCGIServer) err = fcgi.Serve(listener, srv) if err != nil { - fmt.Fprint(os.Stderr, "Server crashed: ", err) + fmt.Fprintln(os.Stderr, "Server crashed: ", err) + os.Exit(1) } + + fmt.Fprintln(os.Stderr, "Server stopped at ", time.Now().String()) }
20e01dae8dbd8b4be4af7b22b243e79d81e7c853
--- +++ @@ -1,12 +1,34 @@ package main import ( - "github.com/kataras/iris" - "github.com/tappsi/airbrake-webhook/webhook" + "os" + "fmt" + "runtime" + "syscall" + "os/signal" + "github.com/kataras/iris" + "github.com/tappsi/airbrake-webhook/webhook" ) func main() { + api := iris.New() api.Post("/airbrake-webhook", webhook.Process) + + go cleanup() api.Listen(":8080") + } + +func cleanup() { + + sigChan := make(chan os.Signal) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGTSTP) + <-sigChan + + fmt.Println("\nReceived an interrupt, stopping services...\n") + + runtime.GC() + os.Exit(0) + +}
abbe90686d8f9b9a35097c07235e52259ea0f453
--- +++ @@ -3,6 +3,7 @@ import ( "bytes" "fmt" + "regexp" log "github.com/Sirupsen/logrus" "github.com/gwatts/kvlog" @@ -27,7 +28,10 @@ // replace the timestamp so the output is consistent output := "2017-01-02T12:00:00.000Z " + buf.String()[25:] + + // replace srcline so tests aren't sensitive to exact line number + output = regexp.MustCompile(`srcline=\d+`).ReplaceAllLiteralString(output, `srcline=100`) + fmt.Println(output) - - // Output: 2017-01-02T12:00:00.000Z ll="info" srcfnc="Example" srcline=29 action="user_login" status="ok" active_sessions=4 email="joe@example.com" username="joe_user" _msg="User logged in" + // Output: 2017-01-02T12:00:00.000Z ll="info" srcfnc="Example" srcline=100 action="user_login" status="ok" active_sessions=4 email="joe@example.com" username="joe_user" _msg="User logged in" }
9aa86a9ebfb12bcea50edbb99d8388ad244d3cff
--- +++ @@ -1,14 +1,13 @@ package main import ( - "log" "os" - "github.com/Sirupsen/logrus" + log "github.com/Sirupsen/logrus" ) func init() { - logrus.SetLevel(logrus.DebugLevel) + log.SetLevel(log.DebugLevel) } func main() {
a28d7be3abc4923bc48061df17c80117e878bc9f
--- +++ @@ -20,6 +20,9 @@ if IsTrue(db, NewTerm("father", NewTerm("sue"))) { t.Errorf("Proved father(sue)") } + if IsTrue(db, NewTerm("father", NewTerm("michael"), NewTerm("marc"))) { + t.Errorf("Proved father(michael, marc)") + } if IsTrue(db, NewTerm("mother", NewTerm("michael"))) { t.Errorf("Proved mother(michael)") }
4f27b0ec2e1d4a9dbf73dfba7fea4f45473652a2
--- +++ @@ -15,7 +15,7 @@ flag.StringVar( &natsURL, "i", - "nats://localhost:2222", + "nats://ingest.albion-data.com:4222", "NATS URL to subscribe to.", ) } @@ -39,7 +39,7 @@ defer nc.Close() marketCh := make(chan *nats.Msg, 64) - marketSub, err := nc.ChanSubscribe("marketorders", marketCh) + marketSub, err := nc.ChanSubscribe("marketorders.ingest", marketCh) if err != nil { fmt.Printf("%v\n", err) return
33fcb45f6150000444a7925fe382e77868d81ad6
--- +++ @@ -33,16 +33,22 @@ var err error homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration") Expect(err).NotTo(HaveOccurred()) - os.Setenv("HOME", homePath) + + err = os.Setenv("HOME", homePath) + Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { - os.Setenv("HOME", oldHome) - os.RemoveAll(homePath) + err := os.Setenv("HOME", oldHome) + Expect(err).NotTo(HaveOccurred()) + + err = os.RemoveAll(homePath) + Expect(err).NotTo(HaveOccurred()) }) AfterSuite(func() { - os.Remove(testCpiFilePath) + err := os.Remove(testCpiFilePath) + Expect(err).NotTo(HaveOccurred()) }) RunSpecs(t, "bosh-micro-cli Integration Suite")
af173743ca07a1d343abe50384378f9155b6a273
--- +++ @@ -14,10 +14,11 @@ return false } - // Named pipes on unix/linux indicate a readable stdin, but might not have size yet - if fi.Mode()&os.ModeNamedPipe != 0 { - return true + // Character devices in Linux/Unix are unbuffered devices that have + // direct access to underlying hardware and don't allow reading single characters at a time + if (fi.Mode() & os.ModeCharDevice) == os.ModeCharDevice { + return false } - return fi.Size() > 0 + return true }
8fa523b125135bbd6f7965798f7fd33f0cfbff26
--- +++ @@ -2,7 +2,8 @@ import ( "encoding/binary" - "hash/crc32" + + "github.com/klauspost/crc32" ) // crc32Field implements the pushEncoder and pushDecoder interfaces for calculating CRC32s.
3f6c538dd1af6ac31ed8f112edbb21e76b9c973b
--- +++ @@ -1,7 +1,5 @@ package netlink -//import "bytes" -//import "encoding/binary" import "os" import "syscall" @@ -15,7 +13,6 @@ } func Dial(nlf NetlinkFamily)(rwc *Socket, err os.Error){ - //func Dial(nlfam netlinkFamily)(rwc netlinkSocket, err os.Error){ fdno, errno := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, int(nlf)) err = toErr(errno) if err == nil { @@ -32,18 +29,12 @@ func (self *Socket)Write(in []byte)(n int, err os.Error){ - if n < 0 { - panic(n) - } n, errno := syscall.Write(self.fd, in) err = toErr(errno) return } func (self *Socket)Read(in []byte)(n int, err os.Error){ - if n < 0 { - panic(n) - } n, errno := syscall.Read(self.fd, in) err = toErr(errno) return
c2d8a81138be3bf77f0019bd91b68dabb8099f8c
--- +++ @@ -15,7 +15,7 @@ Long: `Check if the HTTP server has been started and answer 200 for /status.`, Run: func(cmd *cobra.Command, args []string) { port := os.Getenv("PORT") - if len(port) == 0 { + if port == "" { port = "8080" } resp, err := http.Get("http://localhost:" + port + "/status")
b1f08bcbc8e7880ea81a030e679a6bc779daba08
--- +++ @@ -27,7 +27,7 @@ func (k KeyObject) String() string { if !k.ExpiryTime.IsZero() { - return fmt.Sprintf("KeyObject{ExpiryTime: %s, Key: %s}", k.ExpiryTime, DataToString(k.Key)) + return fmt.Sprintf("KeyObject{ExpiryTime: %s, Key: %s}", k.ExpiryTime.UTC(), DataToString(k.Key)) } return fmt.Sprintf("%s", DataToString(k.Key))
f2e5b570d93253ff9e122c28fdd3e1f21a93a4aa
--- +++ @@ -22,6 +22,8 @@ if ts != nil { ts.Status = lib.PasswordFound ts.Password = password + } else { + fmt.Println("ERROR:", "Id not found in Taskstatus") } } @@ -30,6 +32,8 @@ ts := s.taskStatusWithId(Id) if ts != nil { ts.Status = lib.PasswordNotFound + } else { + fmt.Println("ERROR:", "Id not found in Taskstatus") } }
02e2eebf07da56ec80b2a13a4c4784a34368883c
--- +++ @@ -1,7 +1,12 @@ package server + +import ( + "github.com/centurylinkcloud/clc-go-cli/models" +) type ServerRes struct { Server string IsQueued bool ErrorMessage string + Links []models.LinkEntity }
f9ee6c4ccec0bfca077b484f4f4867c988384650
--- +++ @@ -1,14 +1,13 @@ package version type Version struct { - GitSHA string - Version string + GitCommit string + Version string } -var VersionInfo = Version{ - GitSHA: gitSha, - Version: version, +var VersionInfo = unknownVersion + +var unknownVersion = Version{ + GitCommit: "unknown git commit", + Version: "unknown version", } - -const gitSha = "unknown" -const version = "0.1"
91e5b46ad966ca77fc8077e62fe6460c9c908188
--- +++ @@ -23,12 +23,11 @@ err := decoder.Decode(&out) fmt.Println(err) if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok { - fmt.Println("Original error:", err.UnmarshalTypeError.Error()) + //fmt.Println("Original error:", err.UnmarshalTypeError.Error()) fmt.Println("Error location:", err.Pointer) } // Output: // /value: cannot unmarshal number into Go value of type bool - // Original error: json: cannot unmarshal number into Go struct field .value of type bool // Error location: /value }
9cd1c9b1f88e04c420219b16e239a8f1a5846df9
--- +++ @@ -1,9 +1,6 @@ package radius -import ( - "encoding/binary" - "io" -) +import "io" // AttributeType defines types for an Attribute type AttributeType int64 @@ -29,5 +26,6 @@ // Write writes the attribute type to the given writer func (a AttributeType) Write(w io.Writer) error { - return binary.Write(w, binary.BigEndian, int8(a)) + _, err := w.Write([]byte{byte(a)}) + return err }
747580ae4a2ff7e65398e815eef60b45fe87491a
--- +++ @@ -14,3 +14,13 @@ e := json.NewEncoder(w) return e.Encode(ds.data) } + +// Load reads the content of a serialized DataStore from the io.Reader r. +func Load(r io.Reader) (*DataStore, error) { + d := json.NewDecoder(r) + var data map[string]interface{} + if err := d.Decode(&data); err != nil { + return nil, err + } + return NewDataStoreFromJSONObject(data), nil +}
33e9be254750f2137894f98d51ceb5ee505b6e61
--- +++ @@ -1,4 +1,9 @@ package metadata + +type Specification struct { + Machine string `yaml: "machine"` + Cluster Cluster `yaml: "cluster"` +} type Machine struct { Name string `yaml: "name"`
f538fcc774dd1fe1b03b293c4b5c8b313d4de98c
--- +++ @@ -1,6 +1,7 @@ package trash import ( + "io/ioutil" "os" "path/filepath" ) @@ -9,11 +10,36 @@ func MoveToTrash(name string) error { name = filepath.Clean(name) home := os.Getenv("HOME") - _, file := filepath.Split(name) + dir, file := filepath.Split(name) target := filepath.Join(home, ".Trash", file) // TODO: If target name exists in Trash, come up with a unique one (perhaps append a timestamp) instead of overwriting. // TODO: Support OS X "Put Back". Figure out how it's done and do it. - return os.Rename(name, target) + err := os.Rename(name, target) + if err != nil { + return err + } + + // If directory became empty, remove it (recursively up). + for { + /*// Ensure it's a directory, not file. + if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { + break + }*/ + // Ensure it's an empty directory. + if dirEntries, err := ioutil.ReadDir(dir); err != nil || len(dirEntries) != 0 { + break + } + + // Remove directory if it's (now) empty. + err := os.Remove(dir) + if err != nil { + break + } + + dir, _ = filepath.Split(dir) + } + + return nil }
11320dc0577bdc8dcb8a90ae2c468ee34b50110c
--- +++ @@ -25,7 +25,7 @@ timeRemaining := session.Expiration.Sub(time.Now()) timeRemaining = time.Second * time.Duration(timeRemaining.Seconds()) if s.DisplayStatus { - ask.Print(fmt.Sprintf("%s — expires: %s (%s remaining)\n", session.Name, session.Expiration.Format("2 Jan 2006 15:04 MST"), timeRemaining)) + ask.Print(fmt.Sprintf("%s — expires: %s (%s remaining)\n", session.Name, session.Expiration.Format("2 Jan 2006 15:04 MST"), timeRemaining)) } code, err := session.Spawn(s.Command)
efe9f2bce5cba90966308450131b836bb0b96e41
--- +++ @@ -18,7 +18,7 @@ var ct string // Stop handling assets if frontend is disabled - if w.disableFrontend { + if !w.enableFrontend { rw.WriteHeader(http.StatusForbidden) return }
685257ee0c059ce3e395de606e29fe1f7188d391
--- +++ @@ -23,7 +23,7 @@ for j := 0; j < len(features); j++ { feature := features[j] - fmt.Printf("%v (%v): %.1f\n", feature.Name, feature.GetLabel(), feature.GetValue()) + fmt.Printf("%v ('%v'): %.1f\n", feature.Name, feature.GetLabel(), feature.GetValue()) subfeatures := feature.GetSubFeatures()
55f66b1c0ccd2d6f4e0feec45e7a6c661f78f142
--- +++ @@ -5,9 +5,9 @@ // Version: 1.0.4 const ( - Major = 1 - Minor = 0 - Patch = 4 + Major = 1 + Minor = 0 + Patch = 4 - Version = "1.0.4" + Version = "1.0.4" )
b4a85849423f59f443e6d2006960d4b759d7cab9
--- +++ @@ -4,29 +4,11 @@ "time" ) +const ( + COMMIT_MESSAGE_BASE = "commit_message_base.txt" +) + type Commit struct { dateTime time.Time message string } - -// RandomCommits returns a channel of random commits for a given day. -func RandomCommits(day time.Time, rnd int) chan Commit { - commitChannel := make(chan Commit) - go func() { - for i := 0; i < rnd; i++ { - commitChannel <- Commit{ - dateTime: getRandomTime(), message: getRandomCommitMessage(), - } - } - close(commitChannel) - }() - return commitChannel -} - -func getRandomTime() time.Time { - return time.Now() -} - -func getRandomCommitMessage() string { - return "not so random string" -}
634c7418e45fb68584ae64d5a1c2156fd74d1091
--- +++ @@ -12,13 +12,13 @@ lastcmdFilterTests = []listingFilterTestCases{ {"", []shown{ - {"M-,", ui.Unstyled(theLine)}, + {"M-1", ui.Unstyled(theLine)}, {"0", ui.Unstyled("qw")}, {"1", ui.Unstyled("search")}, {"2", ui.Unstyled("'foo bar ~y'")}}}, {"1", []shown{{"1", ui.Unstyled("search")}}}, {"-", []shown{ - {"M-,", ui.Unstyled(theLine)}, + {"M-1", ui.Unstyled(theLine)}, {"-3", ui.Unstyled("qw")}, {"-2", ui.Unstyled("search")}, {"-1", ui.Unstyled("'foo bar ~y'")}}},
c24a3e389fc63a2cf3d51e0afd743047514ff1d5
--- +++ @@ -8,11 +8,14 @@ // Main executes the main function of the caddy command. func Main() { - err := caddy2.StartAdmin("127.0.0.1:1234") + addr := ":1234" // TODO: for dev only + err := caddy2.StartAdmin(addr) if err != nil { log.Fatal(err) } defer caddy2.StopAdmin() + log.Println("Caddy 2 admin endpoint listening on", addr) + select {} }
801ec2795baad4d74871dbf3c11a0b92809f0500
--- +++ @@ -1,14 +1,16 @@ package example -// Doer does things, sometimes repeatedly +// Doer does things, sometimes graciously type Doer interface { DoIt(task string, graciously bool) (int, error) } +// Delegater employs a Doer to complete tasks type Delegater struct { Delegate Doer } +// DoSomething passes the work to Doer func (d *Delegater) DoSomething(task string) (int, error) { return d.Delegate.DoIt(task, false) }
06fed06a31753a4f1e54e23a61f2896aaed63acf
--- +++ @@ -2,8 +2,10 @@ import ( "bytes" + "fmt" "github.com/Cistern/sflow" "net" + "time" ) func sFlowParser(buffer []byte) { @@ -19,19 +21,40 @@ } } -func sFlowListener() (err error) { - // Start listening UDP socket, check if it started properly - UDPAddr, err := net.ResolveUDPAddr("udp", ":6343") +func sFlowListener(AppConfig app_config) (err error) { + defer wait.Done() + + var udp_addr = fmt.Sprintf("[%s]:%d", AppConfig.SFlowConfig.Address, AppConfig.SFlowConfig.Port) + + DebugLogger.Println("Binding sFlow listener to", udp_addr) + + UDPAddr, err := net.ResolveUDPAddr("udp", udp_addr) + if err != nil { + ErrorLogger.Println(err) + return err + } conn, err := net.ListenUDP("udp", UDPAddr) if err != nil { + ErrorLogger.Println(err) return err } var buffer []byte - for { - conn.ReadFromUDP(buffer) - sFlowParser(buffer) + for running { + /* + Normally read would block, but we want to be able to break this + loop gracefuly. So add read timeout and every 0.1s check if it is + time to finish + */ + conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) + var read, _, err = conn.ReadFromUDP(buffer) + if read > 0 && err != nil { + sFlowParser(buffer) + } + } + + conn.Close() return nil }
cbec6b0f74c6ce48926c4beee7e8424d79ddf028
--- +++ @@ -16,10 +16,10 @@ // dbusGetString calls a D-Bus method that will return a string value. func dbusGetString(path string) (string, error) { - return "", fmt.Errorf("omxplayer: not implemented yet") + return "", fmt.Errorf("omxplayer: %s not implemented yet", path) } // dbusGetStringArray calls a D-Bus method that will return a string array. func dbusGetStringArray(path string) ([]string, error) { - return nil, fmt.Errorf("omxplayer: not implemented yet") + return nil, fmt.Errorf("omxplayer: %s not implemented yet", path) }
4e746575bb94c6347febb0c176e6f0dfdbde2dd4
--- +++ @@ -3,7 +3,7 @@ import ( "io/ioutil" - "launchpad.net/goyaml" + "gopkg.in/yaml.v2" // "log" ) @@ -48,7 +48,7 @@ func LoadFeatureConf(conf []byte) *FeatureSetup { setup := new(FeatureSetup) - goyaml.Unmarshal(conf, setup) + yaml.Unmarshal(conf, setup) return setup }
7fe479c6ebf6fcbeead03911b06fc78eb02e37c2
--- +++ @@ -4,6 +4,7 @@ "github.com/stellar/horizon/db" "github.com/stellar/horizon/txsub" "net/http" + "time" ) func initSubmissionSystem(app *App) { @@ -17,6 +18,14 @@ }, NetworkPassphrase: app.networkPassphrase, } + + //TODO: bundle this with the ledger close pump system + go func() { + for { + <-time.After(1 * time.Second) + app.submitter.Tick(app.ctx) + } + }() } func init() {
18d00f79e0ec80e65714bb4e1fea20dd122e11b3
--- +++ @@ -19,16 +19,17 @@ func TestAsBool(t *testing.T) { for s, b := range map[string]bool{ - "yes": true, - "on": true, - "1": true, - "boo": true, - "0": false, - "99": true, - "a": true, - "off": false, - "no": false, - "": false, + "yes": true, + "on": true, + "1": true, + "boo": true, + "0": false, + "99": true, + "a": true, + "off": false, + "no": false, + "fafafaf": true, + "": false, } { assert.Equal(t, b, asBool(s)) }
616662aaac757337c2c3713ea2e9fabad2ac50ec
--- +++ @@ -12,7 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. +// Package merkle provides Merkle tree interfaces and implementation. package merkle + +// TODO(pavelkalinnikov): Remove this root package. The only interface provided +// here does not have to exist, and can be [re-]defined on the user side, such +// as in compact or proof package. // LogHasher provides the hash functions needed to compute dense merkle trees. type LogHasher interface {
2d5303d4031281c215b115d7609fa087912833a8
--- +++ @@ -1,10 +1,13 @@ package arrays // Strings allows us to limit our filter to just arrays of strings -type Strings struct{} +type strings struct{} + +// Strings allows easy access to the functions that operate on a list of strings +var Strings strings // Filter filters an array of strings. -func (s Strings) Filter(in []string, keep func(item string) bool) []string { +func (s strings) Filter(in []string, keep func(item string) bool) []string { var out []string for _, item := range in { if keep(item) { @@ -13,6 +16,19 @@ } return out +} + +// Remove filters an array by removing all matching items +func (s strings) Remove(in []string, remove ...string) []string { + return s.Filter(in, func(item string) bool { + found := false + for _, removeItem := range remove { + if removeItem == item { + found = true + } + } + return !found + }) }
da43f34f3d2a5b7417f72e36d0a137674a282764
--- +++ @@ -13,7 +13,7 @@ Blobstore BlobstoreOptions - //vcap password + //The SHA-512 encrypted vcap password VcapPassword string }
c179e9583f01fcd3d204ea588c0da3ce59eeff93
--- +++ @@ -1,6 +1,10 @@ package monitor -import "time" +import ( + "time" + + "github.com/pkg/errors" +) // StatusStore is an interface of storage of availability statuses. // Standart implementation of this interface (RedisStore) uses Redis as backend, @@ -9,3 +13,44 @@ GetStatus(t Target) (Status, bool, error) SetStatus(t Target, s Status, exp time.Duration) error } + +type simpleStoreRecord struct { + Target Target + Status Status + Expirated time.Time +} + +// SimpleStore is the basic implementation of StatusStore which uses a map as +// a storage backend. +type SimpleStore map[uint]simpleStoreRecord + +// GetStatus returns status of a target if it's set and not expired. +func (ss SimpleStore) GetStatus(t Target) (Status, bool, error) { + rec, ok := ss[t.ID] + if !ok { + return Status{}, false, nil + } + + if rec.Expirated.Before(time.Now()) { + return Status{}, false, nil + } + + if rec.Target.ID != t.ID || rec.Target.URL != t.URL { + return Status{}, false, errors.Errorf( + "target validation failed: (actual != expected) %v != %v", rec.Target, t) + } + + return rec.Status, true, nil +} + +// SetStatus saves the status of a target and makes it expire after `exp` +// amount of time. +func (ss SimpleStore) SetStatus(t Target, s Status, exp time.Duration) error { + rec := simpleStoreRecord{ + Target: t, + Status: s, + Expirated: time.Now().Add(exp), + } + ss[t.ID] = rec + return nil +}
428f6839ba6b1707e80289c611c8f50f1fee2fee
--- +++ @@ -1,6 +1,10 @@ package cf_http import ( + "crypto/tls" + "crypto/x509" + "errors" + "io/ioutil" "net" "net/http" "time" @@ -35,3 +39,30 @@ Timeout: timeout, } } + +func NewTLSConfig(certFile, keyFile, caCertFile string) (*tls.Config, error) { + tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, err + } + + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{tlsCert}, + InsecureSkipVerify: false, + } + + certBytes, err := ioutil.ReadFile(caCertFile) + if err != nil { + return nil, err + } + + if caCertFile != "" { + caCertPool := x509.NewCertPool() + if ok := caCertPool.AppendCertsFromPEM(certBytes); !ok { + return nil, errors.New("Unable to load caCert") + } + tlsConfig.RootCAs = caCertPool + } + + return tlsConfig, nil +}
bb2d16e9ce3a9ba52da19f6344fea83e1edd726a
--- +++ @@ -2,6 +2,7 @@ import ( "log" + "fmt" ) const ( @@ -19,9 +20,9 @@ } // Utility function for logging message -func logMessagef(actualLogLevel, msgLogLevel, format string, msgArgs...interface{} ) { +func logMessagef(actualLogLevel, msgLogLevel, format string, msgArgs ...interface{}) { if actualLogLevel <= msgLogLevel { - log.Printf("[%s] " + format, msgLogLevel, msgArgs) + log.Printf("[%s] %s", msgLogLevel, fmt.Sprintf(format, msgArgs...)) } }
7ab214657f7f0c4fdb2e9d513151dde09a90c463
--- +++ @@ -33,10 +33,10 @@ fmt.Fprintf(os.Stdout, "%v\n", env) c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"])) - project, err := c.GetProject("pypi", "cookiecutter") + project, _, err := c.GetProject("pypi", "cookiecutter") if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) + fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } fmt.Fprintf(os.Stdout, "%v\n", project)
f6d8190e8f62ce239158be8ffeb9ca63432c28b3
--- +++ @@ -29,3 +29,21 @@ } } } + +func TestParseConfigCRLF(t *testing.T) { + contents := "#cloud-config\r\nhostname: foo\r\nssh_authorized_keys:\r\n - foobar\r\n" + ud, err := ParseUserData(contents) + if err != nil { + t.Fatalf("Failed parsing config: %v", err) + } + + cfg := ud.(CloudConfig) + + if cfg.Hostname != "foo" { + t.Error("Failed parsing hostname from config") + } + + if len(cfg.SSHAuthorizedKeys) != 1 { + t.Error("Parsed incorrect number of SSH keys") + } +}
64faa63b2905e0bc84ea9d446490bcf126d5a756
--- +++ @@ -3,6 +3,7 @@ import ( "fmt" "os" + "strconv" ) func main() { @@ -10,4 +11,84 @@ fmt.Println("bad args") return } + handRaw := make([]string, len(os.Args)-1) + copy(handRaw, os.Args[1:]) + + startCard := Card{ + suit: ToSuit(pop(&handRaw)), + rank: ToRank(pop(&handRaw)), + } + + var hand Hand + for len(handRaw) > 0 { + hand = append(hand, Card{ + suit: ToSuit(pop(&handRaw)), + rank: ToRank(pop(&handRaw)), + }) + } + fmt.Println(startCard) + fmt.Println(hand) + } + +type Hand []Card + +func (h Hand) Len() int { return len(h) } +func (h Hand) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h Hand) Less(i, j int) bool { return h[i].rank < h[j].rank } + +func (h Hand) String() string { + var ret string + for _, c := range h { + ret += c.String() + " " + } + return ret +} + +type Card struct { + rank Rank + suit Suit +} + +func (c Card) String() string { + return fmt.Sprintf("%v%v", c.rank, c.suit) +} + +type Rank int + +func (r Rank) String() string { + switch r { + case 13: + return "K" + case 12: + return "Q" + case 11: + return "J" + default: + return strconv.Itoa(int(r)) + } +} + +func ToRank(a string) Rank { + r, err := strconv.Atoi(a) + if err != nil { + panic(err) + } + return Rank(r) +} + +type Suit byte + +func (s Suit) String() string { + return string([]byte{byte(s)}) +} + +func ToSuit(a string) Suit { + return Suit(a[0]) +} + +func pop(a *[]string) string { + val := (*a)[len(*a)-1] + *a = (*a)[:len(*a)-1] + return val +}
5ed85c6b3ffa1a647cda61b7ce3aa0c7ec2f372e
--- +++ @@ -24,6 +24,10 @@ success := false chessboard.Print() + if chessboard.IsChecked(now) { + fmt.Println("Your king is checked") + } + for success == false { from, err := scanMove() if err != nil {
bfd1fe977e1a4f921fce6b4ca522b024df0b2733
--- +++ @@ -17,19 +17,7 @@ exp2 := "2.19 kB" exp3 := "12.00 B" - res1 := StorageSize(data1).String() - res2 := StorageSize(data2).String() - res3 := StorageSize(data3).String() - - if res1 != exp1 { - t.Errorf("Expected %s got %s", exp1, res1) - } - - if res2 != exp2 { - t.Errorf("Expected %s got %s", exp2, res2) - } - - if res3 != exp3 { - t.Errorf("Expected %s got %s", exp3, res3) - } + c.Assert(StorageSize(data1).String(), checker.Equals, exp1) + c.Assert(StorageSize(data2).String(), checker.Equals, exp2) + c.Assert(StorageSize(data3).String(), checker.Equals, exp3) }
9d339268b019e7cf30818b5073899071aa39bf42
--- +++ @@ -1,9 +1,8 @@ package logouthandler import ( + "context" "net/url" - - "golang.org/x/net/context" "github.com/flimzy/jqeventrouter" "github.com/flimzy/log"
86c1ced2f5b76aa25a023d342b2379411af94754
--- +++ @@ -10,6 +10,8 @@ var ( textTmplCache = gomap.New() ) + +type Var map[string]interface{} func Sprintt(textTmpl string, data interface{}) string { ret := textTmplCache.GetOrCreate(textTmpl, func() interface{} {
6f2375c97130fc61eb62d9691ecd31878a68361f
--- +++ @@ -1,9 +1,6 @@ package anidb import ( - "github.com/Kovensky/go-fscache" - "strconv" - "strings" "time" )
184253db5b698e2f8cb9439262fd5b8262deb0af
--- +++ @@ -16,9 +16,15 @@ pat := os.Args[1] file := os.Args[2] - err := printMatchingLines(pat, file) + cnt, err := printMatchingLines(pat, file) if err != nil { fatal(2, err.Error()) + } + + if cnt > 0 { + os.Exit(0) + } else { + os.Exit(1) } } @@ -27,23 +33,25 @@ os.Exit(exitVal) } -func printMatchingLines(pat string, file string) error { +func printMatchingLines(pat string, file string) (int, error) { f, err := os.Open(file) if err != nil { - return err + return 0, err } defer f.Close() + matchCnt := 0 scan := bufio.NewScanner(bufio.NewReader(f)) for scan.Scan() { line := scan.Text() if strings.Contains(line, pat) { fmt.Println(line) + matchCnt++ } } if scan.Err() != nil { - return scan.Err() + return matchCnt, scan.Err() } - return nil + return matchCnt, nil }