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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
17,300 | mdlayher/waveform | options.go | Scale | func Scale(x uint, y uint) OptionsFunc {
return func(w *Waveform) error {
return w.setScale(x, y)
}
} | go | func Scale(x uint, y uint) OptionsFunc {
return func(w *Waveform) error {
return w.setScale(x, y)
}
} | [
"func",
"Scale",
"(",
"x",
"uint",
",",
"y",
"uint",
")",
"OptionsFunc",
"{",
"return",
"func",
"(",
"w",
"*",
"Waveform",
")",
"error",
"{",
"return",
"w",
".",
"setScale",
"(",
"x",
",",
"y",
")",
"\n",
"}",
"\n",
"}"
] | // Scale generates an OptionsFunc which applies the input X and Y axis scaling
// factors to an input Waveform struct.
//
// This value indicates how a generated waveform image will be scaled, for both
// its X and Y axes. | [
"Scale",
"generates",
"an",
"OptionsFunc",
"which",
"applies",
"the",
"input",
"X",
"and",
"Y",
"axis",
"scaling",
"factors",
"to",
"an",
"input",
"Waveform",
"struct",
".",
"This",
"value",
"indicates",
"how",
"a",
"generated",
"waveform",
"image",
"will",
... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L209-L213 |
17,301 | mdlayher/waveform | options.go | SetScale | func (w *Waveform) SetScale(x uint, y uint) error {
return w.SetOptions(Scale(x, y))
} | go | func (w *Waveform) SetScale(x uint, y uint) error {
return w.SetOptions(Scale(x, y))
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"SetScale",
"(",
"x",
"uint",
",",
"y",
"uint",
")",
"error",
"{",
"return",
"w",
".",
"SetOptions",
"(",
"Scale",
"(",
"x",
",",
"y",
")",
")",
"\n",
"}"
] | // SetScale applies the input X and Y axis scaling to the receiving Waveform
// struct. | [
"SetScale",
"applies",
"the",
"input",
"X",
"and",
"Y",
"axis",
"scaling",
"to",
"the",
"receiving",
"Waveform",
"struct",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L217-L219 |
17,302 | mdlayher/waveform | options.go | setScale | func (w *Waveform) setScale(x uint, y uint) error {
// X scale cannot be zero
if x == 0 {
return errScaleXZero
}
// Y scale cannot be zero
if y == 0 {
return errScaleYZero
}
w.scaleX = x
w.scaleY = y
return nil
} | go | func (w *Waveform) setScale(x uint, y uint) error {
// X scale cannot be zero
if x == 0 {
return errScaleXZero
}
// Y scale cannot be zero
if y == 0 {
return errScaleYZero
}
w.scaleX = x
w.scaleY = y
return nil
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"setScale",
"(",
"x",
"uint",
",",
"y",
"uint",
")",
"error",
"{",
"// X scale cannot be zero",
"if",
"x",
"==",
"0",
"{",
"return",
"errScaleXZero",
"\n",
"}",
"\n\n",
"// Y scale cannot be zero",
"if",
"y",
"==",
... | // setScale directly sets the scaleX and scaleY members of the receiving Waveform
// struct. | [
"setScale",
"directly",
"sets",
"the",
"scaleX",
"and",
"scaleY",
"members",
"of",
"the",
"receiving",
"Waveform",
"struct",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L223-L239 |
17,303 | mdlayher/waveform | options.go | setScaleClipping | func (w *Waveform) setScaleClipping(scaleClipping bool) error {
w.scaleClipping = scaleClipping
return nil
} | go | func (w *Waveform) setScaleClipping(scaleClipping bool) error {
w.scaleClipping = scaleClipping
return nil
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"setScaleClipping",
"(",
"scaleClipping",
"bool",
")",
"error",
"{",
"w",
".",
"scaleClipping",
"=",
"scaleClipping",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // setScaleClipping directly sets the scaleClipping member of the receiving Waveform
// struct. | [
"setScaleClipping",
"directly",
"sets",
"the",
"scaleClipping",
"member",
"of",
"the",
"receiving",
"Waveform",
"struct",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L261-L265 |
17,304 | mdlayher/waveform | options.go | Sharpness | func Sharpness(sharpness uint) OptionsFunc {
return func(w *Waveform) error {
return w.setSharpness(sharpness)
}
} | go | func Sharpness(sharpness uint) OptionsFunc {
return func(w *Waveform) error {
return w.setSharpness(sharpness)
}
} | [
"func",
"Sharpness",
"(",
"sharpness",
"uint",
")",
"OptionsFunc",
"{",
"return",
"func",
"(",
"w",
"*",
"Waveform",
")",
"error",
"{",
"return",
"w",
".",
"setSharpness",
"(",
"sharpness",
")",
"\n",
"}",
"\n",
"}"
] | // Sharpness generates an OptionsFunc which applies the input sharpness
// value to an input Waveform struct.
//
// This value indicates the amount of curvature which is applied to a
// waveform image, scaled on its X-axis. A higher value results in steeper
// curves, and a lower value results in more "blocky" curves. | [
"Sharpness",
"generates",
"an",
"OptionsFunc",
"which",
"applies",
"the",
"input",
"sharpness",
"value",
"to",
"an",
"input",
"Waveform",
"struct",
".",
"This",
"value",
"indicates",
"the",
"amount",
"of",
"curvature",
"which",
"is",
"applied",
"to",
"a",
"wav... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L273-L277 |
17,305 | mdlayher/waveform | options.go | SetSharpness | func (w *Waveform) SetSharpness(sharpness uint) error {
return w.SetOptions(Sharpness(sharpness))
} | go | func (w *Waveform) SetSharpness(sharpness uint) error {
return w.SetOptions(Sharpness(sharpness))
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"SetSharpness",
"(",
"sharpness",
"uint",
")",
"error",
"{",
"return",
"w",
".",
"SetOptions",
"(",
"Sharpness",
"(",
"sharpness",
")",
")",
"\n",
"}"
] | // SetSharpness applies the input sharpness to the receiving Waveform struct. | [
"SetSharpness",
"applies",
"the",
"input",
"sharpness",
"to",
"the",
"receiving",
"Waveform",
"struct",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L280-L282 |
17,306 | mdlayher/waveform | options.go | setSharpness | func (w *Waveform) setSharpness(sharpness uint) error {
w.sharpness = sharpness
return nil
} | go | func (w *Waveform) setSharpness(sharpness uint) error {
w.sharpness = sharpness
return nil
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"setSharpness",
"(",
"sharpness",
"uint",
")",
"error",
"{",
"w",
".",
"sharpness",
"=",
"sharpness",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // setSharpness directly sets the sharpness member of the receiving Waveform
// struct. | [
"setSharpness",
"directly",
"sets",
"the",
"sharpness",
"member",
"of",
"the",
"receiving",
"Waveform",
"struct",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/options.go#L286-L290 |
17,307 | mdlayher/waveform | colorfunc.go | CheckerColor | func CheckerColor(colorA color.Color, colorB color.Color, size uint) ColorFunc {
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
if ((uint(x)/size)+(uint(y)/size))%2 == 0 {
return colorA
}
return colorB
}
} | go | func CheckerColor(colorA color.Color, colorB color.Color, size uint) ColorFunc {
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
if ((uint(x)/size)+(uint(y)/size))%2 == 0 {
return colorA
}
return colorB
}
} | [
"func",
"CheckerColor",
"(",
"colorA",
"color",
".",
"Color",
",",
"colorB",
"color",
".",
"Color",
",",
"size",
"uint",
")",
"ColorFunc",
"{",
"return",
"func",
"(",
"n",
"int",
",",
"x",
"int",
",",
"y",
"int",
",",
"maxN",
"int",
",",
"maxX",
"i... | // CheckerColor generates a ColorFunc which produces a checkerboard pattern,
// using the two input colors. Each square is drawn to the size specified by
// the size parameter. | [
"CheckerColor",
"generates",
"a",
"ColorFunc",
"which",
"produces",
"a",
"checkerboard",
"pattern",
"using",
"the",
"two",
"input",
"colors",
".",
"Each",
"square",
"is",
"drawn",
"to",
"the",
"size",
"specified",
"by",
"the",
"size",
"parameter",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/colorfunc.go#L22-L30 |
17,308 | mdlayher/waveform | colorfunc.go | FuzzColor | func FuzzColor(colors ...color.Color) ColorFunc {
// Filter any nil values
colors = filterNilColors(colors)
// Seed RNG
rand.Seed(time.Now().UnixNano())
// Select a color at random on each call
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
return colors[rand.Intn(len(colors))]
}
} | go | func FuzzColor(colors ...color.Color) ColorFunc {
// Filter any nil values
colors = filterNilColors(colors)
// Seed RNG
rand.Seed(time.Now().UnixNano())
// Select a color at random on each call
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
return colors[rand.Intn(len(colors))]
}
} | [
"func",
"FuzzColor",
"(",
"colors",
"...",
"color",
".",
"Color",
")",
"ColorFunc",
"{",
"// Filter any nil values",
"colors",
"=",
"filterNilColors",
"(",
"colors",
")",
"\n\n",
"// Seed RNG",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"... | // FuzzColor generates a ColorFunc which applies a random color on each call,
// selected from an input, variadic slice of colors. This can be used to create
// a random fuzz or "static" effect in the resulting waveform image. | [
"FuzzColor",
"generates",
"a",
"ColorFunc",
"which",
"applies",
"a",
"random",
"color",
"on",
"each",
"call",
"selected",
"from",
"an",
"input",
"variadic",
"slice",
"of",
"colors",
".",
"This",
"can",
"be",
"used",
"to",
"create",
"a",
"random",
"fuzz",
"... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/colorfunc.go#L35-L46 |
17,309 | mdlayher/waveform | colorfunc.go | GradientColor | func GradientColor(start color.RGBA, end color.RGBA) ColorFunc {
// Float equivalents of color values
startFR, endFR := float64(start.R), float64(end.R)
startFG, endFG := float64(start.G), float64(end.G)
startFB, endFB := float64(start.B), float64(end.B)
// Values used for RGBA and percentage
var r, g, b, p float64
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
// Calculate percentage across waveform image
p = float64((float64(n) / float64(maxN)) * 100)
// Calculate new values for RGB using gradient algorithm
// Thanks: http://stackoverflow.com/questions/27532/generating-gradients-programmatically
r = (endFR * p) + (startFR * (1 - p))
g = (endFG * p) + (startFG * (1 - p))
b = (endFB * p) + (startFB * (1 - p))
// Correct overflow when moving from lighter to darker gradients
if start.R > end.R && r > -255.00 {
r = -255.00
}
if start.G > end.G && g > -255.00 {
g = -255.00
}
if start.B > end.B && b > -255.00 {
b = -255.00
}
// Generate output color
return &color.RGBA{
R: uint8(r / 100),
G: uint8(g / 100),
B: uint8(b / 100),
A: 255,
}
}
} | go | func GradientColor(start color.RGBA, end color.RGBA) ColorFunc {
// Float equivalents of color values
startFR, endFR := float64(start.R), float64(end.R)
startFG, endFG := float64(start.G), float64(end.G)
startFB, endFB := float64(start.B), float64(end.B)
// Values used for RGBA and percentage
var r, g, b, p float64
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
// Calculate percentage across waveform image
p = float64((float64(n) / float64(maxN)) * 100)
// Calculate new values for RGB using gradient algorithm
// Thanks: http://stackoverflow.com/questions/27532/generating-gradients-programmatically
r = (endFR * p) + (startFR * (1 - p))
g = (endFG * p) + (startFG * (1 - p))
b = (endFB * p) + (startFB * (1 - p))
// Correct overflow when moving from lighter to darker gradients
if start.R > end.R && r > -255.00 {
r = -255.00
}
if start.G > end.G && g > -255.00 {
g = -255.00
}
if start.B > end.B && b > -255.00 {
b = -255.00
}
// Generate output color
return &color.RGBA{
R: uint8(r / 100),
G: uint8(g / 100),
B: uint8(b / 100),
A: 255,
}
}
} | [
"func",
"GradientColor",
"(",
"start",
"color",
".",
"RGBA",
",",
"end",
"color",
".",
"RGBA",
")",
"ColorFunc",
"{",
"// Float equivalents of color values",
"startFR",
",",
"endFR",
":=",
"float64",
"(",
"start",
".",
"R",
")",
",",
"float64",
"(",
"end",
... | // GradientColor generates a ColorFunc which produces a color gradient between two
// RGBA input colors. The gradient attempts to gradually reduce the distance between
// two colors, creating a sweeping color change effect in the resulting waveform
// image. | [
"GradientColor",
"generates",
"a",
"ColorFunc",
"which",
"produces",
"a",
"color",
"gradient",
"between",
"two",
"RGBA",
"input",
"colors",
".",
"The",
"gradient",
"attempts",
"to",
"gradually",
"reduce",
"the",
"distance",
"between",
"two",
"colors",
"creating",
... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/colorfunc.go#L52-L89 |
17,310 | mdlayher/waveform | colorfunc.go | SolidColor | func SolidColor(inColor color.Color) ColorFunc {
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
return inColor
}
} | go | func SolidColor(inColor color.Color) ColorFunc {
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
return inColor
}
} | [
"func",
"SolidColor",
"(",
"inColor",
"color",
".",
"Color",
")",
"ColorFunc",
"{",
"return",
"func",
"(",
"n",
"int",
",",
"x",
"int",
",",
"y",
"int",
",",
"maxN",
"int",
",",
"maxX",
"int",
",",
"maxY",
"int",
")",
"color",
".",
"Color",
"{",
... | // SolidColor generates a ColorFunc which simply returns the input color
// as the color which should be drawn at all coordinates.
//
// This is the default behavior of the waveform package. | [
"SolidColor",
"generates",
"a",
"ColorFunc",
"which",
"simply",
"returns",
"the",
"input",
"color",
"as",
"the",
"color",
"which",
"should",
"be",
"drawn",
"at",
"all",
"coordinates",
".",
"This",
"is",
"the",
"default",
"behavior",
"of",
"the",
"waveform",
... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/colorfunc.go#L95-L99 |
17,311 | mdlayher/waveform | colorfunc.go | StripeColor | func StripeColor(colors ...color.Color) ColorFunc {
// Filter any nil values
colors = filterNilColors(colors)
var lastN int
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
// For each new n value, use the next color in the slice
if n > lastN {
lastN = n
}
return colors[lastN%len(colors)]
}
} | go | func StripeColor(colors ...color.Color) ColorFunc {
// Filter any nil values
colors = filterNilColors(colors)
var lastN int
return func(n int, x int, y int, maxN int, maxX int, maxY int) color.Color {
// For each new n value, use the next color in the slice
if n > lastN {
lastN = n
}
return colors[lastN%len(colors)]
}
} | [
"func",
"StripeColor",
"(",
"colors",
"...",
"color",
".",
"Color",
")",
"ColorFunc",
"{",
"// Filter any nil values",
"colors",
"=",
"filterNilColors",
"(",
"colors",
")",
"\n\n",
"var",
"lastN",
"int",
"\n",
"return",
"func",
"(",
"n",
"int",
",",
"x",
"... | // StripeColor generates a ColorFunc which applies one color from the input,
// variadic slice at each computed value. Each color is used in order, and
// the rotation will repeat until the image is complete. This creates a stripe
// effect in the resulting waveform image. | [
"StripeColor",
"generates",
"a",
"ColorFunc",
"which",
"applies",
"one",
"color",
"from",
"the",
"input",
"variadic",
"slice",
"at",
"each",
"computed",
"value",
".",
"Each",
"color",
"is",
"used",
"in",
"order",
"and",
"the",
"rotation",
"will",
"repeat",
"... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/colorfunc.go#L105-L118 |
17,312 | mdlayher/waveform | colorfunc.go | filterNilColors | func filterNilColors(colors []color.Color) []color.Color {
var cleanColors []color.Color
for _, c := range colors {
if c != nil {
cleanColors = append(cleanColors, c)
}
}
return cleanColors
} | go | func filterNilColors(colors []color.Color) []color.Color {
var cleanColors []color.Color
for _, c := range colors {
if c != nil {
cleanColors = append(cleanColors, c)
}
}
return cleanColors
} | [
"func",
"filterNilColors",
"(",
"colors",
"[",
"]",
"color",
".",
"Color",
")",
"[",
"]",
"color",
".",
"Color",
"{",
"var",
"cleanColors",
"[",
"]",
"color",
".",
"Color",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"colors",
"{",
"if",
"c",
"!=",
... | // filterNilColors strips any nil color.Color values from the input slice. | [
"filterNilColors",
"strips",
"any",
"nil",
"color",
".",
"Color",
"values",
"from",
"the",
"input",
"slice",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/colorfunc.go#L121-L130 |
17,313 | mdlayher/waveform | waveform.go | Generate | func Generate(r io.Reader, options ...OptionsFunc) (image.Image, error) {
w, err := New(r, options...)
if err != nil {
return nil, err
}
values, err := w.Compute()
return w.Draw(values), err
} | go | func Generate(r io.Reader, options ...OptionsFunc) (image.Image, error) {
w, err := New(r, options...)
if err != nil {
return nil, err
}
values, err := w.Compute()
return w.Draw(values), err
} | [
"func",
"Generate",
"(",
"r",
"io",
".",
"Reader",
",",
"options",
"...",
"OptionsFunc",
")",
"(",
"image",
".",
"Image",
",",
"error",
")",
"{",
"w",
",",
"err",
":=",
"New",
"(",
"r",
",",
"options",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // Generate immediately opens and reads an input audio stream, computes
// the values required for waveform generation, and returns a waveform image
// which is customized by zero or more, variadic, OptionsFunc parameters.
//
// Generate is equivalent to calling New, followed by the Compute and Draw
// methods of a Waveform struct. In general, Generate should only be used
// for one-time waveform image generation. | [
"Generate",
"immediately",
"opens",
"and",
"reads",
"an",
"input",
"audio",
"stream",
"computes",
"the",
"values",
"required",
"for",
"waveform",
"generation",
"and",
"returns",
"a",
"waveform",
"image",
"which",
"is",
"customized",
"by",
"zero",
"or",
"more",
... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/waveform.go#L68-L76 |
17,314 | mdlayher/waveform | waveform.go | New | func New(r io.Reader, options ...OptionsFunc) (*Waveform, error) {
// Generate Waveform struct with sane defaults
w := &Waveform{
// Read from input stream
r: r,
// Read audio and compute values once per second of audio
resolution: 1,
// Use RMSF64Samples as a SampleReduceFunc
sampleFn: RMSF64Samples,
// Generate solid, black background color with solid, white
// foreground color waveform using ColorFunc
bgColorFn: SolidColor(color.White),
fgColorFn: SolidColor(color.Black),
// No scaling
scaleX: 1,
scaleY: 1,
// Normal sharpness
sharpness: 1,
// Do not scale clipping values
scaleClipping: false,
}
// Apply any input OptionsFunc on return
return w, w.SetOptions(options...)
} | go | func New(r io.Reader, options ...OptionsFunc) (*Waveform, error) {
// Generate Waveform struct with sane defaults
w := &Waveform{
// Read from input stream
r: r,
// Read audio and compute values once per second of audio
resolution: 1,
// Use RMSF64Samples as a SampleReduceFunc
sampleFn: RMSF64Samples,
// Generate solid, black background color with solid, white
// foreground color waveform using ColorFunc
bgColorFn: SolidColor(color.White),
fgColorFn: SolidColor(color.Black),
// No scaling
scaleX: 1,
scaleY: 1,
// Normal sharpness
sharpness: 1,
// Do not scale clipping values
scaleClipping: false,
}
// Apply any input OptionsFunc on return
return w, w.SetOptions(options...)
} | [
"func",
"New",
"(",
"r",
"io",
".",
"Reader",
",",
"options",
"...",
"OptionsFunc",
")",
"(",
"*",
"Waveform",
",",
"error",
")",
"{",
"// Generate Waveform struct with sane defaults",
"w",
":=",
"&",
"Waveform",
"{",
"// Read from input stream",
"r",
":",
"r"... | // New generates a new Waveform struct, applying any input OptionsFunc
// on return. | [
"New",
"generates",
"a",
"new",
"Waveform",
"struct",
"applying",
"any",
"input",
"OptionsFunc",
"on",
"return",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/waveform.go#L80-L110 |
17,315 | mdlayher/waveform | waveform.go | Draw | func (w *Waveform) Draw(values []float64) image.Image {
return w.generateImage(values)
} | go | func (w *Waveform) Draw(values []float64) image.Image {
return w.generateImage(values)
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"Draw",
"(",
"values",
"[",
"]",
"float64",
")",
"image",
".",
"Image",
"{",
"return",
"w",
".",
"generateImage",
"(",
"values",
")",
"\n",
"}"
] | // Draw creates a new image.Image from a slice of float64 values.
//
// Draw is typically used after a waveform has been computed one time, and a slice
// of computed values was returned from the first computation. Subsequent calls to
// Draw may be used to customize a waveform using the same input values. | [
"Draw",
"creates",
"a",
"new",
"image",
".",
"Image",
"from",
"a",
"slice",
"of",
"float64",
"values",
".",
"Draw",
"is",
"typically",
"used",
"after",
"a",
"waveform",
"has",
"been",
"computed",
"one",
"time",
"and",
"a",
"slice",
"of",
"computed",
"val... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/waveform.go#L126-L128 |
17,316 | mdlayher/waveform | waveform.go | readAndComputeSamples | func (w *Waveform) readAndComputeSamples() ([]float64, error) {
// Validate struct members
// These checks are also done when applying options, but verifying them here
// will prevent a runtime panic if called on an empty Waveform instance.
if w.sampleFn == nil {
return nil, errSampleFunctionNil
}
if w.resolution == 0 {
return nil, errResolutionZero
}
// Open audio decoder on input stream
decoder, _, err := audio.NewDecoder(w.r)
if err != nil {
// Unknown format
if err == audio.ErrFormat {
return nil, ErrFormat
}
// Invalid data
if err == audio.ErrInvalidData {
return nil, ErrInvalidData
}
// Unexpected end-of-stream
if err == audio.ErrUnexpectedEOS {
return nil, ErrUnexpectedEOS
}
// All other errors
return nil, err
}
// computed is a slice of computed values by a SampleReduceFunc, from each
// slice of audio samples
var computed []float64
// Track the current computed value
var value float64
// samples is a slice of float64 audio samples, used to store decoded values
config := decoder.Config()
samples := make(audio.Float64, uint(config.SampleRate*config.Channels)/w.resolution)
for {
// Decode at specified resolution from options
// On any error other than end-of-stream, return
_, err := decoder.Read(samples)
if err != nil && err != audio.EOS {
return nil, err
}
// Apply SampleReduceFunc over float64 audio samples
value = w.sampleFn(samples)
// Store computed value
computed = append(computed, value)
// On end of stream, stop reading values
if err == audio.EOS {
break
}
}
// Return slice of computed values
return computed, nil
} | go | func (w *Waveform) readAndComputeSamples() ([]float64, error) {
// Validate struct members
// These checks are also done when applying options, but verifying them here
// will prevent a runtime panic if called on an empty Waveform instance.
if w.sampleFn == nil {
return nil, errSampleFunctionNil
}
if w.resolution == 0 {
return nil, errResolutionZero
}
// Open audio decoder on input stream
decoder, _, err := audio.NewDecoder(w.r)
if err != nil {
// Unknown format
if err == audio.ErrFormat {
return nil, ErrFormat
}
// Invalid data
if err == audio.ErrInvalidData {
return nil, ErrInvalidData
}
// Unexpected end-of-stream
if err == audio.ErrUnexpectedEOS {
return nil, ErrUnexpectedEOS
}
// All other errors
return nil, err
}
// computed is a slice of computed values by a SampleReduceFunc, from each
// slice of audio samples
var computed []float64
// Track the current computed value
var value float64
// samples is a slice of float64 audio samples, used to store decoded values
config := decoder.Config()
samples := make(audio.Float64, uint(config.SampleRate*config.Channels)/w.resolution)
for {
// Decode at specified resolution from options
// On any error other than end-of-stream, return
_, err := decoder.Read(samples)
if err != nil && err != audio.EOS {
return nil, err
}
// Apply SampleReduceFunc over float64 audio samples
value = w.sampleFn(samples)
// Store computed value
computed = append(computed, value)
// On end of stream, stop reading values
if err == audio.EOS {
break
}
}
// Return slice of computed values
return computed, nil
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"readAndComputeSamples",
"(",
")",
"(",
"[",
"]",
"float64",
",",
"error",
")",
"{",
"// Validate struct members",
"// These checks are also done when applying options, but verifying them here",
"// will prevent a runtime panic if called ... | // readAndComputeSamples opens the input audio stream, computes samples according
// to an input function, and returns a slice of computed values and any errors
// which occurred during the computation. | [
"readAndComputeSamples",
"opens",
"the",
"input",
"audio",
"stream",
"computes",
"samples",
"according",
"to",
"an",
"input",
"function",
"and",
"returns",
"a",
"slice",
"of",
"computed",
"values",
"and",
"any",
"errors",
"which",
"occurred",
"during",
"the",
"c... | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/waveform.go#L133-L198 |
17,317 | mdlayher/waveform | waveform.go | generateImage | func (w *Waveform) generateImage(computed []float64) image.Image {
// Store integer scale values
intScaleX := int(w.scaleX)
intScaleY := int(w.scaleY)
// Calculate maximum n, x, y, where:
// - n: number of computed values
// - x: number of pixels on X-axis
// - y: number of pixels on Y-axis
maxN := len(computed)
maxX := maxN * intScaleX
maxY := imgYDefault * intScaleY
// Create output, rectangular image
img := image.NewRGBA(image.Rect(0, 0, maxX, maxY))
bounds := img.Bounds()
// Calculate halfway point of Y-axis for image
imgHalfY := bounds.Max.Y / 2
// Calculate a peak value used for smoothing scaled X-axis images
peak := int(math.Ceil(float64(w.scaleX)) / 2)
// Calculate scaling factor, based upon maximum value computed by a SampleReduceFunc.
// If option ScaleClipping is true, when maximum value is above certain thresholds
// the scaling factor is reduced to show an accurate waveform with less clipping.
imgScale := scaleDefault
if w.scaleClipping {
// Find maximum value from input slice
var maxValue float64
for _, c := range computed {
if c > maxValue {
maxValue = c
}
}
// For each 0.05 maximum increment at 0.30 and above, reduce the scaling
// factor by 0.25. This is a rough estimate and may be tweaked in the future.
for i := 0.30; i < maxValue; i += 0.05 {
imgScale -= 0.25
}
}
// Values to be used for repeated computations
var scaleComputed, halfScaleComputed, adjust int
intBoundY := int(bounds.Max.Y)
f64BoundY := float64(bounds.Max.Y)
intSharpness := int(w.sharpness)
// Begin iterating all computed values
x := 0
for n := range computed {
// Scale computed value to an integer, using the height of the image and a constant
// scaling factor
scaleComputed = int(math.Floor(computed[n] * f64BoundY * imgScale))
// Calculate the halfway point for the scaled computed value
halfScaleComputed = scaleComputed / 2
// Draw background color down the entire Y-axis
for y := 0; y < intBoundY; y++ {
// If X-axis is being scaled, draw background over several X coordinates
for i := 0; i < intScaleX; i++ {
img.Set(x+i, y, w.bgColorFn(n, x+i, y, maxN, maxX, maxY))
}
}
// Iterate image coordinates on the Y-axis, generating a symmetrical waveform
// image above and below the center of the image
for y := imgHalfY - halfScaleComputed; y < scaleComputed+(imgHalfY-halfScaleComputed); y++ {
// If X-axis is being scaled, draw computed value over several X coordinates
for i := 0; i < intScaleX; i++ {
// When scaled, adjust computed value to be lower on either side of the peak,
// so that the image appears more smooth and less "blocky"
if i < peak {
// Adjust downward
adjust = (i - peak) * intSharpness
} else if i == peak {
// No adjustment at peak
adjust = 0
} else {
// Adjust downward
adjust = (peak - i) * intSharpness
}
// On top half of the image, invert adjustment to create symmetry between
// top and bottom halves
if y < imgHalfY {
adjust = -1 * adjust
}
// Retrieve and apply color function at specified computed value
// count, and X and Y coordinates.
// The output color is selected using the function, and is applied to
// the resulting image.
img.Set(x+i, y+adjust, w.fgColorFn(n, x+i, y+adjust, maxN, maxX, maxY))
}
}
// Increase X by scaling factor, to continue drawing at next loop
x += intScaleX
}
// Return generated image
return img
} | go | func (w *Waveform) generateImage(computed []float64) image.Image {
// Store integer scale values
intScaleX := int(w.scaleX)
intScaleY := int(w.scaleY)
// Calculate maximum n, x, y, where:
// - n: number of computed values
// - x: number of pixels on X-axis
// - y: number of pixels on Y-axis
maxN := len(computed)
maxX := maxN * intScaleX
maxY := imgYDefault * intScaleY
// Create output, rectangular image
img := image.NewRGBA(image.Rect(0, 0, maxX, maxY))
bounds := img.Bounds()
// Calculate halfway point of Y-axis for image
imgHalfY := bounds.Max.Y / 2
// Calculate a peak value used for smoothing scaled X-axis images
peak := int(math.Ceil(float64(w.scaleX)) / 2)
// Calculate scaling factor, based upon maximum value computed by a SampleReduceFunc.
// If option ScaleClipping is true, when maximum value is above certain thresholds
// the scaling factor is reduced to show an accurate waveform with less clipping.
imgScale := scaleDefault
if w.scaleClipping {
// Find maximum value from input slice
var maxValue float64
for _, c := range computed {
if c > maxValue {
maxValue = c
}
}
// For each 0.05 maximum increment at 0.30 and above, reduce the scaling
// factor by 0.25. This is a rough estimate and may be tweaked in the future.
for i := 0.30; i < maxValue; i += 0.05 {
imgScale -= 0.25
}
}
// Values to be used for repeated computations
var scaleComputed, halfScaleComputed, adjust int
intBoundY := int(bounds.Max.Y)
f64BoundY := float64(bounds.Max.Y)
intSharpness := int(w.sharpness)
// Begin iterating all computed values
x := 0
for n := range computed {
// Scale computed value to an integer, using the height of the image and a constant
// scaling factor
scaleComputed = int(math.Floor(computed[n] * f64BoundY * imgScale))
// Calculate the halfway point for the scaled computed value
halfScaleComputed = scaleComputed / 2
// Draw background color down the entire Y-axis
for y := 0; y < intBoundY; y++ {
// If X-axis is being scaled, draw background over several X coordinates
for i := 0; i < intScaleX; i++ {
img.Set(x+i, y, w.bgColorFn(n, x+i, y, maxN, maxX, maxY))
}
}
// Iterate image coordinates on the Y-axis, generating a symmetrical waveform
// image above and below the center of the image
for y := imgHalfY - halfScaleComputed; y < scaleComputed+(imgHalfY-halfScaleComputed); y++ {
// If X-axis is being scaled, draw computed value over several X coordinates
for i := 0; i < intScaleX; i++ {
// When scaled, adjust computed value to be lower on either side of the peak,
// so that the image appears more smooth and less "blocky"
if i < peak {
// Adjust downward
adjust = (i - peak) * intSharpness
} else if i == peak {
// No adjustment at peak
adjust = 0
} else {
// Adjust downward
adjust = (peak - i) * intSharpness
}
// On top half of the image, invert adjustment to create symmetry between
// top and bottom halves
if y < imgHalfY {
adjust = -1 * adjust
}
// Retrieve and apply color function at specified computed value
// count, and X and Y coordinates.
// The output color is selected using the function, and is applied to
// the resulting image.
img.Set(x+i, y+adjust, w.fgColorFn(n, x+i, y+adjust, maxN, maxX, maxY))
}
}
// Increase X by scaling factor, to continue drawing at next loop
x += intScaleX
}
// Return generated image
return img
} | [
"func",
"(",
"w",
"*",
"Waveform",
")",
"generateImage",
"(",
"computed",
"[",
"]",
"float64",
")",
"image",
".",
"Image",
"{",
"// Store integer scale values",
"intScaleX",
":=",
"int",
"(",
"w",
".",
"scaleX",
")",
"\n",
"intScaleY",
":=",
"int",
"(",
... | // generateImage takes a slice of computed values and generates
// a waveform image from the input. | [
"generateImage",
"takes",
"a",
"slice",
"of",
"computed",
"values",
"and",
"generates",
"a",
"waveform",
"image",
"from",
"the",
"input",
"."
] | 6b28917edfbacd50bff4d58f951cf80499c952c4 | https://github.com/mdlayher/waveform/blob/6b28917edfbacd50bff4d58f951cf80499c952c4/waveform.go#L202-L307 |
17,318 | neelance/parallel | parallel.go | Error | func (r *Run) Error(err error) {
r.errsMutex.Lock()
r.errs = append(r.errs, err)
r.errsMutex.Unlock()
} | go | func (r *Run) Error(err error) {
r.errsMutex.Lock()
r.errs = append(r.errs, err)
r.errsMutex.Unlock()
} | [
"func",
"(",
"r",
"*",
"Run",
")",
"Error",
"(",
"err",
"error",
")",
"{",
"r",
".",
"errsMutex",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"errs",
"=",
"append",
"(",
"r",
".",
"errs",
",",
"err",
")",
"\n",
"r",
".",
"errsMutex",
".",
"Unlock"... | // Error stores an error to be returned by Wait. | [
"Error",
"stores",
"an",
"error",
"to",
"be",
"returned",
"by",
"Wait",
"."
] | 4de9ce63d14c18517a79efe69e10e99d32c850c3 | https://github.com/neelance/parallel/blob/4de9ce63d14c18517a79efe69e10e99d32c850c3/parallel.go#L45-L49 |
17,319 | neelance/parallel | parallel.go | Wait | func (r *Run) Wait() error {
r.wg.Wait()
if len(r.errs) != 0 {
return Errors(r.errs)
}
return nil
} | go | func (r *Run) Wait() error {
r.wg.Wait()
if len(r.errs) != 0 {
return Errors(r.errs)
}
return nil
} | [
"func",
"(",
"r",
"*",
"Run",
")",
"Wait",
"(",
")",
"error",
"{",
"r",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"if",
"len",
"(",
"r",
".",
"errs",
")",
"!=",
"0",
"{",
"return",
"Errors",
"(",
"r",
".",
"errs",
")",
"\n",
"}",
"\n",
"ret... | // Wait waits for all locks to be released. If any errors were encountered, it returns an
// Errors value describing all the errors in arbitrary order. | [
"Wait",
"waits",
"for",
"all",
"locks",
"to",
"be",
"released",
".",
"If",
"any",
"errors",
"were",
"encountered",
"it",
"returns",
"an",
"Errors",
"value",
"describing",
"all",
"the",
"errors",
"in",
"arbitrary",
"order",
"."
] | 4de9ce63d14c18517a79efe69e10e99d32c850c3 | https://github.com/neelance/parallel/blob/4de9ce63d14c18517a79efe69e10e99d32c850c3/parallel.go#L53-L59 |
17,320 | muesli/regommend | regommendtable.go | Count | func (table *RegommendTable) Count() int {
table.RLock()
defer table.RUnlock()
return len(table.items)
} | go | func (table *RegommendTable) Count() int {
table.RLock()
defer table.RUnlock()
return len(table.items)
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"Count",
"(",
")",
"int",
"{",
"table",
".",
"RLock",
"(",
")",
"\n",
"defer",
"table",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"table",
".",
"items",
")",
"\n",
"}"
] | // Count returns how many items are currently stored in the engine. | [
"Count",
"returns",
"how",
"many",
"items",
"are",
"currently",
"stored",
"in",
"the",
"engine",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L40-L44 |
17,321 | muesli/regommend | regommendtable.go | SetDataLoader | func (table *RegommendTable) SetDataLoader(f func(interface{}) *RegommendItem) {
table.Lock()
defer table.Unlock()
table.loadData = f
} | go | func (table *RegommendTable) SetDataLoader(f func(interface{}) *RegommendItem) {
table.Lock()
defer table.Unlock()
table.loadData = f
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"SetDataLoader",
"(",
"f",
"func",
"(",
"interface",
"{",
"}",
")",
"*",
"RegommendItem",
")",
"{",
"table",
".",
"Lock",
"(",
")",
"\n",
"defer",
"table",
".",
"Unlock",
"(",
")",
"\n",
"table",
".",... | // Configures a data-loader callback, which will be called when trying
// to use access a non-existing key. | [
"Configures",
"a",
"data",
"-",
"loader",
"callback",
"which",
"will",
"be",
"called",
"when",
"trying",
"to",
"use",
"access",
"a",
"non",
"-",
"existing",
"key",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L48-L52 |
17,322 | muesli/regommend | regommendtable.go | SetAddedItemCallback | func (table *RegommendTable) SetAddedItemCallback(f func(*RegommendItem)) {
table.Lock()
defer table.Unlock()
table.addedItem = f
} | go | func (table *RegommendTable) SetAddedItemCallback(f func(*RegommendItem)) {
table.Lock()
defer table.Unlock()
table.addedItem = f
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"SetAddedItemCallback",
"(",
"f",
"func",
"(",
"*",
"RegommendItem",
")",
")",
"{",
"table",
".",
"Lock",
"(",
")",
"\n",
"defer",
"table",
".",
"Unlock",
"(",
")",
"\n",
"table",
".",
"addedItem",
"=",... | // Configures a callback, which will be called every time a new item
// is added to the engine. | [
"Configures",
"a",
"callback",
"which",
"will",
"be",
"called",
"every",
"time",
"a",
"new",
"item",
"is",
"added",
"to",
"the",
"engine",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L56-L60 |
17,323 | muesli/regommend | regommendtable.go | SetAboutToDeleteItemCallback | func (table *RegommendTable) SetAboutToDeleteItemCallback(f func(*RegommendItem)) {
table.Lock()
defer table.Unlock()
table.aboutToDeleteItem = f
} | go | func (table *RegommendTable) SetAboutToDeleteItemCallback(f func(*RegommendItem)) {
table.Lock()
defer table.Unlock()
table.aboutToDeleteItem = f
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"SetAboutToDeleteItemCallback",
"(",
"f",
"func",
"(",
"*",
"RegommendItem",
")",
")",
"{",
"table",
".",
"Lock",
"(",
")",
"\n",
"defer",
"table",
".",
"Unlock",
"(",
")",
"\n",
"table",
".",
"aboutToDel... | // Configures a callback, which will be called every time an item
// is about to be removed from the engine. | [
"Configures",
"a",
"callback",
"which",
"will",
"be",
"called",
"every",
"time",
"an",
"item",
"is",
"about",
"to",
"be",
"removed",
"from",
"the",
"engine",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L64-L68 |
17,324 | muesli/regommend | regommendtable.go | SetLogger | func (table *RegommendTable) SetLogger(logger *log.Logger) {
table.Lock()
defer table.Unlock()
table.logger = logger
} | go | func (table *RegommendTable) SetLogger(logger *log.Logger) {
table.Lock()
defer table.Unlock()
table.logger = logger
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"SetLogger",
"(",
"logger",
"*",
"log",
".",
"Logger",
")",
"{",
"table",
".",
"Lock",
"(",
")",
"\n",
"defer",
"table",
".",
"Unlock",
"(",
")",
"\n",
"table",
".",
"logger",
"=",
"logger",
"\n",
"... | // Sets the logger to be used by this engine table. | [
"Sets",
"the",
"logger",
"to",
"be",
"used",
"by",
"this",
"engine",
"table",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L71-L75 |
17,325 | muesli/regommend | regommendtable.go | Delete | func (table *RegommendTable) Delete(key interface{}) (*RegommendItem, error) {
table.RLock()
r, ok := table.items[key]
if !ok {
table.RUnlock()
return nil, errors.New("Key not found in engine")
}
// engine value so we don't keep blocking the mutex.
aboutToDeleteItem := table.aboutToDeleteItem
table.RUnlock()
// Trigger callbacks before deleting an item from engine.
if aboutToDeleteItem != nil {
aboutToDeleteItem(r)
}
r.RLock()
defer r.RUnlock()
table.Lock()
defer table.Unlock()
delete(table.items, key)
return r, nil
} | go | func (table *RegommendTable) Delete(key interface{}) (*RegommendItem, error) {
table.RLock()
r, ok := table.items[key]
if !ok {
table.RUnlock()
return nil, errors.New("Key not found in engine")
}
// engine value so we don't keep blocking the mutex.
aboutToDeleteItem := table.aboutToDeleteItem
table.RUnlock()
// Trigger callbacks before deleting an item from engine.
if aboutToDeleteItem != nil {
aboutToDeleteItem(r)
}
r.RLock()
defer r.RUnlock()
table.Lock()
defer table.Unlock()
delete(table.items, key)
return r, nil
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"Delete",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"*",
"RegommendItem",
",",
"error",
")",
"{",
"table",
".",
"RLock",
"(",
")",
"\n",
"r",
",",
"ok",
":=",
"table",
".",
"items",
"[",
"key",
... | // Delete an item from the engine. | [
"Delete",
"an",
"item",
"from",
"the",
"engine",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L100-L125 |
17,326 | muesli/regommend | regommendtable.go | Exists | func (table *RegommendTable) Exists(key interface{}) bool {
table.RLock()
defer table.RUnlock()
_, ok := table.items[key]
return ok
} | go | func (table *RegommendTable) Exists(key interface{}) bool {
table.RLock()
defer table.RUnlock()
_, ok := table.items[key]
return ok
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"Exists",
"(",
"key",
"interface",
"{",
"}",
")",
"bool",
"{",
"table",
".",
"RLock",
"(",
")",
"\n",
"defer",
"table",
".",
"RUnlock",
"(",
")",
"\n",
"_",
",",
"ok",
":=",
"table",
".",
"items",
... | // Test whether an item exists in the engine. Unlike the Value method
// Exists neither tries to fetch data via the loadData callback nor
// does it keep the item alive in the engine. | [
"Test",
"whether",
"an",
"item",
"exists",
"in",
"the",
"engine",
".",
"Unlike",
"the",
"Value",
"method",
"Exists",
"neither",
"tries",
"to",
"fetch",
"data",
"via",
"the",
"loadData",
"callback",
"nor",
"does",
"it",
"keep",
"the",
"item",
"alive",
"in",... | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L130-L136 |
17,327 | muesli/regommend | regommendtable.go | Value | func (table *RegommendTable) Value(key interface{}) (*RegommendItem, error) {
table.RLock()
r, ok := table.items[key]
loadData := table.loadData
table.RUnlock()
if ok {
return r, nil
}
// Item doesn't exist in engine. Try and fetch it with a data-loader.
if loadData != nil {
item := loadData(key)
if item != nil {
table.Add(key, item.data)
return item, nil
}
return nil, errors.New("Key not found and could not be loaded into engine")
}
return nil, errors.New("Key not found in engine")
} | go | func (table *RegommendTable) Value(key interface{}) (*RegommendItem, error) {
table.RLock()
r, ok := table.items[key]
loadData := table.loadData
table.RUnlock()
if ok {
return r, nil
}
// Item doesn't exist in engine. Try and fetch it with a data-loader.
if loadData != nil {
item := loadData(key)
if item != nil {
table.Add(key, item.data)
return item, nil
}
return nil, errors.New("Key not found and could not be loaded into engine")
}
return nil, errors.New("Key not found in engine")
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"Value",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"*",
"RegommendItem",
",",
"error",
")",
"{",
"table",
".",
"RLock",
"(",
")",
"\n",
"r",
",",
"ok",
":=",
"table",
".",
"items",
"[",
"key",
... | // Value gets an item from the engine and mark it to be kept alive. | [
"Value",
"gets",
"an",
"item",
"from",
"the",
"engine",
"and",
"mark",
"it",
"to",
"be",
"kept",
"alive",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L139-L161 |
17,328 | muesli/regommend | regommendtable.go | Flush | func (table *RegommendTable) Flush() {
table.Lock()
defer table.Unlock()
table.log("Flushing table", table.name)
table.items = make(map[interface{}]*RegommendItem)
} | go | func (table *RegommendTable) Flush() {
table.Lock()
defer table.Unlock()
table.log("Flushing table", table.name)
table.items = make(map[interface{}]*RegommendItem)
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"Flush",
"(",
")",
"{",
"table",
".",
"Lock",
"(",
")",
"\n",
"defer",
"table",
".",
"Unlock",
"(",
")",
"\n\n",
"table",
".",
"log",
"(",
"\"",
"\"",
",",
"table",
".",
"name",
")",
"\n\n",
"tabl... | // Delete all items from engine. | [
"Delete",
"all",
"items",
"from",
"engine",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L164-L171 |
17,329 | muesli/regommend | regommendtable.go | log | func (table *RegommendTable) log(v ...interface{}) {
if table.logger == nil {
return
}
table.logger.Println(v...)
} | go | func (table *RegommendTable) log(v ...interface{}) {
if table.logger == nil {
return
}
table.logger.Println(v...)
} | [
"func",
"(",
"table",
"*",
"RegommendTable",
")",
"log",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"table",
".",
"logger",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"table",
".",
"logger",
".",
"Println",
"(",
"v",
"...",
")",
... | // Internal logging method for convenience. | [
"Internal",
"logging",
"method",
"for",
"convenience",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommendtable.go#L276-L282 |
17,330 | muesli/regommend | regommend.go | Table | func Table(table string) *RegommendTable {
mutex.RLock()
t, ok := tables[table]
mutex.RUnlock()
if !ok {
t = &RegommendTable{
name: table,
items: make(map[interface{}]*RegommendItem),
}
mutex.Lock()
tables[table] = t
mutex.Unlock()
}
return t
} | go | func Table(table string) *RegommendTable {
mutex.RLock()
t, ok := tables[table]
mutex.RUnlock()
if !ok {
t = &RegommendTable{
name: table,
items: make(map[interface{}]*RegommendItem),
}
mutex.Lock()
tables[table] = t
mutex.Unlock()
}
return t
} | [
"func",
"Table",
"(",
"table",
"string",
")",
"*",
"RegommendTable",
"{",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"t",
",",
"ok",
":=",
"tables",
"[",
"table",
"]",
"\n",
"mutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"!",
"ok",
"{",
"t",
"=",
... | // Table returns the existing engine table with given name or creates a new one
// if the table does not exist yet. | [
"Table",
"returns",
"the",
"existing",
"engine",
"table",
"with",
"given",
"name",
"or",
"creates",
"a",
"new",
"one",
"if",
"the",
"table",
"does",
"not",
"exist",
"yet",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommend.go#L21-L38 |
17,331 | muesli/regommend | regommenditem.go | CreateRegommendItem | func CreateRegommendItem(key interface{}, data map[interface{}]float64) RegommendItem {
return RegommendItem{
key: key,
data: data,
}
} | go | func CreateRegommendItem(key interface{}, data map[interface{}]float64) RegommendItem {
return RegommendItem{
key: key,
data: data,
}
} | [
"func",
"CreateRegommendItem",
"(",
"key",
"interface",
"{",
"}",
",",
"data",
"map",
"[",
"interface",
"{",
"}",
"]",
"float64",
")",
"RegommendItem",
"{",
"return",
"RegommendItem",
"{",
"key",
":",
"key",
",",
"data",
":",
"data",
",",
"}",
"\n",
"}... | // CreateRegommendItem returns a newly created RegommendItem.
// Parameter key is the item's key.
// Parameter data is the item's value. | [
"CreateRegommendItem",
"returns",
"a",
"newly",
"created",
"RegommendItem",
".",
"Parameter",
"key",
"is",
"the",
"item",
"s",
"key",
".",
"Parameter",
"data",
"is",
"the",
"item",
"s",
"value",
"."
] | e879bb52e08f394cfebb9a0d91036cfb7cd8322b | https://github.com/muesli/regommend/blob/e879bb52e08f394cfebb9a0d91036cfb7cd8322b/regommenditem.go#L29-L34 |
17,332 | openshift/openshift-sdn | plugins/osdn/registry.go | RunEventQueue | func (registry *Registry) RunEventQueue(resourceName ResourceName) *oscache.EventQueue {
var client cache.Getter
var expectedType interface{}
switch resourceName {
case HostSubnets:
expectedType = &osapi.HostSubnet{}
client = registry.oClient
case NetNamespaces:
expectedType = &osapi.NetNamespace{}
client = registry.oClient
case Nodes:
expectedType = &kapi.Node{}
client = registry.kClient
case Namespaces:
expectedType = &kapi.Namespace{}
client = registry.kClient
case Services:
expectedType = &kapi.Service{}
client = registry.kClient
case Pods:
expectedType = &kapi.Pod{}
client = registry.kClient
default:
log.Fatalf("Unknown resource %s during initialization of event queue", resourceName)
}
lw := cache.NewListWatchFromClient(client, strings.ToLower(string(resourceName)), kapi.NamespaceAll, fields.Everything())
eventQueue := oscache.NewEventQueue(cache.MetaNamespaceKeyFunc)
// Repopulate event queue every 30 mins
// Existing items in the event queue will have watch.Modified event type
cache.NewReflector(lw, expectedType, eventQueue, 30*time.Minute).Run()
return eventQueue
} | go | func (registry *Registry) RunEventQueue(resourceName ResourceName) *oscache.EventQueue {
var client cache.Getter
var expectedType interface{}
switch resourceName {
case HostSubnets:
expectedType = &osapi.HostSubnet{}
client = registry.oClient
case NetNamespaces:
expectedType = &osapi.NetNamespace{}
client = registry.oClient
case Nodes:
expectedType = &kapi.Node{}
client = registry.kClient
case Namespaces:
expectedType = &kapi.Namespace{}
client = registry.kClient
case Services:
expectedType = &kapi.Service{}
client = registry.kClient
case Pods:
expectedType = &kapi.Pod{}
client = registry.kClient
default:
log.Fatalf("Unknown resource %s during initialization of event queue", resourceName)
}
lw := cache.NewListWatchFromClient(client, strings.ToLower(string(resourceName)), kapi.NamespaceAll, fields.Everything())
eventQueue := oscache.NewEventQueue(cache.MetaNamespaceKeyFunc)
// Repopulate event queue every 30 mins
// Existing items in the event queue will have watch.Modified event type
cache.NewReflector(lw, expectedType, eventQueue, 30*time.Minute).Run()
return eventQueue
} | [
"func",
"(",
"registry",
"*",
"Registry",
")",
"RunEventQueue",
"(",
"resourceName",
"ResourceName",
")",
"*",
"oscache",
".",
"EventQueue",
"{",
"var",
"client",
"cache",
".",
"Getter",
"\n",
"var",
"expectedType",
"interface",
"{",
"}",
"\n\n",
"switch",
"... | // Run event queue for the given resource | [
"Run",
"event",
"queue",
"for",
"the",
"given",
"resource"
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/plugins/osdn/registry.go#L263-L296 |
17,333 | openshift/openshift-sdn | plugins/osdn/subnets.go | watchSubnets | func (node *OsdnNode) watchSubnets() {
subnets := make(map[string]*osapi.HostSubnet)
eventQueue := node.registry.RunEventQueue(HostSubnets)
for {
eventType, obj, err := eventQueue.Pop()
if err != nil {
utilruntime.HandleError(fmt.Errorf("EventQueue failed for subnets: %v", err))
return
}
hs := obj.(*osapi.HostSubnet)
if hs.HostIP == node.localIP {
continue
}
log.V(5).Infof("Watch %s event for HostSubnet %q", strings.Title(string(eventType)), hs.ObjectMeta.Name)
switch eventType {
case watch.Added, watch.Modified:
oldSubnet, exists := subnets[string(hs.UID)]
if exists {
if oldSubnet.HostIP == hs.HostIP {
continue
} else {
// Delete old subnet rules
if err := node.DeleteHostSubnetRules(oldSubnet); err != nil {
log.Error(err)
}
}
}
if err := node.registry.ValidateNodeIP(hs.HostIP); err != nil {
log.Errorf("Ignoring invalid subnet for node %s: %v", hs.HostIP, err)
continue
}
if err := node.AddHostSubnetRules(hs); err != nil {
log.Error(err)
continue
}
subnets[string(hs.UID)] = hs
case watch.Deleted:
delete(subnets, string(hs.UID))
if err := node.DeleteHostSubnetRules(hs); err != nil {
log.Error(err)
}
}
}
} | go | func (node *OsdnNode) watchSubnets() {
subnets := make(map[string]*osapi.HostSubnet)
eventQueue := node.registry.RunEventQueue(HostSubnets)
for {
eventType, obj, err := eventQueue.Pop()
if err != nil {
utilruntime.HandleError(fmt.Errorf("EventQueue failed for subnets: %v", err))
return
}
hs := obj.(*osapi.HostSubnet)
if hs.HostIP == node.localIP {
continue
}
log.V(5).Infof("Watch %s event for HostSubnet %q", strings.Title(string(eventType)), hs.ObjectMeta.Name)
switch eventType {
case watch.Added, watch.Modified:
oldSubnet, exists := subnets[string(hs.UID)]
if exists {
if oldSubnet.HostIP == hs.HostIP {
continue
} else {
// Delete old subnet rules
if err := node.DeleteHostSubnetRules(oldSubnet); err != nil {
log.Error(err)
}
}
}
if err := node.registry.ValidateNodeIP(hs.HostIP); err != nil {
log.Errorf("Ignoring invalid subnet for node %s: %v", hs.HostIP, err)
continue
}
if err := node.AddHostSubnetRules(hs); err != nil {
log.Error(err)
continue
}
subnets[string(hs.UID)] = hs
case watch.Deleted:
delete(subnets, string(hs.UID))
if err := node.DeleteHostSubnetRules(hs); err != nil {
log.Error(err)
}
}
}
} | [
"func",
"(",
"node",
"*",
"OsdnNode",
")",
"watchSubnets",
"(",
")",
"{",
"subnets",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"osapi",
".",
"HostSubnet",
")",
"\n",
"eventQueue",
":=",
"node",
".",
"registry",
".",
"RunEventQueue",
"(",
"Host... | // Only run on the nodes | [
"Only",
"run",
"on",
"the",
"nodes"
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/plugins/osdn/subnets.go#L209-L257 |
17,334 | openshift/openshift-sdn | pkg/exec/exec.go | Exec | func Exec(cmd string, args ...string) (string, error) {
if testMode {
return testModeExec(cmd, args...)
}
glog.V(5).Infof("[cmd] %s %s", cmd, strings.Join(args, " "))
out, err := osexec.Command(cmd, args...).CombinedOutput()
if err != nil {
err = fmt.Errorf("%s failed: '%s %s': %v", cmd, cmd, strings.Join(args, " "), err)
} else if glog.V(5) {
lines := strings.Split(string(out), "\n")
for i, line := range lines {
if i < len(lines)-1 || len(line) > 0 {
glog.V(5).Infof("[cmd] => %s", line)
}
}
}
return string(out), err
} | go | func Exec(cmd string, args ...string) (string, error) {
if testMode {
return testModeExec(cmd, args...)
}
glog.V(5).Infof("[cmd] %s %s", cmd, strings.Join(args, " "))
out, err := osexec.Command(cmd, args...).CombinedOutput()
if err != nil {
err = fmt.Errorf("%s failed: '%s %s': %v", cmd, cmd, strings.Join(args, " "), err)
} else if glog.V(5) {
lines := strings.Split(string(out), "\n")
for i, line := range lines {
if i < len(lines)-1 || len(line) > 0 {
glog.V(5).Infof("[cmd] => %s", line)
}
}
}
return string(out), err
} | [
"func",
"Exec",
"(",
"cmd",
"string",
",",
"args",
"...",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"testMode",
"{",
"return",
"testModeExec",
"(",
"cmd",
",",
"args",
"...",
")",
"\n",
"}",
"\n\n",
"glog",
".",
"V",
"(",
"5",
"... | // Exec executes a command with the given arguments and returns either the
// combined stdout+stdin, or an error. | [
"Exec",
"executes",
"a",
"command",
"with",
"the",
"given",
"arguments",
"and",
"returns",
"either",
"the",
"combined",
"stdout",
"+",
"stdin",
"or",
"an",
"error",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/exec/exec.go#L26-L44 |
17,335 | openshift/openshift-sdn | pkg/ipcmd/ipcmd.go | AddLink | func (tx *Transaction) AddLink(args ...string) {
tx.exec(append([]string{"link", "add", tx.link}, args...))
} | go | func (tx *Transaction) AddLink(args ...string) {
tx.exec(append([]string{"link", "add", tx.link}, args...))
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"AddLink",
"(",
"args",
"...",
"string",
")",
"{",
"tx",
".",
"exec",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"tx",
".",
"link",
"}",
",",
"args",
"...",
")",
... | // AddLink creates the interface associated with the transaction, optionally
// with additional properties. | [
"AddLink",
"creates",
"the",
"interface",
"associated",
"with",
"the",
"transaction",
"optionally",
"with",
"additional",
"properties",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ipcmd/ipcmd.go#L48-L50 |
17,336 | openshift/openshift-sdn | pkg/ipcmd/ipcmd.go | SetLink | func (tx *Transaction) SetLink(args ...string) {
tx.exec(append([]string{"link", "set", tx.link}, args...))
} | go | func (tx *Transaction) SetLink(args ...string) {
tx.exec(append([]string{"link", "set", tx.link}, args...))
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"SetLink",
"(",
"args",
"...",
"string",
")",
"{",
"tx",
".",
"exec",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"tx",
".",
"link",
"}",
",",
"args",
"...",
")",
... | // SetLink sets the indicated properties on the interface. | [
"SetLink",
"sets",
"the",
"indicated",
"properties",
"on",
"the",
"interface",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ipcmd/ipcmd.go#L59-L61 |
17,337 | openshift/openshift-sdn | pkg/ipcmd/ipcmd.go | AddAddress | func (tx *Transaction) AddAddress(cidr string, args ...string) {
tx.exec(append([]string{"addr", "add", cidr, "dev", tx.link}, args...))
} | go | func (tx *Transaction) AddAddress(cidr string, args ...string) {
tx.exec(append([]string{"addr", "add", cidr, "dev", tx.link}, args...))
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"AddAddress",
"(",
"cidr",
"string",
",",
"args",
"...",
"string",
")",
"{",
"tx",
".",
"exec",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cidr",
",",
"\"",
"\"",
... | // AddAddress adds an address to the interface. | [
"AddAddress",
"adds",
"an",
"address",
"to",
"the",
"interface",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ipcmd/ipcmd.go#L64-L66 |
17,338 | openshift/openshift-sdn | pkg/ipcmd/ipcmd.go | GetAddresses | func (tx *Transaction) GetAddresses() ([]string, error) {
out, err := tx.exec(append([]string{"addr", "show", "dev", tx.link}))
if err != nil {
return nil, err
}
matches := addressRegexp.FindAllStringSubmatch(out, -1)
addrs := make([]string, len(matches))
for i, match := range matches {
addrs[i] = match[1]
}
return addrs, nil
} | go | func (tx *Transaction) GetAddresses() ([]string, error) {
out, err := tx.exec(append([]string{"addr", "show", "dev", tx.link}))
if err != nil {
return nil, err
}
matches := addressRegexp.FindAllStringSubmatch(out, -1)
addrs := make([]string, len(matches))
for i, match := range matches {
addrs[i] = match[1]
}
return addrs, nil
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"GetAddresses",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"tx",
".",
"exec",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
... | // GetAddresses returns the IPv4 addresses associated with the interface. Since
// this function has a return value, it also returns an error immediately if an
// error occurs. | [
"GetAddresses",
"returns",
"the",
"IPv4",
"addresses",
"associated",
"with",
"the",
"interface",
".",
"Since",
"this",
"function",
"has",
"a",
"return",
"value",
"it",
"also",
"returns",
"an",
"error",
"immediately",
"if",
"an",
"error",
"occurs",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ipcmd/ipcmd.go#L77-L89 |
17,339 | openshift/openshift-sdn | pkg/ipcmd/ipcmd.go | AddSlave | func (tx *Transaction) AddSlave(slave string) {
tx.exec([]string{"link", "set", slave, "master", tx.link})
} | go | func (tx *Transaction) AddSlave(slave string) {
tx.exec([]string{"link", "set", slave, "master", tx.link})
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"AddSlave",
"(",
"slave",
"string",
")",
"{",
"tx",
".",
"exec",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"slave",
",",
"\"",
"\"",
",",
"tx",
".",
"link",
"}",
")",
"\n",
"}"... | // AddSlave adds the indicated slave interface to the bridge, bond, or team
// interface associated with the transaction. | [
"AddSlave",
"adds",
"the",
"indicated",
"slave",
"interface",
"to",
"the",
"bridge",
"bond",
"or",
"team",
"interface",
"associated",
"with",
"the",
"transaction",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ipcmd/ipcmd.go#L118-L120 |
17,340 | openshift/openshift-sdn | pkg/ipcmd/ipcmd.go | EndTransaction | func (tx *Transaction) EndTransaction() error {
err := tx.err
tx.err = nil
return err
} | go | func (tx *Transaction) EndTransaction() error {
err := tx.err
tx.err = nil
return err
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"EndTransaction",
"(",
")",
"error",
"{",
"err",
":=",
"tx",
".",
"err",
"\n",
"tx",
".",
"err",
"=",
"nil",
"\n",
"return",
"err",
"\n",
"}"
] | // EndTransaction ends a transaction and returns any error that occurred during
// the transaction. You should not use the transaction again after calling this
// function. | [
"EndTransaction",
"ends",
"a",
"transaction",
"and",
"returns",
"any",
"error",
"that",
"occurred",
"during",
"the",
"transaction",
".",
"You",
"should",
"not",
"use",
"the",
"transaction",
"again",
"after",
"calling",
"this",
"function",
"."
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ipcmd/ipcmd.go#L139-L143 |
17,341 | openshift/openshift-sdn | pkg/ovs/ovs.go | DumpFlows | func (tx *Transaction) DumpFlows() ([]string, error) {
out, err := tx.ofctlExec("dump-flows", tx.bridge)
if err != nil {
return nil, err
}
lines := strings.Split(out, "\n")
flows := make([]string, 0, len(lines))
for _, line := range lines {
if strings.Contains(line, "cookie=") {
flows = append(flows, line)
}
}
return flows, nil
} | go | func (tx *Transaction) DumpFlows() ([]string, error) {
out, err := tx.ofctlExec("dump-flows", tx.bridge)
if err != nil {
return nil, err
}
lines := strings.Split(out, "\n")
flows := make([]string, 0, len(lines))
for _, line := range lines {
if strings.Contains(line, "cookie=") {
flows = append(flows, line)
}
}
return flows, nil
} | [
"func",
"(",
"tx",
"*",
"Transaction",
")",
"DumpFlows",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"tx",
".",
"ofctlExec",
"(",
"\"",
"\"",
",",
"tx",
".",
"bridge",
")",
"\n",
"if",
"err",
"!=",
"nil",... | // DumpFlows dumps the flow table for the bridge and returns it as an array of
// strings, one per flow. Since this function has a return value, it also
// returns an error immediately if an error occurs. | [
"DumpFlows",
"dumps",
"the",
"flow",
"table",
"for",
"the",
"bridge",
"and",
"returns",
"it",
"as",
"an",
"array",
"of",
"strings",
"one",
"per",
"flow",
".",
"Since",
"this",
"function",
"has",
"a",
"return",
"value",
"it",
"also",
"returns",
"an",
"err... | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/pkg/ovs/ovs.go#L103-L117 |
17,342 | openshift/openshift-sdn | plugins/osdn/node_iptables.go | getStaticNodeIPTablesRules | func (n *NodeIPTables) getStaticNodeIPTablesRules() []FirewallRule {
return []FirewallRule{
{"nat", "POSTROUTING", []string{"-s", n.clusterNetworkCIDR, "!", "-d", n.clusterNetworkCIDR, "-j", "MASQUERADE"}},
{"filter", "INPUT", []string{"-p", "udp", "-m", "multiport", "--dports", VXLAN_PORT, "-m", "comment", "--comment", "001 vxlan incoming", "-j", "ACCEPT"}},
{"filter", "INPUT", []string{"-i", TUN, "-m", "comment", "--comment", "traffic from docker for internet", "-j", "ACCEPT"}},
{"filter", "FORWARD", []string{"-d", n.clusterNetworkCIDR, "-j", "ACCEPT"}},
{"filter", "FORWARD", []string{"-s", n.clusterNetworkCIDR, "-j", "ACCEPT"}},
}
} | go | func (n *NodeIPTables) getStaticNodeIPTablesRules() []FirewallRule {
return []FirewallRule{
{"nat", "POSTROUTING", []string{"-s", n.clusterNetworkCIDR, "!", "-d", n.clusterNetworkCIDR, "-j", "MASQUERADE"}},
{"filter", "INPUT", []string{"-p", "udp", "-m", "multiport", "--dports", VXLAN_PORT, "-m", "comment", "--comment", "001 vxlan incoming", "-j", "ACCEPT"}},
{"filter", "INPUT", []string{"-i", TUN, "-m", "comment", "--comment", "traffic from docker for internet", "-j", "ACCEPT"}},
{"filter", "FORWARD", []string{"-d", n.clusterNetworkCIDR, "-j", "ACCEPT"}},
{"filter", "FORWARD", []string{"-s", n.clusterNetworkCIDR, "-j", "ACCEPT"}},
}
} | [
"func",
"(",
"n",
"*",
"NodeIPTables",
")",
"getStaticNodeIPTablesRules",
"(",
")",
"[",
"]",
"FirewallRule",
"{",
"return",
"[",
"]",
"FirewallRule",
"{",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"n",
".",
"... | // Get openshift iptables rules | [
"Get",
"openshift",
"iptables",
"rules"
] | 5ca93d25828cb135e3d9c8d1917a8807b37abd1e | https://github.com/openshift/openshift-sdn/blob/5ca93d25828cb135e3d9c8d1917a8807b37abd1e/plugins/osdn/node_iptables.go#L94-L102 |
17,343 | akrennmair/gopcap | io.go | Time | func (p *PacketTime) Time() time.Time {
return time.Unix(int64(p.Sec), int64(p.Usec)*1000)
} | go | func (p *PacketTime) Time() time.Time {
return time.Unix(int64(p.Sec), int64(p.Usec)*1000)
} | [
"func",
"(",
"p",
"*",
"PacketTime",
")",
"Time",
"(",
")",
"time",
".",
"Time",
"{",
"return",
"time",
".",
"Unix",
"(",
"int64",
"(",
"p",
".",
"Sec",
")",
",",
"int64",
"(",
"p",
".",
"Usec",
")",
"*",
"1000",
")",
"\n",
"}"
] | // Convert the PacketTime to a go Time struct. | [
"Convert",
"the",
"PacketTime",
"to",
"a",
"go",
"Time",
"struct",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/io.go#L28-L30 |
17,344 | akrennmair/gopcap | io.go | NewReader | func NewReader(reader io.Reader) (*Reader, error) {
r := &Reader{
buf: reader,
fourBytes: make([]byte, 4),
twoBytes: make([]byte, 2),
sixteenBytes: make([]byte, 16),
}
switch magic := r.readUint32(); magic {
case 0xa1b2c3d4:
r.flip = false
case 0xd4c3b2a1:
r.flip = true
default:
return nil, fmt.Errorf("pcap: bad magic number: %0x", magic)
}
r.Header = FileHeader{
MagicNumber: 0xa1b2c3d4,
VersionMajor: r.readUint16(),
VersionMinor: r.readUint16(),
TimeZone: r.readInt32(),
SigFigs: r.readUint32(),
SnapLen: r.readUint32(),
Network: r.readUint32(),
}
return r, nil
} | go | func NewReader(reader io.Reader) (*Reader, error) {
r := &Reader{
buf: reader,
fourBytes: make([]byte, 4),
twoBytes: make([]byte, 2),
sixteenBytes: make([]byte, 16),
}
switch magic := r.readUint32(); magic {
case 0xa1b2c3d4:
r.flip = false
case 0xd4c3b2a1:
r.flip = true
default:
return nil, fmt.Errorf("pcap: bad magic number: %0x", magic)
}
r.Header = FileHeader{
MagicNumber: 0xa1b2c3d4,
VersionMajor: r.readUint16(),
VersionMinor: r.readUint16(),
TimeZone: r.readInt32(),
SigFigs: r.readUint32(),
SnapLen: r.readUint32(),
Network: r.readUint32(),
}
return r, nil
} | [
"func",
"NewReader",
"(",
"reader",
"io",
".",
"Reader",
")",
"(",
"*",
"Reader",
",",
"error",
")",
"{",
"r",
":=",
"&",
"Reader",
"{",
"buf",
":",
"reader",
",",
"fourBytes",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
",",
"twoBytes",
... | // NewReader reads pcap data from an io.Reader. | [
"NewReader",
"reads",
"pcap",
"data",
"from",
"an",
"io",
".",
"Reader",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/io.go#L66-L91 |
17,345 | akrennmair/gopcap | io.go | Next | func (r *Reader) Next() *Packet {
d := r.sixteenBytes
r.err = r.read(d)
if r.err != nil {
return nil
}
timeSec := asUint32(d[0:4], r.flip)
timeUsec := asUint32(d[4:8], r.flip)
capLen := asUint32(d[8:12], r.flip)
origLen := asUint32(d[12:16], r.flip)
data := make([]byte, capLen)
if r.err = r.read(data); r.err != nil {
return nil
}
return &Packet{
Time: time.Unix(int64(timeSec), int64(timeUsec)),
Caplen: capLen,
Len: origLen,
Data: data,
}
} | go | func (r *Reader) Next() *Packet {
d := r.sixteenBytes
r.err = r.read(d)
if r.err != nil {
return nil
}
timeSec := asUint32(d[0:4], r.flip)
timeUsec := asUint32(d[4:8], r.flip)
capLen := asUint32(d[8:12], r.flip)
origLen := asUint32(d[12:16], r.flip)
data := make([]byte, capLen)
if r.err = r.read(data); r.err != nil {
return nil
}
return &Packet{
Time: time.Unix(int64(timeSec), int64(timeUsec)),
Caplen: capLen,
Len: origLen,
Data: data,
}
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Next",
"(",
")",
"*",
"Packet",
"{",
"d",
":=",
"r",
".",
"sixteenBytes",
"\n",
"r",
".",
"err",
"=",
"r",
".",
"read",
"(",
"d",
")",
"\n",
"if",
"r",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\... | // Next returns the next packet or nil if no more packets can be read. | [
"Next",
"returns",
"the",
"next",
"packet",
"or",
"nil",
"if",
"no",
"more",
"packets",
"can",
"be",
"read",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/io.go#L94-L115 |
17,346 | akrennmair/gopcap | io.go | NewWriter | func NewWriter(writer io.Writer, header *FileHeader) (*Writer, error) {
w := &Writer{
writer: writer,
buf: make([]byte, 24),
}
binary.LittleEndian.PutUint32(w.buf, header.MagicNumber)
binary.LittleEndian.PutUint16(w.buf[4:], header.VersionMajor)
binary.LittleEndian.PutUint16(w.buf[6:], header.VersionMinor)
binary.LittleEndian.PutUint32(w.buf[8:], uint32(header.TimeZone))
binary.LittleEndian.PutUint32(w.buf[12:], header.SigFigs)
binary.LittleEndian.PutUint32(w.buf[16:], header.SnapLen)
binary.LittleEndian.PutUint32(w.buf[20:], header.Network)
if _, err := writer.Write(w.buf); err != nil {
return nil, err
}
return w, nil
} | go | func NewWriter(writer io.Writer, header *FileHeader) (*Writer, error) {
w := &Writer{
writer: writer,
buf: make([]byte, 24),
}
binary.LittleEndian.PutUint32(w.buf, header.MagicNumber)
binary.LittleEndian.PutUint16(w.buf[4:], header.VersionMajor)
binary.LittleEndian.PutUint16(w.buf[6:], header.VersionMinor)
binary.LittleEndian.PutUint32(w.buf[8:], uint32(header.TimeZone))
binary.LittleEndian.PutUint32(w.buf[12:], header.SigFigs)
binary.LittleEndian.PutUint32(w.buf[16:], header.SnapLen)
binary.LittleEndian.PutUint32(w.buf[20:], header.Network)
if _, err := writer.Write(w.buf); err != nil {
return nil, err
}
return w, nil
} | [
"func",
"NewWriter",
"(",
"writer",
"io",
".",
"Writer",
",",
"header",
"*",
"FileHeader",
")",
"(",
"*",
"Writer",
",",
"error",
")",
"{",
"w",
":=",
"&",
"Writer",
"{",
"writer",
":",
"writer",
",",
"buf",
":",
"make",
"(",
"[",
"]",
"byte",
",... | // NewWriter creates a Writer that stores output in an io.Writer.
// The FileHeader is written immediately. | [
"NewWriter",
"creates",
"a",
"Writer",
"that",
"stores",
"output",
"in",
"an",
"io",
".",
"Writer",
".",
"The",
"FileHeader",
"is",
"written",
"immediately",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/io.go#L163-L179 |
17,347 | akrennmair/gopcap | io.go | Write | func (w *Writer) Write(pkt *Packet) error {
binary.LittleEndian.PutUint32(w.buf, uint32(pkt.Time.Unix()))
binary.LittleEndian.PutUint32(w.buf[4:], uint32(pkt.Time.Nanosecond()))
binary.LittleEndian.PutUint32(w.buf[8:], uint32(pkt.Time.Unix()))
binary.LittleEndian.PutUint32(w.buf[12:], pkt.Len)
if _, err := w.writer.Write(w.buf[:16]); err != nil {
return err
}
_, err := w.writer.Write(pkt.Data)
return err
} | go | func (w *Writer) Write(pkt *Packet) error {
binary.LittleEndian.PutUint32(w.buf, uint32(pkt.Time.Unix()))
binary.LittleEndian.PutUint32(w.buf[4:], uint32(pkt.Time.Nanosecond()))
binary.LittleEndian.PutUint32(w.buf[8:], uint32(pkt.Time.Unix()))
binary.LittleEndian.PutUint32(w.buf[12:], pkt.Len)
if _, err := w.writer.Write(w.buf[:16]); err != nil {
return err
}
_, err := w.writer.Write(pkt.Data)
return err
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Write",
"(",
"pkt",
"*",
"Packet",
")",
"error",
"{",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"w",
".",
"buf",
",",
"uint32",
"(",
"pkt",
".",
"Time",
".",
"Unix",
"(",
")",
")",
")",
"\n",
"... | // Writer writes a packet to the underlying writer. | [
"Writer",
"writes",
"a",
"packet",
"to",
"the",
"underlying",
"writer",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/io.go#L182-L192 |
17,348 | akrennmair/gopcap | decode.go | Decode | func (p *Packet) Decode() {
if len(p.Data) <= 14 {
return
}
p.Type = int(binary.BigEndian.Uint16(p.Data[12:14]))
p.DestMac = decodemac(p.Data[0:6])
p.SrcMac = decodemac(p.Data[6:12])
if len(p.Data) >= 15 {
p.Payload = p.Data[14:]
}
switch p.Type {
case TYPE_IP:
p.decodeIp()
case TYPE_IP6:
p.decodeIp6()
case TYPE_ARP:
p.decodeArp()
case TYPE_VLAN:
p.decodeVlan()
}
} | go | func (p *Packet) Decode() {
if len(p.Data) <= 14 {
return
}
p.Type = int(binary.BigEndian.Uint16(p.Data[12:14]))
p.DestMac = decodemac(p.Data[0:6])
p.SrcMac = decodemac(p.Data[6:12])
if len(p.Data) >= 15 {
p.Payload = p.Data[14:]
}
switch p.Type {
case TYPE_IP:
p.decodeIp()
case TYPE_IP6:
p.decodeIp6()
case TYPE_ARP:
p.decodeArp()
case TYPE_VLAN:
p.decodeVlan()
}
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"Decode",
"(",
")",
"{",
"if",
"len",
"(",
"p",
".",
"Data",
")",
"<=",
"14",
"{",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"Type",
"=",
"int",
"(",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"p",
".",... | // Decode decodes the headers of a Packet. | [
"Decode",
"decodes",
"the",
"headers",
"of",
"a",
"Packet",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/decode.go#L73-L96 |
17,349 | akrennmair/gopcap | decode.go | String | func (p *Packet) String() string {
// If there are no headers, print "unsupported protocol".
if len(p.Headers) == 0 {
return fmt.Sprintf("%s unsupported protocol %d", p.Time, int(p.Type))
}
return fmt.Sprintf("%s %s", p.Time, p.headerString(p.Headers))
} | go | func (p *Packet) String() string {
// If there are no headers, print "unsupported protocol".
if len(p.Headers) == 0 {
return fmt.Sprintf("%s unsupported protocol %d", p.Time, int(p.Type))
}
return fmt.Sprintf("%s %s", p.Time, p.headerString(p.Headers))
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"String",
"(",
")",
"string",
"{",
"// If there are no headers, print \"unsupported protocol\".",
"if",
"len",
"(",
"p",
".",
"Headers",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
... | // String prints a one-line representation of the packet header.
// The output is suitable for use in a tcpdump program. | [
"String",
"prints",
"a",
"one",
"-",
"line",
"representation",
"of",
"the",
"packet",
"header",
".",
"The",
"output",
"is",
"suitable",
"for",
"use",
"in",
"a",
"tcpdump",
"program",
"."
] | 00e11033259acb75598ba416495bb708d864a010 | https://github.com/akrennmair/gopcap/blob/00e11033259acb75598ba416495bb708d864a010/decode.go#L134-L140 |
17,350 | zebresel-com/mongodm | query.go | extendQuery | func (self *Query) extendQuery(mgoQuery *mgo.Query) {
if self.selector != nil {
mgoQuery.Select(self.selector)
}
if len(self.sort) > 0 {
mgoQuery.Sort(self.sort...)
}
if self.limit != 0 {
mgoQuery.Limit(self.limit)
}
if self.skip != 0 {
mgoQuery.Skip(self.skip)
}
} | go | func (self *Query) extendQuery(mgoQuery *mgo.Query) {
if self.selector != nil {
mgoQuery.Select(self.selector)
}
if len(self.sort) > 0 {
mgoQuery.Sort(self.sort...)
}
if self.limit != 0 {
mgoQuery.Limit(self.limit)
}
if self.skip != 0 {
mgoQuery.Skip(self.skip)
}
} | [
"func",
"(",
"self",
"*",
"Query",
")",
"extendQuery",
"(",
"mgoQuery",
"*",
"mgo",
".",
"Query",
")",
"{",
"if",
"self",
".",
"selector",
"!=",
"nil",
"{",
"mgoQuery",
".",
"Select",
"(",
"self",
".",
"selector",
")",
"\n",
"}",
"\n\n",
"if",
"len... | //extendQuery sets all native query options if specified | [
"extendQuery",
"sets",
"all",
"native",
"query",
"options",
"if",
"specified"
] | 0f86ddb8074ef02ed5627369f982682db60a98f6 | https://github.com/zebresel-com/mongodm/blob/0f86ddb8074ef02ed5627369f982682db60a98f6/query.go#L211-L228 |
17,351 | chewxy/lingo | dep/dependencyParser.go | New | func New(m *Model) *Parser {
d := &Parser{
Output: make(chan *lingo.Dependency),
Error: make(chan error),
Model: m,
}
return d
} | go | func New(m *Model) *Parser {
d := &Parser{
Output: make(chan *lingo.Dependency),
Error: make(chan error),
Model: m,
}
return d
} | [
"func",
"New",
"(",
"m",
"*",
"Model",
")",
"*",
"Parser",
"{",
"d",
":=",
"&",
"Parser",
"{",
"Output",
":",
"make",
"(",
"chan",
"*",
"lingo",
".",
"Dependency",
")",
",",
"Error",
":",
"make",
"(",
"chan",
"error",
")",
",",
"Model",
":",
"m... | // New creates a new Parser | [
"New",
"creates",
"a",
"new",
"Parser"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/dependencyParser.go#L26-L35 |
17,352 | chewxy/lingo | dep/configuration.go | stackValue | func (c *configuration) stackValue(i int) head {
size := c.stackSize()
if i >= size || i < 0 {
return DOES_NOT_EXIST
}
return c.stack[size-1-i]
} | go | func (c *configuration) stackValue(i int) head {
size := c.stackSize()
if i >= size || i < 0 {
return DOES_NOT_EXIST
}
return c.stack[size-1-i]
} | [
"func",
"(",
"c",
"*",
"configuration",
")",
"stackValue",
"(",
"i",
"int",
")",
"head",
"{",
"size",
":=",
"c",
".",
"stackSize",
"(",
")",
"\n",
"if",
"i",
">=",
"size",
"||",
"i",
"<",
"0",
"{",
"return",
"DOES_NOT_EXIST",
"\n",
"}",
"\n",
"re... | // gets the sentence index of the ith word on the stack. If there isn't anything on the stack, it returns DOES_NOT_EXIST | [
"gets",
"the",
"sentence",
"index",
"of",
"the",
"ith",
"word",
"on",
"the",
"stack",
".",
"If",
"there",
"isn",
"t",
"anything",
"on",
"the",
"stack",
"it",
"returns",
"DOES_NOT_EXIST"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/configuration.go#L72-L78 |
17,353 | chewxy/lingo | dep/configuration.go | removeStack | func (c *configuration) removeStack(i int) {
c.stack = c.stack[:i+copy(c.stack[i:], c.stack[i+1:])]
} | go | func (c *configuration) removeStack(i int) {
c.stack = c.stack[:i+copy(c.stack[i:], c.stack[i+1:])]
} | [
"func",
"(",
"c",
"*",
"configuration",
")",
"removeStack",
"(",
"i",
"int",
")",
"{",
"c",
".",
"stack",
"=",
"c",
".",
"stack",
"[",
":",
"i",
"+",
"copy",
"(",
"c",
".",
"stack",
"[",
"i",
":",
"]",
",",
"c",
".",
"stack",
"[",
"i",
"+",... | // removes a value from the stack. | [
"removes",
"a",
"value",
"from",
"the",
"stack",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/configuration.go#L98-L100 |
17,354 | chewxy/lingo | dep/configuration.go | removeSecondTopStack | func (c *configuration) removeSecondTopStack() bool {
stackSize := c.stackSize()
if stackSize < 2 {
return false
}
i := stackSize - 2
c.removeStack(i)
return true
} | go | func (c *configuration) removeSecondTopStack() bool {
stackSize := c.stackSize()
if stackSize < 2 {
return false
}
i := stackSize - 2
c.removeStack(i)
return true
} | [
"func",
"(",
"c",
"*",
"configuration",
")",
"removeSecondTopStack",
"(",
")",
"bool",
"{",
"stackSize",
":=",
"c",
".",
"stackSize",
"(",
")",
"\n",
"if",
"stackSize",
"<",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"i",
":=",
"stackSize",
"-",
"... | // removeSecondTopStack removes the 2nd-to-last element | [
"removeSecondTopStack",
"removes",
"the",
"2nd",
"-",
"to",
"-",
"last",
"element"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/configuration.go#L103-L111 |
17,355 | chewxy/lingo | dep/configuration.go | lc | func (c *configuration) lc(k, cnt head) head {
if k < 0 || int(k) > c.N() {
return DOES_NOT_EXIST
}
cc := 0
for i := 1; i < int(k); i++ {
if c.Head(i) == int(k) {
cc++
if int(cnt) == cc {
return head(i)
}
}
}
return DOES_NOT_EXIST
} | go | func (c *configuration) lc(k, cnt head) head {
if k < 0 || int(k) > c.N() {
return DOES_NOT_EXIST
}
cc := 0
for i := 1; i < int(k); i++ {
if c.Head(i) == int(k) {
cc++
if int(cnt) == cc {
return head(i)
}
}
}
return DOES_NOT_EXIST
} | [
"func",
"(",
"c",
"*",
"configuration",
")",
"lc",
"(",
"k",
",",
"cnt",
"head",
")",
"head",
"{",
"if",
"k",
"<",
"0",
"||",
"int",
"(",
"k",
")",
">",
"c",
".",
"N",
"(",
")",
"{",
"return",
"DOES_NOT_EXIST",
"\n",
"}",
"\n\n",
"cc",
":=",
... | // gets the jth left child of the ith word of a sentence | [
"gets",
"the",
"jth",
"left",
"child",
"of",
"the",
"ith",
"word",
"of",
"a",
"sentence"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/configuration.go#L157-L172 |
17,356 | chewxy/lingo | dep/configuration.go | shift | func (c *configuration) shift() bool {
i := c.bufferValue(0)
if i == DOES_NOT_EXIST {
return false
}
c.bp++ // move the buffer pointer up
c.stack = append(c.stack, i) // push to it.... gotta work the pop
return true
} | go | func (c *configuration) shift() bool {
i := c.bufferValue(0)
if i == DOES_NOT_EXIST {
return false
}
c.bp++ // move the buffer pointer up
c.stack = append(c.stack, i) // push to it.... gotta work the pop
return true
} | [
"func",
"(",
"c",
"*",
"configuration",
")",
"shift",
"(",
")",
"bool",
"{",
"i",
":=",
"c",
".",
"bufferValue",
"(",
"0",
")",
"\n",
"if",
"i",
"==",
"DOES_NOT_EXIST",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"c",
".",
"bp",
"++",
"// move the b... | // Actual Transitioning stuff | [
"Actual",
"Transitioning",
"stuff"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/configuration.go#L205-L215 |
17,357 | chewxy/lingo | lexer/stateFn.go | lexNumber | func lexNumber(l *Lexer) (fn stateFn) {
l.acceptRunFn(unicode.IsDigit)
next := l.next()
switch next {
case '.':
l.accept() // accept the dot
l.acceptRunFn(unicode.IsDigit)
case '-', '/':
// standardize
l.r = '/'
l.accept()
return lexDate
case ':':
if l.pos-l.start == 3 {
l.accept()
return lexTime
} else {
l.backup()
l.emit(lingo.Number)
return lexPunctuation
}
default:
l.backup()
}
if l.acceptRun("eE") {
// handle negative exponents
if l.peek() == '-' {
l.next()
l.accept()
return lexNumber(l)
}
l.acceptRunFn(unicode.IsDigit)
}
l.backup()
if l.buf.Len() == 1 && l.buf.Bytes()[0] == '-' {
l.emit(lingo.Punctuation) // dash
return lexWhitespace
}
l.emit(lingo.Number)
return lexWhitespace
} | go | func lexNumber(l *Lexer) (fn stateFn) {
l.acceptRunFn(unicode.IsDigit)
next := l.next()
switch next {
case '.':
l.accept() // accept the dot
l.acceptRunFn(unicode.IsDigit)
case '-', '/':
// standardize
l.r = '/'
l.accept()
return lexDate
case ':':
if l.pos-l.start == 3 {
l.accept()
return lexTime
} else {
l.backup()
l.emit(lingo.Number)
return lexPunctuation
}
default:
l.backup()
}
if l.acceptRun("eE") {
// handle negative exponents
if l.peek() == '-' {
l.next()
l.accept()
return lexNumber(l)
}
l.acceptRunFn(unicode.IsDigit)
}
l.backup()
if l.buf.Len() == 1 && l.buf.Bytes()[0] == '-' {
l.emit(lingo.Punctuation) // dash
return lexWhitespace
}
l.emit(lingo.Number)
return lexWhitespace
} | [
"func",
"lexNumber",
"(",
"l",
"*",
"Lexer",
")",
"(",
"fn",
"stateFn",
")",
"{",
"l",
".",
"acceptRunFn",
"(",
"unicode",
".",
"IsDigit",
")",
"\n\n",
"next",
":=",
"l",
".",
"next",
"(",
")",
"\n",
"switch",
"next",
"{",
"case",
"'.'",
":",
"l"... | // lexNumber lexes numbers. It accepts runs of unicode digits.
// Upon stopping, it checks to see if the next value is a '.'. If it is, then it's a decimal value, and continues a run
// Upon stopping a second time, it checks for 'e' or 'E', for exponentiation - 1.2E2 | [
"lexNumber",
"lexes",
"numbers",
".",
"It",
"accepts",
"runs",
"of",
"unicode",
"digits",
".",
"Upon",
"stopping",
"it",
"checks",
"to",
"see",
"if",
"the",
"next",
"value",
"is",
"a",
".",
".",
"If",
"it",
"is",
"then",
"it",
"s",
"a",
"decimal",
"v... | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/lexer/stateFn.go#L117-L160 |
17,358 | chewxy/lingo | dep/train.go | WithTrainingModel | func WithTrainingModel(m *Model) TrainerConsOpt {
f := func(t *Trainer) {
t.Model = m
}
return f
} | go | func WithTrainingModel(m *Model) TrainerConsOpt {
f := func(t *Trainer) {
t.Model = m
}
return f
} | [
"func",
"WithTrainingModel",
"(",
"m",
"*",
"Model",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"t",
".",
"Model",
"=",
"m",
"\n",
"}",
"\n",
"return",
"f",
"\n",
"}"
] | // WithTrainingModel loads a trainer with a model | [
"WithTrainingModel",
"loads",
"a",
"trainer",
"with",
"a",
"model"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L18-L23 |
17,359 | chewxy/lingo | dep/train.go | WithTrainingSet | func WithTrainingSet(st []treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
t.trainingSet = st
}
return f
} | go | func WithTrainingSet(st []treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
t.trainingSet = st
}
return f
} | [
"func",
"WithTrainingSet",
"(",
"st",
"[",
"]",
"treebank",
".",
"SentenceTag",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"t",
".",
"trainingSet",
"=",
"st",
"\n",
"}",
"\n",
"return",
"f",
"\n",
"}"
] | // WithTrainingSet creates a trainer with a training set | [
"WithTrainingSet",
"creates",
"a",
"trainer",
"with",
"a",
"training",
"set"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L26-L31 |
17,360 | chewxy/lingo | dep/train.go | WithCrossValidationSet | func WithCrossValidationSet(st []treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
t.crossValSet = st
}
return f
} | go | func WithCrossValidationSet(st []treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
t.crossValSet = st
}
return f
} | [
"func",
"WithCrossValidationSet",
"(",
"st",
"[",
"]",
"treebank",
".",
"SentenceTag",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"t",
".",
"crossValSet",
"=",
"st",
"\n",
"}",
"\n",
"return",
"f",
"\n",
"}"
] | // WithCrossValidationSet creates a trainer with a cross validation set | [
"WithCrossValidationSet",
"creates",
"a",
"trainer",
"with",
"a",
"cross",
"validation",
"set"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L34-L39 |
17,361 | chewxy/lingo | dep/train.go | WithLemmatizer | func WithLemmatizer(l lingo.Lemmatizer) TrainerConsOpt {
f := func(t *Trainer) {
// cannot pass in itself!
if T, ok := l.(*Trainer); ok && T == t {
panic("Recursive definition of lemmatizer (trying to set the t.lemmatizer = T) !")
}
t.l = l
}
return f
} | go | func WithLemmatizer(l lingo.Lemmatizer) TrainerConsOpt {
f := func(t *Trainer) {
// cannot pass in itself!
if T, ok := l.(*Trainer); ok && T == t {
panic("Recursive definition of lemmatizer (trying to set the t.lemmatizer = T) !")
}
t.l = l
}
return f
} | [
"func",
"WithLemmatizer",
"(",
"l",
"lingo",
".",
"Lemmatizer",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"// cannot pass in itself!",
"if",
"T",
",",
"ok",
":=",
"l",
".",
"(",
"*",
"Trainer",
")",
";",
"ok",
... | // WithLemmatizer sets the lemmatizer option on the Trainer | [
"WithLemmatizer",
"sets",
"the",
"lemmatizer",
"option",
"on",
"the",
"Trainer"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L53-L63 |
17,362 | chewxy/lingo | dep/train.go | WithStemmer | func WithStemmer(s lingo.Stemmer) TrainerConsOpt {
f := func(t *Trainer) {
// cannot pass in itself
if T, ok := s.(*Trainer); ok && T == t {
panic("Recursive setting of stemmer! (Trying to set t.stemmer = T)")
}
t.s = s
}
return f
} | go | func WithStemmer(s lingo.Stemmer) TrainerConsOpt {
f := func(t *Trainer) {
// cannot pass in itself
if T, ok := s.(*Trainer); ok && T == t {
panic("Recursive setting of stemmer! (Trying to set t.stemmer = T)")
}
t.s = s
}
return f
} | [
"func",
"WithStemmer",
"(",
"s",
"lingo",
".",
"Stemmer",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"// cannot pass in itself",
"if",
"T",
",",
"ok",
":=",
"s",
".",
"(",
"*",
"Trainer",
")",
";",
"ok",
"&&",
... | // WithStemmer sets up the stemmer option on the DependencyParser | [
"WithStemmer",
"sets",
"up",
"the",
"stemmer",
"option",
"on",
"the",
"DependencyParser"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L66-L75 |
17,363 | chewxy/lingo | dep/train.go | WithCluster | func WithCluster(c map[string]lingo.Cluster) TrainerConsOpt {
f := func(t *Trainer) {
t.c = c
}
return f
} | go | func WithCluster(c map[string]lingo.Cluster) TrainerConsOpt {
f := func(t *Trainer) {
t.c = c
}
return f
} | [
"func",
"WithCluster",
"(",
"c",
"map",
"[",
"string",
"]",
"lingo",
".",
"Cluster",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"t",
".",
"c",
"=",
"c",
"\n",
"}",
"\n",
"return",
"f",
"\n",
"}"
] | // WithCluster sets the brown cluster options for the DependencyParser | [
"WithCluster",
"sets",
"the",
"brown",
"cluster",
"options",
"for",
"the",
"DependencyParser"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L78-L83 |
17,364 | chewxy/lingo | dep/train.go | WithCorpus | func WithCorpus(c *corpus.Corpus) TrainerConsOpt {
f := func(t *Trainer) {
t.corpus = c
t.nn.dict = c
}
return f
} | go | func WithCorpus(c *corpus.Corpus) TrainerConsOpt {
f := func(t *Trainer) {
t.corpus = c
t.nn.dict = c
}
return f
} | [
"func",
"WithCorpus",
"(",
"c",
"*",
"corpus",
".",
"Corpus",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"t",
".",
"corpus",
"=",
"c",
"\n",
"t",
".",
"nn",
".",
"dict",
"=",
"c",
"\n",
"}",
"\n",
"return... | // WithCorpus creates a Trainer with a corpus | [
"WithCorpus",
"creates",
"a",
"Trainer",
"with",
"a",
"corpus"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L86-L92 |
17,365 | chewxy/lingo | dep/train.go | WithGeneratedCorpus | func WithGeneratedCorpus(sts ...treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
dict := corpus.GenerateCorpus(sts)
if t.corpus == nil {
t.corpus = dict
} else {
t.corpus.Merge(dict)
}
t.nn.dict = t.corpus
}
return f
} | go | func WithGeneratedCorpus(sts ...treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
dict := corpus.GenerateCorpus(sts)
if t.corpus == nil {
t.corpus = dict
} else {
t.corpus.Merge(dict)
}
t.nn.dict = t.corpus
}
return f
} | [
"func",
"WithGeneratedCorpus",
"(",
"sts",
"...",
"treebank",
".",
"SentenceTag",
")",
"TrainerConsOpt",
"{",
"f",
":=",
"func",
"(",
"t",
"*",
"Trainer",
")",
"{",
"dict",
":=",
"corpus",
".",
"GenerateCorpus",
"(",
"sts",
")",
"\n",
"if",
"t",
".",
"... | // WithGeneratedCorpus creates a Trainer's corpus from a list of SentenceTags. The corpus will be generated from the SentenceTags | [
"WithGeneratedCorpus",
"creates",
"a",
"Trainer",
"s",
"corpus",
"from",
"a",
"list",
"of",
"SentenceTags",
".",
"The",
"corpus",
"will",
"be",
"generated",
"from",
"the",
"SentenceTags"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L95-L107 |
17,366 | chewxy/lingo | dep/train.go | NewTrainer | func NewTrainer(opts ...TrainerConsOpt) *Trainer {
t := new(Trainer)
// set up the default model
t.Model = new(Model)
t.corpus = KnownWords
t.ts = transitions
// set up the neural network
t.nn = new(neuralnetwork2)
t.nn.NNConfig = DefaultNNConfig
t.nn.transitions = transitions
t.nn.dict = KnownWords
for _, opt := range opts {
opt(t)
}
return t
} | go | func NewTrainer(opts ...TrainerConsOpt) *Trainer {
t := new(Trainer)
// set up the default model
t.Model = new(Model)
t.corpus = KnownWords
t.ts = transitions
// set up the neural network
t.nn = new(neuralnetwork2)
t.nn.NNConfig = DefaultNNConfig
t.nn.transitions = transitions
t.nn.dict = KnownWords
for _, opt := range opts {
opt(t)
}
return t
} | [
"func",
"NewTrainer",
"(",
"opts",
"...",
"TrainerConsOpt",
")",
"*",
"Trainer",
"{",
"t",
":=",
"new",
"(",
"Trainer",
")",
"\n",
"// set up the default model",
"t",
".",
"Model",
"=",
"new",
"(",
"Model",
")",
"\n",
"t",
".",
"corpus",
"=",
"KnownWords... | // NewTrainer creates a new Trainer. | [
"NewTrainer",
"creates",
"a",
"new",
"Trainer",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L133-L150 |
17,367 | chewxy/lingo | dep/train.go | Lemmatize | func (t *Trainer) Lemmatize(a string, pt lingo.POSTag) ([]string, error) {
if t.l == nil {
return nil, componentUnavailable("Lemmatizer")
}
return t.l.Lemmatize(a, pt)
} | go | func (t *Trainer) Lemmatize(a string, pt lingo.POSTag) ([]string, error) {
if t.l == nil {
return nil, componentUnavailable("Lemmatizer")
}
return t.l.Lemmatize(a, pt)
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"Lemmatize",
"(",
"a",
"string",
",",
"pt",
"lingo",
".",
"POSTag",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"t",
".",
"l",
"==",
"nil",
"{",
"return",
"nil",
",",
"componentUnavailable",
... | // Lemmatize implemnets lingo.Lemmatizer | [
"Lemmatize",
"implemnets",
"lingo",
".",
"Lemmatizer"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L153-L158 |
17,368 | chewxy/lingo | dep/train.go | Stem | func (t *Trainer) Stem(a string) (string, error) {
if t.s == nil {
return "", componentUnavailable("Stemmer")
}
return t.s.Stem(a)
} | go | func (t *Trainer) Stem(a string) (string, error) {
if t.s == nil {
return "", componentUnavailable("Stemmer")
}
return t.s.Stem(a)
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"Stem",
"(",
"a",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"t",
".",
"s",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"componentUnavailable",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ret... | // Stem implements lingo.Stemmer | [
"Stem",
"implements",
"lingo",
".",
"Stemmer"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L161-L166 |
17,369 | chewxy/lingo | dep/train.go | Clusters | func (t *Trainer) Clusters() (map[string]lingo.Cluster, error) {
if t.c == nil {
return nil, componentUnavailable("Clusters")
}
return t.c, nil
} | go | func (t *Trainer) Clusters() (map[string]lingo.Cluster, error) {
if t.c == nil {
return nil, componentUnavailable("Clusters")
}
return t.c, nil
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"Clusters",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"lingo",
".",
"Cluster",
",",
"error",
")",
"{",
"if",
"t",
".",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"componentUnavailable",
"(",
"\"",
"\"",
")... | // Clusters implements lingo.Fixer | [
"Clusters",
"implements",
"lingo",
".",
"Fixer"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L169-L174 |
17,370 | chewxy/lingo | dep/train.go | Perf | func (t *Trainer) Perf() <-chan Performance {
if t.perf == nil {
t.perf = make(chan Performance)
}
return t.perf
} | go | func (t *Trainer) Perf() <-chan Performance {
if t.perf == nil {
t.perf = make(chan Performance)
}
return t.perf
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"Perf",
"(",
")",
"<-",
"chan",
"Performance",
"{",
"if",
"t",
".",
"perf",
"==",
"nil",
"{",
"t",
".",
"perf",
"=",
"make",
"(",
"chan",
"Performance",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"perf",
"\... | // Perf returns a channel of Performance for monitoring the training. | [
"Perf",
"returns",
"a",
"channel",
"of",
"Performance",
"for",
"monitoring",
"the",
"training",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L188-L193 |
17,371 | chewxy/lingo | dep/train.go | Train | func (t *Trainer) Train(epochs int) error {
if err := t.pretrainCheck(); err != nil {
return err
}
if len(t.crossValSet) > 0 {
return t.crossValidateTrain(epochs)
}
return t.train(epochs)
} | go | func (t *Trainer) Train(epochs int) error {
if err := t.pretrainCheck(); err != nil {
return err
}
if len(t.crossValSet) > 0 {
return t.crossValidateTrain(epochs)
}
return t.train(epochs)
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"Train",
"(",
"epochs",
"int",
")",
"error",
"{",
"if",
"err",
":=",
"t",
".",
"pretrainCheck",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"t",
".",
"crossV... | // Train trains a model.
//
// If a cross validation set is provided, it will automatically train with the cross validation set | [
"Train",
"trains",
"a",
"model",
".",
"If",
"a",
"cross",
"validation",
"set",
"is",
"provided",
"it",
"will",
"automatically",
"train",
"with",
"the",
"cross",
"validation",
"set"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L209-L217 |
17,372 | chewxy/lingo | dep/train.go | train | func (t *Trainer) train(epochs int) error {
var epochChan chan struct{}
if t.cost != nil {
defer func() {
close(t.cost)
t.cost = nil
}()
epochChan = t.handleCosts()
if epochChan != nil {
defer close(epochChan)
}
}
examples := makeExamples(t.trainingSet, t.nn.NNConfig, t.nn.dict, t.ts, t)
for e := 0; e < epochs; e++ {
if err := t.nn.train(examples); err != nil {
return err
}
if epochChan != nil {
epochChan <- struct{}{}
}
shuffleExamples(examples)
}
return nil
} | go | func (t *Trainer) train(epochs int) error {
var epochChan chan struct{}
if t.cost != nil {
defer func() {
close(t.cost)
t.cost = nil
}()
epochChan = t.handleCosts()
if epochChan != nil {
defer close(epochChan)
}
}
examples := makeExamples(t.trainingSet, t.nn.NNConfig, t.nn.dict, t.ts, t)
for e := 0; e < epochs; e++ {
if err := t.nn.train(examples); err != nil {
return err
}
if epochChan != nil {
epochChan <- struct{}{}
}
shuffleExamples(examples)
}
return nil
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"train",
"(",
"epochs",
"int",
")",
"error",
"{",
"var",
"epochChan",
"chan",
"struct",
"{",
"}",
"\n",
"if",
"t",
".",
"cost",
"!=",
"nil",
"{",
"defer",
"func",
"(",
")",
"{",
"close",
"(",
"t",
".",
"co... | // train simply trains the model without having a cross validation. | [
"train",
"simply",
"trains",
"the",
"model",
"without",
"having",
"a",
"cross",
"validation",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L225-L254 |
17,373 | chewxy/lingo | dep/train.go | crossValidateTrain | func (t *Trainer) crossValidateTrain(epochs int) error {
if t.perf != nil {
defer func() {
close(t.perf)
t.perf = nil
}()
}
var epochChan chan struct{}
if t.cost != nil {
defer func() {
close(t.cost)
t.cost = nil
}()
epochChan = t.handleCosts()
if epochChan != nil {
defer close(epochChan)
}
}
examples := makeExamples(t.trainingSet, t.nn.NNConfig, t.nn.dict, t.ts, t)
var best Performance
for e := 0; e < epochs; e++ {
if err := t.nn.train(examples); err != nil {
return err
}
if t.EvalPerIter > 0 && e%t.EvalPerIter == 0 || e == epochs-1 {
perf := t.crossValidate(t.crossValSet)
// if there is a channel to report back the performance, send it down
if t.perf != nil {
perf.Iter = e
t.perf <- perf
}
if perf.UAS > best.UAS {
best = perf
if t.SaveBest != "" {
f, err := os.Create(t.SaveBest)
if err != nil {
err = errors.Wrapf(err, "Unable to open SaveBest file %q", t.SaveBest)
return err
}
t.Model.SaveWriter(f)
}
}
}
if epochChan != nil {
epochChan <- struct{}{}
}
shuffleExamples(examples)
}
return nil
} | go | func (t *Trainer) crossValidateTrain(epochs int) error {
if t.perf != nil {
defer func() {
close(t.perf)
t.perf = nil
}()
}
var epochChan chan struct{}
if t.cost != nil {
defer func() {
close(t.cost)
t.cost = nil
}()
epochChan = t.handleCosts()
if epochChan != nil {
defer close(epochChan)
}
}
examples := makeExamples(t.trainingSet, t.nn.NNConfig, t.nn.dict, t.ts, t)
var best Performance
for e := 0; e < epochs; e++ {
if err := t.nn.train(examples); err != nil {
return err
}
if t.EvalPerIter > 0 && e%t.EvalPerIter == 0 || e == epochs-1 {
perf := t.crossValidate(t.crossValSet)
// if there is a channel to report back the performance, send it down
if t.perf != nil {
perf.Iter = e
t.perf <- perf
}
if perf.UAS > best.UAS {
best = perf
if t.SaveBest != "" {
f, err := os.Create(t.SaveBest)
if err != nil {
err = errors.Wrapf(err, "Unable to open SaveBest file %q", t.SaveBest)
return err
}
t.Model.SaveWriter(f)
}
}
}
if epochChan != nil {
epochChan <- struct{}{}
}
shuffleExamples(examples)
}
return nil
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"crossValidateTrain",
"(",
"epochs",
"int",
")",
"error",
"{",
"if",
"t",
".",
"perf",
"!=",
"nil",
"{",
"defer",
"func",
"(",
")",
"{",
"close",
"(",
"t",
".",
"perf",
")",
"\n",
"t",
".",
"perf",
"=",
"n... | // crossValidateTrain trains the model but also does cross validation to ensure overfitting don't happen. | [
"crossValidateTrain",
"trains",
"the",
"model",
"but",
"also",
"does",
"cross",
"validation",
"to",
"ensure",
"overfitting",
"don",
"t",
"happen",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L257-L316 |
17,374 | chewxy/lingo | dep/train.go | pretrainCheck | func (t *Trainer) pretrainCheck() error {
// check
if t.nn == nil || !t.nn.initialized() {
return errors.Errorf("DependencyParser not init()'d. Perhaps you forgot to call .Init() somewhere?")
}
if len(t.trainingSet) == 0 {
return errors.Errorf("Cannot train with no training data set")
}
return nil
} | go | func (t *Trainer) pretrainCheck() error {
// check
if t.nn == nil || !t.nn.initialized() {
return errors.Errorf("DependencyParser not init()'d. Perhaps you forgot to call .Init() somewhere?")
}
if len(t.trainingSet) == 0 {
return errors.Errorf("Cannot train with no training data set")
}
return nil
} | [
"func",
"(",
"t",
"*",
"Trainer",
")",
"pretrainCheck",
"(",
")",
"error",
"{",
"// check",
"if",
"t",
".",
"nn",
"==",
"nil",
"||",
"!",
"t",
".",
"nn",
".",
"initialized",
"(",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
... | // pretrainCheck checks if everything is sane | [
"pretrainCheck",
"checks",
"if",
"everything",
"is",
"sane"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/train.go#L319-L330 |
17,375 | chewxy/lingo | POSTag.go | InPOSTags | func InPOSTags(x POSTag, set []POSTag) bool {
for _, v := range set {
if v == x {
return true
}
}
return false
} | go | func InPOSTags(x POSTag, set []POSTag) bool {
for _, v := range set {
if v == x {
return true
}
}
return false
} | [
"func",
"InPOSTags",
"(",
"x",
"POSTag",
",",
"set",
"[",
"]",
"POSTag",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"set",
"{",
"if",
"v",
"==",
"x",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // POSTag related functions | [
"POSTag",
"related",
"functions"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/POSTag.go#L34-L41 |
17,376 | chewxy/lingo | pos/postagger.go | Lemmatize | func (p *Tagger) Lemmatize(a string, pt lingo.POSTag) ([]string, error) {
if p.Lemmatizer == nil {
return nil, componentUnavailable("lemmatizer")
}
return p.Lemmatizer.Lemmatize(a, pt)
} | go | func (p *Tagger) Lemmatize(a string, pt lingo.POSTag) ([]string, error) {
if p.Lemmatizer == nil {
return nil, componentUnavailable("lemmatizer")
}
return p.Lemmatizer.Lemmatize(a, pt)
} | [
"func",
"(",
"p",
"*",
"Tagger",
")",
"Lemmatize",
"(",
"a",
"string",
",",
"pt",
"lingo",
".",
"POSTag",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"p",
".",
"Lemmatizer",
"==",
"nil",
"{",
"return",
"nil",
",",
"componentUnavaila... | // Lemmatize implements the lingo.Lemmatize interface. It however, defers the actual doing of the job to the Lemmatizer. | [
"Lemmatize",
"implements",
"the",
"lingo",
".",
"Lemmatize",
"interface",
".",
"It",
"however",
"defers",
"the",
"actual",
"doing",
"of",
"the",
"job",
"to",
"the",
"Lemmatizer",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/pos/postagger.go#L138-L143 |
17,377 | chewxy/lingo | pos/postagger.go | Stem | func (p *Tagger) Stem(a string) (string, error) {
if p.Stemmer == nil {
return "", componentUnavailable("stemmer")
}
return p.Stemmer.Stem(a)
} | go | func (p *Tagger) Stem(a string) (string, error) {
if p.Stemmer == nil {
return "", componentUnavailable("stemmer")
}
return p.Stemmer.Stem(a)
} | [
"func",
"(",
"p",
"*",
"Tagger",
")",
"Stem",
"(",
"a",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"p",
".",
"Stemmer",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"componentUnavailable",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
... | // Stem implements the lingo.Stemmer interface. It however, defers the actual stemming to the stemmer passed in. | [
"Stem",
"implements",
"the",
"lingo",
".",
"Stemmer",
"interface",
".",
"It",
"however",
"defers",
"the",
"actual",
"stemming",
"to",
"the",
"stemmer",
"passed",
"in",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/pos/postagger.go#L146-L151 |
17,378 | chewxy/lingo | pos/postagger.go | Clusters | func (p *Tagger) Clusters() (map[string]lingo.Cluster, error) {
if p.clusters == nil {
return nil, componentUnavailable("clusters")
}
return p.clusters, nil
} | go | func (p *Tagger) Clusters() (map[string]lingo.Cluster, error) {
if p.clusters == nil {
return nil, componentUnavailable("clusters")
}
return p.clusters, nil
} | [
"func",
"(",
"p",
"*",
"Tagger",
")",
"Clusters",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"lingo",
".",
"Cluster",
",",
"error",
")",
"{",
"if",
"p",
".",
"clusters",
"==",
"nil",
"{",
"return",
"nil",
",",
"componentUnavailable",
"(",
"\"",
"\""... | // Clusters implements the lingo.AnnotationFixer interface. | [
"Clusters",
"implements",
"the",
"lingo",
".",
"AnnotationFixer",
"interface",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/pos/postagger.go#L154-L159 |
17,379 | chewxy/lingo | pos/postagger.go | Progress | func (p *Tagger) Progress() <-chan Progress {
if p.progress == nil {
p.progress = make(chan Progress)
}
return p.progress
} | go | func (p *Tagger) Progress() <-chan Progress {
if p.progress == nil {
p.progress = make(chan Progress)
}
return p.progress
} | [
"func",
"(",
"p",
"*",
"Tagger",
")",
"Progress",
"(",
")",
"<-",
"chan",
"Progress",
"{",
"if",
"p",
".",
"progress",
"==",
"nil",
"{",
"p",
".",
"progress",
"=",
"make",
"(",
"chan",
"Progress",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"progre... | // Progress creates and returns a channel of progress. By default the progress channel isn't created, and no progress info is sent | [
"Progress",
"creates",
"and",
"returns",
"a",
"channel",
"of",
"progress",
".",
"By",
"default",
"the",
"progress",
"channel",
"isn",
"t",
"created",
"and",
"no",
"progress",
"info",
"is",
"sent"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/pos/postagger.go#L162-L167 |
17,380 | chewxy/lingo | pos/postagger.go | Train | func (p *Tagger) Train(sentences []treebank.SentenceTag, iterations int) {
if p.progress != nil {
defer func() {
close(p.progress)
p.progress = nil
}()
}
p.fillCache(sentences)
// Somehow sentenceTag.AnnotatedSentence() is memory leaky.
// As a result, the more training iterations there is, the more memory is used and not released
// hence the cache is necessary.
cache := make(map[string]lingo.AnnotatedSentence)
for iter := 0; iter < iterations; iter++ {
c := 0
n := 0
shortcutted := 0
var s lingo.AnnotatedSentence
for _, sentenceTag := range sentences {
tags := []lingo.POSTag{lingo.ROOT_TAG}
tags = append(tags, sentenceTag.Tags...)
var ok bool
if s, ok = cache[sentenceTag.String()]; !ok {
s = sentenceTag.AnnotatedSentence(p) // the fixer is used to extract cluster information, etc into the *Annotation
cache[sentenceTag.String()] = s
}
length := len(s)
if length == 0 {
continue
}
for _, a := range s {
if a == lingo.RootAnnotation() {
continue
}
a.POSTag = lingo.X
}
for i, a := range s {
// processing
truth := tags[i]
guess, ok := p.shortcut(a.Lexeme)
if !ok {
sf, tf := getFeatures(s, i)
guess = p.perceptron.predict(sf, tf)
p.perceptron.update(guess, truth, sf, tf)
} else {
shortcutted++
}
p.setTag(a, guess)
if guess == truth {
c++
}
n++
}
}
if iter%150 == 0 {
p.perceptron.average()
logf("Averaged perceptron")
}
if p.progress != nil {
p.progress <- Progress{Iter: iter, Correct: c, Count: n, ShortCutted: shortcutted}
}
treebank.ShuffleSentenceTag(sentences)
}
p.perceptron.average()
} | go | func (p *Tagger) Train(sentences []treebank.SentenceTag, iterations int) {
if p.progress != nil {
defer func() {
close(p.progress)
p.progress = nil
}()
}
p.fillCache(sentences)
// Somehow sentenceTag.AnnotatedSentence() is memory leaky.
// As a result, the more training iterations there is, the more memory is used and not released
// hence the cache is necessary.
cache := make(map[string]lingo.AnnotatedSentence)
for iter := 0; iter < iterations; iter++ {
c := 0
n := 0
shortcutted := 0
var s lingo.AnnotatedSentence
for _, sentenceTag := range sentences {
tags := []lingo.POSTag{lingo.ROOT_TAG}
tags = append(tags, sentenceTag.Tags...)
var ok bool
if s, ok = cache[sentenceTag.String()]; !ok {
s = sentenceTag.AnnotatedSentence(p) // the fixer is used to extract cluster information, etc into the *Annotation
cache[sentenceTag.String()] = s
}
length := len(s)
if length == 0 {
continue
}
for _, a := range s {
if a == lingo.RootAnnotation() {
continue
}
a.POSTag = lingo.X
}
for i, a := range s {
// processing
truth := tags[i]
guess, ok := p.shortcut(a.Lexeme)
if !ok {
sf, tf := getFeatures(s, i)
guess = p.perceptron.predict(sf, tf)
p.perceptron.update(guess, truth, sf, tf)
} else {
shortcutted++
}
p.setTag(a, guess)
if guess == truth {
c++
}
n++
}
}
if iter%150 == 0 {
p.perceptron.average()
logf("Averaged perceptron")
}
if p.progress != nil {
p.progress <- Progress{Iter: iter, Correct: c, Count: n, ShortCutted: shortcutted}
}
treebank.ShuffleSentenceTag(sentences)
}
p.perceptron.average()
} | [
"func",
"(",
"p",
"*",
"Tagger",
")",
"Train",
"(",
"sentences",
"[",
"]",
"treebank",
".",
"SentenceTag",
",",
"iterations",
"int",
")",
"{",
"if",
"p",
".",
"progress",
"!=",
"nil",
"{",
"defer",
"func",
"(",
")",
"{",
"close",
"(",
"p",
".",
"... | // Train trains a POSTagger, given a bunch of SentenceTags | [
"Train",
"trains",
"a",
"POSTagger",
"given",
"a",
"bunch",
"of",
"SentenceTags"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/pos/postagger.go#L170-L245 |
17,381 | chewxy/lingo | pos/postagger.go | LoadShortcuts | func (p *Tagger) LoadShortcuts(shortcuts map[string]lingo.POSTag) {
for shortcut, tags := range shortcuts {
p.cachedTags[shortcut] = tags
}
} | go | func (p *Tagger) LoadShortcuts(shortcuts map[string]lingo.POSTag) {
for shortcut, tags := range shortcuts {
p.cachedTags[shortcut] = tags
}
} | [
"func",
"(",
"p",
"*",
"Tagger",
")",
"LoadShortcuts",
"(",
"shortcuts",
"map",
"[",
"string",
"]",
"lingo",
".",
"POSTag",
")",
"{",
"for",
"shortcut",
",",
"tags",
":=",
"range",
"shortcuts",
"{",
"p",
".",
"cachedTags",
"[",
"shortcut",
"]",
"=",
... | // LoadShortcuts allows for domain specific things to be mapped into the tagger. | [
"LoadShortcuts",
"allows",
"for",
"domain",
"specific",
"things",
"to",
"be",
"mapped",
"into",
"the",
"tagger",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/pos/postagger.go#L248-L252 |
17,382 | chewxy/lingo | dep/example.go | makeOneExample | func makeOneExample(i int, sentenceTag treebank.SentenceTag, dict *corpus.Corpus, ts []transition, f lingo.AnnotationFixer) ([]example, error) {
var examples []example
s := sentenceTag.AnnotatedSentence(f)
dep := s.Dependency()
if dep.IsProjective() {
c := newConfiguration(s, true)
count := 0
for !c.isTerminal() && count < 1000 {
if count == 999 {
return examples, TarpitError{c}
}
oracle := c.oracle(dep)
features := getFeatures(c, dict)
labels := make([]int, MAXTRANSITION)
for i, t := range ts {
if t == oracle {
labels[i] = 1
} else if c.canApply(t) {
labels[i] = 0
} else {
labels[i] = -1
}
}
ex := example{transition{oracle.Move, oracle.DependencyType}, features, labels}
examples = append(examples, ex)
c.apply(oracle)
count++
}
} else {
return nil, NonProjectiveError{dep}
}
return examples, nil
} | go | func makeOneExample(i int, sentenceTag treebank.SentenceTag, dict *corpus.Corpus, ts []transition, f lingo.AnnotationFixer) ([]example, error) {
var examples []example
s := sentenceTag.AnnotatedSentence(f)
dep := s.Dependency()
if dep.IsProjective() {
c := newConfiguration(s, true)
count := 0
for !c.isTerminal() && count < 1000 {
if count == 999 {
return examples, TarpitError{c}
}
oracle := c.oracle(dep)
features := getFeatures(c, dict)
labels := make([]int, MAXTRANSITION)
for i, t := range ts {
if t == oracle {
labels[i] = 1
} else if c.canApply(t) {
labels[i] = 0
} else {
labels[i] = -1
}
}
ex := example{transition{oracle.Move, oracle.DependencyType}, features, labels}
examples = append(examples, ex)
c.apply(oracle)
count++
}
} else {
return nil, NonProjectiveError{dep}
}
return examples, nil
} | [
"func",
"makeOneExample",
"(",
"i",
"int",
",",
"sentenceTag",
"treebank",
".",
"SentenceTag",
",",
"dict",
"*",
"corpus",
".",
"Corpus",
",",
"ts",
"[",
"]",
"transition",
",",
"f",
"lingo",
".",
"AnnotationFixer",
")",
"(",
"[",
"]",
"example",
",",
... | // makeOneExample is an example of a poorly named function. It makes an example from a SentenceTag | [
"makeOneExample",
"is",
"an",
"example",
"of",
"a",
"poorly",
"named",
"function",
".",
"It",
"makes",
"an",
"example",
"from",
"a",
"SentenceTag"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/example.go#L43-L82 |
17,383 | chewxy/lingo | treebank/treebank.go | LoadUniversal | func LoadUniversal(fileName string) []SentenceTag {
f, err := os.Open(fileName)
if err != nil {
panic(err)
}
defer f.Close()
return ReadConllu(f)
} | go | func LoadUniversal(fileName string) []SentenceTag {
f, err := os.Open(fileName)
if err != nil {
panic(err)
}
defer f.Close()
return ReadConllu(f)
} | [
"func",
"LoadUniversal",
"(",
"fileName",
"string",
")",
"[",
"]",
"SentenceTag",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
"... | // LoadUniversal loads a treebank file formatted in a CONLLU format | [
"LoadUniversal",
"loads",
"a",
"treebank",
"file",
"formatted",
"in",
"a",
"CONLLU",
"format"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/treebank/treebank.go#L21-L29 |
17,384 | chewxy/lingo | treebank/treebank.go | ReadConllu | func ReadConllu(reader io.Reader) []SentenceTag {
s, st, sh, sdt := reset()
sentences := make([]SentenceTag, 0)
sentenceCount := 0
var usedTags lingo.TagSet
var usedDepTypes lingo.DependencyTypeSet
var unknownTags = make(map[string]struct{})
var unknownDepType = make(map[string]struct{})
colCount := 0
for bs := bufio.NewScanner(reader); bs.Scan(); colCount++ {
l := bs.Text()
if len(l) == 0 {
// then this is a new sentence
sentences = finish(s, st, sh, sdt, sentences)
s, st, sh, sdt = reset()
sentenceCount++
continue
}
cols := strings.Split(l, "\t")
word := cols[1]
var tag string
switch lingo.BUILD_TAGSET {
case "stanfordtags":
tag = cols[4]
case "universaltags":
tag = cols[3]
default:
panic("Unknown tagset")
}
head := cols[6]
depType := cols[7]
var t lingo.POSTag
var dt lingo.DependencyType
var h int
var ok bool
var err error
word = lingo.UnescapeSpecials(word)
lexType := StringToLexType(tag)
if t, ok = StringToPOSTag(tag); ok {
usedTags[t] = true
} else {
unknownTags[tag] = empty
}
if h, err = strconv.Atoi(head); err != nil {
panic(err) // panic is the right option, because there is no default
}
if dt, ok = StringToDependencyType(depType); ok {
usedDepTypes[dt] = true
} else {
unknownDepType[depType] = empty
}
lexeme := lingo.Lexeme{word, lexType, sentenceCount, colCount}
s = append(s, lexeme)
st = append(st, t)
sh = append(sh, h)
sdt = append(sdt, dt)
}
return sentences
} | go | func ReadConllu(reader io.Reader) []SentenceTag {
s, st, sh, sdt := reset()
sentences := make([]SentenceTag, 0)
sentenceCount := 0
var usedTags lingo.TagSet
var usedDepTypes lingo.DependencyTypeSet
var unknownTags = make(map[string]struct{})
var unknownDepType = make(map[string]struct{})
colCount := 0
for bs := bufio.NewScanner(reader); bs.Scan(); colCount++ {
l := bs.Text()
if len(l) == 0 {
// then this is a new sentence
sentences = finish(s, st, sh, sdt, sentences)
s, st, sh, sdt = reset()
sentenceCount++
continue
}
cols := strings.Split(l, "\t")
word := cols[1]
var tag string
switch lingo.BUILD_TAGSET {
case "stanfordtags":
tag = cols[4]
case "universaltags":
tag = cols[3]
default:
panic("Unknown tagset")
}
head := cols[6]
depType := cols[7]
var t lingo.POSTag
var dt lingo.DependencyType
var h int
var ok bool
var err error
word = lingo.UnescapeSpecials(word)
lexType := StringToLexType(tag)
if t, ok = StringToPOSTag(tag); ok {
usedTags[t] = true
} else {
unknownTags[tag] = empty
}
if h, err = strconv.Atoi(head); err != nil {
panic(err) // panic is the right option, because there is no default
}
if dt, ok = StringToDependencyType(depType); ok {
usedDepTypes[dt] = true
} else {
unknownDepType[depType] = empty
}
lexeme := lingo.Lexeme{word, lexType, sentenceCount, colCount}
s = append(s, lexeme)
st = append(st, t)
sh = append(sh, h)
sdt = append(sdt, dt)
}
return sentences
} | [
"func",
"ReadConllu",
"(",
"reader",
"io",
".",
"Reader",
")",
"[",
"]",
"SentenceTag",
"{",
"s",
",",
"st",
",",
"sh",
",",
"sdt",
":=",
"reset",
"(",
")",
"\n",
"sentences",
":=",
"make",
"(",
"[",
"]",
"SentenceTag",
",",
"0",
")",
"\n",
"sent... | // ReadConllu reads a file formatted in a CONLLU format | [
"ReadConllu",
"reads",
"a",
"file",
"formatted",
"in",
"a",
"CONLLU",
"format"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/treebank/treebank.go#L32-L103 |
17,385 | chewxy/lingo | dependencyType.go | InDepTypes | func InDepTypes(x DependencyType, set []DependencyType) bool {
for _, v := range set {
if v == x {
return true
}
}
return false
} | go | func InDepTypes(x DependencyType, set []DependencyType) bool {
for _, v := range set {
if v == x {
return true
}
}
return false
} | [
"func",
"InDepTypes",
"(",
"x",
"DependencyType",
",",
"set",
"[",
"]",
"DependencyType",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"set",
"{",
"if",
"v",
"==",
"x",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",... | // list of dependency type functions | [
"list",
"of",
"dependency",
"type",
"functions"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dependencyType.go#L35-L42 |
17,386 | chewxy/lingo | dep/nn2.go | train | func (nn *neuralnetwork2) train(examples []example) error {
size := len(examples)
batches := size / nn.BatchSize
var start, end int
if nn.BatchSize > size {
batches = 1
end = size
G.WithBatchSize(float64(size))(nn.solver) // set it such that the solver doesn't get confused
} else {
end = nn.BatchSize
}
for batch := 0; batch < batches; batch++ {
for _, ex := range examples[start:end] {
nn.feats2vec(ex.features)
tid := lookupTransition(ex.transition, nn.transitions)
if err := G.UnsafeLet(nn.cost, G.S(tid)); err != nil {
return err
}
if err := nn.vm.RunAll(); err != nil {
return err
}
nn.vm.Reset()
}
if err := nn.solver.Step(nn.model); err != nil {
err = errors.Wrapf(err, "Stepping on the model failed %v", batch)
return err
}
if nn.costChan != nil {
nn.costChan <- nn.costVal
}
start = end
if start >= size {
break
}
end += nn.BatchSize
if end >= size {
end = size
}
}
return nil
} | go | func (nn *neuralnetwork2) train(examples []example) error {
size := len(examples)
batches := size / nn.BatchSize
var start, end int
if nn.BatchSize > size {
batches = 1
end = size
G.WithBatchSize(float64(size))(nn.solver) // set it such that the solver doesn't get confused
} else {
end = nn.BatchSize
}
for batch := 0; batch < batches; batch++ {
for _, ex := range examples[start:end] {
nn.feats2vec(ex.features)
tid := lookupTransition(ex.transition, nn.transitions)
if err := G.UnsafeLet(nn.cost, G.S(tid)); err != nil {
return err
}
if err := nn.vm.RunAll(); err != nil {
return err
}
nn.vm.Reset()
}
if err := nn.solver.Step(nn.model); err != nil {
err = errors.Wrapf(err, "Stepping on the model failed %v", batch)
return err
}
if nn.costChan != nil {
nn.costChan <- nn.costVal
}
start = end
if start >= size {
break
}
end += nn.BatchSize
if end >= size {
end = size
}
}
return nil
} | [
"func",
"(",
"nn",
"*",
"neuralnetwork2",
")",
"train",
"(",
"examples",
"[",
"]",
"example",
")",
"error",
"{",
"size",
":=",
"len",
"(",
"examples",
")",
"\n",
"batches",
":=",
"size",
"/",
"nn",
".",
"BatchSize",
"\n\n",
"var",
"start",
",",
"end"... | // train does one epoch of training. The examples are batched. | [
"train",
"does",
"one",
"epoch",
"of",
"training",
".",
"The",
"examples",
"are",
"batched",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/nn2.go#L296-L344 |
17,387 | chewxy/lingo | dep/nn2.go | pred | func (nn *neuralnetwork2) pred(ind []int) (int, error) {
nn.feats2vec(ind)
// f, _ := os.OpenFile("LOOOOOG", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
// logger := log.New(f, "", 0)
// logger := log.New(os.Stderr, "", 0)
// m := G.NewLispMachine(nn.sub, G.ExecuteFwdOnly(), G.WithLogger(logger), G.WithWatchlist(), G.LogBothDir(), G.WithValueFmt("%+3.3v"))
m := G.NewLispMachine(nn.sub, G.ExecuteFwdOnly())
if err := m.RunAll(); err != nil {
return 0, err
}
// logger.Println("========================\n")
val := nn.scores.Value().(tensor.Tensor)
t, err := tensor.Argmax(val, tensor.AllAxes)
if err != nil {
return 0, err
}
return t.ScalarValue().(int), nil
} | go | func (nn *neuralnetwork2) pred(ind []int) (int, error) {
nn.feats2vec(ind)
// f, _ := os.OpenFile("LOOOOOG", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
// logger := log.New(f, "", 0)
// logger := log.New(os.Stderr, "", 0)
// m := G.NewLispMachine(nn.sub, G.ExecuteFwdOnly(), G.WithLogger(logger), G.WithWatchlist(), G.LogBothDir(), G.WithValueFmt("%+3.3v"))
m := G.NewLispMachine(nn.sub, G.ExecuteFwdOnly())
if err := m.RunAll(); err != nil {
return 0, err
}
// logger.Println("========================\n")
val := nn.scores.Value().(tensor.Tensor)
t, err := tensor.Argmax(val, tensor.AllAxes)
if err != nil {
return 0, err
}
return t.ScalarValue().(int), nil
} | [
"func",
"(",
"nn",
"*",
"neuralnetwork2",
")",
"pred",
"(",
"ind",
"[",
"]",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"nn",
".",
"feats2vec",
"(",
"ind",
")",
"\n\n",
"// f, _ := os.OpenFile(\"LOOOOOG\", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)",
"// logg... | // pred predicts the index of the transitions | [
"pred",
"predicts",
"the",
"index",
"of",
"the",
"transitions"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/nn2.go#L347-L368 |
17,388 | chewxy/lingo | corpus/functions.go | GenerateCorpus | func GenerateCorpus(sentenceTags []treebank.SentenceTag) *Corpus {
words := make([]string, 3)
frequencies := make([]int, 3)
words[0] = "" // aka NULL, for when no word can be found
frequencies[0] = 0 // no word is never found
words[1] = "-UNKNOWN-"
frequencies[1] = 0
words[2] = "-ROOT-"
frequencies[2] = 1
knownWords := make(map[string]int)
knownWords[""] = 0
knownWords["-UNKNOWN-"] = 1
knownWords["-ROOT-"] = 2
maxWordLength := 0
for _, sentenceTag := range sentenceTags {
for _, lex := range sentenceTag.Sentence {
id, ok := knownWords[lex.Value]
if !ok {
knownWords[lex.Value] = len(words)
words = append(words, lex.Value)
frequencies = append(frequencies, 1)
runeCount := utf8.RuneCountInString(lex.Value)
if runeCount > maxWordLength {
maxWordLength = runeCount
}
} else {
frequencies[id]++
}
}
}
var totals int
for _, f := range frequencies {
totals += f
}
return &Corpus{words, frequencies, knownWords, int64(len(words)), totals, maxWordLength}
} | go | func GenerateCorpus(sentenceTags []treebank.SentenceTag) *Corpus {
words := make([]string, 3)
frequencies := make([]int, 3)
words[0] = "" // aka NULL, for when no word can be found
frequencies[0] = 0 // no word is never found
words[1] = "-UNKNOWN-"
frequencies[1] = 0
words[2] = "-ROOT-"
frequencies[2] = 1
knownWords := make(map[string]int)
knownWords[""] = 0
knownWords["-UNKNOWN-"] = 1
knownWords["-ROOT-"] = 2
maxWordLength := 0
for _, sentenceTag := range sentenceTags {
for _, lex := range sentenceTag.Sentence {
id, ok := knownWords[lex.Value]
if !ok {
knownWords[lex.Value] = len(words)
words = append(words, lex.Value)
frequencies = append(frequencies, 1)
runeCount := utf8.RuneCountInString(lex.Value)
if runeCount > maxWordLength {
maxWordLength = runeCount
}
} else {
frequencies[id]++
}
}
}
var totals int
for _, f := range frequencies {
totals += f
}
return &Corpus{words, frequencies, knownWords, int64(len(words)), totals, maxWordLength}
} | [
"func",
"GenerateCorpus",
"(",
"sentenceTags",
"[",
"]",
"treebank",
".",
"SentenceTag",
")",
"*",
"Corpus",
"{",
"words",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"3",
")",
"\n",
"frequencies",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"3",
")",
... | // GenerateCorpus creates a Corpus given a set of SentenceTag from a training set. | [
"GenerateCorpus",
"creates",
"a",
"Corpus",
"given",
"a",
"set",
"of",
"SentenceTag",
"from",
"a",
"training",
"set",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/functions.go#L14-L58 |
17,389 | chewxy/lingo | corpus/functions.go | ViterbiSplit | func ViterbiSplit(input string, c *Corpus) []string {
s := strings.ToLower(input)
probabilities := []float64{1.0}
lasts := []int{0}
runes := []int{}
for i := range s {
runes = append(runes, i)
}
runes = append(runes, len(s)+1)
for i := range s {
probs := make([]float64, 0)
ls := make([]int, 0)
// m := maxInt(0, i-c.maxWordLength)
for j, r := range runes {
if r > i {
break
}
p, ok := c.WordProb(s[r : i+1])
if !ok {
// http://stackoverflow.com/questions/195010/how-can-i-split-multiple-joined-words#comment48879458_481773
p = (math.Log(float64(1)/float64(c.totalFreq)) - float64(c.maxWordLength) - float64(1)) * float64(i-r) // note it should be i-r not j-i as per the SO post
}
prob := probabilities[j] * p
probs = append(probs, prob)
ls = append(ls, r)
}
maxProb := -math.SmallestNonzeroFloat64
maxK := -1 << 63
for j, p := range probs {
if p > maxProb {
maxProb = p
maxK = ls[j]
}
}
probabilities = append(probabilities, maxProb)
lasts = append(lasts, maxK)
}
words := make([]string, 0)
i := utf8.RuneCountInString(s)
for i > 0 {
start := lasts[i]
words = append(words, s[start:i])
i = start
}
// reverse it
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
return words
} | go | func ViterbiSplit(input string, c *Corpus) []string {
s := strings.ToLower(input)
probabilities := []float64{1.0}
lasts := []int{0}
runes := []int{}
for i := range s {
runes = append(runes, i)
}
runes = append(runes, len(s)+1)
for i := range s {
probs := make([]float64, 0)
ls := make([]int, 0)
// m := maxInt(0, i-c.maxWordLength)
for j, r := range runes {
if r > i {
break
}
p, ok := c.WordProb(s[r : i+1])
if !ok {
// http://stackoverflow.com/questions/195010/how-can-i-split-multiple-joined-words#comment48879458_481773
p = (math.Log(float64(1)/float64(c.totalFreq)) - float64(c.maxWordLength) - float64(1)) * float64(i-r) // note it should be i-r not j-i as per the SO post
}
prob := probabilities[j] * p
probs = append(probs, prob)
ls = append(ls, r)
}
maxProb := -math.SmallestNonzeroFloat64
maxK := -1 << 63
for j, p := range probs {
if p > maxProb {
maxProb = p
maxK = ls[j]
}
}
probabilities = append(probabilities, maxProb)
lasts = append(lasts, maxK)
}
words := make([]string, 0)
i := utf8.RuneCountInString(s)
for i > 0 {
start := lasts[i]
words = append(words, s[start:i])
i = start
}
// reverse it
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
return words
} | [
"func",
"ViterbiSplit",
"(",
"input",
"string",
",",
"c",
"*",
"Corpus",
")",
"[",
"]",
"string",
"{",
"s",
":=",
"strings",
".",
"ToLower",
"(",
"input",
")",
"\n",
"probabilities",
":=",
"[",
"]",
"float64",
"{",
"1.0",
"}",
"\n",
"lasts",
":=",
... | // ViterbiSplit is a Viterbi algorithm for splitting words given a corpus | [
"ViterbiSplit",
"is",
"a",
"Viterbi",
"algorithm",
"for",
"splitting",
"words",
"given",
"a",
"corpus"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/functions.go#L61-L121 |
17,390 | chewxy/lingo | corpus/functions.go | CosineSimilarity | func CosineSimilarity(a, b []string) float64 {
countsA := make([]float64, 0)
countsB := make([]float64, 0)
uniques := make(map[string]int)
// index the strings first
for _, st := range a {
s := strings.ToLower(st)
id, ok := uniques[s]
if !ok {
uniques[s] = len(countsA)
countsA = append(countsA, 1)
countsB = append(countsB, 0) // create for countsB, but don't add
} else {
countsA[id]++
}
}
for _, st := range b {
s := strings.ToLower(st)
id, ok := uniques[s]
if !ok {
uniques[s] = len(countsA)
countsA = append(countsA, 0)
countsB = append(countsB, 1)
} else {
countsB[id]++
}
}
magA, err := mag(countsA)
if err != nil {
panic(err)
}
magB, err := mag(countsB)
if err != nil {
panic(err)
}
dotProd, err := dot(countsA, countsB)
if err != nil {
panic(err)
}
return dotProd / (magA * magB)
} | go | func CosineSimilarity(a, b []string) float64 {
countsA := make([]float64, 0)
countsB := make([]float64, 0)
uniques := make(map[string]int)
// index the strings first
for _, st := range a {
s := strings.ToLower(st)
id, ok := uniques[s]
if !ok {
uniques[s] = len(countsA)
countsA = append(countsA, 1)
countsB = append(countsB, 0) // create for countsB, but don't add
} else {
countsA[id]++
}
}
for _, st := range b {
s := strings.ToLower(st)
id, ok := uniques[s]
if !ok {
uniques[s] = len(countsA)
countsA = append(countsA, 0)
countsB = append(countsB, 1)
} else {
countsB[id]++
}
}
magA, err := mag(countsA)
if err != nil {
panic(err)
}
magB, err := mag(countsB)
if err != nil {
panic(err)
}
dotProd, err := dot(countsA, countsB)
if err != nil {
panic(err)
}
return dotProd / (magA * magB)
} | [
"func",
"CosineSimilarity",
"(",
"a",
",",
"b",
"[",
"]",
"string",
")",
"float64",
"{",
"countsA",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"0",
")",
"\n",
"countsB",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"0",
")",
"\n",
"uniques",
":... | // CosineSimilarity measures the cosine similarity of two strings. | [
"CosineSimilarity",
"measures",
"the",
"cosine",
"similarity",
"of",
"two",
"strings",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/functions.go#L124-L171 |
17,391 | chewxy/lingo | corpus/functions.go | LongestCommonPrefix | func LongestCommonPrefix(strs ...string) string {
switch len(strs) {
case 0:
return "" // idiots
case 1:
return strs[0]
}
min := strs[0]
max := strs[0]
for _, s := range strs[1:] {
switch {
case s < min:
min = s
case s > max:
max = s
}
}
for i := 0; i < len(min) && i < len(max); i++ {
if min[i] != max[i] {
return min[:i]
}
}
// In the case where lengths are not equal but all bytes
// are equal, min is the answer ("foo" < "foobar").
return min
} | go | func LongestCommonPrefix(strs ...string) string {
switch len(strs) {
case 0:
return "" // idiots
case 1:
return strs[0]
}
min := strs[0]
max := strs[0]
for _, s := range strs[1:] {
switch {
case s < min:
min = s
case s > max:
max = s
}
}
for i := 0; i < len(min) && i < len(max); i++ {
if min[i] != max[i] {
return min[:i]
}
}
// In the case where lengths are not equal but all bytes
// are equal, min is the answer ("foo" < "foobar").
return min
} | [
"func",
"LongestCommonPrefix",
"(",
"strs",
"...",
"string",
")",
"string",
"{",
"switch",
"len",
"(",
"strs",
")",
"{",
"case",
"0",
":",
"return",
"\"",
"\"",
"// idiots",
"\n",
"case",
"1",
":",
"return",
"strs",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
... | // LongestCommonPrefix takes a slice of strings, and finds the longest common prefix | [
"LongestCommonPrefix",
"takes",
"a",
"slice",
"of",
"strings",
"and",
"finds",
"the",
"longest",
"common",
"prefix"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/functions.go#L274-L303 |
17,392 | chewxy/lingo | dependency.go | FromAnnotatedSentence | func FromAnnotatedSentence(s AnnotatedSentence) depConsOpt {
fn := func(d *Dependency) {
wc := len(s)
d.AnnotatedSentence = s
d.wordCount = wc
d.n = wc - 1
}
return fn
} | go | func FromAnnotatedSentence(s AnnotatedSentence) depConsOpt {
fn := func(d *Dependency) {
wc := len(s)
d.AnnotatedSentence = s
d.wordCount = wc
d.n = wc - 1
}
return fn
} | [
"func",
"FromAnnotatedSentence",
"(",
"s",
"AnnotatedSentence",
")",
"depConsOpt",
"{",
"fn",
":=",
"func",
"(",
"d",
"*",
"Dependency",
")",
"{",
"wc",
":=",
"len",
"(",
"s",
")",
"\n",
"d",
".",
"AnnotatedSentence",
"=",
"s",
"\n",
"d",
".",
"wordCou... | // FromAnnotatedSentence creates a dependency from an AnnotatedSentence. | [
"FromAnnotatedSentence",
"creates",
"a",
"dependency",
"from",
"an",
"AnnotatedSentence",
"."
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dependency.go#L29-L37 |
17,393 | chewxy/lingo | lexer/lexer.go | nextUntilEOF | func (l *Lexer) nextUntilEOF(s string) bool {
for r := l.next(); r != eof && strings.IndexRune(s, r) < 0; r = l.next() {
// l.next()
l.accept()
}
if l.r == eof {
return true
}
return false
} | go | func (l *Lexer) nextUntilEOF(s string) bool {
for r := l.next(); r != eof && strings.IndexRune(s, r) < 0; r = l.next() {
// l.next()
l.accept()
}
if l.r == eof {
return true
}
return false
} | [
"func",
"(",
"l",
"*",
"Lexer",
")",
"nextUntilEOF",
"(",
"s",
"string",
")",
"bool",
"{",
"for",
"r",
":=",
"l",
".",
"next",
"(",
")",
";",
"r",
"!=",
"eof",
"&&",
"strings",
".",
"IndexRune",
"(",
"s",
",",
"r",
")",
"<",
"0",
";",
"r",
... | // nextUntilEOF will loop until it finds the matching string OR EOF | [
"nextUntilEOF",
"will",
"loop",
"until",
"it",
"finds",
"the",
"matching",
"string",
"OR",
"EOF"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/lexer/lexer.go#L72-L81 |
17,394 | chewxy/lingo | dep/transition.go | init | func init() {
lbls := make([]lingo.DependencyType, lingo.MAXDEPTYPE)
for i := 0; i < int(lingo.MAXDEPTYPE); i++ {
lbls[i] = lingo.DependencyType(i)
}
transitions = buildTransitions(lbls)
MAXTRANSITION = len(transitions)
} | go | func init() {
lbls := make([]lingo.DependencyType, lingo.MAXDEPTYPE)
for i := 0; i < int(lingo.MAXDEPTYPE); i++ {
lbls[i] = lingo.DependencyType(i)
}
transitions = buildTransitions(lbls)
MAXTRANSITION = len(transitions)
} | [
"func",
"init",
"(",
")",
"{",
"lbls",
":=",
"make",
"(",
"[",
"]",
"lingo",
".",
"DependencyType",
",",
"lingo",
".",
"MAXDEPTYPE",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"int",
"(",
"lingo",
".",
"MAXDEPTYPE",
")",
";",
"i",
"++",
... | // this builds the default transitions | [
"this",
"builds",
"the",
"default",
"transitions"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/transition.go#L65-L74 |
17,395 | chewxy/lingo | dep/fix.go | fix | func fix(d *lingo.Dependency) {
// NNP fix:
// If a sentence is [a, b, c, D, E, f, g]
// where D, E are NNPs, they should be compound words
// The head should be the one with higher headID
spans := properNounSpans(d)
for _, s := range spans {
// we don't care about single word proper nouns
if s.end-s.start <= 1 {
continue
}
phrase := d.AnnotatedSentence[s.start:s.end]
// pick up all compound roots
// find annotations that do not have compound as deptype
var compoundRoots lingo.AnnotationSet
var problematic lingo.AnnotationSet
for _, a := range phrase {
if lingo.IsCompound(a.DependencyType) {
compoundRoots = compoundRoots.Add(a.Head)
}
if !lingo.IsCompound(a.DependencyType) && a.ID != s.end-1 {
problematic = problematic.Add(a)
}
}
// if no root
if len(compoundRoots) == 0 {
// actual root is the word with the largest ID
var compoundRoot *lingo.Annotation
var rootRoot *lingo.Annotation
for last := -1; s.end+last >= s.start; last-- {
predictedRoot := s.end + last
compoundRoot = d.AnnotatedSentence[predictedRoot]
// incorrects :
// dep==Dep
// dep==Root && others has dep != root
if compoundRoot.DependencyType == lingo.Dep {
problematic = problematic.Add(compoundRoot)
continue
}
if compoundRoot.DependencyType != lingo.Dep && compoundRoot.DependencyType != lingo.Root {
break
}
if compoundRoot.DependencyType == lingo.Root {
rootRoot = compoundRoot
problematic = problematic.Add(compoundRoot)
}
}
if rootRoot != nil && rootRoot != compoundRoot {
// we have two potential roots. Choose the best
log.Println("Problem when fixing: more than one possible compound root found")
}
for _, a := range problematic {
if a == compoundRoot {
continue
}
tmpHead := a.Head
tmpRel := a.DependencyType
a.SetHead(compoundRoot)
a.DependencyType = lingo.Compound
for _, childID := range d.AnnotatedSentence.Children(a.ID) {
childA := d.AnnotatedSentence[childID]
childA.SetHead(tmpHead)
childA.DependencyType = tmpRel
}
}
}
// if more than one root...
logf("More than zero compound roots not handled yet")
}
// Number fix
} | go | func fix(d *lingo.Dependency) {
// NNP fix:
// If a sentence is [a, b, c, D, E, f, g]
// where D, E are NNPs, they should be compound words
// The head should be the one with higher headID
spans := properNounSpans(d)
for _, s := range spans {
// we don't care about single word proper nouns
if s.end-s.start <= 1 {
continue
}
phrase := d.AnnotatedSentence[s.start:s.end]
// pick up all compound roots
// find annotations that do not have compound as deptype
var compoundRoots lingo.AnnotationSet
var problematic lingo.AnnotationSet
for _, a := range phrase {
if lingo.IsCompound(a.DependencyType) {
compoundRoots = compoundRoots.Add(a.Head)
}
if !lingo.IsCompound(a.DependencyType) && a.ID != s.end-1 {
problematic = problematic.Add(a)
}
}
// if no root
if len(compoundRoots) == 0 {
// actual root is the word with the largest ID
var compoundRoot *lingo.Annotation
var rootRoot *lingo.Annotation
for last := -1; s.end+last >= s.start; last-- {
predictedRoot := s.end + last
compoundRoot = d.AnnotatedSentence[predictedRoot]
// incorrects :
// dep==Dep
// dep==Root && others has dep != root
if compoundRoot.DependencyType == lingo.Dep {
problematic = problematic.Add(compoundRoot)
continue
}
if compoundRoot.DependencyType != lingo.Dep && compoundRoot.DependencyType != lingo.Root {
break
}
if compoundRoot.DependencyType == lingo.Root {
rootRoot = compoundRoot
problematic = problematic.Add(compoundRoot)
}
}
if rootRoot != nil && rootRoot != compoundRoot {
// we have two potential roots. Choose the best
log.Println("Problem when fixing: more than one possible compound root found")
}
for _, a := range problematic {
if a == compoundRoot {
continue
}
tmpHead := a.Head
tmpRel := a.DependencyType
a.SetHead(compoundRoot)
a.DependencyType = lingo.Compound
for _, childID := range d.AnnotatedSentence.Children(a.ID) {
childA := d.AnnotatedSentence[childID]
childA.SetHead(tmpHead)
childA.DependencyType = tmpRel
}
}
}
// if more than one root...
logf("More than zero compound roots not handled yet")
}
// Number fix
} | [
"func",
"fix",
"(",
"d",
"*",
"lingo",
".",
"Dependency",
")",
"{",
"// NNP fix:",
"// If a sentence is [a, b, c, D, E, f, g]",
"// where D, E are NNPs, they should be compound words",
"// The head should be the one with higher headID",
"spans",
":=",
"properNounSpans",
"(",
"d",... | // applies common fixes | [
"applies",
"common",
"fixes"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/dep/fix.go#L10-L96 |
17,396 | chewxy/lingo | corpus/inflection.go | Pluralize | func Pluralize(word string) string {
if lingo.InStringSlice(word, unconvertable) {
return word
}
for _, cp := range irregular {
if cp.pattern.MatchString(word) {
return cp.replacement
}
}
for _, cp := range plural {
if cp.pattern.MatchString(word) {
// log.Printf("\t%q Matches %q", word, cp.pattern.String())
return cp.pattern.ReplaceAllString(word, cp.replacement)
}
}
return word
} | go | func Pluralize(word string) string {
if lingo.InStringSlice(word, unconvertable) {
return word
}
for _, cp := range irregular {
if cp.pattern.MatchString(word) {
return cp.replacement
}
}
for _, cp := range plural {
if cp.pattern.MatchString(word) {
// log.Printf("\t%q Matches %q", word, cp.pattern.String())
return cp.pattern.ReplaceAllString(word, cp.replacement)
}
}
return word
} | [
"func",
"Pluralize",
"(",
"word",
"string",
")",
"string",
"{",
"if",
"lingo",
".",
"InStringSlice",
"(",
"word",
",",
"unconvertable",
")",
"{",
"return",
"word",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cp",
":=",
"range",
"irregular",
"{",
"if",
"cp",
... | // Pluralize pluralizes words based on rules known | [
"Pluralize",
"pluralizes",
"words",
"based",
"on",
"rules",
"known"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/inflection.go#L94-L112 |
17,397 | chewxy/lingo | corpus/inflection.go | Singularize | func Singularize(word string) string {
if lingo.InStringSlice(word, unconvertable) {
return word
}
for _, cp := range singular {
if cp.pattern.MatchString(word) {
return cp.pattern.ReplaceAllString(word, cp.replacement)
}
}
return word
} | go | func Singularize(word string) string {
if lingo.InStringSlice(word, unconvertable) {
return word
}
for _, cp := range singular {
if cp.pattern.MatchString(word) {
return cp.pattern.ReplaceAllString(word, cp.replacement)
}
}
return word
} | [
"func",
"Singularize",
"(",
"word",
"string",
")",
"string",
"{",
"if",
"lingo",
".",
"InStringSlice",
"(",
"word",
",",
"unconvertable",
")",
"{",
"return",
"word",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cp",
":=",
"range",
"singular",
"{",
"if",
"cp",
... | // Singularize singularizes words based on rules known | [
"Singularize",
"singularizes",
"words",
"based",
"on",
"rules",
"known"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/inflection.go#L115-L126 |
17,398 | chewxy/lingo | corpus/corpus.go | Construct | func Construct(opts ...ConsOpt) (*Corpus, error) {
c := new(Corpus)
// checks
if c.words == nil {
c.words = make([]string, 0)
}
if c.frequencies == nil {
c.frequencies = make([]int, 0)
}
if c.ids == nil {
c.ids = make(map[string]int)
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
return c, nil
} | go | func Construct(opts ...ConsOpt) (*Corpus, error) {
c := new(Corpus)
// checks
if c.words == nil {
c.words = make([]string, 0)
}
if c.frequencies == nil {
c.frequencies = make([]int, 0)
}
if c.ids == nil {
c.ids = make(map[string]int)
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
return c, nil
} | [
"func",
"Construct",
"(",
"opts",
"...",
"ConsOpt",
")",
"(",
"*",
"Corpus",
",",
"error",
")",
"{",
"c",
":=",
"new",
"(",
"Corpus",
")",
"\n\n",
"// checks",
"if",
"c",
".",
"words",
"==",
"nil",
"{",
"c",
".",
"words",
"=",
"make",
"(",
"[",
... | // Construct creates a Corpus given the construction options. This allows for more flexibility | [
"Construct",
"creates",
"a",
"Corpus",
"given",
"the",
"construction",
"options",
".",
"This",
"allows",
"for",
"more",
"flexibility"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/corpus.go#L40-L61 |
17,399 | chewxy/lingo | corpus/corpus.go | Id | func (c *Corpus) Id(word string) (int, bool) {
id, ok := c.ids[word]
return id, ok
} | go | func (c *Corpus) Id(word string) (int, bool) {
id, ok := c.ids[word]
return id, ok
} | [
"func",
"(",
"c",
"*",
"Corpus",
")",
"Id",
"(",
"word",
"string",
")",
"(",
"int",
",",
"bool",
")",
"{",
"id",
",",
"ok",
":=",
"c",
".",
"ids",
"[",
"word",
"]",
"\n",
"return",
"id",
",",
"ok",
"\n",
"}"
] | // ID returns the ID of a word and whether or not it was found in the corpus | [
"ID",
"returns",
"the",
"ID",
"of",
"a",
"word",
"and",
"whether",
"or",
"not",
"it",
"was",
"found",
"in",
"the",
"corpus"
] | 238c8836f032c232f721977047cece06842fcdf2 | https://github.com/chewxy/lingo/blob/238c8836f032c232f721977047cece06842fcdf2/corpus/corpus.go#L64-L67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.