input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package augeas
import "C"
import (
"fmt"
)
type ErrorCode int
const (
CouldNotInitialize ErrorCode = -2
NoMatch = -1
NoError = 0
ENOMEM
EINTERNAL
EPATHX
ENOMATCH
EMMATCH
ESYNTAX
ENOLENS
EMXFM
ENOSPAN
EMVDESC
ECMDRUN
EBADARG
)
type Error struct {
Code ErrorCode
Message string
MinorMessage string
Details string
}
func (err Error) Error() string {
return fmt.Sprintf("Message: %s - Minor message: %s - Details: %s",
err.Message, err.MinorMessage, err.Details)
}
func (a Augeas) error() error {
code := a.errorCode()
if code == NoError {
return nil
}
return Error{code, a.errorMessage(), a.errorMinorMessage(), a.errorDetails()}
}
func (a Augeas) errorCode() ErrorCode {
return ErrorCode(C.aug_error(a.handle))
}
func (a Augeas) errorMessage() string {
return C.GoString(C.aug_error_message(a.handle))
}
func (a Augeas) errorMinorMessage() string {
return C.GoString(C.aug_error_minor_message(a.handle))
}
func (a Augeas) errorDetails() string | {
return C.GoString(C.aug_error_details(a.handle))
} |
package circleci
import (
"log"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRecentBuilds(t *testing.T) | {
c := setup()
builds := c.RecentBuilds("ryanlower", "go-circleci")
log.Print(builds)
lastBuild := builds[0]
assert.Equal(t, lastBuild.Branch, "master")
assert.Equal(t, lastBuild.Status, "running")
} |
package names
import "knative.dev/pkg/kmeta"
func Deployment(rev kmeta.Accessor) string {
return kmeta.ChildName(rev.GetName(), "-deployment")
}
func ImageCache(rev kmeta.Accessor) string {
return kmeta.ChildName(rev.GetName(), "-cache")
}
func PA(rev kmeta.Accessor) string | {
return rev.GetName()
} |
package dataflow
import (
"context"
"strconv"
"time"
"go-common/app/interface/main/app-interface/conf"
"go-common/library/log"
"go-common/library/log/infoc"
)
type Service struct {
c *conf.Config
infoc *infoc.Infoc
}
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
infoc: infoc.New(c.Infoc),
}
return
}
func (s *Service) Report(c context.Context, eventID, eventType, buvid, fts, messageInfo string, now time.Time) (err error) | {
if err = s.infoc.Info(strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo); err != nil {
log.Error("s.infoc2.Info(%v,%v,%v,%v,%v,%v) error(%v)", strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo, err)
}
return
} |
package http
import (
"net/url"
"os"
"testing"
)
var cacheKeysTests = []struct {
proxy string
scheme string
addr string
key string
}{
{"", "http", "foo.com", "|http|foo.com"},
{"", "https", "foo.com", "|https|foo.com"},
{"http://foo.com", "http", "foo.com", "http://foo.com|http|"},
{"http://foo.com", "https", "foo.com", "http://foo.com|https|foo.com"},
}
func ResetProxyEnv() {
for _, v := range []string{"HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy", "REQUEST_METHOD"} {
os.Unsetenv(v)
}
ResetCachedEnvironment()
}
func TestCacheKeys(t *testing.T) | {
for _, tt := range cacheKeysTests {
var proxy *url.URL
if tt.proxy != "" {
u, err := url.Parse(tt.proxy)
if err != nil {
t.Fatal(err)
}
proxy = u
}
cm := connectMethod{proxyURL: proxy, targetScheme: tt.scheme, targetAddr: tt.addr}
if got := cm.key().String(); got != tt.key {
t.Fatalf("{%q, %q, %q} cache key = %q; want %q", tt.proxy, tt.scheme, tt.addr, got, tt.key)
}
}
} |
package future
import (
"time"
)
const FuelRechargeRate = float32(1.0 / 3.0)
func CannonX(initial float32, rate float32, elap time.Duration) (float32, float32) {
x := initial + rate*float32(elap)/float32(time.Second)
switch {
case x < 0:
x = -x
rate = -rate
case x > 1:
x = 2 - x
rate = -rate
}
return x, rate
}
func MissileY(initial float32, rate float32, elap time.Duration) float32 {
y := initial + rate*float32(elap)/float32(time.Second)
if y > 1 {
y = 1
}
return y
}
func Fuel(initial float32, elap time.Duration) float32 | {
fuel := initial + FuelRechargeRate*float32(elap)/float32(time.Second)
if fuel > 10 {
fuel = 10
}
return fuel
} |
package main
var x int
func f() | {
L1:
for {
}
L2:
select {
}
L3:
switch {
}
L4:
if true {
}
L5:
f()
L6:
f()
L6:
f()
if x == 20 {
goto L6
}
L7:
for {
break L7
}
L8:
for {
if x == 21 {
continue L8
}
}
L9:
switch {
case true:
break L9
defalt:
}
L10:
select {
default:
break L10
}
} |
package wca
import (
"unsafe"
)
type IAudioClient2 struct {
IAudioClient
}
type IAudioClient2Vtbl struct {
IAudioClientVtbl
IsOffloadCapable uintptr
SetClientProperties uintptr
GetBufferSizeLimits uintptr
}
func (v *IAudioClient2) IsOffloadCapable(category uint32, isOffloadCapable *bool) (err error) {
err = ac2IsOffloadCapable(v, category, isOffloadCapable)
return
}
func (v *IAudioClient2) SetClientProperties(properties *AudioClientProperties) (err error) {
err = ac2SetClientProperties(v, properties)
return
}
func (v *IAudioClient2) GetBufferSizeLimits(wfx *WAVEFORMATEX, isEventDriven bool, minBufferDuration, maxBufferDuration *uint32) (err error) {
err = ac2GetBufferSizeLimits(v, wfx, isEventDriven, minBufferDuration, maxBufferDuration)
return
}
func (v *IAudioClient2) VTable() *IAudioClient2Vtbl | {
return (*IAudioClient2Vtbl)(unsafe.Pointer(v.RawVTable))
} |
package main
import "fmt"
func main() {
x := 1.5
square(&x)
fmt.Println(x)
}
func square(x *float64) | {
*x = *x * *x
} |
package jsoniter
import (
"github.com/stretchr/testify/require"
"testing"
)
func Test_encode_optional_int_pointer(t *testing.T) {
should := require.New(t)
var ptr *int
str, err := MarshalToString(ptr)
should.Nil(err)
should.Equal("null", str)
val := 100
ptr = &val
str, err = MarshalToString(ptr)
should.Nil(err)
should.Equal("100", str)
}
func Test_encode_struct_with_optional_field(t *testing.T) {
should := require.New(t)
type TestObject struct {
Field1 *string
Field2 *string
}
obj := TestObject{}
world := "world"
obj.Field2 = &world
str, err := MarshalToString(obj)
should.Nil(err)
should.Contains(str, `"Field1":null`)
should.Contains(str, `"Field2":"world"`)
}
func Test_decode_struct_with_optional_field(t *testing.T) | {
should := require.New(t)
type TestObject struct {
Field1 *string
Field2 *string
}
obj := TestObject{}
UnmarshalFromString(`{"field1": null, "field2": "world"}`, &obj)
should.Nil(obj.Field1)
should.Equal("world", *obj.Field2)
} |
package apm
import (
"fmt"
)
type KeyTransaction struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
TransactionName string `json:"transaction_name,omitempty"`
HealthStatus string `json:"health_status,omitempty"`
LastReportedAt string `json:"last_reported_at,omitempty"`
Reporting bool `json:"reporting"`
Summary ApplicationSummary `json:"application_summary,omitempty"`
EndUserSummary ApplicationEndUserSummary `json:"end_user_summary,omitempty"`
Links KeyTransactionLinks `json:"links,omitempty"`
}
type KeyTransactionLinks struct {
Application int `json:"application,omitempty"`
}
type ListKeyTransactionsParams struct {
Name string `url:"filter[name],omitempty"`
IDs []int `url:"filter[ids],omitempty,comma"`
}
func (a *APM) GetKeyTransaction(id int) (*KeyTransaction, error) {
response := keyTransactionResponse{}
url := fmt.Sprintf("/key_transactions/%d.json", id)
_, err := a.client.Get(a.config.Region().RestURL(url), nil, &response)
if err != nil {
return nil, err
}
return &response.KeyTransaction, nil
}
type keyTransactionsResponse struct {
KeyTransactions []*KeyTransaction `json:"key_transactions,omitempty"`
}
type keyTransactionResponse struct {
KeyTransaction KeyTransaction `json:"key_transaction,omitempty"`
}
func (a *APM) ListKeyTransactions(params *ListKeyTransactionsParams) ([]*KeyTransaction, error) | {
results := []*KeyTransaction{}
nextURL := a.config.Region().RestURL("key_transactions.json")
for nextURL != "" {
response := keyTransactionsResponse{}
resp, err := a.client.Get(nextURL, ¶ms, &response)
if err != nil {
return nil, err
}
results = append(results, response.KeyTransactions...)
paging := a.pager.Parse(resp)
nextURL = paging.Next
}
return results, nil
} |
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) Move() {
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
}
func (b *Ball) Position() Point {
return Point{b.x, b.y}
}
var b1 = NewBall(Point{40, 80})
var b2 = NewBall(Point{80, 40})
func tick() {
ClearCanvas()
b1.Move()
b2.Move()
DrawImage("ball.png", b1.Position())
DrawImage("ball.png", b2.Position())
}
func main() {
InitCanvas(screen)
MainLoop(tick)
}
func mainConsole() | {
for i := 0; i < 25; i++ {
Println("Ball 1 @", b1.Position())
Println("Ball 2 @", b2.Position())
b1.Move()
b2.Move()
}
} |
package middleware
import (
"github.com/drone/drone/shared/model"
"github.com/zenazn/goji/web"
)
func UserToC(c *web.C, user *model.User) {
c.Env["user"] = user
}
func RepoToC(c *web.C, repo *model.Repo) {
c.Env["repo"] = repo
}
func RoleToC(c *web.C, role *model.Perm) {
c.Env["role"] = role
}
func ToUser(c *web.C) *model.User {
var v = c.Env["user"]
if v == nil {
return nil
}
u, ok := v.(*model.User)
if !ok {
return nil
}
return u
}
func ToRole(c *web.C) *model.Perm {
var v = c.Env["role"]
if v == nil {
return nil
}
p, ok := v.(*model.Perm)
if !ok {
return nil
}
return p
}
func ToRepo(c *web.C) *model.Repo | {
var v = c.Env["repo"]
if v == nil {
return nil
}
r, ok := v.(*model.Repo)
if !ok {
return nil
}
return r
} |
package elastic
type LimitFilter struct {
Filter
limit int
}
func (f LimitFilter) Source() interface{} {
source := make(map[string]interface{})
params := make(map[string]interface{})
source["limit"] = params
params["value"] = f.limit
return source
}
func NewLimitFilter(limit int) LimitFilter | {
f := LimitFilter{limit: limit}
return f
} |
package gospec
import (
"fmt"
filepath "path"
"runtime"
)
type Location struct {
name string
file string
line int
}
func currentLocation() *Location {
return newLocation(1)
}
func callerLocation() *Location {
return newLocation(2)
}
func newLocation(n int) *Location {
if pc, _, _, ok := runtime.Caller(n + 1); ok {
return locationForPC(pc)
}
return nil
}
func locationForPC(pc uintptr) *Location {
pc = pcOfWhereCallWasMade(pc)
f := runtime.FuncForPC(pc)
name := f.Name()
file, line := f.FileLine(pc)
return &Location{name, file, line}
}
func pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {
return pcOfWhereCallReturnsTo - 1
}
func (this *Location) Name() string { return this.name }
func (this *Location) File() string { return this.file }
func (this *Location) FileName() string { return filename(this.file) }
func (this *Location) Line() int { return this.line }
func filename(path string) string {
_, file := filepath.Split(path)
return file
}
func (this *Location) String() string {
return fmt.Sprintf("%v:%v", this.FileName(), this.Line())
}
func (this *Location) equals(that *Location) bool | {
return this.name == that.name &&
this.file == that.file &&
this.line == that.line
} |
package sliceset
import (
"sort"
"github.com/xtgo/set"
)
type Set []int
func (s Set) Len() int { return len(s) }
func (s Set) Less(i, j int) bool { return s[i] < s[j] }
func (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Set) Copy() Set { return append(Set(nil), s...) }
func (s Set) Union(t Set) Set { return s.Do(set.Union, t) }
func (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }
func (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }
func (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }
func (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }
func (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }
func (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }
func (s Set) Uniq() Set {
n := set.Uniq(s)
return s[:n]
}
func (s Set) Do(op set.Op, t Set) Set {
data := append(s, t...)
n := op(data, len(s))
return data[:n]
}
type BoolOp func(sort.Interface, int) bool
func (s Set) DoBool(op BoolOp, t Set) bool {
data := append(s, t...)
return op(data, len(s))
}
func (s Set) IsInter(t Set) bool | { return s.DoBool(set.IsInter, t) } |
package containers
import (
"github.com/nanobox-io/golang-docker-client"
"github.com/nanobox-io/nanobox/util/dhcp"
)
func BridgeConfig() docker.ContainerConfig {
return docker.ContainerConfig{
Name: BridgeName(),
Image: "nanobox/bridge",
Network: "virt",
IP: reserveIP(),
RestartPolicy: "always",
Ports: []string{"1194:1194/udp"},
}
}
func reserveIP() string {
ip, _ := dhcp.ReserveLocal()
return ip.String()
}
func BridgeName() string | {
return "nanobox_bridge"
} |
package redis
import (
"bytes"
"encoding/gob"
"github.com/iris-framework/iris/adaptors/sessions/sessiondb/redis/service"
)
type Database struct {
redis *service.Service
}
func New(cfg ...service.Config) *Database {
return &Database{redis: service.New(cfg...)}
}
func (d *Database) Config() *service.Config {
return d.redis.Config
}
func (d *Database) Load(sid string) map[string]interface{} {
values := make(map[string]interface{})
if !d.redis.Connected {
d.redis.Connect()
_, err := d.redis.PingPong()
if err != nil {
if err != nil {
}
}
}
val, err := d.redis.GetBytes(sid)
if err == nil {
DeserializeBytes(val, &values)
}
return values
}
func serialize(values map[string]interface{}) []byte {
val, err := SerializeBytes(values)
if err != nil {
println("On redisstore.serialize: " + err.Error())
}
return val
}
func SerializeBytes(m interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
err := enc.Encode(m)
if err == nil {
return buf.Bytes(), nil
}
return nil, err
}
func DeserializeBytes(b []byte, m interface{}) error {
dec := gob.NewDecoder(bytes.NewBuffer(b))
return dec.Decode(m)
}
func (d *Database) Update(sid string, newValues map[string]interface{}) | {
if len(newValues) == 0 {
go d.redis.Delete(sid)
} else {
go d.redis.Set(sid, serialize(newValues))
}
} |
package jms
import (
"github.com/oracle/oci-go-sdk/v46/common"
"net/http"
)
type UpdateFleetAgentConfigurationRequest struct {
FleetId *string `mandatory:"true" contributesTo:"path" name:"fleetId"`
UpdateFleetAgentConfigurationDetails `contributesTo:"body"`
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
RequestMetadata common.RequestMetadata
}
func (request UpdateFleetAgentConfigurationRequest) String() string {
return common.PointerString(request)
}
func (request UpdateFleetAgentConfigurationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
func (request UpdateFleetAgentConfigurationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
func (request UpdateFleetAgentConfigurationRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
type UpdateFleetAgentConfigurationResponse struct {
RawResponse *http.Response
OpcWorkRequestId *string `presentIn:"header" name:"opc-work-request-id"`
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response UpdateFleetAgentConfigurationResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
func (response UpdateFleetAgentConfigurationResponse) String() string | {
return common.PointerString(response)
} |
package main
import "fmt"
var c chan int
func main() {
c := make(chan int)
quit := make(chan bool)
go count(c, quit)
for i := 0; i < 10; i++ {
c <- i
}
quit <- false
}
func count(c chan int, quit chan bool) | {
for {
select {
case i := <-c:
fmt.Println(i)
case <-quit:
break
}
}
} |
package geom
import "math"
type Vertex struct {
X, Y float64
}
type Vertices []Vertex
func (l Vertices) Convert() (data []float32) {
data = make([]float32, len(l)*2)
for i, v := range l {
index := i * 2
data[index] = float32(v.X)
data[index+1] = float32(v.Y)
}
return
}
func (c Vertex) SideOfLine(a Vertex, b Vertex) int {
cross := float64((b.X-a.X)*(c.Y-a.Y) - (b.Y-a.Y)*(c.X-a.X))
if cross == 0 {
return 0
}
if math.Signbit(cross) {
return 1
}
return -1
}
type Lexographically []Vertex
func (a Lexographically) Len() int { return len(a) }
func (a Lexographically) Less(i, j int) bool {
if a[i].X == a[j].X {
return a[i].Y < a[j].Y
}
return a[i].X < a[j].X
}
func (a Lexographically) Swap(i, j int) | { a[i], a[j] = a[j], a[i] } |
package tango
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
)
func TestDir1(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()
recorder.Body = buff
tg := New()
tg.Get("/:name", Dir("./public"))
req, err := http.NewRequest("GET", "http://localhost:8000/test.html", nil)
if err != nil {
t.Error(err)
}
tg.ServeHTTP(recorder, req)
expect(t, recorder.Code, http.StatusOK)
refute(t, len(buff.String()), 0)
expect(t, buff.String(), "hello tango")
}
func TestDir2(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()
recorder.Body = buff
tg := New()
tg.Get("/", Dir("./public"))
req, err := http.NewRequest("GET", "http://localhost:8000/", nil)
if err != nil {
t.Error(err)
}
tg.ServeHTTP(recorder, req)
expect(t, recorder.Code, http.StatusNotFound)
refute(t, len(buff.String()), 0)
expect(t, buff.String(), http.StatusText(http.StatusNotFound))
}
func TestFile1(t *testing.T) | {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()
recorder.Body = buff
tg := New()
tg.Get("/test.html", File("./public/test.html"))
req, err := http.NewRequest("GET", "http://localhost:8000/test.html", nil)
if err != nil {
t.Error(err)
}
tg.ServeHTTP(recorder, req)
expect(t, recorder.Code, http.StatusOK)
refute(t, len(buff.String()), 0)
expect(t, buff.String(), "hello tango")
} |
package addrs
import "fmt"
type ResourceInstancePhase struct {
referenceable
ResourceInstance ResourceInstance
Phase ResourceInstancePhaseType
}
var _ Referenceable = ResourceInstancePhase{}
func (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase {
return ResourceInstancePhase{
ResourceInstance: r,
Phase: rpt,
}
}
func (rp ResourceInstancePhase) ContainingResource() ResourcePhase {
return rp.ResourceInstance.Resource.Phase(rp.Phase)
}
func (rp ResourceInstancePhase) String() string {
return fmt.Sprintf("%s#%s", rp.ResourceInstance, rp.Phase)
}
type ResourceInstancePhaseType string
const (
ResourceInstancePhaseDestroy ResourceInstancePhaseType = "destroy"
ResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = "destroy-cbd"
)
func (rpt ResourceInstancePhaseType) String() string {
return string(rpt)
}
type ResourcePhase struct {
referenceable
Resource Resource
Phase ResourceInstancePhaseType
}
var _ Referenceable = ResourcePhase{}
func (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {
return ResourcePhase{
Resource: r,
Phase: rpt,
}
}
func (rp ResourcePhase) String() string | {
return fmt.Sprintf("%s#%s", rp.Resource, rp.Phase)
} |
package cover
import (
"flag"
"io"
"os"
"strings"
"testing"
)
func ParseAndStripTestFlags() {
flag.Parse()
var runtimeArgs []string
for _, arg := range os.Args {
if strings.HasPrefix(arg, "-test.") ||
strings.HasPrefix(arg, "-httptest.") {
continue
}
runtimeArgs = append(runtimeArgs, arg)
}
os.Args = runtimeArgs
}
type dummyTestDeps func(pat, str string) (bool, error)
func (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }
func (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }
func (d dummyTestDeps) StopCPUProfile() {}
func (f dummyTestDeps) StartTestLog(w io.Writer) {}
func (f dummyTestDeps) StopTestLog() error { return nil }
func (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }
func (f dummyTestDeps) ImportPath() string { return "" }
func FlushProfiles() {
oldstdout := os.Stdout
oldstderr := os.Stderr
os.Stdout, _ = os.Open(os.DevNull)
os.Stderr, _ = os.Open(os.DevNull)
tests := []testing.InternalTest{}
benchmarks := []testing.InternalBenchmark{}
examples := []testing.InternalExample{}
var f dummyTestDeps
dummyM := testing.MainStart(f, tests, benchmarks, examples)
dummyM.Run()
os.Stdout = oldstdout
os.Stderr = oldstderr
}
func (d dummyTestDeps) WriteHeapProfile(io.Writer) error | { return nil } |
package client
import (
"encoding/json"
"fmt"
)
type SystemSettings struct {
userStreamAcl *StreamAcl
systemStreamAcl *StreamAcl
}
func NewSystemSettings(
userStreamAcl *StreamAcl,
systemStreamAcl *StreamAcl,
) *SystemSettings {
return &SystemSettings{userStreamAcl, systemStreamAcl}
}
func (s *SystemSettings) UserStreamAcl() *StreamAcl { return s.userStreamAcl }
func (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }
type systemSettingsJson struct {
UserStreamAcl *StreamAcl `json:"$userStreamAcl,omitempty"`
SystemStreamAcl *StreamAcl `json:"$systemStreamAcl,omitempty"`
}
func (s *SystemSettings) MarshalJSON() ([]byte, error) {
return json.Marshal(systemSettingsJson{
UserStreamAcl: s.userStreamAcl,
SystemStreamAcl: s.systemStreamAcl,
})
}
func (s *SystemSettings) UnmarshalJSON(data []byte) error {
ss := systemSettingsJson{}
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
s.userStreamAcl = ss.UserStreamAcl
s.systemStreamAcl = ss.SystemStreamAcl
return nil
}
func SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) {
systemSettings := &SystemSettings{}
return systemSettings, json.Unmarshal(data, systemSettings)
}
func (s *SystemSettings) String() string | {
return fmt.Sprintf("&{userStreamAcl:%+v systemStreamAcl:%+v}", s.userStreamAcl, s.systemStreamAcl)
} |
package service
import (
log "github.com/golang/glog"
"k8s.io/kubernetes/contrib/mesos/pkg/podutil"
"k8s.io/kubernetes/contrib/mesos/pkg/scheduler/resources"
"k8s.io/kubernetes/pkg/api"
)
func StaticPodValidator(
defaultContainerCPULimit resources.CPUShares,
defaultContainerMemLimit resources.MegaBytes,
accumCPU, accumMem *float64,
) podutil.FilterFunc | {
return podutil.FilterFunc(func(pod *api.Pod) (bool, error) {
_, cpu, _, err := resources.LimitPodCPU(pod, defaultContainerCPULimit)
if err != nil {
return false, err
}
_, mem, _, err := resources.LimitPodMem(pod, defaultContainerMemLimit)
if err != nil {
return false, err
}
log.V(2).Infof("reserving %.2f cpu shares and %.2f MB of memory to static pod %s/%s", cpu, mem, pod.Namespace, pod.Name)
*accumCPU += float64(cpu)
*accumMem += float64(mem)
return true, nil
})
} |
package store
import (
"bytes"
"fmt"
"reflect"
"text/tabwriter"
"time"
)
type Metadata map[string]string
type Entry struct {
Name string `json:"name"`
Password []byte `json:"password"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
Metadata Metadata `json:"metadata"`
}
func NewEntry() *Entry {
return &Entry{
Metadata: make(Metadata),
Ctime: getCurrentTime(),
Mtime: getCurrentTime(),
}
}
func (e *Entry) Age() time.Duration {
return time.Since(e.Mtime)
}
func (e *Entry) Touch() {
e.Mtime = getCurrentTime()
}
func (e Entry) String() string {
b := new(bytes.Buffer)
w := tabwriter.NewWriter(b, 0, 0, 0, ' ', 0)
valof := reflect.ValueOf(e)
for i := 0; i < valof.NumField(); i++ {
switch val := valof.Field(i).Interface().(type) {
default:
tag := valof.Type().Field(i).Tag.Get("json")
fmt.Fprintf(w, "%s\t : %s\n", tag, val)
case Metadata:
for k, v := range val {
fmt.Fprintf(w, "%s\t : %s\n", k, v)
}
}
}
w.Flush()
return b.String()
}
func getCurrentTime() time.Time {
return time.Now().Truncate(time.Second)
}
func (m Metadata) String() string | {
var b bytes.Buffer
for k, v := range m {
fmt.Fprintf(&b, "%s:%s", k, v)
}
return b.String()
} |
package leet_25
type ListNode struct {
Val int
Next *ListNode
}
type dequeue struct {
buff []*ListNode
}
func (q *dequeue) lpop() *ListNode {
if 0 == len(q.buff) {
return nil
}
p := q.buff[0]
q.buff = q.buff[1:]
return p
}
func (q *dequeue) rpop() *ListNode {
if 0 == len(q.buff) {
return nil
}
last := len(q.buff) - 1
p := q.buff[last]
q.buff = q.buff[:last]
return p
}
func (q *dequeue) rpush(p *ListNode) {
q.buff = append(q.buff, p)
}
var buff []*ListNode
func reverseKGroup(head *ListNode, k int) *ListNode {
if head == nil {
return nil
}
if k <= 1 {
return head
}
buff = make([]*ListNode, 0, k)
queue := &dequeue{buff: buff}
count := 0
cur := head
for cur != nil {
count++
queue.rpush(cur)
if count == k {
count = 0
for {
l := queue.lpop()
r := queue.rpop()
if l == nil || r == nil {
break
}
l.Val, r.Val = r.Val, l.Val
}
queue.clear()
}
cur = cur.Next
}
return head
}
func (q *dequeue) clear() | {
q.buff = buff[:0]
} |
package history
import (
"fmt"
"github.com/avatar29A/microchat/history/model"
"github.com/avatar29A/microchat/server/protocols"
"github.com/avatar29A/microchat/utils"
log "github.com/Sirupsen/logrus"
)
import "github.com/satori/go.uuid"
type MessagesContext struct {
ctx *DBContext
}
func NewMessagesContext(context *DBContext) *MessagesContext {
c := &MessagesContext{context}
return c
}
func (c *MessagesContext) GetLastNMessages(n int) []*protocols.UserSay {
query := fmt.Sprintf("ORDER BY created_at DESC LIMIT %s", c.ctx.DB.Placeholder(0))
rows, err := c.ctx.DB.SelectAllFrom(model.MessageTable, query, n)
messages := make([]*protocols.UserSay, 0, len(rows))
if err != nil {
log.Error(err)
return messages
}
for _, row := range rows {
message := row.(*model.Message)
messages = append(messages, &protocols.UserSay{
Username: message.UserName,
Message: message.Message,
CreatedAt: utils.MakeTimeStampFromTime(message.CreatedAt),
})
}
return messages
}
func (c *MessagesContext) getDefaultChannel() *model.Channel {
entity, err := c.ctx.DB.FindOneFrom(model.ChannelTable, "name", "default")
if err != nil {
log.Fatal(err)
}
return entity.(*model.Channel)
}
func (c *MessagesContext) SaveMessage(message *protocols.UserSay) error | {
channel := c.getDefaultChannel()
entity := &model.Message{
ID: string(uuid.NewV4().Bytes()),
UserName: message.Username,
ChannelID: channel.ID,
Message: message.Message,
CreatedAt: utils.MakeTimeFromTimestamp(message.CreatedAt),
}
return c.ctx.DB.Save(entity)
} |
package migrator
import (
"github.com/cgrates/cgrates/engine"
"github.com/cgrates/cgrates/utils"
)
func (m *Migrator) migrateCurrentTPactionplans() (err error) {
tpids, err := m.storDBIn.StorDB().GetTpIds(utils.TBLTPActionPlans)
if err != nil {
return err
}
for _, tpid := range tpids {
ids, err := m.storDBIn.StorDB().GetTpTableIds(tpid, utils.TBLTPActionPlans,
utils.TPDistinctIds{"tag"}, map[string]string{}, nil)
if err != nil {
return err
}
for _, id := range ids {
actPln, err := m.storDBIn.StorDB().GetTPActionPlans(tpid, id)
if err != nil {
return err
}
if actPln != nil {
if m.dryRun != true {
if err := m.storDBOut.StorDB().SetTPActionPlans(actPln); err != nil {
return err
}
for _, act := range actPln {
if err := m.storDBIn.StorDB().RemTpData(utils.TBLTPActionPlans,
act.TPid, map[string]string{"tag": act.ID}); err != nil {
return err
}
}
m.stats[utils.TpActionPlans]++
}
}
}
}
return
}
func (m *Migrator) migrateTPactionplans() (err error) | {
var vrs engine.Versions
current := engine.CurrentStorDBVersions()
if vrs, err = m.getVersions(utils.TpActionPlans); err != nil {
return
}
switch vrs[utils.TpActionPlans] {
case current[utils.TpActionPlans]:
if m.sameStorDB {
break
}
if err := m.migrateCurrentTPactionplans(); err != nil {
return err
}
}
return m.ensureIndexesStorDB(utils.TBLTPActionPlans)
} |
package sa
import (
"fmt"
"gopkg.in/go-gorp/gorp.v2"
)
type RollbackError struct {
Err error
RollbackErr error
}
func Rollback(tx *gorp.Transaction, err error) error {
if txErr := tx.Rollback(); txErr != nil {
return &RollbackError{
Err: err,
RollbackErr: txErr,
}
}
return err
}
func (re *RollbackError) Error() string | {
if re.RollbackErr == nil {
return re.Err.Error()
}
return fmt.Sprintf("%s (also, while rolling back: %s)", re.Err, re.RollbackErr)
} |
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoassetRelationKey(t *testing.T) {
convey.Convey("assetRelationKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := assetRelationKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelCacheAssetRelationState(t *testing.T) {
convey.Convey("DelCacheAssetRelationState", t, func(ctx convey.C) {
var (
c = context.Background()
oid = int64(0)
otype = ""
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelCacheAssetRelationState(c, oid, otype, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoassetRelationField(t *testing.T) | {
convey.Convey("assetRelationField", t, func(ctx convey.C) {
var (
oid = int64(0)
otype = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := assetRelationField(oid, otype)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
} |
package sqltrace
import (
"flag"
"log"
"os"
"strconv"
"sync/atomic"
)
func boolToInt64(f bool) int64 {
if f {
return 1
}
return 0
}
type sqlTrace struct {
on int64
*log.Logger
}
func newSQLTrace() *sqlTrace {
return &sqlTrace{
Logger: log.New(os.Stdout, "hdb ", log.Ldate|log.Ltime|log.Lshortfile),
}
}
func (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }
type flagValue struct {
t *sqlTrace
}
func (v flagValue) IsBoolFlag() bool { return true }
func (v flagValue) String() string {
if v.t == nil {
return ""
}
return strconv.FormatBool(v.t.On())
}
func (v flagValue) Set(s string) error {
f, err := strconv.ParseBool(s)
if err != nil {
return err
}
v.t.SetOn(f)
return nil
}
var tracer = newSQLTrace()
func init() {
flag.Var(&flagValue{t: tracer}, "hdb.sqlTrace", "enabling hdb sql trace")
}
func On() bool { return tracer.On() }
func SetOn(on bool) { tracer.SetOn(on) }
func Trace(v ...interface{}) { tracer.Print(v...) }
func Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }
func Traceln(v ...interface{}) { tracer.Println(v...) }
func (t *sqlTrace) On() bool | { return atomic.LoadInt64(&t.on) != 0 } |
package example1
import (
"fmt"
)
type Runner interface {
Run(string) (string, error)
}
type Gopher struct {
name string
age int
}
func (g Gopher) Run(desc string) (string, error) | {
return fmt.Sprintf("I am %s and I run for %s", g.name, desc), nil
} |
package league
type Division struct {
name string
teams map[string]*Team
confrence *Conference
league *League
}
func (division *Division) GetName() string {
return division.name
}
func (division *Division) GetConference() *Conference {
return division.confrence
}
func (division *Division) getLeague() *League {
return division.league
}
func (division *Division) GetTeams() map[string]*Team | {
return division.teams
} |
package main
import (
"fmt"
"os"
"os/exec"
"github.com/rjeczalik/which"
)
func die(v interface{}) {
fmt.Fprintln(os.Stderr, v)
os.Exit(1)
}
const usage = `NAME:
gowhich - shows the import path of Go executables
USAGE:
gowhich name|path
EXAMPLES:
gowhich godoc
gowhich ~/bin/godoc`
func main() {
if len(os.Args) != 2 {
die(usage)
}
if ishelp(os.Args[1]) {
fmt.Println(usage)
return
}
path, err := exec.LookPath(os.Args[1])
if err != nil {
die(err)
}
pkg, err := which.Import(path)
if err != nil {
die(err)
}
fmt.Println(pkg)
}
func ishelp(s string) bool | {
return s == "-h" || s == "-help" || s == "help" || s == "--help" || s == "/?"
} |
package cachestore
import (
"encoding/json"
"sync"
)
type CacheStore struct {
stores map[string]*KVStore
mutex sync.RWMutex
}
func (c *CacheStore) GetStore(svcName string) *KVStore {
c.mutex.RLock()
kvstore := c.stores[svcName]
c.mutex.RUnlock()
return kvstore
}
func (c *CacheStore) CreateStore(svcName string) *KVStore {
kvstore := NewKVStore()
c.mutex.Lock()
c.stores[svcName] = kvstore
c.mutex.Unlock()
return kvstore
}
func (c *CacheStore) DeleteStore(svcName string) {
c.mutex.Lock()
delete(c.stores, svcName)
c.mutex.Unlock()
}
func (c *CacheStore) GetCache(svcName string, key string) interface{} {
svcStore := c.GetStore(svcName)
if svcStore == nil {
return nil
}
return svcStore.Get(key)
}
func (c *CacheStore) DeleteCache(svcName string, key string) {
svcStore := c.GetStore(svcName)
if svcStore != nil {
svcStore.Delete(key)
}
}
func (c *CacheStore) MarshalJSON() ([]byte, error) {
c.mutex.RLock()
bytes, err := json.Marshal(&c.stores)
c.mutex.RUnlock()
return bytes, err
}
func NewCacheStore() *CacheStore {
return &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}
}
func (c *CacheStore) SetCache(svcName string, key string, value interface{}) | {
svcStore := c.GetStore(svcName)
if svcStore == nil {
svcStore = c.CreateStore(svcName)
}
svcStore.Set(key, value)
} |
package agent
import (
"github.com/hashicorp/consul/consul/structs"
"net/http"
"sort"
)
func coordinateDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
resp.WriteHeader(401)
resp.Write([]byte("Coordinate support disabled"))
return nil, nil
}
type sorter struct {
coordinates structs.Coordinates
}
func (s *sorter) Len() int {
return len(s.coordinates)
}
func (s *sorter) Swap(i, j int) {
s.coordinates[i], s.coordinates[j] = s.coordinates[j], s.coordinates[i]
}
func (s *sorter) Less(i, j int) bool {
return s.coordinates[i].Node < s.coordinates[j].Node
}
func (s *HTTPServer) CoordinateDatacenters(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
var out []structs.DatacenterMap
if err := s.agent.RPC("Coordinate.ListDatacenters", struct{}{}, &out); err != nil {
for i := range out {
sort.Sort(&sorter{out[i].Coordinates})
}
return nil, err
}
for i, _ := range out {
if out[i].Coordinates == nil {
out[i].Coordinates = make(structs.Coordinates, 0)
}
}
if out == nil {
out = make([]structs.DatacenterMap, 0)
}
return out, nil
}
func (s *HTTPServer) CoordinateNodes(resp http.ResponseWriter, req *http.Request) (interface{}, error) | {
args := structs.DCSpecificRequest{}
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
var out structs.IndexedCoordinates
defer setMeta(resp, &out.QueryMeta)
if err := s.agent.RPC("Coordinate.ListNodes", &args, &out); err != nil {
sort.Sort(&sorter{out.Coordinates})
return nil, err
}
if out.Coordinates == nil {
out.Coordinates = make(structs.Coordinates, 0)
}
return out.Coordinates, nil
} |
package channelling
import (
"bytes"
"encoding/json"
"errors"
"log"
"github.com/strukturag/spreed-webrtc/go/buffercache"
)
type IncomingDecoder interface {
DecodeIncoming(buffercache.Buffer) (*DataIncoming, error)
}
type OutgoingEncoder interface {
EncodeOutgoing(*DataOutgoing) (buffercache.Buffer, error)
}
type Codec interface {
NewBuffer() buffercache.Buffer
IncomingDecoder
OutgoingEncoder
}
type incomingCodec struct {
buffers buffercache.BufferCache
incomingLimit int
}
func NewCodec(incomingLimit int) Codec {
return &incomingCodec{buffercache.NewBufferCache(1024, bytes.MinRead), incomingLimit}
}
func (codec incomingCodec) DecodeIncoming(b buffercache.Buffer) (*DataIncoming, error) {
length := b.GetBuffer().Len()
if length > codec.incomingLimit {
return nil, errors.New("Incoming message size limit exceeded")
}
incoming := &DataIncoming{}
return incoming, json.Unmarshal(b.Bytes(), incoming)
}
func (codec incomingCodec) EncodeOutgoing(outgoing *DataOutgoing) (buffercache.Buffer, error) {
b := codec.NewBuffer()
if err := json.NewEncoder(b).Encode(outgoing); err != nil {
log.Println("Error while encoding JSON", err)
b.Decref()
return nil, err
}
return b, nil
}
func (codec incomingCodec) NewBuffer() buffercache.Buffer | {
return codec.buffers.New()
} |
package v1alpha1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
var _ runtime.NestedObjectDecoder = &AdmissionConfiguration{}
var _ runtime.NestedObjectEncoder = &AdmissionConfiguration{}
func (c *AdmissionConfiguration) EncodeNestedObjects(e runtime.Encoder) error {
for k, v := range c.Plugins {
if err := encodeNestedRawExtension(e, &v.Configuration); err != nil {
return err
}
c.Plugins[k] = v
}
return nil
}
func decodeNestedRawExtensionOrUnknown(d runtime.Decoder, ext *runtime.RawExtension) {
if ext.Raw == nil || ext.Object != nil {
return
}
obj, gvk, err := d.Decode(ext.Raw, nil, nil)
if err != nil {
unk := &runtime.Unknown{Raw: ext.Raw}
if runtime.IsNotRegisteredError(err) {
if _, gvk, err := d.Decode(ext.Raw, nil, unk); err == nil {
unk.APIVersion = gvk.GroupVersion().String()
unk.Kind = gvk.Kind
ext.Object = unk
return
}
}
if gvk != nil {
unk.APIVersion = gvk.GroupVersion().String()
unk.Kind = gvk.Kind
}
obj = unk
}
ext.Object = obj
}
func encodeNestedRawExtension(e runtime.Encoder, ext *runtime.RawExtension) error {
if ext.Raw != nil || ext.Object == nil {
return nil
}
data, err := runtime.Encode(e, ext.Object)
if err != nil {
return err
}
ext.Raw = data
return nil
}
func (c *AdmissionConfiguration) DecodeNestedObjects(d runtime.Decoder) error | {
for k, v := range c.Plugins {
decodeNestedRawExtensionOrUnknown(d, &v.Configuration)
c.Plugins[k] = v
}
return nil
} |
package analyzer
import (
. "github.com/levythu/gurgling"
"time"
"fmt"
"strconv"
)
type SimpleAnalyzer struct {
}
func ASimpleAnalyzer() Sandwich {
return &SimpleAnalyzer{}
}
const token_returncode="SimpleAnalyzer-Status-Code"
const token_starttime="SimpleAnalyzer-Start-Time"
func (this *SimpleAnalyzer)Handler(req Request, res Response) (bool, Request, Response) {
var newRes=&logResponse {
o: res,
OnHeadSent: logCode,
}
newRes.F()[token_starttime]=time.Now().UnixNano()
return true, req, newRes
}
func (this *SimpleAnalyzer)Final(req Request, res Response) {
var timeStart, ok=res.F()[token_starttime].(int64)
var timeElpase string
if ok {
var t=time.Now().UnixNano()
timeElpase=strconv.FormatInt((t-timeStart)/1000000, 10)+"ms"
} else {
timeElpase="xxxx"
}
var statusCode, ok2=res.F()[token_returncode].(int)
var codeStr string
if ok2 {
codeStr=strconv.Itoa(statusCode)
} else {
codeStr="---"
}
var url=req.R().URL
fmt.Print("- "+timeElpase+"\t\t"+codeStr+"\t"+req.Method()+"\t"+url.Path)
if url.RawQuery!="" {
fmt.Println("?"+url.RawQuery)
} else {
fmt.Println("")
}
}
func logCode(res Response, c int) | {
res.F()[token_returncode]=c
} |
package protobuf
import "github.com/m3db/m3x/pool"
const (
defaultInitBufferSize = 2880
defaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024
)
type UnaggregatedOptions interface {
SetBytesPool(value pool.BytesPool) UnaggregatedOptions
BytesPool() pool.BytesPool
SetInitBufferSize(value int) UnaggregatedOptions
InitBufferSize() int
SetMaxMessageSize(value int) UnaggregatedOptions
MaxMessageSize() int
}
type unaggregatedOptions struct {
bytesPool pool.BytesPool
initBufferSize int
maxMessageSize int
}
func (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {
opts := *o
opts.bytesPool = value
return &opts
}
func (o *unaggregatedOptions) BytesPool() pool.BytesPool {
return o.bytesPool
}
func (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {
opts := *o
opts.initBufferSize = value
return &opts
}
func (o *unaggregatedOptions) InitBufferSize() int {
return o.initBufferSize
}
func (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {
opts := *o
opts.maxMessageSize = value
return &opts
}
func (o *unaggregatedOptions) MaxMessageSize() int {
return o.maxMessageSize
}
func NewUnaggregatedOptions() UnaggregatedOptions | {
p := pool.NewBytesPool(nil, nil)
p.Init()
return &unaggregatedOptions{
bytesPool: p,
initBufferSize: defaultInitBufferSize,
maxMessageSize: defaultMaxUnaggregatedMessageSize,
}
} |
package server
import (
"net/http"
"time"
"aptweb"
)
func NewServer(aptWebConfig *aptweb.Config, config *Config) *http.Server | {
h := NewHandler(aptWebConfig, config)
s := &http.Server{
Addr: config.Address,
Handler: h,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
return s
} |
package dom
import (
"bytes"
"fmt"
)
type Node interface {
String() string
Parent() Node
SetParent(node Node)
Children() []Node
AddChild(child Node)
Clone() Node
}
type Element struct {
text string
parent Node
children []Node
}
func NewElement(text string) *Element {
return &Element{
text: text,
parent: nil,
children: make([]Node, 0),
}
}
func (e *Element) Parent() Node {
return e.parent
}
func (e *Element) SetParent(node Node) {
e.parent = node
}
func (e *Element) AddChild(child Node) {
copy := child.Clone()
copy.SetParent(e)
e.children = append(e.children, copy)
}
func (e *Element) Clone() Node {
copy := &Element{
text: e.text,
parent: nil,
children: make([]Node, 0),
}
for _, child := range e.children {
copy.AddChild(child)
}
return copy
}
func (e *Element) String() string {
buffer := bytes.NewBufferString(e.text)
for _, c := range e.Children() {
text := c.String()
fmt.Fprintf(buffer, "\n %s", text)
}
return buffer.String()
}
func (e *Element) Children() []Node | {
return e.children
} |
package app
import (
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/utils"
)
type AutoChannelCreator struct {
client *model.Client
team *model.Team
Fuzzy bool
DisplayNameLen utils.Range
DisplayNameCharset string
NameLen utils.Range
NameCharset string
ChannelType string
}
func (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, bool) {
var displayName string
if cfg.Fuzzy {
displayName = utils.FuzzName()
} else {
displayName = utils.RandomName(cfg.NameLen, cfg.NameCharset)
}
name := utils.RandomName(cfg.NameLen, cfg.NameCharset)
channel := &model.Channel{
TeamId: cfg.team.Id,
DisplayName: displayName,
Name: name,
Type: cfg.ChannelType}
println(cfg.client.GetTeamRoute())
result, err := cfg.client.CreateChannel(channel)
if err != nil {
err.Translate(utils.T)
println(err.Error())
println(err.DetailedError)
return nil, false
}
return result.Data.(*model.Channel), true
}
func (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, bool) {
numChannels := utils.RandIntFromRange(num)
channels := make([]*model.Channel, numChannels)
for i := 0; i < numChannels; i++ {
var err bool
channels[i], err = cfg.createRandomChannel()
if err != true {
return channels, false
}
}
return channels, true
}
func NewAutoChannelCreator(client *model.Client, team *model.Team) *AutoChannelCreator | {
return &AutoChannelCreator{
client: client,
team: team,
Fuzzy: false,
DisplayNameLen: CHANNEL_DISPLAY_NAME_LEN,
DisplayNameCharset: utils.ALPHANUMERIC,
NameLen: CHANNEL_NAME_LEN,
NameCharset: utils.LOWERCASE,
ChannelType: CHANNEL_TYPE,
}
} |
package rtda
import (
"github.com/zxh0/jvm.go/rtda/heap"
)
type FrameCache struct {
thread *Thread
cachedFrames []*Frame
frameCount uint
maxFrame uint
}
func newFrameCache(thread *Thread, maxFrame uint) *FrameCache {
return &FrameCache{
thread: thread,
maxFrame: maxFrame,
cachedFrames: make([]*Frame, maxFrame),
}
}
func (cache *FrameCache) borrowFrame(method *heap.Method) *Frame {
if cache.frameCount > 0 {
for i, frame := range cache.cachedFrames {
if frame != nil &&
frame.maxLocals >= method.MaxLocals &&
frame.maxStack >= method.MaxStack {
cache.frameCount--
cache.cachedFrames[i] = nil
frame.reset(method)
return frame
}
}
}
return newFrame(cache.thread, method)
}
func (cache *FrameCache) returnFrame(frame *Frame) | {
if cache.frameCount < cache.maxFrame {
for i, cachedFrame := range cache.cachedFrames {
if cachedFrame == nil {
cache.cachedFrames[i] = frame
cache.frameCount++
return
}
}
} else {
for _, cachedFrame := range cache.cachedFrames {
if frame.maxLocals > cachedFrame.maxLocals {
cachedFrame.maxLocals = frame.maxLocals
cachedFrame.LocalVars = frame.LocalVars
frame.maxLocals = 0
}
if frame.maxStack > cachedFrame.maxStack {
cachedFrame.maxStack = frame.maxStack
cachedFrame.OperandStack = frame.OperandStack
frame.maxStack = 0
}
}
}
} |
package commands
import (
log "github.com/sirupsen/logrus"
"github.com/jamesread/ovress/pkg/indexer"
"github.com/spf13/cobra"
)
func runIndexCmd(cmd *cobra.Command, args []string) {
for _, path := range args {
log.WithFields(log.Fields{
"path": path,
}).Infof("Indexing starting")
root := indexer.ScanRoot(path)
indexer.SaveIndex(root)
log.WithFields(log.Fields{
"path": path,
}).Infof("Indexing complete")
}
}
func init() {
rootCmd.AddCommand(newIndexCmd())
}
func newIndexCmd() *cobra.Command | {
var indexCmd = &cobra.Command{
Use: "index",
Short: "Indexes a file path",
Run: runIndexCmd,
Args: cobra.MinimumNArgs(1),
}
return indexCmd
} |
package unibyte
import "unicode"
func IsLower(b byte) bool {
return b >= 'a' && b <= 'z'
}
func IsUpper(b byte) bool {
return b >= 'A' && b <= 'Z'
}
func IsLetter(b byte) bool {
return IsLower(b) || IsUpper(b)
}
func IsSpaceQuote(b byte) bool {
return IsSpace(b) || b == '"' || b == '\''
}
func ToLower(b byte) byte {
if IsUpper(b) {
b = b - 'A' + 'a'
}
return b
}
func ToUpper(b byte) byte {
if IsLower(b) {
b = b - 'a' + 'A'
}
return b
}
func ToLowerString(b byte) string {
if IsUpper(b) {
b = b - 'A' + 'a'
}
return string(b)
}
func ToUpperString(b byte) string {
if IsLower(b) {
b = b - 'a' + 'A'
}
return string(b)
}
func IsSpace(b byte) bool | {
return unicode.IsSpace(rune(b))
} |
package aprs
import (
"fmt"
)
type PacketType byte
var packetTypeNames = map[byte]string{
0x1c: "Current Mic-E Data (Rev 0 beta)",
0x1d: "Old Mic-E Data (Rev 0 beta)",
'!': "Position without timestamp (no APRS messaging), or Ultimeter 2000 WX Station",
'#': "Peet Bros U-II Weather Station",
'$': "Raw GPS data or Ultimeter 2000",
'%': "Agrelo DFJr / MicroFinder",
'"': "Old Mic-E Data (but Current data for TM-D700)",
')': "Item",
'*': "Peet Bros U-II Weather Station",
',': "Invalid data or test data",
'/': "Position with timestamp (no APRS messaging)",
':': "Message",
';': "Object",
'<': "Station Capabilities",
'=': "Position without timestamp (with APRS messaging)",
'>': "Status",
'?': "Query",
'@': "Position with timestamp (with APRS messaging)",
'T': "Telemetry data",
'[': "Maidenhead grid locator beacon (obsolete)",
'_': "Weather Report (without position)",
'`': "Current Mic-E Data (not used in TM-D700)",
'{': "User-Defined APRS packet format",
'}': "Third-party traffic",
}
func (p PacketType) IsThirdParty() bool {
return p == '}'
}
func (p PacketType) String() string {
if t, ok := packetTypeNames[byte(p)]; ok {
return t
}
return fmt.Sprintf("Unknown %x", byte(p))
}
func (p PacketType) IsMessage() bool | {
return p == ':'
} |
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(&i.v, delta)
}
func (i *Uint32) Sub(delta uint32) uint32 {
return atomic.AddUint32(&i.v, ^(delta - 1))
}
func (i *Uint32) Inc() uint32 {
return i.Add(1)
}
func (i *Uint32) Dec() uint32 {
return i.Sub(1)
}
func (i *Uint32) CAS(old, new uint32) (swapped bool) {
return atomic.CompareAndSwapUint32(&i.v, old, new)
}
func (i *Uint32) Store(val uint32) {
atomic.StoreUint32(&i.v, val)
}
func (i *Uint32) Swap(val uint32) (old uint32) {
return atomic.SwapUint32(&i.v, val)
}
func (i *Uint32) MarshalJSON() ([]byte, error) {
return json.Marshal(i.Load())
}
func (i *Uint32) UnmarshalJSON(b []byte) error {
var v uint32
if err := json.Unmarshal(b, &v); err != nil {
return err
}
i.Store(v)
return nil
}
func (i *Uint32) String() string | {
v := i.Load()
return strconv.FormatUint(uint64(v), 10)
} |
package payload
import (
"fmt"
"github.com/hyperledger/burrow/acm/acmstate"
"github.com/hyperledger/burrow/crypto"
)
func NewBondTx(address crypto.Address, amount uint64) *BondTx {
return &BondTx{
Input: &TxInput{
Address: address,
Amount: amount,
},
}
}
func (tx *BondTx) Type() Type {
return TypeBond
}
func (tx *BondTx) GetInputs() []*TxInput {
return []*TxInput{tx.Input}
}
func (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {
addr := pubkey.GetAddress()
acc, err := st.GetAccount(addr)
if err != nil {
return err
}
if acc == nil {
return fmt.Errorf("invalid address %s from pubkey %s", addr, pubkey)
}
return tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))
}
func (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {
tx.Input = &TxInput{
Address: pubkey.GetAddress(),
Amount: amt,
Sequence: sequence,
}
return nil
}
func (tx *BondTx) Any() *Any {
return &Any{
BondTx: tx,
}
}
func (tx *BondTx) String() string | {
return fmt.Sprintf("BondTx{%v}", tx.Input)
} |
package vkutil
import (
"strconv"
"time"
)
type EpochTime time.Time
func (t EpochTime) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil
}
func (t EpochTime) ToTime() time.Time {
return time.Time(t)
}
func (t *EpochTime) UnmarshalJSON(s []byte) error | {
var err error
var q int64
if q, err = strconv.ParseInt(string(s), 10, 64); err != nil {
return err
}
*(*time.Time)(t) = time.Unix(q, 0)
return err
} |
package password
import (
"crypto/rand"
"encoding/base64"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var signingKey = genRandBytes()
func GenToken(id string) (string, error) {
jwt := jwt.New(jwt.SigningMethodHS256)
expTime := time.Now().Add(time.Hour * 72).Unix()
jwt.Claims["sub"] = id
jwt.Claims["exp"] = expTime
jwt.Claims["iat"] = time.Now().Unix()
tokStr, err := jwt.SignedString(signingKey)
if err != nil {
return "", err
}
return tokStr, nil
}
func genRandBytes() []byte {
b := make([]byte, 24)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
return []byte(base64.URLEncoding.EncodeToString(b))
}
func SetSigningKey(key []byte) | {
signingKey = key
} |
package aws
import (
"log"
"fmt"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsVpcPeeringConnectionAccepter() *schema.Resource {
return &schema.Resource{
Create: resourceAwsVPCPeeringAccepterCreate,
Read: resourceAwsVPCPeeringRead,
Update: resourceAwsVPCPeeringUpdate,
Delete: resourceAwsVPCPeeringAccepterDelete,
Schema: map[string]*schema.Schema{
"vpc_peering_connection_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
Computed: false,
},
"auto_accept": {
Type: schema.TypeBool,
Optional: true,
},
"accept_status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_region": {
Type: schema.TypeString,
Computed: true,
},
"accepter": vpcPeeringConnectionOptionsSchema(),
"requester": vpcPeeringConnectionOptionsSchema(),
"tags": tagsSchema(),
},
}
}
func resourceAwsVPCPeeringAccepterDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Will not delete VPC peering connection. Terraform will remove this resource from the state file, however resources may remain.")
d.SetId("")
return nil
}
func resourceAwsVPCPeeringAccepterCreate(d *schema.ResourceData, meta interface{}) error | {
id := d.Get("vpc_peering_connection_id").(string)
d.SetId(id)
if err := resourceAwsVPCPeeringRead(d, meta); err != nil {
return err
}
if d.Id() == "" {
return fmt.Errorf("VPC Peering Connection %q not found", id)
}
return resourceAwsVPCPeeringUpdate(d, meta)
} |
package wire
import (
"time"
)
type periodicTask struct {
period time.Duration
task func()
ticker *time.Ticker
stop chan struct{}
}
func newPeriodicTask(period time.Duration, task func()) *periodicTask {
return &periodicTask{
period: period,
task: task,
}
}
func (pt *periodicTask) Start() {
if pt.ticker != nil || pt.period <= 0 {
return
}
pt.ticker = time.NewTicker(pt.period)
pt.stop = make(chan struct{})
go pt.poll(pt.ticker, pt.stop)
}
func (pt *periodicTask) Stop() {
if pt.ticker == nil {
return
}
pt.ticker.Stop()
close(pt.stop)
pt.ticker = nil
pt.stop = nil
}
func (pt *periodicTask) poll(ticker *time.Ticker, stop chan struct{}) | {
for {
select {
case <-stop:
return
default:
}
select {
case <-stop:
return
case <-ticker.C:
pt.task()
}
}
} |
package embed
import (
"fmt"
"io/ioutil"
"net/url"
"os"
"testing"
"go.etcd.io/etcd/server/v3/auth"
)
func TestStartEtcdWrongToken(t *testing.T) {
tdir, err := ioutil.TempDir(os.TempDir(), "token-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tdir)
cfg := NewConfig()
urls := newEmbedURLs(2)
curls := []url.URL{urls[0]}
purls := []url.URL{urls[1]}
cfg.LCUrls, cfg.ACUrls = curls, curls
cfg.LPUrls, cfg.APUrls = purls, purls
cfg.InitialCluster = ""
for i := range purls {
cfg.InitialCluster += ",default=" + purls[i].String()
}
cfg.InitialCluster = cfg.InitialCluster[1:]
cfg.Dir = tdir
cfg.AuthToken = "wrong-token"
if _, err = StartEtcd(cfg); err != auth.ErrInvalidAuthOpts {
t.Fatalf("expected %v, got %v", auth.ErrInvalidAuthOpts, err)
}
}
func newEmbedURLs(n int) (urls []url.URL) | {
scheme := "unix"
for i := 0; i < n; i++ {
u, _ := url.Parse(fmt.Sprintf("%s:localhost:%d%06d", scheme, os.Getpid(), i))
urls = append(urls, *u)
}
return urls
} |
package main
import (
"errors"
"strings"
"unicode"
)
func splitQuoted(s string) (r []string, err error) {
var args []string
arg := make([]rune, len(s))
escaped := false
quoted := false
quote := '\x00'
i := 0
for _, rune := range s {
switch {
case escaped:
escaped = false
case rune == '\\':
escaped = true
continue
case quote != '\x00':
if rune == quote {
quote = '\x00'
continue
}
case rune == '"' || rune == '\'':
quoted = true
quote = rune
continue
case unicode.IsSpace(rune):
if quoted || i > 0 {
quoted = false
args = append(args, string(arg[:i]))
i = 0
}
continue
}
arg[i] = rune
i++
}
if quoted || i > 0 {
args = append(args, string(arg[:i]))
}
if quote != 0 {
err = errors.New("unclosed quote")
} else if escaped {
err = errors.New("unfinished escaping")
}
return args, err
}
func stringsCut(s, sep string) (before, after string, found bool) | {
if i := strings.Index(s, sep); i >= 0 {
return s[:i], s[i+len(sep):], true
}
return s, "", false
} |
package control
import (
yaml "github.com/cloudfoundry-incubator/candiedyaml"
"github.com/dansteen/controlled-compose/types"
"github.com/docker/libcompose/config"
"github.com/docker/libcompose/utils"
"github.com/imdario/mergo.git"
"io/ioutil"
"path/filepath"
)
func processRequires(file string, configFiles []string) ([]string, error) {
content, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
var requires types.Requires
err = yaml.Unmarshal(content, &requires)
if err != nil {
return nil, err
}
newFiles := append(configFiles, file)
for _, require := range requires.Require {
require = filepath.Join(filepath.Dir(file), require)
if !utils.Contains(configFiles, require) {
newFiles, err = processRequires(require, newFiles)
if err != nil {
return nil, err
}
}
}
return newFiles, nil
}
func consumeConfigs(files []string) ([]byte, error) | {
var configContent config.Config
var mergedConfig config.Config
for _, file := range files {
content, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(content, &configContent)
if err != nil {
return nil, err
}
err = mergo.Merge(&mergedConfig, configContent)
if err != nil {
return nil, err
}
}
yamlConfig, err := yaml.Marshal(mergedConfig)
if err != nil {
return nil, err
}
return []byte(yamlConfig), nil
} |
package container
type (
Lifo struct {
Fifo
}
)
func (li *Lifo) Less(i, j int) bool | {
return li.data[i].index > li.data[j].index
} |
package algorithms
import "log"
func canCompleteCircuit(gas []int, cost []int) int {
for i := 0; i < len(gas); i++ {
gas[i] = gas[i] - cost[i]
}
log.Println("A:", gas)
index := 0
for i := 1; i < len(gas); i++ {
gas[i] += gas[i-1]
if gas[i] < gas[index] {
index = i
}
}
log.Println("B:", gas)
if gas[len(gas)-1] < 0 {
return -1
}
return (index + 1) % len(gas)
}
func canCompleteCircuit(gas []int, cost []int) int {
for i := 0; i < len(gas); i++ {
gas[i] = gas[i] - cost[i]
}
log.Println("A:", gas)
index := 0
for i := 1; i < len(gas); i++ {
gas[i] += gas[i-1]
if gas[i] < gas[index] {
index = i
}
}
log.Println("B:", gas)
if gas[len(gas)-1] < 0 {
return -1
}
return (index + 1) % len(gas)
}
func canCompleteCircuit(gas []int, cost []int) int | {
index := 0
for i := 0; i < len(gas); i++ {
gas[i] = gas[i] - cost[i]
if i > 0 {
gas[i] += gas[i-1]
if gas[i] < gas[index] {
index = i
}
}
}
if gas[len(gas)-1] < 0 {
return -1
}
return (index + 1) % len(gas)
} |
package zk
import "github.com/go-kit/kit/log"
type Registrar struct {
client Client
service Service
logger log.Logger
}
type Service struct {
Path string
Name string
Data []byte
node string
}
func (r *Registrar) Register() {
if err := r.client.Register(&r.service); err != nil {
r.logger.Log("err", err)
} else {
r.logger.Log("action", "register")
}
}
func (r *Registrar) Deregister() {
if err := r.client.Deregister(&r.service); err != nil {
r.logger.Log("err", err)
} else {
r.logger.Log("action", "deregister")
}
}
func NewRegistrar(client Client, service Service, logger log.Logger) *Registrar | {
return &Registrar{
client: client,
service: service,
logger: log.With(logger,
"service", service.Name,
"path", service.Path,
"data", string(service.Data),
),
}
} |
package kv_test
import (
"context"
"testing"
"github.com/influxdata/influxdb"
"github.com/influxdata/influxdb/kv"
influxdbtesting "github.com/influxdata/influxdb/testing"
)
func TestBoltOrganizationService(t *testing.T) {
influxdbtesting.OrganizationService(initBoltOrganizationService, t)
}
func TestInmemOrganizationService(t *testing.T) {
influxdbtesting.OrganizationService(initInmemOrganizationService, t)
}
func initBoltOrganizationService(f influxdbtesting.OrganizationFields, t *testing.T) (influxdb.OrganizationService, string, func()) {
s, closeBolt, err := NewTestBoltStore()
if err != nil {
t.Fatalf("failed to create new kv store: %v", err)
}
svc, op, closeSvc := initOrganizationService(s, f, t)
return svc, op, func() {
closeSvc()
closeBolt()
}
}
func initInmemOrganizationService(f influxdbtesting.OrganizationFields, t *testing.T) (influxdb.OrganizationService, string, func()) {
s, closeBolt, err := NewTestInmemStore()
if err != nil {
t.Fatalf("failed to create new kv store: %v", err)
}
svc, op, closeSvc := initOrganizationService(s, f, t)
return svc, op, func() {
closeSvc()
closeBolt()
}
}
func initOrganizationService(s kv.Store, f influxdbtesting.OrganizationFields, t *testing.T) (influxdb.OrganizationService, string, func()) | {
svc := kv.NewService(s)
svc.OrgBucketIDs = f.OrgBucketIDs
svc.IDGenerator = f.IDGenerator
svc.TimeGenerator = f.TimeGenerator
if f.TimeGenerator == nil {
svc.TimeGenerator = influxdb.RealTimeGenerator{}
}
ctx := context.Background()
if err := svc.Initialize(ctx); err != nil {
t.Fatalf("error initializing organization service: %v", err)
}
for _, u := range f.Organizations {
if err := svc.PutOrganization(ctx, u); err != nil {
t.Fatalf("failed to populate organizations")
}
}
return svc, kv.OpPrefix, func() {
for _, u := range f.Organizations {
if err := svc.DeleteOrganization(ctx, u.ID); err != nil {
t.Logf("failed to remove organizations: %v", err)
}
}
}
} |
package service
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/cilium/cilium/api/v1/models"
)
const GetServiceIDOKCode int = 200
type GetServiceIDOK struct {
Payload *models.Service `json:"body,omitempty"`
}
func NewGetServiceIDOK() *GetServiceIDOK {
return &GetServiceIDOK{}
}
func (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {
o.Payload = payload
return o
}
func (o *GetServiceIDOK) SetPayload(payload *models.Service) {
o.Payload = payload
}
func (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err)
}
}
}
const GetServiceIDNotFoundCode int = 404
type GetServiceIDNotFound struct {
}
func (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType)
rw.WriteHeader(404)
}
func NewGetServiceIDNotFound() *GetServiceIDNotFound | {
return &GetServiceIDNotFound{}
} |
package alicloud
type PrimaryKeyTypeString string
const (
IntegerType = PrimaryKeyTypeString("Integer")
StringType = PrimaryKeyTypeString("String")
BinaryType = PrimaryKeyTypeString("Binary")
)
type InstanceAccessedByType string
const (
AnyNetwork = InstanceAccessedByType("Any")
VpcOnly = InstanceAccessedByType("Vpc")
VpcOrConsole = InstanceAccessedByType("ConsoleOrVpc")
)
type OtsInstanceType string
const (
OtsCapacity = OtsInstanceType("Capacity")
OtsHighPerformance = OtsInstanceType("HighPerformance")
)
func convertInstanceAccessedBy(accessed InstanceAccessedByType) string {
switch accessed {
case VpcOnly:
return "VPC"
case VpcOrConsole:
return "VPC_CONSOLE"
default:
return "NORMAL"
}
}
func convertInstanceAccessedByRevert(network string) InstanceAccessedByType {
switch network {
case "VPC":
return VpcOnly
case "VPC_CONSOLE":
return VpcOrConsole
default:
return AnyNetwork
}
}
func convertInstanceType(instanceType OtsInstanceType) string {
switch instanceType {
case OtsHighPerformance:
return "SSD"
default:
return "HYBRID"
}
}
func convertOtsInstanceStatus(status Status) int {
switch status {
case Running:
return 1
case DisabledStatus:
return 2
case Deleting:
return 3
default:
return -1
}
}
func convertInstanceTypeRevert(instanceType string) OtsInstanceType | {
switch instanceType {
case "SSD":
return OtsHighPerformance
default:
return OtsCapacity
}
} |
package assert
func isPrime(value int) bool | {
if value <= 3 {
return value >= 2
}
if value%2 == 0 || value%3 == 0 {
return false
}
uns := uint(value)
for i := uint(5); i*i <= uns; i += 6 {
if uns%i == 0 || uns%(i+2) == 0 {
return false
}
}
return true
} |
package state
import (
"net/url"
"gopkg.in/juju/charm.v3"
)
type charmDoc struct {
URL *charm.URL `bson:"_id"`
Meta *charm.Meta
Config *charm.Config
Actions *charm.Actions
BundleURL *url.URL
BundleSha256 string
PendingUpload bool
Placeholder bool
}
type Charm struct {
st *State
doc charmDoc
}
func newCharm(st *State, cdoc *charmDoc) (*Charm, error) {
return &Charm{st: st, doc: *cdoc}, nil
}
func (c *Charm) String() string {
return c.doc.URL.String()
}
func (c *Charm) URL() *charm.URL {
clone := *c.doc.URL
return &clone
}
func (c *Charm) Revision() int {
return c.doc.URL.Revision
}
func (c *Charm) Meta() *charm.Meta {
return c.doc.Meta
}
func (c *Charm) Actions() *charm.Actions {
return c.doc.Actions
}
func (c *Charm) BundleURL() *url.URL {
return c.doc.BundleURL
}
func (c *Charm) BundleSha256() string {
return c.doc.BundleSha256
}
func (c *Charm) IsUploaded() bool {
return !c.doc.PendingUpload
}
func (c *Charm) IsPlaceholder() bool {
return c.doc.Placeholder
}
func (c *Charm) Config() *charm.Config | {
return c.doc.Config
} |
package emperror
import (
"errors"
"fmt"
)
func Recover(r interface{}) (err error) | {
if r != nil {
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = fmt.Errorf("unknown panic, received: %v", r)
}
if _, ok := StackTrace(err); !ok {
err = &wrappedError{
err: err,
stack: callers()[2:],
}
}
}
return err
} |
package systemd
import (
"fmt"
"strings"
"github.com/google/cadvisor/container"
"github.com/google/cadvisor/fs"
info "github.com/google/cadvisor/info/v1"
"github.com/google/cadvisor/watcher"
"k8s.io/klog/v2"
)
type systemdFactory struct{}
func (f *systemdFactory) String() string {
return "systemd"
}
func (f *systemdFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) {
return nil, fmt.Errorf("Not yet supported")
}
func (f *systemdFactory) DebugInfo() map[string][]string {
return map[string][]string{}
}
func Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) error {
klog.V(1).Infof("Registering systemd factory")
factory := &systemdFactory{}
container.RegisterContainerHandlerFactory(factory, []watcher.ContainerWatchSource{watcher.Raw})
return nil
}
func (f *systemdFactory) CanHandleAndAccept(name string) (bool, bool, error) | {
if strings.HasSuffix(name, ".mount") {
return true, false, nil
}
klog.V(5).Infof("%s not handled by systemd handler", name)
return false, false, nil
} |
package errors
func NewEmptyResourceError() *EmptyResourceError {
return &EmptyResourceError{}
}
type EmptyResourceError struct{}
func (e *EmptyResourceError) Error() string | {
return "EmptyResourceError"
} |
package wifi
var _ = WiFi(&StubWorker{})
type StubWorker struct {
Options []Option
ID string
}
func (w *StubWorker) Scan() ([]Option, error) {
return w.Options, nil
}
func (*StubWorker) Connect(a ...string) error {
return nil
}
func NewStubWorker(id string, options ...Option) (WiFi, error) {
return &StubWorker{ID: id, Options: options}, nil
}
func (w *StubWorker) GetID() (string, error) | {
return w.ID, nil
} |
package caaa
import (
"encoding/xml"
"github.com/fgrid/iso20022"
)
type Document00900101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document"`
Message *AcceptorReconciliationRequestV01 `xml:"AccptrRcncltnReq"`
}
func (d *Document00900101) AddMessage() *AcceptorReconciliationRequestV01 {
d.Message = new(AcceptorReconciliationRequestV01)
return d.Message
}
type AcceptorReconciliationRequestV01 struct {
Header *iso20022.Header1 `xml:"Hdr"`
ReconciliationRequest *iso20022.AcceptorReconciliationRequest1 `xml:"RcncltnReq"`
SecurityTrailer *iso20022.ContentInformationType3 `xml:"SctyTrlr"`
}
func (a *AcceptorReconciliationRequestV01) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest1 {
a.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest1)
return a.ReconciliationRequest
}
func (a *AcceptorReconciliationRequestV01) AddSecurityTrailer() *iso20022.ContentInformationType3 {
a.SecurityTrailer = new(iso20022.ContentInformationType3)
return a.SecurityTrailer
}
func (a *AcceptorReconciliationRequestV01) AddHeader() *iso20022.Header1 | {
a.Header = new(iso20022.Header1)
return a.Header
} |
package main
import (
"syscall"
)
func setRlimit() error | {
rlimit := int64(100000)
if rlimit > 0 {
var limit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
return err
}
if limit.Cur < rlimit {
limit.Cur = rlimit
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
return err
}
}
}
return nil
} |
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(serverAddress string) error {
delete(c.file.AuthConfigs, serverAddress)
return c.file.Save()
}
func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {
authConfig, ok := c.file.AuthConfigs[serverAddress]
if !ok {
for registry, ac := range c.file.AuthConfigs {
if serverAddress == convertToHostname(registry) {
return ac, nil
}
}
authConfig = types.AuthConfig{}
}
return authConfig, nil
}
func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {
return c.file.AuthConfigs, nil
}
func convertToHostname(url string) string {
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]
}
func (c *fileStore) Store(authConfig types.AuthConfig) error | {
c.file.AuthConfigs[authConfig.ServerAddress] = authConfig
return c.file.Save()
} |
package aggregator
import (
"github.com/CapillarySoftware/gostat/stat"
"math"
)
func Aggregate(stats []*stat.Stat) (aggregate StatsAggregate) {
if stats == nil || len(stats) == 0 {
return StatsAggregate{}
}
aggregate = StatsAggregate{Min : stats[0].Value, Max : stats[0].Value, Count : len(stats)}
sum := 0.0
for i := range stats {
v := stats[i].Value
sum += v
if v < aggregate.Min {
aggregate.Min = v
}
if v > aggregate.Max {
aggregate.Max = v
}
}
aggregate.Average = sum / float64(len(stats))
return
}
func AppendStatsAggregate(a, b StatsAggregate) (aggregate StatsAggregate) | {
if (a.Count == 0) {
return b
}
if (b.Count == 0) {
return a
}
aggregate.Average = ( (a.Average * float64(a.Count)) + (b.Average * float64(b.Count)) ) / float64(a.Count + b.Count)
aggregate.Min = math.Min(a.Min, b.Min)
aggregate.Max = math.Max(a.Max, b.Max)
aggregate.Count = a.Count + b.Count
return
} |
package contextutil_test
import (
"errors"
"testing"
"time"
"github.com/arjantop/cuirass/util/contextutil"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
func TestDoWithCancelErrorReturned(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := contextutil.DoWithCancel(ctx, func() {}, func() error {
return errors.New("foo")
})
assert.Equal(t, errors.New("foo"), err)
}
func TestDoWithCancelTimeout(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
defer cancel()
var called bool
err := contextutil.DoWithCancel(ctx, func() { called = true }, func() error {
time.Sleep(2 * time.Nanosecond)
return nil
})
assert.Equal(t, context.DeadlineExceeded, err)
}
func TestDoErrorReturned(t *testing.T) | {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := contextutil.Do(ctx, func() error {
return errors.New("foo")
})
assert.Equal(t, errors.New("foo"), err)
} |
package bits_test
import (
"github.com/twmb/bits"
"testing"
)
func TestSet(t *testing.T) {
for i := 0; i < 256; i++ {
if int(bits.SetU32(uint32(i))) != bits.Hamming(i, 0) {
t.Errorf("Error in set: wanted %v for %v, got %v",
bits.Hamming(i, 0), i, bits.SetU32(uint32(i)))
}
}
}
func BenchmarkSetKernighan(b *testing.B) {
for i := 0; i < b.N; i++ {
bits.SetKernighan(uint(i))
}
}
func BenchmarkSetU32(b *testing.B) {
for i := 0; i < b.N; i++ {
bits.SetU32(uint32(i))
}
}
func BenchmarkSetU64(b *testing.B) {
for i := 0; i < b.N; i++ {
bits.SetU64(uint64(i))
}
}
func BenchmarkSetTable(b *testing.B) | {
for i := 0; i < b.N; i++ {
bits.SetTable(i)
}
} |
package main
import (
"log"
"os"
"os/signal"
"syscall"
"github.com/opensourceorg/api/license"
)
type Blobs struct {
Licenses license.Licenses
LicenseIdMap map[string]license.License
LicenseTagMap map[string][]license.License
}
func loadBlob(path string, blob *Blobs) error {
licenses, err := license.LoadLicensesFiles(path)
if err != nil {
return err
}
licenseIdMap := licenses.GetIdMap()
licenseTagMap := licenses.GetTagMap()
blob.Licenses = licenses
blob.LicenseIdMap = licenseIdMap
blob.LicenseTagMap = licenseTagMap
return nil
}
func Reloader(file string, target *Blobs) | {
if err := loadBlob(file, target); err != nil {
panic(err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
for _ = range c {
if err := loadBlob(file, target); err != nil {
log.Printf("Error! Can not reload the JSON! - %s", err)
continue
}
}
} |
package iso20022
type ATMTransactionAmounts6 struct {
Currency *ActiveCurrencyCode `xml:"Ccy,omitempty"`
MaximumPossibleAmount *ImpliedCurrencyAndAmount `xml:"MaxPssblAmt,omitempty"`
MinimumPossibleAmount *ImpliedCurrencyAndAmount `xml:"MinPssblAmt,omitempty"`
AdditionalAmount []*ATMTransactionAmounts7 `xml:"AddtlAmt,omitempty"`
}
func (a *ATMTransactionAmounts6) SetMaximumPossibleAmount(value, currency string) {
a.MaximumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)
}
func (a *ATMTransactionAmounts6) SetMinimumPossibleAmount(value, currency string) {
a.MinimumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)
}
func (a *ATMTransactionAmounts6) AddAdditionalAmount() *ATMTransactionAmounts7 {
newValue := new(ATMTransactionAmounts7)
a.AdditionalAmount = append(a.AdditionalAmount, newValue)
return newValue
}
func (a *ATMTransactionAmounts6) SetCurrency(value string) | {
a.Currency = (*ActiveCurrencyCode)(&value)
} |
package systray
import "C"
import (
"unsafe"
)
func nativeLoop() {
C.nativeLoop()
}
func quit() {
C.quit()
}
func SetIcon(iconBytes []byte) {
cstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))
C.setIcon(cstr, (C.int)(len(iconBytes)))
}
func SetTitle(title string) {
C.setTitle(C.CString(title))
}
func SetTooltip(tooltip string) {
C.setTooltip(C.CString(tooltip))
}
func systray_ready() {
systrayReady()
}
func systray_menu_item_selected(cId C.int) {
systrayMenuItemSelected(int32(cId))
}
func addOrUpdateMenuItem(item *MenuItem) | {
var disabled C.short = 0
if item.disabled {
disabled = 1
}
var checked C.short = 0
if item.checked {
checked = 1
}
C.add_or_update_menu_item(
C.int(item.id),
C.CString(item.title),
C.CString(item.tooltip),
disabled,
checked,
)
} |
package displayers
import (
"fmt"
"io"
"github.com/digitalocean/doctl/do"
)
type Size struct {
Sizes do.Sizes
}
var _ Displayable = &Size{}
func (si *Size) JSON(out io.Writer) error {
return writeJSON(si.Sizes, out)
}
func (si *Size) ColMap() map[string]string {
return map[string]string{
"Slug": "Slug", "Memory": "Memory", "VCPUs": "VCPUs",
"Disk": "Disk", "PriceMonthly": "Price Monthly",
"PriceHourly": "Price Hourly",
}
}
func (si *Size) KV() []map[string]interface{} {
out := []map[string]interface{}{}
for _, s := range si.Sizes {
o := map[string]interface{}{
"Slug": s.Slug, "Memory": s.Memory, "VCPUs": s.Vcpus,
"Disk": s.Disk, "PriceMonthly": fmt.Sprintf("%0.2f", s.PriceMonthly),
"PriceHourly": s.PriceHourly,
}
out = append(out, o)
}
return out
}
func (si *Size) Cols() []string | {
return []string{
"Slug", "Memory", "VCPUs", "Disk", "PriceMonthly", "PriceHourly",
}
} |
package build
import "github.com/docker/docker/api/server/router"
type buildRouter struct {
backend Backend
routes []router.Route
}
func NewRouter(b Backend) router.Router {
r := &buildRouter{
backend: b,
}
r.initRoutes()
return r
}
func (r *buildRouter) initRoutes() {
r.routes = []router.Route{
router.NewPostRoute("/build", r.postBuild),
}
}
func (r *buildRouter) Routes() []router.Route | {
return r.routes
} |
package migrations
import (
"database/sql"
"github.com/pressly/goose"
)
func init() {
goose.AddMigration(up00002, down00002)
}
func down00002(tx *sql.Tx) error {
_, err := tx.Exec(`DROP TABLE users`)
return err
}
func up00002(tx *sql.Tx) error | {
_, err := tx.Exec(`CREATE TABLE IF NOT EXISTS users (email text)`)
return err
} |
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("User-Agent")
if ua == "" {
ua = userAgent
} else {
ua = fmt.Sprintf("%s;%s", ua, userAgent)
}
req.Header.Set("User-Agent", ua)
return t.Base.RoundTrip(req)
}
func cloneRequest(r *http.Request) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
func ProjID(ctx context.Context) string {
return ctx.Value(ContextKey("base")).(map[string]interface{})["project_id"].(string)
}
func HttpClient(ctx context.Context) *http.Client {
return ctx.Value(ContextKey("base")).(map[string]interface{})["http_client"].(*http.Client)
}
func Namespace(ctx context.Context) string | {
v := ctx.Value(ContextKey("namespace"))
if v == nil {
return ""
} else {
return v.(string)
}
} |
package app
import (
"net/url"
)
type Service interface {
ProxyPath() string
URL() string
BasicAuth() (username, password string, ok bool)
AddSecret(parameters url.Values)
}
type basicAuthService struct {
proxyPath, url, clientId, clientSecret string
}
func (s basicAuthService) ProxyPath() string {
return s.proxyPath
}
func (s basicAuthService) BasicAuth() (string, string, bool) {
return s.clientId, s.clientSecret, true
}
func (s basicAuthService) AddSecret(parameters url.Values) {
}
type addParameterService struct {
proxyPath, url, parameterName, clientSecret string
}
func (s addParameterService) ProxyPath() string {
return s.proxyPath
}
func (s addParameterService) URL() string {
return s.url
}
func (s addParameterService) BasicAuth() (string, string, bool) {
return "", "", false
}
func (s addParameterService) AddSecret(parameters url.Values) {
parameters.Add(s.parameterName, s.clientSecret)
}
func BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {
return basicAuthService{proxyPath, url, clientId, clientSecret}
}
func AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {
return addParameterService{proxyPath, url, parameterName, clientSecret}
}
func (s basicAuthService) URL() string | {
return s.url
} |
package iso20022
type PlainCardData4 struct {
PAN *Min8Max28NumericText `xml:"PAN"`
CardSequenceNumber *Min2Max3NumericText `xml:"CardSeqNb,omitempty"`
EffectiveDate *Max10Text `xml:"FctvDt,omitempty"`
ExpiryDate *Max10Text `xml:"XpryDt"`
ServiceCode *Exact3NumericText `xml:"SvcCd,omitempty"`
TrackData []*TrackData1 `xml:"TrckData,omitempty"`
CardSecurityCode *CardSecurityInformation1 `xml:"CardSctyCd,omitempty"`
}
func (p *PlainCardData4) SetPAN(value string) {
p.PAN = (*Min8Max28NumericText)(&value)
}
func (p *PlainCardData4) SetEffectiveDate(value string) {
p.EffectiveDate = (*Max10Text)(&value)
}
func (p *PlainCardData4) SetExpiryDate(value string) {
p.ExpiryDate = (*Max10Text)(&value)
}
func (p *PlainCardData4) SetServiceCode(value string) {
p.ServiceCode = (*Exact3NumericText)(&value)
}
func (p *PlainCardData4) AddTrackData() *TrackData1 {
newValue := new(TrackData1)
p.TrackData = append(p.TrackData, newValue)
return newValue
}
func (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {
p.CardSecurityCode = new(CardSecurityInformation1)
return p.CardSecurityCode
}
func (p *PlainCardData4) SetCardSequenceNumber(value string) | {
p.CardSequenceNumber = (*Min2Max3NumericText)(&value)
} |
package geth
import (
"errors"
"fmt"
)
type Strings struct{ strs []string }
func (s *Strings) Size() int {
return len(s.strs)
}
func (s *Strings) Get(index int) (str string, _ error) {
if index < 0 || index >= len(s.strs) {
return "", errors.New("index out of bounds")
}
return s.strs[index], nil
}
func (s *Strings) Set(index int, str string) error {
if index < 0 || index >= len(s.strs) {
return errors.New("index out of bounds")
}
s.strs[index] = str
return nil
}
func (s *Strings) String() string | {
return fmt.Sprintf("%v", s.strs)
} |
package ergo_test
import (
"fmt"
"testing"
"github.com/gima/ergo/v1"
"github.com/gima/ergo/v1/pp"
"github.com/stretchr/testify/require"
)
func TestComposer_AddLinked(t *testing.T) {
olde := fmt.Errorf("")
oldE := ergo.New("").Err()
E := ergo.New("").AddLinked(olde, oldE).Err()
require.Equal(t, 2, E.Linked().Len())
require.Equal(t, olde, E.Linked().Get(0))
require.Equal(t, oldE, E.Linked().Get(1))
}
func TestComposer_SetCause(t *testing.T) {
oldE := ergo.New("").Err()
E := ergo.New("").SetCause(oldE).Err()
require.Equal(t, oldE, E.Cause())
olde := fmt.Errorf("")
E = ergo.New("").SetCause(olde).Err()
require.Equal(t, olde, E.Cause())
}
func TestComposer_SetPub(t *testing.T) {
E := ergo.New("").SetPub("Public Message").Err()
require.Equal(t, "Public Message", E.PublicError())
}
func TestComposer_SkipStackRetainsOne(t *testing.T) {
E := ergo.New("").
SkipStack(-1).
SkipStack(1000).
SkipStack(1).
SkipStack(0).
SkipStack(-1).
Err()
require.Equal(t, 1, E.StackTrace().Len())
}
func TestComposer_AddContext(t *testing.T) | {
E := ergo.New("").Err()
require.Equal(t, 0, E.Context().Len())
E = ergo.New("").AddContext("K1", "V1").Err()
require.Equal(t, 1, E.Context().Len())
k, v := E.Context().Get(0)
require.Equal(t, "K1V1", k+v)
E = ergo.New("").AddContextFrom(pp.Map{"K1": "V1"}).Err()
require.Equal(t, 1, E.Context().Len())
k, v = E.Context().Get(0)
require.Equal(t, "K1V1", k+v)
} |
package log15
import (
"sync/atomic"
"unsafe"
)
type swapHandler struct {
handler unsafe.Pointer
}
func (h *swapHandler) Log(r *Record) error {
return (*(*Handler)(atomic.LoadPointer(&h.handler))).Log(r)
}
func (h *swapHandler) Swap(newHandler Handler) | {
atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler))
} |
package types
import (
"math"
)
func RoundFloat(val float64) float64 {
v, frac := math.Modf(val)
if val >= 0.0 {
if frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) {
v += 1.0
}
} else {
if frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) {
v -= 1.0
}
}
return v
}
func getMaxFloat(flen int, decimal int) float64 {
intPartLen := flen - decimal
f := math.Pow10(intPartLen)
f -= math.Pow10(-decimal)
return f
}
func TruncateFloat(f float64, flen int, decimal int) (float64, error) {
if math.IsNaN(f) {
return 0, nil
}
maxF := getMaxFloat(flen, decimal)
if !math.IsInf(f, 0) {
f = truncateFloat(f, decimal)
}
if f > maxF {
f = maxF
} else if f < -maxF {
f = -maxF
}
return f, nil
}
func truncateFloat(f float64, decimal int) float64 | {
pow := math.Pow10(decimal)
t := (f - math.Floor(f)) * pow
round := RoundFloat(t)
f = math.Floor(f) + round/pow
return f
} |
package hook
import (
"fmt"
"gopkg.in/juju/charm.v6-unstable/hooks"
"gopkg.in/juju/names.v2"
)
const (
LeaderElected hooks.Kind = "leader-elected"
LeaderDeposed hooks.Kind = "leader-deposed"
LeaderSettingsChanged hooks.Kind = "leader-settings-changed"
)
type Info struct {
Kind hooks.Kind `yaml:"kind"`
RelationId int `yaml:"relation-id,omitempty"`
RemoteUnit string `yaml:"remote-unit,omitempty"`
ChangeVersion int64 `yaml:"change-version,omitempty"`
StorageId string `yaml:"storage-id,omitempty"`
}
type Committer interface {
CommitHook(Info) error
}
type Validator interface {
ValidateHook(Info) error
}
func (hi Info) Validate() error | {
switch hi.Kind {
case hooks.RelationJoined, hooks.RelationChanged, hooks.RelationDeparted:
if hi.RemoteUnit == "" {
return fmt.Errorf("%q hook requires a remote unit", hi.Kind)
}
fallthrough
case hooks.Install, hooks.Start, hooks.ConfigChanged, hooks.UpgradeCharm, hooks.Stop, hooks.RelationBroken,
hooks.CollectMetrics, hooks.MeterStatusChanged, hooks.UpdateStatus:
return nil
case hooks.Action:
return fmt.Errorf("hooks.Kind Action is deprecated")
case hooks.StorageAttached, hooks.StorageDetaching:
if !names.IsValidStorage(hi.StorageId) {
return fmt.Errorf("invalid storage ID %q", hi.StorageId)
}
return nil
case LeaderElected, LeaderDeposed, LeaderSettingsChanged:
return nil
}
return fmt.Errorf("unknown hook kind %q", hi.Kind)
} |
package core
import (
"github.com/google/blueprint"
)
type generateBinary struct {
generateLibrary
}
var _ generateLibraryInterface = (*generateBinary)(nil)
var _ singleOutputModule = (*generateBinary)(nil)
var _ splittable = (*generateBinary)(nil)
var _ blueprint.Module = (*generateBinary)(nil)
func (m *generateBinary) generateInouts(ctx blueprint.ModuleContext, g generatorBackend) []inout {
return generateLibraryInouts(m, ctx, g, m.Properties.Headers)
}
func (m *generateBinary) outputFileName() string {
return m.altName() + m.libExtension()
}
func (m *generateBinary) GenerateBuildActions(ctx blueprint.ModuleContext) {
if isEnabled(m) {
g := getBackend(ctx)
g.genBinaryActions(m, ctx)
}
}
func genBinaryFactory(config *bobConfig) (blueprint.Module, []interface{}) {
module := &generateBinary{}
module.generateCommon.init(&config.Properties, GenerateProps{})
return module, []interface{}{
&module.SimpleName.Properties,
&module.generateCommon.Properties,
&module.Properties,
}
}
func (m *generateBinary) libExtension() string | {
return ""
} |
package version
import (
"bytes"
"fmt"
)
var (
GitCommit string
Version = "0.13.0"
VersionPrerelease = "dev"
VersionMetadata = ""
)
type VersionInfo struct {
Revision string
Version string
VersionPrerelease string
VersionMetadata string
}
func (c *VersionInfo) VersionNumber(rev bool) string {
var versionString bytes.Buffer
fmt.Fprintf(&versionString, "v%s", c.Version)
if c.VersionPrerelease != "" {
fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease)
}
if c.VersionMetadata != "" {
fmt.Fprintf(&versionString, "+%s", c.VersionMetadata)
}
if rev && c.Revision != "" {
fmt.Fprintf(&versionString, " (%s)", c.Revision)
}
return versionString.String()
}
func GetVersion() *VersionInfo | {
ver := Version
rel := VersionPrerelease
md := VersionMetadata
return &VersionInfo{
Revision: GitCommit,
Version: ver,
VersionPrerelease: rel,
VersionMetadata: md,
}
} |
package iso20022
type PaymentTransaction17 struct {
SettlementAmount *ActiveCurrencyAndAmount `xml:"SttlmAmt,omitempty"`
SettlementDate *ISODate `xml:"SttlmDt,omitempty"`
PaymentInstrument *PaymentInstrument9Choice `xml:"PmtInstrm,omitempty"`
}
func (p *PaymentTransaction17) SetSettlementDate(value string) {
p.SettlementDate = (*ISODate)(&value)
}
func (p *PaymentTransaction17) AddPaymentInstrument() *PaymentInstrument9Choice {
p.PaymentInstrument = new(PaymentInstrument9Choice)
return p.PaymentInstrument
}
func (p *PaymentTransaction17) SetSettlementAmount(value, currency string) | {
p.SettlementAmount = NewActiveCurrencyAndAmount(value, currency)
} |
package runconfig
import (
"fmt"
"strings"
)
func validateNetMode(vals *validateNM) error {
if (vals.netMode.IsHost() || vals.netMode.IsContainer()) && *vals.flHostname != "" {
return ErrConflictNetworkHostname
}
if vals.netMode.IsHost() && vals.flLinks.Len() > 0 {
return ErrConflictHostNetworkAndLinks
}
if vals.netMode.IsContainer() && vals.flLinks.Len() > 0 {
return ErrConflictContainerNetworkAndLinks
}
if (vals.netMode.IsHost() || vals.netMode.IsContainer()) && vals.flDNS.Len() > 0 {
return ErrConflictNetworkAndDNS
}
if (vals.netMode.IsContainer() || vals.netMode.IsHost()) && vals.flExtraHosts.Len() > 0 {
return ErrConflictNetworkHosts
}
if (vals.netMode.IsContainer() || vals.netMode.IsHost()) && *vals.flMacAddress != "" {
return ErrConflictContainerNetworkAndMac
}
if vals.netMode.IsContainer() && (vals.flPublish.Len() > 0 || *vals.flPublishAll == true) {
return ErrConflictNetworkPublishPorts
}
if vals.netMode.IsContainer() && vals.flExpose.Len() > 0 {
return ErrConflictNetworkExposePorts
}
return nil
}
func parseNetMode(netMode string) (NetworkMode, error) | {
parts := strings.Split(netMode, ":")
switch mode := parts[0]; mode {
case "default", "bridge", "none", "host":
case "container":
if len(parts) < 2 || parts[1] == "" {
return "", fmt.Errorf("invalid container format container:<name|id>")
}
default:
return "", fmt.Errorf("invalid --net: %s", netMode)
}
return NetworkMode(netMode), nil
} |
package cronjob
import (
context "context"
v1beta1 "k8s.io/client-go/informers/batch/v1beta1"
factory "knative.dev/pkg/client/injection/kube/informers/factory"
controller "knative.dev/pkg/controller"
injection "knative.dev/pkg/injection"
logging "knative.dev/pkg/logging"
)
func init() {
injection.Default.RegisterInformer(withInformer)
}
type Key struct{}
func Get(ctx context.Context) v1beta1.CronJobInformer {
untyped := ctx.Value(Key{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch k8s.io/client-go/informers/batch/v1beta1.CronJobInformer from context.")
}
return untyped.(v1beta1.CronJobInformer)
}
func withInformer(ctx context.Context) (context.Context, controller.Informer) | {
f := factory.Get(ctx)
inf := f.Batch().V1beta1().CronJobs()
return context.WithValue(ctx, Key{}, inf), inf.Informer()
} |
package associations_test
import (
"reflect"
"testing"
"github.com/gobuffalo/pop/associations"
"github.com/gobuffalo/pop/nulls"
"github.com/stretchr/testify/require"
)
type FooHasMany struct {
ID int `db:"id"`
BarHasManies *barHasManies `has_many:"bar_has_manies"`
}
type barHasMany struct {
Title string `db:"title"`
FooHasManyID nulls.Int `db:"foo_has_many_id"`
}
type barHasManies []barHasMany
func Test_Has_Many_SetValue(t *testing.T) {
a := require.New(t)
foo := FooHasMany{ID: 1, BarHasManies: &barHasManies{{Title: "bar"}}}
as, _ := associations.ForStruct(&foo)
a.Equal(len(as), 1)
ca, ok := as[0].(associations.AssociationAfterCreatable)
a.True(ok)
ca.AfterSetup()
a.Equal(foo.ID, (*foo.BarHasManies)[0].FooHasManyID.Interface().(int))
}
func Test_Has_Many_Association(t *testing.T) | {
a := require.New(t)
id := 1
foo := FooHasMany{ID: 1}
as, err := associations.ForStruct(&foo)
a.NoError(err)
a.Equal(len(as), 1)
a.Equal(reflect.Slice, as[0].Kind())
where, args := as[0].Constraint()
a.Equal("foo_has_many_id = ?", where)
a.Equal(id, args[0].(int))
} |
package auth
import (
"context"
)
type tokenNop struct{}
func (t *tokenNop) enable() {}
func (t *tokenNop) disable() {}
func (t *tokenNop) invalidateUser(string) {}
func (t *tokenNop) genTokenPrefix() (string, error) { return "", nil }
func (t *tokenNop) assign(ctx context.Context, username string, revision uint64) (string, error) {
return "", ErrAuthFailed
}
func newTokenProviderNop() (*tokenNop, error) {
return &tokenNop{}, nil
}
func (t *tokenNop) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) | {
return nil, false
} |
package validate
import (
"io/ioutil"
"os"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
var (
logMutex = &sync.Mutex{}
)
func TestDebug(t *testing.T) | {
if !enableLongTests {
skipNotify(t)
t.SkipNow()
}
tmpFile, _ := ioutil.TempFile("", "debug-test")
tmpName := tmpFile.Name()
defer func() {
Debug = false
logMutex.Unlock()
os.Remove(tmpName)
}()
logMutex.Lock()
Debug = true
debugOptions()
defer func() {
validateLogger.SetOutput(os.Stdout)
}()
validateLogger.SetOutput(tmpFile)
debugLog("A debug")
Debug = false
tmpFile.Close()
flushed, _ := os.Open(tmpName)
buf := make([]byte, 500)
flushed.Read(buf)
validateLogger.SetOutput(os.Stdout)
assert.Contains(t, string(buf), "A debug")
} |
package spatial
import "fmt"
func (p Polygon) string() string {
s := "("
for _, line := range p {
s += fmt.Sprintf("%v, ", line)
}
return s[:len(s)-2] + ")"
}
func (l Line) string() string | {
s := ""
for _, point := range l {
s += fmt.Sprintf("%v, ", point)
}
return s[:len(s)-2]
} |
package application
import (
"encoding/base64"
"github.com/gorilla/securecookie"
"net/http"
"testing"
)
const cookieName = "recaptcha"
const testHashKey = "RovMQmutMbSogUuGQFZYLb37jwgwFNuMR7wrEz9EILQ9W039UHCFlCfkpX1EbecktHA563XX+7clPRinBPeaeQ=="
const testBlockKey = "+sSXCAbwswiYNqHx4zCuJJTD3hmRQp4f4uJKy+aFL70="
func generateGorillaSecureCookie() *securecookie.SecureCookie {
hashKey, _ := base64.StdEncoding.DecodeString(testHashKey)
blockKey, _ := base64.StdEncoding.DecodeString(testBlockKey)
return securecookie.New(hashKey, blockKey)
}
func TestNewSecureRecaptchaCookie(t *testing.T) {
secureRecaptchaCookie1 := NewSecureRecaptchaCookie(cookieName, nil, generateGorillaSecureCookie())
if secureRecaptchaCookie1.Name != cookieName || len(secureRecaptchaCookie1.Value) != 0 {
t.Error("The new secure cookie based on an empty cookie should have no value")
}
validCookie := &http.Cookie{Value: "Some Value"}
secureRecaptchaCookie2 := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())
if secureRecaptchaCookie2.Name != cookieName || len(secureRecaptchaCookie2.Value) == 0 {
t.Error("The new secure cookie based on a valid cookie should have a value")
}
}
func TestSecureRecaptchaCookie_Encode(t *testing.T) | {
validCookie := &http.Cookie{Value: "Some Value"}
secureRecaptchaCookie := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())
secureRecaptchaCookie.Value = secureRecaptchaCookie.Encode(validCookie.Value)
if secureRecaptchaCookie.IsValid(validCookie.Value) != true {
t.Error("The cookie value should have been encoded and decoded correctly")
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.