_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q18100
SendHostEvent
train
func SendHostEvent(title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Duration: int(duration / time.Millisecond), Severity: int(sev), }) }
go
{ "resource": "" }
q18101
NewTracerWithOptions
train
func NewTracerWithOptions(options *Options) ot.Tracer { InitSensor(options) return NewTracerWithEverything(options, NewRecorder()) }
go
{ "resource": "" }
q18102
NewTracerWithEverything
train
func NewTracerWithEverything(options *Options, recorder SpanRecorder) ot.Tracer { InitSensor(options) ret := &tracerS{options: TracerOptions{ Recorder: recorder, ShouldSample: shouldSample, MaxLogsPerSpan: MaxLogsPerSpan}} ret.textPropagator = &textMapPropagator{ret} return ret }
go
{ "resource": "" }
q18103
RecordSpan
train
func (r *Recorder) RecordSpan(span *spanS) { // If we're not announced and not in test mode then just // return if !r.testMode && !sensor.agent.canSend() { return } var data = &jsonData{} kindTag := span.getSpanKindTag() data.SDK = &jsonSDKData{ Name: span.Operation, Type: kindTag, Custom: &jsonCustomData{Tags: span.Tags, Logs: span.collectLogs()}} baggage := make(map[string]string) span.context.ForeachBaggageItem(func(k string, v string) bool { baggage[k] = v return true }) if len(baggage) > 0 { data.SDK.Custom.Baggage = baggage } data.Service = sensor.serviceName var parentID *int64 if span.ParentSpanID == 0 { parentID = nil } else { parentID = &span.ParentSpanID } r.Lock() defer r.Unlock() if len(r.spans) == sensor.options.MaxBufferedSpans { r.spans = r.spans[1:] } r.spans = append(r.spans, jsonSpan{ TraceID: span.context.TraceID, ParentID: parentID, SpanID: span.context.SpanID, Timestamp: uint64(span.Start.UnixNano()) / uint64(time.Millisecond), Duration: uint64(span.Duration) / uint64(time.Millisecond), Name: "sdk", Error: span.Error, Ec: span.Ec, Lang: "go", From: sensor.agent.from, Kind: span.getSpanKindInt(), Data: data}) if r.testMode || !sensor.agent.canSend() { return } if len(r.spans) >= sensor.options.ForceTransmissionStartingAt { log.debug("Forcing spans to agent. Count:", len(r.spans)) go r.send() } }
go
{ "resource": "" }
q18104
QueuedSpansCount
train
func (r *Recorder) QueuedSpansCount() int { r.RLock() defer r.RUnlock() return len(r.spans) }
go
{ "resource": "" }
q18105
GetQueuedSpans
train
func (r *Recorder) GetQueuedSpans() []jsonSpan { r.Lock() defer r.Unlock() // Copy queued spans queuedSpans := make([]jsonSpan, len(r.spans)) copy(queuedSpans, r.spans) // and clear out the source r.clearQueuedSpans() return queuedSpans }
go
{ "resource": "" }
q18106
send
train
func (r *Recorder) send() { spansToSend := r.GetQueuedSpans() if len(spansToSend) > 0 { go func() { _, err := sensor.agent.request(sensor.agent.makeURL(agentTracesURL), "POST", spansToSend) if err != nil { log.debug("Posting traces failed in send(): ", err) sensor.agent.reset() } }() } }
go
{ "resource": "" }
q18107
CutText
train
func (c *ClientConn) CutText(text string) error { var buf bytes.Buffer // This is the fixed size data we'll send fixedData := []interface{}{ uint8(6), uint8(0), uint8(0), uint8(0), uint32(len(text)), } for _, val := range fixedData { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } for _, char := range text { if char > unicode.MaxLatin1 { return fmt.Errorf("Character '%s' is not valid Latin-1", char) } if err := binary.Write(&buf, binary.BigEndian, uint8(char)); err != nil { return err } } dataLength := 8 + len(text) if _, err := c.c.Write(buf.Bytes()[0:dataLength]); err != nil { return err } return nil }
go
{ "resource": "" }
q18108
FramebufferUpdateRequest
train
func (c *ClientConn) FramebufferUpdateRequest(incremental bool, x, y, width, height uint16) error { var buf bytes.Buffer var incrementalByte uint8 = 0 if incremental { incrementalByte = 1 } data := []interface{}{ uint8(3), incrementalByte, x, y, width, height, } for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } if _, err := c.c.Write(buf.Bytes()[0:10]); err != nil { return err } return nil }
go
{ "resource": "" }
q18109
KeyEvent
train
func (c *ClientConn) KeyEvent(keysym uint32, down bool) error { var downFlag uint8 = 0 if down { downFlag = 1 } data := []interface{}{ uint8(4), downFlag, uint8(0), uint8(0), keysym, } for _, val := range data { if err := binary.Write(c.c, binary.BigEndian, val); err != nil { return err } } return nil }
go
{ "resource": "" }
q18110
PointerEvent
train
func (c *ClientConn) PointerEvent(mask ButtonMask, x, y uint16) error { var buf bytes.Buffer data := []interface{}{ uint8(5), uint8(mask), x, y, } for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } if _, err := c.c.Write(buf.Bytes()[0:6]); err != nil { return err } return nil }
go
{ "resource": "" }
q18111
SetEncodings
train
func (c *ClientConn) SetEncodings(encs []Encoding) error { data := make([]interface{}, 3+len(encs)) data[0] = uint8(2) data[1] = uint8(0) data[2] = uint16(len(encs)) for i, enc := range encs { data[3+i] = int32(enc.Type()) } var buf bytes.Buffer for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } dataLength := 4 + (4 * len(encs)) if _, err := c.c.Write(buf.Bytes()[0:dataLength]); err != nil { return err } c.Encs = encs return nil }
go
{ "resource": "" }
q18112
SetPixelFormat
train
func (c *ClientConn) SetPixelFormat(format *PixelFormat) error { var keyEvent [20]byte keyEvent[0] = 0 pfBytes, err := writePixelFormat(format) if err != nil { return err } // Copy the pixel format bytes into the proper slice location copy(keyEvent[4:], pfBytes) // Send the data down the connection if _, err := c.c.Write(keyEvent[:]); err != nil { return err } // Reset the color map as according to RFC. var newColorMap [256]Color c.ColorMap = newColorMap return nil }
go
{ "resource": "" }
q18113
mainLoop
train
func (c *ClientConn) mainLoop() { defer c.Close() // Build the map of available server messages typeMap := make(map[uint8]ServerMessage) defaultMessages := []ServerMessage{ new(FramebufferUpdateMessage), new(SetColorMapEntriesMessage), new(BellMessage), new(ServerCutTextMessage), } for _, msg := range defaultMessages { typeMap[msg.Type()] = msg } if c.config.ServerMessages != nil { for _, msg := range c.config.ServerMessages { typeMap[msg.Type()] = msg } } for { var messageType uint8 if err := binary.Read(c.c, binary.BigEndian, &messageType); err != nil { break } msg, ok := typeMap[messageType] if !ok { // Unsupported message type! Bad! break } parsedMsg, err := msg.Read(c, c.c) if err != nil { break } if c.config.ServerMessageCh == nil { continue } c.config.ServerMessageCh <- parsedMsg } }
go
{ "resource": "" }
q18114
unixDialer
train
func (w *Writer) unixDialer() (serverConn, string, error) { sc, err := unixSyslog() hostname := w.hostname if hostname == "" { hostname = "localhost" } return sc, hostname, err }
go
{ "resource": "" }
q18115
tlsDialer
train
func (w *Writer) tlsDialer() (serverConn, string, error) { c, err := tls.Dial("tcp", w.raddr, w.tlsConfig) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
go
{ "resource": "" }
q18116
basicDialer
train
func (w *Writer) basicDialer() (serverConn, string, error) { c, err := net.Dial(w.network, w.raddr) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
go
{ "resource": "" }
q18117
customDialer
train
func (w *Writer) customDialer() (serverConn, string, error) { c, err := w.customDial(w.network, w.raddr) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
go
{ "resource": "" }
q18118
getConn
train
func (w *Writer) getConn() serverConn { w.mu.RLock() conn := w.conn w.mu.RUnlock() return conn }
go
{ "resource": "" }
q18119
setConn
train
func (w *Writer) setConn(c serverConn) { w.mu.Lock() w.conn = c w.mu.Unlock() }
go
{ "resource": "" }
q18120
connect
train
func (w *Writer) connect() (serverConn, error) { conn := w.getConn() if conn != nil { // ignore err from close, it makes sense to continue anyway conn.close() w.setConn(nil) } var hostname string var err error dialer := w.getDialer() conn, hostname, err = dialer.Call() if err == nil { w.setConn(conn) w.hostname = hostname return conn, nil } else { return nil, err } }
go
{ "resource": "" }
q18121
WriteWithPriority
train
func (w *Writer) WriteWithPriority(p Priority, b []byte) (int, error) { return w.writeAndRetryWithPriority(p, string(b)) }
go
{ "resource": "" }
q18122
writeAndRetry
train
func (w *Writer) writeAndRetry(severity Priority, s string) (int, error) { pr := (w.priority & facilityMask) | (severity & severityMask) return w.writeAndRetryWithPriority(pr, s) }
go
{ "resource": "" }
q18123
writeAndRetryWithPriority
train
func (w *Writer) writeAndRetryWithPriority(p Priority, s string) (int, error) { conn := w.getConn() if conn != nil { if n, err := w.write(conn, p, s); err == nil { return n, err } } var err error if conn, err = w.connect(); err != nil { return 0, err } return w.write(conn, p, s) }
go
{ "resource": "" }
q18124
write
train
func (w *Writer) write(conn serverConn, p Priority, msg string) (int, error) { // ensure it ends in a \n if !strings.HasSuffix(msg, "\n") { msg += "\n" } err := conn.writeString(w.framer, w.formatter, p, w.hostname, w.tag, msg) if err != nil { return 0, err } // Note: return the length of the input, not the number of // bytes printed by Fprintf, because this must behave like // an io.Writer. return len(msg), nil }
go
{ "resource": "" }
q18125
writeString
train
func (n *netConn) writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, msg string) error { if framer == nil { framer = DefaultFramer } if formatter == nil { formatter = DefaultFormatter } formattedMessage := framer(formatter(p, hostname, tag, msg)) _, err := n.conn.Write([]byte(formattedMessage)) return err }
go
{ "resource": "" }
q18126
UnixFormatter
train
func UnixFormatter(p Priority, hostname, tag, content string) string { timestamp := time.Now().Format(time.Stamp) msg := fmt.Sprintf("<%d>%s %s[%d]: %s", p, timestamp, tag, os.Getpid(), content) return msg }
go
{ "resource": "" }
q18127
truncateStartStr
train
func truncateStartStr(s string, max int) string { if (len(s) > max) { return s[len(s) - max:] } return s }
go
{ "resource": "" }
q18128
RFC5424Formatter
train
func RFC5424Formatter(p Priority, hostname, tag, content string) string { timestamp := time.Now().Format(time.RFC3339) pid := os.Getpid() appName := truncateStartStr(os.Args[0], appNameMaxLength) msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s", p, 1, timestamp, hostname, appName, pid, tag, content) return msg }
go
{ "resource": "" }
q18129
Dial
train
func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) { return DialWithTLSConfig(network, raddr, priority, tag, nil) }
go
{ "resource": "" }
q18130
DialWithCustomDialer
train
func DialWithCustomDialer(network, raddr string, priority Priority, tag string, customDial DialFunc) (*Writer, error) { if customDial == nil { return nil, ErrNilDialFunc } return dialAllParameters(network, raddr, priority, tag, nil, customDial) }
go
{ "resource": "" }
q18131
DialWithTLSCertPath
train
func DialWithTLSCertPath(network, raddr string, priority Priority, tag, certPath string) (*Writer, error) { serverCert, err := ioutil.ReadFile(certPath) if err != nil { return nil, err } return DialWithTLSCert(network, raddr, priority, tag, serverCert) }
go
{ "resource": "" }
q18132
DialWithTLSCert
train
func DialWithTLSCert(network, raddr string, priority Priority, tag string, serverCert []byte) (*Writer, error) { pool := x509.NewCertPool() pool.AppendCertsFromPEM(serverCert) config := tls.Config{ RootCAs: pool, } return DialWithTLSConfig(network, raddr, priority, tag, &config) }
go
{ "resource": "" }
q18133
DialWithTLSConfig
train
func DialWithTLSConfig(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config) (*Writer, error) { return dialAllParameters(network, raddr, priority, tag, tlsConfig, nil) }
go
{ "resource": "" }
q18134
dialAllParameters
train
func dialAllParameters(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config, customDial DialFunc) (*Writer, error) { if err := validatePriority(priority); err != nil { return nil, err } if tag == "" { tag = os.Args[0] } hostname, _ := os.Hostname() w := &Writer{ priority: priority, tag: tag, hostname: hostname, network: network, raddr: raddr, tlsConfig: tlsConfig, customDial: customDial, } _, err := w.connect() if err != nil { return nil, err } return w, err }
go
{ "resource": "" }
q18135
NewLogger
train
func NewLogger(p Priority, logFlag int) (*log.Logger, error) { s, err := New(p, "") if err != nil { return nil, err } return log.New(s, "", logFlag), nil }
go
{ "resource": "" }
q18136
unixSyslog
train
func unixSyslog() (conn serverConn, err error) { logTypes := []string{"unixgram", "unix"} logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"} for _, network := range logTypes { for _, path := range logPaths { conn, err := net.Dial(network, path) if err != nil { continue } else { return &localConn{conn: conn}, nil } } } return nil, errors.New("Unix syslog delivery error") }
go
{ "resource": "" }
q18137
GetSocketFromTCPConnection
train
func GetSocketFromTCPConnection(ctx context.Context, dsn string) (socket string, err error) { db, err := sql.Open("mysql", dsn) if err != nil { return "", ErrNoSocket } defer db.Close() err = db.QueryRowContext(ctx, "SELECT @@socket").Scan(socket) if err != nil { return "", ErrNoSocket } if !path.IsAbs(socket) { return "", ErrNoSocket } if socket != "" { return socket, nil } return "", ErrNoSocket }
go
{ "resource": "" }
q18138
GetSocket
train
func GetSocket(ctx context.Context, dsn string) (string, error) { var socket string var err error socket, err = GetSocketFromTCPConnection(ctx, dsn) if err != nil { socket, err = GetSocketFromProcessList(ctx) if err != nil { socket, err = GetSocketFromNetstat(ctx) } } return socket, err }
go
{ "resource": "" }
q18139
AddEvent
train
func (a *Aggregator) AddEvent(event *log.Event, id, fingerprint string) { if a.rateLimit != event.RateLimit { a.rateLimit = event.RateLimit } outlier := false if a.outlierTime > 0 && event.TimeMetrics["Query_time"] > a.outlierTime { outlier = true } a.global.AddEvent(event, outlier) class, ok := a.classes[id] if !ok { class = NewClass(id, fingerprint, a.samples) a.classes[id] = class } class.AddEvent(event, outlier) }
go
{ "resource": "" }
q18140
Finalize
train
func (a *Aggregator) Finalize() Result { a.global.Finalize(a.rateLimit) a.global.UniqueQueries = uint(len(a.classes)) for _, class := range a.classes { class.Finalize(a.rateLimit) class.UniqueQueries = 1 if class.Example != nil && class.Example.Ts != "" { if t, err := time.Parse("2006-01-02 15:04:05", class.Example.Ts); err != nil { class.Example.Ts = "" } else { class.Example.Ts = t.Add(a.utcOffset).Format("2006-01-02 15:04:05") } } } return Result{ Global: a.global, Class: a.classes, RateLimit: a.rateLimit, } }
go
{ "resource": "" }
q18141
NewSlowLogParser
train
func NewSlowLogParser(file *os.File, opt log.Options) *SlowLogParser { if opt.DefaultLocation == nil { // Old MySQL format assumes time is taken from SYSTEM. opt.DefaultLocation = time.Local } p := &SlowLogParser{ file: file, opt: opt, // -- stopChan: make(chan bool, 1), eventChan: make(chan *log.Event), inHeader: false, inQuery: false, headerLines: 0, queryLines: 0, lineOffset: 0, bytesRead: opt.StartOffset, event: log.NewEvent(), } return p }
go
{ "resource": "" }
q18142
Stop
train
func (p *SlowLogParser) Stop() { if p.opt.Debug { l.Println("stopping") } p.stopChan <- true return }
go
{ "resource": "" }
q18143
Start
train
func (p *SlowLogParser) Start() error { if p.opt.Debug { l.SetFlags(l.Ltime | l.Lmicroseconds) fmt.Println() l.Println("parsing " + p.file.Name()) } // Seek to the offset, if any. // @todo error if start off > file size if p.opt.StartOffset > 0 { if _, err := p.file.Seek(int64(p.opt.StartOffset), os.SEEK_SET); err != nil { return err } } defer close(p.eventChan) r := bufio.NewReader(p.file) SCANNER_LOOP: for !p.stopped { select { case <-p.stopChan: p.stopped = true break SCANNER_LOOP default: } line, err := r.ReadString('\n') if err != nil { if err != io.EOF { return err } break SCANNER_LOOP } lineLen := uint64(len(line)) p.bytesRead += lineLen p.lineOffset = p.bytesRead - lineLen if p.opt.Debug { fmt.Println() l.Printf("+%d line: %s", p.lineOffset, line) } // Filter out meta lines: // /usr/local/bin/mysqld, Version: 5.6.15-62.0-tokudb-7.1.0-tokudb-log (binary). started with: // Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock // Time Id Command Argument if lineLen >= 20 && ((line[0] == '/' && line[lineLen-6:lineLen] == "with:\n") || (line[0:5] == "Time ") || (line[0:4] == "Tcp ") || (line[0:4] == "TCP ")) { if p.opt.Debug { l.Println("meta") } continue } // PMM-1834: Filter out empty comments and MariaDB explain: if line == "#\n" || strings.HasPrefix(line, "# explain:") { continue } // Remove \n. line = line[0 : lineLen-1] if p.inHeader { p.parseHeader(line) } else if p.inQuery { p.parseQuery(line) } else if headerRe.MatchString(line) { p.inHeader = true p.inQuery = false p.parseHeader(line) } } if !p.stopped && p.queryLines > 0 { p.endOffset = p.bytesRead p.sendEvent(false, false) } if p.opt.Debug { l.Printf("\ndone") } return nil }
go
{ "resource": "" }
q18144
NewClass
train
func NewClass(id, fingerprint string, sample bool) *Class { class := &Class{ Id: id, Fingerprint: fingerprint, Metrics: NewMetrics(), TotalQueries: 0, Example: &Example{}, sample: sample, } return class }
go
{ "resource": "" }
q18145
AddEvent
train
func (c *Class) AddEvent(e *log.Event, outlier bool) { if outlier { c.outliers++ } else { c.TotalQueries++ } c.Metrics.AddEvent(e, outlier) // Save last db seen for this query. This helps ensure the sample query // has a db. if e.Db != "" { c.lastDb = e.Db } if c.sample { if n, ok := e.TimeMetrics["Query_time"]; ok { if float64(n) > c.Example.QueryTime { c.Example.QueryTime = float64(n) c.Example.Size = len(e.Query) if e.Db != "" { c.Example.Db = e.Db } else { c.Example.Db = c.lastDb } if len(e.Query) > MaxExampleBytes { c.Example.Query = e.Query[0:MaxExampleBytes-len(TruncatedExampleSuffix)] + TruncatedExampleSuffix } else { c.Example.Query = e.Query } if !e.Ts.IsZero() { // todo use time.RFC3339Nano instead c.Example.Ts = e.Ts.UTC().Format("2006-01-02 15:04:05") } } } } }
go
{ "resource": "" }
q18146
AddClass
train
func (c *Class) AddClass(newClass *Class) { c.UniqueQueries++ c.TotalQueries += newClass.TotalQueries c.Example = nil for newMetric, newStats := range newClass.Metrics.TimeMetrics { stats, ok := c.Metrics.TimeMetrics[newMetric] if !ok { m := *newStats c.Metrics.TimeMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum stats.Avg = Float64(stats.Sum / float64(c.TotalQueries)) if Float64Value(newStats.Min) < Float64Value(stats.Min) || stats.Min == nil { stats.Min = newStats.Min } if Float64Value(newStats.Max) > Float64Value(stats.Max) || stats.Max == nil { stats.Max = newStats.Max } } } for newMetric, newStats := range newClass.Metrics.NumberMetrics { stats, ok := c.Metrics.NumberMetrics[newMetric] if !ok { m := *newStats c.Metrics.NumberMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum stats.Avg = Uint64(stats.Sum / uint64(c.TotalQueries)) if Uint64Value(newStats.Min) < Uint64Value(stats.Min) || stats.Min == nil { stats.Min = newStats.Min } if Uint64Value(newStats.Max) > Uint64Value(stats.Max) || stats.Max == nil { stats.Max = newStats.Max } } } for newMetric, newStats := range newClass.Metrics.BoolMetrics { stats, ok := c.Metrics.BoolMetrics[newMetric] if !ok { m := *newStats c.Metrics.BoolMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum } } }
go
{ "resource": "" }
q18147
Finalize
train
func (c *Class) Finalize(rateLimit uint) { if rateLimit == 0 { rateLimit = 1 } c.TotalQueries = (c.TotalQueries * rateLimit) + c.outliers c.Metrics.Finalize(rateLimit, c.TotalQueries) if c.Example.QueryTime == 0 { c.Example = nil } }
go
{ "resource": "" }
q18148
NewEvent
train
func NewEvent() *Event { event := new(Event) event.TimeMetrics = make(map[string]float64) event.NumberMetrics = make(map[string]uint64) event.BoolMetrics = make(map[string]bool) return event }
go
{ "resource": "" }
q18149
Id
train
func Id(fingerprint string) string { id := md5.New() io.WriteString(id, fingerprint) h := fmt.Sprintf("%x", id.Sum(nil)) return strings.ToUpper(h[16:32]) }
go
{ "resource": "" }
q18150
NewMetrics
train
func NewMetrics() *Metrics { m := &Metrics{ TimeMetrics: make(map[string]*TimeStats), NumberMetrics: make(map[string]*NumberStats), BoolMetrics: make(map[string]*BoolStats), } return m }
go
{ "resource": "" }
q18151
AddEvent
train
func (m *Metrics) AddEvent(e *log.Event, outlier bool) { for metric, val := range e.TimeMetrics { stats, seenMetric := m.TimeMetrics[metric] if !seenMetric { m.TimeMetrics[metric] = &TimeStats{ vals: []float64{}, } stats = m.TimeMetrics[metric] } if outlier { stats.outlierSum += val } else { stats.Sum += val } stats.vals = append(stats.vals, float64(val)) } for metric, val := range e.NumberMetrics { stats, seenMetric := m.NumberMetrics[metric] if !seenMetric { m.NumberMetrics[metric] = &NumberStats{ vals: []uint64{}, } stats = m.NumberMetrics[metric] } if outlier { stats.outlierSum += val } else { stats.Sum += val } stats.vals = append(stats.vals, val) } for metric, val := range e.BoolMetrics { stats, seenMetric := m.BoolMetrics[metric] if !seenMetric { stats = &BoolStats{} m.BoolMetrics[metric] = stats } if val { if outlier { stats.outlierSum += 1 } else { stats.Sum += 1 } } } }
go
{ "resource": "" }
q18152
Finalize
train
func (m *Metrics) Finalize(rateLimit uint, totalQueries uint) { if rateLimit == 0 { rateLimit = 1 } for _, s := range m.TimeMetrics { sort.Float64s(s.vals) cnt := len(s.vals) s.Min = Float64(s.vals[0]) s.Med = Float64(s.vals[(50*cnt)/100]) // median = 50th percentile s.P95 = Float64(s.vals[(95*cnt)/100]) s.Max = Float64(s.vals[cnt-1]) s.Sum = (s.Sum * float64(rateLimit)) + s.outlierSum s.Avg = Float64(s.Sum / float64(totalQueries)) } for _, s := range m.NumberMetrics { sort.Sort(byUint64(s.vals)) cnt := len(s.vals) s.Min = Uint64(s.vals[0]) s.Med = Uint64(s.vals[(50*cnt)/100]) // median = 50th percentile s.P95 = Uint64(s.vals[(95*cnt)/100]) s.Max = Uint64(s.vals[cnt-1]) s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum s.Avg = Uint64(s.Sum / uint64(totalQueries)) } for _, s := range m.BoolMetrics { s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum } }
go
{ "resource": "" }
q18153
String
train
func (v SensorType) String() string { if v == DHT11 { return "DHT11" } else if v == DHT12 { return "DHT12" } else if v == DHT22 || v == AM2302 { return "DHT22|AM2302" } else { return "!!! unknown !!!" } }
go
{ "resource": "" }
q18154
GetHandshakeDuration
train
func (v SensorType) GetHandshakeDuration() time.Duration { if v == DHT11 { return 18 * time.Millisecond } else if v == DHT12 { return 200 * time.Millisecond } else if v == DHT22 || v == AM2302 { return 18 * time.Millisecond } else { return 0 } }
go
{ "resource": "" }
q18155
dialDHTxxAndGetResponse
train
func dialDHTxxAndGetResponse(pin int, handshakeDur time.Duration, boostPerfFlag bool) ([]Pulse, error) { var arr *C.int32_t var arrLen C.int32_t var list []int32 var hsDurUsec C.int32_t = C.int32_t(handshakeDur / time.Microsecond) var boost C.int32_t = 0 var err2 *C.Error if boostPerfFlag { boost = 1 } // return array: [pulse, duration, pulse, duration, ...] r := C.dial_DHTxx_and_read(C.int32_t(pin), hsDurUsec, boost, &arr, &arrLen, &err2) if r == -1 { var err error if err2 != nil { msg := C.GoString(err2.message) err = errors.New(spew.Sprintf("Error during call C.dial_DHTxx_and_read(): %v", msg)) C.free_error(err2) } else { err = errors.New(spew.Sprintf("Error during call C.dial_DHTxx_and_read()")) } return nil, err } defer C.free(unsafe.Pointer(arr)) // convert original C array arr to Go slice list h := (*reflect.SliceHeader)(unsafe.Pointer(&list)) h.Data = uintptr(unsafe.Pointer(arr)) h.Len = int(arrLen) h.Cap = int(arrLen) pulses := make([]Pulse, len(list)/2) // convert original int array ([pulse, duration, pulse, duration, ...]) // to Pulse struct array for i := 0; i < len(list)/2; i++ { var value byte = 0 if list[i*2] != 0 { value = 1 } pulses[i] = Pulse{Value: value, Duration: time.Duration(list[i*2+1]) * time.Microsecond} } return pulses, nil }
go
{ "resource": "" }
q18156
decodeByte
train
func decodeByte(tLow, tHigh0, tHigh1 time.Duration, start int, pulses []Pulse) (byte, error) { if len(pulses)-start < 16 { return 0, fmt.Errorf("Can't decode byte, since range between "+ "index and array length is less than 16: %d, %d", start, len(pulses)) } HIGH_DUR_MAX := tLow + tHigh1 HIGH_LOW_DUR_AVG := ((tLow+tHigh1)/2 + (tLow+tHigh0)/2) / 2 var b int = 0 for i := 0; i < 8; i++ { pulseL := pulses[start+i*2] pulseH := pulses[start+i*2+1] if pulseL.Value != 0 { return 0, fmt.Errorf("Low edge value expected at index %d", start+i*2) } if pulseH.Value == 0 { return 0, fmt.Errorf("High edge value expected at index %d", start+i*2+1) } // const HIGH_DUR_MAX = (70 + (70 + 54)) / 2 * time.Microsecond // Calc average value between 24us (bit 0) and 70us (bit 1). // Everything that less than this param is bit 0, bigger - bit 1. // const HIGH_LOW_DUR_AVG = (24 + (70-24)/2) * time.Microsecond if pulseH.Duration > HIGH_DUR_MAX { return 0, fmt.Errorf("High edge value duration %v exceed "+ "maximum expected %v", pulseH.Duration, HIGH_DUR_MAX) } if pulseH.Duration > HIGH_LOW_DUR_AVG { //fmt.Printf("bit %d is high\n", 7-i) b = b | (1 << uint(7-i)) } } return byte(b), nil }
go
{ "resource": "" }
q18157
toMasks
train
func toMasks(ips []string) (masks []net.IPNet, err error) { for _, cidr := range ips { var network *net.IPNet _, network, err = net.ParseCIDR(cidr) if err != nil { return } masks = append(masks, *network) } return }
go
{ "resource": "" }
q18158
ipInMasks
train
func ipInMasks(ip net.IP, masks []net.IPNet) bool { for _, mask := range masks { if mask.Contains(ip) { return true } } return false }
go
{ "resource": "" }
q18159
IsPublicIP
train
func IsPublicIP(ip net.IP) bool { if !ip.IsGlobalUnicast() { return false } return !ipInMasks(ip, privateMasks) }
go
{ "resource": "" }
q18160
Parse
train
func Parse(ipList string) string { for _, ip := range strings.Split(ipList, ",") { ip = strings.TrimSpace(ip) if IP := net.ParseIP(ip); IP != nil && IsPublicIP(IP) { return ip } } return "" }
go
{ "resource": "" }
q18161
GetRemoteAddr
train
func GetRemoteAddr(r *http.Request) string { return GetRemoteAddrIfAllowed(r, func(sip string) bool { return true }) }
go
{ "resource": "" }
q18162
GetRemoteAddrIfAllowed
train
func GetRemoteAddrIfAllowed(r *http.Request, allowed func(sip string) bool) string { if xffh := r.Header.Get("X-Forwarded-For"); xffh != "" { if sip, sport, err := net.SplitHostPort(r.RemoteAddr); err == nil && sip != "" { if allowed(sip) { if xip := Parse(xffh); xip != "" { return net.JoinHostPort(xip, sport) } } } } return r.RemoteAddr }
go
{ "resource": "" }
q18163
New
train
func New(options Options) (*XFF, error) { allowedMasks, err := toMasks(options.AllowedSubnets) if err != nil { return nil, err } xff := &XFF{ allowAll: len(options.AllowedSubnets) == 0, allowedMasks: allowedMasks, } if options.Debug { xff.Log = log.New(os.Stdout, "[xff] ", log.LstdFlags) } return xff, nil }
go
{ "resource": "" }
q18164
Handler
train
func (xff *XFF) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed) h.ServeHTTP(w, r) }) }
go
{ "resource": "" }
q18165
ServeHTTP
train
func (xff *XFF) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed) next(w, r) }
go
{ "resource": "" }
q18166
allowed
train
func (xff *XFF) allowed(sip string) bool { if xff.allowAll { return true } else if ip := net.ParseIP(sip); ip != nil && ipInMasks(ip, xff.allowedMasks) { return true } return false }
go
{ "resource": "" }
q18167
Errorf
train
func Errorf(t *testing.T, format string, args ...interface{}) { t.Error(Scolorf(ErrorColorSyntaxCode, format, args...)) }
go
{ "resource": "" }
q18168
Fatalf
train
func Fatalf(t *testing.T, format string, args ...interface{}) { t.Fatal(Scolorf(FatalColorSyntaxCode, format, args...)) }
go
{ "resource": "" }
q18169
Dump
train
func Dump(t T, resp *http.Response) { // dump request var buffer bytes.Buffer buffer.WriteString("\n") buffer.WriteString(fmt.Sprintf("%v %v\n", resp.Request.Method, resp.Request.URL)) for k, v := range resp.Request.Header { if IsMaskedHeader(k) { v = []string{strings.Repeat(MaskChar, len(v[0]))} } if len(k) > 0 { buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ","))) } } // dump request payload, only available is there is a Body. if resp != nil && resp.Request != nil && resp.Request.Body != nil { rc, err := resp.Request.GetBody() body, err := ioutil.ReadAll(rc) if err != nil { buffer.WriteString(fmt.Sprintf("unable to read request body:%v", err)) } else { if len(body) > 0 { buffer.WriteString("\n") } buffer.WriteString(string(body)) buffer.WriteString("\n") } } // dump response payload if resp == nil { buffer.WriteString("-- no response --") Logf(t, buffer.String()) return } buffer.WriteString(fmt.Sprintf("\n%s\n", resp.Status)) for k, v := range resp.Header { if len(k) > 0 { buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ","))) } } if resp.Body != nil { body, err := ioutil.ReadAll(resp.Body) if err != nil { if resp.StatusCode/100 == 3 { // redirect closes body ; nothing to read buffer.WriteString("\n") } else { buffer.WriteString(fmt.Sprintf("unable to read response body:%v", err)) } } else { if len(body) > 0 { buffer.WriteString("\n") } buffer.WriteString(string(body)) } resp.Body.Close() // put the body back for re-reads resp.Body = ioutil.NopCloser(bytes.NewReader(body)) } buffer.WriteString("\n") Logf(t, buffer.String()) }
go
{ "resource": "" }
q18170
SkipUnless
train
func SkipUnless(t skippeable, labels ...string) { env := strings.Split(os.Getenv("LABELS"), ",") for _, each := range labels { for _, other := range env { if each == other { return } } } t.Skipf("skipped because provided LABELS=%v does not include any of %v", env, labels) }
go
{ "resource": "" }
q18171
Logf
train
func (l Logger) Logf(format string, args ...interface{}) { if l.InfoEnabled { LoggingPrintf("\tinfo : "+tabify(format)+"\n", args...) } }
go
{ "resource": "" }
q18172
Fatal
train
func (l Logger) Fatal(args ...interface{}) { if l.ErrorEnabled { LoggingPrintf("\tfatal: "+tabify("%s")+"\n", args...) } if l.ExitOnFatal { os.Exit(1) } }
go
{ "resource": "" }
q18173
CheckError
train
func CheckError(t T, err error) bool { if err != nil { logerror(t, serrorf("CheckError: did not expect to receive err: %v", err)) } return err != nil }
go
{ "resource": "" }
q18174
ExpectHeader
train
func ExpectHeader(t T, r *http.Response, name, value string) bool { if r == nil { logerror(t, serrorf("ExpectHeader: got nil but want a Http response")) return false } rname := r.Header.Get(name) if rname != value { logerror(t, serrorf("ExpectHeader: got header %s=%s but want %s", name, rname, value)) } return rname == value }
go
{ "resource": "" }
q18175
ExpectJSONHash
train
func ExpectJSONHash(t T, r *http.Response, callback func(hash map[string]interface{})) bool { if r == nil { logerror(t, serrorf("ExpectJSONHash: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectJSONHash: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONHash: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) dict := map[string]interface{}{} err = json.Unmarshal(data, &dict) if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONHash: unable to unmarshal Json:%v", err)) return false } callback(dict) return true }
go
{ "resource": "" }
q18176
ExpectJSONArray
train
func ExpectJSONArray(t T, r *http.Response, callback func(array []interface{})) bool { if r == nil { logerror(t, serrorf("ExpectJSONArray: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectJSONArray: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONArray: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) slice := []interface{}{} err = json.Unmarshal(data, &slice) if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONArray: unable to unmarshal Json:%v", err)) return false } callback(slice) return true }
go
{ "resource": "" }
q18177
ExpectString
train
func ExpectString(t T, r *http.Response, callback func(content string)) bool { if r == nil { logerror(t, serrorf("ExpectString: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectString: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectString: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) callback(string(data)) return true }
go
{ "resource": "" }
q18178
NewConfig
train
func NewConfig(pathTemplate string, pathParams ...interface{}) *RequestConfig { cfg := &RequestConfig{ HeaderMap: http.Header{}, Values: url.Values{}, } cfg.Path(pathTemplate, pathParams...) return cfg }
go
{ "resource": "" }
q18179
Do
train
func (r *RequestConfig) Do(block func(config *RequestConfig)) *RequestConfig { block(r) return r }
go
{ "resource": "" }
q18180
Query
train
func (r *RequestConfig) Query(name string, value interface{}) *RequestConfig { r.Values.Add(name, fmt.Sprintf("%v", value)) return r }
go
{ "resource": "" }
q18181
Header
train
func (r *RequestConfig) Header(name, value string) *RequestConfig { r.HeaderMap.Add(name, value) return r }
go
{ "resource": "" }
q18182
Body
train
func (r *RequestConfig) Body(body string) *RequestConfig { r.BodyReader = strings.NewReader(body) return r }
go
{ "resource": "" }
q18183
Read
train
func (r *RequestConfig) Read(bodyReader io.Reader) *RequestConfig { r.BodyReader = bodyReader return r }
go
{ "resource": "" }
q18184
ProcessTemplate
train
func ProcessTemplate(t T, templateContent string, value interface{}) string { tmp, err := template.New("temporary").Parse(templateContent) if err != nil { logfatal(t, sfatalf("failed to parse:%v", err)) return "" } var buf bytes.Buffer err = tmp.Execute(&buf, value) if err != nil { logfatal(t, sfatalf("failed to execute template:%v", err)) return "" } return buf.String() }
go
{ "resource": "" }
q18185
structToMapString
train
func structToMapString(i interface{}) map[string][]string { ms := map[string][]string{} iv := reflect.ValueOf(i).Elem() tp := iv.Type() for i := 0; i < iv.NumField(); i++ { k := tp.Field(i).Name f := iv.Field(i) ms[k] = valueToString(f) } return ms }
go
{ "resource": "" }
q18186
valueToString
train
func valueToString(f reflect.Value) []string { var v []string switch reflect.TypeOf(f.Interface()).Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v = []string{strconv.FormatInt(f.Int(), 10)} case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: v = []string{strconv.FormatUint(f.Uint(), 10)} case reflect.Float32: v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 32)} case reflect.Float64: v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 64)} case reflect.Bool: v = []string{strconv.FormatBool(f.Bool())} case reflect.Slice: for i := 0; i < f.Len(); i++ { if s := valueToString(f.Index(i)); len(s) == 1 { v = append(v, s[0]) } } case reflect.String: v = []string{f.String()} } return v }
go
{ "resource": "" }
q18187
SendSMS
train
func (s *MessageService) SendSMS(from, to, body string) (*Message, *Response, error) { return s.Send(from, to, MessageParams{Body: body}) }
go
{ "resource": "" }
q18188
NewClient
train
func NewClient(accountSid, authToken string, httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, _ := url.Parse(apiBaseURL) c := &Client{ client: httpClient, UserAgent: userAgent, BaseURL: baseURL, AccountSid: accountSid, AuthToken: authToken, } c.Messages = &MessageService{client: c} return c }
go
{ "resource": "" }
q18189
getInts
train
func (hdr *rpmHeader) getInts(tag int) (buf interface{}, n int, err error) { ent, ok := hdr.entries[tag] if !ok { return nil, 0, NewNoSuchTagError(tag) } n = len(ent.contents) switch ent.dataType { case RPM_INT8_TYPE: buf = make([]uint8, n) case RPM_INT16_TYPE: n >>= 1 buf = make([]uint16, n) case RPM_INT32_TYPE: n >>= 2 buf = make([]uint32, n) case RPM_INT64_TYPE: n >>= 3 buf = make([]uint64, n) default: return nil, 0, fmt.Errorf("tag %d isn't an int type", tag) } if err := binary.Read(bytes.NewReader(ent.contents), binary.BigEndian, buf); err != nil { return nil, 0, err } return }
go
{ "resource": "" }
q18190
GetInts
train
func (hdr *rpmHeader) GetInts(tag int) ([]int, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } out := make([]int, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = int(v) } case []uint16: for i, v := range bvals { out[i] = int(v) } case []uint32: for i, v := range bvals { if v > (1<<31)-1 { return nil, fmt.Errorf("value %d out of range for int32 array in tag %d", i, tag) } out[i] = int(v) } default: return nil, fmt.Errorf("tag %d is too big for int type", tag) } return out, nil }
go
{ "resource": "" }
q18191
GetUint32s
train
func (hdr *rpmHeader) GetUint32s(tag int) ([]uint32, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } if out, ok := buf.([]uint32); ok { return out, nil } out := make([]uint32, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = uint32(v) } case []uint16: for i, v := range bvals { out[i] = uint32(v) } default: return nil, fmt.Errorf("tag %d is too big for int type", tag) } return out, nil }
go
{ "resource": "" }
q18192
GetUint64s
train
func (hdr *rpmHeader) GetUint64s(tag int) ([]uint64, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } if out, ok := buf.([]uint64); ok { return out, nil } out := make([]uint64, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = uint64(v) } case []uint16: for i, v := range bvals { out[i] = uint64(v) } case []uint32: for i, v := range bvals { out[i] = uint64(v) } } return out, nil }
go
{ "resource": "" }
q18193
GetUint64Fallback
train
func (hdr *rpmHeader) GetUint64Fallback(intTag, longTag int) ([]uint64, error) { if _, ok := hdr.entries[longTag]; ok { return hdr.GetUint64s(longTag) } else { return hdr.GetUint64s(intTag) } }
go
{ "resource": "" }
q18194
InstalledSize
train
func (hdr *RpmHeader) InstalledSize() (int64, error) { u, err := hdr.GetUint64Fallback(SIZE, LONGSIZE) if err != nil { return -1, err } return int64(u), nil }
go
{ "resource": "" }
q18195
PayloadSize
train
func (hdr *RpmHeader) PayloadSize() (int64, error) { u, err := hdr.sigHeader.GetUint64Fallback(SIG_PAYLOADSIZE-_SIGHEADER_TAG_BASE, SIG_LONGARCHIVESIZE) if err != nil { return -1, err } else if len(u) != 1 { return -1, errors.New("incorrect number of values") } return int64(u[0]), err }
go
{ "resource": "" }
q18196
SignRpmStream
train
func SignRpmStream(stream io.Reader, key *packet.PrivateKey, opts *SignatureOptions) (header *RpmHeader, err error) { lead, sigHeader, err := readSignatureHeader(stream) if err != nil { return } // parse the general header and also tee it into a buffer genHeaderBuf := new(bytes.Buffer) headerTee := io.TeeReader(stream, genHeaderBuf) genHeader, err := readHeader(headerTee, getSha1(sigHeader), sigHeader.isSource, false) if err != nil { return } genHeaderBlob := genHeaderBuf.Bytes() // chain the buffered general header to the rest of the payload, and digest the whole lot of it genHeaderAndPayload := io.MultiReader(bytes.NewReader(genHeaderBlob), stream) payloadDigest := md5.New() payloadTee := io.TeeReader(genHeaderAndPayload, payloadDigest) sigPgp, err := makeSignature(payloadTee, key, opts) if err != nil { return } if !checkMd5(sigHeader, payloadDigest) { return nil, errors.New("md5 digest mismatch") } sigRsa, err := makeSignature(bytes.NewReader(genHeaderBlob), key, opts) if err != nil { return } insertSignatures(sigHeader, sigPgp, sigRsa) return &RpmHeader{ lead: lead, sigHeader: sigHeader, genHeader: genHeader, isSource: sigHeader.isSource, }, nil }
go
{ "resource": "" }
q18197
SignRpmFileIntoStream
train
func SignRpmFileIntoStream(outstream io.Writer, infile io.ReadSeeker, key *packet.PrivateKey, opts *SignatureOptions) error { header, err := SignRpmStream(infile, key, opts) if err != nil { return err } delete(header.sigHeader.entries, SIG_RESERVEDSPACE-_SIGHEADER_TAG_BASE) return writeRpm(infile, outstream, header.sigHeader) }
go
{ "resource": "" }
q18198
uncompressRpmPayloadReader
train
func uncompressRpmPayloadReader(r io.Reader, hdr *RpmHeader) (io.Reader, error) { // Check to make sure payload format is a cpio archive. If the tag does // not exist, assume archive is cpio. if hdr.HasTag(PAYLOADFORMAT) { val, err := hdr.GetString(PAYLOADFORMAT) if err != nil { return nil, err } if val != "cpio" { return nil, fmt.Errorf("Unknown payload format %s", val) } } // Check to see how the payload was compressed. If the tag does not // exist, check if it is gzip, if not it is uncompressed. var compression string if hdr.HasTag(PAYLOADCOMPRESSOR) { val, err := hdr.GetString(PAYLOADCOMPRESSOR) if err != nil { return nil, err } compression = val } else { b := make([]byte, 4096) _, err := r.Read(b) if err != nil { return nil, err } if len(b) > 2 && b[0] == 0x1f && b[1] == 0x8b { compression = "gzip" } else { compression = "uncompressed" } } switch compression { case "gzip": return gzip.NewReader(r) case "bzip2": return bzip2.NewReader(r), nil case "lzma", "xz": return xz.NewReader(r, 0) case "uncompressed": return r, nil default: return nil, fmt.Errorf("Unknown compression type %s", compression) } }
go
{ "resource": "" }
q18199
Less
train
func (vs VersionSlice) Less(i, j int) bool { return Vercmp(vs[i], vs[j]) == -1 }
go
{ "resource": "" }