_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L998-L1018
|
func (db *DB) RunValueLogGC(discardRatio float64) error {
if discardRatio >= 1.0 || discardRatio <= 0.0 {
return ErrInvalidRequest
}
// Find head on disk
headKey := y.KeyWithTs(head, math.MaxUint64)
// Need to pass with timestamp, lsm get removes the last 8 bytes and compares key
val, err := db.lc.get(headKey, nil)
if err != nil {
return errors.Wrap(err, "Retrieving head from on-disk LSM")
}
var head valuePointer
if len(val.Value) > 0 {
head.Decode(val.Value)
}
// Pick a log file and run GC
return db.vlog.runGC(discardRatio, head)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/audits.go#L45-L48
|
func (p GetEncodedResponseParams) WithQuality(quality float64) *GetEncodedResponseParams {
p.Quality = quality
return &p
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L1373-L1375
|
func (api *API) InstanceCombinationLocator(href string) *InstanceCombinationLocator {
return &InstanceCombinationLocator{Href(href), api}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/indexeddb.go#L86-L93
|
func DeleteObjectStoreEntries(securityOrigin string, databaseName string, objectStoreName string, keyRange *KeyRange) *DeleteObjectStoreEntriesParams {
return &DeleteObjectStoreEntriesParams{
SecurityOrigin: securityOrigin,
DatabaseName: databaseName,
ObjectStoreName: objectStoreName,
KeyRange: keyRange,
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/assets/standard/standard.go#L13-L33
|
func New(opts *Options) (*genny.Generator, error) {
g := genny.New()
g.Box(packr.New("buffalo:genny:assets:standard", "../standard/templates"))
data := map[string]interface{}{}
h := template.FuncMap{}
t := gogen.TemplateTransformer(data, h)
g.Transformer(t)
g.RunFn(func(r *genny.Runner) error {
f, err := r.FindFile("templates/application.html")
if err != nil {
return err
}
s := strings.Replace(f.String(), "</title>", "</title>\n"+bs4, 1)
return r.File(genny.NewFileS(f.Name(), s))
})
return g, nil
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L90-L99
|
func (l *LexSymbolSet) Set(name string, typ lex.ItemType, prio ...float32) {
var x float32
if len(prio) < 1 {
x = 1.0
} else {
x = prio[0]
}
l.Map[name] = LexSymbol{name, typ, x}
l.SortedList = nil // reset
}
|
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L377-L382
|
func (l *slog) Info(args ...interface{}) {
lvl := l.Level()
if lvl <= LevelInfo {
l.b.print("INF", l.tag, args...)
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L587-L595
|
func (r *ProtocolLXD) UpdateContainer(name string, container api.ContainerPut, ETag string) (Operation, error) {
// Send the request
op, _, err := r.queryOperation("PUT", fmt.Sprintf("/containers/%s", url.QueryEscape(name)), container, ETag)
if err != nil {
return nil, err
}
return op, nil
}
|
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L113-L126
|
func (g Garbler) addNums(p string, numDigits int) string {
if numDigits <= 0 {
return p
}
ret := p
remaining := numDigits
for remaining > 10 {
ret += fmt.Sprintf("%d", pow(10, 9)+randInt(pow(10, 10)-pow(10, 9)))
remaining -= 10
}
ret += fmt.Sprintf("%d", pow(10, remaining-1)+randInt(pow(10, remaining)-pow(10, remaining-1)))
return ret
}
|
https://github.com/mastahyeti/fakeca/blob/c1d84b1b473e99212130da7b311dd0605de5ed0a/configuration.go#L186-L190
|
func PrivateKey(value crypto.Signer) Option {
return func(c *configuration) {
c.priv = &value
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6698-L6706
|
func (u StellarMessage) MustQSet() ScpQuorumSet {
val, ok := u.GetQSet()
if !ok {
panic("arm QSet is not set")
}
return val
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux.go#L265-L282
|
func GetErrno(err error) (errno error, iserrno bool) {
sysErr, ok := err.(*os.SyscallError)
if ok {
return sysErr.Err, true
}
pathErr, ok := err.(*os.PathError)
if ok {
return pathErr.Err, true
}
tmpErrno, ok := err.(syscall.Errno)
if ok {
return tmpErrno, true
}
return nil, false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5276-L5280
|
func (v EventPseudoElementAdded) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom59(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/cachestorage.go#L114-L120
|
func RequestCachedResponse(cacheID CacheID, requestURL string, requestHeaders []*Header) *RequestCachedResponseParams {
return &RequestCachedResponseParams{
CacheID: cacheID,
RequestURL: requestURL,
RequestHeaders: requestHeaders,
}
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/image.go#L68-L73
|
func (c *Client) ListImages() (*Images, error) {
url := imageColPath() + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Images{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/asset.go#L55-L65
|
func (a Asset) String() string {
var t, c, i string
a.MustExtract(&t, &c, &i)
if a.Type == AssetTypeAssetTypeNative {
return t
}
return fmt.Sprintf("%s/%s/%s", t, c, i)
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/config.go#L75-L80
|
func GetConfig(source interface{}, environment string) (server Config, err error) {
var serverEnvironment ServerEnvironment
i, err := config.Get(source, environment, &serverEnvironment)
server = i.(Config)
return
}
|
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/dbprovider/mongodb/monogodbprovider.go#L76-L82
|
func (m MongoDb) InitDb() error {
if err := m.InitUser(); err != nil {
logger.Get().Error("Error Initilaizing User Table", err)
return err
}
return nil
}
|
https://github.com/nightlyone/lockfile/blob/0ad87eef1443f64d3d8c50da647e2b1552851124/lockfile.go#L169-L190
|
func (l Lockfile) Unlock() error {
proc, err := l.GetOwner()
switch err {
case ErrInvalidPid, ErrDeadOwner:
return ErrRogueDeletion
case nil:
if proc.Pid == os.Getpid() {
// we really own it, so let's remove it.
return os.Remove(string(l))
}
// Not owned by me, so don't delete it.
return ErrRogueDeletion
default:
// This is an application error or system error.
// So give a better error for logging here.
if os.IsNotExist(err) {
return ErrRogueDeletion
}
// Other errors -> defensively fail and let caller handle this
return err
}
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/boshrelease.go#L53-L67
|
func (r *BoshRelease) readBoshRelease(rr io.Reader) error {
w := pkg.NewTgzWalker(rr)
w.OnMatch("release.MF", func(file pkg.FileEntry) error {
return decodeYaml(file.Reader, &r.ReleaseManifest)
})
w.OnMatch("/jobs/", func(file pkg.FileEntry) error {
job, jerr := r.readBoshJob(file.Reader)
if jerr == nil {
r.JobManifests[job.Name] = job
}
return jerr
})
err := w.Walk()
return err
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/streambuffer/streambuffer.go#L73-L80
|
func (s *Stream) CloseRecv() {
s.mu.Lock()
if s.recvBuffer != nil {
close(s.recvBuffer)
s.recvBuffer = nil
}
s.mu.Unlock()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/boskos.go#L186-L238
|
func handleAcquireByState(r *ranch.Ranch) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
logrus.WithField("handler", "handleStart").Infof("From %v", req.RemoteAddr)
if req.Method != http.MethodPost {
msg := fmt.Sprintf("Method %v, /acquire only accepts POST.", req.Method)
logrus.Warning(msg)
http.Error(res, msg, http.StatusMethodNotAllowed)
return
}
// TODO(krzyzacy) - sanitize user input
state := req.URL.Query().Get("state")
dest := req.URL.Query().Get("dest")
owner := req.URL.Query().Get("owner")
names := req.URL.Query().Get("names")
if state == "" || dest == "" || owner == "" || names == "" {
msg := fmt.Sprintf(
"state: %v, dest: %v, owner: %v, names: %v - all of them must be set in the request.",
state, dest, owner, names)
logrus.Warning(msg)
http.Error(res, msg, http.StatusBadRequest)
return
}
rNames := strings.Split(names, ",")
logrus.Infof("Request resources %s at state %v from %v, to state %v",
strings.Join(rNames, ", "), state, owner, dest)
resources, err := r.AcquireByState(state, dest, owner, rNames)
if err != nil {
logrus.WithError(err).Errorf("No available resources")
http.Error(res, err.Error(), ErrorToStatus(err))
return
}
resBytes := new(bytes.Buffer)
if err := json.NewEncoder(resBytes).Encode(resources); err != nil {
logrus.WithError(err).Errorf("json.Marshal failed: %v, resources will be released", resources)
http.Error(res, err.Error(), ErrorToStatus(err))
for _, resource := range resources {
err := r.Release(resource.Name, state, owner)
if err != nil {
logrus.WithError(err).Warningf("unable to release resource %s", resource.Name)
}
}
return
}
logrus.Infof("Resource leased: %v", resBytes.String())
fmt.Fprint(res, resBytes.String())
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L280-L285
|
func canIdentifyUser(config restConfig) bool {
return len(config.Username) > 0 ||
(len(config.CertFile) > 0 || len(config.CertData) > 0) ||
len(config.BearerToken) > 0
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L341-L344
|
func (p GetBoxModelParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetBoxModelParams {
p.BackendNodeID = backendNodeID
return &p
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L8402-L8548
|
func (c *containerLXC) getDiskLimits() (map[string]deviceBlockLimit, error) {
result := map[string]deviceBlockLimit{}
// Build a list of all valid block devices
validBlocks := []string{}
dents, err := ioutil.ReadDir("/sys/class/block/")
if err != nil {
return nil, err
}
for _, f := range dents {
fPath := filepath.Join("/sys/class/block/", f.Name())
if shared.PathExists(fmt.Sprintf("%s/partition", fPath)) {
continue
}
if !shared.PathExists(fmt.Sprintf("%s/dev", fPath)) {
continue
}
block, err := ioutil.ReadFile(fmt.Sprintf("%s/dev", fPath))
if err != nil {
return nil, err
}
validBlocks = append(validBlocks, strings.TrimSuffix(string(block), "\n"))
}
// Process all the limits
blockLimits := map[string][]deviceBlockLimit{}
for _, k := range c.expandedDevices.DeviceNames() {
m := c.expandedDevices[k]
if m["type"] != "disk" {
continue
}
// Apply max limit
if m["limits.max"] != "" {
m["limits.read"] = m["limits.max"]
m["limits.write"] = m["limits.max"]
}
// Parse the user input
readBps, readIops, writeBps, writeIops, err := deviceParseDiskLimit(m["limits.read"], m["limits.write"])
if err != nil {
return nil, err
}
// Set the source path
source := shared.HostPath(m["source"])
if source == "" {
source = c.RootfsPath()
}
// Don't try to resolve the block device behind a non-existing path
if !shared.PathExists(source) {
continue
}
// Get the backing block devices (major:minor)
blocks, err := deviceGetParentBlocks(source)
if err != nil {
if readBps == 0 && readIops == 0 && writeBps == 0 && writeIops == 0 {
// If the device doesn't exist, there is no limit to clear so ignore the failure
continue
} else {
return nil, err
}
}
device := deviceBlockLimit{readBps: readBps, readIops: readIops, writeBps: writeBps, writeIops: writeIops}
for _, block := range blocks {
blockStr := ""
if shared.StringInSlice(block, validBlocks) {
// Straightforward entry (full block device)
blockStr = block
} else {
// Attempt to deal with a partition (guess its parent)
fields := strings.SplitN(block, ":", 2)
fields[1] = "0"
if shared.StringInSlice(fmt.Sprintf("%s:%s", fields[0], fields[1]), validBlocks) {
blockStr = fmt.Sprintf("%s:%s", fields[0], fields[1])
}
}
if blockStr == "" {
return nil, fmt.Errorf("Block device doesn't support quotas: %s", block)
}
if blockLimits[blockStr] == nil {
blockLimits[blockStr] = []deviceBlockLimit{}
}
blockLimits[blockStr] = append(blockLimits[blockStr], device)
}
}
// Average duplicate limits
for block, limits := range blockLimits {
var readBpsCount, readBpsTotal, readIopsCount, readIopsTotal, writeBpsCount, writeBpsTotal, writeIopsCount, writeIopsTotal int64
for _, limit := range limits {
if limit.readBps > 0 {
readBpsCount += 1
readBpsTotal += limit.readBps
}
if limit.readIops > 0 {
readIopsCount += 1
readIopsTotal += limit.readIops
}
if limit.writeBps > 0 {
writeBpsCount += 1
writeBpsTotal += limit.writeBps
}
if limit.writeIops > 0 {
writeIopsCount += 1
writeIopsTotal += limit.writeIops
}
}
device := deviceBlockLimit{}
if readBpsCount > 0 {
device.readBps = readBpsTotal / readBpsCount
}
if readIopsCount > 0 {
device.readIops = readIopsTotal / readIopsCount
}
if writeBpsCount > 0 {
device.writeBps = writeBpsTotal / writeBpsCount
}
if writeIopsCount > 0 {
device.writeIops = writeIopsTotal / writeIopsCount
}
result[block] = device
}
return result, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1459-L1463
|
func (v SetStyleTextsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss12(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/releasejob_experiment/job.go#L42-L63
|
func BuildJob(jobMeta BoshJobMeta, dest string) error {
b, err := json.Marshal(jobMeta)
if err != nil {
return err
}
fmt.Println("building job: ", string(b))
monitFile, specFile, err := createJobFiles(dest, jobMeta.Name)
if err != nil {
return err
}
defer monitFile.Close()
defer specFile.Close()
err = writeMonitFile(monitFile, jobMeta.Name, jobMeta.PIDFile)
if err != nil {
return err
}
err = writeSpecFile(specFile, jobMeta.Name, jobMeta.JobProperties, jobMeta.Packages)
return err
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/integers.go#L66-L114
|
func (b *TupleBuilder) PutUint16(field string, value uint16) (wrote uint64, err error) {
// field type should be
if err = b.typeCheck(field, Uint16Field); err != nil {
return 0, err
}
if value < math.MaxUint8 {
// minimum bytes is 2 (type code + value)
if b.available() < 2 {
return 0, xbinary.ErrOutOfRange
}
// write type code
b.buffer[b.pos] = byte(UnsignedShort8Code.OpCode)
// write value
b.buffer[b.pos+1] = byte(value)
// set field offset
b.offsets[field] = b.pos
// incr pos
b.pos += 2
return 2, nil
}
// write value
// length check performed by xbinary
wrote, err = xbinary.LittleEndian.PutUint16(b.buffer, b.pos+1, value)
if err != nil {
return 0, err
}
// write type code
b.buffer[b.pos] = byte(UnsignedShort16Code.OpCode)
// set field offset
b.offsets[field] = b.pos
// incr pos
b.pos += 3
// wrote 3 bytes
return 3, nil
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L195-L207
|
func (api *TelegramBotAPI) NewOutgoingAudioResend(recipient Recipient, fileID string) *OutgoingAudio {
return &OutgoingAudio{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5755-L5759
|
func (v EventChildNodeInserted) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom64(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/iterator.go#L83-L90
|
func (it *Iterator) Refresh() {
if it.Valid() {
itm := it.snap.db.ptrToItem(it.GetNode().Item())
it.iter.Close()
it.iter = it.snap.db.store.NewIterator(it.snap.db.iterCmp, it.buf)
it.iter.Seek(unsafe.Pointer(itm))
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L897-L929
|
func (c *Cluster) ContainerNextSnapshot(project string, name string, pattern string) int {
base := name + shared.SnapshotDelimiter
length := len(base)
q := `
SELECT containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?`
var numstr string
inargs := []interface{}{project, CTypeSnapshot, length, base}
outfmt := []interface{}{numstr}
results, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return 0
}
max := 0
for _, r := range results {
snapOnlyName := strings.SplitN(r[0].(string), shared.SnapshotDelimiter, 2)[1]
fields := strings.SplitN(pattern, "%d", 2)
var num int
count, err := fmt.Sscanf(snapOnlyName, fmt.Sprintf("%s%%d%s", fields[0], fields[1]), &num)
if err != nil || count != 1 {
continue
}
if num >= max {
max = num + 1
}
}
return max
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/domain.go#L54-L66
|
func (cgp *CGP) Domains() ([]*Domain, error) {
var vl valueList
err := cgp.request(listDomains{}, &vl)
if err != nil {
return []*Domain{}, err
}
vals := vl.SubValues
ds := make([]*Domain, len(vals))
for i, d := range vals {
ds[i] = cgp.Domain(d)
}
return ds, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/helpers.go#L64-L78
|
func cleanDescription(doc string) string {
docBits := strings.Split(doc, "Required security scope")
doc = docBits[0]
lines := strings.Split(doc, "\n")
fullLines := make([]string, len(lines))
i := 0
for _, line := range lines {
if len(line) > 0 && !blankRegexp.MatchString(line) {
fullLines[i] = line
i++
}
}
return strings.Join(fullLines[:i], "\n")
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/sidecar/options.go#L94-L97
|
func (o *Options) AddFlags(flags *flag.FlagSet) {
o.GcsOptions.AddFlags(flags)
// DeprecatedWrapperOptions flags should be unused, remove immediately
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L86-L111
|
func (c *ClusterTx) ProjectURIs(filter ProjectFilter) ([]string, error) {
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectNamesByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectNames)
args = []interface{}{}
}
code := cluster.EntityTypes["project"]
formatter := cluster.EntityFormatURIs[code]
return query.SelectURIs(stmt, formatter, args...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/listers/prowjobs/v1/prowjob.go#L77-L82
|
func (s prowJobNamespaceLister) List(selector labels.Selector) (ret []*v1.ProwJob, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1.ProwJob))
})
return ret, err
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L298-L313
|
func (c *Client) pagedQuery(pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) {
// connect to service
service, err := c.connect()
if err != nil {
if dataChan != nil {
dataChan <- Data{Err: err}
}
return nil, nil, err
}
if c.allowLargeResults && len(c.tempTableName) > 0 {
return c.largeDataPagedQuery(service, pageSize, dataset, project, queryStr, dataChan)
}
return c.stdPagedQuery(service, pageSize, dataset, project, queryStr, dataChan)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/pool/pool.go#L466-L481
|
func GetPoolByName(name string) (*Pool, error) {
conn, err := db.Conn()
if err != nil {
return nil, err
}
defer conn.Close()
var p Pool
err = conn.Pools().FindId(name).One(&p)
if err != nil {
if err == mgo.ErrNotFound {
return nil, ErrPoolNotFound
}
return nil, err
}
return &p, nil
}
|
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L311-L319
|
func RandomTCPPort() int {
for i := maxReservedTCPPort; i < maxTCPPort; i++ {
p := tcpPortRand.Intn(maxRandTCPPort) + maxReservedTCPPort + 1
if IsTCPPortAvailable(p) {
return p
}
}
return -1
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/message.go#L49-L74
|
func ToLogLevel(level string) (LogLevel, error) {
lowLevel := strings.ToLower(level)
switch lowLevel {
case "dbg":
fallthrough
case "debug":
return LevelDebug, nil
case "info":
return LevelInfo, nil
case "warn":
fallthrough
case "warning":
return LevelWarning, nil
case "err":
fallthrough
case "error":
return LevelError, nil
case "fatal":
return LevelFatal, nil
case "none":
return LevelNone, nil
}
return 0, ErrUnknownLevel
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode_reader.go#L158-L178
|
func (d *decodeReader) queueFilter(f *filterBlock) error {
if f.reset {
d.filters = nil
}
if len(d.filters) >= maxQueuedFilters {
return errTooManyFilters
}
// offset & length must be < window size
f.offset &= d.win.mask
f.length &= d.win.mask
// make offset relative to previous filter in list
for _, fb := range d.filters {
if f.offset < fb.offset {
// filter block must not start before previous filter
return errInvalidFilter
}
f.offset -= fb.offset
}
d.filters = append(d.filters, f)
return nil
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L304-L312
|
func (op *OutgoingPhoto) querystring() querystring {
toReturn := map[string]string(op.getBaseQueryString())
if op.Caption != "" {
toReturn["caption"] = op.Caption
}
return querystring(toReturn)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L188-L224
|
func (t *PseudoType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch PseudoType(in.String()) {
case PseudoTypeFirstLine:
*t = PseudoTypeFirstLine
case PseudoTypeFirstLetter:
*t = PseudoTypeFirstLetter
case PseudoTypeBefore:
*t = PseudoTypeBefore
case PseudoTypeAfter:
*t = PseudoTypeAfter
case PseudoTypeBackdrop:
*t = PseudoTypeBackdrop
case PseudoTypeSelection:
*t = PseudoTypeSelection
case PseudoTypeFirstLineInherited:
*t = PseudoTypeFirstLineInherited
case PseudoTypeScrollbar:
*t = PseudoTypeScrollbar
case PseudoTypeScrollbarThumb:
*t = PseudoTypeScrollbarThumb
case PseudoTypeScrollbarButton:
*t = PseudoTypeScrollbarButton
case PseudoTypeScrollbarTrack:
*t = PseudoTypeScrollbarTrack
case PseudoTypeScrollbarTrackPiece:
*t = PseudoTypeScrollbarTrackPiece
case PseudoTypeScrollbarCorner:
*t = PseudoTypeScrollbarCorner
case PseudoTypeResizer:
*t = PseudoTypeResizer
case PseudoTypeInputListButton:
*t = PseudoTypeInputListButton
default:
in.AddError(errors.New("unknown PseudoType value"))
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L454-L471
|
func buildQuery(values []APIParams) (APIParams, error) {
query := APIParams{}
for _, value := range values {
// Only one iteration below, flatten params only have one element each
for name, param := range value {
if q, ok := query[name]; ok {
if a, ok := q.([]interface{}); ok {
query[name] = append(a, param)
} else {
query[name] = []interface{}{q, param}
}
} else {
query[name] = param
}
}
}
return query, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/obj_block_api_server.go#L881-L905
|
func (s *objBlockAPIServer) writeInternal(ctx context.Context, path string, data []byte) (retErr error) {
defer func() {
if retErr != nil {
return
}
retErr = func() (retErr error) {
if !s.objClient.Exists(ctx, path) {
logrus.Errorf("%s doesn't exist after write", path)
return fmt.Errorf("%s doesn't exist after write", path)
}
return nil
}()
}()
w, err := s.objClient.Writer(ctx, path)
if err != nil {
return err
}
defer func() {
if err := w.Close(); err != nil && retErr == nil {
retErr = err
}
}()
_, err = w.Write(data)
return err
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L122-L124
|
func (win *Window) SetProperty(prop_id int, value float64) {
C.cvSetWindowProperty(win.name_c, C.int(prop_id), C.double(value))
}
|
https://github.com/Financial-Times/neo-model-utils-go/blob/aea1e95c83055aaed6761c5e546400dd383fb220/mapper/uri_utils.go#L66-L80
|
func TypeURIs(labels []string) []string {
var results []string
sorted, err := SortTypes(labels)
if err != nil {
log.Printf("ERROR - %v", err)
return []string{}
}
for _, label := range sorted {
uri := typeURIs[label]
if uri != "" {
results = append(results, uri)
}
}
return results
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/level.go#L90-L100
|
func (l *moduleLeveled) GetLevel(module string) Level {
level, exists := l.levels[module]
if exists == false {
level, exists = l.levels[""]
// no configuration exists, default to debug
if exists == false {
level = DEBUG
}
}
return level
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L203-L207
|
func (eC2Manager *EC2Manager) RemoveKeyPair(name string) error {
cd := tcclient.Client(*eC2Manager)
_, _, err := (&cd).APICall(nil, "DELETE", "/key-pairs/"+url.QueryEscape(name), nil, nil)
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/clone/clone.go#L99-L109
|
func gitCtxForRefs(refs prowapi.Refs, baseDir string, env []string) gitCtx {
g := gitCtx{
cloneDir: PathForRefs(baseDir, refs),
env: env,
repositoryURI: fmt.Sprintf("https://github.com/%s/%s.git", refs.Org, refs.Repo),
}
if refs.CloneURI != "" {
g.repositoryURI = refs.CloneURI
}
return g
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/easyjson.go#L326-L330
|
func (v *EventSinksUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCast3(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/get_command.go#L44-L66
|
func getCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(c, ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
sorted := c.Bool("sort")
quorum := c.Bool("quorum")
ctx, cancel := contextWithTotalTimeout(c)
resp, err := ki.Get(ctx, key, &client.GetOptions{Sort: sorted, Quorum: quorum})
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
if resp.Node.Dir {
fmt.Fprintln(os.Stderr, fmt.Sprintf("%s: is a directory", resp.Node.Key))
os.Exit(1)
}
printResponseKey(resp, c.GlobalString("output"))
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dimg/ftgc.go#L56-L66
|
func NewGraphicContext(img draw.Image) *GraphicContext {
var painter Painter
switch selectImage := img.(type) {
case *image.RGBA:
painter = raster.NewRGBAPainter(selectImage)
default:
panic("Image type not supported")
}
return NewGraphicContextWithPainter(img, painter)
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L283-L297
|
func (peers *Peers) fetchWithDefault(peer *Peer) *Peer {
peers.Lock()
var pending peersPendingNotifications
defer peers.unlockAndNotify(&pending)
if existingPeer, found := peers.byName[peer.Name]; found {
existingPeer.localRefCount++
return existingPeer
}
peers.byName[peer.Name] = peer
peers.addByShortID(peer, &pending)
peer.localRefCount++
return peer
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L202-L204
|
func Increment(c context.Context, key string, delta int64, initialValue uint64) (newValue uint64, err error) {
return incr(c, key, delta, &initialValue)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L996-L1013
|
func (r *ProtocolLXD) GetContainerSnapshotNames(containerName string) ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots", url.QueryEscape(containerName)), nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
names := []string{}
for _, uri := range urls {
fields := strings.Split(uri, fmt.Sprintf("/containers/%s/snapshots/", url.QueryEscape(containerName)))
names = append(names, fields[len(fields)-1])
}
return names, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L7102-L7111
|
func (u ScpStatementPledges) GetPrepare() (result ScpStatementPrepare, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Prepare" {
result = *u.Prepare
ok = true
}
return
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L183-L213
|
func (s *storageImageSource) GetManifest(ctx context.Context, instanceDigest *digest.Digest) (manifestBlob []byte, MIMEType string, err error) {
if instanceDigest != nil {
return nil, "", ErrNoManifestLists
}
if len(s.cachedManifest) == 0 {
// The manifest is stored as a big data item.
// Prefer the manifest corresponding to the user-specified digest, if available.
if s.imageRef.named != nil {
if digested, ok := s.imageRef.named.(reference.Digested); ok {
key := manifestBigDataKey(digested.Digest())
blob, err := s.imageRef.transport.store.ImageBigData(s.image.ID, key)
if err != nil && !os.IsNotExist(err) { // os.IsNotExist is true if the image exists but there is no data corresponding to key
return nil, "", err
}
if err == nil {
s.cachedManifest = blob
}
}
}
// If the user did not specify a digest, or this is an old image stored before manifestBigDataKey was introduced, use the default manifest.
// Note that the manifest may not match the expected digest, and that is likely to fail eventually, e.g. in c/image/image/UnparsedImage.Manifest().
if len(s.cachedManifest) == 0 {
cachedBlob, err := s.imageRef.transport.store.ImageBigData(s.image.ID, storage.ImageDigestBigDataKey)
if err != nil {
return nil, "", err
}
s.cachedManifest = cachedBlob
}
}
return s.cachedManifest, manifest.GuessMIMEType(s.cachedManifest), err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/manifest.go#L238-L244
|
func layerInfosToStrings(infos []LayerInfo) []string {
layers := make([]string, len(infos))
for i, info := range infos {
layers[i] = info.Digest.String()
}
return layers
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L49-L58
|
func slide(bz *[]byte, n *int, _n int) bool {
if _n < 0 || _n > len(*bz) {
panic(fmt.Sprintf("impossible slide: len:%v _n:%v", len(*bz), _n))
}
*bz = (*bz)[_n:]
if n != nil {
*n += _n
}
return true
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L327-L338
|
func (g *Gateway) Sync() {
if g.server == nil {
return
}
dir := filepath.Join(g.db.Dir(), "global")
err := g.server.Dump("db.bin", dir)
if err != nil {
// Just log a warning, since this is not fatal.
logger.Warnf("Failed to dump database to disk: %v", err)
}
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L125-L202
|
func (p *Pact) Setup(startMockServer bool) *Pact {
p.setupLogging()
log.Println("[DEBUG] pact setup")
dir, _ := os.Getwd()
if p.Network == "" {
p.Network = "tcp"
}
if !p.toolValidityCheck && !(p.DisableToolValidityCheck || os.Getenv("PACT_DISABLE_TOOL_VALIDITY_CHECK") != "") {
checkCliCompatibility()
p.toolValidityCheck = true
}
if p.Host == "" {
p.Host = "localhost"
}
if p.LogDir == "" {
p.LogDir = fmt.Sprintf(filepath.Join(dir, "logs"))
}
if p.PactDir == "" {
p.PactDir = fmt.Sprintf(filepath.Join(dir, "pacts"))
}
if p.SpecificationVersion == 0 {
p.SpecificationVersion = 2
}
if p.ClientTimeout == 0 {
p.ClientTimeout = 10 * time.Second
}
if p.pactClient == nil {
c := NewClient()
c.TimeoutDuration = p.ClientTimeout
p.pactClient = c
}
if p.PactFileWriteMode == "" {
p.PactFileWriteMode = "overwrite"
}
// Need to predefine due to scoping
var port int
var perr error
if p.AllowedMockServerPorts != "" {
port, perr = utils.FindPortInRange(p.AllowedMockServerPorts)
} else {
port, perr = utils.GetFreePort()
}
if perr != nil {
log.Println("[ERROR] unable to find free port, mockserver will fail to start")
}
if p.Server == nil && startMockServer {
log.Println("[DEBUG] starting mock service on port:", port)
args := []string{
"--pact-specification-version",
fmt.Sprintf("%d", p.SpecificationVersion),
"--pact-dir",
filepath.FromSlash(p.PactDir),
"--log",
filepath.FromSlash(p.LogDir + "/" + "pact.log"),
"--consumer",
p.Consumer,
"--provider",
p.Provider,
"--pact-file-write-mode",
p.PactFileWriteMode,
}
p.Server = p.pactClient.StartServer(args, port)
}
return p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L474-L478
|
func (v ResolveAnimationReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L237-L239
|
func (mat *Mat) SetData(data unsafe.Pointer, step int) {
C.cvSetData(unsafe.Pointer(mat), data, C.int(step))
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L463-L503
|
func (c *dockerClient) setupRequestAuth(req *http.Request, extraScope *authScope) error {
if len(c.challenges) == 0 {
return nil
}
schemeNames := make([]string, 0, len(c.challenges))
for _, challenge := range c.challenges {
schemeNames = append(schemeNames, challenge.Scheme)
switch challenge.Scheme {
case "basic":
req.SetBasicAuth(c.username, c.password)
return nil
case "bearer":
cacheKey := ""
scopes := []authScope{c.scope}
if extraScope != nil {
// Using ':' as a separator here is unambiguous because getBearerToken below uses the same separator when formatting a remote request (and because repository names can't contain colons).
cacheKey = fmt.Sprintf("%s:%s", extraScope.remoteName, extraScope.actions)
scopes = append(scopes, *extraScope)
}
var token bearerToken
t, inCache := c.tokenCache.Load(cacheKey)
if inCache {
token = t.(bearerToken)
}
if !inCache || time.Now().After(token.expirationTime) {
t, err := c.getBearerToken(req.Context(), challenge, scopes)
if err != nil {
return err
}
token = *t
c.tokenCache.Store(cacheKey, token)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.Token))
return nil
default:
logrus.Debugf("no handler for %s authentication", challenge.Scheme)
}
}
logrus.Infof("None of the challenges sent by server (%s) are supported, trying an unauthenticated request anyway", strings.Join(schemeNames, ", "))
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/cert.go#L19-L28
|
func (c *Config) GenerateClientCertificate() error {
if c.HasClientCertificate() {
return nil
}
certf := c.ConfigPath("client.crt")
keyf := c.ConfigPath("client.key")
return shared.FindOrGenCert(certf, keyf, true)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/report/report.go#L209-L211
|
func Percentiles(nums []float64) (pcs []float64, data []float64) {
return pctls, percentiles(nums)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/influx.go#L58-L88
|
func (config *InfluxConfig) CreateDatabase(tags map[string]string, measurement string) (*InfluxDB, error) {
client, err := influxdb.NewHTTPClient(influxdb.HTTPConfig{
Addr: config.Host,
Username: config.User,
Password: config.Password,
})
if err != nil {
return nil, err
}
err = dropSeries(client, measurement, config.DB, tags)
if err != nil {
return nil, err
}
bp, err := influxdb.NewBatchPoints(influxdb.BatchPointsConfig{
Database: config.DB,
Precision: "s",
})
if err != nil {
return nil, err
}
return &InfluxDB{
client: client,
database: config.DB,
batch: bp,
tags: tags,
measurement: measurement,
}, err
}
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/usage.go#L16-L20
|
func (p *Parser) Fail(msg string) {
p.WriteUsage(os.Stderr)
fmt.Fprintln(os.Stderr, "error:", msg)
os.Exit(-1)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/exec.go#L30-L49
|
func RunIODirPath(ioObj IO, dirPath string, args ...string) error {
var debugStderr io.ReadWriter = bytes.NewBuffer(nil)
var stderr io.Writer = debugStderr
if ioObj.Stderr != nil {
stderr = io.MultiWriter(debugStderr, ioObj.Stderr)
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = ioObj.Stdin
cmd.Stdout = ioObj.Stdout
cmd.Stderr = stderr
cmd.Dir = dirPath
if err := cmd.Run(); err != nil {
data, _ := ioutil.ReadAll(debugStderr)
if data != nil && len(data) > 0 {
return fmt.Errorf("%s: %s\n%s", strings.Join(args, " "), err.Error(), string(data))
}
return fmt.Errorf("%s: %s", strings.Join(args, " "), err.Error())
}
return nil
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/codec.go#L15-L17
|
func (c Codec) NewEncoder(w io.Writer) *Encoder {
return NewEncoder(c.NewEmitter(w))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1575-L1579
|
func (v *ProfileNode) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler16(&r, v)
return r.Error()
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L171-L178
|
func (r *InclusiveRange) Max() int {
start := r.Start()
end := r.End()
if start > end {
return start
}
return end
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L318-L320
|
func (f *FakeClient) FindIssues(query, sort string, asc bool) ([]github.Issue, error) {
return f.Issues, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/builder.go#L179-L182
|
func (b *Builder) ReachedCapacity(cap int64) bool {
estimateSz := b.buf.Len() + 8 /* empty header */ + 4*len(b.restarts) + 8 // 8 = end of buf offset + len(restarts).
return int64(estimateSz) > cap
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/session.go#L95-L102
|
func (s *Session) Close() error {
s.Orphan()
// if revoke takes longer than the ttl, lease is expired anyway
ctx, cancel := context.WithTimeout(s.opts.ctx, time.Duration(s.opts.ttl)*time.Second)
_, err := s.client.Revoke(ctx, s.id)
cancel()
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/client.go#L45-L74
|
func (c *Client) Acquire(rtype, state, dest string) (*common.Resource, error) {
var resourcesToRelease []common.Resource
releaseOnFailure := func() {
for _, r := range resourcesToRelease {
if err := c.basic.ReleaseOne(r.Name, common.Dirty); err != nil {
logrus.WithError(err).Warningf("failed to release resource %s", r.Name)
}
}
}
res, err := c.basic.Acquire(rtype, state, dest)
if err != nil {
return nil, err
}
var leasedResources common.LeasedResources
if err = res.UserData.Extract(LeasedResources, &leasedResources); err != nil {
if _, ok := err.(*common.UserDataNotFound); !ok {
logrus.WithError(err).Errorf("cannot parse %s from User Data", LeasedResources)
return nil, err
}
}
resourcesToRelease = append(resourcesToRelease, *res)
resources, err := c.basic.AcquireByState(res.Name, dest, leasedResources)
if err != nil {
releaseOnFailure()
return nil, err
}
resourcesToRelease = append(resourcesToRelease, resources...)
c.updateResource(*res)
return res, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L728-L732
|
func (v GetEventListenersReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger8(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/main.go#L585-L597
|
func handleJobHistory(o options, cfg config.Getter, gcsClient *storage.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
tmpl, err := getJobHistory(r.URL, cfg(), gcsClient)
if err != nil {
msg := fmt.Sprintf("failed to get job history: %v", err)
logrus.WithField("url", r.URL).Error(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
handleSimpleTemplate(o, cfg, "job-history.html", tmpl)(w, r)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L713-L717
|
func (v *EventDomStorageItemUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomstorage6(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/query.go#L14-L28
|
func updateNodeVersion(tx *sql.Tx, address string, apiExtensions int) error {
stmt := "UPDATE nodes SET schema=?, api_extensions=? WHERE address=?"
result, err := tx.Exec(stmt, len(updates), apiExtensions, address)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("updated %d rows instead of 1", n)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1898-L1902
|
func (v *EventInspectNodeRequested) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay19(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1800-L1866
|
func (s *EtcdServer) publish(timeout time.Duration) {
b, err := json.Marshal(s.attributes)
if err != nil {
if lg := s.getLogger(); lg != nil {
lg.Panic("failed to marshal JSON", zap.Error(err))
} else {
plog.Panicf("json marshal error: %v", err)
}
return
}
req := pb.Request{
Method: "PUT",
Path: membership.MemberAttributesStorePath(s.id),
Val: string(b),
}
for {
ctx, cancel := context.WithTimeout(s.ctx, timeout)
_, err := s.Do(ctx, req)
cancel()
switch err {
case nil:
close(s.readych)
if lg := s.getLogger(); lg != nil {
lg.Info(
"published local member to cluster through raft",
zap.String("local-member-id", s.ID().String()),
zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
zap.String("request-path", req.Path),
zap.String("cluster-id", s.cluster.ID().String()),
zap.Duration("publish-timeout", timeout),
)
} else {
plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
}
return
case ErrStopped:
if lg := s.getLogger(); lg != nil {
lg.Warn(
"stopped publish because server is stopped",
zap.String("local-member-id", s.ID().String()),
zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
zap.Duration("publish-timeout", timeout),
zap.Error(err),
)
} else {
plog.Infof("aborting publish because server is stopped")
}
return
default:
if lg := s.getLogger(); lg != nil {
lg.Warn(
"failed to publish local member to cluster through raft",
zap.String("local-member-id", s.ID().String()),
zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
zap.String("request-path", req.Path),
zap.Duration("publish-timeout", timeout),
zap.Error(err),
)
} else {
plog.Errorf("publish error: %v", err)
}
}
}
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/retry/retry.go#L40-L46
|
func NewRetrier(retries, sleepSeconds int, retryable Retryable) *Retrier {
return &Retrier{
retries: retries,
sleepSeconds: sleepSeconds,
retryable: retryable,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L120-L122
|
func (t *State) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L12286-L12288
|
func (api *API) ServerTemplateLocator(href string) *ServerTemplateLocator {
return &ServerTemplateLocator{Href(href), api}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L126-L129
|
func (p FulfillRequestParams) WithBody(body string) *FulfillRequestParams {
p.Body = body
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L2389-L2393
|
func (v CacheData) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar14(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_project.go#L477-L486
|
func projectIsEmpty(project *api.Project) bool {
if len(project.UsedBy) > 0 {
// Check if the only entity is the default profile.
if len(project.UsedBy) == 1 && strings.Contains(project.UsedBy[0], "/profiles/default") {
return true
}
return false
}
return true
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L344-L352
|
func KeyEqual(k1, k2 Key) bool {
if k1 == k2 {
return true
}
b1, err1 := k1.Bytes()
b2, err2 := k2.Bytes()
return bytes.Equal(b1, b2) && err1 == err2
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/datasource/mongo/config.go#L39-L53
|
func (m *Environment) UnmarshalYAML(unmarshal func(interface{}) error) error {
var aux struct {
Env map[string]struct {
Config `yaml:"mongo"`
}
}
if err := unmarshal(&aux.Env); err != nil {
return err
}
m.Env = make(map[string]Config)
for env, conf := range aux.Env {
m.Env[env] = conf.Config
}
return nil
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/attrs.go#L35-L41
|
func NewAttrsFromAttrs(attrs ...*Attrs) *Attrs {
newAttrs := NewAttrs()
for _, attr := range attrs {
newAttrs.MergeAttrs(attr)
}
return newAttrs
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go#L16-L22
|
func (in *App) DeepCopyInto(out *App) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L136-L141
|
func (c *Client) ListAttachedVolumes(dcid, srvid string) (*Volumes, error) {
url := serverVolumeColPath(dcid, srvid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Volumes{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L93-L217
|
func raftInstanceInit(
db *db.Node, node *db.RaftNode, cert *shared.CertInfo, latency float64) (*raftInstance, error) {
// FIXME: should be a parameter
timeout := 5 * time.Second
raftLogger := raftLogger()
// Raft config.
config := raftConfig(latency)
config.Logger = raftLogger
config.LocalID = raft.ServerID(strconv.Itoa(int(node.ID)))
// Raft transport
var handler *rafthttp.Handler
var membershipChanger func(*raft.Raft)
var layer *rafthttp.Layer
var transport raft.Transport
addr := node.Address
if addr == "" {
// This should normally be used only for testing as it can
// cause split-brian, but since we are not exposing raft to the
// network at all it's safe to do so. When this node gets
// exposed to the network and assigned an address, we need to
// restart raft anyways.
config.StartAsLeader = true
transport = raftMemoryTransport()
} else {
dial, err := raftDial(cert)
if err != nil {
return nil, err
}
transport, handler, layer, err = raftNetworkTransport(db, addr, log.New(&raftLogWriter{}, "", 0), timeout, dial)
if err != nil {
return nil, err
}
membershipChanger = func(raft *raft.Raft) {
raftmembership.HandleChangeRequests(raft, handler.Requests())
}
}
err := raft.ValidateConfig(config)
if err != nil {
return nil, errors.Wrap(err, "invalid raft configuration")
}
// Rename legacy data directory if needed.
dir := filepath.Join(db.Dir(), "global")
legacyDir := filepath.Join(db.Dir(), "..", "raft")
if shared.PathExists(legacyDir) {
if shared.PathExists(dir) {
return nil, fmt.Errorf("both legacy and new global database directories exist")
}
logger.Info("Renaming global database directory from raft/ to database/global/")
err := os.Rename(legacyDir, dir)
if err != nil {
return nil, errors.Wrap(err, "failed to rename legacy global database directory")
}
}
// Data directory
if !shared.PathExists(dir) {
err := os.Mkdir(dir, 0750)
if err != nil {
return nil, err
}
}
// Raft logs store
logs, err := raftboltdb.New(raftboltdb.Options{
Path: filepath.Join(dir, "logs.db"),
BoltOptions: &bolt.Options{Timeout: timeout},
})
if err != nil {
return nil, errors.Wrap(err, "failed to create bolt store for raft logs")
}
// Raft snapshot store (don't log snapshots since we take them frequently)
snaps, err := raft.NewFileSnapshotStoreWithLogger(dir, 2, log.New(ioutil.Discard, "", 0))
if err != nil {
return nil, errors.Wrap(err, "failed to create file snapshot store")
}
// If we are the initial node, we use the last index persisted in the
// logs store and other checks to determine if we have ever
// bootstrapped the cluster, and if not we do so (see raft.HasExistingState).
if node.ID == 1 {
err := raftMaybeBootstrap(config, logs, snaps, transport)
if err != nil {
return nil, errors.Wrap(err, "failed to boostrap cluster")
}
}
// The dqlite registry and FSM.
registry := dqlite.NewRegistry(strconv.Itoa(serial))
serial++
fsm := dqlite.NewFSM(registry)
// The actual raft instance.
raft, err := raft.NewRaft(config, fsm, logs, logs, snaps, transport)
if err != nil {
logs.Close()
return nil, errors.Wrap(err, "failed to start raft")
}
if membershipChanger != nil {
// Process Raft connections over HTTP. This goroutine will
// terminate when instance.handler.Close() is called, which
// happens indirectly when the raft instance is shutdown in
// instance.Shutdown(), and the associated transport is closed.
go membershipChanger(raft)
}
instance := &raftInstance{
layer: layer,
handler: raftHandler(cert, handler),
membershipChanger: membershipChanger,
logs: logs,
registry: registry,
fsm: fsm,
raft: raft,
}
return instance, nil
}
|
https://github.com/kjk/lzmadec/blob/4c61f00ce86f6f11ed9630fa16b771889b08147b/lzmadec.go#L84-L96
|
func advanceToFirstEntry(scanner *bufio.Scanner) error {
for scanner.Scan() {
s := scanner.Text()
if s == "----------" {
return nil
}
}
err := scanner.Err()
if err == nil {
err = ErrNoEntries
}
return err
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L122-L143
|
func (r *Raft) run() {
for {
// Check if we are doing a shutdown
select {
case <-r.shutdownCh:
// Clear the leader to prevent forwarding
r.setLeader("")
return
default:
}
// Enter into a sub-FSM
switch r.getState() {
case Follower:
r.runFollower()
case Candidate:
r.runCandidate()
case Leader:
r.runLeader()
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L823-L827
|
func (v *GetCategoriesParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTracing7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5275-L5279
|
func (v GetComputedStyleForNodeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss46(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.