_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q179900
Do
test
func (p *DisposeBrowserContextParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandDisposeBrowserContext, p, nil) }
go
{ "resource": "" }
q179901
WithSessionID
test
func (p SendMessageToTargetParams) WithSessionID(sessionID SessionID) *SendMessageToTargetParams { p.SessionID = sessionID return &p }
go
{ "resource": "" }
q179902
Do
test
func (p *SendMessageToTargetParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSendMessageToTarget, p, nil) }
go
{ "resource": "" }
q179903
Do
test
func (p *SetAutoAttachParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetAutoAttach, p, nil) }
go
{ "resource": "" }
q179904
Do
test
func (p *SetDiscoverTargetsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetDiscoverTargets, p, nil) }
go
{ "resource": "" }
q179905
Do
test
func (p *SetRemoteLocationsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetRemoteLocations, p, nil) }
go
{ "resource": "" }
q179906
WithPatterns
test
func (p EnableParams) WithPatterns(patterns []*RequestPattern) *EnableParams { p.Patterns = patterns return &p }
go
{ "resource": "" }
q179907
WithHandleAuthRequests
test
func (p EnableParams) WithHandleAuthRequests(handleAuthRequests bool) *EnableParams { p.HandleAuthRequests = handleAuthRequests return &p }
go
{ "resource": "" }
q179908
Do
test
func (p *FailRequestParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandFailRequest, p, nil) }
go
{ "resource": "" }
q179909
WithBody
test
func (p FulfillRequestParams) WithBody(body string) *FulfillRequestParams { p.Body = body return &p }
go
{ "resource": "" }
q179910
WithResponsePhrase
test
func (p FulfillRequestParams) WithResponsePhrase(responsePhrase string) *FulfillRequestParams { p.ResponsePhrase = responsePhrase return &p }
go
{ "resource": "" }
q179911
Do
test
func (p *FulfillRequestParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandFulfillRequest, p, nil) }
go
{ "resource": "" }
q179912
WithURL
test
func (p ContinueRequestParams) WithURL(url string) *ContinueRequestParams { p.URL = url return &p }
go
{ "resource": "" }
q179913
WithMethod
test
func (p ContinueRequestParams) WithMethod(method string) *ContinueRequestParams { p.Method = method return &p }
go
{ "resource": "" }
q179914
WithPostData
test
func (p ContinueRequestParams) WithPostData(postData string) *ContinueRequestParams { p.PostData = postData return &p }
go
{ "resource": "" }
q179915
WithHeaders
test
func (p ContinueRequestParams) WithHeaders(headers []*HeaderEntry) *ContinueRequestParams { p.Headers = headers return &p }
go
{ "resource": "" }
q179916
Do
test
func (p *ContinueRequestParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueRequest, p, nil) }
go
{ "resource": "" }
q179917
Do
test
func (p *ContinueWithAuthParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueWithAuth, p, nil) }
go
{ "resource": "" }
q179918
Do
test
func (p *ContinueToLocationParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueToLocation, p, nil) }
go
{ "resource": "" }
q179919
WithIncludeCommandLineAPI
test
func (p EvaluateOnCallFrameParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *EvaluateOnCallFrameParams { p.IncludeCommandLineAPI = includeCommandLineAPI return &p }
go
{ "resource": "" }
q179920
Do
test
func (p *PauseParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandPause, nil, nil) }
go
{ "resource": "" }
q179921
Do
test
func (p *PauseOnAsyncCallParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandPauseOnAsyncCall, p, nil) }
go
{ "resource": "" }
q179922
Do
test
func (p *RemoveBreakpointParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRemoveBreakpoint, p, nil) }
go
{ "resource": "" }
q179923
Do
test
func (p *ResumeParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandResume, nil, nil) }
go
{ "resource": "" }
q179924
Do
test
func (p *SetAsyncCallStackDepthParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetAsyncCallStackDepth, p, nil) }
go
{ "resource": "" }
q179925
Do
test
func (p *SetBlackboxPatternsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxPatterns, p, nil) }
go
{ "resource": "" }
q179926
Do
test
func (p *SetBlackboxedRangesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxedRanges, p, nil) }
go
{ "resource": "" }
q179927
WithURL
test
func (p SetBreakpointByURLParams) WithURL(url string) *SetBreakpointByURLParams { p.URL = url return &p }
go
{ "resource": "" }
q179928
WithURLRegex
test
func (p SetBreakpointByURLParams) WithURLRegex(urlRegex string) *SetBreakpointByURLParams { p.URLRegex = urlRegex return &p }
go
{ "resource": "" }
q179929
WithScriptHash
test
func (p SetBreakpointByURLParams) WithScriptHash(scriptHash string) *SetBreakpointByURLParams { p.ScriptHash = scriptHash return &p }
go
{ "resource": "" }
q179930
WithColumnNumber
test
func (p SetBreakpointByURLParams) WithColumnNumber(columnNumber int64) *SetBreakpointByURLParams { p.ColumnNumber = columnNumber return &p }
go
{ "resource": "" }
q179931
WithCondition
test
func (p SetBreakpointOnFunctionCallParams) WithCondition(condition string) *SetBreakpointOnFunctionCallParams { p.Condition = condition return &p }
go
{ "resource": "" }
q179932
Do
test
func (p *SetBreakpointsActiveParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBreakpointsActive, p, nil) }
go
{ "resource": "" }
q179933
Do
test
func (p *SetPauseOnExceptionsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetPauseOnExceptions, p, nil) }
go
{ "resource": "" }
q179934
Do
test
func (p *SetReturnValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetReturnValue, p, nil) }
go
{ "resource": "" }
q179935
WithDryRun
test
func (p SetScriptSourceParams) WithDryRun(dryRun bool) *SetScriptSourceParams { p.DryRun = dryRun return &p }
go
{ "resource": "" }
q179936
Do
test
func (p *SetSkipAllPausesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetSkipAllPauses, p, nil) }
go
{ "resource": "" }
q179937
Do
test
func (p *SetVariableValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetVariableValue, p, nil) }
go
{ "resource": "" }
q179938
WithBreakOnAsyncCall
test
func (p StepIntoParams) WithBreakOnAsyncCall(breakOnAsyncCall bool) *StepIntoParams { p.BreakOnAsyncCall = breakOnAsyncCall return &p }
go
{ "resource": "" }
q179939
Do
test
func (p *StepIntoParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepInto, p, nil) }
go
{ "resource": "" }
q179940
Do
test
func (p *StepOutParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOut, nil, nil) }
go
{ "resource": "" }
q179941
Do
test
func (p *StepOverParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOver, nil, nil) }
go
{ "resource": "" }
q179942
Listen
test
func (nb *NotifyBundle) Listen(n Network, a ma.Multiaddr) { if nb.ListenF != nil { nb.ListenF(n, a) } }
go
{ "resource": "" }
q179943
ListenClose
test
func (nb *NotifyBundle) ListenClose(n Network, a ma.Multiaddr) { if nb.ListenCloseF != nil { nb.ListenCloseF(n, a) } }
go
{ "resource": "" }
q179944
Connected
test
func (nb *NotifyBundle) Connected(n Network, c Conn) { if nb.ConnectedF != nil { nb.ConnectedF(n, c) } }
go
{ "resource": "" }
q179945
Disconnected
test
func (nb *NotifyBundle) Disconnected(n Network, c Conn) { if nb.DisconnectedF != nil { nb.DisconnectedF(n, c) } }
go
{ "resource": "" }
q179946
OpenedStream
test
func (nb *NotifyBundle) OpenedStream(n Network, s Stream) { if nb.OpenedStreamF != nil { nb.OpenedStreamF(n, s) } }
go
{ "resource": "" }
q179947
ClosedStream
test
func (nb *NotifyBundle) ClosedStream(n Network, s Stream) { if nb.ClosedStreamF != nil { nb.ClosedStreamF(n, s) } }
go
{ "resource": "" }
q179948
WithNoDial
test
func WithNoDial(ctx context.Context, reason string) context.Context { return context.WithValue(ctx, noDial, reason) }
go
{ "resource": "" }
q179949
GetNoDial
test
func GetNoDial(ctx context.Context) (nodial bool, reason string) { v := ctx.Value(noDial) if v != nil { return true, v.(string) } return false, "" }
go
{ "resource": "" }
q179950
WithDialPeerTimeout
test
func WithDialPeerTimeout(ctx context.Context, timeout time.Duration) context.Context { return context.WithValue(ctx, dialPeerTimeoutCtxKey{}, timeout) }
go
{ "resource": "" }
q179951
Open
test
func (drv *Driver) Open(name string) (driver.Conn, error) { conn, err := drv.Driver.Open(name) if err != nil { return conn, err } wrapped := &Conn{conn, drv.hooks} if isExecer(conn) && isQueryer(conn) && isSessionResetter(conn) { return &ExecerQueryerContextWithSessionResetter{wrapped, &ExecerContext{wrapped}, &QueryerContext{wrapped}, &SessionResetter{wrapped}}, nil } else if isExecer(conn) && isQueryer(conn) { return &ExecerQueryerContext{wrapped, &ExecerContext{wrapped}, &QueryerContext{wrapped}}, nil } else if isExecer(conn) { // If conn implements an Execer interface, return a driver.Conn which // also implements Execer return &ExecerContext{wrapped}, nil } else if isQueryer(conn) { // If conn implements an Queryer interface, return a driver.Conn which // also implements Queryer return &QueryerContext{wrapped}, nil } return wrapped, nil }
go
{ "resource": "" }
q179952
Prevpos
test
func (f *FixedSizeRingBuf) Prevpos(from int) int { if from >= f.N || from < 0 { return -2 } if f.Readable == 0 { return -1 } if from == f.Beg { return -1 } a0, a1, b0, b1 := f.LegalPos() switch { case from == a0: return -1 case from > a0 && from <= a1: return from - 1 case from == b0: return a1 case from > b0 && from <= b1: return from - 1 } return -1 }
go
{ "resource": "" }
q179953
Last
test
func (f *FixedSizeRingBuf) Last() int { if f.Readable == 0 { return -1 } last := f.Beg + f.Readable - 1 if last < f.N { // we fit without wrapping return last } return last % f.N }
go
{ "resource": "" }
q179954
DeleteMostRecentBytes
test
func (f *FixedSizeRingBuf) DeleteMostRecentBytes(n int) { if n <= 0 { return } if n >= f.Readable { f.Readable = 0 return } f.Readable -= n }
go
{ "resource": "" }
q179955
NewFloat64RingBuf
test
func NewFloat64RingBuf(maxViewItems int) *Float64RingBuf { n := maxViewItems r := &Float64RingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]float64, n, n) return r }
go
{ "resource": "" }
q179956
TwoContig
test
func (b *Float64RingBuf) TwoContig(makeCopy bool) (first []float64, second []float64) { extent := b.Beg + b.Readable if extent <= b.N { // we fit contiguously in this buffer without wrapping to the other. // Let second stay an empty slice. return b.A[b.Beg:(b.Beg + b.Readable)], second } return b.A[b.Beg:b.N], b.A[0:(extent % b.N)] }
go
{ "resource": "" }
q179957
Earliest
test
func (b *Float64RingBuf) Earliest() (v float64, ok bool) { if b.Readable == 0 { return } return b.A[b.Beg], true }
go
{ "resource": "" }
q179958
Values
test
func (b *Float64RingBuf) Values() []float64 { first, second := b.TwoContig(false) if len(first) == 0 { return second } if len(second) == 0 { return first } out := make([]float64, len(first) + len(second)) copy(out, first) copy(out[len(first):], second) return out }
go
{ "resource": "" }
q179959
NewAtomicFixedSizeRingBuf
test
func NewAtomicFixedSizeRingBuf(maxViewInBytes int) *AtomicFixedSizeRingBuf { n := maxViewInBytes r := &AtomicFixedSizeRingBuf{ Use: 0, // 0 or 1, whichever is actually in use at the moment. // If we are asked for Bytes() and we wrap, linearize into the other. N: n, Beg: 0, readable: 0, } r.A[0] = make([]byte, n, n) r.A[1] = make([]byte, n, n) return r }
go
{ "resource": "" }
q179960
Reset
test
func (b *AtomicFixedSizeRingBuf) Reset() { b.tex.Lock() defer b.tex.Unlock() b.Beg = 0 b.readable = 0 b.Use = 0 }
go
{ "resource": "" }
q179961
NewPointerRingBuf
test
func NewPointerRingBuf(sliceN int) *PointerRingBuf { n := sliceN r := &PointerRingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]interface{}, n, n) return r }
go
{ "resource": "" }
q179962
TwoContig
test
func (b *PointerRingBuf) TwoContig() (first []interface{}, second []interface{}) { extent := b.Beg + b.Readable if extent <= b.N { // we fit contiguously in this buffer without wrapping to the other. // Let second stay an empty slice. return b.A[b.Beg:(b.Beg + b.Readable)], second } return b.A[b.Beg:b.N], b.A[0:(extent % b.N)] }
go
{ "resource": "" }
q179963
NumPage
test
func (r *Reader) NumPage() int { return int(r.Trailer().Key("Root").Key("Pages").Key("Count").Int64()) }
go
{ "resource": "" }
q179964
Font
test
func (p Page) Font(name string) Font { return Font{p.Resources().Key("Font").Key(name)} }
go
{ "resource": "" }
q179965
Width
test
func (f Font) Width(code int) float64 { first := f.FirstChar() last := f.LastChar() if code < first || last < code { return 0 } return f.V.Key("Widths").Index(code - first).Float64() }
go
{ "resource": "" }
q179966
Encoder
test
func (f Font) Encoder() TextEncoding { enc := f.V.Key("Encoding") switch enc.Kind() { case Name: switch enc.Name() { case "WinAnsiEncoding": return &byteEncoder{&winAnsiEncoding} case "MacRomanEncoding": return &byteEncoder{&macRomanEncoding} case "Identity-H": // TODO: Should be big-endian UCS-2 decoder return &nopEncoder{} default: println("unknown encoding", enc.Name()) return &nopEncoder{} } case Dict: return &dictEncoder{enc.Key("Differences")} case Null: // ok, try ToUnicode default: println("unexpected encoding", enc.String()) return &nopEncoder{} } toUnicode := f.V.Key("ToUnicode") if toUnicode.Kind() == Dict { m := readCmap(toUnicode) if m == nil { return &nopEncoder{} } return m } return &byteEncoder{&pdfDocEncoding} }
go
{ "resource": "" }
q179967
Interpret
test
func Interpret(strm Value, do func(stk *Stack, op string)) { rd := strm.Reader() b := newBuffer(rd, 0) b.allowEOF = true b.allowObjptr = false b.allowStream = false var stk Stack var dicts []dict Reading: for { tok := b.readToken() if tok == io.EOF { break } if kw, ok := tok.(keyword); ok { switch kw { case "null", "[", "]", "<<", ">>": break default: for i := len(dicts) - 1; i >= 0; i-- { if v, ok := dicts[i][name(kw)]; ok { stk.Push(Value{nil, objptr{}, v}) continue Reading } } do(&stk, string(kw)) continue case "dict": stk.Pop() stk.Push(Value{nil, objptr{}, make(dict)}) continue case "currentdict": if len(dicts) == 0 { panic("no current dictionary") } stk.Push(Value{nil, objptr{}, dicts[len(dicts)-1]}) continue case "begin": d := stk.Pop() if d.Kind() != Dict { panic("cannot begin non-dict") } dicts = append(dicts, d.data.(dict)) continue case "end": if len(dicts) <= 0 { panic("mismatched begin/end") } dicts = dicts[:len(dicts)-1] continue case "def": if len(dicts) <= 0 { panic("def without open dict") } val := stk.Pop() key, ok := stk.Pop().data.(name) if !ok { panic("def of non-name") } dicts[len(dicts)-1][key] = val.data continue case "pop": stk.Pop() continue } } b.unreadToken(tok) obj := b.readObject() stk.Push(Value{nil, objptr{}, obj}) } }
go
{ "resource": "" }
q179968
Open
test
func Open(file string) (*Reader, error) { // TODO: Deal with closing file. f, err := os.Open(file) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { f.Close() return nil, err } return NewReader(f, fi.Size()) }
go
{ "resource": "" }
q179969
NewReader
test
func NewReader(f io.ReaderAt, size int64) (*Reader, error) { return NewReaderEncrypted(f, size, nil) }
go
{ "resource": "" }
q179970
NewReaderEncrypted
test
func NewReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (*Reader, error) { buf := make([]byte, 10) f.ReadAt(buf, 0) if !bytes.HasPrefix(buf, []byte("%PDF-1.")) || buf[7] < '0' || buf[7] > '7' || buf[8] != '\r' && buf[8] != '\n' { return nil, fmt.Errorf("not a PDF file: invalid header") } end := size const endChunk = 100 buf = make([]byte, endChunk) f.ReadAt(buf, end-endChunk) for len(buf) > 0 && buf[len(buf)-1] == '\n' || buf[len(buf)-1] == '\r' { buf = buf[:len(buf)-1] } buf = bytes.TrimRight(buf, "\r\n\t ") if !bytes.HasSuffix(buf, []byte("%%EOF")) { return nil, fmt.Errorf("not a PDF file: missing %%%%EOF") } i := findLastLine(buf, "startxref") if i < 0 { return nil, fmt.Errorf("malformed PDF file: missing final startxref") } r := &Reader{ f: f, end: end, } pos := end - endChunk + int64(i) b := newBuffer(io.NewSectionReader(f, pos, end-pos), pos) if b.readToken() != keyword("startxref") { return nil, fmt.Errorf("malformed PDF file: missing startxref") } startxref, ok := b.readToken().(int64) if !ok { return nil, fmt.Errorf("malformed PDF file: startxref not followed by integer") } b = newBuffer(io.NewSectionReader(r.f, startxref, r.end-startxref), startxref) xref, trailerptr, trailer, err := readXref(r, b) if err != nil { return nil, err } r.xref = xref r.trailer = trailer r.trailerptr = trailerptr if trailer["Encrypt"] == nil { return r, nil } err = r.initEncrypt("") if err == nil { return r, nil } if pw == nil || err != ErrInvalidPassword { return nil, err } for { next := pw() if next == "" { break } if r.initEncrypt(next) == nil { return r, nil } } return nil, err }
go
{ "resource": "" }
q179971
Trailer
test
func (r *Reader) Trailer() Value { return Value{r, r.trailerptr, r.trailer} }
go
{ "resource": "" }
q179972
Kind
test
func (v Value) Kind() ValueKind { switch v.data.(type) { default: return Null case bool: return Bool case int64: return Integer case float64: return Real case string: return String case name: return Name case dict: return Dict case array: return Array case stream: return Stream } }
go
{ "resource": "" }
q179973
newBuffer
test
func newBuffer(r io.Reader, offset int64) *buffer { return &buffer{ r: r, offset: offset, buf: make([]byte, 0, 4096), allowObjptr: true, allowStream: true, } }
go
{ "resource": "" }
q179974
Paginate
test
func (r *ResultSet) Paginate(perPage, page int) (*PaginationInfo, error) { info := new(PaginationInfo) // Get count on a different session to avoid blocking sess := r.Collection.Connection.Session.Copy() count, err := sess.DB(r.Collection.Database).C(r.Collection.Name).Find(r.Params).Count() sess.Close() if err != nil { return info, err } // Calculate how many pages totalPages := int(math.Ceil(float64(count) / float64(perPage))) if page < 1 { page = 1 } else if page > totalPages { page = totalPages } skip := (page - 1) * perPage r.Query.Skip(skip).Limit(perPage) info.TotalPages = totalPages info.PerPage = perPage info.Current = page info.TotalRecords = count if info.Current < info.TotalPages { info.RecordsOnPage = info.PerPage } else { info.RecordsOnPage = int(math.Mod(float64(count), float64(perPage))) if info.RecordsOnPage == 0 && count > 0 { info.RecordsOnPage = perPage } } return info, nil }
go
{ "resource": "" }
q179975
CascadeDelete
test
func CascadeDelete(collection *Collection, doc interface{}) { // Find out which properties to cascade if conv, ok := doc.(interface { GetCascade(*Collection) []*CascadeConfig }); ok { toCascade := conv.GetCascade(collection) // Get the ID for _, conf := range toCascade { if len(conf.ReferenceQuery) == 0 { id, err := reflections.GetField(doc, "Id") if err != nil { panic(err) } conf.ReferenceQuery = []*ReferenceField{&ReferenceField{"_id", id}} } cascadeDeleteWithConfig(conf) } } }
go
{ "resource": "" }
q179976
cascadeDeleteWithConfig
test
func cascadeDeleteWithConfig(conf *CascadeConfig) (*mgo.ChangeInfo, error) { switch conf.RelType { case REL_ONE: update := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update["$set"][p] = nil } } return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update["$pull"][conf.ThroughProp] = q return conf.Collection.Collection().UpdateAll(conf.Query, update) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
go
{ "resource": "" }
q179977
cascadeSaveWithConfig
test
func cascadeSaveWithConfig(conf *CascadeConfig, doc Document) (*mgo.ChangeInfo, error) { // Create a new map with just the props to cascade data := conf.Data switch conf.RelType { case REL_ONE: if len(conf.OldQuery) > 0 { update1 := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update1["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update1["$set"][p] = nil } } ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } update := make(map[string]interface{}) if len(conf.ThroughProp) > 0 { m := bson.M{} m[conf.ThroughProp] = data update["$set"] = m } else { update["$set"] = data } // Just update return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update1 := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update1["$pull"][conf.ThroughProp] = q if len(conf.OldQuery) > 0 { ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } // Remove self from current relations, so we can replace it conf.Collection.Collection().UpdateAll(conf.Query, update1) update2 := map[string]map[string]interface{}{ "$push": map[string]interface{}{}, } update2["$push"][conf.ThroughProp] = data return conf.Collection.Collection().UpdateAll(conf.Query, update2) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
go
{ "resource": "" }
q179978
MapFromCascadeProperties
test
func MapFromCascadeProperties(properties []string, doc Document) map[string]interface{} { data := make(map[string]interface{}) for _, prop := range properties { split := strings.Split(prop, ".") if len(split) == 1 { data[prop], _ = dotaccess.Get(doc, prop) } else { actualProp := split[len(split)-1] split := append([]string{}, split[:len(split)-1]...) curData := data for _, s := range split { if _, ok := curData[s]; ok { if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } else { curData[s] = make(map[string]interface{}) if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } } val, _ := dotaccess.Get(doc, prop) // if bsonId, ok := val.(bson.ObjectId); ok { // if !bsonId.Valid() { // curData[actualProp] = "" // continue // } // } curData[actualProp] = val } } return data }
go
{ "resource": "" }
q179979
Connect
test
func (m *Connection) Connect() (err error) { defer func() { if r := recover(); r != nil { // panic(r) // return if e, ok := r.(error); ok { err = e } else if e, ok := r.(string); ok { err = errors.New(e) } else { err = errors.New(fmt.Sprint(r)) } } }() if m.Config.DialInfo == nil { if m.Config.DialInfo, err = mgo.ParseURL(m.Config.ConnectionString); err != nil { panic(fmt.Sprintf("cannot parse given URI %s due to error: %s", m.Config.ConnectionString, err.Error())) } } session, err := mgo.DialWithInfo(m.Config.DialInfo) if err != nil { return err } m.Session = session m.Session.SetMode(mgo.Monotonic, true) return nil }
go
{ "resource": "" }
q179980
lowerInitial
test
func lowerInitial(str string) string { for i, v := range str { return string(unicode.ToLower(v)) + str[i+1:] } return "" }
go
{ "resource": "" }
q179981
Find
test
func (c *Collection) Find(query interface{}) *ResultSet { col := c.Collection() // Count for testing q := col.Find(query) resultset := new(ResultSet) resultset.Query = q resultset.Params = query resultset.Collection = c return resultset }
go
{ "resource": "" }
q179982
RawInformationQuery
test
func (c *Client) RawInformationQuery(from, to, id, iqType, requestNamespace, body string) (string, error) { const xmlIQ = "<iq from='%s' to='%s' id='%s' type='%s'><query xmlns='%s'>%s</query></iq>" _, err := fmt.Fprintf(c.conn, xmlIQ, xmlEscape(from), xmlEscape(to), id, iqType, requestNamespace, body) return id, err }
go
{ "resource": "" }
q179983
NewClient
test
func (o Options) NewClient() (*Client, error) { host := o.Host c, err := connect(host, o.User, o.Password) if err != nil { return nil, err } if strings.LastIndex(o.Host, ":") > 0 { host = host[:strings.LastIndex(o.Host, ":")] } client := new(Client) if o.NoTLS { client.conn = c } else { var tlsconn *tls.Conn if o.TLSConfig != nil { tlsconn = tls.Client(c, o.TLSConfig) } else { DefaultConfig.ServerName = host newconfig := DefaultConfig newconfig.ServerName = host tlsconn = tls.Client(c, &newconfig) } if err = tlsconn.Handshake(); err != nil { return nil, err } insecureSkipVerify := DefaultConfig.InsecureSkipVerify if o.TLSConfig != nil { insecureSkipVerify = o.TLSConfig.InsecureSkipVerify } if !insecureSkipVerify { if err = tlsconn.VerifyHostname(host); err != nil { return nil, err } } client.conn = tlsconn } if err := client.init(&o); err != nil { client.Close() return nil, err } return client, nil }
go
{ "resource": "" }
q179984
Close
test
func (c *Client) Close() error { if c.conn != (*tls.Conn)(nil) { return c.conn.Close() } return nil }
go
{ "resource": "" }
q179985
startTLSIfRequired
test
func (c *Client) startTLSIfRequired(f *streamFeatures, o *Options, domain string) (*streamFeatures, error) { // whether we start tls is a matter of opinion: the server's and the user's. switch { case f.StartTLS == nil: // the server does not support STARTTLS return f, nil case !o.StartTLS && f.StartTLS.Required == nil: return f, nil case f.StartTLS.Required != nil: // the server requires STARTTLS. case !o.StartTLS: // the user wants STARTTLS and the server supports it. } var err error fmt.Fprintf(c.conn, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n") var k tlsProceed if err = c.p.DecodeElement(&k, nil); err != nil { return f, errors.New("unmarshal <proceed>: " + err.Error()) } tc := o.TLSConfig if tc == nil { tc = new(tls.Config) *tc = DefaultConfig //TODO(scott): we should consider using the server's address or reverse lookup tc.ServerName = domain } t := tls.Client(c.conn, tc) if err = t.Handshake(); err != nil { return f, errors.New("starttls handshake: " + err.Error()) } c.conn = t // restart our declaration of XMPP stream intentions. tf, err := c.startStream(o, domain) if err != nil { return f, err } return tf, nil }
go
{ "resource": "" }
q179986
startStream
test
func (c *Client) startStream(o *Options, domain string) (*streamFeatures, error) { if o.Debug { c.p = xml.NewDecoder(tee{c.conn, DebugWriter}) } else { c.p = xml.NewDecoder(c.conn) } _, err := fmt.Fprintf(c.conn, "<?xml version='1.0'?>\n"+ "<stream:stream to='%s' xmlns='%s'\n"+ " xmlns:stream='%s' version='1.0'>\n", xmlEscape(domain), nsClient, nsStream) if err != nil { return nil, err } // We expect the server to start a <stream>. se, err := nextStart(c.p) if err != nil { return nil, err } if se.Name.Space != nsStream || se.Name.Local != "stream" { return nil, fmt.Errorf("expected <stream> but got <%v> in %v", se.Name.Local, se.Name.Space) } // Now we're in the stream and can use Unmarshal. // Next message should be <features> to tell us authentication options. // See section 4.6 in RFC 3920. f := new(streamFeatures) if err = c.p.DecodeElement(f, nil); err != nil { return f, errors.New("unmarshal <features>: " + err.Error()) } return f, nil }
go
{ "resource": "" }
q179987
IsEncrypted
test
func (c *Client) IsEncrypted() bool { _, ok := c.conn.(*tls.Conn) return ok }
go
{ "resource": "" }
q179988
Recv
test
func (c *Client) Recv() (stanza interface{}, err error) { for { _, val, err := next(c.p) if err != nil { return Chat{}, err } switch v := val.(type) { case *clientMessage: stamp, _ := time.Parse( "2006-01-02T15:04:05Z", v.Delay.Stamp, ) chat := Chat{ Remote: v.From, Type: v.Type, Text: v.Body, Subject: v.Subject, Thread: v.Thread, Other: v.OtherStrings(), OtherElem: v.Other, Stamp: stamp, } return chat, nil case *clientQuery: var r Roster for _, item := range v.Item { r = append(r, Contact{item.Jid, item.Name, item.Group}) } return Chat{Type: "roster", Roster: r}, nil case *clientPresence: return Presence{v.From, v.To, v.Type, v.Show, v.Status}, nil case *clientIQ: // TODO check more strictly if bytes.Equal(bytes.TrimSpace(v.Query), []byte(`<ping xmlns='urn:xmpp:ping'/>`)) || bytes.Equal(bytes.TrimSpace(v.Query), []byte(`<ping xmlns="urn:xmpp:ping"/>`)) { err := c.SendResultPing(v.ID, v.From) if err != nil { return Chat{}, err } } return IQ{ID: v.ID, From: v.From, To: v.To, Type: v.Type, Query: v.Query}, nil } } }
go
{ "resource": "" }
q179989
Send
test
func (c *Client) Send(chat Chat) (n int, err error) { var subtext = `` var thdtext = `` if chat.Subject != `` { subtext = `<subject>` + xmlEscape(chat.Subject) + `</subject>` } if chat.Thread != `` { thdtext = `<thread>` + xmlEscape(chat.Thread) + `</thread>` } stanza := "<message to='%s' type='%s' id='%s' xml:lang='en'>" + subtext + "<body>%s</body>" + thdtext + "</message>" return fmt.Fprintf(c.conn, stanza, xmlEscape(chat.Remote), xmlEscape(chat.Type), cnonce(), xmlEscape(chat.Text)) }
go
{ "resource": "" }
q179990
SendOrg
test
func (c *Client) SendOrg(org string) (n int, err error) { return fmt.Fprint(c.conn, org) }
go
{ "resource": "" }
q179991
SendKeepAlive
test
func (c *Client) SendKeepAlive() (n int, err error) { return fmt.Fprintf(c.conn, " ") }
go
{ "resource": "" }
q179992
SendHtml
test
func (c *Client) SendHtml(chat Chat) (n int, err error) { return fmt.Fprintf(c.conn, "<message to='%s' type='%s' xml:lang='en'>"+ "<body>%s</body>"+ "<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns='http://www.w3.org/1999/xhtml'>%s</body></html></message>", xmlEscape(chat.Remote), xmlEscape(chat.Type), xmlEscape(chat.Text), chat.Text) }
go
{ "resource": "" }
q179993
nextStart
test
func nextStart(p *xml.Decoder) (xml.StartElement, error) { for { t, err := p.Token() if err != nil || t == nil { return xml.StartElement{}, err } switch t := t.(type) { case xml.StartElement: return t, nil } } }
go
{ "resource": "" }
q179994
JoinProtectedMUC
test
func (c *Client) JoinProtectedMUC(jid, nick string, password string, history_type, history int, history_date *time.Time) (n int, err error) { if nick == "" { nick = c.jid } switch history_type { case NoHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>"+ "</x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password)) case CharHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history maxchars='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case StanzaHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history maxstanzas='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case SecondsHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history seconds='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case SinceHistory: if history_date != nil { return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history since='%s'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history_date.Format(time.RFC3339)) } } return 0, errors.New("Unknown history option") }
go
{ "resource": "" }
q179995
LeaveMUC
test
func (c *Client) LeaveMUC(jid string) (n int, err error) { return fmt.Fprintf(c.conn, "<presence from='%s' to='%s' type='unavailable' />", c.jid, xmlEscape(jid)) }
go
{ "resource": "" }
q179996
AttachBuffer
test
func (m *Message) AttachBuffer(filename string, buf []byte, inline bool) error { m.Attachments[filename] = &Attachment{ Filename: filename, Data: buf, Inline: inline, } return nil }
go
{ "resource": "" }
q179997
Attach
test
func (m *Message) Attach(file string) error { return m.attach(file, false) }
go
{ "resource": "" }
q179998
Inline
test
func (m *Message) Inline(file string) error { return m.attach(file, true) }
go
{ "resource": "" }
q179999
AddHeader
test
func (m *Message) AddHeader(key string, value string) Header { newHeader := Header{Key: key, Value: value} m.Headers = append(m.Headers, newHeader) return newHeader }
go
{ "resource": "" }