id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
15,500
intelsdi-x/snap
scheduler/work_manager.go
CollectWkrSizeOption
func CollectWkrSizeOption(v uint) workManagerOption { return func(w *workManager) workManagerOption { previous := w.collectWkrSize w.collectWkrSize = v return CollectWkrSizeOption(previous) } }
go
func CollectWkrSizeOption(v uint) workManagerOption { return func(w *workManager) workManagerOption { previous := w.collectWkrSize w.collectWkrSize = v return CollectWkrSizeOption(previous) } }
[ "func", "CollectWkrSizeOption", "(", "v", "uint", ")", "workManagerOption", "{", "return", "func", "(", "w", "*", "workManager", ")", "workManagerOption", "{", "previous", ":=", "w", ".", "collectWkrSize", "\n", "w", ".", "collectWkrSize", "=", "v", "\n", "return", "CollectWkrSizeOption", "(", "previous", ")", "\n", "}", "\n", "}" ]
// CollectWkrSizeOption sets the collector worker pool size // and returns the previous collector worker pool state.
[ "CollectWkrSizeOption", "sets", "the", "collector", "worker", "pool", "size", "and", "returns", "the", "previous", "collector", "worker", "pool", "state", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L110-L116
15,501
intelsdi-x/snap
scheduler/work_manager.go
ProcessWkrSizeOption
func ProcessWkrSizeOption(v uint) workManagerOption { return func(w *workManager) workManagerOption { previous := w.processWkrSize w.processWkrSize = v return ProcessWkrSizeOption(previous) } }
go
func ProcessWkrSizeOption(v uint) workManagerOption { return func(w *workManager) workManagerOption { previous := w.processWkrSize w.processWkrSize = v return ProcessWkrSizeOption(previous) } }
[ "func", "ProcessWkrSizeOption", "(", "v", "uint", ")", "workManagerOption", "{", "return", "func", "(", "w", "*", "workManager", ")", "workManagerOption", "{", "previous", ":=", "w", ".", "processWkrSize", "\n", "w", ".", "processWkrSize", "=", "v", "\n", "return", "ProcessWkrSizeOption", "(", "previous", ")", "\n", "}", "\n", "}" ]
// ProcessWkrSizeOption sets the processor worker pool size // and return the previous processor worker pool state.
[ "ProcessWkrSizeOption", "sets", "the", "processor", "worker", "pool", "size", "and", "return", "the", "previous", "processor", "worker", "pool", "state", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L120-L126
15,502
intelsdi-x/snap
scheduler/work_manager.go
PublishWkrSizeOption
func PublishWkrSizeOption(v uint) workManagerOption { return func(w *workManager) workManagerOption { previous := w.publishWkrSize w.publishWkrSize = v return PublishWkrSizeOption(previous) } }
go
func PublishWkrSizeOption(v uint) workManagerOption { return func(w *workManager) workManagerOption { previous := w.publishWkrSize w.publishWkrSize = v return PublishWkrSizeOption(previous) } }
[ "func", "PublishWkrSizeOption", "(", "v", "uint", ")", "workManagerOption", "{", "return", "func", "(", "w", "*", "workManager", ")", "workManagerOption", "{", "previous", ":=", "w", ".", "publishWkrSize", "\n", "w", ".", "publishWkrSize", "=", "v", "\n", "return", "PublishWkrSizeOption", "(", "previous", ")", "\n", "}", "\n", "}" ]
// PublishWkrSizeOption sets the publisher worker pool size // and returns the previous previous publisher worker pool state.
[ "PublishWkrSizeOption", "sets", "the", "publisher", "worker", "pool", "size", "and", "returns", "the", "previous", "previous", "publisher", "worker", "pool", "state", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L130-L136
15,503
intelsdi-x/snap
scheduler/work_manager.go
Start
func (w *workManager) Start() { w.mutex.Lock() defer w.mutex.Unlock() if w.state == workManagerStopped { w.state = workManagerRunning go func() { for { select { case <-w.collectq.Err: //TODO: log error case <-w.processq.Err: //TODO: log error case <-w.publishq.Err: //TODO: log error case <-w.kill: return } } }() } }
go
func (w *workManager) Start() { w.mutex.Lock() defer w.mutex.Unlock() if w.state == workManagerStopped { w.state = workManagerRunning go func() { for { select { case <-w.collectq.Err: //TODO: log error case <-w.processq.Err: //TODO: log error case <-w.publishq.Err: //TODO: log error case <-w.kill: return } } }() } }
[ "func", "(", "w", "*", "workManager", ")", "Start", "(", ")", "{", "w", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "w", ".", "state", "==", "workManagerStopped", "{", "w", ".", "state", "=", "workManagerRunning", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "w", ".", "collectq", ".", "Err", ":", "//TODO: log error", "case", "<-", "w", ".", "processq", ".", "Err", ":", "//TODO: log error", "case", "<-", "w", ".", "publishq", ".", "Err", ":", "//TODO: log error", "case", "<-", "w", ".", "kill", ":", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "}" ]
// Start workManager's loop just handles queuing errors.
[ "Start", "workManager", "s", "loop", "just", "handles", "queuing", "errors", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L187-L209
15,504
intelsdi-x/snap
scheduler/work_manager.go
Stop
func (w *workManager) Stop() { w.collectq.Stop() close(workerKillChan) close(w.kill) }
go
func (w *workManager) Stop() { w.collectq.Stop() close(workerKillChan) close(w.kill) }
[ "func", "(", "w", "*", "workManager", ")", "Stop", "(", ")", "{", "w", ".", "collectq", ".", "Stop", "(", ")", "\n", "close", "(", "workerKillChan", ")", "\n", "close", "(", "w", ".", "kill", ")", "\n", "}" ]
// Stop closes the collector queue and worker
[ "Stop", "closes", "the", "collector", "queue", "and", "worker" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L212-L216
15,505
intelsdi-x/snap
scheduler/work_manager.go
Work
func (w *workManager) Work(j job) queuedJob { qj := newQueuedJob(j) switch j.Type() { case collectJobType: w.collectq.Event <- qj case processJobType: w.processq.Event <- qj case publishJobType: w.publishq.Event <- qj } return qj }
go
func (w *workManager) Work(j job) queuedJob { qj := newQueuedJob(j) switch j.Type() { case collectJobType: w.collectq.Event <- qj case processJobType: w.processq.Event <- qj case publishJobType: w.publishq.Event <- qj } return qj }
[ "func", "(", "w", "*", "workManager", ")", "Work", "(", "j", "job", ")", "queuedJob", "{", "qj", ":=", "newQueuedJob", "(", "j", ")", "\n", "switch", "j", ".", "Type", "(", ")", "{", "case", "collectJobType", ":", "w", ".", "collectq", ".", "Event", "<-", "qj", "\n", "case", "processJobType", ":", "w", ".", "processq", ".", "Event", "<-", "qj", "\n", "case", "publishJobType", ":", "w", ".", "publishq", ".", "Event", "<-", "qj", "\n", "}", "\n", "return", "qj", "\n", "}" ]
// Work dispatches jobs to worker pools for processing. // // Returns a queued job to the caller, which will be // completed by the work queue aubsystem.
[ "Work", "dispatches", "jobs", "to", "worker", "pools", "for", "processing", ".", "Returns", "a", "queued", "job", "to", "the", "caller", "which", "will", "be", "completed", "by", "the", "work", "queue", "aubsystem", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L222-L233
15,506
intelsdi-x/snap
scheduler/work_manager.go
AddCollectWorker
func (w *workManager) AddCollectWorker() { nw := newWorker(w.collectchan) go nw.start() w.collectWkrs = append(w.collectWkrs, nw) w.collectWkrSize++ }
go
func (w *workManager) AddCollectWorker() { nw := newWorker(w.collectchan) go nw.start() w.collectWkrs = append(w.collectWkrs, nw) w.collectWkrSize++ }
[ "func", "(", "w", "*", "workManager", ")", "AddCollectWorker", "(", ")", "{", "nw", ":=", "newWorker", "(", "w", ".", "collectchan", ")", "\n", "go", "nw", ".", "start", "(", ")", "\n", "w", ".", "collectWkrs", "=", "append", "(", "w", ".", "collectWkrs", ",", "nw", ")", "\n", "w", ".", "collectWkrSize", "++", "\n", "}" ]
// AddCollectWorker adds a new worker to // the collector worker pool
[ "AddCollectWorker", "adds", "a", "new", "worker", "to", "the", "collector", "worker", "pool" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L237-L242
15,507
intelsdi-x/snap
scheduler/work_manager.go
AddPublishWorker
func (w *workManager) AddPublishWorker() { nw := newWorker(w.publishchan) go nw.start() w.publishWkrs = append(w.publishWkrs, nw) w.publishWkrSize++ }
go
func (w *workManager) AddPublishWorker() { nw := newWorker(w.publishchan) go nw.start() w.publishWkrs = append(w.publishWkrs, nw) w.publishWkrSize++ }
[ "func", "(", "w", "*", "workManager", ")", "AddPublishWorker", "(", ")", "{", "nw", ":=", "newWorker", "(", "w", ".", "publishchan", ")", "\n", "go", "nw", ".", "start", "(", ")", "\n", "w", ".", "publishWkrs", "=", "append", "(", "w", ".", "publishWkrs", ",", "nw", ")", "\n", "w", ".", "publishWkrSize", "++", "\n", "}" ]
// AddPublishWorker adds a new worker to // the publisher worker pool
[ "AddPublishWorker", "adds", "a", "new", "worker", "to", "the", "publisher", "worker", "pool" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L246-L251
15,508
intelsdi-x/snap
scheduler/work_manager.go
AddProcessWorker
func (w *workManager) AddProcessWorker() { nw := newWorker(w.processchan) go nw.start() w.processWkrs = append(w.processWkrs, nw) w.processWkrSize++ }
go
func (w *workManager) AddProcessWorker() { nw := newWorker(w.processchan) go nw.start() w.processWkrs = append(w.processWkrs, nw) w.processWkrSize++ }
[ "func", "(", "w", "*", "workManager", ")", "AddProcessWorker", "(", ")", "{", "nw", ":=", "newWorker", "(", "w", ".", "processchan", ")", "\n", "go", "nw", ".", "start", "(", ")", "\n", "w", ".", "processWkrs", "=", "append", "(", "w", ".", "processWkrs", ",", "nw", ")", "\n", "w", ".", "processWkrSize", "++", "\n", "}" ]
// AddProcessWorker adds a new worker to // the processor worker pool
[ "AddProcessWorker", "adds", "a", "new", "worker", "to", "the", "processor", "worker", "pool" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L255-L260
15,509
intelsdi-x/snap
scheduler/work_manager.go
sendToWorker
func (w *workManager) sendToWorker(j queuedJob) { switch j.Job().Type() { case collectJobType: w.collectchan <- j case publishJobType: w.publishchan <- j case processJobType: w.processchan <- j } }
go
func (w *workManager) sendToWorker(j queuedJob) { switch j.Job().Type() { case collectJobType: w.collectchan <- j case publishJobType: w.publishchan <- j case processJobType: w.processchan <- j } }
[ "func", "(", "w", "*", "workManager", ")", "sendToWorker", "(", "j", "queuedJob", ")", "{", "switch", "j", ".", "Job", "(", ")", ".", "Type", "(", ")", "{", "case", "collectJobType", ":", "w", ".", "collectchan", "<-", "j", "\n", "case", "publishJobType", ":", "w", ".", "publishchan", "<-", "j", "\n", "case", "processJobType", ":", "w", ".", "processchan", "<-", "j", "\n", "}", "\n", "}" ]
// sendToWorker is the handler given to the queue. // it dispatches work to the worker pool.
[ "sendToWorker", "is", "the", "handler", "given", "to", "the", "queue", ".", "it", "dispatches", "work", "to", "the", "worker", "pool", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/work_manager.go#L264-L273
15,510
intelsdi-x/snap
control/plugin/cpolicy/tree.go
UnmarshalJSON
func (c *ConfigPolicy) UnmarshalJSON(data []byte) error { m := map[string]map[string]interface{}{} decoder := json.NewDecoder(bytes.NewReader(data)) if err := decoder.Decode(&m); err != nil { return err } c.config = ctree.New() if config, ok := m["config"]; ok { if node, ok := config["root"]; ok { if n, ok := node.(map[string]interface{}); ok { return unmarshalJSON(n, &[]string{}, c.config) } } } return nil }
go
func (c *ConfigPolicy) UnmarshalJSON(data []byte) error { m := map[string]map[string]interface{}{} decoder := json.NewDecoder(bytes.NewReader(data)) if err := decoder.Decode(&m); err != nil { return err } c.config = ctree.New() if config, ok := m["config"]; ok { if node, ok := config["root"]; ok { if n, ok := node.(map[string]interface{}); ok { return unmarshalJSON(n, &[]string{}, c.config) } } } return nil }
[ "func", "(", "c", "*", "ConfigPolicy", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "m", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "decoder", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "config", "=", "ctree", ".", "New", "(", ")", "\n", "if", "config", ",", "ok", ":=", "m", "[", "\"", "\"", "]", ";", "ok", "{", "if", "node", ",", "ok", ":=", "config", "[", "\"", "\"", "]", ";", "ok", "{", "if", "n", ",", "ok", ":=", "node", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "return", "unmarshalJSON", "(", "n", ",", "&", "[", "]", "string", "{", "}", ",", "c", ".", "config", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON unmarshals JSON into a ConfigPolicy
[ "UnmarshalJSON", "unmarshals", "JSON", "into", "a", "ConfigPolicy" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/tree.go#L60-L75
15,511
intelsdi-x/snap
control/plugin/cpolicy/tree.go
MarshalJSON
func (c *ConfigPolicy) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Config *ctree.ConfigTree `json:"config"` }{ Config: c.config, }) }
go
func (c *ConfigPolicy) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Config *ctree.ConfigTree `json:"config"` }{ Config: c.config, }) }
[ "func", "(", "c", "*", "ConfigPolicy", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Config", "*", "ctree", ".", "ConfigTree", "`json:\"config\"`", "\n", "}", "{", "Config", ":", "c", ".", "config", ",", "}", ")", "\n", "}" ]
// MarshalJSON marshals a ConfigPolicy into JSON
[ "MarshalJSON", "marshals", "a", "ConfigPolicy", "into", "JSON" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/tree.go#L114-L120
15,512
intelsdi-x/snap
control/plugin/cpolicy/tree.go
Add
func (c *ConfigPolicy) Add(ns []string, cpn *ConfigPolicyNode) { c.config.Add(ns, cpn) }
go
func (c *ConfigPolicy) Add(ns []string, cpn *ConfigPolicyNode) { c.config.Add(ns, cpn) }
[ "func", "(", "c", "*", "ConfigPolicy", ")", "Add", "(", "ns", "[", "]", "string", ",", "cpn", "*", "ConfigPolicyNode", ")", "{", "c", ".", "config", ".", "Add", "(", "ns", ",", "cpn", ")", "\n", "}" ]
// Adds a ConfigPolicyNode at the provided namespace.
[ "Adds", "a", "ConfigPolicyNode", "at", "the", "provided", "namespace", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/tree.go#L123-L125
15,513
intelsdi-x/snap
control/plugin/cpolicy/tree.go
Get
func (c *ConfigPolicy) Get(ns []string) *ConfigPolicyNode { n := c.config.Get(ns) if n == nil { return NewPolicyNode() } switch t := n.(type) { case ConfigPolicyNode: return &t default: return t.(*ConfigPolicyNode) } }
go
func (c *ConfigPolicy) Get(ns []string) *ConfigPolicyNode { n := c.config.Get(ns) if n == nil { return NewPolicyNode() } switch t := n.(type) { case ConfigPolicyNode: return &t default: return t.(*ConfigPolicyNode) } }
[ "func", "(", "c", "*", "ConfigPolicy", ")", "Get", "(", "ns", "[", "]", "string", ")", "*", "ConfigPolicyNode", "{", "n", ":=", "c", ".", "config", ".", "Get", "(", "ns", ")", "\n", "if", "n", "==", "nil", "{", "return", "NewPolicyNode", "(", ")", "\n", "}", "\n", "switch", "t", ":=", "n", ".", "(", "type", ")", "{", "case", "ConfigPolicyNode", ":", "return", "&", "t", "\n", "default", ":", "return", "t", ".", "(", "*", "ConfigPolicyNode", ")", "\n", "}", "\n", "}" ]
// Returns a ConfigPolicyNode that is a merged version of the namespace provided.
[ "Returns", "a", "ConfigPolicyNode", "that", "is", "a", "merged", "version", "of", "the", "namespace", "provided", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/tree.go#L128-L140
15,514
intelsdi-x/snap
control/plugin/metric_deprecated.go
NewMetricType
func NewMetricType(namespace core.Namespace, timestamp time.Time, tags map[string]string, unit string, data interface{}) *MetricType { return &MetricType{ Namespace_: namespace, Tags_: tags, Data_: data, Timestamp_: timestamp, LastAdvertisedTime_: timestamp, Unit_: unit, } }
go
func NewMetricType(namespace core.Namespace, timestamp time.Time, tags map[string]string, unit string, data interface{}) *MetricType { return &MetricType{ Namespace_: namespace, Tags_: tags, Data_: data, Timestamp_: timestamp, LastAdvertisedTime_: timestamp, Unit_: unit, } }
[ "func", "NewMetricType", "(", "namespace", "core", ".", "Namespace", ",", "timestamp", "time", ".", "Time", ",", "tags", "map", "[", "string", "]", "string", ",", "unit", "string", ",", "data", "interface", "{", "}", ")", "*", "MetricType", "{", "return", "&", "MetricType", "{", "Namespace_", ":", "namespace", ",", "Tags_", ":", "tags", ",", "Data_", ":", "data", ",", "Timestamp_", ":", "timestamp", ",", "LastAdvertisedTime_", ":", "timestamp", ",", "Unit_", ":", "unit", ",", "}", "\n", "}" ]
// NewMetricType returns a Constructor
[ "NewMetricType", "returns", "a", "Constructor" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/metric_deprecated.go#L47-L56
15,515
intelsdi-x/snap
control/plugin/metric_deprecated.go
SwapMetricContentType
func SwapMetricContentType(contentType, requestedContentType string, payload []byte) ([]byte, string, error) { metrics, err1 := UnmarshallMetricTypes(contentType, payload) if err1 != nil { log.WithFields(log.Fields{ "_module": "control-plugin", "block": "swap-content-type", "error": err1.Error(), }).Error("error while swaping") return nil, "", err1 } newPayload, newContentType, err2 := MarshalMetricTypes(requestedContentType, metrics) if err2 != nil { log.WithFields(log.Fields{ "_module": "control-plugin", "block": "swap-content-type", "error": err2.Error(), }).Error("error while swaping") return nil, "", err2 } return newPayload, newContentType, nil }
go
func SwapMetricContentType(contentType, requestedContentType string, payload []byte) ([]byte, string, error) { metrics, err1 := UnmarshallMetricTypes(contentType, payload) if err1 != nil { log.WithFields(log.Fields{ "_module": "control-plugin", "block": "swap-content-type", "error": err1.Error(), }).Error("error while swaping") return nil, "", err1 } newPayload, newContentType, err2 := MarshalMetricTypes(requestedContentType, metrics) if err2 != nil { log.WithFields(log.Fields{ "_module": "control-plugin", "block": "swap-content-type", "error": err2.Error(), }).Error("error while swaping") return nil, "", err2 } return newPayload, newContentType, nil }
[ "func", "SwapMetricContentType", "(", "contentType", ",", "requestedContentType", "string", ",", "payload", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "string", ",", "error", ")", "{", "metrics", ",", "err1", ":=", "UnmarshallMetricTypes", "(", "contentType", ",", "payload", ")", "\n", "if", "err1", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "err1", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "\"", "\"", ",", "err1", "\n", "}", "\n", "newPayload", ",", "newContentType", ",", "err2", ":=", "MarshalMetricTypes", "(", "requestedContentType", ",", "metrics", ")", "\n", "if", "err2", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "err2", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "\"", "\"", ",", "err2", "\n", "}", "\n", "return", "newPayload", ",", "newContentType", ",", "nil", "\n", "}" ]
// SwapMetricContentType swaps a payload with one content type to another one.
[ "SwapMetricContentType", "swaps", "a", "payload", "with", "one", "content", "type", "to", "another", "one", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/metric_deprecated.go#L152-L172
15,516
ddliu/go-httpclient
httpclient.go
ReadAll
func (this *Response) ReadAll() ([]byte, error) { var reader io.ReadCloser var err error switch this.Header.Get("Content-Encoding") { case "gzip": reader, err = gzip.NewReader(this.Body) if err != nil { return nil, err } default: reader = this.Body } defer reader.Close() return ioutil.ReadAll(reader) }
go
func (this *Response) ReadAll() ([]byte, error) { var reader io.ReadCloser var err error switch this.Header.Get("Content-Encoding") { case "gzip": reader, err = gzip.NewReader(this.Body) if err != nil { return nil, err } default: reader = this.Body } defer reader.Close() return ioutil.ReadAll(reader) }
[ "func", "(", "this", "*", "Response", ")", "ReadAll", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "reader", "io", ".", "ReadCloser", "\n", "var", "err", "error", "\n", "switch", "this", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ":", "reader", ",", "err", "=", "gzip", ".", "NewReader", "(", "this", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "default", ":", "reader", "=", "this", ".", "Body", "\n", "}", "\n\n", "defer", "reader", ".", "Close", "(", ")", "\n", "return", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "}" ]
// Read response body into a byte slice.
[ "Read", "response", "body", "into", "a", "byte", "slice", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L124-L139
15,517
ddliu/go-httpclient
httpclient.go
ToString
func (this *Response) ToString() (string, error) { bytes, err := this.ReadAll() if err != nil { return "", err } return string(bytes), nil }
go
func (this *Response) ToString() (string, error) { bytes, err := this.ReadAll() if err != nil { return "", err } return string(bytes), nil }
[ "func", "(", "this", "*", "Response", ")", "ToString", "(", ")", "(", "string", ",", "error", ")", "{", "bytes", ",", "err", ":=", "this", ".", "ReadAll", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "string", "(", "bytes", ")", ",", "nil", "\n", "}" ]
// Read response body into string.
[ "Read", "response", "body", "into", "string", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L142-L149
15,518
ddliu/go-httpclient
httpclient.go
prepareRequest
func prepareRequest(method string, url_ string, headers map[string]string, body io.Reader, options map[int]interface{}) (*http.Request, error) { req, err := http.NewRequest(method, url_, body) if err != nil { return nil, err } // OPT_REFERER if referer, ok := options[OPT_REFERER]; ok { if refererStr, ok := referer.(string); ok { req.Header.Set("Referer", refererStr) } } // OPT_USERAGENT if useragent, ok := options[OPT_USERAGENT]; ok { if useragentStr, ok := useragent.(string); ok { req.Header.Set("User-Agent", useragentStr) } } for k, v := range headers { req.Header.Set(k, v) } return req, nil }
go
func prepareRequest(method string, url_ string, headers map[string]string, body io.Reader, options map[int]interface{}) (*http.Request, error) { req, err := http.NewRequest(method, url_, body) if err != nil { return nil, err } // OPT_REFERER if referer, ok := options[OPT_REFERER]; ok { if refererStr, ok := referer.(string); ok { req.Header.Set("Referer", refererStr) } } // OPT_USERAGENT if useragent, ok := options[OPT_USERAGENT]; ok { if useragentStr, ok := useragent.(string); ok { req.Header.Set("User-Agent", useragentStr) } } for k, v := range headers { req.Header.Set(k, v) } return req, nil }
[ "func", "prepareRequest", "(", "method", "string", ",", "url_", "string", ",", "headers", "map", "[", "string", "]", "string", ",", "body", "io", ".", "Reader", ",", "options", "map", "[", "int", "]", "interface", "{", "}", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "url_", ",", "body", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// OPT_REFERER", "if", "referer", ",", "ok", ":=", "options", "[", "OPT_REFERER", "]", ";", "ok", "{", "if", "refererStr", ",", "ok", ":=", "referer", ".", "(", "string", ")", ";", "ok", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "refererStr", ")", "\n", "}", "\n", "}", "\n\n", "// OPT_USERAGENT", "if", "useragent", ",", "ok", ":=", "options", "[", "OPT_USERAGENT", "]", ";", "ok", "{", "if", "useragentStr", ",", "ok", ":=", "useragent", ".", "(", "string", ")", ";", "ok", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "useragentStr", ")", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "headers", "{", "req", ".", "Header", ".", "Set", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// Prepare a request.
[ "Prepare", "a", "request", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L152-L179
15,519
ddliu/go-httpclient
httpclient.go
prepareRedirect
func prepareRedirect(options map[int]interface{}) (func(req *http.Request, via []*http.Request) error, error) { var redirectPolicy func(req *http.Request, via []*http.Request) error if redirectPolicy_, ok := options[OPT_REDIRECT_POLICY]; ok { if redirectPolicy, ok = redirectPolicy_.(func(*http.Request, []*http.Request) error); !ok { return nil, fmt.Errorf("OPT_REDIRECT_POLICY is not a desired function") } } else { var followlocation bool if followlocation_, ok := options[OPT_FOLLOWLOCATION]; ok { if followlocation, ok = followlocation_.(bool); !ok { return nil, fmt.Errorf("OPT_FOLLOWLOCATION must be bool") } } var maxredirs int if maxredirs_, ok := options[OPT_MAXREDIRS]; ok { if maxredirs, ok = maxredirs_.(int); !ok { return nil, fmt.Errorf("OPT_MAXREDIRS must be int") } } redirectPolicy = func(req *http.Request, via []*http.Request) error { // no follow if !followlocation || maxredirs <= 0 { return &Error{ Code: ERR_REDIRECT_POLICY, Message: fmt.Sprintf("redirect not allowed"), } } if len(via) >= maxredirs { return &Error{ Code: ERR_REDIRECT_POLICY, Message: fmt.Sprintf("stopped after %d redirects", len(via)), } } last := via[len(via)-1] // keep necessary headers // TODO: pass all headers or add other headers? if useragent := last.Header.Get("User-Agent"); useragent != "" { req.Header.Set("User-Agent", useragent) } return nil } } return redirectPolicy, nil }
go
func prepareRedirect(options map[int]interface{}) (func(req *http.Request, via []*http.Request) error, error) { var redirectPolicy func(req *http.Request, via []*http.Request) error if redirectPolicy_, ok := options[OPT_REDIRECT_POLICY]; ok { if redirectPolicy, ok = redirectPolicy_.(func(*http.Request, []*http.Request) error); !ok { return nil, fmt.Errorf("OPT_REDIRECT_POLICY is not a desired function") } } else { var followlocation bool if followlocation_, ok := options[OPT_FOLLOWLOCATION]; ok { if followlocation, ok = followlocation_.(bool); !ok { return nil, fmt.Errorf("OPT_FOLLOWLOCATION must be bool") } } var maxredirs int if maxredirs_, ok := options[OPT_MAXREDIRS]; ok { if maxredirs, ok = maxredirs_.(int); !ok { return nil, fmt.Errorf("OPT_MAXREDIRS must be int") } } redirectPolicy = func(req *http.Request, via []*http.Request) error { // no follow if !followlocation || maxredirs <= 0 { return &Error{ Code: ERR_REDIRECT_POLICY, Message: fmt.Sprintf("redirect not allowed"), } } if len(via) >= maxredirs { return &Error{ Code: ERR_REDIRECT_POLICY, Message: fmt.Sprintf("stopped after %d redirects", len(via)), } } last := via[len(via)-1] // keep necessary headers // TODO: pass all headers or add other headers? if useragent := last.Header.Get("User-Agent"); useragent != "" { req.Header.Set("User-Agent", useragent) } return nil } } return redirectPolicy, nil }
[ "func", "prepareRedirect", "(", "options", "map", "[", "int", "]", "interface", "{", "}", ")", "(", "func", "(", "req", "*", "http", ".", "Request", ",", "via", "[", "]", "*", "http", ".", "Request", ")", "error", ",", "error", ")", "{", "var", "redirectPolicy", "func", "(", "req", "*", "http", ".", "Request", ",", "via", "[", "]", "*", "http", ".", "Request", ")", "error", "\n\n", "if", "redirectPolicy_", ",", "ok", ":=", "options", "[", "OPT_REDIRECT_POLICY", "]", ";", "ok", "{", "if", "redirectPolicy", ",", "ok", "=", "redirectPolicy_", ".", "(", "func", "(", "*", "http", ".", "Request", ",", "[", "]", "*", "http", ".", "Request", ")", "error", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "var", "followlocation", "bool", "\n", "if", "followlocation_", ",", "ok", ":=", "options", "[", "OPT_FOLLOWLOCATION", "]", ";", "ok", "{", "if", "followlocation", ",", "ok", "=", "followlocation_", ".", "(", "bool", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "var", "maxredirs", "int", "\n", "if", "maxredirs_", ",", "ok", ":=", "options", "[", "OPT_MAXREDIRS", "]", ";", "ok", "{", "if", "maxredirs", ",", "ok", "=", "maxredirs_", ".", "(", "int", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "redirectPolicy", "=", "func", "(", "req", "*", "http", ".", "Request", ",", "via", "[", "]", "*", "http", ".", "Request", ")", "error", "{", "// no follow", "if", "!", "followlocation", "||", "maxredirs", "<=", "0", "{", "return", "&", "Error", "{", "Code", ":", "ERR_REDIRECT_POLICY", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ",", "}", "\n", "}", "\n\n", "if", "len", "(", "via", ")", ">=", "maxredirs", "{", "return", "&", "Error", "{", "Code", ":", "ERR_REDIRECT_POLICY", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "via", ")", ")", ",", "}", "\n", "}", "\n\n", "last", ":=", "via", "[", "len", "(", "via", ")", "-", "1", "]", "\n", "// keep necessary headers", "// TODO: pass all headers or add other headers?", "if", "useragent", ":=", "last", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "useragent", "!=", "\"", "\"", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "useragent", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "redirectPolicy", ",", "nil", "\n", "}" ]
// Prepare a redirect policy.
[ "Prepare", "a", "redirect", "policy", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L306-L356
15,520
ddliu/go-httpclient
httpclient.go
prepareJar
func prepareJar(options map[int]interface{}) (http.CookieJar, error) { var jar http.CookieJar var err error if optCookieJar_, ok := options[OPT_COOKIEJAR]; ok { // is bool if optCookieJar, ok := optCookieJar_.(bool); ok { // default jar if optCookieJar { // TODO: PublicSuffixList jar, err = cookiejar.New(nil) if err != nil { return nil, err } } } else if optCookieJar, ok := optCookieJar_.(http.CookieJar); ok { jar = optCookieJar } else { return nil, fmt.Errorf("invalid cookiejar") } } return jar, nil }
go
func prepareJar(options map[int]interface{}) (http.CookieJar, error) { var jar http.CookieJar var err error if optCookieJar_, ok := options[OPT_COOKIEJAR]; ok { // is bool if optCookieJar, ok := optCookieJar_.(bool); ok { // default jar if optCookieJar { // TODO: PublicSuffixList jar, err = cookiejar.New(nil) if err != nil { return nil, err } } } else if optCookieJar, ok := optCookieJar_.(http.CookieJar); ok { jar = optCookieJar } else { return nil, fmt.Errorf("invalid cookiejar") } } return jar, nil }
[ "func", "prepareJar", "(", "options", "map", "[", "int", "]", "interface", "{", "}", ")", "(", "http", ".", "CookieJar", ",", "error", ")", "{", "var", "jar", "http", ".", "CookieJar", "\n", "var", "err", "error", "\n", "if", "optCookieJar_", ",", "ok", ":=", "options", "[", "OPT_COOKIEJAR", "]", ";", "ok", "{", "// is bool", "if", "optCookieJar", ",", "ok", ":=", "optCookieJar_", ".", "(", "bool", ")", ";", "ok", "{", "// default jar", "if", "optCookieJar", "{", "// TODO: PublicSuffixList", "jar", ",", "err", "=", "cookiejar", ".", "New", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "else", "if", "optCookieJar", ",", "ok", ":=", "optCookieJar_", ".", "(", "http", ".", "CookieJar", ")", ";", "ok", "{", "jar", "=", "optCookieJar", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "jar", ",", "nil", "\n", "}" ]
// Prepare a cookie jar.
[ "Prepare", "a", "cookie", "jar", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L359-L381
15,521
ddliu/go-httpclient
httpclient.go
NewHttpClient
func NewHttpClient() *HttpClient { c := &HttpClient{ reuseTransport: true, reuseJar: true, lock: new(sync.Mutex), } return c }
go
func NewHttpClient() *HttpClient { c := &HttpClient{ reuseTransport: true, reuseJar: true, lock: new(sync.Mutex), } return c }
[ "func", "NewHttpClient", "(", ")", "*", "HttpClient", "{", "c", ":=", "&", "HttpClient", "{", "reuseTransport", ":", "true", ",", "reuseJar", ":", "true", ",", "lock", ":", "new", "(", "sync", ".", "Mutex", ")", ",", "}", "\n\n", "return", "c", "\n", "}" ]
// Create an HTTP client.
[ "Create", "an", "HTTP", "client", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L384-L392
15,522
ddliu/go-httpclient
httpclient.go
Defaults
func (this *HttpClient) Defaults(defaults Map) *HttpClient { options, headers := parseMap(defaults) // merge options if this.options == nil { this.options = options } else { for k, v := range options { this.options[k] = v } } // merge headers if this.Headers == nil { this.Headers = headers } else { for k, v := range headers { this.Headers[k] = v } } return this }
go
func (this *HttpClient) Defaults(defaults Map) *HttpClient { options, headers := parseMap(defaults) // merge options if this.options == nil { this.options = options } else { for k, v := range options { this.options[k] = v } } // merge headers if this.Headers == nil { this.Headers = headers } else { for k, v := range headers { this.Headers[k] = v } } return this }
[ "func", "(", "this", "*", "HttpClient", ")", "Defaults", "(", "defaults", "Map", ")", "*", "HttpClient", "{", "options", ",", "headers", ":=", "parseMap", "(", "defaults", ")", "\n\n", "// merge options", "if", "this", ".", "options", "==", "nil", "{", "this", ".", "options", "=", "options", "\n", "}", "else", "{", "for", "k", ",", "v", ":=", "range", "options", "{", "this", ".", "options", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "// merge headers", "if", "this", ".", "Headers", "==", "nil", "{", "this", ".", "Headers", "=", "headers", "\n", "}", "else", "{", "for", "k", ",", "v", ":=", "range", "headers", "{", "this", ".", "Headers", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "this", "\n", "}" ]
// Set default options and headers.
[ "Set", "default", "options", "and", "headers", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L432-L454
15,523
ddliu/go-httpclient
httpclient.go
Begin
func (this *HttpClient) Begin() *HttpClient { this.lock.Lock() this.withLock = true return this }
go
func (this *HttpClient) Begin() *HttpClient { this.lock.Lock() this.withLock = true return this }
[ "func", "(", "this", "*", "HttpClient", ")", "Begin", "(", ")", "*", "HttpClient", "{", "this", ".", "lock", ".", "Lock", "(", ")", "\n", "this", ".", "withLock", "=", "true", "\n\n", "return", "this", "\n", "}" ]
// Begin marks the begining of a request, it's necessary for concurrent // requests.
[ "Begin", "marks", "the", "begining", "of", "a", "request", "it", "s", "necessary", "for", "concurrent", "requests", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L458-L463
15,524
ddliu/go-httpclient
httpclient.go
reset
func (this *HttpClient) reset() { this.oneTimeOptions = nil this.oneTimeHeaders = nil this.oneTimeCookies = nil this.reuseTransport = true this.reuseJar = true // nil means the Begin has not been called, asume requests are not // concurrent. if this.withLock { this.lock.Unlock() } }
go
func (this *HttpClient) reset() { this.oneTimeOptions = nil this.oneTimeHeaders = nil this.oneTimeCookies = nil this.reuseTransport = true this.reuseJar = true // nil means the Begin has not been called, asume requests are not // concurrent. if this.withLock { this.lock.Unlock() } }
[ "func", "(", "this", "*", "HttpClient", ")", "reset", "(", ")", "{", "this", ".", "oneTimeOptions", "=", "nil", "\n", "this", ".", "oneTimeHeaders", "=", "nil", "\n", "this", ".", "oneTimeCookies", "=", "nil", "\n", "this", ".", "reuseTransport", "=", "true", "\n", "this", ".", "reuseJar", "=", "true", "\n\n", "// nil means the Begin has not been called, asume requests are not", "// concurrent.", "if", "this", ".", "withLock", "{", "this", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// Reset the client state so that other requests can begin.
[ "Reset", "the", "client", "state", "so", "that", "other", "requests", "can", "begin", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L466-L478
15,525
ddliu/go-httpclient
httpclient.go
WithOption
func (this *HttpClient) WithOption(k int, v interface{}) *HttpClient { if this.oneTimeOptions == nil { this.oneTimeOptions = make(map[int]interface{}) } this.oneTimeOptions[k] = v // Conditions we cann't reuse the transport. if hasOption(k, transportOptions) { this.reuseTransport = false } // Conditions we cann't reuse the cookie jar. if hasOption(k, jarOptions) { this.reuseJar = false } return this }
go
func (this *HttpClient) WithOption(k int, v interface{}) *HttpClient { if this.oneTimeOptions == nil { this.oneTimeOptions = make(map[int]interface{}) } this.oneTimeOptions[k] = v // Conditions we cann't reuse the transport. if hasOption(k, transportOptions) { this.reuseTransport = false } // Conditions we cann't reuse the cookie jar. if hasOption(k, jarOptions) { this.reuseJar = false } return this }
[ "func", "(", "this", "*", "HttpClient", ")", "WithOption", "(", "k", "int", ",", "v", "interface", "{", "}", ")", "*", "HttpClient", "{", "if", "this", ".", "oneTimeOptions", "==", "nil", "{", "this", ".", "oneTimeOptions", "=", "make", "(", "map", "[", "int", "]", "interface", "{", "}", ")", "\n", "}", "\n", "this", ".", "oneTimeOptions", "[", "k", "]", "=", "v", "\n\n", "// Conditions we cann't reuse the transport.", "if", "hasOption", "(", "k", ",", "transportOptions", ")", "{", "this", ".", "reuseTransport", "=", "false", "\n", "}", "\n\n", "// Conditions we cann't reuse the cookie jar.", "if", "hasOption", "(", "k", ",", "jarOptions", ")", "{", "this", ".", "reuseJar", "=", "false", "\n", "}", "\n\n", "return", "this", "\n", "}" ]
// Temporarily specify an option of the current request.
[ "Temporarily", "specify", "an", "option", "of", "the", "current", "request", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L481-L498
15,526
ddliu/go-httpclient
httpclient.go
WithOptions
func (this *HttpClient) WithOptions(m Map) *HttpClient { options, _ := parseMap(m) for k, v := range options { this.WithOption(k, v) } return this }
go
func (this *HttpClient) WithOptions(m Map) *HttpClient { options, _ := parseMap(m) for k, v := range options { this.WithOption(k, v) } return this }
[ "func", "(", "this", "*", "HttpClient", ")", "WithOptions", "(", "m", "Map", ")", "*", "HttpClient", "{", "options", ",", "_", ":=", "parseMap", "(", "m", ")", "\n", "for", "k", ",", "v", ":=", "range", "options", "{", "this", ".", "WithOption", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "return", "this", "\n", "}" ]
// Temporarily specify multiple options of the current request.
[ "Temporarily", "specify", "multiple", "options", "of", "the", "current", "request", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L501-L508
15,527
ddliu/go-httpclient
httpclient.go
WithHeader
func (this *HttpClient) WithHeader(k string, v string) *HttpClient { if this.oneTimeHeaders == nil { this.oneTimeHeaders = make(map[string]string) } this.oneTimeHeaders[k] = v return this }
go
func (this *HttpClient) WithHeader(k string, v string) *HttpClient { if this.oneTimeHeaders == nil { this.oneTimeHeaders = make(map[string]string) } this.oneTimeHeaders[k] = v return this }
[ "func", "(", "this", "*", "HttpClient", ")", "WithHeader", "(", "k", "string", ",", "v", "string", ")", "*", "HttpClient", "{", "if", "this", ".", "oneTimeHeaders", "==", "nil", "{", "this", ".", "oneTimeHeaders", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "this", ".", "oneTimeHeaders", "[", "k", "]", "=", "v", "\n\n", "return", "this", "\n", "}" ]
// Temporarily specify a header of the current request.
[ "Temporarily", "specify", "a", "header", "of", "the", "current", "request", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L511-L518
15,528
ddliu/go-httpclient
httpclient.go
WithHeaders
func (this *HttpClient) WithHeaders(m map[string]string) *HttpClient { for k, v := range m { this.WithHeader(k, v) } return this }
go
func (this *HttpClient) WithHeaders(m map[string]string) *HttpClient { for k, v := range m { this.WithHeader(k, v) } return this }
[ "func", "(", "this", "*", "HttpClient", ")", "WithHeaders", "(", "m", "map", "[", "string", "]", "string", ")", "*", "HttpClient", "{", "for", "k", ",", "v", ":=", "range", "m", "{", "this", ".", "WithHeader", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "return", "this", "\n", "}" ]
// Temporarily specify multiple headers of the current request.
[ "Temporarily", "specify", "multiple", "headers", "of", "the", "current", "request", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L521-L527
15,529
ddliu/go-httpclient
httpclient.go
WithCookie
func (this *HttpClient) WithCookie(cookies ...*http.Cookie) *HttpClient { this.oneTimeCookies = append(this.oneTimeCookies, cookies...) return this }
go
func (this *HttpClient) WithCookie(cookies ...*http.Cookie) *HttpClient { this.oneTimeCookies = append(this.oneTimeCookies, cookies...) return this }
[ "func", "(", "this", "*", "HttpClient", ")", "WithCookie", "(", "cookies", "...", "*", "http", ".", "Cookie", ")", "*", "HttpClient", "{", "this", ".", "oneTimeCookies", "=", "append", "(", "this", ".", "oneTimeCookies", ",", "cookies", "...", ")", "\n\n", "return", "this", "\n", "}" ]
// Specify cookies of the current request.
[ "Specify", "cookies", "of", "the", "current", "request", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L530-L534
15,530
ddliu/go-httpclient
httpclient.go
Do
func (this *HttpClient) Do(method string, url string, headers map[string]string, body io.Reader) (*Response, error) { options := mergeOptions(defaultOptions, this.options, this.oneTimeOptions) headers = mergeHeaders(this.Headers, headers, this.oneTimeHeaders) cookies := this.oneTimeCookies var transport http.RoundTripper var jar http.CookieJar var err error // transport if this.transport == nil || !this.reuseTransport { transport, err = prepareTransport(options) if err != nil { this.reset() return nil, err } if this.reuseTransport { this.transport = transport } } else { transport = this.transport } // jar if this.jar == nil || !this.reuseJar { jar, err = prepareJar(options) if err != nil { this.reset() return nil, err } if this.reuseJar { this.jar = jar } } else { jar = this.jar } // release lock this.reset() redirect, err := prepareRedirect(options) if err != nil { return nil, err } c := &http.Client{ Transport: transport, CheckRedirect: redirect, Jar: jar, } req, err := prepareRequest(method, url, headers, body, options) if err != nil { return nil, err } if debugEnabled, ok := options[OPT_DEBUG]; ok { if debugEnabled.(bool) { dump, err := httputil.DumpRequestOut(req, true) if err == nil { fmt.Printf("%s\n", dump) } } } if jar != nil { jar.SetCookies(req.URL, cookies) } else { for _, cookie := range cookies { req.AddCookie(cookie) } } res, err := c.Do(req) return &Response{res}, err }
go
func (this *HttpClient) Do(method string, url string, headers map[string]string, body io.Reader) (*Response, error) { options := mergeOptions(defaultOptions, this.options, this.oneTimeOptions) headers = mergeHeaders(this.Headers, headers, this.oneTimeHeaders) cookies := this.oneTimeCookies var transport http.RoundTripper var jar http.CookieJar var err error // transport if this.transport == nil || !this.reuseTransport { transport, err = prepareTransport(options) if err != nil { this.reset() return nil, err } if this.reuseTransport { this.transport = transport } } else { transport = this.transport } // jar if this.jar == nil || !this.reuseJar { jar, err = prepareJar(options) if err != nil { this.reset() return nil, err } if this.reuseJar { this.jar = jar } } else { jar = this.jar } // release lock this.reset() redirect, err := prepareRedirect(options) if err != nil { return nil, err } c := &http.Client{ Transport: transport, CheckRedirect: redirect, Jar: jar, } req, err := prepareRequest(method, url, headers, body, options) if err != nil { return nil, err } if debugEnabled, ok := options[OPT_DEBUG]; ok { if debugEnabled.(bool) { dump, err := httputil.DumpRequestOut(req, true) if err == nil { fmt.Printf("%s\n", dump) } } } if jar != nil { jar.SetCookies(req.URL, cookies) } else { for _, cookie := range cookies { req.AddCookie(cookie) } } res, err := c.Do(req) return &Response{res}, err }
[ "func", "(", "this", "*", "HttpClient", ")", "Do", "(", "method", "string", ",", "url", "string", ",", "headers", "map", "[", "string", "]", "string", ",", "body", "io", ".", "Reader", ")", "(", "*", "Response", ",", "error", ")", "{", "options", ":=", "mergeOptions", "(", "defaultOptions", ",", "this", ".", "options", ",", "this", ".", "oneTimeOptions", ")", "\n", "headers", "=", "mergeHeaders", "(", "this", ".", "Headers", ",", "headers", ",", "this", ".", "oneTimeHeaders", ")", "\n", "cookies", ":=", "this", ".", "oneTimeCookies", "\n\n", "var", "transport", "http", ".", "RoundTripper", "\n", "var", "jar", "http", ".", "CookieJar", "\n", "var", "err", "error", "\n\n", "// transport", "if", "this", ".", "transport", "==", "nil", "||", "!", "this", ".", "reuseTransport", "{", "transport", ",", "err", "=", "prepareTransport", "(", "options", ")", "\n", "if", "err", "!=", "nil", "{", "this", ".", "reset", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "this", ".", "reuseTransport", "{", "this", ".", "transport", "=", "transport", "\n", "}", "\n", "}", "else", "{", "transport", "=", "this", ".", "transport", "\n", "}", "\n\n", "// jar", "if", "this", ".", "jar", "==", "nil", "||", "!", "this", ".", "reuseJar", "{", "jar", ",", "err", "=", "prepareJar", "(", "options", ")", "\n", "if", "err", "!=", "nil", "{", "this", ".", "reset", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "this", ".", "reuseJar", "{", "this", ".", "jar", "=", "jar", "\n", "}", "\n", "}", "else", "{", "jar", "=", "this", ".", "jar", "\n", "}", "\n\n", "// release lock", "this", ".", "reset", "(", ")", "\n\n", "redirect", ",", "err", ":=", "prepareRedirect", "(", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "transport", ",", "CheckRedirect", ":", "redirect", ",", "Jar", ":", "jar", ",", "}", "\n\n", "req", ",", "err", ":=", "prepareRequest", "(", "method", ",", "url", ",", "headers", ",", "body", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "debugEnabled", ",", "ok", ":=", "options", "[", "OPT_DEBUG", "]", ";", "ok", "{", "if", "debugEnabled", ".", "(", "bool", ")", "{", "dump", ",", "err", ":=", "httputil", ".", "DumpRequestOut", "(", "req", ",", "true", ")", "\n", "if", "err", "==", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "dump", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "jar", "!=", "nil", "{", "jar", ".", "SetCookies", "(", "req", ".", "URL", ",", "cookies", ")", "\n", "}", "else", "{", "for", "_", ",", "cookie", ":=", "range", "cookies", "{", "req", ".", "AddCookie", "(", "cookie", ")", "\n", "}", "\n", "}", "\n\n", "res", ",", "err", ":=", "c", ".", "Do", "(", "req", ")", "\n\n", "return", "&", "Response", "{", "res", "}", ",", "err", "\n", "}" ]
// Start a request, and get the response. // // Usually we just need the Get and Post method.
[ "Start", "a", "request", "and", "get", "the", "response", ".", "Usually", "we", "just", "need", "the", "Get", "and", "Post", "method", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L539-L617
15,531
ddliu/go-httpclient
httpclient.go
Head
func (this *HttpClient) Head(url string) (*Response, error) { return this.Do("HEAD", url, nil, nil) }
go
func (this *HttpClient) Head(url string) (*Response, error) { return this.Do("HEAD", url, nil, nil) }
[ "func", "(", "this", "*", "HttpClient", ")", "Head", "(", "url", "string", ")", "(", "*", "Response", ",", "error", ")", "{", "return", "this", ".", "Do", "(", "\"", "\"", ",", "url", ",", "nil", ",", "nil", ")", "\n", "}" ]
// The HEAD request
[ "The", "HEAD", "request" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L620-L622
15,532
ddliu/go-httpclient
httpclient.go
Put
func (this *HttpClient) Put(url string, body io.Reader) (*Response, error) { return this.Do("PUT", url, nil, body) }
go
func (this *HttpClient) Put(url string, body io.Reader) (*Response, error) { return this.Do("PUT", url, nil, body) }
[ "func", "(", "this", "*", "HttpClient", ")", "Put", "(", "url", "string", ",", "body", "io", ".", "Reader", ")", "(", "*", "Response", ",", "error", ")", "{", "return", "this", ".", "Do", "(", "\"", "\"", ",", "url", ",", "nil", ",", "body", ")", "\n", "}" ]
// The PUT request
[ "The", "PUT", "request" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L722-L724
15,533
ddliu/go-httpclient
httpclient.go
Trace
func (this *HttpClient) Trace(url string, params ...map[string]string) (*Response, error) { for _, p := range params { url = addParams(url, toUrlValues(p)) } return this.Do("TRACE", url, nil, nil) }
go
func (this *HttpClient) Trace(url string, params ...map[string]string) (*Response, error) { for _, p := range params { url = addParams(url, toUrlValues(p)) } return this.Do("TRACE", url, nil, nil) }
[ "func", "(", "this", "*", "HttpClient", ")", "Trace", "(", "url", "string", ",", "params", "...", "map", "[", "string", "]", "string", ")", "(", "*", "Response", ",", "error", ")", "{", "for", "_", ",", "p", ":=", "range", "params", "{", "url", "=", "addParams", "(", "url", ",", "toUrlValues", "(", "p", ")", ")", "\n", "}", "\n\n", "return", "this", ".", "Do", "(", "\"", "\"", ",", "url", ",", "nil", ",", "nil", ")", "\n", "}" ]
// The TRACE request
[ "The", "TRACE", "request" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L750-L756
15,534
ddliu/go-httpclient
httpclient.go
Cookies
func (this *HttpClient) Cookies(url_ string) []*http.Cookie { if this.jar != nil { u, _ := url.Parse(url_) return this.jar.Cookies(u) } return nil }
go
func (this *HttpClient) Cookies(url_ string) []*http.Cookie { if this.jar != nil { u, _ := url.Parse(url_) return this.jar.Cookies(u) } return nil }
[ "func", "(", "this", "*", "HttpClient", ")", "Cookies", "(", "url_", "string", ")", "[", "]", "*", "http", ".", "Cookie", "{", "if", "this", ".", "jar", "!=", "nil", "{", "u", ",", "_", ":=", "url", ".", "Parse", "(", "url_", ")", "\n", "return", "this", ".", "jar", ".", "Cookies", "(", "u", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Get cookies of the client jar.
[ "Get", "cookies", "of", "the", "client", "jar", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L768-L775
15,535
ddliu/go-httpclient
httpclient.go
CookieValue
func (this *HttpClient) CookieValue(url_ string, key string) string { for _, c := range this.Cookies(url_) { if c.Name == key { return c.Value } } return "" }
go
func (this *HttpClient) CookieValue(url_ string, key string) string { for _, c := range this.Cookies(url_) { if c.Name == key { return c.Value } } return "" }
[ "func", "(", "this", "*", "HttpClient", ")", "CookieValue", "(", "url_", "string", ",", "key", "string", ")", "string", "{", "for", "_", ",", "c", ":=", "range", "this", ".", "Cookies", "(", "url_", ")", "{", "if", "c", ".", "Name", "==", "key", "{", "return", "c", ".", "Value", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// Get cookie value of a specified cookie name.
[ "Get", "cookie", "value", "of", "a", "specified", "cookie", "name", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/httpclient.go#L789-L797
15,536
ddliu/go-httpclient
error.go
Error
func (this Error) Error() string { return fmt.Sprintf("httpclient #%d: %s", this.Code, this.Message) }
go
func (this Error) Error() string { return fmt.Sprintf("httpclient #%d: %s", this.Code, this.Message) }
[ "func", "(", "this", "Error", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "this", ".", "Code", ",", "this", ".", "Message", ")", "\n", "}" ]
// Implement the error interface
[ "Implement", "the", "error", "interface" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/error.go#L27-L29
15,537
ddliu/go-httpclient
error.go
IsTimeoutError
func IsTimeoutError(err error) bool { if err == nil { return false } // TODO: does not work? if e, ok := err.(net.Error); ok && e.Timeout() { return true } // TODO: make it reliable if strings.Contains(err.Error(), "timeout") { return true } return false }
go
func IsTimeoutError(err error) bool { if err == nil { return false } // TODO: does not work? if e, ok := err.(net.Error); ok && e.Timeout() { return true } // TODO: make it reliable if strings.Contains(err.Error(), "timeout") { return true } return false }
[ "func", "IsTimeoutError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "// TODO: does not work?", "if", "e", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "e", ".", "Timeout", "(", ")", "{", "return", "true", "\n", "}", "\n\n", "// TODO: make it reliable", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Check a timeout error.
[ "Check", "a", "timeout", "error", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/error.go#L44-L60
15,538
ddliu/go-httpclient
error.go
IsRedirectError
func IsRedirectError(err error) bool { if err == nil { return false } // TODO: does not work? if getErrorCode(err) == ERR_REDIRECT_POLICY { return true } // TODO: make it reliable if strings.Contains(err.Error(), "redirect") { return true } return false }
go
func IsRedirectError(err error) bool { if err == nil { return false } // TODO: does not work? if getErrorCode(err) == ERR_REDIRECT_POLICY { return true } // TODO: make it reliable if strings.Contains(err.Error(), "redirect") { return true } return false }
[ "func", "IsRedirectError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "// TODO: does not work?", "if", "getErrorCode", "(", "err", ")", "==", "ERR_REDIRECT_POLICY", "{", "return", "true", "\n", "}", "\n\n", "// TODO: make it reliable", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Check a redirect error
[ "Check", "a", "redirect", "error" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/error.go#L63-L79
15,539
ddliu/go-httpclient
util.go
addParams
func addParams(url_ string, params url.Values) string { if len(params) == 0 { return url_ } if !strings.Contains(url_, "?") { url_ += "?" } if strings.HasSuffix(url_, "?") || strings.HasSuffix(url_, "&") { url_ += params.Encode() } else { url_ += "&" + params.Encode() } return url_ }
go
func addParams(url_ string, params url.Values) string { if len(params) == 0 { return url_ } if !strings.Contains(url_, "?") { url_ += "?" } if strings.HasSuffix(url_, "?") || strings.HasSuffix(url_, "&") { url_ += params.Encode() } else { url_ += "&" + params.Encode() } return url_ }
[ "func", "addParams", "(", "url_", "string", ",", "params", "url", ".", "Values", ")", "string", "{", "if", "len", "(", "params", ")", "==", "0", "{", "return", "url_", "\n", "}", "\n\n", "if", "!", "strings", ".", "Contains", "(", "url_", ",", "\"", "\"", ")", "{", "url_", "+=", "\"", "\"", "\n", "}", "\n\n", "if", "strings", ".", "HasSuffix", "(", "url_", ",", "\"", "\"", ")", "||", "strings", ".", "HasSuffix", "(", "url_", ",", "\"", "\"", ")", "{", "url_", "+=", "params", ".", "Encode", "(", ")", "\n", "}", "else", "{", "url_", "+=", "\"", "\"", "+", "params", ".", "Encode", "(", ")", "\n", "}", "\n\n", "return", "url_", "\n", "}" ]
// Add params to a url string.
[ "Add", "params", "to", "a", "url", "string", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/util.go#L16-L32
15,540
ddliu/go-httpclient
util.go
addFormFile
func addFormFile(writer *multipart.Writer, name, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := writer.CreateFormFile(name, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err }
go
func addFormFile(writer *multipart.Writer, name, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := writer.CreateFormFile(name, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err }
[ "func", "addFormFile", "(", "writer", "*", "multipart", ".", "Writer", ",", "name", ",", "path", "string", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "part", ",", "err", ":=", "writer", ".", "CreateFormFile", "(", "name", ",", "filepath", ".", "Base", "(", "path", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "part", ",", "file", ")", "\n\n", "return", "err", "\n", "}" ]
// Add a file to a multipart writer.
[ "Add", "a", "file", "to", "a", "multipart", "writer", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/util.go#L35-L49
15,541
ddliu/go-httpclient
util.go
Option
func Option(o map[string]interface{}) map[int]interface{} { rst := make(map[int]interface{}) for k, v := range o { k := "OPT_" + strings.ToUpper(k) if num, ok := CONST[k]; ok { rst[num] = v } } return rst }
go
func Option(o map[string]interface{}) map[int]interface{} { rst := make(map[int]interface{}) for k, v := range o { k := "OPT_" + strings.ToUpper(k) if num, ok := CONST[k]; ok { rst[num] = v } } return rst }
[ "func", "Option", "(", "o", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "int", "]", "interface", "{", "}", "{", "rst", ":=", "make", "(", "map", "[", "int", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "o", "{", "k", ":=", "\"", "\"", "+", "strings", ".", "ToUpper", "(", "k", ")", "\n", "if", "num", ",", "ok", ":=", "CONST", "[", "k", "]", ";", "ok", "{", "rst", "[", "num", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "rst", "\n", "}" ]
// Convert options with string keys to desired format.
[ "Convert", "options", "with", "string", "keys", "to", "desired", "format", "." ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/util.go#L52-L62
15,542
ddliu/go-httpclient
util.go
checkParamFile
func checkParamFile(params url.Values) bool { for k, _ := range params { if k[0] == '@' { return true } } return false }
go
func checkParamFile(params url.Values) bool { for k, _ := range params { if k[0] == '@' { return true } } return false }
[ "func", "checkParamFile", "(", "params", "url", ".", "Values", ")", "bool", "{", "for", "k", ",", "_", ":=", "range", "params", "{", "if", "k", "[", "0", "]", "==", "'@'", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Does the params contain a file?
[ "Does", "the", "params", "contain", "a", "file?" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/util.go#L91-L99
15,543
ddliu/go-httpclient
util.go
hasOption
func hasOption(opt int, options []int) bool { for _, v := range options { if opt == v { return true } } return false }
go
func hasOption(opt int, options []int) bool { for _, v := range options { if opt == v { return true } } return false }
[ "func", "hasOption", "(", "opt", "int", ",", "options", "[", "]", "int", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "options", "{", "if", "opt", "==", "v", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Is opt in options?
[ "Is", "opt", "in", "options?" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/util.go#L102-L110
15,544
ddliu/go-httpclient
util.go
parseMap
func parseMap(m Map) (map[int]interface{}, map[string]string) { var options = make(map[int]interface{}) var headers = make(map[string]string) if m == nil { return options, headers } for k, v := range m { // integer is option if kInt, ok := k.(int); ok { // don't need to validate options[kInt] = v } else if kString, ok := k.(string); ok { kStringUpper := strings.ToUpper(kString) if kInt, ok := CONST[kStringUpper]; ok { options[kInt] = v } else { // it should be header, but we still need to validate it's type if vString, ok := v.(string); ok { headers[kString] = vString } } } } return options, headers }
go
func parseMap(m Map) (map[int]interface{}, map[string]string) { var options = make(map[int]interface{}) var headers = make(map[string]string) if m == nil { return options, headers } for k, v := range m { // integer is option if kInt, ok := k.(int); ok { // don't need to validate options[kInt] = v } else if kString, ok := k.(string); ok { kStringUpper := strings.ToUpper(kString) if kInt, ok := CONST[kStringUpper]; ok { options[kInt] = v } else { // it should be header, but we still need to validate it's type if vString, ok := v.(string); ok { headers[kString] = vString } } } } return options, headers }
[ "func", "parseMap", "(", "m", "Map", ")", "(", "map", "[", "int", "]", "interface", "{", "}", ",", "map", "[", "string", "]", "string", ")", "{", "var", "options", "=", "make", "(", "map", "[", "int", "]", "interface", "{", "}", ")", "\n", "var", "headers", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n\n", "if", "m", "==", "nil", "{", "return", "options", ",", "headers", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "m", "{", "// integer is option", "if", "kInt", ",", "ok", ":=", "k", ".", "(", "int", ")", ";", "ok", "{", "// don't need to validate", "options", "[", "kInt", "]", "=", "v", "\n", "}", "else", "if", "kString", ",", "ok", ":=", "k", ".", "(", "string", ")", ";", "ok", "{", "kStringUpper", ":=", "strings", ".", "ToUpper", "(", "kString", ")", "\n", "if", "kInt", ",", "ok", ":=", "CONST", "[", "kStringUpper", "]", ";", "ok", "{", "options", "[", "kInt", "]", "=", "v", "\n", "}", "else", "{", "// it should be header, but we still need to validate it's type", "if", "vString", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "headers", "[", "kString", "]", "=", "vString", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "options", ",", "headers", "\n", "}" ]
// Parse the Map, return options and headers
[ "Parse", "the", "Map", "return", "options", "and", "headers" ]
095b03c7bbcc67af3414611b53c2bc2e75529269
https://github.com/ddliu/go-httpclient/blob/095b03c7bbcc67af3414611b53c2bc2e75529269/util.go#L116-L143
15,545
rickar/cal
holiday_defs_dk.go
AddDanishHolidays
func AddDanishHolidays(c *Calendar) { c.AddHoliday( DKNytaarsdag, DKSkaertorsdag, DKLangfredag, DKPaaskedag, DKAndenPaaskedag, DKStoreBededag, DKKristiHimmelfartsdag, DKPinsedag, DKAndenPinsedag, DKJuledag, DKAndenJuledag, ) }
go
func AddDanishHolidays(c *Calendar) { c.AddHoliday( DKNytaarsdag, DKSkaertorsdag, DKLangfredag, DKPaaskedag, DKAndenPaaskedag, DKStoreBededag, DKKristiHimmelfartsdag, DKPinsedag, DKAndenPinsedag, DKJuledag, DKAndenJuledag, ) }
[ "func", "AddDanishHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "DKNytaarsdag", ",", "DKSkaertorsdag", ",", "DKLangfredag", ",", "DKPaaskedag", ",", "DKAndenPaaskedag", ",", "DKStoreBededag", ",", "DKKristiHimmelfartsdag", ",", "DKPinsedag", ",", "DKAndenPinsedag", ",", "DKJuledag", ",", "DKAndenJuledag", ",", ")", "\n", "}" ]
// AddDanishHolidays adds all Danish holidays to the Calendar
[ "AddDanishHolidays", "adds", "all", "Danish", "holidays", "to", "the", "Calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_dk.go#L27-L41
15,546
rickar/cal
holiday_defs_gb.go
AddBritishHolidays
func AddBritishHolidays(c *Calendar) { c.AddHoliday( GBNewYear, GBGoodFriday, GBEasterMonday, GBEarlyMay, GBSpringHoliday, GBSummerHoliday, GBChristmasDay, GBBoxingDay, ) }
go
func AddBritishHolidays(c *Calendar) { c.AddHoliday( GBNewYear, GBGoodFriday, GBEasterMonday, GBEarlyMay, GBSpringHoliday, GBSummerHoliday, GBChristmasDay, GBBoxingDay, ) }
[ "func", "AddBritishHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "GBNewYear", ",", "GBGoodFriday", ",", "GBEasterMonday", ",", "GBEarlyMay", ",", "GBSpringHoliday", ",", "GBSummerHoliday", ",", "GBChristmasDay", ",", "GBBoxingDay", ",", ")", "\n", "}" ]
// AddBritishHolidays adds all British holidays to the Calender
[ "AddBritishHolidays", "adds", "all", "British", "holidays", "to", "the", "Calender" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_gb.go#L18-L29
15,547
rickar/cal
holiday_defs_gb.go
calculateNewYearsHoliday
func calculateNewYearsHoliday(year int, loc *time.Location) (time.Month, int) { day := time.Date(year, time.January, 1, 0, 0, 0, 0, loc) switch day.Weekday() { case time.Saturday: day = day.AddDate(0, 0, 2) case time.Sunday: day = day.AddDate(0, 0, 1) } return time.January, day.Day() }
go
func calculateNewYearsHoliday(year int, loc *time.Location) (time.Month, int) { day := time.Date(year, time.January, 1, 0, 0, 0, 0, loc) switch day.Weekday() { case time.Saturday: day = day.AddDate(0, 0, 2) case time.Sunday: day = day.AddDate(0, 0, 1) } return time.January, day.Day() }
[ "func", "calculateNewYearsHoliday", "(", "year", "int", ",", "loc", "*", "time", ".", "Location", ")", "(", "time", ".", "Month", ",", "int", ")", "{", "day", ":=", "time", ".", "Date", "(", "year", ",", "time", ".", "January", ",", "1", ",", "0", ",", "0", ",", "0", ",", "0", ",", "loc", ")", "\n", "switch", "day", ".", "Weekday", "(", ")", "{", "case", "time", ".", "Saturday", ":", "day", "=", "day", ".", "AddDate", "(", "0", ",", "0", ",", "2", ")", "\n", "case", "time", ".", "Sunday", ":", "day", "=", "day", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", "\n", "}", "\n", "return", "time", ".", "January", ",", "day", ".", "Day", "(", ")", "\n", "}" ]
// NewYearsDay is the 1st of January unless the 1st is a Saturday or Sunday // in which case it occurs on the following Monday.
[ "NewYearsDay", "is", "the", "1st", "of", "January", "unless", "the", "1st", "is", "a", "Saturday", "or", "Sunday", "in", "which", "case", "it", "occurs", "on", "the", "following", "Monday", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_gb.go#L33-L42
15,548
rickar/cal
holiday_defs_nz.go
AddNewZealandHoliday
func AddNewZealandHoliday(c *Calendar) { c.AddHoliday( NZNewYear, NZDayAfterNewYear, NZGoodFriday, NZEasterMonday, NZAnzacDay, NZChristmasDay, NZBoxingDays, NZQueensBirthday, NZLabourDay, NZWanagiDay, ) }
go
func AddNewZealandHoliday(c *Calendar) { c.AddHoliday( NZNewYear, NZDayAfterNewYear, NZGoodFriday, NZEasterMonday, NZAnzacDay, NZChristmasDay, NZBoxingDays, NZQueensBirthday, NZLabourDay, NZWanagiDay, ) }
[ "func", "AddNewZealandHoliday", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "NZNewYear", ",", "NZDayAfterNewYear", ",", "NZGoodFriday", ",", "NZEasterMonday", ",", "NZAnzacDay", ",", "NZChristmasDay", ",", "NZBoxingDays", ",", "NZQueensBirthday", ",", "NZLabourDay", ",", "NZWanagiDay", ",", ")", "\n", "}" ]
// AddNewZealandHoliday adds all New Zeland holidays
[ "AddNewZealandHoliday", "adds", "all", "New", "Zeland", "holidays" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_nz.go#L24-L37
15,549
rickar/cal
holiday_defs_au.go
AddAustralianHolidays
func AddAustralianHolidays(c *Calendar) { c.AddHoliday( AUNewYear, AUAustralianDay, AUGoodFriday, AUEasterMonday, AUAnzacDay, AUChristmasDay, AUBoxingDays, AUQueenBirthDay, AULabourDay, ) }
go
func AddAustralianHolidays(c *Calendar) { c.AddHoliday( AUNewYear, AUAustralianDay, AUGoodFriday, AUEasterMonday, AUAnzacDay, AUChristmasDay, AUBoxingDays, AUQueenBirthDay, AULabourDay, ) }
[ "func", "AddAustralianHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "AUNewYear", ",", "AUAustralianDay", ",", "AUGoodFriday", ",", "AUEasterMonday", ",", "AUAnzacDay", ",", "AUChristmasDay", ",", "AUBoxingDays", ",", "AUQueenBirthDay", ",", "AULabourDay", ",", ")", "\n", "}" ]
// AddAustralianHolidays adds all Australian holidays
[ "AddAustralianHolidays", "adds", "all", "Australian", "holidays" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_au.go#L23-L35
15,550
rickar/cal
holiday_defs_au.go
closestMonday
func closestMonday(date time.Time) time.Time { wd := date.Weekday() if wd == 0 { date = date.AddDate(0, 0, 1) } if wd == 6 { date = date.AddDate(0, 0, 2) } return date }
go
func closestMonday(date time.Time) time.Time { wd := date.Weekday() if wd == 0 { date = date.AddDate(0, 0, 1) } if wd == 6 { date = date.AddDate(0, 0, 2) } return date }
[ "func", "closestMonday", "(", "date", "time", ".", "Time", ")", "time", ".", "Time", "{", "wd", ":=", "date", ".", "Weekday", "(", ")", "\n", "if", "wd", "==", "0", "{", "date", "=", "date", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", "\n", "}", "\n\n", "if", "wd", "==", "6", "{", "date", "=", "date", ".", "AddDate", "(", "0", ",", "0", ",", "2", ")", "\n", "}", "\n\n", "return", "date", "\n", "}" ]
// closestMonday returns the closest Monday from a giving date
[ "closestMonday", "returns", "the", "closest", "Monday", "from", "a", "giving", "date" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_au.go#L53-L64
15,551
rickar/cal
holiday_defs_us.go
AddUsHolidays
func AddUsHolidays(cal *Calendar) { cal.AddHoliday( USNewYear, USMLK, USPresidents, USMemorial, USIndependence, USLabor, USColumbus, USVeterans, USThanksgiving, USChristmas, ) }
go
func AddUsHolidays(cal *Calendar) { cal.AddHoliday( USNewYear, USMLK, USPresidents, USMemorial, USIndependence, USLabor, USColumbus, USVeterans, USThanksgiving, USChristmas, ) }
[ "func", "AddUsHolidays", "(", "cal", "*", "Calendar", ")", "{", "cal", ".", "AddHoliday", "(", "USNewYear", ",", "USMLK", ",", "USPresidents", ",", "USMemorial", ",", "USIndependence", ",", "USLabor", ",", "USColumbus", ",", "USVeterans", ",", "USThanksgiving", ",", "USChristmas", ",", ")", "\n", "}" ]
// AddUsHolidays adds all US holidays to the Calendar
[ "AddUsHolidays", "adds", "all", "US", "holidays", "to", "the", "Calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_us.go#L20-L33
15,552
rickar/cal
holiday_defs_no.go
AddNorwegianHolidays
func AddNorwegianHolidays(c *Calendar) { c.AddHoliday( NOFoersteNyttaarsdag, NOSkjaertorsdag, NOLangfredag, NOFoerstePaaskedag, NOAndrePaaskedag, NOArbeiderenesdag, NOGrunnlovsdag, NOKristihimmelfartsdag, NOFoerstePinsedag, NOAndrePinsedag, NOFoersteJuledag, NOAndreJuledag, ) }
go
func AddNorwegianHolidays(c *Calendar) { c.AddHoliday( NOFoersteNyttaarsdag, NOSkjaertorsdag, NOLangfredag, NOFoerstePaaskedag, NOAndrePaaskedag, NOArbeiderenesdag, NOGrunnlovsdag, NOKristihimmelfartsdag, NOFoerstePinsedag, NOAndrePinsedag, NOFoersteJuledag, NOAndreJuledag, ) }
[ "func", "AddNorwegianHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "NOFoersteNyttaarsdag", ",", "NOSkjaertorsdag", ",", "NOLangfredag", ",", "NOFoerstePaaskedag", ",", "NOAndrePaaskedag", ",", "NOArbeiderenesdag", ",", "NOGrunnlovsdag", ",", "NOKristihimmelfartsdag", ",", "NOFoerstePinsedag", ",", "NOAndrePinsedag", ",", "NOFoersteJuledag", ",", "NOAndreJuledag", ",", ")", "\n", "}" ]
// AddNorwegianHolidays adds all Norwegian holidays to Calendar
[ "AddNorwegianHolidays", "adds", "all", "Norwegian", "holidays", "to", "Calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_no.go#L28-L43
15,553
rickar/cal
holiday.go
NewHoliday
func NewHoliday(month time.Month, day int) Holiday { return Holiday{Month: month, Day: day} }
go
func NewHoliday(month time.Month, day int) Holiday { return Holiday{Month: month, Day: day} }
[ "func", "NewHoliday", "(", "month", "time", ".", "Month", ",", "day", "int", ")", "Holiday", "{", "return", "Holiday", "{", "Month", ":", "month", ",", "Day", ":", "day", "}", "\n", "}" ]
// NewHoliday creates a new Holiday instance for an exact day of a month.
[ "NewHoliday", "creates", "a", "new", "Holiday", "instance", "for", "an", "exact", "day", "of", "a", "month", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday.go#L46-L48
15,554
rickar/cal
holiday.go
NewHolidayExact
func NewHolidayExact(month time.Month, day int, year int) Holiday { return Holiday{Month: month, Day: day, Year: year} }
go
func NewHolidayExact(month time.Month, day int, year int) Holiday { return Holiday{Month: month, Day: day, Year: year} }
[ "func", "NewHolidayExact", "(", "month", "time", ".", "Month", ",", "day", "int", ",", "year", "int", ")", "Holiday", "{", "return", "Holiday", "{", "Month", ":", "month", ",", "Day", ":", "day", ",", "Year", ":", "year", "}", "\n", "}" ]
// NewHolidayExact creates a new Holiday instance for an exact day of a month and year.
[ "NewHolidayExact", "creates", "a", "new", "Holiday", "instance", "for", "an", "exact", "day", "of", "a", "month", "and", "year", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday.go#L51-L53
15,555
rickar/cal
holiday.go
NewHolidayFloat
func NewHolidayFloat(month time.Month, weekday time.Weekday, offset int) Holiday { return Holiday{Month: month, Weekday: weekday, Offset: offset} }
go
func NewHolidayFloat(month time.Month, weekday time.Weekday, offset int) Holiday { return Holiday{Month: month, Weekday: weekday, Offset: offset} }
[ "func", "NewHolidayFloat", "(", "month", "time", ".", "Month", ",", "weekday", "time", ".", "Weekday", ",", "offset", "int", ")", "Holiday", "{", "return", "Holiday", "{", "Month", ":", "month", ",", "Weekday", ":", "weekday", ",", "Offset", ":", "offset", "}", "\n", "}" ]
// NewHolidayFloat creates a new Holiday instance for an offset-based day of // a month.
[ "NewHolidayFloat", "creates", "a", "new", "Holiday", "instance", "for", "an", "offset", "-", "based", "day", "of", "a", "month", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday.go#L57-L59
15,556
rickar/cal
holiday.go
matches
func (h *Holiday) matches(date time.Time) bool { if h.Func != nil && (date.Year() != h.lastYear || date.Location() != h.lastLoc) { h.Month, h.Day = h.Func(date.Year(), date.Location()) h.lastYear = date.Year() h.lastLoc = date.Location() } if h.Month > 0 { if date.Month() != h.Month { return false } if h.Year > 0 && date.Year() != h.Year { return false } if h.Day > 0 { return date.Day() == h.Day } if h.Weekday > 0 && h.Offset != 0 { return IsWeekdayN(date, h.Weekday, h.Offset) } } else if h.Offset > 0 { return date.YearDay() == h.Offset } return false }
go
func (h *Holiday) matches(date time.Time) bool { if h.Func != nil && (date.Year() != h.lastYear || date.Location() != h.lastLoc) { h.Month, h.Day = h.Func(date.Year(), date.Location()) h.lastYear = date.Year() h.lastLoc = date.Location() } if h.Month > 0 { if date.Month() != h.Month { return false } if h.Year > 0 && date.Year() != h.Year { return false } if h.Day > 0 { return date.Day() == h.Day } if h.Weekday > 0 && h.Offset != 0 { return IsWeekdayN(date, h.Weekday, h.Offset) } } else if h.Offset > 0 { return date.YearDay() == h.Offset } return false }
[ "func", "(", "h", "*", "Holiday", ")", "matches", "(", "date", "time", ".", "Time", ")", "bool", "{", "if", "h", ".", "Func", "!=", "nil", "&&", "(", "date", ".", "Year", "(", ")", "!=", "h", ".", "lastYear", "||", "date", ".", "Location", "(", ")", "!=", "h", ".", "lastLoc", ")", "{", "h", ".", "Month", ",", "h", ".", "Day", "=", "h", ".", "Func", "(", "date", ".", "Year", "(", ")", ",", "date", ".", "Location", "(", ")", ")", "\n", "h", ".", "lastYear", "=", "date", ".", "Year", "(", ")", "\n", "h", ".", "lastLoc", "=", "date", ".", "Location", "(", ")", "\n", "}", "\n\n", "if", "h", ".", "Month", ">", "0", "{", "if", "date", ".", "Month", "(", ")", "!=", "h", ".", "Month", "{", "return", "false", "\n", "}", "\n", "if", "h", ".", "Year", ">", "0", "&&", "date", ".", "Year", "(", ")", "!=", "h", ".", "Year", "{", "return", "false", "\n", "}", "\n", "if", "h", ".", "Day", ">", "0", "{", "return", "date", ".", "Day", "(", ")", "==", "h", ".", "Day", "\n", "}", "\n", "if", "h", ".", "Weekday", ">", "0", "&&", "h", ".", "Offset", "!=", "0", "{", "return", "IsWeekdayN", "(", "date", ",", "h", ".", "Weekday", ",", "h", ".", "Offset", ")", "\n", "}", "\n", "}", "else", "if", "h", ".", "Offset", ">", "0", "{", "return", "date", ".", "YearDay", "(", ")", "==", "h", ".", "Offset", "\n", "}", "\n", "return", "false", "\n", "}" ]
// matches determines whether the given date is the one referred to by the // Holiday.
[ "matches", "determines", "whether", "the", "given", "date", "is", "the", "one", "referred", "to", "by", "the", "Holiday", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday.go#L69-L94
15,557
rickar/cal
holiday_defs_se.go
AddSwedishHolidays
func AddSwedishHolidays(c *Calendar) { c.AddHoliday( SENyarsdagen, SETrettondedagJul, SELangfredagen, SEPaskdagen, SEAnnandagPask, SEForstaMaj, SEKristiHimmelfardsdag, SEPingstdagen, SENationaldagen, SEMidsommarafton, SEMidsommardagen, SEAllaHelgonsDag, SEJulafton, SEJuldagen, SEAnnandagJul, SENewYearsEve, ) }
go
func AddSwedishHolidays(c *Calendar) { c.AddHoliday( SENyarsdagen, SETrettondedagJul, SELangfredagen, SEPaskdagen, SEAnnandagPask, SEForstaMaj, SEKristiHimmelfardsdag, SEPingstdagen, SENationaldagen, SEMidsommarafton, SEMidsommardagen, SEAllaHelgonsDag, SEJulafton, SEJuldagen, SEAnnandagJul, SENewYearsEve, ) }
[ "func", "AddSwedishHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "SENyarsdagen", ",", "SETrettondedagJul", ",", "SELangfredagen", ",", "SEPaskdagen", ",", "SEAnnandagPask", ",", "SEForstaMaj", ",", "SEKristiHimmelfardsdag", ",", "SEPingstdagen", ",", "SENationaldagen", ",", "SEMidsommarafton", ",", "SEMidsommardagen", ",", "SEAllaHelgonsDag", ",", "SEJulafton", ",", "SEJuldagen", ",", "SEAnnandagJul", ",", "SENewYearsEve", ",", ")", "\n", "}" ]
// AddSwedishHolidays adds all Swedish holidays to the Calendar
[ "AddSwedishHolidays", "adds", "all", "Swedish", "holidays", "to", "the", "Calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_se.go#L31-L50
15,558
rickar/cal
holiday_defs_be.go
AddBelgiumHolidays
func AddBelgiumHolidays(c *Calendar) { c.AddHoliday( BENieuwjaar, BEPaasmaandag, BEDagVanDeArbeid, BEOnzeLieveHeerHemelvaart, BEPinkstermaandag, BENationaleFeestdag, BEOnzeLieveVrouwHemelvaart, BEAllerheiligen, BEWapenstilstand, BEKerstmis, ) }
go
func AddBelgiumHolidays(c *Calendar) { c.AddHoliday( BENieuwjaar, BEPaasmaandag, BEDagVanDeArbeid, BEOnzeLieveHeerHemelvaart, BEPinkstermaandag, BENationaleFeestdag, BEOnzeLieveVrouwHemelvaart, BEAllerheiligen, BEWapenstilstand, BEKerstmis, ) }
[ "func", "AddBelgiumHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "BENieuwjaar", ",", "BEPaasmaandag", ",", "BEDagVanDeArbeid", ",", "BEOnzeLieveHeerHemelvaart", ",", "BEPinkstermaandag", ",", "BENationaleFeestdag", ",", "BEOnzeLieveVrouwHemelvaart", ",", "BEAllerheiligen", ",", "BEWapenstilstand", ",", "BEKerstmis", ",", ")", "\n", "}" ]
// AddBelgiumHolidays adds all Belgium holidays to the Calendar
[ "AddBelgiumHolidays", "adds", "all", "Belgium", "holidays", "to", "the", "Calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_be.go#L20-L33
15,559
rickar/cal
holiday_defs_ecb.go
AddEcbHolidays
func AddEcbHolidays(c *Calendar) { c.AddHoliday( ECBGoodFriday, ECBEasterMonday, ECBNewYearsDay, ECBLabourDay, ECBChristmasDay, ECBChristmasHoliday, ) }
go
func AddEcbHolidays(c *Calendar) { c.AddHoliday( ECBGoodFriday, ECBEasterMonday, ECBNewYearsDay, ECBLabourDay, ECBChristmasDay, ECBChristmasHoliday, ) }
[ "func", "AddEcbHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "ECBGoodFriday", ",", "ECBEasterMonday", ",", "ECBNewYearsDay", ",", "ECBLabourDay", ",", "ECBChristmasDay", ",", "ECBChristmasHoliday", ",", ")", "\n", "}" ]
// AddEcbHolidays adds all ECB Target2 holidays to the calendar
[ "AddEcbHolidays", "adds", "all", "ECB", "Target2", "holidays", "to", "the", "calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_ecb.go#L16-L25
15,560
rickar/cal
holiday_defs_nl.go
AddDutchHolidays
func AddDutchHolidays(c *Calendar) { c.AddHoliday( NLNieuwjaar, NLGoedeVrijdag, NLPaasMaandag, NLKoningsDag, NLBevrijdingsDag, NLHemelvaart, NLPinksterMaandag, NLEersteKerstdag, NLTweedeKerstdag, ) }
go
func AddDutchHolidays(c *Calendar) { c.AddHoliday( NLNieuwjaar, NLGoedeVrijdag, NLPaasMaandag, NLKoningsDag, NLBevrijdingsDag, NLHemelvaart, NLPinksterMaandag, NLEersteKerstdag, NLTweedeKerstdag, ) }
[ "func", "AddDutchHolidays", "(", "c", "*", "Calendar", ")", "{", "c", ".", "AddHoliday", "(", "NLNieuwjaar", ",", "NLGoedeVrijdag", ",", "NLPaasMaandag", ",", "NLKoningsDag", ",", "NLBevrijdingsDag", ",", "NLHemelvaart", ",", "NLPinksterMaandag", ",", "NLEersteKerstdag", ",", "NLTweedeKerstdag", ",", ")", "\n", "}" ]
// AddDutchHolidays adds all Dutch holidays to the Calendar
[ "AddDutchHolidays", "adds", "all", "Dutch", "holidays", "to", "the", "Calendar" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/holiday_defs_nl.go#L19-L31
15,561
rickar/cal
cal.go
IsWeekend
func IsWeekend(date time.Time) bool { day := date.Weekday() return day == time.Saturday || day == time.Sunday }
go
func IsWeekend(date time.Time) bool { day := date.Weekday() return day == time.Saturday || day == time.Sunday }
[ "func", "IsWeekend", "(", "date", "time", ".", "Time", ")", "bool", "{", "day", ":=", "date", ".", "Weekday", "(", ")", "\n", "return", "day", "==", "time", ".", "Saturday", "||", "day", "==", "time", ".", "Sunday", "\n", "}" ]
// IsWeekend reports whether the given date falls on a weekend.
[ "IsWeekend", "reports", "whether", "the", "given", "date", "falls", "on", "a", "weekend", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L11-L14
15,562
rickar/cal
cal.go
MonthStart
func MonthStart(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), 1, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location()) }
go
func MonthStart(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), 1, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location()) }
[ "func", "MonthStart", "(", "t", "time", ".", "Time", ")", "time", ".", "Time", "{", "return", "time", ".", "Date", "(", "t", ".", "Year", "(", ")", ",", "t", ".", "Month", "(", ")", ",", "1", ",", "t", ".", "Hour", "(", ")", ",", "t", ".", "Minute", "(", ")", ",", "t", ".", "Second", "(", ")", ",", "t", ".", "Nanosecond", "(", ")", ",", "t", ".", "Location", "(", ")", ")", "\n", "}" ]
// MonthStart reports the starting day of the month in t. The time portion is // unchanged.
[ "MonthStart", "reports", "the", "starting", "day", "of", "the", "month", "in", "t", ".", "The", "time", "portion", "is", "unchanged", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L53-L56
15,563
rickar/cal
cal.go
NewCalendar
func NewCalendar() *Calendar { c := &Calendar{} for i := range c.holidays { c.holidays[i] = make([]Holiday, 0, 2) } c.workday[time.Monday] = true c.workday[time.Tuesday] = true c.workday[time.Wednesday] = true c.workday[time.Thursday] = true c.workday[time.Friday] = true return c }
go
func NewCalendar() *Calendar { c := &Calendar{} for i := range c.holidays { c.holidays[i] = make([]Holiday, 0, 2) } c.workday[time.Monday] = true c.workday[time.Tuesday] = true c.workday[time.Wednesday] = true c.workday[time.Thursday] = true c.workday[time.Friday] = true return c }
[ "func", "NewCalendar", "(", ")", "*", "Calendar", "{", "c", ":=", "&", "Calendar", "{", "}", "\n", "for", "i", ":=", "range", "c", ".", "holidays", "{", "c", ".", "holidays", "[", "i", "]", "=", "make", "(", "[", "]", "Holiday", ",", "0", ",", "2", ")", "\n", "}", "\n", "c", ".", "workday", "[", "time", ".", "Monday", "]", "=", "true", "\n", "c", ".", "workday", "[", "time", ".", "Tuesday", "]", "=", "true", "\n", "c", ".", "workday", "[", "time", ".", "Wednesday", "]", "=", "true", "\n", "c", ".", "workday", "[", "time", ".", "Thursday", "]", "=", "true", "\n", "c", ".", "workday", "[", "time", ".", "Friday", "]", "=", "true", "\n", "return", "c", "\n", "}" ]
// NewCalendar creates a new Calendar with no holidays defined // and work days of Monday through Friday.
[ "NewCalendar", "creates", "a", "new", "Calendar", "with", "no", "holidays", "defined", "and", "work", "days", "of", "Monday", "through", "Friday", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L109-L120
15,564
rickar/cal
cal.go
AddHoliday
func (c *Calendar) AddHoliday(h ...Holiday) { for _, hd := range h { c.holidays[hd.Month] = append(c.holidays[hd.Month], hd) } }
go
func (c *Calendar) AddHoliday(h ...Holiday) { for _, hd := range h { c.holidays[hd.Month] = append(c.holidays[hd.Month], hd) } }
[ "func", "(", "c", "*", "Calendar", ")", "AddHoliday", "(", "h", "...", "Holiday", ")", "{", "for", "_", ",", "hd", ":=", "range", "h", "{", "c", ".", "holidays", "[", "hd", ".", "Month", "]", "=", "append", "(", "c", ".", "holidays", "[", "hd", ".", "Month", "]", ",", "hd", ")", "\n", "}", "\n", "}" ]
// AddHoliday adds a holiday to the calendar's list.
[ "AddHoliday", "adds", "a", "holiday", "to", "the", "calendar", "s", "list", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L123-L127
15,565
rickar/cal
cal.go
SetWorkday
func (c *Calendar) SetWorkday(day time.Weekday, workday bool) { c.workday[day] = workday }
go
func (c *Calendar) SetWorkday(day time.Weekday, workday bool) { c.workday[day] = workday }
[ "func", "(", "c", "*", "Calendar", ")", "SetWorkday", "(", "day", "time", ".", "Weekday", ",", "workday", "bool", ")", "{", "c", ".", "workday", "[", "day", "]", "=", "workday", "\n", "}" ]
// SetWorkday changes the given day's status as a standard working day
[ "SetWorkday", "changes", "the", "given", "day", "s", "status", "as", "a", "standard", "working", "day" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L130-L132
15,566
rickar/cal
cal.go
IsHoliday
func (c *Calendar) IsHoliday(date time.Time) bool { idx := date.Month() for i := range c.holidays[idx] { if c.holidays[idx][i].matches(date) { return true } } for i := range c.holidays[0] { if c.holidays[0][i].matches(date) { return true } } return false }
go
func (c *Calendar) IsHoliday(date time.Time) bool { idx := date.Month() for i := range c.holidays[idx] { if c.holidays[idx][i].matches(date) { return true } } for i := range c.holidays[0] { if c.holidays[0][i].matches(date) { return true } } return false }
[ "func", "(", "c", "*", "Calendar", ")", "IsHoliday", "(", "date", "time", ".", "Time", ")", "bool", "{", "idx", ":=", "date", ".", "Month", "(", ")", "\n", "for", "i", ":=", "range", "c", ".", "holidays", "[", "idx", "]", "{", "if", "c", ".", "holidays", "[", "idx", "]", "[", "i", "]", ".", "matches", "(", "date", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "range", "c", ".", "holidays", "[", "0", "]", "{", "if", "c", ".", "holidays", "[", "0", "]", "[", "i", "]", ".", "matches", "(", "date", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsHoliday reports whether a given date is a holiday. It does not account // for the observation of holidays on alternate days.
[ "IsHoliday", "reports", "whether", "a", "given", "date", "is", "a", "holiday", ".", "It", "does", "not", "account", "for", "the", "observation", "of", "holidays", "on", "alternate", "days", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L136-L149
15,567
rickar/cal
cal.go
countWorkdays
func (c *Calendar) countWorkdays(dt time.Time, month time.Month) int { n := 0 for ; month == dt.Month(); dt = dt.AddDate(0, 0, 1) { if c.IsWorkday(dt) { n++ } } return n }
go
func (c *Calendar) countWorkdays(dt time.Time, month time.Month) int { n := 0 for ; month == dt.Month(); dt = dt.AddDate(0, 0, 1) { if c.IsWorkday(dt) { n++ } } return n }
[ "func", "(", "c", "*", "Calendar", ")", "countWorkdays", "(", "dt", "time", ".", "Time", ",", "month", "time", ".", "Month", ")", "int", "{", "n", ":=", "0", "\n", "for", ";", "month", "==", "dt", ".", "Month", "(", ")", ";", "dt", "=", "dt", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", "{", "if", "c", ".", "IsWorkday", "(", "dt", ")", "{", "n", "++", "\n", "}", "\n", "}", "\n", "return", "n", "\n", "}" ]
// countWorkdays reports the number of workdays from the given date to the end // of the month.
[ "countWorkdays", "reports", "the", "number", "of", "workdays", "from", "the", "given", "date", "to", "the", "end", "of", "the", "month", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L189-L197
15,568
rickar/cal
cal.go
Workdays
func (c *Calendar) Workdays(year int, month time.Month) int { return c.countWorkdays(time.Date(year, month, 1, 12, 0, 0, 0, time.UTC), month) }
go
func (c *Calendar) Workdays(year int, month time.Month) int { return c.countWorkdays(time.Date(year, month, 1, 12, 0, 0, 0, time.UTC), month) }
[ "func", "(", "c", "*", "Calendar", ")", "Workdays", "(", "year", "int", ",", "month", "time", ".", "Month", ")", "int", "{", "return", "c", ".", "countWorkdays", "(", "time", ".", "Date", "(", "year", ",", "month", ",", "1", ",", "12", ",", "0", ",", "0", ",", "0", ",", "time", ".", "UTC", ")", ",", "month", ")", "\n", "}" ]
// Workdays reports the total number of workdays for the given year and month.
[ "Workdays", "reports", "the", "total", "number", "of", "workdays", "for", "the", "given", "year", "and", "month", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L200-L202
15,569
rickar/cal
cal.go
WorkdaysRemain
func (c *Calendar) WorkdaysRemain(date time.Time) int { return c.countWorkdays(date.AddDate(0, 0, 1), date.Month()) }
go
func (c *Calendar) WorkdaysRemain(date time.Time) int { return c.countWorkdays(date.AddDate(0, 0, 1), date.Month()) }
[ "func", "(", "c", "*", "Calendar", ")", "WorkdaysRemain", "(", "date", "time", ".", "Time", ")", "int", "{", "return", "c", ".", "countWorkdays", "(", "date", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", ",", "date", ".", "Month", "(", ")", ")", "\n", "}" ]
// WorkdaysRemain reports the total number of remaining workdays in the month // for the given date.
[ "WorkdaysRemain", "reports", "the", "total", "number", "of", "remaining", "workdays", "in", "the", "month", "for", "the", "given", "date", "." ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L206-L208
15,570
rickar/cal
cal.go
CountHolidayHoursWithOffset
func (c *Calendar) CountHolidayHoursWithOffset(start time.Time, offsetHour int) int { days := int(math.Ceil(float64(offsetHour) / float64(24))) holidayHours := 0 day := 0 for day <= days { date := start.AddDate(0, 0, day) if !c.IsWorkday(date) { holidayHours += 24 days++ } day++ } return holidayHours }
go
func (c *Calendar) CountHolidayHoursWithOffset(start time.Time, offsetHour int) int { days := int(math.Ceil(float64(offsetHour) / float64(24))) holidayHours := 0 day := 0 for day <= days { date := start.AddDate(0, 0, day) if !c.IsWorkday(date) { holidayHours += 24 days++ } day++ } return holidayHours }
[ "func", "(", "c", "*", "Calendar", ")", "CountHolidayHoursWithOffset", "(", "start", "time", ".", "Time", ",", "offsetHour", "int", ")", "int", "{", "days", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "offsetHour", ")", "/", "float64", "(", "24", ")", ")", ")", "\n\n", "holidayHours", ":=", "0", "\n", "day", ":=", "0", "\n", "for", "day", "<=", "days", "{", "date", ":=", "start", ".", "AddDate", "(", "0", ",", "0", ",", "day", ")", "\n", "if", "!", "c", ".", "IsWorkday", "(", "date", ")", "{", "holidayHours", "+=", "24", "\n", "days", "++", "\n", "}", "\n", "day", "++", "\n", "}", "\n\n", "return", "holidayHours", "\n", "}" ]
// CountHolidayHoursWithOffset returns the number of working hours in a range starting from the consumed start date // to the end date set by the offset
[ "CountHolidayHoursWithOffset", "returns", "the", "number", "of", "working", "hours", "in", "a", "range", "starting", "from", "the", "consumed", "start", "date", "to", "the", "end", "date", "set", "by", "the", "offset" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L278-L293
15,571
rickar/cal
cal.go
CountWorkdays
func (c *Calendar) CountWorkdays(start, end time.Time) int64 { factor := 1 if end.Before(start) { factor = -1 start, end = end, start } result := 0 var i time.Time for i = start; i.Before(end); i = i.AddDate(0, 0, 1) { if c.IsWorkday(i) { result++ } } if i.Equal(end) && c.IsWorkday(end) { result++ } return int64(factor * result) }
go
func (c *Calendar) CountWorkdays(start, end time.Time) int64 { factor := 1 if end.Before(start) { factor = -1 start, end = end, start } result := 0 var i time.Time for i = start; i.Before(end); i = i.AddDate(0, 0, 1) { if c.IsWorkday(i) { result++ } } if i.Equal(end) && c.IsWorkday(end) { result++ } return int64(factor * result) }
[ "func", "(", "c", "*", "Calendar", ")", "CountWorkdays", "(", "start", ",", "end", "time", ".", "Time", ")", "int64", "{", "factor", ":=", "1", "\n", "if", "end", ".", "Before", "(", "start", ")", "{", "factor", "=", "-", "1", "\n", "start", ",", "end", "=", "end", ",", "start", "\n", "}", "\n", "result", ":=", "0", "\n", "var", "i", "time", ".", "Time", "\n", "for", "i", "=", "start", ";", "i", ".", "Before", "(", "end", ")", ";", "i", "=", "i", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", "{", "if", "c", ".", "IsWorkday", "(", "i", ")", "{", "result", "++", "\n", "}", "\n", "}", "\n", "if", "i", ".", "Equal", "(", "end", ")", "&&", "c", ".", "IsWorkday", "(", "end", ")", "{", "result", "++", "\n", "}", "\n", "return", "int64", "(", "factor", "*", "result", ")", "\n", "}" ]
//CountWorkdays return amount of workdays between start and end dates
[ "CountWorkdays", "return", "amount", "of", "workdays", "between", "start", "and", "end", "dates" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L296-L313
15,572
rickar/cal
cal.go
AddSkipNonWorkdays
func (c *Calendar) AddSkipNonWorkdays(start time.Time, d time.Duration) time.Time { const day = 24 * time.Hour s := start for { for !c.IsWorkday(s) { s = s.Add(day) } if d >= day { s = s.Add(day) d = d - day } else if d > 0 { s = s.Add(d) d = 0 } else { break } } return s }
go
func (c *Calendar) AddSkipNonWorkdays(start time.Time, d time.Duration) time.Time { const day = 24 * time.Hour s := start for { for !c.IsWorkday(s) { s = s.Add(day) } if d >= day { s = s.Add(day) d = d - day } else if d > 0 { s = s.Add(d) d = 0 } else { break } } return s }
[ "func", "(", "c", "*", "Calendar", ")", "AddSkipNonWorkdays", "(", "start", "time", ".", "Time", ",", "d", "time", ".", "Duration", ")", "time", ".", "Time", "{", "const", "day", "=", "24", "*", "time", ".", "Hour", "\n", "s", ":=", "start", "\n", "for", "{", "for", "!", "c", ".", "IsWorkday", "(", "s", ")", "{", "s", "=", "s", ".", "Add", "(", "day", ")", "\n", "}", "\n\n", "if", "d", ">=", "day", "{", "s", "=", "s", ".", "Add", "(", "day", ")", "\n", "d", "=", "d", "-", "day", "\n", "}", "else", "if", "d", ">", "0", "{", "s", "=", "s", ".", "Add", "(", "d", ")", "\n", "d", "=", "0", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "return", "s", "\n", "}" ]
// AddSkipNonWorkdays returns start time plus d woking duration
[ "AddSkipNonWorkdays", "returns", "start", "time", "plus", "d", "woking", "duration" ]
7dd8caa87d491626b521d2bf32d4f01d24c2fd37
https://github.com/rickar/cal/blob/7dd8caa87d491626b521d2bf32d4f01d24c2fd37/cal.go#L316-L335
15,573
ikawaha/kagome
tokenizer/tokenizer.go
NewWithDicPath
func NewWithDicPath(p string) (Tokenizer, error) { d, err := dic.Load(p) if err != nil { return Tokenizer{dic: dic.SysDic()}, err } return NewWithDic(Dic{d}), nil }
go
func NewWithDicPath(p string) (Tokenizer, error) { d, err := dic.Load(p) if err != nil { return Tokenizer{dic: dic.SysDic()}, err } return NewWithDic(Dic{d}), nil }
[ "func", "NewWithDicPath", "(", "p", "string", ")", "(", "Tokenizer", ",", "error", ")", "{", "d", ",", "err", ":=", "dic", ".", "Load", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Tokenizer", "{", "dic", ":", "dic", ".", "SysDic", "(", ")", "}", ",", "err", "\n", "}", "\n", "return", "NewWithDic", "(", "Dic", "{", "d", "}", ")", ",", "nil", "\n", "}" ]
// NewWithDicPath create a tokenizer with a dictionary that loads from path.
[ "NewWithDicPath", "create", "a", "tokenizer", "with", "a", "dictionary", "that", "loads", "from", "path", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/tokenizer/tokenizer.go#L56-L62
15,574
ikawaha/kagome
tokenizer/tokenizer.go
Tokenize
func (t Tokenizer) Tokenize(input string) []Token { return t.Analyze(input, Normal) }
go
func (t Tokenizer) Tokenize(input string) []Token { return t.Analyze(input, Normal) }
[ "func", "(", "t", "Tokenizer", ")", "Tokenize", "(", "input", "string", ")", "[", "]", "Token", "{", "return", "t", ".", "Analyze", "(", "input", ",", "Normal", ")", "\n", "}" ]
// Tokenize analyze a sentence in standard tokenize mode.
[ "Tokenize", "analyze", "a", "sentence", "in", "standard", "tokenize", "mode", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/tokenizer/tokenizer.go#L75-L77
15,575
ikawaha/kagome
tokenizer/tokenizer.go
Analyze
func (t Tokenizer) Analyze(input string, mode TokenizeMode) (tokens []Token) { la := lattice.New(t.dic, t.udic) defer la.Free() la.Build(input) m := lattice.Normal switch mode { case Normal: m = lattice.Normal case Search: m = lattice.Search case Extended: m = lattice.Extended } la.Forward(m) la.Backward(m) size := len(la.Output) tokens = make([]Token, 0, size) for i := range la.Output { n := la.Output[size-1-i] tok := Token{ ID: n.ID, Class: TokenClass(n.Class), Start: n.Start, End: n.Start + utf8.RuneCountInString(n.Surface), Surface: n.Surface, dic: t.dic, udic: t.udic, } if tok.ID == lattice.BosEosID { if i == 0 { tok.Surface = "BOS" } else { tok.Surface = "EOS" } } tokens = append(tokens, tok) } return }
go
func (t Tokenizer) Analyze(input string, mode TokenizeMode) (tokens []Token) { la := lattice.New(t.dic, t.udic) defer la.Free() la.Build(input) m := lattice.Normal switch mode { case Normal: m = lattice.Normal case Search: m = lattice.Search case Extended: m = lattice.Extended } la.Forward(m) la.Backward(m) size := len(la.Output) tokens = make([]Token, 0, size) for i := range la.Output { n := la.Output[size-1-i] tok := Token{ ID: n.ID, Class: TokenClass(n.Class), Start: n.Start, End: n.Start + utf8.RuneCountInString(n.Surface), Surface: n.Surface, dic: t.dic, udic: t.udic, } if tok.ID == lattice.BosEosID { if i == 0 { tok.Surface = "BOS" } else { tok.Surface = "EOS" } } tokens = append(tokens, tok) } return }
[ "func", "(", "t", "Tokenizer", ")", "Analyze", "(", "input", "string", ",", "mode", "TokenizeMode", ")", "(", "tokens", "[", "]", "Token", ")", "{", "la", ":=", "lattice", ".", "New", "(", "t", ".", "dic", ",", "t", ".", "udic", ")", "\n", "defer", "la", ".", "Free", "(", ")", "\n", "la", ".", "Build", "(", "input", ")", "\n", "m", ":=", "lattice", ".", "Normal", "\n", "switch", "mode", "{", "case", "Normal", ":", "m", "=", "lattice", ".", "Normal", "\n", "case", "Search", ":", "m", "=", "lattice", ".", "Search", "\n", "case", "Extended", ":", "m", "=", "lattice", ".", "Extended", "\n", "}", "\n", "la", ".", "Forward", "(", "m", ")", "\n", "la", ".", "Backward", "(", "m", ")", "\n", "size", ":=", "len", "(", "la", ".", "Output", ")", "\n", "tokens", "=", "make", "(", "[", "]", "Token", ",", "0", ",", "size", ")", "\n", "for", "i", ":=", "range", "la", ".", "Output", "{", "n", ":=", "la", ".", "Output", "[", "size", "-", "1", "-", "i", "]", "\n", "tok", ":=", "Token", "{", "ID", ":", "n", ".", "ID", ",", "Class", ":", "TokenClass", "(", "n", ".", "Class", ")", ",", "Start", ":", "n", ".", "Start", ",", "End", ":", "n", ".", "Start", "+", "utf8", ".", "RuneCountInString", "(", "n", ".", "Surface", ")", ",", "Surface", ":", "n", ".", "Surface", ",", "dic", ":", "t", ".", "dic", ",", "udic", ":", "t", ".", "udic", ",", "}", "\n", "if", "tok", ".", "ID", "==", "lattice", ".", "BosEosID", "{", "if", "i", "==", "0", "{", "tok", ".", "Surface", "=", "\"", "\"", "\n", "}", "else", "{", "tok", ".", "Surface", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "tokens", "=", "append", "(", "tokens", ",", "tok", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Analyze tokenizes a sentence in the specified mode.
[ "Analyze", "tokenizes", "a", "sentence", "in", "the", "specified", "mode", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/tokenizer/tokenizer.go#L80-L118
15,576
ikawaha/kagome
tokenizer/tokenizer.go
Dot
func (t Tokenizer) Dot(input string, w io.Writer) (tokens []Token) { return t.AnalyzeGraph(input, Normal, w) }
go
func (t Tokenizer) Dot(input string, w io.Writer) (tokens []Token) { return t.AnalyzeGraph(input, Normal, w) }
[ "func", "(", "t", "Tokenizer", ")", "Dot", "(", "input", "string", ",", "w", "io", ".", "Writer", ")", "(", "tokens", "[", "]", "Token", ")", "{", "return", "t", ".", "AnalyzeGraph", "(", "input", ",", "Normal", ",", "w", ")", "\n", "}" ]
// Dot returns morphs of a sentence and exports a lattice graph to dot format in standard tokenize mode.
[ "Dot", "returns", "morphs", "of", "a", "sentence", "and", "exports", "a", "lattice", "graph", "to", "dot", "format", "in", "standard", "tokenize", "mode", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/tokenizer/tokenizer.go#L121-L123
15,577
ikawaha/kagome
splitter/splitter.go
ScanSentences
func ScanSentences(data []byte, atEOF bool) (advance int, token []byte, err error) { return defaultSplitter.ScanSentences(data, atEOF) }
go
func ScanSentences(data []byte, atEOF bool) (advance int, token []byte, err error) { return defaultSplitter.ScanSentences(data, atEOF) }
[ "func", "ScanSentences", "(", "data", "[", "]", "byte", ",", "atEOF", "bool", ")", "(", "advance", "int", ",", "token", "[", "]", "byte", ",", "err", "error", ")", "{", "return", "defaultSplitter", ".", "ScanSentences", "(", "data", ",", "atEOF", ")", "\n", "}" ]
// ScanSentences is a split function for a bufio.Scanner that returns each sentence of text.
[ "ScanSentences", "is", "a", "split", "function", "for", "a", "bufio", ".", "Scanner", "that", "returns", "each", "sentence", "of", "text", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/splitter/splitter.go#L43-L45
15,578
ikawaha/kagome
splitter/splitter.go
ScanSentences
func (s SentenceSplitter) ScanSentences(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } var ( start, end, rcount int head, nn bool ) head = true for p := 0; p < len(data); { r, size := utf8.DecodeRune(data[p:]) if s.SkipWhiteSpace && unicode.IsSpace(r) { p += size if head { start, end = p, p } else if s.isDelim(r) { return p, data[start:end], nil } else if s.DoubleLineFeedSplit && r == '\n' { if nn { return p, data[start:end], nil } nn = true } continue } head, nn = false, false // clear flags if end != p { for i := 0; i < size; i++ { data[end+i] = data[p+i] } } p += size end += size rcount++ if !s.isDelim(r) && rcount < s.MaxRuneLen { continue } // split nn = false for p < len(data) { r, size := utf8.DecodeRune(data[p:]) if s.SkipWhiteSpace && unicode.IsSpace(r) { p += size if s.DoubleLineFeedSplit && r == '\n' { if nn { return p, data[start:end], nil } nn = true } } else if s.isDelim(r) || s.isFollower(r) { if end != p { for i := 0; i < size; i++ { data[end+i] = data[p+i] } } p += size end += size } else { break } } return p, data[start:end], nil } if !atEOF { // Request more data for i := end; i < len(data); i++ { data[i] = ' ' } return start, nil, nil } // If we're at EOF, we have a final, non-terminated line. Return it. return len(data), data[start:end], nil }
go
func (s SentenceSplitter) ScanSentences(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } var ( start, end, rcount int head, nn bool ) head = true for p := 0; p < len(data); { r, size := utf8.DecodeRune(data[p:]) if s.SkipWhiteSpace && unicode.IsSpace(r) { p += size if head { start, end = p, p } else if s.isDelim(r) { return p, data[start:end], nil } else if s.DoubleLineFeedSplit && r == '\n' { if nn { return p, data[start:end], nil } nn = true } continue } head, nn = false, false // clear flags if end != p { for i := 0; i < size; i++ { data[end+i] = data[p+i] } } p += size end += size rcount++ if !s.isDelim(r) && rcount < s.MaxRuneLen { continue } // split nn = false for p < len(data) { r, size := utf8.DecodeRune(data[p:]) if s.SkipWhiteSpace && unicode.IsSpace(r) { p += size if s.DoubleLineFeedSplit && r == '\n' { if nn { return p, data[start:end], nil } nn = true } } else if s.isDelim(r) || s.isFollower(r) { if end != p { for i := 0; i < size; i++ { data[end+i] = data[p+i] } } p += size end += size } else { break } } return p, data[start:end], nil } if !atEOF { // Request more data for i := end; i < len(data); i++ { data[i] = ' ' } return start, nil, nil } // If we're at EOF, we have a final, non-terminated line. Return it. return len(data), data[start:end], nil }
[ "func", "(", "s", "SentenceSplitter", ")", "ScanSentences", "(", "data", "[", "]", "byte", ",", "atEOF", "bool", ")", "(", "advance", "int", ",", "token", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "atEOF", "&&", "len", "(", "data", ")", "==", "0", "{", "return", "0", ",", "nil", ",", "nil", "\n", "}", "\n", "var", "(", "start", ",", "end", ",", "rcount", "int", "\n", "head", ",", "nn", "bool", "\n", ")", "\n", "head", "=", "true", "\n", "for", "p", ":=", "0", ";", "p", "<", "len", "(", "data", ")", ";", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "data", "[", "p", ":", "]", ")", "\n", "if", "s", ".", "SkipWhiteSpace", "&&", "unicode", ".", "IsSpace", "(", "r", ")", "{", "p", "+=", "size", "\n", "if", "head", "{", "start", ",", "end", "=", "p", ",", "p", "\n", "}", "else", "if", "s", ".", "isDelim", "(", "r", ")", "{", "return", "p", ",", "data", "[", "start", ":", "end", "]", ",", "nil", "\n", "}", "else", "if", "s", ".", "DoubleLineFeedSplit", "&&", "r", "==", "'\\n'", "{", "if", "nn", "{", "return", "p", ",", "data", "[", "start", ":", "end", "]", ",", "nil", "\n", "}", "\n", "nn", "=", "true", "\n", "}", "\n", "continue", "\n", "}", "\n", "head", ",", "nn", "=", "false", ",", "false", "// clear flags", "\n", "if", "end", "!=", "p", "{", "for", "i", ":=", "0", ";", "i", "<", "size", ";", "i", "++", "{", "data", "[", "end", "+", "i", "]", "=", "data", "[", "p", "+", "i", "]", "\n", "}", "\n", "}", "\n", "p", "+=", "size", "\n", "end", "+=", "size", "\n", "rcount", "++", "\n", "if", "!", "s", ".", "isDelim", "(", "r", ")", "&&", "rcount", "<", "s", ".", "MaxRuneLen", "{", "continue", "\n", "}", "\n", "// split", "nn", "=", "false", "\n", "for", "p", "<", "len", "(", "data", ")", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "data", "[", "p", ":", "]", ")", "\n", "if", "s", ".", "SkipWhiteSpace", "&&", "unicode", ".", "IsSpace", "(", "r", ")", "{", "p", "+=", "size", "\n", "if", "s", ".", "DoubleLineFeedSplit", "&&", "r", "==", "'\\n'", "{", "if", "nn", "{", "return", "p", ",", "data", "[", "start", ":", "end", "]", ",", "nil", "\n", "}", "\n", "nn", "=", "true", "\n", "}", "\n", "}", "else", "if", "s", ".", "isDelim", "(", "r", ")", "||", "s", ".", "isFollower", "(", "r", ")", "{", "if", "end", "!=", "p", "{", "for", "i", ":=", "0", ";", "i", "<", "size", ";", "i", "++", "{", "data", "[", "end", "+", "i", "]", "=", "data", "[", "p", "+", "i", "]", "\n", "}", "\n", "}", "\n", "p", "+=", "size", "\n", "end", "+=", "size", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "return", "p", ",", "data", "[", "start", ":", "end", "]", ",", "nil", "\n", "}", "\n", "if", "!", "atEOF", "{", "// Request more data", "for", "i", ":=", "end", ";", "i", "<", "len", "(", "data", ")", ";", "i", "++", "{", "data", "[", "i", "]", "=", "' '", "\n", "}", "\n", "return", "start", ",", "nil", ",", "nil", "\n", "}", "\n", "// If we're at EOF, we have a final, non-terminated line. Return it.", "return", "len", "(", "data", ")", ",", "data", "[", "start", ":", "end", "]", ",", "nil", "\n\n", "}" ]
// ScanSentences is a split function for a Scanner that returns each sentence of text.
[ "ScanSentences", "is", "a", "split", "function", "for", "a", "Scanner", "that", "returns", "each", "sentence", "of", "text", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/splitter/splitter.go#L66-L139
15,579
ikawaha/kagome
internal/dic/index.go
BuildIndexTable
func BuildIndexTable(sortedKeywords []string) (IndexTable, error) { idx := IndexTable{Dup: map[int32]int32{}} if !sort.StringsAreSorted(sortedKeywords) { return idx, fmt.Errorf("unsorted keywords") } keys := make([]string, 0, len(sortedKeywords)) ids := make([]int, 0, len(sortedKeywords)) prev := struct { no int word string }{} for i, key := range sortedKeywords { if key == prev.word { idx.Dup[int32(prev.no)]++ continue } prev.no = i prev.word = key keys = append(keys, key) ids = append(ids, i) } d, err := da.BuildWithIDs(keys, ids) if err != nil { return idx, fmt.Errorf("build error, %v", err) } idx.Da = d return idx, nil }
go
func BuildIndexTable(sortedKeywords []string) (IndexTable, error) { idx := IndexTable{Dup: map[int32]int32{}} if !sort.StringsAreSorted(sortedKeywords) { return idx, fmt.Errorf("unsorted keywords") } keys := make([]string, 0, len(sortedKeywords)) ids := make([]int, 0, len(sortedKeywords)) prev := struct { no int word string }{} for i, key := range sortedKeywords { if key == prev.word { idx.Dup[int32(prev.no)]++ continue } prev.no = i prev.word = key keys = append(keys, key) ids = append(ids, i) } d, err := da.BuildWithIDs(keys, ids) if err != nil { return idx, fmt.Errorf("build error, %v", err) } idx.Da = d return idx, nil }
[ "func", "BuildIndexTable", "(", "sortedKeywords", "[", "]", "string", ")", "(", "IndexTable", ",", "error", ")", "{", "idx", ":=", "IndexTable", "{", "Dup", ":", "map", "[", "int32", "]", "int32", "{", "}", "}", "\n", "if", "!", "sort", ".", "StringsAreSorted", "(", "sortedKeywords", ")", "{", "return", "idx", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "sortedKeywords", ")", ")", "\n", "ids", ":=", "make", "(", "[", "]", "int", ",", "0", ",", "len", "(", "sortedKeywords", ")", ")", "\n", "prev", ":=", "struct", "{", "no", "int", "\n", "word", "string", "\n", "}", "{", "}", "\n", "for", "i", ",", "key", ":=", "range", "sortedKeywords", "{", "if", "key", "==", "prev", ".", "word", "{", "idx", ".", "Dup", "[", "int32", "(", "prev", ".", "no", ")", "]", "++", "\n", "continue", "\n", "}", "\n", "prev", ".", "no", "=", "i", "\n", "prev", ".", "word", "=", "key", "\n", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "ids", "=", "append", "(", "ids", ",", "i", ")", "\n", "}", "\n", "d", ",", "err", ":=", "da", ".", "BuildWithIDs", "(", "keys", ",", "ids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "idx", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "idx", ".", "Da", "=", "d", "\n", "return", "idx", ",", "nil", "\n", "}" ]
// BuildIndexTable constructs a index table from keywords.
[ "BuildIndexTable", "constructs", "a", "index", "table", "from", "keywords", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/index.go#L33-L60
15,580
ikawaha/kagome
internal/dic/index.go
Search
func (idx IndexTable) Search(input string) []int { id, ok := idx.Da.Find(input) if !ok { return nil } dup := idx.Dup[int32(id)] list := make([]int, 1+dup) for i := 0; i < len(list); i++ { list[i] = id + i } return list }
go
func (idx IndexTable) Search(input string) []int { id, ok := idx.Da.Find(input) if !ok { return nil } dup := idx.Dup[int32(id)] list := make([]int, 1+dup) for i := 0; i < len(list); i++ { list[i] = id + i } return list }
[ "func", "(", "idx", "IndexTable", ")", "Search", "(", "input", "string", ")", "[", "]", "int", "{", "id", ",", "ok", ":=", "idx", ".", "Da", ".", "Find", "(", "input", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "dup", ":=", "idx", ".", "Dup", "[", "int32", "(", "id", ")", "]", "\n", "list", ":=", "make", "(", "[", "]", "int", ",", "1", "+", "dup", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "i", "++", "{", "list", "[", "i", "]", "=", "id", "+", "i", "\n", "}", "\n", "return", "list", "\n", "}" ]
// Search finds the given keyword and returns the id if found.
[ "Search", "finds", "the", "given", "keyword", "and", "returns", "the", "id", "if", "found", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/index.go#L90-L101
15,581
ikawaha/kagome
internal/dic/index.go
WriteTo
func (idx IndexTable) WriteTo(w io.Writer) (n int64, err error) { if n, err = idx.Da.WriteTo(w); err != nil { return } keys := make([]int32, 0, len(idx.Dup)) for k := range idx.Dup { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] }) sz := int64(len(keys)) if err = binary.Write(w, binary.LittleEndian, sz); err != nil { return } n += int64(binary.Size(sz)) for _, k := range keys { if err = binary.Write(w, binary.LittleEndian, k); err != nil { return } n += int64(binary.Size(k)) v := idx.Dup[k] if err = binary.Write(w, binary.LittleEndian, v); err != nil { return } n += int64(binary.Size(v)) } return }
go
func (idx IndexTable) WriteTo(w io.Writer) (n int64, err error) { if n, err = idx.Da.WriteTo(w); err != nil { return } keys := make([]int32, 0, len(idx.Dup)) for k := range idx.Dup { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] }) sz := int64(len(keys)) if err = binary.Write(w, binary.LittleEndian, sz); err != nil { return } n += int64(binary.Size(sz)) for _, k := range keys { if err = binary.Write(w, binary.LittleEndian, k); err != nil { return } n += int64(binary.Size(k)) v := idx.Dup[k] if err = binary.Write(w, binary.LittleEndian, v); err != nil { return } n += int64(binary.Size(v)) } return }
[ "func", "(", "idx", "IndexTable", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "if", "n", ",", "err", "=", "idx", ".", "Da", ".", "WriteTo", "(", "w", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "keys", ":=", "make", "(", "[", "]", "int32", ",", "0", ",", "len", "(", "idx", ".", "Dup", ")", ")", "\n", "for", "k", ":=", "range", "idx", ".", "Dup", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Slice", "(", "keys", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "keys", "[", "i", "]", "<", "keys", "[", "j", "]", "\n", "}", ")", "\n", "sz", ":=", "int64", "(", "len", "(", "keys", ")", ")", "\n", "if", "err", "=", "binary", ".", "Write", "(", "w", ",", "binary", ".", "LittleEndian", ",", "sz", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", "+=", "int64", "(", "binary", ".", "Size", "(", "sz", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "if", "err", "=", "binary", ".", "Write", "(", "w", ",", "binary", ".", "LittleEndian", ",", "k", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", "+=", "int64", "(", "binary", ".", "Size", "(", "k", ")", ")", "\n", "v", ":=", "idx", ".", "Dup", "[", "k", "]", "\n", "if", "err", "=", "binary", ".", "Write", "(", "w", ",", "binary", ".", "LittleEndian", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", "+=", "int64", "(", "binary", ".", "Size", "(", "v", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// WriteTo saves a index table.
[ "WriteTo", "saves", "a", "index", "table", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/index.go#L104-L132
15,582
ikawaha/kagome
internal/dic/index.go
ReadIndexTable
func ReadIndexTable(r io.Reader) (IndexTable, error) { idx := IndexTable{} d, err := da.Read(r) if err != nil { return idx, fmt.Errorf("read index error, %v", err) } idx.Da = d var sz int64 if err := binary.Read(r, binary.LittleEndian, &sz); err != nil { return idx, err } idx.Dup = make(map[int32]int32, sz) for i := int64(0); i < sz; i++ { var k int32 if err := binary.Read(r, binary.LittleEndian, &k); err != nil { return idx, err } var v int32 if err := binary.Read(r, binary.LittleEndian, &v); err != nil { return idx, err } idx.Dup[k] = v } return idx, nil }
go
func ReadIndexTable(r io.Reader) (IndexTable, error) { idx := IndexTable{} d, err := da.Read(r) if err != nil { return idx, fmt.Errorf("read index error, %v", err) } idx.Da = d var sz int64 if err := binary.Read(r, binary.LittleEndian, &sz); err != nil { return idx, err } idx.Dup = make(map[int32]int32, sz) for i := int64(0); i < sz; i++ { var k int32 if err := binary.Read(r, binary.LittleEndian, &k); err != nil { return idx, err } var v int32 if err := binary.Read(r, binary.LittleEndian, &v); err != nil { return idx, err } idx.Dup[k] = v } return idx, nil }
[ "func", "ReadIndexTable", "(", "r", "io", ".", "Reader", ")", "(", "IndexTable", ",", "error", ")", "{", "idx", ":=", "IndexTable", "{", "}", "\n", "d", ",", "err", ":=", "da", ".", "Read", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "idx", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "idx", ".", "Da", "=", "d", "\n\n", "var", "sz", "int64", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "sz", ")", ";", "err", "!=", "nil", "{", "return", "idx", ",", "err", "\n", "}", "\n", "idx", ".", "Dup", "=", "make", "(", "map", "[", "int32", "]", "int32", ",", "sz", ")", "\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "sz", ";", "i", "++", "{", "var", "k", "int32", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "k", ")", ";", "err", "!=", "nil", "{", "return", "idx", ",", "err", "\n", "}", "\n", "var", "v", "int32", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "idx", ",", "err", "\n", "}", "\n", "idx", ".", "Dup", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "return", "idx", ",", "nil", "\n", "}" ]
// ReadIndexTable loads a index table.
[ "ReadIndexTable", "loads", "a", "index", "table", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/index.go#L135-L161
15,583
ikawaha/kagome
cmd/kagome/lattice/cmd.go
OptionCheck
func OptionCheck(args []string) (err error) { opt := newOption(ioutil.Discard, flag.ContinueOnError) if e := opt.parse(args); e != nil { return fmt.Errorf("%v, %v", CommandName, e) } return nil }
go
func OptionCheck(args []string) (err error) { opt := newOption(ioutil.Discard, flag.ContinueOnError) if e := opt.parse(args); e != nil { return fmt.Errorf("%v, %v", CommandName, e) } return nil }
[ "func", "OptionCheck", "(", "args", "[", "]", "string", ")", "(", "err", "error", ")", "{", "opt", ":=", "newOption", "(", "ioutil", ".", "Discard", ",", "flag", ".", "ContinueOnError", ")", "\n", "if", "e", ":=", "opt", ".", "parse", "(", "args", ")", ";", "e", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "CommandName", ",", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
//OptionCheck receives a slice of args and returns an error if it was not successfully parsed
[ "OptionCheck", "receives", "a", "slice", "of", "args", "and", "returns", "an", "error", "if", "it", "was", "not", "successfully", "parsed" ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/cmd/kagome/lattice/cmd.go#L77-L83
15,584
ikawaha/kagome
cmd/kagome/lattice/cmd.go
Run
func Run(args []string) error { opt := newOption(ErrorWriter, flag.ExitOnError) if e := opt.parse(args); e != nil { Usage() PrintDefaults(flag.ExitOnError) return fmt.Errorf("%v, %v", CommandName, e) } return command(opt) }
go
func Run(args []string) error { opt := newOption(ErrorWriter, flag.ExitOnError) if e := opt.parse(args); e != nil { Usage() PrintDefaults(flag.ExitOnError) return fmt.Errorf("%v, %v", CommandName, e) } return command(opt) }
[ "func", "Run", "(", "args", "[", "]", "string", ")", "error", "{", "opt", ":=", "newOption", "(", "ErrorWriter", ",", "flag", ".", "ExitOnError", ")", "\n", "if", "e", ":=", "opt", ".", "parse", "(", "args", ")", ";", "e", "!=", "nil", "{", "Usage", "(", ")", "\n", "PrintDefaults", "(", "flag", ".", "ExitOnError", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "CommandName", ",", "e", ")", "\n", "}", "\n", "return", "command", "(", "opt", ")", "\n", "}" ]
// Run receives the slice of args and executes the lattice tool
[ "Run", "receives", "the", "slice", "of", "args", "and", "executes", "the", "lattice", "tool" ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/cmd/kagome/lattice/cmd.go#L141-L149
15,585
ikawaha/kagome
internal/dic/morph.go
LoadMorphSlice
func LoadMorphSlice(r io.Reader) ([]Morph, error) { var l int64 if e := binary.Read(r, binary.LittleEndian, &l); e != nil { return nil, e } m := make([]Morph, l) for i := range m { if e := binary.Read(r, binary.LittleEndian, &m[i].LeftID); e != nil { return m, e } if e := binary.Read(r, binary.LittleEndian, &m[i].RightID); e != nil { return m, e } if e := binary.Read(r, binary.LittleEndian, &m[i].Weight); e != nil { return m, e } } return m, nil }
go
func LoadMorphSlice(r io.Reader) ([]Morph, error) { var l int64 if e := binary.Read(r, binary.LittleEndian, &l); e != nil { return nil, e } m := make([]Morph, l) for i := range m { if e := binary.Read(r, binary.LittleEndian, &m[i].LeftID); e != nil { return m, e } if e := binary.Read(r, binary.LittleEndian, &m[i].RightID); e != nil { return m, e } if e := binary.Read(r, binary.LittleEndian, &m[i].Weight); e != nil { return m, e } } return m, nil }
[ "func", "LoadMorphSlice", "(", "r", "io", ".", "Reader", ")", "(", "[", "]", "Morph", ",", "error", ")", "{", "var", "l", "int64", "\n", "if", "e", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "l", ")", ";", "e", "!=", "nil", "{", "return", "nil", ",", "e", "\n", "}", "\n", "m", ":=", "make", "(", "[", "]", "Morph", ",", "l", ")", "\n", "for", "i", ":=", "range", "m", "{", "if", "e", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "m", "[", "i", "]", ".", "LeftID", ")", ";", "e", "!=", "nil", "{", "return", "m", ",", "e", "\n", "}", "\n", "if", "e", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "m", "[", "i", "]", ".", "RightID", ")", ";", "e", "!=", "nil", "{", "return", "m", ",", "e", "\n", "}", "\n", "if", "e", ":=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "LittleEndian", ",", "&", "m", "[", "i", "]", ".", "Weight", ")", ";", "e", "!=", "nil", "{", "return", "m", ",", "e", "\n", "}", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// LoadMorphSlice loads morph data from io.Reader
[ "LoadMorphSlice", "loads", "morph", "data", "from", "io", ".", "Reader" ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/morph.go#L55-L73
15,586
ikawaha/kagome
cmd/kagome/main.go
Usage
func Usage() { fmt.Fprintf(errorWriter, "Japanese Morphological Analyzer -- github.com/ikawaha/kagome\n") fmt.Fprintf(errorWriter, "usage: %s <command>\n", filepath.Base(os.Args[0])) }
go
func Usage() { fmt.Fprintf(errorWriter, "Japanese Morphological Analyzer -- github.com/ikawaha/kagome\n") fmt.Fprintf(errorWriter, "usage: %s <command>\n", filepath.Base(os.Args[0])) }
[ "func", "Usage", "(", ")", "{", "fmt", ".", "Fprintf", "(", "errorWriter", ",", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "errorWriter", ",", "\"", "\\n", "\"", ",", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", ")", "\n", "}" ]
//Usage prints to stdout information about the tool
[ "Usage", "prints", "to", "stdout", "information", "about", "the", "tool" ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/cmd/kagome/main.go#L60-L63
15,587
ikawaha/kagome
tokenizer/udic.go
NewUserDicRecords
func NewUserDicRecords(r io.Reader) (UserDicRecords, error) { var text []string scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() if line == "" || strings.HasPrefix(line, "#") { continue } text = append(text, line) } if err := scanner.Err(); err != nil { return nil, err } var records UserDicRecords for _, line := range text { vec := strings.Split(line, ",") if len(vec) != dic.UserDicColumnSize { return nil, fmt.Errorf("invalid format: %s", line) } tokens := strings.Split(vec[1], " ") yomi := strings.Split(vec[2], " ") if len(tokens) == 0 || len(tokens) != len(yomi) { return nil, fmt.Errorf("invalid format: %s", line) } r := UserDicRecord{ Text: vec[0], Tokens: tokens, Yomi: yomi, Pos: vec[3], } records = append(records, r) } return records, nil }
go
func NewUserDicRecords(r io.Reader) (UserDicRecords, error) { var text []string scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() if line == "" || strings.HasPrefix(line, "#") { continue } text = append(text, line) } if err := scanner.Err(); err != nil { return nil, err } var records UserDicRecords for _, line := range text { vec := strings.Split(line, ",") if len(vec) != dic.UserDicColumnSize { return nil, fmt.Errorf("invalid format: %s", line) } tokens := strings.Split(vec[1], " ") yomi := strings.Split(vec[2], " ") if len(tokens) == 0 || len(tokens) != len(yomi) { return nil, fmt.Errorf("invalid format: %s", line) } r := UserDicRecord{ Text: vec[0], Tokens: tokens, Yomi: yomi, Pos: vec[3], } records = append(records, r) } return records, nil }
[ "func", "NewUserDicRecords", "(", "r", "io", ".", "Reader", ")", "(", "UserDicRecords", ",", "error", ")", "{", "var", "text", "[", "]", "string", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", ":=", "scanner", ".", "Text", "(", ")", "\n", "if", "line", "==", "\"", "\"", "||", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "text", "=", "append", "(", "text", ",", "line", ")", "\n", "}", "\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "records", "UserDicRecords", "\n", "for", "_", ",", "line", ":=", "range", "text", "{", "vec", ":=", "strings", ".", "Split", "(", "line", ",", "\"", "\"", ")", "\n", "if", "len", "(", "vec", ")", "!=", "dic", ".", "UserDicColumnSize", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ")", "\n", "}", "\n", "tokens", ":=", "strings", ".", "Split", "(", "vec", "[", "1", "]", ",", "\"", "\"", ")", "\n", "yomi", ":=", "strings", ".", "Split", "(", "vec", "[", "2", "]", ",", "\"", "\"", ")", "\n", "if", "len", "(", "tokens", ")", "==", "0", "||", "len", "(", "tokens", ")", "!=", "len", "(", "yomi", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ")", "\n", "}", "\n", "r", ":=", "UserDicRecord", "{", "Text", ":", "vec", "[", "0", "]", ",", "Tokens", ":", "tokens", ",", "Yomi", ":", "yomi", ",", "Pos", ":", "vec", "[", "3", "]", ",", "}", "\n", "records", "=", "append", "(", "records", ",", "r", ")", "\n", "}", "\n", "return", "records", ",", "nil", "\n", "}" ]
// NewUserDicRecords loads user dictionary data from io.Reader.
[ "NewUserDicRecords", "loads", "user", "dictionary", "data", "from", "io", ".", "Reader", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/tokenizer/udic.go#L64-L98
15,588
ikawaha/kagome
tokenizer/udic.go
NewUserDic
func (u UserDicRecords) NewUserDic() (UserDic, error) { udic := new(dic.UserDic) sort.Sort(u) prev := "" keys := make([]string, 0, len(u)) for _, r := range u { k := strings.TrimSpace(r.Text) if prev == k { return UserDic{}, fmt.Errorf("duplicated error, %+v", r) } prev = k keys = append(keys, k) if len(r.Tokens) == 0 || len(r.Tokens) != len(r.Yomi) { return UserDic{}, fmt.Errorf("invalid format, %+v", r) } c := dic.UserDicContent{ Tokens: r.Tokens, Yomi: r.Yomi, Pos: r.Pos, } udic.Contents = append(udic.Contents, c) } idx, err := dic.BuildIndexTable(keys) udic.Index = idx return UserDic{dic: udic}, err }
go
func (u UserDicRecords) NewUserDic() (UserDic, error) { udic := new(dic.UserDic) sort.Sort(u) prev := "" keys := make([]string, 0, len(u)) for _, r := range u { k := strings.TrimSpace(r.Text) if prev == k { return UserDic{}, fmt.Errorf("duplicated error, %+v", r) } prev = k keys = append(keys, k) if len(r.Tokens) == 0 || len(r.Tokens) != len(r.Yomi) { return UserDic{}, fmt.Errorf("invalid format, %+v", r) } c := dic.UserDicContent{ Tokens: r.Tokens, Yomi: r.Yomi, Pos: r.Pos, } udic.Contents = append(udic.Contents, c) } idx, err := dic.BuildIndexTable(keys) udic.Index = idx return UserDic{dic: udic}, err }
[ "func", "(", "u", "UserDicRecords", ")", "NewUserDic", "(", ")", "(", "UserDic", ",", "error", ")", "{", "udic", ":=", "new", "(", "dic", ".", "UserDic", ")", "\n", "sort", ".", "Sort", "(", "u", ")", "\n\n", "prev", ":=", "\"", "\"", "\n", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "u", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "u", "{", "k", ":=", "strings", ".", "TrimSpace", "(", "r", ".", "Text", ")", "\n", "if", "prev", "==", "k", "{", "return", "UserDic", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "prev", "=", "k", "\n", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "if", "len", "(", "r", ".", "Tokens", ")", "==", "0", "||", "len", "(", "r", ".", "Tokens", ")", "!=", "len", "(", "r", ".", "Yomi", ")", "{", "return", "UserDic", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "c", ":=", "dic", ".", "UserDicContent", "{", "Tokens", ":", "r", ".", "Tokens", ",", "Yomi", ":", "r", ".", "Yomi", ",", "Pos", ":", "r", ".", "Pos", ",", "}", "\n", "udic", ".", "Contents", "=", "append", "(", "udic", ".", "Contents", ",", "c", ")", "\n", "}", "\n", "idx", ",", "err", ":=", "dic", ".", "BuildIndexTable", "(", "keys", ")", "\n", "udic", ".", "Index", "=", "idx", "\n", "return", "UserDic", "{", "dic", ":", "udic", "}", ",", "err", "\n", "}" ]
// NewUserDic builds a user dictionary.
[ "NewUserDic", "builds", "a", "user", "dictionary", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/tokenizer/udic.go#L101-L127
15,589
ikawaha/kagome
internal/dic/dic.go
CharacterCategory
func (d Dic) CharacterCategory(r rune) byte { if int(r) < len(d.CharCategory) { return d.CharCategory[r] } return d.CharCategory[0] // default }
go
func (d Dic) CharacterCategory(r rune) byte { if int(r) < len(d.CharCategory) { return d.CharCategory[r] } return d.CharCategory[0] // default }
[ "func", "(", "d", "Dic", ")", "CharacterCategory", "(", "r", "rune", ")", "byte", "{", "if", "int", "(", "r", ")", "<", "len", "(", "d", ".", "CharCategory", ")", "{", "return", "d", ".", "CharCategory", "[", "r", "]", "\n", "}", "\n", "return", "d", ".", "CharCategory", "[", "0", "]", "// default", "\n", "}" ]
// CharacterCategory returns the category of a rune.
[ "CharacterCategory", "returns", "the", "category", "of", "a", "rune", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/dic.go#L41-L46
15,590
ikawaha/kagome
internal/dic/dic.go
Load
func Load(path string) (d *Dic, err error) { r, err := zip.OpenReader(path) if err != nil { return d, err } defer r.Close() return load(&r.Reader, true) }
go
func Load(path string) (d *Dic, err error) { r, err := zip.OpenReader(path) if err != nil { return d, err } defer r.Close() return load(&r.Reader, true) }
[ "func", "Load", "(", "path", "string", ")", "(", "d", "*", "Dic", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "zip", ".", "OpenReader", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "err", "\n", "}", "\n", "defer", "r", ".", "Close", "(", ")", "\n", "return", "load", "(", "&", "r", ".", "Reader", ",", "true", ")", "\n", "}" ]
// Load loads a dictionary from a file.
[ "Load", "loads", "a", "dictionary", "from", "a", "file", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/dic.go#L120-L127
15,591
ikawaha/kagome
internal/dic/dic.go
LoadSimple
func LoadSimple(path string) (d *Dic, err error) { r, err := zip.OpenReader(path) if err != nil { return d, err } defer r.Close() return load(&r.Reader, false) }
go
func LoadSimple(path string) (d *Dic, err error) { r, err := zip.OpenReader(path) if err != nil { return d, err } defer r.Close() return load(&r.Reader, false) }
[ "func", "LoadSimple", "(", "path", "string", ")", "(", "d", "*", "Dic", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "zip", ".", "OpenReader", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "err", "\n", "}", "\n", "defer", "r", ".", "Close", "(", ")", "\n", "return", "load", "(", "&", "r", ".", "Reader", ",", "false", ")", "\n", "}" ]
// LoadSimple loads a dictionary from a file without contents.
[ "LoadSimple", "loads", "a", "dictionary", "from", "a", "file", "without", "contents", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/dic.go#L130-L137
15,592
ikawaha/kagome
internal/dic/pos.go
WriteTo
func (p POSTable) WriteTo(w io.Writer) (int64, error) { var b bytes.Buffer enc := gob.NewEncoder(&b) if err := enc.Encode(p.POSs); err != nil { return 0, err } if err := enc.Encode(p.NameList); err != nil { return 0, err } return b.WriteTo(w) }
go
func (p POSTable) WriteTo(w io.Writer) (int64, error) { var b bytes.Buffer enc := gob.NewEncoder(&b) if err := enc.Encode(p.POSs); err != nil { return 0, err } if err := enc.Encode(p.NameList); err != nil { return 0, err } return b.WriteTo(w) }
[ "func", "(", "p", "POSTable", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "var", "b", "bytes", ".", "Buffer", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "&", "b", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "p", ".", "POSs", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "p", ".", "NameList", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "b", ".", "WriteTo", "(", "w", ")", "\n", "}" ]
// WriteTo saves a POS table.
[ "WriteTo", "saves", "a", "POS", "table", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/pos.go#L37-L47
15,593
ikawaha/kagome
internal/dic/pos.go
ReadPOSTable
func ReadPOSTable(r io.Reader) (POSTable, error) { t := POSTable{} dec := gob.NewDecoder(r) if err := dec.Decode(&t.POSs); err != nil { return t, fmt.Errorf("POSs read error, %v", err) } if err := dec.Decode(&t.NameList); err != nil { return t, fmt.Errorf("name list read error, %v", err) } return t, nil }
go
func ReadPOSTable(r io.Reader) (POSTable, error) { t := POSTable{} dec := gob.NewDecoder(r) if err := dec.Decode(&t.POSs); err != nil { return t, fmt.Errorf("POSs read error, %v", err) } if err := dec.Decode(&t.NameList); err != nil { return t, fmt.Errorf("name list read error, %v", err) } return t, nil }
[ "func", "ReadPOSTable", "(", "r", "io", ".", "Reader", ")", "(", "POSTable", ",", "error", ")", "{", "t", ":=", "POSTable", "{", "}", "\n", "dec", ":=", "gob", ".", "NewDecoder", "(", "r", ")", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "t", ".", "POSs", ")", ";", "err", "!=", "nil", "{", "return", "t", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "t", ".", "NameList", ")", ";", "err", "!=", "nil", "{", "return", "t", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}" ]
// ReadPOSTable loads a POS table.
[ "ReadPOSTable", "loads", "a", "POS", "table", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/pos.go#L50-L60
15,594
ikawaha/kagome
internal/dic/pos.go
Add
func (p POSMap) Add(pos []string) POS { ret := make(POS, 0, len(pos)) for _, name := range pos { id := p.add(name) ret = append(ret, id) } return ret }
go
func (p POSMap) Add(pos []string) POS { ret := make(POS, 0, len(pos)) for _, name := range pos { id := p.add(name) ret = append(ret, id) } return ret }
[ "func", "(", "p", "POSMap", ")", "Add", "(", "pos", "[", "]", "string", ")", "POS", "{", "ret", ":=", "make", "(", "POS", ",", "0", ",", "len", "(", "pos", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "pos", "{", "id", ":=", "p", ".", "add", "(", "name", ")", "\n", "ret", "=", "append", "(", "ret", ",", "id", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Add adds part of speech item to the POS control table and returns it's id.
[ "Add", "adds", "part", "of", "speech", "item", "to", "the", "POS", "control", "table", "and", "returns", "it", "s", "id", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/pos.go#L66-L73
15,595
ikawaha/kagome
internal/dic/pos.go
List
func (p POSMap) List() []string { ret := make([]string, len(p)+1) for k, v := range p { ret[v] = k } return ret }
go
func (p POSMap) List() []string { ret := make([]string, len(p)+1) for k, v := range p { ret[v] = k } return ret }
[ "func", "(", "p", "POSMap", ")", "List", "(", ")", "[", "]", "string", "{", "ret", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "p", ")", "+", "1", ")", "\n", "for", "k", ",", "v", ":=", "range", "p", "{", "ret", "[", "v", "]", "=", "k", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// List returns a list whose index is POS ID and value is its name.
[ "List", "returns", "a", "list", "whose", "index", "is", "POS", "ID", "and", "value", "is", "its", "name", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/dic/pos.go#L85-L91
15,596
ikawaha/kagome
internal/da/da.go
BuildWithIDs
func BuildWithIDs(keywords []string, ids []int) (DoubleArray, error) { d := DoubleArray{} d.init() if len(keywords) != len(ids) { return d, fmt.Errorf("invalid arguments") } if len(keywords) == 0 { return d, nil } if !sort.StringsAreSorted(keywords) { h := make(map[string]int) for i, key := range keywords { h[key] = ids[i] } sort.Strings(keywords) ids = ids[:0] for _, key := range keywords { ids = append(ids, h[key]) } } branches := make([]int, len(keywords)) for i := range keywords { branches[i] = i } d.add(0, 0, branches, keywords, ids) d.truncate() return d, nil }
go
func BuildWithIDs(keywords []string, ids []int) (DoubleArray, error) { d := DoubleArray{} d.init() if len(keywords) != len(ids) { return d, fmt.Errorf("invalid arguments") } if len(keywords) == 0 { return d, nil } if !sort.StringsAreSorted(keywords) { h := make(map[string]int) for i, key := range keywords { h[key] = ids[i] } sort.Strings(keywords) ids = ids[:0] for _, key := range keywords { ids = append(ids, h[key]) } } branches := make([]int, len(keywords)) for i := range keywords { branches[i] = i } d.add(0, 0, branches, keywords, ids) d.truncate() return d, nil }
[ "func", "BuildWithIDs", "(", "keywords", "[", "]", "string", ",", "ids", "[", "]", "int", ")", "(", "DoubleArray", ",", "error", ")", "{", "d", ":=", "DoubleArray", "{", "}", "\n", "d", ".", "init", "(", ")", "\n", "if", "len", "(", "keywords", ")", "!=", "len", "(", "ids", ")", "{", "return", "d", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "keywords", ")", "==", "0", "{", "return", "d", ",", "nil", "\n", "}", "\n", "if", "!", "sort", ".", "StringsAreSorted", "(", "keywords", ")", "{", "h", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "i", ",", "key", ":=", "range", "keywords", "{", "h", "[", "key", "]", "=", "ids", "[", "i", "]", "\n", "}", "\n", "sort", ".", "Strings", "(", "keywords", ")", "\n", "ids", "=", "ids", "[", ":", "0", "]", "\n", "for", "_", ",", "key", ":=", "range", "keywords", "{", "ids", "=", "append", "(", "ids", ",", "h", "[", "key", "]", ")", "\n", "}", "\n", "}", "\n", "branches", ":=", "make", "(", "[", "]", "int", ",", "len", "(", "keywords", ")", ")", "\n", "for", "i", ":=", "range", "keywords", "{", "branches", "[", "i", "]", "=", "i", "\n", "}", "\n", "d", ".", "add", "(", "0", ",", "0", ",", "branches", ",", "keywords", ",", "ids", ")", "\n", "d", ".", "truncate", "(", ")", "\n", "return", "d", ",", "nil", "\n", "}" ]
// BuildWithIDs constructs a double array from given keywords and ids.
[ "BuildWithIDs", "constructs", "a", "double", "array", "from", "given", "keywords", "and", "ids", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/da/da.go#L50-L77
15,597
ikawaha/kagome
internal/da/da.go
Find
func (d DoubleArray) Find(input string) (id int, ok bool) { _, q, _, ok := d.search(input) if !ok { return } p := q q = int(d[p].Base) + int(terminator) if q >= len(d) || int(d[q].Check) != p || d[q].Base > 0 { return } return int(-d[q].Base), true }
go
func (d DoubleArray) Find(input string) (id int, ok bool) { _, q, _, ok := d.search(input) if !ok { return } p := q q = int(d[p].Base) + int(terminator) if q >= len(d) || int(d[q].Check) != p || d[q].Base > 0 { return } return int(-d[q].Base), true }
[ "func", "(", "d", "DoubleArray", ")", "Find", "(", "input", "string", ")", "(", "id", "int", ",", "ok", "bool", ")", "{", "_", ",", "q", ",", "_", ",", "ok", ":=", "d", ".", "search", "(", "input", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "p", ":=", "q", "\n", "q", "=", "int", "(", "d", "[", "p", "]", ".", "Base", ")", "+", "int", "(", "terminator", ")", "\n", "if", "q", ">=", "len", "(", "d", ")", "||", "int", "(", "d", "[", "q", "]", ".", "Check", ")", "!=", "p", "||", "d", "[", "q", "]", ".", "Base", ">", "0", "{", "return", "\n", "}", "\n", "return", "int", "(", "-", "d", "[", "q", "]", ".", "Base", ")", ",", "true", "\n", "}" ]
// Find searches TRIE by a given keyword and returns the id if found.
[ "Find", "searches", "TRIE", "by", "a", "given", "keyword", "and", "returns", "the", "id", "if", "found", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/da/da.go#L80-L91
15,598
ikawaha/kagome
internal/da/da.go
PrefixSearch
func (d DoubleArray) PrefixSearch(input string) (id int, ok bool) { var p, q, i int bufLen := len(d) for size := len(input); i < size; i++ { if input[i] == terminator { return } p = q q = int(d[p].Base) + int(input[i]) if q >= bufLen || int(d[q].Check) != p { break } ahead := int(d[q].Base) + int(terminator) if ahead < bufLen && int(d[ahead].Check) == q && int(d[ahead].Base) <= 0 { id = int(-d[ahead].Base) ok = true } } return }
go
func (d DoubleArray) PrefixSearch(input string) (id int, ok bool) { var p, q, i int bufLen := len(d) for size := len(input); i < size; i++ { if input[i] == terminator { return } p = q q = int(d[p].Base) + int(input[i]) if q >= bufLen || int(d[q].Check) != p { break } ahead := int(d[q].Base) + int(terminator) if ahead < bufLen && int(d[ahead].Check) == q && int(d[ahead].Base) <= 0 { id = int(-d[ahead].Base) ok = true } } return }
[ "func", "(", "d", "DoubleArray", ")", "PrefixSearch", "(", "input", "string", ")", "(", "id", "int", ",", "ok", "bool", ")", "{", "var", "p", ",", "q", ",", "i", "int", "\n", "bufLen", ":=", "len", "(", "d", ")", "\n", "for", "size", ":=", "len", "(", "input", ")", ";", "i", "<", "size", ";", "i", "++", "{", "if", "input", "[", "i", "]", "==", "terminator", "{", "return", "\n", "}", "\n", "p", "=", "q", "\n", "q", "=", "int", "(", "d", "[", "p", "]", ".", "Base", ")", "+", "int", "(", "input", "[", "i", "]", ")", "\n", "if", "q", ">=", "bufLen", "||", "int", "(", "d", "[", "q", "]", ".", "Check", ")", "!=", "p", "{", "break", "\n", "}", "\n", "ahead", ":=", "int", "(", "d", "[", "q", "]", ".", "Base", ")", "+", "int", "(", "terminator", ")", "\n", "if", "ahead", "<", "bufLen", "&&", "int", "(", "d", "[", "ahead", "]", ".", "Check", ")", "==", "q", "&&", "int", "(", "d", "[", "ahead", "]", ".", "Base", ")", "<=", "0", "{", "id", "=", "int", "(", "-", "d", "[", "ahead", "]", ".", "Base", ")", "\n", "ok", "=", "true", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// PrefixSearch returns the longest common prefix keyword in an input if found.
[ "PrefixSearch", "returns", "the", "longest", "common", "prefix", "keyword", "in", "an", "input", "if", "found", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/da/da.go#L139-L158
15,599
ikawaha/kagome
internal/da/da.go
WriteTo
func (d DoubleArray) WriteTo(w io.Writer) (n int64, err error) { sz := int64(len(d)) //fmt.Println("write data len:", sz) if err = binary.Write(w, binary.LittleEndian, sz); err != nil { return } n += int64(binary.Size(sz)) for _, v := range d { if err = binary.Write(w, binary.LittleEndian, v.Base); err != nil { return } n += int64(binary.Size(v.Base)) if err = binary.Write(w, binary.LittleEndian, v.Check); err != nil { return } n += int64(binary.Size(v.Check)) } return }
go
func (d DoubleArray) WriteTo(w io.Writer) (n int64, err error) { sz := int64(len(d)) //fmt.Println("write data len:", sz) if err = binary.Write(w, binary.LittleEndian, sz); err != nil { return } n += int64(binary.Size(sz)) for _, v := range d { if err = binary.Write(w, binary.LittleEndian, v.Base); err != nil { return } n += int64(binary.Size(v.Base)) if err = binary.Write(w, binary.LittleEndian, v.Check); err != nil { return } n += int64(binary.Size(v.Check)) } return }
[ "func", "(", "d", "DoubleArray", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "sz", ":=", "int64", "(", "len", "(", "d", ")", ")", "\n", "//fmt.Println(\"write data len:\", sz)", "if", "err", "=", "binary", ".", "Write", "(", "w", ",", "binary", ".", "LittleEndian", ",", "sz", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", "+=", "int64", "(", "binary", ".", "Size", "(", "sz", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "d", "{", "if", "err", "=", "binary", ".", "Write", "(", "w", ",", "binary", ".", "LittleEndian", ",", "v", ".", "Base", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", "+=", "int64", "(", "binary", ".", "Size", "(", "v", ".", "Base", ")", ")", "\n", "if", "err", "=", "binary", ".", "Write", "(", "w", ",", "binary", ".", "LittleEndian", ",", "v", ".", "Check", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", "+=", "int64", "(", "binary", ".", "Size", "(", "v", ".", "Check", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// WriteTo saves a double array.
[ "WriteTo", "saves", "a", "double", "array", "." ]
d76ce24c16d24bc8968d32681d92db4d7ff6bd2d
https://github.com/ikawaha/kagome/blob/d76ce24c16d24bc8968d32681d92db4d7ff6bd2d/internal/da/da.go#L161-L179