_id stringlengths 40 40 | text stringlengths 81 2.19k | title stringclasses 1
value |
|---|---|---|
d71c56ec372cca2ad812250854efcc68da0e718e | ---
+++
@@ -33,8 +33,16 @@
return handle(us.context)
}
+func (us *UnlockedState) String() string {
+ return "UnlockedState"
+}
+
func (ls *LockedState) Handle() (TurnstileState, error) {
return handle(ls.context)
+}
+
+func (ls *LockedState) String() string {
+ return "LockedState"
}
func handle(context TurnstileContext) (TurnstileState, error) {
@@ -48,6 +56,10 @@
}
}
+func (tc *TurnstileContext) setAction(action Action) {
+ tc.action = action
+}
+
func main() {
- fmt.Printf("Turnstile\n")
+ context := &TurnstileContext{}
} | |
2252004e8c6c3fa3bdeb3dfdbda671f4f4e6a7b7 | ---
+++
@@ -20,7 +20,8 @@
// time duration.
func TimeoutAfter(t time.Duration, fn func() error) error {
c := make(chan error, 1)
- go func() { defer close(c); c <- fn() }()
+ defer close(c)
+ go func() { c <- fn() }()
select {
case err := <-c:
return err | |
b4571a99d363aa2239451e516b21a18d6b83603b | ---
+++
@@ -20,9 +20,10 @@
{"Title1", "Body 1"},
{"Title2", "Body 2"},
}
- ctx.WriteString(mustache.RenderFile("hello.mustache",
- map[string]interface{}{
- "entries": data}))
+ html := mustache.RenderFile("hello.mustache",
+ map[string]interface{}{
+ "entries": data})
+ ctx.WriteString(html)
return
} else {
input, err := ioutil.ReadFile(path) | |
994e900c0b4eb6e91236067a6ce97520251fb764 | ---
+++
@@ -2,8 +2,13 @@
import (
"flag"
+ "fmt"
"log"
+ "os"
)
+
+// build number set on during linking
+var minversion string
type AppConfig struct {
verbose bool
@@ -12,6 +17,7 @@
interval int
user string
host string
+ version bool
}
func HandleUserOptions() AppConfig {
@@ -24,8 +30,14 @@
flag.IntVar(&config.interval, "interval", 1, "Sampling interval [min]")
flag.StringVar(&config.user, "user", "postgres", "Database user name")
flag.StringVar(&config.host, "host", "localhost:5432", "Database host")
+ flag.BoolVar(&config.version, "version", false, "Print version")
flag.Parse()
+
+ if config.version {
+ fmt.Printf("Build: %s\n", minversion)
+ os.Exit(0)
+ }
if config.newRelicKey == "" ||
config.database == "" { | |
ca6d60bfdcd711f0ea913b4ea37f979890c4ccd9 | ---
+++
@@ -19,21 +19,28 @@
if err != nil {
log.Fatal(err)
}
+
go func(c net.Conn) {
buf := make([]byte, 4096)
for {
+ fmt.Println("here")
n, err := c.Read(buf)
if err != nil || n == 0 {
c.Close()
break
}
+
b := buf[:n]
s := string(b)
s = strings.TrimSpace(s)
- fmt.Print(s)
- fmt.Println("------")
- n, err = c.Write(b)
+
+ if s == "hello" {
+ c.Write([]byte("Hello user\n"))
+ } else {
+ n, err = c.Write(b)
+ }
+
if err != nil {
c.Close()
break | |
19b02871d27a36a8d1c4aa22cf9257f5593cd4c3 | ---
+++
@@ -13,8 +13,9 @@
*/
func dbConnection() {
db.Init()
- db.CreateTables()
- db.RunFixtures()
+ //db.CreateTables()
+ //db.RunFixtures()
+ //db.Migrate()
}
/** | |
298b727472f2de7563955a6e8414ce2502ecca2c | ---
+++
@@ -19,18 +19,18 @@
"root": {
{`[C*].*\n`, Comment, nil},
{`#.*\n`, CommentPreproc, nil},
- {`[\t ]*!.*\n`, Comment, nil},
+ {` {0,4}!.*\n`, Comment, nil},
{`(.{5})`, NameLabel, Push("cont-char")},
{`.*\n`, Using("Fortran"), nil},
},
"cont-char": {
- {` `, Text, Push("code")},
- {`0`, Comment, Push("code")},
+ {` `, TextWhitespace, Push("code")},
{`.`, GenericStrong, Push("code")},
},
"code": {
- {`(.{66})(.*)(\n)`, ByGroups(Using("Fortran"), Comment, Text), Push("root")},
- {`.*\n`, Using("Fortran"), Push("root")},
+ {`(.{66})(.*)(\n)`, ByGroups(Using("Fortran"), Comment, TextWhitespace), Push("root")},
+ {`(.*)(!.*)(\n)`, ByGroups(Using("Fortran"), Comment, TextWhitespace), Push("root")},
+ {`(.*)(\n)`, ByGroups(Using("Fortran"), TextWhitespace), Push("root")},
Default(Push("root")),
},
} | |
c3901ea2ea5913c711f65f1f3b7fa9d9b5b356e5 | ---
+++
@@ -5,10 +5,10 @@
func (input PacketChannel) PayloadOnly() <-chan []byte {
output := make(chan []byte)
go func() {
+ defer close(output)
for packet := range input {
output <- packet.Payload
}
- close(output)
}()
return output
} | |
9712d06b3674f5e5cd5aeef6a4be1610a393f65f | ---
+++
@@ -1,4 +1,8 @@
package hugolib
+
+import (
+ "html/template"
+)
const Version = "0.13-DEV"
@@ -12,7 +16,7 @@
// HugoInfo contains information about the current Hugo environment
type HugoInfo struct {
Version string
- Generator string
+ Generator template.HTML
CommitHash string
BuildDate string
} | |
768abf16229eb021af66f57739880a62367101b0 | ---
+++
@@ -1,11 +1,12 @@
package ast
type Output struct {
- expr interface{}
+ expr interface{}
+ expanded bool
}
-func NewOutput(expr interface{}) Output {
- return Output{expr}
+func NewOutput(expr interface{}, expanded bool) Output {
+ return Output{expr, expanded}
}
func (o Output) Expr() interface{} { | |
0b7585e2f60b0b710e6dc1e86daff21b9ee20c9a | ---
+++
@@ -6,6 +6,8 @@
docker "github.com/fsouza/go-dockerclient"
)
+
+const VERSION = "0.4.0"
func getEnvVar(name, defval string) string {
val := os.Getenv(name) | |
127d22a477f7ed4791d7b97b40adbfe5cafced81 | ---
+++
@@ -1,9 +1,9 @@
package markdown_test
import (
+ "log"
"os"
- "github.com/russross/blackfriday"
"github.com/shurcooL/go/markdown"
)
@@ -24,7 +24,10 @@
Final paragraph.
`)
- output := blackfriday.Markdown(input, markdown.NewRenderer(), 0)
+ output, err := markdown.Process("", input, nil)
+ if err != nil {
+ log.Fatalln(err)
+ }
os.Stdout.Write(output)
@@ -53,7 +56,10 @@
How about ` + "`this`" + ` and other stuff like *italic*, **bold** and ***super extra***.
`)
- output := blackfriday.Markdown(input, markdown.NewRenderer(), 0)
+ output, err := markdown.Process("", input, nil)
+ if err != nil {
+ log.Fatalln(err)
+ }
os.Stdout.Write(output)
| |
2c915ae40826eea9eb6cc9f2148d4126dd11b29b | ---
+++
@@ -5,11 +5,8 @@
"io/ioutil"
"runtime"
- "github.com/overlordtm/trayhost"
+ "github.com/shurcooL/trayhost"
)
-
-// TODO: Factor into trayhost.
-func trayhost_NewSeparatorMenuItem() trayhost.MenuItem { return trayhost.MenuItem{Title: ""} }
func main() {
runtime.LockOSThread()
@@ -24,7 +21,7 @@
fmt.Println("TODO: upload image in background")
},
},
- trayhost_NewSeparatorMenuItem(),
+ trayhost.SeparatorMenuItem(),
trayhost.MenuItem{
Title: "Quit",
Handler: trayhost.Exit, | |
b74a999a2bb18336ef88b6552d8d93a25fb4353d | ---
+++
@@ -18,8 +18,18 @@
}
// Sha512Sum will create a sha512sum of the string
-func Sha512Sum(content string) string {
- sha512Hasher := sha512.New() // Create a new Hash struct
- sha512Hasher.Write([]byte(content)) // Write the byte array of the content
- return hex.EncodeToString(sha512Hasher.Sum(nil)) // Return string encoded sum of sha512sum
+func Sha512Sum(content string, rounds int) string {
+ var hashString string
+
+ sha512Hasher := sha512.New() // Create a new Hash struct
+ sha512Hasher.Write([]byte(content)) // Write the byte array of the content
+ hashString = hex.EncodeToString(sha512Hasher.Sum(nil)) // Return string encoded sum of sha512sum
+
+ if (rounds != 0) && (rounds > 1) { // If we are cycling more than one rounds
+ for currentRound := 0; currentRound < rounds; currentRound++ {
+ hashString = Sha512Sum(hashString, 1) // Rehash the new hashString
+ }
+ }
+
+ return hashString
} | |
b7c9d3a292dc21878b26e437e4f2ed0e8ce911b9 | ---
+++
@@ -1,31 +1,32 @@
package golog
-import . "github.com/mndrix/golog/term"
+import "github.com/mndrix/golog/read"
import "testing"
func TestFacts (t *testing.T) {
+ rt := read.Term_
db := NewDatabase().
- Asserta(NewTerm("father", NewTerm("michael"))).
- Asserta(NewTerm("father", NewTerm("marc")))
+ Asserta(rt(`father(michael).`)).
+ Asserta(rt(`father(marc).`))
t.Logf("%s\n", db.String())
// these should be provably true
- if !IsTrue(db, NewTerm("father", NewTerm("michael"))) {
+ if !IsTrue(db, rt(`father(michael).`)) {
t.Errorf("Couldn't prove father(michael)")
}
- if !IsTrue(db, NewTerm("father", NewTerm("marc"))) {
+ if !IsTrue(db, rt(`father(marc).`)) {
t.Errorf("Couldn't prove father(marc)")
}
// these should not be provable
- if IsTrue(db, NewTerm("father", NewTerm("sue"))) {
+ if IsTrue(db, rt(`father(sue).`)) {
t.Errorf("Proved father(sue)")
}
- if IsTrue(db, NewTerm("father", NewTerm("michael"), NewTerm("marc"))) {
+ if IsTrue(db, rt(`father(michael,marc).`)) {
t.Errorf("Proved father(michael, marc)")
}
- if IsTrue(db, NewTerm("mother", NewTerm("michael"))) {
+ if IsTrue(db, rt(`mother(michael).`)) {
t.Errorf("Proved mother(michael)")
}
} | |
019c94bdfe2067142c48ce950e693d6eaaa10cf6 | ---
+++
@@ -1,5 +1,9 @@
package rest
+// compareEtag compares a client provided etag with a base etag. The client provided
+// etag may or may not have quotes while the base etag is never quoted. This loose
+// comparison of etag allows clients not stricly respecting RFC to send the etag with
+// or without quotes when the etag comes from, for instance, the API JSON response.
func compareEtag(etag, baseEtag string) bool {
if etag == baseEtag {
return true | |
34c466af0ffc077ffaf6ec6a9d357148f76d8303 | ---
+++
@@ -1,11 +1,14 @@
package isogram
-import "strings"
+import (
+ "strings"
+ "unicode"
+)
// IsIsogram returns whether the provided string is an isogram.
// In other words, whether the string does not contain any duplicate characters.
func IsIsogram(s string) bool {
- parsed := strings.ToLower(removeWhitespaceAndHyphens(s))
+ parsed := strings.ToLower(preserveOnlyLetters(s))
seen := make(map[rune]bool)
for _, c := range parsed {
if (seen[c]) == true {
@@ -16,11 +19,11 @@
return true
}
-func removeWhitespaceAndHyphens(s string) string {
+func preserveOnlyLetters(s string) string {
return strings.Map(func(r rune) rune {
- if r == ' ' || r == '-' {
- return -1
+ if unicode.IsLetter(r) {
+ return r
}
- return r
+ return -1
}, s)
} | |
57d2e92aa2960640063cab007baaaca12050f960 | ---
+++
@@ -9,7 +9,7 @@
func GetSink() (Sink, error) {
sinkType := os.Getenv("SINK_TYPE")
if sinkType == "" {
- return nil, fmt.Errorf("Missing SINK_TYPE: amqp, kafka,kinesis or stdout")
+ return nil, fmt.Errorf("Missing SINK_TYPE: amqp, kafka, kinesis, nsq or stdout")
}
switch sinkType {
@@ -23,7 +23,9 @@
return NewKinesis()
case "stdout":
return NewStdout()
+ case "nsq":
+ return NewNSQ()
default:
- return nil, fmt.Errorf("Invalid SINK_TYPE: %s, Valid values: amqp, kafka, kinesis or stdout",sinkType)
+ return nil, fmt.Errorf("Invalid SINK_TYPE: %s, Valid values: amqp, kafka, kinesis, nsq or stdout", sinkType)
}
} | |
3e1b6d848452ba5f680ecb894884c4d1c542891b | ---
+++
@@ -15,4 +15,14 @@
}
log.Printf("Decoded base58 string to %s (length %d)", hex.EncodeToString(dec), len(dec))
+
+ if dec[0] == 0x01 && dec[1] == 0x42 {
+ log.Printf("EC multiply mode not used")
+
+ } else if dec[0] == 0x01 && dec[1] == 0x43 {
+ log.Printf("EC multiply mode used")
+
+ } else {
+ log.Fatal("Malformed byte slice")
+ }
} | |
7b8803a317794afd4337f9da1e5de740a97c13a2 | ---
+++
@@ -9,14 +9,7 @@
func (c char) contains(other char) bool { return c == other }
func (p pair) contains(c char) bool {
- var first, second bool
- if s, ok := p[0].(simple); ok {
- first = s.contains(c)
- }
- if s, ok := p[1].(simple); ok {
- second = s.contains(c)
- }
- return first || second
+ return p[0].(simple).contains(c) || p[1].(simple).contains(c)
}
func dumbParse(raw []byte) simple { | |
884a64f2cca73bbcf4657168833ccf9d0e610e88 | ---
+++
@@ -27,7 +27,7 @@
data := &LoginResponse{}
data.Session = session
- data.Admin = perms.Admin
+ data.Scopes = perms.ToScopes()
c.JSON(http.StatusOK, data)
} | |
25be4d08fe6a1ff50e85e6a2c09a213e2c87953c | ---
+++
@@ -3,11 +3,13 @@
package host
import (
+ "bytes"
+
"golang.org/x/sys/unix"
)
func kernelArch() (string, error) {
var utsname unix.Utsname
err := unix.Uname(&utsname)
- return string(utsname.Machine[:]), err
+ return string(utsname.Machine[:bytes.IndexByte(utsname.Machine[:], 0)]), err
} | |
130f896e2e3ca78e01794a174382e547ba23adc0 | ---
+++
@@ -17,29 +17,39 @@
package kvledger
import (
+ "math/rand"
"os"
+ "path/filepath"
+ "strconv"
"testing"
- "github.com/hyperledger/fabric/core/config"
"github.com/spf13/viper"
)
type testEnv struct {
- t testing.TB
+ t testing.TB
+ path string
}
func newTestEnv(t testing.TB) *testEnv {
- return createTestEnv(t, "/tmp/fabric/ledgertests/kvledger")
+ path := filepath.Join(
+ os.TempDir(),
+ "fabric",
+ "ledgertests",
+ "kvledger",
+ strconv.Itoa(rand.Int()))
+ return createTestEnv(t, path)
}
func createTestEnv(t testing.TB, path string) *testEnv {
- viper.Set("peer.fileSystemPath", path)
- env := &testEnv{t}
+ env := &testEnv{
+ t: t,
+ path: path}
env.cleanup()
+ viper.Set("peer.fileSystemPath", env.path)
return env
}
func (env *testEnv) cleanup() {
- path := config.GetPath("peer.fileSystemPath")
- os.RemoveAll(path)
+ os.RemoveAll(env.path)
} | |
add5260561eef92dbba183921ed616120f178914 | ---
+++
@@ -2,6 +2,7 @@
import (
"fmt"
+ "strings"
"github.com/deis/helm/log"
"github.com/gobuffalo/buffalo"
@@ -15,15 +16,22 @@
request := c.Request()
request.ParseForm()
+ remoteAddress := strings.Split(request.RemoteAddr, ":")[0]
+
err := tx.RawQuery(
models.Q["registeruser"],
request.FormValue("email"),
- request.FormValue("ip_address"),
+ remoteAddress,
request.FormValue("survey_results"),
).Exec()
if err != nil {
- return c.Error(500, fmt.Errorf("error inserting registration to database: %s", err.Error()))
+ return c.Error(
+ 500,
+ fmt.Errorf(
+ "Error inserting registration to database: %s for remote address %s",
+ err.Error(),
+ remoteAddress))
}
log.Info("processed a registration") | |
5cb367b394300af15f1e850c7cfcb240b4552e13 | ---
+++
@@ -20,6 +20,11 @@
DiagIndex int
}
+// This is a direct translation of the qsort compar function used by PALS.
+// However it results in a different sort order (with respect to the non-key
+// fields) for FilterHits because of differences in the underlying sort
+// algorithms and their respective sort stability.
+// This appears to have some impact on FilterHit merging.
func (self FilterHit) Less(y interface{}) bool {
return self.QFrom < y.(FilterHit).QFrom
} | |
e0a0a1014764145b68e0191f2588886a22f40aaf | ---
+++
@@ -12,7 +12,7 @@
)
const (
- PORT = 9009
+ PORT = 4444
)
var ( | |
33ebc7856ecfb5fe5b24a3dbc77a13c0a39aa27f | ---
+++
@@ -3,8 +3,6 @@
import (
"socialapi/workers/helper"
"socialapi/workers/sitemap/common"
-
- "github.com/koding/redis"
)
type FileSelector interface {
@@ -24,9 +22,9 @@
item, err := redisConn.PopSetMember(common.PrepareCurrentFileNameCacheKey())
- if err != redis.ErrNil {
+ if err != nil {
return "", err
}
- return item, err
+ return item, nil
} | |
626fe0348385cdb1499af28f90a91c70dc6954e3 | ---
+++
@@ -1,3 +1,18 @@
package mathgl
-import ()
+import (
+ "testing"
+)
+
+func TestProject(t *testing.T) {
+ obj := Vec3d{1002, 960, 0}
+ modelview := Mat4d{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 203, 1, 0, 1}
+ projection := Mat4d{0.0013020833721384406, 0, 0, 0, -0, -0.0020833334419876337, -0, -0, -0, -0, -1, -0, -1, 1, 0, 1}
+ initialX, initialY, width, height := 0, 0, 1536, 960
+ win := Projectd(obj, modelview, projection, initialX, initialY, width, height)
+ answer := Vec3d{1205.0000359117985, -1.0000501200556755, 0.5} // From glu.Project()
+
+ if !win.ApproxEqual(answer) {
+ t.Errorf("Project does something weird, differs from expected by of %v", win.Sub(answer).Len())
+ }
+} | |
1de238dc7bf8902f1d210df841eed6426b0928b5 | ---
+++
@@ -1,4 +1,15 @@
package main
+
+/*
+Results
+--
+$ go test -v -bench BenchmarkMap -benchmem
+testing: warning: no tests to run
+BenchmarkMapLookupKeyStringFromBytes-4 100000000 19.6 ns/op 0 B/op 0 allocs/op
+BenchmarkMapSetKeyStringFromBytes-4 20000000 73.8 ns/op 5 B/op 1 allocs/op
+PASS
+ok github.com/robskillington/benchmarks-go 3.561s
+*/
import (
"fmt"
@@ -17,7 +28,6 @@
b.ResetTimer()
for i := 0; i < b.N; i++ {
- // lookup[string(find)] = i
if _, ok := lookup[string(find)]; !ok {
b.Fatalf("key %s should exist", string(find))
} | |
f2d3d803865df6712a60f2c62109750e77ebc6b0 | ---
+++
@@ -24,3 +24,24 @@
assert.NotNil(t, sp)
assert.Nil(t, err)
}
+
+func TestSetAssetPath(t *testing.T) {
+ fileutil.BindataDir = AssetDir
+ fileutil.BindataFn = Asset
+ _, err := LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
+ assert.Nil(t, err)
+ UnloadAll()
+ SetAssetPaths(wd)
+ _, err = LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
+ assert.NotNil(t, err)
+ UnloadAll()
+ SetAssetPaths(
+ filepath.Join(
+ wd,
+ "assets",
+ "images"),
+ )
+ _, err = LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
+ assert.Nil(t, err)
+
+} | |
c2eb972b432698610958c400ec84faa20de1c016 | ---
+++
@@ -3,7 +3,7 @@
import (
"fmt"
"os"
- "jogurto/commands"
+ "github.com/lapingvino/jogurto/commands"
)
func main() { | |
10735dacff0d670a47abc378c6823ee3398e9cf9 | ---
+++
@@ -1,6 +1,9 @@
package sensu
-import "fmt"
+import (
+ "encoding/json"
+ "fmt"
+)
// GetEvents Return all the current events
func (s *Sensu) GetEvents() ([]interface{}, error) {
@@ -21,7 +24,12 @@
return s.GetList(fmt.Sprintf("events/%s/%s", client, check), 0, 0)
}
-// ResolveEvent Resolves an event (delayed action)
-func (s *Sensu) ResolveEvent(client string, check string) (map[string]interface{}, error) {
- return s.Delete(fmt.Sprintf("events/%s/%s", client, check))
+// ResolveEvent delete an event
+func (s *Sensu) ResolveEvent(payload interface{}) (map[string]interface{}, error) {
+ // return s.Post(fmt.Sprintf("stashes/create"), payload)
+ payloadstr, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("Stash parsing error: %q returned: %v", err, err)
+ }
+ return s.PostPayload("resolve", string(payloadstr[:]))
} | |
7bed6a18ea6f00deda4ea0b2797f715c7c555a6c | ---
+++
@@ -13,7 +13,7 @@
)
func TestFoo(t *testing.T) {
- ctx, done, err := aetest.NewContext(nil)
+ ctx, done, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
} | |
95bf065037f2d6ebf7fe59e15361d1e3f4c4ff9e | ---
+++
@@ -1,11 +1,17 @@
package cdp
import (
+ "fmt"
+
"github.com/mafredri/cdp/rpcc"
)
type eventClient interface {
rpcc.Stream
+}
+
+type getStreamer interface {
+ GetStream() rpcc.Stream
}
// Sync takes two or more event clients and sets them into synchronous operation,
@@ -27,7 +33,11 @@
func Sync(c ...eventClient) error {
var s []rpcc.Stream
for _, cc := range c {
- s = append(s, cc)
+ cs, ok := cc.(getStreamer)
+ if !ok {
+ return fmt.Errorf("cdp: Sync: bad eventClient type: %T", cc)
+ }
+ s = append(s, cs.GetStream())
}
return rpcc.Sync(s...)
} | |
fe06051ad3acc48b6d386ae0d3308765f4520027 | ---
+++
@@ -1,6 +1,32 @@
package virtualboxclient
+
+import (
+ "github.com/appropriate/go-virtualboxclient/vboxwebsrv"
+)
type StorageController struct {
virtualbox *VirtualBox
managedObjectId string
}
+
+func (sc *StorageController) GetName() (string, error) {
+ request := vboxwebsrv.IStorageControllergetName{This: sc.managedObjectId}
+
+ response, err := sc.virtualbox.IStorageControllergetName(&request)
+ if err != nil {
+ return "", err // TODO: Wrap the error
+ }
+
+ return response.Returnval, nil
+}
+
+func (sc *StorageController) GetPortCount() (uint32, error) {
+ request := vboxwebsrv.IStorageControllergetPortCount{This: sc.managedObjectId}
+
+ response, err := sc.virtualbox.IStorageControllergetPortCount(&request)
+ if err != nil {
+ return 0, err // TODO: Wrap the error
+ }
+
+ return response.Returnval, nil
+} | |
dc4007005dabaa1e9284e81d0bedcaba683ea269 | ---
+++
@@ -10,7 +10,7 @@
ext := filepath.Ext(base)
drv := os.Getenv("SystemDrive")
- pdDir := "ProgramData"
+ pdDir := `\ProgramData`
name := base[0 : len(base)-len(ext)]
return filepath.Join(drv, pdDir, name, name) | |
15c651b73216daaef24d0b09641511d04cde7970 | ---
+++
@@ -7,7 +7,7 @@
// RepositoryNameComponentRegexp restricts registtry path components names to
// start with at least two letters or numbers, with following parts able to
// separated by one period, dash or underscore.
-var RepositoryNameComponentRegexp = regexp.MustCompile(`[a-z0-9](?:[a-z0-9]+[._-]?)*[a-z0-9]`)
+var RepositoryNameComponentRegexp = regexp.MustCompile(`[a-z0-9]{2,}(?:[._-][a-z0-9]+)*`)
// RepositoryNameRegexp builds on RepositoryNameComponentRegexp to allow 2 to
// 5 path components, separated by a forward slash. | |
a102f95bc8bf2b00c7dd63481a9d629354a82526 | ---
+++
@@ -11,9 +11,74 @@
PORT = ":8080"
)
+func rootHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func todoHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func addHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func editHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func delHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func finishHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func userHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func userDelHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func loginHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func registerHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func logoutHandler(w http.responsewriter, r *http.request) {
+
+}
+
+func resetHandler(w http.responsewriter, r *http.request) {
+
+}
+
func main() {
router := mux.NewRouter()
- router.HandleFunc("/", roothandler)
+ router.HandleFunc("/", rootHandler)
+
+ router.HandleFunc("/todo", todoHandler)
+ router.HandleFunc("/todo/{id}", todoHandler)
+ router.HandleFunc("/todo/add", addHandler)
+ router.HandleFunc("/todo/edit/{id}", editHandler)
+ router.HandleFunc("/todo/del/{id}", delHandler)
+
+ router.HandleFunc("/finish/{id}", finishHandler)
+
+ router.HandleFunc("/user", userHandler)
+ router.HandleFunc("/user/{id}", userHandler)
+ router.HandleFunc("/user/del/{id}", userDelHandler)
+
+ router.HandleFunc("/register", registerHandler)
+ router.HandleFunc("/login", loginHandler)
+ router.HandleFunc("/logout", logoutHandler)
+ router.HandleFunc("/resetpass", resetHandler)
err := http.ListenAndServe(PORT, router)
if err != nil {
log.Fatal(err) | |
1be16f01e01f15c4148c7eacf85c9a297e0c038d | ---
+++
@@ -11,7 +11,7 @@
// RunPush pushes an image to the registry
func RunPush(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) {
pushTag := func(tag string) error {
- return pushImage(ctx, t, tag)
+ return pushImage(ctx, tag)
}
if err := t.ForEachTag(ctx, pushTag); err != nil {
return false, err
@@ -20,7 +20,7 @@
return true, nil
}
-func pushImage(ctx *context.ExecuteContext, t *Task, tag string) error {
+func pushImage(ctx *context.ExecuteContext, tag string) error {
repo, err := parseAuthRepo(tag)
if err != nil {
return err | |
cd9d03f6839cfb5583ebf3bad725372347a43537 | ---
+++
@@ -1,3 +1,17 @@
+// Copyright 2016 Mender Software AS
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package mocks
import ( | |
2ff019010fc527968c57c1843dbd4c7455619251 | ---
+++
@@ -36,7 +36,9 @@
// Get returns the first value of the given attribute, if any.
func (a *AttributesMap) Get(name string) string {
if v, ok := (map[string][]string)(*a)[name]; ok {
- return v[0]
+ if len(v) > 0 {
+ return v[0]
+ }
}
return ""
} | |
0973942020260734e49a59cacb35d78c64aea566 | ---
+++
@@ -5,7 +5,7 @@
"strings"
"testing"
- "."
+ "github.com/ninchat/maxreader"
)
func Test(t *testing.T) { | |
7def621e65be42b0269547de2c62c7b2ebcb84e4 | ---
+++
@@ -10,7 +10,6 @@
)
func LoadSchema(u *url.URL) (*models.Schema, error) {
- var schema models.Schema
response, err := http.Get(u.String())
if err != nil {
return nil, err
@@ -20,6 +19,7 @@
if err != nil {
return nil, err
}
+ var schema models.Schema
json.Unmarshal(specification, &schema)
if err != nil {
return nil, err | |
2266e7f2345c88a8e195fd959550d0d657bec843 | ---
+++
@@ -16,7 +16,7 @@
// postRunProcessing perfoms any processing needed on the container after it has stopped.
func (daemon *Daemon) postRunProcessing(container *container.Container, e libcontainerd.StateInfo) error {
- if e.UpdatePending {
+ if e.ExitCode == 0 && e.UpdatePending {
spec, err := daemon.createSpec(container)
if err != nil {
return err
@@ -29,6 +29,7 @@
// Create a new servicing container, which will start, complete the update, and merge back the
// results if it succeeded, all as part of the below function call.
if err := daemon.containerd.Create((container.ID + "_servicing"), *spec, servicingOption); err != nil {
+ container.ExitCode = -1
return fmt.Errorf("Post-run update servicing failed: %s", err)
}
} | |
f0e7b4ade2cf9a2304e5b92258b68c9f3e15fc3d | ---
+++
@@ -20,7 +20,7 @@
cc.Use = "install"
cc.Short = "install bar support into git repo"
- cc.Flags().StringVarP(&c.Log, "log", "", logx.DEBUG,
+ cc.Flags().StringVarP(&c.Log, "log", "", logx.INFO,
"installable logging level")
cc.Flags() | |
2354c5e2bb0c0132cd6f91d7f772fdce481d1950 | ---
+++
@@ -42,8 +42,6 @@
"Username": currentUser.Name,
})
- cmd.UI.DisplayNewline()
-
if newPassword != verifyPassword {
return translatableerror.PasswordVerificationFailedError{}
} | |
147d5555aef0c08495931f9fa2745829abe3b58f | ---
+++
@@ -1,7 +1,8 @@
-package moeparser
+package moeparser_test
import (
"fmt"
+ "moeparser"
"testing"
)
| |
bb490c1e2c7deddeeaf230587b0373eb37510e8c | ---
+++
@@ -35,7 +35,7 @@
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFound)
r.HandleFunc("/{server}/{project}/{repo}/{box}.json", boxHandler).
- Methods("GET")
+ Methods("GET", "HEAD")
n.UseHandler(r)
listenOn := fmt.Sprintf("%v:%v", cfg.Address, cfg.Port) | |
67d792b9039bf57f47368d3edb9816971eff7ee1 | ---
+++
@@ -2,37 +2,41 @@
import (
"fmt"
+ "log"
"os"
"golang.org/x/crypto/ssh/terminal"
)
-//get number of columns of terminal from crypto subdirectory ssh/terminal
-func getCols() int {
- c, _, err := terminal.GetSize(int(os.Stdout.Fd()))
+// getWidth gets number of width of terminal from crypto subdirectory ssh/terminal
+func getWidth() (int, error) {
+ w, _, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
- panic(err)
+ return -1, err
}
- return c
+ return w, nil
}
-// DrawHr fills a row with '#' by default (if no arguments are provided) or take command line arguments and print each pattern on a new line
-func DrawHr(args ...string) {
- cols := getCols()
+// Draw fills a row with '#' by default (if no arguments are provided) or takes arguments and prints each pattern on a new line.
+func Draw(args ...string) {
+ w, err := getWidth()
+ if err != nil {
+ log.Fatalf("Error getting terminal width: %s\n", err)
+ }
if len(args) == 0 {
- for i := 0; i < cols; i++ {
+ for i := 0; i < w; i++ {
fmt.Printf("#")
}
- fmt.Println()
+ fmt.Printf("\n")
} else {
for _, arg := range args {
l := len(arg)
- for i := 0; i < cols/l; i++ {
+ for i := 0; i < w/l; i++ {
fmt.Printf(arg)
}
- // Fill ups the remaining columns in the row with part of the pattern
- fmt.Printf("%v\n", arg[:cols%l])
+ // Fills up the remaining columns in the row with part of the pattern
+ fmt.Printf("%s\n", arg[:w%l])
}
}
} | |
5807fc82c880ac3da3b9348805113b5a35e5a8c3 | ---
+++
@@ -3,13 +3,14 @@
import (
"crypto/hmac"
"crypto/sha1"
+ "encoding/hex"
)
// ComputeHMAC of a message using a specific key
func ComputeHMAC(message []byte, key string) []byte {
mac := hmac.New(sha1.New, []byte(key))
mac.Write(message)
- return mac.Sum(nil)
+ return []byte(hex.EncodeToString(mac.Sum(nil)))
}
// CheckHMAC of a message | |
56bfaeda70752ff87e8fac957b4c4bad59c4ef17 | ---
+++
@@ -25,3 +25,17 @@
c.Check(clock().Now(), Equals, realNow)
}
+
+func (s *GomolSuite) TestRealClockNow(c *C) {
+ // This test is completely pointless because it's not something that can really
+ // be tested but I was sick of seeing the red for a lack of a unit test. So I created
+ // this one and figure even on slow systems the two lines should be executed within
+ // one second of each other. :P
+ setClock(&realClock{})
+
+ timeNow := time.Now()
+ clockNow := clock().Now()
+
+ diff := clockNow.Sub(timeNow)
+ c.Check(diff < time.Second, Equals, true)
+} | |
ef775b6a90143374b7d5d99ed8e44a512e3cd162 | ---
+++
@@ -14,7 +14,7 @@
RS3 = 16299
// RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server
- // 1809 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update).
+ // 1803 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update).
RS4 = 17134
// RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server | |
1f6d2ea7f827e3c56a5df7deae5dfbf73e71f0d8 | ---
+++
@@ -3,6 +3,7 @@
import (
"log"
"os"
+ "fmt"
"go/ast"
"go/parser"
@@ -10,11 +11,11 @@
)
func validator(name string, s *ast.StructType) {
- log.Print(name)
+ fmt.Println(name)
for _, fld := range(s.Fields.List) {
nam := fld.Names[0].Name
typ := fld.Type.(*ast.Ident)
- log.Printf("%s %s", nam, typ)
+ fmt.Printf("%s %s\n", nam, typ)
}
}
| |
e8aef4b9bf80da660c0374c6d476c87a3233a35e | ---
+++
@@ -1,7 +1,8 @@
package main
import (
- "image/color"
+ "fmt"
+ "image"
"time"
"github.com/voxelbrain/pixelpixel/imageutils"
@@ -12,15 +13,16 @@
c := protocol.PixelPusher()
img := protocol.NewPixel()
- dImg := imageutils.DimensionChanger(img, 4, 1)
+ dImg := imageutils.DimensionChanger(img, 4, 6)
for i := 0; i < 5; i++ {
- if i < 3 {
- dImg.Set(i, 0, color.RGBA{uint8(100 + i*70), 0, 0, 255})
+ color := imageutils.Green
+ if i > 3 {
+ panic("CRASH")
} else if i == 3 {
- dImg.Set(i, 0, color.RGBA{0, 255, 0, 255})
- } else {
- panic("CRASH")
+ color = imageutils.Red
}
+ imageutils.FillRectangle(dImg, image.Rect(0, 0, 4, 6), imageutils.Black)
+ imageutils.DrawText(dImg, image.Rect(0, 0, 4, 6), color, fmt.Sprintf("%d", 3-i))
c <- img
time.Sleep(1 * time.Second)
} | |
f8f10d4218610490587cf7df4230bd8602f2b2c7 | ---
+++
@@ -1,7 +1,7 @@
package read
// Fre scores the Flesch reading-ease.
-// See https://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests#Flesch_reading_ease.
+// See https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FFlesch%E2%80%93Kincaid_readability_tests%23Flesch_reading_ease.
func Fre(text string) float64 {
sylCnt := float64(CntSyls(text))
wordCnt := float64(CntWords(text)) | |
ca3450e2ac99d1d79c0b34b6201381cde5afc44d | ---
+++
@@ -9,6 +9,8 @@
const VERSION = "0.1.0"
func main() {
+ log.Printf("bitrun api v%s\n", VERSION)
+
err := LoadLanguages("./languages.json")
if err != nil {
log.Fatalln(err) | |
5647a87df12726c2b04bf5a09a89471f91a6c1b8 | ---
+++
@@ -1,27 +1,72 @@
/*
This package is just a collection of test cases
- */
+*/
package main
import (
- "fmt"
- "os"
- "ripe-atlas"
+ "fmt"
+ "github.com/codegangsta/cli"
+ "os"
+ "ripe-atlas"
+ "strconv"
)
+// set args for examples sake
+
func main() {
- p, err := atlas.GetProbe(14037)
- if err != nil {
- fmt.Printf("err: %v", err)
- os.Exit(1)
+ app := cli.NewApp()
+ app.Name = "atlas"
+ app.Commands = []cli.Command{
+ {
+ Name: "probes",
+ Aliases: []string{"p"},
+ Usage: "use it to see a description",
+ Description: "This is how we describe hello the function",
+ Subcommands: []cli.Command{
+ {
+ Name: "list",
+ Aliases: []string{"ls"},
+ Usage: "lists all probes",
+ Description: "greets someone in english",
+ Action: func(c *cli.Context) error {
+ q, err := atlas.GetProbes()
+ if err != nil {
+ fmt.Printf("err: %v", err)
+ os.Exit(1)
+ }
+ fmt.Printf("q: %#v\n", q)
+
+ return nil
+ },
+ },
+ {
+ Name: "info",
+ Usage: "info for one probe",
+ Description: "gives info for one probe",
+ Flags: []cli.Flag{
+ cli.IntFlag{
+ Name: "id",
+ Value: 0,
+ Usage: "id of the probe",
+ },
+ },
+ Action: func(c *cli.Context) error {
+ args := c.Args()
+ id, _ := strconv.ParseInt(args[0], 10, 32)
+
+ p, err := atlas.GetProbe(int(id))
+ if err != nil {
+ fmt.Printf("err: %v", err)
+ os.Exit(1)
+ }
+ fmt.Printf("p: %#v\n", p)
+
+ return nil
+ },
+ },
+ },
+ },
}
- fmt.Printf("p: %#v\n", p)
-
- q, err := atlas.GetProbes()
- if err != nil {
- fmt.Printf("err: %v", err)
- os.Exit(1)
- }
- fmt.Printf("q: %#v\n", q)
+ app.Run(os.Args)
} | |
06a6e5bf89d5cfac5330a538395de230489e2d43 | ---
+++
@@ -24,7 +24,10 @@
func content() []string {
filePath := path.Join(home, shortcutFilename)
dat, err := ioutil.ReadFile(filePath)
- check(err)
+ if err != nil {
+ fmt.Println("Unable to open shortcut file. Try doing a search.")
+ panic(1)
+ }
lines := strings.Split(string(dat), "\n")
return lines[0 : len(lines)-1]
} | |
85337525023b304d71ce16fce35208889acf1be4 | ---
+++
@@ -5,7 +5,7 @@
"testing"
)
-func dummyNewUser() *User {
+func dummyNewUser(password string) *User {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
randSeq := func(n int) string {
@@ -16,10 +16,11 @@
return string(b)
}
- return &User{
+ u := &User{
Username: randSeq(10),
- Password: randSeq(8),
}
+ u.Password = u.Hash(password)
+ return u
}
func TestUser(t *testing.T) { | |
ff758e9bb9ca6a6750d21f17cd9653126c467cef | ---
+++
@@ -1,4 +1,8 @@
package radosAPI
+
+type apiError struct {
+ Code string `json:"Code"`
+}
// Usage represents the response of usage requests
type Usage struct { | |
7a9e26edeafc4c2f52faccefaa71c6c92a0d8b33 | ---
+++
@@ -9,7 +9,7 @@
EnvironmentFile=/etc/environment
User=core
TimeoutStartSec=0
-ExecStartPre=/usr/bin/docker pull mmmhm/{{.Name}}:{{.Version}}
+ExecStartPre=/usr/bin/docker pull {{.DockerHubUsername}}/{{.Name}}:{{.Version}}
ExecStartPre=-/usr/bin/docker rm -f {{.Name}}-{{.Version}}-%i
ExecStart=/usr/bin/docker run --name {{.Name}}-{{.Version}}-%i -p 3000 {{.DockerHubUsername}}/{{.Name}}:{{.Version}}
ExecStartPost=/bin/sh -c "sleep 15; /usr/bin/etcdctl set /vulcand/upstreams/{{.Name}}/endpoints/{{.Name}}-{{.Version}}-%i http://$COREOS_PRIVATE_IPV4:$(echo $(/usr/bin/docker port {{.Name}}-{{.Version}}-%i 3000) | cut -d ':' -f 2)" | |
28a4ff944b59d34b868260a1e035aec7f18c3090 | ---
+++
@@ -9,13 +9,22 @@
s2 := []float64{10, -51.2, 8}
s3 := []float64{1, 2, 3, 5, 6}
s4 := []float64{}
+ s5 := []float64{0, 0, 0}
- _, err := Correlation(s1, s2)
+ a, err := Correlation(s5, s5)
+ if err != nil {
+ t.Errorf("Should not have returned an error")
+ }
+ if a != 0 {
+ t.Errorf("Should have returned 0")
+ }
+
+ _, err = Correlation(s1, s2)
if err == nil {
t.Errorf("Mismatched slice lengths should have returned an error")
}
- a, err := Correlation(s1, s3)
+ a, err = Correlation(s1, s3)
if err != nil {
t.Errorf("Should not have returned an error")
}
@@ -29,4 +38,13 @@
t.Errorf("Empty slice should have returned an error")
}
+ a, err = Pearson(s1, s3)
+ if err != nil {
+ t.Errorf("Should not have returned an error")
+ }
+
+ if a != 0.9912407071619302 {
+ t.Errorf("Correlation %v != %v", a, 0.9912407071619302)
+ }
+
} | |
c09b3132053225dd3ea720112a0bf8dcfde4a4d6 | ---
+++
@@ -1,33 +1,21 @@
package main
import (
- "bufio"
- "fmt"
"log"
- "os"
"github.com/griffithsh/sql-squish/database"
)
func main() {
- scanner := bufio.NewScanner(os.Stdin)
+ concatted, err := inputStdin()
- var concatted string
- for scanner.Scan() {
- concatted = concatted + scanner.Text()
+ if err != nil {
+ log.Fatal(err)
}
d, err := database.FromString(concatted)
if err != nil {
log.Fatal(err)
}
- for _, t := range d.Tables {
- fmt.Println(t.String())
- }
- // files, err := db.AsSQL()
- // if err != nil {
- // log.Fatal(err)
- // }
- // for file := range files {
- // fmt.Print(file)
- // }
+
+ outputStdout(d)
} | |
ab33ddcbd734e84b273ee508d380e81cf83ae513 | ---
+++
@@ -2,7 +2,8 @@
// TerminalConnectionTokenParams is the set of parameters that can be used when creating a terminal connection token.
type TerminalConnectionTokenParams struct {
- Params `form:"*"`
+ Params `form:"*"`
+ Location string `form:"location"`
// This feature has been deprecated and should not be used anymore.
OperatorAccount *string `form:"operator_account"`
@@ -10,6 +11,7 @@
// TerminalConnectionToken is the resource representing a Stripe terminal connection token.
type TerminalConnectionToken struct {
- Object string `json:"object"`
- Secret string `json:"secret"`
+ Location string `json:"location"`
+ Object string `json:"object"`
+ Secret string `json:"secret"`
} | |
269ac84b5d1905c513554f6d5d5c5725c172e9f6 | ---
+++
@@ -2,8 +2,18 @@
import (
"runtime"
+
+ . "github.com/onsi/ginkgo"
)
func IsWindows() bool {
return runtime.GOOS == "windows"
}
+
+func SkipIfWindows() {
+
+ if IsWindows() {
+ Skip("the OS is Windows")
+ }
+
+} | |
db1a85cd360a55632d78df9c5e3aad4ec765eeb5 | ---
+++
@@ -1,14 +1,8 @@
package main
-import (
- "testing"
-
- log "github.com/Sirupsen/logrus"
-)
+import "testing"
func TestLineBreaking(t *testing.T) {
- log.SetLevel(log.DebugLevel)
-
var tests = []struct {
text string
result string | |
3165608fb29d17d33ebeb88095e8d4c801b7ed68 | ---
+++
@@ -6,10 +6,64 @@
func main() {
app := cli.NewApp()
app.Name = "exercism"
- app.Usage = "fight the loneliness!"
- app.Action = func(c *cli.Context) {
- println("Hello friend!")
+ app.Usage = "A command line tool to interact with http://exercism.io"
+ app.Commands = []cli.Command{
+ {
+ Name: "demo",
+ ShortName: "d",
+ Usage: "Fetch first assignment for each language from exercism.io",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
+ {
+ Name: "fetch",
+ ShortName: "f",
+ Usage: "Fetch current assignment from exercism.io",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
+ {
+ Name: "login",
+ ShortName: "l",
+ Usage: "Save exercism.io api credentials",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
+ {
+ Name: "logout",
+ ShortName: "o",
+ Usage: "Clear exercism.io api credentials",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
+ {
+ Name: "peek",
+ ShortName: "p",
+ Usage: "Fetch upcoming assignment from exercism.io",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
+ {
+ Name: "submit",
+ ShortName: "s",
+ Usage: "Submit code to exercism.io on your current assignment",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
+ {
+ Name: "whoami",
+ ShortName: "w",
+ Usage: "Get the github username that you are logged in as",
+ Action: func(c *cli.Context) {
+ println("Not yet implemented")
+ },
+ },
}
-
app.Run(os.Args)
} | |
d242ab9b1479a6aebe8e5cbd6b6ae48fb845f950 | ---
+++
@@ -3,9 +3,10 @@
func main() {
Log("main.start")
- queryInterval := QueryInterval()
databaseUrl := DatabaseUrl()
libratoAuth := LibratoAuth()
+ queryInterval := QueryInterval()
+ queryTimeout := queryInterval
queryFiles := ReadQueryFiles("./queries/*.sql")
metricBatches := make(chan []interface{}, 10)
@@ -20,7 +21,7 @@
go TrapStart(globalStop)
go MonitorStart(queryTicks, metricBatches, monitorStop, done)
go LibratoStart(libratoAuth, metricBatches, libratoStop, done)
- go PostgresStart(databaseUrl, queryTicks, queryInterval, metricBatches, postgresStop, done)
+ go PostgresStart(databaseUrl, queryTicks, queryTimeout, metricBatches, postgresStop, done)
go SchedulerStart(queryFiles, queryInterval, queryTicks, schedulerStop, done)
Log("main.await") | |
9e6db73b9cece24d3a5813af5847e8b8390f1d6b | ---
+++
@@ -12,9 +12,8 @@
// deliveryAck acknowledges delivery message with retries on error
func deliveryAck(delivery amqp.Delivery) {
- retryCount := 3
var err error
- for retryCount > 0 {
+ for retryCount := 3; retryCount > 0; retryCount-- {
if err = delivery.Ack(false); err == nil {
break
} | |
bf739142c88471b434526a898bc32737399aa043 | ---
+++
@@ -7,22 +7,21 @@
func SetUp() cli.Command {
cmd := cli.Command{
- Name: "shell",
- Usage: "BQL shell",
- Action: Launch,
+ Name: "shell",
+ Usage: "BQL shell",
+ Description: "shell command launches an interactive shell for BQL",
+ Action: Launch,
}
cmd.Flags = []cli.Flag{
cli.StringFlag{
- Name: "uri",
- Value: "http://localhost:8090/api",
- Usage: "target URI to launch",
- EnvVar: "URI",
+ Name: "uri",
+ Value: "http://localhost:8090/",
+ Usage: "target URI to launch",
},
cli.StringFlag{
- Name: "version,v",
- Value: "v1",
- Usage: "SenserBee API version",
- EnvVar: "VERSION",
+ Name: "version,v",
+ Value: "v1",
+ Usage: "SenserBee API version",
},
}
return cmd
@@ -30,11 +29,11 @@
// Launch SensorBee's command line client tool.
func Launch(c *cli.Context) {
- host := c.String("uri")
+ host := c.String("uri") // TODO: validate URI
if !strings.HasSuffix(host, "/") {
host += "/"
}
- uri := host + c.String("version")
+ uri := host + "api/" + c.String("version")
cmds := []Command{}
for _, c := range NewTopologiesCommands() { | |
b3239e49cb77f8dac7bd968d73aab42cfcd51082 | ---
+++
@@ -1,6 +1,7 @@
/*
-Package rmsd implements a version of the Kabsch algorithm that is described
-in detail here: http://cnx.org/content/m11608/latest/
+Package rmsd implements a version of the Kabsch algorithm to compute the
+minimal RMSD between two equal length sets of atoms. The exact algorithm
+implement is described in detail here: http://cnx.org/content/m11608/latest/.
A convenience function for computing the RMSD of residue ranges from two PDB
files is also provided. | |
d425954d435d1c30f3e4790c6889c6e709458b7f | ---
+++
@@ -11,6 +11,12 @@
_, err := NewClient()
assert.NotNil(t, err)
assert.Equal(t, "host is required", err.Error())
+}
+
+func TestSetHostFailsOnBlank(t *testing.T) {
+ _, err := NewClient(SetHost(""))
+ assert.NotNil(t, err)
+ assert.Equal(t, "host cannot be empty", err.Error())
}
func TestNewClientAddsProtocolWhenNotSpecified(t *testing.T) { | |
60b6ed7bf8c22107e407983043adfd59c1a7e5ab | ---
+++
@@ -8,9 +8,9 @@
RelativePath string
}
-// NewDocument creates a document from a relative filepath.
+// NewDocument creates a document from the filepath.
// The root is typically the root of the exercise, and
-// path is the relative path to the file within the root directory.
+// path is the absolute path to the file.
func NewDocument(root, path string) (Document, error) {
path, err := filepath.Rel(root, path)
if err != nil { | |
b926d476dff7752973c37631488bca21d498d085 | ---
+++
@@ -17,6 +17,11 @@
window := mainWindow.GtkWindow
window.ShowAll()
+ config := models.Config()
+ if config.AccessToken == "" {
+ fmt.Println("No access token, show authentication window")
+ }
+
gtk.Main()
}
| |
1081c7d2285a4d66ef67f4639d8248ebfc16d95c | ---
+++
@@ -49,8 +49,12 @@
func drawGrid(grid *sudoku.Grid) {
for y, line := range strings.Split(grid.Diagram(), "\n") {
- for x, ch := range line {
+ x := 0
+ //The first number in range will be byte offset, but for some items like the bullet, it's two bytes.
+ //But what we care about is that each item is a character.
+ for _, ch := range line {
termbox.SetCell(x, y, ch, termbox.ColorGreen, termbox.ColorDefault)
+ x++
}
}
} | |
5fee4b4aa750182d42626abf5ee69166b497a3c2 | ---
+++
@@ -32,7 +32,7 @@
buf := getBuffer()
defer putBuffer(buf)
io.WriteString(w, "<HTML>\n<BODY>\n")
- n, err := io.CopyBuffer(w, DefaultMarkovMap, buf)
+ n, err := io.CopyBuffer(w, mm, buf)
log.Printf("Wrote: %d (%v)", n, err)
}
} | |
6978577fdf63f3f02ca9c3ac842abab583811f93 | ---
+++
@@ -15,31 +15,29 @@
// http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
var zeroNonce []byte = make([]byte, symmetricNonceLength)
-func symmetricDecrypt(aesKey, ciphertext []byte) ([]byte, error) {
+func makeAESGCM(aesKey []byte) (cipher.AEAD, error) {
blockCipher, err := aes.NewCipher(aesKey)
if err != nil {
return nil, err
}
- streamCipher, err := cipher.NewGCM(blockCipher)
+ return cipher.NewGCM(blockCipher)
+}
+
+func symmetricDecrypt(aesKey, ciphertext []byte) ([]byte, error) {
+ gcm, err := makeAESGCM(aesKey)
if err != nil {
return nil, err
}
- return streamCipher.Open(nil, zeroNonce, ciphertext, nil)
+ return gcm.Open(nil, zeroNonce, ciphertext, nil)
}
func symmetricEncrypt(aesKey, plaintext []byte) ([]byte, error) {
- blockCipher, err := aes.NewCipher(aesKey)
+ gcm, err := makeAESGCM(aesKey)
if err != nil {
- return []byte{}, err
+ return nil, err
}
- streamCipher, err := cipher.NewGCM(blockCipher)
- if err != nil {
- return []byte{}, err
- }
-
- ciphertext := streamCipher.Seal(nil, zeroNonce, plaintext, nil)
- return ciphertext, nil
+ return gcm.Seal(nil, zeroNonce, plaintext, nil), nil
} | |
60a6f7c896230d54d7b040d6be332c66d770d703 | ---
+++
@@ -1,6 +1,8 @@
package main
import (
+ "encoding/binary"
+ "io"
"log"
"os"
)
@@ -10,13 +12,53 @@
DATABLOCK_SIZE = 1024 * 4 // 4KB
)
+var (
+ DatablockByteOrder = binary.BigEndian
+)
+
func main() {
+ file, err := createDatafile()
+ if err != nil {
+ panic(err)
+ }
+
+ writeInt16(file, 7)
+ writeInt16(file, 1)
+
+ if _, err := file.Seek(0, 0); err != nil {
+ panic(err)
+ }
+
+ for i := 0; i < 10; i++ {
+ i, err := readInt16(file)
+ if err != nil {
+ panic(err)
+ }
+
+ println(i)
+ }
+}
+
+func createDatafile() (*os.File, error) {
file, err := os.Create("metadata-db.dat")
if err != nil {
- panic(err)
+ return nil, err
}
log.Println("Creating datafile...")
file.Truncate(DATAFILE_SIZE)
log.Println("DONE")
+
+ return file, nil
}
+
+func writeInt16(f io.Writer, i uint16) error {
+ log.Printf("Writing int16 `%d`", i)
+ return binary.Write(f, DatablockByteOrder, i)
+}
+
+func readInt16(f io.Reader) (ret uint16, err error) {
+ log.Println("Reading int16")
+ err = binary.Read(f, DatablockByteOrder, &ret)
+ return
+} | |
80e5a2ca5170370cd2f0e334498f154a9ccfd4ea | ---
+++
@@ -11,6 +11,10 @@
app.Name = "docker-inject"
app.Usage = "Copy files/directories from hosts to running Docker containers"
app.Version = "0.0.0"
+ app.HideHelp = true
+ app.Flags = []cli.Flag{
+ cli.HelpFlag,
+ }
app.Action = func(c *cli.Context) {
inj, err := newInjector(os.Stderr, c.Args())
if err != nil { | |
36fd44f3b088f9b9f1c75dbcb43bc51ecdcaa2c1 | ---
+++
@@ -6,6 +6,7 @@
"log"
"os"
+ "github.com/relab/raft/commonpb"
"github.com/relab/raft/raftgorums"
)
@@ -25,12 +26,18 @@
log.Fatal(err)
}
- fmt.Printf("Found: %d entries.\n", storage.NumEntries())
+ fmt.Printf("Found: %d entries.\n", storage.NextIndex()-storage.FirstIndex())
- entries, err := storage.GetEntries(0, storage.NumEntries())
+ entries := make([]*commonpb.Entry, storage.NextIndex()-storage.FirstIndex())
- if err != nil {
- log.Fatal(err)
+ for i := storage.FirstIndex(); i < storage.NextIndex(); i++ {
+ entry, err := storage.GetEntry(i)
+
+ if err != nil {
+ entry = &commonpb.Entry{Data: []byte("missing")}
+ }
+
+ entries[i-storage.FirstIndex()] = entry
}
for _, entry := range entries { | |
9392b64be713a848aa23bd9010dd2e82280a79d6 | ---
+++
@@ -20,5 +20,7 @@
api := slack.New(token)
r := slackreporter.GetReport(stdin)
- slackreporter.NotifyToGroup(*api, r, groupName)
+ if *r.ExitCode != 0 {
+ slackreporter.NotifyToGroup(*api, r, groupName)
+ }
} | |
eae28e37654089792133385b5b0df697beddb098 | ---
+++
@@ -6,16 +6,18 @@
)
type ParticipantSerialzer struct {
- ID uint `json:"id"`
- Name string `json:"name"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ AvatarURL string `json:"avatar"`
}
func SerializeParticipant(db *gorm.DB, participant *model.User) *ParticipantSerialzer {
owner := model.User{}
db.Find(&owner, participant.ID)
participantSerialzer := ParticipantSerialzer{
- ID: participant.ID,
- Name: participant.Name,
+ ID: participant.ID,
+ Name: participant.Name,
+ AvatarURL: participant.AvatarURL,
}
return &participantSerialzer
} | |
b9686df0c97c6c029495830042a2aeb52c7d5a0a | ---
+++
@@ -5,6 +5,7 @@
"github.com/ibrt/go-oauto/oauto/config"
"encoding/json"
"fmt"
+ "github.com/go-errors/errors"
)
type ApiHandler func(config *config.Config, r *http.Request, baseURL string) (interface{}, error)
@@ -24,7 +25,7 @@
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(resp)
} else {
- http.Error(w, err.Error(), http.StatusInternalServerError)
+ http.Error(w, err.(*errors.Error).ErrorStack(), http.StatusInternalServerError)
}
}
} | |
b0245d688b93d66794e509d977d444d6f3cc0086 | ---
+++
@@ -2,47 +2,49 @@
import (
"testing"
-
- "gopkg.in/redis.v5"
)
-var defaultAddr = "127.0.0.1:6379"
-
func Test_CheckpointLifecycle(t *testing.T) {
- client := redis.NewClient(&redis.Options{Addr: defaultAddr})
-
- c := &Checkpoint{
- appName: "app",
- client: client,
+ // new
+ c, err := New("app")
+ if err != nil {
+ t.Fatalf("new checkpoint error: %v", err)
}
- // set checkpoint
+ // set
c.Set("streamName", "shardID", "testSeqNum")
- // get checkpoint
+ // get
val, err := c.Get("streamName", "shardID")
if err != nil {
t.Fatalf("get checkpoint error: %v", err)
}
-
if val != "testSeqNum" {
t.Fatalf("checkpoint exists expected %s, got %s", "testSeqNum", val)
}
+}
- client.Del(c.key("streamName", "shardID"))
+func Test_SetEmptySeqNum(t *testing.T) {
+ c, err := New("app")
+ if err != nil {
+ t.Fatalf("new checkpoint error: %v", err)
+ }
+
+ err = c.Set("streamName", "shardID", "")
+ if err == nil {
+ t.Fatalf("should not allow empty sequence number")
+ }
}
func Test_key(t *testing.T) {
- client := redis.NewClient(&redis.Options{Addr: defaultAddr})
-
- c := &Checkpoint{
- appName: "app",
- client: client,
+ c, err := New("app")
+ if err != nil {
+ t.Fatalf("new checkpoint error: %v", err)
}
- expected := "app:checkpoint:stream:shard"
+ want := "app:checkpoint:stream:shard"
- if val := c.key("stream", "shard"); val != expected {
- t.Fatalf("checkpoint exists expected %s, got %s", expected, val)
+ if got := c.key("stream", "shard"); got != want {
+ t.Fatalf("checkpoint key, want %s, got %s", want, got)
}
} | |
0197835acc0edd0bd82ea80b92055d85c1566bc4 | ---
+++
@@ -17,7 +17,7 @@
}
func (raw *RawAction) Verify(context *YaibContext) error {
- if raw.Source != "rootdir" {
+ if raw.Source != "filesystem" {
return errors.New("Only suppport sourcing from filesystem")
}
| |
f6045b9c65448252deb924ff3422fe61b8651d7f | ---
+++
@@ -31,3 +31,9 @@
result.Point.Lng())
}
}
+
+func BenchmarkGeocode(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ geocode("1600 amphitheatre parkway", new(geo.GoogleGeocoder))
+ }
+} | |
854ef6c2e241d628c6d221b6b015bcfcbe77f3bd | ---
+++
@@ -19,7 +19,7 @@
Link("account_transactions", "/accounts/{address}/transactions{?cursor,limit,order}").
Link("transaction", "/transactions/{hash}").
Link("transactions", "/transactions{?cursor,limit,order}").
- Link("orderbook", "/orderbooks{?base_type,base_code,base_issuer,counter_type,counter_code,counter_issuer}").
+ Link("order_book", "/order_book{?selling_type,selling_code,selling_issuer,buying_type,buying_code,buying_issuer}").
Link("metrics", "/metrics").
Link("friendbot", "/friendbot{?addr}"),
} | |
0e85cffe47bf79b03e6e941c93effa39c1005710 | ---
+++
@@ -3,14 +3,13 @@
import (
"fmt"
- "github.com/camd67/moebot/moebot_bot/bot/permissions"
-
"github.com/camd67/moebot/moebot_bot/util/db"
)
type TimerCommand struct {
- ComPrefix string
- Checker permissions.PermissionChecker
+}
+
+func (tc *TimerCommand) Execute(pack *CommPackage) {
}
func (tc *TimerCommand) GetPermLevel() db.Permission { | |
9d8192804c0d609eef2d7956348358615720a0f3 | ---
+++
@@ -3,8 +3,6 @@
import (
"os"
"path"
-
- uuid "github.com/satori/go.uuid"
)
// VersionControl is the interface for specific
@@ -27,7 +25,7 @@
// AddSource for SystemSCM will gather source code
// and then save the files to the local filesystem
func (scm SystemSCM) AddSource(repo *SourceRepository) error {
- location := createSourceFolder(repo.ProjectName)
+ location := path.Join(os.Getenv("GOPATH"), "repos", repo.ProjectName)
err := scm.VersionControl.CloneSource(repo, location)
repo.SourceLocation = location
if err != nil {
@@ -45,9 +43,3 @@
}
return nil
}
-
-func createSourceFolder(project string) string {
- uuid := uuid.NewV4()
- sourceFolder := path.Join(os.Getenv("GOPATH"), "/repos/", project+"_"+uuid.String())
- return sourceFolder
-} | |
565d8da8471ee5149b65b343eb68ff660e45be0a | ---
+++
@@ -1,6 +1,7 @@
package server
import (
+ "errors"
"net/http"
"github.com/heroku/busl/assets"
@@ -8,6 +9,8 @@
"github.com/heroku/busl/storage"
"github.com/heroku/busl/util"
)
+
+var errNoContent = errors.New("No Content")
func handleError(w http.ResponseWriter, r *http.Request, err error) {
if err == broker.ErrNotRegistered || err == storage.ErrNoStorage {
@@ -18,6 +21,12 @@
http.Error(w, message, http.StatusNotFound)
+ } else if err == errNoContent {
+ // As indicated in the w3 spec[1] an SSE stream
+ // that's already done should return a `204 No Content`
+ // [1]: http://www.w3.org/TR/2012/WD-eventsource-20120426/
+ w.WriteHeader(http.StatusNoContent)
+
} else if err != nil {
util.CountWithData("server.handleError", 1, "error=%s", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError) | |
4531cf31257db14549af03dff989cc5c4bc55b55 | ---
+++
@@ -26,9 +26,9 @@
// Error implements error interface.
func (m *MultiError) Error() string {
- var formattedError []string
- for _, e := range m.errs {
- formattedError = append(formattedError, e.Error())
+ formattedError := make([]string, len(m.errs))
+ for i, e := range m.errs {
+ formattedError[i] = e.Error()
}
return strings.Join(formattedError, "\n") | |
181e07d329617cc3d30f8dc1d1a56fb830b584d4 | ---
+++
@@ -1,14 +1,34 @@
package main
+import (
+ "log"
+ "net/http"
+ "time"
+)
+
+import "expvar"
+import _ "net/http/pprof"
+
+var spinCount = expvar.NewInt("SpinCount")
+
func main() {
+
+ go func() {
+ log.Println("Starting HTTP")
+ log.Println(http.ListenAndServe("localhost:6060", nil))
+ }()
+
+ log.Println("Starting spin")
for {
spin()
+ spinCount.Add(1)
+ time.Sleep(0)
}
}
func spin() {
sum := 0
- for i:=0;i<9999999;i++ {
+ for i:=0;i<1000;i++ {
sum += i
sum -= i
} | |
153ce8b0a263edce819a5df534ff89a100c5454a | ---
+++
@@ -4,10 +4,13 @@
"github.com/dustin/go-humanize"
"time"
"strings"
+ "math"
)
func HumanTime(time time.Time) string {
original := humanize.Time(time)
parts := strings.Split(original, " ")
- return parts[0] + " " + parts[1]
+ length := int(math.Min(float64(len(parts)), 2)) // now / x minutes
+ parts = parts[:length]
+ return strings.Join(parts, " ")
} | |
27c646fdcceadb08aebec333c75cf17183d9d51b | ---
+++
@@ -6,21 +6,21 @@
func TestExtract(t *testing.T) {
Seed(123)
- outputs := make([]int, 10)
- for i := 0; i < 10; i++ {
- outputs[i] = Extract()
+ output0 := Extract()
+
+ Seed(123)
+ output1 := Extract()
+
+ Seed(321)
+ output2 := Extract()
+
+ // same seeds should result in same first result
+ if output0 != output1 {
+ t.Fail()
}
- for i, num := range outputs {
- for j, otherNum := range outputs {
- if j == i {
- continue
- }
- if num == otherNum {
- // assuming that there shouldn't be a repeated number
- // in 10 samples
- t.Fail()
- }
- }
+ // different seeds should result in different first result
+ if output2 == output1 {
+ t.Fail()
}
} | |
43da41826b4d1ca50d8fa3a218032c380ef4423f | ---
+++
@@ -20,7 +20,9 @@
if rval := recover(); rval != nil {
debug.PrintStack()
rvalStr := fmt.Sprint(rval)
- packet := raven.NewPacket(rvalStr, raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)))
+ packet := raven.NewPacket(rvalStr,
+ raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)),
+ raven.NewHttp(c.Request))
client.Capture(packet, flags)
c.AbortWithStatus(http.StatusInternalServerError)
} | |
f139d4b750a622b558a5d06d8b8b2ef24da1a600 | ---
+++
@@ -40,3 +40,15 @@
}
return metrics
}
+
+// Return a map of MX4JMetric structs keyed by their human readable name field.
+func RegistryGetHRMap() map[string]MX4JMetric {
+ reglock.RLock()
+ defer reglock.RUnlock()
+
+ metrics := make(map[string]MX4JMetric)
+ for _, mm := range registry {
+ metrics[mm.HumanName] = *mm
+ }
+ return metrics
+} | |
b7bef4feabe2966a326af0d7d0d9508f104e489f | ---
+++
@@ -2,7 +2,12 @@
import (
"fmt"
+ "os"
"time"
+)
+
+var (
+ source = os.Getenv("SHH_SOURCE")
)
type Measurement struct {
@@ -12,5 +17,9 @@
}
func (m *Measurement) String() string {
- return fmt.Sprintf("when=%s measure=%s val=%s", m.When.Format(time.RFC3339Nano), m.What, m.Value)
+ msg := fmt.Sprintf("when=%s measure=%s val=%s", m.When.Format(time.RFC3339Nano), m.What, m.Value)
+ if source != "" {
+ return fmt.Sprintf("%s source=%s", msg, source)
+ }
+ return msg
} | |
6c75828f717b728985782256eb0d22906c8f40d4 | ---
+++
@@ -4,7 +4,6 @@
"flag"
"fmt"
"log"
- "net"
"github.com/umahmood/geoip"
)
@@ -13,15 +12,8 @@
var ip string
func init() {
- flag.StringVar(&ip, "ip", "", "IP to geo locate can be v4 or v6 address.")
+ flag.StringVar(&ip, "ip", "", "IP to geo locate can be v4/v6 address or domain name.")
flag.Parse()
-
- if ip != "" {
- addr := net.ParseIP(ip)
- if addr == nil {
- log.Fatalln("not a valid IP address.")
- }
- }
}
func main() { | |
a71884087fbfebe148542030ff6e6ab4bff40d5d | ---
+++
@@ -7,7 +7,28 @@
"strings"
)
+var version = "0.1.0"
+var helpMsg = `NAME:
+ ext - An interface for command extensions
+USAGE:
+ ext commands...
+`
+
func main() {
+ if len(os.Args) < 2 {
+ fmt.Println(helpMsg)
+ os.Exit(1)
+ }
+
+ switch os.Args[1] {
+ case "-h", "--help":
+ fmt.Println(helpMsg)
+ os.Exit(0)
+ case "-v", "--version":
+ fmt.Println(version)
+ os.Exit(0)
+ }
+
extArgs, err := LookupExtCmd(os.Args[1:])
if err != nil { | |
17e917ddda383c08ba0a79e006a2659ac93508f9 | ---
+++
@@ -17,6 +17,16 @@
p.Connection = conn
}
+// GetDiskConnectionByStr ディスク接続方法 取得
+func (p *propDiskConnection) GetDiskConnectionByStr() string {
+ return string(p.Connection)
+}
+
+// SetDiskConnectionByStr ディスク接続方法 設定
+func (p *propDiskConnection) SetDiskConnectionByStr(conn string) {
+ p.Connection = EDiskConnection(conn)
+}
+
// GetDiskConnectionOrder コネクション順序 取得
func (p *propDiskConnection) GetDiskConnectionOrder() int {
return p.ConnectionOrder |
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.