_id
stringlengths
40
40
text
stringlengths
81
2.19k
title
stringclasses
1 value
7760ebe659fcc116bab1eaf747362e62849cd507
--- +++ @@ -32,7 +32,7 @@ } func (lb *LoadBalancer) Next() *Backend { - b, ok := lb.w[rand.Intn(len(lb.w)-1)] + b := lb.w[rand.Intn(len(lb.w)-1)] b.Handled++ return b }
aa71c88daffcf29c4a3f0038e4767508b795cc93
--- +++ @@ -1,40 +1,42 @@ package main import ( - . "github.com/franela/goblin" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" "errors" "testing" ) func Test(t *testing.T) { - g := Goblin(t) + RegisterFailHandler(Fail) + RunSpecs(t, "Run") +} - g.Describe("Run", func() { - extensionError := errors.New("run could not determine how to run this file because it does not have a known extension") +var _ = Describe("Run", func() { + extensionError := errors.New("run could not determine how to run this file because it does not have a known extension") - g.Describe(".command_for_file", func() { - g.Describe("when a filename is given with a known extension", func() { - g.It("should be a valid command", func() { - command, err := commandForFile("hello.rb") - g.Assert(command).Equal("ruby hello.rb") - g.Assert(err).Equal(nil) - }) + Describe(".command_for_file", func() { + Context("when a filename is given with a known extension", func() { + It("should be a valid command", func() { + command, err := commandForFile("hello.rb") + Expect(command).To(Equal("ruby hello.rb")) + Expect(err).To(BeNil()) }) + }) - g.Describe("when a filename is given without a known extension", func() { - g.It("should return an error", func() { - _, err := commandForFile("hello.unknown") - g.Assert(err).Equal(extensionError) - }) + Context("when a filename is given without a known extension", func() { + It("should return an error", func() { + _, err := commandForFile("hello.unknown") + Expect(err).To(Equal(extensionError)) }) + }) - g.Describe("when a filename is given without any extension", func() { - g.It("should return an error", func() { - _, err := commandForFile("hello") - g.Assert(err).Equal(extensionError) - }) + Context("when a filename is given without any extension", func() { + It("should return an error", func() { + _, err := commandForFile("hello") + Expect(err).To(Equal(extensionError)) }) }) }) -} +})
c4bc3b080eaf57ed3558200d0ca386e18c2331f7
--- +++ @@ -1,18 +1,3 @@ // +build !linux !cgo !seccomp package patchbpf - -import ( - "errors" - - "github.com/opencontainers/runc/libcontainer/configs" - - libseccomp "github.com/seccomp/libseccomp-golang" -) - -func PatchAndLoad(config *configs.Seccomp, filter *libseccomp.ScmpFilter) error { - if config != nil { - return errors.New("cannot patch and load seccomp filter without runc seccomp support") - } - return nil -}
d8603de7acebfbbd54101024afad03781375ea7e
--- +++ @@ -21,11 +21,13 @@ break } - response, err := xip.QueryResponse(query) - if err != nil { - log.Println(err.Error()) - break - } - _, err = conn.WriteToUDP(response, addr) + go func() { + response, err := xip.QueryResponse(query) + if err != nil { + log.Println(err.Error()) + break + } + _, err = conn.WriteToUDP(response, addr) + }() } }
064d5b673d539d884b1dfb53012bf49e56b49832
--- +++ @@ -15,9 +15,13 @@ // Avatar returns the default avatar currently. func Avatar(c echo.Context) error { - f, ok := fs.Get("/images/default-avatar.png", "") + inst := middlewares.GetInstance(c) + f, ok := fs.Get("/images/default-avatar.png", inst.ContextName) if !ok { - return echo.NewHTTPError(http.StatusNotFound, "Page not found") + f, ok = fs.Get("/images/default-avatar.png", "") + if !ok { + return echo.NewHTTPError(http.StatusNotFound, "Page not found") + } } handler := statik.NewHandler() handler.ServeFile(c.Response(), c.Request(), f, true) @@ -29,5 +33,5 @@ cacheControl := middlewares.CacheControl(middlewares.CacheOptions{ MaxAge: 24 * time.Hour, }) - router.GET("/avatar", Avatar, cacheControl) + router.GET("/avatar", Avatar, cacheControl, middlewares.NeedInstance) }
f440bf2f56ea93ed679574086dc7b7960b12b203
--- +++ @@ -6,8 +6,7 @@ now := time.Now().Unix() metrics := []string{"example"} - var accessTimes map[string]int64 - // accessTimes = make(map[string]int64) + var accessTimes map[string]int64 // ISSUE for _, m := range metrics { accessTimes[m] = now }
32aca3e1323886c478141cd488e1a5221fbaa04f
--- +++ @@ -13,7 +13,7 @@ return c, nil } -func (c *Client) Text(msg_sms *SMS) (interface{}, error) { +func (c *Client) Text(msg_sms *SMS) (*SMSResponse, error) { err := Validate(*msg_sms) @@ -23,11 +23,11 @@ smsResponse := &SMSResponse{} - resp, err := Send(c, msg_sms, smsResponse) - return resp,err + err = Send(c, msg_sms, smsResponse) + return smsResponse, err } -func (c *Client) Call(msg_voice *CALL) (interface{}, error) { +func (c *Client) Call(msg_voice *CALL) (*CALLResponse, error) { err := Validate(*msg_voice) @@ -37,6 +37,6 @@ callResponse := &CALLResponse{} - resp, err := Send(c, msg_voice, callResponse) - return resp,err + err = Send(c, msg_voice, callResponse) + return callResponse, err }
c434bbe48ee9c5067abedc31239db2f853ac501f
--- +++ @@ -8,13 +8,23 @@ ) func main() { - docodeFilePath := flag.String("config", "./DocodeFile", "ConfigFile to load") + docodeFilePath := flag.String("c", "./DocodeFile", "ConfigFile to load") + argsConfig := fetchConfigFromArgs() + flag.Parse() fileConfig := docodeconfig.NewFromFile(*docodeFilePath) - runner := docode.New(fileConfig) + config := docodeconfig.MergeConfigurations(argsConfig, fileConfig) + runner := docode.New(config) err := runner.Run() if err != nil { panic("ERROR: " + err.Error()) } } + +func fetchConfigFromArgs() docodeconfig.ArgsConfiguration { + argsConfig := docodeconfig.ArgsConfiguration{} + argsConfig.SSHKey = flag.String("k", "", "Ssh key path to use") + + return argsConfig +}
d3e0b484e37ef86bb6c3597fd06a7f09685069e9
--- +++ @@ -27,7 +27,7 @@ func NewDefaultHTTPClient() HTTPClient { client := http.Client{} rt := NewDefaultHTTPRoundTripper() - client.Transport = NewDefaultHTTPRoundTripper() + client.Transport = rt return HTTPClient{ Client: &client, ByteTracker: rt,
fef72651456546ef604497e028cce74713871741
--- +++ @@ -3,25 +3,26 @@ package draw2d +// PathBuilder define method that create path type Path interface { - // Return the current point of the path + // Return the current point of the current path LastPoint() (x, y float64) - // Create a new subpath that start at the specified point + + // MoveTo start a new path at (x, y) position MoveTo(x, y float64) - // Create a new subpath that start at the specified point - // relative to the current point - RMoveTo(dx, dy float64) - // Add a line to the current subpath + + // LineTo add a line to the current path LineTo(x, y float64) - // Add a line to the current subpath - // relative to the current point - RLineTo(dx, dy float64) + // QuadCurveTo add a quadratic curve to the current path QuadCurveTo(cx, cy, x, y float64) - RQuadCurveTo(dcx, dcy, dx, dy float64) + + // CubicCurveTo add a cubic bezier curve to the current path CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) - RCubicCurveTo(dcx1, dcy1, dcx2, dcy2, dx, dy float64) + + // ArcTo add an arc to the path ArcTo(cx, cy, rx, ry, startAngle, angle float64) - RArcTo(dcx, dcy, rx, ry, startAngle, angle float64) + + // Close the current path Close() }
2124089e144c463de7f21fa0540f6cbd66da4af1
--- +++ @@ -4,15 +4,15 @@ "sync" "testing" - "github.com/hashicorp/terraform/state" + "github.com/hashicorp/terraform/states/statemgr" ) func TestState_impl(t *testing.T) { - var _ state.StateReader = new(State) - var _ state.StateWriter = new(State) - var _ state.StatePersister = new(State) - var _ state.StateRefresher = new(State) - var _ state.Locker = new(State) + var _ statemgr.Reader = new(State) + var _ statemgr.Writer = new(State) + var _ statemgr.Persister = new(State) + var _ statemgr.Refresher = new(State) + var _ statemgr.Locker = new(State) } func TestStateRace(t *testing.T) {
ab30b9640bf308b322654248f67979727b744722
--- +++ @@ -26,3 +26,25 @@ } } } + +func TestParseUser(t *testing.T) { + cases := []struct { + in []byte + want *User + }{ + {[]byte("root"), &User{Name: "root"}}, + {[]byte(" root"), &User{Name: "root"}}, + {[]byte("root "), &User{Name: "root"}}, + } + for _, c := range cases { + got, _ := ParseUser(c.in) + if got.Name != c.want.Name { + t.Errorf( + "ParseUser(%q).Name == %q, want %q", + c.in, + got.Name, + c.want.Name, + ) + } + } +}
6428a6cfc41e39fbc377f4182b80be28bd3dffef
--- +++ @@ -17,10 +17,6 @@ // CensusData is a struct that contains various metadata that a Census request can have. type CensusData struct { Error string `json:"error"` -} - -func (c *CensusData) Error() string { - return c.error } // NewCensus returns a new census object given your service ID
f2495c45cd095ec69836bd6a4ca2841588050b75
--- +++ @@ -2,18 +2,3 @@ // Use of this source code is governed by the MIT license that can be found in the LICENSE file. package handler - -import ( - "testing" - - // . "github.com/TheThingsNetwork/ttn/utils/testing" -) - -func TestRegister(t *testing.T) { -} - -func TestHandleDown(t *testing.T) { -} - -func TestHandleUp(t *testing.T) { -}
fc009925671c235be04231476629f29118302039
--- +++ @@ -2,6 +2,7 @@ import ( "flag" + "fmt" "github.com/driusan/dgit/git" ) @@ -13,6 +14,10 @@ flags.BoolVar(&options.Cached, "cached", false, "Do not compare the filesystem, only the index") args, err := parseCommonDiffFlags(c, &options.DiffCommonOptions, flags, args) + + if len(args) < 1 { + return fmt.Errorf("Must provide a treeish to git diff-index") + } treeish, err := git.RevParseCommit(c, &git.RevParseOptions{}, args[0]) if err != nil {
49a19bb69b8f2573ba6630f5e9b564d304d51536
--- +++ @@ -1,12 +1,12 @@ package main import ( - "github.com/hashicorp/terraform/plugin" "github.com/finn-no/terraform-provider-softlayer/softlayer" + "github.com/hashicorp/terraform/plugin" ) func main() { - plugin.Serve(&plugin.ServeOpts{ - ProviderFunc: softlayer.Provider, - }) + plugin.Serve(&plugin.ServeOpts{ + ProviderFunc: softlayer.Provider, + }) }
51bc8619546d5deb61e73f428f42e4dfdb09ec60
--- +++ @@ -23,18 +23,22 @@ for j := 0; j < 256; j++ { sig[i] = byte(j) url := x.buildURL(addr, file, sig) - start := time.Now() + fastest := time.Hour - for k := 0; k < 15; k++ { + for k := 0; k < 10; k++ { + start := time.Now() resp, _ := http.Get(url) + elapsed := time.Since(start) resp.Body.Close() + + if elapsed < fastest { + fastest = elapsed + } } - elapsed := time.Since(start) - - if elapsed > timeBest { + if fastest > timeBest { valBest = byte(j) - timeBest = elapsed + timeBest = fastest } }
1e626fddc09e34210ba9e4412eb1266a869d0d04
--- +++ @@ -1 +1,16 @@ package main + +import "testing" + +func TestHandleConfigFile(t *testing.T) { + + if _, err := HandleConfigFile(""); err == nil { + t.FailNow() + } + + // Depends on default config being avaiable and correct (which is nice!) + if _, err := HandleConfigFile("config.yaml"); err != nil { + t.FailNow() + } + +}
ff48cecce2391f044c9ea8451ce493f429e7123b
--- +++ @@ -21,14 +21,16 @@ return } target := target_entity.(*entities.Planet) - target.UpdateShipCount() result := entities.EndMission(target, mission) + entities.Save(result) + state_change := response.NewStateChange() state_change.Planets = map[string]entities.Entity{ result.GetKey(): result, } response.Send(state_change, sessions.Broadcast) + entities.Delete(mission.GetKey()) }
0882169cff2bc982773234e7f85c774a8cb015df
--- +++ @@ -2,6 +2,7 @@ package engine -// #cgo CFLAGS: -Iinclude/php5 +// #cgo CFLAGS: -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM +// #cgo CFLAGS: -I/usr/include/Zend -Iinclude/php5 // #cgo LDFLAGS: -lphp5 import "C"
91d71c1963c50743d1dea5395c87561983171b97
--- +++ @@ -6,20 +6,28 @@ "testing" ) -func TestIsVersion2(t *testing.T) { +var ( + V1FilePath, V2FilePath string + V1ComposeFile, V2ComposeFile *ComposeFile +) + +func setup() { workingDir, _ := os.Getwd() - v1FilePath := filepath.Join(workingDir, "fixtures", "docker-compose-v1.yml") - v1ComposeFile, _ := NewComposeFile(v1FilePath) + V1FilePath = filepath.Join(workingDir, "fixtures", "docker-compose-v1.yml") + V2FilePath = filepath.Join(workingDir, "fixtures", "docker-compose-v2.yml") + V1ComposeFile, _ = NewComposeFile(V1FilePath) + V2ComposeFile, _ = NewComposeFile(V2FilePath) +} - if v1ComposeFile.IsVersion2() { - t.Fatalf(v1FilePath + " is actually not based on Compose File Version 2.") +func TestIsVersion2(t *testing.T) { + setup() + + if V1ComposeFile.IsVersion2() { + t.Fatalf(V1FilePath + " is actually not based on Compose File Version 2.") } - v2FilePath := filepath.Join(workingDir, "fixtures", "docker-compose-v2.yml") - v2ComposeFile, _ := NewComposeFile(v2FilePath) - - if !v2ComposeFile.IsVersion2() { - t.Fatalf(v2FilePath + " is actually based on Compose File Version 2.") + if !V2ComposeFile.IsVersion2() { + t.Fatalf(V2FilePath + " is actually based on Compose File Version 2.") } }
f2a753d1df1c3b2188acde5fbfad5ed41a3865c6
--- +++ @@ -6,6 +6,7 @@ "github.com/meatballhat/negroni-logrus" "github.com/unrolled/render" "net/http" + "os" ) func main() { @@ -27,7 +28,13 @@ r.HTML(w, http.StatusOK, "index", "world") }) - addr := ":3000" + var addr string + if len(os.Getenv("PORT")) > 0 { + addr = ":" + os.Getenv("PORT") + } else { + addr = ":3000" + } + l.Logger.Infof("Listening on %s", addr) l.Logger.Fatal(http.ListenAndServe(addr, n)) }
eda1e5db218aad1db63ca4642c8906b26bcf2744
--- +++ @@ -27,17 +27,22 @@ } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Check URL path for non-printable characters - idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { - return !unicode.IsPrint(c) - }) + if r != nil { + // Check URL path for non-printable characters + idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { + return !unicode.IsPrint(c) + }) - if idx != -1 { - w.WriteHeader(input.ErrStatus) - return + if idx != -1 { + w.WriteHeader(input.ErrStatus) + return + } + + if next != nil { + next.ServeHTTP(w, r) + } } - next.ServeHTTP(w, r) return }) }
01c842bf40ca91acf82f64b7e1e665524d5fb8cf
--- +++ @@ -4,9 +4,15 @@ "io" "log" "net" + "os/exec" ) func main() { + _, err := exec.LookPath("pbcopy") + if err != nil { + log.Fatal(err.Error()) + } + log.Print("Starting the server") listener, err := net.Listen("tcp", "127.0.0.1:8377") if err != nil {
5034d6a7d3f9ff718d5fe94dbdf538d60922c12f
--- +++ @@ -1,34 +1,34 @@ package object -type Type string +type Type = string const ( /* Internal Types */ - RETURN_VALUE Type = "<return value>" - FUNCTION Type = "<function>" - NEXT Type = "<next>" - BREAK Type = "<break>" + RETURN_VALUE = "<return value>" + FUNCTION = "<function>" + NEXT = "<next>" + BREAK = "<break>" /* Special Types */ - COLLECTION Type = "<collection>" - CONTAINER Type = "<container>" - HASHER Type = "<hasher>" - ANY Type = "<any>" + COLLECTION = "<collection>" + CONTAINER = "<container>" + HASHER = "<hasher>" + ANY = "<any>" /* Normal Types */ - NUMBER Type = "<number>" - BOOLEAN Type = "<boolean>" - STRING Type = "<string>" - CHAR Type = "<char>" - ARRAY Type = "<array>" - NULL Type = "<null>" - BLOCK Type = "<block>" - TUPLE Type = "<tuple>" - MAP Type = "<map>" - CLASS Type = "<class>" - INIT Type = "<init method>" - METHOD Type = "<method>" - INSTANCE Type = "<instance>" + NUMBER = "<number>" + BOOLEAN = "<boolean>" + STRING = "<string>" + CHAR = "<char>" + ARRAY = "<array>" + NULL = "<null>" + BLOCK = "<block>" + TUPLE = "<tuple>" + MAP = "<map>" + CLASS = "<class>" + INIT = "<init method>" + METHOD = "<method>" + INSTANCE = "<instance>" ) func is(obj Object, t Type) bool {
42d1c52c12fbabf4cfe5cb795e43642c8c925861
--- +++ @@ -22,13 +22,8 @@ } type Disk struct { - Driver Driver `xml:"driver"` Source Source `xml:"source"` Target Target `xml:"target"` -} - -type Driver struct { - Type string `xml:"type,attr"` } type Source struct {
77fec7d1e674771f2ce4a7a60510c0c5a36222ea
--- +++ @@ -10,11 +10,12 @@ func init() { plugin.HandleAutocmd("BufWritePre", - &plugin.AutocmdOptions{Pattern: "*.go", Group: "nvim-go", Eval: "[getcwd(), expand('%:p')]"}, autocmdBufWritePre) + &plugin.AutocmdOptions{Pattern: "*.go", Group: "nvim-go", Eval: "[getcwd(), expand('%:p:h'), expand('%:p')]"}, autocmdBufWritePre) } type bufwritepreEval struct { Cwd string `msgpack:",array"` + Dir string File string } @@ -32,9 +33,10 @@ } if config.FmtAsync { - go commands.Fmt(v, eval.Cwd) + go commands.Fmt(v, eval.Dir) } else { - return commands.Fmt(v, eval.Cwd) + return commands.Fmt(v, eval.Dir) } + return nil }
438f6c96cdc56e1bb3cc12daa16ae08b2ccae18b
--- +++ @@ -3,6 +3,7 @@ package util import ( + "fmt" "os" "os/exec" "syscall" @@ -18,9 +19,9 @@ func ExecCommandWith(_shell string, command string) *exec.Cmd { cmd := exec.Command("cmd") cmd.SysProcAttr = &syscall.SysProcAttr{ - HideWindow: false, - CmdLine: fmt.Sprintf(` /s /c "%s"`, command), - CreationFlags: 0, + HideWindow: false, + CmdLine: fmt.Sprintf(` /s /c "%s"`, command), + CreationFlags: 0, } return cmd }
24f286f82ed3999ed349372c76ccc272bc444362
--- +++ @@ -16,7 +16,7 @@ namespace := c.String("namespace") if namespace == "" { - return fmt.Errorf(`"--namespace" is a required flag for "tag"`) + return fmt.Errorf(`"--namespace" is a required flag for "push"`) } for _, repo := range repos {
2d00a8c4ba276ecd23cedac76754789bdccdd8d3
--- +++ @@ -17,3 +17,9 @@ } return r } + +// In returns true if k is a key of SMap, or false. +func (m SMap) In(k string) bool { + _, ok := m[k] + return ok +}
10d67817e85716b9b0cdbc1c819b36feb9ddfbe8
--- +++ @@ -6,9 +6,13 @@ // Emojis maps a name to an Emoji var Emojis = make(map[string]*Emoji) +// EmojisByChar maps a character to an Emoji +var EmojisByChar = make(map[string]*Emoji) + func init() { for _, e := range emojis { Emojis[e.Name] = e + EmojisByChar[e.Char] = e } }
6ad242e0633e22f1fd16c28200b33e37cd8dedde
--- +++ @@ -5,7 +5,7 @@ ) func TestVersioning(t *testing.T) { - if !NewVersionAvailable("v0.1.0") { - t.Error("should be a version newer than v0.1.0") + if !NewVersionAvailable("v1.0.0") { + t.Error("should be a version newer than v1.0.0") } }
7e5b72c2b0f7a1fdddbf05351fc3c421c5779052
--- +++ @@ -1,4 +1,57 @@ package task +import ( + "net/http" + + "example.com/internal/taskstore" + "github.com/labstack/echo/v4" +) + type TaskServer struct { + store *taskstore.TaskStore } + +func NewTaskServer() *TaskServer { + store := taskstore.New() + return &TaskServer{store: store} +} + +func (ts *TaskServer) GetDueYearMonthDay(ctx echo.Context, year int, month int, day int) error { + return nil +} + +func (ts *TaskServer) GetTagTagname(ctx echo.Context, tagname string) error { + return nil +} + +func (ts *TaskServer) GetTask(ctx echo.Context) error { + return nil +} + +func (ts *TaskServer) PostTask(ctx echo.Context) error { + var taskBody PostTaskJSONBody + err := ctx.Bind(&taskBody) + if err != nil { + return err + } + + // TODO: check non-nil on these fields?! + // TODO: do I need additional error checking here? + id := ts.store.CreateTask(*taskBody.Text, *taskBody.Tags, *taskBody.Due) + type ResponseId struct { + Id int `json:"id"` + } + ctx.JSON(http.StatusOK, ResponseId{Id: id}) +} + +func (ts *TaskServer) DeleteTaskId(ctx echo.Context, id int) error { + return nil +} + +func (ts *TaskServer) GetTaskId(ctx echo.Context, id int) error { + task, err := ts.store.GetTask(id) + if err != nil { + return err + } + ctx.JSON(http.StatusOK, task) +}
a4308d1c7d3dac64808a326b397215cff0f527c2
--- +++ @@ -11,6 +11,9 @@ var NodeNotFound = "can not build dialer to" func IsNodeNotFound(err error) bool { + if err == nil { + return false + } return strings.Contains(err.Error(), NodeNotFound) }
2b404dbe33ca5562ef5ac67b8040a4b86a067cb4
--- +++ @@ -2,78 +2,25 @@ import ( "fmt" - "net/url" - "os" "github.com/spf13/cobra" - - "github.com/lxc/lxd/client" ) type cmdImport struct { global *cmdGlobal - - flagForce bool - flagProject string } func (c *cmdImport) Command() *cobra.Command { cmd := &cobra.Command{} - cmd.Use = "import <container name>" - cmd.Short = "Import existing containers" + cmd.Use = "import" + cmd.Short = `Command has been replaced with "lxd recover"` cmd.Long = `Description: - Import existing containers - - This command is mostly used for disaster recovery. It lets you attempt - to recreate all database entries for containers that LXD no longer knows - about. - - To do so, you must first mount your container storage at the expected - path inside the storage-pools directory. Once that's in place, - ` + "`lxd import`" + ` can be called for each individual container. + This command has been replaced with "lxd recover". Please use that instead. ` cmd.RunE = c.Run - cmd.Flags().BoolVarP(&c.flagForce, "force", "f", false, "Force the import (override existing data or partial restore)") - cmd.Flags().StringVar(&c.flagProject, "project", "", "Specify the project") - return cmd } func (c *cmdImport) Run(cmd *cobra.Command, args []string) error { - // Quick checks. - if len(args) < 1 { - cmd.Help() - - if len(args) == 0 { - return nil - } - - return fmt.Errorf("Missing required arguments") - } - - // Only root should run this - if os.Geteuid() != 0 { - return fmt.Errorf("This must be run as root") - } - - name := args[0] - req := map[string]interface{}{ - "name": name, - "force": c.flagForce, - } - - d, err := lxd.ConnectLXDUnix("", nil) - if err != nil { - return err - } - - v := url.Values{} - v.Set("project", c.flagProject) - - _, _, err = d.RawQuery("POST", fmt.Sprintf("/internal/containers?%s", v.Encode()), req, "") - if err != nil { - return err - } - - return nil + return fmt.Errorf(`Command has been replaced with "lxd recover"`) }
50f8ba0a08e810846c1a764f7fdffe8a3daf53fb
--- +++ @@ -11,6 +11,7 @@ // The time complexity is O(n), where n is the number of digits in x. // The space complexity is O(1). func ReverseInt(x int64) (r int64, ok bool) { + const cutoff = math.MaxInt64/10 + 1 // The first smallest number such that cutoff*10 > MaxInt64. var n uint64 neg := x < 0 @@ -20,6 +21,9 @@ } for u > 0 { + if n >= cutoff { // Check if n*10 overflows. + return 0, false // TODO: cover this in tests! + } n = n*10 + u%10 if neg && n > -math.MinInt64 || !neg && n > math.MaxInt64 { // -n < math.MinInt64 || n > math.MaxInt64 return 0, false
eeea7906918ed8e4a5e16272d7e439390df7fde5
--- +++ @@ -16,7 +16,7 @@ ` func NewCommandSTIBuilder(name string) *cobra.Command { - cmd := &cobra.Command{ + return &cobra.Command{ Use: fmt.Sprintf("%s", name), Short: "Run an OpenShift Source-to-Images build", Long: longCommandSTIDesc, @@ -24,8 +24,6 @@ cmd.RunSTIBuild() }, } - - return cmd } const longCommandDockerDesc = ` @@ -36,7 +34,7 @@ ` func NewCommandDockerBuilder(name string) *cobra.Command { - cmd := &cobra.Command{ + return &cobra.Command{ Use: fmt.Sprintf("%s", name), Short: "Run an OpenShift Docker build", Long: longCommandDockerDesc, @@ -44,6 +42,4 @@ cmd.RunDockerBuild() }, } - - return cmd }
30637533818f789dffa39a51ce191484b026eee8
--- +++ @@ -18,7 +18,7 @@ import "github.com/go-kit/kit/metrics" -// This is a non-concurent safe counter that lets a single goroutine agregate +// This is a non-concurrent safe counter that lets a single goroutine aggregate // a metric before adding them to a larger correlated metric. type SimpleCounter struct { // The active count
2687cbc798235d97f51db8e62439171e6712be59
--- +++ @@ -23,7 +23,7 @@ return } - txb := build.TransactionBuilder{TX: tx.Tx} + txb := build.TransactionBuilder{TX: &tx.Tx} txb.Mutate(build.Network{passphrase}) result.Hash, err = txb.HashHex()
c18a27791884dbf069c1c6430562eec8fda4b345
--- +++ @@ -29,6 +29,11 @@ return "", errList } + return getUnique(list) +} + +func getUnique(list <-chan string) (string, error) { + err := errors.New("Not found (be less specific)") hash := "" for elem := range list {
d0631c8d725713ac3138359fab1dae915eb030cb
--- +++ @@ -1,10 +1,7 @@ package main import ( - "bytes" - c "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-check" - "github.com/flynn/flynn/pkg/exec" ) type PostgresSuite struct { @@ -15,20 +12,7 @@ // Check postgres config to avoid regressing on https://github.com/flynn/flynn/issues/101 func (s *PostgresSuite) TestSSLRenegotiationLimit(t *c.C) { - pgRelease, err := s.controllerClient(t).GetAppRelease("postgres") - t.Assert(err, c.IsNil) - - cmd := exec.Command(exec.DockerImage(imageURIs["postgresql"]), - "--tuples-only", "--command", "show ssl_renegotiation_limit;") - cmd.Entrypoint = []string{"psql"} - cmd.Env = map[string]string{ - "PGDATABASE": "postgres", - "PGHOST": "leader.pg.discoverd", - "PGUSER": "flynn", - "PGPASSWORD": pgRelease.Env["PGPASSWORD"], - } - - res, err := cmd.CombinedOutput() - t.Assert(err, c.IsNil) - t.Assert(string(bytes.TrimSpace(res)), c.Equals, "0") + query := flynn(t, "/", "-a", "controller", "psql", "-c", "SHOW ssl_renegotiation_limit") + t.Assert(query, Succeeds) + t.Assert(query, OutputContains, "ssl_renegotiation_limit \n-------------------------\n 0\n(1 row)") }
b4dc25dc8230f14349832bbfd92e958672f1a548
--- +++ @@ -39,7 +39,7 @@ case count > 1: infile = os.Stdin default: - fmt.Println("usage: grep pattern [file]") + fmt.Fprintln(os.Stderr, "usage: grep pattern [file]") os.Exit(1) }
015644b008dceeb4fc10aaeba280f368910ae44c
--- +++ @@ -30,8 +30,9 @@ }() for _, c := range cmds { + command := c fs = append(fs, func(cancel chan bool) error { - return cmd.Run(c, cancel, output) + return cmd.Run(command, cancel, output) }) } @@ -39,6 +40,7 @@ done <- struct{}{} if err != nil { hub.Send(channel, &hub.Message{Type: hub.MessageTypeError, Payload: err.Error()}) + fmt.Fprintf(w, "err; %v\n", err) } else { hub.Send(channel, &hub.Message{Type: hub.MessageTypeSuccess, Payload: "done without error"}) fmt.Fprintf(w, "")
a910ba609fb67654120cd539e65caa686c8e894e
--- +++ @@ -21,7 +21,7 @@ cmd.Run() } clear["windows"] = func() { - cmd := exec.Command("cls") + cmd := exec.Command("cmd", "/c", "cls") cmd.Stdout = os.Stdout cmd.Run() }
6acf8d0fbb33d3fa96af3900ddb9d062df5fa8a5
--- +++ @@ -1,9 +1,9 @@ package main import ( - "gform" "syscall" - "w32" + "github.com/AllenDang/gform" + "github.com/AllenDang/w32" ) const IDR_PNG1 = 100
10adbb2bdfa621ae3ac43736bd1a23781988b6ea
--- +++ @@ -20,7 +20,7 @@ defer c.mu.RUnlock() val := c.m[key] if val == nil { - return nil, fmt.Errorf("stack.Context: key '%s' does not exist", key) + return nil, fmt.Errorf("stack.Context: key %q does not exist", key) } return val, nil }
407568cc983d16b68baec4c91f40e60a38b5b367
--- +++ @@ -12,8 +12,8 @@ Convey("While creating Cassandra config with proper parameters", t, func() { config, err := cassandra.CreateConfigWithSession("127.0.0.1", "snap") Convey("I should receive not nil config", func() { + So(err, ShouldBeNil) So(config, ShouldNotBeNil) - So(err, ShouldBeNil) Convey("Config should have not nil session", func() { session := config.CassandraSession() So(session, ShouldNotBeNil)
882d2f8f88d80d42d9d79fc115e90ac2cbcaf7b3
--- +++ @@ -34,6 +34,9 @@ err = imageFetcher.Fetch(fetchImageContext{c}, image, &fetcher.FileReseter{File: target}) if err != nil { defer target.Close() + if fetcher.IsBrokenReferenceError(err) { + return runtime.NewMalformedPayloadError("unable to fetch image, error:", err) + } return err } return target.Close()
8f0576a2c63d7ef11bbf2161c00182233deee9ba
--- +++ @@ -5,13 +5,17 @@ import ( "http" "mahonia.googlecode.com/hg" + "strings" ) // phrasesInResponse scans the content of an http.Response for phrases, // and returns a map of phrases and counts. func phrasesInResponse(res *http.Response) map[string]int { defer res.Body.Close() - wr := newWordReader(res.Body, mahonia.NewDecoder("UTF-8")) // TODO: support other encodings, HTML entities + + contentType := res.Header.Get("Content-Type") + + wr := newWordReader(res.Body, decoderForContentType(contentType)) ps := newPhraseScanner() ps.scanByte(' ') buf := make([]byte, 4096) @@ -28,3 +32,28 @@ return ps.tally } + +func decoderForContentType(t string) mahonia.Decoder { + t = strings.ToLower(t) + var result mahonia.Decoder + + i := strings.Index(t, "charset=") + if i != -1 { + charset := t[i+len("charset="):] + i = strings.Index(charset, ";") + if i != -1 { + charset = charset[:i] + } + result = mahonia.NewDecoder(charset) + } + + if result == nil { + result = mahonia.FallbackDecoder(mahonia.NewDecoder("UTF-8"), mahonia.NewDecoder("windows-1252")) + } + + if strings.Contains(t, "html") { + result = mahonia.FallbackDecoder(mahonia.EntityDecoder(), result) + } + + return result +}
a27a91a9d151c339b9c81bebbc5af74cc5b05aa0
--- +++ @@ -2,6 +2,7 @@ import ( "fmt" + "math" "os" "os/exec" "strconv" @@ -25,6 +26,8 @@ fmt.Fprintf(os.Stdout, "NTP drift: %0.2fms\n", drift) + drift = math.Abs(drift) + if drift >= float64(f) { fmt.Fprintf(os.Stdout, "\n%s: NTP drift exceeds threshold (%0.2fms >= %dms)\n", fail, drift, f) return fail
3bb0dd0322d84fdca6405192216718b61a3cc439
--- +++ @@ -24,11 +24,5 @@ } func (d1 Dictionary) Equal(o Object) *Thunk { - d2, ok := o.(Dictionary) - - if !ok { - return False - } - - return NewBool(d1.hashMap.Equal(d2.hashMap)) + return NewBool(d1.hashMap.Equal(o.(Dictionary).hashMap)) }
db5deb62cd98873ab5661f7b818b5ce648f2f96b
--- +++ @@ -1,8 +1,7 @@ package aws import ( - "fmt" - + "github.com/aws/aws-sdk-go/aws/arn" "github.com/hashicorp/terraform/helper/schema" ) @@ -24,7 +23,13 @@ func dataSourceAwsBillingServiceAccountRead(d *schema.ResourceData, meta interface{}) error { d.SetId(billingAccountId) - d.Set("arn", fmt.Sprintf("arn:%s:iam::%s:root", meta.(*AWSClient).partition, billingAccountId)) + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "iam", + AccountID: billingAccountId, + Resource: "root", + } + d.Set("arn", arn.String()) return nil }
883f9be315ef02f77810ec2aef6c1e36f6a1d465
--- +++ @@ -28,7 +28,7 @@ } func NewGenPodOptions() *GenPodOptions { - return &GenPodOptions{} + return &GenPodOptions{Namespace: "default"} } func (s *GenPodOptions) AddFlags(fs *pflag.FlagSet) {
dddcbb71c45932feef3c2d0fe6fbdf375b0de644
--- +++ @@ -8,7 +8,7 @@ "runtime" ) -func (repo *Repository) GraphDescendantOf(commit, ancestor *Oid) (bool, error) { +func (repo *Repository) DescendantOf(commit, ancestor *Oid) (bool, error) { runtime.LockOSThread() defer runtime.UnlockOSThread() @@ -20,7 +20,7 @@ return (ret > 0), nil } -func (repo *Repository) GraphAheadBehind(local, upstream *Oid) (ahead, behind int, err error) { +func (repo *Repository) AheadBehind(local, upstream *Oid) (ahead, behind int, err error) { runtime.LockOSThread() defer runtime.UnlockOSThread()
49d01b6090743bec555987680eba18b776ad76f8
--- +++ @@ -3,14 +3,14 @@ import ( "fmt" "holux" + "log" ) func main() { c, err := holux.Connect() if err != nil { - // TODO LOG - fmt.Println(err) + log.Println(err) return } c.Hello() @@ -18,9 +18,9 @@ index, err := c.GetIndex() if err != nil { - fmt.Printf("Got error %v, arborting", err) + log.Fatalf("Got error %v, arborting", err) } - + for _, row := range index { fmt.Println(row) }
dcd47ba6c002705500a0a57276c83e3a9a3d5101
--- +++ @@ -1,8 +1,9 @@ package hsup import ( + "bitbucket.org/kardianos/osext" "errors" - "os" + "log" "runtime" ) @@ -28,9 +29,14 @@ } func linuxAmd64Path() string { - if runtime.GOOS == "linux" && runtime.GOARCH == "amd64" { - return os.Args[0] + exe, err := osext.Executable() + if err != nil { + log.Fatalf("could not locate own executable:", err) } - return os.Args[0] + "-linux-amd64" + if runtime.GOOS == "linux" && runtime.GOARCH == "amd64" { + return exe + } + + return exe + "-linux-amd64" }
8994563c6d3fd46d9333d7560fe51761c8e7c17c
--- +++ @@ -14,7 +14,7 @@ var v1 int = i; if foo1(v1) != 1 { panicln(1) } var v2 int32 = i.(int).(int32); - if foo1(v2) != 1 { panicln(2) } + if foo2(v2) != 1 { panicln(2) } var v3 int32 = i; // This implicit type conversion should fail at runtime. - if foo1(v3) != 1 { panicln(3) } + if foo2(v3) != 1 { panicln(3) } }
6a1221968544358a98b106045d83e915abd34575
--- +++ @@ -7,17 +7,15 @@ ) func sigChld() { - var sigs = make(chan os.Signal, 1) + var sigs = make(chan os.Signal, 10) // TODO(miek): buffered channel to fix races? signal.Notify(sigs, syscall.SIGCHLD) for { select { case <-sigs: go reap() - default: } } - } func reap() {
fbba21e532eea9f4d9faf9fbb3af3e91c74c6cdd
--- +++ @@ -5,6 +5,7 @@ "io" "io/ioutil" "net/http" + "os" ) type Render struct { @@ -45,3 +46,8 @@ json.Unmarshal(b, &item) return } + +func (r *Render) Write(file, body string) (err error) { + err = ioutil.WriteFile(file, []byte(body), os.ModePerm) + return +}
650103b77015147b18ff640e566937b68ef35db3
--- +++ @@ -22,7 +22,8 @@ // Reset resets the batch for reuse. Reset() - // Replay replays the batch contents. + // Replay replays the batch contents in the same order they were written + // to the batch. Replay(w KeyValueWriter) error // Inner returns a Batch writing to the inner database, if one exists. If
ed64b27081e9cc7e6c3c0caa5abd8ce905c5ed10
--- +++ @@ -3,11 +3,33 @@ import ( "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/spec" + "golang.org/x/net/http2" ) func HTTP2ConnectionPreface() *spec.TestGroup { tg := NewTestGroup("3.5", "HTTP/2 Connection Preface") + // The server connection preface consists of a potentially empty + // SETTINGS frame (Section 6.5) that MUST be the first frame + // the server sends in the HTTP/2 connection. + tg.AddTestCase(&spec.TestCase{ + Desc: "Sends client connection preface", + Requirement: "The server connection preface MUST be the first frame the server sends in the HTTP/2 connection.", + Run: func(c *config.Config, conn *spec.Conn) error { + setting := http2.Setting{ + ID: http2.SettingInitialWindowSize, + Val: spec.DefaultWindowSize, + } + + conn.Send("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") + conn.WriteSettings(setting) + + return spec.VerifyFrameType(conn, http2.FrameSettings) + }, + }) + + // Clients and servers MUST treat an invalid connection preface as + // a connection error (Section 5.4.1) of type PROTOCOL_ERROR. tg.AddTestCase(&spec.TestCase{ Desc: "Sends invalid connection preface", Requirement: "The endpoint MUST terminate the TCP connection.", @@ -17,6 +39,8 @@ return err } + // Connection has not negotiated, so we verify connection close + // instead of connection error. return spec.VerifyConnectionClose(conn) }, })
4622960835d758f3d87637fe2affd214afec46ba
--- +++ @@ -1,12 +1,12 @@ package main import ( - "github.com/hashicorp/terraform/builtin/providers/localfile" + "github.com/hashicorp/terraform/builtin/providers/local" "github.com/hashicorp/terraform/plugin" ) func main() { plugin.Serve(&plugin.ServeOpts{ - ProviderFunc: localfile.Provider, + ProviderFunc: local.Provider, }) }
34d99ff2c2406eb420be2727f0045f0b673a7df6
--- +++ @@ -1,10 +1,6 @@ package grpc -import ( - "testing" - "math/rand" - "time" -) +import "testing" func TestBackoffConfigDefaults(t *testing.T) { b := BackoffConfig{} @@ -13,36 +9,3 @@ t.Fatalf("expected BackoffConfig to pickup default parameters: %v != %v", b, DefaultBackoffConfig) } } - -func TestBackoffWitDifferentNumberOfRetries(t *testing.T) { - const MAX_RETRIES = 10 - randSrc := rand.NewSource(time.Now().UnixNano()) - randGen := rand.New(randSrc) - for i := 0; i < 5; i++ { - // generate a randon number, between 0 and MAX_RETRIES, to be used as number of retries - retries := randGen.Intn(MAX_RETRIES) - b := BackoffConfig{} - setDefaults(&b) - backoffTime := b.backoff(retries) - // backoff time should be between basedelay and max delay - if backoffTime < b.baseDelay || backoffTime > b.MaxDelay { - t.Fatalf("expected backoff time: %v to be between basedelay: %v and maxdelay: %v",backoffTime,b.baseDelay,b.MaxDelay) - } - } -} - -func TestBackOffTimeIncreasesWithRetries(t *testing.T) { - const MAX_RETRIES = 10 - b := BackoffConfig{} - setDefaults(&b) - // base delay - lastBackOffTime := b.backoff(0) - for retries := 1; retries <= MAX_RETRIES; retries++ { - backoffTime := b.backoff(retries) - // backoff time should increase as number of retries increase - if backoffTime <= lastBackOffTime { - t.Fatalf("backoffTime for %v retries : %v is smaller than backoffTime for %v retries: %v",retries,backoffTime,retries-1,lastBackOffTime) - } - lastBackOffTime = backoffTime - } -}
2547713698c5e44991aa0fe9137f07e60fc38dce
--- +++ @@ -6,7 +6,7 @@ ) // Per IP address rate limit in seconds -const rateLimitSeconds = 15 +const rateLimitSeconds = 3 var templates = template.Must(template.ParseFiles("tmpl/header.tmpl", "tmpl/footer.tmpl", "tmpl/homepage.tmpl", "tmpl/results.tmpl", "tmpl/checkForm.tmpl"))
a3590026f85d194f6547d537dffc3afe870dadb9
--- +++ @@ -11,7 +11,8 @@ type DeleteSpaceCommand struct { RequiredArgs flags.Space `positional-args:"yes"` Force bool `short:"f" description:"Force deletion without confirmation"` - usage interface{} `usage:"CF_NAME delete-space SPACE [-f]"` + Org string `short:"o" description:"Delete space within specified org"` + usage interface{} `usage:"CF_NAME delete-space SPACE [-o] [-f]"` } func (_ DeleteSpaceCommand) Setup(config commands.Config, ui commands.UI) error {
302d2b0c2d169d8ad898f4a6758a85fd65aa798f
--- +++ @@ -1,9 +1,23 @@ package model + +import "time" // Post represents a Facebook Post // // https://developers.facebook.com/docs/graph-api/reference/v2.4/post type Post struct { - ID string `json:"id"` - Message string `json:"message,omitempty"` + ID string `json:"id"` + Message string `json:"message,omitempty"` + Published bool `json:"published"` + ScheduledPublishTime time.Time `json:"scheduled_publish_time,omitempty"` + BackdatedTime time.Time `json:"backdated_time,omitempty"` + ObjectAttachment string `json:"object_attachment,omitempty"` + ChildAttachments []Link `json:"child_attachments,omitempty"` } + +// Link is used as a pointer to images in a post +// +// https://developers.facebook.com/docs/graph-api/reference/v2.4/link +type Link struct { + Link string `json:"link"` +}
7a9ca4a397c8b04e3585432f7ff941faa18a89c2
--- +++ @@ -2,6 +2,7 @@ import ( "net/http" + "time" "github.com/influxdata/chronograf" ) @@ -9,6 +10,7 @@ // Logger is middleware that logs the request func Logger(logger chronograf.Logger, next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { + now := time.Now() logger. WithField("component", "server"). WithField("remote_addr", r.RemoteAddr). @@ -16,6 +18,14 @@ WithField("url", r.URL). Info("Request") next.ServeHTTP(w, r) + later := time.Now() + elapsed := later.Sub(now) + + logger. + WithField("component", "server"). + WithField("remote_addr", r.RemoteAddr). + WithField("response_time", elapsed.String()). + Info("Success") } return http.HandlerFunc(fn) }
20eb61f2d513968ae7c916473f377f537f2fc19c
--- +++ @@ -11,6 +11,15 @@ { "https://github.com/sunaku/vim-unbundle", "https://github.com/sunaku/vim-unbundle", + }, + + { + "Shougo/neobundle.vim", + "https://github.com/Shougo/neobundle.vim", + }, + { + "thinca/vim-quickrun", + "https://github.com/thinca/vim-quickrun", }, }
fb881d4ebd787939b3dc88a6788fb4a6f0fd8645
--- +++ @@ -34,6 +34,10 @@ // Scan implements sql.Scanner interface func (js *JSON) Scan(src interface{}) error { + if src == nil { + *js = make(JSON) + return nil + } source, ok := src.([]byte) if !ok { return errors.New("Type assertion .([]byte) failed.")
3619a796dc015f673260575a1910b31bb924ebc8
--- +++ @@ -20,16 +20,21 @@ // // #include <windows.h> // -// static int getDPI() { +// static char* getDPI(int* dpi) { // HDC dc = GetWindowDC(0); -// int dpi = GetDeviceCaps(dc, LOGPIXELSX); -// ReleaseDC(0, dc); -// return dpi; +// *dpi = GetDeviceCaps(dc, LOGPIXELSX); +// if (!ReleaseDC(0, dc)) { +// return "ReleaseDC failed"; +// } +// return ""; // } import "C" func deviceScale() float64 { - dpi := int(C.getDPI()) + dpi := C.int(0) + if errmsg := C.GoString(C.getDPI(&dpi)); errmsg != "" { + panic(errmsg) + } return float64(dpi) / 96 }
10e10a0d172706241d350bfbfe9ac027006dbd86
--- +++ @@ -3,20 +3,17 @@ import ( "fmt" "os" + "strings" "github.com/bfirsh/whalebrew/cmd" ) func main() { - - if len(os.Args) > 1 { - // Check if not command exists - if _, _, err := cmd.RootCmd.Find(os.Args); err != nil { - // Check if file exists - if _, err := os.Stat(os.Args[1]); err == nil { - cmd.RootCmd.SetArgs(append([]string{"run"}, os.Args[1:]...)) - } - } + // HACK: if first argument starts with "/", prefix the subcommand run. + // This allows us to use this command as a shebang, because we can't pass + // the argument "run" in the shebang on Linux. + if len(os.Args) > 1 && strings.HasPrefix(os.Args[1], "/") { + cmd.RootCmd.SetArgs(append([]string{"run"}, os.Args[1:]...)) } if err := cmd.RootCmd.Execute(); err != nil {
2258533f00d6e8383052a06976b86e627bf1cc11
--- +++ @@ -16,7 +16,7 @@ httpdHerd = herd http.HandleFunc("/", statusHandler) http.HandleFunc("/listSubs", listSubsHandler) - http.HandleFunc("/showSubs", showAllSubsHandler) + http.HandleFunc("/showAllSubs", showAllSubsHandler) http.HandleFunc("/showDeviantSubs", showDeviantSubsHandler) http.HandleFunc("/showCompliantSubs", showCompliantSubsHandler) if daemon {
27a30ad59a93c22962db76c69f49bc46b4a9e7f8
--- +++ @@ -3,7 +3,7 @@ import "flag" func FromCommandLineArgs() *ApplicationConfiguration { - hostPort := flag.String("hostPort", ":9000", "Host:port of the greenwall HTTP server") + hostPort := flag.String("hostPort", ":9001", "Host:port of the greenwall HTTP server") staticDir := flag.String("staticDir", "frontend", "Path to frontend static resources") flag.Parse()
876a88b63c155ed97b093821876fcd9d17e92a21
--- +++ @@ -2,21 +2,22 @@ // Written by Maxim Khitrov (June 2013) // -package mock +package mock_test import ( "testing" "code.google.com/p/go-imap/go1/imap" + "code.google.com/p/go-imap/go1/mock" ) func TestNewClientOK(T *testing.T) { - C, t := Client(T, + C, t := mock.Client(T, `S: * OK Test server ready`, `C: A1 CAPABILITY`, `S: * CAPABILITY IMAP4rev1 XYZZY`, `S: A1 OK Thats all she wrote!`, - EOF, + mock.EOF, ) t.CheckState(imap.Login) t.CheckCaps("IMAP4rev1", "XYZZY")
f1d0cf0d906a3ed9543b64fdf7f4cfc0d4c35869
--- +++ @@ -15,7 +15,7 @@ for i := 0; i < 100; i++ { go func() { // Load the configuration file - config, err := env.LoadConfig("../../env.json") + config, err := env.LoadConfig("../../env.json.example") if err != nil { t.Fatal(err) }
878e88e777419ad5bd69ba537c062df7db26a7d4
--- +++ @@ -17,3 +17,35 @@ Stop Watch ) + +func (v Verb) String() string { + switch v { + case Ack: + return "Ack" + case Attach: + return "Attach" + case Connect: + return "Connect" + case Error: + return "Error" + case File: + return "File" + case Get: + return "Get" + case Log: + return "Log" + case Ls: + return "Ls" + case Set: + return "Set" + case Spawn: + return "Spawn" + case Start: + return "Start" + case Stop: + return "Stop" + case Watch: + return "Watch" + } + return "" +}
c71c0e10844ee5ea90099ff70c3fea88b3f3e56b
--- +++ @@ -18,10 +18,11 @@ } func (p Point) Equal(q Point) bool { - if p.X == q.X && p.Y == q.Y { - return true - } - return false + return p.X == q.X && p.Y == q.Y +} + +func (p Point) Less(q Point) bool { + return p.X < q.X || (p.Y < q.Y && p.X == q.X) } func (p Point) String() string {
78e4fa6f41a1061033be63ca323ae7837b3a5cd1
--- +++ @@ -16,5 +16,7 @@ } func (cfg *Config) InitDefaults() { - cfg.TimeFormat = defaultTimeFormat + if cfg.TimeFormat == "" { + cfg.TimeFormat = defaultTimeFormat + } }
ded70ace33c11aa33c8c565cbf852b0b31afa055
--- +++ @@ -54,7 +54,7 @@ go loader.GetHNFeed(hn) phres := <- hn var HNData loader.Feed = &phres - HNData.Display("Hacker News") + HNData.Display() } func doBiz(c *cli.Context) {
aa9e4840c5789a65d2fd9c35d5475b01360dc7bf
--- +++ @@ -9,6 +9,7 @@ fileNotFoundException = "java.io.FileNotFoundException" permissionDeniedException = "org.apache.hadoop.security.AccessControlException" pathIsNotEmptyDirException = "org.apache.hadoop.fs.PathIsNotEmptyDirectoryException" + FileAlreadyExistsException = "org.apache.hadoop.fs.FileAlreadyExistsException" ) // Error represents a remote java exception from an HDFS namenode or datanode. @@ -38,6 +39,8 @@ return os.ErrPermission case pathIsNotEmptyDirException: return syscall.ENOTEMPTY + case FileAlreadyExistsException: + return os.ErrExist default: return err }
345285a30844773b5141f898962dc7b10738a76b
--- +++ @@ -25,15 +25,16 @@ HasVertex(vertex Vertex) bool Order() uint Size() uint - AddVertex(v interface{}) bool - RemoveVertex(v interface{}) bool + AddVertex(v Vertex) bool + RemoveVertex(v Vertex) bool + AddEdge(edge Edge) (bool, error) } type DirectedGraph interface { Graph Transpose() DirectedGraph IsAcyclic() bool - GetCycles() [][]interface{} - addDirectedEdge(source interface{}, target interface{}) bool - removeDirectedEdge(source interface{}, target interface{}) bool + GetCycles() [][]Vertex + addDirectedEdge(source Vertex, target Vertex) bool + removeDirectedEdge(source Vertex, target Vertex) bool }
1d0f638ac2b262a3719bedfe2a2d504d112e16a4
--- +++ @@ -5,8 +5,6 @@ "github.com/joshheinrichs/geosource/server/types/fields" ) - -// "github.com/joshheinrichs/geosource/server/transactions" type PostInfo struct { Id string `json:"id" gorm:"column:p_postid"`
a7c971795e8c7c45015c436381a6c67ee53e9f78
--- +++ @@ -5,29 +5,40 @@ type basicLimiter struct { t *time.Ticker bc ByteCount - cbc chan ByteCount + cbc []chan ByteCount } func (bl *basicLimiter) Start() { for { <-bl.t.C - bl.cbc <- bl.bc + + perChan := bl.bc / ByteCount(len(bl.cbc)) + + for i := range bl.cbc { + go func(i int) { + bl.cbc[i] <- perChan + }(i) + } } } -func (bl basicLimiter) GetLimit() <-chan ByteCount { - return bl.cbc +func (bl *basicLimiter) GetLimit() <-chan ByteCount { + ch := make(chan ByteCount) + bl.cbc = append(bl.cbc, ch) + return ch } const timeSlice = 20 * time.Millisecond -//BasicLimiter will divvy up the bytes into 100 smaller parts to spread the load -//across time -func BasicLimiter(b ByteCount, t time.Duration) Limiter { +//NewBasicLimiter will appropriately distribute the rate given across 20ms +//windows. If used to create multiple LimitedReaders (or if GetLimit called +//multiple times), it will divvy up the rate across all the readers, at the same +//rate. +func NewBasicLimiter(b ByteCount, t time.Duration) Limiter { bl := &basicLimiter{ t: time.NewTicker(timeSlice), bc: b / ByteCount(t/timeSlice), - cbc: make(chan ByteCount), + cbc: make([]chan ByteCount, 0, 1), } go bl.Start() return bl
9900d0380ada6a96b7cf50e847245943de9f65fa
--- +++ @@ -14,7 +14,7 @@ func (bp backendsPresenter) Present() ([]byte, error) { backendsResponse := []string{} - for range bp.backends.All() { + for _ = range bp.backends.All() { backendsResponse = append(backendsResponse, "") }
c75cb871fa03912dac7d3e94cf6decaeadfcba66
--- +++ @@ -1,25 +1,44 @@ package main import ( + "crypto/tls" + "crypto/x509" "fmt" + "io/ioutil" "net/http" "os" "strings" ) func main() { - if len(os.Args) == 4 { - fmt.Println("UNSUPPORTED") - os.Exit(0) - } else if len(os.Args) != 3 { - fmt.Printf("usage: %v <host> <port>\n", os.Args[0]) + if len(os.Args) < 3 || len(os.Args) > 4 { + fmt.Printf("usage: %v <host> <port> [cafile]\n", os.Args[0]) os.Exit(1) } - url := "https://" + os.Args[1] + ":" + os.Args[2] + client := http.DefaultClient + if len(os.Args) == 4 { + cadata, err := ioutil.ReadFile(os.Args[3]) + if err != nil { + fmt.Println(err) + os.Exit(1) + } - // Perform an HTTP(S) Request - _, err := http.Get(url) + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(cadata) { + fmt.Println("Couldn't append certs") + os.Exit(1) + } + + client = &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{RootCAs: pool}, + }, + } + } + + // Perform an HTTPS Request + _, err := client.Get("https://" + os.Args[1] + ":" + os.Args[2]) if err != nil { fatalError := strings.Contains(err.Error(), "no such host") fmt.Println(err.Error())
226d4725bf5aa05eda7ba36f28ac2f222aac8508
--- +++ @@ -24,7 +24,7 @@ } // Remove the nth value from the sequence. -func (me *seq) Delete(index int) { +func (me *seq) DeleteIndex(index int) { me.i[index] = me.Index(me.Len() - 1) me.i = me.i[:me.Len()-1] } @@ -36,7 +36,7 @@ if !callback(s.Index(r)) { return false } - s.Delete(r) + s.DeleteIndex(r) } return true }
045c936958d45ce76820d0f7aad5f9d9c782d5f5
--- +++ @@ -3,6 +3,8 @@ import ( "regexp" "sync" + + "github.com/b2aio/typhon/auth" ) type EndpointRegistry struct { @@ -27,10 +29,17 @@ return nil } -func (r *EndpointRegistry) Register(endpoint *Endpoint) { +// Register an endpoint with the registry +func (r *EndpointRegistry) Register(e *Endpoint) { + + // Always set an Authorizer on an endpoint + if e.Authorizer == nil { + e.Authorizer = auth.DefaultAuthorizer + } + r.Lock() defer r.Unlock() - r.endpoints[endpoint.Name] = endpoint + r.endpoints[e.Name] = e } func (r *EndpointRegistry) Deregister(pattern string) {
6e4546b6820738580d8a30bb1d1719abd12dd41c
--- +++ @@ -6,12 +6,13 @@ "github.com/ghthor/engine/rpg2d" "github.com/ghthor/engine/rpg2d/quad" + "github.com/ghthor/engine/sim/stime" ) type inputPhase struct{} type narrowPhase struct{} -func (inputPhase) ApplyInputsIn(c quad.Chunk) quad.Chunk { +func (inputPhase) ApplyInputsIn(c quad.Chunk, now stime.Time) quad.Chunk { for _, e := range c.Entities { switch a := e.(type) { case actor: @@ -24,7 +25,7 @@ return c } -func (narrowPhase) ResolveCollisions(c quad.Chunk) quad.Chunk { +func (narrowPhase) ResolveCollisions(c quad.Chunk, now stime.Time) quad.Chunk { return c }
580cf7566a2b63c22ce551f72832e4f8fd5415ac
--- +++ @@ -7,8 +7,7 @@ ) func main() { - log.SetFormatter(&log.JSONFormatter{}) - log.AddHook(&logx.ErrorMessageHook{}) + log.DefaultSetup("info") conf, err := dhcp.GetConfig() if err != nil {
f97a196a40767fc931ecab2c9e9486674a8177d8
--- +++ @@ -10,3 +10,13 @@ assert.Equal(t, "foo/bar/baz", cleanImportSpec(&ast.ImportSpec{Path: &ast.BasicLit{Value: "foo/bar/baz"}})) assert.Equal(t, "foo/bar/baz", cleanImportSpec(&ast.ImportSpec{Path: &ast.BasicLit{Value: "\"foo/bar/baz\""}})) } + +func TestCandidatePaths(t *testing.T) { + r := []string{ + "a/b/vendor/c/d", + "a/vendor/c/d", + "vendor/c/d", + "c/d", + } + assert.Equal(t, r, candidatePaths("c/d", "a/b")) +}
0f5237af19a4e27adc2f0c84d236db45ba5e2446
--- +++ @@ -18,7 +18,7 @@ } _, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "") - if err != nil && strings.HasSuffix(err.Error(), ": EOF") { + if err != nil && !strings.HasSuffix(err.Error(), ": EOF") { // NOTE: if we got an EOF error here it means that the daemon // has shutdown so quickly that it already closed the unix // socket. We consider the daemon dead in this case.
dfc49dce9dfaa813328d352fe4f81d39de179139
--- +++ @@ -32,11 +32,5 @@ } return methodList, nil } - // Fallback to deprecated location. - for _, sm := range strings.Split(cert.Subject.CommonName, ",") { - if strings.Count(sm, ".") == 1 { - methodList[sm] = struct{}{} - } - } return methodList, nil }
659b15e37a9111074e9b0ec008b989912ec4dafe
--- +++ @@ -3,8 +3,7 @@ import "encoding/json" type DesireAppRequestFromCC struct { - AppId string `json:"app_id"` - AppVersion string `json:"app_version"` + ProcessGuid string `json:"process_guid"` DropletUri string `json:"droplet_uri"` Stack string `json:"stack"` StartCommand string `json:"start_command"` @@ -14,6 +13,7 @@ FileDescriptors uint64 `json:"file_descriptors"` NumInstances int `json:"num_instances"` Routes []string `json:"routes"` + LogGuid string `json:"log_guid"` } func (d DesireAppRequestFromCC) ToJSON() []byte {
68a9954511dd7825dc9b3744a68b51398ce120b1
--- +++ @@ -9,6 +9,10 @@ ) type WebhookMessage struct { + Username string `json:"username,omitempty"` + IconEmoji string `json:"icon_emoji,omitempty"` + IconURL string `json:"icon_url,omitempty"` + Channel string `json:"channel,omitempty"` Text string `json:"text,omitempty"` Attachments []Attachment `json:"attachments,omitempty"` }
1582f71461543c700a1c0ca34df3440f58a4b7ce
--- +++ @@ -1,6 +1,9 @@ package distribution -import "net/rpc" +import ( + "errors" + "net/rpc" +) // Waiter is a struct that is returned by Go() method to be able to // wait for a Node response. It handles the rpc.Call to be able to get @@ -22,5 +25,8 @@ // Error returns the rpc.Call error if any. func (w *Waiter) Error() error { + if w.rpcCall == nil { + return errors.New("RPC client is nil, maybe node " + w.Node.Addr + " is broken") + } return w.rpcCall.Error }
e91fa495631ff75320600c47c8a2f19614038247
--- +++ @@ -16,22 +16,22 @@ type AppleObserver struct{} func (AppleObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { - appleCount := defaultAppleCount - size := w.Size() + go func() { + appleCount := defaultAppleCount + size := w.Size() - if size > oneAppleArea { - appleCount = int(size / oneAppleArea) - } + if size > oneAppleArea { + appleCount = int(size / oneAppleArea) + } - logger.Debugf("apple count for size %d = %d", size, appleCount) + logger.Debugf("apple count for size %d = %d", size, appleCount) - for i := 0; i < appleCount; i++ { - if _, err := apple.NewApple(w); err != nil { - logger.WithError(err).Error("cannot create apple") + for i := 0; i < appleCount; i++ { + if _, err := apple.NewApple(w); err != nil { + logger.WithError(err).Error("cannot create apple") + } } - } - go func() { for event := range w.Events(stop, chanAppleObserverEventsBuffer) { if event.Type == world.EventTypeObjectDelete { if _, ok := event.Payload.(*apple.Apple); ok {
a1a9ecd3814854b08d58e8c44e40ca0e94b3d0a7
--- +++ @@ -12,7 +12,7 @@ "github.com/hyperledger/fabric/integration/helpers" ) -const DefaultStartTimeout = 30 * time.Second +const DefaultStartTimeout = 45 * time.Second // DefaultNamer is the default naming function. var DefaultNamer NameFunc = helpers.UniqueName
cf97444fc21cb98950213d042b248e540e706be9
--- +++ @@ -5,8 +5,6 @@ package w32 import ( - "fmt" - "syscall" "unicode/utf16" "unsafe" )
c9febb2239ed0f05fb24012a43e55e2a455fcef8
--- +++ @@ -1,3 +1,23 @@ package main -func main() {} +import ( + "fmt" + "os" + + "github.com/libgit2/git2go" +) + +func main() { + repo, err := git.OpenRepository(".") + if err != nil { + fmt.Printf("not a repo: %s\n", err) + os.Exit(5) + } + + desc, err := repo.DescribeWorkdir(&git.DescribeOptions{}) + if err != nil { + fmt.Printf("madness: %s\n", err) + os.Exit(6) + } + fmt.Printf("repo: %s\n", desc) +}
9bce6cad74f30ccc1117f4a76f25d8737213c6cb
--- +++ @@ -5,7 +5,8 @@ ) type Game struct { - Name string + Id uint `json:"id"` + Name string `json:"name"` SetupRules []SetupRule }