input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package main
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"text/template"
"github.com/golang/glog"
k8sexec "k8s.io/kubernetes/pkg/util/exec"
)
const (
nsdTmpl = `
`
)
type record struct {
name string
ip net.IP
}
type nsd struct {
ns []record
a []record
}
func (k *nsd) Start() {
cmd := exec.Command("/usr/sbin/nsd",
"-d",
"-P", "/nsd.pid")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
glog.Errorf("nsd error: %v", err)
}
if err := cmd.Wait(); err != nil {
glog.Fatalf("nsd error: %v", err)
}
}
func (k *nsd) Reload() error {
glog.Info("reloading nsd server")
_, err := k8sexec.New().Command("killall", "-1", "nsd").CombinedOutput()
if err != nil {
return fmt.Errorf("error reloading nsd: %v", err)
}
return nil
}
func (k *nsd) WriteCfg(svcs []vip) error | {
w, err := os.Create("/etc/nsd/nsd.conf.")
if err != nil {
return err
}
defer w.Close()
t, err := template.New("nsd").Parse(nsdTmpl)
if err != nil {
return err
}
conf := make(map[string]interface{})
conf["ns"] = k.iface
conf["a"] = k.ip
b, _ := json.Marshal(conf)
glog.Infof("%v", string(b))
return t.Execute(w, conf)
} |
package engine
import (
"time"
"github.com/aws/amazon-ecs-agent/agent/api"
)
type impossibleTransitionError struct {
state api.ContainerStatus
}
func (err *impossibleTransitionError) Error() string {
return "Cannot transition to " + err.state.String()
}
func (err *impossibleTransitionError) ErrorName() string { return "ImpossibleStateTransitionError" }
type DockerTimeoutError struct {
duration time.Duration
transition string
}
func (err *DockerTimeoutError) Error() string {
return "Could not transition to " + err.transition + "; timed out after waiting " + err.duration.String()
}
func (err *DockerTimeoutError) ErrorName() string { return "DockerTimeoutError" }
type ContainerVanishedError struct{}
func (err ContainerVanishedError) Error() string { return "No container matching saved ID found" }
func (err ContainerVanishedError) ErrorName() string { return "ContainerVanishedError" }
type CannotXContainerError struct {
transition string
msg string
}
func (err CannotXContainerError) Error() string { return err.msg }
func (err CannotXContainerError) ErrorName() string {
return "Cannot" + err.transition + "ContainerError"
}
type OutOfMemoryError struct{}
func (err OutOfMemoryError) Error() string { return "Container killed due to memory usage" }
func (err OutOfMemoryError) ErrorName() string { return "OutOfMemoryError" }
type DockerStateError struct {
dockerError string
name string
}
func (err DockerStateError) Error() string {
return err.dockerError
}
func (err DockerStateError) ErrorName() string {
return err.name
}
func NewDockerStateError(err string) DockerStateError | {
return DockerStateError{
dockerError: err,
name: "DockerStateError",
}
} |
package roles
import (
"strconv"
"strings"
)
var TopLevelRoles = map[string]struct{}{
"root": {},
"targets": {},
"snapshot": {},
"timestamp": {},
}
func IsDelegatedTargetsRole(name string) bool {
return !IsTopLevelRole(name)
}
func IsTopLevelManifest(name string) bool {
return IsTopLevelRole(strings.TrimSuffix(name, ".json"))
}
func IsDelegatedTargetsManifest(name string) bool {
return !IsTopLevelManifest(name)
}
func IsVersionedManifest(name string) bool {
parts := strings.Split(name, ".")
if len(parts) < 3 {
return false
}
_, err := strconv.Atoi(parts[0])
return err == nil
}
func IsTopLevelRole(name string) bool | {
_, ok := TopLevelRoles[name]
return ok
} |
package iddispatcher
import "fmt"
type Dispatch struct {
id chan int
duringLoad chan int
maxValue int
nowID int
}
const idDefaultCount = 10
const idDefaultLoadCount = idDefaultCount
const idDefaultValue = 0
func GetADispather(maxvalue int) Dispatcher {
if maxvalue < 1 {
panic(fmt.Sprintf("error maxvalue: %v", maxvalue))
}
return &Dispatch{
id: make(chan int, idDefaultCount),
duringLoad: make(chan int, 1),
maxValue: maxvalue,
nowID: idDefaultValue,
}
}
func reloadIDs(dispatch *Dispatch) {
if len(dispatch.id) > 0 {
return
}
dispatch.duringLoad <- 1
if len(dispatch.id) > 0 {
<-dispatch.duringLoad
return
}
for i := 1; i <= idDefaultLoadCount; i++ {
if dispatch.nowID > dispatch.maxValue {
dispatch.nowID = idDefaultValue + 1
} else {
dispatch.nowID++
}
select {
case dispatch.id <- dispatch.nowID:
default:
<-dispatch.duringLoad
return
}
}
<-dispatch.duringLoad
}
func (patcher *Dispatch) GetID() int | {
if nil == patcher {
return -1
}
for {
select {
case id := <-patcher.id:
return id
default:
reloadIDs(patcher)
}
}
} |
package async
import (
"sync"
"time"
)
type TTLCache interface {
Get(key string) (value interface{}, expired bool, ok bool)
Set(key string, value interface{})
Delete(key string)
}
type ttlCacheEntry struct {
value interface{}
expiry time.Time
}
type ttlCache struct {
mu sync.RWMutex
cache map[string]*ttlCacheEntry
ttl time.Duration
}
func (t *ttlCache) Get(key string) (value interface{}, expired bool, ok bool) {
t.mu.RLock()
defer t.mu.RUnlock()
if _, iok := t.cache[key]; !iok {
return nil, false, false
}
entry := t.cache[key]
expired = time.Now().After(entry.expiry)
return entry.value, expired, true
}
func (t *ttlCache) Set(key string, value interface{}) {
t.mu.Lock()
defer t.mu.Unlock()
t.cache[key] = &ttlCacheEntry{
value: value,
expiry: time.Now().Add(t.ttl),
}
}
func (t *ttlCache) Delete(key string) {
t.mu.Lock()
defer t.mu.Unlock()
delete(t.cache, key)
}
func NewTTLCache(ttl time.Duration) TTLCache | {
return &ttlCache{
ttl: ttl,
cache: make(map[string]*ttlCacheEntry),
}
} |
package musicserver
import (
"net/http"
"time"
)
func adminHandler(w http.ResponseWriter, req *http.Request) {
ip := getIPFromRequest(req)
if ad.ValidSession(ip) {
tl.Render(w, "admin", newPlaylistInfo(ip))
} else {
http.Redirect(w, req, url("/admin/login"), http.StatusFound)
}
}
func adminLoginHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
tl.Render(w, "admin_login", nil)
return
}
ip := getIPFromRequest(req)
pwd := req.PostFormValue("admin_pwd")
if ad.ValidPassword(pwd) {
ad.StartSession(ip)
http.Redirect(w, req, url("/admin"), http.StatusSeeOther)
return
} else {
tl.Render(w, "admin_bad_login", nil)
return
}
}
func adminLogoutHandler(w http.ResponseWriter, req *http.Request) {
ip := getIPFromRequest(req)
ad.EndSession(ip)
http.Redirect(w, req, url("/"), http.StatusSeeOther)
}
func adminKillVideoHandler(w http.ResponseWriter, req *http.Request) {
ip := getIPFromRequest(req)
if !ad.ValidSession(ip) {
http.Redirect(w, req, url("/admin/login"), http.StatusFound)
return
}
vd.End()
time.Sleep(500 * time.Millisecond)
http.Redirect(w, req, url("/admin"), http.StatusFound)
}
func adminRemoveHandler(w http.ResponseWriter, req *http.Request) | {
ip := getIPFromRequest(req)
if req.Method == http.MethodPost && ad.ValidSession(ip) {
remUUID := req.PostFormValue("video_id")
pl.RemoveVideo(remUUID)
}
http.Redirect(w, req, url("/admin"), http.StatusSeeOther)
} |
package lzma
import (
"errors"
"fmt"
"unicode"
)
type operation interface {
Len() int
}
type match struct {
distance int64
n int
}
func (m match) verify() error {
if !(minDistance <= m.distance && m.distance <= maxDistance) {
return errors.New("distance out of range")
}
if !(1 <= m.n && m.n <= maxMatchLen) {
return errors.New("length out of range")
}
return nil
}
func (m match) l() uint32 {
return uint32(m.n - minMatchLen)
}
func (m match) dist() uint32 {
return uint32(m.distance - minDistance)
}
func (m match) Len() int {
return m.n
}
type lit struct {
b byte
}
func (l lit) Len() int {
return 1
}
func (l lit) String() string {
var c byte
if unicode.IsPrint(rune(l.b)) {
c = l.b
} else {
c = '.'
}
return fmt.Sprintf("L{%c/%02x}", c, l.b)
}
func (m match) String() string | {
return fmt.Sprintf("M{%d,%d}", m.distance, m.n)
} |
package benchmarks
import (
"io/ioutil"
"testing"
"time"
"github.com/go-kit/kit/log"
)
func newKit() *log.Context {
return log.NewContext(log.NewJSONLogger(ioutil.Discard))
}
func BenchmarkGoKitAddingFields(b *testing.B) {
logger := newKit()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.With(
"int", 1,
"int64", int64(1),
"float", 3.0,
"string", "four!",
"bool", true,
"time", time.Unix(0, 0),
"error", errExample.Error(),
"duration", time.Second,
"user-defined type", _jane,
"another string", "done!",
).Log("Go fast.")
}
})
}
func BenchmarkGoKitWithoutFields(b *testing.B) {
logger := newKit()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Log("Go fast.")
}
})
}
func BenchmarkGoKitWithAccumulatedContext(b *testing.B) | {
logger := newKit().With(
"int", 1,
"int64", int64(1),
"float", 3.0,
"string", "four!",
"bool", true,
"time", time.Unix(0, 0),
"error", errExample.Error(),
"duration", time.Second,
"user-defined type", _jane,
"another string", "done!",
)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.Log("Go really fast.")
}
})
} |
package http
import (
"github.com/wcong/ants-go/ants/util"
"log"
Http "net/http"
"strconv"
"sync"
)
type HttpServer struct {
Http.Server
}
func (this *HttpServer) Start(wg sync.WaitGroup) {
go this.server(wg)
}
func (this *HttpServer) server(wg sync.WaitGroup) {
log.Println("start to server http" + this.Addr)
err := this.ListenAndServe()
if err != nil {
log.Panicln(err)
}
log.Println("http server down")
wg.Done()
}
func NewHttpServer(setting *util.Settings, handler Http.Handler) *HttpServer | {
port := strconv.Itoa(setting.HttpPort)
httpServer := &HttpServer{
Http.Server{
Addr: ":" + port,
Handler: handler,
},
}
return httpServer
} |
package server
import (
"math/rand"
"time"
"github.com/kyokomi/expcache"
)
type ImageCache interface {
GetRandomImageURL() string
}
type imageCache struct {
Expire expcache.ExpireOnMemoryCache
cache []string
twAPI TwitterAPI
rd *rand.Rand
twitterID string
cacheCnt int
}
func (c *imageCache) GetRandomImageURL() string {
var result string
c.Expire.WithRefreshLock(time.Now(), func() {
idx := c.rd.Int31n(int32(len(c.cache))) - 1
result = c.cache[idx]
})
return result
}
func (c *imageCache) Refresh() error {
images, err := c.twAPI.GetFavoritesImages(c.cacheCnt, c.twitterID)
if err != nil {
return err
}
c.cache = images
return nil
}
var _ expcache.OnMemoryCache = (*imageCache)(nil)
var _ ImageCache = (*imageCache)(nil)
func NewImageCache(twAPI TwitterAPI, twitterID string, cacheCnt int) ImageCache | {
e := &imageCache{
cache: []string{},
twAPI: twAPI,
rd: rand.New(rand.NewSource(time.Now().UnixNano())),
twitterID: twitterID,
cacheCnt: cacheCnt,
}
e.Expire = expcache.NewExpireMemoryCache(e, 24*time.Hour)
return e
} |
package osenv
import (
"os"
"path/filepath"
"runtime"
)
const (
JujuEnv = "JUJU_ENV"
JujuHome = "JUJU_HOME"
JujuRepository = "JUJU_REPOSITORY"
JujuLoggingConfig = "JUJU_LOGGING_CONFIG"
JujuContainerType = "JUJU_CONTAINER_TYPE"
)
func jujuHomeLinux() string {
home := Home()
if home == "" {
return ""
}
return filepath.Join(home, ".juju")
}
func jujuHomeWin() string {
appdata := os.Getenv("APPDATA")
if appdata == "" {
return ""
}
return filepath.Join(appdata, "Juju")
}
func JujuHomeDir() string | {
jujuHome := os.Getenv(JujuHome)
if jujuHome == "" {
if runtime.GOOS == "windows" {
jujuHome = jujuHomeWin()
} else {
jujuHome = jujuHomeLinux()
}
}
return jujuHome
} |
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)
}
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)
}
func (rp ResourceInstancePhase) String() string | {
return fmt.Sprintf("%s#%s", rp.ResourceInstance, rp.Phase)
} |
package goleveldb
import (
store "github.com/blevesearch/upsidedown_store_api"
"github.com/syndtr/goleveldb/leveldb"
)
type Batch struct {
store *Store
merge *store.EmulatedMerge
batch *leveldb.Batch
}
func (b *Batch) Set(key, val []byte) {
b.batch.Put(key, val)
}
func (b *Batch) Delete(key []byte) {
b.batch.Delete(key)
}
func (b *Batch) Merge(key, val []byte) {
b.merge.Merge(key, val)
}
func (b *Batch) Reset() {
b.batch.Reset()
b.merge = store.NewEmulatedMerge(b.store.mo)
}
func (b *Batch) Close() error | {
b.batch.Reset()
b.batch = nil
b.merge = nil
return nil
} |
package fingerprint
import (
"testing"
"github.com/hashicorp/nomad/client/config"
"github.com/hashicorp/nomad/helper/testlog"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/stretchr/testify/require"
)
func TestMemoryFingerprint_Override(t *testing.T) {
f := NewMemoryFingerprint(testlog.HCLogger(t))
node := &structs.Node{
Attributes: make(map[string]string),
}
memoryMB := 15000
request := &FingerprintRequest{Config: &config.Config{MemoryMB: memoryMB}, Node: node}
var response FingerprintResponse
err := f.Fingerprint(request, &response)
if err != nil {
t.Fatalf("err: %v", err)
}
assertNodeAttributeContains(t, response.Attributes, "memory.totalbytes")
require := require.New(t)
require.NotNil(response.Resources)
require.EqualValues(response.Resources.MemoryMB, memoryMB)
require.NotNil(response.NodeResources)
require.EqualValues(response.NodeResources.Memory.MemoryMB, memoryMB)
}
func TestMemoryFingerprint(t *testing.T) | {
require := require.New(t)
f := NewMemoryFingerprint(testlog.HCLogger(t))
node := &structs.Node{
Attributes: make(map[string]string),
}
request := &FingerprintRequest{Config: &config.Config{}, Node: node}
var response FingerprintResponse
err := f.Fingerprint(request, &response)
require.NoError(err)
assertNodeAttributeContains(t, response.Attributes, "memory.totalbytes")
require.NotNil(response.Resources, "expected response Resources to not be nil")
require.NotZero(response.Resources.MemoryMB, "expected memory to be non-zero")
require.NotNil(response.NodeResources, "expected response NodeResources to not be nil")
require.NotZero(response.NodeResources.Memory.MemoryMB, "expected memory to be non-zero")
} |
package keymanagement
import (
"github.com/oracle/oci-go-sdk/v46/common"
"net/http"
)
type ImportKeyVersionRequest struct {
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
ImportKeyVersionDetails `contributesTo:"body"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
RequestMetadata common.RequestMetadata
}
func (request ImportKeyVersionRequest) String() string {
return common.PointerString(request)
}
func (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
func (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
func (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
type ImportKeyVersionResponse struct {
RawResponse *http.Response
KeyVersion `presentIn:"body"`
Etag *string `presentIn:"header" name:"etag"`
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ImportKeyVersionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
func (response ImportKeyVersionResponse) String() string | {
return common.PointerString(response)
} |
package yaml
import (
"github.com/pinpt/dialect/pkg"
"github.com/pinpt/dialect/pkg/types"
)
type YAMLExaminer struct {
}
func (e *YAMLExaminer) Examine(language string, filename string, line *types.DialectLine) error {
pkg.SingleSymbolProcessor("#", line)
return nil
}
func init() {
types.RegisterExaminer("YAML", &YAMLExaminer{})
}
func (e *YAMLExaminer) NewExaminer() types.DialectExaminer | {
ex := new(YAMLExaminer)
return ex
} |
package merkledag
import (
"context"
cid "gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid"
ipld "gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format"
)
type ErrorService struct {
Err error
}
var _ ipld.DAGService = (*ErrorService)(nil)
func (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error {
return cs.Err
}
func (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) {
return nil, cs.Err
}
func (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption {
ch := make(chan *ipld.NodeOption)
close(ch)
return ch
}
func (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error {
return cs.Err
}
func (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error {
return cs.Err
}
func (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error | {
return cs.Err
} |
package v1
import (
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
rest "k8s.io/client-go/rest"
v1 "k8s.io/code-generator/_examples/crd/apis/example/v1"
"k8s.io/code-generator/_examples/crd/clientset/versioned/scheme"
)
type ExampleV1Interface interface {
RESTClient() rest.Interface
TestTypesGetter
}
type ExampleV1Client struct {
restClient rest.Interface
}
func NewForConfig(c *rest.Config) (*ExampleV1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &ExampleV1Client{client}, nil
}
func NewForConfigOrDie(c *rest.Config) *ExampleV1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
func New(c rest.Interface) *ExampleV1Client {
return &ExampleV1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
func (c *ExampleV1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
func (c *ExampleV1Client) TestTypes(namespace string) TestTypeInterface | {
return newTestTypes(c, namespace)
} |
package database
import (
"github.com/sacloud/libsacloud/v2/helper/validate"
"github.com/sacloud/libsacloud/v2/sacloud/types"
)
type BootRequest struct {
Zone string `request:"-" validate:"required"`
ID types.ID `request:"-" validate:"required"`
NoWait bool `request:"-"`
}
func (req *BootRequest) Validate() error | {
return validate.Struct(req)
} |
package gospell
import (
"fmt"
"sort"
)
type Match struct {
Word []rune
Distance int
Weight int
}
type Matches []Match
func (m Match) String() string {
return fmt.Sprintf("{%v %d %d}", string(m.Word), m.Distance, m.Weight)
}
func (s Matches) Len() int { return len(s) }
func (s Matches) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Matches) Strings() []string {
strings := make([]string, len(s))
sort.Sort(ByDistance{s})
for i, r := range s {
strings[i] = string(r.Word)
}
return strings
}
type ByDistance struct {
Matches
}
func (s ByDistance) Less(i, j int) bool {
d1 := s.Matches[i].Distance
d2 := s.Matches[j].Distance
if d1 == d2 {
return string(s.Matches[i].Word) < string(s.Matches[j].Word)
}
return d1 < d2
}
func (m *Match) update(r rune, distance, weight int) Match {
m2 := Match{}
if r != 0 {
m2.Word = []rune{r}
m2.Word = append(m2.Word, m.Word...)
} else {
m2.Word = m.Word[:]
}
m2.Distance = m.Distance + distance
m2.Weight = m.Weight + weight
return m2
}
func (m1 Match) Equal(m2 Match) bool | {
return string(m1.Word) == string(m2.Word) &&
m1.Distance == m2.Distance && m1.Weight == m2.Weight
} |
package storage
import (
"path/filepath"
"github.com/juju/errors"
)
const (
diskByUUID = "/dev/disk/by-uuid"
diskByLabel = "/dev/disk/by-label"
)
func BlockDevicePath(device BlockDevice) (string, error) | {
if device.Label != "" {
return filepath.Join(diskByLabel, device.Label), nil
}
if device.UUID != "" {
return filepath.Join(diskByUUID, device.UUID), nil
}
if device.DeviceName != "" {
return filepath.Join("/dev", device.DeviceName), nil
}
return "", errors.Errorf("could not determine path for block device %q", device.Name)
} |
package model
import (
"math"
"strconv"
native_time "time"
)
type Timestamp int64
const (
MinimumTick = native_time.Millisecond
second = int64(native_time.Second / MinimumTick)
nanosPerTick = int64(MinimumTick / native_time.Nanosecond)
Earliest = Timestamp(math.MinInt64)
Latest = Timestamp(math.MaxInt64)
)
func (t Timestamp) Equal(o Timestamp) bool {
return t == o
}
func (t Timestamp) Before(o Timestamp) bool {
return t < o
}
func (t Timestamp) After(o Timestamp) bool {
return t > o
}
func (t Timestamp) Add(d native_time.Duration) Timestamp {
return t + Timestamp(d/MinimumTick)
}
func (t Timestamp) Sub(o Timestamp) native_time.Duration {
return native_time.Duration(t-o) * MinimumTick
}
func (t Timestamp) Unix() int64 {
return int64(t) / second
}
func (t Timestamp) UnixNano() int64 {
return int64(t) * nanosPerTick
}
func (t Timestamp) String() string {
return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
}
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(t.String()), nil
}
func Now() Timestamp {
return TimestampFromTime(native_time.Now())
}
func TimestampFromTime(t native_time.Time) Timestamp {
return TimestampFromUnixNano(t.UnixNano())
}
func TimestampFromUnix(t int64) Timestamp {
return Timestamp(t * second)
}
func TimestampFromUnixNano(t int64) Timestamp {
return Timestamp(t / nanosPerTick)
}
func (t Timestamp) Time() native_time.Time | {
return native_time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
} |
package aws
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAWSELB_importBasic(t *testing.T) | {
resourceName := "aws_elb.bar"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSELBDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSELBConfig,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
} |
package sha512
import "crypto/sha512"
const (
Size = 64
Size224 = 28
Size256 = 32
Size384 = 48
BlockSize = 128
)
func Sum384(data []byte) (sum384 []byte) {
a := sha512.Sum384(data)
return a[:]
}
func Sum512_224(data []byte) (sum224 []byte) {
a := sha512.Sum512_224(data)
return a[:]
}
func Sum512_256(data []byte) (sum256 []byte) {
a := sha512.Sum512_256(data)
return a[:]
}
func Sum512(data []byte) []byte | {
a := sha512.Sum512(data)
return a[:]
} |
package migrations
import (
"context"
"github.com/fnproject/fn/api/datastore/sql/migratex"
"github.com/jmoiron/sqlx"
)
func down6(ctx context.Context, tx *sqlx.Tx) error {
_, err := tx.ExecContext(ctx, "ALTER TABLE apps DROP COLUMN updated_at;")
return err
}
func init() {
Migrations = append(Migrations, &migratex.MigFields{
VersionFunc: vfunc(6),
UpFunc: up6,
DownFunc: down6,
})
}
func up6(ctx context.Context, tx *sqlx.Tx) error | {
_, err := tx.ExecContext(ctx, "ALTER TABLE apps ADD updated_at VARCHAR(256);")
return err
} |
package value
import (
"bytes"
)
func Cons(x, y Value) *Cell {
return &Cell{Car: x, Cdr: y}
}
type Cell struct {
Car Value
Cdr Value
}
func (c *Cell) Walk(fn func(Value)) {
cur := c
for {
fn(cur.Car)
if cur.Cdr == NIL {
return
}
next, ok := cur.Cdr.(*Cell)
if !ok {
Errorf("cannot evaluate an improper list: %s", c)
}
cur = next
}
}
func (c *Cell) String() string {
var buf bytes.Buffer
buf.WriteByte('(')
for {
buf.WriteString(c.Car.String())
if c.Cdr == NIL {
break
}
cdr, ok := c.Cdr.(*Cell)
if !ok {
buf.WriteString(" . ")
buf.WriteString(c.Cdr.String())
break
}
c = cdr
buf.WriteByte(' ')
}
buf.WriteByte(')')
return buf.String()
}
func (c *Cell) Equal(cmp Value) Value | {
x, ok := cmp.(*Cell)
if !ok {
return NIL
}
if c.Car.Equal(x.Car) != T {
return NIL
}
if c.Cdr.Equal(x.Cdr) != T {
return NIL
}
return T
} |
package protocol
type LogoutRequestMessageData struct {
}
type LogoutRequestMessage struct {
BaseMessage
Data LogoutRequestMessageData `json:"data"`
}
func NewLogoutRequesMessage(session string) *LogoutRequestMessage {
message := LogoutRequestMessage{}
message.Type = LogoutRequestMessageType
message.Session = session
return &message
}
func (m *LogoutRequestMessage) GetType() string {
return m.Type
}
func (m *LogoutRequestMessage) GetSession() string {
return m.Session
}
func (m *LogoutRequestMessage) SetSession(session string) {
m.BaseMessage.Session = session
}
func (m *LogoutRequestMessage) GetData() interface{} | {
return m.Data
} |
package temperature
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/pelletier/go-toml"
"github.com/rumpelsepp/i3gostatus/lib/config"
"github.com/rumpelsepp/i3gostatus/lib/model"
)
const (
name = "temperature"
moduleName = "i3gostatus.modules." + name
defaultPeriod = 5000
defaultFormat = "%d°C"
defaultUrgentTemp = 70
defaultUrgentColor = "#FF0000"
)
type Config struct {
model.BaseConfig
UrgentTemp int
UrgentColor string
}
func (c *Config) ParseConfig(configTree *toml.TomlTree) {
c.BaseConfig.Parse(name, configTree)
c.BaseConfig.Period = config.GetDurationMs(configTree, c.Name+".period", defaultPeriod)
c.Format = config.GetString(configTree, name+".format", defaultFormat)
c.UrgentTemp = config.GetInt(configTree, name+".urgent_temp", defaultUrgentTemp)
c.UrgentColor = config.GetString(configTree, name+".urgent_color", defaultUrgentColor)
}
func (c *Config) Run(args *model.ModuleArgs) | {
var (
outputBlock *model.I3BarBlock
temperature int
thermalFile = "/sys/class/thermal/thermal_zone0/temp"
)
for range time.NewTicker(c.Period).C {
outputBlock = model.NewBlock(moduleName, c.BaseConfig, args.Index)
data, err := ioutil.ReadFile(thermalFile)
if err != nil {
panic(err)
}
dataStr := strings.TrimSpace(string(data))
if t, err := strconv.Atoi(dataStr); err == nil {
temperature = int(t / 1000)
if temperature >= c.UrgentTemp {
outputBlock.Urgent = true
outputBlock.Color = c.UrgentColor
}
}
outputBlock.FullText = fmt.Sprintf(c.Format, temperature)
args.OutCh <- outputBlock
}
} |
package precis
import (
"unicode"
"unicode/utf8"
"golang.org/x/text/transform"
)
type nickAdditionalMapping struct {
notStart bool
prevSpace bool
}
func (t *nickAdditionalMapping) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
for nSrc < len(src) {
r, size := utf8.DecodeRune(src[nSrc:])
if size == 0 {
if !atEOF {
return nDst, nSrc, transform.ErrShortSrc
}
size = 1
}
if unicode.Is(unicode.Zs, r) {
t.prevSpace = true
} else {
if t.prevSpace && t.notStart {
dst[nDst] = ' '
nDst += 1
}
if size != copy(dst[nDst:], src[nSrc:nSrc+size]) {
nDst += size
return nDst, nSrc, transform.ErrShortDst
}
nDst += size
t.prevSpace = false
t.notStart = true
}
nSrc += size
}
return nDst, nSrc, nil
}
func (t *nickAdditionalMapping) Reset() | {
t.prevSpace = false
t.notStart = false
} |
package consul
import (
"log"
"github.com/armon/consul-api"
"github.com/hashicorp/terraform/helper/config"
"github.com/hashicorp/terraform/terraform"
)
type ResourceProvider struct {
Config Config
client *consulapi.Client
}
func (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {
v := &config.Validator{
Optional: []string{
"datacenter",
"address",
},
}
return v.Validate(c)
}
func (p *ResourceProvider) ValidateResource(
t string, c *terraform.ResourceConfig) ([]string, []error) {
return resourceMap.Validate(t, c)
}
func (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {
if _, err := config.Decode(&p.Config, c.Config); err != nil {
return err
}
log.Printf("[INFO] Initializing Consul client")
var err error
p.client, err = p.Config.Client()
if err != nil {
return err
}
return nil
}
func (p *ResourceProvider) Apply(
s *terraform.ResourceState,
d *terraform.ResourceDiff) (*terraform.ResourceState, error) {
return resourceMap.Apply(s, d, p)
}
func (p *ResourceProvider) Diff(
s *terraform.ResourceState,
c *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {
return resourceMap.Diff(s, c, p)
}
func (p *ResourceProvider) Refresh(
s *terraform.ResourceState) (*terraform.ResourceState, error) {
return resourceMap.Refresh(s, p)
}
func (p *ResourceProvider) Resources() []terraform.ResourceType | {
return resourceMap.Resources()
} |
package v1alpha1
import (
v1alpha1 "k8s.io/api/scheduling/v1alpha1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"github.com/hyperhq/client-go/kubernetes/scheme"
rest "github.com/hyperhq/client-go/rest"
)
type SchedulingV1alpha1Interface interface {
RESTClient() rest.Interface
PriorityClassesGetter
}
type SchedulingV1alpha1Client struct {
restClient rest.Interface
}
func (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {
return newPriorityClasses(c)
}
func NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &SchedulingV1alpha1Client{client}, nil
}
func New(c rest.Interface) *SchedulingV1alpha1Client {
return &SchedulingV1alpha1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1alpha1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
func (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
func NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client | {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
} |
package figure
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
)
const signature = "flf2"
const reverseFlag = "1"
var charDelimiters = [3]string{"@", "#", "$"}
var hardblanksBlacklist = [2]byte{'a', '2'}
func getFile(name string) (file http.File) {
filePath := fmt.Sprintf("%s.flf", name)
file, err := AssetFS().Open(filePath)
if err != nil {
log.Fatalf("invalid font name:%s.",err)
}
return file
}
func getHeight(metadata string) int {
datum := strings.Fields(metadata)[1]
height, _ := strconv.Atoi(datum)
return height
}
func getBaseline(metadata string) int {
datum := strings.Fields(metadata)[2]
baseline, _ := strconv.Atoi(datum)
return baseline
}
func getHardblank(metadata string) byte {
datum := strings.Fields(metadata)[0]
hardblank := datum[len(datum)-1]
if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {
return ' '
} else {
return hardblank
}
}
func lastCharLine(text string, height int) bool {
endOfLine, length := " ", 2
if height == 1 && len(text) > 0 {
length = 1
}
if len(text) >= length {
endOfLine = text[len(text)-length:]
}
return endOfLine == strings.Repeat(charDelimiters[0], length) ||
endOfLine == strings.Repeat(charDelimiters[1], length) ||
endOfLine == strings.Repeat(charDelimiters[2], length)
}
func getReverse(metadata string) bool | {
data := strings.Fields(metadata)
return len(data) > 6 && data[6] == reverseFlag
} |
package dao
import (
"context"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_taskJobKey = "task_job"
)
func (d *Dao) SetnxTaskJob(c context.Context, value string) (ok bool, err error) {
var (
conn = d.dmRds.Get(c)
)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("SETNX", _taskJobKey, value)); err != nil {
log.Error("d.SetnxMask(value:%s),error(%v)", value, err)
return
}
return
}
func (d *Dao) GetSetTaskJob(c context.Context, value string) (old string, err error) {
var (
conn = d.dmRds.Get(c)
)
defer conn.Close()
if old, err = redis.String(conn.Do("GETSET", _taskJobKey, value)); err != nil {
log.Error("d.GetSetTaskJob(value:%s),error(%v)", value, err)
return
}
return
}
func (d *Dao) DelTaskJob(c context.Context) (err error) {
var (
conn = d.dmRds.Get(c)
)
defer conn.Close()
if _, err = conn.Do("DEL", _taskJobKey); err != nil {
log.Error("d.DelTaskJob,error(%v)", err)
return
}
return
}
func (d *Dao) GetTaskJob(c context.Context) (value string, err error) | {
var (
conn = d.dmRds.Get(c)
)
defer conn.Close()
if value, err = redis.String(conn.Do("GET", _taskJobKey)); err != nil {
log.Error("d.GetMaskJob,error(%v)", err)
return
}
return
} |
package daemon
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
)
type GetHealthzHandlerFunc func(GetHealthzParams) middleware.Responder
func (fn GetHealthzHandlerFunc) Handle(params GetHealthzParams) middleware.Responder {
return fn(params)
}
type GetHealthzHandler interface {
Handle(GetHealthzParams) middleware.Responder
}
func NewGetHealthz(ctx *middleware.Context, handler GetHealthzHandler) *GetHealthz {
return &GetHealthz{Context: ctx, Handler: handler}
}
type GetHealthz struct {
Context *middleware.Context
Handler GetHealthzHandler
}
func (o *GetHealthz) ServeHTTP(rw http.ResponseWriter, r *http.Request) | {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
var Params = NewGetHealthzParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params)
o.Context.Respond(rw, r, route.Produces, route, res)
} |
package collaboration
import "sync"
func NewMemoryStorage() *memoryStorage {
return &memoryStorage{
users: make(map[string]*Option),
}
}
type memoryStorage struct {
users map[string]*Option
sync.Mutex
}
func (m *memoryStorage) Get(username string) (*Option, error) {
m.Lock()
defer m.Unlock()
option, ok := m.users[username]
if !ok {
return nil, ErrUserNotFound
}
return option, nil
}
func (m *memoryStorage) GetAll() (map[string]*Option, error) {
m.Lock()
defer m.Unlock()
return m.users, nil
}
func (m *memoryStorage) Delete(username string) error {
m.Lock()
defer m.Unlock()
delete(m.users, username)
return nil
}
func (m *memoryStorage) Close() error {
return nil
}
func (m *memoryStorage) Set(username string, value *Option) error | {
m.Lock()
defer m.Unlock()
m.users[username] = value
return nil
} |
package fake
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
action "github.com/vmware-tanzu/octant/pkg/action"
)
type MockActionRegistrar struct {
ctrl *gomock.Controller
recorder *MockActionRegistrarMockRecorder
}
type MockActionRegistrarMockRecorder struct {
mock *MockActionRegistrar
}
func NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar {
mock := &MockActionRegistrar{ctrl: ctrl}
mock.recorder = &MockActionRegistrarMockRecorder{mock}
return mock
}
func (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder {
return m.recorder
}
func (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Register", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Register", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)
}
func (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unregister", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)
}
func (m *MockActionRegistrar) Unregister(arg0, arg1 string) | {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Unregister", arg0, arg1)
} |
package sw
import (
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"errors"
"fmt"
"github.com/hyperledger/fabric/bccsp"
)
type rsaPublicKey struct{ pubKey *rsa.PublicKey }
func (k *rsaPublicKey) Private() bool { return false }
func (k *rsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil }
func (k *rsaPublicKey) Bytes() (raw []byte, err error) {
if k.pubKey == nil {
return nil, errors.New("Failed marshalling key. Key is nil.")
}
raw, err = x509.MarshalPKIXPublicKey(k.pubKey)
if err != nil {
return nil, fmt.Errorf("Failed marshalling key [%s]", err)
}
return
}
func (k *rsaPublicKey) SKI() []byte {
if k.pubKey == nil {
return nil
}
raw := x509.MarshalPKCS1PublicKey(k.pubKey)
hash := sha256.Sum256(raw)
return hash[:]
}
func (k *rsaPublicKey) Symmetric() bool | { return false } |
package main
import "bufio"
import "log"
import "strings"
func ScanGit(options ParserOptions, otherArgs string) Commits | {
commits := make(Commits, 0)
args := strings.Split(otherArgs, " ")
logArgs := append(options.GitArgs, args...)
cmd := ExecGit(logArgs...)
data, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
s := bufio.NewScanner(data)
s.Split(options.SplitFunc)
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
for s.Scan() {
commits = append(commits, options.CommitParser(s.Text()))
}
if err := s.Err(); err != nil {
log.Fatal(err)
}
cmd.Wait()
return commits
} |
package utils
import (
"bufio"
"fmt"
"os"
"strings"
)
func AskForConfirmation(s string) bool {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("%s [y/n]: ", s)
response, err := reader.ReadString('\n')
if err != nil {
exitWithError(err)
}
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
return true
} else if response == "n" || response == "no" {
return false
}
}
}
func exitWithError(err error) | {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
} |
package structs
import (
"fmt"
"time"
)
const (
DefaultUnpriviledgedUser = "nobody"
CheckBufSize = 4 * 1024
)
type WaitResult struct {
ExitCode int
Signal int
Err error
}
func NewWaitResult(code, signal int, err error) *WaitResult {
return &WaitResult{
ExitCode: code,
Signal: signal,
Err: err,
}
}
func (r *WaitResult) Successful() bool {
return r.ExitCode == 0 && r.Signal == 0 && r.Err == nil
}
func (r *WaitResult) String() string {
return fmt.Sprintf("Wait returned exit code %v, signal %v, and error %v",
r.ExitCode, r.Signal, r.Err)
}
type RecoverableError struct {
Err error
Recoverable bool
}
func NewRecoverableError(e error, recoverable bool) *RecoverableError {
return &RecoverableError{
Err: e,
Recoverable: recoverable,
}
}
type CheckResult struct {
ExitCode int
Output string
Timestamp time.Time
Duration time.Duration
Err error
}
func (r *RecoverableError) Error() string | {
return r.Err.Error()
} |
package chshare
import (
"fmt"
"log"
"os"
)
type Logger struct {
prefix string
logger *log.Logger
Info, Debug bool
}
func NewLogger(prefix string) *Logger {
return NewLoggerFlag(prefix, log.Ldate|log.Ltime)
}
func NewLoggerFlag(prefix string, flag int) *Logger {
l := &Logger{
prefix: prefix,
logger: log.New(os.Stdout, "", flag),
Info: false,
Debug: false,
}
return l
}
func (l *Logger) Infof(f string, args ...interface{}) {
if l.Info {
l.logger.Printf(l.prefix+": "+f, args...)
}
}
func (l *Logger) Debugf(f string, args ...interface{}) {
if l.Debug {
l.logger.Printf(l.prefix+": "+f, args...)
}
}
func (l *Logger) Errorf(f string, args ...interface{}) error {
return fmt.Errorf(l.prefix+": "+f, args...)
}
func (l *Logger) Fork(prefix string, args ...interface{}) *Logger {
args = append([]interface{}{l.prefix}, args...)
ll := NewLogger(fmt.Sprintf("%s: "+prefix, args...))
ll.Info = l.Info
ll.Debug = l.Debug
return ll
}
func (l *Logger) Prefix() string | {
return l.prefix
} |
package header
import (
"net/http"
"github.com/google/martian/v3/proxyutil"
)
type Matcher struct {
name, value string
}
func (m *Matcher) MatchRequest(req *http.Request) bool {
h := proxyutil.RequestHeader(req)
vs, ok := h.All(m.name)
if !ok {
return false
}
for _, v := range vs {
if v == m.value {
return true
}
}
return false
}
func (m *Matcher) MatchResponse(res *http.Response) bool {
h := proxyutil.ResponseHeader(res)
vs, ok := h.All(m.name)
if !ok {
return false
}
for _, v := range vs {
if v == m.value {
return true
}
}
return false
}
func NewMatcher(name, value string) *Matcher | {
return &Matcher{
name: name,
value: value,
}
} |
package builder
import (
"sync"
"github.com/rikvdh/ci/lib/config"
)
type jobCounter struct {
mu sync.RWMutex
jobCounter uint
jobLimit uint
eventCh chan uint
}
func newJobCounter() *jobCounter {
return &jobCounter{
jobCounter: 0,
jobLimit: config.Get().ConcurrentBuilds,
eventCh: make(chan uint),
}
}
func (j *jobCounter) Decrement() {
j.mu.Lock()
j.jobCounter--
j.mu.Unlock()
j.publishEvent()
}
func (j *jobCounter) CanStartJob() bool {
j.mu.RLock()
defer j.mu.RUnlock()
return (j.jobCounter < j.jobLimit)
}
func (j *jobCounter) publishEvent() {
j.mu.RLock()
j.eventCh <- j.jobCounter
j.mu.RUnlock()
}
func (j *jobCounter) GetEventChannel() <-chan uint {
j.mu.RLock()
defer j.mu.RUnlock()
return j.eventCh
}
func (j *jobCounter) Increment() | {
j.mu.Lock()
j.jobCounter++
j.mu.Unlock()
j.publishEvent()
} |
package simple
import (
"bytes"
"fmt"
"github.com/spencergibb/go-nuvem/loadbalancer"
"github.com/spencergibb/go-nuvem/loadbalancer/rule"
"github.com/spencergibb/go-nuvem/loadbalancer/serverlist"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
func TestBuilder(t *testing.T) {
println("\nTestBuilder")
lb := NewBuilder().
Namespace("test").
ServerList(serverlist.NewStaticBuilder("test").Servers("10.0.0.1:80").Build()).
Rule(rule.NewRandomRule()).
Build()
assertLoadBalancer(t, lb)
}
func assertLoadBalancer(t *testing.T, lb loadbalancer.LoadBalancer) {
require.NotNil(t, lb, "lb was nil")
server := lb.Choose()
assert.NotNil(t, server, "server was nil")
}
func TestFactory(t *testing.T) | {
viper.SetConfigType("yaml")
yaml := []byte(`
nuvem.loadbalancer.test.serverlist.static.servers:
- localhost:8080
- 127.0.0.1:9080
`)
err := viper.ReadConfig(bytes.NewBuffer(yaml))
viper.SetDefault("nuvem.loadbalancer.test.factory", FactoryKey)
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
lb := loadbalancer.Create("test")
assertLoadBalancer(t, lb)
} |
package main
import (
"compress/gzip"
"fmt"
"io/ioutil"
"os"
)
func main() {
fpath := "test.tar.gz"
if err := toGzip("Hello World!", fpath); err != nil {
panic(err)
}
if tb, err := toBytes(fpath); err != nil {
panic(err)
} else {
fmt.Println(fpath, ":", string(tb))
}
os.Remove(fpath)
}
func toGzip(txt, fpath string) error {
f, err := os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0777)
if err != nil {
f, err = os.Create(fpath)
if err != nil {
return err
}
}
defer f.Close()
gw := gzip.NewWriter(f)
if _, err := gw.Write([]byte(txt)); err != nil {
return err
}
gw.Close()
gw.Flush()
return nil
}
func toBytes(fpath string) ([]byte, error) | {
f, err := os.OpenFile(fpath, os.O_RDONLY, 0444)
if err != nil {
return nil, err
}
defer f.Close()
fz, err := gzip.NewReader(f)
if err != nil {
return nil, err
}
defer fz.Close()
s, err := ioutil.ReadAll(fz)
if err != nil {
return nil, err
}
return s, nil
} |
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"log"
"net/http"
"os"
"reflect"
"time"
"github.com/robfig/cron"
)
const hook = "http://localhost:8065/hooks/pdusr3nmwfn4pyhrh83dixr1xo"
const filePath = "timetable.csv"
type ChatMsg struct {
Text string `json:"text"`
}
type CsvLoader struct {
FilePath string
rows [][]string
}
func remind(text string) {
jsonMsg, _ := json.Marshal(&ChatMsg{text})
msgReader := bytes.NewReader(jsonMsg)
client := &http.Client{}
r, _ := client.Post(hook, "application/json", msgReader)
log.Println(r.StatusCode, r.Header["X-Request-Id"][0], string(jsonMsg))
}
func main() {
loader := &CsvLoader{FilePath: filePath}
cronJobs := &cron.Cron{}
for true {
csv, differs := loader.Load()
if differs {
cronJobs.Stop()
cronJobs = cron.New()
for _, task := range csv {
cronErr := cronJobs.AddFunc(task[0], func() { remind(task[1]) })
if cronErr != nil {
panic(cronErr)
}
}
cronJobs.Start()
}
time.Sleep(1 * time.Second)
}
}
func (l *CsvLoader) Load() ([][]string, bool) | {
file, err := os.Open(l.FilePath)
if err != nil {
panic(err)
}
rows, csvErr := csv.NewReader(file).ReadAll()
if csvErr != nil {
panic(csvErr)
}
differs := !reflect.DeepEqual(rows, l.rows)
l.rows = rows
return rows, differs
} |
package xmodule
import (
"fmt"
msg "github.com/Centimitr/xmessage"
)
type Comment struct{}
func (m Comment) GetIndexComments(ctx *msg.Ctx) {
fmt.Println("C")
}
func (m Comment) GetMessages(ctx *msg.Ctx) {
fmt.Println("M")
}
func init() | {
var m Comment
msg.LoadModule(m)
} |
package privsep
import "syscall"
func setuid(uid int) (err error) {
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = e1
}
return
}
func setgid(gid int) (err error) | {
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = e1
}
return
} |
package olog
import (
"fmt"
)
type DirectLogger struct {
writers map[string]Writer
}
func NewDirectLogger() *DirectLogger {
return &DirectLogger{
writers: make(map[string]Writer),
}
}
func (dl *DirectLogger) Log(level Level,
module string,
fmtstr string,
args ...interface{}) {
if level == PrintLevel {
return
}
fmtstr = ToString(level) + " [" + module + "] " + fmtstr
msg := fmt.Sprintf(fmtstr, args...)
for _, writer := range dl.writers {
if writer.IsEnabled() {
writer.Write(msg)
}
}
}
func (dl *DirectLogger) RemoveWriter(uniqueID string) {
delete(dl.writers, uniqueID)
}
func (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer) {
return dl.writers[uniqueID]
}
func (dl *DirectLogger) RegisterWriter(writer Writer) | {
if writer != nil {
dl.writers[writer.UniqueID()] = writer
}
} |
package controller
import (
"os"
"path"
mustache "../library/mustache/_obj/mustache"
)
func IndexHandler() string | {
root := os.Getenv("cd ..; pwd")
view := path.Join(root, "view")
file := path.Join(path.Join(view, "index"), "index.mustache")
data := map[string] string {
"title": "Hello, blog.go",
"name": "Welcome to blog.go!",
}
return mustache.RenderFile(file, data)
} |
package copy_to
import (
"github.com/go-zero-boilerplate/job-coordinator/context"
)
type queuedJob struct {
copyToWorker *copyTo
ctx *context.Context
job Job
handlers Handlers
}
func (q *queuedJob) Do(workerID int) error | {
return q.copyToWorker.DoJob(q.ctx, q.job, q.handlers)
} |
package informers
import (
"fmt"
v1alpha1 "github.com/jetstack-experimental/cert-manager/pkg/apis/certmanager/v1alpha1"
schema "k8s.io/apimachinery/pkg/runtime/schema"
cache "k8s.io/client-go/tools/cache"
)
type GenericInformer interface {
Informer() cache.SharedIndexInformer
Lister() cache.GenericLister
}
type genericInformer struct {
informer cache.SharedIndexInformer
resource schema.GroupResource
}
func (f *genericInformer) Lister() cache.GenericLister {
return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)
}
func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {
switch resource {
case v1alpha1.SchemeGroupVersion.WithResource("certificates"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Certificates().Informer()}, nil
case v1alpha1.SchemeGroupVersion.WithResource("issuers"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Issuers().Informer()}, nil
}
return nil, fmt.Errorf("no informer found for %v", resource)
}
func (f *genericInformer) Informer() cache.SharedIndexInformer | {
return f.informer
} |
package adapter
import (
"github.com/arasuresearch/arasu/datastorage/bigdata/adapter/abstract"
"github.com/arasuresearch/arasu/datastorage/bigdata/adapter/hbase"
"log"
)
type Adapter interface {
GetDbName() string
CreateDatabase() error
DropDatabase() error
GetTableNames() ([]string, error)
IsDatabaseExists() bool
CreateTable(string, func(*abstract.Table)) error
AlterTable(name string, args ...interface{}) error
DropTable(string) error
DumpSchema()
CreateSchemaMigration() error
DropSchemaMigration() error
GetAllSchemaMigration() ([]string, error)
DeleteFromSchemaMigration(version string) error
InsertIntoSchemaMigration(version string) error
SchemaToStruct(string) (*abstract.SchemaToStruct, error)
}
func New(name string, conf string) (adapter Adapter) | {
var abstractAdapter = abstract.New(name, conf)
switch name {
case "hbase":
adapter = hbase.New(abstractAdapter)
default:
log.Fatal("Adapter Error (" + name + ") Adapter not supported ")
}
return
} |
package iptables
import (
"github.com/google/netstack/tcpip/buffer"
)
type Hook uint
const (
Prerouting Hook = iota
Input
Forward
Output
Postrouting
NumHooks
)
type Verdict int
const (
Accept Verdict = iota
Drop
Stolen
Queue
Repeat
None
Jump
Continue
Return
)
type IPTables struct {
Tables map[string]Table
Priorities map[Hook][]string
}
type Table struct {
BuiltinChains map[Hook]Chain
DefaultTargets map[Hook]Target
UserChains map[string]Chain
Chains map[string]*Chain
metadata interface{}
}
func (table *Table) Metadata() interface{} {
return table.metadata
}
func (table *Table) SetMetadata(metadata interface{}) {
table.metadata = metadata
}
type Chain struct {
Name string
Rules []Rule
}
type Rule struct {
Matchers []Matcher
Target Target
}
type Matcher interface {
Match(hook Hook, packet buffer.VectorisedView, interfaceName string) (matches bool, hotdrop bool)
}
type Target interface {
Action(packet buffer.VectorisedView) (Verdict, string)
}
func (table *Table) ValidHooks() uint32 | {
hooks := uint32(0)
for hook, _ := range table.BuiltinChains {
hooks |= 1 << hook
}
return hooks
} |
package redis3
import (
"context"
"fmt"
"github.com/chrislusf/seaweedfs/weed/filer"
"github.com/go-redis/redis/v8"
)
func (store *UniversalRedis3Store) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
_, err = store.Client.Set(ctx, string(key), value, 0).Result()
if err != nil {
return fmt.Errorf("kv put: %v", err)
}
return nil
}
func (store *UniversalRedis3Store) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
data, err := store.Client.Get(ctx, string(key)).Result()
if err == redis.Nil {
return nil, filer.ErrKvNotFound
}
return []byte(data), err
}
func (store *UniversalRedis3Store) KvDelete(ctx context.Context, key []byte) (err error) | {
_, err = store.Client.Del(ctx, string(key)).Result()
if err != nil {
return fmt.Errorf("kv delete: %v", err)
}
return nil
} |
package raddress
import (
"fmt"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestLoc(t *testing.T) {
fmt.Println(Loc.RegionName(67))
Convey("test Loc", t, func() {
items := Loc.Cities(67)
So(len(items), ShouldNotEqual, 0)
})
}
func TestCities(t *testing.T) | {
Convey("Test get city", t, func() {
Convey("Test get city", func() {
item := GetCityByName("Москва")
So(item.Id, ShouldNotEqual, 0)
So(item.RegionId, ShouldNotEqual, 0)
})
Convey("Get city region", func() {
item := GetCityRegion("москва")
So(item.Id, ShouldNotEqual, 0)
})
Convey("Get region", func() {
items := GetRegionCities("Смоленска")
So(len(items), ShouldNotEqual, 0)
})
})
} |
package main
import (
"fmt"
"math/rand"
"strings"
)
func MakeIndexMessage(pkg *Package) string {
dependenciesNames := []string{}
for _, dep := range pkg.Dependencies {
dependenciesNames = append(dependenciesNames, dep.Name)
}
namesAsString := strings.Join(dependenciesNames, ",")
return fmt.Sprintf("INDEX|%s|%s", pkg.Name, namesAsString)
}
func MakeRemoveMessage(pkg *Package) string {
return fmt.Sprintf("REMOVE|%s|", pkg.Name)
}
var possibleInvalidCommands = []string{"BLINDEX", "REMOVES", "QUER", "LIZARD", "I"}
var possibleInvalidChars = []string{"=", "+", "☃", " "}
func MakeBrokenMessage() string {
syntaxError := rand.Intn(10)%2 == 0
if syntaxError {
invalidChar := possibleInvalidChars[rand.Intn(len(possibleInvalidChars))]
return fmt.Sprintf("INDEX|emacs%selisp", invalidChar)
}
invalidCommand := possibleInvalidCommands[rand.Intn(len(possibleInvalidCommands))]
return fmt.Sprintf("%s|a|b", invalidCommand)
}
func MakeQueryMessage(pkg *Package) string | {
return fmt.Sprintf("QUERY|%s|", pkg.Name)
} |
package server
import (
"math/rand"
"time"
"github.com/kyokomi/expcache"
)
type ImageCache interface {
GetRandomImageURL() string
}
type imageCache struct {
Expire expcache.ExpireOnMemoryCache
cache []string
twAPI TwitterAPI
rd *rand.Rand
twitterID string
cacheCnt int
}
func NewImageCache(twAPI TwitterAPI, twitterID string, cacheCnt int) ImageCache {
e := &imageCache{
cache: []string{},
twAPI: twAPI,
rd: rand.New(rand.NewSource(time.Now().UnixNano())),
twitterID: twitterID,
cacheCnt: cacheCnt,
}
e.Expire = expcache.NewExpireMemoryCache(e, 24*time.Hour)
return e
}
func (c *imageCache) GetRandomImageURL() string {
var result string
c.Expire.WithRefreshLock(time.Now(), func() {
idx := c.rd.Int31n(int32(len(c.cache))) - 1
result = c.cache[idx]
})
return result
}
var _ expcache.OnMemoryCache = (*imageCache)(nil)
var _ ImageCache = (*imageCache)(nil)
func (c *imageCache) Refresh() error | {
images, err := c.twAPI.GetFavoritesImages(c.cacheCnt, c.twitterID)
if err != nil {
return err
}
c.cache = images
return nil
} |
package content
import (
"go2o/src/core/domain/interface/content"
"time"
)
var _ content.IPage = new(Page)
type Page struct{
_contentRep content.IContentRep
_partnerId int
_value *content.ValuePage
}
func NewPage(partnerId int, rep content.IContentRep,v *content.ValuePage) content.IPage {
return &Page{
_contentRep: rep,
_partnerId: partnerId,
_value:v,
}
}
func (this *Page) GetValue()*content.ValuePage{
return this._value
}
func (this *Page) SetValue(v *content.ValuePage)error{
v.Id = this.GetDomainId()
this._value = v
return nil
}
func (this *Page) Save()(int,error){
this._value.UpdateTime = time.Now().Unix()
return this._contentRep.SavePage(this._partnerId,this._value)
}
func (this *Page) GetDomainId() int | {
return this._value.Id
} |
package pathdb
import (
"github.com/scionproto/scion/go/lib/common"
"github.com/scionproto/scion/go/lib/ctrl/seg"
"github.com/scionproto/scion/go/lib/pathdb/conn"
"github.com/scionproto/scion/go/lib/pathdb/query"
"github.com/scionproto/scion/go/lib/pathdb/sqlite"
)
type DB struct {
conn conn.Conn
}
func New(path string, backend string) (*DB, error) {
db := &DB{}
var err error
switch backend {
case "sqlite":
db.conn, err = sqlite.New(path)
default:
return nil, common.NewBasicError("Unknown backend", nil, "backend", backend)
}
if err != nil {
return nil, err
}
return db, nil
}
func (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) {
return db.conn.Insert(pseg, segTypes)
}
func (db *DB) InsertWithHPCfgIDs(pseg *seg.PathSegment,
segTypes []seg.Type, hpCfgIDs []*query.HPCfgID) (int, error) {
return db.conn.InsertWithHPCfgIDs(pseg, segTypes, hpCfgIDs)
}
func (db *DB) Delete(segID common.RawBytes) (int, error) {
return db.conn.Delete(segID)
}
func (db *DB) DeleteWithIntf(intf query.IntfSpec) (int, error) {
return db.conn.DeleteWithIntf(intf)
}
func (db *DB) Get(params *query.Params) ([]*query.Result, error) | {
return db.conn.Get(params)
} |
package sol
type Operator interface {
Wrap(string) string
}
func Function(name string, col Columnar) ColumnElem {
return col.Column().AddOperator(FuncClause{Name: name})
}
func Avg(col Columnar) ColumnElem {
return Function(AVG, col)
}
func Count(col Columnar) ColumnElem {
return Function(COUNT, col)
}
func Date(col Columnar) ColumnElem {
return Function(DATE, col)
}
func DatePart(part string, col Columnar) ColumnElem {
return col.Column().AddOperator(
FuncClause{Name: DATEPART},
).AddOperator(
ArrayClause{clauses: []Clause{String(part)}, post: true, sep: ", "},
)
}
func Max(col Columnar) ColumnElem {
return Function(MAX, col)
}
func Min(col Columnar) ColumnElem {
return Function(MIN, col)
}
func StdDev(col Columnar) ColumnElem {
return Function(STDDEV, col)
}
func Variance(col Columnar) ColumnElem {
return Function(VARIANCE, col)
}
func Sum(col Columnar) ColumnElem | {
return Function(SUM, col)
} |
package okta
import ()
type SwaApplicationSettingsApplication struct {
ButtonField string `json:"buttonField,omitempty"`
LoginUrlRegex string `json:"loginUrlRegex,omitempty"`
PasswordField string `json:"passwordField,omitempty"`
Url string `json:"url,omitempty"`
UsernameField string `json:"usernameField,omitempty"`
}
func (a *SwaApplicationSettingsApplication) IsApplicationInstance() bool {
return true
}
func NewSwaApplicationSettingsApplication() *SwaApplicationSettingsApplication | {
return &SwaApplicationSettingsApplication{}
} |
package lib
import "C"
func CheckSize(check int) int {
return int(C.lzma_check_size(C.lzma_check(check)))
}
func CRC32(buf []byte, crc uint32) uint32 {
ptr, size := CSlicePtrLen(buf)
return uint32(C.lzma_crc32(ptr, size, C.uint32_t(crc)))
}
func CRC64(buf []byte, crc uint64) uint64 {
ptr, size := CSlicePtrLen(buf)
return uint64(C.lzma_crc64(ptr, size, C.uint64_t(crc)))
}
func (z *Stream) GetCheck() int {
return int(C.lzma_get_check(z.C()))
}
func CheckIsSupported(check int) bool | {
return C.lzma_check_is_supported(C.lzma_check(check)) != 0
} |
package lib
import (
"github.com/atinm/spotify"
)
func FiltersEnabled() bool {
return ParentalControlsEnabled()
}
func ParentalControlsEnabled() bool {
return rule.Explicit
}
func Rules(track *spotify.FullTrack, device string) bool {
if track != nil && rule.Explicit && track.Explicit && !ignored(device) {
return true
}
return false
}
func SetParentalControls(b bool) {
rule.Explicit = b
}
func ignored(device string) bool | {
for _, name := range config.Ignored {
if name == device {
return true
}
}
return false
} |
package resources
import "github.com/awslabs/goformation/cloudformation/policies"
type AWSECSTaskDefinition_DockerVolumeConfiguration struct {
Autoprovision bool `json:"Autoprovision,omitempty"`
Driver string `json:"Driver,omitempty"`
DriverOpts map[string]string `json:"DriverOpts,omitempty"`
Labels map[string]string `json:"Labels,omitempty"`
Scope string `json:"Scope,omitempty"`
_deletionPolicy policies.DeletionPolicy
_dependsOn []string
_metadata map[string]interface{}
}
func (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string {
return "AWS::ECS::TaskDefinition.DockerVolumeConfiguration"
}
func (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) {
r._dependsOn = dependencies
}
func (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} {
return r._metadata
}
func (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) {
r._metadata = metadata
}
func (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) {
r._deletionPolicy = policy
}
func (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string | {
return r._dependsOn
} |
package awstasks
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
)
func findNameTag(tags []*ec2.Tag) *string {
for _, tag := range tags {
if aws.StringValue(tag.Key) == "Name" {
return tag.Value
}
}
return nil
}
func intersectTags(tags []*ec2.Tag, desired map[string]string) map[string]string {
if tags == nil {
return nil
}
actual := make(map[string]string)
for _, t := range tags {
k := aws.StringValue(t.Key)
v := aws.StringValue(t.Value)
if _, found := desired[k]; found {
actual[k] = v
}
}
if len(actual) == 0 && desired == nil {
return nil
}
return actual
}
func mapEC2TagsToMap(tags []*ec2.Tag) map[string]string | {
if tags == nil {
return nil
}
m := make(map[string]string)
for _, t := range tags {
m[aws.StringValue(t.Key)] = aws.StringValue(t.Value)
}
return m
} |
package main
import "C"
import (
"fmt"
"os"
"runtime"
"runtime/pprof"
"time"
"unsafe"
)
func init() {
register("CgoPprofThread", CgoPprofThread)
register("CgoPprofThreadNoTraceback", CgoPprofThreadNoTraceback)
}
func CgoPprofThread() {
runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)
pprofThread()
}
func CgoPprofThreadNoTraceback() {
pprofThread()
}
func pprofThread() | {
f, err := os.CreateTemp("", "prof")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if err := pprof.StartCPUProfile(f); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
C.runCPUHogThread()
t0 := time.Now()
for C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second {
time.Sleep(100 * time.Millisecond)
}
pprof.StopCPUProfile()
name := f.Name()
if err := f.Close(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
fmt.Println(name)
} |
package session
import (
"github.com/coyim/coyim/xmpp/data"
)
const (
MUCStatusJIDPublic = 100
MUCStatusAffiliationChanged = 101
MUCStatusUnavailableShown = 102
MUCStatusUnavailableNotShown = 103
MUCStatusConfigChanged = 104
MUCStatusSelfPresence = 110
MUCStatusRoomLoggingEnabled = 170
MUCStatusRoomLoggingDisabled = 171
MUCStatusRoomNonAnonymous = 172
MUCStatusRoomSemiAnonymous = 173
MUCStatusRoomFullyAnonymous = 174
MUCStatusRoomCreated = 201
MUCStatusNicknameAssigned = 210
MUCStatusBanned = 301
MUCStatusNewNickname = 303
MUCStatusBecauseKickedFrom = 307
MUCStatusRemovedBecauseAffiliationChanged = 321
MUCStatusRemovedBecauseNotMember = 322
MUCStatusRemovedBecauseShutdown = 332
)
type mucUserStatuses []data.MUCUserStatus
func (mus mucUserStatuses) contains(c ...int) bool {
for _, cc := range c {
if !mus.containsOne(cc) {
return false
}
}
return true
}
func (mus mucUserStatuses) containsAny(c ...int) bool {
for _, cc := range c {
if mus.containsOne(cc) {
return true
}
}
return false
}
func (mus mucUserStatuses) isEmpty() bool {
return len(mus) == 0
}
func (mus mucUserStatuses) containsOne(c int) bool | {
for _, s := range mus {
if s.Code == c {
return true
}
}
return false
} |
package vmutil
import (
"bytes"
"testing"
"github.com/bytom/crypto/ed25519"
)
func TestIsUnspendable(t *testing.T) {
tests := []struct {
pkScript []byte
expected bool
}{
{
pkScript: []byte{0x6a, 0x04, 0x74, 0x65, 0x73, 0x74},
expected: true,
},
{
pkScript: []byte{0x76, 0xa9, 0x14, 0x29, 0x95, 0xa0,
0xfe, 0x68, 0x43, 0xfa, 0x9b, 0x95, 0x45,
0x97, 0xf0, 0xdc, 0xa7, 0xa4, 0x4d, 0xf6,
0xfa, 0x0b, 0x5c, 0x88, 0xac},
expected: false,
},
}
for i, test := range tests {
res := IsUnspendable(test.pkScript)
if res != test.expected {
t.Errorf("TestIsUnspendable #%d failed: got %v want %v",
i, res, test.expected)
continue
}
}
}
func TestP2SP(t *testing.T) | {
pub1, _, _ := ed25519.GenerateKey(nil)
pub2, _, _ := ed25519.GenerateKey(nil)
prog, _ := P2SPMultiSigProgram([]ed25519.PublicKey{pub1, pub2}, 1)
pubs, n, err := ParseP2SPMultiSigProgram(prog)
if err != nil {
t.Fatal(err)
}
if n != 1 {
t.Errorf("expected nrequired=1, got %d", n)
}
if !bytes.Equal(pubs[0], pub1) {
t.Errorf("expected first pubkey to be %x, got %x", pub1, pubs[0])
}
if !bytes.Equal(pubs[1], pub2) {
t.Errorf("expected second pubkey to be %x, got %x", pub2, pubs[1])
}
} |
package flag
import (
"errors"
"fmt"
"strings"
"github.com/hashicorp/errwrap"
)
type OptionList struct {
Options []string
allOptions []string
permissible map[string]struct{}
typeName string
}
func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) {
permissible := make(map[string]struct{})
ol := &OptionList{
allOptions: permissibleOptions,
permissible: permissible,
typeName: "OptionList",
}
for _, o := range permissibleOptions {
ol.permissible[o] = struct{}{}
}
if err := ol.Set(defaultOptions); err != nil {
return nil, errwrap.Wrap(errors.New("problem setting defaults"), err)
}
return ol, nil
}
func (ol *OptionList) Set(s string) error {
ol.Options = nil
if s == "" {
return nil
}
options := strings.Split(strings.ToLower(s), ",")
seen := map[string]struct{}{}
for _, o := range options {
if _, ok := ol.permissible[o]; !ok {
return fmt.Errorf("unknown option %q", o)
}
if _, ok := seen[o]; ok {
return fmt.Errorf("duplicated option %q", o)
}
ol.Options = append(ol.Options, o)
seen[o] = struct{}{}
}
return nil
}
func (ol *OptionList) String() string {
return strings.Join(ol.Options, ",")
}
func (ol *OptionList) Type() string {
return ol.typeName
}
func (ol *OptionList) PermissibleString() string | {
return fmt.Sprintf(`"%s"`, strings.Join(ol.allOptions, `", "`))
} |
package expvar
import (
"expvar"
"runtime"
"sync"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
func init() {
caddy.RegisterPlugin("expvar", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
func expVarParse(c *caddy.Controller) (Resource, error) {
var resource Resource
var err error
for c.Next() {
args := c.RemainingArgs()
switch len(args) {
case 0:
resource = Resource(defaultExpvarPath)
case 1:
resource = Resource(args[0])
default:
return resource, c.ArgErr()
}
}
return resource, err
}
func publishExtraVars() {
publishOnce.Do(func() {
expvar.Publish("Goroutines", expvar.Func(func() interface{} {
return runtime.NumGoroutine()
}))
})
}
var publishOnce sync.Once
var defaultExpvarPath = "/debug/vars"
func setup(c *caddy.Controller) error | {
resource, err := expVarParse(c)
if err != nil {
return err
}
publishExtraVars()
ev := ExpVar{Resource: resource}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
ev.Next = next
return ev
})
return nil
} |
package virtualbox
import (
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
)
type stepCreateVM struct {
vmName string
}
func (s *stepCreateVM) Run(state map[string]interface{}) multistep.StepAction {
config := state["config"].(*config)
driver := state["driver"].(Driver)
ui := state["ui"].(packer.Ui)
name := config.VMName
commands := make([][]string, 4)
commands[0] = []string{"createvm", "--name", name, "--ostype", config.GuestOSType, "--register"}
commands[1] = []string{
"modifyvm", name,
"--boot1", "disk", "--boot2", "dvd", "--boot3", "none", "--boot4", "none",
}
commands[2] = []string{"modifyvm", name, "--cpus", "1"}
commands[3] = []string{"modifyvm", name, "--memory", "512"}
ui.Say("Creating virtual machine...")
for _, command := range commands {
err := driver.VBoxManage(command...)
if err != nil {
err := fmt.Errorf("Error creating VM: %s", err)
state["error"] = err
ui.Error(err.Error())
return multistep.ActionHalt
}
if s.vmName == "" {
s.vmName = name
}
}
state["vmName"] = s.vmName
return multistep.ActionContinue
}
func (s *stepCreateVM) Cleanup(state map[string]interface{}) | {
if s.vmName == "" {
return
}
driver := state["driver"].(Driver)
ui := state["ui"].(packer.Ui)
ui.Say("Unregistering and deleting virtual machine...")
if err := driver.VBoxManage("unregistervm", s.vmName, "--delete"); err != nil {
ui.Error(fmt.Sprintf("Error deleting virtual machine: %s", err))
}
} |
package handler
import (
"encoding/json"
"net/http"
"github.com/goharbor/harbor/src/jobservice/job"
libhttp "github.com/goharbor/harbor/src/lib/http"
"github.com/goharbor/harbor/src/pkg/task"
)
type jobStatusHandler struct {
handler *task.HookHandler
}
func (j *jobStatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
sc := &job.StatusChange{}
if err := json.NewDecoder(r.Body).Decode(sc); err != nil {
libhttp.SendError(w, err)
return
}
if err := j.handler.Handle(r.Context(), sc); err != nil {
libhttp.SendError(w, err)
return
}
}
func NewJobStatusHandler() http.Handler | {
return &jobStatusHandler{
handler: task.HkHandler,
}
} |
package opts
import (
"fmt"
"strings"
)
type List struct {
Args []string
}
func (lo *List) Set(arg string) error {
lo.Args = append(lo.Args[:], arg)
return nil
}
func (lo List) String() string {
return fmt.Sprintf("[%s]", strings.Join(lo.Args, ", "))
}
func (lo List) Get() []string | {
return lo.Args
} |
package shoauth
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
)
type expectedSuccessHandler struct{}
func (s *expectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}
type expectedFailureHandler struct{}
func (s *expectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}
type unexpectedSuccessHandler struct {
t *testing.T
}
func (s *unexpectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.t.Errorf("Request should have failed, but succeeded instead!")
}
type unexpectedFailureHandler struct {
t *testing.T
}
func (s *unexpectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.t.Errorf("Request should have succeeded, but failed instead!")
}
type testPersistence struct {
exists bool
create error
session bool
}
func (t *testPersistence) CreateInstallation(shopID string, accessToken string) error {
return t.create
}
func TestAlreadyInstalled(t *testing.T) {
p := testPersistence{
exists: true,
create: errors.New("Installation already exists!"),
session: false,
}
handler := NewShopifyOauthHandler(&unexpectedSuccessHandler{t: t}, &expectedFailureHandler{}, &p)
testServer := httptest.NewServer(handler)
defer testServer.Close()
http.Get(testServer.URL + "/install")
}
func (t *testPersistence) InstallationExists(shopID string) bool | {
return t.exists
} |
package main
import "testing"
func TestNewSliceStack(t *testing.T) {
stack := NewStack()
if len(stack) != 0 {
t.Error(`Expected length of stack to be 0, got`, len(stack))
}
}
func TestSliceStackPush(t *testing.T) {
stack := NewStack()
stack.Push(1111)
stack.Push(2345)
if stack[0] != 1111 {
t.Error(`Expected the first item to be 1111, got`, stack[0])
}
}
func TestSliceStackPeek(t *testing.T) {
stack := NewStack()
stack.Push(1234)
stack.Push(2345)
value, _ := stack.Peek()
if value != 2345 {
t.Error(`Expected peeked value to be 2345, got`, value)
}
}
func BenchmarkSliceStackPush(b *testing.B) {
b.StopTimer()
stack := NewStack()
b.StartTimer()
for n := 0; n < b.N; n++ {
stack.Push(n)
}
}
func BenchmarkSliceStackPeek(b *testing.B) {
b.StopTimer()
stack := make(Stack, b.N, b.N)
b.StartTimer()
for n := 0; n < b.N; n++ {
stack.Peek()
}
}
func BenchmarkSliceStackPop(b *testing.B) {
b.StopTimer()
stack := make(Stack, b.N, b.N)
for n := 0; n < b.N; n++ {
stack[n] = n
}
b.StartTimer()
for n := 0; n < b.N; n++ {
stack.Pop()
}
}
func TestSliceStackPop(t *testing.T) | {
stack := NewStack()
stack.Push(1234)
stack.Push(2345)
value, _ := stack.Pop()
if value != 2345 {
t.Error(`Expected peeked value to be 2345, got`, value)
}
} |
package corehttp
import (
"io"
"net"
"net/http"
core "github.com/ipfs/go-ipfs/core"
logging "github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log"
)
type writeErrNotifier struct {
w io.Writer
errs chan error
}
func newWriteErrNotifier(w io.Writer) (io.WriteCloser, <-chan error) {
ch := make(chan error, 1)
return &writeErrNotifier{
w: w,
errs: ch,
}, ch
}
func (w *writeErrNotifier) Write(b []byte) (int, error) {
n, err := w.w.Write(b)
if err != nil {
select {
case w.errs <- err:
default:
}
}
if f, ok := w.w.(http.Flusher); ok {
f.Flush()
}
return n, err
}
func LogOption() ServeOption {
return func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
wnf, errs := newWriteErrNotifier(w)
logging.WriterGroup.AddWriter(wnf)
log.Event(n.Context(), "log API client connected")
<-errs
})
return mux, nil
}
}
func (w *writeErrNotifier) Close() error | {
select {
case w.errs <- io.EOF:
default:
}
return nil
} |
package fileutil
import (
"os"
"golang.org/x/sys/unix"
)
func Fsync(f *os.File) error {
_, err := unix.FcntlInt(f.Fd(), unix.F_FULLFSYNC, 0)
return err
}
func Fdatasync(f *os.File) error | {
return Fsync(f)
} |
package remotecontext
import (
"os"
"path/filepath"
"testing"
)
func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
path, err := os.MkdirTemp(dir, prefix)
if err != nil {
t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
}
return path, func() {
err = os.RemoveAll(path)
if err != nil {
t.Fatalf("Error when removing directory %s: %s", path, err)
}
}
}
func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
filePath := filepath.Join(dir, filename)
err := os.WriteFile(filePath, []byte(contents), perm)
if err != nil {
t.Fatalf("Error when creating %s file: %s", filename, err)
}
return filePath
}
func createTestTempSubdir(t *testing.T, dir, prefix string) string | {
path, err := os.MkdirTemp(dir, prefix)
if err != nil {
t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
}
return path
} |
package stats
import (
"time"
"sync"
"github.com/paulbellamy/ratecounter"
)
var lock = sync.RWMutex{}
type stat struct {
readReq *ratecounter.RateCounter
writeReq *ratecounter.RateCounter
}
func newStat() stat {
return stat{
readReq: ratecounter.NewRateCounter(time.Hour),
writeReq: ratecounter.NewRateCounter(time.Hour),
}
}
type namespaceStatMap map[string]stat
var golbalNamespaceStat namespaceStatMap
func init() {
golbalNamespaceStat = namespaceStatMap{}
}
func IncrRead(label string) {
lock.Lock()
defer lock.Unlock()
stat, ok := golbalNamespaceStat[label]
if !ok {
AddNamespace(label)
stat = golbalNamespaceStat[label]
}
stat.readReq.Incr(1)
}
func IncrWrite(label string) {
lock.Lock()
defer lock.Unlock()
stat, ok := golbalNamespaceStat[label]
if !ok {
AddNamespace(label)
stat = golbalNamespaceStat[label]
}
stat.writeReq.Incr(1)
}
func Rate(label string) (read, write int64) {
lock.RLock()
defer lock.RUnlock()
stat, ok := golbalNamespaceStat[label]
if !ok {
AddNamespace(label)
stat = golbalNamespaceStat[label]
}
return stat.readReq.Rate(), stat.writeReq.Rate()
}
func AddNamespace(label string) | {
_, ok := golbalNamespaceStat[label]
if ok {
return
}
golbalNamespaceStat[label] = newStat()
return
} |
package v1alpha1
import (
v1alpha1 "k8s.io/api/scheduling/v1alpha1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"github.com/hyperhq/client-go/kubernetes/scheme"
rest "github.com/hyperhq/client-go/rest"
)
type SchedulingV1alpha1Interface interface {
RESTClient() rest.Interface
PriorityClassesGetter
}
type SchedulingV1alpha1Client struct {
restClient rest.Interface
}
func (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {
return newPriorityClasses(c)
}
func NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
func New(c rest.Interface) *SchedulingV1alpha1Client {
return &SchedulingV1alpha1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1alpha1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
func (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
func NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) | {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &SchedulingV1alpha1Client{client}, nil
} |
package main
type MetricMap map[string]float64
type StatsInfo struct {
labels map[string]string
metrics MetricMap
}
type RabbitReply interface {
MakeMap() MetricMap
MakeStatsInfo([]string) []StatsInfo
GetString(key string) (string, bool)
}
func MakeReply(contentType string, body []byte) (RabbitReply, error) | {
if contentType == "application/bert" {
return makeBERTReply(body)
}
return makeJSONReply(body)
} |
package ec2query
import (
"net/url"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol/query/queryutil"
)
func Build(r *request.Request) | {
body := url.Values{
"Action": {r.Operation.Name},
"Version": {r.ClientInfo.APIVersion},
}
if err := queryutil.Parse(body, r.Params, true); err != nil {
r.Error = awserr.New("SerializationError", "failed encoding EC2 Query request", err)
}
if r.ExpireTime == 0 {
r.HTTPRequest.Method = "POST"
r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
r.SetBufferBody([]byte(body.Encode()))
} else {
r.HTTPRequest.Method = "GET"
r.HTTPRequest.URL.RawQuery = body.Encode()
}
} |
package vcf
import "fmt"
const _SVType_name = "DeletionDuplicationInsertionInversionCopyNumberVariationTandemDuplicationDeletionMobileElementInsertionMobileElementBreakend"
var _SVType_index = [...]uint8{0, 8, 19, 28, 37, 56, 73, 94, 116, 124}
func (i SVType) String() string | {
if i < 0 || i >= SVType(len(_SVType_index)-1) {
return fmt.Sprintf("SVType(%d)", i)
}
return _SVType_name[_SVType_index[i]:_SVType_index[i+1]]
} |
package redis
import (
"github.com/fagongzi/goetty"
)
type redisDecoder struct {
}
func (decoder *redisDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {
complete, cmd, err := ReadCommand(in)
if err != nil {
return true, nil, err
}
if !complete {
return false, nil, nil
}
return true, cmd, nil
}
type redisReplyDecoder struct {
}
func NewRedisReplyDecoder() goetty.Decoder {
return &redisReplyDecoder{}
}
func (decoder *redisReplyDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {
complete, cmd, err := readCommandReply(in)
if err != nil {
return true, nil, err
}
if !complete {
return false, nil, nil
}
return true, cmd, nil
}
func NewRedisDecoder() goetty.Decoder | {
return &redisDecoder{}
} |
package convey
import (
"github.com/wallclockbuilder/convey/reporting"
)
type nilReporter struct{}
func (self *nilReporter) BeginStory(story *reporting.StoryReport) {}
func (self *nilReporter) Enter(scope *reporting.ScopeReport) {}
func (self *nilReporter) Report(report *reporting.AssertionResult) {}
func (self *nilReporter) Exit() {}
func (self *nilReporter) EndStory() {}
func (self *nilReporter) Write(p []byte) (int, error) { return len(p), nil }
func newNilReporter() *nilReporter | { return &nilReporter{} } |
package parsing
import (
"testing"
)
func TestConcatIfNotEmpty(t *testing.T) {
x := "Hello World"
output := ConcatIfNotEmpty(" ", "Hello", "", "World")
if x != output {
t.Errorf("Unexpected output from ConcatIfNotEmpty: %s", output)
}
}
func TestParseIntOrDefault(t *testing.T) {
out := ParseIntOrDefault("4", 0)
if out != 4 {
t.Errorf("Unexpected output from ParseIntOrDefault: %s", out)
}
out = ParseIntOrDefault("", 5)
if out != 5 {
t.Errorf("Unexpected output from ParseIntOrDefault default: %s", out)
}
}
func TestParseYesOrNo(t *testing.T) | {
if !ParseYesOrNo("YES") {
t.Errorf("ParseYesOrNo returned false when it should return true")
}
if !ParseYesOrNo("yes") {
t.Errorf("ParseYesOrNo returned false when it should return true")
}
} |
package core
import (
"github.com/oracle/oci-go-sdk/v46/common"
"net/http"
)
type CopyVolumeGroupBackupRequest struct {
VolumeGroupBackupId *string `mandatory:"true" contributesTo:"path" name:"volumeGroupBackupId"`
CopyVolumeGroupBackupDetails `contributesTo:"body"`
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
RequestMetadata common.RequestMetadata
}
func (request CopyVolumeGroupBackupRequest) String() string {
return common.PointerString(request)
}
func (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
func (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
func (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
type CopyVolumeGroupBackupResponse struct {
RawResponse *http.Response
VolumeGroupBackup `presentIn:"body"`
Etag *string `presentIn:"header" name:"etag"`
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response CopyVolumeGroupBackupResponse) String() string {
return common.PointerString(response)
}
func (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response | {
return response.RawResponse
} |
package ctxhttp
import (
"net/http"
"fmt"
"golang.org/x/net/context"
)
type Handler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}
type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error
var _ http.Handler = (*Adapter)(nil)
type Adapter struct {
Ctx context.Context
Handler Handler
ErrorFunc AdapterErrFunc
}
func (ca *Adapter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if err := ca.Handler.ServeHTTPContext(ca.Ctx, rw, req); err != nil {
ca.ErrorFunc(rw, req, err)
}
}
func NewAdapter(ctx context.Context, h Handler) *Adapter {
return &Adapter{
Ctx: ctx,
Handler: h,
ErrorFunc: DefaultAdapterErrFunc,
}
}
type AdapterErrFunc func(http.ResponseWriter, *http.Request, error)
var DefaultAdapterErrFunc AdapterErrFunc = defaultAdapterErrFunc
func defaultAdapterErrFunc(rw http.ResponseWriter, req *http.Request, err error) {
code := http.StatusBadRequest
http.Error(rw, fmt.Sprintf(
"%s\nApp Error: %s",
http.StatusText(code),
err,
), code)
}
func (h HandlerFunc) ServeHTTPContext(ctx context.Context, rw http.ResponseWriter, req *http.Request) error | {
return h(ctx, rw, req)
} |
package automation
import "github.com/Azure/azure-sdk-for-go/version"
func UserAgent() string {
return "Azure-SDK-For-Go/" + Version() + " automation/2017-05-15-preview"
}
func Version() string | {
return version.Number
} |
package parser
type Sequence struct {
Content []Statement
Parent *Sequence
}
func (s Sequence) Undo() (string, error) {
var content string
length := len(s.Content)
if length > 0 {
repr, err := s.Content[0].Undo()
if err != nil {
return "", err
}
content += repr
}
for i := 1; i < length; i++ {
repr, err := s.Content[i].Undo()
if err != nil {
return "", err
}
content += ";" + repr
}
content = "\"" + content + "\""
return content, nil
}
func (s *Sequence) Last() *Statement {
if len(s.Content) == 0 {
return nil
}
return &s.Content[len(s.Content)-1]
}
func (s *Sequence) Add(command string) *Statement {
s.Content = append(s.Content, Statement{Command: command})
return &s.Content[len(s.Content)-1]
}
func (s Sequence) String() (string, error) | {
var content string
if s.Parent != nil {
length := len(s.Content)
if length > 0 {
repr, err := s.Content[0].String()
if err != nil {
return "", err
}
content += repr
}
for i := 1; i < length; i++ {
repr, err := s.Content[i].String()
if err != nil {
return "", err
}
content += ";" + repr
}
content = "\"" + content + "\""
} else {
for _, statement := range s.Content {
repr, err := statement.String()
if err != nil {
return "", err
}
content += repr + "\n"
}
}
return content, nil
} |
package inst
import (
"github.com/outbrain/orchestrator/go/config"
)
type Maintenance struct {
MaintenanceId uint
Key InstanceKey
BeginTimestamp string
SecondsElapsed uint
IsActive bool
Owner string
Reason string
}
var maintenanceOwner string = ""
func SetMaintenanceOwner(owner string) {
maintenanceOwner = owner
}
func GetMaintenanceOwner() string | {
if maintenanceOwner != "" {
return maintenanceOwner
}
return config.Config.MaintenanceOwner
} |
package lbaas
import (
"testing"
"github.com/gophercloud/gophercloud/acceptance/clients"
"github.com/gophercloud/gophercloud/acceptance/tools"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas/monitors"
)
func TestMonitorsList(t *testing.T) {
client, err := clients.NewNetworkV2Client()
if err != nil {
t.Fatalf("Unable to create a network client: %v", err)
}
allPages, err := monitors.List(client, monitors.ListOpts{}).AllPages()
if err != nil {
t.Fatalf("Unable to list monitors: %v", err)
}
allMonitors, err := monitors.ExtractMonitors(allPages)
if err != nil {
t.Fatalf("Unable to extract monitors: %v", err)
}
for _, monitor := range allMonitors {
tools.PrintResource(t, monitor)
}
}
func TestMonitorsCRUD(t *testing.T) | {
client, err := clients.NewNetworkV2Client()
if err != nil {
t.Fatalf("Unable to create a network client: %v", err)
}
monitor, err := CreateMonitor(t, client)
if err != nil {
t.Fatalf("Unable to create monitor: %v", err)
}
defer DeleteMonitor(t, client, monitor.ID)
tools.PrintResource(t, monitor)
updateOpts := monitors.UpdateOpts{
Delay: 999,
}
_, err = monitors.Update(client, monitor.ID, updateOpts).Extract()
if err != nil {
t.Fatalf("Unable to update monitor: %v")
}
newMonitor, err := monitors.Get(client, monitor.ID).Extract()
if err != nil {
t.Fatalf("Unable to get monitor: %v")
}
tools.PrintResource(t, newMonitor)
} |
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
gin.SetMode(gin.ReleaseMode)
router = gin.Default()
router.LoadHTMLGlob("templates/*")
initializeRoutes()
router.Run()
}
func render(c *gin.Context, data gin.H, templateName string) | {
loggedInInterface, _ := c.Get("is_logged_in")
data["is_logged_in"] = loggedInInterface.(bool)
switch c.Request.Header.Get("Accept") {
case "application/json":
c.JSON(http.StatusOK, data["payload"])
case "application/xml":
c.XML(http.StatusOK, data["payload"])
default:
c.HTML(http.StatusOK, templateName, data)
}
} |
package main
import (
"fmt"
"github.com/gourd/goparser"
"github.com/gourd/gourd/compile"
"github.com/gourd/gourd/templates"
)
func init() {
t, err := templates.Asset("store/upperio.tpl")
if err != nil {
panic(err)
}
tpls.Append("gen store:upperio", string(t))
tpls.AddDeps("gen store:upperio", "gen:general")
tpls.AddPrep("gen store:upperio", func(in interface{}) (interface{}, error) {
var data map[string]interface{}
var f interface{}
var id *goparser.FieldSpec
var ok bool
if data, ok = in.(compile.Context); !ok {
return in, fmt.Errorf("Unable to prepare. Incorrect data provided: %#v", in)
}
if f, ok = data["Id"]; !ok {
return in, fmt.Errorf("Unable to prepare. No Id found in given data: %#v",
data)
}
if id, ok = f.(*goparser.FieldSpec); !ok {
return in, fmt.Errorf("Unable to prepare. Wrong Id type: %#v", f)
}
data["Id"] = &UpperFieldSpec{
id,
}
return data, nil
})
}
type UpperFieldSpec struct {
*goparser.FieldSpec
}
func (s *UpperFieldSpec) IsInt() bool {
return s.Type == "int" || s.Type == "uint" ||
s.Type == "int32" || s.Type == "uint32" ||
s.Type == "int64" || s.Type == "uint64"
}
func (s UpperFieldSpec) IsString() bool | {
return s.Type == "string"
} |
package sodium
import "C"
func RuntimeHasSse2() bool {
return C.sodium_runtime_has_sse2() != 0
}
func RuntimeHasSse3() bool {
return C.sodium_runtime_has_sse3() != 0
}
func RuntimeHasNeon() bool | {
return C.sodium_runtime_has_neon() != 0
} |
package helpers
import "testing"
func TestIsRegionNormalized(t *testing.T) {
cases := []struct {
input string
expectedResult string
}{
{
input: "westus",
expectedResult: "westus",
},
{
input: "West US",
expectedResult: "westus",
},
{
input: "Eastern Africa",
expectedResult: "easternafrica",
},
{
input: "",
expectedResult: "",
},
}
for _, c := range cases {
result := NormalizeAzureRegion(c.input)
if c.expectedResult != result {
t.Fatalf("NormalizeAzureRegion returned unexpected result: expected %s but got %s", c.expectedResult, result)
}
}
}
func TestPointerToBool(t *testing.T) | {
boolVar := true
ret := PointerToBool(boolVar)
if *ret != boolVar {
t.Fatalf("expected PointerToBool(true) to return *true, instead returned %#v", ret)
}
} |
package rpc
import (
"github.com/golang/glog"
"github.com/nebulaim/telegramd/proto/mtproto"
"golang.org/x/net/context"
"github.com/nebulaim/telegramd/baselib/grpc_util"
"github.com/nebulaim/telegramd/baselib/logger"
)
func (s *MessagesServiceImpl) MessagesGetHistoryLayer51(ctx context.Context, request *mtproto.TLMessagesGetHistoryLayer51) (*mtproto.Messages_Messages, error) | {
md := grpc_util.RpcMetadataFromIncoming(ctx)
glog.Infof("messages.getHistory#afa92846 - metadata: %s, request: %s", logger.JsonDebugData(md), logger.JsonDebugData(request))
request2 := &mtproto.TLMessagesGetHistory{
Peer: request.GetPeer(),
OffsetId: request.GetOffsetId(),
OffsetDate: request.GetOffsetDate(),
AddOffset: request.GetAddOffset(),
Limit: request.GetLimit(),
MaxId: request.GetMaxId(),
MinId: request.GetMinId(),
Hash: 0,
}
messagesMessages := s.getHistoryMessages(md, request2)
glog.Infof("messages.getHistory#dcbb8260 - reply: %s", logger.JsonDebugData(messagesMessages))
return messagesMessages, nil
} |
package main
import (
"math"
"sort"
)
type NaiveSieve struct {
sieve map[int]bool
}
func NewNaiveSieve(limit int) NaiveSieve {
primes := make(map[int]bool)
primes[2] = true
for n := 3; n < limit; n += 2 {
if IsNaivePrime(n) {
primes[n] = true
}
}
return NaiveSieve{primes}
}
func (self *NaiveSieve) Contains(n int) bool {
_, ok := self.sieve[n]
return ok
}
func IsNaivePrime(n int) bool {
switch {
case n == 1:
return false
case n == 2:
return true
case n%2 == 0:
return false
}
limit := int(math.Sqrt(float64(n)))
for i := 3; i <= limit; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
func (self *NaiveSieve) Primes() []int | {
primes := make([]int, 0, len(self.sieve))
for n, _ := range self.sieve {
primes = append(primes, n)
}
sort.Ints(primes)
return primes
} |
package routing
import "net/http"
func GET(handler http.Handler) Matcher {
return Method("GET", handler)
}
func GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {
return GET(http.HandlerFunc(handler))
}
func POST(handler http.Handler) Matcher {
return Method("POST", handler)
}
func POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {
return POST(http.HandlerFunc(handler))
}
func PUT(handler http.Handler) Matcher {
return Method("PUT", handler)
}
func PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {
return PUT(http.HandlerFunc(handler))
}
func PATCH(handler http.Handler) Matcher {
return Method("PATCH", handler)
}
func PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {
return PATCH(http.HandlerFunc(handler))
}
func DELETE(handler http.Handler) Matcher {
return Method("DELETE", handler)
}
func DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {
return DELETE(http.HandlerFunc(handler))
}
func MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {
resp.WriteHeader(405)
return true
}
func Method(method string, handler http.Handler) Matcher | {
return func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {
if req.Method == method {
handler.ServeHTTP(resp, req)
return true
}
return false
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.