_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L495-L497
|
func (b *Base) Errorf(msg string, a ...interface{}) error {
return b.Log(LevelError, nil, msg, a...)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L429-L439
|
func (c *APIClient) Close() error {
if err := c.clientConn.Close(); err != nil {
return err
}
if c.portForwarder != nil {
c.portForwarder.Close()
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L479-L482
|
func (p SearchInContentParams) WithIsRegex(isRegex bool) *SearchInContentParams {
p.IsRegex = isRegex
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L851-L855
|
func (v *GetTargetInfoReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget8(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L34-L52
|
func (r *ProtocolLXD) GetOperations() ([]api.Operation, error) {
apiOperations := map[string][]api.Operation{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/operations?recursion=1", nil, "", &apiOperations)
if err != nil {
return nil, err
}
// Turn it into just a list of operations
operations := []api.Operation{}
for _, v := range apiOperations {
for _, operation := range v {
operations = append(operations, operation)
}
}
return operations, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L144-L173
|
func (p *ProgressRenderer) Warn(status string, timeout time.Duration) {
// Acquire rendering lock
p.lock.Lock()
defer p.lock.Unlock()
// Check if we're already done
if p.done {
return
}
// Render the new message
p.wait = time.Now().Add(timeout)
msg := fmt.Sprintf("%s", status)
// Truncate msg to terminal length
msg = "\r" + p.truncate(msg)
// Don't print if empty and never printed
if len(msg) == 1 && p.maxLength == 0 {
return
}
if len(msg) > p.maxLength {
p.maxLength = len(msg)
} else {
fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength))
}
fmt.Print(msg)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/abort.go#L48-L50
|
func (i *jobIndentifier) String() string {
return fmt.Sprintf("%s %s/%s#%d", i.job, i.organization, i.repository, i.pullRequest)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1591-L1595
|
func (v *Log) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar8(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L2208-L2212
|
func (v *DocumentSnapshot) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot10(&r, v)
return r.Error()
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L606-L608
|
func FindSequenceOnDisk(pattern *C.char) (FileSeqId, Error) {
return FindSequenceOnDiskPad(pattern, C.int(fileseq.PadStyleDefault))
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/pkg/tgzwalker.go#L17-L22
|
func NewTgzWalker(pkgReader io.Reader) Walker {
return tgzWalker{
pkgReader: pkgReader,
callbacks: make(map[*regexp.Regexp]WalkFunc),
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L110-L119
|
func (c *SubChannel) Register(h Handler, methodName string) {
handlers, ok := c.handler.(*handlerMap)
if !ok {
panic(fmt.Sprintf(
"handler for SubChannel(%v) was changed to disallow method registration",
c.ServiceName(),
))
}
handlers.register(h, methodName)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L233-L254
|
func (s *openshiftImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) {
var imageName string
if instanceDigest == nil {
if err := s.ensureImageIsResolved(ctx); err != nil {
return nil, err
}
imageName = s.imageStreamImageName
} else {
imageName = instanceDigest.String()
}
image, err := s.client.getImage(ctx, imageName)
if err != nil {
return nil, err
}
var sigs [][]byte
for _, sig := range image.Signatures {
if sig.Type == imageSignatureTypeAtomic {
sigs = append(sigs, sig.Content)
}
}
return sigs, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1033-L1037
|
func (v *Param) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar4(&r, v)
return r.Error()
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L350-L362
|
func (n *NetworkTransport) returnConn(conn *netConn) {
n.connPoolLock.Lock()
defer n.connPoolLock.Unlock()
key := conn.target
conns, _ := n.connPool[key]
if !n.IsShutdown() && len(conns) < n.maxPool {
n.connPool[key] = append(conns, conn)
} else {
conn.Release()
}
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/rsa.go#L79-L82
|
func (sk *RsaPrivateKey) Sign(message []byte) ([]byte, error) {
hashed := sha256.Sum256(message)
return rsa.SignPKCS1v15(rand.Reader, sk.sk, crypto.SHA256, hashed[:])
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/client/util.go#L40-L45
|
func IsRoleNotFound(err error) bool {
if ae, ok := err.(authError); ok {
return roleNotFoundRegExp.MatchString(ae.Message)
}
return false
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2232-L2251
|
func (c *Client) UpdateTeamRepo(id int, org, repo string, permission RepoPermissionLevel) error {
c.log("UpdateTeamRepo", id, org, repo, permission)
if c.fake || c.dry {
return nil
}
data := struct {
Permission string `json:"permission"`
}{
Permission: string(permission),
}
_, err := c.request(&request{
method: http.MethodPut,
path: fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo),
requestBody: &data,
exitCodes: []int{204},
}, nil)
return err
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L19-L40
|
func NewClientWriter() (*ClientWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"parameters": parameters,
"paramsInitializer": paramsInitializer,
"blankCondition": blankCondition,
"stripStar": stripStar,
}
headerT, err := template.New("header-client").Funcs(funcMap).Parse(headerTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(resourceTmpl)
if err != nil {
return nil, err
}
return &ClientWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L207-L241
|
func (cdc *Codec) RegisterConcrete(o interface{}, name string, copts *ConcreteOptions) {
cdc.assertNotSealed()
var pointerPreferred bool
// Get reflect.Type.
rt := reflect.TypeOf(o)
if rt.Kind() == reflect.Interface {
panic(fmt.Sprintf("expected a non-interface: %v", rt))
}
if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
if rt.Kind() == reflect.Ptr {
// We can encode/decode pointer-pointers, but not register them.
panic(fmt.Sprintf("registering pointer-pointers not yet supported: *%v", rt))
}
if rt.Kind() == reflect.Interface {
// MARKER: No interface-pointers
panic(fmt.Sprintf("registering interface-pointers not yet supported: *%v", rt))
}
pointerPreferred = true
}
// Construct ConcreteInfo.
var info = cdc.newTypeInfoFromRegisteredConcreteType(rt, pointerPreferred, name, copts)
// Finally, check conflicts and register.
func() {
cdc.mtx.Lock()
defer cdc.mtx.Unlock()
cdc.addCheckConflictsWithConcrete_nolock(info)
cdc.setTypeInfo_nolock(info)
}()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L340-L357
|
func RoleBinding(opts *AssetOpts) *rbacv1.RoleBinding {
return &rbacv1.RoleBinding{
TypeMeta: metav1.TypeMeta{
Kind: "RoleBinding",
APIVersion: "rbac.authorization.k8s.io/v1",
},
ObjectMeta: objectMeta(roleBindingName, labels(""), nil, opts.Namespace),
Subjects: []rbacv1.Subject{{
Kind: "ServiceAccount",
Name: ServiceAccountName,
Namespace: opts.Namespace,
}},
RoleRef: rbacv1.RoleRef{
Kind: "Role",
Name: roleName,
},
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L182-L186
|
func (v *GetDatabaseTableNamesParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDatabase1(&r, v)
return r.Error()
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-decode.go#L482-L504
|
func decodeInterfaceJSON(bz []byte) (name string, data []byte, err error) {
dfw := new(disfixWrapper)
err = json.Unmarshal(bz, dfw)
if err != nil {
err = fmt.Errorf("cannot parse disfix JSON wrapper: %v", err)
return
}
// Get name.
if dfw.Name == "" {
err = errors.New("JSON encoding of interfaces require non-empty type field.")
return
}
name = dfw.Name
// Get data.
if len(dfw.Data) == 0 {
err = errors.New("interface JSON wrapper should have non-empty value field")
return
}
data = dfw.Data
return
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L255-L260
|
func (f *File) MacroName() string {
if f.function != nil && f.function.stmt != nil {
return f.function.stmt.Name
}
return ""
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/sys/apparmor.go#L19-L64
|
func (s *OS) initAppArmor() {
/* Detect AppArmor availability */
_, err := exec.LookPath("apparmor_parser")
if os.Getenv("LXD_SECURITY_APPARMOR") == "false" {
logger.Warnf("AppArmor support has been manually disabled")
} else if !shared.IsDir("/sys/kernel/security/apparmor") {
logger.Warnf("AppArmor support has been disabled because of lack of kernel support")
} else if err != nil {
logger.Warnf("AppArmor support has been disabled because 'apparmor_parser' couldn't be found")
} else {
s.AppArmorAvailable = true
}
/* Detect AppArmor stacking support */
s.AppArmorStacking = appArmorCanStack()
/* Detect existing AppArmor stack */
if shared.PathExists("/sys/kernel/security/apparmor/.ns_stacked") {
contentBytes, err := ioutil.ReadFile("/sys/kernel/security/apparmor/.ns_stacked")
if err == nil && string(contentBytes) == "yes\n" {
s.AppArmorStacked = true
}
}
/* Detect AppArmor admin support */
if !haveMacAdmin() {
if s.AppArmorAvailable {
logger.Warnf("Per-container AppArmor profiles are disabled because the mac_admin capability is missing")
}
} else if s.RunningInUserNS && !s.AppArmorStacked {
if s.AppArmorAvailable {
logger.Warnf("Per-container AppArmor profiles are disabled because LXD is running in an unprivileged container without stacking")
}
} else {
s.AppArmorAdmin = true
}
/* Detect AppArmor confinment */
profile := util.AppArmorProfile()
if profile != "unconfined" && profile != "" {
if s.AppArmorAvailable {
logger.Warnf("Per-container AppArmor profiles are disabled because LXD is already protected by AppArmor")
}
s.AppArmorConfined = true
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L231-L276
|
func (c *ClusterTx) ContainersListByNodeAddress(project string) (map[string][]string, error) {
offlineThreshold, err := c.NodeOfflineThreshold()
if err != nil {
return nil, err
}
stmt := `
SELECT containers.name, nodes.id, nodes.address, nodes.heartbeat
FROM containers
JOIN nodes ON nodes.id = containers.node_id
JOIN projects ON projects.id = containers.project_id
WHERE containers.type=?
AND projects.name = ?
ORDER BY containers.id
`
rows, err := c.tx.Query(stmt, CTypeRegular, project)
if err != nil {
return nil, err
}
defer rows.Close()
result := map[string][]string{}
for i := 0; rows.Next(); i++ {
var name string
var nodeAddress string
var nodeID int64
var nodeHeartbeat time.Time
err := rows.Scan(&name, &nodeID, &nodeAddress, &nodeHeartbeat)
if err != nil {
return nil, err
}
if nodeID == c.nodeID {
nodeAddress = ""
} else if nodeIsOffline(offlineThreshold, nodeHeartbeat) {
nodeAddress = "0.0.0.0"
}
result[nodeAddress] = append(result[nodeAddress], name)
}
err = rows.Err()
if err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/endpoint.go#L34-L146
|
func (a *APIAnalyzer) AnalyzeEndpoint(verb string, path string, ep *Endpoint) error {
path = joinPath(a.Doc.BasePath, path)
dbg("\n------\nDEBUG AnalyzeEndpoint %s %s %+v\n", verb, path, ep)
pattern := toPattern(verb, path)
dbg("DEBUG AnalyzeEndpoint pattern %v\n", pattern)
svc := ep.Service()
// Get Resource -- base it on the service name for now
res := a.api.Resources[svc]
if res == nil {
res = &gen.Resource{
Name: svc,
ClientName: a.ClientName,
Actions: []*gen.Action{},
}
a.api.Resources[svc] = res
}
action := &gen.Action{
Name: ep.Method(),
MethodName: toMethodName(ep.Method()),
Description: cleanDescription(ep.Description),
ResourceName: svc,
PathPatterns: []*gen.PathPattern{pattern},
}
res.Actions = append(res.Actions, action)
var returnDT gen.DataType
var hasLocation bool
for code, response := range ep.Responses {
if code >= 300 {
continue
}
if response.Headers != nil {
if _, ok := response.Headers["Location"]; ok {
hasLocation = true
}
}
if response.Schema == nil {
dbg("DEBUG MISSING SCHEMA SKIP!\n")
break
}
dbg("DEBUG AnalyzeEndpoint %d RESPONSE %#v\n", code, response)
returnDef := a.Doc.Ref(response.Schema)
if returnDef != nil {
ec := EvalCtx{IsResult: true, Trail: nil, Svc: res, Method: action}
if mediaType(returnDef.Title) == "" {
warn("Warning: AnalyzeEndpoint: MediaType not set for %s, will be hard to guess the result type\n", response.Schema.ID())
continue
}
returnDT = a.AnalyzeDefinition(ec, returnDef, response.Schema.ID())
if returnObj, ok := returnDT.(*gen.ObjectDataType); ok {
isResourceType := verb == "get" && returnObj.TypeName == svc
dbg("DEBUG AnalyzeEndpoint Path %s Verb %s returnTypeName %s svc %s\n", path, verb, returnObj.TypeName, svc)
if isResourceType {
res.Description = cleanDescription(ep.Description)
res.Identifier = mediaType(returnDef.Title)
}
a.addType(ec, returnObj, response.Schema)
}
} else {
returnDT = basicType(response.Schema.Type())
}
break
}
for _, p := range ep.Parameters {
ec := EvalCtx{IsResult: false, Trail: nil, Svc: res, Method: action}
ap := a.AnalyzeParam(ec, p)
switch p.In {
case "header":
action.HeaderParamNames = append(action.HeaderParamNames, p.Name)
action.Params = append(action.Params, ap)
case "query":
action.QueryParamNames = append(action.QueryParamNames, p.Name)
action.Params = append(action.Params, ap)
case "path":
action.PathParamNames = append(action.PathParamNames, p.Name)
action.Params = append(action.Params, ap)
case "body":
def := a.Doc.Ref(p.Schema)
if def != nil {
if def.Type == "array" {
fail("Array type for body not implemented yet")
} else if def.Type == "object" {
// Flatten the first level of object
dt := a.AnalyzeDefinition(ec, def, p.Schema.ID())
if obj, ok := dt.(*gen.ObjectDataType); ok {
a.addType(ec, obj, p.Schema)
action.Payload = obj
for _, f := range obj.Fields {
action.PayloadParamNames = append(action.PayloadParamNames, f.Name)
action.Params = append(action.Params, f)
}
}
}
}
}
}
if returnDT != nil {
action.Return = signature(returnDT)
}
action.ReturnLocation = hasLocation
dbg("DEBUG ACTION %s", prettify(action))
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/types.go#L375-L405
|
func (g *GCSConfiguration) ApplyDefault(def *GCSConfiguration) *GCSConfiguration {
if g == nil && def == nil {
return nil
}
var merged GCSConfiguration
if g != nil {
merged = *g
} else {
merged = *def
}
if g == nil || def == nil {
return &merged
}
if merged.Bucket == "" {
merged.Bucket = def.Bucket
}
if merged.PathPrefix == "" {
merged.PathPrefix = def.PathPrefix
}
if merged.PathStrategy == "" {
merged.PathStrategy = def.PathStrategy
}
if merged.DefaultOrg == "" {
merged.DefaultOrg = def.DefaultOrg
}
if merged.DefaultRepo == "" {
merged.DefaultRepo = def.DefaultRepo
}
return &merged
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L208-L215
|
func formatMapKey(v reflect.Value) string {
var opts formatOptions
opts.TypeMode = elideType
opts.AvoidStringer = true
opts.ShallowPointers = true
s := opts.FormatValue(v, visitedPointers{}).String()
return strings.TrimSpace(s)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/peribolos/main.go#L533-L555
|
func validateTeamNames(orgConfig org.Config) error {
// Does the config duplicate any team names?
used := sets.String{}
dups := sets.String{}
for name, orgTeam := range orgConfig.Teams {
if used.Has(name) {
dups.Insert(name)
} else {
used.Insert(name)
}
for _, n := range orgTeam.Previously {
if used.Has(n) {
dups.Insert(n)
} else {
used.Insert(n)
}
}
}
if n := len(dups); n > 0 {
return fmt.Errorf("%d duplicated names: %s", n, strings.Join(dups.List(), ", "))
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log_unstable.go#L44-L52
|
func (u *unstable) maybeLastIndex() (uint64, bool) {
if l := len(u.entries); l != 0 {
return u.offset + uint64(l) - 1, true
}
if u.snapshot != nil {
return u.snapshot.Metadata.Index, true
}
return 0, false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1994-L1998
|
func (v *GetBestEffortCoverageReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler19(&r, v)
return r.Error()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L2114-L2116
|
func (api *API) CookbookLocator(href string) *CookbookLocator {
return &CookbookLocator{Href(href), api}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/trigger/pull-request.go#L207-L223
|
func TrustedPullRequest(ghc githubClient, trigger plugins.Trigger, author, org, repo string, num int, l []github.Label) ([]github.Label, bool, error) {
// First check if the author is a member of the org.
if orgMember, err := TrustedUser(ghc, trigger, author, org, repo); err != nil {
return l, false, fmt.Errorf("error checking %s for trust: %v", author, err)
} else if orgMember {
return l, true, nil
}
// Then check if PR has ok-to-test label
if l == nil {
var err error
l, err = ghc.GetIssueLabels(org, repo, num)
if err != nil {
return l, false, err
}
}
return l, github.HasLabel(labels.OkToTest, l), nil
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L442-L445
|
func (s *FileSequence) SetPadding(padChars string) {
s.padChar = padChars
s.zfill = s.padMapper.PaddingCharsSize(padChars)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L83-L92
|
func (l *PeerList) SetStrategy(sc ScoreCalculator) {
l.Lock()
defer l.Unlock()
l.scoreCalculator = sc
for _, ps := range l.peersByHostPort {
newScore := l.scoreCalculator.GetScore(ps.Peer)
l.updatePeer(ps, newScore)
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/message.go#L62-L71
|
func (m *Message) AddBodies(data render.Data, renderers ...render.Renderer) error {
for _, r := range renderers {
err := m.AddBody(r, data)
if err != nil {
return err
}
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/crier/controller.go#L60-L75
|
func NewController(
pjclientset clientset.Interface,
queue workqueue.RateLimitingInterface,
informer pjinformers.ProwJobInformer,
reporter reportClient,
numWorkers int,
wg *sync.WaitGroup) *Controller {
return &Controller{
pjclientset: pjclientset,
queue: queue,
informer: informer,
reporter: reporter,
numWorkers: numWorkers,
wg: wg,
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/cert.go#L29-L34
|
func PublicCertToPEM(cert *tls.Certificate) []byte {
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Certificate[0],
})
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/hmac.go#L27-L40
|
func ValidatePayload(payload []byte, sig string, key []byte) bool {
if !strings.HasPrefix(sig, "sha1=") {
return false
}
sig = sig[5:]
sb, err := hex.DecodeString(sig)
if err != nil {
return false
}
mac := hmac.New(sha1.New, key)
mac.Write(payload)
expected := mac.Sum(nil)
return hmac.Equal(sb, expected)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/typecheck.go#L81-L93
|
func (cfg *TypeConfig) typeof(name string) string {
if cfg.Var != nil {
if t := cfg.Var[name]; t != "" {
return t
}
}
if cfg.Func != nil {
if t := cfg.Func[name]; t != "" {
return "func()" + t
}
}
return ""
}
|
https://github.com/OneOfOne/xxhash/blob/c1e3185f167680b62832a0a11938a04b1ab265fc/xxhash_go17.go#L12-L62
|
func Checksum32S(in []byte, seed uint32) (h uint32) {
var i int
if len(in) > 15 {
var (
v1 = seed + prime32x1 + prime32x2
v2 = seed + prime32x2
v3 = seed + 0
v4 = seed - prime32x1
)
for ; i < len(in)-15; i += 16 {
in := in[i : i+16 : len(in)]
v1 += u32(in[0:4:len(in)]) * prime32x2
v1 = rotl32_13(v1) * prime32x1
v2 += u32(in[4:8:len(in)]) * prime32x2
v2 = rotl32_13(v2) * prime32x1
v3 += u32(in[8:12:len(in)]) * prime32x2
v3 = rotl32_13(v3) * prime32x1
v4 += u32(in[12:16:len(in)]) * prime32x2
v4 = rotl32_13(v4) * prime32x1
}
h = rotl32_1(v1) + rotl32_7(v2) + rotl32_12(v3) + rotl32_18(v4)
} else {
h = seed + prime32x5
}
h += uint32(len(in))
for ; i <= len(in)-4; i += 4 {
in := in[i : i+4 : len(in)]
h += u32(in[0:4:len(in)]) * prime32x3
h = rotl32_17(h) * prime32x4
}
for ; i < len(in); i++ {
h += uint32(in[i]) * prime32x5
h = rotl32_11(h) * prime32x1
}
h ^= h >> 15
h *= prime32x2
h ^= h >> 13
h *= prime32x3
h ^= h >> 16
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approve.go#L315-L329
|
func findAssociatedIssue(body, org string) (int, error) {
associatedIssueRegex, err := regexp.Compile(fmt.Sprintf(associatedIssueRegexFormat, org))
if err != nil {
return 0, err
}
match := associatedIssueRegex.FindStringSubmatch(body)
if len(match) == 0 {
return 0, nil
}
v, err := strconv.Atoi(match[1])
if err != nil {
return 0, err
}
return v, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/permission.go#L149-L175
|
func roleInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
if !(permission.Check(t, permission.PermRoleUpdate) ||
permission.Check(t, permission.PermRoleUpdateAssign) ||
permission.Check(t, permission.PermRoleUpdateDissociate) ||
permission.Check(t, permission.PermRoleCreate) ||
permission.Check(t, permission.PermRoleDelete)) {
return permission.ErrUnauthorized
}
roleName := r.URL.Query().Get(":name")
role, err := permission.FindRole(roleName)
if err == permTypes.ErrRoleNotFound {
return &errors.HTTP{
Code: http.StatusNotFound,
Message: err.Error(),
}
}
if err != nil {
return err
}
b, err := json.Marshal(role)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(b)
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/update.go#L19-L23
|
func Schema() *schema.Schema {
schema := schema.NewFromMap(updates)
schema.Fresh(freshSchema)
return schema
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L488-L507
|
func (d *dockerImageDestination) putOneSignature(url *url.URL, signature []byte) error {
switch url.Scheme {
case "file":
logrus.Debugf("Writing to %s", url.Path)
err := os.MkdirAll(filepath.Dir(url.Path), 0755)
if err != nil {
return err
}
err = ioutil.WriteFile(url.Path, signature, 0644)
if err != nil {
return err
}
return nil
case "http", "https":
return errors.Errorf("Writing directly to a %s sigstore %s is not supported. Configure a sigstore-staging: location", url.Scheme, url.String())
default:
return errors.Errorf("Unsupported scheme when writing signature to %s", url.String())
}
}
|
https://github.com/ikawaha/kagome.ipadic/blob/fe03f87a0c7c32945d956fcfc934c3e11d5eb182/internal/da/da.go#L182-L198
|
func Read(r io.Reader) (DoubleArray, error) {
var sz int64
if e := binary.Read(r, binary.LittleEndian, &sz); e != nil {
return DoubleArray{}, e
}
//fmt.Println("read data len:", sz)
d := make(DoubleArray, sz, sz)
for i := range d {
if e := binary.Read(r, binary.LittleEndian, &d[i].Base); e != nil {
return d, e
}
if e := binary.Read(r, binary.LittleEndian, &d[i].Check); e != nil {
return d, e
}
}
return d, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/conversion.go#L30-L78
|
func NewIssue(gIssue *github.Issue, repository string) (*sql.Issue, error) {
if gIssue.Number == nil ||
gIssue.Title == nil ||
gIssue.User == nil ||
gIssue.User.Login == nil ||
gIssue.State == nil ||
gIssue.Comments == nil ||
gIssue.CreatedAt == nil ||
gIssue.UpdatedAt == nil {
return nil, fmt.Errorf("Issue is missing mandatory field: %+v", gIssue)
}
var closedAt *time.Time
if gIssue.ClosedAt != nil {
closedAt = gIssue.ClosedAt
}
assignees, err := newAssignees(
*gIssue.Number,
gIssue.Assignees, repository)
if err != nil {
return nil, err
}
var body string
if gIssue.Body != nil {
body = *gIssue.Body
}
isPR := (gIssue.PullRequestLinks != nil && gIssue.PullRequestLinks.URL != nil)
labels, err := newLabels(
*gIssue.Number, gIssue.Labels, repository)
if err != nil {
return nil, err
}
return &sql.Issue{
ID: strconv.Itoa(*gIssue.Number),
Labels: labels,
Title: *gIssue.Title,
Body: body,
User: *gIssue.User.Login,
Assignees: assignees,
State: *gIssue.State,
Comments: *gIssue.Comments,
IsPR: isPR,
IssueClosedAt: closedAt,
IssueCreatedAt: *gIssue.CreatedAt,
IssueUpdatedAt: *gIssue.UpdatedAt,
Repository: strings.ToLower(repository),
}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/boskos.go#L284-L331
|
func handleReset(r *ranch.Ranch) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
logrus.WithField("handler", "handleReset").Infof("From %v", req.RemoteAddr)
if req.Method != http.MethodPost {
msg := fmt.Sprintf("Method %v, /reset only accepts POST.", req.Method)
logrus.Warning(msg)
http.Error(res, msg, http.StatusMethodNotAllowed)
return
}
rtype := req.URL.Query().Get("type")
state := req.URL.Query().Get("state")
expireStr := req.URL.Query().Get("expire")
dest := req.URL.Query().Get("dest")
logrus.Infof("%v, %v, %v, %v", rtype, state, expireStr, dest)
if rtype == "" || state == "" || expireStr == "" || dest == "" {
msg := fmt.Sprintf("Type: %v, state: %v, expire: %v, dest: %v, all of them must be set in the request.", rtype, state, expireStr, dest)
logrus.Warning(msg)
http.Error(res, msg, http.StatusBadRequest)
return
}
expire, err := time.ParseDuration(expireStr)
if err != nil {
logrus.WithError(err).Errorf("Invalid expiration: %v", expireStr)
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
rmap, err := r.Reset(rtype, state, expire, dest)
if err != nil {
logrus.WithError(err).Errorf("could not reset states")
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
resJSON, err := json.Marshal(rmap)
if err != nil {
logrus.WithError(err).Errorf("json.Marshal failed: %v", rmap)
http.Error(res, err.Error(), ErrorToStatus(err))
return
}
logrus.Infof("Resource %v reset successful, %d items moved to state %v", rtype, len(rmap), dest)
fmt.Fprint(res, string(resJSON))
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/crossdock/server/server.go#L60-L79
|
func (s *Server) Start() error {
if s.HostPort == "" {
s.HostPort = ":" + common.DefaultServerPort
}
channelOpts := &tchannel.ChannelOptions{
Tracer: s.Tracer,
}
ch, err := tchannel.NewChannel(common.DefaultServiceName, channelOpts)
if err != nil {
return err
}
if err := ch.ListenAndServe(s.HostPort); err != nil {
return err
}
s.HostPort = ch.PeerInfo().HostPort // override in case it was ":0"
log.Printf("Started tchannel server at %s\n", s.HostPort)
s.Ch = ch
return nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode29.go#L43-L60
|
func (d *decoder29) init(r io.ByteReader, reset bool) error {
if d.br == nil {
d.br = newRarBitReader(r)
} else {
d.br.reset(r)
}
d.eof = false
if reset {
d.initFilters()
d.lz.reset()
d.ppm.reset()
d.decode = nil
}
if d.decode == nil {
return d.readBlockHeader()
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/types.go#L66-L106
|
func (t *ValueType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ValueType(in.String()) {
case ValueTypeBoolean:
*t = ValueTypeBoolean
case ValueTypeTristate:
*t = ValueTypeTristate
case ValueTypeBooleanOrUndefined:
*t = ValueTypeBooleanOrUndefined
case ValueTypeIdref:
*t = ValueTypeIdref
case ValueTypeIdrefList:
*t = ValueTypeIdrefList
case ValueTypeInteger:
*t = ValueTypeInteger
case ValueTypeNode:
*t = ValueTypeNode
case ValueTypeNodeList:
*t = ValueTypeNodeList
case ValueTypeNumber:
*t = ValueTypeNumber
case ValueTypeString:
*t = ValueTypeString
case ValueTypeComputedString:
*t = ValueTypeComputedString
case ValueTypeToken:
*t = ValueTypeToken
case ValueTypeTokenList:
*t = ValueTypeTokenList
case ValueTypeDomRelation:
*t = ValueTypeDomRelation
case ValueTypeRole:
*t = ValueTypeRole
case ValueTypeInternalRole:
*t = ValueTypeInternalRole
case ValueTypeValueUndefined:
*t = ValueTypeValueUndefined
default:
in.AddError(errors.New("unknown ValueType value"))
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/fragmenting_writer.go#L82-L93
|
func (c *writableChunk) writeAsFits(b []byte) int {
if len(b) > c.contents.BytesRemaining() {
b = b[:c.contents.BytesRemaining()]
}
c.checksum.Add(b)
c.contents.WriteBytes(b)
written := len(b)
c.size += uint16(written)
return written
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/podlogartifact.go#L166-L173
|
func (a *PodLogArtifact) Size() (int64, error) {
logs, err := a.jobAgent.GetJobLog(a.name, a.buildID)
if err != nil {
return 0, fmt.Errorf("error getting size of pod log: %v", err)
}
return int64(len(logs)), nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/configure.go#L21-L62
|
func GetConfigCmd(noPortForwarding *bool) *cobra.Command {
var format string
getConfig := &cobra.Command{
Short: "Retrieve Pachyderm's current auth configuration",
Long: "Retrieve Pachyderm's current auth configuration",
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(true, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
resp, err := c.GetConfiguration(c.Ctx(), &auth.GetConfigurationRequest{})
if err != nil {
return grpcutil.ScrubGRPC(err)
}
if resp.Configuration == nil {
fmt.Println("no auth config set")
return nil
}
output, err := json.MarshalIndent(resp.Configuration, "", " ")
if err != nil {
return fmt.Errorf("could not marshal response:\n%v\ndue to: %v", resp.Configuration, err)
}
switch format {
case "json":
// already done
case "yaml":
output, err = yaml.JSONToYAML(output)
if err != nil {
return fmt.Errorf("could not convert json to yaml: %v", err)
}
default:
return fmt.Errorf("invalid output format: %v", format)
}
fmt.Println(string(output))
return nil
}),
}
getConfig.Flags().StringVarP(&format, "output-format", "o", "json", "output "+
"format (\"json\" or \"yaml\")")
return cmdutil.CreateAlias(getConfig, "auth get-config")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L143-L146
|
func (p StartPreciseCoverageParams) WithDetailed(detailed bool) *StartPreciseCoverageParams {
p.Detailed = detailed
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/agent.go#L106-L110
|
func (ca *Agent) Subscribe(subscription DeltaChan) {
ca.mut.Lock()
defer ca.mut.Unlock()
ca.subscriptions = append(ca.subscriptions, subscription)
}
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L135-L144
|
func squeeze(state []uint64, out []byte) {
tmp := make([]byte, blockLenBytes)
for j := 0; j < len(out)/blockLenBytes+1; j++ {
for i := 0; i < blockLenInt64; i++ {
binary.LittleEndian.PutUint64(tmp[i*8:], state[i])
}
copy(out[j*blockLenBytes:], tmp) //be care in case of len(out[i:])<len(tmp)
blake2bLyra(state)
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/search/search.pb.go#L1525-L1530
|
func (m *IndexDocumentParams) GetFreshness() IndexDocumentParams_Freshness {
if m != nil && m.Freshness != nil {
return *m.Freshness
}
return Default_IndexDocumentParams_Freshness
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plank/controller.go#L90-L109
|
func NewController(kc *kube.Client, pkcs map[string]*kube.Client, ghc GitHubClient, logger *logrus.Entry, cfg config.Getter, totURL, selector string, skipReport bool) (*Controller, error) {
if logger == nil {
logger = logrus.NewEntry(logrus.StandardLogger())
}
buildClusters := map[string]kubeClient{}
for alias, client := range pkcs {
buildClusters[alias] = kubeClient(client)
}
return &Controller{
kc: kc,
pkcs: buildClusters,
ghc: ghc,
log: logger,
config: cfg,
pendingJobs: make(map[string]int),
totURL: totURL,
selector: selector,
skipReport: skipReport,
}, nil
}
|
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/crypt.go#L12-L279
|
func crypt(pw string, salt string) string {
var pc1C = []byte{
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
}
var pc1D = []byte{
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4,
}
var pc2C = []byte{
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
}
var pc2D = []byte{
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32,
}
var e2 = []byte{
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1,
}
var ip = []byte{
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7,
}
var fp = []byte{
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25,
}
var s = [][]byte{
[]byte{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
[]byte{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
[]byte{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
[]byte{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
[]byte{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
[]byte{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
[]byte{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
[]byte{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11},
}
var P = []byte{
16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25,
}
var shift = []int{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}
if sLen := len(salt); sLen < 2 {
src := []byte(salt)
for len(src) < 2 {
src = append(src, 0x00)
}
salt = string(src)
}
block := make([]byte, 66)
for i := 0; i < 8 && i < len(pw); i++ {
for j := 0; j < 7; j++ {
block[(8*i)+j] = (pw[i] >> byte(6-j)) & 1
}
}
C := make([]byte, 28)
D := make([]byte, 28)
for i := 0; i < 28; i++ {
C[i] = block[pc1C[i]-1]
D[i] = block[pc1D[i]-1]
}
KS := make([][]byte, 16)
for i := 0; i < 16; i++ {
KS[i] = make([]byte, 48)
}
for i := 0; i < 16; i++ {
for k := 0; k < shift[i]; k++ {
t := C[0]
for j := 0; j < 28-1; j++ {
C[j] = C[j+1]
}
C[27] = t
t = D[0]
for j := 0; j < 28-1; j++ {
D[j] = D[j+1]
}
D[27] = t
}
for j := 0; j < 24; j++ {
KS[i][j] = C[pc2C[j]-1]
KS[i][j+24] = D[pc2D[j]-28-1]
}
}
E := make([]byte, 48)
for i := 0; i < 48; i++ {
E[i] = e2[i]
}
iobuf := make([]byte, 16)
for i := 0; i < 2; i++ {
c := byte(salt[i])
iobuf[i] = c
if c > 'Z' {
c -= 6
}
if c > '9' {
c -= 7
}
c -= '.'
for j := 0; j < 6; j++ {
if (c>>byte(j))&1 != 0 {
k := E[6*i+j]
E[6*i+j] = E[6*i+j+24]
E[6*i+j+24] = k
}
}
}
for i := 0; i < 66; i++ {
block[i] = 0
}
R := make([]byte, 32)
L := make([]byte, 32)
DMY := make([]byte, 32)
preS := make([]byte, 48)
f := make([]byte, 32)
dmyBlock := make([]byte, 64)
for m := 0; m < 25; m++ {
for i := 0; i < 32; i++ {
L[i] = block[ip[i]-1]
}
for i := 32; i < 64; i++ {
R[i-32] = block[ip[i]-1]
}
for i := 0; i < 16; i++ {
for j := 0; j < 32; j++ {
DMY[j] = R[j]
}
for j := 0; j < 48; j++ {
preS[j] = R[E[j]-1] ^ KS[i][j]
}
for j := 0; j < 8; j++ {
t := 6 * j
k := s[j][(preS[t+0]<<5)+
(preS[t+1]<<3)+
(preS[t+2]<<2)+
(preS[t+3]<<1)+
(preS[t+4]<<0)+
(preS[t+5]<<4)]
t = 4 * j
f[t+0] = (k >> 3) & 01
f[t+1] = (k >> 2) & 01
f[t+2] = (k >> 1) & 01
f[t+3] = (k >> 0) & 01
}
for j := 0; j < 32; j++ {
R[j] = L[j] ^ f[P[j]-1]
}
for j := 0; j < 32; j++ {
L[j] = DMY[j]
}
}
for i := 0; i < 32; i++ {
L[i], R[i] = R[i], L[i]
}
for i := 0; i < 32; i++ {
dmyBlock[i] = L[i]
}
for i := 32; i < 64; i++ {
dmyBlock[i] = R[i-32]
}
for i := 0; i < 64; i++ {
block[i] = dmyBlock[fp[i]-1]
}
}
var i int
for i = 0; i < 11; i++ {
c := byte(0)
for j := 0; j < 6; j++ {
c = c << 1
c = c | block[6*i+j]
}
c = c + '.'
if c > '9' {
c += 7
}
if c > 'Z' {
c += 6
}
iobuf[i+2] = c
}
iobuf[i+2] = 0
return string(bytes.Replace(iobuf, []byte{0x00}, []byte{}, -1))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4671-L4678
|
func NewLedgerHeaderExt(v int32, value interface{}) (result LedgerHeaderExt, err error) {
result.V = v
switch int32(v) {
case 0:
// void
}
return
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/ps.go#L54-L124
|
func Interpret(strm Value, do func(stk *Stack, op string)) {
rd := strm.Reader()
b := newBuffer(rd, 0)
b.allowEOF = true
b.allowObjptr = false
b.allowStream = false
var stk Stack
var dicts []dict
Reading:
for {
tok := b.readToken()
if tok == io.EOF {
break
}
if kw, ok := tok.(keyword); ok {
switch kw {
case "null", "[", "]", "<<", ">>":
break
default:
for i := len(dicts) - 1; i >= 0; i-- {
if v, ok := dicts[i][name(kw)]; ok {
stk.Push(Value{nil, objptr{}, v})
continue Reading
}
}
do(&stk, string(kw))
continue
case "dict":
stk.Pop()
stk.Push(Value{nil, objptr{}, make(dict)})
continue
case "currentdict":
if len(dicts) == 0 {
panic("no current dictionary")
}
stk.Push(Value{nil, objptr{}, dicts[len(dicts)-1]})
continue
case "begin":
d := stk.Pop()
if d.Kind() != Dict {
panic("cannot begin non-dict")
}
dicts = append(dicts, d.data.(dict))
continue
case "end":
if len(dicts) <= 0 {
panic("mismatched begin/end")
}
dicts = dicts[:len(dicts)-1]
continue
case "def":
if len(dicts) <= 0 {
panic("def without open dict")
}
val := stk.Pop()
key, ok := stk.Pop().data.(name)
if !ok {
panic("def of non-name")
}
dicts[len(dicts)-1][key] = val.data
continue
case "pop":
stk.Pop()
continue
}
}
b.unreadToken(tok)
obj := b.readObject()
stk.Push(Value{nil, objptr{}, obj})
}
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L109-L111
|
func (t *Tracer) Tag(key string, value interface{}) {
t.Last().SetTag(key, value)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L210-L296
|
func (c *Client) LoadRepoOwners(org, repo, base string) (RepoOwner, error) {
log := c.logger.WithFields(logrus.Fields{"org": org, "repo": repo, "base": base})
cloneRef := fmt.Sprintf("%s/%s", org, repo)
fullName := fmt.Sprintf("%s:%s", cloneRef, base)
mdYaml := c.mdYAMLEnabled(org, repo)
sha, err := c.ghc.GetRef(org, repo, fmt.Sprintf("heads/%s", base))
if err != nil {
return nil, fmt.Errorf("failed to get current SHA for %s: %v", fullName, err)
}
c.lock.Lock()
defer c.lock.Unlock()
entry, ok := c.cache[fullName]
if !ok || entry.sha != sha || entry.owners == nil || !entry.matchesMDYAML(mdYaml) {
gitRepo, err := c.git.Clone(cloneRef)
if err != nil {
return nil, fmt.Errorf("failed to clone %s: %v", cloneRef, err)
}
defer gitRepo.Clean()
reusable := entry.fullyLoaded() && entry.matchesMDYAML(mdYaml)
// In most sha changed cases, the files associated with the owners are unchanged.
// The cached entry can continue to be used, so need do git diff
if reusable {
changes, err := gitRepo.Diff(sha, entry.sha)
if err != nil {
return nil, fmt.Errorf("failed to diff %s with %s", sha, entry.sha)
}
for _, change := range changes {
if mdYaml && strings.HasSuffix(change, ".md") ||
strings.HasSuffix(change, aliasesFileName) ||
strings.HasSuffix(change, ownersFileName) {
reusable = false
break
}
}
}
if reusable {
entry.sha = sha
} else {
if err := gitRepo.Checkout(base); err != nil {
return nil, err
}
if entry.aliases == nil || entry.sha != sha {
// aliases must be loaded
entry.aliases = loadAliasesFrom(gitRepo.Dir, log)
}
dirBlacklistPatterns := append(c.ownersDirBlacklist().DirBlacklist(org, repo), commonDirBlacklist...)
var dirBlacklist []*regexp.Regexp
for _, pattern := range dirBlacklistPatterns {
re, err := regexp.Compile(pattern)
if err != nil {
log.WithError(err).Errorf("Invalid OWNERS dir blacklist regexp %q.", pattern)
continue
}
dirBlacklist = append(dirBlacklist, re)
}
entry.owners, err = loadOwnersFrom(gitRepo.Dir, mdYaml, entry.aliases, dirBlacklist, log)
if err != nil {
return nil, fmt.Errorf("failed to load RepoOwners for %s: %v", fullName, err)
}
entry.sha = sha
c.cache[fullName] = entry
}
}
if c.skipCollaborators(org, repo) {
log.Debugf("Skipping collaborator checks for %s/%s", org, repo)
return entry.owners, nil
}
var owners *RepoOwners
// Filter collaborators. We must filter the RepoOwners struct even if it came from the cache
// because the list of collaborators could have changed without the git SHA changing.
collaborators, err := c.ghc.ListCollaborators(org, repo)
if err != nil {
log.WithError(err).Errorf("Failed to list collaborators while loading RepoOwners. Skipping collaborator filtering.")
owners = entry.owners
} else {
owners = entry.owners.filterCollaborators(collaborators)
}
return owners, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L421-L425
|
func (v *StopWorkerParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoServiceworker3(&r, v)
return r.Error()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L137-L139
|
func (win *Window) Resize(width, height int) {
C.cvResizeWindow(win.name_c, C.int(width), C.int(height))
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L61-L77
|
func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port int, discovery bool, logger Logger) *connectionMaker {
actionChan := make(chan connectionMakerAction, ChannelSize)
cm := &connectionMaker{
ourself: ourself,
peers: peers,
localAddr: localAddr,
port: port,
discovery: discovery,
directPeers: peerAddrs{},
targets: make(map[string]*target),
connections: make(map[Connection]struct{}),
actionChan: actionChan,
logger: logger,
}
go cm.queryLoop(actionChan)
return cm
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/headlessexperimental.go#L88-L103
|
func (p *BeginFrameParams) Do(ctx context.Context) (hasDamage bool, screenshotData []byte, err error) {
// execute
var res BeginFrameReturns
err = cdp.Execute(ctx, CommandBeginFrame, p, &res)
if err != nil {
return false, nil, err
}
// decode
var dec []byte
dec, err = base64.StdEncoding.DecodeString(res.ScreenshotData)
if err != nil {
return false, nil, err
}
return res.HasDamage, dec, nil
}
|
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/stagePlanner.go#L151-L174
|
func makePrecedentFromPlanner(planner *precedencePlanner) precedent {
var generated precedent
var nextRight precedent
generated = func(stream *tokenStream) (*evaluationStage, error) {
return planPrecedenceLevel(
stream,
planner.typeErrorFormat,
planner.validSymbols,
planner.validKinds,
nextRight,
planner.next,
)
}
if planner.nextRight != nil {
nextRight = planner.nextRight
} else {
nextRight = generated
}
return generated
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/sync/sync.go#L202-L281
|
func (p *Puller) PullDiff(client *pachclient.APIClient, root string, newRepo, newCommit, newPath, oldRepo, oldCommit, oldPath string,
newOnly bool, pipes bool, emptyFiles bool, concurrency int, tree hashtree.HashTree, treeRoot string) error {
limiter := limit.New(concurrency)
var eg errgroup.Group
newFiles, oldFiles, err := client.DiffFile(newRepo, newCommit, newPath, oldRepo, oldCommit, oldPath, false)
if err != nil {
return err
}
for _, newFile := range newFiles {
basepath, err := filepath.Rel(newPath, newFile.File.Path)
if err != nil {
return err
}
if tree != nil {
treePath := path.Join(treeRoot, "new", basepath)
if newOnly {
treePath = path.Join(treeRoot, basepath)
}
if err := tree.PutFile(treePath, newFile.Objects, int64(newFile.SizeBytes)); err != nil {
return err
}
}
path := filepath.Join(root, "new", basepath)
if newOnly {
path = filepath.Join(root, basepath)
}
if pipes {
if err := p.makePipe(path, func(w io.Writer) error {
return client.GetFile(newFile.File.Commit.Repo.Name, newFile.File.Commit.ID, newFile.File.Path, 0, 0, w)
}); err != nil {
return err
}
} else if emptyFiles {
if err := p.makeFile(path, func(w io.Writer) error { return nil }); err != nil {
return err
}
} else {
newFile := newFile
limiter.Acquire()
eg.Go(func() error {
defer limiter.Release()
return p.makeFile(path, func(w io.Writer) error {
return client.GetFile(newFile.File.Commit.Repo.Name, newFile.File.Commit.ID, newFile.File.Path, 0, 0, w)
})
})
}
}
if !newOnly {
for _, oldFile := range oldFiles {
basepath, err := filepath.Rel(oldPath, oldFile.File.Path)
if err != nil {
return err
}
if tree != nil {
treePath := path.Join(treeRoot, "old", basepath)
if err := tree.PutFile(treePath, oldFile.Objects, int64(oldFile.SizeBytes)); err != nil {
return err
}
}
path := filepath.Join(root, "old", basepath)
if pipes {
if err := p.makePipe(path, func(w io.Writer) error {
return client.GetFile(oldFile.File.Commit.Repo.Name, oldFile.File.Commit.ID, oldFile.File.Path, 0, 0, w)
}); err != nil {
return err
}
} else {
oldFile := oldFile
limiter.Acquire()
eg.Go(func() error {
defer limiter.Release()
return p.makeFile(path, func(w io.Writer) error {
return client.GetFile(oldFile.File.Commit.Repo.Name, oldFile.File.Commit.ID, oldFile.File.Path, 0, 0, w)
})
})
}
}
}
return eg.Wait()
}
|
https://github.com/grokify/go-scim-client/blob/800878015236174e45b05db1ec125aae20a093e4/user_api.go#L34-L94
|
func (a *UserApiService) CreateUser(ctx context.Context, localVarOptionals map[string]interface{}) (UserResponse, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Post")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
successPayload UserResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/Users"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json", "application/scim+json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
"application/scim+json",
}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
if localVarTempParam, localVarOk := localVarOptionals["body"].(User); localVarOk {
localVarPostBody = &localVarTempParam
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return successPayload, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return successPayload, localVarHttpResponse, err
}
defer localVarHttpResponse.Body.Close()
if localVarHttpResponse.StatusCode >= 300 {
bodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)
return successPayload, localVarHttpResponse, reportError("Status: %v, Body: %s", localVarHttpResponse.Status, bodyBytes)
}
if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {
return successPayload, localVarHttpResponse, err
}
return successPayload, localVarHttpResponse, err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/snapshot/v3_snapshot.go#L72-L77
|
func NewV3(lg *zap.Logger) Manager {
if lg == nil {
lg = zap.NewExample()
}
return &v3Manager{lg: lg}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L513-L516
|
func (p GetPropertiesParams) WithGeneratePreview(generatePreview bool) *GetPropertiesParams {
p.GeneratePreview = generatePreview
return &p
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/arguments.go#L95-L110
|
func (r ArgReadHelper) ReadJSON(data interface{}) error {
return r.read(func() error {
// TChannel allows for 0 length values (not valid JSON), so we use a bufio.Reader
// to check whether data is of 0 length.
reader := bufio.NewReader(r.reader)
if _, err := reader.Peek(1); err == io.EOF {
// If the data is 0 length, then we don't try to read anything.
return nil
} else if err != nil {
return err
}
d := json.NewDecoder(reader)
return d.Decode(data)
})
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L83-L87
|
func Warnf(format string, args ...interface{}) {
if Log != nil {
Log.Warn(fmt.Sprintf(format, args...))
}
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/handler.go#L19-L25
|
func NewStreamHandler(w io.Writer) (*StreamHandler, error) {
h := new(StreamHandler)
h.w = w
return h, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L157-L162
|
func (ep *Endpoint) Method() string {
if strings.Contains(ep.OperationID, "#") {
return strings.Split(ep.OperationID, "#")[1]
}
return ""
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/move_labels/move_labels.go#L152-L166
|
func moveLocations(from, to, str string) string {
matches := locationsRegexp.FindAllStringSubmatchIndex(str, -1)
buf := new(bytes.Buffer)
pos := 0
for _, match := range matches {
buf.WriteString(str[pos:match[2]])
label := str[match[2]:match[3]]
moved := moveLabel(from, to, label)
buf.WriteString(moved)
buf.WriteString(str[match[3]:match[1]])
pos = match[1]
}
buf.WriteString(str[pos:])
return buf.String()
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/gof3r/options.go#L105-L114
|
func homeDir() (string, error) {
if h := os.Getenv("HOME"); h != "" {
return h, nil
}
h, err := exec.Command("sh", "-c", "eval echo ~$USER").Output()
if err == nil && len(h) > 0 {
return strings.TrimSpace(string(h)), nil
}
return "", fmt.Errorf("home directory not found for current user")
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/histogram.go#L27-L37
|
func (db *DB) PrintHistogram(keyPrefix []byte) {
if db == nil {
fmt.Println("\nCannot build histogram: DB is nil.")
return
}
histogram := db.buildHistogram(keyPrefix)
fmt.Printf("Histogram of key sizes (in bytes)\n")
histogram.keySizeHistogram.printHistogram()
fmt.Printf("Histogram of value sizes (in bytes)\n")
histogram.valueSizeHistogram.printHistogram()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1554-L1564
|
func (app *App) Envs() map[string]bind.EnvVar {
mergedEnvs := make(map[string]bind.EnvVar, len(app.Env)+len(app.ServiceEnvs)+1)
for _, e := range app.Env {
mergedEnvs[e.Name] = e
}
for _, e := range app.ServiceEnvs {
mergedEnvs[e.Name] = e.EnvVar
}
mergedEnvs[TsuruServicesEnvVar] = serviceEnvsFromEnvVars(app.ServiceEnvs)
return mergedEnvs
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/install.go#L93-L104
|
func installHostList(w http.ResponseWriter, r *http.Request, t auth.Token) error {
allowed := permission.Check(t, permission.PermInstallManage)
if !allowed {
return permission.ErrUnauthorized
}
hosts, err := install.ListHosts()
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(&hosts)
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/packet/packetSDK/sdk.go#L30-L39
|
func NewSdk() (*Sdk, error) {
sdk := &Sdk{}
apiToken := getToken()
if apiToken == "" {
return nil, fmt.Errorf("Empty $PACKET_APITOKEN")
}
sdk.Client = packngo.NewClient("kubicorn", apiToken, nil)
return sdk, nil
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L125-L133
|
func Diff(x, y interface{}, opts ...Option) string {
r := new(defaultReporter)
eq := Equal(x, y, Options(opts), Reporter(r))
d := r.String()
if (d == "") != eq {
panic("inconsistent difference and equality results")
}
return d
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L58-L60
|
func (t *Token) GetTokenData() (TokenType, []string, time.Time, bson.ObjectId, *bson.ObjectId) {
return t.Type, t.Scope, t.ExpiresAt, t.Application, t.User
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/author_filter_wrapper.go#L71-L76
|
func (a *AuthorFilterPluginWrapper) ReceiveComment(comment sql.Comment) []Point {
if a.match(comment.User) {
return nil
}
return a.plugin.ReceiveComment(comment)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4780-L4784
|
func (v *FontFamilies) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage49(&r, v)
return r.Error()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L497-L500
|
func (iter *SparseMatIterator) Next() *SparseNode {
node := C.cvGetNextSparseNode((*C.CvSparseMatIterator)(iter))
return (*SparseNode)(node)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L266-L280
|
func (m PaymentBuilder) MutateTransaction(o *TransactionBuilder) error {
if m.Err != nil {
return m.Err
}
if m.PathPayment {
m.O.Body, m.Err = xdr.NewOperationBody(xdr.OperationTypePathPayment, m.PP)
o.TX.Operations = append(o.TX.Operations, m.O)
return m.Err
}
m.O.Body, m.Err = xdr.NewOperationBody(xdr.OperationTypePayment, m.P)
o.TX.Operations = append(o.TX.Operations, m.O)
return m.Err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/fuse/file.go#L174-L178
|
func (c *counter) cancel() {
c.mu.Lock()
defer c.mu.Unlock()
c.n = math.MaxInt64
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L434-L437
|
func (f *FakeClient) ListPRCommits(org, repo string, prNumber int) ([]github.RepositoryCommit, error) {
k := fmt.Sprintf("%s/%s#%d", org, repo, prNumber)
return f.CommitMap[k], nil
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1293-L1305
|
func (d *StreamDecoder) Len() int {
if d.err != nil {
return 0
}
if d.typ == Unknown {
if d.init() != nil {
return 0
}
}
return d.max - d.cnt
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/fake/fake_prowjob.go#L75-L79
|
func (c *FakeProwJobs) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(prowjobsResource, c.ns, opts))
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/common.go#L53-L64
|
func capitalizeYs(word *snowballword.SnowballWord) (numCapitalizations int) {
for i, r := range word.RS {
// (Note: Y & y unicode code points = 89 & 121)
if r == 121 && (i == 0 || isLowerVowel(word.RS[i-1])) {
word.RS[i] = 89
numCapitalizations += 1
}
}
return
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/equate.go#L77-L82
|
func EquateNaNs() cmp.Option {
return cmp.Options{
cmp.FilterValues(areNaNsF64s, cmp.Comparer(equateAlways)),
cmp.FilterValues(areNaNsF32s, cmp.Comparer(equateAlways)),
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/fileutil/preallocate.go#L27-L36
|
func Preallocate(f *os.File, sizeInBytes int64, extendFile bool) error {
if sizeInBytes == 0 {
// fallocate will return EINVAL if length is 0; skip
return nil
}
if extendFile {
return preallocExtend(f, sizeInBytes)
}
return preallocFixed(f, sizeInBytes)
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L50-L71
|
func NewServer(filename string, environment string) (server *Server, err error) {
conf, err := GetConfig(filename, environment)
logFile, err := os.OpenFile(conf.Log.File+logFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.SetOutput(os.Stderr)
log.Warningf("Can't open logfile: %v", err)
} else {
log.SetOutput(logFile)
}
level := log.ErrorLevel
if strings.Compare(conf.Log.Level, "") != 0 {
level, _ = log.ParseLevel(conf.Log.Level)
} else {
log.Infof("Log Level: %v", level)
}
log.SetLevel(level)
server = &Server{Config: conf, Done: make(chan bool, 1), Error: make(chan error, 1), Server: http.Server{Handler: NewLoggingServeMux(conf)}, quit: make(chan bool), isStarted: false}
return
}
|
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/ktrie/ktrie.go#L89-L116
|
func NewKTrie(data map[string]bool) (*KTrie, error) {
n := NewKNode(0)
maxDepth := 0
minDepth := 9001
for k := range data {
rs := []rune(k)
l := len(rs)
n.Add(rs)
if l > maxDepth {
maxDepth = l
}
if l < minDepth {
minDepth = l
}
}
t := &KTrie{
maxDepth: maxDepth,
minDepth: minDepth,
KNode: n,
}
return t, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/table.go#L315-L328
|
func ParseFileID(name string) (uint64, bool) {
name = path.Base(name)
if !strings.HasSuffix(name, fileSuffix) {
return 0, false
}
// suffix := name[len(fileSuffix):]
name = strings.TrimSuffix(name, fileSuffix)
id, err := strconv.Atoi(name)
if err != nil {
return 0, false
}
y.AssertTrue(id >= 0)
return uint64(id), true
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.