_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q8600 | SetHeaders | train | func (r *Response) SetHeaders(headers map[string]string) *Response {
for key, value := range headers {
r.Header.Add(key, value)
}
return r
} | go | {
"resource": ""
} |
q8601 | Body | train | func (r *Response) Body(body io.Reader) *Response {
r.BodyBuffer, r.Error = ioutil.ReadAll(body)
return r
} | go | {
"resource": ""
} |
q8602 | BodyString | train | func (r *Response) BodyString(body string) *Response {
r.BodyBuffer = []byte(body)
return r
} | go | {
"resource": ""
} |
q8603 | JSON | train | func (r *Response) JSON(data interface{}) *Response {
r.Header.Set("Content-Type", "application/json")
r.BodyBuffer, r.Error = readAndDecode(data, "json")
return r
} | go | {
"resource": ""
} |
q8604 | SetError | train | func (r *Response) SetError(err error) *Response {
r.Error = err
return r
} | go | {
"resource": ""
} |
q8605 | Delay | train | func (r *Response) Delay(delay time.Duration) *Response {
r.ResponseDelay = delay
return r
} | go | {
"resource": ""
} |
q8606 | Map | train | func (r *Response) Map(fn MapResponseFunc) *Response {
r.Mappers = append(r.Mappers, fn)
return r
} | go | {
"resource": ""
} |
q8607 | New | train | func New(uri string) *Request {
Intercept()
res := NewResponse()
req := NewRequest()
req.URLStruct, res.Error = url.Parse(normalizeURI(uri))
// Create the new mock expectation
exp := NewMock(req, res)
Register(exp)
return req
} | go | {
"resource": ""
} |
q8608 | RestoreClient | train | func RestoreClient(cli *http.Client) {
trans, ok := cli.Transport.(*Transport)
if !ok {
return
}
cli.Transport = trans.Transport
} | go | {
"resource": ""
} |
q8609 | Observe | train | func Observe(fn ObserverFunc) {
mutex.Lock()
defer mutex.Unlock()
config.Observer = fn
} | go | {
"resource": ""
} |
q8610 | NetworkingFilter | train | func NetworkingFilter(fn FilterRequestFunc) {
mutex.Lock()
defer mutex.Unlock()
config.NetworkingFilters = append(config.NetworkingFilters, fn)
} | go | {
"resource": ""
} |
q8611 | NewMock | train | func NewMock(req *Request, res *Response) *Mocker {
mock := &Mocker{
request: req,
response: res,
matcher: DefaultMatcher,
}
res.Mock = mock
req.Mock = mock
req.Response = res
return mock
} | go | {
"resource": ""
} |
q8612 | Done | train | func (m *Mocker) Done() bool {
m.mutex.Lock()
defer m.mutex.Unlock()
return m.disabled || (!m.request.Persisted && m.request.Counter == 0)
} | go | {
"resource": ""
} |
q8613 | Match | train | func (m *Mocker) Match(req *http.Request) (bool, error) {
if m.disabled {
return false, nil
}
// Filter
for _, filter := range m.request.Filters {
if !filter(req) {
return false, nil
}
}
// Map
for _, mapper := range m.request.Mappers {
if treq := mapper(req); treq != nil {
req = treq
}
}
// Match
matches, err := m.matcher.Match(req, m.request)
if matches {
m.decrement()
}
return matches, err
} | go | {
"resource": ""
} |
q8614 | decrement | train | func (m *Mocker) decrement() {
if m.request.Persisted {
return
}
m.mutex.Lock()
defer m.mutex.Unlock()
m.request.Counter--
if m.request.Counter == 0 {
m.disabled = true
}
} | go | {
"resource": ""
} |
q8615 | PredictFilesSet | train | func PredictFilesSet(files []string) PredictFunc {
return func(a Args) (prediction []string) {
// add all matching files to prediction
for _, f := range files {
f = fixPathForm(a.Last, f)
// test matching of file to the argument
if match.File(f, a.Last) {
prediction = append(prediction, f)
}
}
return
}
} | go | {
"resource": ""
} |
q8616 | File | train | func File(file, prefix string) bool {
// special case for current directory completion
if file == "./" && (prefix == "." || prefix == "") {
return true
}
if prefix == "." && strings.HasPrefix(file, ".") {
return true
}
file = strings.TrimPrefix(file, "./")
prefix = strings.TrimPrefix(prefix, "./")
return strings.HasPrefix(file, prefix)
} | go | {
"resource": ""
} |
q8617 | Directory | train | func (a Args) Directory() string {
if info, err := os.Stat(a.Last); err == nil && info.IsDir() {
return fixPathForm(a.Last, a.Last)
}
dir := filepath.Dir(a.Last)
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
return "./"
}
return fixPathForm(a.Last, dir)
} | go | {
"resource": ""
} |
q8618 | predictPackages | train | func predictPackages(a complete.Args) (prediction []string) {
prediction = []string{a.Last}
lastPrediction := ""
for len(prediction) == 1 && (lastPrediction == "" || lastPrediction != prediction[0]) {
// if only one prediction, predict files within this prediction,
// for example, if the user entered 'pk' and we have a package named 'pkg',
// which is the only package prefixed with 'pk', we will automatically go one
// level deeper and give the user the 'pkg' and all the nested packages within
// that package.
lastPrediction = prediction[0]
a.Last = prediction[0]
prediction = predictLocalAndSystem(a)
}
return
} | go | {
"resource": ""
} |
q8619 | listPackages | train | func listPackages(dir string) (directories []string) {
// add subdirectories
files, err := ioutil.ReadDir(dir)
if err != nil {
complete.Log("failed reading directory %s: %s", dir, err)
return
}
// build paths array
paths := make([]string, 0, len(files)+1)
for _, f := range files {
if f.IsDir() {
paths = append(paths, filepath.Join(dir, f.Name()))
}
}
paths = append(paths, dir)
// import packages according to given paths
for _, p := range paths {
pkg, err := build.ImportDir(p, 0)
if err != nil {
complete.Log("failed importing directory %s: %s", p, err)
continue
}
directories = append(directories, pkg.Dir)
}
return
} | go | {
"resource": ""
} |
q8620 | Run | train | func (c *Complete) Run() bool {
c.AddFlags(nil)
flag.Parse()
return c.Complete()
} | go | {
"resource": ""
} |
q8621 | Predict | train | func (c *Command) Predict(a Args) []string {
options, _ := c.predict(a)
return options
} | go | {
"resource": ""
} |
q8622 | Predict | train | func (c Commands) Predict(a Args) (prediction []string) {
for sub := range c {
prediction = append(prediction, sub)
}
return
} | go | {
"resource": ""
} |
q8623 | Predict | train | func (f Flags) Predict(a Args) (prediction []string) {
for flag := range f {
// If the flag starts with a hyphen, we avoid emitting the prediction
// unless the last typed arg contains a hyphen as well.
flagHyphenStart := len(flag) != 0 && flag[0] == '-'
lastHyphenStart := len(a.Last) != 0 && a.Last[0] == '-'
if flagHyphenStart && !lastHyphenStart {
continue
}
prediction = append(prediction, flag)
}
return
} | go | {
"resource": ""
} |
q8624 | predict | train | func (c *Command) predict(a Args) (options []string, only bool) {
// search sub commands for predictions first
subCommandFound := false
for i, arg := range a.Completed {
if cmd, ok := c.Sub[arg]; ok {
subCommandFound = true
// recursive call for sub command
options, only = cmd.predict(a.from(i))
if only {
return
}
// We matched so stop searching. Continuing to search can accidentally
// match a subcommand with current set of commands, see issue #46.
break
}
}
// if last completed word is a global flag that we need to complete
if predictor, ok := c.GlobalFlags[a.LastCompleted]; ok && predictor != nil {
Log("Predicting according to global flag %s", a.LastCompleted)
return predictor.Predict(a), true
}
options = append(options, c.GlobalFlags.Predict(a)...)
// if a sub command was entered, we won't add the parent command
// completions and we return here.
if subCommandFound {
return
}
// if last completed word is a command flag that we need to complete
if predictor, ok := c.Flags[a.LastCompleted]; ok && predictor != nil {
Log("Predicting according to flag %s", a.LastCompleted)
return predictor.Predict(a), true
}
options = append(options, c.Sub.Predict(a)...)
options = append(options, c.Flags.Predict(a)...)
if c.Args != nil {
options = append(options, c.Args.Predict(a)...)
}
return
} | go | {
"resource": ""
} |
q8625 | fixPathForm | train | func fixPathForm(last string, file string) string {
// get wording directory for relative name
workDir, err := os.Getwd()
if err != nil {
return file
}
abs, err := filepath.Abs(file)
if err != nil {
return file
}
// if last is absolute, return path as absolute
if filepath.IsAbs(last) {
return fixDirPath(abs)
}
rel, err := filepath.Rel(workDir, abs)
if err != nil {
return file
}
// fix ./ prefix of path
if rel != "." && strings.HasPrefix(last, ".") {
rel = "./" + rel
}
return fixDirPath(rel)
} | go | {
"resource": ""
} |
q8626 | Run | train | func (f *CLI) Run() bool {
err := f.validate()
if err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
switch {
case f.install:
f.prompt()
err = install.Install(f.Name)
case f.uninstall:
f.prompt()
err = install.Uninstall(f.Name)
default:
// non of the action flags matched,
// returning false should make the real program execute
return false
}
if err != nil {
fmt.Printf("%s failed! %s\n", f.action(), err)
os.Exit(3)
}
fmt.Println("Done!")
return true
} | go | {
"resource": ""
} |
q8627 | prompt | train | func (f *CLI) prompt() {
defer fmt.Println(f.action() + "ing...")
if f.yes {
return
}
fmt.Printf("%s completion for %s? ", f.action(), f.Name)
var answer string
fmt.Scanln(&answer)
switch strings.ToLower(answer) {
case "y", "yes":
return
default:
fmt.Println("Cancelling...")
os.Exit(1)
}
} | go | {
"resource": ""
} |
q8628 | AddFlags | train | func (f *CLI) AddFlags(flags *flag.FlagSet) {
if flags == nil {
flags = flag.CommandLine
}
if f.InstallName == "" {
f.InstallName = defaultInstallName
}
if f.UninstallName == "" {
f.UninstallName = defaultUninstallName
}
if flags.Lookup(f.InstallName) == nil {
flags.BoolVar(&f.install, f.InstallName, false,
fmt.Sprintf("Install completion for %s command", f.Name))
}
if flags.Lookup(f.UninstallName) == nil {
flags.BoolVar(&f.uninstall, f.UninstallName, false,
fmt.Sprintf("Uninstall completion for %s command", f.Name))
}
if flags.Lookup("y") == nil {
flags.BoolVar(&f.yes, "y", false, "Don't prompt user for typing 'yes' when installing completion")
}
} | go | {
"resource": ""
} |
q8629 | validate | train | func (f *CLI) validate() error {
if f.install && f.uninstall {
return errors.New("Install and uninstall are mutually exclusive")
}
return nil
} | go | {
"resource": ""
} |
q8630 | PredictOr | train | func PredictOr(predictors ...Predictor) Predictor {
return PredictFunc(func(a Args) (prediction []string) {
for _, p := range predictors {
if p == nil {
continue
}
prediction = append(prediction, p.Predict(a)...)
}
return
})
} | go | {
"resource": ""
} |
q8631 | Predict | train | func (p PredictFunc) Predict(a Args) []string {
if p == nil {
return nil
}
return p(a)
} | go | {
"resource": ""
} |
q8632 | New | train | func New() *Sling {
return &Sling{
httpClient: http.DefaultClient,
method: "GET",
header: make(http.Header),
queryStructs: make([]interface{}, 0),
responseDecoder: jsonDecoder{},
}
} | go | {
"resource": ""
} |
q8633 | Client | train | func (s *Sling) Client(httpClient *http.Client) *Sling {
if httpClient == nil {
return s.Doer(http.DefaultClient)
}
return s.Doer(httpClient)
} | go | {
"resource": ""
} |
q8634 | Doer | train | func (s *Sling) Doer(doer Doer) *Sling {
if doer == nil {
s.httpClient = http.DefaultClient
} else {
s.httpClient = doer
}
return s
} | go | {
"resource": ""
} |
q8635 | Head | train | func (s *Sling) Head(pathURL string) *Sling {
s.method = "HEAD"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8636 | Get | train | func (s *Sling) Get(pathURL string) *Sling {
s.method = "GET"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8637 | Post | train | func (s *Sling) Post(pathURL string) *Sling {
s.method = "POST"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8638 | Put | train | func (s *Sling) Put(pathURL string) *Sling {
s.method = "PUT"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8639 | Patch | train | func (s *Sling) Patch(pathURL string) *Sling {
s.method = "PATCH"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8640 | Delete | train | func (s *Sling) Delete(pathURL string) *Sling {
s.method = "DELETE"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8641 | Options | train | func (s *Sling) Options(pathURL string) *Sling {
s.method = "OPTIONS"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8642 | Trace | train | func (s *Sling) Trace(pathURL string) *Sling {
s.method = "TRACE"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8643 | Connect | train | func (s *Sling) Connect(pathURL string) *Sling {
s.method = "CONNECT"
return s.Path(pathURL)
} | go | {
"resource": ""
} |
q8644 | Add | train | func (s *Sling) Add(key, value string) *Sling {
s.header.Add(key, value)
return s
} | go | {
"resource": ""
} |
q8645 | Set | train | func (s *Sling) Set(key, value string) *Sling {
s.header.Set(key, value)
return s
} | go | {
"resource": ""
} |
q8646 | SetBasicAuth | train | func (s *Sling) SetBasicAuth(username, password string) *Sling {
return s.Set("Authorization", "Basic "+basicAuth(username, password))
} | go | {
"resource": ""
} |
q8647 | Base | train | func (s *Sling) Base(rawURL string) *Sling {
s.rawURL = rawURL
return s
} | go | {
"resource": ""
} |
q8648 | Path | train | func (s *Sling) Path(path string) *Sling {
baseURL, baseErr := url.Parse(s.rawURL)
pathURL, pathErr := url.Parse(path)
if baseErr == nil && pathErr == nil {
s.rawURL = baseURL.ResolveReference(pathURL).String()
return s
}
return s
} | go | {
"resource": ""
} |
q8649 | BodyProvider | train | func (s *Sling) BodyProvider(body BodyProvider) *Sling {
if body == nil {
return s
}
s.bodyProvider = body
ct := body.ContentType()
if ct != "" {
s.Set(contentType, ct)
}
return s
} | go | {
"resource": ""
} |
q8650 | Request | train | func (s *Sling) Request() (*http.Request, error) {
reqURL, err := url.Parse(s.rawURL)
if err != nil {
return nil, err
}
err = addQueryStructs(reqURL, s.queryStructs)
if err != nil {
return nil, err
}
var body io.Reader
if s.bodyProvider != nil {
body, err = s.bodyProvider.Body()
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(s.method, reqURL.String(), body)
if err != nil {
return nil, err
}
addHeaders(req, s.header)
return req, err
} | go | {
"resource": ""
} |
q8651 | addQueryStructs | train | func addQueryStructs(reqURL *url.URL, queryStructs []interface{}) error {
urlValues, err := url.ParseQuery(reqURL.RawQuery)
if err != nil {
return err
}
// encodes query structs into a url.Values map and merges maps
for _, queryStruct := range queryStructs {
queryValues, err := goquery.Values(queryStruct)
if err != nil {
return err
}
for key, values := range queryValues {
for _, value := range values {
urlValues.Add(key, value)
}
}
}
// url.Values format to a sorted "url encoded" string, e.g. "key=val&foo=bar"
reqURL.RawQuery = urlValues.Encode()
return nil
} | go | {
"resource": ""
} |
q8652 | addHeaders | train | func addHeaders(req *http.Request, header http.Header) {
for key, values := range header {
for _, value := range values {
req.Header.Add(key, value)
}
}
} | go | {
"resource": ""
} |
q8653 | ResponseDecoder | train | func (s *Sling) ResponseDecoder(decoder ResponseDecoder) *Sling {
if decoder == nil {
return s
}
s.responseDecoder = decoder
return s
} | go | {
"resource": ""
} |
q8654 | Decode | train | func (d jsonDecoder) Decode(resp *http.Response, v interface{}) error {
return json.NewDecoder(resp.Body).Decode(v)
} | go | {
"resource": ""
} |
q8655 | NewIssueService | train | func NewIssueService(httpClient *http.Client) *IssueService {
return &IssueService{
sling: sling.New().Client(httpClient).Base(baseURL),
}
} | go | {
"resource": ""
} |
q8656 | List | train | func (s *IssueService) List(params *IssueListParams) ([]Issue, *http.Response, error) {
issues := new([]Issue)
githubError := new(GithubError)
resp, err := s.sling.New().Path("issues").QueryStruct(params).Receive(issues, githubError)
if err == nil {
err = githubError
}
return *issues, resp, err
} | go | {
"resource": ""
} |
q8657 | ListByRepo | train | func (s *IssueService) ListByRepo(owner, repo string, params *IssueListParams) ([]Issue, *http.Response, error) {
issues := new([]Issue)
githubError := new(GithubError)
path := fmt.Sprintf("repos/%s/%s/issues", owner, repo)
resp, err := s.sling.New().Get(path).QueryStruct(params).Receive(issues, githubError)
if err == nil {
err = githubError
}
return *issues, resp, err
} | go | {
"resource": ""
} |
q8658 | Create | train | func (s *IssueService) Create(owner, repo string, issueBody *IssueRequest) (*Issue, *http.Response, error) {
issue := new(Issue)
githubError := new(GithubError)
path := fmt.Sprintf("repos/%s/%s/issues", owner, repo)
resp, err := s.sling.New().Post(path).BodyJSON(issueBody).Receive(issue, githubError)
if err == nil {
err = githubError
}
return issue, resp, err
} | go | {
"resource": ""
} |
q8659 | Sum64 | train | func Sum64(b []byte) uint64 {
// A simpler version would be
// d := New()
// d.Write(b)
// return d.Sum64()
// but this is faster, particularly for small inputs.
n := len(b)
var h uint64
if n >= 32 {
v1 := prime1v + prime2
v2 := prime2
v3 := uint64(0)
v4 := -prime1v
for len(b) >= 32 {
v1 = round(v1, u64(b[0:8:len(b)]))
v2 = round(v2, u64(b[8:16:len(b)]))
v3 = round(v3, u64(b[16:24:len(b)]))
v4 = round(v4, u64(b[24:32:len(b)]))
b = b[32:len(b):len(b)]
}
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
h = mergeRound(h, v1)
h = mergeRound(h, v2)
h = mergeRound(h, v3)
h = mergeRound(h, v4)
} else {
h = prime5
}
h += uint64(n)
i, end := 0, len(b)
for ; i+8 <= end; i += 8 {
k1 := round(0, u64(b[i:i+8:len(b)]))
h ^= k1
h = rol27(h)*prime1 + prime4
}
if i+4 <= end {
h ^= uint64(u32(b[i:i+4:len(b)])) * prime1
h = rol23(h)*prime2 + prime3
i += 4
}
for ; i < end; i++ {
h ^= uint64(b[i]) * prime5
h = rol11(h) * prime1
}
h ^= h >> 33
h *= prime2
h ^= h >> 29
h *= prime3
h ^= h >> 32
return h
} | go | {
"resource": ""
} |
q8660 | Reset | train | func (d *Digest) Reset() {
d.v1 = prime1v + prime2
d.v2 = prime2
d.v3 = 0
d.v4 = -prime1v
d.total = 0
d.n = 0
} | go | {
"resource": ""
} |
q8661 | Sum | train | func (d *Digest) Sum(b []byte) []byte {
s := d.Sum64()
return append(
b,
byte(s>>56),
byte(s>>48),
byte(s>>40),
byte(s>>32),
byte(s>>24),
byte(s>>16),
byte(s>>8),
byte(s),
)
} | go | {
"resource": ""
} |
q8662 | Sum64 | train | func (d *Digest) Sum64() uint64 {
var h uint64
if d.total >= 32 {
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
h = mergeRound(h, v1)
h = mergeRound(h, v2)
h = mergeRound(h, v3)
h = mergeRound(h, v4)
} else {
h = d.v3 + prime5
}
h += d.total
i, end := 0, d.n
for ; i+8 <= end; i += 8 {
k1 := round(0, u64(d.mem[i:i+8]))
h ^= k1
h = rol27(h)*prime1 + prime4
}
if i+4 <= end {
h ^= uint64(u32(d.mem[i:i+4])) * prime1
h = rol23(h)*prime2 + prime3
i += 4
}
for i < end {
h ^= uint64(d.mem[i]) * prime5
h = rol11(h) * prime1
i++
}
h ^= h >> 33
h *= prime2
h ^= h >> 29
h *= prime3
h ^= h >> 32
return h
} | go | {
"resource": ""
} |
q8663 | RateLimit | train | func RateLimit(q Quota, vary *VaryBy, store GCRAStore) *Throttler {
count, period := q.Quota()
if count < 1 {
count = 1
}
if period <= 0 {
period = time.Second
}
rate := Rate{period: period / time.Duration(count)}
limiter, err := NewGCRARateLimiter(store, RateQuota{rate, count - 1})
// This panic in unavoidable because the original interface does
// not support returning an error.
if err != nil {
panic(err)
}
return &Throttler{
HTTPRateLimiter{
RateLimiter: limiter,
VaryBy: vary,
},
}
} | go | {
"resource": ""
} |
q8664 | getConn | train | func (r *RedigoStore) getConn() (redis.Conn, error) {
conn := r.pool.Get()
// Select the specified database
if r.db > 0 {
if _, err := redis.String(conn.Do("SELECT", r.db)); err != nil {
conn.Close()
return nil, err
}
}
return conn, nil
} | go | {
"resource": ""
} |
q8665 | RateLimit | train | func (g *GCRARateLimiter) RateLimit(key string, quantity int) (bool, RateLimitResult, error) {
var tat, newTat, now time.Time
var ttl time.Duration
rlc := RateLimitResult{Limit: g.limit, RetryAfter: -1}
limited := false
i := 0
for {
var err error
var tatVal int64
var updated bool
// tat refers to the theoretical arrival time that would be expected
// from equally spaced requests at exactly the rate limit.
tatVal, now, err = g.store.GetWithTime(key)
if err != nil {
return false, rlc, err
}
if tatVal == -1 {
tat = now
} else {
tat = time.Unix(0, tatVal)
}
increment := time.Duration(quantity) * g.emissionInterval
if now.After(tat) {
newTat = now.Add(increment)
} else {
newTat = tat.Add(increment)
}
// Block the request if the next permitted time is in the future
allowAt := newTat.Add(-(g.delayVariationTolerance))
if diff := now.Sub(allowAt); diff < 0 {
if increment <= g.delayVariationTolerance {
rlc.RetryAfter = -diff
}
ttl = tat.Sub(now)
limited = true
break
}
ttl = newTat.Sub(now)
if tatVal == -1 {
updated, err = g.store.SetIfNotExistsWithTTL(key, newTat.UnixNano(), ttl)
} else {
updated, err = g.store.CompareAndSwapWithTTL(key, tatVal, newTat.UnixNano(), ttl)
}
if err != nil {
return false, rlc, err
}
if updated {
break
}
i++
if i > maxCASAttempts {
return false, rlc, fmt.Errorf(
"Failed to store updated rate limit data for key %s after %d attempts",
key, i,
)
}
}
next := g.delayVariationTolerance - ttl
if next > -g.emissionInterval {
rlc.Remaining = int(next / g.emissionInterval)
}
rlc.ResetAfter = ttl
return limited, rlc, nil
} | go | {
"resource": ""
} |
q8666 | RateLimit | train | func (t *HTTPRateLimiter) RateLimit(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if t.RateLimiter == nil {
t.error(w, r, errors.New("You must set a RateLimiter on HTTPRateLimiter"))
}
var k string
if t.VaryBy != nil {
k = t.VaryBy.Key(r)
}
limited, context, err := t.RateLimiter.RateLimit(k, 1)
if err != nil {
t.error(w, r, err)
return
}
setRateLimitHeaders(w, context)
if !limited {
h.ServeHTTP(w, r)
} else {
dh := t.DeniedHandler
if dh == nil {
dh = DefaultDeniedHandler
}
dh.ServeHTTP(w, r)
}
})
} | go | {
"resource": ""
} |
q8667 | GetWithTime | train | func (ms *MemStore) GetWithTime(key string) (int64, time.Time, error) {
now := time.Now()
valP, ok := ms.get(key, false)
if !ok {
return -1, now, nil
}
return atomic.LoadInt64(valP), now, nil
} | go | {
"resource": ""
} |
q8668 | SetIfNotExistsWithTTL | train | func (ms *MemStore) SetIfNotExistsWithTTL(key string, value int64, _ time.Duration) (bool, error) {
_, ok := ms.get(key, false)
if ok {
return false, nil
}
ms.Lock()
defer ms.Unlock()
_, ok = ms.get(key, true)
if ok {
return false, nil
}
// Store a pointer to a new instance so that the caller
// can't mutate the value after setting
v := value
if ms.keys != nil {
ms.keys.Add(key, &v)
} else {
ms.m[key] = &v
}
return true, nil
} | go | {
"resource": ""
} |
q8669 | CompareAndSwapWithTTL | train | func (ms *MemStore) CompareAndSwapWithTTL(key string, old, new int64, _ time.Duration) (bool, error) {
valP, ok := ms.get(key, false)
if !ok {
return false, nil
}
return atomic.CompareAndSwapInt64(valP, old, new), nil
} | go | {
"resource": ""
} |
q8670 | Key | train | func (vb *VaryBy) Key(r *http.Request) string {
var buf bytes.Buffer
if vb == nil {
return "" // Special case for no vary-by option
}
if vb.Custom != nil {
// A custom key generator is specified
return vb.Custom(r)
}
sep := vb.Separator
if sep == "" {
sep = "\n" // Separator defaults to newline
}
if vb.RemoteAddr && len(r.RemoteAddr) > 0 {
// RemoteAddr usually looks something like `IP:port`. For example,
// `[::]:1234`. However, it seems to occasionally degenerately appear
// as just IP (or other), so be conservative with how we extract it.
index := strings.LastIndex(r.RemoteAddr, ":")
var ip string
if index == -1 {
ip = r.RemoteAddr
} else {
ip = r.RemoteAddr[:index]
}
buf.WriteString(strings.ToLower(ip) + sep)
}
if vb.Method {
buf.WriteString(strings.ToLower(r.Method) + sep)
}
for _, h := range vb.Headers {
buf.WriteString(strings.ToLower(r.Header.Get(h)) + sep)
}
if vb.Path {
buf.WriteString(r.URL.Path + sep)
}
for _, p := range vb.Params {
buf.WriteString(r.FormValue(p) + sep)
}
for _, c := range vb.Cookies {
ck, err := r.Cookie(c)
if err == nil {
buf.WriteString(ck.Value)
}
buf.WriteString(sep) // Write the separator anyway, whether or not the cookie exists
}
return buf.String()
} | go | {
"resource": ""
} |
q8671 | NewMemStore | train | func NewMemStore(maxKeys int) *memstore.MemStore {
st, err := memstore.New(maxKeys)
if err != nil {
// As of this writing, `lru.New` can only return an error if you pass
// maxKeys <= 0 so this should never occur.
panic(err)
}
return st
} | go | {
"resource": ""
} |
q8672 | NewRedisStore | train | func NewRedisStore(pool *redis.Pool, keyPrefix string, db int) *redigostore.RedigoStore {
st, err := redigostore.New(pool, keyPrefix, db)
if err != nil {
// As of this writing, creating a Redis store never returns an error
// so this should be safe while providing some ability to return errors
// in the future.
panic(err)
}
return st
} | go | {
"resource": ""
} |
q8673 | NewException | train | func NewException(err error, stacktrace *Stacktrace) *Exception {
msg := err.Error()
ex := &Exception{
Stacktrace: stacktrace,
Value: msg,
Type: reflect.TypeOf(err).String(),
}
if m := errorMsgPattern.FindStringSubmatch(msg); m != nil {
ex.Module, ex.Value = m[1], m[2]
}
return ex
} | go | {
"resource": ""
} |
q8674 | Culprit | train | func (e *Exception) Culprit() string {
if e.Stacktrace == nil {
return ""
}
return e.Stacktrace.Culprit()
} | go | {
"resource": ""
} |
q8675 | WrapWithExtra | train | func WrapWithExtra(err error, extraInfo map[string]interface{}) error {
return &errWrappedWithExtra{
err: err,
extraInfo: extraInfo,
}
} | go | {
"resource": ""
} |
q8676 | extractExtra | train | func extractExtra(err error) Extra {
extra := Extra{}
currentErr := err
for currentErr != nil {
if errWithExtra, ok := currentErr.(errWithJustExtra); ok {
for k, v := range errWithExtra.ExtraInfo() {
extra[k] = v
}
}
if errWithCause, ok := currentErr.(causer); ok {
currentErr = errWithCause.Cause()
} else {
currentErr = nil
}
}
return extra
} | go | {
"resource": ""
} |
q8677 | Culprit | train | func (s *Stacktrace) Culprit() string {
for i := len(s.Frames) - 1; i >= 0; i-- {
frame := s.Frames[i]
if frame.InApp == true && frame.Module != "" && frame.Function != "" {
return frame.Module + "." + frame.Function
}
}
return ""
} | go | {
"resource": ""
} |
q8678 | NewStacktrace | train | func NewStacktrace(skip int, context int, appPackagePrefixes []string) *Stacktrace {
var frames []*StacktraceFrame
callerPcs := make([]uintptr, 100)
numCallers := runtime.Callers(skip+2, callerPcs)
// If there are no callers, the entire stacktrace is nil
if numCallers == 0 {
return nil
}
callersFrames := runtime.CallersFrames(callerPcs)
for {
fr, more := callersFrames.Next()
frame := NewStacktraceFrame(fr.PC, fr.Function, fr.File, fr.Line, context, appPackagePrefixes)
if frame != nil {
frames = append(frames, frame)
}
if !more {
break
}
}
// If there are no frames, the entire stacktrace is nil
if len(frames) == 0 {
return nil
}
// Optimize the path where there's only 1 frame
if len(frames) == 1 {
return &Stacktrace{frames}
}
// Sentry wants the frames with the oldest first, so reverse them
for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {
frames[i], frames[j] = frames[j], frames[i]
}
return &Stacktrace{frames}
} | go | {
"resource": ""
} |
q8679 | NewStacktraceFrame | train | func NewStacktraceFrame(pc uintptr, fName, file string, line, context int, appPackagePrefixes []string) *StacktraceFrame {
frame := &StacktraceFrame{AbsolutePath: file, Filename: trimPath(file), Lineno: line}
frame.Module, frame.Function = functionName(fName)
frame.InApp = isInAppFrame(*frame, appPackagePrefixes)
// `runtime.goexit` is effectively a placeholder that comes from
// runtime/asm_amd64.s and is meaningless.
if frame.Module == "runtime" && frame.Function == "goexit" {
return nil
}
if context > 0 {
contextLines, lineIdx := sourceCodeLoader.Load(file, line, context)
if len(contextLines) > 0 {
for i, line := range contextLines {
switch {
case i < lineIdx:
frame.PreContext = append(frame.PreContext, string(line))
case i == lineIdx:
frame.ContextLine = string(line)
default:
frame.PostContext = append(frame.PostContext, string(line))
}
}
}
} else if context == -1 {
contextLine, _ := sourceCodeLoader.Load(file, line, 0)
if len(contextLine) > 0 {
frame.ContextLine = string(contextLine[0])
}
}
return frame
} | go | {
"resource": ""
} |
q8680 | isInAppFrame | train | func isInAppFrame(frame StacktraceFrame, appPackagePrefixes []string) bool {
if frame.Module == "main" {
return true
}
for _, prefix := range appPackagePrefixes {
if strings.HasPrefix(frame.Module, prefix) && !strings.Contains(frame.Module, "vendor") && !strings.Contains(frame.Module, "third_party") {
return true
}
}
return false
} | go | {
"resource": ""
} |
q8681 | functionName | train | func functionName(fName string) (pack string, name string) {
name = fName
// We get this:
// runtime/debug.*T·ptrmethod
// and want this:
// pack = runtime/debug
// name = *T.ptrmethod
if idx := strings.LastIndex(name, "."); idx != -1 {
pack = name[:idx]
name = name[idx+1:]
}
name = strings.Replace(name, "·", ".", -1)
return
} | go | {
"resource": ""
} |
q8682 | trimPath | train | func trimPath(filename string) string {
for _, prefix := range trimPaths {
if trimmed := strings.TrimPrefix(filename, prefix); len(trimmed) < len(filename) {
return trimmed
}
}
return filename
} | go | {
"resource": ""
} |
q8683 | MarshalJSON | train | func (timestamp Timestamp) MarshalJSON() ([]byte, error) {
return []byte(time.Time(timestamp).UTC().Format(timestampFormat)), nil
} | go | {
"resource": ""
} |
q8684 | UnmarshalJSON | train | func (timestamp *Timestamp) UnmarshalJSON(data []byte) error {
t, err := time.Parse(timestampFormat, string(data))
if err != nil {
return err
}
*timestamp = Timestamp(t)
return nil
} | go | {
"resource": ""
} |
q8685 | Format | train | func (timestamp Timestamp) Format(format string) string {
t := time.Time(timestamp)
return t.Format(format)
} | go | {
"resource": ""
} |
q8686 | MarshalJSON | train | func (t *Tag) MarshalJSON() ([]byte, error) {
return json.Marshal([2]string{t.Key, t.Value})
} | go | {
"resource": ""
} |
q8687 | UnmarshalJSON | train | func (t *Tag) UnmarshalJSON(data []byte) error {
var tag [2]string
if err := json.Unmarshal(data, &tag); err != nil {
return err
}
*t = Tag{tag[0], tag[1]}
return nil
} | go | {
"resource": ""
} |
q8688 | UnmarshalJSON | train | func (t *Tags) UnmarshalJSON(data []byte) error {
var tags []Tag
switch data[0] {
case '[':
// Unmarshal into []Tag
if err := json.Unmarshal(data, &tags); err != nil {
return err
}
case '{':
// Unmarshal into map[string]string
tagMap := make(map[string]string)
if err := json.Unmarshal(data, &tagMap); err != nil {
return err
}
// Convert to []Tag
for k, v := range tagMap {
tags = append(tags, Tag{k, v})
}
default:
return ErrUnableToUnmarshalJSON
}
*t = tags
return nil
} | go | {
"resource": ""
} |
q8689 | NewPacket | train | func NewPacket(message string, interfaces ...Interface) *Packet {
extra := Extra{}
setExtraDefaults(extra)
return &Packet{
Message: message,
Interfaces: interfaces,
Extra: extra,
}
} | go | {
"resource": ""
} |
q8690 | NewPacketWithExtra | train | func NewPacketWithExtra(message string, extra Extra, interfaces ...Interface) *Packet {
if extra == nil {
extra = Extra{}
}
setExtraDefaults(extra)
return &Packet{
Message: message,
Interfaces: interfaces,
Extra: extra,
}
} | go | {
"resource": ""
} |
q8691 | AddTags | train | func (packet *Packet) AddTags(tags map[string]string) {
for k, v := range tags {
packet.Tags = append(packet.Tags, Tag{k, v})
}
} | go | {
"resource": ""
} |
q8692 | JSON | train | func (packet *Packet) JSON() ([]byte, error) {
packetJSON, err := json.Marshal(packet)
if err != nil {
return nil, err
}
interfaces := make(map[string]Interface, len(packet.Interfaces))
for _, inter := range packet.Interfaces {
if inter != nil {
interfaces[inter.Class()] = inter
}
}
if len(interfaces) > 0 {
interfaceJSON, err := json.Marshal(interfaces)
if err != nil {
return nil, err
}
packetJSON[len(packetJSON)-1] = ','
packetJSON = append(packetJSON, interfaceJSON[1:]...)
}
return packetJSON, nil
} | go | {
"resource": ""
} |
q8693 | interfaces | train | func (c *context) interfaces() []Interface {
len, i := 0, 0
if c.user != nil {
len++
}
if c.http != nil {
len++
}
interfaces := make([]Interface, len)
if c.user != nil {
interfaces[i] = c.user
i++
}
if c.http != nil {
interfaces[i] = c.http
}
return interfaces
} | go | {
"resource": ""
} |
q8694 | New | train | func New(dsn string) (*Client, error) {
client := newClient(nil)
return client, client.SetDSN(dsn)
} | go | {
"resource": ""
} |
q8695 | NewWithTags | train | func NewWithTags(dsn string, tags map[string]string) (*Client, error) {
client := newClient(tags)
return client, client.SetDSN(dsn)
} | go | {
"resource": ""
} |
q8696 | SetIgnoreErrors | train | func (client *Client) SetIgnoreErrors(errs []string) error {
joinedRegexp := strings.Join(errs, "|")
r, err := regexp.Compile(joinedRegexp)
if err != nil {
return fmt.Errorf("raven: failed to compile regexp %q for %q: %v", joinedRegexp, errs, err)
}
client.mu.Lock()
client.ignoreErrorsRegexp = r
client.mu.Unlock()
return nil
} | go | {
"resource": ""
} |
q8697 | SetDSN | train | func (client *Client) SetDSN(dsn string) error {
if dsn == "" {
return nil
}
client.mu.Lock()
defer client.mu.Unlock()
uri, err := url.Parse(dsn)
if err != nil {
return err
}
if uri.User == nil {
return ErrMissingUser
}
publicKey := uri.User.Username()
secretKey, hasSecretKey := uri.User.Password()
uri.User = nil
if idx := strings.LastIndex(uri.Path, "/"); idx != -1 {
client.projectID = uri.Path[idx+1:]
uri.Path = uri.Path[:idx+1] + "api/" + client.projectID + "/store/"
}
if client.projectID == "" {
return ErrMissingProjectID
}
client.url = uri.String()
if hasSecretKey {
client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s, sentry_secret=%s", publicKey, secretKey)
} else {
client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s", publicKey)
}
return nil
} | go | {
"resource": ""
} |
q8698 | SetRelease | train | func (client *Client) SetRelease(release string) {
client.mu.Lock()
defer client.mu.Unlock()
client.release = release
} | go | {
"resource": ""
} |
q8699 | SetEnvironment | train | func (client *Client) SetEnvironment(environment string) {
client.mu.Lock()
defer client.mu.Unlock()
client.environment = environment
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.