input stringlengths 24 2.11k | output stringlengths 7 948 |
|---|---|
package reveldi
type Container struct {
services map[string]Service
}
type Service interface{}
func (c *Container) Register(name string, serviceStruct Service) {
if len(c.services) == 0 {
c.services = make(map[string]Service)
}
c.services[name] = serviceStruct
}
func (c *Container) Get(name string) Service... | {
return c.services[name]
} |
package classReader
import "math"
type ConstantIntegerInfo struct {
val int32
}
func (self *ConstantIntegerInfo) readInfo(reader *ClassReader) {
bytes := reader.readUint32()
self.val = int32(bytes)
}
func (self *ConstantIntegerInfo) Value() int32 {
return self.val
}
type ConstantFloatInfo struct {
val float32... | {
bytes := reader.readUint64()
self.val = math.Float64frombits(bytes)
} |
package client
import (
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
)
type SubjectAccessReviewsNamespacer interface {
SubjectAccessReviews(namespace string) SubjectAccessReviewInterface
}
type ClusterSubjectAccessReviews interface {
ClusterSubjectAccessReviews() SubjectAccessReviewInter... | {
result = &authorizationapi.SubjectAccessReviewResponse{}
err = c.r.Post().Resource("subjectAccessReviews").Body(policy).Do().Into(result)
return
} |
package logging
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/http/httputil"
"strings"
)
type transport struct {
name string
transport http.RoundTripper
}
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if IsDebugOrHigher() {
reqData, err := httputil.DumpRequestOut... | {
parts := strings.Split(string(b), "\n")
for i, p := range parts {
if b := []byte(p); json.Valid(b) {
var out bytes.Buffer
json.Indent(&out, b, "", " ")
parts[i] = out.String()
}
}
return strings.Join(parts, "\n")
} |
package common
import (
"strconv"
)
func Atof32(s string) float64 {
f, err := strconv.ParseFloat(s, 32)
if err != nil {
panic(InputErr(err.Error()))
}
return float64(f)
}
func Atoi(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(InputErr(err.Error()))
}
return i
}
func Atob(str st... | {
i, err := strconv.ParseFloat(str, 64)
if err != nil {
panic(InputErr(err.Error()))
}
return i
} |
package s0081
import (
"github.com/peterstace/project-euler/graph"
)
type matrix [][]int
func parameterised(m matrix) interface{} {
g, start, end := matrixToGraph(m)
return g.ShortestPath(start)[end]
}
func matrixToGraph(m matrix) (g graph.WeightedDigraph, start int, end int) {
g = graph.NewOrderZeroWeighted... | {
return parameterised(data)
} |
package run_model
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
type APIPipelineRuntime struct {
PipelineManifest string `json:"pipeline_manifest,omitempty"`
WorkflowManifest string `json:"workflow_manifest,omitempty"`
}
func (m *APIPipelineRuntime) MarshalBinary() ([]... | {
return nil
} |
package btcec
import (
secp "github.com/decred/dcrd/dcrec/secp256k1/v4"
)
type JacobianPoint = secp.JacobianPoint
func MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {
return secp.MakeJacobianPoint(x, y, z)
}
func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {
return secp.Decompr... | {
secp.AddNonConst(p1, p2, result)
} |
package internalversion
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
admissionregistration "k8s.io/kubernetes/pkg/apis/admissionregistration"
)
type ValidatingWebhookConfigurationLister interface {
List(selector labels.Selector) (ret []*admissionr... | {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*admissionregistration.ValidatingWebhookConfiguration))
})
return ret, err
} |
package machinelearningservices
import (
"github.com/Azure/go-autorest/autorest"
)
const (
DefaultBaseURI = "https:management.azure.com"
)
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBa... | {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
} |
package console
import (
"github.com/cgrates/cgrates/apier/v1"
"github.com/cgrates/cgrates/engine"
"github.com/cgrates/cgrates/utils"
)
func init() {
c := &CmdGetDataCost{
name: "datacost",
rpcMethod: "ApierV1.GetDataCost",
clientArgs: []string{"Direction", "Category", "Tenant", "Account", "Subject",... | {
return self.rpcMethod
} |
package app
import (
. "strconv"
"time"
)
type User struct {
Id int64
Nom string
Prenom string
Email string
Password string
CreatedAt time.Time
UpdatedAt time.Time
}
func (u User) Save() {
db.Save(&u)
}
func (u User) Update() {
db.First(&u, &u.Id).Update(&u)
}
func (u User) G... | {
db.Delete(&u)
} |
package internal
import (
. "github.com/signal18/replication-manager/goofys/api/common"
. "gopkg.in/check.v1"
"github.com/jacobsa/fuse"
)
type AwsTest struct {
s3 *S3Backend
}
var _ = Suite(&AwsTest{})
func (s *AwsTest) SetUpSuite(t *C) {
var err error
s.s3, err = NewS3("", &FlagStorage{}, &S3Config{
Regio... | {
s.s3.bucket = "goofys-eu-west-1.signal18/replication-manager.xyz"
err, isAws := s.s3.detectBucketLocationByHEAD()
t.Assert(err, IsNil)
t.Assert(*s.s3.awsConfig.Region, Equals, "eu-west-1")
t.Assert(isAws, Equals, true)
} |
package fake
import (
v1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudscheduler/v1beta1"
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
)
type FakeCloudschedulerV1beta1 struct {
*testing.Fake
}
func (c *FakeCloudschedul... | {
return &FakeCloudSchedulerJobs{c, namespace}
} |
package s2
var (
_ Shape = (*PointVector)(nil)
)
type PointVector []Point
func (p *PointVector) NumEdges() int { return len(*p) }
func (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }
func (p *PointVector) ReferencePoint() ReferencePoint { return O... | { return ChainPosition{e, 0} } |
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.NewListConsoleClient(subscriptionID)
} |
package resources
import "github.com/awslabs/goformation/cloudformation/policies"
type AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {
Attribute string `json:"Attribute,omitempty"`
Name string `json:"Name,omitempty"`
Next string `json:"Next,omitempty"`
RoleArn string `json:"RoleArn,omitempty"`
ThingNa... | {
return r._metadata
} |
package gaerecords
import (
"testing"
)
func TestSetIDAndGetID(t *testing.T) | {
people := CreateTestModel()
person := people.New()
assertEqual(t, NoIDValue, person.ID())
assertEqual(t, person, person.setID(123))
assertEqual(t, int64(123), person.ID())
} |
package test
import (
"io/ioutil"
)
func Fixture(path string) string | {
contents, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
return string(contents)
} |
package ai
import (
"context"
"sync"
)
type Loader func(context.Context) (map[int64]int64, error)
type AI struct {
whites map[int64]int64
sync.RWMutex
}
func New() (a *AI) {
return &AI{
whites: make(map[int64]int64),
}
}
func (a *AI) White(mid int64) (num int64, ok bool) {
a.RLock()
defer a.RUnlock()
nu... | {
var (
whites map[int64]int64
)
if whites, err = loader(c); err != nil {
return
}
a.Lock()
a.whites = whites
a.Unlock()
return
} |
package main
import (
"github.com/nprog/SkyEye/common"
"github.com/nprog/SkyEye/libnet"
"github.com/nprog/SkyEye/log"
"encoding/json"
"sync"
"time"
)
func Test() {
rti := common.NewMachineInfo()
rti.GetInfo()
temp, err := json.Marshal(rti)
if err != nil {
log.Error(err.Error())
return
}
log.Info(st... | {
return &Collection{}
} |
package action
import (
"io/ioutil"
"net/http"
"strings"
"fmt"
)
type Http struct {
config *ActionConfig
}
func (h *Http) genResult(resp *http.Response) (*Result, error) {
data := make(map[string]interface{})
data["status-code"] = resp.StatusCode
data["headers"] = resp.Header
h.config.Log.Infof("%s %s ->... | {
url := h.config.Params.GetString("url")
if url == "" {
return nil, fmt.Errorf("url parameter required")
}
method := h.config.Params.GetString("method")
if method == "" {
method = "GET"
} else {
method = strings.ToUpper(method)
}
client := &http.Client{}
h.config.Log.Debugf("%s %s", method, url)
re... |
package v1
type ConfigMapProjectionApplyConfiguration struct {
LocalObjectReferenceApplyConfiguration `json:",inline"`
Items []KeyToPathApplyConfiguration `json:"items,omitempty"`
Optional *bool `json:"optional,omitempty"`
}
... | {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithItems")
}
b.Items = append(b.Items, *values[i])
}
return b
} |
package credentials
import (
"strings"
"github.com/docker/docker/cliconfig/configfile"
"github.com/docker/engine-api/types"
)
type fileStore struct {
file *configfile.ConfigFile
}
func NewFileStore(file *configfile.ConfigFile) Store {
return &fileStore{
file: file,
}
}
func (c *fileStore) Erase(serverA... | {
stripped := url
if strings.HasPrefix(url, "http://") {
stripped = strings.Replace(url, "http://", "", 1)
} else if strings.HasPrefix(url, "https://") {
stripped = strings.Replace(url, "https://", "", 1)
}
nameParts := strings.SplitN(stripped, "/", 2)
return nameParts[0]
} |
package spnego
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
"github.com/apcera/gssapi"
)
func CheckSPNEGONegotiate(lib *gssapi.Lib, h http.Header, name string) (present bool, token *gssapi.Buffer) {
var err error
defer func() {
if err != nil {
lib.Debug(fmt.Sprintf("CheckSPNEGONegotiate: %... | {
if name == "" {
return
}
v := "Negotiate"
if token.Length() != 0 {
data := token.Bytes()
v = v + " " + base64.StdEncoding.EncodeToString(data)
}
h.Set(name, v)
} |
package resources
import "github.com/awslabs/goformation/cloudformation/policies"
type AWSBatchJobDefinition_NodeRangeProperty struct {
Container *AWSBatchJobDefinition_ContainerProperties `json:"Container,omitempty"`
TargetNodes string `json:"TargetNodes,omitempty"`
_deletionPolicy policies.DeletionPolicy
... | {
r._metadata = metadata
} |
package versioned
import (
"fmt"
securityv1 "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
... | {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
if configShallowCopy.Burst <= 0 {
return nil, fmt.Errorf("Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
}
configShallowCopy.RateLimiter = flowcontrol.NewTok... |
package validation
import (
"testing"
"time"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
)
func TestWaitForNodeToBeReady(t *testing.T) {
conditions := []v1.NodeCondition{{Type: "Ready", Status: "True"}}
nodeName := "node-foo"
nodeAA := setupNo... | {
conditions := []v1.NodeCondition{{Type: "Ready", Status: "False"}}
nodeName := "node-foo"
nodeAA := setupNodeAA(t, conditions, nodeName)
test, err := nodeAA.WaitForNodeToBeNotReady(nodeName)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if test != true {
t.Fatalf("unexpected error WaitForNodeToB... |
package api
type FormatsResponse struct {
Formats []string `json:"formats"`
}
func (a *API) getFormats(ctx *context) {
ctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})
}
type LeechTypesResponse struct {
LeechTypes []string `json:"leech_types"`
}
type MediaResponse struct {
Media []string `json:"media... | {
ctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})
} |
package platform
var IsPartnerBuild = true
func GuessMimeTypeByBuffer(buf []byte) (mimeType string, err error) {
return "mime type disabled", nil
}
func GuessMimeType(absPath string) (mimeType string, err error) | {
return "mime type disabled", nil
} |
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/common"
)
type UpdateComputeImageCapabilitySchemaDetails struct {
DisplayName *string `mandatory:"false" json:"displayName"`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
SchemaData map[string]ImageCapabilitySchemaDe... | {
return common.PointerString(m)
} |
package clipboard
import (
"time"
)
type Duration struct {
time.Duration
}
func (d Duration) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}
func (d *Duration) UnmarshalText(text []byte) error | {
var err error
d.Duration, err = time.ParseDuration(string(text))
return err
} |
package main
import (
"fmt"
"strings"
)
type talker interface {
talk() string
}
func shout(t talker) {
louder := strings.ToUpper(t.talk())
fmt.Println(louder)
}
type laser int
type rover string
func (r rover) talk() string {
return string(r)
}
func main() {
r := rover("whir whir")
shout(r)
}
func (l l... | {
return strings.Repeat("toot ", int(l))
} |
package caller
import (
"fmt"
"path/filepath"
"regexp"
"testing"
)
func TestCallResolver(t *testing.T) {
cr := NewCallResolver(0, regexp.MustCompile(`resolver_test\.go.*$`))
for i := 0; i < 2; i++ {
if l := len(cr.cache); l != i {
t.Fatalf("cache has %d entries, expected %d", l, i)
}
file, _, fun := fu... | {
defer func() { defaultCallResolver.cache = map[uintptr]*cachedLookup{} }()
for i := 0; i < 2; i++ {
if l := len(defaultCallResolver.cache); l != i {
t.Fatalf("cache has %d entries, expected %d", l, i)
}
file, _, fun := Lookup(0)
if fun != "TestDefaultCallResolver" {
t.Fatalf("unexpected caller report... |
package resistor
func Rpara(resists ...float64) (Rtotal float64) {
for _, r := range resists {
Rtotal = Rtotal + recip(r)
}
return
}
func Rser(resists ...float64) (Rtotal float64) | {
for _, r := range resists {
Rtotal = Rtotal + r
}
return
} |
package routers
import (
"code.google.com/p/go.crypto/bcrypt"
"github.com/codegangsta/martini-contrib/render"
"github.com/martini-contrib/sessions"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"net/http"
)
func AdminUpdatePassword(req *http.Request, r render.Render, db *mgo.Database) {
pass := req.FormValue("p... | {
r.HTML(200, "admin/password", map[string]interface{}{
"IsPassword": true}, render.HTMLOptions{Layout: "admin/layout"})
} |
package main
import (
"fmt"
"os"
"go.pedge.io/dockerplugin"
"go.pedge.io/dockervolume"
)
func main() {
if err := do(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
os.Exit(0)
}
func do() error | {
return dockervolume.NewTCPServer(
newVolumeDriver("/tmp/dockervolume-example-mount"),
"dockervolume-example",
":6789",
dockerplugin.ServerOptions{},
).Serve()
} |
package sysstats
import (
"os/exec"
"strconv"
"strings"
)
type LoadAvg map[string]float64
func getLoadAvg() (loadAvg LoadAvg, err error) | {
out, err := exec.Command(`sysctl`, `-n`, `vm.loadavg`).Output()
if err != nil {
return nil, err
}
loadAvg = LoadAvg{}
fields := strings.Fields(string(out))
for i := 1; i < 4; i++ {
load, err := strconv.ParseFloat(fields[i], 64)
if err != nil {
return nil, err
}
switch i {
case 1:
loadAvg[`avg... |
package kusto
import (
"github.com/Azure/go-autorest/autorest"
)
const (
DefaultBaseURI = "https:management.azure.com"
)
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptio... | {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
} |
package helpers
import (
"bytes"
"errors"
"runtime"
)
func BytesToUint16(field [2]byte) uint16 {
return uint16(field[0])<<8 | uint16(field[1])
}
func Uint16ToBytes(value uint16) [2]byte {
byte0 := byte(value >> 8)
byte1 := byte(0x00ff & value)
return [2]byte{byte0, byte1}
}
func GetBytes(b *byte... | {
byte, err := b.ReadByte()
if err != nil {
panic(errors.New("Unexpected end of data"))
}
return byte
} |
package main
import (
"fmt"
)
type Player struct {
ID string
Name string
Health int
Hunger int
CriticalHunger bool
NextAction int
Dead bool
}
func NewPlayer(ID, name string) *Player {
return &Player{ID, name, 100, 0, false, 0, false}
}
func (p *Player) ... | {
p.Health += amount
if p.Health > 100 {
p.Health = 100
}
if p.Health <= 0 {
p.Health = 0
p.Dead = true
return true
}
return false
} |
package reports
import (
"time"
"github.com/rafaeljusto/druns/core/db"
)
type Service struct {
sqler db.SQLer
}
func (s Service) IncomingPerGroup(month time.Time, classValue float64) ([]Incoming, error) {
dao := newDAO(s.sqler)
return dao.incomingPerGroup(month, classValue)
}
func NewService(sqler db.SQLer)... | {
return Service{sqler}
} |
package udt
import (
"io"
)
type ack2Packet struct {
h header
ackSeqNo uint32
}
func (p *ack2Packet) sendTime() (ts uint32) {
return p.h.ts
}
func (p *ack2Packet) writeTo(w io.Writer) (err error) {
if err := p.h.writeTo(w, ack2, p.ackSeqNo); err != nil {
return err
}
return
}
func (p *ack2Pack... | {
return p.h.dstSockId
} |
package types
import (
"net"
)
type IPv4 [4]byte
func (v4 IPv4) String() string {
return v4.IP().String()
}
func (v4 *IPv4) DeepCopyInto(out *IPv4) {
copy(out[:], v4[:])
return
}
func (v4 IPv4) IP() net.IP | {
return v4[:]
} |
package event
import (
"fmt"
"sync/atomic"
"time"
)
type Increment struct {
Name string
Value int64
}
func (e *Increment) StatClass() string {
return "counter"
}
func (e *Increment) Update(e2 Event) error {
if e.Type() != e2.Type() {
return fmt.Errorf("statsd event type conflict: %s vs %s ", e.String(),... | {
return e.Name
} |
package atc
import (
"errors"
multierror "github.com/hashicorp/go-multierror"
)
type AuthFlags struct {
NoAuth bool `long:"no-really-i-dont-want-any-auth" description:"Ignore warnings about not configuring auth"`
BasicAuth BasicAuthFlag `group:"Basic Authentication" namespace:"basic-auth"`
}
type BasicAuthFlag... | {
var errs *multierror.Error
if auth.Username == "" {
errs = multierror.Append(
errs,
errors.New("must specify --basic-auth-username to use basic auth."),
)
}
if auth.Password == "" {
errs = multierror.Append(
errs,
errors.New("must specify --basic-auth-password to use basic auth."),
)
}
retur... |
package cmd
type readDirOpts struct {
count int
followDirSymlink bool
}
func readDir(dirPath string) (entries []string, err error) {
return readDirWithOpts(dirPath, readDirOpts{count: -1})
}
func readDirN(dirPath string, count int) (entries []string, err error) | {
return readDirWithOpts(dirPath, readDirOpts{count: count})
} |
package v1
import (
common "github.com/kubeflow/common/pkg/apis/common/v1"
"k8s.io/apimachinery/pkg/runtime"
)
func Int32(v int32) *int32 {
return &v
}
func addDefaultingFuncs(scheme *runtime.Scheme) error {
return RegisterDefaults(scheme)
}
func setDefaultsTypeLauncher(spec *common.ReplicaSpec) {
if spec !... | {
if spec != nil && spec.RestartPolicy == "" {
spec.RestartPolicy = DefaultRestartPolicy
}
} |
package problems
import "fmt"
func partitionDfs(data []byte, i int, buf *[]string, out *[][]string) {
if i == len(data) {
m := make([]string, len(*buf))
copy(m, *buf)
*out = append(*out, m)
return
}
var isPalindrome func (data []byte, s int, e int) bool
isPalindrome = func (data []byte, s int, e int) boo... | {
fmt.Printf("<131> ")
fmt.Println(partition("aabc"))
} |
package queue
import "context"
type Client struct {
Content []byte
err error
}
func (c *Client) Push(ctx context.Context, content []byte) error {
if c.err != nil {
return c.err
}
c.Content = content
return nil
}
func NewClient(options ...func(*Client)) *Client {
c := &Client{}
for _, option := ran... | {
return func(c *Client) {
c.err = err
}
} |
package goku
import (
"runtime"
"testing"
"time"
)
type TestReader struct{}
func (self TestReader) Read() ([]Message, error) {
time.Sleep(10 * time.Millisecond)
return []Message{"Hello"}, nil
}
type TestWriter struct {
msgs []Message
}
func TestNewQueueSetupReader(t *testing.T) {
t.Parallel()
q := NewQu... | {
for _, msg := range msgs {
self.msgs = append(self.msgs, msg)
}
return nil
} |
package externalversions
import (
"fmt"
schema "k8s.io/apimachinery/pkg/runtime/schema"
cache "k8s.io/client-go/tools/cache"
v1beta1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1"
)
type GenericInformer interface {
Informer() cache.SharedIndexInformer
Lister() cache.GenericLister
}
type genericIn... | {
return f.informer
} |
package parse
import (
"strings"
)
func indent(s string, character string, size int) string {
indent := strings.Repeat(character, size)
lines := strings.Split(s, newLine)
for k, v := range lines {
if len(v) > 0 {
lines[k] = indent + v
}
}
return strings.Join(lines, newLine)
}
func EqualSlicesFoldPref... | {
if len(a) == 0 && len(b) == 0 {
return true
}
for k := range b {
if EqualSlicesFold(a, b[k]) {
return true
}
}
return false
} |
package main
import (
"fmt"
"os"
"sort"
)
func main() {
in, _ := os.Open("11455.in")
defer in.Close()
out, _ := os.Create("11455.out")
defer out.Close()
var kase int
sides := make([]int, 4)
for fmt.Fscanf(in, "%d", &kase); kase > 0; kase-- {
fmt.Fscanf(in, "%d%d%d%d", &sides[0], &sides[1], &sides[2], &... | {
sort.Ints(sides)
if sides[0] == sides[1] && sides[2] == sides[3] {
if sides[1] == sides[2] {
return "square"
}
return "rectangle"
}
if sides[3] > sides[0]+sides[1]+sides[2] {
return "banana"
}
return "quadrangle"
} |
package route
import (
"io"
"net/http"
"regexp"
"strings"
)
var ()
type Route struct {
Path string
System int
S0 NullRoute
S1 StringRoute
S2 ControllerRoute
S3 FilesystemRoute
S4 FunctionRoute
}
func NewRoute(path string, system int) Route {
return Route{path, system, NullRoute{}... | {
routeStringRegexp := `^\/([a-zA-Z0-9](\/)*)*\s(null|str .*|fs .*)$`
r, _ := regexp.Compile(routeStringRegexp)
if r.MatchString(str) {
return true
}
return false
} |
package project
import (
"testing"
)
func TestTrimSpaceAndNonPrintable_space(t *testing.T) {
t.Parallel()
extraChars := " state \r\t"
want := "state"
got := TrimSpaceAndNonPrintable(extraChars)
if want != got {
t.Fatalf("wrong trim, want: %q got: %q", want, got)
}
}
func TestTrimSpace_unicode(t *testin... | {
t.Parallel()
extraChars := "state\uFEFF"
want := "state"
got := TrimSpaceAndNonPrintable(extraChars)
if want != got {
t.Fatalf("wrong trim, want: %q got: %q", want, got)
}
} |
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
type threadSafePrintliner struct {
l sync.Mutex
w io.Writer
}
func newThreadSafePrintliner(w io.Writer) *threadSafePrintliner {
return &threadSafePrintliner{w: w}
}
func (p *threadSafePrintliner) println... | {
var r = make([]string, 0)
for _, str := range s {
if str != "" {
r = append(r, str)
}
}
return r
} |
package http
import (
"go-common/app/admin/main/tv/model"
bm "go-common/library/net/http/blademaster"
)
func mangoList(c *bm.Context) {
c.JSON(tvSrv.MangoList(c))
}
func mangoAdd(c *bm.Context) {
param := new(struct {
IDs []int64 `form:"rids,split" validate:"required,min=1,dive,gt=0"`
RType int `form:"... | {
param := new(struct {
ID int64 `form:"id" validate:"required,min=1,gt=0"`
})
if err := c.Bind(param); err != nil {
return
}
c.JSON(nil, tvSrv.MangoDel(c, param.ID))
} |
package containerregistry
import (
"context"
"github.com/sacloud/libsacloud/v2/helper/service"
"github.com/sacloud/libsacloud/v2/sacloud"
)
func (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error {
if err := req.Validate(); err != nil {
return err
}
client := sacloud.NewContaine... | {
return s.DeleteWithContext(context.Background(), req)
} |
package global
import (
"fmt"
)
const (
versionMajor = 0
versionMinor = 0
versionPatch = 8
)
func Version() string | {
return fmt.Sprintf("tgen v%d.%d.%d", versionMajor, versionMinor, versionPatch)
} |
package gofixedfield
import (
"io/ioutil"
"strings"
)
const (
EOLUnix = "\n"
EOLMac = "\r"
EOLDOS = "\r\n"
)
var DecimalComma bool
func RecordsFromFile(filename string, eolstyle string) ([]string, error) | {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return strings.Split(string(data), eolstyle), nil
} |
package heckle
import (
"log"
"strings"
"github.com/ianremmler/bort"
)
var (
retorts = retortMap{}
)
type retortMap map[string]string
func setup() error {
if err := bort.GetConfig(&struct{ Retorts retortMap }{retorts}); err != nil {
return err
}
for watch, retort := range retorts {
if _, err := bort.R... | {
return func(in, out *bort.Message) error {
out.Type = bort.PrivMsg
out.Text = strings.Replace(retort, "%m", in.Match, -1)
return nil
}
} |
package opt
import (
"encoding/json"
"reflect"
)
type DisableTypoToleranceOnAttributesOption struct {
value []string
}
func DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption {
return &DisableTypoToleranceOnAttributesOption{v}
}
func (o *DisableTypoToleranceOnAttributesOpt... | {
if string(data) == "null" {
o.value = []string{}
return nil
}
return json.Unmarshal(data, &o.value)
} |
package internal
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error | {
return errors.New(values...).Path("Transport", "Internet", "Internal")
} |
package contract
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
func sha3(in ...[]byte) []byte {
out := make([]byte, len(in)*32)
for i, input := range in {
copy(out[i*32:i*32+32], common.LeftPadBytes(input, 32))
}
return crypto.Sha3(out)
}
func makeChannelNa... | {
return sha3(from[:], to[:])
} |
package fritz
import (
"unicode/utf16"
"unicode/utf8"
)
func utf8To16LE(p []byte) []byte {
bs := make([]byte, 0, 2*len(p))
pos := 0
for pos < len(p) {
bytes, size := consumeNextRune(p[pos:])
pos += size
bs = append(bs, bytes...)
}
return bs
}
func consumeNextRune(p []byte) ([]byte, int) | {
r, size := utf8.DecodeRune(p)
if r <= 0xffff {
return []byte{uint8(r), uint8(r >> 8)}, size
}
r1, r2 := utf16.EncodeRune(r)
return []byte{uint8(r1), uint8(r1 >> 8), uint8(r2), uint8(r2 >> 8)}, size
} |
package main
import . "g2d"
var arena = NewArena(Point{480, 360})
var a1 = NewAlien(arena, Point{40, 40})
var a2 = NewAlien(arena, Point{80, 80})
type Alien struct {
arena *Arena
x, y, w, h int
xmin, xmax int
dx, dy int
}
func NewAlien(arena *Arena, pos Point) *Alien {
a := &Alien{arena... | {
return Point{a.w, a.h}
} |
package internal
import (
"fmt"
"net/http"
"golang.org/x/net/context"
)
type ContextKey string
const userAgent = "gcloud-golang/0.1"
type Transport struct {
Base http.RoundTripper
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
req = cloneRequest(req)
ua := req.Header.Get... | {
r2 := new(http.Request)
*r2 = *r
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
} |
package logging_test
import (
"cloud.google.com/go/logging/apiv2"
"golang.org/x/net/context"
loggingpb "google.golang.org/genproto/googleapis/logging/v2"
)
func ExampleNewConfigClient() {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
_ = c
}
func ExampleConfigClient_G... | {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
req := &loggingpb.ListSinksRequest{
}
it := c.ListSinks(ctx, req)
for {
resp, err := it.Next()
if err != nil {
break
}
_ = resp
}
} |
package middleware
import (
"time"
log "github.com/Sirupsen/logrus"
"gopkg.in/macaron.v1"
"github.com/containerops/configure"
)
func logger() macaron.Handler | {
return func(ctx *macaron.Context) {
if configure.GetString("runmode") == "dev" {
log.Info("------------------------------------------------------------------------------")
log.Info(time.Now().String())
}
log.WithFields(log.Fields{
"Method": ctx.Req.Method,
"URL": ctx.Req.RequestURI,
}).Info(c... |
package authorization
import (
"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
)
const (
APIVersion = "2015-01-01"
DefaultBaseURI = "https:management.azure.com"
)
type ManagementClient struct {
autorest.Client
BaseURI string
Subscriptio... | {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
} |
package http_handlers
import (
"fmt"
"github.com/go-martini/martini"
"net/http"
)
func GetCaches() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return HttpHandler(
[]string{
AUTH_REQUIRED,
},
func(h *Http) {
h.SetResponse(
h.session.Caches,
)
},
)
}
f... | {
return HttpHandler(
[]string{
AUTH_REQUIRED,
CACHE_REQUIRED,
},
func(h *Http) {
if c := h.session.GetCache(
h.vars["cache_id"],
); c != nil {
h.SetResponse(
c,
)
} else {
h.AddError(
fmt.Errorf(
`Cache not found`,
),
404,
)
}
},
)
} |
package pointer
import "time"
func DefaultBool(value *bool, defaultValue bool) *bool {
if value == nil {
return &defaultValue
}
return value
}
func DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {
if value == nil {
return &defaultValue
}
return value
}
func DefaultFloat64... | {
if value == nil {
return &defaultValue
}
return value
} |
package ratelimiter
import "time"
var domainLimitMap = make(map[string]*Limiter)
type Limiter struct {
nextChan chan bool
apiLimit time.Duration
}
func New(domain string, apiLimit time.Duration) *Limiter {
if _, ok := domainLimitMap[domain]; !ok {
domainLimitMap[domain] = &Limiter{
nextChan: make(chan boo... | {
go func(l *Limiter) {
ticker := time.NewTimer(l.apiLimit)
<-ticker.C
ticker.Stop()
l.nextChan <- true
}(limiter)
} |
package cfsb
import (
"fmt"
"github.com/wayneeseguin/rdpg-agent/log"
"github.com/wayneeseguin/rdpg-agent/rdpg"
)
type PlanDetails struct {
Cost string `json:"cost"`
Bullets []map[string]string `json:"bullets"`
DisplayName string `json:"displayname"`
}
type Plan struct {
I... | {
r := rdpg.New()
r.OpenDB("rdpg")
plan = &Plan{}
sq := `SELECT id,name,description FROM cfsb.plans WHERE id=$1 LIMIT 1;`
err = r.DB.Get(&plan, sq, planId)
if err != nil {
log.Error(fmt.Sprintf("cfsb.FindPlan(%s) %s", planId, err))
}
r.DB.Close()
return plan, err
} |
package models
import (
"testing"
"github.com/golib/assert"
uuid "github.com/satori/go.uuid"
)
func Test_NewUserModel(t *testing.T) {
assertion := assert.New(t)
var (
username = uuid.NewV4().String()
email = "tes1@test.com"
password = uuid.NewV4().String()
desc = uuid.NewV4().String()
)
user ... | {
assertion := assert.New(t)
var (
username = uuid.NewV4().String()
email = "test3@test.com"
password = uuid.NewV4().String()
desc = uuid.NewV4().String()
)
user := User.NewUserModel(username, email, password, desc)
err := user.Save()
assertion.Nil(err)
userNew, err := User.FindByUsername(usern... |
package openstacktasks
import (
"encoding/json"
"k8s.io/kops/upup/pkg/fi"
)
type realFloatingIP FloatingIP
func (o *FloatingIP) UnmarshalJSON(data []byte) error {
var jsonName string
if err := json.Unmarshal(data, &jsonName); err == nil {
o.Name = &jsonName
return nil
}
var r realFloatingIP
if err :... | {
return o.Lifecycle
} |
package timeseriesinsights
import (
"github.com/Azure/go-autorest/autorest"
)
const (
DefaultBaseURI = "https:management.azure.com"
)
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(Def... | {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
} |
package qr
import (
"github.com/m3o/m3o-go/client"
)
type QrService struct {
client *client.Client
}
func (t *QrService) Generate(request *GenerateRequest) (*GenerateResponse, error) {
rsp := &GenerateResponse{}
return rsp, t.client.Call("qr", "Generate", request, rsp)
}
type GenerateRequest struct {
Size i... | {
return &QrService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
} |
package logutils
import (
"github.com/stretchr/testify/mock"
)
type MockLog struct {
mock.Mock
}
func NewMockLog() *MockLog {
return &MockLog{}
}
func (m *MockLog) Fatalf(format string, args ...interface{}) {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
}
func (m *MockLog) Panicf(format ... | {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
} |
package libra
import (
"bytes"
"fmt"
"io"
)
type validator struct {
name string
program
stdin io.Reader
}
func (v validator) Name() string {
return v.name
}
func (v validator) Run() Status {
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
v.program.cmd.Stdin = v.stdin
v.program.cmd.Stdout = stdou... | {
ret := make([]Task, len(job.inputs))
for i, v := range job.inputs {
prog, _ := newProgram(job.src.Exec)
ret[i] = validator{name: v.Name(), program: prog, stdin: v.Reader()}
}
return ret
} |
package example
import (
"testing"
"github.com/remogatto/prettytest"
"launchpad.net/gocheck"
)
type testSuite struct {
prettytest.Suite
}
func (t *testSuite) TestTrueIsTrue() {
t.True(true)
}
func (t *testSuite) TestEquality() {
t.Equal("awesome", "awesome")
}
func (t *testSuite) TestNot() {
t.Not(... | {
prettytest.Run(
t,
new(testSuite),
)
} |
package config
import (
"encoding/xml"
)
type defXMLReader struct {
opts ReaderOptions
}
func NewXMLReader(opts ...ReaderOptionFunc) Reader {
r := &defXMLReader{}
for _, o := range opts {
o(&r.opts)
}
return r
}
func (p *defXMLReader) Read(model interface{}) error {
data, err := ReadXMLFile(p.opts.filenam... | {
return xml.Marshal(v)
} |
package worker
import (
"github.com/stitchfix/flotilla-os/config"
"os"
"testing"
"time"
)
func TestGetPollInterval(t *testing.T) | {
conf, _ := config.NewConfig(nil)
expected := time.Duration(500) * time.Millisecond
os.Setenv("WORKER_RETRY_INTERVAL", "500ms")
interval, err := GetPollInterval("retry", conf)
if err != nil {
t.Errorf(err.Error())
}
if interval != expected {
t.Errorf("Expected interval: [%v] but was [%v]", expected, inte... |
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 personChanges Changes
optionsString := getOptionsString(options, changeOptions)
uri := fmt.Sprintf("%s/person/changes?api_key=%s%s", baseURL, tmdb.apiKey, optionsString)
result, err := getTmdb(uri, &personChanges)
return result.(*Changes), err
} |
package fgae
import(
"golang.org/x/net/context"
"github.com/skypies/util/gcp/ds"
fdb "github.com/skypies/flightdb"
)
type FlightIterator ds.Iterator
func NewFlightIterator(ctx context.Context, p ds.DatastoreProvider, fq *FQuery) *FlightIterator {
it := ds.NewIterator(ctx, p, (*ds.Query)(fq), fdb.IndexedFlightBl... | {
it := (*ds.Iterator)(fi)
return it.Iterate(ctx)
} |
package check
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCompare(t *testing.T) {
assert := assert.New(t)
set1 := make(stringSet)
set1.add("bar")
set1.add("foo")
set2 := make(stringSet)
set2.add("foo")
set2.add("bar")
set3 := make(stringSet)
set3.add("foo")
set3.add("baz")
ass... | {
assert := assert.New(t)
set := make(stringSet)
set.add("bar")
set.add("xx")
set.add("foo")
assert.Equal("bar, foo, xx", set.String())
} |
package gocleanup
import (
"os"
"os/signal"
"syscall"
)
var cleanupFuncs []func()
var capturingSignals bool
func Register(f func()) {
cleanupFuncs = append(cleanupFuncs, f)
if !capturingSignals {
capturingSignals = true
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, sysc... | {
for _, f := range cleanupFuncs {
f()
}
cleanupFuncs = []func(){}
} |
package goque
import (
"bytes"
"encoding/binary"
"encoding/gob"
)
type Item struct {
ID uint64
Key []byte
Value []byte
}
func (i *Item) ToString() string {
return string(i.Value)
}
type PriorityItem struct {
ID uint64
Priority uint8
Key []byte
Value []byte
}
func (pi *Prio... | {
buffer := bytes.NewBuffer(i.Value)
dec := gob.NewDecoder(buffer)
return dec.Decode(value)
} |
package token_test
import (
"testing"
"github.com/hyperledger/fabric/core/handlers/validation/token"
"github.com/stretchr/testify/assert"
)
func TestValidation_Validate(t *testing.T) {
factory := &token.ValidationFactory{}
plugin := factory.New()
err := plugin.Init()
assert.NoError(t, err)
err = plugin.V... | {
factory := &token.ValidationFactory{}
plugin := factory.New()
assert.NotNil(t, plugin)
} |
package client
import (
"fmt"
"strings"
"golang.org/x/net/context"
Cli "github.com/docker/docker/cli"
flag "github.com/docker/docker/pkg/mflag"
)
func (cli *DockerCli) CmdWait(args ...string) error | {
cmd := Cli.Subcmd("wait", []string{"CONTAINER [CONTAINER...]"}, Cli.DockerCommands["wait"].Description, true)
cmd.Require(flag.Min, 1)
cmd.ParseFlags(args, true)
var errs []string
for _, name := range cmd.Args() {
status, err := cli.client.ContainerWait(context.Background(), name)
if err != nil {
errs =... |
package window_test
import (
"fmt"
"time"
"github.com/kurin/blazer/x/window"
)
type Accumulator struct {
w *window.Window
}
func (a Accumulator) Add(s string) {
a.w.Insert([]string{s})
}
func (a Accumulator) All() []string {
v := a.w.Reduce()
return v.([]string)
}
func NewAccum(size time.Duration) Accumula... | {
a := NewAccum(time.Minute)
a.Add("this")
a.Add("is")
a.Add("that")
fmt.Printf("total: %v\n", a.All())
} |
package utils
import (
"golang.org/x/crypto/ssh"
)
type SshClient interface {
Close() error
ExecCommand(command string) (string, error)
}
type awsSshClient struct {
client *ssh.Client
}
func GetSshClient(username string, privateKey []byte, ip string) (*awsSshClient, error) {
signer, err := ssh.ParsePrivateKey(... | {
session, err := sshClient.client.NewSession()
if err != nil {
}
defer session.Close()
output, err := session.Output(command)
return string(output), err
} |
package result
type Classic struct {
id int
fitness float64
err error
stop bool
}
func (r Classic) ID() int { return r.id }
func (r Classic) Fitness() float64 { return r.fitness }
func (r Classic) Err() error { return r.err }
func (r Classic) Stop() bool { return r.stop }
func New(id int, fi... | {
return Classic{id, fitness, err, stop}
} |
package endpoints
import (
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
)
func (e *Endpoints) Up(config *Config) error {
return e.up(config)
}
func (e *Endpoints) DevLxdSocketPath() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[devlxd]
return listener.Addr().String()
}
f... | {
return &Endpoints{
systemdListenFDsStart: util.SystemdListenFDsStart,
}
} |
package rule
import (
"go/ast"
"github.com/mgechev/revive/lint"
)
type NestedStructs struct{}
func (r *NestedStructs) Name() string {
return "nested-structs"
}
type lintNestedStructs struct {
fileAST *ast.File
onFailure func(lint.Failure)
}
func (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor {
... | {
var failures []lint.Failure
if len(arguments) > 0 {
panic(r.Name() + " doesn't take any arguments")
}
walker := &lintNestedStructs{
fileAST: file.AST,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, file.AST)
return failures
} |
package clock
import "time"
var Work Clock
func init() {
Work = New()
}
func Now() time.Time {
return Work.Now()
}
func Since(t time.Time) time.Duration {
return Work.Now().Sub(t)
}
func After(d time.Duration) <-chan time.Time {
return Work.After(d)
}
func Tick(d time.Duration) <-chan time.Time {
... | {
Work.Sleep(d)
} |
package main
import "fmt"
const (
a = iota
b
c
d
e
)
var x = []int{1, 2, 3}
func f(x int, len *byte) {
*len = byte(x)
}
func whatis1(x interface{}) string {
xx := x
switch xx.(type) {
default:
return fmt.Sprint("default ", xx)
case int, int8, int16, int32:
return fmt.Sprint("signed ", xx)
case int... | {
switch xx := x.(type) {
default:
return fmt.Sprint("default ", xx)
case int, int8, int16, int32:
return fmt.Sprint("signed ", xx)
case int64:
return fmt.Sprint("signed64 ", int64(xx))
case uint, uint8, uint16, uint32:
return fmt.Sprint("unsigned ", xx)
case uint64:
return fmt.Sprint("unsigned64 ", uin... |
package models
import (
"github.com/go-swagger/go-swagger/errors"
"github.com/go-swagger/go-swagger/strfmt"
"github.com/go-swagger/go-swagger/swag"
)
type NotificationPageableResult struct {
Content []*Notification `json:"content,omitempty"`
First bool `json:"first,omitempty"`
Last bool `json:"last,omite... | {
if swag.IsZero(m.Content) {
return nil
}
for i := 0; i < len(m.Content); i++ {
if m.Content[i] != nil {
if err := m.Content[i].Validate(formats); err != nil {
return err
}
}
}
return nil
} |
package fileinterface
import (
"testing"
"errors"
)
func TestDelete(t *testing.T) {
err := Delete("dummyfile")
if err != nil {
t.Error(err)
}
}
func TestOpen(t *testing.T) {
if f, err := Open("sample.database"); err != nil {
t.Error(err)
} else if err = Close(f); err != nil {
t.Error(err)
}
}
fu... | {
var f FID
var err error
if f, err = Create("dummyfile"); err != nil {
t.Error(err)
} else {
if err = Close(f); err != nil {
t.Error(err)
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.