input stringlengths 24 2.11k | output stringlengths 7 948 |
|---|---|
package main
import (
"fmt"
"github.com/devfeel/dotweb"
"github.com/devfeel/dotweb/cache"
"github.com/devfeel/dotweb/framework/file"
"strconv"
)
func main() {
app := dotweb.New()
app.SetLogPath(file.GetCurrentDirectory())
InitRoute(app.HttpServer)
app.SetCache(cache.NewRuntimeCache())
err := app.Cache... | {
g, err := ctx.Cache().GetString("g")
if err != nil {
g = err.Error()
}
_, err = ctx.Cache().Incr("count")
c, _ := ctx.Cache().GetString("count")
return ctx.WriteString("Two [" + g + "] [" + c + "] " + fmt.Sprint(err))
} |
package wire_test
import (
"bytes"
"io"
)
type fixedWriter struct {
b []byte
pos int
}
func (w *fixedWriter) Write(p []byte) (n int, err error) {
lenp := len(p)
if w.pos+lenp > cap(w.b) {
return 0, io.ErrShortWrite
}
n = lenp
w.pos += copy(w.b[w.pos:], p)
return
}
func (w *fixedWriter) Bytes()... | {
b := make([]byte, max, max)
if buf != nil {
copy(b[:], buf)
}
iobuf := bytes.NewBuffer(b)
fr := fixedReader{b, 0, iobuf}
return &fr
} |
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
auditinstall "k8s.io/apiserver/pkg/apis/audit/install"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
"k8s.io/apiserver/pkg/audit"
)
var (
encoder runtime.Encoder
decod... | {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("could not read request body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
el := &auditv1.EventList{}
if err := runtime.DecodeInto(decoder, body, el); err != nil {
log.Printf("failed decoding buf: %b, apiVersion: %s", b... |
package database
import "database/sql"
var db *sql.DB
func OpenDB() {
openSQLite()
}
func Query(s string, args ...interface{}) (*sql.Rows, error) {
rows, err := db.Query(s, args...)
if err != nil {
return nil, err
}
return rows, nil
}
func Exec(s string, args ...interface{}) (sql.Result, error) {
res... | {
var err error
db, err = sql.Open("sqlite3", "adnalerts.db?loc.auto")
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
} |
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
func read2(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
r := bufio.NewReader(fi)
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
i... | {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
} |
package segment
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/checkr/flagr/swagger_gen/models"
)
const DeleteSegmentOKCode int = 200
type DeleteSegmentOK struct {
}
func NewDeleteSegmentOK() *DeleteSegmentOK {
return &DeleteSegmentOK{}
}
func (o *DeleteSegmentOK) WriteResponse(rw ht... | {
o.Payload = payload
return o
} |
package dns
import (
"strings"
)
const etcHostsFile = "C:/Windows/System32/drivers/etc/hosts"
func getDNSServerList() []string {
output := runCommand("powershell", "-Command", "(Get-DnsClientServerAddress).ServerAddresses")
if len(output) > 0 {
return strings.Split(output, "\r\n")
}
panic("Could not find D... | {
output := runCommand("powershell", "-Command", "(Get-DnsClient)[0].SuffixSearchList")
if len(output) > 0 {
return strings.Split(output, "\r\n")
}
panic("Could not find DNS search list!")
} |
package iiif
import (
"strconv"
)
type Rotation struct {
Mirror bool
Degrees float64
}
func StringToRotation(p string) Rotation {
r := Rotation{}
if p[0:1] == "!" {
r.Mirror = true
p = p[1:]
}
r.Degrees, _ = strconv.ParseFloat(p, 64)
if r.Degrees == 360 {
r.Degrees = 0
}
return r
}
fun... | {
return r.Degrees >= 0 && r.Degrees < 360
} |
package math
func Ceil(x float64) float64 { return -Floor(-x) }
func Trunc(x float64) float64 {
if x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 {
return x
}
d, _ := Modf(x)
return d
}
func Floor(x float64) float64 | {
if x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 {
return x
}
if x < 0 {
d, fract := Modf(-x)
if fract != 0.0 {
d = d + 1
}
return -d
}
d, _ := Modf(x)
return d
} |
package ast
import (
"fmt"
"github.com/rhysd/gocaml/token"
"github.com/rhysd/locerr"
)
type printPath struct {
total int
}
func (v *printPath) VisitTopdown(e Expr) Visitor {
fmt.Printf("\n -> %s (topdown)", e.Name())
return v
}
func (v *printPath) VisitBottomup(e Expr) {
fmt.Printf("\n -> %s (bottomup)", ... | {
src := locerr.NewDummySource("")
rootOfAST := &Let{
LetToken: &token.Token{File: src},
Symbol: NewSymbol("test"),
Bound: &Int{
Token: &token.Token{File: src},
Value: 42,
},
Body: &Add{
Left: &VarRef{
Token: &token.Token{File: src},
Symbol: NewSymbol("test"),
},
Right: &Float{
... |
package fs
import (
"crypto/md5"
"fmt"
"path/filepath"
"runtime"
"strings"
)
const (
WindowsTempPrefix = "~syncthing~"
UnixTempPrefix = ".syncthing."
)
var TempPrefix string
const maxFilenameLength = 160 - len(UnixTempPrefix) - len(".tmp")
func IsTemporary(name string) bool {
name = filepath.Bas... | {
if runtime.GOOS == "windows" {
TempPrefix = WindowsTempPrefix
} else {
TempPrefix = UnixTempPrefix
}
} |
package writer
import (
"bytes"
"encoding/binary"
"hash/crc32"
"github.com/rameshvarun/ups/common"
)
func WriteVariableLengthInteger(value uint64) []byte {
var data []byte
x := value & 0x7f
value >>= 7
for value != 0 {
data = append(data, byte(x))
value--
x = value & 0x7f
value >>= 7
}
data =... | {
var buffer bytes.Buffer
buffer.Write(common.Signature)
buffer.Write(WriteVariableLengthInteger(data.InputFileSize))
buffer.Write(WriteVariableLengthInteger(data.OutputFileSize))
for _, block := range data.PatchBlocks {
buffer.Write(WriteVariableLengthInteger(block.RelativeOffset))
buffer.Write(block.Data)... |
package glw
import "golang.org/x/mobile/gl"
type A2fv gl.Attrib
func (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)
}
type A3fv gl.Attrib
func (a A3fv) Enable() { ctx.EnableVertexAttribArray(... | { ctx.EnableVertexAttribArray(gl.Attrib(a)) } |
package dummy
import (
"log"
"sync"
"time"
"github.com/svenwiltink/go-musicbot/pkg/music"
)
type SongPlayer struct {
lock sync.Mutex
}
func (player *SongPlayer) CanPlay(song music.Song) bool {
return true
}
func (player *SongPlayer) Wait() {
player.lock.Lock()
defer player.lock.Unlock()
time.Sleep(time.S... | {
player.lock.Lock()
defer player.lock.Unlock()
log.Printf("starting playback of %s", song.Name)
return nil
} |
package role
import (
"github.com/watermint/toolbox/domain/dropbox/api/dbx_auth"
"github.com/watermint/toolbox/domain/dropbox/api/dbx_conn"
"github.com/watermint/toolbox/domain/dropbox/model/mo_user"
"github.com/watermint/toolbox/domain/dropbox/service/sv_adminrole"
"github.com/watermint/toolbox/domain/dropbox/se... | {
member, err := sv_member.New(z.Peer.Context()).ResolveByEmail(z.Email)
if err != nil {
return err
}
_, err = sv_adminrole.New(z.Peer.Context()).UpdateRole(mo_user.NewUserSelectorByTeamMemberId(member.TeamMemberId), []string{})
if err != nil {
return err
}
return nil
} |
package testhelpers
import "github.com/go-kit/kit/metrics"
type CollectingCounter struct {
CounterValue float64
LastLabelValues []string
}
func (c *CollectingCounter) With(labelValues ...string) metrics.Counter {
c.LastLabelValues = labelValues
return c
}
func (c *CollectingCounter) Add(delta float64) {
... | {
return m.Gauge
} |
package xenserver
import (
"time"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceXenServerPifs() *schema.Resource {
return &schema.Resource{
Read: dataSourceXenServerPifsRead,
Schema: map[string]*schema.Schema{
"uuids": &schema.Schema{
Type: schema.TypeList,
Computed: true,
... | {
c := meta.(*Connection)
pifUUIDs := make([]string, 0)
if pifs, err := c.client.PIF.GetAllRecords(c.session); err == nil {
for _, pif := range pifs {
pifUUIDs = append(pifUUIDs, pif.UUID)
}
}
d.SetId(time.Now().UTC().String())
d.Set("uuids", pifUUIDs)
return nil
} |
package mediaservices
import (
"github.com/Azure/go-autorest/autorest"
)
const (
APIVersion = "2015-10-01"
DefaultBaseURI = "https:management.azure.com"
)
type ManagementClient struct {
autorest.Client
BaseURI string
APIVersion string
SubscriptionID string
}
func New(subscript... | {
return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
APIVersion: APIVersion,
SubscriptionID: subscriptionID,
}
} |
package proxy
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/fsouza/go-dockerclient"
. "github.com/weaveworks/weave/common"
)
type createExecInterceptor struct {
client *docker.Client
withIPAM bool
}
func (i *createExecInterceptor) InterceptRequest(r *http.Request) error {
body, er... | {
return nil
} |
package v1beta1
import (
v1beta1 "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
type PodSecurityPolicyLister interface {
List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error)
Get(name string) (*v1beta... | {
return &podSecurityPolicyLister{indexer: indexer}
} |
package ovnmodel
import (
"encoding/json"
"fmt"
"github.com/skydive-project/skydive/graffiti/getter"
"github.com/skydive-project/skydive/graffiti/graph"
)
type LoadBalancerHealthCheck struct {
UUID string `ovsdb:"_uuid" json:",omitempty" `
ExternalIDs map[string]string `ovsdb:"external_ids... | {
return t.UUID
} |
package main
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/lightstep/lightstep-tracer-cpp/lightstep-tracer-common"
"io"
)
func computeFieldTypeNumber(field uint64, wireType uint64) uint64 {
return (field << 3) | wireType
}
func readReporter(reader *bufio.R... | {
fieldType, err := binary.ReadUvarint(reader)
if err != nil {
return err
}
if expectedFieldType := computeFieldTypeNumber(field, proto.WireBytes); fieldType != expectedFieldType {
return errors.New(fmt.Sprintf("Unexpected fieldType %d number for Reporter: expected %d", fieldType,
expectedFieldType))
}
len... |
package glw
import "golang.org/x/mobile/gl"
type A2fv gl.Attrib
func (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)
}
type A... | {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)
} |
package main
import (
"reflect"
)
type Person struct {
name string "namestr"
age int
}
func ShowTag(i interface{}) {
switch t := reflect.TypeOf(i); t.Kind() {
case reflect.Ptr:
tag := t.Elem().Field(0).Tag
println(tag)
}
}
func main() {
p := new(Person)
p.name = "test"
p.age = 18
ShowTag(p)
show(p... | {
switch i.(type) {
case *Person:
t := reflect.TypeOf(i)
v := reflect.ValueOf(i)
tag := t.Elem().Field(0).Tag
name := v.Elem().Field(0).String()
age := v.Elem().Field(1).Int()
println(tag)
println(name)
println(age)
}
} |
package tequilapi
import (
"errors"
"fmt"
"net"
"net/http"
"strings"
)
type APIServer interface {
Wait() error
StartServing() error
Stop()
Address() (string, error)
}
type apiServer struct {
errorChannel chan error
handler http.Handler
listenAddress string
listener net.Listener
}
func New... | {
addr := listener.Addr()
parts := strings.Split(addr.String(), ":")
if len(parts) < 2 {
return "", errors.New("Unable to locate address: " + addr.String())
}
return addr.String(), nil
} |
package runners
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"text/template"
"github.com/davecgh/go-spew/spew"
"github.com/kylelemons/godebug/pretty"
yaml "gopkg.in/yaml.v2"
)
func getFuncs() template.FuncMap {
return template.FuncMap{
"pretty": func(i interface{}) string {
return pretty.Sprint(i... | {
prefix := strings.Repeat(" ", depth)
var out string
s := reflect.Indirect(reflect.ValueOf(t))
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
out = fmt.Sprintf("%s%s%s %s\n", out, prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)
switch f.Type().Kind() {
case reflect.Struct... |
package sign
import (
"dfss"
cAPI "dfss/dfssc/api"
pAPI "dfss/dfssp/api"
"dfss/dfsst/entities"
"dfss/net"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
type clientServer struct {
incomingPromises chan interface{}
incomingSignatures chan interface{}
}
func getServerErrorCode(c chan interface{}, in ... | {
return &cAPI.Hello{Version: dfss.Version}, nil
} |
package resolver
var (
m = make(map[string]Builder)
defaultScheme = "passthrough"
)
func Get(scheme string) Builder {
if b, ok := m[scheme]; ok {
return b
}
if b, ok := m[defaultScheme]; ok {
return b
}
return nil
}
func SetDefaultScheme(scheme string) {
defaultScheme = scheme
}
type A... | {
m[b.Scheme()] = b
} |
package bst
import (
"math"
"github.com/catorpilor/leetcode/utils"
)
func helper(node *utils.TreeNode, min, max int) bool {
if node == nil {
return true
}
if node.Val <= min || node.Val >= max {
return false
}
return helper(node.Left, min, node.Val) && helper(node.Right, node.Val, max)
}
func IsValidBS... | {
return helper(root, math.MinInt64, math.MaxInt64)
} |
package master
import (
"fmt"
"log"
"net/http"
auth "github.com/abbot/go-http-auth"
"github.com/h2oai/steam/master/az"
)
type DefaultAz struct {
directory az.Directory
}
func NewDefaultAz(directory az.Directory) *DefaultAz {
return &DefaultAz{directory}
}
func (a *DefaultAz) Authenticate(username string) st... | { return "" } |
package Utils
import (
"fmt"
"testing"
)
func TestGzip(t *testing.T) {
mergeBuf := MergeBinary([]byte("i am first words"), []byte("i am second words"))
gzip, err := FastGZipMsg(mergeBuf, true)
if err != nil {
t.Fail()
return
}
unzip, err := FastUnGZipMsg(gzip, true)
if err != nil {
t.Fail()
return... | {
mergeBuf := MergeBinary([]byte("i am first words"), []byte("i am second words"))
splitBuf := SplitBinary(mergeBuf)
for _, v := range splitBuf {
fmt.Println(string(v))
}
} |
package font
import (
"bytes"
)
var alias = map[rune]string{
0x2764: "\u2665",
0x0001f499: "\u2665",
0x0001f49a: "\u2665",
0x0001f49b: "\u2665",
0x0001f49c: "\u2665",
0x0001f49d: "\u2665",
0x0001F601: ":|",
0x0001F602: ":)",
0x0001F603: ":D",
}
type Font struct {
width int
heigh... | {
return f.width
} |
package v1alpha1_test
import (
"reflect"
"testing"
"k8s.io/api/scheduling/v1alpha1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubernetes/pkg/api/legacyscheme"
apiv1 "k8s.io/api/core/v1"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
_ "k8s.io/k... | {
priorityClass := &v1alpha1.PriorityClass{}
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.NonPreemptingPriority, true)()
output := roundTrip(t, runtime.Object(priorityClass)).(*v1alpha1.PriorityClass)
if output.PreemptionPolicy == nil || *output.PreemptionPolicy !=... |
package sdk
import (
"context"
"time"
)
var NowTime func() time.Time
var Sleep func(time.Duration)
var SleepWithContext func(context.Context, time.Duration) error
func sleepWithContext(ctx context.Context, dur time.Duration) error {
t := time.NewTimer(dur)
defer t.Stop()
select {
case <-t.C:
... | {
NowTime = time.Now
Sleep = time.Sleep
SleepWithContext = sleepWithContext
} |
package main
import (
"fmt"
"testing"
)
func bats(l, d, n int, s []string) (c int) {
var t int
tx := 6 - d
for i := 6; i <= l-6; i += d {
if i > tx-d {
i = tx
if t == n {
tx = l - 6 + d
} else {
fmt.Sscanf(s[t], "%d", &tx)
t++
}
} else {
c++
}
}
return c
}
func TestBats(t *t... | {
if r := bats(22, 2, 2, []string{"9", "11"}); r != 3 {
t.Errorf("failed: bats 22 2 2 9 11 is 3, got %d",
r)
}
if r := bats(835, 125, 1, []string{"113"}); r != 5 {
t.Errorf("failed: bats 835 125 1 113 is 5, got %d",
r)
}
if r := bats(47, 5, 0, []string{}); r != 8 {
t.Errorf("failed: bats 475 5 0 is 8, ... |
package resource
import (
"errors"
"strings"
"time"
)
type Item struct {
ID interface{}
ETag string
Updated time.Time
Payload map[string]interface{}
}
type ItemList struct {
Total int
Page int
Items []*Item
}
func NewItem(payload map[string]interface{}) (*Item, error) {
id, found := payload["id"]
if ... | {
return getField(i.Payload, name)
} |
package core
import (
"fmt"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/tendermint/tendermint/types"
. "github.com/tendermint/tmlibs/common"
)
func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) {
if maxHeight == 0 {
maxHeight = blockStore.Height()
... | {
if height == 0 {
return nil, fmt.Errorf("Height must be greater than 0")
}
if height > blockStore.Height() {
return nil, fmt.Errorf("Height must be less than the current blockchain height")
}
blockMeta := blockStore.LoadBlockMeta(height)
block := blockStore.LoadBlock(height)
return &ctypes.ResultBlock{blo... |
package account
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
}
type DescribeProjectArgs struct{}
type DescribeProjectResponse struct {
Response
Data []Project `json:"data"`
}
type Project struct {
ProjectName string `json:"projectName"`
ProjectId int `json:"projectI... | {
response := &DescribeProjectResponse{}
err := client.Invoke("DescribeProject", args, response)
if err != nil {
return &DescribeProjectResponse{}, err
}
return response, nil
} |
package v1
type EnvVarSourceApplyConfiguration struct {
FieldRef *ObjectFieldSelectorApplyConfiguration `json:"fieldRef,omitempty"`
ResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:"resourceFieldRef,omitempty"`
ConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:"configMapKeyR... | {
b.SecretKeyRef = value
return b
} |
package gbcrypto
import "testing"
func TestDecrypt(t *testing.T) | {
secretKey := "SecretKey"
message := "Pz3cJ61A4Dw4vTFcqWN6t39pyWyOGCQe9F0="
expected := "encrypt me"
cryptography := Cryptography{}
decrypted := cryptography.Decrypt(secretKey, message)
if decrypted != expected {
t.Errorf("Expected %v, got %v", expected, decrypted)
}
} |
package v1
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type ContainerStateRunningApplyConfiguration struct {
StartedAt *v1.Time `json:"startedAt,omitempty"`
}
func ContainerStateRunning() *ContainerStateRunningApplyConfiguration {
return &ContainerStateRunningApplyConfiguration{}
}
func (b *Con... | {
b.StartedAt = &value
return b
} |
package smtp
import (
"errors"
"testing"
)
type EmailRecorder struct {
from string
to []string
msg []byte
}
type SMTPMock struct {
r *EmailRecorder
err error
}
func (s *SMTPMock) SendMail(from string, to []string, msg []byte) error {
s.r = &EmailRecorder{from, to, msg}
return s.err
}
func TestMailSer... | {
err := errors.New("Error")
s := SMTPMock{err: err}
mailService := NewMailService(&s)
err = mailService.Send("message", "test", "john@doe.com", "jane@doe.com")
if err == nil {
t.Fatalf("Must return an error")
}
} |
package data
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNote(t *testing.T) {
acc := AccountNew("mail@example.com")
user, err := acc.Store()
assert.Nil(t, err)
note := NoteNew(user.ID, "example content")
assert.False(t, note.IsStored())
assert.Equal(t, "example content", note.Text)
... | {
acc := AccountNew("mail@example.com")
user, err := acc.Store()
assert.Nil(t, err)
note := NoteNew(user.ID, "This is a note! This is a note! This is a note! This is a note! This is a note! This is a note! This is a note!")
assert.False(t, note.IsStored())
assert.Equal(t, user.ID, note.Account)
note, err = n... |
package portmapper
import (
"fmt"
"strings"
"sync"
"github.com/golang/glog"
)
type PortMap struct {
containerIP string
containerPort int
}
func newPortMap(containerip string, containerport int) *PortMap {
return &PortMap{
containerIP: containerip,
containerPort: containerport,
}
}
type PortSet map[... | {
p.mutex.Lock()
defer p.mutex.Unlock()
var pset PortSet
if strings.EqualFold(protocol, "udp") {
pset = p.udpMap
} else {
pset = p.tcpMap
}
e, ok := pset[hostPort]
if ok {
return fmt.Errorf("Host port %d had already been used, %s %d",
hostPort, e.containerIP, e.containerPort)
}
allocated := newPo... |
package rest
import "net/http"
type StaticResource struct {
ResourceBase
result *Result
self Link
}
func NewStaticResource(result *Result, self Link) Resource {
return &StaticResource{
result: result,
self: self,
}
}
func StaticContent(content []byte, contentType string, selfHref string) Resource {
re... | {
return r.result, nil
} |
package client
import (
"encoding/json"
"io"
"os"
)
func encodeJSON(w io.Writer, v interface{}) {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.Encode(v)
}
func dump(v interface{}) | {
encodeJSON(os.Stdout, v)
} |
package main
import (
"time"
"github.com/PalmStoneGames/polymer"
)
func init() {
polymer.Register("tick-timer", &Timer{})
}
type Timer struct {
*polymer.Proto
Time time.Time `polymer:"bind"`
}
func (t *Timer) Created() {
go func() {
for {
t.Time = time.Now()
t.Notify("time")
time.Sleep(time.Mil... | {
return t.Time.String()
} |
package dialects
import (
"fmt"
"strings"
)
type Filter interface {
Do(sql string) string
}
type SeqFilter struct {
Prefix string
Start int
}
func convertQuestionMark(sql, prefix string, start int) string {
var buf strings.Builder
var beginSingleQuote bool
var index = start
for _, c := range sql {
if ... | {
return convertQuestionMark(sql, s.Prefix, s.Start)
} |
package v1
import context "context"
import proto "github.com/golang/protobuf/proto"
import "go-common/library/net/rpc/liverpc"
var _ proto.Message
type CaptchaRPCClient interface {
Create(ctx context.Context, req *CaptchaCreateReq, opts ...liverpc.CallOption) (resp *CaptchaCreateResp, err error)
}
type ... | {
return &captchaRPCClient{
client: client,
}
} |
package assets
import (
"fmt"
"github.com/iceburg-instance/database"
"github.com/iceburg-instance/database/models/terrain"
)
type HeightData struct {
HeightVals []terrain.HeightTuple
}
func GetHeight() (*HeightData, error) | {
qString := terrain.GetAllString()
rows, err := database.Query(qString)
if err != nil {
fmt.Println(err)
return nil, err
}
defer rows.Close()
var heightSlice []terrain.HeightTuple
var heightTuple terrain.HeightTuple
for rows.Next() {
heightTuple = terrain.HeightTuple{}
if err :... |
package blocker
import "sort"
type sources []string
func (s *sources) Add(source string) {
n := sort.SearchStrings(*s, source)
if n < len(*s) && (*s)[n] == source {
return
}
*s = append(*s, "")
copy((*s)[n+1:], (*s)[n:])
(*s)[n] = source
}
func (s *sources) Remove(source string) bool {
if s == nil {
re... | {
if s == nil {
return false
}
n := sort.SearchStrings(*s, source)
if n < len(*s) && (*s)[n] == source {
return true
}
return false
} |
package adal
import (
"fmt"
"net/url"
)
const (
activeDirectoryAPIVersion = "1.0"
)
type OAuthConfig struct {
AuthorityEndpoint url.URL
AuthorizeEndpoint url.URL
TokenEndpoint url.URL
DeviceCodeEndpoint url.URL
}
func (oac OAuthConfig) IsZero() bool {
return oac == OAuthConfig{}
}
... | {
if len(param) == 0 {
return fmt.Errorf("parameter '" + name + "' cannot be empty")
}
return nil
} |
package main
import (
"fmt"
"time"
)
func createServer() error {
c, err := getClient()
if err != nil {
return err
}
sb := c.NewServerBuilder()
sb.Addr("127.0.0.1:8080").HTTPBackend().MaxQPS(100)
sb.CheckHTTPCode("/check/path", time.Second*10, time.Second*30)
sb.CircuitBreakerCheckPeriod(time.Second)
sb... | {
c, err := getClient()
if err != nil {
return err
}
return c.RemoveServer(id)
} |
package miniredis
import (
"reflect"
"testing"
)
func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
tb.Helper()
if !condition {
tb.Errorf(msg, v...)
}
}
func equals(tb testing.TB, exp, act interface{}) {
tb.Helper()
if !reflect.DeepEqual(exp, act) {
tb.Errorf("expected: %#v ... | {
tb.Helper()
if err != nil {
tb.Errorf("unexpected error: %s", err.Error())
}
} |
package main
import (
"encoding/json"
"time"
)
type Monitor interface {
GetVariables() []string
GetValues([]string) map[string]interface{}
}
var monitorDrivers = make(map[string]func(*json.RawMessage) Monitor)
func AddMonitorDriver(monitor string, constructor func(*json.RawMessage) Monitor) {
monitorDrivers[mo... | {
track, ok := mt.Variables[variable]
if !ok && history > 0 {
track = &MonitorTrackVariable{}
mt.Variables[variable] = track
}
if history == 0 && ok {
delete(mt.Variables, variable)
return
}
track.History = history
} |
package cmd
import (
"errors"
"os"
"github.com/codegangsta/cli"
"github.com/DevMine/srctool/config"
"github.com/DevMine/srctool/log"
)
func Delete(c *cli.Context) {
if !c.Args().Present() {
deleteAll(c.Bool("dry"))
} else {
if err := deleteParser(genParserName(c.Args().First()), c.Bool("dry"), true); er... | {
parsers := getInstalledParsers()
for _, parser := range parsers {
if err := deleteParser(genParserName(parser), dryMode, true); err != nil {
log.Fail(err)
}
}
} |
package router
import (
"net/http"
"strconv"
"time"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service/captcha"
"github.com/ewhal/nyaa/service/torrent"
"github.com/ewhal/nyaa/util"
"github.com/ewhal/nyaa/util/languages"
"github.com/ewhal/nyaa/util/log"
"github.com/goril... | {
vars := mux.Vars(r)
id := vars["id"]
torrent, err := torrentService.GetTorrentById(id)
if err != nil {
NotFoundHandler(w, r)
return
}
b := torrent.ToJson()
htv := ViewTemplateVariables{b, captcha.Captcha{CaptchaID: captcha.GetID()}, NewSearchForm(), Navigation{}, GetUser(r), r.URL, mux.CurrentRoute(r)}
... |
package model
import (
"go-common/app/service/main/archive/model/archive"
)
type ArcToView struct {
*archive.Archive3
Page *archive.Page3 `json:"page,omitempty"`
Count int `json:"count"`
Cid int64 `json:"cid"`
Progress int64 `json:"progress"`
AddTime int64 `j... | { h[i], h[j] = h[j], h[i] } |
package helpers
import (
"fmt"
"gopkg.in/ini.v1"
"runtime"
)
type Distro struct {
Family string
InitSystem string
Version string
}
func (d *Distro) SetInitSystem() error {
switch d.Family {
case "debian":
d.InitSystem = "systemd"
case "centos":
d.InitSystem = "sysv"
default:
return fm... | {
switch family {
case "debian":
d.Family = family
case "centos":
d.Family = family
default:
return fmt.Errorf("Unknown Linux distribution: %s", family)
}
return nil
} |
package helper
import (
"bufio"
"net"
)
type BufConn struct {
net.Conn
BR *bufio.Reader
}
func (c *BufConn) Peek(n int) ([]byte, error) {
return c.BR.Peek(n)
}
func (c *BufConn) Read(b []byte) (n int, err error) {
return c.BR.Read(b)
}
func (c *BufConn) Reset(conn net.Conn) {
c.Conn = conn
}
func NewBufC... | {
return c.Conn.Write(b)
} |
package main
import (
"flag"
"io/ioutil"
"os"
"path"
"gopkg.in/yaml.v1"
)
const (
CONFIG_SUBDIR = "mcmd"
DEFAULT_KNOWN_HOSTS_FILE = "$HOME/.ssh/known_hosts"
)
type HostConfig struct {
User string
Privatekey string
Hosts []string
}
func loadConfig() HostConfig {
rawYaml := readHostf... | {
configFileParam := flag.Arg(0)
for _, file := range getConfigLocationCandidates(configFileParam) {
if exists(file) {
return getContents(file)
}
}
errLogger.Fatalf("hostfile %s not found", configFileParam)
return nil
} |
package main
import (
"encoding/json"
"github.com/bitly/go-nsq"
"log"
"time"
)
var (
Publisher *MsgPublisher
)
type MsgPublisher struct {
usr User
writer *nsq.Writer
}
func init() {
Publisher = &MsgPublisher{
writer: nsq.NewWriter("106.186.31.48:4150"),
}
}
func (publisher *MsgPublisher) SetLoginUsr(... | {
m := Message{
Topic: topic,
Type: MSG_TYPE_CHAT,
Time: time.Now().Format("2006-01-02 15:04:05"),
Body: MessageBody{
From: mp.usr,
Msg: msg,
},
}
msgBytes, _ := json.Marshal(m)
log.Println("Publish.msg = ", string(msgBytes))
return mp.writer.Publish(topic, msgBytes)
} |
package storage
import (
"encoding/json"
"github.com/rynorris/website/server/site"
"github.com/rynorris/website/server/storage"
)
const dummyKey = "site-configuration"
type Service struct {
storage storage.Service
}
func NewService(storage storage.Service) *Service {
return &Service{
storage: storage,
}
}
... | {
site := site.Site{}
blob, err := s.storage.Get(dummyKey)
if err != nil {
return site, err
}
err = json.Unmarshal(blob, &site)
return site, err
} |
package logger
import (
"fmt"
"log"
"gopkg.in/clever/kayvee-go.v2"
)
type M map[string]interface{}
func Info(title string, data M) {
logWithLevel(title, kayvee.Info, data)
}
func Trace(title string, data M) {
logWithLevel(title, kayvee.Trace, data)
}
func Critical(title string, data M) {
logWithLevel... | {
logWithLevel(title, kayvee.Warning, data)
} |
package metrics
import (
"sync"
prom "github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
const (
sandboxGuageName = "bundlelib_sandbox"
)
var (
once sync.Once
collector *Collector
)
type Collector struct {
Sandbox prom.Gauge
}
func recoverMetricPanic() {
if r := re... | {
defer recoverMetricPanic()
collector.Sandbox.Inc()
} |
package openstack
import (
"fmt"
"github.com/gophercloud/gophercloud"
tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens"
tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens"
)
type ErrEndpointNotFound struct{ gophercloud.BaseError }
func (e ErrEndpointNotFound) Erro... | {
return fmt.Sprintf("Discovered %d matching endpoints: %#v", len(e.Endpoints), e.Endpoints)
} |
package sandglass
import (
"fmt"
"github.com/hashicorp/serf/serf"
"github.com/sandglass/sandglass-grpc/go/sgproto"
"google.golang.org/grpc"
)
type Node struct {
ID string
Name string
IP string
GRPCAddr string
RAFTAddr string
HTTPAddr string
Status serf.MemberStatus
conn *grpc.Client... | {
return n.conn != nil
} |
package gorm
import (
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type GR struct {
DB *gorm.DB
ServerInfo
}
type ServerInfo struct {
host string
port uint16
dbname string
user string
pass string
}
var dbInfo GR
func New(host, dbname, user, pass stri... | {
param := "?charset=utf8&parseTime=True&loc=Local"
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s%s",
gr.user, gr.pass, gr.host, gr.port, gr.dbname, param)
} |
package cluster_health
import (
"fmt"
"os"
"testing"
mbtest "github.com/elastic/beats/metricbeat/mb/testing"
)
func TestData(t *testing.T) {
f := mbtest.NewEventFetcher(t, getConfig())
err := mbtest.WriteEvent(f, t)
if err != nil {
t.Fatal("write", err)
}
}
func getConfig() map[string]interface{} {
retur... | {
if len(a) == 0 {
return defaults
}
return a
} |
package config
import (
"encoding/json"
"io/ioutil"
"github.com/hauke96/sigolo"
)
type ConfigLoader struct {
topicConfig *TopicConfig
serverConfig *ServerConfig
}
func (cl *ConfigLoader) loadTopics(filename string) {
data, err := ioutil.ReadFile(filename)
if err != nil {
sigolo.Error("Error readin... | {
data, err := ioutil.ReadFile(filename)
if err != nil {
sigolo.Error("Error reading " + filename)
sigolo.Error("\n\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\nIf not, feel free to contact my m... |
package rancher
import (
"github.com/Sirupsen/logrus"
"github.com/docker/libcompose/logger"
"github.com/docker/libcompose/lookup"
"github.com/docker/libcompose/project"
)
func NewProject(context *Context) (*project.Project, error) | {
context.ConfigLookup = &lookup.FileConfigLookup{}
context.EnvironmentLookup = &lookup.OsEnvLookup{}
context.LoggerFactory = logger.NewColorLoggerFactory()
context.ServiceFactory = &RancherServiceFactory{
Context: context,
}
p := project.NewProject(&context.Context)
err := p.Parse()
if err != nil {
retur... |
package command
import (
"fmt"
"os"
"github.com/coreos/etcd/client"
)
const (
ExitSuccess = iota
ExitError
ExitBadConnection
ExitInvalidInput
ExitBadFeature
ExitInterrupted
ExitIO
ExitBadArgs = 128
)
func ExitWithError(code int, err error) | {
fmt.Fprintln(os.Stderr, "Error:", err)
if cerr, ok := err.(*client.ClusterError); ok {
fmt.Fprintln(os.Stderr, cerr.Detail())
}
os.Exit(code)
} |
package cmd
import (
"fmt"
"github.com/fatih/color"
out "github.com/plouc/go-gitlab-client/cli/output"
"github.com/plouc/go-gitlab-client/gitlab"
"github.com/spf13/cobra"
)
func fetchSshKeys() {
color.Yellow("Fetching current user ssh keys…")
o := &gitlab.PaginationOptions{}
o.Page = page
o.PerPage = per... | {
listCmd.AddCommand(listSshKeysCmd)
} |
package tests
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var (
client *github.Client
auth bool
)
func init() {
token := os.Getenv("GITHUB_AUTH_TOKEN")
if token == "" {
print("!!! No OAuth token. Some tests won't run. !!!\n\n")
cl... | {
var repoName string
for {
repoName = fmt.Sprintf("test-%d", rand.Int())
_, resp, err := client.Repositories.Get(owner, repoName)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
break
}
return nil, err
}
}
repo, _, err := client.Repositories.Create("", &github.Repository{Name: gi... |
package assets
import (
"fmt"
)
const (
analyticsScript = `<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,... | {
if len(names) != 1 && len(names) != 2 {
return nil, fmt.Errorf("analytics requires either 1 or 2 arguments (either \"UA-XXXXXX-YY, mysite.com\" or just \"UA-XXXXXX-YY\" - without quotes in both cases")
}
key := names[0]
if key == "" {
return nil, nil
}
var arg string
if len(names) == 2 {
arg = fmt.Sprint... |
package conway
import (
"fmt"
)
func Example_singleCell() {
var p = Population{cells: map[Cell]int{
Cell{0, 0}: 0,
},
popNumber: 0,
}
p.Next()
fmt.Println(p)
}
func Example_twoCells() {
var p = Population{cells: map[Cell]int{
Cell{0, 0}: 0,
Cell{0, 1}: 0,
},
popNumber: 0,
}
p.Next()
fmt.Println(... | {
var p = Population{cells: map[Cell]int{
Cell{0, 0}: 0,
Cell{0, 1}: 0,
Cell{0, -1}: 0,
},
popNumber: 0,
}
p.SaveToFile("blinker0.log")
p.Next()
p.SaveToFile("blinker1.log")
fmt.Println(len(p.cells))
} |
package handle
import (
"net/http"
)
type HTTPErrorPipeline struct {
Code int
Message string
Global GlobalPipeline
}
func ReturnError(w http.ResponseWriter, code int) int {
w.WriteHeader(code)
tpl, _ := OpenTemplate(ERROR_TPL)
tpl.Execute(w, NewError(code, http.StatusText(co... | {
return HTTPErrorPipeline{
Code: code,
Message: message,
Global: DefaultGlobalPipeline,
}
} |
package rest
type Method int
const (
GET Method = 1 + iota
POST
PUT
DELETE
)
var method = [...]string{
"GET",
"POST",
"PUT",
"DELETE",
}
func (m Method) String() string | { return method[m-1] } |
package commons
import "net/http"
func HttpUnauthorized(w http.ResponseWriter) {
HttpError(w, http.StatusUnauthorized)
}
func HttpBadRequest(w http.ResponseWriter) {
HttpError(w, http.StatusBadRequest)
}
func HttpError(w http.ResponseWriter, code int) {
http.Error(w, http.StatusText(code), code)
}
func HttpCh... | {
HttpError(w, http.StatusNoContent)
} |
package etcd2
import (
"fmt"
"time"
"github.com/coreos/etcd/client"
"golang.org/x/net/context"
)
type Etcd2Connect struct {
etcd2 client.Client
}
func NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error) {
c, err := client.New(client.Config{
Endpoints: []string{fmt.Sprintf("http://%s... | {
kapi := client.NewKeysAPI(e.etcd2)
opts := &client.SetOptions{PrevExist: client.PrevNoExist}
for k, v := range data {
if _, err := kapi.Set(context.Background(), k, v, opts); err != nil {
return err
}
}
return nil
} |
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/APTrust/bagman/bagman"
"github.com/APTrust/bagman/workers"
"io/ioutil"
"os"
)
func main() {
jsonFile := flag.String("file", "", "JSON file to load")
procUtil := workers.CreateProcUtil("aptrust")
procUtil.MessageLog.Info("apt_retry started")
ba... | {
bytes, err := ioutil.ReadFile(jsonFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot read file '%s': %v\n", jsonFile, err)
os.Exit(1)
}
var result bagman.ProcessResult
err = json.Unmarshal(bytes, &result)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot convert JSON to object: %v\n", err)
os.Exit(1)
}
... |
package core
import (
"fmt"
"github.com/spf13/viper"
)
type writeStdout struct {
}
func (s *writeStdout) Write(dirname, filename, content, contentType, contentEncoding string,
metadata map[string]*string) error {
fmt.Printf("--- %s/%s ---\n", dirname, filename)
fmt.Printf("%s\n", content)
return nil
}
fu... | {
return &writeStdout{}, nil
} |
package even
func Even(i int) bool | {
return i%2 == 0
} |
package fabric
func contains(s []DGNode, i DGNode) bool {
for _, v := range s {
if i.ID() == v.ID() {
return true
}
}
return false
}
func ContainsNode(l NodeList, n Node) bool {
for _, v := range l {
if v.ID() == n.ID() {
return true
}
}
return false
}
func ContainsEdge(l EdgeList, e Edge) b... | {
for _, v := range s {
if i.ID() == v.ID() {
return true
}
}
return false
} |
package command
import (
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"time"
getter "github.com/hashicorp/go-getter"
"github.com/hashicorp/nomad/helper/discover"
)
func fetchBinary(bin string) (string, error) {
nomadBinaryDir, err := ioutil.TempDir("", "")
if err != nil {
return "", fmt.Errorf("failed to cre... | {
stop := make(chan struct{})
go func() {
p.Wait()
stop <- struct{}{}
}()
select {
case <-stop:
return nil
case <-time.NewTimer(d).C:
return fmt.Errorf("timeout waiting for process %d to exit", p.Pid)
}
} |
package main
import (
"fmt"
)
type ListOfInt []int
type IntMonad struct {
NeutralElement int
AssocFunc func(int, int) int
}
func main() {
var list = ListOfInt{-2, -1, 2, 2, 3}
monad := IntMonad{0, func(x, y int) int { return x + y }}
fmt.Printf("List %v: Fold(monad) yields %v\n", list, list.Fold(m... | {
out := monad.NeutralElement
for _, i := range list {
out = monad.AssocFunc(out, i)
}
return out
} |
package datasource
import (
"fmt"
"time"
"github.com/golang/glog"
cadvisorClient "github.com/google/cadvisor/client"
cadvisor "github.com/google/cadvisor/info/v1"
"k8s.io/heapster/sources/api"
)
type cadvisorSource struct{}
func (self *cadvisorSource) getAllContainers(client *cadvisorClient.Client, start, e... | {
container := &api.Container{
Name: containerInfo.Name,
Spec: containerInfo.Spec,
Stats: sampleContainerStats(containerInfo.Stats),
}
if len(containerInfo.Aliases) > 0 {
container.Name = containerInfo.Aliases[0]
}
return container
} |
package indexdb
import (
"fmt"
"github.com/eleme/banshee/models"
"github.com/eleme/banshee/util"
)
func encode(idx *models.Index) []byte {
score := util.ToFixed(idx.Score, 5)
average := util.ToFixed(idx.Average, 5)
s := fmt.Sprintf("%d:%s:%s", idx.Stamp, score, average)
return []byte(s)
}
func decode(valu... | {
n, err := fmt.Sscanf(string(value), "%d:%f:%f", &idx.Stamp, &idx.Score, &idx.Average)
if err != nil {
return err
}
if n != 3 {
return ErrCorrupted
}
return nil
} |
package server
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/gorilla/websocket"
)
func TestWsHandler(t *testing.T) {
expectedResponse := []byte("acknowledged")
server := httptest.NewServer(serverEngine())
defer server.Close()
URL, err := url.Parse(server.URL + "/ws")
if err ... | {
server := httptest.NewServer(serverEngine())
defer server.Close()
resp, err := http.Get(server.URL)
if err != nil {
t.Errorf("could not make get request to server")
}
expectedStatus := 200
if resp.StatusCode != expectedStatus {
t.Errorf("expected status code: %d, observed: %d",
resp.StatusCode, expect... |
package service
import (
"context"
"sync"
"go-common/app/service/main/assist/conf"
"go-common/app/service/main/assist/dao/account"
"go-common/app/service/main/assist/dao/assist"
"go-common/app/service/main/assist/dao/message"
"go-common/library/log"
"go-common/library/queue/databus"
)
type Service struct {
... | {
s := &Service{
c: c,
ass: assist.New(c),
acc: account.New(c),
msg: message.New(c),
cacheChan: make(chan func(), 1024),
relationSub: databus.New(c.RelationSub),
}
s.wg.Add(1)
go s.relationConsumer()
s.wg.Add(1)
go s.cacheproc()
return s
} |
package instructions
import (
"fmt"
"github.com/bongo227/goory/types"
"github.com/bongo227/goory/value"
)
type CondBr struct {
block value.Value
name string
condition value.Value
trueBlock value.Value
falseBlock value.Value
}
func NewCondBr(block value.Value, name string, condition value.Valu... | {
return types.VOID
} |
package bsu
import (
"crypto/tls"
"net/http"
"testing"
"github.com/hashicorp/packer/builder/osc/common"
builderT "github.com/hashicorp/packer/helper/builder/testing"
"github.com/outscale/osc-go/oapi"
)
func TestBuilderAcc_basic(t *testing.T) {
builderT.Test(t, builderT.TestCase{
PreCheck: func()... | {
access := &common.AccessConfig{RawRegion: "us-east-1"}
clientConfig, err := access.Config()
if err != nil {
return nil, err
}
skipClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
return oapi.NewClient(clientConfig, skipClient), nil
} |
package app
import (
"fmt"
"net/http"
)
type collect struct{
url string
controller func(w http.ResponseWriter, r *http.Request) bool
}
func render(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
routes := Routes()
url := r.URL.Path
for _, element := range routes{
if... | {
mux := http.NewServeMux()
mux.HandleFunc( "/" , func(w http.ResponseWriter, r *http.Request){
render(w, r)
})
mux.HandleFunc( "/api/" , func(w http.ResponseWriter, r *http.Request){
api(w, r)
})
println( fmt.Sprintf("Starting exodo server on port %d", port))
http.ListenAndServe(fmt.Sprintf("%s:%d... |
package engine
import (
"time"
"github.com/aws/amazon-ecs-agent/agent/api"
)
type impossibleTransitionError struct {
state api.ContainerStatus
}
func (err *impossibleTransitionError) Error() string {
return "Cannot transition to " + err.state.String()
}
func (err *impossibleTransitionError) ErrorName() string... | {
return "Cannot" + err.transition + "ContainerError"
} |
package timeutil
import (
"time"
)
func SetTimeout(t time.Duration, callback func()) {
go func() {
time.Sleep(t)
callback()
}()
}
func SetInterval(t time.Duration, callback func() bool) {
go func() {
for {
time.Sleep(t)
if !callback() {
break
}
}
}()
}
func Nanosecond() int64 {
return... | {
return time.Now().UnixNano() / 1e9
} |
package iso
import (
"context"
"fmt"
"log"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
parallelscommon "github.com/hashicorp/packer/builder/parallels/common"
)
type stepAttachISO struct{}
func (s *stepAttachISO) Cleanup(state multist... | {
driver := state.Get("driver").(parallelscommon.Driver)
isoPath := state.Get("iso_path").(string)
ui := state.Get("ui").(packersdk.Ui)
vmName := state.Get("vmName").(string)
ui.Say("Attaching ISO to the default CD/DVD ROM device...")
command := []string{
"set", vmName,
"--device-set", "cdrom0",
"--image",... |
package tempconv
import "testing"
func TestFToC(t *testing.T) {
var f Fahrenheit = 95
c := FToC(f)
if c != Celsius(35) {
t.Errorf(`FToC(%g) == %g failed`, f, c)
}
}
func TestCToK(t *testing.T) {
var c Celsius = 37
k := CToK(c)
if k != Kelvin(310.15) {
t.Errorf(`CToK(%g) == %g failed`, c, k)
}
}
func T... | {
var c Celsius = 37
f := CToF(c)
if f != Fahrenheit(98.6) {
t.Errorf(`CToF(%g) == %g failed`, c, f)
}
} |
package fasthttpradix
import (
"github.com/valyala/fasthttp"
rr "github.com/byte-mug/golibs/radixroute"
"strings"
)
func NormPath(str string) string {
return "/"+strings.Trim(str,"/")+"/"
}
func InvalidPath(ctx *fasthttp.RequestCtx) {
ctx.SetBody([]byte("404 Not Found\n"))
ctx.SetStatusCode(fasthttp.StatusNo... | {
t := r.routes[string(ctx.Method())]
if t==nil {
InvalidPath(ctx)
return
}
i,_ := t.Get(ctx.Path(),ctx.SetUserValue)
h,ok := i.(*handling)
if !ok {
InvalidPath(ctx)
return
}
h.handle(ctx)
} |
package validator
import (
"fmt"
"github.com/pivotal-cf/pivnet-resource/concourse"
)
type CheckValidator struct {
input concourse.CheckRequest
}
func NewCheckValidator(input concourse.CheckRequest) *CheckValidator {
return &CheckValidator{
input: input,
}
}
func (v CheckValidator) Validate() error | {
if v.input.Source.APIToken == "" {
return fmt.Errorf("%s must be provided", "api_token")
}
if v.input.Source.ProductSlug == "" {
return fmt.Errorf("%s must be provided", "product_slug")
}
return nil
} |
package multiwriter
import (
"io"
)
type multiWriter []io.Writer
func New(w ...io.Writer) io.Writer {
return multiWriter(w)
}
func send(w io.Writer, p []byte, done chan<- result) {
var res result
res.n, res.err = w.Write(p)
if res.n < len(p) && res.err == nil {
res.err = io.ErrShortWrite
}
done <- res... | {
done := make(chan result, len(mw))
for _, w := range mw {
go send(w, p, done)
}
endResult := result{n: len(p)}
for _ = range mw {
res := <-done
if res.err != nil && (endResult.err == nil || res.n < endResult.n) {
endResult = res
}
}
return endResult.n, endResult.err
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.