repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
tealeg/xlsx
stream_file_builder.go
NewStreamFileBuilder
func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder { return &StreamFileBuilder{ zipWriter: zip.NewWriter(writer), xlsxFile: NewFile(), cellTypeToStyleIds: make(map[CellType]int), maxStyleId: initMaxStyleId, } }
go
func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder { return &StreamFileBuilder{ zipWriter: zip.NewWriter(writer), xlsxFile: NewFile(), cellTypeToStyleIds: make(map[CellType]int), maxStyleId: initMaxStyleId, } }
[ "func", "NewStreamFileBuilder", "(", "writer", "io", ".", "Writer", ")", "*", "StreamFileBuilder", "{", "return", "&", "StreamFileBuilder", "{", "zipWriter", ":", "zip", ".", "NewWriter", "(", "writer", ")", ",", "xlsxFile", ":", "NewFile", "(", ")", ",", "cellTypeToStyleIds", ":", "make", "(", "map", "[", "CellType", "]", "int", ")", ",", "maxStyleId", ":", "initMaxStyleId", ",", "}", "\n", "}" ]
// NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer
[ "NewStreamFileBuilder", "creates", "an", "StreamFileBuilder", "that", "will", "write", "to", "the", "the", "provided", "io", ".", "writer" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L58-L65
train
tealeg/xlsx
stream_file_builder.go
NewStreamFileBuilderForPath
func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error) { file, err := os.Create(path) if err != nil { return nil, err } return NewStreamFileBuilder(file), nil }
go
func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error) { file, err := os.Create(path) if err != nil { return nil, err } return NewStreamFileBuilder(file), nil }
[ "func", "NewStreamFileBuilderForPath", "(", "path", "string", ")", "(", "*", "StreamFileBuilder", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewStreamFileBuilder", "(", "file", ")", ",", "nil", "\n", "}" ]
// NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it. // The file will be created if it does not exist, or truncated if it does.
[ "NewStreamFileBuilderForPath", "takes", "the", "name", "of", "an", "XLSX", "file", "and", "returns", "a", "builder", "for", "it", ".", "The", "file", "will", "be", "created", "if", "it", "does", "not", "exist", "or", "truncated", "if", "it", "does", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L69-L75
train
tealeg/xlsx
stream_file_builder.go
AddSheet
func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error { if sb.built { return BuiltStreamFileBuilderError } if len(cellTypes) > len(headers) { return errors.New("cellTypes is longer than headers") } sheet, err := sb.xlsxFile.AddSheet(name) if err != nil { // Set built on error so that all subsequent calls to the builder will also fail. sb.built = true return err } sb.styleIds = append(sb.styleIds, []int{}) row := sheet.AddRow() if count := row.WriteSlice(&headers, -1); count != len(headers) { // Set built on error so that all subsequent calls to the builder will also fail. sb.built = true return errors.New("failed to write headers") } for i, cellType := range cellTypes { var cellStyleIndex int var ok bool if cellType != nil { // The cell type is one of the attributes of a Style. // Since it is the only attribute of Style that we use, we can assume that cell types // map one to one with Styles and their Style ID. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is // used, the pre-existing style will also be used. cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType] if !ok { sb.maxStyleId++ cellStyleIndex = sb.maxStyleId sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId } sheet.Cols[i].SetType(*cellType) } sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex) } return nil }
go
func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error { if sb.built { return BuiltStreamFileBuilderError } if len(cellTypes) > len(headers) { return errors.New("cellTypes is longer than headers") } sheet, err := sb.xlsxFile.AddSheet(name) if err != nil { // Set built on error so that all subsequent calls to the builder will also fail. sb.built = true return err } sb.styleIds = append(sb.styleIds, []int{}) row := sheet.AddRow() if count := row.WriteSlice(&headers, -1); count != len(headers) { // Set built on error so that all subsequent calls to the builder will also fail. sb.built = true return errors.New("failed to write headers") } for i, cellType := range cellTypes { var cellStyleIndex int var ok bool if cellType != nil { // The cell type is one of the attributes of a Style. // Since it is the only attribute of Style that we use, we can assume that cell types // map one to one with Styles and their Style ID. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is // used, the pre-existing style will also be used. cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType] if !ok { sb.maxStyleId++ cellStyleIndex = sb.maxStyleId sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId } sheet.Cols[i].SetType(*cellType) } sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex) } return nil }
[ "func", "(", "sb", "*", "StreamFileBuilder", ")", "AddSheet", "(", "name", "string", ",", "headers", "[", "]", "string", ",", "cellTypes", "[", "]", "*", "CellType", ")", "error", "{", "if", "sb", ".", "built", "{", "return", "BuiltStreamFileBuilderError", "\n", "}", "\n", "if", "len", "(", "cellTypes", ")", ">", "len", "(", "headers", ")", "{", "return", "errors", ".", "New", "(", "\"cellTypes is longer than headers\"", ")", "\n", "}", "\n", "sheet", ",", "err", ":=", "sb", ".", "xlsxFile", ".", "AddSheet", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "sb", ".", "built", "=", "true", "\n", "return", "err", "\n", "}", "\n", "sb", ".", "styleIds", "=", "append", "(", "sb", ".", "styleIds", ",", "[", "]", "int", "{", "}", ")", "\n", "row", ":=", "sheet", ".", "AddRow", "(", ")", "\n", "if", "count", ":=", "row", ".", "WriteSlice", "(", "&", "headers", ",", "-", "1", ")", ";", "count", "!=", "len", "(", "headers", ")", "{", "sb", ".", "built", "=", "true", "\n", "return", "errors", ".", "New", "(", "\"failed to write headers\"", ")", "\n", "}", "\n", "for", "i", ",", "cellType", ":=", "range", "cellTypes", "{", "var", "cellStyleIndex", "int", "\n", "var", "ok", "bool", "\n", "if", "cellType", "!=", "nil", "{", "cellStyleIndex", ",", "ok", "=", "sb", ".", "cellTypeToStyleIds", "[", "*", "cellType", "]", "\n", "if", "!", "ok", "{", "sb", ".", "maxStyleId", "++", "\n", "cellStyleIndex", "=", "sb", ".", "maxStyleId", "\n", "sb", ".", "cellTypeToStyleIds", "[", "*", "cellType", "]", "=", "sb", ".", "maxStyleId", "\n", "}", "\n", "sheet", ".", "Cols", "[", "i", "]", ".", "SetType", "(", "*", "cellType", ")", "\n", "}", "\n", "sb", ".", "styleIds", "[", "len", "(", "sb", ".", "styleIds", ")", "-", "1", "]", "=", "append", "(", "sb", ".", "styleIds", "[", "len", "(", "sb", ".", "styleIds", ")", "-", "1", "]", ",", "cellStyleIndex", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an // error will be thrown.
[ "AddSheet", "will", "add", "sheets", "with", "the", "given", "name", "with", "the", "provided", "headers", ".", "The", "headers", "cannot", "be", "edited", "later", "and", "all", "rows", "written", "to", "the", "sheet", "must", "contain", "the", "same", "number", "of", "cells", "as", "the", "header", ".", "Sheet", "names", "must", "be", "unique", "or", "an", "error", "will", "be", "thrown", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L80-L120
train
tealeg/xlsx
stream_file_builder.go
AddValidation
func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation) { sheet := sb.xlsxFile.Sheets[sheetIndex] column := sheet.Col(colIndex) column.SetDataValidationWithStart(validation, rowStartIndex) }
go
func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation) { sheet := sb.xlsxFile.Sheets[sheetIndex] column := sheet.Col(colIndex) column.SetDataValidationWithStart(validation, rowStartIndex) }
[ "func", "(", "sb", "*", "StreamFileBuilder", ")", "AddValidation", "(", "sheetIndex", ",", "colIndex", ",", "rowStartIndex", "int", ",", "validation", "*", "xlsxCellDataValidation", ")", "{", "sheet", ":=", "sb", ".", "xlsxFile", ".", "Sheets", "[", "sheetIndex", "]", "\n", "column", ":=", "sheet", ".", "Col", "(", "colIndex", ")", "\n", "column", ".", "SetDataValidationWithStart", "(", "validation", ",", "rowStartIndex", ")", "\n", "}" ]
// AddValidation will add a validation to a specific column.
[ "AddValidation", "will", "add", "a", "validation", "to", "a", "specific", "column", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L123-L127
train
tealeg/xlsx
stream_file_builder.go
Build
func (sb *StreamFileBuilder) Build() (*StreamFile, error) { if sb.built { return nil, BuiltStreamFileBuilderError } sb.built = true parts, err := sb.xlsxFile.MarshallParts() if err != nil { return nil, err } es := &StreamFile{ zipWriter: sb.zipWriter, xlsxFile: sb.xlsxFile, sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)), sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)), styleIds: sb.styleIds, } for path, data := range parts { // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this // point the sheets are still empty. The sheet files will be written later as their rows come in. if strings.HasPrefix(path, sheetFilePathPrefix) { if err := sb.processEmptySheetXML(es, path, data); err != nil { return nil, err } continue } metadataFile, err := sb.zipWriter.Create(path) if err != nil { return nil, err } _, err = metadataFile.Write([]byte(data)) if err != nil { return nil, err } } if err := es.NextSheet(); err != nil { return nil, err } return es, nil }
go
func (sb *StreamFileBuilder) Build() (*StreamFile, error) { if sb.built { return nil, BuiltStreamFileBuilderError } sb.built = true parts, err := sb.xlsxFile.MarshallParts() if err != nil { return nil, err } es := &StreamFile{ zipWriter: sb.zipWriter, xlsxFile: sb.xlsxFile, sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)), sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)), styleIds: sb.styleIds, } for path, data := range parts { // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this // point the sheets are still empty. The sheet files will be written later as their rows come in. if strings.HasPrefix(path, sheetFilePathPrefix) { if err := sb.processEmptySheetXML(es, path, data); err != nil { return nil, err } continue } metadataFile, err := sb.zipWriter.Create(path) if err != nil { return nil, err } _, err = metadataFile.Write([]byte(data)) if err != nil { return nil, err } } if err := es.NextSheet(); err != nil { return nil, err } return es, nil }
[ "func", "(", "sb", "*", "StreamFileBuilder", ")", "Build", "(", ")", "(", "*", "StreamFile", ",", "error", ")", "{", "if", "sb", ".", "built", "{", "return", "nil", ",", "BuiltStreamFileBuilderError", "\n", "}", "\n", "sb", ".", "built", "=", "true", "\n", "parts", ",", "err", ":=", "sb", ".", "xlsxFile", ".", "MarshallParts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "es", ":=", "&", "StreamFile", "{", "zipWriter", ":", "sb", ".", "zipWriter", ",", "xlsxFile", ":", "sb", ".", "xlsxFile", ",", "sheetXmlPrefix", ":", "make", "(", "[", "]", "string", ",", "len", "(", "sb", ".", "xlsxFile", ".", "Sheets", ")", ")", ",", "sheetXmlSuffix", ":", "make", "(", "[", "]", "string", ",", "len", "(", "sb", ".", "xlsxFile", ".", "Sheets", ")", ")", ",", "styleIds", ":", "sb", ".", "styleIds", ",", "}", "\n", "for", "path", ",", "data", ":=", "range", "parts", "{", "if", "strings", ".", "HasPrefix", "(", "path", ",", "sheetFilePathPrefix", ")", "{", "if", "err", ":=", "sb", ".", "processEmptySheetXML", "(", "es", ",", "path", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "continue", "\n", "}", "\n", "metadataFile", ",", "err", ":=", "sb", ".", "zipWriter", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "metadataFile", ".", "Write", "(", "[", "]", "byte", "(", "data", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "es", ".", "NextSheet", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "es", ",", "nil", "\n", "}" ]
// Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct // that can be used to write the rows to the sheets.
[ "Build", "begins", "streaming", "the", "XLSX", "file", "to", "the", "io", "by", "writing", "all", "the", "XLSX", "metadata", ".", "It", "creates", "a", "StreamFile", "struct", "that", "can", "be", "used", "to", "write", "the", "rows", "to", "the", "sheets", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L131-L170
train
tealeg/xlsx
stream_file_builder.go
processEmptySheetXML
func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error { // Get the sheet index from the path sheetIndex, err := getSheetIndex(sf, path) if err != nil { return err } // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex]) if err != nil { return err } // Split the sheet at the end of its SheetData tag so that more rows can be added inside. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data) if err != nil { return err } sf.sheetXmlPrefix[sheetIndex] = prefix sf.sheetXmlSuffix[sheetIndex] = suffix return nil }
go
func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error { // Get the sheet index from the path sheetIndex, err := getSheetIndex(sf, path) if err != nil { return err } // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex]) if err != nil { return err } // Split the sheet at the end of its SheetData tag so that more rows can be added inside. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data) if err != nil { return err } sf.sheetXmlPrefix[sheetIndex] = prefix sf.sheetXmlSuffix[sheetIndex] = suffix return nil }
[ "func", "(", "sb", "*", "StreamFileBuilder", ")", "processEmptySheetXML", "(", "sf", "*", "StreamFile", ",", "path", ",", "data", "string", ")", "error", "{", "sheetIndex", ",", "err", ":=", "getSheetIndex", "(", "sf", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "data", ",", "err", "=", "removeDimensionTag", "(", "data", ",", "sf", ".", "xlsxFile", ".", "Sheets", "[", "sheetIndex", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "prefix", ",", "suffix", ",", "err", ":=", "splitSheetIntoPrefixAndSuffix", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sf", ".", "sheetXmlPrefix", "[", "sheetIndex", "]", "=", "prefix", "\n", "sf", ".", "sheetXmlSuffix", "[", "sheetIndex", "]", "=", "suffix", "\n", "return", "nil", "\n", "}" ]
// processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the // XML file so that these can be written at the right time.
[ "processEmptySheetXML", "will", "take", "in", "the", "path", "and", "XML", "data", "of", "an", "empty", "sheet", "and", "will", "save", "the", "beginning", "and", "end", "of", "the", "XML", "file", "so", "that", "these", "can", "be", "written", "at", "the", "right", "time", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L174-L196
train
tealeg/xlsx
stream_file_builder.go
removeDimensionTag
func removeDimensionTag(data string, sheet *Sheet) (string, error) { x := len(sheet.Cols) - 1 y := len(sheet.Rows) - 1 if x < 0 { x = 0 } if y < 0 { y = 0 } var dimensionRef string if x == 0 && y == 0 { dimensionRef = "A1" } else { endCoordinate := GetCellIDStringFromCoords(x, y) dimensionRef = "A1:" + endCoordinate } dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef)) if len(dataParts) != 2 { return "", errors.New("unexpected Sheet XML: dimension tag not found") } return dataParts[0] + dataParts[1], nil }
go
func removeDimensionTag(data string, sheet *Sheet) (string, error) { x := len(sheet.Cols) - 1 y := len(sheet.Rows) - 1 if x < 0 { x = 0 } if y < 0 { y = 0 } var dimensionRef string if x == 0 && y == 0 { dimensionRef = "A1" } else { endCoordinate := GetCellIDStringFromCoords(x, y) dimensionRef = "A1:" + endCoordinate } dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef)) if len(dataParts) != 2 { return "", errors.New("unexpected Sheet XML: dimension tag not found") } return dataParts[0] + dataParts[1], nil }
[ "func", "removeDimensionTag", "(", "data", "string", ",", "sheet", "*", "Sheet", ")", "(", "string", ",", "error", ")", "{", "x", ":=", "len", "(", "sheet", ".", "Cols", ")", "-", "1", "\n", "y", ":=", "len", "(", "sheet", ".", "Rows", ")", "-", "1", "\n", "if", "x", "<", "0", "{", "x", "=", "0", "\n", "}", "\n", "if", "y", "<", "0", "{", "y", "=", "0", "\n", "}", "\n", "var", "dimensionRef", "string", "\n", "if", "x", "==", "0", "&&", "y", "==", "0", "{", "dimensionRef", "=", "\"A1\"", "\n", "}", "else", "{", "endCoordinate", ":=", "GetCellIDStringFromCoords", "(", "x", ",", "y", ")", "\n", "dimensionRef", "=", "\"A1:\"", "+", "endCoordinate", "\n", "}", "\n", "dataParts", ":=", "strings", ".", "Split", "(", "data", ",", "fmt", ".", "Sprintf", "(", "dimensionTag", ",", "dimensionRef", ")", ")", "\n", "if", "len", "(", "dataParts", ")", "!=", "2", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"unexpected Sheet XML: dimension tag not found\"", ")", "\n", "}", "\n", "return", "dataParts", "[", "0", "]", "+", "dataParts", "[", "1", "]", ",", "nil", "\n", "}" ]
// removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed. // data is the XML data for the sheet // sheet is the Sheet struct that the XML was created from. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet
[ "removeDimensionTag", "will", "return", "the", "passed", "in", "XLSX", "Spreadsheet", "XML", "with", "the", "dimension", "tag", "removed", ".", "data", "is", "the", "XML", "data", "for", "the", "sheet", "sheet", "is", "the", "Sheet", "struct", "that", "the", "XML", "was", "created", "from", ".", "Can", "return", "an", "error", "if", "the", "XML", "s", "dimension", "tag", "does", "not", "match", "was", "is", "expected", "based", "on", "the", "provided", "Sheet" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L220-L241
train
tealeg/xlsx
stream_file_builder.go
splitSheetIntoPrefixAndSuffix
func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) { // Split the sheet at the end of its SheetData tag so that more rows can be added inside. sheetParts := strings.Split(data, endSheetDataTag) if len(sheetParts) != 2 { return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found") } return sheetParts[0], sheetParts[1], nil }
go
func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) { // Split the sheet at the end of its SheetData tag so that more rows can be added inside. sheetParts := strings.Split(data, endSheetDataTag) if len(sheetParts) != 2 { return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found") } return sheetParts[0], sheetParts[1], nil }
[ "func", "splitSheetIntoPrefixAndSuffix", "(", "data", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "sheetParts", ":=", "strings", ".", "Split", "(", "data", ",", "endSheetDataTag", ")", "\n", "if", "len", "(", "sheetParts", ")", "!=", "2", "{", "return", "\"\"", ",", "\"\"", ",", "errors", ".", "New", "(", "\"unexpected Sheet XML: SheetData close tag not found\"", ")", "\n", "}", "\n", "return", "sheetParts", "[", "0", "]", ",", "sheetParts", "[", "1", "]", ",", "nil", "\n", "}" ]
// splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that // more spreadsheet rows can be inserted in between.
[ "splitSheetIntoPrefixAndSuffix", "will", "split", "the", "provided", "XML", "sheet", "into", "a", "prefix", "and", "a", "suffix", "so", "that", "more", "spreadsheet", "rows", "can", "be", "inserted", "in", "between", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L245-L252
train
tealeg/xlsx
stream_file.go
Write
func (sf *StreamFile) Write(cells []string) error { if sf.err != nil { return sf.err } err := sf.write(cells) if err != nil { sf.err = err return err } return sf.zipWriter.Flush() }
go
func (sf *StreamFile) Write(cells []string) error { if sf.err != nil { return sf.err } err := sf.write(cells) if err != nil { sf.err = err return err } return sf.zipWriter.Flush() }
[ "func", "(", "sf", "*", "StreamFile", ")", "Write", "(", "cells", "[", "]", "string", ")", "error", "{", "if", "sf", ".", "err", "!=", "nil", "{", "return", "sf", ".", "err", "\n", "}", "\n", "err", ":=", "sf", ".", "write", "(", "cells", ")", "\n", "if", "err", "!=", "nil", "{", "sf", ".", "err", "=", "err", "\n", "return", "err", "\n", "}", "\n", "return", "sf", ".", "zipWriter", ".", "Flush", "(", ")", "\n", "}" ]
// Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the // same number of cells as the header provided when the sheet was created or an error will be returned. This function // will always trigger a flush on success. Currently the only supported data type is string data.
[ "Write", "will", "write", "a", "row", "of", "cells", "to", "the", "current", "sheet", ".", "Every", "call", "to", "Write", "on", "the", "same", "sheet", "must", "contain", "the", "same", "number", "of", "cells", "as", "the", "header", "provided", "when", "the", "sheet", "was", "created", "or", "an", "error", "will", "be", "returned", ".", "This", "function", "will", "always", "trigger", "a", "flush", "on", "success", ".", "Currently", "the", "only", "supported", "data", "type", "is", "string", "data", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L42-L52
train
tealeg/xlsx
stream_file.go
NextSheet
func (sf *StreamFile) NextSheet() error { if sf.err != nil { return sf.err } var sheetIndex int if sf.currentSheet != nil { if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) { sf.err = AlreadyOnLastSheetError return AlreadyOnLastSheetError } if err := sf.writeSheetEnd(); err != nil { sf.currentSheet = nil sf.err = err return err } sheetIndex = sf.currentSheet.index } sheetIndex++ sf.currentSheet = &streamSheet{ index: sheetIndex, columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols), styleIds: sf.styleIds[sheetIndex-1], rowCount: 1, } sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix fileWriter, err := sf.zipWriter.Create(sheetPath) if err != nil { sf.err = err return err } sf.currentSheet.writer = fileWriter if err := sf.writeSheetStart(); err != nil { sf.err = err return err } return nil }
go
func (sf *StreamFile) NextSheet() error { if sf.err != nil { return sf.err } var sheetIndex int if sf.currentSheet != nil { if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) { sf.err = AlreadyOnLastSheetError return AlreadyOnLastSheetError } if err := sf.writeSheetEnd(); err != nil { sf.currentSheet = nil sf.err = err return err } sheetIndex = sf.currentSheet.index } sheetIndex++ sf.currentSheet = &streamSheet{ index: sheetIndex, columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols), styleIds: sf.styleIds[sheetIndex-1], rowCount: 1, } sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix fileWriter, err := sf.zipWriter.Create(sheetPath) if err != nil { sf.err = err return err } sf.currentSheet.writer = fileWriter if err := sf.writeSheetStart(); err != nil { sf.err = err return err } return nil }
[ "func", "(", "sf", "*", "StreamFile", ")", "NextSheet", "(", ")", "error", "{", "if", "sf", ".", "err", "!=", "nil", "{", "return", "sf", ".", "err", "\n", "}", "\n", "var", "sheetIndex", "int", "\n", "if", "sf", ".", "currentSheet", "!=", "nil", "{", "if", "sf", ".", "currentSheet", ".", "index", ">=", "len", "(", "sf", ".", "xlsxFile", ".", "Sheets", ")", "{", "sf", ".", "err", "=", "AlreadyOnLastSheetError", "\n", "return", "AlreadyOnLastSheetError", "\n", "}", "\n", "if", "err", ":=", "sf", ".", "writeSheetEnd", "(", ")", ";", "err", "!=", "nil", "{", "sf", ".", "currentSheet", "=", "nil", "\n", "sf", ".", "err", "=", "err", "\n", "return", "err", "\n", "}", "\n", "sheetIndex", "=", "sf", ".", "currentSheet", ".", "index", "\n", "}", "\n", "sheetIndex", "++", "\n", "sf", ".", "currentSheet", "=", "&", "streamSheet", "{", "index", ":", "sheetIndex", ",", "columnCount", ":", "len", "(", "sf", ".", "xlsxFile", ".", "Sheets", "[", "sheetIndex", "-", "1", "]", ".", "Cols", ")", ",", "styleIds", ":", "sf", ".", "styleIds", "[", "sheetIndex", "-", "1", "]", ",", "rowCount", ":", "1", ",", "}", "\n", "sheetPath", ":=", "sheetFilePathPrefix", "+", "strconv", ".", "Itoa", "(", "sf", ".", "currentSheet", ".", "index", ")", "+", "sheetFilePathSuffix", "\n", "fileWriter", ",", "err", ":=", "sf", ".", "zipWriter", ".", "Create", "(", "sheetPath", ")", "\n", "if", "err", "!=", "nil", "{", "sf", ".", "err", "=", "err", "\n", "return", "err", "\n", "}", "\n", "sf", ".", "currentSheet", ".", "writer", "=", "fileWriter", "\n", "if", "err", ":=", "sf", ".", "writeSheetStart", "(", ")", ";", "err", "!=", "nil", "{", "sf", ".", "err", "=", "err", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// NextSheet will switch to the next sheet. Sheets are selected in the same order they were added. // Once you leave a sheet, you cannot return to it.
[ "NextSheet", "will", "switch", "to", "the", "next", "sheet", ".", "Sheets", "are", "selected", "in", "the", "same", "order", "they", "were", "added", ".", "Once", "you", "leave", "a", "sheet", "you", "cannot", "return", "to", "it", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L128-L165
train
tealeg/xlsx
stream_file.go
Close
func (sf *StreamFile) Close() error { if sf.err != nil { return sf.err } // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them. // XLSX readers may error if the sheets registered in the metadata are not present in the file. if sf.currentSheet != nil { for sf.currentSheet.index < len(sf.xlsxFile.Sheets) { if err := sf.NextSheet(); err != nil { sf.err = err return err } } // Write the end of the last sheet. if err := sf.writeSheetEnd(); err != nil { sf.err = err return err } } err := sf.zipWriter.Close() if err != nil { sf.err = err } return err }
go
func (sf *StreamFile) Close() error { if sf.err != nil { return sf.err } // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them. // XLSX readers may error if the sheets registered in the metadata are not present in the file. if sf.currentSheet != nil { for sf.currentSheet.index < len(sf.xlsxFile.Sheets) { if err := sf.NextSheet(); err != nil { sf.err = err return err } } // Write the end of the last sheet. if err := sf.writeSheetEnd(); err != nil { sf.err = err return err } } err := sf.zipWriter.Close() if err != nil { sf.err = err } return err }
[ "func", "(", "sf", "*", "StreamFile", ")", "Close", "(", ")", "error", "{", "if", "sf", ".", "err", "!=", "nil", "{", "return", "sf", ".", "err", "\n", "}", "\n", "if", "sf", ".", "currentSheet", "!=", "nil", "{", "for", "sf", ".", "currentSheet", ".", "index", "<", "len", "(", "sf", ".", "xlsxFile", ".", "Sheets", ")", "{", "if", "err", ":=", "sf", ".", "NextSheet", "(", ")", ";", "err", "!=", "nil", "{", "sf", ".", "err", "=", "err", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "sf", ".", "writeSheetEnd", "(", ")", ";", "err", "!=", "nil", "{", "sf", ".", "err", "=", "err", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "err", ":=", "sf", ".", "zipWriter", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "sf", ".", "err", "=", "err", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Close closes the Stream File. // Any sheets that have not yet been written to will have an empty sheet created for them.
[ "Close", "closes", "the", "Stream", "File", ".", "Any", "sheets", "that", "have", "not", "yet", "been", "written", "to", "will", "have", "an", "empty", "sheet", "created", "for", "them", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L169-L193
train
tealeg/xlsx
stream_file.go
writeSheetStart
func (sf *StreamFile) writeSheetStart() error { if sf.currentSheet == nil { return NoCurrentSheetError } return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1]) }
go
func (sf *StreamFile) writeSheetStart() error { if sf.currentSheet == nil { return NoCurrentSheetError } return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1]) }
[ "func", "(", "sf", "*", "StreamFile", ")", "writeSheetStart", "(", ")", "error", "{", "if", "sf", ".", "currentSheet", "==", "nil", "{", "return", "NoCurrentSheetError", "\n", "}", "\n", "return", "sf", ".", "currentSheet", ".", "write", "(", "sf", ".", "sheetXmlPrefix", "[", "sf", ".", "currentSheet", ".", "index", "-", "1", "]", ")", "\n", "}" ]
// writeSheetStart will write the start of the Sheet's XML
[ "writeSheetStart", "will", "write", "the", "start", "of", "the", "Sheet", "s", "XML" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L196-L201
train
tealeg/xlsx
stream_file.go
writeSheetEnd
func (sf *StreamFile) writeSheetEnd() error { if sf.currentSheet == nil { return NoCurrentSheetError } if err := sf.currentSheet.write(endSheetDataTag); err != nil { return err } return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1]) }
go
func (sf *StreamFile) writeSheetEnd() error { if sf.currentSheet == nil { return NoCurrentSheetError } if err := sf.currentSheet.write(endSheetDataTag); err != nil { return err } return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1]) }
[ "func", "(", "sf", "*", "StreamFile", ")", "writeSheetEnd", "(", ")", "error", "{", "if", "sf", ".", "currentSheet", "==", "nil", "{", "return", "NoCurrentSheetError", "\n", "}", "\n", "if", "err", ":=", "sf", ".", "currentSheet", ".", "write", "(", "endSheetDataTag", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "sf", ".", "currentSheet", ".", "write", "(", "sf", ".", "sheetXmlSuffix", "[", "sf", ".", "currentSheet", ".", "index", "-", "1", "]", ")", "\n", "}" ]
// writeSheetEnd will write the end of the Sheet's XML
[ "writeSheetEnd", "will", "write", "the", "end", "of", "the", "Sheet", "s", "XML" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L204-L212
train
tealeg/xlsx
format_code.go
compareFormatString
func compareFormatString(fmt1, fmt2 string) bool { if fmt1 == fmt2 { return true } if fmt1 == "" || strings.EqualFold(fmt1, "general") { fmt1 = "general" } if fmt2 == "" || strings.EqualFold(fmt2, "general") { fmt2 = "general" } return fmt1 == fmt2 }
go
func compareFormatString(fmt1, fmt2 string) bool { if fmt1 == fmt2 { return true } if fmt1 == "" || strings.EqualFold(fmt1, "general") { fmt1 = "general" } if fmt2 == "" || strings.EqualFold(fmt2, "general") { fmt2 = "general" } return fmt1 == fmt2 }
[ "func", "compareFormatString", "(", "fmt1", ",", "fmt2", "string", ")", "bool", "{", "if", "fmt1", "==", "fmt2", "{", "return", "true", "\n", "}", "\n", "if", "fmt1", "==", "\"\"", "||", "strings", ".", "EqualFold", "(", "fmt1", ",", "\"general\"", ")", "{", "fmt1", "=", "\"general\"", "\n", "}", "\n", "if", "fmt2", "==", "\"\"", "||", "strings", ".", "EqualFold", "(", "fmt2", ",", "\"general\"", ")", "{", "fmt2", "=", "\"general\"", "\n", "}", "\n", "return", "fmt1", "==", "fmt2", "\n", "}" ]
// Format strings are a little strange to compare because empty string needs to be taken as general, and general needs // to be compared case insensitively.
[ "Format", "strings", "are", "a", "little", "strange", "to", "compare", "because", "empty", "string", "needs", "to", "be", "taken", "as", "general", "and", "general", "needs", "to", "be", "compared", "case", "insensitively", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L224-L235
train
tealeg/xlsx
format_code.go
splitFormatOnSemicolon
func splitFormatOnSemicolon(format string) ([]string, error) { var formats []string prevIndex := 0 for i := 0; i < len(format); i++ { if format[i] == ';' { formats = append(formats, format[prevIndex:i]) prevIndex = i + 1 } else if format[i] == '\\' { i++ } else if format[i] == '"' { endQuoteIndex := strings.Index(format[i+1:], "\"") if endQuoteIndex == -1 { // This is an invalid format string, fall back to general return nil, errors.New("invalid format string, unmatched double quote") } i += endQuoteIndex + 1 } } return append(formats, format[prevIndex:]), nil }
go
func splitFormatOnSemicolon(format string) ([]string, error) { var formats []string prevIndex := 0 for i := 0; i < len(format); i++ { if format[i] == ';' { formats = append(formats, format[prevIndex:i]) prevIndex = i + 1 } else if format[i] == '\\' { i++ } else if format[i] == '"' { endQuoteIndex := strings.Index(format[i+1:], "\"") if endQuoteIndex == -1 { // This is an invalid format string, fall back to general return nil, errors.New("invalid format string, unmatched double quote") } i += endQuoteIndex + 1 } } return append(formats, format[prevIndex:]), nil }
[ "func", "splitFormatOnSemicolon", "(", "format", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "formats", "[", "]", "string", "\n", "prevIndex", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "format", ")", ";", "i", "++", "{", "if", "format", "[", "i", "]", "==", "';'", "{", "formats", "=", "append", "(", "formats", ",", "format", "[", "prevIndex", ":", "i", "]", ")", "\n", "prevIndex", "=", "i", "+", "1", "\n", "}", "else", "if", "format", "[", "i", "]", "==", "'\\\\'", "{", "i", "++", "\n", "}", "else", "if", "format", "[", "i", "]", "==", "'\"'", "{", "endQuoteIndex", ":=", "strings", ".", "Index", "(", "format", "[", "i", "+", "1", ":", "]", ",", "\"\\\"\"", ")", "\n", "\\\"", "\n", "if", "endQuoteIndex", "==", "-", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"invalid format string, unmatched double quote\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "i", "+=", "endQuoteIndex", "+", "1", "\n", "}" ]
// splitFormatOnSemicolon will split the format string into the format sections // This logic to split the different formats on semicolon is fully correct, and will skip all literal semicolons, // and will catch all breaking semicolons.
[ "splitFormatOnSemicolon", "will", "split", "the", "format", "string", "into", "the", "format", "sections", "This", "logic", "to", "split", "the", "different", "formats", "on", "semicolon", "is", "fully", "correct", "and", "will", "skip", "all", "literal", "semicolons", "and", "will", "catch", "all", "breaking", "semicolons", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L315-L334
train
tealeg/xlsx
data_validation.go
SetError
func (dd *xlsxCellDataValidation) SetError(style DataValidationErrorStyle, title, msg *string) { dd.ShowErrorMessage = true dd.Error = msg dd.ErrorTitle = title strStyle := styleStop switch style { case StyleStop: strStyle = styleStop case StyleWarning: strStyle = styleWarning case StyleInformation: strStyle = styleInformation } dd.ErrorStyle = &strStyle }
go
func (dd *xlsxCellDataValidation) SetError(style DataValidationErrorStyle, title, msg *string) { dd.ShowErrorMessage = true dd.Error = msg dd.ErrorTitle = title strStyle := styleStop switch style { case StyleStop: strStyle = styleStop case StyleWarning: strStyle = styleWarning case StyleInformation: strStyle = styleInformation } dd.ErrorStyle = &strStyle }
[ "func", "(", "dd", "*", "xlsxCellDataValidation", ")", "SetError", "(", "style", "DataValidationErrorStyle", ",", "title", ",", "msg", "*", "string", ")", "{", "dd", ".", "ShowErrorMessage", "=", "true", "\n", "dd", ".", "Error", "=", "msg", "\n", "dd", ".", "ErrorTitle", "=", "title", "\n", "strStyle", ":=", "styleStop", "\n", "switch", "style", "{", "case", "StyleStop", ":", "strStyle", "=", "styleStop", "\n", "case", "StyleWarning", ":", "strStyle", "=", "styleWarning", "\n", "case", "StyleInformation", ":", "strStyle", "=", "styleInformation", "\n", "}", "\n", "dd", ".", "ErrorStyle", "=", "&", "strStyle", "\n", "}" ]
// SetError set error notice
[ "SetError", "set", "error", "notice" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/data_validation.go#L72-L87
train
tealeg/xlsx
data_validation.go
SetRange
func (dd *xlsxCellDataValidation) SetRange(f1, f2 int, t DataValidationType, o DataValidationOperator) error { formula1 := fmt.Sprintf("%d", f1) formula2 := fmt.Sprintf("%d", f2) switch o { case DataValidationOperatorBetween: if f1 > f2 { tmp := formula1 formula1 = formula2 formula2 = tmp } case DataValidationOperatorNotBetween: if f1 > f2 { tmp := formula1 formula1 = formula2 formula2 = tmp } } dd.Formula1 = formula1 dd.Formula2 = formula2 dd.Type = convDataValidationType(t) dd.Operator = convDataValidationOperatior(o) return nil }
go
func (dd *xlsxCellDataValidation) SetRange(f1, f2 int, t DataValidationType, o DataValidationOperator) error { formula1 := fmt.Sprintf("%d", f1) formula2 := fmt.Sprintf("%d", f2) switch o { case DataValidationOperatorBetween: if f1 > f2 { tmp := formula1 formula1 = formula2 formula2 = tmp } case DataValidationOperatorNotBetween: if f1 > f2 { tmp := formula1 formula1 = formula2 formula2 = tmp } } dd.Formula1 = formula1 dd.Formula2 = formula2 dd.Type = convDataValidationType(t) dd.Operator = convDataValidationOperatior(o) return nil }
[ "func", "(", "dd", "*", "xlsxCellDataValidation", ")", "SetRange", "(", "f1", ",", "f2", "int", ",", "t", "DataValidationType", ",", "o", "DataValidationOperator", ")", "error", "{", "formula1", ":=", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "f1", ")", "\n", "formula2", ":=", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "f2", ")", "\n", "switch", "o", "{", "case", "DataValidationOperatorBetween", ":", "if", "f1", ">", "f2", "{", "tmp", ":=", "formula1", "\n", "formula1", "=", "formula2", "\n", "formula2", "=", "tmp", "\n", "}", "\n", "case", "DataValidationOperatorNotBetween", ":", "if", "f1", ">", "f2", "{", "tmp", ":=", "formula1", "\n", "formula1", "=", "formula2", "\n", "formula2", "=", "tmp", "\n", "}", "\n", "}", "\n", "dd", ".", "Formula1", "=", "formula1", "\n", "dd", ".", "Formula2", "=", "formula2", "\n", "dd", ".", "Type", "=", "convDataValidationType", "(", "t", ")", "\n", "dd", ".", "Operator", "=", "convDataValidationOperatior", "(", "o", ")", "\n", "return", "nil", "\n", "}" ]
// SetDropList data validation range
[ "SetDropList", "data", "validation", "range" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/data_validation.go#L131-L155
train
tealeg/xlsx
style.go
NewStyle
func NewStyle() *Style { return &Style{ Alignment: *DefaultAlignment(), Border: *DefaultBorder(), Fill: *DefaultFill(), Font: *DefaultFont(), } }
go
func NewStyle() *Style { return &Style{ Alignment: *DefaultAlignment(), Border: *DefaultBorder(), Fill: *DefaultFill(), Font: *DefaultFont(), } }
[ "func", "NewStyle", "(", ")", "*", "Style", "{", "return", "&", "Style", "{", "Alignment", ":", "*", "DefaultAlignment", "(", ")", ",", "Border", ":", "*", "DefaultBorder", "(", ")", ",", "Fill", ":", "*", "DefaultFill", "(", ")", ",", "Font", ":", "*", "DefaultFont", "(", ")", ",", "}", "\n", "}" ]
// Return a new Style structure initialised with the default values.
[ "Return", "a", "new", "Style", "structure", "initialised", "with", "the", "default", "values", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/style.go#L20-L27
train
tealeg/xlsx
style.go
makeXLSXStyleElements
func (style *Style) makeXLSXStyleElements() (xFont xlsxFont, xFill xlsxFill, xBorder xlsxBorder, xCellXf xlsxXf) { xFont = xlsxFont{} xFill = xlsxFill{} xBorder = xlsxBorder{} xCellXf = xlsxXf{} xFont.Sz.Val = strconv.Itoa(style.Font.Size) xFont.Name.Val = style.Font.Name xFont.Family.Val = strconv.Itoa(style.Font.Family) xFont.Charset.Val = strconv.Itoa(style.Font.Charset) xFont.Color.RGB = style.Font.Color if style.Font.Bold { xFont.B = &xlsxVal{} } else { xFont.B = nil } if style.Font.Italic { xFont.I = &xlsxVal{} } else { xFont.I = nil } if style.Font.Underline { xFont.U = &xlsxVal{} } else { xFont.U = nil } xPatternFill := xlsxPatternFill{} xPatternFill.PatternType = style.Fill.PatternType xPatternFill.FgColor.RGB = style.Fill.FgColor xPatternFill.BgColor.RGB = style.Fill.BgColor xFill.PatternFill = xPatternFill xBorder.Left = xlsxLine{ Style: style.Border.Left, Color: xlsxColor{RGB: style.Border.LeftColor}, } xBorder.Right = xlsxLine{ Style: style.Border.Right, Color: xlsxColor{RGB: style.Border.RightColor}, } xBorder.Top = xlsxLine{ Style: style.Border.Top, Color: xlsxColor{RGB: style.Border.TopColor}, } xBorder.Bottom = xlsxLine{ Style: style.Border.Bottom, Color: xlsxColor{RGB: style.Border.BottomColor}, } xCellXf = makeXLSXCellElement() xCellXf.ApplyBorder = style.ApplyBorder xCellXf.ApplyFill = style.ApplyFill xCellXf.ApplyFont = style.ApplyFont xCellXf.ApplyAlignment = style.ApplyAlignment if style.NamedStyleIndex != nil { xCellXf.XfId = style.NamedStyleIndex } return }
go
func (style *Style) makeXLSXStyleElements() (xFont xlsxFont, xFill xlsxFill, xBorder xlsxBorder, xCellXf xlsxXf) { xFont = xlsxFont{} xFill = xlsxFill{} xBorder = xlsxBorder{} xCellXf = xlsxXf{} xFont.Sz.Val = strconv.Itoa(style.Font.Size) xFont.Name.Val = style.Font.Name xFont.Family.Val = strconv.Itoa(style.Font.Family) xFont.Charset.Val = strconv.Itoa(style.Font.Charset) xFont.Color.RGB = style.Font.Color if style.Font.Bold { xFont.B = &xlsxVal{} } else { xFont.B = nil } if style.Font.Italic { xFont.I = &xlsxVal{} } else { xFont.I = nil } if style.Font.Underline { xFont.U = &xlsxVal{} } else { xFont.U = nil } xPatternFill := xlsxPatternFill{} xPatternFill.PatternType = style.Fill.PatternType xPatternFill.FgColor.RGB = style.Fill.FgColor xPatternFill.BgColor.RGB = style.Fill.BgColor xFill.PatternFill = xPatternFill xBorder.Left = xlsxLine{ Style: style.Border.Left, Color: xlsxColor{RGB: style.Border.LeftColor}, } xBorder.Right = xlsxLine{ Style: style.Border.Right, Color: xlsxColor{RGB: style.Border.RightColor}, } xBorder.Top = xlsxLine{ Style: style.Border.Top, Color: xlsxColor{RGB: style.Border.TopColor}, } xBorder.Bottom = xlsxLine{ Style: style.Border.Bottom, Color: xlsxColor{RGB: style.Border.BottomColor}, } xCellXf = makeXLSXCellElement() xCellXf.ApplyBorder = style.ApplyBorder xCellXf.ApplyFill = style.ApplyFill xCellXf.ApplyFont = style.ApplyFont xCellXf.ApplyAlignment = style.ApplyAlignment if style.NamedStyleIndex != nil { xCellXf.XfId = style.NamedStyleIndex } return }
[ "func", "(", "style", "*", "Style", ")", "makeXLSXStyleElements", "(", ")", "(", "xFont", "xlsxFont", ",", "xFill", "xlsxFill", ",", "xBorder", "xlsxBorder", ",", "xCellXf", "xlsxXf", ")", "{", "xFont", "=", "xlsxFont", "{", "}", "\n", "xFill", "=", "xlsxFill", "{", "}", "\n", "xBorder", "=", "xlsxBorder", "{", "}", "\n", "xCellXf", "=", "xlsxXf", "{", "}", "\n", "xFont", ".", "Sz", ".", "Val", "=", "strconv", ".", "Itoa", "(", "style", ".", "Font", ".", "Size", ")", "\n", "xFont", ".", "Name", ".", "Val", "=", "style", ".", "Font", ".", "Name", "\n", "xFont", ".", "Family", ".", "Val", "=", "strconv", ".", "Itoa", "(", "style", ".", "Font", ".", "Family", ")", "\n", "xFont", ".", "Charset", ".", "Val", "=", "strconv", ".", "Itoa", "(", "style", ".", "Font", ".", "Charset", ")", "\n", "xFont", ".", "Color", ".", "RGB", "=", "style", ".", "Font", ".", "Color", "\n", "if", "style", ".", "Font", ".", "Bold", "{", "xFont", ".", "B", "=", "&", "xlsxVal", "{", "}", "\n", "}", "else", "{", "xFont", ".", "B", "=", "nil", "\n", "}", "\n", "if", "style", ".", "Font", ".", "Italic", "{", "xFont", ".", "I", "=", "&", "xlsxVal", "{", "}", "\n", "}", "else", "{", "xFont", ".", "I", "=", "nil", "\n", "}", "\n", "if", "style", ".", "Font", ".", "Underline", "{", "xFont", ".", "U", "=", "&", "xlsxVal", "{", "}", "\n", "}", "else", "{", "xFont", ".", "U", "=", "nil", "\n", "}", "\n", "xPatternFill", ":=", "xlsxPatternFill", "{", "}", "\n", "xPatternFill", ".", "PatternType", "=", "style", ".", "Fill", ".", "PatternType", "\n", "xPatternFill", ".", "FgColor", ".", "RGB", "=", "style", ".", "Fill", ".", "FgColor", "\n", "xPatternFill", ".", "BgColor", ".", "RGB", "=", "style", ".", "Fill", ".", "BgColor", "\n", "xFill", ".", "PatternFill", "=", "xPatternFill", "\n", "xBorder", ".", "Left", "=", "xlsxLine", "{", "Style", ":", "style", ".", "Border", ".", "Left", ",", "Color", ":", "xlsxColor", "{", "RGB", ":", "style", ".", "Border", ".", "LeftColor", "}", ",", "}", "\n", "xBorder", ".", "Right", "=", "xlsxLine", "{", "Style", ":", "style", ".", "Border", ".", "Right", ",", "Color", ":", "xlsxColor", "{", "RGB", ":", "style", ".", "Border", ".", "RightColor", "}", ",", "}", "\n", "xBorder", ".", "Top", "=", "xlsxLine", "{", "Style", ":", "style", ".", "Border", ".", "Top", ",", "Color", ":", "xlsxColor", "{", "RGB", ":", "style", ".", "Border", ".", "TopColor", "}", ",", "}", "\n", "xBorder", ".", "Bottom", "=", "xlsxLine", "{", "Style", ":", "style", ".", "Border", ".", "Bottom", ",", "Color", ":", "xlsxColor", "{", "RGB", ":", "style", ".", "Border", ".", "BottomColor", "}", ",", "}", "\n", "xCellXf", "=", "makeXLSXCellElement", "(", ")", "\n", "xCellXf", ".", "ApplyBorder", "=", "style", ".", "ApplyBorder", "\n", "xCellXf", ".", "ApplyFill", "=", "style", ".", "ApplyFill", "\n", "xCellXf", ".", "ApplyFont", "=", "style", ".", "ApplyFont", "\n", "xCellXf", ".", "ApplyAlignment", "=", "style", ".", "ApplyAlignment", "\n", "if", "style", ".", "NamedStyleIndex", "!=", "nil", "{", "xCellXf", ".", "XfId", "=", "style", ".", "NamedStyleIndex", "\n", "}", "\n", "return", "\n", "}" ]
// Generate the underlying XLSX style elements that correspond to the Style.
[ "Generate", "the", "underlying", "XLSX", "style", "elements", "that", "correspond", "to", "the", "Style", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/style.go#L30-L85
train
tealeg/xlsx
lib.go
ColIndexToLetters
func ColIndexToLetters(colRef int) string { parts := intToBase26(colRef) return formatColumnName(smooshBase26Slice(parts)) }
go
func ColIndexToLetters(colRef int) string { parts := intToBase26(colRef) return formatColumnName(smooshBase26Slice(parts)) }
[ "func", "ColIndexToLetters", "(", "colRef", "int", ")", "string", "{", "parts", ":=", "intToBase26", "(", "colRef", ")", "\n", "return", "formatColumnName", "(", "smooshBase26Slice", "(", "parts", ")", ")", "\n", "}" ]
// ColIndexToLetters is used to convert a zero based, numeric column // indentifier into a character code.
[ "ColIndexToLetters", "is", "used", "to", "convert", "a", "zero", "based", "numeric", "column", "indentifier", "into", "a", "character", "code", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L147-L150
train
tealeg/xlsx
lib.go
GetCellIDStringFromCoords
func GetCellIDStringFromCoords(x, y int) string { return GetCellIDStringFromCoordsWithFixed(x, y, false, false) }
go
func GetCellIDStringFromCoords(x, y int) string { return GetCellIDStringFromCoordsWithFixed(x, y, false, false) }
[ "func", "GetCellIDStringFromCoords", "(", "x", ",", "y", "int", ")", "string", "{", "return", "GetCellIDStringFromCoordsWithFixed", "(", "x", ",", "y", ",", "false", ",", "false", ")", "\n", "}" ]
// GetCellIDStringFromCoords returns the Excel format cell name that // represents a pair of zero based cartesian coordinates.
[ "GetCellIDStringFromCoords", "returns", "the", "Excel", "format", "cell", "name", "that", "represents", "a", "pair", "of", "zero", "based", "cartesian", "coordinates", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L195-L197
train
tealeg/xlsx
lib.go
GetCellIDStringFromCoordsWithFixed
func GetCellIDStringFromCoordsWithFixed(x, y int, xFixed, yFixed bool) string { xStr := ColIndexToLetters(x) if xFixed { xStr = fixedCellRefChar + xStr } yStr := RowIndexToString(y) if yFixed { yStr = fixedCellRefChar + yStr } return xStr + yStr }
go
func GetCellIDStringFromCoordsWithFixed(x, y int, xFixed, yFixed bool) string { xStr := ColIndexToLetters(x) if xFixed { xStr = fixedCellRefChar + xStr } yStr := RowIndexToString(y) if yFixed { yStr = fixedCellRefChar + yStr } return xStr + yStr }
[ "func", "GetCellIDStringFromCoordsWithFixed", "(", "x", ",", "y", "int", ",", "xFixed", ",", "yFixed", "bool", ")", "string", "{", "xStr", ":=", "ColIndexToLetters", "(", "x", ")", "\n", "if", "xFixed", "{", "xStr", "=", "fixedCellRefChar", "+", "xStr", "\n", "}", "\n", "yStr", ":=", "RowIndexToString", "(", "y", ")", "\n", "if", "yFixed", "{", "yStr", "=", "fixedCellRefChar", "+", "yStr", "\n", "}", "\n", "return", "xStr", "+", "yStr", "\n", "}" ]
// GetCellIDStringFromCoordsWithFixed returns the Excel format cell name that // represents a pair of zero based cartesian coordinates. // It can specify either value as fixed.
[ "GetCellIDStringFromCoordsWithFixed", "returns", "the", "Excel", "format", "cell", "name", "that", "represents", "a", "pair", "of", "zero", "based", "cartesian", "coordinates", ".", "It", "can", "specify", "either", "value", "as", "fixed", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L202-L212
train
tealeg/xlsx
lib.go
calculateMaxMinFromWorksheet
func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error) { // Note, this method could be very slow for large spreadsheets. var x, y int var maxVal int maxVal = int(^uint(0) >> 1) minx = maxVal miny = maxVal maxy = 0 maxx = 0 for _, row := range worksheet.SheetData.Row { for _, cell := range row.C { x, y, err = GetCoordsFromCellIDString(cell.R) if err != nil { return -1, -1, -1, -1, err } if x < minx { minx = x } if x > maxx { maxx = x } if y < miny { miny = y } if y > maxy { maxy = y } } } if minx == maxVal { minx = 0 } if miny == maxVal { miny = 0 } return }
go
func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error) { // Note, this method could be very slow for large spreadsheets. var x, y int var maxVal int maxVal = int(^uint(0) >> 1) minx = maxVal miny = maxVal maxy = 0 maxx = 0 for _, row := range worksheet.SheetData.Row { for _, cell := range row.C { x, y, err = GetCoordsFromCellIDString(cell.R) if err != nil { return -1, -1, -1, -1, err } if x < minx { minx = x } if x > maxx { maxx = x } if y < miny { miny = y } if y > maxy { maxy = y } } } if minx == maxVal { minx = 0 } if miny == maxVal { miny = 0 } return }
[ "func", "calculateMaxMinFromWorksheet", "(", "worksheet", "*", "xlsxWorksheet", ")", "(", "minx", ",", "miny", ",", "maxx", ",", "maxy", "int", ",", "err", "error", ")", "{", "var", "x", ",", "y", "int", "\n", "var", "maxVal", "int", "\n", "maxVal", "=", "int", "(", "^", "uint", "(", "0", ")", ">>", "1", ")", "\n", "minx", "=", "maxVal", "\n", "miny", "=", "maxVal", "\n", "maxy", "=", "0", "\n", "maxx", "=", "0", "\n", "for", "_", ",", "row", ":=", "range", "worksheet", ".", "SheetData", ".", "Row", "{", "for", "_", ",", "cell", ":=", "range", "row", ".", "C", "{", "x", ",", "y", ",", "err", "=", "GetCoordsFromCellIDString", "(", "cell", ".", "R", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "err", "\n", "}", "\n", "if", "x", "<", "minx", "{", "minx", "=", "x", "\n", "}", "\n", "if", "x", ">", "maxx", "{", "maxx", "=", "x", "\n", "}", "\n", "if", "y", "<", "miny", "{", "miny", "=", "y", "\n", "}", "\n", "if", "y", ">", "maxy", "{", "maxy", "=", "y", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "minx", "==", "maxVal", "{", "minx", "=", "0", "\n", "}", "\n", "if", "miny", "==", "maxVal", "{", "miny", "=", "0", "\n", "}", "\n", "return", "\n", "}" ]
// calculateMaxMinFromWorkSheet works out the dimensions of a spreadsheet // that doesn't have a DimensionRef set. The only case currently // known where this is true is with XLSX exported from Google Docs. // This is also true for XLSX files created through the streaming APIs.
[ "calculateMaxMinFromWorkSheet", "works", "out", "the", "dimensions", "of", "a", "spreadsheet", "that", "doesn", "t", "have", "a", "DimensionRef", "set", ".", "The", "only", "case", "currently", "known", "where", "this", "is", "true", "is", "with", "XLSX", "exported", "from", "Google", "Docs", ".", "This", "is", "also", "true", "for", "XLSX", "files", "created", "through", "the", "streaming", "APIs", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L236-L272
train
tealeg/xlsx
lib.go
makeRowFromRaw
func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row { var upper int var row *Row var cell *Cell row = new(Row) row.Sheet = sheet upper = -1 for _, rawcell := range rawrow.C { if rawcell.R != "" { x, _, error := GetCoordsFromCellIDString(rawcell.R) if error != nil { panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R)) } if x > upper { upper = x } continue } upper++ } upper++ row.OutlineLevel = rawrow.OutlineLevel row.Cells = make([]*Cell, upper) for i := 0; i < upper; i++ { cell = new(Cell) cell.Value = "" row.Cells[i] = cell } return row }
go
func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row { var upper int var row *Row var cell *Cell row = new(Row) row.Sheet = sheet upper = -1 for _, rawcell := range rawrow.C { if rawcell.R != "" { x, _, error := GetCoordsFromCellIDString(rawcell.R) if error != nil { panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R)) } if x > upper { upper = x } continue } upper++ } upper++ row.OutlineLevel = rawrow.OutlineLevel row.Cells = make([]*Cell, upper) for i := 0; i < upper; i++ { cell = new(Cell) cell.Value = "" row.Cells[i] = cell } return row }
[ "func", "makeRowFromRaw", "(", "rawrow", "xlsxRow", ",", "sheet", "*", "Sheet", ")", "*", "Row", "{", "var", "upper", "int", "\n", "var", "row", "*", "Row", "\n", "var", "cell", "*", "Cell", "\n", "row", "=", "new", "(", "Row", ")", "\n", "row", ".", "Sheet", "=", "sheet", "\n", "upper", "=", "-", "1", "\n", "for", "_", ",", "rawcell", ":=", "range", "rawrow", ".", "C", "{", "if", "rawcell", ".", "R", "!=", "\"\"", "{", "x", ",", "_", ",", "error", ":=", "GetCoordsFromCellIDString", "(", "rawcell", ".", "R", ")", "\n", "if", "error", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"Invalid Cell Coord, %s\\n\"", ",", "\\n", ")", ")", "\n", "}", "\n", "rawcell", ".", "R", "\n", "if", "x", ">", "upper", "{", "upper", "=", "x", "\n", "}", "\n", "}", "\n", "continue", "\n", "}", "\n", "upper", "++", "\n", "upper", "++", "\n", "row", ".", "OutlineLevel", "=", "rawrow", ".", "OutlineLevel", "\n", "row", ".", "Cells", "=", "make", "(", "[", "]", "*", "Cell", ",", "upper", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "upper", ";", "i", "++", "{", "cell", "=", "new", "(", "Cell", ")", "\n", "cell", ".", "Value", "=", "\"\"", "\n", "row", ".", "Cells", "[", "i", "]", "=", "cell", "\n", "}", "\n", "}" ]
// makeRowFromRaw returns the Row representation of the xlsxRow.
[ "makeRowFromRaw", "returns", "the", "Row", "representation", "of", "the", "xlsxRow", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L301-L334
train
tealeg/xlsx
lib.go
fillCellDataFromInlineString
func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell) { cell.Value = "" if rawcell.Is != nil { if rawcell.Is.T != "" { cell.Value = strings.Trim(rawcell.Is.T, " \t\n\r") } else { for _, r := range rawcell.Is.R { cell.Value += r.T } } } }
go
func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell) { cell.Value = "" if rawcell.Is != nil { if rawcell.Is.T != "" { cell.Value = strings.Trim(rawcell.Is.T, " \t\n\r") } else { for _, r := range rawcell.Is.R { cell.Value += r.T } } } }
[ "func", "fillCellDataFromInlineString", "(", "rawcell", "xlsxC", ",", "cell", "*", "Cell", ")", "{", "cell", ".", "Value", "=", "\"\"", "\n", "if", "rawcell", ".", "Is", "!=", "nil", "{", "if", "rawcell", ".", "Is", ".", "T", "!=", "\"\"", "{", "cell", ".", "Value", "=", "strings", ".", "Trim", "(", "rawcell", ".", "Is", ".", "T", ",", "\" \\t\\n\\r\"", ")", "\n", "}", "else", "\\t", "\n", "}", "\n", "}" ]
// fillCellDataFromInlineString attempts to get inline string data and put it into a Cell.
[ "fillCellDataFromInlineString", "attempts", "to", "get", "inline", "string", "data", "and", "put", "it", "into", "a", "Cell", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L509-L520
train
tealeg/xlsx
lib.go
readSheetsFromZipFile
func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error) { var workbook *xlsxWorkbook var err error var rc io.ReadCloser var decoder *xml.Decoder var sheetCount int workbook = new(xlsxWorkbook) rc, err = f.Open() if err != nil { return nil, nil, err } decoder = xml.NewDecoder(rc) err = decoder.Decode(workbook) if err != nil { return nil, nil, err } file.Date1904 = workbook.WorkbookPr.Date1904 for entryNum := range workbook.DefinedNames.DefinedName { file.DefinedNames = append(file.DefinedNames, &workbook.DefinedNames.DefinedName[entryNum]) } // Only try and read sheets that have corresponding files. // Notably this excludes chartsheets don't right now var workbookSheets []xlsxSheet for _, sheet := range workbook.Sheets.Sheet { if f := worksheetFileForSheet(sheet, file.worksheets, sheetXMLMap); f != nil { workbookSheets = append(workbookSheets, sheet) } } sheetCount = len(workbookSheets) sheetsByName := make(map[string]*Sheet, sheetCount) sheets := make([]*Sheet, sheetCount) sheetChan := make(chan *indexedSheet, sheetCount) go func() { defer close(sheetChan) err = nil for i, rawsheet := range workbookSheets { if err := readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap, rowLimit); err != nil { return } } }() for j := 0; j < sheetCount; j++ { sheet := <-sheetChan if sheet.Error != nil { return nil, nil, sheet.Error } sheetName := workbookSheets[sheet.Index].Name sheetsByName[sheetName] = sheet.Sheet sheet.Sheet.Name = sheetName sheets[sheet.Index] = sheet.Sheet } return sheetsByName, sheets, nil }
go
func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error) { var workbook *xlsxWorkbook var err error var rc io.ReadCloser var decoder *xml.Decoder var sheetCount int workbook = new(xlsxWorkbook) rc, err = f.Open() if err != nil { return nil, nil, err } decoder = xml.NewDecoder(rc) err = decoder.Decode(workbook) if err != nil { return nil, nil, err } file.Date1904 = workbook.WorkbookPr.Date1904 for entryNum := range workbook.DefinedNames.DefinedName { file.DefinedNames = append(file.DefinedNames, &workbook.DefinedNames.DefinedName[entryNum]) } // Only try and read sheets that have corresponding files. // Notably this excludes chartsheets don't right now var workbookSheets []xlsxSheet for _, sheet := range workbook.Sheets.Sheet { if f := worksheetFileForSheet(sheet, file.worksheets, sheetXMLMap); f != nil { workbookSheets = append(workbookSheets, sheet) } } sheetCount = len(workbookSheets) sheetsByName := make(map[string]*Sheet, sheetCount) sheets := make([]*Sheet, sheetCount) sheetChan := make(chan *indexedSheet, sheetCount) go func() { defer close(sheetChan) err = nil for i, rawsheet := range workbookSheets { if err := readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap, rowLimit); err != nil { return } } }() for j := 0; j < sheetCount; j++ { sheet := <-sheetChan if sheet.Error != nil { return nil, nil, sheet.Error } sheetName := workbookSheets[sheet.Index].Name sheetsByName[sheetName] = sheet.Sheet sheet.Sheet.Name = sheetName sheets[sheet.Index] = sheet.Sheet } return sheetsByName, sheets, nil }
[ "func", "readSheetsFromZipFile", "(", "f", "*", "zip", ".", "File", ",", "file", "*", "File", ",", "sheetXMLMap", "map", "[", "string", "]", "string", ",", "rowLimit", "int", ")", "(", "map", "[", "string", "]", "*", "Sheet", ",", "[", "]", "*", "Sheet", ",", "error", ")", "{", "var", "workbook", "*", "xlsxWorkbook", "\n", "var", "err", "error", "\n", "var", "rc", "io", ".", "ReadCloser", "\n", "var", "decoder", "*", "xml", ".", "Decoder", "\n", "var", "sheetCount", "int", "\n", "workbook", "=", "new", "(", "xlsxWorkbook", ")", "\n", "rc", ",", "err", "=", "f", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "decoder", "=", "xml", ".", "NewDecoder", "(", "rc", ")", "\n", "err", "=", "decoder", ".", "Decode", "(", "workbook", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "file", ".", "Date1904", "=", "workbook", ".", "WorkbookPr", ".", "Date1904", "\n", "for", "entryNum", ":=", "range", "workbook", ".", "DefinedNames", ".", "DefinedName", "{", "file", ".", "DefinedNames", "=", "append", "(", "file", ".", "DefinedNames", ",", "&", "workbook", ".", "DefinedNames", ".", "DefinedName", "[", "entryNum", "]", ")", "\n", "}", "\n", "var", "workbookSheets", "[", "]", "xlsxSheet", "\n", "for", "_", ",", "sheet", ":=", "range", "workbook", ".", "Sheets", ".", "Sheet", "{", "if", "f", ":=", "worksheetFileForSheet", "(", "sheet", ",", "file", ".", "worksheets", ",", "sheetXMLMap", ")", ";", "f", "!=", "nil", "{", "workbookSheets", "=", "append", "(", "workbookSheets", ",", "sheet", ")", "\n", "}", "\n", "}", "\n", "sheetCount", "=", "len", "(", "workbookSheets", ")", "\n", "sheetsByName", ":=", "make", "(", "map", "[", "string", "]", "*", "Sheet", ",", "sheetCount", ")", "\n", "sheets", ":=", "make", "(", "[", "]", "*", "Sheet", ",", "sheetCount", ")", "\n", "sheetChan", ":=", "make", "(", "chan", "*", "indexedSheet", ",", "sheetCount", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "sheetChan", ")", "\n", "err", "=", "nil", "\n", "for", "i", ",", "rawsheet", ":=", "range", "workbookSheets", "{", "if", "err", ":=", "readSheetFromFile", "(", "sheetChan", ",", "i", ",", "rawsheet", ",", "file", ",", "sheetXMLMap", ",", "rowLimit", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "sheetCount", ";", "j", "++", "{", "sheet", ":=", "<-", "sheetChan", "\n", "if", "sheet", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "sheet", ".", "Error", "\n", "}", "\n", "sheetName", ":=", "workbookSheets", "[", "sheet", ".", "Index", "]", ".", "Name", "\n", "sheetsByName", "[", "sheetName", "]", "=", "sheet", ".", "Sheet", "\n", "sheet", ".", "Sheet", ".", "Name", "=", "sheetName", "\n", "sheets", "[", "sheet", ".", "Index", "]", "=", "sheet", ".", "Sheet", "\n", "}", "\n", "return", "sheetsByName", ",", "sheets", ",", "nil", "\n", "}" ]
// readSheetsFromZipFile is an internal helper function that loops // over the Worksheets defined in the XSLXWorkbook and loads them into // Sheet objects stored in the Sheets slice of a xlsx.File struct.
[ "readSheetsFromZipFile", "is", "an", "internal", "helper", "function", "that", "loops", "over", "the", "Worksheets", "defined", "in", "the", "XSLXWorkbook", "and", "loads", "them", "into", "Sheet", "objects", "stored", "in", "the", "Sheets", "slice", "of", "a", "xlsx", ".", "File", "struct", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L777-L833
train
tealeg/xlsx
lib.go
truncateSheetXML
func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error) { var rowCount int var token xml.Token var readErr error output := new(bytes.Buffer) r = io.TeeReader(r, output) decoder := xml.NewDecoder(r) for { token, readErr = decoder.Token() if readErr == io.EOF { break } else if readErr != nil { return nil, readErr } end, ok := token.(xml.EndElement) if ok && end.Name.Local == "row" { rowCount++ if rowCount >= rowLimit { break } } } offset := decoder.InputOffset() output.Truncate(int(offset)) if readErr != io.EOF { _, err := output.Write([]byte(sheetEnding)) if err != nil { return nil, err } } return output, nil }
go
func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error) { var rowCount int var token xml.Token var readErr error output := new(bytes.Buffer) r = io.TeeReader(r, output) decoder := xml.NewDecoder(r) for { token, readErr = decoder.Token() if readErr == io.EOF { break } else if readErr != nil { return nil, readErr } end, ok := token.(xml.EndElement) if ok && end.Name.Local == "row" { rowCount++ if rowCount >= rowLimit { break } } } offset := decoder.InputOffset() output.Truncate(int(offset)) if readErr != io.EOF { _, err := output.Write([]byte(sheetEnding)) if err != nil { return nil, err } } return output, nil }
[ "func", "truncateSheetXML", "(", "r", "io", ".", "Reader", ",", "rowLimit", "int", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "var", "rowCount", "int", "\n", "var", "token", "xml", ".", "Token", "\n", "var", "readErr", "error", "\n", "output", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "r", "=", "io", ".", "TeeReader", "(", "r", ",", "output", ")", "\n", "decoder", ":=", "xml", ".", "NewDecoder", "(", "r", ")", "\n", "for", "{", "token", ",", "readErr", "=", "decoder", ".", "Token", "(", ")", "\n", "if", "readErr", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "readErr", "!=", "nil", "{", "return", "nil", ",", "readErr", "\n", "}", "\n", "end", ",", "ok", ":=", "token", ".", "(", "xml", ".", "EndElement", ")", "\n", "if", "ok", "&&", "end", ".", "Name", ".", "Local", "==", "\"row\"", "{", "rowCount", "++", "\n", "if", "rowCount", ">=", "rowLimit", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "offset", ":=", "decoder", ".", "InputOffset", "(", ")", "\n", "output", ".", "Truncate", "(", "int", "(", "offset", ")", ")", "\n", "if", "readErr", "!=", "io", ".", "EOF", "{", "_", ",", "err", ":=", "output", ".", "Write", "(", "[", "]", "byte", "(", "sheetEnding", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "output", ",", "nil", "\n", "}" ]
// truncateSheetXML will take in a reader to an XML sheet file and will return a reader that will read an equivalent // XML sheet file with only the number of rows specified. This greatly speeds up XML unmarshalling when only // a few rows need to be read from a large sheet. // When sheets are truncated, all formatting present after the sheetData tag will be lost, but all of this formatting // is related to printing and visibility, and is out of scope for most purposes of this library.
[ "truncateSheetXML", "will", "take", "in", "a", "reader", "to", "an", "XML", "sheet", "file", "and", "will", "return", "a", "reader", "that", "will", "read", "an", "equivalent", "XML", "sheet", "file", "with", "only", "the", "number", "of", "rows", "specified", ".", "This", "greatly", "speeds", "up", "XML", "unmarshalling", "when", "only", "a", "few", "rows", "need", "to", "be", "read", "from", "a", "large", "sheet", ".", "When", "sheets", "are", "truncated", "all", "formatting", "present", "after", "the", "sheetData", "tag", "will", "be", "lost", "but", "all", "of", "this", "formatting", "is", "related", "to", "printing", "and", "visibility", "and", "is", "out", "of", "scope", "for", "most", "purposes", "of", "this", "library", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L1096-L1131
train
tealeg/xlsx
file.go
FileToSliceUnmerged
func FileToSliceUnmerged(path string) ([][][]string, error) { f, err := OpenFile(path) if err != nil { return nil, err } return f.ToSliceUnmerged() }
go
func FileToSliceUnmerged(path string) ([][][]string, error) { f, err := OpenFile(path) if err != nil { return nil, err } return f.ToSliceUnmerged() }
[ "func", "FileToSliceUnmerged", "(", "path", "string", ")", "(", "[", "]", "[", "]", "[", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "OpenFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "f", ".", "ToSliceUnmerged", "(", ")", "\n", "}" ]
// FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged. // It returns the raw data contained in an Excel XLSX file as three // dimensional slice. Merged cells will be unmerged. Covered cells become the // values of theirs origins.
[ "FileToSliceUnmerged", "is", "a", "wrapper", "around", "File", ".", "ToSliceUnmerged", ".", "It", "returns", "the", "raw", "data", "contained", "in", "an", "Excel", "XLSX", "file", "as", "three", "dimensional", "slice", ".", "Merged", "cells", "will", "be", "unmerged", ".", "Covered", "cells", "become", "the", "values", "of", "theirs", "origins", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L112-L118
train
tealeg/xlsx
sheet.go
AddRowAtIndex
func (s *Sheet) AddRowAtIndex(index int) (*Row, error) { if index < 0 || index > len(s.Rows) { return nil, errors.New("AddRowAtIndex: index out of bounds") } row := &Row{Sheet: s} s.Rows = append(s.Rows, nil) if index < len(s.Rows) { copy(s.Rows[index+1:], s.Rows[index:]) } s.Rows[index] = row if len(s.Rows) > s.MaxRow { s.MaxRow = len(s.Rows) } return row, nil }
go
func (s *Sheet) AddRowAtIndex(index int) (*Row, error) { if index < 0 || index > len(s.Rows) { return nil, errors.New("AddRowAtIndex: index out of bounds") } row := &Row{Sheet: s} s.Rows = append(s.Rows, nil) if index < len(s.Rows) { copy(s.Rows[index+1:], s.Rows[index:]) } s.Rows[index] = row if len(s.Rows) > s.MaxRow { s.MaxRow = len(s.Rows) } return row, nil }
[ "func", "(", "s", "*", "Sheet", ")", "AddRowAtIndex", "(", "index", "int", ")", "(", "*", "Row", ",", "error", ")", "{", "if", "index", "<", "0", "||", "index", ">", "len", "(", "s", ".", "Rows", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"AddRowAtIndex: index out of bounds\"", ")", "\n", "}", "\n", "row", ":=", "&", "Row", "{", "Sheet", ":", "s", "}", "\n", "s", ".", "Rows", "=", "append", "(", "s", ".", "Rows", ",", "nil", ")", "\n", "if", "index", "<", "len", "(", "s", ".", "Rows", ")", "{", "copy", "(", "s", ".", "Rows", "[", "index", "+", "1", ":", "]", ",", "s", ".", "Rows", "[", "index", ":", "]", ")", "\n", "}", "\n", "s", ".", "Rows", "[", "index", "]", "=", "row", "\n", "if", "len", "(", "s", ".", "Rows", ")", ">", "s", ".", "MaxRow", "{", "s", ".", "MaxRow", "=", "len", "(", "s", ".", "Rows", ")", "\n", "}", "\n", "return", "row", ",", "nil", "\n", "}" ]
// Add a new Row to a Sheet at a specific index
[ "Add", "a", "new", "Row", "to", "a", "Sheet", "at", "a", "specific", "index" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L60-L75
train
tealeg/xlsx
sheet.go
RemoveRowAtIndex
func (s *Sheet) RemoveRowAtIndex(index int) error { if index < 0 || index >= len(s.Rows) { return errors.New("RemoveRowAtIndex: index out of bounds") } s.Rows = append(s.Rows[:index], s.Rows[index+1:]...) return nil }
go
func (s *Sheet) RemoveRowAtIndex(index int) error { if index < 0 || index >= len(s.Rows) { return errors.New("RemoveRowAtIndex: index out of bounds") } s.Rows = append(s.Rows[:index], s.Rows[index+1:]...) return nil }
[ "func", "(", "s", "*", "Sheet", ")", "RemoveRowAtIndex", "(", "index", "int", ")", "error", "{", "if", "index", "<", "0", "||", "index", ">=", "len", "(", "s", ".", "Rows", ")", "{", "return", "errors", ".", "New", "(", "\"RemoveRowAtIndex: index out of bounds\"", ")", "\n", "}", "\n", "s", ".", "Rows", "=", "append", "(", "s", ".", "Rows", "[", ":", "index", "]", ",", "s", ".", "Rows", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}" ]
// Removes a row at a specific index
[ "Removes", "a", "row", "at", "a", "specific", "index" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L78-L84
train
tealeg/xlsx
sheet.go
handleMerged
func (s *Sheet) handleMerged() { merged := make(map[string]*Cell) for r, row := range s.Rows { for c, cell := range row.Cells { if cell.HMerge > 0 || cell.VMerge > 0 { coord := GetCellIDStringFromCoords(c, r) merged[coord] = cell } } } // This loop iterates over all cells that should be merged and applies the correct // borders to them depending on their position. If any cells required by the merge // are missing, they will be allocated by s.Cell(). for key, cell := range merged { maincol, mainrow, _ := GetCoordsFromCellIDString(key) for rownum := 0; rownum <= cell.VMerge; rownum++ { for colnum := 0; colnum <= cell.HMerge; colnum++ { // make cell s.Cell(mainrow+rownum, maincol+colnum) } } } }
go
func (s *Sheet) handleMerged() { merged := make(map[string]*Cell) for r, row := range s.Rows { for c, cell := range row.Cells { if cell.HMerge > 0 || cell.VMerge > 0 { coord := GetCellIDStringFromCoords(c, r) merged[coord] = cell } } } // This loop iterates over all cells that should be merged and applies the correct // borders to them depending on their position. If any cells required by the merge // are missing, they will be allocated by s.Cell(). for key, cell := range merged { maincol, mainrow, _ := GetCoordsFromCellIDString(key) for rownum := 0; rownum <= cell.VMerge; rownum++ { for colnum := 0; colnum <= cell.HMerge; colnum++ { // make cell s.Cell(mainrow+rownum, maincol+colnum) } } } }
[ "func", "(", "s", "*", "Sheet", ")", "handleMerged", "(", ")", "{", "merged", ":=", "make", "(", "map", "[", "string", "]", "*", "Cell", ")", "\n", "for", "r", ",", "row", ":=", "range", "s", ".", "Rows", "{", "for", "c", ",", "cell", ":=", "range", "row", ".", "Cells", "{", "if", "cell", ".", "HMerge", ">", "0", "||", "cell", ".", "VMerge", ">", "0", "{", "coord", ":=", "GetCellIDStringFromCoords", "(", "c", ",", "r", ")", "\n", "merged", "[", "coord", "]", "=", "cell", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "key", ",", "cell", ":=", "range", "merged", "{", "maincol", ",", "mainrow", ",", "_", ":=", "GetCoordsFromCellIDString", "(", "key", ")", "\n", "for", "rownum", ":=", "0", ";", "rownum", "<=", "cell", ".", "VMerge", ";", "rownum", "++", "{", "for", "colnum", ":=", "0", ";", "colnum", "<=", "cell", ".", "HMerge", ";", "colnum", "++", "{", "s", ".", "Cell", "(", "mainrow", "+", "rownum", ",", "maincol", "+", "colnum", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// When merging cells, the cell may be the 'original' or the 'covered'. // First, figure out which cells are merge starting points. Then create // the necessary cells underlying the merge area. // Then go through all the underlying cells and apply the appropriate // border, based on the original cell.
[ "When", "merging", "cells", "the", "cell", "may", "be", "the", "original", "or", "the", "covered", ".", "First", "figure", "out", "which", "cells", "are", "merge", "starting", "points", ".", "Then", "create", "the", "necessary", "cells", "underlying", "the", "merge", "area", ".", "Then", "go", "through", "all", "the", "underlying", "cells", "and", "apply", "the", "appropriate", "border", "based", "on", "the", "original", "cell", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L175-L201
train
tealeg/xlsx
cell.go
GetTime
func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) { f, err := c.Float() if err != nil { return t, err } return TimeFromExcelTime(f, date1904), nil }
go
func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) { f, err := c.Float() if err != nil { return t, err } return TimeFromExcelTime(f, date1904), nil }
[ "func", "(", "c", "*", "Cell", ")", "GetTime", "(", "date1904", "bool", ")", "(", "t", "time", ".", "Time", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "c", ".", "Float", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "t", ",", "err", "\n", "}", "\n", "return", "TimeFromExcelTime", "(", "f", ",", "date1904", ")", ",", "nil", "\n", "}" ]
//GetTime returns the value of a Cell as a time.Time
[ "GetTime", "returns", "the", "value", "of", "a", "Cell", "as", "a", "time", ".", "Time" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L111-L117
train
tealeg/xlsx
cell.go
SetDateWithOptions
func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) { _, offset := t.In(options.Location).Zone() t = time.Unix(t.Unix()+int64(offset), 0) c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC), c.date1904), options.ExcelTimeFormat) }
go
func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) { _, offset := t.In(options.Location).Zone() t = time.Unix(t.Unix()+int64(offset), 0) c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC), c.date1904), options.ExcelTimeFormat) }
[ "func", "(", "c", "*", "Cell", ")", "SetDateWithOptions", "(", "t", "time", ".", "Time", ",", "options", "DateTimeOptions", ")", "{", "_", ",", "offset", ":=", "t", ".", "In", "(", "options", ".", "Location", ")", ".", "Zone", "(", ")", "\n", "t", "=", "time", ".", "Unix", "(", "t", ".", "Unix", "(", ")", "+", "int64", "(", "offset", ")", ",", "0", ")", "\n", "c", ".", "SetDateTimeWithFormat", "(", "TimeToExcelTime", "(", "t", ".", "In", "(", "timeLocationUTC", ")", ",", "c", ".", "date1904", ")", ",", "options", ".", "ExcelTimeFormat", ")", "\n", "}" ]
// SetDateWithOptions allows for more granular control when exporting dates and times
[ "SetDateWithOptions", "allows", "for", "more", "granular", "control", "when", "exporting", "dates", "and", "times" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L177-L181
train
tealeg/xlsx
cell.go
setNumeric
func (c *Cell) setNumeric(s string) { c.Value = s c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] c.formula = "" c.cellType = CellTypeNumeric }
go
func (c *Cell) setNumeric(s string) { c.Value = s c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] c.formula = "" c.cellType = CellTypeNumeric }
[ "func", "(", "c", "*", "Cell", ")", "setNumeric", "(", "s", "string", ")", "{", "c", ".", "Value", "=", "s", "\n", "c", ".", "NumFmt", "=", "builtInNumFmt", "[", "builtInNumFmtIndex_GENERAL", "]", "\n", "c", ".", "formula", "=", "\"\"", "\n", "c", ".", "cellType", "=", "CellTypeNumeric", "\n", "}" ]
// setNumeric sets a cell's value to a number
[ "setNumeric", "sets", "a", "cell", "s", "value", "to", "a", "number" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L261-L266
train
tealeg/xlsx
cell.go
getNumberFormat
func (c *Cell) getNumberFormat() *parsedNumberFormat { if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt { c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt) } return c.parsedNumFmt }
go
func (c *Cell) getNumberFormat() *parsedNumberFormat { if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt { c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt) } return c.parsedNumFmt }
[ "func", "(", "c", "*", "Cell", ")", "getNumberFormat", "(", ")", "*", "parsedNumberFormat", "{", "if", "c", ".", "parsedNumFmt", "==", "nil", "||", "c", ".", "parsedNumFmt", ".", "numFmt", "!=", "c", ".", "NumFmt", "{", "c", ".", "parsedNumFmt", "=", "parseFullNumberFormatString", "(", "c", ".", "NumFmt", ")", "\n", "}", "\n", "return", "c", ".", "parsedNumFmt", "\n", "}" ]
// getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a // public field that could be edited by clients.
[ "getNumberFormat", "will", "update", "the", "parsedNumFmt", "struct", "if", "it", "has", "become", "out", "of", "date", "since", "a", "cell", "s", "NumFmt", "string", "is", "a", "public", "field", "that", "could", "be", "edited", "by", "clients", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L357-L362
train
tealeg/xlsx
cell.go
FormattedValue
func (c *Cell) FormattedValue() (string, error) { fullFormat := c.getNumberFormat() returnVal, err := fullFormat.FormatValue(c) if fullFormat.parseEncounteredError != nil { return returnVal, *fullFormat.parseEncounteredError } return returnVal, err }
go
func (c *Cell) FormattedValue() (string, error) { fullFormat := c.getNumberFormat() returnVal, err := fullFormat.FormatValue(c) if fullFormat.parseEncounteredError != nil { return returnVal, *fullFormat.parseEncounteredError } return returnVal, err }
[ "func", "(", "c", "*", "Cell", ")", "FormattedValue", "(", ")", "(", "string", ",", "error", ")", "{", "fullFormat", ":=", "c", ".", "getNumberFormat", "(", ")", "\n", "returnVal", ",", "err", ":=", "fullFormat", ".", "FormatValue", "(", "c", ")", "\n", "if", "fullFormat", ".", "parseEncounteredError", "!=", "nil", "{", "return", "returnVal", ",", "*", "fullFormat", ".", "parseEncounteredError", "\n", "}", "\n", "return", "returnVal", ",", "err", "\n", "}" ]
// FormattedValue returns a value, and possibly an error condition // from a Cell. If it is possible to apply a format to the cell // value, it will do so, if not then an error will be returned, along // with the raw value of the Cell.
[ "FormattedValue", "returns", "a", "value", "and", "possibly", "an", "error", "condition", "from", "a", "Cell", ".", "If", "it", "is", "possible", "to", "apply", "a", "format", "to", "the", "cell", "value", "it", "will", "do", "so", "if", "not", "then", "an", "error", "will", "be", "returned", "along", "with", "the", "raw", "value", "of", "the", "Cell", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L368-L375
train
eclipse/paho.mqtt.golang
packets/connect.go
Validate
func (c *ConnectPacket) Validate() byte { if c.PasswordFlag && !c.UsernameFlag { return ErrRefusedBadUsernameOrPassword } if c.ReservedBit != 0 { //Bad reserved bit return ErrProtocolViolation } if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { //Mismatched or unsupported protocol version return ErrRefusedBadProtocolVersion } if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { //Bad protocol name return ErrProtocolViolation } if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { //Bad size field return ErrProtocolViolation } if len(c.ClientIdentifier) == 0 && !c.CleanSession { //Bad client identifier return ErrRefusedIDRejected } return Accepted }
go
func (c *ConnectPacket) Validate() byte { if c.PasswordFlag && !c.UsernameFlag { return ErrRefusedBadUsernameOrPassword } if c.ReservedBit != 0 { //Bad reserved bit return ErrProtocolViolation } if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { //Mismatched or unsupported protocol version return ErrRefusedBadProtocolVersion } if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { //Bad protocol name return ErrProtocolViolation } if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { //Bad size field return ErrProtocolViolation } if len(c.ClientIdentifier) == 0 && !c.CleanSession { //Bad client identifier return ErrRefusedIDRejected } return Accepted }
[ "func", "(", "c", "*", "ConnectPacket", ")", "Validate", "(", ")", "byte", "{", "if", "c", ".", "PasswordFlag", "&&", "!", "c", ".", "UsernameFlag", "{", "return", "ErrRefusedBadUsernameOrPassword", "\n", "}", "\n", "if", "c", ".", "ReservedBit", "!=", "0", "{", "return", "ErrProtocolViolation", "\n", "}", "\n", "if", "(", "c", ".", "ProtocolName", "==", "\"MQIsdp\"", "&&", "c", ".", "ProtocolVersion", "!=", "3", ")", "||", "(", "c", ".", "ProtocolName", "==", "\"MQTT\"", "&&", "c", ".", "ProtocolVersion", "!=", "4", ")", "{", "return", "ErrRefusedBadProtocolVersion", "\n", "}", "\n", "if", "c", ".", "ProtocolName", "!=", "\"MQIsdp\"", "&&", "c", ".", "ProtocolName", "!=", "\"MQTT\"", "{", "return", "ErrProtocolViolation", "\n", "}", "\n", "if", "len", "(", "c", ".", "ClientIdentifier", ")", ">", "65535", "||", "len", "(", "c", ".", "Username", ")", ">", "65535", "||", "len", "(", "c", ".", "Password", ")", ">", "65535", "{", "return", "ErrProtocolViolation", "\n", "}", "\n", "if", "len", "(", "c", ".", "ClientIdentifier", ")", "==", "0", "&&", "!", "c", ".", "CleanSession", "{", "return", "ErrRefusedIDRejected", "\n", "}", "\n", "return", "Accepted", "\n", "}" ]
//Validate performs validation of the fields of a Connect packet
[ "Validate", "performs", "validation", "of", "the", "fields", "of", "a", "Connect", "packet" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/connect.go#L123-L148
train
eclipse/paho.mqtt.golang
store.go
persistInbound
func persistInbound(s Store, m packets.ControlPacket) { switch m.Details().Qos { case 0: switch m.(type) { case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: // Received a puback. delete matching publish // from obound s.Del(outboundKeyFromMID(m.Details().MessageID)) case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 1: switch m.(type) { case *packets.PublishPacket, *packets.PubrelPacket: // Received a publish. store it in ibound // until puback sent s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 2: switch m.(type) { case *packets.PublishPacket: // Received a publish. store it in ibound // until pubrel received s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } } }
go
func persistInbound(s Store, m packets.ControlPacket) { switch m.Details().Qos { case 0: switch m.(type) { case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: // Received a puback. delete matching publish // from obound s.Del(outboundKeyFromMID(m.Details().MessageID)) case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 1: switch m.(type) { case *packets.PublishPacket, *packets.PubrelPacket: // Received a publish. store it in ibound // until puback sent s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 2: switch m.(type) { case *packets.PublishPacket: // Received a publish. store it in ibound // until pubrel received s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } } }
[ "func", "persistInbound", "(", "s", "Store", ",", "m", "packets", ".", "ControlPacket", ")", "{", "switch", "m", ".", "Details", "(", ")", ".", "Qos", "{", "case", "0", ":", "switch", "m", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PubackPacket", ",", "*", "packets", ".", "SubackPacket", ",", "*", "packets", ".", "UnsubackPacket", ",", "*", "packets", ".", "PubcompPacket", ":", "s", ".", "Del", "(", "outboundKeyFromMID", "(", "m", ".", "Details", "(", ")", ".", "MessageID", ")", ")", "\n", "case", "*", "packets", ".", "PublishPacket", ",", "*", "packets", ".", "PubrecPacket", ",", "*", "packets", ".", "PingrespPacket", ",", "*", "packets", ".", "ConnackPacket", ":", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"Asked to persist an invalid messages type\"", ")", "\n", "}", "\n", "case", "1", ":", "switch", "m", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PublishPacket", ",", "*", "packets", ".", "PubrelPacket", ":", "s", ".", "Put", "(", "inboundKeyFromMID", "(", "m", ".", "Details", "(", ")", ".", "MessageID", ")", ",", "m", ")", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"Asked to persist an invalid messages type\"", ")", "\n", "}", "\n", "case", "2", ":", "switch", "m", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PublishPacket", ":", "s", ".", "Put", "(", "inboundKeyFromMID", "(", "m", ".", "Details", "(", ")", ".", "MessageID", ")", ",", "m", ")", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"Asked to persist an invalid messages type\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// govern which incoming messages are persisted
[ "govern", "which", "incoming", "messages", "are", "persisted" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/store.go#L105-L136
train
eclipse/paho.mqtt.golang
options.go
SetClientID
func (o *ClientOptions) SetClientID(id string) *ClientOptions { o.ClientID = id return o }
go
func (o *ClientOptions) SetClientID(id string) *ClientOptions { o.ClientID = id return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetClientID", "(", "id", "string", ")", "*", "ClientOptions", "{", "o", ".", "ClientID", "=", "id", "\n", "return", "o", "\n", "}" ]
// SetClientID will set the client id to be used by this client when // connecting to the MQTT broker. According to the MQTT v3.1 specification, // a client id mus be no longer than 23 characters.
[ "SetClientID", "will", "set", "the", "client", "id", "to", "be", "used", "by", "this", "client", "when", "connecting", "to", "the", "MQTT", "broker", ".", "According", "to", "the", "MQTT", "v3", ".", "1", "specification", "a", "client", "id", "mus", "be", "no", "longer", "than", "23", "characters", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L153-L156
train
eclipse/paho.mqtt.golang
options.go
SetCleanSession
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions { o.CleanSession = clean return o }
go
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions { o.CleanSession = clean return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetCleanSession", "(", "clean", "bool", ")", "*", "ClientOptions", "{", "o", ".", "CleanSession", "=", "clean", "\n", "return", "o", "\n", "}" ]
// SetCleanSession will set the "clean session" flag in the connect message // when this client connects to an MQTT broker. By setting this flag, you are // indicating that no messages saved by the broker for this client should be // delivered. Any messages that were going to be sent by this client before // diconnecting previously but didn't will not be sent upon connecting to the // broker.
[ "SetCleanSession", "will", "set", "the", "clean", "session", "flag", "in", "the", "connect", "message", "when", "this", "client", "connects", "to", "an", "MQTT", "broker", ".", "By", "setting", "this", "flag", "you", "are", "indicating", "that", "no", "messages", "saved", "by", "the", "broker", "for", "this", "client", "should", "be", "delivered", ".", "Any", "messages", "that", "were", "going", "to", "be", "sent", "by", "this", "client", "before", "diconnecting", "previously", "but", "didn", "t", "will", "not", "be", "sent", "upon", "connecting", "to", "the", "broker", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L189-L192
train
eclipse/paho.mqtt.golang
options.go
SetOrderMatters
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions { o.Order = order return o }
go
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions { o.Order = order return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetOrderMatters", "(", "order", "bool", ")", "*", "ClientOptions", "{", "o", ".", "Order", "=", "order", "\n", "return", "o", "\n", "}" ]
// SetOrderMatters will set the message routing to guarantee order within // each QoS level. By default, this value is true. If set to false, // this flag indicates that messages can be delivered asynchronously // from the client to the application and possibly arrive out of order.
[ "SetOrderMatters", "will", "set", "the", "message", "routing", "to", "guarantee", "order", "within", "each", "QoS", "level", ".", "By", "default", "this", "value", "is", "true", ".", "If", "set", "to", "false", "this", "flag", "indicates", "that", "messages", "can", "be", "delivered", "asynchronously", "from", "the", "client", "to", "the", "application", "and", "possibly", "arrive", "out", "of", "order", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L198-L201
train
eclipse/paho.mqtt.golang
options.go
SetStore
func (o *ClientOptions) SetStore(s Store) *ClientOptions { o.Store = s return o }
go
func (o *ClientOptions) SetStore(s Store) *ClientOptions { o.Store = s return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetStore", "(", "s", "Store", ")", "*", "ClientOptions", "{", "o", ".", "Store", "=", "s", "\n", "return", "o", "\n", "}" ]
// SetStore will set the implementation of the Store interface // used to provide message persistence in cases where QoS levels // QoS_ONE or QoS_TWO are used. If no store is provided, then the // client will use MemoryStore by default.
[ "SetStore", "will", "set", "the", "implementation", "of", "the", "Store", "interface", "used", "to", "provide", "message", "persistence", "in", "cases", "where", "QoS", "levels", "QoS_ONE", "or", "QoS_TWO", "are", "used", ".", "If", "no", "store", "is", "provided", "then", "the", "client", "will", "use", "MemoryStore", "by", "default", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L215-L218
train
eclipse/paho.mqtt.golang
options.go
SetProtocolVersion
func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions { if (pv >= 3 && pv <= 4) || (pv > 0x80) { o.ProtocolVersion = pv o.protocolVersionExplicit = true } return o }
go
func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions { if (pv >= 3 && pv <= 4) || (pv > 0x80) { o.ProtocolVersion = pv o.protocolVersionExplicit = true } return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetProtocolVersion", "(", "pv", "uint", ")", "*", "ClientOptions", "{", "if", "(", "pv", ">=", "3", "&&", "pv", "<=", "4", ")", "||", "(", "pv", ">", "0x80", ")", "{", "o", ".", "ProtocolVersion", "=", "pv", "\n", "o", ".", "protocolVersionExplicit", "=", "true", "\n", "}", "\n", "return", "o", "\n", "}" ]
// SetProtocolVersion sets the MQTT version to be used to connect to the // broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1
[ "SetProtocolVersion", "sets", "the", "MQTT", "version", "to", "be", "used", "to", "connect", "to", "the", "broker", ".", "Legitimate", "values", "are", "currently", "3", "-", "MQTT", "3", ".", "1", "or", "4", "-", "MQTT", "3", ".", "1", ".", "1" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L239-L245
train
eclipse/paho.mqtt.golang
options.go
SetOnConnectHandler
func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions { o.OnConnect = onConn return o }
go
func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions { o.OnConnect = onConn return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetOnConnectHandler", "(", "onConn", "OnConnectHandler", ")", "*", "ClientOptions", "{", "o", ".", "OnConnect", "=", "onConn", "\n", "return", "o", "\n", "}" ]
// SetOnConnectHandler sets the function to be called when the client is connected. Both // at initial connection time and upon automatic reconnect.
[ "SetOnConnectHandler", "sets", "the", "function", "to", "be", "called", "when", "the", "client", "is", "connected", ".", "Both", "at", "initial", "connection", "time", "and", "upon", "automatic", "reconnect", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L284-L287
train
eclipse/paho.mqtt.golang
options.go
SetConnectionLostHandler
func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions { o.OnConnectionLost = onLost return o }
go
func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions { o.OnConnectionLost = onLost return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetConnectionLostHandler", "(", "onLost", "ConnectionLostHandler", ")", "*", "ClientOptions", "{", "o", ".", "OnConnectionLost", "=", "onLost", "\n", "return", "o", "\n", "}" ]
// SetConnectionLostHandler will set the OnConnectionLost callback to be executed // in the case where the client unexpectedly loses connection with the MQTT broker.
[ "SetConnectionLostHandler", "will", "set", "the", "OnConnectionLost", "callback", "to", "be", "executed", "in", "the", "case", "where", "the", "client", "unexpectedly", "loses", "connection", "with", "the", "MQTT", "broker", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L291-L294
train
eclipse/paho.mqtt.golang
options.go
SetWriteTimeout
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions { o.WriteTimeout = t return o }
go
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions { o.WriteTimeout = t return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetWriteTimeout", "(", "t", "time", ".", "Duration", ")", "*", "ClientOptions", "{", "o", ".", "WriteTimeout", "=", "t", "\n", "return", "o", "\n", "}" ]
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a // timeout error. A duration of 0 never times out. Default 30 seconds
[ "SetWriteTimeout", "puts", "a", "limit", "on", "how", "long", "a", "mqtt", "publish", "should", "block", "until", "it", "unblocks", "with", "a", "timeout", "error", ".", "A", "duration", "of", "0", "never", "times", "out", ".", "Default", "30", "seconds" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L298-L301
train
eclipse/paho.mqtt.golang
options.go
SetMaxReconnectInterval
func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions { o.MaxReconnectInterval = t return o }
go
func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions { o.MaxReconnectInterval = t return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetMaxReconnectInterval", "(", "t", "time", ".", "Duration", ")", "*", "ClientOptions", "{", "o", ".", "MaxReconnectInterval", "=", "t", "\n", "return", "o", "\n", "}" ]
// SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts // when connection is lost
[ "SetMaxReconnectInterval", "sets", "the", "maximum", "time", "that", "will", "be", "waited", "between", "reconnection", "attempts", "when", "connection", "is", "lost" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L313-L316
train
eclipse/paho.mqtt.golang
options.go
SetAutoReconnect
func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions { o.AutoReconnect = a return o }
go
func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions { o.AutoReconnect = a return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetAutoReconnect", "(", "a", "bool", ")", "*", "ClientOptions", "{", "o", ".", "AutoReconnect", "=", "a", "\n", "return", "o", "\n", "}" ]
// SetAutoReconnect sets whether the automatic reconnection logic should be used // when the connection is lost, even if disabled the ConnectionLostHandler is still // called
[ "SetAutoReconnect", "sets", "whether", "the", "automatic", "reconnection", "logic", "should", "be", "used", "when", "the", "connection", "is", "lost", "even", "if", "disabled", "the", "ConnectionLostHandler", "is", "still", "called" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L321-L324
train
eclipse/paho.mqtt.golang
options.go
SetMessageChannelDepth
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions { o.MessageChannelDepth = s return o }
go
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions { o.MessageChannelDepth = s return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetMessageChannelDepth", "(", "s", "uint", ")", "*", "ClientOptions", "{", "o", ".", "MessageChannelDepth", "=", "s", "\n", "return", "o", "\n", "}" ]
// SetMessageChannelDepth sets the size of the internal queue that holds messages while the // client is temporairily offline, allowing the application to publish when the client is // reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise // ignored.
[ "SetMessageChannelDepth", "sets", "the", "size", "of", "the", "internal", "queue", "that", "holds", "messages", "while", "the", "client", "is", "temporairily", "offline", "allowing", "the", "application", "to", "publish", "when", "the", "client", "is", "reconnecting", ".", "This", "setting", "is", "only", "valid", "if", "AutoReconnect", "is", "set", "to", "true", "it", "is", "otherwise", "ignored", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L330-L333
train
eclipse/paho.mqtt.golang
options.go
SetHTTPHeaders
func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions { o.HTTPHeaders = h return o }
go
func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions { o.HTTPHeaders = h return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetHTTPHeaders", "(", "h", "http", ".", "Header", ")", "*", "ClientOptions", "{", "o", ".", "HTTPHeaders", "=", "h", "\n", "return", "o", "\n", "}" ]
// SetHTTPHeaders sets the additional HTTP headers that will be sent in the WebSocket // opening handshake.
[ "SetHTTPHeaders", "sets", "the", "additional", "HTTP", "headers", "that", "will", "be", "sent", "in", "the", "WebSocket", "opening", "handshake", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L337-L340
train
eclipse/paho.mqtt.golang
token.go
WaitTimeout
func (b *baseToken) WaitTimeout(d time.Duration) bool { b.m.Lock() defer b.m.Unlock() timer := time.NewTimer(d) select { case <-b.complete: if !timer.Stop() { <-timer.C } return true case <-timer.C: } return false }
go
func (b *baseToken) WaitTimeout(d time.Duration) bool { b.m.Lock() defer b.m.Unlock() timer := time.NewTimer(d) select { case <-b.complete: if !timer.Stop() { <-timer.C } return true case <-timer.C: } return false }
[ "func", "(", "b", "*", "baseToken", ")", "WaitTimeout", "(", "d", "time", ".", "Duration", ")", "bool", "{", "b", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "m", ".", "Unlock", "(", ")", "\n", "timer", ":=", "time", ".", "NewTimer", "(", "d", ")", "\n", "select", "{", "case", "<-", "b", ".", "complete", ":", "if", "!", "timer", ".", "Stop", "(", ")", "{", "<-", "timer", ".", "C", "\n", "}", "\n", "return", "true", "\n", "case", "<-", "timer", ".", "C", ":", "}", "\n", "return", "false", "\n", "}" ]
// WaitTimeout takes a time.Duration to wait for the flow associated with the // Token to complete, returns true if it returned before the timeout or // returns false if the timeout occurred. In the case of a timeout the Token // does not have an error set in case the caller wishes to wait again
[ "WaitTimeout", "takes", "a", "time", ".", "Duration", "to", "wait", "for", "the", "flow", "associated", "with", "the", "Token", "to", "complete", "returns", "true", "if", "it", "returned", "before", "the", "timeout", "or", "returns", "false", "if", "the", "timeout", "occurred", ".", "In", "the", "case", "of", "a", "timeout", "the", "Token", "does", "not", "have", "an", "error", "set", "in", "case", "the", "caller", "wishes", "to", "wait", "again" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L66-L81
train
eclipse/paho.mqtt.golang
token.go
Result
func (s *SubscribeToken) Result() map[string]byte { s.m.RLock() defer s.m.RUnlock() return s.subResult }
go
func (s *SubscribeToken) Result() map[string]byte { s.m.RLock() defer s.m.RUnlock() return s.subResult }
[ "func", "(", "s", "*", "SubscribeToken", ")", "Result", "(", ")", "map", "[", "string", "]", "byte", "{", "s", ".", "m", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "m", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "subResult", "\n", "}" ]
// Result returns a map of topics that were subscribed to along with // the matching return code from the broker. This is either the Qos // value of the subscription or an error code.
[ "Result", "returns", "a", "map", "of", "topics", "that", "were", "subscribed", "to", "along", "with", "the", "matching", "return", "code", "from", "the", "broker", ".", "This", "is", "either", "the", "Qos", "value", "of", "the", "subscription", "or", "an", "error", "code", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L168-L172
train
eclipse/paho.mqtt.golang
options_reader.go
Servers
func (r *ClientOptionsReader) Servers() []*url.URL { s := make([]*url.URL, len(r.options.Servers)) for i, u := range r.options.Servers { nu := *u s[i] = &nu } return s }
go
func (r *ClientOptionsReader) Servers() []*url.URL { s := make([]*url.URL, len(r.options.Servers)) for i, u := range r.options.Servers { nu := *u s[i] = &nu } return s }
[ "func", "(", "r", "*", "ClientOptionsReader", ")", "Servers", "(", ")", "[", "]", "*", "url", ".", "URL", "{", "s", ":=", "make", "(", "[", "]", "*", "url", ".", "URL", ",", "len", "(", "r", ".", "options", ".", "Servers", ")", ")", "\n", "for", "i", ",", "u", ":=", "range", "r", ".", "options", ".", "Servers", "{", "nu", ":=", "*", "u", "\n", "s", "[", "i", "]", "=", "&", "nu", "\n", "}", "\n", "return", "s", "\n", "}" ]
//Servers returns a slice of the servers defined in the clientoptions
[ "Servers", "returns", "a", "slice", "of", "the", "servers", "defined", "in", "the", "clientoptions" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options_reader.go#L30-L39
train
eclipse/paho.mqtt.golang
memstore.go
Open
func (store *MemoryStore) Open() { store.Lock() defer store.Unlock() store.opened = true DEBUG.Println(STR, "memorystore initialized") }
go
func (store *MemoryStore) Open() { store.Lock() defer store.Unlock() store.opened = true DEBUG.Println(STR, "memorystore initialized") }
[ "func", "(", "store", "*", "MemoryStore", ")", "Open", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "store", ".", "opened", "=", "true", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "\"memorystore initialized\"", ")", "\n", "}" ]
// Open initializes a MemoryStore instance.
[ "Open", "initializes", "a", "MemoryStore", "instance", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L44-L49
train
eclipse/paho.mqtt.golang
memstore.go
Get
func (store *MemoryStore) Get(key string) packets.ControlPacket { store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return nil } mid := mIDFromKey(key) m := store.messages[key] if m == nil { CRITICAL.Println(STR, "memorystore get: message", mid, "not found") } else { DEBUG.Println(STR, "memorystore get: message", mid, "found") } return m }
go
func (store *MemoryStore) Get(key string) packets.ControlPacket { store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return nil } mid := mIDFromKey(key) m := store.messages[key] if m == nil { CRITICAL.Println(STR, "memorystore get: message", mid, "not found") } else { DEBUG.Println(STR, "memorystore get: message", mid, "found") } return m }
[ "func", "(", "store", "*", "MemoryStore", ")", "Get", "(", "key", "string", ")", "packets", ".", "ControlPacket", "{", "store", ".", "RLock", "(", ")", "\n", "defer", "store", ".", "RUnlock", "(", ")", "\n", "if", "!", "store", ".", "opened", "{", "ERROR", ".", "Println", "(", "STR", ",", "\"Trying to use memory store, but not open\"", ")", "\n", "return", "nil", "\n", "}", "\n", "mid", ":=", "mIDFromKey", "(", "key", ")", "\n", "m", ":=", "store", ".", "messages", "[", "key", "]", "\n", "if", "m", "==", "nil", "{", "CRITICAL", ".", "Println", "(", "STR", ",", "\"memorystore get: message\"", ",", "mid", ",", "\"not found\"", ")", "\n", "}", "else", "{", "DEBUG", ".", "Println", "(", "STR", ",", "\"memorystore get: message\"", ",", "mid", ",", "\"found\"", ")", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Get takes a key and looks in the store for a matching Message // returning either the Message pointer or nil.
[ "Get", "takes", "a", "key", "and", "looks", "in", "the", "store", "for", "a", "matching", "Message", "returning", "either", "the", "Message", "pointer", "or", "nil", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L65-L80
train
eclipse/paho.mqtt.golang
memstore.go
Del
func (store *MemoryStore) Del(key string) { store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return } mid := mIDFromKey(key) m := store.messages[key] if m == nil { WARN.Println(STR, "memorystore del: message", mid, "not found") } else { delete(store.messages, key) DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") } }
go
func (store *MemoryStore) Del(key string) { store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return } mid := mIDFromKey(key) m := store.messages[key] if m == nil { WARN.Println(STR, "memorystore del: message", mid, "not found") } else { delete(store.messages, key) DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") } }
[ "func", "(", "store", "*", "MemoryStore", ")", "Del", "(", "key", "string", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "if", "!", "store", ".", "opened", "{", "ERROR", ".", "Println", "(", "STR", ",", "\"Trying to use memory store, but not open\"", ")", "\n", "return", "\n", "}", "\n", "mid", ":=", "mIDFromKey", "(", "key", ")", "\n", "m", ":=", "store", ".", "messages", "[", "key", "]", "\n", "if", "m", "==", "nil", "{", "WARN", ".", "Println", "(", "STR", ",", "\"memorystore del: message\"", ",", "mid", ",", "\"not found\"", ")", "\n", "}", "else", "{", "delete", "(", "store", ".", "messages", ",", "key", ")", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "\"memorystore del: message\"", ",", "mid", ",", "\"was deleted\"", ")", "\n", "}", "\n", "}" ]
// Del takes a key, searches the MemoryStore and if the key is found // deletes the Message pointer associated with it.
[ "Del", "takes", "a", "key", "searches", "the", "MemoryStore", "and", "if", "the", "key", "is", "found", "deletes", "the", "Message", "pointer", "associated", "with", "it", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L100-L115
train
eclipse/paho.mqtt.golang
client.go
AddRoute
func (c *client) AddRoute(topic string, callback MessageHandler) { if callback != nil { c.msgRouter.addRoute(topic, callback) } }
go
func (c *client) AddRoute(topic string, callback MessageHandler) { if callback != nil { c.msgRouter.addRoute(topic, callback) } }
[ "func", "(", "c", "*", "client", ")", "AddRoute", "(", "topic", "string", ",", "callback", "MessageHandler", ")", "{", "if", "callback", "!=", "nil", "{", "c", ".", "msgRouter", ".", "addRoute", "(", "topic", ",", "callback", ")", "\n", "}", "\n", "}" ]
// AddRoute allows you to add a handler for messages on a specific topic // without making a subscription. For example having a different handler // for parts of a wildcard subscription
[ "AddRoute", "allows", "you", "to", "add", "a", "handler", "for", "messages", "on", "a", "specific", "topic", "without", "making", "a", "subscription", ".", "For", "example", "having", "a", "different", "handler", "for", "parts", "of", "a", "wildcard", "subscription" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L152-L156
train
eclipse/paho.mqtt.golang
client.go
IsConnectionOpen
func (c *client) IsConnectionOpen() bool { c.RLock() defer c.RUnlock() status := atomic.LoadUint32(&c.status) switch { case status == connected: return true default: return false } }
go
func (c *client) IsConnectionOpen() bool { c.RLock() defer c.RUnlock() status := atomic.LoadUint32(&c.status) switch { case status == connected: return true default: return false } }
[ "func", "(", "c", "*", "client", ")", "IsConnectionOpen", "(", ")", "bool", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n", "status", ":=", "atomic", ".", "LoadUint32", "(", "&", "c", ".", "status", ")", "\n", "switch", "{", "case", "status", "==", "connected", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsConnectionOpen return a bool signifying whether the client has an active // connection to mqtt broker, i.e not in disconnected or reconnect mode
[ "IsConnectionOpen", "return", "a", "bool", "signifying", "whether", "the", "client", "has", "an", "active", "connection", "to", "mqtt", "broker", "i", ".", "e", "not", "in", "disconnected", "or", "reconnect", "mode" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L176-L186
train
eclipse/paho.mqtt.golang
client.go
Publish
func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token { token := newToken(packets.Publish).(*PublishToken) DEBUG.Println(CLI, "enter Publish") switch { case !c.IsConnected(): token.setError(ErrNotConnected) return token case c.connectionStatus() == reconnecting && qos == 0: token.flowComplete() return token } pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) pub.Qos = qos pub.TopicName = topic pub.Retain = retained switch payload.(type) { case string: pub.Payload = []byte(payload.(string)) case []byte: pub.Payload = payload.([]byte) default: token.setError(fmt.Errorf("Unknown payload type")) return token } if pub.Qos != 0 && pub.MessageID == 0 { pub.MessageID = c.getID(token) token.messageID = pub.MessageID } persistOutbound(c.persist, pub) if c.connectionStatus() == reconnecting { DEBUG.Println(CLI, "storing publish message (reconnecting), topic:", topic) } else { DEBUG.Println(CLI, "sending publish message, topic:", topic) c.obound <- &PacketAndToken{p: pub, t: token} } return token }
go
func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token { token := newToken(packets.Publish).(*PublishToken) DEBUG.Println(CLI, "enter Publish") switch { case !c.IsConnected(): token.setError(ErrNotConnected) return token case c.connectionStatus() == reconnecting && qos == 0: token.flowComplete() return token } pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) pub.Qos = qos pub.TopicName = topic pub.Retain = retained switch payload.(type) { case string: pub.Payload = []byte(payload.(string)) case []byte: pub.Payload = payload.([]byte) default: token.setError(fmt.Errorf("Unknown payload type")) return token } if pub.Qos != 0 && pub.MessageID == 0 { pub.MessageID = c.getID(token) token.messageID = pub.MessageID } persistOutbound(c.persist, pub) if c.connectionStatus() == reconnecting { DEBUG.Println(CLI, "storing publish message (reconnecting), topic:", topic) } else { DEBUG.Println(CLI, "sending publish message, topic:", topic) c.obound <- &PacketAndToken{p: pub, t: token} } return token }
[ "func", "(", "c", "*", "client", ")", "Publish", "(", "topic", "string", ",", "qos", "byte", ",", "retained", "bool", ",", "payload", "interface", "{", "}", ")", "Token", "{", "token", ":=", "newToken", "(", "packets", ".", "Publish", ")", ".", "(", "*", "PublishToken", ")", "\n", "DEBUG", ".", "Println", "(", "CLI", ",", "\"enter Publish\"", ")", "\n", "switch", "{", "case", "!", "c", ".", "IsConnected", "(", ")", ":", "token", ".", "setError", "(", "ErrNotConnected", ")", "\n", "return", "token", "\n", "case", "c", ".", "connectionStatus", "(", ")", "==", "reconnecting", "&&", "qos", "==", "0", ":", "token", ".", "flowComplete", "(", ")", "\n", "return", "token", "\n", "}", "\n", "pub", ":=", "packets", ".", "NewControlPacket", "(", "packets", ".", "Publish", ")", ".", "(", "*", "packets", ".", "PublishPacket", ")", "\n", "pub", ".", "Qos", "=", "qos", "\n", "pub", ".", "TopicName", "=", "topic", "\n", "pub", ".", "Retain", "=", "retained", "\n", "switch", "payload", ".", "(", "type", ")", "{", "case", "string", ":", "pub", ".", "Payload", "=", "[", "]", "byte", "(", "payload", ".", "(", "string", ")", ")", "\n", "case", "[", "]", "byte", ":", "pub", ".", "Payload", "=", "payload", ".", "(", "[", "]", "byte", ")", "\n", "default", ":", "token", ".", "setError", "(", "fmt", ".", "Errorf", "(", "\"Unknown payload type\"", ")", ")", "\n", "return", "token", "\n", "}", "\n", "if", "pub", ".", "Qos", "!=", "0", "&&", "pub", ".", "MessageID", "==", "0", "{", "pub", ".", "MessageID", "=", "c", ".", "getID", "(", "token", ")", "\n", "token", ".", "messageID", "=", "pub", ".", "MessageID", "\n", "}", "\n", "persistOutbound", "(", "c", ".", "persist", ",", "pub", ")", "\n", "if", "c", ".", "connectionStatus", "(", ")", "==", "reconnecting", "{", "DEBUG", ".", "Println", "(", "CLI", ",", "\"storing publish message (reconnecting), topic:\"", ",", "topic", ")", "\n", "}", "else", "{", "DEBUG", ".", "Println", "(", "CLI", ",", "\"sending publish message, topic:\"", ",", "topic", ")", "\n", "c", ".", "obound", "<-", "&", "PacketAndToken", "{", "p", ":", "pub", ",", "t", ":", "token", "}", "\n", "}", "\n", "return", "token", "\n", "}" ]
// Publish will publish a message with the specified QoS and content // to the specified topic. // Returns a token to track delivery of the message to the broker
[ "Publish", "will", "publish", "a", "message", "with", "the", "specified", "QoS", "and", "content", "to", "the", "specified", "topic", ".", "Returns", "a", "token", "to", "track", "delivery", "of", "the", "message", "to", "the", "broker" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L568-L605
train
eclipse/paho.mqtt.golang
client.go
resume
func (c *client) resume(subscription bool) { storedKeys := c.persist.All() for _, key := range storedKeys { packet := c.persist.Get(key) if packet == nil { continue } details := packet.Details() if isKeyOutbound(key) { switch packet.(type) { case *packets.SubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending subscribe (%d)", details.MessageID)) token := newToken(packets.Subscribe).(*SubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.UnsubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending unsubscribe (%d)", details.MessageID)) token := newToken(packets.Unsubscribe).(*UnsubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.PubrelPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending pubrel (%d)", details.MessageID)) select { case c.oboundP <- &PacketAndToken{p: packet, t: nil}: case <-c.stop: } case *packets.PublishPacket: token := newToken(packets.Publish).(*PublishToken) token.messageID = details.MessageID c.claimID(token, details.MessageID) DEBUG.Println(STR, fmt.Sprintf("loaded pending publish (%d)", details.MessageID)) DEBUG.Println(STR, details) c.obound <- &PacketAndToken{p: packet, t: token} default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } else { switch packet.(type) { case *packets.PubrelPacket, *packets.PublishPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending incomming (%d)", details.MessageID)) select { case c.ibound <- packet: case <-c.stop: } default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } } }
go
func (c *client) resume(subscription bool) { storedKeys := c.persist.All() for _, key := range storedKeys { packet := c.persist.Get(key) if packet == nil { continue } details := packet.Details() if isKeyOutbound(key) { switch packet.(type) { case *packets.SubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending subscribe (%d)", details.MessageID)) token := newToken(packets.Subscribe).(*SubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.UnsubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending unsubscribe (%d)", details.MessageID)) token := newToken(packets.Unsubscribe).(*UnsubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.PubrelPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending pubrel (%d)", details.MessageID)) select { case c.oboundP <- &PacketAndToken{p: packet, t: nil}: case <-c.stop: } case *packets.PublishPacket: token := newToken(packets.Publish).(*PublishToken) token.messageID = details.MessageID c.claimID(token, details.MessageID) DEBUG.Println(STR, fmt.Sprintf("loaded pending publish (%d)", details.MessageID)) DEBUG.Println(STR, details) c.obound <- &PacketAndToken{p: packet, t: token} default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } else { switch packet.(type) { case *packets.PubrelPacket, *packets.PublishPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending incomming (%d)", details.MessageID)) select { case c.ibound <- packet: case <-c.stop: } default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } } }
[ "func", "(", "c", "*", "client", ")", "resume", "(", "subscription", "bool", ")", "{", "storedKeys", ":=", "c", ".", "persist", ".", "All", "(", ")", "\n", "for", "_", ",", "key", ":=", "range", "storedKeys", "{", "packet", ":=", "c", ".", "persist", ".", "Get", "(", "key", ")", "\n", "if", "packet", "==", "nil", "{", "continue", "\n", "}", "\n", "details", ":=", "packet", ".", "Details", "(", ")", "\n", "if", "isKeyOutbound", "(", "key", ")", "{", "switch", "packet", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "SubscribePacket", ":", "if", "subscription", "{", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"loaded pending subscribe (%d)\"", ",", "details", ".", "MessageID", ")", ")", "\n", "token", ":=", "newToken", "(", "packets", ".", "Subscribe", ")", ".", "(", "*", "SubscribeToken", ")", "\n", "c", ".", "oboundP", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "token", "}", "\n", "}", "\n", "case", "*", "packets", ".", "UnsubscribePacket", ":", "if", "subscription", "{", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"loaded pending unsubscribe (%d)\"", ",", "details", ".", "MessageID", ")", ")", "\n", "token", ":=", "newToken", "(", "packets", ".", "Unsubscribe", ")", ".", "(", "*", "UnsubscribeToken", ")", "\n", "c", ".", "oboundP", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "token", "}", "\n", "}", "\n", "case", "*", "packets", ".", "PubrelPacket", ":", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"loaded pending pubrel (%d)\"", ",", "details", ".", "MessageID", ")", ")", "\n", "select", "{", "case", "c", ".", "oboundP", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "nil", "}", ":", "case", "<-", "c", ".", "stop", ":", "}", "\n", "case", "*", "packets", ".", "PublishPacket", ":", "token", ":=", "newToken", "(", "packets", ".", "Publish", ")", ".", "(", "*", "PublishToken", ")", "\n", "token", ".", "messageID", "=", "details", ".", "MessageID", "\n", "c", ".", "claimID", "(", "token", ",", "details", ".", "MessageID", ")", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"loaded pending publish (%d)\"", ",", "details", ".", "MessageID", ")", ")", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "details", ")", "\n", "c", ".", "obound", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "token", "}", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"invalid message type in store (discarded)\"", ")", "\n", "c", ".", "persist", ".", "Del", "(", "key", ")", "\n", "}", "\n", "}", "else", "{", "switch", "packet", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PubrelPacket", ",", "*", "packets", ".", "PublishPacket", ":", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"loaded pending incomming (%d)\"", ",", "details", ".", "MessageID", ")", ")", "\n", "select", "{", "case", "c", ".", "ibound", "<-", "packet", ":", "case", "<-", "c", ".", "stop", ":", "}", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"invalid message type in store (discarded)\"", ")", "\n", "c", ".", "persist", ".", "Del", "(", "key", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Load all stored messages and resend them // Call this to ensure QOS > 1,2 even after an application crash
[ "Load", "all", "stored", "messages", "and", "resend", "them", "Call", "this", "to", "ensure", "QOS", ">", "1", "2", "even", "after", "an", "application", "crash" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L669-L723
train
eclipse/paho.mqtt.golang
client.go
OptionsReader
func (c *client) OptionsReader() ClientOptionsReader { r := ClientOptionsReader{options: &c.options} return r }
go
func (c *client) OptionsReader() ClientOptionsReader { r := ClientOptionsReader{options: &c.options} return r }
[ "func", "(", "c", "*", "client", ")", "OptionsReader", "(", ")", "ClientOptionsReader", "{", "r", ":=", "ClientOptionsReader", "{", "options", ":", "&", "c", ".", "options", "}", "\n", "return", "r", "\n", "}" ]
// OptionsReader returns a ClientOptionsReader which is a copy of the clientoptions // in use by the client.
[ "OptionsReader", "returns", "a", "ClientOptionsReader", "which", "is", "a", "copy", "of", "the", "clientoptions", "in", "use", "by", "the", "client", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L750-L753
train
eclipse/paho.mqtt.golang
packets/publish.go
Copy
func (p *PublishPacket) Copy() *PublishPacket { newP := NewControlPacket(Publish).(*PublishPacket) newP.TopicName = p.TopicName newP.Payload = p.Payload return newP }
go
func (p *PublishPacket) Copy() *PublishPacket { newP := NewControlPacket(Publish).(*PublishPacket) newP.TopicName = p.TopicName newP.Payload = p.Payload return newP }
[ "func", "(", "p", "*", "PublishPacket", ")", "Copy", "(", ")", "*", "PublishPacket", "{", "newP", ":=", "NewControlPacket", "(", "Publish", ")", ".", "(", "*", "PublishPacket", ")", "\n", "newP", ".", "TopicName", "=", "p", ".", "TopicName", "\n", "newP", ".", "Payload", "=", "p", ".", "Payload", "\n", "return", "newP", "\n", "}" ]
//Copy creates a new PublishPacket with the same topic and payload //but an empty fixed header, useful for when you want to deliver //a message with different properties such as Qos but the same //content
[ "Copy", "creates", "a", "new", "PublishPacket", "with", "the", "same", "topic", "and", "payload", "but", "an", "empty", "fixed", "header", "useful", "for", "when", "you", "want", "to", "deliver", "a", "message", "with", "different", "properties", "such", "as", "Qos", "but", "the", "same", "content" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/publish.go#L76-L82
train
eclipse/paho.mqtt.golang
filestore.go
NewFileStore
func NewFileStore(directory string) *FileStore { store := &FileStore{ directory: directory, opened: false, } return store }
go
func NewFileStore(directory string) *FileStore { store := &FileStore{ directory: directory, opened: false, } return store }
[ "func", "NewFileStore", "(", "directory", "string", ")", "*", "FileStore", "{", "store", ":=", "&", "FileStore", "{", "directory", ":", "directory", ",", "opened", ":", "false", ",", "}", "\n", "return", "store", "\n", "}" ]
// NewFileStore will create a new FileStore which stores its messages in the // directory provided.
[ "NewFileStore", "will", "create", "a", "new", "FileStore", "which", "stores", "its", "messages", "in", "the", "directory", "provided", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L46-L52
train
eclipse/paho.mqtt.golang
filestore.go
Open
func (store *FileStore) Open() { store.Lock() defer store.Unlock() // if no store directory was specified in ClientOpts, by default use the // current working directory if store.directory == "" { store.directory, _ = os.Getwd() } // if store dir exists, great, otherwise, create it if !exists(store.directory) { perms := os.FileMode(0770) merr := os.MkdirAll(store.directory, perms) chkerr(merr) } store.opened = true DEBUG.Println(STR, "store is opened at", store.directory) }
go
func (store *FileStore) Open() { store.Lock() defer store.Unlock() // if no store directory was specified in ClientOpts, by default use the // current working directory if store.directory == "" { store.directory, _ = os.Getwd() } // if store dir exists, great, otherwise, create it if !exists(store.directory) { perms := os.FileMode(0770) merr := os.MkdirAll(store.directory, perms) chkerr(merr) } store.opened = true DEBUG.Println(STR, "store is opened at", store.directory) }
[ "func", "(", "store", "*", "FileStore", ")", "Open", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "if", "store", ".", "directory", "==", "\"\"", "{", "store", ".", "directory", ",", "_", "=", "os", ".", "Getwd", "(", ")", "\n", "}", "\n", "if", "!", "exists", "(", "store", ".", "directory", ")", "{", "perms", ":=", "os", ".", "FileMode", "(", "0770", ")", "\n", "merr", ":=", "os", ".", "MkdirAll", "(", "store", ".", "directory", ",", "perms", ")", "\n", "chkerr", "(", "merr", ")", "\n", "}", "\n", "store", ".", "opened", "=", "true", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "\"store is opened at\"", ",", "store", ".", "directory", ")", "\n", "}" ]
// Open will allow the FileStore to be used.
[ "Open", "will", "allow", "the", "FileStore", "to", "be", "used", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L55-L72
train
eclipse/paho.mqtt.golang
filestore.go
All
func (store *FileStore) All() []string { store.RLock() defer store.RUnlock() return store.all() }
go
func (store *FileStore) All() []string { store.RLock() defer store.RUnlock() return store.all() }
[ "func", "(", "store", "*", "FileStore", ")", "All", "(", ")", "[", "]", "string", "{", "store", ".", "RLock", "(", ")", "\n", "defer", "store", ".", "RUnlock", "(", ")", "\n", "return", "store", ".", "all", "(", ")", "\n", "}" ]
// All will provide a list of all of the keys associated with messages // currenly residing in the FileStore.
[ "All", "will", "provide", "a", "list", "of", "all", "of", "the", "keys", "associated", "with", "messages", "currenly", "residing", "in", "the", "FileStore", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L128-L132
train
eclipse/paho.mqtt.golang
filestore.go
Del
func (store *FileStore) Del(key string) { store.Lock() defer store.Unlock() store.del(key) }
go
func (store *FileStore) Del(key string) { store.Lock() defer store.Unlock() store.del(key) }
[ "func", "(", "store", "*", "FileStore", ")", "Del", "(", "key", "string", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "store", ".", "del", "(", "key", ")", "\n", "}" ]
// Del will remove the persisted message associated with the provided // key from the FileStore.
[ "Del", "will", "remove", "the", "persisted", "message", "associated", "with", "the", "provided", "key", "from", "the", "FileStore", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L136-L140
train
eclipse/paho.mqtt.golang
filestore.go
Reset
func (store *FileStore) Reset() { store.Lock() defer store.Unlock() WARN.Println(STR, "FileStore Reset") for _, key := range store.all() { store.del(key) } }
go
func (store *FileStore) Reset() { store.Lock() defer store.Unlock() WARN.Println(STR, "FileStore Reset") for _, key := range store.all() { store.del(key) } }
[ "func", "(", "store", "*", "FileStore", ")", "Reset", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "WARN", ".", "Println", "(", "STR", ",", "\"FileStore Reset\"", ")", "\n", "for", "_", ",", "key", ":=", "range", "store", ".", "all", "(", ")", "{", "store", ".", "del", "(", "key", ")", "\n", "}", "\n", "}" ]
// Reset will remove all persisted messages from the FileStore.
[ "Reset", "will", "remove", "all", "persisted", "messages", "from", "the", "FileStore", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L143-L150
train
eclipse/paho.mqtt.golang
router.go
newRouter
func newRouter() (*router, chan bool) { router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)} stop := router.stop return router, stop }
go
func newRouter() (*router, chan bool) { router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)} stop := router.stop return router, stop }
[ "func", "newRouter", "(", ")", "(", "*", "router", ",", "chan", "bool", ")", "{", "router", ":=", "&", "router", "{", "routes", ":", "list", ".", "New", "(", ")", ",", "messages", ":", "make", "(", "chan", "*", "packets", ".", "PublishPacket", ")", ",", "stop", ":", "make", "(", "chan", "bool", ")", "}", "\n", "stop", ":=", "router", ".", "stop", "\n", "return", "router", ",", "stop", "\n", "}" ]
// newRouter returns a new instance of a Router and channel which can be used to tell the Router // to stop
[ "newRouter", "returns", "a", "new", "instance", "of", "a", "Router", "and", "channel", "which", "can", "be", "used", "to", "tell", "the", "Router", "to", "stop" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L95-L99
train
eclipse/paho.mqtt.golang
router.go
addRoute
func (r *router) addRoute(topic string, callback MessageHandler) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r := e.Value.(*route) r.callback = callback return } } r.routes.PushBack(&route{topic: topic, callback: callback}) }
go
func (r *router) addRoute(topic string, callback MessageHandler) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r := e.Value.(*route) r.callback = callback return } } r.routes.PushBack(&route{topic: topic, callback: callback}) }
[ "func", "(", "r", "*", "router", ")", "addRoute", "(", "topic", "string", ",", "callback", "MessageHandler", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "for", "e", ":=", "r", ".", "routes", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "if", "e", ".", "Value", ".", "(", "*", "route", ")", ".", "match", "(", "topic", ")", "{", "r", ":=", "e", ".", "Value", ".", "(", "*", "route", ")", "\n", "r", ".", "callback", "=", "callback", "\n", "return", "\n", "}", "\n", "}", "\n", "r", ".", "routes", ".", "PushBack", "(", "&", "route", "{", "topic", ":", "topic", ",", "callback", ":", "callback", "}", ")", "\n", "}" ]
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of // routes to see if there is already a matching Route. If there is it replaces the current // callback with the new one. If not it add a new entry to the list of Routes.
[ "addRoute", "takes", "a", "topic", "string", "and", "MessageHandler", "callback", ".", "It", "looks", "in", "the", "current", "list", "of", "routes", "to", "see", "if", "there", "is", "already", "a", "matching", "Route", ".", "If", "there", "is", "it", "replaces", "the", "current", "callback", "with", "the", "new", "one", ".", "If", "not", "it", "add", "a", "new", "entry", "to", "the", "list", "of", "Routes", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L104-L115
train
eclipse/paho.mqtt.golang
router.go
deleteRoute
func (r *router) deleteRoute(topic string) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r.routes.Remove(e) return } } }
go
func (r *router) deleteRoute(topic string) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r.routes.Remove(e) return } } }
[ "func", "(", "r", "*", "router", ")", "deleteRoute", "(", "topic", "string", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "for", "e", ":=", "r", ".", "routes", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "if", "e", ".", "Value", ".", "(", "*", "route", ")", ".", "match", "(", "topic", ")", "{", "r", ".", "routes", ".", "Remove", "(", "e", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// deleteRoute takes a route string, looks for a matching Route in the list of Routes. If // found it removes the Route from the list.
[ "deleteRoute", "takes", "a", "route", "string", "looks", "for", "a", "matching", "Route", "in", "the", "list", "of", "Routes", ".", "If", "found", "it", "removes", "the", "Route", "from", "the", "list", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L119-L128
train
eclipse/paho.mqtt.golang
router.go
setDefaultHandler
func (r *router) setDefaultHandler(handler MessageHandler) { r.Lock() defer r.Unlock() r.defaultHandler = handler }
go
func (r *router) setDefaultHandler(handler MessageHandler) { r.Lock() defer r.Unlock() r.defaultHandler = handler }
[ "func", "(", "r", "*", "router", ")", "setDefaultHandler", "(", "handler", "MessageHandler", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "r", ".", "defaultHandler", "=", "handler", "\n", "}" ]
// setDefaultHandler assigns a default callback that will be called if no matching Route // is found for an incoming Publish.
[ "setDefaultHandler", "assigns", "a", "default", "callback", "that", "will", "be", "called", "if", "no", "matching", "Route", "is", "found", "for", "an", "incoming", "Publish", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L132-L136
train
nats-io/go-nats
enc.go
NewEncodedConn
func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { if c == nil { return nil, errors.New("nats: Nil Connection") } if c.IsClosed() { return nil, ErrConnectionClosed } ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} if ec.Enc == nil { return nil, fmt.Errorf("no encoder registered for '%s'", encType) } return ec, nil }
go
func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { if c == nil { return nil, errors.New("nats: Nil Connection") } if c.IsClosed() { return nil, ErrConnectionClosed } ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} if ec.Enc == nil { return nil, fmt.Errorf("no encoder registered for '%s'", encType) } return ec, nil }
[ "func", "NewEncodedConn", "(", "c", "*", "Conn", ",", "encType", "string", ")", "(", "*", "EncodedConn", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"nats: Nil Connection\"", ")", "\n", "}", "\n", "if", "c", ".", "IsClosed", "(", ")", "{", "return", "nil", ",", "ErrConnectionClosed", "\n", "}", "\n", "ec", ":=", "&", "EncodedConn", "{", "Conn", ":", "c", ",", "Enc", ":", "EncoderForType", "(", "encType", ")", "}", "\n", "if", "ec", ".", "Enc", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"no encoder registered for '%s'\"", ",", "encType", ")", "\n", "}", "\n", "return", "ec", ",", "nil", "\n", "}" ]
// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered // encoder.
[ "NewEncodedConn", "will", "wrap", "an", "existing", "Connection", "and", "utilize", "the", "appropriate", "registered", "encoder", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L61-L73
train
nats-io/go-nats
enc.go
RegisterEncoder
func RegisterEncoder(encType string, enc Encoder) { encLock.Lock() defer encLock.Unlock() encMap[encType] = enc }
go
func RegisterEncoder(encType string, enc Encoder) { encLock.Lock() defer encLock.Unlock() encMap[encType] = enc }
[ "func", "RegisterEncoder", "(", "encType", "string", ",", "enc", "Encoder", ")", "{", "encLock", ".", "Lock", "(", ")", "\n", "defer", "encLock", ".", "Unlock", "(", ")", "\n", "encMap", "[", "encType", "]", "=", "enc", "\n", "}" ]
// RegisterEncoder will register the encType with the given Encoder. Useful for customization.
[ "RegisterEncoder", "will", "register", "the", "encType", "with", "the", "given", "Encoder", ".", "Useful", "for", "customization", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L76-L80
train
nats-io/go-nats
enc.go
EncoderForType
func EncoderForType(encType string) Encoder { encLock.Lock() defer encLock.Unlock() return encMap[encType] }
go
func EncoderForType(encType string) Encoder { encLock.Lock() defer encLock.Unlock() return encMap[encType] }
[ "func", "EncoderForType", "(", "encType", "string", ")", "Encoder", "{", "encLock", ".", "Lock", "(", ")", "\n", "defer", "encLock", ".", "Unlock", "(", ")", "\n", "return", "encMap", "[", "encType", "]", "\n", "}" ]
// EncoderForType will return the registered Encoder for the encType.
[ "EncoderForType", "will", "return", "the", "registered", "Encoder", "for", "the", "encType", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L83-L87
train
nats-io/go-nats
enc.go
Publish
func (c *EncodedConn) Publish(subject string, v interface{}) error { b, err := c.Enc.Encode(subject, v) if err != nil { return err } return c.Conn.publish(subject, _EMPTY_, b) }
go
func (c *EncodedConn) Publish(subject string, v interface{}) error { b, err := c.Enc.Encode(subject, v) if err != nil { return err } return c.Conn.publish(subject, _EMPTY_, b) }
[ "func", "(", "c", "*", "EncodedConn", ")", "Publish", "(", "subject", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "c", ".", "Enc", ".", "Encode", "(", "subject", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "Conn", ".", "publish", "(", "subject", ",", "_EMPTY_", ",", "b", ")", "\n", "}" ]
// Publish publishes the data argument to the given subject. The data argument // will be encoded using the associated encoder.
[ "Publish", "publishes", "the", "data", "argument", "to", "the", "given", "subject", ".", "The", "data", "argument", "will", "be", "encoded", "using", "the", "associated", "encoder", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L91-L97
train
nats-io/go-nats
enc.go
argInfo
func argInfo(cb Handler) (reflect.Type, int) { cbType := reflect.TypeOf(cb) if cbType.Kind() != reflect.Func { panic("nats: Handler needs to be a func") } numArgs := cbType.NumIn() if numArgs == 0 { return nil, numArgs } return cbType.In(numArgs - 1), numArgs }
go
func argInfo(cb Handler) (reflect.Type, int) { cbType := reflect.TypeOf(cb) if cbType.Kind() != reflect.Func { panic("nats: Handler needs to be a func") } numArgs := cbType.NumIn() if numArgs == 0 { return nil, numArgs } return cbType.In(numArgs - 1), numArgs }
[ "func", "argInfo", "(", "cb", "Handler", ")", "(", "reflect", ".", "Type", ",", "int", ")", "{", "cbType", ":=", "reflect", ".", "TypeOf", "(", "cb", ")", "\n", "if", "cbType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "panic", "(", "\"nats: Handler needs to be a func\"", ")", "\n", "}", "\n", "numArgs", ":=", "cbType", ".", "NumIn", "(", ")", "\n", "if", "numArgs", "==", "0", "{", "return", "nil", ",", "numArgs", "\n", "}", "\n", "return", "cbType", ".", "In", "(", "numArgs", "-", "1", ")", ",", "numArgs", "\n", "}" ]
// Dissect the cb Handler's signature
[ "Dissect", "the", "cb", "Handler", "s", "signature" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L156-L166
train
nats-io/go-nats
enc.go
Subscribe
func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { return c.subscribe(subject, _EMPTY_, cb) }
go
func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { return c.subscribe(subject, _EMPTY_, cb) }
[ "func", "(", "c", "*", "EncodedConn", ")", "Subscribe", "(", "subject", "string", ",", "cb", "Handler", ")", "(", "*", "Subscription", ",", "error", ")", "{", "return", "c", ".", "subscribe", "(", "subject", ",", "_EMPTY_", ",", "cb", ")", "\n", "}" ]
// Subscribe will create a subscription on the given subject and process incoming // messages using the specified Handler. The Handler should be a func that matches // a signature from the description of Handler from above.
[ "Subscribe", "will", "create", "a", "subscription", "on", "the", "given", "subject", "and", "process", "incoming", "messages", "using", "the", "specified", "Handler", ".", "The", "Handler", "should", "be", "a", "func", "that", "matches", "a", "signature", "from", "the", "description", "of", "Handler", "from", "above", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L173-L175
train
nats-io/go-nats
enc.go
QueueSubscribe
func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { return c.subscribe(subject, queue, cb) }
go
func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { return c.subscribe(subject, queue, cb) }
[ "func", "(", "c", "*", "EncodedConn", ")", "QueueSubscribe", "(", "subject", ",", "queue", "string", ",", "cb", "Handler", ")", "(", "*", "Subscription", ",", "error", ")", "{", "return", "c", ".", "subscribe", "(", "subject", ",", "queue", ",", "cb", ")", "\n", "}" ]
// QueueSubscribe will create a queue subscription on the given subject and process // incoming messages using the specified Handler. The Handler should be a func that // matches a signature from the description of Handler from above.
[ "QueueSubscribe", "will", "create", "a", "queue", "subscription", "on", "the", "given", "subject", "and", "process", "incoming", "messages", "using", "the", "specified", "Handler", ".", "The", "Handler", "should", "be", "a", "func", "that", "matches", "a", "signature", "from", "the", "description", "of", "Handler", "from", "above", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L180-L182
train
nats-io/go-nats
enc.go
subscribe
func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { if cb == nil { return nil, errors.New("nats: Handler required for EncodedConn Subscription") } argType, numArgs := argInfo(cb) if argType == nil { return nil, errors.New("nats: Handler requires at least one argument") } cbValue := reflect.ValueOf(cb) wantsRaw := (argType == emptyMsgType) natsCB := func(m *Msg) { var oV []reflect.Value if wantsRaw { oV = []reflect.Value{reflect.ValueOf(m)} } else { var oPtr reflect.Value if argType.Kind() != reflect.Ptr { oPtr = reflect.New(argType) } else { oPtr = reflect.New(argType.Elem()) } if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { if c.Conn.Opts.AsyncErrorCB != nil { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) }) } return } if argType.Kind() != reflect.Ptr { oPtr = reflect.Indirect(oPtr) } // Callback Arity switch numArgs { case 1: oV = []reflect.Value{oPtr} case 2: subV := reflect.ValueOf(m.Subject) oV = []reflect.Value{subV, oPtr} case 3: subV := reflect.ValueOf(m.Subject) replyV := reflect.ValueOf(m.Reply) oV = []reflect.Value{subV, replyV, oPtr} } } cbValue.Call(oV) } return c.Conn.subscribe(subject, queue, natsCB, nil, false) }
go
func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { if cb == nil { return nil, errors.New("nats: Handler required for EncodedConn Subscription") } argType, numArgs := argInfo(cb) if argType == nil { return nil, errors.New("nats: Handler requires at least one argument") } cbValue := reflect.ValueOf(cb) wantsRaw := (argType == emptyMsgType) natsCB := func(m *Msg) { var oV []reflect.Value if wantsRaw { oV = []reflect.Value{reflect.ValueOf(m)} } else { var oPtr reflect.Value if argType.Kind() != reflect.Ptr { oPtr = reflect.New(argType) } else { oPtr = reflect.New(argType.Elem()) } if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { if c.Conn.Opts.AsyncErrorCB != nil { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) }) } return } if argType.Kind() != reflect.Ptr { oPtr = reflect.Indirect(oPtr) } // Callback Arity switch numArgs { case 1: oV = []reflect.Value{oPtr} case 2: subV := reflect.ValueOf(m.Subject) oV = []reflect.Value{subV, oPtr} case 3: subV := reflect.ValueOf(m.Subject) replyV := reflect.ValueOf(m.Reply) oV = []reflect.Value{subV, replyV, oPtr} } } cbValue.Call(oV) } return c.Conn.subscribe(subject, queue, natsCB, nil, false) }
[ "func", "(", "c", "*", "EncodedConn", ")", "subscribe", "(", "subject", ",", "queue", "string", ",", "cb", "Handler", ")", "(", "*", "Subscription", ",", "error", ")", "{", "if", "cb", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"nats: Handler required for EncodedConn Subscription\"", ")", "\n", "}", "\n", "argType", ",", "numArgs", ":=", "argInfo", "(", "cb", ")", "\n", "if", "argType", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"nats: Handler requires at least one argument\"", ")", "\n", "}", "\n", "cbValue", ":=", "reflect", ".", "ValueOf", "(", "cb", ")", "\n", "wantsRaw", ":=", "(", "argType", "==", "emptyMsgType", ")", "\n", "natsCB", ":=", "func", "(", "m", "*", "Msg", ")", "{", "var", "oV", "[", "]", "reflect", ".", "Value", "\n", "if", "wantsRaw", "{", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "reflect", ".", "ValueOf", "(", "m", ")", "}", "\n", "}", "else", "{", "var", "oPtr", "reflect", ".", "Value", "\n", "if", "argType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "oPtr", "=", "reflect", ".", "New", "(", "argType", ")", "\n", "}", "else", "{", "oPtr", "=", "reflect", ".", "New", "(", "argType", ".", "Elem", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "Enc", ".", "Decode", "(", "m", ".", "Subject", ",", "m", ".", "Data", ",", "oPtr", ".", "Interface", "(", ")", ")", ";", "err", "!=", "nil", "{", "if", "c", ".", "Conn", ".", "Opts", ".", "AsyncErrorCB", "!=", "nil", "{", "c", ".", "Conn", ".", "ach", ".", "push", "(", "func", "(", ")", "{", "c", ".", "Conn", ".", "Opts", ".", "AsyncErrorCB", "(", "c", ".", "Conn", ",", "m", ".", "Sub", ",", "errors", ".", "New", "(", "\"nats: Got an error trying to unmarshal: \"", "+", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "argType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "oPtr", "=", "reflect", ".", "Indirect", "(", "oPtr", ")", "\n", "}", "\n", "switch", "numArgs", "{", "case", "1", ":", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "oPtr", "}", "\n", "case", "2", ":", "subV", ":=", "reflect", ".", "ValueOf", "(", "m", ".", "Subject", ")", "\n", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "subV", ",", "oPtr", "}", "\n", "case", "3", ":", "subV", ":=", "reflect", ".", "ValueOf", "(", "m", ".", "Subject", ")", "\n", "replyV", ":=", "reflect", ".", "ValueOf", "(", "m", ".", "Reply", ")", "\n", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "subV", ",", "replyV", ",", "oPtr", "}", "\n", "}", "\n", "}", "\n", "cbValue", ".", "Call", "(", "oV", ")", "\n", "}", "\n", "return", "c", ".", "Conn", ".", "subscribe", "(", "subject", ",", "queue", ",", "natsCB", ",", "nil", ",", "false", ")", "\n", "}" ]
// Internal implementation that all public functions will use.
[ "Internal", "implementation", "that", "all", "public", "functions", "will", "use", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L185-L238
train
nats-io/go-nats
parser.go
cloneMsgArg
func (nc *Conn) cloneMsgArg() { nc.ps.argBuf = nc.ps.scratch[:0] nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] if nc.ps.ma.reply != nil { nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] } }
go
func (nc *Conn) cloneMsgArg() { nc.ps.argBuf = nc.ps.scratch[:0] nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] if nc.ps.ma.reply != nil { nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] } }
[ "func", "(", "nc", "*", "Conn", ")", "cloneMsgArg", "(", ")", "{", "nc", ".", "ps", ".", "argBuf", "=", "nc", ".", "ps", ".", "scratch", "[", ":", "0", "]", "\n", "nc", ".", "ps", ".", "argBuf", "=", "append", "(", "nc", ".", "ps", ".", "argBuf", ",", "nc", ".", "ps", ".", "ma", ".", "subject", "...", ")", "\n", "nc", ".", "ps", ".", "argBuf", "=", "append", "(", "nc", ".", "ps", ".", "argBuf", ",", "nc", ".", "ps", ".", "ma", ".", "reply", "...", ")", "\n", "nc", ".", "ps", ".", "ma", ".", "subject", "=", "nc", ".", "ps", ".", "argBuf", "[", ":", "len", "(", "nc", ".", "ps", ".", "ma", ".", "subject", ")", "]", "\n", "if", "nc", ".", "ps", ".", "ma", ".", "reply", "!=", "nil", "{", "nc", ".", "ps", ".", "ma", ".", "reply", "=", "nc", ".", "ps", ".", "argBuf", "[", "len", "(", "nc", ".", "ps", ".", "ma", ".", "subject", ")", ":", "]", "\n", "}", "\n", "}" ]
// cloneMsgArg is used when the split buffer scenario has the pubArg in the existing read buffer, but // we need to hold onto it into the next read.
[ "cloneMsgArg", "is", "used", "when", "the", "split", "buffer", "scenario", "has", "the", "pubArg", "in", "the", "existing", "read", "buffer", "but", "we", "need", "to", "hold", "onto", "it", "into", "the", "next", "read", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/parser.go#L405-L413
train
nats-io/go-nats
nats.go
GetDefaultOptions
func GetDefaultOptions() Options { return Options{ AllowReconnect: true, MaxReconnect: DefaultMaxReconnect, ReconnectWait: DefaultReconnectWait, Timeout: DefaultTimeout, PingInterval: DefaultPingInterval, MaxPingsOut: DefaultMaxPingOut, SubChanLen: DefaultMaxChanLen, ReconnectBufSize: DefaultReconnectBufSize, DrainTimeout: DefaultDrainTimeout, } }
go
func GetDefaultOptions() Options { return Options{ AllowReconnect: true, MaxReconnect: DefaultMaxReconnect, ReconnectWait: DefaultReconnectWait, Timeout: DefaultTimeout, PingInterval: DefaultPingInterval, MaxPingsOut: DefaultMaxPingOut, SubChanLen: DefaultMaxChanLen, ReconnectBufSize: DefaultReconnectBufSize, DrainTimeout: DefaultDrainTimeout, } }
[ "func", "GetDefaultOptions", "(", ")", "Options", "{", "return", "Options", "{", "AllowReconnect", ":", "true", ",", "MaxReconnect", ":", "DefaultMaxReconnect", ",", "ReconnectWait", ":", "DefaultReconnectWait", ",", "Timeout", ":", "DefaultTimeout", ",", "PingInterval", ":", "DefaultPingInterval", ",", "MaxPingsOut", ":", "DefaultMaxPingOut", ",", "SubChanLen", ":", "DefaultMaxChanLen", ",", "ReconnectBufSize", ":", "DefaultReconnectBufSize", ",", "DrainTimeout", ":", "DefaultDrainTimeout", ",", "}", "\n", "}" ]
// GetDefaultOptions returns default configuration options for the client.
[ "GetDefaultOptions", "returns", "default", "configuration", "options", "for", "the", "client", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L117-L129
train
nats-io/go-nats
nats.go
Name
func Name(name string) Option { return func(o *Options) error { o.Name = name return nil } }
go
func Name(name string) Option { return func(o *Options) error { o.Name = name return nil } }
[ "func", "Name", "(", "name", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "Name", "=", "name", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Options that can be passed to Connect. // Name is an Option to set the client name.
[ "Options", "that", "can", "be", "passed", "to", "Connect", ".", "Name", "is", "an", "Option", "to", "set", "the", "client", "name", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L531-L536
train
nats-io/go-nats
nats.go
RootCAs
func RootCAs(file ...string) Option { return func(o *Options) error { pool := x509.NewCertPool() for _, f := range file { rootPEM, err := ioutil.ReadFile(f) if err != nil || rootPEM == nil { return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err) } ok := pool.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("nats: failed to parse root certificate from %q", f) } } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.RootCAs = pool o.Secure = true return nil } }
go
func RootCAs(file ...string) Option { return func(o *Options) error { pool := x509.NewCertPool() for _, f := range file { rootPEM, err := ioutil.ReadFile(f) if err != nil || rootPEM == nil { return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err) } ok := pool.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("nats: failed to parse root certificate from %q", f) } } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.RootCAs = pool o.Secure = true return nil } }
[ "func", "RootCAs", "(", "file", "...", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "pool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "for", "_", ",", "f", ":=", "range", "file", "{", "rootPEM", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "f", ")", "\n", "if", "err", "!=", "nil", "||", "rootPEM", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"nats: error loading or parsing rootCA file: %v\"", ",", "err", ")", "\n", "}", "\n", "ok", ":=", "pool", ".", "AppendCertsFromPEM", "(", "rootPEM", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"nats: failed to parse root certificate from %q\"", ",", "f", ")", "\n", "}", "\n", "}", "\n", "if", "o", ".", "TLSConfig", "==", "nil", "{", "o", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "MinVersion", ":", "tls", ".", "VersionTLS12", "}", "\n", "}", "\n", "o", ".", "TLSConfig", ".", "RootCAs", "=", "pool", "\n", "o", ".", "Secure", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// RootCAs is a helper option to provide the RootCAs pool from a list of filenames. // If Secure is not already set this will set it as well.
[ "RootCAs", "is", "a", "helper", "option", "to", "provide", "the", "RootCAs", "pool", "from", "a", "list", "of", "filenames", ".", "If", "Secure", "is", "not", "already", "set", "this", "will", "set", "it", "as", "well", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L557-L577
train
nats-io/go-nats
nats.go
ClientCert
func ClientCert(certFile, keyFile string) Option { return func(o *Options) error { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return fmt.Errorf("nats: error loading client certificate: %v", err) } cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) if err != nil { return fmt.Errorf("nats: error parsing client certificate: %v", err) } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.Certificates = []tls.Certificate{cert} o.Secure = true return nil } }
go
func ClientCert(certFile, keyFile string) Option { return func(o *Options) error { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return fmt.Errorf("nats: error loading client certificate: %v", err) } cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) if err != nil { return fmt.Errorf("nats: error parsing client certificate: %v", err) } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.Certificates = []tls.Certificate{cert} o.Secure = true return nil } }
[ "func", "ClientCert", "(", "certFile", ",", "keyFile", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "certFile", ",", "keyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"nats: error loading client certificate: %v\"", ",", "err", ")", "\n", "}", "\n", "cert", ".", "Leaf", ",", "err", "=", "x509", ".", "ParseCertificate", "(", "cert", ".", "Certificate", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"nats: error parsing client certificate: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "o", ".", "TLSConfig", "==", "nil", "{", "o", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "MinVersion", ":", "tls", ".", "VersionTLS12", "}", "\n", "}", "\n", "o", ".", "TLSConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", "\n", "o", ".", "Secure", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ClientCert is a helper option to provide the client certificate from a file. // If Secure is not already set this will set it as well.
[ "ClientCert", "is", "a", "helper", "option", "to", "provide", "the", "client", "certificate", "from", "a", "file", ".", "If", "Secure", "is", "not", "already", "set", "this", "will", "set", "it", "as", "well", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L581-L598
train
nats-io/go-nats
nats.go
ReconnectWait
func ReconnectWait(t time.Duration) Option { return func(o *Options) error { o.ReconnectWait = t return nil } }
go
func ReconnectWait(t time.Duration) Option { return func(o *Options) error { o.ReconnectWait = t return nil } }
[ "func", "ReconnectWait", "(", "t", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ReconnectWait", "=", "t", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ReconnectWait is an Option to set the wait time between reconnect attempts.
[ "ReconnectWait", "is", "an", "Option", "to", "set", "the", "wait", "time", "between", "reconnect", "attempts", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L626-L631
train
nats-io/go-nats
nats.go
MaxReconnects
func MaxReconnects(max int) Option { return func(o *Options) error { o.MaxReconnect = max return nil } }
go
func MaxReconnects(max int) Option { return func(o *Options) error { o.MaxReconnect = max return nil } }
[ "func", "MaxReconnects", "(", "max", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "MaxReconnect", "=", "max", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MaxReconnects is an Option to set the maximum number of reconnect attempts.
[ "MaxReconnects", "is", "an", "Option", "to", "set", "the", "maximum", "number", "of", "reconnect", "attempts", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L634-L639
train
nats-io/go-nats
nats.go
MaxPingsOutstanding
func MaxPingsOutstanding(max int) Option { return func(o *Options) error { o.MaxPingsOut = max return nil } }
go
func MaxPingsOutstanding(max int) Option { return func(o *Options) error { o.MaxPingsOut = max return nil } }
[ "func", "MaxPingsOutstanding", "(", "max", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "MaxPingsOut", "=", "max", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MaxPingsOutstanding is an Option to set the maximum number of ping requests // that can go un-answered by the server before closing the connection.
[ "MaxPingsOutstanding", "is", "an", "Option", "to", "set", "the", "maximum", "number", "of", "ping", "requests", "that", "can", "go", "un", "-", "answered", "by", "the", "server", "before", "closing", "the", "connection", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L651-L656
train
nats-io/go-nats
nats.go
ReconnectBufSize
func ReconnectBufSize(size int) Option { return func(o *Options) error { o.ReconnectBufSize = size return nil } }
go
func ReconnectBufSize(size int) Option { return func(o *Options) error { o.ReconnectBufSize = size return nil } }
[ "func", "ReconnectBufSize", "(", "size", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ReconnectBufSize", "=", "size", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
[ "ReconnectBufSize", "sets", "the", "buffer", "size", "of", "messages", "kept", "while", "busy", "reconnecting", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L659-L664
train
nats-io/go-nats
nats.go
DisconnectHandler
func DisconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.DisconnectedCB = cb return nil } }
go
func DisconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.DisconnectedCB = cb return nil } }
[ "func", "DisconnectHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "DisconnectedCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DisconnectHandler is an Option to set the disconnected handler.
[ "DisconnectHandler", "is", "an", "Option", "to", "set", "the", "disconnected", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L691-L696
train
nats-io/go-nats
nats.go
ReconnectHandler
func ReconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.ReconnectedCB = cb return nil } }
go
func ReconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.ReconnectedCB = cb return nil } }
[ "func", "ReconnectHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ReconnectedCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ReconnectHandler is an Option to set the reconnected handler.
[ "ReconnectHandler", "is", "an", "Option", "to", "set", "the", "reconnected", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L699-L704
train
nats-io/go-nats
nats.go
ClosedHandler
func ClosedHandler(cb ConnHandler) Option { return func(o *Options) error { o.ClosedCB = cb return nil } }
go
func ClosedHandler(cb ConnHandler) Option { return func(o *Options) error { o.ClosedCB = cb return nil } }
[ "func", "ClosedHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ClosedCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ClosedHandler is an Option to set the closed handler.
[ "ClosedHandler", "is", "an", "Option", "to", "set", "the", "closed", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L707-L712
train
nats-io/go-nats
nats.go
DiscoveredServersHandler
func DiscoveredServersHandler(cb ConnHandler) Option { return func(o *Options) error { o.DiscoveredServersCB = cb return nil } }
go
func DiscoveredServersHandler(cb ConnHandler) Option { return func(o *Options) error { o.DiscoveredServersCB = cb return nil } }
[ "func", "DiscoveredServersHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "DiscoveredServersCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DiscoveredServersHandler is an Option to set the new servers handler.
[ "DiscoveredServersHandler", "is", "an", "Option", "to", "set", "the", "new", "servers", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L715-L720
train
nats-io/go-nats
nats.go
ErrorHandler
func ErrorHandler(cb ErrHandler) Option { return func(o *Options) error { o.AsyncErrorCB = cb return nil } }
go
func ErrorHandler(cb ErrHandler) Option { return func(o *Options) error { o.AsyncErrorCB = cb return nil } }
[ "func", "ErrorHandler", "(", "cb", "ErrHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "AsyncErrorCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ErrorHandler is an Option to set the async error handler.
[ "ErrorHandler", "is", "an", "Option", "to", "set", "the", "async", "error", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L723-L728
train
nats-io/go-nats
nats.go
UserInfo
func UserInfo(user, password string) Option { return func(o *Options) error { o.User = user o.Password = password return nil } }
go
func UserInfo(user, password string) Option { return func(o *Options) error { o.User = user o.Password = password return nil } }
[ "func", "UserInfo", "(", "user", ",", "password", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "User", "=", "user", "\n", "o", ".", "Password", "=", "password", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// UserInfo is an Option to set the username and password to // use when not included directly in the URLs.
[ "UserInfo", "is", "an", "Option", "to", "set", "the", "username", "and", "password", "to", "use", "when", "not", "included", "directly", "in", "the", "URLs", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L732-L738
train
nats-io/go-nats
nats.go
Token
func Token(token string) Option { return func(o *Options) error { if o.TokenHandler != nil { return ErrTokenAlreadySet } o.Token = token return nil } }
go
func Token(token string) Option { return func(o *Options) error { if o.TokenHandler != nil { return ErrTokenAlreadySet } o.Token = token return nil } }
[ "func", "Token", "(", "token", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "if", "o", ".", "TokenHandler", "!=", "nil", "{", "return", "ErrTokenAlreadySet", "\n", "}", "\n", "o", ".", "Token", "=", "token", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Token is an Option to set the token to use // when a token is not included directly in the URLs // and when a token handler is not provided.
[ "Token", "is", "an", "Option", "to", "set", "the", "token", "to", "use", "when", "a", "token", "is", "not", "included", "directly", "in", "the", "URLs", "and", "when", "a", "token", "handler", "is", "not", "provided", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L743-L751
train
nats-io/go-nats
nats.go
TokenHandler
func TokenHandler(cb AuthTokenHandler) Option { return func(o *Options) error { if o.Token != "" { return ErrTokenAlreadySet } o.TokenHandler = cb return nil } }
go
func TokenHandler(cb AuthTokenHandler) Option { return func(o *Options) error { if o.Token != "" { return ErrTokenAlreadySet } o.TokenHandler = cb return nil } }
[ "func", "TokenHandler", "(", "cb", "AuthTokenHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "if", "o", ".", "Token", "!=", "\"\"", "{", "return", "ErrTokenAlreadySet", "\n", "}", "\n", "o", ".", "TokenHandler", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// TokenHandler is an Option to set the token handler to use // when a token is not included directly in the URLs // and when a token is not set.
[ "TokenHandler", "is", "an", "Option", "to", "set", "the", "token", "handler", "to", "use", "when", "a", "token", "is", "not", "included", "directly", "in", "the", "URLs", "and", "when", "a", "token", "is", "not", "set", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L756-L764
train
nats-io/go-nats
nats.go
UserCredentials
func UserCredentials(userOrChainedFile string, seedFiles ...string) Option { userCB := func() (string, error) { return userFromFile(userOrChainedFile) } var keyFile string if len(seedFiles) > 0 { keyFile = seedFiles[0] } else { keyFile = userOrChainedFile } sigCB := func(nonce []byte) ([]byte, error) { return sigHandler(nonce, keyFile) } return UserJWT(userCB, sigCB) }
go
func UserCredentials(userOrChainedFile string, seedFiles ...string) Option { userCB := func() (string, error) { return userFromFile(userOrChainedFile) } var keyFile string if len(seedFiles) > 0 { keyFile = seedFiles[0] } else { keyFile = userOrChainedFile } sigCB := func(nonce []byte) ([]byte, error) { return sigHandler(nonce, keyFile) } return UserJWT(userCB, sigCB) }
[ "func", "UserCredentials", "(", "userOrChainedFile", "string", ",", "seedFiles", "...", "string", ")", "Option", "{", "userCB", ":=", "func", "(", ")", "(", "string", ",", "error", ")", "{", "return", "userFromFile", "(", "userOrChainedFile", ")", "\n", "}", "\n", "var", "keyFile", "string", "\n", "if", "len", "(", "seedFiles", ")", ">", "0", "{", "keyFile", "=", "seedFiles", "[", "0", "]", "\n", "}", "else", "{", "keyFile", "=", "userOrChainedFile", "\n", "}", "\n", "sigCB", ":=", "func", "(", "nonce", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "sigHandler", "(", "nonce", ",", "keyFile", ")", "\n", "}", "\n", "return", "UserJWT", "(", "userCB", ",", "sigCB", ")", "\n", "}" ]
// UserCredentials is a convenience function that takes a filename // for a user's JWT and a filename for the user's private Nkey seed.
[ "UserCredentials", "is", "a", "convenience", "function", "that", "takes", "a", "filename", "for", "a", "user", "s", "JWT", "and", "a", "filename", "for", "the", "user", "s", "private", "Nkey", "seed", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L768-L782
train
nats-io/go-nats
nats.go
UserJWT
func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option { return func(o *Options) error { if userCB == nil { return ErrNoUserCB } if sigCB == nil { return ErrUserButNoSigCB } o.UserJWT = userCB o.SignatureCB = sigCB return nil } }
go
func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option { return func(o *Options) error { if userCB == nil { return ErrNoUserCB } if sigCB == nil { return ErrUserButNoSigCB } o.UserJWT = userCB o.SignatureCB = sigCB return nil } }
[ "func", "UserJWT", "(", "userCB", "UserJWTHandler", ",", "sigCB", "SignatureHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "if", "userCB", "==", "nil", "{", "return", "ErrNoUserCB", "\n", "}", "\n", "if", "sigCB", "==", "nil", "{", "return", "ErrUserButNoSigCB", "\n", "}", "\n", "o", ".", "UserJWT", "=", "userCB", "\n", "o", ".", "SignatureCB", "=", "sigCB", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// UserJWT will set the callbacks to retrieve the user's JWT and // the signature callback to sign the server nonce. This an the Nkey // option are mutually exclusive.
[ "UserJWT", "will", "set", "the", "callbacks", "to", "retrieve", "the", "user", "s", "JWT", "and", "the", "signature", "callback", "to", "sign", "the", "server", "nonce", ".", "This", "an", "the", "Nkey", "option", "are", "mutually", "exclusive", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L787-L799
train
nats-io/go-nats
nats.go
Nkey
func Nkey(pubKey string, sigCB SignatureHandler) Option { return func(o *Options) error { o.Nkey = pubKey o.SignatureCB = sigCB if pubKey != "" && sigCB == nil { return ErrNkeyButNoSigCB } return nil } }
go
func Nkey(pubKey string, sigCB SignatureHandler) Option { return func(o *Options) error { o.Nkey = pubKey o.SignatureCB = sigCB if pubKey != "" && sigCB == nil { return ErrNkeyButNoSigCB } return nil } }
[ "func", "Nkey", "(", "pubKey", "string", ",", "sigCB", "SignatureHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "Nkey", "=", "pubKey", "\n", "o", ".", "SignatureCB", "=", "sigCB", "\n", "if", "pubKey", "!=", "\"\"", "&&", "sigCB", "==", "nil", "{", "return", "ErrNkeyButNoSigCB", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Nkey will set the public Nkey and the signature callback to // sign the server nonce.
[ "Nkey", "will", "set", "the", "public", "Nkey", "and", "the", "signature", "callback", "to", "sign", "the", "server", "nonce", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L803-L812
train
nats-io/go-nats
nats.go
SetCustomDialer
func SetCustomDialer(dialer CustomDialer) Option { return func(o *Options) error { o.CustomDialer = dialer return nil } }
go
func SetCustomDialer(dialer CustomDialer) Option { return func(o *Options) error { o.CustomDialer = dialer return nil } }
[ "func", "SetCustomDialer", "(", "dialer", "CustomDialer", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "CustomDialer", "=", "dialer", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SetCustomDialer is an Option to set a custom dialer which will be // used when attempting to establish a connection. If both Dialer // and CustomDialer are specified, CustomDialer takes precedence.
[ "SetCustomDialer", "is", "an", "Option", "to", "set", "a", "custom", "dialer", "which", "will", "be", "used", "when", "attempting", "to", "establish", "a", "connection", ".", "If", "both", "Dialer", "and", "CustomDialer", "are", "specified", "CustomDialer", "takes", "precedence", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L836-L841
train