_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q34200 | HasAnySuffix | train | func HasAnySuffix(a string, slice []string) bool {
for _, b := range slice {
if strings.HasSuffix(a, b) {
return true
}
}
return false
} | go | {
"resource": ""
} |
q34201 | ContainsAny | train | func ContainsAny(a string, b []string) bool {
for _, s := range b {
if strings.Contains(a, s) {
return true
}
}
return false
} | go | {
"resource": ""
} |
q34202 | WordDensity | train | func (d *Document) WordDensity() map[string]float64 {
density := make(map[string]float64)
for word, freq := range d.WordFrequency {
val, _ := stats.Round(float64(freq)/d.NumWords, 3)
density[word] = val
}
return density
} | go | {
"resource": ""
} |
q34203 | MeanWordLength | train | func (d *Document) MeanWordLength() float64 {
val, _ := stats.Round(d.NumCharacters/d.NumWords, 3)
return val
} | go | {
"resource": ""
} |
q34204 | GetAsset | train | func GetAsset(name string) *gob.Decoder {
b, err := Asset("internal/model/" + name)
util.CheckError(err)
return gob.NewDecoder(bytes.NewReader(b))
} | go | {
"resource": ""
} |
q34205 | NewDocument | train | func NewDocument(text string) *Document {
wTok := tokenize.NewWordBoundaryTokenizer()
sTok := tokenize.NewPunktSentenceTokenizer()
doc := Document{Content: text, WordTokenizer: wTok, SentenceTokenizer: sTok}
doc.Initialize()
return &doc
} | go | {
"resource": ""
} |
q34206 | Initialize | train | func (d *Document) Initialize() {
d.WordFrequency = make(map[string]int)
for i, paragraph := range strings.Split(d.Content, "\n\n") {
for _, s := range d.SentenceTokenizer.Tokenize(paragraph) {
wordCount := d.NumWords
d.NumSentences++
words := []Word{}
for _, word := range d.WordTokenizer.Tokenize(s) {
... | go | {
"resource": ""
} |
q34207 | Assess | train | func (d *Document) Assess() *Assessment {
a := Assessment{
FleschKincaid: d.FleschKincaid(), ReadingEase: d.FleschReadingEase(),
GunningFog: d.GunningFog(), SMOG: d.SMOG(), DaleChall: d.DaleChall(),
AutomatedReadability: d.AutomatedReadability(), ColemanLiau: d.ColemanLiau()}
gradeScores := []float64{
a.Fles... | go | {
"resource": ""
} |
q34208 | Summary | train | func (d *Document) Summary(n int) []RankedParagraph {
rankings := []RankedParagraph{}
scores := d.Keywords()
for i := 0; i < int(d.NumParagraphs); i++ {
p := RankedParagraph{Position: i}
rank := 0
size := 0
for _, s := range d.Sentences {
if s.Paragraph == i {
size += s.Length
for _, w := range s.... | go | {
"resource": ""
} |
q34209 | NewPunktSentenceTokenizer | train | func NewPunktSentenceTokenizer() *PunktSentenceTokenizer {
var pt PunktSentenceTokenizer
var err error
pt.tokenizer, err = newSentenceTokenizer(nil)
util.CheckError(err)
return &pt
} | go | {
"resource": ""
} |
q34210 | newSentenceTokenizer | train | func newSentenceTokenizer(s *sentences.Storage) (*sentences.DefaultSentenceTokenizer, error) {
training := s
if training == nil {
b, err := data.Asset("data/english.json")
if err != nil {
return nil, err
}
training, err = sentences.LoadTraining(b)
if err != nil {
return nil, err
}
}
// supervis... | go | {
"resource": ""
} |
q34211 | sub | train | func (r *rule) sub(text string) string {
if !r.pattern.MatchString(text) {
return text
}
orig := len(text)
diff := 0
for _, submat := range r.pattern.FindAllStringSubmatchIndex(text, -1) {
for idx, mat := range submat {
if mat != -1 && idx > 0 && idx%2 == 0 {
loc := []int{mat - diff, submat[idx+1] - di... | go | {
"resource": ""
} |
q34212 | subPat | train | func subPat(text, mtype string, pat *regexp.Regexp) string {
canidates := []string{}
for _, s := range pat.FindAllString(text, -1) {
canidates = append(canidates, strings.TrimSpace(s))
}
r := punctuationReplacer{
matches: canidates, text: text, matchType: mtype}
return r.replace()
} | go | {
"resource": ""
} |
q34213 | replaceBetweenQuotes | train | func replaceBetweenQuotes(text string) string {
text = subPat(text, "single", betweenSingleQuotesRE)
text = subPat(text, "double", betweenDoubleQuotesRE)
text = subPat(text, "double", betweenSquareBracketsRE)
text = subPat(text, "double", betweenParensRE)
text = subPat(text, "double", betweenArrowQuotesRE)
text =... | go | {
"resource": ""
} |
q34214 | substitute | train | func substitute(src, sub, repl string) string {
idx := strings.Index(src, sub)
for idx >= 0 {
src = src[:idx] + repl + src[idx+len(sub):]
idx = strings.Index(src, sub)
}
return src
} | go | {
"resource": ""
} |
q34215 | Visualize | train | func Visualize(fsm *FSM) string {
var buf bytes.Buffer
states := make(map[string]int)
buf.WriteString(fmt.Sprintf(`digraph fsm {`))
buf.WriteString("\n")
// make sure the initial state is at top
for k, v := range fsm.transitions {
if k.src == fsm.current {
states[k.src]++
states[v]++
buf.WriteString... | go | {
"resource": ""
} |
q34216 | Current | train | func (f *FSM) Current() string {
f.stateMu.RLock()
defer f.stateMu.RUnlock()
return f.current
} | go | {
"resource": ""
} |
q34217 | Is | train | func (f *FSM) Is(state string) bool {
f.stateMu.RLock()
defer f.stateMu.RUnlock()
return state == f.current
} | go | {
"resource": ""
} |
q34218 | SetState | train | func (f *FSM) SetState(state string) {
f.stateMu.Lock()
defer f.stateMu.Unlock()
f.current = state
return
} | go | {
"resource": ""
} |
q34219 | Can | train | func (f *FSM) Can(event string) bool {
f.stateMu.RLock()
defer f.stateMu.RUnlock()
_, ok := f.transitions[eKey{event, f.current}]
return ok && (f.transition == nil)
} | go | {
"resource": ""
} |
q34220 | AvailableTransitions | train | func (f *FSM) AvailableTransitions() []string {
f.stateMu.RLock()
defer f.stateMu.RUnlock()
var transitions []string
for key := range f.transitions {
if key.src == f.current {
transitions = append(transitions, key.event)
}
}
return transitions
} | go | {
"resource": ""
} |
q34221 | Transition | train | func (f *FSM) Transition() error {
f.eventMu.Lock()
defer f.eventMu.Unlock()
return f.doTransition()
} | go | {
"resource": ""
} |
q34222 | beforeEventCallbacks | train | func (f *FSM) beforeEventCallbacks(e *Event) error {
if fn, ok := f.callbacks[cKey{e.Event, callbackBeforeEvent}]; ok {
fn(e)
if e.canceled {
return CanceledError{e.Err}
}
}
if fn, ok := f.callbacks[cKey{"", callbackBeforeEvent}]; ok {
fn(e)
if e.canceled {
return CanceledError{e.Err}
}
}
return ... | go | {
"resource": ""
} |
q34223 | leaveStateCallbacks | train | func (f *FSM) leaveStateCallbacks(e *Event) error {
if fn, ok := f.callbacks[cKey{f.current, callbackLeaveState}]; ok {
fn(e)
if e.canceled {
return CanceledError{e.Err}
} else if e.async {
return AsyncError{e.Err}
}
}
if fn, ok := f.callbacks[cKey{"", callbackLeaveState}]; ok {
fn(e)
if e.canceled... | go | {
"resource": ""
} |
q34224 | enterStateCallbacks | train | func (f *FSM) enterStateCallbacks(e *Event) {
if fn, ok := f.callbacks[cKey{f.current, callbackEnterState}]; ok {
fn(e)
}
if fn, ok := f.callbacks[cKey{"", callbackEnterState}]; ok {
fn(e)
}
} | go | {
"resource": ""
} |
q34225 | afterEventCallbacks | train | func (f *FSM) afterEventCallbacks(e *Event) {
if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok {
fn(e)
}
if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok {
fn(e)
}
} | go | {
"resource": ""
} |
q34226 | Address | train | func (a AddrSpec) Address() string {
if 0 != len(a.IP) {
return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port))
}
return net.JoinHostPort(a.FQDN, strconv.Itoa(a.Port))
} | go | {
"resource": ""
} |
q34227 | NewRequest | train | func NewRequest(bufConn io.Reader) (*Request, error) {
// Read the version byte
header := []byte{0, 0, 0}
if _, err := io.ReadAtLeast(bufConn, header, 3); err != nil {
return nil, fmt.Errorf("Failed to get command version: %v", err)
}
// Ensure we are compatible
if header[0] != socks5Version {
return nil, fm... | go | {
"resource": ""
} |
q34228 | handleRequest | train | func (s *Server) handleRequest(req *Request, conn conn) error {
ctx := context.Background()
// Resolve the address if we have a FQDN
dest := req.DestAddr
if dest.FQDN != "" {
ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
if err != nil {
if err := sendReply(conn, hostUnreachable, nil); err != ... | go | {
"resource": ""
} |
q34229 | handleConnect | train | func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error {
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
if err := sendReply(conn, ruleFailure, nil); err != nil {
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Connect to %v... | go | {
"resource": ""
} |
q34230 | handleBind | train | func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error {
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
if err := sendReply(conn, ruleFailure, nil); err != nil {
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Bind to %v block... | go | {
"resource": ""
} |
q34231 | readAddrSpec | train | func readAddrSpec(r io.Reader) (*AddrSpec, error) {
d := &AddrSpec{}
// Get the address type
addrType := []byte{0}
if _, err := r.Read(addrType); err != nil {
return nil, err
}
// Handle on a per type basis
switch addrType[0] {
case ipv4Address:
addr := make([]byte, 4)
if _, err := io.ReadAtLeast(r, add... | go | {
"resource": ""
} |
q34232 | sendReply | train | func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error {
// Format the address
var addrType uint8
var addrBody []byte
var addrPort uint16
switch {
case addr == nil:
addrType = ipv4Address
addrBody = []byte{0, 0, 0, 0}
addrPort = 0
case addr.FQDN != "":
addrType = fqdnAddress
addrBody = append([... | go | {
"resource": ""
} |
q34233 | proxy | train | func proxy(dst io.Writer, src io.Reader, errCh chan error) {
_, err := io.Copy(dst, src)
if tcpConn, ok := dst.(closeWriter); ok {
tcpConn.CloseWrite()
}
errCh <- err
} | go | {
"resource": ""
} |
q34234 | New | train | func New(conf *Config) (*Server, error) {
// Ensure we have at least one authentication method enabled
if len(conf.AuthMethods) == 0 {
if conf.Credentials != nil {
conf.AuthMethods = []Authenticator{&UserPassAuthenticator{conf.Credentials}}
} else {
conf.AuthMethods = []Authenticator{&NoAuthAuthenticator{}}... | go | {
"resource": ""
} |
q34235 | ListenAndServe | train | func (s *Server) ListenAndServe(network, addr string) error {
l, err := net.Listen(network, addr)
if err != nil {
return err
}
return s.Serve(l)
} | go | {
"resource": ""
} |
q34236 | Serve | train | func (s *Server) Serve(l net.Listener) error {
for {
conn, err := l.Accept()
if err != nil {
return err
}
go s.ServeConn(conn)
}
return nil
} | go | {
"resource": ""
} |
q34237 | ServeConn | train | func (s *Server) ServeConn(conn net.Conn) error {
defer conn.Close()
bufConn := bufio.NewReader(conn)
// Read the version byte
version := []byte{0}
if _, err := bufConn.Read(version); err != nil {
s.config.Logger.Printf("[ERR] socks: Failed to get version byte: %v", err)
return err
}
// Ensure we are compa... | go | {
"resource": ""
} |
q34238 | authenticate | train | func (s *Server) authenticate(conn io.Writer, bufConn io.Reader) (*AuthContext, error) {
// Get the methods
methods, err := readMethods(bufConn)
if err != nil {
return nil, fmt.Errorf("Failed to get auth methods: %v", err)
}
// Select a usable method
for _, method := range methods {
cator, found := s.authMet... | go | {
"resource": ""
} |
q34239 | noAcceptableAuth | train | func noAcceptableAuth(conn io.Writer) error {
conn.Write([]byte{socks5Version, noAcceptable})
return NoSupportedAuth
} | go | {
"resource": ""
} |
q34240 | readMethods | train | func readMethods(r io.Reader) ([]byte, error) {
header := []byte{0}
if _, err := r.Read(header); err != nil {
return nil, err
}
numMethods := int(header[0])
methods := make([]byte, numMethods)
_, err := io.ReadAtLeast(r, methods, numMethods)
return methods, err
} | go | {
"resource": ""
} |
q34241 | ProductImageURL | train | func (item *OrderItem) ProductImageURL() string {
item.loadSizeVariation()
return item.SizeVariation.ColorVariation.MainImageURL()
} | go | {
"resource": ""
} |
q34242 | SellingPrice | train | func (item *OrderItem) SellingPrice() float32 {
if item.IsCart() {
item.loadSizeVariation()
return item.SizeVariation.ColorVariation.Product.Price
}
return item.Price
} | go | {
"resource": ""
} |
q34243 | ProductName | train | func (item *OrderItem) ProductName() string {
item.loadSizeVariation()
return item.SizeVariation.ColorVariation.Product.Name
} | go | {
"resource": ""
} |
q34244 | ColorName | train | func (item *OrderItem) ColorName() string {
item.loadSizeVariation()
return item.SizeVariation.ColorVariation.Color.Name
} | go | {
"resource": ""
} |
q34245 | SizeName | train | func (item *OrderItem) SizeName() string {
item.loadSizeVariation()
return item.SizeVariation.Size.Name
} | go | {
"resource": ""
} |
q34246 | ProductPath | train | func (item *OrderItem) ProductPath() string {
item.loadSizeVariation()
return item.SizeVariation.ColorVariation.ViewPath()
} | go | {
"resource": ""
} |
q34247 | Amount | train | func (item OrderItem) Amount() float32 {
amount := item.SellingPrice() * float32(item.Quantity)
if item.DiscountRate > 0 && item.DiscountRate <= 100 {
amount = amount * float32(100-item.DiscountRate) / 100
}
return amount
} | go | {
"resource": ""
} |
q34248 | SetupDashboard | train | func SetupDashboard(Admin *admin.Admin) {
// Add Dashboard
Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin", Priority: 1})
Admin.GetRouter().Get("/reports", ReportsDataHandler)
initFuncMap(Admin)
} | go | {
"resource": ""
} |
q34249 | New | train | func New(config *Config) *App {
if config.Prefix == "" {
config.Prefix = "/api"
}
return &App{Config: config}
} | go | {
"resource": ""
} |
q34250 | SetupSEO | train | func SetupSEO(Admin *admin.Admin) {
seo.SEOCollection = qor_seo.New("Common SEO")
seo.SEOCollection.RegisterGlobalVaribles(&seo.SEOGlobalSetting{SiteName: "Qor Shop"})
seo.SEOCollection.SettingResource = Admin.AddResource(&seo.MySEOSetting{}, &admin.Config{Invisible: true})
seo.SEOCollection.RegisterSEO(&qor_seo.SE... | go | {
"resource": ""
} |
q34251 | Index | train | func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) {
ctrl.View.Execute("index", map[string]interface{}{}, req, w)
} | go | {
"resource": ""
} |
q34252 | SwitchLocale | train | func (ctrl Controller) SwitchLocale(w http.ResponseWriter, req *http.Request) {
utils.SetCookie(http.Cookie{Name: "locale", Value: req.URL.Query().Get("locale")}, &qor.Context{Request: req, Writer: w})
http.Redirect(w, req, req.Referer(), http.StatusSeeOther)
} | go | {
"resource": ""
} |
q34253 | New | train | func New(cfg *Config) *Application {
if cfg == nil {
cfg = &Config{}
}
if cfg.Router == nil {
cfg.Router = chi.NewRouter()
}
if cfg.AssetFS == nil {
cfg.AssetFS = assetfs.AssetFS()
}
return &Application{
Config: cfg,
}
} | go | {
"resource": ""
} |
q34254 | Index | train | func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) {
var (
Products []products.Product
tx = utils.GetDB(req)
)
tx.Preload("Category").Find(&Products)
ctrl.View.Execute("index", map[string]interface{}{}, req, w)
} | go | {
"resource": ""
} |
q34255 | Show | train | func (ctrl Controller) Show(w http.ResponseWriter, req *http.Request) {
var (
product products.Product
colorVariation products.ColorVariation
codes = strings.Split(utils.URLParam("code", req), "_")
productCode = codes[0]
colorCode string
tx = utils.GetDB(req)
)
if len... | go | {
"resource": ""
} |
q34256 | Category | train | func (ctrl Controller) Category(w http.ResponseWriter, req *http.Request) {
var (
category products.Category
Products []products.Product
tx = utils.GetDB(req)
)
if tx.Where("code = ?", utils.URLParam("code", req)).First(&category).RecordNotFound() {
http.Redirect(w, req, "/", http.StatusFound)
}
tx... | go | {
"resource": ""
} |
q34257 | Cart | train | func (ctrl Controller) Cart(w http.ResponseWriter, req *http.Request) {
order := getCurrentOrderWithItems(w, req)
ctrl.View.Execute("cart", map[string]interface{}{"Order": order}, req, w)
} | go | {
"resource": ""
} |
q34258 | Checkout | train | func (ctrl Controller) Checkout(w http.ResponseWriter, req *http.Request) {
hasAmazon := req.URL.Query().Get("access_token")
order := getCurrentOrderWithItems(w, req)
ctrl.View.Execute("checkout", map[string]interface{}{"Order": order, "HasAmazon": hasAmazon}, req, w)
} | go | {
"resource": ""
} |
q34259 | Complete | train | func (ctrl Controller) Complete(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
order := getCurrentOrder(w, req)
if order.AmazonOrderReferenceID = req.Form.Get("amazon_order_reference_id"); order.AmazonOrderReferenceID != "" {
order.AmazonAddressAccessToken = req.Form.Get("amazon_address_access_token"... | go | {
"resource": ""
} |
q34260 | CompleteCreditCard | train | func (ctrl Controller) CompleteCreditCard(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
order := getCurrentOrder(w, req)
expMonth, _ := strconv.Atoi(req.Form.Get("exp_month"))
expYear, _ := strconv.Atoi(req.Form.Get("exp_year"))
creditCard := gomerchant.CreditCard{
Name: req.Form.Get("name")... | go | {
"resource": ""
} |
q34261 | UpdateCart | train | func (ctrl Controller) UpdateCart(w http.ResponseWriter, req *http.Request) {
var (
input updateCartInput
tx = utils.GetDB(req)
)
req.ParseForm()
decoder.Decode(&input, req.PostForm)
order := getCurrentOrder(w, req)
if input.Quantity > 0 {
tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID:... | go | {
"resource": ""
} |
q34262 | AmazonCallback | train | func (ctrl Controller) AmazonCallback(w http.ResponseWriter, req *http.Request) {
ipn, ok := amazonpay.VerifyIPNRequest(req)
fmt.Printf("%#v\n", ipn)
fmt.Printf("%#v\n", ok)
} | go | {
"resource": ""
} |
q34263 | ViewPath | train | func (colorVariation ColorVariation) ViewPath() string {
defaultPath := ""
var product Product
if !db.DB.First(&product, "id = ?", colorVariation.ProductID).RecordNotFound() {
defaultPath = fmt.Sprintf("/products/%s_%s", product.Code, colorVariation.ColorCode)
}
return defaultPath
} | go | {
"resource": ""
} |
q34264 | GetEditMode | train | func GetEditMode(w http.ResponseWriter, req *http.Request) bool {
return admin.ActionBar.EditMode(w, req)
} | go | {
"resource": ""
} |
q34265 | Profile | train | func (ctrl Controller) Profile(w http.ResponseWriter, req *http.Request) {
var (
currentUser = utils.GetCurrentUser(req)
tx = utils.GetDB(req)
billingAddress, shippingAddress users.Address
)
// TODO refactor
tx.Model(currentUser).Related(¤tUser.Addresses... | go | {
"resource": ""
} |
q34266 | Orders | train | func (ctrl Controller) Orders(w http.ResponseWriter, req *http.Request) {
var (
Orders []orders.Order
currentUser = utils.GetCurrentUser(req)
tx = utils.GetDB(req)
)
tx.Preload("OrderItems").Where("state <> ? AND state != ?", orders.DraftState, "").Where(&orders.Order{UserID: ¤tUser.ID}).F... | go | {
"resource": ""
} |
q34267 | GetCurrentUser | train | func GetCurrentUser(req *http.Request) *users.User {
if currentUser, ok := auth.Auth.GetCurrentUser(req).(*users.User); ok {
return currentUser
}
return nil
} | go | {
"resource": ""
} |
q34268 | GetCurrentLocale | train | func GetCurrentLocale(req *http.Request) string {
locale := l10n.Global
if cookie, err := req.Cookie("locale"); err == nil {
locale = cookie.Value
}
return locale
} | go | {
"resource": ""
} |
q34269 | GetDB | train | func GetDB(req *http.Request) *gorm.DB {
if db := utils.GetDBFromRequest(req); db != nil {
return db
}
return db.DB
} | go | {
"resource": ""
} |
q34270 | URLParam | train | func URLParam(name string, req *http.Request) string {
return chi.URLParam(req, name)
} | go | {
"resource": ""
} |
q34271 | newBlockingUdsWriter | train | func newBlockingUdsWriter(addr string) (*blockingUdsWriter, error) {
udsAddr, err := net.ResolveUnixAddr("unixgram", addr)
if err != nil {
return nil, err
}
// Defer connection to first Write
writer := &blockingUdsWriter{addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout}
return writer, nil
} | go | {
"resource": ""
} |
q34272 | format | train | func (c *Client) format(name string, value interface{}, suffix []byte, tags []string, rate float64) []byte {
// preallocated buffer, stack allocated as long as it doesn't escape
buf := make([]byte, 0, 200)
if c.Namespace != "" {
buf = append(buf, c.Namespace...)
}
buf = append(buf, name...)
buf = append(buf, '... | go | {
"resource": ""
} |
q34273 | SetWriteTimeout | train | func (c *Client) SetWriteTimeout(d time.Duration) error {
if c == nil {
return fmt.Errorf("Client is nil")
}
return c.writer.SetWriteTimeout(d)
} | go | {
"resource": ""
} |
q34274 | Flush | train | func (c *Client) Flush() error {
if c == nil {
return fmt.Errorf("Client is nil")
}
c.Lock()
defer c.Unlock()
return c.flushLocked()
} | go | {
"resource": ""
} |
q34275 | flushLocked | train | func (c *Client) flushLocked() error {
frames, flushable := c.joinMaxSize(c.commands, "\n", OptimalPayloadSize)
var err error
cmdsFlushed := 0
for i, data := range frames {
_, e := c.writer.Write(data)
if e != nil {
err = e
break
}
cmdsFlushed += flushable[i]
}
// clear the slice with a slice op, d... | go | {
"resource": ""
} |
q34276 | send | train | func (c *Client) send(name string, value interface{}, suffix []byte, tags []string, rate float64) error {
if c == nil {
return fmt.Errorf("Client is nil")
}
if rate < 1 && rand.Float64() > rate {
return nil
}
data := c.format(name, value, suffix, tags, rate)
return c.sendMsg(data)
} | go | {
"resource": ""
} |
q34277 | Gauge | train | func (c *Client) Gauge(name string, value float64, tags []string, rate float64) error {
return c.send(name, value, gaugeSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34278 | Count | train | func (c *Client) Count(name string, value int64, tags []string, rate float64) error {
return c.send(name, value, countSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34279 | Histogram | train | func (c *Client) Histogram(name string, value float64, tags []string, rate float64) error {
return c.send(name, value, histogramSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34280 | Distribution | train | func (c *Client) Distribution(name string, value float64, tags []string, rate float64) error {
return c.send(name, value, distributionSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34281 | Decr | train | func (c *Client) Decr(name string, tags []string, rate float64) error {
return c.send(name, nil, decrSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34282 | Incr | train | func (c *Client) Incr(name string, tags []string, rate float64) error {
return c.send(name, nil, incrSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34283 | Set | train | func (c *Client) Set(name string, value string, tags []string, rate float64) error {
return c.send(name, value, setSuffix, tags, rate)
} | go | {
"resource": ""
} |
q34284 | Timing | train | func (c *Client) Timing(name string, value time.Duration, tags []string, rate float64) error {
return c.TimeInMilliseconds(name, value.Seconds()*1000, tags, rate)
} | go | {
"resource": ""
} |
q34285 | Event | train | func (c *Client) Event(e *Event) error {
if c == nil {
return fmt.Errorf("Client is nil")
}
stat, err := e.Encode(c.Tags...)
if err != nil {
return err
}
return c.sendMsg([]byte(stat))
} | go | {
"resource": ""
} |
q34286 | SimpleEvent | train | func (c *Client) SimpleEvent(title, text string) error {
e := NewEvent(title, text)
return c.Event(e)
} | go | {
"resource": ""
} |
q34287 | ServiceCheck | train | func (c *Client) ServiceCheck(sc *ServiceCheck) error {
if c == nil {
return fmt.Errorf("Client is nil")
}
stat, err := sc.Encode(c.Tags...)
if err != nil {
return err
}
return c.sendMsg([]byte(stat))
} | go | {
"resource": ""
} |
q34288 | SimpleServiceCheck | train | func (c *Client) SimpleServiceCheck(name string, status ServiceCheckStatus) error {
sc := NewServiceCheck(name, status)
return c.ServiceCheck(sc)
} | go | {
"resource": ""
} |
q34289 | Close | train | func (c *Client) Close() error {
if c == nil {
return fmt.Errorf("Client is nil")
}
select {
case c.stop <- struct{}{}:
default:
}
// if this client is buffered, flush before closing the writer
if c.bufferLength > 0 {
if err := c.Flush(); err != nil {
return err
}
}
return c.writer.Close()
} | go | {
"resource": ""
} |
q34290 | NewEvent | train | func NewEvent(title, text string) *Event {
return &Event{
Title: title,
Text: text,
}
} | go | {
"resource": ""
} |
q34291 | Encode | train | func (e Event) Encode(tags ...string) (string, error) {
err := e.Check()
if err != nil {
return "", err
}
text := e.escapedText()
var buffer bytes.Buffer
buffer.WriteString("_e{")
buffer.WriteString(strconv.FormatInt(int64(len(e.Title)), 10))
buffer.WriteRune(',')
buffer.WriteString(strconv.FormatInt(int64(... | go | {
"resource": ""
} |
q34292 | NewServiceCheck | train | func NewServiceCheck(name string, status ServiceCheckStatus) *ServiceCheck {
return &ServiceCheck{
Name: name,
Status: status,
}
} | go | {
"resource": ""
} |
q34293 | Encode | train | func (sc ServiceCheck) Encode(tags ...string) (string, error) {
err := sc.Check()
if err != nil {
return "", err
}
message := sc.escapedMessage()
var buffer bytes.Buffer
buffer.WriteString("_sc|")
buffer.WriteString(sc.Name)
buffer.WriteRune('|')
buffer.WriteString(strconv.FormatInt(int64(sc.Status), 10))
... | go | {
"resource": ""
} |
q34294 | newAsyncUdsWriter | train | func newAsyncUdsWriter(addr string) (*asyncUdsWriter, error) {
udsAddr, err := net.ResolveUnixAddr("unixgram", addr)
if err != nil {
return nil, err
}
writer := &asyncUdsWriter{
addr: udsAddr,
conn: nil,
writeTimeout: defaultUDSTimeout,
// 8192 * 8KB = 65.5MB
datagramQueue: make(chan []... | go | {
"resource": ""
} |
q34295 | SetWriteTimeout | train | func (w *asyncUdsWriter) SetWriteTimeout(d time.Duration) error {
w.writeTimeout = d
return nil
} | go | {
"resource": ""
} |
q34296 | Write | train | func (w *udpWriter) Write(data []byte) (int, error) {
return w.conn.Write(data)
} | go | {
"resource": ""
} |
q34297 | WithNamespace | train | func WithNamespace(namespace string) Option {
return func(o *Options) error {
o.Namespace = namespace
return nil
}
} | go | {
"resource": ""
} |
q34298 | WithTags | train | func WithTags(tags []string) Option {
return func(o *Options) error {
o.Tags = tags
return nil
}
} | go | {
"resource": ""
} |
q34299 | WithMaxMessagesPerPayload | train | func WithMaxMessagesPerPayload(maxMessagesPerPayload int) Option {
return func(o *Options) error {
o.MaxMessagesPerPayload = maxMessagesPerPayload
return nil
}
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.