_id stringlengths 40 40 | text stringlengths 81 2.19k | title stringclasses 1
value |
|---|---|---|
f7176693b242d5f3cd2c3638286145699db243f8 | ---
+++
@@ -4,7 +4,7 @@
// NullNewRelic returns a disabled New Relic appliaction.
func NullNewRelic() newrelic.Application {
- config := newrelic.NewConfig("smsprocessor", "")
+ config := newrelic.NewConfig("application", "")
config.Enabled = false
app, _ := newrelic.NewApplication(config)
| |
fae6ed236a31c146f8e5eb8dc09ef7b703a1389f | ---
+++
@@ -9,12 +9,19 @@
)
func handler(ctx *web.Context, path string) {
- input, err := ioutil.ReadFile("testdata/foo.md")
- if err != nil {
- ctx.NotFound("File Not Found\n" + err.Error())
+ if path == "" {
+ ctx.WriteString("foo")
+ return
+ } else {
+ input, err := ioutil.ReadFile(path)
+ if err != nil {
+ ctx.NotFound("File Not Found\n" + err.Error())
+ return
+ }
+ ctx.WriteString(string(blackfriday.MarkdownCommon(input)))
return
}
- ctx.WriteString(string(blackfriday.MarkdownCommon(input)))
+ ctx.Abort(500, "Server Error")
}
func main() { | |
41fb97bd457998a26e5e64a379c4b5d0d1c90f32 | ---
+++
@@ -9,7 +9,7 @@
Prefix string `json:"prefix,omitempty"`
Endpoint string `json:"endpoint"`
- DoNotUseTLS bool `json:"doNotUseTLS,omitempyy"`
+ DoNotUseTLS bool `json:"doNotUseTLS,omitempty"`
AccessKeyID string `json:"accessKeyID"`
SecretAccessKey string `json:"secretAccessKey" kopia:"sensitive"` | |
bbcee77b028aa3fbd9c54fe129efcbd61bbb6365 | ---
+++
@@ -21,8 +21,10 @@
"time"
)
+var initTime = time.Now()
+
func now() int64 {
- // time.Now() is monotonic:
+ // time.Since() returns monotonic timer difference (#875):
// https://golang.org/pkg/time/#hdr-Monotonic_Clocks
- return time.Now().UnixNano()
+ return int64(time.Since(initTime))
} | |
32daf238e1f3ceb63b590198648a81a6cd56048b | ---
+++
@@ -1,13 +1,28 @@
package test_helpers
-import "github.com/pivotal-cf-experimental/cf-mysql-quota-enforcer/database"
+import (
+ "os"
+
+ "github.com/pivotal-cf-experimental/cf-mysql-quota-enforcer/config"
+ "github.com/pivotal-cf-experimental/cf-mysql-quota-enforcer/database"
+)
func NewRootDatabaseConfig(dbName string) database.Config {
+ configPath := os.Getenv("CONFIG")
+ if configPath == "" {
+ panic("CONFIG path must be specified")
+ }
+
+ config, err := config.Load(configPath)
+ if err != nil {
+ panic(err.Error())
+ }
+
return database.Config{
- Host: "127.0.0.1",
- Port: 3306,
- User: "root",
- Password: "password",
+ Host: config.Host,
+ Port: config.Port,
+ User: config.User,
+ Password: config.Password,
DBName: dbName,
}
} | |
30f677249eef79da5e75cbfd35ed4df78c014e22 | ---
+++
@@ -6,16 +6,47 @@
type AnimeAiringDate struct {
Start string `json:"start"`
End string `json:"end"`
+
+ startHumanReadable string
+ endHumanReadable string
}
// StartDateHuman ...
func (airing *AnimeAiringDate) StartDateHuman() string {
- t, _ := time.Parse(time.RFC3339, airing.Start)
- return t.Format(time.RFC1123)
+ if airing.startHumanReadable == "" {
+ t, _ := time.Parse(time.RFC3339, airing.Start)
+ airing.startHumanReadable = t.Format(time.RFC1123)
+ }
+
+ return airing.startHumanReadable[:len("Thu, 25 May 2017")]
}
// EndDateHuman ...
func (airing *AnimeAiringDate) EndDateHuman() string {
- t, _ := time.Parse(time.RFC3339, airing.End)
- return t.Format(time.RFC1123)
+ if airing.endHumanReadable == "" {
+ t, _ := time.Parse(time.RFC3339, airing.End)
+ airing.endHumanReadable = t.Format(time.RFC1123)
+ }
+
+ return airing.endHumanReadable[:len("Thu, 25 May 2017")]
}
+
+// StartTimeHuman ...
+func (airing *AnimeAiringDate) StartTimeHuman() string {
+ if airing.startHumanReadable == "" {
+ t, _ := time.Parse(time.RFC3339, airing.Start)
+ airing.startHumanReadable = t.Format(time.RFC1123)
+ }
+
+ return airing.startHumanReadable[len("Thu, 25 May 2017 "):]
+}
+
+// EndTimeHuman ...
+func (airing *AnimeAiringDate) EndTimeHuman() string {
+ if airing.endHumanReadable == "" {
+ t, _ := time.Parse(time.RFC3339, airing.End)
+ airing.endHumanReadable = t.Format(time.RFC1123)
+ }
+
+ return airing.endHumanReadable[len("Thu, 25 May 2017 "):]
+} | |
bc7b920406a3f0a142fb57335463628fb9949929 | ---
+++
@@ -24,10 +24,6 @@
Message{"prefix", "command", []string{"one", "two", "three four"}},
":prefix command one two :three four"
},
- tcase {
- Message{Prefix: "prefix", Command: "command"},
- "asdf"
- },
};
for i, tc := range cases { | |
d2165be69c2be3b528f816c52db19f045940f249 | ---
+++
@@ -33,7 +33,7 @@
fmt.Fprintf(os.Stderr, "%s %s\r\n", bin, url)
var attr os.ProcAttr
- proc, err := os.StartProcess(command, []string{url}, &attr)
+ proc, err := os.StartProcess(bin, []string{bin, url}, &attr)
if err != nil {
return err
} | |
6ffdaa50bb51c6fe78e0634a316c468a29f31941 | ---
+++
@@ -1,7 +1,7 @@
package slug
import (
- "code.google.com/p/go.text/unicode/norm"
+ "golang.org/x/text/unicode/norm"
"regexp"
"strings"
"unicode" | |
424bc782bc1d5b5125a0e17aa319bd75132b6309 | ---
+++
@@ -14,8 +14,8 @@
// target OS and architecture, and writes the generated
// executable to the 'outDir' directory.
func goBuild(name string, version string, goos string, goarch string) {
- os.Setenv("goos", goos)
- os.Setenv("goarch", goarch)
+ os.Setenv("GOOS", goos)
+ os.Setenv("GOARCH", goarch)
out := distPath(name, version, goos, goarch)
cmd("go", "build", "-o", out, "-ldflags", "-X main.version="+version).Run()
@@ -30,7 +30,7 @@
// environment variable is set to
// "windows".
func exeSuffix() string {
- if os.Getenv("GOOS") == "windows" {
+ if goOS() == "windows" {
return ".exe"
}
return "" | |
d758ff96e486afc2359f5b958cc213d76c56f89c | ---
+++
@@ -6,10 +6,10 @@
// API key descriptions to use when requesting API keys from Ambassador Cloud.
const (
- KeyDescWorkstation = "laptop"
- KeyDescTrafficManager = "manager"
+ KeyDescWorkstation = "telepresence:workstation"
+ KeyDescTrafficManager = "telepresence:traffic-manager"
)
func KeyDescAgent(spec *manager.InterceptSpec) string {
- return "agent-" + spec.Mechanism
+ return "telepresence:agent-" + spec.Mechanism
} | |
ea12a4c8c3d5fb880ab81c6cd169aba63732b536 | ---
+++
@@ -10,10 +10,10 @@
g.Describe("Get", func() {
g.It("Errors when connection refused", func() {
- _, err := Get("http://localhost", map[string]string{
+ _, err := Get("http://localhost:8000", map[string]string{
"foo": "bar",
})
- g.Assert(err.Error()).Equal("Get http://localhost: dial tcp 127.0.0.1:80: connection refused")
+ g.Assert(err.Error()).Equal("Get http://localhost:8000: dial tcp 127.0.0.1:8000: connection refused")
})
})
} | |
0ae2689d0ae8593d6cba0d6dc7ee4c59ac3080cf | ---
+++
@@ -1,7 +1,6 @@
package events
import (
- "fmt"
"strconv"
"strings"
"time"
@@ -48,12 +47,9 @@
}
func (e *Event) DisplayTags() string {
+ // required as used in template
if e == nil {
return ""
}
- // if e.Tags == nil {
- // return ""
- // }
- fmt.Println(e)
return strings.Join(e.Tags, " ")
} | |
b1f78a296047401f7794bef4ac229c5f6174517f | ---
+++
@@ -3,6 +3,7 @@
import (
"github.com/elves/elvish/cli"
"github.com/elves/elvish/cli/addons/histwalk"
+ "github.com/elves/elvish/cli/el"
"github.com/elves/elvish/cli/histutil"
"github.com/elves/elvish/eval"
)
@@ -14,13 +15,15 @@
eval.Ns{
"binding": bindingVar,
}.AddGoFns("<edit:history>", map[string]interface{}{
- "start": func() {
- buf := app.CodeArea.CopyState().CodeBuffer
- walker := fuser.Walker(buf.Content[:buf.Dot])
- histwalk.Start(app, histwalk.Config{Binding: binding, Walker: walker})
- },
- "prev": func() error { return histwalk.Prev(app) },
- "next": func() error { return histwalk.Next(app) },
+ "start": func() { histWalkStart(app, fuser, binding) },
+ "up": func() error { return histwalk.Prev(app) },
+ "down": func() error { return histwalk.Next(app) },
"close": func() { histwalk.Close(app) },
}))
}
+
+func histWalkStart(app *cli.App, fuser *histutil.Fuser, binding el.Handler) {
+ buf := app.CodeArea.CopyState().CodeBuffer
+ walker := fuser.Walker(buf.Content[:buf.Dot])
+ histwalk.Start(app, histwalk.Config{Binding: binding, Walker: walker})
+} | |
d3dd3e6baf8432622a69f31650f8119edf157fca | ---
+++
@@ -17,7 +17,8 @@
txContext db.SafeTxContext,
) Store {
return &safeStoreImpl{
- impl: newStore(builder, executor, logger),
+ impl: newStore(builder, executor, logger),
+ txContext: txContext,
}
}
| |
a099b5569c226e498ab33e17a116be207557497d | ---
+++
@@ -1,9 +1,48 @@
//go:build !linux && !freebsd
package tuntap
+
+import (
+ "net"
+)
const flagTruncated = 0
func createInterface(ifPattern string, kind DevKind) (*Interface, error) {
panic("tuntap: Not implemented on this platform")
}
+
+// IPv6SLAAC enables/disables stateless address auto-configuration (SLAAC) for the interface.
+func (t *Interface) IPv6SLAAC(ctrl bool) error {
+ panic("tuntap: Not implemented on this platform")
+}
+
+// IPv6Forwarding enables/disables ipv6 forwarding for the interface.
+func (t *Interface) IPv6Forwarding(ctrl bool) error {
+ panic("tuntap: Not implemented on this platform")
+}
+
+// IPv6 enables/disable ipv6 for the interface.
+func (t *Interface) IPv6(ctrl bool) error {
+ panic("tuntap: Not implemented on this platform")
+}
+
+// AddAddress adds an IP address to the tunnel interface.
+func (t *Interface) AddAddress(ip net.IP, subnet *net.IPNet) error {
+ panic("tuntap: Not implemented on this platform")
+}
+
+// SetMTU sets the tunnel interface MTU size.
+func (t *Interface) SetMTU(mtu int) error {
+ panic("tuntap: Not implemented on this platform")
+}
+
+// Up sets the tunnel interface to the UP state.
+func (t *Interface) Up() error {
+ panic("tuntap: Not implemented on this platform")
+}
+
+// GetAddrList returns the IP addresses (as bytes) associated with the interface.
+func (t *Interface) GetAddrList() ([][]byte, error) {
+ panic("tuntap: Not implemented on this platform")
+} | |
e8f2bfa311a7353358a9d4ee326880526d4942fc | ---
+++
@@ -6,8 +6,25 @@
)
// Gnupg keyrings files
-var gPubringFile string = filepath.Join(os.Getenv("HOME"), ".gnupg", "pubring.gpg")
-var gSecringFile string = filepath.Join(os.Getenv("HOME"), ".gnupg", "secring.gpg")
+var gPubringFile string = func() string {
+ envPubring := os.Getenv("GNUPG_PUBRING_PATH")
+
+ if envPubring != "" {
+ return envPubring
+ }
+
+ return filepath.Join(os.Getenv("HOME"), ".gnupg", "pubring.gpg")
+}()
+
+var gSecringFile string = func() string {
+ envSecring := os.Getenv("GNUPG_SECRING_PATH")
+
+ if envSecring != "" {
+ return envSecring
+ }
+
+ return filepath.Join(os.Getenv("HOME"), ".gnupg", "secring.gpg")
+}()
// Gnupg trousseau master gpg key id
var gMasterGpgId string = os.Getenv(ENV_MASTER_GPG_ID_KEY) | |
27288b1b7adb8e07ab942b8c6e1f9c0df43fa4ab | ---
+++
@@ -3,18 +3,12 @@
package isatty
-import (
- "syscall"
- "unsafe"
-)
-
-const ioctlReadTermios = syscall.TIOCGETA
+import "golang.org/x/sys/unix"
// IsTerminal return true if the file descriptor is terminal.
func IsTerminal(fd uintptr) bool {
- var termios syscall.Termios
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
- return err == 0
+ _, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA)
+ return err == nil
}
// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 | |
95431df442eed97dcc6fd45b71bd14ab378346d2 | ---
+++
@@ -1,41 +1,29 @@
package main
import (
+ "crypto/rand"
"encoding/hex"
"flag"
"log"
- "github.com/aarbt/bitcoin-base58"
"github.com/aarbt/hdkeys"
)
-var extendedKey = flag.String("extended_key", "", "")
+var seedHex = flag.String("seed", "", "hex encoded random seed between 16 and 64 bytes.")
func main() {
flag.Parse()
- extended, err := hex.DecodeString(*extendedKey)
+ seed, err := hex.DecodeString(*seedHex)
if err != nil {
log.Fatal(err)
}
- if len(extended) != 64 {
- log.Fatalf("Extended key has wrong length %d (must be 64).",
- len(extended))
+ if len(seed) == 0 {
+ seed = make([]byte, 32)
+ rand.Read(seed)
}
- prvStr := "5KR1vxbnkT49RLW3iRGXVSCLz3C3caXfWpgifnAfrhmfN6NK2Qo"
- prvKey, prvPrefix, err := base58.BitcoinCheckDecode(prvStr)
- if err != nil || prvPrefix != base58.BitcoinPrivateKeyPrefix {
- log.Fatal(err, prvPrefix)
- }
- log.Printf("Private: %x\n", prvKey)
- pubKey, pubPrefix, err := base58.BitcoinCheckDecode("1KREnf3cDoi6oam5H75sBbUEXtrXQSWRw3")
- if err != nil || pubPrefix != base58.BitcoinPublicKeyHashPrefix {
- log.Fatal(err, pubPrefix)
- }
- log.Printf("Public hash: %x\n", pubKey)
-
- key := hdkeys.NewPrivateKeyFromRawData(extended)
+ key := hdkeys.NewMasterKey(seed)
log.Println(key.SerializeEncode())
log.Println(key.PublicKeyHashEncode()) | |
67c05a5d7585e9bed136e9b09a3bffe6a69f48fb | ---
+++
@@ -3,31 +3,39 @@
import (
"fmt"
- "log"
"testing"
)
-func Test(*testing.T) {
- d := &OuiDb{}
- err := d.Load("oui.txt")
+var db OuiDb
+func init() {
+ db = OuiDb{}
+ err := db.Load("oui.txt")
if err != nil {
- log.Fatal("Error %v", err)
+ panic(err.Error())
}
+}
- address, _ := ParseMAC("60:03:08:a0:ec:a6")
- block := d.Lookup(address)
+func lookup(t *testing.T, mac, org string) {
+ address, err := ParseMAC(mac)
+ if err != nil {
+ t.Fatalf("parse: %s", mac)
+ }
+ o := db.Lookup(address).Organization
+ if o != org {
+ t.Fatalf("lookup: input %s, expect %s, got %s", mac, org, o)
+ }
+ fmt.Printf(" %s => %s\n", mac, o)
+}
- fmt.Println("bla %v", block)
+func TestLookup1(t *testing.T) {
+ lookup(t, "60:03:08:a0:ec:a6", "Apple, Inc.")
+}
- address, _ = ParseMAC("00:25:9c:42:c2:62")
- block = d.Lookup(address)
+func TestLookup2(t *testing.T) {
+ lookup(t, "00:25:9c:42:c2:62", "Cisco-Linksys, LLC")
+}
- fmt.Println("Bla %v", block)
-
- address, _ = ParseMAC("00:16:e0:3d:f4:4c")
- block = d.Lookup(address)
-
- fmt.Println("Bla %v", block)
-
+func TestLookup3(t *testing.T) {
+ lookup(t, "00:16:e0:3d:f4:4c", "3Com Ltd")
} | |
8a21b128d4deb874c05eb81ebbc1265175ad69ba | ---
+++
@@ -14,6 +14,11 @@
if backingFs == "xfs" {
msg += " Reformat the filesystem with ftype=1 to enable d_type support."
}
+
+ if backingFs == "extfs" {
+ msg += " Reformat the filesystem (or use tune2fs) with -O filetype flag to enable d_type support."
+ }
+
msg += " Backing filesystems without d_type support are not supported."
return graphdriver.NotSupportedError(msg) | |
6d58e94977400501c09fc1c7ceaa29bc524583ef | ---
+++
@@ -11,3 +11,12 @@
func (m Move) IsCapture() bool {
return m.CapturedChecker != nil
}
+
+// CapturedPos returns position of captured checker for the move
+// if it caused capture or point outside of the board otherwise.
+func (m Move) CapturedPos() Point {
+ if !m.IsCapture() {
+ return Point{-1, -1}
+ }
+ return m.CapturedChecker.Position()
+} | |
8b3863b00d216214994608ebb88d0cf6bbdaa290 | ---
+++
@@ -19,7 +19,9 @@
return err
}
- w.WriteHeader(statusCode)
+ if statusCode != http.StatusOK {
+ w.WriteHeader(statusCode)
+ }
encoder := json.NewEncoder(w)
encoder.SetEscapeHTML(true) | |
c3023b6ea764579035f6953ae18c39f0abdd9e6d | ---
+++
@@ -2,15 +2,12 @@
import (
"fmt"
- "syscall"
-
"github.com/buildkite/agent/v3/logger"
+ "golang.org/x/sys/windows"
)
func VersionDump(_ logger.Logger) (string, error) {
- dll := syscall.MustLoadDLL("kernel32.dll")
- p := dll.MustFindProc("GetVersion")
- v, _, _ := p.Call()
+ info := windows.RtlGetVersion()
- return fmt.Sprintf("Windows version %d.%d (Build %d)\n", byte(v), uint8(v>>8), uint16(v>>16)), nil
+ return fmt.Sprintf("Windows version %d.%d (Build %d)\n", info.MajorVersion, info.MinorVersion, info.BuildNumber), nil
} | |
a0cb02c4ea2aee903bad6b7762887e1830337e77 | ---
+++
@@ -4,8 +4,10 @@
// The uuid package generates and inspects UUIDs.
//
-// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services.
+// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security
+// Services.
//
-// This package is a partial wrapper around the github.com/google/uuid package. This package
-// represents a UUID as []byte while github.com/google/uuid represents a UUID as [16]byte.
+// This package is a partial wrapper around the github.com/google/uuid package.
+// This package represents a UUID as []byte while github.com/google/uuid
+// represents a UUID as [16]byte.
package uuid | |
8d077c0d0a97cbd3e9c2d00c638898a2c2819236 | ---
+++
@@ -12,12 +12,10 @@
func main() {
var port int
- var host string
flag.IntVar(&port, "port", 2489, "TCP port number")
- flag.StringVar(&host, "host", "localhost", "Remote hostname")
flag.Parse()
- l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
+ l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
panic(err)
} | |
8f37aed8328cd444c3ae770f7b57773180bfc7d8 | ---
+++
@@ -1,7 +1,5 @@
package form
type Options struct {
- Fields []string
- Values map[string]interface{}
- Choices map[string]interface{}
+ Fields []string
} | |
81cbba68d09edf8c1ab70f439f1254f238e1ab16 | ---
+++
@@ -16,7 +16,7 @@
func BenchmarkEncryption(b *testing.B) {
s, _ := NewAESSessionEncoder([]byte(SessionKey), base64.StdEncoding)
- config.SessionKey = []byte(SessionKey)
+ config.SessionKey = SessionKey
for i := 0; i < b.N; i++ {
s.encryptStickyCookie(Host, Port)
@@ -25,7 +25,7 @@
func BenchmarkDecryption(b *testing.B) {
s, _ := NewAESSessionEncoder([]byte(SessionKey), base64.StdEncoding)
- config.SessionKey = []byte(SessionKey)
+ config.SessionKey = SessionKey
for i := 0; i < b.N; i++ {
s.decryptStickyCookie(Session) | |
46ce29dc34b300f1b704cfcb921d109bdff7ffc4 | ---
+++
@@ -19,6 +19,10 @@
req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
req.Header.Add("X-Viber-Auth-Token", v.AppKey)
req.Close = true
+
+ if v.client == nil {
+ v.client = &http.Client{}
+ }
resp, err := v.client.Do(req)
if err != nil { | |
79d4ef67b694ce875b11649cc504e32b22dab098 | ---
+++
@@ -1,6 +1,12 @@
package grid
-import "fmt"
+import (
+ "fmt"
+ "io"
+ "log"
+ "mime"
+ "os"
+)
// ExportService handles communication with the Export related
// methods of the GRiD API.
@@ -29,3 +35,22 @@
resp, err := s.client.Do(req, exportDetail)
return exportDetail.ExportFiles, resp, err
}
+
+func (s *ExportService) DownloadByPk(pk int) (*Response, error) {
+ url := fmt.Sprintf("export/download/file/%v/", pk)
+
+ req, err := s.client.NewRequest("GET", url, nil)
+
+ var foo interface{}
+ resp, err := s.client.Do(req, foo)
+
+ cd := resp.Header.Get("Content-Disposition")
+ _, params, err := mime.ParseMediaType(cd)
+ fname := params["filename"]
+ file, err := os.Create(fname)
+ defer file.Close()
+
+ numBytes, err := io.Copy(file, resp.Body)
+ log.Println("Downloaded", numBytes, "bytes to", fname)
+ return resp, err
+} | |
ecdcc574d48390061b2c5a82bb714ad238d70653 | ---
+++
@@ -31,6 +31,8 @@
return multistep.ActionHalt
}
+ state.Put("machine", "")
+
return multistep.ActionContinue
}
| |
58759737673c35a11a89730e80a711ee87bf19e6 | ---
+++
@@ -17,5 +17,8 @@
Debugf(level uint8, format string, v ...interface{})
Debugln(level uint8, v ...interface{})
Logger
+}
+
+type DebugLogLevelSetter interface {
SetLevel(maxLevel int16)
} | |
d04023572e47e5c18fa549fe7f7de301e8470c63 | ---
+++
@@ -1,11 +1,19 @@
package core
import (
+ "fmt"
+
"github.com/akutz/gofig"
+
+ "github.com/emccode/rexray/util"
)
func init() {
initDrivers()
+
+ gofig.SetGlobalConfigPath(util.EtcDirPath())
+ gofig.SetUserConfigPath(fmt.Sprintf("%s/.rexray", util.HomeDir()))
+
gofig.Register(globalRegistration())
gofig.Register(driverRegistration())
} | |
e05259e391d6d62afe5f166c9d05c5933b9b86d8 | ---
+++
@@ -43,5 +43,9 @@
d.last[k] = v
}
}
+
+ if len(changes) == 0 {
+ return nil
+ }
return d.Notifier.Notify(changes)
} | |
b9c9f6ee854f9dde42b8f8f170a114497582bac7 | ---
+++
@@ -2,7 +2,7 @@
// Used in getmarkethistory
type Trade struct {
- OrderUuid string `json:"OrderUuid"`
+ OrderUuid int64 `json:"Id"`
Timestamp jTime `json:"TimeStamp"`
Quantity float64 `json:"Quantity"`
Price float64 `json:"Price"` | |
9cf66af6fdf5ccd6312014071e7eb6f631812a99 | ---
+++
@@ -13,17 +13,10 @@
}
func (api *API) UserAuthenticate(username, email, password string) (errs []error, body string) {
-
- type UserAuthenticateData struct {
- Username string `json:"username,omitempty"`
- Email string `json:"email,omitempty"`
- Password string `json:"password"`
- }
-
- data := UserAuthenticateData{
- Username: username,
- Email: email,
- Password: password,
+ data := map[string]string{
+ "username": username,
+ "email": email,
+ "password": password,
}
_, body, errs = api.request.
Post(api.endpoint + "/v1/users/authenticate"). | |
4f658348d5d5c920968b77c24b7d402f52b7f87c | ---
+++
@@ -18,7 +18,7 @@
// SendTextMessage uses Twilio to send a text message.
// See http://www.twilio.com/docs/api/rest/sending-sms for more information.
-func (twilio *Twilio) SendTextMessage(from, to, body, statusCallback, applicationSid string) (string, error) {
+func (twilio *Twilio) SendSMS(from, to, body, statusCallback, applicationSid string) (string, error) {
twilioUrl := twilio.BaseUrl + "/Accounts/" + twilio.AccountSid + "/SMS/Messages.json" // needs a better variable name
formValues := url.Values{} | |
7a63dce37a0afd42bd9efc9687c55feeaef04130 | ---
+++
@@ -22,14 +22,14 @@
NumGameEventTypes = int(sentinel)
)
-type MoveDirection int
+type MoveDirection byte
const (
- North MoveDirection = iota
+ None MoveDirection = iota
+ North MoveDirection = 1 << (iota - 1)
East
South
West
- None
)
type PlayerMoveEvent struct { | |
74788afc2b0f03051b0fd92db0c0d1664dffd28c | ---
+++
@@ -3,17 +3,17 @@
import "github.com/BurntSushi/toml"
type Config struct {
- App App `toml:"application"`
- Deps Deps `toml:"dependencies"`
+ App ConfigApp `toml:"application"`
+ Deps ConfigDeps `toml:"dependencies"`
}
-type App struct {
+type ConfigApp struct {
Name string
Version string
Authors []string
}
-type Deps map[string]string
+type ConfigDeps map[string]string
func loadConfig() (*Config, error) {
var c Config | |
246e8bcca34cb2f0b0504cc1eee466cdcac2135c | ---
+++
@@ -9,6 +9,9 @@
localtests "github.com/practicum/sandbox/testing"
)
+var sampleTxtFilepath string = localtests.
+ DataAssetFullPath("january.txt", reflectionToy{})
+
// reflectionToy is a dummy type created in the preprocess package as a trick to
// retrieve the package name. http://stackoverflow.com/a/25263604/10278
type reflectionToy struct{}
@@ -17,14 +20,28 @@
datapath := localtests.DataAssetFullPath("january.txt", reflectionToy{})
iterator := NewContentIterator(datapath)
- line, err := iterator()
+ _, err := iterator()
for err == nil {
- line, err = iterator()
- fmt.Println(line)
+ _, err = iterator()
}
if err != io.EOF {
t.Error(err)
}
}
+
+func ExampleNewContentIterator() {
+ iterator := NewContentIterator(sampleTxtFilepath)
+
+ line, err := iterator()
+
+ for err == nil {
+ fmt.Println(line)
+ line, err = iterator()
+ }
+
+ if err != io.EOF {
+ panic(fmt.Sprintf("Error while iterating over %s.", sampleTxtFilepath))
+ }
+} | |
eccc2f678e62451c5515ebc136d6bc0da78cd969 | ---
+++
@@ -10,7 +10,7 @@
// runs a loop to keep the client alive until it is no longer active.
func main() {
// Request a server with the specified details.
- server, err := ircutil.CreateServer("irc.rizon.net", 6667, true, "");
+ server, err := ircutil.CreateServer("irc.rizon.net", 6697, true, "");
if err != nil {
fmt.Println(err.Error())
return | |
2c5dddc7f190e9edddd2296182b88e0212fa8069 | ---
+++
@@ -4,11 +4,14 @@
func Chunk(data []byte, size int) [][]byte {
+ count := len(data) - size
var chunks [][]byte
- for i:=0; i<len(data); i=i+size {
+ for i:=0; i<count; i=i+size {
chunks = append(chunks, data[i:i+size])
}
+
+ chunks = append(chunks, data[count*size:])
return chunks
} | |
3546ca06a8e2311bf5f0b017da79aabf04894901 | ---
+++
@@ -2,17 +2,30 @@
import (
_ "fmt"
+ "io/ioutil"
"log"
"github.com/libgit2/git2go"
)
+var clone string = "./test"
+var repo string = "https://github.com/rollbrettler/go-playground.git"
+
func main() {
- var cloneOptions git.CloneOptions
- cloneOptions.Bare = true
+ var cloneOptions git.CloneOptions
+ cloneOptions.Bare = true
- if _, err := git.Clone("https://github.com/rollbrettler/go-playground.git", "./test", &cloneOptions); err != nil {
+ _, err := ioutil.ReadDir(clone)
+ if err != nil {
log.Println(err)
+
+ _, err := git.Clone(repo, clone, &cloneOptions)
+ if err != nil {
+ log.Println(err)
+ return
+ }
+ return
}
+ log.Println("Folder already cloned")
} | |
1ff58bfae05ef4b367a73a952e8edb218373f195 | ---
+++
@@ -10,7 +10,7 @@
func main() {
if len(os.Args) < 3 {
- fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY COMMAND [ARGS…]")
+ fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY|FILE COMMAND [ARGS…]")
os.Exit(1)
}
@@ -20,7 +20,7 @@
go func() {
for _ = range ch {
- log.Println("Changes in directory, restarting")
+ log.Println("Changes detected, restarting")
cmd.Process.Signal(os.Interrupt)
}
}() | |
95cfaeb5aa27c690ecf06c595fdfb056c1d86ad6 | ---
+++
@@ -6,11 +6,11 @@
)
func TestNewURL(t *testing.T) {
- url, err := NewURL("https://github.com/motemen/pusheen-explorer")
- Expect(url.String()).To(Equal("https://github.com/motemen/pusheen-explorer"))
+ httpsUrl, err := NewURL("https://github.com/motemen/pusheen-explorer")
+ Expect(httpsUrl.String()).To(Equal("https://github.com/motemen/pusheen-explorer"))
Expect(err).To(BeNil())
- url, err = NewURL("git@github.com:motemen/pusheen-explorer.git")
- Expect(url.Host).To(Equal("ssh://git@github.com/motemen/pusheen-explorer.git"))
+ sshUrl, err := NewURL("git@github.com:motemen/pusheen-explorer.git")
+ Expect(sshUrl.String()).To(Equal("ssh://git@github.com/motemen/pusheen-explorer.git"))
Expect(err).To(BeNil())
} | |
c14e4298246c74f064e60d0911b16792acf1caba | ---
+++
@@ -1,75 +1,23 @@
package main
import (
+ "bytes"
"fmt"
- "io"
"os"
"os/exec"
+ "github.com/johnny-morrice/pipeline"
)
func main() {
config := exec.Command("configbrot", os.Args[1:]...)
render := exec.Command("renderbrot")
- confoutp, conferrp, conferr := pipes(config)
- if conferr != nil {
- fatal(conferr)
+ pl := pipeline.New(&bytes.Buffer{}, os.Stdout, os.Stderr)
+ pl.Chain(config, render)
+ err := pl.Exec()
+ if err != nil {
+ fatal(err)
}
-
- rendoutp, renderrp, renderr := pipes(render)
- if renderr != nil {
- fatal(renderr)
- }
-
- render.Stdin = confoutp
-
- tasks := []*exec.Cmd{config, render}
- for _, t := range tasks {
- err := t.Start()
- if err != nil {
- fatal(err)
- }
- }
-
- _, outerr := io.Copy(os.Stdout, rendoutp)
- if outerr != nil {
- fatal(outerr)
- }
-
- cerrcount, confcpyerr := io.Copy(os.Stderr, conferrp)
- if confcpyerr != nil {
- fatal(confcpyerr)
- }
- // If we read an error from configbrot, don't read an error from renderbrot
- if cerrcount == 0 {
- _, rndcpyerr := io.Copy(os.Stderr, renderrp)
- if rndcpyerr != nil {
- fatal(rndcpyerr)
- }
- }
-
- // Order of tasks is important!
- for _, t := range tasks {
- err := t.Wait()
- if err != nil {
- fmt.Fprintf(os.Stderr, "%v: %v\n", t.Path, err)
- os.Exit(2) // Different exit code for subprocess failure
- }
- }
-}
-
-func pipes(task *exec.Cmd) (io.ReadCloser, io.ReadCloser, error) {
- outp, outerr := task.StdoutPipe()
- if outerr != nil {
- return nil, nil, outerr
- }
-
- errp, errerr := task.StderrPipe()
- if errerr != nil {
- return nil, nil, errerr
- }
-
- return outp, errp, nil
}
func fatal(err error) { | |
b4039d9645e7c9479ab84427030da6e01acb7ed1 | ---
+++
@@ -1,15 +1,23 @@
package main
import (
- "fmt"
+ "html/template"
"net/http"
"os"
)
func hello(resp http.ResponseWriter, req *http.Request) {
- fmt.Fprintln(resp, "<html><head><title>How about them apples?!</title></head><body><h1>")
- fmt.Fprintln(resp, "Hello world!")
- fmt.Fprintln(resp, "</h1></body></html>")
+ content, err := template.New("").Parse("<html><head><title>{{.title}}</title></head><body><ul>{{range .envs}}<li>{{.}}</li>{{end}}</ul></body></html>")
+ if err != nil {
+ panic(err)
+ }
+
+ ctx := map[string]interface{} {
+ "title": "How about them apples?!",
+ "envs": os.Environ(),
+ }
+
+ content.Execute(resp, ctx)
}
func main() { | |
b1c64b7458fff743e194812e8bec6ba90cf30512 | ---
+++
@@ -17,7 +17,7 @@
)
func init() {
- flag.BoolVar(&Production, "production", false, "run the server in production environment")
+ flag.BoolVar(&Production, "production", Production, "run the server in production environment")
flag.StringVar(&Address, "address", Address, "the address to listen and serving on")
}
| |
14496a7fed1e9ef222ec25a39574eb03e05e6c55 | ---
+++
@@ -2,6 +2,7 @@
package launcher
import (
+ "fmt"
"github.com/kardianos/osext"
"github.com/luisiturrios/gowin"
@@ -17,23 +18,24 @@
)
func CreateLaunchFile(autoLaunch bool) {
- var err error
+ var startupCommand string
+
+ lanternPath, err := osext.Executable()
+ if err != nil {
+ log.Errorf("Could not get Lantern directory path: %q", err)
+ return
+ }
if autoLaunch {
- lanternPath, err := osext.Executable()
- if err != nil {
- log.Errorf("Could not get Lantern directory path: %q", err)
- return
- }
- err = gowin.WriteStringReg("HKCU", runDir, "Lantern", fmt.Sprintf(`"%s" -startup`, lanternPath))
- if err != nil {
- log.Errorf("Error inserting Lantern auto-start registry key: %q", err)
- }
+ // Start Lantern normally.
+ startupCommand = fmt.Sprintf(`"%s" -startup`, lanternPath)
} else {
- // Just remove proxy settings and quit.
- err = gowin.WriteStringReg("HKCU", runDir, "Lantern", fmt.Sprintf(`"%s" -clear-proxy-settings`, lanternPath))
- if err != nil {
- log.Errorf("Error removing Lantern auto-start registry key: %q", err)
- }
+ // Just clear stored proxy settings and quit.
+ startupCommand = fmt.Sprintf(`"%s" -clear-proxy-settings`, lanternPath)
+ }
+
+ err = gowin.WriteStringReg("HKCU", runDir, "Lantern", startupCommand)
+ if err != nil {
+ log.Errorf("Error setting Lantern auto-start registry key: %q", err)
}
} | |
7baa466a8cad03c01018d4bfb8366205604ce14f | ---
+++
@@ -8,7 +8,7 @@
)
func main() {
- key := os.Args[3]
+ key := os.Args[2]
client, err := controller.NewClient("", os.Getenv("CONTROLLER_AUTH_KEY"))
if err != nil { | |
e2bd4261796d40a3bb47ce84cb30c72e328c483d | ---
+++
@@ -7,13 +7,12 @@
)
func main() {
- word := os.Args[1]
if len(os.Args) != 2 {
fmt.Println("Exactly one argument is required")
os.Exit(1)
}
- s := strings.Split(word, "")
- generatePermutations(len(word)-1, s)
+ word := os.Args[1]
+ generatePermutations(len(word)-1, strings.Split(word, ""))
}
func generatePermutations(n int, a []string) {
@@ -22,7 +21,7 @@
} else {
for i := 0; i <= n; i++ {
generatePermutations(n-1, a)
- if n%2 == 0 {
+ if n % 2 == 0 {
a[i], a[n] = a[n], a[i]
} else {
a[0], a[n] = a[n], a[0] | |
0ef7b331fbab892b121fa51f7ddd82dbcd040e3f | ---
+++
@@ -1,15 +1,18 @@
package interpreter
import (
- "fmt"
+ // "fmt"
+ "CodeCity/server/interpreter/object"
"testing"
)
const onePlusOne = `{"type":"Program","start":0,"end":5,"body":[{"type":"ExpressionStatement","start":0,"end":5,"expression":{"type":"BinaryExpression","start":0,"end":5,"left":{"type":"Literal","start":0,"end":1,"value":1,"raw":"1"},"operator":"+","right":{"type":"Literal","start":4,"end":5,"value":1,"raw":"1"}}}]}`
-func TestInterpreter(t *testing.T) {
+func TestInterpreterOnePlusOne(t *testing.T) {
i := NewInterpreter(onePlusOne)
i.Run()
v := i.Value()
- fmt.Printf("Result: %v (type %T)\n", v, v)
+ if v != object.Number(2) {
+ t.Errorf("1 + 1 == %v (expected 2)", v)
+ }
} | |
3a6634b2456fc0cd151e25cc90b3b6865bbb5332 | ---
+++
@@ -7,15 +7,14 @@
)
func ExampleRegister() {
- pdf := gofpdf.New("", "", "", "")
+ pdf := gofpdf.New("L", "mm", "A4", "")
pdf.SetFont("Helvetica", "", 12)
pdf.SetFillColor(200, 200, 220)
pdf.AddPage()
url := "https://github.com/jung-kurt/gofpdf/raw/master/image/logo_gofpdf.jpg?raw=true"
httpimg.Register(pdf, url, "")
- pdf.Image(url, 100, 100, 20, 20, false, "", 0, "")
-
+ pdf.Image(url, 15, 15, 267, 0, false, "", 0, "")
fileStr := example.Filename("contrib_httpimg_Register")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr) | |
d61adc880ea85c1adc4585afb2aac40ab1602f28 | ---
+++
@@ -6,14 +6,13 @@
"path/filepath"
)
-// Get name of lock file, which is derived from the monitoring event name
-func getLockfileName() string {
- return filepath.Join(os.TempDir(), monitoringEvent, monitoringEvent+".lock")
-}
-
// Create a new lock file
func createLock() (lockfile.Lockfile, error) {
- filename := getLockfileName()
- os.Mkdir(filepath.Dir(filename), 0700)
+ filename := filepath.Join(os.TempDir(), "periodicnoise", monitoringEvent, monitoringEvent+".lock")
+
+ if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
+ return lockfile.Lockfile(""), err
+ }
+
return lockfile.New(filename)
} | |
569042e6dfe2dcf338cb5d584e4d9b7c170af669 | ---
+++
@@ -23,7 +23,7 @@
Package = "github.com/containerd/containerd"
// Version holds the complete version number. Filled in at linking time.
- Version = "1.6.0-beta.3+unknown"
+ Version = "1.6.0-beta.4+unknown"
// Revision is filled with the VCS (e.g. git) revision being used to build
// the program at linking time. | |
94a623fa08b669a41452fa441ad8da2d93baa58b | ---
+++
@@ -2,24 +2,29 @@
import "fmt"
-type HTTP struct {
+type HTTP interface {
+ error
+ Code() int
+}
+
+type http struct {
*primitive
code int
}
-func (h HTTP) Code() int {
+func (h http) Code() int {
return h.code
}
func NewHTTP(cause error, code int, message string) error {
- return &HTTP{
+ return &http{
primitive: newPrimitive(cause, message),
code: code,
}
}
func HTTPf(cause error, code int, format string, args ...interface{}) error {
- return &HTTP{
+ return &http{
primitive: newPrimitive(cause, fmt.Sprintf(format, args...)),
code: code,
} | |
fdddd4a2bf3ee13eebd6699a54a0a86814fae116 | ---
+++
@@ -4,6 +4,7 @@
import (
"io"
+ "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
@@ -11,6 +12,7 @@
// DownloaderAPI is the interface type for s3manager.Downloader.
type DownloaderAPI interface {
Download(io.WriterAt, *s3.GetObjectInput, ...func(*s3manager.Downloader)) (int64, error)
+ DownloadWithContext(aws.Context, io.WriterAt, *s3.GetObjectInput, ...func(*s3manager.Downloader)) (int64, error)
}
var _ DownloaderAPI = (*s3manager.Downloader)(nil)
@@ -18,6 +20,7 @@
// UploaderAPI is the interface type for s3manager.Uploader.
type UploaderAPI interface {
Upload(*s3manager.UploadInput, ...func(*s3manager.Uploader)) (*s3manager.UploadOutput, error)
+ UploadWithContext(aws.Context, *s3manager.UploadInput, ...func(*s3manager.Uploader)) (*s3manager.UploadOutput, error)
}
var _ UploaderAPI = (*s3manager.Uploader)(nil) | |
e4be389a3f47b64e3877a42e0124db41c98856ea | ---
+++
@@ -1,6 +1,7 @@
package money
import (
+ "fmt"
"math"
"strings"
)
@@ -29,3 +30,12 @@
return strings.Join(r, separator)
}
+
+func splitValue(val float64) (integer, fractional string) {
+ i, f := math.Modf(val)
+
+ integer = fmt.Sprintf("%.0f", i)
+ fractional = fmt.Sprintf("%.2f", f)[2:]
+
+ return
+} | |
aae7d0beac11cc3f583d9ec194708c7957d53896 | ---
+++
@@ -11,9 +11,9 @@
antibody() {
case "$1" in
bundle|update)
+ tmp_dir=$(mktemp -d)
while read -u 3 bundle; do
- touch /tmp/antibody-log && chmod 777 /tmp/antibody-log
- source "$bundle" 2&> /tmp/antibody-log
+ source "$bundle" 2&> ${temp_dir}/antibody-log
done 3< <( $ANTIBODY_BINARY $@ )
;;
*) | |
9152646855d907c37c3dade6efba0bd7cea18dd2 | ---
+++
@@ -1,6 +1,11 @@
package option
-import "net/http"
+import (
+ "net/http"
+ "time"
+
+ "github.com/itchio/wharf/timeout"
+)
type EOSSettings struct {
HTTPClient *http.Client
@@ -8,8 +13,13 @@
func DefaultSettings() *EOSSettings {
return &EOSSettings{
- HTTPClient: http.DefaultClient,
+ HTTPClient: defaultHTTPClient(),
}
+}
+
+func defaultHTTPClient() *http.Client {
+ client := timeout.NewClient(time.Second*time.Duration(5), time.Second*time.Duration(5))
+ return client
}
////////////////////////////////////// | |
500a68483fdd9a330ac58d8c8726d187e9e9b578 | ---
+++
@@ -7,13 +7,13 @@
)
var (
- sequenses = regexp.MustCompile(`(?:[^~\\]|\\.)*`)
+ sequenses = regexp.MustCompile(`(?:[^/\\]|\\.)*`)
branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)
func newMatcher(expr string) (m *regexp.Regexp, err error) {
expr = strings.Replace(expr, `\,`, `\\,`, -1)
- expr = strings.Replace(expr, `\~`, `\\~`, -1)
+ expr = strings.Replace(expr, `\/`, `\\/`, -1)
expr, err = strconv.Unquote(`"` + expr + `"`)
if err != nil {
return nil, err
@@ -24,7 +24,7 @@
bls := branches.FindAllString(sls[si], -1)
for bi := 0; bi < len(bls); bi++ {
bls[bi] = strings.Replace(bls[bi], `\,`, `,`, -1)
- bls[bi] = strings.Replace(bls[bi], `\~`, `~`, -1)
+ bls[bi] = strings.Replace(bls[bi], `\/`, `/`, -1)
bls[bi] = regexp.QuoteMeta(bls[bi])
}
sls[si] = "(" + strings.Join(bls, "|") + ")" | |
41bed60213c81ccb550342a1efc24fc48d3587dc | ---
+++
@@ -1,6 +1,8 @@
package main
import (
+ "bufio"
+ "io"
"log"
"os"
"path"
@@ -10,14 +12,33 @@
if len(os.Args) != 3 {
log.Fatalf("Usage: %s input-file output-file", path.Base(os.Args[0]))
}
+
i, err := os.Open(os.Args[1])
if err != nil {
- log.Fatalf("Cannot open %q for reading", os.Args[1])
+ log.Fatalf("Cannot open %q for reading: %v", os.Args[1], err)
}
defer i.Close()
+ r := bufio.NewReader(i)
+
o, err := os.Create(os.Args[2])
if err != nil {
- log.Fatalf("Cannot create new file %q", os.Args[2])
+ log.Fatalf("Cannot create new file %q: %v", os.Args[2], err)
}
defer o.Close()
+ w := bufio.NewWriter(o)
+
+ for {
+ line, err := r.ReadString('\n')
+ if len(line) > 0 {
+ if _, werr := w.WriteString(line); werr != nil {
+ log.Fatalf("Error writing to file: %v", werr)
+ }
+ }
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ log.Fatalf("Error whilst reading file: %v", err)
+ }
+ }
} | |
e2a18a2283a462746b649c25bdcc349b8ac51aab | ---
+++
@@ -25,3 +25,18 @@
h.setFocus(true)
}
}
+
+type serviceTaskScreenEventHandler struct {
+ baseEventHandler
+}
+
+func (h *serviceTaskScreenEventHandler) handle(event termbox.Event) {
+
+ switch event.Key {
+ case termbox.KeyEsc:
+ h.dry.ShowServices()
+ }
+
+ h.baseEventHandler.handle(event)
+
+} | |
cb5e4254572805c3e70a342ce3ad84124ea438fe | ---
+++
@@ -9,6 +9,7 @@
var (
callIPTablesFile = "/proc/sys/net/bridge/bridge-nf-call-iptables"
+ forward = "/proc/sys/net/ipv4/ip_forward"
)
func Configure() error {
@@ -16,5 +17,8 @@
if err := ioutil.WriteFile(callIPTablesFile, []byte("1"), 0640); err != nil {
logrus.Warnf("failed to write value 1 at %s: %v", callIPTablesFile, err)
}
+ if err := ioutil.WriteFile(forward, []byte("1"), 0640); err != nil {
+ logrus.Warnf("failed to write value 1 at %s: %v", forward, err)
+ }
return nil
} | |
1e0b0e6dbfa427afa1772b724f4418dd76313ac1 | ---
+++
@@ -20,8 +20,7 @@
// Validate ensures that at least one sub-validator validates.
func (v AnyOf) Validate(value interface{}) (interface{}, error) {
for _, validator := range v {
- var err error
- if value, err = validator.Validate(value); err == nil {
+ if value, err := validator.Validate(value); err == nil {
return value, nil
}
} | |
ac78c8d8ca36008e9a8afbd4775eb450dcdb8b2b | ---
+++
@@ -50,5 +50,12 @@
os.Exit(1)
}
- printList()
+ switch args[1] {
+ default:
+ printUsage()
+ os.Exit(1)
+ case "list":
+ printList()
+ return
+ }
} | |
92506424bd2a53d3140129ee7eba1cda2b74220d | ---
+++
@@ -16,7 +16,7 @@
go func() {
defer out.Close()
- out.Write([]byte(input))
+ out.Write([]byte(input + "\n"))
}()
return CaptureSTDOUT(reader, func() { block() }) | |
a265d3c2f5eccd509c52e8c25048c8762161e82b | ---
+++
@@ -26,9 +26,9 @@
// Apply default options first
for _, opt := range defaultOptions {
- if err := opt(sm); err != nil {
+ if optErr := opt(sm); optErr != nil {
// Panic if default option could not be applied
- panic(err)
+ panic(optErr)
}
}
| |
cb7937baed0a0057305e347315b6ba9cdf55d8d4 | ---
+++
@@ -6,6 +6,8 @@
"github.com/gorilla/mux"
"log"
"net/http"
+ // neccessary to catch sql.ErrNoRows
+ "database/sql"
"github.com/alex1sz/shotcharter-go/models"
)
@@ -14,8 +16,17 @@
func GetGameByID(w http.ResponseWriter, req *http.Request) {
log.Println("GET request /games/:id")
params := mux.Vars(req)
+ var game models.Game
game, err := models.FindGameByID(params["id"])
+ if err != nil {
+ if err == sql.ErrNoRows {
+ utils.RespondWithAppError(w, err, "An unexpected error has occurred", 404)
+ } else {
+ utils.RespondWithAppError(w, err, "An unexpected error has occurred", 500)
+ }
+ return
+ }
jsonResp, err := json.Marshal(game)
if err != nil { | |
5eb90cd6f2d564fae0ba13901e3c0fe1d0ffccf2 | ---
+++
@@ -1,33 +1,56 @@
package dom
+// ElementNodeType - constant for element node
+const ElementNodeType = "DOM/ELEMENT_NODE"
+
+// TextNodeType - constant for element node
+const TextNodeType = "DOM/TEXT_NODE"
+
// Node - Node interface
-type Node interface{}
+type Node interface {
+ getChildren() []*Node
+ getNodeType() string
+}
-// TextNode - a basic dom node
+// TextNode - a dom text node
type TextNode struct {
- children string
+ text string
+}
+
+func (t *TextNode) getChildren() []*Node {
+ return []*Node{}
+}
+func (t *TextNode) getNodeType() string {
+ return TextNodeType
}
// ElementNode - an html element consists of tagName and attributes
type ElementNode struct {
- children []Node
+ children []*Node
tagName string
attributes AttrMap
+}
+
+func (e *ElementNode) getChildren() []*Node {
+ return e.children
+}
+func (e *ElementNode) getNodeType() string {
+ return ElementNodeType
}
// AttrMap - an attribute map
type AttrMap map[string]string
-// Text - Create a text dom node
-func Text(data string) Node {
- return TextNode{
- children: data,
+// CreateTextNode - Create a text dom node
+func CreateTextNode(data string) Node {
+ return &TextNode{
+ text: data,
}
}
-// Elem - Create an Element dom node
-func Elem(tagName string, attr AttrMap, children []Node) ElementNode {
- return ElementNode{
+// CreateElementNode - Create an Element dom node
+func CreateElementNode(tagName string, attr AttrMap, children []*Node) Node {
+ return &ElementNode{
children: children,
tagName: tagName,
attributes: attr, | |
eb35552fb363ccc70c0473a29e40161ead848e37 | ---
+++
@@ -9,3 +9,10 @@
func NewDaemonProxy() DaemonProxy {
return DaemonProxy{}
}
+
+// Command returns a cli command handler if one exists
+func (p DaemonProxy) Command(name string) func(...string) error {
+ return map[string]func(...string) error{
+ "daemon": p.CmdDaemon,
+ }[name]
+} | |
348b34b8072000c614740c1981c6900033321c65 | ---
+++
@@ -12,9 +12,9 @@
func (c *Chain) Handle(ctx context.Context, conn Conn, msg Message) context.Context {
chainCtx := ctx
for i := range *c {
- chainCtx = (*c)[i].Handle(chainCtx, conn, msg)
- if chainCtx == nil {
- chainCtx = ctx
+ rCtx := (*c)[i].Handle(chainCtx, conn, msg)
+ if rCtx != nil {
+ chainCtx = rCtx
}
select {
case <-chainCtx.Done(): | |
759cbd58e1770a7e3c176e9e1727805640d9247e | ---
+++
@@ -35,9 +35,8 @@
// TaskFixture creates a fixture of tagreplication.Task.
func TaskFixture() *Task {
- id := randutil.Text(4)
- tag := fmt.Sprintf("prime/labrat-%s", id)
+ tag := core.TagFixture()
d := core.DigestFixture()
- dest := fmt.Sprintf("build-index-%s", id)
+ dest := fmt.Sprintf("build-index-%s", randutil.Hex(8))
return NewTask(tag, d, core.DigestListFixture(3), dest)
} | |
e2a811a0566a0bbaf4a1fdc5e1d59fae2a1b746e | ---
+++
@@ -1,6 +1,7 @@
package fetch
import (
+ "os"
"testing"
log "github.com/Sirupsen/logrus"
@@ -11,7 +12,11 @@
func TestFetchPublicKeys(t *testing.T) {
log.SetLevel(log.DebugLevel)
- keys, err := GitHubKeys("devopsfinland", GithubFetchParams{PublicMembersOnly: true})
+ keys, err := GitHubKeys("devopsfinland", GithubFetchParams{
+ // Use token if it's available to avoid hitting API rate limits with the tests...
+ Token: os.Getenv("GITHUB_TOKEN"),
+ PublicMembersOnly: true,
+ })
assert.NoError(t, err, "Fetch GitHub keys returned error")
assert.True(t, len(keys) > 0, "should return SSH at least one public key") | |
68f22a40f30279005d260ba38590e32a0eff01be | ---
+++
@@ -31,17 +31,5 @@
}
// Get the SELinux context of the rootDir.
- rootContext, err := selinux.Getfilecon(kl.getRootDir())
- if err != nil {
- return "", err
- }
-
- // There is a libcontainer bug where the null byte is not stripped from
- // the result of reading some selinux xattrs; strip it.
- //
- // TODO: remove when https://github.com/docker/libcontainer/issues/499
- // is fixed
- rootContext = rootContext[:len(rootContext)-1]
-
- return rootContext, nil
+ return selinux.Getfilecon(kl.getRootDir())
} | |
6bcf463b019461454fb2164b725ad343b42bc386 | ---
+++
@@ -23,7 +23,7 @@
const (
defaultAddress = `\\.\pipe\containerd-containerd-test`
- testImage = "docker.io/microsoft/nanoserver:latest"
+ testImage = "docker.io/microsoft/nanoserver@sha256:8f78a4a7da4464973a5cd239732626141aec97e69ba3e4023357628630bc1ee2"
)
var ( | |
d3f84d8b2f9b3aa392b83d029787a2a452a0ca65 | ---
+++
@@ -1,6 +1,8 @@
package main
import (
+ "bytes"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -26,3 +28,16 @@
c2.setup()
assert.Equal(t, logrus.WarnLevel, logger.Level)
}
+
+func TestLogrusWriter(t *testing.T) {
+ var buf bytes.Buffer
+ logger := logrus.New()
+ logger.Out = &buf
+ subject := &LogrusWriter{Dest: logger, Severity: logrus.InfoLevel}
+ subject.Setup()
+
+ fmt.Fprintln(subject, "Hello world!")
+ s := buf.String()
+ assert.Contains(t, s, "level=info")
+ assert.Contains(t, s, `msg="Hello world!\n"`)
+} | |
cf440052ef862fdc929cac8f757963aea47c3ee4 | ---
+++
@@ -23,10 +23,12 @@
"go.chromium.org/luci/common/errors"
)
-func setSysProcAttr(_ *exec.Cmd) {}
+func setSysProcAttr(cmd *exec.Cmd) {
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+}
func (s *Subprocess) terminate() error {
- if err := s.cmd.Process.Signal(syscall.SIGTERM); err != nil {
+ if err := syscall.Kill(-s.cmd.Process.Pid, syscall.SIGTERM); err != nil {
return errors.Annotate(err, "send SIGTERM").Err()
}
return nil | |
23e9f8fae329f0527ed22317abb85a5859546417 | ---
+++
@@ -1,14 +1,31 @@
package axis
+
+// Positionable is the interface for positionable
+// items on a axis
+type Positionable interface {
+ Current() Position
+ Since(Position) Distance
+}
+
+// Sleepable is the interface for sleepable provider
+type Sleepable interface {
+ Sleep(Distance)
+}
+
+// Trigger is the interface that wraps methods
+// to define triggers
+type Trigger interface {
+ After(Distance) <-chan Position
+ AfterFunc(Distance, func(Position)) Watcher
+ AfterChan(Distance, chan Position) Watcher
+}
// Provider is the interface that wraps methods
// to manipulate position
type Provider interface {
- Current() Position
- Sleep(Distance)
- After(Distance) <-chan Position
- AfterFunc(Distance, func(Position)) Watcher
- AfterChan(Distance, chan Position) Watcher
- Since(Position) Distance
+ Positionable
+ Sleepable
+ Trigger
}
// UpdatableProvider is the interface which allow | |
0a60f16853d284840a996c695ca621519ad32724 | ---
+++
@@ -8,7 +8,19 @@
type Context struct {
*fetchbot.Context
- Cache Cache
+ C Cache
+}
+
+func (c *Context) Cache() Cache {
+ return c.C
+}
+
+func (c *Context) Queue() *fetchbot.Queue {
+ return c.Q
+}
+
+func (c *Context) URL() *url.URL {
+ return c.Cmd.URL()
}
func (c *Context) SourceURL() *url.URL { | |
f798c3e07c1e0764cc2e61b18ba1350a64a3138b | ---
+++
@@ -2,10 +2,10 @@
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
-// +build go1
+// +build go1.1
// +build !go1.6
-package gb
+package internal
const (
showGOTRACEBACKBanner = false | |
289317f7082e35f2103d70449a3dd4db6861a5a1 | ---
+++
@@ -11,6 +11,9 @@
)
func main() {
+
+ // # Get stack name from --name
+ // # Get stack name from directory if not passed
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
@@ -27,9 +30,37 @@
log.Fatal(err)
}
- for name, _ := range project.NetworkConfigs {
- s := fmt.Sprintf("Network: %s", name)
- fmt.Println(s)
+ // Networks
+
+ if project.NetworkConfigs == nil || len(project.NetworkConfigs) == 0 {
+ // if no network create default
+ fmt.Println("No networks!")
+ } else {
+ for name, config := range project.NetworkConfigs {
+ // # if network external check if exists
+ if config.External.External {
+ fmt.Println(fmt.Sprintf("Network: %s (external)", name))
+ // handle external name
+ if config.External.Name != "" {
+ fmt.Println(fmt.Sprintf("Network: %s (external: %s)", name, config.External.Name))
+ }
+ } else {
+ // # else create network
+ // # if no driver set default
+ if config.Driver != "" {
+ fmt.Println(fmt.Sprintf("Network: %s (driver: %s)", name, config.Driver))
+ } else {
+ fmt.Println(fmt.Sprintf("Network: %s (driver: default)", name))
+ }
+ }
+ }
}
+ // # Volumes
+
+ // # Services
+ // # Dependencies?
+
+ // # Timeouts / Errors
+
} | |
a48e7020f845bc5681c9c8588d120f0d99b310e9 | ---
+++
@@ -9,7 +9,10 @@
// RandomReward generates a random reward with rates given
func RandomReward(rates []models.RewardRate) int64 {
- sum := sumOfWeights(rates)
+ var sum int64
+ for i := range rates {
+ sum += rates[i].Weight
+ }
if sum < 1 {
panic("sum of reward rates weight should be greater than 0")
}
@@ -26,13 +29,6 @@
return randInt64(rate.Min, rate.Max)
}
-func sumOfWeights(rates []models.RewardRate) (sum int64) {
- for i := range rates {
- sum += rates[i].Weight
- }
- return
-}
-
func randInt64(min, max int64) int64 {
// panic if rand.Int returns error, fail fast here
n, _ := rand.Int(rand.Reader, big.NewInt(max-min)) | |
a3c6388aa272447266d978ab905fa665746fd527 | ---
+++
@@ -5,21 +5,18 @@
"time"
)
-type Response interface {
- MakeATimestamp()
-}
+type Timestamp int64
type baseResponse struct {
Command string
- Timestamp int64
+ Timestamp Timestamp
}
-func (r *baseResponse) MakeATimestamp() {
- r.Timestamp = time.Now().UnixNano() / 1e6
+func (t *Timestamp) MarshalJSON() ([]byte, error) {
+ return json.Marshal(time.Now().UnixNano() / 1e6)
}
-func Send(r Response, sender func([]byte)) error {
- r.MakeATimestamp()
+func Send(r interface{}, sender func([]byte)) error {
serialized, err := json.Marshal(r)
if err == nil {
sender(serialized) | |
844fa0fb81ef01a35d54c2229e359f9afa0bf35c | ---
+++
@@ -29,8 +29,11 @@
jot.Printf("message dispatch: message %s with cmd %s and args %v", m.Text, cmd, args)
fn, ok := commands[cmd]
if !ok {
- q = oq
- return
+ fn, ok = commands["help"]
+ if !ok {
+ q = oq
+ return
+ }
}
q, response = fn(oq, m.Channel, m.User, args) | |
3b047c3778265bc35448c42bc01e729d20bd69b7 | ---
+++
@@ -27,7 +27,7 @@
e.Use(middleware.CORS())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
- AllowOrigins: []string{"http://localhost:8100/"},
+ AllowOrigins: []string{"*", "http://192.168.43.108:8100/"},
}))
e.POST("/qoutes/", CreateQoute) | |
5d66fa46e201e4989964815561a47ca484df33a2 | ---
+++
@@ -6,11 +6,13 @@
log "github.com/sirupsen/logrus"
)
-func Watch(directory string, deployments chan<- string) {
+func Watch(directory string, batchInterval int, deployments chan<- string) {
done := make(chan bool)
defer close(done)
- watcher, err := NewBatcher(5 * time.Second)
+ log.Infof("Starting watcher with a batch interval of %ds", batchInterval)
+
+ watcher, err := NewBatcher(time.Duration(batchInterval) * time.Second)
if err != nil {
log.Fatal(err)
} | |
a719d3f1e2734708f6b57d645d9fdc53187e88d9 | ---
+++
@@ -12,9 +12,14 @@
var buf bytes.Buffer
for _, c := range []byte(s) {
if isEncodable(c) {
- buf.WriteByte('%')
- buf.WriteByte(hex[c>>4])
- buf.WriteByte(hex[c&15])
+ if c == '+' {
+ // replace plus-encoding with percent-encoding
+ buf.WriteString("%2520")
+ } else {
+ buf.WriteByte('%')
+ buf.WriteByte(hex[c>>4])
+ buf.WriteByte(hex[c&15])
+ }
} else {
buf.WriteByte(c)
} | |
34a8a447d17052cbcfafae7bdb4d9594011495e6 | ---
+++
@@ -12,7 +12,7 @@
keys *Keys
}
-func NewBot(config string) (*TBot, error) {
+func New(config string) (*TBot, error) {
keys, err := ReadConfig(config)
if err != nil {
return nil, err
@@ -29,7 +29,7 @@
NextTweet() string
}
-func (t *TBot) RunBot(creator TweetCreator) {
+func (t *TBot) Run(creator TweetCreator) {
var previousTweet string
for { | |
f9784b202625b37312b0f10a869b73bf049e71f6 | ---
+++
@@ -8,7 +8,7 @@
func (api *API) TokenAuth() gin.HandlerFunc {
return func(c *gin.Context) {
- if api.token != c.Request.Header.Get("token") {
+ if api.token != c.Request.Header.Get("Authorization") {
c.AbortWithStatus(http.StatusUnauthorized)
return
} | |
c2851c6b6ec2be65e9c09b31d64915049b62311a | ---
+++
@@ -6,7 +6,10 @@
"io/ioutil"
"os"
"github.com/robertkrimen/otto"
+ "github.com/robertkrimen/otto/underscore"
)
+
+var underscoreFlag *bool = flag.Bool("underscore", true, "Load underscore into the runtime environment")
func main() {
flag.Parse()
@@ -26,6 +29,9 @@
os.Exit(64)
}
}
+ if !*underscoreFlag {
+ underscore.Disable()
+ }
Otto := otto.New()
_, err = Otto.Run(string(script))
if err != nil { | |
2abbb29dd1512f32a7f85347c3c9554afaced493 | ---
+++
@@ -17,7 +17,7 @@
func (self *UnitsResource) Index(u *url.URL, h http.Header, req interface{}) (int, http.Header, *UnitsResponse, error) {
statusCode := http.StatusOK
- response := &UnitResponse{}
+ response := &UnitsResponse{}
units, err := self.Fleet.Units()
if err != nil { | |
ab410f4943fca756da19a3eb86ad94d999ae2167 | ---
+++
@@ -11,13 +11,7 @@
var _ = Describe("io helpers", func() {
It("will never overflow the pipe", func() {
- characters := make([]string, 0, 75000)
- for i := 0; i < 75000; i++ {
- characters = append(characters, "z")
- }
-
- str := strings.Join(characters, "")
-
+ str := strings.Repeat("z", 75000)
output := CaptureOutput(func() {
os.Stdout.Write([]byte(str))
}) | |
227dac8b50c8817e3a85497e76ad405d5e453d5a | ---
+++
@@ -18,37 +18,37 @@
flag.Parse()
processes, err := ps.Processes()
- if err != nil {
- panic(err)
- }
-
- err = checks.ProcessCheck(processes, requiredProcesses)
- if err != nil {
- log.Fatal(err)
+ if err == nil {
+ err = checks.ProcessCheck(processes, requiredProcesses)
+ if err != nil {
+ log.Print(err)
+ }
+ } else {
+ log.Print(err)
}
err = checks.ContainerCheck(*gardenAddr)
if err != nil {
- log.Fatal(err)
+ log.Print(err)
}
err = checks.ConsulDnsCheck(bbsConsulHost)
if err != nil {
- log.Fatal(err)
+ log.Print(err)
}
err = checks.FairShareCpuCheck()
if err != nil {
- log.Fatal(err)
+ log.Print(err)
}
err = checks.FirewallCheck()
if err != nil {
- log.Fatal(err)
+ log.Print(err)
}
err = checks.NtpCheck()
if err != nil {
- log.Fatal(err)
+ log.Print(err)
}
} | |
95a3a717ed8f5ed245147a1b214218a8ad904098 | ---
+++
@@ -1,8 +1,8 @@
package id
import (
+ "crypto/rand"
"fmt"
- "crypto/rand"
)
// GenerateRandomString creates a random string of characters of the given
@@ -24,3 +24,15 @@
func GenSafeUniqueSlug(slug string) string {
return fmt.Sprintf("%s-%s", slug, GenerateRandomString("0123456789bcdfghjklmnpqrstvwxyz", 4))
}
+
+// Generate62RandomString creates a random string with the given length
+// consisting of characters in [A-Za-z0-9].
+func Generate62RandomString(l int) string {
+ return GenerateRandomString("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", l)
+}
+
+// GenerateFriendlyRandomString creates a random string of characters with the
+// given length consisting of characters in [a-z0-9].
+func GenerateFriendlyRandomString(l int) string {
+ return GenerateRandomString("0123456789abcdefghijklmnopqrstuvwxyz", l)
+} | |
283874315567f7a541ad7d7898fb0b93f205663f | ---
+++
@@ -1,17 +1,14 @@
package netlink
-/*
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <linux/if.h>
-#include <linux/if_tun.h>
-
-#define IFREQ_SIZE sizeof(struct ifreq)
-*/
-import "C"
+// ideally golang.org/x/sys/unix would define IfReq but it only has
+// IFNAMSIZ, hence this minimalistic implementation
+const (
+ SizeOfIfReq = 40
+ IFNAMSIZ = 16
+)
type ifReq struct {
- Name [C.IFNAMSIZ]byte
+ Name [IFNAMSIZ]byte
Flags uint16
- pad [C.IFREQ_SIZE - C.IFNAMSIZ - 2]byte
+ pad [SizeOfIfReq - IFNAMSIZ - 2]byte
} | |
c1411e0ad5199695c808c647e066bfc1c7650a7f | ---
+++
@@ -1,4 +1,8 @@
package test
+
+type E struct {
+ E1 string
+}
type T struct {
F1 string `json:"F1"`
@@ -7,4 +11,5 @@
F4 string `json:"-,"`
F5 string `json:","`
F6 string `json:""`
+ E `json:"e"`
} | |
4ba47bc9e4e1b7b0a0c8d656a18c73f623f74010 | ---
+++
@@ -1,14 +1,12 @@
package main
import (
- "fmt"
"html/template"
- "log"
"net/http"
- "os"
"sort"
"github.com/eknkc/amber"
+ "google.golang.org/appengine"
)
//template map
@@ -27,20 +25,7 @@
http.HandleFunc("/", animeHandler)
http.HandleFunc("/static/", staticHandler)
- //Sets url and port
- bind := fmt.Sprintf("%s:%s", "127.0.0.1", "422")
- if os.Getenv("OPENSHIFT_GO_IP") != "" &&
- os.Getenv("OPENSHIFT_GO_PORT") != "" {
- bind = fmt.Sprintf("%s:%s", os.Getenv("OPENSHIFT_GO_IP"),
- os.Getenv("OPENSHIFT_GO_PORT"))
- }
-
- //Listen and sert to port
- log.Printf("Web server listening on %s", bind)
- err := http.ListenAndServe(bind, nil)
- if err != nil {
- log.Fatal("webServer() => ListenAndServer() error:\t", err)
- }
+ appengine.Main()
}
// /anime path handler | |
69aaaa10381d9487ff3cf9990fca3780e895e450 | ---
+++
@@ -9,8 +9,8 @@
var _ = Describe("Consul DNS checks", func() {
It("returns an error when host is not known", func() {
- err := ConsulDnsCheck("host-non-existing.")
- Expect(err).To(MatchError("Failed to resolve consul host host-non-existing.\nlookup host-non-existing.: getaddrinfow: No such host is known."))
+ err := ConsulDnsCheck("non-existent.example.com.")
+ Expect(err.Error()).To(ContainSubstring("Failed to resolve consul host non-existent.example.com."))
})
It("does not return an error when host is known", func() { | |
8d834e22da1d8159ec61c9ee6a9a6542ca30fbd3 | ---
+++
@@ -28,7 +28,7 @@
return
}
- if iType == PNG {
+ if iType == PNG && !ctx.Options.Webp {
decoded, _, err := image.Decode(bytes.NewReader(*img_buff))
if err != nil {
warning("Can't decode PNG image, reason - %s", err) |
Subsets and Splits
Match Query to Corpus Titles
Matches queries with corpus entries based on their row numbers, providing a simple pairing of text data without revealing deeper insights or patterns.