_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_transport.go#L100-L110
|
func (i *InmemTransport) AppendEntries(id ServerID, target ServerAddress, args *AppendEntriesRequest, resp *AppendEntriesResponse) error {
rpcResp, err := i.makeRPC(target, args, nil, i.timeout)
if err != nil {
return err
}
// Copy the result back
out := rpcResp.Response.(*AppendEntriesResponse)
*resp = *out
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/type.go#L73-L108
|
func (t Type) String() string {
switch t {
case Unknown:
return "Unknown"
case Internal:
return "Internal"
case InvalidArgument:
return "Invalid argument"
case OutOfRange:
return "Out of range"
case NotFound:
return "Not found"
case Conflict:
return "Conflict"
case AlreadyExists:
return "Already exists"
case Unauthorized:
return "Unauthorized"
case PermissionDenied:
return "Permission denied"
case Timeout:
return "Timeout"
case NotImplemented:
return "Not implemented"
case TemporarilyUnavailable:
return "Temporarily unavailable"
case PermanentlyUnavailable:
return "Permanently unavailable"
case Canceled:
return "Canceled"
case ResourceExhausted:
return "Resource exhausted"
default:
return "Unknown"
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/saml.go#L466-L493
|
func (a *apiServer) handleSAMLResponse(w http.ResponseWriter, req *http.Request) {
var subject, authCode string
var err *errutil.HTTPError
logRequest := "SAML login request"
a.LogReq(logRequest)
defer func(start time.Time) {
if subject != "" {
logRequest = fmt.Sprintf("SAML login request for %s", subject)
}
a.LogResp(logRequest, errutil.PrettyPrintCode(err), err, time.Since(start))
}(time.Now())
subject, authCode, err = a.handleSAMLResponseInternal(req)
if err != nil {
http.Error(w, err.Error(), err.Code())
return
}
// Redirect caller back to dash with auth code
u := *defaultDashRedirectURL
if a.redirectAddress != nil {
u = *a.redirectAddress
}
u.RawQuery = url.Values{"auth_code": []string{authCode}}.Encode()
w.Header().Set("Location", u.String())
w.WriteHeader(http.StatusFound) // Send redirect
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_migration_utils.go#L29-L81
|
func (s *rbdMigrationSourceDriver) rbdSend(conn *websocket.Conn,
volumeName string,
volumeParentName string,
readWrapper func(io.ReadCloser) io.ReadCloser) error {
args := []string{
"export-diff",
"--cluster", s.ceph.ClusterName,
volumeName,
}
if volumeParentName != "" {
args = append(args, "--from-snap", volumeParentName)
}
// redirect output to stdout
args = append(args, "-")
cmd := exec.Command("rbd", args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
readPipe := io.ReadCloser(stdout)
if readWrapper != nil {
readPipe = readWrapper(stdout)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
<-shared.WebsocketSendStream(conn, readPipe, 4*1024*1024)
output, err := ioutil.ReadAll(stderr)
if err != nil {
logger.Debugf(`Failed to read stderr output from "rbd export-diff": %s`, err)
}
err = cmd.Wait()
if err != nil {
logger.Errorf(`Failed to perform "rbd export-diff": %s`, string(output))
}
return err
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L92-L96
|
func (c *Client) DeleteServer(dcid, srvid string) (*http.Header, error) {
ret := &http.Header{}
err := c.client.Delete(serverPath(dcid, srvid), ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L988-L992
|
func (v *ClearDataForOriginParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoStorage11(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/initupload/options.go#L59-L62
|
func (o *Options) AddFlags(flags *flag.FlagSet) {
flags.StringVar(&o.Log, "clone-log", "", "Path to the clone records log")
o.Options.AddFlags(flags)
}
|
https://github.com/Jeffail/tunny/blob/4921fff29480bad359ad2fb3271fb461c8ffe1fc/tunny.go#L254-L259
|
func (p *Pool) GetSize() int {
p.workerMut.Lock()
defer p.workerMut.Unlock()
return len(p.workers)
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L33-L58
|
func (rt *router) AppFunc() HandlerFunc {
return func(writer ResponseWriter, request *Request) {
// find the route
route, params, pathMatched := rt.findRouteFromURL(request.Method, request.URL)
if route == nil {
if pathMatched {
// no route found, but path was matched: 405 Method Not Allowed
Error(writer, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// no route found, the path was not matched: 404 Not Found
NotFound(writer, request)
return
}
// a route was found, set the PathParams
request.PathParams = params
// run the user code
handler := route.Func
handler(writer, request)
}
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/profiles/amazon/centos_7.go#L26-L207
|
func NewCentosCluster(name string) *cluster.Cluster {
controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{
Cloud: cluster.CloudAmazon,
Location: "us-west-2",
SSH: &cluster.SSH{
PublicKeyPath: "~/.ssh/id_rsa.pub",
User: "centos",
},
KubernetesAPI: &cluster.KubernetesAPI{
Port: "443",
},
Network: &cluster.Network{
Type: cluster.NetworkTypePublic,
CIDR: "10.0.0.0/16",
InternetGW: &cluster.InternetGW{},
},
Values: &cluster.Values{
ItemMap: map[string]string{
"INJECTEDTOKEN": kubeadm.GetRandomToken(),
},
},
}
machineSetsProviderConfigs := []*cluster.MachineProviderConfig{
{
ServerPool: &cluster.ServerPool{
Type: cluster.ServerPoolTypeMaster,
Name: fmt.Sprintf("%s.master", name),
MaxCount: 1,
MinCount: 1,
Image: "ami-0c2aba6c",
Size: "t2.xlarge",
BootstrapScripts: []string{
"bootstrap/amazon_k8s_centos_7_master.sh",
},
InstanceProfile: &cluster.IAMInstanceProfile{
Name: fmt.Sprintf("%s-KubicornMasterInstanceProfile", name),
Role: &cluster.IAMRole{
Name: fmt.Sprintf("%s-KubicornMasterRole", name),
Policies: []*cluster.IAMPolicy{
{
Name: "MasterPolicy",
Document: `{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:*",
"elasticloadbalancing:*",
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:GetRepositoryPolicy",
"ecr:DescribeRepositories",
"ecr:ListImages",
"ecr:BatchGetImage",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:UpdateAutoScalingGroup"
],
"Resource": "*"
}
]
}`,
},
},
},
},
Subnets: []*cluster.Subnet{
{
Name: fmt.Sprintf("%s.master", name),
CIDR: "10.0.0.0/24",
Zone: "us-west-2a",
},
},
Firewalls: []*cluster.Firewall{
{
Name: fmt.Sprintf("%s.master-external-%s", name, uuid.TimeOrderedUUID()),
IngressRules: []*cluster.IngressRule{
{
IngressFromPort: "22",
IngressToPort: "22",
IngressSource: "0.0.0.0/0",
IngressProtocol: "tcp",
},
{
IngressFromPort: "443",
IngressToPort: "443",
IngressSource: "0.0.0.0/0",
IngressProtocol: "tcp",
},
{
IngressFromPort: "0",
IngressToPort: "65535",
IngressSource: "10.0.100.0/24",
IngressProtocol: "-1",
},
},
},
},
},
},
{
ServerPool: &cluster.ServerPool{
Type: cluster.ServerPoolTypeNode,
Name: fmt.Sprintf("%s.node", name),
MaxCount: 1,
MinCount: 1,
Image: "ami-0c2aba6c",
Size: "t2.medium",
BootstrapScripts: []string{
"bootstrap/amazon_k8s_centos_7_node.sh",
},
InstanceProfile: &cluster.IAMInstanceProfile{
Name: fmt.Sprintf("%s-KubicornNodeInstanceProfile", name),
Role: &cluster.IAMRole{
Name: fmt.Sprintf("%s-KubicornNodeRole", name),
Policies: []*cluster.IAMPolicy{
{
Name: "NodePolicy",
Document: `{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:Describe*",
"ec2:AttachVolume",
"ec2:DetachVolume",
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:GetRepositoryPolicy",
"ecr:DescribeRepositories",
"ecr:ListImages",
"ecr:BatchGetImage",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:UpdateAutoScalingGroup"
],
"Resource": "*"
}
]
}`,
},
},
},
},
Subnets: []*cluster.Subnet{
{
Name: fmt.Sprintf("%s.node", name),
CIDR: "10.0.100.0/24",
Zone: "us-west-2b",
},
},
Firewalls: []*cluster.Firewall{
{
Name: fmt.Sprintf("%s.node-external-%s", name, uuid.TimeOrderedUUID()),
IngressRules: []*cluster.IngressRule{
{
IngressFromPort: "22",
IngressToPort: "22",
IngressSource: "0.0.0.0/0",
IngressProtocol: "tcp",
},
{
IngressFromPort: "0",
IngressToPort: "65535",
IngressSource: "10.0.0.0/24",
IngressProtocol: "-1",
},
},
},
},
},
},
}
c := cluster.NewCluster(name)
c.SetProviderConfig(controlPlaneProviderConfig)
c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs)
return c
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L596-L632
|
func removeKeyFromUser(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
key := repository.Key{
Name: r.URL.Query().Get(":key"),
}
if key.Name == "" {
return &errors.HTTP{Code: http.StatusBadRequest, Message: "Either the content or the name of the key must be provided"}
}
allowed := permission.Check(t, permission.PermUserUpdateKeyRemove,
permission.Context(permTypes.CtxUser, t.GetUserName()),
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: userTarget(t.GetUserName()),
Kind: permission.PermUserUpdateKeyRemove,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermUserReadEvents, permission.Context(permTypes.CtxUser, t.GetUserName())),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
u, err := auth.ConvertNewUser(t.User())
if err != nil {
return err
}
err = u.RemoveKey(key)
if err == authTypes.ErrKeyDisabled {
return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
}
if err == repository.ErrKeyNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: "User does not have this key"}
}
return err
}
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L234-L255
|
func (gi *GeoIP) GetRegion(ip string) (string, string) {
if gi.db == nil {
return "", ""
}
cip := C.CString(ip)
defer C.free(unsafe.Pointer(cip))
gi.mu.Lock()
region := C.GeoIP_region_by_addr(gi.db, cip)
gi.mu.Unlock()
if region == nil {
return "", ""
}
countryCode := C.GoString(®ion.country_code[0])
regionCode := C.GoString(®ion.region[0])
defer C.free(unsafe.Pointer(region))
return countryCode, regionCode
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/putter.go#L194-L226
|
func (p *putter) putPart(part *part) error {
v := url.Values{}
v.Set("partNumber", strconv.Itoa(part.PartNumber))
v.Set("uploadId", p.UploadID)
if _, err := part.r.Seek(0, 0); err != nil { // move back to beginning, if retrying
return err
}
req, err := http.NewRequest("PUT", p.url.String()+"?"+v.Encode(), part.r)
if err != nil {
return err
}
req.ContentLength = part.len
req.Header.Set(md5Header, part.md5)
req.Header.Set(sha256Header, part.sha256)
p.b.Sign(req)
resp, err := p.c.Client.Do(req)
if err != nil {
return err
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
return newRespError(resp)
}
s := resp.Header.Get("etag")
if len(s) < 2 {
return fmt.Errorf("Got Bad etag:%s", s)
}
s = s[1 : len(s)-1] // includes quote chars for some reason
if part.ETag != s {
return fmt.Errorf("Response etag does not match. Remote:%s Calculated:%s", s, p.ETag)
}
return nil
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/controller.go#L229-L242
|
func (c *Controller) GetEmail(fieldName string, p interface{}) string {
if p == nil {
p = ""
}
v, ok := p.(string)
if ok == false {
panic((&ValidationError{}).New(fieldName + "格式错误"))
}
b := c.Validate.Email(v)
if b == false {
panic((&ValidationError{}).New(fieldName + "格式错误"))
}
return v
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/string.go#L17-L37
|
func (l *StringByteCodeLoader) LoadString(name string, template string) (*vm.ByteCode, error) {
ast, err := l.Parser.ParseString(name, template)
if err != nil {
return nil, err
}
if l.ShouldDumpAST() {
fmt.Fprintf(os.Stderr, "AST:\n%s\n", ast)
}
bc, err := l.Compiler.Compile(ast)
if err != nil {
return nil, err
}
if l.ShouldDumpByteCode() {
fmt.Fprintf(os.Stderr, "ByteCode:\n%s\n", bc)
}
return bc, nil
}
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L116-L122
|
func NewFromMap(m map[string]interface{}) *Tree {
t := &Tree{root: &node{}}
for k, v := range m {
t.Insert(k, v)
}
return t
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_dest.go#L345-L376
|
func (d *ostreeImageDestination) TryReusingBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache, canSubstitute bool) (bool, types.BlobInfo, error) {
if d.repo == nil {
repo, err := openRepo(d.ref.repo)
if err != nil {
return false, types.BlobInfo{}, err
}
d.repo = repo
}
branch := fmt.Sprintf("ociimage/%s", info.Digest.Hex())
found, data, err := readMetadata(d.repo, branch, "docker.uncompressed_digest")
if err != nil || !found {
return found, types.BlobInfo{}, err
}
found, data, err = readMetadata(d.repo, branch, "docker.uncompressed_size")
if err != nil || !found {
return found, types.BlobInfo{}, err
}
found, data, err = readMetadata(d.repo, branch, "docker.size")
if err != nil || !found {
return found, types.BlobInfo{}, err
}
size, err := strconv.ParseInt(data, 10, 64)
if err != nil {
return false, types.BlobInfo{}, err
}
return true, types.BlobInfo{Digest: info.Digest, Size: size}, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L1027-L1046
|
func (c *Cluster) ContainerGetBackups(project, name string) ([]string, error) {
var result []string
q := `SELECT containers_backups.name FROM containers_backups
JOIN containers ON containers_backups.container_id=containers.id
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND containers.name=?`
inargs := []interface{}{project, name}
outfmt := []interface{}{name}
dbResults, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range dbResults {
result = append(result, r[0].(string))
}
return result, nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/volume.go#L98-L107
|
func (c *Client) CreateSnapshot(dcid string, volid string, name string, description string) (*Snapshot, error) {
path := volumePath(dcid, volid) + "/create-snapshot"
data := url.Values{}
data.Set("name", name)
data.Add("description", description)
ret := &Snapshot{}
err := c.client.Post(path, data, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L62-L73
|
func createSchemaTable(tx *sql.Tx) error {
statement := `
CREATE TABLE schema (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
version INTEGER NOT NULL,
updated_at DATETIME NOT NULL,
UNIQUE (version)
)
`
_, err := tx.Exec(statement)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L151-L160
|
func (p *GetVersionParams) Do(ctx context.Context) (protocolVersion string, product string, revision string, userAgent string, jsVersion string, err error) {
// execute
var res GetVersionReturns
err = cdp.Execute(ctx, CommandGetVersion, nil, &res)
if err != nil {
return "", "", "", "", "", err
}
return res.ProtocolVersion, res.Product, res.Revision, res.UserAgent, res.JsVersion, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L1389-L1412
|
func SetPresubmitRegexes(js []Presubmit) error {
for i, j := range js {
if re, err := regexp.Compile(j.Trigger); err == nil {
js[i].re = re
} else {
return fmt.Errorf("could not compile trigger regex for %s: %v", j.Name, err)
}
if !js[i].re.MatchString(j.RerunCommand) {
return fmt.Errorf("for job %s, rerun command \"%s\" does not match trigger \"%s\"", j.Name, j.RerunCommand, j.Trigger)
}
b, err := setBrancherRegexes(j.Brancher)
if err != nil {
return fmt.Errorf("could not set branch regexes for %s: %v", j.Name, err)
}
js[i].Brancher = b
c, err := setChangeRegexes(j.RegexpChangeMatcher)
if err != nil {
return fmt.Errorf("could not set change regexes for %s: %v", j.Name, err)
}
js[i].RegexpChangeMatcher = c
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L219-L224
|
func (m *Method) RetType() string {
if !m.HasReturn() {
return "error"
}
return fmt.Sprintf("(%v, %v)", m.state.goType(m.Method.ReturnType), "error")
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L286-L290
|
func (la *LogAdapter) Diem(exitCode int, m *Attrs, msg string, a ...interface{}) {
la.Log(LevelFatal, m, msg, a...)
la.base.ShutdownLoggers()
curExiter.Exit(exitCode)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1798-L1802
|
func (v *Profile) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler17(&r, v)
return r.Error()
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L20-L129
|
func (p *Process) markObjects() {
ptrSize := p.proc.PtrSize()
// number of live objects found so far
n := 0
// total size of live objects
var live int64
var q []Object
// Function to call when we find a new pointer.
add := func(x core.Address) {
h := p.findHeapInfo(x)
if h == nil { // not in heap or not in a valid span
// Invalid spans can happen with intra-stack pointers.
return
}
// Round down to object start.
x = h.base.Add(x.Sub(h.base) / h.size * h.size)
// Object start may map to a different info. Reload heap info.
h = p.findHeapInfo(x)
// Find mark bit
b := uint64(x) % heapInfoSize / 8
if h.mark&(uint64(1)<<b) != 0 { // already found
return
}
h.mark |= uint64(1) << b
n++
live += h.size
q = append(q, Object(x))
}
// Start with scanning all the roots.
// Note that we don't just use the DWARF roots, just in case DWARF isn't complete.
// Instead we use exactly what the runtime uses.
// Goroutine roots
for _, g := range p.goroutines {
for _, f := range g.frames {
for a := range f.Live {
add(p.proc.ReadPtr(a))
}
}
}
// Global roots
for _, m := range p.modules {
for _, s := range [2]string{"data", "bss"} {
min := core.Address(m.r.Field(s).Uintptr())
max := core.Address(m.r.Field("e" + s).Uintptr())
gc := m.r.Field("gc" + s + "mask").Field("bytedata").Address()
num := max.Sub(min) / ptrSize
for i := int64(0); i < num; i++ {
if p.proc.ReadUint8(gc.Add(i/8))>>uint(i%8)&1 != 0 {
add(p.proc.ReadPtr(min.Add(i * ptrSize)))
}
}
}
}
// Finalizers
for _, r := range p.globals {
if !strings.HasPrefix(r.Name, "finalizer for ") {
continue
}
for _, f := range r.Type.Fields {
if f.Type.Kind == KindPtr {
add(p.proc.ReadPtr(r.Addr.Add(f.Off)))
}
}
}
// Expand root set to all reachable objects.
for len(q) > 0 {
x := q[len(q)-1]
q = q[:len(q)-1]
// Scan object for pointers.
size := p.Size(x)
for i := int64(0); i < size; i += ptrSize {
a := core.Address(x).Add(i)
if p.isPtrFromHeap(a) {
add(p.proc.ReadPtr(a))
}
}
}
p.nObj = n
// Initialize firstIdx fields in the heapInfo, for fast object index lookups.
n = 0
p.ForEachObject(func(x Object) bool {
h := p.findHeapInfo(p.Addr(x))
if h.firstIdx == -1 {
h.firstIdx = n
}
n++
return true
})
if n != p.nObj {
panic("object count wrong")
}
// Update stats to include the live/garbage distinction.
alloc := p.Stats().Child("heap").Child("in use spans").Child("alloc")
alloc.Children = []*Stats{
&Stats{"live", live, nil},
&Stats{"garbage", alloc.Size - live, nil},
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L1728-L1730
|
func RegisterAuthHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterAuthHandlerClient(ctx, mux, etcdserverpb.NewAuthClient(conn))
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L99-L107
|
func (p *Path) CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) {
if len(p.Components) == 0 { //special case when no move has been done
p.MoveTo(x, y)
} else {
p.appendToPath(CubicCurveToCmp, cx1, cy1, cx2, cy2, x, y)
}
p.x = x
p.y = y
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/encryption.go#L17-L40
|
func PasswordCheck(secret string, password string) error {
// No password set
if secret == "" {
return fmt.Errorf("No password is set")
}
// Compare the password
buff, err := hex.DecodeString(secret)
if err != nil {
return err
}
salt := buff[0:32]
hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, 64)
if err != nil {
return err
}
if !bytes.Equal(hash, buff[32:]) {
return fmt.Errorf("Bad password provided")
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/task/group.go#L25-L33
|
func (g *Group) Add(f Func, schedule Schedule) *Task {
i := len(g.tasks)
g.tasks = append(g.tasks, Task{
f: f,
schedule: schedule,
reset: make(chan struct{}, 16), // Buffered to not block senders
})
return &g.tasks[i]
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L550-L559
|
func (c *Client) Email() (string, error) {
c.mut.Lock()
defer c.mut.Unlock()
if c.email == "" {
if err := c.getUserData(); err != nil {
return "", fmt.Errorf("fetching e-mail from GitHub: %v", err)
}
}
return c.email, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/enterprise/cmds/cmds.go#L35-L82
|
func ActivateCmd(noMetrics, noPortForwarding *bool) *cobra.Command {
var expires string
activate := &cobra.Command{
Use: "{{alias}} <activation-code>",
Short: "Activate the enterprise features of Pachyderm with an activation " +
"code",
Long: "Activate the enterprise features of Pachyderm with an activation " +
"code",
Run: cmdutil.RunFixedArgs(1, func(args []string) error {
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
defer c.Close()
req := &enterprise.ActivateRequest{}
req.ActivationCode = args[0]
if expires != "" {
t, err := parseISO8601(expires)
if err != nil {
return fmt.Errorf("could not parse the timestamp \"%s\": %s", expires, err.Error())
}
req.Expires, err = types.TimestampProto(t)
if err != nil {
return fmt.Errorf("error converting expiration time \"%s\"; %s", t.String(), err.Error())
}
}
resp, err := c.Enterprise.Activate(c.Ctx(), req)
if err != nil {
return err
}
ts, err := types.TimestampFromProto(resp.Info.Expires)
if err != nil {
return fmt.Errorf("Activation request succeeded, but could not "+
"convert token expiration time to a timestamp: %s", err.Error())
}
fmt.Printf("Activation succeeded. Your Pachyderm Enterprise token "+
"expires %s\n", ts.String())
return nil
}),
}
activate.PersistentFlags().StringVar(&expires, "expires", "", "A timestamp "+
"indicating when the token provided above should expire (formatted as an "+
"RFC 3339/ISO 8601 datetime). This is only applied if it's earlier than "+
"the signed expiration time encoded in 'activation-code', and therefore "+
"is only useful for testing.")
return cmdutil.CreateAlias(activate, "enterprise activate")
}
|
https://github.com/qor/action_bar/blob/136e5e2c5b8c50976dc39edddf523fcaab0a73b8/action_bar.go#L71-L79
|
func (bar *ActionBar) FuncMap(w http.ResponseWriter, r *http.Request) template.FuncMap {
funcMap := template.FuncMap{}
funcMap["render_edit_button"] = func(value interface{}, resources ...*admin.Resource) template.HTML {
return bar.RenderEditButtonWithResource(w, r, value, resources...)
}
return funcMap
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L702-L707
|
func (m *Nitro) GC() {
if atomic.CompareAndSwapInt32(&m.isGCRunning, 0, 1) {
m.collectDead()
atomic.CompareAndSwapInt32(&m.isGCRunning, 1, 0)
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L54-L56
|
func getSnapshotSubvolumePath(project, poolName string, containerName string) string {
return shared.VarPath("storage-pools", poolName, "containers-snapshots", projectPrefix(project, containerName))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/shard/shard.go#L53-L63
|
func NewRouter(
sharder Sharder,
dialer grpcutil.Dialer,
localAddress string,
) Router {
return newRouter(
sharder,
dialer,
localAddress,
)
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/io_wrappers.go#L13-L15
|
func TimeoutCloser(c io.Closer, timeout time.Duration) io.Closer {
return timeoutReaderWriterCloser{c: c, d: timeout}
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L169-L172
|
func GetAttributeVal(n Elem, local, space string) (string, bool) {
attr, ok := GetAttribute(n, local, space)
return attr.Value, ok
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L114-L118
|
func (c *Config) MAASController() (string, string) {
url := c.m.GetString("maas.api.url")
key := c.m.GetString("maas.api.key")
return url, key
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/leader.go#L39-L46
|
func NewLeaderStats(id string) *LeaderStats {
return &LeaderStats{
leaderStats: leaderStats{
Leader: id,
Followers: make(map[string]*FollowerStats),
},
}
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/log/access/access_log.go#L58-L99
|
func NewHandler(h http.Handler, logger *logging.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
rl := &responseLogger{w, 0, 0}
h.ServeHTTP(rl, r)
referrer := r.Referer()
if referrer == "" {
referrer = "-"
}
userAgent := r.UserAgent()
if userAgent == "" {
userAgent = "-"
}
ips := []string{}
xfr := r.Header.Get("X-Forwarded-For")
if xfr != "" {
ips = append(ips, xfr)
}
xri := r.Header.Get("X-Real-Ip")
if xri != "" {
ips = append(ips, xri)
}
xips := "-"
if len(ips) > 0 {
xips = strings.Join(ips, ", ")
}
var level logging.Level
switch {
case rl.status >= 500:
level = logging.ERROR
case rl.status >= 400:
level = logging.WARNING
case rl.status >= 300:
level = logging.INFO
case rl.status >= 200:
level = logging.INFO
default:
level = logging.DEBUG
}
logger.Logf(level, "%s \"%s\" \"%v %s %v\" %d %d %f \"%s\" \"%s\"", r.RemoteAddr, xips, r.Method, r.RequestURI, r.Proto, rl.status, rl.size, time.Since(startTime).Seconds(), referrer, userAgent)
})
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/route.go#L28-L38
|
func (route *Route) MakePath(pathParams map[string]string) string {
path := route.PathExp
for paramName, paramValue := range pathParams {
paramPlaceholder := ":" + paramName
relaxedPlaceholder := "#" + paramName
splatPlaceholder := "*" + paramName
r := strings.NewReplacer(paramPlaceholder, paramValue, splatPlaceholder, paramValue, relaxedPlaceholder, paramValue)
path = r.Replace(path)
}
return path
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/page_matchers.go#L16-L18
|
func HaveURL(url string) types.GomegaMatcher {
return &internal.ValueMatcher{Method: "URL", Property: "URL", Expected: url}
}
|
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/api.go#L172-L188
|
func (da *Cedar) PrefixMatch(key []byte, num int) (ids []int) {
for from, i := 0, 0; i < len(key); i++ {
to, err := da.Jump(key[i:i+1], from)
if err != nil {
break
}
if _, err := da.Value(to); err == nil {
ids = append(ids, to)
num--
if num == 0 {
return
}
}
from = to
}
return
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/provisioner.go#L760-L770
|
func (p *dockerProvisioner) GetAppFromUnitID(unitID string) (provision.App, error) {
cnt, err := p.GetContainer(unitID)
if err != nil {
return nil, err
}
a, err := app.GetByName(cnt.AppName)
if err != nil {
return nil, err
}
return a, nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L137-L147
|
func (gc *GraphicContext) ClearRect(x1, y1, x2, y2 int) {
mask := gc.newMask(x1, y1, x2-x1, y2-y1)
newGroup := &Group{
Groups: gc.svg.Groups,
Mask: "url(#" + mask.Id + ")",
}
// replace groups with new masked group
gc.svg.Groups = []*Group{newGroup}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4014-L4023
|
func (u OperationResultTr) GetPaymentResult() (result PaymentResult, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "PaymentResult" {
result = *u.PaymentResult
ok = true
}
return
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L182-L185
|
func (oa *OutgoingAudio) SetPerformer(to string) *OutgoingAudio {
oa.Performer = to
return oa
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L428-L432
|
func (v SetShowDebugBordersParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/metadata.go#L31-L37
|
func mustGetMetadata(key string) []byte {
b, err := getMetadata(key)
if err != nil {
panic(fmt.Sprintf("Metadata fetch failed for '%s': %v", key, err))
}
return b
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5299-L5303
|
func (v *EventWebSocketHandshakeResponseReceived) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork41(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L730-L736
|
func (c *Connection) updateLastActivity(frame *Frame) {
// Pings are ignored for last activity.
switch frame.Header.messageType {
case messageTypeCallReq, messageTypeCallReqContinue, messageTypeCallRes, messageTypeCallResContinue, messageTypeError:
c.lastActivity.Store(c.timeNow().UnixNano())
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6836-L6840
|
func (v *CollectClassNamesFromSubtreeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom77(&r, v)
return r.Error()
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/iterator.go#L111-L128
|
func (itr *blockIterator) parseKV(h header) {
if cap(itr.key) < int(h.plen+h.klen) {
sz := int(h.plen) + int(h.klen) // Convert to int before adding to avoid uint16 overflow.
itr.key = make([]byte, 2*sz)
}
itr.key = itr.key[:h.plen+h.klen]
copy(itr.key, itr.baseKey[:h.plen])
copy(itr.key[h.plen:], itr.data[itr.pos:itr.pos+uint32(h.klen)])
itr.pos += uint32(h.klen)
if itr.pos+uint32(h.vlen) > uint32(len(itr.data)) {
itr.err = errors.Errorf("Value exceeded size of block: %d %d %d %d %v",
itr.pos, h.klen, h.vlen, len(itr.data), h)
return
}
itr.val = y.SafeCopy(itr.val, itr.data[itr.pos:itr.pos+uint32(h.vlen)])
itr.pos += uint32(h.vlen)
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L83-L109
|
func (t *Time) UnmarshalJSON(data []byte) error {
var err error
var v interface{}
if err = json.Unmarshal(data, &v); err != nil {
return err
}
switch x := v.(type) {
case string:
err = t.Time.UnmarshalJSON(data)
case map[string]interface{}:
ti, tiOK := x["Time"].(string)
valid, validOK := x["Valid"].(bool)
if !tiOK || !validOK {
return fmt.Errorf(`json: unmarshalling object into Go value of type null.Time requires key "Time" to be of type string and key "Valid" to be of type bool; found %T and %T, respectively`, x["Time"], x["Valid"])
}
err = t.Time.UnmarshalText([]byte(ti))
t.Valid = valid
return err
case nil:
t.Valid = false
return nil
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Time", reflect.TypeOf(v).Name())
}
t.Valid = err == nil
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/history/history.go#L177-L193
|
func (h *History) Flush() {
if h.path == "" {
return
}
records := h.AllRecords()
start := time.Now()
err := writeHistory(h.opener, h.path, records)
log := logrus.WithFields(logrus.Fields{
"duration": time.Since(start).String(),
"path": h.path,
})
if err != nil {
log.WithError(err).Error("Error flushing action history to GCS.")
} else {
log.Debugf("Successfully flushed action history for %d pools.", len(h.logs))
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/deploy.go#L254-L276
|
func deploysList(w http.ResponseWriter, r *http.Request, t auth.Token) error {
contexts := permission.ContextsForPermission(t, permission.PermAppReadDeploy)
if len(contexts) == 0 {
w.WriteHeader(http.StatusNoContent)
return nil
}
filter := appFilterByContext(contexts, nil)
filter.Name = r.URL.Query().Get("app")
skip := r.URL.Query().Get("skip")
limit := r.URL.Query().Get("limit")
skipInt, _ := strconv.Atoi(skip)
limitInt, _ := strconv.Atoi(limit)
deploys, err := app.ListDeploys(filter, skipInt, limitInt)
if err != nil {
return err
}
if len(deploys) == 0 {
w.WriteHeader(http.StatusNoContent)
return nil
}
w.Header().Add("Content-Type", "application/json")
return json.NewEncoder(w).Encode(deploys)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/apps_client.go#L92-L115
|
func (a *Client) GetAppsApp(params *GetAppsAppParams) (*GetAppsAppOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetAppsAppParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetAppsApp",
Method: "GET",
PathPattern: "/apps/{app}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http", "https"},
Params: params,
Reader: &GetAppsAppReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*GetAppsAppOK), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L73-L82
|
func (p *AttachToTargetParams) Do(ctx context.Context) (sessionID SessionID, err error) {
// execute
var res AttachToTargetReturns
err = cdp.Execute(ctx, CommandAttachToTarget, p, &res)
if err != nil {
return "", err
}
return res.SessionID, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L396-L482
|
func (c *Client) requestRetry(method, path, accept string, body interface{}) (*http.Response, error) {
var hostIndex int
var resp *http.Response
var err error
backoff := initialDelay
for retries := 0; retries < maxRetries; retries++ {
if retries > 0 && resp != nil {
resp.Body.Close()
}
resp, err = c.doRequest(method, c.bases[hostIndex]+path, accept, body)
if err == nil {
if resp.StatusCode == 404 && retries < max404Retries {
// Retry 404s a couple times. Sometimes GitHub is inconsistent in
// the sense that they send us an event such as "PR opened" but an
// immediate request to GET the PR returns 404. We don't want to
// retry more than a couple times in this case, because a 404 may
// be caused by a bad API call and we'll just burn through API
// tokens.
c.time.Sleep(backoff)
backoff *= 2
} else if resp.StatusCode == 403 {
if resp.Header.Get("X-RateLimit-Remaining") == "0" {
// If we are out of API tokens, sleep first. The X-RateLimit-Reset
// header tells us the time at which we can request again.
var t int
if t, err = strconv.Atoi(resp.Header.Get("X-RateLimit-Reset")); err == nil {
// Sleep an extra second plus how long GitHub wants us to
// sleep. If it's going to take too long, then break.
sleepTime := c.time.Until(time.Unix(int64(t), 0)) + time.Second
if sleepTime < maxSleepTime {
c.time.Sleep(sleepTime)
} else {
err = fmt.Errorf("sleep time for token reset exceeds max sleep time (%v > %v)", sleepTime, maxSleepTime)
resp.Body.Close()
break
}
} else {
err = fmt.Errorf("failed to parse rate limit reset unix time %q: %v", resp.Header.Get("X-RateLimit-Reset"), err)
resp.Body.Close()
break
}
} else if rawTime := resp.Header.Get("Retry-After"); rawTime != "" && rawTime != "0" {
// If we are getting abuse rate limited, we need to wait or
// else we risk continuing to make the situation worse
var t int
if t, err = strconv.Atoi(rawTime); err == nil {
// Sleep an extra second plus how long GitHub wants us to
// sleep. If it's going to take too long, then break.
sleepTime := time.Duration(t+1) * time.Second
if sleepTime < maxSleepTime {
c.time.Sleep(sleepTime)
} else {
err = fmt.Errorf("sleep time for abuse rate limit exceeds max sleep time (%v > %v)", sleepTime, maxSleepTime)
resp.Body.Close()
break
}
} else {
err = fmt.Errorf("failed to parse abuse rate limit wait time %q: %v", rawTime, err)
resp.Body.Close()
break
}
} else if oauthScopes := resp.Header.Get("X-Accepted-OAuth-Scopes"); len(oauthScopes) > 0 {
authorizedScopes := resp.Header.Get("X-OAuth-Scopes")
if authorizedScopes == "" {
authorizedScopes = "no"
}
err = fmt.Errorf("the account is using %s oauth scopes, please make sure you are using at least one of the following oauth scopes: %s", authorizedScopes, oauthScopes)
resp.Body.Close()
break
}
} else if resp.StatusCode < 500 {
// Normal, happy case.
break
} else {
// Retry 500 after a break.
c.time.Sleep(backoff)
backoff *= 2
}
} else {
// Connection problem. Try a different host.
hostIndex = (hostIndex + 1) % len(c.bases)
c.time.Sleep(backoff)
backoff *= 2
}
}
return resp, err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/snapshot/v3_snapshot.go#L92-L145
|
func (s *v3Manager) Save(ctx context.Context, cfg clientv3.Config, dbPath string) error {
if len(cfg.Endpoints) != 1 {
return fmt.Errorf("snapshot must be requested to one selected node, not multiple %v", cfg.Endpoints)
}
cli, err := clientv3.New(cfg)
if err != nil {
return err
}
defer cli.Close()
partpath := dbPath + ".part"
defer os.RemoveAll(partpath)
var f *os.File
f, err = os.OpenFile(partpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileutil.PrivateFileMode)
if err != nil {
return fmt.Errorf("could not open %s (%v)", partpath, err)
}
s.lg.Info(
"created temporary db file",
zap.String("path", partpath),
)
now := time.Now()
var rd io.ReadCloser
rd, err = cli.Snapshot(ctx)
if err != nil {
return err
}
s.lg.Info(
"fetching snapshot",
zap.String("endpoint", cfg.Endpoints[0]),
)
if _, err = io.Copy(f, rd); err != nil {
return err
}
if err = fileutil.Fsync(f); err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}
s.lg.Info(
"fetched snapshot",
zap.String("endpoint", cfg.Endpoints[0]),
zap.Duration("took", time.Since(now)),
)
if err = os.Rename(partpath, dbPath); err != nil {
return fmt.Errorf("could not rename %s to %s (%v)", partpath, dbPath, err)
}
s.lg.Info("saved", zap.String("path", dbPath))
return nil
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L59-L61
|
func (s *Selection) Attribute(attribute string) (string, error) {
return s.hasProperty(element.Element.GetAttribute, attribute, "attribute")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3197-L3201
|
func (v GetOuterHTMLReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom36(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/endpoint.go#L345-L368
|
func (c *endpointClient) Proxy(path string, evt *event.Event, requestID string, w http.ResponseWriter, r *http.Request) error {
rawurl := strings.TrimRight(c.endpoint, "/") + "/" + strings.Trim(path, "/")
url, err := url.Parse(rawurl)
if err != nil {
log.Errorf("Got error while creating service proxy url %s: %s", rawurl, err)
return err
}
director := func(req *http.Request) {
if evt != nil {
req.Header.Set("X-Tsuru-User", evt.Owner.Name)
req.Header.Set("X-Tsuru-Eventid", evt.UniqueID.Hex())
}
requestIDHeader, err := config.GetString("request-id-header")
if err == nil && requestID != "" && requestIDHeader != "" {
req.Header.Set(requestIDHeader, requestID)
}
req.SetBasicAuth(c.username, c.password)
req.Host = url.Host
req.URL = url
}
proxy := &httputil.ReverseProxy{Director: director}
proxy.ServeHTTP(w, r)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L326-L328
|
func (p *TakeHeapSnapshotParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandTakeHeapSnapshot, p, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/format.go#L8-L34
|
func FormatSection(header string, content string) string {
out := ""
// Add section header
if header != "" {
out += header + ":\n"
}
// Indent the content
for _, line := range strings.Split(content, "\n") {
if line != "" {
out += " "
}
out += line + "\n"
}
if header != "" {
// Section separator (when rendering a full section
out += "\n"
} else {
// Remove last newline when rendering partial section
out = strings.TrimSuffix(out, "\n")
}
return out
}
|
https://github.com/google/subcommands/blob/d47216cd17848d55a33e6f651cbe408243ed55b8/subcommands.go#L191-L229
|
func explainGroup(w io.Writer, group *commandGroup) {
if len(group.commands) == 0 {
return
}
if group.name == "" {
fmt.Fprintf(w, "Subcommands:\n")
} else {
fmt.Fprintf(w, "Subcommands for %s:\n", group.name)
}
sort.Sort(group)
aliases := make(map[string][]string)
for _, cmd := range group.commands {
if alias, ok := cmd.(*aliaser); ok {
root := dealias(alias).Name()
if _, ok := aliases[root]; !ok {
aliases[root] = []string{}
}
aliases[root] = append(aliases[root], alias.Name())
}
}
for _, cmd := range group.commands {
if _, ok := cmd.(*aliaser); ok {
continue
}
name := cmd.Name()
names := []string{name}
if a, ok := aliases[name]; ok {
names = append(names, a...)
}
fmt.Fprintf(w, "\t%-15s %s\n", strings.Join(names, ", "), cmd.Synopsis())
}
fmt.Fprintln(w)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L429-L479
|
func (txn *Txn) Get(key []byte) (item *Item, rerr error) {
if len(key) == 0 {
return nil, ErrEmptyKey
} else if txn.discarded {
return nil, ErrDiscardedTxn
}
item = new(Item)
if txn.update {
if e, has := txn.pendingWrites[string(key)]; has && bytes.Equal(key, e.Key) {
if isDeletedOrExpired(e.meta, e.ExpiresAt) {
return nil, ErrKeyNotFound
}
// Fulfill from cache.
item.meta = e.meta
item.val = e.Value
item.userMeta = e.UserMeta
item.key = key
item.status = prefetched
item.version = txn.readTs
item.expiresAt = e.ExpiresAt
// We probably don't need to set db on item here.
return item, nil
}
// Only track reads if this is update txn. No need to track read if txn serviced it
// internally.
txn.addReadKey(key)
}
seek := y.KeyWithTs(key, txn.readTs)
vs, err := txn.db.get(seek)
if err != nil {
return nil, errors.Wrapf(err, "DB::Get key: %q", key)
}
if vs.Value == nil && vs.Meta == 0 {
return nil, ErrKeyNotFound
}
if isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {
return nil, ErrKeyNotFound
}
item.key = key
item.version = vs.Version
item.meta = vs.Meta
item.userMeta = vs.UserMeta
item.db = txn.db
item.vptr = vs.Value // TODO: Do we need to copy this over?
item.txn = txn
item.expiresAt = vs.ExpiresAt
return item, nil
}
|
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L82-L87
|
func BearerAuth(token string) ClientParam {
return func(c *Client) error {
c.auth = &bearerAuth{token: token}
return nil
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/slack/client.go#L53-L58
|
func NewClient(tokenGenerator func() []byte) *Client {
return &Client{
logger: logrus.WithField("client", "slack"),
tokenGenerator: tokenGenerator,
}
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/bit_crush.go#L17-L24
|
func BitCrush(buf *audio.FloatBuffer, factor float64) {
stepSize := crusherStepSize * factor
for i := 0; i < len(buf.Data); i++ {
frac, exp := math.Frexp(buf.Data[i])
frac = signum(frac) * math.Floor(math.Abs(frac)/stepSize+0.5) * stepSize
buf.Data[i] = math.Ldexp(frac, exp)
}
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L2287-L2292
|
func (o *ListInt32Option) Set(value string) error {
val := Int32Option{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L10206-L10213
|
func (r *RunnableBinding) Locator(api *API) *RunnableBindingLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.RunnableBindingLocator(l["href"])
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L219-L223
|
func (v EventContextDestroyed) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1662-L1666
|
func (v HAR) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar9(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L21-L24
|
func (now *Now) BeginningOfDay() time.Time {
y, m, d := now.Date()
return time.Date(y, m, d, 0, 0, 0, 0, now.Time.Location())
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L279-L307
|
func cephRBDSnapshotProtect(clusterName string, poolName string,
volumeName string, volumeType string, snapshotName string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"snap",
"protect",
"--snap", snapshotName,
fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
waitStatus := exitError.Sys().(syscall.WaitStatus)
if waitStatus.ExitStatus() == 16 {
// EBUSY (snapshot already protected)
return nil
}
}
}
return err
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4763-L4766
|
func (e LedgerUpgradeType) ValidEnum(v int32) bool {
_, ok := ledgerUpgradeTypeMap[v]
return ok
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context.go#L98-L102
|
func newIncomingContext(call IncomingCall, timeout time.Duration) (context.Context, context.CancelFunc) {
return NewContextBuilder(timeout).
setIncomingCall(call).
Build()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L227-L231
|
func (v *SetShowPaintRectsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay2(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L6517-L6521
|
func (v *EventRequestServedFromCache) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork51(&r, v)
return r.Error()
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L59-L64
|
func (c *Client) ListServers(dcid string) (*Servers, error) {
url := serverColPath(dcid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Servers{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L2270-L2274
|
func (v Content) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/newapp/web/web.go#L15-L58
|
func New(opts *Options) (*genny.Group, error) {
if err := opts.Validate(); err != nil {
return nil, err
}
gg, err := core.New(opts.Options)
if err != nil {
return gg, err
}
g := genny.New()
g.Transformer(genny.Dot())
data := map[string]interface{}{
"opts": opts,
}
helpers := template.FuncMap{}
t := gogen.TemplateTransformer(data, helpers)
g.Transformer(t)
g.Box(packr.New("buffalo:genny:newapp:web", "../web/templates"))
gg.Add(g)
if opts.Webpack != nil {
// add the webpack generator
g, err = webpack.New(opts.Webpack)
if err != nil {
return gg, err
}
gg.Add(g)
}
if opts.Standard != nil {
// add the standard generator
g, err = standard.New(opts.Standard)
if err != nil {
return gg, err
}
gg.Add(g)
}
return gg, nil
}
|
https://github.com/marcuswestin/go-errs/blob/b09b17aacd5a8213690bc30f9ccfe7400be7b380/errs.go#L110-L112
|
func Format(info Info, format string, argv ...interface{}) Err {
return newErr(debug.Stack(), fmt.Errorf(format, argv...), false, info, nil)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/greenhouse/diskcache/cache.go#L60-L62
|
func (c *Cache) PathToKey(key string) string {
return strings.TrimPrefix(key, c.diskRoot+string(os.PathSeparator))
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/agouti.go#L82-L95
|
func Selendroid(jarFile string, options ...Option) *WebDriver {
absJARPath, err := filepath.Abs(jarFile)
if err != nil {
return nil
}
command := []string{
"java",
"-jar", absJARPath,
"-port", "{{.Port}}",
}
options = append([]Option{Timeout(90), Browser("android")}, options...)
return NewWebDriver("http://{{.Address}}/wd/hub", command, options...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L457-L461
|
func (v *RemoteLocation) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget4(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1655-L1659
|
func (v *SetExtraHTTPHeadersParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork11(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L732-L826
|
func (w *watchGrpcStream) serveSubstream(ws *watcherStream, resumec chan struct{}) {
if ws.closing {
panic("created substream goroutine but substream is closing")
}
// nextRev is the minimum expected next revision
nextRev := ws.initReq.rev
resuming := false
defer func() {
if !resuming {
ws.closing = true
}
close(ws.donec)
if !resuming {
w.closingc <- ws
}
w.wg.Done()
}()
emptyWr := &WatchResponse{}
for {
curWr := emptyWr
outc := ws.outc
if len(ws.buf) > 0 {
curWr = ws.buf[0]
} else {
outc = nil
}
select {
case outc <- *curWr:
if ws.buf[0].Err() != nil {
return
}
ws.buf[0] = nil
ws.buf = ws.buf[1:]
case wr, ok := <-ws.recvc:
if !ok {
// shutdown from closeSubstream
return
}
if wr.Created {
if ws.initReq.retc != nil {
ws.initReq.retc <- ws.outc
// to prevent next write from taking the slot in buffered channel
// and posting duplicate create events
ws.initReq.retc = nil
// send first creation event only if requested
if ws.initReq.createdNotify {
ws.outc <- *wr
}
// once the watch channel is returned, a current revision
// watch must resume at the store revision. This is necessary
// for the following case to work as expected:
// wch := m1.Watch("a")
// m2.Put("a", "b")
// <-wch
// If the revision is only bound on the first observed event,
// if wch is disconnected before the Put is issued, then reconnects
// after it is committed, it'll miss the Put.
if ws.initReq.rev == 0 {
nextRev = wr.Header.Revision
}
}
} else {
// current progress of watch; <= store revision
nextRev = wr.Header.Revision
}
if len(wr.Events) > 0 {
nextRev = wr.Events[len(wr.Events)-1].Kv.ModRevision + 1
}
ws.initReq.rev = nextRev
// created event is already sent above,
// watcher should not post duplicate events
if wr.Created {
continue
}
// TODO pause channel if buffer gets too large
ws.buf = append(ws.buf, wr)
case <-w.ctx.Done():
return
case <-ws.initReq.ctx.Done():
return
case <-resumec:
resuming = true
return
}
}
// lazily send cancel message if events on missing id
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1256-L1258
|
func (p *StopScreencastParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStopScreencast, nil, nil)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L769-L794
|
func (c *Client) ListOrgMembers(org, role string) ([]TeamMember, error) {
c.log("ListOrgMembers", org, role)
if c.fake {
return nil, nil
}
path := fmt.Sprintf("/orgs/%s/members", org)
var teamMembers []TeamMember
err := c.readPaginatedResultsWithValues(
path,
url.Values{
"per_page": []string{"100"},
"role": []string{role},
},
acceptNone,
func() interface{} {
return &[]TeamMember{}
},
func(obj interface{}) {
teamMembers = append(teamMembers, *(obj.(*[]TeamMember))...)
},
)
if err != nil {
return nil, err
}
return teamMembers, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L441-L450
|
func (c *JobConfig) GetPresubmit(repo, jobName string) *Presubmit {
presubmits := c.AllPresubmits([]string{repo})
for i := range presubmits {
ps := presubmits[i]
if ps.Name == jobName {
return &ps
}
}
return nil
}
|
https://github.com/mastahyeti/fakeca/blob/c1d84b1b473e99212130da7b311dd0605de5ed0a/configuration.go#L222-L226
|
func OCSPServer(value ...string) Option {
return func(c *configuration) {
c.ocspServer = append(c.ocspServer, value...)
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L649-L657
|
func newPRMExactRepository(dockerRepository string) (*prmExactRepository, error) {
if _, err := reference.ParseNormalizedNamed(dockerRepository); err != nil {
return nil, InvalidPolicyFormatError(fmt.Sprintf("Invalid format of dockerRepository %s: %s", dockerRepository, err.Error()))
}
return &prmExactRepository{
prmCommon: prmCommon{Type: prmTypeExactRepository},
DockerRepository: dockerRepository,
}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2201-L2227
|
func (c *Client) ListTeamRepos(id int) ([]Repo, error) {
c.log("ListTeamRepos", id)
if c.fake {
return nil, nil
}
path := fmt.Sprintf("/teams/%d/repos", id)
var repos []Repo
err := c.readPaginatedResultsWithValues(
path,
url.Values{
"per_page": []string{"100"},
},
// This accept header enables the nested teams preview.
// https://developer.github.com/changes/2017-08-30-preview-nested-teams/
"application/vnd.github.hellcat-preview+json",
func() interface{} {
return &[]Repo{}
},
func(obj interface{}) {
repos = append(repos, *(obj.(*[]Repo))...)
},
)
if err != nil {
return nil, err
}
return repos, nil
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L75-L80
|
func (c *Client) setAllowLargeResults(shouldAllow bool, tempTableName string, flattenResults bool) error {
c.allowLargeResults = shouldAllow
c.tempTableName = tempTableName
c.flattenResults = flattenResults
return nil
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L11-L28
|
func New() *MockTracer {
t := &MockTracer{
finishedSpans: []*MockSpan{},
injectors: make(map[interface{}]Injector),
extractors: make(map[interface{}]Extractor),
}
// register default injectors/extractors
textPropagator := new(TextMapPropagator)
t.RegisterInjector(opentracing.TextMap, textPropagator)
t.RegisterExtractor(opentracing.TextMap, textPropagator)
httpPropagator := &TextMapPropagator{HTTPHeaders: true}
t.RegisterInjector(opentracing.HTTPHeaders, httpPropagator)
t.RegisterExtractor(opentracing.HTTPHeaders, httpPropagator)
return t
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/servicemanager/mock/servicemanager_mock.go#L33-L54
|
func SetMockService(m *MockService) {
m.Cache = &cache.MockAppCacheService{}
m.Plan = &app.MockPlanService{}
m.Platform = &app.MockPlatformService{}
m.PlatformImage = &image.MockPlatformImageService{}
m.Team = &auth.MockTeamService{}
m.UserQuota = "a.MockQuotaService{}
m.AppQuota = "a.MockQuotaService{}
m.Cluster = &provision.MockClusterService{}
m.ServiceBroker = &service.MockServiceBrokerService{}
m.ServiceBrokerCatalogCache = &service.MockServiceBrokerCatalogCacheService{}
servicemanager.AppCache = m.Cache
servicemanager.Plan = m.Plan
servicemanager.Platform = m.Platform
servicemanager.PlatformImage = m.PlatformImage
servicemanager.Team = m.Team
servicemanager.UserQuota = m.UserQuota
servicemanager.AppQuota = m.AppQuota
servicemanager.Cluster = m.Cluster
servicemanager.ServiceBroker = m.ServiceBroker
servicemanager.ServiceBrokerCatalogCache = m.ServiceBrokerCatalogCache
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/encode.go#L620-L648
|
func (e Encoder) EncodeArray(n int, f func(Encoder) error) (err error) {
if e.key {
if e.key, err = false, e.Emitter.EmitMapValue(); err != nil {
return
}
}
if err = e.Emitter.EmitArrayBegin(n); err != nil {
return
}
encodeArray:
for i := 0; n < 0 || i < n; i++ {
if i != 0 {
if e.Emitter.EmitArrayNext(); err != nil {
return
}
}
switch err = f(e); err {
case nil:
case End:
break encodeArray
default:
return
}
}
return e.Emitter.EmitArrayEnd()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.