_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q37300
printCaption
train
func (t Table) printCaption() { width := t.getTableWidth() paragraph, _ := WrapString(t.captionText, width) for linecount := 0; linecount < len(paragraph); linecount++ { fmt.Fprintln(t.out, paragraph[linecount]) } }
go
{ "resource": "" }
q37301
getTableWidth
train
func (t Table) getTableWidth() int { var chars int for _, v := range t.cs { chars += v } // Add chars, spaces, seperators to calculate the total width of the table. // ncols := t.colSize // spaces := ncols * 2 // seps := ncols + 1 return (chars + (3 * t.colSize) + 2) }
go
{ "resource": "" }
q37302
printRow
train
func (t *Table) printRow(columns [][]string, rowIdx int) { // Get Maximum Height max := t.rs[rowIdx] total := len(columns) // TODO Fix uneven col size // if total < t.colSize { // for n := t.colSize - total; n < t.colSize ; n++ { // columns = append(columns, []string{SPACE}) // t.cs[n] = t.mW // } //} //...
go
{ "resource": "" }
q37303
printRowsMergeCells
train
func (t *Table) printRowsMergeCells() { var previousLine []string var displayCellBorder []bool var tmpWriter bytes.Buffer for i, lines := range t.lines { // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above previousLine, displayCellBorder = t.print...
go
{ "resource": "" }
q37304
NewCSV
train
func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) { file, err := os.Open(fileName) if err != nil { return &Table{}, err } defer file.Close() csvReader := csv.NewReader(file) t, err := NewCSVReader(writer, csvReader, hasHeader) return t, err }
go
{ "resource": "" }
q37305
format
train
func format(s string, codes interface{}) string { var seq string switch v := codes.(type) { case string: seq = v case []int: seq = makeSequence(v) default: return s } if len(seq) == 0 { return s } return startFormat(seq) + s + stopFormat() }
go
{ "resource": "" }
q37306
ConditionString
train
func ConditionString(cond bool, valid, inValid string) string { if cond { return valid } return inValid }
go
{ "resource": "" }
q37307
Title
train
func Title(name string) string { origLen := len(name) rs := []rune(name) for i, r := range rs { switch r { case '_': rs[i] = ' ' case '.': // ignore floating number 0.0 if (i != 0 && !isNumOrSpace(rs[i-1])) || (i != len(rs)-1 && !isNumOrSpace(rs[i+1])) { rs[i] = ' ' } } } name = string(rs) ...
go
{ "resource": "" }
q37308
Pad
train
func Pad(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { gapLeft := int(math.Ceil(float64(gap / 2))) gapRight := gap - gapLeft return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight) } return s }
go
{ "resource": "" }
q37309
PadRight
train
func PadRight(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { return s + strings.Repeat(string(pad), gap) } return s }
go
{ "resource": "" }
q37310
ExtractGRPC
train
func ExtractGRPC(md *metadata.MD) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = GetGRPCHeader(md, TraceID) spanIDHeader = GetGRPCHeader(md, SpanID) parentSpanIDHeader = GetGRPCHeader(md, ParentSpanID) sampledHeader = GetGRPCHeader(md, Sampled) ...
go
{ "resource": "" }
q37311
InjectGRPC
train
func InjectGRPC(md *metadata.MD) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { setGRPCHeader(md, Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, /...
go
{ "resource": "" }
q37312
GetGRPCHeader
train
func GetGRPCHeader(md *metadata.MD, key string) string { v := (*md)[key] if len(v) < 1 { return "" } return v[len(v)-1] }
go
{ "resource": "" }
q37313
Send
train
func (r *ReporterRecorder) Send(span model.SpanModel) { r.mtx.Lock() r.spans = append(r.spans, span) r.mtx.Unlock() }
go
{ "resource": "" }
q37314
Flush
train
func (r *ReporterRecorder) Flush() []model.SpanModel { r.mtx.Lock() spans := r.spans r.spans = nil r.mtx.Unlock() return spans }
go
{ "resource": "" }
q37315
WithLocalEndpoint
train
func WithLocalEndpoint(e *model.Endpoint) TracerOption { return func(o *Tracer) error { if e == nil { o.localEndpoint = nil return nil } ep := *e o.localEndpoint = &ep return nil } }
go
{ "resource": "" }
q37316
WithExtractFailurePolicy
train
func WithExtractFailurePolicy(p ExtractFailurePolicy) TracerOption { return func(o *Tracer) error { if p < 0 || p > ExtractFailurePolicyTagAndRestart { return ErrInvalidExtractFailurePolicy } o.extractFailurePolicy = p return nil } }
go
{ "resource": "" }
q37317
WithNoopSpan
train
func WithNoopSpan(unsampledNoop bool) TracerOption { return func(o *Tracer) error { o.unsampledNoop = unsampledNoop return nil } }
go
{ "resource": "" }
q37318
WithSampler
train
func WithSampler(sampler Sampler) TracerOption { return func(o *Tracer) error { o.sampler = sampler return nil } }
go
{ "resource": "" }
q37319
WithTraceID128Bit
train
func WithTraceID128Bit(val bool) TracerOption { return func(o *Tracer) error { if val { o.generate = idgenerator.NewRandom128() } else { o.generate = idgenerator.NewRandom64() } return nil } }
go
{ "resource": "" }
q37320
WithIDGenerator
train
func WithIDGenerator(generator idgenerator.IDGenerator) TracerOption { return func(o *Tracer) error { o.generate = generator return nil } }
go
{ "resource": "" }
q37321
WithTags
train
func WithTags(tags map[string]string) TracerOption { return func(o *Tracer) error { for k, v := range tags { o.defaultTags[k] = v } return nil } }
go
{ "resource": "" }
q37322
WithNoopTracer
train
func WithNoopTracer(tracerNoop bool) TracerOption { return func(o *Tracer) error { if tracerNoop { o.noop = 1 } else { o.noop = 0 } return nil } }
go
{ "resource": "" }
q37323
NewClientHandler
train
func NewClientHandler(tracer *zipkin.Tracer, options ...ClientOption) stats.Handler { c := &clientHandler{ tracer: tracer, } for _, option := range options { option(c) } return c }
go
{ "resource": "" }
q37324
NewReporter
train
func NewReporter(l *log.Logger) reporter.Reporter { if l == nil { // use standard type of log setup l = log.New(os.Stderr, "", log.LstdFlags) } return &logReporter{ logger: l, } }
go
{ "resource": "" }
q37325
Send
train
func (r *logReporter) Send(s model.SpanModel) { if b, err := json.MarshalIndent(s, "", " "); err == nil { r.logger.Printf("%s:\n%s\n\n", time.Now(), string(b)) } }
go
{ "resource": "" }
q37326
NewContext
train
func NewContext(ctx context.Context, s Span) context.Context { return context.WithValue(ctx, spanKey, s) }
go
{ "resource": "" }
q37327
Timeout
train
func Timeout(duration time.Duration) ReporterOption { return func(r *httpReporter) { r.client.Timeout = duration } }
go
{ "resource": "" }
q37328
BatchInterval
train
func BatchInterval(d time.Duration) ReporterOption { return func(r *httpReporter) { r.batchInterval = d } }
go
{ "resource": "" }
q37329
Client
train
func Client(client *http.Client) ReporterOption { return func(r *httpReporter) { r.client = client } }
go
{ "resource": "" }
q37330
NewServerMiddleware
train
func NewServerMiddleware(t *zipkin.Tracer, options ...ServerOption) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { h := &handler{ tracer: t, next: next, } for _, option := range options { option(h) } return h } }
go
{ "resource": "" }
q37331
ParseSpans
train
func ParseSpans(protoBlob []byte, debugWasSet bool) (zss []*zipkinmodel.SpanModel, err error) { var listOfSpans ListOfSpans if err := proto.Unmarshal(protoBlob, &listOfSpans); err != nil { return nil, err } for _, zps := range listOfSpans.Spans { zms, err := protoSpanToModelSpan(zps, debugWasSet) if err != ni...
go
{ "resource": "" }
q37332
Serialize
train
func (SpanSerializer) Serialize(sms []*zipkinmodel.SpanModel) (protoBlob []byte, err error) { var listOfSpans ListOfSpans for _, sm := range sms { sp, err := modelSpanToProtoSpan(sm) if err != nil { return nil, err } listOfSpans.Spans = append(listOfSpans.Spans, sp) } return proto.Marshal(&listOfSpans)...
go
{ "resource": "" }
q37333
MarshalJSON
train
func (s SpanModel) MarshalJSON() ([]byte, error) { type Alias SpanModel var timestamp int64 if !s.Timestamp.IsZero() { if s.Timestamp.Unix() < 1 { // Zipkin does not allow Timestamps before Unix epoch return nil, ErrValidTimestampRequired } timestamp = s.Timestamp.Round(time.Microsecond).UnixNano() / 1e...
go
{ "resource": "" }
q37334
UnmarshalJSON
train
func (s *SpanModel) UnmarshalJSON(b []byte) error { type Alias SpanModel span := &struct { T uint64 `json:"timestamp,omitempty"` D uint64 `json:"duration,omitempty"` *Alias }{ Alias: (*Alias)(s), } if err := json.Unmarshal(b, &span); err != nil { return err } if s.ID < 1 { return ErrValidIDRequired ...
go
{ "resource": "" }
q37335
Set
train
func (t Tag) Set(s Span, value string) { s.Tag(string(t), value) }
go
{ "resource": "" }
q37336
NewModuloSampler
train
func NewModuloSampler(mod uint64) Sampler { if mod < 2 { return AlwaysSample } return func(id uint64) bool { return (id % mod) == 0 } }
go
{ "resource": "" }
q37337
NewTracer
train
func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) { // set default tracer options t := &Tracer{ defaultTags: make(map[string]string), extractFailurePolicy: ExtractFailurePolicyRestart, sampler: AlwaysSample, generate: idgenerator.NewRandom64(), re...
go
{ "resource": "" }
q37338
StartSpanFromContext
train
func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) { if parentSpan := SpanFromContext(ctx); parentSpan != nil { options = append(options, Parent(parentSpan.Context())) } span := t.StartSpan(name, options...) return span, NewContext(ctx, span) }
go
{ "resource": "" }
q37339
StartSpan
train
func (t *Tracer) StartSpan(name string, options ...SpanOption) Span { if atomic.LoadInt32(&t.noop) == 1 { return &noopSpan{} } s := &spanImpl{ SpanModel: model.SpanModel{ Kind: model.Undetermined, Name: name, LocalEndpoint: t.localEndpoint, Annotations: make([]model.Annotation, 0)...
go
{ "resource": "" }
q37340
Extract
train
func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) { if atomic.LoadInt32(&t.noop) == 1 { return } psc, err := extractor() if psc != nil { sc = *psc } sc.Err = err return }
go
{ "resource": "" }
q37341
SetNoop
train
func (t *Tracer) SetNoop(noop bool) { if noop { atomic.CompareAndSwapInt32(&t.noop, 0, 1) } else { atomic.CompareAndSwapInt32(&t.noop, 1, 0) } }
go
{ "resource": "" }
q37342
LocalEndpoint
train
func (t *Tracer) LocalEndpoint() *model.Endpoint { if t.localEndpoint == nil { return nil } ep := *t.localEndpoint return &ep }
go
{ "resource": "" }
q37343
NewEndpoint
train
func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) { e := &model.Endpoint{ ServiceName: serviceName, } if hostPort == "" || hostPort == ":0" { if serviceName == "" { // if all properties are empty we should not have an Endpoint object. return nil, nil } return e, nil } i...
go
{ "resource": "" }
q37344
Producer
train
func Producer(p sarama.AsyncProducer) ReporterOption { return func(c *kafkaReporter) { c.producer = p } }
go
{ "resource": "" }
q37345
NewServerHandler
train
func NewServerHandler(tracer *zipkin.Tracer, options ...ServerOption) stats.Handler { c := &serverHandler{ tracer: tracer, } for _, option := range options { option(c) } return c }
go
{ "resource": "" }
q37346
Kind
train
func Kind(kind model.Kind) SpanOption { return func(t *Tracer, s *spanImpl) { s.Kind = kind } }
go
{ "resource": "" }
q37347
Parent
train
func Parent(sc model.SpanContext) SpanOption { return func(t *Tracer, s *spanImpl) { if sc.Err != nil { // encountered an extraction error switch t.extractFailurePolicy { case ExtractFailurePolicyRestart: case ExtractFailurePolicyError: panic(s.SpanContext.Err) case ExtractFailurePolicyTagAndResta...
go
{ "resource": "" }
q37348
StartTime
train
func StartTime(start time.Time) SpanOption { return func(t *Tracer, s *spanImpl) { s.Timestamp = start } }
go
{ "resource": "" }
q37349
RemoteEndpoint
train
func RemoteEndpoint(e *model.Endpoint) SpanOption { return func(t *Tracer, s *spanImpl) { s.RemoteEndpoint = e } }
go
{ "resource": "" }
q37350
Tags
train
func Tags(tags map[string]string) SpanOption { return func(t *Tracer, s *spanImpl) { for k, v := range tags { s.Tags[k] = v } } }
go
{ "resource": "" }
q37351
String
train
func (t TraceID) String() string { if t.High == 0 { return fmt.Sprintf("%016x", t.Low) } return fmt.Sprintf("%016x%016x", t.High, t.Low) }
go
{ "resource": "" }
q37352
TraceIDFromHex
train
func TraceIDFromHex(h string) (t TraceID, err error) { if len(h) > 16 { if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil { return } t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64) return } t.Low, err = strconv.ParseUint(h, 16, 64) return }
go
{ "resource": "" }
q37353
MarshalJSON
train
func (t TraceID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("%q", t.String())), nil }
go
{ "resource": "" }
q37354
UnmarshalJSON
train
func (t *TraceID) UnmarshalJSON(traceID []byte) error { if len(traceID) < 3 { return ErrValidTraceIDRequired } // A valid JSON string is encoded wrapped in double quotes. We need to trim // these before converting the hex payload. tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1])) if err != nil { ...
go
{ "resource": "" }
q37355
RoundTripper
train
func RoundTripper(rt http.RoundTripper) TransportOption { return func(t *transport) { if rt != nil { t.rt = rt } } }
go
{ "resource": "" }
q37356
TransportTags
train
func TransportTags(tags map[string]string) TransportOption { return func(t *transport) { t.defaultTags = tags } }
go
{ "resource": "" }
q37357
NewTransport
train
func NewTransport(tracer *zipkin.Tracer, options ...TransportOption) (http.RoundTripper, error) { if tracer == nil { return nil, ErrValidTracerRequired } t := &transport{ tracer: tracer, rt: http.DefaultTransport, httpTrace: false, errHandler: defaultErrHandler, } for _, option := range op...
go
{ "resource": "" }
q37358
RoundTrip
train
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { sp, _ := t.tracer.StartSpanFromContext( req.Context(), req.URL.Scheme+"/"+req.Method, zipkin.Kind(model.Client), ) for k, v := range t.defaultTags { sp.Tag(k, v) } if t.httpTrace { sptr := spanTrace{ Span: sp, } sptr....
go
{ "resource": "" }
q37359
ParseHeaders
train
func ParseHeaders( hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string, ) (*model.SpanContext, error) { var ( err error spanID uint64 requiredCount int sc = &model.SpanContext{} ) // correct values for an existing sampled header are "0" and "1". // For legacy su...
go
{ "resource": "" }
q37360
Serialize
train
func (JSONSerializer) Serialize(spans []*model.SpanModel) ([]byte, error) { return json.Marshal(spans) }
go
{ "resource": "" }
q37361
WithClient
train
func WithClient(client *http.Client) ClientOption { return func(c *Client) { if client == nil { client = &http.Client{} } c.Client = client } }
go
{ "resource": "" }
q37362
ClientTags
train
func ClientTags(tags map[string]string) ClientOption { return func(c *Client) { c.defaultTags = tags } }
go
{ "resource": "" }
q37363
NewClient
train
func NewClient(tracer *zipkin.Tracer, options ...ClientOption) (*Client, error) { if tracer == nil { return nil, ErrValidTracerRequired } c := &Client{tracer: tracer, Client: &http.Client{}} for _, option := range options { option(c) } c.transportOptions = append( c.transportOptions, // the following Cl...
go
{ "resource": "" }
q37364
DoWithAppSpan
train
func (c *Client) DoWithAppSpan(req *http.Request, name string) (res *http.Response, err error) { var parentContext model.SpanContext if span := zipkin.SpanFromContext(req.Context()); span != nil { parentContext = span.Context() } appSpan := c.tracer.StartSpan(name, zipkin.Parent(parentContext)) zipkin.TagHTTP...
go
{ "resource": "" }
q37365
MarshalJSON
train
func (a *Annotation) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Timestamp int64 `json:"timestamp"` Value string `json:"value"` }{ Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3, Value: a.Value, }) }
go
{ "resource": "" }
q37366
UnmarshalJSON
train
func (a *Annotation) UnmarshalJSON(b []byte) error { type Alias Annotation annotation := &struct { TimeStamp uint64 `json:"timestamp"` *Alias }{ Alias: (*Alias)(a), } if err := json.Unmarshal(b, &annotation); err != nil { return err } if annotation.TimeStamp < 1 { return ErrValidTimestampRequired } a...
go
{ "resource": "" }
q37367
ExtractHTTP
train
func ExtractHTTP(r *http.Request) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = r.Header.Get(TraceID) spanIDHeader = r.Header.Get(SpanID) parentSpanIDHeader = r.Header.Get(ParentSpanID) sampledHeader = r.Header.Get(Sampled) flagsHeader ...
go
{ "resource": "" }
q37368
InjectHTTP
train
func InjectHTTP(r *http.Request) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { r.Header.Set(Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // so ...
go
{ "resource": "" }
q37369
Unarchive
train
func (r *Rar) Unarchive(source, destination string) error { if !fileExists(destination) && r.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a s...
go
{ "resource": "" }
q37370
Extract
train
func (r *Rar) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory ...
go
{ "resource": "" }
q37371
Archive
train
func (txz *TarXz) Archive(sources []string, destination string) error { err := txz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } txz.wrapWriter() return txz.Tar.Archive(sources, destination) }
go
{ "resource": "" }
q37372
Archive
train
func (t *Tar) Archive(sources []string, destination string) error { err := t.CheckExt(destination) if t.writerWrapFn == nil && err != nil { return fmt.Errorf("checking extension: %v", err) } if !t.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file already exists: %s", destination) } // ma...
go
{ "resource": "" }
q37373
Unarchive
train
func (t *Tar) Unarchive(source, destination string) error { if !fileExists(destination) && t.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a s...
go
{ "resource": "" }
q37374
Create
train
func (t *Tar) Create(out io.Writer) error { if t.tw != nil { return fmt.Errorf("tar archive is already created for writing") } // wrapping writers allows us to output // compressed tarballs, for example if t.writerWrapFn != nil { var err error out, err = t.writerWrapFn(out) if err != nil { return fmt.E...
go
{ "resource": "" }
q37375
Write
train
func (t *Tar) Write(f File) error { if t.tw == nil { return fmt.Errorf("tar archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } var linkTarget string if isSymlink(f) { var err erro...
go
{ "resource": "" }
q37376
hasTarHeader
train
func hasTarHeader(buf []byte) bool { if len(buf) < tarBlockSize { return false } b := buf[148:156] b = bytes.Trim(b, " \x00") // clean up all spaces and null bytes if len(b) == 0 { return false // unknown format } hdrSum, err := strconv.ParseUint(string(b), 8, 64) if err != nil { return false } // Acc...
go
{ "resource": "" }
q37377
Archive
train
func (tlz4 *TarLz4) Archive(sources []string, destination string) error { err := tlz4.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tlz4.wrapWriter() return tlz4.Tar.Archive(sources, destination) }
go
{ "resource": "" }
q37378
Create
train
func (tlz4 *TarLz4) Create(out io.Writer) error { tlz4.wrapWriter() return tlz4.Tar.Create(out) }
go
{ "resource": "" }
q37379
Archive
train
func (tsz *TarSz) Archive(sources []string, destination string) error { err := tsz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tsz.wrapWriter() return tsz.Tar.Archive(sources, destination) }
go
{ "resource": "" }
q37380
Create
train
func (tsz *TarSz) Create(out io.Writer) error { tsz.wrapWriter() return tsz.Tar.Create(out) }
go
{ "resource": "" }
q37381
Archive
train
func (tgz *TarGz) Archive(sources []string, destination string) error { err := tgz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tgz.wrapWriter() return tgz.Tar.Archive(sources, destination) }
go
{ "resource": "" }
q37382
Archive
train
func (tbz2 *TarBz2) Archive(sources []string, destination string) error { err := tbz2.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tbz2.wrapWriter() return tbz2.Tar.Archive(sources, destination) }
go
{ "resource": "" }
q37383
Create
train
func (tbz2 *TarBz2) Create(out io.Writer) error { tbz2.wrapWriter() return tbz2.Tar.Create(out) }
go
{ "resource": "" }
q37384
Unarchive
train
func (z *Zip) Unarchive(source, destination string) error { if !fileExists(destination) && z.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source file: %v", err) ...
go
{ "resource": "" }
q37385
Create
train
func (z *Zip) Create(out io.Writer) error { if z.zw != nil { return fmt.Errorf("zip archive is already created for writing") } z.zw = zip.NewWriter(out) if z.CompressionLevel != flate.DefaultCompression { z.zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWrite...
go
{ "resource": "" }
q37386
Write
train
func (z *Zip) Write(f File) error { if z.zw == nil { return fmt.Errorf("zip archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } header, err := zip.FileInfoHeader(f) if err != nil { ...
go
{ "resource": "" }
q37387
Open
train
func (z *Zip) Open(in io.Reader, size int64) error { inRdrAt, ok := in.(io.ReaderAt) if !ok { return fmt.Errorf("reader must be io.ReaderAt") } if z.zr != nil { return fmt.Errorf("zip archive is already open for reading") } var err error z.zr, err = zip.NewReader(inRdrAt, size) if err != nil { return fmt....
go
{ "resource": "" }
q37388
Read
train
func (z *Zip) Read() (File, error) { if z.zr == nil { return File{}, fmt.Errorf("zip archive is not open") } if z.ridx >= len(z.zr.File) { return File{}, io.EOF } // access the file and increment counter so that // if there is an error processing this file, the // caller can still iterate to the next file ...
go
{ "resource": "" }
q37389
Extract
train
func (z *Zip) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory ...
go
{ "resource": "" }
q37390
NewZip
train
func NewZip() *Zip { return &Zip{ CompressionLevel: flate.DefaultCompression, MkdirAll: true, SelectiveCompression: true, } }
go
{ "resource": "" }
q37391
Archive
train
func Archive(sources []string, destination string) error { aIface, err := ByExtension(destination) if err != nil { return err } a, ok := aIface.(Archiver) if !ok { return fmt.Errorf("format specified by destination filename is not an archive format: %s (%T)", destination, aIface) } return a.Archive(sources, ...
go
{ "resource": "" }
q37392
Unarchive
train
func Unarchive(source, destination string) error { uaIface, err := ByExtension(source) if err != nil { return err } u, ok := uaIface.(Unarchiver) if !ok { return fmt.Errorf("format specified by source filename is not an archive format: %s (%T)", source, uaIface) } return u.Unarchive(source, destination) }
go
{ "resource": "" }
q37393
Walk
train
func Walk(archive string, walkFn WalkFunc) error { wIface, err := ByExtension(archive) if err != nil { return err } w, ok := wIface.(Walker) if !ok { return fmt.Errorf("format specified by archive filename is not a walker format: %s (%T)", archive, wIface) } return w.Walk(archive, walkFn) }
go
{ "resource": "" }
q37394
Extract
train
func Extract(source, target, destination string) error { eIface, err := ByExtension(source) if err != nil { return err } e, ok := eIface.(Extractor) if !ok { return fmt.Errorf("format specified by source filename is not an extractor format: %s (%T)", source, eIface) } return e.Extract(source, target, destina...
go
{ "resource": "" }
q37395
CompressFile
train
func CompressFile(source, destination string) error { cIface, err := ByExtension(destination) if err != nil { return err } c, ok := cIface.(Compressor) if !ok { return fmt.Errorf("format specified by destination filename is not a recognized compression algorithm: %s", destination) } return FileCompressor{Com...
go
{ "resource": "" }
q37396
DecompressFile
train
func DecompressFile(source, destination string) error { cIface, err := ByExtension(source) if err != nil { return err } c, ok := cIface.(Decompressor) if !ok { return fmt.Errorf("format specified by source filename is not a recognized compression algorithm: %s", source) } return FileCompressor{Decompressor: ...
go
{ "resource": "" }
q37397
within
train
func within(parent, sub string) bool { rel, err := filepath.Rel(parent, sub) if err != nil { return false } return !strings.Contains(rel, "..") }
go
{ "resource": "" }
q37398
multipleTopLevels
train
func multipleTopLevels(paths []string) bool { if len(paths) < 2 { return false } var lastTop string for _, p := range paths { p = strings.TrimPrefix(strings.Replace(p, `\`, "/", -1), "/") for { next := path.Dir(p) if next == "." { break } p = next } if lastTop == "" { lastTop = p } ...
go
{ "resource": "" }
q37399
folderNameFromFileName
train
func folderNameFromFileName(filename string) string { base := filepath.Base(filename) firstDot := strings.Index(base, ".") if firstDot > -1 { return base[:firstDot] } return base }
go
{ "resource": "" }