Dataset Viewer
Auto-converted to Parquet Duplicate
anchor
stringlengths
7
95.4k
positive
stringlengths
8
5.39M
negative
stringlengths
6
7.22M
Returns the value of the 'go_package' option of the first .proto file found in the same directory as projectFile
func detectGoPackageForProject(projectFile string) (string, error) { var goPkg string projectDir := filepath.Dir(projectFile) if err := filepath.Walk(projectDir, func(protoFile string, info os.FileInfo, err error) error { // already set if goPkg != "" { return nil } if !strings.HasSuffix(protoFile, ".prot...
func (g *Generator) GoFilePackage(depfile *fdep.DepFile) string { return fproto_wrap.BaseName(g.GoWrapPackage(depfile)) }
NewQueueManager instantiates a new QueueManager object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed
func NewQueueManager(name string, clusters []string, aliasQueues []AliasQueue, remoteQueues []RemoteQueue, clusterQueues []ClusterQueue, ) *QueueManager { this := QueueManager{} this.Name = name this.Clusters = clusters this.AliasQueues = aliasQueues this.RemoteQueues = remoteQueues this.ClusterQueues = clusterQu...
func NewQueueManager(q amboy.Queue) Manager { return &queueManager{ queue: q, } }
NewQueueManagerWithDefaults instantiates a new QueueManager object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set
func NewQueueManagerWithDefaults() *QueueManager { this := QueueManager{} return &this }
func NewQueueManager(logger log.Logger, cfg config.QueueConfig, externalLabels labels.Labels, relabelConfigs []*relabel.Config, client StorageClient, flushDeadline time.Duration) *QueueManager { if logger == nil { logger = log.NewNopLogger() } else { logger = log.With(logger, "queue", client.Name()) } t := &Que...
GetClusters returns the Clusters field value
func (o *QueueManager) GetClusters() []string { if o == nil { var ret []string return ret } return o.Clusters }
func (c *Config) GetClusters(ctx context.Context, quiet bool, filterMap map[string]string, clustersName ...string) (string, error) { c.Logger.Debugf("Sending parameters to server to get the clusters %q", strings.Join(clustersName, ", ")) filter := MapToSlice(filterMap) return c.RunGRPCnRESTFunc("get", true, func...
GetClustersOk returns a tuple with the Clusters field value and a boolean to check if the value has been set.
func (o *QueueManager) GetClustersOk() (*[]string, bool) { if o == nil { return nil, false } return &o.Clusters, true }
func NewGetClustersOK() *GetClustersOK { return &GetClustersOK{} }
SetClusters sets field value
func (o *QueueManager) SetClusters(v []string) { o.Clusters = v }
func (s *RaftDatabase) SetClusters(clusters int) { s.clusters = clusters }
GetAliasQueues returns the AliasQueues field value
func (o *QueueManager) GetAliasQueues() []AliasQueue { if o == nil { var ret []AliasQueue return ret } return o.AliasQueues }
func (o *QueueManager) GetAliasQueuesOk() (*[]AliasQueue, bool) { if o == nil { return nil, false } return &o.AliasQueues, true }
GetAliasQueuesOk returns a tuple with the AliasQueues field value and a boolean to check if the value has been set.
func (o *QueueManager) GetAliasQueuesOk() (*[]AliasQueue, bool) { if o == nil { return nil, false } return &o.AliasQueues, true }
func (o *QueueManager) GetAliasQueues() []AliasQueue { if o == nil { var ret []AliasQueue return ret } return o.AliasQueues }
SetAliasQueues sets field value
func (o *QueueManager) SetAliasQueues(v []AliasQueue) { o.AliasQueues = v }
func (p *Process) CmdSetQueue(pac teoapi.Packet) (err error) { data := pac.RemoveTrailingZero(pac.Data()) request := cdb.KeyValue{Cmd: pac.Cmd()} if err = request.UnmarshalText(data); err != nil { return } else if err = p.tcdb.SetQueue(request.Key, request.Value); err != nil { return } // Return only Value fo...
GetRemoteQueues returns the RemoteQueues field value
func (o *QueueManager) GetRemoteQueues() []RemoteQueue { if o == nil { var ret []RemoteQueue return ret } return o.RemoteQueues }
func (o *QueueManager) GetRemoteQueuesOk() (*[]RemoteQueue, bool) { if o == nil { return nil, false } return &o.RemoteQueues, true }
GetRemoteQueuesOk returns a tuple with the RemoteQueues field value and a boolean to check if the value has been set.
func (o *QueueManager) GetRemoteQueuesOk() (*[]RemoteQueue, bool) { if o == nil { return nil, false } return &o.RemoteQueues, true }
func (o *QueueManager) GetRemoteQueues() []RemoteQueue { if o == nil { var ret []RemoteQueue return ret } return o.RemoteQueues }
SetRemoteQueues sets field value
func (o *QueueManager) SetRemoteQueues(v []RemoteQueue) { o.RemoteQueues = v }
func (s *Filters) SetQueues(v []*string) *Filters { s.Queues = v return s }
GetClusterQueues returns the ClusterQueues field value
func (o *QueueManager) GetClusterQueues() []ClusterQueue { if o == nil { var ret []ClusterQueue return ret } return o.ClusterQueues }
func (o *QueueManager) GetClusterQueuesOk() (*[]ClusterQueue, bool) { if o == nil { return nil, false } return &o.ClusterQueues, true }
GetClusterQueuesOk returns a tuple with the ClusterQueues field value and a boolean to check if the value has been set.
func (o *QueueManager) GetClusterQueuesOk() (*[]ClusterQueue, bool) { if o == nil { return nil, false } return &o.ClusterQueues, true }
func (o *QueueManager) GetAliasQueuesOk() (*[]AliasQueue, bool) { if o == nil { return nil, false } return &o.AliasQueues, true }
SetClusterQueues sets field value
func (o *QueueManager) SetClusterQueues(v []ClusterQueue) { o.ClusterQueues = v }
func (p *Process) CmdSetQueue(pac teoapi.Packet) (err error) { data := pac.RemoveTrailingZero(pac.Data()) request := cdb.KeyValue{Cmd: pac.Cmd()} if err = request.UnmarshalText(data); err != nil { return } else if err = p.tcdb.SetQueue(request.Key, request.Value); err != nil { return } // Return only Value fo...
Is the tiploc one for this station
func (bf *boardFilter) atStation(tpl string) bool { for _, s := range bf.res.Station { if s == tpl { return true } } return false }
func isStationInJourney(st string, journey timetableRouteJourney) bool { for _, call := range journey.Calls.Call { if call.ScheduledStopPointRef.Ref == st { return true } } return false }
Add a tiploc to the result so that it will be included in the tiploc map
func (bf *boardFilter) addTiploc(tiploc string) { if tiploc != "" { bf.tiplocs[tiploc] = nil } }
func (r *LocationMap) Add(t *Location) { if _, ok := r.m[t.Tiploc]; !ok { r.m[t.Tiploc] = t } }
Add a ViaResolveRequest to the response
func (bf *boardFilter) addVia(rid, dest string) *darwinref.ViaResolveRequest { viaRequest := &darwinref.ViaResolveRequest{ Crs: bf.station.Crs, Destination: dest, } bf.vias[rid] = viaRequest return viaRequest }
func (o *Options) resolve() { o.ContentSource = filepath.ToURL(o.ContentSource) if o.Address == "" { o.Address = ":8080" } if o.TemplateDataFunc == nil { o.TemplateDataFunc = tpl.StdDataFunc } if o.Endpoints == nil { o.Endpoints = make(api.Endpoints, 0) } }
Process calling points so that we generate the appropriate via and include their tiplocs
func (bf *boardFilter) processCallingPoints(s ldb.Service) { if len(s.CallingPoints) > 0 { viaRequest := bf.addVia(s.RID, s.CallingPoints[len(s.CallingPoints)-1].Tiploc) for _, cp := range s.CallingPoints { bf.addTiploc(cp.Tiploc) viaRequest.AppendTiploc(cp.Tiploc) } } }
func (bf *boardFilter) callsAt(callingPoints []darwind3.CallingPoint, tpls []string) bool { for _, cp := range callingPoints { for _, tpl := range tpls { if tpl == cp.Tiploc { return true } } } return false }
Process any associations, pulling in their schedules
func (bf *boardFilter) processAssociations(s ldb.Service) { for _, assoc := range s.Associations { assoc.AddTiplocs(bf.tiplocs) //if assoc.IsJoin() || assoc.IsSplit() { ar := assoc.Main.RID ai := assoc.Main.LocInd if ar == s.RID { ar = assoc.Assoc.RID ai = assoc.Assoc.LocInd } // Resolve the sche...
func (s *candidate) Schedule() (constructedSchedule, error) { sch := constructedSchedule{ earliest: s.earliest, eventsByAttendee: make(map[AttendeeID]*attendeeEvents), } for _, event := range s.order { if err := sch.Add(s.reqs[event]); err != nil { return sch, err } } return sch, nil }
acceptService returns true if the service is to be accepted, false if it's to be ignored
func (bf *boardFilter) acceptService(service ldb.Service) bool { // Original requirement, must have an RID if service.RID == "" { return false } // remove terminating services if bf.terminated && bf.atStation(service.Destination) { return false } if bf.callAt && !bf.callsAt(service.CallingPoints, bf.callAt...
func (f *aclFilter) allowService(service string) bool { if service == "" { return true } if !f.enforceVersion8 && service == structs.ConsulServiceID { return true } return f.authorizer.ServiceRead(service) }
NewSettingsDialog(parent widgets.QWidget, flags) is automatically generated
func (sd *SettingsDialog) OpenSettingsDialog() { if !sd.isDisplayInited { sd.__init_display() } sd.populateFields() sd.Open() }
func newOptions(parent *options) *options { opts := &options{ inherited: inherited{ focusedColor: cell.ColorYellow, }, hAlign: align.HorizontalCenter, vAlign: align.VerticalMiddle, splitPercent: DefaultSplitPercent, } if parent != nil { opts.inherited = parent.inherited } return opts }
List all the known records
func (s *sqlStore) List(opts ...store.ListOption) ([]string, error) { options := store.ListOptions{ Order: store.OrderAsc, } for _, o := range opts { o(&options) } db, queries, err := s.db(options.Database, options.Table) if err != nil { return nil, err } pattern := "%" if options.Prefix != "" { patte...
func ListAll() []ModelUser { common.Logger("info", "Initialize Get Database in PostgreSQL", "Modul User : ListAll") db := common.GetPostgreSQLDB() tx := db.Begin() common.Logger("info", "Prepare Query Select Table in Database PostgreSQL", "Modul User : ListAll") var models []ModelUser common.Logger("info", "Pr...
rowToRecord converts from pgx.Row to a store.Record
func (s *sqlStore) rowToRecord(row pgx.Row) (*store.Record, error) { var expiry *time.Time record := &store.Record{} metadata := make(Metadata) if err := row.Scan(&record.Key, &record.Value, &metadata, &expiry); err != nil { if err == sql.ErrNoRows { return record, store.ErrNotFound } return nil, err } ...
func (s *sqlStore) rowsToRecords(rows pgx.Rows) ([]*store.Record, error) { var records []*store.Record for rows.Next() { var expiry *time.Time record := &store.Record{} metadata := make(Metadata) if err := rows.Scan(&record.Key, &record.Value, &metadata, &expiry); err != nil { return records, err } ...
rowsToRecords converts from pgx.Rows to []store.Record
func (s *sqlStore) rowsToRecords(rows pgx.Rows) ([]*store.Record, error) { var records []*store.Record for rows.Next() { var expiry *time.Time record := &store.Record{} metadata := make(Metadata) if err := rows.Scan(&record.Key, &record.Value, &metadata, &expiry); err != nil { return records, err } ...
func (s *sqlStore) rowToRecord(row pgx.Row) (*store.Record, error) { var expiry *time.Time record := &store.Record{} metadata := make(Metadata) if err := row.Scan(&record.Key, &record.Value, &metadata, &expiry); err != nil { if err == sql.ErrNoRows { return record, store.ErrNotFound } return nil, err } ...
Delete records with keys
func (s *sqlStore) Delete(key string, opts ...store.DeleteOption) error { var options store.DeleteOptions for _, o := range opts { o(&options) } db, queries, err := s.db(options.Database, options.Table) if err != nil { return err } _, err = db.Exec(s.options.Context, queries.Delete, key) return err }
func (r *redisHandler) DeleteKeyEventPublisher(keys[] string, successStatus int) gin.HandlerFunc { for _, key := range keys { if key == "" { systemlog.Fatalln("parameter of DeleteKeyEventPublisher to delete redis key must not be blank string") } } ctx := context.Background() return func(c *gin.Context) { ...
NewStore returns a new micro Store backed by sql
func NewStore(opts ...store.Option) store.Store { options := store.Options{ Database: defaultDatabase, Table: defaultTable, } for _, o := range opts { o(&options) } // new store s := new(sqlStore) s.options = options s.databases = make(map[string]DB) s.re = regexp.MustCompile("[^a-zA-Z0-9]+") go s...
func NewStore() *Store { data := `{ "contacts": [{ "name": "郭仲杰", "department": "公司其他组织/TME商业广告部", "title": "员工", "phoneNumber": "0755-86013388-75789", "email": "authurguo@tencent.com" }] }` s := &Store{} err := json.Unmarshal([]byte(data), s) if err != nil { panic(err) } return s }
findConflict finds the index of the conflict. It returns the first pair of conflicting entries between the existing entries and the given entries, if there are any. If there is no conflicting entries, and the existing entries contains all the given entries, zero will be returned. If there is no conflicting entries, but...
func (l *LogStore) findConflict(entries []*pb.Entry) uint64 { // TODO: 会有第0个冲突么? for _, ne := range entries { if !l.matchTerm(ne.Index, ne.Term) { if ne.Index <= l.lastIndex() { l.logger.Info("log found conflict", zap.Uint64("conflictIndex", ne.Index), zap.Uint64("conflictTerm", ne.Term), zap....
func FindConflictsByUser(entries []*RenderedScheduleEntry) map[string][]*Conflict { entriesByUser := RenderedScheduleEntries(entries).GroupBy(func(entry *RenderedScheduleEntry) string { return entry.User.ID }) var ( m sync.Mutex wg sync.WaitGroup results = make(map[string][]*Conflict, len(entries...
New creates a new crawler
func New(ctx context.Context, logger yolo.Logger, client *http.Client, filter FilterFunc, mapper Mapper) *Crawler { return &Crawler{ ctx: ctx, logger: logger, client: client, filter: filter, mapper: mapper, visitChan: make(chan visit, visitChanBuffer), toVisit: make(map[string]struct{}), } }
func NewCrawler() (crawler *Crawler) { crawler = new(Crawler) crawler.Timeout = 60 * time.Second crawler.MaxDepth = -1 crawler.Auth = nil crawler.Workers = 10 crawler.HashLoopCheck = false crawler.FollowExternal = false crawler.UserAgent = nil crawler.Retries = 0 crawler.SleepBetweenRetries = 0 return }
Add adds one or more previously unadded urls to crawler to visit. source can be nil to indicate root. Returns a list of errors if any occured.
func (c *Crawler) Add(source *url.URL, uri ...*url.URL) []error { var errs []error for _, u := range uri { var err error u := u u.Fragment = "" // reset fragment, we don't want it messing our visited list if source != nil { u = source.ResolveReference(u) } if u.Scheme != "http" && u.Scheme != "http...
func (os *OriginChecker) AddRawURLs(urls []string) { os.Lock() defer os.Unlock() for _, u := range urls { clean, err := cleanOrigin(u) if err == nil { os.origins[clean] = true } } }
getSourcegraphVersion queries the Sourcegraph GraphQL API to get the current version of the Sourcegraph instance.
func (svc *Service) getSourcegraphVersion(ctx context.Context) (string, error) { var result struct { Site struct { ProductVersion string } } ok, err := svc.client.NewQuery(sourcegraphVersionQuery).Do(ctx, &result) if err != nil || !ok { return "", err } return result.Site.ProductVersion, err }
func (obj *Edge) GetVersion() int { return obj.getVersion() }
DetermineFeatureFlags fetches the version of the configured Sourcegraph instance and then sets flags on the Service itself to use features available in that version, e.g. gzip compression.
func (svc *Service) DetermineFeatureFlags(ctx context.Context) error { version, err := svc.getSourcegraphVersion(ctx) if err != nil { return errors.Wrap(err, "failed to query Sourcegraph version to check for available features") } return svc.features.setFromVersion(version) }
func InitFeatureFlags(flag *pflag.FlagSet) { flag.Bool(FeatureFlagAccessCode, false, "Flag (bool) to enable requires-access-code") flag.Bool(FeatureFlagRoleBasedAuth, false, "Flag (bool) to enable role-based-auth") flag.Bool(FeatureFlagConvertPPMsToGHC, false, "Flag (bool) to enable convert-ppms-to-ghc") }
ApplyOptions applies given opts and returns the resulting Options. This function should not be used directly by end users; it's only exposed as a side effect of Option.
func ApplyOptions(opt ...Option) Options { opts := Options{ MaxTraversalLinks: math.MaxInt64, //default: traverse all MaxAllowedHeaderSize: carv1.DefaultMaxAllowedHeaderSize, MaxAllowedSectionSize: carv1.DefaultMaxAllowedSectionSize, } for _, o := range opt { o(&opts) } // Set defaults for zero valued...
func ApplyOptions(f *pflag.Flag, opts ...FlagOption) { for _, opt := range opts { opt(f) } }
ZeroLengthSectionAsEOF sets whether to allow the CARv1 decoder to treat a zerolength section as the end of the input CAR file. For example, this can be useful to allow "null padding" after a CARv1 without knowing where the padding begins.
func ZeroLengthSectionAsEOF(enable bool) Option { return func(o *Options) { o.ZeroLengthSectionAsEOF = enable } }
func TestReadEmptyAtEOF(t *testing.T) { b := new(Builder) slice := make([]byte, 0) n, err := b.Read(slice) if err != nil { t.Errorf("read error: %v", err) } if n != 0 { t.Errorf("wrong count; got %d want 0", n) } }
UseDataPadding sets the padding to be added between CARv2 header and its data payload on Finalize.
func UseDataPadding(p uint64) Option { return func(o *Options) { o.DataPadding = p } }
func padData(rawData []byte) []byte { needPadding := aes.BlockSize - ((len(rawData) + 2) % aes.BlockSize) var dataBuf bytes.Buffer dataBuf.Grow(2 + len(rawData) + (aes.BlockSize % (len(rawData) + 2))) dataBuf.Write([]byte("|")) dataBuf.Write(rawData) dataBuf.Write([]byte("|")) for i := 0; i < needPadding; i++...
UseIndexPadding sets the padding between data payload and its index on Finalize.
func UseIndexPadding(p uint64) Option { return func(o *Options) { o.IndexPadding = p } }
func (s *BasePlSqlParserListener) ExitUsing_index_clause(ctx *Using_index_clauseContext) {}
UseIndexCodec sets the codec used for index generation.
func UseIndexCodec(c multicodec.Code) Option { return func(o *Options) { o.IndexCodec = c } }
func UseIndex(designDocument, name string) Parameter { return func(pa Parameterizable) { if name == "" { pa.SetParameter("use_index", designDocument) } else { pa.SetParameter("use_index", []string{designDocument, name}) } } }
WithoutIndex flags that no index should be included in generation.
func WithoutIndex() Option { return func(o *Options) { o.IndexCodec = index.CarIndexNone } }
func IndexOptionsNone() IndexOptions { result := IndexOptions{} return result }
StoreIdentityCIDs sets whether to persist sections that are referenced by CIDs with multihash.IDENTITY digest. When writing CAR files with this option, Characteristics.IsFullyIndexed will be set. By default, the blockstore interface will always return true for Has() called with identity CIDs, but when this option is tu...
func StoreIdentityCIDs(b bool) Option { return func(o *Options) { o.StoreIdentityCIDs = b } }
func (cosi *cosiAggregate) StoreIdentities(idents map[string]proto.Message) { for k, v := range idents { point := suite.G2().Point() err := point.UnmarshalBinary(v.(*BdnIdentity).PublicKey) if err != nil { panic(err) } cosi.skipchain.identities[k] = point } }
MaxIndexCidSize specifies the maximum allowed size for indexed CIDs in bytes. Indexing a CID with larger than the allowed size results in ErrCidTooLarge error.
func MaxIndexCidSize(s uint64) Option { return func(o *Options) { o.MaxIndexCidSize = s } }
func (c *Cache) MaxSize() (maxSize int64) { for _, shard := range c.shards { maxSize += shard.maxSize } return int64(bytesToMB(int(maxSize))) }
WithTraversalPrototypeChooser specifies the prototype chooser that should be used when performing traversals in writes from a linksystem.
func WithTraversalPrototypeChooser(t traversal.LinkTargetNodePrototypeChooser) Option { return func(o *Options) { o.TraversalPrototypeChooser = t } }
func NewSocketsTraversalExtension() *SocketsTraversalExtension { return &SocketsTraversalExtension{ SocketsToken: traversalSocketsToken, } }
WithTrustedCAR specifies whether CIDs match the block data as they are read from the CAR files.
func WithTrustedCAR(t bool) Option { return func(o *Options) { o.TrustedCAR = t } }
func isSpecTrustedCASet(proxyConfig *configv1.ProxySpec) bool { return len(proxyConfig.TrustedCA.Name) > 0 }
MaxAllowedHeaderSize overrides the default maximum size (of 32 MiB) that a CARv1 decode (including within a CARv2 container) will allow a header to be without erroring.
func MaxAllowedHeaderSize(max uint64) Option { return func(o *Options) { o.MaxAllowedHeaderSize = max } }
func (s *fseEncoder) maxHeaderSize() uint32 { if s.preDefined { return 0 } if s.useRLE { return 8 } return (((uint32(s.symbolLen) * uint32(s.actualTableLog)) >> 3) + 3) * 8 }
MaxAllowedSectionSize overrides the default maximum size (of 8 MiB) that a CARv1 decode (including within a CARv2 container) will allow a header to be without erroring. Typically IPLD blocks should be under 2 MiB (ideally under 1 MiB), so unless atypical data is expected, this should not be a large value.
func MaxAllowedSectionSize(max uint64) Option { return func(o *Options) { o.MaxAllowedSectionSize = max } }
func MaxAllowedHeaderSize(max uint64) Option { return func(o *Options) { o.MaxAllowedHeaderSize = max } }
WriteAsCarV1 is a write option which makes a CAR interface (blockstore or storage) write the output as a CARv1 only, with no CARv2 header or index. Indexing is used internally during write but is discarded upon finalization. Note that this option only affects the storage interfaces (blockstore or storage), and is ignor...
func WriteAsCarV1(asCarV1 bool) Option { return func(o *Options) { o.WriteAsCarV1 = asCarV1 } }
func (r *RAMOutputStream) WriteToV1(bytes []byte) error { err := r.flush() if err != nil { return err } end := int(r.file.length) pos, buffer, bytesUpto := 0, 0, 0 for pos < end { length := r.bufferSize nextPos := pos + length if nextPos > end { length = end - pos } src := r.file.getBuffer(buffe...
AllowDuplicatePuts is a write option which makes a CAR interface (blockstore or storage) not deduplicate blocks in Put and PutMany. The default is to deduplicate, which matches the current semantics of goipfsblockstore v1. Note that this option only affects the storage interfaces (blockstore or storage), and is ignored...
func AllowDuplicatePuts(allow bool) Option { return func(o *Options) { o.BlockstoreAllowDuplicatePuts = allow } }
func DisallowDuplicateKey() DecodeOption { return func(d *Decoder) error { d.disallowDuplicateKey = true return nil } }
Hours returns the duration as a floating point number of hours.
func (d Duration) Hours() float64 { return time.Duration(d).Hours() }
func (f *Formatter) Hours() string { var format string if f.withoutUnit { format = "%.2f\n" } else { format = "%.2f hours\n" } return fmt.Sprintf(format, f.duration.Hours()) }
Minutes returns the duration as a floating point number of minutes.
func (d Duration) Minutes() float64 { return time.Duration(d).Minutes() }
func (f *Formatter) Minutes() string { var format string if f.withoutUnit { format = "%d\n" } else { format = "%d minutes\n" } return fmt.Sprintf(format, int(f.duration.Minutes())) }
Nanoseconds returns the duration as an integer nanosecond count.
func (d Duration) Nanoseconds() int64 { return time.Duration(d).Nanoseconds() }
func (s Stopwatch) Nanoseconds() int64 { return s.acc.Nanoseconds() }
Seconds returns the duration as a floating point number of seconds.
func (d Duration) Seconds() float64 { return time.Duration(d).Seconds() }
func fseconds(d time.Duration) float64 { return float64(d) / float64(time.Second) }
Returns a string representation of the duration in russian language
func (d Duration) String() (result string) { var seconds, minutes, hours int seconds = int(d.Seconds()) if seconds > 60 { minutes = (seconds - seconds%60) / 60 seconds = seconds % 60 } if minutes > 59 { hours = (minutes - minutes%60) / 60 minutes = minutes - hours*60 result = numberInString(hours, false)...
func (d Duration) String() string { sign := "" if d.Seconds < 0 && d.Nanos > 0 { d.Seconds++ d.Nanos = int(time.Second) - d.Nanos if d.Seconds == 0 { sign = "-" } } timePart := "" if d.Nanos == 0 { timePart = fmt.Sprintf("%s%d", sign, d.Seconds) } else { timePart = fmt.Sprintf("%s%d.%09d", sign, ...
Returns a string representation of the approximate duration in russian language
func (d Duration) StringApproximate() (result string) { var seconds, minutes, hours, days, months, years int seconds = int(d.Seconds()) if seconds > 60 { minutes = int(d.Minutes()) } if minutes > 59 { hours = int(d.Hours()) minutes = minutes - hours*60 } if hours > 24 { days = (hours - hours%24) / 24 h...
func toElapsedLabel(rfc850time string) string { created, err := time.Parse(time.RFC850, rfc850time) if err != nil { log.Fatal(err) } elapsed := time.Now().UTC().Sub(created.UTC()) seconds := elapsed.Seconds() minutes := elapsed.Minutes() hours := elapsed.Hours() days := hours / 24 weeks := days / 7 months :...
AddLabel adds a label to the specified PR or issue
func (fc *fakeClient) AddLabel(owner, repo string, number int, label string) error { fc.added = append(fc.added, label) fc.labels = append(fc.labels, label) return nil }
func (c *client) AddRepoLabel(org, repo, label, description, color string) error { durationLogger := c.log("AddRepoLabel", org, repo, label, description, color) defer durationLogger() _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("/repos/%s/%s/labels", org, repo), accept...
RemoveLabel removes the label from the specified PR or issue
func (fc *fakeClient) RemoveLabel(owner, repo string, number int, label string) error { fc.removed = append(fc.removed, label) // remove from existing labels for k, v := range fc.labels { if label == v { fc.labels = append(fc.labels[:k], fc.labels[k+1:]...) break } } return nil }
func (c *client) RemoveLabel(org, repo string, number int, label string) error { return c.RemoveLabelWithContext(context.Background(), org, repo, number, label) }
GetIssueLabels gets the current labels on the specified PR or issue
func (fc *fakeClient) GetIssueLabels(owner, repo string, number int) ([]github.Label, error) { var la []github.Label for _, l := range fc.labels { la = append(la, github.Label{Name: l}) } return la, nil }
func (c *client) GetIssueLabels(org, repo string, number int) ([]Label, error) { durationLogger := c.log("GetIssueLabels", org, repo, number) defer durationLogger() return c.getLabels(fmt.Sprintf("/repos/%s/%s/issues/%d/labels", org, repo, number), org) }
CreateComment adds and tracks a comment in the client
func (fc *fakeClient) CreateComment(owner, repo string, number int, comment string) error { fc.commentsAdded[number] = append(fc.commentsAdded[number], comment) return nil }
func (s *Server) CreateComment(w http.ResponseWriter, r *http.Request) { ctx := r.Context() b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { http.Error(w, err.Error(), 500) return } var comment Comment if err = json.Unmarshal(b, &comment); err != nil { http.Error(w, err.Error(), 500)...
NumComments counts the number of tracked comments
func (fc *fakeClient) NumComments() int { n := 0 for _, comments := range fc.commentsAdded { n += len(comments) } return n }
func (c *commentsQueryBuilder) Count() (int64, error) { if c.err != nil { return 0, c.err } return c.builder.Count() }
NewOutput instantiates a new output plugin instance publishing to elasticsearch.
func (f elasticsearchOutputPlugin) NewOutput( config *outputs.MothershipConfig, topologyExpire int, ) (outputs.Outputer, error) { // configure bulk size in config in case it is not set if config.BulkMaxSize == nil { bulkSize := defaultBulkSize config.BulkMaxSize = &bulkSize } output := &elasticsearchOutput{...
func (m *Manager) NewOutput(conf loutput.Config, pipelines ...processor.PipelineConstructorFunc) (output.Streamed, error) { return bundle.AllOutputs.Init(conf, m, pipelines...) }
loadTemplate checks if the index mapping template should be loaded In case template loading is enabled, template is written to index
func loadTemplate(config outputs.Template, clients []mode.ProtocolClient) { // Check if template should be loaded // Not being able to load the template will output an error but will not stop execution if config.Name != "" && len(clients) > 0 { // Always takes the first client esClient := clients[0].(*Client) ...
func (t *Pongo2Engine) Load() (err error) { err = recoverTemplateNotFound() if err != nil { return err } // time point t.loadedAt = time.Now() // unnamed root template //var root = template.New("") var walkFunc = func(path string, info os.FileInfo, err error) (_ error) { // handle walking error if any ...
New returns a new PagerDuty notifier.
func New(c *config.PagerdutyConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) { client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "pagerduty", httpOpts...) if err != nil { return nil, err } n := &Notifier{conf: c, tmpl: t, logger: l, client: client} ...
func New(c *config.DingTalkConfig, t *template.Template, l log.Logger) (*Notifier, error) { client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "dingtalk", false, false) if err != nil { return nil, err } return &Notifier{conf: c, tmpl: t, logger: l, client: client}, nil }
Notify implements the Notifier interface.
func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) { key, err := notify.ExtractGroupKey(ctx) if err != nil { return false, err } var ( alerts = types.Alerts(as...) data = notify.GetTemplateData(ctx, n.tmpl, as, n.logger) eventType = pagerDutyEventTrigger ) if alerts....
func (n *Node) notify(rn *comm.Rnode) { if n.prev.ID.IsEqual(n.ID) || rn.ID.IsBetween(n.prev.ID, n.ID) { n.setPredecessor(rn) } if alive, _ := n.remote.IsAlive(*n.prev); !alive { n.setPredecessor(rn) } if n.fingers[0].node.ID.IsEqual(n.ID) { n.setSuccessor(rn) } if len(n.successors) == 1 && n.successors[0...
/ Outgoing connections Using an outgoing connection is a snap. A `net.Conn` satisfies the io.Reader and `io.Writer` interfaces, so we can treat a TCP connection just like any other `Reader` or `Writer`. Open connects to a TCP Address. It returns a TCP connection armed with a timeout and wrapped into a buffered ReadWrit...
func Open(addr string) (*bufio.ReadWriter, error) { // Dial the remote process. // Note that the local port is chosen on the fly. If the local port // must be a specific one, use DialTCP() instead. log.Println("Dial " + addr) conn, err := net.Dial("tcp", addr) if err != nil { return nil, errors.Wrap(err,...
func New(nc net.Conn) (*Conn, error) { // XXX: setting deadline to now + 10 min if err := nc.SetDeadline(time.Now().Add(10 * time.Minute)); err != nil { return nil, err } return &Conn{c: nc, r: bufio.NewReader(nc), w: bufio.NewWriter(nc)}, nil }
NewEndpoint creates a new endpoint. To keep things simple, the endpoint listens on a fixed port number.
func NewEndpoint() *Endpoint { // Create a new Endpoint with an empty list of handler funcs. return &Endpoint{ handler: map[string]HandleFunc{}, } }
func (*protocol) NewEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) { return newEndpoint(stack, netProto, waiterQueue), nil }
AddHandleFunc adds a new function for handling incoming data.
func (e *Endpoint) AddHandleFunc(name string, f HandleFunc) { e.mutex.Lock() e.handler[name] = f e.mutex.Unlock() }
func (l Listener) AddHandler(cmd string, handleFunc func()) { l[cmd] = handleFunc }
Listen starts listening on the endpoint port on all interfaces. At least one handler function must have been added through AddHandleFunc() before.
func (e *Endpoint) Listen() error { var err error e.listener, err = net.Listen("tcp", Port) if err != nil { return errors.Wrapf(err, "Unable to listen on port %s\n", Port) } log.Println("Listen on", e.listener.Addr().String()) for { log.Println("Accept a connection request.") conn, err := e.listene...
func (handler *Handler) Listen() error { return handler.engine.Start(g.GetConfig().ListenAddr) }
handleMessages reads the connection up to the first newline. Based on this string, it calls the appropriate HandleFunc.
func (e *Endpoint) handleMessages(conn net.Conn) { // Wrap the connection into a buffered reader for easier reading. rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)) defer conn.Close() // Read from the connection until EOF. Expect a command name as the // next input. Call the handler ...
func (r *MetricReceiver) handleMessage(addr net.Addr, msg []byte) { buf := bytes.NewBuffer(msg) for { line, readerr := buf.ReadBytes('\n') // protocol does not require line to end in \n, if EOF use received line if valid if readerr != nil && readerr != io.EOF { r.handleError(fmt.Errorf("error reading messag...
/ Now let's create two handler functions. The easiest case is where our adhoc protocol only sends string data. The second handler receives and processes a struct that was sent as GOB data. handleStrings handles the "STRING" request.
func handleStrings(rw *bufio.ReadWriter) { // Receive a string. log.Print("Receive STRING message:") s, err := rw.ReadString('\n') if err != nil { log.Println("Cannot read from connection.\n", err) } s = strings.Trim(s, "\n ") log.Println(s) _, err = rw.WriteString("Thank you.\n") if err != nil { ...
func (serv *Server) handleText(conn int, payload []byte) { var ( logp = `handleText` handler RouteHandler err error ctx context.Context req *Request res *Response ok bool ) res = _resPool.Get().(*Response) res.reset() ctx, ok = serv.Clients.Context(conn) if !ok { err = erro...
handleGob handles the "GOB" request. It decodes the received GOB data into a struct.
func handleGob(rw *bufio.ReadWriter) { log.Print("Receive GOB data:") var data complexData // Create a decoder that decodes directly into a struct variable. dec := gob.NewDecoder(rw) err := dec.Decode(&data) if err != nil { log.Println("Error decoding GOB data:", err) return } // Print the complex...
func (d *Decoder) GOB(val interface{}) { gobd := gob.NewDecoder(d.buf) if err := gobd.Decode(val); err != nil { log.Panicf("gob: failed to decode: %v", err) } }
/ The client and server functions With all this in place, we can now set up client and server functions. The client function connects to the server and sends STRING and GOB requests. The server starts listening for requests and triggers the appropriate handlers. client is called if the app is called with connect=`ip ad...
func client(ip string) error { // Some test data. Note how GOB even handles maps, slices, and // recursive data structures without problems. testStruct := complexData{ N: 23, S: "string data", M: map[string]int{"one": 1, "two": 2, "three": 3}, P: []byte("abc"), C: &complexData{ N: 256, S: "...
func (s *server) handleClient(client *client) { defer client.closeConn() sc := s.configStore.Load().(ServerConfig) s.log().Debugf("Handle client [%s], id: %d", client.RemoteIP, client.ID) // Initial greeting greeting := fmt.Sprintf("220 %s UMBO SMTP #%d (%d) %s", sc.Hostname, client.ID, s.clientPool.GetActive...
server listens for incoming requests and dispatches them to registered handler functions.
func server() error { endpoint := NewEndpoint() // Add the handle funcs. endpoint.AddHandleFunc("STRING", handleStrings) endpoint.AddHandleFunc("GOB", handleGob) // Start listening. return endpoint.Listen() }
func handleRequests() { address := "localhost" address += ":" address += "8000" fmt.Printf("Server at address %v is up\n", "http://"+address) http.HandleFunc("/", homePage) http.HandleFunc("/author", author) http.HandleFunc("/articles", returnAllArticles) log.Fatal(http.ListenAndServe(address, nil)) // nill: u...
/ Main Main starts either a client or a server, depending on whether the `connect` flag is set. Without the flag, the process starts as a server, listening for incoming requests. With the flag the process starts as a client and connects to the host specified by the flag value. Try "localhost" or "127.0.0.1" when runnin...
func main() { connect := flag.String("connect", "", "IP address of process to join. If empty, go into listen mode.") flag.Parse() // If the connect flag is set, go into client mode. if *connect != "" { err := client(*connect) if err != nil { log.Println("Error:", errors.WithStack(err)) } log.P...
func main() { flag.StringVar(&MODE, "mode", MODE, "server/client") flag.StringVar(&SERVER_ADDR, "server", SERVER_ADDR, "mode: server => listen, mode: client => connect to") flag.StringVar(&PayLoad, "pl", PayLoad, "PayLoad") flag.BoolVar(&PrintDump, "d", PrintDump, "Print dump") flag.PrintDefaults() flag.Parse() ...
The Lshortfile flag includes file name and line number in log messages.
func init() { log.SetFlags(log.Lshortfile) }
func StatusShort(c *Client, files []File, untracked StatusUntrackedMode, lineprefix, lineending string) (string, error) { var lsfiles []File if len(files) == 0 { lsfiles = []File{File(c.WorkDir)} } else { lsfiles = files } cfiles, err := LsFiles(c, LsFilesOptions{Cached: true}, lsfiles) if err != nil { ret...
NewHealthController creates a health controller.
func NewHealthController(service *goa.Service) *HealthController { return &HealthController{Controller: service.NewController("HealthController")} }
func NewHealthController() *HealthController { return &HealthController{} }
Health runs the health action.
func (c *HealthController) Health(ctx *app.HealthHealthContext) error { // HealthController_Health: start_implement ver := "unknown" semVer, err := semver.Make(MajorMinorPatch + "-" + ReleaseType + "+git.sha." + GitCommit) if err == nil { ver = semVer.String() } return ctx.OK([]byte("Health OK: " + time.Now().S...
func (cmd *HealthHealthCommand) Run(c *client.Client, args []string) error { var path string if len(args) > 0 { path = args[0] } else { path = "/api/_ah/health" } logger := goa.NewLogger(log.New(os.Stderr, "", log.LstdFlags)) ctx := goa.WithLogger(context.Background(), logger) resp, err := c.HealthHealth(ctx...
NewGenerator starts foreground goroutine which generates sequence of unsigned ints and puts them in input channel, also it returnes stop channel which need to be triggered when generator need to be stopped
func NewGenerator(input chan<- uint) chan<- bool { stop := make(chan bool) go func() { var current uint = 1 for { select { case input <- current: current++ case <-stop: close(input) return } } }() return stop }
func Generator(done chan struct{}) <-chan int { out := make(chan int) go func() { defer close(out) for i, j := 0, 1; ; i, j = j, i+j { select { case out <- i: case <-done: return } } }() return out }
genFields generates fields config for given AST
func genFields(fs []*ast.FieldDefinition) *jen.Statement { // // Generate config for fields // // == Example input SDL // // type Dog { // name(style: NameComponentsStyle = SHORT): String! // givenName: String @deprecated(reason: "No longer supported; please use name field.") // } // // == ...
func (g *Generator) generate(typeName string) { fields := make([]Field, 0, 100) for _, file := range g.pkg.files { // Set the state for this run of the walker. file.typeName = typeName if file.file != nil { ast.Inspect(file.file, file.genDecl) fields = append(fields, file.fields...) } } if len(fields)...
genField generates field config for given AST
func genField(field *ast.FieldDefinition) *jen.Statement { // // Generate config for field // // == Example input SDL // // interface Pet { // "name of the pet" // name(style: NameComponentsStyle = SHORT): String! // """ // givenName of the pet ★ // """ // givenName: String...
func genFields(fs []*ast.FieldDefinition) *jen.Statement { // // Generate config for fields // // == Example input SDL // // type Dog { // name(style: NameComponentsStyle = SHORT): String! // givenName: String @deprecated(reason: "No longer supported; please use name field.") // } // // == ...
genArguments generates argument field config for given AST
func genArguments(args []*ast.InputValueDefinition) *jen.Statement { // // Generate config for arguments // // == Example input SDL // // type Dog { // name( // "style is stylish" // style: NameComponentsStyle = SHORT, // ): String! // } // // == Example output // // Fiel...
func genArgument(arg *ast.InputValueDefinition) *jen.Statement { // // Generate config for argument // // == Example input SDL // // type Dog { // name( // "style is stylish" // style: NameComponentsStyle = SHORT, // ): String! // } // // == Example output // // &Argument...
genArgument generates argument config for given AST
func genArgument(arg *ast.InputValueDefinition) *jen.Statement { // // Generate config for argument // // == Example input SDL // // type Dog { // name( // "style is stylish" // style: NameComponentsStyle = SHORT, // ): String! // } // // == Example output // // &Argument...
func genArguments(args []*ast.InputValueDefinition) *jen.Statement { // // Generate config for arguments // // == Example input SDL // // type Dog { // name( // "style is stylish" // style: NameComponentsStyle = SHORT, // ): String! // } // // == Example output // // Fiel...
AddReceipt adds receipt for user.
func (client Client) AddReceipt(userId string, text string) error { addReceiptUrl := client.backendUrl + "/internal/receipt" request := addReceiptRequest{ReceiptString: text, UserId: userId} reader, err := getReader(request) if err != nil { return err } response, err := http.Post(addReceiptUrl, "text/javascrip...
func (puo *ProductUpdateOne) AddReceipt(r ...*Receipt) *ProductUpdateOne { ids := make([]int, len(r)) for i := range r { ids[i] = r[i].ID } return puo.AddReceiptIDs(ids...) }
MergeUnique Merges `source` string slice into `dest` and returns result. Inserts from `source` only when `dest` does not `Contain` given string.
func MergeUnique(dest, source []string) []string { for _, str := range source { if !Contain(dest, str) { dest = append(dest, str) } } return dest }
func MergeAndDeduplicateSlice(src []string, target []string) []string { m := make(map[string]bool) for i := range src { m[src[i]] = true } for i := range target { if _, ok := m[target[i]]; !ok { src = append(src, target[i]) } } return src }
Validate returns an error if key is empty
func (kv BatchKeyRotateKV) Validate() error { if kv.Key == "" { return errInvalidArgument } return nil }
func (kv BatchJobReplicateKV) Validate() error { if kv.Key == "" { return errInvalidArgument } return nil }
Empty indicates if kv is not set
func (kv BatchKeyRotateKV) Empty() bool { return kv.Key == "" && kv.Value == "" }
func hasNonEmptyKV(kvMap map[string]string) bool { for k, v := range kvMap { if strings.TrimSpace(k) == "" && strings.TrimSpace(v) == "" { return false } } return true }
Match matches input kv with kv, value will be wildcard matched depending on the user input
func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool { if kv.Empty() { return true } if strings.EqualFold(kv.Key, ikv.Key) { return wildcard.Match(kv.Value, ikv.Value) } return false }
func Match(goos, kv, key string) (value string, ok bool) { if len(kv) <= len(key) || kv[len(key)] != '=' { return "", false } if goos == "windows" { // Case insensitive. if !strings.EqualFold(kv[:len(key)], key) { return "", false } } else { // Case sensitive. if kv[:len(key)] != key { return "",...
Validate validates input replicate retries.
func (r BatchKeyRotateRetry) Validate() error { if r.Attempts < 0 { return errInvalidArgument } if r.Delay < 0 { return errInvalidArgument } return nil }
func (r *BatchJobReplicateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error { if r == nil { return nil } if r.APIVersion != batchReplJobAPIVersion { return errInvalidArgument } if r.Source.Bucket == "" { return errInvalidArgument } info, err := o.GetBucketInfo(ctx, r.Source.Buc...
Validate validates input key rotation encryption options.
func (e BatchJobKeyRotateEncryption) Validate() error { if e.Type != sses3 && e.Type != ssekms { return errInvalidArgument } spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ") if e.Type == ssekms && spaces { return crypto.ErrInvalidEncryptionKeyID } if e.Type == ssekms && GlobalKMS != ni...
func (kv BatchKeyRotateKV) Validate() error { if kv.Key == "" { return errInvalidArgument } return nil }
Notify notifies notification endpoint if configured regarding job failure or success.
func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error { if r.Flags.Notify.Endpoint == "" { return nil } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body) if err != nil { ...
func (n *IFTTTNotifier) Notify(msg string) error { req := &utility.HTTPRequest{ URL: fmt.Sprintf("https://maker.ifttt.com/trigger/%s/with/key/%s", EventName, n.Key), } resp, _, err := n.httpClient.DoRequest(utility.HTTPMethodGET, req, false) if err != nil { return err } if resp.StatusCode < 200 || resp.Stat...
KeyRotate rotates encryption key of an object
func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error { srcBucket := r.Bucket srcObject := objInfo.Name if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() { return nil } sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined) sseS3 := crypto.S3.IsEn...
func rotateKey(oldKey []byte, newKey []byte, metadata map[string]string) error { delete(metadata, SSECustomerKey) // make sure we do not save the key by accident if metadata[ServerSideEncryptionSealAlgorithm] != SSESealAlgorithmDareSha256 { // currently DARE-SHA256 is the only option return errObjectTampered } i...
Start the batch key rottion job, resumes if there was a pending job via "job.ID"
func (r *BatchJobKeyRotateV1) Start(ctx context.Context, api ObjectLayer, job BatchJobRequest) error { ri := &batchJobInfo{ JobID: job.ID, JobType: string(job.Type()), StartTime: job.Started, } if err := ri.load(ctx, api, job); err != nil { return err } globalBatchJobsMetrics.save(job.ID, ri) lastO...
func StartJob( ctx context.Context, conn sqlexec.SQLExecutor, jobID int64, ) error { ctx = util.WithInternalSourceType(ctx, kv.InternalLoadData) _, err := conn.ExecuteInternal(ctx, `UPDATE mysql.load_data_jobs SET start_time = CURRENT_TIMESTAMP(6), update_time = CURRENT_TIMESTAMP(6) WHERE job_id = %? AND sta...
Validate validates the job definition input
func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error { if r == nil { return nil } if r.APIVersion != batchKeyRotateAPIVersion { return errInvalidArgument } if r.Bucket == "" { return errInvalidArgument } if _, err := o.GetBucketInfo(ctx, r.Bucket, BucketO...
func (j BatchJobRequest) Validate(ctx context.Context, o ObjectLayer) error { if j.Replicate != nil { return j.Replicate.Validate(ctx, j, o) } return errInvalidArgument }
toGA is an utility method to return the baseInstance data as a GA Instance object
func (bi *baseInstance) toGA() *ga.Instance { inst := &ga.Instance{Name: bi.name, Zone: bi.zone, NetworkInterfaces: []*ga.NetworkInterface{{}}} if bi.aliasRange != "" { inst.NetworkInterfaces[0].AliasIpRanges = []*ga.AliasIpRange{ {IpCidrRange: bi.aliasRange, SubnetworkRangeName: util.TestSecondaryRangeName}, ...
func (bi *baseInstance) toBeta() *beta.Instance { inst := &beta.Instance{Name: bi.name, Zone: bi.zone, NetworkInterfaces: []*beta.NetworkInterface{{}}} if bi.aliasRange != "" { inst.NetworkInterfaces[0].AliasIpRanges = []*beta.AliasIpRange{ {IpCidrRange: bi.aliasRange, SubnetworkRangeName: util.TestSecondaryRang...
toGA is an utility method to return the baseInstance data as a beta Instance object
func (bi *baseInstance) toBeta() *beta.Instance { inst := &beta.Instance{Name: bi.name, Zone: bi.zone, NetworkInterfaces: []*beta.NetworkInterface{{}}} if bi.aliasRange != "" { inst.NetworkInterfaces[0].AliasIpRanges = []*beta.AliasIpRange{ {IpCidrRange: bi.aliasRange, SubnetworkRangeName: util.TestSecondaryRang...
func (e *GT) Base() *GT { if e.p == nil { e.p = &gfP12{} } e.p.Set(gfP12Gen) return e }
newBaseInstanceList is the baseInstanceList constructor
func newBaseInstanceList(allocateCIDR bool, clusterCIDR *net.IPNet, subnetMaskSize int) *baseInstanceList { cidrSet, _ := cidrset.NewCIDRSet(clusterCIDR, subnetMaskSize) return &baseInstanceList{ allocateCIDR: allocateCIDR, clusterCIDR: clusterCIDR, subnetMaskSize: subnetMaskSize, cidrSet: cidrSet...
func newBase() *base { return &base{shared.NewUUID(), time.Now().UTC(), time.Now().UTC(), false/*, shared.NewUUID()*/} }
getOrCreateBaseInstance lazily creates a new base instance, assigning if allocateCIDR is true
func (bil *baseInstanceList) getOrCreateBaseInstance(key *meta.Key) *baseInstance { bil.lock.Lock() defer bil.lock.Unlock() inst, found := bil.instances[*key] if !found { inst = &baseInstance{name: key.Name, zone: key.Zone} if bil.allocateCIDR { nextRange, _ := bil.cidrSet.AllocateNext() inst.aliasRange ...
func newBaseInstanceList(allocateCIDR bool, clusterCIDR *net.IPNet, subnetMaskSize int) *baseInstanceList { cidrSet, _ := cidrset.NewCIDRSet(clusterCIDR, subnetMaskSize) return &baseInstanceList{ allocateCIDR: allocateCIDR, clusterCIDR: clusterCIDR, subnetMaskSize: subnetMaskSize, cidrSet: cidrSet...
newGAGetHook creates a new closure with the current baseInstanceList to be used as a MockInstances.GetHook
func (bil *baseInstanceList) newGAGetHook() func(ctx context.Context, key *meta.Key, m *cloud.MockInstances) (bool, *ga.Instance, error) { return func(ctx context.Context, key *meta.Key, m *cloud.MockInstances) (bool, *ga.Instance, error) { m.Lock.Lock() defer m.Lock.Unlock() if _, found := m.Objects[*key]; !fo...
func (bil *baseInstanceList) newBetaGetHook() func(ctx context.Context, key *meta.Key, m *cloud.MockBetaInstances) (bool, *beta.Instance, error) { return func(ctx context.Context, key *meta.Key, m *cloud.MockBetaInstances) (bool, *beta.Instance, error) { m.Lock.Lock() defer m.Lock.Unlock() if _, found := m.Obje...
newBetaGetHook creates a new closure with the current baseInstanceList to be used as a MockBetaInstances.GetHook
func (bil *baseInstanceList) newBetaGetHook() func(ctx context.Context, key *meta.Key, m *cloud.MockBetaInstances) (bool, *beta.Instance, error) { return func(ctx context.Context, key *meta.Key, m *cloud.MockBetaInstances) (bool, *beta.Instance, error) { m.Lock.Lock() defer m.Lock.Unlock() if _, found := m.Obje...
func (bil *baseInstanceList) newGAGetHook() func(ctx context.Context, key *meta.Key, m *cloud.MockInstances) (bool, *ga.Instance, error) { return func(ctx context.Context, key *meta.Key, m *cloud.MockInstances) (bool, *ga.Instance, error) { m.Lock.Lock() defer m.Lock.Unlock() if _, found := m.Objects[*key]; !fo...
newMockCloud returns a mock GCE instance with the appropriate handlers hooks
func (bil *baseInstanceList) newMockCloud() cloud.Cloud { c := cloud.NewMockGCE(nil) // insert hooks to lazy create a instance when needed c.MockInstances.GetHook = bil.newGAGetHook() c.MockBetaInstances.GetHook = bil.newBetaGetHook() return c }
func NewCloudMock() *CloudMock { address, grpcServer, mockTrace := startMockServer() conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %s", err) } traceClient := cloudtrace.NewTraceServiceClient(conn) metricClient := monitoring.NewMetricServiceClient(conn) retu...
Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.
func Asset(name string) ([]byte, error) { canonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) } return a.bytes, nil } return nil, fmt.Errorf("Asset %s not found"...
func Asset(name string) ([]byte, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) } return a.bytes, nil } return nil, fmt.Errorf("Asset %s not foun...
MustAssetString is like AssetString but panics when Asset would return an error. It simplifies safe initialization of global variables.
func MustAssetString(name string) string { return string(MustAsset(name)) }
func AssetString(name string) (string, error) { data, err := Asset(name) return string(data), err }
AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.
func AssetInfo(name string) (os.FileInfo, error) { canonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) } return a.info, nil } return nil, fmt.Errorf("AssetIn...
func AssetInfo(name string) (os.FileInfo, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) } return a.info, nil } return nil, fmt.Errorf("Asset...
End of preview. Expand in Data Studio

cornstack-hard-negatives

2,399,994 (anchor, positive, negative) triplets from CornStack, 400k per language (Go, Java, JavaScript, PHP, Python, Ruby), used to train blink-code-16M. For each pair, the negative is the highest-scoring of CornStack's mined negatives that still scores below the document (higher ones are likely false negatives).

The triplets are cleaned against the CoIR test sets: we drop every triplet whose anchor is a CoIR test query, or whose positive or negative is a relevant CoIR test document (after whitespace normalization).

Downloads last month
164

Models trained or fine-tuned on minishlab/cornstack-hard-negatives