_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/etcdhttp/metrics.go#L94-L123
|
func checkHealth(srv etcdserver.ServerV2) Health {
h := Health{Health: "true"}
as := srv.Alarms()
if len(as) > 0 {
h.Health = "false"
}
if h.Health == "true" {
if uint64(srv.Leader()) == raft.None {
h.Health = "false"
}
}
if h.Health == "true" {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
_, err := srv.Do(ctx, etcdserverpb.Request{Method: "QGET"})
cancel()
if err != nil {
h.Health = "false"
}
}
if h.Health == "true" {
healthSuccess.Inc()
} else {
healthFailed.Inc()
}
return h
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L839-L844
|
func DebugFunc(f func() string) error {
if isModeEnable(DEBG) {
return glg.out(DEBG, "%s", f())
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/status_code.go#L29-L48
|
func (o StatusCode) String() string {
return map[StatusCode]string{
OperationCreated: "Operation created",
Started: "Started",
Stopped: "Stopped",
Running: "Running",
Cancelling: "Cancelling",
Pending: "Pending",
Success: "Success",
Failure: "Failure",
Cancelled: "Cancelled",
Starting: "Starting",
Stopping: "Stopping",
Aborting: "Aborting",
Freezing: "Freezing",
Frozen: "Frozen",
Thawed: "Thawed",
Error: "Error",
}[o]
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L735-L827
|
func (m *Nitro) Visitor(snap *Snapshot, callb VisitorCallback, shards int, concurrency int) error {
var wg sync.WaitGroup
var pivotItems []*Item
wch := make(chan int, shards)
if snap == nil {
panic("snapshot cannot be nil")
}
func() {
tmpIter := m.NewIterator(snap)
if tmpIter == nil {
panic("iterator cannot be nil")
}
defer tmpIter.Close()
barrier := m.store.GetAccesBarrier()
token := barrier.Acquire()
defer barrier.Release(token)
pivotItems = append(pivotItems, nil) // start item
pivotPtrs := m.store.GetRangeSplitItems(shards)
for _, itmPtr := range pivotPtrs {
itm := m.ptrToItem(itmPtr)
tmpIter.Seek(itm.Bytes())
if tmpIter.Valid() {
prevItm := pivotItems[len(pivotItems)-1]
// Find bigger item than prev pivot
if prevItm == nil || m.insCmp(unsafe.Pointer(itm), unsafe.Pointer(prevItm)) > 0 {
pivotItems = append(pivotItems, itm)
}
}
}
pivotItems = append(pivotItems, nil) // end item
}()
errors := make([]error, len(pivotItems)-1)
// Run workers
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
for shard := range wch {
startItem := pivotItems[shard]
endItem := pivotItems[shard+1]
itr := m.NewIterator(snap)
if itr == nil {
panic("iterator cannot be nil")
}
defer itr.Close()
itr.SetRefreshRate(m.refreshRate)
if startItem == nil {
itr.SeekFirst()
} else {
itr.Seek(startItem.Bytes())
}
loop:
for ; itr.Valid(); itr.Next() {
if endItem != nil && m.insCmp(itr.GetNode().Item(), unsafe.Pointer(endItem)) >= 0 {
break loop
}
itm := (*Item)(itr.GetNode().Item())
if err := callb(itm, shard); err != nil {
errors[shard] = err
return
}
}
}
}(&wg)
}
// Provide work and wait
for shard := 0; shard < len(pivotItems)-1; shard++ {
wch <- shard
}
close(wch)
wg.Wait()
for _, err := range errors {
if err != nil {
return err
}
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L349-L380
|
func (d *dockerImageDestination) PutManifest(ctx context.Context, m []byte) error {
digest, err := manifest.Digest(m)
if err != nil {
return err
}
d.manifestDigest = digest
refTail, err := d.ref.tagOrDigest()
if err != nil {
return err
}
path := fmt.Sprintf(manifestPath, reference.Path(d.ref.ref), refTail)
headers := map[string][]string{}
mimeType := manifest.GuessMIMEType(m)
if mimeType != "" {
headers["Content-Type"] = []string{mimeType}
}
res, err := d.c.makeRequest(ctx, "PUT", path, headers, bytes.NewReader(m), v2Auth, nil)
if err != nil {
return err
}
defer res.Body.Close()
if !successStatus(res.StatusCode) {
err = errors.Wrapf(client.HandleErrorResponse(res), "Error uploading manifest %s to %s", refTail, d.ref.ref.Name())
if isManifestInvalidError(errors.Cause(err)) {
err = types.ManifestTypeRejectedError{Err: err}
}
return err
}
return nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L227-L271
|
func (f *FileSnapshotStore) getSnapshots() ([]*fileSnapshotMeta, error) {
// Get the eligible snapshots
snapshots, err := ioutil.ReadDir(f.path)
if err != nil {
f.logger.Printf("[ERR] snapshot: Failed to scan snapshot dir: %v", err)
return nil, err
}
// Populate the metadata
var snapMeta []*fileSnapshotMeta
for _, snap := range snapshots {
// Ignore any files
if !snap.IsDir() {
continue
}
// Ignore any temporary snapshots
dirName := snap.Name()
if strings.HasSuffix(dirName, tmpSuffix) {
f.logger.Printf("[WARN] snapshot: Found temporary snapshot: %v", dirName)
continue
}
// Try to read the meta data
meta, err := f.readMeta(dirName)
if err != nil {
f.logger.Printf("[WARN] snapshot: Failed to read metadata for %v: %v", dirName, err)
continue
}
// Make sure we can understand this version.
if meta.Version < SnapshotVersionMin || meta.Version > SnapshotVersionMax {
f.logger.Printf("[WARN] snapshot: Snapshot version for %v not supported: %d", dirName, meta.Version)
continue
}
// Append, but only return up to the retain count
snapMeta = append(snapMeta, meta)
}
// Sort the snapshot, reverse so we get new -> old
sort.Sort(sort.Reverse(snapMetaSlice(snapMeta)))
return snapMeta, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L252-L258
|
func (c *dummyClient) Get(name string) (Object, error) {
obj, ok := c.objects[name]
if ok {
return obj, nil
}
return nil, fmt.Errorf("could not find %s", name)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L186-L192
|
func (ud *UserData) Extract(id string, out interface{}) error {
content, ok := ud.Load(id)
if !ok {
return &UserDataNotFound{id}
}
return yaml.Unmarshal([]byte(content.(string)), out)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L52-L71
|
func (b *TransactionBuilder) Hash() ([32]byte, error) {
var txBytes bytes.Buffer
_, err := fmt.Fprintf(&txBytes, "%s", b.NetworkID)
if err != nil {
return [32]byte{}, err
}
_, err = xdr.Marshal(&txBytes, xdr.EnvelopeTypeEnvelopeTypeTx)
if err != nil {
return [32]byte{}, err
}
_, err = xdr.Marshal(&txBytes, b.TX)
if err != nil {
return [32]byte{}, err
}
return hash.Hash(txBytes.Bytes()), nil
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L304-L331
|
func (r *Firewall) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("firewall.Delete")
deleteResource, ok := actual.(*Firewall)
if !ok {
return nil, nil, fmt.Errorf("failed to type convert actual Firewall type ")
}
if deleteResource.Name == "" {
return immutable, nil, nil
return nil, nil, fmt.Errorf("Unable to delete firewall resource without Name [%s]", deleteResource.Name)
}
if _, err := Sdk.Client.Firewalls.Delete(context.TODO(), deleteResource.FirewallID); err != nil {
return nil, nil, fmt.Errorf("failed to delete firewall [%s] err: %v", deleteResource.Name, err)
}
logger.Success("Deleted firewall [%s]", deleteResource.FirewallID)
newResource := &Firewall{
Shared: Shared{
Name: r.Name,
Tags: r.Tags,
},
InboundRules: r.InboundRules,
OutboundRules: r.OutboundRules,
Created: r.Created,
}
newCluster := r.immutableRender(newResource, immutable)
return newCluster, newResource, nil
}
|
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L197-L202
|
func Append(buf *bytes.Buffer, node SQLNode) {
tbuf := &TrackedBuffer{
Buffer: buf,
}
node.Format(tbuf)
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L162-L167
|
func (s *MockSpan) SetBaggageItem(key, val string) opentracing.Span {
s.Lock()
defer s.Unlock()
s.SpanContext = s.SpanContext.WithBaggageItem(key, val)
return s
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/comm.go#L18-L28
|
func (p *PubSub) getHelloPacket() *RPC {
var rpc RPC
for t := range p.myTopics {
as := &pb.RPC_SubOpts{
Topicid: proto.String(t),
Subscribe: proto.Bool(true),
}
rpc.Subscriptions = append(rpc.Subscriptions, as)
}
return &rpc
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L2282-L2286
|
func (v *Content) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar13(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/sign.go#L10-L31
|
func (c *copier) createSignature(manifest []byte, keyIdentity string) ([]byte, error) {
mech, err := signature.NewGPGSigningMechanism()
if err != nil {
return nil, errors.Wrap(err, "Error initializing GPG")
}
defer mech.Close()
if err := mech.SupportsSigning(); err != nil {
return nil, errors.Wrap(err, "Signing not supported")
}
dockerReference := c.dest.Reference().DockerReference()
if dockerReference == nil {
return nil, errors.Errorf("Cannot determine canonical Docker reference for destination %s", transports.ImageName(c.dest.Reference()))
}
c.Printf("Signing manifest\n")
newSig, err := signature.SignDockerManifest(manifest, dockerReference.String(), mech, keyIdentity)
if err != nil {
return nil, errors.Wrap(err, "Error creating signature")
}
return newSig, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L145-L161
|
func (cm *connectionMaker) Targets(activeOnly bool) []string {
resultChan := make(chan []string)
cm.actionChan <- func() bool {
var slice []string
for peer, addr := range cm.directPeers {
if activeOnly {
if target, ok := cm.targets[cm.completeAddr(*addr)]; ok && target.tryAfter.IsZero() {
continue
}
}
slice = append(slice, peer)
}
resultChan <- slice
return false
}
return <-resultChan
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6486-L6490
|
func (v DescribeNodeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom73(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcindex/tcindex.go#L86-L93
|
func NewFromEnv() *Index {
c := tcclient.CredentialsFromEnvVars()
return &Index{
Credentials: c,
BaseURL: tcclient.BaseURL(tcclient.RootURLFromEnvVars(), "index", "v1"),
Authenticate: c.ClientID != "",
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/profiles_utils.go#L188-L221
|
func doProfileUpdateContainer(d *Daemon, name string, old api.ProfilePut, nodeName string, args db.ContainerArgs) error {
if args.Node != "" && args.Node != nodeName {
// No-op, this container does not belong to this node.
return nil
}
profiles, err := d.cluster.ProfilesGet(args.Project, args.Profiles)
if err != nil {
return err
}
for i, profileName := range args.Profiles {
if profileName == name {
// Use the old config and devices.
profiles[i].Config = old.Config
profiles[i].Devices = old.Devices
break
}
}
c := containerLXCInstantiate(d.State(), args)
c.expandConfig(profiles)
c.expandDevices(profiles)
return c.Update(db.ContainerArgs{
Architecture: c.Architecture(),
Config: c.LocalConfig(),
Description: c.Description(),
Devices: c.LocalDevices(),
Ephemeral: c.IsEphemeral(),
Profiles: c.Profiles(),
Project: c.Project(),
}, true)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/goimage.go#L62-L88
|
func (img *IplImage) ToImage() image.Image {
var height, width, channels, step int = img.Height(), img.Width(), img.Channels(), img.WidthStep()
out := image.NewNRGBA(image.Rect(0, 0, width, height))
if img.Depth() != IPL_DEPTH_8U {
return nil // TODO return error
}
// Turn opencv.Iplimage.imageData(*char) to slice
var limg *C.char = img.imageData
var limg_ptr unsafe.Pointer = unsafe.Pointer(limg)
var data []C.char = (*[1 << 30]C.char)(limg_ptr)[:height*step : height*step]
c := color.NRGBA{R: uint8(0), G: uint8(0), B: uint8(0), A: uint8(255)}
// Iteratively assign imageData's color to Go's image
for y := 0; y < height; y++ {
for x := 0; x < step; x = x + channels {
c.B = uint8(data[y*step+x])
c.G = uint8(data[y*step+x+1])
c.R = uint8(data[y*step+x+2])
if channels == 4 {
c.A = uint8(data[y*step+x+3])
}
out.SetNRGBA(int(x/channels), y, c)
}
}
return out
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L402-L404
|
func (t TouchType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L277-L281
|
func (eC2Manager *EC2Manager) Regions() error {
cd := tcclient.Client(*eC2Manager)
_, _, err := (&cd).APICall(nil, "GET", "/internal/regions", nil, nil)
return err
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L105-L110
|
func (s *followerReplication) LastContact() time.Time {
s.lastContactLock.RLock()
last := s.lastContact
s.lastContactLock.RUnlock()
return last
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/cmds.go#L436-L468
|
func GetAuthTokenCmd(noMetrics, noPortForwarding *bool) *cobra.Command {
var quiet bool
getAuthToken := &cobra.Command{
Use: "{{alias}} <username>",
Short: "Get an auth token that authenticates the holder as \"username\"",
Long: "Get an auth token that authenticates the holder as \"username\"; " +
"this can only be called by cluster admins",
Run: cmdutil.RunFixedArgs(1, func(args []string) error {
subject := args[0]
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
resp, err := c.GetAuthToken(c.Ctx(), &auth.GetAuthTokenRequest{
Subject: subject,
})
if err != nil {
return grpcutil.ScrubGRPC(err)
}
if quiet {
fmt.Println(resp.Token)
} else {
fmt.Printf("New credentials:\n Subject: %s\n Token: %s\n", resp.Subject, resp.Token)
}
return nil
}),
}
getAuthToken.PersistentFlags().BoolVarP(&quiet, "quiet", "q", false, "if "+
"set, only print the resulting token (if successful). This is useful for "+
"scripting, as the output can be piped to use-auth-token")
return cmdutil.CreateAlias(getAuthToken, "auth get-auth-token")
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L686-L706
|
func (n *netPipeline) decodeResponses() {
timeout := n.trans.timeout
for {
select {
case future := <-n.inprogressCh:
if timeout > 0 {
n.conn.conn.SetReadDeadline(time.Now().Add(timeout))
}
_, err := decodeResponse(n.conn, future.resp)
future.respond(err)
select {
case n.doneCh <- future:
case <-n.shutdownCh:
return
}
case <-n.shutdownCh:
return
}
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_src.go#L94-L96
|
func (s *dirImageSource) LayerInfosForCopy(ctx context.Context) ([]types.BlobInfo, error) {
return nil, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6510-L6519
|
func (u StellarMessage) GetHello() (result Hello, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Hello" {
result = *u.Hello
ok = true
}
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/tlsutil/cipher_suites.go#L48-L51
|
func GetCipherSuite(s string) (uint16, bool) {
v, ok := cipherSuites[s]
return v, ok
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L74-L119
|
func (s *Server) Start() (err error) {
log.Infof("Lunarc is starting on port :%d", s.Config.Port)
var l net.Listener
go func() {
l, err = net.Listen("tcp", fmt.Sprintf(":%d", s.Config.Port))
if err != nil {
log.Errorf("Error: %v", err)
s.Error <- err
return
}
s.isStarted = true
if len(s.Config.SSL.Certificate) > 0 && len(s.Config.SSL.Key) > 0 {
err = s.ServeTLS(l, s.Config.SSL.Certificate, s.Config.SSL.Key)
if err != nil && err != http.ErrServerClosed {
log.Errorf("%v", err)
l.Close()
s.Error <- err
s.quit <- true
}
close(s.quit)
} else {
err = s.Serve(l)
if err != nil && err != http.ErrServerClosed {
log.Errorf("%v", err)
s.Error <- err
s.quit <- true
}
close(s.quit)
}
}()
<-s.quit
if err = s.Shutdown(context.Background()); err != nil {
log.Errorf("%v", err)
s.Error <- err
}
<-s.quit
l = nil
log.Info("Lunarc terminated.")
s.isStarted = false
s.Done <- true
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1488-L1500
|
func (r *ProtocolLXD) SetContainerMetadata(name string, metadata api.ImageMetadata, ETag string) error {
if !r.HasExtension("container_edit_metadata") {
return fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension")
}
url := fmt.Sprintf("/containers/%s/metadata", url.QueryEscape(name))
_, _, err := r.query("PUT", url, metadata, ETag)
if err != nil {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L101-L117
|
func (t *State) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch State(in.String()) {
case StateUnknown:
*t = StateUnknown
case StateNeutral:
*t = StateNeutral
case StateInsecure:
*t = StateInsecure
case StateSecure:
*t = StateSecure
case StateInfo:
*t = StateInfo
default:
in.AddError(errors.New("unknown State value"))
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/build/controller.go#L722-L731
|
func determineTimeout(spec *buildv1alpha1.BuildSpec, dc *prowjobv1.DecorationConfig, defaultTimeout time.Duration) time.Duration {
switch {
case spec.Timeout != nil:
return spec.Timeout.Duration
case dc != nil && dc.Timeout.Duration > 0:
return dc.Timeout.Duration
default:
return defaultTimeout
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L409-L413
|
func (v SamplingProfileNode) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/type_analysis.go#L17-L57
|
func (a *APIAnalyzer) AnalyzeAttribute(name, query string, attr map[string]interface{}) (*gen.ActionParam, error) {
param := gen.ActionParam{Name: name, QueryName: query, VarName: toVarName(name)}
if d, ok := attr["description"]; ok {
param.Description = removeBlankLines(d.(string))
}
if r, ok := attr["required"]; ok {
if r.(bool) {
param.Mandatory = true
}
}
if options, ok := attr["options"]; ok {
opts, ok := options.(map[string]interface{})
if ok {
for n, o := range opts {
switch n {
case "max":
param.Max = int(o.(float64))
case "min":
param.Min = int(o.(float64))
case "regexp":
param.Regexp = o.(string)
}
}
}
}
if values, ok := attr["values"]; ok {
param.ValidValues = values.([]interface{})
}
t := attr["type"].(map[string]interface{})
dataType, err := a.AnalyzeType(t, query)
if err != nil {
return nil, err
}
param.Type = dataType
switch dataType.(type) {
case *gen.ArrayDataType:
param.QueryName += "[]"
}
return ¶m, nil
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L406-L616
|
func (p Page) Content() Content {
strm := p.V.Key("Contents")
var enc TextEncoding = &nopEncoder{}
var g = gstate{
Th: 1,
CTM: ident,
}
var text []Text
showText := func(s string) {
n := 0
for _, ch := range enc.Decode(s) {
Trm := matrix{{g.Tfs * g.Th, 0, 0}, {0, g.Tfs, 0}, {0, g.Trise, 1}}.mul(g.Tm).mul(g.CTM)
w0 := g.Tf.Width(int(s[n]))
n++
if ch != ' ' {
f := g.Tf.BaseFont()
if i := strings.Index(f, "+"); i >= 0 {
f = f[i+1:]
}
text = append(text, Text{f, Trm[0][0], Trm[2][0], Trm[2][1], w0 / 1000 * Trm[0][0], string(ch)})
}
tx := w0/1000*g.Tfs + g.Tc
if ch == ' ' {
tx += g.Tw
}
tx *= g.Th
g.Tm = matrix{{1, 0, 0}, {0, 1, 0}, {tx, 0, 1}}.mul(g.Tm)
}
}
var rect []Rect
var gstack []gstate
Interpret(strm, func(stk *Stack, op string) {
n := stk.Len()
args := make([]Value, n)
for i := n - 1; i >= 0; i-- {
args[i] = stk.Pop()
}
switch op {
default:
//fmt.Println(op, args)
return
case "cm": // update g.CTM
if len(args) != 6 {
panic("bad g.Tm")
}
var m matrix
for i := 0; i < 6; i++ {
m[i/2][i%2] = args[i].Float64()
}
m[2][2] = 1
g.CTM = m.mul(g.CTM)
case "gs": // set parameters from graphics state resource
gs := p.Resources().Key("ExtGState").Key(args[0].Name())
font := gs.Key("Font")
if font.Kind() == Array && font.Len() == 2 {
//fmt.Println("FONT", font)
}
case "f": // fill
case "g": // setgray
case "l": // lineto
case "m": // moveto
case "cs": // set colorspace non-stroking
case "scn": // set color non-stroking
case "re": // append rectangle to path
if len(args) != 4 {
panic("bad re")
}
x, y, w, h := args[0].Float64(), args[1].Float64(), args[2].Float64(), args[3].Float64()
rect = append(rect, Rect{Point{x, y}, Point{x + w, y + h}})
case "q": // save graphics state
gstack = append(gstack, g)
case "Q": // restore graphics state
n := len(gstack) - 1
g = gstack[n]
gstack = gstack[:n]
case "BT": // begin text (reset text matrix and line matrix)
g.Tm = ident
g.Tlm = g.Tm
case "ET": // end text
case "T*": // move to start of next line
x := matrix{{1, 0, 0}, {0, 1, 0}, {0, -g.Tl, 1}}
g.Tlm = x.mul(g.Tlm)
g.Tm = g.Tlm
case "Tc": // set character spacing
if len(args) != 1 {
panic("bad g.Tc")
}
g.Tc = args[0].Float64()
case "TD": // move text position and set leading
if len(args) != 2 {
panic("bad Td")
}
g.Tl = -args[1].Float64()
fallthrough
case "Td": // move text position
if len(args) != 2 {
panic("bad Td")
}
tx := args[0].Float64()
ty := args[1].Float64()
x := matrix{{1, 0, 0}, {0, 1, 0}, {tx, ty, 1}}
g.Tlm = x.mul(g.Tlm)
g.Tm = g.Tlm
case "Tf": // set text font and size
if len(args) != 2 {
panic("bad TL")
}
f := args[0].Name()
g.Tf = p.Font(f)
enc = g.Tf.Encoder()
if enc == nil {
println("no cmap for", f)
enc = &nopEncoder{}
}
g.Tfs = args[1].Float64()
case "\"": // set spacing, move to next line, and show text
if len(args) != 3 {
panic("bad \" operator")
}
g.Tw = args[0].Float64()
g.Tc = args[1].Float64()
args = args[2:]
fallthrough
case "'": // move to next line and show text
if len(args) != 1 {
panic("bad ' operator")
}
x := matrix{{1, 0, 0}, {0, 1, 0}, {0, -g.Tl, 1}}
g.Tlm = x.mul(g.Tlm)
g.Tm = g.Tlm
fallthrough
case "Tj": // show text
if len(args) != 1 {
panic("bad Tj operator")
}
showText(args[0].RawString())
case "TJ": // show text, allowing individual glyph positioning
v := args[0]
for i := 0; i < v.Len(); i++ {
x := v.Index(i)
if x.Kind() == String {
showText(x.RawString())
} else {
tx := -x.Float64() / 1000 * g.Tfs * g.Th
g.Tm = matrix{{1, 0, 0}, {0, 1, 0}, {tx, 0, 1}}.mul(g.Tm)
}
}
case "TL": // set text leading
if len(args) != 1 {
panic("bad TL")
}
g.Tl = args[0].Float64()
case "Tm": // set text matrix and line matrix
if len(args) != 6 {
panic("bad g.Tm")
}
var m matrix
for i := 0; i < 6; i++ {
m[i/2][i%2] = args[i].Float64()
}
m[2][2] = 1
g.Tm = m
g.Tlm = m
case "Tr": // set text rendering mode
if len(args) != 1 {
panic("bad Tr")
}
g.Tmode = int(args[0].Int64())
case "Ts": // set text rise
if len(args) != 1 {
panic("bad Ts")
}
g.Trise = args[0].Float64()
case "Tw": // set word spacing
if len(args) != 1 {
panic("bad g.Tw")
}
g.Tw = args[0].Float64()
case "Tz": // set horizontal text scaling
if len(args) != 1 {
panic("bad Tz")
}
g.Th = args[0].Float64() / 100
}
})
return Content{text, rect}
}
|
https://github.com/alecthomas/mph/blob/cf7b0cd2d9579868ec2a49493fd62b2e28bcb336/chd.go#L133-L166
|
func (c *CHD) Write(w io.Writer) error {
write := func(nd ...interface{}) error {
for _, d := range nd {
if err := binary.Write(w, binary.LittleEndian, d); err != nil {
return err
}
}
return nil
}
data := []interface{}{
uint32(len(c.r)), c.r,
uint32(len(c.indices)), c.indices,
uint32(len(c.keys)),
}
if err := write(data...); err != nil {
return err
}
for i := range c.keys {
k, v := c.keys[i], c.values[i]
if err := write(uint32(len(k)), uint32(len(v))); err != nil {
return err
}
if _, err := w.Write(k); err != nil {
return err
}
if _, err := w.Write(v); err != nil {
return err
}
}
return nil
}
|
https://github.com/intelsdi-x/gomit/blob/286c3ad6599724faed681cd18a9ff595b00d9f3f/event_controller.go#L125-L138
|
func (e *EventController) lazyLoadHandler() {
// Lazy loading of EventController handler mutex
if e.handlerMutex == nil {
e.handlerMutex = new(sync.Mutex)
}
// Lazy loading of EventController handler map
if e.Handlers == nil {
e.handlerMutex.Lock()
e.Handlers = make(map[string]Handler)
e.handlerMutex.Unlock()
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1128-L1132
|
func (v *PageTimings) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar5(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L869-L873
|
func (v *StartTypeProfileParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler10(&r, v)
return r.Error()
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L267-L269
|
func (lf Field) String() string {
return fmt.Sprint(lf.key, ":", lf.Value())
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/diff/differ.go#L18-L46
|
func New(releaseRepo pull.Release, r1Path, r2Path string) (differ Differ, err error) {
if filepath.Ext(r1Path) != filepath.Ext(r2Path) {
err = fmt.Errorf("The specified releases didn't have matching file extensions, " +
"assuming different release types.")
return
}
if filepath.Ext(r1Path) == ".pivotal" {
var r1, r2 *release.PivnetRelease
if r1, err = release.LoadPivnetRelease(releaseRepo, r1Path); err == nil {
if r2, err = release.LoadPivnetRelease(releaseRepo, r2Path); err == nil {
differ = pivnetReleaseDiffer{
release1: r1,
release2: r2,
}
}
}
} else {
var r1, r2 *release.BoshRelease
if r1, err = release.LoadBoshRelease(releaseRepo, r1Path); err == nil {
if r2, err = release.LoadBoshRelease(releaseRepo, r2Path); err == nil {
differ = boshReleaseDiffer{
release1: r1,
release2: r2,
}
}
}
}
return
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L253-L263
|
func (n *NetworkTransport) Close() error {
n.shutdownLock.Lock()
defer n.shutdownLock.Unlock()
if !n.shutdown {
close(n.shutdownCh)
n.stream.Close()
n.shutdown = true
}
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/build.go#L20-L98
|
func New(opts *Options) (*genny.Generator, error) {
g := genny.New()
if err := opts.Validate(); err != nil {
return g, err
}
g.ErrorFn = func(err error) {
events.EmitError(EvtBuildStopErr, err, events.Payload{"opts": opts})
}
g.RunFn(func(r *genny.Runner) error {
events.EmitPayload(EvtBuildStart, events.Payload{"opts": opts})
return nil
})
g.Transformer(genny.Dot())
// validate templates
g.RunFn(ValidateTemplates(templateWalker(opts.App), opts.TemplateValidators))
// rename main() to originalMain()
g.RunFn(transformMain(opts))
// add any necessary templates for the build
box := packr.New("github.com/gobuffalo/buffalo/genny/build", "../build/templates")
if err := g.Box(box); err != nil {
return g, err
}
// configure plush
ctx := plush.NewContext()
ctx.Set("opts", opts)
ctx.Set("buildTime", opts.BuildTime.Format(time.RFC3339))
ctx.Set("buildVersion", opts.BuildVersion)
ctx.Set("buffaloVersion", runtime.Version)
g.Transformer(plushgen.Transformer(ctx))
// create the ./a pkg
ag, err := apkg(opts)
if err != nil {
return g, err
}
g.Merge(ag)
if opts.WithAssets {
// mount the assets generator
ag, err := assets(opts)
if err != nil {
return g, err
}
g.Merge(ag)
}
// mount the build time dependency generator
dg, err := buildDeps(opts)
if err != nil {
return g, err
}
g.Merge(dg)
g.RunFn(func(r *genny.Runner) error {
return jam.Pack(jam.PackOptions{})
})
// create the final go build command
c, err := buildCmd(opts)
if err != nil {
return g, err
}
g.Command(c)
g.RunFn(Cleanup(opts))
g.RunFn(func(r *genny.Runner) error {
events.EmitPayload(EvtBuildStop, events.Payload{"opts": opts})
return nil
})
return g, nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L760-L762
|
func (src *IplImage) Avg(mask *IplImage) Scalar {
return (Scalar)(C.cvAvg(unsafe.Pointer(src), unsafe.Pointer(mask)))
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/pcm_scale.go#L12-L22
|
func PCMScale(buf *audio.FloatBuffer, bitDepth int) error {
if buf == nil || buf.Format == nil {
return audio.ErrInvalidBuffer
}
factor := math.Pow(2, 8*float64(bitDepth/8)-1)
for i := 0; i < len(buf.Data); i++ {
buf.Data[i] *= factor
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L3618-L3625
|
func (r *Image) Locator(api *API) *ImageLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.ImageLocator(l["href"])
}
}
return nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L85-L116
|
func (cm *connectionMaker) InitiateConnections(peers []string, replace bool) []error {
errors := []error{}
addrs := peerAddrs{}
for _, peer := range peers {
host, port, err := net.SplitHostPort(peer)
if err != nil {
host = peer
port = "0" // we use that as an indication that "no port was supplied"
}
if host == "" || !isAlnum(port) {
errors = append(errors, fmt.Errorf("invalid peer name %q, should be host[:port]", peer))
} else if addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%s", host, port)); err != nil {
errors = append(errors, err)
} else {
addrs[peer] = addr
}
}
cm.actionChan <- func() bool {
if replace {
cm.directPeers = peerAddrs{}
}
for peer, addr := range addrs {
cm.directPeers[peer] = addr
// curtail any existing reconnect interval
if target, found := cm.targets[cm.completeAddr(*addr)]; found {
target.nextTryNow()
}
}
return true
}
return errors
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L134-L146
|
func roleGetCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("role get command requires role name as its argument"))
}
name := args[0]
resp, err := mustClientFromCmd(cmd).Auth.RoleGet(context.TODO(), name)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleGet(name, *resp)
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L413-L415
|
func (b *Base) Infof(msg string, a ...interface{}) error {
return b.Log(LevelInfo, nil, msg, a...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6116-L6120
|
func (v *EventFontsUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss55(&r, v)
return r.Error()
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L84-L87
|
func (p MailBuilder) CCAddrs(cc []mail.Address) MailBuilder {
p.cc = cc
return p
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1132-L1200
|
func appLog(w http.ResponseWriter, r *http.Request, t auth.Token) error {
var err error
var lines int
if l := r.URL.Query().Get("lines"); l != "" {
lines, err = strconv.Atoi(l)
if err != nil {
msg := `Parameter "lines" must be an integer.`
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
} else {
return &errors.HTTP{Code: http.StatusBadRequest, Message: `Parameter "lines" is mandatory.`}
}
w.Header().Set("Content-Type", "application/x-json-stream")
source := r.URL.Query().Get("source")
unit := r.URL.Query().Get("unit")
follow := r.URL.Query().Get("follow")
appName := r.URL.Query().Get(":app")
filterLog := app.Applog{Source: source, Unit: unit}
a, err := getAppFromContext(appName, r)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermAppReadLog,
contextsForApp(&a)...,
)
if !allowed {
return permission.ErrUnauthorized
}
logs, err := a.LastLogs(lines, filterLog)
if err != nil {
return err
}
encoder := json.NewEncoder(w)
err = encoder.Encode(logs)
if err != nil {
return err
}
if follow != "1" {
return nil
}
closeChan := r.Context().Done()
l, err := app.NewLogListener(&a, filterLog)
if err != nil {
return err
}
logTracker.add(l)
defer func() {
logTracker.remove(l)
l.Close()
}()
logChan := l.ListenChan()
for {
var logMsg app.Applog
var chOpen bool
select {
case <-closeChan:
return nil
case logMsg, chOpen = <-logChan:
}
if !chOpen {
return nil
}
err := encoder.Encode([]app.Applog{logMsg})
if err != nil {
break
}
}
return nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/delete_apps_app_routes_route_parameters.go#L82-L85
|
func (o *DeleteAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *DeleteAppsAppRoutesRouteParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L834-L836
|
func Debugf(format string, val ...interface{}) error {
return glg.out(DEBG, format, val...)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L1243-L1301
|
func (loc *ScheduledActionLocator) Create(action string, executionId string, firstOccurrence *time.Time, options rsapi.APIParams) (*ScheduledActionLocator, error) {
var res *ScheduledActionLocator
if action == "" {
return res, fmt.Errorf("action is required")
}
if executionId == "" {
return res, fmt.Errorf("executionId is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"action": action,
"execution_id": executionId,
"first_occurrence": firstOccurrence,
}
var nameOpt = options["name"]
if nameOpt != nil {
p["name"] = nameOpt
}
var operationOpt = options["operation"]
if operationOpt != nil {
p["operation"] = operationOpt
}
var recurrenceOpt = options["recurrence"]
if recurrenceOpt != nil {
p["recurrence"] = recurrenceOpt
}
var timezoneOpt = options["timezone"]
if timezoneOpt != nil {
p["timezone"] = timezoneOpt
}
uri, err := loc.ActionPath("ScheduledAction", "create")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
location := resp.Header.Get("Location")
if len(location) == 0 {
return res, fmt.Errorf("Missing location header in response")
} else {
return &ScheduledActionLocator{Href(location), loc.api}, nil
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/transport.go#L302-L312
|
func (p *pipeline) AppendEntries(args *raft.AppendEntriesRequest, resp *raft.AppendEntriesResponse) (raft.AppendFuture, error) {
e := &appendEntry{
req: args,
res: resp,
start: time.Now(),
ready: make(chan error),
consumer: p.consumer,
}
p.work <- e
return e, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L2299-L2303
|
func (v *EventConsoleProfileStarted) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler22(&r, v)
return r.Error()
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L216-L269
|
func (c *Consumer) CommitOffsets() error {
c.commitMu.Lock()
defer c.commitMu.Unlock()
memberID, generationID := c.membership()
req := &sarama.OffsetCommitRequest{
Version: 2,
ConsumerGroup: c.groupID,
ConsumerGroupGeneration: generationID,
ConsumerID: memberID,
RetentionTime: -1,
}
if ns := c.client.config.Consumer.Offsets.Retention; ns != 0 {
req.RetentionTime = int64(ns / time.Millisecond)
}
snap := c.subs.Snapshot()
dirty := false
for tp, state := range snap {
if state.Dirty {
dirty = true
req.AddBlock(tp.Topic, tp.Partition, state.Info.Offset, 0, state.Info.Metadata)
}
}
if !dirty {
return nil
}
broker, err := c.client.Coordinator(c.groupID)
if err != nil {
c.closeCoordinator(broker, err)
return err
}
resp, err := broker.CommitOffset(req)
if err != nil {
c.closeCoordinator(broker, err)
return err
}
for topic, errs := range resp.Errors {
for partition, kerr := range errs {
if kerr != sarama.ErrNoError {
err = kerr
} else if state, ok := snap[topicPartition{topic, partition}]; ok {
if sub := c.subs.Fetch(topic, partition); sub != nil {
sub.markCommitted(state.Info.Offset)
}
}
}
}
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L368-L370
|
func (p *PauseOnAsyncCallParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandPauseOnAsyncCall, p, nil)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L866-L874
|
func (c *putFileClient) PutFileSplitWriter(repoName string, commitID string, path string,
delimiter pfs.Delimiter, targetFileDatums int64, targetFileBytes int64, headerRecords int64, overwrite bool) (io.WriteCloser, error) {
// TODO(msteffen) add headerRecords
var overwriteIndex *pfs.OverwriteIndex
if overwrite {
overwriteIndex = &pfs.OverwriteIndex{}
}
return c.newPutFileWriteCloser(repoName, commitID, path, delimiter, targetFileDatums, targetFileBytes, headerRecords, overwriteIndex)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/flakyjob-reporter.go#L76-L98
|
func (fjr *FlakyJobReporter) Issues(c *creator.IssueCreator) ([]creator.Issue, error) {
fjr.creator = c
json, err := ReadHTTP(fjr.flakyJobDataURL)
if err != nil {
return nil, err
}
flakyJobs, err := fjr.parseFlakyJobs(json)
if err != nil {
return nil, err
}
count := fjr.syncCount
if len(flakyJobs) < count {
count = len(flakyJobs)
}
issues := make([]creator.Issue, 0, count)
for _, fj := range flakyJobs[0:count] {
issues = append(issues, fj)
}
return issues, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1879-L1887
|
func (u OperationBody) MustPathPaymentOp() PathPaymentOp {
val, ok := u.GetPathPaymentOp()
if !ok {
panic("arm PathPaymentOp is not set")
}
return val
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/downwardapi/jobspec.go#L50-L60
|
func NewJobSpec(spec prowapi.ProwJobSpec, buildID, prowJobID string) JobSpec {
return JobSpec{
Type: spec.Type,
Job: spec.Job,
BuildID: buildID,
ProwJobID: prowJobID,
Refs: spec.Refs,
ExtraRefs: spec.ExtraRefs,
agent: spec.Agent,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L184-L188
|
func (v SetDiscoverTargetsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L60-L68
|
func (r *ProtocolLXD) CreateProfile(profile api.ProfilesPost) error {
// Send the request
_, _, err := r.query("POST", "/profiles", profile, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/mason.go#L530-L541
|
func (m *Mason) Start() {
ctx, cancel := context.WithCancel(context.Background())
m.cancel = cancel
m.start(ctx, m.syncAll)
m.start(ctx, m.recycleAll)
m.start(ctx, m.fulfillAll)
for i := 0; i < m.cleanerCount; i++ {
m.start(ctx, m.cleanAll)
}
m.start(ctx, m.freeAll)
logrus.Info("Mason started")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1071-L1075
|
func (v *GetCurrentTimeReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation11(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/tracing.go#L161-L164
|
func (p StartParams) WithTraceConfig(traceConfig *TraceConfig) *StartParams {
p.TraceConfig = traceConfig
return &p
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L92-L95
|
func (p MailBuilder) BCC(name, addr string) MailBuilder {
p.bcc = append(p.bcc, mail.Address{Name: name, Address: addr})
return p
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L98-L121
|
func FromGRPC(in error) Error {
out := &impl{
message: grpc.ErrorDesc(in),
typ: GRPCCodeToType(grpc.Code(in)),
code: NoCode,
}
matches := grpcMessageFormat.FindStringSubmatch(in.Error())
if len(matches) < 4 {
return out
}
out.message = matches[1]
out.code = parseCode(matches[2])
_ = json.Unmarshal([]byte(matches[3]), &out.attributes)
got := Get(Code(out.code))
if got == nil {
return out
}
return got.New(out.attributes)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/prowjob.go#L112-L122
|
func (c *prowJobs) Update(prowJob *v1.ProwJob) (result *v1.ProwJob, err error) {
result = &v1.ProwJob{}
err = c.client.Put().
Namespace(c.ns).
Resource("prowjobs").
Name(prowJob.Name).
Body(prowJob).
Do().
Into(result)
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L373-L376
|
func (p GetCookiesParams) WithUrls(urls []string) *GetCookiesParams {
p.Urls = urls
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L394-L398
|
func (v StopScreencastParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes_cluster_clients.go#L58-L80
|
func (o *ExperimentalKubernetesOptions) Validate(dryRun bool) error {
if dryRun && o.DeckURI == "" {
return errors.New("a dry-run was requested but required flag -deck-url was unset")
}
if o.DeckURI != "" {
if _, err := url.ParseRequestURI(o.DeckURI); err != nil {
return fmt.Errorf("invalid -deck-url URI: %q", o.DeckURI)
}
}
if o.kubeconfig != "" {
if _, err := os.Stat(o.kubeconfig); err != nil {
return fmt.Errorf("error accessing --kubeconfig: %v", err)
}
}
if o.kubeconfig != "" && o.buildCluster != "" {
return errors.New("must provide only --build-cluster OR --kubeconfig")
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_dest.go#L28-L79
|
func newImageDestination(ref dirReference, compress bool) (types.ImageDestination, error) {
d := &dirImageDestination{ref: ref, compress: compress}
// If directory exists check if it is empty
// if not empty, check whether the contents match that of a container image directory and overwrite the contents
// if the contents don't match throw an error
dirExists, err := pathExists(d.ref.resolvedPath)
if err != nil {
return nil, errors.Wrapf(err, "error checking for path %q", d.ref.resolvedPath)
}
if dirExists {
isEmpty, err := isDirEmpty(d.ref.resolvedPath)
if err != nil {
return nil, err
}
if !isEmpty {
versionExists, err := pathExists(d.ref.versionPath())
if err != nil {
return nil, errors.Wrapf(err, "error checking if path exists %q", d.ref.versionPath())
}
if versionExists {
contents, err := ioutil.ReadFile(d.ref.versionPath())
if err != nil {
return nil, err
}
// check if contents of version file is what we expect it to be
if string(contents) != version {
return nil, ErrNotContainerImageDir
}
} else {
return nil, ErrNotContainerImageDir
}
// delete directory contents so that only one image is in the directory at a time
if err = removeDirContents(d.ref.resolvedPath); err != nil {
return nil, errors.Wrapf(err, "error erasing contents in %q", d.ref.resolvedPath)
}
logrus.Debugf("overwriting existing container image directory %q", d.ref.resolvedPath)
}
} else {
// create directory if it doesn't exist
if err := os.MkdirAll(d.ref.resolvedPath, 0755); err != nil {
return nil, errors.Wrapf(err, "unable to create directory %q", d.ref.resolvedPath)
}
}
// create version file
err = ioutil.WriteFile(d.ref.versionPath(), []byte(version), 0644)
if err != nil {
return nil, errors.Wrapf(err, "error creating version file %q", d.ref.versionPath())
}
return d, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/wrapper/options.go#L69-L79
|
func (o *Options) Validate() error {
if o.ProcessLog == "" {
return errors.New("no log file specified with --process-log")
}
if o.MarkerFile == "" {
return errors.New("no marker file specified with --marker-file")
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L799-L802
|
func (p SetCookieParams) WithExpires(expires *cdp.TimeSinceEpoch) *SetCookieParams {
p.Expires = expires
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1026-L1030
|
func (v *KeyRange) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb8(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/storage/chunk/storage.go#L19-L24
|
func NewStorage(objC obj.Client, prefix string) *Storage {
return &Storage{
objC: objC,
prefix: prefix,
}
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/service/lease.go#L70-L82
|
func (s *Lease) ReStock() (skuTask *taskmanager.Task) {
if skuConstructor, ok := s.availableSkus[s.Sku]; ok {
leaseMap := structs.Map(s)
sku := skuConstructor.New(s.taskManager, leaseMap)
skuTask = sku.ReStock()
s.Task = skuTask.GetRedactedVersion()
} else {
s.Task.Status = TaskStatusUnavailable
}
return
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L62-L69
|
func (s *ConcoursePipeline) GetResourceByName(name string) *atc.ResourceConfig {
for i, v := range s.Resources {
if v.Name == name {
return &s.Resources[i]
}
}
return nil
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L161-L172
|
func SliceContains(slice []string, val string) bool {
if slice == nil {
return false
}
for _, it := range slice {
if it == val {
return true
}
}
return false
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2439-L2447
|
func (c *Client) CreateFork(owner, repo string) error {
c.log("CreateFork", owner, repo)
_, err := c.request(&request{
method: http.MethodPost,
path: fmt.Sprintf("/repos/%s/%s/forks", owner, repo),
exitCodes: []int{202},
}, nil)
return err
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/requestbuilder.go#L46-L64
|
func (r *RequestBuilder) Option(key string, value interface{}) *RequestBuilder {
var s string
switch v := value.(type) {
case bool:
s = strconv.FormatBool(v)
case string:
s = v
case []byte:
s = string(v)
default:
// slow case.
s = fmt.Sprint(value)
}
if r.opts == nil {
r.opts = make(map[string]string, 1)
}
r.opts[key] = s
return r
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L482-L499
|
func (c *JobConfig) AllPresubmits(repos []string) []Presubmit {
var res []Presubmit
for repo, v := range c.Presubmits {
if len(repos) == 0 {
res = append(res, v...)
} else {
for _, r := range repos {
if r == repo {
res = append(res, v...)
break
}
}
}
}
return res
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1025-L1030
|
func RemoveAttribute(nodeID cdp.NodeID, name string) *RemoveAttributeParams {
return &RemoveAttributeParams{
NodeID: nodeID,
Name: name,
}
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/nic.go#L76-L83
|
func (c *Client) UpdateNic(dcid string, srvid string, nicid string, obj NicProperties) (*Nic, error) {
url := nicPath(dcid, srvid, nicid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Nic{}
err := c.client.Patch(url, obj, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4881-L4885
|
func (v CallFunctionOnReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime46(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_cluster.go#L67-L79
|
func (r *ProtocolLXD) GetClusterMemberNames() ([]string, error) {
if !r.HasExtension("clustering") {
return nil, fmt.Errorf("The server is missing the required \"clustering\" API extension")
}
urls := []string{}
_, err := r.queryStruct("GET", "/cluster/members", nil, "", &urls)
if err != nil {
return nil, err
}
return urls, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L590-L616
|
func makePipelineRun(pj prowjobv1.ProwJob, pr *pipelinev1alpha1.PipelineResource) (*pipelinev1alpha1.PipelineRun, error) {
if pj.Spec.PipelineRunSpec == nil {
return nil, errors.New("no PipelineSpec defined")
}
p := pipelinev1alpha1.PipelineRun{
ObjectMeta: pipelineMeta(pj),
Spec: *pj.Spec.PipelineRunSpec.DeepCopy(),
}
buildID := pj.Status.BuildID
if buildID == "" {
return nil, errors.New("empty BuildID in status")
}
p.Spec.Params = append(p.Spec.Params, pipelinev1alpha1.Param{
Name: "build_id",
Value: buildID,
})
rb := pipelinev1alpha1.PipelineResourceBinding{
Name: pr.Name,
ResourceRef: pipelinev1alpha1.PipelineResourceRef{
Name: pr.Name,
APIVersion: pr.APIVersion,
},
}
p.Spec.Resources = append(p.Spec.Resources, rb)
return &p, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L813-L822
|
func (p *SetCookieParams) Do(ctx context.Context) (success bool, err error) {
// execute
var res SetCookieReturns
err = cdp.Execute(ctx, CommandSetCookie, p, &res)
if err != nil {
return false, err
}
return res.Success, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/key.go#L149-L151
|
func newUniqueEphemeralKey(s *concurrency.Session, prefix string) (*EphemeralKV, error) {
return newUniqueEphemeralKV(s, prefix, "")
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/ioprogress/reader.go#L14-L25
|
func (pt *ProgressReader) Read(p []byte) (int, error) {
// Do normal reader tasks
n, err := pt.ReadCloser.Read(p)
// Do the actual progress tracking
if pt.Tracker != nil {
pt.Tracker.total += int64(n)
pt.Tracker.update(n)
}
return n, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L249-L251
|
func (t ShadowRootType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L174-L180
|
func (c *ClusterTx) NodesCount() (int, error) {
count, err := query.Count(c.tx, "nodes", "")
if err != nil {
return 0, errors.Wrap(err, "failed to count existing nodes")
}
return count, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L482-L484
|
func (t ScreencastFormat) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_lvm.go#L35-L69
|
func (s *storageLvm) StorageCoreInit() error {
s.sType = storageTypeLvm
typeName, err := storageTypeToString(s.sType)
if err != nil {
return err
}
s.sTypeName = typeName
if lvmVersion != "" {
s.sTypeVersion = lvmVersion
return nil
}
output, err := shared.RunCommand("lvm", "version")
if err != nil {
return fmt.Errorf("Error getting LVM version: %v\noutput:'%s'", err, output)
}
lines := strings.Split(output, "\n")
s.sTypeVersion = ""
for idx, line := range lines {
fields := strings.SplitAfterN(line, ":", 2)
if len(fields) < 2 {
continue
}
if idx > 0 {
s.sTypeVersion += " / "
}
s.sTypeVersion += strings.TrimSpace(fields[1])
}
lvmVersion = s.sTypeVersion
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1465-L1474
|
func (w *PutObjectWriteCloserAsync) Close() error {
w.writeChan <- w.buf
close(w.writeChan)
err := <-w.errChan
if err != nil {
return grpcutil.ScrubGRPC(err)
}
w.object, err = w.client.CloseAndRecv()
return grpcutil.ScrubGRPC(err)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L274-L276
|
func (p *SetXHRBreakpointParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetXHRBreakpoint, p, nil)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/apps_client.go#L62-L85
|
func (a *Client) GetApps(params *GetAppsParams) (*GetAppsOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetAppsParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetApps",
Method: "GET",
PathPattern: "/apps",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http", "https"},
Params: params,
Reader: &GetAppsReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*GetAppsOK), nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.