Dataset Viewer
Auto-converted to Parquet Duplicate
_id
stringlengths
40
40
text
stringlengths
81
2.19k
title
stringclasses
1 value
04b4d8b9ce557e8b1d868c53f29e663c54cc502d
--- +++ @@ -11,6 +11,8 @@ dst *regexp.Regexp }{ {"abc", regexp.MustCompile(`abc`)}, + + {"a,b", regexp.MustCompile(`(a|b)`)}, } func TestGenMatcher(t *testing.T) {
8cbf5b0f35478eeb748c4593f583e4996f3da562
--- +++ @@ -5,6 +5,7 @@ "fmt" "os" "github.com/lestrrat/go-xslate" + "github.com/lestrrat/go-xslate/loader" ) func usage() { @@ -24,14 +25,15 @@ } tx := xslate.New() + // TODO: Accept --path arguments + pwd, err := os.Getwd() + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to get current working directory: %s\n", err) + os.Exit(1) + } + tx.Loader, _ = loader.NewLoadFile([]string { pwd }) for _, file := range args { - fh, err := os.Open(file) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to open %s for reading: %s\n", file, err) - os.Exit(1) - } - - output, err := tx.RenderReader(fh, nil) + output, err := tx.Render(file, nil) if err != nil { fmt.Fprintf(os.Stderr, "Failed to render %s: %s\n", file, err) os.Exit(1)
5eef64a47062d4fc0cd8fa913984278a5ebb6900
--- +++ @@ -18,8 +18,8 @@ expectedType := reflect.TypeOf(matcher.Expected) if actualType.AssignableTo(expectedType) { - return true, formatMessage(actual, "not fitting type", matcher.Expected), nil + return true, formatMessage(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)), nil } else { - return false, formatMessage(actual, "fitting type", matcher.Expected), nil + return false, formatMessage(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)), nil } }
23c6b0c8b61e4b502e14e090c52107a0987e85bd
--- +++ @@ -8,6 +8,7 @@ "github.com/gravitational/trace" ) +// OneOf returns true if the value is present in the list of values func OneOf(value string, values []string) bool { for _, v := range values { if v == value { @@ -17,7 +18,9 @@ return false } +// APIClient defines generic interface for an API client type APIClient interface { + // Health checks the API readiness Health() error }
c9ededb515aefc2e14a021cd38b9313845463524
--- +++ @@ -10,7 +10,6 @@ "os" "path" "path/filepath" - "strings" ) func redirect(w http.ResponseWriter, r *http.Request, location string) { @@ -23,16 +22,8 @@ } func open(root, name string) (http.File, error) { - if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 || - strings.Contains(name, "\x00") { - return nil, errNotFound // invalid character in file path - } if root == "" { root = "." } - f, err := os.Open(filepath.Join(root, filepath.FromSlash(path.Clean("/"+name)))) - if err != nil { - return nil, err - } - return f, nil + return os.Open(filepath.Join(root, filepath.FromSlash(path.Clean("/"+name)))) }
21ffbc825cf7944a91de77d0ffc4c3967130c6f3
--- +++ @@ -13,7 +13,12 @@ func main() { compiler := compiler.New() - p := parser.New("a = 5; a") + p := parser.New(` + +a = 5 +a + +`) program := p.Parse() if len(p.Errors) > 0 {
13cf2a7d4342b448fc2722fb8e5e17f2cbd1bda4
--- +++ @@ -9,11 +9,13 @@ var enableNode bool var nodeName string var nodeCookie string +var nodePort int func init() { flag.BoolVar(&enableNode, "node", false, "start erlang node") flag.StringVar(&nodeName, "node-name", "", "name of erlang node") flag.StringVar(&nodeCookie, "node-cookie", "", "cookie of erlang node") + flag.IntVar(&nodePort, "node-port", 5858, "port of erlang node") } func nodeEnabled() bool { @@ -22,7 +24,7 @@ func runNode() (enode *node.Node) { enode = node.NewNode(nodeName, nodeCookie) - err := enode.Publish(5858) + err := enode.Publish(nodePort) if err != nil { log.Printf("Cannot publish: %s", err) enode = nil
5f86efb800160c786be0e593f6b758eefc47a830
--- +++ @@ -5,7 +5,6 @@ "log" "net/http" - "github.com/ant0ine/go-json-rest/rest" "github.com/julienbayle/jeparticipe/app" ) @@ -24,9 +23,9 @@ flag.Parse() - app := app.NewApp(*dbFile) - defer app.ShutDown() + jeparticipe := app.NewApp(*dbFile) + defer jeparticipe.ShutDown() - api := app.BuildApi(app.ProdMode, *baseUrl) + api := jeparticipe.BuildApi(app.ProdMode, *baseUrl) log.Fatal(http.ListenAndServe(":"+*port, api.MakeHandler())) }
1f3f00407aec774e47493353390622ee1efd5a24
--- +++ @@ -10,7 +10,7 @@ // Package stmt provides SQL statement string constants for SOMA package stmt -var m map[string]string +var m = make(map[string]string) func Name(statement string) string { return m[statement]
e9eec059d3a3a6718a531f0a0082f9664ef6a603
--- +++ @@ -2,7 +2,6 @@ import ( "fmt" - "sync" "testing" "time" ) @@ -13,13 +12,9 @@ var counter = 1 var i = 0 - mu := sync.Mutex{} + f := func(to *Ticker) { - f := func(to *Ticker) { - fmt.Println("Iteration: " + string(i)) - mu.Lock() - defer mu.Unlock() - + fmt.Printf("Iteration: %d\n", i) if i >= 5 { to.Done() }
ab49082107b84599b5475e311d8c72dcdadcbe80
--- +++ @@ -1,8 +1,8 @@ package main import( + "log" "net" - "os" ) const( @@ -10,17 +10,16 @@ ) func main() { - println("Starting the server") + log.Print("Starting the server") listener, err := net.Listen("tcp", "127.0.0.1:8377") if err != nil { - println("error Listen: ", err.Error()) - os.Exit(1) + log.Fatal("Listen: ", err.Error()) } for { conn, err := listener.Accept() if err != nil { - println("error Accept: ", err.Error()) + log.Print("Accept: ", err.Error()) return } @@ -32,15 +31,17 @@ buf := make([]byte, RECV_BUF_LEN) n, err := conn.Read(buf) if err != nil { - println("error Read: ", err.Error()) + log.Print("Read: ", err.Error()) return } - println("Received ", n, " bytes of data: ", string(buf)) + + log.Print("Received ", n, " bytes of data") _, err = conn.Write(buf) if err != nil { - println("error Write: ", err.Error()) + log.Print("Write: ", err.Error()) return } else { - println("Reply echoed") + log.Print("Reply echoed") + conn.Close() } }
33eb8004e43adafd3a6f43e4e3db115b2c7f5b8c
--- +++ @@ -7,16 +7,31 @@ "gopkg.in/juju/charm.v6-unstable" ) +// Status values specific to workload processes. +const ( + StatusPending Status = iota + StatusActive + StatusFailed + StatusStopped +) + // Status represents the status of a worload process. type Status string -// Status values specific to workload processes. -const ( - StatusPending Status = "pending" - StatusActive Status = "active" - StatusFailed Status = "failed" - StatusStopped Status = "stopped" -) +// String implements fmt.Stringer. +func (s Status) String() string { + switch status { + case StatusPending: + return "pending" + case StatusActive: + return "active" + case StatusFailed: + return "failed" + case StatusStopped: + return "stopped" + } + return "Unknown" +} // ProcessInfo holds information about a process that Juju needs. type ProcessInfo struct {
b672e0fe2a92ddfb5f692469e2097c06f8dab202
--- +++ @@ -32,7 +32,7 @@ // meta data about plugin const ( name = "ceph" - version = 2 + version = 3 pluginType = plugin.CollectorPluginType )
5dc526b01ae688ba5d3c89b21a580675898cdd34
--- +++ @@ -6,4 +6,20 @@ "BIT": true, "ONION": true, "ETH": true, + "BBS": true, + "CHAN": true, + "CYB": true, + "DYN": true, + "EPIC": true, + "GEEK": true, + "GOPHER":true, + "INDY": true, + "LIBRE": true, + "NEO": true, + "NULL": true, + "O": true, + "OSS": true, + "OZ": true, + "PARODY":true, + "PIRATE":true, }
a0d849d3a5a1334fb18d24e0c8888f259bbce669
--- +++ @@ -23,8 +23,8 @@ type Middleware func(http.Handler) http.Handler -// PreRequest of WebApp adds a pre-request handler. -// The lastest added middleware is called first. +// UseMiddleware of *WebApp adds a webapp.Middleware to the app. +// The lastest added middleware functions first. func (app *WebApp) UseMiddleware(f Middleware) { app.handler = f(app.handler) } @@ -33,7 +33,7 @@ app.handler.ServeHTTP(w, r) } -// UseAgent of WebApp adds the routes of a routeAgent to the app receiver by calling agent.BindRoute. +// UseAgent of *WebApp adds the routes of a routeAgent to the app receiver by calling agent.BindRoute. func (app *WebApp) UseAgent(agent routeAgent) { agent.BindRoute(app) }
74934f0aa59141418ee8346d26eba9f36ed2fae3
--- +++ @@ -19,3 +19,12 @@ t.Errorf("Time not parsed correctly, got: %s, want: %s.", result, wanted) } } + +func BenchmarkParseTime(b *testing.B) { + + message := []byte{0x24, 0x4b, 0xbb, 0x9a, 0xc9, 0xf0} + + for n := 0; n < b.N; n++ { + parseTime(message) + } +}
b0d24e0843195685b3942de931116b4f30930d2f
--- +++ @@ -5,6 +5,7 @@ import "fmt" func main() { + const max = 20 var k int for i := 1; true; i++ { // Let the user know we are still in search of the solution @@ -12,15 +13,25 @@ fmt.Println(i/1000000, " million numbers processed") } k = 0 - for j := 1; j <= 20; j++ { + for j := 1; j <= max; j++ { if i%j == 0 { k++ } } - if k == 20 { + if k == max { fmt.Println("Hoorrray, here it comes:", i) fmt.Println("Actually, Go supports concurrency by design and could do that much faster.") break } } } + +/* + Smallest multiple + Problem 5 + 2520 is the smallest number that can be divided by each of the numbers + from 1 to 10 without any remainder. + + What is the smallest positive number that is evenly divisible by all of + the numbers from 1 to 20? +*/
383e4f36649b88789333bef1ee3c447fee63ca58
--- +++ @@ -18,3 +18,10 @@ err := encoder.Encode(src) return err } + +func WriteErrorJSON(dst io.Writer, errorMsg string) error { + response := make(map[string]interface{}) + response["ok"] = false + response["failureReason"] = "Request does not have the header \"Content-Type: application-json\"" + return EncodeJSON(dst, response) +}
777289c17a05c3271cf62169a5d02411f2ed06cc
--- +++ @@ -13,15 +13,21 @@ var db gorm.DB type Check struct { - Id int64 - URL string + Id int64 + URL string `gorm:"column:url"` + Status int // status code of last result + Success bool // success status of last result + CreatedAt time.Time + UpdatedAt time.Time } type Result struct { - Timestamp time.Time + Id int64 + CreatedAt time.Time Status int Success bool - IP string + IP string `gorm:"column:ip"` + CheckId int64 } func InitDatabase() (err error) { @@ -35,13 +41,41 @@ return nil } -func (c Check) Create() error { - r := db.Create(c) - return r.Error +func Checks() ([]Check, error) { + var checks []Check + res := db.Find(&checks) + return checks, res.Error } -func Checks() ([]Check, error) { - checks := []Check{} - r := db.Find(&checks) - return checks, r.Error +func (c *Check) Create() error { + res := db.Create(c) + return res.Error } + +func (c *Check) AddResult(r *Result) error { + tx := db.Begin() + + r.CheckId = c.Id + res := tx.Create(r) + if res.Error != nil { + tx.Rollback() + return res.Error + } + + c.Status = r.Status + c.Success = r.Success + res = tx.Save(c) + if res.Error != nil { + tx.Rollback() + return res.Error + } + + tx.Commit() + return nil +} + +func (c *Check) Results() ([]Result, error) { + var results []Result + res := db.Model(c).Related(&results) + return results, res.Error +}
0c2e34e3d8c64bb1c81e41feca9e1f61374752a6
--- +++ @@ -7,7 +7,7 @@ import "unsafe" func GetProcAddress(name string) unsafe.Pointer { - var cname *C.GLubyte = (*C.GLubyte)(C.CString(name)) + var cname *C.GLubyte = (*C.GLubyte)(unsafe.Pointer(C.CString(name))) defer C.free(unsafe.Pointer(cname)) return unsafe.Pointer(C.glXGetProcAddress(cname)) }
8bce574cbba60f3412fc4f4a86d768bac077ac69
--- +++ @@ -11,6 +11,7 @@ "go.skia.org/infra/ct/go/ctfe/chromium_builds" "go.skia.org/infra/ct/go/ctfe/chromium_perf" "go.skia.org/infra/ct/go/ctfe/lua_scripts" + "go.skia.org/infra/ct/go/ctfe/pixel_diff" "go.skia.org/infra/ct/go/ctfe/task_common" ) @@ -19,6 +20,7 @@ return []task_common.Task{ &chromium_analysis.DBTask{}, &chromium_perf.DBTask{}, + &pixel_diff.DBTask{}, &capture_skps.DBTask{}, &lua_scripts.DBTask{}, &chromium_builds.DBTask{},
bcb9ce2498d52214ca4fde9bab8a6b415c350eff
--- +++ @@ -10,5 +10,19 @@ if err != nil { return fmt.Sprintf("error: '%v'", err) // OK } - return versionJSON + return string(versionJSON) } + +type StringWrapper struct { + s string +} + +func marshalUnmarshal(w1 StringWrapper) (string, error) { + buf, err := json.Marshal(w1) + if err != nil { + return "", err + } + var w2 StringWrapper + json.Unmarshal(buf, &w2) + return fmt.Sprintf("wrapped string: '%s'", w2.s), nil // OK +}
4032210a0d0482d6b473fa92bc6fa39346683155
--- +++ @@ -5,7 +5,7 @@ ) func BenchmarkDivisionMod(b *testing.B) { - d := NewDivisionMod(1000) + d := NewDivisionMod(1024) // run the dividable check function b.N times for n := 0; n < b.N; n++ { d.IsRestlessDividable(uint64(n)) @@ -21,7 +21,7 @@ } func BenchmarkZeroremainderUint32(b *testing.B) { - d := NewZeroremainderUint32(1000) + d := NewZeroremainderUint32(1024) // run the dividable check function b.N times for n := 0; n < b.N; n++ { d.IsRestlessDividable(uint64(n)) @@ -29,7 +29,7 @@ } func BenchmarkZeroremainderUint64(b *testing.B) { - d := NewZeroremainderUint64(1000) + d := NewZeroremainderUint64(1024) // run the dividable check function b.N times for n := 0; n < b.N; n++ { d.IsRestlessDividable(uint64(n))
c6388c5255fa615fbdab081374d50000cc6ce027
--- +++ @@ -1,11 +1,21 @@ package protocol import ( + "io" + "math" + "strconv" + . "github.com/Philipp15b/go-steam/protocol/steamlang" - "io" ) type JobId uint64 + +func (j JobId) String() string { + if j == math.MaxUint64 { + return "(none)" + } + return strconv.FormatUint(uint64(j), 10) +} type Serializer interface { Serialize(w io.Writer) error
d070bd6b739a30f8efe4b20363ba1adc5ece0531
--- +++ @@ -28,5 +28,11 @@ if want := "aaa"; string(s) != want { t.Errorf("got %q, want %q", string(s), want) } + if got := outBuf.String(); got != "" { + t.Errorf("got %q, want %q", got, "") + } + if got := errBuf.String(); got != "" { + t.Errorf("got %q, want %q", got, "") + } e.Clear() }
09980b8e6b94a854cded0147f3a904fa93b03484
--- +++ @@ -27,12 +27,21 @@ Subsystem: "ips", Help: "New IPs found", }) + + gaugeJobs = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "job", + Namespace: "scan", + Help: "Number of IPs found in each each job, with submitted and received times", + }, + []string{"id", "submitted", "received"}) ) func init() { prometheus.MustRegister(gaugeTotal) prometheus.MustRegister(gaugeLatest) prometheus.MustRegister(gaugeNew) + prometheus.MustRegister(gaugeJobs) } func metrics() {
4b9eec64fc4cfbc4487d955045956a901425c30e
--- +++ @@ -16,12 +16,16 @@ // Set up tasks for execution barReplacer.Init() - // Connect network + // Manually send file targets on the inport of barReplacer for _, name := range []string{"foo1", "foo2", "foo3"} { barReplacer.InPorts["foo2"] <- sci.NewFileTarget(name + ".txt") } + // We have to manually close the inport as well here, to + // signal that we are done sending targets (the tasks outport will + // then automatically be closed as well) close(barReplacer.InPorts["foo2"]) + for f := range barReplacer.OutPorts["bar"] { - fmt.Println("Processed file", f.GetPath(), "...") + fmt.Println("Finished processing file", f.GetPath(), "...") } }
a12a8dcf70a3c544e5706ce3b9b98b84470ef5c3
--- +++ @@ -21,10 +21,24 @@ func New(n int) *Bucket { b := new(Bucket) - b.bucket = make(chan int, n) b.elems = make([]Elem, n) b.held = make([]bool, n) + b.bucket = make(chan int, n) + for i := 0; i < n; i++ { + b.bucket<-i + } return b +} + +func (b *Bucket) Init(f func(int) interface{}) { + for _, p := range b.held { + if p { + panic("held") + } + } + for i, _ := range b.elems { + b.elems[i] = Elem{i, f(i)} + } } func (b *Bucket) Size() int { @@ -46,6 +60,6 @@ if !b.held[i] { panic("free") } - b.bucket<-i + b.bucket <- i b.held[i] = false }
2c0d6ad1e5b2a44a377e378f5f46d6313a17defd
--- +++ @@ -5,6 +5,7 @@ import ( "flag" + "github.com/russross/blackfriday" "html/template" ) @@ -26,7 +27,17 @@ // Load base templates and templates from the provided pattern // TODO: if performance becomes an issue, we can start caching the base templates, and cloning func LoadTemplates(patterns ...string) (*template.Template, error) { - b, err := template.ParseGlob(*LayoutTemplateGlob) + var err error + // add some key helper functions to the templates + b := template.New("base").Funcs(template.FuncMap{ + "markdownCommon": func(raw string) template.HTML { + return template.HTML(blackfriday.MarkdownCommon([]byte(raw))) + }, + "markdownBasic": func(raw string) template.HTML { + return template.HTML(blackfriday.MarkdownBasic([]byte(raw))) + }, + }) + b, err = b.ParseGlob(*LayoutTemplateGlob) if err != nil { return nil, err }
4d66a86150e620f96c777fbd2db1accc737bddb4
--- +++ @@ -1,18 +1,73 @@ package main import ( + "flag" + "fmt" "log" + "os" + "sort" "github.com/coreos/go-etcd/etcd" ) +type NodeGroup []*etcd.Node //NodeGroup is a slice of pointers to etcd Nodes + +// Sort Interface implementation methods +func (n NodeGroup) Len() int { + return len(n) +} + +func (n NodeGroup) Less(i, j int) bool { + if n[i].Key < n[j].Key { + return true + } + return false +} + +func (n NodeGroup) Swap(i, j int) { + n[i], n[j] = n[j], n[i] +} + +func Usage() { + fmt.Printf("Usage: %s\n", os.Args[0]) + flag.PrintDefaults() + os.Exit(2) +} + +func SetupFlags() (discoveryHost, discoveryPath *string) { + discoveryHost = flag.String("discovery_host", + "http://127.0.0.1:4001", "Discovery URL:Port") + discoveryPath = flag.String("discovery_path", + "", + "Discovery path i.e. _etcd/registry/uVa2GHOTTxl27eyKk6clBwyaurf7KiWd") + + flag.Parse() + + if *discoveryHost == "" || *discoveryPath == "" { + Usage() + } + + return discoveryHost, discoveryPath +} + func main() { - client := etcd.NewClient([]string{"http://104.130.8.142:4001"}) - resp, err := client.Get("testcluster", false, false) - if err != nil { - log.Fatal(err) + // Connect to the etcd discovery to pull the nodes + discoveryHost, discoveryPath := SetupFlags() + + client := etcd.NewClient([]string{*discoveryHost}) + resp, _ := client.Get(*discoveryPath, false, false) + + // Store the pointer to the etcd nodes as a NodeGroup + group := NodeGroup{} + for _, n := range resp.Node.Nodes { + group = append(group, n) } - for _, n := range resp.Node.Nodes { + + // Sort the NodeGroup + sort.Sort(group) + + // Print out sorted NodeGroup by key + for _, n := range group { log.Printf("%s: %s\n", n.Key, n.Value) } }
0292261bc4fb1511f197df986705327fd0b77f1d
--- +++ @@ -2,8 +2,8 @@ import ( "io/ioutil" + "net" "os" - "os/exec" "regexp" "strings" ) @@ -13,16 +13,25 @@ ) func getLocalIP() string { - for _, i := range []string{"en0", "en1", "en2"} { - cmd := exec.Command("ipconfig", "getifaddr", i) - b, err := cmd.Output() - if err != nil { + addrs, err := net.InterfaceAddrs() + if err != nil { + return "" + } + + for _, address := range addrs { + ipnet, ok := address.(*net.IPNet) + if !ok { continue } - if len(b) > 0 { - return strings.Trim(string(b[:]), "\n") + if ipnet.IP.IsLoopback() { + continue } + if ipnet.IP.To4() == nil { + continue + } + + return ipnet.IP.String() } return ""
571bad4bf39576e70e4a4278ba5753a1b59126a1
--- +++ @@ -18,9 +18,6 @@ if err != nil { return nil, err } - if len(buf) != 24 { - return nil, errgo.Newf("invalid nonce length %q", buf) - } copy(nonce[:], buf) return &nonce, nil }
1cdaf06b7edc343a0846f82053aaf9a0d5581e57
--- +++ @@ -7,7 +7,7 @@ "path/filepath" "strings" - "sourcegraph.com/sourcegraph/toolchain" + "sourcegraph.com/sourcegraph/srclib/toolchain" ) func runCmdLogError(cmd *exec.Cmd) {
01c91bef6938e4e4db78fa8e6b2a6b58215140b3
--- +++ @@ -2,7 +2,6 @@ import ( "bytes" - "fmt" "os" "syscall" @@ -24,7 +23,6 @@ signalChannel <- syscall.SIGSEGV <-doneChannel - fmt.Println(errBuf) Expect(errBuf).To(ContainSubstring("Dumping goroutines")) Expect(errBuf).To(MatchRegexp(`goroutine (\d+) \[(syscall|running)\]`)) })
e4b0a989f353a0e9bbca45331c8ae3f9fd69dc50
--- +++ @@ -3,12 +3,10 @@ package main import ( - "bytes" "errors" "os" - "os/exec" + "os/user" "path/filepath" - "strings" ) func configFile() (string, error) { @@ -40,18 +38,15 @@ return home, nil } - // If that fails, try the shell - var stdout bytes.Buffer - cmd := exec.Command("sh", "-c", "eval echo ~$USER") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { + // If that fails, try build-in module + user, err := user.Current() + if err != nil { return "", err } - result := strings.TrimSpace(stdout.String()) - if result == "" { + if user.HomeDir == "" { return "", errors.New("blank output") } - return result, nil + return user.HomeDir, nil }
65c37623ae654d0c362d57f6cbecd5e955ba198c
--- +++ @@ -1,6 +1,8 @@ package cloudwatch import ( + "fmt" + "math/rand" "testing" "time" @@ -26,8 +28,20 @@ go adapter.Stream(messages) for i := 0; i < NumMessages; i++ { - messages <- &router.Message{Data: randomdata.Paragraph(), Time: time.Now()} + messages <- createMessage() } close(messages) } + +func createMessage() *router.Message { + data := "" + timestamp := time.Now() + random := rand.Intn(100) + + if random == 0 { + data = randomdata.Paragraph() + } + + return &router.Message{Data: data, Time: timestamp} +}
02adfa95cc7ea83b13b135a67877b8669fb4ae0d
--- +++ @@ -1,8 +1,14 @@ package dockercommand import ( + "crypto/tls" + "crypto/x509" + "io/ioutil" + "log" + "net/http" + "os" + docker "github.com/fsouza/go-dockerclient" - "os" ) type Docker struct { @@ -15,6 +21,32 @@ if err != nil { return nil, err } + + if len(os.Getenv("DOCKER_CERT_PATH")) != 0 { + cert, err := tls.LoadX509KeyPair(os.Getenv("DOCKER_CERT_PATH")+"/cert.pem", os.Getenv("DOCKER_CERT_PATH")+"/key.pem") + if err != nil { + log.Fatal(err) + } + + caCert, err := ioutil.ReadFile(os.Getenv("DOCKER_CERT_PATH") + "/ca.pem") + if err != nil { + log.Fatal(err) + } + caCertPool := x509.NewCertPool() + caCertPool.AppendCertsFromPEM(caCert) + + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{cert}, + RootCAs: caCertPool, + } + tlsConfig.BuildNameToCertificate() + tr := &http.Transport{ + TLSClientConfig: tlsConfig, + } + client.HTTPClient.Transport = tr + + } + return &Docker{client}, nil }
9d1f233729426e7fca0c8cc5eefedac1b57a7e5f
--- +++ @@ -14,8 +14,8 @@ ) func init() { - acmednsHost = os.Getenv("") - acmednsAccountsJson = []byte(os.Getenv("AZURE_CLIENT_SECRET")) + acmednsHost = os.Getenv("ACME_DNS_HOST") + acmednsAccountsJson = []byte(os.Getenv("ACME_DNS_ACCOUNT_JSON")) if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 { acmednsLiveTest = true }
695d264c9e955632c09a74741d21f31b26e31d2a
--- +++ @@ -6,7 +6,7 @@ import "bufio" import "bytes" -import "github.com/UniversityRadioYork/ury-rapid-go/tokeniser" +import "github.com/UniversityRadioYork/ury-rapid-go/baps3protocol" func main() { conn, err := net.Dial("tcp", "127.0.0.1:1350") @@ -14,7 +14,7 @@ fmt.Println(err) os.Exit(1) } - t := tokeniser.NewTokeniser() + t := baps3protocol.NewTokeniser() for { data, err := bufio.NewReader(conn).ReadBytes('\n') if err != nil {
0ffb77da6e1d1eb8873e70aa081ac3bbffd8dd6f
--- +++ @@ -21,14 +21,22 @@ return NewEnviron(cfg) } +// BoilerplateConfig is specified in the EnvironProvider interface. +func (*maasEnvironProvider) BoilerplateConfig() string { + panic("Not implemented.") +} + +// SecretAttrs is specified in the EnvironProvider interface. func (*maasEnvironProvider) SecretAttrs(*config.Config) (map[string]interface{}, error) { panic("Not implemented.") } +// PublicAddress is specified in the EnvironProvider interface. func (*maasEnvironProvider) PublicAddress() (string, error) { panic("Not implemented.") } +// PrivateAddress is specified in the EnvironProvider interface. func (*maasEnvironProvider) PrivateAddress() (string, error) { panic("Not implemented.") }
b63844bcb5922c6683451a392c732bd00f918d2b
--- +++ @@ -3,23 +3,38 @@ import ( "archive/tar" "bytes" + "errors" "io" ) type Stream struct { io.ReadCloser - Size int64 + Size int64 + closed bool } func NewStream(data io.ReadCloser, size int64) Stream { - return Stream{data, size} + return Stream{data, size, false} } -func (s Stream) Out(dst io.Writer) error { - defer s.Close() - if _, err := io.CopyN(dst, s, s.Size); err != nil { +func (s *Stream) Out(dst io.Writer) error { + if s.closed { + return errors.New("closed") + } + defer s.ReadCloser.Close() + n, err := io.CopyN(dst, s, s.Size) + s.Size -= n + return err +} + +func (s *Stream) Close() error { + if s.closed { + return nil + } + if err := s.ReadCloser.Close(); err != nil { return err } + s.closed = true return nil }
aafa04c15675bca3c3d65d502a22e2a74b3fa664
--- +++ @@ -21,7 +21,7 @@ fields := make([]zapcore.Field, len(data)) i := 0 for k, v := range data { - fields[i] = zap.Reflect(k, v) + fields[i] = zap.Any(k, v) i++ }
0663ffd381df7599c7e3961e8638ded0e322b267
--- +++ @@ -20,10 +20,10 @@ truststore = os.Args[1] switch truststore { case "mozilla": - csvURL = "https://mozillacaprogram.secure.force.com/CA/IncludedCACertificateReportPEMCSV" + csvURL = "https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReportPEMCSV" csvPEMPos = 28 case "microsoft": - csvURL = "https://mozillacaprogram.secure.force.com/CA/apex/IncludedCACertificateReportForMSFTCSVPEM" + csvURL = "https://ccadb-public.secure.force.com/microsoft/IncludedCACertificateReportForMSFTCSVPEM" csvPEMPos = 6 } resp, err := http.Get(csvURL)
a9748f2657b41b03a4209baa8a04e07ba1c023b8
--- +++ @@ -16,24 +16,22 @@ ) // DisplayErrors enables/disables HDF5's automatic error printing -func DisplayErrors(b bool) error { - switch b { - case true: - if err := h5err(C._go_hdf5_unsilence_errors()); err != nil { - return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err) - } - default: - if err := h5err(C._go_hdf5_silence_errors()); err != nil { - return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err) - } +func DisplayErrors(on bool) error { + var err error + if on { + err = h5err(C._go_hdf5_unsilence_errors()) + } else { + err = h5err(C._go_hdf5_silence_errors()) + } + if err != nil { + return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err) } return nil } func init() { - err := DisplayErrors(false) - if err != nil { - panic(err.Error()) + if err := DisplayErrors(false); err != nil { + panic(err) } }
bdac81fced51a326481f473704d677f6a73af953
--- +++ @@ -14,7 +14,7 @@ } var _ = BeforeSuite(func() { - StartChrome() + StartPhantomJS() Server.Start() })
52ceb9fbc6674c9fa4f409d989b9b8c832e1aed7
--- +++ @@ -1,6 +1,18 @@ package main import ( + "os" + "os/exec" + +// "log" + +// "fmt" + "strings" + "runtime" +// "strconv" // For Itoa +// "encoding/csv" + "encoding/json" + "github.com/go-martini/martini" ) @@ -8,6 +20,52 @@ func main() { m := martini.Classic() + // CPU count + m.Get("/sh/numberofcores.php", func () ([]byte, error) { + return json.Marshal(runtime.NumCPU()) + }) + + // Server's hostname + m.Get("/sh/hostname.php", func () ([]byte, error) { + host, err := os.Hostname() + + if err != nil { + return nil, err + } + + return json.Marshal(host) + }) + + + + // PS + m.Get("/sh/ps.php", func () ([]byte, error) { + // Run uptime command + rawOutput, err := exec.Command("ps", "aux").Output() + + // Convert output to a string (it's not binary data, so this is ok) + output := string(rawOutput[:]) + + if err != nil { + return nil, err + } + + // We'll add all the parsed lines here + var entries [][]string + + // Lines of output + lines := strings.Split(output, "\n") + + // Skip first and last line of output + for _, str := range lines[1:len(lines)-1] { + + entries = append(entries, strings.Fields(str)) + } + + return json.Marshal(entries) + }) + + // Serve static files m.Get("/.*", martini.Static("")) m.Run()
2d65002b593899a225f18e239ce6991c677ff69e
--- +++ @@ -13,24 +13,25 @@ package main import ( - "flag" - "fmt" - "github.com/lateefj/fresh/runner" - "os" + "flag" + "fmt" + "os" + + "github.com/pilu/fresh/runner" ) func main() { - configPath := flag.String("c", "", "config file path") - flag.Parse() + configPath := flag.String("c", "", "config file path") + flag.Parse() - if *configPath != "" { - if _, err := os.Stat(*configPath); err != nil { - fmt.Printf("Can't find config file `%s`\n", *configPath) - os.Exit(1) - } else { - os.Setenv("RUNNER_CONFIG_PATH", *configPath) - } - } + if *configPath != "" { + if _, err := os.Stat(*configPath); err != nil { + fmt.Printf("Can't find config file `%s`\n", *configPath) + os.Exit(1) + } else { + os.Setenv("RUNNER_CONFIG_PATH", *configPath) + } + } - runner.Start() + runner.Start() }
4755f8bf41cc3a022fded9eea3cb6b283cad3518
--- +++ @@ -5,4 +5,8 @@ // This is not a generic JSON parser. Instead, it deals with the mapping from // the JSON information model to the HCL information model, using a number // of hard-coded structural conventions. +// +// In most cases applications will not import this package directly, but will +// instead access its functionality indirectly through functions in the main +// "hcl" package and in the "hclparse" package. package json
81d1346bf815b714e5929dc6e9d1bec8c346003f
--- +++ @@ -4,12 +4,12 @@ // Because is context printer. func Because(t *testing.T, context string, wrapper func(*testing.T)) { - Log(" Because:", context, "\n") + Log(" Because ", context, "\n") wrapper(t) } // When is an alternative of `Because` func When(t *testing.T, context string, wrapper func(*testing.T)) { - Log(" When:", context, "\n") + Log(" When ", context, "\n") wrapper(t) }
00ab1bb968d1444d2fe1daa6defd2682c082d361
--- +++ @@ -6,6 +6,7 @@ "time" ) +// ewmaRate tracks an exponentially weighted moving average of a per-second rate. type ewmaRate struct { newEvents int64 alpha float64 @@ -22,12 +23,14 @@ } } +// rate returns the per-second rate. func (r *ewmaRate) rate() float64 { r.mutex.Lock() defer r.mutex.Unlock() return r.lastRate } +// tick assumes to be called every r.interval. func (r *ewmaRate) tick() { newEvents := atomic.LoadInt64(&r.newEvents) atomic.AddInt64(&r.newEvents, -newEvents) @@ -44,6 +47,7 @@ } } +// inc counts one event. func (r *ewmaRate) inc() { atomic.AddInt64(&r.newEvents, 1) }
82fd6f9d4125f8daf16fbdbd88678b5c2a67b6e5
--- +++ @@ -4,10 +4,10 @@ package mat64 -// Inner computes the generalized inner product between x and y with matrix A. -// x^T A y -// This is only a true inner product if m is symmetric positive definite, though -// the operation works for any matrix A. +// Inner computes the generalized inner product +// x^T A y +// between vectors x and y with matrix A. This is only a true inner product if +// A is symmetric positive definite, though the operation works for any matrix A. // // Inner panics if len(x) != m or len(y) != n when A is an m x n matrix. func Inner(x []float64, A Matrix, y []float64) float64 {
433745d068bf6bceb9c438e4bd0a8d713de5ed77
--- +++ @@ -1,4 +1,6 @@ package ast + +import "fmt" // AnonymousFunction represents a anonymous function as an expression. type AnonymousFunction struct { @@ -20,3 +22,7 @@ func (f AnonymousFunction) Body() interface{} { return f.body } + +func (f AnonymousFunction) String() string { + return fmt.Sprintf("(\\ (%v) %v)", f.signature, f.body) +}
5b5dcf2405100a9f87dab83babff4488aa57073d
--- +++ @@ -3,10 +3,12 @@ import ( "code.google.com/p/go-uuid/uuid" - "github.com/dnaeon/gru/minion" +// "github.com/dnaeon/gru/minion" + "gru/minion" ) type Client interface { // Submits a new task to a minion - SubmitTask(minion uuid.UUID, task MinionTask) error + SubmitTask(u uuid.UUID, t minion.MinionTask) error } +
9bd714adb545abd5eaeb19c36a4d897fe4a9f41d
--- +++ @@ -16,20 +16,33 @@ } func main() { - exitCode := 0 - defer os.Exit(exitCode) - + // Catch some signals for whcih we want to clean up on exit sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) fatalSink := fatal.New() i := balancer.Start(os.Args, fatalSink, iptables) - defer i.Stop() + + exitCode := 0 + var exitSignal os.Signal select { - case <-sigs: case err := <-fatalSink: fmt.Fprintln(os.Stderr, err) exitCode = 1 + case exitSignal = <-sigs: + exitCode = 2 } + + i.Stop() + + if sig, ok := exitSignal.(syscall.Signal); ok { + // Now we have cleaned up, re-kill the process with + // the signal in order to produce a signal exit + // status: + signal.Reset(sig) + syscall.Kill(syscall.Getpid(), sig) + } + + os.Exit(exitCode) }
26fead6a64ec453e40f2bc4fb41ac7148ee6cb3b
--- +++ @@ -6,7 +6,7 @@ noise := New(rand.Int63()) w, h := 100, 100 - heightmap := make([]float64, w, h) + heightmap := make([]float64, w*h) for y := 0; y < h; y++ { for x := 0; x < w; x++ { xFloat := float64(x) / float64(w)
297dd000cad23a2416a40be48c86d58dc3ab8d2c
--- +++ @@ -9,6 +9,11 @@ // see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html var DBSubnetGroup = Resource{ AwsType: "AWS::RDS::DBSubnetGroup", + + // Name + ReturnValue: Schema{ + Type: ValueString, + }, Properties: map[string]Schema{ "DBSubnetGroupDescription": Schema{
173a41dd536bf2d7cac4126950c698c590f1f3fd
--- +++ @@ -6,7 +6,7 @@ // IsVTXDisabled checks if VT-x is disabled in the CPU. func (d *Driver) IsVTXDisabled() bool { - if cpuid.HasFeature(cpuid.VMX) || cpuid.HasFeature(cpuid.SVM) { + if cpuid.HasFeature(cpuid.VMX) || cpuid.HasExtraFeature(cpuid.SVM) { return false }
e39a4f111b95a17c5b40afe33771017a52a3f8cb
--- +++ @@ -3,9 +3,6 @@ import ( . "github.com/smartystreets/goconvey/convey" "github.com/stellar/go-horizon/test" - "github.com/zenazn/goji/web" - "net/http" - "net/http/httptest" "testing" ) @@ -14,14 +11,9 @@ Convey("GET /", t, func() { test.LoadScenario("base") app := NewTestApp() + rh := NewRequestHelper(app) - r, _ := http.NewRequest("GET", "/", nil) - w := httptest.NewRecorder() - c := web.C{ - Env: map[interface{}]interface{}{}, - } - - app.web.router.ServeHTTPC(c, w, r) + w := rh.Get("/", test.RequestHelperNoop) So(w.Code, ShouldEqual, 200) })
55ddd24e0357d733b321872fda8b183025f6a2c4
--- +++ @@ -9,7 +9,7 @@ const ( // version of Convoy - VERSION = "0.4.3" + VERSION = "0.4.4-dev" ) func cleanup() {
b6e805835a546d7481bc6f184f174ae5b6d040c6
--- +++ @@ -14,7 +14,7 @@ os.Exit(1) } - reader, err := myShell.Cat("QmQLBvJ3ur7U7mzbYDLid7WkaciY84SLpPYpGPHhDNps2Y") + reader, err := myShell.Cat("QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y") if err != nil { fmt.Fprintf(os.Stderr, "error: %s\n", err) os.Exit(1) @@ -24,7 +24,13 @@ buf.ReadFrom(reader) output := buf.String() - expected := "\"The man who makes no mistakes does not make anything.\" - Edward John Phelps\n" + expected := `Come hang out in our IRC chat room if you have any questions. + +Contact the ipfs dev team: +- Bugs: https://github.com/ipfs/go-ipfs/issues +- Help: irc.freenode.org/#ipfs +- Email: dev@ipfs.io +` if output != expected { t.FailNow()
dcb040897dbb65d073d0e40bee1a32fba9db1dea
--- +++ @@ -10,12 +10,15 @@ mc := NewMergeController(session, dbname, fhirHost) - // Merging and confict resolution + // Merging and confict resolution. router.POST("/merge", mc.Merge) router.POST("/merge/:merge_id/resolve/:conflict_id", mc.Resolve) - router.POST("/merge/:merge_id/abort", mc.Abort) - // Convenience routes + // Abort or delete a merge. Abort is just an alias for delete. + router.POST("/merge/:merge_id/abort", mc.DeleteMerge) + router.DELETE("/merge/:merge_id", mc.DeleteMerge) + + // Convenience routes. router.GET("/merge", mc.AllMerges) router.GET("/merge/:merge_id", mc.GetMerge) router.GET("/merge/:merge_id/conflicts", mc.GetRemainingConflicts)
075bcf92c669fd55c16629e37626aa94a37fe697
--- +++ @@ -3,11 +3,17 @@ import ( "os" + "github.com/agtorre/gocolorize" "github.com/jessevdk/go-flags" "github.com/src-d/beanstool/cli" + "golang.org/x/crypto/ssh/terminal" ) func main() { + if !terminal.IsTerminal(int(os.Stdout.Fd())) { + gocolorize.SetPlain(true) + } + parser := flags.NewNamedParser("beanstool", flags.Default) parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{}) parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})
e5443e64953484cc1c1231ff426a48b624bf61bb
--- +++ @@ -28,3 +28,13 @@ t.Error("URL with defaults is bad") } } + +func TestCreateMissingFile(t *testing.T) { + consumer, _ := Create("") + if consumer != nil { + t.Error("Should fail no file") + } +} + + +
4b13bfde1d9d1e5e49aeecb78f6455dfea2250ce
--- +++ @@ -2,7 +2,11 @@ package mlock -import "syscall" +import ( + "syscall" + + "golang.org/x/sys/unix" +) func init() { supported = true @@ -10,5 +14,5 @@ func lockMemory() error { // Mlockall prevents all current and future pages from being swapped out. - return syscall.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE) + return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE) }
b573d5ad08cfc3a909d62aa9464bfdc4b97c452a
--- +++ @@ -14,13 +14,29 @@ RememberMe bool `json:"remember_me"` } +// Starts the wizard config func configWizard() *Configuration { configuration := new(Configuration) fmt.Println("Welcome to gotify !\nThis wizard will help you set up gotify, follow it carefully !") StartWizard(configuration) + err := saveConfig(configuration) + if err != nil { + log.Fatal(err) + } return configuration } +// Save the configuration in the config.json file +func saveConfig(configuration *Configuration) error { + config, err := json.Marshal(configuration) + if err != nil { + return err + } + err = ioutil.WriteFile("config.json", config, 0644) + return err +} + +// Load the configuration from config.json or launch the wizard if it does not exists func LoadConfig() *Configuration { if _, err := os.Stat("config.json"); os.IsNotExist(err) { configuration := configWizard()
044b900af4fa20c3403b4b59830c9b08e16c9846
--- +++ @@ -9,9 +9,16 @@ ) var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)} +var ar = Response{BodyBytes: []byte(`["jo nesbo",["jo nesbo","jo nesbo harry hole","jo nesbo sohn","jo nesbo koma","jo nesbo hörbuch","jo nesbo headhunter","jo nesbo pupspulver","jo nesbo leopard","jo nesbo schneemann","jo nesbo the son"],[{"nodes":[{"name":"Bücher","alias":"stripbooks"},{"name":"Trade-In","alias":"tradein-aps"},{"name":"Kindle-Shop","alias":"digital-text"}]},{}],[]]`)} + var jsonTests = []TC{ {jr, &JSON{Expression: "(.foo == 5) && ($len(.bar)==3) && (.bar[1]==2)"}, nil}, {jr, &JSON{Expression: ".foo == 3"}, someError}, + {ar, &JSON{Expression: "$len(.) > 3"}, nil}, + {ar, &JSON{Expression: "$len(.) == 4"}, nil}, + {ar, &JSON{Expression: ".[0] == \"jo nesbo\""}, nil}, + {ar, &JSON{Expression: "$len(.[1]) == 10"}, nil}, + {ar, &JSON{Expression: ".[1][6] == \"jo nesbo pupspulver\""}, nil}, } func TestJSON(t *testing.T) {
872b8636fe5a1aa5eb38505249edc9fd13dcb70c
--- +++ @@ -37,3 +37,38 @@ } +func TestQueueCapacity(t *testing.T) { + pq := PacketQueue{} + for i := 0; i < PACKET_BUFFER_SIZE; i++ { + serial, err := pq.Add([]byte{0, 0, byte(i)}) + if err != nil { + t.Error(err) + } + if serial != uint64(i) { + t.Errorf("Serial %d did not match %d", serial, i) + } + } + + _, err := pq.Add([]byte{0}) + if err == nil { + t.Errorf("Queue did not error when adding past capacity") + } + + const trimNum uint64 = 5 + pq.TrimUpTo(trimNum) + + for i := 0; uint64(i) < trimNum; i++ { + serial, err := pq.Add([]byte{1, byte(i)}) + if err != nil { + t.Error(err) + } + if serial != uint64(PACKET_BUFFER_SIZE + i) { + t.Errorf("Serial %d did not match %d", serial, i) + } + } + + _, err = pq.Add([]byte{0}) + if err == nil { + t.Errorf("Queue did not error when adding past capacity") + } +}
ba65a9e5f8f8f152bbf2ab255b2a91a6e540a86e
--- +++ @@ -17,4 +17,9 @@ if median != 2.5 { t.Error("Median must be equal to 2.5") } + + median, err := Median([]float64{}) + if err == nil { + t.Error("Empty list. Must return an error") + } }
61432cd257371a28175c8928deee4588924b0d52
--- +++ @@ -19,7 +19,7 @@ ip, err := driver.GetInstanceIP(id) if err != nil { - err = fmt.Errorf("Error getting instance's public IP: %s", err) + err = fmt.Errorf("Error getting instance's IP: %s", err) ui.Error(err.Error()) state.Put("error", err) return multistep.ActionHalt @@ -27,7 +27,7 @@ state.Put("instance_ip", ip) - ui.Say(fmt.Sprintf("Instance has public IP: %s.", ip)) + ui.Say(fmt.Sprintf("Instance has IP: %s.", ip)) return multistep.ActionContinue }
786327941ec633d34ff9c6844d01815bd75e11da
--- +++ @@ -1,4 +1,9 @@ package gokhipu + +import ( + "fmt" + "net/http" +) var ( basePath = "https://khipu.com/api/2.0" @@ -18,3 +23,24 @@ ReceiverID: receiverID, } } + +// Banks ... +func (kc *Khipu) Banks() (*http.Response, error) { + requestPath := basePath + "/banks" + req, err := http.NewRequest("GET", requestPath, nil) + if err != nil { + return nil, fmt.Errorf(fmt.Sprintf("failed to create request to %s\n%s", requestPath, err)) + } + + req.Header.Set("Authorization", setAuth(nil, "GET", requestPath, kc.Secret, kc.ReceiverID)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + cl := http.Client{} + res, err := cl.Do(req) + if err != nil { + return nil, fmt.Errorf(fmt.Sprintf("failed to made request to %s\n%s", requestPath, err)) + } + + return res, nil +}
44de547317ecb78e4176631c7726f14082db7c48
--- +++ @@ -1,15 +1,21 @@ package service import ( - "github.com/coreos/go-etcd/etcd" + "io/ioutils" "log" "os" + + "github.com/coreos/go-etcd/etcd" ) var ( logger *log.Logger client *etcd.Client hostname string + + cacert = os.Getenv("ETCD_CACERT") + tlskey = os.Getenv("ETCD_TLS_KEY") + tlscert = os.Getenv("ETCD_TLS_CERT") ) func init() { @@ -17,7 +23,11 @@ if len(os.Getenv("ETCD_HOST")) != 0 { host = os.Getenv("ETCD_HOST") } - client = etcd.NewClient([]string{host}) + if len(cacert) != 0 && len(tlskey) != 0 && len(tlscert) != 0 { + client = newTLSClient([]string{host}) + } else { + client = etcd.NewClient([]string{host}) + } if len(os.Getenv("HOSTNAME")) != 0 { hostname = os.Getenv("HOSTNAME") @@ -31,3 +41,23 @@ logger = log.New(os.Stderr, "[etcd-discovery]", log.LstdFlags) } + +func newTLSClient(hosts []string) *etcd.Client { + cacertContent, err := ioutils.ReadAll(cacert) + if err != nil { + panic(err) + } + keyContent, err := ioutils.ReadAll(tlskey) + if err != nil { + panic(err) + } + certContent, err := ioutils.ReadAll(tlscert) + if err != nil { + panic(err) + } + c, err := etcd.NewTLSClient(hosts, string(certContent), string(keyContent), string(cacertContent)) + if err != nil { + panic(err) + } + return c +}
73f5faba9cd044a44c3b2e25f4f8a8fd5327567d
--- +++ @@ -14,6 +14,16 @@ - name: z3 cloud_properties: availability_zone: ((az)) + +- type: replace + path: /vm_types + value: + - name: default + cloud_properties: + instance_type: m1.small + - name: large + cloud_properties: + instance_type: m1.xlarge - type: replace path: /compilation
6ea3342a6ba446a5d73ab80bde427b9791596ddf
--- +++ @@ -9,7 +9,7 @@ // ensureGBDXDir will create the gbdx directory if it doesn't already exist. func ensureGBDXDir() (string, error) { gbdxPath := path.Join(userHomeDir(), ".gbdx") - err := os.MkdirAll(gbdxPath, 0775) + err := os.MkdirAll(gbdxPath, 0600) return gbdxPath, err } @@ -25,14 +25,3 @@ } return os.Getenv("HOME") } - -// conf := &oauth2.Config{ -// ClientID: "...", -// ClientSecret: "...", -// Endpoint: oauth2.Endpoint{ -// TokenURL: "https://geobigdata.io/auth/v1/oauth/token", -// }, -// } - -// ctx := oauth2.NoContext -// token, err := conf.PasswordCredentialsToken(ctx, "...", "...")
7db07de599f0cdcccfa3a5d7a788d312e378b9dc
--- +++ @@ -7,7 +7,7 @@ ) // Flag returns the Value interface to the value of the named flag, -// returning nil if none exists. +// panics if none exists. func (cmd *CLI) Flag(name string) values.Value { flag := cmd.getFlag(name) value := cmd.flagValues[flag]
92a7e3585fa8811d151f3447afecd3809645ae01
--- +++ @@ -10,7 +10,7 @@ Data []byte } -func (image *Image) serialize() (serialized []byte, err error) { +func (image *Image) Serialize() (serialized []byte, err error) { buffer := bytes.NewBuffer([]byte{}) encoder := gob.NewEncoder(buffer) err = encoder.Encode(image) @@ -21,7 +21,7 @@ return } -func (image *Image) unserialize(data []byte) error { +func (image *Image) Unserialize(data []byte) error { buffer := bytes.NewBuffer(data) decoder := gob.NewDecoder(buffer) err := decoder.Decode(image)
2a09bb753794125e929014cf08c431faefeeec32
--- +++ @@ -3,6 +3,11 @@ import ( "net" "os" +) + +const ( + EADDRINUSE = "address in use" + ECONNREFUSED = "connection refused" ) // reuseErrShouldRetry diagnoses whether to retry after a reuse error. @@ -29,9 +34,9 @@ } switch e1.Err.Error() { - case "address in use": + case EADDRINUSE: return true - case "connection refused": + case ECONNREFUSED: return false default: return true // optimistically default to retry.
70b573255d307ac730393fdf5550e32566773ff6
--- +++ @@ -16,6 +16,7 @@ package daemon import ( + "fmt" h "github.com/tgres/tgres/http" x "github.com/tgres/tgres/transceiver" "net" @@ -27,6 +28,7 @@ http.HandleFunc("/metrics/find", h.GraphiteMetricsFindHandler(t)) http.HandleFunc("/render", h.GraphiteRenderHandler(t)) + http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "OK\n") }) server := &http.Server{ Addr: addr,
6205608474a3637d975e8fa4313a78d7e4db51ad
--- +++ @@ -9,7 +9,7 @@ } func (m *RectangeChunkMask) IsMasked(x, z int) bool { - return x <= m.x0 || x > m.x1 || z <= m.z0 || z > m.z1 + return x < m.x0 || x >= m.x1 || z < m.z0 || z >= m.z1 } type AllChunksMask struct{}
3d2822b139183fb030861dc9a016fcd0f6e42d71
--- +++ @@ -25,7 +25,7 @@ Title: "Group Name", Description: "Name of a user-group that task-users should be assigned", }, - Pattern: "^[a-zA-Z0-9_-]+$", + Pattern: "^[a-zA-Z0-9_.-]+$", }, }, },
6901af9d7b87c6460438ea379ea532587ef02eac
--- +++ @@ -6,7 +6,8 @@ } // move moves the position. -// Given invalid position, move sets the position at the end of the buffer. +// Given a invalid position, move sets the position at the end of the buffer. +// Valid positions are in range [0, len(e.buf)]. func (e *basicEditor) move(to int) { switch { case to >= len(e.buf):
f38321fc81802bb3d67519cf249409275f09366a
--- +++ @@ -27,7 +27,7 @@ } func (slice MapInfos) Less(i, j int) bool { - return slice[i].Opened.Before(slice[j].Opened) + return slice[i].Opened.After(slice[j].Opened) } func (slice MapInfos) Swap(i, j int) {
391324115962dcfee0e12b114fc93abfbbaa0c39
--- +++ @@ -10,7 +10,7 @@ ) var ( - blobDeleteCommand = blobCommands.Command("delete", "Show contents of blobs").Alias("rm") + blobDeleteCommand = blobCommands.Command("delete", "Delete blobs by ID").Alias("rm") blobDeleteBlobIDs = blobDeleteCommand.Arg("blobIDs", "Blob IDs").Required().Strings() )
9940844a01dea7d51fb352ff438d1f5bf01dea2e
--- +++ @@ -16,3 +16,22 @@ err = resizeImage(nil, "./content/images/about/avatar.jpg", tmpfile.Name(), 100) assert.NoError(t, err) } + +func TestResizeImage_NoMozJPEG(t *testing.T) { + if conf.MozJPEGBin == "" { + return + } + + oldMozJPEGBin := conf.MozJPEGBin + defer func() { + conf.MozJPEGBin = oldMozJPEGBin + }() + conf.MozJPEGBin = "" + + tmpfile, err := ioutil.TempFile("", "resized_image") + assert.NoError(t, err) + defer os.Remove(tmpfile.Name()) + + err = resizeImage(nil, "./content/images/about/avatar.jpg", tmpfile.Name(), 100) + assert.NoError(t, err) +}
512d3e5cc82c945a6b038e238a5c13ca26e0ce7e
--- +++ @@ -25,7 +25,7 @@ "-c", "python hello.py", "-d", config.AppsDomain, ).Wait(CF_PUSH_TIMEOUT)).To(Exit(0)) - Expect(cf.Cf("start", appName).Wait(DEFAULT_TIMEOUT * 2)).To(Exit(0)) + Expect(cf.Cf("start", appName).Wait(CF_PUSH_TIMEOUT)).To(Exit(0)) }) })
25cfda55014438e50ae38237841d12a9bb112852
--- +++ @@ -1,4 +1,9 @@ package meta + +import ( + "encoding/binary" + "io/ioutil" +) // Application contains third party application specific data. // @@ -14,5 +19,11 @@ // parseApplication reads and parses the body of an Application metadata block. func (block *Block) parseApplication() error { - panic("not yet implemented.") + app := new(Application) + err := binary.Read(block.lr, binary.BigEndian, &app.ID) + if err != nil { + return err + } + app.Data, err = ioutil.ReadAll(block.lr) + return err }
7e5bd6ebe32743afd64b80ef26c5af7f5ae6b350
--- +++ @@ -31,7 +31,7 @@ } func (i immutableMap) Set(key string, value interface{}) ImmutableMap { - newMap := map[string]interface{}{} + newMap := make(map[string]interface{}, len(i.internalMap)) for existingKey, value := range i.internalMap { newMap[existingKey] = value }
b38424b6f1c08cbec2416918169f2b3323cb78c7
--- +++ @@ -1 +1,24 @@ package signature + +import ( + "bytes" + "encoding/base64" + "testing" +) + +const testTs = "1544544948" +const testQp = "abc=foo&def=bar" +const testBody = `{"a key":"some value"}` +const testSignature = "orb0adPhRCYND1WCAvPBr+qjm4STGtyvNDIDNBZ4Ir4=" + +func TestCalculateSignature(t *testing.T) { + v := NewValidator("other-secret", 2, nil, nil) + s, err := v.CalculateSignature(testTs, testQp, []byte(testBody)) + if err != nil { + t.Errorf("Error calculating signature: %s, expected: orb0adPhRCYND1WCAvPBr+qjm4STGtyvNDIDNBZ4Ir4=", s) + } + drs, _ := base64.StdEncoding.DecodeString(testSignature) + if bytes.Compare(s, drs) != 0 { + t.Errorf("Unexpected signature: %s, expected: orb0adPhRCYND1WCAvPBr+qjm4STGtyvNDIDNBZ4Ir4=", s) + } +}
fa93655d90d1518b04e7cfca7d7548d7d133a34e
--- +++ @@ -1,11 +1,13 @@ package metrics import ( + "fmt" + "net/http" "testing" "time" ) -func Test_RegisterServer(t *testing.T) { +func Test_Register_ProvidesBytes(t *testing.T) { metricsPort := 31111 @@ -15,7 +17,41 @@ cancel := make(chan bool) go metricsServer.Serve(cancel) - time.AfterFunc(time.Millisecond*500, func() { + defer func() { cancel <- true - }) + }() + + retries := 10 + + for i := 0; i < retries; i++ { + req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/metrics", metricsPort), nil) + + res, err := http.DefaultClient.Do(req) + + if err != nil { + t.Logf("cannot get metrics, or not ready: %s", err.Error()) + + time.Sleep(time.Millisecond * 100) + continue + } + + wantStatus := http.StatusOK + if res.StatusCode != wantStatus { + t.Errorf("metrics gave wrong status, want: %d, got: %d", wantStatus, res.StatusCode) + t.Fail() + return + } + + if res.Body == nil { + t.Errorf("metrics response should have a body") + t.Fail() + return + } + defer res.Body.Close() + + return + } + + t.Errorf("unable to get expected response from metrics server") + t.Fail() }
adc3c7f16051d51a58d96e32082aaeb051e3da20
--- +++ @@ -22,7 +22,7 @@ t.Error(err) } if reflect.TypeOf(k).String() != tst.want { - t.Errorf("Wrong key type returned. Got %s, wanted %s", reflect.TypeOf(k).String(), tst.want) + t.Errorf("Wrong key type returned. Got %T, wanted %s", k, tst.want) } } }
6cd28e734c926178868dd572a79524d174daa070
--- +++ @@ -1,6 +1,7 @@ package internal_test import ( + "sync/atomic" "testing" "time" @@ -9,40 +10,37 @@ ) func TestTimer_Restart(t *testing.T) { - var fired int + var fired int64 timer := internal.NewTimer(0, 20*time.Millisecond, func() { - fired++ + atomic.AddInt64(&fired, 1) }) time.Sleep(30 * time.Millisecond) timer.Stop() - assert.Equal(t, 1, fired) + assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) time.Sleep(50 * time.Millisecond) - assert.Equal(t, 1, fired) + assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) } func TestTimer_Sleep(t *testing.T) { - var fired int - timer := internal.NewTimer(20*time.Millisecond, 0, func() { - fired++ + var fired int64 + timer := internal.NewTimer(0, 20*time.Millisecond, func() { + atomic.AddInt64(&fired, 1) }) time.Sleep(30 * time.Millisecond) timer.Stop() - assert.Equal(t, 1, fired) + assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) } func TestTimer_Sleep_Stopped(t *testing.T) { - var fired int timer := internal.NewTimer(20*time.Millisecond, 0, func() { - fired++ + t.Error("stopped timer has fired") }) timer.Stop() time.Sleep(30 * time.Millisecond) - - assert.Equal(t, 0, fired) }
706797bd56e2cfab5c821b977cb2cd63f6a99587
--- +++ @@ -4,16 +4,15 @@ package container import ( - "launchpad.net/juju-core/environs" "launchpad.net/juju-core/environs/config" + "launchpad.net/juju-core/instance" "launchpad.net/juju-core/state" "launchpad.net/juju-core/state/api" ) // A Container represents a containerized virtual machine. type Container interface { - Name() string - Instance() environs.Instance + instance.Instance Create( series, nonce string, tools *state.Tools,
0fb1b9947b3720811a66f69e8f652a7257deea41
--- +++ @@ -1,7 +1,7 @@ package gamerules func init() { - if err := LoadGameRules("blocks.json", "items.json", "recipes.json", "furnace.json", "users.json", "groups.json"); err != nil { + if err := LoadGameRules("../blocks.json", "../items.json", "../recipes.json", "../furnace.json", "../users.json", "../groups.json"); err != nil { panic(err) } }
d360d15bd850318b354dd7784d7d78990c6d875d
--- +++ @@ -5,6 +5,9 @@ } func (directory *Directory) rebuildPointers(fs *FileSystem) { + for _, file := range directory.RegularFileList { + file.rebuildPointers(fs) + } for _, file := range directory.FileList { file.rebuildPointers(fs) } @@ -13,6 +16,10 @@ } } +func (file *RegularFile) rebuildPointers(fs *FileSystem) { + file.inode = fs.RegularInodeTable[file.InodeNumber] +} + func (file *File) rebuildPointers(fs *FileSystem) { file.inode = fs.InodeTable[file.InodeNumber] }
3d657054638f89a72d55016b16637de71193247a
--- +++ @@ -27,8 +27,9 @@ BeforeWrite: func([]byte) { c.written = true }, } - // Say to the client to "keep-alive" by default. + // Use default headers. c.ResponseWriter.Header().Set("Connection", "keep-alive") + c.ResponseWriter.Header().Set("Vary", "Accept-Encoding") c.Next() }
8d540120084298983ba1f7b3bd5578fd1817157b
--- +++ @@ -38,7 +38,7 @@ require.Nil(err, "The test data should be unmarshaled without error.") temp, _ := json.Marshal(expected) - fmt.Println(temp) + fmt.Println(string(temp)) json.Unmarshal(result, &actual) assert.Nil(err, "The result should be unmarshaled without error.")
291d0d7f303310c6731eba5fe754b760877d53aa
--- +++ @@ -8,13 +8,19 @@ serializers map[Serializer]filterable } +func Load(identifier string, out interface{}) (*Configuration, error) { + configuration := NewConfiguration(identifier) + err := configuration.Reload(out) + return configuration, err +} + func NewConfiguration(identifier string) *Configuration { return &Configuration{ identifier: identifier, } } -func (configuration *Configuration) Load(out *interface{}) error { +func (configuration *Configuration) Reload(out interface{}) error { loader, err := NewLoader(configuration.identifier) if err != nil { return err
376e150ab4de7365232b447e3333080047a3d17c
--- +++ @@ -3,6 +3,7 @@ import ( "fmt" "io" + "log" "os" ) @@ -10,6 +11,10 @@ controllerKey string ourPort string logOut io.Writer +} + +func init() { + log.SetFlags(log.Lshortfile | log.Lmicroseconds) } func loadConfigFromEnv() (*config, error) {
d0dbb5ec448c78d5902bca454dc5f62e9cdd6ccb
--- +++ @@ -1,10 +1,13 @@ package common +// NetString store the byte length of the data that follows, making it easier +// to unambiguously pass text and byte data between programs that could be +// sensitive to values that could be interpreted as delimiters or terminators +// (such as a null character). type NetString []byte -// implement encoding.TextMarshaller interface to treat []byte as raw string -// by other encoders/serializers (e.g. JSON) - +// MarshalText exists to implement encoding.TextMarshaller interface to +// treat []byte as raw string by other encoders/serializers (e.g. JSON) func (n NetString) MarshalText() ([]byte, error) { return n, nil }
6b1ce991282be24d4a112cd5a20a0ed476a834c1
--- +++ @@ -1,13 +1,19 @@ package stats type SingleStat struct { - TotalGB float32 - UsedGB float32 - AvailableGB float32 - UsagePercentage float32 + TotalGB float32 `json:"totalGB"` + UsedGB float32 `json:"usedGB"` + AvailableGB float32 `json:"availableGB"` + UsagePercentage float32 `json:"usagePercentage"` } type MultipleStat struct { - AverageUsagePercentage float32 - UsagePercentagePerCore []float32 + AverageUsagePercentage float32 `json:"averageUsagePercentage"` + UsagePercentagePerCore []float32 `json:"usagePercentagePerCore"` } + +type AllStat struct { + CPU MultipleStat `json:"cpu"` + RAM SingleStat `json:"ram"` + Disk SingleStat `json:"disk"` +}
8702a31d404b4ecaa096553133676dbc97686204
--- +++ @@ -2,11 +2,24 @@ import ( "fmt" + "io/ioutil" + "log" "net/http" "github.com/zenazn/goji" "github.com/zenazn/goji/web" ) + +// For now, the server stores a great deal of state in memory, although it will +// write as much as it can out to directories that will look reasonable to afl. + +var binary []byte + +type QueueMember []byte + +type NodeState struct { + Queue []QueueMember +} func put(c web.C, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Put a thing") @@ -16,8 +29,24 @@ fmt.Fprintf(w, "Got a thing") } -func main() { +func target(c web.C, w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/octet-stream") + w.Write(binary) +} + +func setupAndServe() { goji.Put("/state", put) goji.Get("/state", get) + goji.Get("/target", target) goji.Serve() } + +func main() { + var err error + binary, err = ioutil.ReadFile("target") + if err != nil { + log.Panicf("Couldn't load target") + } + + setupAndServe() +}
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4