_id stringlengths 40 40 | text stringlengths 81 2.19k | title stringclasses 1
value |
|---|---|---|
3a012e96adbf7c4ca1b90c3af0b3413d2e5393c5 | ---
+++
@@ -2,6 +2,7 @@
import (
"testing"
+ "log"
)
var mersennes = []int {
@@ -16,11 +17,19 @@
61,
}
-func TestPrime(t *testing.T) {
- for _, p := range mersennes {
- if !isPrime(p) {
- t.Errorf("p=[%d] should be calculated as prime", p)
-
+func TestPrimality(t *testing.T) {
+ p := 0
+ for i:= 2; i <= mersennes[len(mersennes) - 1]; i++ {
+ log.Printf("isPrime(%d) -> [%t]\n", i, isPrime(i))
+ if (mersennes[p] == i) {
+ if !isPrime(i) {
+ t.Errorf("[%d] should be calculated as prime", i)
+ }
+ p++
+ } else {
+ if isPrime(i) {
+ t.Errorf("[%d] should be calculated as composite", i)
+ }
}
}
} | |
8d93bc04ad598c95ce9901a73eb7a6840c49fd78 | ---
+++
@@ -18,6 +18,13 @@
}
return atl, nil
}
+func MustBuild(entries ...AtlasEntry) Atlas {
+ atl, err := Build(entries...)
+ if err != nil {
+ panic(err)
+ }
+ return atl
+}
func BuildEntry(typeHintObj interface{}) *BuilderCore {
return &BuilderCore{ | |
5bc6df835b7965590773feafa66145e319b0ec00 | ---
+++
@@ -20,6 +20,9 @@
connect.Start()
defer connect.KillAndPrint(t)
connect_id, err := WaitForID(connect)
+ if err != nil {
+ t.Fatal(err)
+ }
err = WaitForConnection(listen, connect_id)
if err != nil { | |
adfaa0fff200b4dfcab7c6c92b88359e02cdc497 | ---
+++
@@ -5,6 +5,7 @@
"github.com/rancher/norman/store/transform"
"github.com/rancher/norman/types"
+ "github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/settings"
)
@@ -13,13 +14,12 @@
Store: store,
Transformer: func(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}, opt *types.QueryOptions) (map[string]interface{}, error) {
v, ok := data["value"]
- value := os.Getenv(settings.GetENVKey(apiContext.ID))
+ value := os.Getenv(settings.GetENVKey(convert.ToString(data["id"])))
switch {
case value != "":
data["value"] = value
data["customized"] = false
data["source"] = "env"
-
case !ok || v == "":
data["value"] = data["default"]
data["customized"] = false | |
568a305bc9fdf370d7afab3bf46989182d73f1ce | ---
+++
@@ -3,8 +3,9 @@
import (
"bytes"
"fmt"
+ "os"
- "github.com/achilleasa/go-pathtrace/tracer/opencl"
+ "github.com/achilleasa/go-pathtrace/tracer/opencl/device"
"github.com/codegangsta/cli"
)
@@ -13,12 +14,17 @@
var storage []byte
buf := bytes.NewBuffer(storage)
- clPlatforms := opencl.GetPlatformInfo()
+ clPlatforms, err := device.GetPlatformInfo()
+ if err != nil {
+ logger.Printf("error: could not list devices: %s", err.Error())
+ os.Exit(1)
+ }
+
buf.WriteString(fmt.Sprintf("\nSystem provides %d opencl platform(s):\n\n", len(clPlatforms)))
for pIdx, platformInfo := range clPlatforms {
buf.WriteString(fmt.Sprintf("[Platform %02d]\n Name %s\n Version %s\n Profile %s\n Devices %d\n\n", pIdx, platformInfo.Name, platformInfo.Version, platformInfo.Profile, len(platformInfo.Devices)))
- for dIdx, device := range platformInfo.Devices {
- buf.WriteString(fmt.Sprintf(" [Device %02d]\n Name %s\n Type %s\n Speed %3.1f\n\n", dIdx, device.Name, device.Type, device.SpeedEstimate()))
+ for dIdx, dev := range platformInfo.Devices {
+ buf.WriteString(fmt.Sprintf(" [Device %02d]\n Name %s\n Type %s\n Speed %d GFlops\n\n", dIdx, dev.Name, dev.Type, dev.Speed))
}
}
| |
580ad7505adadb621210f3461feb343499fea35e | ---
+++
@@ -2,6 +2,7 @@
import (
"sync"
+ "time"
)
type Pool struct {
@@ -36,8 +37,17 @@
}
func (p Pool) worker() {
+ t := time.Now()
+ for {
- for {
+ since := time.Since(t)
+
+ if since.Minutes() > 5 {
+ p.wg.Done()
+ p.addWorker()
+ break
+ }
+
t, ok := <-p.Input
if !ok {
p.wg.Done()
@@ -46,6 +56,11 @@
v := t.Execute()
p.Output <- v
}
+}
+
+func (p Pool) addWorker() {
+ p.wg.Add(1)
+ go p.worker()
}
func NewPool(numberOfWorkers int) Pool {
@@ -57,8 +72,7 @@
p := Pool{jobs, results, &wg}
for w := 1; w <= numberOfWorkers; w++ {
- wg.Add(1)
- go p.worker()
+ p.addWorker()
}
return p
} | |
00ed6923f7c80857ccd4a21f9044290062a4fc12 | ---
+++
@@ -2,10 +2,15 @@
import "runtime"
+const dumpStackBufSizeInit = 4096
+
func DumpStack() string {
- buf := make([]byte, 1024)
- for runtime.Stack(buf, true) == cap(buf) {
+ buf := make([]byte, dumpStackBufSizeInit)
+ for {
+ n := runtime.Stack(buf, true)
+ if n < cap(buf) {
+ return string(buf[:n])
+ }
buf = make([]byte, cap(buf)*2)
}
- return string(buf)
} | |
8a51aa5909bab38a448e6b75058f87da6964d66e | ---
+++
@@ -24,7 +24,10 @@
}
func main() {
- log.Info("Start up")
+ log.WithFields(logrus.Fields{
+ "addr": *addr,
+ "debug": *debug,
+ }).Info("Start up")
i := make(chan message)
o := make(chan message)
n := newNetwork(i, o) | |
e97dffb5547e9b6c67c1feda609d31019876f455 | ---
+++
@@ -13,7 +13,7 @@
// Version returns the version/commit string.
func Version() string {
version, commit := VERSION, GITCOMMIT
- if commit == "" && version == "" {
+ if commit == "" || version == "" {
version, commit = majorRelease, "master"
}
return fmt.Sprintf("fsql version %v, built off %v", version, commit) | |
561b98067f90326cc3c1d73cab6836a2e50728cd | ---
+++
@@ -20,7 +20,7 @@
func (o *IpOpt) Set(val string) error {
ip := net.ParseIP(val)
if ip == nil {
- return fmt.Errorf("incorrect IP format")
+ return fmt.Errorf("%s is not an ip address", val)
}
(*o.IP) = net.ParseIP(val)
return nil | |
1d2eec1084c16165f49add5975e2e52c286e8daa | ---
+++
@@ -1,24 +1,27 @@
package leetcode
// 345. Reverse Vowels of a String
+
func reverseVowels(s string) string {
- res := make([]byte, 0)
- vowels := make([]byte, 0)
- for i := 0; i < len(s); i++ {
- switch b := s[i]; b {
- case 'a', 'i', 'u', 'e', 'o', 'A', 'I', 'U', 'E', 'O':
- vowels = append(vowels, b)
+ res := make([]byte, len(s))
+ copy(res, s)
+ vowels := map[byte]bool{'a': true, 'i': true, 'u': true, 'e': true, 'o': true, 'A': true, 'I': true, 'U': true, 'E': true, 'O': true}
+ for i, k := 0, len(s)-1; i < k; {
+ for i < k {
+ if _, ok := vowels[s[i]]; ok {
+ break
+ }
+ i++
}
- }
-
- for i, k := 0, len(vowels)-1; i < len(s); i++ {
- switch b := s[i]; b {
- case 'a', 'i', 'u', 'e', 'o', 'A', 'I', 'U', 'E', 'O':
- res = append(res, vowels[k])
+ for i < k {
+ if _, ok := vowels[s[k]]; ok {
+ break
+ }
k--
- default:
- res = append(res, b)
}
+ res[i], res[k] = res[k], res[i]
+ i++
+ k--
}
return string(res)
} | |
1cd89f72170a07c349cbc5b59d53424a57e78c21 | ---
+++
@@ -26,6 +26,8 @@
// When the request comes in, it will be passed to m1, then m2, then m3
// and finally, the given handler
// (assuming every middleware calls the following one)
+//
+// Then() treats nil as http.DefaultServeMux.
func (c Chain) Then(h http.Handler) http.Handler {
var final http.Handler
if h != nil { | |
2f58cbdf8834fe79c36f4cb5428151d0c559bbab | ---
+++
@@ -26,4 +26,12 @@
MaxShipCount: 0,
Owner: "gophie",
}
+ player Player = Player{
+ username: "gophie",
+ Color: Color{22, 22, 22},
+ TwitterID: "asdf",
+ HomePlanet: "planet.271_203",
+ ScreenSize: []int{1, 1},
+ ScreenPosition: []int{2, 2},
+ }
) | |
577a1de6d9c5cd8ec4cf4f8244a117de9eb33321 | ---
+++
@@ -1,22 +1,27 @@
package main
import (
+ "bufio"
"fmt"
"github.com/discoproject/goworker/jobutil"
"github.com/discoproject/goworker/worker"
"io"
- "io/ioutil"
+ "log"
"strings"
)
func Map(reader io.Reader, writer io.Writer) {
- body, err := ioutil.ReadAll(reader)
- jobutil.Check(err)
- strBody := string(body)
- words := strings.Fields(strBody)
- for _, word := range words {
- _, err := writer.Write([]byte(word + "\n"))
- jobutil.Check(err)
+ scanner := bufio.NewScanner(reader)
+ for scanner.Scan() {
+ text := scanner.Text()
+ words := strings.Fields(text)
+ for _, word := range words {
+ _, err := writer.Write([]byte(word + "\n"))
+ jobutil.Check(err)
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ log.Fatal("reading standard input:", err)
}
}
| |
60a9a19ae0fcc57f1e100341b3d3117f8652582d | ---
+++
@@ -15,7 +15,7 @@
var _ = Describe("Riak Broker Registers a Route", func() {
It("Allows users to access the riak-cs broker using a url", func() {
- endpointURL := "http://" + TestConfig.BrokerHost + "/v2/catalog"
+ endpointURL := "https://" + TestConfig.BrokerHost + "/v2/catalog"
// check for 401 because it means we reached the endpoint, but did not supply credentials.
// a failure would be a 404 | |
9b7cd3ec74750744ec31303411a216b35f712930 | ---
+++
@@ -9,8 +9,6 @@
import (
. "gopkg.in/check.v1"
- "path/filepath"
- "time"
)
type LispSuite struct {
@@ -19,18 +17,7 @@
var _ = Suite(&LispSuite{})
func (s *LispSuite) TestLisp(c *C) {
- files, err := filepath.Glob("tests/*.lsp")
- if err != nil {
- c.Fail()
- }
- VerboseTests = false
- startTime := time.Now()
- for _, f := range files {
- c.Logf("Loading %s\n", f)
- _, err := ProcessFile(f)
- if err != nil {
- c.Logf("Error: %s\n", err)
- }
- }
- PrintTestResults(time.Since(startTime))
+ testCommand := "(run-all-tests \"tests\")"
+ ProcessFile("testing.lsp")
+ ParseAndEval(testCommand)
} | |
c6ed4019f34a6de425c0023b50ce6df5569e1aba | ---
+++
@@ -10,13 +10,10 @@
func main() {
server := dictd.NewServer("pault.ag")
- levelDB, err := database.NewLevelDBDatabase("/home/tag/jargon.ldb", "jargon file")
+ // levelDB, err := database.NewLevelDBDatabase("/home/tag/jargon.ldb", "jargon file")
+ urbanDB := database.UrbanDictionaryDatabase{}
- if err != nil {
- log.Fatal(err)
- }
-
- server.RegisterDatabase(levelDB, "jargon")
+ server.RegisterDatabase(&urbanDB, "urban")
link, err := net.Listen("tcp", ":2628")
if err != nil { | |
c56542adca38e4f51055c08dc741d5a48b657c9f | ---
+++
@@ -13,6 +13,10 @@
{"AAAA", "AABB", 2},
{"BAAA", "AAAA", 1},
{"BAAA", "CCCC", 4},
+ {"karolin", "kathrin", 3},
+ {"karolin", "kerstin", 3},
+ {"1011101", "1001001", 2},
+ {"2173896", "2233796", 3},
}
for _, c := range cases { | |
bb6b4cda0ff74856f32ecfc7272064880fa0caea | ---
+++
@@ -3,37 +3,36 @@
package main
import (
- "fmt"
- "math/rand"
- "time"
+ "fmt"
+ "math/rand"
+ "time"
)
-func shuffle(a []int) []int {
- rand.Seed(time.Now().UnixNano())
- for i := len(a) - 1; i > 0; i-- {
- j := rand.Intn(i + 1)
- a[i], a[j] = a[j], a[i]
- }
- return a
-}
-
-func is_sorted(a []int) bool {
- for i := 0; i < len(a)-1; i++ {
- if a[i+1] < a[i] {
- return false
- }
- }
- return true
-}
-
-func bogo_sort(a *[]int) {
- for !is_sorted(*a) {
- *a = shuffle(*a)
+func shuffle(a *[]int) {
+ for i := len(*a) - 1; i > 0; i-- {
+ j := rand.Intn(i + 1)
+ (*a)[i], (*a)[j] = (*a)[j], (*a)[i]
}
}
+func isSorted(a []int) bool {
+ for i := 0; i < len(a)-1; i++ {
+ if a[i+1] < a[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func bogoSort(a *[]int) {
+ for !isSorted(*a) {
+ shuffle(a)
+ }
+}
+
func main() {
- a := []int{1, 3, 4, 2}
- bogo_sort(&a)
- fmt.Println(a)
+ rand.Seed(time.Now().UnixNano())
+ a := []int{1, 3, 4, 2}
+ bogoSort(&a)
+ fmt.Println(a)
} | |
726c5ae6ebedd85c330efb3a263d252f6a30b9a9 | ---
+++
@@ -8,6 +8,7 @@
type ChannelData struct {
ChannelNumber uint16
+ Length uint16
Data []byte
}
@@ -19,7 +20,8 @@
return &ChannelData{
ChannelNumber: cn,
- Data: packet,
+ Length: getChannelLength(packet),
+ Data: packet[4:],
}, nil
}
@@ -33,3 +35,7 @@
}
return cn, nil
}
+
+func getChannelLength(header []byte) uint16 {
+ return binary.BigEndian.Uint16(header[2:])
+} | |
ed45ca9d1da5064115add1172d59d7ea04e5237d | ---
+++
@@ -1,4 +1,10 @@
package microsoft
+
+import (
+ "testing"
+
+ "github.com/st3v/translator"
+)
// func TestTranslate(t *testing.T) {
// api := NewTranslator("", "")
@@ -14,3 +20,45 @@
// t.Errorf("Unexpected translation: %s", translation)
// }
// }
+
+func TestApiLanguages(t *testing.T) {
+ expectedLanguages := []translator.Language{
+ translator.Language{
+ Code: "en",
+ Name: "English",
+ },
+ translator.Language{
+ Code: "de",
+ Name: "Spanish",
+ },
+ translator.Language{
+ Code: "en",
+ Name: "English",
+ },
+ }
+
+ api := &api{
+ languageProvider: &languageProvider{
+ languages: expectedLanguages,
+ },
+ }
+
+ actualLanguages, err := api.Languages()
+ if err != nil {
+ t.Fatalf("Unexpected error: %s", err)
+ }
+
+ if len(actualLanguages) != len(expectedLanguages) {
+ t.Fatalf("Unexpected number of languages: %q", actualLanguages)
+ }
+
+ for i := range expectedLanguages {
+ if actualLanguages[i].Code != expectedLanguages[i].Code {
+ t.Fatalf("Unexpected language code '%s'. Expected '%s'", actualLanguages[i].Code, expectedLanguages[i].Code)
+ }
+
+ if actualLanguages[i].Name != expectedLanguages[i].Name {
+ t.Fatalf("Unexpected language code '%s'. Expected '%s'", actualLanguages[i].Name, expectedLanguages[i].Name)
+ }
+ }
+} | |
6f24c2f9b2eb585b30f1cb3fa5e147875bbd0358 | ---
+++
@@ -23,7 +23,7 @@
utils.Cloudfockerhome() + "/result": "/tmp/result",
utils.Cloudfockerhome() + "/buildpacks": "/tmp/cloudfockerbuildpacks",
utils.Cloudfockerhome() + "/cache": "/tmp/cache",
- utils.Cloudfockerhome() + "/focker": "/fock",
+ utils.Cloudfockerhome() + "/focker": "/focker",
},
Command: []string{"/focker/fock", "stage"},
} | |
431fa015d71a78abafdb71b8ae659088893caa98 | ---
+++
@@ -1,14 +1,21 @@
package main
+
+type tiledata struct {
+ Width int `json:"width"`
+ Height int `json:"height,omitempty"`
+ ScaleFactors []int `json:"scaleFactors"`
+}
// IIIFInfo represents the simplest possible data to provide a valid IIIF
// information JSON response
type IIIFInfo struct {
- Context string `json:"@context"`
- ID string `json:"@id"`
- Protocol string `json:"protocol"`
- Width int `json:"width"`
- Height int `json:"height"`
- Profile []string `json:"profile"`
+ Context string `json:"@context"`
+ ID string `json:"@id"`
+ Protocol string `json:"protocol"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+ Profile []string `json:"profile"`
+ Tiles []tiledata `json:"tiles"`
}
// Creates the default structure for converting to the IIIF Information JSON.
@@ -18,5 +25,10 @@
Context: "http://iiif.io/api/image/2/context.json",
Protocol: "http://iiif.io/api/image",
Profile: []string{"http://iiif.io/api/image/2/level1.json"},
+ Tiles: []tiledata{
+ tiledata{Width: 256, ScaleFactors: []int{1, 2, 4, 8, 16, 32, 64}},
+ tiledata{Width: 512, ScaleFactors: []int{1, 2, 4, 8, 16, 32, 64}},
+ tiledata{Width: 1024, ScaleFactors: []int{1, 2, 4, 8, 16, 32, 64}},
+ },
}
} | |
6aae5a89aae5a2de94251b367c6062d733d36db9 | ---
+++
@@ -28,4 +28,9 @@
test.Equals(t, expectedTimestamp, req.Timestamp)
test.Equals(t, "Hi, my name is Sam!", req.Result.ResolvedQuery)
+ test.Equals(t, "agent", req.Result.Source)
+ test.Equals(t, "greetings", req.Result.Action)
+ test.Equals(t, false, req.Result.ActionIncomplete)
+ test.Equals(t, "Sam", req.Result.Parameters.Parameters["user_name"])
+
} | |
5cb47021ac15f00e54151de0c7aefa03461a980c | ---
+++
@@ -21,8 +21,10 @@
if len(b) == 0 {
return ""
}
- return *(*string)(unsafe.Pointer(&reflect.StringHeader{
- uintptr(unsafe.Pointer(&b[0])),
- len(b),
- }))
+ // See https://github.com/golang/go/issues/40701.
+ var s string
+ hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
+ hdr.Data = uintptr(unsafe.Pointer(&b[0]))
+ hdr.Len = len(b)
+ return s
} | |
50f3f315518d56a8eea76c3d120cd275c6b6d41c | ---
+++
@@ -7,9 +7,10 @@
"time"
"github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/common/math"
)
-var pow256 = common.BigPow(2, 256)
+var pow256 = math.BigPow(2, 256)
func Random() string {
min := int64(100000000000000)
@@ -31,5 +32,5 @@
func TargetHexToDiff(targetHex string) *big.Int {
targetBytes := common.FromHex(targetHex)
- return new(big.Int).Div(pow256, common.BytesToBig(targetBytes))
+ return new(big.Int).Div(pow256, new(big.Int).SetBytes(targetBytes))
} | |
820964a2e18b16020bd780b86e7722350d7163f1 | ---
+++
@@ -2,6 +2,7 @@
import (
"fmt"
+ "os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
@@ -9,7 +10,18 @@
)
func main() {
- svc := ec2.New(session.New(), &aws.Config{Region: aws.String("us-west-2")})
+ if len(os.Args) != 2 {
+ fmt.Println("Usage:\n\tmain region_name")
+ os.Exit(-1)
+ }
+
+ region := os.Args[1]
+ if region == "" {
+ fmt.Println("Usage:\n\tmain region_name")
+ os.Exit(-1)
+ }
+
+ svc := ec2.New(session.New(), &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeInstances(nil)
if err != nil { | |
837fe23ceac180bd7c61482ed2c570e89b821cda | ---
+++
@@ -6,23 +6,28 @@
"time"
)
+func colonGenerator() <-chan string {
+ c := make(chan string)
+ go func() {
+ for {
+ c <- ":"
+ c <- " "
+ }
+ }()
+ return c
+}
+
func main() {
wall, _ := pixelutils.PixelPusher()
pixel := pixelutils.NewPixel()
bigPixel := pixelutils.DimensionChanger(pixel, 5*4, 18)
textPixel := pixelutils.NewImageWriter(bigPixel, pixelutils.Green)
- colon := ":"
+ colons := colonGenerator()
for {
pixelutils.Empty(bigPixel)
- if colon == ":" {
- colon = " "
- } else {
- colon = ":"
- }
-
textPixel.Cls()
- fmt.Fprintf(textPixel, "%02d%s%02d", time.Now().Hour(), colon, time.Now().Minute())
+ fmt.Fprintf(textPixel, "%02d%s%02d", time.Now().Hour(), <-colons, time.Now().Minute())
wall <- pixel
time.Sleep(500 * time.Millisecond)
} | |
d96f724679d653de97198206f7ecd77ae7c3b876 | ---
+++
@@ -3,12 +3,21 @@
package netfs
import (
- "errors"
+ "os/exec"
+ "fmt"
+
+ "github.com/jcelliott/lumber"
)
// reloadServer reloads the nfs server with the new export configuration
func reloadServer() error {
-
- // TODO: figure out how to do this :/
- return errors.New("Reloading an NFS server is not yet implemented on linux")
+ // reload nfs server
+ // TODO: provide a clear error message for a direction to fix
+ cmd := exec.Command("exportfs", "-ra")
+ if b, err := cmd.CombinedOutput(); err != nil {
+ lumber.Debug("update: %s", b)
+ return fmt.Errorf("update: %s %s", b, err.Error())
+ }
+
+ return nil
} | |
068da3ff0d0e1ac5590458d5d814b6c90a2edb55 | ---
+++
@@ -1,7 +1,6 @@
package path
import (
- "fmt"
"github.com/aybabtme/graph"
)
@@ -18,6 +17,14 @@
}
func BuildTremauxDFS(g graph.Graph, from int) PathFinder {
+
+ if from < 0 {
+ panic("Can't start DFS from vertex v < 0")
+ }
+
+ if from >= g.V() {
+ panic("Can't start DFS from vertex v >= total vertex count")
+ }
t := TremauxDFS{
g: g, | |
45a70b6a9b5395f9ecbe72919c714e81494c864f | ---
+++
@@ -5,12 +5,33 @@
"strings"
)
+func parseVaryHeaders(values []string) []string {
+ var headers []string
+ for _, v := range values {
+ for _, h := range strings.Split(v, ",") {
+ h = strings.TrimSpace(h)
+ if h != "" {
+ headers = append(headers, h)
+ }
+ }
+ }
+ return headers
+}
+
func FixupCORSHeaders(downstream http.ResponseWriter, upstream *http.Response) {
hasCORSHeaders := false
- for name := range upstream.Header {
+ for name, values := range upstream.Header {
if strings.HasPrefix(name, "Access-Control-") {
hasCORSHeaders = true
break
+ }
+ if name == "Vary" {
+ varyHeaders := parseVaryHeaders(values)
+ for _, h := range varyHeaders {
+ if http.CanonicalHeaderKey(h) == "Origin" {
+ hasCORSHeaders = true
+ }
+ }
}
}
@@ -21,9 +42,26 @@
// Upstream has provided CORS header; upstream will manage all CORS headers
// Remove existing CORS headers from response to downstream
headers := downstream.Header()
- for name := range headers {
+ for name, values := range headers {
if strings.HasPrefix(name, "Access-Control-") {
headers.Del(name)
}
+ // Delete 'Vary: Origin' header
+ if name == "Vary" {
+ varyHeaders := parseVaryHeaders(values)
+ n := 0
+ for _, h := range varyHeaders {
+ if http.CanonicalHeaderKey(h) != "Origin" {
+ varyHeaders[n] = h
+ n++
+ }
+ }
+ varyHeaders = varyHeaders[:n]
+ if len(varyHeaders) > 0 {
+ headers[name] = []string{strings.Join(varyHeaders, ",")}
+ } else {
+ delete(headers, name)
+ }
+ }
}
} | |
12a6d86a2f7fc26d100cbb6118e91c7f2eab6b67 | ---
+++
@@ -8,12 +8,12 @@
"strings"
)
-// a function that provides a means to retrieve a token
-type TokenGetter func() (string, error)
+// Token Getter is a function that can retrieve a token
+type tokenGetter func() (string, error)
// goes through the provided TokenGetter chain and stops once one reports
// a non-"" value. If any produce errors it'll wrap those up and return 'em.
-func getTokenFromChain(getters ...TokenGetter) (string, error) {
+func getTokenFromChain(getters ...tokenGetter) (string, error) {
errs := make([]string, len(getters))
for _, g := range getters {
@@ -48,9 +48,7 @@
// checks the "-token" flag on the CLI
func getTokenFromCli() (string, error) {
- var str *string
-
- flag.StringVar(str, "token", "", "The token to use with the DO API")
+ str := flag.String("token", "", "The token to use with the DO API")
flag.Parse()
return *str, nil | |
a781391752ed7339e8ae7d298aafe1b4ee6be5b9 | ---
+++
@@ -16,13 +16,12 @@
import "github.com/hajimehoshi/ebiten/v2/internal/driver"
-// A CursorModeType represents
+// CursorModeType represents
// a render and coordinate mode of a mouse cursor.
type CursorModeType int
-// Cursor Modes
const (
- CursorModeVisible = CursorModeType(driver.CursorModeVisible)
- CursorModeHidden = CursorModeType(driver.CursorModeHidden)
- CursorModeCaptured = CursorModeType(driver.CursorModeCaptured)
+ CursorModeVisible CursorModeType = CursorModeType(driver.CursorModeVisible)
+ CursorModeHidden CursorModeType = CursorModeType(driver.CursorModeHidden)
+ CursorModeCaptured CursorModeType = CursorModeType(driver.CursorModeCaptured)
) | |
2e998b3ba8936ed33b06ee4f0e166315a4b720f3 | ---
+++
@@ -8,19 +8,16 @@
var mySession = &SessionMock{}
-func Example_dump() {
- var rows, _ = mySession.QuerySliceMap("select * from users")
+func ExampleBatch() {
+ var b = mySession.QueryBatch(BatchLogged)
- for _, row := range rows {
- fmt.Println(row)
- }
+ b.Query("insert into users (id, name) values (123, 'me')")
+ b.Query("insert into users (id, name) values (456, 'you')")
+
+ b.Exec()
}
-func Example_insert() {
- mySession.QueryExec("insert into users (id, name) values (123, 'me')")
-}
-
-func Example_print() {
+func ExampleIterator() {
var i = mySession.QueryIterator("select * from users")
for done := false; !done; {
@@ -29,6 +26,14 @@
done = i.ScanMap(m)
fmt.Println(m)
+ }
+}
+
+func ExampleSession() {
+ var rows, _ = mySession.QuerySliceMap("select * from users")
+
+ for _, row := range rows {
+ fmt.Println(row)
}
}
| |
e2818f656a7063a988bccf1a97490e5e78bfa00c | ---
+++
@@ -18,9 +18,9 @@
func (req ApiEndpointRequirement) Execute() (success bool) {
if req.config.ApiEndpoint() == "" {
- loginTip := terminal.CommandColor(fmt.Sprintf("%s api", cf.Name()))
- targetTip := terminal.CommandColor(fmt.Sprintf("%s target", cf.Name()))
- req.ui.Say("No API endpoint targeted. Use '%s' or '%s' to target an endpoint.", loginTip, targetTip)
+ loginTip := terminal.CommandColor(fmt.Sprintf("%s login", cf.Name()))
+ apiTip := terminal.CommandColor(fmt.Sprintf("%s api", cf.Name()))
+ req.ui.Say("No API endpoint targeted. Use '%s' or '%s' to target an endpoint.", loginTip, apiTip)
return false
}
return true | |
28610a9a426fac3ae88b812897b1c1a540112071 | ---
+++
@@ -19,7 +19,7 @@
"os"
"strings"
- "github.com/syncthing/syncthing/internal/logger"
+ "github.com/calmh/logger"
)
var ( | |
0a6fa2bc146c5e8684a1aa23092c6fc9bff19de2 | ---
+++
@@ -19,10 +19,13 @@
TargetDir string `env:"TARGET_DIR,default=./public"`
}
+// Left as a global for now for the sake of convenience, but it's not used in
+// very many places and can probably be refactored as a local if desired.
+var conf Conf
+
func main() {
sorg.InitLog(false)
- var conf Conf
err := envdecode.Decode(&conf)
if err != nil {
log.Fatal(err) | |
abcb562402dffca3006b3e20273841c0293c21cf | ---
+++
@@ -19,7 +19,7 @@
// checking for a false positive.
type FalsePositiveMatchCriteria struct {
PluginID int
- Port int
+ Ports []int
Protocol string
DescriptionRegexp []string
CheckIfIsNotDefined bool | |
2f53b95e6c61e2e08e23ac3f8086b11a8f86b718 | ---
+++
@@ -17,21 +17,20 @@
}
func TestInteraction(t *testing.T) {
- // The -l flag is a line-buffered mode, and it is required for interaction.
- command := exec.Command("sed", "-le", "s/xxx/zzz/")
+ command := exec.Command("cat")
raw_stdin, _ := command.StdinPipe()
stdin := bufio.NewWriter(raw_stdin)
raw_stdout, _ := command.StdoutPipe()
stdout := bufio.NewReader(raw_stdout)
command.Start()
for i := 0; i < 3; i++ {
- size, _ := stdin.WriteString("aaaxxxccc\n")
- if size != 10 {
- t.Errorf("Output size should be 10, but %#v.", size)
+ size, _ := stdin.WriteString("abc\n")
+ if size != 4 {
+ t.Errorf("Output size should be 4, but %#v.", size)
}
stdin.Flush()
actual, _ := stdout.ReadString('\n')
- expected := "aaazzzccc\n"
+ expected := "abc\n"
if actual != expected {
t.Errorf("Output should be %#v, but %#v.", expected, actual)
} | |
c0885bdf4ad7dc8622133cdc3176c7dca64afa9c | ---
+++
@@ -15,7 +15,7 @@
}
func main() {
- f, err := os.Open("/home/user/GoCode/src/html/SimpleTemplate.html")
+ f, err := os.Open("src/html/SimpleTemplate.html")
defer f.Close()
if err != nil {
fmt.Println(err) | |
2c1a2293b76c1edaa42a28fa4aaf8a4ff6fcbc24 | ---
+++
@@ -1,18 +1,16 @@
-package controllers
-
package controllers
import (
- "github.com/astaxie/beego"
+ "github.com/astaxie/beego"
)
type ImageController struct {
- beego.Controller
+ beego.Controller
}
func (this *ImageController) Prepare() {
- this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Version", beego.AppConfig.String("Version"))
- this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Standalone", beego.AppConfig.String("Standalone"))
+ this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Version", beego.AppConfig.String("Version"))
+ this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Standalone", beego.AppConfig.String("Standalone"))
}
func (this *ImageController) GETPrivateLayer() {
@@ -52,5 +50,5 @@
}
func (this *ImageController) GETFiles() {
-
+
} | |
f3c6187e8df2ee60caaf07851535588a20ab14c1 | ---
+++
@@ -1,38 +1,55 @@
package server
import (
- "github.com/xgfone/go-tools/atomics"
+ "sync"
+
"github.com/xgfone/go-tools/lifecycle"
)
var (
manager = lifecycle.GetDefaultManager()
- shutdowned = atomics.NewBool()
+ locked = new(sync.Mutex)
+ shutdowned = false
shouldShutdown = make(chan bool, 1)
)
// RunForever runs for ever.
func RunForever() {
- if shutdowned.Get() {
+ locked.Lock()
+ if shutdowned {
+ locked.Unlock()
panic("The server has been shutdowned")
}
+ locked.Unlock()
+
<-shouldShutdown
manager.Stop()
}
// Shutdown shutdowns the server gracefully.
func Shutdown() {
- shutdowned.SetTrue()
+ locked.Lock()
+ defer locked.Unlock()
+ if shutdowned {
+ return
+ }
+
+ shutdowned = true
shouldShutdown <- true
}
// IsShutdowned returns whether the server has been shutdowned.
-func IsShutdowned() bool {
- return shutdowned.Get()
+func IsShutdowned() (yes bool) {
+ locked.Lock()
+ yes = shutdowned
+ locked.Unlock()
+ return
}
// RegisterManager replaces the default lifecycle manager.
// The default manager is the default global manager in the package lifecycle.
func RegisterManager(m *lifecycle.Manager) {
+ locked.Lock()
manager = m
+ locked.Unlock()
} | |
07b04c7a0112bcb7430f4277772d03a918963f51 | ---
+++
@@ -2,10 +2,10 @@
import (
"github.com/dgryski/go-farm"
- "github.com/lazybeaver/xorshift"
+ "github.com/dgryski/go-pcgr"
)
-var rnd = xorshift.NewXorShift64Star(42)
+var rnd = pcgr.Rand{0x0ddc0ffeebadf00d, 0xcafebabe}
func randFloat() float64 {
return float64(rnd.Next()%10e5) / 10e5 | |
5300c55a73f678fda2830a9909c8df1c55b257b2 | ---
+++
@@ -1,38 +1,36 @@
package main
-import ()
+// func ExampleCliNoArguments() {
+// repos := map[string]Repo{
+// "zathura": Repo{},
+// "test": Repo{},
+// "gamma": Repo{},
+// }
-func ExampleCliNoArguments() {
- repos := map[string]Repo{
- "zathura": Repo{},
- "test": Repo{},
- "gamma": Repo{},
- }
+// app := BuildCLI(repos, Config{})
+// args := make([]string, 1)
- app := BuildCLI(repos, Config{})
- args := make([]string, 1)
+// app.Run(args)
+// // Output: gamma
+// // test
+// // zathura
+// }
- app.Run(args)
- // Output: gamma
- // test
- // zathura
-}
+// func ExampleCliPrintItem() {
+// repos := map[string]Repo{
+// "joanjett": Repo{
+// Info: map[string]Info{
+// "bad_reputation": Info{
+// Type: "info",
+// Body: "I don't give a damn about my bad reputation!",
+// },
+// },
+// },
+// }
-func ExampleCliPrintItem() {
- repos := map[string]Repo{
- "joanjett": Repo{
- Info: map[string]Info{
- "bad_reputation": Info{
- Type: "info",
- Body: "I don't give a damn about my bad reputation!",
- },
- },
- },
- }
+// app := BuildCLI(repos, Config{})
+// args := []string{"/go/bin/sagacity", "joanjett", "bad_reputation"}
- app := BuildCLI(repos, Config{})
- args := []string{"/go/bin/sagacity", "joanjett", "bad_reputation"}
-
- app.Run(args)
- // Output: I don't give a damn about my bad reputation!
-}
+// app.Run(args)
+// // Output: I don't give a damn about my bad reputation!
+// } | |
b059059a68b83f26aeda05e0cabc63423f6424dc | ---
+++
@@ -13,11 +13,11 @@
var (
FailBase = 0
FailType = 1
+ Scolds = map[int]string{
+ FailBase: "Expected to be `%+v`, but actual `%+v`\n",
+ FailType: "Expectec type `%+v`, but actual `%T`\n",
+ }
)
-var Scolds = map[int]string{
- FailBase: "Expected to be `%+v`, but actual `%+v`\n",
- FailType: "Expectec type `%+v`, but actual `%T`\n",
-}
func Expect(t *testing.T, actual interface{}) *ProxyTestee {
return &ProxyTestee{t: t, actual: actual} | |
0194aff9e0cae475df41f9d4bd4b650e630ce65f | ---
+++
@@ -1,6 +1,49 @@
package meta
-// CueSheet contains the track information of a cue sheet.
+// A CueSheet describes how tracks are layed out within a FLAC stream.
//
-// https://www.xiph.org/flac/format.html#metadata_block_cuesheet
-type CueSheet struct{}
+// ref: https://www.xiph.org/flac/format.html#metadata_block_cuesheet
+type CueSheet struct {
+ // Media catalog number.
+ MCN string
+ // Number of lead-in samples. This field only has meaning for CD-DA cue
+ // sheets; for other uses it should be 0. Refer to the spec for additional
+ // information.
+ NLeadInSamples uint64
+ // Specifies if the cue sheet corresponds to a Compact Disc.
+ IsCompactDisc bool
+ // One or more tracks. The last track of a cue sheet is always the lead-out
+ // track.
+ Tracks []CueSheetTrack
+}
+
+// CueSheetTrack contains the start offset of a track and other track specific
+// metadata.
+type CueSheetTrack struct {
+ // Track offset in samples, relative to the beginning of the FLAC audio
+ // stream.
+ Offset uint64
+ // Track number; never 0, always unique.
+ Num uint8
+ // International Standard Recording Code; empty string if not present.
+ //
+ // ref: http://isrc.ifpi.org/
+ ISRC string
+ // Specifies if the track contains audio or data.
+ IsAudio bool
+ // Specifies if the track has been recorded with pre-emphasis
+ HasPreEmphasis bool
+ // Every track has one or more track index points, except for the lead-out
+ // track which has zero. Each index point specifies a position within the
+ // track.
+ Indicies []CueSheetTrackIndex
+}
+
+// A CueSheetTrackIndex specifies a position within a track.
+type CueSheetTrackIndex struct {
+ // Index point offset in samples, relative to the track offset.
+ Offset uint64
+ // Index point number; subsequently incrementing by 1 and always unique
+ // within a track.
+ Num uint8
+} | |
28748acc82edfc70a5db8d3727496508dafbe82c | ---
+++
@@ -1,8 +1,6 @@
// Copyright 2020 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-
-// +build ignore
// This program was used to generate dir-hard-link.cpio, which is
// an archive containing two directories with the same inode (0). | |
e1f20b9613cfd1c2d31b1fac5de4614d0af4559a | ---
+++
@@ -6,6 +6,7 @@
import (
"os"
"path/filepath"
+ "strings"
"testing"
)
@@ -20,7 +21,6 @@
}
func testParse(t *testing.T, path string) {
- println(path)
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
@@ -30,3 +30,27 @@
t.Fatalf("Parse error: %v", err)
}
}
+
+func TestParseErr(t *testing.T) {
+ errs := []string{
+ "'",
+ ";",
+ //"{",
+ "=",
+ "foo(",
+ "foo()",
+ "foo &&",
+ "foo |",
+ "foo ||",
+ "foo >",
+ "foo >>",
+ "foo >&",
+ "foo <",
+ }
+ for _, s := range errs {
+ r := strings.NewReader(s)
+ if err := parse(r, "stdin.go"); err == nil {
+ t.Fatalf("Expected error in: %s", s)
+ }
+ }
+} | |
a218e85835ec4c5d86366dc153cdcf901c452fc1 | ---
+++
@@ -7,23 +7,22 @@
"go.skia.org/infra/go/gce/server"
)
-func SKFEBase(name, ipAddress string) *gce.Instance {
+func SKFEBase(name string) *gce.Instance {
vm := server.Server20170613(name)
vm.DataDisk = nil
- vm.ExternalIpAddress = ipAddress
vm.MachineType = gce.MACHINE_TYPE_STANDARD_4
vm.Metadata["owner_primary"] = "stephana"
vm.Metadata["owner_secondary"] = "jcgregorio"
return vm
}
-func Prod(num int, ip string) *gce.Instance {
- return SKFEBase(fmt.Sprintf("skia-skfe-%d", num), ip)
+func Prod(num int) *gce.Instance {
+ return SKFEBase(fmt.Sprintf("skia-skfe-%d", num))
}
func main() {
server.Main(gce.ZONE_DEFAULT, map[string]*gce.Instance{
- "prod-1": Prod(1, "104.154.112.11"),
- "prod-2": Prod(2, "104.154.112.103"),
+ "prod-1": Prod(1),
+ "prod-2": Prod(2),
})
} | |
7e0a2d1baf29cc5ffc996d27937feabceb3dcff1 | ---
+++
@@ -2,7 +2,7 @@
import (
"bytes"
- "code.google.com/p/snappy-go/snappy"
+ "github.com/golang/snappy/snappy"
"encoding/binary"
)
| |
81c5d8a9689114d3b25758a45096cef78ea49749 | ---
+++
@@ -3,8 +3,6 @@
import (
"github.com/spf13/cobra"
)
-
-var autocompleteTarget string
var cmdAutocomplete = &cobra.Command{
Use: "autocomplete",
@@ -28,10 +26,12 @@
},
}
+var autocompleteTarget string
+
func init() {
cmdRoot.AddCommand(cmdAutocomplete)
- cmdAutocomplete.Flags().StringVarP(&autocompleteTarget, "completionfile", "", "/etc/bash_completion.d/restic.sh", "autocompletion file")
+ cmdAutocomplete.Flags().StringVarP(&autocompleteTarget, "completionfile", "", "/usr/share/bash-completion/completions/restic", "autocompletion file")
// For bash-completion
cmdAutocomplete.Flags().SetAnnotation("completionfile", cobra.BashCompFilenameExt, []string{})
} | |
11fb2c6c9f583570ef82650a64e125c36c3114be | ---
+++
@@ -2,12 +2,18 @@
import (
"errors"
+ "fmt"
"io"
"github.com/vapourismo/knx-go/knx/encoding"
)
// Address is a IPv4 address.
type Address [4]byte
+
+// String formats the address.
+func (addr Address) String() string {
+ return fmt.Sprintf("%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3])
+}
// Port is a port number.
type Port uint16 | |
8961b23ed64d67cb7843d54521e7c76347af7096 | ---
+++
@@ -29,7 +29,7 @@
acc := newAccumulator(r.PxWide, r.PxHigh)
for i := 0; i < int(r.Quality); i++ {
log.Print(i)
- TracerImage(scene.Camera, world, acc)
+ TraceImage(scene.Camera, world, acc)
}
img := acc.toImage(1.0) // XXX should be configurable
f, err := os.Create(r.BaseName + ".png") | |
1508b7ca7250ed81320ad0272b5b98c3d8f25172 | ---
+++
@@ -17,7 +17,7 @@
r.POST("/", func(c *gin.Context) {
body, ioerr := ioutil.ReadAll(c.Request.Body)
if ioerr != nil {
- c.String(500, "Could not read request body")
+ c.String(400, "Could not read request body")
log.Critical(ioerr)
return
}
@@ -25,7 +25,7 @@
//TODO: Request can be ambiguous
request, err := gitlab.Parse(string(body))
if err != nil {
- c.String(500, "Could not parse request body")
+ c.String(400, "Could not parse request body")
log.Critical(err)
return
} | |
5bc9b7a6744253f155d17c77fb3cc0b380e7b7b2 | ---
+++
@@ -37,3 +37,11 @@
err = stow.NotSupported("feature")
is.True(stow.IsNotSupported(err))
}
+
+func TestDuplicateKinds(t *testing.T) {
+ is := is.New(t)
+ stow.Register("example", nil, nil)
+ is.Equal(stow.Kinds(), []string{"test", "example"})
+ stow.Register("example", nil, nil)
+ is.Equal(stow.Kinds(), []string{"test", "example"})
+} | |
31a1efc4e81100349be820f1b06b44c60a00b8c9 | ---
+++
@@ -1,6 +1,7 @@
package main
import (
+ "fmt"
"os/exec"
"github.com/mikepea/go-jira-ui"
@@ -9,6 +10,7 @@
func resetTTY() {
cmd := exec.Command("reset")
_ = cmd.Run()
+ fmt.Println()
}
func main() { | |
2b3143dfbb318efa6e3789f039375f5f8320be56 | ---
+++
@@ -1,8 +1,9 @@
package actions
import (
- "fmt"
+ _ "fmt"
"github.com/bronzdoc/skeletor/template"
+ "io/ioutil"
"log"
"os"
)
@@ -16,21 +17,36 @@
if key == "dir" {
data := val.(map[interface{}]interface{})
dir_name := data["name"]
- fmt.Println(dir_name)
os.Mkdir(context+"/"+dir_name.(string), 0777)
if _, ok := data["files"]; ok {
files := data["files"].([]interface{})
for j := range files {
filename := context + "/" + dir_name.(string) + "/" + files[j].(string)
- fmt.Println(filename)
- f, err := os.Create(filename)
- if err != nil {
- log.Fatal(err)
+ f := create_file(filename)
+ defer f.Close()
+ template_name := os.Getenv("HOME") + "/" + ".skeletor/templates" + "/" + files[j].(string)
+ if _, err := os.Stat(template_name); err == nil {
+ add_template_content_to_file(template_name, f)
}
- defer f.Close()
}
}
}
}
}
}
+
+func create_file(filename string) *os.File {
+ f, err := os.Create(filename)
+ if err != nil {
+ log.Fatal(err)
+ }
+ return f
+}
+
+func add_template_content_to_file(template_name string, file *os.File) {
+ template_content, err := ioutil.ReadFile(template_name)
+ if err != nil {
+ log.Fatal(err)
+ }
+ file.Write(template_content)
+} | |
93ecd403e3b1c6037e61d8b2c8602d078530b8b9 | ---
+++
@@ -12,7 +12,7 @@
func GetConfigName(program, filename string) (string, error) {
u, err := user.Current()
if err != nil {
- return nil, err
+ return "", err
}
dir := filepath.Join(u.HomeDir, "."+program)
@@ -23,7 +23,7 @@
}
}
- return filepath.Join(dir, filename)
+ return filepath.Join(dir, filename), nil
}
// GetServerConfigName gets the correct full path of the configuration file for servers.
@@ -36,5 +36,5 @@
}
}
- return filepath.Join(dir, filename)
+ return filepath.Join(dir, filename), nil
} | |
33e90105f4391f9546d300a182bd155adf1bb00a | ---
+++
@@ -3,20 +3,42 @@
package tv_test
import (
+ "database/sql"
+ "fmt"
"time"
"github.com/appneta/go-appneta/v1/tv"
"golang.org/x/net/context"
)
+// measure a DB query
+func dbQuery(ctx context.Context, host, query string, args ...interface{}) *sql.Rows {
+ // Begin a TraceView layer for this DB query
+ l, _ := tv.BeginLayer(ctx, "dbQuery", "Query", query, "RemoteHost", host)
+ defer l.End()
+
+ db, err := sql.Open("mysql", fmt.Sprintf("user:password@tcp(%s:3306)/db", host))
+ if err != nil {
+ l.Err(err) // Report error & stack trace on Layer span
+ return nil
+ }
+ defer db.Close()
+ rows, err := db.Query(query, args...)
+ if err != nil {
+ l.Err(err)
+ }
+ return rows
+}
+
+// measure a slow function
func slowFunc(ctx context.Context) {
defer tv.BeginProfile(ctx, "slowFunc").End()
- // ... do something else ...
time.Sleep(1 * time.Second)
}
func Example() {
ctx := tv.NewContext(context.Background(), tv.NewTrace("myLayer"))
+ _ = dbQuery(ctx, "dbhost.net", "SELECT * from tbl LIMIT 1")
slowFunc(ctx)
tv.EndTrace(ctx)
} | |
1f222b9156cb2abd7689f7fabdc53bc54bef369c | ---
+++
@@ -5,15 +5,15 @@
"github.com/pmezard/go-difflib/difflib"
)
-func init() {
- spew.Config.SortKeys = true // :\
-}
-
// Diff diffs two arbitrary data structures, giving human-readable output.
func Diff(want, have interface{}) string {
+ config := spew.NewDefaultConfig()
+ config.ContinueOnMethod = true
+ config.SortKeys = true
+ config.SpewKeys = true
text, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
- A: difflib.SplitLines(spew.Sdump(want)),
- B: difflib.SplitLines(spew.Sdump(have)),
+ A: difflib.SplitLines(config.Sdump(want)),
+ B: difflib.SplitLines(config.Sdump(have)),
FromFile: "want",
ToFile: "have",
Context: 3, | |
5561a910c4c29d660bb26e6970b5125fa7e72f96 | ---
+++
@@ -4,7 +4,7 @@
"encoding/json"
"fmt"
"io/ioutil"
- "os"
+ "log"
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
@@ -34,8 +34,7 @@
func main() {
file, e := ioutil.ReadFile("./privy.cfg")
if e != nil {
- fmt.Printf("File error: %v\n", e)
- os.Exit(1)
+ log.Fatal("File error: ", e)
}
var config Config | |
2106e0fa6a6d245a6f5a1f65a67849987eacfabc | ---
+++
@@ -19,6 +19,10 @@
)
func impl(x, y int) float64 {
+ if go2cpp := js.Global().Get("go2cpp"); go2cpp.Truthy() {
+ return go2cpp.Get("devicePixelRatio").Float()
+ }
+
window := js.Global().Get("window")
if !window.Truthy() {
return 1 | |
e992a8d75516a96dcfd718d028a58ab55d599330 | ---
+++
@@ -19,7 +19,7 @@
m := pat.New()
n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
l := negronilogrus.NewMiddleware()
- r := render.New(render.Options{
+ o := render.New(render.Options{
Layout: "layout",
})
@@ -29,7 +29,7 @@
m.Get("/debug/vars", http.DefaultServeMux)
m.Get("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- r.HTML(w, http.StatusOK, "index", "world")
+ o.HTML(w, http.StatusOK, "index", "world")
}))
var addr string | |
3e0bf925f86b00256549597a85216ff6c9faba18 | ---
+++
@@ -20,6 +20,14 @@
pidFile := filepath.Join(tmpdir, "influxdb.pid")
cmd := run.NewCommand()
+ cmd.Getenv = func(key string) string {
+ switch key {
+ case "INFLUXDB_BIND_ADDRESS", "INFLUXDB_HTTP_BIND_ADDRESS":
+ return "127.0.0.1:0"
+ default:
+ return os.Getenv(key)
+ }
+ }
if err := cmd.Run("-pidfile", pidFile); err != nil {
t.Fatalf("unexpected error: %s", err)
} | |
316208bf23abed1623b2c229884b98fcec482f82 | ---
+++
@@ -11,12 +11,13 @@
*mgo.Session
url string
name string
+ coll string
}
-func NewDatabaseAccessor(url, name, string) (*DatabaseAccessor, error) {
+func NewDatabaseAccessor(url, name, coll string) (*DatabaseAccessor, error) {
session, err := mgo.Dial(url)
if err == nil {
- return &DatabaseAccessor{session, url, name}, nil
+ return &DatabaseAccessor{session, url, name, coll}, nil
} else {
return &DatabaseAccessor{}, err
} | |
e426c2fd3d932a3fe6cbc5d054c46d73e6eefe02 | ---
+++
@@ -8,6 +8,10 @@
strings.HasPrefix(sentence, "yt") {
return sentence + "ay"
}
+ if strings.HasPrefix(sentence, "p") {
+ return strings.TrimPrefix(sentence, "p") + "p" + "ay"
+ }
+
return sentence
}
| |
531dfc22018fae9d6fa725a2090fed0b65bd5860 | ---
+++
@@ -6,9 +6,9 @@
func NewFormatter(next types.Formatter) types.Formatter {
return func(request *types.APIContext, resource *types.RawResource) {
- resource.Links["yaml"] = request.URLBuilder.Link("yaml", resource)
if next != nil {
next(request, resource)
}
+ resource.Links["yaml"] = request.URLBuilder.Link("yaml", resource)
}
} | |
646b91a408e95c73466ea946aed893987542b30e | ---
+++
@@ -4,7 +4,7 @@
"fmt"
"os"
- "github.com/segmentio/go-loggly"
+ "github.com/cocoonlife/go-loggly"
)
// A timber.LogWriter for the loggly service.
@@ -36,4 +36,5 @@
// Close the write. Satifies the timber.LogWriter interface.
func (w *LogglyWriter) Close() {
w.c.Flush()
+ close(w.c.ShutdownChan)
} | |
01333813814eb47fd91c6181733d921b6e2aa4f4 | ---
+++
@@ -11,6 +11,9 @@
package main
+import "net"
+
type Client struct {
Name string
+ Conn net.Conn
} | |
32d3e4397ecb9fb3cb8bf87ab9b07f7a551f5447 | ---
+++
@@ -3,13 +3,15 @@
import (
"github.com/gin-gonic/gin"
"github.com/pufferpanel/pufferd/logging"
+ "runtime/debug"
)
func Recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
- logging.Errorf("Error handling route\n%+v", err)
+ c.Status(500)
+ logging.Errorf("Error handling route\n%+v\n%s", err, debug.Stack())
}
}()
| |
49aaa45315a16a8e09bb55222cf1aea18ef6e162 | ---
+++
@@ -1,49 +1,33 @@
package repo
import (
- "fmt"
-
"github.com/cathalgarvey/go-minilock"
- zxcvbn "github.com/nbutton23/zxcvbn-go"
)
-func EncryptMSG(jid, pass, plaintext, filename string, selfenc bool, mid ...string) (string, error) {
- ciphertext, err := minilock.EncryptFileContentsWithStrings(filename, []byte(plaintext), jid, pass, selfenc, mid...)
+// EncryptMinilockMsg encrypts a given plaintext for multiple receivers.
+func EncryptMinilockMsg(jid, pass, plaintext string, mid ...string) (string, error) {
+ ciphertext, err := minilock.EncryptFileContentsWithStrings("Minilock Filename.", []byte(plaintext), jid, pass, false, mid...)
if err != nil {
return "", nil
}
return string(ciphertext), nil
}
-func DecryptMSG(jid, pass, msg string) (string, error) {
+// DecryptMinilockMsg decrypts a given ciphertext.
+func DecryptMinilockMsg(jid, pass, ciphertext string) (string, error) {
userKey, err := minilock.GenerateKey(jid, pass)
if err != nil {
return "", nil
}
- _, _, plaintext, _ := minilock.DecryptFileContents([]byte(msg), userKey)
+ _, _, plaintext, _ := minilock.DecryptFileContents([]byte(ciphertext), userKey)
return string(plaintext), nil
}
-// TODO(elk): bad name?
-func GetUserlogin(jabberid string) (string, string) {
- var username string
- if jabberid == "" {
- fmt.Print("JabberID: ")
- fmt.Scanln(&username)
- } else {
- username = jabberid
+// GenerateMinilockID generates a base58-encoded pubkey + 1-byte blake2s checksum as a string
+func GenerateMinilockID(jid, pass string) (string, error) {
+ keys, err := minilock.GenerateKey(jid, pass)
+ if err != nil {
+ return "", err
}
-
- var password string
- for {
- fmt.Print("Password:")
- fmt.Scanln(&password)
- passStrength := zxcvbn.PasswordStrength(password, []string{})
- if passStrength.Entropy < 60 {
- fmt.Printf("Password is to weak (%f bits).\n", passStrength.Entropy)
- continue
- }
- break
- }
- return username, password
+ return keys.EncodeID()
} | |
e46d766aaf90b5eaf79cf40f2e57604a9ade12e9 | ---
+++
@@ -3,12 +3,15 @@
import (
"bufio"
"fmt"
+ "math/rand"
"os"
"strings"
"github.com/fabiofalci/sconsify/events"
"github.com/fabiofalci/sconsify/spotify"
+ ui "github.com/fabiofalci/sconsify/ui"
"github.com/howeyc/gopass"
+ sp "github.com/op/go-libspotify/spotify"
)
func main2() {
@@ -18,16 +21,32 @@
go spotify.Initialise(username, pass, events)
playlists := <-events.WaitForPlaylists()
- playlist := playlists["Ramones"]
- playlist.Wait()
- track := playlist.Track(3).Track()
- track.Wait()
+ allTracks := getAllTracks(playlists).Contents()
- events.ToPlay <- track
+ for {
+ index := rand.Intn(len(allTracks))
+ track := allTracks[index]
- println(track.Name())
- <-events.WaitForStatus()
- <-events.NextPlay
+ events.ToPlay <- track
+
+ println(<-events.WaitForStatus())
+ <-events.NextPlay
+ }
+}
+
+func getAllTracks(playlists map[string]*sp.Playlist) *ui.Queue {
+ queue := ui.InitQueue()
+
+ for _, playlist := range playlists {
+ playlist.Wait()
+ for i := 0; i < playlist.Tracks(); i++ {
+ track := playlist.Track(i).Track()
+ track.Wait()
+ queue.Add(track)
+ }
+ }
+
+ return queue
}
func credentials() (*string, *[]byte) { | |
214f8cc14203d1a1a1f670e3805b7cb117bc4dfb | ---
+++
@@ -5,96 +5,6 @@
// I am using a programming skill call precomputation.
// It has a very good performance
const ans = `
- 34
-- 09
------
- 25
-+ 86
------
- 111
-=====
-
- 36
-- 09
------
- 27
-+ 84
------
- 111
-=====
-
- 45
-- 06
------
- 39
-+ 72
------
- 111
-
-=====
- 52
-- 09
------
- 43
-+ 68
------
- 111
-=====
-
- 57
-- 08
------
- 49
-+ 62
------
- 111
-=====
-
- 57
-- 09
------
- 48
-+ 63
------
- 111
-=====
-
- 72
-- 09
------
- 63
-+ 48
------
- 111
-=====
-
- 84
-- 05
------
- 79
-+ 32
------
- 111
-=====
-
- 84
-- 09
------
- 75
-+ 36
------
- 111
-=====
-
- 85
-- 06
------
- 79
-+ 32
------
- 111
-=====
-
85
- 46
-----
@@ -131,24 +41,6 @@
111
=====
- 93
-- 06
------
- 87
-+ 24
------
- 111
-=====
-
- 93
-- 07
------
- 86
-+ 25
------
- 111
-=====
-
95
- 27
----- | |
3aa439b17e1cdc99545770639d28e730d82e035e | ---
+++
@@ -1,10 +1,10 @@
package main
import (
- _ "github.com/sheenobu/quicklog/filters/uuid"
+ "github.com/sheenobu/quicklog/filters/uuid"
"github.com/sheenobu/quicklog/inputs/stdin"
- _ "github.com/sheenobu/quicklog/outputs/stdout"
- _ "github.com/sheenobu/quicklog/parsers/plain"
+ "github.com/sheenobu/quicklog/outputs/debug"
+ "github.com/sheenobu/quicklog/parsers/plain"
"golang.org/x/net/context"
@@ -14,10 +14,11 @@
func main() {
chain := ql.Chain{
- Input: &stdin.Process{},
- Output: ql.GetOutput("stdout"),
- Filter: ql.GetFilter("uuid"),
- Parser: ql.GetParser("plain"),
+ Input: &stdin.Process{},
+ //Output: &stdout.Process{},
+ Output: &debug.Handler{PrintFields: debug.NullableBool{NotNull: false, Value: true}},
+ Filter: &uuid.Handler{FieldName: "uuid"},
+ Parser: &plain.Parser{},
}
ctx := context.Background() | |
3e1377d6c5f151b9c4ed74b618fa17ac2f28f73f | ---
+++
@@ -10,7 +10,7 @@
if tf {
return "Y"
}
- return "F"
+ return "N"
}
func CurrentUser() string { | |
5eabc60fda9687cb3906680f1078e700975c523e | ---
+++
@@ -7,7 +7,7 @@
const Version = "0.0.3"
const ApiVersion = "v1"
-var Trace = false
+var Trace = true
// Ed is thew editor singleton
var Ed Editable
@@ -41,16 +41,16 @@
type CursorMvmt byte
const (
- CursorMvmtRight CursorMvmt = iota
- CursorMvmtLeft
- CursorMvmtUp
- CursorMvmtDown
- CursorMvmtPgDown
- CursorMvmtPgUp
- CursorMvmtHome
- CursorMvmtEnd
- CursorMvmtTop
- CursorMvmtBottom
+ CursorMvmtRight CursorMvmt = 0
+ CursorMvmtLeft = 1
+ CursorMvmtUp = 2
+ CursorMvmtDown = 3
+ CursorMvmtPgDown = 4
+ CursorMvmtPgUp = 5
+ CursorMvmtHome = 6
+ CursorMvmtEnd = 7
+ CursorMvmtTop = 8
+ CursorMvmtBottom = 9
)
type ViewType int | |
b593fc243e010d1c19416c3b282ca20bca4055d7 | ---
+++
@@ -4,9 +4,16 @@
package main
-import "testing"
+import (
+ "os"
+ "testing"
+)
func TestGetMeetupEvents(t *testing.T) {
+ if os.Getenv("CHADEV_MEETUP") == "" {
+ t.Skip("no meetup API key set, skipping test")
+ }
+
_, err := getTalkDetails()
if err != nil {
t.Error(err) | |
e0dd532d12b6bc448757b2bc0ea22527630c612c | ---
+++
@@ -1,6 +1,77 @@
package vecty
+
+import (
+ "fmt"
+ "testing"
+)
var _ = func() bool {
isTest = true
return true
}()
+
+// TODO(slimsag): TestCore; Core.Context
+// TODO(slimsag): TestComponent; Component.Render; Component.Context
+// TODO(slimsag): TestUnmounter; Unmounter.Unmount
+// TODO(slimsag): TestComponentOrHTML
+// TODO(slimsag): TestRestorer; Restorer.Restore
+// TODO(slimsag): TestHTML; HTML.Restore
+// TODO(slimsag): TestTag
+// TODO(slimsag): TestText
+// TODO(slimsag): TestRerender
+
+// TestRenderBody_ExpectsBody tests that RenderBody always expects a "body" tag
+// and panics otherwise.
+func TestRenderBody_ExpectsBody(t *testing.T) {
+ cases := []struct {
+ name string
+ render *HTML
+ wantPanic string
+ }{
+ {
+ name: "text",
+ render: Text("Hello world!"),
+ wantPanic: "vecty: RenderBody expected Component.Render to return a body tag, found \"\"", // TODO(slimsag): bug
+ },
+ {
+ name: "div",
+ render: Tag("div"),
+ wantPanic: "vecty: RenderBody expected Component.Render to return a body tag, found \"div\"",
+ },
+ {
+ name: "body",
+ render: Tag("body"),
+ wantPanic: "runtime error: invalid memory address or nil pointer dereference", // TODO(slimsag): relies on js
+ },
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ var gotPanic string
+ func() {
+ defer func() {
+ r := recover()
+ if r != nil {
+ gotPanic = fmt.Sprint(r)
+ }
+ }()
+ RenderBody(&componentFunc{render: func() *HTML {
+ return c.render
+ }})
+ }()
+ if c.wantPanic != gotPanic {
+ t.Fatalf("want panic %q got panic %q", c.wantPanic, gotPanic)
+ }
+ })
+ }
+}
+
+// TODO(slimsag): TestRenderBody_Standard
+// TODO(slimsag): TestSetTitle
+// TODO(slimsag): TestAddStylesheet
+
+type componentFunc struct {
+ Core
+ render func() *HTML
+}
+
+func (c *componentFunc) Render() *HTML { return c.render() } | |
cac90d50a1f81b223f5b111e0a943c386499b906 | ---
+++
@@ -5,6 +5,8 @@
"net/http"
)
+// To try out: https://github.com/pressly/chi
+
func main() {
// Simple static webserver:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("./webroot")))) | |
e8c10476269fce8903785a1e93db0fd5b8f06c9e | ---
+++
@@ -16,7 +16,7 @@
hff := NewHandlerFilter(http.HandlerFunc(handler))
tmp, _ := http.NewRequest("GET", "/hello", nil)
- _, res := TestWithRequest(tmp, hff)
+ _, res := TestWithRequest(tmp, hff, nil)
if res == nil {
t.Errorf("Response is nil") | |
69d4dd3f26cb03ef8c5171bc661725fc12304282 | ---
+++
@@ -12,7 +12,6 @@
}
mock := Mock{}
-
configuration, err := Load("share/fixtures/example", &mock)
checkTestError(t, err)
@@ -25,6 +24,20 @@
if mock.Name != "Bailey" || mock.Age != 30 {
t.Error("Got unexpected values from configuration file.")
+ }
+}
+
+func TestLoadReturnsErrorForFilesWhichDontExist(t *testing.T) {
+ type Mock struct {
+ Name string `json:"name"`
+ Age int `json:"age"`
+ }
+
+ mock := Mock{}
+ _, err := Load("this/is/a/fake/filename", &mock)
+
+ if err == nil {
+ t.Error("Expected an error but one was not returned.")
}
}
| |
16b353ce4ff8cab3447b428c6918554bc2917f5b | ---
+++
@@ -7,7 +7,7 @@
func PortfoliosExt() (entity.PortfoliosExt, error) {
portfolios := entity.PortfoliosExt{}
- err := db.Connection().Select(&portfolios, "SELECT portfolio_id, name, currency, cache_value, gain_of_sold_shares, commision, tax, gain_of_owned_shares, estimated_gain, estimated_gain_costs_inc, estimated_value, annual_balance, month_balance FROM portfolios_ext")
+ err := db.Connection().Select(&portfolios, "SELECT portfolio_id, name, currency, cache_value, gain_of_sold_shares, commision, tax, gain_of_owned_shares, estimated_gain, estimated_gain_costs_inc, estimated_value, annual_balance, month_balance FROM portfolios_ext ORDER BY portfolio_id")
return portfolios, err
}
| |
0225a379518fa292d5808fe1ef31947d0ce30577 | ---
+++
@@ -36,7 +36,7 @@
if len(parts) < 2 {
continue
}
- switch strings.TrimSpace(parts[0]) {
+ switch strings.ToLower(strings.TrimSpace(parts[0])) {
case "state":
info.Running = strings.TrimSpace(parts[1]) == "RUNNING"
case "pid": | |
09971f297453cc7a98e8fb6058c265efdee02c44 | ---
+++
@@ -1,11 +1,15 @@
package allyourbase
import (
+ "errors"
"fmt"
"math"
)
func ConvertToBase(inputBase int, inputDigits []int, outputBase int) (outputDigits []int, e error) {
+ if inputBase < 2 {
+ return []int{}, errors.New("input base must be >= 2")
+ }
base10 := getBase10Input(inputBase, inputDigits)
if base10 == 0 {
return []int{0}, nil | |
21db66e8ab1bb14e7e142f8717a9ee587e27b739 | ---
+++
@@ -1,13 +1,6 @@
package dropsonde_unmarshaller_test
import (
- "time"
-
- "github.com/cloudfoundry/dropsonde/emitter/fake"
- "github.com/cloudfoundry/dropsonde/metric_sender"
- "github.com/cloudfoundry/dropsonde/metricbatcher"
- "github.com/cloudfoundry/dropsonde/metrics"
-
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
@@ -18,12 +11,3 @@
RegisterFailHandler(Fail)
RunSpecs(t, "Dropsonde Unmarshaller Suite")
}
-
-var fakeEventEmitter = fake.NewFakeEventEmitter("doppler")
-var metricBatcher *metricbatcher.MetricBatcher
-
-var _ = BeforeSuite(func() {
- sender := metric_sender.NewMetricSender(fakeEventEmitter)
- metricBatcher = metricbatcher.New(sender, 100*time.Millisecond)
- metrics.Initialize(sender, metricBatcher)
-}) | |
f460c300cbafcadf65edff59285d6bd346b9fc16 | ---
+++
@@ -30,7 +30,7 @@
build.Stdout = os.Stdout
build.Stderr = os.Stderr
build.Stdin = os.Stdin
- build.Env = []string{"GOPATH=" + gopath}
+ build.Env = append(os.Environ(), "GOPATH="+gopath)
err = build.Run()
if err != nil { | |
427a9b6b1a50cc5d58ed0a760d3186f0f475c409 | ---
+++
@@ -7,8 +7,11 @@
import "time"
+const DEFAULT_SOUND = "/usr/share/sounds/freedesktop/stereo/complete.oga"
+
+
func main() {
- cmd := exec.Command("paplay", "/usr/share/sounds/freedesktop/stereo/complete.oga")
+ cmd := exec.Command("paplay", DEFAULT_SOUND)
cmd.Start()
var interval int
@@ -29,7 +32,7 @@
for true {
fmt.Println("Ding!", counter)
time.Sleep(time.Second * time.Duration(interval))
- cmd := exec.Command("paplay", "/usr/share/sounds/freedesktop/stereo/complete.oga")
+ cmd := exec.Command("paplay", DEFAULT_SOUND)
cmd.Start()
counter++
} | |
57e28dbc82966b03569338bce11048ad96ed59a2 | ---
+++
@@ -9,7 +9,7 @@
func main() {
c := make(map[string]string)
- c["name"] = "test"
+ c["name"] = "dev"
c["url"] = "localhost"
c["leads"] = "newlead"
c["contacts"] = "newcontact" | |
6fcc9a77e70103972d279e4df6d6856dd2de5c39 | ---
+++
@@ -7,7 +7,7 @@
func TestParseTHGR122NX(t *testing.T) {
var o Oregon
res := o.Parse("OS3", "1D20485C480882835")
- if res.ID != "1D20" {
+ if res.ID != "OS3:1D20" {
t.Error("Error parsing ID")
}
if res.Data["Temperature"] != -8.4 { | |
72c282466e2c9f9564fe4331dafbb50964a3f4c1 | ---
+++
@@ -15,7 +15,7 @@
switch driver {
case "mysql":
connect = fmt.Sprintf(
- "%s:%s@(%s)/%s?parseTime=True&loc=Local",
+ "%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local",
cfg.Database.Username,
cfg.Database.Password,
cfg.Database.Host, | |
645ef489efa037919f4f1c90129a8cd5a831a0c9 | ---
+++
@@ -31,19 +31,19 @@
}
func (ls *LinkService) CreateLink(name string, paths []string, public bool) error {
- return nil, nil
+ return nil
}
func (ls *LinkService) AddPaths(token string, paths []string) error {
- return nil, nil
+ return nil
}
func (ls *LinkService) AddRecipients(token string, recipients []Recipient) error {
- return nil, nil
+ return nil
}
func (ls *LinkService) DeleteLink(token string) error {
- return nil, nil
+ return nil
}
func (ls *LinkService) GetFilesMetaFromLink(token string) (*Meta, error) { | |
87a94c9fe9618135282cd43695523a620a9bcc49 | ---
+++
@@ -25,10 +25,10 @@
)
func main() {
+ flag.CommandLine.Parse([]string{"-v", "4", "-logtostderr=true"})
cmd.Execute()
}
func init() {
- flag.CommandLine.Parse([]string{})
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
} | |
435b63ff092f54d7a7739d2010345bb917d0fbfc | ---
+++
@@ -1,8 +1,6 @@
package bot
-import (
- "github.com/graffic/wanon/telegram"
-)
+import "github.com/graffic/wanon/telegram"
// RouteNothing do nothing in handling
const RouteNothing = 0
@@ -13,10 +11,16 @@
RouteStop
)
+// Message from the telegram router
+type Message struct {
+ *telegram.Message
+ *telegram.AnswerBack
+}
+
// Handler pairs a check and a handle function
type Handler interface {
- Check(*telegram.Message, *Context) int
- Handle(*telegram.Message, *Context)
+ Check(messages *Message) int
+ Handle(messages *Message)
}
// Router stores handlers for messages
@@ -33,11 +37,14 @@
func (router *Router) RouteMessages(messages chan *telegram.Message, context *Context) {
for {
message := <-messages
+ answer := telegram.AnswerBack{API: context.API, Message: message}
+ routerMessage := Message{message, &answer}
for _, handler := range router.handles {
- result := handler.Check(message, context)
+
+ result := handler.Check(&routerMessage)
if (result & RouteAccept) > 0 {
- handler.Handle(message, context)
+ handler.Handle(&routerMessage)
}
if (result & RouteStop) > 0 {
break | |
a2d14d4e98cb1620043c4ba868aad0e277ea41b4 | ---
+++
@@ -34,3 +34,12 @@
func (e ErrUnmarshalIncongruent) Error() string {
return fmt.Sprintf("cannot assign %s to %s field", e.Token, e.Value.Kind())
}
+
+type ErrUnexpectedTokenType struct {
+ Got TokenType // Token in the stream that triggered the error.
+ Expected string // Freeform string describing valid token types. Often a summary like "array close or start of value", or "map close or key".
+}
+
+func (e ErrUnexpectedTokenType) Error() string {
+ return fmt.Sprintf("unexpected %s token; expected %s", e.Got, e.Expected)
+} | |
b19dc050e5c6c78f4a5cc6264234aab7989ac9c3 | ---
+++
@@ -1,14 +1,13 @@
package transcode
-
-import (
-
-)
// Options represents an audio codec and its quality settings, and includes methods to
// retrieve these settings
type Options interface {
Codec() string
+ Ext() string
FFmpegCodec() string
+ FFmpegFlags() string
FFmpegQuality() string
+ MIMEType() string
Quality() string
} | |
5dc838ca8c7100e44290ed77640a57da23a6aa7a | ---
+++
@@ -5,6 +5,7 @@
"encoding/json"
"io"
"net/http"
+ "strings"
"github.com/labstack/echo"
)
@@ -29,6 +30,10 @@
return bytes.NewReader(jsForm)
}
+func NewStringReader(s string) io.Reader {
+ return strings.NewReader(s)
+}
+
func Form() *testForm {
return &testForm{}
} | |
60bb144532a799d3151daceb77e41568cb1c129c | ---
+++
@@ -20,7 +20,7 @@
Describe("Generate", func() {
It("generates a terraform template for azure", func() {
- expectedTemplate, err := ioutil.ReadFile("fixtures/azure_template_rg.tf")
+ expectedTemplate, err := ioutil.ReadFile("fixtures/azure_template.tf")
Expect(err).NotTo(HaveOccurred())
template := templateGenerator.Generate(storage.State{ | |
17d372677d08cf2a9a4c0f83807f20fcfb182de7 | ---
+++
@@ -10,10 +10,23 @@
// given string and returns it if found. If no keyword is close enough, returns
// the empty string.
func keywordSuggestion(given string) string {
- for _, kw := range keywords {
- dist := levenshtein.Distance(given, kw, nil)
+ return nameSuggestion(given, keywords)
+}
+
+// nameSuggestion tries to find a name from the given slice of suggested names
+// that is close to the given name and returns it if found. If no suggestion
+// is close enough, returns the empty string.
+//
+// The suggestions are tried in order, so earlier suggestions take precedence
+// if the given string is similar to two or more suggestions.
+//
+// This function is intended to be used with a relatively-small number of
+// suggestions. It's not optimized for hundreds or thousands of them.
+func nameSuggestion(given string, suggestions []string) string {
+ for _, suggestion := range suggestions {
+ dist := levenshtein.Distance(given, suggestion, nil)
if dist < 3 { // threshold determined experimentally
- return kw
+ return suggestion
}
}
return "" | |
dadf097c0c5f7dec5a451c34464b8c5994d1f596 | ---
+++
@@ -34,7 +34,12 @@
for _, s := range current {
color.Green("%s\n", s.Spec.Name)
- fmt.Printf(" - Published Port => %d\n", s.Endpoint.Ports[0].PublishedPort)
+ fmt.Println(" - Published Ports")
+
+ for _, port := range s.Endpoint.Ports {
+ fmt.Printf(" %d => %d\n", port.TargetPort, port.PublishedPort)
+ }
+
fmt.Println()
}
} | |
94eb97bfe9d18ee8093b83562e17ee600c055a1b | ---
+++
@@ -27,6 +27,8 @@
switch cmd := c.Cmd.(type) {
case Cmd:
return cmd.SourceURL()
+ case CmdBasicAuth:
+ return cmd.SourceURL()
default:
return nil
} |
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.