_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/types.go#L79-L81
|
func (t *VersionRunningStatus) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/flakyjob-reporter.go#L102-L144
|
func (fjr *FlakyJobReporter) parseFlakyJobs(jsonIn []byte) ([]*FlakyJob, error) {
var flakeMap map[string]*FlakyJob
err := json.Unmarshal(jsonIn, &flakeMap)
if err != nil || flakeMap == nil {
return nil, fmt.Errorf("error unmarshaling flaky jobs json: %v", err)
}
flakyJobs := make([]*FlakyJob, 0, len(flakeMap))
for job, fj := range flakeMap {
if job == "" {
glog.Errorf("Flaky jobs json contained a job with an empty jobname.\n")
continue
}
if fj == nil {
glog.Errorf("Flaky jobs json has invalid data for job '%s'.\n", job)
continue
}
if fj.Consistency == nil {
glog.Errorf("Flaky jobs json has no 'consistency' field for job '%s'.\n", job)
continue
}
if fj.FlakeCount == nil {
glog.Errorf("Flaky jobs json has no 'flakes' field for job '%s'.\n", job)
continue
}
if fj.FlakyTests == nil {
glog.Errorf("Flaky jobs json has no 'flakiest' field for job '%s'.\n", job)
continue
}
fj.Name = job
fj.reporter = fjr
flakyJobs = append(flakyJobs, fj)
}
sort.SliceStable(flakyJobs, func(i, j int) bool {
if *flakyJobs[i].FlakeCount == *flakyJobs[j].FlakeCount {
return *flakyJobs[i].Consistency < *flakyJobs[j].Consistency
}
return *flakyJobs[i].FlakeCount > *flakyJobs[j].FlakeCount
})
return flakyJobs, nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L931-L965
|
func (r *Raft) processLog(l *Log, future *logFuture) {
switch l.Type {
case LogBarrier:
// Barrier is handled by the FSM
fallthrough
case LogCommand:
// Forward to the fsm handler
select {
case r.fsmMutateCh <- &commitTuple{l, future}:
case <-r.shutdownCh:
if future != nil {
future.respond(ErrRaftShutdown)
}
}
// Return so that the future is only responded to
// by the FSM handler when the application is done
return
case LogConfiguration:
case LogAddPeerDeprecated:
case LogRemovePeerDeprecated:
case LogNoop:
// Ignore the no-op
default:
panic(fmt.Errorf("unrecognized log type: %#v", l))
}
// Invoke the future if given
if future != nil {
future.respond(nil)
}
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L61-L66
|
func (st *State) PushFrame() *frame.Frame {
f := frame.New(st.framestack)
st.frames.Push(f)
f.SetMark(st.frames.Size())
return f
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3114-L3118
|
func (v *Property) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss27(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L364-L447
|
func (g *Gateway) LeaderAddress() (string, error) {
// If we aren't clustered, return an error.
if g.memoryDial != nil {
return "", fmt.Errorf("Node is not clustered")
}
ctx, cancel := context.WithTimeout(g.ctx, 5*time.Second)
defer cancel()
// If this is a raft node, return the address of the current leader, or
// wait a bit until one is elected.
if g.raft != nil {
for ctx.Err() == nil {
address := string(g.raft.Raft().Leader())
if address != "" {
return address, nil
}
time.Sleep(time.Second)
}
return "", ctx.Err()
}
// If this isn't a raft node, contact a raft node and ask for the
// address of the current leader.
config, err := tlsClientConfig(g.cert)
if err != nil {
return "", err
}
addresses := []string{}
err = g.db.Transaction(func(tx *db.NodeTx) error {
nodes, err := tx.RaftNodes()
if err != nil {
return err
}
for _, node := range nodes {
addresses = append(addresses, node.Address)
}
return nil
})
if err != nil {
return "", errors.Wrap(err, "Failed to fetch raft nodes addresses")
}
if len(addresses) == 0 {
// This should never happen because the raft_nodes table should
// be never empty for a clustered node, but check it for good
// measure.
return "", fmt.Errorf("No raft node known")
}
for _, address := range addresses {
url := fmt.Sprintf("https://%s%s", address, databaseEndpoint)
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
request = request.WithContext(ctx)
client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}}
response, err := client.Do(request)
if err != nil {
logger.Debugf("Failed to fetch leader address from %s", address)
continue
}
if response.StatusCode != http.StatusOK {
logger.Debugf("Request for leader address from %s failed", address)
continue
}
info := map[string]string{}
err = shared.ReadToJSON(response.Body, &info)
if err != nil {
logger.Debugf("Failed to parse leader address from %s", address)
continue
}
leader := info["leader"]
if leader == "" {
logger.Debugf("Raft node %s returned no leader address", address)
continue
}
return leader, nil
}
return "", fmt.Errorf("RAFT cluster is unavailable")
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/types.go#L233-L272
|
func (d *DecorationConfig) ApplyDefault(def *DecorationConfig) *DecorationConfig {
if d == nil && def == nil {
return nil
}
var merged DecorationConfig
if d != nil {
merged = *d
} else {
merged = *def
}
if d == nil || def == nil {
return &merged
}
merged.UtilityImages = merged.UtilityImages.ApplyDefault(def.UtilityImages)
merged.GCSConfiguration = merged.GCSConfiguration.ApplyDefault(def.GCSConfiguration)
if merged.Timeout.Duration == 0 {
merged.Timeout = def.Timeout
}
if merged.GracePeriod.Duration == 0 {
merged.GracePeriod = def.GracePeriod
}
if merged.GCSCredentialsSecret == "" {
merged.GCSCredentialsSecret = def.GCSCredentialsSecret
}
if len(merged.SSHKeySecrets) == 0 {
merged.SSHKeySecrets = def.SSHKeySecrets
}
if len(merged.SSHHostFingerprints) == 0 {
merged.SSHHostFingerprints = def.SSHHostFingerprints
}
if merged.SkipCloning == nil {
merged.SkipCloning = def.SkipCloning
}
if merged.CookiefileSecret == "" {
merged.CookiefileSecret = def.CookiefileSecret
}
return &merged
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/endpoint.go#L302-L319
|
func (c *endpointClient) Info(instance *ServiceInstance, requestID string) ([]map[string]string, error) {
log.Debugf("Attempting to call info of service instance %q at %q api", instance.Name, instance.ServiceName)
url := "/resources/" + instance.GetIdentifier()
resp, err := c.issueRequest(url, "GET", nil, requestID)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, nil
}
result := []map[string]string{}
err = c.jsonFromResponse(resp, &result)
if err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/secp256k1.go#L20-L28
|
func GenerateSecp256k1Key(src io.Reader) (PrivKey, PubKey, error) {
privk, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, nil, err
}
k := (*Secp256k1PrivateKey)(privk)
return k, k.GetPublic(), nil
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L119-L129
|
func VerifyJSON(expectedJSON string) http.HandlerFunc {
return CombineHandlers(
VerifyMimeType("application/json"),
func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
req.Body.Close()
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(MatchJSON(expectedJSON), "JSON Mismatch")
},
)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_post.go#L505-L513
|
func internalClusterContainerMovedPost(d *Daemon, r *http.Request) Response {
project := projectParam(r)
containerName := mux.Vars(r)["name"]
err := containerPostCreateContainerMountPoint(d, project, containerName)
if err != nil {
return SmartError(err)
}
return EmptySyncResponse
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/easyjson.go#L877-L881
|
func (v Frame) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCdp2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3989-L3993
|
func (v *EventResumed) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger39(&r, v)
return r.Error()
}
|
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/dbprovider/dbprovider.go#L62-L95
|
func InitDbProvider(name string, configFilePath string) (DbInterface, error) {
var dbprovider DbInterface
if name == "" {
logger.Get().Info("No providers specified.")
return nil, nil
}
var err error
if configFilePath != "" {
config, err := os.Open(configFilePath)
if err != nil {
logger.Get().Critical("Couldn't open Db provider configuration %s: %v",
configFilePath, err)
}
defer config.Close()
dbprovider, err = GetDbProvider(name, config)
} else {
// Pass explicit nil so providers can actually check for nil. See
// "Why is my nil error value not equal to nil?" in golang.org/doc/faq.
dbprovider, err = GetDbProvider(name, nil)
}
if err != nil {
return nil, fmt.Errorf("could not initialize Db Provider %q: %v", name, err)
}
if dbprovider == nil {
return nil, fmt.Errorf("unknown Db Provider %q", name)
}
return dbprovider, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L82-L96
|
func (t *Tracer) Push(name string) {
// get context
var ctx opentracing.SpanContext
if len(t.spans) > 0 {
ctx = t.Last().Context()
} else {
ctx = t.root.Context()
}
// create new span
span := opentracing.StartSpan(name, opentracing.ChildOf(ctx))
// push span
t.spans = append(t.spans, span)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L26-L54
|
func (op *operation) AddHandler(function func(api.Operation)) (*EventTarget, error) {
// Make sure we have a listener setup
err := op.setupListener()
if err != nil {
return nil, err
}
// Make sure we're not racing with ourselves
op.handlerLock.Lock()
defer op.handlerLock.Unlock()
// If we're done already, just return
if op.StatusCode.IsFinal() {
return nil, nil
}
// Wrap the function to filter unwanted messages
wrapped := func(event api.Event) {
newOp := api.Operation{}
err := json.Unmarshal(event.Metadata, &newOp)
if err != nil || newOp.ID != op.ID {
return
}
function(newOp)
}
return op.listener.AddHandler([]string{"operation"}, wrapped)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L126-L153
|
func (c *Cluster) ImageSourceGet(imageID int) (int, api.ImageSource, error) {
q := `SELECT id, server, protocol, certificate, alias FROM images_source WHERE image_id=?`
id := 0
protocolInt := -1
result := api.ImageSource{}
arg1 := []interface{}{imageID}
arg2 := []interface{}{&id, &result.Server, &protocolInt, &result.Certificate, &result.Alias}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err != nil {
if err == sql.ErrNoRows {
return -1, api.ImageSource{}, ErrNoSuchObject
}
return -1, api.ImageSource{}, err
}
protocol, found := ImageSourceProtocol[protocolInt]
if !found {
return -1, api.ImageSource{}, fmt.Errorf("Invalid protocol: %d", protocolInt)
}
result.Protocol = protocol
return id, result, nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/creds.go#L153-L155
|
func (permaCreds *Credentials) CreateTemporaryCredentials(duration time.Duration, scopes ...string) (tempCreds *Credentials, err error) {
return permaCreds.CreateNamedTemporaryCredentials("", duration, scopes...)
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L114-L118
|
func (r *MapErrorRegistry) MustAddHandler(code int, handler func(body []byte) error) {
if err := r.AddHandler(code, handler); err != nil {
panic(err)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/tot.go#L51-L56
|
func PresubmitToJobSpec(pre config.Presubmit) *downwardapi.JobSpec {
return &downwardapi.JobSpec{
Type: prowapi.PresubmitJob,
Job: pre.Name,
}
}
|
https://github.com/anmitsu/go-shlex/blob/648efa622239a2f6ff949fed78ee37b48d499ba4/shlex.go#L74-L76
|
func NewLexerString(s string, posix, whitespacesplit bool) *Lexer {
return NewLexer(strings.NewReader(s), posix, whitespacesplit)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/delete_apps_app_routes_route_parameters.go#L104-L107
|
func (o *DeleteAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *DeleteAppsAppRoutesRouteParams {
o.SetHTTPClient(client)
return o
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/struct.go#L128-L147
|
func (cache *structTypeCache) lookup(t reflect.Type) (s *structType) {
cache.mutex.RLock()
s = cache.store[t]
cache.mutex.RUnlock()
if s == nil {
// There's a race confition here where this value may be generated
// multiple times.
// The impact in practice is really small as it's unlikely to happen
// often, we take the approach of keeping the logic simple and avoid
// a more complex synchronization logic required to solve this edge
// case.
s = newStructType(t, map[reflect.Type]*structType{})
cache.mutex.Lock()
cache.store[t] = s
cache.mutex.Unlock()
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L463-L481
|
func (f *FakeClient) CreateProjectCard(columnID int, projectCard github.ProjectCard) (*github.ProjectCard, error) {
if f.ColumnCardsMap == nil {
f.ColumnCardsMap = make(map[int][]github.ProjectCard)
}
for project, columnIDMap := range f.ColumnIDMap {
columnName, exists := columnIDMap[columnID]
if exists {
f.ColumnCardsMap[columnID] = append(
f.ColumnCardsMap[columnID],
projectCard,
)
f.Column = columnName
f.Project = project
return &projectCard, nil
}
}
return nil, fmt.Errorf("Provided column %d does not exist, ColumnIDMap is %v", columnID, f.ColumnIDMap)
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L168-L173
|
func DefaultVM(tx *Xslate, args Args) error {
dvm := vm.NewVM()
dvm.Loader = tx.Loader
tx.VM = dvm
return nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L98-L101
|
func (wb *WriteBatch) Set(k, v []byte, meta byte) error {
e := &Entry{Key: k, Value: v, UserMeta: meta}
return wb.SetEntry(e)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/capability.go#L60-L82
|
func UpdateCapability(lg *zap.Logger, v *semver.Version) {
if v == nil {
// if recovered but version was never set by cluster
return
}
enableMapMu.Lock()
if curVersion != nil && !curVersion.LessThan(*v) {
enableMapMu.Unlock()
return
}
curVersion = v
enabledMap = capabilityMaps[curVersion.String()]
enableMapMu.Unlock()
if lg != nil {
lg.Info(
"enabled capabilities for version",
zap.String("cluster-version", version.Cluster(v.String())),
)
} else {
plog.Infof("enabled capabilities for version %s", version.Cluster(v.String()))
}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/selection_matchers.go#L36-L38
|
func HaveCSS(property string, value string) types.GomegaMatcher {
return &internal.HaveCSSMatcher{ExpectedProperty: property, ExpectedValue: value}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/layertree.go#L149-L158
|
func (p *MakeSnapshotParams) Do(ctx context.Context) (snapshotID SnapshotID, err error) {
// execute
var res MakeSnapshotReturns
err = cdp.Execute(ctx, CommandMakeSnapshot, p, &res)
if err != nil {
return "", err
}
return res.SnapshotID, nil
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/utils.go#L41-L47
|
func HashPassword(password []byte, salt []byte) (hash []byte, err error) {
hash, err = scrypt.Key(password, salt, N, R, P, KEYLENGTH)
if err != nil {
return nil, err
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L231-L234
|
func (p EmulateNetworkConditionsParams) WithConnectionType(connectionType ConnectionType) *EmulateNetworkConditionsParams {
p.ConnectionType = connectionType
return &p
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L6139-L6146
|
func (r *Network) Locator(api *API) *NetworkLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.NetworkLocator(l["href"])
}
}
return nil
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/utils.go#L95-L114
|
func EncodeOAuth2Code(clientID, redirectURI, userID, sharedKey string) (code string, err error) {
rand := RandStringBytesMaskImprSrc(20)
exp := time.Now().Add(time.Minute * 10).String()
response := NewResponse(clientID, redirectURI, userID, exp, rand)
jresponse, err := json.Marshal(response)
if err != nil {
log.Printf("Error: %v", err)
}
j64response := base64.StdEncoding.EncodeToString(jresponse)
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS512, Key: []byte(sharedKey)}, nil)
if err != nil {
log.Printf("Error: %v", err)
}
object, err := signer.Sign([]byte(j64response))
if err != nil {
log.Printf("Error: %v", err)
}
code, err = object.CompactSerialize()
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L217-L220
|
func (p CompileScriptParams) WithExecutionContextID(executionContextID ExecutionContextID) *CompileScriptParams {
p.ExecutionContextID = executionContextID
return &p
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_dest.go#L382-L401
|
func (d *ostreeImageDestination) PutManifest(ctx context.Context, manifestBlob []byte) error {
d.manifest = string(manifestBlob)
if err := json.Unmarshal(manifestBlob, &d.schema); err != nil {
return err
}
manifestPath := filepath.Join(d.tmpDirPath, d.ref.manifestPath())
if err := ensureParentDirectoryExists(manifestPath); err != nil {
return err
}
digest, err := manifest.Digest(manifestBlob)
if err != nil {
return err
}
d.digest = digest
return ioutil.WriteFile(manifestPath, manifestBlob, 0644)
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/options.go#L65-L69
|
func HTTPClient(client *http.Client) Option {
return func(c *config) {
c.HTTPClient = client
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3146-L3154
|
func (u ManageOfferResult) MustSuccess() ManageOfferSuccessResult {
val, ok := u.GetSuccess()
if !ok {
panic("arm Success is not set")
}
return val
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1829-L1837
|
func (u OperationBody) MustCreateAccountOp() CreateAccountOp {
val, ok := u.GetCreateAccountOp()
if !ok {
panic("arm CreateAccountOp is not set")
}
return val
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-decode.go#L837-L858
|
func consumeAny(typ3 Typ3, bz []byte) (n int, err error) {
var _n int
switch typ3 {
case Typ3_Varint:
_, _n, err = DecodeVarint(bz)
case Typ3_8Byte:
_, _n, err = DecodeInt64(bz)
case Typ3_ByteLength:
_, _n, err = DecodeByteSlice(bz)
case Typ3_4Byte:
_, _n, err = DecodeInt32(bz)
default:
err = fmt.Errorf("invalid typ3 bytes %v", typ3)
return
}
if err != nil {
// do not slide
return
}
slide(&bz, &n, _n)
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L975-L979
|
func (pr *progressRequest) toPB() *pb.WatchRequest {
req := &pb.WatchProgressRequest{}
cr := &pb.WatchRequest_ProgressRequest{ProgressRequest: req}
return &pb.WatchRequest{RequestUnion: cr}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L612-L639
|
func serviceInstanceGrantTeam(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
instanceName := r.URL.Query().Get(":instance")
serviceName := r.URL.Query().Get(":service")
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceInstanceUpdateGrant,
contextsForServiceInstance(serviceInstance, serviceName)...,
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: serviceInstanceTarget(serviceName, instanceName),
Kind: permission.PermServiceInstanceUpdateGrant,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermServiceInstanceReadEvents,
contextsForServiceInstance(serviceInstance, serviceName)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
teamName := r.URL.Query().Get(":team")
return serviceInstance.Grant(teamName)
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L280-L285
|
func (c *Client) GetUser(usrid string) (*User, error) {
url := umUsersPath(usrid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &User{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L116-L121
|
func (p *Process) ReadUintptr(a Address) uint64 {
if p.ptrSize == 4 {
return uint64(p.ReadUint32(a))
}
return p.ReadUint64(a)
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L406-L411
|
func (p *Page) CloseWindow() error {
if err := p.session.DeleteWindow(); err != nil {
return fmt.Errorf("failed to close active window: %s", err)
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L268-L280
|
func (s *dockerImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) {
if err := s.c.detectProperties(ctx); err != nil {
return nil, err
}
switch {
case s.c.signatureBase != nil:
return s.getSignaturesFromLookaside(ctx, instanceDigest)
case s.c.supportsSignatures:
return s.getSignaturesFromAPIExtension(ctx, instanceDigest)
default:
return [][]byte{}, nil
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/clonerefs/options.go#L209-L217
|
func (a *orgRepoFormat) Set(value string) error {
templ, err := template.New("format").Parse(value)
if err != nil {
return err
}
a.raw = value
a.format = templ
return nil
}
|
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/result.go#L42-L45
|
func NewOUWCStatusPolicy() *statusPolicy {
pol, _ := NewStatusPolicy([]Status{OK, UNKNOWN, WARNING, CRITICAL})
return pol
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/skiplist.go#L85-L121
|
func NewWithConfig(cfg Config) *Skiplist {
if runtime.GOARCH != "amd64" {
cfg.UseMemoryMgmt = false
}
s := &Skiplist{
Config: cfg,
barrier: newAccessBarrier(cfg.UseMemoryMgmt, cfg.BarrierDestructor),
}
s.newNode = func(itm unsafe.Pointer, level int) *Node {
return allocNode(itm, level, cfg.Malloc)
}
if cfg.UseMemoryMgmt {
s.freeNode = func(n *Node) {
if Debug {
debugMarkFree(n)
}
cfg.Free(unsafe.Pointer(n))
}
} else {
s.freeNode = func(*Node) {}
}
head := allocNode(minItem, MaxLevel, nil)
tail := allocNode(maxItem, MaxLevel, nil)
for i := 0; i <= MaxLevel; i++ {
head.setNext(i, tail, false)
}
s.head = head
s.tail = tail
return s
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L223-L226
|
func (p SetEventListenerBreakpointParams) WithTargetName(targetName string) *SetEventListenerBreakpointParams {
p.TargetName = targetName
return &p
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L201-L204
|
func (c MemoryCache) Delete(key string) error {
delete(c, key)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L349-L352
|
func (p EmulateTouchFromMouseEventParams) WithClickCount(clickCount int64) *EmulateTouchFromMouseEventParams {
p.ClickCount = clickCount
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/balancer.go#L53-L86
|
func (b *builder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer {
bb := &baseBalancer{
id: strconv.FormatInt(time.Now().UnixNano(), 36),
policy: b.cfg.Policy,
name: b.cfg.Name,
lg: b.cfg.Logger,
addrToSc: make(map[resolver.Address]balancer.SubConn),
scToAddr: make(map[balancer.SubConn]resolver.Address),
scToSt: make(map[balancer.SubConn]connectivity.State),
currentConn: nil,
csEvltr: &connectivityStateEvaluator{},
// initialize picker always returns "ErrNoSubConnAvailable"
Picker: picker.NewErr(balancer.ErrNoSubConnAvailable),
}
if bb.lg == nil {
bb.lg = zap.NewNop()
}
// TODO: support multiple connections
bb.mu.Lock()
bb.currentConn = cc
bb.mu.Unlock()
bb.lg.Info(
"built balancer",
zap.String("balancer-id", bb.id),
zap.String("policy", bb.policy.String()),
zap.String("resolver-target", cc.Target()),
)
return bb
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L111-L124
|
func (p *peer) OnGossipBroadcast(src mesh.PeerName, buf []byte) (received mesh.GossipData, err error) {
var set map[mesh.PeerName]int
if err := gob.NewDecoder(bytes.NewReader(buf)).Decode(&set); err != nil {
return nil, err
}
received = p.st.mergeReceived(set)
if received == nil {
p.logger.Printf("OnGossipBroadcast %s %v => delta %v", src, set, received)
} else {
p.logger.Printf("OnGossipBroadcast %s %v => delta %v", src, set, received.(*state).set)
}
return received, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1414-L1418
|
func (v EventReportHeapSnapshotProgress) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler16(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L60-L62
|
func Bool(name string, value bool, usage string) *bool {
return EnvironmentFlags.Bool(name, value, usage)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/template/chroot.go#L27-L51
|
func (l ChrootLoader) Get(path string) (io.Reader, error) {
// Get the full path
path, err := filepath.EvalSymlinks(path)
if err != nil {
return nil, err
}
basePath, err := filepath.EvalSymlinks(l.Path)
if err != nil {
return nil, err
}
// Validate that we're under the expected prefix
if !strings.HasPrefix(path, basePath) {
return nil, fmt.Errorf("Attempting to access a file outside the container")
}
// Open and read the file
buf, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return bytes.NewReader(buf), nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/handler.go#L112-L131
|
func CallerStackHandler(format string, h Handler) Handler {
return FuncHandler(func(r *Record) error {
s := stack.Callers().
TrimBelow(stack.Call(r.CallPC[0])).
TrimRuntime()
if len(s) > 0 {
buf := &bytes.Buffer{}
buf.WriteByte('[')
for i, pc := range s {
if i > 0 {
buf.WriteByte(' ')
}
fmt.Fprintf(buf, format, pc)
}
buf.WriteByte(']')
r.Ctx = append(r.Ctx, "stack", buf.String())
}
return h.Log(r)
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3636-L3640
|
func (v *GetFrameOwnerParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom41(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/cmds.go#L341-L373
|
func SetScopeCmd(noMetrics, noPortForwarding *bool) *cobra.Command {
setScope := &cobra.Command{
Use: "{{alias}} <username> (none|reader|writer|owner) <repo>",
Short: "Set the scope of access that 'username' has to 'repo'",
Long: "Set the scope of access that 'username' has to 'repo'. For " +
"example, 'pachctl auth set github-alice none private-data' prevents " +
"\"github-alice\" from interacting with the \"private-data\" repo in any " +
"way (the default). Similarly, 'pachctl auth set github-alice reader " +
"private-data' would let \"github-alice\" read from \"private-data\" but " +
"not create commits (writer) or modify the repo's access permissions " +
"(owner). Currently all Pachyderm authentication uses GitHub OAuth, so " +
"'username' must be a GitHub username",
Run: cmdutil.RunFixedArgs(3, func(args []string) error {
scope, err := auth.ParseScope(args[1])
if err != nil {
return err
}
username, repo := args[0], args[2]
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
_, err = c.SetScope(c.Ctx(), &auth.SetScopeRequest{
Repo: repo,
Scope: scope,
Username: username,
})
return grpcutil.ScrubGRPC(err)
}),
}
return cmdutil.CreateAlias(setScope, "auth set")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/easyjson.go#L397-L401
|
func (v *EventIssueUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCast4(&r, v)
return r.Error()
}
|
https://github.com/Financial-Times/neo-model-utils-go/blob/aea1e95c83055aaed6761c5e546400dd383fb220/mapper/types.go#L64-L78
|
func FullTypeHierarchy(highestLevelType string) []string {
var typeHierarchy []string
t := strings.Split(highestLevelType, "/")
typeToCheck := t[len(t)-1]
for {
typeHierarchy = append(typeHierarchy, typeToCheck)
parentType := ParentType(typeToCheck)
if parentType != "" {
typeToCheck = parentType
} else {
return TypeURIs(typeHierarchy)
}
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5234-L5253
|
func NewBucketEntry(aType BucketEntryType, value interface{}) (result BucketEntry, err error) {
result.Type = aType
switch BucketEntryType(aType) {
case BucketEntryTypeLiveentry:
tv, ok := value.(LedgerEntry)
if !ok {
err = fmt.Errorf("invalid value, must be LedgerEntry")
return
}
result.LiveEntry = &tv
case BucketEntryTypeDeadentry:
tv, ok := value.(LedgerKey)
if !ok {
err = fmt.Errorf("invalid value, must be LedgerKey")
return
}
result.DeadEntry = &tv
}
return
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/util.go#L108-L114
|
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(buf, &hd)
err := enc.Encode(in)
return buf, err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L98-L106
|
func NewPresubmit(pr github.PullRequest, baseSHA string, job config.Presubmit, eventGUID string) prowapi.ProwJob {
refs := createRefs(pr, baseSHA)
labels := make(map[string]string)
for k, v := range job.Labels {
labels[k] = v
}
labels[github.EventGUID] = eventGUID
return NewProwJob(PresubmitSpec(job, refs), labels)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1130-L1134
|
func (v GetCurrentTimeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation12(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/server.go#L90-L96
|
func (s *Server) Publish(id string, event *Event) {
s.mu.Lock()
defer s.mu.Unlock()
if s.Streams[id] != nil {
s.Streams[id].event <- s.process(event)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L835-L839
|
func (v *GetEventListenersParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomdebugger9(&r, v)
return r.Error()
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/smtp/config.go#L41-L55
|
func (se *SMTPEnvironment) UnmarshalYAML(unmarshal func(interface{}) error) error {
var aux struct {
Env map[string]struct {
Config Config `yaml:"smtp"`
}
}
if err := unmarshal(&aux.Env); err != nil {
return err
}
se.Env = make(map[string]Config)
for env, conf := range aux.Env {
se.Env[env] = conf.Config
}
return nil
}
|
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L381-L398
|
func Encode(img image.Image, format string) ([]byte, error) {
tmp := toNRGBA(img)
i := C.mapnik_image_from_raw(
(*C.uint8_t)(unsafe.Pointer(&tmp.Pix[0])),
C.int(tmp.Bounds().Dx()),
C.int(tmp.Bounds().Dy()),
)
defer C.mapnik_image_free(i)
cformat := C.CString(format)
b := C.mapnik_image_to_blob(i, cformat)
if b == nil {
return nil, errors.New("mapnik: " + C.GoString(C.mapnik_image_last_error(i)))
}
C.free(unsafe.Pointer(cformat))
defer C.mapnik_image_blob_free(b)
return C.GoBytes(unsafe.Pointer(b.ptr), C.int(b.len)), nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/peersjson.go#L15-L46
|
func ReadPeersJSON(path string) (Configuration, error) {
// Read in the file.
buf, err := ioutil.ReadFile(path)
if err != nil {
return Configuration{}, err
}
// Parse it as JSON.
var peers []string
dec := json.NewDecoder(bytes.NewReader(buf))
if err := dec.Decode(&peers); err != nil {
return Configuration{}, err
}
// Map it into the new-style configuration structure. We can only specify
// voter roles here, and the ID has to be the same as the address.
var configuration Configuration
for _, peer := range peers {
server := Server{
Suffrage: Voter,
ID: ServerID(peer),
Address: ServerAddress(peer),
}
configuration.Servers = append(configuration.Servers, server)
}
// We should only ingest valid configurations.
if err := checkConfiguration(configuration); err != nil {
return Configuration{}, err
}
return configuration, nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L313-L318
|
func (cdc *Codec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{}) {
err := cdc.UnmarshalBinaryLengthPrefixed(bz, ptr)
if err != nil {
panic(err)
}
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L930-L946
|
func (p *PubSub) RegisterTopicValidator(topic string, val Validator, opts ...ValidatorOpt) error {
addVal := &addValReq{
topic: topic,
validate: val,
resp: make(chan error, 1),
}
for _, opt := range opts {
err := opt(addVal)
if err != nil {
return err
}
}
p.addVal <- addVal
return <-addVal.resp
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/main.go#L139-L159
|
func parseTemplates(skipTChannel bool, templateFiles []string) ([]*Template, error) {
var templates []*Template
if !skipTChannel {
templates = append(templates, &Template{
name: "tchan",
template: template.Must(parseTemplate(tchannelTmpl)),
})
}
for _, f := range templateFiles {
t, err := parseTemplateFile(f)
if err != nil {
return nil, err
}
templates = append(templates, t)
}
return templates, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L131-L148
|
func findStruct(scope *ast.Scope, name string) *ast.StructType {
obj := scope.Lookup(name)
if obj == nil {
return nil
}
typ, ok := obj.Decl.(*ast.TypeSpec)
if !ok {
return nil
}
str, ok := typ.Type.(*ast.StructType)
if !ok {
return nil
}
return str
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/event_counter.go#L49-L64
|
func (e *EventCounterPlugin) ReceiveIssueEvent(event sql.IssueEvent) []Point {
var label string
if event.Label != nil {
label = *event.Label
}
if !e.matcher.Match(event.Event, label) {
return nil
}
return []Point{
{
Values: map[string]interface{}{"event": 1},
Date: event.EventCreatedAt,
},
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L137-L150
|
func (c *openshiftClient) getImage(ctx context.Context, imageStreamImageName string) (*image, error) {
// FIXME: validate components per validation.IsValidPathSegmentName?
path := fmt.Sprintf("/oapi/v1/namespaces/%s/imagestreamimages/%s@%s", c.ref.namespace, c.ref.stream, imageStreamImageName)
body, err := c.doRequest(ctx, "GET", path, nil)
if err != nil {
return nil, err
}
// Note: This does absolutely no kind/version checking or conversions.
var isi imageStreamImage
if err := json.Unmarshal(body, &isi); err != nil {
return nil, err
}
return &isi.Image, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/version/api_server.go#L37-L42
|
func GetServerVersion(clientConn *grpc.ClientConn) (*pb.Version, error) {
return pb.NewAPIClient(clientConn).GetVersion(
context.Background(),
&types.Empty{},
)
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L19-L26
|
func NewBool(b bool, valid bool) Bool {
return Bool{
NullBool: sql.NullBool{
Bool: b,
Valid: valid,
},
}
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/loadbalancer.go#L121-L126
|
func (c *Client) DeleteBalancedNic(dcid, lbalid, balnicid string) (*http.Header, error) {
url := balnicPath(dcid, lbalid, balnicid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &http.Header{}
err := c.client.Delete(url, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/osarch/architectures_linux.go#L10-L17
|
func ArchitectureGetLocal() (string, error) {
uname, err := shared.Uname()
if err != nil {
return ArchitectureDefault, err
}
return uname.Machine, nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/resp.go#L15-L20
|
func (r *Resp) PrintHeaders() {
for key, value := range r.Headers {
fmt.Println(key, " : ", value[0])
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_volumes.go#L943-L1055
|
func storagePoolVolumeTypeDelete(d *Daemon, r *http.Request, volumeTypeName string) Response {
project := projectParam(r)
// 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) > 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))
}
response := ForwardedResponseIfTargetIsRemote(d, r)
if response != nil {
return response
}
poolID, _, err := d.cluster.StoragePoolGet(poolName)
if err != nil {
return SmartError(err)
}
response = ForwardedResponseIfVolumeIsRemote(d, r, poolID, volumeName, volumeType)
if response != nil {
return response
}
switch volumeType {
case storagePoolVolumeTypeCustom:
// allowed
case storagePoolVolumeTypeImage:
// allowed
default:
return BadRequest(fmt.Errorf("storage volumes of type \"%s\" cannot be deleted with the storage api", volumeTypeName))
}
volumeUsedBy, err := storagePoolVolumeUsedByGet(d.State(), project, volumeName, volumeTypeName)
if err != nil {
return SmartError(err)
}
if len(volumeUsedBy) > 0 {
if len(volumeUsedBy) != 1 ||
volumeType != storagePoolVolumeTypeImage ||
volumeUsedBy[0] != fmt.Sprintf(
"/%s/images/%s",
version.APIVersion,
volumeName) {
return BadRequest(fmt.Errorf(`The storage volume is ` +
`still in use by containers or profiles`))
}
}
s, err := storagePoolVolumeInit(d.State(), "default", poolName, volumeName, volumeType)
if err != nil {
return NotFound(err)
}
switch volumeType {
case storagePoolVolumeTypeCustom:
var snapshots []string
// Delete storage volume snapshots
snapshots, err = d.cluster.StoragePoolVolumeSnapshotsGetType(volumeName, volumeType, poolID)
if err != nil {
return SmartError(err)
}
for _, snapshot := range snapshots {
s, err := storagePoolVolumeInit(d.State(), project, poolName, snapshot, volumeType)
if err != nil {
return NotFound(err)
}
err = s.StoragePoolVolumeSnapshotDelete()
if err != nil {
return SmartError(err)
}
}
err = s.StoragePoolVolumeDelete()
case storagePoolVolumeTypeImage:
err = s.ImageDelete(volumeName)
default:
return BadRequest(fmt.Errorf(`Storage volumes of type "%s" `+
`cannot be deleted with the storage api`,
volumeTypeName))
}
if err != nil {
return SmartError(err)
}
return EmptySyncResponse
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1782-L1784
|
func (app *App) LastLogs(lines int, filterLog Applog) ([]Applog, error) {
return app.lastLogs(lines, filterLog, false)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L897-L901
|
func (v GetSamplingProfileReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler9(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L886-L921
|
func (s *storageImageSource) getSize() (int64, error) {
var sum int64
// Size up the data blobs.
dataNames, err := s.imageRef.transport.store.ListImageBigData(s.image.ID)
if err != nil {
return -1, errors.Wrapf(err, "error reading image %q", s.image.ID)
}
for _, dataName := range dataNames {
bigSize, err := s.imageRef.transport.store.ImageBigDataSize(s.image.ID, dataName)
if err != nil {
return -1, errors.Wrapf(err, "error reading data blob size %q for %q", dataName, s.image.ID)
}
sum += bigSize
}
// Add the signature sizes.
for _, sigSize := range s.SignatureSizes {
sum += int64(sigSize)
}
// Walk the layer list.
layerID := s.image.TopLayer
for layerID != "" {
layer, err := s.imageRef.transport.store.Layer(layerID)
if err != nil {
return -1, err
}
if layer.UncompressedDigest == "" || layer.UncompressedSize < 0 {
return -1, errors.Errorf("size for layer %q is unknown, failing getSize()", layerID)
}
sum += layer.UncompressedSize
if layer.Parent == "" {
break
}
layerID = layer.Parent
}
return sum, nil
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodetable/table.go#L110-L120
|
func (nt *NodeTable) Get(key []byte) unsafe.Pointer {
res := nt.find(key)
if res.status&ntFoundMask == ntFoundMask {
if res.status == ntFoundInFast {
return decodePointer(res.fastHTValue)
}
return decodePointer(res.slowHTValues[res.slowHTPos])
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/strkey/main.go#L74-L99
|
func Encode(version VersionByte, src []byte) (string, error) {
if err := checkValidVersionByte(version); err != nil {
return "", err
}
var raw bytes.Buffer
// write version byte
if err := binary.Write(&raw, binary.LittleEndian, version); err != nil {
return "", err
}
// write payload
if _, err := raw.Write(src); err != nil {
return "", err
}
// calculate and write checksum
checksum := crc16.Checksum(raw.Bytes())
if _, err := raw.Write(checksum); err != nil {
return "", err
}
result := base32.StdEncoding.EncodeToString(raw.Bytes())
return result, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L332-L336
|
func (v *HeaderEntry) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoFetch3(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5933-L5937
|
func (v *EventCharacterDataModified) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom66(&r, v)
return r.Error()
}
|
https://github.com/gokyle/fswatch/blob/1dbdf8320a690537582afe0f45c947f501adeaad/watcher.go#L19-L40
|
func newWatcher(dir_notify bool, initpaths ...string) (w *Watcher) {
w = new(Watcher)
w.auto_watch = dir_notify
w.paths = make(map[string]*watchItem, 0)
var paths []string
for _, path := range initpaths {
matches, err := filepath.Glob(path)
if err != nil {
continue
}
paths = append(paths, matches...)
}
if dir_notify {
w.syncAddPaths(paths...)
} else {
for _, path := range paths {
w.paths[path] = watchPath(path)
}
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1168-L1172
|
func (v *ResolveNodeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom11(&r, v)
return r.Error()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L765-L767
|
func (src *IplImage) EqualizeHist(dst *IplImage) {
C.cvEqualizeHist(unsafe.Pointer(src), unsafe.Pointer(dst))
}
|
https://github.com/jpillora/velox/blob/42845d32322027cde41ba6b065a083ea4120238f/go/state.go#L145-L154
|
func (s *State) Push() bool {
//attempt to mark state as 'pushing'
if atomic.CompareAndSwapUint32(&s.push.ing, 0, 1) {
go s.gopush()
return true
}
//if already pushing, mark queued
atomic.StoreUint32(&s.push.queued, 1)
return false
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/types.go#L549-L556
|
func (i Issue) HasLabel(labelToFind string) bool {
for _, label := range i.Labels {
if strings.ToLower(label.Name) == strings.ToLower(labelToFind) {
return true
}
}
return false
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/internal/execxp/execxp.go#L12-L22
|
func Exec(n *parser.Node, t tree.Node, ns map[string]string, fns map[xml.Name]tree.Wrap, v map[string]tree.Result) (tree.Result, error) {
f := xpFilt{
t: t,
ns: ns,
ctx: tree.NodeSet{t},
fns: fns,
variables: v,
}
return exec(&f, n)
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L235-L237
|
func (w *SnowballWord) HasSuffixRunes(suffixRunes []rune) bool {
return w.HasSuffixRunesIn(0, len(w.RS), suffixRunes)
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L885-L891
|
func (db *DB) columnFromTag(field reflect.StructField) string {
col := field.Tag.Get(dbColumnTag)
if col == "" {
return stringutil.ToSnakeCase(field.Name)
}
return col
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4064-L4073
|
func (u OperationResultTr) GetManageOfferResult() (result ManageOfferResult, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "ManageOfferResult" {
result = *u.ManageOfferResult
ok = true
}
return
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/utils.go#L60-L66
|
func CheckPassword(password []byte, salt []byte, hpassword []byte) (bool, error) {
hash, err := HashPassword(password, salt)
if err != nil {
return false, err
}
return bytes.Equal(hash, hpassword), nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcindex/tcindex.go#L172-L176
|
func (index *Index) InsertTask(namespace string, payload *InsertTaskRequest) (*IndexedTaskResponse, error) {
cd := tcclient.Client(*index)
responseObject, _, err := (&cd).APICall(payload, "PUT", "/task/"+url.QueryEscape(namespace), new(IndexedTaskResponse), nil)
return responseObject.(*IndexedTaskResponse), err
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.