commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
4.24k
new_contents
stringlengths
1
5.44k
subject
stringlengths
14
778
message
stringlengths
15
9.92k
lang
stringclasses
277 values
license
stringclasses
13 values
repos
stringlengths
5
127k
7a9ca4a397c8b04e3585432f7ff941faa18a89c2
server/logger.go
server/logger.go
package server import ( "net/http" "github.com/influxdata/chronograf" ) // Logger is middleware that logs the request func Logger(logger chronograf.Logger, next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { logger. WithField("component", "server"). WithField("remote_add...
package server import ( "net/http" "time" "github.com/influxdata/chronograf" ) // Logger is middleware that logs the request func Logger(logger chronograf.Logger, next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { now := time.Now() logger. WithField("component", "server...
Add logging of response times
Add logging of response times This makes monitoring Chronograf :+1:
Go
agpl-3.0
brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf
88c13bcb5c55ddd09494944c97e7d14e1c738e10
xfrm_policy.go
xfrm_policy.go
package netlink import ( "fmt" "net" ) // Dir is an enum representing an ipsec template direction. type Dir uint8 const ( XFRM_DIR_IN = iota XFRM_DIR_OUT = iota ) func (d Dir) String() string { switch d { case XFRM_DIR_IN: return "in" case XFRM_DIR_OUT: return "out" } return fmt.Sprintf("%d", d) } //...
package netlink import ( "fmt" "net" ) // Dir is an enum representing an ipsec template direction. type Dir uint8 const ( XFRM_DIR_IN Dir = iota XFRM_DIR_OUT Dir = iota XFRM_DIR_FWD Dir = iota XFRM_SOCKET_IN Dir = iota XFRM_SOCKET_OUT Dir = iota XFRM_SOCKET_FWD Dir = iota ) func (d Dir) String() ...
Add support for more xfrm policy dir values
Add support for more xfrm policy dir values
Go
apache-2.0
mcastelino/netlink,nickethier/netlink,LK4D4/netlink,ninjadq/netlink,paravmellanox/netlink,chantra/netlink,porjo/netlink,axsh/netlink,vishvananda/netlink,clearlinux/netlink,mrjana/netlink,bboreham/netlink
5b76abab10292af97ae9c3ea3da825c3353c224f
controllers/game_controller.go
controllers/game_controller.go
package controllers import ( "encoding/json" "github.com/alex1sz/shotcharter-go/utilities" "github.com/gorilla/mux" // "log" "net/http" // neccessary to catch sql.ErrNoRows // "database/sql" "github.com/alex1sz/shotcharter-go/models" ) // GET /games/:id func GetGameByID(w http.ResponseWriter, req *http.Reque...
package controllers import ( "encoding/json" "github.com/alex1sz/shotcharter-go/utilities" "github.com/gorilla/mux" // "log" "net/http" // neccessary to catch sql.ErrNoRows // "database/sql" "github.com/alex1sz/shotcharter-go/models" ) // GET /games/:id func GetGameByID(w http.ResponseWriter, req *http.Reque...
Add CreateGame to Game controller
Add CreateGame to Game controller
Go
mit
Alex1sz/shotcharter-go-api
2c973222464a9ae133b089aa0f7cd48958bc36ed
models/user.go
models/user.go
package models import ( "github.com/yawnt/index.spacedock/couch" "github.com/fjl/go-couchdb" ) type User struct { } func NewUser() *User { return &User{} } func GetUser(name string) (*User, error) { ret := &User{} err := couch.Couch.Get("user/" + name, nil, ret) if err != nil { dberr, ok := err.(c...
package models import ( "github.com/yawnt/index.spacedock/couch" "github.com/fjl/go-couchdb" ) type User struct { } func NewUser() *User { return &User{} } func GetUser(name string) (*User, error) { ret := &User{} err := couch.Couch.Get("user/" + name, nil, ret) if err != nil { dberr, ok := err.(c...
Make the 404 check shorter
Make the 404 check shorter
Go
mit
spacedock-io/index
bf00c5a6cc5c9e004cdf628b8c630a1f03583fca
parser_test.go
parser_test.go
package main_test import "testing" func Test_failure(t *testing.T) { t.Fatal("Write a test...") }
package main_test import "testing" func Test_failure(t *testing.T) { }
Remove failing test to verify travis builds succeed now.
Remove failing test to verify travis builds succeed now.
Go
bsd-3-clause
nfisher/apib2go
992935a9ebd9603cf13fe0f94f6a302bf7135cda
state/address.go
state/address.go
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package state // AddressType represents the possible ways of specifying a machine location by // either a hostname resolvable by dns lookup, or ipv4 or ipv6 address. type AddressType string const ( HostName AddressType =...
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package state // AddressType represents the possible ways of specifying a machine location by // either a hostname resolvable by dns lookup, or ipv4 or ipv6 address. type AddressType string const ( HostName AddressType =...
Use Address.Value rather than name as suggested by fwereade in review and use NetworkScope type
Use Address.Value rather than name as suggested by fwereade in review and use NetworkScope type
Go
agpl-3.0
davecheney/juju,perrito666/juju,cloud-green/juju,cherylj/juju,sinzui/juju,mikemccracken/juju,AdamIsrael/juju,makyo/juju,AdamIsrael/juju,kat-co/juju,bac/juju,gabriel-samfira/juju,gabriel-samfira/juju,kat-co/juju,wwitzel3/juju,thomnico/juju,cmars/juju,mhilton/juju,mhilton/juju,makyo/juju,anastasiamac/juju,bac/juju,makyo/...
f091d6da065552c707bf9fca580a12602393b47c
util/resolver.go
util/resolver.go
package util // resolves a relative image path to a fully qialified path. func ResolveImagePath(relativePath string) string { return "images/" + relativePath }
package util var imageDir = "images/" // resolves a relative image path to a fully qialified path. func ResolveImagePath(relativePath string) string { return imageDir + "/" + relativePath } // the directory used to resolve the func SetImageDir(newDir string) { imageDir = newDir }
Allow images directory to be configured.
Allow images directory to be configured. Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@ninjablocks.com>
Go
mit
lindsaymarkward/sphere-go-led-controller,ninjasphere/sphere-go-led-controller,lindsaymarkward/sphere-go-led-controller,ninjasphere/sphere-go-led-controller,ninjasphere/sphere-go-led-controller,lindsaymarkward/sphere-go-led-controller,ninjasphere/sphere-go-led-controller,lindsaymarkward/sphere-go-led-controller
85337525023b304d71ce16fce35208889acf1be4
_examples/2_server/user_test.go
_examples/2_server/user_test.go
package main import ( "math/rand" "testing" ) func dummyNewUser() *User { var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") randSeq := func(n int) string { b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } return &User{ ...
package main import ( "math/rand" "testing" ) func dummyNewUser(password string) *User { var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") randSeq := func(n int) string { b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } ...
Improve dummy user generate in example 2
Improve dummy user generate in example 2 Accept password as parameter to prevent hashing problem. Since hash is used before saving the Password field, cannot get the real password in the struct.
Go
apache-2.0
gourd/gourd
7cdfe9a31d3590bce98a928428b6b17389239ccb
src/provisioner/provisioner/commands/close_all_ports.go
src/provisioner/provisioner/commands/close_all_ports.go
package commands import ( "provisioner/provisioner" ) type CloseAllPorts struct { CmdRunner provisioner.CmdRunner } func (c *CloseAllPorts) Run() error { err := c.CmdRunner.Run("iptables", "-I", "INPUT", "-i", "eth0", "-p", "tcp", "-j", "DROP") if err != nil { return err } err = c.CmdRunner.Run("iptables", ...
package commands import ( "provisioner/provisioner" ) type CloseAllPorts struct { CmdRunner provisioner.CmdRunner } func (c *CloseAllPorts) Run() error { if err := c.dropNewConnections("eth0"); err != nil { return err } if err := c.dropNewConnections("eth1"); err != nil { return err } return c.CmdRunner...
Allow traffic to come in on eth0 and eth1 for established connections
Allow traffic to come in on eth0 and eth1 for established connections * Without this rule app containers cannot communicate with the internet. For example, when pushing a docker app, the container makes a get request to docker hub but the response gets dropped by iptables [#130758953]
Go
apache-2.0
pivotal-cf/micropcf,pivotal-cf/micropcf
8585162422198b6961bc736bde20ad9ab80b3829
result.go
result.go
package nagiosplugin // Nagios plugin exit status. type Status uint // The usual mapping from 0-3. const ( OK Status = iota WARNING CRITICAL UNKNOWN ) // Returns string representation of a Status. Panics if given an invalid // status. func (s Status) String() string { switch s { case OK: return "OK" case WA...
package nagiosplugin // Nagios plugin exit status. type Status uint // The usual mapping from 0-3. const ( OK Status = iota WARNING CRITICAL UNKNOWN ) // Returns string representation of a Status. Panics if given an invalid // status (this will be recovered in check.Finish if it has been deferred). func (s Stat...
Document recovery of panic on invalid status
Document recovery of panic on invalid status
Go
bsd-3-clause
fractalcat/nagiosplugin,olorin/nagiosplugin
23d07ef0a6818fa4dbe343dfd35e324a96fb1763
signer.go
signer.go
package jwthelper import ( "github.com/dgrijalva/jwt-go" ) type Signer struct { Method jwt.SigningMethod key interface{} } type SignerOption struct { f func(s *Signer) } func SignerMethod(m jwt.SigningMethod) SignerOption { return SignerOption{func(s *Signer) { s.Method = m }} } func NewRSASHASigner(pri...
package jwthelper import ( "github.com/dgrijalva/jwt-go" ) type Signer struct { Method jwt.SigningMethod key interface{} } type SignerOption struct { f func(s *Signer) } func SignerMethod(m jwt.SigningMethod) SignerOption { return SignerOption{func(s *Signer) { s.Method = m }} } func NewRSASHASigner(sig...
Use []byte as 1st arg of NewRSASHASigner()
Use []byte as 1st arg of NewRSASHASigner() * Use []byte as first arg of NewRSASHASigner() * Add NewRSASHASignerFromPEM() to new a signer from private PEM file
Go
mit
northbright/jwthelper
8be6da3b9e29bc5701fad75f3253a30805f28cf4
writer_unsafe.go
writer_unsafe.go
// +build !appengine,!tinygo package fwd import ( "reflect" "unsafe" ) // unsafe cast string as []byte func unsafestr(b string) []byte { l := len(b) return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ Len: l, Cap: l, Data: (*reflect.StringHeader)(unsafe.Pointer(&b)).Data, })) }
// +build !appengine,!tinygo package fwd import ( "reflect" "unsafe" ) // unsafe cast string as []byte func unsafestr(s string) []byte { var b []byte sHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) bHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) bHdr.Data = sHdr.Data bHdr.Len = sHdr.Len bHdr.Cap = sHd...
Fix invalid usage of reflect.SliceHeader
Fix invalid usage of reflect.SliceHeader Using plain reflect.SliceHeader struct violates unsafe pointer 6th rule.
Go
mit
philhofer/fwd
16235b6286b42477477123de4e1ab5dcead7da4e
util.go
util.go
// Copyright 2018 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
// Copyright 2018 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
Remove padding characters from cert URL.
Remove padding characters from cert URL. This makes the URL prettier by removing reserved characters, and matches the behavior of the planned AMP CDN URL.
Go
apache-2.0
ampproject/amppackager,ampproject/amppackager,ampproject/amppackager
f6ee3f8284632a262556a95bf05be32469e99ffa
daemon/service/service_nocgo.go
daemon/service/service_nocgo.go
// +build !cgo // Package service implements the daemon service for mediating access to the // storage backend. package service import ( "github.com/elves/elvish/util" "syscall" ) var logger = util.GetLogger("[daemon-dummy] ") // A dummy implementation of Serve for the environment of Cgo being disabled. func Serv...
// +build !cgo // Package service implements the daemon service for mediating access to the // storage backend. package service import ( "syscall" "github.com/elves/elvish/util" ) var logger = util.GetLogger("[daemon-dummy] ") // A dummy implementation of Serve for the environment of Cgo being disabled. func Ser...
Fix imports order with goimports.
Fix imports order with goimports.
Go
bsd-2-clause
elves/elvish,elves/elvish,elves/elvish,elves/elvish,elves/elvish
f2da51b51b059f30ee715c9e0bd87d9c50f12b78
constants_test.go
constants_test.go
package magic import ( "testing" ) func TestConstants(t *testing.T) { var constantTests = []struct { given int expected []int }{ { MIME, []int{ MIME_TYPE, MIME_ENCODING, }, }, { NO_CHECK_ASCII, []int{ NO_CHECK_TEXT, }, }, { NO_CHECK_BUILTIN, []int{ NO_CHECK_...
package magic import ( "testing" ) func TestConstants(t *testing.T) { var constantTests = []struct { given int expected []int }{ { MIME, []int{ MIME_TYPE, MIME_ENCODING, }, }, { NO_CHECK_ASCII, []int{ NO_CHECK_TEXT, }, }, { NO_CHECK_BUILTIN, []int{ NO_CHECK_...
Make sure to skip flags that are not available when testing constants
Make sure to skip flags that are not available when testing constants Signed-off-by: Krzysztof Wilczyński <5f1c0be89013f8fde969a8dcb2fa1d522e94ee00@linux.com>
Go
apache-2.0
kwilczynski/go-magic,kwilczynski/go-magic,kwilczynski/go-magic
8f37aed8328cd444c3ae770f7b57773180bfc7d8
form/options.go
form/options.go
package form type Options struct { Fields []string Values map[string]interface{} Choices map[string]interface{} }
package form type Options struct { Fields []string }
Remove Values and Choices from Options
Remove Values and Choices from Options They're not used
Go
mpl-2.0
rainycape/gondola,rainycape/gondola,rainycape/gondola,rainycape/gondola
c645bdd74a494329c37efd240af3b74f37a42d68
store/store_test.go
store/store_test.go
package store import ( "io/ioutil" "os" "testing" ) func Test_StoreOpen(t *testing.T) { s := New() tmpDir, _ := ioutil.TempDir("", "store_test") defer os.RemoveAll(tmpDir) s.RaftBind = "127.0.0.1:8088" s.RaftDir = tmpDir if s == nil { t.Fatalf("failed to create store") } if err := s.Open(false); err !=...
package store import ( "io/ioutil" "os" "testing" "time" ) func Test_StoreOpen(t *testing.T) { s := New() tmpDir, _ := ioutil.TempDir("", "store_test") defer os.RemoveAll(tmpDir) s.RaftBind = "127.0.0.1:0" s.RaftDir = tmpDir if s == nil { t.Fatalf("failed to create store") } if err := s.Open(false); e...
Add simple unit test of SET and GET
Add simple unit test of SET and GET
Go
mit
otoolep/hraftd
e3d73a6350901b1fb9b73d5a8f8d97d949524c33
sysdep/x86_code_generator.go
sysdep/x86_code_generator.go
package sysdep import ( bs_core "bitbucket.org/yyuu/bs/core" bs_ir "bitbucket.org/yyuu/bs/ir" ) type X86CodeGenerator struct { errorHandler *bs_core.ErrorHandler } func NewX86CodeGenerator(errorHandler *bs_core.ErrorHandler) *X86CodeGenerator { return &X86CodeGenerator { errorHandler } } func (self *X86Code...
package sysdep import ( bs_core "bitbucket.org/yyuu/bs/core" bs_ir "bitbucket.org/yyuu/bs/ir" ) type X86CodeGenerator struct { errorHandler *bs_core.ErrorHandler } func NewX86CodeGenerator(errorHandler *bs_core.ErrorHandler) *X86CodeGenerator { return &X86CodeGenerator { errorHandler } } func (self *X86Code...
Fix compile errors relating to the change of interface of errorHandler
Fix compile errors relating to the change of interface of errorHandler
Go
mit
yyuu/xtc,yyuu/xtc
fe45885f549b877bf3ad59d08b551acab1ae03f0
core/description/package_test.go
core/description/package_test.go
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package description import ( "testing" gc "gopkg.in/check.v1" ) // Useful test constants. // Constraints and CloudInstance store megabytes const gig uint64 = 1024 // None of the tests in this package require mongo. func...
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package description import ( "testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" coretesting "github.com/juju/juju/testing" ) // Useful test constants. // Constraints and CloudInstance store megabyt...
Add a test to make sure we don't get package dependency creep.
Add a test to make sure we don't get package dependency creep.
Go
agpl-3.0
AdamIsrael/juju,bac/juju,anastasiamac/juju,anastasiamac/juju,macgreagoir/juju,gabriel-samfira/juju,makyo/juju,dimitern/juju,bogdanteleaga/juju,alesstimec/juju,marcmolla/juju,bz2/juju,axw/juju,frankban/juju,ericsnowcurrently/juju,ericsnowcurrently/juju,bogdanteleaga/juju,dooferlad/juju,gabriel-samfira/juju,reedobrien/ju...
7fd9584ebeb30f4bb1e6d79ada5d3a5da0f20a5a
go/vt/logutil/throttled_test.go
go/vt/logutil/throttled_test.go
package logutil import ( "testing" "time" ) func TestThrottledLogger(t *testing.T) { tl := NewThrottledLogger("test", 100*time.Millisecond) tl.Infof("test %v", 1) tl.Infof("test %v", 2) if tl.skippedCount != 1 { t.Fatalf("skippedCount is %v but was expecting 1", tl.skippedCount) } time.Sleep(100 * time.Mil...
package logutil import ( "fmt" "testing" "time" ) func TestThrottledLogger(t *testing.T) { // Install a fake log func for testing. log := make(chan string) infof = func(format string, args ...interface{}) { log <- fmt.Sprintf(format, args...) } interval := 100 * time.Millisecond tl := NewThrottledLogger("n...
Remove Sleep() from ThrottledLogger test and check output format.
Remove Sleep() from ThrottledLogger test and check output format.
Go
apache-2.0
alainjobart/vitess,tjyang/vitess,cloudbearings/vitess,mapbased/vitess,mlc0202/vitess,aaijazi/vitess,dcadevil/vitess,cloudbearings/vitess,enisoc/vitess,sougou/vitess,AndyDiamondstein/vitess,nurblieh/vitess,cloudbearings/vitess,guokeno0/vitess,kuipertan/vitess,aaijazi/vitess,yangzhongj/vitess,guokeno0/vitess,nurblieh/vit...
99363331e8532d09ba0602d80c344707f8e29d98
cmd/xurls/main.go
cmd/xurls/main.go
/* Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc> */ /* See LICENSE for licensing information */ package main import ( "bufio" "fmt" "os" "github.com/mvdan/xurls" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() urls := xurls.WebUrl.FindAllString(line, -...
/* Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc> */ /* See LICENSE for licensing information */ package main import ( "bufio" "flag" "fmt" "os" "github.com/mvdan/xurls" ) var ( email = flag.Bool("e", false, "match e-mails instead of web urls") ) func main() { flag.Parse() scanner := bufio.NewScanner(os...
Add -e to xurls to match emails
Add -e to xurls to match emails
Go
bsd-3-clause
digideskio/xurls,mvdan/xurls
18de99b55b77c3d965af8774a99d7abdb2ddea3f
server/response/server_params.go
server/response/server_params.go
package response import ( "fmt" "warcluster/entities" ) type ServerParams struct { baseResponse HomeSPM float64 //ships per minute PlanetsSPM map[string]float64 Races map[string]entities.Race } func NewServerParams() *ServerParams { var planetSizeIdx int8 r := new(ServerParams) r.Races = make(map[...
package response import ( "fmt" "warcluster/entities" ) type ServerParams struct { baseResponse HomeSPM float64 //ships per minute PlanetsSPM map[string]float64 ShipsDeathModifier float64 Races map[string]entities.Race } func NewServerParams() *ServerParams { var planetSizeId...
Add new death modifier to SetupParams
Add new death modifier to SetupParams
Go
mit
WarCluster/warcluster-server,WarCluster/warcluster-server
c25ab2d107b7750f5cc955ff68bb4f8a7c75dccc
pkg/minikube/bootstrapper/kubeadm/default_cni.go
pkg/minikube/bootstrapper/kubeadm/default_cni.go
/* Copyright 2018 The Kubernetes Authors All rights reserved. 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 ag...
/* Copyright 2018 The Kubernetes Authors All rights reserved. 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 ag...
Upgrade CNI config version to 0.3.0
Upgrade CNI config version to 0.3.0 Was using the default version of 0.2.0, didn't load with 0.4.0. closes https://github.com/kubernetes/minikube/issues/4406
Go
apache-2.0
warmchang/minikube,dlorenc/minikube,kubernetes/minikube,warmchang/minikube,warmchang/minikube,dalehamel/minikube,warmchang/minikube,kubernetes/minikube,dlorenc/minikube,kubernetes/minikube,warmchang/minikube,kubernetes/minikube,kubernetes/minikube,kubernetes/minikube,warmchang/minikube,dlorenc/minikube,dalehamel/miniku...
3a012e96adbf7c4ca1b90c3af0b3413d2e5393c5
src/github.com/ericdahl/go-mersenne-primes/lucas-lehmer_test.go
src/github.com/ericdahl/go-mersenne-primes/lucas-lehmer_test.go
package main import ( "testing" ) var mersennes = []int { 2, 3, 5, 7, 13, 17, 19, 31, 61, } func TestPrime(t *testing.T) { for _, p := range mersennes { if !isPrime(p) { t.Errorf("p=[%d] should be calculated as prime", p) } } }
package main import ( "testing" "log" ) var mersennes = []int { 2, 3, 5, 7, 13, 17, 19, 31, 61, } 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 (m...
Update test to also check for composites
Update test to also check for composites
Go
bsd-3-clause
ericdahl/go-mersenne-primes
a0542b662899c105853eaebeef9a751ceb7af00f
models/user_test.go
models/user_test.go
package models import ( "testing" ) func SetUser() *User { return &User { LoginName: "loginName", GitHubUsername: "github_user", SlackUsername: "slack_user", SlackUserId: "SLACKID", } } func TestSlackMention(t *testing.T) { user := SetUser() expect := "<@SLACKID|slack_user>" actual := user.SlackMentio...
package models import ( "testing" ) func SetUser() *User { return &User { LoginName: "loginName", GitHubUsername: "github_user", SlackUsername: "slack_user", SlackUserId: "SLACKID", } } func TestSlackMention(t *testing.T) { user := SetUser() expect := "<@SLACKID|slack_user>" actual := user.SlackMentio...
Check every element of slices
Check every element of slices
Go
mit
wantedly/developers-account-mapper
5d6392b65d25818f52a19c23d4a2f7bb5716fdb3
rpc/legacyrpc/rpcserver_test.go
rpc/legacyrpc/rpcserver_test.go
// Copyright (c) 2013-2014 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package legacyrpc import ( "net/http" "net/http/httptest" "reflect" "testing" "time" ) func TestThrottle(t *testing.T) { const threshold = 1 srv := httptest.Ne...
// Copyright (c) 2013-2014 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package legacyrpc import ( "net/http" "net/http/httptest" "reflect" "testing" ) func TestThrottle(t *testing.T) { const threshold = 1 busy := make(chan struct{})...
Fix race in TestThrottle test.
Fix race in TestThrottle test. Closes #355.
Go
isc
jrick/btcwallet,btcsuite/btcwallet,btcsuite/btcwallet,jrick/btcwallet,jrick/dcrwallet,Roasbeef/btcwallet,synrg-labs/btcwallet,Stash-Crypto/btcwallet,Stash-Crypto/btcwallet,synrg-labs/btcwallet,decred/dcrwallet,jrick/dcrwallet,Roasbeef/btcwallet,decred/dcrwallet
4515b9792230777b10db50b9cdbb5d3fd0c2a035
types.go
types.go
/* Copyright The containerd Authors. 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...
/* Copyright The containerd Authors. 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...
Use uint64 for bandwidth capability
Use uint64 for bandwidth capability Signed-off-by: Johannes M. Scheuermann <84221072773eb526ff46440bf01afde36bd32e36@gmail.com>
Go
apache-2.0
containerd/go-cni,containerd/go-cni
06349aab2d237f87e05132dcbf0732ac4f309a19
routes.go
routes.go
package main import ( _ "expvar" "net/http" "gitlab.com/mattbostock/timeoff/handler" ) func registerRoutes() { mux.Add("GET", "/debug/vars", http.DefaultServeMux) mux.Get("/", handler.Index) }
package main import ( _ "expvar" "net/http" "gitlab.com/mattbostock/timeoff/handler" ) func registerRoutes() { // Expose `expvar` debug variables mux.Add("GET", "/debug/vars", http.DefaultServeMux) mux.Get("/", handler.Index) }
Add comment explaining `/debug/vars` route
Add comment explaining `/debug/vars` route
Go
mit
mattbostock/leavediary
0cf0543a24707bdf99b72591745271447fa39222
pkg/utils/pwd/pwd.go
pkg/utils/pwd/pwd.go
// Copyright 2019 The OpenSDS Authors. // // 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 agre...
// Copyright 2019 The OpenSDS Authors. // // 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 agre...
Remove unneeded log to avoid duplicate log
Remove unneeded log to avoid duplicate log
Go
apache-2.0
opensds/opensds,opensds/opensds,opensds/opensds
cb2f15f770e449cd019212fd8d3c3b78298b73c6
ql/test/query-tests/Security/CWE-190/AllocationSizeOverflowGood2.go
ql/test/query-tests/Security/CWE-190/AllocationSizeOverflowGood2.go
package main import ( "encoding/json" ) func encryptValueGood(v interface{}) ([]byte, error) { jsonData, err := json.Marshal(v) if err != nil { return nil, err } size := uint64(len(jsonData)) + (uint64(len(jsonData)) % 16) buffer := make([]byte, size) copy(buffer, jsonData) return encryptBuffer(buffer) }
package main import ( "encoding/json" ) func encryptValueGood2(v interface{}) ([]byte, error) { jsonData, err := json.Marshal(v) if err != nil { return nil, err } size := uint64(len(jsonData)) + (uint64(len(jsonData)) % 16) buffer := make([]byte, size) copy(buffer, jsonData) return encryptBuffer(buffer) }
Fix frontend errors in `AllocationSizeOverflow` test.
Fix frontend errors in `AllocationSizeOverflow` test.
Go
mit
github/codeql,github/codeql-go,github/codeql-go,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql-go,github/codeql,github/codeql,github/codeql,github/codeql-go,github/codeql
c88fe4ae49b26caef567bad8b7a4e4f1267ca96a
pixy/logging.go
pixy/logging.go
package pixy import ( "fmt" "github.com/mailgun/kafka-pixy/Godeps/_workspace/src/github.com/mailgun/log" "github.com/mailgun/kafka-pixy/Godeps/_workspace/src/github.com/mailgun/sarama" "github.com/mailgun/kafka-pixy/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" ) // InitLibraryLoggers makes the intern...
package pixy import ( "fmt" "github.com/mailgun/kafka-pixy/Godeps/_workspace/src/github.com/mailgun/log" "github.com/mailgun/kafka-pixy/Godeps/_workspace/src/github.com/mailgun/sarama" "github.com/mailgun/kafka-pixy/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" ) // InitLibraryLoggers makes the intern...
Make logger adapters prefix output with library names
Make logger adapters prefix output with library names
Go
apache-2.0
mailgun/kafka-pixy,mailgun/kafka-pixy,mailgun/kafka-pixy
123967e28d46d223de62a175f6aa225c94721ccb
pkg/cmd/branch.go
pkg/cmd/branch.go
package cmd import ( "fmt" "io" "os" "github.com/ClusterHQ/dvol/pkg/api" "github.com/spf13/cobra" ) func NewCmdBranch(out io.Writer) *cobra.Command { cmd := &cobra.Command{ // TODO: Improve the usage string to include a volume name to remove Use: "branch", Short: "List branches on the active volume.", ...
package cmd import ( "fmt" "io" "os" "github.com/ClusterHQ/dvol/pkg/api" "github.com/spf13/cobra" ) func NewCmdBranch(out io.Writer) *cobra.Command { cmd := &cobra.Command{ // TODO: Improve the usage string to include a volume name to remove Use: "branch", Short: "List branches on the active volume.", ...
Update according to comments from rob
Update according to comments from rob
Go
apache-2.0
ClusterHQ/dvol,ClusterHQ/dvol,ClusterHQ/dvol
7ebdcd7ee77d88e37e3354cec46eeca3f1c9bf0b
types/common.go
types/common.go
/* Package types implements support for the types used in the Navitia API (see doc.navitia.io), simplified and modified for idiomatic Go use. This package was and is developed as a supporting library for the gonavitia API client (https://github.com/aabizri/gonavitia) but can be used to build other API clients. This s...
/* Package types implements support for the types used in the Navitia API (see doc.navitia.io), simplified and modified for idiomatic Go use. This package was and is developed as a supporting library for the gonavitia API client (https://github.com/aabizri/navitia) but can be used to build other API clients. */ packag...
Update package-level documentation in navitia/types
Update package-level documentation in navitia/types
Go
unlicense
aabizri/navitia,aabizri/navitia
0a88fd404a28faa2b1359a5450713963961e64a7
plot/plot_test.go
plot/plot_test.go
package plot import ( "testing" ) func TestDrawImage(t *testing.T) { Example().Save(4, 4, "test.png") } func TestDrawEps(t *testing.T) { Example().Save(4, 4, "test.eps") }
package plot import ( "testing" ) func TestDrawImage(t *testing.T) { if err := Example().Save(4, 4, "test.png"); err != nil { t.Error(err) } } func TestDrawEps(t *testing.T) { if err := Example().Save(4, 4, "test.eps"); err != nil { t.Error(err) } }
Test for errors in the test.
Test for errors in the test.
Go
mit
aquarat/plotinum,tectronics/plotinum,zhanglong2005/plotinum
10adbb2bdfa621ae3ac43736bd1a23781988b6ea
context.go
context.go
package stack import ( "fmt" "sync" ) type Context struct { mu sync.RWMutex m map[string]interface{} } func NewContext() *Context { m := make(map[string]interface{}) return &Context{m: m} } func (c *Context) Get(key string) (interface{}, error) { c.mu.RLock() defer c.mu.RUnlock() val := c.m[key] if val =...
package stack import ( "fmt" "sync" ) type Context struct { mu sync.RWMutex m map[string]interface{} } func NewContext() *Context { m := make(map[string]interface{}) return &Context{m: m} } func (c *Context) Get(key string) (interface{}, error) { c.mu.RLock() defer c.mu.RUnlock() val := c.m[key] if val =...
Use double-quoted string in error message
Use double-quoted string in error message
Go
mit
alexedwards/stack
c131b0b4397f177324d693b09759eea007b8c41e
cmd/transmission-exporter/main.go
cmd/transmission-exporter/main.go
package main import ( "log" "net/http" transmission "github.com/metalmatze/transmission-exporter" "github.com/prometheus/client_golang/prometheus" ) const ( path string = "/metrics" addr string = ":19091" ) func main() { log.Println("starting transmission-exporter") client := transmission.New("http://local...
package main import ( "log" "net/http" arg "github.com/alexflint/go-arg" transmission "github.com/metalmatze/transmission-exporter" "github.com/prometheus/client_golang/prometheus" ) type Config struct { WebPath string `arg:"env:WEB_PATH"` WebAddr string `arg:"env:WEB_ADDR"` Transmi...
Add Config{} that gets content loaded from env
Add Config{} that gets content loaded from env
Go
mit
metalmatze/transmission-exporter
37487e685b21926ec218d1d3f0948459fcbb32f2
go/keyderivation/internal/streamingprf/streaming_prf_test.go
go/keyderivation/internal/streamingprf/streaming_prf_test.go
// Copyright 2022 Google LLC // // 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 ...
// Copyright 2022 Google LLC // // 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 ...
Add comment to streamingprf_test's limitFromHash().
Add comment to streamingprf_test's limitFromHash(). PiperOrigin-RevId: 476540085
Go
apache-2.0
google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink
d0352a6064678c0cca4c4b6019ee0476ccb34e28
nats_requester.go
nats_requester.go
package bench import ( "time" "github.com/nats-io/nats" ) // NATSRequester implements Requester by publishing a message to NATS and // waiting to receive it. type NATSRequester struct { URL string PayloadSize int Subject string conn *nats.Conn sub *nats.Subscription msg []b...
package bench import ( "time" "github.com/nats-io/nats" ) // NATSRequester implements Requester by publishing a message to NATS and // waiting to receive it. type NATSRequester struct { URL string PayloadSize int Subject string conn *nats.Conn sub *nats.Subscription msg []b...
Fix NATSRequester to connect to right URL
Fix NATSRequester to connect to right URL
Go
apache-2.0
tylertreat/bench
a0c5eb039ee82477bef82de69c679b9d6e8c098b
librariesio/librariesio_test.go
librariesio/librariesio_test.go
package librariesio import ( "testing" "time" ) const APIKey string = "1234" func TestNewClient(t *testing.T) { c := NewClient(APIKey) if got, want := c.apiKey, APIKey; got != want { t.Errorf("NewClient baseURL is %v, want %v", got, want) } if got, want := c.BaseURL.String(), "https://libraries.io/api/"; g...
package librariesio import ( "testing" "time" ) const APIKey string = "1234" func TestNewClient(t *testing.T) { c := NewClient(APIKey) if got, want := c.apiKey, APIKey; got != want { t.Errorf("NewClient baseURL is %v, want %v", got, want) } if got, want := c.BaseURL.String(), "https://libraries.io/api/"; g...
Add a basic test for client.NewRequest for no payload
Add a basic test for client.NewRequest for no payload
Go
mit
hackebrot/go-librariesio
a87a0f30d6325705f200c2137dbb2d5a9b0222b9
pkg/term/tc_linux_cgo.go
pkg/term/tc_linux_cgo.go
// +build linux,cgo package term import ( "syscall" "unsafe" ) // #include <termios.h> import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr)...
// +build linux,cgo package term import ( "syscall" "unsafe" ) // #include <termios.h> import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr)...
Fix weird terminal output format
Fix weird terminal output format Signed-off-by: Lei Jitang <9ac444d2b5df3db1f31aa1c6462ac8e9e2bde241@huawei.com>
Go
apache-2.0
moby/term
bdad1a9d5e902c11f0854bbc61a1e4e8136c9bba
api/endpoints/context_helpers.go
api/endpoints/context_helpers.go
package api import "github.com/labstack/echo" // GetProjectID returns projectID for current HTTP request func GetProjectID(c echo.Context) int64 { return c.Get("projectID").(int64) }
package api import ( "errors" "github.com/labstack/echo" ) // GetProjectID returns projectID for current HTTP request func GetProjectID(c echo.Context) int64 { if projectID, ok := c.Get("projectID").(int64); ok { return projectID } panic(errors.New("failed to get projectID, is mw.RequireProject call missing?"...
Use safe type assertion in GetProjectID
Use safe type assertion in GetProjectID
Go
mit
diyan/assimilator,diyan/assimilator,diyan/assimilator
d85d2805568f8ea3af628aa82192c497e4229981
resources/ec2-subnets.go
resources/ec2-subnets.go
package resources import ( "fmt" "github.com/aws/aws-sdk-go/service/ec2" ) type EC2Subnet struct { svc *ec2.EC2 id *string region *string } func (n *EC2Nuke) ListSubnets() ([]Resource, error) { params := &ec2.DescribeSubnetsInput{} resp, err := n.Service.DescribeSubnets(params) if err != nil { retu...
package resources import "github.com/aws/aws-sdk-go/service/ec2" type EC2Subnet struct { svc *ec2.EC2 id *string region *string } func (n *EC2Nuke) ListSubnets() ([]Resource, error) { params := &ec2.DescribeSubnetsInput{} resp, err := n.Service.DescribeSubnets(params) if err != nil { return nil, err ...
Revert "fixup! CLOUD-1047: Add region to resources"
Revert "fixup! CLOUD-1047: Add region to resources" This reverts commit 05773b07489f247b989f30f866bcba77d9522ac8.
Go
mit
rebuy-de/aws-nuke,rebuy-de/aws-nuke
8f937ea95c24488e1ac6fb824d3493fd0c34d521
examples/methodhandler.go
examples/methodhandler.go
package main import ( "github.com/xyproto/web.go" ) type Greeter struct { greeting string } func (g *Greeter) Greet(s string) string { return g.greeting + " " + s } func main() { g := &Greeter{"hello"} web.Get("/(.*)", func(ctx *web.Context, path string) string { return g.Greet(path) }) web.Run("0.0.0.0:9999"...
package main import ( "github.com/xyproto/web.go" ) type Greeter struct { greeting string } func (g *Greeter) Greet(s string) string { return g.greeting + " " + s } func main() { g := &Greeter{"hello"} web.Get("/(.*)", web.MethodHandler(g, "Greet")) web.Run("0.0.0.0:9999") }
Revert "fixed method handler example"
Revert "fixed method handler example" This reverts commit 3d470f58ea86647a80763e02608a3f2a9b2a06b6.
Go
mit
hraban/web
20ee955c66228e098680b7bf99bb02a9fb0dc526
http_handlers/rest_json/utils.go
http_handlers/rest_json/utils.go
package rest_json import ( "encoding/json" "fmt" "net/http" ) func bodyWithMessage(message string) []byte { body, err := json.Marshal(map[string]interface{}{ "message": message, }) if err != nil { panic(err) // Something real bad happened } return body } func respondWithError(res http.ResponseWriter, err...
package rest_json import ( "encoding/json" "net/http" ) func bodyWithMessage(message string) []byte { body, err := json.Marshal(map[string]interface{}{ "message": message, }) if err != nil { panic(err) // Something real bad happened } return body } func respondWithError(res http.ResponseWriter, err error,...
Fix response writing in REST API
Fix response writing in REST API
Go
mit
Everlane/evan
5cb47021ac15f00e54151de0c7aefa03461a980c
bencode/misc.go
bencode/misc.go
package bencode import ( "reflect" "unsafe" ) // Wow Go is retarded. var marshalerType = reflect.TypeOf(func() *Marshaler { var m Marshaler return &m }()).Elem() // Wow Go is retarded. var unmarshalerType = reflect.TypeOf(func() *Unmarshaler { var i Unmarshaler return &i }()).Elem() func bytesAsString(b []byt...
package bencode import ( "reflect" "unsafe" ) // Wow Go is retarded. var marshalerType = reflect.TypeOf(func() *Marshaler { var m Marshaler return &m }()).Elem() // Wow Go is retarded. var unmarshalerType = reflect.TypeOf(func() *Unmarshaler { var i Unmarshaler return &i }()).Elem() func bytesAsString(b []byt...
Fix possible misuse of reflect.StringHeader
Fix possible misuse of reflect.StringHeader
Go
mpl-2.0
anacrolix/torrent,anacrolix/torrent
027a290a2d885cf93d296769570a840a78b2981d
server.go
server.go
package main import ( "fmt" "io" //"io/ioutil" "log" "net/http" "os" //"strings" ) func receive(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello world!") } func main() { // Read the port from the file. //fileContents, err := ioutil.ReadFile("port.txt") //if err != nil { // log.Fatal(err...
package main import ( "fmt" //"io" //"io/ioutil" "log" "net/http" "os" //"strings" ) func receive(w http.ResponseWriter, r *http.Request) { wholeurl := r.URL.String() body := r.URL.Query()["Body"] phone := r.URL.Query()["From"] fmt.Printf("wholeurl:\n%s\n\nPhone: %s\nBody: %s,\n\n", wholeurl, phone, body...
Print out phone number and message from twilio get requests
Print out phone number and message from twilio get requests
Go
apache-2.0
ovaskevich/TxtRoulette
1e3609474470876732e0db9852f2fadad4021d0a
anony_func/main.go
anony_func/main.go
// http://blog.denevell.org/golang-closures-anonymous-functions.html package main import "fmt" func main() { anon := func(name string) string { return "Hiya, " + name } anotherFunction(anon) } func anotherFunction(f func(string) string) { result := f("David") fmt.Println(result) // Prints "Hiya, David" }
// http://blog.denevell.org/golang-closures-anonymous-functions.html package main import "fmt" func main() { anon := func(name string) string { return "Hiya" } anonyFunc(anon) } func anonyFunc(f func(string) string) { result := f("David") fmt.Println(result) // Prints "Hiya, David" }
Fix anonymous func name & Remove name arg
Fix anonymous func name & Remove name arg Signed-off-by: Koichi Shiraishi <2e5bdfebde234ed3509bcfc18121c70b6631e207@gmail.com>
Go
bsd-3-clause
zchee/cgo,zchee/cgo
73367ff68093dfddc3bf4ecafed31853d0867375
signaller/notification.go
signaller/notification.go
package signaller import ( "fmt" ) // NotifySource indicates what mechanism triggered the event. type NotifySource int // String provides a printable representation of a NotifySource. func (ns NotifySource) String() string { switch ns { case KNS_TIMER: return "timer" case KNS_ZK: return "zk" default: retu...
package signaller import ( "fmt" ) // NotifySource indicates what mechanism triggered the event. type NotifySource int // String provides a printable representation of a NotifySource. func (ns NotifySource) String() string { switch ns { case KNS_FORCED: return "forced" case KNS_TIMER: return "timer" case KN...
Add a "forced" NotifySource constant
Add a "forced" NotifySource constant
Go
bsd-2-clause
mredivo/pulldeploy,mredivo/pulldeploy
48b2b60608a101d56c6835dfa5aa1d08deda0910
go/src/socialapi/workers/emailnotifier/models/templateparser_test.go
go/src/socialapi/workers/emailnotifier/models/templateparser_test.go
package models import ( "testing" "socialapi/config" . "github.com/smartystreets/goconvey/convey" ) func TestTemplateRender(t *testing.T) { uc := UserContact{} Convey("Daily email", t, func() { Convey("Should load a correct config", func() { So(func() { config.MustRead("./tes...
package models import ( "testing" "socialapi/config" . "github.com/smartystreets/goconvey/convey" ) func TestTemplateRender(t *testing.T) { uc := UserContact{} Convey("Daily email", t, func() { Convey("Should load a correct config", func() { So(func() { config.MustRead("./test...
Add unit test for daily email
Add unit test for daily email
Go
agpl-3.0
jack89129/koding,gokmen/koding,cihangir/koding,szkl/koding,koding/koding,sinan/koding,cihangir/koding,kwagdy/koding-1,alex-ionochkin/koding,rjeczalik/koding,drewsetski/koding,drewsetski/koding,acbodine/koding,andrewjcasal/koding,acbodine/koding,kwagdy/koding-1,mertaytore/koding,gokmen/koding,drewsetski/koding,alex-iono...
e3b45696e080e7f51f1fcf0e0881200e83a256fd
settings/settings.go
settings/settings.go
package settings import ( "io/ioutil" "upper.io/db" "upper.io/db/mysql" ) // CHANGE IN PRODUCTION // KEEP SECRET!!! var SecretKey = "dongLyfe420" var Themes = [...]string{"material", "space"} var dbsettings = mysql.ConnectionURL{ Address: db.Socket("/var/run/mysqld/mysqld.sock"), Database: "lambda_go", User:...
package settings import ( "io/ioutil" "upper.io/db" "upper.io/db/mysql" ) // CHANGE IN PRODUCTION // KEEP SECRET!!! var SecretKey = "dongLyfe420" var Themes = [...]string{"material", "space"} var dbsettings = mysql.ConnectionURL{ Address: db.Socket("/var/run/mysqld/mysqld.sock"), Database: "lambda_go", User:...
Load secret key from file
Load secret key from file
Go
bsd-2-clause
marcusant/Lambda-Go,marcusant/Lambda-Go,mstojcevich/Lambda-Go,mstojcevich/Lambda-Go,marcusant/Lambda-Go,mstojcevich/Lambda-Go
9b7b65e49057b0baf39c96426f22b1d9d17a17e8
csc/cmd/controller_get_capacity.go
csc/cmd/controller_get_capacity.go
package cmd import ( "context" "fmt" "github.com/spf13/cobra" "github.com/container-storage-interface/spec/lib/go/csi" ) var getCapacity struct { caps volumeCapabilitySliceArg } var getCapacityCmd = &cobra.Command{ Use: "get-capacity", Aliases: []string{"capacity"}, Short: `invokes the rpc "GetCapaci...
package cmd import ( "context" "fmt" "github.com/spf13/cobra" "github.com/container-storage-interface/spec/lib/go/csi" ) var getCapacity struct { caps volumeCapabilitySliceArg params mapOfStringArg } var getCapacityCmd = &cobra.Command{ Use: "get-capacity", Aliases: []string{"capacity"}, Short: `i...
Add --params flag to get-capacity
Add --params flag to get-capacity
Go
apache-2.0
akutz/gocsi,akutz/gocsi
b9686df0c97c6c029495830042a2aeb52c7d5a0a
oauto/api/api.go
oauto/api/api.go
package api import ( "net/http" "github.com/ibrt/go-oauto/oauto/config" "encoding/json" "fmt" ) type ApiHandler func(config *config.Config, r *http.Request, baseURL string) (interface{}, error) func RegisterApiRoutes(config *config.Config) { http.HandleFunc("/api/authenticate", MakeHandlerFunc(config, HandleAut...
package api import ( "net/http" "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) func RegisterApiRoutes(config *config.Config) { http.HandleFunc("/api/authenticate", Ma...
Improve error reporting in API response.
Improve error reporting in API response.
Go
mit
ibrt/go-oauto,ibrt/go-oauto
0023a2a2598aa5d36d57230c7cb6086d93bb2d09
index/handler.go
index/handler.go
package index import ( "database/sql" "html/template" "log" "net/http" "github.com/concourse/atc" "github.com/concourse/atc/db" "github.com/pivotal-golang/lager" ) type TemplateData struct{} func NewHandler( logger lager.Logger, pipelineDBFactory db.PipelineDBFactory, pipelineHandler func(db.PipelineDB) h...
package index import ( "database/sql" "html/template" "log" "net/http" "github.com/concourse/atc" "github.com/concourse/atc/db" "github.com/pivotal-golang/lager" ) type TemplateData struct{} func NewHandler( logger lager.Logger, pipelineDBFactory db.PipelineDBFactory, pipelineHandler func(db.PipelineDB) h...
Add return in index to prevent 2 write responses
Add return in index to prevent 2 write responses
Go
apache-2.0
concourse/concourse,concourse/concourse,concourse/concourse,concourse/concourse,concourse/concourse
91cd0bf56db9a0840b52e40ebc130b12233b6b45
src/wapbot.co.uk/crawlapp/main.go
src/wapbot.co.uk/crawlapp/main.go
package main import ( "flag" "fmt" "log" "net/url" "os" "runtime/pprof" "wapbot.co.uk/crawler" ) var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } pprof....
package main import ( "flag" "fmt" "log" "net/url" "os" "runtime" "runtime/pprof" "wapbot.co.uk/crawler" ) var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") func main() { flag.Parse() fmt.Printf("GOMAXPROCS is set to: %d\n", runtime.GOMAXPROCS(-1)) if *cpuprofile != "" { f, e...
Add output with the number of CPU that will be used.
Add output with the number of CPU that will be used.
Go
mit
yoink00/crawler,yoink00/crawler
2ce9a9b374519db51cc889a3473a550450a4daa9
cmd/server/main.go
cmd/server/main.go
package main import ( "github.com/itsankoff/gotcha/server" "time" "log" ) func main() { s := server.New() wss := server.NewWebSocket() s.AddTransport("127.0.0.1:9000", &wss) done := make(chan interface{}) // go func() { // log.Println("Will close done channel") // time...
package main import ( "github.com/itsankoff/gotcha/server" "time" "log" ) func main() { s := server.New() wss := server.NewWebSocket() s.AddTransport("127.0.0.1:9000", &wss) done := make(chan interface{}) go func() { log.Println("Will close done channel") time.Sleep(10 ...
Add error handling for server's Start method
Add error handling for server's Start method
Go
mit
itsankoff/gotcha,itsankoff/gotcha
241c0115a1d1a7414bbe22408635276581270787
2019/cgo-callback/example_test.go
2019/cgo-callback/example_test.go
package main import "testing" type testVisitor struct { start int end int } func (v *testVisitor) Start(i int) { v.start = i } func (v *testVisitor) End(a, b int) { v.end = a + b } func TestTraverseBasic(t *testing.T) { var v testVisitor GoTraverse("joe", &v) if v.start != 100 { t.Errorf("start got %v,...
// Run these tests with -race package main import ( "math/rand" "sync" "testing" "time" ) type testVisitor struct { start int end int } func (v *testVisitor) Start(i int) { v.start = i } func (v *testVisitor) End(a, b int) { v.end = a + b } func TestTraverseBasic(t *testing.T) { var v testVisitor GoTra...
Add some testing with concurrency
Add some testing with concurrency
Go
unlicense
eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog
f527e9ddd72dd7995afac6bab46c7ec1d15b5437
pkg/model/service/list.go
pkg/model/service/list.go
package service import "github.com/containerum/kube-client/pkg/model" type ServiceList []Service func ServiceListFromKube(kubeList model.ServicesList) ServiceList { var list ServiceList = make([]Service, 0, len(kubeList.Services)) for _, kubeService := range kubeList.Services { list = append(list, ServiceFromKub...
package service import "github.com/containerum/kube-client/pkg/model" type ServiceList []Service func ServiceListFromKube(kubeList model.ServicesList) ServiceList { var list ServiceList = make([]Service, 0, len(kubeList.Services)) for _, kubeService := range kubeList.Services { list = append(list, ServiceFromKub...
Allow internal services to be used in ingresses
Allow internal services to be used in ingresses
Go
mit
containerum/chkit,containerum/chkit
9ce57fbcbca565916398e1c11623b87fd032edfb
logger/stats.go
logger/stats.go
package logger import ( "fmt" "sort" "time" ) var tickLog = GetLogger("stats") // The interval between logging the number of actions/sec var ReportInterval = time.Second * 5 var ticks = make(map[string]int) func init() { go func() { for { time.Sleep(ReportInterval) if len(ticks) == 0 { continue ...
package logger import ( "fmt" "sort" "time" "sync" ) var tickLog = GetLogger("stats") // The interval between logging the number of actions/sec var ReportInterval = time.Second * 5 var ticks = make(map[string]int) var mu = sync.Mutex{} func init() { go func() { for { time.Sleep(ReportInterval) if len...
Add a mutex to guard access to the ticks map.
Add a mutex to guard access to the ticks map. The need to do this became apparent once compiling with go 1.6 which it now does more aggressive race condition checks. Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@wildducktheories.com>
Go
mit
ninjasphere/go-ninja,ninjasphere/go-ninja
6c463461d2ffecfcf911bf0915bdf44144fb698b
cmd/scollector/collectors/snmp.go
cmd/scollector/collectors/snmp.go
package collectors import ( "fmt" "io" "github.com/mjibson/snmp" ) // snmp_subtree takes an oid and returns all data exactly one level below it. It // produces an error if there is more than one level below. func snmp_subtree(host, community, oid string) (map[int]interface{}, error) { rows, err := snmp.Walk(host...
package collectors import ( "fmt" "io" "math/big" "github.com/mjibson/snmp" ) // snmp_subtree takes an oid and returns all data exactly one level below it. It // produces an error if there is more than one level below. func snmp_subtree(host, community, oid string) (map[int]interface{}, error) { rows, err := sn...
Use math/big for certain OIDs
cmd/scollector: Use math/big for certain OIDs fixes #28
Go
mit
couchand/bosun,bosun-sharklasers/bosun,dieface/bosun,bridgewell/bosun,dimamedvedev/bosun,couchand/bosun,briantist/bosun,seekingalpha/bosun,objStorage/bosun,mxk1235/bosun,bosun-monitor/bosun,madhukarreddy/bosun,jareksm/bosun,bridgewell/bosun,youngl98/bosun,shanemadden/bosun,augporto/bosun,couchand/bosun,bosun-sharklaser...
103d3d0a018556293bd7542436b9c7fa9d161e7f
evepraisal/config.go
evepraisal/config.go
package main import "github.com/spf13/viper" func init() { viper.SetDefault("base-url", "http://127.0.0.1:8080") viper.SetDefault("http_addr", ":8080") viper.SetDefault("https_addr", "") viper.SetDefault("https_domain-whitelist", []string{"evepraisal.com"}) viper.SetDefault("letsencrypt_email", "") viper.SetDef...
package main import "github.com/spf13/viper" func init() { viper.SetDefault("base-url", "http://127.0.0.1:8080") viper.SetDefault("http_addr", ":8080") viper.SetDefault("https_addr", "") viper.SetDefault("https_domain-whitelist", []string{"evepraisal.com"}) viper.SetDefault("letsencrypt_email", "") viper.SetDef...
Change default ESI URL to the new one
Change default ESI URL to the new one
Go
mit
evepraisal/go-evepraisal,evepraisal/go-evepraisal,evepraisal/go-evepraisal
9d9132668ae3d395940c3c67c4c23265c48f9c92
cmd/root.go
cmd/root.go
package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" "os" ) var Vebose bool = false var cfgFile string var RootCmd = &cobra.Command{ Short: "Proj simplifies local development config", Long: ``, } func init() { cobra.OnInitialize(initConfig) RootCmd.Persistent...
package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" "os" ) var verbose bool = false var cfgFile string var RootCmd = &cobra.Command{ Short: "Proj simplifies local development config", Long: ``, } func init() { cobra.OnInitialize(initConfig) RootCmd.Persisten...
Add verbose as viper flag and fix spelling
Add verbose as viper flag and fix spelling
Go
mit
SolidWorx/ProJ
e6c27b2b8f76e5d664752aa5487169981756a5bc
euler/templates.go
euler/templates.go
package main var ( problemTemplate = `/* {{problem_description}} */ package main import "github.com/jacobhands/pu" var ( answer = "NA" // Change to correct answer once solved. problem = pu.Problem{ ID: 1, Solver: solve, CorrectAnswer: answer} ) func main() { problem.Answer() } func sol...
package main var ( problemTemplate = `/* {{problem_description}} */ package main import "github.com/jacobhands/pu" var ( answer = "NA" // Change to correct answer once solved. problem = pu.Problem{ ID: 1, Solver: solve, CorrectAnswer: answer} ) func main() { problem.Answer() } // This ...
Add comment to template for clarity
Add comment to template for clarity
Go
mit
jacobhands/pu
95d18b713432aa052b3d2cdc8a71d63482127875
useragent.go
useragent.go
package main import ( "net/http" "strings" ) var ( // Whitelist crawlers here crawlerPatterns = [...]string{ "Googlebot", "bingbot", "MSNbot", "facebookexternalhit", "PlurkBot", "Twitterbot", } ) func isCrawlerUserAgent(r *http.Request) bool { ua := r.UserAgent() for _, pattern := range crawlerPa...
package main import ( "net/http" "strings" ) var ( // Whitelist crawlers here crawlerPatterns = [...]string{ "Googlebot", "bingbot", "MSNbot", "facebookexternalhit", "PlurkBot", "Twitterbot", "CloudFlare-AlwaysOnline", } ) func isCrawlerUserAgent(r *http.Request) bool { ua := r.UserAgent() for ...
Add CloudFlare AlwaysOnline to crawler list
Add CloudFlare AlwaysOnline to crawler list
Go
mit
ptt/pttweb
afa6221178a5ceb0ff20a9232307d183f264ae0f
bootstrap/integration/main_test.go
bootstrap/integration/main_test.go
package integration import ( "io/ioutil" "log" "os" "os/exec" "path/filepath" "runtime" "testing" ) var agentBinary string // This init compiles a bootstrap to be invoked by the bootstrap tester // We could possibly use the compiled test stub, but ran into some issues with mock compilation func compileBootstr...
package integration import ( "io/ioutil" "log" "os" "os/exec" "path/filepath" "runtime" "testing" ) var agentBinary string // This init compiles a bootstrap to be invoked by the bootstrap tester // We could possibly use the compiled test stub, but ran into some issues with mock compilation func compileBootstr...
Add a .exe to the compile bootstrap for testing
Add a .exe to the compile bootstrap for testing
Go
mit
buildkite/agent,buildkite/agent,buildkite/agent
af376fedf745cf30afaae5a960c9eb439b574269
web/index/handler.go
web/index/handler.go
package index import ( "database/sql" "html/template" "log" "net/http" "github.com/concourse/atc" "github.com/concourse/atc/db" "github.com/pivotal-golang/lager" ) type TemplateData struct{} func NewHandler( logger lager.Logger, pipelineDBFactory db.PipelineDBFactory, pipelineHandler func(db.PipelineDB) h...
package index import ( "database/sql" "html/template" "log" "net/http" "github.com/concourse/atc" "github.com/concourse/atc/db" "github.com/pivotal-golang/lager" ) type TemplateData struct{} func NewHandler( logger lager.Logger, pipelineDBFactory db.PipelineDBFactory, pipelineHandler func(db.PipelineDB) h...
Add return in index to prevent 2 write responses
Add return in index to prevent 2 write responses
Go
apache-2.0
concourse/concourse,concourse/concourse,concourse/concourse,concourse/concourse,concourse/concourse
e3fe637d6d2c21d7027982ccd220345a6acbee11
go/src/aoc17/problems/p01/p01.go
go/src/aoc17/problems/p01/p01.go
package p01 import ( "fmt" "common" ) func Solve(input string) (string, string) { return solve(input, 1), solve(input, len(input)/2) } func solve(input string, lookahead int) string { sum := 0 for i := 0; i < len(input); i += 1 { if input[i] == input[(i+lookahead)%len(input)] { sum += int(common.ToIntOrPan...
package p01 import ( "fmt" "common" ) // --- Day 1: Inverse Captcha --- // http://adventofcode.com/2017/day/1 func Solve(input string) (string, string) { return solve(input, 1), solve(input, len(input)/2) } func solve(input string, lookahead int) string { sum := 0 for i := 0; i < len(input); i += 1 { if input...
Add link to puzzle to code.
Add link to puzzle to code.
Go
apache-2.0
shaeberling/euler,shaeberling/euler,shaeberling/euler,shaeberling/euler
54e415353fe766cd7d856e9cd6d7d04013b90b28
main.go
main.go
package main import ( "flag" "fmt" "os" ) var ( port int storage string dockerHost string dockerCertPath string ) func init() { flag.IntVar(&port, "port", 8080, "port number") flag.StringVar(&storage, "storage", "filesystem", "storage type") flag.StringVar(&dockerHost, "docker-host", o...
package main import ( "flag" "fmt" "os" "strconv" ) var ( port int storage string dockerHost string dockerCertPath string ) func init() { defaultPort, _ := strconv.Atoi(os.Getenv("PORT")) flag.IntVar(&port, "port", defaultPort, "port number") flag.StringVar(&storage, "storage", "files...
Change port option default value.
Change port option default value.
Go
mit
monochromegane/torokko
50edc3655ef91f22de01ba122a09f722557fa469
main.go
main.go
/* Package sentences is a golang package will convert a blob of text into a list of sentences. This package attempts to support a multitude of languages: czech, danish, dutch, english, estonian, finnish, french, german, greek, italian, norwegian, polish, portuguese, slovene, spanish, swedish, and turkish. An unsuperv...
/* Package sentences is a golang package that will convert a blob of text into a list of sentences. This package attempts to support a multitude of languages: Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Italian, Norwegian, Polish, Portuguese, Slovene, Spanish, Swedish, and Turkish. An uns...
Fix typos discovered by the Debian Lintian tool
Fix typos discovered by the Debian Lintian tool
Go
mit
neurosnap/sentences,neurosnap/sentences
5e53e3dd7de0df7b2426d14aff333f0d940e1694
pipe.go
pipe.go
package main import ( "net" "runtime" "sync/atomic" ) const ( BufSize = 256 ) // Copy data between two connections. Return EOF on connection close. func Pipe(a, b net.Conn) error { done := make(chan error) var stop int32 defer func() { atomic.StoreInt32(&stop, 1) }() cp := func(r, w net.Conn) { var err...
package main import ( "net" "sync/atomic" ) const ( BufSize = 256 ) // Copy data between two connections. Return EOF on connection close. func Pipe(a, b net.Conn) error { done := make(chan error) var stop int32 defer func() { atomic.StoreInt32(&stop, 1) }() cp := func(r, w net.Conn) { var err error va...
Remove Gosched call as network I/O blocks.
Remove Gosched call as network I/O blocks.
Go
bsd-3-clause
BlueDragonX/go-proxy-example
7c89dc46f539fe69588b2721f03875624ac455da
play.go
play.go
package main import ( "github.com/gordonklaus/portaudio" ) const playBufferSize = 8192 func playTune(tune []int32, sampleRate float64) error { err := portaudio.Initialize() if err != nil { return err } defer portaudio.Terminate() buffer := make([]int32, playBufferSize) stream, err := portaudio.OpenDefaultSt...
package main import ( "github.com/Orion90/portaudio" ) const playBufferSize = 8192 func playTune(tune []int32, sampleRate float64) error { err := portaudio.Initialize() if err != nil { return err } defer portaudio.Terminate() buffer := make([]int32, playBufferSize) stream, err := portaudio.OpenDefaultStream...
Switch to Orion90's fork of the go portaudio wrapper, for fixes to run with go 1.6
Switch to Orion90's fork of the go portaudio wrapper, for fixes to run with go 1.6
Go
bsd-2-clause
draringi/synthia
8161abe1e7aaa6bfbdf87f6e635c8ba73c731701
agorn_test.go
agorn_test.go
package main import ( "bytes" "testing" ) type offsetTest struct { data []byte offset int byteOffset int } var offsetTests = []offsetTest{ offsetTest{[]byte("abcdef"), 0, 0}, offsetTest{[]byte("abcdef"), 1, 1}, offsetTest{[]byte("abcdef"), 5, 5}, offsetTest{[]byte("日本語def"), 0, 0}, offsetTest{[]b...
// Copyright (c) 2014 David R. Jenni. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "testing" ) type offsetTest struct { data []byte offset int byteOffset int } var offsetTests = []offsetTest{...
Add license statement to test file.
Add license statement to test file.
Go
bsd-2-clause
davidrjenni/agorn
b90e4837fbb0c1c1be17a712e3390beef9015057
text.go
text.go
// Copyright 2015 The Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package markdown import "strings" func isTerminatorChar(ch byte) bool { return strings.IndexByte("\n!#$%&*+-:<=>@[\\]^_`{}~", ch) != -1 } func ruleText(s *Stat...
// Copyright 2015 The Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package markdown var terminatorCharTable = [256]bool{ '\n': true, '!': true, '#': true, '$': true, '%': true, '&': true, '*': true, '+': true, '-'...
Use character table for faster lookup (-6-8% ns/op)
Use character table for faster lookup (-6-8% ns/op)
Go
bsd-2-clause
golang-commonmark/markdown
1d4341684f3124ce06f061929a512b31b7c57216
core/exec.go
core/exec.go
package core import ( "io" "os/exec" "strings" "github.com/kr/pty" ) type Command struct { command string args []string } func NewCommand(command string, args ...string) Command { return Command{command, args} } // Install is a command executer for install commands. func (c Command) Install(input []strin...
package core import ( "io" "os/exec" "strings" "github.com/kr/pty" ) type Command struct { command string args []string } func NewCommand(command string, args ...string) Command { return Command{command, args} } // Install is a command executer for install commands. func (c Command) Install(input ...stri...
Change Install command to accept variadic input.
Change Install command to accept variadic input.
Go
mit
hansrodtang/runcom,hansrodtang/runcom
7f750bd33ce9cd8eab697bd7c19cd2a19f4a6e05
persistence/in_memory_provider.go
persistence/in_memory_provider.go
package persistence import "github.com/gogo/protobuf/proto" type NoSnapshotSupport struct { } func (provider *NoSnapshotSupport) GetSnapshotInterval() int { return 0 //snapshotting is disabled } func (provider *NoSnapshotSupport) GetPersistSnapshot(actorName string) func(snapshot interface{}) { return nil } func...
package persistence import "github.com/golang/protobuf/proto" type snapshotEntry struct { eventIndex int snapshot proto.Message } type InMemoryProvider struct { snapshotInterval int snapshots map[string]*snapshotEntry // actorName -> a snapshot entry events map[string][]proto.Message // acto...
Improve the in-memory implementation of persistence provider
Improve the in-memory implementation of persistence provider
Go
apache-2.0
AsynkronIT/gam,AsynkronIT/protoactor-go,AsynkronIT/protoactor-go,rogeralsing/gam,Huawei-PTLab/protoactor-go,Huawei-PTLab/protoactor-go,AsynkronIT/gam
48d9c0605c92f092ea82e675a103b645446db0e3
db/query_account_by_address.go
db/query_account_by_address.go
package db import "golang.org/x/net/context" // AccountByAddressQuery represents a query that retrieves a composite // of the CoreAccount and the HistoryAccount associated with an address. type AccountByAddressQuery struct { History SqlQuery Core SqlQuery Address string } // Get executes the query, returning a...
package db import "golang.org/x/net/context" // AccountByAddressQuery represents a query that retrieves a composite // of the CoreAccount and the HistoryAccount associated with an address. type AccountByAddressQuery struct { History SqlQuery Core SqlQuery Address string } // Get executes the query, returning a...
Fix test breakage in db
Fix test breakage in db
Go
apache-2.0
FredericHeem/go-horizon,stellar/horizon,lackac/horizon,stellar/horizon,FredericHeem/go-horizon,lackac/horizon,nullstyle/go-horizon,stellar/horizon,irisli/horizon,masonforest/go-horizon,masonforest/horizon,masonforest/horizon,masonforest/go-horizon,irisli/horizon,nullstyle/go-horizon,masonforest/horizon,nullstyle/go-hor...
d77e77680d52d232305d0f12af6e3e1c857903cb
pkg/server/handler.go
pkg/server/handler.go
package server import ( "mime" "net/http" "path" "path/filepath" "github.com/facette/facette/pkg/logger" ) func (server *Server) serveError(writer http.ResponseWriter, status int) { err := server.execTemplate( writer, status, struct { URLPrefix string ReadOnly bool Status int }{ URLPref...
package server import ( "mime" "net/http" "path" "path/filepath" "github.com/facette/facette/pkg/logger" ) func (server *Server) serveError(writer http.ResponseWriter, status int) { err := server.execTemplate( writer, status, struct { URLPrefix string ReadOnly bool Status int }{ URLPref...
Add default MIME type for JSON files
Add default MIME type for JSON files
Go
bsd-3-clause
facette/facette,vovkasm/facette,facette/facette,vovkasm/facette,facette/facette,vovkasm/facette,facette/facette
054a9a6159d2d77ece3d249c88bd198891f6ff11
internal/keys/sequence_test.go
internal/keys/sequence_test.go
package keys_test import ( "testing" "github.com/kezhuw/leveldb/internal/keys" ) type sequenceTest struct { seq keys.Sequence next uint64 want keys.Sequence } var sequenceTests = []sequenceTest{ { seq: 0x00123456789abcde, next: 0x000fc9a8743210fe, want: 0x0021fdfeeccccddc, }, { seq: 0x00edcba9876...
package keys_test import ( "testing" "github.com/kezhuw/leveldb/internal/keys" ) type nextSequenceTest struct { seq keys.Sequence next uint64 want keys.Sequence } var nextSequenceTests = []nextSequenceTest{ { seq: 0x00123456789abcde, next: 0x000fc9a8743210fe, want: 0x0021fdfeeccccddc, }, { seq: 0...
Rename test case type for Sequence.Next
Rename test case type for Sequence.Next
Go
mit
kezhuw/leveldb,kezhuw/leveldb
64e261132ad277dad02b866bdf66b07ec979d1be
queries_service/ids_repository.go
queries_service/ids_repository.go
// Copyright 2015 The http2amqp Authors. All rights reserved. Use of this // source code is governed by a MIT-style license that can be found in the // LICENSE file. package queries_service type Id int type IdsRepository interface { Next() Id }
// Copyright 2015 The http2amqp Authors. All rights reserved. Use of this // source code is governed by a MIT-style license that can be found in the // LICENSE file. package queries_service type Id int type IdsRepository interface { Next() Id } func NewIdsRepository() IdsRepository { return &idsRepository{} } t...
Fix build with dummy ids repository
Fix build with dummy ids repository
Go
mit
aleasoluciones/http2amqp,aleasoluciones/http2amqp
184e4c0f422b5d31ea7cf7b56b3cf7e99fc4c58a
collector/counters.go
collector/counters.go
package collector import ( "fmt" "github.com/prometheus/client_golang/prometheus" ) type SquidCounter struct { Section string Counter string Description string } var squidCounters = []SquidCounter{ {"client_http", "requests", "The total number of client requests"}, {"client_http", "hits", "The total ...
package collector import ( "fmt" "strings" "github.com/prometheus/client_golang/prometheus" ) type SquidCounter struct { Section string Counter string Description string } var squidCounters = []SquidCounter{ {"client_http", "requests", "The total number of client requests"}, {"client_http", "hits", ...
Add counter for server http requests
Add counter for server http requests
Go
mit
boynux/squid-exporter,boynux/squid-exporter
93ecd403e3b1c6037e61d8b2c8602d078530b8b9
common/config_unix.go
common/config_unix.go
// +build linux dragonfly freebsd netbsd openbsd solaris package common import ( "os" "os/user" "path/filepath" ) // GetConfigName gets the correct full path of the configuration file. func GetConfigName(program, filename string) (string, error) { u, err := user.Current() if err != nil { return nil, err } ...
// +build linux dragonfly freebsd netbsd openbsd solaris package common import ( "os" "os/user" "path/filepath" ) // GetConfigName gets the correct full path of the configuration file. func GetConfigName(program, filename string) (string, error) { u, err := user.Current() if err != nil { return "", err } d...
Build fix for Unix-likes other than macOS.
Build fix for Unix-likes other than macOS.
Go
mit
Urethramancer/lbapi,Urethramancer/lbapi
3a361cb00c620e78cf4b6ab11976b862621723fb
objectserver/rpcd/checkObjects.go
objectserver/rpcd/checkObjects.go
package rpcd import ( "encoding/gob" "github.com/Symantec/Dominator/lib/srpc" "github.com/Symantec/Dominator/proto/objectserver" ) func (t *srpcType) CheckObjects(conn *srpc.Conn) error { var request objectserver.CheckObjectsRequest var response objectserver.CheckObjectsResponse decoder := gob.NewDecoder(conn) ...
package rpcd import ( "github.com/Symantec/Dominator/lib/srpc" "github.com/Symantec/Dominator/proto/objectserver" ) func (t *srpcType) CheckObjects(conn *srpc.Conn, request objectserver.CheckObjectsRequest, reply *objectserver.CheckObjectsResponse) error { sizes, err := t.objectServer.CheckObjects(request.Hashes...
Switch objectserver SRPC methods to request/reply style methods.
Switch objectserver SRPC methods to request/reply style methods.
Go
apache-2.0
rgooch/Dominator,Symantec/Dominator,rgooch/Dominator,rgooch/Dominator,keep94/Dominator,Symantec/Dominator,keep94/Dominator,keep94/Dominator,Symantec/Dominator
044b900af4fa20c3403b4b59830c9b08e16c9846
json_test.go
json_test.go
// Copyright 2014 Volker Dobler. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ht import ( "testing" ) var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)} var jsonTests = []TC{ {jr, &JSON{Expression: "(.foo == 5)...
// Copyright 2014 Volker Dobler. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ht import ( "testing" ) var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)} var ar = Response{BodyBytes: []byte(`["jo nesbo",["jo nesb...
Add real-wolrd JSON check tests
Add real-wolrd JSON check tests A (almost) real JSON response from an Amazon autocompletion AJAX call Only a few empty structs have been deleted from the response of http://completion.amazon.co.uk/search/complete?q=jo%20nesbo&search-alias=aps&mkt=4&fb=1&xcat=0
Go
bsd-3-clause
vdobler/ht,vdobler/ht,vdobler/ht,vdobler/ht
863b50faafe3f20297ec824f9c8c58c1c5dd0cf0
src/version/gen.go
src/version/gen.go
// +build ignore package main import ( "os" "os/exec" "strings" ) func main() { var err error var cmd = exec.Command("git", "describe") var out []byte out, err = cmd.CombinedOutput() if err != nil { panic("Unable to run `git describe`: " + err.Error()) } var build = string(out) build = strings.TrimSpac...
// +build ignore package main import ( "os" "os/exec" "rais/src/version" "strings" ) func main() { var err error var cmd = exec.Command("git", "describe") var out []byte out, err = cmd.CombinedOutput() // This can fail when there's no git repository, so instead of crashing, we // just have a build tag of...
Fix crash when building without .git
Fix crash when building without .git
Go
cc0-1.0
uoregon-libraries/rais-image-server,uoregon-libraries/rais-image-server,uoregon-libraries/rais-image-server,uoregon-libraries/rais-image-server
30637533818f789dffa39a51ce191484b026eee8
src/caduceus/simpleCounter.go
src/caduceus/simpleCounter.go
/** * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 requir...
/** * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 requir...
Fix misspelled words in a comment.
Fix misspelled words in a comment.
Go
apache-2.0
Comcast/caduceus,Comcast/caduceus
c99d5b2f83d87f24892841a0f21638753e753fc2
src/vivoupdater/batch_indexer.go
src/vivoupdater/batch_indexer.go
package vivoupdater type BatchIndexer interface { Name() string Index(b map[string]bool) (map[string]bool, error) } func IndexBatch(ctx Context, i BatchIndexer, b map[string]bool) { ib, err := i.Index(b) if err != nil { ctx.handleError("Indexing Error", err, true) } ctx.Logger.Printf("%v uris indexed by %s", ...
package vivoupdater type BatchIndexer interface { Name() string Index(b map[string]bool) (map[string]bool, error) } func IndexBatch(ctx Context, i BatchIndexer, b map[string]bool) { ib, err := i.Index(b) if err != nil { ctx.handleError("Indexing Error", err, true) } ctx.Logger.Printf("%v uris indexed by %s", ...
Add uri logging for each batch
Add uri logging for each batch Temporary for troubleshooting
Go
mit
OIT-ADS-Web/vivoupdater,OIT-ADS-Web/vivoupdater
6e277a2d8f4af200197d02a126f92351c2b15e21
util/util_linux.go
util/util_linux.go
package util import ( "syscall" ) // IsCgroup2UnifiedMode returns whether we are running in cgroup 2 cgroup2 mode. func IsCgroup2UnifiedMode() (bool, error) { isUnifiedOnce.Do(func() { _cgroup2SuperMagic := int64(0x63677270) var st syscall.Statfs_t if err := syscall.Statfs("/sys/fs/cgroup", &st); err != nil {...
package util import ( "syscall" "golang.org/x/sys/unix" ) // IsCgroup2UnifiedMode returns whether we are running in cgroup 2 cgroup2 mode. func IsCgroup2UnifiedMode() (bool, error) { isUnifiedOnce.Do(func() { var st syscall.Statfs_t if err := syscall.Statfs("/sys/fs/cgroup", &st); err != nil { isUnified, i...
Fix build for 32bit platforms
Fix build for 32bit platforms Signed-off-by: Sascha Grunert <sgrunert@suse.com> Closes: #2100 Approved by: rhatdan
Go
apache-2.0
TomSweeneyRedHat/buildah,nalind/buildah-1,nalind/buildah,rhatdan/buildah,rhatdan/buildah,rhatdan/buildah,TomSweeneyRedHat/buildah,nalind/buildah-1,projectatomic/buildah,projectatomic/buildah,nalind/buildah-1,TomSweeneyRedHat/buildah,projectatomic/buildah,nalind/buildah
b81494ba22d323a52ec7f6b8200f45de26462c1b
partition_test.go
partition_test.go
package gosort import ( "testing" ) type testFunc func(elem int) bool func trueForAll(a []int, test testFunc) bool { for _, v := range a { if !test(v) { return false } } return true } func genGreaterThan(pivot int) testFunc { return func(elem int) bool { ret...
package gosort import ( "testing" ) type testFunc func(elem int) bool func isTrueForAll(a []int, test testFunc) bool { for _, v := range a { if !test(v) { return false } } return true } func createGreaterThanTest(pivot int) testFunc { return func(elem int) bool { ...
Rename helper functions with more descriptive names
Rename helper functions with more descriptive names
Go
mit
munckymagik/gosort
fbb0d707577616c12a770c5b82d84b401832e500
utils.go
utils.go
package bamstats import ( "bufio" "encoding/json" "io" "os" log "github.com/Sirupsen/logrus" ) func check(err error) { if err != nil { log.Fatal(err) } } func max(a, b uint32) uint32 { if a < b { return b } return a } func min(a, b uint32) uint32 { if a < b { return a } return b } func OutputJs...
package bamstats import ( "bufio" "encoding/json" "io" "os" log "github.com/Sirupsen/logrus" ) func check(err error) { if err != nil { log.Fatal(err) } } func max(a, b int) int { if a < b { return b } return a } func min(a, b int) int { if a < b { return a } return b } func OutputJson(writer io...
Update max and min functions
Update max and min functions
Go
bsd-3-clause
guigolab/bamstats,guigolab/bamstats
55b8f3486ff718f6383dc6f42e1bf06635baf453
xlog_examples_test.go
xlog_examples_test.go
package xlog_test import ( "context" "errors" "log" "github.com/rs/xlog" ) func Example_log() { ctx := context.TODO() l := xlog.FromContext(ctx) // Log a simple message l.Debug("message") if err := errors.New("some error"); err != nil { l.Errorf("Some error happened: %v", err) } // With optional fiel...
// +build go1.7 package xlog_test import ( "context" "errors" "log" "github.com/rs/xlog" ) func Example_log() { ctx := context.TODO() l := xlog.FromContext(ctx) // Log a simple message l.Debug("message") if err := errors.New("some error"); err != nil { l.Errorf("Some error happened: %v", err) } // W...
Make example compile with go 1.7 only
Make example compile with go 1.7 only
Go
mit
rs/xlog
80b65c7a5bc3b61147e338e242655c3d31ba9ba0
util/manifestparser/application.go
util/manifestparser/application.go
package manifestparser import "errors" type Application struct { Name string `yaml:"name"` Data map[string]interface{} } func (application Application) MarshalYAML() (interface{}, error) { return application.Data, nil } func (app *Application) UnmarshalYAML(unmarshal func(v interface{}) error) error { err := un...
package manifestparser import "errors" type Application struct { Name string Data map[string]interface{} } func (application Application) MarshalYAML() (interface{}, error) { return application.Data, nil } func (app *Application) UnmarshalYAML(unmarshal func(v interface{}) error) error { err := unmarshal(&app.D...
Remove redundant yaml struct tag
Remove redundant yaml struct tag The yaml package that we use assumes that the yaml key is a lowercase version of the field name. [#163575911]
Go
apache-2.0
cloudfoundry/cli,cloudfoundry/cli,cloudfoundry/cli
2f53b95e6c61e2e08e23ac3f8086b11a8f86b718
exec/exec_test.go
exec/exec_test.go
package exec import ( "bufio" "os/exec" "testing" ) func TestSimpleRead(t *testing.T) { command := exec.Command("echo", "hoge", "piyo") command_output, _ := command.Output() actual := string(command_output) expected := "hoge piyo\n" if actual != expected { t.Errorf("Command line output should be %...
package exec import ( "bufio" "os/exec" "testing" ) func TestSimpleRead(t *testing.T) { command := exec.Command("echo", "hoge", "piyo") command_output, _ := command.Output() actual := string(command_output) expected := "hoge piyo\n" if actual != expected { t.Errorf("Command line output should be %...
Use cat instead of sed for an exec.Command example.
Use cat instead of sed for an exec.Command example. The flags of sed are varied in OS, so it is not suitable for tests.
Go
mit
imos/go-samples
6bc03bbc469dbc19709075b4dcabf0c9d20540e2
tokenize/tokenize.go
tokenize/tokenize.go
/* Package tokenize implements functions to split strings into slices of substrings. */ package tokenize import ( "github.com/jdkato/prose/internal/util" "gopkg.in/neurosnap/sentences.v1/english" ) // ProseTokenizer is the interface implemented by an object that takes a string // and returns a slice of substrings. ...
/* Package tokenize implements functions to split strings into slices of substrings. */ package tokenize // ProseTokenizer is the interface implemented by an object that takes a string // and returns a slice of substrings. type ProseTokenizer interface { Tokenize(text string) []string } // TextToWords converts the s...
Use modified PunktSentenceTokenizer in TextToWords
Use modified PunktSentenceTokenizer in TextToWords
Go
mit
jdkato/prose,jdkato/prose,jdkato/prose
dfb5c8189269c3e0f5ce21bf4b78f9a09562b7b0
internal/perms.go
internal/perms.go
// Copyright 2015 - 2017 Ka-Hing Cheung // Copyright 2015 - 2017 Google Inc. All Rights Reserved. // // 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/...
// Copyright 2015 - 2017 Ka-Hing Cheung // Copyright 2015 - 2017 Google Inc. All Rights Reserved. // // 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/...
Use getuid and getgid to avoid USER HOME environment issue
Use getuid and getgid to avoid USER HOME environment issue user.Current() fails when USER & HOME are not set.
Go
apache-2.0
kahing/goofys,kahing/goofys,kahing/goofys
c2ff1a0a00e8c67c5d53e9b6e5a590ce3cd8e3cb
cmd/help_test.go
cmd/help_test.go
package cmd import ( "github.com/gsamokovarov/jump/cli" ) func Example_helpCmd() { _ = helpCmd(cli.Args{}, nil) // Output: // Usage: jump [COMMAND ...] // // Jump to a fuzzy-matched directory passed as an argument. // // Commands: // cd Fuzzy match a directory to jump to. // chdir Upda...
package cmd import ( "github.com/gsamokovarov/jump/cli" ) func Example_helpCmd() { _ = helpCmd(cli.Args{}, nil) // Output: // Usage: jump [COMMAND ...] // // Jump to a fuzzy-matched directory passed as an argument. // // Commands: // cd Fuzzy match a directory to jump to. // chdir Upda...
Fix the help command test after the introduction of settings
Fix the help command test after the introduction of settings
Go
mit
gsamokovarov/jump
81a379d4295da4cc1980a5187ba6c5634988305f
cmd/list_test.go
cmd/list_test.go
package cmd import ( "testing" "github.com/stretchr/testify/assert" ) func TestListCmdHasUse(t *testing.T) { assert.NotEmpty(t, ListCmd.Use) } func TestListCmdHasShort(t *testing.T) { assert.NotEmpty(t, ListCmd.Short) } func TestListCmdHasLong(t *testing.T) { assert.NotEmpty(t, ListCmd.Long) } func TestListC...
package cmd import ( "testing" "github.com/stretchr/testify/assert" ) func TestListCmdHasUse(t *testing.T) { assert.NotEmpty(t, ListCmd.Use) } func TestListCmdHasShort(t *testing.T) { assert.NotEmpty(t, ListCmd.Short) } func TestListCmdHasLong(t *testing.T) { assert.NotEmpty(t, ListCmd.Long) } func TestListC...
Add test for ls alias
Add test for ls alias
Go
mit
hoop33/limo
fd2b1b4c99bf2c9bb2c0951091fa4dc2c0d2ae83
clients/locationClient/entities.go
clients/locationClient/entities.go
package locationClient import ( "encoding/xml" ) type LocationList struct { XMLName xml.Name `xml:"Locations"` Xmlns string `xml:"xmlns,attr"` Locations []Location `xml:"Location"` } type Location struct { Name string DisplayName string AvailableServices []string `xml:"Available...
package locationClient import ( "encoding/xml" ) type LocationList struct { XMLName xml.Name `xml:"Locations"` Xmlns string `xml:"xmlns,attr"` Locations []Location `xml:"Location"` } type Location struct { Name string DisplayName string AvailableServices []stri...
Include the available role sizes from locations
Include the available role sizes from locations Previously the locations client did not return information about the available role sizes in each location. This commit adds two additional properties to the LocationList type to expose a list of Web/Worker role sizes and VM sizes available per region. Since the data is ...
Go
apache-2.0
StorReduce/azure-sdk-for-go,bingosummer/azure-sdk-for-go,paulmey/azure-sdk-for-go,MindFlavor/azure-sdk-for-go,mvanotti/azure-sdk-for-go,bingosummer/azure-sdk-for-go,paulmey/azure-sdk-for-go,Nepomuceno/azure-sdk-for-go,Nepomuceno/azure-sdk-for-go,curoverse/azure-sdk-for-go,lirao/azure-sdk-for-go,mvanotti/azure-sdk-for-g...
8491877a9019062c68e21a05a7cf0b73f29b49c7
testdata/src/ping/ping.go
testdata/src/ping/ping.go
// +build OMIT package main import ( "fmt" _ "v.io/core/veyron/profiles" "v.io/core/veyron2/rt" "pingpong" ) func main() { runtime, err := rt.New() if err != nil { panic(err) } defer runtime.Cleanup() log := runtime.Logger() s := pingpong.PingPongClient("pingpong") pong, err := s.Ping(runtime.NewCont...
// +build OMIT package main import ( "fmt" _ "v.io/core/veyron/profiles" "v.io/core/veyron2" "v.io/core/veyron2/rt" "pingpong" ) func main() { runtime, err := rt.New() if err != nil { panic(err) } defer runtime.Cleanup() ctx := runtime.NewContext() log := veyron2.GetLogger(ctx) s := pingpong.PingPong...
Update playground test to not use the deprecated rt.Logger() method.
TBR: Update playground test to not use the deprecated rt.Logger() method. Change-Id: I91ca68efffbfb756d2bf1cf36aa7b14fbf87aad2
Go
bsd-3-clause
vanadium/playground,vanadium/playground,vanadium/playground,vanadium/playground
faaef83954e9564a9ec054c464a59e041c8c2b3d
middleware/markdown/watcher_test.go
middleware/markdown/watcher_test.go
package markdown import ( "fmt" "strings" "sync" "testing" "time" ) func TestWatcher(t *testing.T) { expected := "12345678" interval := time.Millisecond * 100 i := 0 out := "" stopChan := TickerFunc(interval, func() { i++ out += fmt.Sprint(i) }) time.Sleep(interval * 8) stopChan <- struct{}{} if exp...
package markdown import ( "fmt" "strings" "sync" "testing" "time" ) func TestWatcher(t *testing.T) { expected := "12345678" interval := time.Millisecond * 100 i := 0 out := "" stopChan := TickerFunc(interval, func() { i++ out += fmt.Sprint(i) }) // wait little more because of concurrency time.Sleep(i...
Use less strict condition to avoid problems with concurrency
Use less strict condition to avoid problems with concurrency In latest go versions TestWatcher fails pretty often, because it is "more concurrent" now. Reproducible with go master: while go test github.com/mholt/caddy/middleware/markdown; do :; done Signed-off-by: Alexander Morozov <4efb7da3e38416208b41d8021a942884d8...
Go
apache-2.0
tgulacsi/caddy,devangels/caddy,yukimochi/caddy,tpng/caddy,devangels/caddy,eiszfuchs/caddy,hackintoshrao/caddy,guilhermebr/caddy,evermax/caddy,DenBeke/caddy,tw4452852/caddy,tgulacsi/caddy,dusty/caddy,liufuqiang/caddy,eiszfuchs/caddy,lukw00/caddy,tobya/caddy,elcore/caddy,hackintoshrao/caddy,tobya/caddy,buddhamagnet/caddy...
c6a7d2da7552e42a81b25cf2db328223e02fba24
todoist/oauth2.go
todoist/oauth2.go
package todoist import ( "fmt" "golang.org/x/oauth2" "log" ) func buildConfig() *oauth2.Config { // todoist.com requires ClientID and ClientSecret to be set as parameters // in the POST. oauth2.RegisterBrokenAuthHeaderProvider("https://todoist.com") return &oauth2.Config{ ClientID: Oauth2ClientID, Cli...
package todoist import ( "fmt" "golang.org/x/oauth2" "log" ) func buildConfig() *oauth2.Config { // todoist.com requires ClientID and ClientSecret to be set as parameters // in the POST. //oauth2.RegisterBrokenAuthHeaderProvider("https://todoist.com") return &oauth2.Config{ ClientID: Oauth2ClientID, C...
Remove Todoist from the broken list
Remove Todoist from the broken list
Go
mit
seanrees/tripist,seanrees/tripist
10685a495e984532ca683288685bf83b708277bb
server/logging.go
server/logging.go
package weavedns import ( "io" "log" ) // Inspired by http://www.goinggo.net/2013/11/using-log-package-in-go.html var ( Debug *log.Logger Info *log.Logger Warning *log.Logger Error *log.Logger ) func InitLogging(debugHandle io.Writer, infoHandle io.Writer, warningHandle io.Writer, errorHandle io.Wri...
package weavedns import ( "io" "io/ioutil" "log" "os" ) const ( standard_log_flags = log.Ldate | log.Ltime | log.Lshortfile ) // Inspired by http://www.goinggo.net/2013/11/using-log-package-in-go.html var ( Debug *log.Logger = log.New(ioutil.Discard, "DEBUG: ", standard_log_flags) Info *log.Logger = log...
Set up defaults so it doesn't crash in tests
Set up defaults so it doesn't crash in tests
Go
apache-2.0
narry/weave,cgvarela/weave,errordeveloper/weave,OnePaaS/weave,bboreham/weave,paladin74/weave,rade/weave,paladin74/weave,2opremio/weave,2opremio/weave,paulbellamy/weave,OnePaaS/weave,achanda/weave,awh/weave,errordeveloper/weave,philipz/weave,n054/weave,dpw/weave,squaremo/weave,Lawouach/weave,n054/weave,rade/weave,19hz/w...