input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package glw
import "golang.org/x/mobile/gl"
type A2fv gl.Attrib
func (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)
}
type A3fv gl.Attrib
func (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A3fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)
}
type A4fv gl.Attrib
func (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A4fv) Pointer() | {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)
} |
package cli
import (
"errors"
"fmt"
"log"
"github.com/alexyer/ghost/client"
)
func ObtainUnixSocketClient(socket string) (*client.GhostClient, error) {
return connect(socket, "unix")
}
func connect(addr, network string) (*client.GhostClient, error) {
c := client.New(&client.Options{
Addr: addr,
Network: network,
})
if _, err := c.Ping(); err != nil {
return nil, errors.New(fmt.Sprintf("cli-ghost: cannot obtain connection to %s", addr))
}
log.Printf("Connection to %s is successfull.", addr)
return c, nil
}
func ObtainClient(host string, port int) (*client.GhostClient, error) | {
addr := fmt.Sprintf("%s:%d", host, port)
return connect(addr, "tcp")
} |
package command
import (
"errors"
"os"
"strings"
"github.com/bitrise-io/go-utils/pathutil"
)
func CopyFile(src, dst string) error {
isDir, err := pathutil.IsDirExists(src)
if err != nil {
return err
}
if isDir {
return errors.New("Source is a directory: " + src)
}
args := []string{src, dst}
return RunCommand("rsync", args...)
}
func RemoveDir(dirPth string) error {
if exist, err := pathutil.IsPathExists(dirPth); err != nil {
return err
} else if exist {
if err := os.RemoveAll(dirPth); err != nil {
return err
}
}
return nil
}
func RemoveFile(pth string) error {
if exist, err := pathutil.IsPathExists(pth); err != nil {
return err
} else if exist {
if err := os.Remove(pth); err != nil {
return err
}
}
return nil
}
func CopyDir(src, dst string, isOnlyContent bool) error | {
if isOnlyContent && !strings.HasSuffix(src, "/") {
src = src + "/"
}
args := []string{"-ar", src, dst}
return RunCommand("rsync", args...)
} |
package watch
type FilterFunc func(in Event) (out Event, keep bool)
func Filter(w Interface, f FilterFunc) Interface {
fw := &filteredWatch{
incoming: w,
result: make(chan Event),
f: f,
}
go fw.loop()
return fw
}
type filteredWatch struct {
incoming Interface
result chan Event
f FilterFunc
}
func (fw *filteredWatch) Stop() {
fw.incoming.Stop()
}
func (fw *filteredWatch) loop() {
defer close(fw.result)
for {
event, ok := <-fw.incoming.ResultChan()
if !ok {
break
}
filtered, keep := fw.f(event)
if keep {
fw.result <- filtered
}
}
}
func (fw *filteredWatch) ResultChan() <-chan Event | {
return fw.result
} |
package controller
import (
"fmt"
)
type AdminParams struct {
Name *string
InviteId *string
InviteKey *string
ConfirmDelete *string
}
func NewAdminParams() *AdminParams {
return new(AdminParams)
}
func (params *AdminParams) ValidateName(required bool) error {
if required && *params.Name == "" {
return fmt.Errorf("name cannot be empty")
}
return nil
}
func (params *AdminParams) ValidateInviteId(required bool) error { return nil }
func (params *AdminParams) ValidateInviteKey(required bool) error | { return nil } |
package main
import (
"net/http"
"os"
"gopkg.in/gin-gonic/gin.v1"
)
var router *gin.Engine
func main() {
if os.Getenv("GIN_ENV") == "production" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
router = gin.Default()
router.LoadHTMLGlob("templates/*")
initializeRoutes()
router.Run()
}
func render(c *gin.Context, templateName string, data gin.H) | {
c.HTML(http.StatusOK, templateName, data)
} |
package bc
import (
"io"
"log"
"os"
"os/exec"
)
type Bc interface {
Exec(string) error
Quit()
}
type bc struct {
cmd *exec.Cmd
stdin io.WriteCloser
stdout io.ReadCloser
}
func Start() Bc {
cmd := exec.Command("bc")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
cmd.Stderr = os.Stderr
cmd.Start()
return &bc{cmd, stdin, stdout}
}
var inputSuffix = []byte("\n\"\x04\"\n")
func readByte(r io.Reader) (byte, error) {
var buf [1]byte
_, err := r.Read(buf[:])
if err != nil {
return 0, err
}
return buf[0], nil
}
func (bc *bc) Quit() {
bc.stdin.Close()
bc.cmd.Wait()
bc.stdout.Close()
}
func (bc *bc) Exec(code string) error | {
bc.stdin.Write([]byte(code))
bc.stdin.Write(inputSuffix)
for {
b, err := readByte(bc.stdout)
if err != nil {
return err
}
if b == 0x04 {
break
}
os.Stdout.Write([]byte{b})
}
return nil
} |
package wxdata
import (
"fmt"
"sync"
"time"
)
func DownloadGfs(targetFolder string) {
for _,t:= range GetGfsCandidateAnatimes(){
downloadGfs(targetFolder, t)
}
}
func downloadGfs(targetFolder string, date time.Time) | {
items := GetGfsDownloadItems(date)
var wg sync.WaitGroup
wg.Add(len(items))
for _,item := range items {
go (func(item DownloadItem){
defer wg.Done()
Download(item, targetFolder)
})(item)
fmt.Println(item.Url)
}
wg.Wait()
} |
package tc
import (
"encoding/json"
)
type CRStates struct {
Caches map[CacheName]IsAvailable `json:"caches"`
DeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:"deliveryServices"`
}
type CRStatesDeliveryService struct {
DisabledLocations []CacheGroupName `json:"disabledLocations"`
IsAvailable bool `json:"isAvailable"`
}
type IsAvailable struct {
IsAvailable bool `json:"isAvailable"`
}
func NewCRStates() CRStates {
return CRStates{
Caches: map[CacheName]IsAvailable{},
DeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{},
}
}
func (a CRStates) Copy() CRStates {
b := NewCRStates()
for k, v := range a.Caches {
b.Caches[k] = v
}
for k, v := range a.DeliveryService {
b.DeliveryService[k] = v
}
return b
}
func (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService {
b := map[DeliveryServiceName]CRStatesDeliveryService{}
for k, v := range a.DeliveryService {
b[k] = v
}
return b
}
func CRStatesMarshall(states CRStates) ([]byte, error) {
return json.Marshal(states)
}
func CRStatesUnMarshall(body []byte) (CRStates, error) {
var crStates CRStates
err := json.Unmarshal(body, &crStates)
return crStates, err
}
func (a CRStates) CopyCaches() map[CacheName]IsAvailable | {
b := map[CacheName]IsAvailable{}
for k, v := range a.Caches {
b[k] = v
}
return b
} |
package main
import (
"fmt"
"strconv"
)
func simpleEvalInt(a, b int, op string) int {
switch op {
case "+":
return a + b
case "-":
return a - b
case "/":
return a / b
case "*":
return a * b
case "^":
return power(a, b)
default:
return 0
}
}
func power(a, b int) int {
ans := 1
for i := 0; i < b; i++ {
ans = a * ans
}
return ans
}
func evalPostfixInt(postfix []string) (int, error) | {
var stack []int
for _, val := range postfix {
if isOp(val) {
a := stack[len(stack)-2]
b := stack[len(stack)-1]
retVal := simpleEvalInt(a, b, val)
stack = append(stack[0:len(stack)-2], retVal)
} else {
num, err := strconv.Atoi(val)
if err != nil {
return 0, nil
}
stack = append(stack, num)
}
}
if len(stack) != 1 {
err := fmt.Errorf("error calculating postfix")
return 0, err
}
return stack[0], nil
} |
package dns
import (
"github.com/cilium/cilium/pkg/hubble/metrics/api"
)
type dnsPlugin struct{}
func (p *dnsPlugin) NewHandler() api.Handler {
return &dnsHandler{}
}
func (p *dnsPlugin) HelpText() string {
return `dns - DNS related metrics
Reports metrics related to DNS queries and responses
Metrics:
hubble_dns_queries_total Number of observed TCP queries
hubble_dns_responses_total Number of observed TCP responses
Options:
query - Include query name as label
ignoreAAAA - Do not include AAAA query & responses in metrics` +
api.ContextOptionsHelp
}
func init() | {
api.DefaultRegistry().Register("dns", &dnsPlugin{})
} |
package srpc
import (
"crypto/tls"
"github.com/Symantec/Dominator/lib/connpool"
)
func newClientResource(network, address string) *ClientResource {
clientResource := &ClientResource{
network: network,
address: address,
}
clientResource.privateClientResource.clientResource = clientResource
rp := connpool.GetResourcePool()
clientResource.resource = rp.Create(&clientResource.privateClientResource)
return clientResource
}
func (cr *ClientResource) getHTTP(tlsConfig *tls.Config,
cancelChannel <-chan struct{}, dialer connpool.Dialer) (*Client, error) {
cr.privateClientResource.tlsConfig = tlsConfig
cr.privateClientResource.dialer = dialer
if err := cr.resource.Get(cancelChannel); err != nil {
return nil, err
}
cr.inUse = true
clientMetricsMutex.Lock()
numInUseClientConnections++
clientMetricsMutex.Unlock()
return cr.client, nil
}
func (pcr *privateClientResource) Allocate() error {
cr := pcr.clientResource
client, err := dialHTTP(cr.network, cr.address, pcr.tlsConfig, pcr.dialer)
if err != nil {
return err
}
cr.client = client
client.resource = cr
return nil
}
func (pcr *privateClientResource) Release() error {
cr := pcr.clientResource
err := cr.client.conn.Close()
cr.client = nil
return err
}
func (client *Client) put() | {
client.resource.resource.Put()
if client.resource.inUse {
clientMetricsMutex.Lock()
numInUseClientConnections--
clientMetricsMutex.Unlock()
client.resource.inUse = false
}
} |
package scripts
import (
"bytes"
"io/ioutil"
"github.com/lfkeitel/inca-tool/devices"
)
func getHostVariables(host *devices.Device) map[string]string {
argList := make(map[string]string)
argList["protocol"] = host.GetSetting("protocol")
if argList["protocol"] == "" {
argList["protocol"] = "ssh"
}
argList["hostname"] = host.GetSetting("address")
if argList["hostname"] == "" {
argList["hostname"] = host.Name
}
argList["remote_user"] = host.GetSetting("remote_user")
if argList["remote_user"] == "" {
argList["remote_user"] = "root"
}
argList["remote_password"] = host.GetSetting("remote_password")
argList["cisco_enable"] = host.GetSetting("cisco_enable")
if argList["cisco_enable"] == "" {
argList["cisco_enable"] = host.GetSetting("remote_password")
}
return argList
}
func insertVariables(filename string, vars map[string]string) error | {
file, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
for n, v := range vars {
if n[0] == '_' {
n = n[1:]
}
file = bytes.Replace(file, []byte("{{"+n+"}}"), []byte(v), -1)
}
if err := ioutil.WriteFile(filename, file, 0744); err != nil {
return err
}
return nil
} |
package wait
import (
"fmt"
"time"
)
func Predicate(pred func() bool, timeout time.Duration) error {
const pollInterval = 20 * time.Millisecond
exitTimer := time.After(timeout)
for {
<-time.After(pollInterval)
select {
case <-exitTimer:
return fmt.Errorf("predicate not satisfied after time out")
default:
}
if pred() {
return nil
}
}
}
func Invariant(statement func() bool, timeout time.Duration) error {
const pollInterval = 20 * time.Millisecond
exitTimer := time.After(timeout)
for {
<-time.After(pollInterval)
if !statement() {
return fmt.Errorf("invariant broken before time out")
}
select {
case <-exitTimer:
return nil
default:
}
}
}
func InvariantNoError(f func() error, timeout time.Duration) error {
var predErr error
pred := func() bool {
if err := f(); err != nil {
predErr = err
return false
}
return true
}
if err := Invariant(pred, timeout); err != nil {
return predErr
}
return nil
}
func NoError(f func() error, timeout time.Duration) error | {
var predErr error
pred := func() bool {
if err := f(); err != nil {
predErr = err
return false
}
return true
}
if err := Predicate(pred, timeout); err != nil {
return predErr
}
return nil
} |
package minicon
import "container/ring"
type History struct {
r *ring.Ring
}
type HistoryMarker *ring.Ring
func NewHistory(capacity int) *History {
return &History{ring.New(capacity)}
}
func (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {
hs.Restore(mark)
if s != "" && hs.r.Value != s {
hs.r.Value = s
hs.r = hs.r.Next()
}
return nil
}
func (hs *History) Back() (string, bool) {
return hs._update(hs.r.Prev())
}
func (hs *History) Forward() (string, bool) {
return hs._update(hs.r.Next())
}
func (hs *History) Restore(mark HistoryMarker) {
if mark != nil {
hs.r = mark
}
}
func (hs *History) _update(r *ring.Ring) (ret string, okay bool) {
if s, ok := r.Value.(string); ok && s != "" {
hs.r = r
ret, okay = s, ok
}
return ret, okay
}
func (hs *History) Mark() HistoryMarker | {
return hs.r
} |
package lmath
func selfDividingNumbers(left int, right int) []int | {
res := []int{}
for i := left; i <= right; i++ {
j := i
for ; j > 0; j /= 10 {
if j%10 == 0 || i%(j%10) != 0 {
break
}
}
if j == 0 {
res = append(res, i)
}
}
return res
} |
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) 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)
}
func (i *Uint32) Add(delta uint32) uint32 | {
return atomic.AddUint32(&i.v, delta)
} |
package v1alpha1
import (
"testing"
"github.com/google/go-cmp/cmp"
corev1 "k8s.io/api/core/v1"
)
func TestBuildTemplateSpec(t *testing.T) {
c := BuildTemplate{
Spec: BuildTemplateSpec{
Steps: []corev1.Container{{
Name: "build-spec",
}},
},
}
expectedBuildSpec := BuildTemplateSpec{Steps: []corev1.Container{{Name: "build-spec"}}}
if a := cmp.Diff(c.TemplateSpec(), expectedBuildSpec); a != "" {
t.Errorf("templateSpec mismatch; expected: %v got: %v", expectedBuildSpec, a)
}
}
func TestBuildTemplateGroupVersionKind(t *testing.T) | {
c := BuildTemplate{}
expectedKind := "BuildTemplate"
if c.GetGroupVersionKind().Kind != expectedKind {
t.Errorf("GetGroupVersionKind mismatch; expected: %v got: %v", expectedKind, c.GetGroupVersionKind().Kind)
}
} |
package main
import (
"os"
"runtime"
)
func main() {
}
func init() | {
c := make(chan int, 1)
defer func() {
c <- 0
}()
go func() {
os.Exit(<-c)
}()
runtime.Goexit()
} |
package mock
import (
"github.com/eventials/goevents/messaging"
"github.com/stretchr/testify/mock"
)
type Connection struct {
mock.Mock
}
func NewMockConnection() messaging.Connection {
return &Connection{}
}
func (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {
args := c.Called(autoAck, exchange, queue)
return args.Get(0).(messaging.Consumer), args.Error(1)
}
func (c *Connection) Producer(exchange string) (messaging.Producer, error) {
args := c.Called(exchange)
return args.Get(0).(messaging.Producer), args.Error(1)
}
func (c *Connection) Close() {
c.Called()
}
func (c *Connection) NotifyConnectionClose() <-chan error {
args := c.Called()
return args.Get(0).(chan error)
}
func (c *Connection) NotifyReestablish() <-chan bool {
args := c.Called()
return args.Get(0).(chan bool)
}
func (c *Connection) WaitUntilConnectionCloses() {
c.Called()
}
func (c *Connection) WaitUntilConnectionReestablished() {
c.Called()
}
func (c *Connection) IsConnected() bool | {
args := c.Called()
return args.Get(0).(bool)
} |
package miniredis
import (
"reflect"
"testing"
)
func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
tb.Helper()
if !condition {
tb.Errorf(msg, v...)
}
}
func ok(tb testing.TB, err error) {
tb.Helper()
if err != nil {
tb.Errorf("unexpected error: %s", err.Error())
}
}
func equals(tb testing.TB, exp, act interface{}) {
tb.Helper()
if !reflect.DeepEqual(exp, act) {
tb.Errorf("expected: %#v got: %#v", exp, act)
}
}
func mustFail(tb testing.TB, err error, want string) | {
tb.Helper()
if err == nil {
tb.Errorf("expected an error, but got a nil")
}
if have := err.Error(); have != want {
tb.Errorf("have %q, want %q", have, want)
}
} |
package handlers
import (
"net/http"
"appengine/user"
"appengine"
"appengine/datastore"
"text/template"
"time"
"model"
"model/booth"
"util"
)
func handleGetAllBooths(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
util.RedirectIfNotLoggedIn(w, r)
q := datastore.NewQuery("Booth").Ancestor(booth.Key(c)).Order("-Date").Limit(10)
booths := make([]model.Booth, 10)
if _, err := q.GetAll(c, &booths); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
boothsTemplate, _ := template.ParseFiles("./templates/booths/index.html")
if err := boothsTemplate.Execute(w, booths); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func handleCreateBooth(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
u := user.Current(c)
util.RedirectIfNotLoggedIn(w, r)
b := model.Booth{
Author: u.String(),
Date: time.Now(),
Name: r.FormValue("name"),
}
key := datastore.NewIncompleteKey(c, "Booth", booth.Key(c))
_, err := datastore.Put(c, key, &b)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusCreated)
}
func HandleBooths(w http.ResponseWriter, r *http.Request) | {
switch r.Method {
case "GET":
handleGetAllBooths(w, r)
break;
case "POST":
handleCreateBooth(w, r)
break;
default:
http.Error(w, "", http.StatusMethodNotAllowed)
}
} |
package models
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/errors"
"github.com/go-openapi/validate"
)
type TaskIDRange struct {
End *int32 `json:"end"`
Start *int32 `json:"start"`
}
func (m *TaskIDRange) validateEnd(formats strfmt.Registry) error {
if err := validate.Required("end", "body", m.End); err != nil {
return err
}
return nil
}
func (m *TaskIDRange) validateStart(formats strfmt.Registry) error {
if err := validate.Required("start", "body", m.Start); err != nil {
return err
}
return nil
}
func (m *TaskIDRange) Validate(formats strfmt.Registry) error | {
var res []error
if err := m.validateEnd(formats); err != nil {
res = append(res, err)
}
if err := m.validateStart(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
} |
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccGoogleSqlDatabaseInstance_importBasic(t *testing.T) {
t.Parallel()
resourceName := "google_sql_database_instance.instance"
databaseID := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccGoogleSqlDatabaseInstanceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: fmt.Sprintf(
testGoogleSqlDatabaseInstance_basic, databaseID),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func TestAccGoogleSqlDatabaseInstance_importBasic3(t *testing.T) | {
t.Parallel()
resourceName := "google_sql_database_instance.instance"
databaseID := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccGoogleSqlDatabaseInstanceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: fmt.Sprintf(
testGoogleSqlDatabaseInstance_basic3, databaseID),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
} |
package plugin
type Kind uint8
const (
Audit Kind = 1 + iota
Authentication
Schema
Daemon
)
type State uint8
const (
Uninitialized State = iota
Ready
Dying
Disable
)
func (s State) String() (str string) {
switch s {
case Uninitialized:
str = "Uninitialized"
case Ready:
str = "Ready"
case Dying:
str = "Dying"
case Disable:
str = "Disable"
}
return
}
func (k Kind) String() (str string) | {
switch k {
case Audit:
str = "Audit"
case Authentication:
str = "Authentication"
case Schema:
str = "Schema"
case Daemon:
str = "Daemon"
}
return
} |
package common
import (
"fmt"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/component-helpers/storage/ephemeral"
)
const (
PodPVCIndex = "pod-pvc-index"
)
func PodPVCIndexFunc() func(obj interface{}) ([]string, error) {
return func(obj interface{}) ([]string, error) {
pod, ok := obj.(*v1.Pod)
if !ok {
return []string{}, nil
}
keys := []string{}
for _, podVolume := range pod.Spec.Volumes {
claimName := ""
if pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {
claimName = pvcSource.ClaimName
} else if podVolume.VolumeSource.Ephemeral != nil {
claimName = ephemeral.VolumeClaimName(pod, &podVolume)
}
if claimName != "" {
keys = append(keys, fmt.Sprintf("%s/%s", pod.Namespace, claimName))
}
}
return keys, nil
}
}
func AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error {
indexers := indexer.GetIndexers()
if _, ok := indexers[indexName]; ok {
return nil
}
return indexer.AddIndexers(cache.Indexers{indexName: indexFunc})
}
func AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error | {
return AddIndexerIfNotPresent(indexer, PodPVCIndex, PodPVCIndexFunc())
} |
package aws
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSInspectorResourceGroup_basic(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSInspectorResourceGroup,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSInspectorResourceGroupExists("aws_inspector_resource_group.foo"),
),
},
{
Config: testAccCheckAWSInspectorResourceGroupModified,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSInspectorResourceGroupExists("aws_inspector_resource_group.foo"),
),
},
},
})
}
var testAccAWSInspectorResourceGroup = `
resource "aws_inspector_resource_group" "foo" {
tags = {
Name = "foo"
}
}`
var testAccCheckAWSInspectorResourceGroupModified = `
resource "aws_inspector_resource_group" "foo" {
tags = {
Name = "bar"
}
}`
func testAccCheckAWSInspectorResourceGroupExists(name string) resource.TestCheckFunc | {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}
return nil
}
} |
package browser
import (
"os"
"os/exec"
"runtime"
)
func Open(url string) bool {
for _, args := range Commands() {
cmd := exec.Command(args[0], append(args[1:], url)...)
if cmd.Start() == nil {
return true
}
}
return false
}
func Commands() [][]string | {
var cmds [][]string
if exe := os.Getenv("BROWSER"); exe != "" {
cmds = append(cmds, []string{exe})
}
switch runtime.GOOS {
case "darwin":
cmds = append(cmds, []string{"/usr/bin/open"})
case "windows":
cmds = append(cmds, []string{"cmd", "/c", "start"})
default:
cmds = append(cmds, []string{"xdg-open"})
}
cmds = append(cmds,
[]string{"chrome"},
[]string{"google-chrome"},
[]string{"chromium"},
[]string{"firefox"},
)
return cmds
} |
package nogo
type Permission int
type Principal interface {
GetId() string
GetSid() string
GetRoleNames() []string
}
type Role interface {
GetName() string
IsAdmin() bool
HasPermission(permission Permission) (bool, error)
}
func NewRole(name string, mask Permission) Role {
return &defaultRole{RoleName: name, PermissionMask: mask, Admin: false}
}
func NewAdminRole(name string, mask Permission) Role {
return &defaultRole{RoleName: name, PermissionMask: mask, Admin: true}
}
type defaultRole struct {
RoleName string `db:"role_name"`
PermissionMask Permission `db:"permission_mask"`
Admin bool `db:"is_admin"`
}
func (this *defaultRole) GetName() string {
return this.RoleName
}
func (this *defaultRole) HasPermission(permission Permission) (bool, error) {
val := (this.PermissionMask&permission != 0)
return val, nil
}
func (this *defaultRole) IsAdmin() bool | {
return this.Admin
} |
package coverage
import "testing"
func TestCoverage(t *testing.T) | {
live()
} |
package windows
import (
"fmt"
"io"
"io/ioutil"
"net/http"
)
func downloadFile(url string) (string, error) | {
response, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("unable to download from %q: %w", url, err)
}
defer response.Body.Close()
tempFile, err := ioutil.TempFile("", "")
if err != nil {
return "", fmt.Errorf("unable to create temp file: %w", err)
}
defer tempFile.Close()
_, err = io.Copy(tempFile, response.Body)
return tempFile.Name(), err
} |
package buckets
import (
"github.com/campadrenalin/scrap"
"testing"
)
func TestAnyBucket_Empty(t *testing.T) {
b := AnyBucket{}
if b.Check("foo") {
t.Fatal("Should always return false when there are no children")
}
}
func TestAnyBucket_OneItem(t *testing.T) {
b := AnyBucket{
Children: []scrap.Bucket{
scrap.NewCountBucket(1),
},
}
tests := bt_slice{
bt{"foo", true, "First should succeed"},
bt{"foo", false, "Second should fail"},
}
tests.Run(t, b)
}
func TestAnyBucket_MultipleItems(t *testing.T) | {
b := AnyBucket{
Children: []scrap.Bucket{
scrap.NewCountBucket(1),
scrap.NewCountBucket(2),
},
}
tests := bt_slice{
bt{"foo", true, "First bucket says yes"},
bt{"foo", true, "First bucket exhausted, second says yes"},
bt{"foo", true, "Second bucket says yes for the final time"},
bt{"foo", false, "Second bucket exhausted"},
}
tests.Run(t, b)
b.Children[0].(*scrap.CountBucket).SetMaxHits(3)
tests = bt_slice{
bt{"foo", true, "First bucket says yes"},
bt{"foo", true, "First bucket says yes for the final time"},
bt{"foo", false, "Both buckets exhausted"},
}
tests.Run(t, b)
} |
package git
import (
"fmt"
"os"
"github.com/Originate/git-town/src/command"
"github.com/Originate/git-town/src/util"
)
func EnsureDoesNotHaveOpenChanges(message string) {
util.Ensure(!HasOpenChanges(), "You have uncommitted changes. "+message)
}
var rootDirectory string
func GetRootDirectory() string {
if rootDirectory == "" {
rootDirectory = command.MustRun("git", "rev-parse", "--show-toplevel").OutputSanitized()
}
return rootDirectory
}
func HasConflicts() bool {
return command.MustRun("git", "status").OutputContainsText("Unmerged paths")
}
func HasOpenChanges() bool {
return command.MustRun("git", "status", "--porcelain").OutputSanitized() != ""
}
func HasShippableChanges(branchName string) bool {
return command.MustRun("git", "diff", Config().GetMainBranch()+".."+branchName).OutputSanitized() != ""
}
func IsMergeInProgress() bool {
_, err := os.Stat(fmt.Sprintf("%s/.git/MERGE_HEAD", GetRootDirectory()))
return err == nil
}
func IsRebaseInProgress() bool {
return command.MustRun("git", "status").OutputContainsText("rebase in progress")
}
func EnsureDoesNotHaveConflicts() | {
util.Ensure(!HasConflicts(), "You must resolve the conflicts before continuing")
} |
package checker
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"errors"
"net/http"
)
type tokenChecker struct {
}
func (checker *tokenChecker) Support(eventMap map[string]string) bool {
return true
}
func (checker *tokenChecker) Check(eventMap map[string]string, expectedToken string, reqHeader http.Header, reqBody []byte) (bool, error) | {
passCheck := false
switch eventMap["sourceType"] {
case "customize":
if expectedToken == eventMap["token"] {
passCheck = true
}
case "gitlab":
if expectedToken == eventMap["token"] {
passCheck = true
}
case "github":
mac := hmac.New(sha1.New, []byte(expectedToken))
mac.Write(reqBody)
expectedMAC := mac.Sum(nil)
expectedSig := "sha1=" + hex.EncodeToString(expectedMAC)
if expectedSig == eventMap["token"] {
passCheck = true
}
}
if passCheck {
return passCheck, nil
}
return passCheck, errors.New("token checker failed")
} |
package main
import (
"encoding/hex"
"errors"
)
type User struct {
Id uint32
Name string
Password string
CertHash string
Email string
TextureBlob string
CommentBlob string
LastChannelId int
LastActive uint64
}
func NewUser(id uint32, name string) (user *User, err error) {
if id < 0 {
return nil, errors.New("Invalid user id")
}
if len(name) == 0 {
return nil, errors.New("Invalid username")
}
return &User{
Id: id,
Name: name,
}, nil
}
func (user *User) HasComment() bool {
return len(user.CommentBlob) > 0
}
func (user *User) CommentBlobHashBytes() (buf []byte) {
buf, err := hex.DecodeString(user.CommentBlob)
if err != nil {
return nil
}
return buf
}
func (user *User) HasTexture() bool {
return len(user.TextureBlob) > 0
}
func (user *User) TextureBlobHashBytes() (buf []byte) | {
buf, err := hex.DecodeString(user.TextureBlob)
if err != nil {
return nil
}
return buf
} |
package plus
func keySearch(keys keys, key Key) int {
low, high := 0, len(keys)-1
var mid int
for low <= high {
mid = (high + low) / 2
switch keys[mid].Compare(key) {
case 1:
low = mid + 1
case -1:
high = mid - 1
case 0:
return mid
}
}
return low
}
type btree struct {
root node
nodeSize, number uint64
}
func (tree *btree) Insert(keys ...Key) {
for _, key := range keys {
tree.insert(key)
}
}
func (tree *btree) Iter(key Key) Iterator {
if tree.root == nil {
return nilIterator()
}
return tree.root.find(key)
}
func (tree *btree) get(key Key) Key {
iter := tree.root.find(key)
if !iter.Next() {
return nil
}
if iter.Value().Compare(key) == 0 {
return iter.Value()
}
return nil
}
func (tree *btree) Get(keys ...Key) Keys {
results := make(Keys, 0, len(keys))
for _, k := range keys {
results = append(results, tree.get(k))
}
return results
}
func (tree *btree) Len() uint64 {
return tree.number
}
func newBTree(nodeSize uint64) *btree {
return &btree{
nodeSize: nodeSize,
root: newLeafNode(nodeSize),
}
}
func (tree *btree) insert(key Key) | {
if tree.root == nil {
n := newLeafNode(tree.nodeSize)
n.insert(tree, key)
tree.number = 1
return
}
result := tree.root.insert(tree, key)
if result {
tree.number++
}
if tree.root.needsSplit(tree.nodeSize) {
tree.root = split(tree, nil, tree.root)
}
} |
package slice
import (
"fmt"
"testing"
"github.com/speedland/go/x/xtesting/assert"
)
func ExampleSplitByLength() {
var a = []int{0, 1, 2, 3, 4}
var b = SplitByLength(a, 2).([][]int)
fmt.Println(b)
}
func Test_ToInterface(t *testing.T) {
a := assert.New(t)
type T struct {
i int
}
intSlice := []int{1, 2, 3}
ia := ToInterface(intSlice)
a.EqInt(2, ia[1].(int))
tSlice := []T{T{1}, T{2}, T{3}}
ia = ToInterface(tSlice)
a.EqInt(2, ia[1].(T).i)
ptrTSlice := []*T{&T{1}, &T{2}, &T{3}}
ia = ToInterface(ptrTSlice)
a.EqInt(2, ia[1].(*T).i)
}
func Test_ToAddr(t *testing.T) {
a := assert.New(t)
type Foo struct {
field string
}
list := ToAddr([]Foo{Foo{
field: "foo",
}}).([]*Foo)
a.EqStr("foo", list[0].field)
}
func Test_ToElem(t *testing.T) {
a := assert.New(t)
type Foo struct {
field string
}
list := ToElem([]*Foo{&Foo{
field: "foo",
}}).([]Foo)
a.EqStr("foo", list[0].field)
}
func Test_SplitByLength(t *testing.T) | {
a := assert.New(t)
var a1 = []int{1, 2, 3, 4, 5}
var a2 = SplitByLength(a1, 3).([][]int)
a.EqInt(1, a2[0][0])
a.EqInt(2, a2[0][1])
a.EqInt(3, a2[0][2])
a.EqInt(2, len(a2[1]))
a.EqInt(4, a2[1][0])
a.EqInt(5, a2[1][1])
} |
package local
import (
"time"
"github.com/prometheus/prometheus/util/testutil"
)
type testStorageCloser struct {
storage Storage
directory testutil.Closer
}
func NewTestStorage(t testutil.T, encoding chunkEncoding) (*memorySeriesStorage, testutil.Closer) {
DefaultChunkEncoding = encoding
directory := testutil.NewTemporaryDirectory("test_storage", t)
o := &MemorySeriesStorageOptions{
MemoryChunks: 1000000,
MaxChunksToPersist: 1000000,
PersistenceRetentionPeriod: 24 * time.Hour * 365 * 100,
PersistenceStoragePath: directory.Path(),
CheckpointInterval: time.Hour,
SyncStrategy: Adaptive,
}
storage := NewMemorySeriesStorage(o)
if err := storage.Start(); err != nil {
directory.Close()
t.Fatalf("Error creating storage: %s", err)
}
closer := &testStorageCloser{
storage: storage,
directory: directory,
}
return storage.(*memorySeriesStorage), closer
}
func (t *testStorageCloser) Close() | {
t.storage.Stop()
t.directory.Close()
} |
package tlv
import (
"bytes"
"io"
)
type ByteTLV struct {
T uint64
V []byte
}
func (t ByteTLV) Type() uint64 {
return t.T
}
func (t ByteTLV) WriteTo(w io.Writer) (n int64, err error) {
n, err = WriteNumber(w, t.T)
if err != nil {
return
}
written, err := WriteNumber(w, uint64(len(t.V)))
n += written
if err != nil {
return
}
written2, err := w.Write(t.V)
n += int64(written2)
return
}
func (t ByteTLV) MarshalBinary() ([]byte, error) {
buf := &bytes.Buffer{}
_, err := t.WriteTo(buf)
return buf.Bytes(), err
}
func readByteTLV(r io.Reader) (ByteTLV, error) | {
t, _, err := ReadNumber(r)
if err != nil {
return ByteTLV{}, err
}
length, _, err := ReadNumber(r)
if err != nil {
return ByteTLV{}, err
}
value := make([]byte, length)
n, err := r.Read(value)
if err != nil {
return ByteTLV{}, err
}
if uint64(n) < length {
return ByteTLV{}, io.ErrUnexpectedEOF
}
return ByteTLV{T: t, V: value[0:n]}, nil
} |
package tagquery
import (
"io"
"github.com/grafana/metrictank/schema"
)
type expressionMatchNone struct {
expressionCommon
originalOperator ExpressionOperator
}
func (e *expressionMatchNone) Equals(other Expression) bool {
return e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()
}
func (e *expressionMatchNone) GetDefaultDecision() FilterDecision {
return Fail
}
func (e *expressionMatchNone) GetValue() string {
return e.value
}
func (e *expressionMatchNone) GetOperator() ExpressionOperator {
return MATCH_NONE
}
func (e *expressionMatchNone) GetOperatorCost() uint32 {
return 0
}
func (e *expressionMatchNone) RequiresNonEmptyValue() bool {
return true
}
func (e *expressionMatchNone) Matches(value string) bool {
return false
}
func (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {
return func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }
}
func (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {
writer.Write([]byte(e.key))
e.originalOperator.StringIntoWriter(writer)
writer.Write([]byte(e.value))
}
func (e *expressionMatchNone) GetKey() string | {
return e.key
} |
package main
import (
"log"
"net/http"
"os/exec"
"github.com/gin-gonic/gin"
)
func addRouteWithArg(name string, cmd string, router *gin.RouterGroup) {
log.Printf("Configuring route %v with command %s and argument\n", name, cmd)
path := name + "/:arg"
router.GET(path, func(c *gin.Context) {
arg := c.Params.ByName("arg")
if cmdOut, err := exec.Command(cmd, arg).Output(); err == nil {
c.JSON(http.StatusOK, gin.H{"status": "ok", "cmd": string(cmd), "argument": string(arg), "stdout": string(cmdOut)})
}
})
}
func addRouteWithoutArg(name string, cmd string, router *gin.RouterGroup) {
log.Printf("Configuring route %s with command: %s\n", name, cmd)
router.GET(name, func(c *gin.Context) {
if cmdOut, err := exec.Command(cmd).Output(); err == nil {
c.JSON(http.StatusOK, gin.H{"status": "ok", "cmd": string(cmd), "stdout": string(cmdOut)})
}
})
}
func getPing(c *gin.Context) | {
c.String(200, "pong")
} |
package controller
import (
"github.com/tmacychen/UFG/framework"
"github.com/tmacychen/UFG/framework/outer"
)
type AttachableOuter interface {
outer.Relayouter
}
type Attachable struct {
outer AttachableOuter
onAttach framework.Event
onDetach framework.Event
attached bool
}
func (a *Attachable) Init(outer AttachableOuter) {
a.outer = outer
}
func (a *Attachable) Attached() bool {
return a.attached
}
func (a *Attachable) Detach() {
if !a.attached {
panic("Control already detached")
}
a.attached = false
if a.onDetach != nil {
a.onDetach.Fire()
}
}
func (a *Attachable) OnAttach(f func()) framework.EventSubscription {
if a.onAttach == nil {
a.onAttach = CreateEvent(func() {})
}
return a.onAttach.Listen(f)
}
func (a *Attachable) OnDetach(f func()) framework.EventSubscription {
if a.onDetach == nil {
a.onDetach = CreateEvent(func() {})
}
return a.onDetach.Listen(f)
}
func (a *Attachable) Attach() | {
if a.attached {
panic("Control already attached")
}
a.attached = true
if a.onAttach != nil {
a.onAttach.Fire()
}
} |
package errors
import (
"fmt"
"github.com/GoogleContainerTools/skaffold/proto/v1"
)
type Error interface {
Error() string
StatusCode() proto.StatusCode
Suggestions() []*proto.Suggestion
Unwrap() error
}
type ErrDef struct {
err error
ae *proto.ActionableErr
}
var _ error = (*ErrDef)(nil)
func (e *ErrDef) Unwrap() error {
return e.err
}
func (e *ErrDef) StatusCode() proto.StatusCode {
return e.ae.ErrCode
}
func (e *ErrDef) Suggestions() []*proto.Suggestion {
return e.ae.Suggestions
}
func NewError(err error, ae *proto.ActionableErr) *ErrDef {
return &ErrDef{
err: err,
ae: ae,
}
}
func NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {
return &ErrDef{
ae: ae,
}
}
func IsSkaffoldErr(err error) bool {
if _, ok := err.(Error); ok {
return true
}
return false
}
func (e *ErrDef) Error() string | {
if s := concatSuggestions(e.Suggestions()); s != "" {
return fmt.Sprintf("%s. %s", e.ae.Message, concatSuggestions(e.Suggestions()))
}
return e.ae.Message
} |
package chatwork
import (
"encoding/json"
"net/url"
"strings"
)
type MessageResult struct {
MessageId int `json:"message_id"`
}
var format string = "/rooms/{roomId}/messages"
func escapeMessage(message string) string {
replacer := strings.NewReplacer("&", "&", "<", "<", ">", ">")
return replacer.Replace(message)
}
func (api *Client) PostMessage(roomId, text string) int | {
text = escapeMessage(text)
apiUrl := CHATWORK_API + strings.Replace(format, "{roomId}", roomId, 1)
values := url.Values{}
values.Add("body", text)
contents := api.Request("POST", apiUrl, values.Encode())
var result MessageResult
json.Unmarshal(contents, &result)
return result.MessageId
} |
package underscore
func Select(source, predicate interface{}) interface{} {
return filter(source, predicate, true)
}
func (this *Query) Select(predicate interface{}) Queryer {
this.source = Select(this.source, predicate)
return this
}
func (this *Query) SelectBy(properties map[string]interface{}) Queryer {
this.source = SelectBy(this.source, properties)
return this
}
func SelectBy(source interface{}, properties map[string]interface{}) interface{} | {
return Select(source, func (value, _ interface{}) bool {
return IsMatch(value, properties)
})
} |
package camelcase
import (
"bytes"
"unicode/utf8"
"github.com/blevesearch/bleve/analysis"
"github.com/blevesearch/bleve/registry"
)
const Name = "camelCase"
type CamelCaseFilter struct{}
func NewCamelCaseFilter() *CamelCaseFilter {
return &CamelCaseFilter{}
}
func CamelCaseFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {
return NewCamelCaseFilter(), nil
}
func init() {
registry.RegisterTokenFilter(Name, CamelCaseFilterConstructor)
}
func (f *CamelCaseFilter) Filter(input analysis.TokenStream) analysis.TokenStream | {
rv := make(analysis.TokenStream, 0, len(input))
nextPosition := 1
for _, token := range input {
runeCount := utf8.RuneCount(token.Term)
runes := bytes.Runes(token.Term)
p := NewParser(runeCount, nextPosition, token.Start)
for i := 0; i < runeCount; i++ {
if i+1 >= runeCount {
p.Push(runes[i], nil)
} else {
p.Push(runes[i], &runes[i+1])
}
}
rv = append(rv, p.FlushTokens()...)
nextPosition = p.NextPosition()
}
return rv
} |
package enforcer
import (
"bufio"
"encoding/binary"
)
type hashWriter struct {
*bufio.Writer
}
func (w hashWriter) WriteString(s string) {
w.WriteInt(len(s))
w.Writer.WriteString(s)
}
func (w hashWriter) WriteInt(v int) | {
var buf [8]byte
binary.LittleEndian.PutUint64(buf[:], uint64(v))
w.Write(buf[:])
} |
package iso20022
type SecuritiesCertificate5 struct {
Number *RestrictedFINXMax30Text `xml:"Nb"`
Issuer *Max4AlphaNumericText `xml:"Issr,omitempty"`
SchemeName *Max4AlphaNumericText `xml:"SchmeNm,omitempty"`
}
func (s *SecuritiesCertificate5) SetNumber(value string) {
s.Number = (*RestrictedFINXMax30Text)(&value)
}
func (s *SecuritiesCertificate5) SetIssuer(value string) {
s.Issuer = (*Max4AlphaNumericText)(&value)
}
func (s *SecuritiesCertificate5) SetSchemeName(value string) | {
s.SchemeName = (*Max4AlphaNumericText)(&value)
} |
package logrus_papertrail
import (
"fmt"
"net"
"os"
"time"
"github.com/botemout/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
)
const (
format = "Jan 2 15:04:05"
)
type PapertrailHook struct {
Host string
Port int
AppName string
UDPConn net.Conn
}
func NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) {
conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", host, port))
return &PapertrailHook{host, port, appName, conn}, err
}
func (hook *PapertrailHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}
}
func (hook *PapertrailHook) Fire(entry *logrus.Entry) error | {
date := time.Now().Format(format)
msg, _ := entry.String()
payload := fmt.Sprintf("<22> %s %s: %s", date, hook.AppName, msg)
bytesWritten, err := hook.UDPConn.Write([]byte(payload))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v", bytesWritten, err)
return err
}
return nil
} |
package trie
import "fmt"
type FullNode struct {
trie *Trie
nodes [17]Node
}
func NewFullNode(t *Trie) *FullNode {
return &FullNode{trie: t}
}
func (self *FullNode) Dirty() bool { return true }
func (self *FullNode) Value() Node {
self.nodes[16] = self.trie.trans(self.nodes[16])
return self.nodes[16]
}
func (self *FullNode) Branches() []Node {
return self.nodes[:16]
}
func (self *FullNode) Len() (amount int) {
for _, node := range self.nodes {
if node != nil {
amount++
}
}
return
}
func (self *FullNode) Hash() interface{} {
return self.trie.store(self)
}
func (self *FullNode) RlpData() interface{} {
t := make([]interface{}, 17)
for i, node := range self.nodes {
if node != nil {
t[i] = node.Hash()
} else {
t[i] = ""
}
}
return t
}
func (self *FullNode) set(k byte, value Node) {
if _, ok := value.(*ValueNode); ok && k != 16 {
fmt.Println(value, k)
}
self.nodes[int(k)] = value
}
func (self *FullNode) branch(i byte) Node {
if self.nodes[int(i)] != nil {
self.nodes[int(i)] = self.trie.trans(self.nodes[int(i)])
return self.nodes[int(i)]
}
return nil
}
func (self *FullNode) Copy(t *Trie) Node | {
nnode := NewFullNode(t)
for i, node := range self.nodes {
if node != nil {
nnode.nodes[i] = node.Copy(t)
}
}
return nnode
} |
package main
import (
"log"
"net/http"
"os"
"os/user"
)
func main() {
startServer()
}
func certsExists(certFile string, keyFile string) bool {
for _, file := range []string{certFile, keyFile} {
_, err := os.Stat(file)
if os.IsNotExist(err) {
return false
}
}
return true
}
func findPort(ssl bool) string {
port := os.Getenv("PORT")
if len(port) == 0 {
user := !isRoot()
if ssl {
if user {
port = "4443"
} else {
port = "443"
}
} else {
if user {
port = "8080"
} else {
port = "80"
}
}
}
return port
}
func startServer() {
certFile := "certs/server.pem"
keyFile := "certs/server.key"
ssl := certsExists(certFile, keyFile)
port := findPort(ssl)
router := NewRouter()
log.Printf("start listening on port %s", port)
var err error
if ssl {
err = http.ListenAndServeTLS(":"+port, certFile, keyFile, router)
} else {
err = http.ListenAndServe(":"+port, router)
}
log.Fatal(err)
}
func isRoot() bool | {
usr, _ := user.Current()
return usr.Uid == "0"
} |
package private
import "testing"
func TestGetFreePort(t *testing.T) | {
p, _ := GetFreePort()
if p <= 0 {
t.Fatal("expecting > 0 port, got:", p)
}
} |
package simple
import (
"testing"
)
func TestEqualShouldFail(t *testing.T) | {
a := 1
b := 1
shouldNotBe := false
if real := equal(a, b); real == shouldNotBe {
t.Errorf("equal(%d, %d) should not be %v, but is:%v\n", a, b, shouldNotBe, real)
}
} |
package apigateway
import (
"github.com/oracle/oci-go-sdk/v46/common"
)
type RenameQueryParameterPolicyItem struct {
From *string `mandatory:"true" json:"from"`
To *string `mandatory:"true" json:"to"`
}
func (m RenameQueryParameterPolicyItem) String() string | {
return common.PointerString(m)
} |
package cpf
import (
"errors"
"strconv"
"strings"
)
func Valid(digits string) (bool, error) {
return valid(digits)
}
func sanitize(data string) string {
data = strings.Replace(data, ".", "", -1)
data = strings.Replace(data, "-", "", -1)
return data
}
const blacklist = `00000000000
11111111111
22222222222
33333333333
44444444444
55555555555
66666666666
77777777777
88888888888
99999999999
12345678909`
func stringToIntSlice(data string) (res []int) {
for _, d := range data {
x, err := strconv.Atoi(string(d))
if err != nil {
continue
}
res = append(res, x)
}
return
}
func verify(data []int, n int) int {
var total int
for i := 0; i < n; i++ {
total += data[i] * (n + 1 - i)
}
total = total % 11
if total < 2 {
return 0
}
return 11 - total
}
func check(data string) bool {
return checkEach(data, 9) && checkEach(data, 10)
}
func checkEach(data string, n int) bool {
final := verify(stringToIntSlice(data), n)
x, err := strconv.Atoi(string(data[n]))
if err != nil {
return false
}
return final == x
}
func valid(data string) (bool, error) | {
data = sanitize(data)
if len(data) != 11 {
return false, errors.New("Invalid length")
}
if strings.Contains(blacklist, data) || !check(data) {
return false, errors.New("Invalid value")
}
return true, nil
} |
package api
import (
"github.com/gin-gonic/gin"
"github.com/mundipagg/boleto-api/models"
)
func validateRegisterV1(c *gin.Context) {
rules := getBoletoFromContext(c).Title.Rules
bn := getBankFromContext(c).GetBankNumber()
if rules != nil {
c.AbortWithStatusJSON(400, models.NewSingleErrorCollection("MP400", "title.rules not available in this version"))
return
}
if bn == models.Stone {
c.AbortWithStatusJSON(400, models.NewSingleErrorCollection("MP400", "bank Stone not available in this version"))
return
}
}
func validateRegisterV2(c *gin.Context) | {
r := getBoletoFromContext(c).Title.Rules
bn := getBankFromContext(c).GetBankNumber()
if r != nil && bn != models.Caixa {
c.AbortWithStatusJSON(400, models.NewSingleErrorCollection("MP400", "title.rules not available for this bank"))
return
}
} |
package commands
import (
log "github.com/sirupsen/logrus"
"github.com/jamesread/ovress/pkg/indexer"
"github.com/spf13/cobra"
)
func newIndexCmd() *cobra.Command {
var indexCmd = &cobra.Command{
Use: "index",
Short: "Indexes a file path",
Run: runIndexCmd,
Args: cobra.MinimumNArgs(1),
}
return indexCmd
}
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())
} |
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) ValidHooks() uint32 {
hooks := uint32(0)
for hook, _ := range table.BuiltinChains {
hooks |= 1 << hook
}
return hooks
}
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) Metadata() interface{} | {
return table.metadata
} |
package memory
import (
"github.com/golang/glog"
"github.com/google/trillian/monitoring"
"github.com/google/trillian/storage"
)
func init() {
if err := storage.RegisterProvider("memory", newMemoryStorageProvider); err != nil {
glog.Fatalf("Failed to register storage provider memory: %v", err)
}
}
type memProvider struct {
mf monitoring.MetricFactory
ts *TreeStorage
}
func (s *memProvider) LogStorage() storage.LogStorage {
return NewLogStorage(s.ts, s.mf)
}
func (s *memProvider) MapStorage() storage.MapStorage {
return nil
}
func (s *memProvider) AdminStorage() storage.AdminStorage {
return NewAdminStorage(s.ts)
}
func (s *memProvider) Close() error {
return nil
}
func newMemoryStorageProvider(mf monitoring.MetricFactory) (storage.Provider, error) | {
return &memProvider{
mf: mf,
ts: NewTreeStorage(),
}, nil
} |
package core
import (
"fmt"
)
func PodContainerKey(namespace, podName, containerName string) string {
return fmt.Sprintf("namespace:%s/pod:%s/container:%s", namespace, podName, containerName)
}
func PodKey(namespace, podName string) string {
return fmt.Sprintf("namespace:%s/pod:%s", namespace, podName)
}
func NodeKey(node string) string {
return fmt.Sprintf("node:%s", node)
}
func NodeContainerKey(node, container string) string {
return fmt.Sprintf("node:%s/container:%s", node, container)
}
func ClusterKey() string {
return "cluster"
}
func NamespaceKey(namespace string) string | {
return fmt.Sprintf("namespace:%s", namespace)
} |
package fake
import (
"encoding/json"
"fmt"
"net/http"
"strings"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
type CFAPI struct {
server *ghttp.Server
}
type CFAPIConfig struct {
Routes map[string]Response
}
type Response struct {
Code int
Body interface{}
}
func NewCFAPI() *CFAPI {
server := ghttp.NewServer()
return &CFAPI{
server: server,
}
}
func (a *CFAPI) SetConfiguration(config CFAPIConfig) {
a.server.Reset()
for request, response := range config.Routes {
method, path := parseRequest(request)
responseBytes, err := json.Marshal(response.Body)
Expect(err).NotTo(HaveOccurred())
a.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))
}
}
func (a *CFAPI) Close() {
a.server.Close()
}
func (a *CFAPI) URL() string {
return a.server.URL()
}
func parseRequest(request string) (string, string) {
fields := strings.Split(request, " ")
Expect(fields).To(HaveLen(2))
return fields[0], fields[1]
}
func (a *CFAPI) ReceivedRequests() map[string][]*http.Request | {
result := map[string][]*http.Request{}
for _, req := range a.server.ReceivedRequests() {
key := fmt.Sprintf("%s %s", req.Method, req.URL.Path)
result[key] = append(result[key], req)
}
return result
} |
package next_permutation
func nextPermutation(nums []int) {
n := len(nums)
if n < 2 {
return
}
index := n - 1
for ; index > 0; index-- {
if nums[index-1] < nums[index] {
break
}
}
if index == 0 {
reverseSort(nums, 0, n-1)
return
}
val := nums[index-1]
j := n - 1
for ; j >= index && nums[j] <= val; j-- {
}
nums[j], nums[index-1] = val, nums[j]
reverseSort(nums, index, n-1)
}
func reverseSort(nums []int, start, end int) | {
if start > end {
return
}
for i := start; i <= (end+start)/2; i++ {
nums[i], nums[start+end-i] = nums[start+end-i], nums[i]
}
} |
package v1
import (
v1 "k8s.io/api/networking/v1"
"k8s.io/client-go/deprecated/scheme"
rest "k8s.io/client-go/rest"
)
type NetworkingV1Interface interface {
RESTClient() rest.Interface
NetworkPoliciesGetter
}
type NetworkingV1Client struct {
restClient rest.Interface
}
func (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {
return newNetworkPolicies(c, namespace)
}
func NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
func New(c rest.Interface) *NetworkingV1Client {
return &NetworkingV1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
func (c *NetworkingV1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
func NewForConfig(c *rest.Config) (*NetworkingV1Client, error) | {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &NetworkingV1Client{client}, nil
} |
package runtime
import (
"strings"
"github.com/Shopify/go-lua"
"github.com/fsouza/go-dockerclient"
"github.com/involucro/involucro/auth"
"github.com/involucro/involucro/ilog"
)
type pushStepBuilderState struct {
pushStep
upper fm
registerStep func(Step)
}
type pushStep struct {
docker.PushImageOptions
}
func newPushSubBuilder(upper fm, register func(Step)) lua.Function {
psbs := pushStepBuilderState{
upper: upper,
registerStep: register,
}
return psbs.push
}
func (psbs pushStepBuilderState) push(l *lua.State) int {
opts := &psbs.PushImageOptions
opts.Name = lua.CheckString(l, 1)
if l.Top() >= 2 {
opts.Tag = lua.CheckString(l, 2)
} else {
opts.Name, _, opts.Tag = repoNameAndTagFrom(opts.Name)
}
psbs.registerStep(psbs.pushStep)
return tableWith(l, psbs.upper)
}
func (s pushStep) Take(i *Runtime) error {
ac, foundAuthentication, err := auth.ForServer(serverOfRepo(s.PushImageOptions.Name))
if err != nil {
return err
}
if err := i.client.PushImage(s.PushImageOptions, ac); err != nil {
if !foundAuthentication {
ilog.Warn.Logf("Pull may have failed due to missing authentication information in ~/.involucro")
}
return err
}
return nil
}
func (s pushStep) ShowStartInfo() {
logTask.Logf("Push image [%s:%s]", s.Name, s.Tag)
}
func serverOfRepo(name string) string | {
parts := strings.Split(name, "/")
if len(parts) < 3 {
return ""
}
return strings.Join(parts[:len(parts)-2], "/")
} |
package main
import (
"flag"
"log"
"net/http"
"github.com/jackmanlabs/rpc/v2"
"github.com/jackmanlabs/rpc/v2/json2"
)
type Counter struct {
Count int
}
type IncrReq struct {
Delta int
}
func (c *Counter) Incr(r *http.Request, req *IncrReq, res *json2.EmptyResponse) error {
log.Printf("<- Incr %+v", *req)
c.Count += req.Delta
return nil
}
type GetReq struct {
}
func main() {
address := flag.String("address", ":65534", "")
s := rpc.NewServer()
s.RegisterCodec(json2.NewCustomCodec(&rpc.CompressionSelector{}), "application/json")
s.RegisterService(new(Counter), "")
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./"))))
http.Handle("/jsonrpc/", s)
log.Fatal(http.ListenAndServe(*address, nil))
}
func (c *Counter) Get(r *http.Request, req *GetReq, res *Counter) error | {
log.Printf("<- Get %+v", *req)
*res = *c
log.Printf("-> %v", *res)
return nil
} |
package main
import (
"context"
"fmt"
"github.com/codegangsta/cli"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
)
func imagesCmd(ctx *cli.Context) {
client := getDockerClient()
if ctx.GlobalBool("force") {
cd := getCacheFile()
cd.reset()
}
if imgs, err := client.ImageList(context.Background(), types.ImageListOptions{}); err != nil {
logAndFatalf("Cannot proceed safely: %v.", err)
} else {
printImages(imgs)
exitWithCode(0)
}
}
func checkImageExists(repo, tag string) (bool, error) {
client := getDockerClient()
images, err := client.ImageList(context.Background(), types.ImageListOptions{
All: false,
Filters: filters.NewArgs(filters.Arg("reference", repo)),
})
if err != nil {
return false, err
}
if len(images) == 0 {
return false, nil
}
ref := fmt.Sprintf("%s:%s", repo, tag)
for _, image := range images {
for _, t := range image.RepoTags {
if ref == t {
return true, nil
}
}
}
return false, nil
}
func printImages(images []types.ImageSummary) | {
suseImages := make([]types.ImageSummary, 0, len(images))
cache := getCacheFile()
counter := 0
for _, img := range images {
select {
case <-killChannel:
return
default:
fmt.Printf("Inspecting image %d/%d\r", (counter + 1), len(images))
if cache.isSUSE(img.ID) {
suseImages = append(suseImages, img)
}
}
counter++
}
formatAndPrint(suseImages)
cache.flush()
} |
package sample
import (
"fmt"
"math/rand"
)
type sampleState struct {
rate uint64
seed int64
sampleCount uint64
trueCount uint64
rnd *rand.Rand
}
type Sampler interface {
Sample() bool
SampleFrom(probe uint64) bool
State
}
type State interface {
Reset()
String() string
Rate() uint64
Calls() uint64
Count() uint64
}
func (state *sampleState) Calls() uint64 {
if state != nil {
return state.sampleCount
}
return 0
}
func (state *sampleState) Count() uint64 {
if state != nil {
return state.trueCount
}
return 0
}
func (state *sampleState) Reset() {
state.rnd.Seed(state.seed)
state.sampleCount = 0
state.trueCount = 0
}
func (state *sampleState) String() string {
type X *sampleState
x := X(state)
return fmt.Sprintf("%+v", x)
}
func Deviation(state State) (deviation float64) {
if state != nil && state.Count() > 0 {
deviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))
} else {
deviation = 1.0
}
return
}
func Stats(state State) string {
if state != nil {
return fmt.Sprintf("Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)
}
return "No state provided"
}
func (state *sampleState) Rate() uint64 | {
if state != nil {
return state.rate
}
return 0
} |
package gce
import (
"context"
"github.com/supergiant/control/pkg/clouds/gcesdk"
"io"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/supergiant/control/pkg/workflows/steps"
"google.golang.org/api/compute/v1"
)
const DeleteTargetPoolStepName = "gce_delete_target_pool"
type DeleteTargetPoolStep struct {
getComputeSvc func(context.Context, steps.GCEConfig) (*computeService, error)
}
func (s *DeleteTargetPoolStep) Run(ctx context.Context, output io.Writer,
config *steps.Config) error {
logrus.Debugf("Step %s", DeleteTargetPoolStepName)
svc, err := s.getComputeSvc(ctx, config.GCEConfig)
if err != nil {
logrus.Errorf("Error getting service %v", err)
return errors.Wrapf(err, "%s getting service caused", DeleteTargetPoolStepName)
}
_, err = svc.deleteTargetPool(ctx, config.GCEConfig, config.GCEConfig.TargetPoolName)
if err != nil {
logrus.Errorf("Error deleting target pool %v", err)
}
return nil
}
func (s *DeleteTargetPoolStep) Name() string {
return DeleteTargetPoolStepName
}
func (s *DeleteTargetPoolStep) Depends() []string {
return nil
}
func (s *DeleteTargetPoolStep) Description() string {
return "Delete target pool master nodes"
}
func (s *DeleteTargetPoolStep) Rollback(context.Context, io.Writer, *steps.Config) error {
return nil
}
func NewDeleteTargetPoolStep() *DeleteTargetPoolStep | {
return &DeleteTargetPoolStep{
getComputeSvc: func(ctx context.Context, config steps.GCEConfig) (*computeService, error) {
client, err := gcesdk.GetClient(ctx, config)
if err != nil {
return nil, err
}
return &computeService{
deleteTargetPool: func(ctx context.Context, config steps.GCEConfig, targetPoolName string) (*compute.Operation, error) {
return client.TargetPools.Delete(config.ServiceAccount.ProjectID, config.Region, targetPoolName).Do()
},
}, nil
},
}
} |
package local
import (
"context"
"os"
"path/filepath"
"github.com/grafana/loki/pkg/storage/chunk"
)
type TableClient struct {
directory string
}
func NewTableClient(directory string) (chunk.TableClient, error) {
return &TableClient{directory: directory}, nil
}
func (c *TableClient) ListTables(ctx context.Context) ([]string, error) {
boltDbFiles := []string{}
err := filepath.Walk(c.directory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
boltDbFiles = append(boltDbFiles, info.Name())
}
return nil
})
if err != nil {
return nil, err
}
return boltDbFiles, nil
}
func (c *TableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error {
file, err := os.OpenFile(filepath.Join(c.directory, desc.Name), os.O_CREATE|os.O_RDONLY, 0666)
if err != nil {
return err
}
return file.Close()
}
func (c *TableClient) DeleteTable(ctx context.Context, name string) error {
return os.Remove(filepath.Join(c.directory, name))
}
func (c *TableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) {
return chunk.TableDesc{
Name: name,
}, true, nil
}
func (*TableClient) Stop() {}
func (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error | {
return nil
} |
package main
func Build(srcPath, targetPath string) (files Files, err error) | {
files, err = ReadFiles(srcPath)
if err != nil {
logger.Error("Read", "err", err)
return
}
err = TransformFiles(files)
if err != nil {
logger.Error("Transform", "err", err)
return
}
err = WriteFiles(files, targetPath)
if err != nil {
logger.Error("Write", "err", err)
return
}
return
} |
package ftp
import "io"
type debugWrapper struct {
conn io.ReadWriteCloser
io.Reader
io.Writer
}
func newDebugWrapper(conn io.ReadWriteCloser, w io.Writer) io.ReadWriteCloser {
return &debugWrapper{
Reader: io.TeeReader(conn, w),
Writer: io.MultiWriter(w, conn),
conn: conn,
}
}
func (w *debugWrapper) Close() error {
return w.conn.Close()
}
type streamDebugWrapper struct {
io.Reader
closer io.ReadCloser
}
func newStreamDebugWrapper(rd io.ReadCloser, w io.Writer) io.ReadCloser {
return &streamDebugWrapper{
Reader: io.TeeReader(rd, w),
closer: rd,
}
}
func (w *streamDebugWrapper) Close() error | {
return w.closer.Close()
} |
package database
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
type TerminateDbSystemRequest struct {
DbSystemId *string `mandatory:"true" contributesTo:"path" name:"dbSystemId"`
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
RequestMetadata common.RequestMetadata
}
func (request TerminateDbSystemRequest) String() string {
return common.PointerString(request)
}
func (request TerminateDbSystemRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
type TerminateDbSystemResponse struct {
RawResponse *http.Response
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response TerminateDbSystemResponse) String() string {
return common.PointerString(response)
}
func (response TerminateDbSystemResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
func (request TerminateDbSystemRequest) RetryPolicy() *common.RetryPolicy | {
return request.RequestMetadata.RetryPolicy
} |
package graph
import (
"fmt"
"github.com/gonum/graph"
"github.com/gonum/graph/concrete"
"github.com/gonum/graph/encoding/dot"
)
type Node struct {
Id int
UniqueName string
LabelName string
Color string
}
func (n Node) ID() int {
return n.Id
}
func (n Node) DOTAttributes() []dot.Attribute {
color := n.Color
if len(color) == 0 {
color = "black"
}
return []dot.Attribute{
{Key: "label", Value: fmt.Sprintf("%q", n.LabelName)},
{Key: "color", Value: color},
}
}
func NewMutableDirectedGraph(g *concrete.DirectedGraph) *MutableDirectedGraph {
return &MutableDirectedGraph{
DirectedGraph: concrete.NewDirectedGraph(),
nodesByName: make(map[string]graph.Node),
}
}
type MutableDirectedGraph struct {
*concrete.DirectedGraph
nodesByName map[string]graph.Node
}
func (g *MutableDirectedGraph) NodeByName(name string) (graph.Node, bool) {
n, exists := g.nodesByName[name]
return n, exists && g.DirectedGraph.Has(n)
}
func (g *MutableDirectedGraph) AddNode(n *Node) error | {
if _, exists := g.nodesByName[n.UniqueName]; exists {
return fmt.Errorf("node .UniqueName collision: %s", n.UniqueName)
}
g.nodesByName[n.UniqueName] = n
g.DirectedGraph.AddNode(n)
return nil
} |
package tcp
import (
"net"
"strconv"
"github.com/reinit/coward/roles/common/network"
)
type listener struct {
host net.IP
port uint16
connectionWrapper network.ConnectionWrapper
}
type acceptor struct {
listener *net.TCPListener
connectionWrapper network.ConnectionWrapper
closed chan struct{}
}
func New(
host net.IP,
port uint16,
connectionWrapper network.ConnectionWrapper,
) network.Listener {
return listener{
host: host,
port: port,
connectionWrapper: connectionWrapper,
}
}
func (t listener) Listen() (network.Acceptor, error) {
listener, listenErr := net.ListenTCP("tcp", &net.TCPAddr{
IP: t.host,
Port: int(t.port),
Zone: "",
})
if listenErr != nil {
return nil, listenErr
}
return acceptor{
listener: listener,
connectionWrapper: t.connectionWrapper,
closed: make(chan struct{}),
}, nil
}
func (t listener) String() string {
return net.JoinHostPort(
t.host.String(), strconv.FormatUint(uint64(t.port), 10))
}
func (a acceptor) Addr() net.Addr {
return a.listener.Addr()
}
func (a acceptor) Closed() chan struct{} {
return a.closed
}
func (a acceptor) Close() error {
close(a.closed)
return a.listener.Close()
}
func (a acceptor) Accept() (network.Connection, error) | {
accepted, acceptErr := a.listener.AcceptTCP()
if acceptErr != nil {
return nil, acceptErr
}
optErr := accepted.SetLinger(0)
if optErr != nil {
return nil, optErr
}
optErr = accepted.SetNoDelay(false)
if optErr != nil {
return nil, optErr
}
return a.connectionWrapper(accepted), nil
} |
package clipboard
import (
ps "github.com/mitchellh/go-ps"
)
func killPrecedessors() error | {
procs, err := ps.Processes()
if err != nil {
return err
}
for _, proc := range procs {
walkFn(proc.Pid(), killProc)
}
return nil
} |
package collector
import (
"fmt"
"strconv"
"github.com/go-kit/kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs"
)
type softnetCollector struct {
fs procfs.FS
processed *prometheus.Desc
dropped *prometheus.Desc
timeSqueezed *prometheus.Desc
logger log.Logger
}
const (
softnetSubsystem = "softnet"
)
func init() {
registerCollector("softnet", defaultEnabled, NewSoftnetCollector)
}
func NewSoftnetCollector(logger log.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath)
if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err)
}
return &softnetCollector{
fs: fs,
processed: prometheus.NewDesc(
prometheus.BuildFQName(namespace, softnetSubsystem, "processed_total"),
"Number of processed packets",
[]string{"cpu"}, nil,
),
dropped: prometheus.NewDesc(
prometheus.BuildFQName(namespace, softnetSubsystem, "dropped_total"),
"Number of dropped packets",
[]string{"cpu"}, nil,
),
timeSqueezed: prometheus.NewDesc(
prometheus.BuildFQName(namespace, softnetSubsystem, "times_squeezed_total"),
"Number of times processing packets ran out of quota",
[]string{"cpu"}, nil,
),
logger: logger,
}, nil
}
func (c *softnetCollector) Update(ch chan<- prometheus.Metric) error | {
stats, err := c.fs.NetSoftnetStat()
if err != nil {
return fmt.Errorf("could not get softnet statistics: %s", err)
}
for cpuNumber, cpuStats := range stats {
cpu := strconv.Itoa(cpuNumber)
ch <- prometheus.MustNewConstMetric(
c.processed,
prometheus.CounterValue,
float64(cpuStats.Processed),
cpu,
)
ch <- prometheus.MustNewConstMetric(
c.dropped,
prometheus.CounterValue,
float64(cpuStats.Dropped),
cpu,
)
ch <- prometheus.MustNewConstMetric(
c.timeSqueezed,
prometheus.CounterValue,
float64(cpuStats.TimeSqueezed),
cpu,
)
}
return nil
} |
package aes
import (
"crypto/aes"
"crypto/cipher"
"github.com/golang/glog"
)
type aesInfo struct {
keyLen int
ivLen int
}
var info = map[string]aesInfo{
"aes-128-cfb": aesInfo{keyLen: 16, ivLen: 16},
"aes-192-cfb": aesInfo{keyLen: 24, ivLen: 16},
"aes-256-cfb": aesInfo{keyLen: 32, ivLen: 16},
}
type AES struct {
Name string
}
func NewAES(aesType string) (*AES, error) {
alg := &AES{
Name: aesType,
}
return alg, nil
}
func (a *AES) NewStream(key, iv []byte, encrypt bool) (cipher.Stream, error) {
glog.V(5).Infoln("New Aes Stream")
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if encrypt {
return cipher.NewCFBEncrypter(block, iv), nil
}
return cipher.NewCFBDecrypter(block, iv), nil
}
func (a *AES) GetKeyLen() int {
v, ok := info[a.Name]
if !ok {
return 0
}
return v.keyLen
}
func (a *AES) GetIVLen() int | {
v, ok := info[a.Name]
if !ok {
return 0
}
return v.ivLen
} |
package utils
import (
"github.com/labstack/gommon/log"
"io/ioutil"
"os"
"path/filepath"
)
func UpdateFile(file, val string) error {
dir := filepath.Dir(file)
log.Info("creating dir %s", dir)
dir, err := CreateDirIfReqd(dir)
if err != nil {
return err
}
ioutil.WriteFile(filepath.Join(dir, filepath.Base(file)), []byte(val), 0777)
return nil
}
func CreateDirIfReqd(dir string) (string, error) | {
dirAbsPath, err := filepath.Abs(dir)
if err != nil {
return dirAbsPath, err
}
if _, err := os.Stat(dirAbsPath); err == nil {
return dirAbsPath, nil
}
err = os.MkdirAll(dirAbsPath, 0777)
return dirAbsPath, err
} |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(Reverse(-27))
fmt.Println(Reverse(314))
}
func Reverse(d int) (r int) | {
factors := make([]int, 0, 0)
isNeg := false
if d < 0 {
isNeg = true
d *= -1
}
for {
if d == 0 {
break
} else {
factors = append(factors, d%10)
d = d / 10
}
}
for i, v := range factors {
r += v * int(math.Pow10(len(factors)-1-i))
}
if isNeg {
r *= -1
}
return r
} |
package test_helpers
import (
"encoding/json"
"errors"
datatypes "github.com/maximilien/softlayer-go/data_types"
)
type MockProductPackageService struct{}
func (mock *MockProductPackageService) GetName() string {
return "Mock_Product_Package_Service"
}
func (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {
response, _ := ReadJsonTestFixtures("services", "SoftLayer_Product_Package_getItemsByType_virtual_server.json")
productItems := []datatypes.SoftLayer_Product_Item{}
json.Unmarshal(response, &productItems)
return productItems, nil
}
func (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {
return []datatypes.SoftLayer_Product_Item_Price{}, errors.New("Not supported")
}
func (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {
return []datatypes.SoftLayer_Product_Item{}, errors.New("Not supported")
}
func (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {
return []datatypes.Softlayer_Product_Package{}, errors.New("Not supported")
}
func (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {
return datatypes.Softlayer_Product_Package{}, errors.New("Not supported")
}
func (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) | {
return []datatypes.SoftLayer_Product_Item_Price{}, errors.New("Not supported")
} |
package train
import (
"io"
"log"
"net/http"
"path"
"strings"
)
var assetServer *http.Handler
var publicAssetServer *http.Handler
func servePublicAssets(w http.ResponseWriter, r *http.Request) {
(*publicAssetServer).ServeHTTP(w, r)
}
var contentTypes = map[string]string{
".js": "application/javascript",
".css": "text/css",
}
func serveAssets(w http.ResponseWriter, r *http.Request) {
url := r.URL.Path
ext := path.Ext(url)
switch ext {
case ".js", ".css":
content, err := ReadAsset(url)
if err != nil {
if strings.Contains(err.Error(), "Could not compile") {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusNotFound)
}
io.Copy(w, strings.NewReader(err.Error()))
log.Printf("Failed to deliver asset\nGET %s\n-----------------------\n%s\n", url, err.Error())
} else {
w.Header().Set("Content-Type", contentTypes[ext])
io.Copy(w, strings.NewReader(content))
}
default:
(*assetServer).ServeHTTP(w, r)
}
}
func setupFileServer() | {
if assetServer == nil {
server := http.FileServer(http.Dir(Config.AssetsPath + "/.."))
assetServer = &server
}
if publicAssetServer == nil {
server := http.FileServer(http.Dir("public"))
publicAssetServer = &server
}
} |
package p10
import (
"fmt"
c "s13g.com/euler/common"
)
func Solve(input string) (string, string) {
return c.ToString(solveA(c.ParseIntArray(c.SplitByCommaTrim(input)))), solveB(input)
}
func solveA(lengths []int) int {
numbers := ProcessLengths(lengths, 1)
return numbers[0] * numbers[1]
}
func solveB(input string) string {
lengths := make([]int, len(input))
for i, c := range input {
lengths[i] = int(c)
}
lengths = append(lengths, 17, 31, 73, 47, 23)
numbers := ProcessLengths(lengths, 64)
denseHash := make([]int, 16)
for block := 0; block < 16; block++ {
for start, i := block*16, 0; i < 16; i++ {
denseHash[block] ^= numbers[start+i]
}
}
return c.MapIStr(denseHash, func(b int) string { return fmt.Sprintf("%02x", b) })
}
func KnotHash(input string) string {
return solveB(input)
}
func ProcessLengths(lengths []int, numRounds int) []int | {
reverseCircular := func(list []int, start int, length int) {
for l, r := start, start+length-1; l < r; l, r = l+1, r-1 {
ll, rr := l%len(list), r%len(list)
list[ll], list[rr] = list[rr], list[ll]
}
}
numbers := make([]int, 256)
for i := range numbers {
numbers[i] = i
}
currPos, skipSize := 0, 0
for round := 0; round < numRounds; round++ {
for _, length := range lengths {
reverseCircular(numbers, currPos, length)
currPos += length + skipSize
skipSize++
}
}
return numbers
} |
package operations
import (
"github.com/asuleymanov/golos-go/encoding/transaction"
)
type BreakFreeReferralOperation struct {
Referral string `json:"referral"`
Extensions []interface{} `json:"extensions"`
}
func (op *BreakFreeReferralOperation) Type() OpType {
return TypeBreakFreeReferral
}
func (op *BreakFreeReferralOperation) Data() interface{} {
return op
}
func (op *BreakFreeReferralOperation) MarshalTransaction(encoder *transaction.Encoder) error | {
enc := transaction.NewRollingEncoder(encoder)
enc.EncodeUVarint(uint64(TypeBreakFreeReferral.Code()))
enc.Encode(op.Referral)
enc.Encode(byte(0))
return enc.Err()
} |
package misc
import (
"net/http"
"strconv"
"time"
)
type Writer interface {
http.ResponseWriter
http.Hijacker
}
func ElapsedTime(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
nw := elapsedTimeResponseWriter{
Writer: w.(Writer),
Timestamp: time.Now().UnixNano(),
written: false,
}
next(&nw, r)
}
type elapsedTimeResponseWriter struct {
Writer
Timestamp int64
written bool
}
func (e *elapsedTimeResponseWriter) WriteHeader(status int) {
if e.written == false {
e.written = true
e.Writer.Header().Set("Elapsed-Time", strconv.FormatInt(time.Now().UnixNano()-e.Timestamp, 10)+" ns")
}
e.Writer.WriteHeader(status)
}
func (e *elapsedTimeResponseWriter) Write(data []byte) (int, error) | {
if e.written == false {
e.WriteHeader(http.StatusOK)
}
return e.Writer.Write(data)
} |
package events
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/klog"
)
type LoggingEventRecorder struct {
component string
}
func NewLoggingEventRecorder(component string) Recorder {
return &LoggingEventRecorder{component: component}
}
func (r *LoggingEventRecorder) ComponentName() string {
return r.component
}
func (r *LoggingEventRecorder) ForComponent(component string) Recorder {
newRecorder := *r
newRecorder.component = component
return &newRecorder
}
func (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {
return r.ForComponent(fmt.Sprintf("%s-%s", r.ComponentName(), suffix))
}
func (r *LoggingEventRecorder) Event(reason, message string) {
event := makeEvent(&inMemoryDummyObjectReference, "", corev1.EventTypeNormal, reason, message)
klog.Info(event.String())
}
func (r *LoggingEventRecorder) Warning(reason, message string) {
event := makeEvent(&inMemoryDummyObjectReference, "", corev1.EventTypeWarning, reason, message)
klog.Warning(event.String())
}
func (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {
r.Warning(reason, fmt.Sprintf(messageFmt, args...))
}
func (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) | {
r.Event(reason, fmt.Sprintf(messageFmt, args...))
} |
package custom_commands
import (
"github.com/jmoiron/sqlx"
"github.com/sgt-kabukiman/kabukibot/bot"
)
type pluginStruct struct {
db *sqlx.DB
}
func NewPlugin() *pluginStruct {
return &pluginStruct{}
}
func (self *pluginStruct) Name() string {
return "custom_commands"
}
func (self *pluginStruct) Setup(bot *bot.Kabukibot) {
self.db = bot.Database()
}
func (self *pluginStruct) CreateWorker(channel bot.Channel) bot.PluginWorker | {
return &worker{
channel: channel,
acl: channel.ACL(),
db: self.db,
}
} |
package thread
import "time"
type ThreadStatistic struct {
ThreadId int `json:"thread_id"`
ProcessedLines int `json:"processed_lines"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
DeltaTime time.Duration `json:"delta_time"`
}
func NewThreadStadistic(threadId int) *ThreadStatistic {
var ts ThreadStatistic
ts.ThreadId = threadId
ts.ProcessedLines = 0
ts.StartTime = time.Now()
return &ts
}
func (ts *ThreadStatistic) SetEndTime() {
ts.EndTime = time.Now()
ts.DeltaTime = ts.EndTime.Sub(ts.StartTime) / time.Millisecond
}
func (ts *ThreadStatistic) IncreaseProcessedLines() | {
ts.ProcessedLines += 1
} |
package osc
import (
"net"
"testing"
)
func TestValidateAddress(t *testing.T) {
if err := ValidateAddress("/foo"); err != nil {
t.Fatal(err)
}
if err := ValidateAddress("/foo@^#&*$^*%)()#($*@"); err == nil {
t.Fatal("expected error, got nil")
}
}
func TestUDPConn(t *testing.T) | {
laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
lc, err := ListenUDP("udp", laddr)
if err != nil {
t.Fatal(err)
}
var c Conn = lc
_ = c
} |
package main
import (
"log"
"net/http"
)
func main() {
http.HandleFunc("/", droneServer)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func droneServer(w http.ResponseWriter, req *http.Request) | {
w.Write([]byte("Built by Drone in Kubernetes!"))
} |
package vflag
import "strings"
import "net/url"
type URL struct {
Raw string
Solt *url.URL
Schemes *[]string
RequirePort bool
}
func (val URL) String() string {
return val.Raw
}
func (val URL) Set(urlArg string) error | {
var err error = nil
var u *url.URL = nil
var isValid bool = false
if u, err = url.Parse(urlArg); err != nil {
return err
}
if strings.Index(u.Host, ":") == -1 && val.RequirePort {
return ErrUrlNoPort
}
if val.Schemes != nil {
for _, s := range *val.Schemes {
if s == u.Scheme {
isValid = true
break
}
}
if !isValid {
return ErrInvalidUrlScheme
}
}
*val.Solt = *u
return nil
} |
package main
import "fmt"
func main() {
c := incrementor()
cSum := puller(c)
for n := range cSum {
fmt.Println(n)
}
}
func puller(c chan int) chan int {
out := make(chan int)
go func() {
var sum int
for n := range c {
sum += n
}
out <- sum
close(out)
}()
return out
}
func incrementor() chan int | {
out := make(chan int)
go func() {
for i := 0; i < 10; i++ {
out <- i
}
close(out)
}()
return out
} |
package keys
import "context"
type keySetType int
const keySet = keySetType(0)
func WithValue(ctx context.Context, key interface{}, value interface{}) context.Context {
old, _ := ctx.Value(keySet).(*Link)
ctx = context.WithValue(ctx, key, value)
return context.WithValue(ctx, keySet, &Link{Value: key, Next: old})
}
func Clone(ctx context.Context, from context.Context) context.Context {
for _, key := range Get(from) {
ctx = WithValue(ctx, key, from.Value(key))
}
return ctx
}
func Get(ctx context.Context) []interface{} | {
seen := map[interface{}]bool{}
result := make([]interface{}, 0, 10)
for link, _ := ctx.Value(keySet).(*Link); link != nil; link = link.Next {
if !seen[link.Value] {
seen[link.Value] = true
result = append(result, link.Value)
}
}
return result
} |
package memdb
type Changes []Change
type Change struct {
Table string
Before interface{}
After interface{}
primaryKey []byte
}
func (m *Change) Updated() bool {
return m.Before != nil && m.After != nil
}
func (m *Change) Deleted() bool {
return m.Before != nil && m.After == nil
}
func (m *Change) Created() bool | {
return m.Before == nil && m.After != nil
} |
package collector
import (
"errors"
"strconv"
"unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
)
import "C"
const maxCPUTimesLen = C.MAXCPU * C.CPUSTATES
type statCollector struct {
cpu *prometheus.Desc
logger log.Logger
}
func init() {
registerCollector("cpu", defaultEnabled, NewStatCollector)
}
func NewStatCollector(logger log.Logger) (Collector, error) {
return &statCollector{
cpu: nodeCPUSecondsDesc,
logger: logger,
}, nil
}
func getDragonFlyCPUTimes() ([]float64, error) {
var (
cpuTimesC *C.uint64_t
cpuTimesLength C.size_t
)
if C.getCPUTimes(&cpuTimesC, &cpuTimesLength) == -1 {
return nil, errors.New("could not retrieve CPU times")
}
defer C.free(unsafe.Pointer(cpuTimesC))
cput := (*[maxCPUTimesLen]C.uint64_t)(unsafe.Pointer(cpuTimesC))[:cpuTimesLength:cpuTimesLength]
cpuTimes := make([]float64, cpuTimesLength)
for i, value := range cput {
cpuTimes[i] = float64(value) / float64(1000000)
}
return cpuTimes, nil
}
func (c *statCollector) Update(ch chan<- prometheus.Metric) error | {
var fieldsCount = 5
cpuTimes, err := getDragonFlyCPUTimes()
if err != nil {
return err
}
cpuFields := []string{"user", "nice", "sys", "interrupt", "idle"}
for i, value := range cpuTimes {
cpux := strconv.Itoa(i / fieldsCount)
ch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, value, cpux, cpuFields[i%fieldsCount])
}
return nil
} |
package models
import (
"database/sql"
"github.com/BrandonRomano/serf"
db "github.com/carrot/burrow/db/postgres"
"time"
)
type Topic struct {
serf.Worker `json:"-"`
Id int64 `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func NewTopic() *Topic {
topic := new(Topic)
return topic.Prep()
}
func (t *Topic) Prep() *Topic {
t.Worker = &serf.PqWorker{
Database: db.Get(),
Config: serf.Configuration{
TableName: "topics",
Fields: []serf.Field{
serf.Field{Pointer: &t.Id, Name: "id", UniqueIdentifier: true,
IsSet: func(pointer interface{}) bool {
pointerInt := *pointer.(*int64)
return pointerInt != 0
},
},
serf.Field{Pointer: &t.Name, Name: "name", Insertable: true, Updatable: true},
serf.Field{Pointer: &t.CreatedAt, Name: "created_at"},
serf.Field{Pointer: &t.UpdatedAt, Name: "updated_at"},
},
},
}
return t
}
func (t *Topic) consumeNextRow(rows *sql.Rows) error {
return rows.Scan(
&t.Id,
&t.Name,
&t.CreatedAt,
&t.UpdatedAt,
)
}
func AllTopics(limit int64, offset int64) ([]Topic, error) | {
database := db.Get()
rows, err := database.Query("SELECT * FROM topics ORDER BY created_at LIMIT $1 OFFSET $2", limit, offset)
if err != nil {
return nil, err
}
defer rows.Close()
var topics []Topic = []Topic{}
for rows.Next() {
t := new(Topic)
err = t.consumeNextRow(rows)
if err != nil {
return nil, err
}
topics = append(topics, *t)
}
err = rows.Err()
if err != nil {
return nil, err
}
return topics, nil
} |
package chapter3_cf
type SourceFileAttribute struct {
cp ConstantPool
sourceFileIndex uint16
}
func (self *SourceFileAttribute) FileName() string {
return self.cp.getUtf8(self.sourceFileIndex)
}
func (self *SourceFileAttribute) readInfo(reader *ClassReader) | {
self.sourceFileIndex = reader.readUint16()
} |
package server
import (
"encoding/json"
"fmt"
"net/http"
"github.com/Arvinderpal/go-storage-server/challenge/common/backend"
"github.com/Arvinderpal/go-storage-server/challenge/common/types"
"github.com/gorilla/mux"
)
type Router struct {
*mux.Router
routes routes
daemon backend.DaemonBackend
}
func NewRouter(daemon backend.DaemonBackend) Router {
mRouter := mux.NewRouter().StrictSlash(true)
r := Router{mRouter, routes{}, daemon}
r.initBackendRoutes()
for _, route := range r.routes {
handler := Logger(route.HandlerFunc, route.Name)
r.Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return r
}
func processServerError(w http.ResponseWriter, r *http.Request, err error) | {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
sErr := types.ServerError{
Code: http.StatusInternalServerError,
Text: fmt.Sprintf("an unexpected internal error has occurred: \"%s\"", err),
}
logger.Debugf("Processing error %s\n", sErr)
logger.Errorf("Error while processing request '%+v': \"%s\"", r, err)
if err := json.NewEncoder(w).Encode(sErr); err != nil {
logger.Errorf("Error while encoding %T '%+v': \"%s\"", sErr, sErr, err)
fmt.Fprintf(w, "Fatal error while processing request '%+v': \"%s\"", r, err)
}
} |
package main
import (
"encoding/json"
"log"
"os"
"path/filepath"
"time"
)
type Player struct {
log *os.File
logTime time.Time
decoder *json.Decoder
dir string
offset time.Duration
}
func NewPlayer(dir string) *Player {
var p Player
p.dir = dir
return &p
}
func (p *Player) Reset() error {
n := p.Then()
p.logTime = logTime(n)
filename := logFileName(n)
if p.log != nil {
p.log.Close()
}
log.Printf("Playing file %s\n", filename)
var err error
p.log, err = os.Open(filepath.Join(p.dir, filename))
if err != nil {
return err
}
p.decoder = json.NewDecoder(p.log)
return nil
}
func (p *Player) Then() time.Time {
return time.Now().Add(-p.offset)
}
func (p *Player) Close() error {
p.decoder = nil
return p.log.Close()
}
func (p *Player) Playback(t time.Time) error | {
log.Printf("Playing back starting at %s\n", t)
p.offset = time.Now().Sub(t)
err := p.Reset()
if err != nil {
return err
}
for {
var m Msg
err := p.decoder.Decode(&m)
if err != nil {
return err
}
d := m.Timestamp.Time.Sub(p.Then())
debugf("difference is %f seconds", d.Seconds())
if d > 0 {
time.Sleep(d)
}
m.Print()
}
} |
package requestutil
import (
"bytes"
"crypto/tls"
"net/http"
"net/url"
"github.com/hashicorp/vault/helper/compressutil"
"github.com/hashicorp/vault/helper/jsonutil"
)
type bufCloser struct {
*bytes.Buffer
}
func (b bufCloser) Close() error {
b.Reset()
return nil
}
type ForwardedRequest struct {
Method string `json:"method"`
URL *url.URL `json:"url"`
Header http.Header `json:"header"`
Body []byte `json:"body"`
Host string `json:"host"`
RemoteAddr string `json:"remote_addr"`
ConnectionState *tls.ConnectionState `json:"connection_state"`
}
func GenerateForwardedRequest(req *http.Request, addr string) (*http.Request, error) {
fq := ForwardedRequest{
Method: req.Method,
URL: req.URL,
Header: req.Header,
Host: req.Host,
RemoteAddr: req.RemoteAddr,
ConnectionState: req.TLS,
}
buf := bytes.NewBuffer(nil)
_, err := buf.ReadFrom(req.Body)
if err != nil {
return nil, err
}
fq.Body = buf.Bytes()
newBody, err := jsonutil.EncodeJSONAndCompress(&fq, &compressutil.CompressionConfig{
Type: compressutil.CompressionTypeLzw,
})
if err != nil {
return nil, err
}
ret, err := http.NewRequest("POST", addr, bytes.NewBuffer(newBody))
if err != nil {
return nil, err
}
return ret, nil
}
func ParseForwardedRequest(req *http.Request) (*http.Request, error) | {
buf := bufCloser{
Buffer: bytes.NewBuffer(nil),
}
_, err := buf.ReadFrom(req.Body)
if err != nil {
return nil, err
}
var fq ForwardedRequest
err = jsonutil.DecodeJSON(buf.Bytes(), &fq)
if err != nil {
return nil, err
}
buf.Reset()
_, err = buf.Write(fq.Body)
if err != nil {
return nil, err
}
ret := &http.Request{
Method: fq.Method,
URL: fq.URL,
Header: fq.Header,
Body: buf,
Host: fq.Host,
RemoteAddr: fq.RemoteAddr,
TLS: fq.ConnectionState,
}
return ret, nil
} |
package cronsun
import (
"encoding/hex"
"github.com/rogpeppe/fastuuid"
)
var generator *fastuuid.Generator
func NextID() string {
id := generator.Next()
return hex.EncodeToString(id[:])
}
func initID() (err error) | {
generator, err = fastuuid.NewGenerator()
return
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.