input stringlengths 24 2.11k | output stringlengths 7 948 |
|---|---|
package flag
import (
"flag"
"github.com/mono83/cfg"
"github.com/mono83/cfg/reflect"
"os"
"sync"
)
type flagSource struct {
set *flag.FlagSet
args []string
m sync.Mutex
values map[string]interface{}
}
func NewFlagSource() cfg.Configurer {
return NewCustomFlagSource(flag.CommandLine, os.Args[1:])
}
... | {
if f.values == nil {
err := f.load()
if err != nil {
return err
}
}
v, ok := f.values[key]
if !ok {
return cfg.ErrKeyMissing{Key: key}
}
return reflect.CopyHelper(key, v, target)
} |
package main
func isValidUsername(s string) bool | {
return false
} |
package schedulercache
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
)
type FakeCache struct {
AssumeFunc func(*api.Pod)
}
func (f *FakeCache) AssumePod(pod *api.Pod) error {
f.AssumeFunc(pod)
return nil
}
func (f *FakeCache) AddPo... | { return nil } |
package gq
import (
"testing"
"time"
)
var count int
type WorkerTest struct {
Delay time.Duration
}
func (w WorkerTest) Data() string {
return ""
}
func (w WorkerTest) DelayTime() time.Duration {
return w.Delay
}
func (w WorkerTest) Preprocess() string {
return ""
}
func (w WorkerTest) Postprocess() stri... | {
count++
} |
package client
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
"golang.org/x/net/context"
)
func TestVolumeRemoveError(t *testing.T) {
client := &Client{
transport: newMockClient(nil, errorMock(http.StatusInternalServerError, "Server error")),
}
err := client.VolumeRemove(context.Backg... | {
expectedURL := "/volumes/volume_id"
client := &Client{
transport: newMockClient(nil, func(req *http.Request) (*http.Response, error) {
if !strings.HasPrefix(req.URL.Path, expectedURL) {
return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
}
if req.Method != "DELETE" {
retu... |
package downloader
import (
"fmt"
"github.com/WhaleCoinOrg/WhaleCoin/core/types"
)
type peerDropFn func(id string)
type dataPack interface {
PeerId() string
Items() int
Stats() string
}
type headerPack struct {
peerId string
headers []*types.Header
}
func (p *headerPack) PeerId() string { return p.peer... | { return p.peerId } |
package action
import (
"bytes"
"encoding/base64"
"errors"
boshagentblobstore "github.com/cloudfoundry/bosh-agent/agent/blobstore"
boshcrypto "github.com/cloudfoundry/bosh-utils/crypto"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
type UploadBlobSpec struct {
BlobID string `json... | {
decodedPayload, err := base64.StdEncoding.DecodeString(content.Payload)
if err != nil {
return content.BlobID, err
}
if err = a.validatePayload(decodedPayload, content.Checksum); err != nil {
return content.BlobID, err
}
reader := bytes.NewReader(decodedPayload)
err = a.blobManager.Write(content.BlobID... |
package gitlab
import (
"fmt"
"strings"
"testing"
"github.com/nlamirault/guzuta/utils"
)
var (
namespace = "nicolas-lamirault"
name = "scame"
description = "An Emacs configuration"
)
func getGitlabClient() *Client {
return NewClient(utils.Getenv("GUZUTA_GITLAB_TOKEN"))
}
func TestRetrieveGitLabPro... | {
client := getGitlabClient()
_, err := client.GetProject(namespace, "aaaaaaaaaa")
if err == nil {
t.Fatalf("No error with unknown username")
}
} |
package buffactory
import (
"testing"
)
func TestStats(t *testing.T) {
stats := make(Stats, 0, 3)
stats.InsertData(1)
stats.InsertData(2)
stats.InsertData(3)
if stats.Min() != 1 {
t.Fatal("Min failed", stats.Min())
}
if stats.Max() != 3 {
t.Fatal("Max failed", stats.Max())
}
if stats.Average() != 2.0 ... | {
stats := make(Stats, 0, 3)
stats.InsertData(0)
stats.InsertData(1)
stats.InsertData(2)
stats.InsertData(3)
for i, s := range stats {
if int64(i) != s {
t.Fatal("numbers don't match", i , s, []int64(stats))
}
}
} |
package server
import (
"context"
"os"
"os/signal"
"k8s.io/klog/v2"
)
var onlyOneSignalHandler = make(chan struct{})
var shutdownHandler chan os.Signal
func SetupSignalHandlerIgnoringFurtherSignals() <-chan struct{} {
return SetupSignalContextNotExiting().Done()
}
func SetupSignalContext() context... | {
return SetupSignalContext().Done()
} |
package ldb
import (
"bytes"
"testing"
"github.com/decred/dcrd/database"
"github.com/decred/dcrutil"
"github.com/btcsuite/golangcrypto/ripemd160"
)
func TestAddrIndexKeySerialization(t *testing.T) {
var hash160Bytes [ripemd160.Size]byte
var packedIndex [35]byte
fakeHash160 := dcrutil.Hash160([]byte("testi... | {
testKey := []byte("a")
prefixRange := bytesPrefix(testKey)
if !bytes.Equal(prefixRange.Start, []byte("a")) {
t.Errorf("Wrong prefix start, got %d, expected %d", prefixRange.Start,
[]byte("a"))
}
if !bytes.Equal(prefixRange.Limit, []byte("b")) {
t.Errorf("Wrong prefix end, got %d, expected %d", prefixRan... |
package proxy
import (
"github.com/fatedier/frp/models/config"
)
type StcpProxy struct {
*BaseProxy
cfg *config.StcpProxyConf
}
func (pxy *StcpProxy) Run() (remoteAddr string, err error) {
listener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)
if errRet != nil {
err = errRet
return
}
... | {
return pxy.cfg
} |
package main
import (
"io"
"os"
"bufio"
"fmt"
)
type Store struct {
}
func NewStore() *Store {
return &Store{}
}
func (s Store)WriteStore(store map[string]string, file string) error {
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
return s.WriteTo(store, f)
}
func (s Store)W... | {
store := make(map[string]string)
f, err := os.Open(file)
if err != nil {
if os.IsNotExist(err) {
return store, nil
}
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
handleCommand(store, scanner.Text())
}
return store, scanner.Err()
} |
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... | {
for actionPotential := range n.dendrite {
n.potential += actionPotential
if n.HasReachedThreshold() {
n.Fire()
}
}
} |
package controllers
import (
"fmt"
"github.com/codeskyblue/go-sh"
"github.com/revel/revel"
"strings"
)
type Search struct {
*revel.Controller
}
func (c Search) Search(q string, count int) revel.Result | {
fmt.Printf("query string is %s\n", q)
fmt.Printf("count is %d\n", count)
if count == 0 {
count = 10
}
command := fmt.Sprintf("ag --silent -i -m %d \"%s\" \"/Users/Join/Elements\"", count, strings.Trim(q, " "))
shell_out, err := sh.Command("bash", "-c", command).Output()
var pretty_results []string
if err !=... |
package core
import (
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)
type ByoipRangeCollection struct {
Items []ByoipRangeSummary `mandatory:"true" json:"items"`
}
func (m ByoipRangeCollection) String() string | {
return common.PointerString(m)
} |
package system
import (
"fmt"
"strings"
)
const (
execErrorMsgFmt = "Running command: '%s', stdout: '%s', stderr: '%s'"
execShortErrorMaxLines = 100
)
type ExecError struct {
Command string
StdOut string
StdErr string
}
func NewExecError(cmd, stdout, stderr string) ExecError {
return ExecError{
C... | {
outLines := strings.Split(in, "\n")
if i := len(outLines); i > maxLines {
outLines = outLines[i-maxLines:]
}
return strings.Join(outLines, "\n")
} |
package olog
import (
"fmt"
)
type DirectLogger struct {
writers map[string]Writer
}
func NewDirectLogger() *DirectLogger {
return &DirectLogger{
writers: make(map[string]Writer),
}
}
func (dl *DirectLogger) Log(level Level,
module string,
fmtstr string,
args ...interface{}) {
if level == PrintLevel {
... | {
delete(dl.writers, uniqueID)
} |
package render
import (
"net/http"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
)
var pbContentType = []string{"application/x-protobuf"}
func (r PB) Render(w http.ResponseWriter) error {
if r.TTL <= 0 {
r.TTL = 1
}
return writePB(w, r)
}
func writePB(w http.ResponseWriter, obj PB) (err erro... | {
writeContentType(w, pbContentType)
} |
package dbr
import (
"github.com/stretchr/testify/assert"
"testing"
)
func BenchmarkDeleteSql(b *testing.B) {
s := createFakeSession()
b.ResetTimer()
for i := 0; i < b.N; i++ {
s.DeleteFrom("alpha").Where("a", "b").Limit(1).OrderDir("id", true).ToSql()
}
}
func TestDeleteAllToSql(t *testing.T) {
s := crea... | {
s := createRealSessionWithFixtures()
res, err := s.InsertInto("dbr_people").Columns("name", "email").Values("Barack", "barack@whitehouse.gov").Exec()
assert.NoError(t, err)
id, err := res.LastInsertId()
assert.NoError(t, err)
res, err = s.DeleteFrom("dbr_people").Where("id = ?", id).Exec()
assert.NoError(t,... |
package roles
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsTopLevelRole(t *testing.T) {
assert.True(t, IsTopLevelRole("root"))
assert.True(t, IsTopLevelRole("targets"))
assert.True(t, IsTopLevelRole("timestamp"))
assert.True(t, IsTopLevelRole("snapshot"))
assert.False(t, IsTopLevelRole... | {
assert.False(t, IsDelegatedTargetsManifest("root.json"))
assert.False(t, IsDelegatedTargetsManifest("targets.json"))
assert.False(t, IsDelegatedTargetsManifest("timestamp.json"))
assert.False(t, IsDelegatedTargetsManifest("snapshot.json"))
assert.True(t, IsDelegatedTargetsManifest("bins.json"))
} |
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")
}
storeHeight := blockStore.Height()
if height > storeHeight {
return nil, fmt.Errorf("Height must be less than or equal to the current blockchain height")
}
header := blockStore.LoadBlockMeta(height).Header
if height == storeHeight... |
package loop
import (
"github.com/tideland/golib/errors"
)
const (
ErrLoopPanicked = iota + 1
ErrHandlingFailed
ErrRestartNonStopped
ErrKilledBySentinel
)
var errorMessages = errors.Messages{
ErrLoopPanicked: "loop panicked: %v",
ErrHandlingFailed: "error handling for %q failed",
ErrRestartN... | {
return errors.IsError(err, ErrKilledBySentinel)
} |
package main
import "C"
import (
"fmt"
"os"
"runtime"
"runtime/pprof"
"time"
"unsafe"
)
func init() {
register("CgoPprofThread", CgoPprofThread)
register("CgoPprofThreadNoTraceback", CgoPprofThreadNoTraceback)
}
func CgoPprofThreadNoTraceback() {
pprofThread()
}
func pprofThread() {
f, err := os.Cre... | {
runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)
pprofThread()
} |
package conditions_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestConditions(t *testing.T) | {
RegisterFailHandler(Fail)
RunSpecs(t, "Conditions Suite")
} |
package resources
import "github.com/awslabs/goformation/cloudformation/policies"
type AWSOpsWorksStack_ElasticIp struct {
Ip string `json:"Ip,omitempty"`
Name string `json:"Name,omitempty"`
_deletionPolicy policies.DeletionPolicy
_dependsOn []string
_metadata map[string]interface{}
}
func (r *AWSOpsWor... | {
r._metadata = metadata
} |
package watcher
func (w *Watcher) webhookPolling() | {
defer w.syncWg.Done()
if w.once {
return
}
errCh := make(chan error, 1)
go w.ListenAndServe(errCh)
for {
select {
case err := <-errCh:
w.ErrCh <- err
case <-w.rcvDoneCh:
return
}
}
} |
package cli
import (
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
)
func CheckError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func FileExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
fu... | {
if err != nil {
CheckError(fmt.Errorf("Fatal error: %v", err))
}
} |
package main
import (
"fmt"
"os"
"strings"
)
func produce(s string) string {
if s == "2" {
return s
}
return s[1:]
}
func associate(s string) string {
if s == "" {
return s
}
return s + "2" + s
}
func main() {
in, _ := os.Open("743.in")
defer in.Close()
out, _ := os.Create("743.out")
defer out.Cl... | {
switch {
case strings.Contains(s, "0"):
return ""
case s[0] == '3':
return associate(solve(s[1:]))
case len(s) > 1 && s[0] == '2':
return produce(s)
default:
return ""
}
} |
package main
import (
"io/ioutil"
"testing"
)
var cliParamsTcs = []struct {
params []string
resultIsError bool
}{
{[]string{"FOO=BAR", "BAZ=BLAH"}, false},
{[]string{"FOO=BAR", "BAZ"}, true},
}
var cliExistsTcs = []struct {
cmd string
resultIsError bool
}{
{"ls", false},
{"no-way-this-ex... | {
for _, tc := range cliParamsTcs {
err := validateCliParameters(tc.params)
if (err != nil) != tc.resultIsError {
t.Fatalf("Expected '%v' got '%v' for '%v'", tc.resultIsError, err, tc.params)
}
}
} |
package lib
import "sync"
type ConcurrentPrinterMap struct {
byCUPSName map[string]Printer
byGCPID map[string]Printer
mutex sync.RWMutex
}
func NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap {
cpm := ConcurrentPrinterMap{}
cpm.Refresh(printers)
return &cpm
}
func (cpm *Concurren... | {
cpm.mutex.RLock()
defer cpm.mutex.RUnlock()
if p, exists := cpm.byCUPSName[name]; exists {
return p, true
}
return Printer{}, false
} |
package crypto
import (
"crypto/rand"
"encoding/base64"
"io"
"time"
)
func GenerateRandomBytes(n int) []byte {
b := make([]byte, n)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
panic(err)
}
return b
}
func Timestamp() int64 {
return time.Now().UTC().Unix()
}
func Base64Decode(value []by... | {
enc := make([]byte, base64.RawURLEncoding.EncodedLen(len(value)))
base64.RawURLEncoding.Encode(enc, value)
return enc
} |
package hdinsight
import (
"github.com/Azure/go-autorest/autorest"
)
type BaseClient struct {
autorest.Client
Endpoint string
UserName string
}
func NewWithoutDefaults(endpoint string, userName string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
Endpoin... | {
return NewWithoutDefaults(endpoint, userName)
} |
package common
import (
"fmt"
v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
"github.com/rancher/rancher/pkg/ref"
"github.com/sirupsen/logrus"
)
func GetRuleID(groupID string, ruleName string) string {
return fmt.Sprintf("%s_%s", groupID, ruleName)
}
func GetGroupID(namespace, nam... | {
cluster, err := clusterLister.Get("", clusterName)
if err != nil {
logrus.Warnf("Failed to get cluster for %s: %v", clusterName, err)
return clusterName
}
return formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)
} |
package sha512
import "crypto/sha512"
const (
Size = 64
Size224 = 28
Size256 = 32
Size384 = 48
BlockSize = 128
)
func Sum512(data []byte) []byte {
a := sha512.Sum512(data)
return a[:]
}
func Sum512_224(data []byte) (sum224 []byte) {
a := sha512.Sum512_224(data)
return a[:]
}
func Sum512_256(data... | {
a := sha512.Sum384(data)
return a[:]
} |
package customer
import (
"testing"
assert "github.com/stretchr/testify/require"
stripe "github.com/stripe/stripe-go"
_ "github.com/stripe/stripe-go/testing"
)
func TestCustomerDel(t *testing.T) {
customer, err := Del("cus_123", nil)
assert.Nil(t, err)
assert.NotNil(t, customer)
}
func TestCustomerGet(t *tes... | {
customer, err := New(&stripe.CustomerParams{
Email: stripe.String("foo@example.com"),
Shipping: &stripe.CustomerShippingDetailsParams{
Address: &stripe.AddressParams{
Line1: stripe.String("line1"),
City: stripe.String("city"),
},
Name: stripe.String("name"),
},
})
assert.Nil(t, err)
assert... |
package model
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
)
type Response struct {
Status string `json:"status"`
ErrorText string `json:"errorText,omitempty"`
Address string `json:"address,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
Version string `json:"version,omit... | {
if r.StatusCode == 0 {
r.StatusCode = 200
}
w.WriteHeader(r.StatusCode)
return EncodeJson(r, w)
} |
package component
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/config"
"go.opentelemetry.io/collector/consumer"
)
func TestNewProcessorFactory(t *testing.T) {
const typeStr = "test"
defaultCfg := config.NewProcessorSettings(config.NewComponentID(typeStr))
... | {
const typeStr = "test"
defaultCfg := config.NewProcessorSettings(config.NewComponentID(typeStr))
factory := NewProcessorFactory(
typeStr,
func() config.Processor { return &defaultCfg },
WithTracesProcessor(createTracesProcessor),
WithMetricsProcessor(createMetricsProcessor),
WithLogsProcessor(createLogsP... |
package main
import (
"fmt"
"os"
"strings"
)
func produce(s string) string {
if s == "2" {
return s
}
return s[1:]
}
func solve(s string) string {
switch {
case strings.Contains(s, "0"):
return ""
case s[0] == '3':
return associate(solve(s[1:]))
case len(s) > 1 && s[0] == '2':
return produce(s)
... | {
if s == "" {
return s
}
return s + "2" + s
} |
package policy
import "github.com/Azure/azure-sdk-for-go/version"
func UserAgent() string {
return "Azure-SDK-For-Go/" + version.Number + " policy/2019-01-01"
}
func Version() string | {
return version.Number
} |
package fs
import (
. "launchpad.net/gocheck"
"os"
)
type CommonTestSuite struct{}
var _ = Suite(&CommonTestSuite{})
func (s *CommonTestSuite) TestMkDir_NonRecursive(c *C) {
tmpDir := c.MkDir() + "/foo"
err := MkDir(tmpDir, false, 0755)
c.Assert(err, IsNil)
f, err := os.Stat(tmpDir)
c.Assert(err, IsNil)
c... | {
suffix := "/foo/bar/baz"
tmpDir := c.MkDir()
err := MkDir(tmpDir+suffix, true, 0755)
c.Assert(err, IsNil)
f, err := os.Stat(tmpDir)
c.Assert(err, IsNil)
c.Assert(f.IsDir(), Equals, true)
err = RmDir(tmpDir, true)
c.Assert(err, IsNil)
f, err = os.Stat(tmpDir + suffix)
c.Assert(os.IsNotExist(err), Equals... |
package authmethod
import (
"sync"
"github.com/hashicorp/consul/agent/structs"
)
type syncCache struct {
lock sync.RWMutex
cache authMethodCache
}
func (c *syncCache) GetValidator(method *structs.ACLAuthMethod) (uint64, Validator, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
return c.cache.GetValidator(m... | {
c := &syncCache{}
c.cache.init()
return c
} |
package gorocksdb
import (
"testing"
"github.com/facebookgo/ensure"
)
func TestSliceTransform(t *testing.T) {
db := newTestDB(t, "TestSliceTransform", func(opts *Options) {
opts.SetPrefixExtractor(&testSliceTransform{})
})
defer db.Close()
wo := NewDefaultWriteOptions()
ensure.Nil(t, db.Put(wo, []byte("foo... | {
db := newTestDB(t, "TestFixedPrefixTransformOpen", func(opts *Options) {
opts.SetPrefixExtractor(NewFixedPrefixTransform(3))
})
defer db.Close()
} |
package shell
import (
"context"
"github.com/hashicorp/hcl/v2/hcldec"
sl "github.com/hashicorp/packer/common/shell-local"
"github.com/hashicorp/packer/packer"
)
type Provisioner struct {
config sl.Config
}
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
... | {
err := sl.Decode(&p.config, raws...)
if err != nil {
return err
}
err = sl.Validate(&p.config)
if err != nil {
return err
}
return nil
} |
package acpi
import (
"testing"
"github.com/u-root/u-root/pkg/testutil"
)
func TestRSDP(t *testing.T) | {
testutil.SkipIfNotRoot(t)
_, err := GetRSDP()
if err != nil {
t.Fatalf("GetRSDP: got %v, want nil", err)
}
} |
package jsondns
import (
"encoding/json"
"log"
"net/http"
"github.com/miekg/dns"
)
type dnsError struct {
Status uint32 `json:"Status"`
Comment string `json:"Comment,omitempty"`
}
func FormatError(w http.ResponseWriter, comment string, errcode int) | {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
errJSON := dnsError{
Status: dns.RcodeServerFailure,
Comment: comment,
}
errStr, err := json.Marshal(errJSON)
if err != nil {
log.Fatalln(err)
}
w.WriteHeader(errcode)
w.Write(errStr)
} |
package lib
import (
"log"
"strings"
)
type (
Question struct {
RelatesTo struct {
Answers []string `json:"answers"`
Save bool `json:"save"`
SaveTag string `json:"saveTag"`
} `json:"relatesTo"`
Context []string `json:"context"`
QuestionText string `json:"question"`
Possible... | {
for i := range this {
for a := range this[i].RelatesTo.Answers {
if strings.EqualFold(this[i].RelatesTo.Answers[a], prevAnswer) {
return this[i], this[i].RelatesTo.Save
}
}
}
return nil, false
} |
package cmd
import (
"reflect"
"testing"
)
func TestEnvDiff(t *testing.T) {
diff := &EnvDiff{map[string]string{"FOO": "bar"}, map[string]string{"BAR": "baz"}}
out := diff.Serialize()
diff2, err := LoadEnvDiff(out)
if err != nil {
t.Error("parse error", err)
}
if len(diff2.Prev) != 1 {
t.Error("len(diff... | {
if !IgnoredEnv(DIRENV_BASH) {
t.Fail()
}
if IgnoredEnv(DIRENV_DIFF) {
t.Fail()
}
if !IgnoredEnv("_") {
t.Fail()
}
if !IgnoredEnv("__fish_foo") {
t.Fail()
}
if !IgnoredEnv("__fishx") {
t.Fail()
}
} |
package rpc
import (
"fmt"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"github.com/eduardonunesp/sslb/lb"
)
type ServerStatus struct {
Server *lb.Server
}
type StatusResponse struct {
IdleWPool int
}
func StartServer(s *lb.Server) {
go func() {
serverStatus := &ServerStatus{s}
server := rpc.NewServer()... | {
statusRes := StatusResponse{
s.Server.CountIdle(),
}
*reply = statusRes
return nil
} |
package ray
import (
"github.com/v2ray/v2ray-core/common/alloc"
)
const (
bufferSize = 16
)
func NewRay() Ray {
return &directRay{
Input: make(chan *alloc.Buffer, bufferSize),
Output: make(chan *alloc.Buffer, bufferSize),
}
}
type directRay struct {
Input chan *alloc.Buffer
Output chan *alloc.Buffer
}
... | {
return this.Input
} |
package fake
import (
context "context"
runtime "k8s.io/apimachinery/pkg/runtime"
rest "k8s.io/client-go/rest"
fake "knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake"
client "knative.dev/eventing-prometheus/pkg/client/injection/client"
injection "knative.dev/pkg/injection"
logging "knative.d... | {
untyped := ctx.Value(client.Key{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake.Clientset from context.")
}
return untyped.(*fake.Clientset)
} |
package log
import "gopkg.in/inconshreveable/log15.v2"
var (
Logger log15.Logger
)
func init() {
Logger = log15.New()
Logger.SetHandler(log15.DiscardHandler())
}
func Interactive() {
Logger.SetHandler(log15.MultiHandler(
log15.LvlFilterHandler(
log15.LvlError,
log15.StderrHandler)))
}
func Debug(msg... | { Logger.Info(msg, ctx...) } |
package http
import (
"github.com/wcong/ants-go/ants/util"
"log"
Http "net/http"
"strconv"
"sync"
)
type HttpServer struct {
Http.Server
}
func NewHttpServer(setting *util.Settings, handler Http.Handler) *HttpServer {
port := strconv.Itoa(setting.HttpPort)
httpServer := &HttpServer{
Http.Server{
Addr: ... | {
go this.server(wg)
} |
package gmcache
import (
"fmt"
"github.com/codinl/go-logger"
"github.com/liyue201/gmcache/gmcache/config"
"github.com/liyue201/gmcache/utils"
"os"
)
func InitLog() error | {
if !utils.PathExist(config.AppConfig.Log.Dir) {
os.MkdirAll(config.AppConfig.Log.Dir, os.ModePerm)
}
err := logger.Init(config.AppConfig.Log.Dir, config.AppConfig.Log.File, config.AppConfig.Log.Level)
if err != nil {
fmt.Println("logger init error err=", err)
return err
}
logger.SetConsole(true)
fmt.P... |
package fake
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
action "github.com/vmware-tanzu/octant/pkg/action"
)
type MockActionRegistrar struct {
ctrl *gomock.Controller
recorder *MockActionRegistrarMockRecorder
}
type MockActionRegistrarMockRecorder struct {
mock *MockActionRegistr... | {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Register", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} |
package null
import (
"github.com/lmorg/murex/lang/stdio"
"github.com/lmorg/murex/lang/types"
)
func init() | {
stdio.RegisterWriteArray(types.Null, newArrayWriter)
} |
package elastic
type MissingAggregation struct {
field string
subAggregations map[string]Aggregation
meta map[string]interface{}
}
func NewMissingAggregation() *MissingAggregation {
return &MissingAggregation{
subAggregations: make(map[string]Aggregation),
}
}
func (a *MissingAggr... | {
source := make(map[string]interface{})
opts := make(map[string]interface{})
source["missing"] = opts
if a.field != "" {
opts["field"] = a.field
}
if len(a.subAggregations) > 0 {
aggsMap := make(map[string]interface{})
source["aggregations"] = aggsMap
for name, aggregate := range a.subAggregations {
... |
package main
import (
"net/http"
"time"
"github.com/VojtechVitek/ratelimit"
)
func main() {
middleware := ratelimit.Throttle(1)
http.ListenAndServe(":3333", middleware(http.HandlerFunc(Work)))
}
func Work(w http.ResponseWriter, r *http.Request) | {
w.Write([]byte("working hard...\n\n"))
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
time.Sleep(10 * time.Second)
w.Write([]byte("done"))
} |
package message
import (
"bytes"
"math/rand"
"time"
"encoding/json"
)
const MaxVectors = 32
const PacketSize = 512
type Packet []byte
type Vector struct {
X int
Y int
}
type Message struct {
Name int
Vectors []*Vector
Value string
}
var delim = byte(0)
func MessageToPacket(m *Message) Packe... | {
if len(vectors) <= MaxVectors {
results := make([]*Message, 0)
results = append(results, &Message{Name: name, Vectors: vectors})
return results
}
numMessages := len(vectors) / MaxVectors
results := make([]*Message, numMessages)
j := 0
for i := range results {
m := &Message{Vectors: make([]*Vector, 0... |
package utils
import (
"math/rand"
"time"
"github.com/astaxie/beego"
)
var testRandNum int
var testRandString string
func SetTestRandNum(n int) {
if !IsTest() {
return
}
testRandNum = n
}
func GetRandNum(n int) int {
if IsTest() {
return testRandNum
}
rand.Seed(time.Now().UnixNano())
return rand... | {
if !IsTest() {
return
}
testRandString = s
} |
package persona
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
type personaResponse struct {
Status string `json:"status"`
Email string `json:"email"`
}
func assert(audience, assertion string) (string, error) | {
params := url.Values{}
params.Add("assertion", assertion)
params.Add("audience", audience)
resp, err := http.PostForm("https://verifier.login.persona.org/verify", params)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var f personaResponse
err = json.Un... |
package playground
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
)
const baseURL = "https://play.golang.org"
func init() {
http.HandleFunc("/compile", bounce)
http.HandleFunc("/share", bounce)
}
func bounce(w http.ResponseWriter, r *http.Request) {
b := new(bytes.Buffer)
if err := pas... | {
if req.URL.Path == "/share" && !allowShare(req) {
return errors.New("Forbidden")
}
defer req.Body.Close()
url := baseURL + req.URL.Path
ctx, cancel := context.WithTimeout(contextFunc(req), 60*time.Second)
defer cancel()
r, err := post(ctx, url, req.Header.Get("Content-type"), req.Body)
if err != nil {
ret... |
package main
import "errors"
type Item struct {
Id int
Path string
}
type Status struct {
Status string
List []Item
Id int
}
const (
StateStopped = iota
StatePlaying
)
var items []Item
var nextId int
var currentTrack int
var currentState int
func addItem(path string) (id int) {
id = nextId
... | {
items = []Item{}
nextId = 1
currentTrack = 0
currentState = StateStopped
} |
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.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)
} |
package blobstore
import (
"fmt"
"os"
"path/filepath"
"sync"
)
type localStore struct {
sync.Mutex
root string
}
func NewLocalStore(root string) (Store, error) {
return newLocalStore(root)
}
func (ls *localStore) blobDirname(digest string) string {
return filepath.Join(ls.root, "blobs", digest)
}
func (ls... | {
ls := &localStore{root: root}
blobsDirname := ls.blobDirname("")
if err := os.MkdirAll(blobsDirname, os.FileMode(0755)); err != nil {
return nil, fmt.Errorf("unable to create local blob store directory %q: %s", blobsDirname, err)
}
return ls, nil
} |
package client
import (
"bufio"
"bytes"
"fmt"
"net/http"
"net/http/httputil"
log "github.com/Sirupsen/logrus"
"github.com/akutz/gotil"
)
func (c *client) logRequest(req *http.Request) {
if !c.logRequests {
return
}
w := log.StandardLogger().Writer()
fmt.Fprintln(w, "")
fmt.Fprint(w, " -----------... | {
if !c.logResponses {
return
}
w := log.StandardLogger().Writer()
fmt.Fprintln(w)
fmt.Fprint(w, " -------------------------- ")
fmt.Fprint(w, "HTTP RESPONSE (CLIENT)")
fmt.Fprintln(w, " -------------------------")
buf, err := httputil.DumpResponse(
res,
res.Header.Get("Content-Type") != "applicati... |
package kubectl
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
)
type FilterFunc func(runtime.Object, PrintOptions) bool
type Filters []FilterFunc
func NewResourceFilter() Filters {
return []FilterFunc{
filterPods,
}
}
func filterPods(obj runtime.... | {
var err error
switch obj.(type) {
case runtime.Unstructured, *runtime.Unknown:
if objBytes, err := runtime.Encode(api.Codecs.LegacyCodec(), obj); err == nil {
if decodedObj, err := runtime.Decode(api.Codecs.UniversalDecoder(), objBytes); err == nil {
obj = decodedObj
}
}
}
return obj, err
} |
package format
import (
"github.com/kitwalker12/fotomat/vips"
)
type Metadata struct {
Width int
Height int
Format Format
Orientation Orientation
HasAlpha bool
}
func (format Format) MetadataBytes(blob []byte) (Metadata, error) {
image, err := format.LoadBytes(blob)
if err != nil {
... | {
format := DetectFormat(blob)
if format == Unknown {
return Metadata{}, ErrUnknownFormat
}
return format.MetadataBytes(blob)
} |
package errorreporting
import (
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
)
func DefaultAuthScopes() []string {
return []string{
"https:www.googleapis.com/auth/cloud-platform",
}
}
func insertXGoog(ctx context.Context, val []string) context.Context | {
md, _ := metadata.FromOutgoingContext(ctx)
md = md.Copy()
md["x-goog-api-client"] = val
return metadata.NewOutgoingContext(ctx, md)
} |
package comm
import (
"context"
"github.com/hyperledger/fabric/common/semaphore"
"google.golang.org/grpc"
)
type Semaphore interface {
Acquire(ctx context.Context) error
Release()
}
type Throttle struct {
newSemaphore NewSemaphoreFunc
semaphore Semaphore
}
type ThrottleOption func(t *Throttle)
type NewSe... | {
t := &Throttle{
newSemaphore: func(count int) Semaphore { return semaphore.New(count) },
}
for _, optionFunc := range options {
optionFunc(t)
}
t.semaphore = t.newSemaphore(maxConcurrency)
return t
} |
package thrift
import "io"
type RichTransport struct {
TTransport
}
func (r *RichTransport) ReadByte() (c byte, err error) {
return readByte(r.TTransport)
}
func (r *RichTransport) WriteByte(c byte) error {
return writeByte(r.TTransport, c)
}
func (r *RichTransport) WriteString(s string) (n int, err error) {... | {
return &RichTransport{trans}
} |
package model
type RepoSecret struct {
ID int64 `json:"id" meddler:"secret_id,pk"`
RepoID int64 `json:"-" meddler:"secret_repo_id"`
Name string `json:"name" meddler:"secret_name"`
Value string `json:"value" meddler:"secret_value"`
Images []string `json:"image,omitempty" meddler:"secret_images,json"`
Events ... | {
return nil
} |
package client
import (
"encoding/xml"
)
type Frame struct {
ID string `xml:"id,attr"`
FrameType int
OpMode int
Name string
Contact string
OSVersion string
Version string
IsConnected int
SyncedSetting int
}
type FrameCollection map[string]Frame
func (col ... | {
return marshalJSONMap(col)
} |
package lzma
import (
"errors"
"fmt"
"unicode"
)
type operation interface {
Len() int
}
type match struct {
distance int64
n int
}
func (m match) verify() error {
if !(minDistance <= m.distance && m.distance <= maxDistance) {
return errors.New("distance out of range")
}
if !(1 <= m.n && m.n <= maxMa... | {
return m.n
} |
package main
import (
"github.com/faceless-saint/go-socketcmd"
"os"
"strings"
)
const EnvSocketPath = "SOCKET_PATH"
var ExampleSocketPath = "example.sock"
func main() {
client := socketcmd.NewClient("unix", ExampleSocketPath, nil)
if resp, err := client.Send(os.Args[1:]...); err != nil {
panic(err)
} ... | {
envPath := os.Getenv(EnvSocketPath)
if envPath != "" {
ExampleSocketPath = envPath
}
} |
package codec
import "time"
func fmtTime(t time.Time, fmt string, b []byte) []byte | {
s := t.Format(fmt)
b = b[:len(s)]
copy(b, s)
return b
} |
package daemon
import (
"os"
"path/filepath"
"github.com/docker/docker/container"
)
func fixPermissions(source, destination string, uid, gid int, destExisted bool) error {
destStat, err := os.Stat(destination)
if err != nil {
return err
}
doChownDestination := !destExisted || !destStat.IsDir()
return... | {
var toVolume bool
for _, mnt := range container.MountPoints {
if toVolume = mnt.HasResource(absPath); toVolume {
if mnt.RW {
break
}
return false, ErrVolumeReadonly
}
}
return toVolume, nil
} |
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/karrick/godirwalk"
"github.com/pkg/errors"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: %s dir1 [dir2 [dir3...]]\n", filepath.Base(os.Args[0]))
os.Exit(2)
}
scratchBuffer := make([]byte, 64*1024)
var count, total int
... | {
var count int
err := godirwalk.Walk(osDirname, &godirwalk.Options{
Unsorted: true,
ScratchBuffer: scratchBuffer,
Callback: func(_ string, _ *godirwalk.Dirent) error {
return nil
},
PostChildrenCallback: func(osPathname string, _ *godirwalk.Dirent) error {
deChildren, err := godirwalk.ReadDiren... |
package phaul
import (
"fmt"
"os"
"path/filepath"
)
type images struct {
cursor int
dir string
}
func (i *images) getPath(idx int) string {
return fmt.Sprintf(i.dir+"/%d", idx)
}
func (i *images) openNextDir() (*os.File, error) {
ipath := i.getPath(i.cursor)
err := os.Mkdir(ipath, 0700)
if err != nil ... | {
return &images{dir: wdir}, nil
} |
package v1
type ConfigMapProjectionApplyConfiguration struct {
LocalObjectReferenceApplyConfiguration `json:",inline"`
Items []KeyToPathApplyConfiguration `json:"items,omitempty"`
Optional *bool `json:"optional,omitempty"`
}
... | {
b.Optional = &value
return b
} |
package two
import (
"math"
"strings"
)
type Key struct {
code string
U bool
R bool
D bool
L bool
}
func KeypadCode(lines []string, keypad map[int]Key, currentKeypadIndex int) string {
code := make([]string, len(lines))
rowsQty := int(math.Sqrt(float64(len(keypad))))
currentKey := keypad[curr... | {
lines := strings.Split(directions, "\n")
keypad := make(map[int]Key)
keypad[0] = Key{"1", false, true, true, false}
keypad[1] = Key{"2", false, true, true, true}
keypad[2] = Key{"3", false, false, true, true}
keypad[3] = Key{"4", true, true, true, false}
keypad[4] = Key{"5", true, true, true, true}
keypad[5... |
package path
import (
"encoding/binary"
"time"
"github.com/scionproto/scion/go/lib/serrors"
)
const (
HopLen = 12
MacLen = 6
)
const MaxTTL = 24 * 60 * 60
const expTimeUnit = MaxTTL / 256
type HopField struct {
IngressRouterAlert bool
EgressRouterAlert bool
ExpTime uint8
ConsIngress uint1... | {
if len(raw) < HopLen {
return serrors.New("HopField raw too short", "expected", HopLen, "actual", len(raw))
}
h.EgressRouterAlert = raw[0]&0x1 == 0x1
h.IngressRouterAlert = raw[0]&0x2 == 0x2
h.ExpTime = raw[1]
h.ConsIngress = binary.BigEndian.Uint16(raw[2:4])
h.ConsEgress = binary.BigEndian.Uint16(raw[4:6])
... |
package suite_init
type SuiteData struct {
*StubsData
*SynchronizedSuiteCallbacksData
*WerfBinaryData
*ProjectNameData
*K8sDockerRegistryData
*TmpDirData
*ContainerRegistryPerImplementationData
}
func (data *SuiteData) SetupStubs(setupData *StubsData) bool {
data.StubsData = setupData
return true
}
func (... | {
data.SynchronizedSuiteCallbacksData = setupData
return true
} |
package queue
import "testing"
func TestQueueS(t *testing.T) {
q := NewSQ()
if !q.IsEmpty() ||
q.size != 0 ||
q.Size() != 0 {
t.Error()
}
q.EnQueue(0)
q.EnQueue(1)
q.EnQueue(2)
if q.Size() != 3 {
t.Error()
}
e0 := q.DeQueue()
if e0 != 0 || q.Size() != 2 {
t.Error()
}
e1 := q.DeQueue()
... | {
q := New()
if !q.IsEmpty() ||
q.size != 0 ||
q.Size() != 0 {
t.Error()
}
q.EnQueue(0)
q.EnQueue(1)
q.EnQueue(2)
if q.Size() != 3 {
t.Error()
}
e0 := q.DeQueue()
if e0 != 0 || q.Size() != 2 {
t.Error()
}
e1 := q.DeQueue()
if e1 != 1 {
t.Error()
}
e2 := q.DeQueue()
if e2 != 2 || q.S... |
package logger
import (
"log"
"log/syslog"
)
const (
LOG_PRIORITY = syslog.LOG_DAEMON | syslog.LOG_INFO
LOG_FLAGS = log.Lshortfile
)
var (
Logger *log.Logger
)
func init() | {
var err error
log.SetFlags(LOG_FLAGS)
Logger, err = syslog.NewLogger(LOG_PRIORITY, LOG_FLAGS)
if err != nil {
log.Fatal(err)
}
} |
package db
import (
"hg/messages"
"fmt"
"gopkg.in/mgo.v2"
)
const (
mongoURL = "127.0.0.1:27017"
)
func RecordHistory(historyEntry messages.HistoryMessage){
fmt.Println("Start to record history object")
persist("Insert",historyEntry)
}
func persist(operation string,historyEntry messages.HistoryMessage) | {
fmt.Println("Do db operation")
session, err := mgo.Dial(mongoURL)
if err != nil {
panic(err)
}
defer session.Close()
historyCollection := session.DB("historys").C("history")
switch operation {
case "Insert":
err = historyCollection.Insert(historyEntry)
if err != nil {
fmt.Printf("Can't insert docum... |
package scaleway
import (
"log"
"time"
"github.com/scaleway/scaleway-cli/pkg/api"
)
func Bool(val bool) *bool {
return &val
}
func deleteServerSafe(s *api.ScalewayAPI, serverID string) error {
server, err := s.GetServer(serverID)
if err != nil {
return err
}
if server.State != "stopped" {
if err... | {
return &val
} |
package l4
type TCP struct{}
func (t *TCP) String() string | {
return "<TCP header isn't supported>"
} |
package entity
import (
"context"
"github.com/utahta/momoclo-channel/dao"
)
type (
ReminderRepository interface {
FindAll(context.Context) ([]*Reminder, error)
Save(context.Context, *Reminder) error
}
reminderRepository struct {
dao.PersistenceHandler
}
)
func (repo *reminderRepository) FindAll(ctx... | {
return &reminderRepository{h}
} |
package clients
import (
"sync"
"sync/atomic"
"github.com/VolantMQ/volantmq/subscriber"
)
var subCount int32 = 0
type container struct {
lock sync.Mutex
rmLock sync.RWMutex
ses *session
expiry atomic.Value
sub *subscriber.Type
removable bool
removed bool
}
func (s *container) s... | {
if cleanStart && s.sub != nil {
s.sub.Offline(true)
s.sub = nil
}
if s.sub == nil {
s.sub = subscriber.New(c)
}
return s.sub
} |
package goji
import "net/http"
type router []route
type route struct {
Pattern
http.Handler
}
func (rt *router) route(r *http.Request) *http.Request {
for _, route := range *rt {
if r2 := route.Match(r); r2 != nil {
return r2.WithContext(&match{
Context: r2.Context(),
p: route.Pattern,
... | {
*rt = append(*rt, route{p, h})
} |
package pango_mock
import "github.com/coyim/gotk3adapter/pangoi"
func init() | {
pangoi.AssertPango(&Mock{})
pangoi.AssertFontDescription(&MockFontDescription{})
} |
package backend
import (
"path/filepath"
"github.com/webx-top/echo/handler/captcha"
"github.com/webx-top/echo/middleware/render"
"github.com/admpub/nging/v4/application/handler"
"github.com/admpub/nging/v4/application/library/common"
"github.com/admpub/nging/v4/application/library/config"
"github.com/admpub/n... | {
if config.DefaultCLIConfig.Type != `manager` {
return
}
conf := filepath.Base(config.DefaultCLIConfig.Conf)
config.WatchConfig(func(file string) error {
name := filepath.Base(file)
switch name {
case conf:
err := config.ParseConfig()
if err != nil {
if mustOk && config.IsInstalled() {
confi... |
package reaperlog
import (
log "github.com/Sirupsen/logrus"
"github.com/rifflock/lfshook"
"go.mozilla.org/mozlogrus"
)
var config LogConfig
type LogConfig struct {
Extras bool
}
func EnableExtras() {
config.Extras = true
}
func EnableMozlog() {
mozlogrus.Enable("Reaper")
}
func Extras() bool {
return confi... | {
log.Fatalf(format, args...)
} |
package geo
import (
"image/jpeg"
"image/png"
"io"
"github.com/mmcloughlin/globe"
)
type Sphere struct {
*globe.Globe
}
func (s *Sphere) EncodePNG(size int, writer io.Writer) error {
image := s.Image(size)
return png.Encode(writer, image)
}
func (s *Sphere) EncodeJPEG(size int, quality int, writer io.Writ... | {
s := &Sphere{globe.New()}
return s
} |
package cluster
import (
"encoding/base64"
"encoding/json"
"github.com/docker/docker/api/types"
v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
"github.com/rancher/rancher/pkg/settings"
rketypes "github.com/rancher/rke/types"
)
func GetPrivateRepo(cluster *v3.Cluster) *rketypes.P... | {
registry := GetPrivateRepo(cluster)
if registry == nil {
return ""
}
return registry.URL
} |
package stringutil
import (
"strings"
"unicode"
)
func Rstrip(s string) string | {
return strings.TrimRightFunc(s, unicode.IsSpace)
} |
package main
import (
"fmt"
"strconv"
)
func simpleEvalInt(a, b int, op string) int {
switch op {
case "+":
return a + b
case "-":
return a - b
case "/":
return a / b
case "*":
return a * b
case "^":
return power(a, b)
default:
return 0
}
}
func evalPostfixInt(postfix []string) (int, error)... | {
ans := 1
for i := 0; i < b; i++ {
ans = a * ans
}
return ans
} |
package main
import . "g2d"
var screen = Point{480, 360}
var size = Point{20, 20}
type Ball struct {
x, y int
dx, dy int
}
func NewBall(pos Point) *Ball {
return &Ball{pos.X, pos.Y, 5, 5}
}
func (b *Ball) Position() Point {
return Point{b.x, b.y}
}
var b1 = NewBall(Point{40, 80})
var b2 = New... | {
if !(0 <= b.x+b.dx && b.x+b.dx <= screen.X-size.X) {
b.dx = -b.dx
}
if !(0 <= b.y+b.dy && b.y+b.dy <= screen.Y-size.Y) {
b.dy = -b.dy
}
b.x += b.dx
b.y += b.dy
} |
package acquire
import "math/rand"
func countTiles(c *PieceCollection) [BoardHeight][BoardWidth]int {
var tileCount [BoardHeight][BoardWidth]int
for _, p := range c.Pieces {
tileCount[p.Row][p.Col]++
}
return tileCount
}
func _genTestGame() (*Game, *PlayerRandom) {
r := rand.New(rand.NewSource(0))
p1 := Ne... | {
r = rand.New(rand.NewSource(0))
players = []Player{NewPlayerRandom(r)}
return
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.