_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection.go#L82-L100
|
func startLocalConnection(connRemote *remoteConnection, tcpConn *net.TCPConn, router *Router, acceptNewPeer bool, logger Logger) {
if connRemote.local != router.Ourself.Peer {
panic("attempt to create local connection from a peer which is not ourself")
}
errorChan := make(chan error, 1)
finished := make(chan struct{})
conn := &LocalConnection{
remoteConnection: *connRemote, // NB, we're taking a copy of connRemote here.
router: router,
tcpConn: tcpConn,
trustRemote: router.trusts(connRemote),
uid: randUint64(),
errorChan: errorChan,
finished: finished,
logger: logger,
}
conn.senders = newGossipSenders(conn, finished)
go conn.run(errorChan, finished, acceptNewPeer)
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L120-L140
|
func (r *Firewall) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("firewall.Expected")
newResource := &Firewall{
Shared: Shared{
Name: r.Name,
CloudID: r.ServerPool.Identifier,
},
InboundRules: r.InboundRules,
OutboundRules: r.OutboundRules,
DropletIDs: r.DropletIDs,
Tags: r.Tags,
FirewallID: r.FirewallID,
Status: r.Status,
Created: r.Created,
}
//logger.Info("Expected firewall returned is %+v", immutable)
newCluster := r.immutableRender(newResource, immutable)
return newCluster, newResource, nil
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L182-L206
|
func (w *SnowballWord) FirstPrefix(prefixes ...string) (foundPrefix string, foundPrefixRunes []rune) {
found := false
rsLen := len(w.RS)
for _, prefix := range prefixes {
prefixRunes := []rune(prefix)
if len(prefixRunes) > rsLen {
continue
}
found = true
for i, r := range prefixRunes {
if i > rsLen-1 || (w.RS)[i] != r {
found = false
break
}
}
if found {
foundPrefix = prefix
foundPrefixRunes = prefixRunes
break
}
}
return
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L114-L129
|
func DefaultParser(tx *Xslate, args Args) error {
syntax, ok := args.Get("Syntax")
if !ok {
syntax = "TTerse"
}
switch syntax {
case "TTerse":
tx.Parser = tterse.New()
case "Kolon", "Kolonish":
tx.Parser = kolonish.New()
default:
return errors.New("sytanx '" + syntax.(string) + "' is not available")
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/mason.go#L92-L107
|
func ParseConfig(configPath string) ([]common.ResourcesConfig, error) {
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return nil, err
}
file, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, err
}
var data common.MasonConfig
err = yaml.Unmarshal(file, &data)
if err != nil {
return nil, err
}
return data.Configs, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L780-L783
|
func (p PrintToPDFParams) WithPreferCSSPageSize(preferCSSPageSize bool) *PrintToPDFParams {
p.PreferCSSPageSize = preferCSSPageSize
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/get_command.go#L38-L55
|
func NewGetCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "get [options] <key> [range_end]",
Short: "Gets the key or a range of keys",
Run: getCommandFunc,
}
cmd.Flags().StringVar(&getConsistency, "consistency", "l", "Linearizable(l) or Serializable(s)")
cmd.Flags().StringVar(&getSortOrder, "order", "", "Order of results; ASCEND or DESCEND (ASCEND by default)")
cmd.Flags().StringVar(&getSortTarget, "sort-by", "", "Sort target; CREATE, KEY, MODIFY, VALUE, or VERSION")
cmd.Flags().Int64Var(&getLimit, "limit", 0, "Maximum number of results")
cmd.Flags().BoolVar(&getPrefix, "prefix", false, "Get keys with matching prefix")
cmd.Flags().BoolVar(&getFromKey, "from-key", false, "Get keys that are greater than or equal to the given key using byte compare")
cmd.Flags().Int64Var(&getRev, "rev", 0, "Specify the kv revision")
cmd.Flags().BoolVar(&getKeysOnly, "keys-only", false, "Get only the keys")
cmd.Flags().BoolVar(&printValueOnly, "print-value-only", false, `Only write values when using the "simple" output format`)
return cmd
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/message_service.go#L17-L24
|
func (v *MessageService) NewService(args []string) Service {
v.Args = args
log.Printf("[DEBUG] starting message service with args: %v\n", v.Args)
v.Cmd = "pact-message"
return v
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L51-L58
|
func (x *Exception) SetObject(object string) error {
objectRegexp, err := regexp.Compile("(?i)" + object)
if err != nil {
return err
}
x.Object = objectRegexp
return nil
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/norwegian/step2.go#L10-L22
|
func step2(w *snowballword.SnowballWord) bool {
suffix, suffixRunes := w.FirstSuffix(
"dt", "vt",
)
// If it is not in R1, do nothing
if suffix == "" || len(suffixRunes) > len(w.RS)-w.R1start {
return false
}
w.RemoveLastNRunes(1)
return true
}
|
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_file.go#L24-L35
|
func (f *File) Init() error {
if f.Path == "" {
return fmt.Errorf("Path required")
}
if f.Interval < 1*time.Second {
f.Interval = 1 * time.Second
}
if err := f.updateHash(); err != nil {
return err
}
return nil
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/merger.go#L53-L64
|
func (mit *MergeIterator) SeekFirst() {
for _, it := range mit.iters {
it.SeekFirst()
if it.Valid() {
n := it.GetNode()
mit.h = append(mit.h, heapItem{iter: it, n: n})
}
}
heap.Init(&mit.h)
mit.Next()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/debug/server/server.go#L22-L29
|
func NewDebugServer(name string, etcdClient *etcd.Client, etcdPrefix string, workerGrpcPort uint16) debug.DebugServer {
return &debugServer{
name: name,
etcdClient: etcdClient,
etcdPrefix: etcdPrefix,
workerGrpcPort: workerGrpcPort,
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L796-L811
|
func writeLevel0Table(ft flushTask, f io.Writer) error {
iter := ft.mt.NewIterator()
defer iter.Close()
b := table.NewTableBuilder()
defer b.Close()
for iter.SeekToFirst(); iter.Valid(); iter.Next() {
if len(ft.dropPrefix) > 0 && bytes.HasPrefix(iter.Key(), ft.dropPrefix) {
continue
}
if err := b.Add(iter.Key(), iter.Value()); err != nil {
return err
}
}
_, err := f.Write(b.Finish())
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L934-L942
|
func (c *Cluster) ContainerPool(project, containerName string) (string, error) {
var poolName string
err := c.Transaction(func(tx *ClusterTx) error {
var err error
poolName, err = tx.ContainerPool(project, containerName)
return err
})
return poolName, err
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/tcqueue.go#L823-L834
|
func (queue *Queue) ListProvisioners(continuationToken, limit string) (*ListProvisionersResponse, error) {
v := url.Values{}
if continuationToken != "" {
v.Add("continuationToken", continuationToken)
}
if limit != "" {
v.Add("limit", limit)
}
cd := tcclient.Client(*queue)
responseObject, _, err := (&cd).APICall(nil, "GET", "/provisioners", new(ListProvisionersResponse), v)
return responseObject.(*ListProvisionersResponse), err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/backup_command.go#L58-L103
|
func handleBackup(c *cli.Context) error {
var srcWAL string
var destWAL string
withV3 := c.Bool("with-v3")
srcSnap := filepath.Join(c.String("data-dir"), "member", "snap")
destSnap := filepath.Join(c.String("backup-dir"), "member", "snap")
if c.String("wal-dir") != "" {
srcWAL = c.String("wal-dir")
} else {
srcWAL = filepath.Join(c.String("data-dir"), "member", "wal")
}
if c.String("backup-wal-dir") != "" {
destWAL = c.String("backup-wal-dir")
} else {
destWAL = filepath.Join(c.String("backup-dir"), "member", "wal")
}
if err := fileutil.CreateDirAll(destSnap); err != nil {
log.Fatalf("failed creating backup snapshot dir %v: %v", destSnap, err)
}
walsnap := saveSnap(destSnap, srcSnap)
metadata, state, ents := loadWAL(srcWAL, walsnap, withV3)
saveDB(filepath.Join(destSnap, "db"), filepath.Join(srcSnap, "db"), state.Commit, withV3)
idgen := idutil.NewGenerator(0, time.Now())
metadata.NodeID = idgen.Next()
metadata.ClusterID = idgen.Next()
neww, err := wal.Create(zap.NewExample(), destWAL, pbutil.MustMarshal(&metadata))
if err != nil {
log.Fatal(err)
}
defer neww.Close()
if err := neww.Save(state, ents); err != nil {
log.Fatal(err)
}
if err := neww.SaveSnapshot(walsnap); err != nil {
log.Fatal(err)
}
return nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decrypt_reader.go#L87-L105
|
func (cr *cipherBlockReader) ReadByte() (byte, error) {
for {
if cr.n < len(cr.outbuf) {
c := cr.outbuf[cr.n]
cr.n++
return c, nil
}
if cr.err != nil {
err := cr.err
cr.err = nil
return 0, err
}
// refill outbuf
var n int
n, cr.err = cr.read(cr.outbuf[:cap(cr.outbuf)])
cr.outbuf = cr.outbuf[:n]
cr.n = 0
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/easyjson.go#L152-L156
|
func (v *StartTabMirroringParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCast1(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L8649-L8689
|
func (c *containerLXC) setNetworkRoutes(m types.Device) error {
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", m["host_name"])) {
return fmt.Errorf("Unknown or missing host side veth: %s", m["host_name"])
}
// Flush all IPv4 routes
_, err := shared.RunCommand("ip", "-4", "route", "flush", "dev", m["host_name"], "proto", "static")
if err != nil {
return err
}
// Flush all IPv6 routes
_, err = shared.RunCommand("ip", "-6", "route", "flush", "dev", m["host_name"], "proto", "static")
if err != nil {
return err
}
// Add additional IPv4 routes
if m["ipv4.routes"] != "" {
for _, route := range strings.Split(m["ipv4.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-4", "route", "add", "dev", m["host_name"], route, "proto", "static")
if err != nil {
return err
}
}
}
// Add additional IPv6 routes
if m["ipv6.routes"] != "" {
for _, route := range strings.Split(m["ipv6.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-6", "route", "add", "dev", m["host_name"], route, "proto", "static")
if err != nil {
return err
}
}
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L285-L287
|
func (rn *RawNode) TransferLeader(transferee uint64) {
_ = rn.raft.Step(pb.Message{Type: pb.MsgTransferLeader, From: transferee})
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1547-L1555
|
func (u AllowTrustOpAsset) ArmForSwitch(sw int32) (string, bool) {
switch AssetType(sw) {
case AssetTypeAssetTypeCreditAlphanum4:
return "AssetCode4", true
case AssetTypeAssetTypeCreditAlphanum12:
return "AssetCode12", true
}
return "-", false
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L292-L305
|
func FileSequence_Format(id FileSeqId, tpl *C.char) (*C.char, Error) {
fs, ok := sFileSeqs.Get(id)
if !ok {
return C.CString(""), nil
}
str, err := fs.Format(C.GoString(tpl))
if err != nil {
return nil, C.CString(err.Error())
}
// caller must free the string
return C.CString(str), nil
}
|
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/utils/util.go#L52-L65
|
func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
for {
select {
case <-stopCh:
return
default:
}
func() {
defer HandleCrash()
f()
}()
time.Sleep(period)
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1295-L1298
|
func (e EnvelopeType) ValidEnum(v int32) bool {
_, ok := envelopeTypeMap[v]
return ok
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L196-L202
|
func (router *Router) sendAllGossip() {
for channel := range router.gossipChannelSet() {
if gossip := channel.gossiper.Gossip(); gossip != nil {
channel.Send(gossip)
}
}
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/ppm_model.go#L393-L398
|
func (a *subAllocator) succContext(i int32) *context {
if i <= 0 {
return nil
}
return &context{i: i, s: a.states[i : i+2 : i+2], a: a}
}
|
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L74-L84
|
func CreateRandom(bs []byte, length int) []byte {
filled := make([]byte, length)
max := len(bs)
for i := 0; i < length; i++ {
Shuffle(bs)
filled[i] = bs[random(0, max)]
}
return filled
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L290-L301
|
func (mexset *messageExchangeSet) addExchange(mex *messageExchange) error {
if mexset.shutdown {
return errMexSetShutdown
}
if _, ok := mexset.exchanges[mex.msgID]; ok {
return errDuplicateMex
}
mexset.exchanges[mex.msgID] = mex
return nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L244-L349
|
func RecoverCluster(conf *Config, fsm FSM, logs LogStore, stable StableStore,
snaps SnapshotStore, trans Transport, configuration Configuration) error {
// Validate the Raft server config.
if err := ValidateConfig(conf); err != nil {
return err
}
// Sanity check the Raft peer configuration.
if err := checkConfiguration(configuration); err != nil {
return err
}
// Refuse to recover if there's no existing state. This would be safe to
// do, but it is likely an indication of an operator error where they
// expect data to be there and it's not. By refusing, we force them
// to show intent to start a cluster fresh by explicitly doing a
// bootstrap, rather than quietly fire up a fresh cluster here.
hasState, err := HasExistingState(logs, stable, snaps)
if err != nil {
return fmt.Errorf("failed to check for existing state: %v", err)
}
if !hasState {
return fmt.Errorf("refused to recover cluster with no initial state, this is probably an operator error")
}
// Attempt to restore any snapshots we find, newest to oldest.
var snapshotIndex uint64
var snapshotTerm uint64
snapshots, err := snaps.List()
if err != nil {
return fmt.Errorf("failed to list snapshots: %v", err)
}
for _, snapshot := range snapshots {
_, source, err := snaps.Open(snapshot.ID)
if err != nil {
// Skip this one and try the next. We will detect if we
// couldn't open any snapshots.
continue
}
defer source.Close()
if err := fsm.Restore(source); err != nil {
// Same here, skip and try the next one.
continue
}
snapshotIndex = snapshot.Index
snapshotTerm = snapshot.Term
break
}
if len(snapshots) > 0 && (snapshotIndex == 0 || snapshotTerm == 0) {
return fmt.Errorf("failed to restore any of the available snapshots")
}
// The snapshot information is the best known end point for the data
// until we play back the Raft log entries.
lastIndex := snapshotIndex
lastTerm := snapshotTerm
// Apply any Raft log entries past the snapshot.
lastLogIndex, err := logs.LastIndex()
if err != nil {
return fmt.Errorf("failed to find last log: %v", err)
}
for index := snapshotIndex + 1; index <= lastLogIndex; index++ {
var entry Log
if err := logs.GetLog(index, &entry); err != nil {
return fmt.Errorf("failed to get log at index %d: %v", index, err)
}
if entry.Type == LogCommand {
_ = fsm.Apply(&entry)
}
lastIndex = entry.Index
lastTerm = entry.Term
}
// Create a new snapshot, placing the configuration in as if it was
// committed at index 1.
snapshot, err := fsm.Snapshot()
if err != nil {
return fmt.Errorf("failed to snapshot FSM: %v", err)
}
version := getSnapshotVersion(conf.ProtocolVersion)
sink, err := snaps.Create(version, lastIndex, lastTerm, configuration, 1, trans)
if err != nil {
return fmt.Errorf("failed to create snapshot: %v", err)
}
if err := snapshot.Persist(sink); err != nil {
return fmt.Errorf("failed to persist snapshot: %v", err)
}
if err := sink.Close(); err != nil {
return fmt.Errorf("failed to finalize snapshot: %v", err)
}
// Compact the log so that we don't get bad interference from any
// configuration change log entries that might be there.
firstLogIndex, err := logs.FirstIndex()
if err != nil {
return fmt.Errorf("failed to get first log index: %v", err)
}
if err := logs.DeleteRange(firstLogIndex, lastLogIndex); err != nil {
return fmt.Errorf("log compaction failed: %v", err)
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_urls.go#L59-L66
|
func (us *UniqueURLs) String() string {
all := make([]string, 0, len(us.Values))
for u := range us.Values {
all = append(all, u)
}
sort.Strings(all)
return strings.Join(all, ",")
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dimg/ftgc.go#L339-L365
|
func (gc *GraphicContext) FillStroke(paths ...*draw2d.Path) {
paths = append(paths, gc.Current.Path)
gc.fillRasterizer.UseNonZeroWinding = gc.Current.FillRule == draw2d.FillRuleWinding
gc.strokeRasterizer.UseNonZeroWinding = true
flattener := draw2dbase.Transformer{Tr: gc.Current.Tr, Flattener: FtLineBuilder{Adder: gc.fillRasterizer}}
stroker := draw2dbase.NewLineStroker(gc.Current.Cap, gc.Current.Join, draw2dbase.Transformer{Tr: gc.Current.Tr, Flattener: FtLineBuilder{Adder: gc.strokeRasterizer}})
stroker.HalfLineWidth = gc.Current.LineWidth / 2
var liner draw2dbase.Flattener
if gc.Current.Dash != nil && len(gc.Current.Dash) > 0 {
liner = draw2dbase.NewDashConverter(gc.Current.Dash, gc.Current.DashOffset, stroker)
} else {
liner = stroker
}
demux := draw2dbase.DemuxFlattener{Flatteners: []draw2dbase.Flattener{flattener, liner}}
for _, p := range paths {
draw2dbase.Flatten(p, demux, gc.Current.Tr.GetScale())
}
// Fill
gc.paint(gc.fillRasterizer, gc.Current.FillColor)
// Stroke
gc.paint(gc.strokeRasterizer, gc.Current.StrokeColor)
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L363-L366
|
func (op *OutgoingUserProfilePhotosRequest) SetLimit(to int) *OutgoingUserProfilePhotosRequest {
op.Limit = to
return op
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/lan.go#L92-L97
|
func (c *Client) DeleteLan(dcid, lanid string) (*http.Header, error) {
url := lanPath(dcid, lanid)
ret := &http.Header{}
err := c.client.Delete(url, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L775-L785
|
func MeanStdDevWithMask(src, mask *IplImage) (Scalar, Scalar) {
var mean, stdDev Scalar
C.cvAvgSdv(
unsafe.Pointer(src),
(*C.CvScalar)(&mean),
(*C.CvScalar)(&stdDev),
unsafe.Pointer(mask),
)
return mean, stdDev
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L659-L663
|
func (auth *Auth) SentryDSN(project string) (*SentryDSNResponse, error) {
cd := tcclient.Client(*auth)
responseObject, _, err := (&cd).APICall(nil, "GET", "/sentry/"+url.QueryEscape(project)+"/dsn", new(SentryDSNResponse), nil)
return responseObject.(*SentryDSNResponse), err
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/stream.go#L340-L347
|
func (db *DB) NewStreamAt(readTs uint64) *Stream {
if !db.opt.managedTxns {
panic("This API can only be called in managed mode.")
}
stream := db.newStream()
stream.readTs = readTs
return stream
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/encode.go#L731-L750
|
func (e *StreamEncoder) Open(n int) error {
if err := e.err; err != nil {
return err
}
if e.closed {
return io.ErrClosedPipe
}
if !e.opened {
e.max = n
e.opened = true
if !e.oneshot {
e.err = e.Emitter.EmitArrayBegin(n)
}
}
return e.err
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L57-L69
|
func (xp XPathExec) ExecBool(t tree.Node, opts ...FuncOpts) (bool, error) {
res, err := xp.Exec(t, opts...)
if err != nil {
return false, err
}
b, ok := res.(tree.IsBool)
if !ok {
return false, fmt.Errorf("Cannot convert result to a boolean")
}
return bool(b.Bool()), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2996-L3000
|
func (v *GetSearchResultsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom33(&r, v)
return r.Error()
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L341-L344
|
func (gc *GraphicContext) Rotate(angle float64) {
gc.StackGraphicContext.Rotate(angle)
gc.pdf.TransformRotate(-angle*180/math.Pi, 0, 0)
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcindex/tcindex.go#L64-L70
|
func New(credentials *tcclient.Credentials, rootURL string) *Index {
return &Index{
Credentials: credentials,
BaseURL: tcclient.BaseURL(rootURL, "index", "v1"),
Authenticate: credentials != nil,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L468-L472
|
func (v StopAllWorkersParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L50-L60
|
func Bool(key string, val bool) Field {
var numericVal int64
if val {
numericVal = 1
}
return Field{
key: key,
fieldType: boolType,
numericVal: numericVal,
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/scheduler.go#L302-L313
|
func (s *segregatedScheduler) chooseContainerToRemove(nodes []cluster.Node, appName, process string) (string, error) {
_, chosenNode, err := s.minMaxNodes(nodes, appName, process)
if err != nil {
return "", err
}
log.Debugf("[scheduler] Chosen node for remove a container: %#v", chosenNode)
containerID, err := s.getContainerPreferablyFromHost(chosenNode, appName, process)
if err != nil {
return "", err
}
return containerID, err
}
|
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L158-L163
|
func ErrorReportingService(service string) Option {
return func(sh *StackdriverHook) error {
sh.errorReportingServiceName = service
return nil
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L383-L405
|
func (a *ssAuthenticator) CanAuthenticate(host string) error {
url := fmt.Sprintf("api/catalog/accounts/%d/user_preferences", a.accountID)
req, err := http.NewRequest("GET", buildURL(host, url), nil)
if err != nil {
return err
}
req.Header.Set("X-Api-Version", "1.0")
if err := a.Sign(req); err != nil {
return err
}
resp, err := a.client.DoHidden(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
var body string
if b, err := ioutil.ReadAll(resp.Body); err != nil {
body = ": " + string(b)
}
return fmt.Errorf("%s%s", resp.Status, body)
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/internal/oci_util.go#L37-L42
|
func SplitPathAndImage(reference string) (string, string) {
if runtime.GOOS == "windows" {
return splitPathAndImageWindows(reference)
}
return splitPathAndImageNonWindows(reference)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L524-L532
|
func pipelineMeta(pj prowjobv1.ProwJob) metav1.ObjectMeta {
labels, annotations := decorate.LabelsAndAnnotationsForJob(pj)
return metav1.ObjectMeta{
Annotations: annotations,
Name: pj.Name,
Namespace: pj.Spec.Namespace,
Labels: labels,
}
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxtype.go#L869-L872
|
func WholeSeq() Slice {
slice := C.cvSlice(C.int(0), C.CV_WHOLE_SEQ_END_INDEX)
return (Slice)(slice)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L288-L297
|
func (c APIClient) FlushJobAll(commits []*pfs.Commit, toPipelines []string) ([]*pps.JobInfo, error) {
var result []*pps.JobInfo
if err := c.FlushJob(commits, toPipelines, func(ji *pps.JobInfo) error {
result = append(result, ji)
return nil
}); err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L393-L399
|
func (t *target) nextTryLater() {
t.tryAfter = time.Now().Add(t.tryInterval/2 + time.Duration(rand.Int63n(int64(t.tryInterval))))
t.tryInterval = t.tryInterval * 3 / 2
if t.tryInterval > maxInterval {
t.tryInterval = maxInterval
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L149-L207
|
func (loc *AppliedPolicyLocator) Create(name string, templateHref string, options rsapi.APIParams) (*AppliedPolicy, error) {
var res *AppliedPolicy
if name == "" {
return res, fmt.Errorf("name is required")
}
if templateHref == "" {
return res, fmt.Errorf("templateHref is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"name": name,
"template_href": templateHref,
}
var descriptionOpt = options["description"]
if descriptionOpt != nil {
p["description"] = descriptionOpt
}
var dryRunOpt = options["dry_run"]
if dryRunOpt != nil {
p["dry_run"] = dryRunOpt
}
var frequencyOpt = options["frequency"]
if frequencyOpt != nil {
p["frequency"] = frequencyOpt
}
var optionsOpt = options["options"]
if optionsOpt != nil {
p["options"] = optionsOpt
}
uri, err := loc.ActionPath("AppliedPolicy", "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)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L527-L529
|
func (p *Page) SetPageLoad(timeout int) error {
return p.session.SetPageLoad(timeout)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/util.go#L59-L68
|
func voteRespMsgType(msgt pb.MessageType) pb.MessageType {
switch msgt {
case pb.MsgVote:
return pb.MsgVoteResp
case pb.MsgPreVote:
return pb.MsgPreVoteResp
default:
panic(fmt.Sprintf("not a vote message: %s", msgt))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1355-L1359
|
func (v EventAnimationCanceled) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation15(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L144-L153
|
func (p *CloseTargetParams) Do(ctx context.Context) (success bool, err error) {
// execute
var res CloseTargetReturns
err = cdp.Execute(ctx, CommandCloseTarget, p, &res)
if err != nil {
return false, err
}
return res.Success, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1497-L1501
|
func (v EventLastSeenObjectID) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler17(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L330-L333
|
func (p EmulateTouchFromMouseEventParams) WithDeltaX(deltaX float64) *EmulateTouchFromMouseEventParams {
p.DeltaX = deltaX
return &p
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/tchooks.go#L249-L253
|
func (hooks *Hooks) TriggerHookWithToken(hookGroupId, hookId, token string, payload *TriggerHookRequest) (*TriggerHookResponse, error) {
cd := tcclient.Client(*hooks)
responseObject, _, err := (&cd).APICall(payload, "POST", "/hooks/"+url.QueryEscape(hookGroupId)+"/"+url.QueryEscape(hookId)+"/trigger/"+url.QueryEscape(token), new(TriggerHookResponse), nil)
return responseObject.(*TriggerHookResponse), err
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/uuid.go#L92-L97
|
func (s *Xor64Source) Seed(seed int64) {
if seed == 0 {
seed = seed0
}
*s = Xor64Source(seed)
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/type.go#L328-L499
|
func (p *Process) typeHeap() {
p.initTypeHeap.Do(func() {
// Type info for the start of each object. a.k.a. "0 offset" typings.
p.types = make([]typeInfo, p.nObj)
// Type info for the interior of objects, a.k.a. ">0 offset" typings.
// Type information is arranged in chunks. Chunks are stored in an
// arbitrary order, and are guaranteed to not overlap. If types are
// equal, chunks are also guaranteed not to abut.
// Interior typings are kept separate because they hopefully are rare.
// TODO: They aren't really that rare. On some large heaps I tried
// ~50% of objects have an interior pointer into them.
// Keyed by object index.
interior := map[int][]typeChunk{}
// Typings we know about but haven't scanned yet.
type workRecord struct {
a core.Address
t *Type
r int64
}
var work []workRecord
// add records the fact that we know the object at address a has
// r copies of type t.
add := func(a core.Address, t *Type, r int64) {
if a == 0 { // nil pointer
return
}
i, off := p.findObjectIndex(a)
if i < 0 { // pointer doesn't point to an object in the Go heap
return
}
if off == 0 {
// We have a 0-offset typing. Replace existing 0-offset typing
// if the new one is larger.
ot := p.types[i].t
or := p.types[i].r
if ot == nil || r*t.Size > or*ot.Size {
if t == ot {
// Scan just the new section.
work = append(work, workRecord{
a: a.Add(or * ot.Size),
t: t,
r: r - or,
})
} else {
// Rescan the whole typing using the updated type.
work = append(work, workRecord{
a: a,
t: t,
r: r,
})
}
p.types[i].t = t
p.types[i].r = r
}
return
}
// Add an interior typing to object #i.
c := typeChunk{off: off, t: t, r: r}
// Merge the given typing into the chunks we already know.
// TODO: this could be O(n) per insert if there are lots of internal pointers.
chunks := interior[i]
newchunks := chunks[:0]
addWork := true
for _, d := range chunks {
if c.max() <= d.min() || c.min() >= d.max() {
// c does not overlap with d.
if c.t == d.t && (c.max() == d.min() || c.min() == d.max()) {
// c and d abut and share the same base type. Merge them.
c = c.merge(d)
continue
}
// Keep existing chunk d.
// Overwrites chunks slice, but we're only merging chunks so it
// can't overwrite to-be-processed elements.
newchunks = append(newchunks, d)
continue
}
// There is some overlap. There are a few possibilities:
// 1) One is completely contained in the other.
// 2) Both are slices of a larger underlying array.
// 3) Some unsafe trickery has happened. Non-containing overlap
// can only happen in safe Go via case 2.
if c.min() >= d.min() && c.max() <= d.max() {
// 1a: c is contained within the existing chunk d.
// Note that there can be a type mismatch between c and d,
// but we don't care. We use the larger chunk regardless.
c = d
addWork = false // We've already scanned all of c.
continue
}
if d.min() >= c.min() && d.max() <= c.max() {
// 1b: existing chunk d is completely covered by c.
continue
}
if c.t == d.t && c.matchingAlignment(d) {
// Union two regions of the same base type. Case 2 above.
c = c.merge(d)
continue
}
if c.size() < d.size() {
// Keep the larger of the two chunks.
c = d
addWork = false
}
}
// Add new chunk to list of chunks for object.
newchunks = append(newchunks, c)
interior[i] = newchunks
// Also arrange to scan the new chunk. Note that if we merged
// with an existing chunk (or chunks), those will get rescanned.
// Duplicate work, but that's ok. TODO: but could be expensive.
if addWork {
work = append(work, workRecord{
a: a.Add(c.off - off),
t: c.t,
r: c.r,
})
}
}
// Get typings starting at roots.
fr := &frameReader{p: p}
p.ForEachRoot(func(r *Root) bool {
if r.Frame != nil {
fr.live = r.Frame.Live
p.typeObject(r.Addr, r.Type, fr, add)
} else {
p.typeObject(r.Addr, r.Type, p.proc, add)
}
return true
})
// Propagate typings through the heap.
for len(work) > 0 {
c := work[len(work)-1]
work = work[:len(work)-1]
for i := int64(0); i < c.r; i++ {
p.typeObject(c.a.Add(i*c.t.Size), c.t, p.proc, add)
}
}
// Merge any interior typings with the 0-offset typing.
for i, chunks := range interior {
t := p.types[i].t
r := p.types[i].r
if t == nil {
continue // We have no type info at offset 0.
}
for _, c := range chunks {
if c.max() <= r*t.Size {
// c is completely contained in the 0-offset typing. Ignore it.
continue
}
if c.min() <= r*t.Size {
// Typings overlap or abut. Extend if we can.
if c.t == t && c.min()%t.Size == 0 {
r = c.max() / t.Size
p.types[i].r = r
}
continue
}
// Note: at this point we throw away any interior typings that weren't
// merged with the 0-offset typing. TODO: make more use of this info.
}
}
})
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/indexer.go#L28-L42
|
func (i *Indexer) Add(model Model, unique bool, expireAfter time.Duration, fields ...string) {
// construct key from fields
var key []string
for _, f := range fields {
key = append(key, F(model, f))
}
// add index
i.AddRaw(C(model), mgo.Index{
Key: key,
Unique: unique,
ExpireAfter: expireAfter,
Background: true,
})
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L285-L294
|
func PathTransform(gc draw2d.GraphicContext, x, y, width, height float64) {
gc.Save()
gc.SetLineWidth(width / 10)
gc.Translate(x+width/2, y+height/2)
gc.Scale(1, 4)
gc.ArcTo(0, 0, width/8, height/8, 0, math.Pi*2)
gc.Close()
gc.Stroke()
gc.Restore()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1151-L1155
|
func (v *KeyPath) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb9(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/clientv3util/util.go#L31-L33
|
func KeyMissing(key string) clientv3.Cmp {
return clientv3.Compare(clientv3.Version(key), "=", 0)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1982-L1986
|
func (v GetBestEffortCoverageReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler19(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L859-L861
|
func (c *Cluster) StoragePoolNodeVolumeGetTypeByProject(project, volumeName string, volumeType int, poolID int64) (int64, *api.StorageVolume, error) {
return c.StoragePoolVolumeGetType(project, volumeName, volumeType, poolID, c.nodeID)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L141-L145
|
func (v SetInstrumentationBreakpointParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/match.go#L14-L34
|
func (p *Part) BreadthMatchFirst(matcher PartMatcher) *Part {
q := list.New()
q.PushBack(p)
// Push children onto queue and attempt to match in that order
for q.Len() > 0 {
e := q.Front()
p := e.Value.(*Part)
if matcher(p) {
return p
}
q.Remove(e)
c := p.FirstChild
for c != nil {
q.PushBack(c)
c = c.NextSibling
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/easyjson.go#L1300-L1304
|
func (v *GetFullAXTreeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAccessibility8(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L315-L325
|
func (e *Endpoints) closeListener(kind kind) error {
listener := e.listeners[kind]
if listener == nil {
return nil
}
delete(e.listeners, kind)
logger.Info(" - closing socket", log.Ctx{"socket": listener.Addr()})
return listener.Close()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/config.go#L40-L60
|
func (cfg *ClientConfig) Save(path string) error {
encrypted_password, err := Encrypt(cfg.Password)
if err != nil {
return fmt.Errorf("Failed to encrypt password: %s", err)
}
cfg.Password = encrypted_password
encrypted_refresh, err := Encrypt(cfg.RefreshToken)
if err != nil {
return fmt.Errorf("Failed to encrypt refresh token: %s", err)
}
cfg.RefreshToken = encrypted_refresh
bytes, err := json.Marshal(cfg)
if err != nil {
return fmt.Errorf("Failed to serialize config: %s", err)
}
err = ioutil.WriteFile(path, bytes, 0644)
if err != nil {
return fmt.Errorf("Failed to write config file: %s", err)
}
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/smtp.go#L54-L64
|
func NewDialer(host string, port int, username, password string) *Dialer {
return &Dialer{
Host: host,
Port: port,
Username: username,
Password: password,
SSL: port == 465,
Timeout: 10 * time.Second,
RetryFailure: true,
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L332-L373
|
func serviceInstances(w http.ResponseWriter, r *http.Request, t auth.Token) error {
appName := r.URL.Query().Get("app")
contexts := permission.ContextsForPermission(t, permission.PermServiceInstanceRead)
instances, err := readableInstances(t, contexts, appName, "")
if err != nil {
return err
}
contexts = permission.ContextsForPermission(t, permission.PermServiceRead)
services, err := readableServices(t, contexts)
if err != nil {
return err
}
servicesMap := map[string]*service.ServiceModel{}
for _, s := range services {
if _, in := servicesMap[s.Name]; !in {
servicesMap[s.Name] = &service.ServiceModel{
Service: s.Name,
Instances: []string{},
}
}
}
for _, instance := range instances {
entry := servicesMap[instance.ServiceName]
if entry == nil {
continue
}
entry.Instances = append(entry.Instances, instance.Name)
entry.Plans = append(entry.Plans, instance.PlanName)
entry.ServiceInstances = append(entry.ServiceInstances, instance)
}
result := []service.ServiceModel{}
for _, name := range sortedServiceNames(servicesMap) {
entry := servicesMap[name]
result = append(result, *entry)
}
if len(result) == 0 {
w.WriteHeader(http.StatusNoContent)
return nil
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(result)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/pbutil/pbutil.go#L72-L78
|
func (r *readWriter) Write(val proto.Message) (int64, error) {
bytes, err := proto.Marshal(val)
if err != nil {
return 0, err
}
return r.WriteBytes(bytes)
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L307-L319
|
func getLengthStr(info *TypeInfo) string {
switch info.Type.Kind() {
case reflect.Array,
reflect.Int8,
reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Float32, reflect.Float64,
reflect.Complex64, reflect.Complex128:
s := info.Type.Size()
return fmt.Sprintf("0x%X", s)
default:
return "variable"
}
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router/brace.go#L15-L20
|
func Brace(path string) *brace {
matches := strings.Split(path, "/")
return &brace{
matches: matches,
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L229-L345
|
func (c *Controller) UpdateContainer(name string, interfaces []ContainerInterface) error {
// Parse the provided interfaces
macInterfaces, err := parseInterfaces(interfaces)
if err != nil {
return err
}
// Get all the subnets
subnets, err := c.getSubnets()
if err != nil {
return err
}
device, err := c.getDevice(name)
if err != nil {
return err
}
// Iterate over existing interfaces, drop all removed ones and update existing ones
existingInterfaces := map[string]gomaasapi.Interface{}
for _, entry := range device.InterfaceSet() {
// Check if the interface has been removed from the container
iface, ok := macInterfaces[entry.MACAddress()]
if !ok {
// Delete the interface in MAAS
err = entry.Delete()
if err != nil {
return err
}
continue
}
// Update the subnets
existingSubnets := map[string]gomaasapi.Subnet{}
for _, link := range entry.Links() {
// Check if the MAAS subnet matches any of the container's
found := false
for _, subnet := range iface.Subnets {
if subnet.Name == link.Subnet().Name() {
if subnet.Address == "" || subnet.Address == link.IPAddress() {
found = true
}
break
}
}
// If no exact match could be found, remove it from MAAS
if !found {
err = entry.UnlinkSubnet(link.Subnet())
if err != nil {
return err
}
continue
}
// Record the existing up to date subnet
existingSubnets[link.Subnet().Name()] = link.Subnet()
}
// Add any missing (or updated) subnet to MAAS
for _, subnet := range iface.Subnets {
// Check that it's not configured yet
_, ok := existingSubnets[subnet.Name]
if ok {
continue
}
// Add the link
err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{
Mode: gomaasapi.LinkModeStatic,
Subnet: subnets[subnet.Name],
IPAddress: subnet.Address,
})
if err != nil {
return err
}
}
// Record the interface has being configured
existingInterfaces[entry.MACAddress()] = entry
}
// Iterate over expected interfaces, add any missing one
for _, iface := range macInterfaces {
_, ok := existingInterfaces[iface.MACAddress]
if ok {
// We already have it so just move on
continue
}
// Create the new interface
entry, err := device.CreateInterface(gomaasapi.CreateInterfaceArgs{
Name: iface.Name,
MACAddress: iface.MACAddress,
VLAN: subnets[iface.Subnets[0].Name].VLAN(),
})
if err != nil {
return err
}
// Add the subnets
for _, subnet := range iface.Subnets {
err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{
Mode: gomaasapi.LinkModeStatic,
Subnet: subnets[subnet.Name],
IPAddress: subnet.Address,
})
if err != nil {
return err
}
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_unix.go#L22-L25
|
func IsTerminal(fd int) bool {
_, err := GetState(fd)
return err == nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/network.go#L49-L64
|
func InitTLSConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
},
PreferServerCipherSuites: true,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1374-L1378
|
func (v GetHistogramParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser14(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3553-L3557
|
func (v GetFrameOwnerReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom40(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/functions/hash/hash.go#L15-L23
|
func Keys(m map[interface{}]interface{}) []interface{} {
l := make([]interface{}, len(m))
i := 0
for k := range m {
l[i] = k
i++
}
return l
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/attrs.go#L44-L53
|
func (a *Attrs) MergeAttrs(attrs *Attrs) {
if attrs == nil {
return
}
a.attrsLock.Lock()
defer a.attrsLock.Unlock()
for hash, val := range attrs.attrs {
a.attrs[hash] = val
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L312-L314
|
func (c APIClient) ListCommitByRepo(repoName string) ([]*pfs.CommitInfo, error) {
return c.ListCommit(repoName, "", "", 0)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L165-L172
|
func (in *ProwJobList) DeepCopy() *ProwJobList {
if in == nil {
return nil
}
out := new(ProwJobList)
in.DeepCopyInto(out)
return out
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/easyjson.go#L741-L745
|
func (v *GPUDevice) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoSysteminfo6(&r, v)
return r.Error()
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/shared.go#L43-L53
|
func (r Recipient) MarshalJSON() ([]byte, error) {
toReturn := ""
if r.isChannel() {
toReturn = fmt.Sprintf("\"%s\"", *r.ChannelID)
} else {
toReturn = fmt.Sprintf("%d", *r.ChatID)
}
return []byte(toReturn), nil
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/controller.go#L101-L115
|
func (c *Controller) IntRange(fieldName string, p interface{}, n int, m int) int {
if p == nil {
p = 0
}
value, ok := c.toNumber(p)
if ok == false {
panic((&ValidationError{}).New(fieldName + "必须是数字"))
}
b := c.Validate.Range(value, n, m)
if b == false {
panic((&ValidationError{}).New(fieldName + "值的范围应该从 " + strconv.Itoa(n) + " 到 " + strconv.Itoa(m)))
}
return value
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service.go#L76-L125
|
func serviceCreate(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
s := service.Service{
Name: InputValue(r, "id"),
Username: InputValue(r, "username"),
Endpoint: map[string]string{"production": InputValue(r, "endpoint")},
Password: InputValue(r, "password"),
}
team := InputValue(r, "team")
if team == "" {
team, err = permission.TeamForPermission(t, permission.PermServiceCreate)
if err == permission.ErrTooManyTeams {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "You must provide a team responsible for this service in the manifest file.",
}
}
if err != nil {
return err
}
}
s.OwnerTeams = []string{team}
allowed := permission.Check(t, permission.PermServiceCreate,
permission.Context(permTypes.CtxTeam, s.OwnerTeams[0]),
)
if !allowed {
return permission.ErrUnauthorized
}
delete(r.Form, "password")
evt, err := event.New(&event.Opts{
Target: serviceTarget(s.Name),
Kind: permission.PermServiceCreate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermServiceReadEvents, contextsForServiceProvision(&s)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
err = service.Create(s)
if err != nil {
if err == service.ErrServiceAlreadyExists {
return &errors.HTTP{Code: http.StatusConflict, Message: err.Error()}
}
return err
}
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, "success")
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L335-L338
|
func (p GetBoxModelParams) WithNodeID(nodeID cdp.NodeID) *GetBoxModelParams {
p.NodeID = nodeID
return &p
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/rsssh/main.go#L109-L125
|
func fetchDetails(client *cm15.API, envName string, envDetail EnvironmentDetail, sshConfig *[]SSHConfig) {
for nickname, name := range envDetail.ServerArrays {
// Obtain the resource
instances := serverArray(client, name)
// Obtain the IP address of the first instance (only one instance is considered here -- for now)
for _, instance := range instances {
ipAddress := instance.PublicIpAddresses[0]
number := getInstanceNumber(instance.Name)
*sshConfig = append(*sshConfig, SSHConfig{Name: envName + "_" + nickname + number, IPAddress: ipAddress})
}
}
for nickname, name := range envDetail.Servers {
instance := server(client, name)
ipAddress := instance.PublicIpAddresses[0]
*sshConfig = append(*sshConfig, SSHConfig{Name: envName + "_" + nickname, IPAddress: ipAddress})
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes_cluster_clients.go#L120-L130
|
func (o *ExperimentalKubernetesOptions) ProwJobClientset(namespace string, dryRun bool) (prowJobClientset prow.Interface, err error) {
if err := o.resolve(dryRun); err != nil {
return nil, err
}
if o.dryRun {
return nil, errors.New("no dry-run prowjob clientset is supported in dry-run mode")
}
return o.prowJobClientset, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L249-L263
|
func NewMicrosoftClientFromEnv() (Client, error) {
container, ok := os.LookupEnv(MicrosoftContainerEnvVar)
if !ok {
return nil, fmt.Errorf("%s not found", MicrosoftContainerEnvVar)
}
id, ok := os.LookupEnv(MicrosoftIDEnvVar)
if !ok {
return nil, fmt.Errorf("%s not found", MicrosoftIDEnvVar)
}
secret, ok := os.LookupEnv(MicrosoftSecretEnvVar)
if !ok {
return nil, fmt.Errorf("%s not found", MicrosoftSecretEnvVar)
}
return NewMicrosoftClient(container, id, secret)
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L283-L291
|
func (s Service) StatusHandler(w http.ResponseWriter, r *http.Request) {
on, err := s.store.Status()
if err != nil {
s.logger.Errorf("maintenance status: %s", err)
jsonInternalServerErrorResponse(w)
return
}
jsonStatusResponse(w, on)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L314-L320
|
func GetOrg(org string) (string, bool) {
data := strings.Split(org, ":")
if len(data) == 2 && data[0] == "user" {
return data[1], true
}
return org, false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1326-L1330
|
func (v *GetAllTimeSamplingProfileParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory15(&r, v)
return r.Error()
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L216-L225
|
func FrameSet_InvertedFrameRange(id FrameSetId, pad int) (ret *C.char) {
fs, ok := sFrameSets.Get(id)
if !ok {
ret = C.CString("")
} else {
ret = C.CString(fs.InvertedFrameRange(pad))
}
// caller must free the string
return ret
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/tracing.go#L103-L112
|
func (p *RequestMemoryDumpParams) Do(ctx context.Context) (dumpGUID string, success bool, err error) {
// execute
var res RequestMemoryDumpReturns
err = cdp.Execute(ctx, CommandRequestMemoryDump, nil, &res)
if err != nil {
return "", false, err
}
return res.DumpGUID, res.Success, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.