_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/diff/view.go#L45-L61
|
func makeTable(baseCovList, newCovList *calculation.CoverageList, coverageThreshold float32) (string, bool) {
var rows []string
isCoverageLow := false
for _, change := range findChanges(baseCovList, newCovList) {
filePath := change.name
rows = append(rows, fmt.Sprintf("%s | %s | %s | %s",
filePath,
formatPercentage(change.baseRatio),
formatPercentage(change.newRatio),
deltaDisplayed(change)))
if change.newRatio < coverageThreshold {
isCoverageLow = true
}
}
return strings.Join(rows, "\n"), isCoverageLow
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L287-L290
|
func (a *rl10Authenticator) Sign(r *http.Request) error {
r.Header.Set("X-RLL-Secret", a.secret)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L107-L125
|
func (c *CertInfo) PrivateKey() []byte {
ecKey, ok := c.KeyPair().PrivateKey.(*ecdsa.PrivateKey)
if ok {
data, err := x509.MarshalECPrivateKey(ecKey)
if err != nil {
return nil
}
return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data})
}
rsaKey, ok := c.KeyPair().PrivateKey.(*rsa.PrivateKey)
if ok {
data := x509.MarshalPKCS1PrivateKey(rsaKey)
return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: data})
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/collection.go#L563-L576
|
func (c *readonlyCollection) ListPrefix(prefix string, val proto.Message, opts *Options, f func(string) error) error {
queryPrefix := c.prefix
if prefix != "" {
// If we always call join, we'll get rid of the trailing slash we need
// on the root c.prefix
queryPrefix = filepath.Join(c.prefix, prefix)
}
return c.list(queryPrefix, &c.limit, opts, func(kv *mvccpb.KeyValue) error {
if err := proto.Unmarshal(kv.Value, val); err != nil {
return err
}
return f(strings.TrimPrefix(string(kv.Key), queryPrefix))
})
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L351-L353
|
func CompareAndSwapMulti(c context.Context, item []*Item) error {
return set(c, item, nil, pb.MemcacheSetRequest_CAS)
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/version.go#L25-L36
|
func VersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Verify Kubicorn version",
Long: `Use this command to check the version of Kubicorn.
This command will return the version of the Kubicorn binary.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("%s\n", version.GetVersionJSON())
},
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4324-L4328
|
func (v EntryPreview) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime39(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L218-L223
|
func (l *PeerList) GetOrAdd(hostPort string) *Peer {
if ps, ok := l.exists(hostPort); ok {
return ps.Peer
}
return l.Add(hostPort)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/raftexample/raft.go#L200-L224
|
func (rc *raftNode) openWAL(snapshot *raftpb.Snapshot) *wal.WAL {
if !wal.Exist(rc.waldir) {
if err := os.Mkdir(rc.waldir, 0750); err != nil {
log.Fatalf("raftexample: cannot create dir for wal (%v)", err)
}
w, err := wal.Create(zap.NewExample(), rc.waldir, nil)
if err != nil {
log.Fatalf("raftexample: create wal error (%v)", err)
}
w.Close()
}
walsnap := walpb.Snapshot{}
if snapshot != nil {
walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
}
log.Printf("loading WAL at term %d and index %d", walsnap.Term, walsnap.Index)
w, err := wal.Open(zap.NewExample(), rc.waldir, walsnap)
if err != nil {
log.Fatalf("raftexample: error loading wal (%v)", err)
}
return w
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L522-L598
|
func (c *ClusterTx) ProfileUsedByRef(filter ProfileFilter) (map[string]map[string][]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileUsedByRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileUsedByRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileUsedByRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch string ref for profiles")
}
// Build index by primary name.
index := map[string]map[string][]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string][]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = []string{}
}
index[object.Project][object.Name] = append(item, object.Value)
}
return index, nil
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L131-L133
|
func (s *selectable) FirstByButton(text string) *Selection {
return newSelection(s.session, s.selectors.Append(target.Button, text).At(0))
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L123-L136
|
func (peer *Peer) forEachConnectedPeer(establishedAndSymmetric bool, exclude map[PeerName]PeerName, f func(*Peer)) {
for remoteName, conn := range peer.connections {
if establishedAndSymmetric && !conn.isEstablished() {
continue
}
if _, found := exclude[remoteName]; found {
continue
}
remotePeer := conn.Remote()
if remoteConn, found := remotePeer.connections[peer.Name]; !establishedAndSymmetric || (found && remoteConn.isEstablished()) {
f(remotePeer)
}
}
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/generators/generate.go#L115-L124
|
func CreateNewRecord(property string, yaml enaml.JobManifestProperty) (record Record) {
elementArray := strings.Split(property, ".")
record = Record{
Length: len(elementArray),
Orig: property,
Slice: elementArray,
Yaml: yaml,
}
return
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift_transport.go#L134-L140
|
func (ref openshiftReference) NewImage(ctx context.Context, sys *types.SystemContext) (types.ImageCloser, error) {
src, err := newImageSource(sys, ref)
if err != nil {
return nil, err
}
return genericImage.FromSource(ctx, sys, src)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_volumes.go#L730-L823
|
func storagePoolVolumeTypePut(d *Daemon, r *http.Request, volumeTypeName string) Response {
// Get the name of the storage volume.
var volumeName string
fields := strings.Split(mux.Vars(r)["name"], "/")
if len(fields) == 3 && fields[1] == "snapshots" {
// Handle volume snapshots
volumeName = fmt.Sprintf("%s%s%s", fields[0], shared.SnapshotDelimiter, fields[2])
} else if len(fields) > 1 {
volumeName = fmt.Sprintf("%s%s%s", fields[0], shared.SnapshotDelimiter, fields[1])
} else if len(fields) > 0 {
// Handle volume
volumeName = fields[0]
} else {
return BadRequest(fmt.Errorf("invalid storage volume %s", mux.Vars(r)["name"]))
}
// Get the name of the storage pool the volume is supposed to be
// attached to.
poolName := mux.Vars(r)["pool"]
// Convert the volume type name to our internal integer representation.
volumeType, err := storagePoolVolumeTypeNameToType(volumeTypeName)
if err != nil {
return BadRequest(err)
}
// Check that the storage volume type is valid.
if !shared.IntInSlice(volumeType, supportedVolumeTypes) {
return BadRequest(fmt.Errorf("invalid storage volume type %s", volumeTypeName))
}
poolID, pool, err := d.cluster.StoragePoolGet(poolName)
if err != nil {
return SmartError(err)
}
response := ForwardedResponseIfTargetIsRemote(d, r)
if response != nil {
return response
}
response = ForwardedResponseIfVolumeIsRemote(d, r, poolID, volumeName, volumeType)
if response != nil {
return response
}
// Get the existing storage volume.
_, volume, err := d.cluster.StoragePoolNodeVolumeGetType(volumeName, volumeType, poolID)
if err != nil {
return SmartError(err)
}
// Validate the ETag
etag := []interface{}{volumeName, volume.Type, volume.Config}
err = util.EtagCheck(r, etag)
if err != nil {
return PreconditionFailed(err)
}
req := api.StorageVolumePut{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return BadRequest(err)
}
if req.Restore != "" {
ctsUsingVolume, err := storagePoolVolumeUsedByRunningContainersWithProfilesGet(d.State(), poolName, volume.Name, storagePoolVolumeTypeNameCustom, true)
if err != nil {
return InternalError(err)
}
if len(ctsUsingVolume) != 0 {
return BadRequest(fmt.Errorf("Cannot restore custom volume used by running containers"))
}
err = storagePoolVolumeRestore(d.State(), poolName, volumeName, volumeType, req.Restore)
if err != nil {
return SmartError(err)
}
} else {
// Validate the configuration
err = storageVolumeValidateConfig(volumeName, req.Config, pool)
if err != nil {
return BadRequest(err)
}
err = storagePoolVolumeUpdate(d.State(), poolName, volumeName, volumeType, req.Description, req.Config)
if err != nil {
return SmartError(err)
}
}
return EmptySyncResponse
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/cluster_util.go#L299-L357
|
func getVersion(lg *zap.Logger, m *membership.Member, rt http.RoundTripper) (*version.Versions, error) {
cc := &http.Client{
Transport: rt,
}
var (
err error
resp *http.Response
)
for _, u := range m.PeerURLs {
addr := u + "/version"
resp, err = cc.Get(addr)
if err != nil {
if lg != nil {
lg.Warn(
"failed to reach the peer URL",
zap.String("address", addr),
zap.String("remote-member-id", m.ID.String()),
zap.Error(err),
)
} else {
plog.Warningf("failed to reach the peerURL(%s) of member %s (%v)", u, m.ID, err)
}
continue
}
var b []byte
b, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
if lg != nil {
lg.Warn(
"failed to read body of response",
zap.String("address", addr),
zap.String("remote-member-id", m.ID.String()),
zap.Error(err),
)
} else {
plog.Warningf("failed to read out the response body from the peerURL(%s) of member %s (%v)", u, m.ID, err)
}
continue
}
var vers version.Versions
if err = json.Unmarshal(b, &vers); err != nil {
if lg != nil {
lg.Warn(
"failed to unmarshal response",
zap.String("address", addr),
zap.String("remote-member-id", m.ID.String()),
zap.Error(err),
)
} else {
plog.Warningf("failed to unmarshal the response body got from the peerURL(%s) of member %s (%v)", u, m.ID, err)
}
continue
}
return &vers, nil
}
return nil, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L364-L374
|
func (t *DispatchMouseEventPointerType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch DispatchMouseEventPointerType(in.String()) {
case Mouse:
*t = Mouse
case Pen:
*t = Pen
default:
in.AddError(errors.New("unknown DispatchMouseEventPointerType value"))
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/fake/fake_app.go#L70-L78
|
func (c *FakeApps) Create(app *tsuru_v1.App) (result *tsuru_v1.App, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(appsResource, c.ns, app), &tsuru_v1.App{})
if obj == nil {
return nil, err
}
return obj.(*tsuru_v1.App), err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L406-L424
|
func (ic *imageCopier) updateEmbeddedDockerReference() error {
if ic.c.dest.IgnoresEmbeddedDockerReference() {
return nil // Destination would prefer us not to update the embedded reference.
}
destRef := ic.c.dest.Reference().DockerReference()
if destRef == nil {
return nil // Destination does not care about Docker references
}
if !ic.src.EmbeddedDockerReferenceConflicts(destRef) {
return nil // No reference embedded in the manifest, or it matches destRef already.
}
if !ic.canModifyManifest {
return errors.Errorf("Copying a schema1 image with an embedded Docker reference to %s (Docker reference %s) would invalidate existing signatures. Explicitly enable signature removal to proceed anyway",
transports.ImageName(ic.c.dest.Reference()), destRef.String())
}
ic.manifestUpdates.EmbeddedDockerReference = destRef
return nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L39-L42
|
func WaitKey(delay int) int {
key := C.cvWaitKey(C.int(delay))
return int(key)
}
|
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/api/valuestore_GEN_.go#L44-L97
|
func NewValueStore(addr string, concurrency int, ftlsConfig *ftls.Config, opts ...grpc.DialOption) (store.ValueStore, error) {
stor := &valueStore{
addr: addr,
ftlsc: ftlsConfig,
opts: opts,
handlersDoneChan: make(chan struct{}),
}
stor.pendingLookupReqChan = make(chan *asyncValueLookupRequest, concurrency)
stor.freeLookupReqChan = make(chan *asyncValueLookupRequest, concurrency)
stor.freeLookupResChan = make(chan *asyncValueLookupResponse, concurrency)
for i := 0; i < cap(stor.freeLookupReqChan); i++ {
stor.freeLookupReqChan <- &asyncValueLookupRequest{resChan: make(chan *asyncValueLookupResponse, 1)}
}
for i := 0; i < cap(stor.freeLookupResChan); i++ {
stor.freeLookupResChan <- &asyncValueLookupResponse{}
}
go stor.handleLookupStream()
stor.pendingReadReqChan = make(chan *asyncValueReadRequest, concurrency)
stor.freeReadReqChan = make(chan *asyncValueReadRequest, concurrency)
stor.freeReadResChan = make(chan *asyncValueReadResponse, concurrency)
for i := 0; i < cap(stor.freeReadReqChan); i++ {
stor.freeReadReqChan <- &asyncValueReadRequest{resChan: make(chan *asyncValueReadResponse, 1)}
}
for i := 0; i < cap(stor.freeReadResChan); i++ {
stor.freeReadResChan <- &asyncValueReadResponse{}
}
go stor.handleReadStream()
stor.pendingWriteReqChan = make(chan *asyncValueWriteRequest, concurrency)
stor.freeWriteReqChan = make(chan *asyncValueWriteRequest, concurrency)
stor.freeWriteResChan = make(chan *asyncValueWriteResponse, concurrency)
for i := 0; i < cap(stor.freeWriteReqChan); i++ {
stor.freeWriteReqChan <- &asyncValueWriteRequest{resChan: make(chan *asyncValueWriteResponse, 1)}
}
for i := 0; i < cap(stor.freeWriteResChan); i++ {
stor.freeWriteResChan <- &asyncValueWriteResponse{}
}
go stor.handleWriteStream()
stor.pendingDeleteReqChan = make(chan *asyncValueDeleteRequest, concurrency)
stor.freeDeleteReqChan = make(chan *asyncValueDeleteRequest, concurrency)
stor.freeDeleteResChan = make(chan *asyncValueDeleteResponse, concurrency)
for i := 0; i < cap(stor.freeDeleteReqChan); i++ {
stor.freeDeleteReqChan <- &asyncValueDeleteRequest{resChan: make(chan *asyncValueDeleteResponse, 1)}
}
for i := 0; i < cap(stor.freeDeleteResChan); i++ {
stor.freeDeleteResChan <- &asyncValueDeleteResponse{}
}
go stor.handleDeleteStream()
return stor, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L196-L222
|
func PartitionActive(pjs []prowapi.ProwJob) (pending, triggered chan prowapi.ProwJob) {
// Size channels correctly.
pendingCount, triggeredCount := 0, 0
for _, pj := range pjs {
switch pj.Status.State {
case prowapi.PendingState:
pendingCount++
case prowapi.TriggeredState:
triggeredCount++
}
}
pending = make(chan prowapi.ProwJob, pendingCount)
triggered = make(chan prowapi.ProwJob, triggeredCount)
// Partition the jobs into the two separate channels.
for _, pj := range pjs {
switch pj.Status.State {
case prowapi.PendingState:
pending <- pj
case prowapi.TriggeredState:
triggered <- pj
}
}
close(pending)
close(triggered)
return pending, triggered
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1820-L1829
|
func (c *Client) CloseIssue(org, repo string, number int) error {
c.log("CloseIssue", org, repo, number)
_, err := c.request(&request{
method: http.MethodPatch,
path: fmt.Sprintf("/repos/%s/%s/issues/%d", org, repo, number),
requestBody: map[string]string{"state": "closed"},
exitCodes: []int{200},
}, nil)
return err
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L100-L102
|
func (s *selectable) FindByClass(text string) *Selection {
return newSelection(s.session, s.selectors.Append(target.Class, text).Single())
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/auth.go#L24-L32
|
func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
raw, err := rsapi.FromCommandLine(cmdLine)
cmdLine.Host = HostFromLogin(cmdLine.Host)
if err != nil {
return nil, err
}
return fromAPI(raw), nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L73-L79
|
func EmptyFile(path, pkg string) *File {
return &File{
File: &bzl.File{Path: path, Type: bzl.TypeBuild},
Path: path,
Pkg: pkg,
}
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/create.go#L90-L253
|
func RunCreate(options *cli.CreateOptions) error {
// Create our cluster resource
name := options.Name
var newCluster *cluster.Cluster
if _, ok := cli.ProfileMapIndexed[options.Profile]; ok {
newCluster = cli.ProfileMapIndexed[options.Profile].ProfileFunc(name)
} else {
return fmt.Errorf("Invalid profile [%s]", options.Profile)
}
if options.KubeConfigLocalFile != "" {
if newCluster.Annotations == nil {
newCluster.Annotations = make(map[string]string)
}
newCluster.Annotations[kubeconfig.ClusterAnnotationKubeconfigLocalFile] = options.KubeConfigLocalFile
}
if len(options.Set) > 0 {
// Here we override Set options
for _, set := range options.Set {
parts := strings.SplitN(set, "=", 2)
if len(parts) == 1 {
continue
}
providerConfig := newCluster.ProviderConfig()
err := cli.SwalkerWrite(strings.Title(parts[0]), providerConfig, parts[1])
if err != nil {
//fmt.Println(1)
return fmt.Errorf("Invalid --set: %v", err)
}
newCluster.SetProviderConfig(providerConfig)
}
}
if len(options.MasterSet) > 0 {
// Here we override MasterSet options
for _, set := range options.MasterSet {
parts := strings.SplitN(set, "=", 2)
if len(parts) == 1 {
continue
}
for i, ms := range newCluster.MachineSets {
isMaster := false
for _, role := range ms.Spec.Template.Spec.Roles {
if role == v1alpha1.MasterRole {
isMaster = true
break
}
}
if !isMaster {
continue
}
pcStr := ms.Spec.Template.Spec.ProviderConfig
providerConfig := &cluster.MachineProviderConfig{}
json.Unmarshal([]byte(pcStr), providerConfig)
err := cli.SwalkerWrite(strings.Title(parts[0]), providerConfig, parts[1])
if err != nil {
//fmt.Println(2)
return fmt.Errorf("Invalid --set: %v", err)
}
// Now set the provider config
bytes, err := json.Marshal(providerConfig)
if err != nil {
logger.Critical("Unable to marshal provider config: %v", err)
return err
}
str := string(bytes)
newCluster.MachineSets[i].Spec.Template.Spec.ProviderConfig = str
}
}
}
if len(options.NodeSet) > 0 {
// Here we override NodeSet options
for _, set := range options.NodeSet {
parts := strings.SplitN(set, "=", 2)
if len(parts) == 1 {
continue
}
for i, ms := range newCluster.MachineSets {
isNode := false
for _, role := range ms.Spec.Template.Spec.Roles {
if role == v1alpha1.NodeRole {
isNode = true
break
}
}
if !isNode {
continue
}
pcStr := ms.Spec.Template.Spec.ProviderConfig
providerConfig := &cluster.MachineProviderConfig{}
json.Unmarshal([]byte(pcStr), providerConfig)
err := cli.SwalkerWrite(strings.Title(parts[0]), providerConfig, parts[1])
if err != nil {
//fmt.Println(3)
return fmt.Errorf("Invalid --set: %v", err)
}
// Now set the provider config
bytes, err := json.Marshal(providerConfig)
if err != nil {
logger.Critical("Unable to marshal provider config: %v", err)
return err
}
str := string(bytes)
newCluster.MachineSets[i].Spec.Template.Spec.ProviderConfig = str
}
}
}
if len(options.AwsOptions.PolicyAttachments) > 0 {
for i, ms := range newCluster.MachineSets {
pcStr := ms.Spec.Template.Spec.ProviderConfig
providerConfig := &cluster.MachineProviderConfig{}
if err := json.Unmarshal([]byte(pcStr), providerConfig); err != nil {
logger.Critical("Unable to unmarshal provider config: %v", err)
return err
}
if providerConfig.ServerPool != nil && providerConfig.ServerPool.InstanceProfile != nil && providerConfig.ServerPool.InstanceProfile.Role != nil {
providerConfig.ServerPool.InstanceProfile.Role.PolicyAttachments = options.AwsOptions.PolicyAttachments
}
// Now set the provider config
bytes, err := json.Marshal(providerConfig)
if err != nil {
logger.Critical("Unable to marshal provider config: %v", err)
return err
}
str := string(bytes)
newCluster.MachineSets[i].Spec.Template.Spec.ProviderConfig = str
}
}
if newCluster.ProviderConfig().Cloud == cluster.CloudGoogle && options.CloudID == "" {
return fmt.Errorf("CloudID is required for google cloud. Please set it to your project ID")
}
providerConfig := newCluster.ProviderConfig()
providerConfig.CloudId = options.CloudID
newCluster.SetProviderConfig(providerConfig)
// Expand state store path
// Todo (@kris-nova) please pull this into a filepath package or something
options.StateStorePath = cli.ExpandPath(options.StateStorePath)
// Register state store and check if it exists
stateStore, err := options.NewStateStore()
if err != nil {
return err
} else if stateStore.Exists() {
return fmt.Errorf("State store [%s] exists, will not overwrite. Delete existing profile [%s] and retry", name, options.StateStorePath+"/"+name)
}
// Init new state store with the cluster resource
err = stateStore.Commit(newCluster)
if err != nil {
return fmt.Errorf("Unable to init state store: %v", err)
}
logger.Always("The state [%s/%s/cluster.yaml] has been created. You can edit the file, then run `kubicorn apply %s`", options.StateStorePath, name, name)
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/platform.go#L147-L179
|
func (s *platformService) Remove(name string) error {
if name == "" {
return appTypes.ErrPlatformNameMissing
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
apps, _ := conn.Apps().Find(bson.M{"framework": name}).Count()
if apps > 0 {
return appTypes.ErrDeletePlatformWithApps
}
err = builder.PlatformRemove(name)
if err != nil {
log.Errorf("Failed to remove platform from builder: %s", err)
}
images, err := servicemanager.PlatformImage.ListImagesOrDefault(name)
if err == nil {
for _, img := range images {
if regErr := registry.RemoveImage(img); regErr != nil {
log.Errorf("Failed to remove platform image from registry: %s", regErr)
}
}
} else {
log.Errorf("Failed to retrieve platform images from storage: %s", err)
}
err = servicemanager.PlatformImage.DeleteImages(name)
if err != nil {
log.Errorf("Failed to remove platform images from storage: %s", err)
}
return s.storage.Delete(appTypes.Platform{Name: name})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L274-L277
|
func (p DispatchTouchEventParams) WithModifiers(modifiers Modifier) *DispatchTouchEventParams {
p.Modifiers = modifiers
return &p
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L326-L328
|
func (l *Logger) Errorln(args ...interface{}) {
l.Output(2, LevelError, fmt.Sprintln(args...))
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L106-L112
|
func WithTemplatesFromStrings(ts map[string][]string) Option {
return func(o *Options) {
for name, strings := range ts {
o.strings[name] = strings
}
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L496-L509
|
func (p *Peer) removeConnection(connsPtr *[]*Connection, changed *Connection) bool {
conns := *connsPtr
for i, c := range conns {
if c == changed {
// Remove the connection by moving the last item forward, and slicing the list.
last := len(conns) - 1
conns[i], conns[last] = conns[last], nil
*connsPtr = conns[:last]
return true
}
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L538-L542
|
func (v *GrantPermissionsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser4(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L347-L356
|
func IsTerminal(state pps.JobState) bool {
switch state {
case pps.JobState_JOB_SUCCESS, pps.JobState_JOB_FAILURE, pps.JobState_JOB_KILLED:
return true
case pps.JobState_JOB_STARTING, pps.JobState_JOB_RUNNING, pps.JobState_JOB_MERGING:
return false
default:
panic(fmt.Sprintf("unrecognized job state: %s", state))
}
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L143-L213
|
func (r *Firewall) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("firewall.Apply")
expectedResource := expected.(*Firewall)
actualResource := actual.(*Firewall)
isEqual, err := compare.IsEqual(actualResource, expectedResource)
if err != nil {
return nil, nil, err
}
if isEqual {
return immutable, expected, nil
}
firewallRequest := godo.FirewallRequest{
Name: expectedResource.Name,
InboundRules: convertInRuleType(expectedResource.InboundRules),
OutboundRules: convertOutRuleType(expectedResource.OutboundRules),
DropletIDs: expectedResource.DropletIDs,
Tags: expectedResource.Tags,
}
// Make sure Droplets are fully created before applying a firewall
machineProviderConfigs := immutable.MachineProviderConfigs()
for _, machineProviderConfig := range machineProviderConfigs {
for i := 0; i <= TagsGetAttempts; i++ {
active := true
droplets, _, err := Sdk.Client.Droplets.ListByTag(context.TODO(), machineProviderConfig.ServerPool.Name, &godo.ListOptions{})
if err != nil {
logger.Debug("Hanging for droplets to get created.. (%v)", err)
time.Sleep(time.Duration(TagsGetTimeout) * time.Second)
continue
}
if len(droplets) == 0 {
continue
}
for _, d := range droplets {
if d.Status != "active" {
active = false
break
}
}
if !active {
logger.Debug("Waiting for droplets to become active..")
time.Sleep(time.Duration(TagsGetTimeout) * time.Second)
continue
}
break
}
}
firewall, _, err := Sdk.Client.Firewalls.Create(context.TODO(), &firewallRequest)
if err != nil {
return nil, nil, fmt.Errorf("failed to create the firewall err: %v", err)
}
logger.Success("Created Firewall [%s]", firewall.ID)
newResource := &Firewall{
Shared: Shared{
CloudID: firewall.ID,
Name: r.Name,
Tags: r.Tags,
},
DropletIDs: r.DropletIDs,
FirewallID: firewall.ID,
InboundRules: r.InboundRules,
OutboundRules: r.OutboundRules,
Created: r.Created,
}
newCluster := r.immutableRender(newResource, immutable)
return newCluster, newResource, nil
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/model.go#L37-L113
|
func (m *Model) SetDefault() error {
cType := reflect.TypeOf(m).Elem()
cValue := reflect.ValueOf(m).Elem()
structLen := cValue.NumField()
for i := 0; i < structLen; i++ {
field := cType.Field(i)
defaultValue := field.Tag.Get("default")
if defaultValue == "" {
continue
}
switch cValue.FieldByName(field.Name).Kind() {
case reflect.String:
cValue.FieldByName(field.Name).Set(reflect.ValueOf(defaultValue))
case reflect.Int8:
v, err := strconv.ParseInt(defaultValue, 10, 8)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(int8(v)))
case reflect.Int16:
v, err := strconv.ParseInt(defaultValue, 10, 16)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(int16(v)))
case reflect.Int:
v, err := strconv.ParseInt(defaultValue, 10, 32)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(int32(v)))
case reflect.Int64:
v, err := strconv.ParseInt(defaultValue, 10, 64)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(int64(v)))
case reflect.Uint8:
v, err := strconv.ParseUint(defaultValue, 10, 8)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(uint8(v)))
case reflect.Uint16:
v, err := strconv.ParseUint(defaultValue, 10, 16)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(uint16(v)))
case reflect.Uint32:
v, err := strconv.ParseUint(defaultValue, 10, 32)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(uint32(v)))
case reflect.Uint64:
v, err := strconv.ParseUint(defaultValue, 10, 64)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(uint64(v)))
case reflect.Float32:
v, err := strconv.ParseFloat(defaultValue, 32)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(float32(v)))
case reflect.Float64:
v, err := strconv.ParseFloat(defaultValue, 64)
if err != nil {
return validationError.New(fmt.Sprintf("model: %s, field: %s, the type of default data is incorrect.", cType, field.Name))
}
cValue.FieldByName(field.Name).Set(reflect.ValueOf(float64(v)))
}
}
return nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-encode.go#L353-L369
|
func (cdc *Codec) encodeReflectBinaryByteSlice(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if printLog {
fmt.Println("(e) encodeReflectBinaryByteSlice")
defer func() {
fmt.Printf("(e) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
if ert.Kind() != reflect.Uint8 {
panic("should not happen")
}
// Write byte-length prefixed byte-slice.
var byteslice = rv.Bytes()
err = EncodeByteSlice(w, byteslice)
return
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L73-L93
|
func Schema1FromComponents(ref reference.Named, fsLayers []Schema1FSLayers, history []Schema1History, architecture string) (*Schema1, error) {
var name, tag string
if ref != nil { // Well, what to do if it _is_ nil? Most consumers actually don't use these fields nowadays, so we might as well try not supplying them.
name = reference.Path(ref)
if tagged, ok := ref.(reference.NamedTagged); ok {
tag = tagged.Tag()
}
}
s1 := Schema1{
Name: name,
Tag: tag,
Architecture: architecture,
FSLayers: fsLayers,
History: history,
SchemaVersion: 1,
}
if err := s1.initialize(); err != nil {
return nil, err
}
return &s1, nil
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/sendable.go#L121-L130
|
func (ia *InlineQueryAnswer) Send() error {
resp := &baseResponse{}
_, err := ia.api.c.postJSON(answerInlineQuery, resp, ia)
if err != nil {
return err
}
return check(resp)
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L34-L39
|
func BoolFromPtr(b *bool) Bool {
if b == nil {
return NewBool(false, false)
}
return NewBool(*b, true)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/register.go#L48-L55
|
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&ProwJob{},
&ProwJobList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L36-L46
|
func (b *PointerRingBuf) TwoContig() (first []interface{}, second []interface{}) {
extent := b.Beg + b.Readable
if extent <= b.N {
// we fit contiguously in this buffer without wrapping to the other.
// Let second stay an empty slice.
return b.A[b.Beg:(b.Beg + b.Readable)], second
}
return b.A[b.Beg:b.N], b.A[0:(extent % b.N)]
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1417-L1421
|
func (h *dbHashTree) Hash() error {
return h.Batch(func(tx *bolt.Tx) error {
return canonicalize(tx, "")
})
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L372-L384
|
func (c *Controller) DeleteContainer(name string) error {
device, err := c.getDevice(name)
if err != nil {
return err
}
err = device.Delete()
if err != nil {
return err
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/task/start.go#L12-L21
|
func Start(f Func, schedule Schedule) (func(time.Duration) error, func()) {
group := Group{}
task := group.Add(f, schedule)
group.Start()
stop := group.Stop
reset := task.Reset
return stop, reset
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L211-L216
|
func ContinueWithAuth(requestID RequestID, authChallengeResponse *AuthChallengeResponse) *ContinueWithAuthParams {
return &ContinueWithAuthParams{
RequestID: requestID,
AuthChallengeResponse: authChallengeResponse,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/slack/client.go#L102-L114
|
func (sl *Client) WriteMessage(text, channel string) error {
sl.log("WriteMessage", text, channel)
if sl.fake {
return nil
}
var uv = sl.urlValues()
uv.Add("channel", channel)
uv.Add("text", text)
_, err := sl.postMessage(chatPostMessage, uv)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L4218-L4222
|
func (v EventPaused) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger40(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/config.go#L12-L49
|
func CompareConfigs(config1, config2 map[string]string, exclude []string) error {
if exclude == nil {
exclude = []string{}
}
delta := []string{}
for key, value := range config1 {
if shared.StringInSlice(key, exclude) {
continue
}
if config2[key] != value {
delta = append(delta, key)
}
}
for key, value := range config2 {
if shared.StringInSlice(key, exclude) {
continue
}
if config1[key] != value {
present := false
for i := range delta {
if delta[i] == key {
present = true
}
break
}
if !present {
delta = append(delta, key)
}
}
}
sort.Strings(delta)
if len(delta) > 0 {
return fmt.Errorf("different values for keys: %s", strings.Join(delta, ", "))
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L40-L42
|
func NewProwJobWithAnnotation(spec prowapi.ProwJobSpec, labels, annotations map[string]string) prowapi.ProwJob {
return newProwJob(spec, labels, annotations)
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/gen/update_proto_csv.go#L289-L325
|
func generateFromPath(w io.Writer, rootPath string) error {
return filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !strings.HasSuffix(path, ".proto") {
return nil
}
relPath, err := filepath.Rel(rootPath, path)
if err != nil || strings.HasPrefix(relPath, "..") {
log.Panicf("file %q not in repository rootPath %q", path, rootPath)
}
relPath = filepath.ToSlash(relPath)
if strings.HasPrefix(relPath, "google/api/experimental/") {
// Special case: these protos need to be built together with protos in
// google/api. They have the same 'option go_package'. The proto_library
// rule requires them to be in the same Bazel package, so we don't
// create a build file in experimental.
packagePath := "google.golang.org/genproto/googleapis/api"
protoLabel, goLabel := protoLabels("google/api/x", "api")
fmt.Fprintf(w, "%s,%s,%s,%s\n", relPath, protoLabel, packagePath, goLabel)
return nil
}
packagePath, packageName, err := loadGoPackage(path)
if err != nil {
log.Print(err)
return nil
}
protoLabel, goLabel := protoLabels(relPath, packageName)
fmt.Fprintf(w, "%s,%s,%s,%s\n", relPath, protoLabel, packagePath, goLabel)
return nil
})
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L991-L1009
|
func (r *Raft) processHeartbeat(rpc RPC) {
defer metrics.MeasureSince([]string{"raft", "rpc", "processHeartbeat"}, time.Now())
// Check if we are shutdown, just ignore the RPC
select {
case <-r.shutdownCh:
return
default:
}
// Ensure we are only handling a heartbeat
switch cmd := rpc.Command.(type) {
case *AppendEntriesRequest:
r.appendEntries(rpc, cmd)
default:
r.logger.Error(fmt.Sprintf("Expected heartbeat, got command: %#v", rpc.Command))
rpc.Respond(nil, fmt.Errorf("unexpected command"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6664-L6668
|
func (v *CopyToParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom75(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/resource_crd.go#L130-L135
|
func (in *ResourceObject) FromItem(i common.Item) {
r, err := common.ItemToResource(i)
if err == nil {
in.fromResource(r)
}
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L74-L80
|
func (s *Stack) Get(i int) (interface{}, error) {
if i < 0 || i >= len(*s) {
return nil, errors.New(strconv.Itoa(i) + " is out of range")
}
return (*s)[i], nil
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/group.go#L52-L76
|
func (dom *Domain) GetGroup(name string) (*Group, error) {
var d dictionary
err := dom.cgp.request(getGroup{Name: fmt.Sprintf("%s@%s", name, dom.Name)}, &d)
if err != nil {
return &Group{}, err
}
memStr := d.toMap()["Members"]
var mems []*Account
dec := xml.NewDecoder(bytes.NewBufferString(memStr))
for {
var a string
err := dec.Decode(&a)
if err == io.EOF {
break
}
if err != nil {
return dom.Group(name, mems), err
}
if a == "" {
continue
}
mems = append(mems, dom.Account(a))
}
return dom.Group(name, mems), nil
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/forwarder.go#L21-L23
|
func (dom *Domain) Forwarder(name, to string) *Forwarder {
return &Forwarder{Domain: dom, Name: name, To: to}
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L118-L120
|
func (la *LogAdapter) Debug(msg string) error {
return la.Log(LevelDebug, nil, msg)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L99-L168
|
func memberAddCommandFunc(cmd *cobra.Command, args []string) {
if len(args) < 1 {
ExitWithError(ExitBadArgs, errors.New("member name not provided"))
}
if len(args) > 1 {
ev := "too many arguments"
for _, s := range args {
if strings.HasPrefix(strings.ToLower(s), "http") {
ev += fmt.Sprintf(`, did you mean --peer-urls=%s`, s)
}
}
ExitWithError(ExitBadArgs, errors.New(ev))
}
newMemberName := args[0]
if len(memberPeerURLs) == 0 {
ExitWithError(ExitBadArgs, errors.New("member peer urls not provided"))
}
urls := strings.Split(memberPeerURLs, ",")
ctx, cancel := commandCtx(cmd)
cli := mustClientFromCmd(cmd)
resp, err := cli.MemberAdd(ctx, urls)
cancel()
if err != nil {
ExitWithError(ExitError, err)
}
newID := resp.Member.ID
display.MemberAdd(*resp)
if _, ok := (display).(*simplePrinter); ok {
ctx, cancel = commandCtx(cmd)
listResp, err := cli.MemberList(ctx)
// get latest member list; if there's failover new member might have outdated list
for {
if err != nil {
ExitWithError(ExitError, err)
}
if listResp.Header.MemberId == resp.Header.MemberId {
break
}
// quorum get to sync cluster list
gresp, gerr := cli.Get(ctx, "_")
if gerr != nil {
ExitWithError(ExitError, err)
}
resp.Header.MemberId = gresp.Header.MemberId
listResp, err = cli.MemberList(ctx)
}
cancel()
conf := []string{}
for _, memb := range listResp.Members {
for _, u := range memb.PeerURLs {
n := memb.Name
if memb.ID == newID {
n = newMemberName
}
conf = append(conf, fmt.Sprintf("%s=%s", n, u))
}
}
fmt.Print("\n")
fmt.Printf("ETCD_NAME=%q\n", newMemberName)
fmt.Printf("ETCD_INITIAL_CLUSTER=%q\n", strings.Join(conf, ","))
fmt.Printf("ETCD_INITIAL_ADVERTISE_PEER_URLS=%q\n", memberPeerURLs)
fmt.Printf("ETCD_INITIAL_CLUSTER_STATE=\"existing\"\n")
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L123-L129
|
func (s storageReference) Transport() types.ImageTransport {
return &storageTransport{
store: s.transport.store,
defaultUIDMap: s.transport.defaultUIDMap,
defaultGIDMap: s.transport.defaultGIDMap,
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2941-L2944
|
func (e ManageOfferResultCode) ValidEnum(v int32) bool {
_, ok := manageOfferResultCodeMap[v]
return ok
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/master.go#L561-L633
|
func (a *apiServer) makeCronCommits(pachClient *client.APIClient, in *pps.Input) error {
schedule, err := cron.ParseStandard(in.Cron.Spec)
if err != nil {
return err // Shouldn't happen, as the input is validated in CreatePipeline
}
// make sure there isn't an unfinished commit on the branch
commitInfo, err := pachClient.InspectCommit(in.Cron.Repo, "master")
if err != nil && !isNilBranchErr(err) {
return err
} else if commitInfo != nil && commitInfo.Finished == nil {
// and if there is, delete it
if err = pachClient.DeleteCommit(in.Cron.Repo, "master"); err != nil {
return err
}
}
var latestTime time.Time
files, err := pachClient.ListFile(in.Cron.Repo, "master", "")
if err != nil && !isNilBranchErr(err) {
return err
} else if err != nil || len(files) == 0 {
// File not found, this happens the first time the pipeline is run
latestTime, err = types.TimestampFromProto(in.Cron.Start)
if err != nil {
return err
}
} else {
// Take the name of the most recent file as the latest timestamp
// ListFile returns the files in lexicographical order, and the RFC3339 format goes
// from largest unit of time to smallest, so the most recent file will be the last one
latestTime, err = time.Parse(time.RFC3339, path.Base(files[len(files)-1].File.Path))
if err != nil {
return err
}
}
for {
// get the time of the next time from the latest time using the cron schedule
next := schedule.Next(latestTime)
// and wait until then to make the next commit
time.Sleep(time.Until(next))
if err != nil {
return err
}
// We need the DeleteFile and the PutFile to happen in the same commit
_, err = pachClient.StartCommit(in.Cron.Repo, "master")
if err != nil {
return err
}
if in.Cron.Overwrite {
// If we want to "overwrite" the file, we need to delete the file with the previous time
err := pachClient.DeleteFile(in.Cron.Repo, "master", latestTime.Format(time.RFC3339))
if err != nil && !isNotFoundErr(err) && !isNilBranchErr(err) {
return fmt.Errorf("delete error %v", err)
}
}
// Put in an empty file named by the timestamp
_, err = pachClient.PutFile(in.Cron.Repo, "master", next.Format(time.RFC3339), strings.NewReader(""))
if err != nil {
return fmt.Errorf("put error %v", err)
}
err = pachClient.FinishCommit(in.Cron.Repo, "master")
if err != nil {
return err
}
// set latestTime to the next time
latestTime = next
}
}
|
https://github.com/moul/sapin/blob/03dc419f50a637fd6fd353ffa8f4c93b4f3a80a6/sapin.go#L35-L37
|
func (s *Sapin) GetMaxSize() int {
return s.GetLineSize(s.Size-1, s.Size+3)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L179-L192
|
func (c *ServerConfig) VerifyJoinExisting() error {
// The member has announced its peer urls to the cluster before starting; no need to
// set the configuration again.
if err := c.hasLocalMember(); err != nil {
return err
}
if checkDuplicateURL(c.InitialPeerURLsMap) {
return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
}
if c.DiscoveryURL != "" {
return fmt.Errorf("discovery URL should not be set when joining existing initial cluster")
}
return nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L257-L282
|
func FillStyle(gc draw2d.GraphicContext, x, y, width, height float64) {
sx, sy := width/232, height/220
gc.SetLineWidth(width / 40)
draw2dkit.Rectangle(gc, x+sx*0, y+sy*12, x+sx*232, y+sy*70)
var wheel1, wheel2 draw2d.Path
wheel1.ArcTo(x+sx*52, y+sy*70, sx*40, sy*40, 0, 2*math.Pi)
wheel2.ArcTo(x+sx*180, y+sy*70, sx*40, sy*40, 0, -2*math.Pi)
gc.SetFillRule(draw2d.FillRuleEvenOdd)
gc.SetFillColor(color.NRGBA{0, 0xB2, 0, 0xFF})
gc.SetStrokeColor(image.Black)
gc.FillStroke(&wheel1, &wheel2)
draw2dkit.Rectangle(gc, x, y+sy*140, x+sx*232, y+sy*198)
wheel1.Clear()
wheel1.ArcTo(x+sx*52, y+sy*198, sx*40, sy*40, 0, 2*math.Pi)
wheel2.Clear()
wheel2.ArcTo(x+sx*180, y+sy*198, sx*40, sy*40, 0, -2*math.Pi)
gc.SetFillRule(draw2d.FillRuleWinding)
gc.SetFillColor(color.NRGBA{0, 0, 0xE5, 0xFF})
gc.FillStroke(&wheel1, &wheel2)
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L616-L636
|
func (g *Guest) Logout() error {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
jobHandle = C.VixVM_LogoutFromGuest(g.handle,
nil, // callbackProc
nil) // clientData
defer C.Vix_ReleaseHandle(jobHandle)
err = C.vix_job_wait(jobHandle)
if C.VIX_OK != err {
return &Error{
Operation: "guest.Logout",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return nil
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L852-L854
|
func (g *Glg) Warnf(format string, val ...interface{}) error {
return g.out(WARN, format, val...)
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/struct.go#L87-L117
|
func newStructType(t reflect.Type, c map[reflect.Type]*structType) *structType {
if s := c[t]; s != nil {
return s
}
n := t.NumField()
s := &structType{
fields: make([]structField, 0, n),
fieldsByName: make(map[string]*structField),
}
c[t] = s
for i := 0; i != n; i++ {
ft := t.Field(i)
if ft.Anonymous || len(ft.PkgPath) != 0 { // anonymous or non-exported
continue
}
sf := makeStructField(ft, c)
if sf.name == "-" { // skip
continue
}
s.fields = append(s.fields, sf)
s.fieldsByName[sf.name] = &s.fields[len(s.fields)-1]
}
return s
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/strkey/main.go#L29-L61
|
func Decode(expected VersionByte, src string) ([]byte, error) {
if err := checkValidVersionByte(expected); err != nil {
return nil, err
}
raw, err := base32.StdEncoding.DecodeString(src)
if err != nil {
return nil, err
}
if len(raw) < 3 {
return nil, fmt.Errorf("encoded value is %d bytes; minimum valid length is 3", len(raw))
}
// decode into components
version := VersionByte(raw[0])
vp := raw[0 : len(raw)-2]
payload := raw[1 : len(raw)-2]
checksum := raw[len(raw)-2:]
// ensure version byte is expected
if version != expected {
return nil, ErrInvalidVersionByte
}
// ensure checksum is valid
if err := crc16.Validate(vp, checksum); err != nil {
return nil, err
}
// if we made it through the gaunlet, return the decoded value
return payload, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/update_command.go#L27-L40
|
func NewUpdateCommand() cli.Command {
return cli.Command{
Name: "update",
Usage: "update an existing key with a given value",
ArgsUsage: "<key> <value>",
Flags: []cli.Flag{
cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live in seconds"},
},
Action: func(c *cli.Context) error {
updateCommandFunc(c, mustNewKeyAPI(c))
return nil
},
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/grpcutil/buffer.go#L14-L18
|
func NewBufPool(size int) *BufPool {
return &BufPool{sync.Pool{
New: func() interface{} { return make([]byte, size) },
}}
}
|
https://github.com/alecthomas/mph/blob/cf7b0cd2d9579868ec2a49493fd62b2e28bcb336/chd_builder.go#L58-L89
|
func tryHash(hasher *chdHasher, seen map[uint64]bool, keys [][]byte, values [][]byte, indices []uint16, bucket *bucket, ri uint16, r uint64) bool {
// Track duplicates within this bucket.
duplicate := make(map[uint64]bool)
// Make hashes for each entry in the bucket.
hashes := make([]uint64, len(bucket.keys))
for i, k := range bucket.keys {
h := hasher.Table(r, k)
hashes[i] = h
if seen[h] {
return false
}
if duplicate[h] {
return false
}
duplicate[h] = true
}
// Update seen hashes
for _, h := range hashes {
seen[h] = true
}
// Add the hash index.
indices[bucket.index] = ri
// Update the the hash table.
for i, h := range hashes {
keys[h] = bucket.keys[i]
values[h] = bucket.values[i]
}
return true
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L79-L83
|
func CheckBaggageValues(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckBaggageValues = val
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L308-L310
|
func (c *Client) Metric(rtype string) (common.Metric, error) {
return c.metric(rtype)
}
|
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L156-L161
|
func FileExists(filePath string) bool {
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
return true
}
return false
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/schema/lexer.go#L211-L223
|
func (l *Lexer) Offset() int {
// find last line break
lineoffset := strings.LastIndex(l.input[:l.Pos], "\n")
if lineoffset != -1 {
// calculate current offset from last line break
return l.Pos - lineoffset
}
// first line
return l.Pos
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L67-L72
|
func (o *KubernetesClientOptions) Client(t Type) (ClientInterface, error) {
if o.inMemory {
return newDummyClient(t), nil
}
return o.newCRDClient(t)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pretty/pretty.go#L241-L243
|
func CompactPrintFile(f *pfs.File) string {
return fmt.Sprintf("%s@%s:%s", f.Commit.Repo.Name, f.Commit.ID, f.Path)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps/util.go#L91-L122
|
func ValidateGitCloneURL(url string) error {
exampleURL := "https://github.com/org/foo.git"
if url == "" {
return fmt.Errorf("clone URL is missing (example clone URL %v)", exampleURL)
}
// Use the git client's validator to make sure its a valid URL
o := &git.CloneOptions{
URL: url,
}
if err := o.Validate(); err != nil {
return err
}
// Make sure its the type that we want. Of the following we
// only accept the 'clone' type of url:
// git_url: "git://github.com/sjezewski/testgithook.git",
// ssh_url: "git@github.com:sjezewski/testgithook.git",
// clone_url: "https://github.com/sjezewski/testgithook.git",
// svn_url: "https://github.com/sjezewski/testgithook",
invalidErr := fmt.Errorf("clone URL is missing .git suffix (example clone URL %v)", exampleURL)
if !strings.HasSuffix(url, ".git") {
// svn_url case
return invalidErr
}
if !strings.HasPrefix(url, "https://") {
// git_url or ssh_url cases
return invalidErr
}
return nil
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/common.go#L68-L78
|
func uncapitalizeYs(word *snowballword.SnowballWord) {
for i, r := range word.RS {
// (Note: Y & y unicode code points = 89 & 121)
if r == 89 {
word.RS[i] = 121
}
}
return
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L57-L206
|
func (p *ParamAnalyzer) Analyze() {
// Order params using their length so "foo[bar]" is analyzed before "foo"
params := p.rawParams
paths := make([]string, len(params))
i := 0
for n := range params {
paths[i] = n
i++
}
sort.Strings(paths)
sort.Sort(ByReverseLength(paths))
rawLeafParams := []string{}
for _, p := range paths {
hasLeaf := false
for _, r := range rawLeafParams {
if strings.HasSuffix(r, "]") && strings.HasPrefix(r, p) {
hasLeaf = true
break
}
}
if hasLeaf {
continue
}
rawLeafParams = append(rawLeafParams, p)
}
sort.Strings(rawLeafParams)
p.leafParamNames = rawLeafParams
// Iterate through all params and build corresponding ActionParam structs
p.parsed = map[string]*gen.ActionParam{}
top := map[string]*gen.ActionParam{}
for _, path := range paths {
if strings.HasSuffix(path, "[*]") {
// Cheat a little bit - there a couple of cases where parent type is
// Hash instead of Enumerable, make that enumerable everywhere
// There are also cases where there's no parent path, fix that up also
matches := parentPathRegexp.FindStringSubmatch(path)
if hashParam, ok := params[matches[1]].(map[string]interface{}); ok {
hashParam["class"] = "Enumerable"
} else {
// Create parent
rawParams := map[string]interface{}{}
parentPath := matches[1]
p.parsed[parentPath] = p.newParam(parentPath, rawParams,
new(gen.EnumerableDataType))
if parentPathRegexp.FindStringSubmatch(parentPath) == nil {
top[parentPath] = p.parsed[parentPath]
}
}
continue
}
var child *gen.ActionParam
origPath := path
origParam := params[path].(map[string]interface{})
matches := parentPathRegexp.FindStringSubmatch(path)
isTop := (matches == nil)
if prev, ok := p.parsed[path]; ok {
if isTop {
top[path] = prev
}
continue
}
var branch []*gen.ActionParam
for matches != nil {
param := params[path].(map[string]interface{})
parentPath := matches[1]
var isArrayChild bool
if strings.HasSuffix(parentPath, "[]") {
isArrayChild = true
}
if parent, ok := p.parsed[parentPath]; ok {
a, ok := parent.Type.(*gen.ArrayDataType)
if ok {
parent = a.ElemType
}
child = p.parseParam(path, param, child)
if !parent.Mandatory {
// Make required fields of optional hashes optional.
child.Mandatory = false
}
branch = append(branch, child)
if _, ok = parent.Type.(*gen.EnumerableDataType); !ok {
o := parent.Type.(*gen.ObjectDataType)
o.Fields = appendSorted(o.Fields, child)
p.parsed[path] = child
}
break // No need to keep going back, we already have a parent
} else {
child = p.parseParam(path, param, child)
branch = append(branch, child)
p.parsed[path] = child
if isArrayChild {
// Generate array item as it's not listed explicitly in JSON
itemPath := matches[1] + "[item]"
typeName := p.typeName(matches[1])
parent = p.newParam(itemPath, map[string]interface{}{},
&gen.ObjectDataType{typeName, []*gen.ActionParam{child}})
p.parsed[parentPath] = parent
child = parent
branch = append(branch, child)
parentPath = parentPath[:len(parentPath)-2]
}
}
path = parentPath
matches = parentPathRegexp.FindStringSubmatch(path)
}
if isTop {
if _, ok := p.parsed[path]; !ok {
actionParam := p.parseParam(path, origParam, nil)
p.parsed[path] = actionParam
}
top[path] = p.parsed[path]
} else {
matches := rootRegexp.FindStringSubmatch(origPath)
rootPath := matches[1]
if _, ok := p.parsed[rootPath]; !ok {
p.parsed[rootPath] = p.parseParam(rootPath,
params[rootPath].(map[string]interface{}), child)
}
actionParam, _ := p.parsed[rootPath]
mandatory := actionParam.Mandatory
if len(branch) > 0 {
for i := len(branch) - 1; i >= 0; i-- {
p := branch[i]
if mandatory {
if !p.Mandatory {
mandatory = false
}
} else {
p.Mandatory = false
}
}
}
}
}
// Now do a second pass on parsed params to generate their declarations
p.ParamTypes = make(map[string]*gen.ObjectDataType)
for _, param := range top {
p.recordTypes(param.Type)
}
i = 0
res := make([]*gen.ActionParam, len(top))
for _, param := range top {
res[i] = param
i++
}
sort.Sort(gen.ByName(res))
p.Params = res
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L325-L328
|
func (txn *Txn) SetWithMeta(key, val []byte, meta byte) error {
e := &Entry{Key: key, Value: val, UserMeta: meta}
return txn.SetEntry(e)
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router.go#L44-L58
|
func (rs *Routers) Add(r router.Router, h HandlerFunc, v view.View) {
defer rs.Unlock()
rs.Lock()
s := struct {
r router.Router
v view.View
h HandlerFunc
}{r, v, h}
// simple will full-match the path
if sr, ok := r.(*router.Base); ok {
rs.s[sr.Path] = s
return
}
rs.l.PushFront(s)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L6772-L6776
|
func (v EventRequestIntercepted) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork52(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L71-L76
|
func (r region) Uint32() uint32 {
if r.typ.Kind != KindUint || r.typ.Size != 4 {
panic("bad uint32 type " + r.typ.Name)
}
return r.p.proc.ReadUint32(r.a)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L263-L269
|
func SetTiming(animationID string, duration float64, delay float64) *SetTimingParams {
return &SetTimingParams{
AnimationID: animationID,
Duration: duration,
Delay: delay,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L235-L277
|
func (c *Config) GetPolicy(org, repo, branch string, b Branch) (*Policy, error) {
policy := b.Policy
// Automatically require contexts from prow which must always be present
if prowContexts, _, _ := BranchRequirements(org, repo, branch, c.Presubmits); len(prowContexts) > 0 {
// Error if protection is disabled
if policy.Protect != nil && !*policy.Protect {
return nil, fmt.Errorf("required prow jobs require branch protection")
}
ps := Policy{
RequiredStatusChecks: &ContextPolicy{
Contexts: prowContexts,
},
}
// Require protection by default if ProtectTested is true
if c.BranchProtection.ProtectTested {
yes := true
ps.Protect = &yes
}
policy = policy.Apply(ps)
}
if policy.Protect != nil && !*policy.Protect {
// Ensure that protection is false => no protection settings
var old *bool
old, policy.Protect = policy.Protect, old
switch {
case policy.defined() && c.BranchProtection.AllowDisabledPolicies:
logrus.Warnf("%s/%s=%s defines a policy but has protect: false", org, repo, branch)
policy = Policy{
Protect: policy.Protect,
}
case policy.defined():
return nil, fmt.Errorf("%s/%s=%s defines a policy, which requires protect: true", org, repo, branch)
}
policy.Protect = old
}
if !policy.defined() {
return nil, nil
}
return &policy, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry.go#L133-L137
|
func RetryLeaseClient(c *Client) pb.LeaseClient {
return &retryLeaseClient{
lc: pb.NewLeaseClient(c.conn),
}
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/patch_apps_app_routes_route_parameters.go#L89-L92
|
func (o *PatchAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *PatchAppsAppRoutesRouteParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/loadbalancer.go#L63-L69
|
func (c *Client) CreateLoadbalancer(dcid string, request Loadbalancer) (*Loadbalancer, error) {
url := lbalColPath(dcid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Loadbalancer{}
err := c.client.Post(url, request, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L662-L685
|
func (w *watchGrpcStream) dispatchEvent(pbresp *pb.WatchResponse) bool {
events := make([]*Event, len(pbresp.Events))
for i, ev := range pbresp.Events {
events[i] = (*Event)(ev)
}
// TODO: return watch ID?
wr := &WatchResponse{
Header: *pbresp.Header,
Events: events,
CompactRevision: pbresp.CompactRevision,
Created: pbresp.Created,
Canceled: pbresp.Canceled,
cancelReason: pbresp.CancelReason,
}
// watch IDs are zero indexed, so request notify watch responses are assigned a watch ID of -1 to
// indicate they should be broadcast.
if wr.IsProgressNotify() && pbresp.WatchId == -1 {
return w.broadcastResponse(wr)
}
return w.unicastResponse(wr, pbresp.WatchId)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L182-L188
|
func (l *TestListener) Accept() (net.Conn, error) {
conn := <-l.connCh
if conn == nil {
return nil, errors.New("Accept() has already been called on this TestListener")
}
return conn, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_windows.go#L18-L26
|
func GetState(fd int) (*State, error) {
state, err := terminal.GetState(fd)
if err != nil {
return nil, err
}
currentState := State(*state)
return ¤tState, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/error.go#L60-L64
|
func AssertTruef(b bool, format string, args ...interface{}) {
if !b {
log.Fatalf("%+v", errors.Errorf(format, args...))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L128-L152
|
func (t *ScopeType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ScopeType(in.String()) {
case ScopeTypeGlobal:
*t = ScopeTypeGlobal
case ScopeTypeLocal:
*t = ScopeTypeLocal
case ScopeTypeWith:
*t = ScopeTypeWith
case ScopeTypeClosure:
*t = ScopeTypeClosure
case ScopeTypeCatch:
*t = ScopeTypeCatch
case ScopeTypeBlock:
*t = ScopeTypeBlock
case ScopeTypeScript:
*t = ScopeTypeScript
case ScopeTypeEval:
*t = ScopeTypeEval
case ScopeTypeModule:
*t = ScopeTypeModule
default:
in.AddError(errors.New("unknown ScopeType value"))
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/app_id.go#L22-L28
|
func appID(fullAppID string) string {
_, dom, dis := parseFullAppID(fullAppID)
if dom != "" {
return dom + ":" + dis
}
return dis
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/keypair/main.go#L62-L70
|
func Master(networkPassphrase string) KP {
kp, err := FromRawSeed(network.ID(networkPassphrase))
if err != nil {
panic(err)
}
return kp
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L241-L243
|
func (la *LogAdapter) Errorm(m *Attrs, msg string, a ...interface{}) error {
return la.Log(LevelError, m, msg, a...)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L120-L131
|
func compareMajorMinorVersion(a, b *semver.Version) int {
na := &semver.Version{Major: a.Major, Minor: a.Minor}
nb := &semver.Version{Major: b.Major, Minor: b.Minor}
switch {
case na.LessThan(*nb):
return -1
case nb.LessThan(*na):
return 1
default:
return 0
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L79-L81
|
func (s *Storage) DeleteResource(name string) error {
return s.resources.Delete(name)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.