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 entropy import ( kanzi "github.com/flanglet/kanzi-go" ) // AdaptiveProbMap maps a probability and a context to a new probability // that the next bit will be 1. After each guess, it updates // its state to improve future predictions. type AdaptiveProbMap struct { index int // last prob, context rate uint // update rate data []uint16 // prob, context -> prob } // LinearAdaptiveProbMap maps a probability and a context into a new probability // using linear interpolation of probabilities type LinearAdaptiveProbMap AdaptiveProbMap // LogisticAdaptiveProbMap maps a probability and a context into a new probability // using interpolation in the logistic domain type LogisticAdaptiveProbMap AdaptiveProbMap // FastLogisticAdaptiveProbMap is similar to LogisticAdaptiveProbMap but works // faster at the expense of some accuracy type FastLogisticAdaptiveProbMap AdaptiveProbMap func newLogisticAdaptiveProbMap(n, rate uint) (*LogisticAdaptiveProbMap, error) { this := &LogisticAdaptiveProbMap{} this.data = make([]uint16, n*33) this.rate = rate for j := 0; j <= 32; j++ { this.data[j] = uint16(kanzi.Squash((j-16)<<7) << 4) } for i := uint(1); i < n; i++ { copy(this.data[i*33:], this.data[0:33]) } return this, nil } // get returns improved prediction given current bit, prediction and context func (this *LogisticAdaptiveProbMap) get(bit int, pr int, ctx int) int { // Update probability based on error and learning rate g := (-bit & 65528) + (bit << this.rate) this.data[this.index+1] += uint16((g - int(this.data[this.index+1])) >> this.rate) this.data[this.index] += uint16((g - int(this.data[this.index])) >> this.rate) pr = kanzi.STRETCH[pr] // Find index: 33*ctx + quantized prediction in [0..32] this.index = ((pr + 2048) >> 7) + 33*ctx // Return interpolated probability w := pr & 127 return (int(this.data[this.index+1])*w + int(this.data[this.index])*(128-w)) >> 11 } func newFastLogisticAdaptiveProbMap(n, rate uint) (*FastLogisticAdaptiveProbMap, error) { this := &FastLogisticAdaptiveProbMap{} this.data = make([]uint16, n*32) this.rate = rate for j := 0; j < 32; j++ { this.data[j] = uint16(kanzi.Squash((j-16)<<7) << 4) } for i := uint(1); i < n; i++ { copy(this.data[i*32:], this.data[0:32]) } return this, nil } // get returns improved prediction given current bit, prediction and context func (this *FastLogisticAdaptiveProbMap) get(bit int, pr int, ctx int) int { // Update probability based on error and learning rate g := (-bit & 65528) + (bit << this.rate) this.data[this.index] += uint16((g - int(this.data[this.index])) >> this.rate) this.index = ((kanzi.STRETCH[pr] + 2048) >> 7) + 32*ctx return int(this.data[this.index]) >> 4 } func newLinearAdaptiveProbMap(n, rate uint) (*LinearAdaptiveProbMap, error) { this := &LinearAdaptiveProbMap{} this.data = make([]uint16, n*65) this.rate = rate for j := 0; j <= 64; j++ { this.data[j] = uint16(j<<6) << 4 } for i := uint(1); i < n; i++ { copy(this.data[i*65:], this.data[0:65]) } return this, nil } // get returns improved prediction given current bit, prediction and context func (this *LinearAdaptiveProbMap) get(bit int, pr int, ctx int) int { // Update probability based on error and learning rate g := (-bit & 65528) + (bit << this.rate) this.data[this.index+1] += uint16((g - int(this.data[this.index+1])) >> this.rate) this.data[this.index] += uint16((g - int(this.data[this.index])) >> this.rate) // Find index: 65*ctx + quantized prediction in [0..64] this.index = (pr >> 6) + 65*ctx // Return interpolated probability w := pr & 127 return (int(this.data[this.index+1])*w + int(this.data[this.index])*(128-w)) >> 11 }
entropy/AdaptiveProbMap.go
0.789802
0.704262
AdaptiveProbMap.go
starcoder
package forGraphBLASGo func VectorEWiseMultBinaryOp[Dw, Du, Dv any](w *Vector[Dw], mask *Vector[bool], accum BinaryOp[Dw, Dw, Dw], op BinaryOp[Dw, Du, Dv], u *Vector[Du], v *Vector[Dv], desc Descriptor) error { size, err := w.Size() if err != nil { return err } if err = u.expectSize(size); err != nil { return err } if err = v.expectSize(size); err != nil { return err } maskAsStructure, err := vectorMask(mask, size) if err != nil { return err } w.ref = newVectorReference[Dw](newComputedVector[Dw]( size, w.ref, maskAsStructure, accum, newVectorEWiseMultBinaryOp[Dw, Du, Dv](op, u.ref, v.ref), desc, ), -1) return nil } func VectorEWiseMultMonoid[D any](w *Vector[D], mask *Vector[bool], accum BinaryOp[D, D, D], op Monoid[D], u, v *Vector[D], desc Descriptor) error { return VectorEWiseMultBinaryOp(w, mask, accum, op.operator(), u, v, desc) } func VectorEWiseMultSemiring[Dw, Du, Dv any](w *Vector[Dw], mask *Vector[bool], accum BinaryOp[Dw, Dw, Dw], op Semiring[Dw, Du, Dv], u *Vector[Du], v *Vector[Dv], desc Descriptor) error { return VectorEWiseMultBinaryOp(w, mask, accum, op.multiplication(), u, v, desc) } func VectorEWiseAddBinaryOp[D any](w *Vector[D], mask *Vector[bool], accum, op BinaryOp[D, D, D], u, v *Vector[D], desc Descriptor) error { size, err := w.Size() if err != nil { return err } if err = u.expectSize(size); err != nil { return err } if err = v.expectSize(size); err != nil { return err } maskAsStructure, err := vectorMask(mask, size) if err != nil { return err } w.ref = newVectorReference[D](newComputedVector[D]( size, w.ref, maskAsStructure, accum, newVectorEWiseAddBinaryOp[D](op, u.ref, v.ref), desc, ), -1) return nil } func VectorEWiseAddMonoid[D any](w *Vector[D], mask *Vector[bool], accum BinaryOp[D, D, D], op Monoid[D], u, v *Vector[D], desc Descriptor) error { return VectorEWiseAddBinaryOp(w, mask, accum, op.operator(), u, v, desc) } func VectorEWiseAddSemiring[D, Din1, Din2 any](w *Vector[D], mask *Vector[bool], accum BinaryOp[D, D, D], op Semiring[D, Din1, Din2], u, v *Vector[D], desc Descriptor) error { return VectorEWiseAddBinaryOp(w, mask, accum, op.addition().operator(), u, v, desc) } func MatrixEWiseMultBinaryOp[DC, DA, DB any](C *Matrix[DC], mask *Matrix[bool], accum BinaryOp[DC, DC, DC], op BinaryOp[DC, DA, DB], A *Matrix[DA], B *Matrix[DB], desc Descriptor) error { nrows, ncols, err := C.Size() if err != nil { return err } AIsTran, err := A.expectSizeTran(nrows, ncols, desc, Inp0) if err != nil { return err } BIsTran, err := B.expectSizeTran(nrows, ncols, desc, Inp1) if err != nil { return err } maskAsStructure, err := matrixMask(mask, nrows, ncols) if err != nil { return err } C.ref = newMatrixReference[DC](newComputedMatrix[DC]( nrows, ncols, C.ref, maskAsStructure, accum, newMatrixEWiseMultBinaryOp[DC, DA, DB](op, maybeTran(A.ref, AIsTran), maybeTran(B.ref, BIsTran)), desc, ), -1) return nil } func MatrixEWiseMultMonoid[D any](C *Matrix[D], mask *Matrix[bool], accum BinaryOp[D, D, D], op Monoid[D], A, B *Matrix[D], desc Descriptor) error { return MatrixEWiseMultBinaryOp(C, mask, accum, op.operator(), A, B, desc) } func MatrixEWiseMultSemiring[DC, DA, DB any](C *Matrix[DC], mask *Matrix[bool], accum BinaryOp[DC, DC, DC], op Semiring[DC, DA, DB], A *Matrix[DA], B *Matrix[DB], desc Descriptor) error { return MatrixEWiseMultBinaryOp(C, mask, accum, op.multiplication(), A, B, desc) } func MatrixEWiseAddBinaryOp[D any](C *Matrix[D], mask *Matrix[bool], accum, op BinaryOp[D, D, D], A, B *Matrix[D], desc Descriptor) error { nrows, ncols, err := C.Size() if err != nil { return err } AIsTran, err := A.expectSizeTran(nrows, ncols, desc, Inp0) if err != nil { return err } BIsTran, err := B.expectSizeTran(nrows, ncols, desc, Inp1) if err != nil { return err } maskAsStructure, err := matrixMask(mask, nrows, ncols) if err != nil { return err } C.ref = newMatrixReference[D](newComputedMatrix[D]( nrows, ncols, C.ref, maskAsStructure, accum, newMatrixEWiseAddBinaryOp[D](op, maybeTran(A.ref, AIsTran), maybeTran(B.ref, BIsTran)), desc, ), -1) return nil } func MatrixEWiseAddMonoid[D any](C *Matrix[D], mask *Matrix[bool], accum BinaryOp[D, D, D], op Monoid[D], A, B *Matrix[D], desc Descriptor) error { return MatrixEWiseAddBinaryOp(C, mask, accum, op.operator(), A, B, desc) } func MatrixEWiseAddSemiring[D, Din1, Din2 any](C *Matrix[D], mask *Matrix[bool], accum BinaryOp[D, D, D], op Semiring[D, Din1, Din2], A, B *Matrix[D], desc Descriptor) error { return MatrixEWiseAddBinaryOp(C, mask, accum, op.addition().operator(), A, B, desc) }
api_EWise.go
0.745028
0.72086
api_EWise.go
starcoder
package test import ( "bytes" "net/http/httptest" "os" "strings" "testing" "time" ) // StrEquals tests two strings for equality and fails t if they are not equal func StrEquals(t *testing.T, expected string, actual string) { if actual != expected { t.Fatalf("expected %s, got %s", expected, actual) } } // StrContains tests if substr is contained in s and fails t if it is not func StrContains(t *testing.T, s string, substr string) { if !strings.Contains(s, substr) { t.Fatalf("expected %s to be contained in string, but it wasn't: %s", substr, s) } } // Int64Equals tests if two int64s match and fails t if they are not equal func Int64Equals(t *testing.T, expected int64, actual int64) { if actual != expected { t.Fatalf("expected %d, got %d", expected, actual) } } // BoolEquals tests if two bools match and fails t if they are not equal func BoolEquals(t *testing.T, expected bool, actual bool) { if actual != expected { t.Fatalf("expected %t, got %t", expected, actual) } } // BytesEquals tests if two byte arrays match and fails t if they are not equal func BytesEquals(t *testing.T, expected []byte, actual []byte) { if !bytes.Equal(actual, expected) { t.Fatalf("expected %x, got %x", expected, actual) } } // DurationEquals tests if two durations match and fails t if they are not equal func DurationEquals(t *testing.T, expected time.Duration, actual time.Duration) { if actual != expected { t.Fatalf("expected %d, got %d", expected, actual) } } // FileNotExist asserts that a file does not exist and fails t if it does func FileNotExist(t *testing.T, filename string) { if stat, _ := os.Stat(filename); stat != nil { t.Fatalf("expected file %s to not exist, but it does", filename) } } // FileExist asserts that a file exists and fails t if it does not func FileExist(t *testing.T, filename string) { if stat, _ := os.Stat(filename); stat == nil { t.Fatalf("expected file %s to exist, but it does not", filename) } } // Response tests if a HTTP response status code and body match the expected values and fails t if they do not func Response(t *testing.T, rr *httptest.ResponseRecorder, status int, body string) { Status(t, rr, status) Body(t, rr, body) } // Status tests if a HTTP response status code matches the expected values and fails t if it does not func Status(t *testing.T, rr *httptest.ResponseRecorder, status int) { if rr.Code != status { t.Errorf("unexpected status code: got %v want %v", rr.Code, status) } } // Body tests if a HTTP response body matches the expected values and fails t if it does not func Body(t *testing.T, rr *httptest.ResponseRecorder, body string) { if strings.TrimSpace(rr.Body.String()) != strings.TrimSpace(body) { t.Errorf("unexpected body: got %v want %v", strings.TrimSpace(rr.Body.String()), strings.TrimSpace(body)) } }
test/assert.go
0.565779
0.498535
assert.go
starcoder
package data import ( "gogen/matchers" "time" ) type Subject struct { ID string Name string DOB time.Time Convictions []*DOJRow seenConvictions map[string]bool PC290Registration bool CyclesWithProp64Charges map[string]bool CaseNumbers map[string][]string IsDeceased bool } func (subject *Subject) PushRow(row DOJRow, eligibilityFlow EligibilityFlow) { if subject.ID == "" { subject.ID = row.SubjectID subject.Name = row.Name subject.DOB = row.DOB subject.seenConvictions = make(map[string]bool) subject.CyclesWithProp64Charges = make(map[string]bool) subject.CaseNumbers = make(map[string][]string) } if row.WasConvicted && subject.seenConvictions[row.CountOrder] { lastConviction := subject.Convictions[len(subject.Convictions)-1] newEndDate := lastConviction.SentenceEndDate.Add(row.SentencePartDuration) lastConviction.SentenceEndDate = newEndDate } if row.Type == "DECEASED" { subject.IsDeceased = true } if row.Type == "COURT ACTION" && row.OFN != "" { subject.CaseNumbers[row.CountOrder[0:6]] = setAppend(subject.CaseNumbers[row.CountOrder[0:6]], row.OFN) } if row.IsPC290Registration { subject.PC290Registration = true } if row.WasConvicted && !subject.seenConvictions[row.CountOrder] { row.HasProp64ChargeInCycle = subject.CyclesWithProp64Charges[row.CountOrder[0:3]] subject.Convictions = append(subject.Convictions, &row) subject.seenConvictions[row.CountOrder] = true } if matchers.IsProp64Charge(row.CodeSection) { subject.CyclesWithProp64Charges[row.CountOrder[0:3]] = true for _, conviction := range subject.Convictions { if conviction.CountOrder[0:3] == row.CountOrder[0:3] { conviction.HasProp64ChargeInCycle = true } } } } func (subject *Subject) MostRecentConvictionDate() time.Time { var latestDate time.Time for _, conviction := range subject.Convictions { if conviction.DispositionDate.After(latestDate) { latestDate = conviction.DispositionDate } } return latestDate } func (subject *Subject) SuperstrikeCodeSections() []string { var result []string for _, row := range subject.Convictions { if IsSuperstrike(row.CodeSection) { result = append(result, row.CodeSection) } } return result } func (subject *Subject) PC290CodeSections() []string { var result []string for _, row := range subject.Convictions { if IsPC290(row.CodeSection) { result = append(result, row.CodeSection) } } return result } func (subject *Subject) Prop64ConvictionsBySection() (int, int, int, int, int) { convictionCountBySection := make(map[string]int) for _, conviction := range subject.Convictions { matched, codeSection := matchers.ExtractProp64Section(conviction.CodeSection) if matched { convictionCountBySection[codeSection]++ } } return convictionCountBySection["11357"] + convictionCountBySection["11358"] + convictionCountBySection["11359"] + convictionCountBySection["11360"], convictionCountBySection["11357"], convictionCountBySection["11358"], convictionCountBySection["11359"], convictionCountBySection["11360"] } func (subject *Subject) NumberOfConvictionsInCounty(county string) int { result := 0 for _, row := range subject.Convictions { if row.County == county { result++ } } return result } func (subject *Subject) NumberOfFelonies() int { felonies := 0 for _, row := range subject.Convictions { if row.IsFelony { felonies++ } } return felonies } func (subject *Subject) NumberOfConvictionsInLast7Years() int { convictionsInRange := 0 for _, conviction := range subject.Convictions { if conviction.OccurredInLast7Years() { convictionsInRange++ } } return convictionsInRange } func setAppend(arr []string, item string) []string { for _, el := range arr { if el == item { return arr } } return append(arr, item) } func (subject *Subject) computeEligibilities(infos map[int]*EligibilityInfo, comparisonTime time.Time, county string) { for _, row := range subject.Convictions { if row.County == county { eligibilityInfo := NewEligibilityInfo(row, subject, comparisonTime, county) if eligibilityInfo != nil { infos[row.Index] = eligibilityInfo } } } } func (subject *Subject) olderThan(years int, t time.Time) bool { return !subject.DOB.AddDate(years, 0, 0).After(t) }
data/subject.go
0.52829
0.438785
subject.go
starcoder
package graph import ( i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time" i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization" ) // Subscription provides operations to manage the drive singleton. type Subscription struct { Entity // Optional. Identifier of the application used to create the subscription. Read-only. applicationId *string; // Required. Indicates the type of change in the subscribed resource that will raise a change notification. The supported values are: created, updated, deleted. Multiple values can be combined using a comma-separated list. Note: Drive root item and list change notifications support only the updated changeType. User and group change notifications support updated and deleted changeType. changeType *string; // Optional. Specifies the value of the clientState property sent by the service in each change notification. The maximum length is 128 characters. The client can check that the change notification came from the service by comparing the value of the clientState property sent with the subscription with the value of the clientState property received with each change notification. clientState *string; // Optional. Identifier of the user or service principal that created the subscription. If the app used delegated permissions to create the subscription, this field contains the id of the signed-in user the app called on behalf of. If the app used application permissions, this field contains the id of the service principal corresponding to the app. Read-only. creatorId *string; // Optional. A base64-encoded representation of a certificate with a public key used to encrypt resource data in change notifications. Optional but required when includeResourceData is true. encryptionCertificate *string; // Optional. A custom app-provided identifier to help identify the certificate needed to decrypt resource data. encryptionCertificateId *string; // Required. Specifies the date and time when the webhook subscription expires. The time is in UTC, and can be an amount of time from subscription creation that varies for the resource subscribed to. For the maximum supported subscription length of time, see the table below. expirationDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // Optional. When set to true, change notifications include resource data (such as content of a chat message). includeResourceData *bool; // Optional. Specifies the latest version of Transport Layer Security (TLS) that the notification endpoint, specified by notificationUrl, supports. The possible values are: v1_0, v1_1, v1_2, v1_3. For subscribers whose notification endpoint supports a version lower than the currently recommended version (TLS 1.2), specifying this property by a set timeline allows them to temporarily use their deprecated version of TLS before completing their upgrade to TLS 1.2. For these subscribers, not setting this property per the timeline would result in subscription operations failing. For subscribers whose notification endpoint already supports TLS 1.2, setting this property is optional. In such cases, Microsoft Graph defaults the property to v1_2. latestSupportedTlsVersion *string; // Optional. The URL of the endpoint that receives lifecycle notifications, including subscriptionRemoved and missed notifications. This URL must make use of the HTTPS protocol. lifecycleNotificationUrl *string; // Optional. OData query options for specifying value for the targeting resource. Clients receive notifications when resource reaches the state matching the query options provided here. With this new property in the subscription creation payload along with all existing properties, Webhooks will deliver notifications whenever a resource reaches the desired state mentioned in the notificationQueryOptions property. For example, when the print job is completed or when a print job resource isFetchable property value becomes true etc. notificationQueryOptions *string; // Required. The URL of the endpoint that will receive the change notifications. This URL must make use of the HTTPS protocol. notificationUrl *string; // Optional. The app ID that the subscription service can use to generate the validation token. This allows the client to validate the authenticity of the notification received. notificationUrlAppId *string; // Required. Specifies the resource that will be monitored for changes. Do not include the base URL (https://graph.microsoft.com/v1.0/). See the possible resource path values for each supported resource. resource *string; } // NewSubscription instantiates a new subscription and sets the default values. func NewSubscription()(*Subscription) { m := &Subscription{ Entity: *NewEntity(), } return m } // CreateSubscriptionFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateSubscriptionFromDiscriminatorValue(parseNode i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, error) { return NewSubscription(), nil } // GetApplicationId gets the applicationId property value. Optional. Identifier of the application used to create the subscription. Read-only. func (m *Subscription) GetApplicationId()(*string) { if m == nil { return nil } else { return m.applicationId } } // GetChangeType gets the changeType property value. Required. Indicates the type of change in the subscribed resource that will raise a change notification. The supported values are: created, updated, deleted. Multiple values can be combined using a comma-separated list. Note: Drive root item and list change notifications support only the updated changeType. User and group change notifications support updated and deleted changeType. func (m *Subscription) GetChangeType()(*string) { if m == nil { return nil } else { return m.changeType } } // GetClientState gets the clientState property value. Optional. Specifies the value of the clientState property sent by the service in each change notification. The maximum length is 128 characters. The client can check that the change notification came from the service by comparing the value of the clientState property sent with the subscription with the value of the clientState property received with each change notification. func (m *Subscription) GetClientState()(*string) { if m == nil { return nil } else { return m.clientState } } // GetCreatorId gets the creatorId property value. Optional. Identifier of the user or service principal that created the subscription. If the app used delegated permissions to create the subscription, this field contains the id of the signed-in user the app called on behalf of. If the app used application permissions, this field contains the id of the service principal corresponding to the app. Read-only. func (m *Subscription) GetCreatorId()(*string) { if m == nil { return nil } else { return m.creatorId } } // GetEncryptionCertificate gets the encryptionCertificate property value. Optional. A base64-encoded representation of a certificate with a public key used to encrypt resource data in change notifications. Optional but required when includeResourceData is true. func (m *Subscription) GetEncryptionCertificate()(*string) { if m == nil { return nil } else { return m.encryptionCertificate } } // GetEncryptionCertificateId gets the encryptionCertificateId property value. Optional. A custom app-provided identifier to help identify the certificate needed to decrypt resource data. func (m *Subscription) GetEncryptionCertificateId()(*string) { if m == nil { return nil } else { return m.encryptionCertificateId } } // GetExpirationDateTime gets the expirationDateTime property value. Required. Specifies the date and time when the webhook subscription expires. The time is in UTC, and can be an amount of time from subscription creation that varies for the resource subscribed to. For the maximum supported subscription length of time, see the table below. func (m *Subscription) GetExpirationDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.expirationDateTime } } // GetFieldDeserializers the deserialization information for the current model func (m *Subscription) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["applicationId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetApplicationId(val) } return nil } res["changeType"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetChangeType(val) } return nil } res["clientState"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetClientState(val) } return nil } res["creatorId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetCreatorId(val) } return nil } res["encryptionCertificate"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetEncryptionCertificate(val) } return nil } res["encryptionCertificateId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetEncryptionCertificateId(val) } return nil } res["expirationDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetExpirationDateTime(val) } return nil } res["includeResourceData"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetIncludeResourceData(val) } return nil } res["latestSupportedTlsVersion"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetLatestSupportedTlsVersion(val) } return nil } res["lifecycleNotificationUrl"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetLifecycleNotificationUrl(val) } return nil } res["notificationQueryOptions"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetNotificationQueryOptions(val) } return nil } res["notificationUrl"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetNotificationUrl(val) } return nil } res["notificationUrlAppId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetNotificationUrlAppId(val) } return nil } res["resource"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetResource(val) } return nil } return res } // GetIncludeResourceData gets the includeResourceData property value. Optional. When set to true, change notifications include resource data (such as content of a chat message). func (m *Subscription) GetIncludeResourceData()(*bool) { if m == nil { return nil } else { return m.includeResourceData } } // GetLatestSupportedTlsVersion gets the latestSupportedTlsVersion property value. Optional. Specifies the latest version of Transport Layer Security (TLS) that the notification endpoint, specified by notificationUrl, supports. The possible values are: v1_0, v1_1, v1_2, v1_3. For subscribers whose notification endpoint supports a version lower than the currently recommended version (TLS 1.2), specifying this property by a set timeline allows them to temporarily use their deprecated version of TLS before completing their upgrade to TLS 1.2. For these subscribers, not setting this property per the timeline would result in subscription operations failing. For subscribers whose notification endpoint already supports TLS 1.2, setting this property is optional. In such cases, Microsoft Graph defaults the property to v1_2. func (m *Subscription) GetLatestSupportedTlsVersion()(*string) { if m == nil { return nil } else { return m.latestSupportedTlsVersion } } // GetLifecycleNotificationUrl gets the lifecycleNotificationUrl property value. Optional. The URL of the endpoint that receives lifecycle notifications, including subscriptionRemoved and missed notifications. This URL must make use of the HTTPS protocol. func (m *Subscription) GetLifecycleNotificationUrl()(*string) { if m == nil { return nil } else { return m.lifecycleNotificationUrl } } // GetNotificationQueryOptions gets the notificationQueryOptions property value. Optional. OData query options for specifying value for the targeting resource. Clients receive notifications when resource reaches the state matching the query options provided here. With this new property in the subscription creation payload along with all existing properties, Webhooks will deliver notifications whenever a resource reaches the desired state mentioned in the notificationQueryOptions property. For example, when the print job is completed or when a print job resource isFetchable property value becomes true etc. func (m *Subscription) GetNotificationQueryOptions()(*string) { if m == nil { return nil } else { return m.notificationQueryOptions } } // GetNotificationUrl gets the notificationUrl property value. Required. The URL of the endpoint that will receive the change notifications. This URL must make use of the HTTPS protocol. func (m *Subscription) GetNotificationUrl()(*string) { if m == nil { return nil } else { return m.notificationUrl } } // GetNotificationUrlAppId gets the notificationUrlAppId property value. Optional. The app ID that the subscription service can use to generate the validation token. This allows the client to validate the authenticity of the notification received. func (m *Subscription) GetNotificationUrlAppId()(*string) { if m == nil { return nil } else { return m.notificationUrlAppId } } // GetResource gets the resource property value. Required. Specifies the resource that will be monitored for changes. Do not include the base URL (https://graph.microsoft.com/v1.0/). See the possible resource path values for each supported resource. func (m *Subscription) GetResource()(*string) { if m == nil { return nil } else { return m.resource } } func (m *Subscription) IsNil()(bool) { return m == nil } // Serialize serializes information the current object func (m *Subscription) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } { err = writer.WriteStringValue("applicationId", m.GetApplicationId()) if err != nil { return err } } { err = writer.WriteStringValue("changeType", m.GetChangeType()) if err != nil { return err } } { err = writer.WriteStringValue("clientState", m.GetClientState()) if err != nil { return err } } { err = writer.WriteStringValue("creatorId", m.GetCreatorId()) if err != nil { return err } } { err = writer.WriteStringValue("encryptionCertificate", m.GetEncryptionCertificate()) if err != nil { return err } } { err = writer.WriteStringValue("encryptionCertificateId", m.GetEncryptionCertificateId()) if err != nil { return err } } { err = writer.WriteTimeValue("expirationDateTime", m.GetExpirationDateTime()) if err != nil { return err } } { err = writer.WriteBoolValue("includeResourceData", m.GetIncludeResourceData()) if err != nil { return err } } { err = writer.WriteStringValue("latestSupportedTlsVersion", m.GetLatestSupportedTlsVersion()) if err != nil { return err } } { err = writer.WriteStringValue("lifecycleNotificationUrl", m.GetLifecycleNotificationUrl()) if err != nil { return err } } { err = writer.WriteStringValue("notificationQueryOptions", m.GetNotificationQueryOptions()) if err != nil { return err } } { err = writer.WriteStringValue("notificationUrl", m.GetNotificationUrl()) if err != nil { return err } } { err = writer.WriteStringValue("notificationUrlAppId", m.GetNotificationUrlAppId()) if err != nil { return err } } { err = writer.WriteStringValue("resource", m.GetResource()) if err != nil { return err } } return nil } // SetApplicationId sets the applicationId property value. Optional. Identifier of the application used to create the subscription. Read-only. func (m *Subscription) SetApplicationId(value *string)() { if m != nil { m.applicationId = value } } // SetChangeType sets the changeType property value. Required. Indicates the type of change in the subscribed resource that will raise a change notification. The supported values are: created, updated, deleted. Multiple values can be combined using a comma-separated list. Note: Drive root item and list change notifications support only the updated changeType. User and group change notifications support updated and deleted changeType. func (m *Subscription) SetChangeType(value *string)() { if m != nil { m.changeType = value } } // SetClientState sets the clientState property value. Optional. Specifies the value of the clientState property sent by the service in each change notification. The maximum length is 128 characters. The client can check that the change notification came from the service by comparing the value of the clientState property sent with the subscription with the value of the clientState property received with each change notification. func (m *Subscription) SetClientState(value *string)() { if m != nil { m.clientState = value } } // SetCreatorId sets the creatorId property value. Optional. Identifier of the user or service principal that created the subscription. If the app used delegated permissions to create the subscription, this field contains the id of the signed-in user the app called on behalf of. If the app used application permissions, this field contains the id of the service principal corresponding to the app. Read-only. func (m *Subscription) SetCreatorId(value *string)() { if m != nil { m.creatorId = value } } // SetEncryptionCertificate sets the encryptionCertificate property value. Optional. A base64-encoded representation of a certificate with a public key used to encrypt resource data in change notifications. Optional but required when includeResourceData is true. func (m *Subscription) SetEncryptionCertificate(value *string)() { if m != nil { m.encryptionCertificate = value } } // SetEncryptionCertificateId sets the encryptionCertificateId property value. Optional. A custom app-provided identifier to help identify the certificate needed to decrypt resource data. func (m *Subscription) SetEncryptionCertificateId(value *string)() { if m != nil { m.encryptionCertificateId = value } } // SetExpirationDateTime sets the expirationDateTime property value. Required. Specifies the date and time when the webhook subscription expires. The time is in UTC, and can be an amount of time from subscription creation that varies for the resource subscribed to. For the maximum supported subscription length of time, see the table below. func (m *Subscription) SetExpirationDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.expirationDateTime = value } } // SetIncludeResourceData sets the includeResourceData property value. Optional. When set to true, change notifications include resource data (such as content of a chat message). func (m *Subscription) SetIncludeResourceData(value *bool)() { if m != nil { m.includeResourceData = value } } // SetLatestSupportedTlsVersion sets the latestSupportedTlsVersion property value. Optional. Specifies the latest version of Transport Layer Security (TLS) that the notification endpoint, specified by notificationUrl, supports. The possible values are: v1_0, v1_1, v1_2, v1_3. For subscribers whose notification endpoint supports a version lower than the currently recommended version (TLS 1.2), specifying this property by a set timeline allows them to temporarily use their deprecated version of TLS before completing their upgrade to TLS 1.2. For these subscribers, not setting this property per the timeline would result in subscription operations failing. For subscribers whose notification endpoint already supports TLS 1.2, setting this property is optional. In such cases, Microsoft Graph defaults the property to v1_2. func (m *Subscription) SetLatestSupportedTlsVersion(value *string)() { if m != nil { m.latestSupportedTlsVersion = value } } // SetLifecycleNotificationUrl sets the lifecycleNotificationUrl property value. Optional. The URL of the endpoint that receives lifecycle notifications, including subscriptionRemoved and missed notifications. This URL must make use of the HTTPS protocol. func (m *Subscription) SetLifecycleNotificationUrl(value *string)() { if m != nil { m.lifecycleNotificationUrl = value } } // SetNotificationQueryOptions sets the notificationQueryOptions property value. Optional. OData query options for specifying value for the targeting resource. Clients receive notifications when resource reaches the state matching the query options provided here. With this new property in the subscription creation payload along with all existing properties, Webhooks will deliver notifications whenever a resource reaches the desired state mentioned in the notificationQueryOptions property. For example, when the print job is completed or when a print job resource isFetchable property value becomes true etc. func (m *Subscription) SetNotificationQueryOptions(value *string)() { if m != nil { m.notificationQueryOptions = value } } // SetNotificationUrl sets the notificationUrl property value. Required. The URL of the endpoint that will receive the change notifications. This URL must make use of the HTTPS protocol. func (m *Subscription) SetNotificationUrl(value *string)() { if m != nil { m.notificationUrl = value } } // SetNotificationUrlAppId sets the notificationUrlAppId property value. Optional. The app ID that the subscription service can use to generate the validation token. This allows the client to validate the authenticity of the notification received. func (m *Subscription) SetNotificationUrlAppId(value *string)() { if m != nil { m.notificationUrlAppId = value } } // SetResource sets the resource property value. Required. Specifies the resource that will be monitored for changes. Do not include the base URL (https://graph.microsoft.com/v1.0/). See the possible resource path values for each supported resource. func (m *Subscription) SetResource(value *string)() { if m != nil { m.resource = value } }
models/microsoft/graph/subscription.go
0.868158
0.410225
subscription.go
starcoder
package models import ( i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // Location type Location struct { // Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. additionalData map[string]interface{} // The street address of the location. address PhysicalAddressable // The geographic coordinates and elevation of the location. coordinates OutlookGeoCoordinatesable // The name associated with the location. displayName *string // Optional email address of the location. locationEmailAddress *string // The type of location. Possible values are: default, conferenceRoom, homeAddress, businessAddress,geoCoordinates, streetAddress, hotel, restaurant, localBusiness, postalAddress. Read-only. locationType *LocationType // Optional URI representing the location. locationUri *string // For internal use only. uniqueId *string // For internal use only. uniqueIdType *LocationUniqueIdType } // NewLocation instantiates a new location and sets the default values. func NewLocation()(*Location) { m := &Location{ } m.SetAdditionalData(make(map[string]interface{})); return m } // CreateLocationFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateLocationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewLocation(), nil } // GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *Location) GetAdditionalData()(map[string]interface{}) { if m == nil { return nil } else { return m.additionalData } } // GetAddress gets the address property value. The street address of the location. func (m *Location) GetAddress()(PhysicalAddressable) { if m == nil { return nil } else { return m.address } } // GetCoordinates gets the coordinates property value. The geographic coordinates and elevation of the location. func (m *Location) GetCoordinates()(OutlookGeoCoordinatesable) { if m == nil { return nil } else { return m.coordinates } } // GetDisplayName gets the displayName property value. The name associated with the location. func (m *Location) GetDisplayName()(*string) { if m == nil { return nil } else { return m.displayName } } // GetFieldDeserializers the deserialization information for the current model func (m *Location) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) res["address"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreatePhysicalAddressFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetAddress(val.(PhysicalAddressable)) } return nil } res["coordinates"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreateOutlookGeoCoordinatesFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetCoordinates(val.(OutlookGeoCoordinatesable)) } return nil } res["displayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetDisplayName(val) } return nil } res["locationEmailAddress"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetLocationEmailAddress(val) } return nil } res["locationType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseLocationType) if err != nil { return err } if val != nil { m.SetLocationType(val.(*LocationType)) } return nil } res["locationUri"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetLocationUri(val) } return nil } res["uniqueId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetUniqueId(val) } return nil } res["uniqueIdType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseLocationUniqueIdType) if err != nil { return err } if val != nil { m.SetUniqueIdType(val.(*LocationUniqueIdType)) } return nil } return res } // GetLocationEmailAddress gets the locationEmailAddress property value. Optional email address of the location. func (m *Location) GetLocationEmailAddress()(*string) { if m == nil { return nil } else { return m.locationEmailAddress } } // GetLocationType gets the locationType property value. The type of location. Possible values are: default, conferenceRoom, homeAddress, businessAddress,geoCoordinates, streetAddress, hotel, restaurant, localBusiness, postalAddress. Read-only. func (m *Location) GetLocationType()(*LocationType) { if m == nil { return nil } else { return m.locationType } } // GetLocationUri gets the locationUri property value. Optional URI representing the location. func (m *Location) GetLocationUri()(*string) { if m == nil { return nil } else { return m.locationUri } } // GetUniqueId gets the uniqueId property value. For internal use only. func (m *Location) GetUniqueId()(*string) { if m == nil { return nil } else { return m.uniqueId } } // GetUniqueIdType gets the uniqueIdType property value. For internal use only. func (m *Location) GetUniqueIdType()(*LocationUniqueIdType) { if m == nil { return nil } else { return m.uniqueIdType } } // Serialize serializes information the current object func (m *Location) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { { err := writer.WriteObjectValue("address", m.GetAddress()) if err != nil { return err } } { err := writer.WriteObjectValue("coordinates", m.GetCoordinates()) if err != nil { return err } } { err := writer.WriteStringValue("displayName", m.GetDisplayName()) if err != nil { return err } } { err := writer.WriteStringValue("locationEmailAddress", m.GetLocationEmailAddress()) if err != nil { return err } } if m.GetLocationType() != nil { cast := (*m.GetLocationType()).String() err := writer.WriteStringValue("locationType", &cast) if err != nil { return err } } { err := writer.WriteStringValue("locationUri", m.GetLocationUri()) if err != nil { return err } } { err := writer.WriteStringValue("uniqueId", m.GetUniqueId()) if err != nil { return err } } if m.GetUniqueIdType() != nil { cast := (*m.GetUniqueIdType()).String() err := writer.WriteStringValue("uniqueIdType", &cast) if err != nil { return err } } { err := writer.WriteAdditionalData(m.GetAdditionalData()) if err != nil { return err } } return nil } // SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *Location) SetAdditionalData(value map[string]interface{})() { if m != nil { m.additionalData = value } } // SetAddress sets the address property value. The street address of the location. func (m *Location) SetAddress(value PhysicalAddressable)() { if m != nil { m.address = value } } // SetCoordinates sets the coordinates property value. The geographic coordinates and elevation of the location. func (m *Location) SetCoordinates(value OutlookGeoCoordinatesable)() { if m != nil { m.coordinates = value } } // SetDisplayName sets the displayName property value. The name associated with the location. func (m *Location) SetDisplayName(value *string)() { if m != nil { m.displayName = value } } // SetLocationEmailAddress sets the locationEmailAddress property value. Optional email address of the location. func (m *Location) SetLocationEmailAddress(value *string)() { if m != nil { m.locationEmailAddress = value } } // SetLocationType sets the locationType property value. The type of location. Possible values are: default, conferenceRoom, homeAddress, businessAddress,geoCoordinates, streetAddress, hotel, restaurant, localBusiness, postalAddress. Read-only. func (m *Location) SetLocationType(value *LocationType)() { if m != nil { m.locationType = value } } // SetLocationUri sets the locationUri property value. Optional URI representing the location. func (m *Location) SetLocationUri(value *string)() { if m != nil { m.locationUri = value } } // SetUniqueId sets the uniqueId property value. For internal use only. func (m *Location) SetUniqueId(value *string)() { if m != nil { m.uniqueId = value } } // SetUniqueIdType sets the uniqueIdType property value. For internal use only. func (m *Location) SetUniqueIdType(value *LocationUniqueIdType)() { if m != nil { m.uniqueIdType = value } }
models/location.go
0.7181
0.432423
location.go
starcoder
package storage import ( "encoding/binary" "math" "github.com/john-nguyen09/phpintel/internal/lsp/protocol" ) // PutUInt64 appends an uint64 to the byte slice func PutUInt64(dst []byte, v uint64) []byte { return append(dst, byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) } // PutUInt32 appends an uint32 to the byte slice func PutUInt32(dst []byte, v uint32) []byte { return append(dst, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) } // PutFloat64 appends a float64 to the byte slice func PutFloat64(dst []byte, v float64) []byte { return PutUInt64(dst, math.Float64bits(v)) } // PutFloat32 appens a float32 to the byte slice func PutFloat32(dst []byte, v float32) []byte { return PutUInt32(dst, math.Float32bits(v)) } // ReadUInt64 reads an uint64 from the byte slice func ReadUInt64(src []byte) uint64 { return binary.BigEndian.Uint64(src) } // ReadUInt32 reads an uint32 from the byte slice func ReadUInt32(src []byte) uint32 { return binary.BigEndian.Uint32(src) } // ReadFloat64 reads a float64 from the byte slice func ReadFloat64(src []byte) float64 { u := ReadUInt64(src) return math.Float64frombits(u) } // ReadFloat32 reads a float32 from the byte slice func ReadFloat32(src []byte) float32 { u := ReadUInt32(src) return math.Float32frombits(u) } type coder struct { buf []byte offset int } // Encoder is an encoder to encode primitives to byte slice type Encoder coder // NewEncoder creates an encoder func NewEncoder() *Encoder { return &Encoder{} } // WriteUInt64 writes an uint64 func (e *Encoder) WriteUInt64(v uint64) { e.buf = PutUInt64(e.buf, v) } // WriteInt writes an int func (e *Encoder) WriteInt(v int) { e.WriteUInt64(uint64(v)) } // WriteUInt32 writes an uint32 func (e *Encoder) WriteUInt32(v uint32) { e.buf = PutUInt32(e.buf, v) } // WriteFloat64 writes a float64 func (e *Encoder) WriteFloat64(v float64) { e.buf = PutFloat64(e.buf, v) } // WriteFloat32 writes a float32 func (e *Encoder) WriteFloat32(v float32) { e.buf = PutFloat32(e.buf, v) } // WriteBytes writes bytes func (e *Encoder) WriteBytes(b []byte) { e.WriteInt(len(b)) e.buf = append(e.buf, b...) } // WriteString writes string func (e *Encoder) WriteString(v string) { e.WriteBytes([]byte(v)) } // WriteBool writes bool func (e *Encoder) WriteBool(b bool) { by := byte(0) if b { by = byte(1) } e.buf = append(e.buf, by) } // WritePosition writes a LSP position func (e *Encoder) WritePosition(v protocol.Position) { e.WriteInt(v.Line) e.WriteInt(v.Character) } // WriteLocation writes a LSP location func (e *Encoder) WriteLocation(v protocol.Location) { e.WriteString(v.URI) e.WritePosition(v.Range.Start) e.WritePosition(v.Range.End) } // Bytes returns the underlying byte slice func (e *Encoder) Bytes() []byte { return e.buf } // Decoder is a coder to decode byte slice into primitives type Decoder coder // NewDecoder creates a decoder func NewDecoder(b []byte) *Decoder { return &Decoder{b, 0} } // ReadInt reads an int func (d *Decoder) ReadInt() int { return int(d.ReadUInt64()) } // ReadUInt64 reads an uint64 func (d *Decoder) ReadUInt64() uint64 { u := ReadUInt64(d.buf) d.buf = d.buf[8:] return u } // ReadUInt32 reads an uint32 func (d *Decoder) ReadUInt32() uint32 { u := ReadUInt32(d.buf) d.buf = d.buf[4:] return u } // ReadFloat64 reads a float64 func (d *Decoder) ReadFloat64() float64 { f := ReadFloat64(d.buf) d.buf = d.buf[8:] return f } // ReadFloat32 reads a float32 func (d *Decoder) ReadFloat32() float32 { f := ReadFloat32(d.buf) d.buf = d.buf[4:] return f } // ReadBytes reads bytes func (d *Decoder) ReadBytes() []byte { len := d.ReadInt() b := append(d.buf[:0:0], d.buf[:len]...) d.buf = d.buf[len:] return b } // ReadString reads a string func (d *Decoder) ReadString() string { return string(d.ReadBytes()) } // ReadBool reads a bool func (d *Decoder) ReadBool() bool { b := d.buf[0] d.buf = d.buf[1:] return b != 0 } // ReadPosition reads a LSP position func (d *Decoder) ReadPosition() protocol.Position { return protocol.Position{ Line: d.ReadInt(), Character: d.ReadInt(), } } // ReadLocation reads a LSP location func (d *Decoder) ReadLocation() protocol.Location { return protocol.Location{ URI: d.ReadString(), Range: protocol.Range{ Start: d.ReadPosition(), End: d.ReadPosition(), }, } }
analysis/storage/encoding.go
0.789518
0.473779
encoding.go
starcoder
package export import "github.com/prometheus/client_golang/prometheus" // QueryHistoricalExporter contains all the Prometheus metrics that are possible to gather from the historicals type QueryHistoricalExporter struct { QueryTime *prometheus.HistogramVec `description:"milliseconds taken to complete a query"` QuerySegmentTime *prometheus.HistogramVec `description:"milliseconds taken to query individual segment. Includes time to page in the segment from disk"` QueryWaitTime *prometheus.HistogramVec `description:"milliseconds spent waiting for a segment to be scanned"` QuerySegmentAndCacheTime *prometheus.HistogramVec `description:"milliseconds taken to query individual segment or hit the cache (if it is enabled on the Historical process)"` QueryCPUTime *prometheus.HistogramVec `description:"Microseconds of CPU time taken to complete a query"` QueryCount *prometheus.GaugeVec `description:"number of total queries"` QuerySuccessCount *prometheus.GaugeVec `description:"number of queries successfully processed"` QueryFailedCount *prometheus.GaugeVec `description:"number of failed queries"` QueryInterruptedCount *prometheus.GaugeVec `description:"number of queries interrupted due to cancellation or timeout"` SegmentScanPending *prometheus.GaugeVec `description:"number of segments in queue waiting to be scanned"` } // NewQueryHistoricalExporter returns a new historical exporter object func NewQueryHistoricalExporter() *QueryHistoricalExporter { qh := &QueryHistoricalExporter{ QueryTime: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_time", Help: "milliseconds taken to complete a query", Buckets: []float64{10, 100, 500, 1000, 2000, 3000, 5000, 7000, 10000}, }, []string{"dataSource", "type", "hasFilters", "duration", "remoteAddress", "id", "numMetrics", "numComplexMetrics", "numDimensions", "threshold", "dimension"}), QuerySegmentTime: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_segment_time", Help: "milliseconds taken to query individual segment. Includes time to page in the segment from disk", Buckets: []float64{10, 100, 500, 1000, 2000, 3000, 5000, 7000, 10000}, }, []string{"id", "status", "segment"}), QueryWaitTime: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_wait_time", Help: "milliseconds spent waiting for a segment to be scanned", Buckets: []float64{10, 100, 500, 1000, 2000, 3000, 5000, 7000, 10000}, }, []string{"id", "segment"}), QuerySegmentAndCacheTime: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_segmentandcache_time", Help: "milliseconds taken to query individual segment or hit the cache (if it is enabled on the Historical process)", Buckets: []float64{10, 100, 500, 1000, 2000, 3000, 5000, 7000, 10000}, }, []string{"id", "segment"}), QueryCPUTime: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_cpu_time", Help: "Microseconds of CPU time taken to complete a query", Buckets: []float64{10, 100, 500, 1000, 2000, 3000, 5000, 7000, 10000}, }, []string{"dataSource", "type", "hasFilters", "duration", "remoteAddress", "id", "numMetrics", "numComplexMetrics", "numDimensions", "threshold", "dimension"}), QueryCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_count", Help: "number of total queries", }, []string{}), QuerySuccessCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_success_count", Help: "number of queries successfully processed", }, []string{}), QueryFailedCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_failed_count", Help: "number of failed queries", }, []string{}), QueryInterruptedCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "druid", Subsystem: "historical", Name: "query_interrupted_count", Help: "number of queries interrupted due to cancellation or timeout", }, []string{}), SegmentScanPending: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "druid", Subsystem: "historical", Name: "segment_scan_pending", Help: "number of segments in queue waiting to be scanned", }, []string{}), } // register all prometheus metrics prometheus.MustRegister(qh.QueryTime) prometheus.MustRegister(qh.QuerySegmentTime) prometheus.MustRegister(qh.QueryWaitTime) prometheus.MustRegister(qh.QuerySegmentAndCacheTime) prometheus.MustRegister(qh.QueryCPUTime) prometheus.MustRegister(qh.QueryCount) prometheus.MustRegister(qh.QuerySuccessCount) prometheus.MustRegister(qh.QueryFailedCount) prometheus.MustRegister(qh.QueryInterruptedCount) prometheus.MustRegister(qh.SegmentScanPending) return qh } // SetQueryTime . func (qh *QueryHistoricalExporter) SetQueryTime(labels map[string]string, val float64) { qh.QueryTime.With(labels).Observe(val) } // SetQuerySegmentTime . func (qh *QueryHistoricalExporter) SetQuerySegmentTime(labels map[string]string, val float64) { qh.QuerySegmentTime.With(labels).Observe(val) } // SetQueryWaitTime . func (qh *QueryHistoricalExporter) SetQueryWaitTime(labels map[string]string, val float64) { qh.QueryWaitTime.With(labels).Observe(val) } // SetQuerySegmentAndCacheTime . func (qh *QueryHistoricalExporter) SetQuerySegmentAndCacheTime(labels map[string]string, val float64) { qh.QuerySegmentAndCacheTime.With(labels).Observe(val) } // SetQueryCPUTime . func (qh *QueryHistoricalExporter) SetQueryCPUTime(labels map[string]string, val float64) { qh.QueryCPUTime.With(labels).Observe(val) } // SetQueryCount . func (qh *QueryHistoricalExporter) SetQueryCount(val float64) { qh.QueryCount.WithLabelValues().Add(val) } // SetQuerySuccessCount . func (qh *QueryHistoricalExporter) SetQuerySuccessCount(val float64) { qh.QuerySuccessCount.WithLabelValues().Add(val) } // SetQueryFailedCount . func (qh *QueryHistoricalExporter) SetQueryFailedCount(val float64) { qh.QueryFailedCount.WithLabelValues().Add(val) } // SetQueryInterruptedCount . func (qh *QueryHistoricalExporter) SetQueryInterruptedCount(val float64) { qh.QueryInterruptedCount.WithLabelValues().Add(val) } // SetSegmentScanPending . func (qh *QueryHistoricalExporter) SetSegmentScanPending(val float64) { qh.SegmentScanPending.WithLabelValues().Add(val) }
pkg/export/query_historical.go
0.793586
0.523603
query_historical.go
starcoder
package lib import ( "container/list" "fmt" ) type TreeNode struct { Val, size int Left *TreeNode Right *TreeNode Parent *TreeNode } func NewTreeNode(v int) *TreeNode { return &TreeNode{ Val: v, size: 1, } } func (t *TreeNode) setLeftChild(left *TreeNode) { t.Left = left if left != nil { left.Parent = t } } func (t *TreeNode) setRightChild(right *TreeNode) { t.Right = right if right != nil { right.Parent = t } } func (t *TreeNode) InsertInOrder(d int) { if d <= t.Val { if t.Left == nil { t.setLeftChild(NewTreeNode(d)) } else { t.Left.InsertInOrder(d) } } else { if t.Right == nil { t.setRightChild(NewTreeNode(d)) } else { t.Right.InsertInOrder(d) } } t.size++ } func (t *TreeNode) Size() int { if t == nil { return 0 } return t.size } func (t *TreeNode) IsBST() bool { if t.Left != nil { if t.Val < t.Left.Val || !t.Left.IsBST() { return false } } if t.Right != nil { if t.Val >= t.Right.Val || !t.Right.IsBST() { return false } } return true } func (t *TreeNode) Height() int { if t == nil { return 0 } return 1 + max(t.Left.Height(), t.Right.Height()) } func (t *TreeNode) Find(d int) *TreeNode { if t != nil { if d == t.Val { return t } else if d <= t.Val { return t.Left.Find(d) } else if d > t.Val { return t.Right.Find(d) } } return nil } func (t *TreeNode) GetRandomNode() *TreeNode { var leftSize int if t.Left != nil { leftSize = t.Left.Size() } index := RandomInt(t.Size()) if index < leftSize { return t.Left.GetRandomNode() } else if index == leftSize { return t } else { return t.Right.GetRandomNode() } } func (t *TreeNode) GetIthNode(i int) *TreeNode { var leftSize int if t.Left != nil { leftSize = t.Left.Size() } if i < leftSize { return t.Left.GetIthNode(i) } else if i == leftSize { return t } else { return t.Right.GetIthNode(i - (leftSize + 1)) } } func (t *TreeNode) Print() { PrintNode(t) } func CreateMinimalBst(array []int) *TreeNode { return createMinimalBST(array, 0, len(array)-1) } func createMinimalBST(arr []int, start, end int) *TreeNode { if end < start { return nil } mid := (start + end) / 2 n := NewTreeNode(arr[mid]) n.setLeftChild(createMinimalBST(arr, start, mid-1)) n.setRightChild(createMinimalBST(arr, mid+1, end)) return n } func RandomBST(N, min, max int) *TreeNode { d := RandomIntInRange(min, max) root := NewTreeNode(d) for i := 1; i < N; i++ { root.InsertInOrder(RandomIntInRange(min, max)) } return root } func CreateTreeFromArray(array []int) *TreeNode { if len(array) > 0 { root := NewTreeNode(array[0]) queue := make([]*TreeNode, 0) queue = append(queue, root) done := false i := 1 for !done { r := queue[0] if r.Left == nil { r.Left = NewTreeNode(array[i]) i++ queue = append(queue, r.Left) } else if r.Right == nil { r.Right = NewTreeNode(array[i]) i++ queue = append(queue, r.Left) } else { queue = queue[1:] } if i == len(array) { done = true } } return root } else { return nil } } func (t *TreeNode) InOrder() { if t == nil { return } t.Left.InOrder() fmt.Println(t.Val) t.Right.InOrder() } func (t *TreeNode) PreOrder() { if t == nil { return } fmt.Println(t.Val) t.Left.PreOrder() t.Right.PreOrder() } func (t *TreeNode) PostOrder() { if t == nil { return } t.Left.PostOrder() t.Right.PostOrder() fmt.Println(t.Val) } func (t *TreeNode) BFS() { queue := list.New() queue.PushBack(t) for queue.Len() != 0 { current := queue.Front() queue.Remove(current) treeNode := current.Value.(*TreeNode) fmt.Println(t.Val) children := []*TreeNode{treeNode.Left, treeNode.Right} for _, child := range children { queue.PushBack(child) } } }
golang/lib/tree_node.go
0.520009
0.431225
tree_node.go
starcoder
package cluster import ( "encoding/gob" "errors" "fmt" "math" "math/rand" "os" "time" "gonum.org/v1/gonum/mat" ) // DistanceFunction compute distance between two vectors. type DistanceFunction func(a, b *DenseVector) (float64, error) // InitializationFunction compute initial vales for cluster_centroids_. type InitializationFunction func(X *DenseMatrix, clustersNumber int, distFunc DistanceFunction) (*DenseMatrix, error) // KModes is a basic class for the k-modes algorithm, it contains all necessary // information as alg. parameters, labels, centroids, ... type KModes struct { DistanceFunc DistanceFunction InitializationFunc InitializationFunction ClustersNumber int RunsNumber int MaxIterationNumber int WeightVectors [][]float64 FrequencyTable [][]map[float64]float64 // frequency table - list of lists with dictionaries containing frequencies of values per cluster and attribute LabelsCounter []int Labels *DenseVector ClusterCentroids *DenseMatrix IsFitted bool ModelPath string } // NewKModes implements constructor for the KModes struct. func NewKModes(dist DistanceFunction, init InitializationFunction, clusters int, runs int, iters int, weights [][]float64, modelPath string) *KModes { rand.Seed(time.Now().UnixNano()) return &KModes{ DistanceFunc: dist, InitializationFunc: init, ClustersNumber: clusters, RunsNumber: runs, MaxIterationNumber: iters, WeightVectors: weights, ModelPath: modelPath, Labels: &DenseVector{VecDense: new(mat.VecDense)}, ClusterCentroids: &DenseMatrix{Dense: new(mat.Dense)}, } } // FitModel main algorithm function which finds the best clusters centers for // the given dataset X. //func (km *KModes) FitModel(X *mat.Dense) error { func (km *KModes) FitModel(X *DenseMatrix) error { err := km.validateParameters() if err != nil { return fmt.Errorf("kmodes: failed to fit the model: %v", err) } // Initialize weightVector SetWeights(km.WeightVectors[0]) xRows, xCols := X.Dims() // Initialize clusters km.ClusterCentroids, err = km.InitializationFunc(X, km.ClustersNumber, km.DistanceFunc) if err != nil { return fmt.Errorf("kmodes: failed to fit the model: %v", err) } // Initialize labels vector km.Labels = NewDenseVector(xRows, nil) km.LabelsCounter = make([]int, km.ClustersNumber) // Create frequency table km.FrequencyTable = make([][]map[float64]float64, km.ClustersNumber) for i := range km.FrequencyTable { km.FrequencyTable[i] = make([]map[float64]float64, xCols) for j := range km.FrequencyTable[i] { km.FrequencyTable[i][j] = make(map[float64]float64) } } // Perform initial assignements to clusters - in order to fill in frequency // table. for i := 0; i < xRows; i++ { row := X.RowView(i) newLabel, _, err := km.near(i, &DenseVector{X.RowView(i).(*mat.VecDense)}) km.LabelsCounter[int(newLabel)]++ km.Labels.SetVec(i, newLabel) if err != nil { return fmt.Errorf("kmodes: initial labels assignement failure: %v", err) } for j := 0; j < xCols; j++ { km.FrequencyTable[int(newLabel)][j][row.At(j, 0)]++ } } // Perform initial centers update - because iteration() starts with label // assignements. for i := 0; i < km.ClustersNumber; i++ { km.findNewCenters(i, xCols) } for i := 0; i < km.MaxIterationNumber; i++ { _, change, err := km.iteration(X) if err != nil { return fmt.Errorf("KMeans error at iteration %d: %v", i, err) } if change == false { km.IsFitted = true return nil } } return nil } func (km *KModes) findNewCenters(i, xCols int) { newCentroid := make([]float64, xCols) for j := 0; j < xCols; j++ { val, empty := findHighestMapValue(km.FrequencyTable[i][j]) if !empty { newCentroid[j] = val } else { newCentroid[j] = km.ClusterCentroids.At(i, j) } } km.ClusterCentroids.SetRow(i, newCentroid) } func (km *KModes) iteration(X *DenseMatrix) (float64, bool, error) { changed := make([]bool, km.ClustersNumber) var change bool var numOfChanges float64 var totalCost float64 // Find closest cluster for all data vectors - assign new labels. xRows, xCols := X.Dims() for i := 0; i < xRows; i++ { row := X.RowView(i) newLabel, cost, err := km.near(i, &DenseVector{X.RowView(i).(*mat.VecDense)}) if err != nil { return totalCost, change, fmt.Errorf("iteration error: %v", err) } totalCost += cost if newLabel != km.Labels.At(i, 0) { km.LabelsCounter[int(newLabel)]++ km.LabelsCounter[int(km.Labels.At(i, 0))]-- // Make changes in frequency table. for j := 0; j < xCols; j++ { km.FrequencyTable[int(km.Labels.At(i, 0))][j][row.At(j, 0)]-- km.FrequencyTable[int(newLabel)][j][row.At(j, 0)]++ } change = true numOfChanges++ changed[int(newLabel)] = true changed[int(km.Labels.At(i, 0))] = true km.Labels.SetVec(i, newLabel) } } // Check for empty clusters - if such cluster is found reassign the center // and return. for i := 0; i < km.ClustersNumber; i++ { if km.LabelsCounter[i] == 0 { vector := X.RawRowView(rand.Intn(xRows)) km.ClusterCentroids.SetRow(i, vector) return totalCost, true, nil } } // Recompute cluster centers for all clusters with changes. for i, elem := range changed { if elem == true { //find new values for clusters centers km.findNewCenters(i, xCols) } } return totalCost, change, nil } func (km *KModes) near(index int, vector *DenseVector) (float64, float64, error) { var newLabel, distance float64 distance = math.MaxFloat64 for i := 0; i < km.ClustersNumber; i++ { dist, err := km.DistanceFunc(vector, &DenseVector{km.ClusterCentroids.RowView(i).(*mat.VecDense)}) if err != nil { return -1, -1, fmt.Errorf("Cannot compute nearest cluster for vector %q: %v", index, err) } if dist < distance { distance = dist newLabel = float64(i) } } return newLabel, distance, nil } func findHighestMapValue(m map[float64]float64) (float64, bool) { var key float64 var highestValue float64 // Do something different if map is empty because if its empty it returns // key=0 !!! if len(m) == 0 { return 0, true } for k, value := range m { if value > highestValue { highestValue = value key = k } } return key, false } // Predict assign labels for the set of new vectors. func (km *KModes) Predict(X *DenseMatrix) (*DenseVector, error) { if km.IsFitted != true { return NewDenseVector(0, nil), errors.New("kmodes: cannot predict labels, model is not fitted yet") } xRows, _ := X.Dims() labelsVec := NewDenseVector(xRows, nil) for i := 0; i < xRows; i++ { label, _, err := km.near(i, &DenseVector{X.RowView(i).(*mat.VecDense)}) if err != nil { return NewDenseVector(0, nil), fmt.Errorf("kmodes Predict: %v", err) } labelsVec.SetVec(i, label) } return labelsVec, nil } // SaveModel saves computed ml model (KModes struct) in file specified in // configuration. func (km *KModes) SaveModel() error { file, err := os.Create(km.ModelPath) if err == nil { encoder := gob.NewEncoder(file) encoder.Encode(km) } file.Close() return err } // LoadModel loads model (KModes struct) from file. func (km *KModes) LoadModel() error { file, err := os.Open(km.ModelPath) if err == nil { decoder := gob.NewDecoder(file) err = decoder.Decode(km) } file.Close() SetWeights(km.WeightVectors[0]) return err } func (km *KModes) validateParameters() error { if km.InitializationFunc == nil { return errors.New("initializationFunction is nil") } if km.DistanceFunc == nil { return errors.New("distanceFunction is nil") } if km.ClustersNumber < 1 || km.MaxIterationNumber < 1 || km.RunsNumber < 1 { return errors.New("wrong initialization parameters (should be >1)") } return nil }
cluster/kmodes.go
0.739328
0.600833
kmodes.go
starcoder
package godal // Block is a window inside a dataset, starting at pixel X0,Y0 and spanning // W,H pixels. type Block struct { X0, Y0 int W, H int bw, bh int //block size sx, sy int //img size nx, ny int //num blocks i, j int //cur } // Next returns the following block in scanline order. It returns Block{},false // when there are no more blocks in the scanlines func (b Block) Next() (Block, bool) { nb := b nb.i++ if nb.i >= nb.nx { nb.i = 0 nb.j++ } if nb.j >= nb.ny { return Block{}, false } nb.X0 = nb.i * nb.bw nb.Y0 = nb.j * nb.bh nb.W, nb.H = actualBlockSize(nb.sx, nb.sy, nb.bw, nb.bh, nb.i, nb.j) return nb, true } // BlockIterator returns the blocks covering a sizeX,sizeY dataset. // All sizes must be strictly positive. func BlockIterator(sizeX, sizeY int, blockSizeX, blockSizeY int) Block { bl := Block{ X0: 0, Y0: 0, i: 0, j: 0, bw: blockSizeX, bh: blockSizeY, sx: sizeX, sy: sizeY, } bl.nx, bl.ny = (sizeX+blockSizeX-1)/blockSizeX, (sizeY+blockSizeY-1)/blockSizeY bl.W, bl.H = actualBlockSize(sizeX, sizeY, blockSizeX, blockSizeY, 0, 0) return bl } // BandStructure implements Structure for a Band type BandStructure struct { SizeX, SizeY int BlockSizeX, BlockSizeY int DataType DataType } // DatasetStructure implements Structure for a Dataset type DatasetStructure struct { BandStructure NBands int } // FirstBlock returns the topleft block definition func (is BandStructure) FirstBlock() Block { return BlockIterator(is.SizeX, is.SizeY, is.BlockSizeX, is.BlockSizeY) } // BlockCount returns the number of blocks in the x and y dimensions func (is BandStructure) BlockCount() (int, int) { return (is.SizeX + is.BlockSizeX - 1) / is.BlockSizeX, (is.SizeY + is.BlockSizeY - 1) / is.BlockSizeY } // ActualBlockSize returns the number of pixels in the x and y dimensions // that actually contain data for the given x,y block func (is BandStructure) ActualBlockSize(blockX, blockY int) (int, int) { return actualBlockSize(is.SizeX, is.SizeY, is.BlockSizeX, is.BlockSizeY, blockX, blockY) } func actualBlockSize(sizeX, sizeY int, blockSizeX, blockSizeY int, blockX, blockY int) (int, int) { cx, cy := (sizeX+blockSizeX-1)/blockSizeX, (sizeY+blockSizeY-1)/blockSizeY if blockX < 0 || blockY < 0 || blockX >= cx || blockY >= cy { return 0, 0 } retx := blockSizeX rety := blockSizeY if blockX == cx-1 { nXPixelOff := blockX * blockSizeX retx = sizeX - nXPixelOff } if blockY == cy-1 { nYPixelOff := blockY * blockSizeY rety = sizeY - nYPixelOff } return retx, rety }
structure.go
0.754915
0.499207
structure.go
starcoder
package main import ( "fmt" ) // tag::set[] // This file contains the exact same counting set as used for day 3. // CountingSet is a set that also knows how often each element has been added. It does support // non-empty strings only. type CountingSet map[string]int // Add adds an entry to the set. The empty string is not supported! func (c *CountingSet) Add(entry string) error { if len(entry) == 0 { return fmt.Errorf("empty string not supported in counting set") } // We don't have to handle non-existing values here since Go returns the zero value (0 for // integers) for such entries. (*c)[entry] = (*c)[entry] + 1 return nil } // Count determines how often an entry has been added to the set. func (c *CountingSet) Count(entry string) int { return (*c)[entry] } // RemoveAll removes all counts for a specific key. func (c *CountingSet) RemoveAll(entry string) { delete(*c, entry) } // MostCommon determines the most common entry in the set. If the set is empty, this returns the // empty string! A non-empty tie breaker will be returned in case there are multiple most common // entries. If the tie breaker is empty but there are duplicates, an empty string will be returned. func (c *CountingSet) MostCommon(tieBreaker string) string { return c.filter( tieBreaker, func(i1, i2 int) bool { return i1 > i2 }, ) } // LeastCommon determines the least common entry in the set. If the set is empty, this returns the // empty string! A non-empty tie breaker will be returned in case there are multiple least common // entries. If the tie breaker is empty but there are duplicates, an empty string will be returned. func (c *CountingSet) LeastCommon(tieBreaker string) string { return c.filter( tieBreaker, func(i1, i2 int) bool { return i1 < i2 }, ) } type comparisonFunc = func(int, int) bool func (c *CountingSet) filter(tieBreaker string, cmpFn comparisonFunc) string { var result string var resultCount int foundOne := false for entry, count := range *c { if !foundOne || cmpFn(count, resultCount) { foundOne = true result = entry resultCount = count } } // Check whether there are any duplicate findings and handle appropriately. for entry, count := range *c { if count == resultCount && entry != result { return tieBreaker } } return result } // end::set[]
day06/go/razziel89/set.go
0.760028
0.417212
set.go
starcoder
package chapter10 import ( "math" ) // MatrixCoordinate represents teh coordinates of a matrix type MatrixCoordinate struct { row int column int } // NewMatrixCoordinate creates a new coordinate func NewMatrixCoordinate(row, col int) MatrixCoordinate { return MatrixCoordinate{ row: row, column: col, } } func (mc MatrixCoordinate) inbounds(matrix [][]int) bool { return mc.row >= 0 && mc.column >= 0 && mc.row < len(matrix) && mc.column < len(matrix[0]) } func (mc MatrixCoordinate) clone() MatrixCoordinate { return MatrixCoordinate{ row: mc.row, column: mc.column, } } func (mc *MatrixCoordinate) setToAverage(min, max MatrixCoordinate) { mc.row = (min.row + max.row) / 2 mc.column = (min.column + max.column) / 2 } func (mc MatrixCoordinate) isBefore(end MatrixCoordinate) bool { return mc.row <= end.row && mc.column <= end.column } // FindElementInSortedMatrix finds x in a matrix that is sorted by both row and column func FindElementInSortedMatrix(matrix [][]int, x int) *MatrixCoordinate { origin := NewMatrixCoordinate(0, 0) dest := NewMatrixCoordinate(len(matrix)-1, len(matrix[0])-1) return findElementInSortedMatrix(matrix, origin, dest, x) } func findElementInSortedMatrix(matrix [][]int, origin, dest MatrixCoordinate, x int) *MatrixCoordinate { if !origin.inbounds(matrix) || !dest.inbounds(matrix) { return nil } if matrix[origin.row][origin.column] == x { return &origin } // Set start to start of diagonal and end tot he end of the diagonal. Since the grid may not be square. The end of // the grid may not be square, the end of the diagonal may not be equal to the destination start := origin.clone() diagDist := int(math.Min(float64(dest.row-origin.row), float64(dest.column-origin.column))) end := NewMatrixCoordinate(start.row+diagDist, start.column+diagDist) p := NewMatrixCoordinate(0, 0) // Do binary search on the diagonal, looking for the first element > x */ for start.isBefore(end) { p.setToAverage(start, end) if x > matrix[p.row][p.column] { start.row = p.row + 1 start.column = p.column + 1 } else { end.row = p.row - 1 end.column = p.column - 1 } } // Split the grid into quadrants. Search the bottom left and the top right return partitionSearch(matrix, origin, dest, start, x) } func partitionSearch(matrix [][]int, origin, dest, pivot MatrixCoordinate, x int) *MatrixCoordinate { lowerLeftOrigin := NewMatrixCoordinate(pivot.row, origin.column) lowerLeftDest := NewMatrixCoordinate(dest.row, pivot.column-1) upperRightOrigin := NewMatrixCoordinate(origin.row, pivot.column) upperRightDest := NewMatrixCoordinate(pivot.row-1, dest.column) lowerLeft := findElementInSortedMatrix(matrix, lowerLeftOrigin, lowerLeftDest, x) if lowerLeft == nil { return findElementInSortedMatrix(matrix, upperRightOrigin, upperRightDest, x) } return lowerLeft }
chapter10/9_matrix_sort.go
0.877837
0.600686
9_matrix_sort.go
starcoder
package neat import ( "errors" "fmt" "github.com/yaricom/goNEAT/v2/neat/math" "math/rand" ) // NumTraitParams The number of parameters used in neurons that learn through habituation, sensitization or Hebbian-type processes const NumTraitParams = 8 var ( ErrTraitsParametersCountMismatch = errors.New("traits parameters number mismatch") ) // Trait is a group of parameters that can be expressed as a group more than one time. Traits save a genetic // algorithm from having to search vast parameter landscapes on every node. Instead, each node can simply point to a trait // and those traits can evolve on their own. type Trait struct { // The trait ID Id int `yaml:"id"` // The learned trait parameters Params []float64 `yaml:"params"` } // NewTrait is to create empty trait with default parameters number (see: NumTraitParams above) func NewTrait() *Trait { trait := newTrait(NumTraitParams) return trait } // NewTraitCopy The copy constructor func NewTraitCopy(t *Trait) *Trait { nt := newTrait(len(t.Params)) nt.Id = t.Id for i, p := range t.Params { nt.Params[i] = p } return nt } // NewTraitAvrg Special Constructor creates a new Trait which is the average of two existing traits passed in func NewTraitAvrg(t1, t2 *Trait) (*Trait, error) { if len(t1.Params) != len(t2.Params) { return nil, ErrTraitsParametersCountMismatch } nt := newTrait(len(t1.Params)) nt.Id = t1.Id for i := 0; i < len(t1.Params); i++ { nt.Params[i] = (t1.Params[i] + t2.Params[i]) / 2.0 } return nt, nil } // The default private constructor func newTrait(length int) *Trait { return &Trait{ Params: make([]float64, length), } } // Mutate perturb the trait parameters slightly func (t *Trait) Mutate(traitMutationPower, traitParamMutProb float64) { for i := 0; i < len(t.Params); i++ { if rand.Float64() > traitParamMutProb { t.Params[i] += float64(math.RandSign()) * rand.Float64() * traitMutationPower if t.Params[i] < 0 { t.Params[i] = 0 } } } } func (t *Trait) String() string { s := fmt.Sprintf("Trait #%d (", t.Id) for _, p := range t.Params { s = fmt.Sprintf("%s %f", s, p) } s = fmt.Sprintf("%s )", s) return s }
neat/trait.go
0.657868
0.40116
trait.go
starcoder
package droid import ( "fmt" "github.com/bogosj/advent-of-code/2019/computer" "github.com/bogosj/advent-of-code/intmath" ) type state struct { // Whether these directions have been explored. eN, eS, eW, eE bool isWall bool isO2 bool } // Droid represents a repair droid. type Droid struct { c *computer.Computer m map[intmath.Point]*state cur intmath.Point opp map[int]int in chan int out <-chan int } // New creates a new Droid based on the provided file path program. func New(n string) *Droid { c := computer.New(n) d := Droid{c: c} d.m = map[intmath.Point]*state{} s := state{} d.m[intmath.Point{}] = &s d.opp = map[int]int{1: 2, 2: 1, 3: 4, 4: 3} return &d } // pointInDir returns the potential new point to explore, and the state of that point. func pointInDir(p intmath.Point, dir int) (intmath.Point, *state) { switch dir { case 1: return intmath.Point{X: p.X, Y: p.Y + 1}, &state{eS: true} case 2: return intmath.Point{X: p.X, Y: p.Y - 1}, &state{eN: true} case 3: return intmath.Point{X: p.X - 1, Y: p.Y}, &state{eE: true} case 4: return intmath.Point{X: p.X + 1, Y: p.Y}, &state{eW: true} } return intmath.Point{}, nil } func (d *Droid) move(dir int) bool { p, ns := pointInDir(d.cur, dir) switch dir { case 1: d.m[d.cur].eN = true case 2: d.m[d.cur].eS = true case 3: d.m[d.cur].eW = true case 4: d.m[d.cur].eE = true } d.in <- dir out := <-d.out if out == 0 { ns.isWall = true d.m[p] = ns return false } d.cur = p _, ok := d.m[d.cur] if !ok { d.m[d.cur] = ns } if out == 2 { d.m[d.cur].isO2 = true } return true } // Walk makes the droid walk and find all paths to the goal. func (d *Droid) Walk() (ret [][]int) { d.in = make(chan int) d.out = d.c.Compute(d.in) path := []int{} for { s := d.m[d.cur] dir := 0 if !s.eN { dir = 1 } else if !s.eS { dir = 2 } else if !s.eW { dir = 3 } else if !s.eE { dir = 4 } if dir == 0 { // Backtrack if len(path) == 0 { return } dir, path = path[len(path)-1], path[:len(path)-1] d.move(d.opp[dir]) } else { moved := d.move(dir) if moved { path = append(path, dir) } if d.m[d.cur].isO2 { ret = append(ret, path) } continue } } } // PrintMap renders the map to stdout. func (d *Droid) PrintMap() { var allX, allY []int for k := range d.m { allX = append(allX, k.X) allY = append(allY, k.Y) } minX := intmath.Min(allX...) minY := intmath.Min(allY...) maxX := intmath.Max(allX...) maxY := intmath.Max(allY...) for x := minX; x <= maxX; x++ { for y := minY; y <= maxY; y++ { s, ok := d.m[intmath.Point{X: x, Y: y}] if ok { if s.isWall { fmt.Print("#") } else if s.isO2 { fmt.Print("O") } else { fmt.Print(".") } } else { fmt.Print("?") } } fmt.Println() } } func (d *Droid) lackO2Points() (ret []intmath.Point) { for k, v := range d.m { if !v.isO2 && !v.isWall { ret = append(ret, k) } } return } func (d *Droid) o2Points() (ret []intmath.Point) { for k, v := range d.m { if v.isO2 { ret = append(ret, k) } } return } // ExpandO2 redraws the map placing oxygen in cells that neighbor other oxygen. // It returns the number of minutes it took to fill the space with oxygen. func (d *Droid) ExpandO2() (minutes int) { for len(d.lackO2Points()) > 0 { o2p := d.o2Points() for _, p := range o2p { ns := p.Neighbors() for _, n := range ns { if newO2Point, ok := d.m[n]; ok { if !newO2Point.isWall { newO2Point.isO2 = true } } } } minutes++ } return }
2019/day15/droid/droid.go
0.634543
0.461563
droid.go
starcoder
package geom //GeometryCollection is a collection of two-dimensional geometries type GeometryCollection []Geometry //GeometryCollectionZ is a collection of three-dimensional geometries type GeometryCollectionZ []GeometryZ //GeometryCollectionM is a collection of two-dimensional geometries, with an additional value defined on each vertex type GeometryCollectionM []GeometryM //GeometryCollectionZM is a collection of three-dimensional geometries, with an additional value defined on each vertex type GeometryCollectionZM []GeometryZM //Envelope returns an envelope around the GeometryCollection func (c GeometryCollection) Envelope() *Envelope { e := NewEnvelope() for _, g := range c { e.Extend(g.Envelope()) } return e } //Envelope returns an envelope around the geometry collection func (c GeometryCollectionZ) Envelope() *Envelope { e := NewEnvelope() for _, g := range c { e.Extend(g.Envelope()) } return e } //EnvelopeZ returns an envelope around the geometry collection func (c GeometryCollectionZ) EnvelopeZ() *EnvelopeZ { e := NewEnvelopeZ() for _, g := range c { e.Extend(g.EnvelopeZ()) } return e } //Envelope returns an envelope around the geometry collection func (c GeometryCollectionM) Envelope() *Envelope { e := NewEnvelope() for _, g := range c { e.Extend(g.Envelope()) } return e } //EnvelopeM returns an envelope around the geometry collection func (c GeometryCollectionM) EnvelopeM() *EnvelopeM { e := NewEnvelopeM() for _, g := range c { e.Extend(g.EnvelopeM()) } return e } //Envelope returns an envelope around the geometry collection func (c GeometryCollectionZM) Envelope() *Envelope { e := NewEnvelope() for _, g := range c { e.Extend(g.Envelope()) } return e } //EnvelopeZ returns an envelope around the geometry collection func (c GeometryCollectionZM) EnvelopeZ() *EnvelopeZ { e := NewEnvelopeZ() for _, g := range c { e.Extend(g.EnvelopeZ()) } return e } //EnvelopeM returns an envelope around the geometry collection func (c GeometryCollectionZM) EnvelopeM() *EnvelopeM { e := NewEnvelopeM() for _, g := range c { e.Extend(g.EnvelopeM()) } return e } //EnvelopeZM returns an envelope around the GeometryCollection func (c GeometryCollectionZM) EnvelopeZM() *EnvelopeZM { e := NewEnvelopeZM() for _, g := range c { e.Extend(g.EnvelopeZM()) } return e } //Clone returns a deep copy of the geometry collection func (c GeometryCollection) Clone() Geometry { return &c } //Clone returns a deep copy of the geometry collection func (c GeometryCollectionZ) Clone() Geometry { return &c } //Clone returns a deep copy of the geometry collection func (c GeometryCollectionM) Clone() Geometry { return &c } //Clone returns a deep copy of the geometry collection func (c GeometryCollectionZM) Clone() Geometry { return &c } //Iterate walks over the points (and can modify in situ) the geometry collection func (c GeometryCollection) Iterate(f func([]Point) error) error { for i := range c { if err := c[i].Iterate(f); err != nil { return err } } return nil } //Iterate walks over the points (and can modify in situ) the geometry collection func (c GeometryCollectionZ) Iterate(f func([]Point) error) error { for i := range c { if err := c[i].Iterate(f); err != nil { return err } } return nil } //Iterate walks over the points (and can modify in situ) the geometry collection func (c GeometryCollectionM) Iterate(f func([]Point) error) error { for i := range c { if err := c[i].Iterate(f); err != nil { return err } } return nil } //Iterate walks over the points (and can modify in situ) the geometry collection func (c GeometryCollectionZM) Iterate(f func([]Point) error) error { for i := range c { if err := c[i].Iterate(f); err != nil { return err } } return nil }
geometrycollection.go
0.911535
0.594257
geometrycollection.go
starcoder
package helpers import "github.com/lquesada/cavernal/model" import "github.com/lquesada/cavernal/entity" import "github.com/lquesada/cavernal/entity/humanoid" import "github.com/lquesada/cavernal/lib/g3n/engine/math32" type BasicHumanoidEquipable struct { BasicEquipable cloneSpecification *BasicHumanoidEquipableSpecification armRightNode model.INode armLeftNode model.INode legRightNode model.INode legLeftNode model.INode } func (e *BasicHumanoidEquipable) ArmRightNode() model.INode { return e.armRightNode } func (e *BasicHumanoidEquipable) ArmLeftNode() model.INode { return e.armLeftNode } func (e *BasicHumanoidEquipable) LegRightNode() model.INode { return e.legRightNode } func (e *BasicHumanoidEquipable) LegLeftNode() model.INode { return e.legLeftNode } func (e *BasicHumanoidEquipable) Clone() entity.IItem { return e.cloneSpecification.New() } type BasicHumanoidEquipableSpecification struct { BasicEquipableSpecification ArmRightNode model.INode ArmLeftNode model.INode LegRightNode model.INode LegLeftNode model.INode CoverDrawSlots []entity.DrawSlotId } func (s *BasicHumanoidEquipableSpecification) New() *BasicHumanoidEquipable { e := s.BasicEquipableSpecification.New() e.SetCoverDrawSlots(append(e.CoverDrawSlots(), s.CoverDrawSlots...)) return &BasicHumanoidEquipable{ BasicEquipable: *e, armRightNode: s.ArmRightNode, armLeftNode: s.ArmLeftNode, legRightNode: s.LegRightNode, legLeftNode: s.LegLeftNode, cloneSpecification: s, } } // -- func NewBasicArmor(category entity.ItemCategory, name string, defense int, main, armLeft, armRight *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Armor, BodyType: humanoid.HumanoidBody, DefenseValue: defense, EquippedNode: main.Build(), DroppedNode: model.NewNode( main.Build(), armLeft.Build().Transform( (&model.Transform{ Position: humanoid.ArmLeftTransformPosition, Rotation: &math32.Vector3{math32.Pi/2, 0, 0}, }).Inverse()), armRight.Build().Transform( (&model.Transform{ Position: humanoid.ArmRightTransformPosition, Rotation: &math32.Vector3{math32.Pi/2, 0, 0}, }).Inverse()), ), InventoryNode: model.NewNode( main.Build(), armLeft.Build().Transform( (&model.Transform{ Position: humanoid.ArmLeftTransformPosition, Rotation: &math32.Vector3{math32.Pi/2, 0, 0}, }).Inverse()), armRight.Build().Transform( (&model.Transform{ Position: humanoid.ArmRightTransformPosition, Rotation: &math32.Vector3{math32.Pi/2, 0, 0}, }).Inverse()), ), }, ArmLeftNode: armLeft.Build(), ArmRightNode: armRight.Build(), CoverDrawSlots: []entity.DrawSlotId{humanoid.ProtrudeNeck}, } } func NewBasicPants(category entity.ItemCategory, name string, defense int, main, legLeft, legRight *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Pants, BodyType: humanoid.HumanoidBody, DefenseValue: defense, EquippedNode: main.Build(), DroppedNode: model.NewNode( legLeft.Build(), legRight.Build(), ), InventoryNode: model.NewNode( legLeft.Build(), legRight.Build(), ), }, LegLeftNode: legLeft.Build(), LegRightNode: legRight.Build(), } } func NewBasicBoots(category entity.ItemCategory, name string, defense int, legLeft, legRight *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Boots, BodyType: humanoid.HumanoidBody, DefenseValue: defense, DroppedNode: model.NewNode( legLeft.Build(), legRight.Build(), ), InventoryNode: model.NewNode( legLeft.Build(), legRight.Build(), ), }, LegLeftNode: legLeft.Build(), LegRightNode: legRight.Build(), } } func NewBasicAmulet(category entity.ItemCategory, name string, defense int, attack int, main *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Amulet, BodyType: humanoid.HumanoidBody, DefenseValue: defense, AttackValue: attack, EquippedNode: main.Build(), DroppedNode: main.Build(), InventoryNode: main.Build(), }, } } func NewBasicBackpack(category entity.ItemCategory, name string, defense int, attack int, main *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Back, BodyType: humanoid.HumanoidBody, DefenseValue: defense, AttackValue: attack, EquippedNode: main.Build(), DroppedNode: main.Build(), InventoryNode: main.Build(), }, } } func NewBasicGloves(category entity.ItemCategory, name string, defense int, armLeft, armRight *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Gloves, BodyType: humanoid.HumanoidBody, DefenseValue: defense, DroppedNode: model.NewNode( armLeft.Build(), armRight.Build(), ), InventoryNode: model.NewNode( armLeft.Build(), armRight.Build(), ), }, ArmLeftNode: armLeft.Build(), ArmRightNode: armRight.Build(), CoverDrawSlots: []entity.DrawSlotId{humanoid.ProtrudeHandLeft, humanoid.ProtrudeHandRight}, } } func NewBasicHelmet(category entity.ItemCategory, name string, defense int, main *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Helmet, BodyType: humanoid.HumanoidBody, DefenseValue: defense, EquippedNode: main.Build(), DroppedNode: main.Build().Transform(&model.Transform{ Position: &math32.Vector3{0, -0.8, 0}, }, ), InventoryNode: main.Build().Transform(&model.Transform{ Position: &math32.Vector3{0, -0.9, 0}, }, ), }, CoverDrawSlots: []entity.DrawSlotId{humanoid.ProtrudeHeadUpOrBackLong, humanoid.ProtrudeHeadSidesShort, humanoid.ProtrudeHeadSidesLong}, } } func NewBasicRing(category entity.ItemCategory, name string, defense, attack int, armLeft, armRight *model.NodeSpec) *BasicHumanoidEquipableSpecification { return &BasicHumanoidEquipableSpecification{ BasicEquipableSpecification: BasicEquipableSpecification{ Category: category, Name: name, ItemType: humanoid.Ring, BodyType: humanoid.HumanoidBody, DefenseValue: defense, DroppedNode: model.NewNode( armRight.Build(), ), InventoryNode: model.NewNode( armRight.Build(), ), }, ArmLeftNode: armLeft.Build(), ArmRightNode: armRight.Build(), } }
helpers/basichumanoidequipable.go
0.541409
0.515681
basichumanoidequipable.go
starcoder
package strassen import ( "math" "github.com/Rongcong/algorithms/data-structures/matrix" ) func Multiply(A *matrix.Matrix, B *matrix.Matrix) *matrix.Matrix { n := A.CountRows() bigN := scaleSize(n) bigA := matrix.MakeMatrix(make([]float64, bigN*bigN), bigN, bigN) bigB := matrix.MakeMatrix(make([]float64, bigN*bigN), bigN, bigN) for i := 0; i < n; i++ { for j := 0; j < n; j++ { bigA.SetElm(i, j, A.GetElm(i, j)) bigB.SetElm(i, j, B.GetElm(i, j)) } } bigC := recurse(bigA, bigB) C := matrix.MakeMatrix(make([]float64, n*n), n, n) for i := 0; i < n; i++ { for j := 0; j < n; j++ { C.SetElm(i, j, bigC.GetElm(i, j)) } } return C } func recurse(A *matrix.Matrix, B *matrix.Matrix) *matrix.Matrix { n := A.CountRows() newSize := n / 2 if n < 2 { return matrix.MakeMatrix([]float64{A.GetElm(0, 0) * B.GetElm(0, 0)}, 1, 1) } A11 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) A12 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) A21 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) A22 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) B11 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) B12 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) B21 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) B22 := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) for i := 0; i < newSize; i++ { for j := 0; j < newSize; j++ { A11.SetElm(i, j, A.GetElm(i, j)) A12.SetElm(i, j, A.GetElm(i, j+newSize)) A21.SetElm(i, j, A.GetElm(i+newSize, j)) A22.SetElm(i, j, A.GetElm(i+newSize, j+newSize)) B11.SetElm(i, j, B.GetElm(i, j)) B12.SetElm(i, j, B.GetElm(i, j+newSize)) B21.SetElm(i, j, B.GetElm(i+newSize, j)) B22.SetElm(i, j, B.GetElm(i+newSize, j+newSize)) } } a := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) b := matrix.MakeMatrix(make([]float64, newSize*newSize), newSize, newSize) // P1 = (A11 + A22) * (B11 + B22) a = matrix.Add(A11, A22) b = matrix.Add(B11, B22) P1 := recurse(a, b) // P2 = (A21 + A22) * (B11) a = matrix.Add(A21, A22) P2 := recurse(a, B11) // P3 = (A11) * (B12 - B11) b = matrix.Substract(B12, B22) P3 := recurse(A11, b) // P4 = A22 * (B21 - B22) b = matrix.Substract(B21, B11) P4 := recurse(A22, b) // P5 = (A11 + A12) * B22 a = matrix.Add(A11, A12) P5 := recurse(a, B22) // P6 = (A21 - A11) * (B11 + B12) a = matrix.Substract(A21, A11) b = matrix.Add(B11, B12) P6 := recurse(a, b) // P7 = (A12 - A22) * (B21 + B22) a = matrix.Substract(A12, A22) b = matrix.Add(B21, B22) P7 := recurse(a, b) // Aggregates the result into C C12 := matrix.Add(P3, P5) C21 := matrix.Add(P2, P4) a = matrix.Add(P1, P4) b = matrix.Add(a, P7) C11 := matrix.Substract(b, P5) a = matrix.Add(P1, P3) b = matrix.Add(a, P6) C22 := matrix.Substract(b, P2) C := matrix.MakeMatrix(make([]float64, n*n), n, n) for i := 0; i < newSize; i++ { for j := 0; j < newSize; j++ { C.SetElm(i, j, C11.GetElm(i, j)) C.SetElm(i, j+newSize, C12.GetElm(i, j)) C.SetElm(i+newSize, j, C21.GetElm(i, j)) C.SetElm(i+newSize, j+newSize, C22.GetElm(i, j)) } } return C } func scaleSize(n int) int { log2 := math.Ceil(math.Log(float64(n)) / math.Log(float64(2))) return int(math.Pow(2, log2)) }
algorithms/maths/strassen/strassen.go
0.640861
0.522141
strassen.go
starcoder
package ghist // Percentile returns a float64 of the percentile of a given value in the histogram func (h *Histogram) Percentile(value float64) (percentile float64) { var position uint64 for i := h.Size - 1; i >= 0; i-- { // iterate in reverse to get a percentile if h.Bins[i].Count == 0 { continue } if value > h.Bins[i].Max { position += h.Bins[i].Count } else if value >= h.Bins[i].Min { // linear estimate of value's position in its bin pct := 0.5 if h.Bins[i].Max-h.Bins[i].Min > 0.0 { pct = (value - h.Bins[i].Min) / (h.Bins[i].Max - h.Bins[i].Min) } position += uint64(float64(h.Bins[i].Count) * pct) break } } return float64(position) / float64(h.Count) } // Percentile32 returns Percentile() as a float32 func (h *Histogram) Percentile32(value float32) (percentile float32) { return float32(h.Percentile(float64(value))) } // Median returns an estimate of the distribution's median value by interpolating within // the bucket that contains the median value func (h *Histogram) Median() (median float64) { var ( midPoint uint64 = h.Count / 2 seenCount uint64 = 0 ) for i := 0; i < h.Size; i++ { seenCount += h.Bins[i].Count if seenCount >= midPoint { if h.Bins[i].Count > 1 { offset := 1 - (float64(seenCount-midPoint) / float64(h.Bins[i].Count-1)) return h.Bins[i].Max - offset*(h.Bins[i].Max-h.Bins[i].Min) } return h.Bins[i].Max } } return } // Median32 returns Median() as a float32 func (h *Histogram) Median32() (median float32) { return float32(h.Median()) } // Mean returns the mean value of the histogram func (h *Histogram) Mean() (mean float64) { if h.Count > 0 { mean = h.Sum / float64(h.Count) } return } // Mean32 returns Mean() as a float32 func (h *Histogram) Mean32() (mean float32) { return float32(h.Mean()) } // Mode returns the most populated Bin in the histogram func (h *Histogram) Mode() (mode Bin) { var ( modeIndex = 0 maxCount uint64 = 0 ) if h.Size > 0 { for i := 0; i < h.Size; i++ { if h.Bins[i].Count > maxCount { modeIndex = i maxCount = h.Bins[i].Count } } mode = h.Bins[modeIndex] } return }
statistics.go
0.829871
0.669286
statistics.go
starcoder
package deps import ( "testing" "github.com/stretchr/testify/assert" "github.com/pip-services/pip-services-runtime-go" "github.com/pip-services/pip-clients-quotes-go/version1" ) type QuotesClientFixture struct { client quotes_v1.IQuotesClient } func NewQuotesClientFixture(client quotes_v1.IQuotesClient) *QuotesClientFixture { return &QuotesClientFixture { client: client } } var QUOTE1 *quotes_v1.Quote = createQuote("", "Text 1", "Author 1") var QUOTE2 *quotes_v1.Quote = createQuote("", "Text 2", "Author 2") func createQuote(id, text, author string) *quotes_v1.Quote { return &quotes_v1.Quote { ID: "", Text: map[string]string { "en": text }, Author: map[string]string { "en": author }, Status: "new", Tags: []string {}, AllTags: []string {}, } } func (c *QuotesClientFixture) TestCrudOperations(t *testing.T) { // Create one quote quote1, err := c.client.CreateQuote(QUOTE1) assert.Nil(t, err) assert.NotNil(t, quote1) assert.NotEmpty(t, quote1.ID) assert.Equal(t, QUOTE1.Text["en"], quote1.Text["en"]) assert.Equal(t, QUOTE1.Author["en"], quote1.Author["en"]) // Create another quote quote2, err := c.client.CreateQuote(QUOTE2) assert.Nil(t, err) assert.NotNil(t, quote2) assert.NotEmpty(t, quote2.ID) assert.Equal(t, QUOTE2.Text["en"], quote2.Text["en"]) assert.Equal(t, QUOTE2.Author["en"], quote2.Author["en"]) // Get all quotes quotes, err2 := c.client.GetQuotes(nil, nil) assert.Nil(t, err2) assert.NotNil(t, quotes) assert.NotNil(t, quotes.Data) assert.True(t, len(quotes.Data) >= 2) // Update the quote quoteData := runtime.NewMapAndSet("text.en", "Updated Text 1") quote1, err = c.client.UpdateQuote(quote1.ID, quoteData) assert.Nil(t, err) assert.NotNil(t, quote1) assert.Equal(t, "Updated Text 1", quote1.Text["en"]) // Delete the quote #1 err = c.client.DeleteQuote(quote1.ID) assert.Nil(t, err) // Delete the quote #2 err = c.client.DeleteQuote(quote2.ID) assert.Nil(t, err) // Try to get deleted quote quote1, err = c.client.GetQuoteById(quote1.ID) assert.Nil(t, err) assert.Nil(t, quote1) }
test/version1/QuotesClientFixture.go
0.634656
0.404096
QuotesClientFixture.go
starcoder
package main import ( "cloud.google.com/go/bigquery" "github.com/maruel/subcommands" "go.chromium.org/luci/auth" "go.chromium.org/luci/common/cli" "go.chromium.org/luci/common/data/text" "go.chromium.org/luci/common/errors" ) func cmdFetchRejections(authOpt *auth.Options) *subcommands.Command { return &subcommands.Command{ UsageLine: `fetch-rejections`, ShortDesc: "fetch test rejection data", LongDesc: text.Doc(` Fetch change rejection data, suitable for model creation. For format details, see comments of Rejection protobuf message. `), CommandRun: func() subcommands.CommandRun { r := &fetchRejectionsRun{} r.authOpt = authOpt r.RegisterBaseFlags(&r.Flags) r.Flags.IntVar(&r.minCLFlakes, "min-cl-flakes", 5, text.Doc(` In order to conlude that a test variant is flaky and exclude it from analysis, it must have mixed results in <min-cl-flakes> unique CLs. `)) r.Flags.IntVar(&r.failedVariantsLimit, "failed-variants-limit", 100000, text.Doc(` The number of failed test variants in a patchset we truncate to. This config helps prevent row size overflows in the rejections query. `)) return r }, } } type fetchRejectionsRun struct { baseCommandRun baseHistoryRun minCLFlakes int failedVariantsLimit int } func (r *fetchRejectionsRun) Run(a subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(a, r, env) if len(args) != 0 { return r.done(errors.New("unexpected positional arguments")) } if err := r.baseHistoryRun.Init(ctx); err != nil { return r.done(err) } return r.done(r.runAndFetchResults( ctx, rejectedPatchSetsSQL, bigquery.QueryParameter{ Name: "minCLFlakes", Value: r.minCLFlakes, }, bigquery.QueryParameter{ Name: "failedVariantsLimit", Value: r.failedVariantsLimit, }, )) } // rejectedPatchSetsSQL is a BigQuery query that returns patchsets with test // failures. Excludes flaky tests. const rejectedPatchSetsSQL = commonSubqueries + ` -- Group all test results by patchset, test_id and variant_hash -- in order to analyze individual test variants in each patchset, -- and in particular exclude flaky tests. test_variants_per_ps AS ( SELECT change, patchset, testVariant.id AS test_id, variant_hash, ANY_VALUE(testVariant) as testVariant, LOGICAL_OR(expected) AND LOGICAL_OR(NOT expected) AS flake, # Sometimes ResultDB table misses data. For example, if a test # flaked, the table might miss the pass, and it might look like the test # has failed. Also sometimes builds are incomplete because they # infra-failed or were canceled midway, and the test results do not # represent the whole picture. In particular, CANCELED might mean that the # "without patch" part didn't finish and test results were not properly # exonerated. # Thus ensure that the build has failed too. LOGICAL_AND(NOT expected) AND LOGICAL_AND(t.status = 'FAILURE') all_unexpected, ANY_VALUE(ps_approx_timestamp) AS ps_approx_timestamp, FROM tryjobs_with_status t JOIN test_results_base tr ON t.id = tr.build_id WHERE not exonerated AND tr.status != 'SKIP' -- not needed for RTS purposes GROUP BY change, patchset, test_id, variant_hash # Exclude all-expected results early on. HAVING NOT LOGICAL_AND(expected) ), -- Find all true test failures, without flakes. failed_test_variants AS ( SELECT test_id, variant_hash, ANY_VALUE(testVariant) AS testVariant, ARRAY_AGG( IF(all_unexpected, STRUCT(change, patchset, ps_approx_timestamp), NULL) IGNORE NULLS ) AS patchsets_with_failures, FROM test_variants_per_ps GROUP BY test_id, variant_hash # Exclude test variants where flakiness was observed in @minCLFlakes CLs # (not patchsets) or more. HAVING COUNT(DISTINCT IF(flake, change, NULL)) < @minCLFlakes ) -- Join all tables and produce rows in the Rejection protojson format. SELECT patchsetArray(change, patchset, ANY_VALUE(files)) AS patchsets, RFC3339(MIN(ps_approx_timestamp)) as timestamp, ARRAY_AGG(testVariant LIMIT @failedVariantsLimit) as failedTestVariants FROM failed_test_variants tv, tv.patchsets_with_failures JOIN affected_files USING (change, patchset) GROUP BY change, patchset `
go/src/infra/rts/cmd/rts-chromium/rejections.go
0.593138
0.401717
rejections.go
starcoder
package engine // Cropped quantity refers to a cut-out piece of a large quantity import ( "fmt" "github.com/mumax/3/cuda" "github.com/mumax/3/data" "github.com/mumax/3/util" ) func init() { DeclFunc("Crop", Crop, "Crops a quantity to cell ranges [x1,x2[, [y1,y2[, [z1,z2[") DeclFunc("CropX", CropX, "Crops a quantity to cell ranges [x1,x2[") DeclFunc("CropY", CropY, "Crops a quantity to cell ranges [y1,y2[") DeclFunc("CropZ", CropZ, "Crops a quantity to cell ranges [z1,z2[") DeclFunc("CropLayer", CropLayer, "Crops a quantity to a single layer") } type cropped struct { parent Quantity name string x1, x2, y1, y2, z1, z2 int } func CropLayer(parent Quantity, layer int) *cropped { n := parent.Mesh().Size() return Crop(parent, 0, n[X], 0, n[Y], layer, layer+1) } func CropX(parent Quantity, x1, x2 int) *cropped { n := parent.Mesh().Size() return Crop(parent, x1, x2, 0, n[Y], 0, n[Z]) } func CropY(parent Quantity, y1, y2 int) *cropped { n := parent.Mesh().Size() return Crop(parent, 0, n[X], y1, y2, 0, n[Z]) } func CropZ(parent Quantity, z1, z2 int) *cropped { n := parent.Mesh().Size() return Crop(parent, 0, n[X], 0, n[Y], z1, z2) } func Crop(parent Quantity, x1, x2, y1, y2, z1, z2 int) *cropped { n := parent.Mesh().Size() util.Argument(x1 < x2 && y1 < y2 && z1 < z2) util.Argument(x1 >= 0 && y1 >= 0 && z1 >= 0) util.Argument(x2 <= n[X] && y2 <= n[Y] && z2 <= n[Z]) name := parent.Name() if x1 != 0 || x2 != n[X] { name += "_xrange" + rangeStr(x1, x2) } if y1 != 0 || y2 != n[Y] { name += "_yrange" + rangeStr(y1, y2) } if z1 != 0 || z2 != n[Z] { name += "_zrange" + rangeStr(z1, z2) } return &cropped{parent, name, x1, x2, y1, y2, z1, z2} } func rangeStr(a, b int) string { if a+1 == b { return fmt.Sprint(a, "_") } else { return fmt.Sprint(a, "-", b, "_") } // (trailing underscore to separate from subsequent autosave number) } func (q *cropped) NComp() int { return q.parent.NComp() } func (q *cropped) Name() string { return q.name } func (q *cropped) Unit() string { return q.parent.Unit() } func (q *cropped) Mesh() *data.Mesh { c := q.parent.Mesh().CellSize() return data.NewMesh(q.x2-q.x1, q.y2-q.y1, q.z2-q.z1, c[X], c[Y], c[Z]) } func (q *cropped) average() []float64 { return qAverageUniverse(q) } // needed for table func (q *cropped) Average() []float64 { return q.average() } // handy for script func (q *cropped) Slice() (*data.Slice, bool) { src, r := q.parent.Slice() if r { defer cuda.Recycle(src) } dst := cuda.Buffer(q.NComp(), q.Mesh().Size()) cuda.Crop(dst, src, q.x1, q.y1, q.z1) return dst, true }
engine/crop.go
0.712332
0.52275
crop.go
starcoder
package bits import "unicode/utf8" /** This class is used for traversing the succinctly encoded trie. */ type FrozenTrieNode struct { trie *FrozenTrie index uint letter string final bool firstChild uint childCount uint } /** Returns the number of children. */ func (f *FrozenTrieNode) GetChildCount() uint { return f.childCount } /** Returns the FrozenTrieNode for the given child. @param index The 0-based index of the child of this node. For example, if the node has 5 children, and you wanted the 0th one, pass in 0. */ func (f *FrozenTrieNode) GetChild(index uint) FrozenTrieNode { return f.trie.GetNodeByIndex(f.firstChild + index) } /** The FrozenTrie is used for looking up words in the encoded trie. @param data A string representing the encoded trie. @param directoryData A string representing the RankDirectory. The global L1 and L2 constants are used to determine the L1Size and L2size. @param nodeCount The number of nodes in the trie. */ type FrozenTrie struct { data BitString directory RankDirectory letterStart uint } func (f *FrozenTrie) Init(data, directoryData string, nodeCount uint) { f.data.Init(data) f.directory.Init(directoryData, data, nodeCount*2+1, L1, L2) // The position of the first bit of the data in 0th node. In non-root // nodes, this would contain 6-bit letters. f.letterStart = nodeCount*2 + 1 } /** Retrieve the FrozenTrieNode of the trie, given its index in level-order. This is a private function that you don't have to use. */ func (f *FrozenTrie) GetNodeByIndex(index uint) FrozenTrieNode { // retrieve the (dataBits)-bit letter. final := (f.data.Get(f.letterStart+index*dataBits, 1) == 1) letter, ok := mapUintToChar[f.data.Get(f.letterStart+index*dataBits+1, (dataBits-1))] if !ok { panic("illegal: bits -> char failed") } firstChild := f.directory.Select(0, index+1) - index // Since the nodes are in level order, this nodes children must go up // until the next node's children start. childOfNextNode := f.directory.Select(0, index+2) - index - 1 return FrozenTrieNode{ trie: f, index: index, letter: letter, final: final, firstChild: firstChild, childCount: (childOfNextNode - firstChild), } } /** Retrieve the root node. You can use this node to obtain all of the other nodes in the trie. */ func (f *FrozenTrie) GetRoot() FrozenTrieNode { return f.GetNodeByIndex(0) } /** Look-up a word in the trie. Returns true if and only if the word exists in the trie. */ func (f *FrozenTrie) Lookup(word string) bool { node := f.GetRoot() for i, w := 0, 0; i < len(word); i += w { runeValue, width := utf8.DecodeRuneInString(word[i:]) w = width var child FrozenTrieNode var j uint = 0 for ; j < node.GetChildCount(); j++ { child = node.GetChild(j) if child.letter == string(runeValue) { break } } if j == node.GetChildCount() { return false } node = child } return node.final }
frozentrie.go
0.754644
0.476397
frozentrie.go
starcoder
package expect import ( "fmt" "reflect" "regexp" "testing" "vincent.click/pkg/preflight/expect/kind" ) // ExpectedValue is an expectation on a realized value type ExpectedValue struct { *testing.T actual interface{} } // Value returns a new value-based Expectation func Value(t *testing.T, actual interface{}) Expectation { return &ExpectedValue{ T: t, actual: actual, } } // To returns the current expectation func (e *ExpectedValue) To() Expectation { return e } // Be returns the current expectation func (e *ExpectedValue) Be() Expectation { return e } // Is returns the current expectation func (e *ExpectedValue) Is() Expectation { return e } // Should returns the current expectation func (e *ExpectedValue) Should() Expectation { return e } // Not negates the current expectation func (e *ExpectedValue) Not() Expectation { return &Negation{ T: e.T, inverse: e, } } // IsNot is equivalent to Not() func (e *ExpectedValue) IsNot() Expectation { return e.Not() } // DoesNot is equivalent to Not() func (e *ExpectedValue) DoesNot() Expectation { return e.Not() } // At returns an expectation about the element at the given index func (e *ExpectedValue) At(index interface{}) Expectation { k := kind.Of(e.actual) switch k { case kind.List: if i, ok := index.(int); ok { element := reflect.ValueOf(e.actual).Index(i).Interface() return Value(e.T, element) } return Faulty(e.T, fmt.Errorf("%s: slice or array index must be an int", e.Name())) case kind.String: if i, ok := index.(int); ok { element := []rune(e.actual.(string))[i] return Value(e.T, element) } return Faulty(e.T, fmt.Errorf("%s: string index must be an int", e.Name())) case kind.Map: key := reflect.ValueOf(index) element := reflect.ValueOf(e.actual).MapIndex(key).Interface() return Value(e.T, element) default: return Faulty(e.T, fmt.Errorf("%s: %v: not a slice, array, string, or map", e.Name(), e.actual)) } } // Nil asserts the value is nil func (e *ExpectedValue) Nil() { e.Equals(nil) } // True asserts the value is true func (e *ExpectedValue) True() { e.Equals(true) } // False asserts the value is false func (e *ExpectedValue) False() { e.Equals(false) } // Empty asserts the value has length 0 func (e *ExpectedValue) Empty() { e.HasLength(0) } // HasLength asserts the value is an array with a given length func (e *ExpectedValue) HasLength(expected int) { if reflect.ValueOf(e.actual).Len() != expected { e.Errorf("%s: len(%#v) != %d", e.Name(), e.actual, expected) } } // HaveLength is equivalent to HasLength() func (e *ExpectedValue) HaveLength(expected int) { e.HasLength(expected) } // Equals asserts equality to an expected value func (e *ExpectedValue) Equals(expected interface{}) { if !equal(e.actual, expected) { e.Errorf("%s: %#v != %#v", e.Name(), e.actual, expected) } } // Eq is equivalent to Equals() func (e *ExpectedValue) Eq(expected interface{}) { e.Equals(expected) } // Equal is equivalent to Equals() func (e *ExpectedValue) Equal(expected interface{}) { e.Equals(expected) } // EqualTo is equivalent to Equals() func (e *ExpectedValue) EqualTo(expected interface{}) { e.Equals(expected) } // Matches asserts that the value matches a given pattern func (e *ExpectedValue) Matches(pattern string) { str := fmt.Sprint(e.actual) match, err := regexp.MatchString(pattern, str) if err != nil { e.Errorf("%s: %s", e.Name(), err) } else if !match { e.Errorf("%s: '%s' does not match /%s/", e.Name(), str, pattern) } } // Match is equivalent to Matches() func (e *ExpectedValue) Match(pattern string) { e.Matches(pattern) }
expect/value.go
0.841956
0.621684
value.go
starcoder
package dusl import ( "fmt" ) // Undent transforms a source text into a syntax tree of unparsed sentences. func Undent(src *Source) *Syntax { ambit := src.FullAmbit() return undent(ambit) } func undent(ambit *Ambit) *Syntax { for !ambit.IsEmpty() { indentedLineAmbit, remainderAmbit := ambit.SplitLine() lineIndent, lineAmbit := indentedLineAmbit.StripIndent() if lineAmbit.IsWhitespace() || lineAmbit.FirstByteIs('#') { ambit = remainderAmbit continue } margin := lineIndent if margin % 2 != 0 { return &Syntax{ Cat: "ERR", Err: fmt.Sprintf("first line indented with odd number of spaces"), Ambit: lineAmbit } } root, _ := undentSequence(margin, 0, ambit) return root } return &Syntax{ Ambit: ambit } } func undentSequence(margin int, currIndent int, ambit *Ambit) (*Syntax, *Ambit) { for !ambit.IsEmpty() { indentedLineAmbit, remainderAmbit := ambit.SplitLine() lineIndent, lineAmbit := indentedLineAmbit.StripIndent() if lineAmbit.IsWhitespace() || lineAmbit.FirstByteIs('#') { ambit = remainderAmbit continue } lineIndent -= margin if lineIndent >= 0 && lineIndent < currIndent { return &Syntax{ Ambit: ambit.CollapseLeft() }, ambit } var head *Syntax if lineIndent < 0 { head = &Syntax{ Cat: "ERR", Err: fmt.Sprintf("line indented %d space(s) before source margin", -lineIndent), Ambit: lineAmbit } } else if lineIndent == currIndent { head, remainderAmbit = undentSentence(margin, currIndent, lineAmbit, remainderAmbit) } else if lineIndent == currIndent+1 { head = &Syntax{ Cat: "ERR", Err: fmt.Sprintf("line indented with odd number of spaces"), Ambit: lineAmbit } } else if lineIndent >= currIndent+2 && lineIndent < currIndent+5 { head = &Syntax{ Cat: "ERR", Err: fmt.Sprintf("line indented more than 2 and less than 5 spaces with respect to previous line: indent 2 spaces for sub-block: indent 5 spaces or more for continuing previous line"), Ambit: lineAmbit } } else if lineIndent >= currIndent + 5 { head = &Syntax{ Cat: "ERR", Err: fmt.Sprintf("line continuation not possible here: indent less than 5 spaces with respect to previous line"), Ambit: lineAmbit } } var tail *Syntax tail, remainderAmbit = undentSequence(margin, currIndent, remainderAmbit) return &Syntax{ Cat: "SQ", Ambit: head.Ambit.Merge(tail.Ambit), Left: head, Right: tail }, remainderAmbit } return &Syntax{ Ambit: ambit }, ambit } func undentSentence(margin int, currIndent int, firstLineAmbit *Ambit, ambit *Ambit) (*Syntax, *Ambit) { sentenceAmbit := firstLineAmbit for !ambit.IsEmpty() { indentedLineAmbit, remainderAmbit := ambit.SplitLine() lineIndent, lineAmbit := indentedLineAmbit.StripIndent() if lineAmbit.IsWhitespace()|| lineAmbit.FirstByteIs('#') { sentenceAmbit = sentenceAmbit.Merge(lineAmbit) ambit = remainderAmbit continue } if lineIndent < margin + currIndent + 5 { break } sentenceAmbit = sentenceAmbit.Merge(lineAmbit) ambit = remainderAmbit } var subSequence *Syntax subSequence, ambit = undentSequence(margin, currIndent+2, ambit) return &Syntax{ Cat: "SN", Ambit: sentenceAmbit.Merge(subSequence.Ambit), Left: &Syntax{ Cat: "UN", Ambit: sentenceAmbit }, Right: subSequence }, ambit }
undent.go
0.649023
0.414543
undent.go
starcoder
package basic import ( "encoding/json" "fmt" ) /* This file contains helper functions for json marshaling. */ type basicGeometry struct { Type string `json:"type"` Coordinates json.RawMessage `json:"coordinates,omitempty"` Geometries []basicGeometry `json:"geometries,omitempty"` } func point(pts []float64) (Point, error) { if len(pts) < 2 { return Point{}, fmt.Errorf("Not enough points for a Point") } return Point{pts[0], pts[1]}, nil } func point3(pts []float64) (Point3, error) { if len(pts) < 3 { return Point3{}, fmt.Errorf("Not enough points for a Point3") } return Point3{pts[0], pts[1], pts[2]}, nil } func pointSlice(pts [][]float64) (mp []Point, err error) { for _, p := range pts { pt, err := point(p) if err != nil { return nil, err } mp = append(mp, pt) } return mp, nil } func unmarshalBasicGeometry(bgeo basicGeometry) (geo Geometry, err error) { switch bgeo.Type { case "Point": var pts []float64 if err = json.Unmarshal(bgeo.Coordinates, &pts); err != nil { return nil, err } return point(pts) case "Point3": var pts []float64 if err = json.Unmarshal(bgeo.Coordinates, &pts); err != nil { return nil, err } return point3(pts) case "MultiPoint": var pts [][]float64 if err = json.Unmarshal(bgeo.Coordinates, &pts); err != nil { return nil, err } mp, err := pointSlice(pts) return MultiPoint(mp), err case "MultiPoint3": var mp MultiPoint3 var pts [][]float64 if err = json.Unmarshal(bgeo.Coordinates, &pts); err != nil { return nil, err } for _, p := range pts { pt, err := point3(p) if err != nil { return nil, err } mp = append(mp, pt) } return mp, nil case "LineString": var pts [][]float64 if err = json.Unmarshal(bgeo.Coordinates, &pts); err != nil { return nil, err } mp, err := pointSlice(pts) return Line(mp), err case "MultiLineString": var ml MultiLine var lines [][][]float64 if err = json.Unmarshal(bgeo.Coordinates, &lines); err != nil { return nil, err } for _, lpts := range lines { mp, err := pointSlice(lpts) if err != nil { return nil, err } ml = append(ml, Line(mp)) } return ml, nil case "Polygon": var p Polygon var lines [][][]float64 if err = json.Unmarshal(bgeo.Coordinates, &lines); err != nil { return nil, err } for _, lpts := range lines { mp, err := pointSlice(lpts) if err != nil { return nil, err } p = append(p, Line(mp)) } return p, nil case "MultiPolygon": var mpoly MultiPolygon var polygons [][][][]float64 if err = json.Unmarshal(bgeo.Coordinates, &polygons); err != nil { return nil, err } for _, lines := range polygons { var p Polygon for _, lpts := range lines { mp, err := pointSlice(lpts) if err != nil { return nil, err } p = append(p, Line(mp)) } mpoly = append(mpoly, p) } return mpoly, nil case "GeometeryCollection": var c Collection for _, basicgeo := range bgeo.Geometries { geo, err := unmarshalBasicGeometry(basicgeo) if err != nil { return nil, err } c = append(c, geo) } return c, nil } return nil, fmt.Errorf("Unknown Type (%v).", bgeo.Type) } func UnmarshalJSON(data []byte) (geo Geometry, err error) { var bgeo basicGeometry if err = json.Unmarshal(data, &bgeo); err != nil { return nil, err } return unmarshalBasicGeometry(bgeo) } /*========================= BASIC TYPES ======================================*/ func jsonTemplate(name, coords string) []byte { return []byte(`{"type":"` + name + `","coordinates":` + coords + `}`) } // MarshalJSON func (p Point) internalMarshalJSON() string { return fmt.Sprintf(`[%v,%v]`, p[0], p[1]) } func (p Point) MarshalJSON() ([]byte, error) { return jsonTemplate("Point", p.internalMarshalJSON()), nil } func (p Point3) internalMarshalJSON() string { return fmt.Sprintf(`[%v,%v,%v]`, p[0], p[1], p[2]) } func (p Point3) MarshalJSON() ([]byte, error) { return jsonTemplate("Point3", p.internalMarshalJSON()), nil } func (p MultiPoint) internalMarshalJSON() string { s := "[" for i, pt := range p { if i != 0 { s += "," } s += pt.internalMarshalJSON() } s += `]` return s } func (p MultiPoint) MarshalJSON() ([]byte, error) { return jsonTemplate("MultiPoint", p.internalMarshalJSON()), nil } func (p MultiPoint3) internalMarshalJSON() string { s := "[" for i, pt := range p { if i != 0 { s += "," } s += pt.internalMarshalJSON() } s += `]` return s } func (p MultiPoint3) MarshalJSON() ([]byte, error) { return jsonTemplate("MultiPoint3", p.internalMarshalJSON()), nil } func (l Line) internalMarshalJSON() string { s := "[" for i, pt := range l { if i != 0 { s += "," } s += pt.internalMarshalJSON() } s += `]` return s } func (l Line) MarshalJSON() ([]byte, error) { return jsonTemplate("LineString", l.internalMarshalJSON()), nil } func (l MultiLine) internalMarshalJSON() string { s := "[" for i, line := range l { if i != 0 { s += "," } s += line.internalMarshalJSON() } s += `]` return s } func (l MultiLine) MarshalJSON() ([]byte, error) { return jsonTemplate("MultiLineString", l.internalMarshalJSON()), nil } func (p Polygon) internalMarshalJSON() string { s := "[" for i, line := range p { if i != 0 { s += "," } s += line.internalMarshalJSON() } s += `]` return s } func (p Polygon) MarshalJSON() ([]byte, error) { return jsonTemplate("Polygon", p.internalMarshalJSON()), nil } func (p MultiPolygon) internalMarshalJSON() string { s := "[" for i, line := range p { if i != 0 { s += "," } s += line.internalMarshalJSON() } s += `]` return s } func (p MultiPolygon) MarshalJSON() ([]byte, error) { return jsonTemplate("MultiPolygon", p.internalMarshalJSON()), nil } func (c Collection) MarshalJSON() ([]byte, error) { js := []byte(`{"type":"GeometryCollection","geometries":[`) for i, g := range c { if i != 0 { js = append(js, ',') } v, ok := g.(json.Marshaler) if !ok { continue } b, e := v.MarshalJSON() if e != nil { return nil, e } js = append(js, b...) } js = append(js, ']', '}') return js, nil }
basic/json_marshal.go
0.567457
0.402862
json_marshal.go
starcoder
package gft import "github.com/infastin/gul/gm32" type ResamplingFilter interface { Kernel(x float32) float32 Support() float32 } type resampFilter struct { kernel func(x float32) float32 support float32 } func (f *resampFilter) Kernel(x float32) float32 { return f.kernel(x) } func (f *resampFilter) Support() float32 { return f.support } func MakeResamplingFilter(kernel func(x float32) float32, support float32) ResamplingFilter { return &resampFilter{ kernel: kernel, support: support, } } var ( NearestNeighborResampling ResamplingFilter = MakeResamplingFilter(nil, 0) BoxResampling ResamplingFilter = MakeResamplingFilter(boxKernel, 0.5) BilinearResampling ResamplingFilter = MakeResamplingFilter(bicubic5Kernel, 1) Bicubic5Resampling ResamplingFilter = MakeResamplingFilter(bicubic5Kernel, 2) Bicubic75Resampling ResamplingFilter = MakeResamplingFilter(bicubic75Kernel, 2) BSplineResampling ResamplingFilter = MakeResamplingFilter(bSplineKernel, 2) MitchellResampling ResamplingFilter = MakeResamplingFilter(mitchellKernel, 2) CatmullRomResampling ResamplingFilter = MakeResamplingFilter(catmullRomKernel, 2) Lanczos3Resampling ResamplingFilter = MakeResamplingFilter(lanczos3Kernel, 3) Lanczos4Resampling ResamplingFilter = MakeResamplingFilter(lanczos4Kernel, 4) Lanczos6Resampling ResamplingFilter = MakeResamplingFilter(lanczos4Kernel, 6) Lanczos12Resampling ResamplingFilter = MakeResamplingFilter(lanczos4Kernel, 12) ) func boxKernel(x float32) float32 { if x < 0 { x = -x } if x < 0.5 { return 1 } return 0 } func bilinearKernel(x float32) float32 { if x < 0 { x = -x } if x < 1 { return 1 - x } return 0 } func bicubic5Kernel(x float32) float32 { abs := gm32.Abs(x) switch { case abs >= 0 && abs <= 1: return 1.5*gm32.Pow(abs, 3) - 2.5*gm32.Pow(abs, 2) + 1 case abs > 1 && abs <= 2: return -0.5*gm32.Pow(abs, 3) + 2.5*gm32.Pow(abs, 2) - 4*abs + 2 default: return 0 } } func bicubic75Kernel(x float32) float32 { abs := gm32.Abs(x) switch { case abs >= 0 && abs <= 1: return 1.25*gm32.Pow(abs, 3) - 2.25*gm32.Pow(abs, 2) + 1 case abs > 1 && abs <= 2: return -0.75*gm32.Pow(abs, 3) + 3.75*gm32.Pow(abs, 2) - 6*abs + 3 default: return 0 } } func bSplineKernel(x float32) float32 { if x < 0 { x = -x } switch { case x < 1: return (0.5 * gm32.Pow(x, 3)) - gm32.Pow(x, 2) + (2.0 / 3.0) case x < 2: x = 2 - x return (1.0 / 6.0) * gm32.Pow(x, 3) default: return 0 } } func lanczos3Kernel(x float32) float32 { if x < 0 { x = -x } if x < 3 { return gm32.Sinc(x) * gm32.Sinc(x/3) } return 0 } func lanczos4Kernel(x float32) float32 { if x < 0 { x = -x } if x < 4 { return gm32.Sinc(x) * gm32.Sinc(x/4) } return 0 } func lanczos6Kernel(x float32) float32 { if x < 0 { x = -x } if x < 6 { return gm32.Sinc(x) * gm32.Sinc(x/6) } return 0 } func lanczos12Kernel(x float32) float32 { if x < 0 { x = -x } if x < 12 { return gm32.Sinc(x) * gm32.Sinc(x/12) } return 0 } func mitchell(x, b, c float32) float32 { if x < 0 { x = -x } switch { case x < 1: return ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6 case x < 2: return ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6 default: return 0 } } func mitchellKernel(x float32) float32 { if x < 0 { x = -x } if x < 2 { return mitchell(x, 1.0/3.0, 1.0/3.0) } return 0 } func catmullRomKernel(x float32) float32 { if x < 0 { x = -x } if x < 2 { return mitchell(x, 0, 0.5) } return 0 }
gft/resampling_filter.go
0.733547
0.550547
resampling_filter.go
starcoder
package resources // The payload for a simple fuse integration based on timer and logger const FuseIntegrationPayload = ` { "name": "test-integration", "tags": [ "timer" ], "flows": [ { "id": "-M30tHvcORdr7SjkRAjn", "name": "", "steps": [ { "id": "-M30tMT1ORdr7SjkRAjn", "configuredProperties": { "period": "60000" }, "metadata": { "configured": "true" }, "action": { "id": "io.syndesis:timer-action", "name": "Simple", "description": "Specify an amount of time and its unit to periodically trigger integration execution. ", "descriptor": { "inputDataShape": { "kind": "none" }, "outputDataShape": { "kind": "none" }, "propertyDefinitionSteps": [ { "name": "Period", "properties": { "period": { "componentProperty": false, "defaultValue": "60000", "deprecated": false, "description": "Period", "displayName": "Period", "javaType": "long", "kind": "parameter", "labelHint": "Delay between each execution of the integration.", "required": true, "secret": false, "type": "duration" } }, "description": "Period" } ], "configuredProperties": { "timerName": "syndesis-timer" }, "componentScheme": "timer" }, "actionType": "connector", "pattern": "From" }, "connection": { "uses": 0, "id": "timer", "name": "Timer", "metadata": { "hide-from-connection-pages": "true" }, "connector": { "id": "timer", "version": 4, "actions": [ { "id": "io.syndesis:timer-action", "name": "Simple", "description": "Specify an amount of time and its unit to periodically trigger integration execution. ", "descriptor": { "inputDataShape": { "kind": "none" }, "outputDataShape": { "kind": "none" }, "propertyDefinitionSteps": [ { "name": "Period", "properties": { "period": { "componentProperty": false, "defaultValue": "60000", "deprecated": false, "description": "Period", "displayName": "Period", "javaType": "long", "kind": "parameter", "labelHint": "Delay between each execution of the integration.", "required": true, "secret": false, "type": "duration" } }, "description": "Period" } ], "configuredProperties": { "timerName": "syndesis-timer" }, "componentScheme": "timer" }, "actionType": "connector", "pattern": "From" }, { "id": "io.syndesis:timer-chron", "name": "Cron", "description": "Specify a cron utility expression for a more complex integration execution schedule.", "descriptor": { "inputDataShape": { "kind": "none" }, "outputDataShape": { "kind": "none" }, "propertyDefinitionSteps": [ { "name": "cron", "properties": { "cron": { "componentProperty": false, "defaultValue": "0 0/1 * * * ?", "deprecated": false, "description": "A cron expression, for example the expression for every minute is 0 0/1 * * * ?", "displayName": "Cron Expression", "javaType": "string", "kind": "parameter", "labelHint": "Delay between scheduling (executing) the integration expressed as a cron expression", "required": true, "secret": false, "type": "string" } }, "description": "Cron" } ], "configuredProperties": { "triggerName": "syndesis-quartz" }, "componentScheme": "quartz2" }, "actionType": "connector", "pattern": "From" } ], "name": "Timer", "dependencies": [ { "type": "MAVEN", "id": "io.syndesis.connector:connector-timer:1.8.6.fuse-750001-redhat-00002" }, { "type": "MAVEN", "id": "org.apache.camel:camel-quartz2:2.21.0.fuse-750033-redhat-00001" } ], "metadata": { "hide-from-connection-pages": "true" }, "description": "Trigger events based on an interval or a quartz expression", "icon": "assets:timer.svg" }, "connectorId": "timer", "icon": "assets:timer.svg", "description": "Trigger integration execution based on an interval or a cron expression", "isDerived": false }, "stepKind": "endpoint" }, { "id": "-M30tNPcORdr7SjkRAjn", "configuredProperties": { "contextLoggingEnabled": "false", "bodyLoggingEnabled": "false" }, "metadata": { "configured": "true" }, "stepKind": "log", "name": "Log" } ], "tags": [ "timer" ], "type": "PRIMARY" } ], "description": "" } `
test/resources/fuse_payload.go
0.657318
0.503174
fuse_payload.go
starcoder
package heap import ( g "github.com/zyedidia/generic" ) // Heap implements a binary heap. type Heap[T any] struct { data []T less func(a, b T) bool } // New returns a new heap with the given less function. func New[T any](less g.LessFn[T]) *Heap[T] { return &Heap[T]{ data: make([]T, 0), less: less, } } // From returns a new heap with the given less function and initial data. func From[T any](less g.LessFn[T], t ...T) *Heap[T] { return FromSlice(less, t) } // FromSlice returns a new heap with the given less function and initial data. // The `data` is not copied and used as the inside array. func FromSlice[T any](less g.LessFn[T], data []T) *Heap[T] { n := len(data) for i := n/2 - 1; i >= 0; i-- { down(data, i, less) } return &Heap[T]{ data: data, less: less, } } // Push pushes the given element onto the heap. func (h *Heap[T]) Push(x T) { h.data = append(h.data, x) up(h.data, len(h.data)-1, h.less) } // Pop removes and returns the minimum element from the heap. If the heap is // empty, it returns zero value and false. func (h *Heap[T]) Pop() (T, bool) { var x T if h.Size() == 0 { return x, false } x = h.data[0] h.data[0] = h.data[len(h.data)-1] h.data = h.data[:len(h.data)-1] down(h.data, 0, h.less) return x, true } // Peek returns the minimum element from the heap without removing it. if the // heap is empty, it returns zero value and false. func (h *Heap[T]) Peek() (T, bool) { if h.Size() == 0 { var x T return x, false } return h.data[0], true } // Size returns the number of elements in the heap. func (h *Heap[T]) Size() int { return len(h.data) } func down[T any](h []T, i int, less g.LessFn[T]) { for { left, right := 2*i+1, 2*i+2 if left >= len(h) || left < 0 { // `left < 0` in case of overflow break } // find the smallest child j := left if right < len(h) && less(h[right], h[left]) { j = right } if !less(h[j], h[i]) { break } h[i], h[j] = h[j], h[i] i = j } } func up[T any](h []T, i int, less g.LessFn[T]) { for { parent := (i - 1) / 2 if i == 0 || !less(h[i], h[parent]) { break } h[i], h[parent] = h[parent], h[i] i = parent } }
heap/heap.go
0.881334
0.598606
heap.go
starcoder
package iterate // KeyValue represents a key value pair. type KeyValue[K comparable, V any] struct { Key K Value V } // Split return the key and the value. func (kv KeyValue[K, V]) Split() (K, V) { return kv.Key, kv.Value } // Zip returns an iterator of key/value pairs produced by the given key/value // iterators. The shorter of the two iterators is used. An error is returned if // any of the two iterators returns an error. func Zip[K comparable, V any](keys Iterator[K], values Iterator[V]) Iterator[KeyValue[K, V]] { return &zipper[K, V]{ keys: keys, values: values, } } type zipper[K comparable, V any] struct { keys Iterator[K] values Iterator[V] stopped bool } // Next implements Iterator[T].Next. func (it *zipper[K, V]) Next() bool { if it.keys.Next() && it.values.Next() { return true } it.stopped = true return false } // Value implements Iterator[T].Value by returning key/value pairs. func (it *zipper[K, V]) Value() KeyValue[K, V] { if it.stopped { return KeyValue[K, V]{} } return KeyValue[K, V]{ Key: it.keys.Value(), Value: it.values.Value(), } } // Err implements Iterator[T].Err by propagating the error from the keys and // values iterators. func (it *zipper[K, V]) Err() error { if err := it.keys.Err(); err != nil { return err } return it.values.Err() } // Unzip returns a key iterator and a value iterator with pairs produced by the // given key/value iterator. func Unzip[K comparable, V any](kvs Iterator[KeyValue[K, V]]) (Iterator[K], Iterator[V]) { u := unzipper[K, V]{ kvs: kvs, } return u.iterators() } type unzipper[K comparable, V any] struct { kvs Iterator[KeyValue[K, V]] keys []K values []V } func (u *unzipper[K, V]) iterators() (Iterator[K], Iterator[V]) { return &keyIterator[K, V]{ u: u, }, &valueIterator[K, V]{ u: u, } } type keyIterator[K comparable, V any] struct { u *unzipper[K, V] key K } // Next implements Iterator[T].Next. func (it *keyIterator[K, V]) Next() bool { // TODO(frankban): make this thread safe. if len(it.u.keys) != 0 { it.key, it.u.keys = it.u.keys[0], it.u.keys[1:] return true } if it.u.kvs.Next() { kv := it.u.kvs.Value() it.key = kv.Key it.u.values = append(it.u.values, kv.Value) return true } it.key = *new(K) return false } // Value implements Iterator[T].Value by returning keys from the key/value // iterator stored in the unzipper. func (it *keyIterator[K, V]) Value() K { return it.key } // Err implements Iterator[T].Err by propagating the error from the key/value // source iterator. func (it *keyIterator[K, V]) Err() error { return it.u.kvs.Err() } type valueIterator[K comparable, V any] struct { u *unzipper[K, V] value V } // Next implements Iterator[T].Next. func (it *valueIterator[K, V]) Next() bool { // TODO(frankban): make this thread safe. if len(it.u.values) != 0 { it.value, it.u.values = it.u.values[0], it.u.values[1:] return true } if it.u.kvs.Next() { kv := it.u.kvs.Value() it.value = kv.Value it.u.keys = append(it.u.keys, kv.Key) return true } it.value = *new(V) return false } // Value implements Iterator[T].Value by returning values from the key/value // iterator stored in the unzipper. func (it *valueIterator[K, V]) Value() V { return it.value } // Err implements Iterator[T].Err by propagating the error from the key/value // source iterator. func (it *valueIterator[K, V]) Err() error { return it.u.kvs.Err() } // ToMap returns a map with the values produced by the given key/value iterator. // An error is returned if the iterator returns an error, in which case the // returned map includes the key/value pairs already consumed. func ToMap[K comparable, V any](it Iterator[KeyValue[K, V]]) (map[K]V, error) { m := make(map[K]V) for it.Next() { kv := it.Value() m[kv.Key] = kv.Value } return m, it.Err() }
keyvalue.go
0.76986
0.449574
keyvalue.go
starcoder
package fb // You must have flatc installed to regenerate these files. Get it here: // https://google.github.io/flatbuffers/ //go:generate flatc --go -o ../../../../.. state.fbs /* The curator stores metadata in BoltDB, encoded with FlatBuffers. Why FlatBuffers? They encode somewhat larger than another obvious choice, Protocol Buffers (30% in informal testing), but they have the large advantage that decoding doesn't require allocating any memory. For reading, this works very nicely with BoltDB, which returns pointers directly into an mmaped database file: reads are essentially "zero-copy" and even don't need to parse fields that aren't being read. Since a lot of the curator's work involves concurrent read-only scans through the database, this saves a lot of allocation and GC work. Besides the larger encoding, another downside is that the API is somewhat clunky: FlatBuffers' Go support doesn't yet include an "object" API or easy-to-use builders, so we have to write some additional code to make things usable. For now, we'll adopt these conventions: - Each FlatBuffer type should have a corresponding plain Go struct (in structs.go). The Go struct is named as usual, and the FlatBuffer type is named with an "F" suffix. - Each type has a ToStruct method (in unbuilders.go) that returns a new struct type from the FlatBuffer type. - Each root type (i.e. type that is the root of an encoded buffer), there's a Build___ function (in builders.go) that takes the struct and returns an encoded FlatBuffer as a []byte. Hopefully, eventually the FlatBuffers compiler will be able to generate most of that code from the schema. For now, if you add a new type, you'll have to write a struct and builders and unbuilders manually. When working with curator database code, keep these guildelines in mind: - When possible, work with the FlatBuffers objects directly and don't call ToStruct. This maximizes the benefit of the direct access model. In general, anything that's just reading should use the FlatBuffers objects. - Similarly, try to provide a stack-allocated value to struct/table accessors to prevent unnecessary allocation. - When creating new values, create them as a struct and call the Build function. - When modifiying existing values, if the change is "trivial" (i.e. it's changing a field that is definitely already present to another value), you can use the "fast path": call CloneBuffer on the root object, use the FlatBuffers mutators, then write the cloned and modified buffer back to the database. - If the change isn't trivial (i.e. it can add or removes fields, or changes the length of a vector), use the "slow path": call ToStruct, change the struct accordingly, then call Build and write it to the database. - If performance requires it, you could try the fast path and fall back to the slow path if the fields to be modified aren't present. Consider whether the additional code complexity is worth it though. To keep the size of common values down, we use a few tricks: - We store TractIDs as five 2-byte values in a "struct". - We pack three 20-bit TractserverID values in a 64 bit field in TractF. - We pack several small fields into one 32-bit value in BlobF. - We store times at one second precision instead of nanosecond. The code to encapsulate these tricks is in extras.go. */
internal/curator/durable/state/fb/doc.go
0.631594
0.553988
doc.go
starcoder
package guitar var Larrivee = Levels{ Gradient: []float32{10, 20, 25, 35, 42, 55, 70, 85, 90, 100}, Risk: []Danger{Extreme, Severe, High, Elevated, Moderate, Low, Moderate, Elevated, High, Severe}, Details: &Notification{ SubjectTmpl: `Your guitar is in {{.Risk}} danger!`, BodyTmpl: `Your guitar is not in the correct humidity range (42–55%). You should make changes to the environment of the guitar to maintain this range. Currently, the environment is in the range of {{.Low}}–{{.High}} relative humidity. This humidity range is categorized as: {{.Risk}} If the guitar remains in this humidity range, you can expect the following effects: ## 1–3 Days {{.ShorttermEffects}} ## 3+ Days {{.LongtermEffects}} This information is made available by Larrivee. See http://www.larivee.com/pdfs/Larrivee%20Care%20%20Maintenance.pdf for more information. ## Humidity Trend You can use the following humidity trend chart to diagnose the problem. {{.Trend}} Greetings, <NAME> `, ShortEffects: []string{ `Frets will feel sharp, top and back will become collapsed (concave), Action will lower very quickly, and guitar will develop a buzz. Soundboard may develop cracks especially running from the bridge to the butt, bridge may shear off.`, `Frets will likely feel sharp, top and back will likely become collapsed (concave), Action will lower very quickly, guitar will likely develop a buzz. Soundboard may develop a crack running from the bridge to the butt, bridge may come unglued.`, `Frets will feel sharp, top may begin to collapse (concave), Action will lower very quickly, guitar may develop a buzz.`, `Fret ends may start to feel sharp, top may become slightly collapsed (concave).`, `No major problems should occur with limited exposure.`, `No problem will occur in this range.`, `No major problems should occur with limited exposure.`, `Sound quality may be diminished. Soundboard may appear swollen. Action may be slightly high.`, `Guitar body may appear swollen, sound quality will slightly diminish, playability may decrease. Action will become higher.`, `Guitar body will appear swollen and sound quality will be diminished, playability will decrease. Back braces may come unglued as the wood expands. Action will get very high quickly.`, }, LongEffects: []string{ `Fret Ends will feel very sharp, Soundboard and back will become collapsed (concave), last six frets of the fingerboard will sink into sound hole, the action will be extremely low with buzzes up and down the fingerboard, the Bridge wings will appear concave, cracks will develop in the soundboard especially from the bridge to the butt of the instrument, and the bridge will shear off. Rosette rings and tail wedge will appear raised. Braces which do not shear off may push out the binding of the instrument Braces will be visible as high spots on the top and back.`, `Fret Ends will feel very sharp, Soundboard and back will be collapsed (concave), last six frets of the fingerboard will sink into sound hole, action will be lower, and guitar will buzz, Bridge wings will appear concave, a large crack in the soundboard will likely develop from the bridge to the butt of the instrument, and the bridge may come unglued. Rosette rings and tail wedge may be visibly raised.`, `Fret Ends will likely feel very sharp, Soundboard and back will become flat or collapsed (concave), last six frets of the fingerboard will likely sink into sound hole, the action will lower, and guitar will buzz, the Bridge wings will appear concave, cracks in the soundboard may develop especially from the bridge to the butt of the instrument, the bridge may shear off (come unglued).`, `Fret Ends will feel sharp, Soundboard and back will become flat or collapsed (concave), action will feel lower, guitar will likely buzz, Bridge wings will appear concave, after several months the bridge may “lift” or shear off.`, `Fret ends may feel sharp, soundboard may appear slightly collapsed (concave), action may lower slightly, bridge wings will appear concave, the guitar may develop a buzz.`, `No problem will occur in this range.`, `Top and back will appear bellied (convex), playability will be affected. Fretboard from the 14th on may appear raised. Guitar will start to have a musty smell after a couple of months.`, `Top and back will appear bellied (convex), playability will be affected. Fretboard from the 14th on may appear raised. Guitar will start to have a musty smell after a couple of months.`, `Braces will come loose after a few weeks, top and back will appear very bellied (convex), bridge may loosen or come off, playability will be affected. Fretboard from the 14th on will appear raised. Mildew may form inside the guitar.`, `All Glue Joints will loosen, Top and Back braces will loosen. Bridge may shear come off the top, the guitar top will expand and belly (become convex) both in front of and behind bridge, if the glue joints do not delaminate then the guitar will be unplayable. Fretboard from the 14th on will appear raised. Mildew may form inside the guitar. Guitar will very likely de-construct itself.`, }, }, }
guitar/larrivee.go
0.694821
0.563258
larrivee.go
starcoder
package comb import ( "fmt" "strings" ) // Char creates a parser parsing a character. func (s *State) Char(r rune) Parser { return func() (interface{}, error) { if s.currentRune() != r { return nil, fmt.Errorf("invalid character, '%c'", s.currentRune()) } s.increment() return r, nil } } // NotChar creates a parser parsing a character which is not one of an argument. func (s *State) NotChar(r rune) Parser { return s.NotChars(string(r)) } // String creates a parser parsing a string. func (s *State) String(str string) Parser { rs := []rune(str) ps := make([]Parser, 0, len(rs)) for _, r := range rs { ps = append(ps, s.Char(r)) } return s.Stringify(s.And(ps...)) } // Chars creates a parser parsing a character in a given string. func (s *State) Chars(cs string) Parser { rs := stringToRuneSet(cs) return func() (interface{}, error) { if _, ok := rs[s.currentRune()]; ok { defer s.increment() return s.currentRune(), nil } return nil, fmt.Errorf("invalid character, '%c'", s.currentRune()) } } // NotChars creates a parser parsing a character not in a given string. func (s *State) NotChars(str string) Parser { rs := stringToRuneSet(str) return func() (interface{}, error) { if _, ok := rs[s.currentRune()]; !ok { defer s.increment() return s.currentRune(), nil } return nil, fmt.Errorf("invalid character, '%c'", s.currentRune()) } } // Wrap wraps a parser with parsers which parse something on the leftside and // rightside of it and creates a new parser. Its parsing result will be m's. func (s *State) Wrap(l, m, r Parser) Parser { return second(s.And(l, m, r)) } // Prefix creates a parser with a prefix parser and content parser and returns // the latter's result. func (s *State) Prefix(pre, p Parser) Parser { return second(s.And(pre, p)) } func second(p Parser) Parser { return func() (interface{}, error) { results, err := p() if results, ok := results.([]interface{}); ok { return results[1], err } return nil, err } } // Many creates a parser of more than or equal to 0 reptation of a given parser. func (s *State) Many(p Parser) Parser { return func() (interface{}, error) { results, err := s.Many1(p)() if err != nil { return []interface{}{}, nil } return results, nil } } // Many1 creates a parser of more than 0 reptation of a given parser. func (s *State) Many1(p Parser) Parser { return func() (interface{}, error) { var results []interface{} for i := 0; ; i++ { old := *s result, err := p() if err != nil { *s = old if i == 0 { return nil, err } break } results = append(results, result) } return results, nil } } // Or creates a selectional parser from given parsers. func (s *State) Or(ps ...Parser) Parser { return func() (interface{}, error) { var err error old := *s for _, p := range ps { var result interface{} result, err = p() if err == nil { return result, nil } *s = old } return nil, err } } // And creates a parser combining given parsers sequentially. func (s *State) And(ps ...Parser) Parser { return func() (interface{}, error) { results := make([]interface{}, 0, len(ps)) old := *s for _, p := range ps { result, err := p() if err != nil { *s = old return nil, err } results = append(results, result) } return results, nil } } // Lazy evaluates and runs a given parser constructor. This is useful to define // recursive parsers. func (s *State) Lazy(f func() Parser) Parser { p := Parser(nil) return func() (interface{}, error) { if p == nil { p = f() } return p() } } // Void creates a parser whose result is always nil from a given parser. func (State) Void(p Parser) Parser { return func() (interface{}, error) { _, err := p() return nil, err } } // Exhaust creates a parser which fails when a source string is not exhausted // after running a given parser. func (s *State) Exhaust(p Parser, f func(State) error) Parser { return func() (interface{}, error) { result, err := p() if err != nil { return nil, err } else if !s.exhausted() { return nil, f(*s) } return result, err } } // App applies a function to results of a given parser. func (s *State) App(f func(interface{}) interface{}, p Parser) Parser { return func() (interface{}, error) { result, err := p() if err == nil { return f(result), err } return result, err } } func stringToRuneSet(s string) map[rune]bool { rs := make(map[rune]bool) for _, r := range s { rs[r] = true } return rs } // None creates a parser which parses nothing and succeeds always. func (s *State) None() Parser { return func() (interface{}, error) { return nil, nil } } // Maybe creates a parser which runs a given parser or parses nothing when it // fails. func (s *State) Maybe(p Parser) Parser { return s.Or(p, s.None()) } // Stringify creates a parser which returns a string converted from a result of // a given parser. The result of a given parser must be a rune, a string or a // sequence of them in []interface{}. func (s *State) Stringify(p Parser) Parser { return s.App(func(x interface{}) interface{} { return stringify(x) }, p) } func stringify(x interface{}) string { switch x := x.(type) { case string: return x case rune: return string(x) case []interface{}: ss := make([]string, 0, len(x)) for _, s := range x { ss = append(ss, stringify(s)) } return strings.Join(ss, "") } panic("unreachable") }
src/lib/parse/comb/combinator.go
0.793666
0.412116
combinator.go
starcoder
package imageutil import ( "fmt" "image" "image/color" "github.com/grokify/simplego/reflect/reflectutil" "golang.org/x/image/draw" ) func ImageToRGBA(img image.Image) *image.RGBA { // https://stackoverflow.com/questions/31463756/convert-image-image-to-image-nrgba switch img := img.(type) { case *image.NRGBA: return NRGBAtoRGBA(img) case *image.Paletted: return ImageWithSetToRGBA(img) case *image.RGBA: return img case *image.YCbCr: return YCbCrToRGBA(img) } panic(fmt.Sprintf("Format not supported [%v].", reflectutil.TypeName(img))) } type ImageWithSet interface { // ColorModel returns the Image's color model. ColorModel() color.Model // Bounds returns the domain for which At can return non-zero color. // The bounds do not necessarily contain the point (0, 0). Bounds() image.Rectangle // At returns the color of the pixel at (x, y). // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid. // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one. At(x, y int) color.Color Set(x, y int, c color.Color) } func NRGBAtoRGBA(imgNRGBA *image.NRGBA) *image.RGBA { rect := imgNRGBA.Bounds() imgRGBA := image.NewRGBA(rect) for x := rect.Min.X; x <= rect.Max.X; x++ { for y := rect.Min.Y; y <= rect.Max.Y; y++ { imgRGBA.Set(x, y, imgNRGBA.At(x, y)) } } return imgRGBA } func ImageWithSetToRGBA(src ImageWithSet) *image.RGBA { rect := src.Bounds() imgRGBA := image.NewRGBA(rect) for x := rect.Min.X; x <= rect.Max.X; x++ { for y := rect.Min.Y; y <= rect.Max.Y; y++ { imgRGBA.Set(x, y, src.At(x, y)) } } return imgRGBA } func ImageAnyToRGBA(src image.Image) *image.RGBA { // https://stackoverflow.com/questions/31463756/convert-image-image-to-image-nrgba b := src.Bounds() img := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) draw.Draw(img, img.Bounds(), src, b.Min, draw.Src) return img } func YCbCrToRGBA(src *image.YCbCr) *image.RGBA { // https://stackoverflow.com/questions/31463756/convert-image-image-to-image-nrgba b := src.Bounds() img := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) draw.Draw(img, img.Bounds(), src, b.Min, draw.Src) return img }
image/imageutil/convert.go
0.84759
0.529628
convert.go
starcoder
package polygon import ( "math" "strings" "github.com/adamcolton/geom/d2" "github.com/adamcolton/geom/d2/curve/line" ) // Polygon represents a Convex Polygon type Polygon []d2.Pt // Pt2c1 returns line.Segments as d2.Pt1 that adheres to the Shape rules func (p Polygon) Pt2c1(t0 float64) d2.Pt1 { n := (len(p) - 1) h := n - (n / 2) // half rounded up as := line.Segments(p[0:h]) bs := line.Segments(p[h:]) a := as.Pt1(t0) b := bs.Pt1(1 - t0) return line.New(a, b) } // Pt2 returns a point in the polygon and adheres to the Shape rules. func (p Polygon) Pt2(t0, t1 float64) d2.Pt { return p.Pt2c1(t0).Pt1(t1) } // Pt1 returns a point on the perimeter. func (p Polygon) Pt1(t0 float64) d2.Pt { ln := len(p) t0 -= math.Floor(t0) // [0,1) t0 *= float64(ln) idx := int(t0) t0 -= float64(idx) return line.New(p[idx], p[(idx+1)%ln]).Pt1(t0) } // String lists the points as a string. func (p Polygon) String() string { pts := make([]string, len(p)) for i, pt := range p { pts[i] = pt.String() } return strings.Join([]string{"Polygon{ ", strings.Join(pts, ", "), " }"}, "") } // SignedArea returns the Area and may be negative depending on the polarity. func (p Polygon) SignedArea() float64 { var s float64 prev := d2.V(p[len(p)-1]) for _, cur := range p { v := d2.V(cur) s += prev.Cross(v) prev = v } return s / 2 } // Area of the polygon func (p Polygon) Area() float64 { return math.Abs(p.SignedArea()) } // Centroid returns the center of mass of the polygon func (p Polygon) Centroid() d2.Pt { var x, y, a float64 prev := p[len(p)-1] for _, cur := range p { t := (prev.X*cur.Y - cur.X*prev.Y) x += (prev.X + cur.X) * t y += (prev.Y + cur.Y) * t a += t prev = cur } a = 1 / (3 * a) return d2.Pt{x * a, y * a} } // Contains returns true of the point f is inside of the polygon func (p Polygon) Contains(pt d2.Pt) bool { // http://geomalgorithms.com/a03-_inclusion.html wn := 0 prev := p[len(p)-1] for _, cur := range p { c := line.New(prev, cur).Cross(pt) if prev.Y <= pt.Y { if c > 0 && cur.Y > pt.Y { wn++ } } else if c < 0 && cur.Y <= pt.Y { wn-- } prev = cur } return wn != 0 } // Perimeter returngs the total length of the perimeter func (p Polygon) Perimeter() float64 { var sum float64 prev := p[0] for _, f := range p[1:] { sum += prev.Distance(f) prev = f } sum += prev.Distance(p[0]) return sum } // CountAngles returns the number of counter clockwise and clockwise angles. If // ccwOut or cwOut is not nil, they will be populated with the indexes of the // verticies func (p Polygon) CountAngles(out []int) (ccw int, cw int) { if out != nil && len(out) != len(p) { out = nil } prevF := p[len(p)-1] prevAngle := p[len(p)-2].Subtract(prevF).Angle() for idx, f := range p { curAngle := prevF.Subtract(f).Angle() a := curAngle - prevAngle if a < 0 { a += 2 * math.Pi } if a > math.Pi { if out != nil { out[len(out)-cw-1] = idx } cw++ } else if a < math.Pi { if out != nil { out[ccw] = idx } ccw++ } prevAngle, prevF = curAngle, f } return } // Convex returns True if the polygon contains a convex angle. func (p Polygon) Convex() bool { ccw, cw := p.CountAngles(nil) return ccw == 0 || cw == 0 } const small = 1e-5 // FindTriangles returns the index sets of the polygon broken up into triangles. // Given a unit square it would return [[0,1,2], [0,2,3]] which means that // the square can be broken up in to 2 triangles formed by the points at those // indexes. func (p Polygon) FindTriangles() [][3]uint32 { // This is the ear clipping, there are better algorithms out := make([][3]uint32, 0, len(p)-2) ll := NewLL(p) left := len(p) n0 := &(ll.Nodes[0]) n1 := &(ll.Nodes[1]) n2 := &(ll.Nodes[2]) cur := make(Polygon, len(p)) copy(cur, p) ctr := 0 for ctr < len(p) { ctr++ n0, n1, n2 = n1, n2, &(ll.Nodes[n2.NextIdx]) ll.Start = n0.NextIdx if left == 3 { out = append(out, [3]uint32{n0.PIdx, n1.PIdx, n2.PIdx}) break } ln := line.New(ll.Pts[n0.PIdx], ll.Pts[n2.PIdx]) if !ll.Contains(ln.Pt1(0.5)) || ll.DoesIntersect(ln) { continue } ctr = 0 left-- out = append(out, [3]uint32{n0.PIdx, n1.PIdx, n2.PIdx}) n0.NextIdx = n1.NextIdx n1, n2 = n2, &(ll.Nodes[n2.NextIdx]) } return out } // Collision returns the first side that is intersected by the given // lineSegment, returning the parametic t for the lineSegment, the index of the // side and the parametric t of the side func (p Polygon) Collision(lineSegment line.Line) (lineT float64, idx int, sideT float64) { idx = -1 ln := len(p) for i, f := range p { side := line.New(f, p[(i+1)%ln]) t0, t1, ok := side.Intersection(lineSegment) if ok && t0 >= 0 && t0 < 1 && t1 >= 0 && t1 < 1 && (idx == -1 || lineT > t0) { lineT = t0 idx = i sideT = t1 } } return } // LineIntersections fulfills line.LineIntersector func (p Polygon) LineIntersections(ln line.Line, buf []float64) []float64 { max := len(buf) buf = buf[:0] prev := p[len(p)-1] for _, cur := range p { side := line.New(prev, cur) t0, t1, ok := ln.Intersection(side) if ok && t0 >= 0 && t0 < 1 { buf = append(buf, t1) if max > 0 && len(buf) == max { return buf } } prev = cur } return buf } // Sides converts the perimeter of the polygon to a slice of lines. func (p Polygon) Sides() []line.Line { side := make([]line.Line, len(p)) prev := p[len(p)-1] for i, f := range p { side[i] = line.New(prev, f) prev = f } return side } // NonIntersecting returns false if any two sides intersect. This requires // O(N^2) time to check. func (p Polygon) NonIntersecting() bool { side := p.Sides() // Each side needs to be check against each non-adjacent side with a greater // index. for i, si := range side[:len(side)-2] { for _, sj := range side[i+2:] { t0, t1, ok := si.Intersection(sj) if ok && t0 > 0 && t0 < 1 && t1 > 0 && t1 < 1 { return false } } } return true } // Reverse the order of the points defining the polygon func (p Polygon) Reverse() Polygon { out := make([]d2.Pt, len(p)) l := len(p) - 1 m := (len(p) + 1) / 2 //+1 causes round up for i := 0; i < m; i++ { out[i], out[l-i] = p[l-i], p[i] } return out } // BoundingBox fulfills BoundingBoxer returning a box that contains the polygon. func (p Polygon) BoundingBox() (min, max d2.Pt) { return d2.MinMax(p...) }
d2/shape/polygon/polygon.go
0.843975
0.58883
polygon.go
starcoder
package triangle import ( "math" "strings" "github.com/adamcolton/geom/d2" "github.com/adamcolton/geom/d2/curve/line" ) // Triangle is a 2D triangle type Triangle [3]d2.Pt // Contains checks if a point is inside the triangle. func (t *Triangle) Contains(pt d2.Pt) bool { // If a point is inside the triangle, the sign of the cross product from the // point to each vertex will be the same. But a cross product of exactly 0 // doesn't have a sign. s1 := t[0].Subtract(t[1]) r1 := pt.Subtract(t[1]) s2 := t[1].Subtract(t[2]) r2 := pt.Subtract(t[2]) c1 := s1.Cross(r1) c2 := s2.Cross(r2) if !(c1 >= 0 && c2 >= 0) && !(c1 <= 0 && c2 <= 0) { return false } s3 := t[2].Subtract(t[0]) r3 := pt.Subtract(t[0]) c3 := s3.Cross(r3) return (c2 >= 0 && c3 >= 0) || (c2 <= 0 && c3 <= 0) } // SignedArea of the triangle func (t *Triangle) SignedArea() float64 { v1 := t[0].Subtract(t[1]) v2 := t[0].Subtract(t[2]) return 0.5 * v1.Cross(v2) } // Area of the triangle func (t *Triangle) Area() float64 { return math.Abs(t.SignedArea()) } // Perimeter of the triangle func (t *Triangle) Perimeter() float64 { return t[0].Distance(t[1]) + t[1].Distance(t[2]) + t[2].Distance(t[0]) } // Centroid returns the center of mass of the triangle func (t *Triangle) Centroid() d2.Pt { return d2.Pt{ X: (t[0].X + t[1].X + t[2].X) / 3.0, Y: (t[0].Y + t[1].Y + t[2].Y) / 3.0, } } // String fulfills Stringer func (t *Triangle) String() string { return strings.Join([]string{ "Triangle[ ", t[0].String(), ",", t[1].String(), ",", t[2].String(), " ]", }, "") } // Pt1c0 converts the triangle to line.Segments func (t *Triangle) Pt1c0() d2.Pt1 { return line.Segments(append(t[:], t[0])) } // Pt1 returns a point along the perimeter is t0 is between 0 and 1. func (t *Triangle) Pt1(t0 float64) d2.Pt { return t.Pt1c0().Pt1(t0) } // Pt2c1 finds the fill line for t0. func (t *Triangle) Pt2c1(t0 float64) d2.Pt1 { m := line.New(t[0], t[1]).Pt1(0.5) p0 := line.New(t[0], m).Pt1(t0) p1 := line.New(t[2], t[1]).Pt1(t0) return line.New(p0, p1) } // Pt2 finds a point inside the triange if t0 and t1 are both between 0 and 1 // inclusive. Conforms to shape filling rules. func (t *Triangle) Pt2(t0, t1 float64) d2.Pt { return t.Pt2c1(t0).Pt1(t1) } // L fulfills Limiter and describes the parametric methods on the triangle. func (t *Triangle) L(ts, c int) d2.Limit { if (ts == 1 && c == 1) || (ts == 2 && c == 2) || (ts == 1 && c == 0) || (ts == 2 && c == 1) { return d2.LimitBounded } return d2.LimitUndefined } // LineIntersections find the intersections of the given line with the triangle // relative to the line func (t *Triangle) LineIntersections(l line.Line, buf []float64) []float64 { max := len(buf) buf = buf[:0] prev := t[2] for _, cur := range t { l2 := line.New(prev, cur) prev = cur tt, t0, ok := l.Intersection(l2) if tt >= 0 && tt < 1 && ok { buf = append(buf, t0) if max > 0 && len(buf) == max { return buf } } } return buf } // BoundingBox returns a bounding box that contains the triangle func (t *Triangle) BoundingBox() (d2.Pt, d2.Pt) { return d2.MinMax(t[:]...) } // CircumCenter find the point where the bisectors of the sides intersect. func (t *Triangle) CircumCenter() d2.Pt { l01 := line.Bisect(t[0], t[1]) l02 := line.Bisect(t[0], t[2]) t0, _, ok := l01.Intersection(l02) if ok { return l02.Pt1(t0) } if t[0] == t[1] || t[1] == t[2] { return line.New(t[0], t[2]).Pt1(0.5) } return line.New(t[0], t[1]).Pt1(0.5) }
d2/shape/triangle/triangle.go
0.837952
0.694474
triangle.go
starcoder
package math import "math" type Box3 struct { Min *Vector3 Max *Vector3 } func NewBox3() *Box3 { b := &Box3{ Min:&Vector3{ X:math.Inf(0), Y:math.Inf(0), Z:math.Inf(0)}, Max:&Vector3{ X:math.Inf(-1), Y:math.Inf(-1), Z:math.Inf(-1)}, } return b } func (b *Box3) Set( min, max *Vector3 ) *Box3 { b.Min.Copy( min ) b.Max.Copy( max ) return b } func (b *Box3) SetFromArray( array []float64 ) { minX := math.Inf(0) minY := math.Inf(0) minZ := math.Inf(0) maxX := math.Inf(-1) maxY := math.Inf(-1) maxZ := math.Inf(-1) for i := 0 ; i < len(array); i += 3 { x := array[ i ] y := array[ i + 1 ] z := array[ i + 2 ] if x < minX { minX = x } if y < minY { minY = y } if z < minZ { minZ = z } if x > maxX { maxX = x } if y > maxY { maxY = y } if z > maxZ { maxZ = z } } b.Min.Set( minX, minY, minZ ) b.Max.Set( maxX, maxY, maxZ ) } func (b *Box3) SetFromPoints( points []Vector3 ) *Box3 { b.MakeEmpty() for i := 0 ; i < len(points); i++ { b.ExpandByPoint( &points[i] ) } return b } func (b *Box3) SetFromCenterAndSize( center, size *Vector3 ) *Box3 { v1 := &Vector3{} halfSize := v1.Copy( size ).MultiplyScalar( 0.5 ) b.Min.Copy( center ).Sub( halfSize ) b.Max.Copy( center ).Add( halfSize ) return b } func (b *Box3) SetFromObject( ) { // TODO After core/Object3D } func (b *Box3) Clone() *Box3 { b1 := &Box3{} b1.Set( b.Min, b.Max ) return b1 } func (b *Box3) Copy( box *Box3 ) *Box3 { b.Min.Copy( box.Min ) b.Max.Copy( box.Max ) return b } func (b *Box3) MakeEmpty() *Box3 { b.Min.X = math.Inf(0) b.Min.Y = math.Inf(0) b.Min.Z = math.Inf(0) b.Max.X = math.Inf(-1) b.Max.Y = math.Inf(-1) b.Max.Z = math.Inf(-1) return b } func (b *Box3) IsEmpty() bool { return ( b.Max.X < b.Min.X ) || ( b.Max.Y < b.Min.Y ) || ( b.Max.Z < b.Min.Z ) } func (b *Box3) Center() *Vector3 { result := &Vector3{} return b.CenterTarget(result) } func (b *Box3) CenterTarget( optionalTarget *Vector3 ) *Vector3 { return optionalTarget.AddVectors( b.Min, b.Max ).MultiplyScalar( 0.5 ) } func (b *Box3) Size() *Vector3 { result := &Vector3{} return b.SizeTarget(result) } func (b *Box3) SizeTarget( optionalTarget *Vector3 ) *Vector3 { return optionalTarget.SubVectors( b.Max, b.Min ) } func (b *Box3) ExpandByPoint( point *Vector3 ) *Box3 { b.Min.Min( point ) b.Max.Max( point ) return b } func (b *Box3) ExpandByVector( vector *Vector3 ) *Box3 { b.Min.Sub( vector ) b.Max.Add( vector ) return b } func (b *Box3) ExpandByScalar( scalar float64 ) *Box3 { b.Min.AddScalar( -scalar ) b.Max.AddScalar( scalar ) return b } func (b *Box3) ContainsPoint( point Vector3 ) bool { if point.X < b.Min.X || point.X > b.Max.X || point.Y < b.Min.Y || point.Y > b.Max.Y || point.Z < b.Min.Z || point.Z > b.Max.Z { return false } return true } func (b *Box3) ContainsBox( box *Box3 ) bool { if ( b.Min.X <= box.Min.X ) && ( box.Max.X <= b.Max.X ) && ( b.Min.Y <= box.Min.Y ) && ( box.Max.Y <= b.Max.Y ) && ( b.Min.Z <= box.Min.Z ) && ( box.Max.Z <= b.Max.Z ) { return true } return false } func (b *Box3) GetParamaeter( point *Vector3 ) *Vector3 { result := &Vector3{} return b.GetParamaeterTarget( point, result ) } func (b *Box3) GetParamaeterTarget( point *Vector3, optionalTarget *Vector3 ) *Vector3 { return optionalTarget.Set( ( point.X - b.Min.X ) / ( b.Max.X - b.Min.X ), ( point.Y - b.Min.Y ) / ( b.Max.Y - b.Min.Y ), ( point.Z - b.Min.Z ) / ( b.Max.Z - b.Min.Z ), ) } func (b *Box3) IntersectsBox( box *Box3 ) bool { if box.Max.X < b.Min.X || box.Min.X > b.Max.X || box.Max.Y < b.Min.Y || box.Min.Y > b.Max.Y || box.Max.Z < b.Min.Z || box.Min.Z > b.Max.Z { return false } return true } func (b *Box3) IntersectsSphere() { // TODO After Sphere } func (b *Box3) IntersectsPlane() { // TODO After Plane } func (b *Box3) ClampPoint( point *Vector3 ) *Vector3 { result := &Vector3{} return b.ClampPointTarget( point, result ) } func (b *Box3) ClampPointTarget( point, optionalTarget *Vector3 ) *Vector3 { return optionalTarget.Copy( point ).Clamp( b.Min, b.Max ) } func (b *Box3) DistanceToPoint( point *Vector3 ) float64 { v1 := &Vector3{} clampedPoint := v1.Copy( point ).Clamp( b.Min, b.Max ) return clampedPoint.Sub( point ).Length() } func (b *Box3) GetBoundingSphere() { // TODO After Sphere } func (b *Box3) Intersect( box *Box3 ) *Box3 { b.Min.Max( box.Min ) b.Max.Min( box.Max ) if b.IsEmpty() { b.MakeEmpty() } return b } func (b *Box3) Union( box *Box3 ) *Box3 { b.Min.Min( box.Min ) b.Max.Max( box.Max ) return b } func (b *Box3) ApplyMatrix4() { // TODO After Matrix4 } func (b *Box3) Translate( offset *Vector3 ) *Box3 { b.Min.Add( offset ) b.Max.Add( offset ) return b } func (b *Box3) Equals( box Box3 ) bool { return box.Min.Equals( b.Min ) && box.Max.Equals( b.Max ) }
math/box3.go
0.519278
0.568715
box3.go
starcoder
package statsd import ( "errors" "fmt" "math/rand" "net" ) type Statter interface { Inc(stat string, value int64, rate float32) error Dec(stat string, value int64, rate float32) error Gauge(stat string, value int64, rate float32) error GaugeDelta(stat string, value int64, rate float32) error Timing(stat string, delta int64, rate float32) error Raw(stat string, value string, rate float32) error SetPrefix(prefix string) Close() error } type Client struct { // underlying connection c net.PacketConn // resolved udp address ra *net.UDPAddr // prefix for statsd name prefix string } // Close closes the connection and cleans up. func (s *Client) Close() error { err := s.c.Close() return err } // Increments a statsd count type. // stat is a string name for the metric. // value is the integer value // rate is the sample rate (0.0 to 1.0) func (s *Client) Inc(stat string, value int64, rate float32) error { dap := fmt.Sprintf("%d|c", value) return s.Raw(stat, dap, rate) } // Decrements a statsd count type. // stat is a string name for the metric. // value is the integer value. // rate is the sample rate (0.0 to 1.0). func (s *Client) Dec(stat string, value int64, rate float32) error { return s.Inc(stat, -value, rate) } // Submits/Updates a statsd gauge type. // stat is a string name for the metric. // value is the integer value. // rate is the sample rate (0.0 to 1.0). func (s *Client) Gauge(stat string, value int64, rate float32) error { dap := fmt.Sprintf("%d|g", value) return s.Raw(stat, dap, rate) } // Submits a delta to a statsd gauge. // stat is the string name for the metric. // value is the (positive or negative) change. // rate is the sample rate (0.0 to 1.0). func (s *Client) GaugeDelta(stat string, value int64, rate float32) error { dap := fmt.Sprintf("%+d|g", value) return s.Raw(stat, dap, rate) } // Submits a statsd timing type. // stat is a string name for the metric. // value is the integer value. // rate is the sample rate (0.0 to 1.0). func (s *Client) Timing(stat string, delta int64, rate float32) error { dap := fmt.Sprintf("%d|ms", delta) return s.Raw(stat, dap, rate) } // Raw formats the statsd event data, handles sampling, prepares it, // and sends it to the server. // stat is the string name for the metric. // value is a preformatted "raw" value string. // rate is the sample rate (0.0 to 1.0). func (s *Client) Raw(stat string, value string, rate float32) error { if rate < 1 { if rand.Float32() < rate { value = fmt.Sprintf("%s|@%f", value, rate) } else { return nil } } if s.prefix != "" { stat = fmt.Sprintf("%s.%s", s.prefix, stat) } data := fmt.Sprintf("%s:%s", stat, value) _, err := s.send([]byte(data)) if err != nil { return err } return nil } // Sets/Updates the statsd client prefix func (s *Client) SetPrefix(prefix string) { s.prefix = prefix } // sends the data to the server endpoint func (s *Client) send(data []byte) (int, error) { // no need for locking here, as the underlying fdNet // already serialized writes n, err := s.c.(*net.UDPConn).WriteToUDP([]byte(data), s.ra) if err != nil { return 0, err } if n == 0 { return n, errors.New("Wrote no bytes") } return n, nil } // Returns a pointer to a new Client, and an error. // addr is a string of the format "hostname:port", and must be parsable by // net.ResolveUDPAddr. // prefix is the statsd client prefix. Can be "" if no prefix is desired. func New(addr, prefix string) (*Client, error) { c, err := net.ListenPacket("udp", ":0") if err != nil { return nil, err } ra, err := net.ResolveUDPAddr("udp", addr) if err != nil { return nil, err } client := &Client{ c: c, ra: ra, prefix: prefix} return client, nil } // Compatibility alias var Dial = New
statsd/main.go
0.824921
0.482612
main.go
starcoder
package triangle import ( "errors" "fmt" "math" "math/big" "strings" ) type side float64 type angle float64 func (triangle AbstractTriangle) isEqual(otherTriangle AbstractTriangle) bool { return triangle.A.isEqual(otherTriangle.A) && triangle.B.isEqual(otherTriangle.B) && triangle.C.isEqual(otherTriangle.C) && triangle.Alpha.isEqual(otherTriangle.Alpha) && triangle.Beta.isEqual(otherTriangle.Beta) && triangle.Gamma.isEqual(otherTriangle.Gamma) } func (a side) isEqual(b side) bool { floatA := big.NewFloat(float64(a)) floatB := big.NewFloat(float64(b)) return floatA.Cmp(floatB) == 0 } func (a angle) isEqual(b angle) bool { floatA := big.NewFloat(float64(a)) floatB := big.NewFloat(float64(b)) return floatA.Cmp(floatB) == 0 } type kind string type sideClassification string type angleClassification string const ( sss kind = "Side-Side-Side" aas kind = "Angle-Angle-Side" asa kind = "Angle-Side-Angle" sas kind = "Side-Angle-Side" ssa kind = "Side-Side-Angle" ) const ( right sideClassification = "Right" equilateral sideClassification = "Equilateral" isosceles sideClassification = "Isosceles" scalene sideClassification = "Scalene" ) const ( acute angleClassification = "Acute" obtuse angleClassification = "Obtuse" ) type AbstractTriangle struct { A side Alpha angle B side Beta angle C side Gamma angle kind kind } type Triangle interface { Solve() Description() string } func (triangle *AbstractTriangle) Description() string { var builder strings.Builder sideClassification, angleClassification := triangle.classification() header := fmt.Sprintf("%v Triangle\n", triangle.kind) title := fmt.Sprintf("Classification by sides: %v, by angles: %v\n", sideClassification, angleClassification) sides := fmt.Sprintf("Sides - A: %v, B: %v, C: %v\n", triangle.A, triangle.B, triangle.C) angles := fmt.Sprintf("Angles - Alpha: %v, Beta: %v, Gamma: %v\n", triangle.Alpha, triangle.Beta, triangle.Gamma) perimeter := fmt.Sprintf("Perimeter: %v\n", triangle.perimeter()) semiPerimeter := fmt.Sprintf("Semiperimeter: %v\n", triangle.semiPerimeter()) area := fmt.Sprintf("Area: %v\n", triangle.area()) inradius := fmt.Sprintf("Inradius: %v\n", triangle.inradius()) circumradius := fmt.Sprintf("Circumradius: %v\n", triangle.circumradius()) builder.WriteString(header) builder.WriteString(title) builder.WriteString(sides) builder.WriteString(angles) builder.WriteString(perimeter) builder.WriteString(semiPerimeter) builder.WriteString(area) builder.WriteString(inradius) builder.WriteString(circumradius) return builder.String() } // NewTriangle returns a Triangle type based on the input received func NewTriangle(a float64, alpha float64, b float64, beta float64, c float64, gamma float64) (Triangle, error) { if a != 0 && b != 0 && c != 0 { return newSSSTriangle(side(a), side(b), side(c)), nil } else if a != 0 && b != 0 && beta != 0 { return newSSATriangle(side(a), side(b), angle(beta)), nil } else if a != 0 && beta != 0 && c != 0 { return newSASTriangle(side(a), angle(beta), side(c)), nil } else if alpha != 0 && b != 0 && gamma != 0 { return newASATriangle(angle(alpha), side(b), angle(gamma)), nil } else if a != 0 && alpha != 0 && beta != 0 { return newAASTriangle(side(a), angle(alpha), angle(beta)), nil } return nil, errors.New("unable to understand the triangle, please format your input as SSS/SSA/SAS/ASA/AAS triangles") } func (triangle *AbstractTriangle) perimeter() float64 { return float64(triangle.A) + float64(triangle.B) + float64(triangle.C) } func (triangle *AbstractTriangle) semiPerimeter() float64 { return triangle.perimeter() / 2 } func (triangle *AbstractTriangle) area() float64 { semiPerimeter := triangle.semiPerimeter() return math.Sqrt(semiPerimeter * (semiPerimeter - float64(triangle.A)) * (semiPerimeter - float64(triangle.B)) * (semiPerimeter - float64(triangle.C))) } func (triangle *AbstractTriangle) inradius() float64 { return triangle.semiPerimeter() / triangle.area() } func (triangle *AbstractTriangle) circumradius() float64 { return float64(triangle.A) / (2 * math.Sin(float64(triangle.Alpha))) } func (triangle *AbstractTriangle) classification() (sideClassification, angleClassification) { rightAngle := angle(math.Pi / 2) var sideClass sideClassification var angleClass angleClassification if triangle.Alpha.isEqual(rightAngle) || triangle.Beta.isEqual(rightAngle) || triangle.Gamma.isEqual(rightAngle) { sideClass = right } else if triangle.A == triangle.B && triangle.B == triangle.C && triangle.C == triangle.A { sideClass = equilateral } else if triangle.A == triangle.B || triangle.B == triangle.C || triangle.C == triangle.A { sideClass = isosceles } else { sideClass = scalene } if float64(triangle.Alpha) < float64(rightAngle) || float64(triangle.Beta) < float64(rightAngle) || float64(triangle.Gamma) < float64(rightAngle) { angleClass = acute } else { angleClass = obtuse } return sideClass, angleClass } func radiansToDegrees(radians float64) float64 { return ((radians * 180) / math.Pi) } func degreesToRadians(degrees float64) float64 { return float64((degrees * math.Pi) / 180) } func (triangle *AbstractTriangle) sineLawForAngle(baseSide side, baseAngle angle, knownLeg side) angle { a := float64(baseSide) alpha := float64(baseAngle) b := float64(knownLeg) return angle(math.Asin(b * math.Sin(alpha) / a)) } func (triangle *AbstractTriangle) sineLawForSide(baseSide side, baseAngle angle, knownAngle angle) side { a := float64(baseSide) alpha := float64(baseAngle) beta := float64(knownAngle) return side(math.Sin(beta) * a / math.Sin(alpha)) }
pkg/triangle/triangle.go
0.879121
0.613237
triangle.go
starcoder
package bn256 import ( "errors" "math/big" ) // G1 is an abstract cyclic group. The zero value is suitable for use as the // output of an operation, but cannot be used as an input. type G1 struct { p *curvePoint } func (g *G1) String() string { return "bn256.G1" + g.p.String() } // Base set e to g where g is the generator of the group and then returns e. func (e *G1) Base() *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.Set(curveGen) return e } // Zero set e to the null element and then returns e. func (e *G1) Zero() *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.SetInfinity() return e } // IsZero returns whether e is zero or not. func (e *G1) IsZero() bool { if e.p == nil { return true } return e.p.IsInfinity() } // ScalarBaseMult sets e to g*k where g is the generator of the group and then // returns e. func (e *G1) ScalarBaseMult(k *big.Int) *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.Mul(curveGen, k) return e } // ScalarMult sets e to a*k and then returns e. func (e *G1) ScalarMult(a *G1, k *big.Int) *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.Mul(a.p, k) return e } // Add sets e to a+b and then returns e. func (e *G1) Add(a, b *G1) *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.Add(a.p, b.p) return e } // Neg sets e to -a and then returns e. func (e *G1) Neg(a *G1) *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.Neg(a.p) return e } // Set sets e to a and then returns e. func (e *G1) Set(a *G1) *G1 { if e.p == nil { e.p = &curvePoint{} } e.p.Set(a.p) return e } // Marshal converts e to a byte slice. func (e *G1) Marshal() []byte { // Each value is a 256-bit number. const numBytes = 256 / 8 if e.p == nil { e.p = &curvePoint{} } e.p.MakeAffine() ret := make([]byte, numBytes*2) if e.p.IsInfinity() { return ret } temp := &gfP{} montDecode(temp, &e.p.x) temp.Marshal(ret) montDecode(temp, &e.p.y) temp.Marshal(ret[numBytes:]) return ret } // Unmarshal sets e to the result of converting the output of Marshal back into // a group element and then returns e. func (e *G1) Unmarshal(m []byte) error { // Each value is a 256-bit number. const numBytes = 256 / 8 if len(m) != 2*numBytes { return errors.New("bn256.G1: incorrect data length") } if e.p == nil { e.p = &curvePoint{} } e.p.x.Unmarshal(m) e.p.y.Unmarshal(m[numBytes:]) montEncode(&e.p.x, &e.p.x) montEncode(&e.p.y, &e.p.y) if e.p.x.IsZero() && e.p.y.IsZero() { // This is the point at infinity. e.p.SetInfinity() } else { e.p.z.SetOne() e.p.t.SetOne() if !e.p.IsOnCurve() { return errors.New("bn256.G1: malformed point") } } return nil }
bn256/bn256g1.go
0.822403
0.443721
bn256g1.go
starcoder
package tic import ( "fmt" "strconv" "strings" "github.com/jwalton/gchalk" "github.com/shurcooL/tictactoe" i "devzat/pkg/interfaces" "devzat/pkg/models" ) const ( name = "tic" argsInfo = "" info = "start a game of tic tac toe" ) type state = struct { Board *tictactoe.Board currentPlayer tictactoe.State } type Command struct { state map[string]*state // each room has its own state } func (c *Command) Name() string { return name } func (c *Command) ArgsInfo() string { return argsInfo } func (c *Command) Info() string { return info } func (c *Command) Visibility() models.CommandVisibility { return models.CommandVisNormal } func (c *Command) Fn(rest string, u i.User) error { if c.state == nil { c.state = make(map[string]*state) } s := c.getState(u) if rest == "" { u.Room().BotCast("Starting a new game of Tic Tac Toe! The first player is always X.") u.Room().BotCast("Play using tic <cell num>") s.currentPlayer = tictactoe.X s.Board = new(tictactoe.Board) u.Room().BotCast("```\n" + " 1 │ 2 │ 3\n───┼───┼───\n 4 │ 5 │ 6\n───┼───┼───\n 7 │ 8 │ 9\n" + "\n```") return nil } m, err := strconv.Atoi(rest) if err != nil { u.Room().BotCast("Make sure you're using a number lol") return nil } if m < 1 || m > 9 { u.Room().BotCast("Moves are numbers between 1 and 9!") return nil } err = s.Board.Apply(tictactoe.Move(m-1), s.currentPlayer) if err != nil { u.Room().BotCast(err.Error()) return nil } u.Room().BotCast("```\n" + tttPrint(s.Board.Cells) + "\n```") if s.currentPlayer == tictactoe.X { s.currentPlayer = tictactoe.O } else { s.currentPlayer = tictactoe.X } if !(s.Board.Condition() == tictactoe.NotEnd) { u.Room().BotCast(s.Board.Condition().String()) s.currentPlayer = tictactoe.X s.Board = new(tictactoe.Board) } return nil } func (c *Command) getState(u i.User) *state { if c.state[u.Room().Name()] == nil { c.state[u.Room().Name()] = &state{} } return c.state[u.Room().Name()] } func tttPrint(cells [9]tictactoe.State) string { chalk := gchalk.New(gchalk.ForceLevel(gchalk.LevelAnsi256)) return strings.ReplaceAll(strings.ReplaceAll( fmt.Sprintf(` %v │ %v │ %v ───┼───┼─── %v │ %v │ %v ───┼───┼─── %v │ %v │ %v `, cells[0], cells[1], cells[2], cells[3], cells[4], cells[5], cells[6], cells[7], cells[8]), tictactoe.X.String(), chalk.BrightYellow(tictactoe.X.String())), // add some coloring tictactoe.O.String(), chalk.BrightGreen(tictactoe.O.String())) }
pkg/commands/tic/command.go
0.523177
0.436682
command.go
starcoder
package bigquery import ( "errors" "fmt" "strconv" "time" bq "google.golang.org/api/bigquery/v2" ) // Value stores the contents of a single cell from a BigQuery result. type Value interface{} // ValueLoader stores a slice of Values representing a result row from a Read operation. // See Iterator.Get for more information. type ValueLoader interface { Load(v []Value) error } // ValueList converts a []Value to implement ValueLoader. type ValueList []Value // Load stores a sequence of values in a ValueList. func (vs *ValueList) Load(v []Value) error { *vs = append(*vs, v...) return nil } // convertRows converts a series of TableRows into a series of Value slices. // schema is used to interpret the data from rows; its length must match the // length of each row. func convertRows(rows []*bq.TableRow, schema Schema) ([][]Value, error) { var rs [][]Value for _, r := range rows { row, err := convertRow(r, schema) if err != nil { return nil, err } rs = append(rs, row) } return rs, nil } func convertRow(r *bq.TableRow, schema Schema) ([]Value, error) { if len(schema) != len(r.F) { return nil, errors.New("schema length does not match row length") } var values []Value for i, cell := range r.F { fs := schema[i] v, err := convertValue(cell.V, fs.Type, fs.Schema) if err != nil { return nil, err } values = append(values, v) } return values, nil } func convertValue(val interface{}, typ FieldType, schema Schema) (Value, error) { switch val := val.(type) { case nil: return nil, nil case []interface{}: return convertRepeatedRecord(val, typ, schema) case map[string]interface{}: return convertNestedRecord(val, schema) case string: return convertBasicType(val, typ) default: return nil, fmt.Errorf("got value %v; expected a value of type %s", val, typ) } } func convertRepeatedRecord(vals []interface{}, typ FieldType, schema Schema) (Value, error) { var values []Value for _, cell := range vals { // each cell contains a single entry, keyed by "v" val := cell.(map[string]interface{})["v"] v, err := convertValue(val, typ, schema) if err != nil { return nil, err } values = append(values, v) } return values, nil } func convertNestedRecord(val map[string]interface{}, schema Schema) (Value, error) { // convertNestedRecord is similar to convertRow, as a record has the same structure as a row. // Nested records are wrapped in a map with a single key, "f". record := val["f"].([]interface{}) if len(record) != len(schema) { return nil, errors.New("schema length does not match record length") } var values []Value for i, cell := range record { // each cell contains a single entry, keyed by "v" val := cell.(map[string]interface{})["v"] fs := schema[i] v, err := convertValue(val, fs.Type, fs.Schema) if err != nil { return nil, err } values = append(values, v) } return values, nil } // convertBasicType returns val as an interface with a concrete type specified by typ. func convertBasicType(val string, typ FieldType) (Value, error) { switch typ { case StringFieldType: return val, nil case IntegerFieldType: return strconv.Atoi(val) case FloatFieldType: return strconv.ParseFloat(val, 64) case BooleanFieldType: return strconv.ParseBool(val) case TimestampFieldType: f, err := strconv.ParseFloat(val, 64) return Value(time.Unix(0, int64(f*1e9))), err default: return nil, errors.New("unrecognized type") } }
vendor/google.golang.org/cloud/bigquery/value.go
0.751466
0.53777
value.go
starcoder
package main import "sort" /***************************************************************************************************** * * 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], * * A solution set is: * [ * [-1, 0, 1], * [-1, -1, 2] * ] * ******************************************************************************************************/ // 1。首先使用2+1实现3sum // 2。整合成nSum //time:30 mem:8 func threeSum(nums []int) [][]int { if len(nums) < 1 { return nil } sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] }) ans := [][]int{} for i := 0; i < len(nums); i++ { sub := twoSum(nums, i+1, 0-nums[i]) for _, v := range sub { ans = append(ans, append(v, nums[i])) } for i < len(nums)-1 && nums[i] == nums[i+1] { i++ } } return ans } func twoSum(nums []int, start, target int) [][]int { if len(nums) < 2 || start >= len(nums) { return nil } var ( l, r = start, len(nums) - 1 ans = [][]int{} ) for l < r { sum := nums[l] + nums[r] left, right := nums[l], nums[r] if sum == target { ans = append(ans, []int{nums[l], nums[r]}) for l < r && left == nums[l] { l++ } for l < r && right == nums[r] { r-- } } else if sum < target { for l < r && left == nums[l] { l++ } } else if sum > target { for l < r && right == nums[r] { r-- } } } return ans } // 整合nSum func nSumTarget(nums []int, start, n, target int) [][]int { sz := len(nums) if n < 2 || sz < n { return nil } ans := [][]int{} if n == 2 { l, r := start, sz-1 for l < r { left, right := nums[l], nums[r] sum := left + right if sum == target { ans = append(ans, []int{left, right}) for l < r && left == nums[l] { l++ } for l < r && right == nums[r] { r-- } } else if sum < target { for l < r && left == nums[l] { l++ } } else if sum > target { for l < r && right == nums[r] { r-- } } } } else { for i := start; i < sz; i++ { sub := nSumTarget(nums, i+1, n-1, target-nums[i]) for _, v := range sub { ans = append(ans, append(v, nums[i])) } for i < sz-1 && nums[i] == nums[i+1] { i++ } } } return ans } func threeSum2(nums []int) [][]int{ if len(nums) < 1 { return nil } sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] }) return nSumTarget(nums,0,3,0) }
leetcode/15.3sum/15.3Sum_zhangsl.go
0.544317
0.504272
15.3Sum_zhangsl.go
starcoder
package assets // GKEPlanSchema is the JSON schema used to describe and validate GKE Plans const GKEPlanSchema = ` { "$id": "https://appvia.io/schemas/gke/plan.json", "$schema": "http://json-schema.org/draft-07/schema#", "description": "GKE Cluster Plan Schema", "type": "object", "additionalProperties": false, "required": [ "authorizedMasterNetworks", "authProxyAllowedIPs", "description", "diskSize", "domain", "enableAutoupgrade", "enableAutorepair", "enableAutoscaler", "enableDefaultTrafficBlock", "enableHTTPLoadBalancer", "enableHorizontalPodAutoscaler", "enableIstio", "enablePrivateEndpoint", "enablePrivateNetwork", "enableShieldedNodes", "enableStackDriverLogging", "enableStackDriverMetrics", "imageType", "inheritTeamMembers", "machineType", "maintenanceWindow", "maxSize", "network", "region", "size", "subnetwork", "version" ], "properties": { "authorizedMasterNetworks": { "type": "array", "description": "The networks which are allowed to access the master control plane.", "items": { "type": "object", "additionalProperties": false, "required": [ "name", "cidr" ], "properties": { "name": { "type": "string", "minLength": 1 }, "cidr": { "type": "string", "format": "1.2.3.4/16" } } }, "minItems": 1 }, "authProxyAllowedIPs": { "type": "array", "description": "The networks which are allowed to connect to this cluster (e.g. via kubectl).", "items": { "type": "string", "format": "1.2.3.4/16" }, "minItems": 1 }, "authProxyImage": { "type": "string", "description": "TBC" }, "clusterUsers": { "type": "array", "description": "Users who should be allowed to access this cluster.", "items": { "type": "object", "additionalProperties": false, "required": [ "username", "roles" ], "properties": { "username": { "type": "string", "minLength": 1 }, "roles": { "type": "array", "items": { "type": "string", "minLength": 1 }, "minItems": 1 } } } }, "defaultTeamRole": { "type": "string", "description": "The default role that team members have on this cluster." }, "description": { "type": "string", "description": "Meaningful description of this cluster.", "minLength": 1 }, "diskSize": { "type": "number", "description": "The amount of storage provisioned on this cluster? Or on its nodes?", "multipleOf": 1, "minimum": 10, "maximum": 65536 }, "domain": { "type": "string", "description": "The domain for this cluster.", "minLength": 1 }, "enableAutoupgrade": { "type": "boolean", "description": "Enable to keep this cluster updated whenever new versions of Kubernetes are made available by GCP." }, "enableAutorepair": { "type": "boolean" }, "enableAutoscaler": { "type": "boolean" }, "enableDefaultTrafficBlock": { "type": "boolean" }, "enableHTTPLoadBalancer": { "type": "boolean" }, "enableHorizontalPodAutoscaler": { "type": "boolean" }, "enableIstio": { "type": "boolean" }, "enablePrivateEndpoint": { "type": "boolean" }, "enablePrivateNetwork": { "type": "boolean" }, "enableShieldedNodes": { "type": "boolean" }, "enableStackDriverLogging": { "type": "boolean" }, "enableStackDriverMetrics": { "type": "boolean" }, "imageType": { "type": "string", "minLength": 1 }, "inheritTeamMembers": { "type": "boolean" }, "machineType": { "type": "string", "description": "The type of nodes used for this cluster's node pool.", "minLength": 1 }, "maintenanceWindow": { "type": "string", "description": "Time of day to allow maintenance operations to be performed by the cloud provider on this cluster.", "format": "hh:mm" }, "maxSize": { "type": "number", "description": "Maximum number of nodes? to allow for this cluster if auto-scaling enabled.", "multipleOf": 1, "minimum": 0 }, "network": { "type": "string", "minLength": 1 }, "region": { "type": "string", "minLength": 1, "immutable": true }, "size": { "type": "number", "multipleOf": 1, "minimum": 0 }, "subnetwork": { "type": "string", "minLength": 1 }, "version": { "type": "string", "description": "The Kubernetes version to deploy.", "minLength": 1 } }, "if": { "properties": { "inheritTeamMembers": { "const": true } }, "required": ["inheritTeamMembers"] }, "then": { "properties": { "defaultTeamRole": { "minLength": 1 } }, "required": ["defaultTeamRole"] }, "else": { } } `
pkg/kore/assets/plan_schema_gke.go
0.660063
0.498962
plan_schema_gke.go
starcoder
package training import ( "bufio" "fmt" "math" "os" "github.com/AlessandroPomponio/go-gibberish/analysis" "github.com/AlessandroPomponio/go-gibberish/persistence" "github.com/AlessandroPomponio/go-gibberish/structs" ) // TrainModel computes the probabilities of having a certain // digraph by reading a big file. func TrainModel(acceptedChars, trainingFileName, goodFileName, badFileName, outputFileName string) error { position := getRunePosition(acceptedChars) // Assume we have seen 10 of each character pair. This acts as a kind of // prior or smoothing factor. This way, if we see a character transition // live that we've never observed in the past, we won't assume the entire // string has 0 probability. occurrences := initializeOccurrencesMatrix(len(acceptedChars)) trainingFile, err := os.Open(trainingFileName) if err != nil { return fmt.Errorf("TrainModel: unable to open training file %s", trainingFileName) } // Count the occurrences of rune pairs by reading a big file. tfReader := bufio.NewReader(trainingFile) for { line, _, err := tfReader.ReadLine() if err != nil { break } for _, pair := range analysis.GetDigraphs(string(line)) { firstPosition, firstRuneFound := position[pair.First] if !firstRuneFound { return fmt.Errorf("TrainModel: unable to find the position of the rune %s", string(pair.First)) } secondPosition, secondRuneFound := position[pair.Second] if !secondRuneFound { return fmt.Errorf("TrainModel: unable to find the position of the rune %s", string(pair.First)) } occurrences[firstPosition][secondPosition]++ } } _ = trainingFile.Close() // Normalize the counts so that they become log probabilities. // We use log probabilities rather than straight probabilities to avoid // numeric underflow issues with long texts. // This contains a justification: // http://squarecog.wordpress.com/2009/01/10/dealing-with-underflow-in-joint-probability-calculations/ normalizeOccurrencesMatrix(occurrences) // Find the probability of generating a few arbitrarily chosen good and bad phrases. goodProbabilities, err := averageTransitionProbabilitiesInFile(goodFileName, occurrences, position) if err != nil { return fmt.Errorf("TrainModel: error when computing good probabilities: %s", err) } badProbabilities, err := averageTransitionProbabilitiesInFile(badFileName, occurrences, position) if err != nil { return fmt.Errorf("TrainModel: error when computing bad probabilities: %s", err) } minimumGoodProbability := analysis.MinForSlice(goodProbabilities) maximumBadProbability := analysis.MaxForSlice(badProbabilities) // Make sure we are actually capable of detecting the junk. if minimumGoodProbability <= maximumBadProbability { return fmt.Errorf("TrainModel: minimumGoodProbability <= maximumBadProbability") } // Pick a threshold halfway between the worst good and best bad inputs. threshold := (minimumGoodProbability + maximumBadProbability) / 2 data := structs.GibberishData{ Occurrences: occurrences, Positions: position, Threshold: threshold, } err = persistence.WriteKnowledgeBase(&data, outputFileName) return err } func averageTransitionProbabilitiesInFile(fileName string, occurrences [][]float64, position map[rune]int) ([]float64, error) { res := make([]float64, 0, 5) file, err := os.Open(fileName) if err != nil { return nil, fmt.Errorf("averageTransitionProbabilitiesInFile: unable to open file %s", fileName) } fReader := bufio.NewReader(file) for { line, _, err := fReader.ReadLine() if err != nil { break } avgProb, err := analysis.AverageTransitionProbability(string(line), occurrences, position) if err != nil { break } res = append(res, avgProb) } _ = file.Close() return res, err } func getRunePosition(characters string) map[rune]int { position := make(map[rune]int) for index, currentRune := range characters { position[currentRune] = index } return position } func initializeOccurrencesMatrix(symbols int) [][]float64 { occurrences := make([][]float64, symbols) for row := range occurrences { occurrences[row] = make([]float64, symbols) for column := range occurrences[row] { occurrences[row][column] = 10 } } return occurrences } func normalizeOccurrencesMatrix(occurrences [][]float64) { for _, row := range occurrences { sum := 0. for i := 0; i < len(row); i++ { sum += row[i] } for i := 0; i < len(row); i++ { row[i] = math.Log(row[i] / sum) } } }
training/training.go
0.708313
0.488649
training.go
starcoder
package gorgonia import ( "fmt" tf32 "github.com/chewxy/gorgonia/tensor/f32" tf64 "github.com/chewxy/gorgonia/tensor/f64" "github.com/chewxy/gorgonia/tensor/types" "github.com/pkg/errors" ) // Functions in this file returns *Node and panics if an error happens /* Helper functions to create new input nodes */ // Must indicates a node must be created. If there isn't a node created, or there was an error, // it subsumes the error, and immediately panics func Must(n *Node, err error, opts ...NodeConsOpt) *Node { if err != nil || n == nil { panic(err) } return n } // NewScalar creates a Node representing a variable that holds a scalar value func NewScalar(g *ExprGraph, t Dtype, opts ...NodeConsOpt) *Node { curOpts := []NodeConsOpt{withType(t), withGraph(g)} curOpts = append(curOpts, opts...) return newUniqueNode(curOpts...) } // NewVector creates a Node representing a variable that holds a vector (nx1 matrix) func NewVector(g *ExprGraph, t Dtype, opts ...NodeConsOpt) *Node { tt := newTensorType(1, t) curOpts := []NodeConsOpt{withType(tt), withGraph(g)} curOpts = append(curOpts, opts...) return newUniqueNode(curOpts...) } // NewMatrix creates a Node representing a variable that holds a matrix (nxm) func NewMatrix(g *ExprGraph, t Dtype, opts ...NodeConsOpt) *Node { tt := newTensorType(2, t) curOpts := []NodeConsOpt{withType(tt), withGraph(g)} curOpts = append(curOpts, opts...) return newUniqueNode(curOpts...) } // NewTensor creates a Node representing a variable that holds a tensor (any n-dimensional array with dimensions greater than 2) func NewTensor(g *ExprGraph, t Dtype, dims int, opts ...NodeConsOpt) *Node { tt := newTensorType(dims, t) curOpts := []NodeConsOpt{withType(tt), withGraph(g)} curOpts = append(curOpts, opts...) return newUniqueNode(curOpts...) } // NewConstant takes in any reasonable value and makes it a constant node. func NewConstant(v interface{}, opts ...NodeConsOpt) *Node { var op Op var t Type var name string var s types.Shape var val Value name = fmt.Sprintf("%v", v) switch a := v.(type) { case Scalar: op = constantScalar{a} val = a t = a.Type() s = scalarShape case Tensor: op = constantTensor{a} val = a t = a.Type() s = a.Shape() case int, int64, float64, float32, byte, bool: sv := NewScalarValue(v) op = constantScalar{sv} val = sv t = sv.Type() s = scalarShape case types.Tensor: T := FromTensor(a) op = constantTensor{T} val = T s = a.Shape() t = T.Type() } if op == nil || t == nil { panic("HELP") } consOpts := []NodeConsOpt{withOp(op), withType(t), WithName(name), WithShape(s...), WithValue(val)} consOpts = append(consOpts, opts...) return newNode(consOpts...) } // UniformRandomNode creates an input node that has a random op so everytime the node is passed, random values will be plucked from // a uniform distribution. The type of the node depends on the // shape passed in. To get a scalar value at run time, don't pass in any shapes func UniformRandomNode(dt Dtype, low, high float64, shape ...int) *Node { op := makeRandomOp(uniform, dt, low, high, shape...) retVal, err := applyOp(op) if err != nil { panic(err) } return retVal } // GaussianRandomNode creates an input node that has a random op so everytime the node is passed, random values will be plucked from // a gaussian distribution with the mean and stdev provided. The type of the node depends on the // shape passed in. To get a scalar value at run time, don't pass in any shapes func GaussianRandomNode(dt Dtype, mean, stdev float64, shape ...int) *Node { op := makeRandomOp(gaussian, dt, mean, stdev, shape...) retVal, err := applyOp(op) if err != nil { panic(err) } return retVal } // OneHotVector creates a node representing a one hot vector func OneHotVector(id, classes int, t Dtype, opts ...NodeConsOpt) *Node { switch t { case Float64: backing := make([]float64, classes) backing[id] = float64(1) T := tf64.NewTensor(tf64.WithBacking(backing)) // dt, d := tensorInfo(T) return NewConstant(T, opts...) case Float32: backing := make([]float32, classes) backing[id] = float32(1) T := tf32.NewTensor(tf32.WithBacking(backing)) return NewConstant(T, opts...) default: panic("Not yet implemented for OneHotVector") } panic("unreachable") } // Grad takes a scalar cost node and a list of with-regards-to, and returns the gradient func Grad(cost *Node, WRTs ...*Node) (retVal []*Node, err error) { symdiffLogf("Cost:%v", cost) if !cost.IsScalar() { err = NewError(SymbDiffError, "Expected Cost to be a scalar. Got %v instead", cost) return } for i, n := range WRTs { if !n.isInput() { err = NewError(SymbDiffError, "Can only differentiate with regards to input nodes. Node %d isn't an input", i) } } var dt Dtype var ok bool if dt, ok = cost.t.(Dtype); !ok { err = NewError(TypeError, "Expected a scalar dtype for cost") } var gradOut *Node switch dt { case Float64: gradOut = onef64 case Float32: gradOut = onef32 default: err = nyi(dt.String(), "Grad()'s gradOut") return } gradOut = cost.g.AddNode(gradOut) return Backpropagate(Nodes{cost}, Nodes{gradOut}, Nodes(WRTs)) } // Let binds a Value to a node that is a variable. A variable is represented as a *Node with no Op. // It is equivalent to : // x = 2 func Let(n *Node, be interface{}) (err error) { if !n.isInput() { err = NewError(RuntimeError, "Cannot bind a value to a non input node") return } var val Value if val, err = anyToValue(be); err != nil { err = errors.Wrapf(err, anyToValueFail, be, be) return } n.bind(val) return } // Set is the equivalent of doing this: // a = b // where a and b are both variables func Set(a, b *Node) (retVal *Node) { op := letOp{} name := fmt.Sprintf("%v %s %v", a, op, b) return newUniqueNode(withOp(op), withChildren(Nodes{a, b}), WithName(name), withGraph(a.g)) } // Read is one of those special snowflake tumblrina *Nodes. It allows for extraction of the value of the *Node at runtime // into a Value. Note that a *Value (a pointer to a Value) is passed into this function, not a Value. func Read(n *Node, into *Value) (retVal *Node) { op := readOp{into} name := fmt.Sprintf("read %v into %v", n, into) retVal = newUniqueNode(withOp(op), withChildren(Nodes{n}), WithName(name), withGraph(n.g)) retVal.op = op // this ensures the correct pointer is written retVal.name = name return }
gorgonia.go
0.741487
0.453685
gorgonia.go
starcoder
Package clustertemplates provides information and interaction with the cluster-templates through the OpenStack Container Infra service. Example to Create Cluster Template boolFalse := false boolTrue := true createOpts := clustertemplates.CreateOpts{ Name: "test-cluster-template", Labels: map[string]string{}, FixedSubnet: "", MasterFlavorID: "", NoProxy: "10.0.0.0/8,172.16.58.3/8,192.0.0.0/8,localhost", HTTPSProxy: "http://10.164.177.169:8080", TLSDisabled: &boolFalse, KeyPairID: "kp", Public: &boolFalse, HTTPProxy: "http://10.164.177.169:8080", ServerType: "vm", ExternalNetworkID: "public", ImageID: "fedora-atomic-latest", VolumeDriver: "cinder", RegistryEnabled: &boolFalse, DockerStorageDriver: "devicemapper", NetworkDriver: "flannel", FixedNetwork: "", COE: "kubernetes", FlavorID: "m1.small", MasterLBEnabled: &boolTrue, DNSNameServer: "8.8.8.8", } clustertemplate, err := clustertemplates.Create(serviceClient, createOpts).Extract() if err != nil { panic(err) } Example to Delete Cluster Template clusterTemplateID := "dc6d336e3fc4c0a951b5698cd1236ee" err := clustertemplates.Delete(serviceClient, clusterTemplateID).ExtractErr() if err != nil { panic(err) } Example to List Clusters Templates listOpts := clustertemplates.ListOpts{ Limit: 20, } allPages, err := clustertemplates.List(serviceClient, listOpts).AllPages() if err != nil { panic(err) } allClusterTemplates, err := clusters.ExtractClusterTemplates(allPages) if err != nil { panic(err) } for _, clusterTemplate := range allClusterTemplates { fmt.Printf("%+v\n", clusterTemplate) } Example to Update Cluster Template updateOpts := []clustertemplates.UpdateOptsBuilder{ clustertemplates.UpdateOpts{ Op: clustertemplates.ReplaceOp, Path: "/master_lb_enabled", Value: "True", }, clustertemplates.UpdateOpts{ Op: clustertemplates.ReplaceOp, Path: "/registry_enabled", Value: "True", }, } clustertemplate, err := clustertemplates.Update(serviceClient, updateOpts).Extract() if err != nil { panic(err) } */ package clustertemplates
vendor/github.com/gophercloud/gophercloud/openstack/containerinfra/v1/clustertemplates/doc.go
0.521471
0.556641
doc.go
starcoder
package main import ( "fmt" "strconv" "github.com/pkg/errors" "github.com/scylladb/scylla-manager/pkg/managerclient" "github.com/scylladb/scylla-manager/pkg/service/scheduler" "github.com/spf13/cobra" "github.com/spf13/pflag" ) const parallelLongDesc = ` The --parallel flag specifies the maximum number of Scylla repair jobs that can run at the same time (on different token ranges and replicas). Each node can take part in at most one repair at any given moment. By default the maximum possible parallelism is used. The effective parallelism depends on a keyspace replication factor (RF) and the number of nodes. The formula to calculate it is as follows: number of nodes / RF, e.g. for 6 node cluster with RF=3 the maximum parallelism is 2.` const intensityLongDesc = ` The --intensity flag specifies how many token ranges per shard to repair in a single Scylla repair job. By default this is 1. It can be a decimal between (0,1). In that case the number of token ranges is a fraction of number of shards. For Scylla clusters that do not support row-level repair (Scylla 2019 and earlier), it specifies percent of shards that can be repaired in parallel on a repair master node. If you set it to 0 the number of token ranges is adjusted to the maximum supported by node (see max_repair_ranges_in_parallel in Scylla logs). Changing the intensity impacts repair granularity if you need to resume it, the higher the value the more work on resume.` var repairCmd = &cobra.Command{ Use: "repair", Short: "Schedules repairs", Long: `Repair speed is controlled by two flags --parallel and --intensity. The values of those flags can be adjusted while a repair is running using the 'sctool repair control' command. ` + parallelLongDesc + ` ` + intensityLongDesc, RunE: func(cmd *cobra.Command, args []string) error { t := &managerclient.Task{ Type: "repair", Enabled: true, Schedule: new(managerclient.Schedule), Properties: make(map[string]interface{}), } return repairTaskUpdate(t, cmd) }, } func repairTaskUpdate(t *managerclient.Task, cmd *cobra.Command) error { if err := commonFlagsUpdate(t, cmd); err != nil { return err } props := t.Properties.(map[string]interface{}) failFast, err := cmd.Flags().GetBool("fail-fast") if err != nil { return err } if failFast { t.Schedule.NumRetries = 0 props["fail_fast"] = true } t.Properties = props if f := cmd.Flag("host"); f.Changed { host, err := cmd.Flags().GetString("host") if err != nil { return err } props["host"] = host } if f := cmd.Flag("ignore-down-hosts"); f.Changed { ignoreDownHosts, err := cmd.Flags().GetBool("ignore-down-hosts") if err != nil { return err } props["ignore_down_hosts"] = ignoreDownHosts } if f := cmd.Flag("intensity"); f.Changed { intensity, err := cmd.Flags().GetFloat64("intensity") if err != nil { return err } props["intensity"] = intensity } if f := cmd.Flag("parallel"); f.Changed { parallel, err := cmd.Flags().GetInt64("parallel") if err != nil { return err } props["parallel"] = parallel } if f := cmd.Flag("small-table-threshold"); f.Changed { smallTableThreshold, err := cmd.Flags().GetString("small-table-threshold") if err != nil { return err } threshold, err := managerclient.ParseByteCount(smallTableThreshold) if err != nil { return err } props["small_table_threshold"] = threshold } dryRun, err := cmd.Flags().GetBool("dry-run") if err != nil { return err } if dryRun { res, err := client.GetRepairTarget(ctx, cfgCluster, t) if err != nil { return err } showTables, err := cmd.Flags().GetBool("show-tables") if err != nil { return err } if showTables { res.ShowTables = -1 } fmt.Fprintf(cmd.OutOrStderr(), "NOTICE: dry run mode, repair is not scheduled\n\n") return res.Render(cmd.OutOrStdout()) } if t.ID == "" { id, err := client.CreateTask(ctx, cfgCluster, t) if err != nil { return err } t.ID = id.String() } else if err := client.UpdateTask(ctx, cfgCluster, t); err != nil { return err } fmt.Fprintln(cmd.OutOrStdout(), managerclient.TaskJoin(t.Type, t.ID)) return nil } func init() { cmd := repairCmd taskInitCommonFlags(repairFlags(cmd)) register(cmd, rootCmd) } func repairFlags(cmd *cobra.Command) *pflag.FlagSet { fs := cmd.Flags() fs.StringSliceP("keyspace", "K", nil, "comma-separated `list` of keyspace/tables glob patterns, e.g. 'keyspace,!keyspace.table_prefix_*' used to include or exclude keyspaces from repair") fs.StringSlice("dc", nil, "comma-separated `list` of datacenter glob patterns, e.g. 'dc1,!otherdc*', used to specify the DCs to include or exclude from repair") fs.Bool("dry-run", false, "validate and print repair information without scheduling a repair") fs.Bool("fail-fast", false, "stop repair on first error") fs.String("host", "", "host to repair, by default all hosts are repaired") fs.Bool("ignore-down-hosts", false, "do not repair nodes that are down i.e. in status DN") fs.Bool("show-tables", false, "print all table names for a keyspace. Used only in conjunction with --dry-run") fs.Var(&IntensityFlag{Value: 1}, "intensity", "how many token ranges (per shard) to repair in a single Scylla repair job, see the command description for details") fs.String("small-table-threshold", "1GiB", "enable small table optimization for tables of size lower than given threshold. Supported units [B, MiB, GiB, TiB]") fs.Int64("parallel", 0, "limit of parallel repair jobs, full parallelism by default, see the command description for details") return fs } var repairControlCmd = &cobra.Command{ Use: "control", Short: "Changes repair parameters on the flight", Long: `Changes repair parameters on the flight ` + parallelLongDesc + ` ` + intensityLongDesc, RunE: func(cmd *cobra.Command, args []string) error { if !cmd.Flag("intensity").Changed && !cmd.Flag("parallel").Changed { return errors.New("at least one of intensity or parallel flags needs to be specified") } if f := cmd.Flag("intensity"); f.Changed { i, err := cmd.Flags().GetFloat64("intensity") if err != nil { return err } if err := client.SetRepairIntensity(ctx, cfgCluster, i); err != nil { return err } } if f := cmd.Flag("parallel"); f.Changed { p, err := cmd.Flags().GetInt64("parallel") if err != nil { return err } if err := client.SetRepairParallel(ctx, cfgCluster, p); err != nil { return err } } return nil }, } func init() { cmd := repairControlCmd fs := cmd.Flags() fs.Var(&IntensityFlag{Value: 1}, "intensity", "how many token ranges (per shard) to repair in a single Scylla repair job, see the command description for details") fs.Int64("parallel", 0, "limit of parallel repair jobs, full parallelism by default, see the command description for details") register(cmd, repairCmd) } // IntensityFlag represents intensity flag which is a float64 value with a custom validation. type IntensityFlag struct { Value float64 } // String returns intensity value as string. func (fl *IntensityFlag) String() string { return fmt.Sprint(fl.Value) } // Set validates and sets intensity value. func (fl *IntensityFlag) Set(s string) error { errValidation := errors.New("intensity must be an integer >= 1 or a decimal between (0,1)") f, err := strconv.ParseFloat(s, 64) if err != nil { return errValidation } if f > 1 { _, err := strconv.ParseInt(s, 10, 64) if err != nil { return errValidation } } fl.Value = f return nil } // Type returns type of intensity. func (fl *IntensityFlag) Type() string { return "float64" } var repairUpdateCmd = &cobra.Command{ Use: "update <type/task-id>", Short: "Modifies a repair task", Long: `Modifies a repair task Repair speed is controlled by two flags --parallel and --intensity. The values of those flags can be adjusted while a repair is running using the 'sctool repair control' command. ` + parallelLongDesc + ` ` + intensityLongDesc, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { taskType, taskID, err := managerclient.TaskSplit(args[0]) if err != nil { return err } if scheduler.TaskType(taskType) != scheduler.RepairTask { return fmt.Errorf("repair update can't handle %s task", taskType) } t, err := client.GetTask(ctx, cfgCluster, taskType, taskID) if err != nil { return err } return repairTaskUpdate(t, cmd) }, } func init() { cmd := repairUpdateCmd fs := repairFlags(cmd) fs.StringP("enabled", "e", "true", "enabled") taskInitCommonFlags(fs) register(cmd, repairCmd) }
pkg/cmd/sctool/repair.go
0.651133
0.424352
repair.go
starcoder
package ween import ( "korok.io/korok/math/f32" "korok.io/korok/gfx" "log" ) func U8Lerp(from, to uint8, f float32) uint8 { v1, v2 := float32(from), float32(to) return uint8(v1+(v2-v1)*f) } func U16Lerp(from, to uint16, f float32) uint16 { v1, v2 := float32(from), float32(to) return uint16(v1+(v2-v1)*f) } func IntLerp(from, to int, f float32) int { return from + int(float32(to-from)*f) } func F32Lerp(from, to float32, f float32) float32 { return from + (to-from)*f } func Vec2Lerp(from, to f32.Vec2, f float32) f32.Vec2 { v2 := f32.Vec2{ F32Lerp(from[0], to[0], f), F32Lerp(from[1], to[1], f), } return v2 } func ColorLerp(from, to gfx.Color, f float32) gfx.Color { c := gfx.Color{ R: U8Lerp(from.R, to.R, f), G: U8Lerp(from.G, to.G, f), B: U8Lerp(from.B, to.B, f), A: U8Lerp(from.A, to.A, f), } return c } // A float32 linear interpolation between a beginning and ending value. // It use the Animator as the input. type F32Tween struct { am Animator from, to float32 } // Animate sets the Animator that drives the Tween. func (t *F32Tween) Animate(am Animator) Animator { t.am = am return am } // Animator returns the Animator driving the Tween. func (t *F32Tween) Animator() Animator { if !t.am.Valid() { log.Println("animator is unavailable") } return t.am } // Range sets the beginning and ending value of the F32Tween. func (t *F32Tween) Range(from, to float32) *F32Tween { t.from = from t.to = to return t } // Returns the interpolated value for the current value of the given Animator. func (t *F32Tween) Value() float32 { return F32Lerp(t.from, t.to, t.am.Value()) } // A f32.Vec2 linear interpolation between a beginning and ending value. // It use the Animator as the input. type Vec2Tween struct { am Animator from, to f32.Vec2 } // Animate sets the Animator that drives the Tween. func (t *Vec2Tween) Animate(am Animator) Animator { t.am = am return am } // Animator returns the Animator driving the Tween. func (t *Vec2Tween) Animator() Animator { return t.am } // Range sets the beginning and ending value of the Vec2Tween. func (t *Vec2Tween) Range(from, to f32.Vec2) *Vec2Tween { t.from, t.to = from, to return t } // Returns the interpolated value for the current value of the given Animator. func (t *Vec2Tween) Value() f32.Vec2 { return Vec2Lerp(t.from, t.to, t.am.Value()) } // A gfx.Color linear interpolation between a beginning and ending value. // It use the Animator as the input. type ColorTween struct { am Animator from, to gfx.Color } // Range sets the beginning and ending value of the ColorTween. func (t *ColorTween) Range(from, to gfx.Color) *ColorTween { t.from, t.to = from, to return t } // Animate sets the Animator that drives the Tween. func (t *ColorTween) Animate(animator Animator) Animator { t.am = animator return animator } // Animator returns the Animator driving the Tween. func (t *ColorTween) Animator() Animator { return t.am } // Returns the interpolated value for the current value of the given Animator. func (t *ColorTween) Value() gfx.Color { return ColorLerp(t.from, t.to, t.am.Value()) }
anim/ween/tweens.go
0.859059
0.479626
tweens.go
starcoder
package scf import ( "encoding/binary" "errors" "fmt" "math" "reflect" ) // Validate checks that command has a type that is compatible with the // requirements of this package and can be safely passed to Serialize and Parse. // Command must be a struct and all fields must be supported data types (see package description). // It returns an error if this is not the case. func Validate(command interface{}) error { return ValidateType(reflect.TypeOf(command)) } // Validate checks that commandType is compatible with the requirements of this // package and can be safely passed to Serialize and Parse. // Command must be a struct and all fields must be supported data types (see package description). // It returns an error if this is not the case. func ValidateType(commandType reflect.Type) error { if commandType.Kind() != reflect.Struct { return errors.New("command must be a struct") } for f := 0; f < commandType.NumField(); f++ { field := commandType.Field(f) if !isFieldTypeValid(field.Type) { return fmt.Errorf("command field %s.%s has invalid type", commandType.Name(), field.Name) } } return nil } func isFieldTypeValid(fieldType reflect.Type) bool { fieldKind := fieldType.Kind() if fieldKind == reflect.Slice { fieldKind = fieldType.Elem().Kind() } validKinds := []reflect.Kind{ reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, } for _, kind := range validKinds { if fieldKind == kind { return true } } return false } // Serialize returns the binary representation of a command. // Serialize panics if the type of command is not supported (use Validate to check). // If a slice has more than 255 elements, it is truncated to the first 255 elements. func Serialize(command interface{}) []byte { return SerializeValue(reflect.ValueOf(command)) } // SerializeValue is the same as Serialize, except it accepts command already // wrapped in a reflect.Value. func SerializeValue(commandValue reflect.Value) (data []byte) { for f := 0; f < commandValue.NumField(); f++ { field := commandValue.Field(f) fieldKind := field.Kind() if fieldKind == reflect.Slice { length := field.Len() if length > math.MaxUint8 { length = math.MaxUint8 } switch field.Type().Elem().Kind() { case reflect.Uint8: data = append(data, byte(length)) data = append(data, field.Bytes()[:length]...) case reflect.Uint16: data = append(data, byte(length)) for _, value := range field.Interface().([]uint16)[:length] { start := len(data) data = append(data, 0, 0) binary.LittleEndian.PutUint16(data[start:], uint16(value)) } case reflect.Uint32: data = append(data, byte(length)) for _, value := range field.Interface().([]uint32)[:length] { start := len(data) data = append(data, 0, 0, 0, 0) binary.LittleEndian.PutUint32(data[start:], uint32(value)) } case reflect.Uint64: data = append(data, byte(length)) for _, value := range field.Interface().([]uint64)[:length] { start := len(data) data = append(data, 0, 0, 0, 0, 0, 0, 0, 0) binary.LittleEndian.PutUint64(data[start:], uint64(value)) } case reflect.Int8: data = append(data, byte(length)) for _, value := range field.Interface().([]int8)[:length] { data = append(data, byte(value)) } case reflect.Int16: data = append(data, byte(length)) for _, value := range field.Interface().([]int16)[:length] { start := len(data) data = append(data, 0, 0) binary.LittleEndian.PutUint16(data[start:], uint16(value)) } case reflect.Int32: data = append(data, byte(length)) for _, value := range field.Interface().([]int32)[:length] { start := len(data) data = append(data, 0, 0, 0, 0) binary.LittleEndian.PutUint32(data[start:], uint32(value)) } case reflect.Int64: data = append(data, byte(length)) for _, value := range field.Interface().([]int64)[:length] { start := len(data) data = append(data, 0, 0, 0, 0, 0, 0, 0, 0) binary.LittleEndian.PutUint64(data[start:], uint64(value)) } default: commandType := commandValue.Type() panic(fmt.Sprintf("serialization for command field not implemented: field=%s.%s type=%v kind=%v", commandType.Name(), commandType.Field(f).Name, field.Type(), fieldKind)) } continue } var value uint64 switch fieldKind { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value = uint64(field.Int()) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: value = field.Uint() default: commandType := commandValue.Type() panic(fmt.Sprintf("serialization for command field not implemented: field=%s.%s type=%v kind=%v", commandType.Name(), commandType.Field(f).Name, field.Type(), fieldKind)) } switch fieldKind { case reflect.Int8, reflect.Uint8: data = append(data, byte(value)) case reflect.Int16, reflect.Uint16: start := len(data) data = append(data, 0, 0) binary.LittleEndian.PutUint16(data[start:], uint16(value)) case reflect.Int32, reflect.Uint32: start := len(data) data = append(data, 0, 0, 0, 0) binary.LittleEndian.PutUint32(data[start:], uint32(value)) case reflect.Int64, reflect.Uint64: start := len(data) data = append(data, 0, 0, 0, 0, 0, 0, 0, 0) binary.LittleEndian.PutUint64(data[start:], uint64(value)) } } return } var ErrInvalidData = errors.New("invalid data") // Parse parses a command from the binary representation. // command must be a pointer to a struct, as the results are written into it. // Parse panics if the type of the struct is not supported (use Validate to check). // If the command could not be parsed, ErrInvalidData is returned. // Otherwise Parse returns the remaining part of data, that was not read into command. func Parse(command interface{}, data []byte) ([]byte, error) { return ParseValue(reflect.ValueOf(command).Elem(), data) } // ParseValue is like Parse except it accepts a reflect.Value. // In contrast to Parse, commandValue must wrap the struct directly (instead of being a pointer). // Also, commandValue must be addressable, as the parsed values are written into it. func ParseValue(commandValue reflect.Value, data []byte) ([]byte, error) { for f := 0; f < commandValue.NumField(); f++ { field := commandValue.Field(f) fieldKind := field.Kind() if fieldKind == reflect.Slice { if len(data) == 0 { return nil, ErrInvalidData } length := int(data[0]) data = data[1:] elemKind := field.Type().Elem().Kind() switch elemKind { case reflect.Uint8, reflect.Int8: if len(data) < length { return nil, ErrInvalidData } case reflect.Uint16, reflect.Int16: if 2*len(data) < length { return nil, ErrInvalidData } case reflect.Uint32, reflect.Int32: if 4*len(data) < length { return nil, ErrInvalidData } case reflect.Uint64, reflect.Int64: if 8*len(data) < length { return nil, ErrInvalidData } default: commandType := commandValue.Type() panic(fmt.Sprintf("deserialization for command field not implemented: field=%s.%s type=%v kind=%v", commandType.Name(), commandType.Field(f).Name, field.Type(), fieldKind)) } switch elemKind { case reflect.Uint8: fieldData := make([]uint8, length) copy(fieldData, data) data = data[length:] field.SetBytes(fieldData) case reflect.Uint16: fieldData := make([]uint16, length) for i := range fieldData { fieldData[i] = binary.LittleEndian.Uint16(data[2*i:]) } data = data[2*length:] field.Set(reflect.ValueOf(fieldData)) case reflect.Uint32: fieldData := make([]uint32, length) for i := range fieldData { fieldData[i] = binary.LittleEndian.Uint32(data[4*i:]) } data = data[4*length:] field.Set(reflect.ValueOf(fieldData)) case reflect.Uint64: fieldData := make([]uint64, length) for i := range fieldData { fieldData[i] = binary.LittleEndian.Uint64(data[8*i:]) } data = data[8*length:] field.Set(reflect.ValueOf(fieldData)) case reflect.Int8: fieldData := make([]int8, length) for i := range fieldData { fieldData[i] = int8(data[i]) } data = data[length:] field.Set(reflect.ValueOf(fieldData)) case reflect.Int16: fieldData := make([]int16, length) for i := range fieldData { fieldData[i] = int16(binary.LittleEndian.Uint16(data[2*i:])) } data = data[2*length:] field.Set(reflect.ValueOf(fieldData)) case reflect.Int32: fieldData := make([]int32, length) for i := range fieldData { fieldData[i] = int32(binary.LittleEndian.Uint32(data[4*i:])) } data = data[4*length:] field.Set(reflect.ValueOf(fieldData)) case reflect.Int64: fieldData := make([]int64, length) for i := range fieldData { fieldData[i] = int64(binary.LittleEndian.Uint64(data[8*i:])) } data = data[8*length:] field.Set(reflect.ValueOf(fieldData)) } continue } length := int(field.Type().Size()) if len(data) < length { return nil, ErrInvalidData } var value uint64 switch fieldKind { case reflect.Int8, reflect.Uint8: value = uint64(data[0]) case reflect.Int16, reflect.Uint16: value = uint64(binary.LittleEndian.Uint16(data)) case reflect.Int32, reflect.Uint32: value = uint64(binary.LittleEndian.Uint32(data)) case reflect.Int64, reflect.Uint64: value = uint64(binary.LittleEndian.Uint64(data)) default: commandType := commandValue.Type() panic(fmt.Sprintf("deserialization for command field not implemented: field=%s.%s type=%v kind=%v", commandType.Name(), commandType.Field(f).Name, field.Type(), fieldKind)) } data = data[length:] switch fieldKind { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: field.SetInt(int64(value)) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: field.SetUint(value) } } return data, nil }
pkg/scf/scf.go
0.727782
0.432483
scf.go
starcoder
package config import ( "strings" ) // Doc: https://core.telegram.org/bots/api#markdownv2-style var ( bracketsRepl *strings.Replacer sqBracketsRepl *strings.Replacer codeRepl *strings.Replacer htmlRepl *strings.Replacer mdv2Repl *strings.Replacer ) // EscapeBrackets provede escape syntax inside (...) and [...] // Inside (...) part of inline link definition, all ')' and '\' must be escaped with a preceding '\' character. func (TplData) EscapeBrackets(in string) string { return bracketsRepl.Replace(in) } // EscapeCode escaps '`' and '\' inside code block (```) func (TplData) EscapeCode(in string) string { return codeRepl.Replace(in) } // EscapeHTML escape html code // The Telegram API currently supports only the following // named HTML entities: &lt;, &gt;, &amp; and &quot;. func (TplData) EscapeHTML(in string) string { return htmlRepl.Replace(in) } func (TplData) EscapeMD2(in string) string { return mdv2Repl.Replace(in) } func (TplData) RemoveSquqreBrackets(in string) string { return sqBracketsRepl.Replace(in) } func (TplData) Replace(in, old, new string) string { return strings.ReplaceAll(in, old, new) } func (TplData) TrimSpace(in string) string { return strings.TrimSpace(in) } func (TplData) Contains(s, sub string) bool { return strings.Contains(s, sub) } func (TplData) Equal(s, t string) bool { return strings.EqualFold(s, t) } func (TplData) HasPrefix(s, prefix string) bool { return strings.HasPrefix(s, prefix) } func (TplData) HasSuffix(s, suffix string) bool { return strings.HasSuffix(s, suffix) } func init_tplfilters() { bracketsRepl = strings.NewReplacer( ")", "\\)", "\\", "\\\\", ) sqBracketsRepl = strings.NewReplacer( "[", "", "]", "", ) codeRepl = strings.NewReplacer( "`", "\\`", "\\", "\\\\", ) htmlRepl = strings.NewReplacer( "<", "&lt;", ">", "&gt;", "&", "&amp;", "\"", "&quot;", ) // EscapMarkdown filters reserved characters for markdown syntax mdv2Repl = strings.NewReplacer( "_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", "(", "\\(", ")", "\\)", "~", "\\~", "`", "\\`", ">", "\\>", "#", "\\#", "+", "\\+", "-", "\\-", "=", "\\=", "|", "\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!", ) }
internal/config/tpl_filters.go
0.500488
0.513973
tpl_filters.go
starcoder
package proto import ( "time" ) // TimeSinceEpoch UTC time in seconds, counted from January 1, 1970. // To convert a time.Time to TimeSinceEpoch, for example: // proto.TimeSinceEpoch(time.Now().Unix()) // For session cookie, the value should be -1. type TimeSinceEpoch float64 // Time interface func (t TimeSinceEpoch) Time() time.Time { return (time.Unix(0, 0)).Add( time.Duration(t * TimeSinceEpoch(time.Second)), ) } // String interface func (t TimeSinceEpoch) String() string { return t.Time().String() } // MonotonicTime Monotonically increasing time in seconds since an arbitrary point in the past. type MonotonicTime float64 // Duration interface func (t MonotonicTime) Duration() time.Duration { return time.Duration(t * MonotonicTime(time.Second)) } // String interface func (t MonotonicTime) String() string { return t.Duration().String() } // Point from the origin (0, 0) type Point struct { X float64 `json:"x"` Y float64 `json:"y"` } // Len is the number of vertices func (q DOMQuad) Len() int { return len(q) / 2 } // Each point func (q DOMQuad) Each(fn func(pt Point, i int)) { for i := 0; i < q.Len(); i++ { fn(Point{q[i*2], q[i*2+1]}, i) } } // Center of the polygon func (q DOMQuad) Center() Point { var x, y float64 q.Each(func(pt Point, _ int) { x += pt.X y += pt.Y }) return Point{x / float64(q.Len()), y / float64(q.Len())} } // Area of the polygon // https://en.wikipedia.org/wiki/Polygon#Area func (q DOMQuad) Area() float64 { area := 0.0 l := len(q)/2 - 1 for i := 0; i < l; i++ { area += q[i*2]*q[i*2+3] - q[i*2+2]*q[i*2+1] } area += q[l*2]*q[1] - q[0]*q[l*2+1] return area / 2 } // OnePointInside the shape func (res *DOMGetContentQuadsResult) OnePointInside() *Point { for _, q := range res.Quads { if q.Area() >= 1 { pt := q.Center() return &pt } } return nil } // Box returns the smallest leveled rectangle that can cover the whole shape. func (res *DOMGetContentQuadsResult) Box() (box *DOMRect) { return Shape(res.Quads).Box() } // Shape is a list of DOMQuad type Shape []DOMQuad // Box returns the smallest leveled rectangle that can cover the whole shape. func (qs Shape) Box() (box *DOMRect) { if len(qs) == 0 { return } left := qs[0][0] top := qs[0][1] right := left bottom := top for _, q := range qs { q.Each(func(pt Point, _ int) { if pt.X < left { left = pt.X } if pt.Y < top { top = pt.Y } if pt.X > right { right = pt.X } if pt.Y > bottom { bottom = pt.Y } }) } box = &DOMRect{left, top, right - left, bottom - top} return } // MoveTo X and Y to x and y func (p *InputTouchPoint) MoveTo(x, y float64) { p.X = x p.Y = y } // CookiesToParams converts Cookies list to NetworkCookieParam list func CookiesToParams(cookies []*NetworkCookie) []*NetworkCookieParam { list := []*NetworkCookieParam{} for _, c := range cookies { list = append(list, &NetworkCookieParam{ Name: c.Name, Value: c.Value, Domain: c.Domain, Path: c.Path, Secure: c.Secure, HTTPOnly: c.HTTPOnly, SameSite: c.SameSite, Expires: c.Expires, Priority: c.Priority, }) } return list }
lib/proto/a_patch.go
0.848062
0.527012
a_patch.go
starcoder
package bitset type FixedBitSet struct { data []byte maxBits int } // Non-resizable bitset with basic operations. func NewFixed(maxBits int) *FixedBitSet { var bytes = maxBits / 8 if maxBits > bytes*8 { bytes++ } return &FixedBitSet{data: make([]byte, bytes), maxBits: maxBits} } // Write one at the given bit position. func (bs *FixedBitSet) Set(bit int) { bpos, shift := bs.position(bit) bs.data[bpos] |= 1 << shift } // Write zero at the given bit position. func (bs *FixedBitSet) Clear(bit int) { bpos, shift := bs.position(bit) bs.data[bpos] &^= 1 << shift } // Determine if given bit position was set. func (bs *FixedBitSet) Get(bit int) bool { bpos, shift := bs.position(bit) return bs.data[bpos]&(1<<shift) > 0 } // Return positions of all previously set bits. func (bs *FixedBitSet) Ones() []int { return bs.indexes(true) } // Return positions of all zero-bits in the bitset. func (bs *FixedBitSet) Zeros() []int { return bs.indexes(false) } // Return total number of ones in the bitset. func (bs *FixedBitSet) CountOnes() int { return bs.count(true) } // Return total number of zeros in the bitset. func (bs *FixedBitSet) CountZeros() int { return bs.count(false) } // Clear entire bitset. func (bs *FixedBitSet) Reset() { bs.data = make([]byte, len(bs.data)) } // Return size of underlying bytearray. func (bs *FixedBitSet) Size() int { return len(bs.data) } func (bs *FixedBitSet) position(bit int) (bytePos int, shift int) { if bit >= bs.maxBits || bit < 0 { panic("bit index out of range") } bytePos, shift = bit/8, bit%8 return } func (bs *FixedBitSet) indexes(ones bool) []int { var idxs = make([]int, 0, 1) for bit := 0; bit < bs.maxBits; bit++ { var bpos, shift = bit / 8, bit % 8 if ones == (bs.data[bpos]&(1<<shift) > 0) { idxs = append(idxs, bit) } } return idxs } func (bs *FixedBitSet) count(ones bool) int { var total int for bit := 0; bit < bs.maxBits; bit++ { var bpos, shift = bit / 8, bit % 8 if ones == (bs.data[bpos]&(1<<shift) > 0) { total++ } } return total }
bitset/fixed.go
0.757525
0.41947
fixed.go
starcoder
package main /* import ( "fmt" "github.com/hashicorp/terraform/dag" "math" "time" ) type largeVertex struct { value int } // implement the Vertex's interface method String() func (v largeVertex) String() string { return fmt.Sprintf("%d", v.value) } // implement the Vertex's interface method ID() func (v largeVertex) ID() string { return fmt.Sprintf("%d", v.value) } */ func main() { /* var d dag.AcyclicGraph root := d.Add(1) levels := 7 branches := 9 var start, end time.Time start = time.Now() largeAux(d, levels, branches, root) _ = d.Validate() end = time.Now() fmt.Printf("%fs to add %d vertices and %d edges\n", end.Sub(start).Seconds(), len(d.Vertices()), len(d.Edges())) expectedVertexCount := sum(0, levels-1, branches, pow) vertexCount := len(d.Vertices()) if vertexCount != expectedVertexCount { panic(fmt.Sprintf("GetVertices() = %d, want %d", vertexCount, expectedVertexCount)) } start = time.Now() descendants, _ := d.Descendents(root) end = time.Now() fmt.Printf("%fs to get descendants\n", end.Sub(start).Seconds()) descendantsCount := descendants.Len() expectedDescendantsCount := vertexCount - 1 if descendantsCount != expectedDescendantsCount { panic(fmt.Sprintf("GetDescendants(root) = %d, want %d", descendantsCount, expectedDescendantsCount)) } start = time.Now() _, _ = d.Descendents(root) end = time.Now() fmt.Printf("%fs to get descendants 2nd time\n", end.Sub(start).Seconds()) start = time.Now() d.TransitiveReduction() end = time.Now() fmt.Printf("%fs to transitively reduce the graph\n", end.Sub(start).Seconds()) */ } /* func largeAux(d dag.AcyclicGraph, level int, branches int, parent dag.Vertex) { if level > 1 { if branches < 1 || branches > 9 { panic("number of branches must be between 1 and 9") } for i := 1; i <= branches; i++ { value := parent.(int)*10 + i child := d.Add(value) d.Connect(dag.BasicEdge(child, parent)) largeAux(d, level-1, branches, child) } } } func sum(x, y, branches int, fn interface{}) int { if x > y { return 0 } f, ok := fn.(func(int, int) int) if !ok { panic("function no of correct tpye") } current := f(branches, x) rest := sum(x+1, y, branches, f) return current + rest } func pow(base int, exp int) int { pow := math.Pow(float64(base), float64(exp)) return int(pow) }*/
cmd/terraform/main.go
0.624064
0.45532
main.go
starcoder
package mario_go type Ground struct { Sprite sx float32 sy float32 } func NewGround() *Ground { s := &Ground{} return s } func (s Ground) Dots() Dots { var m int32 = 0x9B4808 var l int32 = 0xFECDC6 var b int32 = 0x000000 indices := []int32{ 0, 15, m, 1, 15, l, 2, 15, l, 3, 15, l, 4, 15, l, 5, 15, l, 6, 15, l, 7, 15, l, 8, 15, l, 9, 15, l, 10, 15, b, 11, 15, m, 12, 15, l, 13, 15, l, 14, 15, l, 15, 15, m, 0, 14, l, 1, 14, m, 2, 14, m, 3, 14, m, 4, 14, m, 5, 14, m, 6, 14, m, 7, 14, m, 8, 14, m, 9, 14, m, 10, 14, b, 11, 14, l, 12, 14, m, 13, 14, m, 14, 14, m, 15, 14, b, 0, 13, l, 1, 13, m, 2, 13, m, 3, 13, m, 4, 13, m, 5, 13, m, 6, 13, m, 7, 13, m, 8, 13, m, 9, 13, m, 10, 13, b, 11, 13, l, 12, 13, m, 13, 13, m, 14, 13, m, 15, 13, b, 0, 12, l, 1, 12, m, 2, 12, m, 3, 12, m, 4, 12, m, 5, 12, m, 6, 12, m, 7, 12, m, 8, 12, m, 9, 12, m, 10, 12, b, 11, 12, l, 12, 12, m, 13, 12, m, 14, 12, m, 15, 12, b, 0, 11, l, 1, 11, m, 2, 11, m, 3, 11, m, 4, 11, m, 5, 11, m, 6, 11, m, 7, 11, m, 8, 11, m, 9, 11, m, 10, 11, b, 11, 11, l, 12, 11, b, 13, 11, m, 14, 11, m, 15, 11, b, 0, 10, l, 1, 10, m, 2, 10, m, 3, 10, m, 4, 10, m, 5, 10, m, 6, 10, m, 7, 10, m, 8, 10, m, 9, 10, m, 10, 10, b, 11, 10, m, 12, 10, b, 13, 10, b, 14, 10, b, 15, 10, m, 0, 9, l, 1, 9, m, 2, 9, m, 3, 9, m, 4, 9, m, 5, 9, m, 6, 9, m, 7, 9, m, 8, 9, m, 9, 9, m, 10, 9, b, 11, 9, l, 12, 9, l, 13, 9, l, 14, 9, l, 15, 9, b, 0, 8, l, 1, 8, m, 2, 8, m, 3, 8, m, 4, 8, m, 5, 8, m, 6, 8, m, 7, 8, m, 8, 8, m, 9, 8, m, 10, 8, b, 11, 8, l, 12, 8, m, 13, 8, m, 14, 8, m, 15, 8, b, 0, 7, l, 1, 7, m, 2, 7, m, 3, 7, m, 4, 7, m, 5, 7, m, 6, 7, m, 7, 7, m, 8, 7, m, 9, 7, m, 10, 7, b, 11, 7, l, 12, 7, m, 13, 7, m, 14, 7, m, 15, 7, b, 0, 6, l, 1, 6, m, 2, 6, m, 3, 6, m, 4, 6, m, 5, 6, m, 6, 6, m, 7, 6, m, 8, 6, m, 9, 6, m, 10, 6, b, 11, 6, l, 12, 6, m, 13, 6, m, 14, 6, m, 15, 6, b, 0, 5, b, 1, 5, b, 2, 5, m, 3, 5, m, 4, 5, m, 5, 5, m, 6, 5, m, 7, 5, m, 8, 5, m, 9, 5, b, 10, 5, l, 11, 5, m, 12, 5, m, 13, 5, m, 14, 5, m, 15, 5, b, 0, 4, l, 1, 4, l, 2, 4, b, 3, 4, b, 4, 4, m, 5, 4, m, 6, 4, m, 7, 4, m, 8, 4, m, 9, 4, b, 10, 4, l, 11, 4, m, 12, 4, m, 13, 4, m, 14, 4, m, 15, 4, b, 0, 3, l, 1, 3, m, 2, 3, l, 3, 3, l, 4, 3, b, 5, 3, b, 6, 3, b, 7, 3, b, 8, 3, l, 9, 3, m, 10, 3, m, 11, 3, m, 12, 3, m, 13, 3, m, 14, 3, m, 15, 3, b, 0, 2, l, 1, 2, m, 2, 2, m, 3, 2, m, 4, 2, l, 5, 2, l, 6, 2, l, 7, 2, b, 8, 2, l, 9, 2, m, 10, 2, m, 11, 2, m, 12, 2, m, 13, 2, m, 14, 2, m, 15, 2, b, 0, 1, l, 1, 1, m, 2, 1, m, 3, 1, m, 4, 1, m, 5, 1, m, 6, 1, m, 7, 1, b, 8, 1, l, 9, 1, m, 10, 1, m, 11, 1, m, 12, 1, m, 13, 1, m, 14, 1, b, 15, 1, b, 0, 0, m, 1, 0, b, 2, 0, b, 3, 0, b, 4, 0, b, 5, 0, b, 6, 0, b, 7, 0, m, 8, 0, l, 9, 0, b, 10, 0, b, 11, 0, b, 12, 0, b, 13, 0, b, 14, 0, b, 15, 0, m, } return MakeDots(indices) } func (s Ground) Width() int { return 16 } func (s Ground) Height() int { return 16 }
ground.go
0.569374
0.491944
ground.go
starcoder
package recordio import ( "fmt" "io" "io/fs" "strings" ) // DecoderIterator is an iterator over Decoders, for use with the MultiDecoder. type DecoderIterator interface { io.Closer Next() (*Decoder, error) Done() bool } // MultiDecoder wraps multiple readers, either specified directly or through a // reader iterator interface that can produce them on demanad. This is useful // when concatenating multiple file shards together as a single record store. type MultiDecoder struct { readers []*Decoder readerIter DecoderIterator reader *Decoder prevConsumed int64 } // NewMultiDecoder creates a MultiDecoder from a slice of readers. These are // ordered, and will be consumed in the order given. func NewMultiDecoder(readers []*Decoder) *MultiDecoder { return &MultiDecoder{ readers: readers, } } // NewMultiDecoderIter creates a MultiDecoder where each reader is requested, one // at a time, through the given reader-returning function. The function is // expected to return a nil Decoder if there are no more readers. func NewMultiDecoderIter(ri DecoderIterator) *MultiDecoder { return &MultiDecoder{ readerIter: ri, } } // ensureDecoder makes sure that there is a current reader available that isn't // exhausted, if possible. func (d *MultiDecoder) ensureDecoder() error { // Current and not exhausted. if d.reader != nil { if !d.reader.Done() { return nil } // Exhausted, close it and remember how much it consumed. d.prevConsumed += d.reader.Consumed() d.reader.Close() d.reader = nil } // If we get here, the reader is either nil or finished. Create a new one. // Try the function. if d.readerIter != nil && !d.readerIter.Done() { var err error if d.reader, err = d.readerIter.Next(); err != nil { return fmt.Errorf("ensure reader: %w", err) } return nil } // Try the list. if len(d.readers) == 0 { return io.EOF } d.reader = d.readers[0] d.readers = d.readers[1:] return nil } // Consumed returns the total number of bytes consumed thus far. func (d *MultiDecoder) Consumed() int64 { if d.reader != nil { return d.prevConsumed + d.reader.Consumed() } return d.prevConsumed } // Next gets the next record for these readers. func (d *MultiDecoder) Next() ([]byte, error) { if err := d.ensureDecoder(); err != nil { return nil, fmt.Errorf("multi next: %w", err) } b, err := d.reader.Next() if err != nil { return nil, fmt.Errorf("multi next: %w", err) } return b, nil } // Done returns whether this multi reader has exhausted all underlying readers. func (d *MultiDecoder) Done() bool { if d.readerIter == nil && len(d.readers) == 0 { return true } // Current reader, not exhausted. if d.reader != nil && !d.reader.Done() { return false } // Not finished with the list. if len(d.readers) != 0 { return false } // Not finished with the reader iterator. if d.readerIter != nil && !d.readerIter.Done() { return false } return true } // Close closes the currently busy underlying reader and reader iterator, if any. func (d *MultiDecoder) Close() error { defer func() { d.reader = nil d.readers = nil d.readerIter = nil }() var msgs []string if err := d.readerIter.Close(); err != nil { msgs = append(msgs, err.Error()) } if err := d.reader.Close(); err != nil { msgs = append(msgs, err.Error()) } for _, reader := range d.readers { if err := reader.Close(); err != nil { msgs = append(msgs, err.Error()) } } if len(msgs) == 0 { return nil } return fmt.Errorf("wal dir close: %v", strings.Join(msgs, " :: ")) } // FilesDecoderIterator is an iterator over readers based on a list of file names. type FilesDecoderIterator struct { fsys fs.FS names []string file io.ReadCloser nextName int } // NewFilesDecoderIterator creates a new iterator from a list of file names. func NewFilesDecoderIterator(fsys fs.FS, names []string) *FilesDecoderIterator { return &FilesDecoderIterator{ names: names, fsys: fsys, } } // Next returns a new reader if possible, or io.EOF. func (d *FilesDecoderIterator) Next() (*Decoder, error) { if d.Done() { return nil, io.EOF } defer func() { d.nextName++ }() if d.file != nil { d.file.Close() } fname := d.names[d.nextName] f, err := d.fsys.Open(fname) if err != nil { return nil, fmt.Errorf("next reader file: %w", err) } d.file = f return NewDecoder(f), nil } // Done returns true iff there are no more readers to produce. func (d *FilesDecoderIterator) Done() bool { return d.nextName >= len(d.names) } // Close closes the last file, if there is one open, and makes this return io.EOF ever after. func (d *FilesDecoderIterator) Close() error { d.nextName = len(d.names) if d.file != nil { return d.file.Close() } return nil }
recordio/multi.go
0.679179
0.431464
multi.go
starcoder
package obj7 type LightType int const ( LightType_Other LightType = 0 LightType_RedNavigation LightType = 1 LightType_GreenNavigation LightType = 2 LightType_Beacon LightType = 3 LightType_Strobe LightType = 4 LightType_Landing LightType = 5 LightType_Taxi LightType = 6 ) type LightInfo struct { XYZ [3]float32 RGB [3]int LightType LightType RGB_Float [4]float32 } var ( NavLightRedColor = [4]float32{1.0, 0.0, 0.2, 0.5} NavLightGreenColor = [4]float32{0.0, 1.0, 0.3, 0.5} LandingLightColor = [4]float32{1.0, 1.0, 0.7, 0.6} StrobeLightColor = [4]float32{1.0, 1.0, 1.0, 0.7} ) func NewLightInfo(vrgb VecRGB) *LightInfo { result := &LightInfo{} result.XYZ[0] = vrgb.V[0] result.XYZ[1] = vrgb.V[1] result.XYZ[2] = vrgb.V[2] result.RGB[0] = int(vrgb.RGB[0]) result.RGB[1] = int(vrgb.RGB[1]) result.RGB[2] = int(vrgb.RGB[2]) result.LightType = result.buildType() result.RGB_Float = result.buildFloatColor() return result } func (self *LightInfo) buildType() LightType { if self.RGB[0] == 11 && self.RGB[1] == 11 && self.RGB[2] == 11 { return LightType_RedNavigation } if self.RGB[0] == 22 && self.RGB[1] == 22 && self.RGB[2] == 22 { return LightType_GreenNavigation } if self.RGB[0] == 33 && self.RGB[1] == 33 && self.RGB[2] == 33 { return LightType_Beacon } if self.RGB[0] == 44 && self.RGB[1] == 44 && self.RGB[2] == 44 { return LightType_Strobe } if self.RGB[0] == 55 && self.RGB[1] == 55 && self.RGB[2] == 55 { return LightType_Landing } if self.RGB[0] == 66 && self.RGB[1] == 66 && self.RGB[2] == 66 { return LightType_Taxi } return LightType_Other } func (self *LightInfo) buildFloatColor() [4]float32 { switch self.LightType { case LightType_RedNavigation, LightType_Beacon: return NavLightRedColor case LightType_GreenNavigation: return NavLightGreenColor case LightType_Strobe: return StrobeLightColor case LightType_Landing: return LandingLightColor default: return [4]float32{float32(self.RGB[0]) * 0.1, float32(self.RGB[1]) * 0.1, float32(self.RGB[2]) * 0.1, 0.0} } }
internal/obj7/LightInfo.go
0.67405
0.431584
LightInfo.go
starcoder
package goval import ( "bytes" "strconv" "github.com/shunsukuda/forceconv" ) type Bytes struct { Bytes []byte } // func (e Bytes) GoBytes() []byte { return e.Bytes } func (e Bytes) Type() Type { return ValTypes.Bytes } func (e Bytes) Equal(x Bytes) bool { return bytes.Equal(e.Bytes, x.Bytes) } func (e Bytes) IsZero() bool { return e.Len() == 0 } func (e Bytes) Len() int { return len(e.Bytes) } func (e Bytes) ToInt8() Int8 { return e.ToString().ToInt8() } func (e Bytes) ToInt16() Int16 { return e.ToString().ToInt16() } func (e Bytes) ToInt32() Int32 { return e.ToString().ToInt32() } func (e Bytes) ToInt64() Int64 { return e.ToString().ToInt64() } func (e Bytes) ToUint8() Uint8 { return e.ToString().ToUint8() } func (e Bytes) ToUint16() Uint16 { return e.ToString().ToUint16() } func (e Bytes) ToUint32() Uint32 { return e.ToString().ToUint32() } func (e Bytes) ToUint64() Uint64 { return e.ToString().ToUint64() } func (e Bytes) ToFloat32() Float32 { return e.ToString().ToFloat32() } func (e Bytes) ToFloat64() Float64 { return e.ToString().ToFloat64() } func (e Bytes) ToComplex64() Complex64 { return e.ToString().ToComplex64() } func (e Bytes) ToComplex128() Complex128 { return e.ToString().ToComplex128() } func (e Bytes) ToBool() Bool { return e.ToString().ToBool() } func (e Bytes) ToString() String { return String{forceconv.BytesToString(e.Bytes)} } func (e Bytes) ToBytes() Bytes { return e } type String struct { String string } // func (e String) GoString() string { return e.String } func (e String) Type() Type { return ValTypes.String } func (e String) Equal(x String) bool { return e.String == x.String } func (e String) IsZero() bool { return e.Len() == 0 } func (e String) Len() int { return len(e.String) } func (e String) ToInt8() Int8 { ce, _ := strconv.ParseInt(e.String, 0, 8) return Int8{int8(ce)} } func (e String) ToInt16() Int16 { ce, _ := strconv.ParseInt(e.String, 0, 16) return Int16{int16(ce)} } func (e String) ToInt32() Int32 { ce, _ := strconv.ParseInt(e.String, 0, 32) return Int32{int32(ce)} } func (e String) ToInt64() Int64 { ce, _ := strconv.ParseInt(e.String, 0, 64) return Int64{int64(ce)} } func (e String) ToUint8() Uint8 { ce, _ := strconv.ParseUint(e.String, 0, 8) return Uint8{uint8(ce)} } func (e String) ToUint16() Uint16 { ce, _ := strconv.ParseUint(e.String, 0, 16) return Uint16{uint16(ce)} } func (e String) ToUint32() Uint32 { ce, _ := strconv.ParseUint(e.String, 0, 32) return Uint32{uint32(ce)} } func (e String) ToUint64() Uint64 { ce, _ := strconv.ParseUint(e.String, 0, 64) return Uint64{uint64(ce)} } func (e String) ToFloat32() Float32 { ce, _ := strconv.ParseFloat(e.String, 0) return Float32{float32(ce)} } func (e String) ToFloat64() Float64 { ce, _ := strconv.ParseFloat(e.String, 0) return Float64{float64(ce)} } func (e String) ToComplex64() Complex64 { ce, _ := strconv.ParseComplex(e.String, 0) return Complex64{complex64(ce)} } func (e String) ToComplex128() Complex128 { ce, _ := strconv.ParseComplex(e.String, 0) return Complex128{complex128(ce)} } func (e String) ToBool() Bool { ce, _ := strconv.ParseBool(e.String) return Bool{ce} } func (e String) ToString() String { return e } func (e String) ToBytes() Bytes { return Bytes{forceconv.StringToBytes(e.String)} }
string.gen.go
0.730482
0.567218
string.gen.go
starcoder
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // PathArrayFromFloat64Array2SliceSlice returns a driver.Valuer that produces a PostgreSQL path[] from the given Go [][][2]float64. func PathArrayFromFloat64Array2SliceSlice(val [][][2]float64) driver.Valuer { return pathArrayFromFloat64Array2SliceSlice{val: val} } // PathArrayToFloat64Array2SliceSlice returns an sql.Scanner that converts a PostgreSQL path[] into a Go [][][2]float64 and sets it to val. func PathArrayToFloat64Array2SliceSlice(val *[][][2]float64) sql.Scanner { return pathArrayToFloat64Array2SliceSlice{val: val} } type pathArrayFromFloat64Array2SliceSlice struct { val [][][2]float64 } func (v pathArrayFromFloat64Array2SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } size := (len(v.val) * 4) + // len(`"[]"`) == len(`NULL`) == 4 (len(v.val) - 1) + // number of commas between elements 2 // surrounding parentheses for i := 0; i < len(v.val); i++ { if v.val[i] != nil { size += (len(v.val[i]) * 5) + // len(`(x,y)`) (len(v.val[i]) - 1) // number of commas between points } } out := make([]byte, 1, size) out[0] = '{' for i := 0; i < len(v.val); i++ { if v.val[i] == nil { out = append(out, 'N', 'U', 'L', 'L', ',') continue } out = append(out, '"', '[') for j := 0; j < len(v.val[i]); j++ { out = append(out, '(') out = strconv.AppendFloat(out, v.val[i][j][0], 'f', -1, 64) out = append(out, ',') out = strconv.AppendFloat(out, v.val[i][j][1], 'f', -1, 64) out = append(out, ')', ',') } out[len(out)-1] = ']' out = append(out, '"', ',') } out[len(out)-1] = '}' return out, nil } type pathArrayToFloat64Array2SliceSlice struct { val *[][][2]float64 } func (v pathArrayToFloat64Array2SliceSlice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { *v.val = nil return nil } elems := pgParsePathArray(data) polygons := make([][][2]float64, len(elems)) for i := 0; i < len(elems); i++ { if elems[i] == nil { continue } polygon := make([][2]float64, len(elems[i])) for j := 0; j < len(elems[i]); j++ { f0, err := strconv.ParseFloat(string(elems[i][j][0]), 64) if err != nil { return err } f1, err := strconv.ParseFloat(string(elems[i][j][1]), 64) if err != nil { return err } polygon[j][0] = f0 polygon[j][1] = f1 } polygons[i] = polygon } *v.val = polygons return nil }
pgsql/patharr.go
0.677047
0.498047
patharr.go
starcoder
package gogm import ( "fmt" "math" ) // Vec3 is a vector with 3 components, of type T. type Vec3[T number] [3]T // Vec3CopyVec3 copies the content of src to dst. func Vec3CopyVec3[T1, T2 number](dst *Vec3[T1], src *Vec3[T2]) { dst[0] = T1(src[0]) dst[1] = T1(src[1]) dst[2] = T1(src[2]) } // Vec3CopyVec2 copies the content of src to dst. func Vec3CopyVec2[T1, T2 number](dst *Vec3[T1], src *Vec2[T2]) { dst[0] = T1(src[0]) dst[1] = T1(src[1]) } // Vec3CopyVec4 copies the content of src to dst. func Vec3CopyVec4[T1, T2 number](dst *Vec3[T1], src *Vec4[T2]) { dst[0] = T1(src[0]) dst[1] = T1(src[1]) dst[2] = T1(src[2]) } // String returns a string representation of the vector. func (v1 *Vec3[T]) String() string { return fmt.Sprintf("{%v, %v, %v}", v1[0], v1[1], v1[2]) } // Len returns the length of the vector. func (v1 *Vec3[T]) Len() float64 { return math.Sqrt(math.Pow(float64(v1[0]), 2) + math.Pow(float64(v1[1]), 2) + math.Pow(float64(v1[2]), 2)) } // Normalize normalizes v2, and stores the result in v1. func (v1 *Vec3[T]) Normalize(v2 *Vec3[T]) { l := T(v2.Len()) v1[0] = v2[0] / l v1[1] = v2[1] / l v1[2] = v2[2] / l } // Inverse sets v1 to the inverse of v2. // v1 = -v2 func (v1 *Vec3[T]) Inverse(v2 *Vec3[T]) { v1[0] = -v2[0] v1[1] = -v2[1] v1[2] = -v2[2] } // Add adds v2 with v3 component-wise, and stores the result in v1. // v1 = v2 + v3 func (v1 *Vec3[T]) Add(v2 *Vec3[T], v3 *Vec3[T]) { v1[0] = v2[0] + v3[0] v1[1] = v2[1] + v3[1] v1[2] = v2[2] + v3[2] } // Sub subtracts v2 from v3 component-wise, and stores the result in v1. // v1 = v2 - v3 func (v1 *Vec3[T]) Sub(v2 *Vec3[T], v3 *Vec3[T]) { v1[0] = v2[0] - v3[0] v1[1] = v2[1] - v3[1] v1[2] = v2[2] - v3[2] } // Mul multiplies v2 with v3 component-wise, and stores the result in v1. // v1 = v2 * v3 func (v1 *Vec3[T]) Mul(v2 *Vec3[T], v3 *Vec3[T]) { v1[0] = v2[0] * v3[0] v1[1] = v2[1] * v3[1] v1[2] = v2[2] * v3[2] } // Div divides v2 by v3 component-wise, and stores the result in v1. // v1 = v2 / v3 func (v1 *Vec3[T]) Div(v2 *Vec3[T], v3 *Vec3[T]) { v1[0] = v2[0] / v3[0] v1[1] = v2[1] / v3[1] v1[2] = v2[2] / v3[2] } // AddS adds each component of v2 with s, and stores the result in v1. // v1 = v2 + s func (v1 *Vec3[T]) AddS(v2 *Vec3[T], s T) { v1[0] = v2[0] + s v1[1] = v2[1] + s v1[2] = v2[2] + s } // SubS subtracts each component of v2 by s, and stores the result in v1. // v1 = v2 - s func (v1 *Vec3[T]) SubS(v2 *Vec3[T], s T) { v1[0] = v2[0] - s v1[1] = v2[1] - s v1[2] = v2[2] - s } // MulS multiplies each component of v2 with s, and stores the result in v1. // v1 = v2 * s func (v1 *Vec3[T]) MulS(v2 *Vec3[T], s T) { v1[0] = v2[0] * s v1[1] = v2[1] * s v1[2] = v2[2] * s } // DivS divides each component of v2 by s, and stores the result in v1. // v1 = v2 / s func (v1 *Vec3[T]) DivS(v2 *Vec3[T], s T) { v1[0] = v2[0] / s v1[1] = v2[1] / s v1[2] = v2[2] / s } // Cross takes the cross product of v1 and v2, and stores the result in v1. // v1 = v2 x v3 func (v1 *Vec3[T]) Cross(v2 *Vec3[T], v3 *Vec3[T]) { v1[0], v1[1], v1[2] = v2[1]*v3[2]-v3[1]*v2[2], v2[2]*v3[0]-v3[2]*v2[0], v2[0]*v3[1]-v3[0]*v2[1] } // CrossFast takes the cross product of v1 and v2, and stores the result in v1. // v1 = v2 x v3 func (v1 *Vec3[T]) CrossFast(v2 *Vec3[T], v3 *Vec3[T]) { v1[0] = v2[1]*v3[2] - v3[1]*v2[2] v1[1] = v2[2]*v3[0] - v3[2]*v2[0] v1[2] = v2[0]*v3[1] - v3[0]*v2[1] } // Dot takes the dot product of v1 and v2, and returns the result. func (v1 *Vec3[T]) Dot(v2 *Vec3[T]) T { return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] }
vec3.go
0.718792
0.565299
vec3.go
starcoder
package util import "math" func Div(num, denom int32) (uint32, uint32, uint32) { const I32_MIN = -2147483647 - 1 if denom == 0 { // If abs(num) > 1, this should hang, but that would be painful to // emulate in HLE, and no game will get into a state under normal // operation where it hangs... if num < 0 { return uint32(0xffff_ffff), uint32(num), 1 } return 1, uint32(num), 1 } else if denom == -1 && num == I32_MIN { return 0x8000_0000, 0, 0x8000_0000 } else { result := num / denom mod := num % denom return uint32(result), uint32(mod), uint32(math.Abs(float64(result))) } } func Sqrt(x uint32) uint32 { if x == 0 { return 0 } lower, upper, bound := uint32(0), x, uint32(1) for bound < upper { upper >>= 1 bound <<= 1 } for { upper = x accum := uint32(0) lower = bound for { oldLower := lower if lower <= upper>>1 { lower <<= 1 } if oldLower >= upper>>1 { break } } for { accum <<= 1 if upper >= lower { accum++ upper -= lower } if lower == bound { break } lower >>= 1 } oldBound := bound bound += accum bound >>= 1 if bound >= oldBound { bound = oldBound break } } return bound } func ArcTan(i int32) (uint32, uint32, uint32) { a := -(int32(i*i) >> 14) b := (int32(0xa9*a) >> 14) + 0x390 b = ((b * a) >> 14) + 0x91c b = ((b * a) >> 14) + 0xfb6 b = ((b * a) >> 14) + 0x16aa b = ((b * a) >> 14) + 0x2081 b = ((b * a) >> 14) + 0x3651 b = ((b * a) >> 14) + 0xa2f9 r0, r1, r3 := int32(i*b)>>16, a, b return uint32(r0), uint32(r1), uint32(r3) } func ArcTan2(x, y int32) (uint32, uint32) { if y == 0 { if x >= 0 { return 0, 0 } return 0x8000, 0 } if x == 0 { if y >= 0 { return 0x4000, uint32(y) } return 0xc000, uint32(y) } if y >= 0 { if x >= 0 { if x >= y { r0, r1, _ := ArcTan((y << 14) / x) return r0, r1 } } else if -x >= y { r0, r1, _ := ArcTan((y << 14) / x) return r0 + 0x8000, r1 } r0, r1, _ := ArcTan((x << 14) / y) return 0x4000 - r0, r1 } else { if x <= 0 { if -x > -y { r0, r1, _ := ArcTan((y << 14) / x) return r0 + 0x8000, r1 } } else if x >= -y { r0, r1, _ := ArcTan((y << 14) / x) return r0 + 0x10000, r1 } r0, r1, _ := ArcTan((x << 14) / y) return 0xc000 - r0, r1 } }
pkg/util/bios.go
0.581303
0.515315
bios.go
starcoder
package data import "bytes" type ( // Sequence interfaces expose a lazily resolved sequence Sequence interface { Value First() Value Rest() Sequence Split() (Value, Sequence, bool) IsEmpty() bool } // Appender is a Sequence that can be appended to Appender interface { Sequence Append(Value) Sequence } // Mapper is a Sequence that provides a mutable Mapped interface Mapper interface { Sequence Mapped Put(Pair) Sequence Remove(Value) (Value, Sequence, bool) } // Prepender is a Sequence that can be prepended to Prepender interface { Sequence Prepend(Value) Sequence } // Reverser is a Sequence than can be reversed Reverser interface { Sequence Reverse() Sequence } // RandomAccess provides a Sequence that supports random access RandomAccess interface { Sequence Indexed Counted } // IndexedSequence is a Sequence that has indexed elements IndexedSequence interface { Sequence Indexed } // CountedSequence is a Sequence that returns a count of its items CountedSequence interface { Sequence Counted } // ValuerSequence is a Sequence that returns its data as a slice of Values ValuerSequence interface { Sequence Valuer } ) // MakeSequenceStr converts a Sequence to a String func MakeSequenceStr(s Sequence) string { f, r, ok := s.Split() if !ok { return "()" } var b bytes.Buffer b.WriteString("(") b.WriteString(MaybeQuoteString(f)) for f, r, ok = r.Split(); ok; f, r, ok = r.Split() { b.WriteString(" ") b.WriteString(MaybeQuoteString(f)) } b.WriteString(")") return b.String() } // Last returns the final element of a Sequence, possibly by scanning func Last(s Sequence) (Value, bool) { if s.IsEmpty() { return Nil, false } if i, ok := s.(RandomAccess); ok { return i.ElementAt(i.Count() - 1) } var res Value var lok bool for f, s, ok := s.Split(); ok; f, s, ok = s.Split() { res = f lok = ok } return res, lok } func indexedCall(s IndexedSequence, args []Value) Value { idx := args[0].(Integer) res, ok := s.ElementAt(int(idx)) if !ok && len(args) > 1 { return args[1] } return res } func mappedCall(m Mapper, args []Value) Value { res, ok := m.Get(args[0]) if !ok && len(args) > 1 { return args[1] } return res }
data/sequence.go
0.778186
0.455078
sequence.go
starcoder
package jbtracer import "math" const ( Axis_X = iota Axis_Y Axis_Z Degrees180 = 3.1415926536 // pi Degrees90 = 1.5707963268 // pi/2 Degrees60 = 1.0471975512 // pi/3 Degrees45 = 0.7853981634 // pi/4 Degrees30 = 0.5235987756 // pi/6 Degrees10 = 0.1745329252 // pi/18 Pi = 3.1415926536 // pi Pi2 = 1.5707963268 // pi/2 Pi3 = 1.0471975512 // pi/3 Pi4 = 0.7853981634 // pi/4 Pi6 = 0.5235987756 // pi/6 Pi18 = 0.1745329252 // pi/18 ) // Translation returns a translation matrix for vector(x, y, z) func Translation(x, y, z float64) *Matrix { a := IdentityMatrix() a.Set(0, 3, x) a.Set(1, 3, y) a.Set(2, 3, z) return a } // Scaling returns a scaling matrix for vector(x, y, z) func Scaling(x, y, z float64) *Matrix { a := IdentityMatrix() a.Set(0, 0, x) a.Set(1, 1, y) a.Set(2, 2, z) return a } // Rotation returns the rotation matrix around the x, y, or z axis by // the provided radians func Rotation(axis int, radians float64) *Matrix { a := IdentityMatrix() sin := math.Sin(radians) cos := math.Cos(radians) switch axis { case Axis_X: a.Set(1, 1, cos) a.Set(1, 2, -1*sin) a.Set(2, 1, sin) a.Set(2, 2, cos) case Axis_Y: a.Set(0, 0, cos) a.Set(0, 2, sin) a.Set(2, 0, -1*sin) a.Set(2, 2, cos) case Axis_Z: a.Set(0, 0, cos) a.Set(0, 1, -1*sin) a.Set(1, 0, sin) a.Set(1, 1, cos) } return a } // Shearing returns the shearing matrix func Shearing(xY, xZ, yX, yZ, zX, zY float64) *Matrix { a := IdentityMatrix() a.Set(0, 1, xY) a.Set(0, 2, xZ) a.Set(1, 0, yX) a.Set(1, 2, yZ) a.Set(2, 0, zX) a.Set(2, 1, zY) return a } // ViewTransform returns the tranformation matrix that orients the world relative to the // eye func ViewTransform(from, to, up *Tuple) *Matrix { forward := to.Subtract(from).Normalize() upn := up.Normalize() left := forward.Cross(upn) trueUp := left.Cross(forward) orientation := IdentityMatrix() orientation.Set(0, 0, left.X) orientation.Set(0, 1, left.Y) orientation.Set(0, 2, left.Z) orientation.Set(1, 0, trueUp.X) orientation.Set(1, 1, trueUp.Y) orientation.Set(1, 2, trueUp.Z) orientation.Set(2, 0, -1*forward.X) orientation.Set(2, 1, -1*forward.Y) orientation.Set(2, 2, -1*forward.Z) return orientation.Multiply(Translation(-1*from.X, -1*from.Y, -1*from.Z)) }
transformations.go
0.832509
0.619644
transformations.go
starcoder
// TODO: How exactly are sensitivity and delta related to each other? How does the // inclusion of delta in this scheme change these calculations? package wdp import "math" // Provide a qualitative explanation for what a particular epsilon value means. func QualEps(eps, p float64) float64 { // Recommended description: // If someone believed a user was in the data with probability p, // then at most after seeing the data they will be qual_eps(eps, p) certain // (assuming the sensitivity value is correct). // e.g., for eps=1; p=0.5, they'd go from 50% certainty to at most 73.1% certainty. // Parameters: // eps: epsilon value that quantifies "privacy" level of differential privacy. // p: initial belief that a given user is in the data -- e.g.,: // 0.5 represents complete uncertainty (50/50 chance) // 0.01 represents high certainty the person isn't in the data // 0.99 represents high certainty the person is in the data if p > 0 && p < 1 { return (math.Exp(eps) * p) / (1 + ((math.Exp(eps) - 1) * p)) } else { return -1 } } func AggregationThreshold(sensitivity int, eps, alpha, propWithin float64) float64 { // Same as doAggregate but determines threshold where data is deemed 'too noisy'. var rank = alpha / 2 var lbda = float64(sensitivity) / eps // get confidence interval; this is symmetric where `lower bound = noisedX - ci` and `upper bound = noisedX + ci` var ci = math.Abs(lbda * math.Log(2*rank)) return math.Ceil(ci / propWithin) } func DoAggregate(noisedX, sensitivity int, eps, alpha, propWithin float64) int { // Check whether noisy data X is at least (100 * alpha)% of being within Y% of true value. // Doesn't use true value (only noisy value and parameters) so no privacy cost to this. // Should identify in advance what threshold -- e.g., 50% probability within 25% of actual value -- in advance // to determine whether to keep the data or suppress it until it can be further aggregated so more signal to noise. // See a more complete description in the paper below for how to effectively use this data. // Based on: // * Description: https://arxiv.org/pdf/2009.01265.pdf#section.4 // * Code: https://github.com/google/differential-privacy/blob/main/java/main/com/google/privacy/differentialprivacy/LaplaceNoise.java#L127 // Parameters: // noisedX: the count after adding Laplace noise // sensitivity: L1 sensitivity for Laplace // eps: selected epsilon value // alpha: how confident (0.5 = 50%; 0.1 = 90%) should we be that the noisy data is within (100 * prop_within)% of the true data? // prop_within: how close (0.25 = 25%) to actual value should we expect the noisy data to be? // Divide alpha by 2 because two-tailed var rank = alpha / 2 var lbda = float64(sensitivity) / eps // get confidence interval; this is symmetric where `lower bound = noisedX - ci` and `upper bound = noisedX + ci` var ci = math.Abs(float64(lbda) * math.Log(2*rank)) if ci > (propWithin * float64(noisedX)) { return 1 } else { return 0 } }
wdp/math.go
0.717012
0.733857
math.go
starcoder
package scw import ( "encoding/json" "fmt" "io" "time" "github.com/scaleway/scaleway-sdk-go/internal/errors" ) // ServiceInfo contains API metadata // These metadata are only here for debugging. Do not rely on these values type ServiceInfo struct { // Name is the name of the API Name string `json:"name"` // Description is a human readable description for the API Description string `json:"description"` // Version is the version of the API Version string `json:"version"` // DocumentationUrl is the a web url where the documentation of the API can be found DocumentationUrl *string `json:"documentation_url"` } // File is the structure used to receive / send a file from / to the API type File struct { // Name of the file Name string `json:"name"` // ContentType used in the HTTP header `Content-Type` ContentType string `json:"content_type"` // Content of the file Content io.Reader `json:"content"` } // Money represents an amount of money with its currency type. type Money struct { // CurrencyCode is the 3-letter currency code defined in ISO 4217. CurrencyCode string `json:"currency_code,omitempty"` // Units is the whole units of the amount. // For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. Units int64 `json:"units,omitempty"` // Nanos is the number of nano (10^-9) units of the amount. // The value must be between -999,999,999 and +999,999,999 inclusive. // If `units` is positive, `nanos` must be positive or zero. // If `units` is zero, `nanos` can be positive, zero, or negative. // If `units` is negative, `nanos` must be negative or zero. // For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. Nanos int32 `json:"nanos,omitempty"` } // NewMoneyFromFloat conerts a float with currency to a Money object. func NewMoneyFromFloat(value float64, currency string) *Money { return &Money{ CurrencyCode: currency, Units: int64(value), Nanos: int32((value - float64(int64(value))) * 1000000000), } } // ToFloat converts a Money object to a float. func (m *Money) ToFloat() float64 { return float64(m.Units) + float64(m.Nanos)/1000000000 } // Money represents a size in bytes. type Size uint64 const ( B Size = 1 KB = 1000 * B MB = 1000 * KB GB = 1000 * MB TB = 1000 * GB PB = 1000 * TB ) // String returns the string representation of a Size. func (s Size) String() string { return fmt.Sprintf("%d", s) } // TimeSeries represents a time series that could be used for graph purposes. type TimeSeries struct { // Name of the metric. Name string `json:"name"` // Points contains all the points that composed the series. Points []*TimeSeriesPoint `json:"points"` // Metadata contains some string metadata related to a metric. Metadata map[string]string `json:"metadata"` } // TimeSeriesPoint represents a point of a time series. type TimeSeriesPoint struct { Timestamp time.Time Value float32 } func (tsp *TimeSeriesPoint) MarshalJSON() ([]byte, error) { timestamp := tsp.Timestamp.Format(time.RFC3339) value, err := json.Marshal(tsp.Value) if err != nil { return nil, err } return []byte(`["` + timestamp + `",` + string(value) + "]"), nil } func (tsp *TimeSeriesPoint) UnmarshalJSON(b []byte) error { point := [2]interface{}{} err := json.Unmarshal(b, &point) if err != nil { return err } if len(point) != 2 { return errors.New("invalid point array") } strTimestamp, isStrTimestamp := point[0].(string) if !isStrTimestamp { return errors.New("%s timestamp is not a string in RFC 3339 format", point[0]) } timestamp, err := time.Parse(time.RFC3339, strTimestamp) if err != nil { return errors.New("%s timestamp is not in RFC 3339 format", point[0]) } tsp.Timestamp = timestamp // By default, JSON unmarshal a float in float64 but the TimeSeriesPoint is a float32 value. value, isValue := point[1].(float64) if !isValue { return errors.New("%s is not a valid float32 value", point[1]) } tsp.Value = float32(value) return nil }
scw/custom_types.go
0.882162
0.425486
custom_types.go
starcoder
package main import ( "fmt" ) type TZLabel struct { Abbreviation string Full string UTCOffset int } // lookupFullTZ returns the full name of an abbreviation of a timezone. // If two tzs exist for an abbreviation, the closest tz to offset is returned. func lookupFullTZ(abbrev string, utcOffset int) (TZLabel, error) { val, exists := tzAbbrevsTable[abbrev] if !exists { return TZLabel{}, fmt.Errorf("abbrev: %s does not exist in the lookup table", abbrev) } ret := val[0] if len(val) > 1 { // two possible tzs for this abbrev lesserDiff := val[0] for i := 1; i < len(val); i++ { if abs(utcOffset-val[i].UTCOffset) < abs(utcOffset-lesserDiff.UTCOffset) { lesserDiff = val[i] } } ret = lesserDiff } return ret, nil } func abs(x int) int { if x < 0 { return x * -1 } return x } var tzAbbrevsTable = map[string][]TZLabel{ "ACDT": {{"ACDT", "Australian Central Daylight Saving Time", 10}}, "ACST": {{"ACST", "Australian Central Standard Time", 9}}, "ACT": {{"ACT", "Acre Time", -5}}, "ACWST": {{"ACWST", "Australian Central Western Standard Time (unofficial)", 8}}, "ADT": {{"ADT", "Atlantic Daylight Time", -3}}, "AEDT": {{"AEDT", "Australian Eastern Daylight Saving Time", 11}}, "AEST": {{"AEST", "Australian Eastern Standard Time", 10}}, "AET": {{"AET", "Australian Eastern Time", 10}}, "AFT": {{"AFT", "Afghanistan Time", 4}}, "AKDT": {{"AKDT", "Alaska Daylight Time", -8}}, "AKST": {{"AKST", "Alaska Standard Time", -9}}, "ALMT": {{"ALMT", "Alma-Ata Time", 6}}, "AMST": {{"AMST", "Amazon Summer Time (Brazil)", -3}}, "AMT": {{"AMT", "Amazon Time (Brazil)", -4}, {"AMT", "Armenia Time", 4}}, "ANAT": {{"ANAT", "Anadyr Time", 12}}, "AQTT": {{"AQTT", "Aqtobe Time", 5}}, "ART": {{"ART", "Argentina Time", -3}}, "AST": {{"AST", "Arabia Standard Time", 3}, {"AST", "Atlantic Standard Time", -4}}, "AWST": {{"AWST", "Australian Western Standard Time", 8}}, "AZOST": {{"AZOST", "Azores Summer Time", 0}}, "AZOT": {{"AZOT", "Azores Standard Time", -1}}, "AZT": {{"AZT", "Azerbaijan Time", 4}}, "BNT": {{"BNT", "Brunei Time", 8}}, "BIOT": {{"BIOT", "British Indian Ocean Time", 6}}, "BIT": {{"BIT", "Baker Island Time", -12}}, "BOT": {{"BOT", "Bolivia Time", -4}}, "BRST": {{"BRST", "Brasília Summer Time", -2}}, "BRT": {{"BRT", "Brasília Time", -3}}, "BST": {{"BST", "Bangladesh Standard Time", 6}, {"BST", "Bougainville Standard Time", 11}}, "BTT": {{"BTT", "Bhutan Time", 6}}, "CAT": {{"CAT", "Central Africa Time", 2}}, "CCT": {{"CCT", "Cocos Islands Time", 6}}, "CDT": {{"CDT", "Central Daylight Time (North America)", -5}, {"CDT", "Cuba Daylight Time", -4}}, "CEST": {{"CEST", "Central European Summer Time (Cf. HAEC)", 2}}, "CET": {{"CET", "Central European Time", 1}}, "CHADT": {{"CHADT", "Chatham Daylight Time", 13}}, "CHAST": {{"CHAST", "Chatham Standard Time", 12}}, "CHOT": {{"CHOT", "Choibalsan Standard Time", 8}}, "CHOST": {{"CHOST", "Choibalsan Summer Time", 9}}, "CHST": {{"CHST", "Chamorro Standard Time", 10}}, "CHUT": {{"CHUT", "Chuuk Time", 10}}, "CIST": {{"CIST", "Clipperton Island Standard Time", -8}}, "CKT": {{"CKT", "Cook Island Time", -10}}, "CLST": {{"CLST", "Chile Summer Time", -3}}, "CLT": {{"CLT", "Chile Standard Time", -4}}, "COST": {{"COST", "Colombia Summer Time", -4}}, "COT": {{"COT", "Colombia Time", -5}}, "CST": {{"CST", "Central Standard Time (North America)", -6}, {"CST", "China Standard Time", 8}, {"CST", "Cuba Standard Time", -5}}, "CT": {{"CT", "Central Time", -6}}, "CVT": {{"CVT", "Cape Verde Time", -1}}, "CWST": {{"CWST", "Central Western Standard Time (Australia) unofficial", 8}}, "CXT": {{"CXT", "Christmas Island Time", 7}}, "DAVT": {{"DAVT", "Davis Time", 7}}, "DDUT": {{"DDUT", "Dumont d'Urville Time", 10}}, "DFT": {{"DFT", "AIX-specific equivalent of Central European Time", 1}}, "EASST": {{"EASST", "Easter Island Summer Time", -5}}, "EAST": {{"EAST", "Easter Island Standard Time", -6}}, "EAT": {{"EAT", "East Africa Time", 3}}, "ECT": {{"ECT", "Eastern Caribbean Time", -4}, {"ECT", "Ecuador Time", -5}}, "EDT": {{"EDT", "Eastern Daylight Time (North America)", -4}}, "EEST": {{"EEST", "Eastern European Summer Time", 3}}, "EET": {{"EET", "Eastern European Time", 2}}, "EGST": {{"EGST", "Eastern Greenland Summer Time", 0}}, "EGT": {{"EGT", "Eastern Greenland Time", -1}}, "EST": {{"EST", "Eastern Standard Time (North America)", -5}}, "FET": {{"FET", "Further-eastern European Time", 3}}, "FJT": {{"FJT", "Fiji Time", 12}}, "FKST": {{"FKST", "Falkland Islands Summer Time", -3}}, "FKT": {{"FKT", "Falkland Islands Time", -4}}, "FNT": {{"FNT", "Fernando de Noronha Time", -2}}, "GALT": {{"GALT", "Galápagos Time", -6}}, "GAMT": {{"GAMT", "Gambier Islands Time", -9}}, "GET": {{"GET", "Georgia Standard Time", 4}}, "GFT": {{"GFT", "French Guiana Time", -3}}, "GILT": {{"GILT", "Gilbert Island Time", 12}}, "GIT": {{"GIT", "Gambier Island Time", -9}}, "GMT": {{"GMT", "Greenwich Mean Time", 0}}, "GST": {{"GST", "South Georgia and the South Sandwich Islands Time", -2}, {"GST", "Gulf Standard Time", 4}}, "GYT": {{"GYT", "Guyana Time", -4}}, "HDT": {{"HDT", "Hawaii–Aleutian Daylight Time", -9}}, "HAEC": {{"HAEC", "Heure Avancée d'Europe Centrale", 2}}, "HST": {{"HST", "Hawaii–Aleutian Standard Time", -10}}, "HKT": {{"HKT", "Hong Kong Time", 8}}, "HMT": {{"HMT", "Heard and McDonald Islands Time", 5}}, "HOVST": {{"HOVST", "Hovd Summer Time", 8}}, "HOVT": {{"HOVT", "Hovd Time", 7}}, "ICT": {{"ICT", "Indochina Time", 7}}, "IDLW": {{"IDLW", "International Day Line West", -12}}, "IDT": {{"IDT", "Israel Daylight Time", 3}}, "IOT": {{"IOT", "Indian Ocean Time", 3}}, "IRDT": {{"IRDT", "Iran Daylight Time", 4}}, "IRKT": {{"IRKT", "Irkutsk Time", 8}}, "IRST": {{"IRST", "Iran Standard Time", 3}}, "IST": {{"IST", "Indian Standard Time", 5}, {"IST", "Irish Standard Time", 1}, {"IST", "Israel Standard Time", 2}}, "JST": {{"JST", "Japan Standard Time", 9}}, "KALT": {{"KALT", "Kaliningrad Time", 2}}, "KGT": {{"KGT", "Kyrgyzstan Time", 6}}, "KOST": {{"KOST", "Kosrae Time", 11}}, "KRAT": {{"KRAT", "Krasnoyarsk Time", 7}}, "KST": {{"KST", "Korea Standard Time", 9}}, "LHST": {{"LHST", "Lord Howe Standard Time", 10}}, "LINT": {{"LINT", "Line Islands Time", 14}}, "MAGT": {{"MAGT", "Magadan Time", 12}}, "MART": {{"MART", "Marquesas Islands Time", -9}}, "MAWT": {{"MAWT", "Mawson Station Time", 5}}, "MDT": {{"MDT", "Mountain Daylight Time (North America)", -6}}, "MET": {{"MET", "Middle European Time (same zone as CET)", 1}}, "MEST": {{"MEST", "Middle European Summer Time (same zone as CEST)", 2}}, "MHT": {{"MHT", "Marshall Islands Time", 12}}, "MIST": {{"MIST", "Macquarie Island Station Time", 11}}, "MIT": {{"MIT", "Marquesas Islands Time", -9}}, "MMT": {{"MMT", "Myanmar Standard Time", 6}}, "MSK": {{"MSK", "Moscow Time", 3}}, "MST": {{"MST", "Malaysia Standard Time", 8}, {"MST", "Mountain Standard Time (North America)", -7}}, "MUT": {{"MUT", "Mauritius Time", 4}}, "MVT": {{"MVT", "Maldives Time", 5}}, "MYT": {{"MYT", "Malaysia Time", 8}}, "NCT": {{"NCT", "New Caledonia Time", 11}}, "NDT": {{"NDT", "Newfoundland Daylight Time", -2}}, "NFT": {{"NFT", "Norfolk Island Time", 11}}, "NOVT": {{"NOVT", "Novosibirsk Time", 7}}, "NPT": {{"NPT", "Nepal Time", 5}}, "NST": {{"NST", "Newfoundland Standard Time", -3}}, "NT": {{"NT", "Newfoundland Time", -3}}, "NUT": {{"NUT", "Niue Time", -11}}, "NZDT": {{"NZDT", "New Zealand Daylight Time", 13}}, "NZST": {{"NZST", "New Zealand Standard Time", 12}}, "OMST": {{"OMST", "Omsk Time", 6}}, "ORAT": {{"ORAT", "Oral Time", 5}}, "PDT": {{"PDT", "Pacific Daylight Time (North America)", -7}}, "PET": {{"PET", "Peru Time", -5}}, "PETT": {{"PETT", "Kamchatka Time", 12}}, "PGT": {{"PGT", "Papua New Guinea Time", 10}}, "PHOT": {{"PHOT", "Phoenix Island Time", 13}}, "PHT": {{"PHT", "Philippine Time", 8}}, "PKT": {{"PKT", "Pakistan Standard Time", 5}}, "PMDT": {{"PMDT", "Saint Pierre and Miquelon Daylight Time", -2}}, "PMST": {{"PMST", "Saint Pierre and Miquelon Standard Time", -3}}, "PONT": {{"PONT", "Pohnpei Standard Time", 11}}, "PST": {{"PST", "Pacific Standard Time (North America)", -8}, {"PST", "Philippine Standard Time", 8}}, "PWT": {{"PWT", "Palau Time", 9}}, "PYST": {{"PYST", "Paraguay Summer Time", -3}}, "PYT": {{"PYT", "Paraguay Time", -4}}, "RET": {{"RET", "Réunion Time", 4}}, "ROTT": {{"ROTT", "Rothera Research Station Time", -3}}, "SAKT": {{"SAKT", "Sakhalin Island Time", 11}}, "SAMT": {{"SAMT", "Samara Time", 4}}, "SAST": {{"SAST", "South African Standard Time", 2}}, "SBT": {{"SBT", "Solomon Islands Time", 11}}, "SCT": {{"SCT", "Seychelles Time", 4}}, "SDT": {{"SDT", "Samoa Daylight Time", -10}}, "SGT": {{"SGT", "Singapore Time", 8}}, "SLST": {{"SLST", "Sri Lanka Standard Time", 5}}, "SRET": {{"SRET", "Srednekolymsk Time", 11}}, "SRT": {{"SRT", "Suriname Time", -3}}, "SST": {{"SST", "Samoa Standard Time", -11}, {"SST", "Singapore Standard Time", 8}}, "SYOT": {{"SYOT", "Showa Station Time", 3}}, "TAHT": {{"TAHT", "Tahiti Time", -10}}, "THA": {{"THA", "Thailand Standard Time", 7}}, "TFT": {{"TFT", "French Southern and Antarctic Time", 5}}, "TJT": {{"TJT", "Tajikistan Time", 5}}, "TKT": {{"TKT", "Tokelau Time", 13}}, "TLT": {{"TLT", "Timor Leste Time", 9}}, "TMT": {{"TMT", "Turkmenistan Time", 5}}, "TRT": {{"TRT", "Turkey Time", 3}}, "TOT": {{"TOT", "Tonga Time", 13}}, "TVT": {{"TVT", "Tuvalu Time", 12}}, "ULAST": {{"ULAST", "Ulaanbaatar Summer Time", 9}}, "ULAT": {{"ULAT", "Ulaanbaatar Standard Time", 8}}, "UTC": {{"UTC", "Coordinated Universal Time", 0}}, "UYST": {{"UYST", "Uruguay Summer Time", -2}}, "UYT": {{"UYT", "Uruguay Standard Time", -3}}, "UZT": {{"UZT", "Uzbekistan Time", 5}}, "VET": {{"VET", "Venezuelan Standard Time", -4}}, "VLAT": {{"VLAT", "Vladivostok Time", 10}}, "VOLT": {{"VOLT", "Volgograd Time", 4}}, "VOST": {{"VOST", "Vostok Station Time", 6}}, "VUT": {{"VUT", "Vanuatu Time", 11}}, "WAKT": {{"WAKT", "Wake Island Time", 12}}, "WAST": {{"WAST", "West Africa Summer Time", 2}}, "WAT": {{"WAT", "West Africa Time", 1}}, "WEST": {{"WEST", "Western European Summer Time", 1}}, "WET": {{"WET", "Western European Time", 0}}, "WIB": {{"WIB", "Western Indonesian Time", 7}}, "WIT": {{"WIT", "Eastern Indonesian Time", 9}}, "WITA": {{"WITA", "Central Indonesia Time", 8}}, "WGST": {{"WGST", "West Greenland Summer Time", -2}}, "WGT": {{"WGT", "West Greenland Time", -3}}, "WST": {{"WST", "Western Standard Time", 8}}, "YAKT": {{"YAKT", "Yakutsk Time", 9}}, "YEKT": {{"YEKT", "Yekaterinburg Time", 5}}, } // // https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations // let t = "" // Array.from(document.getElementsByTagName("tbody")[1].children).forEach((el) => { // let ar = el.children // let abbrev = ar[0].textContent.replaceAll("\n","") // let full = ar[1].textContent.replaceAll("\n","") // .replaceAll(/\[.*\]/g, "") // remove citations e.g, [5] // let of = ar[2].textContent // .replaceAll(/[\/–:].*/g,"") // replace everything after "/" or emdash "–" or ":" aka unneccesary tz info to calculate most accurate tz // .replaceAll("−", "-") // replace minus sign with a parsable minus sign // .replaceAll("±", "") // .replaceAll("UTC", "") // .replaceAll("\n","") // of = Number.parseInt(of) // t += `"${abbrev}": {{"${abbrev}", "${full}", ${of}}},` + "\n" // }) // console.log(t)
tztable.go
0.577495
0.522446
tztable.go
starcoder
package leaves import ( "math" "github.com/fredrikluo/leaves/util" ) const ( categorical = 1 << 0 defaultLeft = 1 << 1 leftLeaf = 1 << 2 rightLeaf = 1 << 3 missingZero = 1 << 4 missingNan = 1 << 5 catOneHot = 1 << 6 catSmall = 1 << 7 ) const zeroThreshold = 1e-35 type lgNode struct { Threshold float64 Left uint32 Right uint32 Feature uint32 Flags uint8 } type lgTree struct { nodes []lgNode leafValues []float64 catBoundaries []uint32 catThresholds []uint32 nCategorical uint32 } func (t *lgTree) numericalDecision(node *lgNode, fval float64) bool { if math.IsNaN(fval) && (node.Flags&missingNan == 0) { fval = 0.0 } if ((node.Flags&missingZero > 0) && isZero(fval)) || ((node.Flags&missingNan > 0) && math.IsNaN(fval)) { return node.Flags&defaultLeft > 0 } // Note: LightGBM uses `<=`, but XGBoost uses `<` return fval <= node.Threshold } func (t *lgTree) categoricalDecision(node *lgNode, fval float64) bool { ifval := int32(fval) if ifval < 0 { return false } else if math.IsNaN(fval) { if node.Flags&missingNan > 0 { return false } ifval = 0 } if node.Flags&catOneHot > 0 { return int32(node.Threshold) == ifval } else if node.Flags&catSmall > 0 { return util.FindInBitsetUint32(uint32(node.Threshold), uint32(ifval)) } return t.findInBitset(uint32(node.Threshold), uint32(ifval)) } func (t *lgTree) decision(node *lgNode, fval float64) bool { if node.Flags&categorical > 0 { return t.categoricalDecision(node, fval) } return t.numericalDecision(node, fval) } func (t *lgTree) predict(fvals []float64) (float64, uint32) { if len(t.nodes) == 0 { return t.leafValues[0], 0 } idx := uint32(0) for { node := &t.nodes[idx] left := t.decision(node, fvals[node.Feature]) if left { if node.Flags&leftLeaf > 0 { return t.leafValues[node.Left], node.Left } idx = node.Left } else { if node.Flags&rightLeaf > 0 { return t.leafValues[node.Right], node.Right } idx++ } } } func (t *lgTree) findInBitset(idx uint32, pos uint32) bool { i1 := pos / 32 idxS := t.catBoundaries[idx] idxE := t.catBoundaries[idx+1] if i1 >= (idxE - idxS) { return false } i2 := pos % 32 return (t.catThresholds[idxS+i1]>>i2)&1 > 0 } func (t *lgTree) nLeaves() int { return len(t.nodes) + 1 } func (t *lgTree) nNodes() int { return len(t.nodes) } func isZero(fval float64) bool { return (fval > -zeroThreshold && fval <= zeroThreshold) } func categoricalNode(feature uint32, missingType uint8, threshold uint32, catType uint8) lgNode { node := lgNode{} node.Feature = feature node.Flags = categorical | missingType | catType node.Threshold = float64(threshold) return node } func numericalNode(feature uint32, missingType uint8, threshold float64, defaultType uint8) lgNode { node := lgNode{} node.Feature = feature node.Flags = missingType | defaultType node.Threshold = threshold return node }
lgtree.go
0.629319
0.411998
lgtree.go
starcoder
package c8y import ( "regexp" "strconv" "time" ) // GetDateRange returns the dateFrom and dateTo based on an interval string, i.e. 1d, is 1 day func GetDateRange(dateInterval string) (string, string) { pattern := regexp.MustCompile(`^(\d+)\s*([a-zA-Z]+)$`) result := pattern.FindStringSubmatch(dateInterval) if len(result) == 0 { Logger.Println("Invalid date interval. Using default '1d'") result = []string{"-", "1", "d"} } period, err := strconv.ParseFloat(result[1], 32) if err != nil { period = 1.0 } unit := result[2] duration := convertToDuration(period, unit) dateTo := time.Now().Add(-1 * 10 * time.Second) dateFrom := dateTo.Add(-1 * duration) return dateFrom.Format(time.RFC3339), dateTo.Format(time.RFC3339) } func convertToDuration(period float64, unit string) time.Duration { duration := time.Duration(period) * time.Hour * 24 switch unit { case "d": duration = time.Duration(period) * time.Hour * 24 case "h": duration = time.Duration(period) * time.Hour case "min": duration = time.Duration(period) * time.Minute case "s": duration = time.Duration(period) * time.Second } return duration } // GetRoundedTime Get the rounded timestamp (i.e. start of the hour, start of the minute, start of the day) func GetRoundedTime(date *time.Time, unit string) (roundTime time.Time) { var now time.Time if date != nil { now = *date } else { now = time.Now() } switch unit { case "d": roundTime = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) case "h": roundTime = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, time.Local) case "min": roundTime = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, time.Local) case "s": roundTime = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), 0, time.Local) case "10min": rounded10Min := now.Minute() - (now.Minute() % 10) roundTime = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), rounded10Min, 0, 0, time.Local) default: panic("Invalid unit. Only d, h, min, s and 10min are valid units") } return } // ParseDate returns a Time object from a string /* func ParseDate(value string) (dateObj *time.Time, err error) { var tempDate time.Time // Try to parse with ISO8801 format if tempDate, err = time.Parse("2006-01-02T15:04:05-07", value); err == nil { dateObj = &tempDate return dateObj, nil } // Try generic date parser if tempDate, err = dateparse.ParseAny(value); err == nil { dateObj = &tempDate return dateObj, nil } err = fmt.Errorf("Could not parse date") return nil, err } */
pkg/c8y/dateHelper.go
0.747708
0.511046
dateHelper.go
starcoder
package matrixexp import ( "fmt" "github.com/gonum/blas/blas64" ) // General is a typical matrix literal. type General struct { blas64.General } // String implements the Stringer interface. func (m1 *General) String() string { return fmt.Sprintf("%#v", m1) } // Dims returns the matrix dimensions. func (m1 *General) Dims() (r, c int) { r, c = m1.Rows, m1.Cols return } // At returns the value at a given row, column index. func (m1 *General) At(r, c int) float64 { return m1.Data[r*m1.Stride+c] } // Set changes the value at a given row, column index. func (m1 *General) Set(r, c int, v float64) { m1.Data[r*m1.Stride+c] = v } // Eval returns a matrix literal. func (m1 *General) Eval() MatrixLiteral { return m1 } // Copy creates a (deep) copy of the Matrix Expression. func (m1 *General) Copy() MatrixExp { v := make([]float64, len(m1.Data)) copy(v, m1.Data) return &General{ blas64.General{ Rows: m1.Rows, Cols: m1.Cols, Stride: m1.Stride, Data: v, }, } } // Err returns the first error encountered while constructing the matrix expression. func (m1 *General) Err() error { if m1.Rows < 0 { return ErrInvalidRows(m1.Rows) } if m1.Cols < 0 { return ErrInvalidCols(m1.Cols) } if m1.Stride < 1 { return ErrInvalidStride(m1.Stride) } if m1.Stride < m1.Cols { return ErrStrideLessThanCols{m1.Stride, m1.Cols} } if maxLen := (m1.Rows-1)*m1.Stride + m1.Cols; maxLen > len(m1.Data) { return ErrInvalidDataLen{len(m1.Data), maxLen} } return nil } // T transposes a matrix. func (m1 *General) T() MatrixExp { return &T{m1} } // Add two matrices together. func (m1 *General) Add(m2 MatrixExp) MatrixExp { return &Add{ Left: m1, Right: m2, } } // Sub subtracts the right matrix from the left matrix. func (m1 *General) Sub(m2 MatrixExp) MatrixExp { return &Sub{ Left: m1, Right: m2, } } // Scale performs scalar multiplication. func (m1 *General) Scale(c float64) MatrixExp { return &Scale{ C: c, M: m1, } } // Mul performs matrix multiplication. func (m1 *General) Mul(m2 MatrixExp) MatrixExp { return &Mul{ Left: m1, Right: m2, } } // MulElem performs element-wise multiplication. func (m1 *General) MulElem(m2 MatrixExp) MatrixExp { return &MulElem{ Left: m1, Right: m2, } } // DivElem performs element-wise division. func (m1 *General) DivElem(m2 MatrixExp) MatrixExp { return &DivElem{ Left: m1, Right: m2, } } // AsVector returns a copy of the values in the matrix as a []float64, in row order. func (m1 *General) AsVector() []float64 { // TODO(jonlawlor): make use of a pool. v := make([]float64, m1.Rows*m1.Cols) for i := 0; i < m1.Rows; i++ { copy(v[i*m1.Cols:(i+1)*m1.Cols], m1.Data[i*m1.Stride:i*m1.Stride+m1.Cols]) } copy(v, m1.Data) return v } // AsGeneral returns the matrix as a blas64.General (not a copy!) func (m1 *General) AsGeneral() blas64.General { return m1.General }
general.go
0.859605
0.500793
general.go
starcoder
package main import ( "strings" . "../lib" ) type strategy func([]string, int, int) int var tolerance = 4 func part1(state []string) (int, error) { var stable bool for { state, stable = iterate(state, countAdjacent, 4) if stable { break } } occupied := 0 for _, row := range state { occupied += strings.Count(row, "#") } return occupied, nil } func iterate(state []string, count strategy, tolerance int) ([]string, bool) { stable := true newState := make([]string, len(state)) for i := 0; i < len(state); i++ { for j := 0; j < len(state[i]); j++ { c := count(state, i, j) n := state[i][j] if n == 'L' && c == 0 { n = '#' stable = false } if n == '#' && c >= tolerance { n = 'L' stable = false } newState[i] += string(n) } } return newState, stable } func countAdjacent(state []string, y, x int) int { adjacent := []byte{ at(state, y-1, x-1), at(state, y-1, x), at(state, y-1, x+1), at(state, y, x-1), at(state, y, x+1), at(state, y+1, x-1), at(state, y+1, x), at(state, y+1, x+1), } count := 0 for _, r := range adjacent { if r == '#' { count++ } } return count } func countVisible(state []string, y, x int) int { visible := []byte{ find(state, y, x, -1, -1), find(state, y, x, -1, 0), find(state, y, x, -1, 1), find(state, y, x, 0, -1), find(state, y, x, 0, 1), find(state, y, x, 1, -1), find(state, y, x, 1, 0), find(state, y, x, 1, 1), } count := 0 for _, r := range visible { if r == '#' { count++ } } return count } func find(state []string, y, x, vy, vx int) byte { for { x += vx y += vy if x < 0 || y < 0 || x >= len(state[0]) || y >= len(state) { return '.' } if state[y][x] != '.' { return state[y][x] } } } func at(state []string, y, x int) byte { if x < 0 || y < 0 || x >= len(state[0]) || y >= len(state) { return '.' } return state[y][x] } func part2(state []string) (int, error) { var stable bool for { state, stable = iterate(state, countVisible, 5) if stable { break } } occupied := 0 for _, row := range state { occupied += strings.Count(row, "#") } return occupied, nil } func main() { Solve(11, part1, part2) }
2020/day-11/main.go
0.580828
0.447641
main.go
starcoder
package yeelight import ( "context" "fmt" "time" ) // FlowExpression is the expression of the state changing series. type FlowExpression struct { // Duration Gradual change time or sleep time. Minimum value 50 milliseconds. Duration time.Duration // Mode can be FlowModeColor, FlowColorTemperature, FlowSleep Mode FlowMode // Value is RGB value when mode is FlowModeColor, CT value when mode is FlowColorTemperature, Ignored when mode is FlowSleep. Value int // Brightness value, -1 or 1 ~ 100. Ignored when mode is FlowSleep. // When this value is -1, brightness in this tuple is ignored (only color or CT change takes effect). Brightness int } // StartColorFlow method is used to start a color flow. Color flow is a series of smart LED visible state changing. // It can be brightness changing, color changing or color temperature changing. // `count` is the total number of visible state changing before color flow stopped. 0 means infinite loop on the state changing. func (c Client) StartColorFlow(ctx context.Context, count int, action FlowAction, expressions []FlowExpression) error { return c.startColorFlow(ctx, MethodStartCF, count, action, expressions) } // StartBackgroundColorFlow method is used to start a color flow. Color flow is a series of smart LED visible state changing. // It can be brightness changing, color changing or color temperature changing. // `count` is the total number of visible state changing before color flow stopped. 0 means infinite loop on the state changing. func (c Client) StartBackgroundColorFlow(ctx context.Context, count int, action FlowAction, expressions []FlowExpression) error { return c.startColorFlow(ctx, MethodBgStartCF, count, action, expressions) } // StopColorFlow method is used to stop a running color flow. func (c Client) StopColorFlow(ctx context.Context) error { return c.stopColorFlow(ctx, MethodStopCF) } // StopBackgroundColorFlow method is used to stop a running color flow. func (c Client) StopBackgroundColorFlow(ctx context.Context) error { return c.stopColorFlow(ctx, MethodBgStopCF) } func (c Client) startColorFlow(ctx context.Context, method string, count int, action FlowAction, expressions []FlowExpression) error { if len(expressions) == 0 { return ErrRequiredMinimumOneExpression } var expressionStr string for _, exp := range expressions { if len(expressionStr) > 0 { expressionStr += "," } expressionStr += fmt.Sprintf("%d,%d,%d,%d", exp.Duration.Milliseconds(), exp.Mode, exp.Value, exp.Brightness) } return c.rawWithOk(ctx, method, count, action, expressionStr) } func (c Client) stopColorFlow(ctx context.Context, method string) error { return c.rawWithOk(ctx, method) }
flow.go
0.798265
0.45417
flow.go
starcoder
package main import ( "fmt" "math" "math/cmplx" ) // a type to represent matrices type matrix struct { ele []complex128 cols int } // conjugate transpose, implemented here as a method on the matrix type. func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) rx += r.cols if rx >= len(r.ele) { rx -= len(r.ele) - 1 } } return r } // program to demonstrate capabilites on example matricies func main() { show("h", matrixFromRows([][]complex128{ {3, 2 + 1i}, {2 - 1i, 1}})) show("n", matrixFromRows([][]complex128{ {1, 1, 0}, {0, 1, 1}, {1, 0, 1}})) show("u", matrixFromRows([][]complex128{ {math.Sqrt2 / 2, math.Sqrt2 / 2, 0}, {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0}, {0, 0, 1i}})) } func show(name string, m *matrix) { m.print(name) ct := m.conjTranspose() ct.print(name + "_ct") fmt.Println("Hermitian:", m.equal(ct, 1e-14)) mct := m.mult(ct) ctm := ct.mult(m) fmt.Println("Normal:", mct.equal(ctm, 1e-14)) i := eye(m.cols) fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14)) } // two constructors func matrixFromRows(rows [][]complex128) *matrix { m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} for rx, row := range rows { copy(m.ele[rx*m.cols:(rx+1)*m.cols], row) } return m } func eye(n int) *matrix { r := &matrix{make([]complex128, n*n), n} n++ for x := 0; x < len(r.ele); x += n { r.ele[x] = 1 } return r } // print method outputs matrix to stdout func (m *matrix) print(heading string) { fmt.Print("\n", heading, "\n") for e := 0; e < len(m.ele); e += m.cols { fmt.Printf("%6.3f ", m.ele[e:e+m.cols]) fmt.Println() } } // equal method uses ε to allow for floating point error. func (a *matrix) equal(b *matrix, ε float64) bool { for x, aEle := range a.ele { if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε || math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε { return false } } return true } // mult method taken from matrix multiply task func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) { m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols} for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols { for m2r0 := 0; m2r0 < m2.cols; m2r0++ { for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols { m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] m1x++ } m3x++ } } return m3 } //\Conjugate-transpose\conjugate-transpose.go
tasks/Conjugate-transpose/conjugate-transpose.go
0.577972
0.669029
conjugate-transpose.go
starcoder
package parser import ( "fmt" ) // Abstract, should not get called but needed to cast abstract struct to Expression func (e *Positioned) Label() string { return "Positioned" } // Concrete func (e *ActivityExpression) Label() string { return "Activity" } func (e *AccessExpression) Label() string { return "'[]' expression" } func (e *AndExpression) Label() string { return "'and' expression" } func (e *ArithmeticExpression) Label() string { return fmt.Sprintf("'%s' expression", e.operator) } func (e *Application) Label() string { return "Application" } func (e *AssignmentExpression) Label() string { return fmt.Sprintf("'%s' expression", e.operator) } func (e *AttributeOperation) Label() string { return fmt.Sprintf("'%s' expression", e.operator) } func (e *AttributesOperation) Label() string { return "AttributesOperation" } func (e *BlockExpression) Label() string { return "Block Expression" } func (e *CallMethodExpression) Label() string { return "Method Call" } func (e *CallNamedFunctionExpression) Label() string { return "Function Call" } func (e *CapabilityMapping) Label() string { return "Capability Mapping" } func (e *CaseExpression) Label() string { return "'case' statement" } func (e *CaseOption) Label() string { return "CaseOption" } func (e *CollectExpression) Label() string { return "CollectExpression" } func (e *ComparisonExpression) Label() string { return fmt.Sprintf("'%s' expression", e.operator) } func (e *ConcatenatedString) Label() string { return "Concatenated String" } func (e *EppExpression) Label() string { return "Epp Template" } func (e *ExportedQuery) Label() string { return "Exported Query" } func (e *FunctionDefinition) Label() string { return "Function Definition" } func (e *HeredocExpression) Label() string { return "Heredoc" } func (e *HostClassDefinition) Label() string { return "Host Class Definition" } func (e *IfExpression) Label() string { return "'if' statement" } func (e *InExpression) Label() string { return "'in' expression" } func (e *KeyedEntry) Label() string { return "Hash Entry" } func (e *LiteralBoolean) Label() string { return "Literal Boolean" } func (e *LiteralDefault) Label() string { return "'default' expression" } func (e *LiteralFloat) Label() string { return "Literal Float" } func (e *LiteralHash) Label() string { return "Hash Expression" } func (e *LiteralInteger) Label() string { return "Literal Integer" } func (e *LiteralList) Label() string { return "Array expression" } func (e *LiteralString) Label() string { return "Literal String" } func (e *LiteralUndef) Label() string { return "'undef' expression" } func (e *Locator) Label() string { return "Locator" } func (e *MatchExpression) Label() string { return fmt.Sprintf("'%s' expression", e.operator) } func (e *NamedAccessExpression) Label() string { return "'.' expression" } func (e *NodeDefinition) Label() string { return "Node Definition" } func (e *Nop) Label() string { return "Nop" } func (e *NotExpression) Label() string { return "'!' expression" } func (e *OrExpression) Label() string { return "'or' expression" } func (e *Parameter) Label() string { return "Parameter Definition" } func (e *Program) Label() string { return "Program" } func (e *QualifiedName) Label() string { return "Name" } func (e *QualifiedReference) Label() string { return "Type-Name" } func (e *RelationshipExpression) Label() string { return fmt.Sprintf("'%s' expression", e.operator) } func (e *RenderExpression) Label() string { return "Epp Interpolated Expression" } func (e *RenderStringExpression) Label() string { return "Epp Text" } func (e *RegexpExpression) Label() string { return "Regular Expression" } func (e *ReservedWord) Label() string { return fmt.Sprintf("Reserved Word '%s'", e.word) } func (e *ResourceBody) Label() string { return "Resource Instance Definition" } func (e *ResourceDefaultsExpression) Label() string { return "Resource Defaults Expression" } func (e *ResourceExpression) Label() string { return "Resource Statement" } func (e *ResourceOverrideExpression) Label() string { return "Resource Override" } func (e *ResourceTypeDefinition) Label() string { return "'define' expression" } func (e *SelectorEntry) Label() string { return "Selector option" } func (e *SelectorExpression) Label() string { return "Selector expression" } func (e *SiteDefinition) Label() string { return "Site Definition" } func (e *TextExpression) Label() string { return "Text expression" } func (e *TypeAlias) Label() string { return "Type Alias" } func (e *TypeDefinition) Label() string { return "Type Definition" } func (e *TypeMapping) Label() string { return "Type Mapping" } func (e *UnaryMinusExpression) Label() string { return "Unary Minus" } func (e *UnfoldExpression) Label() string { return "Unfold" } func (e *UnlessExpression) Label() string { return "'unless' statement" } func (e *VariableExpression) Label() string { return "Variable" } func (e *VirtualQuery) Label() string { return "Virtual Query" }
parser/label.go
0.632616
0.418043
label.go
starcoder
package fn import ( "sort" "github.com/nlpodyssey/spago/mat" "github.com/nlpodyssey/spago/mat/float" ) // SparseMax function implementation, based on https://github.com/gokceneraslan/SparseMax.torch type SparseMax[O Operand] struct { x O y mat.Matrix // initialized during the forward pass, required by the backward pass operands []O } // NewSparseMax returns a new SparseMax Function. func NewSparseMax[O Operand](x O) *SparseMax[O] { return &SparseMax[O]{ x: x, operands: []O{x}, } } // Operands returns the list of operands. func (r *SparseMax[O]) Operands() []O { return r.operands } // Forward computes the output of the function. func (r *SparseMax[O]) Forward() mat.Matrix { x := r.x.Value() xMax := x.Max().Scalar().F64() // translate the input by max for numerical stability v := x.SubScalar(xMax) zs, cumSumInput, _, tau := sparseMaxCommon(v) mat.ReleaseMatrix(zs) mat.ReleaseMatrix(cumSumInput) v.SubScalarInPlace(tau).ClipInPlace(0, xMax) r.y = v return v } // Backward computes the backward pass. func (r *SparseMax[O]) Backward(gy mat.Matrix) { if r.x.RequiresGrad() { var nzSum float64 var nzCount float64 r.y.DoVecNonZero(func(i int, _ float64) { nzSum += gy.ScalarAtVec(i).F64() nzCount++ }) nzSum = nzSum / nzCount gx := r.x.Value().ZerosLike() defer mat.ReleaseMatrix(gx) r.y.DoVecNonZero(func(i int, _ float64) { gyi := gy.ScalarAtVec(i).F64() gx.SetVecScalar(i, float.Interface(gyi-nzSum)) }) r.x.AccGrad(gx) } } func sparseMaxCommon(v mat.Matrix) (zs, cumSumInput mat.Matrix, bounds []float64, tau float64) { // FIXME: avoid casting to specific type zsData := make([]float64, v.Size()) copy(zsData, v.Data().F64()) // Sort zs in descending order. sort.Slice(zsData, func(i, j int) bool { return zsData[i] > zsData[j] }) zs = mat.NewVecDense(zsData) bounds = make([]float64, len(zsData)) for i := range bounds { bounds[i] = 1 + float64(i+1)*zsData[i] } cumSumInput = zs.CumSum() cumSumInputData := cumSumInput.Data().F64() k := -1 tau = 0.0 for i := range zsData { if bounds[i] > cumSumInputData[i] { if k < (i + 1) { k = i + 1 } tau += zsData[i] } } tau = (tau - 1) / float64(k) return zs, cumSumInput, bounds, tau }
ag/fn/sparsemax.go
0.765506
0.53959
sparsemax.go
starcoder
package stats // QueryTiming identifies the code area or functionality in which time is spent // during a query. type QueryTiming int // Query timings. const ( EvalTotalTime QueryTiming = iota ResultSortTime QueryPreparationTime InnerEvalTime ResultAppendTime ExecQueueTime ExecTotalTime ) // Return a string representation of a QueryTiming identifier. func (s QueryTiming) String() string { switch s { case EvalTotalTime: return "Eval total time" case ResultSortTime: return "Result sorting time" case QueryPreparationTime: return "Query preparation time" case InnerEvalTime: return "Inner eval time" case ResultAppendTime: return "Result append time" case ExecQueueTime: return "Exec queue wait time" case ExecTotalTime: return "Exec total time" default: return "Unknown query timing" } } // queryTimings with all query timers mapped to durations. type queryTimings struct { EvalTotalTime float64 `json:"evalTotalTime"` ResultSortTime float64 `json:"resultSortTime"` QueryPreparationTime float64 `json:"queryPreparationTime"` InnerEvalTime float64 `json:"innerEvalTime"` ResultAppendTime float64 `json:"resultAppendTime"` ExecQueueTime float64 `json:"execQueueTime"` ExecTotalTime float64 `json:"execTotalTime"` } // QueryStats currently only holding query timings. type QueryStats struct { Timings queryTimings `json:"timings,omitempty"` } // NewQueryStats makes a QueryStats struct with all QueryTimings found in the // given TimerGroup. func NewQueryStats(tg *TimerGroup) *QueryStats { var qt queryTimings for s, timer := range tg.timers { switch s { case EvalTotalTime: qt.EvalTotalTime = timer.Duration() case ResultSortTime: qt.ResultSortTime = timer.Duration() case QueryPreparationTime: qt.QueryPreparationTime = timer.Duration() case InnerEvalTime: qt.InnerEvalTime = timer.Duration() case ResultAppendTime: qt.ResultAppendTime = timer.Duration() case ExecQueueTime: qt.ExecQueueTime = timer.Duration() case ExecTotalTime: qt.ExecTotalTime = timer.Duration() } } qs := QueryStats{Timings: qt} return &qs }
monitoring/prometheus/busybox-prometheus/util/stats/query_stats.go
0.798423
0.44553
query_stats.go
starcoder
package movers import ( "danser/beatmap/objects" "danser/bmath" "danser/bmath/curves" . "danser/osuconst" "danser/settings" "math" ) type BezierMover struct { pt bmath.Vector2d bz curves.Bezier beginTime, endTime int64 previousSpeed float64 invert float64 } func NewBezierMover() MultiPointMover { bm := &BezierMover{invert: 1} bm.pt = bmath.NewVec2d(PLAYFIELD_WIDTH/2, PLAYFIELD_HEIGHT/2) bm.previousSpeed = -1 return bm } func (bm *BezierMover) Reset() { bm.pt = bmath.NewVec2d(PLAYFIELD_WIDTH/2, PLAYFIELD_HEIGHT/2) bm.invert = 1 bm.previousSpeed = -1 } func (bm *BezierMover) SetObjects(objs []objects.BaseObject) { end := objs[0] start := objs[1] endPos := end.GetBasicData().EndPos endTime := end.GetBasicData().EndTime startPos := start.GetBasicData().StartPos startTime := start.GetBasicData().StartTime dst := endPos.Dst(startPos) if bm.previousSpeed < 0 { bm.previousSpeed = dst / float64(startTime-endTime) } s1, ok1 := end.(*objects.Slider) s2, ok2 := start.(*objects.Slider) var points []bmath.Vector2d genScale := bm.previousSpeed aggressiveness := settings.Dance.Bezier.Aggressiveness sliderAggressiveness := settings.Dance.Bezier.SliderAggressiveness if endPos == startPos { points = []bmath.Vector2d{endPos, startPos} } else if ok1 && ok2 { endAngle := s1.GetEndAngle() startAngle := s2.GetStartAngle() bm.pt = bmath.NewVec2dRad(endAngle, s1.GetPointAt(endTime-10).Dst(endPos)*aggressiveness*sliderAggressiveness/10).Add(endPos) pt2 := bmath.NewVec2dRad(startAngle, s2.GetPointAt(startTime+10).Dst(startPos)*aggressiveness*sliderAggressiveness/10).Add(startPos) points = []bmath.Vector2d{endPos, bm.pt, pt2, startPos} } else if ok1 { endAngle := s1.GetEndAngle() pt1 := bmath.NewVec2dRad(endAngle, s1.GetPointAt(endTime-10).Dst(endPos)*aggressiveness*sliderAggressiveness/10).Add(endPos) bm.pt = bmath.NewVec2dRad(startPos.AngleRV(bm.pt), genScale*aggressiveness).Add(startPos) points = []bmath.Vector2d{endPos, pt1, bm.pt, startPos} } else if ok2 { startAngle := s2.GetStartAngle() bm.pt = bmath.NewVec2dRad(endPos.AngleRV(bm.pt), genScale*aggressiveness).Add(endPos) pt1 := bmath.NewVec2dRad(startAngle, s2.GetPointAt(startTime+10).Dst(startPos)*aggressiveness*sliderAggressiveness/10).Add(startPos) points = []bmath.Vector2d{endPos, bm.pt, pt1, startPos} } else { angle := endPos.AngleRV(bm.pt) if math.IsNaN(angle) { angle = 0 } bm.pt = bmath.NewVec2dRad(angle, bm.previousSpeed*aggressiveness).Add(endPos) points = []bmath.Vector2d{endPos, bm.pt, startPos} } bm.bz = curves.NewBezier(points) bm.endTime = endTime bm.beginTime = startTime bm.previousSpeed = (dst + 1.0) / float64(startTime-endTime) } func (bm *BezierMover) Update(time int64) bmath.Vector2d { return bm.bz.NPointAt(float64(time-bm.endTime) / float64(bm.beginTime-bm.endTime)) } func (bm *BezierMover) GetEndTime() int64 { return bm.beginTime }
dance/movers/bezier.go
0.609873
0.401776
bezier.go
starcoder
package oauth2test import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) // AccessTokenTest validates the specified access token by requesting the // protected resource. func AccessTokenTest(t *testing.T, spec *Spec, accessToken string) { // check token functionality Do(spec.Handler, &Request{ Method: "GET", Path: spec.ProtectedResource, Header: map[string]string{ "Authorization": "Bearer " + accessToken, }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) }, }) // check if access token is active if spec.IntrospectionEndpoint != "" { Do(spec.Handler, &Request{ Method: "POST", Path: spec.IntrospectionEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "token": accessToken, "token_type_hint": "access_token", }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) assert.True(t, jsonFieldBool(r, "active"), debug(r)) assert.Equal(t, "access_token", jsonFieldString(r, "token_type"), debug(r)) }, }) } // skip if revocation is not available if spec.RevocationEndpoint == "" { return } // revoke access token Do(spec.Handler, &Request{ Method: "POST", Path: spec.RevocationEndpoint, Form: map[string]string{ "token": accessToken, "token_type_hint": "access_token", }, Username: spec.ConfidentialClientID, Password: <PASSWORD>.ConfidentialClientSecret, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) }, }) // check token functionality Do(spec.Handler, &Request{ Method: "GET", Path: spec.ProtectedResource, Header: map[string]string{ "Authorization": "Bearer " + accessToken, }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusUnauthorized, r.Code, debug(r)) assert.Equal(t, "invalid_token", auth(r, "error"), debug(r)) }, }) // check if access token is now inactive if spec.IntrospectionEndpoint != "" { Do(spec.Handler, &Request{ Method: "POST", Path: spec.IntrospectionEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "token": accessToken, "token_type_hint": "access_token", }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) assert.False(t, jsonFieldBool(r, "active"), debug(r)) }, }) } } // RefreshTokenTest validates the specified refreshToken by requesting a new // access token and validating it as well. func RefreshTokenTest(t *testing.T, spec *Spec, refreshToken string) { // check if refresh token is active if spec.IntrospectionEndpoint != "" { Do(spec.Handler, &Request{ Method: "POST", Path: spec.IntrospectionEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "token": refreshToken, "token_type_hint": "refresh_token", }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) assert.True(t, jsonFieldBool(r, "active"), debug(r)) assert.Equal(t, "refresh_token", jsonFieldString(r, "token_type"), debug(r)) }, }) } var accessToken, newRefreshToken string // test refresh token grant Do(spec.Handler, &Request{ Method: "POST", Path: spec.TokenEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "grant_type": "refresh_token", "refresh_token": refreshToken, }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) assert.Equal(t, "bearer", jsonFieldString(r, "token_type"), debug(r)) assert.Equal(t, spec.ValidScope, jsonFieldString(r, "scope"), debug(r)) assert.Equal(t, float64(spec.ExpectedExpiresIn), jsonFieldFloat(r, "expires_in"), debug(r)) accessToken = jsonFieldString(r, "access_token") assert.NotEmpty(t, accessToken, debug(r)) newRefreshToken = jsonFieldString(r, "refresh_token") assert.NotEmpty(t, newRefreshToken, debug(r)) }, }) // test access token AccessTokenTest(t, spec, accessToken) // check if refresh token is spent Do(spec.Handler, &Request{ Method: "POST", Path: spec.TokenEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "grant_type": "refresh_token", "refresh_token": refreshToken, }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusBadRequest, r.Code, debug(r)) assert.Equal(t, "invalid_grant", jsonFieldString(r, "error"), debug(r)) }, }) // check if refresh token is now inactive if spec.IntrospectionEndpoint != "" { Do(spec.Handler, &Request{ Method: "POST", Path: spec.IntrospectionEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "token": refreshToken, "token_type_hint": "refresh_token", }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) assert.False(t, jsonFieldBool(r, "active"), debug(r)) }, }) } // skip if revocation is not available if spec.RevocationEndpoint == "" { return } // revoke new refresh token Do(spec.Handler, &Request{ Method: "POST", Path: spec.RevocationEndpoint, Form: map[string]string{ "token": newRefreshToken, "token_type_hint": "refresh_token", }, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) }, }) // check if new refresh token is revoked Do(spec.Handler, &Request{ Method: "POST", Path: spec.TokenEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "grant_type": "refresh_token", "refresh_token": <PASSWORD>RefreshToken, }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusBadRequest, r.Code, debug(r)) assert.Equal(t, "invalid_grant", jsonFieldString(r, "error"), debug(r)) }, }) // check if new refresh token is now inactive if spec.IntrospectionEndpoint != "" { Do(spec.Handler, &Request{ Method: "POST", Path: spec.IntrospectionEndpoint, Username: spec.ConfidentialClientID, Password: <PASSWORD>, Form: map[string]string{ "token": <PASSWORD>, "token_type_hint": "refresh_token", }, Callback: func(r *httptest.ResponseRecorder, rq *http.Request) { assert.Equal(t, http.StatusOK, r.Code, debug(r)) assert.False(t, jsonFieldBool(r, "active"), debug(r)) }, }) } }
oauth2test/general.go
0.514644
0.405449
general.go
starcoder
package fp25519 import ( "errors" "circl/internal/conv" ) // Size in bytes of an element. const Size = 32 // Elt is a prime field element. type Elt [Size]byte func (e Elt) String() string { return conv.BytesLe2Hex(e[:]) } // p is the prime modulus 2^255-19. var p = Elt{ 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, } // P returns the prime modulus 2^255-19. func P() Elt { return p } // ToBytes stores in b the little-endian byte representation of x. func ToBytes(b []byte, x *Elt) error { if len(b) != Size { return errors.New("wrong size") } Modp(x) copy(b, x[:]) return nil } // IsZero returns true if x is equal to 0. func IsZero(x *Elt) bool { Modp(x); return *x == Elt{} } // SetOne assigns x=1. func SetOne(x *Elt) { *x = Elt{}; x[0] = 1 } // Neg calculates z = -x. func Neg(z, x *Elt) { Sub(z, &p, x) } // InvSqrt calculates z = sqrt(x/y) iff x/y is a quadratic-residue, which is // indicated by returning isQR = true. Otherwise, when x/y is a quadratic // non-residue, z will have an undetermined value and isQR = false. func InvSqrt(z, x, y *Elt) (isQR bool) { sqrtMinusOne := &Elt{ 0xb0, 0xa0, 0x0e, 0x4a, 0x27, 0x1b, 0xee, 0xc4, 0x78, 0xe4, 0x2f, 0xad, 0x06, 0x18, 0x43, 0x2f, 0xa7, 0xd7, 0xfb, 0x3d, 0x99, 0x00, 0x4d, 0x2b, 0x0b, 0xdf, 0xc1, 0x4f, 0x80, 0x24, 0x83, 0x2b, } t0, t1, t2, t3 := &Elt{}, &Elt{}, &Elt{}, &Elt{} Mul(t0, x, y) // t0 = u*v Sqr(t1, y) // t1 = v^2 Mul(t2, t0, t1) // t2 = u*v^3 Sqr(t0, t1) // t0 = v^4 Mul(t1, t0, t2) // t1 = u*v^7 var Tab [4]*Elt Tab[0] = &Elt{} Tab[1] = &Elt{} Tab[2] = t3 Tab[3] = t1 *Tab[0] = *t1 Sqr(Tab[0], Tab[0]) Sqr(Tab[1], Tab[0]) Sqr(Tab[1], Tab[1]) Mul(Tab[1], Tab[1], Tab[3]) Mul(Tab[0], Tab[0], Tab[1]) Sqr(Tab[0], Tab[0]) Mul(Tab[0], Tab[0], Tab[1]) Sqr(Tab[1], Tab[0]) for i := 0; i < 4; i++ { Sqr(Tab[1], Tab[1]) } Mul(Tab[1], Tab[1], Tab[0]) Sqr(Tab[2], Tab[1]) for i := 0; i < 4; i++ { Sqr(Tab[2], Tab[2]) } Mul(Tab[2], Tab[2], Tab[0]) Sqr(Tab[1], Tab[2]) for i := 0; i < 14; i++ { Sqr(Tab[1], Tab[1]) } Mul(Tab[1], Tab[1], Tab[2]) Sqr(Tab[2], Tab[1]) for i := 0; i < 29; i++ { Sqr(Tab[2], Tab[2]) } Mul(Tab[2], Tab[2], Tab[1]) Sqr(Tab[1], Tab[2]) for i := 0; i < 59; i++ { Sqr(Tab[1], Tab[1]) } Mul(Tab[1], Tab[1], Tab[2]) for i := 0; i < 5; i++ { Sqr(Tab[1], Tab[1]) } Mul(Tab[1], Tab[1], Tab[0]) Sqr(Tab[2], Tab[1]) for i := 0; i < 124; i++ { Sqr(Tab[2], Tab[2]) } Mul(Tab[2], Tab[2], Tab[1]) Sqr(Tab[2], Tab[2]) Sqr(Tab[2], Tab[2]) Mul(Tab[2], Tab[2], Tab[3]) Mul(z, t3, t2) // z = xy^(p+3)/8 = xy^3*(xy^7)^(p-5)/8 // Checking whether y z^2 == x Sqr(t0, z) // t0 = z^2 Mul(t0, t0, y) // t0 = yz^2 Sub(t1, t0, x) // t1 = t0-u Add(t2, t0, x) // t2 = t0+u if IsZero(t1) { return true } else if IsZero(t2) { Mul(z, z, sqrtMinusOne) // z = z*sqrt(-1) return true } else { return false } } // Inv calculates z = 1/x mod p. func Inv(z, x *Elt) { x0, x1, x2 := &Elt{}, &Elt{}, &Elt{} Sqr(x1, x) Sqr(x0, x1) Sqr(x0, x0) Mul(x0, x0, x) Mul(z, x0, x1) Sqr(x1, z) Mul(x0, x0, x1) Sqr(x1, x0) for i := 0; i < 4; i++ { Sqr(x1, x1) } Mul(x0, x0, x1) Sqr(x1, x0) for i := 0; i < 9; i++ { Sqr(x1, x1) } Mul(x1, x1, x0) Sqr(x2, x1) for i := 0; i < 19; i++ { Sqr(x2, x2) } Mul(x2, x2, x1) for i := 0; i < 10; i++ { Sqr(x2, x2) } Mul(x2, x2, x0) Sqr(x0, x2) for i := 0; i < 49; i++ { Sqr(x0, x0) } Mul(x0, x0, x2) Sqr(x1, x0) for i := 0; i < 99; i++ { Sqr(x1, x1) } Mul(x1, x1, x0) for i := 0; i < 50; i++ { Sqr(x1, x1) } Mul(x1, x1, x2) for i := 0; i < 5; i++ { Sqr(x1, x1) } Mul(z, z, x1) } // Cmov assigns y to x if n is 1. func Cmov(x, y *Elt, n uint) { cmov(x, y, n) } // Cswap interchanges x and y if n is 1. func Cswap(x, y *Elt, n uint) { cswap(x, y, n) } // Add calculates z = x+y mod p. func Add(z, x, y *Elt) { add(z, x, y) } // Sub calculates z = x-y mod p. func Sub(z, x, y *Elt) { sub(z, x, y) } // AddSub calculates (x,y) = (x+y mod p, x-y mod p). func AddSub(x, y *Elt) { addsub(x, y) } // Mul calculates z = x*y mod p. func Mul(z, x, y *Elt) { mul(z, x, y) } // Sqr calculates z = x^2 mod p. func Sqr(z, x *Elt) { sqr(z, x) } // Modp ensures that z is between [0,p-1]. func Modp(z *Elt) { modp(z) }
src/circl/math/fp25519/fp.go
0.602179
0.523299
fp.go
starcoder
package triplestore // Triple consists of a subject, a predicate and a object type Triple interface { Subject() string Predicate() string Object() Object Equal(Triple) bool } // Object is a resource (i.e. IRI), a literal or a blank node. type Object interface { Literal() (Literal, bool) Resource() (string, bool) Bnode() (string, bool) Equal(Object) bool } // Literal is a unicode string associated with a datatype (ex: string, integer, ...). type Literal interface { Type() XsdType Value() string Lang() string } type triple struct { sub, pred string isSubBnode bool obj object triKey string } func (t *triple) Object() Object { return t.obj } func (t *triple) Subject() string { return t.sub } func (t *triple) Predicate() string { return t.pred } func (t *triple) key() string { if t.triKey == "" { var sub string if t.isSubBnode { sub = "_:" + t.sub } else { sub = "<" + t.sub + ">" } t.triKey = sub + "<" + t.pred + ">" + t.obj.key() return t.triKey } return t.triKey } func (t *triple) clone() *triple { return &triple{ sub: t.sub, pred: t.pred, obj: t.obj, triKey: t.triKey, } } func (t *triple) Equal(other Triple) bool { switch { case t == nil: return other == nil case other == nil: return false default: otherT, ok := other.(*triple) if !ok { return false } return t.key() == otherT.key() } } type object struct { isLit, isBnode bool resource, bnode string lit literal } func (o object) Literal() (Literal, bool) { return o.lit, o.isLit } func (o object) Resource() (string, bool) { return o.resource, !o.isLit } func (o object) Bnode() (string, bool) { return o.bnode, o.isBnode } func (o object) key() string { if o.isLit { if o.lit.langtag != "" { return "\"" + o.lit.val + "\"@" + o.lit.langtag } return "\"" + o.lit.val + "\"^^<" + string(o.lit.typ) + ">" } if o.isBnode { return "_:" + o.bnode } return "<" + o.resource + ">" } func (o object) Equal(other Object) bool { lit, ok := o.Literal() otherLit, otherOk := other.Literal() if ok != otherOk { return false } if ok { return lit.Type() == otherLit.Type() && lit.Value() == otherLit.Value() } res, ok := o.Resource() otherRes, otherOk := other.Resource() if ok != otherOk { return false } if ok { return res == otherRes } return true } type literal struct { typ XsdType val, langtag string } func (l literal) Type() XsdType { return l.typ } func (l literal) Value() string { return l.val } func (l literal) Lang() string { return l.langtag }
vendor/github.com/wallix/triplestore/rdf.go
0.731922
0.455199
rdf.go
starcoder
package data import ( "errors" "fmt" "github.com/PolymerGuy/golmes/fileutils" "github.com/PolymerGuy/golmes/maths" "github.com/pkelchte/spline" "gonum.org/v1/gonum/floats" "log" "math" "sort" ) type DataReader interface { Read() []float64 } type DataReaderWithArgs interface { Read() []float64 ReadArgs() []float64 ReadAt([]float64) []float64 } type Comparator interface { Compare(dataset DataReaderWithArgs) (float64, error) } type Serie []float64 type SerieWithArgs struct { arguments DataReader functionValues DataReader } type Pair struct { data1 DataReader data2 DataReader } type PairWithArgs struct { data1 DataReaderWithArgs data2 DataReaderWithArgs commonArgs DataReader } type DataFromFile struct { fileName string key string } type WeightedPairs struct { objectiveFunctions []Pair weights []float64 } func NewSeries(data []float64) Serie { return data } func NewSeriesWithArgs(arguments DataReader, functionValues DataReader) SerieWithArgs { return SerieWithArgs{functionValues: functionValues, arguments: arguments} } func NewPair(data1 DataReader, data2 DataReader) Pair { return Pair{data1, data2} } func NewPairWithArgs(data1 DataReaderWithArgs, data2 DataReaderWithArgs, commonArgs DataReader) PairWithArgs { return PairWithArgs{data1, data2, commonArgs} } func NewSeriesFromFile(fileName string, key string) DataFromFile { return DataFromFile{fileName, key} } func (pair Pair) GetFields() []DataReader { return []DataReader{pair.data1, pair.data2} } func (pair PairWithArgs) GetFields() []DataReaderWithArgs { return []DataReaderWithArgs{pair.data1, pair.data2} } func (series DataFromFile) Read() []float64 { return fileutils.GetColumnFromCSVFile(series.fileName, series.key) } func (series Serie) Read() []float64 { return series } func (series SerieWithArgs) Read() []float64 { return series.functionValues.Read() } func (series SerieWithArgs) ReadAt(xs []float64) []float64 { if !sort.Float64sAreSorted(series.arguments.Read()) { fmt.Println("Args arguments: ", series.arguments.Read()) log.Fatal("arguments are not sorted") } //interpolator := spline.NewCubic(series.arguments.Read(), series.functionValues.Read()) // Check if it works properly... // Check if xs is witin the args of series if !floats.Equal(maths.EnclosedWithin(xs, series.arguments.Read()), xs) { log.Fatalln("Tried to evaluate interpolator outside its domain") } s := spline.Spline{} if len(series.arguments.Read()) != len(series.functionValues.Read()) { log.Fatalln("Cannot initialize interpolator, arguments and values are of unequal length") } s.Set_points(series.arguments.Read(), series.functionValues.Read(), true) results := []float64{} for _, x := range xs { results = append(results, s.Operate(x)) } return results } func (series SerieWithArgs) ReadArgs() []float64 { return series.arguments.Read() } func (data Pair) Compare() (float64, error) { data1 := data.data1.Read() data2 := data.data2.Read() rmsError, err := maths.RMSError(data1, data2) if err != nil { return math.Inf(1), errors.New(fmt.Sprintf("Comparison of data failed: %s", err)) } return rmsError, nil } // Compare return the RMS error of two series, synced to the largest common overlapping range. // If an commonArgs serie is provided, this is used to sync the series // TODO: Extend Compare to return an error as well... func (data PairWithArgs) Compare(datas2 DataReaderWithArgs) (float64, error) { args := []float64{} switch len(data.commonArgs.Read()) { case 0: args = maths.EnclosedWithin(data.data1.ReadArgs(), datas2.ReadArgs()) default: // The common arguments should be enclosed within the args of serie1 and serie2 commonArguments := maths.EnclosedWithin(data.data1.ReadArgs(), datas2.ReadArgs()) args = maths.EnclosedWithin(commonArguments, data.commonArgs.Read()) } if floats.Equal(args, []float64{}) { return math.Inf(1), errors.New(fmt.Sprintln("No overlapping arguments for compare")) } data1 := data.data1.ReadAt(args) data2 := datas2.ReadAt(args) rmsError, err := maths.RMSError(data1, data2) if err != nil { return math.Inf(1), errors.New(fmt.Sprintf("Comparison of data failed: %s", err)) } return rmsError, nil } func (objFuncs WeightedPairs) Compare() (float64, error) { var weightedFuncVals float64 for i, objFunc := range objFuncs.objectiveFunctions { comp, err := objFunc.Compare() if err != nil { return math.Inf(1), errors.New(fmt.Sprintf("Comparison of data failed: %s", err)) } weightedFuncVals = weightedFuncVals + objFuncs.weights[i]*comp } return weightedFuncVals, nil }
data/data.go
0.553747
0.432183
data.go
starcoder
package suffixtree import ( "sort" ) type Node struct { /* * The payload array used to store the data (indexes) associated with this node. * In this case, it is used to store all property indexes. */ Data []int /** * The set of edges starting from this Node */ Edges []*Edge /** * The suffix link as described in Ukkonen's paper. * if str is the string denoted by the path from the root to this, this.suffix * is the node denoted by the path that corresponds to str without the first Symbol. */ suffix *Node } /* * getData returns the first numElements elements from the ones associated to this node. * * Gets data from the payload of both this node and its children, the string representation * of the path to this node is a substring of the one of the children nodes. * * @param numElements the number of results to return. Use <=0 to get all * @return the first numElements associated to this node and children */ func (n *Node) getData(numElements int) (ret []int) { if numElements > 0 { if numElements > len(n.Data) { numElements -= len(n.Data) ret = n.Data } else { ret = n.Data[:numElements] return } } else { ret = n.Data } // need to get more matches from child nodes. This is what may waste time for _, edge := range n.Edges { data := edge.Node.getData(numElements) NEXTIDX: for _, idx := range data { for _, v := range ret { if v == idx { continue NEXTIDX } } if numElements > 0 { numElements-- } ret = append(ret, idx) } if numElements == 0 { break } } return } // addRef adds the given index to the set of indexes associated with this func (n *Node) addRef(index int) { if n.contains(index) { return } n.addIndex(index) // add this reference to all the suffixes as well iter := n.suffix for iter != nil { if iter.contains(index) { break } iter.addRef(index) iter = iter.suffix } } func (n *Node) contains(index int) bool { i := sort.SearchInts(n.Data, index) return i < len(n.Data) && n.Data[i] == index } func (n *Node) addEdge(r Symbol, e *Edge) { if idx := n.search(r); idx == -1 { n.Edges = append(n.Edges, e) sort.Slice(n.Edges, func(i, j int) bool { return n.Edges[i].Label[0].IsLess(n.Edges[j].Label[0]) }) } else { n.Edges[idx] = e } } func (n *Node) getEdge(r Symbol) *Edge { idx := n.search(r) if idx < 0 { return nil } return n.Edges[idx] } func (n *Node) search(r Symbol) int { idx := sort.Search(len(n.Edges), func(i int) bool { return !n.Edges[i].Label[0].IsLess(r) }) if idx < len(n.Edges) && n.Edges[idx].Label[0].IsEqual(r) { return idx } return -1 } func (n *Node) addIndex(idx int) { n.Data = append(n.Data, idx) } func newNode() *Node { return &Node{} }
node.go
0.653348
0.491273
node.go
starcoder
package ast import ( "fmt" "go.etcd.io/bbolt" "time" ) type NodeType int const ( NodeTypeBool NodeType = iota NodeTypeDatetime NodeTypeFloat64 NodeTypeInt64 NodeTypeString NodeTypeAnyType NodeTypeOther ) func NodeTypeName(nodeType NodeType) string { return nodeTypeNames[nodeType] } var nodeTypeNames = map[NodeType]string{ NodeTypeString: "string", NodeTypeInt64: "number", NodeTypeFloat64: "number", NodeTypeDatetime: "date", NodeTypeBool: "bool", NodeTypeOther: "other", NodeTypeAnyType: "any", } type BinaryOp int const ( BinaryOpEQ BinaryOp = iota BinaryOpNEQ BinaryOpLT BinaryOpLTE BinaryOpGT BinaryOpGTE BinaryOpIn BinaryOpNotIn BinaryOpBetween BinaryOpNotBetween BinaryOpContains BinaryOpNotContains ) func (op BinaryOp) String() string { return binaryOpNames[op] } var binaryOpNames = map[BinaryOp]string{ BinaryOpEQ: "=", BinaryOpNEQ: "!=", BinaryOpLT: "<", BinaryOpLTE: "<=", BinaryOpGT: ">", BinaryOpGTE: ">=", BinaryOpIn: "in", BinaryOpNotIn: "not in", BinaryOpBetween: "between", BinaryOpNotBetween: "not between", BinaryOpContains: "contains", BinaryOpNotContains: "not contains", } var binaryOpValues = map[string]BinaryOp{ "=": BinaryOpEQ, "!=": BinaryOpNEQ, "<": BinaryOpLT, "<=": BinaryOpLTE, ">": BinaryOpGT, ">=": BinaryOpGTE, } type SetFunction int const ( SetFunctionAllOf SetFunction = iota SetFunctionAnyOf SetFunctionCount SetFunctionIsEmpty ) var BoolNodeTrue = NewBoolConstNode(true) var SetFunctionNames = map[SetFunction]string{ SetFunctionAllOf: "allOf", SetFunctionAnyOf: "anyOf", SetFunctionCount: "count", SetFunctionIsEmpty: "isEmpty", } type SymbolTypes interface { GetSymbolType(name string) (NodeType, bool) GetSetSymbolTypes(name string) SymbolTypes IsSet(name string) (bool, bool) } type Symbols interface { SymbolTypes EvalBool(name string) *bool EvalString(name string) *string EvalInt64(name string) *int64 EvalFloat64(name string) *float64 EvalDatetime(name string) *time.Time IsNil(name string) bool OpenSetCursor(name string) SetCursor OpenSetCursorForQuery(name string, query Query) SetCursor } type SetCursorProvider func(tx *bbolt.Tx, forward bool) SetCursor type SetCursor interface { Next() IsValid() bool Current() []byte } type SeekableSetCursor interface { SetCursor Seek([]byte) } type TypeSeekableSetCursor interface { SeekableSetCursor SeekToString(val string) } type Node interface { fmt.Stringer GetType() NodeType Accept(visitor Visitor) IsConst() bool } type TypeTransformable interface { Node TypeTransform(s SymbolTypes) (Node, error) } type BoolNode interface { Node // NOTE: IF we want to reintroduce error reporting on Eval* at some point in the future, probably better plan // would be to incorporate into Symbols, which we can then retrieve at the top level, rather than threading // it through here everywhere, similar to how we do it with TypedBucket EvalBool(s Symbols) bool } type BoolTypeTransformable interface { BoolNode TypeTransformBool(s SymbolTypes) (BoolNode, error) } type DatetimeNode interface { Node EvalDatetime(s Symbols) *time.Time } type Float64Node interface { StringNode EvalFloat64(s Symbols) *float64 } type Int64Node interface { StringNode EvalInt64(s Symbols) *int64 ToFloat64() Float64Node } type StringNode interface { Node EvalString(s Symbols) *string } type SymbolNode interface { Node Symbol() string } type AsStringArrayable interface { AsStringArray() *StringArrayNode } type SortField interface { fmt.Stringer Symbol() string IsAscending() bool } type Query interface { BoolNode GetPredicate() BoolNode SetPredicate(BoolNode) // GetSortFields returns the fields on which to sort. Returning nil or empty means the default sort order // will be used, usually by id ascending GetSortFields() []SortField AdoptSortFields(query Query) error // GetSkip returns the number of rows to skip. nil, or a values less than one will mean no rows skipped GetSkip() *int64 // GetLimit returns the maximum number of rows to return. Returning nil will use the system configured // default for max rows. Returning -1 means do not limit results. GetLimit() *int64 SetSkip(int64) SetLimit(int64) }
storage/ast/node.go
0.612541
0.42919
node.go
starcoder
package square // Represents a tax that applies to one or more line item in the order. Fixed-amount, order-scoped taxes are distributed across all non-zero line item totals. The amount distributed to each line item is relative to the amount the item contributes to the order subtotal. type OrderLineItemTax struct { // Unique ID that identifies the tax only within this order. Uid string `json:"uid,omitempty"` // The catalog object id referencing `CatalogTax`. CatalogObjectId string `json:"catalog_object_id,omitempty"` // The tax's name. Name string `json:"name,omitempty"` // Indicates the calculation method used to apply the tax. See [OrderLineItemTaxType](#type-orderlineitemtaxtype) for possible values Type_ string `json:"type,omitempty"` // The percentage of the tax, as a string representation of a decimal number. For example, a value of `\"7.25\"` corresponds to a percentage of 7.25%. Percentage string `json:"percentage,omitempty"` // Application-defined data attached to this tax. Metadata fields are intended to store descriptive references or associations with an entity in another system or store brief information about the object. Square does not process this field; it only stores and returns it in relevant API calls. Do not use metadata to store any sensitive information (personally identifiable information, card details, etc.). Keys written by applications must be 60 characters or less and must be in the character set `[a-zA-Z0-9_-]`. Entries may also include metadata generated by Square. These keys are prefixed with a namespace, separated from the key with a ':' character. Values have a max length of 255 characters. An application may have up to 10 entries per metadata field. Entries written by applications are private and can only be read or modified by the same application. See [Metadata](https://developer.squareup.com/docs/build-basics/metadata) for more information. Metadata map[string]string `json:"metadata,omitempty"` AppliedMoney *Money `json:"applied_money,omitempty"` // Indicates the level at which the tax applies. For `ORDER` scoped taxes, Square generates references in `applied_taxes` on all order line items that do not have them. For `LINE_ITEM` scoped taxes, the tax will only apply to line items with references in their `applied_taxes` field. This field is immutable. To change the scope, you must delete the tax and re-add it as a new tax. See [OrderLineItemTaxScope](#type-orderlineitemtaxscope) for possible values Scope string `json:"scope,omitempty"` // Determines whether the tax was automatically applied to the order based on the catalog configuration. For an example, see [Automatically Apply Taxes to an Order](https://developer.squareup.com/docs/docs/orders-api/apply-taxes-and-discounts/auto-apply-taxes). AutoApplied bool `json:"auto_applied,omitempty"` }
square/model_order_line_item_tax.go
0.846419
0.489442
model_order_line_item_tax.go
starcoder
// This package implements translation between // unsigned integer values and byte sequences. package binary import ( "math"; "io"; "os"; "reflect"; ) // A ByteOrder specifies how to convert byte sequences into // 16-, 32-, or 64-bit unsigned integers. type ByteOrder interface { Uint16(b []byte) uint16; Uint32(b []byte) uint32; Uint64(b []byte) uint64; PutUint16([]byte, uint16); PutUint32([]byte, uint32); PutUint64([]byte, uint64); String() string; } // This is byte instead of struct{} so that it can be compared, // allowing, e.g., order == binary.LittleEndian. type unused byte var LittleEndian ByteOrder = littleEndian(0) var BigEndian ByteOrder = bigEndian(0) type littleEndian unused func (littleEndian) Uint16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8; } func (littleEndian) PutUint16(b []byte, v uint16) { b[0] = byte(v); b[1] = byte(v>>8); } func (littleEndian) Uint32(b []byte) uint32 { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24; } func (littleEndian) PutUint32(b []byte, v uint32) { b[0] = byte(v); b[1] = byte(v>>8); b[2] = byte(v>>16); b[3] = byte(v>>24); } func (littleEndian) Uint64(b []byte) uint64 { return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56; } func (littleEndian) PutUint64(b []byte, v uint64) { b[0] = byte(v); b[1] = byte(v>>8); b[2] = byte(v>>16); b[3] = byte(v>>24); b[4] = byte(v>>32); b[5] = byte(v>>40); b[6] = byte(v>>48); b[7] = byte(v>>56); } func (littleEndian) String() string { return "LittleEndian"; } func (littleEndian) GoString() string { return "binary.LittleEndian"; } type bigEndian unused func (bigEndian) Uint16(b []byte) uint16 { return uint16(b[1]) | uint16(b[0])<<8; } func (bigEndian) PutUint16(b []byte, v uint16) { b[0] = byte(v>>8); b[1] = byte(v); } func (bigEndian) Uint32(b []byte) uint32 { return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24; } func (bigEndian) PutUint32(b []byte, v uint32) { b[0] = byte(v>>24); b[1] = byte(v>>16); b[2] = byte(v>>8); b[3] = byte(v); } func (bigEndian) Uint64(b []byte) uint64 { return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56; } func (bigEndian) PutUint64(b []byte, v uint64) { b[0] = byte(v>>56); b[1] = byte(v>>48); b[2] = byte(v>>40); b[3] = byte(v>>32); b[4] = byte(v>>24); b[5] = byte(v>>16); b[6] = byte(v>>8); b[7] = byte(v); } func (bigEndian) String() string { return "BigEndian"; } func (bigEndian) GoString() string { return "binary.BigEndian"; } // Read reads structured binary data from r into data. // Data must be a pointer to a fixed-size value. // A fixed-size value is either a fixed-size integer // (int8, uint8, int16, uint16, ...) or an array or struct // containing only fixed-size values. Bytes read from // r are decoded using order and written to successive // fields of the data. func Read(r io.Reader, order ByteOrder, data interface{}) os.Error { v := reflect.NewValue(data).(*reflect.PtrValue).Elem(); size := sizeof(v.Type()); if size < 0 { return os.NewError("binary.Read: invalid type " + v.Type().String()); } d := &decoder{order: order, buf: make([]byte, size)}; if _, err := io.ReadFull(r, d.buf); err != nil { return err; } d.value(v); return nil; } func sizeof(t reflect.Type) int { switch t := t.(type) { case *reflect.ArrayType: n := sizeof(t.Elem()); if n < 0 { return -1; } return t.Len() * n; case *reflect.StructType: sum := 0; for i, n := 0, t.NumField(); i < n; i++ { s := sizeof(t.Field(i).Type); if s < 0 { return -1; } sum += s; } return sum; case *reflect.Uint8Type: return 1; case *reflect.Uint16Type: return 2; case *reflect.Uint32Type: return 4; case *reflect.Uint64Type: return 8; case *reflect.Int8Type: return 1; case *reflect.Int16Type: return 2; case *reflect.Int32Type: return 4; case *reflect.Int64Type: return 8; case *reflect.Float32Type: return 4; case *reflect.Float64Type: return 8; } return -1; } type decoder struct { order ByteOrder; buf []byte; } func (d *decoder) uint8() uint8 { x := d.buf[0]; d.buf = d.buf[1:len(d.buf)]; return x; } func (d *decoder) uint16() uint16 { x := d.order.Uint16(d.buf[0:2]); d.buf = d.buf[2:len(d.buf)]; return x; } func (d *decoder) uint32() uint32 { x := d.order.Uint32(d.buf[0:4]); d.buf = d.buf[4:len(d.buf)]; return x; } func (d *decoder) uint64() uint64 { x := d.order.Uint64(d.buf[0:8]); d.buf = d.buf[8:len(d.buf)]; return x; } func (d *decoder) int8() int8 { return int8(d.uint8()); } func (d *decoder) int16() int16 { return int16(d.uint16()); } func (d *decoder) int32() int32 { return int32(d.uint32()); } func (d *decoder) int64() int64 { return int64(d.uint64()); } func (d *decoder) value(v reflect.Value) { switch v := v.(type) { case *reflect.ArrayValue: l := v.Len(); for i := 0; i < l; i++ { d.value(v.Elem(i)); } case *reflect.StructValue: l := v.NumField(); for i := 0; i < l; i++ { d.value(v.Field(i)); } case *reflect.Uint8Value: v.Set(d.uint8()); case *reflect.Uint16Value: v.Set(d.uint16()); case *reflect.Uint32Value: v.Set(d.uint32()); case *reflect.Uint64Value: v.Set(d.uint64()); case *reflect.Int8Value: v.Set(d.int8()); case *reflect.Int16Value: v.Set(d.int16()); case *reflect.Int32Value: v.Set(d.int32()); case *reflect.Int64Value: v.Set(d.int64()); case *reflect.Float32Value: v.Set(math.Float32frombits(d.uint32())); case *reflect.Float64Value: v.Set(math.Float64frombits(d.uint64())); } }
src/pkg/encoding/binary/binary.go
0.678966
0.418043
binary.go
starcoder
package geometry import ( "math" "time" "github.com/g3n/engine/geometry" "github.com/g3n/engine/graphic" "github.com/g3n/engine/light" "github.com/g3n/engine/material" "github.com/g3n/engine/math32" "github.com/g3n/engine/util/helper" "github.com/g3n/g3nd/app" ) func init() { app.DemoMap["geometry.torus"] = &Torus{} } type Torus struct { torus1 *graphic.Mesh normals *helper.Normals } // Start is called once at the start of the demo. func (t *Torus) Start(a *app.App) { // Add directional red light from right l1 := light.NewDirectional(&math32.Color{1, 0, 0}, 1.0) l1.SetPosition(1, 0, 0) a.Scene().Add(l1) // Add directional green light from top l2 := light.NewDirectional(&math32.Color{0, 1, 0}, 1.0) l2.SetPosition(0, 1, 0) a.Scene().Add(l2) // Add directional blue light from front l3 := light.NewDirectional(&math32.Color{0, 0, 1}, 1.0) l3.SetPosition(0, 0, 1) a.Scene().Add(l3) // Add torus at upper-left geom1 := geometry.NewTorus(1, 0.25, 8, 8, 2*math.Pi) mat1 := material.NewStandard(&math32.Color{0, 0, 0.5}) t.torus1 = graphic.NewMesh(geom1, mat1) mat1.SetWireframe(true) mat1.SetSide(material.SideDouble) t.torus1.SetPosition(-2, 1.5, 0) a.Scene().Add(t.torus1) // Add torus at upper-right geom2 := geometry.NewTorus(1, 0.25, 32, 32, 2*math.Pi) mat2 := material.NewStandard(&math32.Color{1, 1, 1}) torus2 := graphic.NewMesh(geom2, mat2) torus2.SetPosition(2, 1.5, 0) a.Scene().Add(torus2) // Add torus at bottom-left geom3 := geometry.NewTorus(1, 0.25, 32, 32, 2*math.Pi) mat3 := material.NewStandard(&math32.Color{0.5, 0.5, 0.5}) torus3 := graphic.NewMesh(geom3, mat3) torus3.SetPosition(-2, -1.5, 0) a.Scene().Add(torus3) // Add torus at bottom-right geom4 := geometry.NewTorus(1, 0.25, 64, 64, 3*math.Pi/2) mat4 := material.NewStandard(&math32.Color{0.5, 0.5, 0.5}) mat4.SetSide(material.SideDouble) torus4 := graphic.NewMesh(geom4, mat4) torus4.SetPosition(2, -1.5, 0) a.Scene().Add(torus4) // Create axes helper axes := helper.NewAxes(2) a.Scene().Add(axes) // Adds normals helper t.normals = helper.NewNormals(t.torus1, 0.5, &math32.Color{0, 1, 0}, 1) a.Scene().Add(t.normals) } // Update is called every frame. func (t *Torus) Update(a *app.App, deltaTime time.Duration) { // Rotate at 1 rotation each 5 seconds delta := float32(deltaTime.Seconds()) * 2 * math32.Pi / 5 t.torus1.RotateZ(delta) t.normals.Update() } // Cleanup is called once at the end of the demo. func (t *Torus) Cleanup(a *app.App) {}
demos/geometry/torus.go
0.667364
0.458106
torus.go
starcoder
package main import ( "time" "math/rand" sf "bitbucket.org/krepa098/gosfml2" ) type Enemy struct { HasChild bool HasFather bool HasMother bool FatherHasWeapon bool Shape *sf.RectangleShape } func NewEnemy(WorldWidth int, Textures []Texture) *Enemy { Enemy := new(Enemy) rand.Seed(time.Now().UnixNano()) Enemy.HasChild = true if rand.Intn(100) < 80 { Enemy.HasMother = true } else { Enemy.HasMother = false } if Enemy.HasMother == true { if rand.Intn(1) == 1 { Enemy.HasFather = true } else { Enemy.HasFather = false } } else { Enemy.HasFather = true } if rand.Intn(1000) == 1 { Enemy.FatherHasWeapon = true } else { Enemy.FatherHasWeapon = false } Enemy.Shape, _ = sf.NewRectangleShape() if Enemy.HasMother == true && Enemy.HasFather == true && Enemy.HasChild == true { Enemy.Shape.SetSize(sf.Vector2f{96, 32}) Enemy.Shape.SetFillColor(sf.Color{128,128,128,255}) Enemy.Shape.SetTexture((GetTexture("ParentsAndChild.png", Textures)).Data, false) } else if Enemy.HasMother == true && Enemy.HasFather == false && Enemy.HasChild == true { Enemy.Shape.SetSize(sf.Vector2f{64, 32}) Enemy.Shape.SetFillColor(sf.Color{128,0,128,255}) Enemy.Shape.SetTexture((GetTexture("MotherAndChild.png", Textures)).Data, false) } else if Enemy.HasMother == false && Enemy.HasFather == true && Enemy.HasFather == true { Enemy.Shape.SetSize(sf.Vector2f{64, 32}) if Enemy.FatherHasWeapon == true { Enemy.Shape.SetFillColor(sf.Color{0,128,255,255}) } else { Enemy.Shape.SetFillColor(sf.Color{0,128,128,255}) } Enemy.Shape.SetTexture((GetTexture("FatherAndChild.png", Textures)).Data, false) } x := rand.Intn(WorldWidth); if x > 96 { x -= 96 } Enemy.Shape.SetPosition(sf.Vector2f{float32(x), 0.0}) return Enemy } func (this *Enemy) GetHasFather() bool { return this.HasFather } func (this *Enemy) GetHasMother() bool { return this.HasMother } func (this *Enemy) GetFatherHasWeapon() bool { return this.FatherHasWeapon } func (this *Enemy) MoveDown() { this.Shape.Move(sf.Vector2f{0.0, 5.0}) } func (this *Enemy) Collision(Player *Player) bool { PlayerRect := Player.Shape.GetGlobalBounds() EnemyRect := this.Shape.GetGlobalBounds() test, _ := PlayerRect.Intersects(EnemyRect); return test; } func (this *Enemy) Destroy(WorldHeight int) bool { position := this.Shape.GetPosition() if position.Y > float32(WorldHeight) { return true } return false } func (this *Enemy) Draw(RenderWindow *sf.RenderWindow, RenderStates sf.RenderStates) { RenderWindow.Draw(this.Shape, RenderStates) }
enemy.go
0.506836
0.501648
enemy.go
starcoder
package metadata const ( // Equals is a mathematical symbol used to indicate equality. // It is also a Drama/Science fiction film from 2015. Equals Operator = "=" // GreaterThan is a mathematical symbol that denotes an inequality between two values. // It is typically placed between the two values being compared and signals that the first number is greater than the second number. GreaterThan Operator = ">" // GreaterThanEquals is a mathematical symbol that denotes an inequality between two values. // It is typically placed between the two values being compared and signals that the first number is greater than or equal to the second number. GreaterThanEquals Operator = ">=" // LowerThan is a mathematical symbol that denotes an inequality between two values. // It is typically placed between the two values being compared and signals that the first number is less than the second number. LowerThan Operator = "<" // LowerThanEquals is a mathematical symbol that denotes an inequality between two values. // It is typically placed between the two values being compared and signals that the first number is less than or equal to the second number. LowerThanEquals Operator = "<=" // NotEquals is a mathematical symbol that denotes an inequality between two values. // It is typically placed between the two values being compared and signals that the first number is not equal the second number. NotEquals Operator = "!=" ) var ( // Ensure emptyMatcher implements the Matcher interface _ Matcher = new(emptyMatcher) // Ensure constraintMatcher implements the Matcher interface _ Matcher = &constraintMatcher{} ) type ( // Operator represents a operation for a constraint Operator string // Matcher is a struct used to register constraints that should be applied // to the metadata of for example a Message Matcher interface { // Iterate calls the callback for each constraint Iterate(callback func(constraint Constraint)) } emptyMatcher int constraintMatcher struct { Matcher constraint Constraint } ) // NewMatcher return a new Matcher instance without any constraints func NewMatcher() Matcher { return new(emptyMatcher) } // WithConstraint add a constraint to the matcher func WithConstraint(parent Matcher, field string, operator Operator, value interface{}) Matcher { return &constraintMatcher{ parent, Constraint{ field: field, operator: operator, value: value, }, } } func (*emptyMatcher) Iterate(callback func(constraint Constraint)) { } func (c *constraintMatcher) Iterate(callback func(constraint Constraint)) { if c.Matcher != nil { c.Matcher.Iterate(callback) } callback(c.constraint) }
metadata/matcher.go
0.866486
0.798265
matcher.go
starcoder
// Package algorithm contain some basic algorithm functions. eg. sort, search package algorithm import "github.com/duke-git/lancet/v2/lancetconstraints" // BubbleSort use bubble to sort slice. func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) { for i := 0; i < len(slice); i++ { for j := 0; j < len(slice)-1-i; j++ { isCurrGreatThanNext := comparator.Compare(slice[j], slice[j+1]) == 1 if isCurrGreatThanNext { swap(slice, j, j+1) } } } } // InsertionSort use insertion to sort slice. func InsertionSort[T any](slice []T, comparator lancetconstraints.Comparator) { for i := 0; i < len(slice); i++ { for j := i; j > 0; j-- { isPreLessThanCurrent := comparator.Compare(slice[j], slice[j-1]) == -1 if isPreLessThanCurrent { swap(slice, j, j-1) } else { break } } } } // SelectionSort use selection to sort slice. func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator) { for i := 0; i < len(slice); i++ { min := i for j := i + 1; j < len(slice); j++ { if comparator.Compare(slice[j], slice[min]) == -1 { min = j } } swap(slice, i, min) } } // ShellSort shell sort slice. func ShellSort[T any](slice []T, comparator lancetconstraints.Comparator) { size := len(slice) gap := 1 for gap < size/3 { gap = 3*gap + 1 } for gap >= 1 { for i := gap; i < size; i++ { for j := i; j >= gap && comparator.Compare(slice[j], slice[j-gap]) == -1; j -= gap { swap(slice, j, j-gap) } } gap = gap / 3 } } // QuickSort quick sorting for slice, lowIndex is 0 and highIndex is len(slice)-1 func QuickSort[T any](slice []T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) { if lowIndex < highIndex { p := partition(slice, lowIndex, highIndex, comparator) QuickSort(slice, lowIndex, p-1, comparator) QuickSort(slice, p+1, highIndex, comparator) } } // partition split slice into two parts func partition[T any](slice []T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int { p := slice[highIndex] i := lowIndex for j := lowIndex; j < highIndex; j++ { if comparator.Compare(slice[j], p) == -1 { //slice[j] < p swap(slice, i, j) i++ } } swap(slice, i, highIndex) return i } // HeapSort use heap to sort slice func HeapSort[T any](slice []T, comparator lancetconstraints.Comparator) { size := len(slice) for i := size/2 - 1; i >= 0; i-- { sift(slice, i, size-1, comparator) } for j := size - 1; j > 0; j-- { swap(slice, 0, j) sift(slice, 0, j-1, comparator) } } func sift[T any](slice []T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) { i := lowIndex j := 2*i + 1 temp := slice[i] for j <= highIndex { if j < highIndex && comparator.Compare(slice[j], slice[j+1]) == -1 { //slice[j] < slice[j+1] j++ } if comparator.Compare(temp, slice[j]) == -1 { //tmp < slice[j] slice[i] = slice[j] i = j j = 2*i + 1 } else { break } } slice[i] = temp } // MergeSort merge sorting for slice func MergeSort[T any](slice []T, comparator lancetconstraints.Comparator) { mergeSort(slice, 0, len(slice)-1, comparator) } func mergeSort[T any](slice []T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) { if lowIndex < highIndex { mid := (lowIndex + highIndex) / 2 mergeSort(slice, lowIndex, mid, comparator) mergeSort(slice, mid+1, highIndex, comparator) merge(slice, lowIndex, mid, highIndex, comparator) } } func merge[T any](slice []T, lowIndex, midIndex, highIndex int, comparator lancetconstraints.Comparator) { i := lowIndex j := midIndex + 1 temp := []T{} for i <= midIndex && j <= highIndex { //slice[i] < slice[j] if comparator.Compare(slice[i], slice[j]) == -1 { temp = append(temp, slice[i]) i++ } else { temp = append(temp, slice[j]) j++ } } if i <= midIndex { temp = append(temp, slice[i:midIndex+1]...) } else { temp = append(temp, slice[j:highIndex+1]...) } for k := 0; k < len(temp); k++ { slice[lowIndex+k] = temp[k] } } // CountSort use count sorting for slice func CountSort[T any](slice []T, comparator lancetconstraints.Comparator) []T { size := len(slice) out := make([]T, size) for i := 0; i < size; i++ { count := 0 for j := 0; j < size; j++ { //slice[i] > slice[j] if comparator.Compare(slice[i], slice[j]) == 1 { count++ } } out[count] = slice[i] } return out } // swap two slice value at index i and j func swap[T any](slice []T, i, j int) { slice[i], slice[j] = slice[j], slice[i] }
algorithm/sorter.go
0.586404
0.600598
sorter.go
starcoder
package display import ( "math" "sync" ) // RectangleRasterInput part of options that is passed to rasterizer workers. type RectangleRasterInput struct { // Pixel buffer. Shader needs to output color to buffer with // boffs offset and value calculated by shader. Buffer can use multiple // bytes for pixel. Multiply boffs by pixel size in this case. Buffer []byte BufferWidth int BufferHeight int // Function to call for each fragment. // Shader is responsible for saving pixel to the buffer. Use lambda function that // has access to the buffer to do that. See bit-shader for example. Shader func(o *RectangleShaderOpts) // Raster chunks size (in bits, e.g. 3 bits = 8 pixels). ChunkBits int // Lights model. Lights Lights // Object to convert to index color. Indexizer Indexizer // Any other data to pass to shader. Extra interface{} } // RectangleRasterStatic part of options including input and precalculated for the whole triangle. type RectangleRasterStatic struct { RectangleRasterInput // Percentage texture coords step per pixel. Pxs, Pys float64 } // ShaderOpts options for shader. type RectangleShaderOpts struct { RectangleRasterStatic // Cooridnates in buffer, pixels. X, Y float64 // Percentage texture coords origin. Px, Py float64 // Offset in buffer, pixels. Equal to int(x) + int(y) * BufferWidth. BufferOffset int } // RectangleInfo input data to DrawRectangle call. type RectangleInfo struct { RectangleRasterInput X, Y float64 W, H float64 } // RectangleChunk data for rectangle chunk to pass to rasterizer worker. type RectangleChunk struct { RectangleRasterStatic // Origin x, y, pixels. Xo, Yo float64 // Origin percentage coords. Pxo, Pyo float64 // Offset in buffer, pixels. Equal to x + y * BufferWidth. BufferOffset int // Chunk width in pixels (can be less than chunk size). Width float64 // Chunk height in pixels (can be less than chunk size). Height float64 WG *sync.WaitGroup } func (r *Rasterizer) DrawRectangle(ri RectangleInfo) { r.Run() if ri.Buffer == nil { panic("Rasterizer.DrawRectangle: buffer is not set") } if ri.Shader == nil { panic("Rasterizer.DrawRectangle: shader is not set") } if ri.Lights == nil { panic("Rasterizer.DrawRectangle: lights are not set") } if ri.Indexizer == nil { panic("Rasterizer.DrawRectangle: indexizer is not set") } if ri.ChunkBits == 0 { ri.ChunkBits = 3 } if ri.W == 0 || ri.H == 0 { return } if ri.W < 0 { ri.X += ri.W ri.W = -ri.W } if ri.H < 0 { ri.Y += ri.H ri.H = -ri.H } // Structure that will contain values precomputed for all pixels. rs := RectangleRasterStatic{ RectangleRasterInput: ri.RectangleRasterInput, } // Rounded to nearest pixel coords. sm := 0.5 //1 - math.SmallestNonzeroFloat64 x, y := math.Floor(ri.X+sm), math.Floor(ri.Y+sm) w, h := math.Floor(ri.W), math.Floor(ri.H) rs.Pxs = 1 / w rs.Pys = 1 / h // Initial texture position. var pxd, pyd float64 if x < 0 { pxd = -x * rs.Pxs } if y < 0 { pyd = -y * rs.Pys } // Clip. minX := math.Max(x, 0) minY := math.Max(y, 0) maxX := math.Min(x+w, float64(ri.BufferWidth-1)) maxY := math.Min(y+h, float64(ri.BufferHeight-1)) chunkSize := 1 << ri.ChunkBits chunkSizef := float64(chunkSize) // Steps for chunks. pxCh := chunkSizef * rs.Pxs pyCh := chunkSizef * rs.Pys // Buffer offset for top-left bounding box corner. boffso := int(minX) + int(minY)*ri.BufferWidth var wg sync.WaitGroup py := pyd for y := minY; y < maxY; y += chunkSizef { px := pxd boffs := boffso chunkHeight := maxY - y if chunkHeight > chunkSizef { chunkHeight = chunkSizef } for x := minX; x < maxX; x += chunkSizef { wg.Add(1) chunk := RectangleChunk{ RectangleRasterStatic: rs, Xo: x, Yo: y, Pxo: px, Pyo: py, BufferOffset: boffs, Width: maxX - x, Height: chunkHeight, WG: &wg, } if chunk.Width > chunkSizef { chunk.Width = chunkSizef } r.renderChunk(chunk) px += pxCh boffs += chunkSize } py += pyCh boffso += ri.BufferWidth * chunkSize } wg.Wait() } func (c RectangleChunk) Process() { defer c.WG.Done() maxX := c.Xo + c.Width maxY := c.Yo + c.Height so := RectangleShaderOpts{ RectangleRasterStatic: c.RectangleRasterStatic, } cnt := 0 py := c.Pyo for y := c.Yo; y < maxY; y++ { px := c.Pxo boffs := c.BufferOffset for x := c.Xo; x < maxX; x++ { so.BufferOffset = boffs so.X = x so.Y = y so.Px = px so.Py = py c.Shader(&so) px += c.Pxs boffs++ cnt++ } py += c.Pys c.BufferOffset += c.BufferWidth } }
pkg/display/rectangle.go
0.740456
0.527195
rectangle.go
starcoder
package main import ( XPression "github.com/FlowingSPDG/XPression-go" "github.com/c-bata/go-prompt" ) func completer(in prompt.Document) []prompt.Suggest { s := []prompt.Suggest{ {Text: "CLFB",Description: "Clears framebuffer number buffer. For example, CLFB 0000 clears framebuffer 1."}, {Text: "CLRA",Description: "Clears all framebuffers."}, {Text: "CUE",Description: "Prepares take item takeid to go to air next in framebuffer number buffer on layer number layer. The take item is not taken to air, but is prepared to be taken to air without any frame delay. For example, CUE 3:2:-5 prepares to load the take item 3 into the framebuffer 3 and onto layer -5."}, {Text: "DOWN",Description: "Move the current selection in the sequencer to the item below it in the list."}, {Text: "FOCUS ",Description: "Set the sequencer focus to the take item number takeid. For example, FOCUS 0005 set the focus to take item 0005."}, {Text: "GPI ",Description: "Trigger the simulated GPI input gpi. This is treated as if the GPI input were triggered externally. For example, GPI 5 triggers GPI input 5."}, {Text: "LAYEROFF ",Description: "Takes a scene in framebuffer number buffer on layer number layer off air using the defined out transition. For example, LAYEROFF 0000:2 removes the scene on layer 2 of framebuffer 0000 (the first framebuffer)."}, {Text: "NEXT",Description: "Take the current take item in the sequencer to air and advance the current selection to the next item in the list."}, {Text: "READ",Description: "Take the current selection in the sequencer to air."}, {Text: "RESUME ",Description: "Resumes all layers in framebuffer number buffer. For example, RESUME 0000 resumes all layers in framebuffer 1."}, {Text: "SEQI",Description: "Loads the take item takeid to air on layer number layer to the output channel selected in the template. The Sequencer focus moves to this item. For example, SEQI 0005:7 loads the take item 0005 onto layer 7."}, {Text: "SEQO",Description: "Takes the take item takeid off-air. For example, SEQO 0005 takes the template with TakeID 5 off-air."}, {Text: "SWAP",Description: "Loads all the take items that are currently in the cued state to air in framebuffer number buffer. If a framebuffer is not specified, all cued take items in all framebuffers are taken to air. For example, SWAP 0 takes all the cued take items in framebuffer 1 to air."}, {Text: "TAKE",Description: "Loads take item takeid to air in framebuffer number buffer on layer number layer. The Sequencer focus does not move to this item. For example, TAKE 5:0:7 loads the template with TakeID 5 into framebuffer 1 and onto layer 7."}, {Text: "UNCUEALL",Description: "Removes all cued items from the cued state."}, {Text: "UNCUE",Description: "Remove item with take id takeid from the cued state."}, {Text:"UP",Description: "Move the current selection in the sequencer to the item above it in the list."}, {Text: "UPNEXT",Description: "Sets the preview to the take item takeid in the sequencer without moving the focus bar."}, } return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true) } func main() { xp, err := XPression.New("localhost",7788) if err != nil { panic(err) } for { cmd := prompt.Input("XPression >>> ", completer) if err := xp.Write(cmd); err != nil { panic(err) } } }
examples/cui/main.go
0.571647
0.453262
main.go
starcoder
package utility import ( "encoding/json" "math" "math/rand" "syscall/js" "github.com/go-gl/mathgl/mgl32" "github.com/udhos/gwob" ) func ProgressUpdate(progress float32, event string, taskId int, rays uint64) { data := struct { Progress float32 `json:"progress"` Event string `json:"event"` TaskID int `json:"taskId"` Rays uint64 `json:"rays"` }{ progress, event, taskId, rays, } raw, err := json.Marshal(data) if err != nil { panic(err) } js.Global().Call("progressUpdate", string(raw)) } func ClampColor(c mgl32.Vec3) mgl32.Vec3 { return mgl32.Vec3{ float32(math.Min(math.Max(float64(c.X()), 0), 1.0)), float32(math.Min(math.Max(float64(c.Y()), 0), 1.0)), float32(math.Min(math.Max(float64(c.Z()), 0), 1.0)), } } func MultiplyColor(c1 mgl32.Vec3, c2 mgl32.Vec3) mgl32.Vec3 { return mgl32.Vec3{ c1[0] * c2[0], c1[1] * c2[1], c1[2] * c2[2], } } func RandomInHemisphere(normal mgl32.Vec3) mgl32.Vec3 { inUnitSphere := RandomInUnitSphere() if inUnitSphere.Dot(normal) > 0.0 { return inUnitSphere } return inUnitSphere.Mul(-1) } func RandomInUnitSphere() mgl32.Vec3 { for { p := mgl32.Vec3{ rand.Float32()*2 - 1, rand.Float32()*2 - 1, rand.Float32()*2 - 1, } if p.LenSqr() < 1 { return p } } } func BoolToInt(b bool) uint8 { if b { return 1 } return 0 } // Returns combined minimum of the two vectors func Vec3Min(v1 mgl32.Vec3, v2 mgl32.Vec3) mgl32.Vec3 { return mgl32.Vec3{ float32(math.Min(float64(v1.X()), float64(v2.X()))), float32(math.Min(float64(v1.Y()), float64(v2.Y()))), float32(math.Min(float64(v1.Z()), float64(v2.Z()))), } } // Returns combined maximum of the two vectors func Vec3Max(v1 mgl32.Vec3, v2 mgl32.Vec3) mgl32.Vec3 { return mgl32.Vec3{ float32(math.Max(float64(v1.X()), float64(v2.X()))), float32(math.Max(float64(v1.Y()), float64(v2.Y()))), float32(math.Max(float64(v1.Z()), float64(v2.Z()))), } } // TextureCoordinates gets texture coordinates for a stride index. func TextureCoordinates(o *gwob.Obj, stride int) (float32, float32, error) { offset := o.StrideOffsetTexture / 4 floatsPerStride := o.StrideSize / 4 f := offset + stride*floatsPerStride return o.Coord[f], o.Coord[f+1], nil } // VertexCoordinates gets vertex coordinates for a stride index. func VertexCoordinates(o *gwob.Obj, stride int) (float32, float32, float32, error) { offset := o.StrideOffsetPosition / 4 floatsPerStride := o.StrideSize / 4 f := offset + stride*floatsPerStride return o.Coord[f], o.Coord[f+1], o.Coord[f+2], nil }
src/backend/utility/utility.go
0.765856
0.430028
utility.go
starcoder
package require import ( "bytes" "fmt" "reflect" "runtime" "strings" "testing" "unicode" "unicode/utf8" "github.com/wdvxdr1123/tengo/v2" "github.com/wdvxdr1123/tengo/v2/parser" "github.com/wdvxdr1123/tengo/v2/token" ) // NoError asserts err is not an error. func NoError(t *testing.T, err error, msg ...interface{}) { if err != nil { failExpectedActual(t, "no error", err, msg...) } } // Error asserts err is an error. func Error(t *testing.T, err error, msg ...interface{}) { if err == nil { failExpectedActual(t, "error", err, msg...) } } // Nil asserts v is nil. func Nil(t *testing.T, v interface{}, msg ...interface{}) { if !isNil(v) { failExpectedActual(t, "nil", v, msg...) } } // True asserts v is true. func True(t *testing.T, v bool, msg ...interface{}) { if !v { failExpectedActual(t, "true", v, msg...) } } // False asserts vis false. func False(t *testing.T, v bool, msg ...interface{}) { if v { failExpectedActual(t, "false", v, msg...) } } // NotNil asserts v is not nil. func NotNil(t *testing.T, v interface{}, msg ...interface{}) { if isNil(v) { failExpectedActual(t, "not nil", v, msg...) } } // IsType asserts expected and actual are of the same type. func IsType( t *testing.T, expected, actual interface{}, msg ...interface{}, ) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { failExpectedActual(t, reflect.TypeOf(expected), reflect.TypeOf(actual), msg...) } } // Equal asserts expected and actual are equal. func Equal( t *testing.T, expected, actual interface{}, msg ...interface{}, ) { if isNil(expected) { Nil(t, actual, "expected nil, but got not nil") return } NotNil(t, actual, "expected not nil, but got nil") IsType(t, expected, actual, msg...) switch expected := expected.(type) { case int: if expected != actual.(int) { failExpectedActual(t, expected, actual, msg...) } case int64: if expected != actual.(int64) { failExpectedActual(t, expected, actual, msg...) } case float64: if expected != actual.(float64) { failExpectedActual(t, expected, actual, msg...) } case string: if expected != actual.(string) { failExpectedActual(t, expected, actual, msg...) } case []byte: if !bytes.Equal(expected, actual.([]byte)) { failExpectedActual(t, string(expected), string(actual.([]byte)), msg...) } case []string: if !equalStringSlice(expected, actual.([]string)) { failExpectedActual(t, expected, actual, msg...) } case []int: if !equalIntSlice(expected, actual.([]int)) { failExpectedActual(t, expected, actual, msg...) } case bool: if expected != actual.(bool) { failExpectedActual(t, expected, actual, msg...) } case rune: if expected != actual.(rune) { failExpectedActual(t, expected, actual, msg...) } case *tengo.Symbol: if !equalSymbol(expected, actual.(*tengo.Symbol)) { failExpectedActual(t, expected, actual, msg...) } case parser.Pos: if expected != actual.(parser.Pos) { failExpectedActual(t, expected, actual, msg...) } case token.Token: if expected != actual.(token.Token) { failExpectedActual(t, expected, actual, msg...) } case []tengo.Object: equalObjectSlice(t, expected, actual.([]tengo.Object), msg...) case *tengo.Int: Equal(t, expected.Value, actual.(*tengo.Int).Value, msg...) case *tengo.Float: Equal(t, expected.Value, actual.(*tengo.Float).Value, msg...) case *tengo.String: Equal(t, expected.Value, actual.(*tengo.String).Value, msg...) case *tengo.Char: Equal(t, expected.Value, actual.(*tengo.Char).Value, msg...) case *tengo.Bool: if expected != actual { failExpectedActual(t, expected, actual, msg...) } case *tengo.Array: equalObjectSlice(t, expected.Value, actual.(*tengo.Array).Value, msg...) case *tengo.ImmutableArray: equalObjectSlice(t, expected.Value, actual.(*tengo.ImmutableArray).Value, msg...) case *tengo.Bytes: if !bytes.Equal(expected.Value, actual.(*tengo.Bytes).Value) { failExpectedActual(t, string(expected.Value), string(actual.(*tengo.Bytes).Value), msg...) } case *tengo.Map: equalObjectMap(t, expected.Value, actual.(*tengo.Map).Value, msg...) case *tengo.ImmutableMap: equalObjectMap(t, expected.Value, actual.(*tengo.ImmutableMap).Value, msg...) case *tengo.CompiledFunction: equalCompiledFunction(t, expected, actual.(*tengo.CompiledFunction), msg...) case *tengo.Undefined: if expected != actual { failExpectedActual(t, expected, actual, msg...) } case *tengo.Error: Equal(t, expected.Value, actual.(*tengo.Error).Value, msg...) case tengo.Object: if !expected.Equals(actual.(tengo.Object)) { failExpectedActual(t, expected, actual, msg...) } case *parser.SourceFileSet: equalFileSet(t, expected, actual.(*parser.SourceFileSet), msg...) case *parser.SourceFile: Equal(t, expected.Name, actual.(*parser.SourceFile).Name, msg...) Equal(t, expected.Base, actual.(*parser.SourceFile).Base, msg...) Equal(t, expected.Size, actual.(*parser.SourceFile).Size, msg...) True(t, equalIntSlice(expected.Lines, actual.(*parser.SourceFile).Lines), msg...) case error: if expected != actual.(error) { failExpectedActual(t, expected, actual, msg...) } default: panic(fmt.Errorf("type not implemented: %T", expected)) } } // Fail marks the function as having failed but continues execution. func Fail(t *testing.T, msg ...interface{}) { t.Logf("\nError trace:\n\t%s\n%s", strings.Join(errorTrace(), "\n\t"), message(msg...)) t.Fail() } func failExpectedActual( t *testing.T, expected, actual interface{}, msg ...interface{}, ) { var addMsg string if len(msg) > 0 { addMsg = "\nMessage: " + message(msg...) } t.Logf("\nError trace:\n\t%s\nExpected: %v\nActual: %v%s", strings.Join(errorTrace(), "\n\t"), expected, actual, addMsg) t.FailNow() } func message(formatArgs ...interface{}) string { var format string var args []interface{} if len(formatArgs) > 0 { format = formatArgs[0].(string) } if len(formatArgs) > 1 { args = formatArgs[1:] } return fmt.Sprintf(format, args...) } func equalIntSlice(a, b []int) bool { if len(a) != len(b) { return false } for i := 0; i < len(a); i++ { if a[i] != b[i] { return false } } return true } func equalStringSlice(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 } func equalSymbol(a, b *tengo.Symbol) bool { return a.Name == b.Name && a.Index == b.Index && a.Scope == b.Scope } func equalObjectSlice( t *testing.T, expected, actual []tengo.Object, msg ...interface{}, ) { Equal(t, len(expected), len(actual), msg...) for i := 0; i < len(expected); i++ { Equal(t, expected[i], actual[i], msg...) } } func equalFileSet( t *testing.T, expected, actual *parser.SourceFileSet, msg ...interface{}, ) { Equal(t, len(expected.Files), len(actual.Files), msg...) for i, f := range expected.Files { Equal(t, f, actual.Files[i], msg...) } Equal(t, expected.Base, actual.Base) Equal(t, expected.LastFile, actual.LastFile) } func equalObjectMap( t *testing.T, expected, actual map[string]tengo.Object, msg ...interface{}, ) { Equal(t, len(expected), len(actual), msg...) for key, expectedVal := range expected { actualVal := actual[key] Equal(t, expectedVal, actualVal, msg...) } } func equalCompiledFunction( t *testing.T, expected, actual tengo.Object, msg ...interface{}, ) { expectedT := expected.(*tengo.CompiledFunction) actualT := actual.(*tengo.CompiledFunction) Equal(t, tengo.FormatInstructions(expectedT.Instructions, 0), tengo.FormatInstructions(actualT.Instructions, 0), msg...) } func isNil(v interface{}) bool { if v == nil { return true } value := reflect.ValueOf(v) kind := value.Kind() return kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() } func errorTrace() []string { var pc uintptr file := "" line := 0 var ok bool name := "" var callers []string for i := 0; ; i++ { pc, file, line, ok = runtime.Caller(i) if !ok { break } if file == "<autogenerated>" { break } f := runtime.FuncForPC(pc) if f == nil { break } name = f.Name() if name == "testing.tRunner" { break } parts := strings.Split(file, "/") file = parts[len(parts)-1] if len(parts) > 1 { dir := parts[len(parts)-2] if dir != "require" || file == "mock_test.go" { callers = append(callers, fmt.Sprintf("%s:%d", file, line)) } } // Drop the package segments := strings.Split(name, ".") name = segments[len(segments)-1] if isTest(name, "Test") || isTest(name, "Benchmark") || isTest(name, "Example") { break } } return callers } func isTest(name, prefix string) bool { if !strings.HasPrefix(name, prefix) { return false } if len(name) == len(prefix) { // "Test" is ok return true } r, _ := utf8.DecodeRuneInString(name[len(prefix):]) return !unicode.IsLower(r) }
require/require.go
0.518059
0.506225
require.go
starcoder
package plaid import ( "encoding/json" ) // PaystubDetails An object representing details that can be found on the paystub. type PaystubDetails struct { // Beginning date of the pay period on the paystub in the 'YYYY-MM-DD' format. PayPeriodStartDate NullableString `json:"pay_period_start_date,omitempty"` // Ending date of the pay period on the paystub in the 'YYYY-MM-DD' format. PayPeriodEndDate NullableString `json:"pay_period_end_date,omitempty"` // Pay date on the paystub in the 'YYYY-MM-DD' format. PayDate NullableString `json:"pay_date,omitempty"` // The name of the payroll provider that generated the paystub, e.g. ADP PaystubProvider NullableString `json:"paystub_provider,omitempty"` PayFrequency NullablePaystubPayFrequency `json:"pay_frequency,omitempty"` AdditionalProperties map[string]interface{} } type _PaystubDetails PaystubDetails // NewPaystubDetails instantiates a new PaystubDetails object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewPaystubDetails() *PaystubDetails { this := PaystubDetails{} return &this } // NewPaystubDetailsWithDefaults instantiates a new PaystubDetails object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewPaystubDetailsWithDefaults() *PaystubDetails { this := PaystubDetails{} return &this } // GetPayPeriodStartDate returns the PayPeriodStartDate field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PaystubDetails) GetPayPeriodStartDate() string { if o == nil || o.PayPeriodStartDate.Get() == nil { var ret string return ret } return *o.PayPeriodStartDate.Get() } // GetPayPeriodStartDateOk returns a tuple with the PayPeriodStartDate field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PaystubDetails) GetPayPeriodStartDateOk() (*string, bool) { if o == nil { return nil, false } return o.PayPeriodStartDate.Get(), o.PayPeriodStartDate.IsSet() } // HasPayPeriodStartDate returns a boolean if a field has been set. func (o *PaystubDetails) HasPayPeriodStartDate() bool { if o != nil && o.PayPeriodStartDate.IsSet() { return true } return false } // SetPayPeriodStartDate gets a reference to the given NullableString and assigns it to the PayPeriodStartDate field. func (o *PaystubDetails) SetPayPeriodStartDate(v string) { o.PayPeriodStartDate.Set(&v) } // SetPayPeriodStartDateNil sets the value for PayPeriodStartDate to be an explicit nil func (o *PaystubDetails) SetPayPeriodStartDateNil() { o.PayPeriodStartDate.Set(nil) } // UnsetPayPeriodStartDate ensures that no value is present for PayPeriodStartDate, not even an explicit nil func (o *PaystubDetails) UnsetPayPeriodStartDate() { o.PayPeriodStartDate.Unset() } // GetPayPeriodEndDate returns the PayPeriodEndDate field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PaystubDetails) GetPayPeriodEndDate() string { if o == nil || o.PayPeriodEndDate.Get() == nil { var ret string return ret } return *o.PayPeriodEndDate.Get() } // GetPayPeriodEndDateOk returns a tuple with the PayPeriodEndDate field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PaystubDetails) GetPayPeriodEndDateOk() (*string, bool) { if o == nil { return nil, false } return o.PayPeriodEndDate.Get(), o.PayPeriodEndDate.IsSet() } // HasPayPeriodEndDate returns a boolean if a field has been set. func (o *PaystubDetails) HasPayPeriodEndDate() bool { if o != nil && o.PayPeriodEndDate.IsSet() { return true } return false } // SetPayPeriodEndDate gets a reference to the given NullableString and assigns it to the PayPeriodEndDate field. func (o *PaystubDetails) SetPayPeriodEndDate(v string) { o.PayPeriodEndDate.Set(&v) } // SetPayPeriodEndDateNil sets the value for PayPeriodEndDate to be an explicit nil func (o *PaystubDetails) SetPayPeriodEndDateNil() { o.PayPeriodEndDate.Set(nil) } // UnsetPayPeriodEndDate ensures that no value is present for PayPeriodEndDate, not even an explicit nil func (o *PaystubDetails) UnsetPayPeriodEndDate() { o.PayPeriodEndDate.Unset() } // GetPayDate returns the PayDate field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PaystubDetails) GetPayDate() string { if o == nil || o.PayDate.Get() == nil { var ret string return ret } return *o.PayDate.Get() } // GetPayDateOk returns a tuple with the PayDate field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PaystubDetails) GetPayDateOk() (*string, bool) { if o == nil { return nil, false } return o.PayDate.Get(), o.PayDate.IsSet() } // HasPayDate returns a boolean if a field has been set. func (o *PaystubDetails) HasPayDate() bool { if o != nil && o.PayDate.IsSet() { return true } return false } // SetPayDate gets a reference to the given NullableString and assigns it to the PayDate field. func (o *PaystubDetails) SetPayDate(v string) { o.PayDate.Set(&v) } // SetPayDateNil sets the value for PayDate to be an explicit nil func (o *PaystubDetails) SetPayDateNil() { o.PayDate.Set(nil) } // UnsetPayDate ensures that no value is present for PayDate, not even an explicit nil func (o *PaystubDetails) UnsetPayDate() { o.PayDate.Unset() } // GetPaystubProvider returns the PaystubProvider field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PaystubDetails) GetPaystubProvider() string { if o == nil || o.PaystubProvider.Get() == nil { var ret string return ret } return *o.PaystubProvider.Get() } // GetPaystubProviderOk returns a tuple with the PaystubProvider field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PaystubDetails) GetPaystubProviderOk() (*string, bool) { if o == nil { return nil, false } return o.PaystubProvider.Get(), o.PaystubProvider.IsSet() } // HasPaystubProvider returns a boolean if a field has been set. func (o *PaystubDetails) HasPaystubProvider() bool { if o != nil && o.PaystubProvider.IsSet() { return true } return false } // SetPaystubProvider gets a reference to the given NullableString and assigns it to the PaystubProvider field. func (o *PaystubDetails) SetPaystubProvider(v string) { o.PaystubProvider.Set(&v) } // SetPaystubProviderNil sets the value for PaystubProvider to be an explicit nil func (o *PaystubDetails) SetPaystubProviderNil() { o.PaystubProvider.Set(nil) } // UnsetPaystubProvider ensures that no value is present for PaystubProvider, not even an explicit nil func (o *PaystubDetails) UnsetPaystubProvider() { o.PaystubProvider.Unset() } // GetPayFrequency returns the PayFrequency field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PaystubDetails) GetPayFrequency() PaystubPayFrequency { if o == nil || o.PayFrequency.Get() == nil { var ret PaystubPayFrequency return ret } return *o.PayFrequency.Get() } // GetPayFrequencyOk returns a tuple with the PayFrequency field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PaystubDetails) GetPayFrequencyOk() (*PaystubPayFrequency, bool) { if o == nil { return nil, false } return o.PayFrequency.Get(), o.PayFrequency.IsSet() } // HasPayFrequency returns a boolean if a field has been set. func (o *PaystubDetails) HasPayFrequency() bool { if o != nil && o.PayFrequency.IsSet() { return true } return false } // SetPayFrequency gets a reference to the given NullablePaystubPayFrequency and assigns it to the PayFrequency field. func (o *PaystubDetails) SetPayFrequency(v PaystubPayFrequency) { o.PayFrequency.Set(&v) } // SetPayFrequencyNil sets the value for PayFrequency to be an explicit nil func (o *PaystubDetails) SetPayFrequencyNil() { o.PayFrequency.Set(nil) } // UnsetPayFrequency ensures that no value is present for PayFrequency, not even an explicit nil func (o *PaystubDetails) UnsetPayFrequency() { o.PayFrequency.Unset() } func (o PaystubDetails) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.PayPeriodStartDate.IsSet() { toSerialize["pay_period_start_date"] = o.PayPeriodStartDate.Get() } if o.PayPeriodEndDate.IsSet() { toSerialize["pay_period_end_date"] = o.PayPeriodEndDate.Get() } if o.PayDate.IsSet() { toSerialize["pay_date"] = o.PayDate.Get() } if o.PaystubProvider.IsSet() { toSerialize["paystub_provider"] = o.PaystubProvider.Get() } if o.PayFrequency.IsSet() { toSerialize["pay_frequency"] = o.PayFrequency.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *PaystubDetails) UnmarshalJSON(bytes []byte) (err error) { varPaystubDetails := _PaystubDetails{} if err = json.Unmarshal(bytes, &varPaystubDetails); err == nil { *o = PaystubDetails(varPaystubDetails) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "pay_period_start_date") delete(additionalProperties, "pay_period_end_date") delete(additionalProperties, "pay_date") delete(additionalProperties, "paystub_provider") delete(additionalProperties, "pay_frequency") o.AdditionalProperties = additionalProperties } return err } type NullablePaystubDetails struct { value *PaystubDetails isSet bool } func (v NullablePaystubDetails) Get() *PaystubDetails { return v.value } func (v *NullablePaystubDetails) Set(val *PaystubDetails) { v.value = val v.isSet = true } func (v NullablePaystubDetails) IsSet() bool { return v.isSet } func (v *NullablePaystubDetails) Unset() { v.value = nil v.isSet = false } func NewNullablePaystubDetails(val *PaystubDetails) *NullablePaystubDetails { return &NullablePaystubDetails{value: val, isSet: true} } func (v NullablePaystubDetails) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullablePaystubDetails) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_paystub_details.go
0.737725
0.42054
model_paystub_details.go
starcoder
package main import ( "fmt" "time" "math/rand" "os" "strconv" "sort" ) func MergeSort(slice []int) []int { if len(slice) < 2 { return slice } mid := len(slice) / 2 return Merge( MergeSort(slice[:mid]), MergeSort(slice[mid:]), ) } func Merge(left, right []int) []int { size, i, j := len(left) + len(right), 0, 0 slice := make([]int, size, size) for i < len(left) && j < len(right) { if left[i] < right[j] { slice[i+j] = left[i] i++ } else { slice[i+j] = right[j] j++ } } if i < len(left) { copy(slice[i+j:], left[i:]) } else if j < len(right) { copy(slice[i+j:], right[j:]) } return slice } func ParallelMergeSort(data []int, out chan []int) { if len(data) <= (1 << 13) { out <- MergeSort(data) } else { leftChan := make(chan []int) rightChan := make(chan []int) middle := len(data)/2 go ParallelMergeSort(data[:middle], leftChan) go ParallelMergeSort(data[middle:], rightChan) ldata := <-leftChan rdata := <-rightChan close(leftChan) close(rightChan) out <- Merge(ldata, rdata) } } func Bench(N int, sorter func([]int)) time.Duration { r := rand.New(rand.NewSource(18)) unsorted := make([]int, N) for i := 0; i < N; i++ { unsorted[i] = r.Intn(1 << 30) } now := time.Now() sorter(unsorted) elapsed := time.Now().Sub(now) return elapsed } func main() { N := 100000000 if len(os.Args) > 1 { N, _ = strconv.Atoi(os.Args[1]) } single := Bench(N, func (s []int) { MergeSort(s) }) multi := Bench(N, func (s []int) { out := make(chan []int) go ParallelMergeSort(s, out) <-out close(out) }) builtin := Bench(N, func (s []int) { sort.Ints(s) }) fmt.Printf("Single thread: %v\n", single) fmt.Printf("Multi thread: %v\n", multi) fmt.Printf("Builtin sort: %v\n", builtin) }
go/merge.go
0.566019
0.410343
merge.go
starcoder
package mfi import ( "time" ) //Ticker ticker price information type Ticker struct { Open float64 Close float64 High float64 Low float64 Vol float64 Date time.Time } //moneyFlow money flow type moneyFlow struct { positive float64 negative float64 } //mfiCalculator MFI calculator type mfiCalculator struct { *Ticker FlowIdx int32 MaxFlowIdx int32 POSSumMF float64 NEGSumMF float64 PrevValue float64 Period int32 Count int32 TempValue float64 CalcValue float64 Result float64 MoneyFlow []moneyFlow } //MFI MFI object type MFI struct { Value float64 Calculator *mfiCalculator } //NewMFI factory function return a new object of MFI func (t *Ticker) NewMFI(inTimePeriod int32) *MFI { calculator := &mfiCalculator{ Ticker: t, FlowIdx: 0, MaxFlowIdx: inTimePeriod - 1, Period: inTimePeriod, MoneyFlow: make([]moneyFlow, inTimePeriod), } return &MFI{ Calculator: calculator, } } //setMarket set up market data func (t *Ticker) setMarket(open, close, high, low, vol float64, date time.Time) { t.Open = open t.Close = close t.High = high t.Low = low t.Vol = vol t.Date = date } //calcMFI calculate MFI func (m *mfiCalculator) calcMFI() { if m.Count == 0 { m.PrevValue = (m.High + m.Low + m.Close) / 3.0 } if m.Count > m.Period { m.POSSumMF -= m.MoneyFlow[m.FlowIdx].positive m.NEGSumMF -= m.MoneyFlow[m.FlowIdx].negative } m.TempValue = (m.High + m.Low + m.Close) / 3.0 m.CalcValue = m.TempValue - m.PrevValue m.PrevValue = m.TempValue m.TempValue *= m.Vol switch { case m.CalcValue < 0: m.MoneyFlow[m.FlowIdx].negative = m.TempValue m.NEGSumMF += m.TempValue m.MoneyFlow[m.FlowIdx].positive = 0.0 case m.CalcValue > 0: m.MoneyFlow[m.FlowIdx].positive = m.TempValue m.POSSumMF += m.TempValue m.MoneyFlow[m.FlowIdx].negative = 0.0 default: m.MoneyFlow[m.FlowIdx].positive = 0.0 m.MoneyFlow[m.FlowIdx].negative = 0.0 } m.FlowIdx++ if m.FlowIdx > m.MaxFlowIdx { m.FlowIdx = 0 } if m.Count >= m.Period { m.TempValue = m.POSSumMF + m.NEGSumMF if m.TempValue < 1.0 { m.Result = 0.0 } else { m.Result = 100 * (m.POSSumMF / m.TempValue) } } m.Count++ } //Update Update the MFI value of the current price func (r *MFI) Update(open, close, high, low, vol float64, date time.Time) { r.Calculator.setMarket(open, close, high, low, vol, date) r.Calculator.calcMFI() r.Value = r.Calculator.Result } //Sum Returns the MFI value of the current MFI object func (r *MFI) Sum() float64 { return r.Value }
mfi/mfi.go
0.604049
0.517449
mfi.go
starcoder
package patterns import ( "bytes" "github.com/sniperkit/xfilter/internal/persist" ) // BMH turns patterns into BMH sequences if possible. func BMH(p Pattern, rev bool) Pattern { s, ok := p.(Sequence) if !ok { return p } if rev { return NewRBMHSequence(s) } return NewBMHSequence(s) } // BMHSequence is an optimised version of the regular Sequence pattern. // It is used behind the scenes in the Bytematcher package to speed up matching and should not be used directly in other packages (use the plain Sequence instead). type BMHSequence struct { Seq Sequence Shift [256]int } // NewBMHSequence turns a Sequence into a BMHSequence. func NewBMHSequence(s Sequence) *BMHSequence { var shift [256]int for i := range shift { shift[i] = len(s) } last := len(s) - 1 for i := 0; i < last; i++ { shift[s[i]] = last - i } return &BMHSequence{s, shift} } // Test bytes against the pattern. // For a positive match, the integer value represents the length of the match. // For a negative match, the integer represents an offset jump before a subsequent test. func (s *BMHSequence) Test(b []byte) (bool, int) { if len(b) < len(s.Seq) { return false, 0 } for i := len(s.Seq) - 1; i > -1; i-- { if b[i] != s.Seq[i] { return false, s.Shift[b[len(s.Seq)-1]] } } return true, len(s.Seq) } // Test bytes against the pattern in reverse. // For a positive match, the integer value represents the length of the match. // For a negative match, the integer represents an offset jump before a subsequent test. func (s *BMHSequence) TestR(b []byte) (bool, int) { if len(b) < len(s.Seq) { return false, 0 } if bytes.Equal(s.Seq, b[len(b)-len(s.Seq):]) { return true, len(s.Seq) } return false, 1 } // Equals reports whether a pattern is identical to another pattern. func (s *BMHSequence) Equals(pat Pattern) bool { seq2, ok := pat.(*BMHSequence) if ok { return bytes.Equal(s.Seq, seq2.Seq) } return false } // Length returns a minimum and maximum length for the pattern. func (s *BMHSequence) Length() (int, int) { return len(s.Seq), len(s.Seq) } // NumSequences reports how many plain sequences are needed to represent this pattern. func (s *BMHSequence) NumSequences() int { return 1 } // Sequences converts the pattern into a slice of plain sequences. func (s *BMHSequence) Sequences() []Sequence { return []Sequence{s.Seq} } func (s *BMHSequence) String() string { return "seq " + Stringify(s.Seq) } // Save persists the pattern. func (s *BMHSequence) Save(ls *persist.LoadSaver) { ls.SaveByte(bmhLoader) ls.SaveBytes(s.Seq) for _, v := range s.Shift { ls.SaveSmallInt(v) } } func loadBMH(ls *persist.LoadSaver) Pattern { bmh := &BMHSequence{} bmh.Seq = Sequence(ls.LoadBytes()) for i := range bmh.Shift { bmh.Shift[i] = ls.LoadSmallInt() } return bmh } // RBMHSequence is a variant of the BMH sequence designed for reverse (R-L) matching. // It is used behind the scenes in the Bytematcher package to speed up matching and should not be used directly in other packages (use the plain Sequence instead). type RBMHSequence struct { Seq Sequence Shift [256]int } // NewRBMHSequence create a reverse matching BMH sequence (apply the BMH optimisation to TestR rather than Test). func NewRBMHSequence(s Sequence) *RBMHSequence { var shift [256]int for i := range shift { shift[i] = len(s) } last := len(s) - 1 for i := 0; i < last; i++ { shift[s[last-i]] = last - i } return &RBMHSequence{s, shift} } // Test bytes against the pattern. // For a positive match, the integer value represents the length of the match. // For a negative match, the integer represents an offset jump before a subsequent test. func (s *RBMHSequence) Test(b []byte) (bool, int) { if len(b) < len(s.Seq) { return false, 0 } if bytes.Equal(s.Seq, b[:len(s.Seq)]) { return true, len(s.Seq) } return false, 1 } // Test bytes against the pattern in reverse. // For a positive match, the integer value represents the length of the match. // For a negative match, the integer represents an offset jump before a subsequent test. func (s *RBMHSequence) TestR(b []byte) (bool, int) { if len(b) < len(s.Seq) { return false, 0 } for i, v := range b[len(b)-len(s.Seq):] { if v != s.Seq[i] { return false, s.Shift[b[len(b)-len(s.Seq)]] } } return true, len(s.Seq) } // Equals reports whether a pattern is identical to another pattern. func (s *RBMHSequence) Equals(pat Pattern) bool { seq2, ok := pat.(*RBMHSequence) if ok { return bytes.Equal(s.Seq, seq2.Seq) } return false } // Length returns a minimum and maximum length for the pattern. func (s *RBMHSequence) Length() (int, int) { return len(s.Seq), len(s.Seq) } // NumSequences reports how many plain sequences are needed to represent this pattern. func (s *RBMHSequence) NumSequences() int { return 1 } // Sequences converts the pattern into a slice of plain sequences. func (s *RBMHSequence) Sequences() []Sequence { return []Sequence{s.Seq} } func (s *RBMHSequence) String() string { return "seq " + Stringify(s.Seq) } // Save persists the pattern. func (s *RBMHSequence) Save(ls *persist.LoadSaver) { ls.SaveByte(rbmhLoader) ls.SaveBytes(s.Seq) for _, v := range s.Shift { ls.SaveSmallInt(v) } } func loadRBMH(ls *persist.LoadSaver) Pattern { rbmh := &RBMHSequence{} rbmh.Seq = Sequence(ls.LoadBytes()) for i := range rbmh.Shift { rbmh.Shift[i] = ls.LoadSmallInt() } return rbmh }
internal/bytematcher/patterns/bmh.go
0.765067
0.415254
bmh.go
starcoder
package cmath import ( "fmt" "math" ) type Matrix struct { n, m int a []float64 } func (a *Matrix) Vector(i int) IVector { v := newVector(a.m) for j := 0; j < a.m; j++ { v.Set(j, a.At(i, j)) } return v } func (a *Matrix) VectorT(i int) IVector { v := newVector(a.m) for j := 0; j < a.m; j++ { v.Set(j, a.At(j, i)) } return v } func (a *Matrix) At(i, j int) float64 { if !(0 <= i && i < a.n && 0 <= j && j < a.m) { panic("index out of range") } return a.a[i*a.m+j] } func (a *Matrix) DimN() int { return a.n } func (a *Matrix) DimM() int { return a.m } func (a *Matrix) Set(i, j int, x float64) { if !(0 <= i && i < a.n && 0 <= j && j < a.m) { panic("index out of range") } a.a[i*a.m+j] = x } func (a *Matrix) Transposition() IMatrix{ m := newMatrix(a.DimM(),a.DimN()) for i:=0;i<a.DimN();i++{ for j:=0;j<a.DimM();j++{ m.Set(j,i,a.At(i,j)) } } return m } func (a *Matrix) NormalizeN() IMatrix { c := newMatrix(a.n, a.m) for i := 0; i < c.n; i++ { sum := 0.0 for j := 0; j < a.m; j++ { sum += math.Pow(a.At(i, j), 2) } sum = math.Sqrt(sum) for j := 0; j < a.m; j++ { if sum == 0 { c.Set(i, j, 0) } else { c.Set(i, j, a.At(i, j)/sum) } } } return c } func (a *Matrix) NormalizeM() IMatrix { c := newMatrix(a.n, a.m) for i := 0; i < c.m; i++ { sum := 0.0 for j := 0; j < a.n; j++ { sum += math.Pow(a.At(j, i), 2) } sum = math.Sqrt(sum) for j := 0; j < a.n; j++ { if sum == 0 { c.Set(j, i, 0) } else { c.Set(j, i, a.At(j, i)/sum) } } } return c } func (a *Matrix) MatrixT() IMatrix { c := newMatrix(a.m, a.n) for i := 0; i < c.m; i++ { for j := 0; j < a.n; j++ { c.Set(j, i, a.At(i, j)) } } return c } func (a *Matrix) Mul(b IMatrix) IMatrix { if a.m != b.DimN() { panic("illegal Matrix multiply") } c := newMatrix(a.n, b.DimM()) for i := 0; i < c.n; i++ { for j := 0; j < c.m; j++ { x := 0.0 for k := 0; k < a.m; k++ { x += a.At(i, k) * b.At(k, j) } c.Set(i, j, x) } } return c } func (a *Matrix) Eql(b IMatrix) bool { if a.n != b.DimN() || a.m != b.DimM() { return false } for i := 0; i < a.n; i++ { for j := 0; j < a.m; j++ { if a.At(i, j) != b.At(i, j) { return false } } } return true } func (a *Matrix) String() string { s := "" for i := 0; i < a.n; i++ { for j := 0; j < a.m; j++ { s += fmt.Sprintf("%f,", a.At(i, j)) } s += "\n" } return s } func newMatrix(n, m int) *Matrix { if !(0 <= n && 0 <= m) { return nil } a := new(Matrix) a.n = n a.m = m a.a = make([]float64, n*m) return a } func newUnit(n int) *Matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { for j := 0; j < n; j++ { x := 0.0 if i == j { x = 1 } a.Set(i, j, x) } } return a } func NewMatrix(n, m int) IMatrix { return newMatrix(n, m) } func NewUnit(n int) IMatrix { return newUnit(n) }
math/matrix.go
0.727589
0.436502
matrix.go
starcoder
package gxtime import ( "strconv" "time" ) func TimeDayDuration(day float64) time.Duration { return time.Duration(day * 24 * float64(time.Hour)) } func TimeHourDuration(hour float64) time.Duration { return time.Duration(hour * float64(time.Hour)) } func TimeMinuteDuration(minute float64) time.Duration { return time.Duration(minute * float64(time.Minute)) } func TimeSecondDuration(sec float64) time.Duration { return time.Duration(sec * float64(time.Second)) } func TimeMillisecondDuration(m float64) time.Duration { return time.Duration(m * float64(time.Millisecond)) } func TimeMicrosecondDuration(m float64) time.Duration { return time.Duration(m * float64(time.Microsecond)) } func TimeNanosecondDuration(n float64) time.Duration { return time.Duration(n * float64(time.Nanosecond)) } // desc: convert year-month-day-hour-minute-second to int in second // @month: 1 ~ 12 // @hour: 0 ~ 23 // @minute: 0 ~ 59 func YMD(year int, month int, day int, hour int, minute int, sec int) int { return int(time.Date(year, time.Month(month), day, hour, minute, sec, 0, time.Local).Unix()) } // @YMD in UTC timezone func YMDUTC(year int, month int, day int, hour int, minute int, sec int) int { return int(time.Date(year, time.Month(month), day, hour, minute, sec, 0, time.UTC).Unix()) } func YMDPrint(sec int, nsec int) string { return time.Unix(int64(sec), int64(nsec)).Format("2006-01-02 15:04:05.99999") } func Future(sec int, f func()) { time.AfterFunc(TimeSecondDuration(float64(sec)), f) } func Unix2Time(unix int64) time.Time { return time.Unix(unix, 0) } func UnixNano2Time(nano int64) time.Time { return time.Unix(nano/1e9, nano%1e9) } func UnixString2Time(unix string) time.Time { i, err := strconv.ParseInt(unix, 10, 64) if err != nil { panic(err) } return time.Unix(i, 0) } // 注意把time转换成unix的时候有精度损失,只返回了秒值,没有用到纳秒值 func Time2Unix(t time.Time) int64 { return t.Unix() } func Time2UnixNano(t time.Time) int64 { return t.UnixNano() } func GetEndTime(format string) time.Time { timeNow := time.Now() switch format { case "day": year, month, _ := timeNow.Date() nextDay := timeNow.AddDate(0, 0, 1).Day() t := time.Date(year, month, nextDay, 0, 0, 0, 0, time.Local) return time.Unix(t.Unix()-1, 0) case "week": year, month, _ := timeNow.Date() weekday := int(timeNow.Weekday()) weekendday := timeNow.AddDate(0, 0, 8-weekday).Day() t := time.Date(year, month, weekendday, 0, 0, 0, 0, time.Local) return time.Unix(t.Unix()-1, 0) case "month": year := timeNow.Year() nextMonth := timeNow.AddDate(0, 1, 0).Month() t := time.Date(year, nextMonth, 1, 0, 0, 0, 0, time.Local) return time.Unix(t.Unix()-1, 0) case "year": nextYear := timeNow.AddDate(1, 0, 0).Year() t := time.Date(nextYear, 1, 1, 0, 0, 0, 0, time.Local) return time.Unix(t.Unix()-1, 0) } return timeNow }
vendor/github.com/dubbogo/gost/time/time.go
0.738575
0.460107
time.go
starcoder
package types import ( "github.com/lyraproj/issue/issue" "github.com/lyraproj/puppet-evaluator/eval" "github.com/lyraproj/semver/semver" "math" "reflect" "strings" ) const tagName = "puppet" type reflector struct { c eval.Context } var pValueType = reflect.TypeOf((*eval.Value)(nil)).Elem() func NewReflector(c eval.Context) eval.Reflector { return &reflector{c} } func Methods(t reflect.Type) []reflect.Method { if t.Kind() == reflect.Ptr { // Pointer may have methods if t.NumMethod() == 0 { t = t.Elem() } } nm := t.NumMethod() ms := make([]reflect.Method, nm) for i := 0; i < nm; i++ { ms[i] = t.Method(i) } return ms } func Fields(t reflect.Type) []reflect.StructField { if t.Kind() == reflect.Ptr { t = t.Elem() } nf := 0 if t.Kind() == reflect.Struct { nf = t.NumField() } fs := make([]reflect.StructField, nf) for i := 0; i < nf; i++ { fs[i] = t.Field(i) } return fs } // NormalizeType ensures that pointers to interface is converted to interface and that struct is converted to // pointer to struct func NormalizeType(rt reflect.Type) reflect.Type { switch rt.Kind() { case reflect.Struct: rt = reflect.PtrTo(rt) case reflect.Ptr: re := rt.Elem() if re.Kind() == reflect.Interface { rt = re } } return rt } func (r *reflector) Methods(t reflect.Type) []reflect.Method { return Methods(t) } func (r *reflector) Fields(t reflect.Type) []reflect.StructField { return Fields(t) } func (r *reflector) FieldName(f *reflect.StructField) string { if tagHash, ok := r.TagHash(f); ok { if nv, ok := tagHash.Get4(`name`); ok { return nv.String() } } return issue.CamelToSnakeCase(f.Name) } func (r *reflector) Reflect(src eval.Value) reflect.Value { if sn, ok := src.(eval.Reflected); ok { return sn.Reflect(r.c) } panic(eval.Error(eval.EVAL_UNREFLECTABLE_VALUE, issue.H{`type`: src.PType()})) } func (r *reflector) Reflect2(src eval.Value, rt reflect.Type) reflect.Value { if rt != nil && rt.Kind() == reflect.Interface && rt.AssignableTo(pValueType) { sv := reflect.ValueOf(src) if sv.Type().AssignableTo(rt) { return sv } } v := reflect.New(rt).Elem() r.ReflectTo(src, v) return v } // ReflectTo assigns the native value of src to dest func (r *reflector) ReflectTo(src eval.Value, dest reflect.Value) { assertSettable(&dest) if dest.Kind() == reflect.Interface && dest.Type().AssignableTo(pValueType) { sv := reflect.ValueOf(src) if !sv.Type().AssignableTo(dest.Type()) { panic(eval.Error(eval.EVAL_ATTEMPT_TO_SET_WRONG_KIND, issue.H{`expected`: sv.Type().String(), `actual`: dest.Type().String()})) } dest.Set(sv) } else { switch src.(type) { case eval.Reflected: src.(eval.Reflected).ReflectTo(r.c, dest) case eval.PuppetObject: po := src.(eval.PuppetObject) po.PType().(eval.ObjectType).ToReflectedValue(r.c, po, dest) default: panic(eval.Error(eval.EVAL_INVALID_SOURCE_FOR_SET, issue.H{`type`: src.PType()})) } } } func (r *reflector) ReflectType(src eval.Type) (reflect.Type, bool) { return ReflectType(r.c, src) } func ReflectType(c eval.Context, src eval.Type) (reflect.Type, bool) { if sn, ok := src.(eval.ReflectedType); ok { return sn.ReflectType(c) } return nil, false } func (r *reflector) TagHash(f *reflect.StructField) (eval.OrderedMap, bool) { return TagHash(r.c, f) } func TagHash(c eval.Context, f *reflect.StructField) (eval.OrderedMap, bool) { return ParseTagHash(c, f.Tag.Get(tagName)) } func ParseTagHash(c eval.Context, tag string) (eval.OrderedMap, bool) { if tag != `` { tagExpr := c.ParseAndValidate(``, `{`+tag+`}`, true) if tagHash, ok := eval.Evaluate(c, tagExpr).(eval.OrderedMap); ok { return tagHash, true } } return nil, false } var errorType = reflect.TypeOf((*error)(nil)).Elem() func (r *reflector) FunctionDeclFromReflect(name string, mt reflect.Type, withReceiver bool) eval.OrderedMap { returnsError := false var rt eval.Type oc := mt.NumOut() switch oc { case 0: rt = DefaultAnyType() case 1: ot := mt.Out(0) if ot.AssignableTo(errorType) { returnsError = true } else { rt = wrapReflectedType(r.c, mt.Out(0)) } case 2: rt = wrapReflectedType(r.c, mt.Out(0)) ot := mt.Out(1) if ot.AssignableTo(errorType) { returnsError = true } else { rt = NewTupleType([]eval.Type{rt, wrapReflectedType(r.c, mt.Out(1))}, nil) } default: ot := mt.Out(oc - 1) if ot.AssignableTo(errorType) { returnsError = true oc = oc - 1 } ts := make([]eval.Type, oc) for i := 0; i < oc; i++ { ts[i] = wrapReflectedType(r.c, mt.Out(i)) } rt = NewTupleType(ts, nil) } var pt *TupleType pc := mt.NumIn() ix := 0 if withReceiver { // First argumnet is the receiver itself ix = 1 } if pc == ix { pt = EmptyTupleType() } else { ps := make([]eval.Type, pc-ix) for p := ix; p < pc; p++ { ps[p-ix] = wrapReflectedType(r.c, mt.In(p)) } var sz *IntegerType if mt.IsVariadic() { last := pc - ix - 1 ps[last] = ps[last].(*ArrayType).ElementType() sz = NewIntegerType(int64(last), math.MaxInt64) } pt = NewTupleType(ps, sz) } ne := 2 if returnsError { ne++ } ds := make([]*HashEntry, ne) ds[0] = WrapHashEntry2(KEY_TYPE, NewCallableType(pt, rt, nil)) ds[1] = WrapHashEntry2(KEY_GONAME, WrapString(name)) if returnsError { ds[2] = WrapHashEntry2(KEY_RETURNS_ERROR, Boolean_TRUE) } return WrapHash(ds) } func (r *reflector) InitializerFromTagged(typeName string, parent eval.Type, tg eval.AnnotatedType) eval.OrderedMap { rf := tg.Type() ie := make([]*HashEntry, 0, 2) if rf.Kind() == reflect.Func { fn := rf.Name() if fn == `` { fn = `do` } ie = append(ie, WrapHashEntry2(KEY_FUNCTIONS, SingletonHash2(`do`, r.FunctionDeclFromReflect(fn, rf, false)))) } else { tags := tg.Tags(r.c) fs := r.Fields(rf) nf := len(fs) var pt reflect.Type if nf > 0 { es := make([]*HashEntry, 0, nf) for i, f := range fs { if i == 0 && f.Anonymous { // Parent pt = reflect.PtrTo(f.Type) continue } if f.PkgPath != `` { // Unexported continue } name, decl := r.ReflectFieldTags(&f, tags[f.Name]) es = append(es, WrapHashEntry2(name, decl)) } ie = append(ie, WrapHashEntry2(KEY_ATTRIBUTES, WrapHash(es))) } ms := r.Methods(rf) nm := len(ms) if nm > 0 { es := make([]*HashEntry, 0, nm) for _, m := range ms { if m.PkgPath != `` { // Not exported struct method continue } if pt != nil { if _, ok := pt.MethodByName(m.Name); ok { // Redeclarations of parent method are not included continue } } es = append(es, WrapHashEntry2(issue.CamelToSnakeCase(m.Name), r.FunctionDeclFromReflect(m.Name, m.Type, rf.Kind() != reflect.Interface))) } ie = append(ie, WrapHashEntry2(KEY_FUNCTIONS, WrapHash(es))) } } ats := tg.Annotations() if ats != nil && !ats.IsEmpty() { ie = append(ie, WrapHashEntry2(KEY_ANNOTATIONS, ats)) } return WrapHash(ie) } func (r *reflector) TypeFromReflect(typeName string, parent eval.Type, rf reflect.Type) eval.ObjectType { return r.TypeFromTagged(typeName, parent, eval.NewTaggedType(rf, nil), nil) } func (r *reflector) TypeFromTagged(typeName string, parent eval.Type, tg eval.AnnotatedType, rcFunc eval.Doer) eval.ObjectType { return NewObjectType3(typeName, parent, func(obj eval.ObjectType) eval.OrderedMap { obj.(*objectType).goType = tg r.c.ImplementationRegistry().RegisterType(r.c, obj, tg.Type()) if rcFunc != nil { rcFunc() } return r.InitializerFromTagged(typeName, parent, tg) }) } func (r *reflector) ReflectFieldTags(f *reflect.StructField, fh eval.OrderedMap) (name string, decl eval.OrderedMap) { as := make([]*HashEntry, 0) var val eval.Value var typ eval.Type if fh != nil { if v, ok := fh.Get4(KEY_NAME); ok { name = v.String() } if v, ok := fh.GetEntry(KEY_KIND); ok { as = append(as, v.(*HashEntry)) } if v, ok := fh.GetEntry(KEY_VALUE); ok { val = v.Value() as = append(as, v.(*HashEntry)) } if v, ok := fh.Get4(KEY_TYPE); ok { if t, ok := v.(eval.Type); ok { typ = t } } } if typ == nil { typ = eval.WrapReflectedType(r.c, f.Type) } optional := typ.IsInstance(eval.UNDEF, nil) if optional { if val == nil { // If no value is declared and the type is declared as optional, then // value is an implicit undef as = append(as, WrapHashEntry2(KEY_VALUE, _UNDEF)) } } else { if eval.Equals(val, _UNDEF) { // Convenience. If a value is declared as being undef, then ensure that // type accepts undef typ = NewOptionalType(typ) optional = true } } if optional { switch f.Type.Kind() { case reflect.Ptr, reflect.Interface: // OK. Can be nil default: // The field will always have a value (the Go zero value), so it cannot be nil. panic(eval.Error(eval.EVAL_IMPOSSIBLE_OPTIONAL, issue.H{`name`: f.Name, `type`: typ.String()})) } } as = append(as, WrapHashEntry2(KEY_TYPE, typ)) as = append(as, WrapHashEntry2(KEY_GONAME, WrapString(f.Name))) if name == `` { name = issue.CamelToSnakeCase(f.Name) } return name, WrapHash(as) } func (r *reflector) TypeSetFromReflect(typeSetName string, version semver.Version, aliases map[string]string, rTypes ...reflect.Type) eval.TypeSet { types := make([]*HashEntry, 0) prefix := typeSetName + `::` for _, rt := range rTypes { var parent eval.Type fs := r.Fields(rt) nf := len(fs) if nf > 0 { f := fs[0] if f.Anonymous && f.Type.Kind() == reflect.Struct { parent = NewTypeReferenceType(typeName(prefix, aliases, f.Type)) } } name := typeName(prefix, aliases, rt) types = append(types, WrapHashEntry2( name[strings.LastIndex(name, `::`)+2:], r.TypeFromReflect(name, parent, rt))) } es := make([]*HashEntry, 0) es = append(es, WrapHashEntry2(eval.KEY_PCORE_URI, WrapString(string(eval.PCORE_URI)))) es = append(es, WrapHashEntry2(eval.KEY_PCORE_VERSION, WrapSemVer(eval.PCORE_VERSION))) es = append(es, WrapHashEntry2(KEY_VERSION, WrapSemVer(version))) es = append(es, WrapHashEntry2(KEY_TYPES, WrapHash(types))) return NewTypeSetType(eval.RUNTIME_NAME_AUTHORITY, typeSetName, WrapHash(es)) } func ParentType(t reflect.Type) reflect.Type { if t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() == reflect.Struct && t.NumField() > 0 { f := t.Field(0) if f.Anonymous && f.Type.Kind() == reflect.Struct { return f.Type } } return nil } func typeName(prefix string, aliases map[string]string, rt reflect.Type) string { if rt.Kind() == reflect.Ptr { // Pointers have no names rt = rt.Elem() } name := rt.Name() if aliases != nil { if alias, ok := aliases[name]; ok { name = alias } } return prefix + name } func assertSettable(value *reflect.Value) { if !value.CanSet() { panic(eval.Error(eval.EVAL_ATTEMPT_TO_SET_UNSETTABLE, issue.H{`kind`: value.Type().String()})) } }
types/reflector.go
0.550607
0.412648
reflector.go
starcoder
package main import ( "fmt" r "github.com/lachee/raylib-goplus/raylib" ) func main() { screenWidth := 800 screenHeight := 450 r.SetConfigFlags(r.FlagMsaa4xHint) // Enable Multi Sampling Anti Aliasing 4x (if available) r.SetTraceLogLevel(r.LogAll) r.SetTraceLogCallback(func(logType r.TraceLogType, text string) { fmt.Println(logType.ToString(), ": ", text) }) r.InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform variable") defer r.UnloadAll() camera := r.Camera{} camera.Position = r.NewVector3(3.0, 3.0, 3.0) camera.Target = r.NewVector3(0.0, 1.5, 0.0) camera.Up = r.NewVector3(0.0, 1.0, 0.0) camera.FOVY = 45.0 dwarf := r.LoadModel("../resources/dwarf.obj") // Load OBJ model texture := r.LoadTexture("../resources/dwarf_diffuse.png") // Load model texture //dwarf.Materials.Maps[r.MapDiffuse].Texture = texture // Set dwarf model diffuse texture mat := dwarf.Materials[0] mat.SetTexture(r.MapAlbedo, texture) position := r.NewVector3(0.0, 0.0, 0.0) // Set model position shader := r.LoadShader("", "../resources/glsl330/swirl.fs") // Load postpro shader // Get variable (uniform) location on the shader to connect with the program // NOTE: If uniform variable could not be found in the shader, function returns -1 //swirlCenterLoc := r.GetShaderLocation(shader, "center") swirlCenterLoc := shader.GetLocation("center") swirlCenter := r.NewVector2(float32(screenWidth)/2, float32(screenHeight)/2) // Create a RenderTexture2D to be used for render to texture target := r.LoadRenderTexture(screenWidth-10, screenHeight-10) // Setup orbital camera //r.SetCameraMode(camera, r.CameraOrbital) // Set an orbital camera mode camera.SetMode(r.CameraOrbital) r.SetTargetFPS(60) for !r.WindowShouldClose() { // Update //---------------------------------------------------------------------------------- camera.Update() //Begin drawing like normal r.BeginDrawing() r.ClearBackground(r.RayWhite) //Start a texture drawing. Anything rendered will now be on the target r.BeginTextureMode(target) // Enable drawing to texture r.ClearBackground(r.RayWhite) // Clear texture background. 3D wont work if you forget this r.DrawText("Drawing Before 3D", 200, 10, 30, r.Red) //Draw some text to show the 3D models draw order //Start the 3D camera r.BeginMode3D(camera) r.DrawModel(*dwarf, position, 2.0, r.White) // Draw 3d model with texture r.DrawGrid(10, 1.0) // Draw a grid r.EndMode3D() //Stop the 3D camera, and draw text again above. r.DrawText("Drawing After 3D", 200, screenHeight-40, 30, r.Red) r.EndTextureMode() // End drawing to texture (now we have a texture available for next passes) //Button press to export the generated image. if r.IsKeyReleased(r.KeyS) { td := r.GetTextureData(target.Texture) td.Export("C:/myimage.png") td.Unload() } //Update the swirl position, converting Screen Space to Shader Space (by flipping the Y) swirlCenter = r.GetMousePosition() swirlCenter.Y = float32(screenHeight) - swirlCenter.Y //Set teh shader `center` value (its a Vector2). // Note that because we are setting 1 value, we use SetValueFloat32, // and NOT the SetValueFloat32V. shader.SetValueFloat32(swirlCenterLoc, swirlCenter.Decompose(), r.UniformVec2) r.BeginShaderMode(shader) // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) r.DrawTextureRec(target.Texture, r.NewRectangle(0, 0, float32(target.Texture.Width), float32(-target.Texture.Height)), r.NewVector2(0, 0), r.White) r.EndShaderMode() r.DrawText("(c) Dwarf 3D model by <NAME>", screenWidth-200, screenHeight-20, 10, r.Gray) r.DrawFPS(10, 10) r.EndDrawing() } r.CloseWindow() }
raylib-example/render-texture/rendertexture.go
0.605799
0.428114
rendertexture.go
starcoder