_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L285-L291
|
func (op *remoteOperation) CancelTarget() error {
if op.targetOp == nil {
return fmt.Errorf("No associated target operation")
}
return op.targetOp.Cancel()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L469-L489
|
func serviceInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
serviceName := r.URL.Query().Get(":name")
_, err := getService(serviceName)
if err != nil {
return err
}
contexts := permission.ContextsForPermission(t, permission.PermServiceInstanceRead)
instances, err := readableInstances(t, contexts, "", serviceName)
if err != nil {
return err
}
var result []service.ServiceInstanceWithInfo
for _, instance := range instances {
infoData, err := instance.ToInfo()
if err != nil {
return err
}
result = append(result, infoData)
}
return json.NewEncoder(w).Encode(result)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L118-L120
|
func (t ScopeType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L453-L464
|
func (c *JobConfig) SetPresubmits(jobs map[string][]Presubmit) error {
nj := map[string][]Presubmit{}
for k, v := range jobs {
nj[k] = make([]Presubmit, len(v))
copy(nj[k], v)
if err := SetPresubmitRegexes(nj[k]); err != nil {
return err
}
}
c.Presubmits = nj
return nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/error.go#L34-L40
|
func (e *Error) Error() string {
sev := "W"
if e.Severe {
sev = "E"
}
return fmt.Sprintf("[%s] %s: %s", sev, e.Name, e.Detail)
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vmx.go#L68-L84
|
func readVmx(path string) (map[string]string, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
vmx := make(map[string]string)
for _, line := range strings.Split(string(data), "\n") {
values := strings.Split(line, "=")
if len(values) == 2 {
vmx[strings.TrimSpace(values[0])] = strings.Trim(strings.TrimSpace(values[1]), `"`)
}
}
return vmx, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/dco/dco.go#L125-L141
|
func checkExistingStatus(gc gitHubClient, l *logrus.Entry, org, repo, sha string) (string, error) {
statuses, err := gc.ListStatuses(org, repo, sha)
if err != nil {
return "", fmt.Errorf("error listing pull request statuses: %v", err)
}
existingStatus := ""
for _, status := range statuses {
if status.Context != dcoContextName {
continue
}
existingStatus = status.State
break
}
l.Debugf("Existing DCO status context status is %q", existingStatus)
return existingStatus, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3448-L3452
|
func (v *GetPossibleBreakpointsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger36(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_dest.go#L28-L60
|
func newImageDestination(sys *types.SystemContext, ref ociReference) (types.ImageDestination, error) {
var index *imgspecv1.Index
if indexExists(ref) {
var err error
index, err = ref.getIndex()
if err != nil {
return nil, err
}
} else {
index = &imgspecv1.Index{
Versioned: imgspec.Versioned{
SchemaVersion: 2,
},
}
}
d := &ociImageDestination{ref: ref, index: *index}
if sys != nil {
d.sharedBlobDir = sys.OCISharedBlobDirPath
d.acceptUncompressedLayers = sys.OCIAcceptUncompressedLayers
}
if err := ensureDirectoryExists(d.ref.dir); err != nil {
return nil, err
}
// Per the OCI image specification, layouts MUST have a "blobs" subdirectory,
// but it MAY be empty (e.g. if we never end up calling PutBlob)
// https://github.com/opencontainers/image-spec/blame/7c889fafd04a893f5c5f50b7ab9963d5d64e5242/image-layout.md#L19
if err := ensureDirectoryExists(filepath.Join(d.ref.dir, "blobs")); err != nil {
return nil, err
}
return d, nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L512-L515
|
func (capture *Capture) QueryFrame() *IplImage {
rv := C.cvQueryFrame((*C.CvCapture)(capture))
return (*IplImage)(rv)
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/path.go#L96-L104
|
func (pa Path) String() string {
var ss []string
for _, s := range pa {
if _, ok := s.(StructField); ok {
ss = append(ss, s.String())
}
}
return strings.TrimPrefix(strings.Join(ss, ""), ".")
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L378-L386
|
func (pa *ConfigAgent) getPlugins(owner, repo string) []string {
var plugins []string
fullName := fmt.Sprintf("%s/%s", owner, repo)
plugins = append(plugins, pa.configuration.Plugins[owner]...)
plugins = append(plugins, pa.configuration.Plugins[fullName]...)
return plugins
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L36-L41
|
func NewDryRunProwJobClient(deckURL string) prowv1.ProwJobInterface {
return &dryRunProwJobClient{
deckURL: deckURL,
client: &http.Client{},
}
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L38-L42
|
func (b *ByteCode) AppendOp(o OpType, args ...interface{}) Op {
x := NewOp(o, args...)
b.Append(x)
return x
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L402-L418
|
func (p *Peer) GetConnection(ctx context.Context) (*Connection, error) {
if activeConn, ok := p.getActiveConn(); ok {
return activeConn, nil
}
// Lock here to restrict new connection creation attempts to one goroutine
p.newConnLock.Lock()
defer p.newConnLock.Unlock()
// Check active connections again in case someone else got ahead of us.
if activeConn, ok := p.getActiveConn(); ok {
return activeConn, nil
}
// No active connections, make a new outgoing connection.
return p.Connect(ctx)
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L372-L403
|
func (p *Page) NextWindow() error {
windows, err := p.session.GetWindows()
if err != nil {
return fmt.Errorf("failed to find available windows: %s", err)
}
var windowIDs []string
for _, window := range windows {
windowIDs = append(windowIDs, window.ID)
}
// order not defined according to W3 spec
sort.Strings(windowIDs)
activeWindow, err := p.session.GetWindow()
if err != nil {
return fmt.Errorf("failed to find active window: %s", err)
}
for position, windowID := range windowIDs {
if windowID == activeWindow.ID {
activeWindow.ID = windowIDs[(position+1)%len(windowIDs)]
break
}
}
if err := p.session.SetWindow(activeWindow); err != nil {
return fmt.Errorf("failed to change active window: %s", err)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L123-L128
|
func RemoveDOMStorageItem(storageID *StorageID, key string) *RemoveDOMStorageItemParams {
return &RemoveDOMStorageItemParams{
StorageID: storageID,
Key: key,
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L182-L191
|
func (l *networkListener) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
l.mu.RLock()
defer l.mu.RUnlock()
config := l.config
return tls.Server(c, config), nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/backend/batch_tx.go#L214-L218
|
func (t *batchTx) CommitAndStop() {
t.Lock()
t.commit(true)
t.Unlock()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L6157-L6159
|
func (api *API) NetworkLocator(href string) *NetworkLocator {
return &NetworkLocator{Href(href), api}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L500-L518
|
func (c *ClusterTx) NodeUpdateVersion(id int64, version [2]int) error {
stmt := "UPDATE nodes SET schema=?, api_extensions=? WHERE id=?"
result, err := c.tx.Exec(stmt, version[0], version[1], id)
if err != nil {
return errors.Wrap(err, "Failed to update nodes table")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Failed to get affected rows")
}
if n != 1 {
return fmt.Errorf("Expected exactly one row to be updated")
}
return nil
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L227-L229
|
func (s *Seekret) GroupObjectsByPrimaryKeyHash() map[string][]models.Object {
return models.GroupObjectsByPrimaryKeyHash(s.objectList)
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/deploymentmanifest.go#L110-L118
|
func (s *DeploymentManifest) AddRemoteStemcell(os, alias, ver, url, sha1 string) {
s.Stemcells = append(s.Stemcells, Stemcell{
OS: os,
Alias: alias,
Version: ver,
URL: url,
SHA1: sha1,
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1235-L1237
|
func (p *SetAttributeValueParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetAttributeValue, p, nil)
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L204-L221
|
func listDirs(dir string) ([]string, []error) {
var dirs []string
var errs []error
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
errs = append(errs, err)
return nil
}
if info.IsDir() {
dirs = append(dirs, path)
}
return nil
})
if err != nil {
errs = append(errs, err)
}
return dirs, errs
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5288-L5292
|
func (v *EventPseudoElementAdded) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom59(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L177-L181
|
func (v *SetPlaybackRateParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation1(&r, v)
return r.Error()
}
|
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L77-L81
|
func PrintRow(fields []string, row map[string]interface{}) {
table := New(fields)
table.AddRow(row)
table.Print()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/types.go#L101-L115
|
func (t *OrientationType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch OrientationType(in.String()) {
case OrientationTypePortraitPrimary:
*t = OrientationTypePortraitPrimary
case OrientationTypePortraitSecondary:
*t = OrientationTypePortraitSecondary
case OrientationTypeLandscapePrimary:
*t = OrientationTypeLandscapePrimary
case OrientationTypeLandscapeSecondary:
*t = OrientationTypeLandscapeSecondary
default:
in.AddError(errors.New("unknown OrientationType value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L106-L116
|
func (t *StreamCompression) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch StreamCompression(in.String()) {
case StreamCompressionNone:
*t = StreamCompressionNone
case StreamCompressionGzip:
*t = StreamCompressionGzip
default:
in.AddError(errors.New("unknown StreamCompression value"))
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L166-L178
|
func (ref ociReference) getIndex() (*imgspecv1.Index, error) {
indexJSON, err := os.Open(ref.indexPath())
if err != nil {
return nil, err
}
defer indexJSON.Close()
index := &imgspecv1.Index{}
if err := json.NewDecoder(indexJSON).Decode(index); err != nil {
return nil, err
}
return index, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/git.go#L246-L261
|
func (r *Repo) Merge(commitlike string) (bool, error) {
r.logger.Infof("Merging %s.", commitlike)
co := r.gitCommand("merge", "--no-ff", "--no-stat", "-m merge", commitlike)
b, err := co.CombinedOutput()
if err == nil {
return true, nil
}
r.logger.WithError(err).Infof("Merge failed with output: %s", string(b))
if b, err := r.gitCommand("merge", "--abort").CombinedOutput(); err != nil {
return false, fmt.Errorf("error aborting merge for commitlike %s: %v. output: %s", commitlike, err, string(b))
}
return false, nil
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/format.go#L409-L414
|
func (bf *backendFormatter) Log(level Level, calldepth int, r *Record) error {
// Make a shallow copy of the record and replace any formatter
r2 := *r
r2.formatter = bf.f
return bf.b.Log(level, calldepth+1, &r2)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L164-L166
|
func (p *StartTypeProfileParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStartTypeProfile, nil, nil)
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L408-L414
|
func ToFloat32Or(s string, defaultValue float32) float32 {
f, err := strconv.ParseFloat(s, 32)
if err != nil {
return defaultValue
}
return float32(f)
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L524-L537
|
func (s *Snapshot) Encode(buf []byte, w io.Writer) error {
l := 4
if len(buf) < l {
return errNotEnoughSpace
}
binary.BigEndian.PutUint32(buf[0:4], s.sn)
if _, err := w.Write(buf[0:4]); err != nil {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L333-L335
|
func (t *ButtonType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L35-L37
|
func (p *ActivateTargetParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandActivateTarget, p, nil)
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L868-L873
|
func (db *DB) sizeFromTag(field *reflect.StructField) (size uint64, err error) {
if s := field.Tag.Get(dbSizeTag); s != "" {
size, err = strconv.ParseUint(s, 10, 64)
}
return size, err
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/http.go#L35-L57
|
func (l *HTTPTemplateFetcher) FetchTemplate(path string) (TemplateSource, error) {
u, err := url.Parse(path)
if err != nil {
return nil, fmt.Errorf("error parsing given path as url: %s", err)
}
if u.IsAbs() {
return nil, ErrAbsolutePathNotAllowed
}
// XXX Consider caching!
for _, base := range l.URLs {
u := base + "/" + path
res, err := http.Get(u)
if err != nil {
continue
}
return NewHTTPSource(res)
}
return nil, ErrTemplateNotFound
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L155-L158
|
func (p CallFunctionOnParams) WithExecutionContextID(executionContextID ExecutionContextID) *CallFunctionOnParams {
p.ExecutionContextID = executionContextID
return &p
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L212-L221
|
func (c Client) StreamContext(ctx context.Context, method, path string, query url.Values, body io.Reader, accept []string) (data io.ReadCloser, contentType string, err error) {
resp, err := c.RequestContext(ctx, method, path, query, body, accept)
if err != nil {
return
}
contentType = resp.Header.Get("Content-Type")
data = resp.Body
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1378-L1399
|
func (c *Client) GetBranches(org, repo string, onlyProtected bool) ([]Branch, error) {
c.log("GetBranches", org, repo)
var branches []Branch
err := c.readPaginatedResultsWithValues(
fmt.Sprintf("/repos/%s/%s/branches", org, repo),
url.Values{
"protected": []string{strconv.FormatBool(onlyProtected)},
"per_page": []string{"100"},
},
acceptNone,
func() interface{} { // newObj
return &[]Branch{}
},
func(obj interface{}) {
branches = append(branches, *(obj.(*[]Branch))...)
},
)
if err != nil {
return nil, err
}
return branches, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2http/client.go#L370-L551
|
func parseKeyRequest(r *http.Request, clock clockwork.Clock) (etcdserverpb.Request, bool, error) {
var noValueOnSuccess bool
emptyReq := etcdserverpb.Request{}
err := r.ParseForm()
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidForm,
err.Error(),
)
}
if !strings.HasPrefix(r.URL.Path, keysPrefix) {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidForm,
"incorrect key prefix",
)
}
p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
var pIdx, wIdx uint64
if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeIndexNaN,
`invalid value for "prevIndex"`,
)
}
if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeIndexNaN,
`invalid value for "waitIndex"`,
)
}
var rec, sort, wait, dir, quorum, stream bool
if rec, err = getBool(r.Form, "recursive"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "recursive"`,
)
}
if sort, err = getBool(r.Form, "sorted"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "sorted"`,
)
}
if wait, err = getBool(r.Form, "wait"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "wait"`,
)
}
// TODO(jonboulle): define what parameters dir is/isn't compatible with?
if dir, err = getBool(r.Form, "dir"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "dir"`,
)
}
if quorum, err = getBool(r.Form, "quorum"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "quorum"`,
)
}
if stream, err = getBool(r.Form, "stream"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "stream"`,
)
}
if wait && r.Method != "GET" {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`"wait" can only be used with GET requests`,
)
}
pV := r.FormValue("prevValue")
if _, ok := r.Form["prevValue"]; ok && pV == "" {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodePrevValueRequired,
`"prevValue" cannot be empty`,
)
}
if noValueOnSuccess, err = getBool(r.Form, "noValueOnSuccess"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "noValueOnSuccess"`,
)
}
// TTL is nullable, so leave it null if not specified
// or an empty string
var ttl *uint64
if len(r.FormValue("ttl")) > 0 {
i, err := getUint64(r.Form, "ttl")
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeTTLNaN,
`invalid value for "ttl"`,
)
}
ttl = &i
}
// prevExist is nullable, so leave it null if not specified
var pe *bool
if _, ok := r.Form["prevExist"]; ok {
bv, err := getBool(r.Form, "prevExist")
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
"invalid value for prevExist",
)
}
pe = &bv
}
// refresh is nullable, so leave it null if not specified
var refresh *bool
if _, ok := r.Form["refresh"]; ok {
bv, err := getBool(r.Form, "refresh")
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
"invalid value for refresh",
)
}
refresh = &bv
if refresh != nil && *refresh {
val := r.FormValue("value")
if _, ok := r.Form["value"]; ok && val != "" {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeRefreshValue,
`A value was provided on a refresh`,
)
}
if ttl == nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeRefreshTTLRequired,
`No TTL value set`,
)
}
}
}
rr := etcdserverpb.Request{
Method: r.Method,
Path: p,
Val: r.FormValue("value"),
Dir: dir,
PrevValue: pV,
PrevIndex: pIdx,
PrevExist: pe,
Wait: wait,
Since: wIdx,
Recursive: rec,
Sorted: sort,
Quorum: quorum,
Stream: stream,
}
if pe != nil {
rr.PrevExist = pe
}
if refresh != nil {
rr.Refresh = refresh
}
// Null TTL is equivalent to unset Expiration
if ttl != nil {
expr := time.Duration(*ttl) * time.Second
rr.Expiration = clock.Now().Add(expr).UnixNano()
}
return rr, noValueOnSuccess, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L1072-L1076
|
func (v *MakeSnapshotReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree10(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L283-L309
|
func BranchRequirements(org, repo, branch string, presubmits map[string][]Presubmit) ([]string, []string, []string) {
jobs, ok := presubmits[org+"/"+repo]
if !ok {
return nil, nil, nil
}
var required, requiredIfPresent, optional []string
for _, j := range jobs {
if !j.CouldRun(branch) {
continue
}
if j.ContextRequired() {
if j.TriggersConditionally() {
// jobs that trigger conditionally cannot be
// required as their status may not exist on PRs
requiredIfPresent = append(requiredIfPresent, j.Context)
} else {
// jobs that produce required contexts and will
// always run should be required at all times
required = append(required, j.Context)
}
} else {
optional = append(optional, j.Context)
}
}
return required, requiredIfPresent, optional
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/types.go#L169-L171
|
func (t *PermissionType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/charsets.go#L305-L311
|
func FindCharsetInHTML(html string) string {
charsetMatches := metaTagCharsetRegexp.FindAllStringSubmatch(html, -1)
if len(charsetMatches) > 0 {
return charsetMatches[0][metaTagCharsetIndex]
}
return ""
}
|
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L84-L91
|
func (m *Message) Finish() {
if m.Complete() {
panic("(*Message).Finish or (*Message).Requeue has already been called")
}
defer func() { recover() }() // the connection may have been closed asynchronously
m.cmdChan <- Fin{MessageID: m.ID}
m.cmdChan = nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L159-L161
|
func (p *InsertTextParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandInsertText, p, nil)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L295-L304
|
func GetRows(arr Arr, submat *Mat, start_row, end_row, delta_row int) *Mat {
mat_new := C.cvGetRows(
unsafe.Pointer(arr),
(*C.CvMat)(submat),
C.int(start_row),
C.int(end_row),
C.int(delta_row),
)
return (*Mat)(mat_new)
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/jsonp.go#L94-L97
|
func (w *jsonpResponseWriter) CloseNotify() <-chan bool {
notifier := w.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
|
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/role.go#L75-L84
|
func (role *Role) MatchedRoles(req *http.Request, user interface{}) (roles []string) {
if definitions := role.definitions; definitions != nil {
for name, definition := range definitions {
if definition(req, user) {
roles = append(roles, name)
}
}
}
return
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/builder.go#L186-L200
|
func (b *Builder) blockIndex() []byte {
// Store the end offset, so we know the length of the final block.
b.restarts = append(b.restarts, uint32(b.buf.Len()))
// Add 4 because we want to write out number of restarts at the end.
sz := 4*len(b.restarts) + 4
out := make([]byte, sz)
buf := out
for _, r := range b.restarts {
binary.BigEndian.PutUint32(buf[:4], r)
buf = buf[4:]
}
binary.BigEndian.PutUint32(buf[:4], uint32(len(b.restarts)))
return out
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/allow_trust.go#L56-L75
|
func (m AllowTrustAsset) MutateAllowTrust(o *xdr.AllowTrustOp) (err error) {
length := len(m.Code)
switch {
case length >= 1 && length <= 4:
var code [4]byte
byteArray := []byte(m.Code)
copy(code[:], byteArray[0:length])
o.Asset, err = xdr.NewAllowTrustOpAsset(xdr.AssetTypeAssetTypeCreditAlphanum4, code)
case length >= 5 && length <= 12:
var code [12]byte
byteArray := []byte(m.Code)
copy(code[:], byteArray[0:length])
o.Asset, err = xdr.NewAllowTrustOpAsset(xdr.AssetTypeAssetTypeCreditAlphanum12, code)
default:
err = errors.New("Asset code length is invalid")
}
return
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/item.go#L52-L56
|
func CompareBytes(this, that unsafe.Pointer) int {
thisItem := (*byteKeyItem)(this)
thatItem := (*byteKeyItem)(that)
return bytes.Compare([]byte(*thisItem), []byte(*thatItem))
}
|
https://github.com/grokify/go-scim-client/blob/800878015236174e45b05db1ec125aae20a093e4/api_client.go#L56-L70
|
func NewAPIClient(cfg *Configuration) *APIClient {
if cfg.HTTPClient == nil {
cfg.HTTPClient = http.DefaultClient
}
c := &APIClient{}
c.cfg = cfg
c.common.client = c
// API Services
c.ServiceProviderConfigApi = (*ServiceProviderConfigApiService)(&c.common)
c.UserApi = (*UserApiService)(&c.common)
return c
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2544-L2551
|
func (u CreateAccountResult) ArmForSwitch(sw int32) (string, bool) {
switch CreateAccountResultCode(sw) {
case CreateAccountResultCodeCreateAccountSuccess:
return "", true
default:
return "", true
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/lease_command.go#L119-L132
|
func leaseTimeToLiveCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("lease timetolive command needs lease ID as argument"))
}
var opts []v3.LeaseOption
if timeToLiveKeys {
opts = append(opts, v3.WithAttachedKeys())
}
resp, rerr := mustClientFromCmd(cmd).TimeToLive(context.TODO(), leaseFromArgs(args[0]), opts...)
if rerr != nil {
ExitWithError(ExitBadConnection, rerr)
}
display.TimeToLive(*resp, timeToLiveKeys)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3lock/v3lockpb/gw/v3lock.pb.gw.go#L94-L155
|
func RegisterLockHandlerClient(ctx context.Context, mux *runtime.ServeMux, client v3lockpb.LockClient) error {
mux.Handle("POST", pattern_Lock_Lock_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Lock_Lock_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Lock_Lock_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Lock_Unlock_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Lock_Unlock_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Lock_Unlock_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L148-L160
|
func (o *oracle) hasConflict(txn *Txn) bool {
if len(txn.reads) == 0 {
return false
}
for _, ro := range txn.reads {
// A commit at the read timestamp is expected.
// But, any commit after the read timestamp should cause a conflict.
if ts, has := o.commits[ro]; has && ts > txn.readTs {
return true
}
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5921-L5925
|
func (v EventCharacterDataModified) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom66(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L99-L105
|
func New() *Map {
return &Map{
m: C.mapnik_map(C.uint(800), C.uint(600)),
width: 800,
height: 600,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5110-L5114
|
func (v *EventSetChildNodes) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom57(&r, v)
return r.Error()
}
|
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L355-L360
|
func (l *slog) Debug(args ...interface{}) {
lvl := l.Level()
if lvl <= LevelDebug {
l.b.print("DBG", l.tag, args...)
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1816-L1829
|
func (r *ProtocolLXD) RenameContainerBackup(containerName string, name string, backup api.ContainerBackupPost) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/backups/%s",
url.QueryEscape(containerName), url.QueryEscape(name)), backup, "")
if err != nil {
return nil, err
}
return op, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2658-L2676
|
func (c *Client) GetProjectColumns(projectID int) ([]ProjectColumn, error) {
c.log("GetProjectColumns", projectID)
path := (fmt.Sprintf("/projects/%d/columns", projectID))
var projectColumns []ProjectColumn
err := c.readPaginatedResults(
path,
"application/vnd.github.inertia-preview+json",
func() interface{} {
return &[]ProjectColumn{}
},
func(obj interface{}) {
projectColumns = append(projectColumns, *(obj.(*[]ProjectColumn))...)
},
)
if err != nil {
return nil, err
}
return projectColumns, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L176-L178
|
func (t DialogType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L172-L181
|
func GetPathParts(path string) (dirPath, fileName, absPath string) {
lookup, lookupErr := exec.LookPath(path)
if lookupErr == nil {
path = lookup
}
absPath, _ = filepath.Abs(path)
dirPath = filepath.Dir(absPath)
fileName = filepath.Base(absPath)
return
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L190-L192
|
func (la *LogAdapter) Warningf(msg string, a ...interface{}) error {
return la.Log(LevelWarning, nil, msg, a...)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L317-L331
|
func (c APIClient) CreateBranch(repoName string, branch string, commit string, provenance []*pfs.Branch) error {
var head *pfs.Commit
if commit != "" {
head = NewCommit(repoName, commit)
}
_, err := c.PfsAPIClient.CreateBranch(
c.Ctx(),
&pfs.CreateBranchRequest{
Branch: NewBranch(repoName, branch),
Head: head,
Provenance: provenance,
},
)
return grpcutil.ScrubGRPC(err)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L526-L528
|
func (t SetWebLifecycleStateState) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/wood/error_reporter.go#L17-L23
|
func NewErrorReporter(out io.Writer) func(error) {
return func(err error) {
_, _ = fmt.Fprintf(out, "===> Begin Error: %s\n", err.Error())
_, _ = out.Write(debug.Stack())
_, _ = fmt.Fprintln(out, "<=== End Error")
}
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/int.go#L85-L95
|
func (i *Int) UnmarshalText(text []byte) error {
str := string(text)
if str == "" || str == "null" {
i.Valid = false
return nil
}
var err error
i.Int64, err = strconv.ParseInt(string(text), 10, 64)
i.Valid = err == nil
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/plank/main.go#L180-L183
|
func serve() {
http.Handle("/metrics", promhttp.Handler())
logrus.WithError(http.ListenAndServe(":8080", nil)).Fatal("ListenAndServe returned.")
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/tchooks.go#L114-L118
|
func (hooks *Hooks) ListHooks(hookGroupId string) (*HookList, error) {
cd := tcclient.Client(*hooks)
responseObject, _, err := (&cd).APICall(nil, "GET", "/hooks/"+url.QueryEscape(hookGroupId), new(HookList), nil)
return responseObject.(*HookList), err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L673-L677
|
func (v Event) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBackgroundservice6(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2261-L2270
|
func (u Memo) GetText() (result string, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Text" {
result = *u.Text
ok = true
}
return
}
|
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/req.go#L29-L56
|
func (c Req) Write(w *bufio.Writer) (err error) {
if _, err = w.WriteString("REQ "); err != nil {
err = errors.Wrap(err, "writing REQ command")
return
}
if _, err = c.MessageID.WriteTo(w); err != nil {
err = errors.Wrap(err, "writing REQ message ID")
return
}
if err = w.WriteByte(' '); err != nil {
err = errors.Wrap(err, "writing REQ command")
return
}
if _, err = w.WriteString(strconv.FormatUint(uint64(c.Timeout/time.Millisecond), 10)); err != nil {
err = errors.Wrap(err, "writing REQ timeout")
return
}
if err = w.WriteByte('\n'); err != nil {
err = errors.Wrap(err, "writing REQ command")
return
}
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/selective_string.go#L61-L67
|
func NewSelectiveStringValue(valids ...string) *SelectiveStringValue {
vm := make(map[string]struct{})
for _, v := range valids {
vm[v] = struct{}{}
}
return &SelectiveStringValue{valids: vm, v: valids[0]}
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/gopher2/gopher2.go#L35-L122
|
func Draw(gc draw2d.GraphicContext, x, y, w, h float64) {
h23 := (h * 2) / 3
blf := color.RGBA{0, 0, 0, 0xff} // black
wf := color.RGBA{0xff, 0xff, 0xff, 0xff} // white
nf := color.RGBA{0x8B, 0x45, 0x13, 0xff} // brown opaque
brf := color.RGBA{0x8B, 0x45, 0x13, 0x99} // brown transparant
brb := color.RGBA{0x8B, 0x45, 0x13, 0xBB} // brown transparant
// round head top
gc.MoveTo(x, y+h*1.002)
gc.CubicCurveTo(x+w/4, y-h/3, x+3*w/4, y-h/3, x+w, y+h*1.002)
gc.Close()
gc.SetFillColor(brb)
gc.Fill()
// rectangle head bottom
draw2dkit.RoundedRectangle(gc, x, y+h, x+w, y+h+h, h/5, h/5)
gc.Fill()
// left ear outside
draw2dkit.Circle(gc, x, y+h, w/12)
gc.SetFillColor(brf)
gc.Fill()
// left ear inside
draw2dkit.Circle(gc, x, y+h, 0.5*w/12)
gc.SetFillColor(nf)
gc.Fill()
// right ear outside
draw2dkit.Circle(gc, x+w, y+h, w/12)
gc.SetFillColor(brf)
gc.Fill()
// right ear inside
draw2dkit.Circle(gc, x+w, y+h, 0.5*w/12)
gc.SetFillColor(nf)
gc.Fill()
// left eye outside white
draw2dkit.Circle(gc, x+w/3, y+h23, w/9)
gc.SetFillColor(wf)
gc.Fill()
// left eye black
draw2dkit.Circle(gc, x+w/3+w/24, y+h23, 0.5*w/9)
gc.SetFillColor(blf)
gc.Fill()
// left eye inside white
draw2dkit.Circle(gc, x+w/3+w/24+w/48, y+h23, 0.2*w/9)
gc.SetFillColor(wf)
gc.Fill()
// right eye outside white
draw2dkit.Circle(gc, x+w-w/3, y+h23, w/9)
gc.Fill()
// right eye black
draw2dkit.Circle(gc, x+w-w/3+w/24, y+h23, 0.5*w/9)
gc.SetFillColor(blf)
gc.Fill()
// right eye inside white
draw2dkit.Circle(gc, x+w-(w/3)+w/24+w/48, y+h23, 0.2*w/9)
gc.SetFillColor(wf)
gc.Fill()
// left tooth
gc.SetFillColor(wf)
draw2dkit.RoundedRectangle(gc, x+w/2-w/8, y+h+h/2.5, x+w/2-w/8+w/8, y+h+h/2.5+w/6, w/10, w/10)
gc.Fill()
// right tooth
draw2dkit.RoundedRectangle(gc, x+w/2, y+h+h/2.5, x+w/2+w/8, y+h+h/2.5+w/6, w/10, w/10)
gc.Fill()
// snout
draw2dkit.Ellipse(gc, x+(w/2), y+h+h/2.5, w/6, w/12)
gc.SetFillColor(nf)
gc.Fill()
// nose
draw2dkit.Ellipse(gc, x+(w/2), y+h+h/7, w/10, w/12)
gc.SetFillColor(blf)
gc.Fill()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L120-L122
|
func (r *ProtocolLXD) RawWebsocket(path string) (*websocket.Conn, error) {
return r.websocket(path)
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/mux/provider/user_service.go#L45-L76
|
func UserLogin(w http.ResponseWriter, r *http.Request) {
var login types.LoginRequest
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Api-Correlation-Id", "1234")
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
err = json.Unmarshal(body, &login)
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
user, err := userRepository.ByUsername(login.Username)
if err != nil {
w.WriteHeader(http.StatusNotFound)
} else if user.Username != login.Username || user.Password != login.Password {
w.WriteHeader(http.StatusUnauthorized)
} else {
w.Header().Set("X-Auth-Token", getAuthToken())
w.WriteHeader(http.StatusOK)
res := types.LoginResponse{User: user}
resBody, _ := json.Marshal(res)
w.Write(resBody)
}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L161-L163
|
func (s *selectable) AllByLabel(text string) *MultiSelection {
return newMultiSelection(s.session, s.selectors.Append(target.Label, text))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1129-L1133
|
func (v *SetDocumentContentParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage12(&r, v)
return r.Error()
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/method_override.go#L15-L21
|
func MethodOverride(res http.ResponseWriter, req *http.Request) {
if req.Method == "POST" {
req.Method = defaults.String(req.FormValue("_method"), "POST")
req.Form.Del("_method")
req.PostForm.Del("_method")
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/examples/keyvalue/server/server.go#L91-L104
|
func (h *kvHandler) Get(ctx thrift.Context, key string) (string, error) {
if err := isValidKey(key); err != nil {
return "", err
}
h.RLock()
defer h.RUnlock()
if val, ok := h.vals[key]; ok {
return val, nil
}
return "", &keyvalue.KeyNotFound{Key: key}
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L77-L204
|
func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out textNode) {
if !v.IsValid() {
return nil
}
t := v.Type()
// Check whether there is an Error or String method to call.
if !opts.AvoidStringer && v.CanInterface() {
// Avoid calling Error or String methods on nil receivers since many
// implementations crash when doing so.
if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() {
switch v := v.Interface().(type) {
case error:
return textLine("e" + formatString(v.Error()))
case fmt.Stringer:
return textLine("s" + formatString(v.String()))
}
}
}
// Check whether to explicitly wrap the result with the type.
var skipType bool
defer func() {
if !skipType {
out = opts.FormatType(t, out)
}
}()
var ptr string
switch t.Kind() {
case reflect.Bool:
return textLine(fmt.Sprint(v.Bool()))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return textLine(fmt.Sprint(v.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
// Unnamed uints are usually bytes or words, so use hexadecimal.
if t.PkgPath() == "" || t.Kind() == reflect.Uintptr {
return textLine(formatHex(v.Uint()))
}
return textLine(fmt.Sprint(v.Uint()))
case reflect.Float32, reflect.Float64:
return textLine(fmt.Sprint(v.Float()))
case reflect.Complex64, reflect.Complex128:
return textLine(fmt.Sprint(v.Complex()))
case reflect.String:
return textLine(formatString(v.String()))
case reflect.UnsafePointer, reflect.Chan, reflect.Func:
return textLine(formatPointer(v))
case reflect.Struct:
var list textList
for i := 0; i < v.NumField(); i++ {
vv := v.Field(i)
if value.IsZero(vv) {
continue // Elide fields with zero values
}
s := opts.WithTypeMode(autoType).FormatValue(vv, m)
list = append(list, textRecord{Key: t.Field(i).Name, Value: s})
}
return textWrap{"{", list, "}"}
case reflect.Slice:
if v.IsNil() {
return textNil
}
if opts.PrintAddresses {
ptr = formatPointer(v)
}
fallthrough
case reflect.Array:
var list textList
for i := 0; i < v.Len(); i++ {
vi := v.Index(i)
if vi.CanAddr() { // Check for cyclic elements
p := vi.Addr()
if m.Visit(p) {
var out textNode
out = textLine(formatPointer(p))
out = opts.WithTypeMode(emitType).FormatType(p.Type(), out)
out = textWrap{"*", out, ""}
list = append(list, textRecord{Value: out})
continue
}
}
s := opts.WithTypeMode(elideType).FormatValue(vi, m)
list = append(list, textRecord{Value: s})
}
return textWrap{ptr + "{", list, "}"}
case reflect.Map:
if v.IsNil() {
return textNil
}
if m.Visit(v) {
return textLine(formatPointer(v))
}
var list textList
for _, k := range value.SortKeys(v.MapKeys()) {
sk := formatMapKey(k)
sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), m)
list = append(list, textRecord{Key: sk, Value: sv})
}
if opts.PrintAddresses {
ptr = formatPointer(v)
}
return textWrap{ptr + "{", list, "}"}
case reflect.Ptr:
if v.IsNil() {
return textNil
}
if m.Visit(v) || opts.ShallowPointers {
return textLine(formatPointer(v))
}
if opts.PrintAddresses {
ptr = formatPointer(v)
}
skipType = true // Let the underlying value print the type instead
return textWrap{"&" + ptr, opts.FormatValue(v.Elem(), m), ""}
case reflect.Interface:
if v.IsNil() {
return textNil
}
// Interfaces accept different concrete types,
// so configure the underlying value to explicitly print the type.
skipType = true // Print the concrete type instead
return opts.WithTypeMode(emitType).FormatValue(v.Elem(), m)
default:
panic(fmt.Sprintf("%v kind not handled", v.Kind()))
}
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L150-L154
|
func (receiver *gobTCPReceiver) Receive() ([]byte, error) {
var msg []byte
err := receiver.decoder.Decode(&msg)
return msg, err
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/json_indent.go#L54-L60
|
func (w *jsonIndentResponseWriter) EncodeJson(v interface{}) ([]byte, error) {
b, err := json.MarshalIndent(v, w.prefix, w.indent)
if err != nil {
return nil, err
}
return b, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L883-L908
|
func getTextColor(backgroundColor string) (string, error) {
d, err := hex.DecodeString(backgroundColor)
if err != nil || len(d) != 3 {
return "", errors.New("expect 6-digit color hex of label")
}
// Calculate the relative luminance (L) of a color
// L = 0.2126 * R + 0.7152 * G + 0.0722 * B
// Formula details at: https://www.w3.org/TR/WCAG20/#relativeluminancedef
color := [3]float64{}
for i, v := range d {
color[i] = float64(v) / 255.0
if color[i] <= 0.03928 {
color[i] = color[i] / 12.92
} else {
color[i] = math.Pow((color[i]+0.055)/1.055, 2.4)
}
}
L := 0.2126*color[0] + 0.7152*color[1] + 0.0722*color[2]
if (L+0.05)/(0.0+0.05) > (1.0+0.05)/(L+0.05) {
return "000000", nil
} else {
return "ffffff", nil
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/backend.go#L68-L97
|
func openBackend(cfg ServerConfig) backend.Backend {
fn := cfg.backendPath()
now, beOpened := time.Now(), make(chan backend.Backend)
go func() {
beOpened <- newBackend(cfg)
}()
select {
case be := <-beOpened:
if cfg.Logger != nil {
cfg.Logger.Info("opened backend db", zap.String("path", fn), zap.Duration("took", time.Since(now)))
}
return be
case <-time.After(10 * time.Second):
if cfg.Logger != nil {
cfg.Logger.Info(
"db file is flocked by another process, or taking too long",
zap.String("path", fn),
zap.Duration("took", time.Since(now)),
)
} else {
plog.Warningf("another etcd process is using %q and holds the file lock, or loading backend file is taking >10 seconds", fn)
plog.Warningf("waiting for it to exit before starting...")
}
}
return <-beOpened
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1278-L1282
|
func (v SetDefaultBackgroundColorOverrideParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/s3util/open.go#L13-L33
|
func Open(url string, c *Config) (io.ReadCloser, error) {
if c == nil {
c = DefaultConfig
}
// TODO(kr): maybe parallel range fetching
r, _ := http.NewRequest("GET", url, nil)
r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
c.Sign(r, *c.Keys)
client := c.Client
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, newRespError(resp)
}
return resp.Body, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L3511-L3515
|
func (v ResourceTiming) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork23(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/transforms.go#L29-L79
|
func MonoRMS(b *audio.FloatBuffer, windowSize int) error {
if b == nil {
return audio.ErrInvalidBuffer
}
if len(b.Data) == 0 {
return nil
}
out := []float64{}
winBuf := make([]float64, windowSize)
windowSizeF := float64(windowSize)
processWindow := func(idx int) {
total := 0.0
for i := 0; i < len(winBuf); i++ {
total += winBuf[idx] * winBuf[idx]
}
v := math.Sqrt((1.0 / windowSizeF) * total)
out = append(out, v)
}
nbrChans := 1
if b.Format != nil {
nbrChans = b.Format.NumChannels
}
var windowIDX int
// process each frame, convert it to mono and them RMS it
for i := 0; i < len(b.Data); i++ {
v := b.Data[i]
if nbrChans > 1 {
for j := 1; j < nbrChans; j++ {
i++
v += b.Data[i]
}
v /= float64(nbrChans)
}
winBuf[windowIDX] = v
windowIDX++
if windowIDX == windowSize || i == (len(b.Data)-1) {
windowIDX = 0
processWindow(windowIDX)
}
}
if b.Format != nil {
b.Format.NumChannels = 1
b.Format.SampleRate /= windowSize
}
b.Data = out
return nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L59-L82
|
func NewRouter(config Config, name PeerName, nickName string, overlay Overlay, logger Logger) (*Router, error) {
router := &Router{Config: config, gossipChannels: make(gossipChannels)}
if overlay == nil {
overlay = NullOverlay{}
}
router.Overlay = overlay
router.Ourself = newLocalPeer(name, nickName, router)
router.Peers = newPeers(router.Ourself)
router.Peers.OnGC(func(peer *Peer) {
logger.Printf("Removed unreachable peer %s", peer)
})
router.Routes = newRoutes(router.Ourself, router.Peers)
router.ConnectionMaker = newConnectionMaker(router.Ourself, router.Peers, net.JoinHostPort(router.Host, "0"), router.Port, router.PeerDiscovery, logger)
router.logger = logger
gossip, err := router.NewGossip("topology", router)
if err != nil {
return nil, err
}
router.topologyGossip = gossip
router.acceptLimiter = newTokenBucket(acceptMaxTokens, acceptTokenDelay)
return router, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/smtp.go#L195-L203
|
func (d *Dialer) DialAndSend(m ...*Message) error {
s, err := d.Dial()
if err != nil {
return err
}
defer s.Close()
return Send(s, m...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L287-L296
|
func (p *GetScriptSourceParams) Do(ctx context.Context) (scriptSource string, err error) {
// execute
var res GetScriptSourceReturns
err = cdp.Execute(ctx, CommandGetScriptSource, p, &res)
if err != nil {
return "", err
}
return res.ScriptSource, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L603-L606
|
func (e LedgerEntryType) ValidEnum(v int32) bool {
_, ok := ledgerEntryTypeMap[v]
return ok
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.