code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1 value |
|---|---|---|---|---|---|
package buffer
import (
"gvisor.dev/gvisor/pkg/safemem"
)
// WriteBlock returns this buffer as a write Block.
func (b *buffer) WriteBlock() safemem.Block {
return safemem.BlockFromSafeSlice(b.WriteSlice())
}
// ReadBlock returns this buffer as a read Block.
func (b *buffer) ReadBlock() safemem.Block {
return safemem.BlockFromSafeSlice(b.ReadSlice())
}
// WriteFromSafememReader writes up to count bytes from r to v and advances the
// write index by the number of bytes written. It calls r.ReadToBlocks() at
// most once.
func (v *View) WriteFromSafememReader(r safemem.Reader, count uint64) (uint64, error) {
if count == 0 {
return 0, nil
}
var (
dst safemem.BlockSeq
blocks []safemem.Block
)
// Need at least one buffer.
firstBuf := v.data.Back()
if firstBuf == nil {
firstBuf = bufferPool.Get().(*buffer)
v.data.PushBack(firstBuf)
}
// Does the last block have sufficient capacity alone?
if l := uint64(firstBuf.WriteSize()); l >= count {
dst = safemem.BlockSeqOf(firstBuf.WriteBlock().TakeFirst64(count))
} else {
// Append blocks until sufficient.
count -= l
blocks = append(blocks, firstBuf.WriteBlock())
for count > 0 {
emptyBuf := bufferPool.Get().(*buffer)
v.data.PushBack(emptyBuf)
block := emptyBuf.WriteBlock().TakeFirst64(count)
count -= uint64(block.Len())
blocks = append(blocks, block)
}
dst = safemem.BlockSeqFromSlice(blocks)
}
// Perform I/O.
n, err := r.ReadToBlocks(dst)
v.size += int64(n)
// Update all indices.
for left := n; left > 0; firstBuf = firstBuf.Next() {
if l := firstBuf.WriteSize(); left >= uint64(l) {
firstBuf.WriteMove(l) // Whole block.
left -= uint64(l)
} else {
firstBuf.WriteMove(int(left)) // Partial block.
left = 0
}
}
return n, err
}
// WriteFromBlocks implements safemem.Writer.WriteFromBlocks. It advances the
// write index by the number of bytes written.
func (v *View) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {
return v.WriteFromSafememReader(&safemem.BlockSeqReader{srcs}, srcs.NumBytes())
}
// ReadToSafememWriter reads up to count bytes from v to w. It does not advance
// the read index. It calls w.WriteFromBlocks() at most once.
func (v *View) ReadToSafememWriter(w safemem.Writer, count uint64) (uint64, error) {
if count == 0 {
return 0, nil
}
var (
src safemem.BlockSeq
blocks []safemem.Block
)
firstBuf := v.data.Front()
if firstBuf == nil {
return 0, nil // No EOF.
}
// Is all the data in a single block?
if l := uint64(firstBuf.ReadSize()); l >= count {
src = safemem.BlockSeqOf(firstBuf.ReadBlock().TakeFirst64(count))
} else {
// Build a list of all the buffers.
count -= l
blocks = append(blocks, firstBuf.ReadBlock())
for buf := firstBuf.Next(); buf != nil && count > 0; buf = buf.Next() {
block := buf.ReadBlock().TakeFirst64(count)
count -= uint64(block.Len())
blocks = append(blocks, block)
}
src = safemem.BlockSeqFromSlice(blocks)
}
// Perform I/O. As documented, we don't advance the read index.
return w.WriteFromBlocks(src)
}
// ReadToBlocks implements safemem.Reader.ReadToBlocks. It does not advance the
// read index by the number of bytes read, such that it's only safe to call if
// the caller guarantees that ReadToBlocks will only be called once.
func (v *View) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {
return v.ReadToSafememWriter(&safemem.BlockSeqWriter{dsts}, dsts.NumBytes())
} | pkg/buffer/safemem.go | 0.713631 | 0.427935 | safemem.go | starcoder |
package util
import (
"time"
)
// String returns a string representing the duration in the form "72h3m0.5s".
// Leading zero units are omitted. As a special case, durations less than one
// second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
// that the leading digit is non-zero. The zero duration formats as 0s.
func FormatDuration(d *time.Duration, showSecondsOver1Min bool) string {
// Largest time is 2540400h10m10.000000000s
if d == nil {
return "<nil>"
}
var buf [32]byte
w := len(buf)
u := uint64(*d)
neg := *d < 0
if neg {
u = -u
}
if u < uint64(time.Second) {
// Special case: if duration is smaller than a second,
// use smaller units, like 1.2ms
var prec int
w--
buf[w] = 's'
w--
switch {
case u == 0:
return "0s"
case u < uint64(time.Microsecond):
// print nanoseconds
prec = 0
buf[w] = 'n'
case u < uint64(time.Millisecond):
// print microseconds
prec = 3
// U+00B5 'µ' micro sign == 0xC2 0xB5
w-- // Need room for two bytes.
copy(buf[w:], "µ")
default:
// print milliseconds
prec = 6
buf[w] = 'm'
}
w, u = fmtFrac(buf[:w], u, prec)
w = fmtInt(buf[:w], u, false)
} else {
// Fraction of a second
//w, u = fmtFrac(buf[:w], u, 9)
u = u / 1000000000
// u is now integer seconds
sec := u
u /= 60
// Only includes seconds if less then 1 minutes
if showSecondsOver1Min || u == 0 {
w--
buf[w] = 's'
//w, u = fmtFrac(buf[:w], u, 9)
leadingZero := u > 0
w = fmtInt(buf[:w], sec%60, leadingZero)
}
// u is now integer minutes
if u > 0 {
w--
buf[w] = 'm'
min := u
u /= 60
leadingZero := u > 0
w = fmtInt(buf[:w], min%60, leadingZero)
// u is now integer hours
if u > 0 {
w--
buf[w] = 'h'
hour := u
u /= 24
leadingZero := u > 0
w = fmtInt(buf[:w], hour%24, leadingZero)
// u is now integer days
if u > 0 {
w--
buf[w] = ' '
w--
buf[w] = 'd'
w = fmtInt(buf[:w], u, false)
}
}
}
}
if neg {
w--
buf[w] = '-'
}
return string(buf[w:])
}
// fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
// tail of buf, omitting trailing zeros. it omits the decimal
// point too when the fraction is 0. It returns the index where the
// output bytes begin and the value v/10**prec.
func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
// Omit trailing zeros up to and including decimal point.
w := len(buf)
print := false
for i := 0; i < prec; i++ {
digit := v % 10
print = print || digit != 0
if print {
w--
buf[w] = byte(digit) + '0'
}
v /= 10
}
if print {
w--
buf[w] = '.'
}
return w, v
}
// fmtInt formats v into the tail of buf.
// It returns the index where the output begins.
func fmtInt(buf []byte, v uint64, twoDigit bool) int {
w := len(buf)
if v == 0 {
w--
buf[w] = '0'
w--
buf[w] = '0'
} else {
oldV := v
for v > 0 {
w--
buf[w] = byte(v%10) + '0'
v /= 10
}
if twoDigit && oldV < 10 {
w--
buf[w] = '0'
}
}
return w
} | util/durationFormat.go | 0.672117 | 0.434041 | durationFormat.go | starcoder |
package merkle
import (
"github.com/dist-ribut-us/crypto"
"github.com/dist-ribut-us/errors"
"io"
)
// ErrIncomplete is returned when trying to perform an operation limited to a
// complete Tree (Read or ReadAll). Check if the Tree is complete with
// Tree.Complete()
const ErrIncomplete = errors.String("Tree is incomplete")
// ReadAll reads the contents of a tree into a byte slice
func (t *Tree) ReadAll() ([]byte, error) {
if !t.complete {
return nil, ErrIncomplete
}
l := int(t.leaves-1)*BlockSize + int(t.lastBlockLen)
b := make([]byte, l)
var startAt int64
_, err := recursiveRead(b, &startAt, t.dig, t.leaves == 1, t.f, true, int(t.lastBlockLen))
return b, err
}
// ValidationChain is used to validate that a leaf belongs to a tree. It
// includes all the Uncle digests.
type ValidationChain []*crypto.Digest
func recursiveRead(b []byte, startAt *int64, d *crypto.Digest, isLeaf bool, f *Forest, rightMost bool, lastLen int) (int, error) {
// startAt is a bit confusing, if we're starting at position 1000, we add the
// data length to it, when it becomes <=0, then we start reading. The negative value is how far from the beginning to start
if isLeaf {
if rightMost {
*startAt -= int64(lastLen)
if (*startAt) >= 0 {
return 0, io.EOF
}
} else {
*startAt -= BlockSize
}
l := 0
if *startAt <= 0 {
lf, _ := f.readLeaf(d)
if rightMost {
lf = lf[:lastLen]
}
l = len(lf)
s := l + int(*startAt)
if s < 0 {
s = 0
}
lf = lf[s:]
l = len(lf)
if lb := len(b); l > lb {
l = lb
}
copy(b, lf)
}
return l, nil
}
br := f.readBranch(d)
lb := len(b)
l := 0
var err error
if lb > 0 {
l, _ = recursiveRead(b, startAt, br.left, br.lIsLeaf(), f, false, lastLen)
}
var r int
if lb > l {
r, err = recursiveRead(b[l:], startAt, br.right, br.rIsLeaf(), f, rightMost, lastLen)
}
return l + r, err
}
// GetLeaf returns the ValidationChain and Leaf for a tree.
func (t *Tree) GetLeaf(lIdx int) (ValidationChain, []byte, error) {
vc, l, err := recursiveGetLeaf(uint32(lIdx), 0, t.leaves, t.dig, t.leaves == 1, t.f)
if lbl := int(t.lastBlockLen); lIdx == int(t.leaves)-1 && len(l) > lbl {
l = l[:lbl]
}
return vc, l, err
}
func recursiveGetLeaf(lIdx, start, end uint32, d *crypto.Digest, isLeaf bool, f *Forest) ([]*crypto.Digest, []byte, error) {
if isLeaf {
l, err := f.readLeaf(d)
return nil, l, err
}
b := f.readBranch(d)
mid := (start + end) / 2
var ud *crypto.Digest
if lIdx < mid || lIdx == start {
end = mid
d = b.left
ud = b.right
isLeaf = b.lIsLeaf()
} else {
start = mid
d = b.right
ud = b.left
isLeaf = b.rIsLeaf()
}
us, l, err := recursiveGetLeaf(lIdx, start, end, d, isLeaf, f)
return append(us, ud), l, err
}
// ValidateLeaf uses a ValidationChain to confirm that a leaf belongs to a tree
func (t *Tree) ValidateLeaf(vc ValidationChain, leaf []byte, lIdx int) bool {
return validateLeaf(vc, leaf, lIdx, t.dig, t.leaves)
}
func validateLeaf(vc ValidationChain, leaf []byte, lIdx int, d *crypto.Digest, ln uint32) bool {
v := crypto.GetDigest(leaf)
dirs := dirChain(uint32(lIdx), 0, ln)
if len(dirs) != len(vc) {
return false
}
for i, vd := range vc {
if dirs[i] {
v = crypto.GetDigest(v.Slice(), vd.Slice())
} else {
v = crypto.GetDigest(vd.Slice(), v.Slice())
}
}
return v.Equal(d)
}
func dirChain(lIdx, start, end uint32) []bool {
if start == end {
return nil
}
if end-start == 1 {
return nil
}
mid := (start + end) / 2
if lIdx < mid {
return append(dirChain(lIdx, start, mid), true)
}
return append(dirChain(lIdx, mid, end), false)
}
// Read implements the io.Reader interface to allow a tree to be read into a
// byte slice
func (t *Tree) Read(p []byte) (int, error) {
if !t.complete {
return 0, ErrIncomplete
}
startAt := t.pos
n, err := recursiveRead(p, &startAt, t.dig, t.leaves == 1, t.f, true, int(t.lastBlockLen))
t.pos += int64(n)
return n, err
}
// ErrBadWhence is returned if the whence value given to Seek is unknown
const ErrBadWhence = errors.String("Bad whence value")
// ErrNegativeOffset is returned if the result of a seek would set the tree
// offset position to a negative value.
const ErrNegativeOffset = errors.String("Attempting to Seek to negative offset")
// Seek implements io.Seeker
func (t *Tree) Seek(offset int64, whence int) (int64, error) {
var newPos int64
switch whence {
case io.SeekStart:
newPos = offset
case io.SeekCurrent:
newPos = t.pos + offset
case io.SeekEnd:
newPos = int64(t.Len()) + offset
default:
return t.pos, ErrBadWhence
}
if newPos < 0 {
return t.pos, ErrNegativeOffset
}
t.pos = newPos
return t.pos, nil
}
// Len returns the byte size of the tree
func (t *Tree) Len() int {
return (int(t.leaves-1)*BlockSize + int(t.lastBlockLen))
} | read_tree.go | 0.627038 | 0.416441 | read_tree.go | starcoder |
package dao
//GetCourseNumStudents returns the number of students enrolled in the course
func GetCourseNumStudents(courseID uint) (int64, error) {
var res int64
err := DB.Table("course_users").Where("course_id = ? OR ? = 0", courseID, courseID).Count(&res).Error
return res, err
}
//GetCourseNumVodViews returns the sum of vod views of a course
func GetCourseNumVodViews(courseID uint) (int, error) {
var res int
err := DB.Raw(`SELECT SUM(stats.viewers) FROM stats
JOIN streams s ON s.id = stats.stream_id
WHERE (s.course_id = ? or ? = 0) AND live = 0`, courseID, courseID).Scan(&res).Error
return res, err
}
//GetCourseNumLiveViews returns the sum of live views of a course based on the maximum views per lecture
func GetCourseNumLiveViews(courseID uint) (int, error) {
var res int
err := DB.Raw(`WITH views_per_stream AS (SELECT MAX(stats.viewers) AS y
FROM stats
JOIN streams s ON s.id = stats.stream_id
WHERE (s.course_id = ? OR ? = 0)
AND stats.live = 1
GROUP BY stats.stream_id)
SELECT SUM(y)
FROM views_per_stream`, courseID, courseID).Scan(&res).Error
return res, err
}
//GetCourseNumVodViewsPerDay returns the daily amount of vod views for each day
func GetCourseNumVodViewsPerDay(courseID uint) ([]Stat, error) {
var res []Stat
err := DB.Raw(`SELECT DATE_FORMAT(stats.time, GET_FORMAT(DATE, 'EUR')) AS x, sum(viewers) AS y
FROM stats
JOIN streams s ON s.id = stats.stream_id
WHERE (s.course_id = ? OR ? = 0) AND live = 0
GROUP BY DATE(stats.time);`,
courseID, courseID).Scan(&res).Error
return res, err
}
//GetCourseStatsWeekdays returns the days and their sum of vod views of a course
func GetCourseStatsWeekdays(courseID uint) ([]Stat, error) {
var res []Stat
err := DB.Raw(`SELECT DAYNAME(stats.time) AS x, SUM(stats.viewers) as y
FROM stats
JOIN streams s ON s.id = stats.stream_id
WHERE (s.course_id = ? OR ? = 0) AND stats.live = 0
GROUP BY DAYOFWEEK(stats.time);`,
courseID, courseID).Scan(&res).Error
return res, err
}
//GetCourseStatsHourly returns the hours with most vod viewing activity of a course
func GetCourseStatsHourly(courseID uint) ([]Stat, error) {
var res []Stat
err := DB.Raw(`SELECT HOUR(stats.time) AS x, SUM(stats.viewers) as y
FROM stats
JOIN streams s ON s.id = stats.stream_id
WHERE (s.course_id = ? or ? = 0) AND stats.live = 0
GROUP BY HOUR(stats.time);`,
courseID, courseID).Scan(&res).Error
return res, err
}
func GetStudentActivityCourseStats(courseID uint, live bool) ([]Stat, error) {
var res []Stat
err := DB.Raw(`SELECT DATE_FORMAT(stats.time, "%Y w%v") AS x, MAX(stats.viewers) AS y
FROM stats
JOIN streams s ON s.id = stats.stream_id
WHERE (s.course_id = ? OR ? = 0) AND stats.live = ?
GROUP BY year(stats.time), week(stats.time)
ORDER BY stats.time;`,
courseID, courseID, live).Scan(&res).Error
return res, err
}
//Stat key value struct that is parsable by Chart.js without further modifications.
//See https://www.chartjs.org/docs/master/general/data-structures.html
type Stat struct {
X string `json:"x"` // label for stat
Y int `json:"y"` // value for stat
} | dao/statistics.go | 0.600071 | 0.474266 | statistics.go | starcoder |
package unstructpath
// NumberP is a "number predicate". It's a type that decides if a
// number matches or not.
type NumberP interface {
Match(float64) bool
}
// NumberNot inverts the result of the sub-predicate.
func NumberNot(predicate NumberP) NumberP {
return numberNot{ip: predicate}
}
type numberNot struct {
ip NumberP
}
func (p numberNot) Match(i float64) bool {
return !p.ip.Match(i)
}
// NumberAnd returns true if all the sub-predicates are true. If there are
// no sub-predicates, always returns true.
func NumberAnd(predicates ...NumberP) NumberP {
return numberAnd{ips: predicates}
}
type numberAnd struct {
ips []NumberP
}
func (p numberAnd) Match(i float64) bool {
for _, ip := range p.ips {
if !ip.Match(i) {
return false
}
}
return true
}
// NumberOr returns true if any sub-predicate is true. If there are no
// sub-predicates, always returns false.
func NumberOr(predicates ...NumberP) NumberP {
ips := []NumberP{}
// Implements "De Morgan's law"
for _, ip := range predicates {
ips = append(ips, NumberNot(ip))
}
return NumberNot(NumberAnd(ips...))
}
// NumberEqual returns true if the value is exactly i.
func NumberEqual(i float64) NumberP {
return numberEqual{i: i}
}
type numberEqual struct {
i float64
}
func (p numberEqual) Match(i float64) bool {
return i == p.i
}
// NumberGreaterThan returns true if the value is strictly greater than i.
func NumberGreaterThan(i float64) NumberP {
return numberGreaterThan{i: i}
}
type numberGreaterThan struct {
i float64
}
func (p numberGreaterThan) Match(i float64) bool {
return i > p.i
}
// NumberEqualOrGreaterThan returns true if the value is equal or greater
// than i.
func NumberEqualOrGreaterThan(i float64) NumberP {
return NumberOr(NumberEqual(i), NumberGreaterThan(i))
}
// NumberLessThan returns true if the value is strictly less than i.
func NumberLessThan(i float64) NumberP {
// It's not equal, and it's not greater than i.
return NumberAnd(NumberNot(NumberEqual(i)), NumberNot(NumberGreaterThan(i)))
}
// NumberEqualOrLessThan returns true if the value is equal or less than i.
func NumberEqualOrLessThan(i float64) NumberP {
return NumberOr(NumberEqual(i), NumberLessThan(i))
} | pkg/framework/unstructpath/numberp.go | 0.871201 | 0.447279 | numberp.go | starcoder |
package scrummy
// Chart represents each graph build of a coodinates system and (possibly multiple) data lines.
type Chart interface {
Xaxis() []float64
Yaxis() []float64
Xlegend() string
Ylegend() string
Values() []float64
Legend() []string
}
// LineChart is a diagram with one or more data lines.
type LineChart struct {
xaxis []float64
yaxisL []float64
yaxisR []float64
xlegend string
ylegendL string
ylegendR string
values [][]float64
legend []string
}
// NewLineChart is the constructor for LineChart.
func NewLineChart(xaxis, yaxisL []float64, xlegend, ylegendR string) *LineChart {
l := new(LineChart)
l.xaxis = xaxis
l.yaxisL = yaxisL
l.xlegend = xlegend
l.ylegendR = ylegendR
return l
}
// Xaxis retrieves the values of the x-axis.
func (l *LineChart) Xaxis() []float64 {
return l.xaxis
}
// YaxisL retrieves the values of the left y-axis.
func (l *LineChart) YaxisL() []float64 {
return l.yaxisL
}
// YaxisR retrieves the values of the right y-axis.
func (l *LineChart) YaxisR() []float64 {
return l.yaxisR
}
// SetYAxisR set the values and the title for the optional right y-axis.
func (l *LineChart) SetYAxisR(values []float64, title string) {
l.yaxisR = values
l.ylegendR = title
}
// Xlegend retrieves the title of the x-axis.
func (l *LineChart) Xlegend() string {
return l.xlegend
}
// YlegendL retrieves the title of the left y-axis.
func (l *LineChart) YlegendL() string {
return l.ylegendL
}
// YlegendR retrieves the title of the right y-axis.
func (l *LineChart) YlegendR() string {
return l.ylegendR
}
// ValueMatrix retrieves the values of the line plots.
func (l *LineChart) ValueMatrix() [][]float64 {
return l.values
}
// Values retrieves the values of the line plots.
func (l *LineChart) Values(i int) []float64 {
return l.values[i]
}
// AddValues adds a new dataset (line) and its legend to the chart.
// It returns the index of the added dataset.
func (l *LineChart) AddValues(values []float64, legend string) int {
l.values = append(l.values, values)
l.legend = append(l.legend, legend)
return len(l.values) - 1
}
// Legend retrieves the titles of the line plots.
func (l *LineChart) Legend() []string {
return l.Legend()
} | chart.go | 0.846483 | 0.566019 | chart.go | starcoder |
package iso20022
// Information needed to process a currency exchange or conversion.
type ForeignExchangeTerms33 struct {
// Cash amount resulting from a foreign exchange trade.
ToAmount *ActiveCurrencyAndAmount `xml:"ToAmt,omitempty"`
// Cash amount for which a foreign exchange is required.
FromAmount *ActiveCurrencyAndAmount `xml:"FrAmt,omitempty"`
// Currency from which the quoted currency is converted in an exchange rate calculation.
// 1 x <UnitCcy> = <XchgRate> x <QtdCcy>.
UnitCurrency *ActiveCurrencyCode `xml:"UnitCcy"`
// Currency into which the unit currency is converted in an exchange rate calculation.
// 1 x <UnitCcy> = <XchgRate> x <QtdCcy>.
QuotedCurrency *ActiveCurrencyCode `xml:"QtdCcy"`
// Factor used for the conversion of an amount from one currency into another. This reflects that amount of the quoted currency that can be purchased with one unit of the unit currency , as follows:
// 1 x CUR1 = nnn x CUR2,
// where:
// CUR1 is the unit currency
// CUR2 is the quoted currency
// nnn is the exchange rate.
// 1 x <UnitCcy> = <XchgRate> x <QtdCcy>.
ExchangeRate *BaseOneRate `xml:"XchgRate"`
// Date and time at which an exchange rate is quoted.
QuotationDate *ISODateTime `xml:"QtnDt,omitempty"`
// Party that proposes the foreign exchange rate.
QuotingInstitution *PartyIdentification113 `xml:"QtgInstn,omitempty"`
}
func (f *ForeignExchangeTerms33) SetToAmount(value, currency string) {
f.ToAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (f *ForeignExchangeTerms33) SetFromAmount(value, currency string) {
f.FromAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (f *ForeignExchangeTerms33) SetUnitCurrency(value string) {
f.UnitCurrency = (*ActiveCurrencyCode)(&value)
}
func (f *ForeignExchangeTerms33) SetQuotedCurrency(value string) {
f.QuotedCurrency = (*ActiveCurrencyCode)(&value)
}
func (f *ForeignExchangeTerms33) SetExchangeRate(value string) {
f.ExchangeRate = (*BaseOneRate)(&value)
}
func (f *ForeignExchangeTerms33) SetQuotationDate(value string) {
f.QuotationDate = (*ISODateTime)(&value)
}
func (f *ForeignExchangeTerms33) AddQuotingInstitution() *PartyIdentification113 {
f.QuotingInstitution = new(PartyIdentification113)
return f.QuotingInstitution
} | ForeignExchangeTerms33.go | 0.778733 | 0.482856 | ForeignExchangeTerms33.go | starcoder |
package mdm
import (
"encoding/binary"
"errors"
"fmt"
"io"
"sort"
"sync"
"gitlab.com/NebulousLabs/Sia/build"
"gitlab.com/NebulousLabs/Sia/crypto"
"gitlab.com/NebulousLabs/Sia/modules"
"gitlab.com/NebulousLabs/Sia/types"
"gitlab.com/NebulousLabs/encoding"
)
// programData is a buffer for the program data. It will read packets from r and
// append them to data.
type programData struct {
// data contains the already received data.
data modules.ProgramData
// staticLength is the expected length of the program data. This is the
// amount of data that was paid for and not more than that will be read from
// the reader. Less data will be considered an unexpected EOF.
staticLength uint64
// readErr contains the first error encountered by threadedFetchData.
readErr error
// requests are queued up calls to 'bytes' waiting for the requested data to
// arrive.
requests []dataRequest
// cancel is used to cancel the background thread.
cancel chan struct{}
// wg is used to wait for the background thread to finish.
wg sync.WaitGroup
mu sync.Mutex
}
type dataRequest struct {
requiredLength uint64
c chan struct{}
}
// openProgramData creates a new programData object from the specified reader. It
// will read from the reader until dataLength is reached.
func openProgramData(r io.Reader, dataLength uint64) *programData {
pd := &programData{
cancel: make(chan struct{}),
staticLength: dataLength,
}
pd.wg.Add(1)
go func() {
defer pd.wg.Done()
pd.threadedFetchData(r)
}()
return pd
}
// threadedFetchData fetches the program's data from the underlying reader of
// the ProgramData. It will read from the reader until io.EOF is reached or
// until the maximum number of packets are read.
func (pd *programData) threadedFetchData(r io.Reader) {
var packet [1024]byte // 1kib
remainingData := int64(pd.staticLength)
quit := func(err error) {
pd.mu.Lock()
defer pd.mu.Unlock()
// Remember the error and close all open requests before stopping
// the loop.
pd.readErr = err
for _, r := range pd.requests {
close(r.c)
}
}
for remainingData > 0 {
pd.mu.Lock()
select {
case <-pd.cancel:
pd.mu.Unlock()
quit(errors.New("stop called"))
return
default:
}
pd.mu.Unlock()
// Adjust the length of the packet according to the remaining data.
d := packet[:]
if remainingData <= int64(cap(d)) {
d = d[:remainingData]
}
n, err := r.Read(d)
if err != nil {
quit(err)
return
}
remainingData -= int64(n)
pd.mu.Lock()
pd.data = append(pd.data, packet[:n]...)
// Sort the request and unlock the ones that are ready to be unlocked.
sort.Slice(pd.requests, func(i, j int) bool {
return pd.requests[i].requiredLength < pd.requests[j].requiredLength
})
for len(pd.requests) > 0 {
r := pd.requests[0]
if r.requiredLength > uint64(len(pd.data)) {
break
}
close(r.c)
pd.requests = pd.requests[1:]
}
pd.mu.Unlock()
}
}
// managedBytes tries to fetch length bytes at offset from the underlying data
// slice of the programData. If the data is not available yet, a request will be
// queued up and the method will block for the data to be read.
func (pd *programData) managedBytes(offset, length uint64) ([]byte, error) {
// Check if request is valid.
if offset+length > pd.staticLength {
return nil, fmt.Errorf("offset+length out of bounds: %v > %v", offset+length, pd.staticLength)
}
pd.mu.Lock()
// Check if data is available already.
if uint64(len(pd.data)) >= offset+length {
defer pd.mu.Unlock()
return pd.data[offset:][:length], nil
}
// Check for previous error.
if pd.readErr != nil {
defer pd.mu.Unlock()
return nil, pd.readErr
}
// If not, queue up a request.
c := make(chan struct{})
pd.requests = append(pd.requests, dataRequest{
requiredLength: offset + length,
c: c,
})
pd.mu.Unlock()
<-c
pd.mu.Lock()
defer pd.mu.Unlock()
// Check if the data is available again. It should be unless there was a
// reading error.
outOfBounds := uint64(len(pd.data)) < offset+length
if outOfBounds && pd.readErr == nil {
err := errors.New("requested data was out of bounds even though there was no readErr")
build.Critical(err)
return nil, err
} else if outOfBounds && pd.readErr != nil {
return nil, pd.readErr
}
return pd.data[offset:][:length], nil
}
// Uint64 returns the next 8 bytes at the specified offset within the program
// data as an uint64. This call will block if the data at the specified offset
// hasn't been fetched yet.
func (pd *programData) Uint64(offset uint64) (uint64, error) {
d, err := pd.managedBytes(offset, 8)
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint64(d), nil
}
// Hash returns the next crypto.HashSize bytes at the specified offset within
// the program data as a crypto.Hash. This call will block if the data at the
// specified offset hasn't been fetched yet.
func (pd *programData) Hash(offset uint64) (crypto.Hash, error) {
d, err := pd.managedBytes(offset, crypto.HashSize)
if err != nil {
return crypto.Hash{}, err
}
var h crypto.Hash
copy(h[:], d)
return h, nil
}
// SiaPublicKey reads a types.SiaPublicKey from the programData. Given an offset
// and a key length. The length includes the specifier size.
func (pd *programData) SiaPublicKey(offset, length uint64) (types.SiaPublicKey, error) {
d, err := pd.managedBytes(offset, length)
if err != nil {
return types.SiaPublicKey{}, err
}
var spk types.SiaPublicKey
err = encoding.Unmarshal(d, &spk)
return spk, err
}
// Signature returns the next crypto.SignatureSize bytes at the specified offset
// within the program data as a crypto.Signature. This call will block if the
// data at the specified offset hasn't been fetched yet.
func (pd *programData) Signature(offset uint64) (crypto.Signature, error) {
d, err := pd.managedBytes(offset, crypto.SignatureSize)
if err != nil {
return crypto.Signature{}, err
}
var sig crypto.Signature
copy(sig[:], d)
return sig, nil
}
// Bytes returns 'length' bytes from offset 'offset' from the programData.
func (pd *programData) Bytes(offset, length uint64) ([]byte, error) {
return pd.managedBytes(offset, length)
}
// Len returns the length of the program data.
func (pd *programData) Len() uint64 {
return pd.staticLength
}
// Close will stop the background thread and wait for it to return.
func (pd *programData) Close() error {
pd.mu.Lock()
close(pd.cancel)
pd.mu.Unlock()
pd.wg.Wait()
return nil
} | modules/host/mdm/programdata.go | 0.555194 | 0.482246 | programdata.go | starcoder |
package giso
import (
"image/color"
"math"
"github.com/fogleman/gg"
"github.com/teacat/noire"
)
// https://github.com/FabianTerhorst/Isometric/blob/master/lib/src/main/java/io/fabianterhorst/isometric/Isometric.java
type FilledPath struct {
*Path
fillColorHex string
}
type Isometric struct {
originX, originY float64
scale float64
angle float64
lightPosition *Vector
lightAngle *Vector
colorDifference float64
lightColor color.Color
transformation [][]float64
dc *gg.Context
paths []*FilledPath
}
func NewIsometric(width, height int, scale float64) *Isometric {
angle := math.Pi / 6
res := &Isometric{
scale: scale,
angle: angle,
colorDifference: 0.20,
lightColor: color.White,
originX: 0.5 * float64(width),
originY: 0.9 * float64(height),
dc: gg.NewContext(width, height),
paths: make([]*FilledPath, 0),
transformation: [][]float64{
{
scale * math.Cos(angle),
scale * math.Sin(angle),
},
{
scale * math.Cos(math.Pi-angle),
scale * math.Sin(math.Pi-angle),
},
},
}
res.Clear("#ffffff")
res.SetLightPosition(&Vector{2, -1, 3})
return res
}
func (iso *Isometric) Clear(fillColorHex string) {
iso.dc.SetHexColor(fillColorHex)
iso.dc.Clear()
}
func (iso *Isometric) SetLightColor(hexColor string) {
iso.lightColor = ParseHexColor(hexColor)
}
func (iso *Isometric) SetLightPosition(pos *Vector) {
iso.lightPosition = pos
iso.lightAngle = iso.lightPosition.Normalize()
}
func (iso *Isometric) AddShape(shape *Shape, hexColor string) {
paths := shape.orderedPaths()
for _, el := range paths {
iso.paths = append(iso.paths, &FilledPath{el, hexColor})
}
}
func (iso *Isometric) Render() {
for _, el := range iso.paths {
fc := iso.computeColor(el.Path, el.fillColorHex)
tp := iso.translatePath(el.Path)
iso.drawPath(tp.points, fc)
}
}
func (iso *Isometric) drawPath(points []*Point, c color.Color) {
iso.dc.Push()
iso.dc.MoveTo(points[0].x, points[0].y)
for i := 1; i < len(points); i++ {
iso.dc.LineTo(points[i].x, points[i].y)
}
iso.dc.ClosePath()
iso.dc.Push()
iso.dc.SetColor(c)
iso.dc.Fill()
iso.dc.Pop()
}
func (iso *Isometric) translatePath(pat *Path) *Path {
res := &Path{
points: make([]*Point, len(pat.points)),
}
for i, el := range pat.points {
res.points[i] = iso.translatePoint(el)
}
return res
}
func (iso *Isometric) SavePNG(filename string) error {
return iso.dc.SavePNG(filename)
}
/**
* X rides along the angle extended from the origin
* Y rides perpendicular to this angle (in isometric view: PI - angle)
* Z affects the y coordinate of the drawn point
*/
func (iso *Isometric) translatePoint(pt *Point) *Point {
xMap := Point{
pt.x * iso.transformation[0][0],
pt.x * iso.transformation[0][1],
0.0,
}
yMap := Point{
pt.y * iso.transformation[1][0],
pt.y * iso.transformation[1][1],
0.0,
}
x := iso.originX + xMap.x + yMap.x
y := iso.originY - xMap.y - yMap.y - (pt.z * iso.scale)
return &Point{x, y, 0.0}
}
func (iso *Isometric) computeColor(el *Path, source string) color.Color {
baseColor := noire.NewHex(source)
v1 := FromTwoPoints(el.points[1], el.points[0])
v2 := FromTwoPoints(el.points[2], el.points[1])
normal := CrossProduct(v1, v2)
normal = normal.Normalize()
/**
* Brightness is between -1 and 1 and is computed based
* on the dot product between the light source vector and normal.
*/
brightness := DotProduct(normal, iso.lightAngle)
res := baseColor.Lighten(brightness * iso.colorDifference).Hex()
return ParseHexColor(res)
} | isometric.go | 0.812421 | 0.514461 | isometric.go | starcoder |
Finials for pillar decorations.
*/
//-----------------------------------------------------------------------------
package main
import (
"math"
. "github.com/deadsy/sdfx/sdf"
)
//-----------------------------------------------------------------------------
func square1(l float64) SDF2 {
return Polygon2D(Nagon(4, l*math.Sqrt(0.5)))
}
func square2(l float64) SDF2 {
h := l * 0.5
r := l * 0.1
n := 5
s := NewPolygon()
s.Add(h, -h).Smooth(r, n)
s.Add(h, h).Smooth(r, n)
s.Add(-h, h).Smooth(r, n)
s.Add(-h, -h).Smooth(r, n)
s.Close()
return Polygon2D(s.Vertices())
}
//-----------------------------------------------------------------------------
func finial2() error {
base := 100.0
base_height := 20.0
column_radius := 15.0
column_height := 60.0
ball_radius := 45.0
column_ofs := (column_height + base_height) / 2
ball_ofs := (base_height / 2) + column_height + ball_radius*0.8
round := ball_radius / 5
//s0 := Offset2D(square2(base), base*0.1)
s0 := square2(base)
s1 := Circle2D(column_radius)
column_3d, err := Loft3D(s0, s1, column_height, 0)
if err != nil {
return err
}
column_3d = Transform3D(column_3d, Translate3d(V3{0, 0, column_ofs}))
ball_3d := Sphere3D(ball_radius)
ball_3d = Transform3D(ball_3d, Translate3d(V3{0, 0, ball_ofs}))
base_3d := Extrude3D(s0, base_height)
bc_3d := Union3D(column_3d, ball_3d)
bc_3d.(*UnionSDF3).SetMin(PolyMin(round))
RenderSTLSlow(Union3D(bc_3d, base_3d), 300, "f2.stl")
return err
}
//-----------------------------------------------------------------------------
func finial1() error {
base := 100.0
base_height := 20.0
column_radius := 15.0
column_height := 60.0
ball_radius := 45.0
column_ofs := (column_height + base_height) / 2
ball_ofs := (base_height / 2) + column_height + ball_radius*0.8
round := ball_radius / 5
s0 := Polygon2D(Nagon(4, base*math.Sqrt(0.5)))
s1 := Circle2D(column_radius)
column_3d, err := Loft3D(s0, s1, column_height, 0)
if err != nil {
return err
}
column_3d = Transform3D(column_3d, Translate3d(V3{0, 0, column_ofs}))
ball_3d := Sphere3D(ball_radius)
ball_3d = Transform3D(ball_3d, Translate3d(V3{0, 0, ball_ofs}))
base_3d := Extrude3D(s0, base_height)
bc_3d := Union3D(column_3d, ball_3d)
bc_3d.(*UnionSDF3).SetMin(PolyMin(round))
RenderSTLSlow(Union3D(bc_3d, base_3d), 300, "f1.stl")
return err
}
//-----------------------------------------------------------------------------
func main() {
finial1()
finial2()
}
//----------------------------------------------------------------------------- | examples/finial/main.go | 0.63477 | 0.415966 | main.go | starcoder |
package main
type (
BfWrite Handle
BfRead struct {
BytesLeft int
}
)
func (BfWrite) WriteBool(bit bool)
func (BfWrite) WriteByte(byt int)
func (BfWrite) WriteChar(chr int)
func (BfWrite) WriteShort(shrt int)
func (BfWrite) WriteWord(w int)
func (BfWrite) WriteNum(num int)
func (BfWrite) WriteFloat(num float)
func (BfWrite) WriteString(s string)
func (BfWrite) WriteEntity(ent Entity)
func (BfWrite) WriteAngle(angle float, numBits int)
func (BfWrite) WriteCoord(coord float)
func (BfWrite) WriteVecCoord(vec Vec3)
func (BfWrite) WriteVecNormal(vec Vec3)
func (BfWrite) WriteAngles(vec Vec3)
func (BfRead) ReadBool() bool
func (BfRead) ReadByte() int
func (BfRead) ReadChar() int
func (BfRead) ReadShort() int
func (BfRead) ReadWord() int
func (BfRead) ReadNum() int
func (BfRead) ReadFloat() float
func (BfRead) ReadString(buffer []char, maxlength int, line bool) int
func (BfRead) ReadEntity() Entity
func (BfRead) ReadAngle(numBits int) float
func (BfRead) ReadCoord() float
func (BfRead) ReadVecCoord(vec *Vec3)
func (BfRead) ReadVecNormal(vec *Vec3)
func (BfRead) ReadAngles(vec *Vec3)
func BfWriteBool(bf BfWrite, bit bool)
func BfWriteByte(bf BfWrite, byt int)
func BfWriteChar(bf BfWrite, chr int)
func BfWriteShort(bf BfWrite, num int)
func BfWriteWord(bf BfWrite, num int)
func BfWriteNum(bf BfWrite, num int)
func BfWriteFloat(bf BfWrite, num float)
func BfWriteString(bf BfWrite, str string)
func BfWriteEntity(bf BfWrite, ent Entity)
func BfWriteAngle(bf BfWrite, angle float, numBits int)
func BfWriteCoord(bf BfWrite, coord float)
func BfWriteVecCoord(bf BfWrite, vec Vec3)
func BfWriteVecNormal(bf BfWrite, vec Vec3)
func BfWriteAngles(bf BfWrite, vec Vec3)
func BfReadBool(bf BfRead) bool
func BfReadByte(bf BfRead) int
func BfReadChar(bf BfRead) int
func BfReadShort(bf BfRead) int
func BfReadWord(bf BfRead) int
func BfReadNum(bf BfRead) int
func BfReadFloat(bf BfRead) float
func BfReadString(bf BfRead, buffer []char, maxlength int, line bool) int
func BfReadEntity(bf BfRead) int
func BfReadAngle(bf BfRead, numBits int) float
func BfReadCoord(bf BfRead) float
func BfReadVecCoord(bf BfRead, vec *Vec3)
func BfReadVecNormal(bf BfRead, vec *Vec3)
func BfReadAngles(bf BfRead, vec *Vec3)
func BfGetNumBytesLeft(bf BfRead) int | sourcemod/bitbuffer.go | 0.780579 | 0.49939 | bitbuffer.go | starcoder |
package main
import (
"strings"
"time"
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
dns "github.com/miekg/dns"
cdns "github.com/niclabs/dnszeppelin"
)
/*
From:
Detecting Anomalies at a TLD Name Server Based on DNS Traffic Predictions
<NAME>, <NAME>, <NAME>, <NAME>,
and <NAME>
IEEE Transactions on Network and Service Management (IEEE TNSM) Journal
Given the aforementioned, our proposed AD-BoP method
is focused on the following nine DNS traffic features:
• Number of DNS queries of types A (1), AAAA (2), NS
(3), MX (4), and ANY (5).
• Number of unique queried domains (6).
• Number of DNS response packets with codes NXDOMAIN
(7) and NOERROR (8).
• Total number of DNS packets (9).
*/
type maps struct {
fields map[string]int
sources map[string]int
domains map[string]int
responses map[int]int
filter map[string][]float64
}
func InfluxAgg(batch []cdns.DNSResult, m *maps) error {
m.fields = make(map[string]int)
m.sources = make(map[string]int)
m.domains = make(map[string]int)
m.responses = make(map[int]int)
if len(batch) == 0 {
return nil
}
m.fields["TOTALQ"] = 0
m.fields["TOTALR"] = 0
for _, b := range batch {
ip := b.SrcIP.String()
if b.DNS.Response {
m.fields["TOTALR"] = 1 + m.fields["TOTALR"]
m.responses[b.DNS.Rcode] = 1 + m.responses[b.DNS.Rcode]
} else {
m.fields["TOTALQ"] = 1 + m.fields["TOTALQ"]
for _, d := range b.DNS.Question {
qt := dns.TypeToString[d.Qtype]
name := strings.ToLower(d.Name)
m.domains[name] = 1 + m.domains[name]
m.sources[ip] = 1 + m.sources[ip]
m.fields[qt] = 1 + m.fields[qt]
}
}
}
// Adding some stats
m.fields["NOERROR"] = m.responses[0]
m.fields["NXDOMAIN"] = m.responses[3]
m.fields["UNIQUERY"] = len(m.domains)
for key := range m.fields {
if len(key) >= 5 && key[0:5] == "TREND" || len(key) >= 5 && key[0:5] == "ERROR" {
continue
}
emafilter(m, 5, key)
}
return nil
}
//filter and error
func emafilter(m *maps, number int, ttype string) error {
var k float64 = 2 / (float64(number) + 1)
if m.filter["DATA"+ttype] == nil {
m.filter["DATA"+ttype] = make([]float64, 0, number+1)
}
if len(m.filter["DATA"+ttype]) > number {
step := Emastep(k, float64(m.fields[ttype]), m.filter[ttype][0])
m.filter[ttype][0] = step
m.fields["TREND"+ttype] = int(step)
errorp := Errorfunc(m.fields[ttype], m.fields["TREND"+ttype])
m.fields["ERROR"+ttype] = errorp
} else if len(m.filter["DATA"+ttype]) == number {
m.filter["DATA"+ttype] = append(m.filter["DATA"+ttype], float64(m.fields[ttype]))
filtered := Ema(number, m.filter["DATA"+ttype])
m.filter[ttype] = []float64{filtered[len(filtered)-1]}
m.fields["TREND"+ttype] = int(m.filter[ttype][0])
} else {
m.filter["DATA"+ttype] = append(m.filter["DATA"+ttype], float64(m.fields[ttype]))
}
return nil
}
func (d database) InfluxStore(m *maps, batch []cdns.DNSResult) error {
if len(batch) == 0 {
return nil
}
now := time.Now()
defer d.api.Flush()
// Store TNSM stats
go d.StoreEachMap(m.fields, "stat", "type", now)
// Store also sources
go d.StoreEachMap(m.sources, "source", "ip", now)
// Store domain names
go d.StoreEachMap(m.domains, "domain", "qname", now)
return nil
}
func (d database) StoreEachMap(mapa map[string]int, metric, field string, now time.Time) {
for k, v := range mapa {
p := influxdb2.NewPoint(metric,
map[string]string{field: k},
map[string]interface{}{"freq": v},
now)
d.api.WritePoint(p)
}
} | stats_influx.go | 0.559771 | 0.420005 | stats_influx.go | starcoder |
package txqr
import (
"fmt"
"math/rand"
"strings"
fountain "github.com/google/gofountain"
)
// Decoder represents protocol decode.
type Decoder struct {
chunkLen int
codec fountain.Codec
fd fountain.Decoder
completed bool
total int
cache map[string]struct{}
}
// NewDecoder creates and inits a new decoder.
func NewDecoder() *Decoder {
return &Decoder{
cache: make(map[string]struct{}),
}
}
// NewDecoderSize creates and inits a new decoder for the known size.
func NewDecoderSize(size, chunkLen int) *Decoder {
numChunks := numberOfChunks(size, chunkLen)
codec := fountain.NewLubyCodec(numChunks, rand.New(fountain.NewMersenneTwister(200)), solitonDistribution(numChunks))
return &Decoder{
codec: codec,
fd: codec.NewDecoder(size),
total: size,
chunkLen: chunkLen,
cache: make(map[string]struct{}),
}
}
// Decode takes a single chunk of data and decodes it.
// Chunk expected to be validated (see Validate) before.
func (d *Decoder) Decode(chunk string) error {
idx := strings.IndexByte(chunk, '|') // expected to be validated before
if idx == -1 {
return fmt.Errorf("invalid frame: \"%s\"", chunk)
}
header := chunk[:idx]
// continuous QR reading often sends the same chunk in a row, skip it
if d.isCached(header) {
return nil
}
var (
blockCode int64
chunkLen, total int
)
_, err := fmt.Sscanf(header, "%d/%d/%d", &blockCode, &chunkLen, &total)
if err != nil {
return fmt.Errorf("invalid header: %v (%s)", err, header)
}
payload := chunk[idx+1:]
lubyBlock := fountain.LTBlock{
BlockCode: blockCode,
Data: []byte(payload),
}
if d.fd == nil {
d.total = total
d.chunkLen = chunkLen
numChunks := numberOfChunks(d.total, d.chunkLen)
d.codec = fountain.NewLubyCodec(numChunks, rand.New(fountain.NewMersenneTwister(200)), solitonDistribution(numChunks))
d.fd = d.codec.NewDecoder(total)
}
d.completed = d.fd.AddBlocks([]fountain.LTBlock{lubyBlock})
return nil
}
// Validate checks if a given chunk of data is a valid txqr protocol packet.
func (d *Decoder) Validate(chunk string) error {
if chunk == "" || len(chunk) < 4 {
return fmt.Errorf("invalid frame: \"%s\"", chunk)
}
idx := strings.IndexByte(chunk, '|')
if idx == -1 {
return fmt.Errorf("invalid frame: \"%s\"", chunk)
}
return nil
}
// Data returns decoded data.
func (d *Decoder) Data() string {
return string(d.DataBytes())
}
// DataBytes returns decoded data as a byte slice.
func (d *Decoder) DataBytes() []byte {
if d.fd == nil {
return []byte{}
}
if !d.completed {
return []byte{}
}
return d.fd.Decode()
}
// Length returns length of the decoded data.
// TODO: remove
func (d *Decoder) Length() int {
return 0
}
// Read returns amount of currently read bytes.
// TODO: remove
func (d *Decoder) Read() int {
return 0
}
// Total returns total amount of data.
func (d *Decoder) Total() int {
return d.total
}
// IsCompleted reports whether the read was completed successfully or not.
func (d *Decoder) IsCompleted() bool {
return d.completed
}
// Reset resets decoder, preparing it for the next run.
func (d *Decoder) Reset() {
d.fd = nil
d.completed = false
d.chunkLen = 0
d.total = 0
d.cache = map[string]struct{}{}
d.codec = nil
}
// isCached takes the header of chunk data and see if it's been cached.
// If not, it caches it.
func (d *Decoder) isCached(header string) bool {
if _, ok := d.cache[header]; ok {
return true
}
// cache it
d.cache[header] = struct{}{}
return false
} | decode.go | 0.654453 | 0.484075 | decode.go | starcoder |
package toscalib
import (
"io/ioutil"
"os"
"path/filepath"
"reflect"
)
// Original source:
// https://gist.github.com/hvoecking/10772475
// There is an implied assumption that all attributes on a Struct are exported.
// For toscalib that will be the case so that assumption should work for us.
func _deepClone(to, from reflect.Value) {
switch from.Kind() {
// The first cases handle nested structures and translate them recursively
// If it is a pointer we need to unwrap and call once again
case reflect.Ptr:
// To get the actual value of the from we have to call Elem()
// At the same time this unwraps the pointer so we don't end up in
// an infinite recursion
fromValue := from.Elem()
// Check if the pointer is nil
if !fromValue.IsValid() {
return
}
// Allocate a new object and set the pointer to it
to.Set(reflect.New(fromValue.Type()))
// Unwrap the newly created pointer
_deepClone(to.Elem(), fromValue)
// If it is an interface (which is very similar to a pointer), do basically the
// same as for the pointer. Though a pointer is not the same as an interface so
// note that we have to call Elem() after creating a new object because otherwise
// we would end up with an actual pointer
case reflect.Interface:
// Get rid of the wrapping interface
fromValue := from.Elem()
if !fromValue.IsValid() {
return
}
// Create a new object. Now new gives us a pointer, but we want the value it
// points to, so we have to call Elem() to unwrap it
toValue := reflect.New(fromValue.Type()).Elem()
_deepClone(toValue, fromValue)
to.Set(toValue)
// If it is a struct we translate each field
case reflect.Struct:
for i := 0; i < from.NumField(); i++ {
_deepClone(to.Field(i), from.Field(i))
}
// If it is a slice we create a new slice and translate each element
case reflect.Slice:
if from.IsNil() {
return
}
to.Set(reflect.MakeSlice(from.Type(), from.Len(), from.Cap()))
for i := 0; i < from.Len(); i++ {
_deepClone(to.Index(i), from.Index(i))
}
// If it is a map we create a new map and translate each value
case reflect.Map:
if from.IsNil() {
return
}
to.Set(reflect.MakeMap(from.Type()))
for _, key := range from.MapKeys() {
fromValue := from.MapIndex(key)
// New gives us a pointer, but again we want the value
toValue := reflect.New(fromValue.Type()).Elem()
_deepClone(toValue, fromValue)
to.SetMapIndex(key, toValue)
}
// And everything else will simply be taken from the from
default:
to.Set(from)
}
}
func clone(obj interface{}) interface{} {
// Wrap the from in a reflect.Value
from := reflect.ValueOf(obj)
to := reflect.New(from.Type()).Elem()
_deepClone(to, from)
// Remove the reflection wrapper
return to.Interface()
}
func get(k int, list []interface{}) string {
if len(list) <= k {
return ""
}
if v, ok := list[k].(string); ok {
return v
}
return ""
}
func remainder(k int, list []interface{}) []interface{} {
if len(list) <= k {
return make([]interface{}, 0)
}
return list[k+1:]
}
func copyFile(src, destDir string) (string, error) {
absSrc, err := filepath.Abs(src)
if err != nil {
return "", err
}
srcFilename := filepath.Base(absSrc)
dest, err := filepath.Abs(filepath.Join(destDir, srcFilename))
if err != nil {
return "", err
}
data, err := ioutil.ReadFile(absSrc)
if err != nil {
return "", err
}
// Write data to dst
err = ioutil.WriteFile(dest, data, 0644)
if err != nil {
return "", err
}
return dest, nil
}
func isAbsLocalPath(location string) bool {
if filepath.IsAbs(location) {
_, err := os.Stat(location)
return !os.IsNotExist(err)
}
return false
} | utils.go | 0.601945 | 0.422266 | utils.go | starcoder |
package main
import (
"log"
"math/rand"
"sync"
)
const (
// JumpAITries contains the number of iterations JumpAI uses to find a jump
JumpAITries = 100
)
const (
jumpAIprogressNormal = iota
jumpAIprogressJump
jumpAIprogressCrash
)
type jumpAIRevert struct {
X, Y, Speed, stepCounter int
Direction string
Cells []struct{ X, Y int }
}
// JumpAI tries to find a possible jump and then tries to execute it if possible. If no jump is found, it behaves like RandomAI.
type JumpAI struct {
l sync.Mutex
i chan string
plan []string
r *rand.Rand
}
// GetChannel receives the answer channel.
func (j *JumpAI) GetChannel(c chan string) {
j.l.Lock()
defer j.l.Unlock()
j.i = c
}
// GetState gets the game state and computes an answer.
func (j *JumpAI) GetState(g *Game) {
j.l.Lock()
defer j.l.Unlock()
if j.i == nil {
return
}
if g.Running && g.Players[g.You].Active {
// Fill potential dead zones
for k := range g.Players {
if k == g.You {
continue
}
if !g.Players[k].Active {
continue
}
for i := 1; i <= g.Players[k].Speed+1; i++ {
x, y := g.Players[k].X+i, g.Players[k].Y
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
x, y = g.Players[k].X-i, g.Players[k].Y
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
x, y = g.Players[k].X, g.Players[k].Y+i
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
x, y = g.Players[k].X, g.Players[k].Y-i
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
}
}
if len(j.plan) != 0 {
if !j.executePlan(g, j.plan) {
j.plan = nil
}
}
if len(j.plan) == 0 {
if j.r == nil {
j.r = rand.New(rand.NewSource(rand.Int63()))
}
length := HolesEachStep - (g.Players[g.You].stepCounter % HolesEachStep)
// Try finding jump
j.plan = j.findPlan(length, g.PublicCopy())
if len(j.plan) == 0 {
// Try finding 1 step - reuse RandomAI
c := make(chan string, 1)
ai := RandomAI{}
ai.GetChannel(c)
ai.GetState(g)
j.plan = []string{<-c}
}
}
action := j.plan[0]
j.plan = j.plan[1:]
j.i <- action
}
}
// Name returns the name of the AI.
func (j *JumpAI) Name() string {
return "JumpAI"
}
// findPlan will try to find a plan containing a jump with a maximum of length steps.
// Function will return nil if no plan is found.
// Not safe for concurrent use.
func (j *JumpAI) findPlan(length int, g *Game) []string {
length--
if length < 0 {
return nil
}
actions := []string{ActionTurnLeft, ActionTurnRight, ActionSlower, ActionFaster, ActionNOOP}
j.r.Shuffle(len(actions), func(i, j int) { actions[i], actions[j] = actions[j], actions[i] })
for i := range actions {
result, revert := j.progress(g, g.You, actions[i])
switch result {
case jumpAIprogressCrash:
j.revert(g, g.You, revert)
continue
case jumpAIprogressNormal:
plan := j.findPlan(length, g)
j.revert(g, g.You, revert)
if plan == nil {
continue
}
plan = append([]string{actions[i]}, plan...)
return plan
case jumpAIprogressJump:
j.revert(g, g.You, revert)
return []string{actions[i]}
}
}
return nil
}
// progress will progress the game by one step and return the result.
// Not safe for concurrent use on the same game.
func (j *JumpAI) progress(g *Game, player int, command string) (int, jumpAIRevert) {
p := g.Players[player]
r := jumpAIRevert{
X: p.X,
Y: p.Y,
Speed: p.Speed,
stepCounter: p.stepCounter,
Direction: p.Direction,
Cells: make([]struct{ X, Y int }, 0, p.Speed),
}
jump := false
switch command {
case ActionTurnLeft:
switch p.Direction {
case DirectionLeft:
p.Direction = DirectionDown
case DirectionRight:
p.Direction = DirectionUp
case DirectionUp:
p.Direction = DirectionLeft
case DirectionDown:
p.Direction = DirectionRight
}
case ActionTurnRight:
switch p.Direction {
case DirectionLeft:
p.Direction = DirectionUp
case DirectionRight:
p.Direction = DirectionDown
case DirectionUp:
p.Direction = DirectionRight
case DirectionDown:
p.Direction = DirectionLeft
}
case ActionFaster:
p.Speed++
if p.Speed > MaxSpeed {
return jumpAIprogressCrash, r
}
case ActionSlower:
p.Speed--
if p.Speed < 1 {
return jumpAIprogressCrash, r
}
case ActionNOOP:
// Do nothing
default:
log.Println("jump ai:", "unknown action", command)
}
var dostep func(x, y int) (int, int)
switch p.Direction {
case DirectionUp:
dostep = func(x, y int) (int, int) { return x, y - 1 }
case DirectionDown:
dostep = func(x, y int) (int, int) { return x, y + 1 }
case DirectionLeft:
dostep = func(x, y int) (int, int) { return x - 1, y }
case DirectionRight:
dostep = func(x, y int) (int, int) { return x + 1, y }
}
p.stepCounter++
for s := 0; s < p.Speed; s++ {
p.X, p.Y = dostep(p.X, p.Y)
if p.X < 0 || p.X >= g.Width || p.Y < 0 || p.Y >= g.Height {
return jumpAIprogressCrash, r
}
if p.Speed >= HoleSpeed && p.stepCounter%HolesEachStep == 0 && s != 0 && s != p.Speed-1 {
if g.Cells[p.Y][p.X] != 0 {
jump = true
}
continue
}
if g.Cells[p.Y][p.X] != 0 {
return jumpAIprogressCrash, r
}
r.Cells = append(r.Cells, struct{ X, Y int }{p.X, p.Y})
g.Cells[p.Y][p.X] = -33
}
if jump {
return jumpAIprogressJump, r
}
return jumpAIprogressNormal, r
}
// revert reverts the game state by the revert struct.
// Not safe for cocurrent use on the same game.
func (j *JumpAI) revert(g *Game, player int, r jumpAIRevert) {
p := g.Players[player]
p.X = r.X
p.Y = r.Y
p.Speed = r.Speed
p.stepCounter = r.stepCounter
p.Direction = r.Direction
for i := range r.Cells {
g.Cells[r.Cells[i].Y][r.Cells[i].X] = 0
}
}
// executePlan returns true if given plan jumps over SOMETHING.
// It is not safe for concurrent usage on the same game, however it will revert the game to the initial state given to the function.
func (j *JumpAI) executePlan(g *Game, plan []string) bool {
revert := make([]struct{ X, Y int }, 0, 60)
defer func() {
// Revert cells
for i := range revert {
g.Cells[revert[i].Y][revert[i].X] = 0
}
}()
sc := g.Players[g.You].stepCounter
direction := g.Players[g.You].Direction
speed := g.Players[g.You].Speed
x, y := g.Players[g.You].X, g.Players[g.You].Y
// Execute plan
jump := false
for i := range plan {
switch plan[i] {
case ActionTurnLeft:
switch direction {
case DirectionLeft:
direction = DirectionDown
case DirectionRight:
direction = DirectionUp
case DirectionUp:
direction = DirectionLeft
case DirectionDown:
direction = DirectionRight
}
case ActionTurnRight:
switch direction {
case DirectionLeft:
direction = DirectionUp
case DirectionRight:
direction = DirectionDown
case DirectionUp:
direction = DirectionRight
case DirectionDown:
direction = DirectionLeft
}
case ActionFaster:
speed++
if speed > MaxSpeed {
return false
}
case ActionSlower:
speed--
if speed < 1 {
return false
}
case ActionNOOP:
// Do nothing
default:
log.Println("jump ai:", "unknown action", plan[i])
}
var dostep func(x, y int) (int, int)
switch direction {
case DirectionUp:
dostep = func(x, y int) (int, int) { return x, y - 1 }
case DirectionDown:
dostep = func(x, y int) (int, int) { return x, y + 1 }
case DirectionLeft:
dostep = func(x, y int) (int, int) { return x - 1, y }
case DirectionRight:
dostep = func(x, y int) (int, int) { return x + 1, y }
}
sc++
for s := 0; s < speed; s++ {
x, y = dostep(x, y)
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
return false
}
if speed >= HoleSpeed && sc%HolesEachStep == 0 && s != 0 && s != speed-1 {
if g.Cells[y][x] != 0 {
jump = true
}
continue
}
if g.Cells[y][x] != 0 {
return false
}
g.Cells[y][x] = -33
revert = append(revert, struct{ X, Y int }{x, y})
}
}
return jump
} | ai_jump.go | 0.529507 | 0.444806 | ai_jump.go | starcoder |
package rateengine
import (
"github.com/transcom/mymove/pkg/unit"
)
type pricer interface {
price(rate unit.Cents, q1 unit.BaseQuantity, discount *unit.DiscountRate) unit.Cents
}
// Basic pricer, multiplies the rate against the provided quantity
type basicQuantityPricer struct{}
func newBasicQuantityPricer() basicQuantityPricer {
return basicQuantityPricer{}
}
func (m basicQuantityPricer) price(rate unit.Cents, q1 unit.BaseQuantity, discount *unit.DiscountRate) unit.Cents {
calculatedRate := rate.MultiplyFloat64(q1.ToUnitFloat())
if discount != nil {
calculatedRate = discount.Apply(calculatedRate)
}
return calculatedRate
}
// Like the basic pricer, but enforces a minimum value for the quantity
type minimumQuantityPricer struct {
min int
}
func newMinimumQuantityPricer(min int) minimumQuantityPricer {
return minimumQuantityPricer{min}
}
func (m minimumQuantityPricer) price(rate unit.Cents, q1 unit.BaseQuantity, discount *unit.DiscountRate) unit.Cents {
if qConv := q1.ToUnitFloat(); qConv < float64(m.min) {
q1 = unit.BaseQuantityFromInt(m.min)
}
calculatedRate := rate.MultiplyFloat64(q1.ToUnitFloat())
if discount != nil {
calculatedRate = discount.Apply(calculatedRate)
}
return calculatedRate
}
// Line the min quantity pricer, but multiplies rate by quantity / 100
type minimumQuantityHundredweightPricer struct {
min int
}
func newMinimumQuantityHundredweightPricer(min int) minimumQuantityHundredweightPricer {
return minimumQuantityHundredweightPricer{min}
}
func (m minimumQuantityHundredweightPricer) price(rate unit.Cents, q1 unit.BaseQuantity, discount *unit.DiscountRate) unit.Cents {
if qConv := q1.ToUnitFloat(); qConv < float64(m.min) {
q1 = unit.BaseQuantityFromInt(m.min)
}
calculatedRate := rate.MultiplyFloat64(q1.ToUnitFloat() / 100.0)
if discount != nil {
calculatedRate = discount.Apply(calculatedRate)
}
return calculatedRate
}
// Ignores quantity, just returns rate with discount applied
type flatRatePricer struct{}
func newFlatRatePricer() flatRatePricer {
return flatRatePricer{}
}
func (m flatRatePricer) price(rate unit.Cents, q1 unit.BaseQuantity, discount *unit.DiscountRate) unit.Cents {
calculatedRate := rate
if discount != nil {
calculatedRate = discount.Apply(calculatedRate)
}
return calculatedRate
} | pkg/rateengine/pricers.go | 0.823435 | 0.617426 | pricers.go | starcoder |
package unary
import (
"fmt"
"github.com/matrixorigin/matrixone/pkg/container/nulls"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/vectorize/space"
"github.com/matrixorigin/matrixone/pkg/vm/process"
"golang.org/x/exp/constraints"
)
var (
errorSpaceCountExceedsThreshold = fmt.Errorf("total space count exceeds %d MB", space.TotalMaximumSpaceCount/1024/1024)
)
// the function registeration for generics functions may have some problem now, change this to generics later
func SpaceInt64(vectors []*vector.Vector, proc *process.Process) (*vector.Vector, error) {
inputVector := vectors[0]
resultType := types.Type{Oid: types.T_varchar, Size: 24}
inputValues := vector.MustTCols[int64](inputVector)
if inputVector.IsScalar() {
if inputVector.ConstVectorIsNull() {
return proc.AllocScalarNullVector(resultType), nil
}
resultVector := vector.NewConst(resultType)
bytesNeed := space.CountSpacesSigned(inputValues)
if bytesNeed < 0 {
return nil, errorSpaceCountExceedsThreshold
}
results := &types.Bytes{
Data: make([]byte, bytesNeed),
Offsets: make([]uint32, 1),
Lengths: make([]uint32, 1),
}
result := space.FillSpacesSigned[int64](inputValues, results)
nulls.Or(inputVector.Nsp, result.Nsp, resultVector.Nsp)
vector.SetCol(resultVector, result.Result)
return resultVector, nil
}
bytesNeed := space.CountSpacesSigned(inputValues)
if bytesNeed < 0 {
return nil, errorSpaceCountExceedsThreshold
}
resultVector, err := proc.AllocVector(resultType, bytesNeed)
if err != nil {
return nil, err
}
resultValues := &types.Bytes{
Data: resultVector.Data,
Offsets: make([]uint32, len(inputValues)),
Lengths: make([]uint32, len(inputValues)),
}
result := space.FillSpacesSigned[int64](inputValues, resultValues)
nulls.Or(inputVector.Nsp, result.Nsp, resultVector.Nsp)
vector.SetCol(resultVector, result.Result)
return resultVector, nil
}
func SpaceUint64(vectors []*vector.Vector, proc *process.Process) (*vector.Vector, error) {
inputVector := vectors[0]
resultType := types.Type{Oid: types.T_varchar, Size: 24}
inputValues := vector.MustTCols[uint64](inputVector)
if inputVector.IsScalar() {
if inputVector.ConstVectorIsNull() {
return proc.AllocScalarNullVector(resultType), nil
}
resultVector := vector.NewConst(resultType)
bytesNeed := space.CountSpacesUnsigned[uint64](inputValues)
if bytesNeed < 0 {
return nil, errorSpaceCountExceedsThreshold
}
results := &types.Bytes{
Data: make([]byte, bytesNeed),
Offsets: make([]uint32, 1),
Lengths: make([]uint32, 1),
}
result := space.FillSpacesUnsigned[uint64](inputValues, results)
nulls.Or(inputVector.Nsp, result.Nsp, resultVector.Nsp)
vector.SetCol(resultVector, result.Result)
return resultVector, nil
}
bytesNeed := space.CountSpacesUnsigned[uint64](inputValues)
if bytesNeed < 0 {
return nil, errorSpaceCountExceedsThreshold
}
resultVector, err := proc.AllocVector(resultType, bytesNeed)
if err != nil {
return nil, err
}
resultValues := &types.Bytes{
Data: resultVector.Data,
Offsets: make([]uint32, len(inputValues)),
Lengths: make([]uint32, len(inputValues)),
}
result := space.FillSpacesUnsigned[uint64](inputValues, resultValues)
nulls.Or(inputVector.Nsp, result.Nsp, resultVector.Nsp)
vector.SetCol(resultVector, result.Result)
return resultVector, nil
}
func SpaceFloat[T constraints.Float](vectors []*vector.Vector, proc *process.Process) (*vector.Vector, error) {
inputVector := vectors[0]
resultType := types.Type{Oid: types.T_varchar, Size: 24}
inputValues := vector.MustTCols[T](inputVector)
if inputVector.IsScalar() {
if inputVector.ConstVectorIsNull() {
return proc.AllocScalarNullVector(resultType), nil
}
resultVector := vector.NewConst(resultType)
bytesNeed := space.CountSpacesFloat[T](inputValues)
if bytesNeed < 0 {
return nil, errorSpaceCountExceedsThreshold
}
results := &types.Bytes{
Data: make([]byte, bytesNeed),
Offsets: make([]uint32, 1),
Lengths: make([]uint32, 1),
}
result := space.FillSpacesFloat[T](inputValues, results)
nulls.Or(inputVector.Nsp, result.Nsp, resultVector.Nsp)
vector.SetCol(resultVector, result.Result)
return resultVector, nil
}
bytesNeed := space.CountSpacesFloat[T](inputValues)
if bytesNeed < 0 {
return nil, errorSpaceCountExceedsThreshold
}
resultVector, err := proc.AllocVector(resultType, bytesNeed)
if err != nil {
return nil, err
}
resultValues := &types.Bytes{
Data: resultVector.Data,
Offsets: make([]uint32, len(inputValues)),
Lengths: make([]uint32, len(inputValues)),
}
result := space.FillSpacesFloat[T](inputValues, resultValues)
nulls.Or(inputVector.Nsp, result.Nsp, resultVector.Nsp)
vector.SetCol(resultVector, result.Result)
return resultVector, nil
} | pkg/sql/plan2/function/builtin/unary/space.go | 0.570451 | 0.626081 | space.go | starcoder |
package main
import (
"fmt"
"log"
"os/exec"
"strings"
"time"
"strconv"
)
func getNextMonth(t time.Time) string {
// Determine the first of the next month after t.
firstOfNextMonth := t.AddDate(0,1,-(t.Day()-1))
// Get the string representation of the month number.
return strconv.Itoa(int(firstOfNextMonth.Month()))
}
func getMonthAndDay(s string) string {
if(len(s) < 7) {
log.Fatal("getMonthAndDay called with too short string!")
}
return s[0:6]
}
func main() {
// We get the output of cal. These will be printed on the left side, showing
// an overview of the next two months.
curMonth, err := exec.Command("cal").Output()
if err != nil {
log.Fatal(err)
}
// We get the output of cal for next month. This will be printed on the left
// side, below the current month.
nextMonthI := getNextMonth(time.Now())
nextMonth, err := exec.Command("ncal", "-bMm " + nextMonthI).Output()
if err != nil {
log.Fatal(err)
}
// We get the tasks for today and tomorrow. These will be printed on the
// right side.
taskOutput, err := exec.Command("calendar", "-A 2").Output()
if err != nil {
log.Fatal(err)
}
// Now we compose the left hand side into a string array ready to be
// printed.
months := string(curMonth) + string(nextMonth)
monthLines := strings.Split(strings.TrimSuffix(months, "\n"), "\n")
monthLineCount := len(monthLines)
tasks := string(taskOutput)
taskLines := strings.Split(strings.TrimSuffix(tasks, "\n"), "\n")
// The lines look like "Jan 18 XXXXXXX". We determine what the first
// letters look like in the first line, "MON DD", and when this string
// changes, we know that we've progressed to tomorrow.
today := getMonthAndDay(taskLines[0])
taskLinesf := []string{"Today:"}
// We haven't added the header for tomorrow yet.
missingHeader := true
for i := range taskLines[1:] {
md := getMonthAndDay(taskLines[i])
// We only want to add the heading once, thus we use a boolean flag
// to indicate, that we've added the header.
if(md != today && missingHeader) {
taskLinesf = append(taskLinesf, "")
taskLinesf = append(taskLinesf, "Tomorrow:")
missingHeader = false
}
// We skip the first 8 characters, since we're not interested in the
// month and date, when showing the task.
taskLinesf = append(taskLinesf, taskLines[i][8:])
}
// Ensure that there are at least as many task lines, as month lines.
for len(taskLinesf) < monthLineCount {
taskLinesf = append(taskLinesf, "")
}
// Since there are an equal amount of lines, we can use a single index to
// print both arrays.
for i, _ := range monthLines {
fmt.Printf("%s %s\n", monthLines[i], taskLinesf[i])
}
} | khal.go | 0.649356 | 0.487429 | khal.go | starcoder |
package prototests
import (
"bytes"
)
// deriveEqualSimple returns whether this and that are equal.
func deriveEqualSimple(this, that *Simple) bool {
return (this == nil && that == nil) ||
this != nil && that != nil &&
((this.Field1 == nil && that.Field1 == nil) || (this.Field1 != nil && that.Field1 != nil && *(this.Field1) == *(that.Field1))) &&
((this.Field2 == nil && that.Field2 == nil) || (this.Field2 != nil && that.Field2 != nil && *(this.Field2) == *(that.Field2))) &&
((this.Field3 == nil && that.Field3 == nil) || (this.Field3 != nil && that.Field3 != nil && *(this.Field3) == *(that.Field3))) &&
((this.Field4 == nil && that.Field4 == nil) || (this.Field4 != nil && that.Field4 != nil && *(this.Field4) == *(that.Field4))) &&
((this.Field5 == nil && that.Field5 == nil) || (this.Field5 != nil && that.Field5 != nil && *(this.Field5) == *(that.Field5))) &&
((this.Field6 == nil && that.Field6 == nil) || (this.Field6 != nil && that.Field6 != nil && *(this.Field6) == *(that.Field6))) &&
((this.Field7 == nil && that.Field7 == nil) || (this.Field7 != nil && that.Field7 != nil && *(this.Field7) == *(that.Field7))) &&
((this.Field8 == nil && that.Field8 == nil) || (this.Field8 != nil && that.Field8 != nil && *(this.Field8) == *(that.Field8))) &&
((this.Field9 == nil && that.Field9 == nil) || (this.Field9 != nil && that.Field9 != nil && *(this.Field9) == *(that.Field9))) &&
((this.Field10 == nil && that.Field10 == nil) || (this.Field10 != nil && that.Field10 != nil && *(this.Field10) == *(that.Field10))) &&
((this.Field11 == nil && that.Field11 == nil) || (this.Field11 != nil && that.Field11 != nil && *(this.Field11) == *(that.Field11))) &&
((this.Field12 == nil && that.Field12 == nil) || (this.Field12 != nil && that.Field12 != nil && *(this.Field12) == *(that.Field12))) &&
((this.Field13 == nil && that.Field13 == nil) || (this.Field13 != nil && that.Field13 != nil && *(this.Field13) == *(that.Field13))) &&
((this.Field14 == nil && that.Field14 == nil) || (this.Field14 != nil && that.Field14 != nil && *(this.Field14) == *(that.Field14))) &&
bytes.Equal(this.Field15, that.Field15) &&
deriveEqual(this.Fields1, that.Fields1) &&
deriveEqual_(this.Fields2, that.Fields2) &&
deriveEqual_1(this.Fields3, that.Fields3) &&
deriveEqual_2(this.Fields4, that.Fields4) &&
deriveEqual_3(this.Fields5, that.Fields5) &&
deriveEqual_4(this.Fields6, that.Fields6) &&
deriveEqual_1(this.Fields7, that.Fields7) &&
deriveEqual_2(this.Fields8, that.Fields8) &&
deriveEqual_3(this.Fields9, that.Fields9) &&
deriveEqual_1(this.Fields10, that.Fields10) &&
deriveEqual_4(this.Fields11, that.Fields11) &&
deriveEqual_2(this.Fields12, that.Fields12) &&
deriveEqual_5(this.Fields13, that.Fields13) &&
deriveEqual_6(this.Fields14, that.Fields14) &&
deriveEqual_7(this.Fields15, that.Fields15) &&
bytes.Equal(this.XXX_unrecognized, that.XXX_unrecognized)
}
// deriveEqualNested returns whether this and that are equal.
func deriveEqualNested(this, that *Nested) bool {
return (this == nil && that == nil) ||
this != nil && that != nil &&
this.One.Equal(that.One) &&
deriveEqual_8(this.Many, that.Many) &&
bytes.Equal(this.XXX_unrecognized, that.XXX_unrecognized)
}
// deriveEqual returns whether this and that are equal.
func deriveEqual(this, that []float64) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_ returns whether this and that are equal.
func deriveEqual_(this, that []float32) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_1 returns whether this and that are equal.
func deriveEqual_1(this, that []int32) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_2 returns whether this and that are equal.
func deriveEqual_2(this, that []int64) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_3 returns whether this and that are equal.
func deriveEqual_3(this, that []uint32) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_4 returns whether this and that are equal.
func deriveEqual_4(this, that []uint64) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_5 returns whether this and that are equal.
func deriveEqual_5(this, that []bool) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_6 returns whether this and that are equal.
func deriveEqual_6(this, that []string) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i] == that[i]) {
return false
}
}
return true
}
// deriveEqual_7 returns whether this and that are equal.
func deriveEqual_7(this, that [][]byte) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(bytes.Equal(this[i], that[i])) {
return false
}
}
return true
}
// deriveEqual_8 returns whether this and that are equal.
func deriveEqual_8(this, that []*Simple) bool {
if this == nil || that == nil {
return this == nil && that == nil
}
if len(this) != len(that) {
return false
}
for i := 0; i < len(this); i++ {
if !(this[i].Equal(that[i])) {
return false
}
}
return true
} | encode/proto/prototests/derived.gen.go | 0.622115 | 0.528047 | derived.gen.go | starcoder |
package insight
import (
"fmt"
"time"
"github.com/pipe-cd/pipe/pkg/model"
)
// deploy frequency
// DeployFrequencyChunk represents a chunk of DeployFrequency data points.
type DeployFrequencyChunk struct {
AccumulatedTo int64 `json:"accumulated_to"`
DataPoints DeployFrequencyDataPoint `json:"data_points"`
FilePath string
}
type DeployFrequencyDataPoint struct {
Daily []*DeployFrequency `json:"daily"`
Weekly []*DeployFrequency `json:"weekly"`
Monthly []*DeployFrequency `json:"monthly"`
Yearly []*DeployFrequency `json:"yearly"`
}
func (c *DeployFrequencyChunk) GetFilePath() string {
return c.FilePath
}
func (c *DeployFrequencyChunk) SetFilePath(path string) {
c.FilePath = path
}
func (c *DeployFrequencyChunk) GetAccumulatedTo() int64 {
return c.AccumulatedTo
}
func (c *DeployFrequencyChunk) SetAccumulatedTo(a int64) {
c.AccumulatedTo = a
}
func (c *DeployFrequencyChunk) GetDataPoints(step model.InsightStep) ([]DataPoint, error) {
switch step {
case model.InsightStep_YEARLY:
return ToDataPoints(c.DataPoints.Yearly)
case model.InsightStep_MONTHLY:
return ToDataPoints(c.DataPoints.Monthly)
case model.InsightStep_WEEKLY:
return ToDataPoints(c.DataPoints.Weekly)
case model.InsightStep_DAILY:
return ToDataPoints(c.DataPoints.Daily)
}
return nil, fmt.Errorf("invalid step: %v", step)
}
func (c *DeployFrequencyChunk) SetDataPoints(step model.InsightStep, points []DataPoint) error {
dfs := make([]*DeployFrequency, len(points))
for i, p := range points {
dfs[i] = p.(*DeployFrequency)
}
switch step {
case model.InsightStep_YEARLY:
c.DataPoints.Yearly = dfs
case model.InsightStep_MONTHLY:
c.DataPoints.Monthly = dfs
case model.InsightStep_WEEKLY:
c.DataPoints.Weekly = dfs
case model.InsightStep_DAILY:
c.DataPoints.Daily = dfs
default:
return fmt.Errorf("invalid step: %v", step)
}
return nil
}
// change failure rate
// ChangeFailureRateChunk represents a chunk of ChangeFailureRate data points.
type ChangeFailureRateChunk struct {
AccumulatedTo int64 `json:"accumulated_to"`
DataPoints ChangeFailureRateDataPoint `json:"data_points"`
FilePath string
}
type ChangeFailureRateDataPoint struct {
Daily []*ChangeFailureRate `json:"daily"`
Weekly []*ChangeFailureRate `json:"weekly"`
Monthly []*ChangeFailureRate `json:"monthly"`
Yearly []*ChangeFailureRate `json:"yearly"`
}
func (c *ChangeFailureRateChunk) GetFilePath() string {
return c.FilePath
}
func (c *ChangeFailureRateChunk) SetFilePath(path string) {
c.FilePath = path
}
func (c *ChangeFailureRateChunk) GetAccumulatedTo() int64 {
return c.AccumulatedTo
}
func (c *ChangeFailureRateChunk) SetAccumulatedTo(a int64) {
c.AccumulatedTo = a
}
func (c *ChangeFailureRateChunk) GetDataPoints(step model.InsightStep) ([]DataPoint, error) {
switch step {
case model.InsightStep_YEARLY:
return ToDataPoints(c.DataPoints.Yearly)
case model.InsightStep_MONTHLY:
return ToDataPoints(c.DataPoints.Monthly)
case model.InsightStep_WEEKLY:
return ToDataPoints(c.DataPoints.Weekly)
case model.InsightStep_DAILY:
return ToDataPoints(c.DataPoints.Daily)
}
return nil, fmt.Errorf("invalid step: %v", step)
}
func (c *ChangeFailureRateChunk) SetDataPoints(step model.InsightStep, points []DataPoint) error {
cfs := make([]*ChangeFailureRate, len(points))
for i, p := range points {
cfs[i] = p.(*ChangeFailureRate)
}
switch step {
case model.InsightStep_YEARLY:
c.DataPoints.Yearly = cfs
case model.InsightStep_MONTHLY:
c.DataPoints.Monthly = cfs
case model.InsightStep_WEEKLY:
c.DataPoints.Weekly = cfs
case model.InsightStep_DAILY:
c.DataPoints.Daily = cfs
default:
return fmt.Errorf("invalid step: %v", step)
}
return nil
}
type Chunk interface {
// GetFilePath gets filepath
GetFilePath() string
// SetFilePath sets filepath
SetFilePath(path string)
// GetAccumulatedTo gets AccumulatedTo
GetAccumulatedTo() int64
// SetAccumulatedTo sets AccumulatedTo
SetAccumulatedTo(a int64)
// GetDataPoints gets list of data points of specify step
GetDataPoints(step model.InsightStep) ([]DataPoint, error)
// SetDataPoints sets list of data points of specify step
SetDataPoints(step model.InsightStep, points []DataPoint) error
}
func NewChunk(projectID string, metricsKind model.InsightMetricsKind, step model.InsightStep, appID string, timestamp time.Time) Chunk {
paths := DetermineFilePaths(projectID, appID, metricsKind, step, timestamp, 1)
path := paths[0]
var chunk Chunk
switch metricsKind {
case model.InsightMetricsKind_DEPLOYMENT_FREQUENCY:
chunk = &DeployFrequencyChunk{
FilePath: path,
}
case model.InsightMetricsKind_CHANGE_FAILURE_RATE:
chunk = &ChangeFailureRateChunk{
FilePath: path,
}
default:
return nil
}
return chunk
}
// convert types to Chunk.
func ToChunk(i interface{}) (Chunk, error) {
switch p := i.(type) {
case *DeployFrequencyChunk:
return p, nil
case *ChangeFailureRateChunk:
return p, nil
default:
return nil, fmt.Errorf("cannot convert to Chunk: %v", p)
}
}
type Chunks []Chunk
func (cs Chunks) ExtractDataPoints(step model.InsightStep, from time.Time, count int) ([]*model.InsightDataPoint, error) {
var out []*model.InsightDataPoint
var to time.Time
switch step {
case model.InsightStep_YEARLY:
to = from.AddDate(count-1, 0, 0)
case model.InsightStep_MONTHLY:
to = from.AddDate(0, count-1, 0)
case model.InsightStep_WEEKLY:
to = from.AddDate(0, 0, (count-1)*7)
case model.InsightStep_DAILY:
to = from.AddDate(0, 0, count-1)
}
for _, c := range cs {
dp, err := c.GetDataPoints(step)
if err != nil {
return nil, err
}
idp, err := extractDataPoints(dp, from, to)
if err != nil {
return nil, err
}
out = append(out, idp...)
}
return out, nil
} | pkg/insight/chunk.go | 0.737725 | 0.539711 | chunk.go | starcoder |
package machine
import (
"math"
"unsafe"
)
type Ram struct {
Data []byte `json:"data"`
}
func (ram *Ram) Size() int {
return len(ram.Data)
}
func (ram *Ram) GrowTo(size int) {
if size > len(ram.Data) {
missing := size - len(ram.Data)
new_bytes := make([]byte, missing, missing)
ram.Data = append(ram.Data, new_bytes...)
}
}
func (ram *Ram) Set8(offset int, data uint8) {
ram.Data[offset] = byte(data)
}
func (ram *Ram) Get8(offset int) uint8 {
return ram.Data[offset]
}
func (ram *Ram) Set16(offset int, data uint16) {
*(*uint16)(unsafe.Pointer(&ram.Data[offset])) = data
}
func (ram *Ram) Get16(offset int) uint16 {
return *(*uint16)(unsafe.Pointer(&ram.Data[offset]))
}
func (ram *Ram) Set32(offset int, data uint32) {
*(*uint32)(unsafe.Pointer(&ram.Data[offset])) = data
}
func (ram *Ram) Get32(offset int) uint32 {
return *(*uint32)(unsafe.Pointer(&ram.Data[offset]))
}
func (ram *Ram) Set64(offset int, data uint64) {
*(*uint64)(unsafe.Pointer(&ram.Data[offset])) = data
}
func (ram *Ram) Get64(offset int) uint64 {
return *(*uint64)(unsafe.Pointer(&ram.Data[offset]))
}
func (ram *Ram) Read(offset uint64, size uint) (uint64, error) {
value := uint64(math.MaxUint64)
// Is it greater than our size?
if offset+uint64(size) > uint64(ram.Size()) {
// Ignore.
return value, nil
}
// Handle default.
switch size {
case 1:
value = uint64(ram.Get8(int(offset)))
case 2:
value = uint64(ram.Get16(int(offset)))
case 4:
value = uint64(ram.Get32(int(offset)))
case 8:
value = ram.Get64(int(offset))
}
return value, nil
}
func (ram *Ram) Write(offset uint64, size uint, value uint64) error {
// Is it greater than our size?
if offset+uint64(size) > uint64(ram.Size()) {
// Ignore.
return nil
}
// Handle default.
switch size {
case 1:
ram.Set8(int(offset), uint8(value))
case 2:
ram.Set16(int(offset), uint16(value))
case 4:
ram.Set32(int(offset), uint32(value))
case 8:
ram.Set64(int(offset), value)
}
return nil
}
func NewRam(size int) *Ram {
ram := new(Ram)
ram.Data = make([]byte, size, size)
return ram
} | src/novmm/machine/ram.go | 0.661814 | 0.453322 | ram.go | starcoder |
package drawer
import (
"fmt"
"image"
"image/color"
"math"
"math/rand"
"time"
proc "github.com/esimov/legoizer/processor"
"github.com/fogleman/gg"
"github.com/lucasb-eyer/go-colorful"
)
const (
_1x1 = iota
_2x1
_3x1
_4x1
_6x1
_2x2
_3x2
_4x2
_6x2
)
type point struct {
x, y float64
}
type lego struct {
point
cellSize float64
cellColor color.NRGBA64
}
type context struct {
*gg.Context
}
type Quantizer struct {
proc.Quant
}
type legoIndexes struct {
idx int
idy int
}
var legos []legoIndexes
var (
threshold uint16 = 127
legoMaxRows = 3
legoMaxCols = 2
idx, idy = 1, 1
)
// Process is the main function responsible to generate the lego bricks based on the provided source image.
func (quant *Quantizer) Process(input image.Image, nq int, cs int) image.Image {
rand.Seed(time.Now().UTC().Unix())
var (
legoType int
cellSize int
current, total, progress float64
)
dx, dy := input.Bounds().Dx(), input.Bounds().Dy()
imgRatio := func(w, h int) float64 {
var ratio float64
if w > h {
ratio = float64((w / h) * w)
} else {
ratio = float64((h / w) * h)
}
return ratio
}
if cs == 0 {
cellSize = int(round(float64(imgRatio(dx, dy)) * 0.015))
} else {
cellSize = cs
}
quantified := quant.Quantize(input, nq)
nrgbaImg := convertToNRGBA64(quantified)
dc := &context{gg.NewContext(dx, dy)}
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0, 0, 0)
total = math.Floor(float64(dx * dy / (cellSize * cellSize)))
for x := 0; x < dx; x += cellSize {
// Reset Y index after each row
idy = 1
for y := 0; y < dy; y += cellSize {
xx := x + (cellSize / 2)
yy := y + (cellSize / 2)
current = math.Floor(float64(idx * dy / cellSize))
if xx < dx && yy < dy {
subImg := nrgbaImg.SubImage(image.Rect(x, y, x+cellSize, y+cellSize)).(*image.NRGBA64)
cellColor := getAvgColor(subImg)
lego := dc.getCurrentLego(nrgbaImg, float64(x), float64(y), float64(cellSize))
rows, cols := dc.checkNeighbors(lego, nrgbaImg)
switch {
case rows == 1 && cols == 1:
legoType = _1x1
case rows == 2 && cols == 1:
legoType = _2x1
case rows == 3 && cols == 1:
legoType = _3x1
case rows == 4 && cols == 1:
legoType = _4x1
case rows == 6 && cols == 1:
legoType = _6x1
case rows == 2 && cols == 2:
legoType = _2x2
case rows == 3 && cols == 2:
legoType = _3x2
case rows == 4 && cols == 2:
legoType = _4x2
case rows == 6 && cols == 2:
legoType = _6x2
}
dc.generateLegoSet(float64(x), float64(y), float64(xx), float64(yy), float64(cellSize), idx, idy, cellColor, legoType)
}
idy++
}
if current < total {
progress = math.Floor(float64(current/total) * 100.0)
showProgress(progress)
}
idx++
}
if progress < 100 {
showProgress(100)
}
img := dc.Image()
noisyImg := noise(10, img, img.Bounds().Dx(), img.Bounds().Dy())
return noisyImg
}
// createLegoPiece creates the lego piece
func (dc *context) createLegoPiece(x, y, xx, yy, cellSize float64, c color.NRGBA64) *lego {
// Brightness factor
var bf = 1.0005
// Background
dc.DrawRectangle(x, y, x+cellSize, y+cellSize)
dc.SetRGBA(float64(c.R/255^0xff)*bf, float64(c.G/255^0xff)*bf, float64(c.B/255^0xff)*bf, 1)
dc.Fill()
// Create a shadow effect
dc.Push()
// Top circle
grad := gg.NewRadialGradient(xx, yy, cellSize/2, x, y, 0)
grad.AddColorStop(0, color.RGBA{177, 177, 177, 0})
grad.AddColorStop(1, color.RGBA{255, 255, 255, 177})
dc.SetFillStyle(grad)
dc.DrawCircle(float64(xx-1), float64(yy-1), cellSize/2-math.Sqrt(cellSize))
dc.Fill()
// Bottom circle
grad = gg.NewRadialGradient(xx, yy, cellSize/2, x, y, 0)
grad.AddColorStop(0, color.RGBA{0, 0, 0, 177})
r, g, b := c.R/255^0xff, c.G/255^0xff, c.B/255^0xff
if r > threshold || g > threshold || b > threshold {
grad.AddColorStop(1, color.RGBA{0, 0, 0, 255})
} else {
grad.AddColorStop(1, color.RGBA{177, 177, 177, 255})
}
dc.SetFillStyle(grad)
dc.StrokePreserve()
dc.DrawCircle(float64(xx+1), float64(yy+1), cellSize/2-math.Sqrt(cellSize))
dc.Fill()
dc.Pop()
// Draw the main circle
dc.DrawCircle(xx, yy, float64(cellSize/2)-math.Sqrt(float64(cellSize)))
dc.SetRGBA(float64(c.R/255^0xff), float64(c.G/255^0xff), float64(c.B/255^0xff), float64(c.A/255))
dc.Fill()
return &lego{
point{x: x, y: y},
cellSize,
c,
}
}
// generateLegoSet creates the lego block constituted by the lego pieces.
// This function traces the lego borders on the intersection of columns and rows.
func (dc *context) generateLegoSet(x, y, xx, yy, cellSize float64, idx, idy int, c color.NRGBA64, legoType int) *lego {
var rows, cols int
switch legoType {
case _1x1:
rows, cols = 1, 1
case _2x1:
rows, cols = 2, 1
case _3x1:
rows, cols = 3, 1
case _4x1:
rows, cols = 4, 1
case _6x1:
rows, cols = 6, 1
case _2x2:
rows, cols = 2, 2
case _3x2:
rows, cols = 3, 2
case _4x2:
rows, cols = 4, 2
case _6x2:
rows, cols = 6, 2
}
drawLeftBorderLine := func(x, y float64) {
dc.SetColor(color.RGBA{177, 177, 177, 177})
dc.SetLineWidth(0.10)
dc.MoveTo(x, y)
dc.LineTo(x, y+cellSize)
dc.ClosePath()
dc.Stroke()
}
drawTopBorderLine := func(x, y float64) {
dc.SetColor(color.RGBA{177, 177, 177, 177})
dc.SetLineWidth(0.05)
dc.MoveTo(x, y)
dc.LineTo(x+cellSize, y)
dc.ClosePath()
dc.Stroke()
}
drawRightBorderLine := func(x, y float64) {
dc.SetColor(color.RGBA{0, 0, 0, 177})
dc.SetLineWidth(0.15)
dc.MoveTo(x+cellSize, y)
dc.LineTo(x+cellSize, y+cellSize)
dc.ClosePath()
dc.Stroke()
}
drawBottomBorderLine := func(x, y float64) {
dc.SetColor(color.RGBA{0, 0, 0, 177})
dc.SetLineWidth(0.15)
dc.MoveTo(x, y+cellSize)
dc.LineTo(x+cellSize, y+cellSize)
dc.ClosePath()
dc.Stroke()
}
// Create the lego piece then trace the borders.
dc.createLegoPiece(x, y, float64(xx), float64(yy), float64(cellSize), c)
legoExists := findLegoIndex(legos, int(x), int(y))
// Draw the borders only if index does not exists in the index table.
if !legoExists {
if idx%rows == 0 {
drawLeftBorderLine(x-(cellSize*float64(rows))+cellSize+1, y)
drawRightBorderLine(x, y)
}
if idy%cols == 0 {
drawTopBorderLine(x, y-(cellSize*float64(cols))+cellSize+1)
drawBottomBorderLine(x, y)
}
}
return &lego{
point{x: x, y: y},
cellSize,
c,
}
}
// getCurrentLego returns the current lego's first pixel color.
// We don't need to get all the colors of the cell, since we are averaging the cell color.
func (dc *context) getCurrentLego(cell *image.NRGBA64, x, y, cellSize float64) *lego {
// Get the first pixel color
var c = cell.NRGBA64At(int(x), int(y))
return &lego{
point{x: x, y: y},
cellSize,
c,
}
}
// Check if the current lego color is identical with the neighbors color.
// Returns the number of rows and columns identical with the current lego, with the rows & columns representing the lego type.
func (dc *context) checkNeighbors(lego *lego, neighborCell *image.NRGBA64) (int, int) {
var lastIdx, lastIdy int = 1, 1
var (
cellSize = lego.cellSize
cellColor = lego.cellColor
x = lego.x
y = lego.y
ct = 7.0
currentRowCellColor color.NRGBA64
)
rows, cols := 1, 1
legoWidth := random(rows, legoMaxRows)
legoHeight := random(cols, legoMaxCols)
xi := int(x)
yi := int(y)
// Rows
for i := 1; ; i++ {
if i > legoWidth {
break
}
if xi*i < dc.Width() && yi*i < dc.Height() {
nextCell := neighborCell.SubImage(image.Rect(xi*i, yi, xi*i+int(cellSize), yi+int(cellSize))).(*image.NRGBA64)
nextCellColor := getAvgColor(nextCell)
// Because the next cell average color might differ from the current cell color even with a small amount,
// we have to check if the current cell color is approximately identical with the neighboring cells.
c1 := colorful.Color{
R: float64(cellColor.R >> 8),
G: float64(cellColor.G >> 8),
B: float64(cellColor.B >> 8),
}
c2 := colorful.Color{
R: float64(nextCellColor.R >> 8),
G: float64(nextCellColor.G >> 8),
B: float64(nextCellColor.B >> 8),
}
colorThreshold := c1.DistanceCIE94(c2)
if colorThreshold > ct {
currentRowCellColor = cellColor
lastIdx = xi * i
break
}
}
rows++
}
// Columns
for i := 1; ; i++ {
if i > legoHeight {
break
}
if xi*i < dc.Width() && yi*i < dc.Height() {
nextCell := neighborCell.SubImage(image.Rect(xi, yi*i, xi+int(cellSize), yi*i+int(cellSize))).(*image.NRGBA64)
nextCellColor := getAvgColor(nextCell)
c1 := colorful.Color{
R: float64(cellColor.R >> 8),
G: float64(cellColor.G >> 8),
B: float64(cellColor.B >> 8),
}
c2 := colorful.Color{
R: float64(nextCellColor.R >> 8),
G: float64(nextCellColor.G >> 8),
B: float64(nextCellColor.B >> 8),
}
colorThreshold := c1.DistanceCIE94(c2)
if colorThreshold > ct || currentRowCellColor.R != cellColor.R {
lastIdy = yi * i
break
}
}
cols++
}
// No lego piece with 5 rows
if rows == 5 {
rows = 4
}
// Save the generated lego indexes into the index table.
// We need verify if the lego borders have been traced based on the index value.
if !findLegoIndex(legos, lastIdx, lastIdy) {
legos = append(legos, legoIndexes{lastIdx, lastIdy})
}
return rows, cols
}
// getAvgColor get the average color of a cell
func getAvgColor(img *image.NRGBA64) color.NRGBA64 {
var (
bounds = img.Bounds()
r, g, b int
)
for x := bounds.Min.X; x < bounds.Max.X; x++ {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
var c = img.NRGBA64At(x, y)
r += int(c.R)
g += int(c.G)
b += int(c.B)
}
}
return color.NRGBA64{
R: maxUint16(0, minUint16(65535, uint16(r/(bounds.Dx()*bounds.Dy())))),
G: maxUint16(0, minUint16(65535, uint16(g/(bounds.Dx()*bounds.Dy())))),
B: maxUint16(0, minUint16(65535, uint16(b/(bounds.Dx()*bounds.Dy())))),
A: 255,
}
}
// convertToNRGBA64 converts an image.Image into an image.NRGBA64.
func convertToNRGBA64(img image.Image) *image.NRGBA64 {
var (
bounds = img.Bounds()
nrgba = image.NewNRGBA64(bounds)
)
for x := bounds.Min.X; x < bounds.Max.X; x++ {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
nrgba.Set(x, y, img.At(x, y))
}
}
return nrgba
}
// findLegoIndex check if the processed lego index exists in the lego table.
func findLegoIndex(legos []legoIndexes, ix, iy int) bool {
for i := 0; i < len(legos); i++ {
idx, idy := legos[i].idx, legos[i].idy
if idx == ix && idy == iy {
return true
}
}
return false
}
// round number down.
func round(x float64) float64 {
return math.Floor(x)
}
// random generates a random number between min & max.
func random(min, max int) int {
return rand.Intn(max-min) + min
}
// minUint16 returns the smallest number between two uint16 numbers.
func minUint16(x, y uint16) uint16 {
if x < y {
return x
}
return y
}
// maxUint16 returns the biggest number between two uint16 numbers.
func maxUint16(x, y uint16) uint16 {
if x > y {
return x
}
return y
}
// showProgress show the progress status.
func showProgress(progress float64) {
fmt.Printf(" \r %v%% [", progress)
for p := 0; p < 100; p += 3 {
if progress > float64(p) {
fmt.Print("=")
} else {
fmt.Print(" ")
}
}
fmt.Printf("] \r")
} | drawer/drawer.go | 0.591015 | 0.495545 | drawer.go | starcoder |
package bindings
import "strconv"
type tFloat64 struct {
listeners []Float64Listener
value float64
filter Float64Filter
}
type tFloat64AB struct {
tFloat64
parentA Float64
parentB Float64
}
type tFloat64BooleanAB struct {
tBoolean
parentA Float64
parentB Float64
}
type tFloat64Divide struct {
tFloat64AB
}
type tFloat64Equal struct {
tFloat64BooleanAB
}
type tFloat64Greater struct {
tFloat64BooleanAB
}
type tFloat64GreaterOrEqual struct {
tFloat64BooleanAB
}
type tFloat64Less struct {
tFloat64BooleanAB
}
type tFloat64LessOrEqual struct {
tFloat64BooleanAB
}
type tFloat64Minus struct {
tFloat64AB
}
type tFloat64Multiply struct {
tFloat64AB
}
type tFloat64NotEqual struct {
tFloat64BooleanAB
}
type tFloat64Plus struct {
tFloat64AB
}
func (float64Value *tFloat64) AddListener(listener Float64Listener) {
if !containsFloat64Listener(float64Value.listeners, listener) {
float64Value.listeners = append(float64Value.listeners, listener)
}
}
func (float64Value *tFloat64) Divide(float64ValueB Float64) Float64 {
float64Divide := new(tFloat64Divide)
float64Divide.parentA = float64Value
float64Divide.parentB = float64ValueB
float64Value.AddListener(float64Divide)
float64ValueB.AddListener(float64Divide)
return float64Divide
}
func (float64Value *tFloat64) EqualTo(float64ValueB Float64) Boolean {
float64Equal := new(tFloat64Equal)
float64Equal.parentA = float64Value
float64Equal.parentB = float64ValueB
float64Value.AddListener(float64Equal)
float64ValueB.AddListener(float64Equal)
return float64Equal
}
func (float64Value *tFloat64) Float32() Float32 {
float32Value := new(tFloat32)
float64Value.AddListener(float32Value)
return float32Value
}
func (float64Value *tFloat64) GreaterThan(float64ValueB Float64) Boolean {
float64Greater := new(tFloat64Greater)
float64Greater.parentA = float64Value
float64Greater.parentB = float64ValueB
float64Value.AddListener(float64Greater)
float64ValueB.AddListener(float64Greater)
return float64Greater
}
func (float64Value *tFloat64) GreaterThanOrEqualTo(float64ValueB Float64) Boolean {
float64GreaterOrEqual := new(tFloat64GreaterOrEqual)
float64GreaterOrEqual.parentA = float64Value
float64GreaterOrEqual.parentB = float64ValueB
float64Value.AddListener(float64GreaterOrEqual)
float64ValueB.AddListener(float64GreaterOrEqual)
return float64GreaterOrEqual
}
func (float64Value *tFloat64) Int() Int {
intValue := new(tInt)
float64Value.AddListener(intValue)
return intValue
}
func (float64Value *tFloat64) LessThan(float64ValueB Float64) Boolean {
float64Less := new(tFloat64Less)
float64Less.parentA = float64Value
float64Less.parentB = float64ValueB
float64Value.AddListener(float64Less)
float64ValueB.AddListener(float64Less)
return float64Less
}
func (float64Value *tFloat64) LessThanOrEqualTo(float64ValueB Float64) Boolean {
float64LessOrEqual := new(tFloat64LessOrEqual)
float64LessOrEqual.parentA = float64Value
float64LessOrEqual.parentB = float64ValueB
float64Value.AddListener(float64LessOrEqual)
float64ValueB.AddListener(float64LessOrEqual)
return float64LessOrEqual
}
func (float64Value *tFloat64) Minus(float64ValueB Float64) Float64 {
float64Minus := new(tFloat64Minus)
float64Minus.parentA = float64Value
float64Minus.parentB = float64ValueB
float64Value.AddListener(float64Minus)
float64ValueB.AddListener(float64Minus)
return float64Minus
}
func (float64Value *tFloat64) Multiply(float64ValueB Float64) Float64 {
float64Multiply := new(tFloat64Multiply)
float64Multiply.parentA = float64Value
float64Multiply.parentB = float64ValueB
float64Value.AddListener(float64Multiply)
float64ValueB.AddListener(float64Multiply)
return float64Multiply
}
func (float64Value *tFloat64) NotEqualTo(float64ValueB Float64) Boolean {
float64ValueNotEqual := new(tFloat64NotEqual)
float64ValueNotEqual.parentA = float64Value
float64ValueNotEqual.parentB = float64ValueB
float64Value.AddListener(float64ValueNotEqual)
float64ValueB.AddListener(float64ValueNotEqual)
return float64ValueNotEqual
}
func (float64Value *tFloat64) Plus(float64ValueB Float64) Float64 {
float64Plus := new(tFloat64Plus)
float64Plus.parentA = float64Value
float64Plus.parentB = float64ValueB
float64Value.AddListener(float64Plus)
float64ValueB.AddListener(float64Plus)
return float64Plus
}
func (float64Value *tFloat64) RemoveListener(listener Float64Listener) {
i := indexFloat64Listener(float64Value.listeners, listener)
if i >= 0 {
float64Value.listeners = removeFloat64Listener(float64Value.listeners, i)
}
}
func (float64Value *tFloat64) Set(newValue float64) {
oldValue := float64Value.value
if float64Value.filter != nil {
newValue = float64Value.filter.FilterFloat64(float64Value, oldValue, newValue)
}
if float64Value.value != newValue {
observable := Float64(float64Value)
float64Value.value = newValue
for _, listener := range float64Value.listeners {
listener.Float64Changed(observable, oldValue, newValue)
}
}
}
func (float64Value *tFloat64) SetFilter(filter Float64Filter) {
float64Value.filter = filter
}
func (float64Value *tFloat64) String() String {
stringValue := new(tString)
float64Value.AddListener(stringValue)
return stringValue
}
func (float64Value *tFloat64) Value() float64 {
return float64Value.value
}
func (float64Value *tFloat64) Float32Changed(observable Float32, oldValue, newValue float32) {
float64Value.Set(float64(newValue))
}
func (float64Value *tFloat64) IntChanged(observable Int, oldValue, newValue int) {
float64Value.Set(float64(newValue))
}
func (float64Value *tFloat64) StringChanged(observable String, oldValue, newValue string) {
if val, err := strconv.ParseFloat(newValue, 64); err == nil {
float64Value.Set(val)
}
}
func (float64Value *tFloat64Divide) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(newValue / float64Value.parentB.Value())
} else {
float64Value.Set(float64Value.parentA.Value() / newValue)
}
}
func (float64Value *tFloat64Equal) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() == newValue)
} else {
float64Value.Set(float64Value.parentA.Value() == newValue)
}
}
func (float64Value *tFloat64Greater) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() < newValue)
} else {
float64Value.Set(float64Value.parentA.Value() > newValue)
}
}
func (float64Value *tFloat64GreaterOrEqual) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() <= newValue)
} else {
float64Value.Set(float64Value.parentA.Value() >= newValue)
}
}
func (float64Value *tFloat64Less) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() > newValue)
} else {
float64Value.Set(float64Value.parentA.Value() < newValue)
}
}
func (float64Value *tFloat64LessOrEqual) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() >= newValue)
} else {
float64Value.Set(float64Value.parentA.Value() <= newValue)
}
}
func (float64Value *tFloat64Minus) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(newValue - float64Value.parentB.Value())
} else {
float64Value.Set(float64Value.parentA.Value() - newValue)
}
}
func (float64Value *tFloat64Multiply) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() * newValue)
} else {
float64Value.Set(float64Value.parentA.Value() * newValue)
}
}
func (float64Value *tFloat64NotEqual) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() != newValue)
} else {
float64Value.Set(float64Value.parentA.Value() != newValue)
}
}
func (float64Value *tFloat64Plus) Float64Changed(observable Float64, oldValue, newValue float64) {
if float64Value.parentA == observable {
float64Value.Set(float64Value.parentB.Value() + newValue)
} else {
float64Value.Set(float64Value.parentA.Value() + newValue)
}
} | float64.go | 0.764892 | 0.610686 | float64.go | starcoder |
package letters
import (
"image/color"
"github.com/llgcode/draw2d"
"github.com/llgcode/draw2d/draw2dimg"
)
// CellDrawer represents a type that contains all of the drawing
// functions needed by a segment in order to draw within the cell
type CellDrawer interface {
Fill(paths ...*draw2d.Path)
FillStroke(paths ...*draw2d.Path)
Stroke(paths ...*draw2d.Path)
Close()
SetFillColor(c color.Color)
SetStrokeColor(c color.Color)
MoveTo(x, y float64)
LineTo(x, y float64)
}
// cellDrawer is the actual struct that implements the CellDrawer interface
type cellDrawer struct {
GraphicContext *draw2dimg.GraphicContext
CellTopLeft [2]float64
CellWidth float64
CellHeight float64
SegmentWidth float64
SegmentHeight float64
}
// NewCellDrawer creates a CellDrawer for allowing a segment to draw
// within a cell. It allows the Cell and the segment's reference sizes
// to be different, and will translate between one and the other to
// simplify the construction of segment drawing procedures.
func NewCellDrawer(gc *draw2dimg.GraphicContext, cell *Cell, segment Segment) CellDrawer {
return &cellDrawer{
GraphicContext: gc,
CellTopLeft: cell.TopLeft,
CellWidth: cell.Width(),
CellHeight: cell.Height(),
SegmentWidth: segment.Width(),
SegmentHeight: segment.Height(),
}
}
// Fill wraps GraphicContext.Fill
func (cd *cellDrawer) Fill(paths ...*draw2d.Path) {
cd.GraphicContext.Fill(paths...)
}
// FillStroke wraps GraphicContext.FillStroke
func (cd *cellDrawer) FillStroke(paths ...*draw2d.Path) {
cd.GraphicContext.FillStroke(paths...)
}
// Stroke wraps GraphicContext.Stroke
func (cd *cellDrawer) Stroke(paths ...*draw2d.Path) {
cd.GraphicContext.Stroke(paths...)
}
// Close wraps GraphicContext.Close
func (cd *cellDrawer) Close() {
cd.GraphicContext.Close()
}
// SetFillColor wraps GraphicContext.SetFillColor
func (cd *cellDrawer) SetFillColor(c color.Color) {
cd.GraphicContext.SetFillColor(c)
}
// SetStrokeColor wraps GraphicContext.SetStrokeColor
func (cd *cellDrawer) SetStrokeColor(c color.Color) {
cd.GraphicContext.SetStrokeColor(c)
}
// ConvertCoords converts coordinates from the segment system to the global cell system
func (cd *cellDrawer) ConvertCoords(x, y float64) (newX, newY float64) {
// (x, y) is in the segment coordinate system
// segment top left = (0,0), segment bottom right = (width-1, height-1)
u := x / (cd.SegmentWidth - 1)
v := y / (cd.SegmentHeight - 1)
newX = cd.CellTopLeft[0] + u*(cd.CellWidth-1)
newY = cd.CellTopLeft[1] + v*(cd.CellHeight-1)
return
}
// MoveTo wraps GraphicContext.MoveTo, converting between coordinate systems in the process
func (cd *cellDrawer) MoveTo(x, y float64) {
newX, newY := cd.ConvertCoords(x, y)
cd.GraphicContext.MoveTo(newX, newY)
}
// LineTo wraps GraphicContext.LineTo, converting between coordinate systems in the process
func (cd *cellDrawer) LineTo(x, y float64) {
newX, newY := cd.ConvertCoords(x, y)
cd.GraphicContext.LineTo(newX, newY)
} | pkg/letters/celldraw.go | 0.815233 | 0.478712 | celldraw.go | starcoder |
package goNixArgParser
import "strconv"
func getValue(source map[string][]string, key string) (value string, found bool) {
var values []string
values, found = source[key]
if found && len(values) > 0 {
value = values[0]
}
return
}
func getValues(source map[string][]string, key string) (values []string, found bool) {
values, found = source[key]
if found {
values = copys(values)
return values, true
}
return
}
func copys(input []string) []string {
if input == nil {
return nil
}
output := make([]string, len(input))
copy(output, input)
return output
}
func toBool(input string) (bool, error) {
if len(input) == 0 {
return false, nil
}
return strconv.ParseBool(input)
}
func toBools(input []string) ([]bool, error) {
inputLen := len(input)
output := make([]bool, inputLen)
for i, l := 0, inputLen; i < l; i++ {
v, err := toBool(input[i])
if err != nil {
return nil, err
}
output[i] = v
}
return output, nil
}
func toInt(input string) (int, error) {
return strconv.Atoi(input)
}
func toInts(input []string) ([]int, error) {
inputLen := len(input)
output := make([]int, inputLen)
for i, l := 0, inputLen; i < l; i++ {
v, err := toInt(input[i])
if err != nil {
return nil, err
}
output[i] = v
}
return output, nil
}
func toInt64(input string) (int64, error) {
return strconv.ParseInt(input, 10, 64)
}
func toInt64s(input []string) ([]int64, error) {
inputLen := len(input)
output := make([]int64, inputLen)
for i, l := 0, inputLen; i < l; i++ {
v, err := toInt64(input[i])
if err != nil {
return nil, err
}
output[i] = v
}
return output, nil
}
func toUint64(input string) (uint64, error) {
return strconv.ParseUint(input, 10, 64)
}
func toUint64s(input []string) ([]uint64, error) {
inputLen := len(input)
output := make([]uint64, inputLen)
for i, l := 0, inputLen; i < l; i++ {
v, err := toUint64(input[i])
if err != nil {
return nil, err
}
output[i] = v
}
return output, nil
}
func toFloat64(input string) (float64, error) {
return strconv.ParseFloat(input, 64)
}
func toFloat64s(input []string) ([]float64, error) {
inputLen := len(input)
output := make([]float64, inputLen)
for i, l := 0, inputLen; i < l; i++ {
v, err := toFloat64(input[i])
if err != nil {
return nil, err
}
output[i] = v
}
return output, nil
}
func contains(collection []string, find string) bool {
for _, item := range collection {
if item == find {
return true
}
}
return false
}
func appendUnique(origins []string, items ...string) []string {
for _, item := range items {
if !contains(origins, item) {
origins = append(origins, item)
}
}
return origins
} | util.go | 0.504394 | 0.401952 | util.go | starcoder |
package dtw
import (
"errors"
"fmt"
"io"
"math"
"reflect"
)
// DistanceFunc is the function used to calculate the distance between x and y
type DistanceFunc func(x, y interface{}) float64
// Dtw ...
type Dtw struct {
s reflect.Value
t reflect.Value
df DistanceFunc
matrix [][]float64
}
// New ...
func New() *Dtw {
return &Dtw{}
}
// Distance calculates the DTW between series s and t.
func (dtw *Dtw) Distance(s, t interface{}, f DistanceFunc) (float64, error) {
if f == nil {
return 0, errors.New("invalid distance func")
}
dtw.df = f
if reflect.TypeOf(s).Kind() != reflect.Slice {
return 0, errors.New("series s is not a slice")
}
if reflect.TypeOf(t).Kind() != reflect.Slice {
return 0, errors.New("series t is not a slice")
}
ss := reflect.ValueOf(s)
tt := reflect.ValueOf(t)
if ss.Len() == 0 {
return 0, errors.New("s series is empty")
}
if tt.Len() == 0 {
return 0, errors.New("t series is empty")
}
// get dtw.s be the longer series
dtw.s, dtw.t = ss, tt
if ss.Len() < tt.Len() {
dtw.s, dtw.t = tt, ss
}
dtw.initMatrix()
m, n := dtw.s.Len(), dtw.t.Len()
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
dtw.matrix[r][c] = dtw.dist(r, c)
}
}
return dtw.matrix[m-1][n-1], nil
}
// Path ...
func (dtw *Dtw) Path() [][2]int {
m, n := dtw.s.Len(), dtw.t.Len()
r, c := m-1, n-1
path := [][2]int{}
path = append(path, [2]int{r, c})
for r > 0 && c > 0 {
min := dtw.matrix[r-1][c-1]
rr, cc := r-1, c-1
if dtw.matrix[r-1][c] < min {
rr, cc = r-1, c
min = dtw.matrix[r-1][c]
}
if dtw.matrix[r][c-1] < min {
rr, cc = r, c-1
}
r, c = rr, cc
path = append(path, [2]int{r, c})
}
// reverse
for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
path[i], path[j] = path[j], path[i]
}
return path
}
// Draw ...
func (dtw *Dtw) Draw(w io.Writer) {
m, n := dtw.s.Len(), dtw.t.Len()
matrix := make([][]string, m)
for i := 0; i < m; i++ {
matrix[i] = make([]string, n)
}
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
s := fmt.Sprintf("%.2f ", dtw.matrix[r][c])
matrix[r][c] = fmt.Sprintf("%15s", s)
}
}
path := dtw.Path()
for _, p := range path {
r, c := p[0], p[1]
s := fmt.Sprintf("[%.2f]", dtw.matrix[r][c])
matrix[r][c] = fmt.Sprintf("%15s", s)
}
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
fmt.Fprintf(w, "%v", matrix[r][c])
}
fmt.Fprintln(w)
}
}
func (dtw *Dtw) initMatrix() {
m := dtw.s.Len()
n := dtw.t.Len()
matrix := make([][]float64, m)
for i := 0; i < m; i++ {
matrix[i] = make([]float64, n)
for j := 0; j < n; j++ {
matrix[i][j] = math.Inf(1)
}
}
dtw.matrix = matrix
}
func (dtw *Dtw) min(v1, v2, v3 float64) float64 {
min := v1
if v2 < min {
min = v2
}
if v3 < min {
min = v3
}
return min
}
func (dtw *Dtw) dist(r, c int) float64 {
dist := dtw.df(dtw.s.Index(r).Interface(), dtw.t.Index(c).Interface())
if r == 0 && c == 0 {
return dist
}
if r == 0 && c > 0 {
return dist + dtw.matrix[r][c-1]
}
if c == 0 && r > 0 {
return dist + dtw.matrix[r-1][c]
}
return dist + dtw.min(dtw.matrix[r-1][c-1], dtw.matrix[r-1][c], dtw.matrix[r][c-1])
} | dtw.go | 0.617974 | 0.447279 | dtw.go | starcoder |
package graph
import (
"fmt"
"strings"
"github.com/heustis/tsp-solver-go/model"
)
type GraphVertex struct {
id string
adjacentVertices map[*GraphVertex]float64
paths map[model.CircuitVertex]*GraphEdge
}
func NewGraphVertex(id string) *GraphVertex {
g := &GraphVertex{
id: id,
adjacentVertices: make(map[*GraphVertex]float64),
paths: make(map[model.CircuitVertex]*GraphEdge),
}
return g
}
func (v *GraphVertex) AddAdjacentVertex(other *GraphVertex, distance float64) {
v.adjacentVertices[other] = distance
}
func (v *GraphVertex) Delete() {
for k := range v.adjacentVertices {
delete(v.adjacentVertices, k)
}
v.adjacentVertices = nil
v.DeletePaths()
}
func (v *GraphVertex) DeletePaths() {
for end, edge := range v.paths {
edge.Delete()
delete(v.paths, end)
}
v.paths = nil
}
func (v *GraphVertex) DistanceTo(other model.CircuitVertex) float64 {
return v.EdgeTo(other).GetLength()
}
// EdgeTo creates a new GraphEdge from the start vertex to the end vertex.
// Its complexity is O(n*log(n)), due to needing to find the optimal path, which potentially involves
// checking each vertex in the graph, which are sorted by distance from the start vertex, for early escape.
// If a path cannot be created from the start vertex to the end vertex nil will be returned (the graph is asymmetric, so it is possible to connect only one way).
func (start *GraphVertex) EdgeTo(end model.CircuitVertex) model.CircuitEdge {
if path := start.paths[end]; path != nil && len(path.path) > 0 {
return path
} else {
visited := make(map[*GraphVertex]bool)
toVisit := model.NewHeap(func(a interface{}) float64 {
return a.(*GraphEdge).distance
})
current := &GraphEdge{
path: []*GraphVertex{start},
distance: 0.0,
}
for okay := true; okay; current, okay = toVisit.PopHeap().(*GraphEdge) {
currentVertex := current.GetEnd().(*GraphVertex)
if current.GetEnd() == end {
start.paths[end] = current
break
}
if !visited[currentVertex] {
// Only visit vertices once, base on the shortest path to the vertex.
// Update visited map only with the current vertex, to ensure that it is shortest path to that vertex.
visited[currentVertex] = true
for v, dist := range currentVertex.adjacentVertices {
// Avoid creating unnecessary objects if we've already visted the vertex.
if !visited[v] {
next := &GraphEdge{
path: make([]*GraphVertex, len(current.path), len(current.path)+1),
distance: current.distance + dist,
}
copy(next.path, current.path)
next.path = append(next.path, v)
toVisit.PushHeap(next)
}
}
}
current.Delete()
}
toVisit.Delete()
return current
}
}
func (v *GraphVertex) Equals(other interface{}) bool {
if otherVertex, okay := other.(*GraphVertex); okay {
return strings.Compare(v.id, otherVertex.id) == 0
}
return false
}
func (v *GraphVertex) GetAdjacentVertices() map[*GraphVertex]float64 {
return v.adjacentVertices
}
func (v *GraphVertex) GetId() string {
return v.id
}
func (v *GraphVertex) GetPaths() map[model.CircuitVertex]*GraphEdge {
return v.paths
}
// InitializePaths sets up the map of the most efficient edges from this vertex to all other vertices in the graph.
// Its complexity is O(n*e*log(n*e)), where n is the number of nodes and e is the average number of edges off of each node.
// We only visit each node once, however for each node we add each of its connected nodes to a heap to find the shortest path to the next unvisited node.
func (start *GraphVertex) InitializePaths() {
toVisit := model.NewHeap(func(a interface{}) float64 {
return a.(*GraphEdge).distance
})
startEdge := &GraphEdge{
path: []*GraphVertex{start},
distance: 0.0,
}
for current, okay := startEdge, true; okay; current, okay = toVisit.PopHeap().(*GraphEdge) {
currentVertex := current.GetEnd().(*GraphVertex)
// Only visit vertices once, base on the shortest path to the vertex.
if _, visited := start.paths[currentVertex]; !visited {
start.paths[currentVertex] = current
for v, dist := range currentVertex.adjacentVertices {
// Don't push vertices with a shorter path, also prevent looping between adjacent vertices.
// Note: we don't update visited yet, since there may be a vertex that is farther than the current vertex, but with a shorter connection to 'v'.
if _, nextVisited := start.paths[v]; !nextVisited {
next := &GraphEdge{
path: make([]*GraphVertex, len(current.path), len(current.path)+1),
distance: current.distance + dist,
}
copy(next.path, current.path)
next.path = append(next.path, v)
toVisit.PushHeap(next)
}
}
}
}
}
func (v *GraphVertex) String() string {
s := fmt.Sprintf(`{"id":"%s","adjacentVertices":{`, v.id)
// Sort the adjacent vertices by distance to ensure consistent string representation of the vertex.
h := model.NewHeap(func(a interface{}) float64 {
return a.(*StringVertex).distance
})
defer h.Delete()
for adj, dist := range v.adjacentVertices {
h.PushHeap(&StringVertex{
id: adj.id,
distance: dist,
})
}
isFirst := true
for v, okay := h.PopHeap().(*StringVertex); okay; v, okay = h.PopHeap().(*StringVertex) {
if !isFirst {
s += ","
}
isFirst = false
s += fmt.Sprintf(`"%s":%g`, v.id, v.distance)
}
s += "}}"
return s
}
type StringVertex struct {
id string
distance float64
}
var _ model.CircuitVertex = (*GraphVertex)(nil) | graph/graphvertex.go | 0.780997 | 0.554953 | graphvertex.go | starcoder |
package tester
import (
"fmt"
"github.com/byorty/contractor/common"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pkg/errors"
"regexp"
"strconv"
"strings"
"time"
)
//go:generate mockgen -source=$GOFILE -package=mocks -destination=mocks/$GOFILE
type Assertion struct {
Name string
Expected string
Actual string
expression string
value interface{}
}
type AssertionMap map[string]*Assertion
type AsserterBuilder interface {
Build(testCase *TestCase) AssertionProcessor
}
func NewFxAsserterBuilder(
dataCrawler common.DataCrawler,
expressionFactory common.ExpressionFactory,
) AsserterBuilder {
return &asserterBuilder{
expressionFactory: expressionFactory,
dataCrawler: dataCrawler,
dataCrawlerOpts: []common.DataCrawlerOption{
common.WithPrefix("$"),
common.WithJoinKeys(),
common.WithSkipCollections(),
},
}
}
type asserterBuilder struct {
dataCrawler common.DataCrawler
dataCrawlerOpts []common.DataCrawlerOption
expressionFactory common.ExpressionFactory
}
func (b *asserterBuilder) Build(testCase *TestCase) AssertionProcessor {
processor := &assertionProcessor{
expressionFactory: b.expressionFactory,
assertions: AssertionMap{
"__Err__": &Assertion{
Name: "Error",
expression: "empty()",
value: testCase.Err,
},
},
}
if testCase.ActualResult == nil {
return processor
}
processor.assertions["__Status__"] = &Assertion{
Name: "Status Code",
expression: fmt.Sprintf("eq(%d)", testCase.ExpectedResult.StatusCode),
value: testCase.ActualResult.StatusCode,
}
for expectedHeaderName, expectedHeaderValue := range testCase.ExpectedResult.Headers {
processor.assertions[fmt.Sprintf("__%s__", expectedHeaderName)] = &Assertion{
Name: fmt.Sprintf("Header %s", expectedHeaderName),
expression: fmt.Sprintf("eq('%s')", expectedHeaderValue),
value: testCase.ActualResult.Headers[expectedHeaderName],
}
}
b.dataCrawler.Walk(testCase.ExpectedResult.Body, func(k string, v interface{}) {
processor.assertions[k] = &Assertion{
expression: fmt.Sprint(v),
}
}, b.dataCrawlerOpts...)
b.dataCrawler.Walk(testCase.ActualResult.Body, func(k string, v interface{}) {
_, ok := processor.assertions[k]
if !ok {
processor.assertions[k] = &Assertion{
value: v,
}
return
}
processor.assertions[k].value = v
}, b.dataCrawlerOpts...)
return processor
}
type AssertionProcessor interface {
Process(testCase *TestCase)
}
type assertionProcessor struct {
expressionFactory common.ExpressionFactory
assertions AssertionMap
}
func (a *assertionProcessor) Process(testCase *TestCase) {
testCase.Assertions = make([]*Assertion, 0)
defer func() {
if len(testCase.Assertions) == 0 {
testCase.Status = TestCaseStatusSuccess
} else {
testCase.Status = TestCaseStatusFailure
}
}()
for path, assertion := range a.assertions {
if len(assertion.Name) == 0 {
assertion.Name = fmt.Sprintf("Property '%s' value is invalid", strings.TrimLeft(path, "."))
}
if len(assertion.expression) == 0 {
assertion.Expected = "not present"
assertion.Actual = "present"
testCase.Assertions = append(testCase.Assertions, assertion)
continue
}
output, err := a.expressionFactory.Create(common.ExpressionTypeAsserter, assertion.expression)
if err != nil {
assertion.Actual = err.Error()
testCase.Assertions = append(testCase.Assertions, assertion)
continue
}
asserter := output.(Asserter)
err = asserter.Assert(assertion.value)
if err != nil {
assertion.Expected = asserter.GetExpected()
assertion.Actual = asserter.GetActual()
testCase.Assertions = append(testCase.Assertions, assertion)
}
}
}
type Asserter interface {
Assert(value interface{}) error
GetExpected() string
GetActual() string
}
func NewEqAsserter(expected interface{}) Asserter {
return &eqAsserter{
expected: expected,
}
}
type eqAsserter struct {
expected interface{}
actual interface{}
}
func (a *eqAsserter) Assert(value interface{}) error {
switch a.expected.(type) {
case int8, int, int16, int32, int64:
switch v := value.(type) {
case float64:
a.actual = int(v)
case string:
i, err := strconv.Atoi(fmt.Sprintf("%v", value))
if err != nil {
return err
}
a.actual = i
default:
a.actual = value
}
default:
a.actual = value
}
return validation.In(a.expected).Validate(a.actual)
}
func (a *eqAsserter) GetExpected() string {
return fmt.Sprint(a.expected)
}
func (a *eqAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewPositiveAsserter() Asserter {
return &minAsserter{
expected: 1,
}
}
func NewMinAsserter(expected float64) Asserter {
return &minAsserter{
expected: expected,
}
}
type minAsserter struct {
expected float64
actual interface{}
}
func (a *minAsserter) Assert(value interface{}) error {
a.actual = value
return validation.Min(a.expected).Validate(value)
}
func (a *minAsserter) GetExpected() string {
return fmt.Sprintf("great than %f", a.expected)
}
func (a *minAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewMaxAsserter(expected float64) Asserter {
return &maxAsserter{
expected: expected,
}
}
type maxAsserter struct {
expected float64
actual interface{}
}
func (a *maxAsserter) Assert(value interface{}) error {
a.actual = value
return validation.Max(a.expected).Validate(value)
}
func (a *maxAsserter) GetExpected() string {
return fmt.Sprintf("less than %f", a.expected)
}
func (a *maxAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewRangeAsserter(min, max interface{}) Asserter {
return &rangeAsserter{
min: min,
max: max,
}
}
type rangeAsserter struct {
min interface{}
max interface{}
actual interface{}
}
func (a *rangeAsserter) Assert(value interface{}) error {
a.actual = value
return validation.Validate(value, validation.Min(a.min), validation.Max(a.max))
}
func (a *rangeAsserter) GetExpected() string {
return fmt.Sprintf("great than %v and less than %v", a.min, a.max)
}
func (a *rangeAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewRegexAsserter(expr string) Asserter {
return ®exAsserter{
expected: expr,
}
}
type regexAsserter struct {
expected string
actual interface{}
}
func (a *regexAsserter) Assert(value interface{}) error {
a.actual = value
return validation.Match(regexp.MustCompile(a.expected)).Validate(value)
}
func (a *regexAsserter) GetExpected() string {
return a.expected
}
func (a *regexAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewEmptyAsserter() Asserter {
return &emptyAsserter{}
}
type emptyAsserter struct {
actual interface{}
}
func (a *emptyAsserter) Assert(value interface{}) error {
a.actual = value
return validation.Empty.Validate(value)
}
func (a *emptyAsserter) GetExpected() string {
return "nil"
}
func (a *emptyAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewDateAsserter(layout string) Asserter {
var expected string
switch layout {
case common.ExpressionDateLayoutRFC3339:
expected = time.RFC3339
case common.ExpressionDateLayoutRFC3339Nano:
expected = time.RFC3339Nano
default:
expected = layout
}
return &dateAsserter{
expected: expected,
}
}
type dateAsserter struct {
expected string
actual interface{}
}
func (a *dateAsserter) Assert(value interface{}) error {
a.actual = value
return validation.Date(a.expected).Validate(value)
}
func (a *dateAsserter) GetExpected() string {
return fmt.Sprintf("format %s", a.expected)
}
func (a *dateAsserter) GetActual() string {
return fmt.Sprint(a.actual)
}
func NewContainsAsserter(expr string) Asserter {
return &containsAsserter{
expected: expr,
}
}
type containsAsserter struct {
expected string
actual interface{}
}
func (a *containsAsserter) Assert(value interface{}) error {
a.actual = value
if strings.Contains(fmt.Sprint(value), a.expected) {
return nil
}
return errors.New(a.GetExpected())
}
func (a *containsAsserter) GetExpected() string {
return fmt.Sprintf("must contains %s", a.expected)
}
func (a *containsAsserter) GetActual() string {
return fmt.Sprint(a.actual)
} | tester/asserter.go | 0.604866 | 0.48871 | asserter.go | starcoder |
package main
import (
"fmt"
"math"
)
// location with a latitude, longitude.
type location struct {
lat, long float64
}
// coordinate in degrees, minutes, seconds in a N/S/E/W hemisphere.
type coordinate struct {
d, m, s float64
h rune
}
// newLocation from latitude, longitude d/m/s coordinates.
func newLocation(lat, long coordinate) location {
return location{lat.decimal(), long.decimal()}
}
// decimal converts a d/m/s coordinate to decimal degrees.
func (c coordinate) decimal() float64 {
sign := 1.0
switch c.h {
case 'S', 'W', 's', 'w':
sign = -1
}
return sign * (c.d + c.m/60 + c.s/3600)
}
// world with a volumetric mean radius in kilometers
type world struct {
radius float64
}
// distance calculation using the Spherical Law of Cosines.
func (w world) distance(p1, p2 location) float64 {
s1, c1 := math.Sincos(rad(p1.lat))
s2, c2 := math.Sincos(rad(p2.lat))
clong := math.Cos(rad(p1.long - p2.long))
return w.radius * math.Acos(s1*s2+c1*c2*clong)
}
// rad converts degrees to radians.
func rad(deg float64) float64 {
return deg * math.Pi / 180
}
var (
mars = world{radius: 3389.5}
earth = world{radius: 6371}
)
func main() {
spirit := newLocation(coordinate{14, 34, 6.2, 'S'}, coordinate{175, 28, 21.5, 'E'})
opportunity := newLocation(coordinate{1, 56, 46.3, 'S'}, coordinate{354, 28, 24.2, 'E'})
curiosity := newLocation(coordinate{4, 35, 22.2, 'S'}, coordinate{137, 26, 30.12, 'E'})
insight := newLocation(coordinate{4, 30, 0.0, 'N'}, coordinate{135, 54, 0, 'E'})
fmt.Printf("Spirit to Opportunity %.2f km\n", mars.distance(spirit, opportunity))
fmt.Printf("Spirit to Curiosity %.2f km\n", mars.distance(spirit, curiosity))
fmt.Printf("Spirit to InSight %.2f km\n", mars.distance(spirit, insight))
fmt.Printf("Opportunity to Curiosity %.2f km\n", mars.distance(opportunity, curiosity))
fmt.Printf("Opportunity to InSight %.2f km\n", mars.distance(opportunity, insight))
fmt.Printf("Curiosity to InSight %.2f km\n", mars.distance(curiosity, insight))
london := newLocation(coordinate{51, 30, 0, 'N'}, coordinate{0, 8, 0, 'W'})
paris := newLocation(coordinate{48, 51, 0, 'N'}, coordinate{2, 21, 0, 'E'})
fmt.Printf("London to Paris %.2f km\n", earth.distance(london, paris))
edmonton := newLocation(coordinate{53, 32, 0, 'N'}, coordinate{113, 30, 0, 'W'})
ottawa := newLocation(coordinate{45, 25, 0, 'N'}, coordinate{75, 41, 0, 'W'})
fmt.Printf("Hometown to Capital %.2f km\n", earth.distance(edmonton, ottawa))
mountSharp := newLocation(coordinate{5, 4, 48, 'S'}, coordinate{137, 51, 0, 'E'})
olympusMons := newLocation(coordinate{18, 39, 0, 'N'}, coordinate{226, 12, 0, 'E'})
fmt.Printf("Mount Sharp to Olympus Mons %.2f km\n", mars.distance(mountSharp, olympusMons))
} | solutions/lesson22/distance/distance.go | 0.825062 | 0.466967 | distance.go | starcoder |
package skein
const (
Key int = 0
Config int = 4
Personalization int = 8
PublicKey int = 12
KeyIdentifier int = 16
Nonce int = 20
Message int = 48
Out int = 63
)
const t1FlagFinal = uint64(1) << 63
const t1FlagFirst = uint64(1) << 62
const t1FlagBitPad = uint64(1) << 55
type ubiTweak struct {
tweak [2]uint64
}
func newUbiTweak() *ubiTweak {
return new(ubiTweak)
}
/**
* Get status of the first block flag.
*/
func (u *ubiTweak) isFirstBlock() bool {
return (u.tweak[1] & t1FlagFirst) != 0
}
/**
* Sets status of the first block flag.
*/
func (u *ubiTweak) setFirstBlock(value bool) {
if value {
u.tweak[1] |= t1FlagFirst
} else {
u.tweak[1] &^= t1FlagFirst
}
}
/**
* Gets status of the final block flag.
*/
func (u *ubiTweak) isFinalBlock() bool {
return (u.tweak[1] & t1FlagFinal) != 0
}
/**
* Sets status of the final block flag.
*/
func (u *ubiTweak) setFinalBlock(value bool) {
if value {
u.tweak[1] |= t1FlagFinal
} else {
u.tweak[1] &^= t1FlagFinal
}
}
/**
* Gets status of the final block flag.
*/
func (u *ubiTweak) isBitPad() bool {
return (u.tweak[1] & t1FlagBitPad) != 0
}
/**
* Sets status of the final block flag.
*/
func (u *ubiTweak) setBitPad(value bool) {
if value {
u.tweak[1] |= t1FlagBitPad
} else {
u.tweak[1] &^= t1FlagBitPad
}
}
/**
* Gets the current tree level.
*/
func (u *ubiTweak) getTreeLevel() byte {
return byte((u.tweak[1] >> 48) & 0x7f)
}
/**
* Set the current tree level.
*
* @param value
* the tree level
*/
func (u *ubiTweak) setTreeLevel(value int) {
u.tweak[1] &^= uint64(0x7f) << 48
u.tweak[1] |= uint64(value) << 48
}
/**
* Gets the number of bytes processed so far, inclusive.
*
* @return
* Number of processed bytes.
*/
func (u *ubiTweak) getBitsProcessed() (low, high uint64) {
low = u.tweak[0]
high = u.tweak[1] & 0xffffffff
return
}
/**
* Set the number of bytes processed so far
*
* @param value
* The number of bits to set - low 64 bits
*/
func (u *ubiTweak) setBitsProcessed(value uint64) {
u.tweak[0] = value
u.tweak[1] &= 0xffffffff00000000
}
/**
* Add number of processed bytes.
*
* Adds the integer value to the 96-bit field of processed
* bytes.
*
* @param value
* Number of processed bytes.
*/
func (u *ubiTweak) addBytesProcessed(value int) {
const len = 3
carry := uint64(value)
var words [len]uint64
words[0] = u.tweak[0] & 0xffffffff
words[1] = (u.tweak[0] >> 32) & 0xffffffff
words[2] = u.tweak[1] & 0xffffffff
for i := 0; i < len; i++ {
carry += words[i]
words[i] = carry
carry >>= 32
}
u.tweak[0] = words[0] & 0xffffffff
u.tweak[0] |= (words[1] & 0xffffffff) << 32
u.tweak[1] |= words[2] & 0xffffffff
}
/**
* Get the current UBI block type.
*/
func (u *ubiTweak) getBlockType() uint64 {
return (u.tweak[1] >> 56) & 0x3f
}
/**
* Set the current UBI block type.
*
* @param value
* Block type
*/
func (u *ubiTweak) setBlockType(value uint64) {
u.tweak[1] = value << 56
}
/**
* Starts a new UBI block type by setting BitsProcessed to zero, setting
* the first flag, and setting the block type.
*
* @param type
* The UBI block type of the new block
*/
func (u *ubiTweak) startNewBlockType(t uint64) {
u.setBitsProcessed(0)
u.setBlockType(t)
u.setFirstBlock(true)
}
/**
* @return the tweak
*/
func (u *ubiTweak) getTweak() []uint64 {
return u.tweak[:]
}
/**
* @param word0
* the lower word of the tweak
* @param word1
* the upper word of the tweak
*/
func (u *ubiTweak) setTweak(tw []uint64) {
u.tweak[0] = tw[0]
u.tweak[1] = tw[1]
} | vendor/github.com/gxed/hashland/skein/ubiTweak.go | 0.678114 | 0.419113 | ubiTweak.go | starcoder |
package log
// Start is used for the entry into a function.
func Start(context interface{}, function string) {
Up1.Start(context, function)
}
// Startf is used for the entry into a function with a formatted message.
func Startf(context interface{}, function string, format string, a ...interface{}) {
Up1.Startf(context, function, format, a...)
}
// Complete is used for the exit of a function.
func Complete(context interface{}, function string) {
Up1.Complete(context, function)
}
// Completef is used for the exit of a function with a formatted message.
func Completef(context interface{}, function string, format string, a ...interface{}) {
Up1.Completef(context, function, format, a...)
}
// CompleteErr is used to write an error with complete into the trace.
func CompleteErr(err error, context interface{}, function string) {
Up1.CompleteErr(err, context, function)
}
// CompleteErrf is used to write an error with complete into the trace with a formatted message.
func CompleteErrf(err error, context interface{}, function string, format string, a ...interface{}) {
Up1.CompleteErrf(err, context, function, format, a...)
}
// Err is used to write an error into the trace.
func Err(err error, context interface{}, function string) {
Up1.Err(err, context, function)
}
// Errf is used to write an error into the trace with a formatted message.
func Errf(err error, context interface{}, function string, format string, a ...interface{}) {
Up1.Errf(err, context, function, format, a...)
}
// ErrFatal is used to write an error into the trace then terminate the program.
func ErrFatal(err error, context interface{}, function string) {
Up1.ErrFatal(err, context, function)
}
// ErrFatalf is used to write an error into the trace with a formatted message then terminate the program.
func ErrFatalf(err error, context interface{}, function string, format string, a ...interface{}) {
Up1.ErrFatalf(err, context, function, format, a...)
}
// ErrPanic is used to write an error into the trace then panic the program.
func ErrPanic(err error, context interface{}, function string) {
Up1.ErrPanic(err, context, function)
}
// ErrPanicf is used to write an error into the trace with a formatted message then panic the program.
func ErrPanicf(err error, context interface{}, function string, format string, a ...interface{}) {
Up1.ErrPanicf(err, context, function, format, a...)
}
// Tracef is used to write information into the trace with a formatted message.
func Tracef(context interface{}, function string, format string, a ...interface{}) {
Up1.Tracef(context, function, format, a...)
}
// Warnf is used to write a warning into the trace with a formatted message.
func Warnf(context interface{}, function string, format string, a ...interface{}) {
Up1.Warnf(context, function, format, a...)
}
// Queryf is used to write a query into the trace with a formatted message.
func Queryf(context interface{}, function string, format string, a ...interface{}) {
Up1.Queryf(context, function, format, a...)
}
// DataKV is used to write a key/value pair into the trace.
func DataKV(context interface{}, function string, key string, value interface{}) {
Up1.DataKV(context, function, key, value)
}
// DataBlock is used to write a block of data into the trace.
func DataBlock(context interface{}, function string, block interface{}) {
Up1.DataBlock(context, function, block)
}
// DataString is used to write a string with CRLF each on their own line.
func DataString(context interface{}, function string, message string) {
Up1.DataString(context, function, message)
}
// DataTrace is used to write a block of data from an io.Stringer respecting each line.
func DataTrace(context interface{}, function string, formatters ...Formatter) {
Up1.DataTrace(context, function, formatters...)
}
// Splunk is used to write a log message in a splunk-able format.
func Splunk(m ...SplunkPair) {
Up1.Splunk(m...)
} | log/log_calls.go | 0.50415 | 0.412589 | log_calls.go | starcoder |
package ndarray
type Array struct {
dims *Shape
Data []float64
Length int
}
// ---------------------------------------------------------------
func (this *Array) DataCopy() []float64 {
d := make([]float64, len(this.Data))
copy(d, this.Data)
return d
}
func (this Array) Dims() (rows, columns int) {
return this.dims.Rows(), this.dims.Columns()
}
func (this Array) Dim(index int) int {
return this.dims.Dim(index)
}
func (this *Array) Row(i int) []float64 {
row := make([]float64, this.dims.Columns())
for j := range row {
row[j] = this.At(i, j)
}
return row
}
func (this *Array) Column(j int) []float64 {
columns := make([]float64, this.dims.Rows())
for i := range columns {
columns[j] = this.At(i, j)
}
return columns
}
func (this *Array) AsScalar() float64 {
return this.Data[0]
}
func (this Array) At(r, c int) float64 {
return this.Data[r*this.dims.Columns()+c]
}
func (this *Array) Set(r, c int, value float64) {
this.Data[r*this.dims.Columns()+c] = value
}
// ---------------------------------------------------------------
func (this *Array) Equal(with *Array) bool {
equal := true
for i, v := range this.Data {
if v != with.Data[i] {
equal = false
break
}
}
return equal
}
func (this *Array) EqualDims(with *Array) bool {
equal := true
for i, v := range this.dims.dims {
if v != with.Dim(i) {
equal = false
break
}
}
return equal
}
func (this *Array) Inverse() *Array {
return this.Scale(-1)
}
func (this Array) IsScalar() bool {
r, c := this.Dims()
if r == 1 && c == 1 {
return true
}
return false
}
func (this Array) IsVec() bool {
r, c := this.Dims()
if r == 1 && c > 1 || r > 1 && c == 1 {
return true
}
return false
}
func (this Array) IsMatrix() bool {
r, c := this.Dims()
if r > 1 && c > 1 {
return true
}
return false
}
func (this Array) Type() int {
r, c := this.Dims()
if r == 0 || c == 0 {
return TYPE_EMPTY
} else if r == 1 && c == 1 {
return TYPE_SCALER
} else if (r == 1 && c > 1) || (r > 1 && c == 1) {
return TYPE_VEC
} else if r > 1 && c > 1 {
return TYPE_MATRIX
}
return TYPE_N
} | ndarray.go | 0.594198 | 0.543348 | ndarray.go | starcoder |
package imaging
import (
"image"
"image/color"
"math"
"golang.org/x/image/draw"
)
// Resize creates a copy of the given image, scaled to the given rectangle.
func Resize(i image.Image, width float64) image.Image {
scaledSize := int(math.Round(width))
size := image.Rect(0, 0, scaledSize, scaledSize)
dst := image.NewRGBA(size)
// nearst neighbour preserves pixel-struture of masks (i.e. for Pencil)
s := draw.NearestNeighbor
s.Scale(dst, size, i, i.Bounds(), draw.Over, nil)
return dst
}
// CreateMask creates a mask image by using the gray value of the given image
// as the value for the mask alpha channel.
// Returns the mask image.
func CreateMask(i image.Image) image.Image {
rect := i.Bounds()
mask := image.NewRGBA(rect)
x0 := rect.Min.X
x1 := rect.Max.X
y0 := rect.Min.Y
y1 := rect.Max.Y
var gray uint8
var r, g, b uint32
for x := x0; x < x1; x++ {
for y := y0; y < y1; y++ {
r, g, b, _ = i.At(x, y).RGBA()
gray = uint8((r + g + b) / 3)
mask.Set(x, y, color.RGBA{0, 0, 0, gray})
}
}
return mask
}
// ApplyOpacity applies the given opacity (0.0..1.0) to the given image.
// This method returns a new image where the alpha channel is a combination
// of the source alpha and the opacity.
func ApplyOpacity(i image.Image, opacity float64) image.Image {
alpha := uint8(math.Round(255 * opacity))
mask := image.NewUniform(color.Alpha{alpha})
rect := i.Bounds()
dst := image.NewRGBA(rect)
draw.DrawMask(dst, rect, i, image.Point{}, mask, image.Point{}, draw.Over)
return dst
}
// Rotate the given image counter-clockwise by angle (radians) degrees.
// Rotation is around the center of the source image.
// Returns an image with the rotated pixels.
func Rotate(angle float64, i image.Image) image.Image {
// Size of the source image
box := i.Bounds()
xMax := box.Max.X
yMax := box.Max.Y
// Create the destination image.
// The dst size is the diagonal accross the source Rectangle.
a := float64(box.Max.X - box.Min.X)
b := float64(box.Max.Y - box.Min.Y)
c := math.Sqrt(math.Pow(a, 2) + math.Pow(b, 2))
size := int(math.Ceil(c))
dst := image.NewRGBA(image.Rect(0, 0, size, size))
// Rotation around center instead of origin
// means: Translate - Rotate - Translate
t0 := translation(-a/2, -b/2)
rot := rotation(angle)
t1 := translation(a/2, b/2)
// Transform each pixel and set it on the destination image.
var tx, ty float64
for x := 0; x < xMax; x++ {
for y := 0; y < yMax; y++ {
tx, ty = float64(x), float64(y)
tx, ty = transform(t0, tx, ty)
tx, ty = transform(rot, tx, ty)
tx, ty = transform(t1, tx, ty)
tx = math.Round(tx)
ty = math.Round(ty)
dst.Set(int(tx), int(ty), i.At(x, y))
}
}
return dst
}
// ToGray creates a grayscale version of the given image.
func ToGray(i image.Image) image.Image {
b := i.Bounds()
g := image.NewGray(b)
for x := 0; x < b.Max.X; x++ {
for y := 0; y < b.Max.Y; y++ {
g.Set(x, y, i.At(x, y))
}
}
return g
} | internal/imaging/imaging.go | 0.870212 | 0.665906 | imaging.go | starcoder |
package models
// Dataset: Earnings by place of work
// Dimensions: Sex | Employment status
// Variables: gross weekly pay, weekly pay excluding overtime
// Table
// Observation | Variable (Earnings)| Sex | Employment status
// 123 | Gross weekly pay | Male | Full Time
// 70 | Gross weekly pay | Male | Part Time
// 119 | Gross weekly pay | Female| Full Time
// 70 | Gross weekly pay | Female| Part Time
// 123 | weekly pay excluding overtime | Male | Full Time
// 70 | weekly pay excluding overtime | Male | Part Time
// 119 | weekly pay excluding overtime | Female| Full Time
// 70 | weekly pay excluding overtime | Female| Part Time
// Table - Observation | DimensionID | DimensionOptionID | DimensionOptionLabel
// Observation | Geography ID | Geography Label | Sex ID | Sex Label | Age ID | Age Label | Residence Type ID | Residence Type Label
// 105 | K04000001 | England and Wales | 1 | Females | 1 | 50+ | 1 | Lives in a communal establishment
// human readable flag - include labels / replace them?
// The csv output should not rely on fixed column locations. columns should be identified by their header value/ label.
// by doing this we can remove all of the blank
//Denormalisation
// ---------------
// The ID / details / label for the dimension can be held at the dataset level - it should not be repeated throughout the table.
// Fixed dimension options - if the dimension only ever has one value for the dataset, we can define it as a fixed dimension.
// This prevents it being repeated for each observation.
// Create ID's for dimensions and their options
// when multiple datasets have the same dimensions they can be the same ID instead of having various string representations of the same thing.
// e.g. year can mean different things in different datasets - financial year or calendar year
// can we translate dimensions to ID's as part of the data baker step??
type Datasets struct {
Items []*Dataset `json:"items,omitempty"`
Count int `json:"count"`
Total int `json:"total"`
StartIndex int `json:"startIndex"`
ItemsPerPage int `json:"itemsPerPage"`
}
type Dataset struct {
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url,omitempty"`
Metadata *Metadata `json:"metadata,omitempty"`
Dimensions []*Dimension `json:"dimensions,omitempty"`
Data *Table `json:"data,omitempty"`
}
type Metadata struct {
Description string `json:"description,omitempty"`
Taxonomies []string `json:"taxonomies,omitempty"`
}
type Dimension struct {
ID string `json:"id"`
Name string `json:"name"` // Sex
Options []*DimensionOption `json:"options,omitempty"`
SelectedOption *DimensionOption `json:"selectedOption,omitempty"`
}
type DimensionOption struct {
ID string `json:"id"`
Name string `json:"name"` // Male
Options []*DimensionOption `json:"options,omitempty"`
}
type Row struct {
Observation interface{} // 123
Dimensions []*DimensionOption // Sex=Male
}
type Table struct {
Rows []*Row
} | models/dataset.go | 0.70028 | 0.592637 | dataset.go | starcoder |
package te
import (
"fmt"
"sort"
"strings"
"time"
)
// Expression represents a temporal expression.
type Expression interface {
IsActive(t time.Time) bool
Next(t time.Time) time.Time
}
type hourExpr int
func (expr hourExpr) IsActive(t time.Time) bool {
return t.Hour() == int(expr)
}
func (expr hourExpr) Next(t time.Time) time.Time {
year, month, day := t.Date()
loc := t.Location()
next := time.Date(year, month, day, int(expr), 0, 0, 0, loc)
if t.Equal(next) || t.After(next) {
next = next.AddDate(0, 0, 1)
}
return next
}
func (expr hourExpr) GoString() string {
return fmt.Sprintf("te.Hour(%d)", int(expr))
}
type hourlyExpr struct {
n int
d time.Duration
}
func (expr hourlyExpr) IsActive(t time.Time) bool {
return t.Hour()%expr.n == 0
}
func (expr hourlyExpr) Next(t time.Time) time.Time {
year, month, day := t.Date()
hour := t.Hour()
loc := t.Location()
next := time.Date(year, month, day, hour+expr.n-(hour%expr.n), 0, 0, 0, loc)
if next.Day() != day {
next = time.Date(year, month, day+1, 0, 0, 0, 0, loc)
}
return next
}
func (expr hourlyExpr) GoString() string {
return fmt.Sprintf("te.Hourly(%d)", expr.n)
}
type minuteExpr int
func (expr minuteExpr) IsActive(t time.Time) bool {
return t.Minute() == int(expr)
}
func (expr minuteExpr) Next(t time.Time) time.Time {
year, month, day := t.Date()
hour := t.Hour()
loc := t.Location()
next := time.Date(year, month, day, hour, int(expr), 0, 0, loc)
if t.Equal(next) || t.After(next) {
next = next.Add(time.Hour)
}
return next
}
func (expr minuteExpr) GoString() string {
return fmt.Sprintf("te.Minute(%d)", int(expr))
}
type minutelyExpr struct {
n int
d time.Duration
}
func (expr minutelyExpr) IsActive(t time.Time) bool {
return t.Minute()%expr.n == 0
}
func (expr minutelyExpr) Next(t time.Time) time.Time {
year, month, day := t.Date()
hour, min, _ := t.Clock()
loc := t.Location()
next := time.Date(year, month, day, hour, min+expr.n-(min%expr.n), 0, 0, loc)
if next.Hour() != hour {
next = time.Date(year, month, day, hour+1, 0, 0, 0, loc)
}
return next
}
func (expr minutelyExpr) GoString() string {
return fmt.Sprintf("te.Minutely(%d)", expr.n)
}
type secondExpr int
func (expr secondExpr) IsActive(t time.Time) bool {
return t.Second() == int(expr)
}
func (expr secondExpr) Next(t time.Time) time.Time {
year, month, day := t.Date()
hour, min, _ := t.Clock()
loc := t.Location()
next := time.Date(year, month, day, hour, min, int(expr), 0, loc)
if t.Equal(next) || t.After(next) {
next = next.Add(time.Minute)
}
return next
}
func (expr secondExpr) GoString() string {
return fmt.Sprintf("te.Second(%d)", int(expr))
}
type secondlyExpr struct {
n int
d time.Duration
}
func (expr secondlyExpr) IsActive(t time.Time) bool {
return t.Second()%expr.n == 0
}
func (expr secondlyExpr) Next(t time.Time) time.Time {
year, month, day := t.Date()
hour, min, sec := t.Clock()
loc := t.Location()
next := time.Date(year, month, day, hour, min, sec+expr.n-(sec%expr.n), 0, loc)
if next.Minute() != min {
next = time.Date(year, month, day, hour, min+1, 0, 0, loc)
}
return next
}
func (expr secondlyExpr) GoString() string {
return fmt.Sprintf("te.Secondly(%d)", expr.n)
}
type dayExpr int
func (expr dayExpr) IsActive(t time.Time) bool {
return t.Day() == int(expr)
}
func (expr dayExpr) Next(t time.Time) time.Time {
loc := t.Location()
next := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, loc)
if int(expr) > 0 {
next = next.AddDate(0, 0, int(expr)-1)
} else {
next = next.AddDate(0, 1, -1)
}
if t.Equal(next) || t.After(next) {
next = next.AddDate(0, 1, 0)
if !expr.IsActive(next) {
return expr.Next(next)
}
}
return next
}
func (expr dayExpr) GoString() string {
return fmt.Sprintf("te.Day(%d)", int(expr))
}
type weekdayExpr time.Weekday
func (expr weekdayExpr) IsActive(t time.Time) bool {
return t.Weekday() == time.Weekday(expr)
}
func (expr weekdayExpr) Next(t time.Time) time.Time {
loc := t.Location()
year, month, day := t.Date()
next := time.Date(year, month, day, 0, 0, 0, 0, loc)
days := int(time.Weekday(expr) - t.Weekday())
if days <= 0 {
days += 7
}
return next.AddDate(0, 0, days)
}
func (expr weekdayExpr) GoString() string {
return fmt.Sprintf("te.Weekday(time.%s)", time.Weekday(expr))
}
type monthExpr time.Month
func (expr monthExpr) IsActive(t time.Time) bool {
return t.Month() == time.Month(expr)
}
func (expr monthExpr) Next(t time.Time) time.Time {
loc := t.Location()
next := time.Date(t.Year(), time.Month(expr), 1, 0, 0, 0, 0, loc)
if t.Equal(next) || t.After(next) {
next = next.AddDate(1, 0, 0)
}
return next
}
func (expr monthExpr) GoString() string {
return fmt.Sprintf("te.Month(time.%s)", time.Month(expr))
}
type yearExpr int
func (expr yearExpr) IsActive(t time.Time) bool {
return t.Year() == int(expr)
}
func (expr yearExpr) Next(t time.Time) time.Time {
return time.Time{}
}
func (expr yearExpr) GoString() string {
return fmt.Sprintf("te.Year(%d)", int(expr))
}
type dateRangeExpr struct {
t1 time.Time
t2 time.Time
}
func (expr dateRangeExpr) IsActive(t time.Time) bool {
t1 := dateFrom(t, expr.t1)
t2 := dateFrom(t, expr.t2)
return isBetween(t, t1, t2)
}
func (expr dateRangeExpr) Next(t time.Time) time.Time {
next := dateFrom(t, expr.t1)
if t.Equal(next) || t.After(next) {
next = next.AddDate(1, 0, 0)
}
return next
}
func (expr dateRangeExpr) GoString() string {
return fmt.Sprintf("te.DateRange(time.%s, %d, time.%s, %d)",
expr.t1.Month(), expr.t1.Day(),
expr.t2.Month(), expr.t2.Day())
}
type timeRangeExpr struct {
t1 time.Time
t2 time.Time
}
func (expr timeRangeExpr) IsActive(t time.Time) bool {
t1 := timeFrom(t, expr.t1)
t2 := timeFrom(t, expr.t2)
return isBetween(t, t1, t2)
}
func (expr timeRangeExpr) Next(t time.Time) time.Time {
next := timeFrom(t, expr.t1)
if t.Equal(next) || t.After(next) {
next = next.AddDate(0, 0, 1)
}
return next
}
func (expr timeRangeExpr) GoString() string {
return fmt.Sprintf("te.TimeRange(%d, %d, %d, %d, %d, %d)",
expr.t1.Hour(), expr.t1.Minute(), expr.t1.Second(),
expr.t2.Hour(), expr.t2.Minute(), expr.t2.Second())
}
type unionExpr []Expression
func (expr unionExpr) IsActive(t time.Time) bool {
for _, e := range expr {
if e.IsActive(t) {
return true
}
}
return false
}
func (expr unionExpr) Next(t time.Time) time.Time {
ts := make(byTime, len(expr))
for i, e := range expr {
ts[i] = e.Next(t)
}
sort.Sort(ts)
return ts[0]
}
func (expr unionExpr) GoString() string {
return formatExpr("Union", expr)
}
type intersectExpr []Expression
func (expr intersectExpr) IsActive(t time.Time) bool {
for _, e := range expr {
if !e.IsActive(t) {
return false
}
}
return true
}
func (expr intersectExpr) Next(t time.Time) time.Time {
ts := make(byTime, 0)
for _, e := range expr {
next := e.Next(t)
if next.IsZero() {
if !e.IsActive(t) {
return time.Time{}
}
continue
}
ts = append(ts, next)
}
sort.Sort(ts)
t = ts[0]
if expr.IsActive(t) {
return t
}
return expr.Next(t)
}
func (expr intersectExpr) GoString() string {
return formatExpr("Intersect", expr)
}
type exceptExpr []Expression
func (expr exceptExpr) IsActive(t time.Time) bool {
for _, e := range expr {
if e.IsActive(t) {
return false
}
}
return true
}
func (expr exceptExpr) Next(t time.Time) time.Time {
ts := make(byTime, len(expr))
for i, e := range expr {
ts[i] = e.Next(t)
}
sort.Sort(ts)
return ts[0]
}
func (expr exceptExpr) GoString() string {
return formatExpr("Except", expr)
}
type nilExpr struct{}
func (expr nilExpr) IsActive(t time.Time) bool { return false }
func (expr nilExpr) Next(t time.Time) time.Time { return time.Time{} }
type byTime []time.Time
func (ts byTime) Len() int { return len(ts) }
func (ts byTime) Less(i, j int) bool { return ts[i].Before(ts[j]) }
func (ts byTime) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
func dateFrom(t, date time.Time) time.Time {
loc := t.Location()
_, month, day := date.Date()
return time.Date(t.Year(), month, day, 0, 0, 0, 0, loc)
}
func timeFrom(t, clock time.Time) time.Time {
loc := t.Location()
year, month, day := t.Date()
hour, min, sec := clock.Clock()
return time.Date(year, month, day, hour, min, sec, 0, loc)
}
func isBetween(t, t1, t2 time.Time) bool {
return (t.Equal(t1) || t.After(t1)) && (t.Equal(t2) || t.Before(t2))
}
func formatExpr(kind string, expr []Expression) string {
var s strings.Builder
s.WriteString("te.")
s.WriteString(kind)
s.WriteString("(")
for i, e := range expr {
s.WriteString(fmt.Sprintf("%#v", e))
if i != len(expr)-1 {
s.WriteString(", ")
}
}
s.WriteString(")")
return s.String()
} | expressions.go | 0.696371 | 0.518302 | expressions.go | starcoder |
package main
import (
"os"
"bufio"
"fmt"
"math"
"sort"
)
type point struct {
X int
Y int
}
func distance(p1 point, p2 point) float64 {
dx, dy := float64(p2.X - p1.X), float64(p2.Y - p1.Y)
return math.Sqrt(math.Pow(dx, 2) + math.Pow(dy, 2))
}
func angle(p1 point, p2 point) float64 {
dx, dy := float64(p2.X - p1.X), float64(p2.Y - p1.Y)
return math.Atan2(dx, dy)
}
func determineBestAsteroid(asteroids []point) (int, point) {
mostHits := 0
bestPoint := point{}
for _, ast1 := range asteroids {
set := map[float64]bool{}
for _, ast2 := range asteroids {
if ast1.X != ast2.X || ast1.Y != ast2.Y {
angle := angle(ast1, ast2)
set[angle] = true
}
}
if len(set) > mostHits {
mostHits = len(set)
bestPoint = ast1
}
}
return mostHits, bestPoint
}
func determineVaporizationOrder(from point, asteroids []point) []point {
vaporizedAsteroids := []point{from}
visitedAsteroids := map[point]bool{}
type AsteroidToVisit struct {
Angle float64
Point point
}
for len(vaporizedAsteroids) != len(asteroids) {
possibleTargets := map[float64]point{}
// determining the closest non-vaporized asteroid for each angle
for _, asteroid := range asteroids {
_, present := visitedAsteroids[asteroid]
if !present && asteroid != from {
angle := angle(from, asteroid)
currentPoint, ok := possibleTargets[angle]
if !ok || distance(currentPoint, from) > distance(asteroid, from) {
possibleTargets[angle] = asteroid
}
}
}
// sorting the asteroids in clockwise order
toVisit := []AsteroidToVisit{}
for k, v := range possibleTargets {
toVisit = append(toVisit, AsteroidToVisit{k, v})
}
sort.Slice(toVisit, func(i, j int) bool {
return toVisit[i].Angle > toVisit[j].Angle
})
// marking the asteroids as vaporized
for _, ast := range toVisit {
vaporizedAsteroids = append(vaporizedAsteroids, ast.Point)
visitedAsteroids[ast.Point] = true
}
}
return vaporizedAsteroids
}
func main() {
file, _ := os.Open("input")
defer file.Close()
scanner := bufio.NewScanner(file)
m := []point{}
for y := 0; scanner.Scan(); y++ {
line := scanner.Text()
for x := 0; x < len(line); x++ {
if string(line[x]) == "#" {
m = append(m, point{x, y})
}
}
}
hits, bestAsteroid := determineBestAsteroid(m)
vaporized := determineVaporizationOrder(bestAsteroid, m)
fmt.Printf("Part 1: %d\nPart 2: %d\n", hits, vaporized[200].X * 100 + vaporized[200].Y)
} | Day 10/main.go | 0.732687 | 0.465691 | main.go | starcoder |
package mysql_nodejs
import (
. "github.com/gocircuit/circuit/gocircuit.org/render"
)
func RenderApp() string {
return RenderHtml("Write the circuit app", Render(appBody, nil))
}
const appBody = `
<h1>Write the circuit app</h1>
<p>In this section we are going to write a Go program (the circuit app),
which when executed will connect to the circuit cluster and deploy
the tutorial's MySQL/Node.js-based web service using two hosts from
the cluster.
<p>The source of the finished app is located in:
<pre>
$GOPATH/github.com/gocircuit/circuit/tutorial/nodejs-using-mysql/start-app/main.go
</pre>
<h2>First strokes</h2>
<p>This is going to be a single source-file Go program, which will expect exactly one command-line
parameter, <code>-addr</code>, specifying the circuit address to connect into. As
a start, the program will look like this:
<pre>
package main
import (
"flag"
"github.com/gocircuit/circuit/client"
)
var flagAddr = flag.String("addr", "", "circuit server address (looks like circuit://...)")
func fatalf(format string, arg ...interface{}) {
println(fmt.Sprintf(format, arg...))
os.Exit(1)
}
func main() {
flag.Parse()
…
}
</pre>
<p>Notable here is the import of the circuit client package <code>"github.com/gocircuit/circuit/client"</code>
and the definition of function <code>fatalf()</code>, which we'll use to report terminal errors.
<h2>Connecting to the cluster</h2>
<p>The next step is to connect into a circuit server (specified by a circuit address) and obtain a client
object that will give us access to the circuit API.
The following subroutine takes a circuit address as an argument and returns a connected client object
as a result:
<pre>
func connect(addr string) *client.Client {
defer func() {
if r := recover(); r != nil {
fatalf("could not connect: %v", r)
}
}()
return client.Dial(addr, nil)
}
</pre>
<p>Note that by convention, the circuit client library universally reports loss
of connection (or inability to establish connection) conditions via panics,
as they can occur anywhere in its methods.
Such panics are normal error conditions, and can be recovered from.
In our case, we prefer to terminate the program with an error message.
<p>The <code>main</code> function can now be updated to:
<pre>
func main() {
flag.Parse()
c := connect(*flagAddr)
…
}
</pre>
<h2>Selecting hosts</h2>
<p>The next goal is to “list” the contents of the circuit cluster and to
choose two hosts out of the inventory — one for the MySQL database
and one for the Node.js front-end service.
<p>The circuit Go API represents all cluster resources in the form of one
big hierarchy of “anchors”. Each anchor can have any number of
uniquely-named sub-anchors, and it can be associated with one
resource (process, server, container, etc.) Anchors are represented
by the interface type <code>client.Anchor</code>.
<p>The client object, of type <code>*client.Client</code>, is itself an
anchor (it implements <code>client.Anchor</code>) and it is in fact
the root anchor of the circuit cluster's virtual hierarchy.
<p>The root anchor is unique in that it is not associated with any
resource and its sub-anchors automatically exactly correspond
to the circuit servers that are presently members of the cluster.
<p>Every anchor has a <code>View</code> method:
<pre>
View() map[string]client.Anchor
</pre>
which returns the sub-anchors of this anchor and their names.
If we invoke the <code>View</code> method of the root anchor,
we obtain a list of anchors corresponding to the currently live
circuit servers.
<p>We are going to use this to write a simple subroutine that blindly
picks a fixed number of hosts out of the available ones, re-using
some hosts if necessary:
<pre>
func pickHosts(c *client.Client, n int) (hosts []client.Anchor) {
defer func() {
if recover() != nil {
fatalf("client connection lost")
}
}()
view := c.View()
if len(view) == 0 {
fatalf("no hosts in cluster")
}
for len(hosts) < n {
for _, a := range view {
if len(hosts) >= n {
break
}
hosts = append(hosts, a)
}
}
return
}
</pre>
<p>Note again here that a panic ensuing from <code>c.View()</code> would
indicate a broken connection between the client and the circuit server, in which
case we prefer to exit the program.
<p>We can further update <code>main</code> to:
<pre>
func main() {
flag.Parse()
c := connect(*flagAddr)
hosts := pickHosts(c, 2)
…
}
</pre>
<p>Before we continue with the main app logic—starting MySQL and starting Node.js—we
are going to make a small detour. We are going to implement a useful subroutine
that executes shell commands and scripts on any desired host directly from the
Go environment of our app.
<h2>A versatile orchestration subroutine</h2>
<p>The function <code>runShellStdin</code> takes an anchor parameter <code>host</code>,
which is expected to be an anchor corresponding to a circuit server. It
executes a desired shell command <code>cmd</code> on the corresponding host,
and it also supplies the string <code>stdin</code> as standard input to the
shell process.
<p>The function waits (blocks) until the shell process terminates and returns its
standard output in the form of a string. If the shell process exits in error, this
is reflected in a non-nil return error value. If the function fails due to loss of
connection (as opposed to due to an unsuccessful exit from the shell process),
<code>runShellStdin</code> will terminate the processes and exit with an error message.
<pre>
func runShellStdin(host client.Anchor, cmd, stdin string) (string, error) {
defer func() {
if recover() != nil {
fatalf("connection to host lost")
}
}()
job := host.Walk([]string{"shelljob", strconv.Itoa(rand.Int())})
proc, _ := job.MakeProc(client.Cmd{
Path: "/bin/sh",
Dir: "/tmp",
Args: []string{"-c", cmd},
Scrub: true,
})
go func() {
io.Copy(proc.Stdin(), bytes.NewBufferString(stdin))
proc.Stdin().Close() // Must close the standard input of the shell process.
}()
proc.Stderr().Close() // Close to indicate discarding standard error
var buf bytes.Buffer
io.Copy(&buf, proc.Stdout())
stat, _ := proc.Wait()
return buf.String(), stat.Exit
}
</pre>
<p>Let's break down what this function accomplishes:
<ol>
<li><pre>
defer func() {
if recover() != nil {
fatalf("connection to host lost")
}
}()
</pre>
<p>The <code>defer</code> statement catches panics that may arise from the circuit API calls.
By convention, any such panic indicates that either (i) the particular host we are manipulating
(through the methods of the anchor object) has become disconnected from the cluster, or
(ii) our client has lost connection to the circuit server that it initially connected to, using <code>client.Dial</code>.
<p>In this example, we prefer to terminate the app if we encounter loss of connectivity of either kind.
<p>In general, one could detect whether (i) or (ii) was the cause for the panic.
For instance, if a subsequent call to a client method, like <code>View()</code>, also panics
then the client itself has been disconnected, i.e. condition (ii). In this case, you need to discard
the client object as well as any anchors derived from it. But if such a subsequent call does not panic, it implies
that the initial panic was caused by condition (i). In this case, only the host that your anchor
refers to has been disconnected and you can continue using the same client.
<li><pre>
job := host.Walk([]string{"shelljob", strconv.Itoa(rand.Int())})
</pre>
<p>The next line, which invokes <code>host.Walk</code>, creates an anchor (i.e. a node in the
circuit's virtual hierarchy) for the shell process that we are about to execute.
For instance, if the host anchor corresponds to a path like <code>/Xfea8b5b798f2fc09</code>,
then the anchor <code>job</code> will correspond to a path like
<code>/Xfea8b5b798f2fc09/shelljob/1234</code>, where <code>1234</code> is an
integer that we pick randomly to make sure we arrive at an anchor that does not
already have a resource attached to it.
<p>In general, calls to <code>anchor.Walk()</code> always succeed (as long as the implied
underlying host is connected). If the anchor we are “walking” to does not already exist,
it is automatically created. On the other hand, anchors that are not used by any clients
and have no resources attached to them are eventually garbage-collected for you.
<li><pre>
proc, _ := job.MakeProc(client.Cmd{
Path: "/bin/sh",
Dir: "/tmp",
Args: []string{"-c", cmd},
Scrub: true,
})
</pre>
<p>The following call to <code>job.MakeProc</code> executes the shell process
and creates a process handle — which we call a <em>process element</em> — and
attaches the process element to the anchor <code>job</code>.
The process element is represented by the returned value in <code>proc</code>.
(In general, elements attached to an anchor can be retrieved using the <code>Get</code> method.)
<p>The function <code>MakeProc</code> returns as soon as the process is executed, it
does not wait for the process to complete. The returned error value, ignored in our example,
is non-nil only in the event that the binary to be executed is not found on the host.
<p>The argument to <code>MakeProc</code> specifies the command, as usual.
The field <code>Scrub</code>, when set to <code>true</code>, tells the circuit runtime to remove
the process anchor automatically when the process dies. (Normally anchors that
have resources attached to them are not garbage-collected from the virtual hierarchy.
They must be scrubbed explicitly by the user.)
<li><pre>
go func() {
io.Copy(proc.Stdin(), bytes.NewBufferString(stdin))
proc.Stdin().Close() // Must close the standard input of the shell process.
}()
proc.Stderr().Close() // Close to indicate discarding standard error
var buf bytes.Buffer
io.Copy(&buf, proc.Stdout())
</pre>
<p>As soon as <code>MakeProc</code> returns, the process is running.
Our next goal is to take care of its standard streams: By POSIX convention,
every process will block if (i) it tries to read from standard input and there is nothing
to read and the descriptor is still open, or (ii) it tries to write to standard
error or output and they are not being consumed.
<p>We have direct access to the standard streams of the running process
via the methods
<pre>
Stdin() io.WriteCloser
Stdout() io.ReadCloser
Stderr() io.ReadCloser
</pre>
of the <code>proc</code> variable.
<p>In a separate goroutine, we write the contents of the parameter <code>stdin</code>
to the standard input of the shell process and then we close the stream, indicating that
no more input is to be expected.
<p>Meanwhile, in the main goroutine we first close the standard error stream.
This tells the circuit that all output to that stream should be discarded. Closing
a stream never blocks.
<p>Finally, we block on greedily reading the standard output of the shell process
into a buffer until we encounter closure, i.e. an EOF condition. Closure of the
standard output stream happens immediately before the process exits. At
this point <code>io.Copy()</code> will unblock.
<li><pre>
stat, _ := proc.Wait()
return buf.String(), stat.Exit
</pre>
<p>At last we invoke <code>proc.Wait</code> to wait for the death of the
process and capture its exit state within the returned <code>stat</code> structure.
If the error field <code>stat.Exit</code> is non-nil, it means the process
exited in error.
</ol>
<p>Often we won't be interested in passing any data to the standard input of the shell process,
for which cases we add a shortcut subroutine:
<pre>
func runShell(host client.Anchor, cmd string) (string, error) {
return runShellStdin(host, cmd, "")
}
</pre>
<p>We are now going to use <code>runShell</code> to fetch the public
and private IP addresses of any host on the cluster.
<h3>Retrieving EC2 host public and private IP addresses</h3>
<p>On any Amazon EC2 host instance, by definition, one is able to
retrieve the public and private IP addresses of the host instance using
the following command-lines, respectively:
<pre>
curl http://169.254.169.254/latest/meta-data/public-ipv4
curl http://169.254.169.254/latest/meta-data/local-ipv4
</pre>
<p>Basing on that and using <code>runShell</code>, the following subroutine will
fetch the public address of any host on the circuit cluster, specified by its anchor:
<pre>
func getEc2PublicIP(host client.Anchor) string {
out, err := runShell(host, "curl http://169.254.169.254/latest/meta-data/public-ipv4")
if err != nil {
fatalf("get ec2 public ip error: %v", err)
}
out = strings.TrimSpace(out)
if _, err := net.ResolveIPAddr("ip", out); err != nil {
fatalf("ip %q unrecognizable: %v", out, err)
}
return out
}
</pre>
<p>To retrieve the private host IP we implement a similar function <code>getEc2PrivateIP</code>,
which only differs from the above in that <code>public-ipv4</code> is substituted with
<code>local-ipv4</code>.
<h2>Starting the MySQL database on host A</h2>
<p>We would like to write a routine that starts a fresh MySQL server on a given host and
returns its server address and port number as a result.
<pre>
func startMysql(host client.Anchor) (ip, port string)
</pre>
<p>We are first going to describe the “manual” processs of starting a fresh
MySQL server, assuming we have a shell session at the host.
<p>Then we are going to show how this manual process can be codified
into a Go subroutine that performs its steps directly from the client application.
<h3>Manually starting MySQL at the host</h3>
<p>Let's asume you are at the shell of the host machine. The following
steps describe the way to start the MySQL server with a new database.
<p>Obtain the private IP address of this host:
<pre>
$ IP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)
</pre>
<p>Rewrite MySQL's configuration file to bind to the private IP address
and the default port 3306:
<pre>
$ sudo sed -i 's/^bind-address\s*=.*$/bind-address = '$IP:3306'/' /etc/mysql/my.cnf
</pre>
<p>Start the server:
<pre>
$ sudo /etc/init.d/mysql start
</pre>
<p>Connect to MySQL as root to prepare the tutorial user and database:
<pre>
$ sudo mysql
mysql> DROP USER tutorial;
mysql> DROP DATABASE tutorial;
mysql> CREATE USER tutorial;
mysql> CREATE DATABASE tutorial;
mysql> GRANT ALL ON tutorial.* TO tutorial;
</pre>
<p>Then connect as the <code>tutorial</code> user and set up the main table:
<pre>
$ mysql -u tutorial
mysql> USE tutorial;
mysql> CREATE TABLE NameValue (name VARCHAR(100), value TEXT, PRIMARY KEY (name));
</pre>
<p>The database is now configured, up and accepting connections at <code>$IP:3306</code>.
<h3>Programmatically starting MySQL from the app</h3>
<p>Retracing the manual steps programmatically is straightforward, purely using the
subroutines <code>getEc2PrivateIP</code>, <code>runShell</code> and <code>runShellStdin</code>
that we created earlier.
<pre>
func startMysql(host client.Anchor) (ip, port string) {
// Retrieve the IP address of this host within the cluster's private network.
ip = getEc2PrivateIP(host)
// We use the default MySQL server port
port = strconv.Itoa(3306)
// Rewrite MySQL config to bind to the private host address
cfg := fmt.Sprintf(` + "`" + `sudo sed -i 's/^bind-address\s*=.*$/bind-address = %s/' /etc/mysql/my.cnf` + "`" + `, ip)
if _, err := runShell(host, cfg); err != nil {
fatalf("mysql configuration error: %v", err)
}
// Start MySQL server
if _, err := runShell(host, "sudo /etc/init.d/mysql start"); err != nil {
fatalf("mysql start error: %v", err)
}
// Remove old database and user
runShellStdin(host, "sudo /usr/bin/mysql", "DROP USER tutorial;")
runShellStdin(host, "sudo /usr/bin/mysql", "DROP DATABASE tutorial;")
// Create tutorial user and database within MySQL
const m1 = ` + "`" + `
CREATE USER tutorial;
CREATE DATABASE tutorial;
GRANT ALL ON tutorial.* TO tutorial;
` + "`" + `
if _, err := runShellStdin(host, "sudo /usr/bin/mysql", m1); err != nil {
fatalf("problem creating database and user: %v", err)
}
// Create key/value table within tutorial database
const m2 = ` + "`" + `
USE tutorial;
CREATE TABLE NameValue (name VARCHAR(100), value TEXT, PRIMARY KEY (name));
` + "`" + `
if _, err := runShellStdin(host, "/usr/bin/mysql -u tutorial", m2); err != nil {
fatalf("problem creating table: %v", err)
}
return
}
</pre>
<p>We add a call to <code>startMysql</code> to the main logic:
<pre>
func main() {
flag.Parse()
c := connect(*flagAddr)
host := pickHosts(c, 2)
mysqlIP, mysqlPort := startMysql(host[0])
println("Started MySQL on private address:", mysqlIP, mysqlPort)
…
}
</pre>
<h2>Starting the Node.js app on host B</h2>
<p>Starting the Node.js app amounts to running the following command-line on the target host:
<pre>
$ sudo /usr/bin/nodejs nodejs-app/index.js \
--mysql_host $MYSQL_HOST --mysql_port $MYSQL_PORT \
--api_host $API_HOST --api_port $API_PORT \
&> /tmp/tutorial-nodejs.log
</pre>
<p>The app finds the backend MySQL server via the arguments <code>--mysql_host</code>
and <code>--mysql_port</code>. While it binds its HTTP API server to the address given by
the arguments <code>--api_host</code> and <code>--api_port</code>.
<p>The function <code>startNodejs</code> takes a target host parameter,
as well as the host and port of the backing MySQL server. It starts the Node.js
app on the target host and returns the public IP address and port of the HTTP API endpoint.
<pre>
func startNodejs(host client.Anchor, mysqlIP, mysqlPort string) (ip, port string) {
defer func() {
if recover() != nil {
fatalf("connection to host lost")
}
}()
// Start node.js application
ip = getEc2PublicIP(host)
port = "8080"
job := host.Walk([]string{"nodejs"})
shell := fmt.Sprintf(
"sudo /usr/bin/nodejs index.js "+
"--mysql_host %s --mysql_port %s --api_host %s --api_port %s "+
"&> /tmp/tutorial-nodejs.log",
mysqlIP, mysqlPort,
"0.0.0.0", port,
)
proc, err := job.MakeProc(client.Cmd{
Path: "/bin/sh",
Dir: "/home/ubuntu/nodejs-app",
Args: []string{"-c", shell},
Scrub: true,
})
if err != nil {
fatalf("nodejs app already running")
}
proc.Stdin().Close()
proc.Stdout().Close()
proc.Stderr().Close()
return
}
</pre>
<p>Note how we run the server. We execute a shell process, which itself executes the Node.js app.
The shell process, which is the one created by the circuit, is a long-running one. It will run
for as long as the child Node.js server is running.
<p>As soon as the process is executed <code>MakeProc</code> returns, but the process continues
executing in the background. We then close all of its standard streams as we don't intend them to be used.
<p>The process element is attached to anchor of the form <code>/X686ea8f7374e59a2/nodejs</code>.
This will allow you to find it in the future and check its state, for instance, by using the command-lines
<code>circuit ls</code> and <code>circuit peek</code>.
<p>At last, we tie this function into the main logic, which completes our circuit app implementation:
<pre>
func main() {
flag.Parse()
c := connect(*flagAddr)
host := pickHosts(c, 2)
mysqlIP, mysqlPort := startMysql(host[0])
println("Started MySQL on private address:", mysqlIP, mysqlPort)
nodejsIP, nodejsPort := startNodejs(host[1], mysqlIP, mysqlPort)
println("Started Node.js service on public address:", nodejsIP, nodejsPort)
}
</pre>
` | gocircuit.org/tutorial/mysql-nodejs/app.go | 0.698329 | 0.612165 | app.go | starcoder |
package rand
import (
"crypto/internal/randutil"
"errors"
"io"
"math/big"
)
// Prime returns a number of the given bit length that is prime with high probability.
// Prime will return error for any error returned by rand.Read or if bits < 2.
func Prime(rand io.Reader, bits int) (*big.Int, error) {
if bits < 2 {
return nil, errors.New("crypto/rand: prime size must be at least 2-bit")
}
randutil.MaybeReadByte(rand)
b := uint(bits % 8)
if b == 0 {
b = 8
}
bytes := make([]byte, (bits+7)/8)
p := new(big.Int)
for {
if _, err := io.ReadFull(rand, bytes); err != nil {
return nil, err
}
// Clear bits in the first byte to make sure the candidate has a size <= bits.
bytes[0] &= uint8(int(1<<b) - 1)
// Don't let the value be too small, i.e, set the most significant two bits.
// Setting the top two bits, rather than just the top bit,
// means that when two of these values are multiplied together,
// the result isn't ever one bit short.
if b >= 2 {
bytes[0] |= 3 << (b - 2)
} else {
// Here b==1, because b cannot be zero.
bytes[0] |= 1
if len(bytes) > 1 {
bytes[1] |= 0x80
}
}
// Make the value odd since an even number this large certainly isn't prime.
bytes[len(bytes)-1] |= 1
p.SetBytes(bytes)
if p.ProbablyPrime(20) {
return p, nil
}
}
}
// Int returns a uniform random value in [0, max). It panics if max <= 0.
func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) {
if max.Sign() <= 0 {
panic("crypto/rand: argument to Int is <= 0")
}
n = new(big.Int)
n.Sub(max, n.SetUint64(1))
// bitLen is the maximum bit length needed to encode a value < max.
bitLen := n.BitLen()
if bitLen == 0 {
// the only valid result is 0
return
}
// k is the maximum byte length needed to encode a value < max.
k := (bitLen + 7) / 8
// b is the number of bits in the most significant byte of max-1.
b := uint(bitLen % 8)
if b == 0 {
b = 8
}
bytes := make([]byte, k)
for {
_, err = io.ReadFull(rand, bytes)
if err != nil {
return nil, err
}
// Clear bits in the first byte to increase the probability
// that the candidate is < max.
bytes[0] &= uint8(int(1<<b) - 1)
n.SetBytes(bytes)
if n.Cmp(max) < 0 {
return
}
}
} | src/crypto/rand/util.go | 0.680666 | 0.46642 | util.go | starcoder |
package phy
import (
"image"
"image/color"
"image/draw"
"math"
"math/rand"
"time"
"github.com/icexin/eggos/app"
"github.com/icexin/eggos/drivers/kbd"
"github.com/icexin/eggos/drivers/vbe"
"github.com/jakecoffman/cp"
)
const gravityStrength = 5.0e6
var planetBody *cp.Body
func planetGravityVelocity(body *cp.Body, gravity cp.Vector, damping, dt float64) {
p := body.Position()
sqdist := p.LengthSq()
g := p.Mult(-gravityStrength / (sqdist * math.Sqrt(sqdist)))
body.UpdateVelocity(g, damping, dt)
}
func randPos(radius float64) cp.Vector {
var v cp.Vector
for {
v = cp.Vector{rand.Float64()*(640-2*radius) - (320 - radius), rand.Float64()*(480-2*radius) - (240 - radius)}
if v.Length() >= 85 {
return v
}
}
}
func addBox(space *cp.Space) {
size := 10.0
mass := 1.0
verts := []cp.Vector{
{-size, -size},
{-size, size},
{size, size},
{size, -size},
}
radius := cp.Vector{size, size}.Length()
pos := randPos(radius)
body := space.AddBody(cp.NewBody(mass, cp.MomentForPoly(mass, len(verts), verts, cp.Vector{}, 0)))
body.SetVelocityUpdateFunc(planetGravityVelocity)
body.SetPosition(pos)
r := pos.Length()
v := math.Sqrt(gravityStrength/r) / r
body.SetVelocityVector(pos.Perp().Mult(v))
body.SetAngularVelocity(v)
body.SetAngle(math.Atan2(pos.Y, pos.X))
shape := space.AddShape(cp.NewPolyShape(body, 4, verts, cp.NewTransformIdentity(), 0))
// shape := space.AddShape(cp.NewCircle(body, float64(size), cp.Vector{0, 0}))
shape.SetElasticity(0)
shape.SetFriction(0.7)
}
var GRABBABLE_MASK_BIT uint = 1 << 31
type Game struct {
space *cp.Space
drawer *Drawer
}
func NewGame(w, h int) *Game {
g := &Game{
space: cp.NewSpace(),
drawer: NewDrawer(DrawOption{
Width: w,
Height: h,
Flags: cp.DRAW_SHAPES | cp.DRAW_CONSTRAINTS | cp.DRAW_COLLISION_POINTS,
Outline: cp.FColor{200.0 / 255.0, 210.0 / 255.0, 230.0 / 255.0, 1},
Constraint: cp.FColor{0, 0.75, 0, 1},
CollisionPoint: cp.FColor{1, 0, 0, 1},
}),
}
g.Init()
return g
}
func (g *Game) Init() {
planetBody = g.space.AddBody(cp.NewKinematicBody())
planetBody.SetAngularVelocity(0.2)
N := 50
for i := 0; i < N; i++ {
addBox(g.space)
}
shape := g.space.AddShape(cp.NewCircle(planetBody, 70, cp.Vector{}))
shape.SetElasticity(1)
shape.SetFriction(1)
shape.SetFilter(cp.ShapeFilter{
cp.NO_GROUP, ^GRABBABLE_MASK_BIT, ^GRABBABLE_MASK_BIT,
})
}
func (g *Game) Update(dt float64) error {
// g.space.Step(dt)
g.space.Step(1 / (120.0))
return nil
}
func (g *Game) Draw(screen *vbe.View) {
g.drawer.NewFrame()
cp.DrawSpace(g.space, g.drawer)
draw.Draw(screen.Canvas(), g.drawer.Image().Bounds(), image.NewUniform(color.RGBA{38, 47, 57, 255}), image.ZP, draw.Src)
draw.Draw(screen.Canvas(), g.drawer.Image().Bounds(), g.drawer.Image(), image.ZP, draw.Src)
screen.Commit()
}
func (g *Game) Layout(outsideWidth int, outsideHeight int) (screenWidth int, screenHeight int) {
return outsideWidth, outsideHeight
}
func main(ctx *app.Context) error {
game := NewGame(600, 480)
game.Init()
last := time.Now()
for !kbd.Pressed('q') {
now := time.Now()
game.Update(now.Sub(last).Seconds())
game.Draw(vbe.DefaultView)
last = now
}
return nil
}
func init() {
app.Register("phy", main)
} | app/phy/game.go | 0.624179 | 0.446796 | game.go | starcoder |
package bisect
// Package bisect implements common bisection algorithms
// Interface is a type, typically a collection can be
// sorted in-place by the routines in this package
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Compares a given item with the element x at index i
// Should return a bool:
// negative , if a[i] < than
// positive , if a[i] > than
Less(i int, than interface{}) bool
}
// Return the index where to insert item x in a, assuming a is sorted.
// The return value i is such that all e in a[:i] have e <= x, and all e in
// a[i:] have e > x. So if x already appears in the list, a.insert(x) will
// insert just after the rightmost x already there.
func BisectRight(a Interface, x interface{}) int {
lo, hi := 0, a.Len()
for lo < hi {
m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow.
if a.Less(m, x) {
hi = m
} else {
lo = m + 1
}
}
return lo
}
// Return the index where to insert item x in a, assuming a is sorted.
// The return value i is such that all e in a[:i] have e < x, and all e in
// a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
// insert just before the leftmost x already there.
func BisectLeft(a Interface, x interface{}) int {
lo, hi := 0, a.Len()
for lo < hi {
m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow.
if a.Less(m, x) {
lo = m + 1
} else {
hi = m
}
}
return lo
}
// Convenience types for common cases
// IntSlice attaches the methods of Items to []int
type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i int, with interface{}) bool { return p[i] < with.(int) }
func (p *IntSlice) Insert(i int, x interface{}) {
*p = append(*p, 0)
copy((*p)[i+1:], (*p)[i:])
(*p)[i] = x.(int)
}
var _ Interface = (*IntSlice)(nil)
// Convenience methods.
func (p *IntSlice) InsortRight(x int) { p.Insert(BisectRight(p, x), x) }
func (p *IntSlice) InsortLeft(x int) { p.Insert(BisectLeft(p, x), x) }
func (p *IntSlice) BisectRight(x int) { BisectRight(p, x) }
func (p *IntSlice) BisectLeft(x int) { BisectLeft(p, x) }
// StringSlice attaches the methods of Items to []string
type StringSlice []string
func (p StringSlice) Len() int { return len(p) }
func (p StringSlice) Less(i int, with interface{}) bool { return p[i] < with.(string) }
func (p *StringSlice) Insert(i int, x interface{}) {
*p = append(*p, "")
copy((*p)[i+1:], (*p)[i:])
(*p)[i] = x.(string)
}
// Convenience methods.
func (p *StringSlice) InsortRight(x string) { p.Insert(BisectRight(p, x), x) }
func (p *StringSlice) InsortLeft(x string) { p.Insert(BisectLeft(p, x), x) }
func (p *StringSlice) BisectRight(x string) { BisectRight(p, x) }
func (p *StringSlice) BisectLeft(x string) { BisectLeft(p, x) }
var _ Interface = (*StringSlice)(nil)
// Float64Slice attaches the methods of items to []float64
type Float64Slice []float64
func (p Float64Slice) Len() int { return len(p) }
func (p Float64Slice) Less(i int, with interface{}) bool {
return p[i] < with.(float64) || isNaN(p[i]) && !isNaN(with.(float64))
}
func (p *Float64Slice) Insert(i int, x interface{}) {
*p = append(*p, float64(0))
copy((*p)[i+1:], (*p)[i:])
(*p)[i] = x.(float64)
}
// isNaN is a copy of math.IsNaN to avoid a dependency on the math package.
func isNaN(f float64) bool {
return f != f
}
// InsortRight is a convenience method.
func (p *Float64Slice) InsortRight(x float64) { p.Insert(BisectRight(p, x), x) }
func (p *Float64Slice) InsortLeft(x float64) { p.Insert(BisectLeft(p, x), x) }
func (p *Float64Slice) BisectRight(x float64) { BisectRight(p, x) }
func (p *Float64Slice) BisectLeft(x float64) { BisectLeft(p, x) }
var _ Interface = (*Float64Slice)(nil) | bisect.go | 0.810704 | 0.671147 | bisect.go | starcoder |
package main
import (
"fmt"
)
// Triangle stores the amount of white and black pieces
type Triangle struct {
White int
Black int
}
// Board represents the board
type Board struct {
Tris [24]Triangle
Bar Triangle
Finished Triangle
Turn bool
}
// NewBoard creates a board
func NewBoard() Board {
b := Board{}
b.Tris[0] = Triangle{White: 2}
b.Tris[5] = Triangle{Black: 5}
b.Tris[7] = Triangle{Black: 3}
b.Tris[11] = Triangle{White: 5}
b.Tris[12] = Triangle{Black: 5}
b.Tris[16] = Triangle{White: 3}
b.Tris[18] = Triangle{White: 5}
b.Tris[23] = Triangle{Black: 2}
return b
}
// GameTurn has a single turn of the game, returns whether the game is over or not
func (b *Board) GameTurn() bool {
fmt.Println()
if b.Turn {
fmt.Println("White's Turn")
} else {
fmt.Println("Black's Turn")
}
// Rolling
rolls := Roll()
fmt.Printf("You rolled a %d and a %d\n", rolls[0], rolls[1])
if rolls[0] == rolls[1] {
fmt.Println("Doubles!")
rolls = append(rolls, rolls...)
}
fmt.Println()
b.Print()
fmt.Println()
for len(rolls) > 0 {
// Input
s, e, err := b.GetInput()
if err {
return false
}
success := false
// Is valid?
for i, val := range rolls {
if b.IsValid(val, s, e) {
b.Tris[s] = SetPieces(b.Turn, b.Tris[s], GetPieces(b.Turn, b.Tris[s])-1)
b.Tris[e] = SetPieces(b.Turn, b.Tris[e], GetPieces(b.Turn, b.Tris[e])+1)
if i == len(rolls)-1 {
rolls = rolls[:i]
} else {
rolls = append(rolls[:i], rolls[i+1:]...)
}
b.Print()
fmt.Println()
success = true
}
}
if !success {
fmt.Println("Invalid Move!")
fmt.Println()
}
}
b.Turn = !b.Turn // Next turn
return true
}
// GetInput gets input
func (b *Board) GetInput() (int, int, bool) {
// Input
fmt.Print("Your Move: ")
s, e, err := ParseMove(Input())
for err != "" {
if err == "exit" {
return 0, 0, true
}
if err == "bear" { // Bear off piece
if !b.Bear() {
continue
}
}
fmt.Println(err)
fmt.Print("Your Move: ")
s, e, err = ParseMove(Input())
}
return s, e, false
}
// Start starts the game
func (b *Board) Start() {
roll := Roll()
fmt.Printf("White rolled %d. Black rolled %d\n", roll[0], roll[1])
for roll[0] == roll[1] {
roll = Roll()
fmt.Printf("White rolled %d. Black rolled %d\n", roll[0], roll[1])
}
if roll[0] > roll[1] {
b.Turn = true
fmt.Println("White goes first!")
} else {
b.Turn = false
fmt.Println("Black goes first!")
}
} | board.go | 0.520984 | 0.418578 | board.go | starcoder |
package util
import (
"github.com/samber/lo"
"golang.org/x/exp/slices"
)
type List[T comparable] []T
func (l List[T]) Has(elements ...T) bool {
return Any(elements, func(e T) bool {
return slices.Contains(l, e)
})
}
func (l List[T]) At(i int) *T {
if len(l) == 0 || i < 0 || len(l) <= i {
return nil
}
e := l[i]
return &e
}
func (l List[T]) Index(e T) int {
return slices.Index(l, e)
}
func (l List[T]) Len() int {
return len(l)
}
func (l List[T]) Copy() List[T] {
if l == nil {
return nil
}
return slices.Clone(l)
}
func (l List[T]) Ref() *List[T] {
if l == nil {
return nil
}
return &l
}
func (l List[T]) Refs() []*T {
return Map(l, func(e T) *T {
return &e
})
}
func (l List[T]) Delete(elements ...T) List[T] {
if l == nil {
return nil
}
m := l.Copy()
for _, e := range elements {
if j := l.Index(e); j >= 0 {
m = slices.Delete[[]T](m, j, j+1)
}
}
return m
}
func (l List[T]) DeleteAt(i int) List[T] {
if l == nil {
return nil
}
m := l.Copy()
return slices.Delete(m, i, i+1)
}
func (l List[T]) Add(elements ...T) List[T] {
res := l.Copy()
for _, e := range elements {
res = append(res, e)
}
return res
}
func (l List[T]) AddUniq(elements ...T) List[T] {
res := append(List[T]{}, l...)
for _, id := range elements {
if !res.Has(id) {
res = append(res, id)
}
}
return res
}
func (l List[T]) Insert(i int, elements ...T) List[T] {
if i < 0 || len(l) < i {
return l.Add(elements...)
}
return slices.Insert(l, i, elements...)
}
func (l List[T]) Move(e T, to int) List[T] {
return l.MoveAt(l.Index(e), to)
}
func (l List[T]) MoveAt(from, to int) List[T] {
if from < 0 || from == to || len(l) <= from {
return l.Copy()
}
e := l[from]
if from < to {
to--
}
m := l.DeleteAt(from)
if to < 0 {
return m
}
return m.Insert(to, e)
}
func (l List[T]) Reverse() List[T] {
return lo.Reverse(l.Copy())
}
func (l List[T]) Concat(m []T) List[T] {
return append(l, m...)
}
func (l List[T]) Intersect(m []T) List[T] {
if l == nil {
return nil
}
return lo.Intersect(m, l)
} | server/pkg/util/list.go | 0.578924 | 0.471223 | list.go | starcoder |
package deque
// Power of 2 for bitwise modulus: x % n == x & (n - 1).
const minSize = 64
// Deque represents a single instance of the data structure.
type Deque struct {
buffer []interface{}
first int
last int
size int
}
// Len returns the number of elements in the deque
func (q *Deque) Len() int {
return q.size
}
//------------------------------------------------------------------------
// FIFO deque: add with PushLast()
// remove with PopFirst()
// LIFO deque: add with PushFirst()
// remove with PopLast()
// Pop from an empty deque returns nil
//------------------------------------------------------------------------
// PushLast appends an element to the Last of the deque
func (q *Deque) PushLast(dequeitem interface{}) {
q.resizeIfNeeded()
q.buffer[q.last] = dequeitem
// Calculate new last position.
q.last = q.next(q.last)
q.size++
}
// PushFirst adds an element to the First of the deque
func (q *Deque) PushFirst(dequeitem interface{}) {
q.resizeIfNeeded()
// Calculate new first position.
q.first = q.prev(q.first)
q.buffer[q.first] = dequeitem
q.size++
}
// PopFirst removes and returns the first of the deque
func (q *Deque) PopFirst() interface{} {
if q.size <= 0 { return nil }
ret := q.buffer[q.first]
q.buffer[q.first] = nil
// Calculate new first position.
q.first = q.next(q.first)
q.size--
q.compactIfNeeded()
return ret
}
// PopLast removes and returns the element from the Last of the deque
func (q *Deque) PopLast() interface{} {
if q.size <= 0 { return nil }
// Calculate new last position
q.last = q.prev(q.last)
// Remove value at last.
ret := q.buffer[q.last]
q.buffer[q.last] = nil
q.size--
q.compactIfNeeded()
return ret
}
// First returns (browse) the element at the First of the deque,
// that would be returned by PopFirst()
func (q *Deque) First() interface{} {
if q.size <= 0 { return nil }
return q.buffer[q.first]
}
// Last returns the element at the Last of the deque,
// that would be returned by PopLast()
func (q *Deque) Last() interface{} {
if q.size <= 0 { return nil }
return q.buffer[q.prev(q.last)]
}
// At returns (browse) the element at index i in the deque
// without removing the element. Index i is non negative.
// Index 0 is the first element and same as First()
// Index Len()-1 is the last element and same as Last()
func (q *Deque) At(i int) interface{} {
if i < 0 || i >= q.size { return nil }
// bitwise modulus
return q.buffer[(q.first+i)&(len(q.buffer)-1)]
}
// Clear removes all elements from the deque
func (q *Deque) Clear() {
// bitwise modulus
modBits := len(q.buffer) - 1
for h := q.first; h != q.last; h = (h + 1) & modBits {
q.buffer[h] = nil
}
q.first = 0
q.last = 0
q.size = 0
}
// Rotate rotates the deque +n steps First-to-Last
// -n steps Last-to-First
func (q *Deque) Rotate(n int) {
if q.size <= 1 { return }
// Rotating a multiple of q.size is same as no rotation.
n %= q.size
if n == 0 { return }
modBits := len(q.buffer) - 1
// If no empty space in buffer, only move first and last indexes.
if q.first == q.last {
// Calculate new first and last using bitwise modulus.
q.first = (q.first + n) & modBits
q.last = (q.last + n) & modBits
return
}
if n < 0 {
// Rotate Last to First.
for ; n < 0; n++ {
// Calculate new first and last using bitwise modulus.
q.first = (q.first - 1) & modBits
q.last = (q.last - 1) & modBits
// Put last value at first and remove value at last.
q.buffer[q.first] = q.buffer[q.last]
q.buffer[q.last] = nil
}
return
}
// Rotate First to Last.
for ; n > 0; n-- {
// Put first value at last and remove value at first.
q.buffer[q.last] = q.buffer[q.first]
q.buffer[q.first] = nil
// Calculate new first and last using bitwise modulus.
q.first = (q.first + 1) & modBits
q.last = (q.last + 1) & modBits
}
}
// prev returns the previous buffer position wrapping around buffer.
func (q *Deque) prev(i int) int {
return (i - 1) & (len(q.buffer) - 1) // bitwise modulus
}
// next returns the next buffer position wrapping around buffer.
func (q *Deque) next(i int) int {
return (i + 1) & (len(q.buffer) - 1) // bitwise modulus
}
// resizeIfNeeded resizes up if the buffer is full.
func (q *Deque) resizeIfNeeded() {
if len(q.buffer) == 0 {
q.buffer = make([]interface{}, minSize)
return
}
if q.size == len(q.buffer) {
q.resize()
}
}
// compactIfNeeded resize down if the buffer 1/4 full.
func (q *Deque) compactIfNeeded() {
if len(q.buffer) > minSize && (q.size<<2) == len(q.buffer) {
q.resize()
}
}
// resizes the deque to fit exactly twice its current contents
func (q *Deque) resize() {
newBuf := make([]interface{}, q.size<<1)
if q.last > q.first {
copy(newBuf, q.buffer[q.first:q.last])
} else {
n := copy(newBuf, q.buffer[q.first:])
copy(newBuf[n:], q.buffer[:q.last])
}
q.first = 0
q.last = q.size
q.buffer = newBuf
} | deque/deque.go | 0.738575 | 0.523359 | deque.go | starcoder |
package kpage
import (
"container/list"
"fmt"
"math/rand"
"time"
"github.com/mohae/deepcopy"
)
// Solution represents a solution of a kPage problem
type Solution struct {
Pages uint
Crossings uint
Vertex uint
Edges []*Edge
Order []uint
vPosition []uint
adj []*list.List
}
// BuildAdj creates and fill the adjacency matrix in a pseudo-random way
func (s *Solution) buildAdj() {
// Change the seed to ensure randomness
rand.Seed(time.Now().UTC().UnixNano())
// If the adjacency matrix alredy exits the job is done
if s.adj != nil {
return
}
// Create the slice if alredy not exist
s.adj = make([]*list.List, len(s.Order))
// Create the double linked list of every index of the slice
for i := 1; i < len(s.adj); i++ {
s.adj[i] = list.New()
}
// Insert a pointer of every edge to the adj matrix
// Pointer to edge is used to avoid waste of space and unnecesary allocation
for _, e := range s.Edges {
l1, l2 := s.adj[e.Src], s.adj[e.Dst]
// The randomness of rdfs is simulated by select ind a random way to push the new edge to the front or the back of the double linked list
if rand.Int()%2 == 0 {
l1.PushFront(e)
} else {
l1.PushBack(e)
}
if rand.Int()%2 == 0 {
l2.PushFront(e)
} else {
l2.PushBack(e)
}
}
}
// OrderVertexes modify the vertexes array to change the order of the vertex without the need of change the edge number reference
func (s *Solution) OrderVertexes(start uint) error {
// Build the adj matrix if it doesnt exist
if s.adj == nil {
s.buildAdj()
}
if s.Order[start] == 0 {
return fmt.Errorf("start value dont have asigned any vertex assigned")
}
//Create a stack and push the starting vertex to it
var st stack
st.push(s.Order[start])
// Keep track of the current position to be assign
i := start
// Dfs implementation
DFS:
for curr, ok := st.pop(); ok; curr, ok = st.pop() {
// If the value is already assign skip it
if s.vPosition[curr] != 0 {
continue
}
// If the value hasnt been assign assign a value to it
s.Order[i] = curr
s.vPosition[curr] = i
// Add all the vertexes that are connected with the current vertex
for e := s.adj[curr].Front(); e != nil; e = e.Next() {
v := e.Value.(*Edge).otherOne(curr)
// Just add vertexes to the stack if they are alredy not assign
// This reduce the number of repeting vertexes that enters the stack but doesn't stop the push of vetex that are already on the stack but not assigned.
if s.vPosition[v] != 0 {
st.push(v)
}
}
i++
}
// Get all conex components
for i := uint(1); i < uint(len(s.vPosition)); i++ {
if s.vPosition[i] == 0 {
st.push(i)
goto DFS
}
}
return nil
}
// AssignPages iterates over all the edges an assign on page to that edge
func (s *Solution) AssignPages(limit uint) {
// First sort the edges in decreasing order using heapsort
heapSort(s)
var u, v, p, q uint
s.Crossings = 0
var bestCross, currCross, page uint
// Iterate over all the edges and assign it a page
for i := uint(0); i < uint(len(s.Edges)); i++ {
// Check which of the 2 vertexes goes first
if s.vPosition[s.Edges[i].Src] < s.vPosition[s.Edges[i].Dst] {
u, v = s.vPosition[s.Edges[i].Src], s.vPosition[s.Edges[i].Dst]
} else {
v, u = s.vPosition[s.Edges[i].Src], s.vPosition[s.Edges[i].Dst]
}
page = 1
// If the length of the edge is one or n - 1 there's no need to find the best page because it cant generate crossings
if s.getEdgeLength(i) != 1 || s.getEdgeLength(i) != s.Vertex-1 {
// Sets all the bits of bestCross to 1 to get the maximun value
bestCross = ^uint(0)
// Search in all the pages which generates the minimum number of posible crossings
for k := uint(1); k <= s.Pages; k++ {
currCross = uint(0)
// Loop that counts the posible crossings in the current page
for j := uint(0); j < i; j++ {
if k == s.Edges[j].Page {
// Check which of the 2 vertexes goes first
if s.vPosition[s.Edges[j].Src] < s.vPosition[s.Edges[j].Dst] {
p, q = s.vPosition[s.Edges[j].Src], s.vPosition[s.Edges[j].Dst]
} else {
q, p = s.vPosition[s.Edges[j].Src], s.vPosition[s.Edges[j].Dst]
}
// Check cross condition
if u < p && p < v && v < q || p < u && u < q && q < v {
currCross++
}
}
}
// If this page has a lower number of posibles crossings assign the page to the current one
if currCross < bestCross {
bestCross = currCross
page = k
}
// If the best number of crossings is 0 dont check the other pages
if bestCross == 0 {
break
}
}
}
// Once the best page was found assing it to the edge and increase the number of crossings
s.Edges[i].Page = page
s.Crossings += bestCross
// If the limit is already exceeded dont calculate the remainig edges
if s.Crossings > limit {
return
}
}
}
// Copy return a complete copy of the solution if posible
func (s *Solution) Copy() (*Solution, error) {
var sCopy *Solution
var err error
temp := deepcopy.Copy(s)
sCopy, ok := temp.(*Solution)
if !ok {
err = fmt.Errorf("unable to copy solution")
}
// deepcopy only copy exported values, wee neew to manually copy some unexported values
sCopy.vPosition = make([]uint, len(s.vPosition))
copy(sCopy.vPosition, s.vPosition)
return sCopy, err
}
// Swap 2 values based on s.Order value
func (s *Solution) Swap(a, b uint) {
s.vPosition[s.Order[a]], s.vPosition[s.Order[b]], s.Order[a], s.Order[b] = s.vPosition[s.Order[b]], s.vPosition[s.Order[a]], s.Order[b], s.Order[a]
}
// ResetFrom erase all the vertex order starting from index and do rdfs to reordenate
func (s *Solution) ResetFrom(index uint) error {
// Set all the vertex next to the start index as unassign
for i := index; i < s.Vertex+1; i++ {
s.vPosition[s.Order[i]] = 0
}
err := s.OrderVertexes(index)
return err
}
// getEdgeLength gives the length of an edge using the position of it vetexes in the current solution
// getEdgeLength dont chech if the index of the edge exists because its an unexported function and its always called from other functions inside the package that already check it
func (s *Solution) getEdgeLength(index uint) uint {
// Check which of the values has a higher position to avoid an overflow in the substraction
// The values of s.vPosition are unsigned integers so an overflow will cause the number become close to 2^64 - 1 getting a wrong length value
if s.vPosition[s.Edges[index].Src] < s.vPosition[s.Edges[index].Dst] {
return s.vPosition[s.Edges[index].Dst] - s.vPosition[s.Edges[index].Src]
}
return s.vPosition[s.Edges[index].Src] - s.vPosition[s.Edges[index].Dst]
}
// CalculateCrossings erase the previus Crossings value and recalculate it from zero
func (s *Solution) CalculateCrossings() uint {
cross := uint(0)
var u, v, p, q uint
for i := 0; i < len(s.Edges); i++ {
if s.vPosition[s.Edges[i].Src] < s.vPosition[s.Edges[i].Dst] {
u, v = s.vPosition[s.Edges[i].Src], s.vPosition[s.Edges[i].Dst]
} else {
v, u = s.vPosition[s.Edges[i].Src], s.vPosition[s.Edges[i].Dst]
}
for j := i + 1; j < len(s.Edges); j++ {
if s.Edges[i].Page == s.Edges[j].Page {
if s.vPosition[s.Edges[j].Src] < s.vPosition[s.Edges[j].Dst] {
p, q = s.vPosition[s.Edges[j].Src], s.vPosition[s.Edges[j].Dst]
} else {
q, p = s.vPosition[s.Edges[j].Src], s.vPosition[s.Edges[j].Dst]
}
if u < p && p < v && v < q || p < u && u < q && q < v {
cross++
}
}
}
}
return cross
} | kpage/solution.go | 0.608361 | 0.414484 | solution.go | starcoder |
package binarysearch
// BinarySearch binary search
// 二分查找,非递归版本
func BinarySearch(a []int, v int) int {
if len(a) == 0 {
return -1
}
low := 0
high := len(a) - 1
for low <= high {
mid := low + (high-low)/2
if a[mid] == v {
return mid
} else if a[mid] > v {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// BinarySearchRecursive binary search
// 二分查找,递归版本
func BinarySearchRecursive(a []int, v int) int {
if len(a) == 0 {
return -1
}
return BinarySearchRecursiveInner(a, v, 0, len(a)-1)
}
func BinarySearchRecursiveInner(a []int, v int, low int, high int) int {
if low > high {
return -1
}
mid := low + (high-low)/2
if a[mid] == v {
return mid
} else if a[mid] > v {
return BinarySearchRecursiveInner(a, v, low, mid-1)
} else {
return BinarySearchRecursiveInner(a, v, mid+1, high)
}
}
// BinarySearchFirst binary search first element equal to v
// 查找第一个值等于给定值的元素
func BinarySearchFirst(a []int, v int) int {
if len(a) == 0 {
return -1
}
low := 0
high := len(a) - 1
for low <= high {
mid := low + ((high - low) >> 2)
if a[mid] > v {
high = mid - 1
} else if a[mid] < v {
low = mid + 1
} else {
if mid == 0 || a[mid-1] != v {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
// BinarySearchLast binary search last element equal to v
// 查找最后一个值等于给定值的元素
func BinarySearchLast(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
low := 0
high := n - 1
for low <= high {
mid := low + ((high - low) >> 2)
if a[mid] > v {
high = mid - 1
} else if a[mid] < v {
low = mid + 1
} else {
if mid == n-1 || a[mid+1] != v {
return mid
} else {
low = mid + 1
}
}
}
return -1
}
// BinarySearchFirstGT binary search first element greater than v
// 查找第一个大于给定值的元素
func BinarySearchFirstGT(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
low := 0
high := n - 1
for low <= high {
mid := low + ((high - low) >> 2)
if a[mid] > v {
if (mid == 0) || (a[mid-1] <= v) {
return mid
} else {
high = mid - 1
}
} else {
low = mid + 1
}
}
return -1
}
// BinarySearchFirstGE binary search first element greater or equal to v
// 查找第一个大于等于给定值的元素
func BinarySearchFirstGE(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
low := 0
high := n - 1
for low <= high {
mid := low + ((high - low) >> 2)
if a[mid] >= v {
if (mid == 0) || (a[mid-1] < v) {
return mid
} else {
high = mid - 1
}
} else {
low = mid + 1
}
}
return -1
}
// BinarySearchLastLT binary search last element less than v
// 查找最后一个小于给定值的元素
func BinarySearchLastLT(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
low := 0
high := n - 1
for low <= high {
mid := low + ((high - low) >> 2)
if a[mid] >= v {
high = mid - 1
} else {
if (mid == n-1) || (a[mid+1] >= v) {
return mid
} else {
low = mid + 1
}
}
}
return -1
}
// BinarySearchLastLE binary search last element less or equal to v
// 查找最后一个小于等于给定值的元素
func BinarySearchLastLE(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
low := 0
high := n - 1
for low <= high {
mid := low + ((high - low) >> 2)
if a[mid] > v {
high = mid - 1
} else {
if (mid == n-1) || (a[mid+1] > v) {
return mid
} else {
low = mid + 1
}
}
}
return -1
} | binarysearch/golang/binarysearch.go | 0.572723 | 0.472988 | binarysearch.go | starcoder |
package routing
import (
"errors"
"fmt"
)
// Node represents a vertex in the graph.
type Node struct {
ID string // ID of this node.
Endhost bool // Whether it is an end-host (important dst for routing).
}
func (n Node) String() string {
return n.ID
}
// Key returns the beehive key representing this node.
func (n Node) Key() string {
return n.String()
}
// Edge represents a driected edge between two nodes.
type Edge struct {
From Node
To Node
}
// Edges is an alias for a slice of edges.
type Edges []Edge
// Contains returns whether the edges contain edge.
func (s Edges) Contains(edge Edge) bool {
for _, e := range s {
if e == edge {
return true
}
}
return false
}
// Path represents a directed path between two nodes.
type Path []Node
// Equal checks the equality of paths.
func (p Path) Equal(thatp Path) bool {
if p.Len() != thatp.Len() {
return false
}
for i := range p {
if p[i] != thatp[i] {
return false
}
}
return true
}
// Len returns the length of the path.
func (p Path) Len() int {
return len(p)
}
// Valid returns true if the path is a valid path. It checks the length of the
// path and also detects if the path has a loop.
func (p Path) Valid() bool {
if p.Len() <= 0 {
return false
}
nmap := make(map[Node]bool)
for _, n := range p {
if nmap[n] {
return false
}
nmap[n] = true
}
return true
}
// To returns the destination node of the path.
func (p Path) To() (Node, error) {
if !p.Valid() {
return Node{}, errors.New("This is an invalid path")
}
return p[p.Len()-1], nil
}
// From returns the source node of the path.
func (p Path) From() (Node, error) {
if !p.Valid() {
return Node{}, errors.New("This is an invalid path")
}
return p[0], nil
}
// Append creates a copy of the path, appends n to the path, and returns
// that copy. It will not directly modify the path. It returns error if the
// resulting path is an invalid path.
func (p Path) Append(n ...Node) (Path, error) {
c := make(Path, p.Len()+len(n))
copy(c, p)
copy(c[p.Len():], n)
if !c.Valid() {
return c, fmt.Errorf("This is an invalid path %v", c)
}
return c, nil
}
// Prepend creates a copy of the path, prepends n to the path, and returns
// that copy. It will not directly modify the path. It returns error if the
// resulting path is an invalid path.
func (p Path) Prepend(n ...Node) (Path, error) {
c := make(Path, p.Len()+len(n))
copy(c, n)
copy(c[len(n):], p)
if !c.Valid() {
return c, fmt.Errorf("This is an invalid path %v", c)
}
return c, nil
} | examples/routing/graph.go | 0.858289 | 0.451387 | graph.go | starcoder |
package internal
import (
"errors"
"fmt"
"math"
)
// A 2-dimensional point with floating point coordinates.
type Point2D struct {
X float32
Y float32
}
// A 2-dimensional rectangle with floating point coordinates
type Rect2D struct {
A Point2D
B Point2D
}
// A 3-dimensional point with floating point coordinates.
type Point3D struct {
X float32
Y float32
Z float32
}
// A 3-dimensional point with floating point coordinates and payload
type Point3DPayload struct {
Point3D
Payload interface{}
}
// A 2D coordinate transformation.
type Transform2D struct {
A float32
B float32
C float32
D float32
E float32
F float32
}
func (p Point2D) String() string {
return fmt.Sprintf("(%.2f, %.2f)", p.X, p.Y)
}
func (r Rect2D) String() string {
return fmt.Sprintf("(%v, %v)", r.A, r.B)
}
func (p Point3D) String() string {
return fmt.Sprintf("(%.2f, %.2f, %.2f)", p.X, p.Y, p.Z)
}
func (t Transform2D) String() string {
return fmt.Sprintf("x'=%.5fx %+.5fy %+.2f, y'=%.5fx %+.5fy %+.2f",
t.A, t.B, t.C, t.D, t.E, t.F)
}
// Returns the euclidian distance between the two given points
func Dist2D(a,b Point2D) float32 {
dSquared:=Dist2DSquared(a,b)
return float32(math.Sqrt(float64(dSquared)))
}
// Returns the squared euclididian distance between the two given points
func Dist2DSquared(a,b Point2D) float32 {
dx, dy:=a.X-b.X, a.Y-b.Y
return dx*dx + dy*dy
}
func Add2D(a,b Point2D) Point2D {
return Point2D{a.X+b.X, a.Y+b.Y}
}
func Sub2D(a,b Point2D) Point2D {
return Point2D{a.X-b.X, a.Y-b.Y}
}
// Returns the euclidian distance between the two given points
func Dist3D(a,b Point3D) float32 {
dSquared:=Dist3DSquared(a,b)
return float32(math.Sqrt(float64(dSquared)))
}
// Returns the squared euclididian distance between the two given points
func Dist3DSquared(a,b Point3D) float32 {
dx, dy, dz:=a.X-b.X, a.Y-b.Y, a.Z-b.Z
return dx*dx + dy*dy + dz*dz
}
func IdentityTransform2D() Transform2D {
return Transform2D{1,0,0, 0,1,0}
}
// Calculate 2D transformation matrix from three given points in first coordinate
// system, and corresponding reference points in second coordinate system.
// p1, p2, p3 are in the first system. p1p, p2p, p3p are in the second.
func NewTransform2D(p1, p2, p3, p1p, p2p, p3p Point2D) (Transform2D, error) {
a:=( (p3p.X-p1p.X)*(p2.Y-p1.Y) - (p2p.X-p1p.X)*(p3.Y-p1.Y) ) /
( (p2 .Y-p1 .Y)*(p3.X-p1.X) - (p2 .X-p1 .X)*(p3.Y-p1.Y) )
b:=( (p2p.X-p1p.X) - a*(p2.X-p1.X) ) / (p2.Y-p1.Y)
c:=p1p.X - a*p1.X - b*p1.Y
d:=( (p3p.Y-p1p.Y)*(p2.Y-p1.Y) - (p2p.Y-p1p.Y)*(p3.Y-p1.Y) ) /
( (p2 .Y-p1 .Y)*(p3.X-p1.X) - (p2 .X-p1 .X)*(p3.Y-p1.Y) )
e:=( (p2p.Y-p1p.Y) - d*(p2.X-p1.X) ) / (p2.Y-p1.Y)
f:=p1p.Y - d*p1.X - e*p1.Y
if math.IsInf(float64(a),0) || math.IsInf(float64(b),0) || math.IsInf(float64(d),0) || math.IsInf(float64(e),0) {
return Transform2D{}, errors.New("divide by zero")
}
return Transform2D{a,b,c,d,e,f}, nil
}
// Apply given 2D transformation to the given coordinates
func (t *Transform2D) Apply(p Point2D) (pP Point2D) {
xP:=t.A*p.X + t.B*p.Y + t.C
yP:=t.D*p.X + t.E*p.Y + t.F
return Point2D{xP, yP}
}
// Apply given 2D transformation to many given coordinates
func (t *Transform2D) ApplySlice(ps []Point2D) (pPs []Point2D) {
pPs=make([]Point2D, len(ps))
for i, p := range(ps) {
pPs[i]=t.Apply(p)
}
return pPs
}
// Invert a given 2D transformation. Returns error in the case of divid
func (t* Transform2D) Invert() (inv Transform2D, err error) {
if epsilon:=t.B*t.D-t.A*t.E; epsilon<1e-8 && -epsilon<1e-8 {
msg:=fmt.Sprintf("Matrix has no inverse, epsilon=%g", epsilon)
return Transform2D{}, errors.New(msg)
}
return Transform2D{
/* x' = a*x + b*y +c
y' = d*x + e*y +f
b*y = x' - a*x - c
e*y = y' - d*x - f
b*e*y = e*x' - a*e*x - c*e
b*e*y = b*y' - b*d*x - b*f
e*x' - a*e*x - c*e = b*y' - b*d*x - b*f
b*d*x - a*e*x = b*y' - e*x' + c*e - b*f
x = -e/(b*d-a*e)*x' + b/(b*d-a*e)*y' + (c*e-b*f)/(b*d-a*e)
x = a'*x' + b'*y' + c'
with a'=-e/(b*d-a*e), b'=b/(b*d-a*e) and c'=(c*e-b*f)/(b*d-a*e) */
A: -t.E/(t.B*t.D-t.A*t.E),
B: t.B/(t.B*t.D-t.A*t.E),
C: (t.C*t.E-t.B*t.F)/(t.B*t.D-t.A*t.E),
/* x' = a*x + b*y +c
y' = d*x + e*y +f
a*x = x' - b*y - c
d*x = y' - e*y - f
a*d*x = d*x' - b*d*y - c*d
a*d*x = a*y' - a*e*y - a*f
d*x' - b*d*y - c*d = a*y' - a*e*y - a*f
a*e*y - b*d*y = -d*x' + a*y' + c*d - a*f
y = -d/(a*e-b*d)*x' + a/(a*e-b*d)*y' + (c*d-a*f)/(a*e-b*d)
y = d'*x' + e'+y* + f'
with d'=-d/(a*e-b*d), e'=a/(a*e-b*d) and f'=(c*d-a*f)/(a*e-b*d) */
D: -t.D/(t.A*t.E-t.B*t.D),
E: t.A/(t.A*t.E-t.B*t.D),
F: (t.C*t.D-t.A*t.F)/(t.A*t.E-t.B*t.D),
}, nil
} | internal/coord.go | 0.849535 | 0.786869 | coord.go | starcoder |
package backbuf
import (
"fmt"
)
const minSize = 1
// Buffer implements a circular byte buffer, data is read from left to right
// but chucks are read from right to left. Unread data is never overwriten
type Buffer struct {
buffer []byte
wpos int
rpos int
full bool
}
// New creates a Buffer with a capacity of `size´ bytes
func New(size int) (*Buffer, error) {
if size < minSize {
return nil, fmt.Errorf("Size must be greater than %d", minSize)
}
b := &Buffer{buffer: make([]byte, size)}
b.Reset()
return b, nil
}
// Size returns the capacity of the buffer
func (cb *Buffer) Size() int {
return len(cb.buffer)
}
// Reset makes the buffer fully available
func (cb *Buffer) Reset() {
cb.wpos = len(cb.buffer)
cb.rpos = cb.wpos
cb.full = false
}
// WriteAvailability returns the number of bytes that can be writen
// without overwriting unread data
func (cb *Buffer) WriteAvailability() int {
if cb.full {
return 0
}
if cb.wpos <= cb.rpos {
return len(cb.buffer) - cb.rpos + cb.wpos
}
return cb.wpos - cb.rpos
}
// ReadAvailability returns the number of bytes that can be read
func (cb *Buffer) ReadAvailability() int {
return len(cb.buffer) - cb.WriteAvailability()
}
// Write stores bytes into the buffer without overriding unread data
func (cb *Buffer) Write(buf []byte) (n int, err error) {
if buf == nil || len(buf) == 0 {
return 0, fmt.Errorf("Input buffer is null or empty")
}
toWrite := min(cb.WriteAvailability(), len(buf))
if toWrite == 0 {
return 0, fmt.Errorf("Buffer is full")
}
if cb.wpos <= cb.rpos {
if toWrite < cb.wpos {
copy(cb.buffer[cb.wpos-toWrite:cb.wpos], buf[:toWrite])
cb.wpos -= toWrite
} else {
copy(cb.buffer[:cb.wpos], buf[:cb.wpos])
copy(cb.buffer[len(cb.buffer)-toWrite+cb.wpos:len(cb.buffer)], buf[cb.wpos:toWrite])
cb.wpos = len(cb.buffer) - toWrite + cb.wpos
}
} else {
copy(cb.buffer[cb.wpos-toWrite:cb.wpos], buf[:toWrite])
cb.wpos -= toWrite
}
cb.full = cb.wpos == cb.rpos
return toWrite, nil
}
// Read reads up to len(buf) bytes
func (cb *Buffer) Read(buf []byte) (int, error) {
if buf == nil || len(buf) == 0 {
return 0, fmt.Errorf("Target buffer is null or empty")
}
toRead := min(len(buf), cb.ReadAvailability())
lBytes := min(cb.rpos, toRead)
copy(buf[toRead-lBytes:toRead], cb.buffer[cb.rpos-lBytes:cb.rpos])
if toRead > lBytes {
rBytes := toRead - lBytes
copy(buf[:rBytes], cb.buffer[len(cb.buffer)-rBytes:len(cb.buffer)])
cb.rpos = len(cb.buffer) - rBytes
} else {
cb.rpos -= lBytes
}
cb.full = false
return toRead, nil
}
// ReadByte returns the first unread byte
func (cb *Buffer) ReadByte() (byte, error) {
buf := make([]byte, 1)
n, err := cb.Read(buf)
if err != nil {
return 0, err
}
if n == 0 {
return 0, fmt.Errorf("Buffer is empty")
}
return buf[0], nil
}
// Omit updates read position as if n bytes were read
func (cb *Buffer) Omit(n int) error {
if n < 1 {
return fmt.Errorf("Positive number required")
}
if cb.ReadAvailability() < n {
return fmt.Errorf("Not enough unread data")
}
if cb.rpos <= n {
cb.rpos = len(cb.buffer) - n + cb.rpos
} else {
cb.rpos -= n
}
cb.full = false
return nil
}
func min(x, y int) int {
if x < y {
return x
}
return y
} | backbuf/backbuf.go | 0.781205 | 0.492493 | backbuf.go | starcoder |
package redblack
type Tree struct {
root *Node
nil *Node
}
type color int
const (
colorRed = iota
colorBlack
)
type Node struct {
color color
key int
left *Node
right *Node
p *Node
}
// rotate change pointer's reference to recovery red-black tree's property
func (t *Tree) LeftRotate(node *Node) {
right := node.right
node.right = right.left
if right.left != t.nil {
right.left.p = node
}
right.p = node.p // 替换父节点的子节点
if right.p == nil {
t.root = right
} else if node == node.p.left {
right.p.left = right
} else {
right.p.right = right
}
right.left = node
node.p = right
}
// RightRotate node x
func (t *Tree) RightRotate(x *Node) {
y := x.left
x.left = y.right
if y.right != t.nil {
y.right.p = x
}
y.p = x.p
if x.p == nil {
t.root = y
} else if x == x.p.right {
x.p.right = y
} else {
x.p.left = y
}
y.right = x
x.p = y
}
func (t *Tree) Insert(x int) {
node := &Node{
key: x,
color: colorRed,
}
t.InsertNode(node)
}
func (t *Tree) InsertNode(node *Node) {
x := t.root
y := t.nil
for x != t.nil {
y = x
if node.key > x.key {
node = node.right
} else {
node = node.left
}
}
x.p = y
if y == t.nil {
t.root = x
} else if node.key > x.key {
x.right = node
} else {
x.left = node
}
node.left, node.right = t.nil, t.nil // 插入节点后性质被破坏
t.fixUp(node)
}
func (t *Tree) fixUp(node *Node) {
for node.p.color == colorRed { // 当插入结点的父节点不是红色结点时,只会破坏性质1(插入结点就是根节点)
if node.p == node.p.p.right {
y := node.p.p.left // 叔结点
if y.color == colorRed {
node.p.color = colorBlack
y.color = colorBlack
node.p.p.color = colorRed
node = node.p.p
continue
}
if node == node.p.right { // 插入结点为右结点,性质4被破坏,左旋转
node = node.p
t.LeftRotate(node)
}
node.p.color = colorBlack
node.p.p.color = colorRed
t.RightRotate(node.p.p)
} else {
y := node.p.p.right
if y.color == colorRed {
node.p.color = colorBlack
y.color = colorBlack
node.p.p.color = colorRed
node = node.p
continue
}
if node == node.p.right {
node = node.p
t.LeftRotate(node)
}
node.p.color = colorBlack
node.p.p.color = colorRed
t.RightRotate(node.p.p)
}
}
t.root.color = colorBlack
} | redblack/red_black_tree.go | 0.549641 | 0.510863 | red_black_tree.go | starcoder |
package main
import (
"bufio"
"flag"
"fmt"
"math"
"os"
"strconv"
"strings"
)
// haversin(θ) function
func hsin(theta float64) float64 {
return math.Pow(math.Sin(theta/2), 2)
}
// http://en.wikipedia.org/wiki/Haversine_formula
func Distance(lat1, lon1, lat2, lon2 float64) float64 {
var la1, lo1, la2, lo2, r float64
la1 = lat1 * math.Pi / 180.0
lo1 = lon1 * math.Pi / 180.0
la2 = lat2 * math.Pi / 180.0
lo2 = lon2 * math.Pi / 180.0
r = 6378100.0 // Earth radius in meters
// calculate
h := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1)
return 2 * r * math.Asin(math.Sqrt(h))
}
func main() {
predFile := flag.String("predicted", "pred_grid.xyz", "predicted grid file")
obsFile := flag.String("observed", "obs_grid.xyz", "observed grid file")
aTime := flag.Float64("atime", 3.59, "alert time")
flag.Parse()
// variables for computations
var sWaveVelocity float64 = 3.0
var tolerance float64 = 0.5
/* read in each file into array */
pFile, err := os.Open(*predFile)
if err != nil {
fmt.Println(err)
}
defer pFile.Close()
oFile, err := os.Open(*obsFile)
if err != nil {
fmt.Println(err)
}
defer oFile.Close()
pLines := []string{} // slice of strings to hold the read in data from predicted.xyz
oLines := []string{} // slice of strings to hold the read in data from observed.xyz
// read in pred grid
pScanner := bufio.NewScanner(pFile)
for pScanner.Scan() {
pLines = append(pLines, pScanner.Text())
}
// read in obs grid
oScanner := bufio.NewScanner(oFile)
for oScanner.Scan() {
oLines = append(oLines, oScanner.Text())
}
// observed values
oLat, _ := strconv.ParseFloat(strings.Split(oLines[0], " ")[2], 64)
oLon, _ := strconv.ParseFloat(strings.Split(oLines[0], " ")[3], 64)
// array creations to hold elements from obs and pred grids
pRows := len(pLines)
oRows := len(oLines)
pVals := make([][]float64, pRows)
oVals := make([][]float64, oRows)
numTP := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numFP := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numFN := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numTN := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
truePR := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numTPT := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numFPT := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numFNT := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
numTNT := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
falsePR := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
truePRT := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
falsePRT := [6]float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
distGrid := make([]float64, pRows)
mmiThresholds := [6]float64{2.0, 3.0, 4.0, 5.0, 6.0, 7.0}
// split predicted file lines into array
for i := 0; i < len(pLines); i++ {
lat, _ := strconv.ParseFloat(strings.Split(pLines[i], " ")[1], 64)
lon, _ := strconv.ParseFloat(strings.Split(pLines[i], " ")[0], 64)
mmi, _ := strconv.ParseFloat(strings.Split(pLines[i], " ")[4], 64)
pVals[i] = make([]float64, 3) // 3 elements in each pVal
pVals[i][0] = lat
pVals[i][1] = lon
pVals[i][2] = mmi
//fmt.Println(i, ": ", lat, lon, mmi)
}
// split observed lines into array
for i := 0; i < len(oLines); i++ {
lat, _ := strconv.ParseFloat(strings.Split(oLines[i], " ")[1], 64)
lon, _ := strconv.ParseFloat(strings.Split(oLines[i], " ")[0], 64)
mmi, _ := strconv.ParseFloat(strings.Split(oLines[i], " ")[4], 64)
oVals[i] = make([]float64, 3) // 3 elements in each oVal
oVals[i][0] = lat
oVals[i][1] = lon
oVals[i][2] = mmi
}
// populate distance grid
for i := 0; i < len(pVals); i++ {
distGrid[i] = Distance(oLat, oLon, pVals[i][0], pVals[i][1])
}
// loop through each array and compare/populate the ROC arrays
// For more on ROC, read https://en.wikipedia.org/wiki/Receiver_operating_characteristic
for i := 0; i < len(mmiThresholds); i++ {
for j := 0; j < len(oVals); j++ {
if oVals[j][2] > mmiThresholds[i] {
if (pVals[j][2] + tolerance) > mmiThresholds[i] {
numTP[i] = numTP[i] + 1.0
} else {
numFN[i] = numFN[i] + 1.0
}
} else {
if (pVals[j][2] - tolerance) > mmiThresholds[i] {
numFP[i] = numFP[i] + 1.0
} else {
numTN[i] = numTN[i] + 1.0
}
}
// populate the true and false positive rates
if (numTP[i] + numFN[i]) != 0.0 {
truePR[i] = numTP[i] / (numTP[i] + numFN[i])
falsePR[i] = numFP[i] / (numTP[i] + numFN[i])
}
}
}
// loop through each array and compare/populate the ROC arrays
// For more on ROC, read https://en.wikipedia.org/wiki/Receiver_operating_characteristic
// Timeliness calculated
for i := 0; i < len(mmiThresholds); i++ {
for j := 0; j < len(oVals); j++ {
distKM := distGrid[j] / 1000.0
groundMT := distKM / sWaveVelocity
if oVals[j][2] > mmiThresholds[i] {
if (pVals[j][2] + tolerance) > mmiThresholds[i] {
if *aTime <= groundMT {
numTPT[i] = numTPT[i] + 1.0
} else {
numFNT[i] = numFNT[i] + 1.0
}
} else {
numFNT[i] = numFNT[i] + 1.0
}
} else {
if (pVals[j][2] - tolerance) > mmiThresholds[i] {
numFPT[i] = numFPT[i] + 1.0
} else {
numTNT[i] = numTNT[i] + 1.0
}
}
// populate the true and false positive rates
if (numTPT[i] + numFNT[i]) != 0.0 {
truePRT[i] = numTPT[i] / (numTPT[i] + numFNT[i])
falsePRT[i] = numFPT[i] / (numTPT[i] + numFNT[i])
}
}
}
fmt.Println("Timeliness not considered")
fmt.Println(truePR)
fmt.Println(falsePR)
fmt.Println("\nTimeliness considered")
fmt.Println(truePRT)
fmt.Println(falsePRT)
// remove references to slices; memory allocated earlier with make can now be garbage collected
pVals = nil
oVals = nil
} | gmp_compare/gmp_compare.go | 0.714628 | 0.416559 | gmp_compare.go | starcoder |
package main
import (
"fmt"
"io/ioutil"
"math"
"sort"
"strings"
)
type coordinates struct {
x, y float64
}
type asteroid struct {
visibleAsteroids int
tangentsOfObstruction map[string]bool
}
type distance struct {
coordinates
value float64
}
type byDistance []distance
func (d byDistance) Len() int { return len(d) }
func (d byDistance) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d byDistance) Less(i, j int) bool { return d[i].value < d[j].value }
func main() {
var asteroidCoordinates []coordinates
input, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
inputString := string(input)
inputArray := strings.Split(strings.Trim(inputString, "\n"), "\n")
for y, row := range inputArray {
for x, el := range row {
if el == '#' {
asteroidCoordinates = append(asteroidCoordinates, coordinates{float64(x), float64(y)})
}
}
}
var mostVisibleAsteroids int
var laserLocation coordinates
var laserQuadrants [][]distance
for _, firstCoordinates := range asteroidCoordinates {
var distances []distance
quadrants := make([][]distance, 4)
currentAsteroid := asteroid{
tangentsOfObstruction: make(map[string]bool),
}
for _, secondCoordinates := range asteroidCoordinates {
if firstCoordinates != secondCoordinates {
distances = append(distances, distance{secondCoordinates, findDistance(firstCoordinates, secondCoordinates)})
}
}
sort.Sort(byDistance(distances))
for _, distance := range distances {
quadrant := getQuadrant(firstCoordinates, distance.coordinates)
quadrants[quadrant] = append(quadrants[quadrant], distance)
tangent := (firstCoordinates.x - distance.x) / (firstCoordinates.y - distance.y)
if !currentAsteroid.tangentsOfObstruction[fmt.Sprintf("%v_%v", quadrant, tangent)] {
currentAsteroid.visibleAsteroids++
currentAsteroid.tangentsOfObstruction[fmt.Sprintf("%v_%v", quadrant, tangent)] = true
}
}
if currentAsteroid.visibleAsteroids > mostVisibleAsteroids {
laserLocation = firstCoordinates
laserQuadrants = quadrants
mostVisibleAsteroids = currentAsteroid.visibleAsteroids
}
}
var asteroidsDestroyed int
alreadyDestroyed := make(map[string]bool)
currentQuadrant := 0
for {
laser := asteroid{
tangentsOfObstruction: make(map[string]bool),
}
asteroidsForDestruction := make(map[float64]coordinates)
for _, distance := range laserQuadrants[currentQuadrant] {
tangent := (laserLocation.x - distance.x) / (laserLocation.y - distance.y)
if !alreadyDestroyed[fmt.Sprintf("%v:%v", distance.x, distance.y)] {
if !laser.tangentsOfObstruction[fmt.Sprintf("%v_%v", currentQuadrant, tangent)] {
if currentQuadrant%2 == 0 {
asteroidsForDestruction[math.Abs(tangent)] = distance.coordinates
} else {
asteroidsForDestruction[-math.Abs(tangent)] = distance.coordinates
}
laser.tangentsOfObstruction[fmt.Sprintf("%v_%v", currentQuadrant, tangent)] = true
}
}
}
var tangents []float64
for tan := range asteroidsForDestruction {
tangents = append(tangents, tan)
}
sort.Float64s(tangents)
for _, tan := range tangents {
asteroidsDestroyed++
currentAsteroidCoordinates := asteroidsForDestruction[tan]
fmt.Println(asteroidsDestroyed, currentAsteroidCoordinates, tan)
alreadyDestroyed[fmt.Sprintf("%v:%v", currentAsteroidCoordinates.x, currentAsteroidCoordinates.y)] = true
if asteroidsDestroyed == 200 {
fmt.Println(currentAsteroidCoordinates.x*100 + currentAsteroidCoordinates.y)
break
}
}
if asteroidsDestroyed == 200 {
break
}
currentQuadrant = (currentQuadrant + 1) % 4
}
}
func findDistance(a, b coordinates) float64 {
return math.Sqrt(math.Pow(a.x-b.x, 2) + math.Pow(a.y-b.y, 2))
}
func getQuadrant(a, b coordinates) int {
if a.x <= b.x && a.y > b.y {
return 0
} else if a.x < b.x && a.y <= b.y {
return 1
} else if a.x >= b.x && a.y < b.y {
return 2
} else if a.x > b.x && a.y >= b.y {
return 3
} else {
panic(b)
}
} | day20/main.go | 0.527803 | 0.415136 | main.go | starcoder |
package g
import (
)
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// Angular events - http://www.w3schools.com/angular/angular_events.asp
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
func (ele *ELEMENT) NgBlur(expression string) *ELEMENT { return ele.Attr("ng-blur", expression) }
func (ele *ELEMENT) NgChange(expression string) *ELEMENT { return ele.Attr("ng-change", expression) }
func (ele *ELEMENT) NgClick(expression string) *ELEMENT { return ele.Attr("ng-click", expression) }
func (ele *ELEMENT) NgCopy(expression string) *ELEMENT { return ele.Attr("ng-copy", expression) }
func (ele *ELEMENT) NgCut(expression string) *ELEMENT { return ele.Attr("ng-cut", expression) }
func (ele *ELEMENT) NgDblClick(expression string) *ELEMENT { return ele.Attr("ng-dblclick", expression) }
func (ele *ELEMENT) NgFocus(expression string) *ELEMENT { return ele.Attr("ng-focus", expression) }
func (ele *ELEMENT) NgKeyDown(expression string) *ELEMENT { return ele.Attr("ng-keydown", expression) }
func (ele *ELEMENT) NgKeyPress(expression string) *ELEMENT { return ele.Attr("ng-keypress", expression) }
func (ele *ELEMENT) NgKeyUp(expression string) *ELEMENT { return ele.Attr("ng-keyup", expression) }
func (ele *ELEMENT) NgMouseDown(expression string) *ELEMENT { return ele.Attr("ng-mousedown", expression) }
func (ele *ELEMENT) NgMouseEnter(expression string) *ELEMENT { return ele.Attr("ng-mouseenter", expression) }
func (ele *ELEMENT) NgMouseLeave(expression string) *ELEMENT { return ele.Attr("ng-mouseleave", expression) }
func (ele *ELEMENT) NgMouseMove(expression string) *ELEMENT { return ele.Attr("ng-mousemove", expression) }
func (ele *ELEMENT) NgMouseOver(expression string) *ELEMENT { return ele.Attr("ng-mouseover", expression) }
func (ele *ELEMENT) NgMouseUp(expression string) *ELEMENT { return ele.Attr("ng-mouseup", expression) }
func (ele *ELEMENT) NgPaste(expression string) *ELEMENT { return ele.Attr("ng-paste", expression) } | markup/angular_events.go | 0.541894 | 0.408513 | angular_events.go | starcoder |
package core
import (
"runtime"
. "github.com/gooid/gocv/opencv3/internal/native"
)
const _channelsMatOfRect = 4
var _depthMatOfRect = CvTypeCV_32S
type MatOfRect struct {
*Mat
}
func NewMatOfRect() (rcvr *MatOfRect) {
rcvr = &MatOfRect{}
rcvr.Mat = NewMat2()
runtime.SetFinalizer(rcvr, func(interface{}) { rcvr.finalize() })
return
}
func NewMatOfRect2(addr int64) (rcvr *MatOfRect) {
rcvr = &MatOfRect{}
rcvr.Mat = NewMat(addr)
runtime.SetFinalizer(rcvr, func(interface{}) { rcvr.finalize() })
if !rcvr.Empty() && rcvr.CheckVector2(_channelsMatOfRect, _depthMatOfRect) < 0 {
Throw(NewIllegalArgumentException("Incompatible Mat"))
}
return
}
func NewMatOfRect3(m *Mat) (rcvr *MatOfRect) {
rcvr = &MatOfRect{}
rcvr.Mat = NewMat8(m, RangeAll())
runtime.SetFinalizer(rcvr, func(interface{}) { rcvr.finalize() })
if !rcvr.Empty() && rcvr.CheckVector2(_channelsMatOfRect, _depthMatOfRect) < 0 {
Throw(NewIllegalArgumentException("Incompatible Mat"))
}
return
}
func (rcvr *MatOfRect) Alloc(elemNumber int) {
if elemNumber > 0 {
rcvr.Create(elemNumber, 1, CvTypeMakeType(_depthMatOfRect, _channelsMatOfRect))
}
}
func (rcvr *MatOfRect) FromArray(a []*Rect) {
if a == nil || len(a) == 0 {
return
}
num := len(a)
rcvr.Alloc(num)
buff := make([]int32, num*_channelsMatOfRect)
for i := 0; i < num; i++ {
r := a[i]
buff[_channelsMatOfRect*i+0] = int32(r.X)
buff[_channelsMatOfRect*i+1] = int32(r.Y)
buff[_channelsMatOfRect*i+2] = int32(r.Width)
buff[_channelsMatOfRect*i+3] = int32(r.Height)
}
rcvr.PutI(0, 0, buff)
}
func MatOfRectFromNativeAddr(addr int64) *MatOfRect {
return NewMatOfRect2(addr)
}
func (rcvr *MatOfRect) ToArray() []*Rect {
num := rcvr.Total()
a := make([]*Rect, num)
if num == 0 {
return a
}
buff := make([]int32, num*_channelsMatOfRect)
rcvr.GetI(0, 0, buff)
for i := int64(0); i < num; i++ {
a[i] = NewRect(int(buff[i*_channelsMatOfRect]), int(buff[i*_channelsMatOfRect+1]), int(buff[i*_channelsMatOfRect+2]), int(buff[i*_channelsMatOfRect+3]))
}
return a
} | opencv3/core/MatOfRect.java.go | 0.626353 | 0.405478 | MatOfRect.java.go | starcoder |
package mat64
import "math"
// Float is the main float type for the mat64 package. It is an alias for float64.
type Float = float64
const (
// SmallestNonzeroFloat corresponds to math.SmallestNonzeroFloat64.
SmallestNonzeroFloat Float = math.SmallestNonzeroFloat64
// Pi mathematical constant.
Pi Float = math.Pi
)
// Pow returns x**y, the base-x exponential of y.
func Pow(x, y Float) Float {
return math.Pow(x, y)
}
// Cos returns the cosine of the radian argument x.
func Cos(x Float) Float {
return math.Cos(x)
}
// Sin returns the sine of the radian argument x.
func Sin(x Float) Float {
return math.Sin(x)
}
// Cosh returns the hyperbolic cosine of x.
func Cosh(x Float) Float {
return math.Cosh(x)
}
// Sinh returns the hyperbolic sine of x.
func Sinh(x Float) Float {
return math.Sinh(x)
}
// Exp returns e**x, the base-e exponential of x.
func Exp(x Float) Float {
return math.Exp(x)
}
// Abs returns the absolute value of x.
func Abs(x Float) Float {
return math.Abs(x)
}
// Sqrt returns the square root of x.
func Sqrt(x Float) Float {
return math.Sqrt(x)
}
// Log returns the natural logarithm of x.
func Log(x Float) Float {
return math.Log(x)
}
// Tan returns the tangent of the radian argument x.
func Tan(x Float) Float {
return math.Tan(x)
}
// Tanh returns the hyperbolic tangent of x.
func Tanh(x Float) Float {
return math.Tanh(x)
}
// Max returns the larger of x or y.
func Max(x, y Float) Float {
return math.Max(x, y)
}
// Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.
func Inf(sign int) Float {
return math.Inf(sign)
}
// IsInf reports whether f is an infinity, according to sign.
func IsInf(f Float, sign int) bool {
return math.IsInf(f, sign)
}
// NaN returns an IEEE 754 ``not-a-number'' value.
func NaN() Float {
return math.NaN()
}
// Ceil returns the least integer value greater than or equal to x.
func Ceil(x Float) Float {
return math.Ceil(x)
}
// Floor returns the greatest integer value less than or equal to x.
func Floor(x Float) Float {
return math.Floor(x)
}
// Round returns the nearest integer, rounding half away from zero.
func Round(x Float) Float {
return math.Round(x)
} | pkg/mat64/mat.go | 0.920781 | 0.709787 | mat.go | starcoder |
package circuit
type BitVector struct {
Nodes []*Node
}
func NewBitVector(n int) *BitVector {
return &BitVector{make([]*Node, n)}
}
func FillVector(n int, node *Node) *BitVector {
r := NewBitVector(n)
for i := range(r.Nodes) {
r.Nodes[i] = node
}
return r
}
func ZeroVector(n int) *BitVector {
return FillVector(n, Low)
}
func OneVector(n int) *BitVector {
return FillVector(n, High)
}
func (v *BitVector) optimize() {
for i, n := range v.Nodes {
v.Nodes[i] = Optimize(n)
}
}
func (v *BitVector) Optimize() int {
begin := EliminatedNodeCount
e := EliminatedNodeCount + 1
for e != EliminatedNodeCount {
e = EliminatedNodeCount
v.optimize()
}
return EliminatedNodeCount - begin
}
func (v *BitVector) makeUnaryOperate(f UnaryGateMaker) *BitVector {
ret := NewBitVector(len(v.Nodes))
for i := range(ret.Nodes) {
ret.Nodes[i] = f(v.Nodes[i])
}
return ret
}
func (v *BitVector) makeBinaryOperate(v2 *BitVector, f BinaryGateMaker) *BitVector {
n := len(v.Nodes)
if n > len(v2.Nodes) {
n = len(v2.Nodes)
}
ret := NewBitVector(n)
for i := len(ret.Nodes) - 1; i >= 0; i-- {
ret.Nodes[i] = f(v.Nodes[i], v2.Nodes[i])
}
return ret
}
func (v *BitVector) Copy() *BitVector {
nodes := make([]*Node, len(v.Nodes))
copy(nodes, v.Nodes)
return &BitVector{Nodes: nodes}
}
func (v *BitVector) Not() *BitVector {
return v.makeUnaryOperate(func(n *Node) *Node {
return Not(n)
})
}
func (v *BitVector) RotateRight(n int) *BitVector {
r := v.Copy()
l := len(v.Nodes)
for n < 0 {
n += l;
}
for n >= l {
n -= l;
}
tail := make([]*Node, n)
copy(tail, r.Nodes[l-n:])
copy(r.Nodes[n:], r.Nodes)
copy(r.Nodes, tail)
return r
}
func (v *BitVector) RotateLeft(n int) *BitVector {
return v.RotateRight(-n)
}
func (v *BitVector) ShiftRight(n int) *BitVector {
r := v.Copy()
l := len(v.Nodes)
for n >= l {
n -= l;
}
copy(r.Nodes[n:], r.Nodes)
for i := 0; i < n; i++ {
r.Nodes[i] = Low
}
return r
}
func (v *BitVector) And(v2 *BitVector) *BitVector {
return v.makeBinaryOperate(v2, func(n1, n2 *Node) *Node {
return And(n1, n2)
})
}
func (v *BitVector) Or(v2 *BitVector) *BitVector {
return v.makeBinaryOperate(v2, func(n1, n2 *Node) *Node {
return Or(n1, n2)
})
}
func (v *BitVector) Xor(v2 *BitVector) *BitVector {
return v.makeBinaryOperate(v2, func(n1, n2 *Node) *Node {
return Xor(n1, n2)
})
}
func (v *BitVector) add(v2 *BitVector, carry *Node) *BitVector {
return v.makeBinaryOperate(v2, func(a, b *Node) (sum *Node) {
sum, carry = FullAdd(a, b, carry)
return
})
}
func (v *BitVector) Add(v2 *BitVector) *BitVector {
return v.add(v2, Low)
}
func (v *BitVector) Sub(v2 *BitVector) *BitVector {
return v.add(v2.Not(), High)
}
func (v *BitVector) Eval() BitArray {
return Eval(v.Nodes...)
} | bitvector.go | 0.678433 | 0.743959 | bitvector.go | starcoder |
package measurements
import (
"github.com/Debiancc/go-turf/features"
"github.com/Debiancc/go-turf/helpers"
"github.com/Debiancc/go-turf/types"
"math"
)
func Destination(origin features.Point, distance float64, bearing float64, units types.Units, properties *features.Properties) *features.Point {
lng1 := helpers.DegreesToRadians(origin.GetLng())
lat1 := helpers.DegreesToRadians(origin.GetLat())
bearingRad := helpers.DegreesToRadians(bearing)
radians := helpers.LengthToRadians(distance, units)
lat2 := math.Asin(math.Sin(lat1)*math.Cos(radians) + math.Cos(lat1)*math.Sin(radians)*math.Cos(bearingRad))
lng2 := lng1 + math.Atan2(
math.Sin(bearingRad)*math.Sin(radians)*math.Cos(lat1),
math.Cos(radians)-math.Sin(lat1)*math.Sin(lat2),
)
lng := helpers.RadiansToDegrees(lng2)
lat := helpers.RadiansToDegrees(lat2)
return features.NewPoint([2]float64{lng, lat}, properties, nil)
}
func RhumbDestination(origin features.Point, distance float64, bearing float64, units types.Units, properties *features.Properties) *features.Point {
wasNegativeDostamce := distance < 0
distanceInMeters := helpers.ConvertLength(math.Abs(distance), units, types.UnitMeters)
if wasNegativeDostamce {
distanceInMeters = -math.Abs(distanceInMeters)
}
destination := calcRhumbDestination(origin, distanceInMeters, bearing, nil)
if destination.GetLng()-origin.GetLng() > 180 {
destination.Geometry.Coordinates[0] += -360
} else {
if origin.GetLng()-destination.GetLng() > 180 {
destination.Geometry.Coordinates[0] += 360
}
}
return features.NewPoint(destination.Geometry.Coordinates, properties, nil)
}
func calcRhumbDestination(origin features.Point, distance float64, bearing float64, radius *float64) *features.Point {
var delta float64
if radius == nil {
delta = distance / types.FactorEarthRadius
} else {
delta = distance / *radius
}
lambda1 := origin.GetLng() * math.Pi / 180
phi1 := helpers.DegreesToRadians(origin.GetLat())
theta := helpers.DegreesToRadians(bearing)
deltaPhi := delta * math.Cos(theta)
phi2 := phi1 + deltaPhi
if math.Abs(phi2) > math.Pi/2 {
if phi2 > 0 {
phi2 = math.Pi - phi2
} else {
phi2 = -math.Pi - phi2
}
}
deltaPsi := math.Log(math.Tan(phi2/2+math.Pi/4) / math.Tan(phi1/2+math.Pi/4))
var q float64
if math.Abs(deltaPsi) > 10e-12 {
q = deltaPhi / deltaPsi
} else {
q = math.Cos(phi1)
}
deltaLambda := delta * math.Sin(theta) / q
lambda2 := lambda1 + deltaLambda
lng := math.Mod((lambda2*180/math.Pi)+540, 360) - 180
lat := phi2 * 180 / math.Pi
return features.NewPoint([2]float64{lng, lat}, nil, nil)
} | measurements/destination.go | 0.790166 | 0.604195 | destination.go | starcoder |
package gmgmap
import "math/rand"
type connectInfo struct {
up bool
right bool
down bool
left bool
}
// NewRogue - generate a new Rogue-like map, with rooms connected with tunnels
func NewRogue(width, height,
gridWidth, gridHeight, minRoomPct, maxRoomPct int) *Map {
m := NewMap(width, height)
// Divide into grid, with flags marking grid connections
totalGrids := gridWidth * gridHeight
connected := make([]connectInfo, totalGrids)
// Pick random grid to start with
gridIndex := rand.Intn(len(connected))
firstRoomIndex := gridIndex
var lastRoomIndex int
grid := rect{gridIndex % gridWidth, gridIndex / gridWidth,
gridWidth, gridHeight}
// Connect to a random neighbour
for {
// Mark edges as already connected
if grid.x == 0 {
connected[gridIndex].left = true
}
if grid.y == 0 {
connected[gridIndex].up = true
}
if grid.x == gridWidth-1 {
connected[gridIndex].right = true
}
if grid.y == gridHeight-1 {
connected[gridIndex].down = true
}
// If all neighbours connected, end
if connected[gridIndex].allConnected() {
break
}
// Otherwise, connect to a random unconnected neighbour
for {
neighbourX, neighbourY := randomWalk(grid.x, grid.y, gridWidth, gridHeight)
neighbourIndex := neighbourX + neighbourY*gridWidth
if !tryConnect(connected, grid.x, grid.y, neighbourX, neighbourY,
gridIndex, neighbourIndex) {
continue
}
// Set neighbour as current grid
grid.x, grid.y, gridIndex = neighbourX, neighbourY, neighbourIndex
lastRoomIndex = neighbourIndex
break
}
}
// Scan for unconnected grids; if so try to connect them to a neighbouring
// connected grid
for {
hasUnconnected := false
for grid.x = 0; grid.x < gridWidth; grid.x++ {
for grid.y = 0; grid.y < gridHeight; grid.y++ {
gridIndex = grid.x + grid.y*gridWidth
if connected[gridIndex].isConnected() {
// Grid is already connected
continue
}
hasUnconnected = true
// If no neighbours connected, continue
if (grid.x == 0 || !connected[gridIndex-1].isConnected()) &&
(grid.x == gridWidth-1 || !connected[gridIndex+1].isConnected()) &&
(grid.y == 0 || !connected[gridIndex-gridWidth].isConnected()) &&
(grid.y == gridHeight-1 || !connected[gridIndex+gridWidth].isConnected()) {
continue
}
// Try connecting to a random connected neighbour
for {
neighbourX, neighbourY := randomWalk(grid.x, grid.y, gridWidth, gridHeight)
neighbourIndex := neighbourX + neighbourY*gridWidth
if !connected[neighbourIndex].isConnected() {
continue
}
if !tryConnect(connected, grid.x, grid.y, neighbourX, neighbourY,
gridIndex, neighbourIndex) {
panic("unexpected error")
}
lastRoomIndex = gridIndex
break
}
}
}
// Continue until no unconnected grids
if !hasUnconnected {
break
}
}
// Make some random connections
extraConnections := rand.Intn(gridWidth)
for i := 0; i < extraConnections; i++ {
for {
gridIndex = rand.Intn(len(connected))
grid.x = gridIndex % gridWidth
grid.y = gridIndex / gridWidth
if connected[gridIndex].allConnected() {
break
}
// Try connecting to a random neighbour
for {
neighbourX, neighbourY := randomWalk(grid.x, grid.y, gridWidth, gridHeight)
neighbourIndex := neighbourX + neighbourY*gridWidth
if tryConnect(connected, grid.x, grid.y, neighbourX, neighbourY,
gridIndex, neighbourIndex) {
break
}
}
break
}
}
g := m.Layer("Ground")
s := m.Layer("Structures")
// Try to place rooms - one for each grid
numRooms := (rand.Intn(maxRoomPct-minRoomPct) + minRoomPct) * totalGrids / 100
roomIndices := rand.Perm(totalGrids)
rooms := make([]rect, totalGrids)
gridWidthTiles := width / gridWidth
gridHeightTiles := height / gridHeight
for i := 0; i < totalGrids; i++ {
// Coordinates of grid top-left corner
grid.x, grid.y = roomIndices[i]%gridWidth, roomIndices[i]/gridWidth
grid.w, grid.h = gridWidth, gridHeight
gridStartX, gridStartY := grid.x*gridWidthTiles, grid.y*gridHeightTiles
var roomRect rect
// force dead ends to be rooms
numConnections := connected[roomIndices[i]].numConnections(grid)
// also force first/last room to be rooms
if i < numRooms || numConnections <= 1 ||
roomIndices[i] == firstRoomIndex || roomIndices[i] == lastRoomIndex {
// Generate random room
roomRect.w = rand.Intn(gridWidthTiles-4) + 4
roomRect.h = rand.Intn(gridHeightTiles-4) + 4
} else {
// Generate "gone rooms"
roomRect.w = 1
roomRect.h = 1
}
// Place the room
roomRect.x = rand.Intn(width/gridWidth-roomRect.w) + gridStartX
roomRect.y = rand.Intn(height/gridHeight-roomRect.h) + gridStartY
for x := roomRect.x; x < roomRect.x+roomRect.w; x++ {
for y := roomRect.y; y < roomRect.y+roomRect.h; y++ {
if roomRect.w > 1 &&
(x == roomRect.x || x == roomRect.x+roomRect.w-1 ||
y == roomRect.y || y == roomRect.y+roomRect.h-1) {
s.setTile(x, y, wall2)
} else {
g.setTile(x, y, room)
}
}
}
rooms[roomIndices[i]] = roomRect
}
// Connect each room to connected neighbours
for i := 0; i < totalGrids; i++ {
connections := connected[i]
x, y := i%gridWidth, i/gridHeight
roomRect := rooms[i]
// Only connect to the right and below
if connections.right && x < gridWidth-1 {
// Connect with neighbour on right
neighbour := rooms[i+1]
addCorridor(g, s, roomRect.x+roomRect.w-1, roomRect.y+roomRect.h/2,
neighbour.x, neighbour.y+neighbour.h/2, room2)
}
if connections.down && y < gridHeight-1 {
// Connect with neighbour below
neighbour := rooms[i+gridWidth]
addCorridor(g, s, roomRect.x+roomRect.w/2, roomRect.y+roomRect.h-1,
neighbour.x+neighbour.w/2, neighbour.y, room2)
}
}
// Find door tiles: those with 2 neighbour walls and 1 each of corridor/room
for y := 0; y < m.Height; y++ {
for x := 0; x < m.Width; x++ {
if IsWall(s.getTile(x, y)) {
continue
}
walls, corridors, rooms := 0, 0, 0
var countTile = func(x, y int) {
if IsWall(s.getTile(x, y)) {
walls++
} else {
switch g.getTile(x, y) {
case room:
rooms++
case room2:
corridors++
}
}
}
if y > 0 {
countTile(x, y-1)
}
if x < m.Width-1 {
countTile(x+1, y)
}
if y < m.Height-1 {
countTile(x, y+1)
}
if x > 0 {
countTile(x-1, y)
}
if walls == 2 && corridors == 1 && rooms == 1 {
s.setTile(x, y, door)
}
}
}
// Put stairs in the first and last room
firstRoom := rooms[firstRoomIndex]
lastRoom := rooms[lastRoomIndex]
s.setTile(firstRoom.x+firstRoom.w/2, firstRoom.y+firstRoom.h/2, stairsUp)
s.setTile(lastRoom.x+lastRoom.w/2, lastRoom.y+lastRoom.h/2, stairsDown)
return m
}
// Don't count edges as connections
func (c connectInfo) numConnections(grid rect) int {
n := 0
if c.up && grid.y > 0 {
n++
}
if c.right && grid.x < grid.w-1 {
n++
}
if c.down && grid.y < grid.h-1 {
n++
}
if c.left && grid.x > 0 {
n++
}
return n
}
func (c connectInfo) isConnected() bool {
return c.up || c.right || c.down || c.left
}
func (c connectInfo) allConnected() bool {
return c.up && c.right && c.down && c.left
}
func tryConnect(connected []connectInfo, x, y, x1, y1, index, index2 int) bool {
switch {
case y > y1:
// up
if connected[index].up {
return false
}
connected[index].up = true
connected[index2].down = true
case x < x1:
// right
if connected[index].right {
return false
}
connected[index].right = true
connected[index2].left = true
case y < y1:
// down
if connected[index].down {
return false
}
connected[index].down = true
connected[index2].up = true
case x > x1:
// left
if connected[index].left {
return false
}
connected[index].left = true
connected[index2].right = true
}
return true
} | gmgmap/rogue.go | 0.569613 | 0.460592 | rogue.go | starcoder |
package value
import "strconv"
// UInt holds a single uint64 value.
type UInt struct {
valPtr *uint64
}
// NewUInt makes a new UInt with the given uint64 value.
func NewUInt(val uint64) *UInt {
valPtr := new(uint64)
*valPtr = val
return &UInt{valPtr: valPtr}
}
// NewUIntFromPtr makes a new UInt with the given pointer to uint64 value.
func NewUIntFromPtr(valPtr *uint64) *UInt {
return &UInt{valPtr: valPtr}
}
// Set changes the uint64 value.
func (v *UInt) Set(val uint64) { *v.valPtr = val }
// Type return TypeUInt.
func (v *UInt) Type() Type { return TypeUInt }
// IsSlice returns false.
func (v *UInt) IsSlice() bool { return false }
// Clone produce a clone that is identical except for the backing pointer.
func (v *UInt) Clone() Value { return NewUInt(*v.valPtr) }
// Parse sets the value from the given string.
func (v *UInt) Parse(str string) error {
u, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return err
}
*v.valPtr = u
return nil
}
// ValuePointer returns the pointer for value storage.
func (v *UInt) ValuePointer() interface{} { return v.valPtr }
// Value returns the uint64 value.
func (v *UInt) Value() interface{} { return *v.valPtr }
// Equal returns checks if type and value of the given single are equal.
func (v *UInt) Equal(v2 Single) (bool, error) {
if err := CheckType(TypeUInt, v2.Type()); err != nil {
return false, err
}
return *v.valPtr == v2.Value().(uint64), nil
}
// Greater checks if the current value is greater than the given.
// Returns non-nil error if types do not match.
func (v *UInt) Greater(v2 Single) (bool, error) {
if err := CheckType(TypeUInt, v2.Type()); err != nil {
return false, err
}
return *v.valPtr > v2.Value().(uint64), nil
}
// GreaterEqual checks if the current value is greater or equal to the given.
// Returns non-nil error if types do not match.
func (v *UInt) GreaterEqual(v2 Single) (bool, error) {
if err := CheckType(TypeUInt, v2.Type()); err != nil {
return false, err
}
return *v.valPtr >= v2.Value().(uint64), nil
}
// Less checks if the current value is less than the given.
// Returns non-nil error if types do not match.
func (v *UInt) Less(v2 Single) (bool, error) {
if err := CheckType(TypeUInt, v2.Type()); err != nil {
return false, err
}
return *v.valPtr < v2.Value().(uint64), nil
}
// LessEqual checks if the current value is less or equal to the given.
// Returns non-nil error if types do not match.
func (v *UInt) LessEqual(v2 Single) (bool, error) {
if err := CheckType(TypeUInt, v2.Type()); err != nil {
return false, err
}
return *v.valPtr <= v2.Value().(uint64), nil
}
// OneOf checks if the current value is one of the given.
// Returns non-nil error if types do not match.
func (v *UInt) OneOf(v2 Slice) (bool, error) {
return v2.Contains(v)
} | value/uint.go | 0.799599 | 0.574037 | uint.go | starcoder |
package avl_tree
import (
"math"
)
type AVLTree struct {
root *Node
size int
}
func (a *AVLTree) GetSize() int {
return a.size
}
func (a *AVLTree) IsEmpty() bool {
return a.size == 0
}
func (a *AVLTree) isBalanced() bool {
return a.root.isBalanced()
}
func (a *AVLTree) Add(data int) {
a.size++
if a.root == nil {
// 根节点没有数据
a.root = NewNode(data)
return
}
// 防止root发生旋转
a.root = a.add(a.root, data)
}
func (a *AVLTree) Find(data int) *int {
if a.IsEmpty() {
// 空树
return nil
}
n := a.find(a.root, data)
if n == nil {
return nil
}
t := n.Data
return &t
}
func (a *AVLTree) Remove(data int) {
if a.IsEmpty() {
// 空树
return
}
// 防止删除根节点
a.root = a.remove(a.root, data)
}
// 内部使用
func (a *AVLTree) add(n *Node, data int) *Node {
r := data - n.Data
if r < 0 {
// 左
if n.left == nil {
n.left = NewNode(data)
} else {
a.add(n.left, data)
}
} else if r > 0 {
// 右
if n.right == nil {
n.right = NewNode(data)
} else {
a.add(n.right, data)
}
}
// 平衡
return a.balance(n)
}
func (a *AVLTree) balance(n *Node) *Node {
// 更新高度
n.height = 1 + int(math.Max(float64(n.left.getHeight()), float64(n.right.getHeight())))
factor := n.getBalanceFactor()
if factor > 1 && n.left.getBalanceFactor() > 0 {
// LL
return n.rightRotate()
}
if factor < -1 && n.right.getBalanceFactor() < 0 {
// RR
return n.leftRotate()
}
if factor > 1 && n.left.getBalanceFactor() < 0 {
// LR
t := n.left.rightRotate()
return t.rightRotate()
}
if factor < -1 && n.right.getBalanceFactor() > 0 {
// RL
t := n.right.right
return t.leftRotate()
}
return n
}
func (a *AVLTree) find(n *Node, data int) *Node {
if n == nil {
return nil
}
factor := data - n.Data
if factor == 0 {
return n
}
if factor < 0 {
return a.find(n.left, data)
} else {
return a.find(n.right, data)
}
}
// 返回被删除节点的替换节点
func (a *AVLTree) remove(n *Node, data int) *Node {
if n == nil {
return nil
}
var returnNode *Node
factor := data - n.Data
if factor < 0 {
// 左
n.left = a.remove(n.left, data)
returnNode = n
} else if factor > 0 {
// 右
n.right = a.remove(n.right, data)
returnNode = n
} else {
// 找到需要删除
a.size--
if n.left == nil {
// 左边为空
returnNode = n.right
n.right = nil
} else if n.right == nil {
// 删除右边为空
returnNode = n.left
n.left = nil
} else {
// 删除左右都不为空
min := a.minimum(n.right)
min.right = a.remove(n.right, min.Data)
min.left = n.left
n.right = nil
n.left = nil
returnNode = min
}
}
if returnNode == nil {
return nil
}
return a.balance(returnNode)
}
func (a *AVLTree) minimum(node *Node) *Node {
if node.left == nil {
return node
}
return a.minimum(node.left)
} | golang/datastructure/tree/avl-tree/avl_tree.go | 0.61231 | 0.442576 | avl_tree.go | starcoder |
package internal
import (
mgl "github.com/go-gl/mathgl/mgl32"
"math"
)
type Camera struct {
Position, WorldUp mgl.Vec3
Yaw, Pitch, Zoom float32
MovementSpeed, RotationSpeed float32
}
func cos(arg float32) float32 {
return float32(math.Cos(float64(arg)))
}
func sin(arg float32) float32 {
return float32(math.Sin(float64(arg)))
}
func (camera *Camera) PositionalVectors() (right, front, up mgl.Vec3) {
yaw, pitch := mgl.DegToRad(camera.Yaw), mgl.DegToRad(camera.Pitch)
front[0] = cos(yaw) * cos(pitch)
front[1] = sin(pitch)
front[2] = sin(yaw) * cos(pitch)
front = front.Normalize()
right = front.Cross(camera.WorldUp).Normalize()
up = right.Cross(front).Normalize()
return
}
func (camera *Camera) ViewMatrix() mgl.Mat4 {
_, front, up := camera.PositionalVectors()
return mgl.LookAtV(camera.Position, camera.Position.Add(front), up)
}
type Direction int
const (
ForwardDirection Direction = iota
BackwardDirection
UpDirection
DownDirection
LeftDirection
RightDirection
UpRotation
DownRotation
LeftRotation
RightRotation
)
func (camera *Camera) Move(delta float64, directions ...Direction) {
right, front, up := camera.PositionalVectors()
positionVelocity, rotationVelocity := camera.MovementSpeed*float32(delta), camera.RotationSpeed*float32(delta)
for _, direction := range directions {
switch direction {
case ForwardDirection:
camera.Position = camera.Position.Add(front.Mul(positionVelocity))
case BackwardDirection:
camera.Position = camera.Position.Sub(front.Mul(positionVelocity))
case UpDirection:
camera.Position = camera.Position.Add(up.Mul(positionVelocity))
case DownDirection:
camera.Position = camera.Position.Sub(up.Mul(positionVelocity))
case LeftDirection:
camera.Position = camera.Position.Sub(right.Mul(positionVelocity))
case RightDirection:
camera.Position = camera.Position.Add(right.Mul(positionVelocity))
case UpRotation:
camera.Pitch += rotationVelocity
case DownRotation:
camera.Pitch -= rotationVelocity
case LeftRotation:
camera.Yaw -= rotationVelocity
if camera.Yaw < -89 {
camera.Yaw = -89
}
case RightRotation:
camera.Yaw += rotationVelocity
if camera.Yaw > 89 {
camera.Yaw = 89
}
}
}
} | internal/camera.go | 0.767429 | 0.584212 | camera.go | starcoder |
package ui
import (
"bytes"
"fmt"
)
// DefaultTableColumnSeperator is the default seperater for tabluar columns
var DefaultTableColumnSeperator = "\t"
// Table is a UI component that renders the data in formatted in a table
type Table struct {
// Rows is the collection of rows in the table
Rows []*Row
// MaxCellWidth is the maximum allowed with for cells in the table
MaxCellWidth int
// Seperater for tabluar columns
Seperator string
}
// Row represents a row in a table
type Row struct {
// Cells is the group of cell for the row
Cells []*Cell
}
// Cell Represents a column in a row
type Cell struct {
Witdh int
// Data is the cell data
Data interface{}
formatted string
}
// NewTable returns an instance of Table with the given headers
func NewTable(headers ...interface{}) *Table {
t := &Table{Seperator: DefaultTableColumnSeperator}
if len(headers) == 0 {
return t
}
t.AddRow(headers...)
return t
}
// Add row adds the data as a row to the table
func (t *Table) AddRow(data ...interface{}) *Table {
cells := make([]*Cell, len(data))
for i, col := range data {
cells[i] = &Cell{Data: col, Witdh: t.MaxCellWidth}
}
t.Rows = append(t.Rows, &Row{Cells: cells})
return t
}
// Format returns the formated table
func (t *Table) String() string {
// determine no of columns
var colLen int
for _, row := range t.rows() {
if rlen := len(row.cells()); rlen > colLen {
colLen = rlen
}
}
// determine width for each column
colWidths := make([]int, colLen)
for _, row := range t.rows() {
for i, cell := range row.cells() {
if cellWidth := cell.width(t.MaxCellWidth); cellWidth > colWidths[i] {
colWidths[i] = cellWidth
}
}
}
var buf bytes.Buffer
for _, row := range t.rows() {
for i, cell := range row.cells() {
// format the data by resizing each cell to match the width of the column
dat := alignStringLeft(cell.Format(t.MaxCellWidth), colWidths[i])
buf.WriteString(dat + t.Seperator)
}
buf.WriteString("\n")
}
return buf.String()
}
// Format converts the data to a string. It inserts an ellipsis when the width
// of the cell exceeds the maxwidth. It does not trim when the maxwidth is set to 0
func (c *Cell) Format(maxwidth int) string {
if len(c.formatted) == 0 {
s := fmt.Sprintf("%v", c.Data)
if maxwidth != 0 && len(s) > maxwidth {
var buf bytes.Buffer
b := []byte(s)
for i := 0; i < maxwidth-3; i++ {
buf.WriteByte(b[i])
}
buf.WriteString("...")
c.formatted = buf.String()
return c.formatted
}
c.formatted = s
}
return c.formatted
}
func (c *Cell) width(maxwidth int) int {
return len(c.Format(maxwidth))
}
func alignStringLeft(s string, width int) string {
var buf bytes.Buffer
b := []byte(s)
for i := 0; i < width; i++ {
if i >= len(b) {
buf.WriteString(" ")
} else {
buf.WriteByte(b[i])
}
}
return buf.String()
}
func (t *Table) rows() []*Row {
if t.Rows == nil {
t.Rows = make([]*Row, 0)
}
return t.Rows
}
func (r *Row) cells() []*Cell {
if r.Cells == nil {
r.Cells = make([]*Cell, 0)
}
return r.Cells
} | ui/table.go | 0.683842 | 0.498291 | table.go | starcoder |
package filters
import (
"fmt"
"math"
"strings"
flowpb "github.com/cilium/cilium/api/v1/flow"
)
type portMap map[uint32]uint32
// FlowContext can carry state from one filter to another.
type FlowContext struct {
// tcpPorts is filled in when matching a wildcarded source port for a TCP SYN.
// Subsequent non-SYN TCP matches using the same FlowContext will match this stored port number.
// Keyed by the known destination port so that we can track multiple connections at the same time
tcpPorts portMap
// udpPorts is filled in when matching a wildcarded source port for a UDP request.
// Subsequent UDP matches using the same FlowContext will match this stored port number.
// Keyed by the known destination port so that we can track multiple connections at the same time
udpPorts portMap
}
func NewFlowContext() FlowContext {
return FlowContext{
tcpPorts: make(portMap, 1),
udpPorts: make(portMap, 1),
}
}
// FlowFilterFunc is a function to filter on a condition in a flow. It returns
// true if the condition is true.
type FlowFilterFunc func(flow *flowpb.Flow, fc *FlowContext) bool
type FlowFilterImplementation interface {
Match(flow *flowpb.Flow, fc *FlowContext) bool
String(fc *FlowContext) string
}
type FlowRequirement struct {
Filter FlowFilterImplementation
Msg string
SkipOnAggregation bool
}
type FlowSetRequirement struct {
First FlowRequirement
Middle []FlowRequirement
Last FlowRequirement
Except []FlowRequirement
}
type andFilter struct {
filters []FlowFilterImplementation
}
func (a *andFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
for _, f := range a.filters {
if !f.Match(flow, fc) {
return false
}
}
return true
}
func (a *andFilter) String(fc *FlowContext) string {
var s []string
for _, f := range a.filters {
s = append(s, f.String(fc))
}
return "and(" + strings.Join(s, ",") + ")"
}
// And returns true if all filters return true
func And(filters ...FlowFilterImplementation) FlowFilterImplementation {
return &andFilter{
filters: filters,
}
}
type orFilter struct {
filters []FlowFilterImplementation
}
func (o *orFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
for _, f := range o.filters {
if f.Match(flow, fc) {
return true
}
}
return false
}
func (o *orFilter) String(fc *FlowContext) string {
var s []string
for _, f := range o.filters {
s = append(s, f.String(fc))
}
return "or(" + strings.Join(s, ",") + ")"
}
// Or returns true if any FlowFilterImplementation return true
func Or(filters ...FlowFilterImplementation) FlowFilterImplementation {
return &orFilter{filters: filters}
}
type dropFilter struct{}
func (d *dropFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
return flow.GetDropReasonDesc() != flowpb.DropReason_DROP_REASON_UNKNOWN
}
func (d *dropFilter) String(fc *FlowContext) string {
return "drop"
}
// Drop matches on drops
func Drop() FlowFilterImplementation {
return &dropFilter{}
}
type l7DropFilter struct{}
func (d *l7DropFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l7 := flow.GetL7()
if l7 == nil {
return false
}
return flow.GetVerdict() == flowpb.Verdict_DROPPED
}
func (d *l7DropFilter) String(fc *FlowContext) string {
return "l7 drop"
}
// L7Drop matches on drops reported by L7 proxied
func L7Drop() FlowFilterImplementation {
return &l7DropFilter{}
}
type icmpFilter struct {
typ uint32
}
func (i *icmpFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l4 := flow.GetL4()
if l4 == nil {
return false
}
icmp := l4.GetICMPv4()
if icmp == nil {
return false
}
if icmp.Type != i.typ {
return false
}
return true
}
func (i *icmpFilter) String(fc *FlowContext) string {
return fmt.Sprintf("icmp(%d)", i.typ)
}
// ICMP matches on ICMP messages of the specified type
func ICMP(typ uint32) FlowFilterImplementation {
return &icmpFilter{typ: typ}
}
type icmpv6Filter struct {
typ uint32
}
func (i *icmpv6Filter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l4 := flow.GetL4()
if l4 == nil {
return false
}
icmpv6 := l4.GetICMPv6()
if icmpv6 == nil {
return false
}
if icmpv6.Type != i.typ {
return false
}
return true
}
func (i *icmpv6Filter) String(fc *FlowContext) string {
return fmt.Sprintf("icmpv6(%d)", i.typ)
}
// ICMPv6 matches on ICMPv6 messages of the specified type
func ICMPv6(typ uint32) FlowFilterImplementation {
return &icmpv6Filter{typ: typ}
}
type udpFilter struct {
srcPort int
dstPort int
}
func (u *udpFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l4 := flow.GetL4()
if l4 == nil {
return false
}
udp := l4.GetUDP()
if udp == nil {
return false
}
if u.srcPort != 0 && udp.SourcePort != uint32(u.srcPort) {
return false
}
if u.dstPort != 0 && udp.DestinationPort != uint32(u.dstPort) {
return false
}
if u.srcPort == 0 { // wildcarded source port
fc.udpPorts[udp.DestinationPort] = udp.SourcePort
}
// Match previously seen (ephemeral) source port as the destination port?
if u.dstPort == 0 && fc.udpPorts[udp.SourcePort] != udp.DestinationPort {
return false
}
return true
}
func (u *udpFilter) String(fc *FlowContext) string {
var s []string
srcPort := u.srcPort
if srcPort == 0 {
srcPort = int(fc.udpPorts[uint32(u.dstPort)])
}
if srcPort != 0 {
s = append(s, fmt.Sprintf("srcPort=%d", srcPort))
}
dstPort := u.dstPort
if dstPort == 0 {
dstPort = int(fc.udpPorts[uint32(u.srcPort)])
}
if dstPort != 0 {
s = append(s, fmt.Sprintf("dstPort=%d", dstPort))
}
return "udp(" + strings.Join(s, ",") + ")"
}
// UDP matches on UDP packets with the specified source and destination ports
func UDP(srcPort, dstPort int) FlowFilterImplementation {
return &udpFilter{srcPort: srcPort, dstPort: dstPort}
}
type tcpFlagsFilter struct {
syn, ack, fin, rst bool
}
func (t *tcpFlagsFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l4 := flow.GetL4()
if l4 == nil {
return false
}
tcp := l4.GetTCP()
if tcp == nil || tcp.Flags == nil {
return false
}
if tcp.Flags.SYN != t.syn || tcp.Flags.ACK != t.ack || tcp.Flags.FIN != t.fin || tcp.Flags.RST != t.rst {
return false
}
return true
}
func (t *tcpFlagsFilter) String(fc *FlowContext) string {
var s []string
if t.syn {
s = append(s, "syn")
}
if t.ack {
s = append(s, "ack")
}
if t.fin {
s = append(s, "fin")
}
if t.rst {
s = append(s, "rst")
}
return "tcpflags(" + strings.Join(s, ",") + ")"
}
// TCPFlags matches on TCP packets with the specified TCP flags
func TCPFlags(syn, ack, fin, rst bool) FlowFilterImplementation {
return &tcpFlagsFilter{syn: syn, ack: ack, fin: fin, rst: rst}
}
// FIN matches on TCP packets with FIN+ACK flags
func FIN() FlowFilterImplementation {
return TCPFlags(false, true, true, false)
}
// RST matches on TCP packets with RST+ACK flags
func RST() FlowFilterImplementation {
return TCPFlags(false, true, false, true)
}
// SYNACK matches on TCP packets with SYN+ACK flags
func SYNACK() FlowFilterImplementation {
return TCPFlags(true, true, false, false)
}
// SYN matches on TCP packets with SYN flag
func SYN() FlowFilterImplementation {
return TCPFlags(true, false, false, false)
}
type ipFilter struct {
srcIP string
dstIP string
}
func (i *ipFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
ip := flow.GetIP()
if ip == nil {
return false
}
if i.srcIP != "" && ip.Source != i.srcIP {
return false
}
if i.dstIP != "" && ip.Destination != i.dstIP {
return false
}
return true
}
func (i *ipFilter) String(fc *FlowContext) string {
var s []string
if i.srcIP != "" {
s = append(s, "src="+i.srcIP)
}
if i.dstIP != "" {
s = append(s, "dst="+i.dstIP)
}
return "ip(" + strings.Join(s, ",") + ")"
}
// IP matches on IP packets with specified source and destination IP
func IP(srcIP, dstIP string) FlowFilterImplementation {
return &ipFilter{srcIP: srcIP, dstIP: dstIP}
}
type tcpFilter struct {
srcPort uint32
dstPort uint32
}
func (t *tcpFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l4 := flow.GetL4()
if l4 == nil {
return false
}
tcp := l4.GetTCP()
if tcp == nil {
return false
}
if t.srcPort != 0 && tcp.SourcePort != uint32(t.srcPort) {
return false
}
if t.dstPort != 0 && tcp.DestinationPort != uint32(t.dstPort) {
return false
}
if t.srcPort == 0 {
if tcp.Flags != nil && tcp.Flags.SYN && !tcp.Flags.ACK && !tcp.Flags.FIN && !tcp.Flags.RST {
// save wildcarded source port
fc.tcpPorts[tcp.DestinationPort] = tcp.SourcePort
} else if tcp.SourcePort != fc.tcpPorts[tcp.DestinationPort] {
return false
}
}
// Match previously seen (ephemeral) source port as the destination port?
if t.dstPort == 0 && tcp.DestinationPort != fc.tcpPorts[tcp.SourcePort] {
return false
}
return true
}
func (t *tcpFilter) String(fc *FlowContext) string {
var s []string
if t.srcPort != 0 {
s = append(s, fmt.Sprintf("srcPort=%d", t.srcPort))
}
if t.dstPort != 0 {
s = append(s, fmt.Sprintf("dstPort=%d", t.dstPort))
}
return "tcp(" + strings.Join(s, ",") + ")"
}
// TCP matches on TCP packets with the specified source and destination ports
func TCP(srcPort, dstPort uint32) FlowFilterImplementation {
return &tcpFilter{srcPort: srcPort, dstPort: dstPort}
}
type dnsFilter struct {
query string
rcode uint32
}
func (d *dnsFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l7 := flow.GetL7()
if l7 == nil {
return false
}
dns := l7.GetDns()
if dns == nil {
return false
}
if d.query != "" && dns.Query != d.query {
return false
}
if d.rcode != math.MaxUint32 && dns.Rcode != d.rcode {
return false
}
return true
}
func (d *dnsFilter) String(fc *FlowContext) string {
var s []string
if d.query != "" {
s = append(s, fmt.Sprintf("query=%s", d.query))
}
if d.rcode != math.MaxUint32 {
s = append(s, fmt.Sprintf("rcode=%d", d.rcode))
}
return "dns(" + strings.Join(s, ",") + ")"
}
// DNS matches on proxied DNS packets containing a specific value, if any
func DNS(query string, rcode uint32) FlowFilterImplementation {
return &dnsFilter{query: query, rcode: rcode}
}
type httpFilter struct {
code uint32
method string
url string
protocol string
headers map[string]string
}
func (h *httpFilter) Match(flow *flowpb.Flow, fc *FlowContext) bool {
l7 := flow.GetL7()
if l7 == nil {
return false
}
http := l7.GetHttp()
if http == nil {
return false
}
if h.code != math.MaxUint32 && http.Code != h.code {
return false
}
if h.method != "" && http.Method != h.method {
return false
}
if h.url != "" && http.Url != h.url {
return false
}
if h.protocol != "" && http.Protocol != h.protocol {
return false
}
for k, v := range h.headers {
idx := -1
for i, hdr := range http.Headers {
if hdr != nil && hdr.Key == k && (v == "" || hdr.Value == v) {
idx = i
}
}
if idx < 0 {
return false
}
}
return true
}
func (h *httpFilter) String(fc *FlowContext) string {
var s []string
if h.code != math.MaxUint32 {
s = append(s, fmt.Sprintf("code=%d", h.code))
}
if h.method != "" {
s = append(s, fmt.Sprintf("method=%s", h.method))
}
if h.url != "" {
s = append(s, fmt.Sprintf("url=%s", h.url))
}
if h.protocol != "" {
s = append(s, fmt.Sprintf("protocol=%s", h.protocol))
}
if len(h.headers) > 0 {
var hs []string
for k, v := range h.headers {
hs = append(hs, fmt.Sprintf("%s=%s", k, v))
}
s = append(s, "headers=("+strings.Join(hs, ",")+")")
}
return "http(" + strings.Join(s, ",") + ")"
}
// HTTP matches on proxied HTTP packets containing a specific value, if any
func HTTP(code uint32, method, url string) FlowFilterImplementation {
return &httpFilter{code: code, method: method, url: url}
} | connectivity/filters/filters.go | 0.687 | 0.44559 | filters.go | starcoder |
package coo
import (
"math"
)
var WebMercator = &System{
toGeographic: func(east, north float64, ell *Ellipsoid) (lon, lat float64) {
if ell == nil {
ell = DefaultEllipsoid
}
a := ell.A
lon = east / a * toDeg
lat = math.Atan(math.Exp(north/a))*toDeg*2 - 90
return
},
fromGeographic: func(lon, lat float64, ell *Ellipsoid) (east, north float64) {
if ell == nil {
ell = DefaultEllipsoid
}
a := ell.A
east = lon * a * toRad
north = math.Log(math.Tan((90+lat)*toRad/2)) * a
return
},
}
func TransverseMercator(centralMeridian, scale, falseEasting, falseNorthing float64) *System {
return &System{
toGeographic: func(east, north float64, ell *Ellipsoid) (lon, lat float64) {
if ell == nil {
ell = DefaultEllipsoid
}
a := ell.A
fi := ell.Fi
north = (north - falseNorthing) / scale
n := f3rd(fi)
n2 := n * n
n3 := n2 * n
n4 := n3 * n
n5 := n4 * n
alpha := (a + b(a, fi)) / 2 * (1 + n2/4 + n4/64)
latta := 3*n/2 - 27*n3/32 + 269*n5/512
gamma := 21*n2/16 - 55*n4/32
dellta := 151*n3/96 - 417*n5/128
epsilon := 1097 * n4 / 512
Y := (east - falseEasting) / scale
Y2 := Y * Y
Y3 := Y2 * Y
Y4 := Y3 * Y
Y5 := Y4 * Y
Y6 := Y5 * Y
Y7 := Y6 * Y
BO := north / alpha
BF := BO + latta*math.Sin(2*BO) + gamma*math.Sin(4*BO) + dellta*math.Sin(6*BO) + epsilon*math.Sin(8*BO)
NF := a / math.Sqrt(1-(e2(fi)*math.Pow(math.Sin(BF), 2)))
NF2 := NF * NF
NF3 := NF2 * NF
NF4 := NF3 * NF
NF5 := NF4 * NF
NF6 := NF5 * NF
NF7 := NF6 * NF
NPhi := math.Sqrt(a * a / b2(a, fi) * e2(fi) * math.Pow(math.Cos(BF), 2))
NPhi2 := NPhi * NPhi
NPhi4 := NPhi2 * NPhi2
tF := math.Tan(BF)
tF2 := tF * tF
tF4 := tF2 * tF2
tF6 := tF4 * tF2
B1 := (tF / 2.0) / NF2 * (-1 - NPhi2) * Y2
B2 := (tF / 24.0) / NF4 * (5 + 3*tF2 + 6*NPhi2 - 6*tF2*NPhi2 - 4*NPhi4 - 9*tF2*NPhi4) * Y4
B3 := (tF / 720.0) / NF6 * (-61 - 90*tF2 - 45*tF4 - 107*NPhi2 + 162*tF2*NPhi2 + 45*tF4*NPhi2) * Y6
lat = (BF + B1 + B2 + B3) * toDeg
L1 := ((1 / NF) / math.Cos(BF)) * Y
L2 := (1 / 6.0 * 1 / NF3) / math.Cos(BF) * (-1 - 2*tF2 - NPhi2) * Y3
L3 := (1 / 120.0 * 1 / NF5) / math.Cos(BF) * (5 + 28*tF2 + 24*tF4 + 6*NPhi2 + 8*tF2*NPhi2) * Y5
L4 := (1 / 15040.0 * 1 / NF7) / math.Cos(BF) * (-61 - 622*tF2 - 1320*tF4 - 720*tF6) * Y7
lon = centralMeridian + (L1+L2+L3+L4)*toDeg
return
},
fromGeographic: func(lon, lat float64, ell *Ellipsoid) (east, north float64) {
if ell == nil {
ell = DefaultEllipsoid
}
a := ell.A
fi := ell.Fi
n := f3rd(fi)
n2 := n * n
n3 := n2 * n
n4 := n3 * n
n5 := n4 * n
alpha := (a + b(a, fi)) / 2 * (1 + n2/4 + n4/64)
beta := -3*n/2 + 9*n3/16 - 3*n5/32
gamma := 15*n2/16 - 15*n4/32
dellta := -35*n3/48 + 105*n5/256
epsilon := 315 * n4 / 512
lat *= toRad
l := (lon - centralMeridian) * toRad
l2 := l * l
l3 := l2 * l
l4 := l3 * l
Ne := a / math.Sqrt(1-e2(fi)*math.Pow(math.Sin(lat), 2))
eta := math.Sqrt(a * a / b2(a, fi) * e2(fi) * math.Pow(math.Cos(lat), 2))
t := math.Tan(lat)
R := alpha * (lat + beta*math.Sin(2*lat) + gamma*math.Sin(4*lat) + dellta*math.Sin(6*lat) + epsilon*math.Sin(8*lat))
h1 := t / 2 * Ne * math.Pow(math.Cos(lat), 2) * l2
h2 := t / 24 * Ne * math.Pow(math.Cos(lat), 4) * (5 - t*t + 9*eta*eta + 4*eta*eta*eta*eta) * l4
north = (R+h1+h2)*scale + falseNorthing
r1 := Ne * math.Cos(lat) * l
r2 := Ne / 6 * math.Pow(math.Cos(lat), 3) * (1 - t*t + eta*eta) * l3
east = (r1+r2)*scale + falseEasting
return
},
}
}
func UTM(zone float64, hemisphere string) *System {
for {
if zone > 0 && zone < 61 {
break
}
if zone < 1 {
zone += 60
}
if zone > 60 {
zone = math.Mod(zone, 60)
}
}
if hemisphere == "S" {
return TransverseMercator(zone*6-183, 0.9996, 500000, 10000000)
}
return TransverseMercator(zone*6-183, 0.9996, 500000, 0)
}
func GaussKrueger(zone float64) *System {
for {
if zone > 0 && zone < 121 {
break
}
if zone < 1 {
zone += 120
}
if zone > 120 {
zone = math.Mod(zone, 120)
}
}
return TransverseMercator(zone*3, 1, zone*1000000+500000, 0)
}
func ConformalConic(lat1, lat2, falseLat, falseLon, falseEasting, falseNorthing float64) *System {
return &System{
toGeographic: func(east, north float64, ell *Ellipsoid) (lon, lat float64) {
if ell == nil {
ell = DefaultEllipsoid
}
a := ell.A
fi := ell.Fi
f := 1 / fi
ef := math.Sqrt(2*f - f*f)
m := func(l float64) float64 {
return math.Cos(l) / math.Sqrt(1-ef*ef*math.Pow(math.Sin(l), 2))
}
m1 := m(lat1 * toRad)
m2 := m(lat2 * toRad)
t := func(l float64) float64 {
return math.Tan(math.Pi*0.25-l*0.5) / math.Pow((1-ef*math.Sin(l))/(1+ef*math.Sin(l)), ef/2)
}
tO := t(falseLat * toRad)
t1 := t(lat1 * toRad)
t2 := t(lat2 * toRad)
n := (math.Log(m1) - math.Log(m2)) / (math.Log(t1) - math.Log(t2))
if lat1 == lat2 {
n = math.Sin(lat1 * toRad)
}
F := m1 / (n * math.Pow(t1, n))
pO := a * F * math.Pow(tO, n)
Ni := north - falseNorthing
Ei := east - falseEasting
pi := math.Sqrt(math.Abs(Ei*Ei + math.Pow(pO-Ni, 2)))
if n < 0 {
pi = -pi
}
ti := math.Pow(pi/(a*F), 1/n)
yi := math.Atan(Ei / (pO - Ni))
lat = math.Pi*0.5 - 2*math.Atan(ti)
for i := 0; i < 3; i++ {
lat = math.Pi*0.5 - 2*math.Atan(ti*math.Pow((1-ef*math.Sin(lat))/(1+ef*math.Sin(lat)), ef/2))
}
lat *= toDeg
lon = (yi/n + falseLon*toRad) * toDeg
return
},
fromGeographic: func(lon, lat float64, ell *Ellipsoid) (east, north float64) {
lon *= toRad
lat *= toRad
if ell == nil {
ell = DefaultEllipsoid
}
a := ell.A
fi := ell.Fi
f := 1 / fi
ef := math.Sqrt(2*f - f*f)
m := func(l float64) float64 {
return math.Cos(l) / math.Sqrt(1-ef*ef*math.Pow(math.Sin(l), 2))
}
m1 := m(lat1 * toRad)
m2 := m(lat2 * toRad)
t := func(l float64) float64 {
return math.Tan(math.Pi*0.25-l*0.5) / math.Pow((1-ef*math.Sin(l))/(1+ef*math.Sin(l)), ef/2)
}
t1 := t(lat1 * toRad)
t2 := t(lat2 * toRad)
n := (math.Log(m1) - math.Log(m2)) / (math.Log(t1) - math.Log(t2))
if lat1 == lat2 {
n = math.Sin(lat1 * toRad)
}
F := m1 / (n * math.Pow(t1, n))
p := func(l float64) float64 {
return a * F * math.Pow(t(l), n)
}
pO := p(falseLat * toRad)
y := n * (lon - falseLon*toRad)
north = falseNorthing + pO - p(lat)*math.Cos(y)
east = falseEasting + p(lat)*math.Sin(y)
return
},
}
} | system.go | 0.656658 | 0.511168 | system.go | starcoder |
package sliceWrapper
const objectTemplate = `{{range .Types}}
type {{.NameTitle}}Slice struct {
s []{{.Name}}
}
func New{{.NameTitle}}Slice() *{{.NameTitle}}Slice {
return &{{.NameTitle}}Slice{}
}
func (v *{{.NameTitle}}Slice) Clear() {
v.s = v.s[:0]
}
func (v *{{.NameTitle}}Slice) Equal(rhs *{{.NameTitle}}Slice) bool {
if rhs == nil {
return false
}
if len(v.s) != len(rhs.s) {
return false
}
for i := range v.s {
if v.s[i] != rhs.s[i] {
return false
}
}
return true
}
func (v *{{.NameTitle}}Slice) MarshalJSON() ([]byte, error) {
return json.Marshal(v.s)
}
func (v *{{.NameTitle}}Slice) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &v.s)
}
func (v *{{.NameTitle}}Slice) Copy(rhs *{{.NameTitle}}Slice) {
v.s = make([]{{.Name}}, len(rhs.s))
copy(v.s, rhs.s)
}
func (v *{{.NameTitle}}Slice) Clone() *{{.NameTitle}}Slice {
return &{{.NameTitle}}Slice{
s: v.s[:],
}
}
func (v *{{.NameTitle}}Slice) Index(rhs {{.Name}}) int {
for i, lhs := range v.s {
if lhs == rhs {
return i
}
}
return -1
}
func (v *{{.NameTitle}}Slice) Append(n {{.Name}}) {
v.s = append(v.s, n)
}
func (v *{{.NameTitle}}Slice) Insert(i int, n {{.Name}}) {
if i < 0 || i > len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go error trying to insert at index %d\n", i)
return
}
v.s = append(v.s, reflect.Zero(reflect.TypeOf(n)).Interface().({{.Name}}))
copy(v.s[i+1:], v.s[i:])
v.s[i] = n
}
func (v *{{.NameTitle}}Slice) Remove(i int) {
if i < 0 || i >= len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go error trying to remove bad index %d\n", i)
return
}
copy(v.s[i:], v.s[i+1:])
v.s[len(v.s)-1] = reflect.Zero(reflect.TypeOf(v.s[i])).Interface().({{.Name}})
v.s = v.s[:len(v.s)-1]
}
func (v *{{.NameTitle}}Slice) Count() int {
return len(v.s)
}
func (v *{{.NameTitle}}Slice) At(i int) {{.Name}} {
if i < 0 || i >= len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go invalid index %d\n", i)
}
return v.s[i]
}
func (v *{{.NameTitle}}Slice) GetItem(i int) (i int) Any {
if i < 0 || i >= len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go invalid index %d\n", i)
}
return v.s[i]
}
func New{{.NameTitle}}SliceWithObjects(objects []{{.Name}}) *{{.NameTitle}}Slice {
pSlice := make([]{{.Name}}, 0, len(objects))
for _, i := range objects {
pSlice = append(pSlice, i)
}
return &{{.NameTitle}}Slice{pSlice}
}
{{end}}` | sliceWrapper/objectTemplate.go | 0.669096 | 0.50891 | objectTemplate.go | starcoder |
package ml
import (
"fmt"
"math"
"math/rand"
"strconv"
cabiriaMath "github.com/liampulles/cabiria/pkg/math"
)
// Split can be used to split training ang test data by a percentage.
// The resulting arrays are pseudorandom in composition; not consistent
// between runs.
func Split(samples []Sample, split float64) ([]Sample, []Sample) {
rand.Shuffle(len(samples), func(i, j int) { samples[i], samples[j] = samples[j], samples[i] })
cutoff := int(math.Ceil(float64(len(samples)) * cabiriaMath.ClampFloat64(split, 0.0, 1.0)))
return samples[:cutoff], samples[cutoff:]
}
// Test runs test samples against a trained predictor to see how accurate it is.
// The result is percentage accuracy.
func Test(cls Predictor, testData []Sample) (float64, error) {
passed := 0
for _, datum := range testData {
prediction, err := cls.PredictSingle(datum.Input)
if err != nil {
return -1.0, err
}
match, err := Match(datum.Output, prediction)
if err != nil {
return -1.0, err
}
if match {
passed++
}
}
return float64(passed) / float64(len(testData)), nil
}
// Match returns true if the Datum' are the same, otherwise false.
// An error is returned if the Datum' have different lengths.
func Match(actual Datum, expected Datum) (bool, error) {
if len(actual) != len(expected) {
return false, fmt.Errorf("Cannot Match outputs with different lengths. Actual length: %d, expected length: %d",
len(actual), len(expected))
}
for i, actualI := range actual {
if actualI != expected[i] {
return false, nil
}
}
return true, nil
}
// InitializeKMeans implements the init step for KMeans++ (at least,
// it implements whatever this GeeksForGeeks article says:
// https://www.geeksforgeeks.org/ml-k-means-algorithm/)
func InitializeKMeans(input []Datum, k int) ([]Datum, error) {
if k == 0 {
return []Datum{}, nil
}
if len(input) < k {
return nil, fmt.Errorf("need at least k input to initialize KMeans")
}
centroids := make([]Datum, 1)
// Effectively choose a pseudo-random element, but don;t change in-between
// runs so our tests remian deterministic
centroids[0] = input[1820244659%len(input)]
for len(centroids) < k {
newCentroid, err := computeNextBestCentroid(centroids, input)
if err != nil {
return nil, err
}
centroids = append(centroids, newCentroid)
}
return centroids, nil
}
// AsCSV maps a datum to a CSV line for ML purposes.
func (d Datum) AsCSV() string {
result := ""
for i, elem := range d {
if i > 0 {
result = result + ","
}
result = result + strconv.FormatFloat(elem, 'f', -1, 64)
}
return result
}
func computeNextBestCentroid(centroids []Datum, input []Datum) (Datum, error) {
largestSquareDist := -1.0
largestIdx := -1
for i, elem := range input {
squareDist, err := squareDistanceToClosestCentroid(centroids, elem)
if err != nil {
return nil, err
}
if squareDist > largestSquareDist {
largestSquareDist = squareDist
largestIdx = i
}
}
return input[largestIdx], nil
}
func squareDistanceToClosestCentroid(centroids []Datum, elem Datum) (float64, error) {
min := math.MaxFloat64
for _, centroid := range centroids {
squareDist, err := cabiriaMath.SquareDistance(elem, centroid)
if err != nil {
return -1.0, err
}
if squareDist < min {
min = squareDist
}
}
return min, nil
} | pkg/ml/common.go | 0.703957 | 0.514949 | common.go | starcoder |
package indexer
import (
"github.com/Jragonmiris/mathgl"
)
// Note: is_near is implemented in mathgl already as FloatEqual
type PackedVertex struct {
Position mathgl.Vec3f
UV mathgl.Vec2f
Norm mathgl.Vec3f
}
// Only implementing the fast version
func IndexVBO(vertices []mathgl.Vec3f, uvs []mathgl.Vec2f, normals []mathgl.Vec3f) (outIndices []uint16, outVertices []mathgl.Vec3f, outUVs []mathgl.Vec2f, outNorms []mathgl.Vec3f) {
vertToOutIndex := make(map[PackedVertex]uint16, 0)
for i := range vertices {
packed := PackedVertex{vertices[i], uvs[i], normals[i]}
index, ok := vertToOutIndex[packed]
if ok {
outIndices = append(outIndices, index)
} else {
outVertices = append(outVertices, vertices[i])
outUVs = append(outUVs, uvs[i])
outNorms = append(outNorms, normals[i])
index = uint16(len(outVertices) - 1)
outIndices = append(outIndices, index)
vertToOutIndex[packed] = index
}
}
return
}
func IndexVBOSlow(vertices []mathgl.Vec3f, uvs []mathgl.Vec2f, normals []mathgl.Vec3f) (outIndices []uint16, outVertices []mathgl.Vec3f, outUVs []mathgl.Vec2f, outNorms []mathgl.Vec3f) {
for i := range vertices {
index, ok := SimilarVertexIndexSlow(vertices[i], uvs[i], normals[i], outVertices, outUVs, outNorms)
if ok {
outIndices = append(outIndices, index)
} else {
outVertices = append(outVertices, vertices[i])
outUVs = append(outUVs, uvs[i])
outNorms = append(outNorms, normals[i])
index = uint16(len(outVertices) - 1)
outIndices = append(outIndices, index)
}
}
return
}
func SimilarVertexIndexSlow(vertex mathgl.Vec3f, uv mathgl.Vec2f, normal mathgl.Vec3f, vertices []mathgl.Vec3f, uvs []mathgl.Vec2f, normals []mathgl.Vec3f) (index uint16, found bool) {
// Lame linear search
for i := range vertices {
if mathgl.FloatEqualThreshold32(vertex[0], vertices[i][0], .01) && mathgl.FloatEqualThreshold32(vertex[1], vertices[i][1], .01) && mathgl.FloatEqualThreshold32(vertex[2], vertices[i][2], .01) &&
mathgl.FloatEqualThreshold32(uv[0], uvs[i][0], .01) && mathgl.FloatEqualThreshold32(uv[1], uvs[i][1], .01) &&
mathgl.FloatEqualThreshold32(normal[0], normals[i][0], .01) && mathgl.FloatEqualThreshold32(normal[1], normals[i][1], .01) && mathgl.FloatEqualThreshold32(normal[2], normals[i][2], .01) {
return uint16(i), true
}
}
// No other vertex could be used instead.
// Looks like we'll have to add it to the VBO.
return uint16(0), false
} | examples/opengl-tutorial/indexer/indexer.go | 0.628521 | 0.501465 | indexer.go | starcoder |
package sql
import (
"fmt"
"io"
)
// SelectStatement represents a SQL SELECT statement.
type SelectStatement struct {
Fields []string
TableName string
}
// Parser represents a parser.
type Parser struct {
s *Scanner
buf struct {
tok Token // last read token
lit string // last read literal
n int // buffer size (max=1)
}
}
// NewParser returns a new instance of Parser.
func NewParser(r io.Reader) *Parser {
return &Parser{s: NewScanner(r)}
}
// Parse parses a SQL SELECT statement.
func (p *Parser) Parse() (*SelectStatement, error) {
stmt := &SelectStatement{}
// First token should be a "SELECT" keyword.
if tok, lit := p.scanIgnoreWhitespace(); tok != SELECT {
return nil, fmt.Errorf("found %q, expected SELECT", lit)
}
// Next we should loop over all our comma-delimited fields.
for {
// Read a field.
tok, lit := p.scanIgnoreWhitespace()
if tok != IDENT && tok != ASTERISK {
return nil, fmt.Errorf("found %q, expected field", lit)
}
stmt.Fields = append(stmt.Fields, lit)
// If the next token is not a comma then break the loop.
if tok, _ := p.scanIgnoreWhitespace(); tok != COMMA {
p.unscan()
break
}
}
// Next we should see the "FROM" keyword.
if tok, lit := p.scanIgnoreWhitespace(); tok != FROM {
return nil, fmt.Errorf("found %q, expected FROM", lit)
}
// Finally we should read the table name.
tok, lit := p.scanIgnoreWhitespace()
if tok != IDENT {
return nil, fmt.Errorf("found %q, expected table name", lit)
}
stmt.TableName = lit
// Return the successfully parsed statement.
return stmt, nil
}
// scan returns the next token from the underlying scanner.
// If a token has been unscanned then read that instead.
func (p *Parser) scan() (Token, string) {
// If we have a token on the buffer, then return it.
if p.buf.n != 0 {
p.buf.n = 0
return p.buf.tok, p.buf.lit
}
// Otherwise read the next token from the scanner.
tok, lit := p.s.Scan()
// Save it to the buffer in case we unscan later.
p.buf.tok, p.buf.lit = tok, lit
return tok, lit
}
// scanIgnoreWhitespace scans the next non-whitespace token.
func (p *Parser) scanIgnoreWhitespace() (Token, string) {
tok, lit := p.scan()
if tok == WS {
return p.scan()
}
return tok, lit
}
// unscan pushes the previously read token back onto the buffer.
func (p *Parser) unscan() { p.buf.n = 1 } | parser.go | 0.70253 | 0.40869 | parser.go | starcoder |
package k8sTest
import (
"bytes"
"context"
"fmt"
"net"
"path/filepath"
"time"
. "github.com/cilium/cilium/test/ginkgo-ext"
"github.com/cilium/cilium/test/helpers"
external_ips "github.com/cilium/cilium/test/k8sT/manifests/externalIPs"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
const (
namespaceTest = "external-ips-test"
)
func skipSuite(name string, t func()) bool {
return false
}
// Replace "skipSuite" with "Describe" to enable the suite.
var _ = skipSuite("K8sKubeProxyFreeMatrix tests", func() {
var (
kubectl *helpers.Kubectl
ciliumFilename string
podNode1 string
podNode2 string
hostNetworkPodNode1 string
hostNetworkPodNode2 string
// name2IP maps the service-name-cluster-ip to the running clusterIP
// assigned by kubernetes. Since the IPs are ephemeral over CI runs,
// it's the only way we can have consistent test results for the same
// unit test.
name2IP = map[string]string{
"svc-a-external-ips-cluster-ip": "",
"svc-b-external-ips-cluster-ip": "",
"svc-c-node-port-cluster-ip": "",
"svc-d-node-port-cluster-ip": "",
"svc-e-node-port-cluster-ip": "",
}
)
// deploys cilium with the given options.
deployCilium := func(options map[string]string) {
DeployCiliumOptionsAndDNS(kubectl, ciliumFilename, options)
_, err := kubectl.CiliumNodesWait()
ExpectWithOffset(1, err).Should(BeNil(), "Failure while waiting for k8s nodes to be annotated by Cilium")
By("Making sure all endpoints are in ready state")
err = kubectl.CiliumEndpointWaitReady()
ExpectWithOffset(1, err).To(BeNil(), "Failure while waiting for all cilium endpoints to reach ready state")
}
// Returns the pod nome for the given label.
getPodName := func(lbl string) string {
podNames, err := kubectl.GetPodNames(namespaceTest, lbl)
Expect(err).To(BeNil(), "Cannot get pods names")
Expect(len(podNames)).To(BeNumerically("==", 1), "No pods available to test connectivity, expected 1, got %d", len(podNames))
return podNames[0]
}
// Returns the pod name running in the given node for the given filter.
getPodNodeName := func(nodeName, filter string) string {
podNames, err := kubectl.GetPodsNodes(namespaceTest, filter)
Expect(err).To(BeNil(), "Cannot get pods names")
Expect(len(podNames)).To(BeNumerically(">", 0), "No pods available to test connectivity")
var podName string
for nodePodName, node := range podNames {
if nodeName == node {
podName = nodePodName
break
}
}
Expect(podName).To(Not(Equal("")), "No pods available to test connectivity, expected pods to be running on node %s: %+v", nodeName, podNames)
return podName
}
BeforeAll(func() {
if !helpers.RunsOn419OrLaterKernel() {
return
}
kubectl = helpers.CreateKubectl(helpers.K8s1VMName(), logger)
ciliumFilename = helpers.TimestampFilename("cilium.yaml")
DeployCiliumAndDNS(kubectl, ciliumFilename)
// create namespace used for this test
res := kubectl.NamespaceCreate(namespaceTest)
res.ExpectSuccess("unable to create namespace %q", namespaceTest)
externalIPsDir := helpers.ManifestGet(kubectl.BasePath(), "externalIPs")
// Deploy server and client pods
appsDir := filepath.Join(externalIPsDir, "apps")
kubectl.ApplyDefault(appsDir)
err := kubectl.WaitforPods(namespaceTest, "", helpers.HelperTimeout)
Expect(err).To(BeNil())
podNode1 = getPodName("id=app1")
podNode2 = getPodName("id=app3")
hostNetworkPodNode1 = getPodNodeName(helpers.K8s1, "id=host-client")
hostNetworkPodNode2 = getPodNodeName(helpers.K8s2, "id=host-client")
// map the public and private ip addresses of k8s1. We need to do this
// since the public and private IP addresses are also ephemeral across
// CI runs.
getIntIP := `ip -4 address show dev %s | grep inet | awk '{ print $2 }' | sed 's+/.*++' | tr -d '\n'`
publicIPGrep := fmt.Sprintf(getIntIP, external_ips.PublicInterfaceName)
privateIPGrep := fmt.Sprintf(getIntIP, external_ips.PrivateInterfaceName)
cmd := kubectl.ExecPodContainerCmd(namespaceTest, hostNetworkPodNode1, "curl", publicIPGrep)
publicIP := cmd.CombineOutput().String()
cmd = kubectl.ExecPodContainerCmd(namespaceTest, hostNetworkPodNode1, "curl", privateIPGrep)
privateIP := cmd.CombineOutput().String()
for k, v := range external_ips.NetDevTranslation {
switch v {
case external_ips.PublicInterfaceName:
name2IP[k] = publicIP
case external_ips.PrivateInterfaceName:
name2IP[k] = privateIP
}
}
svcsDir := filepath.Join(externalIPsDir, "svcs")
svcA := filepath.Join(svcsDir, "svc-a-external-ips.yaml")
svcB := filepath.Join(svcsDir, "svc-b-external-ips.yaml")
svcC := filepath.Join(svcsDir, "svc-c-node-port.yaml")
svcD := filepath.Join(svcsDir, "svc-d-node-port.yaml")
svcE := filepath.Join(svcsDir, "svc-e-node-port.yaml")
// Create svcA and svcB with the patched IP addresses that we have discovered
patch := fmt.Sprintf(`'{"spec":{"externalIPs":["192.0.2.223","%s","%s"]}}'`, publicIP, privateIP)
err = kubectl.DeployPatchStdIn(svcA, patch)
Expect(err).To(BeNil())
err = kubectl.DeployPatchStdIn(svcB, patch)
Expect(err).To(BeNil())
kubectl.ApplyDefault(svcC).ExpectSuccess("Unable to deploy service-c")
kubectl.ApplyDefault(svcD).ExpectSuccess("Unable to deploy service-d")
kubectl.ApplyDefault(svcE).ExpectSuccess("Unable to deploy service-e")
setClusterIPOf := func(name string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
clusterIP, err := kubectl.GetSvcIP(ctx, namespaceTest, name)
Expect(err).To(BeNil())
name2IP[name+"-cluster-ip"] = clusterIP
}
setClusterIPOf("svc-a-external-ips")
setClusterIPOf("svc-b-external-ips")
setClusterIPOf("svc-c-node-port")
setClusterIPOf("svc-d-node-port")
setClusterIPOf("svc-e-node-port")
})
AfterFailed(func() {
if !helpers.RunsOn419OrLaterKernel() {
return
}
kubectl.CiliumReport("cilium service list", "cilium endpoint list")
})
AfterAll(func() {
if !helpers.RunsOn419OrLaterKernel() {
return
}
UninstallCiliumFromManifest(kubectl, ciliumFilename)
_ = kubectl.NamespaceDelete(namespaceTest)
kubectl.CloseSSHClient()
})
testFunc := func(podClient string) func(ipName, ip, port, expected, skipReason string) {
return func(ipName, ip, port, expected, skipReason string) {
testIP, ok := name2IP[ipName]
if !ok {
testIP = ip
}
curlCmd := fmt.Sprintf("curl --connect-timeout 2 -v %s", net.JoinHostPort(testIP, port))
cmd := kubectl.ExecPodContainerCmd(namespaceTest, podClient, "curl", curlCmd)
b := cmd.CombineOutput().Bytes()
var got string
switch {
case bytes.Contains(b, []byte("Guestbook")):
got = "app1"
case bytes.Contains(b, []byte("Connection refused")):
got = "connection refused"
case bytes.Contains(b, []byte("No route to host")),
bytes.Contains(b, []byte("Network unreachable")),
bytes.Contains(b, []byte("Host is unreachable")),
bytes.Contains(b, []byte("Connection timed out")):
got = "No route to host / connection timed out"
case bytes.Contains(b, []byte("It works!")):
got = "app2"
case bytes.Contains(b, []byte("app4")):
got = "app4"
case bytes.Contains(b, []byte("app6")):
got = "app6"
default:
got = "None? " + string(b)
}
if skipReason != "" {
if got != expected {
Skip(skipReason)
return
}
// TODO @brb, once the kube-proxy free is merged in master
// we can uncomment this
// Expect(got).ToNot(Equal(expected), "It seems this test is disabled but your changes have fix this test case")
return
}
Expect(got).To(Equal(expected), cmd.GetCmd())
}
}
SkipContextIf(
func() bool { return helpers.DoesNotRunOn419OrLaterKernel() },
"DirectRouting", func() {
BeforeAll(func() {
deployCilium(map[string]string{
"tunnel": "disabled",
"autoDirectNodeRoutes": "true",
"devices": external_ips.PublicInterfaceName,
"nodePort.enabled": "true",
"bpf.masquerade": "false",
})
})
DescribeTable("From pod running on node-1 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(podNode1)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromPodInNode1)...,
)
DescribeTable("From host running on node-1 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(hostNetworkPodNode1)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromNode1)...,
)
DescribeTable("From pod running on node-2 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(podNode2)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromPodInNode2)...,
)
DescribeTable("From host running on node-2 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(hostNetworkPodNode2)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromNode2)...,
)
// TODO: Enable me once the 3rd VM is added to the CI
// DescribeTable("From host running on node-3 to services being backed by a pod running on node-1",
// func(ipName, ip, port, expected, skipReason string) {
// testFunc(hostNetworkPodNode3)(ipName, ip, port, expected, skipReason)
// },
// getTableEntries(external_ips.ExpectedResultFromNode2)...,
// )
},
)
SkipContextIf(
func() bool { return helpers.DoesNotRunOn419OrLaterKernel() },
"VxLANMode", func() {
BeforeAll(func() {
deployCilium(map[string]string{
"tunnel": "vxlan",
"devices": external_ips.PublicInterfaceName,
"nodePort.enabled": "true",
"bpf.masquerade": "false",
})
})
DescribeTable("From pod running on node-1 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(podNode1)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromPodInNode1)...,
)
DescribeTable("From host running on node-1 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(hostNetworkPodNode1)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromNode1)...,
)
DescribeTable("From pod running on node-2 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(podNode2)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromPodInNode2)...,
)
DescribeTable("From host running on node-2 to services being backed by a pod running on node-1",
func(ipName, ip, port, expected, skipReason string) {
testFunc(hostNetworkPodNode2)(ipName, ip, port, expected, skipReason)
},
getTableEntries(external_ips.ExpectedResultFromNode2)...,
)
// TODO: Enable me once the 3rd VM is added to the CI
// DescribeTable("From host running on node-3 to services being backed by a pod running on node-1",
// func(ipName, ip, port, expected, skipReason string) {
// testFunc(hostNetworkPodNode3)(ipName, ip, port, expected, skipReason)
// },
// getTableEntries(external_ips.ExpectedResultFromNode2)...,
// )
},
)
})
func getTableEntries(expectedResult map[string]map[string]external_ips.EntryTestArgs) []TableEntry {
var te []TableEntry
for ipName, ipPortTest := range expectedResult {
for _, testCaseExpected := range ipPortTest {
te = append(te, Entry(
fmt.Sprintf("%s curl %s",
testCaseExpected.Description,
net.JoinHostPort(ipName, testCaseExpected.Port),
),
ipName,
testCaseExpected.IP,
testCaseExpected.Port,
testCaseExpected.Expected,
testCaseExpected.SkipReason,
))
}
}
return te
} | test/k8sT/external_ips.go | 0.574514 | 0.451629 | external_ips.go | starcoder |
package ring
import (
"math/bits"
"unsafe"
)
// NTT computes the NTT of p1 and returns the result on p2.
func (r *Ring) NTT(p1, p2 *Poly) {
r.NumberTheoreticTransformer.Forward(r, p1, p2)
}
// NTTLvl computes the NTT of p1 and returns the result on p2.
// The value level defines the number of moduli of the input polynomials.
func (r *Ring) NTTLvl(level int, p1, p2 *Poly) {
r.NumberTheoreticTransformer.ForwardLvl(r, level, p1, p2)
}
// NTTLazy computes the NTT of p1 and returns the result on p2.
// Output values are in the range [0, 2q-1]
func (r *Ring) NTTLazy(p1, p2 *Poly) {
r.NumberTheoreticTransformer.ForwardLazy(r, p1, p2)
}
// NTTLazyLvl computes the NTT of p1 and returns the result on p2.
// The value level defines the number of moduli of the input polynomials.
// Output values are in the range [0, 2q-1]
func (r *Ring) NTTLazyLvl(level int, p1, p2 *Poly) {
r.NumberTheoreticTransformer.ForwardLazyLvl(r, level, p1, p2)
}
// NTTSingle computes the NTT of p1 and returns the result on p2.
// The level-th moduli of the ring NTT params are used.
func (r *Ring) NTTSingle(level int, p1, p2 []uint64) {
r.NumberTheoreticTransformer.ForwardVec(r, level, p1, p2)
}
// NTTSingleLazy computes the NTT of p1 and returns the result on p2.
// The level-th moduli of the ring NTT params are used.
// Output values are in the range [0, 2q-1]
func (r *Ring) NTTSingleLazy(level int, p1, p2 []uint64) {
r.NumberTheoreticTransformer.ForwardLazyVec(r, level, p1, p2)
}
// InvNTT computes the inverse-NTT of p1 and returns the result on p2.
func (r *Ring) InvNTT(p1, p2 *Poly) {
r.NumberTheoreticTransformer.Backward(r, p1, p2)
}
// InvNTTLvl computes the inverse-NTT of p1 and returns the result on p2.
// The value level defines the number of moduli of the input polynomials.
func (r *Ring) InvNTTLvl(level int, p1, p2 *Poly) {
r.NumberTheoreticTransformer.BackwardLvl(r, level, p1, p2)
}
// InvNTTLazy computes the inverse-NTT of p1 and returns the result on p2.
// Output values are in the range [0, 2q-1]
func (r *Ring) InvNTTLazy(p1, p2 *Poly) {
r.NumberTheoreticTransformer.BackwardLazy(r, p1, p2)
}
// InvNTTLazyLvl computes the inverse-NTT of p1 and returns the result on p2.
// The value level defines the number of moduli of the input polynomials.
// Output values are in the range [0, 2q-1]
func (r *Ring) InvNTTLazyLvl(level int, p1, p2 *Poly) {
r.NumberTheoreticTransformer.BackwardLazyLvl(r, level, p1, p2)
}
// InvNTTSingle computes the InvNTT of p1 and returns the result on p2.
// The level-th moduli of the ring InvNTT params are used.
// Only computes the InvNTT for the i-th level.
func (r *Ring) InvNTTSingle(level int, p1, p2 []uint64) {
r.NumberTheoreticTransformer.BackwardVec(r, level, p1, p2)
}
// InvNTTSingleLazy computes the InvNTT of p1 and returns the result on p2.
// The level-th moduli of the ring InvNTT params are used.
// Output values are in the range [0, 2q-1]
func (r *Ring) InvNTTSingleLazy(level int, p1, p2 []uint64) {
r.NumberTheoreticTransformer.BackwardLazyVec(r, level, p1, p2)
}
// butterfly computes X, Y = U + V*Psi, U - V*Psi mod Q.
func butterfly(U, V, Psi, twoQ, fourQ, Q, Qinv uint64) (uint64, uint64) {
if U >= fourQ {
U -= fourQ
}
V = MRedConstant(V, Psi, Q, Qinv)
return U + V, U + twoQ - V
}
// invbutterfly computes X, Y = U + V, (U - V) * Psi mod Q.
func invbutterfly(U, V, Psi, twoQ, fourQ, Q, Qinv uint64) (X, Y uint64) {
X = U + V
if X >= twoQ {
X -= twoQ
}
Y = MRedConstant(U+fourQ-V, Psi, Q, Qinv) // At the moment it is not possible to use MRedConstant if Q > 61 bits
return
}
// NTT computes the NTT on the input coefficients using the input parameters.
func NTT(coeffsIn, coeffsOut []uint64, N int, nttPsi []uint64, Q, mredParams uint64, bredParams []uint64) {
NTTLazy(coeffsIn, coeffsOut, N, nttPsi, Q, mredParams, bredParams)
ReduceVec(coeffsOut, coeffsOut, Q, bredParams)
}
// NTTLazy computes the NTT on the input coefficients using the input parameters with output values in the range [0, 2q-1].
func NTTLazy(coeffsIn, coeffsOut []uint64, N int, nttPsi []uint64, Q, QInv uint64, bredParams []uint64) {
var j1, j2, t int
var F, V uint64
fourQ := 4 * Q
twoQ := 2 * Q
// Copy the result of the first round of butterflies on p2 with approximate reduction
t = N >> 1
F = nttPsi[1]
for jx, jy := 0, t; jx <= t-1; jx, jy = jx+8, jy+8 {
xin := (*[8]uint64)(unsafe.Pointer(&coeffsIn[jx]))
yin := (*[8]uint64)(unsafe.Pointer(&coeffsIn[jy]))
xout := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
yout := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
V = MRedConstant(yin[0], F, Q, QInv)
xout[0], yout[0] = xin[0]+V, xin[0]+twoQ-V
V = MRedConstant(yin[1], F, Q, QInv)
xout[1], yout[1] = xin[1]+V, xin[1]+twoQ-V
V = MRedConstant(yin[2], F, Q, QInv)
xout[2], yout[2] = xin[2]+V, xin[2]+twoQ-V
V = MRedConstant(yin[3], F, Q, QInv)
xout[3], yout[3] = xin[3]+V, xin[3]+twoQ-V
V = MRedConstant(yin[4], F, Q, QInv)
xout[4], yout[4] = xin[4]+V, xin[4]+twoQ-V
V = MRedConstant(yin[5], F, Q, QInv)
xout[5], yout[5] = xin[5]+V, xin[5]+twoQ-V
V = MRedConstant(yin[6], F, Q, QInv)
xout[6], yout[6] = xin[6]+V, xin[6]+twoQ-V
V = MRedConstant(yin[7], F, Q, QInv)
xout[7], yout[7] = xin[7]+V, xin[7]+twoQ-V
}
// Continue the rest of the second to the n-1 butterflies on p2 with approximate reduction
var reduce bool
for m := 2; m < N; m <<= 1 {
reduce = (bits.Len64(uint64(m))&1 == 1)
t >>= 1
if t >= 8 {
for i := 0; i < m; i++ {
j1 = (i * t) << 1
j2 = j1 + t - 1
F = nttPsi[m+i]
if reduce {
for jx, jy := j1, j1+t; jx <= j2; jx, jy = jx+8, jy+8 {
x := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
y := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
x[0], y[0] = butterfly(x[0], y[0], F, twoQ, fourQ, Q, QInv)
x[1], y[1] = butterfly(x[1], y[1], F, twoQ, fourQ, Q, QInv)
x[2], y[2] = butterfly(x[2], y[2], F, twoQ, fourQ, Q, QInv)
x[3], y[3] = butterfly(x[3], y[3], F, twoQ, fourQ, Q, QInv)
x[4], y[4] = butterfly(x[4], y[4], F, twoQ, fourQ, Q, QInv)
x[5], y[5] = butterfly(x[5], y[5], F, twoQ, fourQ, Q, QInv)
x[6], y[6] = butterfly(x[6], y[6], F, twoQ, fourQ, Q, QInv)
x[7], y[7] = butterfly(x[7], y[7], F, twoQ, fourQ, Q, QInv)
}
} else {
for jx, jy := j1, j1+t; jx <= j2; jx, jy = jx+8, jy+8 {
x := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
y := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
V = MRedConstant(y[0], F, Q, QInv)
x[0], y[0] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(y[1], F, Q, QInv)
x[1], y[1] = x[1]+V, x[1]+twoQ-V
V = MRedConstant(y[2], F, Q, QInv)
x[2], y[2] = x[2]+V, x[2]+twoQ-V
V = MRedConstant(y[3], F, Q, QInv)
x[3], y[3] = x[3]+V, x[3]+twoQ-V
V = MRedConstant(y[4], F, Q, QInv)
x[4], y[4] = x[4]+V, x[4]+twoQ-V
V = MRedConstant(y[5], F, Q, QInv)
x[5], y[5] = x[5]+V, x[5]+twoQ-V
V = MRedConstant(y[6], F, Q, QInv)
x[6], y[6] = x[6]+V, x[6]+twoQ-V
V = MRedConstant(y[7], F, Q, QInv)
x[7], y[7] = x[7]+V, x[7]+twoQ-V
}
}
}
} else if t == 4 {
if reduce {
for i, j1 := m, 0; i < 2*m; i, j1 = i+2, j1+4*t {
psi := (*[2]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[4] = butterfly(x[0], x[4], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[5] = butterfly(x[1], x[5], psi[0], twoQ, fourQ, Q, QInv)
x[2], x[6] = butterfly(x[2], x[6], psi[0], twoQ, fourQ, Q, QInv)
x[3], x[7] = butterfly(x[3], x[7], psi[0], twoQ, fourQ, Q, QInv)
x[8], x[12] = butterfly(x[8], x[12], psi[1], twoQ, fourQ, Q, QInv)
x[9], x[13] = butterfly(x[9], x[13], psi[1], twoQ, fourQ, Q, QInv)
x[10], x[14] = butterfly(x[10], x[14], psi[1], twoQ, fourQ, Q, QInv)
x[11], x[15] = butterfly(x[11], x[15], psi[1], twoQ, fourQ, Q, QInv)
}
} else {
for i, j1 := m, 0; i < 2*m; i, j1 = i+2, j1+4*t {
psi := (*[2]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
V = MRedConstant(x[4], psi[0], Q, QInv)
x[0], x[4] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(x[5], psi[0], Q, QInv)
x[1], x[5] = x[1]+V, x[1]+twoQ-V
V = MRedConstant(x[6], psi[0], Q, QInv)
x[2], x[6] = x[2]+V, x[2]+twoQ-V
V = MRedConstant(x[7], psi[0], Q, QInv)
x[3], x[7] = x[3]+V, x[3]+twoQ-V
V = MRedConstant(x[12], psi[1], Q, QInv)
x[8], x[12] = x[8]+V, x[8]+twoQ-V
V = MRedConstant(x[13], psi[1], Q, QInv)
x[9], x[13] = x[9]+V, x[9]+twoQ-V
V = MRedConstant(x[14], psi[1], Q, QInv)
x[10], x[14] = x[10]+V, x[10]+twoQ-V
V = MRedConstant(x[15], psi[1], Q, QInv)
x[11], x[15] = x[11]+V, x[11]+twoQ-V
}
}
} else if t == 2 {
if reduce {
for i, j1 := m, 0; i < 2*m; i, j1 = i+4, j1+8*t {
psi := (*[4]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[2] = butterfly(x[0], x[2], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[3] = butterfly(x[1], x[3], psi[0], twoQ, fourQ, Q, QInv)
x[4], x[6] = butterfly(x[4], x[6], psi[1], twoQ, fourQ, Q, QInv)
x[5], x[7] = butterfly(x[5], x[7], psi[1], twoQ, fourQ, Q, QInv)
x[8], x[10] = butterfly(x[8], x[10], psi[2], twoQ, fourQ, Q, QInv)
x[9], x[11] = butterfly(x[9], x[11], psi[2], twoQ, fourQ, Q, QInv)
x[12], x[14] = butterfly(x[12], x[14], psi[3], twoQ, fourQ, Q, QInv)
x[13], x[15] = butterfly(x[13], x[15], psi[3], twoQ, fourQ, Q, QInv)
}
} else {
for i, j1 := m, 0; i < 2*m; i, j1 = i+4, j1+8*t {
psi := (*[4]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
V = MRedConstant(x[2], psi[0], Q, QInv)
x[0], x[2] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(x[3], psi[0], Q, QInv)
x[1], x[3] = x[1]+V, x[1]+twoQ-V
V = MRedConstant(x[6], psi[1], Q, QInv)
x[4], x[6] = x[4]+V, x[4]+twoQ-V
V = MRedConstant(x[7], psi[1], Q, QInv)
x[5], x[7] = x[5]+V, x[5]+twoQ-V
V = MRedConstant(x[10], psi[2], Q, QInv)
x[8], x[10] = x[8]+V, x[8]+twoQ-V
V = MRedConstant(x[11], psi[2], Q, QInv)
x[9], x[11] = x[9]+V, x[9]+twoQ-V
V = MRedConstant(x[14], psi[3], Q, QInv)
x[12], x[14] = x[12]+V, x[12]+twoQ-V
V = MRedConstant(x[15], psi[3], Q, QInv)
x[13], x[15] = x[13]+V, x[13]+twoQ-V
}
}
} else {
for i, j1 := m, 0; i < 2*m; i, j1 = i+8, j1+16 {
psi := (*[8]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[1] = butterfly(x[0], x[1], psi[0], twoQ, fourQ, Q, QInv)
x[2], x[3] = butterfly(x[2], x[3], psi[1], twoQ, fourQ, Q, QInv)
x[4], x[5] = butterfly(x[4], x[5], psi[2], twoQ, fourQ, Q, QInv)
x[6], x[7] = butterfly(x[6], x[7], psi[3], twoQ, fourQ, Q, QInv)
x[8], x[9] = butterfly(x[8], x[9], psi[4], twoQ, fourQ, Q, QInv)
x[10], x[11] = butterfly(x[10], x[11], psi[5], twoQ, fourQ, Q, QInv)
x[12], x[13] = butterfly(x[12], x[13], psi[6], twoQ, fourQ, Q, QInv)
x[14], x[15] = butterfly(x[14], x[15], psi[7], twoQ, fourQ, Q, QInv)
}
/*
for i := uint64(0); i < m; i = i + 8 {
psi := (*[8]uint64)(unsafe.Pointer(&nttPsi[m+i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[2*i]))
V = MRedConstant(x[1], psi[0], Q, QInv)
x[0], x[1] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(x[3], psi[1], Q, QInv)
x[2], x[3] = x[2]+V, x[2]+twoQ-V
V = MRedConstant(x[5], psi[2], Q, QInv)
x[4], x[5] = x[4]+V, x[4]+twoQ-V
V = MRedConstant(x[7], psi[3], Q, QInv)
x[6], x[7] = x[6]+V, x[6]+twoQ-V
V = MRedConstant(x[9], psi[4], Q, QInv)
x[8], x[9] = x[8]+V, x[8]+twoQ-V
V = MRedConstant(x[11], psi[5], Q, QInv)
x[10], x[11] = x[10]+V, x[10]+twoQ-V
V = MRedConstant(x[13], psi[6], Q, QInv)
x[12], x[13] = x[12]+V, x[12]+twoQ-V
V = MRedConstant(x[15], psi[7], Q, QInv)
x[14], x[15] = x[14]+V, x[14]+twoQ-V
}
*/
}
}
}
func invNTTCore(coeffsIn, coeffsOut []uint64, N int, nttPsiInv []uint64, Q, QInv uint64) {
var h, t int
var F uint64
// Copy the result of the first round of butterflies on p2 with approximate reduction
t = 1
h = N >> 1
twoQ := Q << 1
fourQ := Q << 2
for i, j := h, 0; i < 2*h; i, j = i+8, j+16 {
psi := (*[8]uint64)(unsafe.Pointer(&nttPsiInv[i]))
xin := (*[16]uint64)(unsafe.Pointer(&coeffsIn[j]))
xout := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j]))
xout[0], xout[1] = invbutterfly(xin[0], xin[1], psi[0], twoQ, fourQ, Q, QInv)
xout[2], xout[3] = invbutterfly(xin[2], xin[3], psi[1], twoQ, fourQ, Q, QInv)
xout[4], xout[5] = invbutterfly(xin[4], xin[5], psi[2], twoQ, fourQ, Q, QInv)
xout[6], xout[7] = invbutterfly(xin[6], xin[7], psi[3], twoQ, fourQ, Q, QInv)
xout[8], xout[9] = invbutterfly(xin[8], xin[9], psi[4], twoQ, fourQ, Q, QInv)
xout[10], xout[11] = invbutterfly(xin[10], xin[11], psi[5], twoQ, fourQ, Q, QInv)
xout[12], xout[13] = invbutterfly(xin[12], xin[13], psi[6], twoQ, fourQ, Q, QInv)
xout[14], xout[15] = invbutterfly(xin[14], xin[15], psi[7], twoQ, fourQ, Q, QInv)
}
// Continue the rest of the second to the n-1 butterflies on p2 with approximate reduction
t <<= 1
for m := N >> 1; m > 1; m >>= 1 {
h = m >> 1
if t >= 8 {
for i, j1, j2 := 0, 0, t-1; i < h; i, j1, j2 = i+1, j1+2*t, j2+2*t {
F = nttPsiInv[h+i]
for jx, jy := j1, j1+t; jx <= j2; jx, jy = jx+8, jy+8 {
x := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
y := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
x[0], y[0] = invbutterfly(x[0], y[0], F, twoQ, fourQ, Q, QInv)
x[1], y[1] = invbutterfly(x[1], y[1], F, twoQ, fourQ, Q, QInv)
x[2], y[2] = invbutterfly(x[2], y[2], F, twoQ, fourQ, Q, QInv)
x[3], y[3] = invbutterfly(x[3], y[3], F, twoQ, fourQ, Q, QInv)
x[4], y[4] = invbutterfly(x[4], y[4], F, twoQ, fourQ, Q, QInv)
x[5], y[5] = invbutterfly(x[5], y[5], F, twoQ, fourQ, Q, QInv)
x[6], y[6] = invbutterfly(x[6], y[6], F, twoQ, fourQ, Q, QInv)
x[7], y[7] = invbutterfly(x[7], y[7], F, twoQ, fourQ, Q, QInv)
}
}
} else if t == 4 {
for i, j1 := h, 0; i < 2*h; i, j1 = i+2, j1+4*t {
psi := (*[2]uint64)(unsafe.Pointer(&nttPsiInv[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[4] = invbutterfly(x[0], x[4], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[5] = invbutterfly(x[1], x[5], psi[0], twoQ, fourQ, Q, QInv)
x[2], x[6] = invbutterfly(x[2], x[6], psi[0], twoQ, fourQ, Q, QInv)
x[3], x[7] = invbutterfly(x[3], x[7], psi[0], twoQ, fourQ, Q, QInv)
x[8], x[12] = invbutterfly(x[8], x[12], psi[1], twoQ, fourQ, Q, QInv)
x[9], x[13] = invbutterfly(x[9], x[13], psi[1], twoQ, fourQ, Q, QInv)
x[10], x[14] = invbutterfly(x[10], x[14], psi[1], twoQ, fourQ, Q, QInv)
x[11], x[15] = invbutterfly(x[11], x[15], psi[1], twoQ, fourQ, Q, QInv)
}
} else {
for i, j1 := h, 0; i < 2*h; i, j1 = i+4, j1+8*t {
psi := (*[4]uint64)(unsafe.Pointer(&nttPsiInv[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[2] = invbutterfly(x[0], x[2], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[3] = invbutterfly(x[1], x[3], psi[0], twoQ, fourQ, Q, QInv)
x[4], x[6] = invbutterfly(x[4], x[6], psi[1], twoQ, fourQ, Q, QInv)
x[5], x[7] = invbutterfly(x[5], x[7], psi[1], twoQ, fourQ, Q, QInv)
x[8], x[10] = invbutterfly(x[8], x[10], psi[2], twoQ, fourQ, Q, QInv)
x[9], x[11] = invbutterfly(x[9], x[11], psi[2], twoQ, fourQ, Q, QInv)
x[12], x[14] = invbutterfly(x[12], x[14], psi[3], twoQ, fourQ, Q, QInv)
x[13], x[15] = invbutterfly(x[13], x[15], psi[3], twoQ, fourQ, Q, QInv)
}
}
t <<= 1
}
}
// InvNTT computes the InvNTT transformation on the input coefficients using the input parameters.
func InvNTT(coeffsIn, coeffsOut []uint64, N int, nttPsiInv []uint64, nttNInv, Q, QInv uint64) {
invNTTCore(coeffsIn, coeffsOut, N, nttPsiInv, Q, QInv)
MulScalarMontgomeryVec(coeffsOut, coeffsOut, nttNInv, Q, QInv)
}
// InvNTTLazy computes the InvNTT transformation on the input coefficients using the input parameters with output values in the range [0, 2q-1].
func InvNTTLazy(coeffsIn, coeffsOut []uint64, N int, nttPsiInv []uint64, nttNInv, Q, QInv uint64) {
invNTTCore(coeffsIn, coeffsOut, N, nttPsiInv, Q, QInv)
MulScalarMontgomeryConstantVec(coeffsOut, coeffsOut, nttNInv, Q, QInv)
}
// NTTConjugateInvariant computes the NTT in the closed sub-ring Z[X + X^-1]/(X^2N +1) of Z[X]/(X^2N+1).
func NTTConjugateInvariant(coeffsIn, coeffsOut []uint64, N int, nttPsi []uint64, Q, QInv uint64, bredParams []uint64) {
NTTConjugateInvariantLazy(coeffsIn, coeffsOut, N, nttPsi, Q, QInv, bredParams)
ReduceVec(coeffsOut, coeffsOut, Q, bredParams)
}
// NTTConjugateInvariantLazy computes the NTT in the closed sub-ring Z[X + X^-1]/(X^2N +1) of Z[X]/(X^2N+1) with output values in the range [0, 2q-1].
func NTTConjugateInvariantLazy(coeffsIn, coeffsOut []uint64, N int, nttPsi []uint64, Q, QInv uint64, bredParams []uint64) {
var t, h int
var F, V uint64
var reduce bool
fourQ := 4 * Q
twoQ := 2 * Q
// Copy the result of the first round of butterflies on p2 with approximate reduction
t = N
F = nttPsi[1]
for jx, jy := 1, N-8; jx < (N>>1)-7; jx, jy = jx+8, jy-8 {
xin := (*[8]uint64)(unsafe.Pointer(&coeffsIn[jx]))
yin := (*[8]uint64)(unsafe.Pointer(&coeffsIn[jy]))
xout := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
yout := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
xout[0], yout[7] = xin[0]+twoQ-MRedConstant(yin[7], F, Q, QInv), yin[7]+twoQ-MRedConstant(xin[0], F, Q, QInv)
xout[1], yout[6] = xin[1]+twoQ-MRedConstant(yin[6], F, Q, QInv), yin[6]+twoQ-MRedConstant(xin[1], F, Q, QInv)
xout[2], yout[5] = xin[2]+twoQ-MRedConstant(yin[5], F, Q, QInv), yin[5]+twoQ-MRedConstant(xin[2], F, Q, QInv)
xout[3], yout[4] = xin[3]+twoQ-MRedConstant(yin[4], F, Q, QInv), yin[4]+twoQ-MRedConstant(xin[3], F, Q, QInv)
xout[4], yout[3] = xin[4]+twoQ-MRedConstant(yin[3], F, Q, QInv), yin[3]+twoQ-MRedConstant(xin[4], F, Q, QInv)
xout[5], yout[2] = xin[5]+twoQ-MRedConstant(yin[2], F, Q, QInv), yin[2]+twoQ-MRedConstant(xin[5], F, Q, QInv)
xout[6], yout[1] = xin[6]+twoQ-MRedConstant(yin[1], F, Q, QInv), yin[1]+twoQ-MRedConstant(xin[6], F, Q, QInv)
xout[7], yout[0] = xin[7]+twoQ-MRedConstant(yin[0], F, Q, QInv), yin[0]+twoQ-MRedConstant(xin[7], F, Q, QInv)
}
j := (N >> 1) - 7
xin := (*[7]uint64)(unsafe.Pointer(&coeffsIn[j]))
yin := (*[7]uint64)(unsafe.Pointer(&coeffsIn[N-j-6]))
xout := (*[7]uint64)(unsafe.Pointer(&coeffsOut[j]))
yout := (*[7]uint64)(unsafe.Pointer(&coeffsOut[N-j-6]))
xout[0], yout[6] = xin[0]+twoQ-MRedConstant(yin[6], F, Q, QInv), yin[6]+twoQ-MRedConstant(xin[0], F, Q, QInv)
xout[1], yout[5] = xin[1]+twoQ-MRedConstant(yin[5], F, Q, QInv), yin[5]+twoQ-MRedConstant(xin[1], F, Q, QInv)
xout[2], yout[4] = xin[2]+twoQ-MRedConstant(yin[4], F, Q, QInv), yin[4]+twoQ-MRedConstant(xin[2], F, Q, QInv)
xout[3], yout[3] = xin[3]+twoQ-MRedConstant(yin[3], F, Q, QInv), yin[3]+twoQ-MRedConstant(xin[3], F, Q, QInv)
xout[4], yout[2] = xin[4]+twoQ-MRedConstant(yin[2], F, Q, QInv), yin[2]+twoQ-MRedConstant(xin[4], F, Q, QInv)
xout[5], yout[1] = xin[5]+twoQ-MRedConstant(yin[1], F, Q, QInv), yin[1]+twoQ-MRedConstant(xin[5], F, Q, QInv)
xout[6], yout[0] = xin[6]+twoQ-MRedConstant(yin[0], F, Q, QInv), yin[0]+twoQ-MRedConstant(xin[6], F, Q, QInv)
coeffsOut[N>>1] = coeffsIn[N>>1] + twoQ - MRedConstant(coeffsIn[N>>1], F, Q, QInv)
coeffsOut[0] = coeffsIn[0]
// Continue the rest of the second to the n-1 butterflies on p2 with approximate reduction
for m := 2; m < 2*N; m <<= 1 {
reduce = (bits.Len64(uint64(m))&1 == 1)
t >>= 1
h = m >> 1
if t >= 8 {
for i, j1, j2 := 0, 0, t-1; i < h; i, j1, j2 = i+1, j1+2*t, j2+2*t {
F = nttPsi[m+i]
if reduce {
for jx, jy := j1, j1+t; jx <= j2; jx, jy = jx+8, jy+8 {
x := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
y := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
x[0], y[0] = butterfly(x[0], y[0], F, twoQ, fourQ, Q, QInv)
x[1], y[1] = butterfly(x[1], y[1], F, twoQ, fourQ, Q, QInv)
x[2], y[2] = butterfly(x[2], y[2], F, twoQ, fourQ, Q, QInv)
x[3], y[3] = butterfly(x[3], y[3], F, twoQ, fourQ, Q, QInv)
x[4], y[4] = butterfly(x[4], y[4], F, twoQ, fourQ, Q, QInv)
x[5], y[5] = butterfly(x[5], y[5], F, twoQ, fourQ, Q, QInv)
x[6], y[6] = butterfly(x[6], y[6], F, twoQ, fourQ, Q, QInv)
x[7], y[7] = butterfly(x[7], y[7], F, twoQ, fourQ, Q, QInv)
}
} else {
for jx, jy := j1, j1+t; jx <= j2; jx, jy = jx+8, jy+8 {
x := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
y := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
V = MRedConstant(y[0], F, Q, QInv)
x[0], y[0] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(y[1], F, Q, QInv)
x[1], y[1] = x[1]+V, x[1]+twoQ-V
V = MRedConstant(y[2], F, Q, QInv)
x[2], y[2] = x[2]+V, x[2]+twoQ-V
V = MRedConstant(y[3], F, Q, QInv)
x[3], y[3] = x[3]+V, x[3]+twoQ-V
V = MRedConstant(y[4], F, Q, QInv)
x[4], y[4] = x[4]+V, x[4]+twoQ-V
V = MRedConstant(y[5], F, Q, QInv)
x[5], y[5] = x[5]+V, x[5]+twoQ-V
V = MRedConstant(y[6], F, Q, QInv)
x[6], y[6] = x[6]+V, x[6]+twoQ-V
V = MRedConstant(y[7], F, Q, QInv)
x[7], y[7] = x[7]+V, x[7]+twoQ-V
}
}
}
} else if t == 4 {
if reduce {
for i, j1 := m, 0; i < h+m; i, j1 = i+2, j1+4*t {
psi := (*[2]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[4] = butterfly(x[0], x[4], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[5] = butterfly(x[1], x[5], psi[0], twoQ, fourQ, Q, QInv)
x[2], x[6] = butterfly(x[2], x[6], psi[0], twoQ, fourQ, Q, QInv)
x[3], x[7] = butterfly(x[3], x[7], psi[0], twoQ, fourQ, Q, QInv)
x[8], x[12] = butterfly(x[8], x[12], psi[1], twoQ, fourQ, Q, QInv)
x[9], x[13] = butterfly(x[9], x[13], psi[1], twoQ, fourQ, Q, QInv)
x[10], x[14] = butterfly(x[10], x[14], psi[1], twoQ, fourQ, Q, QInv)
x[11], x[15] = butterfly(x[11], x[15], psi[1], twoQ, fourQ, Q, QInv)
}
} else {
for i, j1 := m, 0; i < h+m; i, j1 = i+2, j1+4*t {
psi := (*[2]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
V = MRedConstant(x[4], psi[0], Q, QInv)
x[0], x[4] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(x[5], psi[0], Q, QInv)
x[1], x[5] = x[1]+V, x[1]+twoQ-V
V = MRedConstant(x[6], psi[0], Q, QInv)
x[2], x[6] = x[2]+V, x[2]+twoQ-V
V = MRedConstant(x[7], psi[0], Q, QInv)
x[3], x[7] = x[3]+V, x[3]+twoQ-V
V = MRedConstant(x[12], psi[1], Q, QInv)
x[8], x[12] = x[8]+V, x[8]+twoQ-V
V = MRedConstant(x[13], psi[1], Q, QInv)
x[9], x[13] = x[9]+V, x[9]+twoQ-V
V = MRedConstant(x[14], psi[1], Q, QInv)
x[10], x[14] = x[10]+V, x[10]+twoQ-V
V = MRedConstant(x[15], psi[1], Q, QInv)
x[11], x[15] = x[11]+V, x[11]+twoQ-V
}
}
} else if t == 2 {
if reduce {
for i, j1 := m, 0; i < h+m; i, j1 = i+4, j1+8*t {
psi := (*[4]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[2] = butterfly(x[0], x[2], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[3] = butterfly(x[1], x[3], psi[0], twoQ, fourQ, Q, QInv)
x[4], x[6] = butterfly(x[4], x[6], psi[1], twoQ, fourQ, Q, QInv)
x[5], x[7] = butterfly(x[5], x[7], psi[1], twoQ, fourQ, Q, QInv)
x[8], x[10] = butterfly(x[8], x[10], psi[2], twoQ, fourQ, Q, QInv)
x[9], x[11] = butterfly(x[9], x[11], psi[2], twoQ, fourQ, Q, QInv)
x[12], x[14] = butterfly(x[12], x[14], psi[3], twoQ, fourQ, Q, QInv)
x[13], x[15] = butterfly(x[13], x[15], psi[3], twoQ, fourQ, Q, QInv)
}
} else {
for i, j1 := m, 0; i < h+m; i, j1 = i+4, j1+8*t {
psi := (*[4]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
V = MRedConstant(x[2], psi[0], Q, QInv)
x[0], x[2] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(x[3], psi[0], Q, QInv)
x[1], x[3] = x[1]+V, x[1]+twoQ-V
V = MRedConstant(x[6], psi[1], Q, QInv)
x[4], x[6] = x[4]+V, x[4]+twoQ-V
V = MRedConstant(x[7], psi[1], Q, QInv)
x[5], x[7] = x[5]+V, x[5]+twoQ-V
V = MRedConstant(x[10], psi[2], Q, QInv)
x[8], x[10] = x[8]+V, x[8]+twoQ-V
V = MRedConstant(x[11], psi[2], Q, QInv)
x[9], x[11] = x[9]+V, x[9]+twoQ-V
V = MRedConstant(x[14], psi[3], Q, QInv)
x[12], x[14] = x[12]+V, x[12]+twoQ-V
V = MRedConstant(x[15], psi[3], Q, QInv)
x[13], x[15] = x[13]+V, x[13]+twoQ-V
}
}
} else {
if reduce {
for i, j1 := m, 0; i < h+m; i, j1 = i+8, j1+16 {
psi := (*[8]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[1] = butterfly(x[0], x[1], psi[0], twoQ, fourQ, Q, QInv)
x[2], x[3] = butterfly(x[2], x[3], psi[1], twoQ, fourQ, Q, QInv)
x[4], x[5] = butterfly(x[4], x[5], psi[2], twoQ, fourQ, Q, QInv)
x[6], x[7] = butterfly(x[6], x[7], psi[3], twoQ, fourQ, Q, QInv)
x[8], x[9] = butterfly(x[8], x[9], psi[4], twoQ, fourQ, Q, QInv)
x[10], x[11] = butterfly(x[10], x[11], psi[5], twoQ, fourQ, Q, QInv)
x[12], x[13] = butterfly(x[12], x[13], psi[6], twoQ, fourQ, Q, QInv)
x[14], x[15] = butterfly(x[14], x[15], psi[7], twoQ, fourQ, Q, QInv)
}
} else {
for i, j1 := m, 0; i < h+m; i, j1 = i+8, j1+16 {
psi := (*[8]uint64)(unsafe.Pointer(&nttPsi[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
V = MRedConstant(x[1], psi[0], Q, QInv)
x[0], x[1] = x[0]+V, x[0]+twoQ-V
V = MRedConstant(x[3], psi[1], Q, QInv)
x[2], x[3] = x[2]+V, x[2]+twoQ-V
V = MRedConstant(x[5], psi[2], Q, QInv)
x[4], x[5] = x[4]+V, x[4]+twoQ-V
V = MRedConstant(x[7], psi[3], Q, QInv)
x[6], x[7] = x[6]+V, x[6]+twoQ-V
V = MRedConstant(x[9], psi[4], Q, QInv)
x[8], x[9] = x[8]+V, x[8]+twoQ-V
V = MRedConstant(x[11], psi[5], Q, QInv)
x[10], x[11] = x[10]+V, x[10]+twoQ-V
V = MRedConstant(x[13], psi[6], Q, QInv)
x[12], x[13] = x[12]+V, x[12]+twoQ-V
V = MRedConstant(x[15], psi[7], Q, QInv)
x[14], x[15] = x[14]+V, x[14]+twoQ-V
}
}
}
}
}
// InvNTTConjugateInvariant computes the InvNTT in the closed sub-ring Z[X + X^-1]/(X^2N +1) of Z[X]/(X^2N+1).
func InvNTTConjugateInvariant(coeffsIn, coeffsOut []uint64, N int, nttPsiInv []uint64, nttNInv, Q, QInv uint64) {
invNTTConjugateInvariantCore(coeffsIn, coeffsOut, N, nttPsiInv, Q, QInv)
MulScalarMontgomeryVec(coeffsOut, coeffsOut, nttNInv, Q, QInv)
}
// InvNTTConjugateInvariantLazy computes the InvNTT in the closed sub-ring Z[X + X^-1]/(X^2N +1) of Z[X]/(X^2N+1) with output values in the range [0, 2q-1].
func InvNTTConjugateInvariantLazy(coeffsIn, coeffsOut []uint64, N int, nttPsiInv []uint64, nttNInv, Q, QInv uint64) {
invNTTConjugateInvariantCore(coeffsIn, coeffsOut, N, nttPsiInv, Q, QInv)
MulScalarMontgomeryConstantVec(coeffsOut, coeffsOut, nttNInv, Q, QInv)
}
func invNTTConjugateInvariantCore(coeffsIn, coeffsOut []uint64, N int, nttPsiInv []uint64, Q, QInv uint64) {
var j1, j2, h, t int
var F uint64
// Copy the result of the first round of butterflies on p2 with approximate reduction
t = 1
h = N >> 1
twoQ := Q << 1
fourQ := Q << 2
for i, j := N, 0; i < h+N; i, j = i+8, j+16 {
psi := (*[8]uint64)(unsafe.Pointer(&nttPsiInv[i]))
xin := (*[16]uint64)(unsafe.Pointer(&coeffsIn[j]))
xout := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j]))
xout[0], xout[1] = invbutterfly(xin[0], xin[1], psi[0], twoQ, fourQ, Q, QInv)
xout[2], xout[3] = invbutterfly(xin[2], xin[3], psi[1], twoQ, fourQ, Q, QInv)
xout[4], xout[5] = invbutterfly(xin[4], xin[5], psi[2], twoQ, fourQ, Q, QInv)
xout[6], xout[7] = invbutterfly(xin[6], xin[7], psi[3], twoQ, fourQ, Q, QInv)
xout[8], xout[9] = invbutterfly(xin[8], xin[9], psi[4], twoQ, fourQ, Q, QInv)
xout[10], xout[11] = invbutterfly(xin[10], xin[11], psi[5], twoQ, fourQ, Q, QInv)
xout[12], xout[13] = invbutterfly(xin[12], xin[13], psi[6], twoQ, fourQ, Q, QInv)
xout[14], xout[15] = invbutterfly(xin[14], xin[15], psi[7], twoQ, fourQ, Q, QInv)
}
// Continue the rest of the second to the n-1 butterflies on p2 with approximate reduction
t <<= 1
for m := N >> 1; m > 1; m >>= 1 {
j1 = 0
h = m >> 1
if t >= 8 {
for i := 0; i < h; i++ {
j2 = j1 + t - 1
F = nttPsiInv[m+i]
for jx, jy := j1, j1+t; jx <= j2; jx, jy = jx+8, jy+8 {
x := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
y := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
x[0], y[0] = invbutterfly(x[0], y[0], F, twoQ, fourQ, Q, QInv)
x[1], y[1] = invbutterfly(x[1], y[1], F, twoQ, fourQ, Q, QInv)
x[2], y[2] = invbutterfly(x[2], y[2], F, twoQ, fourQ, Q, QInv)
x[3], y[3] = invbutterfly(x[3], y[3], F, twoQ, fourQ, Q, QInv)
x[4], y[4] = invbutterfly(x[4], y[4], F, twoQ, fourQ, Q, QInv)
x[5], y[5] = invbutterfly(x[5], y[5], F, twoQ, fourQ, Q, QInv)
x[6], y[6] = invbutterfly(x[6], y[6], F, twoQ, fourQ, Q, QInv)
x[7], y[7] = invbutterfly(x[7], y[7], F, twoQ, fourQ, Q, QInv)
}
j1 = j1 + (t << 1)
}
} else if t == 4 {
for i := m; i < h+m; i = i + 2 {
psi := (*[2]uint64)(unsafe.Pointer(&nttPsiInv[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[4] = invbutterfly(x[0], x[4], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[5] = invbutterfly(x[1], x[5], psi[0], twoQ, fourQ, Q, QInv)
x[2], x[6] = invbutterfly(x[2], x[6], psi[0], twoQ, fourQ, Q, QInv)
x[3], x[7] = invbutterfly(x[3], x[7], psi[0], twoQ, fourQ, Q, QInv)
x[8], x[12] = invbutterfly(x[8], x[12], psi[1], twoQ, fourQ, Q, QInv)
x[9], x[13] = invbutterfly(x[9], x[13], psi[1], twoQ, fourQ, Q, QInv)
x[10], x[14] = invbutterfly(x[10], x[14], psi[1], twoQ, fourQ, Q, QInv)
x[11], x[15] = invbutterfly(x[11], x[15], psi[1], twoQ, fourQ, Q, QInv)
j1 = j1 + (t << 2)
}
} else {
for i := m; i < h+m; i = i + 4 {
psi := (*[4]uint64)(unsafe.Pointer(&nttPsiInv[i]))
x := (*[16]uint64)(unsafe.Pointer(&coeffsOut[j1]))
x[0], x[2] = invbutterfly(x[0], x[2], psi[0], twoQ, fourQ, Q, QInv)
x[1], x[3] = invbutterfly(x[1], x[3], psi[0], twoQ, fourQ, Q, QInv)
x[4], x[6] = invbutterfly(x[4], x[6], psi[1], twoQ, fourQ, Q, QInv)
x[5], x[7] = invbutterfly(x[5], x[7], psi[1], twoQ, fourQ, Q, QInv)
x[8], x[10] = invbutterfly(x[8], x[10], psi[2], twoQ, fourQ, Q, QInv)
x[9], x[11] = invbutterfly(x[9], x[11], psi[2], twoQ, fourQ, Q, QInv)
x[12], x[14] = invbutterfly(x[12], x[14], psi[3], twoQ, fourQ, Q, QInv)
x[13], x[15] = invbutterfly(x[13], x[15], psi[3], twoQ, fourQ, Q, QInv)
j1 = j1 + (t << 3)
}
}
t <<= 1
}
F = nttPsiInv[1]
for jx, jy := 1, N-8; jx < (N>>1)-7; jx, jy = jx+8, jy-8 {
xout := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jx]))
yout := (*[8]uint64)(unsafe.Pointer(&coeffsOut[jy]))
xout[0], yout[7] = xout[0]+twoQ-MRedConstant(yout[7], F, Q, QInv), yout[7]+twoQ-MRedConstant(xout[0], F, Q, QInv)
xout[1], yout[6] = xout[1]+twoQ-MRedConstant(yout[6], F, Q, QInv), yout[6]+twoQ-MRedConstant(xout[1], F, Q, QInv)
xout[2], yout[5] = xout[2]+twoQ-MRedConstant(yout[5], F, Q, QInv), yout[5]+twoQ-MRedConstant(xout[2], F, Q, QInv)
xout[3], yout[4] = xout[3]+twoQ-MRedConstant(yout[4], F, Q, QInv), yout[4]+twoQ-MRedConstant(xout[3], F, Q, QInv)
xout[4], yout[3] = xout[4]+twoQ-MRedConstant(yout[3], F, Q, QInv), yout[3]+twoQ-MRedConstant(xout[4], F, Q, QInv)
xout[5], yout[2] = xout[5]+twoQ-MRedConstant(yout[2], F, Q, QInv), yout[2]+twoQ-MRedConstant(xout[5], F, Q, QInv)
xout[6], yout[1] = xout[6]+twoQ-MRedConstant(yout[1], F, Q, QInv), yout[1]+twoQ-MRedConstant(xout[6], F, Q, QInv)
xout[7], yout[0] = xout[7]+twoQ-MRedConstant(yout[0], F, Q, QInv), yout[0]+twoQ-MRedConstant(xout[7], F, Q, QInv)
}
j := (N >> 1) - 7
xout := (*[7]uint64)(unsafe.Pointer(&coeffsOut[j]))
yout := (*[7]uint64)(unsafe.Pointer(&coeffsOut[N-j-6]))
xout[0], yout[6] = xout[0]+twoQ-MRedConstant(yout[6], F, Q, QInv), yout[6]+twoQ-MRedConstant(xout[0], F, Q, QInv)
xout[1], yout[5] = xout[1]+twoQ-MRedConstant(yout[5], F, Q, QInv), yout[5]+twoQ-MRedConstant(xout[1], F, Q, QInv)
xout[2], yout[4] = xout[2]+twoQ-MRedConstant(yout[4], F, Q, QInv), yout[4]+twoQ-MRedConstant(xout[2], F, Q, QInv)
xout[3], yout[3] = xout[3]+twoQ-MRedConstant(yout[3], F, Q, QInv), yout[3]+twoQ-MRedConstant(xout[3], F, Q, QInv)
xout[4], yout[2] = xout[4]+twoQ-MRedConstant(yout[2], F, Q, QInv), yout[2]+twoQ-MRedConstant(xout[4], F, Q, QInv)
xout[5], yout[1] = xout[5]+twoQ-MRedConstant(yout[1], F, Q, QInv), yout[1]+twoQ-MRedConstant(xout[5], F, Q, QInv)
xout[6], yout[0] = xout[6]+twoQ-MRedConstant(yout[0], F, Q, QInv), yout[0]+twoQ-MRedConstant(xout[6], F, Q, QInv)
coeffsOut[N>>1] = coeffsOut[N>>1] + twoQ - MRedConstant(coeffsOut[N>>1], F, Q, QInv)
coeffsOut[0] = CRed(coeffsOut[0]<<1, Q)
} | ring/ring_ntt.go | 0.855791 | 0.66266 | ring_ntt.go | starcoder |
package v2
import (
"bytes"
"encoding/json"
)
// UnstructuredTypesEqual compares two unstructured object.
func UnstructuredTypesEqual(a, b *UnstructuredTypedObject) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if a.GetType() != b.GetType() {
return false
}
rawA, err := a.GetRaw()
if err != nil {
return false
}
rawB, err := b.GetRaw()
if err != nil {
return false
}
return bytes.Equal(rawA, rawB)
}
// TypedObjectEqual compares two typed objects using the unstructured type.
func TypedObjectEqual(a, b TypedObjectAccessor) bool {
if a.GetType() != b.GetType() {
return false
}
uA, err := NewUnstructured(a)
if err != nil {
return false
}
uB, err := NewUnstructured(b)
if err != nil {
return false
}
return UnstructuredTypesEqual(&uA, &uB)
}
// NewUnstructured creates a new unstructured object from a typed object using the default codec.
func NewUnstructured(obj TypedObjectAccessor) (UnstructuredTypedObject, error) {
uObj, err := ToUnstructuredTypedObject(NewDefaultCodec(), obj)
if err != nil {
return UnstructuredTypedObject{}, nil
}
return *uObj, nil
}
// NewEmptyUnstructured creates a new typed object without additional data.
func NewEmptyUnstructured(ttype string) *UnstructuredTypedObject {
return NewUnstructuredType(ttype, nil)
}
// NewUnstructuredType creates a new unstructured typed object.
func NewUnstructuredType(ttype string, data map[string]interface{}) *UnstructuredTypedObject {
unstr := &UnstructuredTypedObject{}
unstr.Object = data
unstr.SetType(ttype)
return unstr
}
// UnstructuredTypedObject describes a generic typed object.
// +k8s:openapi-gen=true
type UnstructuredTypedObject struct {
ObjectType `json:",inline"`
Raw []byte `json:"-"`
Object map[string]interface{} `json:"object"`
}
func (u *UnstructuredTypedObject) SetType(ttype string) {
u.ObjectType.SetType(ttype)
if u.Object == nil {
u.Object = make(map[string]interface{})
}
u.Object["type"] = ttype
}
// DeepCopyInto is deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (u *UnstructuredTypedObject) DeepCopyInto(out *UnstructuredTypedObject) {
*out = *u
raw := make([]byte, len(u.Raw))
copy(raw, u.Raw)
_ = out.setRaw(raw)
}
// DeepCopy is deepcopy function, copying the receiver, creating a new UnstructuredTypedObject.
func (u *UnstructuredTypedObject) DeepCopy() *UnstructuredTypedObject {
if u == nil {
return nil
}
out := new(UnstructuredTypedObject)
u.DeepCopyInto(out)
return out
}
// DecodeInto decodes a unstructured typed object into a TypedObjectAccessor using the default codec
func (u *UnstructuredTypedObject) DecodeInto(into TypedObjectAccessor) error {
return FromUnstructuredObject(NewDefaultCodec(), u, into)
}
func (u UnstructuredTypedObject) GetRaw() ([]byte, error) {
data, err := json.Marshal(u.Object)
if err != nil {
return nil, err
}
if !bytes.Equal(data, u.Raw) {
u.Raw = data
}
return u.Raw, nil
}
func (u *UnstructuredTypedObject) setRaw(data []byte) error {
obj := map[string]interface{}{}
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
u.Raw = data
u.Object = obj
return nil
}
// UnmarshalJSON implements a custom json unmarshal method for a unstructured typed object.
func (u *UnstructuredTypedObject) UnmarshalJSON(data []byte) error {
typedObj := ObjectType{}
if err := json.Unmarshal(data, &typedObj); err != nil {
return err
}
obj := UnstructuredTypedObject{
ObjectType: typedObj,
}
if err := obj.setRaw(data); err != nil {
return err
}
*u = obj
return nil
}
// MarshalJSON implements a custom json unmarshal method for a unstructured type.
func (u *UnstructuredTypedObject) MarshalJSON() ([]byte, error) {
data, err := json.Marshal(u.Object)
if err != nil {
return nil, err
}
return data, nil
} | vendor/github.com/gardener/component-spec/bindings-go/apis/v2/unstructured.go | 0.70416 | 0.490175 | unstructured.go | starcoder |
package geogoth
// MultiPoint ...
type MultiPoint struct {
Coords [][]float64
}
// NewMultiPoint creates MultiPoint
func NewMultiPoint(coords [][]float64) MultiPoint {
return MultiPoint{
Coords: coords,
}
}
// Coordinates returns array of longitude, latitude of the MultiPoint
func (m MultiPoint) Coordinates() interface{} {
return m.Coords // longitude (Y), latitude (X)
}
// GetCoordinates returns array of longitude, latitude of MultiPoint
// coordnum - index of coordinate arr
func (m MultiPoint) GetCoordinates(coordnum int) (float64, float64) {
coords := (m.Coordinates()).([][]float64)
lon := coords[coordnum][0]
lat := coords[coordnum][1]
return lon, lat // longitude (Y), latitude (X)
}
// Type returns type of the MultiPoint (MultiPoint)
func (m MultiPoint) Type() string {
return "MultiPoint"
}
// Length returns length of the MultiPoint
func (m MultiPoint) Length() float64 {
return 0
}
// DistanceTo returns distance between two geo objects
func (m MultiPoint) DistanceTo(f Feature) float64 {
var distance float64
switch f.Type() {
case "Point":
point := f.(*Point)
distance = DistancePointMultipoint(point, &m)
case "MultiPoint":
mpoint := f.(*MultiPoint)
distance = DistanceMultipointMultipoint(&m, mpoint)
case "LineString":
linestr := f.(*LineString)
distance = DistanceMultipointLinestring(&m, linestr)
case "MultiLineString":
mlinestr := f.(*MultiLineString)
distance = DistanceMultiPointMultiLinestring(&m, mlinestr)
case "Polygon":
polyg := f.(*Polygon)
distance = DistanceMultiPointPolygon(&m, polyg)
case "MultiPolygon":
mpol := f.(*MultiPolygon)
distance = DistanceMultiPointMultiPolygon(&m, mpol)
}
return distance
}
// IntersectsWith returns true if geoObject intersects with Feature
func (m MultiPoint) IntersectsWith(f Feature) bool {
var intersection bool
switch f.Type() {
case "Point":
// point := f.(*Point)
case "MultiPoint":
// mpoint := f.(*MultiPoint)
case "LineString":
// lstr := f.(*LineString)
case "MultiLineString":
// mlinestr := f.(*MultiLineString)
case "Polygon":
// polygon := f.(*Polygon)
case "MultiPolygon":
// mpolyg := f.(*MultiPolygon)
}
return intersection
} | multipoint .go | 0.900489 | 0.713269 | multipoint .go | starcoder |
package vec
import (
"github.com/chewxy/math32"
"github.com/itohio/EasyRobot/pkg/core/math"
)
type Quaternion [4]float32
func (v *Quaternion) Sum() float32 {
var sum float32
for _, val := range v {
sum += val
}
return sum
}
func (v *Quaternion) Vector() Vector {
return v[:]
}
func (v *Quaternion) Slice(start, end int) Vector {
if end < 0 {
end = len(v)
}
return v[start:end]
}
func (v *Quaternion) XYZ() (float32, float32, float32) {
return v[0], v[1], v[2]
}
func (v *Quaternion) XYZW() (float32, float32, float32, float32) {
return v[0], v[1], v[2], v[3]
}
func (v *Quaternion) SumSqr() float32 {
var sum float32
for _, val := range v {
sum += val * val
}
return sum
}
func (v *Quaternion) Magnitude() float32 {
return math32.Sqrt(v.SumSqr())
}
func (v *Quaternion) DistanceSqr(v1 Quaternion) float32 {
return v.Clone().Sub(v1).SumSqr()
}
func (v *Quaternion) Distance(v1 Quaternion) float32 {
return math32.Sqrt(v.DistanceSqr(v1))
}
func (v *Quaternion) Clone() *Quaternion {
clone := Quaternion{}
copy(clone[:], v[:])
return &clone
}
func (v *Quaternion) CopyFrom(start int, v1 Vector) *Quaternion {
copy(v[start:], v1)
return v
}
func (v *Quaternion) CopyTo(start int, v1 Vector) Vector {
copy(v1, v[start:])
return v1
}
func (v *Quaternion) Clamp(min, max Quaternion) *Quaternion {
for i := range v {
v[i] = math.Clamp(v[i], min[i], max[i])
}
return v
}
func (v *Quaternion) FillC(c float32) *Quaternion {
for i := range v {
v[i] = c
}
return v
}
func (v *Quaternion) Neg() *Quaternion {
for i := range v {
v[i] = -v[i]
}
return v
}
func (v *Quaternion) Add(v1 Quaternion) *Quaternion {
for i := range v {
v[i] += v1[i]
}
return v
}
func (v *Quaternion) AddC(c float32) *Quaternion {
for i := range v {
v[i] += c
}
return v
}
func (v *Quaternion) Sub(v1 Quaternion) *Quaternion {
for i := range v {
v[i] -= v1[i]
}
return v
}
func (v *Quaternion) SubC(c float32) *Quaternion {
for i := range v {
v[i] -= c
}
return v
}
func (v *Quaternion) MulC(c float32) *Quaternion {
for i := range v {
v[i] *= c
}
return v
}
func (v *Quaternion) MulCAdd(c float32, v1 Quaternion) *Quaternion {
for i := range v {
v[i] += v1[i] * c
}
return v
}
func (v *Quaternion) MulCSub(c float32, v1 Quaternion) *Quaternion {
for i := range v {
v[i] -= v1[i] * c
}
return v
}
func (v *Quaternion) DivC(c float32) *Quaternion {
for i := range v {
v[i] /= c
}
return v
}
func (v *Quaternion) DivCAdd(c float32, v1 Quaternion) *Quaternion {
for i := range v {
v[i] += v1[i] / c
}
return v
}
func (v *Quaternion) DivCSub(c float32, v1 Quaternion) *Quaternion {
for i := range v {
v[i] -= v1[i] / c
}
return v
}
func (v *Quaternion) Normal() *Quaternion {
d := v.Magnitude()
return v.DivC(d)
}
func (v *Quaternion) NormalFast() *Quaternion {
d := v.SumSqr()
return v.MulC(math.FastISqrt(d))
}
func (v *Quaternion) Axis() Vector {
return v[:3]
}
func (v *Quaternion) Theta() float32 {
return v[3]
}
func (v *Quaternion) Conjugate() *Quaternion {
v[0] = -v[0]
v[1] = -v[1]
v[2] = -v[2]
return v
}
func (v *Quaternion) Roll() float32 {
return math32.Atan2(v[3]*v[0]+v[1]*v[2], 0.5-v[0]*v[0]-v[1]*v[1])
}
func (v *Quaternion) Pitch() float32 {
return math32.Asin(-2.0 * (v[0]*v[2] - v[3]*v[1]))
}
func (v *Quaternion) Yaw() float32 {
return math32.Atan2(v[0]*v[1]+v[3]*v[2], 0.5-v[1]*v[1]-v[2]*v[2])
}
func (a *Quaternion) Product(b Quaternion) *Quaternion {
x := a[3]*b[0] + a[0]*b[3] + a[1]*b[2] - a[2]*b[1]
y := a[3]*b[1] - a[0]*b[2] + a[1]*b[3] + a[2]*b[0]
z := a[3]*b[2] + a[0]*b[1] - a[1]*b[0] + a[2]*b[3]
w := a[3]*b[3] - a[0]*b[0] - a[1]*b[1] - a[2]*b[2]
a[0] = x
a[1] = y
a[2] = z
a[3] = w
return a
}
func (v *Quaternion) Slerp(v1 Quaternion, time, spin float32) *Quaternion {
const SLERP_EPSILON = 1.0e-10
var (
k1, k2 float32 // interpolation coefficions.
angle float32 // angle between A and B
angleSpin float32 // angle between A and B plus spin.
sin_a, cos_a float32 // sine, cosine of angle
)
flipk2 := 0
cos_a = v.Dot(v1)
if cos_a < 0.0 {
cos_a = -cos_a
flipk2 = -1
} else {
flipk2 = 1
}
if (1.0 - cos_a) < SLERP_EPSILON {
k1 = 1.0 - time
k2 = time
} else { /* normal case */
angle = math32.Acos(cos_a)
sin_a = math32.Sin(angle)
angleSpin = angle + spin*math32.Pi
k1 = math32.Sin(angle-time*angleSpin) / sin_a
k2 = math32.Sin(time*angleSpin) / sin_a
}
k2 *= float32(flipk2)
v[0] = k1*v[0] + k2*v1[0]
v[1] = k1*v[1] + k2*v1[1]
v[2] = k1*v[2] + k2*v1[2]
v[3] = k1*v[3] + k2*v1[3]
return v
}
func (v *Quaternion) SlerpLong(v1 Quaternion, time, spin float32) *Quaternion {
const SLERP_EPSILON = 1.0e-10
var (
k1, k2 float32 // interpolation coefficions.
angle float32 // angle between A and B
angleSpin float32 // angle between A and B plus spin.
sin_a, cos_a float32 // sine, cosine of angle
)
cos_a = v.Dot(v1)
if 1.0-math32.Abs(cos_a) < SLERP_EPSILON {
k1 = 1.0 - time
k2 = time
} else { /* normal case */
angle = math32.Acos(cos_a)
sin_a = math32.Sin(angle)
angleSpin = angle + spin*math32.Pi
k1 = math32.Sin(angle-time*angleSpin) / sin_a
k2 = math32.Sin(time*angleSpin) / sin_a
}
v[0] = k1*v[0] + k2*v1[0]
v[1] = k1*v[1] + k2*v1[1]
v[2] = k1*v[2] + k2*v1[2]
v[3] = k1*v[3] + k2*v1[3]
return v
}
func (v *Quaternion) Multiply(v1 Quaternion) *Quaternion {
for i := range v {
v[i] *= v1[i]
}
return v
}
func (v *Quaternion) Dot(v1 Quaternion) float32 {
var sum float32
for i := range v {
sum += v[i] * v1[i]
}
return sum
}
func (v *Quaternion) Refract(n Quaternion, ni, nt float32) (*Quaternion, bool) {
var (
sin_T Quaternion /* sin vect of the refracted vect */
cos_V Quaternion /* cos vect of the incident vect */
n_mult float32 /* ni over nt */
)
N_dot_V := n.Dot(*v)
if N_dot_V > 0.0 {
n_mult = ni / nt
} else {
n_mult = nt / ni
}
cos_V[0] = n[0] * N_dot_V
cos_V[1] = n[1] * N_dot_V
cos_V[2] = n[2] * N_dot_V
sin_T[0] = (cos_V[0] - v[0]) * (n_mult)
sin_T[1] = (cos_V[1] - v[1]) * (n_mult)
sin_T[2] = (cos_V[2] - v[2]) * (n_mult)
len_sin_T := sin_T.Dot(sin_T)
if len_sin_T >= 1.0 {
return v, false // internal reflection
}
N_dot_T := math32.Sqrt(1.0 - len_sin_T)
if N_dot_V < 0.0 {
N_dot_T = -N_dot_T
}
v[0] = sin_T[0] - n[0]*N_dot_T
v[1] = sin_T[1] - n[1]*N_dot_T
v[2] = sin_T[2] - n[2]*N_dot_T
return v, true
}
func (v *Quaternion) Reflect(n Quaternion) *Quaternion {
N_dot_V := n.Dot(*v) * 2
return v.Neg().MulCAdd(N_dot_V, n)
}
func (v *Quaternion) Interpolate(v1 Quaternion, t float32) *Quaternion {
d := v1.Clone().Sub(*v)
return v.MulCAdd(t, *d)
} | pkg/core/math/vec/quaternion.go | 0.807954 | 0.514644 | quaternion.go | starcoder |
package a
import (
"fmt"
"math"
)
// Represents a point in 3D space
type Vector3 struct {
X, Y, Z float32
}
func (v Vector3) SetXYZ(x, y, z float32) {
v.X = x
v.Y = y
v.Z = z
}
func NewVector3(x, y, z float32) Vector3 {
return Vector3{
X: x,
Y: y,
Z: z,
}
}
func (v Vector3) ToMap() SiMap {
return map[string]interface{}{
"x": v.X,
"y": v.Y,
"z": v.Z,
}
}
func (v *Vector3) FromMap(siMap SiMap) {
v.X = requireFloat32(siMap["x"])
v.Y = requireFloat32(siMap["y"])
v.Z = requireFloat32(siMap["z"])
}
func (v Vector3) String() string {
return fmt.Sprintf("(%f, %f, %f)", v.X, v.Y, v.Z)
}
// Returns a new vector - the sum of two vectors
func (v Vector3) Add(v2 Vector3) Vector3 {
return Vector3{
X: v.X + v2.X,
Y: v.Y + v2.Y,
Z: v.Z + v2.Z,
}
}
// Returns a new vector - v-v2
func (v Vector3) Sub(v2 Vector3) Vector3 {
return Vector3{
X: v.X - v2.X,
Y: v.Y - v2.Y,
Z: v.Z - v2.Z,
}
}
// Returns new vector - multiplication of two vectors
func (v Vector3) Multiply(v2 Vector3) Vector3 {
return Vector3{
X: v.X * v2.X,
Y: v.Y * v2.Y,
Z: v.Z * v2.Z,
}
}
// Rounds the valued of the vector
func (v Vector3) Round() IntVector3 {
return IntVector3{
X: int(math.Round(float64(v.X))),
Y: int(math.Round(float64(v.Y))),
Z: int(math.Round(float64(v.Z))),
}
}
// Transforms vector ro normalized device coordinates vector
func (v Vector3) Ndc(screen Vector3) Vector3 {
xs := screen.X
ys := screen.Y
x0 := screen.X / 2
y0 := screen.Y / 2
x := v.X
y := v.Y
newX := (2*(x-x0))/xs
newY := (-2*(y-y0))/ys
return Vector3{newX, newY, 0}
}
// Checks if the vector is the same as other vector
func (v Vector3) Equals(other interface{}) bool {
switch other.(type) {
case Vector3:
v2 := other.(Vector3)
return v.X == v2.X && v.Y == v2.Y && v.Z == v2.Z
default:
return false
}
}
func (v Vector3) EncodeToByteArray() []byte {
arr := make([]byte, 12)
_ = CopyByteArray(Float32ToByteArray(v.X), arr, 0, 4)
_ = CopyByteArray(Float32ToByteArray(v.Y), arr, 4, 4)
_ = CopyByteArray(Float32ToByteArray(v.Z), arr, 8, 4)
return arr
}
func ZeroVector() Vector3 {
return Vector3{}
}
func OneVector() Vector3 {
return Vector3{
X: 1,
Y: 1,
Z: 1,
}
}
func NewVector3FromMap(siMap SiMap) Vector3 {
var v Vector3
v.FromMap(siMap)
return v
}
func requireFloat32(num interface{}) float32 {
switch num.(type) {
case byte:
return float32(num.(byte))
case int:
return float32(num.(int))
case int32:
return float32(num.(int32))
case int64:
return float32(num.(int64))
case float32:
return num.(float32)
case float64:
return float32(num.(float64))
default:
return 0
}
} | common/a/vector.go | 0.867724 | 0.725794 | vector.go | starcoder |
package algebra
import (
"math"
)
//EPSILON for testing floating point equality
var EPSILON float64 = 0.0001
type Vector struct {
tuple []float64
}
//NewPoint creates a tuple with the data and appends a 1.0 to signify it is a point
func NewPoint(data ...float64) *Vector {
newData := append(data, 1.0)
v := &Vector{tuple: newData}
return v
}
//NewVector creates a tuple with the data and appends a 0.0 to signify it is point
func NewVector(data ...float64) *Vector {
newData := append(data, 0.0)
v := &Vector{tuple: newData}
return v
}
//Get getter function for the vector tuple
func (v *Vector) Get() []float64 {
return v.tuple
}
//IsPoint returns true iff the Vector is a point
func (v *Vector) IsPoint() bool {
return v.tuple[len(v.tuple)-1] == 1.0
}
//IsVector returns true iff the Vector is a vector and returns that new vector
func (v *Vector) IsVector() bool {
return v.tuple[len(v.tuple)-1] == 0.0
}
//Add adds two vectors together
func (v *Vector) Add(v2 *Vector) (*Vector, error) {
if len(v.tuple) != len(v2.tuple) {
return nil, MismatchedLength([2]int{len(v.tuple), len(v2.tuple)})
}
res := make([]float64, len(v.tuple), len(v.tuple))
for i, val := range v.tuple {
res[i] = val + v2.tuple[i]
}
return &Vector{res}, nil
}
//Subtract subtracts two vectors together and returns that new vector
func (v *Vector) Subtract(v2 *Vector) (*Vector, error) {
if len(v.tuple) != len(v2.tuple) {
return nil, MismatchedLength([2]int{len(v.tuple), len(v2.tuple)})
}
res := make([]float64, len(v.tuple), len(v.tuple))
for i, val := range v.tuple {
res[i] = val - v2.tuple[i]
}
return &Vector{res}, nil
}
//Negate returns -vector
func (v *Vector) Negate() *Vector {
res := make([]float64, len(v.tuple), len(v.tuple))
for i := 0; i < len(v.tuple); i++ {
if i == len(v.tuple)-1 {
res[i] = v.tuple[i] // keep attribute that keeps track of pointedness/vectoredness the same
} else {
res[i] = -v.tuple[i]
}
}
return &Vector{res}
}
//MultScalar performs vector scalar multiplication
func (v *Vector) MultScalar(c float64) *Vector {
res := make([]float64, len(v.tuple), len(v.tuple))
for i, val := range v.tuple {
if i == len(v.tuple)-1 {
res[i] = val // keep attribute that keeps track of pointedness/vectoredness the same
} else {
res[i] = c * val
}
}
return &Vector{res}
}
//DivideScalar performs vector scalar division. (Notationally more convenient sometimes than MultScalar method)
func (v *Vector) DivideScalar(c float64) *Vector {
res := make([]float64, len(v.tuple), len(v.tuple))
for i, val := range v.tuple {
if i == len(v.tuple)-1 {
res[i] = val
} else {
res[i] = (1 / c) * val
}
}
return &Vector{res}
}
//Magnitude returns the provided vectors magnitude
func (v *Vector) Magnitude() float64 {
sum := 0.0
for i, val := range v.tuple {
if i == len(v.tuple)-1 {
continue
} else {
sum += math.Pow(val, 2)
}
}
return math.Sqrt(sum)
}
//Magnitude returns the provided vectors magnitude
func (v *Vector) Magnitude2() float64 {
sum := 0.0
for i, val := range v.tuple {
if i == len(v.tuple)-1 {
continue
} else {
sum += math.Pow(val, 2)
}
}
return sum
}
//Normalize returns a normalized version of the original vector
func (v *Vector) Normalize() (*Vector, error) {
norm := v.Magnitude()
if norm == 0 {
return nil, ZeroDivide(0)
}
res := make([]float64, len(v.tuple), len(v.tuple))
for i, val := range v.tuple {
if i == len(v.tuple)-1 {
res[i] = val
} else {
res[i] = val / norm
}
}
return &Vector{res}, nil
}
//DotProduct returns the dot product of two vectors
func DotProduct(v *Vector, v2 *Vector) (float64, error) {
if len(v.tuple) != len(v2.tuple) {
return 0.0, MismatchedLength([2]int{len(v.tuple), len(v2.tuple)})
}
sum := 0.0
for i, val := range v.tuple {
sum += val * v2.tuple[i]
}
return sum, nil
}
func CrossProduct(v1 *Vector, v2 *Vector) (*Vector, error) {
if len(v1.tuple) != len(v2.tuple) {
return nil, MismatchedLength([2]int{len(v1.tuple), len(v2.tuple)})
}
if len(v1.tuple) != 4 {
return nil, ExpectedDimension(3)
}
a := v1.tuple
b := v2.tuple
return NewVector(a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]), nil
}
func (v *Vector) Reflect(normal *Vector) *Vector {
dot, err := DotProduct(v, normal)
if err != nil {
panic(err)
return nil
}
dot = 2 * dot
reflect, err := v.Subtract(normal.MultScalar(dot))
if err != nil {
panic(err)
return nil
}
return reflect
} | pkg/algebra/vector.go | 0.826537 | 0.696094 | vector.go | starcoder |
package chart
import (
"fmt"
"time"
util "github.com/iesreza/go-chart/util"
)
// Interface Assertions.
var (
_ Series = (*TimeSeries)(nil)
_ FirstValuesProvider = (*TimeSeries)(nil)
_ LastValuesProvider = (*TimeSeries)(nil)
_ ValueFormatterProvider = (*TimeSeries)(nil)
)
// TimeSeries is a line on a chart.
type TimeSeries struct {
Name string
Style Style
YAxis YAxisType
XValues []time.Time
YValues []float64
}
// GetName returns the name of the time series.
func (ts TimeSeries) GetName() string {
return ts.Name
}
// GetStyle returns the line style.
func (ts TimeSeries) GetStyle() Style {
return ts.Style
}
// Len returns the number of elements in the series.
func (ts TimeSeries) Len() int {
return len(ts.XValues)
}
// GetValues gets x, y values at a given index.
func (ts TimeSeries) GetValues(index int) (x, y float64) {
x = util.Time.ToFloat64(ts.XValues[index])
y = ts.YValues[index]
return
}
// GetFirstValues gets the first values.
func (ts TimeSeries) GetFirstValues() (x, y float64) {
x = util.Time.ToFloat64(ts.XValues[0])
y = ts.YValues[0]
return
}
// GetLastValues gets the last values.
func (ts TimeSeries) GetLastValues() (x, y float64) {
x = util.Time.ToFloat64(ts.XValues[len(ts.XValues)-1])
y = ts.YValues[len(ts.YValues)-1]
return
}
// GetValueFormatters returns value formatter defaults for the series.
func (ts TimeSeries) GetValueFormatters() (x, y ValueFormatter) {
x = TimeValueFormatter
y = FloatValueFormatter
return
}
// GetYAxis returns which YAxis the series draws on.
func (ts TimeSeries) GetYAxis() YAxisType {
return ts.YAxis
}
// Render renders the series.
func (ts TimeSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) {
style := ts.Style.InheritFrom(defaults)
Draw.LineSeries(r, canvasBox, xrange, yrange, style, ts)
}
// Validate validates the series.
func (ts TimeSeries) Validate() error {
if len(ts.XValues) == 0 {
return fmt.Errorf("time series must have xvalues set")
}
if len(ts.YValues) == 0 {
return fmt.Errorf("time series must have yvalues set")
}
return nil
} | time_series.go | 0.825097 | 0.518485 | time_series.go | starcoder |
package clock
import "time"
// Work mirrors the behaviour of Go's time package.
var Work Clock
func init() {
Work = New()
}
// Now returns the current local time.
func Now() time.Time {
return Work.Now()
}
func Since(t time.Time) time.Duration {
return Work.Now().Sub(t)
}
// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
func Sleep(d time.Duration) {
Work.Sleep(d)
}
// After waits for the duration to elapse and then sends the current time
// on the returned channel. It is equivalent to NewTimer(d).C.
func After(d time.Duration) <-chan time.Time {
return Work.After(d)
}
// Tick is a convenience wrapper for NewTicker providing access to the
// ticking channel only.
func Tick(d time.Duration) <-chan time.Time {
return Work.Tick(d)
}
// Ticker returns a new Ticker containing a channel that will send the
// time with a period specified by the duration argument. It adjusts
// the intervals or drops ticks to make up for slow receivers.
// The duration d must be greater than zero; if not, Ticker will panic.
func Ticker(d time.Duration) *time.Ticker {
return Work.Ticker(d)
}
// Clock provides the functions from the time package.
type Clock interface {
// Now returns the current local time.
Now() time.Time
// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
Sleep(d time.Duration)
// After waits for the duration to elapse and then sends the current time
// on the returned channel. It is equivalent to NewTimer(d).C.
After(d time.Duration) <-chan time.Time
// Tick is a convenience wrapper for NewTicker providing access to the
// ticking channel only.
Tick(d time.Duration) <-chan time.Time
// Ticker returns a new Ticker containing a channel that will send the
// time with a period specified by the duration argument. It adjusts
// the intervals or drops ticks to make up for slow receivers.
// The duration d must be greater than zero; if not, Ticker will panic.
Ticker(d time.Duration) *time.Ticker
// TODO: At(t time.Time) <-chan time.Time
}
// Mock represents a manipulable Work. It is concurrent-friendly.
type Mock interface {
Clock
// ==== manipulate Now()
// Set applies the passed-in time to the Clock's time.
Set(t time.Time) Mock
// Add changes the Clock's time by the passed-in duration.
Add(d time.Duration) Mock
// Freeze stops the clock's time.
Freeze() Mock
// IsFrozen is whether the clock's time is stopped.
IsFrozen() bool
// Unfreeze starts the clock's time again.
Unfreeze() Mock
Close()
} | clock.go | 0.735737 | 0.423398 | clock.go | starcoder |
package wad
import (
"fmt"
"time"
)
// Rate is the conversion rate.
type Rate struct {
// BaseCode is the rate we're converting from
BaseCode string
// QuoteCode is the rate we're converting to
QuoteCode string
// RateValue is the conversion rate
RateValue float64
// Timestamp is the timestamp of the conversion
Timestamp time.Time
}
// NewRate creates a rate from base quote->quote code (rate).
func NewRate(baseCode string, quoteCode string, rate float64) Rate {
return Rate{
BaseCode: baseCode,
QuoteCode: quoteCode,
RateValue: rate,
Timestamp: time.Now(),
}
}
// ToString converts the rate to a string.
func (r Rate) ToString() string {
return fmt.Sprintf("%.8f %s%s", r.RateValue, r.BaseCode, r.QuoteCode)
}
// Includes determines whether or not the Rate.BaseCode is Rate.BaseCode or the Rate.QuoteCode.
func (r Rate) Includes(quote string) bool {
return r.BaseCode == quote || r.QuoteCode == quote
}
// Invert inverts the wad by flipping the currency conversion.
func (r Rate) Invert() Rate {
return Rate{
BaseCode: r.QuoteCode,
QuoteCode: r.BaseCode,
RateValue: 1.0 / r.RateValue,
Timestamp: r.Timestamp,
}
}
// Other determines if base get quote if quote get base.
func (r Rate) Other(code string) string {
if !r.Includes(code) {
panic(fmt.Errorf("Code must be %s or %s to use other", r.QuoteCode, r.BaseCode))
}
if r.BaseCode == code {
return r.QuoteCode
}
return r.BaseCode
}
// Convert converts a value/code into a new currency.
func (r Rate) Convert(value float64, valueCode string) (converted float64, code string) {
if valueCode == r.BaseCode {
return value * r.RateValue, r.QuoteCode
} else if valueCode == r.QuoteCode {
return value / r.RateValue, r.BaseCode
}
panic(fmt.Errorf("expected Code to be either %s or %s", r.QuoteCode, r.BaseCode))
}
// DeriveRate does a cross-currency rate conversion.
func DeriveRate(baseQuote string, quoteCode string, rates [2]Rate) Rate {
if !(rates[0].Includes(baseQuote) || rates[1].Includes(baseQuote)) {
panic(fmt.Errorf("at least one rate must use baseQuote %s", baseQuote))
}
if !(rates[0].Includes(quoteCode) || rates[1].Includes(quoteCode)) {
panic(fmt.Errorf("at least one rate must use quoteCode %s", quoteCode))
}
var first, second Rate
if rates[0].Includes(baseQuote) {
first = rates[0]
second = rates[1]
} else {
first = rates[1]
second = rates[0]
}
otherCode := first.Other(baseQuote)
if !second.Includes(otherCode) {
panic(fmt.Errorf("expected second to include %s", otherCode))
}
otherConverted, otherCheck := first.Convert(1.0, baseQuote)
if otherCheck != otherCode {
panic(fmt.Errorf("expected %s to equal %s", otherCode, otherCheck))
}
quoteConverted, quoteCheck := second.Convert(otherConverted, otherCode)
if quoteCheck != quoteCode {
panic(fmt.Errorf("expected %s to equal %s", quoteCheck, quoteCode))
}
timestamp := minTime(first.Timestamp, second.Timestamp)
return Rate{
BaseCode: baseQuote,
QuoteCode: quoteCode,
RateValue: quoteConverted,
Timestamp: timestamp,
}
}
// minTime is a helper function that get the lesser of two times.
func minTime(time1 time.Time, time2 time.Time) time.Time {
if time1.Before(time2) {
return time1
}
return time2
} | moneysocket/wad/rate.go | 0.77806 | 0.50891 | rate.go | starcoder |
package exiftag
const (
// Image width - SHORT or LONG (1)
ImageWidth = Tiff | 0x0100
// Image height - SHORT or LONG (1)
ImageLength = Tiff | 0x0101
// Number of bits per component - SHORT (3)
BitsPerSample = Tiff | 0x0102
// Compression scheme - SHORT (1)
Compression = Tiff | 0x0103
// Pixel composition - SHORT (1)
PhotometricInterpretation = Tiff | 0x0106
// Orientation of image - SHORT (1)
Orientation = Tiff | 0x0112
// Number of components - SHORT (1)
SamplesPerPixel = Tiff | 0x0115
// Image data arrangement - SHORT (1)
PlanarConfiguration = Tiff | 0x011c
// Subsampling ratio of Y to C - SHORT (2)
YCbCrSubSampling = Tiff | 0x0212
// Y and C positioning - SHORT (1)
YCbCrPositioning = Tiff | 0x0213
// Image resolution in width direction - RATIONAL (1)
XResolution = Tiff | 0x011a
// Image resolution in height direction - RATIONAL (1)
YResolution = Tiff | 0x011b
// Unit of X and Y resolution - SHORT (1)
ResolutionUnit = Tiff | 0x0128
// Image data location - SHORT or LONG (*S)
StripOffsets = Tiff | 0x0111
// Number of rows per strip - SHORT or LONG (1)
RowsPerStrip = Tiff | 0x0116
// Bytes per compressed strip - SHORT or LONG (*S)
StripByteCounts = Tiff | 0x0117
// Offset to JPEG SOI - LONG (1)
JPEGInterchangeFormat = Tiff | 0x0201
// Bytes of JPEG data - LONG (1)
JPEGInterchangeFormatLength = Tiff | 0x0202
// Transfer function - SHORT (3*256)
TransferFunction = Tiff | 0x012d
// White point chromaticity - RATIONAL (2)
WhitePoint = Tiff | 0x013e
// Chromaticities of primaries - RATIONAL (6)
PrimaryChromaticities = Tiff | 0x013f
// Color space transformation matrix coefficients - RATIONAL (3)
YCbCrCoefficients = Tiff | 0x0211
// Pair of black and white reference values - RATIONAL (6)
ReferenceBlackWhite = Tiff | 0x0214
// File change date and time - ASCII (20)
DateTime = Tiff | 0x0132
// Image title - ASCII (Any)
ImageDescription = Tiff | 0x010e
// Image input equipment manufacturer - ASCII (Any)
Make = Tiff | 0x010f
// Image input equipment model - ASCII (Any)
Model = Tiff | 0x0110
// Software used - ASCII (Any)
Software = Tiff | 0x0131
// Person who created the image - ASCII (Any)
Artist = Tiff | 0x013b
// Copyright holder - ASCII (Any)
Copyright = Tiff | 0x8298
// Exif version - UNDEFINED (4)
ExifVersion = Exif | 0x9000
// Supported Flashpix version - UNDEFINED (4)
FlashpixVersion = Exif | 0xa000
// Color space information - SHORT (1)
ColorSpace = Exif | 0xa001
// Meaning of each component - UNDEFINED (4)
ComponentsConfiguration = Exif | 0x9101
// Image compression mode - RATIONAL (1)
CompressedBitsPerPixel = Exif | 0x9102
// Valid image width - SHORT or LONG (1)
PixelXDimension = Exif | 0xa002
// Valid image height - SHORT or LONG (1)
PixelYDimension = Exif | 0xa003
// Manufacturer notes - UNDEFINED (Any)
MakerNote = Exif | 0x927c
// User comments - UNDEFINED (Any)
UserComment = Exif | 0x9286
// Related audio file - ASCII (13)
RelatedSoundFile = Exif | 0xa004
// Date and time of original data generation - ASCII (20)
DateTimeOriginal = Exif | 0x9003
// Date and time of digital data generation - ASCII (20)
DateTimeDigitized = Exif | 0x9004
// DateTime subseconds - ASCII (Any)
SubSecTime = Exif | 0x9290
// DateTimeOriginal subseconds - ASCII (Any)
SubSecTimeOriginal = Exif | 0x9291
// DateTimeDigitized subseconds - ASCII (Any)
SubSecTimeDigitized = Exif | 0x9292
// Exposure time - RATIONAL (1)
ExposureTime = Exif | 0x829a
// F number - RATIONAL (1)
FNumber = Exif | 0x829d
// Exposure program - SHORT (1)
ExposureProgram = Exif | 0x8822
// Spectral sensitivity - ASCII (Any)
SpectralSensitivity = Exif | 0x8824
// ISO speed rating - SHORT (Any)
ISOSpeedRatings = Exif | 0x8827
// Optoelectric conversion factor - UNDEFINED (Any)
OECF = Exif | 0x8828
// Shutter speed - SRATIONAL (1)
ShutterSpeedValue = Exif | 0x9201
// Aperture - RATIONAL (1)
ApertureValue = Exif | 0x9202
// Brightness - SRATIONAL (1)
BrightnessValue = Exif | 0x9203
// Exposure bias - SRATIONAL (1)
ExposureBiasValue = Exif | 0x9204
// Maximum lens aperture - RATIONAL (1)
MaxApertureValue = Exif | 0x9205
// Subject distance - RATIONAL (1)
SubjectDistance = Exif | 0x9206
// Metering mode - SHORT (1)
MeteringMode = Exif | 0x9207
// Light source - SHORT (1)
LightSource = Exif | 0x9208
// Flash - SHORT (1)
Flash = Exif | 0x9209
// Lens focal length - RATIONAL (1)
FocalLength = Exif | 0x920a
// Subject area - SHORT (2 or 3 or 4)
SubjectArea = Exif | 0x9214
// Flash energy - RATIONAL (1)
FlashEnergy = Exif | 0xa20b
// Spatial frequency response - UNDEFINED (Any)
SpatialFrequencyResponse = Exif | 0xa20c
// Focal plane X resolution - RATIONAL (1)
FocalPlaneXResolution = Exif | 0xa20e
// Focal plane Y resolution - RATIONAL (1)
FocalPlaneYResolution = Exif | 0xa20f
// Focal plane resolution unit - SHORT (1)
FocalPlaneResolutionUnit = Exif | 0xa210
// Subject location - SHORT (2)
SubjectLocation = Exif | 0xa214
// Exposure index - RATIONAL (1)
ExposureIndex = Exif | 0xa215
// Sensing method - SHORT (1)
SensingMethod = Exif | 0xa217
// File source - UNDEFINED (1)
FileSource = Exif | 0xa300
// Scene type - UNDEFINED (1)
SceneType = Exif | 0xa301
// CFA pattern - UNDEFINED (Any)
CFAPattern = Exif | 0xa302
// Custom image processing - SHORT (1)
CustomRendered = Exif | 0xa401
// Exposure mode - SHORT (1)
ExposureMode = Exif | 0xa402
// White balance - SHORT (1)
WhiteBalance = Exif | 0xa403
// Digital zoom ratio - RATIONAL (1)
DigitalZoomRatio = Exif | 0xa404
// Focal length in 35 mm film - SHORT (1)
FocalLengthIn35mmFilm = Exif | 0xa405
// Scene capture type - SHORT (1)
SceneCaptureType = Exif | 0xa406
// Gain control - RATIONAL (1)
GainControl = Exif | 0xa407
// Contrast - SHORT (1)
Contrast = Exif | 0xa408
// Saturation - SHORT (1)
Saturation = Exif | 0xa409
// Sharpness - SHORT (1)
Sharpness = Exif | 0xa40a
// Device settings description - UNDEFINED (Any)
DeviceSettingDescription = Exif | 0xa40b
// Subject distance range - SHORT (1)
SubjectDistanceRange = Exif | 0xa40c
// Unique image ID - ASCII (33)
ImageUniqueID = Exif | 0xa420
// GPS tag version - BYTE (4)
GPSVersionID = GPS | 0x0000
// North or South Latitude - ASCII (2)
GPSLatitudeRef = GPS | 0x0001
// Latitude - RATIONAL (3)
GPSLatitude = GPS | 0x0002
// East or West Longitude - ASCII (2)
GPSLongitudeRef = GPS | 0x0003
// Longitude - RATIONAL (3)
GPSLongitude = GPS | 0x0004
// Altitude reference - BYTE (1)
GPSAltitudeRef = GPS | 0x0005
// Altitude - RATIONAL (1)
GPSAltitude = GPS | 0x0006
// GPS time (atomic clock) - RATIONAL (3)
GPSTimeStamp = GPS | 0x0007
// GPS satellites used for measurement - ASCII (Any)
GPSSatellites = GPS | 0x0008
// GPS receiver status - ASCII (2)
GPSStatus = GPS | 0x0009
// GPS measurement mode - ASCII (2)
GPSMeasureMode = GPS | 0x000a
// Measurement precision - RATIONAL (1)
GPSDOP = GPS | 0x000b
// Speed unit - ASCII (2)
GPSSpeedRef = GPS | 0x000c
// Speed of GPS receiver - RATIONAL (1)
GPSSpeed = GPS | 0x000d
// Reference for direction of movement - ASCII (2)
GPSTrackRef = GPS | 0x000e
// Direction of movement - RATIONAL (1)
GPSTrack = GPS | 0x000f
// Reference for direction of image - ASCII (2)
GPSImgDirectionRef = GPS | 0x0010
// Direction of image - RATIONAL (1)
GPSImgDirection = GPS | 0x0011
// Geodetic survey data used - ASCII (Any)
GPSMapDatum = GPS | 0x0012
// Reference for latitude of destination - ASCII (2)
GPSDestLatitudeRef = GPS | 0x0013
// Latitude of destination - RATIONAL (3)
GPSDestLatitude = GPS | 0x0014
// Reference for longitude of destination - ASCII (2)
GPSDestLongitudeRef = GPS | 0x0015
// Longitude of destination - RATIONAL (3)
GPSDestLongitude = GPS | 0x0016
// Reference for bearing of destination - ASCII (2)
GPSDestBearingRef = GPS | 0x0017
// Bearing of destination - RATIONAL (1)
GPSDestBearing = GPS | 0x0018
// Reference for distance to destination - ASCII (2)
GPSDestDistanceRef = GPS | 0x0019
// Distance to destination - RATIONAL (1)
GPSDestDistance = GPS | 0x001a
// Name of GPS processing method - UNDEFINED (Any)
GPSProcessingMethod = GPS | 0x001b
// Name of GPS area - UNDEFINED (Any)
GPSAreaInformation = GPS | 0x001c
// GPS date - ASCII (11)
GPSDateStamp = GPS | 0x001d
// GPS differential correction - SHORT (1)
GPSDifferential = GPS | 0x001e
)
var nameMap = map[uint32]name{
ImageWidth: {"ImageWidth", "Image width"},
ImageLength: {"ImageLength", "Image height"},
BitsPerSample: {"BitsPerSample", "Number of bits per component"},
Compression: {"Compression", "Compression scheme"},
PhotometricInterpretation: {"PhotometricInterpretation", "Pixel composition"},
Orientation: {"Orientation", "Orientation of image"},
SamplesPerPixel: {"SamplesPerPixel", "Number of components"},
PlanarConfiguration: {"PlanarConfiguration", "Image data arrangement"},
YCbCrSubSampling: {"YCbCrSubSampling", "Subsampling ratio of Y to C"},
YCbCrPositioning: {"YCbCrPositioning", "Y and C positioning"},
XResolution: {"XResolution", "Image resolution in width direction"},
YResolution: {"YResolution", "Image resolution in height direction"},
ResolutionUnit: {"ResolutionUnit", "Unit of X and Y resolution"},
StripOffsets: {"StripOffsets", "Image data location"},
RowsPerStrip: {"RowsPerStrip", "Number of rows per strip"},
StripByteCounts: {"StripByteCounts", "Bytes per compressed strip"},
JPEGInterchangeFormat: {"JPEGInterchangeFormat", "Offset to JPEG SOI"},
JPEGInterchangeFormatLength: {"JPEGInterchangeFormatLength", "Bytes of JPEG data"},
TransferFunction: {"TransferFunction", "Transfer function"},
WhitePoint: {"WhitePoint", "White point chromaticity"},
PrimaryChromaticities: {"PrimaryChromaticities", "Chromaticities of primaries"},
YCbCrCoefficients: {"YCbCrCoefficients", "Color space transformation matrix coefficients"},
ReferenceBlackWhite: {"ReferenceBlackWhite", "Pair of black and white reference values"},
DateTime: {"DateTime", "File change date and time"},
ImageDescription: {"ImageDescription", "Image title"},
Make: {"Make", "Image input equipment manufacturer"},
Model: {"Model", "Image input equipment model"},
Software: {"Software", "Software used"},
Artist: {"Artist", "Person who created the image"},
Copyright: {"Copyright", "Copyright holder"},
ExifVersion: {"ExifVersion", "Exif version"},
FlashpixVersion: {"FlashpixVersion", "Supported Flashpix version"},
ColorSpace: {"ColorSpace", "Color space information"},
ComponentsConfiguration: {"ComponentsConfiguration", "Meaning of each component"},
CompressedBitsPerPixel: {"CompressedBitsPerPixel", "Image compression mode"},
PixelXDimension: {"PixelXDimension", "Valid image width"},
PixelYDimension: {"PixelYDimension", "Valid image height"},
MakerNote: {"MakerNote", "Manufacturer notes"},
UserComment: {"UserComment", "User comments"},
RelatedSoundFile: {"RelatedSoundFile", "Related audio file"},
DateTimeOriginal: {"DateTimeOriginal", "Date and time of original data generation"},
DateTimeDigitized: {"DateTimeDigitized", "Date and time of digital data generation"},
SubSecTime: {"SubSecTime", "DateTime subseconds"},
SubSecTimeOriginal: {"SubSecTimeOriginal", "DateTimeOriginal subseconds"},
SubSecTimeDigitized: {"SubSecTimeDigitized", "DateTimeDigitized subseconds"},
ExposureTime: {"ExposureTime", "Exposure time"},
FNumber: {"FNumber", "F number"},
ExposureProgram: {"ExposureProgram", "Exposure program"},
SpectralSensitivity: {"SpectralSensitivity", "Spectral sensitivity"},
ISOSpeedRatings: {"ISOSpeedRatings", "ISO speed rating"},
OECF: {"OECF", "Optoelectric conversion factor"},
ShutterSpeedValue: {"ShutterSpeedValue", "Shutter speed"},
ApertureValue: {"ApertureValue", "Aperture"},
BrightnessValue: {"BrightnessValue", "Brightness"},
ExposureBiasValue: {"ExposureBiasValue", "Exposure bias"},
MaxApertureValue: {"MaxApertureValue", "Maximum lens aperture"},
SubjectDistance: {"SubjectDistance", "Subject distance"},
MeteringMode: {"MeteringMode", "Metering mode"},
LightSource: {"LightSource", "Light source"},
Flash: {"Flash", "Flash"},
FocalLength: {"FocalLength", "Lens focal length"},
SubjectArea: {"SubjectArea", "Subject area"},
FlashEnergy: {"FlashEnergy", "Flash energy"},
SpatialFrequencyResponse: {"SpatialFrequencyResponse", "Spatial frequency response"},
FocalPlaneXResolution: {"FocalPlaneXResolution", "Focal plane X resolution"},
FocalPlaneYResolution: {"FocalPlaneYResolution", "Focal plane Y resolution"},
FocalPlaneResolutionUnit: {"FocalPlaneResolutionUnit", "Focal plane resolution unit"},
SubjectLocation: {"SubjectLocation", "Subject location"},
ExposureIndex: {"ExposureIndex", "Exposure index"},
SensingMethod: {"SensingMethod", "Sensing method"},
FileSource: {"FileSource", "File source"},
SceneType: {"SceneType", "Scene type"},
CFAPattern: {"CFAPattern", "CFA pattern"},
CustomRendered: {"CustomRendered", "Custom image processing"},
ExposureMode: {"ExposureMode", "Exposure mode"},
WhiteBalance: {"WhiteBalance", "White balance"},
DigitalZoomRatio: {"DigitalZoomRatio", "Digital zoom ratio"},
FocalLengthIn35mmFilm: {"FocalLengthIn35mmFilm", "Focal length in 35 mm film"},
SceneCaptureType: {"SceneCaptureType", "Scene capture type"},
GainControl: {"GainControl", "Gain control"},
Contrast: {"Contrast", "Contrast"},
Saturation: {"Saturation", "Saturation"},
Sharpness: {"Sharpness", "Sharpness"},
DeviceSettingDescription: {"DeviceSettingDescription", "Device settings description"},
SubjectDistanceRange: {"SubjectDistanceRange", "Subject distance range"},
ImageUniqueID: {"ImageUniqueID", "Unique image ID"},
GPSVersionID: {"GPSVersionID", "GPS tag version"},
GPSLatitudeRef: {"GPSLatitudeRef", "North or South Latitude"},
GPSLatitude: {"GPSLatitude", "Latitude"},
GPSLongitudeRef: {"GPSLongitudeRef", "East or West Longitude"},
GPSLongitude: {"GPSLongitude", "Longitude"},
GPSAltitudeRef: {"GPSAltitudeRef", "Altitude reference"},
GPSAltitude: {"GPSAltitude", "Altitude"},
GPSTimeStamp: {"GPSTimeStamp", "GPS time (atomic clock)"},
GPSSatellites: {"GPSSatellites", "GPS satellites used for measurement"},
GPSStatus: {"GPSStatus", "GPS receiver status"},
GPSMeasureMode: {"GPSMeasureMode", "GPS measurement mode"},
GPSDOP: {"GPSDOP", "Measurement precision"},
GPSSpeedRef: {"GPSSpeedRef", "Speed unit"},
GPSSpeed: {"GPSSpeed", "Speed of GPS receiver"},
GPSTrackRef: {"GPSTrackRef", "Reference for direction of movement"},
GPSTrack: {"GPSTrack", "Direction of movement"},
GPSImgDirectionRef: {"GPSImgDirectionRef", "Reference for direction of image"},
GPSImgDirection: {"GPSImgDirection", "Direction of image"},
GPSMapDatum: {"GPSMapDatum", "Geodetic survey data used"},
GPSDestLatitudeRef: {"GPSDestLatitudeRef", "Reference for latitude of destination"},
GPSDestLatitude: {"GPSDestLatitude", "Latitude of destination"},
GPSDestLongitudeRef: {"GPSDestLongitudeRef", "Reference for longitude of destination"},
GPSDestLongitude: {"GPSDestLongitude", "Longitude of destination"},
GPSDestBearingRef: {"GPSDestBearingRef", "Reference for bearing of destination"},
GPSDestBearing: {"GPSDestBearing", "Bearing of destination"},
GPSDestDistanceRef: {"GPSDestDistanceRef", "Reference for distance to destination"},
GPSDestDistance: {"GPSDestDistance", "Distance to destination"},
GPSProcessingMethod: {"GPSProcessingMethod", "Name of GPS processing method"},
GPSAreaInformation: {"GPSAreaInformation", "Name of GPS area"},
GPSDateStamp: {"GPSDateStamp", "GPS date"},
GPSDifferential: {"GPSDifferential", "GPS differential correction"},
} | exif/exiftag/name.go | 0.543348 | 0.470858 | name.go | starcoder |
// Package stat implements facilities for storing distribution sketches and updating them
package stat
import (
"math"
)
// Moment is a streaming sketch data structure.
// It keeps track of moment statistics for an incoming stream of floating point numbers.
type Moment struct {
sum float64
sumAbs float64
sumSq float64
min float64
max float64
weight float64
n int64
}
// Init initializes the sketch.
func (x *Moment) Init() {
x.sum, x.sumAbs, x.sumSq, x.min, x.max, x.weight, x.n = 0, 0, 0, math.NaN(), math.NaN(), 0, 0
}
// Add adds sample with weight one.
func (x *Moment) Add(sample float64) {
x.AddWeighted(sample, 1)
}
// AddWeighted adds sample with the given weight.
func (x *Moment) AddWeighted(sample float64, weight float64) {
x.n++
x.sum += sample * weight
x.sumAbs += math.Abs(sample * weight)
x.sumSq += sample * sample * weight
x.weight += weight
if math.IsNaN(x.min) || sample < x.min {
x.min = sample
}
if math.IsNaN(x.max) || sample > x.max {
x.max = sample
}
}
// IsEmpty returns true if no samples have been added to this sketch yet.
func (x *Moment) IsEmpty() bool {
return x.n == 0
}
// Count returns the number of samples added to this sketch.
func (x *Moment) Count() int64 {
return x.n
}
// Weight returns the total sample weight added to this sketch.
func (x *Moment) Weight() float64 {
return x.weight
}
// Mass returns the sum of absolute values of the sample-weight product of all added samples.
func (x *Moment) Mass() float64 {
return x.sumAbs
}
// Average returns the weighted average of samples added to the sketch.
func (x *Moment) Average() float64 {
return x.Moment(1)
}
// Variance returns the weighted variance of the samples added to this sketch.
func (x *Moment) Variance() float64 {
m1 := x.Moment(1)
return x.Moment(2) - m1*m1
}
// StdDev returns the weighted standard deviation of the samples added to this sketch.
func (x *Moment) StdDev() float64 {
return math.Sqrt(x.Variance())
}
// Min returns the smallest sample added to this sketch.
func (x *Moment) Min() float64 {
return x.min
}
// Ma returns the largest sample added to this sketch.
func (x *Moment) Max() float64 {
return x.max
}
// Moment returns the weighted k-th moment of the samples added to this sketch.
func (x *Moment) Moment(k float64) float64 {
switch k {
case 0:
return 1
case 1:
return x.sumAbs / x.weight
case 2:
return x.sumSq / x.weight
}
if math.IsInf(k, 1) {
return x.max
}
panic("not yet supported")
} | src/circuit/kit/stat/moment.go | 0.873714 | 0.571348 | moment.go | starcoder |
package restorable
import (
"fmt"
"image"
"github.com/hajimehoshi/ebiten/v2/internal/graphicscommand"
)
type pixelsRecord struct {
rect image.Rectangle
pix []byte
mask []byte
}
func (p *pixelsRecord) clearIfOverlapped(rect image.Rectangle) {
r := p.rect.Intersect(rect)
ox := r.Min.X - p.rect.Min.X
oy := r.Min.Y - p.rect.Min.Y
w := p.rect.Dx()
for j := 0; j < r.Dy(); j++ {
for i := 0; i < r.Dx(); i++ {
idx := 4 * ((oy+j)*w + ox + i)
p.pix[idx] = 0
p.pix[idx+1] = 0
p.pix[idx+2] = 0
p.pix[idx+3] = 0
}
}
}
func (p *pixelsRecord) merge(pix []byte, mask []byte) {
if len(p.pix) != len(pix) {
panic(fmt.Sprintf("restorable: len(p.pix) (%d) and len(pix) (%d) must match but not", len(p.pix), len(pix)))
}
if mask == nil {
p.pix = pix
return
}
if p.mask == nil {
p.mask = mask
}
if len(p.mask) != len(mask) {
panic(fmt.Sprintf("restorable: len(p.mask) (%d) and len(mask) (%d) must match but not", len(p.mask), len(mask)))
}
for i := 0; i < len(p.pix)/4; i++ {
if mask[i/8]>>(i%8)&1 == 0 {
continue
}
p.mask[i/8] |= 1 << (i % 8)
copy(p.pix[4*i:4*(i+1)], pix[4*i:4*(i+1)])
}
}
func (p *pixelsRecord) at(x, y int) (r, g, b, a byte, ok bool) {
if !image.Pt(x, y).In(p.rect) {
return 0, 0, 0, 0, false
}
idx := ((y-p.rect.Min.Y)*p.rect.Dx() + (x - p.rect.Min.X))
if p.mask != nil && p.mask[idx/8]>>(idx%8)&1 == 0 {
return 0, 0, 0, 0, false
}
return p.pix[4*idx], p.pix[4*idx+1], p.pix[4*idx+2], p.pix[4*idx+3], true
}
type pixelsRecords struct {
records []*pixelsRecord
}
func (pr *pixelsRecords) addOrReplace(pixels []byte, mask []byte, x, y, width, height int) {
if len(pixels) != 4*width*height {
msg := fmt.Sprintf("restorable: len(pixels) must be 4*%d*%d = %d but %d", width, height, 4*width*height, len(pixels))
if pixels == nil {
msg += " (nil)"
}
panic(msg)
}
rect := image.Rect(x, y, x+width, y+height)
if mask != nil {
// If a mask is specified, try merging the records.
var merged bool
for idx := len(pr.records) - 1; idx >= 0; idx-- {
if r := pr.records[idx]; r.rect.Overlaps(rect) {
if r.rect == rect {
r.merge(pixels, mask)
merged = true
}
// If there is an overlap with other regions in the existing records,
// give up modifying them and just add a record.
break
}
}
if !merged {
pr.records = append(pr.records, &pixelsRecord{
rect: rect,
pix: pixels,
mask: mask,
})
}
return
}
// Remove or update the duplicated records first.
var n int
for _, r := range pr.records {
if r.rect.In(rect) {
continue
}
pr.records[n] = r
n++
}
for i := n; i < len(pr.records); i++ {
pr.records[i] = nil
}
pr.records = pr.records[:n]
// Add the new record.
pr.records = append(pr.records, &pixelsRecord{
rect: rect,
pix: pixels,
})
}
func (pr *pixelsRecords) clear(x, y, width, height int) {
newr := image.Rect(x, y, x+width, y+height)
var n int
for _, r := range pr.records {
if r.rect.In(newr) {
continue
}
r.clearIfOverlapped(newr)
pr.records[n] = r
n++
}
for i := n; i < len(pr.records); i++ {
pr.records[i] = nil
}
pr.records = pr.records[:n]
}
func (pr *pixelsRecords) at(i, j int) (r, g, b, a byte, ok bool) {
// Traverse the slice in the reversed order.
for idx := len(pr.records) - 1; idx >= 0; idx-- {
r, g, b, a, ok := pr.records[idx].at(i, j)
if ok {
return r, g, b, a, true
}
}
return 0, 0, 0, 0, false
}
func (pr *pixelsRecords) apply(img *graphicscommand.Image) {
// TODO: Isn't this too heavy? Can we merge the operations?
for _, r := range pr.records {
img.ReplacePixels(r.pix, r.mask, r.rect.Min.X, r.rect.Min.Y, r.rect.Dx(), r.rect.Dy())
}
} | internal/restorable/rect.go | 0.526586 | 0.469034 | rect.go | starcoder |
package gintersect
// NonEmpty is true if the intersection of lhs and rhs matches a non-empty set of non-empty str1ngs.
func NonEmpty(lhs string, rhs string) (bool, error) {
g1, err := NewGlob(lhs)
if err != nil {
return false, err
}
g2, err := NewGlob(rhs)
if err != nil {
return false, err
}
var match bool
g1, g2, match = trimGlobs(g1, g2)
if !match {
return false, nil
}
return intersectNormal(g1, g2), nil
}
// trimGlobs removes matching prefixes and suffixes from g1, g2, or returns false if prefixes/suffixes don't match.
func trimGlobs(g1, g2 Glob) (Glob, Glob, bool) {
var l, r1, r2 int
// Trim from the beginning until a flagged Token or a mismatch is found.
for l = 0; l < len(g1) && l < len(g2) && g1[l].Flag() == FlagNone && g2[l].Flag() == FlagNone; l++ {
if !Match(g1[l], g2[l]) {
return nil, nil, false
}
}
// Leave one prefix Token untrimmed to avoid empty Globs because those will break the algorithm.
if l > 0 {
l--
}
// Trim from the end until a flagged Token or a mismatch is found.
for r1, r2 = len(g1)-1, len(g2)-1; r1 >= 0 && r1 >= l && r2 >= 0 && r2 >= l && g1[r1].Flag() == FlagNone && g2[r2].Flag() == FlagNone; r1, r2 = r1-1, r2-1 {
if !Match(g1[r1], g2[r2]) {
return nil, nil, false
}
}
// Leave one suffix Token untrimmed to avoid empty Globs because those will break the algorithm.
if r1 < len(g1)-1 {
r1++
r2++
}
return g1[l : r1+1], g2[l : r2+1], true
}
// All uses of `intersection exists` below mean that the intersection of the globs matches a non-empty set of non-empty strings.
// intersectNormal accepts two globs and returns a boolean describing whether their intersection exists.
// It traverses g1, g2 while ensuring that their Tokens match.
// If a flagged Token is encountered, flow of control is handed off to intersectSpecial.
func intersectNormal(g1, g2 Glob) bool {
var i, j int
for i, j = 0, 0; i < len(g1) && j < len(g2); i, j = i+1, j+1 {
if g1[i].Flag() == FlagNone && g2[j].Flag() == FlagNone {
if !Match(g1[i], g2[j]) {
return false
}
} else {
return intersectSpecial(g1[i:], g2[j:])
}
}
if i == len(g1) && j == len(g2) {
return true
}
return false
}
// intersectSpecial accepts two globs such that at least one starts with a flagged Token.
// It returns a boolean describing whether their intersection exists.
// It hands flow of control to intersectPlus or intersectStar correctly.
func intersectSpecial(g1, g2 Glob) bool {
if g1[0].Flag() != FlagNone { // If g1 starts with a Token having a Flag.
switch g1[0].Flag() {
case FlagPlus:
return intersectPlus(g1, g2)
case FlagStar:
return intersectStar(g1, g2)
}
} else { // If g2 starts with a Token having a Flag.
switch g2[0].Flag() {
case FlagPlus:
return intersectPlus(g2, g1)
case FlagStar:
return intersectStar(g2, g1)
}
}
return false
}
// intersectPlus accepts two globs such that plussed[0].Flag() == FlagPlus.
// It returns a boolean describing whether their intersection exists.
// It ensures that at least one token in other maches plussed[0], before handing flow of control to intersectSpecial.
func intersectPlus(plussed, other Glob) bool {
if !Match(plussed[0], other[0]) {
return false
}
return intersectStar(plussed, other[1:])
}
// intersectStar accepts two globs such that starred[0].Flag() == FlagStar.
// It returns a boolean describing whether their intersection exists.
// It gobbles up Tokens from other until the Tokens remaining in other intersect with starred[1:]
func intersectStar(starred, other Glob) bool {
// starToken, nextToken are the token having FlagStar and the one that follows immediately after, respectively.
var starToken, nextToken Token
starToken = starred[0]
if len(starred) > 1 {
nextToken = starred[1]
}
for i, t := range other {
// Start gobbl1ng up tokens in other while they match starToken.
if nextToken != nil && Match(t, nextToken) {
// When a token in other matches the token after starToken, stop gobbl1ng and try to match the two all the way.
allTheWay := intersectNormal(starred[1:], other[i:])
// If they match all the way, the Globs intersect.
if allTheWay {
return true
} else {
// If they don't match all the way, then the current token from other should still match starToken.
if !Match(t, starToken) {
return false
}
}
} else {
// Only move forward if this token can be gobbled up by starToken.
if !Match(t, starToken) {
return false
}
}
}
// If there was no token following starToken, and everything from other was gobbled, the Globs intersect.
if nextToken == nil {
return true
}
// If everything from other was gobbles but there was a nextToken to match, they don't intersect.
return false
} | vendor/github.com/yashtewari/glob-intersection/non_empty.go | 0.851351 | 0.44089 | non_empty.go | starcoder |
package neuralnets
import (
"math"
"math/rand"
log "github.com/sirupsen/logrus"
"gonum.org/v1/gonum/floats"
"gonum.org/v1/gonum/mat"
"libs.altipla.consulting/errors"
"code.ia/internal/config"
)
type NeuralNetwork struct {
Settings NeuralNetworkSettings
WeightsHidden *mat.Dense
BiasesHidden *mat.Dense
WeightsOut *mat.Dense
BiasesOut *mat.Dense
}
// Se utiliza la función sigmoide como función de activación.
func (network *NeuralNetwork) Sigmoid(x float64) float64 {
return 1.0 / (1.0 + math.Exp(-x))
}
// La derivada de la función sigmoide. Es necesaria para la retropropagación.
func (network *NeuralNetwork) SigmoidPrime(x float64) float64 {
return x * (1.0 - x)
}
func (network *NeuralNetwork) Print() {
log.Infof("\nPesos de la capa oculta = \n %v\n\n", mat.Formatted(network.WeightsHidden, mat.Prefix(" ")))
log.Infof("\nBiases de la capa oculta = \n %v\n\n", mat.Formatted(network.BiasesHidden, mat.Prefix(" ")))
log.Infof("\nPesos de la capa de salida = \n %v\n\n", mat.Formatted(network.WeightsOut, mat.Prefix(" ")))
log.Infof("\nBiases de la capa de salida = \n %v\n\n", mat.Formatted(network.BiasesOut, mat.Prefix(" ")))
}
// Configuración de la red neuronal.
type NeuralNetworkSettings struct {
InputNeurons int
OutputNeurons int
HiddenNeurons int
Epochs int
LearningRate float64
}
func NewNetwork(settings NeuralNetworkSettings) *NeuralNetwork {
return &NeuralNetwork{Settings: settings}
}
// Trains the neural network using backpropagation.
func (network *NeuralNetwork) Train(features, labels *mat.Dense) error {
// Primer paso. Inicializamos los pesos y desplazamientos de la red con valores aleatorios.
dataWeightsHidden := make([]float64, network.Settings.HiddenNeurons*network.Settings.InputNeurons)
dataBiasesHidden := make([]float64, network.Settings.HiddenNeurons)
dataWeightsOut := make([]float64, network.Settings.OutputNeurons*network.Settings.HiddenNeurons)
dataBiasesOut := make([]float64, network.Settings.OutputNeurons)
for _, values := range [][]float64{dataWeightsHidden, dataBiasesHidden, dataWeightsOut, dataBiasesOut} {
for i := range values {
values[i] = rand.Float64()
}
}
weightsHidden := mat.NewDense(network.Settings.InputNeurons, network.Settings.HiddenNeurons, dataWeightsHidden)
biasesHidden := mat.NewDense(1, network.Settings.HiddenNeurons, dataBiasesHidden)
weightsOut := mat.NewDense(network.Settings.HiddenNeurons, network.Settings.OutputNeurons, dataWeightsOut)
biasesOut := mat.NewDense(1, network.Settings.OutputNeurons, dataBiasesOut)
output := new(mat.Dense)
// Número de ciclos.
for i := 0; i < network.Settings.Epochs; i++ {
// Paso 1. Feedforward.
// Capa oculta.
// z^l = w^l*a^l-1+b^l
hiddenLayerInput := new(mat.Dense)
hiddenLayerInput.Mul(features, weightsHidden)
addBiasesHidden := func(_, col int, v float64) float64 {
return v + biasesHidden.At(0, col)
}
hiddenLayerInput.Apply(addBiasesHidden, hiddenLayerInput)
// a^l=sigmoide(z)
hiddenLayerActivations := new(mat.Dense)
applySigmoid := func(_, _ int, v float64) float64 {
return network.Sigmoid(v)
}
hiddenLayerActivations.Apply(applySigmoid, hiddenLayerInput)
// Capa de salida.
outputLayerInput := new(mat.Dense)
outputLayerInput.Mul(hiddenLayerActivations, weightsOut)
addBiasesOut := func(_, col int, v float64) float64 {
return v + biasesOut.At(0, col)
}
outputLayerInput.Apply(addBiasesOut, outputLayerInput)
output.Apply(applySigmoid, outputLayerInput)
// Paso 2. Calcular el error.
// Resultados esperados - resultados predichos.
networkError := new(mat.Dense)
networkError.Sub(labels, output)
// Paso 3. Propagar los errores hacia atrás.
// Derivada de la activación en la capa de salida.
spOutputLayer := new(mat.Dense)
applySigmoidPrime := func(_, _ int, v float64) float64 {
return network.SigmoidPrime(v)
}
spOutputLayer.Apply(applySigmoidPrime, output)
// Derivada de la activación en la capa de oculta.
spHiddenLayer := new(mat.Dense)
spHiddenLayer.Apply(applySigmoidPrime, hiddenLayerActivations)
// Error en la capa de salida.
deltasOutput := new(mat.Dense)
deltasOutput.MulElem(networkError, spOutputLayer)
errorsHiddenLayer := new(mat.Dense)
errorsHiddenLayer.Mul(deltasOutput, weightsOut.T())
// Error en la capa oculta.
deltasHiddenLayer := new(mat.Dense)
deltasHiddenLayer.MulElem(errorsHiddenLayer, spHiddenLayer)
// Paso 4. Ajustar pesos y desplazamientos.
// Actualizar los pesos de la capa de salida.
nablasWeightsOut := new(mat.Dense)
nablasWeightsOut.Mul(hiddenLayerActivations.T(), deltasOutput)
nablasWeightsOut.Scale(network.Settings.LearningRate, nablasWeightsOut)
weightsOut.Add(weightsOut, nablasWeightsOut)
// Actualizar los desplazamientos de la capa de salida
nablasBiasesOut, err := sumCols(deltasOutput)
if err != nil {
return errors.Trace(err)
}
// Se escalan los ajustes con la tasa de aprendizaje.
nablasBiasesOut.Scale(network.Settings.LearningRate, nablasBiasesOut)
biasesOut.Add(biasesOut, nablasBiasesOut)
// Actualizar los pesos de la capa de oculta.
nablasWeightsHidden := new(mat.Dense)
nablasWeightsHidden.Mul(features.T(), deltasHiddenLayer)
nablasWeightsHidden.Scale(network.Settings.LearningRate, nablasWeightsHidden)
weightsHidden.Add(weightsHidden, nablasWeightsHidden)
// Actualizar los desplazamientos de la capa de oculta.
nablasBiasesHidden, err := sumCols(deltasHiddenLayer)
if err != nil {
return errors.Trace(err)
}
nablasBiasesHidden.Scale(network.Settings.LearningRate, nablasBiasesHidden)
biasesHidden.Add(biasesHidden, nablasBiasesHidden)
}
// Se actualizan los pesos y desplazamientos con los valores obtenidos.
network.WeightsHidden = weightsHidden
network.BiasesHidden = biasesHidden
network.WeightsOut = weightsOut
network.BiasesOut = biasesOut
return nil
}
func (network *NeuralNetwork) Validate() (float64, error) {
// Se realiza el proceso de feedforward con el conjunto de datos de prueba.
predictions, err := network.test(config.TestFeatures)
if err != nil {
return -1, errors.Trace(err)
}
var hits, classes int
rows, _ := predictions.Dims()
for i := 0; i < rows; i++ {
labelRow := mat.Row(nil, i, config.TestLabels)
for j, label := range labelRow {
if label == 1.0 {
classes = j
break
}
}
if predictions.At(i, classes) == floats.Max(mat.Row(nil, i, predictions)) {
hits++
}
}
accuracy := float64(hits) / float64(rows)
return accuracy, nil
}
// Realiza una predicción.
func (network *NeuralNetwork) test(features *mat.Dense) (*mat.Dense, error) {
if network.WeightsHidden == nil || network.WeightsOut == nil || network.BiasesHidden == nil || network.BiasesOut == nil {
return nil, errors.Errorf("los pesos y desplamientos deben estar inicializados")
}
// Sólo realiza el proceso de feedforward.
hiddenLayerInput := new(mat.Dense)
hiddenLayerInput.Mul(features, network.WeightsHidden)
addBiasesHidden := func(_, col int, v float64) float64 {
return v + network.BiasesHidden.At(0, col)
}
hiddenLayerInput.Apply(addBiasesHidden, hiddenLayerInput)
hiddenLayerActivations := new(mat.Dense)
applySigmoid := func(_, _ int, v float64) float64 {
return network.Sigmoid(v)
}
hiddenLayerActivations.Apply(applySigmoid, hiddenLayerInput)
outputLayerInput := new(mat.Dense)
outputLayerInput.Mul(hiddenLayerActivations, network.WeightsOut)
addBiasesOut := func(_, col int, v float64) float64 {
return v + network.BiasesOut.At(0, col)
}
outputLayerInput.Apply(addBiasesOut, outputLayerInput)
output := new(mat.Dense)
output.Apply(applySigmoid, outputLayerInput)
return output, nil
}
// Suma las columnas de una matriz dejando intacta la matriz.
func sumCols(m *mat.Dense) (*mat.Dense, error) {
_, nCols := m.Dims()
var output *mat.Dense
data := make([]float64, nCols)
for i := 0; i < nCols; i++ {
col := mat.Col(nil, i, m)
data[i] = floats.Sum(col)
}
output = mat.NewDense(1, nCols, data)
return output, nil
} | internal/neuralnets/neural_networks.go | 0.648689 | 0.408454 | neural_networks.go | starcoder |
package alt
import (
"fmt"
"github.com/ngjaying/ojg/gen"
)
var emptySlice = []interface{}{}
// Builder is a basic type builder. It uses a stack model to build where maps
// (objects) and slices (arrays) add pushed on the stack and closed with a
// pop.
type Builder struct {
stack []interface{}
starts []int
}
// Reset the builder.
func (b *Builder) Reset() {
if 0 < cap(b.stack) && 0 < len(b.stack) {
b.stack = b.stack[:0]
b.starts = b.starts[:0]
} else {
b.stack = make([]interface{}, 0, 64)
b.starts = make([]int, 0, 16)
}
}
// Object pushs a map[string]interface{} onto the stack. A key must be
// provided if the top of the stack is an object (map) and must not be
// provided if the op of the stack is an array or slice.
func (b *Builder) Object(key ...string) error {
newObj := map[string]interface{}{}
if 0 < len(key) {
if len(b.starts) == 0 || 0 <= b.starts[len(b.starts)-1] {
return fmt.Errorf("can not use a key when pushing to an array")
}
if obj, _ := b.stack[len(b.stack)-1].(map[string]interface{}); obj != nil {
obj[key[0]] = newObj
}
} else if 0 < len(b.starts) && b.starts[len(b.starts)-1] < 0 {
return fmt.Errorf("must have a key when pushing to an object")
}
b.starts = append(b.starts, -1)
b.stack = append(b.stack, newObj)
return nil
}
// Array pushs a []interface{} onto the stack. A key must be provided if the
// top of the stack is an object (map) and must not be provided if the op of
// the stack is an array or slice.
func (b *Builder) Array(key ...string) error {
if 0 < len(key) {
if len(b.starts) == 0 || 0 <= b.starts[len(b.starts)-1] {
return fmt.Errorf("can not use a key when pushing to an array")
}
b.stack = append(b.stack, gen.Key(key[0]))
} else if 0 < len(b.starts) && b.starts[len(b.starts)-1] < 0 {
return fmt.Errorf("must have a key when pushing to an object")
}
b.starts = append(b.starts, len(b.stack))
b.stack = append(b.stack, emptySlice)
return nil
}
// Value pushs a value onto the stack. A key must be provided if the top of
// the stack is an object (map) and must not be provided if the op of the
// stack is an array or slice.
func (b *Builder) Value(value interface{}, key ...string) error {
if 0 < len(key) {
if len(b.starts) == 0 || 0 <= b.starts[len(b.starts)-1] {
return fmt.Errorf("can not use a key when pushing to an array")
}
if obj, _ := b.stack[len(b.stack)-1].(map[string]interface{}); obj != nil {
obj[key[0]] = value
}
} else if 0 < len(b.starts) && b.starts[len(b.starts)-1] < 0 {
return fmt.Errorf("must have a key when pushing to an object")
} else {
b.stack = append(b.stack, value)
}
return nil
}
// Pop the stack, closing an array or object.
func (b *Builder) Pop() {
if 0 < len(b.starts) {
start := b.starts[len(b.starts)-1]
if 0 <= start { // array
start++
size := len(b.stack) - start
a := make([]interface{}, size)
copy(a, b.stack[start:len(b.stack)])
b.stack = b.stack[:start]
b.stack[start-1] = a
if 2 < len(b.stack) {
if k, ok := b.stack[len(b.stack)-2].(gen.Key); ok {
if obj, _ := b.stack[len(b.stack)-3].(map[string]interface{}); obj != nil {
obj[string(k)] = a
b.stack = b.stack[:len(b.stack)-2]
}
}
}
}
b.starts = b.starts[:len(b.starts)-1]
}
}
// PopAll repeats Pop until all open arrays or objects are closed.
func (b *Builder) PopAll() {
for 0 < len(b.starts) {
b.Pop()
}
}
// Result of the builder is returned. This is the first item pushed on to the
// stack.
func (b *Builder) Result() (result interface{}) {
if 0 < len(b.stack) {
result = b.stack[0]
}
return
} | alt/builder.go | 0.537041 | 0.487307 | builder.go | starcoder |
package p1847
import "sort"
func closestRoom(rooms [][]int, queries [][]int) []int {
rs := make([]Room, len(rooms))
for i, r := range rooms {
rs[i] = Room{r[0], r[1]}
}
sort.Slice(rs, func(i, j int) bool {
return rs[i].size > rs[j].size
})
qs := make([]Query, len(queries))
for i, q := range queries {
qs[i] = Query{q[0], q[1], i}
}
sort.Slice(qs, func(i, j int) bool {
return qs[i].size > qs[j].size
})
var root *Node
ans := make([]int, len(queries))
var j int
for _, q := range qs {
for j < len(rs) && rs[j].size >= q.size {
root = Insert(root, rs[j].id)
j++
}
a := LowerBound(root, q.pref)
ans[q.id] = -1
if a != nil {
ans[q.id] = a.key
}
b := Before(root, q.pref)
if b != nil {
if ans[q.id] < 0 || abs(q.pref-b.key) <= abs(q.pref-ans[q.id]) {
ans[q.id] = b.key
}
}
}
return ans
}
type Room struct {
id int
size int
}
type Query struct {
pref int
size int
id int
}
func max(a, b int) int {
if a >= b {
return a
}
return b
}
func abs(num int) int {
if num < 0 {
return -num
}
return num
}
/**
* this is a AVL tree
*/
type Node struct {
key int
height int
cnt int
left, right *Node
}
func (node *Node) Height() int {
if node == nil {
return 0
}
return node.height
}
func NewNode(key int) *Node {
node := new(Node)
node.key = key
node.height = 1
node.cnt = 1
return node
}
func rightRotate(y *Node) *Node {
x := y.left
t2 := x.right
x.right = y
y.left = t2
y.height = max(y.left.Height(), y.right.Height()) + 1
x.height = max(x.left.Height(), x.right.Height()) + 1
return x
}
func leftRotate(x *Node) *Node {
y := x.right
t2 := y.left
y.left = x
x.right = t2
x.height = max(x.left.Height(), x.right.Height()) + 1
y.height = max(y.left.Height(), y.right.Height()) + 1
return y
}
func (node *Node) GetBalance() int {
if node == nil {
return 0
}
return node.left.Height() - node.right.Height()
}
func Insert(node *Node, key int) *Node {
if node == nil {
return NewNode(key)
}
if node.key == key {
node.cnt++
return node
}
if node.key > key {
node.left = Insert(node.left, key)
} else {
node.right = Insert(node.right, key)
}
node.height = max(node.left.Height(), node.right.Height()) + 1
balance := node.GetBalance()
if balance > 1 && key < node.left.key {
return rightRotate(node)
}
if balance < -1 && key > node.right.key {
return leftRotate(node)
}
if balance > 1 && key > node.left.key {
node.left = leftRotate(node.left)
return rightRotate(node)
}
if balance < -1 && key < node.right.key {
node.right = rightRotate(node.right)
return leftRotate(node)
}
return node
}
func LowerBound(root *Node, key int) *Node {
if root == nil {
return nil
}
if root.key >= key {
res := LowerBound(root.left, key)
if res != nil {
return res
}
return root
}
return LowerBound(root.right, key)
}
func Before(root *Node, key int) *Node {
if root == nil {
return nil
}
if root.key >= key {
return Before(root.left, key)
}
// root.key < key
res := Before(root.right, key)
if res != nil {
return res
}
return root
}
func MinValueNode(root *Node) *Node {
cur := root
for cur.left != nil {
cur = cur.left
}
return cur
}
func Delete(root *Node, key int) *Node {
if root == nil {
return nil
}
if key < root.key {
root.left = Delete(root.left, key)
} else if key > root.key {
root.right = Delete(root.right, key)
} else {
root.cnt--
if root.cnt > 0 {
return root
}
if root.left == nil || root.right == nil {
tmp := root.left
if root.left == nil {
tmp = root.right
}
root = tmp
} else {
tmp := MinValueNode(root.right)
root.key = tmp.key
root.cnt = tmp.cnt
// make sure tmp node deleted after call delete on root.right
tmp.cnt = 1
root.right = Delete(root.right, tmp.key)
}
}
if root == nil {
return root
}
root.height = max(root.left.Height(), root.right.Height()) + 1
balance := root.GetBalance()
if balance > 1 && root.left.GetBalance() >= 0 {
return rightRotate(root)
}
if balance > 1 && root.left.GetBalance() < 0 {
root.left = leftRotate(root.left)
return rightRotate(root)
}
if balance < -1 && root.right.GetBalance() <= 0 {
return leftRotate(root)
}
if balance < -1 && root.right.GetBalance() > 0 {
root.right = rightRotate(root.right)
return leftRotate(root)
}
return root
} | src/leetcode/set1000/set1000/set1800/set1840/p1847/solution.go | 0.647241 | 0.414188 | solution.go | starcoder |
package api
func init() {
Swagger.Add("chef", `{
"swagger": "2.0",
"info": {
"title": "api/external/ingest/chef.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/ingest/events/chef/action": {
"post": {
"operationId": "ProcessChefAction",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/responseProcessChefActionResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/requestAction"
}
}
],
"tags": [
"ChefIngester"
]
}
},
"/ingest/events/chef/liveness": {
"post": {
"operationId": "ProcessLivenessPing",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/responseProcessLivenessResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/requestLiveness"
}
}
],
"tags": [
"ChefIngester"
]
}
},
"/ingest/events/chef/node-multiple-deletes": {
"post": {
"operationId": "ProcessMultipleNodeDeletes",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/responseProcessMultipleNodeDeleteResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/requestMultipleNodeDeleteRequest"
}
}
],
"tags": [
"ChefIngester"
]
}
},
"/ingest/events/chef/nodedelete": {
"post": {
"operationId": "ProcessNodeDelete",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/responseProcessNodeDeleteResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/requestDelete"
}
}
],
"tags": [
"ChefIngester"
]
}
},
"/ingest/events/chef/run": {
"post": {
"operationId": "ProcessChefRun",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/responseProcessChefRunResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/requestRun"
}
}
],
"tags": [
"ChefIngester"
]
}
},
"/ingest/version": {
"get": {
"operationId": "GetVersion",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/versionVersionInfo"
}
}
},
"tags": [
"ChefIngester"
]
}
}
},
"definitions": {
"protobufListValue": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufValue"
},
"description": "Repeated field of dynamically typed values."
}
},
"description": "` + "`" + `ListValue` + "`" + ` is a wrapper around a repeated field of values.\n\nThe JSON representation for ` + "`" + `ListValue` + "`" + ` is JSON array."
},
"protobufNullValue": {
"type": "string",
"enum": [
"NULL_VALUE"
],
"default": "NULL_VALUE",
"description": "` + "`" + `NullValue` + "`" + ` is a singleton enumeration to represent the null value for the\n` + "`" + `Value` + "`" + ` type union.\n\n The JSON representation for ` + "`" + `NullValue` + "`" + ` is JSON ` + "`" + `null` + "`" + `.\n\n - NULL_VALUE: Null value."
},
"protobufStruct": {
"type": "object",
"properties": {
"fields": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/protobufValue"
},
"description": "Unordered map of dynamically typed values."
}
},
"description": "` + "`" + `Struct` + "`" + ` represents a structured data value, consisting of fields\nwhich map to dynamically typed values. In some languages, ` + "`" + `Struct` + "`" + `\nmight be supported by a native representation. For example, in\nscripting languages like JS a struct is represented as an\nobject. The details of that representation are described together\nwith the proto support for the language.\n\nThe JSON representation for ` + "`" + `Struct` + "`" + ` is JSON object."
},
"protobufValue": {
"type": "object",
"properties": {
"null_value": {
"$ref": "#/definitions/protobufNullValue",
"description": "Represents a null value."
},
"number_value": {
"type": "number",
"format": "double",
"description": "Represents a double value."
},
"string_value": {
"type": "string",
"description": "Represents a string value."
},
"bool_value": {
"type": "boolean",
"format": "boolean",
"description": "Represents a boolean value."
},
"struct_value": {
"$ref": "#/definitions/protobufStruct",
"description": "Represents a structured value."
},
"list_value": {
"$ref": "#/definitions/protobufListValue",
"description": "Represents a repeated ` + "`" + `Value` + "`" + `."
}
},
"description": "` + "`" + `Value` + "`" + ` represents a dynamically typed value which can be either\nnull, a number, a string, a boolean, a recursive struct value, or a\nlist of values. A producer of value is expected to set one of that\nvariants, absence of any variant indicates an error.\n\nThe JSON representation for ` + "`" + `Value` + "`" + ` is JSON value."
},
"requestAction": {
"type": "object",
"properties": {
"id": {
"type": "string",
"title": "ID of the action message itself"
},
"message_type": {
"type": "string"
},
"message_version": {
"type": "string"
},
"entity_name": {
"type": "string"
},
"entity_type": {
"type": "string"
},
"task": {
"type": "string"
},
"organization_name": {
"type": "string"
},
"remote_hostname": {
"type": "string"
},
"run_id": {
"type": "string"
},
"content": {
"type": "string",
"format": "byte",
"description": "This new field called 'content' is being used to send the entire raw JSON\nmessage in bytes, this field is heavily used by the gateway for the DataCollector\nFunc Handler that will send the Action message to the (receiver) ingest-service\nthat will manually unmarshal the message from this field if it is provided.\nThe main purpose of this field it to improve the performance of ingestion when\nthe requests comes in REST/HTTP format."
},
"node_id": {
"type": "string"
},
"recorded_at": {
"type": "string"
},
"remote_request_id": {
"type": "string"
},
"request_id": {
"type": "string"
},
"requestor_name": {
"type": "string"
},
"requestor_type": {
"type": "string"
},
"service_hostname": {
"type": "string"
},
"user_agent": {
"type": "string"
},
"parent_type": {
"type": "string"
},
"parent_name": {
"type": "string"
},
"revision_id": {
"type": "string"
}
}
},
"requestDelete": {
"type": "object",
"properties": {
"id": {
"type": "string",
"title": "ID of the action message itself"
},
"node_name": {
"type": "string"
},
"organization_name": {
"type": "string"
},
"remote_hostname": {
"type": "string"
},
"service_hostname": {
"type": "string"
},
"node_id": {
"type": "string"
}
}
},
"requestDeprecation": {
"type": "object",
"properties": {
"message": {
"type": "string"
},
"url": {
"type": "string"
},
"location": {
"type": "string"
}
}
},
"requestDescription": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"sections": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufStruct"
}
}
}
},
"requestError": {
"type": "object",
"properties": {
"class": {
"type": "string"
},
"message": {
"type": "string"
},
"backtrace": {
"type": "array",
"items": {
"type": "string"
}
},
"description": {
"$ref": "#/definitions/requestDescription"
}
}
},
"requestExpandedRunList": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"run_list": {
"type": "array",
"items": {
"$ref": "#/definitions/requestRunList"
}
}
}
},
"requestLiveness": {
"type": "object",
"properties": {
"event_type": {
"type": "string"
},
"entity_uuid": {
"type": "string"
},
"chef_server_fqdn": {
"type": "string"
},
"source": {
"type": "string"
},
"message_version": {
"type": "string"
},
"organization_name": {
"type": "string"
},
"node_name": {
"type": "string"
}
}
},
"requestMultipleNodeDeleteRequest": {
"type": "object",
"properties": {
"node_ids": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"requestResource": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"name": {
"type": "string"
},
"id": {
"type": "string"
},
"after": {
"$ref": "#/definitions/protobufStruct"
},
"before": {
"$ref": "#/definitions/protobufStruct"
},
"duration": {
"type": "string"
},
"delta": {
"type": "string"
},
"cookbook_name": {
"type": "string"
},
"cookbook_version": {
"type": "string"
},
"status": {
"type": "string"
},
"recipe_name": {
"type": "string"
},
"ignore_failure": {
"$ref": "#/definitions/protobufValue"
},
"conditional": {
"type": "string"
},
"result": {
"type": "string"
}
}
},
"requestRun": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "1 through 15 are for frequently occuring fields\nReserving for shared fields between run_start and run_converge mesages."
},
"run_id": {
"type": "string"
},
"entity_uuid": {
"type": "string"
},
"message_version": {
"type": "string"
},
"message_type": {
"type": "string"
},
"node_name": {
"type": "string"
},
"organization_name": {
"type": "string"
},
"start_time": {
"type": "string"
},
"chef_server_fqdn": {
"type": "string"
},
"content": {
"type": "string",
"format": "byte",
"description": "This new field called 'content' is being used to send the entire raw JSON\nmessage in bytes, this field is heavily used by the gateway for the DataCollector\nFunc Handler that will send the Run message to the (receiver) ingest-service\nthat will manually unmarshal the message from this field if it is provided.\nThe main purpose of this field it to improve the performance of ingestion when\nthe requests comes in REST/HTTP format."
},
"end_time": {
"type": "string"
},
"status": {
"type": "string"
},
"total_resource_count": {
"type": "integer",
"format": "int32"
},
"updated_resource_count": {
"type": "integer",
"format": "int32"
},
"source": {
"type": "string"
},
"expanded_run_list": {
"$ref": "#/definitions/requestExpandedRunList"
},
"resources": {
"type": "array",
"items": {
"$ref": "#/definitions/requestResource"
}
},
"run_list": {
"type": "array",
"items": {
"type": "string"
}
},
"node": {
"$ref": "#/definitions/protobufStruct"
},
"error": {
"$ref": "#/definitions/requestError"
},
"policy_name": {
"type": "string"
},
"policy_group": {
"type": "string"
},
"deprecations": {
"type": "array",
"items": {
"$ref": "#/definitions/requestDeprecation"
}
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"requestRunList": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"skipped": {
"type": "boolean",
"format": "boolean"
},
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/requestRunList"
}
}
}
},
"responseProcessChefActionResponse": {
"type": "object"
},
"responseProcessChefRunResponse": {
"type": "object"
},
"responseProcessLivenessResponse": {
"type": "object"
},
"responseProcessMultipleNodeDeleteResponse": {
"type": "object"
},
"responseProcessNodeDeleteResponse": {
"type": "object"
},
"versionVersionInfo": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"sha": {
"type": "string"
},
"built": {
"type": "string"
}
}
}
}
}
`)
} | components/automate-gateway/api/chef.pb.swagger.go | 0.833291 | 0.422683 | chef.pb.swagger.go | starcoder |
package noarch
import (
"fmt"
"time"
)
// TimeT is the representation of "time_t".
// For historical reasons, it is generally implemented as an integral value
// representing the number of seconds elapsed
// since 00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp).
// Although libraries may implement this type using alternative time
// representations.
type TimeT int32
// NullToTimeT converts a NULL to an array of TimeT.
func NullToTimeT(i int32) []TimeT {
return []TimeT{}
}
// Time returns the current time.
func Time(tloc []TimeT) TimeT {
var t = TimeT(int32(time.Now().Unix()))
if len(tloc) > 0 {
tloc[0] = t
}
return t
}
// IntToTimeT converts an int32 to a TimeT.
func IntToTimeT(t int32) TimeT {
return TimeT(t)
}
// Ctime converts TimeT to a string.
func Ctime(tloc []TimeT) []byte {
if len(tloc) > 0 {
var t = time.Unix(int64(tloc[0]), 0)
return []byte(t.Format(time.ANSIC) + "\n")
}
return nil
}
// TimeTToFloat64 converts TimeT to a float64. It is used by the tests.
func TimeTToFloat64(t TimeT) float64 {
return float64(t)
}
// Tm - base struct in "time.h"
// Structure containing a calendar date and time broken down into its
// components
type Tm struct {
TmSec int
TmMin int
TmHour int
TmMday int
TmMon int
TmYear int
TmWday int
TmYday int
TmIsdst int
// tm_gmtoff int32
// tm_zone []byte
}
// LocalTime - Convert time_t to tm as local time
// Uses the value pointed by timer to fill a tm structure with the values that
// represent the corresponding time, expressed for the local timezone.
func LocalTime(timer []TimeT) (tm []Tm) {
t := time.Unix(int64(timer[0]), 0)
tm = make([]Tm, 1)
tm[0].TmSec = t.Second()
tm[0].TmMin = t.Minute()
tm[0].TmHour = t.Hour()
tm[0].TmMday = t.Day()
tm[0].TmMon = int(t.Month()) - 1
tm[0].TmYear = t.Year() - 1900
tm[0].TmWday = int(t.Weekday())
tm[0].TmYday = t.YearDay() - 1
return
}
// Gmtime - Convert time_t to tm as UTC time
func Gmtime(timer []TimeT) (tm []Tm) {
t := time.Unix(int64(timer[0]), 0)
t = t.UTC()
tm = make([]Tm, 1)
tm[0].TmSec = t.Second()
tm[0].TmMin = t.Minute()
tm[0].TmHour = t.Hour()
tm[0].TmMday = t.Day()
tm[0].TmMon = int(t.Month()) - 1
tm[0].TmYear = t.Year() - 1900
tm[0].TmWday = int(t.Weekday())
tm[0].TmYday = t.YearDay() - 1
return
}
// Mktime - Convert tm structure to time_t
// Returns the value of type time_t that represents the local time described
// by the tm structure pointed by timeptr (which may be modified).
func Mktime(tm []Tm) TimeT {
t := time.Date(tm[0].TmYear+1900, time.Month(tm[0].TmMon)+1, tm[0].TmMday,
tm[0].TmHour, tm[0].TmMin, tm[0].TmSec, 0, time.Now().Location())
tm[0].TmWday = int(t.Weekday())
return TimeT(int32(t.Unix()))
}
// constants for asctime
var wdayName = [...]string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
var monName = [...]string{
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
}
// Asctime - Convert tm structure to string
func Asctime(tm []Tm) []byte {
return []byte(fmt.Sprintf("%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wdayName[tm[0].TmWday],
monName[tm[0].TmMon],
tm[0].TmMday, tm[0].TmHour,
tm[0].TmMin, tm[0].TmSec,
1900+tm[0].TmYear))
}
type ClockT int64
func Clock() ClockT {
return ClockT(time.Now().Unix())
}
func Difftime(end, start TimeT) float64 {
return float64(end - start)
} | noarch/time.go | 0.783368 | 0.544862 | time.go | starcoder |
package main
import (
"container/list"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/mathgl/mgl32"
)
// MatrixStack Maps the stack of rendering matrixes
type MatrixStack struct {
Current *mgl32.Mat4
Stack *list.List
}
// MatrixUniforms Maps uniform matrixes
type MatrixUniforms struct {
Model int32
Normal int32
Texture int32
}
// InstanceMatrixStack Stores the stack of rendering matrixes
var InstanceMatrixStack MatrixStack
// InstanceMatrixUniforms Stores uniform matrixes
var InstanceMatrixUniforms MatrixUniforms
func initializeMatrix() {
identityMatrix := mgl32.Ident4()
setMatrixStack(list.New())
setMatrix(&identityMatrix)
}
func getMatrix() (*mgl32.Mat4) {
return InstanceMatrixStack.Current
}
func setMatrix(matrix *mgl32.Mat4) {
InstanceMatrixStack.Current = matrix
}
func getMatrixStack() (*list.List) {
return InstanceMatrixStack.Stack
}
func setMatrixStack(matrixStack *list.List) {
InstanceMatrixStack.Stack = matrixStack
}
func pushMatrix() {
// Stack current matrix
currentMatrix := *getMatrix()
getMatrixStack().PushBack(currentMatrix)
// Generate new current matrix
newMatrix := mgl32.Ident4().Mul4(currentMatrix)
setMatrix(&newMatrix)
}
func popMatrix() {
if getMatrixStack().Len() == 0 {
panic("Cannot pop: matrix stack is empty")
}
lastElementList := getMatrixStack().Back()
if previousMatrix, ok := (lastElementList.Value).(mgl32.Mat4); ok {
// Assign now-popped element
setMatrix(&previousMatrix)
// Remove this element from the stack
getMatrixStack().Remove(lastElementList)
} else {
panic("Cannot pop: error")
}
}
func getMatrixUniforms() (*MatrixUniforms) {
return &InstanceMatrixUniforms
}
func setMatrixUniforms(program uint32) {
matrixUniforms := getMatrixUniforms()
matrixUniforms.Model = gl.GetUniformLocation(program, gl.Str("modelUniform\x00"))
matrixUniforms.Normal = gl.GetUniformLocation(program, gl.Str("normalUniform\x00"))
matrixUniforms.Texture = gl.GetUniformLocation(program, gl.Str("textureUniform\x00"))
} | matrix.go | 0.78695 | 0.402451 | matrix.go | starcoder |
package core
import (
"math"
)
// Transform is a 4x4 transformation matrix.
type Transform struct {
mat [4][4]Float // Matrix entries
}
// NewTransform returns a pointer of the Transform.
func NewTransform(mat [4][4]Float) *Transform {
t := new(Transform)
t.mat = mat
return t
}
// NewTransformWithElements returns a pointer of the Transform,
// which has specified elements as its entries.
func NewTransformWithElements(
m00, m01, m02, m03 Float,
m10, m11, m12, m13 Float,
m20, m21, m22, m23 Float,
m30, m31, m32, m33 Float) *Transform {
t := new(Transform)
t.mat = [4][4]Float{
{m00, m01, m02, m03},
{m10, m11, m12, m13},
{m20, m21, m22, m23},
{m30, m31, m32, m33},
}
return t
}
// NewScale returns a scaling Transform.
func NewScale(sx, sy, sz Float) *Transform {
return NewTransformWithElements(
sx, 0.0, 0.0, 0.0,
0.0, sy, 0.0, 0.0,
0.0, 0.0, sz, 0.0,
0.0, 0.0, 0.0, 1.0)
}
// NewLookAt returns a pointer of the "lookAt" Transform.
func NewLookAt(origin, target, up *Vector3d) *Transform {
m03 := origin.X
m13 := origin.Y
m23 := origin.Z
m33 := 1.0
dir := target.Subtract(origin).Normalized()
left := dir.Cross(up).Normalized()
newUp := left.Cross(dir)
m00 := left.X
m10 := left.Y
m20 := left.Z
m30 := 0.0
m01 := newUp.X
m11 := newUp.Y
m21 := newUp.Z
m31 := 0.0
m02 := dir.X
m12 := dir.Y
m22 := dir.Z
m32 := 0.0
return NewTransformWithElements(
m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33,
)
}
// NewPerspective returns a pointer of the perspective Transform.
func NewPerspective(fov, aspect, near, far Float) *Transform {
pers := [4][4]Float{
{1.0 / aspect, 0.0, 0.0, 0.0},
{0.0, 1.0, 0.0, 0.0},
{0.0, 0.0, far / (far - near), -far * near / (far - near)},
{0.0, 0.0, 1.0, 0.0},
}
s := 1.0 / math.Tan(DegreeToRadian(fov)*0.5)
return NewScale(s, s, 1.0).Multiply(NewTransform(pers))
}
// At returns an element of Transform.
func (t *Transform) At(i, j int) Float {
if i < 0 || j < 0 || i >= 4 || j >= 4 {
panic("Index out of bounds!")
}
return t.mat[i][j]
}
// Multiply computes the multiplications of Transforms.
func (t1 *Transform) Multiply(t2 *Transform) *Transform {
ret := new(Transform)
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
ret.mat[i][j] = 0.0
for k := 0; k < 4; k++ {
ret.mat[i][j] += t1.mat[i][k] * t2.mat[k][j]
}
}
}
return ret
}
// Apply multiplies the transform to a vector.
func (t *Transform) ApplyToP(v *Vector3d) *Vector3d {
u := [4]Float{v.X, v.Y, v.Z, 1.0}
ret := [4]Float{0.0, 0.0, 0.0, 0.0}
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
ret[i] += t.mat[i][j] * u[j]
}
}
return NewVector3d(ret[0], ret[1], ret[2]).Divide(ret[3])
}
// Apply multiplies the transform to a vector.
func (t *Transform) ApplyToV(v *Vector3d) *Vector3d {
u := [3]Float{v.X, v.Y, v.Z}
ret := [3]Float{0.0, 0.0, 0.0}
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
ret[i] += t.mat[i][j] * u[j]
}
}
return NewVector3d(ret[0], ret[1], ret[2])
}
// Inverted returns a inverted Transform.
func (t *Transform) Inverted() *Transform {
indxc := make([]int, 4)
indxr := make([]int, 4)
ipiv := [4]int{0, 0, 0, 0}
mInv := [4][4]Float{}
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
mInv[i][j] = t.mat[i][j]
}
}
for i := 0; i < 4; i++ {
irow, icol := 0, 0
big := 0.0
// Choose pivot
for j := 0; j < 4; j++ {
if ipiv[j] != 1 {
for k := 0; k < 4; k++ {
if ipiv[k] == 0 {
if math.Abs(mInv[j][k]) >= big {
big = math.Abs(mInv[j][k])
irow = j
icol = k
}
} else if ipiv[k] > 1 {
panic("Singular matrix cannot be inverted")
}
}
}
}
ipiv[icol]++
// Swap pivot row
if irow != icol {
for k := 0; k < 4; k++ {
mInv[irow][k], mInv[icol][k] = mInv[icol][k], mInv[irow][k]
}
}
indxr[i] = irow
indxc[i] = icol
if math.Abs(mInv[icol][icol]) < Eps {
panic("Singular matrix cannot be inverted")
}
pinv := 1.0 / mInv[icol][icol]
mInv[icol][icol] = 1.0
for j := 0; j < 4; j++ {
mInv[icol][j] *= pinv
}
// Subtract diagonal value from the other rows
for j := 0; j < 4; j++ {
if j != icol {
save := mInv[j][icol]
mInv[j][icol] = 0.0
for k := 0; k < 4; k++ {
mInv[j][k] -= mInv[icol][k] * save
}
}
}
}
// Swap columins to reset permutations
for j := 3; j >= 0; j-- {
if indxr[j] != indxc[j] {
for k := 0; k < 4; k++ {
mInv[k][indxr[j]], mInv[k][indxc[j]] =
mInv[k][indxc[j]], mInv[k][indxr[j]]
}
}
}
return NewTransform(mInv)
} | src/core/transform.go | 0.826782 | 0.65758 | transform.go | starcoder |
package disttwoatoms
import (
"bufio"
"errors"
"fmt"
"strconv"
"strings"
)
// readCfgFirst reads the first configuration. It reads the number of atoms, the
// columns and performs the usual calculations like in readCfg. This method
// saves a lot of runtime because it saves the number of columns. It is
// therefore non essential to re-read the number of columns and detect where the
// interesting columns are located.
func (d *DistTwoAtoms) readCfgFirst(r *bufio.Reader) (xyz1 [3]float64, xyz2 [3]float64, err error) {
for i := 0; i < 3; i++ {
r.ReadSlice('\n')
}
b, _ := r.ReadSlice('\n')
d.atoms, err = strconv.Atoi(string(b)[:len(b)-1])
if err != nil {
return
}
for i := 0; i < 4; i++ {
r.ReadSlice('\n')
}
b, _ = r.ReadSlice('\n')
fields := strings.Fields(string(b))
if len(fields) <= 2 {
err = fmt.Errorf("not enough columns (at least 3; got %d)", len(fields))
return
}
fields = fields[2:]
var found int
d.colsLen = len(fields)
for k, v := range fields {
switch v {
case "xu":
d.cols[0] = k
case "yu":
d.cols[1] = k
case "zu":
d.cols[2] = k
default:
continue
}
found++
}
if found < len(d.cols) {
err = errors.New("cannot find the columns xu, yu, and zu")
return
}
xyz1, xyz2, err = d.fetchXYZ(r)
if err != nil {
err = fmt.Errorf("fetchXYZ: %w", err)
return
}
return
}
// readCfg reads a configuration of the LAMMPS trajectory. This method will call
// fetchXYZ to fetch the coordinates of the two atoms. readCfgFirst must be
// called before using this method as it doesn't read the number of atoms nor
// it analyzes the columns.
func (d *DistTwoAtoms) readCfg(r *bufio.Reader) (xyz1 [3]float64, xyz2 [3]float64, err error) {
for i := 0; i < 9; i++ {
r.ReadSlice('\n')
}
xyz1, xyz2, err = d.fetchXYZ(r)
if err != nil {
err = fmt.Errorf("fetchXYZ: %w", err)
}
return
}
// fetchXYZ fetches the coordinates of the two atoms by calling readXYZ two
// times (one for the first atom, and the other for the second atom).
func (d *DistTwoAtoms) fetchXYZ(r *bufio.Reader) (xyz1 [3]float64, xyz2 [3]float64, err error) {
for i := 0; i < d.Atom1; i++ {
r.ReadSlice('\n')
}
xyz1, err = d.readXYZ(r)
if err != nil {
err = fmt.Errorf("readXYZ: %w", err)
return
}
for i := 0; i < (d.Atom2 - d.Atom1 - 1); i++ {
r.ReadSlice('\n')
}
xyz2, err = d.readXYZ(r)
if err != nil {
err = fmt.Errorf("readXYZ: %w", err)
return
}
for i := 0; i < (d.atoms - d.Atom2 - 1); i++ {
r.ReadSlice('\n')
}
return
}
func (d *DistTwoAtoms) readXYZ(r *bufio.Reader) (xyz [3]float64, err error) {
b, _ := r.ReadSlice('\n')
fields := strings.Fields(string(b))
if len(fields) != d.colsLen {
err = fmt.Errorf("number of columns don't match: %d (expected %d)", len(fields), d.colsLen)
return
}
for k := 0; k < 3; k++ {
xyz[k], _ = strconv.ParseFloat(fields[d.cols[k]], 64)
}
return
} | pkg/disttwoatoms/read.go | 0.609757 | 0.568176 | read.go | starcoder |
package camera
import (
"image/png"
"jensmcatanho/raytracer-go/math/color"
"jensmcatanho/raytracer-go/math/geometry"
"jensmcatanho/raytracer-go/math/sampler"
"jensmcatanho/raytracer-go/tracer"
"log"
"os"
)
// Pinhole is a camera that renders a scene with a perspective projection
type Pinhole struct {
Eye *geometry.Vector
LookAt *geometry.Vector
u *geometry.Vector
v *geometry.Vector
w *geometry.Vector
Yaw float64
Pitch float64
Roll float64
Exposure float64
Zoom float64
ProjectionPlane ProjectionPlane
Tracer tracer.Tracer
Sampler sampler.Sampler
}
// RenderScene traces a ray for every pixel in the target image and sets the pixel color with the color of the object hit
func (p *Pinhole) RenderScene() {
ray := new(geometry.Ray)
ray.Origin = *p.Eye
pixelSize := p.ProjectionPlane.PixelSize / p.Zoom
p.ComputeUVW()
for row := 0; row < p.ProjectionPlane.Height; row++ {
for col := 0; col < p.ProjectionPlane.Width; col++ {
pixelColor := *color.NewColor(0., 0., 0.)
for sample := 0; sample < p.Sampler.Samples; sample++ {
samplePoint := p.Sampler.SampleUnitSquare()
ray.Direction = p.RayDirection(*geometry.NewVector(
pixelSize*(float64(col)-0.5*float64(p.ProjectionPlane.Width)+samplePoint.X),
pixelSize*(float64(row)-0.5*float64(p.ProjectionPlane.Height)+samplePoint.Y),
0.,
))
surface := p.Tracer.TraceRay(*ray)
if surface != nil && surface.Hit {
pixelColor = *pixelColor.Add(surface.Color)
}
}
pixelColor = *pixelColor.Multiply(p.Exposure / float64(p.Sampler.Samples))
p.ProjectionPlane.SetPixel(row, col, pixelColor)
}
}
}
// ComputeUVW calculates the camera's coordinate system
func (p *Pinhole) ComputeUVW() {
if p.Eye.X == p.LookAt.X && p.Eye.Z == p.LookAt.Z && p.Eye.Y > p.LookAt.Y {
// Looking down
p.u = geometry.NewVector(0., 0., 1.)
p.v = geometry.NewVector(1., 0., 0.)
p.w = geometry.NewVector(0., 1., 0.)
return
} else if p.Eye.X == p.LookAt.X && p.Eye.Z == p.LookAt.Z && p.Eye.Y < p.LookAt.Y {
// Looking up
p.u = geometry.NewVector(1., 0., 0.)
p.v = geometry.NewVector(0., 0., 1.)
p.w = geometry.NewVector(0., -1., 0.)
return
}
p.w = p.Eye.Sub(p.LookAt)
p.w.Normalize()
p.u = worldUp.Cross(p.w)
p.u.Normalize()
p.v = p.w.Cross(p.u)
}
// RayDirection returns the direction of a ray given a sample point on the projection plane
func (p *Pinhole) RayDirection(samplePoint geometry.Vector) geometry.Vector {
direction := p.u.Multiply(samplePoint.X)
direction = direction.Add(p.v.Multiply(samplePoint.Y))
direction = direction.Sub(p.w.Multiply(p.ProjectionPlane.Distance))
direction.Normalize()
return *direction
}
// SaveImage saves a png image of the rendered scene
func (p *Pinhole) SaveImage() {
file, err := os.Create("image.png")
if err != nil {
log.Fatal(err)
}
if err := png.Encode(file, &p.ProjectionPlane.Image); err != nil {
file.Close()
log.Fatal(err)
}
if err := file.Close(); err != nil {
log.Fatal(err)
}
} | camera/pinhole.go | 0.842021 | 0.603844 | pinhole.go | starcoder |
package chart
import (
"fmt"
"math"
)
// MinSeries draws a horizontal line at the minimum value of the inner series.
type MinSeries struct {
Name string
Style Style
YAxis YAxisType
InnerSeries ValuesProvider
minValue *float64
}
// GetName returns the name of the time series.
func (ms MinSeries) GetName() string {
return ms.Name
}
// GetStyle returns the line style.
func (ms MinSeries) GetStyle() Style {
return ms.Style
}
// GetYAxis returns which YAxis the series draws on.
func (ms MinSeries) GetYAxis() YAxisType {
return ms.YAxis
}
// Len returns the number of elements in the series.
func (ms MinSeries) Len() int {
return ms.InnerSeries.Len()
}
// GetValues gets a value at a given index.
func (ms *MinSeries) GetValues(index int) (x, y float64) {
ms.ensureMinValue()
x, _ = ms.InnerSeries.GetValues(index)
y = *ms.minValue
return
}
// Render renders the series.
func (ms *MinSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) {
style := ms.Style.InheritFrom(defaults)
Draw.LineSeries(r, canvasBox, xrange, yrange, style, ms)
}
func (ms *MinSeries) ensureMinValue() {
if ms.minValue == nil {
minValue := math.MaxFloat64
var y float64
for x := 0; x < ms.InnerSeries.Len(); x++ {
_, y = ms.InnerSeries.GetValues(x)
if y < minValue {
minValue = y
}
}
ms.minValue = &minValue
}
}
// Validate validates the series.
func (ms *MinSeries) Validate() error {
if ms.InnerSeries == nil {
return fmt.Errorf("min series requires InnerSeries to be set")
}
return nil
}
// MaxSeries draws a horizontal line at the maximum value of the inner series.
type MaxSeries struct {
Name string
Style Style
YAxis YAxisType
InnerSeries ValuesProvider
maxValue *float64
}
// GetName returns the name of the time series.
func (ms MaxSeries) GetName() string {
return ms.Name
}
// GetStyle returns the line style.
func (ms MaxSeries) GetStyle() Style {
return ms.Style
}
// GetYAxis returns which YAxis the series draws on.
func (ms MaxSeries) GetYAxis() YAxisType {
return ms.YAxis
}
// Len returns the number of elements in the series.
func (ms MaxSeries) Len() int {
return ms.InnerSeries.Len()
}
// GetValues gets a value at a given index.
func (ms *MaxSeries) GetValues(index int) (x, y float64) {
ms.ensureMaxValue()
x, _ = ms.InnerSeries.GetValues(index)
y = *ms.maxValue
return
}
// Render renders the series.
func (ms *MaxSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) {
style := ms.Style.InheritFrom(defaults)
Draw.LineSeries(r, canvasBox, xrange, yrange, style, ms)
}
func (ms *MaxSeries) ensureMaxValue() {
if ms.maxValue == nil {
maxValue := -math.MaxFloat64
var y float64
for x := 0; x < ms.InnerSeries.Len(); x++ {
_, y = ms.InnerSeries.GetValues(x)
if y > maxValue {
maxValue = y
}
}
ms.maxValue = &maxValue
}
}
// Validate validates the series.
func (ms *MaxSeries) Validate() error {
if ms.InnerSeries == nil {
return fmt.Errorf("max series requires InnerSeries to be set")
}
return nil
} | vendor/github.com/wcharczuk/go-chart/v2/min_max_series.go | 0.883425 | 0.532425 | min_max_series.go | starcoder |
package orb
import (
"math"
)
var emptyBound = Bound{Min: Point{1, 1}, Max: Point{-1, -1}}
// A Bound represents a closed box or rectangle.
// To create a bound with two points you can do something like:
// orb.MultiPoint{p1, p2}.Bound()
type Bound struct {
Min, Max Point
}
// GeoJSONType returns the GeoJSON type for the object.
func (b Bound) GeoJSONType() string {
return "Polygon"
}
// Dimensions returns 2 because a Bound is a 2d object.
func (b Bound) Dimensions() int {
return 2
}
// ToPolygon converts the bound into a Polygon object.
func (b Bound) ToPolygon() Polygon {
return Polygon{b.ToRing()}
}
// ToRing converts the bound into a loop defined
// by the boundary of the box.
func (b Bound) ToRing() Ring {
return Ring{
b.Min,
Point{b.Max[0], b.Min[1]},
b.Max,
Point{b.Min[0], b.Max[1]},
b.Min,
}
}
// Extend grows the bound to include the new point.
func (b Bound) Extend(point Point) Bound {
// already included, no big deal
if b.Contains(point) {
return b
}
return Bound{
Min: Point{
math.Min(b.Min[0], point[0]),
math.Min(b.Min[1], point[1]),
},
Max: Point{
math.Max(b.Max[0], point[0]),
math.Max(b.Max[1], point[1]),
},
}
}
// Union extends this bound to contain the union of this and the given bound.
func (b Bound) Union(other Bound) Bound {
if other.IsEmpty() {
return b
}
b = b.Extend(other.Min)
b = b.Extend(other.Max)
b = b.Extend(other.LeftTop())
b = b.Extend(other.RightBottom())
return b
}
// Contains determines if the point is within the bound.
// Points on the boundary are considered within.
func (b Bound) Contains(point Point) bool {
if point[1] < b.Min[1] || b.Max[1] < point[1] {
return false
}
if point[0] < b.Min[0] || b.Max[0] < point[0] {
return false
}
return true
}
// Intersects determines if two bounds intersect.
// Returns true if they are touching.
func (b Bound) Intersects(bound Bound) bool {
if (b.Max[0] < bound.Min[0]) ||
(b.Min[0] > bound.Max[0]) ||
(b.Max[1] < bound.Min[1]) ||
(b.Min[1] > bound.Max[1]) {
return false
}
return true
}
// Pad extends the bound in all directions by the given value.
func (b Bound) Pad(d float64) Bound {
b.Min[0] -= d
b.Min[1] -= d
b.Max[0] += d
b.Max[1] += d
return b
}
// Center returns the center of the bounds by "averaging" the x and y coords.
func (b Bound) Center() Point {
return Point{
(b.Min[0] + b.Max[0]) / 2.0,
(b.Min[1] + b.Max[1]) / 2.0,
}
}
// Top returns the top of the bound.
func (b Bound) Top() float64 {
return b.Max[1]
}
// Bottom returns the bottom of the bound.
func (b Bound) Bottom() float64 {
return b.Min[1]
}
// Right returns the right of the bound.
func (b Bound) Right() float64 {
return b.Max[0]
}
// Left returns the left of the bound.
func (b Bound) Left() float64 {
return b.Min[0]
}
// LeftTop returns the upper left point of the bound.
func (b Bound) LeftTop() Point {
return Point{b.Left(), b.Top()}
}
// RightBottom return the lower right point of the bound.
func (b Bound) RightBottom() Point {
return Point{b.Right(), b.Bottom()}
}
// IsEmpty returns true if it contains zero area or if
// it's in some malformed negative state where the left point is larger than the right.
// This can be caused by padding too much negative.
func (b Bound) IsEmpty() bool {
return b.Min[0] > b.Max[0] || b.Min[1] > b.Max[1]
}
// IsZero return true if the bound just includes just null island.
func (b Bound) IsZero() bool {
return b.Max == Point{} && b.Min == Point{}
}
// Bound returns the the same bound.
func (b Bound) Bound() Bound {
return b
}
// Equal returns if two bounds are equal.
func (b Bound) Equal(c Bound) bool {
return b.Min == c.Min && b.Max == c.Max
}
// GCJ02ToWGS84 GCJ02 to WGS84.
func (b Bound) GCJ02ToWGS84() {
b.Min.GCJ02ToWGS84()
b.Max.GCJ02ToWGS84()
}
// WGS84ToGCJ02 WGS84 to GCJ02.
func (b Bound) WGS84ToGCJ02() {
b.Min.WGS84ToGCJ02()
b.Max.WGS84ToGCJ02()
}
// BD09ToWGS84 BD09 to WGS84.
func (b Bound) BD09ToWGS84() {
b.Min.BD09ToWGS84()
b.Max.BD09ToWGS84()
}
// WGS84ToBD09 WGS84 to BD09.
func (b Bound) WGS84ToBD09() {
b.Min.WGS84ToBD09()
b.Max.WGS84ToBD09()
} | bound.go | 0.892533 | 0.702505 | bound.go | starcoder |
package sqlparser
// CloneAlterOption creates a deep clone of the input.
func CloneAlterOption(in AlterOption) AlterOption {
if in == nil {
return nil
}
switch in := in.(type) {
case *AddColumns:
return CloneRefOfAddColumns(in)
case *AddConstraintDefinition:
return CloneRefOfAddConstraintDefinition(in)
case *AddIndexDefinition:
return CloneRefOfAddIndexDefinition(in)
case AlgorithmValue:
return in
case *AlterCharset:
return CloneRefOfAlterCharset(in)
case *AlterColumn:
return CloneRefOfAlterColumn(in)
case *ChangeColumn:
return CloneRefOfChangeColumn(in)
case *DropColumn:
return CloneRefOfDropColumn(in)
case *DropKey:
return CloneRefOfDropKey(in)
case *Force:
return CloneRefOfForce(in)
case *KeyState:
return CloneRefOfKeyState(in)
case *LockOption:
return CloneRefOfLockOption(in)
case *ModifyColumn:
return CloneRefOfModifyColumn(in)
case *OrderByOption:
return CloneRefOfOrderByOption(in)
case *RenameIndex:
return CloneRefOfRenameIndex(in)
case *RenameTableName:
return CloneRefOfRenameTableName(in)
case TableOptions:
return CloneTableOptions(in)
case *TablespaceOperation:
return CloneRefOfTablespaceOperation(in)
case *Validation:
return CloneRefOfValidation(in)
default:
// this should never happen
return nil
}
}
// EqualsAlterOption does deep equals between the two objects.
func EqualsAlterOption(inA, inB AlterOption) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AddColumns:
b, ok := inB.(*AddColumns)
if !ok {
return false
}
return EqualsRefOfAddColumns(a, b)
case *AddConstraintDefinition:
b, ok := inB.(*AddConstraintDefinition)
if !ok {
return false
}
return EqualsRefOfAddConstraintDefinition(a, b)
case *AddIndexDefinition:
b, ok := inB.(*AddIndexDefinition)
if !ok {
return false
}
return EqualsRefOfAddIndexDefinition(a, b)
case AlgorithmValue:
b, ok := inB.(AlgorithmValue)
if !ok {
return false
}
return a == b
case *AlterCharset:
b, ok := inB.(*AlterCharset)
if !ok {
return false
}
return EqualsRefOfAlterCharset(a, b)
case *AlterColumn:
b, ok := inB.(*AlterColumn)
if !ok {
return false
}
return EqualsRefOfAlterColumn(a, b)
case *ChangeColumn:
b, ok := inB.(*ChangeColumn)
if !ok {
return false
}
return EqualsRefOfChangeColumn(a, b)
case *DropColumn:
b, ok := inB.(*DropColumn)
if !ok {
return false
}
return EqualsRefOfDropColumn(a, b)
case *DropKey:
b, ok := inB.(*DropKey)
if !ok {
return false
}
return EqualsRefOfDropKey(a, b)
case *Force:
b, ok := inB.(*Force)
if !ok {
return false
}
return EqualsRefOfForce(a, b)
case *KeyState:
b, ok := inB.(*KeyState)
if !ok {
return false
}
return EqualsRefOfKeyState(a, b)
case *LockOption:
b, ok := inB.(*LockOption)
if !ok {
return false
}
return EqualsRefOfLockOption(a, b)
case *ModifyColumn:
b, ok := inB.(*ModifyColumn)
if !ok {
return false
}
return EqualsRefOfModifyColumn(a, b)
case *OrderByOption:
b, ok := inB.(*OrderByOption)
if !ok {
return false
}
return EqualsRefOfOrderByOption(a, b)
case *RenameIndex:
b, ok := inB.(*RenameIndex)
if !ok {
return false
}
return EqualsRefOfRenameIndex(a, b)
case *RenameTableName:
b, ok := inB.(*RenameTableName)
if !ok {
return false
}
return EqualsRefOfRenameTableName(a, b)
case TableOptions:
b, ok := inB.(TableOptions)
if !ok {
return false
}
return EqualsTableOptions(a, b)
case *TablespaceOperation:
b, ok := inB.(*TablespaceOperation)
if !ok {
return false
}
return EqualsRefOfTablespaceOperation(a, b)
case *Validation:
b, ok := inB.(*Validation)
if !ok {
return false
}
return EqualsRefOfValidation(a, b)
default:
// this should never happen
return false
}
}
// CloneCharacteristic creates a deep clone of the input.
func CloneCharacteristic(in Characteristic) Characteristic {
if in == nil {
return nil
}
switch in := in.(type) {
case AccessMode:
return in
case IsolationLevel:
return in
default:
// this should never happen
return nil
}
}
// EqualsCharacteristic does deep equals between the two objects.
func EqualsCharacteristic(inA, inB Characteristic) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case AccessMode:
b, ok := inB.(AccessMode)
if !ok {
return false
}
return a == b
case IsolationLevel:
b, ok := inB.(IsolationLevel)
if !ok {
return false
}
return a == b
default:
// this should never happen
return false
}
}
// CloneColTuple creates a deep clone of the input.
func CloneColTuple(in ColTuple) ColTuple {
if in == nil {
return nil
}
switch in := in.(type) {
case ListArg:
return CloneListArg(in)
case *Subquery:
return CloneRefOfSubquery(in)
case ValTuple:
return CloneValTuple(in)
default:
// this should never happen
return nil
}
}
// EqualsColTuple does deep equals between the two objects.
func EqualsColTuple(inA, inB ColTuple) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case ListArg:
b, ok := inB.(ListArg)
if !ok {
return false
}
return EqualsListArg(a, b)
case *Subquery:
b, ok := inB.(*Subquery)
if !ok {
return false
}
return EqualsRefOfSubquery(a, b)
case ValTuple:
b, ok := inB.(ValTuple)
if !ok {
return false
}
return EqualsValTuple(a, b)
default:
// this should never happen
return false
}
}
// CloneConstraintInfo creates a deep clone of the input.
func CloneConstraintInfo(in ConstraintInfo) ConstraintInfo {
if in == nil {
return nil
}
switch in := in.(type) {
case *CheckConstraintDefinition:
return CloneRefOfCheckConstraintDefinition(in)
case *ForeignKeyDefinition:
return CloneRefOfForeignKeyDefinition(in)
default:
// this should never happen
return nil
}
}
// EqualsConstraintInfo does deep equals between the two objects.
func EqualsConstraintInfo(inA, inB ConstraintInfo) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *CheckConstraintDefinition:
b, ok := inB.(*CheckConstraintDefinition)
if !ok {
return false
}
return EqualsRefOfCheckConstraintDefinition(a, b)
case *ForeignKeyDefinition:
b, ok := inB.(*ForeignKeyDefinition)
if !ok {
return false
}
return EqualsRefOfForeignKeyDefinition(a, b)
default:
// this should never happen
return false
}
}
// CloneDBDDLStatement creates a deep clone of the input.
func CloneDBDDLStatement(in DBDDLStatement) DBDDLStatement {
if in == nil {
return nil
}
switch in := in.(type) {
case *AlterDatabase:
return CloneRefOfAlterDatabase(in)
case *CreateDatabase:
return CloneRefOfCreateDatabase(in)
case *DropDatabase:
return CloneRefOfDropDatabase(in)
default:
// this should never happen
return nil
}
}
// EqualsDBDDLStatement does deep equals between the two objects.
func EqualsDBDDLStatement(inA, inB DBDDLStatement) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AlterDatabase:
b, ok := inB.(*AlterDatabase)
if !ok {
return false
}
return EqualsRefOfAlterDatabase(a, b)
case *CreateDatabase:
b, ok := inB.(*CreateDatabase)
if !ok {
return false
}
return EqualsRefOfCreateDatabase(a, b)
case *DropDatabase:
b, ok := inB.(*DropDatabase)
if !ok {
return false
}
return EqualsRefOfDropDatabase(a, b)
default:
// this should never happen
return false
}
}
// CloneDDLStatement creates a deep clone of the input.
func CloneDDLStatement(in DDLStatement) DDLStatement {
if in == nil {
return nil
}
switch in := in.(type) {
case *AlterTable:
return CloneRefOfAlterTable(in)
case *AlterView:
return CloneRefOfAlterView(in)
case *CreateTable:
return CloneRefOfCreateTable(in)
case *CreateView:
return CloneRefOfCreateView(in)
case *DropTable:
return CloneRefOfDropTable(in)
case *DropView:
return CloneRefOfDropView(in)
case *RenameTable:
return CloneRefOfRenameTable(in)
case *TruncateTable:
return CloneRefOfTruncateTable(in)
default:
// this should never happen
return nil
}
}
// EqualsDDLStatement does deep equals between the two objects.
func EqualsDDLStatement(inA, inB DDLStatement) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AlterTable:
b, ok := inB.(*AlterTable)
if !ok {
return false
}
return EqualsRefOfAlterTable(a, b)
case *AlterView:
b, ok := inB.(*AlterView)
if !ok {
return false
}
return EqualsRefOfAlterView(a, b)
case *CreateTable:
b, ok := inB.(*CreateTable)
if !ok {
return false
}
return EqualsRefOfCreateTable(a, b)
case *CreateView:
b, ok := inB.(*CreateView)
if !ok {
return false
}
return EqualsRefOfCreateView(a, b)
case *DropTable:
b, ok := inB.(*DropTable)
if !ok {
return false
}
return EqualsRefOfDropTable(a, b)
case *DropView:
b, ok := inB.(*DropView)
if !ok {
return false
}
return EqualsRefOfDropView(a, b)
case *RenameTable:
b, ok := inB.(*RenameTable)
if !ok {
return false
}
return EqualsRefOfRenameTable(a, b)
case *TruncateTable:
b, ok := inB.(*TruncateTable)
if !ok {
return false
}
return EqualsRefOfTruncateTable(a, b)
default:
// this should never happen
return false
}
}
// CloneExplain creates a deep clone of the input.
func CloneExplain(in Explain) Explain {
if in == nil {
return nil
}
switch in := in.(type) {
case *ExplainStmt:
return CloneRefOfExplainStmt(in)
case *ExplainTab:
return CloneRefOfExplainTab(in)
default:
// this should never happen
return nil
}
}
// EqualsExplain does deep equals between the two objects.
func EqualsExplain(inA, inB Explain) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *ExplainStmt:
b, ok := inB.(*ExplainStmt)
if !ok {
return false
}
return EqualsRefOfExplainStmt(a, b)
case *ExplainTab:
b, ok := inB.(*ExplainTab)
if !ok {
return false
}
return EqualsRefOfExplainTab(a, b)
default:
// this should never happen
return false
}
}
// CloneExpr creates a deep clone of the input.
func CloneExpr(in Expr) Expr {
if in == nil {
return nil
}
switch in := in.(type) {
case *AndExpr:
return CloneRefOfAndExpr(in)
case Argument:
return in
case *BinaryExpr:
return CloneRefOfBinaryExpr(in)
case BoolVal:
return in
case *CaseExpr:
return CloneRefOfCaseExpr(in)
case *ColName:
return CloneRefOfColName(in)
case *CollateExpr:
return CloneRefOfCollateExpr(in)
case *ComparisonExpr:
return CloneRefOfComparisonExpr(in)
case *ConvertExpr:
return CloneRefOfConvertExpr(in)
case *ConvertUsingExpr:
return CloneRefOfConvertUsingExpr(in)
case *CurTimeFuncExpr:
return CloneRefOfCurTimeFuncExpr(in)
case *Default:
return CloneRefOfDefault(in)
case *ExistsExpr:
return CloneRefOfExistsExpr(in)
case *FuncExpr:
return CloneRefOfFuncExpr(in)
case *GroupConcatExpr:
return CloneRefOfGroupConcatExpr(in)
case *IntervalExpr:
return CloneRefOfIntervalExpr(in)
case *IsExpr:
return CloneRefOfIsExpr(in)
case ListArg:
return CloneListArg(in)
case *Literal:
return CloneRefOfLiteral(in)
case *MatchExpr:
return CloneRefOfMatchExpr(in)
case *NotExpr:
return CloneRefOfNotExpr(in)
case *NullVal:
return CloneRefOfNullVal(in)
case *OrExpr:
return CloneRefOfOrExpr(in)
case *RangeCond:
return CloneRefOfRangeCond(in)
case *Subquery:
return CloneRefOfSubquery(in)
case *SubstrExpr:
return CloneRefOfSubstrExpr(in)
case *TimestampFuncExpr:
return CloneRefOfTimestampFuncExpr(in)
case *UnaryExpr:
return CloneRefOfUnaryExpr(in)
case ValTuple:
return CloneValTuple(in)
case *ValuesFuncExpr:
return CloneRefOfValuesFuncExpr(in)
case *XorExpr:
return CloneRefOfXorExpr(in)
default:
// this should never happen
return nil
}
}
// EqualsExpr does deep equals between the two objects.
func EqualsExpr(inA, inB Expr) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AndExpr:
b, ok := inB.(*AndExpr)
if !ok {
return false
}
return EqualsRefOfAndExpr(a, b)
case Argument:
b, ok := inB.(Argument)
if !ok {
return false
}
return a == b
case *BinaryExpr:
b, ok := inB.(*BinaryExpr)
if !ok {
return false
}
return EqualsRefOfBinaryExpr(a, b)
case BoolVal:
b, ok := inB.(BoolVal)
if !ok {
return false
}
return a == b
case *CaseExpr:
b, ok := inB.(*CaseExpr)
if !ok {
return false
}
return EqualsRefOfCaseExpr(a, b)
case *ColName:
b, ok := inB.(*ColName)
if !ok {
return false
}
return EqualsRefOfColName(a, b)
case *CollateExpr:
b, ok := inB.(*CollateExpr)
if !ok {
return false
}
return EqualsRefOfCollateExpr(a, b)
case *ComparisonExpr:
b, ok := inB.(*ComparisonExpr)
if !ok {
return false
}
return EqualsRefOfComparisonExpr(a, b)
case *ConvertExpr:
b, ok := inB.(*ConvertExpr)
if !ok {
return false
}
return EqualsRefOfConvertExpr(a, b)
case *ConvertUsingExpr:
b, ok := inB.(*ConvertUsingExpr)
if !ok {
return false
}
return EqualsRefOfConvertUsingExpr(a, b)
case *CurTimeFuncExpr:
b, ok := inB.(*CurTimeFuncExpr)
if !ok {
return false
}
return EqualsRefOfCurTimeFuncExpr(a, b)
case *Default:
b, ok := inB.(*Default)
if !ok {
return false
}
return EqualsRefOfDefault(a, b)
case *ExistsExpr:
b, ok := inB.(*ExistsExpr)
if !ok {
return false
}
return EqualsRefOfExistsExpr(a, b)
case *FuncExpr:
b, ok := inB.(*FuncExpr)
if !ok {
return false
}
return EqualsRefOfFuncExpr(a, b)
case *GroupConcatExpr:
b, ok := inB.(*GroupConcatExpr)
if !ok {
return false
}
return EqualsRefOfGroupConcatExpr(a, b)
case *IntervalExpr:
b, ok := inB.(*IntervalExpr)
if !ok {
return false
}
return EqualsRefOfIntervalExpr(a, b)
case *IsExpr:
b, ok := inB.(*IsExpr)
if !ok {
return false
}
return EqualsRefOfIsExpr(a, b)
case ListArg:
b, ok := inB.(ListArg)
if !ok {
return false
}
return EqualsListArg(a, b)
case *Literal:
b, ok := inB.(*Literal)
if !ok {
return false
}
return EqualsRefOfLiteral(a, b)
case *MatchExpr:
b, ok := inB.(*MatchExpr)
if !ok {
return false
}
return EqualsRefOfMatchExpr(a, b)
case *NotExpr:
b, ok := inB.(*NotExpr)
if !ok {
return false
}
return EqualsRefOfNotExpr(a, b)
case *NullVal:
b, ok := inB.(*NullVal)
if !ok {
return false
}
return EqualsRefOfNullVal(a, b)
case *OrExpr:
b, ok := inB.(*OrExpr)
if !ok {
return false
}
return EqualsRefOfOrExpr(a, b)
case *RangeCond:
b, ok := inB.(*RangeCond)
if !ok {
return false
}
return EqualsRefOfRangeCond(a, b)
case *Subquery:
b, ok := inB.(*Subquery)
if !ok {
return false
}
return EqualsRefOfSubquery(a, b)
case *SubstrExpr:
b, ok := inB.(*SubstrExpr)
if !ok {
return false
}
return EqualsRefOfSubstrExpr(a, b)
case *TimestampFuncExpr:
b, ok := inB.(*TimestampFuncExpr)
if !ok {
return false
}
return EqualsRefOfTimestampFuncExpr(a, b)
case *UnaryExpr:
b, ok := inB.(*UnaryExpr)
if !ok {
return false
}
return EqualsRefOfUnaryExpr(a, b)
case ValTuple:
b, ok := inB.(ValTuple)
if !ok {
return false
}
return EqualsValTuple(a, b)
case *ValuesFuncExpr:
b, ok := inB.(*ValuesFuncExpr)
if !ok {
return false
}
return EqualsRefOfValuesFuncExpr(a, b)
case *XorExpr:
b, ok := inB.(*XorExpr)
if !ok {
return false
}
return EqualsRefOfXorExpr(a, b)
default:
// this should never happen
return false
}
}
// CloneInsertRows creates a deep clone of the input.
func CloneInsertRows(in InsertRows) InsertRows {
if in == nil {
return nil
}
switch in := in.(type) {
case *ParenSelect:
return CloneRefOfParenSelect(in)
case *Select:
return CloneRefOfSelect(in)
case *Union:
return CloneRefOfUnion(in)
case Values:
return CloneValues(in)
default:
// this should never happen
return nil
}
}
// EqualsInsertRows does deep equals between the two objects.
func EqualsInsertRows(inA, inB InsertRows) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *ParenSelect:
b, ok := inB.(*ParenSelect)
if !ok {
return false
}
return EqualsRefOfParenSelect(a, b)
case *Select:
b, ok := inB.(*Select)
if !ok {
return false
}
return EqualsRefOfSelect(a, b)
case *Union:
b, ok := inB.(*Union)
if !ok {
return false
}
return EqualsRefOfUnion(a, b)
case Values:
b, ok := inB.(Values)
if !ok {
return false
}
return EqualsValues(a, b)
default:
// this should never happen
return false
}
}
// CloneSQLNode creates a deep clone of the input.
func CloneSQLNode(in SQLNode) SQLNode {
if in == nil {
return nil
}
switch in := in.(type) {
case AccessMode:
return in
case *AddColumns:
return CloneRefOfAddColumns(in)
case *AddConstraintDefinition:
return CloneRefOfAddConstraintDefinition(in)
case *AddIndexDefinition:
return CloneRefOfAddIndexDefinition(in)
case AlgorithmValue:
return in
case *AliasedExpr:
return CloneRefOfAliasedExpr(in)
case *AliasedTableExpr:
return CloneRefOfAliasedTableExpr(in)
case *AlterCharset:
return CloneRefOfAlterCharset(in)
case *AlterColumn:
return CloneRefOfAlterColumn(in)
case *AlterDatabase:
return CloneRefOfAlterDatabase(in)
case *AlterTable:
return CloneRefOfAlterTable(in)
case *AlterView:
return CloneRefOfAlterView(in)
case *AlterVschema:
return CloneRefOfAlterVschema(in)
case *AndExpr:
return CloneRefOfAndExpr(in)
case Argument:
return in
case *AutoIncSpec:
return CloneRefOfAutoIncSpec(in)
case *Begin:
return CloneRefOfBegin(in)
case *BinaryExpr:
return CloneRefOfBinaryExpr(in)
case BoolVal:
return in
case *CallProc:
return CloneRefOfCallProc(in)
case *CaseExpr:
return CloneRefOfCaseExpr(in)
case *ChangeColumn:
return CloneRefOfChangeColumn(in)
case *CheckConstraintDefinition:
return CloneRefOfCheckConstraintDefinition(in)
case ColIdent:
return CloneColIdent(in)
case *ColName:
return CloneRefOfColName(in)
case *CollateExpr:
return CloneRefOfCollateExpr(in)
case *ColumnDefinition:
return CloneRefOfColumnDefinition(in)
case *ColumnType:
return CloneRefOfColumnType(in)
case Columns:
return CloneColumns(in)
case Comments:
return CloneComments(in)
case *Commit:
return CloneRefOfCommit(in)
case *ComparisonExpr:
return CloneRefOfComparisonExpr(in)
case *ConstraintDefinition:
return CloneRefOfConstraintDefinition(in)
case *ConvertExpr:
return CloneRefOfConvertExpr(in)
case *ConvertType:
return CloneRefOfConvertType(in)
case *ConvertUsingExpr:
return CloneRefOfConvertUsingExpr(in)
case *CreateDatabase:
return CloneRefOfCreateDatabase(in)
case *CreateTable:
return CloneRefOfCreateTable(in)
case *CreateView:
return CloneRefOfCreateView(in)
case *CurTimeFuncExpr:
return CloneRefOfCurTimeFuncExpr(in)
case *Default:
return CloneRefOfDefault(in)
case *Delete:
return CloneRefOfDelete(in)
case *DerivedTable:
return CloneRefOfDerivedTable(in)
case *DropColumn:
return CloneRefOfDropColumn(in)
case *DropDatabase:
return CloneRefOfDropDatabase(in)
case *DropKey:
return CloneRefOfDropKey(in)
case *DropTable:
return CloneRefOfDropTable(in)
case *DropView:
return CloneRefOfDropView(in)
case *ExistsExpr:
return CloneRefOfExistsExpr(in)
case *ExplainStmt:
return CloneRefOfExplainStmt(in)
case *ExplainTab:
return CloneRefOfExplainTab(in)
case Exprs:
return CloneExprs(in)
case *Flush:
return CloneRefOfFlush(in)
case *Force:
return CloneRefOfForce(in)
case *ForeignKeyDefinition:
return CloneRefOfForeignKeyDefinition(in)
case *FuncExpr:
return CloneRefOfFuncExpr(in)
case GroupBy:
return CloneGroupBy(in)
case *GroupConcatExpr:
return CloneRefOfGroupConcatExpr(in)
case *IndexDefinition:
return CloneRefOfIndexDefinition(in)
case *IndexHints:
return CloneRefOfIndexHints(in)
case *IndexInfo:
return CloneRefOfIndexInfo(in)
case *Insert:
return CloneRefOfInsert(in)
case *IntervalExpr:
return CloneRefOfIntervalExpr(in)
case *IsExpr:
return CloneRefOfIsExpr(in)
case IsolationLevel:
return in
case JoinCondition:
return CloneJoinCondition(in)
case *JoinTableExpr:
return CloneRefOfJoinTableExpr(in)
case *KeyState:
return CloneRefOfKeyState(in)
case *Limit:
return CloneRefOfLimit(in)
case ListArg:
return CloneListArg(in)
case *Literal:
return CloneRefOfLiteral(in)
case *Load:
return CloneRefOfLoad(in)
case *LockOption:
return CloneRefOfLockOption(in)
case *LockTables:
return CloneRefOfLockTables(in)
case *MatchExpr:
return CloneRefOfMatchExpr(in)
case *ModifyColumn:
return CloneRefOfModifyColumn(in)
case *Nextval:
return CloneRefOfNextval(in)
case *NotExpr:
return CloneRefOfNotExpr(in)
case *NullVal:
return CloneRefOfNullVal(in)
case OnDup:
return CloneOnDup(in)
case *OptLike:
return CloneRefOfOptLike(in)
case *OrExpr:
return CloneRefOfOrExpr(in)
case *Order:
return CloneRefOfOrder(in)
case OrderBy:
return CloneOrderBy(in)
case *OrderByOption:
return CloneRefOfOrderByOption(in)
case *OtherAdmin:
return CloneRefOfOtherAdmin(in)
case *OtherRead:
return CloneRefOfOtherRead(in)
case *ParenSelect:
return CloneRefOfParenSelect(in)
case *ParenTableExpr:
return CloneRefOfParenTableExpr(in)
case *PartitionDefinition:
return CloneRefOfPartitionDefinition(in)
case *PartitionSpec:
return CloneRefOfPartitionSpec(in)
case Partitions:
return ClonePartitions(in)
case *RangeCond:
return CloneRefOfRangeCond(in)
case ReferenceAction:
return in
case *Release:
return CloneRefOfRelease(in)
case *RenameIndex:
return CloneRefOfRenameIndex(in)
case *RenameTable:
return CloneRefOfRenameTable(in)
case *RenameTableName:
return CloneRefOfRenameTableName(in)
case *Rollback:
return CloneRefOfRollback(in)
case *SRollback:
return CloneRefOfSRollback(in)
case *Savepoint:
return CloneRefOfSavepoint(in)
case *Select:
return CloneRefOfSelect(in)
case SelectExprs:
return CloneSelectExprs(in)
case *SelectInto:
return CloneRefOfSelectInto(in)
case *Set:
return CloneRefOfSet(in)
case *SetExpr:
return CloneRefOfSetExpr(in)
case SetExprs:
return CloneSetExprs(in)
case *SetTransaction:
return CloneRefOfSetTransaction(in)
case *Show:
return CloneRefOfShow(in)
case *ShowBasic:
return CloneRefOfShowBasic(in)
case *ShowCreate:
return CloneRefOfShowCreate(in)
case *ShowFilter:
return CloneRefOfShowFilter(in)
case *ShowLegacy:
return CloneRefOfShowLegacy(in)
case *StarExpr:
return CloneRefOfStarExpr(in)
case *Stream:
return CloneRefOfStream(in)
case *Subquery:
return CloneRefOfSubquery(in)
case *SubstrExpr:
return CloneRefOfSubstrExpr(in)
case TableExprs:
return CloneTableExprs(in)
case TableIdent:
return CloneTableIdent(in)
case TableName:
return CloneTableName(in)
case TableNames:
return CloneTableNames(in)
case TableOptions:
return CloneTableOptions(in)
case *TableSpec:
return CloneRefOfTableSpec(in)
case *TablespaceOperation:
return CloneRefOfTablespaceOperation(in)
case *TimestampFuncExpr:
return CloneRefOfTimestampFuncExpr(in)
case *TruncateTable:
return CloneRefOfTruncateTable(in)
case *UnaryExpr:
return CloneRefOfUnaryExpr(in)
case *Union:
return CloneRefOfUnion(in)
case *UnionSelect:
return CloneRefOfUnionSelect(in)
case *UnlockTables:
return CloneRefOfUnlockTables(in)
case *Update:
return CloneRefOfUpdate(in)
case *UpdateExpr:
return CloneRefOfUpdateExpr(in)
case UpdateExprs:
return CloneUpdateExprs(in)
case *Use:
return CloneRefOfUse(in)
case *VStream:
return CloneRefOfVStream(in)
case ValTuple:
return CloneValTuple(in)
case *Validation:
return CloneRefOfValidation(in)
case Values:
return CloneValues(in)
case *ValuesFuncExpr:
return CloneRefOfValuesFuncExpr(in)
case VindexParam:
return CloneVindexParam(in)
case *VindexSpec:
return CloneRefOfVindexSpec(in)
case *When:
return CloneRefOfWhen(in)
case *Where:
return CloneRefOfWhere(in)
case *XorExpr:
return CloneRefOfXorExpr(in)
default:
// this should never happen
return nil
}
}
// EqualsSQLNode does deep equals between the two objects.
func EqualsSQLNode(inA, inB SQLNode) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case AccessMode:
b, ok := inB.(AccessMode)
if !ok {
return false
}
return a == b
case *AddColumns:
b, ok := inB.(*AddColumns)
if !ok {
return false
}
return EqualsRefOfAddColumns(a, b)
case *AddConstraintDefinition:
b, ok := inB.(*AddConstraintDefinition)
if !ok {
return false
}
return EqualsRefOfAddConstraintDefinition(a, b)
case *AddIndexDefinition:
b, ok := inB.(*AddIndexDefinition)
if !ok {
return false
}
return EqualsRefOfAddIndexDefinition(a, b)
case AlgorithmValue:
b, ok := inB.(AlgorithmValue)
if !ok {
return false
}
return a == b
case *AliasedExpr:
b, ok := inB.(*AliasedExpr)
if !ok {
return false
}
return EqualsRefOfAliasedExpr(a, b)
case *AliasedTableExpr:
b, ok := inB.(*AliasedTableExpr)
if !ok {
return false
}
return EqualsRefOfAliasedTableExpr(a, b)
case *AlterCharset:
b, ok := inB.(*AlterCharset)
if !ok {
return false
}
return EqualsRefOfAlterCharset(a, b)
case *AlterColumn:
b, ok := inB.(*AlterColumn)
if !ok {
return false
}
return EqualsRefOfAlterColumn(a, b)
case *AlterDatabase:
b, ok := inB.(*AlterDatabase)
if !ok {
return false
}
return EqualsRefOfAlterDatabase(a, b)
case *AlterTable:
b, ok := inB.(*AlterTable)
if !ok {
return false
}
return EqualsRefOfAlterTable(a, b)
case *AlterView:
b, ok := inB.(*AlterView)
if !ok {
return false
}
return EqualsRefOfAlterView(a, b)
case *AlterVschema:
b, ok := inB.(*AlterVschema)
if !ok {
return false
}
return EqualsRefOfAlterVschema(a, b)
case *AndExpr:
b, ok := inB.(*AndExpr)
if !ok {
return false
}
return EqualsRefOfAndExpr(a, b)
case Argument:
b, ok := inB.(Argument)
if !ok {
return false
}
return a == b
case *AutoIncSpec:
b, ok := inB.(*AutoIncSpec)
if !ok {
return false
}
return EqualsRefOfAutoIncSpec(a, b)
case *Begin:
b, ok := inB.(*Begin)
if !ok {
return false
}
return EqualsRefOfBegin(a, b)
case *BinaryExpr:
b, ok := inB.(*BinaryExpr)
if !ok {
return false
}
return EqualsRefOfBinaryExpr(a, b)
case BoolVal:
b, ok := inB.(BoolVal)
if !ok {
return false
}
return a == b
case *CallProc:
b, ok := inB.(*CallProc)
if !ok {
return false
}
return EqualsRefOfCallProc(a, b)
case *CaseExpr:
b, ok := inB.(*CaseExpr)
if !ok {
return false
}
return EqualsRefOfCaseExpr(a, b)
case *ChangeColumn:
b, ok := inB.(*ChangeColumn)
if !ok {
return false
}
return EqualsRefOfChangeColumn(a, b)
case *CheckConstraintDefinition:
b, ok := inB.(*CheckConstraintDefinition)
if !ok {
return false
}
return EqualsRefOfCheckConstraintDefinition(a, b)
case ColIdent:
b, ok := inB.(ColIdent)
if !ok {
return false
}
return EqualsColIdent(a, b)
case *ColName:
b, ok := inB.(*ColName)
if !ok {
return false
}
return EqualsRefOfColName(a, b)
case *CollateExpr:
b, ok := inB.(*CollateExpr)
if !ok {
return false
}
return EqualsRefOfCollateExpr(a, b)
case *ColumnDefinition:
b, ok := inB.(*ColumnDefinition)
if !ok {
return false
}
return EqualsRefOfColumnDefinition(a, b)
case *ColumnType:
b, ok := inB.(*ColumnType)
if !ok {
return false
}
return EqualsRefOfColumnType(a, b)
case Columns:
b, ok := inB.(Columns)
if !ok {
return false
}
return EqualsColumns(a, b)
case Comments:
b, ok := inB.(Comments)
if !ok {
return false
}
return EqualsComments(a, b)
case *Commit:
b, ok := inB.(*Commit)
if !ok {
return false
}
return EqualsRefOfCommit(a, b)
case *ComparisonExpr:
b, ok := inB.(*ComparisonExpr)
if !ok {
return false
}
return EqualsRefOfComparisonExpr(a, b)
case *ConstraintDefinition:
b, ok := inB.(*ConstraintDefinition)
if !ok {
return false
}
return EqualsRefOfConstraintDefinition(a, b)
case *ConvertExpr:
b, ok := inB.(*ConvertExpr)
if !ok {
return false
}
return EqualsRefOfConvertExpr(a, b)
case *ConvertType:
b, ok := inB.(*ConvertType)
if !ok {
return false
}
return EqualsRefOfConvertType(a, b)
case *ConvertUsingExpr:
b, ok := inB.(*ConvertUsingExpr)
if !ok {
return false
}
return EqualsRefOfConvertUsingExpr(a, b)
case *CreateDatabase:
b, ok := inB.(*CreateDatabase)
if !ok {
return false
}
return EqualsRefOfCreateDatabase(a, b)
case *CreateTable:
b, ok := inB.(*CreateTable)
if !ok {
return false
}
return EqualsRefOfCreateTable(a, b)
case *CreateView:
b, ok := inB.(*CreateView)
if !ok {
return false
}
return EqualsRefOfCreateView(a, b)
case *CurTimeFuncExpr:
b, ok := inB.(*CurTimeFuncExpr)
if !ok {
return false
}
return EqualsRefOfCurTimeFuncExpr(a, b)
case *Default:
b, ok := inB.(*Default)
if !ok {
return false
}
return EqualsRefOfDefault(a, b)
case *Delete:
b, ok := inB.(*Delete)
if !ok {
return false
}
return EqualsRefOfDelete(a, b)
case *DerivedTable:
b, ok := inB.(*DerivedTable)
if !ok {
return false
}
return EqualsRefOfDerivedTable(a, b)
case *DropColumn:
b, ok := inB.(*DropColumn)
if !ok {
return false
}
return EqualsRefOfDropColumn(a, b)
case *DropDatabase:
b, ok := inB.(*DropDatabase)
if !ok {
return false
}
return EqualsRefOfDropDatabase(a, b)
case *DropKey:
b, ok := inB.(*DropKey)
if !ok {
return false
}
return EqualsRefOfDropKey(a, b)
case *DropTable:
b, ok := inB.(*DropTable)
if !ok {
return false
}
return EqualsRefOfDropTable(a, b)
case *DropView:
b, ok := inB.(*DropView)
if !ok {
return false
}
return EqualsRefOfDropView(a, b)
case *ExistsExpr:
b, ok := inB.(*ExistsExpr)
if !ok {
return false
}
return EqualsRefOfExistsExpr(a, b)
case *ExplainStmt:
b, ok := inB.(*ExplainStmt)
if !ok {
return false
}
return EqualsRefOfExplainStmt(a, b)
case *ExplainTab:
b, ok := inB.(*ExplainTab)
if !ok {
return false
}
return EqualsRefOfExplainTab(a, b)
case Exprs:
b, ok := inB.(Exprs)
if !ok {
return false
}
return EqualsExprs(a, b)
case *Flush:
b, ok := inB.(*Flush)
if !ok {
return false
}
return EqualsRefOfFlush(a, b)
case *Force:
b, ok := inB.(*Force)
if !ok {
return false
}
return EqualsRefOfForce(a, b)
case *ForeignKeyDefinition:
b, ok := inB.(*ForeignKeyDefinition)
if !ok {
return false
}
return EqualsRefOfForeignKeyDefinition(a, b)
case *FuncExpr:
b, ok := inB.(*FuncExpr)
if !ok {
return false
}
return EqualsRefOfFuncExpr(a, b)
case GroupBy:
b, ok := inB.(GroupBy)
if !ok {
return false
}
return EqualsGroupBy(a, b)
case *GroupConcatExpr:
b, ok := inB.(*GroupConcatExpr)
if !ok {
return false
}
return EqualsRefOfGroupConcatExpr(a, b)
case *IndexDefinition:
b, ok := inB.(*IndexDefinition)
if !ok {
return false
}
return EqualsRefOfIndexDefinition(a, b)
case *IndexHints:
b, ok := inB.(*IndexHints)
if !ok {
return false
}
return EqualsRefOfIndexHints(a, b)
case *IndexInfo:
b, ok := inB.(*IndexInfo)
if !ok {
return false
}
return EqualsRefOfIndexInfo(a, b)
case *Insert:
b, ok := inB.(*Insert)
if !ok {
return false
}
return EqualsRefOfInsert(a, b)
case *IntervalExpr:
b, ok := inB.(*IntervalExpr)
if !ok {
return false
}
return EqualsRefOfIntervalExpr(a, b)
case *IsExpr:
b, ok := inB.(*IsExpr)
if !ok {
return false
}
return EqualsRefOfIsExpr(a, b)
case IsolationLevel:
b, ok := inB.(IsolationLevel)
if !ok {
return false
}
return a == b
case JoinCondition:
b, ok := inB.(JoinCondition)
if !ok {
return false
}
return EqualsJoinCondition(a, b)
case *JoinTableExpr:
b, ok := inB.(*JoinTableExpr)
if !ok {
return false
}
return EqualsRefOfJoinTableExpr(a, b)
case *KeyState:
b, ok := inB.(*KeyState)
if !ok {
return false
}
return EqualsRefOfKeyState(a, b)
case *Limit:
b, ok := inB.(*Limit)
if !ok {
return false
}
return EqualsRefOfLimit(a, b)
case ListArg:
b, ok := inB.(ListArg)
if !ok {
return false
}
return EqualsListArg(a, b)
case *Literal:
b, ok := inB.(*Literal)
if !ok {
return false
}
return EqualsRefOfLiteral(a, b)
case *Load:
b, ok := inB.(*Load)
if !ok {
return false
}
return EqualsRefOfLoad(a, b)
case *LockOption:
b, ok := inB.(*LockOption)
if !ok {
return false
}
return EqualsRefOfLockOption(a, b)
case *LockTables:
b, ok := inB.(*LockTables)
if !ok {
return false
}
return EqualsRefOfLockTables(a, b)
case *MatchExpr:
b, ok := inB.(*MatchExpr)
if !ok {
return false
}
return EqualsRefOfMatchExpr(a, b)
case *ModifyColumn:
b, ok := inB.(*ModifyColumn)
if !ok {
return false
}
return EqualsRefOfModifyColumn(a, b)
case *Nextval:
b, ok := inB.(*Nextval)
if !ok {
return false
}
return EqualsRefOfNextval(a, b)
case *NotExpr:
b, ok := inB.(*NotExpr)
if !ok {
return false
}
return EqualsRefOfNotExpr(a, b)
case *NullVal:
b, ok := inB.(*NullVal)
if !ok {
return false
}
return EqualsRefOfNullVal(a, b)
case OnDup:
b, ok := inB.(OnDup)
if !ok {
return false
}
return EqualsOnDup(a, b)
case *OptLike:
b, ok := inB.(*OptLike)
if !ok {
return false
}
return EqualsRefOfOptLike(a, b)
case *OrExpr:
b, ok := inB.(*OrExpr)
if !ok {
return false
}
return EqualsRefOfOrExpr(a, b)
case *Order:
b, ok := inB.(*Order)
if !ok {
return false
}
return EqualsRefOfOrder(a, b)
case OrderBy:
b, ok := inB.(OrderBy)
if !ok {
return false
}
return EqualsOrderBy(a, b)
case *OrderByOption:
b, ok := inB.(*OrderByOption)
if !ok {
return false
}
return EqualsRefOfOrderByOption(a, b)
case *OtherAdmin:
b, ok := inB.(*OtherAdmin)
if !ok {
return false
}
return EqualsRefOfOtherAdmin(a, b)
case *OtherRead:
b, ok := inB.(*OtherRead)
if !ok {
return false
}
return EqualsRefOfOtherRead(a, b)
case *ParenSelect:
b, ok := inB.(*ParenSelect)
if !ok {
return false
}
return EqualsRefOfParenSelect(a, b)
case *ParenTableExpr:
b, ok := inB.(*ParenTableExpr)
if !ok {
return false
}
return EqualsRefOfParenTableExpr(a, b)
case *PartitionDefinition:
b, ok := inB.(*PartitionDefinition)
if !ok {
return false
}
return EqualsRefOfPartitionDefinition(a, b)
case *PartitionSpec:
b, ok := inB.(*PartitionSpec)
if !ok {
return false
}
return EqualsRefOfPartitionSpec(a, b)
case Partitions:
b, ok := inB.(Partitions)
if !ok {
return false
}
return EqualsPartitions(a, b)
case *RangeCond:
b, ok := inB.(*RangeCond)
if !ok {
return false
}
return EqualsRefOfRangeCond(a, b)
case ReferenceAction:
b, ok := inB.(ReferenceAction)
if !ok {
return false
}
return a == b
case *Release:
b, ok := inB.(*Release)
if !ok {
return false
}
return EqualsRefOfRelease(a, b)
case *RenameIndex:
b, ok := inB.(*RenameIndex)
if !ok {
return false
}
return EqualsRefOfRenameIndex(a, b)
case *RenameTable:
b, ok := inB.(*RenameTable)
if !ok {
return false
}
return EqualsRefOfRenameTable(a, b)
case *RenameTableName:
b, ok := inB.(*RenameTableName)
if !ok {
return false
}
return EqualsRefOfRenameTableName(a, b)
case *Rollback:
b, ok := inB.(*Rollback)
if !ok {
return false
}
return EqualsRefOfRollback(a, b)
case *SRollback:
b, ok := inB.(*SRollback)
if !ok {
return false
}
return EqualsRefOfSRollback(a, b)
case *Savepoint:
b, ok := inB.(*Savepoint)
if !ok {
return false
}
return EqualsRefOfSavepoint(a, b)
case *Select:
b, ok := inB.(*Select)
if !ok {
return false
}
return EqualsRefOfSelect(a, b)
case SelectExprs:
b, ok := inB.(SelectExprs)
if !ok {
return false
}
return EqualsSelectExprs(a, b)
case *SelectInto:
b, ok := inB.(*SelectInto)
if !ok {
return false
}
return EqualsRefOfSelectInto(a, b)
case *Set:
b, ok := inB.(*Set)
if !ok {
return false
}
return EqualsRefOfSet(a, b)
case *SetExpr:
b, ok := inB.(*SetExpr)
if !ok {
return false
}
return EqualsRefOfSetExpr(a, b)
case SetExprs:
b, ok := inB.(SetExprs)
if !ok {
return false
}
return EqualsSetExprs(a, b)
case *SetTransaction:
b, ok := inB.(*SetTransaction)
if !ok {
return false
}
return EqualsRefOfSetTransaction(a, b)
case *Show:
b, ok := inB.(*Show)
if !ok {
return false
}
return EqualsRefOfShow(a, b)
case *ShowBasic:
b, ok := inB.(*ShowBasic)
if !ok {
return false
}
return EqualsRefOfShowBasic(a, b)
case *ShowCreate:
b, ok := inB.(*ShowCreate)
if !ok {
return false
}
return EqualsRefOfShowCreate(a, b)
case *ShowFilter:
b, ok := inB.(*ShowFilter)
if !ok {
return false
}
return EqualsRefOfShowFilter(a, b)
case *ShowLegacy:
b, ok := inB.(*ShowLegacy)
if !ok {
return false
}
return EqualsRefOfShowLegacy(a, b)
case *StarExpr:
b, ok := inB.(*StarExpr)
if !ok {
return false
}
return EqualsRefOfStarExpr(a, b)
case *Stream:
b, ok := inB.(*Stream)
if !ok {
return false
}
return EqualsRefOfStream(a, b)
case *Subquery:
b, ok := inB.(*Subquery)
if !ok {
return false
}
return EqualsRefOfSubquery(a, b)
case *SubstrExpr:
b, ok := inB.(*SubstrExpr)
if !ok {
return false
}
return EqualsRefOfSubstrExpr(a, b)
case TableExprs:
b, ok := inB.(TableExprs)
if !ok {
return false
}
return EqualsTableExprs(a, b)
case TableIdent:
b, ok := inB.(TableIdent)
if !ok {
return false
}
return EqualsTableIdent(a, b)
case TableName:
b, ok := inB.(TableName)
if !ok {
return false
}
return EqualsTableName(a, b)
case TableNames:
b, ok := inB.(TableNames)
if !ok {
return false
}
return EqualsTableNames(a, b)
case TableOptions:
b, ok := inB.(TableOptions)
if !ok {
return false
}
return EqualsTableOptions(a, b)
case *TableSpec:
b, ok := inB.(*TableSpec)
if !ok {
return false
}
return EqualsRefOfTableSpec(a, b)
case *TablespaceOperation:
b, ok := inB.(*TablespaceOperation)
if !ok {
return false
}
return EqualsRefOfTablespaceOperation(a, b)
case *TimestampFuncExpr:
b, ok := inB.(*TimestampFuncExpr)
if !ok {
return false
}
return EqualsRefOfTimestampFuncExpr(a, b)
case *TruncateTable:
b, ok := inB.(*TruncateTable)
if !ok {
return false
}
return EqualsRefOfTruncateTable(a, b)
case *UnaryExpr:
b, ok := inB.(*UnaryExpr)
if !ok {
return false
}
return EqualsRefOfUnaryExpr(a, b)
case *Union:
b, ok := inB.(*Union)
if !ok {
return false
}
return EqualsRefOfUnion(a, b)
case *UnionSelect:
b, ok := inB.(*UnionSelect)
if !ok {
return false
}
return EqualsRefOfUnionSelect(a, b)
case *UnlockTables:
b, ok := inB.(*UnlockTables)
if !ok {
return false
}
return EqualsRefOfUnlockTables(a, b)
case *Update:
b, ok := inB.(*Update)
if !ok {
return false
}
return EqualsRefOfUpdate(a, b)
case *UpdateExpr:
b, ok := inB.(*UpdateExpr)
if !ok {
return false
}
return EqualsRefOfUpdateExpr(a, b)
case UpdateExprs:
b, ok := inB.(UpdateExprs)
if !ok {
return false
}
return EqualsUpdateExprs(a, b)
case *Use:
b, ok := inB.(*Use)
if !ok {
return false
}
return EqualsRefOfUse(a, b)
case *VStream:
b, ok := inB.(*VStream)
if !ok {
return false
}
return EqualsRefOfVStream(a, b)
case ValTuple:
b, ok := inB.(ValTuple)
if !ok {
return false
}
return EqualsValTuple(a, b)
case *Validation:
b, ok := inB.(*Validation)
if !ok {
return false
}
return EqualsRefOfValidation(a, b)
case Values:
b, ok := inB.(Values)
if !ok {
return false
}
return EqualsValues(a, b)
case *ValuesFuncExpr:
b, ok := inB.(*ValuesFuncExpr)
if !ok {
return false
}
return EqualsRefOfValuesFuncExpr(a, b)
case VindexParam:
b, ok := inB.(VindexParam)
if !ok {
return false
}
return EqualsVindexParam(a, b)
case *VindexSpec:
b, ok := inB.(*VindexSpec)
if !ok {
return false
}
return EqualsRefOfVindexSpec(a, b)
case *When:
b, ok := inB.(*When)
if !ok {
return false
}
return EqualsRefOfWhen(a, b)
case *Where:
b, ok := inB.(*Where)
if !ok {
return false
}
return EqualsRefOfWhere(a, b)
case *XorExpr:
b, ok := inB.(*XorExpr)
if !ok {
return false
}
return EqualsRefOfXorExpr(a, b)
default:
// this should never happen
return false
}
}
// CloneSelectExpr creates a deep clone of the input.
func CloneSelectExpr(in SelectExpr) SelectExpr {
if in == nil {
return nil
}
switch in := in.(type) {
case *AliasedExpr:
return CloneRefOfAliasedExpr(in)
case *Nextval:
return CloneRefOfNextval(in)
case *StarExpr:
return CloneRefOfStarExpr(in)
default:
// this should never happen
return nil
}
}
// EqualsSelectExpr does deep equals between the two objects.
func EqualsSelectExpr(inA, inB SelectExpr) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AliasedExpr:
b, ok := inB.(*AliasedExpr)
if !ok {
return false
}
return EqualsRefOfAliasedExpr(a, b)
case *Nextval:
b, ok := inB.(*Nextval)
if !ok {
return false
}
return EqualsRefOfNextval(a, b)
case *StarExpr:
b, ok := inB.(*StarExpr)
if !ok {
return false
}
return EqualsRefOfStarExpr(a, b)
default:
// this should never happen
return false
}
}
// CloneSelectStatement creates a deep clone of the input.
func CloneSelectStatement(in SelectStatement) SelectStatement {
if in == nil {
return nil
}
switch in := in.(type) {
case *ParenSelect:
return CloneRefOfParenSelect(in)
case *Select:
return CloneRefOfSelect(in)
case *Union:
return CloneRefOfUnion(in)
default:
// this should never happen
return nil
}
}
// EqualsSelectStatement does deep equals between the two objects.
func EqualsSelectStatement(inA, inB SelectStatement) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *ParenSelect:
b, ok := inB.(*ParenSelect)
if !ok {
return false
}
return EqualsRefOfParenSelect(a, b)
case *Select:
b, ok := inB.(*Select)
if !ok {
return false
}
return EqualsRefOfSelect(a, b)
case *Union:
b, ok := inB.(*Union)
if !ok {
return false
}
return EqualsRefOfUnion(a, b)
default:
// this should never happen
return false
}
}
// CloneShowInternal creates a deep clone of the input.
func CloneShowInternal(in ShowInternal) ShowInternal {
if in == nil {
return nil
}
switch in := in.(type) {
case *ShowBasic:
return CloneRefOfShowBasic(in)
case *ShowCreate:
return CloneRefOfShowCreate(in)
case *ShowLegacy:
return CloneRefOfShowLegacy(in)
default:
// this should never happen
return nil
}
}
// EqualsShowInternal does deep equals between the two objects.
func EqualsShowInternal(inA, inB ShowInternal) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *ShowBasic:
b, ok := inB.(*ShowBasic)
if !ok {
return false
}
return EqualsRefOfShowBasic(a, b)
case *ShowCreate:
b, ok := inB.(*ShowCreate)
if !ok {
return false
}
return EqualsRefOfShowCreate(a, b)
case *ShowLegacy:
b, ok := inB.(*ShowLegacy)
if !ok {
return false
}
return EqualsRefOfShowLegacy(a, b)
default:
// this should never happen
return false
}
}
// CloneSimpleTableExpr creates a deep clone of the input.
func CloneSimpleTableExpr(in SimpleTableExpr) SimpleTableExpr {
if in == nil {
return nil
}
switch in := in.(type) {
case *DerivedTable:
return CloneRefOfDerivedTable(in)
case TableName:
return CloneTableName(in)
default:
// this should never happen
return nil
}
}
// EqualsSimpleTableExpr does deep equals between the two objects.
func EqualsSimpleTableExpr(inA, inB SimpleTableExpr) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *DerivedTable:
b, ok := inB.(*DerivedTable)
if !ok {
return false
}
return EqualsRefOfDerivedTable(a, b)
case TableName:
b, ok := inB.(TableName)
if !ok {
return false
}
return EqualsTableName(a, b)
default:
// this should never happen
return false
}
}
// CloneStatement creates a deep clone of the input.
func CloneStatement(in Statement) Statement {
if in == nil {
return nil
}
switch in := in.(type) {
case *AlterDatabase:
return CloneRefOfAlterDatabase(in)
case *AlterTable:
return CloneRefOfAlterTable(in)
case *AlterView:
return CloneRefOfAlterView(in)
case *AlterVschema:
return CloneRefOfAlterVschema(in)
case *Begin:
return CloneRefOfBegin(in)
case *CallProc:
return CloneRefOfCallProc(in)
case *Commit:
return CloneRefOfCommit(in)
case *CreateDatabase:
return CloneRefOfCreateDatabase(in)
case *CreateTable:
return CloneRefOfCreateTable(in)
case *CreateView:
return CloneRefOfCreateView(in)
case *Delete:
return CloneRefOfDelete(in)
case *DropDatabase:
return CloneRefOfDropDatabase(in)
case *DropTable:
return CloneRefOfDropTable(in)
case *DropView:
return CloneRefOfDropView(in)
case *ExplainStmt:
return CloneRefOfExplainStmt(in)
case *ExplainTab:
return CloneRefOfExplainTab(in)
case *Flush:
return CloneRefOfFlush(in)
case *Insert:
return CloneRefOfInsert(in)
case *Load:
return CloneRefOfLoad(in)
case *LockTables:
return CloneRefOfLockTables(in)
case *OtherAdmin:
return CloneRefOfOtherAdmin(in)
case *OtherRead:
return CloneRefOfOtherRead(in)
case *ParenSelect:
return CloneRefOfParenSelect(in)
case *Release:
return CloneRefOfRelease(in)
case *RenameTable:
return CloneRefOfRenameTable(in)
case *Rollback:
return CloneRefOfRollback(in)
case *SRollback:
return CloneRefOfSRollback(in)
case *Savepoint:
return CloneRefOfSavepoint(in)
case *Select:
return CloneRefOfSelect(in)
case *Set:
return CloneRefOfSet(in)
case *SetTransaction:
return CloneRefOfSetTransaction(in)
case *Show:
return CloneRefOfShow(in)
case *Stream:
return CloneRefOfStream(in)
case *TruncateTable:
return CloneRefOfTruncateTable(in)
case *Union:
return CloneRefOfUnion(in)
case *UnlockTables:
return CloneRefOfUnlockTables(in)
case *Update:
return CloneRefOfUpdate(in)
case *Use:
return CloneRefOfUse(in)
case *VStream:
return CloneRefOfVStream(in)
default:
// this should never happen
return nil
}
}
// EqualsStatement does deep equals between the two objects.
func EqualsStatement(inA, inB Statement) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AlterDatabase:
b, ok := inB.(*AlterDatabase)
if !ok {
return false
}
return EqualsRefOfAlterDatabase(a, b)
case *AlterTable:
b, ok := inB.(*AlterTable)
if !ok {
return false
}
return EqualsRefOfAlterTable(a, b)
case *AlterView:
b, ok := inB.(*AlterView)
if !ok {
return false
}
return EqualsRefOfAlterView(a, b)
case *AlterVschema:
b, ok := inB.(*AlterVschema)
if !ok {
return false
}
return EqualsRefOfAlterVschema(a, b)
case *Begin:
b, ok := inB.(*Begin)
if !ok {
return false
}
return EqualsRefOfBegin(a, b)
case *CallProc:
b, ok := inB.(*CallProc)
if !ok {
return false
}
return EqualsRefOfCallProc(a, b)
case *Commit:
b, ok := inB.(*Commit)
if !ok {
return false
}
return EqualsRefOfCommit(a, b)
case *CreateDatabase:
b, ok := inB.(*CreateDatabase)
if !ok {
return false
}
return EqualsRefOfCreateDatabase(a, b)
case *CreateTable:
b, ok := inB.(*CreateTable)
if !ok {
return false
}
return EqualsRefOfCreateTable(a, b)
case *CreateView:
b, ok := inB.(*CreateView)
if !ok {
return false
}
return EqualsRefOfCreateView(a, b)
case *Delete:
b, ok := inB.(*Delete)
if !ok {
return false
}
return EqualsRefOfDelete(a, b)
case *DropDatabase:
b, ok := inB.(*DropDatabase)
if !ok {
return false
}
return EqualsRefOfDropDatabase(a, b)
case *DropTable:
b, ok := inB.(*DropTable)
if !ok {
return false
}
return EqualsRefOfDropTable(a, b)
case *DropView:
b, ok := inB.(*DropView)
if !ok {
return false
}
return EqualsRefOfDropView(a, b)
case *ExplainStmt:
b, ok := inB.(*ExplainStmt)
if !ok {
return false
}
return EqualsRefOfExplainStmt(a, b)
case *ExplainTab:
b, ok := inB.(*ExplainTab)
if !ok {
return false
}
return EqualsRefOfExplainTab(a, b)
case *Flush:
b, ok := inB.(*Flush)
if !ok {
return false
}
return EqualsRefOfFlush(a, b)
case *Insert:
b, ok := inB.(*Insert)
if !ok {
return false
}
return EqualsRefOfInsert(a, b)
case *Load:
b, ok := inB.(*Load)
if !ok {
return false
}
return EqualsRefOfLoad(a, b)
case *LockTables:
b, ok := inB.(*LockTables)
if !ok {
return false
}
return EqualsRefOfLockTables(a, b)
case *OtherAdmin:
b, ok := inB.(*OtherAdmin)
if !ok {
return false
}
return EqualsRefOfOtherAdmin(a, b)
case *OtherRead:
b, ok := inB.(*OtherRead)
if !ok {
return false
}
return EqualsRefOfOtherRead(a, b)
case *ParenSelect:
b, ok := inB.(*ParenSelect)
if !ok {
return false
}
return EqualsRefOfParenSelect(a, b)
case *Release:
b, ok := inB.(*Release)
if !ok {
return false
}
return EqualsRefOfRelease(a, b)
case *RenameTable:
b, ok := inB.(*RenameTable)
if !ok {
return false
}
return EqualsRefOfRenameTable(a, b)
case *Rollback:
b, ok := inB.(*Rollback)
if !ok {
return false
}
return EqualsRefOfRollback(a, b)
case *SRollback:
b, ok := inB.(*SRollback)
if !ok {
return false
}
return EqualsRefOfSRollback(a, b)
case *Savepoint:
b, ok := inB.(*Savepoint)
if !ok {
return false
}
return EqualsRefOfSavepoint(a, b)
case *Select:
b, ok := inB.(*Select)
if !ok {
return false
}
return EqualsRefOfSelect(a, b)
case *Set:
b, ok := inB.(*Set)
if !ok {
return false
}
return EqualsRefOfSet(a, b)
case *SetTransaction:
b, ok := inB.(*SetTransaction)
if !ok {
return false
}
return EqualsRefOfSetTransaction(a, b)
case *Show:
b, ok := inB.(*Show)
if !ok {
return false
}
return EqualsRefOfShow(a, b)
case *Stream:
b, ok := inB.(*Stream)
if !ok {
return false
}
return EqualsRefOfStream(a, b)
case *TruncateTable:
b, ok := inB.(*TruncateTable)
if !ok {
return false
}
return EqualsRefOfTruncateTable(a, b)
case *Union:
b, ok := inB.(*Union)
if !ok {
return false
}
return EqualsRefOfUnion(a, b)
case *UnlockTables:
b, ok := inB.(*UnlockTables)
if !ok {
return false
}
return EqualsRefOfUnlockTables(a, b)
case *Update:
b, ok := inB.(*Update)
if !ok {
return false
}
return EqualsRefOfUpdate(a, b)
case *Use:
b, ok := inB.(*Use)
if !ok {
return false
}
return EqualsRefOfUse(a, b)
case *VStream:
b, ok := inB.(*VStream)
if !ok {
return false
}
return EqualsRefOfVStream(a, b)
default:
// this should never happen
return false
}
}
// CloneTableExpr creates a deep clone of the input.
func CloneTableExpr(in TableExpr) TableExpr {
if in == nil {
return nil
}
switch in := in.(type) {
case *AliasedTableExpr:
return CloneRefOfAliasedTableExpr(in)
case *JoinTableExpr:
return CloneRefOfJoinTableExpr(in)
case *ParenTableExpr:
return CloneRefOfParenTableExpr(in)
default:
// this should never happen
return nil
}
}
// EqualsTableExpr does deep equals between the two objects.
func EqualsTableExpr(inA, inB TableExpr) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *AliasedTableExpr:
b, ok := inB.(*AliasedTableExpr)
if !ok {
return false
}
return EqualsRefOfAliasedTableExpr(a, b)
case *JoinTableExpr:
b, ok := inB.(*JoinTableExpr)
if !ok {
return false
}
return EqualsRefOfJoinTableExpr(a, b)
case *ParenTableExpr:
b, ok := inB.(*ParenTableExpr)
if !ok {
return false
}
return EqualsRefOfParenTableExpr(a, b)
default:
// this should never happen
return false
}
}
// CloneRefOfAddColumns creates a deep clone of the input.
func CloneRefOfAddColumns(n *AddColumns) *AddColumns {
if n == nil {
return nil
}
out := *n
out.Columns = CloneSliceOfRefOfColumnDefinition(n.Columns)
out.First = CloneRefOfColName(n.First)
out.After = CloneRefOfColName(n.After)
return &out
}
// EqualsRefOfAddColumns does deep equals between the two objects.
func EqualsRefOfAddColumns(a, b *AddColumns) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfRefOfColumnDefinition(a.Columns, b.Columns) &&
EqualsRefOfColName(a.First, b.First) &&
EqualsRefOfColName(a.After, b.After)
}
// CloneRefOfAddConstraintDefinition creates a deep clone of the input.
func CloneRefOfAddConstraintDefinition(n *AddConstraintDefinition) *AddConstraintDefinition {
if n == nil {
return nil
}
out := *n
out.ConstraintDefinition = CloneRefOfConstraintDefinition(n.ConstraintDefinition)
return &out
}
// EqualsRefOfAddConstraintDefinition does deep equals between the two objects.
func EqualsRefOfAddConstraintDefinition(a, b *AddConstraintDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfConstraintDefinition(a.ConstraintDefinition, b.ConstraintDefinition)
}
// CloneRefOfAddIndexDefinition creates a deep clone of the input.
func CloneRefOfAddIndexDefinition(n *AddIndexDefinition) *AddIndexDefinition {
if n == nil {
return nil
}
out := *n
out.IndexDefinition = CloneRefOfIndexDefinition(n.IndexDefinition)
return &out
}
// EqualsRefOfAddIndexDefinition does deep equals between the two objects.
func EqualsRefOfAddIndexDefinition(a, b *AddIndexDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfIndexDefinition(a.IndexDefinition, b.IndexDefinition)
}
// CloneRefOfAlterCharset creates a deep clone of the input.
func CloneRefOfAlterCharset(n *AlterCharset) *AlterCharset {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfAlterCharset does deep equals between the two objects.
func EqualsRefOfAlterCharset(a, b *AlterCharset) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.CharacterSet == b.CharacterSet &&
a.Collate == b.Collate
}
// CloneRefOfAlterColumn creates a deep clone of the input.
func CloneRefOfAlterColumn(n *AlterColumn) *AlterColumn {
if n == nil {
return nil
}
out := *n
out.Column = CloneRefOfColName(n.Column)
out.DefaultVal = CloneExpr(n.DefaultVal)
return &out
}
// EqualsRefOfAlterColumn does deep equals between the two objects.
func EqualsRefOfAlterColumn(a, b *AlterColumn) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.DropDefault == b.DropDefault &&
EqualsRefOfColName(a.Column, b.Column) &&
EqualsExpr(a.DefaultVal, b.DefaultVal)
}
// CloneRefOfChangeColumn creates a deep clone of the input.
func CloneRefOfChangeColumn(n *ChangeColumn) *ChangeColumn {
if n == nil {
return nil
}
out := *n
out.OldColumn = CloneRefOfColName(n.OldColumn)
out.NewColDefinition = CloneRefOfColumnDefinition(n.NewColDefinition)
out.First = CloneRefOfColName(n.First)
out.After = CloneRefOfColName(n.After)
return &out
}
// EqualsRefOfChangeColumn does deep equals between the two objects.
func EqualsRefOfChangeColumn(a, b *ChangeColumn) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfColName(a.OldColumn, b.OldColumn) &&
EqualsRefOfColumnDefinition(a.NewColDefinition, b.NewColDefinition) &&
EqualsRefOfColName(a.First, b.First) &&
EqualsRefOfColName(a.After, b.After)
}
// CloneRefOfDropColumn creates a deep clone of the input.
func CloneRefOfDropColumn(n *DropColumn) *DropColumn {
if n == nil {
return nil
}
out := *n
out.Name = CloneRefOfColName(n.Name)
return &out
}
// EqualsRefOfDropColumn does deep equals between the two objects.
func EqualsRefOfDropColumn(a, b *DropColumn) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfColName(a.Name, b.Name)
}
// CloneRefOfDropKey creates a deep clone of the input.
func CloneRefOfDropKey(n *DropKey) *DropKey {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfDropKey does deep equals between the two objects.
func EqualsRefOfDropKey(a, b *DropKey) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Name == b.Name &&
a.Type == b.Type
}
// CloneRefOfForce creates a deep clone of the input.
func CloneRefOfForce(n *Force) *Force {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfForce does deep equals between the two objects.
func EqualsRefOfForce(a, b *Force) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfKeyState creates a deep clone of the input.
func CloneRefOfKeyState(n *KeyState) *KeyState {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfKeyState does deep equals between the two objects.
func EqualsRefOfKeyState(a, b *KeyState) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Enable == b.Enable
}
// CloneRefOfLockOption creates a deep clone of the input.
func CloneRefOfLockOption(n *LockOption) *LockOption {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfLockOption does deep equals between the two objects.
func EqualsRefOfLockOption(a, b *LockOption) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type
}
// CloneRefOfModifyColumn creates a deep clone of the input.
func CloneRefOfModifyColumn(n *ModifyColumn) *ModifyColumn {
if n == nil {
return nil
}
out := *n
out.NewColDefinition = CloneRefOfColumnDefinition(n.NewColDefinition)
out.First = CloneRefOfColName(n.First)
out.After = CloneRefOfColName(n.After)
return &out
}
// EqualsRefOfModifyColumn does deep equals between the two objects.
func EqualsRefOfModifyColumn(a, b *ModifyColumn) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfColumnDefinition(a.NewColDefinition, b.NewColDefinition) &&
EqualsRefOfColName(a.First, b.First) &&
EqualsRefOfColName(a.After, b.After)
}
// CloneRefOfOrderByOption creates a deep clone of the input.
func CloneRefOfOrderByOption(n *OrderByOption) *OrderByOption {
if n == nil {
return nil
}
out := *n
out.Cols = CloneColumns(n.Cols)
return &out
}
// EqualsRefOfOrderByOption does deep equals between the two objects.
func EqualsRefOfOrderByOption(a, b *OrderByOption) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColumns(a.Cols, b.Cols)
}
// CloneRefOfRenameIndex creates a deep clone of the input.
func CloneRefOfRenameIndex(n *RenameIndex) *RenameIndex {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfRenameIndex does deep equals between the two objects.
func EqualsRefOfRenameIndex(a, b *RenameIndex) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.OldName == b.OldName &&
a.NewName == b.NewName
}
// CloneRefOfRenameTableName creates a deep clone of the input.
func CloneRefOfRenameTableName(n *RenameTableName) *RenameTableName {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableName(n.Table)
return &out
}
// EqualsRefOfRenameTableName does deep equals between the two objects.
func EqualsRefOfRenameTableName(a, b *RenameTableName) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableName(a.Table, b.Table)
}
// CloneTableOptions creates a deep clone of the input.
func CloneTableOptions(n TableOptions) TableOptions {
res := make(TableOptions, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfTableOption(x))
}
return res
}
// EqualsTableOptions does deep equals between the two objects.
func EqualsTableOptions(a, b TableOptions) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfTableOption(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfTablespaceOperation creates a deep clone of the input.
func CloneRefOfTablespaceOperation(n *TablespaceOperation) *TablespaceOperation {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfTablespaceOperation does deep equals between the two objects.
func EqualsRefOfTablespaceOperation(a, b *TablespaceOperation) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Import == b.Import
}
// CloneRefOfValidation creates a deep clone of the input.
func CloneRefOfValidation(n *Validation) *Validation {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfValidation does deep equals between the two objects.
func EqualsRefOfValidation(a, b *Validation) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.With == b.With
}
// CloneListArg creates a deep clone of the input.
func CloneListArg(n ListArg) ListArg {
res := make(ListArg, 0, len(n))
copy(res, n)
return res
}
// EqualsListArg does deep equals between the two objects.
func EqualsListArg(a, b ListArg) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneRefOfSubquery creates a deep clone of the input.
func CloneRefOfSubquery(n *Subquery) *Subquery {
if n == nil {
return nil
}
out := *n
out.Select = CloneSelectStatement(n.Select)
return &out
}
// EqualsRefOfSubquery does deep equals between the two objects.
func EqualsRefOfSubquery(a, b *Subquery) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSelectStatement(a.Select, b.Select)
}
// CloneValTuple creates a deep clone of the input.
func CloneValTuple(n ValTuple) ValTuple {
res := make(ValTuple, 0, len(n))
for _, x := range n {
res = append(res, CloneExpr(x))
}
return res
}
// EqualsValTuple does deep equals between the two objects.
func EqualsValTuple(a, b ValTuple) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfCheckConstraintDefinition creates a deep clone of the input.
func CloneRefOfCheckConstraintDefinition(n *CheckConstraintDefinition) *CheckConstraintDefinition {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfCheckConstraintDefinition does deep equals between the two objects.
func EqualsRefOfCheckConstraintDefinition(a, b *CheckConstraintDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Enforced == b.Enforced &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfForeignKeyDefinition creates a deep clone of the input.
func CloneRefOfForeignKeyDefinition(n *ForeignKeyDefinition) *ForeignKeyDefinition {
if n == nil {
return nil
}
out := *n
out.Source = CloneColumns(n.Source)
out.ReferencedTable = CloneTableName(n.ReferencedTable)
out.ReferencedColumns = CloneColumns(n.ReferencedColumns)
return &out
}
// EqualsRefOfForeignKeyDefinition does deep equals between the two objects.
func EqualsRefOfForeignKeyDefinition(a, b *ForeignKeyDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColumns(a.Source, b.Source) &&
EqualsTableName(a.ReferencedTable, b.ReferencedTable) &&
EqualsColumns(a.ReferencedColumns, b.ReferencedColumns) &&
a.OnDelete == b.OnDelete &&
a.OnUpdate == b.OnUpdate
}
// CloneRefOfAlterDatabase creates a deep clone of the input.
func CloneRefOfAlterDatabase(n *AlterDatabase) *AlterDatabase {
if n == nil {
return nil
}
out := *n
out.AlterOptions = CloneSliceOfCollateAndCharset(n.AlterOptions)
return &out
}
// EqualsRefOfAlterDatabase does deep equals between the two objects.
func EqualsRefOfAlterDatabase(a, b *AlterDatabase) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.DBName == b.DBName &&
a.UpdateDataDirectory == b.UpdateDataDirectory &&
a.FullyParsed == b.FullyParsed &&
EqualsSliceOfCollateAndCharset(a.AlterOptions, b.AlterOptions)
}
// CloneRefOfCreateDatabase creates a deep clone of the input.
func CloneRefOfCreateDatabase(n *CreateDatabase) *CreateDatabase {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.CreateOptions = CloneSliceOfCollateAndCharset(n.CreateOptions)
return &out
}
// EqualsRefOfCreateDatabase does deep equals between the two objects.
func EqualsRefOfCreateDatabase(a, b *CreateDatabase) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.DBName == b.DBName &&
a.IfNotExists == b.IfNotExists &&
a.FullyParsed == b.FullyParsed &&
EqualsComments(a.Comments, b.Comments) &&
EqualsSliceOfCollateAndCharset(a.CreateOptions, b.CreateOptions)
}
// CloneRefOfDropDatabase creates a deep clone of the input.
func CloneRefOfDropDatabase(n *DropDatabase) *DropDatabase {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
return &out
}
// EqualsRefOfDropDatabase does deep equals between the two objects.
func EqualsRefOfDropDatabase(a, b *DropDatabase) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.DBName == b.DBName &&
a.IfExists == b.IfExists &&
EqualsComments(a.Comments, b.Comments)
}
// CloneRefOfAlterTable creates a deep clone of the input.
func CloneRefOfAlterTable(n *AlterTable) *AlterTable {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableName(n.Table)
out.AlterOptions = CloneSliceOfAlterOption(n.AlterOptions)
out.PartitionSpec = CloneRefOfPartitionSpec(n.PartitionSpec)
return &out
}
// EqualsRefOfAlterTable does deep equals between the two objects.
func EqualsRefOfAlterTable(a, b *AlterTable) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.FullyParsed == b.FullyParsed &&
EqualsTableName(a.Table, b.Table) &&
EqualsSliceOfAlterOption(a.AlterOptions, b.AlterOptions) &&
EqualsRefOfPartitionSpec(a.PartitionSpec, b.PartitionSpec)
}
// CloneRefOfAlterView creates a deep clone of the input.
func CloneRefOfAlterView(n *AlterView) *AlterView {
if n == nil {
return nil
}
out := *n
out.ViewName = CloneTableName(n.ViewName)
out.Columns = CloneColumns(n.Columns)
out.Select = CloneSelectStatement(n.Select)
return &out
}
// EqualsRefOfAlterView does deep equals between the two objects.
func EqualsRefOfAlterView(a, b *AlterView) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Algorithm == b.Algorithm &&
a.Definer == b.Definer &&
a.Security == b.Security &&
a.CheckOption == b.CheckOption &&
EqualsTableName(a.ViewName, b.ViewName) &&
EqualsColumns(a.Columns, b.Columns) &&
EqualsSelectStatement(a.Select, b.Select)
}
// CloneRefOfCreateTable creates a deep clone of the input.
func CloneRefOfCreateTable(n *CreateTable) *CreateTable {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableName(n.Table)
out.TableSpec = CloneRefOfTableSpec(n.TableSpec)
out.OptLike = CloneRefOfOptLike(n.OptLike)
return &out
}
// EqualsRefOfCreateTable does deep equals between the two objects.
func EqualsRefOfCreateTable(a, b *CreateTable) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Temp == b.Temp &&
a.IfNotExists == b.IfNotExists &&
a.FullyParsed == b.FullyParsed &&
EqualsTableName(a.Table, b.Table) &&
EqualsRefOfTableSpec(a.TableSpec, b.TableSpec) &&
EqualsRefOfOptLike(a.OptLike, b.OptLike)
}
// CloneRefOfCreateView creates a deep clone of the input.
func CloneRefOfCreateView(n *CreateView) *CreateView {
if n == nil {
return nil
}
out := *n
out.ViewName = CloneTableName(n.ViewName)
out.Columns = CloneColumns(n.Columns)
out.Select = CloneSelectStatement(n.Select)
return &out
}
// EqualsRefOfCreateView does deep equals between the two objects.
func EqualsRefOfCreateView(a, b *CreateView) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Algorithm == b.Algorithm &&
a.Definer == b.Definer &&
a.Security == b.Security &&
a.CheckOption == b.CheckOption &&
a.IsReplace == b.IsReplace &&
EqualsTableName(a.ViewName, b.ViewName) &&
EqualsColumns(a.Columns, b.Columns) &&
EqualsSelectStatement(a.Select, b.Select)
}
// CloneRefOfDropTable creates a deep clone of the input.
func CloneRefOfDropTable(n *DropTable) *DropTable {
if n == nil {
return nil
}
out := *n
out.FromTables = CloneTableNames(n.FromTables)
return &out
}
// EqualsRefOfDropTable does deep equals between the two objects.
func EqualsRefOfDropTable(a, b *DropTable) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Temp == b.Temp &&
a.IfExists == b.IfExists &&
EqualsTableNames(a.FromTables, b.FromTables)
}
// CloneRefOfDropView creates a deep clone of the input.
func CloneRefOfDropView(n *DropView) *DropView {
if n == nil {
return nil
}
out := *n
out.FromTables = CloneTableNames(n.FromTables)
return &out
}
// EqualsRefOfDropView does deep equals between the two objects.
func EqualsRefOfDropView(a, b *DropView) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.IfExists == b.IfExists &&
EqualsTableNames(a.FromTables, b.FromTables)
}
// CloneRefOfRenameTable creates a deep clone of the input.
func CloneRefOfRenameTable(n *RenameTable) *RenameTable {
if n == nil {
return nil
}
out := *n
out.TablePairs = CloneSliceOfRefOfRenameTablePair(n.TablePairs)
return &out
}
// EqualsRefOfRenameTable does deep equals between the two objects.
func EqualsRefOfRenameTable(a, b *RenameTable) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfRefOfRenameTablePair(a.TablePairs, b.TablePairs)
}
// CloneRefOfTruncateTable creates a deep clone of the input.
func CloneRefOfTruncateTable(n *TruncateTable) *TruncateTable {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableName(n.Table)
return &out
}
// EqualsRefOfTruncateTable does deep equals between the two objects.
func EqualsRefOfTruncateTable(a, b *TruncateTable) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableName(a.Table, b.Table)
}
// CloneRefOfExplainStmt creates a deep clone of the input.
func CloneRefOfExplainStmt(n *ExplainStmt) *ExplainStmt {
if n == nil {
return nil
}
out := *n
out.Statement = CloneStatement(n.Statement)
return &out
}
// EqualsRefOfExplainStmt does deep equals between the two objects.
func EqualsRefOfExplainStmt(a, b *ExplainStmt) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
EqualsStatement(a.Statement, b.Statement)
}
// CloneRefOfExplainTab creates a deep clone of the input.
func CloneRefOfExplainTab(n *ExplainTab) *ExplainTab {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableName(n.Table)
return &out
}
// EqualsRefOfExplainTab does deep equals between the two objects.
func EqualsRefOfExplainTab(a, b *ExplainTab) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Wild == b.Wild &&
EqualsTableName(a.Table, b.Table)
}
// CloneRefOfAndExpr creates a deep clone of the input.
func CloneRefOfAndExpr(n *AndExpr) *AndExpr {
if n == nil {
return nil
}
out := *n
out.Left = CloneExpr(n.Left)
out.Right = CloneExpr(n.Right)
return &out
}
// EqualsRefOfAndExpr does deep equals between the two objects.
func EqualsRefOfAndExpr(a, b *AndExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Left, b.Left) &&
EqualsExpr(a.Right, b.Right)
}
// CloneRefOfBinaryExpr creates a deep clone of the input.
func CloneRefOfBinaryExpr(n *BinaryExpr) *BinaryExpr {
if n == nil {
return nil
}
out := *n
out.Left = CloneExpr(n.Left)
out.Right = CloneExpr(n.Right)
return &out
}
// EqualsRefOfBinaryExpr does deep equals between the two objects.
func EqualsRefOfBinaryExpr(a, b *BinaryExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Operator == b.Operator &&
EqualsExpr(a.Left, b.Left) &&
EqualsExpr(a.Right, b.Right)
}
// CloneRefOfCaseExpr creates a deep clone of the input.
func CloneRefOfCaseExpr(n *CaseExpr) *CaseExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
out.Whens = CloneSliceOfRefOfWhen(n.Whens)
out.Else = CloneExpr(n.Else)
return &out
}
// EqualsRefOfCaseExpr does deep equals between the two objects.
func EqualsRefOfCaseExpr(a, b *CaseExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Expr, b.Expr) &&
EqualsSliceOfRefOfWhen(a.Whens, b.Whens) &&
EqualsExpr(a.Else, b.Else)
}
// CloneRefOfColName creates a deep clone of the input.
func CloneRefOfColName(n *ColName) *ColName {
return n
}
// EqualsRefOfColName does deep equals between the two objects.
func EqualsRefOfColName(a, b *ColName) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name) &&
EqualsTableName(a.Qualifier, b.Qualifier)
}
// CloneRefOfCollateExpr creates a deep clone of the input.
func CloneRefOfCollateExpr(n *CollateExpr) *CollateExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfCollateExpr does deep equals between the two objects.
func EqualsRefOfCollateExpr(a, b *CollateExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Charset == b.Charset &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfComparisonExpr creates a deep clone of the input.
func CloneRefOfComparisonExpr(n *ComparisonExpr) *ComparisonExpr {
if n == nil {
return nil
}
out := *n
out.Left = CloneExpr(n.Left)
out.Right = CloneExpr(n.Right)
out.Escape = CloneExpr(n.Escape)
return &out
}
// EqualsRefOfComparisonExpr does deep equals between the two objects.
func EqualsRefOfComparisonExpr(a, b *ComparisonExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Operator == b.Operator &&
EqualsExpr(a.Left, b.Left) &&
EqualsExpr(a.Right, b.Right) &&
EqualsExpr(a.Escape, b.Escape)
}
// CloneRefOfConvertExpr creates a deep clone of the input.
func CloneRefOfConvertExpr(n *ConvertExpr) *ConvertExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
out.Type = CloneRefOfConvertType(n.Type)
return &out
}
// EqualsRefOfConvertExpr does deep equals between the two objects.
func EqualsRefOfConvertExpr(a, b *ConvertExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Expr, b.Expr) &&
EqualsRefOfConvertType(a.Type, b.Type)
}
// CloneRefOfConvertUsingExpr creates a deep clone of the input.
func CloneRefOfConvertUsingExpr(n *ConvertUsingExpr) *ConvertUsingExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfConvertUsingExpr does deep equals between the two objects.
func EqualsRefOfConvertUsingExpr(a, b *ConvertUsingExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfCurTimeFuncExpr creates a deep clone of the input.
func CloneRefOfCurTimeFuncExpr(n *CurTimeFuncExpr) *CurTimeFuncExpr {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
out.Fsp = CloneExpr(n.Fsp)
return &out
}
// EqualsRefOfCurTimeFuncExpr does deep equals between the two objects.
func EqualsRefOfCurTimeFuncExpr(a, b *CurTimeFuncExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name) &&
EqualsExpr(a.Fsp, b.Fsp)
}
// CloneRefOfDefault creates a deep clone of the input.
func CloneRefOfDefault(n *Default) *Default {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfDefault does deep equals between the two objects.
func EqualsRefOfDefault(a, b *Default) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.ColName == b.ColName
}
// CloneRefOfExistsExpr creates a deep clone of the input.
func CloneRefOfExistsExpr(n *ExistsExpr) *ExistsExpr {
if n == nil {
return nil
}
out := *n
out.Subquery = CloneRefOfSubquery(n.Subquery)
return &out
}
// EqualsRefOfExistsExpr does deep equals between the two objects.
func EqualsRefOfExistsExpr(a, b *ExistsExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfSubquery(a.Subquery, b.Subquery)
}
// CloneRefOfFuncExpr creates a deep clone of the input.
func CloneRefOfFuncExpr(n *FuncExpr) *FuncExpr {
if n == nil {
return nil
}
out := *n
out.Qualifier = CloneTableIdent(n.Qualifier)
out.Name = CloneColIdent(n.Name)
out.Exprs = CloneSelectExprs(n.Exprs)
return &out
}
// EqualsRefOfFuncExpr does deep equals between the two objects.
func EqualsRefOfFuncExpr(a, b *FuncExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Distinct == b.Distinct &&
EqualsTableIdent(a.Qualifier, b.Qualifier) &&
EqualsColIdent(a.Name, b.Name) &&
EqualsSelectExprs(a.Exprs, b.Exprs)
}
// CloneRefOfGroupConcatExpr creates a deep clone of the input.
func CloneRefOfGroupConcatExpr(n *GroupConcatExpr) *GroupConcatExpr {
if n == nil {
return nil
}
out := *n
out.Exprs = CloneSelectExprs(n.Exprs)
out.OrderBy = CloneOrderBy(n.OrderBy)
out.Limit = CloneRefOfLimit(n.Limit)
return &out
}
// EqualsRefOfGroupConcatExpr does deep equals between the two objects.
func EqualsRefOfGroupConcatExpr(a, b *GroupConcatExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Distinct == b.Distinct &&
a.Separator == b.Separator &&
EqualsSelectExprs(a.Exprs, b.Exprs) &&
EqualsOrderBy(a.OrderBy, b.OrderBy) &&
EqualsRefOfLimit(a.Limit, b.Limit)
}
// CloneRefOfIntervalExpr creates a deep clone of the input.
func CloneRefOfIntervalExpr(n *IntervalExpr) *IntervalExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfIntervalExpr does deep equals between the two objects.
func EqualsRefOfIntervalExpr(a, b *IntervalExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Unit == b.Unit &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfIsExpr creates a deep clone of the input.
func CloneRefOfIsExpr(n *IsExpr) *IsExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfIsExpr does deep equals between the two objects.
func EqualsRefOfIsExpr(a, b *IsExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Operator == b.Operator &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfLiteral creates a deep clone of the input.
func CloneRefOfLiteral(n *Literal) *Literal {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfLiteral does deep equals between the two objects.
func EqualsRefOfLiteral(a, b *Literal) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Val == b.Val &&
a.Type == b.Type
}
// CloneRefOfMatchExpr creates a deep clone of the input.
func CloneRefOfMatchExpr(n *MatchExpr) *MatchExpr {
if n == nil {
return nil
}
out := *n
out.Columns = CloneSelectExprs(n.Columns)
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfMatchExpr does deep equals between the two objects.
func EqualsRefOfMatchExpr(a, b *MatchExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSelectExprs(a.Columns, b.Columns) &&
EqualsExpr(a.Expr, b.Expr) &&
a.Option == b.Option
}
// CloneRefOfNotExpr creates a deep clone of the input.
func CloneRefOfNotExpr(n *NotExpr) *NotExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfNotExpr does deep equals between the two objects.
func EqualsRefOfNotExpr(a, b *NotExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfNullVal creates a deep clone of the input.
func CloneRefOfNullVal(n *NullVal) *NullVal {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfNullVal does deep equals between the two objects.
func EqualsRefOfNullVal(a, b *NullVal) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfOrExpr creates a deep clone of the input.
func CloneRefOfOrExpr(n *OrExpr) *OrExpr {
if n == nil {
return nil
}
out := *n
out.Left = CloneExpr(n.Left)
out.Right = CloneExpr(n.Right)
return &out
}
// EqualsRefOfOrExpr does deep equals between the two objects.
func EqualsRefOfOrExpr(a, b *OrExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Left, b.Left) &&
EqualsExpr(a.Right, b.Right)
}
// CloneRefOfRangeCond creates a deep clone of the input.
func CloneRefOfRangeCond(n *RangeCond) *RangeCond {
if n == nil {
return nil
}
out := *n
out.Left = CloneExpr(n.Left)
out.From = CloneExpr(n.From)
out.To = CloneExpr(n.To)
return &out
}
// EqualsRefOfRangeCond does deep equals between the two objects.
func EqualsRefOfRangeCond(a, b *RangeCond) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Operator == b.Operator &&
EqualsExpr(a.Left, b.Left) &&
EqualsExpr(a.From, b.From) &&
EqualsExpr(a.To, b.To)
}
// CloneRefOfSubstrExpr creates a deep clone of the input.
func CloneRefOfSubstrExpr(n *SubstrExpr) *SubstrExpr {
if n == nil {
return nil
}
out := *n
out.Name = CloneRefOfColName(n.Name)
out.StrVal = CloneRefOfLiteral(n.StrVal)
out.From = CloneExpr(n.From)
out.To = CloneExpr(n.To)
return &out
}
// EqualsRefOfSubstrExpr does deep equals between the two objects.
func EqualsRefOfSubstrExpr(a, b *SubstrExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfColName(a.Name, b.Name) &&
EqualsRefOfLiteral(a.StrVal, b.StrVal) &&
EqualsExpr(a.From, b.From) &&
EqualsExpr(a.To, b.To)
}
// CloneRefOfTimestampFuncExpr creates a deep clone of the input.
func CloneRefOfTimestampFuncExpr(n *TimestampFuncExpr) *TimestampFuncExpr {
if n == nil {
return nil
}
out := *n
out.Expr1 = CloneExpr(n.Expr1)
out.Expr2 = CloneExpr(n.Expr2)
return &out
}
// EqualsRefOfTimestampFuncExpr does deep equals between the two objects.
func EqualsRefOfTimestampFuncExpr(a, b *TimestampFuncExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Name == b.Name &&
a.Unit == b.Unit &&
EqualsExpr(a.Expr1, b.Expr1) &&
EqualsExpr(a.Expr2, b.Expr2)
}
// CloneRefOfUnaryExpr creates a deep clone of the input.
func CloneRefOfUnaryExpr(n *UnaryExpr) *UnaryExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfUnaryExpr does deep equals between the two objects.
func EqualsRefOfUnaryExpr(a, b *UnaryExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Operator == b.Operator &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneRefOfValuesFuncExpr creates a deep clone of the input.
func CloneRefOfValuesFuncExpr(n *ValuesFuncExpr) *ValuesFuncExpr {
if n == nil {
return nil
}
out := *n
out.Name = CloneRefOfColName(n.Name)
return &out
}
// EqualsRefOfValuesFuncExpr does deep equals between the two objects.
func EqualsRefOfValuesFuncExpr(a, b *ValuesFuncExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfColName(a.Name, b.Name)
}
// CloneRefOfXorExpr creates a deep clone of the input.
func CloneRefOfXorExpr(n *XorExpr) *XorExpr {
if n == nil {
return nil
}
out := *n
out.Left = CloneExpr(n.Left)
out.Right = CloneExpr(n.Right)
return &out
}
// EqualsRefOfXorExpr does deep equals between the two objects.
func EqualsRefOfXorExpr(a, b *XorExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Left, b.Left) &&
EqualsExpr(a.Right, b.Right)
}
// CloneRefOfParenSelect creates a deep clone of the input.
func CloneRefOfParenSelect(n *ParenSelect) *ParenSelect {
if n == nil {
return nil
}
out := *n
out.Select = CloneSelectStatement(n.Select)
return &out
}
// EqualsRefOfParenSelect does deep equals between the two objects.
func EqualsRefOfParenSelect(a, b *ParenSelect) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSelectStatement(a.Select, b.Select)
}
// CloneRefOfSelect creates a deep clone of the input.
func CloneRefOfSelect(n *Select) *Select {
if n == nil {
return nil
}
out := *n
out.Cache = CloneRefOfBool(n.Cache)
out.Comments = CloneComments(n.Comments)
out.SelectExprs = CloneSelectExprs(n.SelectExprs)
out.From = CloneTableExprs(n.From)
out.Where = CloneRefOfWhere(n.Where)
out.GroupBy = CloneGroupBy(n.GroupBy)
out.Having = CloneRefOfWhere(n.Having)
out.OrderBy = CloneOrderBy(n.OrderBy)
out.Limit = CloneRefOfLimit(n.Limit)
out.Into = CloneRefOfSelectInto(n.Into)
return &out
}
// EqualsRefOfSelect does deep equals between the two objects.
func EqualsRefOfSelect(a, b *Select) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Distinct == b.Distinct &&
a.StraightJoinHint == b.StraightJoinHint &&
a.SQLCalcFoundRows == b.SQLCalcFoundRows &&
EqualsRefOfBool(a.Cache, b.Cache) &&
EqualsComments(a.Comments, b.Comments) &&
EqualsSelectExprs(a.SelectExprs, b.SelectExprs) &&
EqualsTableExprs(a.From, b.From) &&
EqualsRefOfWhere(a.Where, b.Where) &&
EqualsGroupBy(a.GroupBy, b.GroupBy) &&
EqualsRefOfWhere(a.Having, b.Having) &&
EqualsOrderBy(a.OrderBy, b.OrderBy) &&
EqualsRefOfLimit(a.Limit, b.Limit) &&
a.Lock == b.Lock &&
EqualsRefOfSelectInto(a.Into, b.Into)
}
// CloneRefOfUnion creates a deep clone of the input.
func CloneRefOfUnion(n *Union) *Union {
if n == nil {
return nil
}
out := *n
out.FirstStatement = CloneSelectStatement(n.FirstStatement)
out.UnionSelects = CloneSliceOfRefOfUnionSelect(n.UnionSelects)
out.OrderBy = CloneOrderBy(n.OrderBy)
out.Limit = CloneRefOfLimit(n.Limit)
return &out
}
// EqualsRefOfUnion does deep equals between the two objects.
func EqualsRefOfUnion(a, b *Union) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSelectStatement(a.FirstStatement, b.FirstStatement) &&
EqualsSliceOfRefOfUnionSelect(a.UnionSelects, b.UnionSelects) &&
EqualsOrderBy(a.OrderBy, b.OrderBy) &&
EqualsRefOfLimit(a.Limit, b.Limit) &&
a.Lock == b.Lock
}
// CloneValues creates a deep clone of the input.
func CloneValues(n Values) Values {
res := make(Values, 0, len(n))
for _, x := range n {
res = append(res, CloneValTuple(x))
}
return res
}
// EqualsValues does deep equals between the two objects.
func EqualsValues(a, b Values) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsValTuple(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfAliasedExpr creates a deep clone of the input.
func CloneRefOfAliasedExpr(n *AliasedExpr) *AliasedExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
out.As = CloneColIdent(n.As)
return &out
}
// EqualsRefOfAliasedExpr does deep equals between the two objects.
func EqualsRefOfAliasedExpr(a, b *AliasedExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Expr, b.Expr) &&
EqualsColIdent(a.As, b.As)
}
// CloneRefOfAliasedTableExpr creates a deep clone of the input.
func CloneRefOfAliasedTableExpr(n *AliasedTableExpr) *AliasedTableExpr {
if n == nil {
return nil
}
out := *n
out.Expr = CloneSimpleTableExpr(n.Expr)
out.Partitions = ClonePartitions(n.Partitions)
out.As = CloneTableIdent(n.As)
out.Hints = CloneRefOfIndexHints(n.Hints)
return &out
}
// EqualsRefOfAliasedTableExpr does deep equals between the two objects.
func EqualsRefOfAliasedTableExpr(a, b *AliasedTableExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSimpleTableExpr(a.Expr, b.Expr) &&
EqualsPartitions(a.Partitions, b.Partitions) &&
EqualsTableIdent(a.As, b.As) &&
EqualsRefOfIndexHints(a.Hints, b.Hints)
}
// CloneRefOfAlterVschema creates a deep clone of the input.
func CloneRefOfAlterVschema(n *AlterVschema) *AlterVschema {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableName(n.Table)
out.VindexSpec = CloneRefOfVindexSpec(n.VindexSpec)
out.VindexCols = CloneSliceOfColIdent(n.VindexCols)
out.AutoIncSpec = CloneRefOfAutoIncSpec(n.AutoIncSpec)
return &out
}
// EqualsRefOfAlterVschema does deep equals between the two objects.
func EqualsRefOfAlterVschema(a, b *AlterVschema) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Action == b.Action &&
EqualsTableName(a.Table, b.Table) &&
EqualsRefOfVindexSpec(a.VindexSpec, b.VindexSpec) &&
EqualsSliceOfColIdent(a.VindexCols, b.VindexCols) &&
EqualsRefOfAutoIncSpec(a.AutoIncSpec, b.AutoIncSpec)
}
// CloneRefOfAutoIncSpec creates a deep clone of the input.
func CloneRefOfAutoIncSpec(n *AutoIncSpec) *AutoIncSpec {
if n == nil {
return nil
}
out := *n
out.Column = CloneColIdent(n.Column)
out.Sequence = CloneTableName(n.Sequence)
return &out
}
// EqualsRefOfAutoIncSpec does deep equals between the two objects.
func EqualsRefOfAutoIncSpec(a, b *AutoIncSpec) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Column, b.Column) &&
EqualsTableName(a.Sequence, b.Sequence)
}
// CloneRefOfBegin creates a deep clone of the input.
func CloneRefOfBegin(n *Begin) *Begin {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfBegin does deep equals between the two objects.
func EqualsRefOfBegin(a, b *Begin) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfCallProc creates a deep clone of the input.
func CloneRefOfCallProc(n *CallProc) *CallProc {
if n == nil {
return nil
}
out := *n
out.Name = CloneTableName(n.Name)
out.Params = CloneExprs(n.Params)
return &out
}
// EqualsRefOfCallProc does deep equals between the two objects.
func EqualsRefOfCallProc(a, b *CallProc) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableName(a.Name, b.Name) &&
EqualsExprs(a.Params, b.Params)
}
// CloneColIdent creates a deep clone of the input.
func CloneColIdent(n ColIdent) ColIdent {
return *CloneRefOfColIdent(&n)
}
// EqualsColIdent does deep equals between the two objects.
func EqualsColIdent(a, b ColIdent) bool {
return a.val == b.val &&
a.lowered == b.lowered &&
a.at == b.at
}
// CloneRefOfColumnDefinition creates a deep clone of the input.
func CloneRefOfColumnDefinition(n *ColumnDefinition) *ColumnDefinition {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
out.Type = CloneColumnType(n.Type)
return &out
}
// EqualsRefOfColumnDefinition does deep equals between the two objects.
func EqualsRefOfColumnDefinition(a, b *ColumnDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name) &&
EqualsColumnType(a.Type, b.Type)
}
// CloneRefOfColumnType creates a deep clone of the input.
func CloneRefOfColumnType(n *ColumnType) *ColumnType {
if n == nil {
return nil
}
out := *n
out.Options = CloneRefOfColumnTypeOptions(n.Options)
out.Length = CloneRefOfLiteral(n.Length)
out.Scale = CloneRefOfLiteral(n.Scale)
out.EnumValues = CloneSliceOfString(n.EnumValues)
return &out
}
// EqualsRefOfColumnType does deep equals between the two objects.
func EqualsRefOfColumnType(a, b *ColumnType) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
a.Unsigned == b.Unsigned &&
a.Zerofill == b.Zerofill &&
a.Charset == b.Charset &&
a.Collate == b.Collate &&
EqualsRefOfColumnTypeOptions(a.Options, b.Options) &&
EqualsRefOfLiteral(a.Length, b.Length) &&
EqualsRefOfLiteral(a.Scale, b.Scale) &&
EqualsSliceOfString(a.EnumValues, b.EnumValues)
}
// CloneColumns creates a deep clone of the input.
func CloneColumns(n Columns) Columns {
res := make(Columns, 0, len(n))
for _, x := range n {
res = append(res, CloneColIdent(x))
}
return res
}
// EqualsColumns does deep equals between the two objects.
func EqualsColumns(a, b Columns) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsColIdent(a[i], b[i]) {
return false
}
}
return true
}
// CloneComments creates a deep clone of the input.
func CloneComments(n Comments) Comments {
res := make(Comments, 0, len(n))
copy(res, n)
return res
}
// EqualsComments does deep equals between the two objects.
func EqualsComments(a, b Comments) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneRefOfCommit creates a deep clone of the input.
func CloneRefOfCommit(n *Commit) *Commit {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfCommit does deep equals between the two objects.
func EqualsRefOfCommit(a, b *Commit) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfConstraintDefinition creates a deep clone of the input.
func CloneRefOfConstraintDefinition(n *ConstraintDefinition) *ConstraintDefinition {
if n == nil {
return nil
}
out := *n
out.Details = CloneConstraintInfo(n.Details)
return &out
}
// EqualsRefOfConstraintDefinition does deep equals between the two objects.
func EqualsRefOfConstraintDefinition(a, b *ConstraintDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Name == b.Name &&
EqualsConstraintInfo(a.Details, b.Details)
}
// CloneRefOfConvertType creates a deep clone of the input.
func CloneRefOfConvertType(n *ConvertType) *ConvertType {
if n == nil {
return nil
}
out := *n
out.Length = CloneRefOfLiteral(n.Length)
out.Scale = CloneRefOfLiteral(n.Scale)
return &out
}
// EqualsRefOfConvertType does deep equals between the two objects.
func EqualsRefOfConvertType(a, b *ConvertType) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
a.Charset == b.Charset &&
EqualsRefOfLiteral(a.Length, b.Length) &&
EqualsRefOfLiteral(a.Scale, b.Scale) &&
a.Operator == b.Operator
}
// CloneRefOfDelete creates a deep clone of the input.
func CloneRefOfDelete(n *Delete) *Delete {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.Targets = CloneTableNames(n.Targets)
out.TableExprs = CloneTableExprs(n.TableExprs)
out.Partitions = ClonePartitions(n.Partitions)
out.Where = CloneRefOfWhere(n.Where)
out.OrderBy = CloneOrderBy(n.OrderBy)
out.Limit = CloneRefOfLimit(n.Limit)
return &out
}
// EqualsRefOfDelete does deep equals between the two objects.
func EqualsRefOfDelete(a, b *Delete) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Ignore == b.Ignore &&
EqualsComments(a.Comments, b.Comments) &&
EqualsTableNames(a.Targets, b.Targets) &&
EqualsTableExprs(a.TableExprs, b.TableExprs) &&
EqualsPartitions(a.Partitions, b.Partitions) &&
EqualsRefOfWhere(a.Where, b.Where) &&
EqualsOrderBy(a.OrderBy, b.OrderBy) &&
EqualsRefOfLimit(a.Limit, b.Limit)
}
// CloneRefOfDerivedTable creates a deep clone of the input.
func CloneRefOfDerivedTable(n *DerivedTable) *DerivedTable {
if n == nil {
return nil
}
out := *n
out.Select = CloneSelectStatement(n.Select)
return &out
}
// EqualsRefOfDerivedTable does deep equals between the two objects.
func EqualsRefOfDerivedTable(a, b *DerivedTable) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSelectStatement(a.Select, b.Select)
}
// CloneExprs creates a deep clone of the input.
func CloneExprs(n Exprs) Exprs {
res := make(Exprs, 0, len(n))
for _, x := range n {
res = append(res, CloneExpr(x))
}
return res
}
// EqualsExprs does deep equals between the two objects.
func EqualsExprs(a, b Exprs) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfFlush creates a deep clone of the input.
func CloneRefOfFlush(n *Flush) *Flush {
if n == nil {
return nil
}
out := *n
out.FlushOptions = CloneSliceOfString(n.FlushOptions)
out.TableNames = CloneTableNames(n.TableNames)
return &out
}
// EqualsRefOfFlush does deep equals between the two objects.
func EqualsRefOfFlush(a, b *Flush) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.IsLocal == b.IsLocal &&
a.WithLock == b.WithLock &&
a.ForExport == b.ForExport &&
EqualsSliceOfString(a.FlushOptions, b.FlushOptions) &&
EqualsTableNames(a.TableNames, b.TableNames)
}
// CloneGroupBy creates a deep clone of the input.
func CloneGroupBy(n GroupBy) GroupBy {
res := make(GroupBy, 0, len(n))
for _, x := range n {
res = append(res, CloneExpr(x))
}
return res
}
// EqualsGroupBy does deep equals between the two objects.
func EqualsGroupBy(a, b GroupBy) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfIndexDefinition creates a deep clone of the input.
func CloneRefOfIndexDefinition(n *IndexDefinition) *IndexDefinition {
if n == nil {
return nil
}
out := *n
out.Info = CloneRefOfIndexInfo(n.Info)
out.Columns = CloneSliceOfRefOfIndexColumn(n.Columns)
out.Options = CloneSliceOfRefOfIndexOption(n.Options)
return &out
}
// EqualsRefOfIndexDefinition does deep equals between the two objects.
func EqualsRefOfIndexDefinition(a, b *IndexDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfIndexInfo(a.Info, b.Info) &&
EqualsSliceOfRefOfIndexColumn(a.Columns, b.Columns) &&
EqualsSliceOfRefOfIndexOption(a.Options, b.Options)
}
// CloneRefOfIndexHints creates a deep clone of the input.
func CloneRefOfIndexHints(n *IndexHints) *IndexHints {
if n == nil {
return nil
}
out := *n
out.Indexes = CloneSliceOfColIdent(n.Indexes)
return &out
}
// EqualsRefOfIndexHints does deep equals between the two objects.
func EqualsRefOfIndexHints(a, b *IndexHints) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
EqualsSliceOfColIdent(a.Indexes, b.Indexes)
}
// CloneRefOfIndexInfo creates a deep clone of the input.
func CloneRefOfIndexInfo(n *IndexInfo) *IndexInfo {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
out.ConstraintName = CloneColIdent(n.ConstraintName)
return &out
}
// EqualsRefOfIndexInfo does deep equals between the two objects.
func EqualsRefOfIndexInfo(a, b *IndexInfo) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
a.Primary == b.Primary &&
a.Spatial == b.Spatial &&
a.Fulltext == b.Fulltext &&
a.Unique == b.Unique &&
EqualsColIdent(a.Name, b.Name) &&
EqualsColIdent(a.ConstraintName, b.ConstraintName)
}
// CloneRefOfInsert creates a deep clone of the input.
func CloneRefOfInsert(n *Insert) *Insert {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.Table = CloneTableName(n.Table)
out.Partitions = ClonePartitions(n.Partitions)
out.Columns = CloneColumns(n.Columns)
out.Rows = CloneInsertRows(n.Rows)
out.OnDup = CloneOnDup(n.OnDup)
return &out
}
// EqualsRefOfInsert does deep equals between the two objects.
func EqualsRefOfInsert(a, b *Insert) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Action == b.Action &&
EqualsComments(a.Comments, b.Comments) &&
a.Ignore == b.Ignore &&
EqualsTableName(a.Table, b.Table) &&
EqualsPartitions(a.Partitions, b.Partitions) &&
EqualsColumns(a.Columns, b.Columns) &&
EqualsInsertRows(a.Rows, b.Rows) &&
EqualsOnDup(a.OnDup, b.OnDup)
}
// CloneJoinCondition creates a deep clone of the input.
func CloneJoinCondition(n JoinCondition) JoinCondition {
return *CloneRefOfJoinCondition(&n)
}
// EqualsJoinCondition does deep equals between the two objects.
func EqualsJoinCondition(a, b JoinCondition) bool {
return EqualsExpr(a.On, b.On) &&
EqualsColumns(a.Using, b.Using)
}
// CloneRefOfJoinTableExpr creates a deep clone of the input.
func CloneRefOfJoinTableExpr(n *JoinTableExpr) *JoinTableExpr {
if n == nil {
return nil
}
out := *n
out.LeftExpr = CloneTableExpr(n.LeftExpr)
out.RightExpr = CloneTableExpr(n.RightExpr)
out.Condition = CloneJoinCondition(n.Condition)
return &out
}
// EqualsRefOfJoinTableExpr does deep equals between the two objects.
func EqualsRefOfJoinTableExpr(a, b *JoinTableExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableExpr(a.LeftExpr, b.LeftExpr) &&
a.Join == b.Join &&
EqualsTableExpr(a.RightExpr, b.RightExpr) &&
EqualsJoinCondition(a.Condition, b.Condition)
}
// CloneRefOfLimit creates a deep clone of the input.
func CloneRefOfLimit(n *Limit) *Limit {
if n == nil {
return nil
}
out := *n
out.Offset = CloneExpr(n.Offset)
out.Rowcount = CloneExpr(n.Rowcount)
return &out
}
// EqualsRefOfLimit does deep equals between the two objects.
func EqualsRefOfLimit(a, b *Limit) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Offset, b.Offset) &&
EqualsExpr(a.Rowcount, b.Rowcount)
}
// CloneRefOfLoad creates a deep clone of the input.
func CloneRefOfLoad(n *Load) *Load {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfLoad does deep equals between the two objects.
func EqualsRefOfLoad(a, b *Load) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfLockTables creates a deep clone of the input.
func CloneRefOfLockTables(n *LockTables) *LockTables {
if n == nil {
return nil
}
out := *n
out.Tables = CloneTableAndLockTypes(n.Tables)
return &out
}
// EqualsRefOfLockTables does deep equals between the two objects.
func EqualsRefOfLockTables(a, b *LockTables) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableAndLockTypes(a.Tables, b.Tables)
}
// CloneRefOfNextval creates a deep clone of the input.
func CloneRefOfNextval(n *Nextval) *Nextval {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfNextval does deep equals between the two objects.
func EqualsRefOfNextval(a, b *Nextval) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Expr, b.Expr)
}
// CloneOnDup creates a deep clone of the input.
func CloneOnDup(n OnDup) OnDup {
res := make(OnDup, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfUpdateExpr(x))
}
return res
}
// EqualsOnDup does deep equals between the two objects.
func EqualsOnDup(a, b OnDup) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfUpdateExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfOptLike creates a deep clone of the input.
func CloneRefOfOptLike(n *OptLike) *OptLike {
if n == nil {
return nil
}
out := *n
out.LikeTable = CloneTableName(n.LikeTable)
return &out
}
// EqualsRefOfOptLike does deep equals between the two objects.
func EqualsRefOfOptLike(a, b *OptLike) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableName(a.LikeTable, b.LikeTable)
}
// CloneRefOfOrder creates a deep clone of the input.
func CloneRefOfOrder(n *Order) *Order {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfOrder does deep equals between the two objects.
func EqualsRefOfOrder(a, b *Order) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Expr, b.Expr) &&
a.Direction == b.Direction
}
// CloneOrderBy creates a deep clone of the input.
func CloneOrderBy(n OrderBy) OrderBy {
res := make(OrderBy, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfOrder(x))
}
return res
}
// EqualsOrderBy does deep equals between the two objects.
func EqualsOrderBy(a, b OrderBy) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfOrder(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfOtherAdmin creates a deep clone of the input.
func CloneRefOfOtherAdmin(n *OtherAdmin) *OtherAdmin {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfOtherAdmin does deep equals between the two objects.
func EqualsRefOfOtherAdmin(a, b *OtherAdmin) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfOtherRead creates a deep clone of the input.
func CloneRefOfOtherRead(n *OtherRead) *OtherRead {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfOtherRead does deep equals between the two objects.
func EqualsRefOfOtherRead(a, b *OtherRead) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfParenTableExpr creates a deep clone of the input.
func CloneRefOfParenTableExpr(n *ParenTableExpr) *ParenTableExpr {
if n == nil {
return nil
}
out := *n
out.Exprs = CloneTableExprs(n.Exprs)
return &out
}
// EqualsRefOfParenTableExpr does deep equals between the two objects.
func EqualsRefOfParenTableExpr(a, b *ParenTableExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableExprs(a.Exprs, b.Exprs)
}
// CloneRefOfPartitionDefinition creates a deep clone of the input.
func CloneRefOfPartitionDefinition(n *PartitionDefinition) *PartitionDefinition {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
out.Limit = CloneExpr(n.Limit)
return &out
}
// EqualsRefOfPartitionDefinition does deep equals between the two objects.
func EqualsRefOfPartitionDefinition(a, b *PartitionDefinition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Maxvalue == b.Maxvalue &&
EqualsColIdent(a.Name, b.Name) &&
EqualsExpr(a.Limit, b.Limit)
}
// CloneRefOfPartitionSpec creates a deep clone of the input.
func CloneRefOfPartitionSpec(n *PartitionSpec) *PartitionSpec {
if n == nil {
return nil
}
out := *n
out.Names = ClonePartitions(n.Names)
out.Number = CloneRefOfLiteral(n.Number)
out.TableName = CloneTableName(n.TableName)
out.Definitions = CloneSliceOfRefOfPartitionDefinition(n.Definitions)
return &out
}
// EqualsRefOfPartitionSpec does deep equals between the two objects.
func EqualsRefOfPartitionSpec(a, b *PartitionSpec) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.IsAll == b.IsAll &&
a.WithoutValidation == b.WithoutValidation &&
a.Action == b.Action &&
EqualsPartitions(a.Names, b.Names) &&
EqualsRefOfLiteral(a.Number, b.Number) &&
EqualsTableName(a.TableName, b.TableName) &&
EqualsSliceOfRefOfPartitionDefinition(a.Definitions, b.Definitions)
}
// ClonePartitions creates a deep clone of the input.
func ClonePartitions(n Partitions) Partitions {
res := make(Partitions, 0, len(n))
for _, x := range n {
res = append(res, CloneColIdent(x))
}
return res
}
// EqualsPartitions does deep equals between the two objects.
func EqualsPartitions(a, b Partitions) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsColIdent(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfRelease creates a deep clone of the input.
func CloneRefOfRelease(n *Release) *Release {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
return &out
}
// EqualsRefOfRelease does deep equals between the two objects.
func EqualsRefOfRelease(a, b *Release) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name)
}
// CloneRefOfRollback creates a deep clone of the input.
func CloneRefOfRollback(n *Rollback) *Rollback {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfRollback does deep equals between the two objects.
func EqualsRefOfRollback(a, b *Rollback) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfSRollback creates a deep clone of the input.
func CloneRefOfSRollback(n *SRollback) *SRollback {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
return &out
}
// EqualsRefOfSRollback does deep equals between the two objects.
func EqualsRefOfSRollback(a, b *SRollback) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name)
}
// CloneRefOfSavepoint creates a deep clone of the input.
func CloneRefOfSavepoint(n *Savepoint) *Savepoint {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
return &out
}
// EqualsRefOfSavepoint does deep equals between the two objects.
func EqualsRefOfSavepoint(a, b *Savepoint) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name)
}
// CloneSelectExprs creates a deep clone of the input.
func CloneSelectExprs(n SelectExprs) SelectExprs {
res := make(SelectExprs, 0, len(n))
for _, x := range n {
res = append(res, CloneSelectExpr(x))
}
return res
}
// EqualsSelectExprs does deep equals between the two objects.
func EqualsSelectExprs(a, b SelectExprs) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsSelectExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfSelectInto creates a deep clone of the input.
func CloneRefOfSelectInto(n *SelectInto) *SelectInto {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfSelectInto does deep equals between the two objects.
func EqualsRefOfSelectInto(a, b *SelectInto) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.FileName == b.FileName &&
a.Charset == b.Charset &&
a.FormatOption == b.FormatOption &&
a.ExportOption == b.ExportOption &&
a.Manifest == b.Manifest &&
a.Overwrite == b.Overwrite &&
a.Type == b.Type
}
// CloneRefOfSet creates a deep clone of the input.
func CloneRefOfSet(n *Set) *Set {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.Exprs = CloneSetExprs(n.Exprs)
return &out
}
// EqualsRefOfSet does deep equals between the two objects.
func EqualsRefOfSet(a, b *Set) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsComments(a.Comments, b.Comments) &&
EqualsSetExprs(a.Exprs, b.Exprs)
}
// CloneRefOfSetExpr creates a deep clone of the input.
func CloneRefOfSetExpr(n *SetExpr) *SetExpr {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfSetExpr does deep equals between the two objects.
func EqualsRefOfSetExpr(a, b *SetExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Scope == b.Scope &&
EqualsColIdent(a.Name, b.Name) &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneSetExprs creates a deep clone of the input.
func CloneSetExprs(n SetExprs) SetExprs {
res := make(SetExprs, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfSetExpr(x))
}
return res
}
// EqualsSetExprs does deep equals between the two objects.
func EqualsSetExprs(a, b SetExprs) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfSetExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfSetTransaction creates a deep clone of the input.
func CloneRefOfSetTransaction(n *SetTransaction) *SetTransaction {
if n == nil {
return nil
}
out := *n
out.SQLNode = CloneSQLNode(n.SQLNode)
out.Comments = CloneComments(n.Comments)
out.Characteristics = CloneSliceOfCharacteristic(n.Characteristics)
return &out
}
// EqualsRefOfSetTransaction does deep equals between the two objects.
func EqualsRefOfSetTransaction(a, b *SetTransaction) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSQLNode(a.SQLNode, b.SQLNode) &&
EqualsComments(a.Comments, b.Comments) &&
a.Scope == b.Scope &&
EqualsSliceOfCharacteristic(a.Characteristics, b.Characteristics)
}
// CloneRefOfShow creates a deep clone of the input.
func CloneRefOfShow(n *Show) *Show {
if n == nil {
return nil
}
out := *n
out.Internal = CloneShowInternal(n.Internal)
return &out
}
// EqualsRefOfShow does deep equals between the two objects.
func EqualsRefOfShow(a, b *Show) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsShowInternal(a.Internal, b.Internal)
}
// CloneRefOfShowBasic creates a deep clone of the input.
func CloneRefOfShowBasic(n *ShowBasic) *ShowBasic {
if n == nil {
return nil
}
out := *n
out.Tbl = CloneTableName(n.Tbl)
out.Filter = CloneRefOfShowFilter(n.Filter)
return &out
}
// EqualsRefOfShowBasic does deep equals between the two objects.
func EqualsRefOfShowBasic(a, b *ShowBasic) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Full == b.Full &&
a.DbName == b.DbName &&
a.Command == b.Command &&
EqualsTableName(a.Tbl, b.Tbl) &&
EqualsRefOfShowFilter(a.Filter, b.Filter)
}
// CloneRefOfShowCreate creates a deep clone of the input.
func CloneRefOfShowCreate(n *ShowCreate) *ShowCreate {
if n == nil {
return nil
}
out := *n
out.Op = CloneTableName(n.Op)
return &out
}
// EqualsRefOfShowCreate does deep equals between the two objects.
func EqualsRefOfShowCreate(a, b *ShowCreate) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Command == b.Command &&
EqualsTableName(a.Op, b.Op)
}
// CloneRefOfShowFilter creates a deep clone of the input.
func CloneRefOfShowFilter(n *ShowFilter) *ShowFilter {
if n == nil {
return nil
}
out := *n
out.Filter = CloneExpr(n.Filter)
return &out
}
// EqualsRefOfShowFilter does deep equals between the two objects.
func EqualsRefOfShowFilter(a, b *ShowFilter) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Like == b.Like &&
EqualsExpr(a.Filter, b.Filter)
}
// CloneRefOfShowLegacy creates a deep clone of the input.
func CloneRefOfShowLegacy(n *ShowLegacy) *ShowLegacy {
if n == nil {
return nil
}
out := *n
out.OnTable = CloneTableName(n.OnTable)
out.Table = CloneTableName(n.Table)
out.ShowTablesOpt = CloneRefOfShowTablesOpt(n.ShowTablesOpt)
out.ShowCollationFilterOpt = CloneExpr(n.ShowCollationFilterOpt)
return &out
}
// EqualsRefOfShowLegacy does deep equals between the two objects.
func EqualsRefOfShowLegacy(a, b *ShowLegacy) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Extended == b.Extended &&
a.Type == b.Type &&
EqualsTableName(a.OnTable, b.OnTable) &&
EqualsTableName(a.Table, b.Table) &&
EqualsRefOfShowTablesOpt(a.ShowTablesOpt, b.ShowTablesOpt) &&
a.Scope == b.Scope &&
EqualsExpr(a.ShowCollationFilterOpt, b.ShowCollationFilterOpt)
}
// CloneRefOfStarExpr creates a deep clone of the input.
func CloneRefOfStarExpr(n *StarExpr) *StarExpr {
if n == nil {
return nil
}
out := *n
out.TableName = CloneTableName(n.TableName)
return &out
}
// EqualsRefOfStarExpr does deep equals between the two objects.
func EqualsRefOfStarExpr(a, b *StarExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableName(a.TableName, b.TableName)
}
// CloneRefOfStream creates a deep clone of the input.
func CloneRefOfStream(n *Stream) *Stream {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.SelectExpr = CloneSelectExpr(n.SelectExpr)
out.Table = CloneTableName(n.Table)
return &out
}
// EqualsRefOfStream does deep equals between the two objects.
func EqualsRefOfStream(a, b *Stream) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsComments(a.Comments, b.Comments) &&
EqualsSelectExpr(a.SelectExpr, b.SelectExpr) &&
EqualsTableName(a.Table, b.Table)
}
// CloneTableExprs creates a deep clone of the input.
func CloneTableExprs(n TableExprs) TableExprs {
res := make(TableExprs, 0, len(n))
for _, x := range n {
res = append(res, CloneTableExpr(x))
}
return res
}
// EqualsTableExprs does deep equals between the two objects.
func EqualsTableExprs(a, b TableExprs) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsTableExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneTableIdent creates a deep clone of the input.
func CloneTableIdent(n TableIdent) TableIdent {
return *CloneRefOfTableIdent(&n)
}
// EqualsTableIdent does deep equals between the two objects.
func EqualsTableIdent(a, b TableIdent) bool {
return a.v == b.v
}
// CloneTableName creates a deep clone of the input.
func CloneTableName(n TableName) TableName {
return *CloneRefOfTableName(&n)
}
// EqualsTableName does deep equals between the two objects.
func EqualsTableName(a, b TableName) bool {
return EqualsTableIdent(a.Name, b.Name) &&
EqualsTableIdent(a.Qualifier, b.Qualifier)
}
// CloneTableNames creates a deep clone of the input.
func CloneTableNames(n TableNames) TableNames {
res := make(TableNames, 0, len(n))
for _, x := range n {
res = append(res, CloneTableName(x))
}
return res
}
// EqualsTableNames does deep equals between the two objects.
func EqualsTableNames(a, b TableNames) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsTableName(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfTableSpec creates a deep clone of the input.
func CloneRefOfTableSpec(n *TableSpec) *TableSpec {
if n == nil {
return nil
}
out := *n
out.Columns = CloneSliceOfRefOfColumnDefinition(n.Columns)
out.Indexes = CloneSliceOfRefOfIndexDefinition(n.Indexes)
out.Constraints = CloneSliceOfRefOfConstraintDefinition(n.Constraints)
out.Options = CloneTableOptions(n.Options)
return &out
}
// EqualsRefOfTableSpec does deep equals between the two objects.
func EqualsRefOfTableSpec(a, b *TableSpec) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfRefOfColumnDefinition(a.Columns, b.Columns) &&
EqualsSliceOfRefOfIndexDefinition(a.Indexes, b.Indexes) &&
EqualsSliceOfRefOfConstraintDefinition(a.Constraints, b.Constraints) &&
EqualsTableOptions(a.Options, b.Options)
}
// CloneRefOfUnionSelect creates a deep clone of the input.
func CloneRefOfUnionSelect(n *UnionSelect) *UnionSelect {
if n == nil {
return nil
}
out := *n
out.Statement = CloneSelectStatement(n.Statement)
return &out
}
// EqualsRefOfUnionSelect does deep equals between the two objects.
func EqualsRefOfUnionSelect(a, b *UnionSelect) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Distinct == b.Distinct &&
EqualsSelectStatement(a.Statement, b.Statement)
}
// CloneRefOfUnlockTables creates a deep clone of the input.
func CloneRefOfUnlockTables(n *UnlockTables) *UnlockTables {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfUnlockTables does deep equals between the two objects.
func EqualsRefOfUnlockTables(a, b *UnlockTables) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfUpdate creates a deep clone of the input.
func CloneRefOfUpdate(n *Update) *Update {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.TableExprs = CloneTableExprs(n.TableExprs)
out.Exprs = CloneUpdateExprs(n.Exprs)
out.Where = CloneRefOfWhere(n.Where)
out.OrderBy = CloneOrderBy(n.OrderBy)
out.Limit = CloneRefOfLimit(n.Limit)
return &out
}
// EqualsRefOfUpdate does deep equals between the two objects.
func EqualsRefOfUpdate(a, b *Update) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsComments(a.Comments, b.Comments) &&
a.Ignore == b.Ignore &&
EqualsTableExprs(a.TableExprs, b.TableExprs) &&
EqualsUpdateExprs(a.Exprs, b.Exprs) &&
EqualsRefOfWhere(a.Where, b.Where) &&
EqualsOrderBy(a.OrderBy, b.OrderBy) &&
EqualsRefOfLimit(a.Limit, b.Limit)
}
// CloneRefOfUpdateExpr creates a deep clone of the input.
func CloneRefOfUpdateExpr(n *UpdateExpr) *UpdateExpr {
if n == nil {
return nil
}
out := *n
out.Name = CloneRefOfColName(n.Name)
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfUpdateExpr does deep equals between the two objects.
func EqualsRefOfUpdateExpr(a, b *UpdateExpr) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsRefOfColName(a.Name, b.Name) &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneUpdateExprs creates a deep clone of the input.
func CloneUpdateExprs(n UpdateExprs) UpdateExprs {
res := make(UpdateExprs, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfUpdateExpr(x))
}
return res
}
// EqualsUpdateExprs does deep equals between the two objects.
func EqualsUpdateExprs(a, b UpdateExprs) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfUpdateExpr(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfUse creates a deep clone of the input.
func CloneRefOfUse(n *Use) *Use {
if n == nil {
return nil
}
out := *n
out.DBName = CloneTableIdent(n.DBName)
return &out
}
// EqualsRefOfUse does deep equals between the two objects.
func EqualsRefOfUse(a, b *Use) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableIdent(a.DBName, b.DBName)
}
// CloneRefOfVStream creates a deep clone of the input.
func CloneRefOfVStream(n *VStream) *VStream {
if n == nil {
return nil
}
out := *n
out.Comments = CloneComments(n.Comments)
out.SelectExpr = CloneSelectExpr(n.SelectExpr)
out.Table = CloneTableName(n.Table)
out.Where = CloneRefOfWhere(n.Where)
out.Limit = CloneRefOfLimit(n.Limit)
return &out
}
// EqualsRefOfVStream does deep equals between the two objects.
func EqualsRefOfVStream(a, b *VStream) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsComments(a.Comments, b.Comments) &&
EqualsSelectExpr(a.SelectExpr, b.SelectExpr) &&
EqualsTableName(a.Table, b.Table) &&
EqualsRefOfWhere(a.Where, b.Where) &&
EqualsRefOfLimit(a.Limit, b.Limit)
}
// CloneVindexParam creates a deep clone of the input.
func CloneVindexParam(n VindexParam) VindexParam {
return *CloneRefOfVindexParam(&n)
}
// EqualsVindexParam does deep equals between the two objects.
func EqualsVindexParam(a, b VindexParam) bool {
return a.Val == b.Val &&
EqualsColIdent(a.Key, b.Key)
}
// CloneRefOfVindexSpec creates a deep clone of the input.
func CloneRefOfVindexSpec(n *VindexSpec) *VindexSpec {
if n == nil {
return nil
}
out := *n
out.Name = CloneColIdent(n.Name)
out.Type = CloneColIdent(n.Type)
out.Params = CloneSliceOfVindexParam(n.Params)
return &out
}
// EqualsRefOfVindexSpec does deep equals between the two objects.
func EqualsRefOfVindexSpec(a, b *VindexSpec) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Name, b.Name) &&
EqualsColIdent(a.Type, b.Type) &&
EqualsSliceOfVindexParam(a.Params, b.Params)
}
// CloneRefOfWhen creates a deep clone of the input.
func CloneRefOfWhen(n *When) *When {
if n == nil {
return nil
}
out := *n
out.Cond = CloneExpr(n.Cond)
out.Val = CloneExpr(n.Val)
return &out
}
// EqualsRefOfWhen does deep equals between the two objects.
func EqualsRefOfWhen(a, b *When) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.Cond, b.Cond) &&
EqualsExpr(a.Val, b.Val)
}
// CloneRefOfWhere creates a deep clone of the input.
func CloneRefOfWhere(n *Where) *Where {
if n == nil {
return nil
}
out := *n
out.Expr = CloneExpr(n.Expr)
return &out
}
// EqualsRefOfWhere does deep equals between the two objects.
func EqualsRefOfWhere(a, b *Where) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type &&
EqualsExpr(a.Expr, b.Expr)
}
// CloneSliceOfRefOfColumnDefinition creates a deep clone of the input.
func CloneSliceOfRefOfColumnDefinition(n []*ColumnDefinition) []*ColumnDefinition {
res := make([]*ColumnDefinition, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfColumnDefinition(x))
}
return res
}
// EqualsSliceOfRefOfColumnDefinition does deep equals between the two objects.
func EqualsSliceOfRefOfColumnDefinition(a, b []*ColumnDefinition) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfColumnDefinition(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfTableOption creates a deep clone of the input.
func CloneRefOfTableOption(n *TableOption) *TableOption {
if n == nil {
return nil
}
out := *n
out.Value = CloneRefOfLiteral(n.Value)
out.Tables = CloneTableNames(n.Tables)
return &out
}
// EqualsRefOfTableOption does deep equals between the two objects.
func EqualsRefOfTableOption(a, b *TableOption) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Name == b.Name &&
a.String == b.String &&
EqualsRefOfLiteral(a.Value, b.Value) &&
EqualsTableNames(a.Tables, b.Tables)
}
// CloneSliceOfCollateAndCharset creates a deep clone of the input.
func CloneSliceOfCollateAndCharset(n []CollateAndCharset) []CollateAndCharset {
res := make([]CollateAndCharset, 0, len(n))
for _, x := range n {
res = append(res, CloneCollateAndCharset(x))
}
return res
}
// EqualsSliceOfCollateAndCharset does deep equals between the two objects.
func EqualsSliceOfCollateAndCharset(a, b []CollateAndCharset) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsCollateAndCharset(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfAlterOption creates a deep clone of the input.
func CloneSliceOfAlterOption(n []AlterOption) []AlterOption {
res := make([]AlterOption, 0, len(n))
for _, x := range n {
res = append(res, CloneAlterOption(x))
}
return res
}
// EqualsSliceOfAlterOption does deep equals between the two objects.
func EqualsSliceOfAlterOption(a, b []AlterOption) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsAlterOption(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfRefOfRenameTablePair creates a deep clone of the input.
func CloneSliceOfRefOfRenameTablePair(n []*RenameTablePair) []*RenameTablePair {
res := make([]*RenameTablePair, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfRenameTablePair(x))
}
return res
}
// EqualsSliceOfRefOfRenameTablePair does deep equals between the two objects.
func EqualsSliceOfRefOfRenameTablePair(a, b []*RenameTablePair) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfRenameTablePair(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfRefOfWhen creates a deep clone of the input.
func CloneSliceOfRefOfWhen(n []*When) []*When {
res := make([]*When, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfWhen(x))
}
return res
}
// EqualsSliceOfRefOfWhen does deep equals between the two objects.
func EqualsSliceOfRefOfWhen(a, b []*When) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfWhen(a[i], b[i]) {
return false
}
}
return true
}
// EqualsRefOfBool does deep equals between the two objects.
func EqualsRefOfBool(a, b *bool) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
// CloneRefOfBool creates a deep clone of the input.
func CloneRefOfBool(n *bool) *bool {
if n == nil {
return nil
}
out := *n
return &out
}
// CloneSliceOfRefOfUnionSelect creates a deep clone of the input.
func CloneSliceOfRefOfUnionSelect(n []*UnionSelect) []*UnionSelect {
res := make([]*UnionSelect, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfUnionSelect(x))
}
return res
}
// EqualsSliceOfRefOfUnionSelect does deep equals between the two objects.
func EqualsSliceOfRefOfUnionSelect(a, b []*UnionSelect) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfUnionSelect(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfColIdent creates a deep clone of the input.
func CloneSliceOfColIdent(n []ColIdent) []ColIdent {
res := make([]ColIdent, 0, len(n))
for _, x := range n {
res = append(res, CloneColIdent(x))
}
return res
}
// EqualsSliceOfColIdent does deep equals between the two objects.
func EqualsSliceOfColIdent(a, b []ColIdent) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsColIdent(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfColIdent creates a deep clone of the input.
func CloneRefOfColIdent(n *ColIdent) *ColIdent {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfColIdent does deep equals between the two objects.
func EqualsRefOfColIdent(a, b *ColIdent) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.val == b.val &&
a.lowered == b.lowered &&
a.at == b.at
}
// CloneColumnType creates a deep clone of the input.
func CloneColumnType(n ColumnType) ColumnType {
return *CloneRefOfColumnType(&n)
}
// EqualsColumnType does deep equals between the two objects.
func EqualsColumnType(a, b ColumnType) bool {
return a.Type == b.Type &&
a.Unsigned == b.Unsigned &&
a.Zerofill == b.Zerofill &&
a.Charset == b.Charset &&
a.Collate == b.Collate &&
EqualsRefOfColumnTypeOptions(a.Options, b.Options) &&
EqualsRefOfLiteral(a.Length, b.Length) &&
EqualsRefOfLiteral(a.Scale, b.Scale) &&
EqualsSliceOfString(a.EnumValues, b.EnumValues)
}
// CloneRefOfColumnTypeOptions creates a deep clone of the input.
func CloneRefOfColumnTypeOptions(n *ColumnTypeOptions) *ColumnTypeOptions {
if n == nil {
return nil
}
out := *n
out.Default = CloneExpr(n.Default)
out.OnUpdate = CloneExpr(n.OnUpdate)
out.Comment = CloneRefOfLiteral(n.Comment)
return &out
}
// EqualsRefOfColumnTypeOptions does deep equals between the two objects.
func EqualsRefOfColumnTypeOptions(a, b *ColumnTypeOptions) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.NotNull == b.NotNull &&
a.Autoincrement == b.Autoincrement &&
EqualsExpr(a.Default, b.Default) &&
EqualsExpr(a.OnUpdate, b.OnUpdate) &&
EqualsRefOfLiteral(a.Comment, b.Comment) &&
a.KeyOpt == b.KeyOpt
}
// CloneSliceOfString creates a deep clone of the input.
func CloneSliceOfString(n []string) []string {
res := make([]string, 0, len(n))
copy(res, n)
return res
}
// EqualsSliceOfString does deep equals between the two objects.
func EqualsSliceOfString(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneSliceOfRefOfIndexColumn creates a deep clone of the input.
func CloneSliceOfRefOfIndexColumn(n []*IndexColumn) []*IndexColumn {
res := make([]*IndexColumn, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfIndexColumn(x))
}
return res
}
// EqualsSliceOfRefOfIndexColumn does deep equals between the two objects.
func EqualsSliceOfRefOfIndexColumn(a, b []*IndexColumn) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfIndexColumn(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfRefOfIndexOption creates a deep clone of the input.
func CloneSliceOfRefOfIndexOption(n []*IndexOption) []*IndexOption {
res := make([]*IndexOption, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfIndexOption(x))
}
return res
}
// EqualsSliceOfRefOfIndexOption does deep equals between the two objects.
func EqualsSliceOfRefOfIndexOption(a, b []*IndexOption) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfIndexOption(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfJoinCondition creates a deep clone of the input.
func CloneRefOfJoinCondition(n *JoinCondition) *JoinCondition {
if n == nil {
return nil
}
out := *n
out.On = CloneExpr(n.On)
out.Using = CloneColumns(n.Using)
return &out
}
// EqualsRefOfJoinCondition does deep equals between the two objects.
func EqualsRefOfJoinCondition(a, b *JoinCondition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsExpr(a.On, b.On) &&
EqualsColumns(a.Using, b.Using)
}
// CloneTableAndLockTypes creates a deep clone of the input.
func CloneTableAndLockTypes(n TableAndLockTypes) TableAndLockTypes {
res := make(TableAndLockTypes, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfTableAndLockType(x))
}
return res
}
// EqualsTableAndLockTypes does deep equals between the two objects.
func EqualsTableAndLockTypes(a, b TableAndLockTypes) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfTableAndLockType(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfRefOfPartitionDefinition creates a deep clone of the input.
func CloneSliceOfRefOfPartitionDefinition(n []*PartitionDefinition) []*PartitionDefinition {
res := make([]*PartitionDefinition, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfPartitionDefinition(x))
}
return res
}
// EqualsSliceOfRefOfPartitionDefinition does deep equals between the two objects.
func EqualsSliceOfRefOfPartitionDefinition(a, b []*PartitionDefinition) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfPartitionDefinition(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfCharacteristic creates a deep clone of the input.
func CloneSliceOfCharacteristic(n []Characteristic) []Characteristic {
res := make([]Characteristic, 0, len(n))
for _, x := range n {
res = append(res, CloneCharacteristic(x))
}
return res
}
// EqualsSliceOfCharacteristic does deep equals between the two objects.
func EqualsSliceOfCharacteristic(a, b []Characteristic) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsCharacteristic(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfShowTablesOpt creates a deep clone of the input.
func CloneRefOfShowTablesOpt(n *ShowTablesOpt) *ShowTablesOpt {
if n == nil {
return nil
}
out := *n
out.Filter = CloneRefOfShowFilter(n.Filter)
return &out
}
// EqualsRefOfShowTablesOpt does deep equals between the two objects.
func EqualsRefOfShowTablesOpt(a, b *ShowTablesOpt) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Full == b.Full &&
a.DbName == b.DbName &&
EqualsRefOfShowFilter(a.Filter, b.Filter)
}
// CloneRefOfTableIdent creates a deep clone of the input.
func CloneRefOfTableIdent(n *TableIdent) *TableIdent {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfTableIdent does deep equals between the two objects.
func EqualsRefOfTableIdent(a, b *TableIdent) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.v == b.v
}
// CloneRefOfTableName creates a deep clone of the input.
func CloneRefOfTableName(n *TableName) *TableName {
if n == nil {
return nil
}
out := *n
out.Name = CloneTableIdent(n.Name)
out.Qualifier = CloneTableIdent(n.Qualifier)
return &out
}
// EqualsRefOfTableName does deep equals between the two objects.
func EqualsRefOfTableName(a, b *TableName) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableIdent(a.Name, b.Name) &&
EqualsTableIdent(a.Qualifier, b.Qualifier)
}
// CloneSliceOfRefOfIndexDefinition creates a deep clone of the input.
func CloneSliceOfRefOfIndexDefinition(n []*IndexDefinition) []*IndexDefinition {
res := make([]*IndexDefinition, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfIndexDefinition(x))
}
return res
}
// EqualsSliceOfRefOfIndexDefinition does deep equals between the two objects.
func EqualsSliceOfRefOfIndexDefinition(a, b []*IndexDefinition) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfIndexDefinition(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfRefOfConstraintDefinition creates a deep clone of the input.
func CloneSliceOfRefOfConstraintDefinition(n []*ConstraintDefinition) []*ConstraintDefinition {
res := make([]*ConstraintDefinition, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfConstraintDefinition(x))
}
return res
}
// EqualsSliceOfRefOfConstraintDefinition does deep equals between the two objects.
func EqualsSliceOfRefOfConstraintDefinition(a, b []*ConstraintDefinition) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfConstraintDefinition(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfVindexParam creates a deep clone of the input.
func CloneRefOfVindexParam(n *VindexParam) *VindexParam {
if n == nil {
return nil
}
out := *n
out.Key = CloneColIdent(n.Key)
return &out
}
// EqualsRefOfVindexParam does deep equals between the two objects.
func EqualsRefOfVindexParam(a, b *VindexParam) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Val == b.Val &&
EqualsColIdent(a.Key, b.Key)
}
// CloneSliceOfVindexParam creates a deep clone of the input.
func CloneSliceOfVindexParam(n []VindexParam) []VindexParam {
res := make([]VindexParam, 0, len(n))
for _, x := range n {
res = append(res, CloneVindexParam(x))
}
return res
}
// EqualsSliceOfVindexParam does deep equals between the two objects.
func EqualsSliceOfVindexParam(a, b []VindexParam) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsVindexParam(a[i], b[i]) {
return false
}
}
return true
}
// CloneCollateAndCharset creates a deep clone of the input.
func CloneCollateAndCharset(n CollateAndCharset) CollateAndCharset {
return *CloneRefOfCollateAndCharset(&n)
}
// EqualsCollateAndCharset does deep equals between the two objects.
func EqualsCollateAndCharset(a, b CollateAndCharset) bool {
return a.IsDefault == b.IsDefault &&
a.Value == b.Value &&
a.Type == b.Type
}
// CloneRefOfRenameTablePair creates a deep clone of the input.
func CloneRefOfRenameTablePair(n *RenameTablePair) *RenameTablePair {
if n == nil {
return nil
}
out := *n
out.FromTable = CloneTableName(n.FromTable)
out.ToTable = CloneTableName(n.ToTable)
return &out
}
// EqualsRefOfRenameTablePair does deep equals between the two objects.
func EqualsRefOfRenameTablePair(a, b *RenameTablePair) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableName(a.FromTable, b.FromTable) &&
EqualsTableName(a.ToTable, b.ToTable)
}
// CloneRefOfIndexColumn creates a deep clone of the input.
func CloneRefOfIndexColumn(n *IndexColumn) *IndexColumn {
if n == nil {
return nil
}
out := *n
out.Column = CloneColIdent(n.Column)
out.Length = CloneRefOfLiteral(n.Length)
return &out
}
// EqualsRefOfIndexColumn does deep equals between the two objects.
func EqualsRefOfIndexColumn(a, b *IndexColumn) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsColIdent(a.Column, b.Column) &&
EqualsRefOfLiteral(a.Length, b.Length) &&
a.Direction == b.Direction
}
// CloneRefOfIndexOption creates a deep clone of the input.
func CloneRefOfIndexOption(n *IndexOption) *IndexOption {
if n == nil {
return nil
}
out := *n
out.Value = CloneRefOfLiteral(n.Value)
return &out
}
// EqualsRefOfIndexOption does deep equals between the two objects.
func EqualsRefOfIndexOption(a, b *IndexOption) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Name == b.Name &&
a.String == b.String &&
EqualsRefOfLiteral(a.Value, b.Value)
}
// CloneRefOfTableAndLockType creates a deep clone of the input.
func CloneRefOfTableAndLockType(n *TableAndLockType) *TableAndLockType {
if n == nil {
return nil
}
out := *n
out.Table = CloneTableExpr(n.Table)
return &out
}
// EqualsRefOfTableAndLockType does deep equals between the two objects.
func EqualsRefOfTableAndLockType(a, b *TableAndLockType) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsTableExpr(a.Table, b.Table) &&
a.Lock == b.Lock
}
// CloneRefOfCollateAndCharset creates a deep clone of the input.
func CloneRefOfCollateAndCharset(n *CollateAndCharset) *CollateAndCharset {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfCollateAndCharset does deep equals between the two objects.
func EqualsRefOfCollateAndCharset(a, b *CollateAndCharset) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.IsDefault == b.IsDefault &&
a.Value == b.Value &&
a.Type == b.Type
} | go/vt/sqlparser/clone.go | 0.590425 | 0.406744 | clone.go | starcoder |
package main
import (
"strconv"
"strings"
)
const ALL_CHARS = "abcdefg"
// FindCountOfUniqueNumbers finds the count of unique numbers.
// Unique numbers being the keys for 1, 4, 7 and 8.
func FindCountOfUniqueNumbers(input []string) int {
count := 0
for _, s := range input {
split := strings.Split(s, " | ")
final := strings.Split(split[1], " ")
for _, num := range final {
len := len(num)
if len == 2 || len == 3 || len == 4 || len == 7 {
count++
}
}
}
return count
}
// ProcessInputsAndOutputs processes the inputs and outputs to a count of the
// output numbers.
// Returns the count of the output numbers.
func ProcessInputsAndOutputs(input []string) int {
count := 0
for _, s := range input {
split := strings.Split(s, " | ")
random := strings.Split(split[0], " ")
mapping := make(map[int]string, 10)
fives := make([]string, 0)
sixes := make([]string, 0)
for _, num := range random {
len := len(num)
switch len {
case 2:
mapping[1] = num
case 3:
mapping[7] = num
case 4:
mapping[4] = num
case 5:
fives = append(fives, num)
case 6:
sixes = append(sixes, num)
case 7:
mapping[8] = num
}
}
six, c, f := find6cf(mapping[1], sixes)
sixes = remove(sixes, six)
mapping[6] = six
two, three, five := parseFives(fives, c, f)
mapping[2] = two
mapping[3] = three
mapping[5] = five
zero, nine := parseZeroNine(sixes, five)
mapping[0] = zero
mapping[9] = nine
final := strings.Split(split[1], " ")
flipped := flipMap(mapping)
str := ""
for _, word := range final {
str = str + flipped[SortStringByCharacter(word)]
}
num, _ := strconv.Atoi(str)
count += num
}
return count
}
// find6cf Finds 6 'c' and 'f' by using the segments with 6 segments lit
// and the fact 6 is the only six segment number that doesn't have one
// part of the segments for 1. That being the 'c' segment.
// Returns six, c, f in that order.
func find6cf(one string, sixes []string) (string, rune, rune) {
chars := []rune(one)
for i, c := range chars {
for _, sixChars := range sixes {
if !strings.ContainsRune(sixChars, c) {
if i == 0 {
return sixChars, c, chars[1]
}
return sixChars, c, chars[0]
}
}
}
return "", 'c', 'f'
}
// parseFives parses all the 5 segment displays to map each one to the correct
// Number. 5 wont contain 'c', 2 wont contain 'f' and three will contain both.
// Returns two, three and five in that order.
func parseFives(fives []string, c rune, f rune) (string, string, string) {
var two string
var three string
var five string
for _, fiveChars := range fives {
if !strings.ContainsRune(fiveChars, c) {
five = fiveChars
} else if !strings.ContainsRune(fiveChars, f) {
two = fiveChars
} else {
three = fiveChars
}
}
return two, three, five
}
// parseZeroNine finds zero and nine using 5 because all the characters
// that make up 5 make up 9 but not zero.
// Returns Zero and Nine
func parseZeroNine(sixes []string, five string) (string, string) {
option := sixes[0]
for _, c := range []rune(five) {
if !strings.ContainsRune(option, c) {
return option, sixes[1]
}
}
return sixes[1], option
}
// flipMap flips the numbered keys to be a sorted map of the sorted
// input seqments to the string representation e.g. mapping[1] = fc
// would flip to be flipped[cf] = "1"
// Retruns the flipped map.
func flipMap(mapping map[int]string) map[string]string {
flipped := make(map[string]string, 10)
for key, value := range mapping {
sort := SortStringByCharacter(value)
flipped[sort] = strconv.Itoa(key)
}
return flipped
}
// Removes an element from the list
// Returns the list.
func remove(list []string, elem string) []string {
for i, s := range list {
if s == elem {
list[i] = list[len(list)-1]
return list[:len(list)-1]
}
}
return list
} | day8.go | 0.633297 | 0.50653 | day8.go | starcoder |
package ruler
import (
"reflect"
"fmt"
)
type node struct {
// name
Label string
// Value
Value interface{}
// operation code
op int
// kind
kind reflect.Kind
// chilren
node []*node
}
func nodeFromAny(label string, val interface{}) (r *node) {
v := ValueFormat(val)
switch v.(type) {
case int:
r = nodeFromInt(label, v.(int))
case bool:
r = nodeFromBool(label, v.(bool))
case float64:
r = nodeFromFloat(label, v.(float64))
case string:
r = nodeFromString(label, v.(string))
default:
r = &node{
Label: label,
Value: val,
}
}
return r
}
func nodeFromInt(label string, val int) *node {
return &node{
Label: label,
Value: val,
kind: reflect.Int,
}
}
func nodeFromFloat(label string, val float64) *node {
return &node{
Label: label,
Value: val,
kind: reflect.Float64,
}
}
func nodeFromBool(label string, val bool) *node {
return &node{
Label: label,
Value: val,
kind: reflect.Bool,
}
}
func nodeFromString(label string, val string) *node {
return &node{
Label: label,
Value: val,
kind: reflect.String,
}
}
func nodeFromIdent(op int, label string) *node {
return &node{
Label: label,
op: op,
}
}
func nodeFromNode(op int, ns ...*node) *node {
return nodeFromNode2(op, "", ns...)
}
func nodeFromNode2(op int, label string, ns ...*node) *node {
c := &node{
op: op,
Label: label,
kind: reflect.Slice,
}
c.node = append(c.node, ns...)
return c
}
func nodeFromFunc(op int, name string, ns ...*node) *node {
c := &node{
op: op,
Label: name,
kind: reflect.Func,
}
c.node = append(c.node, ns...)
return c
}
func (n *node) AppendNode(ns ...*node) *node {
n.node = append(n.node, ns...)
return n
}
func (r node) Len() int {
return len(r.node)
}
func calc(op int, l, r interface{}) *node {
var result interface{}
switch l.(type) {
case int:
m := l.(int)
n := r.(int)
switch op {
case '+':
result = m + n
case '-':
result = m - n
case '*':
result = m * n
case '/':
result = m / n
case '%':
result = m % n
case BITAND:
result = m & n
case BITOR:
result = m | n
case LSS:
result = m < n
case LEQ:
result = m <= n
case GTR:
result = m > n
case GEQ:
result = m >= n
}
case float64:
m := l.(float64)
n := r.(float64)
switch op {
case '+':
result = m + n
case '-':
result = m - n
case '*':
result = m * n
case '/':
result = m / n
case LSS:
result = m < n
case LEQ:
result = m <= n
case GTR:
result = m > n
case GEQ:
result = m >= n
}
case string:
m := l.(string)
n := r.(string)
switch op {
case '+':
result = m + n
case LSS:
result = m < n
case LEQ:
result = m <= n
case GTR:
result = m > n
case GEQ:
result = m >= n
}
}
return nodeFromAny("", result)
// throwException(500, "不支持的运算类型 %T %d[%s] %T, result = %T, %v", l, op, yySymNames[yyXLAT[op]], r, result, result)
return nil
}
func (r *node) Exec(dp *DataPackage) *node {
switch r.op {
case IDENT:
if v, ok := dp.GetAttr(r.Label); ok {
return nodeFromAny(r.Label, v)
} else {
throwException(E_DATA_INVALID, "找不到 %s", r.Label)
}
case ARRAY:
if v, ok := dp.GetDeepAttr(r.Label); ok {
return nodeFromAny(r.Label, v)
} else {
throwException(E_DATA_INVALID, "找不到 %s", r.Label)
}
case NEG:
var val interface{}
switch r.kind {
case reflect.Int:
val = -r.Value.(int)
case reflect.Float64:
val = -r.Value.(float64)
default:
throwException(500, "一元减不支持的类型 %T", r.Value)
}
return nodeFromAny("", val)
case EQU:
r, v := r.node[0].Exec(dp), r.node[1].Exec(dp)
return nodeFromBool("", r.Value == v.Value)
case NEQ:
r, v := r.node[0].Exec(dp), r.node[1].Exec(dp)
return nodeFromBool("", r.Value != v.Value)
case '+', '-', '*', '/', '%', LSS, LEQ, GTR, GEQ:
left, right := r.node[0].Exec(dp), r.node[1].Exec(dp)
if left.kind != right.kind {
switch left.kind {
case reflect.Int:
if right.kind == reflect.Float64 {
left.Value = float64(left.Value.(int))
} else {
right.Value = ConvertInt(right.Value)
}
case reflect.Float64:
right.Value = ConvertFloat(right.Value)
case reflect.String:
right.Value = ConvertString(right.Value)
default:
throwException(E_DATA_INVALID, "错误的数据类型: %T %s %T", left.Value, yySymNames[yyXLAT[r.op]], right.Value)
}
}
return calc(r.op, left.Value, right.Value)
case BITAND, BITOR:
left, right := r.node[0].Exec(dp).Value, r.node[1].Exec(dp).Value
return calc(r.op, ConvertInt(left), ConvertInt(right))
case AND:
return nodeFromBool("", ConvertBool(r.node[0].Exec(dp).Value) && ConvertBool(r.node[1].Exec(dp).Value))
case OR:
return nodeFromBool("", ConvertBool(r.node[0].Exec(dp).Value) || ConvertBool(r.node[1].Exec(dp).Value))
case FUNC:
switch r.Value {
case "int":
return nodeFromInt("", ConvertInt(r.node[0].Exec(dp).Value))
case "float":
return nodeFromFloat("", ConvertFloat(r.node[0].Exec(dp).Value))
case "bool":
return nodeFromBool("", ConvertBool(r.node[0].Exec(dp).Value))
case "string":
return nodeFromString("", ConvertString(r.node[0].Exec(dp).Value))
default:
var args []interface{}
for _, node := range r.node {
args = append(args, node.Exec(dp).Value)
}
res := Call(r.Value.(string), args...)
return nodeFromAny("", res)
}
case FILTER:
n := r.node[0]
name := n.Label
data := reflect.ValueOf(n.Exec(dp).Value)
if data.Kind() != reflect.Slice {
throwException(500, "%s 不是数组数据,无法过滤", name)
}
size := data.Len()
res := make([]bool, size)
for i := 0; i < size; i++ {
dp.Push(data.Index(i).Interface())
res[i] = ConvertBool(r.node[1].Exec(dp).Value)
dp.Pop()
}
return nodeFromAny("", res)
case LISTA:
if ConvertBool(r.node[0].Exec(dp).Value) {
return r.node[1].Exec(dp)
} else {
return nodeFromBool("", false)
}
case LISTO:
if ConvertBool(r.node[0].Exec(dp).Value) {
return nodeFromBool("", true)
} else {
return r.node[1].Exec(dp)
}
case IN:
val := r.node[0].Exec(dp).Value
for _, v := range r.node[1].node {
if val == v.Exec(dp).Value {
return nodeFromBool("", r.Label == "i")
}
}
return nodeFromBool("", r.Label == "n")
}
return r
}
func (r node) Debug() {
r.debug(0)
}
func (r node) debug(lev int) {
var (
v string
ok bool
)
pre := fmt.Sprintf("%*s", 4*lev, "")
typeName := map[reflect.Kind]string{
reflect.Invalid: "ident",
reflect.Int: "int",
reflect.Float64: "float64",
reflect.Bool: "bool",
reflect.String: "string",
reflect.Func: "func",
}
var op string
if m, ok := yyXLAT[r.op]; ok {
op = yySymNames[m]
} else {
op = "NA"
}
if v, ok = typeName[r.kind]; ok {
fmt.Printf("%s%s: op[%s] %v %v\n", pre, v, op, r.Label, r.Value)
} else if r.kind == reflect.Slice {
fmt.Printf("%sSlice: op[%s] %+v\n", pre, yySymNames[yyXLAT[r.op]], r.node)
}
for i := 0; i < r.Len(); i++ {
r.node[i].debug(lev + 1)
}
} | node.go | 0.553264 | 0.445107 | node.go | starcoder |
package array
import(
"sort"
)
/*
# https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/776/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
[-4,-1,-1,0,1,2]
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Hint #1
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand!
Hint #2
For the two-sum problem, if we fix one of the numbers, say
x
, we have to scan the entire array to find the next number
y
which is
value - x
where value is the input parameter. Can we change our array somehow so that this search becomes faster?
Hint #3
The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
*/
func ThreeSum(nums []int) [][]int {
return threeSum(nums)
}
func threeSum(nums []int) [][]int {
if nums == nil || len(nums) < 3 {
return nil
}
sort.Ints(nums)
var result [][]int
for povit := 0; povit <= len(nums)-3; povit++ {
if povit!=0&&nums[povit]==nums[povit-1]{
continue
}
start, end := povit+1, len(nums)-1
for start < end {
if nums[start]+nums[end]+nums[povit] == 0 {
result = append(result, []int{nums[povit], nums[start], nums[end]})
start++
end--
} else if nums[povit]+nums[start]+nums[end] > 0 {
end--
} else {
start++
}
}
}
LOOP:
// 去重
if len(result)>=2{
for i:=0;i<len(result)-1;i++{
var equal bool
for j:=range result[i]{
if result[i][j]==result[i+1][j]{
equal=true
}else{
equal=false
break
}
}
if equal{
result=append(result[:i],result[i+1:]...)
goto LOOP
}
}
}
return result
} | interview/medium/array/3sum.go | 0.579638 | 0.546073 | 3sum.go | starcoder |
package parameters
// parameters which define a 1-d impact oscillator system with no damping between impacts
import (
"fmt"
"math")
type Parameters struct {
ForcingFrequency float64
CoefficientOfRestitution float64
ObstacleOffset float64
Gamma float64
MaximumPeriods uint // maximum forcing periods to detect impact
}
type ZeroForcingFrequencyError float64
func (f ZeroForcingFrequencyError) Error() string {
return "Forcing frequency cannot be zero"
}
type NegativeForcingFrequencyError float64
func (f NegativeForcingFrequencyError) Error() string {
return fmt.Sprintf("The model cannot handle negative forcing frequency %g", f)
}
type ResonantForcingFrequencyError float64
func (f ResonantForcingFrequencyError) Error() string {
return "A forcing frequency of 1 is a resonant case with unbounded solutions"
}
type LargeCoefficientOfRestitutionError float64
func (r LargeCoefficientOfRestitutionError) Error() string {
return fmt.Sprintf("A coefficient of restitution of %g > 1 will generate unbounded solutions", r)
}
type NegativeCoefficientOfRestitutionError float64
func (r NegativeCoefficientOfRestitutionError) Error() string {
return fmt.Sprintf("A negative coefficient of restitution %g will generate unphysical solutions", r)
}
type ZeroMaxmimumPeriodsError uint
func (n ZeroMaxmimumPeriodsError) Error() string {
return "maximum forcing periods to detect impact must be > 0"
}
func NewParameters(frequency float64, offset float64, r float64, maxPeriods uint) (*Parameters, []error) {
errorList := make([]error, 6)
i := 0
if frequency == 0.0 {
errorList[i] = ZeroForcingFrequencyError(frequency)
i++
}
if 0.0 > frequency {
errorList[i] = NegativeForcingFrequencyError(frequency)
i++
}
if frequency == 1.0 {
errorList[i] = ResonantForcingFrequencyError(frequency)
i++
}
if 1.0 < r {
errorList[i] = LargeCoefficientOfRestitutionError(r)
i++
}
if 0.0 > r {
errorList[i] = NegativeCoefficientOfRestitutionError(r)
i++
}
if maxPeriods == 0 {
errorList[i] = ZeroMaxmimumPeriodsError(maxPeriods)
i++
}
errorList = errorList[:i]
if i > 0 {
return nil, errorList
} else {
return &Parameters{ForcingFrequency: frequency, ObstacleOffset: offset, CoefficientOfRestitution: r, MaximumPeriods: maxPeriods, Gamma: 1.0/(1.0 - math.Pow(frequency, 2))}, errorList
}
} | dynamics/parameters/parameters.go | 0.874761 | 0.658692 | parameters.go | starcoder |
package simulations
import (
"context"
"time"
"github.com/matrix/go-matrix/p2p/discover"
)
// Simulation provides a framework for running actions in a simulated network
// and then waiting for expectations to be met
type Simulation struct {
network *Network
}
// NewSimulation returns a new simulation which runs in the given network
func NewSimulation(network *Network) *Simulation {
return &Simulation{
network: network,
}
}
// Run performs a step of the simulation by performing the step's action and
// then waiting for the step's expectation to be met
func (s *Simulation) Run(ctx context.Context, step *Step) (result *StepResult) {
result = newStepResult()
result.StartedAt = time.Now()
defer func() { result.FinishedAt = time.Now() }()
// watch network events for the duration of the step
stop := s.watchNetwork(result)
defer stop()
// perform the action
if err := step.Action(ctx); err != nil {
result.Error = err
return
}
// wait for all node expectations to either pass, error or timeout
nodes := make(map[discover.NodeID]struct{}, len(step.Expect.Nodes))
for _, id := range step.Expect.Nodes {
nodes[id] = struct{}{}
}
for len(result.Passes) < len(nodes) {
select {
case id := <-step.Trigger:
// skip if we aren't checking the node
if _, ok := nodes[id]; !ok {
continue
}
// skip if the node has already passed
if _, ok := result.Passes[id]; ok {
continue
}
// run the node expectation check
pass, err := step.Expect.Check(ctx, id)
if err != nil {
result.Error = err
return
}
if pass {
result.Passes[id] = time.Now()
}
case <-ctx.Done():
result.Error = ctx.Err()
return
}
}
return
}
func (s *Simulation) watchNetwork(result *StepResult) func() {
stop := make(chan struct{})
done := make(chan struct{})
events := make(chan *Event)
sub := s.network.Events().Subscribe(events)
go func() {
defer close(done)
defer sub.Unsubscribe()
for {
select {
case event := <-events:
result.NetworkEvents = append(result.NetworkEvents, event)
case <-stop:
return
}
}
}()
return func() {
close(stop)
<-done
}
}
type Step struct {
// Action is the action to perform for this step
Action func(context.Context) error
// Trigger is a channel which receives node ids and triggers an
// expectation check for that node
Trigger chan discover.NodeID
// Expect is the expectation to wait for when performing this step
Expect *Expectation
}
type Expectation struct {
// Nodes is a list of nodes to check
Nodes []discover.NodeID
// Check checks whether a given node meets the expectation
Check func(context.Context, discover.NodeID) (bool, error)
}
func newStepResult() *StepResult {
return &StepResult{
Passes: make(map[discover.NodeID]time.Time),
}
}
type StepResult struct {
// Error is the error encountered whilst running the step
Error error
// StartedAt is the time the step started
StartedAt time.Time
// FinishedAt is the time the step finished
FinishedAt time.Time
// Passes are the timestamps of the successful node expectations
Passes map[discover.NodeID]time.Time
// NetworkEvents are the network events which occurred during the step
NetworkEvents []*Event
} | p2p/simulations/simulation.go | 0.705684 | 0.47244 | simulation.go | starcoder |
package SetSimilaritySearch
import (
"errors"
"sort"
)
// SearchIndex is a data structure supports set similarity search queries.
// The algorithm is a combination of the prefix filter and position filter
// techniques.
type SearchIndex struct {
threshold float64
simFunc function
overlapThresholdFunc overlapThresholdFunction
overlapIndexThresholdFunc overlapThresholdFunction
positionFilterFunc positionFilter
sets [][]int
postingLists map[int][]postingListEntry
}
// NewSearchIndex builds a search index on the transformed sets given
// the similarity function and threshold.
// Currently supported similarity functions are "jaccard", "cosine"
// and "containment".
func NewSearchIndex(sets [][]int, similarityFunctionName string,
similarityThreshold float64) (*SearchIndex, error) {
if len(sets) == 0 {
return nil, errors.New("input sets cannot be empty")
}
if similarityThreshold < 0 || similarityThreshold > 1.0 {
return nil, errors.New("input similarityThreshold must be in the range [0, 1]")
}
si := SearchIndex{
threshold: similarityThreshold,
sets: sets,
postingLists: make(map[int][]postingListEntry),
}
if f, exists := similarityFuncs[similarityFunctionName]; exists {
si.simFunc = f
} else {
return nil, errors.New("input similarityFunctionName is not supported")
}
si.overlapThresholdFunc = overlapThresholdFuncs[similarityFunctionName]
si.overlapIndexThresholdFunc = overlapIndexThresholdFuncs[similarityFunctionName]
si.positionFilterFunc = positionFilterFuncs[similarityFunctionName]
// Index transformed sets.
for i, s := range sets {
t := si.overlapIndexThresholdFunc(len(s), si.threshold)
prefixSize := len(s) - t + 1
prefix := s[:prefixSize]
for j, token := range prefix {
if _, exists := si.postingLists[token]; !exists {
si.postingLists[token] = make([]postingListEntry, 0)
}
si.postingLists[token] = append(si.postingLists[token],
postingListEntry{i, j, len(s)})
}
}
// Sort each posting lists by set size for length filter.
for token, postingList := range si.postingLists {
sort.Slice(si.postingLists[token], func(i, j int) bool {
return postingList[i].setSize < postingList[j].setSize
})
}
return &si, nil
}
// SearchResult corresponding a set found from a query.
// It contains the index of the set found and the similarity to the query set.
type SearchResult struct {
X int
Similarity float64
}
// Query probes the search index for sets whose similarity with the query set
// are above the given similarity threshold specified for the index.
// This function takes a transformed set and
// returns a slice of SearchResult that contain the indexes of the sets found.
func (si *SearchIndex) Query(s []int) []SearchResult {
t := si.overlapThresholdFunc(len(s), si.threshold)
prefixSize := len(s) - t + 1
prefix := s[:prefixSize]
// Find candidates using tokens in the prefix.
candidates := make([]int, 0)
for p1, token := range prefix {
// TODO: use binary search to find starting position.
// TODO: stops at an ending position for symmetric function.
for _, entry := range si.postingLists[token] {
if si.positionFilterFunc(s, si.sets[entry.setIndex], p1,
entry.tokenPosition, si.threshold) {
candidates = append(candidates, entry.setIndex)
}
}
}
// Sort and iterate through candidate indexes to verify
// pairs.
// TODO: optimize using partial overlaps.
sort.Ints(candidates)
results := make([]SearchResult, 0)
prevCandidate := -1
for _, x2 := range candidates {
// Skip seen candidate.
if x2 == prevCandidate {
continue
}
prevCandidate = x2
// Compute the exact similarity of this candidate
sim := si.simFunc(s, si.sets[x2])
if sim < si.threshold {
continue
}
results = append(results, SearchResult{x2, sim})
}
return results
} | search.go | 0.599485 | 0.518729 | search.go | starcoder |
package shp
import (
"fmt"
"github.com/golang/geo/r1"
"github.com/golang/geo/s1"
"github.com/golang/geo/s2"
)
// Validator is used to validate shapes inside a shp file.
type Validator struct {
box s2.Rect
}
// MakeValidator creates a new Validator based on the constraints of a particular shp file.
func MakeValidator(box BoundingBox) (Validator, error) {
rect, err := boxToRect(box)
if err != nil {
return Validator{}, err
}
return Validator{
box: rect,
}, nil
}
// Validate the Point by checking that it is within the shp file bounding box.
func (p Point) Validate(v Validator) error {
ll := pointToLatLng(p)
if p.box != nil {
box, err := boxToRect(*p.box)
if err != nil {
return err
}
if !box.ContainsLatLng(ll) {
return fmt.Errorf("point %s is not in own bounding box '%s'", ll.String(), box.String())
}
}
if !v.box.ContainsLatLng(ll) {
return fmt.Errorf("point '%s' is not in file bounding box '%s'", ll.String(), v.box.String())
}
return nil
}
// Validate the Polyline.
func (p Polyline) Validate(v Validator) error {
if len(p.Parts) < 1 {
return fmt.Errorf("must contain at least 1 part")
}
for _, part := range p.Parts {
latlngs := make([]s2.LatLng, len(part))
for i, point := range part {
if err := point.Validate(v); err != nil {
return err
}
latlngs[i] = pointToLatLng(point)
}
line := s2.PolylineFromLatLngs(latlngs)
if line.NumEdges() < 1 {
return fmt.Errorf("part must have at least 1 edge")
}
}
return nil
}
// Validate the Polygon.
func (p Polygon) Validate(v Validator) error {
return (Polyline)(p).Validate(v)
}
func boxToRect(box BoundingBox) (s2.Rect, error) {
tl := s2.LatLngFromDegrees(box.MaxY, box.MinX)
br := s2.LatLngFromDegrees(box.MinY, box.MaxX)
rect := s2.Rect{
Lat: r1.Interval{Lo: br.Lat.Radians(), Hi: tl.Lat.Radians()},
Lng: s1.Interval{Lo: tl.Lng.Radians(), Hi: br.Lng.Radians()},
}
if !rect.IsValid() {
return s2.Rect{}, fmt.Errorf("invalid box")
}
return rect, nil
}
func pointToLatLng(p Point) s2.LatLng {
return s2.LatLngFromDegrees(p.Y, p.X)
} | shp/validator.go | 0.812904 | 0.534673 | validator.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.