_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/outbound.go#L251-L258
|
func (response *OutboundCallResponse) Arg2Reader() (ArgReader, error) {
var method []byte
if err := NewArgReader(response.arg1Reader()).Read(&method); err != nil {
return nil, err
}
return response.arg2Reader()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L57-L95
|
func (t *ResourceType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ResourceType(in.String()) {
case ResourceTypeDocument:
*t = ResourceTypeDocument
case ResourceTypeStylesheet:
*t = ResourceTypeStylesheet
case ResourceTypeImage:
*t = ResourceTypeImage
case ResourceTypeMedia:
*t = ResourceTypeMedia
case ResourceTypeFont:
*t = ResourceTypeFont
case ResourceTypeScript:
*t = ResourceTypeScript
case ResourceTypeTextTrack:
*t = ResourceTypeTextTrack
case ResourceTypeXHR:
*t = ResourceTypeXHR
case ResourceTypeFetch:
*t = ResourceTypeFetch
case ResourceTypeEventSource:
*t = ResourceTypeEventSource
case ResourceTypeWebSocket:
*t = ResourceTypeWebSocket
case ResourceTypeManifest:
*t = ResourceTypeManifest
case ResourceTypeSignedExchange:
*t = ResourceTypeSignedExchange
case ResourceTypePing:
*t = ResourceTypePing
case ResourceTypeCSPViolationReport:
*t = ResourceTypeCSPViolationReport
case ResourceTypeOther:
*t = ResourceTypeOther
default:
in.AddError(errors.New("unknown ResourceType value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2533-L2537
|
func (v *NavigateReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage26(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L218-L374
|
func (c *copier) copyOneImage(ctx context.Context, policyContext *signature.PolicyContext, options *Options, unparsedImage *image.UnparsedImage) (manifestBytes []byte, retErr error) {
// The caller is handling manifest lists; this could happen only if a manifest list contains a manifest list.
// Make sure we fail cleanly in such cases.
multiImage, err := isMultiImage(ctx, unparsedImage)
if err != nil {
// FIXME FIXME: How to name a reference for the sub-image?
return nil, errors.Wrapf(err, "Error determining manifest MIME type for %s", transports.ImageName(unparsedImage.Reference()))
}
if multiImage {
return nil, fmt.Errorf("Unexpectedly received a manifest list instead of a manifest for a single image")
}
// Please keep this policy check BEFORE reading any other information about the image.
// (the multiImage check above only matches the MIME type, which we have received anyway.
// Actual parsing of anything should be deferred.)
if allowed, err := policyContext.IsRunningImageAllowed(ctx, unparsedImage); !allowed || err != nil { // Be paranoid and fail if either return value indicates so.
return nil, errors.Wrap(err, "Source image rejected")
}
src, err := image.FromUnparsedImage(ctx, options.SourceCtx, unparsedImage)
if err != nil {
return nil, errors.Wrapf(err, "Error initializing image from source %s", transports.ImageName(c.rawSource.Reference()))
}
// If the destination is a digested reference, make a note of that, determine what digest value we're
// expecting, and check that the source manifest matches it.
destIsDigestedReference := false
if named := c.dest.Reference().DockerReference(); named != nil {
if digested, ok := named.(reference.Digested); ok {
destIsDigestedReference = true
sourceManifest, _, err := src.Manifest(ctx)
if err != nil {
return nil, errors.Wrapf(err, "Error reading manifest from source image")
}
matches, err := manifest.MatchesDigest(sourceManifest, digested.Digest())
if err != nil {
return nil, errors.Wrapf(err, "Error computing digest of source image's manifest")
}
if !matches {
return nil, errors.New("Digest of source image's manifest would not match destination reference")
}
}
}
if err := checkImageDestinationForCurrentRuntimeOS(ctx, options.DestinationCtx, src, c.dest); err != nil {
return nil, err
}
var sigs [][]byte
if options.RemoveSignatures {
sigs = [][]byte{}
} else {
c.Printf("Getting image source signatures\n")
s, err := src.Signatures(ctx)
if err != nil {
return nil, errors.Wrap(err, "Error reading signatures")
}
sigs = s
}
if len(sigs) != 0 {
c.Printf("Checking if image destination supports signatures\n")
if err := c.dest.SupportsSignatures(ctx); err != nil {
return nil, errors.Wrap(err, "Can not copy signatures")
}
}
ic := imageCopier{
c: c,
manifestUpdates: &types.ManifestUpdateOptions{InformationOnly: types.ManifestUpdateInformation{Destination: c.dest}},
src: src,
// diffIDsAreNeeded is computed later
canModifyManifest: len(sigs) == 0 && !destIsDigestedReference,
}
// Ensure _this_ copy sees exactly the intended data when either processing a signed image or signing it.
// This may be too conservative, but for now, better safe than sorry, _especially_ on the SignBy path:
// The signature makes the content non-repudiable, so it very much matters that the signature is made over exactly what the user intended.
// We do intend the RecordDigestUncompressedPair calls to only work with reliable data, but at least there’s a risk
// that the compressed version coming from a third party may be designed to attack some other decompressor implementation,
// and we would reuse and sign it.
ic.canSubstituteBlobs = ic.canModifyManifest && options.SignBy == ""
if err := ic.updateEmbeddedDockerReference(); err != nil {
return nil, err
}
// We compute preferredManifestMIMEType only to show it in error messages.
// Without having to add this context in an error message, we would be happy enough to know only that no conversion is needed.
preferredManifestMIMEType, otherManifestMIMETypeCandidates, err := ic.determineManifestConversion(ctx, c.dest.SupportedManifestMIMETypes(), options.ForceManifestMIMEType)
if err != nil {
return nil, err
}
// If src.UpdatedImageNeedsLayerDiffIDs(ic.manifestUpdates) will be true, it needs to be true by the time we get here.
ic.diffIDsAreNeeded = src.UpdatedImageNeedsLayerDiffIDs(*ic.manifestUpdates)
if err := ic.copyLayers(ctx); err != nil {
return nil, err
}
// With docker/distribution registries we do not know whether the registry accepts schema2 or schema1 only;
// and at least with the OpenShift registry "acceptschema2" option, there is no way to detect the support
// without actually trying to upload something and getting a types.ManifestTypeRejectedError.
// So, try the preferred manifest MIME type. If the process succeeds, fine…
manifestBytes, err = ic.copyUpdatedConfigAndManifest(ctx)
if err != nil {
logrus.Debugf("Writing manifest using preferred type %s failed: %v", preferredManifestMIMEType, err)
// … if it fails, _and_ the failure is because the manifest is rejected, we may have other options.
if _, isManifestRejected := errors.Cause(err).(types.ManifestTypeRejectedError); !isManifestRejected || len(otherManifestMIMETypeCandidates) == 0 {
// We don’t have other options.
// In principle the code below would handle this as well, but the resulting error message is fairly ugly.
// Don’t bother the user with MIME types if we have no choice.
return nil, err
}
// If the original MIME type is acceptable, determineManifestConversion always uses it as preferredManifestMIMEType.
// So if we are here, we will definitely be trying to convert the manifest.
// With !ic.canModifyManifest, that would just be a string of repeated failures for the same reason,
// so let’s bail out early and with a better error message.
if !ic.canModifyManifest {
return nil, errors.Wrap(err, "Writing manifest failed (and converting it is not possible)")
}
// errs is a list of errors when trying various manifest types. Also serves as an "upload succeeded" flag when set to nil.
errs := []string{fmt.Sprintf("%s(%v)", preferredManifestMIMEType, err)}
for _, manifestMIMEType := range otherManifestMIMETypeCandidates {
logrus.Debugf("Trying to use manifest type %s…", manifestMIMEType)
ic.manifestUpdates.ManifestMIMEType = manifestMIMEType
attemptedManifest, err := ic.copyUpdatedConfigAndManifest(ctx)
if err != nil {
logrus.Debugf("Upload of manifest type %s failed: %v", manifestMIMEType, err)
errs = append(errs, fmt.Sprintf("%s(%v)", manifestMIMEType, err))
continue
}
// We have successfully uploaded a manifest.
manifestBytes = attemptedManifest
errs = nil // Mark this as a success so that we don't abort below.
break
}
if errs != nil {
return nil, fmt.Errorf("Uploading manifest failed, attempted the following formats: %s", strings.Join(errs, ", "))
}
}
if options.SignBy != "" {
newSig, err := c.createSignature(manifestBytes, options.SignBy)
if err != nil {
return nil, err
}
sigs = append(sigs, newSig)
}
c.Printf("Storing signatures\n")
if err := c.dest.PutSignatures(ctx, sigs); err != nil {
return nil, errors.Wrap(err, "Error writing signatures")
}
return manifestBytes, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/storage/driver.go#L60-L81
|
func GetCurrentDbDriver() (*DbDriver, error) {
driverLock.RLock()
if currentDbDriver != nil {
driverLock.RUnlock()
return currentDbDriver, nil
}
driverLock.RUnlock()
driverLock.Lock()
defer driverLock.Unlock()
if currentDbDriver != nil {
return currentDbDriver, nil
}
dbDriverName, err := config.GetString("database:driver")
if err != nil || dbDriverName == "" {
dbDriverName = DefaultDbDriverName
}
currentDbDriver, err = GetDbDriver(dbDriverName)
if err != nil {
return nil, err
}
return currentDbDriver, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L257-L264
|
func (s *MergeIterator) Close() error {
for _, itr := range s.all {
if err := itr.Close(); err != nil {
return errors.Wrap(err, "MergeIterator")
}
}
return nil
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/service_mock.go#L44-L55
|
func (s *ServiceMock) Start() *exec.Cmd {
s.ServiceStartCount++
cmd := s.ExecFunc()
cmd.Start()
if s.processes == nil {
s.processes = make(map[int]*exec.Cmd)
}
s.processes[cmd.Process.Pid] = cmd
return cmd
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/main.go#L461-L467
|
func dupeRequest(original *http.Request) *http.Request {
r2 := new(http.Request)
*r2 = *original
r2.URL = new(url.URL)
*r2.URL = *original.URL
return r2
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L75-L77
|
func (c *dryRunProwJobClient) Get(name string, options metav1.GetOptions) (*prowapi.ProwJob, error) {
return nil, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config.go#L831-L850
|
func checkBindURLs(urls []url.URL) error {
for _, url := range urls {
if url.Scheme == "unix" || url.Scheme == "unixs" {
continue
}
host, _, err := net.SplitHostPort(url.Host)
if err != nil {
return err
}
if host == "localhost" {
// special case for local address
// TODO: support /etc/hosts ?
continue
}
if net.ParseIP(host) == nil {
return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
}
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L42-L164
|
func (a *API) ParseCommand(cmd, hrefPrefix string, values ActionCommands) (*ParsedCommand, error) {
// 0. Show help if requested
val, ok := values[cmd]
if !ok {
return nil, fmt.Errorf("Unknown command '%s'", cmd)
}
if val.ShowHelp != "" {
a.ShowHelp(cmd, hrefPrefix, values)
return nil, nil
}
// 1. Initialize / find href as well as resource and action command definitions
target, params, err := a.ParseCommandAndFlags(cmd, hrefPrefix, values)
if err != nil {
return nil, err
}
resource, action, path := target.Resource, target.Action, target.Path
// 2. Coerce and validate given flag values, use array for payload as order is meaningful
// when building the data structure (e.g. in the case of array of hashes)
var queryParams, payloadParams []APIParams
var seen []string
for _, p := range params {
param, value, err := a.findParamAndValue(action, p)
if err != nil {
return nil, err
}
if param == nil {
name := strings.SplitN(p, "=", 2)[0]
if len(action.CommandFlags) > 0 {
supported := make([]string, len(action.CommandFlags))
for i, p := range action.CommandFlags {
supported[i] = p.Name
}
return nil, fmt.Errorf("Unknown %s.%s flag '%s'. Supported flags are: %s",
resource.Name, action.Name, name, strings.Join(supported, ", "))
}
return nil, fmt.Errorf("Unknown %s.%s flag '%s'. %s.%s does not accept any flag",
resource.Name, action.Name, name, resource.Name, action.Name)
}
name := param.Name
seen = append(seen, name)
if err := validateFlagValue(value, param); err != nil {
return nil, err
}
coerced := &queryParams
if param.Location == metadata.PayloadParam {
coerced = &payloadParams
}
switch param.Type {
case "string", "[]string", "interface{}":
*coerced = append(*coerced, APIParams{name: value})
case "int", "[]int":
val, err := strconv.Atoi(value)
if err != nil {
return nil, fmt.Errorf("Value for '%s' must be an integer, value provided was '%s'",
name, value)
}
*coerced = append(*coerced, APIParams{name: val})
case "bool", "[]bool":
val, err := strconv.ParseBool(value)
if err != nil {
return nil, fmt.Errorf("Value for '%s' must be a bool, value provided was '%s'",
name, value)
}
*coerced = append(*coerced, APIParams{name: val})
case "*time.Time":
// Try to parse the input as int64 and if it was successful, treat is as a Unix
// time otherwise parse as RFC3339.
if val, err := strconv.ParseInt(value, 10, 64); err == nil {
*coerced = append(*coerced, APIParams{name: time.Unix(val, 0)})
} else {
val, err := time.Parse(time.RFC3339, value)
if err != nil {
return nil, fmt.Errorf("Invalid time '%s' for %s: %s", value, name, err)
}
*coerced = append(*coerced, APIParams{name: val})
}
case "map":
velems := strings.SplitN(value, "=", 2)
if len(velems) != 2 {
return nil, fmt.Errorf("Value for '%s' must be of the form NAME=VALUE, got %s", name, value)
}
*coerced = append(*coerced, APIParams{fmt.Sprintf("%s[%s]", name, velems[0]): velems[1]})
case "sourcefile":
file, err := os.Open(value)
if err != nil {
return nil, fmt.Errorf("Invalid file upload path '%s' for %s: %s", value, name, err)
}
*coerced = append(*coerced, APIParams{name: &SourceUpload{Reader: file}})
case "file":
file, err := os.Open(value)
if err != nil {
return nil, fmt.Errorf("Invalid file upload path '%s' for %s: %s", value, name, err)
}
*coerced = append(*coerced, APIParams{name: &FileUpload{Name: name, Filename: value, Reader: file}})
}
}
for _, p := range action.CommandFlags {
var ok bool
for _, s := range seen {
if s == p.Name {
ok = true
break
}
}
if p.Mandatory && !ok {
return nil, fmt.Errorf("Missing required flag '%s'", p.Name)
}
}
// Reconstruct data structure from flat values
qParams, err := buildQuery(queryParams)
if err != nil {
return nil, err
}
pParams, err := buildPayload(payloadParams)
if err != nil {
return nil, err
}
return &ParsedCommand{path.HTTPMethod, path.Path, qParams, pParams}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/easyjson.go#L340-L344
|
func (v EventEntryAdded) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoLog3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L469-L487
|
func (s *store) walk(nodePath string, walkFunc func(prev *node, component string) (*node, *v2error.Error)) (*node, *v2error.Error) {
components := strings.Split(nodePath, "/")
curr := s.Root
var err *v2error.Error
for i := 1; i < len(components); i++ {
if len(components[i]) == 0 { // ignore empty string
return curr, nil
}
curr, err = walkFunc(curr, components[i])
if err != nil {
return nil, err
}
}
return curr, nil
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/apply.go#L39-L76
|
func ApplyCmd() *cobra.Command {
var ao = &cli.ApplyOptions{}
var applyCmd = &cobra.Command{
Use: "apply <NAME>",
Short: "Apply a cluster resource to a cloud",
Long: `Use this command to apply an API model in a cloud.
This command will attempt to find an API model in a defined state store, and then apply any changes needed directly to a cloud.
The apply will run once, and ultimately time out if something goes wrong.`,
Run: func(cmd *cobra.Command, args []string) {
switch len(args) {
case 0:
ao.Name = viper.GetString(keyKubicornName)
case 1:
ao.Name = args[0]
default:
logger.Critical("Too many arguments.")
os.Exit(1)
}
if err := runApply(ao); err != nil {
logger.Critical(err.Error())
os.Exit(1)
}
},
}
fs := applyCmd.Flags()
bindCommonStateStoreFlags(&ao.StateStoreOptions, fs)
bindCommonAwsFlags(&ao.AwsOptions, fs)
fs.StringArrayVarP(&ao.Set, keyKubicornSet, "e", viper.GetStringSlice(keyKubicornSet), descSet)
fs.StringVar(&ao.AwsProfile, keyAwsProfile, viper.GetString(keyAwsProfile), descAwsProfile)
fs.StringVar(&ao.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig)
return applyCmd
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/greenhouse/diskcache/cache.go#L93-L145
|
func (c *Cache) Put(key string, content io.Reader, contentSHA256 string) error {
// make sure directory exists
path := c.KeyToPath(key)
dir := filepath.Dir(path)
err := ensureDir(dir)
if err != nil {
logrus.WithError(err).Errorf("error ensuring directory '%s' exists", dir)
}
// create a temp file to get the content on disk
temp, err := ioutil.TempFile(dir, "temp-put")
if err != nil {
return fmt.Errorf("failed to create cache entry: %v", err)
}
// fast path copying when not hashing content,s
if contentSHA256 == "" {
_, err = io.Copy(temp, content)
if err != nil {
removeTemp(temp.Name())
return fmt.Errorf("failed to copy into cache entry: %v", err)
}
} else {
hasher := sha256.New()
_, err = io.Copy(io.MultiWriter(temp, hasher), content)
if err != nil {
removeTemp(temp.Name())
return fmt.Errorf("failed to copy into cache entry: %v", err)
}
actualContentSHA256 := hex.EncodeToString(hasher.Sum(nil))
if actualContentSHA256 != contentSHA256 {
removeTemp(temp.Name())
return fmt.Errorf(
"hashes did not match for '%s', given: '%s' actual: '%s",
key, contentSHA256, actualContentSHA256)
}
}
// move the content to the key location
err = temp.Sync()
if err != nil {
removeTemp(temp.Name())
return fmt.Errorf("failed to sync cache entry: %v", err)
}
temp.Close()
err = os.Rename(temp.Name(), path)
if err != nil {
removeTemp(temp.Name())
return fmt.Errorf("failed to insert contents into cache: %v", err)
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L295-L314
|
func (c *Client) CrumbRequest() error {
if c.authConfig.csrfToken != "" && c.authConfig.csrfRequestField != "" {
return nil
}
c.logger.Debug("CrumbRequest")
data, err := c.GetSkipMetrics("/crumbIssuer/api/json")
if err != nil {
return err
}
crumbResp := struct {
Crumb string `json:"crumb"`
CrumbRequestField string `json:"crumbRequestField"`
}{}
if err := json.Unmarshal(data, &crumbResp); err != nil {
return fmt.Errorf("cannot unmarshal crumb response: %v", err)
}
c.authConfig.csrfToken = crumbResp.Crumb
c.authConfig.csrfRequestField = crumbResp.CrumbRequestField
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/mock/mockserver/mockserver.go#L146-L158
|
func (ms *MockServers) StopAt(idx int) {
ms.mu.Lock()
defer ms.mu.Unlock()
if ms.Servers[idx].ln == nil {
return
}
ms.Servers[idx].GrpcServer.Stop()
ms.Servers[idx].GrpcServer = nil
ms.Servers[idx].ln = nil
ms.wg.Done()
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L388-L408
|
func (cdc *Codec) getTypeInfoFromPrefix_rlock(iinfo *TypeInfo, pb PrefixBytes) (info *TypeInfo, err error) {
// We do not use defer cdc.mtx.Unlock() here due to performance overhead of
// defer in go1.11 (and prior versions). Ensure new code paths unlock the
// mutex.
cdc.mtx.RLock()
infos, ok := iinfo.Implementers[pb]
if !ok {
err = fmt.Errorf("unrecognized prefix bytes %X", pb)
cdc.mtx.RUnlock()
return
}
if len(infos) > 1 {
err = fmt.Errorf("conflicting concrete types registered for %X: e.g. %v and %v", pb, infos[0].Type, infos[1].Type)
cdc.mtx.RUnlock()
return
}
info = infos[0]
cdc.mtx.RUnlock()
return
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/functions_client.go#L57-L70
|
func New(transport runtime.ClientTransport, formats strfmt.Registry) *Functions {
cli := new(Functions)
cli.Transport = transport
cli.Apps = apps.New(transport, formats)
cli.Routes = routes.New(transport, formats)
cli.Tasks = tasks.New(transport, formats)
cli.Version = version.New(transport, formats)
return cli
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L128-L134
|
func BlockPathFromEnv(block *pfs.Block) (string, error) {
storageRoot, err := StorageRootFromEnv()
if err != nil {
return "", err
}
return filepath.Join(storageRoot, "block", block.Hash), nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L143-L150
|
func (r *AccountGroup) Locator(api *API) *AccountGroupLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.AccountGroupLocator(l["href"])
}
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/server.go#L103-L105
|
func (s *Server) SetContextFn(f func(ctx context.Context, method string, headers map[string]string) Context) {
s.ctxFn = f
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L686-L689
|
func (p PrintToPDFParams) WithLandscape(landscape bool) *PrintToPDFParams {
p.Landscape = landscape
return &p
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/mm/malloc.go#L44-L49
|
func Free(p unsafe.Pointer) {
if Debug {
atomic.AddUint64(&stats.frees, 1)
}
C.mm_free(p)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/events.go#L21-L43
|
func Events(endpoints *endpoints.Endpoints, cluster *db.Cluster, f func(int64, api.Event)) (task.Func, task.Schedule) {
listeners := map[int64]*lxd.EventListener{}
// Update our pool of event listeners. Since database queries are
// blocking, we spawn the actual logic in a goroutine, to abort
// immediately when we receive the stop signal.
update := func(ctx context.Context) {
ch := make(chan struct{})
go func() {
eventsUpdateListeners(endpoints, cluster, listeners, f)
ch <- struct{}{}
}()
select {
case <-ch:
case <-ctx.Done():
}
}
schedule := task.Every(time.Second)
return update, schedule
}
|
https://github.com/jtacoma/uritemplates/blob/307ae868f90f4ee1b73ebe4596e0394237dacce8/uritemplates.go#L192-L206
|
func (self *UriTemplate) Names() []string {
names := make([]string, 0, len(self.parts))
for _, p := range self.parts {
if len(p.raw) > 0 || len(p.terms) == 0 {
continue
}
for _, term := range p.terms {
names = append(names, term.name)
}
}
return names
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L136-L193
|
func decodeName(buf []byte) string {
i := bytes.IndexByte(buf, 0)
if i < 0 {
return string(buf) // filename is UTF-8
}
name := buf[:i]
encName := readBuf(buf[i+1:])
if len(encName) < 2 {
return "" // invalid encoding
}
highByte := uint16(encName.byte()) << 8
flags := encName.byte()
flagBits := 8
var wchars []uint16 // decoded characters are UTF-16
for len(wchars) < len(name) && len(encName) > 0 {
if flagBits == 0 {
flags = encName.byte()
flagBits = 8
if len(encName) == 0 {
break
}
}
switch flags >> 6 {
case 0:
wchars = append(wchars, uint16(encName.byte()))
case 1:
wchars = append(wchars, uint16(encName.byte())|highByte)
case 2:
if len(encName) < 2 {
break
}
wchars = append(wchars, encName.uint16())
case 3:
n := encName.byte()
b := name[len(wchars):]
if l := int(n&0x7f) + 2; l < len(b) {
b = b[:l]
}
if n&0x80 > 0 {
if len(encName) < 1 {
break
}
ec := encName.byte()
for _, c := range b {
wchars = append(wchars, uint16(c+ec)|highByte)
}
} else {
for _, c := range b {
wchars = append(wchars, uint16(c))
}
}
}
flags <<= 2
flagBits -= 2
}
return string(utf16.Decode(wchars))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L89-L100
|
func (c APIClient) InspectRepo(repoName string) (*pfs.RepoInfo, error) {
resp, err := c.PfsAPIClient.InspectRepo(
c.Ctx(),
&pfs.InspectRepoRequest{
Repo: NewRepo(repoName),
},
)
if err != nil {
return nil, grpcutil.ScrubGRPC(err)
}
return resp, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/easyjson.go#L425-L429
|
func (v EventSecurityStateChanged) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoSecurity2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L159-L168
|
func (t *Tide) MergeCommitTemplate(org, repo string) TideMergeCommitTemplate {
name := org + "/" + repo
v, ok := t.MergeTemplate[name]
if !ok {
return t.MergeTemplate[org]
}
return v
}
|
https://github.com/drone/drone-plugin-go/blob/d6109f644c5935c22620081b4c234bb2263743c7/plugin/param.go#L31-L55
|
func deprecated_init() {
// if piping from stdin we can just exit
// and use the default Stdin value
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
return
}
// check for params after the double dash
// in the command string
for i, argv := range os.Args {
if argv == "--" {
arg := os.Args[i+1]
buf := bytes.NewBufferString(arg)
Stdin = NewParamSet(buf)
return
}
}
// else use the first variable in the list
if len(os.Args) > 1 {
buf := bytes.NewBufferString(os.Args[1])
Stdin = NewParamSet(buf)
}
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L86-L90
|
func CheckExtract(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckExtract = val
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L470-L492
|
func (it *Iterator) Close() {
if it.closed {
return
}
it.closed = true
it.iitr.Close()
// It is important to wait for the fill goroutines to finish. Otherwise, we might leave zombie
// goroutines behind, which are waiting to acquire file read locks after DB has been closed.
waitFor := func(l list) {
item := l.pop()
for item != nil {
item.wg.Wait()
item = l.pop()
}
}
waitFor(it.waste)
waitFor(it.data)
// TODO: We could handle this error.
_ = it.txn.db.vlog.decrIteratorCount()
atomic.AddInt32(&it.txn.numIterators, -1)
}
|
https://github.com/suicidejack/throttled/blob/373909e862a27e2190015918229c2605b3221f1d/wait_group.go#L45-L55
|
func (w *WaitGroup) Wait() {
if w.outstanding == 0 {
return
}
for w.outstanding > 0 {
select {
case <-w.completed:
w.outstanding--
}
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L137-L144
|
func ParseKey(key []byte) []byte {
if key == nil {
return nil
}
AssertTrue(len(key) > 8)
return key[:len(key)-8]
}
|
https://github.com/felixge/httpsnoop/blob/eadd4fad6aac69ae62379194fe0219f3dbc80fd3/wrap_generated_gteq_1.8.go#L66-L316
|
func Wrap(w http.ResponseWriter, hooks Hooks) http.ResponseWriter {
rw := &rw{w: w, h: hooks}
_, i0 := w.(http.Flusher)
_, i1 := w.(http.CloseNotifier)
_, i2 := w.(http.Hijacker)
_, i3 := w.(io.ReaderFrom)
_, i4 := w.(http.Pusher)
switch {
// combination 1/32
case !i0 && !i1 && !i2 && !i3 && !i4:
return struct {
http.ResponseWriter
}{rw}
// combination 2/32
case !i0 && !i1 && !i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.Pusher
}{rw, rw}
// combination 3/32
case !i0 && !i1 && !i2 && i3 && !i4:
return struct {
http.ResponseWriter
io.ReaderFrom
}{rw, rw}
// combination 4/32
case !i0 && !i1 && !i2 && i3 && i4:
return struct {
http.ResponseWriter
io.ReaderFrom
http.Pusher
}{rw, rw, rw}
// combination 5/32
case !i0 && !i1 && i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.Hijacker
}{rw, rw}
// combination 6/32
case !i0 && !i1 && i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.Hijacker
http.Pusher
}{rw, rw, rw}
// combination 7/32
case !i0 && !i1 && i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.Hijacker
io.ReaderFrom
}{rw, rw, rw}
// combination 8/32
case !i0 && !i1 && i2 && i3 && i4:
return struct {
http.ResponseWriter
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw}
// combination 9/32
case !i0 && i1 && !i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.CloseNotifier
}{rw, rw}
// combination 10/32
case !i0 && i1 && !i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.CloseNotifier
http.Pusher
}{rw, rw, rw}
// combination 11/32
case !i0 && i1 && !i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.CloseNotifier
io.ReaderFrom
}{rw, rw, rw}
// combination 12/32
case !i0 && i1 && !i2 && i3 && i4:
return struct {
http.ResponseWriter
http.CloseNotifier
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw}
// combination 13/32
case !i0 && i1 && i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.CloseNotifier
http.Hijacker
}{rw, rw, rw}
// combination 14/32
case !i0 && i1 && i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.CloseNotifier
http.Hijacker
http.Pusher
}{rw, rw, rw, rw}
// combination 15/32
case !i0 && i1 && i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.CloseNotifier
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 16/32
case !i0 && i1 && i2 && i3 && i4:
return struct {
http.ResponseWriter
http.CloseNotifier
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 17/32
case i0 && !i1 && !i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
}{rw, rw}
// combination 18/32
case i0 && !i1 && !i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.Pusher
}{rw, rw, rw}
// combination 19/32
case i0 && !i1 && !i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
io.ReaderFrom
}{rw, rw, rw}
// combination 20/32
case i0 && !i1 && !i2 && i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw}
// combination 21/32
case i0 && !i1 && i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
http.Hijacker
}{rw, rw, rw}
// combination 22/32
case i0 && !i1 && i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.Hijacker
http.Pusher
}{rw, rw, rw, rw}
// combination 23/32
case i0 && !i1 && i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 24/32
case i0 && !i1 && i2 && i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 25/32
case i0 && i1 && !i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
}{rw, rw, rw}
// combination 26/32
case i0 && i1 && !i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Pusher
}{rw, rw, rw, rw}
// combination 27/32
case i0 && i1 && !i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 28/32
case i0 && i1 && !i2 && i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 29/32
case i0 && i1 && i2 && !i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
}{rw, rw, rw, rw}
// combination 30/32
case i0 && i1 && i2 && !i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 31/32
case i0 && i1 && i2 && i3 && !i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 32/32
case i0 && i1 && i2 && i3 && i4:
return struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw, rw}
}
panic("unreachable")
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L356-L402
|
func NewAmazonClientFromSecret(bucket string, reversed ...bool) (Client, error) {
// Get AWS region (required for constructing an AWS client)
region, err := readSecretFile("/amazon-region")
if err != nil {
return nil, fmt.Errorf("amazon-region not found")
}
// Use or retrieve S3 bucket
if bucket == "" {
bucket, err = readSecretFile("/amazon-bucket")
if err != nil {
return nil, err
}
}
// Retrieve either static or vault credentials; if neither are found, we will
// use IAM roles (i.e. the EC2 metadata service)
var creds AmazonCreds
creds.ID, err = readSecretFile("/amazon-id")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
creds.Secret, err = readSecretFile("/amazon-secret")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
creds.Token, err = readSecretFile("/amazon-token")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
creds.VaultAddress, err = readSecretFile("/amazon-vault-addr")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
creds.VaultRole, err = readSecretFile("/amazon-vault-role")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
creds.VaultToken, err = readSecretFile("/amazon-vault-token")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
// Get Cloudfront distribution (not required, though we can log a warning)
distribution, err := readSecretFile("/amazon-distribution")
return NewAmazonClient(region, bucket, &creds, distribution, reversed...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L39-L45
|
func (s Schema) mustGetKey(name string) Key {
key, ok := s[name]
if !ok {
panic(fmt.Sprintf("attempt to access unknown key '%s'", name))
}
return key
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L416-L426
|
func (c *Connection) handlePingReq(frame *Frame) {
if state := c.readState(); state != connectionActive {
c.protocolError(frame.Header.ID, errConnNotActive{"ping on incoming", state})
return
}
pingRes := &pingRes{id: frame.Header.ID}
if err := c.sendMessage(pingRes); err != nil {
c.connectionError("send pong", err)
}
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L821-L826
|
func (g *Glg) DebugFunc(f func() string) error {
if g.isModeEnable(DEBG) {
return g.out(DEBG, "%s", f())
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/auth/auth.go#L206-L214
|
func IsErrTooShortTTL(err error) bool {
if err == nil {
return false
}
errMsg := err.Error()
return strings.Contains(errMsg, "provided TTL (") &&
strings.Contains(errMsg, ") is shorter than token's existing TTL (") &&
strings.Contains(errMsg, ")")
}
|
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/context.go#L9-L14
|
func (c *Context) Get(key string) interface{} {
if value, ok := c.set[key]; ok {
return value
}
return nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/iterator.go#L391-L394
|
func (itr *Iterator) Value() (ret y.ValueStruct) {
ret.Decode(itr.bi.Value())
return
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L1154-L1156
|
func (c *Condition) Like(arg string) *Condition {
return c.appendQuery(100, Like, arg)
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/taskmanager/task.go#L9-L15
|
func (s *Task) SetPrivateMeta(name string, value interface{}) {
if s.PrivateMetaData == nil {
s.PrivateMetaData = make(map[string]interface{})
}
s.PrivateMetaData[name] = value
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/volume.go#L82-L100
|
func volumeInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
v, err := volume.Load(r.URL.Query().Get(":name"))
if err != nil {
if err == volume.ErrVolumeNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
return err
}
canRead := permission.Check(t, permission.PermVolumeRead, contextsForVolume(v)...)
if !canRead {
return permission.ErrUnauthorized
}
_, err = v.LoadBinds()
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(&v)
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/validate.go#L67-L73
|
func PlushValidator(f genny.File) error {
if !genny.HasExt(f, ".html", ".md", ".plush") {
return nil
}
_, err := plush.Parse(f.String())
return err
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L234-L238
|
func (w *WriteBuffer) WriteUint64(n uint64) {
if b := w.reserve(8); b != nil {
binary.BigEndian.PutUint64(b, n)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes.go#L36-L40
|
func (o *KubernetesOptions) AddFlags(fs *flag.FlagSet) {
fs.StringVar(&o.cluster, "cluster", "", "Path to kube.Cluster YAML file. If empty, uses the local cluster.")
fs.StringVar(&o.kubeconfig, "kubeconfig", "", "Path to .kube/config file. If empty, uses the local cluster.")
fs.StringVar(&o.DeckURI, "deck-url", "", "Deck URI for read-only access to the cluster.")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L196-L199
|
func (p DispatchMouseEventParams) WithModifiers(modifiers Modifier) *DispatchMouseEventParams {
p.Modifiers = modifiers
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L128-L139
|
func (ms *MemoryStorage) Term(i uint64) (uint64, error) {
ms.Lock()
defer ms.Unlock()
offset := ms.ents[0].Index
if i < offset {
return 0, ErrCompacted
}
if int(i-offset) >= len(ms.ents) {
return 0, ErrUnavailable
}
return ms.ents[i-offset].Term, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L403-L405
|
func (p *SetShowFPSCounterParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetShowFPSCounter, p, nil)
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L74-L76
|
func (s *selectable) FindByXPath(selector string) *Selection {
return newSelection(s.session, s.selectors.Append(target.XPath, selector).Single())
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive.go#L85-L91
|
func readFull(r io.Reader, buf []byte) error {
_, err := io.ReadFull(r, buf)
if err == io.EOF {
return io.ErrUnexpectedEOF
}
return err
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L726-L736
|
func (db *DB) View(fn func(txn *Txn) error) error {
var txn *Txn
if db.opt.managedTxns {
txn = db.NewTransactionAt(math.MaxUint64, false)
} else {
txn = db.NewTransaction(false)
}
defer txn.Discard()
return fn(txn)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3436-L3440
|
func (v GetPossibleBreakpointsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger36(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/update_dir_command.go#L42-L57
|
func updatedirCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(c, ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
ttl := c.Int("ttl")
ctx, cancel := contextWithTotalTimeout(c)
resp, err := ki.Set(ctx, key, "", &client.SetOptions{TTL: time.Duration(ttl) * time.Second, Dir: true, PrevExist: client.PrevExist})
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
if c.GlobalString("output") != "simple" {
printResponseKey(resp, c.GlobalString("output"))
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L45-L54
|
func (c APIClient) ExtractAll(objects bool) ([]*admin.Op, error) {
var result []*admin.Op
if err := c.Extract(objects, func(op *admin.Op) error {
result = append(result, op)
return nil
}); err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/authenticator.go#L71-L129
|
func (a *Authenticator) Endpoint(prefix string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// create tracer
tracer := fire.NewTracerFromRequest(r, "flame/Authenticator.Endpoint")
tracer.Tag("prefix", prefix)
defer tracer.Finish(true)
// continue any previous aborts
defer stack.Resume(func(err error) {
// directly write oauth2 errors
if oauth2Error, ok := err.(*oauth2.Error); ok {
_ = oauth2.WriteError(w, oauth2Error)
return
}
// set critical error on last span
tracer.Tag("error", true)
tracer.Log("error", err.Error())
tracer.Log("stack", stack.Trace())
// otherwise report critical errors
if a.Reporter != nil {
a.Reporter(err)
}
// ignore errors caused by writing critical errors
_ = oauth2.WriteError(w, oauth2.ServerError(""))
})
// trim and split path
s := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, prefix), "/"), "/")
if len(s) != 1 || (s[0] != "authorize" && s[0] != "token" && s[0] != "revoke") {
w.WriteHeader(http.StatusNotFound)
return
}
// copy store
store := a.store.Copy()
defer store.Close()
// create
state := &state{
request: r,
writer: w,
store: store,
tracer: tracer,
}
// call endpoints
switch s[0] {
case "authorize":
a.authorizationEndpoint(state)
case "token":
a.tokenEndpoint(state)
case "revoke":
a.revocationEndpoint(state)
}
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3656-L3660
|
func (v *GetInstallabilityErrorsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage39(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/lock_command.go#L35-L43
|
func NewLockCommand() *cobra.Command {
c := &cobra.Command{
Use: "lock <lockname> [exec-command arg1 arg2 ...]",
Short: "Acquires a named lock",
Run: lockCommandFunc,
}
c.Flags().IntVarP(&lockTTL, "ttl", "", lockTTL, "timeout for session")
return c
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L845-L862
|
func (db *DB) findPKIndex(typ reflect.Type, index []int) []int {
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if IsUnexportedField(field) {
continue
}
if field.Anonymous {
if idx := db.findPKIndex(field.Type, append(index, i)); idx != nil {
return append(index, idx...)
}
continue
}
if db.hasPKTag(&field) {
return append(index, i)
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2772-L2776
|
func (v *SearchInResponseBodyReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork20(&r, v)
return r.Error()
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L1300-L1309
|
func (o *MapFloat32Option) Set(value string) error {
parts := stringMapRegex.Split(value, 2)
if len(parts) != 2 {
return fmt.Errorf("expected KEY=VALUE got '%s'", value)
}
val := Float32Option{}
val.Set(parts[1])
(*o)[parts[0]] = val
return nil
}
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/cubehash.go#L88-L124
|
func NewCubeHash() *CubeHash {
c := &CubeHash{}
c.x0 = iv[0]
c.x1 = iv[1]
c.x2 = iv[2]
c.x3 = iv[3]
c.x4 = iv[4]
c.x5 = iv[5]
c.x6 = iv[6]
c.x7 = iv[7]
c.x8 = iv[8]
c.x9 = iv[9]
c.xa = iv[10]
c.xb = iv[11]
c.xc = iv[12]
c.xd = iv[13]
c.xe = iv[14]
c.xf = iv[15]
c.xg = iv[16]
c.xh = iv[17]
c.xi = iv[18]
c.xj = iv[19]
c.xk = iv[20]
c.xl = iv[21]
c.xm = iv[22]
c.xn = iv[23]
c.xo = iv[24]
c.xp = iv[25]
c.xq = iv[26]
c.xr = iv[27]
c.xs = iv[28]
c.xt = iv[29]
c.xu = iv[30]
c.xv = iv[31]
return c
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1125-L1133
|
func (u LedgerEntryData) MustTrustLine() TrustLineEntry {
val, ok := u.GetTrustLine()
if !ok {
panic("arm TrustLine is not set")
}
return val
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L95-L119
|
func ContainerToArgs(container *Container) ContainerArgs {
args := ContainerArgs{
ID: container.ID,
Project: container.Project,
Name: container.Name,
Node: container.Node,
Ctype: ContainerType(container.Type),
Architecture: container.Architecture,
Ephemeral: container.Ephemeral,
CreationDate: container.CreationDate,
Stateful: container.Stateful,
LastUsedDate: container.LastUseDate,
Description: container.Description,
Config: container.Config,
Devices: container.Devices,
Profiles: container.Profiles,
ExpiryDate: container.ExpiryDate,
}
if args.Devices == nil {
args.Devices = types.Devices{}
}
return args
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L521-L530
|
func (p *GetFlattenedDocumentParams) Do(ctx context.Context) (nodes []*cdp.Node, err error) {
// execute
var res GetFlattenedDocumentReturns
err = cdp.Execute(ctx, CommandGetFlattenedDocument, p, &res)
if err != nil {
return nil, err
}
return res.Nodes, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L562-L588
|
func storagePoolConfigAdd(tx *sql.Tx, poolID, nodeID int64, poolConfig map[string]string) error {
str := "INSERT INTO storage_pools_config (storage_pool_id, node_id, key, value) VALUES(?, ?, ?, ?)"
stmt, err := tx.Prepare(str)
defer stmt.Close()
if err != nil {
return err
}
for k, v := range poolConfig {
if v == "" {
continue
}
var nodeIDValue interface{}
if !shared.StringInSlice(k, StoragePoolNodeConfigKeys) {
nodeIDValue = nil
} else {
nodeIDValue = nodeID
}
_, err = stmt.Exec(poolID, nodeIDValue, k, v)
if err != nil {
return err
}
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L50-L61
|
func newPeriodic(lg *zap.Logger, clock clockwork.Clock, h time.Duration, rg RevGetter, c Compactable) *Periodic {
pc := &Periodic{
lg: lg,
clock: clock,
period: h,
rg: rg,
c: c,
revs: make([]int64, 0),
}
pc.ctx, pc.cancel = context.WithCancel(context.Background())
return pc
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6129-L6137
|
func (u PeerAddressIp) MustIpv4() [4]byte {
val, ok := u.GetIpv4()
if !ok {
panic("arm Ipv4 is not set")
}
return val
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L1102-L1123
|
func (m *member) Terminate(t testing.TB) {
lg.Info(
"terminating a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-address", m.grpcAddr),
)
m.Close()
if !m.keepDataDirTerminate {
if err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {
t.Fatal(err)
}
}
lg.Info(
"terminated a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-address", m.grpcAddr),
)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L949-L951
|
func (api *API) NotificationRuleLocator(href string) *NotificationRuleLocator {
return &NotificationRuleLocator{Href(href), api}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L108-L114
|
func RemoveAllAuthentication(sys *types.SystemContext) error {
return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) {
auths.CredHelpers = make(map[string]string)
auths.AuthConfigs = make(map[string]dockerAuthConfig)
return true, nil
})
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aedeploy/aedeploy.go#L64-L72
|
func deploy() error {
vlogf("Running command %v", flag.Args())
cmd := exec.Command(flag.Arg(0), flag.Args()[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("unable to run %q: %v", strings.Join(flag.Args(), " "), err)
}
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/session.go#L28-L34
|
func (s *Session) GetOnce(name interface{}) interface{} {
if x, ok := s.Session.Values[name]; ok {
s.Delete(name)
return x
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/easyjson.go#L81-L85
|
func (v ScreenshotParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeadlessexperimental(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L150-L160
|
func (s *Shell) List(path string) ([]*LsLink, error) {
var out struct{ Objects []LsObject }
err := s.Request("ls", path).Exec(context.Background(), &out)
if err != nil {
return nil, err
}
if len(out.Objects) != 1 {
return nil, errors.New("bad response from server")
}
return out.Objects[0].Links, nil
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L36-L42
|
func New(dialect Dialect, dsn string) (*DB, error) {
db, err := sql.Open(dialect.Name(), dsn)
if err != nil {
return nil, err
}
return &DB{db: db, dialect: dialect, logger: defaultLogger}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L810-L814
|
func (v *Style) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss5(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L927-L957
|
func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
backoff := time.Millisecond
for {
select {
case <-w.ctx.Done():
if err == nil {
return nil, w.ctx.Err()
}
return nil, err
default:
}
if ws, err = w.remote.Watch(w.ctx, w.callOpts...); ws != nil && err == nil {
break
}
if isHaltErr(w.ctx, err) {
return nil, v3rpc.Error(err)
}
if isUnavailableErr(w.ctx, err) {
// retry, but backoff
if backoff < maxBackoff {
// 25% backoff factor
backoff = backoff + backoff/4
if backoff > maxBackoff {
backoff = maxBackoff
}
}
time.Sleep(backoff)
}
}
return ws, nil
}
|
https://github.com/sourcegraph/sitemap/blob/24a7b21aa1d824b55cc618352839f4ea7eb80423/sitemap.go#L76-L92
|
func Marshal(urlset *URLSet) (sitemapXML []byte, err error) {
if len(urlset.URLs) > MaxURLs {
err = ErrExceededMaxURLs
return
}
urlset.XMLNS = xmlns
sitemapXML = []byte(preamble)
var urlsetXML []byte
urlsetXML, err = xml.Marshal(urlset)
if err == nil {
sitemapXML = append(sitemapXML, urlsetXML...)
}
if len(sitemapXML) > MaxFileSize {
err = ErrExceededMaxFileSize
}
return
}
|
https://github.com/giantswarm/certctl/blob/2a6615f61499cd09a8d5ced9a5fade322d2de254/service/cert-signer/cert_signer.go#L165-L176
|
func computeRoleHash(organizations string) string {
// Sort organizations alphabetically
organizationsSlice := strings.Split(organizations, ",")
sort.Strings(organizationsSlice)
organizations = strings.Join(organizationsSlice, ",")
h := sha1.New()
h.Write([]byte(organizations))
bs := h.Sum(nil)
return fmt.Sprintf("%x", bs)
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L44-L46
|
func (r region) Cast(typ string) region {
return region{p: r.p, a: r.a, typ: r.p.findType(typ)}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/platform_strings.go#L59-L85
|
func (ps *PlatformStrings) Flat() []string {
unique := make(map[string]struct{})
for _, s := range ps.Generic {
unique[s] = struct{}{}
}
for _, ss := range ps.OS {
for _, s := range ss {
unique[s] = struct{}{}
}
}
for _, ss := range ps.Arch {
for _, s := range ss {
unique[s] = struct{}{}
}
}
for _, ss := range ps.Platform {
for _, s := range ss {
unique[s] = struct{}{}
}
}
flat := make([]string, 0, len(unique))
for s := range unique {
flat = append(flat, s)
}
sort.Strings(flat)
return flat
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L55-L69
|
func (r *ProtocolLXD) GetContainersFull() ([]api.ContainerFull, error) {
containers := []api.ContainerFull{}
if !r.HasExtension("container_full") {
return nil, fmt.Errorf("The server is missing the required \"container_full\" API extension")
}
// Fetch the raw value
_, err := r.queryStruct("GET", "/containers?recursion=2", nil, "", &containers)
if err != nil {
return nil, err
}
return containers, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/main.go#L23-L94
|
func main() {
app := kingpin.New("rsc", "A RightScale API client")
app.Writer(os.Stdout)
app.Version(VV)
cmdLine, err := ParseCommandLine(app)
if err != nil {
line := strings.Join(os.Args, " ")
PrintFatal("%s: %s", line, err.Error())
}
resp, err := ExecuteCommand(app, cmdLine)
if err != nil {
PrintFatal("%s", err.Error())
}
if resp == nil {
return // No results, just exit (e.g. setup, printed help...)
}
var notExactlyOneError bool
displayer, err := NewDisplayer(resp)
if err != nil {
PrintFatal("%s", err.Error())
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
// Let user know if something went wrong
fmt.Fprintln(errOut, resp.Status)
if len(displayer.body) > 0 {
fmt.Fprintln(errOut, displayer.body)
}
} else if cmdLine.ExtractOneSelect != "" {
err = displayer.ApplySingleExtract(cmdLine.ExtractOneSelect)
if err != nil {
notExactlyOneError = strings.Contains(err.Error(),
"instead of one value") // Ugh, there has to be a better way
PrintError(err.Error())
}
fmt.Fprint(out, displayer.Output())
} else {
if cmdLine.ExtractSelector != "" {
err = displayer.ApplyExtract(cmdLine.ExtractSelector, false)
} else if cmdLine.ExtractSelectorJSON != "" {
err = displayer.ApplyExtract(cmdLine.ExtractSelectorJSON, true)
} else if cmdLine.ExtractHeader != "" {
err = displayer.ApplyHeaderExtract(cmdLine.ExtractHeader)
}
if err != nil {
PrintFatal("%s", err.Error())
} else if cmdLine.Pretty {
displayer.Pretty()
}
fmt.Fprint(out, displayer.Output())
}
// Figure out exit code
exitStatus := 0
switch {
case notExactlyOneError:
exitStatus = 6
case resp.StatusCode == 401:
exitStatus = 1
case resp.StatusCode == 403:
exitStatus = 3
case resp.StatusCode == 404:
exitStatus = 4
case resp.StatusCode > 399 && resp.StatusCode < 500:
exitStatus = 2
case resp.StatusCode > 499:
exitStatus = 5
}
//fmt.Fprintf(os.Stderr, "exitStatus=%d\n", exitStatus)
osExit(exitStatus)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L85-L87
|
func (p *DispatchSyncEventParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDispatchSyncEvent, p, nil)
}
|
https://github.com/ikawaha/kagome.ipadic/blob/fe03f87a0c7c32945d956fcfc934c3e11d5eb182/internal/da/da.go#L37-L47
|
func Build(keywords []string) (DoubleArray, error) {
s := len(keywords)
if s == 0 {
return DoubleArray{}, nil
}
ids := make([]int, s, s)
for i := range ids {
ids[i] = i + 1
}
return BuildWithIDs(keywords, ids)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/cmd/junit/junit.go#L35-L50
|
func MakeCommand() *cobra.Command {
flags := &flags{}
cmd := &cobra.Command{
Use: "junit [profile]",
Short: "Summarize coverage profile and produce the result in junit xml format.",
Long: `Summarize coverage profile and produce the result in junit xml format.
Summary done at per-file and per-package level. Any coverage below coverage-threshold will be marked
with a <failure> tag in the xml produced.`,
Run: func(cmd *cobra.Command, args []string) {
run(flags, cmd, args)
},
}
cmd.Flags().StringVarP(&flags.outputFile, "output", "o", "-", "output file")
cmd.Flags().Float32VarP(&flags.threshold, "threshold", "t", .8, "code coverage threshold")
return cmd
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_transport.go#L250-L252
|
func (ref ostreeReference) signaturePath(index int) string {
return filepath.Join("manifest", fmt.Sprintf("signature-%d", index+1))
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/webhook.go#L81-L115
|
func webhookCreate(w http.ResponseWriter, r *http.Request, t auth.Token) error {
var webhook eventTypes.Webhook
err := ParseInput(r, &webhook)
if err != nil {
return err
}
if webhook.TeamOwner == "" {
webhook.TeamOwner, err = autoTeamOwner(t, permission.PermWebhookCreate)
if err != nil {
return err
}
}
ctx := permission.Context(permTypes.CtxTeam, webhook.TeamOwner)
if !permission.Check(t, permission.PermWebhookCreate, ctx) {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeWebhook, Value: webhook.Name},
Kind: permission.PermWebhookCreate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermWebhookReadEvents, ctx),
})
if err != nil {
return err
}
defer func() {
evt.Done(err)
}()
err = servicemanager.Webhook.Create(webhook)
if err == eventTypes.ErrWebhookAlreadyExists {
w.WriteHeader(http.StatusConflict)
}
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L701-L705
|
func (v EventDomStorageItemUpdated) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomstorage6(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L45-L49
|
func (nb *NotifyBundle) Disconnected(n Network, c Conn) {
if nb.DisconnectedF != nil {
nb.DisconnectedF(n, c)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/agent.go#L123-L144
|
func (ca *Agent) Set(c *Config) {
ca.mut.Lock()
defer ca.mut.Unlock()
var oldConfig Config
if ca.c != nil {
oldConfig = *ca.c
}
delta := Delta{oldConfig, *c}
ca.c = c
for _, subscription := range ca.subscriptions {
go func(sub DeltaChan) { // wait a minute to send each event
end := time.NewTimer(time.Minute)
select {
case sub <- delta:
case <-end.C:
}
if !end.Stop() { // prevent new events
<-end.C // drain the pending event
}
}(subscription)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L172-L186
|
func (ms *MemoryStorage) ApplySnapshot(snap pb.Snapshot) error {
ms.Lock()
defer ms.Unlock()
//handle check for old snapshot being applied
msIndex := ms.snapshot.Metadata.Index
snapIndex := snap.Metadata.Index
if msIndex >= snapIndex {
return ErrSnapOutOfDate
}
ms.snapshot = snap
ms.ents = []pb.Entry{{Term: snap.Metadata.Term, Index: snap.Metadata.Index}}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plank/controller.go#L169-L252
|
func (c *Controller) Sync() error {
pjs, err := c.kc.ListProwJobs(c.selector)
if err != nil {
return fmt.Errorf("error listing prow jobs: %v", err)
}
selector := fmt.Sprintf("%s=true", kube.CreatedByProw)
if len(c.selector) > 0 {
selector = strings.Join([]string{c.selector, selector}, ",")
}
pm := map[string]kube.Pod{}
for alias, client := range c.pkcs {
pods, err := client.ListPods(selector)
if err != nil {
return fmt.Errorf("error listing pods in cluster %q: %v", alias, err)
}
for _, pod := range pods {
pm[pod.ObjectMeta.Name] = pod
}
}
// TODO: Replace the following filtering with a field selector once CRDs support field selectors.
// https://github.com/kubernetes/kubernetes/issues/53459
var k8sJobs []prowapi.ProwJob
for _, pj := range pjs {
if pj.Spec.Agent == prowapi.KubernetesAgent {
k8sJobs = append(k8sJobs, pj)
}
}
pjs = k8sJobs
var syncErrs []error
if err := c.terminateDupes(pjs, pm); err != nil {
syncErrs = append(syncErrs, err)
}
// Share what we have for gathering metrics.
c.pjLock.Lock()
c.pjs = pjs
c.pjLock.Unlock()
pendingCh, triggeredCh := pjutil.PartitionActive(pjs)
errCh := make(chan error, len(pjs))
reportCh := make(chan prowapi.ProwJob, len(pjs))
// Reinstantiate on every resync of the controller instead of trying
// to keep this in sync with the state of the world.
c.pendingJobs = make(map[string]int)
// Sync pending jobs first so we can determine what is the maximum
// number of new jobs we can trigger when syncing the non-pendings.
maxSyncRoutines := c.config().Plank.MaxGoroutines
c.log.Debugf("Handling %d pending prowjobs", len(pendingCh))
syncProwJobs(c.log, c.syncPendingJob, maxSyncRoutines, pendingCh, reportCh, errCh, pm)
c.log.Debugf("Handling %d triggered prowjobs", len(triggeredCh))
syncProwJobs(c.log, c.syncTriggeredJob, maxSyncRoutines, triggeredCh, reportCh, errCh, pm)
close(errCh)
close(reportCh)
for err := range errCh {
syncErrs = append(syncErrs, err)
}
var reportErrs []error
if !c.skipReport {
reportTemplate := c.config().Plank.ReportTemplate
reportTypes := c.config().GitHubReporter.JobTypesToReport
for report := range reportCh {
if err := reportlib.Report(c.ghc, reportTemplate, report, reportTypes); err != nil {
reportErrs = append(reportErrs, err)
c.log.WithFields(pjutil.ProwJobFields(&report)).WithError(err).Warn("Failed to report ProwJob status")
}
// plank is not retrying on errors, so we just set the current state as reported
if err := c.setPreviousReportState(report); err != nil {
c.log.WithFields(pjutil.ProwJobFields(&report)).WithError(err).Error("Failed to patch PrevReportStates")
}
}
}
if len(syncErrs) == 0 && len(reportErrs) == 0 {
return nil
}
return fmt.Errorf("errors syncing: %v, errors reporting: %v", syncErrs, reportErrs)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/headlessexperimental.go#L72-L75
|
func (p BeginFrameParams) WithScreenshot(screenshot *ScreenshotParams) *BeginFrameParams {
p.Screenshot = screenshot
return &p
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L61-L76
|
func (peer *localPeer) ConnectionsTo(names []PeerName) []Connection {
if len(names) == 0 {
return nil
}
conns := make([]Connection, 0, len(names))
peer.RLock()
defer peer.RUnlock()
for _, name := range names {
conn, found := peer.connections[name]
// Again, !found could just be due to a race.
if found {
conns = append(conns, conn)
}
}
return conns
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/simplestreams_images.go#L214-L228
|
func (r *ProtocolSimpleStreams) GetImageAliasNames() ([]string, error) {
// Get all the images from simplestreams
aliases, err := r.ssClient.ListAliases()
if err != nil {
return nil, err
}
// And now extract just the names
names := []string{}
for _, alias := range aliases {
names = append(names, alias.Name)
}
return names, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.