input stringlengths 24 2.11k | output stringlengths 7 948 |
|---|---|
package cli
import (
"fmt"
"github.com/dailymuse/git-fit/config"
"github.com/dailymuse/git-fit/transport"
"github.com/dailymuse/git-fit/util"
"io/ioutil"
"os"
)
func Gc(schema *config.Config, trans transport.Transport, args []string) | {
savedFiles := make(map[string]bool, len(schema.Files)*2)
for _, hash := range schema.Files {
savedFiles[hash] = true
}
allFiles, err := ioutil.ReadDir(".git/fit")
if err != nil {
util.Fatal("Could not read .git/fit: %s\n", err.Error())
}
for _, file := range allFiles {
_, ok := savedFiles[file.Name()... |
package session
import (
"github.com/gorilla/mux"
"github.com/rebel-l/sessionservice/src/authentication"
"github.com/rebel-l/sessionservice/src/configuration"
"github.com/rebel-l/sessionservice/src/storage"
log "github.com/sirupsen/logrus"
"net/http"
)
type Session struct {
Storage storage.Handler
Aut... | {
log.Debug("Session endpoint: Init ...")
router.Handle("/session/", s.handlerFactory(http.MethodPut)).Methods(http.MethodPut)
log.Debug("Session endpoint: initialized!")
} |
package eventbreakpoints
import (
"context"
"github.com/chromedp/cdproto/cdp"
)
type SetInstrumentationBreakpointParams struct {
EventName string `json:"eventName"`
}
func SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams {
return &SetInstrumentationBreakpointParams{
... | {
return &RemoveInstrumentationBreakpointParams{
EventName: eventName,
}
} |
package menu
import "fmt"
type MenuFunc func()
type MenuEntry struct {
MenuText string
MenuSelector int
MenuFunction MenuFunc
StopRunning bool
}
func (entry MenuEntry) IsSelected(selector int) bool {
return entry.MenuSelector == selector
}
func (entry MenuEntry) PrintEntry() | {
fmt.Printf("%d - %v\n", entry.MenuSelector, entry.MenuText)
} |
package language
import (
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
)
func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
out, _ := metadata.FromOutgoingContext(ctx)
out = out.Copy()
for _, md := range mds {
for k, v := range md {
out[k] = append(out[k], v...)
... | {
return []string{
"https:www.googleapis.com/auth/cloud-platform",
}
} |
package db
import (
"github.com/globalsign/mgo"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/db/storage"
)
const (
DefaultDatabaseURL = "127.0.0.1:27017"
DefaultDatabaseName = "gandalf"
)
type Storage struct {
*storage.Storage
}
func conn() (*storage.Storage, error) {
url, dbname := DbConfig()
ret... | {
var (
strg Storage
err error
)
strg.Storage, err = conn()
return &strg, err
} |
package watt
import (
"encoding/json"
"time"
"github.com/datawire/ambassador/pkg/consulwatch"
"github.com/datawire/ambassador/pkg/k8s"
)
type ConsulSnapshot struct {
Endpoints map[string]consulwatch.Endpoints `json:",omitempty"`
}
type Error struct {
Source string
Message string
Timestamp int64
}
f... | {
jsonBytes, err := json.Marshal(s)
if err != nil {
return nil, err
}
res := &ConsulSnapshot{}
err = json.Unmarshal(jsonBytes, res)
return res, err
} |
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 err.name
} |
package do
import (
"fmt"
"reflect"
)
func WaitForErrorChannels(ctx Context, channels ...<-chan error) (err error) {
cases := make([]reflect.SelectCase, len(channels)+1)
ctxDoneCaseIndex := len(channels)
for i, ch := range channels {
cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.Val... | {
didRead, val := nonBlockingChannelRead(errChan)
return didRead, val.(error)
} |
package model
import (
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"
"strings"
)
type RegisterServerAutoRecoveryResponse struct {
HttpStatusCode int `json:"-"`
}
func (o RegisterServerAutoRecoveryResponse) String() string | {
data, err := utils.Marshal(o)
if err != nil {
return "RegisterServerAutoRecoveryResponse struct{}"
}
return strings.Join([]string{"RegisterServerAutoRecoveryResponse", string(data)}, " ")
} |
package model
type Interface interface {
VisitString(name string, resume func())
VisitInt(name string, resume func())
VisitFloat(name string, resume func())
VisitBool(name string, resume func())
VisitPtr(name string, resume func())
VisitBytes(name string, resume func())
VisitSlice(name string, resume func())
V... | {
resume()
} |
package mock
import (
"fmt"
"time"
"github.com/cilium/cilium/pkg/lock"
)
type MockMetrics struct {
mutex lock.RWMutex
apiCall map[string]float64
rateLimit map[string]time.Duration
}
func NewMockMetrics() *MockMetrics {
return &MockMetrics{
apiCall: map[string]float64{},
rateLimit: map[string]ti... | {
m.mutex.Lock()
m.apiCall[fmt.Sprintf("operation=%s, status=%s", operation, status)] += duration
m.mutex.Unlock()
} |
package main
import (
fmtlog "log"
"time"
"github.com/BurntSushi/toml"
"github.com/emilevauge/traefik/provider"
"github.com/emilevauge/traefik/types"
)
type GlobalConfiguration struct {
Port string
GraceTimeOut int64
AccessLogsFile string
TraefikLogsFile ... | {
globalConfiguration := new(GlobalConfiguration)
globalConfiguration.Port = ":80"
globalConfiguration.GraceTimeOut = 10
globalConfiguration.LogLevel = "ERROR"
globalConfiguration.ProvidersThrottleDuration = time.Duration(2 * time.Second)
return globalConfiguration
} |
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 describeStruct(t interface{}, depth int) string {
prefix := strings.Repeat(" ", depth)
var out string
s := reflect.I... | {
return template.FuncMap{
"pretty": func(i interface{}) string {
return pretty.Sprint(i)
},
"json": func(i interface{}) string {
json, _ := json.MarshalIndent(i, "", "\t")
return string(json)
},
"yaml": func(i interface{}) string {
yaml, _ := yaml.Marshal(i)
return string(yaml)
},
"spew":... |
package vm
import (
"github.com/rancher/wrangler/pkg/generic"
"k8s.io/client-go/rest"
)
type Factory struct {
*generic.Factory
}
func NewFactoryFromConfigOrDie(config *rest.Config) *Factory {
f, err := NewFactoryFromConfig(config)
if err != nil {
panic(err)
}
return f
}
func NewFactoryFromConfig(config *re... | {
f, err := generic.NewFactoryFromConfigWithOptions(config, opts)
return &Factory{
Factory: f,
}, err
} |
package locus
import (
"github.com/gocircuit/circuit/use/circuit"
)
type XLocus struct {
l *Locus
}
func (x XLocus) GetPeers() []*Peer {
return x.l.GetPeers()
}
func (x XLocus) Self() interface{} {
return x.l.Self()
}
type YLocus struct {
X circuit.PermX
}
func (y YLocus) GetPeers() map[string]*Peer {
r ... | {
circuit.RegisterValue(XLocus{})
} |
package rfc
import (
"fmt"
"strings"
"github.com/zmap/zcrypto/x509"
"github.com/zmap/zlint/v3/lint"
"github.com/zmap/zlint/v3/util"
)
type extDuplicateExtension struct{}
func init() {
lint.RegisterLint(&lint.Lint{
Name: "e_ext_duplicate_extension",
Description: "A certificate MUST NOT inclu... | {
extensionOIDs := make(map[string]bool)
duplicateOIDs := make(map[string]bool)
for _, ext := range cert.Extensions {
oid := ext.Id.String()
if alreadySeen := extensionOIDs[oid]; alreadySeen {
duplicateOIDs[oid] = true
} else {
extensionOIDs[oid] = true
}
}
if len(duplicateOIDs) == 0 {
return &l... |
package rest
import (
"time"
eventsapiv1beta1 "k8s.io/api/events/v1beta1"
"k8s.io/apiserver/pkg/registry/generic"
"k8s.io/apiserver/pkg/registry/rest"
genericapiserver "k8s.io/apiserver/pkg/server"
serverstorage "k8s.io/apiserver/pkg/server/storage"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/... | {
storage := map[string]rest.Storage{}
eventsStorage := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))
storage["events"] = eventsStorage
return storage
} |
package atomic
import (
"encoding/json"
"strconv"
"sync/atomic"
)
type Uint32 struct {
_ nocmp
v uint32
}
func NewUint32(val uint32) *Uint32 {
return &Uint32{v: val}
}
func (i *Uint32) Load() uint32 {
return atomic.LoadUint32(&i.v)
}
func (i *Uint32) Add(delta uint32) uint32 {
return atomic.AddUint32... | {
atomic.StoreUint32(&i.v, val)
} |
package test_utils
import (
"fmt"
"simplejsondb/dbio"
)
type InMemoryDataFile struct {
Blocks [][]byte
CloseFunc func() error
ReadBlockFunc func(uint16, []byte) error
WriteBlockFunc func(uint16, []byte) error
}
func NewFakeDataFile(blocksCount int) *InMemoryDataFile {
blocks := [][]byte{}
for... | {
return df.WriteBlockFunc(id, data)
} |
package main
import (
"strings"
"testing"
)
func TestLogParser(t *testing.T) | {
fields := []string{"", "", "size", "", "", "duration", "method", "url", "", "", "mime_type", "agent"}
p := NewLogParser(strings.NewReader(ssvLog), NewSSVLexer(fields))
ch, err := p.Get()
if err != nil {
t.Fatalf("%v\n", err)
}
for r := range ch {
if r.Err() != nil {
t.Errorf("%v", r.Err())
}
}
} |
package server
var skipSystemMastersAuthorizer = false
func SkipSystemMastersAuthorizer() | {
skipSystemMastersAuthorizer = true
} |
package server
import (
"reflect"
"testing"
"github.com/cockroachdb/cockroach/gossip/resolver"
"github.com/cockroachdb/cockroach/util/leaktest"
)
func TestParseNodeAttributes(t *testing.T) {
defer leaktest.AfterTest(t)
ctx := NewContext()
ctx.Attrs = "attr1=val1::attr2=val2"
ctx.Stores = "mem=1"
ctx.GossipB... | {
defer leaktest.AfterTest(t)
ctx := NewContext()
ctx.GossipBootstrap = "localhost:12345,,localhost:23456"
ctx.Stores = "mem=1"
if err := ctx.Init("start"); err != nil {
t.Fatalf("Failed to initialize the context: %v", err)
}
r1, err := resolver.NewResolver(&ctx.Context, "tcp=localhost:12345")
if err != nil {... |
package cmd
import (
"fmt"
"github.com/aptly-dev/aptly/deb"
"github.com/smira/commander"
)
func aptlySnapshotRename(cmd *commander.Command, args []string) error {
var (
err error
snapshot *deb.Snapshot
)
if len(args) != 2 {
cmd.Usage()
return commander.ErrCommandError
}
oldName, newName := arg... | {
cmd := &commander.Command{
Run: aptlySnapshotRename,
UsageLine: "rename <old-name> <new-name>",
Short: "renames snapshot",
Long: `
Command changes name of the snapshot. Snapshot name should be unique.
Example:
$ aptly snapshot rename wheezy-min wheezy-main
`,
}
return cmd
} |
package main
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) {
TestingT(t)
}
type CommonTests struct {
out *bytes.Buffer
d *Dispatcher
}
var _ = Suite(&CommonTests{})
func removeFilesInDir(dir string) error {
files, err := ioutil.ReadDir(di... | {
t.out = new(bytes.Buffer)
t.d = &Dispatcher{stderr: t.out}
} |
import "sort"
type Schedule struct {
intervals []Interval
}
func (s *Schedule) Len() int {
return len(s.intervals)
}
func (s *Schedule) Swap(i, j int) {
s.intervals[i], s.intervals[j] = s.intervals[j], s.intervals[i]
}
func (s *Schedule) Check() bool {
for i:=0; i<len(s.intervals)-1; i++ {
... | {
if s.intervals[i].Start < s.intervals[j].Start {
return true
}
return false
} |
package sample
import (
"time"
"encoding/json"
)
type Datum struct {
Status string `json:"status"`
Timestamp time.Time `json:"timestamp"`
}
type Sample struct {
Key string `json:"key"`
Typ string `json:"type"`
Data Datum `json:"data"`
}
func Init() Sample {
sample := Sample{"sample","testing", Datum{"ok", ... | {
result, _ := json.Marshal(m)
return string(result)
} |
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... | {
timestamp := Second()
if len(timestamps) > 0 {
timestamp = timestamps[0]
}
return time.Unix(timestamp, 0).Format(format)
} |
package dbr
import "bytes"
type Buffer interface {
WriteString(s string) (n int, err error)
String() string
WriteValue(v ...interface{}) (err error)
Value() []interface{}
}
type buffer struct {
bytes.Buffer
v []interface{}
}
func (b *buffer) WriteValue(v ...interface{}) error {
b.v = append(b.v, v...)
... | {
return &buffer{}
} |
package system
import (
"context"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/formatter"
"github.com/spf13/cobra"
)
type diskUsageOptions struct {
verbose bool
format string
}
func newDiskUsageCommand(dockerCli command.Cli) *cobra.Command {
var opts d... | {
du, err := dockerCli.Client().DiskUsage(context.Background())
if err != nil {
return err
}
format := opts.format
if len(format) == 0 {
format = formatter.TableFormatKey
}
var bsz int64
for _, bc := range du.BuildCache {
if !bc.Shared {
bsz += bc.Size
}
}
duCtx := formatter.DiskUsageContext{
... |
package factor
import (
"github.com/jesand/stats"
"github.com/jesand/stats/dist"
"github.com/jesand/stats/variable"
)
type Factor interface {
Adjacent() []variable.RandomVariable
Score() float64
}
func NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {
return &DistFactor{
Va... | {
return factor.Vars
} |
package main
import (
"bytes"
"github.com/bitly/go-nsq"
)
type BackendQueue interface {
Put([]byte) error
ReadChan() chan []byte
Close() error
Delete() error
Depth() int64
Empty() error
}
type DummyBackendQueue struct {
readChan chan []byte
}
func NewDummyBackendQueue() BackendQueue {
return &DummyBac... | {
return nil
} |
package context
import (
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
"testing"
)
func TestGetterAndSetter(t *testing.T) | {
params := httprouter.Params{{"foo", "bar"}}
ctx := NewContextFromRouterParams(context.Background(), params)
assert.NotNil(t, ctx)
res, err := FetchRouterParamsFromContext(ctx, "foo")
assert.Nil(t, err)
assert.Equal(t, map[string]string{"foo": "bar"}, res)
_, err = FetchRouterParamsFromContext(context.Backgrou... |
package utils
import (
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
"github.com/pinterb/hsc/config"
)
type Utils struct {
client *github.Client
config *config.Config
Users *UserUtils
}
type Response struct {
*github.Response
}
func NewUtils(config *config.Config) *Utils {
clie... | {
resp := &Response{Response: r}
return resp
} |
package action
import (
"io/ioutil"
"net/http"
"strings"
"fmt"
)
type Http struct {
config *ActionConfig
}
func (h *Http) Run() (*Result, error) {
url := h.config.Params.GetString("url")
if url == "" {
return nil, fmt.Errorf("url parameter required")
}
method := h.config.Params.GetString("method")
if me... | {
data := make(map[string]interface{})
data["status-code"] = resp.StatusCode
data["headers"] = resp.Header
h.config.Log.Infof("%s %s -> %d", resp.Request.Method, resp.Request.URL.String(), resp.StatusCode)
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data["raw-body"] = body... |
package eventlistener
import (
"testing"
"github.com/docker/docker/api/types"
"golang.org/x/net/context"
"fmt"
"time"
"github.com/docker/docker/api/types/events"
)
func TestEventListener(t *testing.T) {
const labelToMonitor = "tugbot-test"
tsk := make(chan string, 10)
Register(dockerClientMock{}, labelToM... | {
panic("This function not suppose to be called")
} |
package command
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"google.golang.org/grpc"
"github.com/itslab-kyushu/simple-kvs/kvs"
"github.com/itslab-kyushu/sss/cfg"
"github.com/urfave/cli"
)
type getOpt struct {
Config *cfg.Config
Name string
OutputFile string
Log io.Writer
}
func Cm... | {
if opt.Config.NServers() == 0 {
return fmt.Errorf("No server information is given.")
}
fmt.Fprintln(opt.Log, "Downloading a file")
server := opt.Config.Servers[0]
conn, err := grpc.Dial(
fmt.Sprintf("%s:%d", server.Address, server.Port),
grpc.WithInsecure(),
grpc.WithCompressor(grpc.NewGZIPCompressor(... |
package douban
import (
"encoding/json"
"time"
"github.com/q191201771/chef_go/http"
)
type Book struct {
pubdate time.Time
Authors []string `json:"author"`
Title string `json:"title"`
PubDate string `json:"pubdate"`
ISBN10 string `json:"isbn10"`
Summary string `json:"summary"`
}
type Resp struct... | {
var resp Resp
queries := map[string]string{
"q": bookname,
}
res, _, _ := http.Get(PATH, queries, nil, nil)
err := json.Unmarshal([]byte(res), &resp)
if err != nil {
panic(err)
}
return resp.Books[0]
} |
package match
import (
"reflect"
"testing"
)
func Match(t *testing.T, value interface{}) *Matcher {
return &Matcher{
t: t,
value: value,
}
}
func IsNil(t *testing.T, value interface{}) *Matcher {
return Match(t, value).IsNil()
}
func IsNotNil(t *testing.T, value interface{}) *Matcher {
return Match... | {
return Match(t, value).Matches(pattern)
} |
package example
import (
"net/http"
"gopkg.in/gin-gonic/gin.v1"
)
func GinEngine() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/", ginHelloHandler)
return r
}
func ginHelloHandler(c *gin.Context) | {
c.String(http.StatusOK, "Hello World")
} |
package string
import (
dss "github.com/emirpasic/gods/stacks/arraystack"
)
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func ReverseNest1(s string) string {
r := []rune(s)
switchHeadTail(r)
r... | {
r := []rune(s)
if len(r) == 1 || len(r) == 0 {
return s
}
sub := ReverseNest(string(r[1:]))
return sub + string(r[0:1])
} |
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... | {
if server.listener == nil {
return "", errors.New("not bound")
}
return extractBoundAddress(server.listener)
} |
package tmdb
import (
"fmt"
)
type Changes struct {
Results []struct {
ID int
Adult bool
}
}
var changeOptions = map[string]struct{}{
"page": {},
"start_date": {},
"end_date": {}}
func (tmdb *TMDb) GetChangesMovie(options map[string]string) (*Changes, error) {
var movieChanges Changes
opti... | {
var tvChanges Changes
optionsString := getOptionsString(options, changeOptions)
uri := fmt.Sprintf("%s/tv/changes?api_key=%s%s", baseURL, tmdb.apiKey, optionsString)
result, err := getTmdb(uri, &tvChanges)
return result.(*Changes), err
} |
package service
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_OnlineList(t *testing.T) {
Convey("online list", t, WithService(func(s *Service) {
data, err := s.OnlineList(context.Background())
So(err, ShouldBeNil)
Printf("%v", data)
}))
}
func TestService_... | {
Convey("test online OnlineArchiveCount", t, WithService(func(s *Service) {
res := s.OnlineArchiveCount(context.Background())
So(res, ShouldNotBeNil)
}))
} |
package gc
import "strconv"
func _() {
var x [1]struct{}
_ = x[Pxxx-0]
_ = x[PEXTERN-1]
_ = x[PAUTO-2]
_ = x[PAUTOHEAP-3]
_ = x[PPARAM-4]
_ = x[PPARAMOUT-5]
_ = x[PFUNC-6]
}
const _Class_name = "PxxxPEXTERNPAUTOPAUTOHEAPPPARAMPPARAMOUTPFUNC"
var _Class_index = [...]uint8{0, 4, 11, 16, 25, 31, 40, 45}
fun... | {
if i >= Class(len(_Class_index)-1) {
return "Class(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Class_name[_Class_index[i]:_Class_index[i+1]]
} |
package main
type OffState struct {
statusLed Output
}
func NewOffState(statusLed Output) State {
s := OffState{statusLed: statusLed}
return &s
}
func (s *OffState) Event(m StateMachine, pin uint, value uint) {
if pin == GPIO_SWITCH_PIN && value == GPIO_SWITCH_ON {
m.Transit(STATE_WAITING)
}
}
func (s *Off... | {
s.statusLed.Low()
} |
package cache
import (
"time"
utilcache "k8s.io/apimachinery/pkg/util/cache"
"k8s.io/apimachinery/pkg/util/clock"
)
type simpleCache struct {
cache *utilcache.Expiring
}
func newSimpleCache(clock clock.Clock) cache {
return &simpleCache{cache: utilcache.NewExpiringWithClock(clock)}
}
func (c *simpleCache) s... | {
record, ok := c.cache.Get(key)
if !ok {
return nil, false
}
value, ok := record.(*cacheRecord)
return value, ok
} |
package protocol
import "sync"
var msgPool = sync.Pool{
New: func() interface{} {
header := Header([12]byte{})
header[0] = magicNumber
return &Message{
Header: &header,
}
},
}
func FreeMsg(msg *Message) {
if msg != nil {
msg.Reset()
msgPool.Put(msg)
}
}
var poolUint32Data = sync.Pool{
New: ... | {
return msgPool.Get().(*Message)
} |
package main_test
import (
"testing"
"github.com/boltdb/bolt"
. "github.com/boltdb/bolt/cmd/bolt"
)
func TestBucketsDBNotFound(t *testing.T) {
SetTestMode(true)
output := run("buckets", "no/such/db")
equals(t, "stat no/such/db: no such file or directory", output)
}
func TestBuckets(t *testing.T) | {
SetTestMode(true)
open(func(db *bolt.DB, path string) {
db.Update(func(tx *bolt.Tx) error {
tx.CreateBucket([]byte("woojits"))
tx.CreateBucket([]byte("widgets"))
tx.CreateBucket([]byte("whatchits"))
return nil
})
db.Close()
output := run("buckets", path)
equals(t, "whatchits\nwidgets\nwoojits"... |
package model
import (
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"
"errors"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter"
"strings"
)
type PrePaidServerSchedulerHints struct {
Group *string `json:"g... | {
return PrePaidServerSchedulerHintsTenancyEnum{
SHARED: PrePaidServerSchedulerHintsTenancy{
value: "shared",
},
DEDICATED: PrePaidServerSchedulerHintsTenancy{
value: "dedicated",
},
}
} |
package proxy
import (
"store"
"utils"
)
const (
EFFICIENT_POOL_KEY = "EfficientPoolKey"
)
var (
efficientPool = InitEfficientPool()
)
type EfficientPool struct {
BasePool
Storage store.SetStringStorer
}
func InitEfficientPool() *EfficientPool {
return &EfficientPool{BasePool: *InitBasePool(), Storage: stor... | {
pool.Storage.Add(EFFICIENT_POOL_KEY, proxy)
} |
package models
import "encoding/binary"
type Page struct {
Prev bool
PrevVal int
Next bool
NextVal int
NextURL string
pages int
Pages []string
Total int
Count int
Skip int
}
func itob(v int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
return b
}
func SearchPa... | {
var pg Page
var total int
if count%perPage != 0 {
total = count/perPage + 1
} else {
total = count / perPage
}
if total < page {
page = total
}
if page == 1 {
pg.Prev = false
pg.Next = true
}
if page != 1 {
pg.Prev = true
}
if total > page {
pg.Next = true
}
if total == page {
pg.N... |
package go_koans
func isPrimeNumber(possiblePrime int) bool {
for underPrime := 2; underPrime < possiblePrime; underPrime++ {
if possiblePrime%underPrime == 0 {
return false
}
}
return true
}
func aboutConcurrency() {
ch := make(chan int)
assert(__delete_me__)
assert(<-ch == 2)
assert(<-ch == 3)
a... | {
for i := 2; ; i++ {
assert(i < 100)
}
} |
package v1beta1
import (
"context"
"github.com/google/knative-gcp/pkg/apis/duck"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"knative.dev/pkg/apis"
)
func (t *Topic) Validate(ctx context.Context) *apis.FieldError {
err := t.Spec.Validate(ctx).ViaField("spec")
if apis.IsInUpdate(ct... | {
var errs *apis.FieldError
if ts.Topic == "" {
errs = errs.Also(
apis.ErrMissingField("topic"),
)
}
switch ts.PropagationPolicy {
case TopicPolicyCreateDelete, TopicPolicyCreateNoDelete, TopicPolicyNoCreateNoDelete:
default:
errs = errs.Also(
apis.ErrInvalidValue(ts.PropagationPolicy, "propagation... |
package manual
import (
"os/exec"
)
type sshOption []string
var allocateTTY sshOption = []string{"-t"}
var commonSSHOptions = []string{"-o", "StrictHostKeyChecking no"}
func sshCommand(host string, command string, options ...sshOption) *exec.Cmd | {
args := append([]string{}, commonSSHOptions...)
for _, option := range options {
args = append(args, option...)
}
args = append(args, host, "--", command)
return exec.Command("ssh", args...)
} |
package oci
import (
"encoding/json"
"fmt"
"github.com/phoenix-io/phoenix-mon/plugins"
ps "github.com/shirou/gopsutil/process"
"io/ioutil"
)
type OCI struct {
process []plugin.Process
count int
}
type PState struct {
ID string `json:"id"`
Pid int `json:"init_process_pid"`
}
func init() {
plugin.Regist... | {
return &OCI{}, nil
} |
package sparta
import (
"context"
"github.com/aws/aws-lambda-go/lambdacontext"
)
func cloudWatchLogsProcessor(ctx context.Context,
props map[string]interface{}) error {
lambdaCtx, _ := lambdacontext.FromContext(ctx)
Logger().Info().
Str("RequestID", lambdaCtx.AwsRequestID).
Msg("CloudWatch log event")
Logg... | {
var lambdaFunctions []*LambdaAWSInfo
cloudWatchLogsLambda, _ := NewAWSLambda(LambdaName(cloudWatchLogsProcessor),
cloudWatchLogsProcessor,
IAMRoleDefinition{})
cloudWatchLogsPermission := CloudWatchLogsPermission{}
cloudWatchLogsPermission.Filters = make(map[string]CloudWatchLogsSubscriptionFilter, 1)
clou... |
package fake
import (
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
v1alpha1 "k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1"
)
type FakeKopsV1alpha1 struct {
*testing.Fake
}
func (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {
return &Fak... | {
var ret *rest.RESTClient
return ret
} |
package logger
import (
"io"
"log"
"os"
"github.com/influxdata/wlog"
)
func newTelegrafWriter(w io.Writer) io.Writer {
return &telegrafLog{
writer: wlog.NewWriter(w),
}
}
type telegrafLog struct {
writer io.Writer
}
func SetupLogging(debug, quiet bool, logfile string) {
if debug {
wlog.SetLeve... | {
return t.writer.Write(p)
} |
package cpdf
import (
"io/ioutil"
)
type bookmarkable interface {
CombinedBookmarkList() string
LocalPath() string
Dir() string
}
func (c *Cpdf) addBookmarksArgs(job bookmarkable) {
c.addArgs("-add-bookmarks", infoPath(job))
}
func infoPath(job bookmarkable) string {
return job.Dir() + "bookmarks.info"
}
... | {
return ioutil.WriteFile(infoPath(job), []byte(job.CombinedBookmarkList()), 0644)
} |
package cmd
import (
"github.com/mgoltzsche/ctnr/bundle/builder"
"github.com/mgoltzsche/ctnr/model/oci"
"github.com/mgoltzsche/ctnr/run"
"github.com/spf13/cobra"
)
var (
execCmd = &cobra.Command{
Use: "exec [flags] CONTAINERID COMMAND",
Short: "Executes a process in a container",
Long: `Executes a proce... | {
flagsBundle.InitProcessFlags(execCmd.Flags())
flagsBundle.InitRunFlags(execCmd.Flags())
} |
package esbuilder
import "github.com/serulian/compiler/sourcemap"
type StatementBuilder interface {
WithMapping(mapping sourcemap.SourceMapping) SourceBuilder
mapping() (sourcemap.SourceMapping, bool)
emitSource(sb *sourceBuilder)
}
type statementNode interface {
emit(sb *sourceBuilder)
}
type statementBui... | {
builder.statement.emit(sb)
} |
package datastore
import "strconv"
func _() {
var x [1]struct{}
_ = x[PTNull-0]
_ = x[PTInt-1]
_ = x[PTTime-2]
_ = x[PTBool-3]
_ = x[PTBytes-4]
_ = x[PTString-5]
_ = x[PTFloat-6]
_ = x[PTGeoPoint-7]
_ = x[PTKey-8]
_ = x[PTBlobKey-9]
_ = x[PTPropertyMap-10]
_ = x[PTUnknown-11]
}
const _PropertyType_name ... | {
if i >= PropertyType(len(_PropertyType_index)-1) {
return "PropertyType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _PropertyType_name[_PropertyType_index[i]:_PropertyType_index[i+1]]
} |
package syscall
import "unsafe"
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint64(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func... | {
return Timeval{Sec: sec, Usec: usec}
} |
package gtimer
func (h *priorityQueueHeap) Len() int {
return len(h.array)
}
func (h *priorityQueueHeap) Less(i, j int) bool {
return h.array[i].priority < h.array[j].priority
}
func (h *priorityQueueHeap) Push(x interface{}) {
h.array = append(h.array, x.(priorityQueueItem))
}
func (h *priorityQueueHeap... | {
if len(h.array) == 0 {
return
}
h.array[i], h.array[j] = h.array[j], h.array[i]
} |
package plan
import (
"github.com/pingcap/tidb/expression"
)
func projectionCanBeEliminated(p *Projection) bool {
child := p.children[0].(PhysicalPlan)
if p.Schema().Len() != child.Schema().Len() {
return false
}
for i, expr := range p.Exprs {
col, ok := expr.(*expression.Column)
if !ok {
ret... | {
switch plan := p.(type) {
case *Projection:
if !projectionCanBeEliminated(plan) {
break
}
child := plan.children[0].(PhysicalPlan)
child.SetSchema(plan.Schema())
RemovePlan(p)
p = EliminateProjection(child)
}
children := make([]Plan, 0, len(p.Children()))
for _, child := range p.Children() {
chi... |
package characteristic
import (
"github.com/brutella/hc/model"
)
type HeatingCoolingMode struct {
*ByteCharacteristic
}
func NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode {
c := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions... | {
return model.HeatCoolModeType(c.Byte())
} |
package fake
import (
"encoding/json"
"fmt"
"net/http"
"strings"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
type CFAPI struct {
server *ghttp.Server
}
type CFAPIConfig struct {
Routes map[string]Response
}
type Response struct {
Code int
Body interface{}
}
func NewCFAPI() *CFAPI {
serv... | {
fields := strings.Split(request, " ")
Expect(fields).To(HaveLen(2))
return fields[0], fields[1]
} |
package astar
import (
"os"
"image"
)
import _ "image/png"
func openImage(filename string) (image.Image) {
f, err := os.Open(filename)
if err != nil {
return nil
}
defer f.Close()
img, _, _ := image.Decode(f)
return img
}
func GetMapFromImage(filename string) MapData {
img := openImage(filename)
if(im... | {
max := uint32(65536-1)
bounds := img.Bounds()
map_data := NewMapData(bounds.Max.X, bounds.Max.Y)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := img.At(x, y).RGBA()
if(r == max && g == max && b == max && a == max) {
map_data[x][bounds.Max.... |
package runconfig
import (
"fmt"
"io"
"io/ioutil"
"strings"
"github.com/hyperhq/hypercli/pkg/broadcaster"
"github.com/hyperhq/hypercli/pkg/ioutils"
)
type StreamConfig struct {
stdout *broadcaster.Unbuffered
stderr *broadcaster.Unbuffered
stdin io.ReadCloser
stdinPipe io.WriteCloser
}
... | {
var errors []string
if streamConfig.stdin != nil {
if err := streamConfig.stdin.Close(); err != nil {
errors = append(errors, fmt.Sprintf("error close stdin: %s", err))
}
}
if err := streamConfig.stdout.Clean(); err != nil {
errors = append(errors, fmt.Sprintf("error close stdout: %s", err))
}
if er... |
package swt
import "github.com/timob/javabind"
type EventsTraverseEventInterface interface {
EventsKeyEventInterface
}
type EventsTraverseEvent struct {
EventsKeyEvent
}
func (jbobject *EventsTraverseEvent) ToString() string {
jret, err := jbobject.CallMethod(javabind.GetEnv(), "toString", "java/lang/String"... | {
conv_a := javabind.NewGoToJavaCallable()
if err := conv_a.Convert(a); err != nil {
panic(err)
}
obj, err := javabind.GetEnv().NewObject("org/eclipse/swt/events/TraverseEvent", conv_a.Value().Cast("org/eclipse/swt/widgets/Event"))
if err != nil {
panic(err)
}
conv_a.CleanUp()
x := &EventsTraverseEvent{}
... |
package check
type GoFmt struct {
Dir string
Filenames []string
}
func (g GoFmt) Weight() float64 {
return .35
}
func (g GoFmt) Percentage() (float64, []FileSummary, error) {
return GoTool(g.Dir, g.Filenames, []string{"gofmt", "-s", "-l"})
}
func (g GoFmt) Description() string {
return `Gofmt form... | {
return "gofmt"
} |
package models
import "fmt"
var RoomPool = make([] *Room, 0)
func AddRoom(r *Room) {
RoomPool = append(RoomPool, r)
}
func FindRoom(d string) (int, *Room) {
for i, v := range RoomPool {
if v.Name == d {
return i, v
}
}
return -1, &Room{}
}
func RemoveRoom(r *Room) {
index, _ := FindRoom(r.Name)
... | {
pool := make([]string, 0)
for _, obj := range RoomPool {
pool = append(pool, obj.Name)
}
return len(RoomPool), pool
} |
package lwmq
import (
"fmt"
)
type MessageStore interface {
Messages(*Queue) ([]*Message, error)
AddMessage(*Message) error
PopMessages(*Queue) ([]*Message, error)
}
type MemoryMessageStore struct {
messages map[*Queue][]*Message
}
func NewMemoryMessageStore() *MemoryMessageStore {
s := &MemoryMessageSto... | {
messages, err := self.Messages(q)
if err != nil {
return nil, err
}
self.messages[q] = []*Message{}
return messages, nil
} |
package global
import (
"database/sql"
"encoding/json"
"html/template"
"io/ioutil"
"log"
)
var Templates *template.Template
var DB *sql.DB
var Config Configuration
type Configuration struct {
Port string
DbUser string
DbPassword string
DbName string
JWTtokenPassw... | {
data, err := ioutil.ReadFile("config.json")
if err != nil {
log.Fatal("Please add config.json file:", err)
}
config := Configuration{}
if err := json.Unmarshal(data, &config); err != nil {
log.Fatal("Please format configuration file correctly:", err)
}
ParseTemplates()
Config = config
return config
} |
package core
import (
"github.com/oracle/oci-go-sdk/common"
)
type UpdatePublicIpDetails struct {
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
DisplayName *string `mandatory:"false" json:"displayName"`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags... | {
return common.PointerString(m)
} |
package decorators
import (
"fmt"
"os/exec"
"strings"
"github.com/antham/chyle/chyle/convh"
)
type shellConfig map[string]struct {
COMMAND string
ORIGKEY string
DESTKEY string
}
type shell struct {
COMMAND string
ORIGKEY string
DESTKEY string
}
func (s shell) execute(value string) (string, error) {
... | {
var tmp interface{}
var value string
var ok bool
var err error
if tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {
return commitMap, nil
}
if value, err = convh.ConvertToString(tmp); err != nil {
return commitMap, nil
}
if (*commitMap)[s.DESTKEY], err = s.execute(value); err != nil {
return commitMap, err
... |
package common
import "math/big"
type _N_ [_S_]byte
func BytesTo_N_(b []byte) _N_ {
var h _N_
h.SetBytes(b)
return h
}
func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }
func BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }
func HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }
... | { return string(h[:]) } |
package permute
import "testing"
func BenchmarkPermGenLex(b *testing.B) {
p := New(20)
for i := 0; i < b.N; i++ {
LexNext(p)
}
}
func BenchmarkPermGenHeap(b *testing.B) {
h := NewHeap(20)
var sw [2]int
for i := 0; i < b.N; i++ {
h.Next(&sw)
}
}
func BenchmarkPermGenEven(b *testing.B) {
h := NewPlainCha... | {
h := NewPlainChangeGen(20)
var sw [2]int
for i := 0; i < b.N; i++ {
h.Next(&sw)
}
} |
package main
import (
"flag"
"github.com/jonasi/baller"
"os"
)
func init() {
methods["boxscore_advanced_v2"] = cmd_boxscore_advanced_v2
}
func cmd_boxscore_advanced_v2(cl *baller.Client) (interface{}, error) | {
var (
fs = flag.NewFlagSet("boxscore_advanced_v2", flag.ExitOnError)
verbose = fs.Bool("verbose", false, "")
options baller.BoxscoreAdvancedV2Options
)
fs.StringVar(&options.GameID, "GameID", "", "")
fs.IntVar(&options.StartPeriod, "StartPeriod", 0, "")
fs.IntVar(&options.EndPeriod, "EndPeriod", 0, "... |
package seqnum
type Value uint32
type Size uint32
func (v Value) LessThan(w Value) bool {
return int32(v-w) < 0
}
func (v Value) LessThanEq(w Value) bool {
if v == w {
return true
}
return v.LessThan(w)
}
func (v Value) InRange(a, b Value) bool {
return v-a < b-a
}
func (v Value) InWindow(first Valu... | {
*v += Value(s)
} |
package auth
import (
authorizationapi "github.com/projectatomic/atomic-enterprise/pkg/authorization/api"
"github.com/projectatomic/atomic-enterprise/pkg/client"
)
type Review interface {
Users() []string
Groups() []string
}
type review struct {
response *authorizationapi.ResourceAccessReviewResponse
}
func ... | {
return &reviewer{
resourceAccessReviewsNamespacer: resourceAccessReviewsNamespacer,
}
} |
package httpmux
import "net/http"
type ConfigOption interface {
Set(c *Config)
}
type ConfigOptionFunc func(c *Config)
func (f ConfigOptionFunc) Set(c *Config) { f(c) }
func WithPrefix(prefix string) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })
}
func WithMiddleware(mw ...M... | {
return ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })
} |
package shutdown
import (
"log"
"os/exec"
"strconv"
)
func abort() {
run("/a")
}
func run(args ...string) {
cmd := exec.Command("shutdown", args...)
err := cmd.Run()
if err != nil {
log.Println("error: " + err.Error())
}
}
func start(sec int) | {
run("/s", "/t", strconv.Itoa(sec))
} |
package refmt
import (
"github.com/polydawn/refmt/obj"
"github.com/polydawn/refmt/obj/atlas"
"github.com/polydawn/refmt/shared"
)
func Clone(src, dst interface{}) error {
return CloneAtlased(src, dst, atlas.MustBuild())
}
func MustClone(src, dst interface{}) {
if err := Clone(src, dst); err != nil {
panic(err)... | {
x := &cloner{
marshaller: obj.NewMarshaller(atl),
unmarshaller: obj.NewUnmarshaller(atl),
}
x.pump = shared.TokenPump{x.marshaller, x.unmarshaller}
return x
} |
package eventstreamapi
import (
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
type Marshaler interface {
MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)
}
type Encoder interface {
Encode(eventstream.Message) error
}
type EventW... | {
msg, err := w.marshal(event)
if err != nil {
return err
}
return w.encoder.Encode(msg)
} |
package spotify
import (
"os"
"testing"
"github.com/laicosly/goth"
"github.com/stretchr/testify/assert"
)
func provider() *Provider {
return New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "/foo", "user")
}
func Test_New(t *testing.T) {
t.Parallel()
a := assert.New(t)
p := provider()
a.Equal(p.... | {
t.Parallel()
a := assert.New(t)
p := provider()
session, err := p.BeginAuth("test_state")
s := session.(*Session)
a.NoError(err)
a.Contains(s.AuthURL, "accounts.spotify.com/authorize")
} |
package gapbuf
import "github.com/millere/jk/line"
type GapBuf struct {
buffer []*line.Line
gapStart int
gapEnd int
readPoint int
}
func New(size int) *GapBuf {
a := GapBuf{
buffer: make([]*line.Line, size),
gapStart: 0,
gapEnd: size,
}
return &a
}
func (a *GapBuf) Len(... | {
if i >= a.gapStart {
return a.buffer[i+a.gapEnd-a.gapStart]
} else {
return a.buffer[i]
}
} |
package stdlib
import (
"container/heap"
"reflect"
)
func init() {
Symbols["container/heap"] = map[string]reflect.Value{
"Fix": reflect.ValueOf(heap.Fix),
"Init": reflect.ValueOf(heap.Init),
"Pop": reflect.ValueOf(heap.Pop),
"Push": reflect.ValueOf(heap.Push),
"Remove": reflect.ValueOf(heap.Rem... | { W.WSwap(i, j) } |
package packages
import (
"fmt"
"github.com/alexandrecarlton/gogurt"
)
type PkgConfig struct{}
func (pkgconfig PkgConfig) URL(version string) string {
return fmt.Sprintf("https://pkgconfig.freedesktop.org/releases/pkg-config-%s.tar.gz", version)
}
func (pkgconfig PkgConfig) Build(config gogurt.Config) error {
... | {
return "pkg-config"
} |
package blanket_emulator
import (
"testing"
"github.com/ranmrdrakono/indika/loader/elf"
)
func TestRun(t *testing.T) | {
elf.Run("../samples/binutils/bin_O1/gdb")
} |
package main
import (
"io"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type Client struct {
hub *Hub
ws *websocket.Conn
otherSide *Client
channelID uuid.UUID
remoteType string
params map[string][]string
wmu sync.Mutex
rmu sync.Mutex
}
func ... | {
c.rmu.Lock()
err = c.ws.SetReadDeadline(t)
c.rmu.Unlock()
return
} |
package main
import (
"log"
"time"
)
var ACTION_POTENTIAL_THRESHOLD int = 30
var DELAY_BETWEEN_FIRINGS time.Duration = 10
var SIGNAL_BUFFER_SIZE = 2048
type Neuron struct {
tag string
dendrite chan int
synapses []Synapse
potential int
}
func (n *Neuron) Fire() {
log.Println(n.tag, "Fired")
n.pote... | {
return Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}
} |
package graph
import (
"fmt"
"github.com/gonum/graph"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
)
var (
UnknownNodeKind = "UnknownNode"
)
var (
UnknownEdgeKind = "UnknownEdge"
ReferencedByEdgeKind = "ReferencedBy"
ContainsEdgeKind = "Co... | {
visited := map[int]bool{}
prevContainingNode := containedNode
for {
visited[prevContainingNode.ID()] = true
currContainingNode := GetContainingNode(g, prevContainingNode)
if currContainingNode == nil {
return prevContainingNode
}
if _, alreadyVisited := visited[currContainingNode.ID()]; alreadyVisit... |
package serialconsole
import original "github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole"
const (
DefaultBaseURI = original.DefaultBaseURI
)
type BaseClient = original.BaseClient
type ConsoleClient = original.ConsoleClient
type DeploymentValidateResult = original.DeploymentValid... | {
return original.New(subscriptionID)
} |
package permissions
import (
"path/filepath"
"util"
)
var globalPermissions *PermissionsLoader
func SetPath(permissions string) error {
if permissions != "default" {
pl, err := NewPermissionsLoader(permissions)
if err != nil {
return err
}
if globalPermissions != nil {
globalPermissions.Close()... | {
if globalPermissions == nil {
return &Default
}
return globalPermissions.Get()
} |
package leetcode
func pow(x float64, n int) float64 {
if n == 1 {
return x
}
res := pow(x*x, n/2)
if n%2 == 1 {
res *= x
}
return res
}
func myPow(x float64, n int) float64 | {
if n == 0 {
return 1
}
flag := false
if n > 0 {
flag = true
} else {
n = -n
}
res := pow(x, n)
if !flag {
res = 1 / res
}
return res
} |
package websocket
type data struct {
Index int
Body []byte
Error error
}
func parseHeader(header []byte) (index int, ok bool) {
index = int(header[0])<<24 | int(header[1])<<16 | int(header[2])<<8 | int(header[3])
if ok = (header[0]&0x80 == 0); !ok {
index &= 0x7fffffff
}
return
}
func makeHeader(index in... | {
header[0] = byte(index >> 24 & 0xff)
header[1] = byte(index >> 16 & 0xff)
header[2] = byte(index >> 8 & 0xff)
header[3] = byte(index & 0xff)
return
} |
package terminal
import "fmt"
var ColorError int = 167
var ColorWarn int = 93
var ColorSuccess int = 82
var ColorNeutral int = 50
var BackgroundColorBlack = "\033[30;49m"
var BackgroundColorWhite = "\033[30;47m"
var ResetCode string = "\033[0m"
func Colorize(color int, msg string) string {
if !stdoutIsTTY {
... | {
if !stdoutIsTTY {
return msg
}
return fmt.Sprintf("\033[1m%s\033[0m", msg)
} |
package testing
import "k8s.io/kubernetes/pkg/util/iptables"
type fake struct{}
func NewFake() *fake {
return &fake{}
}
func (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {
return true, nil
}
func (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {
return n... | {
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.