_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/broker.go#L415-L417
|
func (b *brokerClient) UnbindUnit(instance *ServiceInstance, app bind.App, unit bind.Unit) error {
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/compactor.go#L60-L75
|
func New(
lg *zap.Logger,
mode string,
retention time.Duration,
rg RevGetter,
c Compactable,
) (Compactor, error) {
switch mode {
case ModePeriodic:
return newPeriodic(lg, clockwork.NewRealClock(), retention, rg, c), nil
case ModeRevision:
return newRevision(lg, clockwork.NewRealClock(), int64(retention), rg, c), nil
default:
return nil, fmt.Errorf("unsupported compaction mode %s", mode)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L1846-L1894
|
func (a *apiServer) setGroupsForUserInternal(ctx context.Context, subject string, groups []string) error {
_, err := col.NewSTM(ctx, a.env.GetEtcdClient(), func(stm col.STM) error {
members := a.members.ReadWrite(stm)
// Get groups to remove/add user from/to
var removeGroups authclient.Groups
addGroups := addToSet(nil, groups...)
if err := members.Get(subject, &removeGroups); err == nil {
for _, group := range groups {
if removeGroups.Groups[group] {
removeGroups.Groups = removeFromSet(removeGroups.Groups, group)
addGroups = removeFromSet(addGroups, group)
}
}
}
// Set groups for user
if err := members.Put(subject, &authclient.Groups{
Groups: addToSet(nil, groups...),
}); err != nil {
return err
}
// Remove user from previous groups
groups := a.groups.ReadWrite(stm)
var membersProto authclient.Users
for group := range removeGroups.Groups {
if err := groups.Upsert(group, &membersProto, func() error {
membersProto.Usernames = removeFromSet(membersProto.Usernames, subject)
return nil
}); err != nil {
return err
}
}
// Add user to new groups
for group := range addGroups {
if err := groups.Upsert(group, &membersProto, func() error {
membersProto.Usernames = addToSet(membersProto.Usernames, subject)
return nil
}); err != nil {
return err
}
}
return nil
})
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L8355-L8359
|
func (v *ClearBrowserCacheParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork65(&r, v)
return r.Error()
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L372-L377
|
func (l *InclusiveRanges) numRanges() int {
if l.blocks == nil {
return 0
}
return len(l.blocks)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L8116-L8241
|
func (c *containerLXC) createDiskDevice(name string, m types.Device) (string, error) {
// source paths
relativeDestPath := strings.TrimPrefix(m["path"], "/")
devName := fmt.Sprintf("disk.%s.%s", strings.Replace(name, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
srcPath := shared.HostPath(m["source"])
// Check if read-only
isOptional := shared.IsTrue(m["optional"])
isReadOnly := shared.IsTrue(m["readonly"])
isRecursive := shared.IsTrue(m["recursive"])
isFile := false
if m["pool"] == "" {
isFile = !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath)
} else {
// Deal with mounting storage volumes created via the storage
// api. Extract the name of the storage volume that we are
// supposed to attach. We assume that the only syntactically
// valid ways of specifying a storage volume are:
// - <volume_name>
// - <type>/<volume_name>
// Currently, <type> must either be empty or "custom". We do not
// yet support container mounts.
if filepath.IsAbs(m["source"]) {
return "", fmt.Errorf("When the \"pool\" property is set \"source\" must specify the name of a volume, not a path")
}
volumeTypeName := ""
volumeName := filepath.Clean(m["source"])
slash := strings.Index(volumeName, "/")
if (slash > 0) && (len(volumeName) > slash) {
// Extract volume name.
volumeName = m["source"][(slash + 1):]
// Extract volume type.
volumeTypeName = m["source"][:slash]
}
switch volumeTypeName {
case storagePoolVolumeTypeNameContainer:
return "", fmt.Errorf("Using container storage volumes is not supported")
case "":
// We simply received the name of a storage volume.
volumeTypeName = storagePoolVolumeTypeNameCustom
fallthrough
case storagePoolVolumeTypeNameCustom:
srcPath = shared.VarPath("storage-pools", m["pool"], volumeTypeName, volumeName)
case storagePoolVolumeTypeNameImage:
return "", fmt.Errorf("Using image storage volumes is not supported")
default:
return "", fmt.Errorf("Unknown storage type prefix \"%s\" found", volumeTypeName)
}
// Initialize a new storage interface and check if the
// pool/volume is mounted. If it is not, mount it.
volumeType, _ := storagePoolVolumeTypeNameToType(volumeTypeName)
s, err := storagePoolVolumeAttachInit(c.state, m["pool"], volumeName, volumeType, c)
if err != nil && !isOptional {
return "", fmt.Errorf("Failed to initialize storage volume \"%s\" of type \"%s\" on storage pool \"%s\": %s",
volumeName,
volumeTypeName,
m["pool"], err)
} else if err == nil {
_, err = s.StoragePoolVolumeMount()
if err != nil {
msg := fmt.Sprintf("Could not mount storage volume \"%s\" of type \"%s\" on storage pool \"%s\": %s.",
volumeName,
volumeTypeName,
m["pool"], err)
if !isOptional {
logger.Errorf(msg)
return "", err
}
logger.Warnf(msg)
}
}
}
// Check if the source exists
if !shared.PathExists(srcPath) {
if isOptional {
return "", nil
}
return "", fmt.Errorf("Source path %s doesn't exist for device %s", srcPath, name)
}
// Create the devices directory if missing
if !shared.PathExists(c.DevicesPath()) {
err := os.Mkdir(c.DevicesPath(), 0711)
if err != nil {
return "", err
}
}
// Clean any existing entry
if shared.PathExists(devPath) {
err := os.Remove(devPath)
if err != nil {
return "", err
}
}
// Create the mount point
if isFile {
f, err := os.Create(devPath)
if err != nil {
return "", err
}
f.Close()
} else {
err := os.Mkdir(devPath, 0700)
if err != nil {
return "", err
}
}
// Mount the fs
err := deviceMountDisk(srcPath, devPath, isReadOnly, isRecursive, m["propagation"])
if err != nil {
return "", err
}
return devPath, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdmain/grpc_proxy.go#L98-L106
|
func newGRPCProxyCommand() *cobra.Command {
lpc := &cobra.Command{
Use: "grpc-proxy <subcommand>",
Short: "grpc-proxy related command",
}
lpc.AddCommand(newGRPCProxyStartCommand())
return lpc
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L486-L490
|
func (v *GetResponseBodyParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoFetch5(&r, v)
return r.Error()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3305-L3308
|
func (e ChangeTrustResultCode) ValidEnum(v int32) bool {
_, ok := changeTrustResultCodeMap[v]
return ok
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L361-L368
|
func (p *Peer) getConn(i int) *Connection {
inboundLen := len(p.inboundConnections)
if i < inboundLen {
return p.inboundConnections[i]
}
return p.outboundConnections[i-inboundLen]
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L217-L239
|
func (n *node) printDebug(level int) {
level++
// *splat branch
if n.SplatChild != nil {
printFPadding(level, "*splat\n")
n.SplatChild.printDebug(level)
}
// :param branch
if n.ParamChild != nil {
printFPadding(level, ":param\n")
n.ParamChild.printDebug(level)
}
// #param branch
if n.RelaxedChild != nil {
printFPadding(level, "#relaxed\n")
n.RelaxedChild.printDebug(level)
}
// main branch
for key, node := range n.Children {
printFPadding(level, "\"%s\"\n", key)
node.printDebug(level)
}
}
|
https://github.com/qor/action_bar/blob/136e5e2c5b8c50976dc39edddf523fcaab0a73b8/action_bar.go#L46-L68
|
func (bar *ActionBar) Render(w http.ResponseWriter, r *http.Request) template.HTML {
var (
actions, inlineActions []ActionInterface
context = bar.Admin.NewContext(w, r)
)
for _, action := range bar.actions {
if action.InlineAction() {
inlineActions = append(inlineActions, action)
} else {
actions = append(actions, action)
}
}
context.Context.CurrentUser = bar.Admin.Auth.GetCurrentUser(context)
result := map[string]interface{}{
"EditMode": bar.EditMode(w, r),
"Auth": bar.Admin.Auth,
"CurrentUser": context.Context.CurrentUser,
"Actions": actions,
"InlineActions": inlineActions,
"RouterPrefix": bar.Admin.GetRouter().Prefix,
}
return context.Render("action_bar/action_bar", result)
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/api.go#L145-L153
|
func (api *TelegramBotAPI) Close() {
select {
case <-api.closed:
return
default:
}
close(api.closed)
api.wg.Wait()
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L96-L98
|
func (s *ConcoursePipeline) AddBoshDeploymentResource(name string, source map[string]interface{}) {
s.AddResource(name, BoshDeploymentResourceName, source)
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ed25519.go#L112-L114
|
func (k *Ed25519PublicKey) Verify(data []byte, sig []byte) (bool, error) {
return ed25519.Verify(k.k, data, sig), nil
}
|
https://github.com/OneOfOne/xxhash/blob/c1e3185f167680b62832a0a11938a04b1ab265fc/xxhash.go#L56-L62
|
func NewS32(seed uint32) (xx *XXHash32) {
xx = &XXHash32{
seed: seed,
}
xx.Reset()
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_certificates.go#L71-L83
|
func (r *ProtocolLXD) UpdateCertificate(fingerprint string, certificate api.CertificatePut, ETag string) error {
if !r.HasExtension("certificate_update") {
return fmt.Errorf("The server is missing the required \"certificate_update\" API extension")
}
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/certificates/%s", url.QueryEscape(fingerprint)), certificate, ETag)
if err != nil {
return err
}
return nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L884-L909
|
func (t *Iterator) Facets() ([][]FacetResult, error) {
t.fetchMore()
if t.err != nil && t.err != Done {
return nil, t.err
}
var facets [][]FacetResult
for _, f := range t.facetRes {
fres := make([]FacetResult, 0, len(f.Value))
for _, v := range f.Value {
ref := v.Refinement
facet := FacetResult{
Facet: Facet{Name: ref.GetName()},
Count: int(v.GetCount()),
}
if ref.Value != nil {
facet.Value = Atom(*ref.Value)
} else {
facet.Value = protoToRange(ref.Range)
}
fres = append(fres, facet)
}
facets = append(facets, fres)
}
return facets, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/etcd_config.go#L110-L174
|
func (e *Etcd) EmbedConfig() (cfg *embed.Config, err error) {
var lcURLs types.URLs
lcURLs, err = types.NewURLs(e.ListenClientURLs)
if err != nil {
return nil, err
}
var acURLs types.URLs
acURLs, err = types.NewURLs(e.AdvertiseClientURLs)
if err != nil {
return nil, err
}
var lpURLs types.URLs
lpURLs, err = types.NewURLs(e.ListenPeerURLs)
if err != nil {
return nil, err
}
var apURLs types.URLs
apURLs, err = types.NewURLs(e.AdvertisePeerURLs)
if err != nil {
return nil, err
}
cfg = embed.NewConfig()
cfg.Name = e.Name
cfg.Dir = e.DataDir
cfg.WalDir = e.WALDir
cfg.TickMs = uint(e.HeartbeatIntervalMs)
cfg.ElectionMs = uint(e.ElectionTimeoutMs)
cfg.LCUrls = lcURLs
cfg.ACUrls = acURLs
cfg.ClientAutoTLS = e.ClientAutoTLS
cfg.ClientTLSInfo = transport.TLSInfo{
ClientCertAuth: e.ClientCertAuth,
CertFile: e.ClientCertFile,
KeyFile: e.ClientKeyFile,
TrustedCAFile: e.ClientTrustedCAFile,
}
cfg.LPUrls = lpURLs
cfg.APUrls = apURLs
cfg.PeerAutoTLS = e.PeerAutoTLS
cfg.PeerTLSInfo = transport.TLSInfo{
ClientCertAuth: e.PeerClientCertAuth,
CertFile: e.PeerCertFile,
KeyFile: e.PeerKeyFile,
TrustedCAFile: e.PeerTrustedCAFile,
}
cfg.InitialCluster = e.InitialCluster
cfg.ClusterState = e.InitialClusterState
cfg.InitialClusterToken = e.InitialClusterToken
cfg.SnapshotCount = uint64(e.SnapshotCount)
cfg.QuotaBackendBytes = e.QuotaBackendBytes
cfg.PreVote = e.PreVote
cfg.ExperimentalInitialCorruptCheck = e.InitialCorruptCheck
cfg.Logger = e.Logger
cfg.LogOutputs = e.LogOutputs
cfg.Debug = e.Debug
return cfg, nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-encode.go#L25-L165
|
func (cdc *Codec) encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (err error) {
if rv.Kind() == reflect.Ptr {
panic("not allowed to be called with a reflect.Ptr")
}
if !rv.IsValid() {
panic("not allowed to be called with invalid / zero Value")
}
if printLog {
spew.Printf("(E) encodeReflectBinary(info: %v, rv: %#v (%v), fopts: %v)\n",
info, rv.Interface(), rv.Type(), fopts)
defer func() {
fmt.Printf("(E) -> err: %v\n", err)
}()
}
// Handle override if rv implements json.Marshaler.
if info.IsAminoMarshaler {
// First, encode rv into repr instance.
var rrv, rinfo = reflect.Value{}, (*TypeInfo)(nil)
rrv, err = toReprObject(rv)
if err != nil {
return
}
rinfo, err = cdc.getTypeInfo_wlock(info.AminoMarshalReprType)
if err != nil {
return
}
// Then, encode the repr instance.
err = cdc.encodeReflectBinary(w, rinfo, rrv, fopts, bare)
return
}
switch info.Type.Kind() {
//----------------------------------------
// Complex
case reflect.Interface:
err = cdc.encodeReflectBinaryInterface(w, info, rv, fopts, bare)
case reflect.Array:
if info.Type.Elem().Kind() == reflect.Uint8 {
err = cdc.encodeReflectBinaryByteArray(w, info, rv, fopts)
} else {
err = cdc.encodeReflectBinaryList(w, info, rv, fopts, bare)
}
case reflect.Slice:
if info.Type.Elem().Kind() == reflect.Uint8 {
err = cdc.encodeReflectBinaryByteSlice(w, info, rv, fopts)
} else {
err = cdc.encodeReflectBinaryList(w, info, rv, fopts, bare)
}
case reflect.Struct:
err = cdc.encodeReflectBinaryStruct(w, info, rv, fopts, bare)
//----------------------------------------
// Signed
case reflect.Int64:
if fopts.BinFixed64 {
err = EncodeInt64(w, rv.Int())
} else {
err = EncodeUvarint(w, uint64(rv.Int()))
}
case reflect.Int32:
if fopts.BinFixed32 {
err = EncodeInt32(w, int32(rv.Int()))
} else {
err = EncodeUvarint(w, uint64(rv.Int()))
}
case reflect.Int16:
err = EncodeInt16(w, int16(rv.Int()))
case reflect.Int8:
err = EncodeInt8(w, int8(rv.Int()))
case reflect.Int:
err = EncodeUvarint(w, uint64(rv.Int()))
//----------------------------------------
// Unsigned
case reflect.Uint64:
if fopts.BinFixed64 {
err = EncodeUint64(w, rv.Uint())
} else {
err = EncodeUvarint(w, rv.Uint())
}
case reflect.Uint32:
if fopts.BinFixed32 {
err = EncodeUint32(w, uint32(rv.Uint()))
} else {
err = EncodeUvarint(w, rv.Uint())
}
case reflect.Uint16:
err = EncodeUint16(w, uint16(rv.Uint()))
case reflect.Uint8:
err = EncodeUint8(w, uint8(rv.Uint()))
case reflect.Uint:
err = EncodeUvarint(w, rv.Uint())
//----------------------------------------
// Misc
case reflect.Bool:
err = EncodeBool(w, rv.Bool())
case reflect.Float64:
if !fopts.Unsafe {
err = errors.New("Amino float* support requires `amino:\"unsafe\"`.")
return
}
err = EncodeFloat64(w, rv.Float())
case reflect.Float32:
if !fopts.Unsafe {
err = errors.New("Amino float* support requires `amino:\"unsafe\"`.")
return
}
err = EncodeFloat32(w, float32(rv.Float()))
case reflect.String:
err = EncodeString(w, rv.String())
//----------------------------------------
// Default
default:
panic(fmt.Sprintf("unsupported type %v", info.Type.Kind()))
}
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes_linux.go#L227-L250
|
func parsePREFSRC(m *syscall.NetlinkMessage) (host string, oif uint32, err error) {
var attrs []syscall.NetlinkRouteAttr
attrs, err = syscall.ParseNetlinkRouteAttr(m)
if err != nil {
return "", 0, err
}
for _, attr := range attrs {
if attr.Attr.Type == syscall.RTA_PREFSRC {
host = net.IP(attr.Value).String()
}
if attr.Attr.Type == syscall.RTA_OIF {
oif = cpuutil.ByteOrder().Uint32(attr.Value)
}
if host != "" && oif != uint32(0) {
break
}
}
if oif == 0 {
err = errNoDefaultRoute
}
return host, oif, err
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L116-L118
|
func OutgoingContextWithServiceInfo(ctx context.Context, serviceName, serviceVersion, netAddress string) context.Context {
return outgoingContextWithMergedMetadata(ctx, "service-name", serviceName, "service-version", serviceVersion, "net-address", netAddress)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L830-L832
|
func (p *SetMaxCallStackSizeToCaptureParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetMaxCallStackSizeToCapture, p, nil)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/trigger/trigger.go#L198-L210
|
func runAndSkipJobs(c Client, pr *github.PullRequest, requestedJobs []config.Presubmit, skippedJobs []config.Presubmit, eventGUID string, elideSkippedContexts bool) error {
if err := validateContextOverlap(requestedJobs, skippedJobs); err != nil {
c.Logger.WithError(err).Warn("Could not run or skip requested jobs, overlapping contexts.")
return err
}
runErr := RunRequested(c, pr, requestedJobs, eventGUID)
var skipErr error
if !elideSkippedContexts {
skipErr = skipRequested(c, pr, skippedJobs)
}
return errorutil.NewAggregate(runErr, skipErr)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L165-L169
|
func (v *Timings) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar(&r, v)
return r.Error()
}
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L239-L282
|
func reducedDuplexRow1(state []uint64, rowIn []uint64, rowOut []uint64, nCols int) {
ptrIn := 0
ptrOut := (nCols - 1) * blockLenInt64
for i := 0; i < nCols; i++ {
ptrWordIn := rowIn[ptrIn:] //In Lyra2: pointer to prev
ptrWordOut := rowOut[ptrOut:] //In Lyra2: pointer to row
//Absorbing "M[prev][col]"
state[0] ^= (ptrWordIn[0])
state[1] ^= (ptrWordIn[1])
state[2] ^= (ptrWordIn[2])
state[3] ^= (ptrWordIn[3])
state[4] ^= (ptrWordIn[4])
state[5] ^= (ptrWordIn[5])
state[6] ^= (ptrWordIn[6])
state[7] ^= (ptrWordIn[7])
state[8] ^= (ptrWordIn[8])
state[9] ^= (ptrWordIn[9])
state[10] ^= (ptrWordIn[10])
state[11] ^= (ptrWordIn[11])
//Applies the reduced-round transformation f to the sponge's state
reducedBlake2bLyra(state)
//M[row][C-1-col] = M[prev][col] XOR rand
ptrWordOut[0] = ptrWordIn[0] ^ state[0]
ptrWordOut[1] = ptrWordIn[1] ^ state[1]
ptrWordOut[2] = ptrWordIn[2] ^ state[2]
ptrWordOut[3] = ptrWordIn[3] ^ state[3]
ptrWordOut[4] = ptrWordIn[4] ^ state[4]
ptrWordOut[5] = ptrWordIn[5] ^ state[5]
ptrWordOut[6] = ptrWordIn[6] ^ state[6]
ptrWordOut[7] = ptrWordIn[7] ^ state[7]
ptrWordOut[8] = ptrWordIn[8] ^ state[8]
ptrWordOut[9] = ptrWordIn[9] ^ state[9]
ptrWordOut[10] = ptrWordIn[10] ^ state[10]
ptrWordOut[11] = ptrWordIn[11] ^ state[11]
//Input: next column (i.e., next block in sequence)
ptrIn += blockLenInt64
//Output: goes to previous column
ptrOut -= blockLenInt64
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L181-L194
|
func (p *ProgressRenderer) UpdateOp(op api.Operation) {
if op.Metadata == nil {
return
}
for key, value := range op.Metadata {
if !strings.HasSuffix(key, "_progress") {
continue
}
p.Update(value.(string))
break
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/sql/model.go#L42-L52
|
func (issue *Issue) FindLabels(regex *regexp.Regexp) []Label {
labels := []Label{}
for _, label := range issue.Labels {
if regex.MatchString(label.Name) {
labels = append(labels, label)
}
}
return labels
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L458-L462
|
func (v RequestDataReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/autoscale.go#L167-L191
|
func autoScaleRunHandler(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
if !permission.Check(t, permission.PermNodeAutoscaleUpdateRun) {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypePool},
Kind: permission.PermNodeAutoscaleUpdateRun,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
DisableLock: true,
Allowed: event.Allowed(permission.PermPoolReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
w.Header().Set("Content-Type", "application/x-json-stream")
w.WriteHeader(http.StatusOK)
keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 15*time.Second, "")
defer keepAliveWriter.Stop()
writer := &tsuruIo.SimpleJsonMessageEncoderWriter{
Encoder: json.NewEncoder(keepAliveWriter),
}
return autoscale.RunOnce(writer)
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/log/panic.go#L28-L53
|
func Panic(h http.Handler, opts ...Option) http.Handler {
o := options{logger: handler.ErrLogger(), dateFormat: PanicDateFormat}
o.apply(opts)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
stack := debug.Stack()
timestamp := time.Now().Format(o.dateFormat)
message := fmt.Sprintf("%s - %s\n%s\n", timestamp, rec, stack)
o.logger.Print(message)
w.WriteHeader(http.StatusInternalServerError)
if !o.showStack {
message = "Internal Server Error"
}
w.Write([]byte(message))
}
}()
h.ServeHTTP(w, r)
})
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/pr_history.go#L186-L201
|
func parsePullURL(u *url.URL) (org, repo string, pr int, err error) {
var prStr string
vals := u.Query()
if org = vals.Get("org"); org == "" {
return "", "", 0, fmt.Errorf("no value provided for org")
}
if repo = vals.Get("repo"); repo == "" {
return "", "", 0, fmt.Errorf("no value provided for repo")
}
prStr = vals.Get("pr")
pr, err = strconv.Atoi(prStr)
if err != nil {
return "", "", 0, fmt.Errorf("invalid PR number %q: %v", prStr, err)
}
return org, repo, pr, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L213-L216
|
func (p StartSamplingParams) WithSamplingInterval(samplingInterval float64) *StartSamplingParams {
p.SamplingInterval = samplingInterval
return &p
}
|
https://github.com/kjk/lzmadec/blob/4c61f00ce86f6f11ed9630fa16b771889b08147b/lzmadec.go#L271-L282
|
func (a *Archive) ExtractToWriter(dst io.Writer, name string) error {
r, err := a.GetFileReader(name)
if err != nil {
return err
}
_, err = io.Copy(dst, r)
err2 := r.Close()
if err != nil {
return err
}
return err2
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L86-L88
|
func (s *ConcoursePipeline) AddGithubResource(name string, source map[string]interface{}) {
s.AddResource(name, GithubResourceName, source)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1621-L1625
|
func (v *ClearGeolocationOverrideParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation18(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L269-L278
|
func (r *reqResReader) failed(err error) error {
r.log.Debugf("reader failed: %v existing err: %v", err, r.err)
if r.err != nil {
return r.err
}
r.mex.shutdown()
r.err = err
return r.err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L753-L757
|
func (v *SetReturnValueParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger7(&r, v)
return r.Error()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L2081-L2083
|
func (api *API) PatternLocator(href string) *PatternLocator {
return &PatternLocator{Href(href), api}
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dwarf.go#L278-L330
|
func runtimeName(dt dwarf.Type) string {
switch x := dt.(type) {
case *dwarf.PtrType:
if _, ok := x.Type.(*dwarf.VoidType); ok {
return "unsafe.Pointer"
}
return "*" + runtimeName(x.Type)
case *dwarf.ArrayType:
return fmt.Sprintf("[%d]%s", x.Count, runtimeName(x.Type))
case *dwarf.StructType:
if !strings.HasPrefix(x.StructName, "struct {") {
// This is a named type, return that name.
return stripPackagePath(x.StructName)
}
// Figure out which fields have anonymous names.
var anon []bool
for _, f := range strings.Split(x.StructName[8:len(x.StructName)-1], ";") {
f = strings.TrimSpace(f)
anon = append(anon, !strings.Contains(f, " "))
// TODO: this isn't perfect. If the field type has a space in it,
// then this logic doesn't work. Need to search for keyword for
// field type, like "interface", "struct", ...
}
// Make sure anon is long enough. This probably never triggers.
for len(anon) < len(x.Field) {
anon = append(anon, false)
}
// Build runtime name from the DWARF fields.
s := "struct {"
first := true
for _, f := range x.Field {
if !first {
s += ";"
}
name := f.Name
if i := strings.Index(name, "."); i >= 0 {
name = name[i+1:]
}
if anon[0] {
s += fmt.Sprintf(" %s", runtimeName(f.Type))
} else {
s += fmt.Sprintf(" %s %s", name, runtimeName(f.Type))
}
first = false
anon = anon[1:]
}
s += " }"
return s
default:
return stripPackagePath(dt.String())
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5525-L5529
|
func (v EventWebSocketFrameReceived) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork43(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/shutdown/shutdown.go#L33-L67
|
func Do(ctx context.Context, w io.Writer) error {
lock.Lock()
defer lock.Unlock()
done := make(chan bool)
wg := sync.WaitGroup{}
for _, h := range registered {
wg.Add(1)
go func(h Shutdownable) {
defer wg.Done()
var name string
if _, ok := h.(fmt.Stringer); ok {
name = fmt.Sprintf("%s", h)
} else {
name = fmt.Sprintf("%T", h)
}
fmt.Fprintf(w, "[shutdown] running shutdown for %s...\n", name)
err := h.Shutdown(ctx)
if err != nil {
fmt.Fprintf(w, "[shutdown] running shutdown for %s. ERROED: %v", name, err)
return
}
fmt.Fprintf(w, "[shutdown] running shutdown for %s. DONE.\n", name)
}(h)
}
go func() {
wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
}
return nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L334-L337
|
func isPtrPkgDot(t ast.Expr, pkg, name string) bool {
ptr, ok := t.(*ast.StarExpr)
return ok && isPkgDot(ptr.X, pkg, name)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L519-L523
|
func (v *TakeResponseBodyForInterceptionAsStreamReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork3(&r, v)
return r.Error()
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L208-L215
|
func (s *Seekret) LoadObjects(st SourceType, source string, opt LoadOptions) error {
objectList, err := st.LoadObjects(source, opt)
if err != nil {
return err
}
s.objectList = append(s.objectList, objectList...)
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L206-L210
|
func (pc *Periodic) Pause() {
pc.mu.Lock()
pc.paused = true
pc.mu.Unlock()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/mechanism.go#L64-L85
|
func gpgUntrustedSignatureContents(untrustedSignature []byte) (untrustedContents []byte, shortKeyIdentifier string, err error) {
// This uses the Golang-native OpenPGP implementation instead of gpgme because we are not doing any cryptography.
md, err := openpgp.ReadMessage(bytes.NewReader(untrustedSignature), openpgp.EntityList{}, nil, nil)
if err != nil {
return nil, "", err
}
if !md.IsSigned {
return nil, "", errors.New("The input is not a signature")
}
content, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
// Coverage: An error during reading the body can happen only if
// 1) the message is encrypted, which is not our case (and we don’t give ReadMessage the key
// to decrypt the contents anyway), or
// 2) the message is signed AND we give ReadMessage a correspnding public key, which we don’t.
return nil, "", err
}
// Uppercase the key ID for minimal consistency with the gpgme-returned fingerprints
// (but note that key ID is a suffix of the fingerprint only for V4 keys, not V3)!
return content, strings.ToUpper(fmt.Sprintf("%016X", md.SignedByKeyId)), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/githuboauth.go#L45-L48
|
func (gac *GitHubOAuthConfig) InitGitHubOAuthConfig(cookie *sessions.CookieStore) {
gob.Register(&oauth2.Token{})
gac.CookieStore = cookie
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1746-L1750
|
func (v EventAttachedToTarget) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget19(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/history/history.go#L196-L205
|
func (h *History) AllRecords() map[string][]*Record {
h.Lock()
defer h.Unlock()
res := make(map[string][]*Record, len(h.logs))
for key, log := range h.logs {
res[key] = log.toSlice()
}
return res
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L369-L374
|
func (s *FakeCollection) FindAndModify(selector interface{}, update interface{}, result interface{}) (info *mgo.ChangeInfo, err error) {
if s.AssignResult != nil {
s.AssignResult(result, s.FakeResultFindAndModify)
}
return s.FakeChangeInfo, s.ErrFindAndModify
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L323-L330
|
func (d *Daemon) UnixSocket() string {
path := os.Getenv("LXD_SOCKET")
if path != "" {
return path
}
return filepath.Join(d.os.VarDir, "unix.socket")
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L1079-L1109
|
func (v *VM) SharedFolderState(index int) (string, string, int, error) {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
var (
folderName, folderHostPath *C.char
folderFlags *C.int
)
jobHandle = C.VixVM_GetSharedFolderState(v.handle, //vmHandle
C.int(index), //index
nil, //callbackProc
nil) //clientData
defer C.Vix_ReleaseHandle(jobHandle)
err = C.get_shared_folder(jobHandle, folderName, folderHostPath, folderFlags)
defer C.Vix_FreeBuffer(unsafe.Pointer(folderName))
defer C.Vix_FreeBuffer(unsafe.Pointer(folderHostPath))
if C.VIX_OK != err {
return "", "", 0, &Error{
Operation: "vm.SharedFolderState",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
C.Vix_ReleaseHandle(v.handle)
return C.GoString(folderName), C.GoString(folderHostPath), int(*folderFlags),
nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L448-L451
|
func (p GetDocumentParams) WithDepth(depth int64) *GetDocumentParams {
p.Depth = depth
return &p
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/encoder.go#L23-L25
|
func NewEncoder(w io.Writer) Encoder {
return versionOneEncoder{w, make([]byte, 9), bytes.NewBuffer(make([]byte, 0, 4096))}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L36-L38
|
func (p *AddInspectedHeapObjectParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandAddInspectedHeapObject, p, nil)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/github.go#L92-L111
|
func (o *GitHubOptions) GitHubClientWithLogFields(secretAgent *secret.Agent, dryRun bool, fields logrus.Fields) (client *github.Client, err error) {
var generator *func() []byte
if o.TokenPath == "" {
generatorFunc := func() []byte {
return []byte{}
}
generator = &generatorFunc
} else {
if secretAgent == nil {
return nil, fmt.Errorf("cannot store token from %q without a secret agent", o.TokenPath)
}
generatorFunc := secretAgent.GetTokenGenerator(o.TokenPath)
generator = &generatorFunc
}
if dryRun {
return github.NewDryRunClientWithFields(fields, *generator, o.graphqlEndpoint, o.endpoint.Strings()...), nil
}
return github.NewClientWithFields(fields, *generator, o.graphqlEndpoint, o.endpoint.Strings()...), nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry_interceptor.go#L277-L290
|
func isSafeRetry(lg *zap.Logger, err error, callOpts *options) bool {
if isContextError(err) {
return false
}
switch callOpts.retryPolicy {
case repeatable:
return isSafeRetryImmutableRPC(err)
case nonRepeatable:
return isSafeRetryMutableRPC(err)
default:
lg.Warn("unrecognized retry policy", zap.String("retryPolicy", callOpts.retryPolicy.String()))
return false
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L528-L532
|
func (c *Cluster) ContainerRemove(project, name string) error {
return c.Transaction(func(tx *ClusterTx) error {
return tx.ContainerDelete(project, name)
})
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/attrs.go#L65-L78
|
func (a *Attrs) SetAttr(key string, value interface{}) *Attrs {
a.attrsLock.Lock()
defer a.attrsLock.Unlock()
valVal := reflect.ValueOf(value)
switch valVal.Kind() {
case reflect.Func:
value = valVal.Type().String()
}
hash := getAttrHash(key)
a.attrs[hash] = value
return a
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/cache/cache.go#L95-L99
|
func (c *Cache) Describe(in chan<- *prometheus.Desc) {
c.hitsTotal.Describe(in)
c.refreshTotal.Describe(in)
c.missesTotal.Describe(in)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pfsdb/pfsdb.go#L40-L49
|
func PutFileRecords(etcdClient *etcd.Client, etcdPrefix string) col.Collection {
return col.NewCollection(
etcdClient,
path.Join(etcdPrefix, putFileRecordsPrefix),
nil,
&pfs.PutFileRecords{},
nil,
nil,
)
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L865-L867
|
func Warn(val ...interface{}) error {
return glg.out(WARN, blankFormat(len(val)), val...)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/manifest.go#L99-L105
|
func (m *Manifest) asChanges() []*pb.ManifestChange {
changes := make([]*pb.ManifestChange, 0, len(m.Tables))
for id, tm := range m.Tables {
changes = append(changes, newCreateChange(id, int(tm.Level), tm.Checksum))
}
return changes
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L128-L134
|
func (s *MockSpan) Logs() []MockLogRecord {
s.RLock()
defer s.RUnlock()
logs := make([]MockLogRecord, len(s.logs))
copy(logs, s.logs)
return logs
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L92-L97
|
func (p *Message) AsType(t interface{}) *Message {
fmt.Println("[DEBUG] setting Message decoding to type:", reflect.TypeOf(t))
p.Type = t
return p
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3524-L3538
|
func NewAccountMergeResult(code AccountMergeResultCode, value interface{}) (result AccountMergeResult, err error) {
result.Code = code
switch AccountMergeResultCode(code) {
case AccountMergeResultCodeAccountMergeSuccess:
tv, ok := value.(Int64)
if !ok {
err = fmt.Errorf("invalid value, must be Int64")
return
}
result.SourceAccountBalance = &tv
default:
// void
}
return
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tclogin/tclogin.go#L95-L99
|
func (login *Login) Ping() error {
cd := tcclient.Client(*login)
_, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil)
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L81-L175
|
func storagePoolsPost(d *Daemon, r *http.Request) Response {
storagePoolCreateLock.Lock()
defer storagePoolCreateLock.Unlock()
req := api.StoragePoolsPost{}
// Parse the request.
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return BadRequest(err)
}
// Sanity checks.
if req.Name == "" {
return BadRequest(fmt.Errorf("No name provided"))
}
if strings.Contains(req.Name, "/") {
return BadRequest(fmt.Errorf("Storage pool names may not contain slashes"))
}
if req.Driver == "" {
return BadRequest(fmt.Errorf("No driver provided"))
}
url := fmt.Sprintf("/%s/storage-pools/%s", version.APIVersion, req.Name)
response := SyncResponseLocation(true, nil, url)
if isClusterNotification(r) {
// This is an internal request which triggers the actual
// creation of the pool across all nodes, after they have been
// previously defined.
err = storagePoolValidate(req.Name, req.Driver, req.Config)
if err != nil {
return BadRequest(err)
}
err = doStoragePoolCreateInternal(
d.State(), req.Name, req.Description, req.Driver, req.Config, true)
if err != nil {
return SmartError(err)
}
return response
}
targetNode := queryParam(r, "target")
if targetNode == "" {
count, err := cluster.Count(d.State())
if err != nil {
return SmartError(err)
}
if count == 1 {
// No targetNode was specified and we're either a single-node
// cluster or not clustered at all, so create the storage
// pool immediately.
err = storagePoolCreateInternal(
d.State(), req.Name, req.Description, req.Driver, req.Config)
} else {
// No targetNode was specified and we're clustered, so finalize the
// config in the db and actually create the pool on all nodes.
err = storagePoolsPostCluster(d, req)
}
if err != nil {
return InternalError(err)
}
return response
}
// A targetNode was specified, let's just define the node's storage
// without actually creating it. The only legal key values for the
// storage config are the ones in StoragePoolNodeConfigKeys.
for key := range req.Config {
if !shared.StringInSlice(key, db.StoragePoolNodeConfigKeys) {
return SmartError(fmt.Errorf("Config key '%s' may not be used as node-specific key", key))
}
}
err = storagePoolValidate(req.Name, req.Driver, req.Config)
if err != nil {
return BadRequest(err)
}
err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.StoragePoolCreatePending(targetNode, req.Name, req.Driver, req.Config)
})
if err != nil {
if err == db.ErrAlreadyDefined {
return BadRequest(fmt.Errorf("The storage pool already defined on node %s", targetNode))
}
return SmartError(err)
}
return response
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L87-L89
|
func (api *API) AccountPreferenceLocator(href string) *AccountPreferenceLocator {
return &AccountPreferenceLocator{Href(href), api}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/cmds/cmds.go#L918-L945
|
func pushImage(client *docker.Client, authConfig docker.AuthConfiguration, repo string, sourceTag string, destTag string) (string, error) {
sourceImage := fmt.Sprintf("%s:%s", repo, sourceTag)
destImage := fmt.Sprintf("%s:%s", repo, destTag)
fmt.Printf("Tagging/pushing %s, this may take a while.\n", destImage)
if err := client.TagImage(sourceImage, docker.TagImageOptions{
Repo: repo,
Tag: destTag,
Context: context.Background(),
}); err != nil {
err = fmt.Errorf("could not tag docker image: %s", err)
return "", err
}
if err := client.PushImage(
docker.PushImageOptions{
Name: repo,
Tag: destTag,
},
authConfig,
); err != nil {
err = fmt.Errorf("could not push docker image: %s", err)
return "", err
}
return destImage, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3636-L3643
|
func (u InflationResult) ArmForSwitch(sw int32) (string, bool) {
switch InflationResultCode(sw) {
case InflationResultCodeInflationSuccess:
return "Payouts", true
default:
return "", true
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/pathtools/path.go#L40-L48
|
func TrimPrefix(p, prefix string) string {
if prefix == "" {
return p
}
if prefix == p {
return ""
}
return strings.TrimPrefix(p, prefix+"/")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1173-L1176
|
func (p ResolveNodeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *ResolveNodeParams {
p.BackendNodeID = backendNodeID
return &p
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L2647-L2696
|
func nodeToFileInfoHeaderFooter(ci *pfs.CommitInfo, filePath string,
node *hashtree.NodeProto, tree hashtree.HashTree, full bool) (*pfs.FileInfo, error) {
if node.FileNode == nil || !node.FileNode.HasHeaderFooter {
return nodeToFileInfo(ci, filePath, node, full), nil
}
node = proto.Clone(node).(*hashtree.NodeProto)
// validate baseFileInfo for logic below--if input hashtrees start using
// blockrefs instead of objects, this logic will need to be adjusted
if node.FileNode.Objects == nil {
return nil, fmt.Errorf("input commit node uses blockrefs; cannot apply header")
}
// 'file' includes header from parent—construct synthetic file info that
// includes header in list of objects & hash
parentPath := path.Dir(filePath)
parentNode, err := tree.Get(parentPath)
if err != nil {
return nil, fmt.Errorf("file %q has a header, but could not "+
"retrieve parent node at %q to get header content: %v", filePath,
parentPath, err)
}
if parentNode.DirNode == nil {
return nil, fmt.Errorf("parent of %q is not a directory; this is "+
"likely an internal error", filePath)
}
if parentNode.DirNode.Shared == nil {
return nil, fmt.Errorf("file %q has a shared header or footer, "+
"but parent directory does not permit shared data", filePath)
}
s := parentNode.DirNode.Shared
var newObjects []*pfs.Object
if s.Header != nil {
// cap := len+1 => newObjects is right whether or not we append() a footer
newL := len(node.FileNode.Objects) + 1
newObjects = make([]*pfs.Object, newL, newL+1)
newObjects[0] = s.Header
copy(newObjects[1:], node.FileNode.Objects)
} else {
newObjects = node.FileNode.Objects
}
if s.Footer != nil {
newObjects = append(newObjects, s.Footer)
}
node.FileNode.Objects = newObjects
node.SubtreeSize += s.HeaderSize + s.FooterSize
node.Hash = hashtree.HashFileNode(node.FileNode)
return nodeToFileInfo(ci, filePath, node, full), nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L520-L536
|
func (c *Cmd) StdinPipe() (io.WriteCloser, error) {
if c.Stdin != nil {
return nil, errors.New("exec: Stdin already set")
}
if c.Process != nil {
return nil, errors.New("exec: StdinPipe after process started")
}
pr, pw, err := os.Pipe()
if err != nil {
return nil, err
}
c.Stdin = pr
c.closeAfterStart = append(c.closeAfterStart, pr)
wc := &closeOnce{File: pw}
c.closeAfterWait = append(c.closeAfterWait, closerFunc(wc.safeClose))
return wc, nil
}
|
https://github.com/texttheater/golang-levenshtein/blob/d188e65d659ef53fcdb0691c12f1bba64928b649/levenshtein/levenshtein.go#L184-L186
|
func EditScriptForMatrix(matrix [][]int, op Options) EditScript {
return backtrace(len(matrix)-1, len(matrix[0])-1, matrix, op)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/prstatus/prstatus.go#L344-L350
|
func (da *DashboardAgent) ConstructSearchQuery(login string) string {
tokens := []string{"is:pr", "state:open", "author:" + login}
for i := range da.repos {
tokens = append(tokens, fmt.Sprintf("repo:\"%s\"", da.repos[i]))
}
return strings.Join(tokens, " ")
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6710-L6719
|
func (u StellarMessage) GetQSet() (result ScpQuorumSet, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "QSet" {
result = *u.QSet
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2076-L2080
|
func (v *SetKeyframeKeyReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss19(&r, v)
return r.Error()
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L272-L277
|
func (c *Client) ListUsers() (*Users, error) {
url := umUsers() + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Users{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_snapshot.go#L77-L86
|
func (m *InmemSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {
m.RLock()
defer m.RUnlock()
if m.latest.meta.ID != id {
return nil, nil, fmt.Errorf("[ERR] snapshot: failed to open snapshot id: %s", id)
}
return &m.latest.meta, ioutil.NopCloser(m.latest.contents), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/accessibility.go#L78-L81
|
func (p GetPartialAXTreeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetPartialAXTreeParams {
p.BackendNodeID = backendNodeID
return &p
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L931-L939
|
func (c *Cluster) ImageGetNodesWithImage(fingerprint string) ([]string, error) {
q := `
SELECT DISTINCT nodes.address FROM nodes
LEFT JOIN images_nodes ON images_nodes.node_id = nodes.id
LEFT JOIN images ON images_nodes.image_id = images.id
WHERE images.fingerprint = ?
`
return c.getNodesByImageFingerprint(q, fingerprint)
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/smtp/mail.go#L34-L45
|
func (m *MailService) Send(message string, subject string, from string, to string) (err error) {
t := []string{to}
msg := []byte("From: " + from + "\r\n" +
"To: " + to + "\r\n" +
"Subject: " + subject + "\r\n" +
"\r\n" +
message + "\r\n")
err = m.SMTP.SendMail(from, t, msg)
return
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/main.go#L23-L40
|
func SafeUnmarshalBase64(data string, dest interface{}) error {
count := &countWriter{}
l := len(data)
b64 := io.TeeReader(strings.NewReader(data), count)
raw := base64.NewDecoder(base64.StdEncoding, b64)
_, err := Unmarshal(raw, dest)
if err != nil {
return err
}
if count.Count != l {
return fmt.Errorf("input not fully consumed. expected to read: %d, actual: %d", l, count.Count)
}
return nil
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L166-L171
|
func EscapeHTML(s string) string {
if Verbose {
fmt.Println("Use html.EscapeString instead of EscapeHTML")
}
return html.EscapeString(s)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7166-L7170
|
func (v CaptureScreenshotReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage79(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L171-L191
|
func (q *Query) Order(fieldName string) *Query {
q = q.clone()
fieldName = strings.TrimSpace(fieldName)
o := order{
Direction: ascending,
FieldName: fieldName,
}
if strings.HasPrefix(fieldName, "-") {
o.Direction = descending
o.FieldName = strings.TrimSpace(fieldName[1:])
} else if strings.HasPrefix(fieldName, "+") {
q.err = fmt.Errorf("datastore: invalid order: %q", fieldName)
return q
}
if len(o.FieldName) == 0 {
q.err = errors.New("datastore: empty order")
return q
}
q.order = append(q.order, o)
return q
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L136-L141
|
func (r region) SliceLen() int64 {
if r.typ.Kind != KindSlice {
panic("can't len a non-slice")
}
return r.p.proc.ReadInt(r.a.Add(r.p.proc.PtrSize()))
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection.go#L77-L103
|
func (s *Selection) EqualsElement(other interface{}) (bool, error) {
otherSelection, ok := other.(*Selection)
if !ok {
multiSelection, ok := other.(*MultiSelection)
if !ok {
return false, fmt.Errorf("must be *Selection or *MultiSelection")
}
otherSelection = &multiSelection.Selection
}
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return false, fmt.Errorf("failed to select element from %s: %s", s, err)
}
otherElement, err := otherSelection.elements.GetExactlyOne()
if err != nil {
return false, fmt.Errorf("failed to select element from %s: %s", other, err)
}
equal, err := selectedElement.IsEqualTo(otherElement.(*api.Element))
if err != nil {
return false, fmt.Errorf("failed to compare %s to %s: %s", s, other, err)
}
return equal, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L1249-L1308
|
func (loc *BackupLocator) Cleanup(keepLast string, lineage string, options rsapi.APIParams) error {
if keepLast == "" {
return fmt.Errorf("keepLast is required")
}
if lineage == "" {
return fmt.Errorf("lineage is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"keep_last": keepLast,
"lineage": lineage,
}
var cloudHrefOpt = options["cloud_href"]
if cloudHrefOpt != nil {
p["cloud_href"] = cloudHrefOpt
}
var dailiesOpt = options["dailies"]
if dailiesOpt != nil {
p["dailies"] = dailiesOpt
}
var monthliesOpt = options["monthlies"]
if monthliesOpt != nil {
p["monthlies"] = monthliesOpt
}
var skipDeletionOpt = options["skip_deletion"]
if skipDeletionOpt != nil {
p["skip_deletion"] = skipDeletionOpt
}
var weekliesOpt = options["weeklies"]
if weekliesOpt != nil {
p["weeklies"] = weekliesOpt
}
var yearliesOpt = options["yearlies"]
if yearliesOpt != nil {
p["yearlies"] = yearliesOpt
}
uri, err := loc.ActionPath("Backup", "cleanup")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L202-L208
|
func (subChMap *subChannelMap) getOrAdd(serviceName string, ch *Channel) (_ *SubChannel, added bool) {
if sc, ok := subChMap.get(serviceName); ok {
return sc, false
}
return subChMap.registerNewSubChannel(serviceName, ch)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L7165-L7173
|
func (u ScpStatementPledges) MustNominate() ScpNomination {
val, ok := u.GetNominate()
if !ok {
panic("arm Nominate is not set")
}
return val
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L85-L106
|
func AskPassword(question string) string {
for {
fmt.Printf(question)
pwd, _ := terminal.ReadPassword(0)
fmt.Println("")
inFirst := string(pwd)
inFirst = strings.TrimSuffix(inFirst, "\n")
fmt.Printf("Again: ")
pwd, _ = terminal.ReadPassword(0)
fmt.Println("")
inSecond := string(pwd)
inSecond = strings.TrimSuffix(inSecond, "\n")
if inFirst == inSecond {
return inFirst
}
invalidInput()
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2995-L2999
|
func (v *GetStackTraceReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger31(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L974-L978
|
func (v *EventWorkerVersionUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoServiceworker10(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/handler.go#L96-L124
|
func Register(registrar tchannel.Registrar, funcs Handlers, onError func(context.Context, error)) error {
handlers := make(map[string]*handler)
handler := tchannel.HandlerFunc(func(ctx context.Context, call *tchannel.InboundCall) {
h, ok := handlers[string(call.Method())]
if !ok {
onError(ctx, fmt.Errorf("call for unregistered method: %s", call.Method()))
return
}
if err := h.Handle(ctx, call); err != nil {
onError(ctx, err)
}
})
for m, f := range funcs {
h, err := toHandler(f)
if err != nil {
return fmt.Errorf("%v cannot be used as a handler: %v", m, err)
}
h.tracer = func() opentracing.Tracer {
return tchannel.TracerFromRegistrar(registrar)
}
handlers[m] = h
registrar.Register(handler, m)
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L38-L45
|
func (l *inMemoryListener) Accept() (net.Conn, error) {
select {
case conn := <-l.conns:
return conn, nil
case <-l.closed:
return nil, fmt.Errorf("closed")
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L183-L222
|
func (c *ClusterTx) ContainerNodeAddress(project string, name string) (string, error) {
stmt := `
SELECT nodes.id, nodes.address
FROM nodes
JOIN containers ON containers.node_id = nodes.id
JOIN projects ON projects.id = containers.project_id
WHERE projects.name = ? AND containers.name = ?
`
var address string
var id int64
rows, err := c.tx.Query(stmt, project, name)
if err != nil {
return "", err
}
defer rows.Close()
if !rows.Next() {
return "", ErrNoSuchObject
}
err = rows.Scan(&id, &address)
if err != nil {
return "", err
}
if rows.Next() {
return "", fmt.Errorf("more than one node associated with container")
}
err = rows.Err()
if err != nil {
return "", err
}
if id == c.nodeID {
return "", nil
}
return address, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.