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 search import ( "github.com/ebay/beam/util/cmp" ) // A Definition is the interface that users of this package need to define. type Definition interface { // ExplorationRules returns the set of exploration rules that the optimizer may // apply in searching for a low-cost plan. ExplorationRules() []ExplorationRule // ImplementationRules returns the set of implementation rules that the // optimizer may apply in searching for a low-cost plan. ImplementationRules() []ImplementationRule // LocalCost returns the predicted costs of the operator itself, excluding // the costs of its inputs. It should return an infiniteCost for non-physical // operators. When invoked, each expr.Inputs group will have LogicalProperties // available but may not have Best set, and each of the groups Exprs may not have // LocalCost or CombinedCost set. LocalCost(expr *Expr) Cost // CombinedCost returns the cost of the operator combined with the costs of its inputs. // When invoked, each expr.Inputs group wil have Best set, and the Best expr // will have its LocalCost and CombinedCost set. // For most operators, this returns: // expr.LocalCost + [group.Best.CombinedCost for group in expr.Inputs] CombinedCost(expr *Expr) Cost // LogicalProperties computes and returns the logical properties for a logical // expression. It should panic if invoked for a physical operators, as this is // only needed when creating a new logical equivalence class. LogicalProperties(op Operator, inputs []LogicalProperties) LogicalProperties // MakePlanNode creates a new PlanNode object. A simple implementation could // just create a struct out of the given arguments, but this function exists as // an opportunity for the user of this package to transform the output into a // more convenient format. For example, the given operator can be cast into a // more specific type. MakePlanNode(op Operator, inputs []PlanNode, lprop LogicalProperties) PlanNode } // An ExplorationRule defines a logical equivalence. type ExplorationRule struct { Name string // Returns logical or physical expressions that are equivalent to the input. Apply func(*Expr) []*IntoExpr } // An ImplementationRule maps logical expressions to physical access plans. type ImplementationRule struct { Name string // Returns physical expressions that are equivalent to the non-physical input. Apply func(*Expr) []*IntoExpr } // An Operator is a logical or physical (executable) function attached to an // expression. type Operator interface { // Returns a human-readable single-line string describing the operator. String() string // The identity of an Operator is given by its Key() output. Two distinct // operators or operators with distinct parameters must produce distinct // keys. Also, the returned key cannot change over the lifetime of the // Operator -- Operators should be immutable. cmp.Key } // LogicalProperties are properties that remain true across logically equivalent // expressions. They are defined by the specific optimizer needs but are // commonly used to represent the schema of the results and the expected result // size. type LogicalProperties interface { String() string DetailString() string } // Cost represents an estimated cost for an Expr, used to find a low-cost plan. type Cost interface { // Returns a human-readable single-line description of the cost. String() string // Returns true if the expression can't be executed in any reasonable period of // time, false otherwise. Infinite() bool // Returns true if this cost is strictly lower than the given cost, false otherwise. // This method may assume the two Costs have been produced by the same Estimator // (for most Estimators, this and 'other' will have the same type). Less(other Cost) bool } // A PlanNode is part of a physically executable plan. It represents one node in // the plan tree that is the result of the search. A PlanNode differs from an // Expr in that it takes concrete inputs, whereas an Expr takes equivalence // classes as inputs. type PlanNode interface{}
src/github.com/ebay/beam/query/planner/search/definition.go
0.694303
0.625295
definition.go
starcoder
package gohome import ( // "fmt" "github.com/PucklaMotzer09/mathgl/mgl32" ) const ( LOOK_DIRECTION_MAGNIFIER float32 = 100.0 ) // A 3D camera used to show different parts of the world type Camera3D struct { // It's position in world space Position mgl32.Vec3 // The direction in which the camera looks LookDirection mgl32.Vec3 // The up vector of the camera Up mgl32.Vec3 rotation mgl32.Vec2 oldPosition mgl32.Vec3 oldLookDirection mgl32.Vec3 oldUp mgl32.Vec3 oldrotation mgl32.Vec2 // The maximum [pitch,yaw] rotation MaxRotation mgl32.Vec2 // The minimum [pitch,yaw] rotation MinRotation mgl32.Vec2 viewMatrix mgl32.Mat4 inverseViewMatrix mgl32.Mat4 } // Initialises everything of the camera and applies default values func (cam *Camera3D) Init() { cam.LookDirection = [3]float32{0.0, 0.0, -1.0} cam.MaxRotation = [2]float32{89.9, 370.0} cam.MinRotation = [2]float32{-89.9, -370.0} cam.Up = [3]float32{0.0, 1.0, 0.0} cam.CalculateViewMatrix() } func (cam *Camera3D) valuesChanged() bool { return cam.Position != cam.oldPosition || cam.LookDirection != cam.oldLookDirection || cam.Up != cam.oldUp } // Calculates the view matrix of the camera that will be used in the shaders func (cam *Camera3D) CalculateViewMatrix() { if cam.valuesChanged() { center := cam.Position.Add(cam.LookDirection.Mul(LOOK_DIRECTION_MAGNIFIER)) cam.viewMatrix = mgl32.LookAtV(cam.Position, center, cam.Up) cam.inverseViewMatrix = cam.viewMatrix.Inv() } else { return } cam.oldPosition = cam.Position cam.oldLookDirection = cam.LookDirection cam.oldUp = cam.Up } // Returns the view matrix of the camera func (cam *Camera3D) GetViewMatrix() mgl32.Mat4 { return cam.viewMatrix } // Returns the inverse view matrix of the camera func (cam *Camera3D) GetInverseViewMatrix() mgl32.Mat4 { return cam.inverseViewMatrix } // Sets the rotation of the camera using pitch and yaw // Rotates the look direction func (cam *Camera3D) SetRotation(rot mgl32.Vec2) { if rot[0] > 360.0 { rot[0] = rot[0] - 360.0 } else if rot[0] < -360.0 { rot[0] = -360.0 - rot[0] } if rot[1] > 360.0 { rot[1] = rot[1] - 360.0 } else if rot[1] < -360.0 { rot[1] = -360.0 - rot[1] } rot[0] = mgl32.Clamp(rot[0], cam.MinRotation[0], cam.MaxRotation[0]) rot[1] = mgl32.Clamp(rot[1], cam.MinRotation[1], cam.MaxRotation[1]) RX := mgl32.Rotate3DX(mgl32.DegToRad(rot[0])) RY := mgl32.Rotate3DY(mgl32.DegToRad(rot[1])) matrix := RY.Mat4().Mul4(RX.Mat4()) temp := [4]float32{0.0, 0.0, -1.0, 1.0} temp[0] = /*matrix.At(0, 0)*0.0 + matrix.At(0, 1)*0.0 +*/ matrix.At(0, 2)*-1.0 + matrix.At(0, 3)*1.0 temp[1] = /*matrix.At(1, 0)*0.0 + matrix.At(1, 1)*0.0 +*/ matrix.At(1, 2)*-1.0 + matrix.At(1, 3)*1.0 temp[2] = /*matrix.At(2, 0)*0.0 + matrix.At(2, 1)*0.0 +*/ matrix.At(2, 2)*-1.0 + matrix.At(2, 3)*1.0 temp[3] = /*matrix.At(3, 0)*0.0 + matrix.At(3, 1)*0.0 +*/ matrix.At(3, 2)*-1.0 + matrix.At(3, 3)*1.0 cam.LookDirection = [3]float32{temp[0] / temp[3], temp[1] / temp[3], temp[2] / temp[3]} cam.rotation = rot } // Adds [pitch,yaw] to the current rotation func (cam *Camera3D) AddRotation(rot mgl32.Vec2) { cam.SetRotation(cam.rotation.Add(rot)) } // Adds pos to the camera relative to the current rotation func (cam *Camera3D) AddPositionRelative(pos mgl32.Vec3) { if pos.Len() == 0.0 { return } cam.CalculateViewMatrix() matrix := cam.GetInverseViewMatrix() var worldPos mgl32.Vec3 worldPos[0] = matrix.At(0, 0)*pos[0] + matrix.At(0, 1)*pos[1] + matrix.At(0, 2)*pos[2] + matrix.At(0, 3)*1.0 worldPos[1] = matrix.At(1, 0)*pos[0] + matrix.At(1, 1)*pos[1] + matrix.At(1, 2)*pos[2] + matrix.At(1, 3)*1.0 worldPos[2] = matrix.At(2, 0)*pos[0] + matrix.At(2, 1)*pos[1] + matrix.At(2, 2)*pos[2] + matrix.At(2, 3)*1.0 worldPos = worldPos.Sub(cam.Position) cam.Position = cam.Position.Add(worldPos.Normalize().Mul(pos.Len())) } // Using the arguments of the look at matrix to configure the camera func (cam *Camera3D) LookAt(position, center, up mgl32.Vec3) { cam.Position = position cam.LookDirection = center.Sub(position).Normalize() cam.Up = up cam.rotation = [2]float32{0.0, 0.0} }
src/gohome/camera3d.go
0.687105
0.503357
camera3d.go
starcoder
package parser type ControlFlowExpr interface { Expr isControlFlowExpr() } type controlFlowExpr struct { expr } func (controlFlowExpr) isControlFlowExpr() {} // Placeholder for comments at the end of file type Noop struct { Location controlFlowExpr Value *Token } func (noop *Noop) String() string { return prettyFormatNode("", noop, 0) } type ScopeDef struct { Location Name *Token At *Token } func (sd *ScopeDef) String() string { return prettyFormatNode("", sd, 0) } type ExprBlock struct { Location controlFlowExpr *ScopeDef // Optional LBrace *Token Statements []ControlFlowExpr RBrace *Token } func (block *ExprBlock) String() string { return prettyFormatNode("", block, 0) } type ConditionalExpr struct { Location controlFlowExpr *ScopeDef // Optional If *Token Predicate Expr TrueClause *ExprBlock Else *Token // Optional FalseClause ControlFlowExpr // Optional } func (cond *ConditionalExpr) String() string { return prettyFormatNode("", cond, 0) } type ForExpr struct { Location controlFlowExpr *ScopeDef // Optional For *Token Predicate Expr Body *ExprBlock } func (fe *ForExpr) String() string { return prettyFormatNode("", fe, 0) } // <expr> type EvalExpr struct { Location controlFlowExpr Expression Expr } func (eval *EvalExpr) String() string { return prettyFormatNode("", eval, 0) } // (var|const) <name> = <expr>. NOTE: var can only be a statement within // an expression block, const can be a declaration or a statement. type AssignExpr struct { Location controlFlowExpr declaration AssignmentType *Token // Optional (const or var) Name *Token TypeSpec TypeSpec // Optional (disallow implicit embedded field access) Assign *Token Expression Expr } func (assign *AssignExpr) String() string { return prettyFormatNode("", assign, 0) } type ReturnExpr struct { Location controlFlowExpr Return *Token At *Token // Optional Label *Token // Optional Expression Expr } func (ret *ReturnExpr) String() string { return prettyFormatNode("", ret, 0) }
parser/control_flow_expr.go
0.761184
0.486392
control_flow_expr.go
starcoder
package controller type DecodeUnit struct { InstructionMap instructionCode string instructionType1 string instructionType2 string instructionName string instructionFormat map[string]string opcode string gapAddress bool } func NewDecodeUnit() *DecodeUnit { decodeunit := new(DecodeUnit) decodeunit.instructionMap = map[string][3]string{ // Arithmetic "000001": {"ADDS", "Arithmetic", "1"}, "100001": {"ADDS", "Arithmetic", "2"}, "000010": {"SUBS", "Arithmetic", "1"}, "100010": {"SUBS", "Arithmetic", "2"}, "000011": {"MULS", "Arithmetic", "1"}, "100011": {"MULS", "Arithmetic", "2"}, "000100": {"ANDS", "Arithmetic", "1"}, "100100": {"ANDS", "Arithmetic", "2"}, "000101": {"ORRS", "Arithmetic", "1"}, "100101": {"ORRS", "Arithmetic", "2"}, "000110": {"EORS", "Arithmetic", "1"}, "100110": {"EORS", "Arithmetic", "2"}, "000111": {"BICS", "Arithmetic", "1"}, "100111": {"BICS", "Arithmetic", "2"}, "001000": {"ASRS", "Arithmetic", "1"}, "101000": {"ASRS", "Arithmetic", "2"}, "001001": {"LSLS", "Arithmetic", "1"}, "101001": {"LSLS", "Arithmetic", "2"}, "001010": {"LSRS", "Arithmetic", "1"}, "101010": {"LSRS", "Arithmetic", "2"}, "001011": {"RORS", "Arithmetic", "1"}, "101011": {"RORS", "Arithmetic", "2"}, // Comparison "001100": {"CMN", "Comparison", "1"}, "101100": {"CMN", "Comparison", "2"}, "001101": {"CMP", "Comparison", "1"}, "101101": {"CMP", "Comparison", "2"}, // Bypass "001110": {"MOVS", "Bypass", "1"}, "101110": {"MOVS", "Bypass", "2"}, "001111": {"BEQ", "Bypass", "1"}, "101111": {"BEQ", "Bypass", "2"}, "010000": {"BNE", "Bypass", "1"}, "110000": {"BNE", "Bypass", "2"}, "010001": {"BLT", "Bypass", "1"}, "110001": {"BLT", "Bypass", "2"}, "010010": {"BL", "Bypass", "1"}, "110010": {"BL", "Bypass", "2"}, "010011": {"BX", "Bypass", "1"}, //"110011": {"BX", "Bypass", "2"}, PERGUNTAR PARA PROFESSOR "011011": {"B", "Bypass", "1"}, "111011": {"B", "Bypass", "2"}, // Load and Store "010100": {"LDR", "Load", "1"}, "110100": {"LDR", "Load", "2"}, "010101": {"STR", "Store", "1"}, "110101": {"STR", "Store", "2"}, // Nothing "000000": {"NOP", "Nothing", "1"}, } decodeunit.gapAddress = false decodeunit.instructionCode = "00000000000000000000000000000000" decodeunit.instructionType1 = "" decodeunit.instructionType2 = "" decodeunit.instructionFormat = make(map[string]string) return decodeunit } func (it *DecodeUnit) SetInstruction(inst string) { it.instructionCode = inst } func (dc *DecodeUnit) GetOpcode() string { return dc.opcode } func (dc *DecodeUnit) getOpcode(inst string) string { instructionRune := []rune(dc.instructionCode) opcode := string(instructionRune[0:6]) return opcode } func (dc *DecodeUnit) GetGapAddressFlag() bool { return dc.gapAddress } func (dc *DecodeUnit) MapInstruction() { dc.opcode = dc.getOpcode(dc.instructionCode) dc.instructionName = dc.instructionMap[dc.opcode][0] dc.instructionType1 = dc.instructionMap[dc.opcode][1] dc.instructionType2 = dc.instructionMap[dc.opcode][2] } func (dc *DecodeUnit) SplitInstruction() { instructionRune := []rune(dc.instructionCode) dc.MapInstruction() // Instance map dc.instructionFormat = make(map[string]string) // Verify what's type of instruction if dc.instructionType1 == "Arithmetic" { dc.gapAddress = false if dc.instructionType2 == "1" { dc.instructionFormat["rd"] = string(instructionRune[6:11]) dc.instructionFormat["rn"] = string(instructionRune[11:16]) dc.instructionFormat["rm"] = string(instructionRune[16:21]) } else { dc.instructionFormat["rd"] = string(instructionRune[6:11]) dc.instructionFormat["rn"] = string(instructionRune[11:16]) dc.instructionFormat["data"] = string(instructionRune[16:32]) } } else if dc.instructionType1 == "Comparison" { dc.gapAddress = false if dc.instructionType2 == "1" { dc.instructionFormat["rn"] = string(instructionRune[6:11]) dc.instructionFormat["rm"] = string(instructionRune[11:16]) } else { dc.instructionFormat["rn"] = string(instructionRune[6:11]) dc.instructionFormat["imediato"] = string(instructionRune[11:19]) } } else if dc.instructionType1 == "Bypass" { dc.gapAddress = true if dc.instructionType2 == "1" { dc.instructionFormat["rn"] = string(instructionRune[6:11]) } else { dc.instructionFormat["label"] = string(instructionRune[6:32]) } } else if dc.instructionType1 == "Load" || dc.instructionType1 == "Store" { dc.gapAddress = false if dc.instructionType2 == "1" { dc.instructionFormat["rd"] = string(instructionRune[6:11]) dc.instructionFormat["rn"] = string(instructionRune[11:16]) } else { dc.instructionFormat["rd"] = string(instructionRune[6:11]) dc.instructionFormat["address"] = string(instructionRune[11:25]) } } else if dc.instructionType1 == "Nop" { dc.gapAddress = false dc.instructionFormat["rest"] = string(instructionRune[6:32]) } else { dc.gapAddress = false dc.instructionFormat["rest"] = dc.instructionCode } } func (dc *DecodeUnit) GetInstruction() string { return dc.instructionCode } func (dc *DecodeUnit) GetInstructionFormat() map[string]string { return dc.instructionFormat } func (dc *DecodeUnit) GetInstructionName() string { return dc.instructionName } func (dc *DecodeUnit) GetInstructionType2() string { return dc.instructionType2 }
controller/decodeunit.go
0.636692
0.530845
decodeunit.go
starcoder
package types // TrafficAccidents holds the data for the traffic accidents. type TrafficAccidents struct { Year int `json:"year" fake:"{year}"` DeadlyAccidents int `json:"deadly_accidents" fake:"{number:0,100}"` Deaths int `json:"deaths" fake:"{number:0,100}"` Jurisdiction string `json:"jurisdiction" fake:"{randomstring:[Γ.Π.Α.Δ. ΑΤΤΙΚΗΣ,Γ.Π.Α.Δ. ΚΡΗΤΗΣ,Γ.Α.Δ. ΘΕΣΣΑΛΟΝΙΚΗΣ]}"` OtherAccidents int `json:"other_accidents" fake:"{number:0,1000}"` OtherInjured int `json:"other_injured" fake:"{number:0,1000}"` SeriousAccidents int `json:"serious_accidents" fake:"{number:0,100}"` SeriouslyInjured int `json:"seriously_injured" fake:"{number:0,100}"` } // RescueOperations holds the data for the rescue operations. type RescueOperations struct { Year int `json:"year" fake:"{year}"` Incident string `json:"incident" fake:"{randomstring:[ΑΓΝΟΟΥΜΕΝΟ ΣΚΑΦΟΣ,ΕΙΣΡΟΗ ΥΔΑΤΩΝ,ΠΡΟΣΚΡΟΥΣΗ,ΚΑΤΑΓΓΕΛΙΕΣ]}"` Domestic int `json:"domestic" fake:"{number:0,50}"` International int `json:"international" fake:"{number:0,10}"` } // TrafficViolations holds the data for the traffic violations. type TrafficViolations struct { Year int `json:"year" fake:"{year}"` Violation string `json:"violation" fake:"{randomstring:[ΑΝΑΣΦΑΛΙΣΤΑ ΟΧΗΜΑΤΑ,ΘΟΡΥΒΟΙ ΓΕΝΙΚΑ,ΠΑΡΑΝΟΜΕΣ ΣΤΑΘΜΕΥΣΕΙΣ]}"` Count int `json:"count" fake:"{number:0,10000}"` } // CrimeStatistics holds statistics for crime. type CrimeStatistics struct { Year int `json:"year" fake:"{year}"` Crime string `json:"crime" fake:"{randomstring:[ΑΝΘΡΩΠΟΚΤΟΝΙΕΣ,ΑΠΑΤΕΣ,ΕΚΒΙΑΣΕΙΣ]}"` Committed int `json:"committed" fake:"{number:0,1000}"` Attempted int `json:"attempted" fake:"{number:0,1000}"` Solved int `json:"solved" fake:"{number:0,100}"` DomesticCriminals int `json:"domestic_criminals" fake:"{number:0,1000}"` ForeignCriminals int `json:"foreign_criminals" fake:"{number:0,1000}"` } // FinancialCrimes holds the data for the financial crimes. type FinancialCrimes struct { Year int `json:"year" fake:"{year}"` Crime string `json:"crime" fake:"{randomstring:[Λαθρεμπόριο καυσίμων,Λαθρεμπόριο αλκοόλ,Λαθρεμπόριο τσιγάρων]}"` Count int `json:"count" fake:"{number:0,100}"` } // NumberOfLawyers holds the data for the number of lawyers. type NumberOfLawyers struct { Year int `json:"year" fake:"{year}"` Quarter string `json:"quarter" fake:"{randomstring:[Q1,Q2,Q3,Q4]}"` Active int `json:"active" fake:"{number:0,10000}"` Entrants int `json:"entrants" fake:"{number:0,100}"` Exits int `json:"exits" fake:"{number:0,100}"` } // NumberOfLawFirms holds the data for the number of law firms. type NumberOfLawFirms struct { Year int `json:"year" fake:"{year}"` Quarter string `json:"quarter" fake:"{randomstring:[Q1,Q2,Q3,Q4]}"` Active int `json:"active" fake:"{number:0,10000}"` Entrants int `json:"entrants" fake:"{number:0,100}"` Exits int `json:"exits" fake:"{number:0,100}"` }
types/crime_justice.go
0.57081
0.533154
crime_justice.go
starcoder
package script import ( "fmt" "math" "strconv" "time" "unsafe" ) const ( ValueTypeInterface uint16 = iota // must be zero here ValueTypeBool ValueTypeInt ValueTypeFloat ) type pointer = unsafe.Pointer type Value struct { pointer *interface{} } func (value *Value) GetType() uint16 { return uint16(*(*uint64)(pointer(value)) >> 48) } func (value Value) Get() interface{} { switch value.GetType() { case ValueTypeInt: return value.GetInt() case ValueTypeFloat: return value.GetFloat() case ValueTypeBool: return value.GetBool() default: return value.GetInterface() } } func (value *Value) Set(v interface{}) Value { switch val := v.(type) { case bool: value.SetBool(Bool(val)) case int: value.SetInt(Int(val)) case int64: value.SetInt64(Int64(val)) case int32: value.SetInt(Int(val)) case uint32: value.SetInt64(Int64(val)) case int8: value.SetInt(Int(val)) case uint8: value.SetInt(Int(val)) case float32: value.SetFloat(Float(val)) case float64: value.SetFloat64(Float64(val)) case string: value.SetInterface(String(val)) case time.Time: value.SetInt64(Int64(val.UnixNano() / 1000000)) case Int: value.SetInt(val) case Float: value.SetFloat(val) case Bool: value.SetBool(val) default: value.SetInterface(val) } return *value } func (value Value) Interface() *interface{} { return value.pointer } func (value Value) GetInterface() interface{} { if value.pointer == nil { return nil } return *value.pointer } func InterfaceToValue(val interface{}) Value { value := Value{} value.SetInterface(val) return value } func ToValue(val interface{}) Value { value := Value{} value.Set(val) return value } func (value *Value) SetInterface(v interface{}) { if v != nil { value.pointer = &v } else { value.pointer = nil } } func (value *Value) GetInt() Int { return *(*Int)(pointer(value)) } func (value *Value) SetInt(v Int) { *(*uint32)(pointer(uintptr(pointer(value)) + 4)) = uint32(ValueTypeInt) << 16 *(*Int)(pointer(value)) = v } func (value *Value) GetFloat() Float { return *(*Float)(pointer(value)) } func (value *Value) SetFloat(v Float) { *(*uint32)(pointer(uintptr(pointer(value)) + 4)) = uint32(ValueTypeFloat) << 16 *(*Float)(pointer(value)) = v } func (value *Value) GetBool() Bool { return *(*Bool)(pointer(value)) } func (value *Value) SetBool(v Bool) { *(*uint32)(pointer(uintptr(pointer(value)) + 4)) = uint32(ValueTypeBool) << 16 *(*Bool)(pointer(value)) = v } func (value Value) GetObject() Object { val := value.GetInterface() if val == nil { return nil } return val.(Object) } func (value Value) String() string { switch value.GetType() { case ValueTypeInt: return strconv.FormatInt(int64(value.GetInt()), 10) case ValueTypeFloat: return strconv.FormatFloat(float64(value.GetFloat()), 'g', -1, 32) case ValueTypeBool: return fmt.Sprint(bool(value.GetBool())) default: switch val := value.GetInterface().(type) { case String: return fmt.Sprintf("\"%v\"", string(val)) default: return fmt.Sprintf("%v", val) } } } func (value Value) ToInt() Int { switch value.GetType() { case ValueTypeInt: return value.GetInt() case ValueTypeFloat: return Int(value.GetFloat()) default: switch val := value.GetInterface().(type) { case Int64: return Int(val) case Float64: return Int(val) } return 0 } } func (value Value) ToFloat() Float { switch value.GetType() { case ValueTypeFloat: return value.GetFloat() case ValueTypeInt: return Float(value.GetInt()) case ValueTypeInterface: switch val := value.GetInterface().(type) { case Int64: return Float(val) case Float64: return Float(val) } } return Float(math.NaN()) } func (value Value) ToInt64() Int64 { switch value.GetType() { case ValueTypeInterface: switch val := value.GetInterface().(type) { case Int64: return val case Float64: return Int64(val) } case ValueTypeInt: return Int64(value.GetInt()) case ValueTypeFloat: return Int64(value.GetFloat()) } return 0 } func (value *Value) SetInt64(s Int64) { value.SetInterface(s) } func (value Value) ToFloat64() Float64 { switch value.GetType() { case ValueTypeInterface: switch val := value.GetInterface().(type) { case Float64: return val case Int64: return Float64(val) } case ValueTypeFloat: return Float64(value.GetFloat()) case ValueTypeInt: return Float64(value.GetInt()) } return Float64(math.NaN()) } func (value *Value) SetFloat64(s Float64) { value.SetInterface(s) } func (value Value) ToBool() Bool { switch value.GetType() { case ValueTypeBool: return value.GetBool() case ValueTypeInt: return value.GetInt() != 0 case ValueTypeFloat: return value.GetFloat() != 0 case ValueTypeInterface: switch val := value.GetInterface().(type) { case Int64: return val != 0 case Float64: return val != 0 default: return true } } return false } func (value Value) ToString() string { switch value.GetType() { case ValueTypeInterface: return fmt.Sprint(value.GetInterface()) } return "" } func (value Value) IsNull() bool { return value.pointer == nil || value.Get() == Null } func (value *Value) SetNull() { value.pointer = nil }
value.go
0.559531
0.420897
value.go
starcoder
package binarysearch /* # https://leetcode.com/explore/learn/card/binary-search/138/background/1038/ Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Note: You may assume that all elements in nums are unique. n will be in the range [1, 10000]. The value of each element in nums will be in the range [-9999, 9999]. */ func Search(nums []int, target int) int { return search(nums, target) } func search(nums []int, target int) int { left, right := 0, len(nums)-1 for right >= left { mid := (left + right) / 2 if nums[mid] == target { return mid } else if nums[mid] > target { right = mid - 1 } else { left = mid + 1 } } return -1 } /* leetcode上的解法 */ func binarySearch(nums []int, l int, r int, tar int) int { if l > r { return -1 } mid := (l + r) / 2 if nums[mid] == tar { return mid } if nums[l] <= nums[mid] { // 此区间是升序区间 if tar >= nums[l] && tar < nums[mid] { // tar在升序区间序列中 return binarySearch(nums, l, mid-1, tar) } return binarySearch(nums, mid+1, r, tar) } if tar > nums[mid] && tar <= nums[r] { //tar在mid和r区间中 return binarySearch(nums, mid+1, r, tar) } return binarySearch(nums, l, mid-1, tar) } func searchInLeetCode(nums []int, target int) int { return binarySearch(nums, 0, len(nums)-1, target) } /* # https://leetcode.com/explore/learn/card/binary-search/125/template-i/952/ Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 */ func SearchWithRorated(nums []int, target int) int { return searchWithRorated(nums, target) } func searchWithRorated(nums []int, target int) int { if nums == nil || len(nums) == 0 { return -1 } if len(nums) == 1 && nums[0] == target { return 0 } else if len(nums) == 1 && nums[0] != target { return -1 } povit := -1 for i := 0; i < len(nums)-1; i++ { if nums[i] > nums[i+1] { povit = i break } } if povit >= 0 && (nums[povit] < target || nums[povit+1] > target) { return -1 } var wait []int var inRight bool if povit < 0 { wait = nums } else if nums[len(nums)-1] >= target { wait = nums[povit+1:] inRight = true } else { wait = nums[:povit+1] } left, right := 0, len(wait)-1 for right >= left { mid := (left + right) / 2 if wait[mid] == target { if inRight { return mid + povit + 1 } return mid } else if wait[mid] > target { right = mid - 1 } else { left = mid + 1 } } return -1 }
binarysearch/array.go
0.810291
0.61734
array.go
starcoder
package board import ( "fmt" "strings" ) // MoveType indicates the type of move. The no-progress counter is reset with any non-Normal move. type MoveType uint8 const ( Normal MoveType = 1 + iota Push // Pawn move Jump // Pawn 2-square move EnPassant // Implicitly a pawn capture QueenSideCastle KingSideCastle Capture Promotion CapturePromotion ) func (m MoveType) String() string { switch m { case Normal: return "Normal" case Push: return "Push" case Jump: return "Jump" case EnPassant: return "EnPassant" case QueenSideCastle: return "QueenSideCastle" case KingSideCastle: return "KingSideCastle" case Capture: return "Capture" case Promotion: return "Promotion" case CapturePromotion: return "CapturePromotion" default: return "?" } } // TODO(herohde) 2/21/2021: add remarks, like "dubious", to represent standard notation? // Move represents a not-necessarily legal move along with contextual metadata. 64bits. type Move struct { Type MoveType From, To Square Piece Piece // moved piece Promotion Piece // desired piece for promotion, if any. Capture Piece // captured piece, if any. Not set if EnPassant. } // ParseMove parses a move in pure algebraic coordinate notation, such as "a2a4" or "a7a8q". // The parsed move does not contain contextual information like castling or en passant. func ParseMove(str string) (Move, error) { runes := []rune(str) if len(runes) < 4 || len(runes) > 5 { return Move{}, fmt.Errorf("invalid move: '%v'", str) } from, err := ParseSquare(runes[0], runes[1]) if err != nil { return Move{}, fmt.Errorf("invalid from: '%v': %v", str, err) } to, err := ParseSquare(runes[2], runes[3]) if err != nil { return Move{}, fmt.Errorf("invalid to: '%v': %v", str, err) } if len(runes) == 5 { promo, ok := ParsePiece(runes[4]) if !ok || promo == Pawn || promo == King { return Move{}, fmt.Errorf("invalid promotion: '%v'", str) } return Move{From: from, To: to, Promotion: promo}, nil } return Move{From: from, To: to}, nil } // IsInvalid true iff the move is of invalid type. Convenience function. func (m Move) IsInvalid() bool { return m.Type == 0 } // IsCapture returns true iff the move is a Capture or CapturePromotion. Convenience function. func (m Move) IsCapture() bool { return m.Type == CapturePromotion || m.Type == Capture } // IsPromotion returns true iff the move is a Promotion or CapturePromotion. Convenience function. func (m Move) IsPromotion() bool { return m.Type == CapturePromotion || m.Type == Promotion } // IsCastle returns true iff the move is a KingSideCastle or QueenSideCastle. Convenience function. func (m Move) IsCastle() bool { return m.Type == KingSideCastle || m.Type == QueenSideCastle } // EnPassantTarget return the e.p target square, if a Jump move. For e2-e4, it turns e3. func (m Move) EnPassantTarget() (Square, bool) { if m.Type != Jump { return 0, false } if m.To.Rank() == Rank4 { // White return NewSquare(m.To.File(), Rank3), true } else { return NewSquare(m.To.File(), Rank6), true } } // EnPassantCapture return the e.p capture square, if a EnPassant move. For d4*e3 e.p, it turns e4. func (m Move) EnPassantCapture() (Square, bool) { if m.Type != EnPassant { return 0, false } if m.To.Rank() == Rank3 { // Black return NewSquare(m.To.File(), Rank4), true } else { return NewSquare(m.To.File(), Rank5), true } } // CastlingRookMove returns the implicit rook move (from, to), if a KingSideCastle or QueenSideCastle move. func (m Move) CastlingRookMove() (Square, Square, bool) { switch { case m.Type == KingSideCastle && m.From == E1: return H1, F1, true case m.Type == QueenSideCastle && m.From == E1: return A1, D1, true case m.Type == KingSideCastle && m.From == E8: return H8, F8, true case m.Type == QueenSideCastle && m.From == E8: return A8, D8, true default: return 0, 0, false } } // CastlingRightsLost returns the castling rights that are definitely not present after this move. // If king moves, rights are lost. Ditto if rook moves or is captured. func (m Move) CastlingRightsLost() Castling { switch { case m.From == E1: return WhiteKingSideCastle | WhiteQueenSideCastle case m.From == A1 || m.To == A1: return WhiteQueenSideCastle case m.From == H1 || m.To == H1: return WhiteKingSideCastle case m.From == E8: return BlackKingSideCastle | BlackQueenSideCastle case m.From == A8 || m.To == A8: return BlackQueenSideCastle case m.From == H8 || m.To == H8: return BlackKingSideCastle default: return NoCastlingRights } } func (m Move) Equals(o Move) bool { return m.From == o.From && m.To == o.To && m.Promotion == o.Promotion } func (m Move) String() string { if m.IsInvalid() { return "invalid" } switch m.Type { case Promotion: return fmt.Sprintf("%v-%v=%v", m.From, m.To, m.Promotion) case CapturePromotion: return fmt.Sprintf("%v*%v=%v", m.From, m.To, m.Promotion) case EnPassant: return fmt.Sprintf("%v*%v e.p.", m.From, m.To) case KingSideCastle: return fmt.Sprintf("0-0") case QueenSideCastle: return fmt.Sprintf("0-0-0") case Capture: return fmt.Sprintf("%v%v*%v", ignorePawn(m.Piece), m.From, m.To) default: return fmt.Sprintf("%v%v-%v", ignorePawn(m.Piece), m.From, m.To) } } // PrintMoves prints a list of moves. func PrintMoves(list []Move) string { return FormatMoves(list, func(m Move) string { return m.String() }) } // FormatMoves formats a list of moves. func FormatMoves(list []Move, fn func(Move) string) string { var ret []string for _, m := range list { ret = append(ret, fn(m)) } return strings.Join(ret, " ") } func ignorePawn(piece Piece) string { if piece == Pawn || piece == NoPiece { return "" } return piece.String() }
pkg/board/move.go
0.605799
0.422445
move.go
starcoder
package render import ( "fmt" "github.com/jschaf/bibtex/ast" "io" ) type NodeRenderer interface { Render(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) } type NodeRendererFunc func(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) func (nf NodeRendererFunc) Render(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return nf(w, n, entering) } func Defaults() []NodeRenderer { return []NodeRenderer{ ast.KindTexComment: NodeRendererFunc(renderTexComment), ast.KindTexCommentGroup: NodeRendererFunc(renderTexCommentGroup), ast.KindBadExpr: NodeRendererFunc(renderBadExpr), ast.KindIdent: NodeRendererFunc(renderIdent), ast.KindNumber: NodeRendererFunc(renderNumber), ast.KindAuthors: NodeRendererFunc(renderAuthors), ast.KindAuthor: NodeRendererFunc(renderAuthor), ast.KindUnparsedText: NodeRendererFunc(renderUnparsedText), ast.KindParsedText: NodeRendererFunc(renderParsedText), ast.KindText: NodeRendererFunc(renderText), ast.KindTextComma: NodeRendererFunc(renderTextComma), ast.KindTextEscaped: NodeRendererFunc(renderTextEscaped), ast.KindTextHyphen: NodeRendererFunc(renderTextHyphen), ast.KindTextMath: NodeRendererFunc(renderTextMath), ast.KindTextNBSP: NodeRendererFunc(renderTextNBSP), ast.KindTextSpace: NodeRendererFunc(renderTextSpace), ast.KindTextMacro: NodeRendererFunc(renderTextMacro), ast.KindConcatExpr: NodeRendererFunc(renderConcatExpr), ast.KindBadStmt: NodeRendererFunc(renderBadStmt), ast.KindTagStmt: NodeRendererFunc(renderTagStmt), ast.KindBadDecl: NodeRendererFunc(renderBadDecl), ast.KindAbbrevDecl: NodeRendererFunc(renderAbbrevDecl), ast.KindBibDecl: NodeRendererFunc(renderBibDecl), ast.KindPreambleDecl: NodeRendererFunc(renderPreambleDecl), ast.KindFile: NodeRendererFunc(renderFile), ast.KindPackage: NodeRendererFunc(renderPackage), } } func renderTexComment(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderTexCommentGroup(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderBadExpr(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkStop, fmt.Errorf("render bad expr") } func renderIdent(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { ident := n.(*ast.Ident) _, _ = w.Write([]byte(ident.Name)) return ast.WalkContinue, nil } func renderNumber(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderAuthors(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderAuthor(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderUnparsedText(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderParsedText(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { txt := n.(*ast.ParsedText) left, right := `{`, `}` if txt.Delim == ast.QuoteDelimiter { left, right = `"`, `"` } if entering { if _, err := w.Write([]byte(left)); err != nil { return ast.WalkStop, fmt.Errorf("default renderParsedText left: %w", err) } } else { if _, err := w.Write([]byte(right)); err != nil { return ast.WalkStop, fmt.Errorf("default renderParsedText right: %w", err) } } return ast.WalkContinue, nil } func renderText(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { txt := n.(*ast.TextSpace) if _, err := w.Write([]byte(txt.Value)); err != nil { return ast.WalkStop, fmt.Errorf("default renderText: %w", err) } return ast.WalkContinue, nil } func renderTextComma(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { if _, err := w.Write([]byte(",")); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextComma: %w", err) } return ast.WalkContinue, nil } func renderTextEscaped(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { esc := n.(*ast.TextEscaped) if _, err := w.Write([]byte(`\` + esc.Value)); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextEscaped: %w", err) } return ast.WalkContinue, nil } func renderTextHyphen(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { if _, err := w.Write([]byte("-")); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextHyphen: %w", err) } return ast.WalkContinue, nil } func renderTextMath(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { if entering { if _, err := w.Write([]byte("$")); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextMath left: %w", err) } } else { if _, err := w.Write([]byte("$")); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextMath right: %w", err) } } return ast.WalkContinue, nil } func renderTextNBSP(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { if _, err := w.Write([]byte(" ")); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextNBSP: %w", err) } return ast.WalkContinue, nil } func renderTextSpace(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { sp := n.(*ast.TextSpace) if _, err := w.Write([]byte(sp.Value)); err != nil { return ast.WalkStop, fmt.Errorf("default renderTextSpace: %w", err) } return ast.WalkContinue, nil } func renderTextMacro(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { // Skip the command and write the args. return ast.WalkContinue, nil } func renderConcatExpr(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil // skip } func renderBadStmt(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkStop, fmt.Errorf("render bad stmt") } func renderTagStmt(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderBadDecl(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderAbbrevDecl(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderBibDecl(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderPreambleDecl(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderFile(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } func renderPackage(w io.Writer, n ast.Node, entering bool) (ast.WalkStatus, error) { return ast.WalkContinue, nil } type TextRenderer struct { } type Option func(p *TextRenderer) func NewTextRenderer() *TextRenderer { return &TextRenderer{} } func (p TextRenderer) Render(w io.Writer, x ast.Expr) (mErr error) { switch t := x.(type) { case *ast.ParsedText: for _, v := range t.Values { if err := p.Render(w, v); err != nil { return err } } case *ast.ConcatExpr: if mErr = p.Render(w, t.X); mErr != nil { return } _, _ = w.Write([]byte{'#'}) if mErr = p.Render(w, t.Y); mErr != nil { return } case *ast.TextMacro: for _, v := range t.Values { if mErr = p.Render(w, v); mErr != nil { return } } // TODO: add overrides and TextMacro case *ast.TextComma: _, mErr = w.Write([]byte(",")) case *ast.Text: _, mErr = w.Write([]byte(t.Value)) case *ast.TextEscaped: _, mErr = w.Write([]byte(t.Value)) case *ast.TextHyphen: _, mErr = w.Write([]byte("-")) case *ast.TextMath: if _, mErr = w.Write([]byte("$")); mErr != nil { return mErr } if _, mErr = w.Write([]byte(t.Value)); mErr != nil { return mErr } if _, mErr = w.Write([]byte("$")); mErr != nil { return mErr } case *ast.TextNBSP, *ast.TextSpace: _, mErr = w.Write([]byte(" ")) default: return fmt.Errorf("renderer - unhandled ast.Expr type %T, %v", t, t) } return nil }
render/render.go
0.70619
0.460168
render.go
starcoder
package main import ( "github.com/ByteArena/box2d" "github.com/wdevore/Ranger-Go-IGE/api" "github.com/wdevore/Ranger-Go-IGE/engine/rendering/color" "github.com/wdevore/Ranger-Go-IGE/extras/shapes" ) type quadBoxPhysicsComponent struct { physicsComponent boxes []api.INode } func newQuadBoxPhysicsComponent() *quadBoxPhysicsComponent { o := new(quadBoxPhysicsComponent) return o } func (p *quadBoxPhysicsComponent) Update(msPerUpdate, secPerUpdate float64) { if p.b2Body.IsActive() { pos := p.b2Body.GetPosition() p.phyNode.SetPosition(float32(pos.X), float32(pos.Y)) rot := p.b2Body.GetAngle() p.phyNode.SetRotation(rot) } } func (p *quadBoxPhysicsComponent) Reset() { x := p.position.X() y := p.position.Y() p.phyNode.SetPosition(float32(x), float32(y)) p.b2Body.SetTransform(box2d.MakeB2Vec2(float64(x), float64(y)), 0.0) p.b2Body.SetLinearVelocity(box2d.MakeB2Vec2(0.0, 0.0)) p.b2Body.SetAngularVelocity(0.0) p.b2Body.SetAwake(true) } func (p *quadBoxPhysicsComponent) Build(world api.IWorld, parent api.INode, phyWorld *box2d.B2World, position api.IPoint) { // phyNode is the Anchor node. p.phyNode, _ = shapes.NewMonoSquareNode("Anchor", api.OUTLINED, true, world, parent) // Make the anchor invisible but not the children. gsq := p.phyNode.(*shapes.MonoSquareNode) gsq.SetOutlineAlpha(0.0) p.phyNode.SetPosition(position.X(), position.Y()) p.buildBoxes(world, p.phyNode) p.buildPhysics(phyWorld, position) } func (p *quadBoxPhysicsComponent) buildPhysics(phyWorld *box2d.B2World, position api.IPoint) { p.position = position // ------------------------------------------- // A body def used to create bodies bDef := box2d.MakeB2BodyDef() bDef.Type = box2d.B2BodyType.B2_dynamicBody // Set the position of the Body px := position.X() py := position.Y() bDef.Position.Set( float64(px), float64(py), ) // An instance of a body to contain Fixtures p.b2Body = phyWorld.CreateBody(&bDef) for i := 0.0; i < 4.0; i++ { // Every Fixture has a shape b2Shape := box2d.MakeB2PolygonShape() // Box2D assumes the same is defined in unit-space which // means if the object is defined otherwise we need the object // to return the correct value box := p.boxes[int(i)] tcc := box.(*shapes.MonoSquareNode) pos := box.Position() offsetFromBodyOriginX := float64(pos.X()) offsetFromBodyOriginY := float64(pos.Y()) b2Shape.SetAsBoxFromCenterAndAngle( float64(tcc.HalfSide()), float64(tcc.HalfSide()), box2d.B2Vec2{X: offsetFromBodyOriginX, Y: offsetFromBodyOriginY}, 0.0) fd := box2d.MakeB2FixtureDef() fd.Shape = &b2Shape fd.Density = 1.0 fd.Friction = i / 4.0 fd.Restitution = (4.0 - i) / 4.0 p.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body } } func (p *quadBoxPhysicsComponent) buildBoxes(world api.IWorld, parent api.INode) error { var err error // -------------------------------------------------------------- node, err := shapes.NewMonoSquareNode("Square1", api.FILLED, true, world, parent) if err != nil { return err } node.SetScale(3.0) node.SetPosition(1.5, 0.0) gsq := node.(*shapes.MonoSquareNode) gsq.SetFilledColor(color.NewPaletteInt64(color.Aqua)) gsq.SetFilledAlpha(0.5) p.boxes = append(p.boxes, node) // -------------------------------------------------------------- node, err = shapes.NewMonoSquareNode("Square2", api.FILLED, true, world, parent) if err != nil { return err } node.SetScale(3.0) node.SetPosition(0.0, 1.5) gsq = node.(*shapes.MonoSquareNode) gsq.SetFilledColor(color.NewPaletteInt64(color.Aqua)) gsq.SetFilledAlpha(0.5) p.boxes = append(p.boxes, node) // -------------------------------------------------------------- node, err = shapes.NewMonoSquareNode("Square3", api.FILLED, true, world, parent) if err != nil { return err } node.SetScale(3.0) node.SetPosition(-1.5, 0.0) gsq = node.(*shapes.MonoSquareNode) gsq.SetFilledColor(color.NewPaletteInt64(color.Aqua)) gsq.SetFilledAlpha(0.5) p.boxes = append(p.boxes, node) // -------------------------------------------------------------- node, err = shapes.NewMonoSquareNode("Square4", api.FILLED, true, world, parent) if err != nil { return err } node.SetScale(3.0) node.SetPosition(0.0, -1.5) gsq = node.(*shapes.MonoSquareNode) gsq.SetFilledColor(color.NewPaletteInt64(color.Aqua)) gsq.SetFilledAlpha(0.5) p.boxes = append(p.boxes, node) return nil }
examples/complex/physics/basic/p5_bouncy_blocks/quadbox_physics_component.go
0.665193
0.464234
quadbox_physics_component.go
starcoder
package main import ( "fmt" "math" "runtime" "sort" "github.com/fluhus/biostuff/formats/newick" "github.com/fluhus/gostuff/ppln" ) // Converts an abundance map to a list of flat nodes. Returns the sum of // abundances under the given tree. func abundanceToFlatNodes(abnd map[string]float64, tree *newick.Node, enum map[*newick.Node]int, result *[]flatNode) float64 { sum := 0.0 for _, c := range tree.Children { sum += abundanceToFlatNodes(abnd, c, enum, result) } if a := abnd[tree.Name]; a > 0 { sum += a } if sum > 0 { *result = append(*result, flatNode{enum[tree], sum}) } return sum } // Sorts and divides abundances by their sum. func normalizeFlatNodes(nodes []flatNode) { sort.Slice(nodes, func(i, j int) bool { return nodes[i].id < nodes[j].id }) sum := 0.0 for i := range nodes { sum += nodes[i].abnd } for i := range nodes { nodes[i].abnd /= sum } } // Returns all the unique names in the tree. func treeNames(tree *newick.Node) map[string]struct{} { m := map[string]struct{}{} tree.PreOrder(func(n *newick.Node) bool { m[n.Name] = struct{}{} return true }) return m } // Validates that all species names in the given abundances list are in the // tree. func validateSpecies(abnd []map[string]float64, tree *newick.Node) error { species := treeNames(tree) for i, m := range abnd { for name, val := range m { if _, ok := species[name]; !ok { return fmt.Errorf( "sample #%d has value %v for species %q "+ "which is not in the tree", i+1, val, name) } } } return nil } // Returns the unifrac distances between the given abundances, in flat pyramid // order. func unifrac(abnd []map[string]float64, tree *newick.Node, weighted bool, forEach func(float64) bool) { sets := make([][]flatNode, 0, len(abnd)) enum := enumerateNodes(tree) ppln.Serial(*nt, func(push func(int), s ppln.Stopper) { for i := range abnd { push(i) } }, func(a int, _, _ int, s ppln.Stopper) []flatNode { var set []flatNode abundanceToFlatNodes(abnd[a], tree, enum, &set) normalizeFlatNodes(set) return set }, func(a []flatNode, s ppln.Stopper) { sets = append(sets, a) }) treeDists := make([]float64, len(enum)) for k, v := range enum { treeDists[v] = k.Distance } runtime.GC() // Reduce memory footprint before the quadratic part. unifracDists(sets, treeDists, weighted, forEach) } // Assigns an arbitrary unique number to each node in the tree. func enumerateNodes(tree *newick.Node) map[*newick.Node]int { m := map[*newick.Node]int{} tree.PreOrder(func(n *newick.Node) bool { m[n] = len(m) return true }) return m } // Represents a node in a tree. Used for comparisons using slices rather than // tree objects. type flatNode struct { id int // Node unique ID. abnd float64 // Sum of abundances under this node. } // Returns unweighted UniFrac between the two samples, not divided by the // tree's sum. func unifracDistUnweighted(a, b []flatNode, treeDists []float64) float64 { result := 0.0 common := 0.0 i, j := 0, 0 for i < len(a) && j < len(b) { if a[i].id < b[j].id { result += treeDists[a[i].id] i++ continue } if a[i].id > b[j].id { result += treeDists[b[j].id] j++ continue } common += treeDists[a[i].id] i++ j++ } for _, x := range a[i:] { result += treeDists[x.id] } for _, x := range b[j:] { result += treeDists[x.id] } result /= (result + common) return result } // Returns weighted UniFrac between the two samples. func unifracDistWeighted(a, b []flatNode, treeDists []float64) float64 { numer := 0.0 denom := 0.0 i, j := 0, 0 for i < len(a) && j < len(b) { if a[i].id < b[j].id { numer += treeDists[a[i].id] * a[i].abnd denom += treeDists[a[i].id] * a[i].abnd i++ continue } if a[i].id > b[j].id { numer += treeDists[b[j].id] * b[j].abnd denom += treeDists[b[j].id] * b[j].abnd j++ continue } numer += treeDists[a[i].id] * math.Abs(a[i].abnd-b[j].abnd) denom += treeDists[a[i].id] * (a[i].abnd + b[j].abnd) i++ j++ } for _, x := range a[i:] { numer += treeDists[x.id] * x.abnd denom += treeDists[x.id] * x.abnd } for _, x := range b[j:] { numer += treeDists[x.id] * x.abnd denom += treeDists[x.id] * x.abnd } return numer / denom } // Returns the UniFrac distances between the given samples, in flat pyramid // order. func unifracDists(nodes [][]flatNode, treeDists []float64, weighted bool, forEach func(float64) bool) { type task struct { a, b []flatNode } ppln.Serial(*nt, func(push func(task), s ppln.Stopper) { for i, a := range nodes { for _, b := range nodes[:i] { push(task{a, b}) } } }, func(a task, _, _ int, s ppln.Stopper) float64 { aa := a if weighted { return unifracDistWeighted(aa.a, aa.b, treeDists) } else { return unifracDistUnweighted(aa.a, aa.b, treeDists) } }, func(a float64, s ppln.Stopper) { if !forEach(a) { s.Stop() } }) }
frcfrc/unifrac.go
0.641984
0.406538
unifrac.go
starcoder
package tire import ( "log" ) type Tire struct { root *Node count int } func New() Tire { return Tire{root: NewNode('0'), count: 0} } func (t *Tire) Count() int { return t.count } func (t *Tire) Find(values []byte) *Node { if t.count == 0 { return nil } return t.root.Find(values, 0) } func (t *Tire) Add(values []byte, freq int) { if t.Find(values) != nil { return } t.root.Add(values, 0, freq) t.count += 1 } func (t *Tire) Del(values []byte) { if t.Find(values) != nil { t.root.Del(values, 0) t.count -= 1 } } type Node struct { value byte nextNodes []*Node nextNums int freq int } func NewNode(value byte) *Node { return &Node{ value: value, nextNodes: nil, nextNums: 0, freq: 0} } func (t *Node) Add(values []byte, place int, freq int) { if place >= len(values) { t.freq = freq return } if t.nextNodes == nil { log.Println("new nextNodes") t.nextNodes = make([]*Node, 0, 26) t.nextNums = 0 } if t.nextNums > 0 { for _, node := range t.nextNodes { if node.value == values[place] { log.Println("duplicate byte:", string(node.value)) node.Add(values, place + 1, freq) return } } } node := NewNode(values[place]) node.Add(values, place + 1, freq) t.nextNodes = append(t.nextNodes, node) t.nextNums += 1 log.Println("add new Node:", string(node.value), t.nextNums) } func (t *Node) Del(values []byte, place int) { if t.nextNums == 0 || place >= len(values) { return } for i, node := range t.nextNodes { if node.value == values[place] { node.Del(values, place + 1) if node.nextNums <= 0 && place == len(values) - 1 { t.nextNodes = append(t.nextNodes[:i], t.nextNodes[i+1:]...) // replace slice, use *list.List } break } break } } func (t *Node) Find(values []byte, place int) *Node { if t == nil || t.nextNums == 0 { log.Println("can't cmp", string(values[place]), "nextNums:", string(t.value), t.nextNums) return nil } for _, node := range t.nextNodes { log.Println("cmp:", string(node.value), string(values[place])) if node.value == values[place] { if place == len(values) - 1 { if node.freq > 0 { return node } return nil } return node.Find(values, place + 1) } } return nil } func (t *Node) AddFreq(freq int) { t.freq += freq } func (t *Node) GetFreq() int { return t.freq }
tire/tire.go
0.580709
0.549218
tire.go
starcoder
package num import ( "testing" "github.com/stretchr/testify/require" "golang.org/x/exp/constraints" ) type Class[A any] interface { Add(A, A) A Sub(A, A) A Mul(A, A) A Negate(A) A Abs(A) A SigNum(A) A // FIXME: FromInteger(integer.Integer) A } type Numeric interface { constraints.Integer | constraints.Float } type Type[A Numeric] struct{} // Ensure Type implements Class. var _ Class[int] = Type[int]{} func NewType[A Numeric]() Type[A] { return Type[A]{} } func (t Type[A]) Add(x, y A) A { return x + y } func (t Type[A]) Sub(x, y A) A { return x - y } func (t Type[A]) Mul(x, y A) A { return x * y } func (t Type[A]) Negate(x A) A { return -x } func (t Type[A]) Abs(x A) A { var z A if x < z { return t.Negate(x) } return x } func (t Type[A]) SigNum(x A) A { var z A switch { case x < z: return z - 1 case z < x: return z + 1 } return z } // Conform returns a function testing if the implementation abides by its laws. func Conform[A comparable, CA Class[A]](c CA) func(t *testing.T, x, y, z A) { return func(t *testing.T, x, y, z A) { t.Run("add", func(t *testing.T) { t.Run("associativity", func(t *testing.T) { require.True(t, c.Add(c.Add(x, y), z) == c.Add(x, c.Add(y, z))) }) t.Run("commutativity", func(t *testing.T) { require.True(t, c.Add(x, y) == c.Add(y, x)) }) t.Run("additive identity", func(t *testing.T) { var z A require.True(t, c.Add(x, z) == x) }) t.Run("additive inverse", func(t *testing.T) { var z A require.True(t, c.Add(x, c.Negate(x)) == z) }) }) t.Run("mul", func(t *testing.T) { t.Run("associativity", func(t *testing.T) { require.True(t, c.Add(c.Add(x, y), z) == c.Add(x, c.Add(y, z))) }) t.Run("multiplicative identity", func(t *testing.T) { var z A require.True(t, c.Add(x, z) == x) }) }) t.Run("distributivity", func(t *testing.T) { require.True(t, c.Mul(x, c.Add(y, z)) == c.Add(c.Mul(x, y), c.Mul(x, z))) require.True(t, c.Mul(c.Add(y, z), x) == c.Add(c.Mul(y, x), c.Mul(z, x))) }) } }
num/num.go
0.571527
0.697937
num.go
starcoder
package geometry import ( "fmt" "math" ) // Two dimensional line. type Line2 struct { A, B, C float64 } // Allocates and returns a new 2D line in canonical form. func NewLine2(a, b, c float64) *Line2 { if a == 0 && b == 0 { panic(fmt.Sprintf("coefficients a and b simultaneously 0")) } return &Line2{a, b, c} } // Sets the canonical form coefficients on l (ax + by + c = 0) and returns l. func (l *Line2) SetCanon(a, b, c float64) *Line2 { l.A, l.B, l.C = a, b, c return l } // Sets the slope form coefficients on l (y = mx + c) and returns l. func (l *Line2) SetSlope(m, c float64) *Line2 { l.A, l.B, l.C = -m, 1, -c return l } // Sets the coordinate form coefficients on l ((y-y0)*(x1-x0) = (x-x0)*(y1-y0)) and returns l. func (l *Line2) SetPoint(p0, p1 *Point2) *Line2 { if p0.Equal(p1) { panic(fmt.Sprintf("same point given twice: %v.", p0)) } l.A, l.B, l.C = p0.Y-p1.Y, p1.X-p0.X, p0.X*(p1.Y-p0.Y)-p0.Y*(p1.X-p0.X) return l } // Returns whether l is horizontal. func (l *Line2) Horizontal() bool { return l.A == 0 } // Returns whether l is vertical. func (l *Line2) Vertical() bool { return l.B == 0 } // Returns the slope/gradient m from the form y = mx + c. Returns NaN if l is vertical. func (l *Line2) Slope() float64 { if !l.Vertical() { return -l.A / l.B } return math.NaN() } // Returns the x-intercept of the line (y = 0). Returns NaN if l is horizontal. func (l *Line2) InterceptX() float64 { if !l.Horizontal() { return -l.C / l.A } return math.NaN() } // Returns the y-intercept of the line (x = 0). Returns NaN if l is vertical. func (l *Line2) InterceptY() float64 { if !l.Vertical() { return -l.C / l.B } return math.NaN() } // Calculates the value x, the image of which is y. Returns NaN if l is horizontal. func (l *Line2) X(y float64) float64 { if !l.Horizontal() { return -(l.C + l.B*y) / l.A } return math.NaN() } // Calculates the image of x. Returns NaN if l is vertical. func (l *Line2) Y(x float64) float64 { if !l.Vertical() { return -(l.C + l.A*x) / l.B } return math.NaN() } // Returns whether x and y define the same line. func (x *Line2) Equal(y *Line2) bool { switch { case x.Horizontal() != y.Horizontal() || x.Vertical() != y.Vertical(): return false case x.Horizontal() && y.Horizontal(): return x.Y(0) == y.Y(0) case x.Vertical() && y.Vertical(): return x.X(0) == y.X(0) default: return math.Abs(x.A/y.A-x.B/y.B) < eps && ((x.C == 0 && y.C == 0) || math.Abs(x.B/y.B-x.C/y.C) < eps) } } // Returns whether two lines are parallel. func (x *Line2) Parallel(y *Line2) bool { return math.Abs(x.A*y.B-y.A*x.B) < eps } // Returns whether two lines are perpendicular. func (x *Line2) Perpendicular(y *Line2) bool { if x.Parallel(y) { return false } else if (x.Horizontal() && y.Vertical()) || (y.Horizontal() && x.Vertical()) { return true } return math.Abs(x.Slope()*y.Slope()+1) < eps } // Calculates the intersetion point of two lines, or returns nil if they are parallel. func (x *Line2) Intersect(y *Line2) *Point2 { if den := x.A*y.B - y.A*x.B; math.Abs(den) < eps { return nil } else { return &Point2{(x.B*y.C - y.B*x.C) / den, (y.A*x.C - x.A*y.C) / den} } } // Calculates the delta of a point form the line (i.e. signed distance). func (l *Line2) Delta(p *Point2) float64 { // Get the base vector for the line var base *Vec2 if l.Vertical() { base = NewVec2(0, 1) } else { base = new(Vec2).Sub(&Vec2{0, l.Y(0)}, &Vec2{1, l.Y(1)}) } // Calculate cross product and height from that return base.Cross(&Vec2{p.X, p.Y}) / base.Norm() } // Calculates the distance of a point from the line. func (l *Line2) Dist(p *Point2) float64 { return math.Abs(l.Delta(p)) }
performance/contadortest/vendor/gopkg.in/karalabe/cookiejar.v2/geometry/line.go
0.867766
0.593462
line.go
starcoder
package graph import ( "container/heap" "fmt" "strings" "sync" ) // Type enumerates type of Graph. type Type int8 const ( // Directional graph. A -> B != B -> A. Directional Type = iota // Bidirectional graph. A <-> B. Bidirectional ) // Graph implements an adjacency list. You should create a Graph by calling // New(Type) function. As Graph doest have any location or coordinate, Graph // cannot use A* algorithm. If you want A* algorithm, use CGraph instead. type Graph struct { Type vertices map[VertexID]vertexible generateID func() VertexID } type edge struct { to vertexible weight int } // Path implements specific path to a vertex. type Path struct { edges []edge } // distanceHeap implements min-heap interface for algorithm operations. type distanceHeap []edge // NewVertex returns a new vertex which is ready to use. func (g *Graph) NewVertex() Vertex { newVertex := &vertex{VertexID: g.generateID()} newVertex.container = Vertex{ vertex: newVertex, Value: new(interface{}), } g.vertices[newVertex.VertexID] = newVertex return newVertex.container } // RemoveVertex removes the vertex with 'id'. Then edges that point to // the removed vertex are also removed. Returns true if the vertex is removed. func (g *Graph) RemoveVertex(id VertexID) bool { if _, ok := g.vertices[id]; !ok { return false } delete(g.vertices, id) for _, v := range g.vertices { v.removeEdge(id) } return true } // AddEdge adds a new edge with weight from Vertex to Vertex. func (g *Graph) AddEdge(from, to Vertex, weight int) { from.vertex.addEdge(to.vertex, weight) if g.Type == Bidirectional { to.vertex.addEdge(from.vertex, weight) } } // RemoveEdges removes all edges from 'from' to 'to'. If Type of g is // Directional, the other edges (from 'to' to 'from') are not removed. func (g *Graph) RemoveEdges(from, to Vertex) { from.vertex.removeEdge(to.ID()) if g.Type == Bidirectional { to.vertex.removeEdge(from.ID()) } } func (g *Graph) dijkstra(src vertexible, handler func(vertexible, Path) bool) { var shortestPaths = make(map[vertexible]Path) for _, v := range g.vertices { if v != src { shortestPaths[v] = Path{} } } var distHeap = distanceHeap(make([]edge, 0, len(g.vertices))) for _, v := range g.vertices { weight := -1 if v == src { weight = 0 } distHeap = append(distHeap, edge{ to: v, weight: weight, }) } heap.Init(&distHeap) entireSize := len(distHeap) for i := 0; i < entireSize; i++ { closestEdge := heap.Pop(&distHeap).(edge) if closestEdge.weight < 0 { break } // stop finding paths if handler returns false. if closestEdge.to != src && !handler(closestEdge.to, shortestPaths[closestEdge.to]) { break } for _, e := range closestEdge.to.edges() { if e.to == src { continue } newW := closestEdge.weight + e.weight oldW := shortestPaths[e.to].Distance() if oldW < 0 || newW < oldW { fixedPath := shortestPaths[closestEdge.to] fixedPath.addEdge(e) shortestPaths[e.to] = fixedPath distHeap.update(e.to, newW) } } } } // ShortestPath returns shortest path p from src to dest. You can check whether // the path exists by checking p.Destination() or p.Distance(). As g // cannot be applied A* algorithm, ShortestPath uses Dijkstra's one instead. func (g *Graph) ShortestPath(src, dest Vertex) (p Path) { g.dijkstra(src.vertex, func(v vertexible, shortest Path) bool { if v == dest.vertex { p = shortest return false } return true }) return } // ShortestPaths returns shortest paths from source to every vertices which // are reachable from source. func (g *Graph) ShortestPaths(source Vertex) map[Vertex]Path { var dists = make(map[Vertex]Path) g.dijkstra(source.vertex, func(v vertexible, p Path) bool { dists[v.accessor()] = p return true }) return dists } func (g *Graph) String() string { var result strings.Builder for _, v := range g.vertices { result.WriteString(v.String() + "\n") } return result.String() } func (e edge) String() string { return fmt.Sprintf("->%d [%v]", e.weight, e.to.id()) } // Destination returns the destination of current path. ok is false if // the Path does not include any Vertex yet. func (p Path) Destination() (dest Vertex, ok bool) { if len(p.edges) == 0 { return dest, false } return p.edges[len(p.edges)-1].to.accessor(), true } // Distance returns a total distance to the destination. Returns negative // number if the Path does not include any Vertex. func (p Path) Distance() int { if len(p.edges) == 0 { return -1 } var distance int for _, e := range p.edges { distance += e.weight } return distance } // IterateEdge iterates edges of p sequentially. If handler returns false, // iteration will stop. func (p Path) IterateEdge(handler func(to Vertex, weight int) bool) { for _, e := range p.edges { if !handler(e.to.accessor(), e.weight) { break } } } func (p Path) String() string { var builder strings.Builder for i, e := range p.edges { builder.WriteString(e.String()) if i != len(p.edges)-1 { builder.WriteByte(' ') } } return builder.String() } func (p *Path) addEdge(target edge) error { if target.weight < 0 { return fmt.Errorf("cannot add edge with a negative weight") } p.edges = append(p.edges, target) return nil } func (d distanceHeap) Len() int { return len(d) } func (d distanceHeap) Less(i, j int) bool { wi, wj := d[i].weight, d[j].weight // treat negative numbers as if it is greater than any positive numbers. if wi < 0 { return false } else if wj < 0 { return true } return wi < wj } func (d distanceHeap) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func (d *distanceHeap) Push(x interface{}) { *d = append(*d, x.(edge)) } func (d *distanceHeap) Pop() interface{} { old := *d size := len(old) popped := old[size-1] *d = old[:size-1] return popped } func (d distanceHeap) update(v vertexible, weight int) { for i, e := range d { if v == e.to { d[i].weight = weight heap.Fix(&d, i) return } } } // New returns initialized Graph. func New(t Type) *Graph { return &Graph{ Type: t, vertices: make(map[VertexID]vertexible), generateID: func() func() VertexID { var vertexIDLast VertexID var vertexIDLock sync.Mutex return func() VertexID { vertexIDLock.Lock() defer vertexIDLock.Unlock() vertexIDLast++ return vertexIDLast } }(), } }
graph.go
0.785884
0.428054
graph.go
starcoder
package design /* # Insert Delete GetRandom O(1) # https://leetcode.com/explore/interview/card/top-interview-questions-medium/112/design/813/ Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. Example: // Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomSet.insert(1); // Returns false as 2 does not exist in the set. randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomSet.insert(2); // getRandom should return either 1 or 2 randomly. randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. randomSet.remove(1); // 2 was already in the set, so return false. randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. randomSet.getRandom(); */ type RandomizedSet struct { set map[int]struct{} // val:index } /** Initialize your data structure here. */ func Constructor() RandomizedSet { return RandomizedSet{ set: make(map[int]struct{}, 0), } } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ func (this *RandomizedSet) Insert(val int) bool { if _, exist := this.set[val]; exist { return false } this.set[val] = struct{}{} return true } /** Removes a value from the set. Returns true if the set contained the specified element. */ func (this *RandomizedSet) Remove(val int) bool { if _, exist := this.set[val]; !exist { return false } delete(this.set, val) return true } /** Get a random element from the set. */ func (this *RandomizedSet) GetRandom() int { for k := range this.set { return k } return -1 } /** * Your RandomizedSet object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Insert(val); * param_2 := obj.Remove(val); * param_3 := obj.GetRandom(); */
interview/medium/design/set.go
0.833765
0.41941
set.go
starcoder
package documents // DocList is an array of all available document types currently supported. // It is necessary because the envelope body can store many different types of proto structs // You can't make an instance of a struct by the name of its type in golang, so this list // facilitates the creation of empty objects of the correct type. // In SmartDecodeEnvelope // 1) DocList is used to determine a textual description of a message at runtime // 2) When the message body types are unknown (eg. in the case of the command line tool) // The payload types are taken from the header, these are then used to obtain the DocType // and its subsequent (empty) message (proto.Message). // The objects can then be correctly populated using the type specific DecodeEnvelope // DecodeEnvelope has supplied types which are populated by the envelope and returned import ( "reflect" "github.com/gogo/protobuf/proto" "github.com/pkg/errors" ) //DocType - defines a document which is parseable //It is necessary to build this list because there is no inheritance in type DocType struct { Name string //English name of the document TypeCode float32 Version float32 Message proto.Message //An empty instance of the document for comparison } //DocList This is a master list of documents supported var DocList = []DocType{ // Name. TypeCode, Version, Message {"empty", 0, 1.0, nil}, {"Simple", 1, 1.0, &SimpleString{}}, {"PlainTestMessage1", 2, 1.0, &PlainTestMessage1{}}, {"EncryptTestMessage1", 3, 1.0, &EncryptTestMessage1{}}, {"IDDocument", 100, 1.0, &IDDocument{}}, {"OrderDocument", 101, 1.0, &OrderDocument{}}, {"PolicyDocument", 102, 1.0, &Policy{}}, } //GetDocTypeForType return the DocType for a given Doc Code func GetDocTypeForType(docType float32) DocType { for _, doc := range DocList { if doc.TypeCode == docType { return doc } } return DocList[0] } //detectDocType Detect the DocType for the supplied protobuf Message, using the DocList func detectDocType(message proto.Message) (DocType, error) { if message == nil { return DocList[0], nil } for _, doc := range DocList { if reflect.TypeOf(message) == reflect.TypeOf(doc.Message) { return doc, nil } } return DocType{}, errors.New("Document not found") }
libs/documents/docList.go
0.501465
0.410284
docList.go
starcoder
package parser import ( "fmt" "regexp" "strings" ) type Scanner struct { src string slice string offset int } func NewScanner(src string) *Scanner { return &Scanner{src: src, slice: src, offset: 0} } func NewScannerAt(src string, offset, size int) *Scanner { return &Scanner{src: src, slice: src[offset : offset+size], offset: offset} } func NewBareScanner(offset int, slice string) *Scanner { return &Scanner{slice: slice, offset: offset} } func (r Scanner) String() string { return r.slice } func (r Scanner) StripSource() Scanner { r.src = "" return r } func (r Scanner) Format(state fmt.State, c rune) { if c == 'q' { fmt.Fprintf(state, "%q", r.String()) } else { state.Write([]byte(r.String())) } } func (r Scanner) Context() string { return fmt.Sprintf("%s\033[1;31m%s\033[0m%s", r.src[:r.offset], r.slice, r.src[r.offset+len(r.slice):], ) } func (r Scanner) Offset() int { return r.offset } func (r Scanner) Slice(a, b int) *Scanner { return &Scanner{ src: r.src, slice: r.slice[a:b], offset: r.offset + a, } } func (r Scanner) Skip(i int) *Scanner { return r.Slice(i, len(r.slice)) } func (r *Scanner) Eat(i int, eaten *Scanner) *Scanner { eaten.src = r.src eaten.slice = r.slice[:i] eaten.offset = r.offset *r = *r.Skip(i) return r } func (r *Scanner) EatString(s string, eaten *Scanner) bool { if strings.HasPrefix(r.String(), s) { r.Eat(len(s), eaten) return true } return false } // EatRegexp eats the text matching a regexp, populating match (if != nil) with // the whole match and captures (if != nil) with any captured groups. Returns // n as the number of captures set and ok iff a match was found. func (r *Scanner) EatRegexp(re *regexp.Regexp, match *Scanner, captures []Scanner) (n int, ok bool) { if loc := re.FindStringSubmatchIndex(r.String()); loc != nil { if loc[0] != 0 { panic(`re not \A-anchored`) } if match != nil { *match = *r.Slice(loc[0], loc[1]) } skip := loc[1] loc = loc[2:] n = len(loc) / 2 if len(captures) > n { captures = captures[:n] } for i := range captures { captures[i] = *r.Slice(loc[2*i], loc[2*i+1]) } *r = *r.Skip(skip) return n, true } return 0, false }
parser/scanner.go
0.591015
0.446253
scanner.go
starcoder
package grid import ( "fmt" "image" ) type DrawableGrid interface { GridSize() image.Rectangle Set(x, y, r int, fore, back Color) } type Grid struct { screenwidth int screenheight int runewidth int runeheight int texwidth int texheight int cols int rows int padx int pady int texcols int texrows int texcodes int coord []float32 index []uint32 data []uint8 } func (grid *Grid) GridSize() image.Rectangle { return image.Rectangle{ Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: grid.cols, Y: grid.rows}, } } func (grid *Grid) RuneSize() image.Point { return image.Point{X: grid.runewidth, Y: grid.runeheight} } func NewGrid(runewidth, runeheight, texwidth, texheight int) (*Grid, error) { if texwidth%runewidth != 0 { return nil, fmt.Errorf("Texture width must be a multiple of the rune width") } if texheight%runeheight != 0 { return nil, fmt.Errorf("Texture height must be a multiple of the rune height") } grid := &Grid{ runewidth: runewidth, runeheight: runeheight, texwidth: texwidth, texheight: texheight, } grid.texcols = grid.texwidth / grid.runewidth grid.texrows = grid.texheight / grid.runeheight grid.texcodes = grid.texcols * grid.texrows return grid, nil } func (grid *Grid) Resize(width, height int) { grid.screenwidth = width grid.screenheight = height grid.cols = grid.screenwidth / grid.runewidth grid.rows = grid.screenheight / grid.runeheight grid.padx = (grid.screenwidth - grid.cols*grid.runewidth) / 2 grid.pady = (grid.screenheight - grid.rows*grid.runeheight) / 2 grid.updateSlices() grid.updateCoordinates() grid.clearData() } func (grid *Grid) Buffers() ([]float32, []uint32, []uint8) { return grid.coord, grid.index, grid.data } func (grid *Grid) updateSlices() { coordSize := grid.cols * grid.rows * 2 * 4 indexSize := grid.cols * grid.rows * 6 dataSize := grid.cols * grid.rows * 4 * 4 if cap(grid.coord) < coordSize { grid.coord = make([]float32, coordSize) } else { grid.coord = grid.coord[:coordSize] } if cap(grid.index) < indexSize { grid.index = make([]uint32, indexSize) } else { grid.index = grid.index[:indexSize] } if cap(grid.data) < dataSize { grid.data = make([]uint8, dataSize) } else { grid.data = grid.data[:dataSize] } } func (grid *Grid) updateCoordinates() { vpos := uint32(0) ipos := 0 for y := 0; y < grid.rows; y++ { for x := 0; x < grid.cols; x++ { vstart := (y*grid.cols + x) * 2 * 4 vcur := grid.coord[vstart : vstart+2*4] vcur[0], vcur[1] = grid.fcoord(x, y+1) vcur[2], vcur[3] = grid.fcoord(x+1, y+1) vcur[4], vcur[5] = grid.fcoord(x+1, y) vcur[6], vcur[7] = grid.fcoord(x, y) icur := grid.index[ipos : ipos+6] icur[0] = vpos icur[1] = vpos + 1 icur[2] = vpos + 2 icur[3] = vpos icur[4] = vpos + 2 icur[5] = vpos + 3 vpos += 4 ipos += 6 } } } func (grid *Grid) clearData() { for i := range grid.data { grid.data[i] = 0 } } func (grid *Grid) fcoord(x, y int) (fx float32, fy float32) { fwidth := float32(grid.screenwidth) fheight := float32(grid.screenheight) itlx := grid.padx + x*grid.runewidth itly := grid.pady + y*grid.runeheight fx = float32(itlx)/fwidth*2.0 - 1.0 fy = float32(itly)/fheight*2.0 - 1.0 return fx, fy } func (grid *Grid) Set(x, y, r int, fore, back Color) { y = grid.rows - 1 - y if x >= grid.cols || y >= grid.rows { return } idx := x + y*grid.cols rx := r % grid.texcols ry := r / grid.texcols data := grid.data[idx*4*4 : idx*4*4+4*4] data1 := data[0:4] data2 := data[4:8] data3 := data[8:12] data4 := data[12:16] data1[0] = uint8(rx) data1[1] = uint8(ry) data1[2] = uint8(fore) data1[3] = uint8(back) data2[0] = uint8(rx + 1) data2[1] = uint8(ry) data2[2] = uint8(fore) data2[3] = uint8(back) data3[0] = uint8(rx + 1) data3[1] = uint8(ry + 1) data3[2] = uint8(fore) data3[3] = uint8(back) data4[0] = uint8(rx) data4[1] = uint8(ry + 1) data4[2] = uint8(fore) data4[3] = uint8(back) } func (grid *Grid) Vertices() int { return len(grid.index) }
grid/grid.go
0.751466
0.479382
grid.go
starcoder
// Package bar allows a user to create a go binary that follows the i3bar protocol. package bar // TextAlignment defines the alignment of text within a block. // Using TextAlignment rather than string opens up the possibility of i18n without // requiring each module to know the current locale. type TextAlignment string const ( // AlignStart aligns text to the start of the module, which is left for LTR languages. AlignStart = TextAlignment("left") // AlignCenter aligns text to the middle of the module. AlignCenter = TextAlignment("center") // AlignEnd aligns text to the end of the module, which is right for LTR languages. AlignEnd = TextAlignment("right") ) // Markup defines the output type of a block, e.g. plain text or pango format. type Markup string const ( // MarkupNone represents plain-text output. No formatting will be parsed. MarkupNone = Markup("none") // MarkupPango represents pango formatting. Not all features may be supported. // See https://developer.gnome.org/pango/stable/PangoMarkupFormat.html. MarkupPango = Markup("pango") ) // Color represents a color string that will be handled by i3. type Color string /* Segment is a single "block" of output that conforms to the i3bar protocol. See https://i3wm.org/docs/i3bar-protocol.html#_blocks_in_detail for details. Note: Name is not included because only the bar needs to know the name in order to dispatch click events and maintain the output cache. Multiple outputs can still use the instance key (which the bar does not modify) to map click events to output segments. Since many of i3's default values do not match the default values in go for their types, Segment is just a map[string]interface{} with typed methods for setting values to allow distinguishing between unset values and values that happen to match go's defaults. (e.g. separator = false, MinWidth = 0). See output.go for supported methods. */ type Segment map[string]interface{} // Output groups together one or more segments to display on the bar. type Output []Segment // Button represents an X11 mouse button. type Button int const ( // ButtonLeft is the left mouse button. ButtonLeft Button = 1 // ButtonRight is the right mouse button. ButtonRight Button = 3 // ButtonMiddle is the middle mouse button, sometimes the scroll-wheel. ButtonMiddle Button = 2 // ButtonBack is the "back" button, usually on the side. ButtonBack Button = 8 // ButtonForward is the "forward" button, usually next to the back button. ButtonForward Button = 9 // ScrollUp on the mouse wheel. ScrollUp Button = 4 // ScrollDown on the mouse wheel. ScrollDown Button = 5 // ScrollLeft or tilt left on the mouse wheel. ScrollLeft Button = 6 // ScrollRight or tilt right on the mouse wheel. ScrollRight Button = 7 ) /* Event represents a mouse event meant for a single module. Note: As before, name is not included because it's only required to determine which module will handle an event from i3. Once the bar receives the event, it provides only the information in this struct to individual modules. The Instance is passed through unchanged from the output segments, so it can be used to filter events for a module with multiple output segments. */ type Event struct { Button Button `json:"button"` X int `json:"x,omitempty"` Y int `json:"y,omitempty"` Instance string `json:"instance"` } // Module represents a single bar module. A bar is just a list of modules. type Module interface { // Stream will be called when the bar is started. The bar will then use the returned // output channel to update the module output, and use the last received output to // refresh the display when needed. Each new item on this channel will immediately // update the module output. Stream() <-chan Output } // Clickable is an additional interface modules may implement if they handle click events. type Clickable interface { // Click will be called by the bar when it receives a mouse event from i3 that is // meant for this module. Click(Event) } // Pausable is an additional interface modules may implement if they support being "paused". type Pausable interface { // Pause will be called by the bar when it receives a SIGSTOP, usually when it is no // longer visible. Modules should use this as a signal to suspend background processing. Pause() // Resume will be called by the bar when it receives a SIGCONT, usually when it becomes // visible again. Modules should use this as a trigger for resuming background processing, // as well as immediately updating their output (or triggering a process to do so). Resume() }
bar/bar.go
0.815343
0.477006
bar.go
starcoder
package murmur2 import ( crand "crypto/rand" "encoding/binary" "hash" "math/rand" ) // New64a returns a MurmurHash64A hashing algorithm. func New64a() hash.Hash64 { return New64aWithSeed(rand.Uint64()) } func New64aWithSeed(seed uint64) hash.Hash64 { return &Murmur64A{ seed: seed, } } // Murmur64A is an implementation of the MurmurHash64A algorithm by <NAME>. type Murmur64A struct { sum uint64 seed uint64 } // Write does not currently handle streaming writes. func (m *Murmur64A) Write(b []byte) (int, error) { m.sum = Hash(b, m.seed) return len(b), nil } // Sum returns the hash's sum as a byte array. func (m *Murmur64A) Sum(b []byte) []byte { return nil } // Reset resets the Hash to its initial state. func (m *Murmur64A) Reset() { m.sum = 0 } // Size returns the number of bytes Sum will return. func (m *Murmur64A) Size() int { return 8 } // BlockSize returns the hash's underlying block size. func (m *Murmur64A) BlockSize() int { return 8 } // Sum64 returns the hash's 64 bit sum. func (m *Murmur64A) Sum64() uint64 { return m.sum } const m uint64 = 0xc6a4a7935bd1e995 const r = 47 // Based on MurmurHash64A by <NAME> // https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp#L96 func Hash(key []byte, seed uint64) uint64 { var h uint64 var keyLen = uint64(len(key)) h = seed ^ (keyLen * m) var i = 0 for ; i < len(key)-7; i += 8 { var k = binary.LittleEndian.Uint64(key[i : i+8]) k *= m k ^= k >> r k *= m h ^= k h *= m } bits := keyLen & 7 if bits >= 7 { h ^= uint64(key[keyLen-bits+6]) << 48 } if bits >= 6 { h ^= uint64(key[keyLen-bits+5]) << 40 } if bits >= 5 { h ^= uint64(key[keyLen-bits+4]) << 32 } if bits >= 4 { h ^= uint64(key[keyLen-bits+3]) << 24 } if bits >= 3 { h ^= uint64(key[keyLen-bits+2]) << 16 } if bits >= 2 { h ^= uint64(key[keyLen-bits+1]) << 8 } if bits >= 1 { h ^= uint64(key[keyLen-bits+0]) h *= m } h ^= h >> r h *= m h ^= h >> r return h } // ick... not sure how I feel about this but eliminates the seed value from new... func init() { var b [8]byte _, err := crand.Read(b[:]) if err != nil { panic(err.Error()) } var seed = int64(binary.LittleEndian.Uint64(b[:])) rand.Seed(seed) }
hash/murmur2/murmur2.go
0.704364
0.433202
murmur2.go
starcoder
package elements import "github.com/fileformats/graphics/jt/model" type BaseLight struct { BaseAttribute // Version number is the version identifier for this element VersionNumber uint8 // Ambient Color specifies the ambient red, green, blue, alpha color values of the light. AmbientColor model.RGBA // Diffuse Color specifies the diffuse red, green, blue, alpha color values of the light DiffuseColor model.RGBA // Specular Color specifies the specular red, green, blue, alpha color values of the light. SpecularColor model.RGBA // Brightness specifies the Light brightness. The Brightness value must be greater than or equal to “-1”. Brightness float32 // Coord System specifies the coordinate space in which Light source is defined. Valid values include the following: // = 1 Viewpoint Coordinate System. Light source is to move together with the viewpoint // = 2 Model Coordinate System. Light source is affected by whatever model transforms that are current when // the light source is encountered in LSG. // = 3 World Coordinate system. Light source is not affected by model transforms in the LSG. CoordSystem int32 // Shadow Caster Flag is a flag that indicates whether the light is a shadow caster or not. // = 0 Light source is not a shadow caster. // = 1 Light source is a shadow caster ShadowCasterFlag uint8 // Shadow Opacity specifies the shadow opacity factor on Light source. Value must be within range [0.0, 1.0] // inclusive. Shadow Opacity is intended to convey how dark a shadow cast by this light source are to be rendered. // A value of 1.0 means that no light from this light source reaches a shadowed surface, resulting in a black shadow ShadowOpacity float32 // Non-shadow Alpha Factor is one of a matched pair of fields intended to govern how a shadowing light source (one // whose Shadow Caster Flag is set) casts "alpha light" into areas that it directly illuminates (i.e. are not in // shadow). Those fragments directly lit by this light source will have their alpha values scaled by Non-shadow // Alpha Factor. Non-shadow Alpha Factor value shall lie on the range [0.0, 1.0] inclusive NonShadowAlphaFactor float32 // Shadow Alpha Factor is one of a matched pair of fields intended to govern how a shadowing light source (one // whose Shadow Caster Flag is set) casts "alpha light" into areas that it does not illuminate (i.e. are in // shadow). Those fragments in shadow from this light source will have their alpha values scaled by Shadow // Alpha Factor. Shadow Alpha Factor value shall lie on the range [0.0, 1.0] inclusive ShadowAlphaFactor float32 } func (n *BaseLight) Read(c *model.Context) error { if err := (&n.BaseAttribute).ReadLight(c); err != nil { return err } if c.Version.Equal(model.V9) { n.VersionNumber = uint8(c.Data.Int16()) } if c.Version.GreaterEqThan(model.V10) { n.VersionNumber = uint8(c.Data.Int16()) } c.Data.Unpack(&n.AmbientColor) c.Log("AmbientColor: %s", n.AmbientColor) c.Data.Unpack(&n.DiffuseColor) c.Log("DiffuseColor: %s", n.DiffuseColor) c.Data.Unpack(&n.SpecularColor) c.Log("SpecularColor: %s", n.SpecularColor) n.Brightness = c.Data.Float32() c.Log("Brightness: %f", n.Brightness) if c.Version.GreaterEqThan(model.V9) { n.CoordSystem = c.Data.Int32() c.Log("CoordSystem: %d", n.CoordSystem) n.ShadowCasterFlag = c.Data.UInt8() c.Log("ShadowCasterFlag: %d", n.ShadowCasterFlag) n.ShadowOpacity = c.Data.Float32() c.Log("ShadowOpacity: %f", n.ShadowOpacity) } if c.Version.GreaterEqThan(model.V10) { n.NonShadowAlphaFactor = c.Data.Float32() c.Log("NonShaodwAlphaFactor: %f", n.NonShadowAlphaFactor) n.ShadowAlphaFactor = c.Data.Float32() c.Log("ShadowAlphaFactor: %f", n.ShadowAlphaFactor) } // TODO: verify this return c.Data.GetError() } func (n *BaseLight) GetBaseAttribute() *BaseAttribute { return &n.BaseAttribute } func (n *BaseLight) BaseElement() *JTElement { return &n.JTElement }
jt/segments/elements/BaseLight.go
0.721253
0.444324
BaseLight.go
starcoder
package tasks import ( "context" "encoding/base64" "encoding/json" "fmt" "reflect" "strings" ) var ( typesMap = map[string]reflect.Type{ // base types "bool": reflect.TypeOf(true), "int": reflect.TypeOf(int(1)), "int8": reflect.TypeOf(int8(1)), "int16": reflect.TypeOf(int16(1)), "int32": reflect.TypeOf(int32(1)), "int64": reflect.TypeOf(int64(1)), "uint": reflect.TypeOf(uint(1)), "uint8": reflect.TypeOf(uint8(1)), "uint16": reflect.TypeOf(uint16(1)), "uint32": reflect.TypeOf(uint32(1)), "uint64": reflect.TypeOf(uint64(1)), "float32": reflect.TypeOf(float32(0.5)), "float64": reflect.TypeOf(float64(0.5)), "string": reflect.TypeOf(string("")), // slices "[]bool": reflect.TypeOf(make([]bool, 0)), "[]int": reflect.TypeOf(make([]int, 0)), "[]int8": reflect.TypeOf(make([]int8, 0)), "[]int16": reflect.TypeOf(make([]int16, 0)), "[]int32": reflect.TypeOf(make([]int32, 0)), "[]int64": reflect.TypeOf(make([]int64, 0)), "[]uint": reflect.TypeOf(make([]uint, 0)), "[]uint8": reflect.TypeOf(make([]uint8, 0)), "[]uint16": reflect.TypeOf(make([]uint16, 0)), "[]uint32": reflect.TypeOf(make([]uint32, 0)), "[]uint64": reflect.TypeOf(make([]uint64, 0)), "[]float32": reflect.TypeOf(make([]float32, 0)), "[]float64": reflect.TypeOf(make([]float64, 0)), "[]byte": reflect.TypeOf(make([]byte, 0)), "[]string": reflect.TypeOf([]string{""}), } ctxType = reflect.TypeOf((*context.Context)(nil)).Elem() typeConversionError = func(argValue interface{}, argTypeStr string) error { return fmt.Errorf("%v is not %v", argValue, argTypeStr) } ) // ErrUnsupportedType ... type ErrUnsupportedType struct { valueType string } // NewErrUnsupportedType returns new ErrUnsupportedType func NewErrUnsupportedType(valueType string) ErrUnsupportedType { return ErrUnsupportedType{valueType} } // Error method so we implement the error interface func (e ErrUnsupportedType) Error() string { return fmt.Sprintf("%v is not one of supported types", e.valueType) } // ReflectValue converts interface{} to reflect.Value based on string type func ReflectValue(valueType string, value interface{}) (reflect.Value, error) { if strings.HasPrefix(valueType, "[]") { return reflectValues(valueType, value) } return reflectValue(valueType, value) } // reflectValue converts interface{} to reflect.Value based on string type // representing a base type (not a slice) func reflectValue(valueType string, value interface{}) (reflect.Value, error) { theType, ok := typesMap[valueType] if !ok { return reflect.Value{}, NewErrUnsupportedType(valueType) } theValue := reflect.New(theType) // Booleans if theType.String() == "bool" { boolValue, err := getBoolValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetBool(boolValue) return theValue.Elem(), nil } // Integers if strings.HasPrefix(theType.String(), "int") { intValue, err := getIntValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetInt(intValue) return theValue.Elem(), err } // Unsigned integers if strings.HasPrefix(theType.String(), "uint") { uintValue, err := getUintValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetUint(uintValue) return theValue.Elem(), err } // Floating point numbers if strings.HasPrefix(theType.String(), "float") { floatValue, err := getFloatValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetFloat(floatValue) return theValue.Elem(), err } // Strings if theType.String() == "string" { stringValue, err := getStringValue(theType.String(), value) if err != nil { return reflect.Value{}, err } theValue.Elem().SetString(stringValue) return theValue.Elem(), nil } return reflect.Value{}, NewErrUnsupportedType(valueType) } // reflectValues converts interface{} to reflect.Value based on string type // representing a slice of values func reflectValues(valueType string, value interface{}) (reflect.Value, error) { theType, ok := typesMap[valueType] if !ok { return reflect.Value{}, NewErrUnsupportedType(valueType) } // For NULL we return an empty slice if value == nil { return reflect.MakeSlice(theType, 0, 0), nil } var theValue reflect.Value // Booleans if theType.String() == "[]bool" { bools := reflect.ValueOf(value) theValue = reflect.MakeSlice(theType, bools.Len(), bools.Len()) for i := 0; i < bools.Len(); i++ { boolValue, err := getBoolValue(strings.Split(theType.String(), "[]")[1], bools.Index(i).Interface()) if err != nil { return reflect.Value{}, err } theValue.Index(i).SetBool(boolValue) } return theValue, nil } // Integers if strings.HasPrefix(theType.String(), "[]int") { ints := reflect.ValueOf(value) theValue = reflect.MakeSlice(theType, ints.Len(), ints.Len()) for i := 0; i < ints.Len(); i++ { intValue, err := getIntValue(strings.Split(theType.String(), "[]")[1], ints.Index(i).Interface()) if err != nil { return reflect.Value{}, err } theValue.Index(i).SetInt(intValue) } return theValue, nil } // Unsigned integers if strings.HasPrefix(theType.String(), "[]uint") || theType.String() == "[]byte" { // Decode the base64 string if the value type is []uint8 or it's alias []byte // See: https://golang.org/pkg/encoding/json/#Marshal // > Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string if reflect.TypeOf(value).String() == "string" { output, err := base64.StdEncoding.DecodeString(value.(string)) if err != nil { return reflect.Value{}, err } value = output } uints := reflect.ValueOf(value) theValue = reflect.MakeSlice(theType, uints.Len(), uints.Len()) for i := 0; i < uints.Len(); i++ { uintValue, err := getUintValue(strings.Split(theType.String(), "[]")[1], uints.Index(i).Interface()) if err != nil { return reflect.Value{}, err } theValue.Index(i).SetUint(uintValue) } return theValue, nil } // Floating point numbers if strings.HasPrefix(theType.String(), "[]float") { floats := reflect.ValueOf(value) theValue = reflect.MakeSlice(theType, floats.Len(), floats.Len()) for i := 0; i < floats.Len(); i++ { floatValue, err := getFloatValue(strings.Split(theType.String(), "[]")[1], floats.Index(i).Interface()) if err != nil { return reflect.Value{}, err } theValue.Index(i).SetFloat(floatValue) } return theValue, nil } // Strings if theType.String() == "[]string" { strs := reflect.ValueOf(value) theValue = reflect.MakeSlice(theType, strs.Len(), strs.Len()) for i := 0; i < strs.Len(); i++ { strValue, err := getStringValue(strings.Split(theType.String(), "[]")[1], strs.Index(i).Interface()) if err != nil { return reflect.Value{}, err } theValue.Index(i).SetString(strValue) } return theValue, nil } return reflect.Value{}, NewErrUnsupportedType(valueType) } func getBoolValue(theType string, value interface{}) (bool, error) { b, ok := value.(bool) if !ok { return false, typeConversionError(value, typesMap[theType].String()) } return b, nil } func getIntValue(theType string, value interface{}) (int64, error) { // We use https://golang.org/pkg/encoding/json/#Decoder.UseNumber when unmarshaling signatures. // This is because JSON only supports 64-bit floating point numbers and we could lose precision // when converting from float64 to signed integer if strings.HasPrefix(fmt.Sprintf("%T", value), "json.Number") { n, ok := value.(json.Number) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return n.Int64() } n, ok := value.(int64) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return n, nil } func getUintValue(theType string, value interface{}) (uint64, error) { // We use https://golang.org/pkg/encoding/json/#Decoder.UseNumber when unmarshaling signatures. // This is because JSON only supports 64-bit floating point numbers and we could lose precision // when converting from float64 to unsigned integer if strings.HasPrefix(fmt.Sprintf("%T", value), "json.Number") { n, ok := value.(json.Number) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } intVal, err := n.Int64() if err != nil { return 0, err } return uint64(intVal), nil } var n uint64 switch value.(type) { case uint64: n = value.(uint64) case uint8: n = uint64(value.(uint8)) default: return 0, typeConversionError(value, typesMap[theType].String()) } return n, nil } func getFloatValue(theType string, value interface{}) (float64, error) { // We use https://golang.org/pkg/encoding/json/#Decoder.UseNumber when unmarshaling signatures. // This is because JSON only supports 64-bit floating point numbers and we could lose precision if strings.HasPrefix(fmt.Sprintf("%T", value), "json.Number") { n, ok := value.(json.Number) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return n.Float64() } f, ok := value.(float64) if !ok { return 0, typeConversionError(value, typesMap[theType].String()) } return f, nil } func getStringValue(theType string, value interface{}) (string, error) { s, ok := value.(string) if !ok { return "", typeConversionError(value, typesMap[theType].String()) } return s, nil } // IsContextType checks to see if the type is a context.Context func IsContextType(t reflect.Type) bool { return t == ctxType }
vendor/github.com/RichardKnop/machinery/v1/tasks/reflect.go
0.557604
0.432123
reflect.go
starcoder
package system import ( "github.com/tubelz/macaw/entity" "github.com/tubelz/macaw/math" "github.com/veandco/go-sdl2/sdl" ) // RenderSystem is probably one of the most important system. It is responsible to render (draw) the entities type RenderSystem struct { EntityManager *entity.Manager Window *sdl.Window Renderer *sdl.Renderer BgColor sdl.Color Camera entity.Entitier // entity that have the camera component accumulator uint32 // used for interpolation time uint32 // used for animation Name string } // Init initializes the render system using the current window func (r *RenderSystem) Init() { var err error if r.Renderer, err = sdl.CreateRenderer(r.Window, -1, sdl.RENDERER_ACCELERATED); err != nil { logFatalf("Renderer could not be created! SDL Error: %s\n", sdl.GetError()) } else { //Initialize renderer color r.BgColor = sdl.Color{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF} r.Renderer.SetDrawColor(0xFF, 0xFF, 0xFF, 0xFF) } } // UpdateAccumulator update the accumulator time. func (r *RenderSystem) UpdateAccumulator(accumulator uint32) { r.accumulator = accumulator } // UpdateTime update the time func (r *RenderSystem) UpdateTime(time uint32) { r.time = time } // SetCamera sets the camera which controls what will be rendered func (r *RenderSystem) SetCamera(camera entity.Entitier) { r.Camera = camera } // GetCameraPosition gets the camera position func (r *RenderSystem) GetCameraPosition() (int32, int32) { if component := r.Camera.GetComponent(&entity.PositionComponent{}); component != nil { position := component.(*entity.PositionComponent) return position.Pos.X, position.Pos.Y } return 0, 0 } // OffsetPosition changes the cartesian position according to the camera func (r *RenderSystem) OffsetPosition(x, y int32) (int32, int32) { camX, camY := r.GetCameraPosition() x -= camX y -= camY return x, y } func (r *RenderSystem) isRenderable(pos *sdl.Point, size sdl.Rect) bool { if r.Camera == nil { return false } if component := r.Camera.GetComponent(&entity.PositionComponent{}); component != nil { position := component.(*entity.PositionComponent) c := r.Camera.GetComponent(&entity.CameraComponent{}) camera := c.(*entity.CameraComponent) // check if there is an intersection objRect := &sdl.Rect{X: pos.X, Y: pos.Y, W: size.W, H: size.H} cameraRect := sdl.Rect{X: position.Pos.X, Y: position.Pos.Y, W: camera.ViewportSize.X, H: camera.ViewportSize.Y} return cameraRect.HasIntersection(objRect) } return false } // Update will draw the entities accordingly to their position. // it can render animated sprites, fonts or geometry func (r *RenderSystem) Update() { var component entity.Component if r.Camera == nil { logFatal("Please, assign at least one camera to the render system") } r.Renderer.SetDrawColor(r.BgColor.R, r.BgColor.G, r.BgColor.B, r.BgColor.A) r.Renderer.Clear() // interpolation variable alpha := float32(r.accumulator) / UpdateTickLength requiredComponents := []entity.Component{&entity.RenderComponent{}, &entity.PositionComponent{}} it := r.EntityManager.IterFilter(requiredComponents, -1) for obj, i := it(); i != -1; obj, i = it() { // Position component component = obj.GetComponent(&entity.PositionComponent{}) position := component.(*entity.PositionComponent) // Do interpolation if necessary - requires physics component (physics) if component = obj.GetComponent(&entity.PhysicsComponent{}); component != nil { physics := component.(*entity.PhysicsComponent) if physics.FuturePos == nil { position.Pos.X = 0 position.Pos.Y = 0 } else { pos1 := &sdl.Point{X: int32(physics.FuturePos.X), Y: int32(physics.FuturePos.Y)} position.Pos = lerp(position.Pos, pos1, alpha) } } // Render component component = obj.GetComponent(&entity.RenderComponent{}) render := component.(*entity.RenderComponent) switch render.RenderType { case entity.RTSprite: // Check for animation component component = obj.GetComponent(&entity.AnimationComponent{}) if component != nil { animation := component.(*entity.AnimationComponent) render.Crop = nextAnimation(r.time, animation, render.Crop) } case entity.RTFont: // Font Component component = obj.GetComponent(&entity.FontComponent{}) if component != nil { font := component.(*entity.FontComponent) if font.Modified { r.generateTextureFromFont(render, font) font.Modified = false } } case entity.RTGeometry: // Check for geometry components r.drawGeometry(obj, position.Pos) continue case entity.RTGrid: // Grid component if component = obj.GetComponent(&entity.GridComponent{}); component != nil { grid := component.(*entity.GridComponent) r.drawGrid(grid) continue } } // Draw objects that have texture // Offset according to the camera crop := *render.Crop var x, y int32 if !r.isRenderable(position.Pos, crop) { // check if it is necessary to render continue } else { x, y = r.OffsetPosition(position.Pos.X, position.Pos.Y) } dst := createDestPos(*position, *render, x, y) r.Renderer.CopyEx(render.Texture, &crop, dst, render.Angle, render.Center, render.Flip) } r.Renderer.Present() } // createDestPos creates the rect destination using the Z position, thus with perspective. func createDestPos(position entity.PositionComponent, render entity.RenderComponent, x, y int32) *sdl.Rect { var dst *sdl.Rect if position.Z != 0 { z := position.Z + 1 dst = &sdl.Rect{ X: int32(float32(x) / z), Y: int32(float32(y) / z), W: int32(float32(render.Crop.W) / z), H: int32(float32(render.Crop.H) / z), } } else { dst = &sdl.Rect{X: x, Y: y, W: render.Crop.W, H: render.Crop.H} } return dst } // generateTextureFromFont generate Texture from Font component func (r *RenderSystem) generateTextureFromFont(render *entity.RenderComponent, font *entity.FontComponent) { var newTexture *sdl.Texture var solid *sdl.Surface var color sdl.Color var err error // Get color. If color is not set, make it black if font.Color == nil { color = sdl.Color{R: 0, G: 0, B: 0, A: 255} } else { color = *font.Color } //Load image at specified path if solid, err = font.Font.RenderUTF8Solid(font.Text, color); err != nil { logFatalf("Failed to render text: %s\n", err) } defer solid.Free() //Create texture from surface pixels newTexture, err = r.Renderer.CreateTextureFromSurface(solid) if err != nil { logFatalf("Unable to create texture from %s! SDL Error: %s\n", font.Text, sdl.GetError()) } render.Texture = newTexture render.Crop = &sdl.Rect{X: 0, Y: 0, W: solid.W, H: solid.H} } // drawGeometry draws on the renderer the geometry. We don't use texture, because it's faster to draw directly using the renderer func (r *RenderSystem) drawGeometry(geometryEntity *entity.Entity, pos *sdl.Point) { render := r.Renderer var component entity.Component component = geometryEntity.GetComponent(&entity.RectangleComponent{}) if component != nil { g := component.(*entity.RectangleComponent) render.SetDrawColor(g.Color.R, g.Color.G, g.Color.B, g.Color.A) w := g.Size.X h := g.Size.Y // Offset position according to camera x, y := r.OffsetPosition(pos.X, pos.Y) // Result of rectangle to draw rect := &sdl.Rect{X: x, Y: y, W: w, H: h} // check if it is necessary to render if !r.isRenderable(pos, *rect) { return } if g.Filled { render.FillRect(rect) } else { render.DrawRect(rect) } } else { logFatal("Geometry component not implemented in render function") } } // lerp is the linear interpolation. pos0 is the old position, pos1 is the new position, // alpha is the coeficient of the linear interpolation func lerp(pos0, pos1 *sdl.Point, alpha float32) *sdl.Point { x := math.Round(float32(pos1.X)*alpha + float32(pos0.X)*(1.0-alpha)) y := math.Round(float32(pos1.Y)*alpha + float32(pos0.Y)*(1.0-alpha)) return &sdl.Point{X: x, Y: y} } // nextAnimation returns the crop for the next animation func nextAnimation(now uint32, anim *entity.AnimationComponent, currentRect *sdl.Rect) *sdl.Rect { dt := now - anim.PreviousTime // log.Printf("diff time: %v\n", anim.PreviousTime) animations := dt * uint32(anim.AnimationSpeed) / 1000 if animations < 1 { // don't do anything. No animations to be done return currentRect } anim.Current += int(animations) anim.PreviousTime = now // log.Printf("Animation frame: %d\n", anim.Current) if lastElement := anim.Frames; anim.Current >= lastElement { anim.Current %= anim.Frames } xMultiplier := anim.Current % anim.RowLength yMultiplier := anim.Current / anim.RowLength x := int32(xMultiplier)*currentRect.W + anim.InitialPos.X y := int32(yMultiplier)*currentRect.H + anim.InitialPos.Y return &sdl.Rect{X: x, Y: y, W: currentRect.W, H: currentRect.H} } // drawGrid is used to draw a grid to help debugging func (r *RenderSystem) drawGrid(grid *entity.GridComponent) { render := r.Renderer var area sdl.Point area.X, area.Y = r.Window.GetSize() if grid.Color != nil { render.SetDrawColor(grid.Color.R, grid.Color.G, grid.Color.B, grid.Color.A) } else { render.SetDrawColor(0x0, 0x0, 0x0, 0xFF) } xIterations := area.X / grid.Size.X yIterations := area.Y / grid.Size.Y for i := int32(0); i < xIterations; i++ { for j := int32(0); j < yIterations; j++ { rect := &sdl.Rect{X: i * grid.Size.X, Y: j * grid.Size.Y, W: grid.Size.X, H: grid.Size.Y} render.DrawRect(rect) } } }
system/render.go
0.632957
0.407451
render.go
starcoder
package plan import ( "sync" "github.com/linanh/go-mysql-server/sql" ) // NewHashLookup returns a node that performs an indexed hash lookup // of cached rows for fulfilling RowIter() calls. In particular, this // node sits directly on top of a `CachedResults` node and has two // expressions: a projection for hashing the Child row results and // another projection for hashing the parent row values when // performing a lookup. When RowIter is called, if cached results are // available, it fulfills the RowIter call by performing a hash lookup // on the projected results. If cached results are not available, it // simply delegates to the child. func NewHashLookup(n *CachedResults, childProjection sql.Expression, lookupProjection sql.Expression) *HashLookup { return &HashLookup{ UnaryNode: UnaryNode{n}, childProjection: childProjection, lookupProjection: lookupProjection, mutex: new(sync.Mutex), } } type HashLookup struct { UnaryNode childProjection sql.Expression lookupProjection sql.Expression mutex *sync.Mutex lookup map[interface{}][]sql.Row } func (n *HashLookup) String() string { pr := sql.NewTreePrinter() _ = pr.WriteNode("HashLookup(child: %v, lookup: %v)", n.childProjection, n.lookupProjection) _ = pr.WriteChildren(n.UnaryNode.Child.String()) return pr.String() } func (n *HashLookup) DebugString() string { pr := sql.NewTreePrinter() _ = pr.WriteNode("HashLookup(child: %v, lookup: %v)", sql.DebugString(n.childProjection), sql.DebugString(n.lookupProjection)) _ = pr.WriteChildren(sql.DebugString(n.UnaryNode.Child)) return pr.String() } func (n *HashLookup) WithChildren(children ...sql.Node) (sql.Node, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(n, len(children), 1) } if _, ok := children[0].(*CachedResults); !ok { return nil, sql.ErrInvalidChildType.New(n, children[0], (*CachedResults)(nil)) } nn := *n nn.UnaryNode.Child = children[0] return &nn, nil } func (n *HashLookup) RowIter(ctx *sql.Context, r sql.Row) (sql.RowIter, error) { n.mutex.Lock() defer n.mutex.Unlock() if n.lookup == nil { // Instead of building the mapping inline here with a special // RowIter, we currently make use of CachedResults and require // *CachedResults to be our direct child. if res := n.UnaryNode.Child.(*CachedResults).getCachedResults(); res != nil { n.lookup = make(map[interface{}][]sql.Row) for _, row := range res { // TODO: Maybe do not put nil stuff in here. key, err := n.getHashKey(ctx, n.childProjection, row) if err != nil { return nil, err } n.lookup[key] = append(n.lookup[key], row) } // TODO: After the row cache is consumed and // hashed, it would be nice to dispose it. It // will never be used again. } } if n.lookup != nil { key, err := n.getHashKey(ctx, n.lookupProjection, r) if err != nil { return nil, err } return sql.RowsToRowIter(n.lookup[key]...), nil } return n.UnaryNode.Child.RowIter(ctx, r) } // Convert a tuple expression returning []interface{} into something comparable. // Fast paths a few smaller slices into fixed size arrays, puts everything else // through string serialization and a hash for now. It is OK to hash lossy here // as the join condition is still evaluated after the matching rows are returned. func (n *HashLookup) getHashKey(ctx *sql.Context, e sql.Expression, row sql.Row) (interface{}, error) { key, err := e.Eval(ctx, row) if err != nil { return nil, err } if s, ok := key.([]interface{}); ok { switch len(s) { case 0: return [0]interface{}{}, nil case 1: return [1]interface{}{s[0]}, nil case 2: return [2]interface{}{s[0], s[1]}, nil case 3: return [3]interface{}{s[0], s[1], s[2]}, nil case 4: return [4]interface{}{s[0], s[1], s[2], s[3]}, nil case 5: return [5]interface{}{s[0], s[1], s[2], s[3], s[4]}, nil default: return sql.HashOf(s) } } return key, nil }
sql/plan/hash_lookup.go
0.575111
0.400075
hash_lookup.go
starcoder
package kdtree import "math" var ( _ Interface = Points(nil) _ Comparable = Point(nil) ) // Point represents a point in a k-d space that satisfies the Comparable interface. type Point []float64 // Compare returns the signed distance of p from the plane passing through c and // perpendicular to the dimension d. The concrete type of c must be Point. func (p Point) Compare(c Comparable, d Dim) float64 { q := c.(Point); return p[d] - q[d] } // Dims returns the number of dimensions described by the receiver. func (p Point) Dims() int { return len(p) } // Distance returns the squared Euclidean distance between c and the receiver. The // concrete type of c must be Point. func (p Point) Distance(c Comparable) float64 { q := c.(Point) var sum float64 for dim, c := range p { d := c - q[dim] sum += d * d } return sum } // Extend returns a bounding box that has been extended to include the receiver. func (p Point) Extend(b *Bounding) *Bounding { if b == nil { b = &Bounding{append(Point(nil), p...), append(Point(nil), p...)} } min := b.Min.(Point) max := b.Max.(Point) for d, v := range p { min[d] = math.Min(min[d], v) max[d] = math.Max(max[d], v) } *b = Bounding{Min: min, Max: max} return b } // Points is a collection of point values that satisfies the Interface. type Points []Point func (p Points) Bounds() *Bounding { if p.Len() == 0 { return nil } min := append(Point(nil), p[0]...) max := append(Point(nil), p[0]...) for _, e := range p[1:] { for d, v := range e { min[d] = math.Min(min[d], v) max[d] = math.Max(max[d], v) } } return &Bounding{Min: min, Max: max} } func (p Points) Index(i int) Comparable { return p[i] } func (p Points) Len() int { return len(p) } func (p Points) Pivot(d Dim) int { return Plane{Points: p, Dim: d}.Pivot() } func (p Points) Slice(start, end int) Interface { return p[start:end] } // Plane is a wrapping type that allows a Points type be pivoted on a dimension. // The Pivot method of Plane uses MedianOfRandoms sampling at most 100 elements // to find a pivot element. type Plane struct { Dim Points } // randoms is the maximum number of random values to sample for calculation of // median of random elements. const randoms = 100 func (p Plane) Less(i, j int) bool { return p.Points[i][p.Dim] < p.Points[j][p.Dim] } func (p Plane) Pivot() int { return Partition(p, MedianOfRandoms(p, randoms)) } func (p Plane) Slice(start, end int) SortSlicer { p.Points = p.Points[start:end]; return p } func (p Plane) Swap(i, j int) { p.Points[i], p.Points[j] = p.Points[j], p.Points[i] }
spatial/kdtree/points.go
0.89818
0.704377
points.go
starcoder
package entities import "github.com/rpaloschi/dxf-go/core" // Spline Entity representation type Spline struct { BaseEntity NormalVector core.Point Closed bool Periodic bool Rational bool Planar bool Linear bool Degree int64 KnotTolerance float64 ControlPointTolerance float64 FitTolerance float64 StartTangent core.Point EndTangent core.Point KnotValues []float64 Weights []float64 ControlPoints core.PointSlice FitPoints core.PointSlice } // Equals tests equality against another Spline. func (s Spline) Equals(other core.DxfElement) bool { if otherSpline, ok := other.(*Spline); ok { return s.BaseEntity.Equals(otherSpline.BaseEntity) && s.NormalVector.Equals(otherSpline.NormalVector) && s.Closed == otherSpline.Closed && s.Periodic == otherSpline.Periodic && s.Rational == otherSpline.Rational && s.Planar == otherSpline.Planar && s.Linear == otherSpline.Linear && s.Degree == otherSpline.Degree && core.FloatEquals(s.KnotTolerance, otherSpline.KnotTolerance) && core.FloatEquals(s.ControlPointTolerance, otherSpline.ControlPointTolerance) && core.FloatEquals(s.FitTolerance, otherSpline.FitTolerance) && s.StartTangent.Equals(otherSpline.StartTangent) && s.EndTangent.Equals(otherSpline.EndTangent) && core.FloatSliceEquals(s.KnotValues, otherSpline.KnotValues) && core.FloatSliceEquals(s.Weights, otherSpline.Weights) && s.ControlPoints.Equals(otherSpline.ControlPoints) && s.FitPoints.Equals(otherSpline.FitPoints) } return false } const closedSplineBit = 0x1 const periodicSplineBit = 0x2 const rationalSplineBit = 0x4 const planarBit = 0x8 const linearBit = 0x10 // NewSpline builds a new Spline from a slice of Tags. func NewSpline(tags core.TagSlice) (*Spline, error) { spline := new(Spline) // set defaults spline.KnotTolerance = 0.0000001 spline.ControlPointTolerance = 0.0000001 spline.FitTolerance = 0.0000000001 spline.KnotValues = make([]float64, 0) spline.Weights = make([]float64, 0) spline.ControlPoints = make(core.PointSlice, 0) spline.FitPoints = make(core.PointSlice, 0) spline.InitBaseEntityParser() spline.Update(map[int]core.TypeParser{ 10: core.NewFloatTypeParser(func(value float64) { spline.ControlPoints = append(spline.ControlPoints, core.Point{X: value}) }), 20: core.NewFloatTypeParser(func(value float64) { spline.ControlPoints[len(spline.ControlPoints)-1].Y = value }), 30: core.NewFloatTypeParser(func(value float64) { spline.ControlPoints[len(spline.ControlPoints)-1].Z = value }), 11: core.NewFloatTypeParser(func(value float64) { spline.FitPoints = append(spline.FitPoints, core.Point{X: value}) }), 21: core.NewFloatTypeParser(func(value float64) { spline.FitPoints[len(spline.FitPoints)-1].Y = value }), 31: core.NewFloatTypeParser(func(value float64) { spline.FitPoints[len(spline.FitPoints)-1].Z = value }), 12: core.NewFloatTypeParserToVar(&spline.StartTangent.X), 22: core.NewFloatTypeParserToVar(&spline.StartTangent.Y), 32: core.NewFloatTypeParserToVar(&spline.StartTangent.Z), 13: core.NewFloatTypeParserToVar(&spline.EndTangent.X), 23: core.NewFloatTypeParserToVar(&spline.EndTangent.Y), 33: core.NewFloatTypeParserToVar(&spline.EndTangent.Z), 40: core.NewFloatTypeParser(func(value float64) { spline.KnotValues = append(spline.KnotValues, value) }), 41: core.NewFloatTypeParser(func(value float64) { spline.Weights = append(spline.Weights, value) }), 42: core.NewFloatTypeParserToVar(&spline.KnotTolerance), 43: core.NewFloatTypeParserToVar(&spline.ControlPointTolerance), 44: core.NewFloatTypeParserToVar(&spline.FitTolerance), 70: core.NewIntTypeParser(func(flags int64) { spline.Closed = flags&closedSplineBit != 0 spline.Periodic = flags&periodicSplineBit != 0 spline.Rational = flags&rationalSplineBit != 0 spline.Planar = flags&planarBit != 0 spline.Linear = flags&linearBit != 0 }), 71: core.NewIntTypeParserToVar(&spline.Degree), // We don't need those as we accumulate the values. // leaving them here as documentation and to remember to generate // them on writing. // 72: core.NewIntTypeParserToVar(&spline.NrKnots), // 73: core.NewIntTypeParserToVar(&spline.NrControlPoints), // 74: core.NewIntTypeParserToVar(&spline.NrFitPoints), 210: core.NewFloatTypeParserToVar(&spline.NormalVector.X), 220: core.NewFloatTypeParserToVar(&spline.NormalVector.Y), 230: core.NewFloatTypeParserToVar(&spline.NormalVector.Z), }) err := spline.Parse(tags) return spline, err }
vendor/github.com/rpaloschi/dxf-go/entities/spline.go
0.663887
0.518607
spline.go
starcoder
package models import ( i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time" i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // ServicePrincipalRiskDetection type ServicePrincipalRiskDetection struct { Entity // Indicates the activity type the detected risk is linked to. The possible values are: signin, unknownFutureValue, servicePrincipal. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: servicePrincipal. activity *ActivityType // Date and time when the risky activity occurred. The DateTimeOffset type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z activityDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time // Additional information associated with the risk detection. This string value is represented as a JSON object with the quotations escaped. additionalInfo *string // The unique identifier for the associated application. appId *string // Correlation ID of the sign-in activity associated with the risk detection. This property is null if the risk detection is not associated with a sign-in activity. correlationId *string // Date and time when the risk was detected. The DateTimeOffset type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. detectedDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time // Timing of the detected risk , whether real-time or offline). The possible values are: notDefined, realtime, nearRealtime, offline, unknownFutureValue. detectionTimingType *RiskDetectionTimingType // Provides the IP address of the client from where the risk occurred. ipAddress *string // The unique identifier (GUID) for the key credential associated with the risk detection. keyIds []string // Date and time when the risk detection was last updated. lastUpdatedDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time // Location from where the sign-in was initiated. location SignInLocationable // Request identifier of the sign-in activity associated with the risk detection. This property is null if the risk detection is not associated with a sign-in activity. Supports $filter (eq). requestId *string // Details of the detected risk. Note: Details for this property are only available for Azure AD Premium P2 customers. P1 customers will be returned hidden. The possible values are: none, hidden, unknownFutureValue, adminConfirmedServicePrincipalCompromised, adminDismissedAllRiskForServicePrincipal. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: adminConfirmedServicePrincipalCompromised , adminDismissedAllRiskForServicePrincipal. riskDetail *RiskDetail // The type of risk event detected. The possible values are: investigationsThreatIntelligence, generic, adminConfirmedServicePrincipalCompromised, suspiciousSignins, leakedCredentials, unknownFutureValue. Supports $filter (eq). riskEventType *string // Level of the detected risk. Note: Details for this property are only available for Azure AD Premium P2 customers. P1 customers will be returned hidden. The possible values are: low, medium, high, hidden, none, unknownFutureValue. riskLevel *RiskLevel // The state of a detected risky service principal or sign-in activity. The possible values are: none, dismissed, atRisk, confirmedCompromised, unknownFutureValue. riskState *RiskState // The display name for the service principal. servicePrincipalDisplayName *string // The unique identifier for the service principal. Supports $filter (eq). servicePrincipalId *string // Source of the risk detection. For example, identityProtection. source *string // Indicates the type of token issuer for the detected sign-in risk. The possible values are: AzureAD, UnknownFutureValue. tokenIssuerType *TokenIssuerType } // NewServicePrincipalRiskDetection instantiates a new servicePrincipalRiskDetection and sets the default values. func NewServicePrincipalRiskDetection()(*ServicePrincipalRiskDetection) { m := &ServicePrincipalRiskDetection{ Entity: *NewEntity(), } return m } // CreateServicePrincipalRiskDetectionFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateServicePrincipalRiskDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewServicePrincipalRiskDetection(), nil } // GetActivity gets the activity property value. Indicates the activity type the detected risk is linked to. The possible values are: signin, unknownFutureValue, servicePrincipal. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: servicePrincipal. func (m *ServicePrincipalRiskDetection) GetActivity()(*ActivityType) { if m == nil { return nil } else { return m.activity } } // GetActivityDateTime gets the activityDateTime property value. Date and time when the risky activity occurred. The DateTimeOffset type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z func (m *ServicePrincipalRiskDetection) GetActivityDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.activityDateTime } } // GetAdditionalInfo gets the additionalInfo property value. Additional information associated with the risk detection. This string value is represented as a JSON object with the quotations escaped. func (m *ServicePrincipalRiskDetection) GetAdditionalInfo()(*string) { if m == nil { return nil } else { return m.additionalInfo } } // GetAppId gets the appId property value. The unique identifier for the associated application. func (m *ServicePrincipalRiskDetection) GetAppId()(*string) { if m == nil { return nil } else { return m.appId } } // GetCorrelationId gets the correlationId property value. Correlation ID of the sign-in activity associated with the risk detection. This property is null if the risk detection is not associated with a sign-in activity. func (m *ServicePrincipalRiskDetection) GetCorrelationId()(*string) { if m == nil { return nil } else { return m.correlationId } } // GetDetectedDateTime gets the detectedDateTime property value. Date and time when the risk was detected. The DateTimeOffset type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. func (m *ServicePrincipalRiskDetection) GetDetectedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.detectedDateTime } } // GetDetectionTimingType gets the detectionTimingType property value. Timing of the detected risk , whether real-time or offline). The possible values are: notDefined, realtime, nearRealtime, offline, unknownFutureValue. func (m *ServicePrincipalRiskDetection) GetDetectionTimingType()(*RiskDetectionTimingType) { if m == nil { return nil } else { return m.detectionTimingType } } // GetFieldDeserializers the deserialization information for the current model func (m *ServicePrincipalRiskDetection) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["activity"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseActivityType) if err != nil { return err } if val != nil { m.SetActivity(val.(*ActivityType)) } return nil } res["activityDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetActivityDateTime(val) } return nil } res["additionalInfo"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetAdditionalInfo(val) } return nil } res["appId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetAppId(val) } return nil } res["correlationId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetCorrelationId(val) } return nil } res["detectedDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetDetectedDateTime(val) } return nil } res["detectionTimingType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseRiskDetectionTimingType) if err != nil { return err } if val != nil { m.SetDetectionTimingType(val.(*RiskDetectionTimingType)) } return nil } res["ipAddress"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetIpAddress(val) } return nil } res["keyIds"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfPrimitiveValues("string") if err != nil { return err } if val != nil { res := make([]string, len(val)) for i, v := range val { res[i] = *(v.(*string)) } m.SetKeyIds(res) } return nil } res["lastUpdatedDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetLastUpdatedDateTime(val) } return nil } res["location"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreateSignInLocationFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetLocation(val.(SignInLocationable)) } return nil } res["requestId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetRequestId(val) } return nil } res["riskDetail"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseRiskDetail) if err != nil { return err } if val != nil { m.SetRiskDetail(val.(*RiskDetail)) } return nil } res["riskEventType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetRiskEventType(val) } return nil } res["riskLevel"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseRiskLevel) if err != nil { return err } if val != nil { m.SetRiskLevel(val.(*RiskLevel)) } return nil } res["riskState"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseRiskState) if err != nil { return err } if val != nil { m.SetRiskState(val.(*RiskState)) } return nil } res["servicePrincipalDisplayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetServicePrincipalDisplayName(val) } return nil } res["servicePrincipalId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetServicePrincipalId(val) } return nil } res["source"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetSource(val) } return nil } res["tokenIssuerType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseTokenIssuerType) if err != nil { return err } if val != nil { m.SetTokenIssuerType(val.(*TokenIssuerType)) } return nil } return res } // GetIpAddress gets the ipAddress property value. Provides the IP address of the client from where the risk occurred. func (m *ServicePrincipalRiskDetection) GetIpAddress()(*string) { if m == nil { return nil } else { return m.ipAddress } } // GetKeyIds gets the keyIds property value. The unique identifier (GUID) for the key credential associated with the risk detection. func (m *ServicePrincipalRiskDetection) GetKeyIds()([]string) { if m == nil { return nil } else { return m.keyIds } } // GetLastUpdatedDateTime gets the lastUpdatedDateTime property value. Date and time when the risk detection was last updated. func (m *ServicePrincipalRiskDetection) GetLastUpdatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.lastUpdatedDateTime } } // GetLocation gets the location property value. Location from where the sign-in was initiated. func (m *ServicePrincipalRiskDetection) GetLocation()(SignInLocationable) { if m == nil { return nil } else { return m.location } } // GetRequestId gets the requestId property value. Request identifier of the sign-in activity associated with the risk detection. This property is null if the risk detection is not associated with a sign-in activity. Supports $filter (eq). func (m *ServicePrincipalRiskDetection) GetRequestId()(*string) { if m == nil { return nil } else { return m.requestId } } // GetRiskDetail gets the riskDetail property value. Details of the detected risk. Note: Details for this property are only available for Azure AD Premium P2 customers. P1 customers will be returned hidden. The possible values are: none, hidden, unknownFutureValue, adminConfirmedServicePrincipalCompromised, adminDismissedAllRiskForServicePrincipal. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: adminConfirmedServicePrincipalCompromised , adminDismissedAllRiskForServicePrincipal. func (m *ServicePrincipalRiskDetection) GetRiskDetail()(*RiskDetail) { if m == nil { return nil } else { return m.riskDetail } } // GetRiskEventType gets the riskEventType property value. The type of risk event detected. The possible values are: investigationsThreatIntelligence, generic, adminConfirmedServicePrincipalCompromised, suspiciousSignins, leakedCredentials, unknownFutureValue. Supports $filter (eq). func (m *ServicePrincipalRiskDetection) GetRiskEventType()(*string) { if m == nil { return nil } else { return m.riskEventType } } // GetRiskLevel gets the riskLevel property value. Level of the detected risk. Note: Details for this property are only available for Azure AD Premium P2 customers. P1 customers will be returned hidden. The possible values are: low, medium, high, hidden, none, unknownFutureValue. func (m *ServicePrincipalRiskDetection) GetRiskLevel()(*RiskLevel) { if m == nil { return nil } else { return m.riskLevel } } // GetRiskState gets the riskState property value. The state of a detected risky service principal or sign-in activity. The possible values are: none, dismissed, atRisk, confirmedCompromised, unknownFutureValue. func (m *ServicePrincipalRiskDetection) GetRiskState()(*RiskState) { if m == nil { return nil } else { return m.riskState } } // GetServicePrincipalDisplayName gets the servicePrincipalDisplayName property value. The display name for the service principal. func (m *ServicePrincipalRiskDetection) GetServicePrincipalDisplayName()(*string) { if m == nil { return nil } else { return m.servicePrincipalDisplayName } } // GetServicePrincipalId gets the servicePrincipalId property value. The unique identifier for the service principal. Supports $filter (eq). func (m *ServicePrincipalRiskDetection) GetServicePrincipalId()(*string) { if m == nil { return nil } else { return m.servicePrincipalId } } // GetSource gets the source property value. Source of the risk detection. For example, identityProtection. func (m *ServicePrincipalRiskDetection) GetSource()(*string) { if m == nil { return nil } else { return m.source } } // GetTokenIssuerType gets the tokenIssuerType property value. Indicates the type of token issuer for the detected sign-in risk. The possible values are: AzureAD, UnknownFutureValue. func (m *ServicePrincipalRiskDetection) GetTokenIssuerType()(*TokenIssuerType) { if m == nil { return nil } else { return m.tokenIssuerType } } // Serialize serializes information the current object func (m *ServicePrincipalRiskDetection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } if m.GetActivity() != nil { cast := (*m.GetActivity()).String() err = writer.WriteStringValue("activity", &cast) if err != nil { return err } } { err = writer.WriteTimeValue("activityDateTime", m.GetActivityDateTime()) if err != nil { return err } } { err = writer.WriteStringValue("additionalInfo", m.GetAdditionalInfo()) if err != nil { return err } } { err = writer.WriteStringValue("appId", m.GetAppId()) if err != nil { return err } } { err = writer.WriteStringValue("correlationId", m.GetCorrelationId()) if err != nil { return err } } { err = writer.WriteTimeValue("detectedDateTime", m.GetDetectedDateTime()) if err != nil { return err } } if m.GetDetectionTimingType() != nil { cast := (*m.GetDetectionTimingType()).String() err = writer.WriteStringValue("detectionTimingType", &cast) if err != nil { return err } } { err = writer.WriteStringValue("ipAddress", m.GetIpAddress()) if err != nil { return err } } if m.GetKeyIds() != nil { err = writer.WriteCollectionOfStringValues("keyIds", m.GetKeyIds()) if err != nil { return err } } { err = writer.WriteTimeValue("lastUpdatedDateTime", m.GetLastUpdatedDateTime()) if err != nil { return err } } { err = writer.WriteObjectValue("location", m.GetLocation()) if err != nil { return err } } { err = writer.WriteStringValue("requestId", m.GetRequestId()) if err != nil { return err } } if m.GetRiskDetail() != nil { cast := (*m.GetRiskDetail()).String() err = writer.WriteStringValue("riskDetail", &cast) if err != nil { return err } } { err = writer.WriteStringValue("riskEventType", m.GetRiskEventType()) if err != nil { return err } } if m.GetRiskLevel() != nil { cast := (*m.GetRiskLevel()).String() err = writer.WriteStringValue("riskLevel", &cast) if err != nil { return err } } if m.GetRiskState() != nil { cast := (*m.GetRiskState()).String() err = writer.WriteStringValue("riskState", &cast) if err != nil { return err } } { err = writer.WriteStringValue("servicePrincipalDisplayName", m.GetServicePrincipalDisplayName()) if err != nil { return err } } { err = writer.WriteStringValue("servicePrincipalId", m.GetServicePrincipalId()) if err != nil { return err } } { err = writer.WriteStringValue("source", m.GetSource()) if err != nil { return err } } if m.GetTokenIssuerType() != nil { cast := (*m.GetTokenIssuerType()).String() err = writer.WriteStringValue("tokenIssuerType", &cast) if err != nil { return err } } return nil } // SetActivity sets the activity property value. Indicates the activity type the detected risk is linked to. The possible values are: signin, unknownFutureValue, servicePrincipal. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: servicePrincipal. func (m *ServicePrincipalRiskDetection) SetActivity(value *ActivityType)() { if m != nil { m.activity = value } } // SetActivityDateTime sets the activityDateTime property value. Date and time when the risky activity occurred. The DateTimeOffset type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z func (m *ServicePrincipalRiskDetection) SetActivityDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.activityDateTime = value } } // SetAdditionalInfo sets the additionalInfo property value. Additional information associated with the risk detection. This string value is represented as a JSON object with the quotations escaped. func (m *ServicePrincipalRiskDetection) SetAdditionalInfo(value *string)() { if m != nil { m.additionalInfo = value } } // SetAppId sets the appId property value. The unique identifier for the associated application. func (m *ServicePrincipalRiskDetection) SetAppId(value *string)() { if m != nil { m.appId = value } } // SetCorrelationId sets the correlationId property value. Correlation ID of the sign-in activity associated with the risk detection. This property is null if the risk detection is not associated with a sign-in activity. func (m *ServicePrincipalRiskDetection) SetCorrelationId(value *string)() { if m != nil { m.correlationId = value } } // SetDetectedDateTime sets the detectedDateTime property value. Date and time when the risk was detected. The DateTimeOffset type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. func (m *ServicePrincipalRiskDetection) SetDetectedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.detectedDateTime = value } } // SetDetectionTimingType sets the detectionTimingType property value. Timing of the detected risk , whether real-time or offline). The possible values are: notDefined, realtime, nearRealtime, offline, unknownFutureValue. func (m *ServicePrincipalRiskDetection) SetDetectionTimingType(value *RiskDetectionTimingType)() { if m != nil { m.detectionTimingType = value } } // SetIpAddress sets the ipAddress property value. Provides the IP address of the client from where the risk occurred. func (m *ServicePrincipalRiskDetection) SetIpAddress(value *string)() { if m != nil { m.ipAddress = value } } // SetKeyIds sets the keyIds property value. The unique identifier (GUID) for the key credential associated with the risk detection. func (m *ServicePrincipalRiskDetection) SetKeyIds(value []string)() { if m != nil { m.keyIds = value } } // SetLastUpdatedDateTime sets the lastUpdatedDateTime property value. Date and time when the risk detection was last updated. func (m *ServicePrincipalRiskDetection) SetLastUpdatedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.lastUpdatedDateTime = value } } // SetLocation sets the location property value. Location from where the sign-in was initiated. func (m *ServicePrincipalRiskDetection) SetLocation(value SignInLocationable)() { if m != nil { m.location = value } } // SetRequestId sets the requestId property value. Request identifier of the sign-in activity associated with the risk detection. This property is null if the risk detection is not associated with a sign-in activity. Supports $filter (eq). func (m *ServicePrincipalRiskDetection) SetRequestId(value *string)() { if m != nil { m.requestId = value } } // SetRiskDetail sets the riskDetail property value. Details of the detected risk. Note: Details for this property are only available for Azure AD Premium P2 customers. P1 customers will be returned hidden. The possible values are: none, hidden, unknownFutureValue, adminConfirmedServicePrincipalCompromised, adminDismissedAllRiskForServicePrincipal. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: adminConfirmedServicePrincipalCompromised , adminDismissedAllRiskForServicePrincipal. func (m *ServicePrincipalRiskDetection) SetRiskDetail(value *RiskDetail)() { if m != nil { m.riskDetail = value } } // SetRiskEventType sets the riskEventType property value. The type of risk event detected. The possible values are: investigationsThreatIntelligence, generic, adminConfirmedServicePrincipalCompromised, suspiciousSignins, leakedCredentials, unknownFutureValue. Supports $filter (eq). func (m *ServicePrincipalRiskDetection) SetRiskEventType(value *string)() { if m != nil { m.riskEventType = value } } // SetRiskLevel sets the riskLevel property value. Level of the detected risk. Note: Details for this property are only available for Azure AD Premium P2 customers. P1 customers will be returned hidden. The possible values are: low, medium, high, hidden, none, unknownFutureValue. func (m *ServicePrincipalRiskDetection) SetRiskLevel(value *RiskLevel)() { if m != nil { m.riskLevel = value } } // SetRiskState sets the riskState property value. The state of a detected risky service principal or sign-in activity. The possible values are: none, dismissed, atRisk, confirmedCompromised, unknownFutureValue. func (m *ServicePrincipalRiskDetection) SetRiskState(value *RiskState)() { if m != nil { m.riskState = value } } // SetServicePrincipalDisplayName sets the servicePrincipalDisplayName property value. The display name for the service principal. func (m *ServicePrincipalRiskDetection) SetServicePrincipalDisplayName(value *string)() { if m != nil { m.servicePrincipalDisplayName = value } } // SetServicePrincipalId sets the servicePrincipalId property value. The unique identifier for the service principal. Supports $filter (eq). func (m *ServicePrincipalRiskDetection) SetServicePrincipalId(value *string)() { if m != nil { m.servicePrincipalId = value } } // SetSource sets the source property value. Source of the risk detection. For example, identityProtection. func (m *ServicePrincipalRiskDetection) SetSource(value *string)() { if m != nil { m.source = value } } // SetTokenIssuerType sets the tokenIssuerType property value. Indicates the type of token issuer for the detected sign-in risk. The possible values are: AzureAD, UnknownFutureValue. func (m *ServicePrincipalRiskDetection) SetTokenIssuerType(value *TokenIssuerType)() { if m != nil { m.tokenIssuerType = value } }
models/service_principal_risk_detection.go
0.750644
0.429728
service_principal_risk_detection.go
starcoder
package sema import ( "github.com/onflow/cadence/runtime/ast" ) func (checker *Checker) VisitSwitchStatement(statement *ast.SwitchStatement) ast.Repr { testType := checker.VisitExpression(statement.Expression, nil) testTypeIsValid := !testType.IsInvalidType() // The test expression must be equatable if testTypeIsValid && !testType.IsEquatable() { checker.report( &NotEquatableTypeError{ Type: testType, Range: ast.NewRangeFromPositioned(statement.Expression), }, ) } // Check all cases caseCount := len(statement.Cases) for i, switchCase := range statement.Cases { // Only one default case is allowed, as the last case defaultAllowed := i == caseCount-1 checker.visitSwitchCase(switchCase, defaultAllowed, testType, testTypeIsValid) } checker.functionActivations.WithSwitch(func() { checker.checkSwitchCasesStatements(statement.Cases) }) return nil } func (checker *Checker) visitSwitchCase( switchCase *ast.SwitchCase, defaultAllowed bool, testType Type, testTypeIsValid bool, ) { caseExpression := switchCase.Expression // If the case has no expression, it is a default case if caseExpression == nil { // Only one default case is allowed, as the last case if !defaultAllowed { checker.report( &SwitchDefaultPositionError{ Range: switchCase.Range, }, ) } } else { checker.checkSwitchCaseExpression(caseExpression, testType, testTypeIsValid) } } func (checker *Checker) checkSwitchCaseExpression( caseExpression ast.Expression, testType Type, testTypeIsValid bool, ) { caseType := checker.VisitExpression(caseExpression, nil) if caseType.IsInvalidType() { return } // The type of each case expression must be the same // as the type of the test expression if testTypeIsValid { // If the test type is valid, // the case type can be checked to be equatable and compatible in one go if !AreCompatibleEquatableTypes(testType, caseType) { checker.report( &InvalidBinaryOperandsError{ Operation: ast.OperationEqual, LeftType: testType, RightType: caseType, Range: ast.NewRangeFromPositioned(caseExpression), }, ) } } else { // If the test type is invalid, // at least the case type can be checked to be equatable if !caseType.IsEquatable() { checker.report( &NotEquatableTypeError{ Type: caseType, Range: ast.NewRangeFromPositioned(caseExpression), }, ) } } } func (checker *Checker) checkSwitchCasesStatements(cases []*ast.SwitchCase) { caseCount := len(cases) if caseCount == 0 { return } // NOTE: always check blocks as if they're only *potentially* evaluated. // However, the default case's block must be checked directly as the "else", // because if a default case exists, the whole switch statement // will definitely have one case which will be taken. switchCase := cases[0] if caseCount == 1 && switchCase.Expression == nil { checker.checkSwitchCaseStatements(switchCase) return } _, _ = checker.checkConditionalBranches( func() Type { checker.checkSwitchCaseStatements(switchCase) return nil }, func() Type { checker.checkSwitchCasesStatements(cases[1:]) return nil }, ) } func (checker *Checker) checkSwitchCaseStatements(switchCase *ast.SwitchCase) { // Switch-cases must have at least one statement. // This avoids cases that look like implicit fallthrough is assumed. if len(switchCase.Statements) == 0 { checker.report( &MissingSwitchCaseStatementsError{ Pos: switchCase.EndPosition().Shifted(1), }, ) return } // NOTE: the block ensures that the statements are checked in a new scope block := &ast.Block{ Statements: switchCase.Statements, Range: ast.Range{ StartPos: switchCase.Statements[0].StartPosition(), EndPos: switchCase.EndPos, }, } block.Accept(checker) }
runtime/sema/check_switch.go
0.617051
0.475971
check_switch.go
starcoder
package clusters import ( "fmt" "math/rand" "time" ) // A Cluster which data points gravitate around type Cluster struct { Center Coordinates Observations Observations } // Clusters is a slice of clusters type Clusters []Cluster // New sets up a new set of clusters and randomly seeds their initial positions func New(k int, dataset Observations) (Clusters, error) { var c Clusters if len(dataset) == 0 || len(dataset[0].Coordinates()) == 0 { return c, fmt.Errorf("there must be at least one dimension in the data set") } if k == 0 { return c, fmt.Errorf("k must be greater than 0") } rand.Seed(time.Now().UnixNano()) for i := 0; i < k; i++ { var p Coordinates for j := 0; j < len(dataset[0].Coordinates()); j++ { p = append(p, rand.Float64()) } c = append(c, Cluster{ Center: p, }) } return c, nil } // Append adds an observation to the Cluster func (c *Cluster) Append(point Observation) { c.Observations = append(c.Observations, point) } // Nearest returns the index of the cluster nearest to point func (c Clusters) Nearest(point Observation) int { var ci int dist := -1.0 // Find the nearest cluster for this data point for i, cluster := range c { d := point.Distance(cluster.Center) if dist < 0 || d < dist { dist = d ci = i } } return ci } // Neighbour returns the neighbouring cluster of a point along with the average distance to its points func (c Clusters) Neighbour(point Observation, fromCluster int) (int, float64) { var d float64 nc := -1 for i, cluster := range c { if i == fromCluster { continue } cd := AverageDistance(point, cluster.Observations) if nc < 0 || cd < d { nc = i d = cd } } return nc, d } // Recenter recenters a cluster func (c *Cluster) Recenter() { center, err := c.Observations.Center() if err != nil { return } c.Center = center } // Recenter recenters all clusters func (c Clusters) Recenter() { for i := 0; i < len(c); i++ { c[i].Recenter() } } // Reset clears all point assignments func (c Clusters) Reset() { for i := 0; i < len(c); i++ { c[i].Observations = Observations{} } } // PointsInDimension returns all coordinates in a given dimension func (c Cluster) PointsInDimension(n int) Coordinates { var v []float64 for _, p := range c.Observations { v = append(v, p.Coordinates()[n]) } return v } // CentersInDimension returns all cluster centroids' coordinates in a given // dimension func (c Clusters) CentersInDimension(n int) Coordinates { var v []float64 for _, cl := range c { v = append(v, cl.Center[n]) } return v }
cluster.go
0.827863
0.544983
cluster.go
starcoder
package logic import ( "fmt" "github.com/inkyblackness/res/data" ) // LevelObjectChainLinkGetter is a function to return links from a chain. type LevelObjectChainLinkGetter func(index data.LevelObjectChainIndex) LevelObjectChainLink // LevelObjectChain handles the logic for a chain of level objects. type LevelObjectChain struct { start LevelObjectChainStart link LevelObjectChainLinkGetter } // NewLevelObjectChain returns a new chain based on the given accessors. func NewLevelObjectChain(start LevelObjectChainStart, linkGetter LevelObjectChainLinkGetter) *LevelObjectChain { return &LevelObjectChain{start: start, link: linkGetter} } // Initialize resets all entries to an clean state. // All links will be added to the pool of available entries. // The provided size is the number of possible links - excluding the start entry. func (chain *LevelObjectChain) Initialize(size int) { chain.start.SetReferenceIndex(0) chain.start.SetNextIndex(0) chain.start.SetPreviousIndex(0) for counter := size; counter > 0; counter-- { index := data.LevelObjectChainIndex(counter) chain.addLinkToAvailablePool(index) } } // AcquireLink tries to reserve a new chain link from the chain. // If the chain is exhausted, an error is returned. func (chain *LevelObjectChain) AcquireLink() (index data.LevelObjectChainIndex, err error) { index = chain.start.PreviousIndex() if !index.IsStart() { link := chain.link(index) previousIndex := chain.start.ReferenceIndex() previous := chain.link(previousIndex) chain.start.SetPreviousIndex(link.PreviousIndex()) chain.start.SetReferenceIndex(index) link.SetNextIndex(previous.NextIndex()) previous.SetNextIndex(index) link.SetPreviousIndex(previousIndex) } else { err = fmt.Errorf("Object chain exhausted - Can not add more entries.") } return } // ReleaseLink releases a link from the chain. func (chain *LevelObjectChain) ReleaseLink(index data.LevelObjectChainIndex) { link := chain.link(index) chain.link(link.PreviousIndex()).SetNextIndex(link.NextIndex()) if link.NextIndex().IsStart() { chain.start.SetReferenceIndex(link.PreviousIndex()) } else { chain.link(link.NextIndex()).SetPreviousIndex(link.PreviousIndex()) } chain.addLinkToAvailablePool(index) } func (chain *LevelObjectChain) addLinkToAvailablePool(index data.LevelObjectChainIndex) { link := chain.link(index) link.SetPreviousIndex(chain.start.PreviousIndex()) chain.start.SetPreviousIndex(index) }
logic/LevelObjectChain.go
0.690246
0.431045
LevelObjectChain.go
starcoder
package main import "math" /** 给定两个整数,被除数dividend和除数divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 返回被除数dividend除以除数divisor得到的商。 整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2 示例1: 输入: dividend = 10, divisor = 3 输出: 3 解释: 10/3 = truncate(3.33333..) = truncate(3) = 3 示例2: 输入: dividend = 7, divisor = -3 输出: -2 解释: 7/-3 = truncate(-2.33333..) = -2 提示: 被除数和除数均为 32 位有符号整数。 除数不为0。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231− 1]。本题中,如果除法结果溢出,则返回 231− 1。 */ /** 二分法 超出时间限制 */ func divide(dividend int, divisor int) int { x := int64(dividend) y := int64(divisor) if x == 0 { return 0 } negative := (x ^ y) < 0 //用异或来计算是否符号相异 if x < 0 { x = -x } if y < 0 { y = -y } var l int64 = 0 var r = x for l < r { mid := l + r + 1>>1 if quickMul(mid, y) <= x { l = mid } else { r = mid - 1 } } ans := l if negative { //符号相异取反 ans = -l } if ans > math.MaxInt32 || ans < math.MinInt32 { return math.MaxInt32 } return int(ans) } func quickMul(a int64, b int64) int64 { var res int64 if b < 0 { a = -a b = -b } for b > 0 { if b&1 == 1 { res += a } a += a b >>= 1 } return res } /** * 解题思路:这题是除法,所以先普及下除法术语 * 商,公式是:(被除数-余数)÷除数=商,记作:被除数÷除数=商...余数,是一种数学术语。 * 在一个除法算式里,被除数、余数、除数和商的关系为:(被除数-余数)÷除数=商,记作:被除数÷除数=商...余数, * 进而推导得出:商×除数+余数=被除数。 * * 要求商,我们首先想到的是减法,能被减多少次,那么商就为多少,但是明显减法的效率太低 * * 那么我们可以用位移法,因为计算机在做位移时效率特别高,向左移1相当于乘以2,向右位移1相当于除以2 * * 我们可以把一个dividend(被除数)先除以2^n,n最初为31,不断减小n去试探,当某个n满足dividend/2^n>=divisor时, * * 表示我们找到了一个足够大的数,这个数*divisor是不大于dividend的,所以我们就可以减去2^n个divisor,以此类推 * * 我们可以以100/3为例 * * 2^n是1,2,4,8...2^31这种数,当n为31时,这个数特别大,100/2^n是一个很小的数,肯定是小于3的,所以循环下来, * * 当n=5时,100/32=3, 刚好是大于等于3的,这时我们将100-32*3=4,也就是减去了32个3,接下来我们再处理4,同样手法可以再减去一个3 * * 所以一共是减去了33个3,所以商就是33 * * 这其中得处理一些特殊的数,比如divisor是不能为0的,Integer.MIN_VALUE和Integer.MAX_VALUE * */ func divide2(dividend int, divisor int) int { if dividend == 0 { return 0 } if dividend == math.MinInt32 && divisor == -1 { return math.MaxInt32 } negative := (dividend ^ divisor) < 0 //用异或来计算是否符号相异 if dividend < 0 { dividend = -dividend } if divisor < 0 { divisor = -divisor } result := 0 for i := 31; i >= 0; i-- { if (dividend >> i) >= divisor { //找出足够大的数2^n*divisor result += 1 << i //将结果加上2^n dividend -= divisor << i //将被除数减去2^n*divisor } } if negative { //符号相异取反 return -result } return result } /** java版 class Solution { public int divide(int a, int b) { long x = a, y = b; boolean isNeg = false; if ((x > 0 && y < 0) || (x < 0 && y > 0)) isNeg = true; if (x < 0) x = -x; if (y < 0) y = -y; long l = 0, r = x; while (l < r) { long mid = l + r + 1 >> 1; if (mul(mid, y) <= x) { l = mid; } else { r = mid - 1; } } long ans = isNeg ? -l : l; if (ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) return Integer.MAX_VALUE; return (int) ans; } long mul(long a, long k) { long ans = 0; while (k > 0) { if ((k & 1) == 1) ans += a; k >>= 1; a += a; } return ans; } } class Solution { public int divide(int dividend, int divisor) { if (dividend == 0) { return 0; } if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } boolean negative; negative = (dividend ^ divisor) <0;//用异或来计算是否符号相异 long t = Math.abs((long) dividend); long d= Math.abs((long) divisor); int result = 0; for (int i=31; i>=0;i--) { if ((t>>i)>=d) {//找出足够大的数2^n*divisor result+=1<<i;//将结果加上2^n t-=d<<i;//将被除数减去2^n*divisor } } return negative ? -result : result;//符号相异取反 } } */ func main() { }
leetcode/divide/divide.go
0.514888
0.455562
divide.go
starcoder
package main import ( "fmt" "sync" "github.com/go-playground/validator" "github.com/rs/zerolog/log" "gorm.io/gorm" ) var ( resourceLock sync.Mutex ) // Formation is the lowest-level object that is directly addressable by the user (within the context of Captain). A // formation manages a group of planes that are scaled up and down automatically. A formation is a logical representation // of an internal service for an application. For example, all web servers that serve the same web app would be // considered part of the same formation. All planes in a formation will be exactly the same except for the FQDN. type Formation struct { gorm.Model // Name of the service. Used only in user-facing queries, and is not used internally. Should be as unique as // possible for easy identification. Name string `validate:"required,min=1"` // Number of CPU cores to assign to each plane. The actual implementation of this varies depending on which // provider adapter is used. CPU int `validate:"required,gte=1,lte=8192"` // Amount of RAM in megabytes to assign to each plane. RAM int `validate:"required,gte=1,lte=307200"` // Size of disk in gigabytes to assign to each plane. It is important that this disk is big enough to store the // container OS in addition to application data. Disk int `validate:"required,gte=1"` // URL-safe name for each plane in formation. Should be unique within the flight. Will be used in the FQDN of each // plane that is provisioned within the formation. For example: formation1.example.com. BaseName string `validate:"alphanum,min=1,max=256"` // Domain name that forms the ending of the FQDN for each plane. In the future this will be moved to be the same // airspace-wide or stack-wide. Domain string `validate:"required,fqdn,min=1"` // Desired number of planes that should be operational at any given moment. At each health check interval, // remediations will be made to adjust the number of healthy planes in service until it equals this number. TargetCount int `validate:"gte=0"` // Relative path to playbook file to use to provision plane once the underlying VM/container is created. PreflightPlaybook string `validate:"-"` Planes []Plane `validate:"-"` FlightID int Flight Flight `validate:"-"` } // Performs all needed migrations to store formation state information in the database. func initFormations(db *gorm.DB) error { err := initPlanes(db) if err != nil { return fmt.Errorf("unable to migrate formation dependencies with error:\n%w", err) } err = db.AutoMigrate(&Formation{}) if err != nil { return fmt.Errorf("unable to migrate formation schema with error:\n%w", err) } resourceLock = sync.Mutex{} return nil } // Checks the health of the specified formation by checking the health of each plane. Remediation will be performed // until the number of operational planes matches the target number in the state database. func (f *Formation) performHealthChecks(db *gorm.DB) error { result := db.Where("formation_id = ?", f.ID).Preload("Formation").Find(&f.Planes) if result.Error != nil { return fmt.Errorf("unable to list planes for formation %s with error:\n%w", f.Name, result.Error) } // Remove dead planes. for i := 0; i < len(f.Planes); i++ { log.Trace().Str("formation", f.Name).Str("plane", f.Planes[i].getFQDN()).Msg("checking health of plane") isHealthy, err := f.Planes[i].isHealthy(db) if err != nil { return fmt.Errorf("unable to check health of plane %s with error:\n%w", f.Planes[i].getFQDN(), err) } if !isHealthy { // TODO: Possibly have a grace period up to X seconds before destroying container? result := db.Unscoped().Delete(&f.Planes[i]) if result.Error != nil { return fmt.Errorf("unable to remove unhealthy plane %s with error:\n%w", f.Planes[i].getFQDN(), result.Error) } } } // Check that the number of active (or planned) planes equals the target. if len(f.Planes) < f.TargetCount { log.Debug().Str("formation", f.Name).Msgf("formation currently has %d planes, expected %d", len(f.Planes), f.TargetCount) var offset = f.TargetCount - len(f.Planes) wg := new(sync.WaitGroup) wg.Add(offset) for i := 0; i < offset; i++ { f.launchBuilder(i, offset, wg, &resourceLock) } log.Trace().Str("formation", f.Name).Msgf("waiting for %d builder threads to return", offset) wg.Wait() } // Reload plane list in case changes were made result = db.Where("formation_id = ?", f.ID).Preload("Formation").Find(&f.Planes) if result.Error != nil { return fmt.Errorf("unable to list planes for formation %s with error:\n%w", f.Name, result.Error) } if len(f.Planes) > f.TargetCount { log.Debug().Str("formation", f.Name).Msgf("formation currently has %d planes, expected %d", len(f.Planes), f.TargetCount) // Delete oldest planes first (usually the first indexes) var numToDelete = len(f.Planes) - f.TargetCount for i := 0; i < numToDelete; i++ { result := db.Unscoped().Delete(&f.Planes[i]) if result.Error != nil { return fmt.Errorf("unable to delete excess plane %s with error:\n%w", f.Planes[i].getFQDN(), result.Error) } } } return nil } func (f *Formation) launchBuilder(id, totalBuilders int, wg *sync.WaitGroup, mx *sync.Mutex) { builder := builder{ ID: id, } log.Trace().Str("formation", f.Name).Msgf("firing off builder %d/%d to build plane", id, totalBuilders) go builder.buildPlane(Plane{ Formation: *f, FormationID: int(f.ID), Num: f.getNextNum(id), }, wg, mx) } // Gets the next available unique ID within a formation. func (f *Formation) getNextNum(offset int) int { var nextNum = 1 for i := 0; i < len(f.Planes); i++ { if f.Planes[i].Num > nextNum { nextNum = f.Planes[i].Num + 1 } } return nextNum + offset } // Validates the attributes of a formation object (Note: does not validate any child or parent objects). func (f *Formation) Validate() error { err := validator.New().Struct(f) if err != nil { return fmt.Errorf("invalid parameters for formation:\n%w", err) } return nil } // Handler before creation of a formation object in the state database. Validates the attributes of the formation // object to be sure that all technical values are url-safe and valid. func (f *Formation) BeforeCreate(tx *gorm.DB) error { err := f.Validate() if err != nil { return fmt.Errorf("invalid formation object:\n%w", err) } return nil }
ATC/Formation.go
0.672547
0.444806
Formation.go
starcoder
package material import ( "github.com/Glenn-Gray-Labs/g3n/gls" "github.com/Glenn-Gray-Labs/g3n/math32" ) // Standard material supports the classic lighting model with // ambient, diffuse, specular and emissive lights. // The lighting calculation is implemented in the vertex shader. type Standard struct { Material // Embedded material uni gls.Uniform // Uniform location cache udata struct { // Combined uniform data in 6 vec3: ambient math32.Color // Ambient color reflectivity diffuse math32.Color // Diffuse color reflectivity specular math32.Color // Specular color reflectivity emissive math32.Color // Emissive color shininess float32 // Specular shininess factor opacity float32 // Opacity psize float32 // Point size protationZ float32 // Point rotation around Z axis } } // Number of glsl shader vec3 elements used by uniform data const standardVec3Count = 6 // NewStandard creates and returns a pointer to a new standard material func NewStandard(color *math32.Color) *Standard { ms := new(Standard) ms.Init("standard", color) return ms } // Init initializes the material setting the specified shader and color // It is used mainly when the material is embedded in another type func (ms *Standard) Init(shader string, color *math32.Color) { ms.Material.Init() ms.SetShader(shader) // Creates uniforms and set initial values ms.uni.Init("Material") ms.SetColor(color) ms.SetSpecularColor(&math32.Color{0.5, 0.5, 0.5}) ms.SetEmissiveColor(&math32.Color{0, 0, 0}) ms.SetShininess(30.0) ms.SetOpacity(1.0) } // AmbientColor returns the material ambient color reflectivity. func (ms *Standard) AmbientColor() math32.Color { return ms.udata.ambient } // SetAmbientColor sets the material ambient color reflectivity. // The default is the same as the diffuse color func (ms *Standard) SetAmbientColor(color *math32.Color) { ms.udata.ambient = *color } // SetColor sets the material diffuse color and also the // material ambient color reflectivity func (ms *Standard) SetColor(color *math32.Color) { ms.udata.diffuse = *color ms.udata.ambient = *color } // SetEmissiveColor sets the material emissive color // The default is {0,0,0} func (ms *Standard) SetEmissiveColor(color *math32.Color) { ms.udata.emissive = *color } // EmissiveColor returns the material current emissive color func (ms *Standard) EmissiveColor() math32.Color { return ms.udata.emissive } // SetSpecularColor sets the material specular color reflectivity. // The default is {0.5, 0.5, 0.5} func (ms *Standard) SetSpecularColor(color *math32.Color) { ms.udata.specular = *color } // SetShininess sets the specular highlight factor. Default is 30. func (ms *Standard) SetShininess(shininess float32) { ms.udata.shininess = shininess } // SetOpacity sets the material opacity (alpha). Default is 1.0. func (ms *Standard) SetOpacity(opacity float32) { ms.udata.opacity = opacity } // RenderSetup is called by the engine before drawing the object // which uses this material func (ms *Standard) RenderSetup(gs *gls.GLS) { ms.Material.RenderSetup(gs) location := ms.uni.Location(gs) gs.Uniform3fv(location, standardVec3Count, &ms.udata.ambient.R) }
material/standard.go
0.872836
0.517449
standard.go
starcoder
package line import ( "github.com/gravestench/pho/geom/point" ) type LineNamespace interface { New(x1, y1, x2, y2 float64) *Line BresenhamPoints(l *Line, stepRate int, out []*point.Point) []*point.Point Length(l *Line) float64 GetPoint(l *Line, position float64, out *point.Point) *point.Point GetPoints(l *Line, quantity int, stepRate float64, out []*point.Point) []*point.Point GetRandomPoint(l *Line, assignTo *point.Point) *point.Point Angle(l *Line) float64 CenterOn(l *Line, x, y float64) *Line Clone(l *Line) *Line CopyFrom(l *Line, from *Line) *Line Equals(l *Line, other *Line) bool GetMidPoint(l *Line, out *point.Point) *point.Point GetNearestPoint(l *Line, p, out *point.Point) *point.Point GetNormal(l *Line, p, out *point.Point) *point.Point GetShortestDistance(l *Line, p *point.Point) float64 Height(l *Line) float64 Width(l *Line) float64 NormalAngle(l *Line) float64 NormalX(l *Line) float64 NormalY(l *Line) float64 Offset(l *Line, x, y float64) *Line PerpendicularSlope(l *Line) float64 ReflectAngle(l *Line, other *Line) float64 Rotate(l *Line, angle float64) *Line RotateAroundPoint(l *Line, p *point.Point, angle float64) *Line RotateAroundXY(l *Line, x, y, angle float64) *Line SetToAngle(l *Line, x, y, angle, length float64) *Line Slope(l *Line) float64 } type Namespace struct{} // New creates a new line func (*Namespace) New(x1, y1, x2, y2 float64) *Line { return New(x1, y1, x2, y2) } // BresenhamPoints uses Bresenham's line algorithm to return an array of all coordinates // on this line. func (*Namespace) BresenhamPoints(l *Line, stepRate int, out []*point.Point) []*point.Point { return BresenhamPoints(l, stepRate, out) } // Length calculates the length of the line. func (*Namespace) Length(l *Line) float64 { return Length(l) } // GetPoint on a line that's a given percentage along its length. func (*Namespace) GetPoint(l *Line, position float64, out *point.Point) *point.Point { return GetPoint(l, position, out) } // Get a number of points along a line's length. // Provide a `quantity` to get an exact number of points along the line. func (*Namespace) GetPoints(l *Line, quantity int, stepRate float64, out []*point.Point) []*point.Point { return GetPoints(l, quantity, stepRate, out) } // GetRandomPoint picks a random point along the line and assigns it to the argument point. // If argument is nil, a new point is created and returned. func (*Namespace) GetRandomPoint(l *Line, assignTo *point.Point) *point.Point { return GetRandomPoint(l, assignTo) } // Angle calculates the angle of the line in radians func (*Namespace) Angle(l *Line, ) float64 { return Angle(l) } // CenterOn centers a line on the given coordinates. func (*Namespace) CenterOn(l *Line, x, y float64) *Line { return CenterOn(l, x, y) } // Clone creates a clone of the line func (*Namespace) Clone(l *Line, ) *Line { return Clone(l) } // CopyFrom copies the values of one line to the line. func (*Namespace) CopyFrom(l *Line, from *Line) *Line { return CopyFrom(from, l) } // Equals checks if the line is approximately equal to another func (*Namespace) Equals(l *Line, other *Line) bool { return Equals(l, other) } // GetMidPoint get the midpoint of the line. // Assigns to the `out` point, or creates one if nil. func (*Namespace) GetMidPoint(l *Line, out *point.Point) *point.Point { return GetMidPoint(l, out) } // GetNearestPoint get the nearest point on a line perpendicular to the given point. func (*Namespace) GetNearestPoint(l *Line, p, out *point.Point) *point.Point { return GetNearestPoint(l, p, out) } // GetNormal calculates the normal of the line. // The normal of a line is a vector that points perpendicular from it. func (*Namespace) GetNormal(l *Line, p, out *point.Point) *point.Point { return GetNormal(l, p, out) } // GetShortestDistance get the shortest distance from a Line to the given Point. func (*Namespace) GetShortestDistance(l *Line, p *point.Point) float64 { return GetShortestDistance(l, p) } // Height calculates the height of the line. func (*Namespace) Height(l *Line, ) float64 { return Height(l) } // Width calculates the width of the given line. func (*Namespace) Width(l *Line, ) float64 { return Width(l) } // NormalAngle get the angle of the normal of the line in radians. func (*Namespace) NormalAngle(l *Line, ) float64 { return NormalAngle(l) } // NormalX returns the x component of the normal vector of the line. // The normal of a line is a vector that points perpendicular from it. func (*Namespace) NormalX(l *Line, ) float64 { return NormalX(l) } // NormalX returns the x component of the normal vector of the line. // The normal of a line is a vector that points perpendicular from it. func (*Namespace) NormalY(l *Line, ) float64 { return NormalY(l) } // Offset the line by the given amount. func (*Namespace) Offset(l *Line, x, y float64) *Line { return Offset(l, x, y) } // PerpendicularSlope calculates the perpendicular slope of the line. func (*Namespace) PerpendicularSlope(l *Line, ) float64 { return PerpendicularSlope(l) } // ReflectAngle calculates the reflected angle between the line and another line. // This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. func (*Namespace) ReflectAngle(l *Line, other *Line) float64 { return ReflectAngle(l, other) } // Rotate a line around its midpoint by the given angle in radians. func (*Namespace) Rotate(l *Line, angle float64) *Line { return Rotate(l, angle) } // RotateAroundPoint rotates a line around a point by the given angle in radians. func (*Namespace) RotateAroundPoint(l *Line, p *point.Point, angle float64) *Line { return RotateAroundPoint(l, p, angle) } // RotateXY rotates a line around the given coordinates by the given angle in radians. func (*Namespace) RotateAroundXY(l *Line, x, y, angle float64) *Line { return RotateAroundXY(l, x, y, angle) } // SetToAngle sets a line to a given position, angle and length. func (*Namespace) SetToAngle(l *Line, x, y, angle, length float64) *Line { return SetToAngle(l, x, y, angle, length) } // Slope calculates the slope of the line. func (*Namespace) Slope(l *Line, ) float64 { return Slope(l) }
geom/line/namespace.go
0.902287
0.542318
namespace.go
starcoder
package distuv import ( "math" "golang.org/x/exp/rand" "gonum.org/v1/gonum/mathext" ) // Poisson implements the Poisson distribution, a discrete probability distribution // that expresses the probability of a given number of events occurring in a fixed // interval. // The poisson distribution has density function: // f(k) = λ^k / k! e^(-λ) // For more information, see https://en.wikipedia.org/wiki/Poisson_distribution. type Poisson struct { // Lambda is the average number of events in an interval. // Lambda must be greater than 0. Lambda float64 Src rand.Source } // CDF computes the value of the cumulative distribution function at x. func (p Poisson) CDF(x float64) float64 { if x < 0 { return 0 } return mathext.GammaIncRegComp(math.Floor(x+1), p.Lambda) } // ExKurtosis returns the excess kurtosis of the distribution. func (p Poisson) ExKurtosis() float64 { return 1 / p.Lambda } // LogProb computes the natural logarithm of the value of the probability // density function at x. func (p Poisson) LogProb(x float64) float64 { if x < 0 || math.Floor(x) != x { return math.Inf(-1) } lg, _ := math.Lgamma(math.Floor(x) + 1) return x*math.Log(p.Lambda) - p.Lambda - lg } // Mean returns the mean of the probability distribution. func (p Poisson) Mean() float64 { return p.Lambda } // NumParameters returns the number of parameters in the distribution. func (Poisson) NumParameters() int { return 1 } // Prob computes the value of the probability density function at x. func (p Poisson) Prob(x float64) float64 { return math.Exp(p.LogProb(x)) } // Rand returns a random sample drawn from the distribution. func (p Poisson) Rand() float64 { // NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) // p. 294 // <http://www.aip.de/groups/soe/local/numres/bookcpdf/c7-3.pdf> rnd := rand.ExpFloat64 var rng *rand.Rand if p.Src != nil { rng = rand.New(p.Src) rnd = rng.ExpFloat64 } if p.Lambda < 10.0 { // Use direct method. var em float64 t := 0.0 for { t += rnd() if t >= p.Lambda { break } em++ } return em } // Use rejection method. rnd = rand.Float64 if rng != nil { rnd = rng.Float64 } sq := math.Sqrt(2.0 * p.Lambda) alxm := math.Log(p.Lambda) lg, _ := math.Lgamma(p.Lambda + 1) g := p.Lambda*alxm - lg for { var em, y float64 for { y = math.Tan(math.Pi * rnd()) em = sq*y + p.Lambda if em >= 0 { break } } em = math.Floor(em) lg, _ = math.Lgamma(em + 1) t := 0.9 * (1.0 + y*y) * math.Exp(em*alxm-lg-g) if rnd() <= t { return em } } } // Skewness returns the skewness of the distribution. func (p Poisson) Skewness() float64 { return 1 / math.Sqrt(p.Lambda) } // StdDev returns the standard deviation of the probability distribution. func (p Poisson) StdDev() float64 { return math.Sqrt(p.Variance()) } // Survival returns the survival function (complementary CDF) at x. func (p Poisson) Survival(x float64) float64 { return 1 - p.CDF(x) } // Variance returns the variance of the probability distribution. func (p Poisson) Variance() float64 { return p.Lambda }
stat/distuv/poisson.go
0.903084
0.655818
poisson.go
starcoder
package test import ( "reflect" "testing" "time" ) func ExpectedError(t *testing.T, err error, expected string) { t.Helper() ExpectedErrorF(t, err, expected, "") } func ExpectedErrorF(t *testing.T, err error, expected, msg string) { t.Helper() var actual string if err == nil { actual = "<no error>" } else { actual = err.Error() } if len(msg) > 0 { msg = "\n" + msg } if actual != expected { t.Errorf("expected error\ngot: \"%s\"\nexpected: %s\n%s", actual, expected, msg) t.Fail() } } func ExpectedNoError(t *testing.T, err error) { t.Helper() ExpectedNoErrorF(t, err, "") } func ExpectedNoErrorF(t *testing.T, err error, msg string) { t.Helper() if err == nil { return } if len(msg) > 0 { msg = "\n" + msg } t.Errorf("expected no error\ngot: %s\n%s", err, msg) t.Fail() } func ExpectedNotEqual(t *testing.T, actual, expected interface{}) { t.Helper() ExpectedEqualF(t, actual, expected, true, "") } func ExpectedEqual(t *testing.T, actual, expected interface{}) { t.Helper() ExpectedEqualF(t, actual, expected, false, "") } func ExpectedEqualF(t *testing.T, actual, expected interface{}, reverse bool, msg string) { t.Helper() equal := reflect.DeepEqual(actual, expected) if (!reverse && equal) || (reverse && !equal) { return } if len(msg) > 0 { msg = "\n" + msg } aType := reflect.TypeOf(actual) eType := reflect.TypeOf(expected) var not string if reverse { not = "not " } t.Errorf("expected values to %sbe equal\ngot: %s (%s)\nexpected: %s (%s)%s", not, actual, aType, expected, eType, msg) t.Fail() } func ExpectedTime(t *testing.T, start, end time.Time, expected, delta time.Duration) { t.Helper() ExpectedTimeF(t, start, end, expected, delta, "") } func ExpectedTimeF(t *testing.T, start, end time.Time, expected, delta time.Duration, msg string) { t.Helper() actual := end.Sub(start).Truncate(time.Millisecond) if actual >= expected-delta && actual <= expected+delta { return } if len(msg) > 0 { msg = "\n" + msg } t.Errorf("expected duration to equal (+-%s)\ngot: %s\nexpected: %s%s", delta, actual, expected, msg) t.Fail() } func ExpectedZeroValue(t *testing.T, actual interface{}) { t.Helper() ExpectedZeroValueF(t, actual, false, "") } func ExpectedNoZeroValue(t *testing.T, actual interface{}) { t.Helper() ExpectedZeroValueF(t, actual, true, "") } func ExpectedZeroValueF(t *testing.T, actual interface{}, reverse bool, msg string) { t.Helper() zeroVal := actual == nil || reflect.ValueOf(actual).IsZero() if (!reverse && zeroVal) || (reverse && !zeroVal) { return } if len(msg) > 0 { msg = "\n" + msg } var not string if reverse { not = "not " } t.Errorf("expected interface to %sbe zero value\ngot: %v, %s", not, actual, msg) t.Fail() }
test.go
0.690976
0.632049
test.go
starcoder
// Package byteutil provides utilities for working with bytes using little endian binary encoding. package byteutil // MaxUint24 is the maximum value representable 3-octet uint. const MaxUint24 = 1<<24 - 1 // ParseUint32 parses uint32 from b assuming little endian binary encoding. func ParseUint32(b []byte) uint32 { switch len(b) { case 0: return 0 case 1: _ = b[0] return uint32(b[0]) case 2: _ = b[1] return uint32(b[0]) | uint32(b[1])<<8 case 3: _ = b[2] return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 default: _ = b[3] return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 } } // ParseUint64 parses uint64 from b assuming little endian binary encoding. func ParseUint64(b []byte) uint64 { switch len(b) { case 0: return 0 case 1: _ = b[0] return uint64(b[0]) case 2: _ = b[1] return uint64(b[0]) | uint64(b[1])<<8 case 3: _ = b[2] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 case 4: _ = b[3] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 case 5: _ = b[4] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 case 6: _ = b[5] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 case 7: _ = b[6] 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 default: _ = b[7] 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 } } // AppendUint16 appends v to dst using little endian binary encoding using at most byteCount bytes. func AppendUint16(dst []byte, v uint16, byteCount uint8) []byte { switch byteCount { case 0: return dst case 1: return append(dst, byte(v)) default: dst = append(dst, byte(v), byte(v>>8)) for i := uint8(2); i < byteCount; i++ { dst = append(dst, 0) } return dst } } // AppendUint32 appends v to dst using little endian binary encoding using at most byteCount bytes. func AppendUint32(dst []byte, v uint32, byteCount uint8) []byte { switch byteCount { case 0, 1, 2: return AppendUint16(dst, uint16(v), byteCount) case 3: return append(dst, byte(v), byte(v>>8), byte(v>>16)) default: dst = append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24)) for i := uint8(4); i < byteCount; i++ { dst = append(dst, 0) } return dst } } // AppendUint64 appends v to dst using little endian binary encoding using at most byteCount bytes. func AppendUint64(dst []byte, v uint64, byteCount uint8) []byte { switch byteCount { case 0, 1, 2, 3, 4: return AppendUint32(dst, uint32(v), byteCount) case 5: return append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32)) case 6: return append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40)) case 7: return append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48)) default: dst = append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48), byte(v>>56)) for i := uint8(8); i < byteCount; i++ { dst = append(dst, 0) } return dst } }
pkg/util/byteutil/byteutil.go
0.632843
0.600364
byteutil.go
starcoder
package datadog import ( "encoding/json" ) // AuditLogsQueryFilter Search and filter query settings. type AuditLogsQueryFilter struct { // Minimum time for the requested events. Supports date, math, and regular timestamps (in milliseconds). From *string `json:"from,omitempty"` // Search query following the Audit Logs search syntax. Query *string `json:"query,omitempty"` // Maximum time for the requested events. Supports date, math, and regular timestamps (in milliseconds). To *string `json:"to,omitempty"` // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct UnparsedObject map[string]interface{} `json:-` } // NewAuditLogsQueryFilter instantiates a new AuditLogsQueryFilter 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 NewAuditLogsQueryFilter() *AuditLogsQueryFilter { this := AuditLogsQueryFilter{} var from string = "now-15m" this.From = &from var query string = "*" this.Query = &query var to string = "now" this.To = &to return &this } // NewAuditLogsQueryFilterWithDefaults instantiates a new AuditLogsQueryFilter 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 NewAuditLogsQueryFilterWithDefaults() *AuditLogsQueryFilter { this := AuditLogsQueryFilter{} var from string = "now-15m" this.From = &from var query string = "*" this.Query = &query var to string = "now" this.To = &to return &this } // GetFrom returns the From field value if set, zero value otherwise. func (o *AuditLogsQueryFilter) GetFrom() string { if o == nil || o.From == nil { var ret string return ret } return *o.From } // GetFromOk returns a tuple with the From field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AuditLogsQueryFilter) GetFromOk() (*string, bool) { if o == nil || o.From == nil { return nil, false } return o.From, true } // HasFrom returns a boolean if a field has been set. func (o *AuditLogsQueryFilter) HasFrom() bool { if o != nil && o.From != nil { return true } return false } // SetFrom gets a reference to the given string and assigns it to the From field. func (o *AuditLogsQueryFilter) SetFrom(v string) { o.From = &v } // GetQuery returns the Query field value if set, zero value otherwise. func (o *AuditLogsQueryFilter) GetQuery() string { if o == nil || o.Query == nil { var ret string return ret } return *o.Query } // GetQueryOk returns a tuple with the Query field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AuditLogsQueryFilter) GetQueryOk() (*string, bool) { if o == nil || o.Query == nil { return nil, false } return o.Query, true } // HasQuery returns a boolean if a field has been set. func (o *AuditLogsQueryFilter) HasQuery() bool { if o != nil && o.Query != nil { return true } return false } // SetQuery gets a reference to the given string and assigns it to the Query field. func (o *AuditLogsQueryFilter) SetQuery(v string) { o.Query = &v } // GetTo returns the To field value if set, zero value otherwise. func (o *AuditLogsQueryFilter) GetTo() string { if o == nil || o.To == nil { var ret string return ret } return *o.To } // GetToOk returns a tuple with the To field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AuditLogsQueryFilter) GetToOk() (*string, bool) { if o == nil || o.To == nil { return nil, false } return o.To, true } // HasTo returns a boolean if a field has been set. func (o *AuditLogsQueryFilter) HasTo() bool { if o != nil && o.To != nil { return true } return false } // SetTo gets a reference to the given string and assigns it to the To field. func (o *AuditLogsQueryFilter) SetTo(v string) { o.To = &v } func (o AuditLogsQueryFilter) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.UnparsedObject != nil { return json.Marshal(o.UnparsedObject) } if o.From != nil { toSerialize["from"] = o.From } if o.Query != nil { toSerialize["query"] = o.Query } if o.To != nil { toSerialize["to"] = o.To } return json.Marshal(toSerialize) } func (o *AuditLogsQueryFilter) UnmarshalJSON(bytes []byte) (err error) { raw := map[string]interface{}{} all := struct { From *string `json:"from,omitempty"` Query *string `json:"query,omitempty"` To *string `json:"to,omitempty"` }{} err = json.Unmarshal(bytes, &all) if err != nil { err = json.Unmarshal(bytes, &raw) if err != nil { return err } o.UnparsedObject = raw return nil } o.From = all.From o.Query = all.Query o.To = all.To return nil }
api/v2/datadog/model_audit_logs_query_filter.go
0.770724
0.40928
model_audit_logs_query_filter.go
starcoder
package hbook // Bin2D models a bin in a 2-dim space. type Bin2D struct { xrange Range yrange Range dist dist2D } // Rank returns the number of dimensions for this bin. func (Bin2D) Rank() int { return 2 } func (b *Bin2D) scaleW(f float64) { b.dist.scaleW(f) } func (b *Bin2D) fill(x, y, w float64) { b.dist.fill(x, y, w) } // Entries returns the number of entries in this bin. func (b *Bin2D) Entries() int64 { return b.dist.Entries() } // EffEntries returns the effective number of entries \f$ = (\sum w)^2 / \sum w^2 \f$ func (b *Bin2D) EffEntries() float64 { return b.dist.EffEntries() } // SumW returns the sum of weights in this bin. func (b *Bin2D) SumW() float64 { return b.dist.SumW() } // SumW2 returns the sum of squared weights in this bin. func (b *Bin2D) SumW2() float64 { return b.dist.SumW2() } // XEdges returns the [low,high] edges of this bin. func (b *Bin2D) XEdges() Range { return b.xrange } // YEdges returns the [low,high] edges of this bin. func (b *Bin2D) YEdges() Range { return b.yrange } // XMin returns the lower limit of the bin (inclusive). func (b *Bin2D) XMin() float64 { return b.xrange.Min } // YMin returns the lower limit of the bin (inclusive). func (b *Bin2D) YMin() float64 { return b.yrange.Min } // XMax returns the upper limit of the bin (exclusive). func (b *Bin2D) XMax() float64 { return b.xrange.Max } // YMax returns the upper limit of the bin (exclusive). func (b *Bin2D) YMax() float64 { return b.yrange.Max } // XMid returns the geometric center of the bin. // i.e.: 0.5*(high+low) func (b *Bin2D) XMid() float64 { return 0.5 * (b.xrange.Min + b.xrange.Max) } // YMid returns the geometric center of the bin. // i.e.: 0.5*(high+low) func (b *Bin2D) YMid() float64 { return 0.5 * (b.yrange.Min + b.yrange.Max) } // XYMid returns the (x,y) coordinates of the geometric center of the bin. // i.e.: 0.5*(high+low) func (b *Bin2D) XYMid() (float64, float64) { return b.XMid(), b.YMid() } // XWidth returns the (signed) width of the bin func (b *Bin2D) XWidth() float64 { return b.xrange.Max - b.xrange.Min } // YWidth returns the (signed) width of the bin func (b *Bin2D) YWidth() float64 { return b.yrange.Max - b.yrange.Min } // XYWidth returns the (signed) (x,y) widths of the bin func (b *Bin2D) XYWidth() (float64, float64) { return b.XWidth(), b.YWidth() } // XFocus returns the mean position in the bin, or the midpoint (if the // sum of weights for this bin is 0). func (b *Bin2D) XFocus() float64 { if b.SumW() == 0 { return b.XMid() } return b.XMean() } // YFocus returns the mean position in the bin, or the midpoint (if the // sum of weights for this bin is 0). func (b *Bin2D) YFocus() float64 { if b.SumW() == 0 { return b.YMid() } return b.YMean() } // XYFocus returns the mean position in the bin, or the midpoint (if the // sum of weights for this bin is 0). func (b *Bin2D) XYFocus() (float64, float64) { if b.SumW() == 0 { return b.XMid(), b.YMid() } return b.XMean(), b.YMean() } // XMean returns the mean X. func (b *Bin2D) XMean() float64 { return b.dist.xMean() } // YMean returns the mean Y. func (b *Bin2D) YMean() float64 { return b.dist.yMean() } // XVariance returns the variance in X. func (b *Bin2D) XVariance() float64 { return b.dist.xVariance() } // YVariance returns the variance in Y. func (b *Bin2D) YVariance() float64 { return b.dist.yVariance() } // XStdDev returns the standard deviation in X. func (b *Bin2D) XStdDev() float64 { return b.dist.xStdDev() } // YStdDev returns the standard deviation in Y. func (b *Bin2D) YStdDev() float64 { return b.dist.yStdDev() } // XStdErr returns the standard error in X. func (b *Bin2D) XStdErr() float64 { return b.dist.xStdErr() } // YStdErr returns the standard error in Y. func (b *Bin2D) YStdErr() float64 { return b.dist.yStdErr() } // XRMS returns the RMS in X. func (b *Bin2D) XRMS() float64 { return b.dist.xRMS() } // YRMS returns the RMS in Y. func (b *Bin2D) YRMS() float64 { return b.dist.yRMS() } // check Bin2D implements interfaces var _ Bin = (*Bin2D)(nil)
hbook/bin2d.go
0.947745
0.806129
bin2d.go
starcoder
package helpers // github.com/openshift-online/ocm-sdk-go/helpers import ( "context" "fmt" "net/http" "net/url" "strings" "time" ) // AddValue creates the given set of query parameters if needed, an then adds // the given parameter. func AddValue(query *url.Values, name string, value interface{}) { if *query == nil { *query = make(url.Values) } query.Add(name, fmt.Sprintf("%v", value)) } // CopyQuery creates a copy of the given set of query parameters. func CopyQuery(query url.Values) url.Values { if query == nil { return nil } result := make(url.Values) for name, values := range query { result[name] = CopyValues(values) } return result } // AddHeader creates the given set of headers if needed, and then adds the given // header: func AddHeader(header *http.Header, name string, value interface{}) { if *header == nil { *header = make(http.Header) } header.Add(name, fmt.Sprintf("%v", value)) } // SetHeader creates a copy of the given set of headers, and adds the header // containing the given metrics path. func SetHeader(header http.Header, metric string) http.Header { result := make(http.Header) for name, values := range header { result[name] = CopyValues(values) } result.Set(metricHeader, metric) return result } // CopyValues copies a slice of strings. func CopyValues(values []string) []string { if values == nil { return nil } result := make([]string, len(values)) copy(result, values) return result } // Segments calculates the path segments for the given path. func Segments(path string) []string { for strings.HasPrefix(path, "/") { path = path[1:] } for strings.HasSuffix(path, "/") { path = path[0 : len(path)-1] } return strings.Split(path, "/") } // PollContext repeatedly executes a task till it returns one of the given statuses and till the result // satisfies all the given predicates. func PollContext( ctx context.Context, interval time.Duration, statuses []int, predicates []func(interface{}) bool, task func(context.Context) (int, interface{}, error), ) (result interface{}, err error) { // Check the deadline: deadline, ok := ctx.Deadline() if !ok { err = fmt.Errorf("context deadline is mandatory") return } // Check the interval: if interval <= 0 { err = fmt.Errorf("interval must be greater than zero") return } // Create a cancellable context so that we can explicitly cancel it when we know that the next // iteration of the loop will be after the deadline: ctx, cancel := context.WithCancel(ctx) // If no expected status has been explicitly specified then add the default: if len(statuses) == 0 { statuses = []int{http.StatusOK} } for { // Execute the task. If this produces an error and the status code is zero it means that // there was an error like a timeout, or a low level communications problem. In that // case we want to immediately stop waiting. var status int status, result, err = task(ctx) if err != nil && status == 0 { break } // Evaluate the status and the predicates: statusOK := evalStatus(statuses, status) predicatesOK := evalPredicates(predicates, result) if statusOK && predicatesOK { break } // If either the status or the predicates aren't acceptable then we need to check if we // have enough time for another iteration before the deadline: if time.Now().Add(interval).After(deadline) { cancel() break } time.Sleep(interval) } return } // evalStatus checks if the actual status is one of the expected ones. func evalStatus(expected []int, actual int) bool { for _, current := range expected { if actual == current { return true } } return false } // evalPredicates checks if the object satisfies all the predicates. func evalPredicates(predicates []func(interface{}) bool, object interface{}) bool { if len(predicates) > 0 && object == nil { return false } for _, predicate := range predicates { if !predicate(object) { return false } } return true } // Name of the header used to contain the metrics path: const metricHeader = "X-Metric"
vendor/github.com/openshift-online/ocm-sdk-go/helpers/helpers.go
0.680029
0.402333
helpers.go
starcoder
package particle import ( "math" "math/rand" "time" gaussian "github.com/chobie/go-gaussian" ) type ParticleFilter struct { N int // Number of particles to sample Dimensions int // Number of dimensions to record Particles []Particle // Slice of particles sampled resampler Resampler // Function to resample more accurate particles } type Particle struct { Weight float64 // Measure of how accurate we think this particle is Dimensions []float64 // Slice of values, indexes correspond to the dimensions of our state space } func init() { rand.Seed(time.Now().Unix()) } func New(particleCount int, initialGuess [][]float64, resampler Resampler) *ParticleFilter { //Initialize to 1/N weight := 1.0 / float64(particleCount) //Initialize Particles particles := make([]Particle, particleCount) for x := 0; x < len(particles); x++ { dims := make([]float64, len(initialGuess)) for idx, dim := range initialGuess { dims[idx] = (rand.NormFloat64() * dim[1]) + dim[0] } particles[x] = Particle{ Weight: weight, Dimensions: dims, } } return &ParticleFilter{ N: particleCount, Dimensions: len(initialGuess), Particles: particles, resampler: resampler, } } // Predict the next movement of the object we're tracking // u is the process model, and it contains the predicted dimensional advancment // std expresses the uncertainty in the process model prediction by dimension func (p *ParticleFilter) Predict(u, std []float64) { if len(u) != len(std) { return //TODO:: Return Error } //Advance each particle for _, particle := range p.Particles { for idx := range u { particle.Dimensions[idx] += (rand.NormFloat64()*std[idx] + u[idx]) } } } func (p *ParticleFilter) Update(measurements, variances []float64) { totalWeight := 0.0 //Build Gaussians from variances g := []*gaussian.Gaussian{} for _, val := range variances { g = append(g, gaussian.NewGaussian(0.0, math.Sqrt(val))) } //Reweight for idx, particle := range p.Particles { for midx, m := range measurements { distance := particle.Dimensions[midx] - m p.Particles[idx].Weight += math.Max(g[midx].Pdf(distance), 1e-12) } totalWeight += p.Particles[idx].Weight } //Normalize for idx := range p.Particles { p.Particles[idx].Weight /= totalWeight } } func (p *ParticleFilter) Resample() { if p.performResample() { p.Particles = p.resampler(p.Particles) } } func (p *ParticleFilter) performResample() bool { //TODO:: add other thresholding funcs sumOfSquares := 0.0 for _, particle := range p.Particles { sumOfSquares += math.Pow(particle.Weight, 2) } return (1.0 / sumOfSquares) > (float64(len(p.Particles)) / 2.0) } func (p *ParticleFilter) Estimate() ([]float64, []float64) { avg := make([]float64, p.Dimensions) variance := make([]float64, p.Dimensions) for _, particle := range p.Particles { for idx, val := range particle.Dimensions { avg[idx] += (val * particle.Weight) } } for _, particle := range p.Particles { for idx, val := range particle.Dimensions { variance[idx] += (math.Pow(val-avg[idx], 2) * particle.Weight) } } return avg, variance }
particle/filter.go
0.649801
0.646962
filter.go
starcoder
package graphics2d import ( "github.com/jphsd/graphics2d/util" "math" ) // RoundedProc replaces adjacent line segments in a path with line-arc-line where the radius of the // arc is the minimum of Radius or the maximum allowable for the length of the shorter line segment. // This ensures that the rounded corner doesn't end beyond the mid point of either line. type RoundedProc struct { Radius float64 } // Process implements the PathProcessor interface. func (rp *RoundedProc) Process(p *Path) []*Path { parts := p.Parts() np := len(parts) if np < 2 { return []*Path{p} } res := [][][]float64{} for i, part := range parts { if len(part) != 2 { res = append(res, part) continue } if i < np-1 { if len(parts[i+1]) == 2 { nparts := rp.calcPieces(part[0], part[1], parts[i+1][1]) res = append(res, [][]float64{part[0], nparts[0][0]}) res = append(res, nparts...) } else { res = append(res, part) } } else { if !p.Closed() || len(parts[0]) != 2 { res = append(res, part) continue } // Path is closed and the first part is also a line nparts := rp.calcPieces(part[0], part[1], parts[0][1]) res = append(res, [][]float64{part[0], nparts[0][0]}) res = append(res, nparts...) lnp := len(nparts) - 1 res[0][0] = nparts[lnp][len(nparts[lnp])-1] } } return []*Path{PartsToPath(res...)} } // Return p1-p2, p2-p3 intercepts and c, and final r and theta func (rp *RoundedProc) calcPieces(p1, p2, p3 []float64) [][][]float64 { theta := util.AngleBetweenLines(p1, p2, p3, p2) neg := theta < 0 if neg { theta = -theta } t2 := theta / 2 tt2 := math.Tan(t2) // Check r is < min(p12, p23) / 2 v1, v2 := util.Vec(p1, p2), util.Vec(p2, p3) d1, d2 := util.VecMag(v1), util.VecMag(v2) m1, m2 := d1/2, d2/2 md := m1 if m2 < m1 { md = m2 } r := tt2 * md if r > rp.Radius { r = rp.Radius } // Find intersection of arc with p1-p2 u1 := []float64{v1[0] / d1, v1[1] / d1} s := r / tt2 i12 := []float64{p2[0] - s*u1[0], p2[1] - s*u1[1]} // Calc center c := []float64{i12[0], i12[1]} theta = math.Pi - theta n1 := []float64{u1[1], -u1[0]} if neg { n1[0], n1[1] = -n1[0], -n1[1] } else { theta = -theta } c = []float64{c[0] + r*n1[0], c[1] + r*n1[1]} // Calc offset a12 := math.Atan2(-n1[1], -n1[0]) return MakeArcParts(c[0], c[1], r, a12, theta) }
roundedproc.go
0.708414
0.45538
roundedproc.go
starcoder
package check import ( "fmt" "regexp" ) // String is the type of a check function for a string. It takes a string as // a parameter and returns an error or nil if the check passes type String func(s string) error // StringLenEQ returns a function that will check that the // length of the string is equal to the limit func StringLenEQ(limit int) String { return func(s string) error { if len(s) == limit { return nil } return fmt.Errorf("the length of the value (%d) must equal %d", len(s), limit) } } // StringLenLT returns a function that will check that the // length of the string is less than the limit func StringLenLT(limit int) String { return func(s string) error { if len(s) < limit { return nil } return fmt.Errorf( "the length of the value (%d) must be less than %d", len(s), limit) } } // StringLenGT returns a function that will check that the // length of the string is less than the limit func StringLenGT(limit int) String { return func(s string) error { if len(s) > limit { return nil } return fmt.Errorf( "the length of the value (%d) must be greater than %d", len(s), limit) } } // StringLenBetween returns a function that will check that the // length of the string is between the two limits (inclusive) func StringLenBetween(low, high int) String { if low >= high { panic(fmt.Sprintf("Impossible checks passed to StringLenBetween:"+ " the lower limit (%d) should be less than the upper limit (%d)", low, high)) } return func(s string) error { if len(s) < low { return fmt.Errorf( "the length of the value (%d) must be between %d and %d"+ " - too short", len(s), low, high) } if len(s) > high { return fmt.Errorf( "the length of the value (%d) must be between %d and %d"+ " - too long", len(s), low, high) } return nil } } // StringMatchesPattern returns a function that checks that the // string matches the supplied regexp func StringMatchesPattern(re *regexp.Regexp, reDesc string) String { return func(v string) error { if !re.MatchString(v) { return fmt.Errorf("%s does not match the pattern: %s", v, reDesc) } return nil } } // StringOr returns a function that will check that the value, when // passed to each of the check funcs in turn, passes at least one of them func StringOr(chkFuncs ...String) String { return func(s string) error { compositeErr := "" sep := "(" for _, cf := range chkFuncs { err := cf(s) if err == nil { return nil } compositeErr += sep + err.Error() sep = " OR " } return fmt.Errorf("%s)", compositeErr) } } // StringAnd returns a function that will check that the value, when // passed to each of the check funcs in turn, passes all of them func StringAnd(chkFuncs ...String) String { return func(s string) error { for _, cf := range chkFuncs { err := cf(s) if err != nil { return err } } return nil } }
check/string.go
0.675015
0.586434
string.go
starcoder
package funk import ( "fmt" "math/rand" "reflect" ) // Chunk creates an array of elements split into groups with the length of size. // If array can't be split evenly, the final chunk will be // the remaining element. func Chunk(arr interface{}, size int) interface{} { if !IsIteratee(arr) { panic("First parameter must be neither array nor slice") } arrValue := reflect.ValueOf(arr) arrType := arrValue.Type() resultSliceType := reflect.SliceOf(arrType) // Initialize final result slice which will contains slice resultSlice := reflect.MakeSlice(resultSliceType, 0, 0) itemType := arrType.Elem() var itemSlice reflect.Value itemSliceType := reflect.SliceOf(itemType) length := arrValue.Len() for i := 0; i < length; i++ { if i%size == 0 || i == 0 { if itemSlice.Kind() != reflect.Invalid { resultSlice = reflect.Append(resultSlice, itemSlice) } itemSlice = reflect.MakeSlice(itemSliceType, 0, 0) } itemSlice = reflect.Append(itemSlice, arrValue.Index(i)) if i == length-1 { resultSlice = reflect.Append(resultSlice, itemSlice) } } return resultSlice.Interface() } // ToMap transforms a slice of instances to a Map. // []*Foo => Map<int, *Foo> func ToMap(in interface{}, pivot string) interface{} { value := reflect.ValueOf(in) // input value must be a slice if value.Kind() != reflect.Slice { panic(fmt.Sprintf("%v must be a slice", in)) } inType := value.Type() structType := inType.Elem() // retrieve the struct in the slice to deduce key type if structType.Kind() == reflect.Ptr { structType = structType.Elem() } field, _ := structType.FieldByName(pivot) // value of the map will be the input type collectionType := reflect.MapOf(field.Type, inType.Elem()) // create a map from scratch collection := reflect.MakeMap(collectionType) for i := 0; i < value.Len(); i++ { instance := value.Index(i) var field reflect.Value if instance.Kind() == reflect.Ptr { field = instance.Elem().FieldByName(pivot) } else { field = instance.FieldByName(pivot) } collection.SetMapIndex(field, instance) } return collection.Interface() } func mapSlice(arrValue reflect.Value, funcValue reflect.Value) interface{} { funcType := funcValue.Type() if funcType.NumIn() != 1 || funcType.NumOut() == 0 || funcType.NumOut() > 2 { panic("Map function with an array must have one parameter and must return one or two parameters") } arrElemType := arrValue.Type().Elem() // Checking whether element type is convertible to function's first argument's type. if !arrElemType.ConvertibleTo(funcType.In(0)) { panic("Map function's argument is not compatible with type of array.") } if funcType.NumOut() == 1 { // Get slice type corresponding to function's return value's type. resultSliceType := reflect.SliceOf(funcType.Out(0)) // MakeSlice takes a slice kind type, and makes a slice. resultSlice := reflect.MakeSlice(resultSliceType, 0, 0) for i := 0; i < arrValue.Len(); i++ { result := funcValue.Call([]reflect.Value{arrValue.Index(i)})[0] resultSlice = reflect.Append(resultSlice, result) } return resultSlice.Interface() } if funcType.NumOut() == 2 { // value of the map will be the input type collectionType := reflect.MapOf(funcType.Out(0), funcType.Out(1)) // create a map from scratch collection := reflect.MakeMap(collectionType) for i := 0; i < arrValue.Len(); i++ { results := funcValue.Call([]reflect.Value{arrValue.Index(i)}) collection.SetMapIndex(results[0], results[1]) } return collection.Interface() } return nil } func mapMap(arrValue reflect.Value, funcValue reflect.Value) interface{} { funcType := funcValue.Type() if funcType.NumIn() != 2 || funcType.NumOut() == 0 || funcType.NumOut() > 2 { panic("Map function with an map must have one parameter and must return one or two parameters") } // Only one returned parameter, should be a slice if funcType.NumOut() == 1 { // Get slice type corresponding to function's return value's type. resultSliceType := reflect.SliceOf(funcType.Out(0)) // MakeSlice takes a slice kind type, and makes a slice. resultSlice := reflect.MakeSlice(resultSliceType, 0, 0) for _, key := range arrValue.MapKeys() { results := funcValue.Call([]reflect.Value{key, arrValue.MapIndex(key)}) result := results[0] resultSlice = reflect.Append(resultSlice, result) } return resultSlice.Interface() } // two parameters, should be a map if funcType.NumOut() == 2 { // value of the map will be the input type collectionType := reflect.MapOf(funcType.Out(0), funcType.Out(1)) // create a map from scratch collection := reflect.MakeMap(collectionType) for _, key := range arrValue.MapKeys() { results := funcValue.Call([]reflect.Value{key, arrValue.MapIndex(key)}) collection.SetMapIndex(results[0], results[1]) } return collection.Interface() } return nil } // Map manipulates an iteratee and transforms it to another type. func Map(arr interface{}, mapFunc interface{}) interface{} { if !IsIteratee(arr) { panic("First parameter must be an iteratee") } if !IsFunction(mapFunc) { panic("Second argument must be function") } var ( funcValue = reflect.ValueOf(mapFunc) arrValue = reflect.ValueOf(arr) arrType = arrValue.Type() ) kind := arrType.Kind() if kind == reflect.Slice || kind == reflect.Array { return mapSlice(arrValue, funcValue) } if kind == reflect.Map { return mapMap(arrValue, funcValue) } panic(fmt.Sprintf("Type %s is not supported by Map", arrType.String())) } // FlattenDeep recursively flattens array. func FlattenDeep(out interface{}) interface{} { return flattenDeep(reflect.ValueOf(out)).Interface() } func flattenDeep(value reflect.Value) reflect.Value { sliceType := sliceElem(value.Type()) resultSlice := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, 0) return flatten(value, resultSlice) } func flatten(value reflect.Value, result reflect.Value) reflect.Value { length := value.Len() for i := 0; i < length; i++ { item := value.Index(i) kind := item.Kind() if kind == reflect.Slice || kind == reflect.Array { result = flatten(item, result) } else { result = reflect.Append(result, item) } } return result } // Shuffle creates an array of shuffled values func Shuffle(in interface{}) interface{} { value := reflect.ValueOf(in) valueType := value.Type() kind := value.Kind() if kind == reflect.Array || kind == reflect.Slice { length := value.Len() resultSlice := makeSlice(value, length) for i, v := range rand.Perm(length) { resultSlice.Index(i).Set(value.Index(v)) } return resultSlice.Interface() } panic(fmt.Sprintf("Type %s is not supported by Shuffle", valueType.String())) } // Reverse transforms an array the first element will become the last, // the second element will become the second to last, etc. func Reverse(in interface{}) interface{} { value := reflect.ValueOf(in) valueType := value.Type() kind := value.Kind() if kind == reflect.String { return ReverseString(in.(string)) } if kind == reflect.Array || kind == reflect.Slice { length := value.Len() resultSlice := makeSlice(value, length) j := 0 for i := length - 1; i >= 0; i-- { resultSlice.Index(j).Set(value.Index(i)) j++ } return resultSlice.Interface() } panic(fmt.Sprintf("Type %s is not supported by Reverse", valueType.String())) } // Uniq creates an array with unique values. func Uniq(in interface{}) interface{} { value := reflect.ValueOf(in) valueType := value.Type() kind := value.Kind() if kind == reflect.Array || kind == reflect.Slice { length := value.Len() seen := make(map[interface{}]bool, length) j := 0 for i := 0; i < length; i++ { val := value.Index(i) v := val.Interface() if _, ok := seen[v]; ok { continue } seen[v] = true value.Index(j).Set(val) j++ } return value.Slice(0, j).Interface() } panic(fmt.Sprintf("Type %s is not supported by Uniq", valueType.String())) } // ConvertSlice converts a slice type to another, // a perfect example would be to convert a slice of struct to a slice of interface. func ConvertSlice(in interface{}, out interface{}) { srcValue := reflect.ValueOf(in) dstValue := reflect.ValueOf(out) if dstValue.Kind() != reflect.Ptr { panic("Second argument must be a pointer") } dstValue = dstValue.Elem() if srcValue.Kind() != reflect.Slice && srcValue.Kind() != reflect.Array { panic("First argument must be an array or slice") } if dstValue.Kind() != reflect.Slice && dstValue.Kind() != reflect.Array { panic("Second argument must be an array or slice") } // returns value that points to dstValue direct := reflect.Indirect(dstValue) length := srcValue.Len() for i := 0; i < length; i++ { dstValue = reflect.Append(dstValue, srcValue.Index(i)) } direct.Set(dstValue) } // Drop creates an array/slice with `n` elements dropped from the beginning. func Drop(in interface{}, n int) interface{} { value := reflect.ValueOf(in) valueType := value.Type() kind := value.Kind() if kind == reflect.Array || kind == reflect.Slice { length := value.Len() resultSlice := makeSlice(value, length-n) j := 0 for i := n; i < length; i++ { resultSlice.Index(j).Set(value.Index(i)) j++ } return resultSlice.Interface() } panic(fmt.Sprintf("Type %s is not supported by Drop", valueType.String())) }
vendor/github.com/thoas/go-funk/transform.go
0.705785
0.512022
transform.go
starcoder
package geom //Polygon对象 多变形对象是一个LinearRing(线环)的集合。第一个LinearRing作为外边界, //随后的LinearRing对象作为内边界 type Polygon struct { geom2 } // NewPolygon函数 创建一个空的多边形 func NewPolygon(layout Layout) *Polygon { return NewPolygonFlat(layout, nil, nil) } // NewPolygonFlat函数 根据传入的坐标和视图类型创建多边形 func NewPolygonFlat(layout Layout, flatCoords []float64, ends []int) *Polygon { p := new(Polygon) p.layout = layout p.stride = layout.Stride() p.flatCoords = flatCoords p.ends = ends return p } /** *------------------------------ * Polygon(多边形)相关的方法 *--------------------------------- */ // Area方法 返回多边形的面积 func (p *Polygon) Area() float64 { return doubleArea2(p.flatCoords, 0, p.ends, p.stride) / 2 } // Clone方法 深层拷贝多边形 func (p *Polygon) Clone() *Polygon { return deriveClonePolygon(p) } // Empty方法 返回False func (p *Polygon) Empty() bool { return false } // Length方法 返回周长 func (p *Polygon) Length() float64 { return length2(p.flatCoords, 0, p.ends, p.stride) } // LinearRing方法 获取指定索引的线环 func (p *Polygon) LinearRing(i int) *LinearRing { offset := 0 if i > 0 { offset = p.ends[i-1] } return NewLinearRingFlat(p.layout, p.flatCoords[offset:p.ends[i]]) } // MustSetCoords方法 设置坐标,任何错误都将抛出 func (p *Polygon) MustSetCoords(coords [][]Coord) *Polygon { Must(p.SetCoords(coords)) return p } // NumLinearRings方法 返回LinearRing的数目 func (p *Polygon) NumLinearRings() int { return len(p.ends) } // Push方法 向多边形中添加LinearRing func (p *Polygon) Push(lr *LinearRing) error { if lr.layout != p.layout { return ErrLayoutMismatch{Got: lr.layout, Want: p.layout} } p.flatCoords = append(p.flatCoords, lr.flatCoords...) p.ends = append(p.ends, len(p.flatCoords)) return nil } // SetCoords方法 设置坐标 func (p *Polygon) SetCoords(coords [][]Coord) (*Polygon, error) { if err := p.setCoords(coords); err != nil { return nil, err } return p, nil } // SetSRID方法 设置多变形的坐标系参考 func (p *Polygon) SetSRID(srid int) *Polygon { p.srid = srid return p } // Swap方法 将本对象与传入的多边形对象互相交换 func (p *Polygon) Swap(p2 *Polygon) { *p, *p2 = *p2, *p }
polygon.go
0.538255
0.60778
polygon.go
starcoder
package volume import ( "fmt" "io" "github.com/sirupsen/logrus" "github.com/vatine/3dmandel/pkg/coords" ) type Volume interface { Set(coords.Coord) Render(io.Writer) IsFull() bool IsEmpty() bool mini() coords.Coord } type empty struct { min coords.Coord side float64 } func (e empty) Set(c coords.Coord) { logrus.Error("Unexpect set on empty.") } func (e empty) Render(w io.Writer) { } func (e empty) IsEmpty() bool { return true } func (e empty) IsFull() bool { return false } func (e empty) mini() coords.Coord { return e.min } func (e empty) String() string { return fmt.Sprintf("empty{%s, %f}", e.min, e.side) } type full struct { min coords.Coord side float64 } func (f full) Set(c coords.Coord) { } func (f full) Render(w io.Writer) { fmt.Fprintf(w, "translate(v = [ %f, %f, %f ]) { cube(size = %f, center=true); }\n", f.min[0], f.min[1], f.min[2], f.side) } func (f full) IsEmpty() bool { return false } func (f full) IsFull() bool { return true } func (f full) mini() coords.Coord { return f.min } func (e full) String() string { return fmt.Sprintf("full{%s, %f}", e.min, e.side) } type partial struct { min coords.Coord side float64 subs [2][2][2]Volume step float64 } func (p partial) mini() coords.Coord { return p.min } func computeSide(side, step float64) float64 { for step < side { step = 2.0 * step } return step } func New(min coords.Coord, side, step float64) Volume { rv := partial{min: min, step: step} rv.side = computeSide(side, step) half := rv.side / 2.0 for x := 0; x < 2; x++ { for y := 0; y < 2; y++ { for z := 0; z < 2; z++ { delta := coords.Coord{float64(x) * half, float64(y) * half, float64(z) * half} rv.subs[x][y][z] = empty{min: min.Add(delta), side: half} } } } return &rv } func (v partial) findSub(c coords.Coord) (int, int, int) { x, y, z := 0, 0, 0 half := v.side / 2.0 if (c[0] >= v.min[0] + half) { x++ } if (c[1] >= v.min[1] + half) { y++ } if (c[2] >= v.min[2] + half) { z++ } return x, y, z } func subPartial(min coords.Coord, side, step float64) *partial { rv := partial{min: min, step: step, side: side} half := rv.side / 2.0 for x := 0; x < 2; x++ { for y := 0; y < 2; y++ { for z := 0; z < 2; z++ { delta := coords.Coord{float64(x) * half, float64(y) * half, float64(z) * half} rv.subs[x][y][z] = empty{min: min.Add(delta), side: half} } } } return &rv } func (v *partial) Set(c coords.Coord) { x, y, z := v.findSub(c) half := v.side / 2.0 logrus.WithFields(logrus.Fields{ "c": c, "x": x, "y": y, "z": z, "half": half, "min": v.min, "side": v.side, }).Debug("partial.Set") switch { case half <= v.step: v.subs[x][y][z] = full{min: v.subs[x][y][z].mini(), side: half} case v.subs[x][y][z].IsEmpty(): v.subs[x][y][z] = subPartial(v.subs[x][y][z].mini(), half, v.step) v.subs[x][y][z].Set(c) case v.subs[x][y][z].IsFull(): return default: v.subs[x][y][z].Set(c) if v.subs[x][y][z].IsFull() { v.subs[x][y][z] = full{v.subs[x][y][z].mini(), half} } } } func (v partial) IsEmpty() bool { for x := 0; x < 2; x++ { for y := 0; y < 2; y++ { for z := 0; z < 2; z++ { if !v.subs[x][y][z].IsEmpty() { return false } } } } return true } func (v partial) IsFull() bool { for x := 0; x < 2; x++ { for y := 0; y < 2; y++ { for z := 0; z < 2; z++ { if !v.subs[x][y][z].IsFull() { return false } } } } return true } func (v partial) Render(w io.Writer) { for x := 0; x < 2; x++ { for y := 0; y < 2; y++ { for z := 0; z < 2; z++ { v.subs[x][y][z].Render(w) } } } }
pkg/volume/volume.go
0.667473
0.404919
volume.go
starcoder
package gopdf // Margins type. type Margins struct { Left, Top, Right, Bottom float64 } // SetLeftMargin sets left margin. func (gp *GoPdf2) SetLeftMargin(margin float64) { gp.UnitsToPointsVar(&margin) gp.margins.Left = margin } // SetTopMargin sets top margin. func (gp *GoPdf2) SetTopMargin(margin float64) { gp.UnitsToPointsVar(&margin) gp.margins.Top = margin } // SetMargins defines the left, top, right and bottom margins. By default, they equal 1 cm. Call this method to change them. func (gp *GoPdf2) SetMargins(left, top, right, bottom float64) { gp.UnitsToPointsVar(&left, &top, &right, &bottom) gp.margins = Margins{left, top, right, bottom} } // SetMarginLeft sets the left margin func (gp *GoPdf2) SetMarginLeft(margin float64) { gp.margins.Left = gp.UnitsToPoints(margin) } // SetMarginTop sets the top margin func (gp *GoPdf2) SetMarginTop(margin float64) { gp.margins.Top = gp.UnitsToPoints(margin) } // SetMarginRight sets the right margin func (gp *GoPdf2) SetMarginRight(margin float64) { gp.margins.Right = gp.UnitsToPoints(margin) } // SetMarginBottom set the bottom margin func (gp *GoPdf2) SetMarginBottom(margin float64) { gp.margins.Bottom = gp.UnitsToPoints(margin) } // Margins gets the current margins, The margins will be converted back to the documents units. Returned values will be in the following order Left, Top, Right, Bottom func (gp *GoPdf2) Margins() (float64, float64, float64, float64) { return gp.PointsToUnits(gp.margins.Left), gp.PointsToUnits(gp.margins.Top), gp.PointsToUnits(gp.margins.Right), gp.PointsToUnits(gp.margins.Bottom) } // MarginLeft returns the left margin. func (gp *GoPdf2) MarginLeft() float64 { return gp.PointsToUnits(gp.margins.Left) } // MarginTop returns the top margin. func (gp *GoPdf2) MarginTop() float64 { return gp.PointsToUnits(gp.margins.Top) } // MarginRight returns the right margin. func (gp *GoPdf2) MarginRight() float64 { return gp.PointsToUnits(gp.margins.Right) } // MarginBottom returns the bottom margin. func (gp *GoPdf2) MarginBottom() float64 { return gp.PointsToUnits(gp.margins.Bottom) }
margin.go
0.891179
0.458531
margin.go
starcoder
package es_mx import "github.com/rannoch/cldr" var calendar = cldr.Calendar{ Formats: cldr.CalendarFormats{ Date: cldr.CalendarDateFormat{Full: "EEEE, d 'de' MMMM 'de' y", Long: "d 'de' MMMM 'de' y", Medium: "d MMM y", Short: "d/M/yy"}, Time: cldr.CalendarDateFormat{Full: "H:mm:ss (zzzz)", Long: "H:mm:ss z", Medium: "H:mm:ss", Short: "H:mm"}, DateTime: cldr.CalendarDateFormat{Full: "{1}, {0}", Long: "{1}, {0}", Medium: "{1} {0}", Short: "{1} {0}"}, }, FormatNames: cldr.CalendarFormatNames{ Months: cldr.CalendarMonthFormatNames{ Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "Ene.", Feb: "Feb.", Mar: "Mar.", Apr: "Abr.", May: "May.", Jun: "Jun.", Jul: "Jul.", Aug: "Ago.", Sep: "Sept.", Oct: "Oct.", Nov: "Nov.", Dec: "Dic."}, Narrow: cldr.CalendarMonthFormatNameValue{Jan: "E", Feb: "F", Mar: "M", Apr: "A", May: "M", Jun: "J", Jul: "J", Aug: "A", Sep: "S", Oct: "O", Nov: "N", Dec: "D"}, Short: cldr.CalendarMonthFormatNameValue{}, Wide: cldr.CalendarMonthFormatNameValue{Jan: "Enero", Feb: "Febrero", Mar: "Marzo", Apr: "Abril", May: "Mayo", Jun: "Junio", Jul: "Julio", Aug: "Agosto", Sep: "Septiembre", Oct: "Octubre", Nov: "Noviembre", Dec: "Diciembre"}, }, Days: cldr.CalendarDayFormatNames{ Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "Dom.", Mon: "Lun.", Tue: "Mar.", Wed: "Mié.", Thu: "Jue.", Fri: "Vie.", Sat: "Sáb."}, Narrow: cldr.CalendarDayFormatNameValue{Sun: "D", Mon: "L", Tue: "M", Wed: "X", Thu: "J", Fri: "V", Sat: "S"}, Short: cldr.CalendarDayFormatNameValue{Sun: "DO", Mon: "LU", Tue: "MA", Wed: "MI", Thu: "JU", Fri: "VI", Sat: "SA"}, Wide: cldr.CalendarDayFormatNameValue{Sun: "Domingo", Mon: "Lunes", Tue: "Martes", Wed: "Miércoles", Thu: "Jueves", Fri: "Viernes", Sat: "Sábado"}, }, Periods: cldr.CalendarPeriodFormatNames{ Abbreviated: cldr.CalendarPeriodFormatNameValue{}, Narrow: cldr.CalendarPeriodFormatNameValue{AM: "a.m.", PM: "p.m."}, Short: cldr.CalendarPeriodFormatNameValue{}, Wide: cldr.CalendarPeriodFormatNameValue{AM: "a. m.", PM: "p. m."}, }, }, }
resources/locales/es_MX/calendar.go
0.54698
0.401336
calendar.go
starcoder
package surface import ( "math/rand" "github.com/hunterloftis/pbr/pkg/geom" "github.com/hunterloftis/pbr/pkg/render" "github.com/hunterloftis/pbr/pkg/rgb" ) // Triangle describes a triangle type Triangle struct { Points [3]geom.Vec // TODO: private fields? Normals [3]geom.Dir Texture [3]geom.Vec Mat Material edge1 geom.Vec edge2 geom.Vec bounds *geom.Bounds } // NewTriangle creates a new triangle func NewTriangle(a, b, c geom.Vec, m ...Material) *Triangle { edge1 := b.Minus(a) edge2 := c.Minus(a) n, _ := edge1.Cross(edge2).Unit() t := &Triangle{ Points: [3]geom.Vec{a, b, c}, Normals: [3]geom.Dir{n, n, n}, Mat: &DefaultMaterial{}, edge1: edge1, edge2: edge2, } if len(m) > 0 { t.Mat = m[0] } min := t.Points[0].Min(t.Points[1]).Min(t.Points[2]) max := t.Points[0].Max(t.Points[1]).Max(t.Points[2]) t.bounds = geom.NewBounds(min, max) return t } func (t *Triangle) Transformed(mtx *geom.Mtx) *Triangle { t2 := &Triangle{ Mat: t.Mat, } for i := 0; i < 3; i++ { t2.Points[i] = mtx.MultPoint(t.Points[i]) t2.Normals[i] = mtx.MultDir(t.Normals[i]) t2.Texture[i] = t.Texture[i] } t2.edge1 = t2.Points[1].Minus(t2.Points[0]) t2.edge2 = t2.Points[2].Minus(t2.Points[0]) min := t2.Points[0].Min(t2.Points[1]).Min(t2.Points[2]) max := t2.Points[0].Max(t2.Points[1]).Max(t2.Points[2]) t2.bounds = geom.NewBounds(min, max) return t2 } func (t *Triangle) Bounds() *geom.Bounds { return t.bounds } // https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm func (t *Triangle) Intersect(ray *geom.Ray, max float64) (obj render.Object, dist float64) { if ok, near, _ := t.bounds.Check(ray); !ok || near >= max { return nil, 0 } h := geom.Vec(ray.Dir).Cross(t.edge2) a := t.edge1.Dot(h) if a > -bias && a < bias { return nil, 0 } f := 1 / a s := ray.Origin.Minus(t.Points[0]) u := f * s.Dot(h) if u < 0 || u > 1 { return nil, 0 } q := s.Cross(t.edge1) v := f * geom.Vec(ray.Dir).Dot(q) if v < 0 || u+v > 1 { return nil, 0 } dist = f * t.edge2.Dot(q) if dist <= bias || dist >= max { return nil, 0 } return t, dist } // At returns the material at a point on the Triangle // https://stackoverflow.com/questions/21210774/normal-mapping-on-procedural-sphere func (t *Triangle) At(pt geom.Vec, in geom.Dir, rnd *rand.Rand) (geom.Dir, render.BSDF) { u, v, w := t.Bary(pt) n := t.normal(u, v, w) texture := t.texture(u, v, w) n2, bsdf := t.Mat.At(texture.X, texture.Y, in, n, rnd) // TODO: compute binormal and combine texture normal with n to return actual normal _ = n2 normal := n return normal, bsdf } func (t *Triangle) Lights() []render.Object { if !t.Mat.Light().Zero() { return []render.Object{t} } return nil } func (t *Triangle) Light() rgb.Energy { return t.Mat.Light() } func (t *Triangle) Transmit() rgb.Energy { return t.Mat.Transmit() } // SetNormals sets values for each vertex normal func (t *Triangle) SetNormals(a, b, c geom.Dir) { t.Normals[0] = a t.Normals[1] = b t.Normals[2] = c } func (t *Triangle) SetTexture(a, b, c geom.Vec) { t.Texture[0] = a t.Texture[1] = b t.Texture[2] = c } // Normal computes the smoothed normal func (t *Triangle) normal(u, v, w float64) geom.Dir { // TODO: instead of separate u, v, w just use a Vec and multiply n0 := t.Normals[0].Scaled(u) n1 := t.Normals[1].Scaled(v) n2 := t.Normals[2].Scaled(w) n, _ := n0.Plus(n1).Plus(n2).Unit() return n } func (t *Triangle) texture(u, v, w float64) geom.Vec { tex0 := t.Texture[0].Scaled(u) tex1 := t.Texture[1].Scaled(v) tex2 := t.Texture[2].Scaled(w) return tex0.Plus(tex1).Plus(tex2) } // Bary returns the Barycentric coords of Vector p on Triangle t // https://codeplea.com/triangular-interpolation func (t *Triangle) Bary(p geom.Vec) (u, v, w float64) { v0 := t.Points[1].Minus(t.Points[0]) v1 := t.Points[2].Minus(t.Points[0]) v2 := p.Minus(t.Points[0]) d00 := v0.Dot(v0) d01 := v0.Dot(v1) d11 := v1.Dot(v1) d20 := v2.Dot(v0) d21 := v2.Dot(v1) d := d00*d11 - d01*d01 v = (d11*d20 - d01*d21) / d w = (d00*d21 - d01*d20) / d u = 1 - v - w return }
pkg/surface/triangle.go
0.542863
0.544862
triangle.go
starcoder
package main import ( "math" "math/rand" ) // The Source interface represents a source of randomized data. type Source interface { Advance(int) // Advance sets the source's time. Value() float64 // Value gets the source's current value } // Generator is a generic type implemening Source that's based on a randomized // "next" function mapping float64 -> float64. type Generator struct { epoch int value float64 next func(float64) float64 } // Advance will update the value stored in the generator if the epoch is new. func (g *Generator) Advance(epoch int) { if g.epoch == epoch { return } g.epoch = epoch g.value = g.next(g.value) } // Value will return the correct value stored in the generator. func (g *Generator) Value() float64 { return g.value } // Generate takes a successor function and creates a source. func Generate(f func(float64) float64) Source { return &Generator{0, 0, f} } // Normal is a source of normally distributed data points. func Normal() Source { return &Generator{0, 0, func(old float64) float64 { return rand.NormFloat64() }} } // Uniform is a source of uniformly distributed data points on [0, 1]. func Uniform() Source { return &Generator{0, 0, func(old float64) float64 { return rand.Float64() }} } // Brownian is a source of brownian data points (first differences are normal). func Brownian() Source { return &Generator{0, 0, func(old float64) float64 { return old + rand.NormFloat64() }} } // Linear computes a linear mix of sources. type Linear struct { sources []Source weights []float64 } // Advance advances every source in the linear collection. func (linear *Linear) Advance(epoch int) { for i := range linear.sources { linear.sources[i].Advance(epoch) } } // Value gets the linear mix of the value's of all the sources in the linear container. func (linear *Linear) Value() float64 { value := 0.0 for i := range linear.sources { value += linear.weights[i] * linear.sources[i].Value() } return value } // NewLinear takes a slice of sources as input and assigns weights randomly to each. func NewLinear(sources []Source) Source { weights := make([]float64, len(sources)) weight := 0.0 for i := range weights { weights[i] = rand.Float64() weight += weights[i] } for i := range weights { weights[i] /= weight } return &Linear{sources, weights} } // Capper is an implementation for Source that caps its outputs (above and below). type Capper struct { source Source min float64 max float64 } // Advance advances the underlying source. func (c *Capper) Advance(epoch int) { c.source.Advance(epoch) } // Value gets the capped source for the capper. func (c *Capper) Value() float64 { return math.Max(c.min, math.Min(c.max, c.source.Value())) } // Cumulative is an implementation for Source that computes a running sum of outputs. type Cumulative struct { source Source epoch int sum float64 } // Advance advances the underlying source. func (c *Cumulative) Advance(epoch int) { c.source.Advance(epoch) if c.epoch == epoch { return } c.sum += c.source.Value() } // Value gets the current value in the sum. func (c *Cumulative) Value() float64 { return c.sum } // Mapper changes the distribution of the underlying source by remapping all outputs. type Mapper struct { source Source fun func(float64) float64 } // Advance advances the underlying container. func (m *Mapper) Advance(epoch int) { m.source.Advance(epoch) } // Value computes the redistributed value of the underlying source. func (m *Mapper) Value() float64 { return m.fun(m.source.Value()) } // RequestSources provides a random collection of several sources. func RequestSources(count int) []Source { base := []Source{Normal(), Uniform(), Brownian(), Brownian(), Brownian()} result := make([]Source, count) for i := range result { result[i] = NewLinear(base) } return result }
demo/emit/source.go
0.826642
0.568715
source.go
starcoder
package parser import ( "fmt" "log" "sort" "strconv" "github.com/facebookresearch/clinical-trial-parser/src/common/col/set" "github.com/facebookresearch/clinical-trial-parser/src/ct/relation" "github.com/facebookresearch/clinical-trial-parser/src/ct/variables" ) // Tree defines the parse tree. type Tree struct { root *Node score float64 } // NewTree creates a new parse tree. func NewTree(root *Node, score float64) *Tree { return &Tree{root: root, score: score} } // Size calculates the number of leafs (terminals). func (t *Tree) Size() int { if t == nil || t.root == nil { return 0 } return t.root.Size() } // Contains returns true if the tree t contains the tree v as a sub-tree or they are same. func (t *Tree) Contains(v *Tree) bool { return t.root.Contains(v.root) } // String returns the string representation of the tree. func (t *Tree) String() string { return fmt.Sprintf("{%q:%.3f,%q:%s}", "score", t.score, "tree", t.root.String()) } // Relations converts the tree to 'or' and 'and' relations. func (t *Tree) Relations() (relation.Relations, relation.Relations) { orRels, andRels := t.root.EvalRelations() orRels.SetScore(t.score) orRels.Sort() andRels.SetScore(t.score) andRels.Sort() return orRels, andRels } // Trees defines a slice of parse trees. type Trees []*Tree // NewTrees creates a new slice of trees. func NewTrees() Trees { return make(Trees, 0) } // Dedupe deduplicates trees by removing exact duplicates and stumps // that are contained by other trees. func (ts *Trees) Dedupe() { a := *ts if len(a) < 2 { return } sort.SliceStable(a, func(i, j int) bool { return a[i].Size() > a[j].Size() }) for i := len(a) - 1; i > 0; i-- { for j := 0; j < i; j++ { if a[j].Contains(a[i]) { a = append(a[:i], a[i+1:]...) break } } } *ts = a } // String returns the string representation of the trees. func (ts Trees) String() string { switch len(ts) { case 0: return "" case 1: return ts[0].String() default: s := ts[0].String() for i := 1; i < len(ts); i++ { s += "\n" + ts[i].String() } return s } } // Relations converts the trees to 'or' and 'and' relations. func (ts Trees) Relations() (relation.Relations, relation.Relations) { orRels := relation.NewRelations() andRels := relation.NewRelations() for _, t := range ts { or, and := t.Relations() orRels = append(orRels, or...) andRels = append(andRels, and...) } return orRels, andRels } // Empty tests whether ts has any trees in it. func (ts Trees) Empty() bool { return len(ts) == 0 } // Node defines a node in the parse tree, which is constructed by applying // grammar production rules to the parsed items. type Node struct { val string left *Node right *Node pos int width int } // NewNode creates a new node. func NewNode(val string, pos int, width int) *Node { return &Node{val: val, pos: pos, width: width} } // Size calculates the number of leafs (terminals). func (n *Node) Size() int { switch { case n == nil: return 0 case n.left == nil && n.right == nil: return 1 default: return n.left.Size() + n.right.Size() } } // Contains returns true if n contains m and its left and right children. func (n *Node) Contains(m *Node) bool { switch { case m == nil: return true case n == nil: return false case n.val != m.val: return false default: return n.left.Contains(m.left) && n.right.Contains(m.right) } } // String returns the string representation of the node. func (n *Node) String() string { s := fmt.Sprintf("{%q:%q", "value", n.val) if n.left != nil { s += fmt.Sprintf(",%q:%s", "left", n.left.String()) } if n.right != nil { s += fmt.Sprintf(",%q:%s", "right", n.right.String()) } s += "}" return s } // EvalVariable evaluates and returns the variable name stored in the terminal leaf. func (n *Node) EvalVariable() string { variable := n.left.left.val if n.right != nil { variable += "/" + n.right.right.left.val } return variable } func (n *Node) EvalStart() int { return n.left.left.pos } func (n *Node) EvalEnd() int { return n.left.left.width } // EvalNums evaluates and returns the list of numbers stored in the terminal leafs. func (n *Node) EvalNums() []string { set := set.New() var eval func(n *Node) eval = func(n *Node) { if n.left != nil { m := n.left if m.val == "N" { set.Add(m.left.val) } else { eval(m) } } if n.right != nil { m := n.right if m.val == "N" { set.Add(m.left.val) } else { eval(m) } } } eval(n) return set.Slice() } // EvalNums evaluates and returns the list of numbers stored in the terminal leafs. func (n *Node) EvalPos(s string) []string { set := set.New() var eval func(n *Node) eval = func(n *Node) { if n.left != nil { m := n.left if m.val == "N" || m.val == "D" { if s == "Start" { set.Add(strconv.Itoa(m.left.pos)) } if s == "End" { set.Add(strconv.Itoa(m.left.width)) } } else { eval(m) } } if n.right != nil { m := n.right if m.val == "N" { if s == "Start" { set.Add(strconv.Itoa(m.left.pos)) } if s == "End" { set.Add(strconv.Itoa(m.left.width)) } } else { eval(m) } } } eval(n) return set.Slice() } // EvalUnit evaluates and returns the unit stored in the terminal leaf. func (n *Node) EvalUnit() *relation.Unit { unit := &relation.Unit{} var eval func(n *Node) eval = func(n *Node) { if len(unit.Value) > 0 { return } if n.left != nil { log.Printf("%+v", n.left) m := n.left if m.val == "U" { unit.Value = m.left.val unit.Start = append(unit.Start, m.left.pos) unit.End = append(unit.End, m.left.width) return } eval(m) } if n.right != nil { m := n.right if m.val == "U" { unit.Value = m.left.val unit.Start = append(unit.Start, m.left.pos) unit.End = append(unit.End, m.left.width) return } eval(m) } } eval(n) return unit } // EvalBound evaluates and returns the bound relation. func (n *Node) EvalBound() (*relation.Limit, bool) { l := &relation.Limit{} lower := false if n.left.val == "L" && n.right.val == "T" { n.left, n.right = n.right, n.left } t := n.left if t.val != "T" { return nil, false } switch t.left.val { case "<": l.Value = "<" l.Incl = false case "≤": l.Value = "≤" l.Incl = true case ">": l.Value = ">" l.Incl = false lower = true case "≥": l.Value = "≥" l.Incl = true lower = true } num := n.right.left l.Value = num.left.val l.Start = append(l.Start, t.left.pos) l.Start = append(l.Start, num.left.pos) l.End = append(l.End, t.left.width) l.End = append(l.End, num.left.width) return l, lower } // EvalRange evaluates and returns the lower or upper bound of the range condition. func (n *Node) EvalRange() *relation.Limit { l := &relation.Limit{} l.Incl = true nums := n.EvalNums() starts := n.EvalPos("Start") ends := n.EvalPos("End") if len(nums) == 1 { l.Value = nums[0] for _, start := range starts { startint, _ := strconv.Atoi(start) l.Start = append(l.Start, startint) } for _, end := range ends { endint, _ := strconv.Atoi(end) l.End = append(l.End, endint) } } return l } // EvalRelation evaluates and returns the relation stored in the parse node based on the production rules. func (n *Node) EvalRelation() (*relation.Relation, error) { r := relation.New() left := n.left right := n.right if left.val != "V" { left, right = right, left } if left.val != "V" { return nil, fmt.Errorf("bad or missing variable node: %s, %s", left.val, right.val) } r.Name = left.EvalVariable() r.Start = left.EvalStart() r.End = left.EvalEnd() r.ID, _ = variables.Get().ID(r.Name) // Check that the attribute node A exists: if right == nil || right.val != "A" { return r, nil } m := right r.Unit = m.EvalUnit() // Check the left branch of A: setBound := func(b *relation.Limit, lower bool) { switch { case lower: if r.Lower == nil { r.Lower = b } case !lower: if r.Upper == nil { r.Upper = b } } } left = m.left switch left.val { case "E": nums := m.EvalNums() r.Value = nums return r, nil case "B": b, lower := left.EvalBound() setBound(b, lower) case "L", "Y": r.Lower = left.EvalRange() } // Check the right branch of A: right = m.right if right == nil { return r, nil } switch right.val { case "W": b, lower := right.right.EvalBound() setBound(b, lower) case "B": b, lower := right.EvalBound() setBound(b, lower) case "Y": r.Upper = right.EvalRange() } return r, nil } // EvalRelations evaluates and returns the 'or' and 'and' relations stored in the parse node. func (n *Node) EvalRelations() (relation.Relations, relation.Relations) { if n.left == nil { return relation.NewRelations(), relation.NewRelations() } switch { case n.left.val == "C" && n.right == nil: return n.left.EvalRelations() case n.left.val == "R" && n.right == nil: orRels := relation.NewRelations() andRels := relation.NewRelations() r, _ := n.left.EvalRelation() andRels = append(andRels, r) return orRels, andRels default: m := n.right conj := "and" if m.right != nil { conj = m.left.left.val m = m.right } else { m = m.left } orRels, andRels := n.left.EvalRelations() if r, err := m.EvalRelation(); err == nil { switch conj { case "or": orRels = append(orRels, r) orRels = append(orRels, andRels...) andRels = relation.NewRelations() default: andRels = append(andRels, r) andRels = append(andRels, orRels...) orRels = relation.NewRelations() } } return orRels, andRels } }
src/ct/parser/tree.go
0.754101
0.422386
tree.go
starcoder
package main import ( "math/rand" ) type Individ struct { ps []Point2f distance float64 fitness float64 } func NewIndivid(ps []Point2f, distance float64) *Individ { d := &Individ{ ps: ps, distance: distance, } d.calcFitness() return d } func RandIndivid(r *rand.Rand, n int, distance float64) *Individ { ps := make([]Point2f, n) for i := range ps { ps[i] = randPoint2f(r) } return NewIndivid(ps, distance) } func RandIndividBySeed(seed int64, n int, distance float64) *Individ { r := newRandSeed(seed) ps := make([]Point2f, n) for i := range ps { ps[i] = randPoint2f(r) } return NewIndivid(ps, distance) } func RandIndividGridBySeed(seed int64, n int, distance float64) *Individ { r := newRandSeed(seed) ps := make([]Point2f, 0, n) d := 1 / float64(n-1) for x := 0; x < n; x++ { for y := 0; y < n; y++ { p := Point2f{ X: float64(x) * d, Y: float64(y) * d, } ps = append(ps, p) } } shuffleElements(r, Point2fSlice(ps)) return NewIndivid(ps, distance) } func (a *Individ) Clone() *Individ { if a != nil { return &Individ{ ps: clonePoint2fSlice(a.ps), distance: a.distance, fitness: a.fitness, } } return nil } func (a *Individ) Fitness() float64 { return a.fitness } // MSE - Mean squared error // https://en.wikipedia.org/wiki/Mean_squared_error func (d *Individ) calcFitnessMSE() { x0 := d.distance n := len(d.ps) var sum float64 for i := 0; i < n-1; i++ { for j := i + 1; j < n; j++ { x := Distance(d.ps[i], d.ps[j]) delta := (x - x0) sum += delta * delta } } m := n * (n - 1) / 2 mse := sum / float64(m) d.fitness = mse } func (d *Individ) calcFitness() { d.calcFitnessMSE() } func (d *Individ) Range(f func(i int, p Point2f) bool) { for i, p := range d.ps { if !f(i, p) { return } } } func (d *Individ) PointsChan() <-chan Point2f { ps := make(chan Point2f) go func() { for _, p := range d.ps { ps <- p } close(ps) }() return ps } func (d *Individ) Random(r *rand.Rand) { if randBool(r) { d.randomFull(r) } else { d.randomShort(r) } } func (d *Individ) randomFull(r *rand.Rand) { i := r.Intn(len(d.ps)) d.ps[i] = randPoint2f(r) d.calcFitness() } func (d *Individ) randomShort(r *rand.Rand) { delta := 0.01 halfDelta := delta / 2 dx := halfDelta - r.Float64()*delta dy := halfDelta - r.Float64()*delta i := r.Intn(len(d.ps)) p := d.ps[i] p.X = clampFloat64(p.X+dx, 0, 1) p.Y = clampFloat64(p.Y+dy, 0, 1) d.ps[i] = p d.calcFitness() } type ByFitness []*Individ func (p ByFitness) Len() int { return len(p) } func (p ByFitness) Less(i, j int) bool { return p[i].fitness < p[j].fitness } func (p ByFitness) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
ga/closedist/individ.go
0.778649
0.47025
individ.go
starcoder
package gstr import "strings" // Str returns part of `haystack` string starting from and including // the first occurrence of `needle` to the end of `haystack`. // See http://php.net/manual/en/function.strstr.php. func Str(haystack string, needle string) string { if needle == "" { return "" } pos := strings.Index(haystack, needle) if pos == NotFoundIndex { return "" } return haystack[pos+len([]byte(needle))-1:] } // StrEx returns part of `haystack` string starting from and excluding // the first occurrence of `needle` to the end of `haystack`. func StrEx(haystack string, needle string) string { if s := Str(haystack, needle); s != "" { return s[1:] } return "" } // StrTill returns part of `haystack` string ending to and including // the first occurrence of `needle` from the start of `haystack`. func StrTill(haystack string, needle string) string { pos := strings.Index(haystack, needle) if pos == NotFoundIndex || pos == 0 { return "" } return haystack[:pos+1] } // StrTillEx returns part of `haystack` string ending to and excluding // the first occurrence of `needle` from the start of `haystack`. func StrTillEx(haystack string, needle string) string { pos := strings.Index(haystack, needle) if pos == NotFoundIndex || pos == 0 { return "" } return haystack[:pos] } // SubStr returns a portion of string `str` specified by the `start` and `length` parameters. // The parameter `length` is optional, it uses the length of `str` in default. func SubStr(str string, start int, length ...int) (substr string) { strLength := len(str) // Simple border checks. if start < 0 { start = 0 } if start >= strLength { start = strLength } end := strLength if len(length) > 0 { end = start + length[0] if end < start { end = strLength } } if end > strLength { end = strLength } return str[start:end] } // SubStrRune returns a portion of string `str` specified by the `start` and `length` parameters. // SubStrRune considers parameter `str` as unicode string. // The parameter `length` is optional, it uses the length of `str` in default. func SubStrRune(str string, start int, length ...int) (substr string) { // Converting to []rune to support unicode. var ( runes = []rune(str) runesLength = len(runes) ) // Simple border checks. if start < 0 { start = 0 } if start >= runesLength { start = runesLength } end := runesLength if len(length) > 0 { end = start + length[0] if end < start { end = runesLength } } if end > runesLength { end = runesLength } return string(runes[start:end]) } // StrLimit returns a portion of string `str` specified by `length` parameters, if the length // of `str` is greater than `length`, then the `suffix` will be appended to the result string. func StrLimit(str string, length int, suffix ...string) string { if len(str) < length { return str } suffixStr := defaultSuffixForStrLimit if len(suffix) > 0 { suffixStr = suffix[0] } return str[0:length] + suffixStr } // StrLimitRune returns a portion of string `str` specified by `length` parameters, if the length // of `str` is greater than `length`, then the `suffix` will be appended to the result string. // StrLimitRune considers parameter `str` as unicode string. func StrLimitRune(str string, length int, suffix ...string) string { runes := []rune(str) if len(runes) < length { return str } suffixStr := defaultSuffixForStrLimit if len(suffix) > 0 { suffixStr = suffix[0] } return string(runes[0:length]) + suffixStr } // SubStrFrom returns a portion of string `str` starting from first occurrence of and including `need` // to the end of `str`. func SubStrFrom(str string, need string) (substr string) { pos := Pos(str, need) if pos < 0 { return "" } return str[pos:] } // SubStrFromEx returns a portion of string `str` starting from first occurrence of and excluding `need` // to the end of `str`. func SubStrFromEx(str string, need string) (substr string) { pos := Pos(str, need) if pos < 0 { return "" } return str[pos+len(need):] } // SubStrFromR returns a portion of string `str` starting from last occurrence of and including `need` // to the end of `str`. func SubStrFromR(str string, need string) (substr string) { pos := PosR(str, need) if pos < 0 { return "" } return str[pos:] } // SubStrFromREx returns a portion of string `str` starting from last occurrence of and excluding `need` // to the end of `str`. func SubStrFromREx(str string, need string) (substr string) { pos := PosR(str, need) if pos < 0 { return "" } return str[pos+len(need):] }
text/gstr/gstr_sub.go
0.794225
0.513607
gstr_sub.go
starcoder
package migrator import ( "database/sql" ) var ( // DefaultBatchSize represents the default size of extracted batches DefaultBatchSize = 1000 // TrackingTableName represents the name of the database table used // to track TrackingStatus instances, and exists within the target // database. TrackingTableName = "EtlPosition" // TransformerMap is a map of Transformer functions which can be used // to instantiate a Transformer based only on a string. TransformerMap = make(map[string]Transformer) // ExtractorMap is a map of Extractor functions which can be used // to instantiate an Extractor based only on a string. ExtractorMap = make(map[string]Extractor) // RecordQueueTable is the table name for the non-update field // capable entries. RecordQueueTable = "MigratorRecordQueue" // ParamMethod is the parameter name which specifies the insert or // update method being used by portions of the migrator. ParamMethod = "METHOD" // ParamInsertBatchSize is the parameter used by the default loader // to batch queries. Int, defaults to 1000. ParamInsertBatchSize = "InsertBatchSize" // ParamDebug is the parameter used to enable basic debugging // code in modules. Boolean, defaults to false. ParamDebug = "Debug" // ParamLowLevelDebug is the parameter used to enable lower level // debugging code in modules. It is boolean and defaults to false. ParamLowLevelDebug = "LowLevelDebug" // ParamBatchSize is the parameter used to specify general batch // processing size for polling records from the database. Int, // defaults to 100. ParamBatchSize = "BatchSize" // ParamOnlyPast is the parameter for timestamp-based polling which // only polls for timestamps in the past. Boolean, defaults to // false. ParamOnlyPast = "OnlyPast" // ParamSequentialReplace is the parameter for loading which uses // REPLACE instead of INSERT for sequentially extracted data. Boolean, // defaults to false. ParamSequentialReplace = "SequentialReplace" // ParamTableName is the parameter for an adjusted table name. // String, defaults to "". ParamTableName = "TableName" // ParamSleepBetweenRuns is the parameter which defines the amount of // time between runs in seconds. Int, defaults to 5. ParamSleepBetweenRuns = "SleepBetweenRuns" ) // SQLUntypedRow represents a single row of SQL data which is not strongly // typed to a structure. This obviates the need to create Golang-level language // structures to represent tables. type SQLUntypedRow map[string]interface{} // SQLRow represents a single row of SQL data with an action associated with it type SQLRow struct { Data SQLUntypedRow Method string } // Parameters represents a series of untyped parameters which are passed to // Extractors, Transformers, and Loaders. All stages of the ETL process // receive the same parameters. type Parameters map[string]interface{} // TableData represents identifying information and data for a table. type TableData struct { DbName string TableName string Data []SQLRow Method string // only used with loader, specifies INSERT/REPLACE } // Extractor is a callback function type type Extractor func(*sql.DB, string, string, TrackingStatus, *Parameters) (bool, []SQLRow, TrackingStatus, error) // Transformer is a callback function type which transforms an array of untyped // information into another array of untyped information. This is used for the // "transform" step of the ETL process. type Transformer func(string, string, []SQLRow, *Parameters) []TableData // Loader is a callback function type type Loader func(*sql.DB, []TableData, *Parameters) error
types.go
0.604282
0.478285
types.go
starcoder
package write import ( "bytes" "fmt" "github.com/lukasaron/data-discogs/model" "io" "strings" ) // SQLWriter is one of few provided writers that implements the Writer interface and provides the ability to save // decoded data in the format of SQL insert commands. type SQLWriter struct { o Options w io.Writer b *bytes.Buffer err error } // NewSQLWriter creates a new Writer instance based on the provided output writer (for instance a file). // Options with ExcludeImages can be set when we don't want images as part of the final solution. // When this is not the case and we want images in the result SQL commands the Option can be omitted. func NewSQLWriter(output io.Writer, options *Options) Writer { if options == nil { options = &Options{} } return &SQLWriter{ b: &bytes.Buffer{}, o: *options, w: output, } } // WriteArtist function writes an artist as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteArtist(artist model.Artist) error { s.beginTransaction() s.writeArtist(artist) s.writeImages(artist.ID, "", "", "", artist.Images) s.writeAliases(artist.ID, artist.Aliases) s.writeArtistMembers(artist.ID, artist.Members) s.commitTransaction() s.flush() s.clean() return s.err } // WriteArtists function writes a slice of artists as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteArtists(artists []model.Artist) error { s.beginTransaction() for _, a := range artists { s.writeArtist(a) s.writeImages(a.ID, "", "", "", a.Images) s.writeAliases(a.ID, a.Aliases) s.writeArtistMembers(a.ID, a.Members) if s.err != nil { return s.err } } s.commitTransaction() s.flush() s.clean() return s.err } // WriteLabel function writes a label as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteLabel(label model.Label) error { s.beginTransaction() s.writeLabel(label) s.writeLabelLabels(label.ID, "false", label.SubLabels) s.writeImages("", label.ID, "", "", label.Images) if label.ParentLabel != nil { s.writeLabelLabel(label.ID, "true", *label.ParentLabel) } s.commitTransaction() s.flush() s.clean() return s.err } // WriteLabels function writes a slice of labels as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteLabels(labels []model.Label) error { s.beginTransaction() for _, l := range labels { s.writeLabel(l) s.writeLabelLabels(l.ID, "false", l.SubLabels) s.writeImages("", l.ID, "", "", l.Images) if l.ParentLabel != nil { s.writeLabelLabel(l.ID, "true", *l.ParentLabel) } if s.err != nil { return s.err } } s.commitTransaction() s.flush() s.clean() return s.err } // WriteMaster function writes a master as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteMaster(master model.Master) (err error) { s.beginTransaction() s.writeMaster(master) s.writeReleaseArtists(master.ID, "", "false", master.Artists) s.writeImages("", "", master.ID, "", master.Images) s.writeVideos(master.ID, "", master.Videos) s.commitTransaction() s.flush() s.clean() return s.err } // WriteMasters function writes a slice of masters as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteMasters(masters []model.Master) error { s.beginTransaction() for _, m := range masters { s.writeMaster(m) s.writeReleaseArtists(m.ID, "", "false", m.Artists) s.writeImages("", "", m.ID, "", m.Images) s.writeVideos(m.ID, "", m.Videos) if s.err != nil { return s.err } } s.commitTransaction() s.flush() s.clean() return s.err } // WriteRelease function writes a release as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteRelease(release model.Release) error { s.beginTransaction() s.writeRelease(release) s.writeImages("", "", "", release.ID, release.Images) s.writeReleaseArtists("", release.ID, "false", release.Artists) s.writeReleaseArtists("", release.ID, "true", release.ExtraArtists) s.writeFormats(release.ID, release.Formats) s.writeTrackList(release.ID, release.TrackList) s.writeIdentifiers(release.ID, release.Identifiers) s.writeReleaseLabels(release.ID, release.Labels) s.writeCompanies(release.ID, release.Companies) s.writeVideos("", release.ID, release.Videos) s.commitTransaction() s.flush() s.clean() return s.err } // WriteReleases function writes a slice of releases as a set of SQL insert commands into the SQL output. func (s SQLWriter) WriteReleases(releases []model.Release) error { s.beginTransaction() for _, r := range releases { s.writeRelease(r) s.writeImages("", "", "", r.ID, r.Images) s.writeReleaseArtists("", r.ID, "false", r.Artists) s.writeReleaseArtists("", r.ID, "true", r.ExtraArtists) s.writeFormats(r.ID, r.Formats) s.writeTrackList(r.ID, r.TrackList) s.writeIdentifiers(r.ID, r.Identifiers) s.writeReleaseLabels(r.ID, r.Labels) s.writeCompanies(r.ID, r.Companies) s.writeVideos("", r.ID, r.Videos) if s.err != nil { return s.err } } s.commitTransaction() s.flush() s.clean() return s.err } // Options function returns the current options. It could be useful to get the default options. func (s SQLWriter) Options() Options { return s.o } // ----------------------------------------------- UNPUBLISHED FUNCTIONS ----------------------------------------------- func (s SQLWriter) beginTransaction() { if s.err != nil { return } _, s.err = s.b.WriteString("BEGIN;\n") } func (s SQLWriter) commitTransaction() { if s.err != nil { return } _, s.err = s.b.WriteString("COMMIT;\n") } func (s SQLWriter) writeArtist(a model.Artist) { if s.err != nil { return } _, s.err = s.b.WriteString( fmt.Sprintf("INSERT INTO artists (artist_id, name, real_name, profile, data_quality, name_variations, urls) VALUES ('%s', '%s', '%s', '%s', '%s', ARRAY[%s], ARRAY[%s]);\n", a.ID, cleanText(a.Name), cleanText(a.RealName), cleanText(a.Profile), a.DataQuality, array(a.NameVariations), array(a.Urls)), ) } func (s SQLWriter) writeImage(artistID, labelID, masterID, releaseID string, img model.Image) { if !s.o.ExcludeImages { _, s.err = s.b.WriteString( fmt.Sprintf("INSERT INTO images (artist_id, label_id, master_id, release_id, height, width, type, uri, uri_150) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');\n", artistID, labelID, masterID, releaseID, img.Height, img.Width, img.Type, img.URI, img.URI150, ), ) } } func (s SQLWriter) writeImages(artistID, labelID, masterID, releaseID string, imgs []model.Image) { if s.err == nil && !s.o.ExcludeImages { for _, img := range imgs { s.writeImage(artistID, labelID, masterID, releaseID, img) if s.err != nil { return } } } } func (s SQLWriter) writeAlias(artistID string, a model.Alias) { if s.err != nil { return } _, s.err = s.b.WriteString( fmt.Sprintf("INSERT INTO artist_aliases (artist_id, alias_id, name) VALUES ('%s', '%s', '%s');\n", artistID, a.ID, cleanText(a.Name)), ) } func (s SQLWriter) writeAliases(artistID string, as []model.Alias) { if s.err != nil { return } for _, a := range as { s.writeAlias(artistID, a) if s.err != nil { return } } } func (s SQLWriter) writeArtistMember(artistID string, m model.Member) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO artist_members (artist_id, member_id, name) VALUES ('%s', '%s', '%s');\n", artistID, m.ID, cleanText(m.Name)), ) } func (s SQLWriter) writeArtistMembers(artistID string, ms []model.Member) { if s.err != nil { return } for _, m := range ms { s.writeArtistMember(artistID, m) if s.err != nil { return } } } func (s SQLWriter) writeLabel(l model.Label) { if s.err != nil { return } _, s.err = s.b.WriteString( fmt.Sprintf("INSERT INTO labels (label_id, name, contact_info, profile, data_quality, urls) VALUES ('%s', '%s', '%s', '%s', '%s', ARRAY[%s]);\n", l.ID, cleanText(l.Name), cleanText(l.ContactInfo), cleanText(l.Profile), l.DataQuality, array(l.Urls), ), ) } func (s SQLWriter) writeLabelLabel(labelID, parent string, l model.LabelLabel) { if s.err != nil { return } _, s.err = s.b.WriteString( fmt.Sprintf("INSERT INTO label_labels (label_id, sub_label_id, name, parent) VALUES ('%s', '%s', '%s', '%s');\n", labelID, l.ID, cleanText(l.Name), parent, ), ) } func (s SQLWriter) writeLabelLabels(labelID, parent string, lls []model.LabelLabel) { if s.err != nil { return } for _, ll := range lls { s.writeLabelLabel(labelID, parent, ll) if s.err != nil { return } } } func (s SQLWriter) writeMaster(m model.Master) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO masters (master_id, main_release, genres, styles, year, title, data_quality) VALUES ('%s', '%s', ARRAY[%s], ARRAY[%s], '%s', '%s', '%s');\n", m.ID, m.MainRelease, array(m.Genres), array(m.Styles), m.Year, cleanText(m.Title), m.DataQuality), ) } func (s SQLWriter) writeRelease(r model.Release) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO releases (release_id, status, title, genres, styles, country, released, notes, data_quality, master_id, main_release) VALUES ('%s', '%s', '%s', ARRAY[%s], ARRAY[%s], '%s', '%s', '%s', '%s', '%s', '%s');\n", r.ID, cleanText(r.Status), cleanText(r.Title), array(r.Genres), array(r.Styles), cleanText(r.Country), r.Released, cleanText(r.Notes), r.DataQuality, r.MasterID, r.MainRelease), ) } func (s SQLWriter) writeCompany(releaseID string, c model.Company) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO release_companies (release_id, release_company_id, name, category, entity_type, entity_type_name, resource_url) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s');\n", releaseID, c.ID, cleanText(c.Name), cleanText(c.Category), cleanText(c.EntityType), cleanText(c.EntityTypeName), cleanText(c.ResourceURL)), ) } func (s SQLWriter) writeCompanies(releaseID string, cs []model.Company) { if s.err != nil { return } for _, c := range cs { s.writeCompany(releaseID, c) if s.err != nil { return } } } func (s SQLWriter) writeReleaseLabel(releaseID string, rl model.ReleaseLabel) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO release_labels (release_id, release_label_id, name, category) VALUES ('%s', '%s', '%s', '%s');\n", releaseID, rl.ID, cleanText(rl.Name), cleanText(rl.Category)), ) } func (s SQLWriter) writeReleaseLabels(releaseID string, rls []model.ReleaseLabel) { if s.err != nil { return } for _, rl := range rls { s.writeReleaseLabel(releaseID, rl) if s.err != nil { return } } } func (s SQLWriter) writeIdentifier(releaseID string, i model.Identifier) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO release_identifiers (release_id, description, type, value) VALUES ('%s', '%s', '%s', '%s');\n", releaseID, cleanText(i.Description), cleanText(i.Type), cleanText(i.Value)), ) } func (s SQLWriter) writeIdentifiers(releaseID string, is []model.Identifier) { if s.err != nil { return } for _, i := range is { s.writeIdentifier(releaseID, i) if s.err != nil { return } } } func (s SQLWriter) writeTrack(releaseID string, t model.Track) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO release_tracks (release_id, position, title, duration) VALUES ('%s', '%s', '%s', '%s');\n", releaseID, cleanText(t.Position), cleanText(t.Title), cleanText(t.Duration)), ) } func (s SQLWriter) writeTrackList(releaseID string, tl []model.Track) { if s.err != nil { return } for _, t := range tl { s.writeTrack(releaseID, t) if s.err != nil { return } } } func (s SQLWriter) writeFormat(releaseID string, f model.Format) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO release_formats (release_id, name, quantity, text, descriptions) VALUES ('%s', '%s', '%s', '%s', ARRAY[%s]);\n", releaseID, cleanText(f.Name), f.Quantity, cleanText(f.Text), array(f.Descriptions)), ) } func (s SQLWriter) writeFormats(releaseID string, fs []model.Format) { if s.err != nil { return } for _, f := range fs { s.writeFormat(releaseID, f) if s.err != nil { return } } } func (s SQLWriter) writeReleaseArtist(masterID, releaseID, extra string, ra model.ReleaseArtist) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO release_artists (master_id, release_id, release_artist_id, name, extra, joiner, anv, role, tracks) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');\n", masterID, releaseID, ra.ID, cleanText(ra.Name), extra, cleanText(ra.Join), cleanText(ra.Anv), cleanText(ra.Role), cleanText(ra.Tracks)), ) } func (s SQLWriter) writeReleaseArtists(masterID, releaseID, extra string, ras []model.ReleaseArtist) { if s.err != nil { return } for _, ra := range ras { s.writeReleaseArtist(masterID, releaseID, extra, ra) if s.err != nil { return } } } func (s SQLWriter) writeVideo(masterID, releaseID string, v model.Video) { if s.err != nil { return } _, s.err = s.b.WriteString(fmt.Sprintf("INSERT INTO videos (master_id, release_id, duration, embed, src, title, description) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s');\n", masterID, releaseID, cleanText(v.Duration), v.Embed, cleanText(v.Src), cleanText(v.Title), cleanText(v.Description)), ) } func (s SQLWriter) writeVideos(masterID, releaseID string, vs []model.Video) { if s.err != nil { return } for _, v := range vs { s.writeVideo(masterID, releaseID, v) if s.err != nil { return } } } func (s SQLWriter) flush() { if s.err != nil { return } _, s.err = s.w.Write(s.b.Bytes()) } func (s SQLWriter) clean() { s.b.Reset() } // ----------------------------------------------- HELPER FUNCTIONS ----------------------------------------------- func cleanText(str string) string { return strings.ReplaceAll(str, "'", "''") } func array(str []string) string { sb := strings.Builder{} sb.WriteString("'") sb.WriteString(strings.ReplaceAll(cleanText(strings.Join(str, ",")), ",", "','")) sb.WriteString("'") return sb.String() }
write/sql.go
0.610453
0.407687
sql.go
starcoder
package xy // Cell is a 64-bit integer that interleaves two coordinates. type Cell uint64 func (c Cell) String() string { s := make([]byte, 0, 32) const hex = "0123456789abcdef" for i := 0; i < 64; i += 4 { s = append(s, hex[(c>>(60-i))&15]) } return string(s) } // Quad returns a value or 0, 1, 2, or 3 representing the "quad" for the cell // at a specified level. func (c Cell) Quad(forLevel int) int { return int((uint64(c) >> (64 - forLevel*2)) & 3) } // The maximum coord that is less than 1.0. Equal to math.Nextafter(1, 0). const maxCoord = 0.99999999999999988897769753748434595763683319091796875 func clip(x float64) float64 { if x < 0 { return 0 } if x > maxCoord { return maxCoord } return x } // Encode returns an encoded Cell from X/Y floating points. // The input floating points must be within the range [0.0,1.0). // Values outside that range are clipped. func Encode(x, y float64) Cell { // Produce 32-bit integers for X/Y-> A/B a := uint32(clip(x) * (1 << 32)) b := uint32(clip(y) * (1 << 32)) // Interleave A/B into 64-bit integers AB ab := interleave(a)<<1 | interleave(b) return Cell(ab) } // Decode returns the decoded values from a cell. func Decode(cell Cell) (x, y float64) { // Decoding is the inverse of the Encode logic. ab := uint64(cell) a := deinterleave(ab >> 1) b := deinterleave(ab) x = float64(a) / (1 << 32) y = float64(b) / (1 << 32) return x, y } // CellFromString returns the decoded values from a cell string. func CellFromString(s string) Cell { const tbl = "" + "------------------------------------------------" + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09" + "-------" + "\x0A\x0B\x0C\x0D\x0E\x0F" + "--------------------------" + "\x0A\x0B\x0C\x0D\x0E\x0F" + "---------------------------------------------------------" + "---------------------------------------------------------" + "---------------------------------------" var ab uint64 for i := 0; i < len(s) && i < 16; i++ { ab = (ab << 4) | uint64(tbl[s[i]]) } return Cell(ab) } // Bit interleaving thanks to the Daniel Lemire's blog entry: // https://lemire.me/blog/2018/01/08/how-fast-can-you-bit-interleave-32-bit-integers/ func interleave(input uint32) uint64 { word := uint64(input) word = (word ^ (word << 16)) & 0x0000ffff0000ffff word = (word ^ (word << 8)) & 0x00ff00ff00ff00ff word = (word ^ (word << 4)) & 0x0f0f0f0f0f0f0f0f word = (word ^ (word << 2)) & 0x3333333333333333 word = (word ^ (word << 1)) & 0x5555555555555555 return word } func deinterleave(word uint64) uint32 { word &= 0x5555555555555555 word = (word ^ (word >> 1)) & 0x3333333333333333 word = (word ^ (word >> 2)) & 0x0f0f0f0f0f0f0f0f word = (word ^ (word >> 4)) & 0x00ff00ff00ff00ff word = (word ^ (word >> 8)) & 0x0000ffff0000ffff word = (word ^ (word >> 16)) & 0x00000000ffffffff return uint32(word) }
xy/cell.go
0.846054
0.518059
cell.go
starcoder
package paseto import ( "encoding/json" "fmt" "time" ) // JSONToken defines standard token payload claims and allows for additional // claims to be added. All of the standard claims are optional. type JSONToken struct { // Audience identifies the intended recipients of the token. // It should be a string or a URI and is case sensitive. Audience string // Issuer identifies the entity which issued the token. // It should be a string or a URI and is case sensitive. Issuer string // JTI is a globally unique identifier for the token. It must be created in // such a way as to ensure that there is negligible probability that the same // value will be used in another token. Jti string // Subject identifies the principal entity that is the subject of the token. // For example, for an authentication token, the subject might be the user ID // of a person. Subject string // Expiration is a time on or after which the token must not be accepted for processing. Expiration time.Time // IssuedAt is the time at which the token was issued. IssuedAt time.Time // NotBefore is a time on or before which the token must not be accepted for // processing. NotBefore time.Time claims map[string]string } // Get returns the value of a custom claim, as a string. // If there is no such claim, an empty string is returned. func (t *JSONToken) Get(key string) string { return t.claims[key] } // Set sets the value of a custom claim to the string value provided. func (t *JSONToken) Set(key string, value string) { if t.claims == nil { t.claims = make(map[string]string) } t.claims[key] = value } // MarshalJSON implements json.Marshaler interface func (t JSONToken) MarshalJSON() ([]byte, error) { if t.claims == nil { t.claims = make(map[string]string) } if t.Audience != "" { t.claims["aud"] = t.Audience } if t.Issuer != "" { t.claims["iss"] = t.Issuer } if t.Jti != "" { t.claims["jti"] = t.Jti } if t.Subject != "" { t.claims["sub"] = t.Subject } if !t.Expiration.IsZero() { t.claims["exp"] = t.Expiration.Format(time.RFC3339) } if !t.IssuedAt.IsZero() { t.claims["iat"] = t.IssuedAt.Format(time.RFC3339) } if !t.NotBefore.IsZero() { t.claims["nbf"] = t.NotBefore.Format(time.RFC3339) } return json.Marshal(t.claims) } // UnmarshalJSON implements json.Unmarshaler interface func (t *JSONToken) UnmarshalJSON(data []byte) error { var err error if err := json.Unmarshal(data, &t.claims); err != nil { return err } t.Audience = t.claims["aud"] t.Issuer = t.claims["iss"] t.Jti = t.claims["jti"] t.Subject = t.claims["sub"] if timeStr, ok := t.claims["exp"]; ok { t.Expiration, err = time.Parse(time.RFC3339, timeStr) if err != nil { return fmt.Errorf(`incorrect time format for Expiration field "%s". It should be RFC3339`, timeStr) } } if timeStr, ok := t.claims["iat"]; ok { t.IssuedAt, err = time.Parse(time.RFC3339, timeStr) if err != nil { return fmt.Errorf(`incorrect time format for IssuedAt field "%s". It should be RFC3339`, timeStr) } } if timeStr, ok := t.claims["nbf"]; ok { t.NotBefore, err = time.Parse(time.RFC3339, timeStr) if err != nil { return fmt.Errorf(`incorrect time format for NotBefore field "%s". It should be RFC3339`, timeStr) } } return nil } // Validate validates a token with the given validators. If no validators are // specified, then by default it validates the token with ValidAt(time.Now()), // which checks IssuedAt, NotBefore and Expiration fields against the current // time. func (t *JSONToken) Validate(validators ...Validator) error { var err error if len(validators) == 0 { validators = append(validators, ValidAt(time.Now())) } for _, validator := range validators { if err = validator(t); err != nil { return err } } return nil }
vendor/github.com/o1egl/paseto/json_token.go
0.660063
0.456531
json_token.go
starcoder
package main import ( "fmt" "strings" ) // R1: representation is a slice of int8 digits of -1, 0, or 1. // digit at index 0 is least significant. zero value of type is // representation of the number 0. type bt []int8 // R2: string conversion: // btString is a constructor. valid input is a string of any length // consisting of only '+', '-', and '0' characters. // leading zeros are allowed but are trimmed and not represented. // false return means input was invalid. func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } // String method converts the other direction, returning a string of // '+', '-', and '0' characters representing the number. func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } // R3: integer conversion // int chosen as "native integer" // btInt is a constructor like btString. func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } // Int method converts the other way, returning the value as an int type. // !ok means overflow occurred during conversion, not necessarily that the // value is not representable as an int. (Of course there are other ways // of doing it but this was chosen as "reasonable.") func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } // R4: negation, addition, and multiplication func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } } //\Balanced-ternary\balanced-ternary.go
tasks/Balanced-ternary/balanced-ternary.go
0.559892
0.484258
balanced-ternary.go
starcoder
package main import ( // "fmt" // tests // "errors" // "github.com/go-gl/gl/v3.3-core/gl" // "github.com/go-gl/glfw/v3.2/glfw" "github.com/go-gl/mathgl/mgl32" // "github.com/mki1967/go-mki3d/mki3d" // "github.com/mki1967/go-mki3d/glmki3d" "math" "math/rand" ) // Random position in the game stage box with the margin offset from the borders func (game *Mki3dGame) RandPosition(margin float32) mgl32.Vec3 { m := mgl32.Vec3{margin, margin, margin} v1 := game.VMin.Add(m) v2 := game.VMax.Sub(m) return RandPosition(v1, v2) } // Random position in the box [vmin, vmax] func RandPosition(vmin, vmax mgl32.Vec3) mgl32.Vec3 { return mgl32.Vec3{ rand.Float32()*(vmax[0]-vmin[0]) + vmin[0], rand.Float32()*(vmax[1]-vmin[1]) + vmin[1], rand.Float32()*(vmax[2]-vmin[2]) + vmin[2], } } // RotHVType represents sequence of two rotations: // by the angle XY on XY-plane and by the angle YZ on YZ-plane // (in degrees) type RotHVType struct { XZ float64 YZ float64 } // Rotate XZ by angle (in degrees) func (rot *RotHVType) RotateXZ(angle float64) { rot.XZ = math.Remainder(rot.XZ+angle, 360) } // Rotate YZ by angle (in degrees) an clamping result to [-90,90] func (rot *RotHVType) RotateYZ(angle float64) { rot.YZ = math.Remainder(rot.YZ+angle, 360) if rot.YZ < -90 { rot.YZ = -90 } if rot.YZ > 90 { rot.YZ = 90 } } const degToRadians = math.Pi / 180 func (rot *RotHVType) WorldRotatedVector(vector mgl32.Vec3) mgl32.Vec3 { c1 := float32(math.Cos(rot.XZ * degToRadians)) s1 := float32(math.Sin(rot.XZ * degToRadians)) c2 := float32(math.Cos(rot.YZ * degToRadians)) s2 := float32(math.Sin(rot.YZ * degToRadians)) return mgl32.Vec3{ c1*vector[0] - s1*s2*vector[1] - s1*c2*vector[2], c2*vector[1] - s2*vector[2], s1*vector[0] + c1*s2*vector[1] + c1*c2*vector[2], } } func (rot *RotHVType) ViewerRotatedVector(vector mgl32.Vec3) mgl32.Vec3 { c1 := float32(math.Cos(-rot.XZ * degToRadians)) s1 := float32(math.Sin(-rot.XZ * degToRadians)) c2 := float32(math.Cos(-rot.YZ * degToRadians)) s2 := float32(math.Sin(-rot.YZ * degToRadians)) return mgl32.Vec3{ c1*vector[0] - s1*vector[2], -s2*s1*vector[0] + c2*vector[1] - s2*c1*vector[2], c2*s1*vector[0] + s2*vector[1] + c2*c1*vector[2], } } func RandRotated(vec mgl32.Vec3) mgl32.Vec3 { var rot RotHVType rot.XZ = rand.Float64() * 360 rot.YZ = rand.Float64() * 360 return rot.WorldRotatedVector(vec) }
mki3dgame/gamemath.go
0.724481
0.485295
gamemath.go
starcoder
package runtime import ( "bytes" "fmt" "os/exec" "strings" ) type DefaultRuntime struct { scope *Scope } func CreateDefaultRuntime() *DefaultRuntime { return &DefaultRuntime{ scope: CreateScope(nil, ScopeTypeGlobal), } } func (runtime *DefaultRuntime) Add(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeNumber, Value: left.Value.(int) + right.Value.(int), } case ValueTypeString: return &Value{ Type: ValueTypeString, Value: left.Value.(string) + right.Value.(string), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Subtract(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeNumber, Value: left.Value.(int) - right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Multiply(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeNumber, Value: left.Value.(int) * right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Divide(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeNumber, Value: left.Value.(int) / right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Modulo(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeNumber, Value: left.Value.(int) % right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Equals(left *Value, right *Value) *Value { if left.Type != right.Type { return &Value{ Type: ValueTypeBool, Value: false, } } equal := false switch left.Type { case ValueTypeNumber: equal = left.Value.(int) == right.Value.(int) case ValueTypeString: equal = left.Value.(string) == right.Value.(string) case ValueTypeBool: equal = left.Value.(bool) == right.Value.(bool) } return &Value{ Type: ValueTypeBool, Value: equal, } } func (runtime *DefaultRuntime) NotEquals(left *Value, right *Value) *Value { if left.Type != right.Type { return &Value{ Type: ValueTypeBool, Value: false, } } equal := false switch left.Type { case ValueTypeNumber: equal = left.Value.(int) != right.Value.(int) case ValueTypeString: equal = left.Value.(string) != right.Value.(string) case ValueTypeBool: equal = left.Value.(bool) != right.Value.(bool) } return &Value{ Type: ValueTypeBool, Value: equal, } } func (runtime *DefaultRuntime) GreaterThan(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeBool, Value: left.Value.(int) > right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) GreaterThanOrEqual(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeBool, Value: left.Value.(int) >= right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) LessThan(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeBool, Value: left.Value.(int) < right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) LessThanOrEqual(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeBool, Value: left.Value.(int) <= right.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) And(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeBool: return &Value{ Type: ValueTypeBool, Value: left.Value.(bool) && right.Value.(bool), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Or(left *Value, right *Value) *Value { runtime.assertSameType(left, right) switch left.Type { case ValueTypeBool: return &Value{ Type: ValueTypeBool, Value: left.Value.(bool) || right.Value.(bool), } default: panic(fmt.Errorf("invalid operation for type %s", left.Type)) } } func (runtime *DefaultRuntime) Not(operand *Value) *Value { switch operand.Type { case ValueTypeBool: return &Value{ Type: ValueTypeBool, Value: !operand.Value.(bool), } default: panic(fmt.Errorf("invalid operation for type %s", operand.Type)) } } func (runtime *DefaultRuntime) Negative(operand *Value) *Value { switch operand.Type { case ValueTypeNumber: return &Value{ Type: ValueTypeNumber, Value: -operand.Value.(int), } default: panic(fmt.Errorf("invalid operation for type %s", operand.Type)) } } func (runtime *DefaultRuntime) Shell(script string) { cmd := exec.Command("/bin/bash") var stdout, stderr bytes.Buffer // Always end the script with a newline to ensure it's executed if !strings.HasSuffix(script, "\n") { script += "\n" } cmd.Stdin = strings.NewReader(script) cmd.Stdout = &stdout cmd.Stderr = &stderr cmd.Run() context := runtime.Resolve("context").Value.(Object) if shellValue, ok := context["shell"]; ok { shell := shellValue.Value.(Object) shell["stdout"].Value = strings.TrimSpace(stdout.String()) shell["stderr"].Value = strings.TrimSpace(stderr.String()) shell["status"].Value = cmd.ProcessState.ExitCode() } } func (runtime *DefaultRuntime) ResolveEscapes(value string) string { value = strings.ReplaceAll(value, "\\\"", "\"") value = strings.ReplaceAll(value, "\\t", "\t") value = strings.ReplaceAll(value, "\\n", "\n") value = strings.ReplaceAll(value, "\\$", "$") return value } func (runtime *DefaultRuntime) ShellFormat(value *Value) string { switch value.Type { case ValueTypeNone: return "" case ValueTypeNumber: return fmt.Sprintf("%d", value.Value) case ValueTypeString: return fmt.Sprintf("%s", value.Value) case ValueTypeBool: return fmt.Sprintf("%t", value.Value) case ValueTypeArray: array := value.Value.(Array) var builder strings.Builder for i, x := range array { if i > 0 { builder.WriteString(" ") } builder.WriteString(runtime.ShellFormat(x)) } return builder.String() default: panic(fmt.Errorf("cannot format value '%s' for current shell", value.String())) } } func (runtime *DefaultRuntime) Index(left *Value, right *Value) *Value { switch left.Type { case ValueTypeObject: if right.Type != ValueTypeString { panic(fmt.Errorf("an object can only be indexed with a string")) } object := left.Value.(Object) if value, ok := object[right.Value.(string)]; ok { return value } else { return &Value{Type: ValueTypeNone} } case ValueTypeArray: if right.Type != ValueTypeNumber { panic(fmt.Errorf("an array can only be indexed with a number")) } index := right.Value.(int) array := left.Value.(Array) if index >= 0 && index < len(array) { return array[index] } else { panic(fmt.Errorf("index is out of bounds")) } case ValueTypeString: if right.Type != ValueTypeNumber { panic(fmt.Errorf("an array can only be indexed with a number")) } index := right.Value.(int) text := left.Value.(string) if index >= 0 && index < len(text) { return &Value{Type: ValueTypeString, Value: string(text[index])} } else { panic(fmt.Errorf("index is out of bounds")) } default: panic(fmt.Errorf("cannot index a value of type '%s'", left.Type)) } } func (runtime *DefaultRuntime) Selector(value *Value, identifier string) *Value { switch value.Type { case ValueTypeObject: object := value.Value.(Object) if value, ok := object[identifier]; ok { return value } else { return &Value{Type: ValueTypeNone} } case ValueTypeArray: array := value.Value.(Array) switch identifier { case "length": return &Value{Type: ValueTypeNumber, Value: len(array)} default: panic(fmt.Errorf("arrays have no such property '%s'", identifier)) } case ValueTypeString: text := value.Value.(string) switch identifier { case "length": return &Value{Type: ValueTypeNumber, Value: len(text)} default: panic(fmt.Errorf("strings have no such property '%s'", identifier)) } default: panic(fmt.Errorf("invalid operand on non-object '%s'", value.Type)) } } func (runtime *DefaultRuntime) Define(identifier string, value *Value) { runtime.scope.Define(identifier, value) } func (runtime *DefaultRuntime) Resolve(identifier string) *Value { value := runtime.scope.Lookup(identifier) if value == nil { panic(fmt.Errorf("'%s' is undefined", identifier)) } return value } func (runtime *DefaultRuntime) SetScope(scope *Scope) { runtime.scope = scope } func (runtime *DefaultRuntime) Scope() *Scope { return runtime.scope } func (runtime *DefaultRuntime) PushScope(scopeType ScopeType) { runtime.scope = runtime.scope.CreateScope(scopeType) if scopeType == ScopeTypeFunction || scopeType == ScopeTypeRuleFunction || scopeType == ScopeTypeRule { context := make(Object) shell := make(Object) shell["stdout"] = &Value{ Type: ValueTypeString, Value: "", } shell["stderr"] = &Value{ Type: ValueTypeString, Value: "", } shell["status"] = &Value{ Type: ValueTypeNumber, Value: 0, } context["shell"] = &Value{ Type: ValueTypeObject, Value: shell, } if scopeType == ScopeTypeRule || scopeType == ScopeTypeRuleFunction { context["input"] = &Value{ Type: ValueTypeArray, Value: make(Array, 0), } context["output"] = &Value{ Type: ValueTypeArray, Value: make(Array, 0), } } value := &Value{Type: ValueTypeObject, Value: context} runtime.Define("context", value) } } func (runtime *DefaultRuntime) PopScope() { if runtime.scope.ParentScope == nil { panic(fmt.Errorf("cannot pop outside global scope")) } runtime.scope = runtime.scope.ParentScope } func (runtime *DefaultRuntime) assertSameType(left *Value, right *Value) { if left.Type != right.Type { panic(fmt.Errorf("invalid operation between two values of different types")) } }
runtime/defaultruntime.go
0.68679
0.426531
defaultruntime.go
starcoder
package papernet var arxivCategories = map[string]string{ "stat.AP": "Statistics - Applications", "stat.CO": "Statistics - Computation", "stat.ML": "Statistics - Machine Learning", "stat.ME": "Statistics - Methodology", "stat.TH": "Statistics - Theory", "q-bio.BM": "Quantitative Biology - Biomolecules", "q-bio.CB": "Quantitative Biology - Cell Behavior", "q-bio.GN": "Quantitative Biology - Genomics", "q-bio.MN": "Quantitative Biology - Molecular Networks", "q-bio.NC": "Quantitative Biology - Neurons and Cognition", "q-bio.OT": "Quantitative Biology - Other", "q-bio.PE": "Quantitative Biology - Populations and Evolution", "q-bio.QM": "Quantitative Biology - Quantitative Methods", "q-bio.SC": "Quantitative Biology - Subcellular Processes", "q-bio.TO": "Quantitative Biology - Tissues and Organs", "cs.AR": "Computer Science - Architecture", "cs.AI": "Computer Science - Artificial Intelligence", "cs.CL": "Computer Science - Computation and Language", "cs.CC": "Computer Science - Computational Complexity", "cs.CE": "Computer Science - Computational Engineering; Finance; and Science", "cs.CG": "Computer Science - Computational Geometry", "cs.GT": "Computer Science - Computer Science and Game Theory", "cs.CV": "Computer Science - Computer Vision and Pattern Recognition", "cs.CY": "Computer Science - Computers and Society", "cs.CR": "Computer Science - Cryptography and Security", "cs.DS": "Computer Science - Data Structures and Algorithms", "cs.DB": "Computer Science - Databases", "cs.DL": "Computer Science - Digital Libraries", "cs.DM": "Computer Science - Discrete Mathematics", "cs.DC": "Computer Science - Distributed; Parallel; and Cluster Computing", "cs.GL": "Computer Science - General Literature", "cs.GR": "Computer Science - Graphics", "cs.HC": "Computer Science - Human-Computer Interaction", "cs.IR": "Computer Science - Information Retrieval", "cs.IT": "Computer Science - Information Theory", "cs.LG": "Computer Science - Learning", "cs.LO": "Computer Science - Logic in Computer Science", "cs.MS": "Computer Science - Mathematical Software", "cs.MA": "Computer Science - Multiagent Systems", "cs.MM": "Computer Science - Multimedia", "cs.NI": "Computer Science - Networking and Internet Architecture", "cs.NE": "Computer Science - Neural and Evolutionary Computing", "cs.NA": "Computer Science - Numerical Analysis", "cs.OS": "Computer Science - Operating Systems", "cs.OH": "Computer Science - Other", "cs.PF": "Computer Science - Performance", "cs.PL": "Computer Science - Programming Languages", "cs.RO": "Computer Science - Robotics", "cs.SE": "Computer Science - Software Engineering", "cs.SD": "Computer Science - Sound", "cs.SC": "Computer Science - Symbolic Computation", "nlin.AO": "Nonlinear Sciences - Adaptation and Self-Organizing Systems", "nlin.CG": "Nonlinear Sciences - Cellular Automata and Lattice Gases", "nlin.CD": "Nonlinear Sciences - Chaotic Dynamics", "nlin.SI": "Nonlinear Sciences - Exactly Solvable and Integrable Systems", "nlin.PS": "Nonlinear Sciences - Pattern Formation and Solitons", "math.AG": "Mathematics - Algebraic Geometry", "math.AT": "Mathematics - Algebraic Topology", "math.AP": "Mathematics - Analysis of PDEs", "math.CT": "Mathematics - Category Theory", "math.CA": "Mathematics - Classical Analysis and ODEs", "math.CO": "Mathematics - Combinatorics", "math.AC": "Mathematics - Commutative Algebra", "math.CV": "Mathematics - Complex Variables", "math.DG": "Mathematics - Differential Geometry", "math.DS": "Mathematics - Dynamical Systems", "math.FA": "Mathematics - Functional Analysis", "math.GM": "Mathematics - General Mathematics", "math.GN": "Mathematics - General Topology", "math.GT": "Mathematics - Geometric Topology", "math.GR": "Mathematics - Group Theory", "math.HO": "Mathematics - History and Overview", "math.IT": "Mathematics - Information Theory", "math.KT": "Mathematics - K-Theory and Homology", "math.LO": "Mathematics - Logic", "math.MP": "Mathematics - Mathematical Physics", "math.MG": "Mathematics - Metric Geometry", "math.NT": "Mathematics - Number Theory", "math.NA": "Mathematics - Numerical Analysis", "math.OA": "Mathematics - Operator Algebras", "math.OC": "Mathematics - Optimization and Control", "math.PR": "Mathematics - Probability", "math.QA": "Mathematics - Quantum Algebra", "math.RT": "Mathematics - Representation Theory", "math.RA": "Mathematics - Rings and Algebras", "math.SP": "Mathematics - Spectral Theory", "math.ST": "Mathematics - Statistics", "math.SG": "Mathematics - Symplectic Geometry", "astro-ph": "Astrophysics", "cond-mat.dis-nn": "Physics - Disordered Systems and Neural Networks", "cond-mat.mes-hall": "Physics - Mesoscopic Systems and Quantum Hall Effect", "cond-mat.mtrl-sci": "Physics - Materials Science", "cond-mat.other": "Physics - Other", "cond-mat.soft": "Physics - Soft Condensed Matter", "cond-mat.stat-mech": "Physics - Statistical Mechanics", "cond-mat.str-el": "Physics - Strongly Correlated Electrons", "cond-mat.supr-con": "Physics - Superconductivity", "gr-qc": "General Relativity and Quantum Cosmology", "hep-ex": "High Energy Physics - Experiment", "hep-lat": "High Energy Physics - Lattice", "hep-ph": "High Energy Physics - Phenomenology", "hep-th": "High Energy Physics - Theory", "math-ph": "Mathematical Physics", "nucl-ex": "Nuclear Experiment", "nucl-th": "Nuclear Theory", "physics.acc-ph": "Physics - Accelerator Physics", "physics.ao-ph": "Physics - Atmospheric and Oceanic Physics", "physics.atom-ph": "Physics - Atomic Physics", "physics.atm-clus": "Physics - Atomic and Molecular Clusters", "physics.bio-ph": "Physics - Biological Physics", "physics.chem-ph": "Physics - Chemical Physics", "physics.class-ph": "Physics - Classical Physics", "physics.comp-ph": "Physics - Computational Physics", "physics.data-an": "Physics - Data Analysis; Statistics and Probability", "physics.flu-dyn": "Physics - Fluid Dynamics", "physics.gen-ph": "Physics - General Physics", "physics.geo-ph": "Physics - Geophysics", "physics.hist-ph": "Physics - History of Physics", "physics.ins-det": "Physics - Instrumentation and Detectors", "physics.med-ph": "Physics - Medical Physics", "physics.optics": "Physics - Optics", "physics.ed-ph": "Physics - Physics Education", "physics.soc-ph": "Physics - Physics and Society", "physics.plasm-ph": "Physics - Plasma Physics", "physics.pop-ph": "Physics - Popular Physics", "physics.space-ph": "Physics - Space Physics", "quant-ph": "Quantum Physics", }
arxiv_categories.go
0.702836
0.685601
arxiv_categories.go
starcoder
package stream import ( "reflect" "github.com/wesovilabs/koazee/errors" ) // Output structure for returning single values type Output struct { value reflect.Value error *errors.Error } // Val reurn the Output of the Stream func (o Output) Val() interface{} { v := (o.value) if !o.value.IsValid() { return nil } return v.Interface() } // Err reurn the error in the Stream func (o Output) Err() *errors.Error { if o.error == nil || o.error.Code() == "" { return nil } return o.error } // Bool parses the Output of the Stream as a bool type func (o Output) Bool() bool { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Bool { return o.value.Interface().(bool) } return false } // String parses the Output of the Stream as a string type func (o Output) String() string { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.String { return o.value.Interface().(string) } return "" } // Int parses the Output of the Stream as a int type func (o Output) Int() int { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Int { return o.value.Interface().(int) } return 0 } // Int8 parses the Output of the Stream as a int8 type func (o Output) Int8() int8 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Int8 { return o.value.Interface().(int8) } return 0 } // Int16 parses the Output of the Stream as a int16 type func (o Output) Int16() int16 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Int16 { return o.value.Interface().(int16) } return 0 } // Int32 parses the Output of the Stream as a int32 type func (o Output) Int32() int32 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Int32 { return o.value.Interface().(int32) } return 0 } // Int64 parses the Output of the Stream as a int64 type func (o Output) Int64() int64 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Int64 { return o.value.Interface().(int64) } return 0 } // Uint parses the Output of the Stream as a Uint type func (o Output) Uint() uint { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Uint { return o.value.Interface().(uint) } return 0 } // Uint8 parses the Output of the Stream as a Uint type8 func (o Output) Uint8() uint8 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Uint8 { return o.value.Interface().(uint8) } return 0 } // Uint16 parses the Output of the Stream as a Uint type16 func (o Output) Uint16() uint16 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Uint16 { return o.value.Interface().(uint16) } return 0 } // Uint32 parses the Output of the Stream as a Uint type32 func (o Output) Uint32() uint32 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Uint32 { return o.value.Interface().(uint32) } return 0 } // Uint64 parses the Output of the Stream as a Uint type64 func (o Output) Uint64() uint64 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Uint64 { return o.value.Interface().(uint64) } return 0 } // Float32 parses the Output of the Stream as a Uint float32 func (o Output) Float32() float32 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Float32 { return o.value.Interface().(float32) } return 0.00 } // Float64 parses the Output of the Stream as a Uint float64 func (o Output) Float64() float64 { if reflect.TypeOf(o.value.Interface()).Kind() == reflect.Float64 { return o.value.Interface().(float64) } return 0.00 } type lazyOp interface { run(Stream) Stream } // Stream stream structure type Stream struct { items interface{} itemsValue reflect.Value itemsType reflect.Type itemsLen int err *errors.Error operations []lazyOp } func (s Stream) run() Stream { if len(s.operations) == 0 { return s } s = s.operations[0].run(s) if s.err != nil { return s } s.operations = s.operations[1:] return s.run() } // New creates a Stream with the provided array of elements func New(items interface{}) Stream { s := Stream{} if items != nil { itemsValue := reflect.ValueOf(items) itemsType := reflect.TypeOf(items).Elem() s.items = items s.itemsType = itemsType s.itemsValue = itemsValue s.itemsLen = itemsValue.Len() } return s } func (s Stream) withItemsValue(items reflect.Value) Stream { s.itemsValue = items s.items = items.Interface() s.itemsLen = items.Len() return s } // Error initialize the Stream with error func Error(err *errors.Error) Stream { return Stream{ err: err, } }
stream/stream.go
0.719482
0.499878
stream.go
starcoder
package byteconv import ( "fmt" "strconv" "strings" "unicode" ) const ( BYTE float64 = 1 << (10 * iota) KiB // 1024 MiB // 1048576 GiB // 1073741824 TiB // 1099511627776 (exceeds 1 << 32) PiB // 1125899906842624 EiB // 1152921504606846976 KB float64 = 1e3 // 1000 MB float64 = 1e6 // 1000000 GB float64 = 1e9 // 1000000000 TB float64 = 1e12 // 100000000000 PB float64 = 1e15 // 1000000000000000 EB float64 = 1e18 // 1000000000000000000 ) // BytesToBinarySize returns a human-readable IEC (binary) format string of the form 10MiB, 12.5KiB. // History https://en.wikipedia.org/wiki/Mebibyte // The following units are available: // EiB: exbibyte // PiB: pebibyte // TiB: tebibyte // GiB: gibibyte // MiB: mebibyte // KiB: kibibyte // B: Byte // The unit that results in the smallest number greater than or equal to 1 is always chosen. func BytesToBinarySize(bytes float64) string { if bytes <= 0 { return "0" } var unit string var res float64 switch { case bytes >= EiB: unit = "EiB" res = bytes / EiB case bytes >= PiB: unit = "PiB" res = bytes / PiB case bytes >= TiB: unit = "TiB" res = bytes / TiB case bytes >= GiB: unit = "GiB" res = bytes / GiB case bytes >= MiB: unit = "MiB" res = bytes / MiB case bytes >= KiB: unit = "KiB" res = bytes / KiB case bytes >= BYTE: unit = "B" res = bytes } strRes := strconv.FormatFloat(res, 'f', 1, 64) strRes = strings.TrimSuffix(strRes, ".0") return strRes + unit } // StringBinaryToBytes parses a string formatted by ByteSize as bytes. // Note binary-prefixed and SI prefixed units both mean a base-2 units // KiB = 1024 // MiB = 1024 * K // GiB = 1024 * M // TiB = 1024 * G // PiB = 1024 * T // EiB = 1024 * P func StringToBytes(s string) float64 { s = strings.TrimSpace(s) s = strings.ToUpper(s) i := strings.IndexFunc(s, unicode.IsLetter) if i == -1 { return 0 } bytesString, multiple := s[:i], s[i:] bytes, err := strconv.ParseFloat(bytesString, 64) if err != nil || bytes <= 0 { return 0 } switch multiple { case "EIB": return bytes * EiB case "EB": return bytes * EB case "PIB": return bytes * PiB case "PB": return bytes * PB case "TIB": return bytes * TiB case "TB": return bytes * TB case "GIB": return bytes * GiB case "GB": return bytes * GB case "MIB": return bytes * MiB case "MB": return bytes * MB case "KIB": return bytes * KiB case "KB": return bytes * KB case "B": return bytes default: return 0 } } // BytesSize returns a human-readable in 2 formats: IEC (binary) or SI (decimal) // Binary string of the form 10MiB, 12.5KiB // Decimal string of the form 10MB, 12.5KB // The precision prec controls the number of digits //The special precision -1 uses the smallest number of digits func BytesSize(bytes float64, format string, prec int) string { if bytes <= 0 { return "0" } // Default format is decimal: MB, GB value := 1000.0 resFormat := "" // Binary format: MiB, GiB if format == "binary" { value = 1024.0 resFormat = "i" } if bytes < value { strRes := strconv.FormatFloat(bytes, 'f', prec, 64) return strings.TrimSuffix(strRes, ".0") + "B" } divider, exp := value, 0 for n := bytes / value; n >= value; n /= value { divider *= value exp++ } strRes := strconv.FormatFloat(bytes/divider, 'f', prec, 64) if prec == 0 { strRes = strings.TrimSuffix(strRes, ".0") } return strRes + fmt.Sprintf("%c%sB", "KMGTPE"[exp], resFormat) }
byteconv.go
0.654895
0.429489
byteconv.go
starcoder
package data import ( "encoding/json" "errors" "fmt" "strconv" "strings" ) // Type denotes a data type type Type int //var intSize = strconv.IntSize const ( TypeUnknown Type = iota // interface{} TypeAny // interface{} // simple types TypeString // string TypeInt // int TypeInt32 // int32 TypeInt64 // int64 TypeFloat32 // float32 TypeFloat64 // float64 TypeBool // bool TypeObject // map[string]interface{} TypeBytes // []byte // compound types TypeParams // map[string]string TypeArray // []interface{} TypeMap // map[interface{}]interface{} //Special Type TypeConnection ) var types = [...]string{ "unknown", "any", "string", "int", "int32", "int64", "float32", "float64", "bool", "object", "bytes", "params", "array", "map", "connection", } func (t Type) String() string { return types[t] } // IsSimple returns wither a type is simple func (t Type) IsSimple() bool { return t > 1 && t < 8 } var names = map[Type]string{ TypeUnknown: "TypeUnknown", TypeAny: "TypeAny", TypeString: "TypeString", TypeInt: "TypeInt", TypeInt32: "TypeInt32", TypeInt64: "TypeInt64", TypeFloat32: "TypeFloat32", TypeFloat64: "TypeFloat64", TypeBool: "TypeBool", TypeObject: "TypeObject", TypeBytes: "TypeBytes", TypeParams: "TypeParams", TypeArray: "TypeArray", TypeMap: "TypeMap", TypeConnection: "TypeConnection", } // Name returns the name of the type func (t Type) Name() string { return names[t] } // ToTypeEnum get the data type that corresponds to the specified name func ToTypeEnum(typeStr string) (Type, error) { switch strings.ToLower(typeStr) { case "any": return TypeAny, nil case "string": return TypeString, nil case "int", "integer": return TypeInt, nil case "int32": return TypeInt32, nil case "int64", "long": return TypeInt64, nil case "float32", "float": return TypeFloat32, nil case "float64", "double": return TypeFloat64, nil case "bool", "boolean": return TypeBool, nil case "object": return TypeObject, nil case "bytes": return TypeBytes, nil case "params": return TypeParams, nil case "array": return TypeArray, nil case "map": return TypeMap, nil case "connection": return TypeConnection, nil default: return TypeUnknown, errors.New("unknown type: " + typeStr) } } // GetType get the Type of the supplied value func GetType(val interface{}) (Type, error) { switch t := val.(type) { case string: return TypeString, nil case int: if strconv.IntSize == 64 { return TypeInt64, nil } return TypeInt, nil case int32: return TypeInt32, nil case int64: return TypeInt64, nil case float32: return TypeFloat32, nil case float64: return TypeFloat64, nil case json.Number: if strings.Contains(t.String(), ".") { return TypeFloat64, nil } else { return TypeInt64, nil } case bool: return TypeBool, nil case map[string]interface{}: return TypeObject, nil case []interface{}: return TypeArray, nil case map[string]string: return TypeParams, nil case []byte: return TypeBytes, nil default: return TypeUnknown, fmt.Errorf("unable to determine type of %#v", t) } } func ToTypeFromGoRep(strType string) Type { dt := TypeUnknown switch strType { case "interface{}", "interface {}": dt = TypeAny case "string": dt = TypeString case "int": dt = TypeInt case "int32": dt = TypeInt32 case "int64": dt = TypeInt64 case "float32": dt = TypeFloat32 case "float64": dt = TypeFloat64 case "bool": dt = TypeBool case "map[string]interface{}": dt = TypeObject case "[]byte": dt = TypeBytes case "map[string]string": dt = TypeParams case "connection.Manager": dt = TypeConnection } return dt } func IsSimpleType(val interface{}) bool { switch val.(type) { case string, int, int32, int64, float32, float64, json.Number, bool: return true default: return false } } var typeConverter TypeConverter func SetAttributeTypeConverter(converter TypeConverter) { typeConverter = converter } type TypeConverter func(value interface{}, toType Type) (interface{}, error)
data/types.go
0.621885
0.419707
types.go
starcoder
package monotone import ( compgeo "github.com/200sc/go-compgeo" "github.com/200sc/go-compgeo/dcel" "github.com/200sc/go-compgeo/dcel/pointLoc" "github.com/200sc/go-compgeo/geom" "github.com/200sc/go-compgeo/search" "github.com/200sc/go-compgeo/search/tree" ) // DoubleIntervalTree converts a monotonized f into a // structure that can be pointlocated on to determine if // a given point exists inside or outside the face. // Because this is a monotone polygon we don't actually // make an interval tree, we just make bsts. The intervals // we use will be non-overlapping except at vertices func NewDoubleIntervalTree(f *dcel.Face, dc *dcel.DCEL) (pointLoc.LocatesPoints, error) { var e *dcel.Edge for e = f.Outer; VertexType(e.Origin, dc) != START; e = e.Next { } // e is now the edge whose origin is the start vertex. leftTree := tree.New(tree.RedBlack) rightTree := tree.New(tree.RedBlack) st := e leftTree.Insert(interval{st}) tree := leftTree for e := st.Next; e != st; e = e.Next { if VertexType(e.Origin, dc) == END { tree = rightTree } tree.Insert(interval{e}) } return DblIntervalTree{leftTree, rightTree, f}, nil } type DblIntervalTree struct { leftTree, rightTree search.Dynamic f *dcel.Face } func (dit DblIntervalTree) PointLocate(vs ...float64) (*dcel.Face, error) { if len(vs) < 2 { return nil, compgeo.InsufficientDimensionsError{} } found, i1 := dit.leftTree.Search(yVal(vs[1])) if !found { return nil, nil } found2, i2 := dit.rightTree.Search(yVal(vs[1])) if !found2 { return nil, nil } e1 := i1.(interval).Edge e2 := i2.(interval).Edge pt := geom.NewPoint(vs[0], vs[1], 0) // Consider-- this could probably be a direct comparison // to pointAt instead of a cross product c1 := geom.VertCross2D(pt, e1.Origin, e1.Twin.Origin) c2 := geom.VertCross2D(pt, e2.Origin, e2.Twin.Origin) // Check that either c1 or c2 is 0, or otherwise // that the signs of c1 and c2 are different. // We don't actually care if the left and right trees are on the left // and right respectively. If we are on the same side of both trees, // we aren't in the polygon. If we are on different sides of both trees, // as we can't both be to the left of the (actual) left tree and right // of the (actual) right tree, we'll be in the polygon. if c1 == 0 || c2 == 0 { return dit.f, nil } else if c1*c2 < 0 { return dit.f, nil } return nil, nil } type interval struct { *dcel.Edge } func (i interval) Key() search.Comparable { return i } func (i interval) Val() search.Equalable { return i } func (i interval) Equals(e search.Equalable) bool { switch i2 := e.(type) { case interval: return i == i2 } return false } func (i interval) Compare(s interface{}) search.CompareResult { switch i2 := s.(type) { case interval: if geom.F64eq(i.Origin.Y(), i2.Origin.Y()) { if geom.F64eq(i.Twin.Origin.Y(), i2.Twin.Origin.Y()) { return search.Equal } else if i.Twin.Origin.Y() < i2.Twin.Origin.Y() { return search.Less } return search.Greater } else if i.Origin.Y() < i2.Origin.Y() { return search.Less } return search.Greater case yVal: return i2.Compare(i) } return search.Invalid } type yVal float64 func (yv yVal) Compare(s interface{}) search.CompareResult { switch i := s.(type) { case interval: y := float64(yv) if geom.F64eq(y, i.Origin.Y()) || geom.F64eq(y, i.Twin.Origin.Y()) { return search.Equal } c1 := y < i.Origin.Y() c2 := y > i.Twin.Origin.Y() c3 := y > i.Origin.Y() c4 := y < i.Twin.Origin.Y() if (c1 && c2) || (c3 && c4) { return search.Equal } if c1 && c4 { return search.Less } return search.Greater } return search.Invalid }
dcel/pointLoc/monotone/doubleInsertionTree.go
0.737631
0.423637
doubleInsertionTree.go
starcoder
package ln import ( "math" "math/rand" ) type Vector struct { X, Y, Z float64 } func RandomUnitVector() Vector { for { x := rand.Float64()*2 - 1 y := rand.Float64()*2 - 1 z := rand.Float64()*2 - 1 if x*x+y*y+z*z > 1 { continue } return Vector{x, y, z}.Normalize() } } func (a Vector) Length() float64 { return math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z) } func (a Vector) Distance(b Vector) float64 { return a.Sub(b).Length() } func (a Vector) LengthSquared() float64 { return a.X*a.X + a.Y*a.Y + a.Z*a.Z } func (a Vector) DistanceSquared(b Vector) float64 { return a.Sub(b).LengthSquared() } func (a Vector) Dot(b Vector) float64 { return a.X*b.X + a.Y*b.Y + a.Z*b.Z } func (a Vector) Cross(b Vector) Vector { x := a.Y*b.Z - a.Z*b.Y y := a.Z*b.X - a.X*b.Z z := a.X*b.Y - a.Y*b.X return Vector{x, y, z} } func (a Vector) Normalize() Vector { d := a.Length() return Vector{a.X / d, a.Y / d, a.Z / d} } func (a Vector) Add(b Vector) Vector { return Vector{a.X + b.X, a.Y + b.Y, a.Z + b.Z} } func (a Vector) Sub(b Vector) Vector { return Vector{a.X - b.X, a.Y - b.Y, a.Z - b.Z} } func (a Vector) Mul(b Vector) Vector { return Vector{a.X * b.X, a.Y * b.Y, a.Z * b.Z} } func (a Vector) Div(b Vector) Vector { return Vector{a.X / b.X, a.Y / b.Y, a.Z / b.Z} } func (a Vector) AddScalar(b float64) Vector { return Vector{a.X + b, a.Y + b, a.Z + b} } func (a Vector) SubScalar(b float64) Vector { return Vector{a.X - b, a.Y - b, a.Z - b} } func (a Vector) MulScalar(b float64) Vector { return Vector{a.X * b, a.Y * b, a.Z * b} } func (a Vector) DivScalar(b float64) Vector { return Vector{a.X / b, a.Y / b, a.Z / b} } func (a Vector) Min(b Vector) Vector { return Vector{math.Min(a.X, b.X), math.Min(a.Y, b.Y), math.Min(a.Z, b.Z)} } func (a Vector) Max(b Vector) Vector { return Vector{math.Max(a.X, b.X), math.Max(a.Y, b.Y), math.Max(a.Z, b.Z)} } func (a Vector) MinAxis() Vector { x, y, z := math.Abs(a.X), math.Abs(a.Y), math.Abs(a.Z) switch { case x <= y && x <= z: return Vector{1, 0, 0} case y <= x && y <= z: return Vector{0, 1, 0} } return Vector{0, 0, 1} } func (a Vector) MinComponent() float64 { return math.Min(math.Min(a.X, a.Y), a.Z) } func (p Vector) SegmentDistance(v Vector, w Vector) float64 { l2 := v.DistanceSquared(w) if l2 == 0 { return p.Distance(v) } t := p.Sub(v).Dot(w.Sub(v)) / l2 if t < 0 { return p.Distance(v) } if t > 1 { return p.Distance(w) } return v.Add(w.Sub(v).MulScalar(t)).Distance(p) }
ln/vector.go
0.847274
0.795499
vector.go
starcoder
package graphblas import ( "context" "log" "reflect" "github.com/rossmerr/graphblas/constraints" ) // type Ordered interface { // Integer | Float | ~string // } func init() { RegisterMatrix(reflect.TypeOf((*SparseVector[float64])(nil)).Elem()) } // SparseVector compressed storage by indices type SparseVector[T constraints.Number] struct { l int // length of the sparse vector values []T indices []int } // NewSparseVector returns a SparseVector func NewSparseVector[T constraints.Number](l int) *SparseVector[T] { return newSparseVector[T](l, 0) } // NewSparseVectorFromArray returns a SparseVector func NewSparseVectorFromArray[T constraints.Number](data []T) *SparseVector[T] { l := len(data) s := newSparseVector[T](l, 0) for i := 0; i < l; i++ { s.SetVec(i, data[i]) } return s } func newSparseVector[T constraints.Number](l, s int) *SparseVector[T] { return &SparseVector[T]{l: l, values: make([]T, s), indices: make([]int, s)} } // Length of the vector func (s *SparseVector[T]) Length() int { return s.l } // AtVec returns the value of a vector element at i-th func (s *SparseVector[T]) AtVec(i int) T { if i < 0 || i >= s.Length() { log.Panicf("Length '%+v' is invalid", i) } pointer, length, _ := s.index(i) if pointer < length && s.indices[pointer] == i { return s.values[pointer] } return Zero[T]() } // SetVec sets the value at i-th of the vector func (s *SparseVector[T]) SetVec(i int, value T) { if i < 0 || i >= s.Length() { log.Panicf("Length '%+v' is invalid", i) } pointer, length, _ := s.index(i) if pointer < length && s.indices[pointer] == i { if IsZero(value) { s.remove(pointer) } else { s.values[pointer] = value } } else { s.insert(pointer, i, value) } } // Columns the number of columns of the vector func (s *SparseVector[T]) Columns() int { return 1 } // Rows the number of rows of the vector func (s *SparseVector[T]) Rows() int { return s.l } // Update does a At and Set on the vector element at r-th, c-th func (s *SparseVector[T]) Update(r, c int, f func(T) T) { if r < 0 || r >= s.Rows() { log.Panicf("Row '%+v' is invalid", r) } if c < 0 || c >= s.Columns() { log.Panicf("Column '%+v' is invalid", c) } v := s.AtVec(r) s.SetVec(r, f(v)) } // At returns the value of a vector element at r-th, c-th func (s *SparseVector[T]) At(r, c int) (value T) { s.Update(r, c, func(v T) T { value = v return v }) return } // Set sets the value at r-th, c-th of the vector func (s *SparseVector[T]) Set(r, c int, value T) { if r < 0 || r >= s.Rows() { log.Panicf("Row '%+v' is invalid", r) } if c < 0 || c >= s.Columns() { log.Panicf("Column '%+v' is invalid", c) } s.SetVec(r, value) } // ColumnsAt return the columns at c-th func (s *SparseVector[T]) ColumnsAt(c int) Vector[T] { if c < 0 || c >= s.Columns() { log.Panicf("Column '%+v' is invalid", c) } return s.copy() } // RowsAt return the rows at r-th func (s *SparseVector[T]) RowsAt(r int) Vector[T] { if r < 0 || r >= s.Rows() { log.Panicf("Row '%+v' is invalid", r) } rows := NewSparseVector[T](1) v := s.AtVec(r) rows.SetVec(0, v) return rows } // RowsAtToArray return the rows at r-th func (s *SparseVector[T]) RowsAtToArray(r int) []T { if r < 0 || r >= s.Rows() { log.Panicf("Row '%+v' is invalid", r) } rows := make([]T, 1) v := s.AtVec(r) rows[0] = v return rows } func (s *SparseVector[T]) insert(pointer, i int, value T) { if IsZero(value) { return } s.indices = append(s.indices[:pointer], append([]int{i}, s.indices[pointer:]...)...) s.values = append(s.values[:pointer], append([]T{value}, s.values[pointer:]...)...) } func (s *SparseVector[T]) remove(pointer int) { s.indices = append(s.indices[:pointer], s.indices[pointer+1:]...) s.values = append(s.values[:pointer], s.values[pointer+1:]...) } func (s *SparseVector[T]) index(i int) (int, int, error) { length := len(s.indices) if i > length { return length, length, nil } start := 0 end := length for start < end { p := (start + end) / 2 if s.indices[p] > i { end = p } else if s.indices[p] < i { start = p + 1 } else { return p, length, nil } } return start, length, nil } func (s *SparseVector[T]) copy() *SparseVector[T] { vector := newSparseVector[T](s.l, len(s.indices)) for i := range s.values { vector.values[i] = s.values[i] vector.indices[i] = s.indices[i] } return vector } // Copy copies the vector func (s *SparseVector[T]) Copy() Matrix[T] { return s.copy() } // Scalar multiplication of a vector by alpha func (s *SparseVector[T]) Scalar(alpha T) Matrix[T] { return Scalar[T](context.Background(), s, alpha) } // Multiply multiplies a vector by another vector func (s *SparseVector[T]) Multiply(m Matrix[T]) Matrix[T] { matrix := newMatrix[T](m.Rows(), s.Columns(), nil) MatrixMatrixMultiply[T](context.Background(), s, m, nil, matrix) return matrix } // Add addition of a metrix by another metrix func (s *SparseVector[T]) Add(m Matrix[T]) Matrix[T] { matrix := s.Copy() Add[T](context.Background(), s, m, nil, matrix) return matrix } // Subtract subtracts one metrix from another metrix func (s *SparseVector[T]) Subtract(m Matrix[T]) Matrix[T] { matrix := m.Copy() Subtract[T](context.Background(), s, m, nil, matrix) return matrix } // Negative the negative of a metrix func (s *SparseVector[T]) Negative() Matrix[T] { matrix := s.Copy() Negative[T](context.Background(), s, nil, matrix) return matrix } // Transpose swaps the rows and columns func (s *SparseVector[T]) Transpose() Matrix[T] { matrix := newMatrix[T](s.Columns(), s.Rows(), nil) Transpose[T](context.Background(), s, nil, matrix) return matrix } // Equal the two metrics are equal func (s *SparseVector[T]) Equal(m Matrix[T]) bool { return Equal[T](context.Background(), s, m) } // NotEqual the two metrix are not equal func (s *SparseVector[T]) NotEqual(m Matrix[T]) bool { return NotEqual[T](context.Background(), s, m) } // Size of the vector func (s *SparseVector[T]) Size() int { return s.l } // Values the number of non-zero elements in the Vector func (s *SparseVector[T]) Values() int { return len(s.values) } // Clear removes all elements from a vector func (s *SparseVector[T]) Clear() { s.values = make([]T, 0) s.indices = make([]int, 0) } // Enumerate iterates through all non-zero elements, order is not guaranteed func (s *SparseVector[T]) Enumerate() Enumerate[T] { return s.iterator() } func (s *SparseVector[T]) iterator() *sparseVectorIterator[T] { i := &sparseVectorIterator[T]{ matrix: s, size: len(s.values), last: 0, } return i } type sparseVectorIterator[T constraints.Number] struct { matrix *SparseVector[T] size int last int old int } // HasNext checks the iterator has any more values func (s *sparseVectorIterator[T]) HasNext() bool { if s.last >= s.size { return false } return true } func (s *sparseVectorIterator[T]) next() { s.old = s.last s.last++ } // Next moves the iterator and returns the row, column and value func (s *sparseVectorIterator[T]) Next() (int, int, T) { s.next() return s.matrix.indices[s.old], 0, s.matrix.values[s.old] } // Map replace each element with the result of applying a function to its value func (s *SparseVector[T]) Map() Map[T] { t := s.iterator() i := &sparseVectorMap[T]{t} return i } type sparseVectorMap[T constraints.Number] struct { *sparseVectorIterator[T] } // HasNext checks the iterator has any more values func (s *sparseVectorMap[T]) HasNext() bool { return s.sparseVectorIterator.HasNext() } // Map move the iterator and uses a higher order function to changes the elements current value func (s *sparseVectorMap[T]) Map(f func(int, int, T) T) { s.next() value := f(s.matrix.indices[s.old], 0, s.matrix.values[s.old]) if !IsZero(value) { s.matrix.values[s.old] = value } else { s.matrix.remove(s.old) } } // Element of the mask for each tuple that exists in the matrix for which the value of the tuple cast to Boolean is true func (s *SparseVector[T]) Element(r, c int) bool { return s.AtVec(r) > Default[T]() }
sparseVector.go
0.759671
0.588712
sparseVector.go
starcoder
package jsonlog import ( "encoding/json" "time" ) // An Event represents a structured logeevent inspired by the semantic model of OTEL (https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md) type Event struct { Time *time.Time `json:"time,omitempty"` // Time when the event occurred measured by the origin clock, normalized to UTC. Severity Severity `json:"sev,omitempty"` // Numerical value of the severity cf. Severity constants like SeverityInfo for possible values and their semantics Name string `json:"name,omitempty"` // Short event identifier that does not contain varying parts. Name describes what happened (e.g. "ProcessStarted"). Recommended to be no longer than 50 characters. Not guaranteed to be unique in any way. Typically used for filtering and grouping purposes in backends. Can be used to identify domain events like FeaturesRequested or UserLoggedIn (cf. example). Body interface{} `json:"body,omitempty"` // A value containing the body of the log record. Can be for example a human-readable string message (including multi-line) describing the event in a free form or it can be a structured data composed of arrays and maps of other values. Can vary for each occurrence of the event coming from the same source. TenantId string `json:"tn,omitempty"` // ID of the tenant to which this event belongs. TraceId string `json:"trace,omitempty"` // Request trace-id as defined in W3C Trace Context (https://www.w3.org/TR/trace-context/#trace-id) specification. That is the ID of the whole trace forest used to uniquely identify a distributed trace through a system. SpanId string `json:"span,omitempty"` // span-id. Can be set for logs that are part of a particular processing span. A span (https://opentracing.io/docs/overview/spans/) is the primary building block of a distributed trace, representing an individual unit of work done in a distributed system. Resource *Resource `json:"res,omitempty"` // Describes the source of the log. Multiple occurrences of events coming from the same event source can happen across time and they all have the same value of Resource. Can contain for example information about the application that emits the record or about the infrastructure where the application runs. Attributes *Attributes `json:"attr,omitempty"` // Additional information about the specific event occurrence. Unlike the Resource field, which is fixed for a particular source, Attributes can vary for each occurrence of the event coming from the same source. Can contain information about the request context (other than TraceId/SpanId). Visibility *int `json:"vis,omitempty"` // Specifies if the logstatement is visible for tenant owner / customer. For now possible values are 1: true 0: false 1 is the default value, that is statements are visible if not explicitly denied by setting this value to 0 } // A Resource describes the source of the log. Multiple occurrences of events coming from the same event source can happen across time and they all have the same value of res. Can contain for example information about the application that emits the record or about the infrastructure where the application runs. type Resource struct { Service *Service `json:"svc,omitempty"` } // A Service describes a service instance type Service struct { Name string `json:"name,omitempty"` // Logical name of the service. MUST be the same for all instances of horizontally scaled services. If necessary dots can be used to denote subcomponents like myservice.syncworker or myservice.scheduler. Version string `json:"ver,omitempty"` // The version string of the service API or implementation. Instance string `json:"inst,omitempty"` // The ID of the service instance. MUST be unique for each instance of the same service. The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). } // Attributes contains additional information about the specific event occurrence. Unlike the res field, which is fixed for a particular source, attr can vary for each occurrence of the event coming from the same source. Can contain information about the request context (other than TraceId/SpanId). type Attributes struct { Http *Http `json:"http,omitempty"` // Information about outbound or inbound http requests. DB *DB `json:"db,omitempty"` // Information about outbound db requests. Exception *Exception `json:"exception,omitempty"` // Information about an exception } // Http contains information about outbound or inbound HTTP requests type Http struct { Method string `json:"method,omitempty"` // HTTP request method in upper case. For example GET, POST, DELETE StatusCode uint16 `json:"statusCode,omitempty"` // HTTP response status code URL string `json:"url,omitempty"` // Full HTTP request URL in the form scheme://host[:port]/path?query[#fragment]. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. MUST NOT contain credentials passed via URL in form of https://username:password@www.example.com/. In such case the attribute's value should be https://www.example.com/. Target string `json:"target,omitempty"` // The full request target as passed in a HTTP request line or equivalent. For example /path/12314/?q=ddds#123 Host string `json:"host,omitempty"` // The value of the HTTP host header. For example www.example.org Scheme string `json:"scheme,omitempty"` // The URI scheme identifying the used protocol. For example http or https Route string `json:"route,omitempty"` // The matched route (path template). For example /users/:userID? UserAgent string `json:"userAgent,omitempty"` // Value of the HTTP User-Agent header sent by the client. ClientIP string `json:"clientIP,omitempty"` // The IP address of the original client behind all proxies, if known (e.g. from X-Forwarded-For). Server *Server `json:"server,omitempty"` // Specific values for inbound HTTP requests Client *Client `json:"client,omitempty"` // Specific values for outbound HTTP requests } // Server contains specific values for inbound HTTP requests type Server struct { Duration time.Duration `json:"duration,omitempty"` // Measures the duration of the inbound HTTP request in ms } // Client contains specific values for outbound HTTP requests type Client struct { Duration time.Duration `json:"duration,omitempty"` // Measures the duration of the outbound HTTP request in ms } // DB contains information about outbound db requests. type DB struct { Name string `json:"name,omitempty"` // This attribute is used to report the name of the database being accessed. For example customers oder main Statement string `json:"statement,omitempty"` // The database statement being executed. Must be sanitized to exclude sensitive information. For example SELECT * FROM wuser_table; SET mykey "WuValue" Operation string `json:"operation,omitempty"` // The name of the operation being executed, e.g. the MongoDB command name such as findAndModify, or the SQL keyword. For example findAndModify; HMSET; SELECT } // Exception contains information about an exception type Exception struct { Type string `json:"type,omitempty"` // The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. For example java.net.ConnectException; OSError Message string `json:"message,omitempty"` // The exception message. For example Division by zero Stacktrace string `json:"stacktrace,omitempty"` // A stacktrace as a string in the natural representation for the language runtime. } // MarshalJSON customizes the JSON Representation of the Event type func (e Event) MarshalJSON() ([]byte, error) { type Alias Event // type alias to prevent infinite recursion ev := Alias(e) if ev.Visibility != nil && *ev.Visibility == 1 { cp := *ev.Visibility ev.Visibility = &cp ev.Visibility = nil // don't serialize default value } if ev.Time != nil && ev.Time.Location() != time.UTC { cp := *ev.Time // copy prevents changing the original event ev.Time = &cp *ev.Time = ev.Time.UTC() // normalize to UTC } return json.Marshal(ev) } // UnmarshalJSON customizes the JSON Deserialization of the Event type func (e *Event) UnmarshalJSON(data []byte) error { type Alias Event // type alias to prevent infinite recursion var ev Alias if err := json.Unmarshal(data, &ev); err != nil { return err } if ev.Visibility == nil { var v = 1 ev.Visibility = &v } *e = Event(ev) return nil } // MarshalJSON customizes the JSON Representation of the Server type func (s Server) MarshalJSON() ([]byte, error) { return json.Marshal(struct { Duration int64 `json:"duration,omitempty"` // Measures the duration of the inbound HTTP request in ms }{ s.Duration.Milliseconds(), }) } // UnmarshalJSON customizes the JSON Deserialization of the Event type func (s *Server) UnmarshalJSON(data []byte) error { str := struct { Duration int64 `json:"duration,omitempty"` // Measures the duration of the inbound HTTP request in ms }{} if err := json.Unmarshal(data, &str); err != nil { return err } s.Duration = time.Millisecond * time.Duration(str.Duration) return nil } // MarshalJSON customizes the JSON Representation of the Client type func (s Client) MarshalJSON() ([]byte, error) { return json.Marshal(struct { Duration int64 `json:"duration,omitempty"` // Measures the duration of the inbound HTTP request in ms }{ s.Duration.Milliseconds(), }) } // UnmarshalJSON customizes the JSON Deserialization of the Event type func (s *Client) UnmarshalJSON(data []byte) error { str := struct { Duration int64 `json:"duration,omitempty"` // Measures the duration of the inbound HTTP request in ms }{} if err := json.Unmarshal(data, &str); err != nil { return err } s.Duration = time.Millisecond * time.Duration(str.Duration) return nil } type Severity uint8 const ( SeverityDebug = 5 // The information is meant for the developer of the app or component. The purpose it to follow the execution path while explicitly debugging a certain problem. SeverityInfo = 9 // The information is meant for the developer or operator of the own or other teams. In contrast to SeverityError this severity is used to emit events which work as designed. SeverityError = 17 // The information is meant for the developer or operator of the own or other teams. In contrast to SeverityInfo this severity number is used to emit events which denote that something unexpected happened. Which can't be compensated in the own component. For example a failed outbound http request which can be compensated with a subsequent retry must not be logged as SeverityError. SeverityInfo must be used because from the outside everything works as expected. Whereas an inbound request which yields a 500 - internal server error must use SeverityError because there is no chance for the own component to recover. )
jsonlog/event.go
0.875268
0.542136
event.go
starcoder
package parser import ( "errors" "io" "github.com/golangee/tadl/token" ) // TreeNode is a node in the parse tree. // For regular nodes Text and Comment will always be nil. // For terminal text nodes Children and Name will be empty and Text will be set. // For comment nodes Children and Name will be empty and only Comment will be set. type TreeNode struct { Name string Text *string Comment *string Attributes AttributeList Parent *TreeNode Children []*TreeNode // BlockType describes the type of brackets the children were surrounded with. // This may be BlockNone in which case this node either has no or one children. BlockType BlockType // Range will span all tokens that were processed to build this node. Range token.Position } // NewNode creates a new node for the parse tree. func NewNode(name string) *TreeNode { return &TreeNode{ Name: name, Attributes: NewAttributeList(), BlockType: BlockNone, } } // NewTextNode creates a node that will only contain text. func NewTextNode(cd *token.CharData) *TreeNode { return &TreeNode{ Text: &cd.Value, Range: token.Position{ BeginPos: cd.Begin(), EndPos: cd.End(), }, } } // NewCommentNode creates a node that will only contain a comment. func NewCommentNode(cd *token.CharData) *TreeNode { return &TreeNode{ Comment: &cd.Value, Range: token.Position{ BeginPos: cd.Begin(), EndPos: cd.End(), }, } } // NewStringNode will create a text node, like NewTextNode, // but without positional information. This is only used for testing. // Use NewTextNode with a CharData token if you can. func NewStringNode(text string) *TreeNode { return &TreeNode{ Text: &text, } } // NewStringCommentNode will create a comment node, like NewCommentNode, // but without positional information. This is only used for testing. // Use NewCommentNode with a CharData token if you can. func NewStringCommentNode(text string) *TreeNode { return &TreeNode{ Comment: &text, } } // AddChildren adds children to a node and can be used builder-style. func (t *TreeNode) AddChildren(children ...*TreeNode) *TreeNode { if t.Children != nil { t.Children = append(t.Children, children...) } else { t.Children = children } return t } // AddAttribute adds an attribute to a node and can be used builder-style. func (t *TreeNode) AddAttribute(key, value string) *TreeNode { t.Attributes.Set(&key, &value) return t } // Block is used to set the BlockType of this node. func (t *TreeNode) Block(blockType BlockType) *TreeNode { t.BlockType = blockType return t } // IsClosedBy returns true if tok is a BlockEnd/GroupEnd/GenericEnd that is the correct // match for closing this TreeNode. func (t *TreeNode) IsClosedBy(tok token.Token) bool { switch tok.(type) { case *token.BlockEnd: return t.BlockType == BlockNormal case *token.GroupEnd: return t.BlockType == BlockGroup case *token.GenericEnd: return t.BlockType == BlockGeneric default: return false } } // IsText returns true if this node is a text only node. // Only one of IsText, IsComment, IsNode should be true. func (t *TreeNode) IsText() bool { return t.Text != nil } // IsComment returns true if this node is a comment node. // Only one of IsText, IsComment, IsNode should be true. func (t *TreeNode) IsComment() bool { return t.Comment != nil } // IsNode returns true if this is a regular node. // Only one of IsText, IsComment, IsNode should be true. func (t *TreeNode) IsNode() bool { return !t.IsText() && !t.IsComment() } // unbindParents recursively sets all parent Pointers of a tree to nil func unbindParents(t *TreeNode) { t.Parent = nil for _, child := range t.Children { unbindParents(child) } } // tokenWithError is a struct that wraps a Token and an error that may // have occurred while reading that Token. // This type simplifies storing tokens in the parser. type tokenWithError struct { tok token.Token err error } // BlockType is an addition for nodes that describes with what brackets their children were surrounded. type BlockType string const ( // BlockNone represents no BlockType BlockNone BlockType = "" // BlockNormal represents curly brackets BlockNormal BlockType = "{}" // BlockGroup represents round brackets BlockGroup BlockType = "()" // BlockGeneric represents pointed brackets BlockGeneric BlockType = "<>" ) // Parser is used to get a tree representation from Tadl input. type Parser struct { //forwardingAttributes contains all Attributes that have been forwarded to be added to the next viable node. forwardingAttributes *AttributeList // root and parent are pointers to work with the successively built Tree. // root holds the root Node, parent holds the currently to modify Node root *TreeNode parent *TreeNode // root- and parentForward have the same functionality as root and parent. // they are used to create full trees being forwarded, added later to the main tree rootForward *TreeNode parentForward *TreeNode // g2Comments contains all comments in G2 that were eaten from the input, // but are not yet placed in a sensible position. g2Comments []*TreeNode visitor Visitor firstNode bool globalForward bool } // NewParser creates and returns a new Parser with corresponding Visitor func NewParser(filename string, r io.Reader) *Parser { parser := &Parser{ visitor: *NewVisitor(nil, token.NewLexer(filename, r)), globalForward: false, rootForward: NewNode("root").Block(BlockNormal), } parser.parentForward = parser.rootForward parser.visitor.SetVisitable(parser) parser.firstNode = true return parser } // Parse returns a parsed tree. func (p *Parser) Parse() (*TreeNode, error) { err := p.visitor.Run() if err != nil { return nil, err } unbindParents(p.root) return p.root, nil } // open sets the parent pointer to the latest Child of it's current Node func (p *Parser) open() { p.parent = p.parent.Children[len(p.parent.Children)-1] } // Close moves the parent pointer to its current parent Node func (p *Parser) Close() error { if p.parent.Parent != nil { p.parent = p.parent.Parent } return nil } // NewNode creates a named Node and adds it as a child to the current parent Node // Opens the new Node func (p *Parser) NewNode(name string) error { if p.root == nil || p.firstNode { p.root = NewNode(name) p.parent = p.root if p.firstNode { p.firstNode = false } return nil } p.parent.AddChildren(NewNode(name)) p.parent.Children[len(p.parent.Children)-1].Parent = p.parent p.open() return nil } // NewTextNode creates a new Node with Text based on CharData and adds it as a child to the current parent Node // Opens the new Node func (p *Parser) NewTextNode(cd *token.CharData) error { p.parent.AddChildren(NewTextNode(cd)) p.parent.Children[len(p.parent.Children)-1].Parent = p.parent return nil } // NewCommentNode creates a new Node with Text as Comment, based on CharData and adds it as a child to the current parent Node // Opens the new Node func (p *Parser) NewCommentNode(cd *token.CharData) error { p.parent.AddChildren(NewCommentNode(cd)) p.parent.Children[len(p.parent.Children)-1].Parent = p.parent return nil } // SetBlockType sets the current parent Nodes BlockType func (p *Parser) SetBlockType(b BlockType) error { p.parent.Block(b) return nil } // GetRootBlockType returns the root Nodes BlockType func (p *Parser) GetRootBlockType() (BlockType, error) { return p.root.BlockType, nil } // GetBlockType returns the block type of the current parent node func (p *Parser) GetBlockType() (BlockType, error) { return p.parent.BlockType, nil } // GetForwardingLength returns the length of the List of forwaring Nodes func (p *Parser) GetForwardingLength() (int, error) { if p.rootForward != nil && p.rootForward.Children != nil { return len(p.rootForward.Children), nil } return 0, nil } // GetForwardingAttributesLength returns the length of the forwarding AttributeMap func (p *Parser) GetForwardingAttributesLength() (int, error) { if p.forwardingAttributes == nil { return 0, nil } return p.forwardingAttributes.Len(), nil } // GetForwardingPosition retrieves a forwarded Node based on given Index and // returns the Rangespan the Token corresponding to said Node had in the input tadl text func (p *Parser) GetForwardingPosition(i int) (token.Node, error) { return p.rootForward.Children[i].Range, nil } // AddAttribute adds a given Attribute to the current parent Node func (p *Parser) AddAttribute(key, value string) error { p.parent.Attributes.Set(&key, &value) return nil } // AddAttributeForward adds a given AttributeMap to the forwaring Attributes func (p *Parser) AddAttributeForward(key, value string) error { if p.forwardingAttributes == nil { p.forwardingAttributes = &AttributeList{} } p.forwardingAttributes.Push(&key, &value) return nil } // AddNodeForward appends a given Node to the list of forwarding Nodes func (p *Parser) AddNodeForward(name string) error { err := p.SwitchActiveTree() if err != nil { return err } p.parent = p.root err = p.NewNode(name) if err != nil { return err } err = p.SwitchActiveTree() if err != nil { return err } return nil } // MergeAttributes merges the list of forwarded Attributes to the current parent Nodes Attributes func (p *Parser) MergeAttributes() error { if p.forwardingAttributes != nil && p.forwardingAttributes.Len() > 0 { p.parent.Attributes = p.parent.Attributes.Merge(*p.forwardingAttributes) p.forwardingAttributes = nil } return nil } // MergeAttributesForwarded adds the buffered forwarding AttributeMap to the latest forwarded Node func (p *Parser) MergeAttributesForwarded() error { if p.forwardingAttributes != nil && p.forwardingAttributes.Len() > 0 { err := p.SwitchActiveTree() if err != nil { return err } p.parent.Attributes = p.parent.Attributes.Merge(*p.forwardingAttributes) p.forwardingAttributes = nil err = p.SwitchActiveTree() if err != nil { return err } return nil } return nil } // MergeNodesForwarded appends the current list of forwarding Nodes // as Children to the current parent Node func (p *Parser) MergeNodesForwarded() error { if p.rootForward != nil && p.rootForward.Children != nil && len(p.rootForward.Children) != 0 { p.parent.Children = append(p.parent.Children, p.rootForward.Children...) p.rootForward.Children = nil p.parentForward = p.rootForward } return nil } // G2AppendComments will append all comments that were parsed with g2EatComments as children // into the parent node. func (p *Parser) G2AppendComments() error { if p.parent != nil { p.parent.Children = append(p.parent.Children, p.g2Comments...) p.g2Comments = nil } else if p.g2Comments != nil { return errors.New("could not append comments, parent is nil") } return nil } // G2AddComments adds a new Comment Node based on given CharData to the g2Comments List, // to be added to the tree later func (p *Parser) G2AddComments(cd *token.CharData) error { p.g2Comments = append(p.g2Comments, NewCommentNode(cd)) return nil } // SwitchActiveTree switches the active Tree between the main syntax tree and the forwarding tree // To modify the forwarding tree, call SwitchActiveTree, call treeCreation functions, call SwitchActiveTree func (p *Parser) SwitchActiveTree() error { var cache *TreeNode = p.parent p.parent = p.parentForward p.parentForward = cache cache = p.root p.root = p.rootForward p.rootForward = cache p.globalForward = !p.globalForward return nil } // NewStringNode creates a Node with Text and adds it as a child to the current parent Node // Opens the new Node, used for testing purposes only func (p *Parser) NewStringNode(name string) { p.parent.AddChildren(NewStringNode(name)) p.parent.Children[len(p.parent.Children)-1].Parent = p.parent p.open() } // NewStringCommentNode creates a new Node with Text as Comment, based on string and adds it as a child to the current parent Node // Opens the new Node, used for testing purposes only func (p *Parser) NewStringCommentNode(text string) { p.parent.AddChildren(NewStringCommentNode(text)) p.parent.Children[len(p.parent.Children)-1].Parent = p.parent p.open() } // GetGlobalForward returns the global forward flag func (p *Parser) GetGlobalForward() (bool, error) { return p.globalForward, nil }
parser/parser.go
0.654564
0.543287
parser.go
starcoder
package internal import ( "fmt" "math" "math/big" "reflect" "strconv" "github.com/tada/catch" "github.com/tada/dgo/dgo" ) type ( // intVal is an int64 that implements the dgo.Value interface intVal int64 defaultIntegerType int integerType struct { min dgo.Integer max dgo.Integer inclusive bool } ) // DefaultIntegerType is the unconstrained Int64 type const DefaultIntegerType = defaultIntegerType(dgo.TiInteger) var reflectIntegerType = reflect.TypeOf(int64(0)) // Integer64Type returns a dgo.Integer64Type that is limited to the inclusive range given by min and max // If inclusive is true, then the range has an inclusive end. func Integer64Type(min, max int64, inclusive bool) dgo.IntegerType { if min == max { if !inclusive { panic(catch.Error(`non inclusive range cannot have equal min and max`)) } return intVal(min).Type().(dgo.IntegerType) } if max < min { t := max max = min min = t } var minV dgo.Integer var maxV dgo.Integer if min != math.MinInt64 { minV = intVal(min) } if max != math.MaxInt64 { maxV = intVal(max) } if minV == nil && maxV == nil { return DefaultIntegerType } return &integerType{min: minV, max: maxV, inclusive: inclusive} } // IntegerType returns a dgo.Integer64Type that is limited to the inclusive range given by min and max // If inclusive is true, then the range has an inclusive end. The IntegerType.ReflectType() returns // the *big.Int type. func IntegerType(min, max dgo.Integer, inclusive bool) dgo.IntegerType { if min != nil && max != nil { cmp, _ := min.CompareTo(max) if cmp == 0 { if !inclusive { panic(catch.Error(`non inclusive range cannot have equal min and max`)) } return min.(dgo.IntegerType) } if cmp > 0 { t := max max = min min = t } } else if min == nil && max == nil { return DefaultIntegerType } _, useBig := min.(dgo.BigInt) if !useBig { _, useBig = max.(dgo.BigInt) } if useBig { return &bigIntType{integerType{min: min, max: max, inclusive: inclusive}} } return &integerType{min: min, max: max, inclusive: inclusive} } func (t *integerType) Assignable(other dgo.Type) bool { switch ot := other.(type) { case defaultIntegerType: return false case dgo.IntegerType: if t.min != nil { om := ot.Min() if om == nil { return false } cmp, _ := t.min.CompareTo(om) if cmp > 0 { return false } } if mm := t.max; mm != nil { om := ot.Max() if om == nil { return false } if t.Inclusive() { mm = mm.Inc() } if ot.Inclusive() { om = om.Inc() } cmp, _ := mm.CompareTo(om) if cmp < 0 { return false } } return true } return CheckAssignableTo(nil, other, t) } func (t *integerType) Equals(other interface{}) bool { ot, ok := other.(dgo.IntegerType) return ok && t.inclusive == ot.Inclusive() && equals(nil, t.min, ot.Min()) && equals(nil, t.max, ot.Max()) } func (t *integerType) HashCode() dgo.Hash { h := dgo.Hash(dgo.TiIntegerRange) if t.min != nil { h = h*31 + t.min.HashCode() } if t.max != nil { h = h*31 + t.max.HashCode() } if t.inclusive { h *= 3 } return h } func (t *integerType) Inclusive() bool { return t.inclusive } func (t *integerType) Instance(value interface{}) bool { yes := false switch ov := value.(type) { case dgo.Integer: yes = t.isInstance(ov) case int: yes = t.isInstance(intVal(ov)) case uint: yes = t.isInstance(uintVal(ov)) case uint64: yes = t.isInstance(uintVal(ov)) case *big.Int: yes = t.isInstance(&bigIntVal{ov}) default: var iv int64 iv, yes = ToInt(value) yes = yes && t.isInstance(intVal(iv)) } return yes } func (t *integerType) isInstance(i dgo.Integer) bool { if t.min != nil { cmp, ok := t.min.CompareTo(i) if !ok || cmp > 0 { return false } } if t.max != nil { cmp, ok := t.max.CompareTo(i) if !ok || cmp < 0 || cmp == 0 && !t.inclusive { return false } } return true } func (t *integerType) Max() dgo.Integer { return t.max } func (t *integerType) Min() dgo.Integer { return t.min } func (t *integerType) New(arg dgo.Value) dgo.Value { return newInt(t, arg) } func (t *integerType) ReflectType() reflect.Type { return reflectIntegerType } func (t *integerType) String() string { return TypeString(t) } func (t *integerType) Type() dgo.Type { return MetaType(t) } func (t *integerType) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiIntegerRange } func (t defaultIntegerType) Assignable(other dgo.Type) bool { _, ok := other.(dgo.IntegerType) return ok || CheckAssignableTo(nil, other, t) } func (t defaultIntegerType) Equals(other interface{}) bool { _, ok := other.(defaultIntegerType) return ok } func (t defaultIntegerType) HashCode() dgo.Hash { return dgo.Hash(dgo.TiInteger) } func (t defaultIntegerType) Instance(value interface{}) bool { switch value.(type) { case dgo.Integer, *big.Int, int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8: return true } return false } func (t defaultIntegerType) Inclusive() bool { return true } func (t defaultIntegerType) Max() dgo.Integer { return nil } func (t defaultIntegerType) Min() dgo.Integer { return nil } func (t defaultIntegerType) New(arg dgo.Value) dgo.Value { return newInt(t, arg) } func (t defaultIntegerType) ReflectType() reflect.Type { return reflectIntegerType } func (t defaultIntegerType) String() string { return TypeString(t) } func (t defaultIntegerType) Type() dgo.Type { return MetaType(t) } func (t defaultIntegerType) TypeIdentifier() dgo.TypeIdentifier { return dgo.TypeIdentifier(t) } // IntEnumType returns a Type that represents any of the given integers func IntEnumType(ints []int) dgo.Type { switch len(ints) { case 0: return &notType{DefaultAnyType} case 1: return intVal(ints[0]).Type() } ts := make([]dgo.Value, len(ints)) for i := range ints { ts[i] = intVal(ints[i]).Type() } return &anyOfType{slice: ts} } // Int64 returns the dgo.Integer for the given int64 func Int64(v int64) dgo.Integer { return intVal(v) } func (v intVal) Assignable(other dgo.Type) bool { return v.Equals(other) || CheckAssignableTo(nil, other, v) } func (v intVal) compare64(fv int64) int { r := 0 switch { case int64(v) > fv: r = 1 case int64(v) < fv: r = -1 } return r } func (v intVal) compareBig(ov *big.Int) int { r := 0 if ov.IsInt64() { r = v.compare64(ov.Int64()) } else { r = -ov.Sign() } return r } func (v intVal) compareU64(ov uint64) int { r := 0 if ov > math.MaxInt64 { r = -1 } else { r = v.compare64(int64(ov)) } return r } func (v intVal) CompareTo(other interface{}) (int, bool) { r := 0 ok := true switch ov := other.(type) { case nil, nilValue: r = 1 case intVal: r = v.compare64(int64(ov)) case int: r = v.compare64(int64(ov)) case int64: r = v.compare64(ov) case uintVal: r = v.compareU64(uint64(ov)) case uint: r = v.compareU64(uint64(ov)) case uint64: r = v.compareU64(ov) case *bigIntVal: r = v.compareBig(ov.Int) case *big.Int: r = v.compareBig(ov) case dgo.Float: r, ok = v.Float().CompareTo(ov) default: // all other int types var iv int64 iv, ok = ToInt(other) if ok { r = v.compare64(iv) } } return r, ok } func (v intVal) Dec() dgo.Integer { return v - 1 } func (v intVal) Equals(other interface{}) bool { i, ok := ToInt(other) return ok && int64(v) == i } func (v intVal) Float() dgo.Float { return floatVal(v) } func (v intVal) Format(s fmt.State, format rune) { doFormat(int64(v), s, format) } func (v intVal) Generic() dgo.Type { return DefaultIntegerType } func (v intVal) GoInt() int64 { return int64(v) } func (v intVal) HashCode() dgo.Hash { return dgo.Hash(v ^ (v >> 32)) } func (v intVal) Inc() dgo.Integer { return v + 1 } func (v intVal) Inclusive() bool { return true } func (v intVal) Instance(value interface{}) bool { return v.Equals(value) } func (v intVal) Integer() dgo.Integer { return v } func (v intVal) intPointer(kind reflect.Kind) reflect.Value { var p reflect.Value switch kind { case reflect.Int: gv := int(v) p = reflect.ValueOf(&gv) case reflect.Int8: gv := int8(v) p = reflect.ValueOf(&gv) case reflect.Int16: gv := int16(v) p = reflect.ValueOf(&gv) case reflect.Int32: gv := int32(v) p = reflect.ValueOf(&gv) case reflect.Uint: gv := uint(v) p = reflect.ValueOf(&gv) case reflect.Uint8: gv := uint8(v) p = reflect.ValueOf(&gv) case reflect.Uint16: gv := uint16(v) p = reflect.ValueOf(&gv) case reflect.Uint32: gv := uint32(v) p = reflect.ValueOf(&gv) case reflect.Uint64: gv := uint64(v) p = reflect.ValueOf(&gv) default: gv := int64(v) p = reflect.ValueOf(&gv) } return p } func (v intVal) Max() dgo.Integer { return v } func (v intVal) Min() dgo.Integer { return v } func (v intVal) New(arg dgo.Value) dgo.Value { return newInt(v, arg) } func (v intVal) ReflectTo(value reflect.Value) { switch value.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value.SetInt(int64(v)) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: value.SetUint(uint64(v)) case reflect.Ptr: value.Set(v.intPointer(value.Type().Elem().Kind())) default: value.Set(reflect.ValueOf(int64(v))) } } func (v intVal) ReflectType() reflect.Type { return reflectIntegerType } func (v intVal) String() string { return TypeString(v) } func (v intVal) ToBigInt() *big.Int { return big.NewInt(int64(v)) } func (v intVal) ToBigFloat() *big.Float { return new(big.Float).SetInt64(int64(v)) } func (v intVal) ToFloat() (float64, bool) { return float64(v), true } func (v intVal) ToInt() (int64, bool) { return int64(v), true } func (v intVal) ToUint() (uint64, bool) { if v >= 0 { return uint64(v), true } return 0, false } func (v intVal) Type() dgo.Type { return v } func (v intVal) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiIntegerExact } // ToInt returns the (value as an int64, true) if it fits into that data type, (0, false) if not func ToInt(value interface{}) (int64, bool) { ok := true v := int64(0) switch value := value.(type) { case intVal: v = int64(value) case int: v = int64(value) case int64: v = value case int32: v = int64(value) case int16: v = int64(value) case int8: v = int64(value) case uint: if value <= math.MaxInt64 { v = int64(value) } else { ok = false } case uint64: if value <= math.MaxInt64 { v = int64(value) } else { ok = false } case uintVal: if value <= math.MaxInt64 { v = int64(value) } else { ok = false } case uint32: v = int64(value) case uint16: v = int64(value) case uint8: v = int64(value) case *big.Int: if value.IsInt64() { v = value.Int64() } else { ok = false } case dgo.BigInt: v, ok = value.ToInt() default: ok = false } return v, ok } var radixType = IntEnumType([]int{0, 2, 8, 10, 16}) func newInt(t dgo.Type, arg dgo.Value) (i dgo.Integer) { if args, ok := arg.(dgo.Arguments); ok { args.AssertSize(`int`, 1, 2) if args.Len() == 2 { i = intFromConvertible(args.Get(0), int(args.Arg(`int`, 1, radixType).(dgo.Integer).GoInt())) } else { i = intFromConvertible(args.Get(0), 0) } } else { i = intFromConvertible(arg, 0) } if !t.Instance(i) { panic(IllegalAssignment(t, i)) } return i } func intFromConvertible(from dgo.Value, radix int) dgo.Integer { switch from := from.(type) { case dgo.Number: return from.Integer() case dgo.Boolean: if from.GoBool() { return intVal(1) } return intVal(0) case dgo.String: s := from.GoString() i, err := strconv.ParseInt(s, radix, 64) if err == nil { return Int64(i) } numErr, ok := err.(*strconv.NumError) if ok && numErr.Err == strconv.ErrRange { var bi *big.Int if bi, ok = new(big.Int).SetString(s, radix); ok { if bi.IsUint64() { return uintVal(bi.Uint64()) } return BigInt(bi) } } } panic(catch.Error(`the value '%v' cannot be converted to an int`, from)) }
internal/integer.go
0.7478
0.433142
integer.go
starcoder
package voxelgrid import ( "github.com/seqsense/pcgol/mat" ) type VoxelGrid struct { voxel [][]int size [3]int origin mat.Vec3 resolution float32 resolutionInv float32 } func New(resolution float32, size [3]int, origin mat.Vec3) *VoxelGrid { return &VoxelGrid{ voxel: make([][]int, size[0]*size[1]*size[2]), size: size, origin: origin, resolution: resolution, resolutionInv: 1 / resolution, } } func (v *VoxelGrid) MinMax() (min, max mat.Vec3) { return v.origin, v.origin.Add(mat.Vec3{ float32(v.size[0]) * v.resolution, float32(v.size[1]) * v.resolution, float32(v.size[2]) * v.resolution, }) } func (v *VoxelGrid) Resolution() float32 { return v.resolution } func (v *VoxelGrid) Add(p mat.Vec3, index int) bool { addr, ok := v.Addr(p) if !ok { return false } ptr := &v.voxel[addr] *ptr = append(*ptr, index) return true } func (v *VoxelGrid) AddByAddr(a int, index int) { ptr := &v.voxel[a] *ptr = append(*ptr, index) } func (v *VoxelGrid) Get(p mat.Vec3) []int { addr, ok := v.Addr(p) if !ok { return nil } return v.voxel[addr] } func (v *VoxelGrid) GetByAddr(a int) []int { return v.voxel[a] } func (v *VoxelGrid) Addr(p mat.Vec3) (int, bool) { pos := p.Sub(v.origin) x := int(pos[0]*v.resolutionInv + 0.5) if x < 0 || x >= v.size[0] { return 0, false } y := int(pos[1]*v.resolutionInv + 0.5) if y < 0 || y >= v.size[1] { return 0, false } z := int(pos[2]*v.resolutionInv + 0.5) if z < 0 || z >= v.size[2] { return 0, false } return x + (y+z*v.size[1])*v.size[0], true } func (v *VoxelGrid) AddrByPosInt(p [3]int) (int, bool) { x, y, z := p[0], p[1], p[2] if x < 0 || y < 0 || z < 0 || x >= v.size[0] || y >= v.size[1] || z >= v.size[2] { return 0, false } return x + (y+z*v.size[1])*v.size[0], true } func (v *VoxelGrid) PosInt(p mat.Vec3) ([3]int, bool) { pos := p.Sub(v.origin) x := int(pos[0]*v.resolutionInv + 0.5) if x < 0 || x >= v.size[0] { return [3]int{}, false } y := int(pos[1]*v.resolutionInv + 0.5) if y < 0 || y >= v.size[1] { return [3]int{}, false } z := int(pos[2]*v.resolutionInv + 0.5) if z < 0 || z >= v.size[2] { return [3]int{}, false } return [3]int{x, y, z}, true } func (v *VoxelGrid) Len() int { return v.size[0] * v.size[1] * v.size[2] } func (v *VoxelGrid) Indice() []int { out := make([]int, 0, 1024) for _, g := range v.voxel { out = append(out, g...) } return out } func (v *VoxelGrid) Reset() { for i := range v.voxel { v.voxel[i] = nil } }
pc/storage/voxelgrid/voxelgrid.go
0.666822
0.490846
voxelgrid.go
starcoder
package generator import ( _ "embed" "encoding/json" "github.com/m2q/siam-cs/model" "time" ) // refRaw contains real reference match data as a raw json string. The data is sorted, so // that ALL past matches (i.e. matches that have a non-empty `Winner` field) occur BEFORE // all future or live matches (i.e. matches where `Winner` is empty). //go:embed reference_data.json var refRaw string // ref is the match data parsed from refRaw. var ref []model.Match // init parses the raw match data and initializes ref func init() { if err := json.Unmarshal([]byte(refRaw), &ref); err != nil { panic(err) } } // GetData returns a time-normalized sample of real data. A combination of past and // future matches. First return value is past, second is future matches. // Note: The Date fields are normalized w.r.t the reference time. That means that the // MOST recent past match has a date of refTime, and all other matches are adjusted // according to this delta func GetData(refTime time.Time) ([]model.Match, []model.Match) { // copy reference data result := make([]model.Match, len(ref)) copy(result, ref) // find index of last past match lastPast := len(result) for i, v := range result { if v.Result.Winner == "" { lastPast = i break } } // normalize time diff := refTime.Sub(result[lastPast].Date) for i, _ := range result { result[i].Date = result[i].Date.Add(diff) } return result[:lastPast], result[lastPast:] } // GenerateFutureData returns an artificial array of matches that happen after the given // match. Use this method to generate fake "future" matches. func GenerateFutureData(m model.Match, n int) []model.Match { data := make([]model.Match, n) // add big offset to visually distinguish future matches id := m.ID + 100000 t := m.Date for i := 0; i < n; i++ { // set every subsequent future match 5 hours apart. This is arbitrary. t = t.Add(time.Hour * 5) id++ data[i] = model.Match{ ID: id, Date: t, Result: model.Result{Winner: "G2", Score: "16-11"}, } } return data } // NormalizeTime shifts the Dates of all matches by the difference between refTime // and the last past match. Essentially, this means that the time of the data is // transposed so that the most recent past match happened exactly at refTime. func NormalizeTime(past []model.Match, future []model.Match, refTime time.Time) { // last past match diff := refTime.Sub(past[len(past)-1].Date) // shift past matches for i, _ := range past { past[i].Date = past[i].Date.Add(diff) } // also shift future matches for i, _ := range future { future[i].Date = future[i].Date.Add(diff) } } // ProgressTime lets a specified number of future matches conclude, and // re-normalizes the time. Effectively, this simulates a passing of time. func ProgressTime(past, future []model.Match, matchCount int) ([]model.Match, []model.Match) { // matchCount can't exceed future slice length if matchCount > len(future) { matchCount = len(future) } // set result data for i := 0; i < matchCount; i++ { // just set random stuff future[i].Result.Winner = future[i].Team1.Name future[i].Result.Score = "16-10" // assume that the game took 1 hour, so the Date is set later future[i].Date = future[i].Date.Add(time.Hour) } // re-slice past and future boundaries past = append(past, future[:matchCount]...) future = future[matchCount:] NormalizeTime(past, future, time.Now()) return past, future }
generator/generator.go
0.689201
0.449997
generator.go
starcoder
package level0 import ( "github.com/sfomuseum/go-edtf" "github.com/sfomuseum/go-edtf/common" "github.com/sfomuseum/go-edtf/re" ) /* Time Interval EDTF Level 0 adopts representations of a time interval where both the start and end are dates: start and end date only; that is, both start and duration, and duration and end, are excluded. Time of day is excluded. Example 1 ‘1964/2008’ is a time interval with calendar year precision, beginning sometime in 1964 and ending sometime in 2008. Example 2 ‘2004-06/2006-08’ is a time interval with calendar month precision, beginning sometime in June 2004 and ending sometime in August of 2006. Example 3 ‘2004-02-01/2005-02-08’ is a time interval with calendar day precision, beginning sometime on February 1, 2004 and ending sometime on February 8, 2005. Example 4 ‘2004-02-01/2005-02’ is a time interval beginning sometime on February 1, 2004 and ending sometime in February 2005. Since the start endpoint precision (day) is different than that of the end endpoint (month) the precision of the time interval at large is undefined. Example 5 ‘2004-02-01/2005’ is a time interval beginning sometime on February 1, 2004 and ending sometime in 2005. The start endpoint has calendar day precision and the end endpoint has calendar year precision. Similar to the previous example, the precision of the time interval at large is undefined. Example 6 ‘2005/2006-02’ is a time interval beginning sometime in 2005 and ending sometime in February 2006. */ func IsTimeInterval(edtf_str string) bool { return re.TimeInterval.MatchString(edtf_str) } func ParseTimeInterval(edtf_str string) (*edtf.EDTFDate, error) { if !re.TimeInterval.MatchString(edtf_str) { return nil, edtf.Invalid(TIME_INTERVAL, edtf_str) } sp, err := common.DateSpanFromEDTF(edtf_str) if err != nil { return nil, err } d := &edtf.EDTFDate{ Start: sp.Start, End: sp.End, EDTF: edtf_str, Level: LEVEL, Feature: TIME_INTERVAL, } return d, nil }
vendor/github.com/sfomuseum/go-edtf/level0/time_interval.go
0.745861
0.543893
time_interval.go
starcoder
package main import ( "bufio" "fmt" "os" "strings" ) // Grid represents the cluster computing grid type Grid map[string]string // A function to perform a burst of activity by the carrier type burstFunc func(grid Grid, x, y int, direction Direction) (int, int, Direction, bool) // CLEAN state const CLEAN = "." // INFECTED state const INFECTED = "#" // FLAGGED state const FLAGGED = "F" // WEAKENED state const WEAKENED = "W" // ReadInputLines reads the input file line by line, // passing each line to the given channel. func ReadInputLines(infile string, c chan string) { f, err := os.Open(infile) if err != nil { panic("foo") } scanner := bufio.NewScanner(f) for scanner.Scan() { c <- scanner.Text() } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } close(c) } func gridEntry(x, y int) string { return fmt.Sprintf("%d,%d", x, y) } func setGrid(grid Grid, x, y int, state string) { if state == CLEAN { delete(grid, gridEntry(x, y)) } else { grid[gridEntry(x, y)] = state } } func gridState(grid Grid, x, y int) string { state, ok := grid[gridEntry(x, y)] if !ok { state = CLEAN } return state } func loadGrid(c chan string) (Grid, int, int) { result := make([][]string, 0) for line := range c { result = append(result, strings.Split(line, "")) } // Now reverse the grid. We read it in top to bottom, so // so the 0,0 point is the top left. We want it to be the // bottom left. nRows := len(result) grid := make(map[string]string, nRows) for y := range result { for x, state := range result[y] { yValue := nRows - y - 1 setGrid(grid, x, yValue, state) } } midpoint := nRows / 2 return grid, midpoint, midpoint } func moveForward(x, y int, direction Direction) (int, int) { return x + direction.x, y + direction.y } func carrierBurst(grid Grid, x, y int, direction Direction) (int, int, Direction, bool) { // fmt.Printf("carrierBurst(%d, %d, %s)\n", x, y, direction.name) infected := false switch gridState(grid, x, y) { case INFECTED: direction = turnRight(direction) setGrid(grid, x, y, CLEAN) case CLEAN: direction = turnLeft(direction) setGrid(grid, x, y, INFECTED) infected = true } // fmt.Printf("Moving %s from %d,%d", direction.name, x, y) x, y = moveForward(x, y, direction) // fmt.Printf(" to %d, %d\n", x, y) return x, y, direction, infected } func runCarrier(grid Grid, x, y int, activityBurst burstFunc, iters int) { infectedCount := 0 var infected bool // fmt.Printf("Initial position [%d, %d]\n", x, y) direction := up // fmt.Println("Direction:", direction) for i := 0; i < iters; i++ { x, y, direction, infected = activityBurst(grid, x, y, direction) if infected { infectedCount++ } // fmt.Printf("Carrier at %d, %d, facing %s. State = %s, infected %d\n", // x, y, direction.name, gridState(grid, x, y), infectedCount) } fmt.Printf("Infected %d nodes\n", infectedCount) } func part1(grid Grid, x, y int) { runCarrier(grid, x, y, carrierBurst, 10000) } func carrierBurst2(grid Grid, x, y int, direction Direction) (int, int, Direction, bool) { // fmt.Printf("carrierBurst2(%d, %d, %s)\n", x, y, direction.name) infected := false switch gridState(grid, x, y) { case CLEAN: direction = turnLeft(direction) setGrid(grid, x, y, WEAKENED) case WEAKENED: // Keep current direction setGrid(grid, x, y, INFECTED) infected = true case INFECTED: direction = turnRight(direction) setGrid(grid, x, y, FLAGGED) case FLAGGED: direction = reverse(direction) setGrid(grid, x, y, CLEAN) } // fmt.Printf("Moving %s from %d,%d", direction.name, x, y) x, y = moveForward(x, y, direction) // fmt.Printf(" to %d, %d\n", x, y) return x, y, direction, infected } func part2(puzzleInput string) { c := make(chan string, 1) go ReadInputLines(puzzleInput, c) grid, x, y := loadGrid(c) runCarrier(grid, x, y, carrierBurst2, 10000000) } func main() { c := make(chan string, 1) go ReadInputLines("input.txt", c) grid, x, y := loadGrid(c) part1(grid, x, y) part2("input.txt") }
2017/day22/day22.go
0.62223
0.459197
day22.go
starcoder
package ecc import ( "fmt" "math/big" ) // Point represents a point in an elliptic curve. type Point struct { X FieldInteger Y FieldInteger A FieldInteger B FieldInteger } // NewPoint returns a Point. func NewPoint(x FieldInteger, y FieldInteger, a FieldInteger, b FieldInteger) (*Point, error) { if x == nil && y == nil { return &Point{X: nil, Y: nil, A: a, B: b}, nil } // Verify that y^2 = x^3 + ax + b var left, right FieldInteger = y.Copy(), x.Copy() left.Pow(left, big.NewInt(2)) right.Pow(right, big.NewInt(3)).Add(right, x.Copy().Mul(x, a)).Add(right, b) if !left.Eq(right) { return nil, fmt.Errorf("(%d, %d) is not on the curve", x, y) } return &Point{X: x, Y: y, A: a, B: b}, nil } func (p *Point) String() string { if p.X == nil { return "Point(infinity)" } return fmt.Sprintf("Point(%v,%v)_%v_%v", p.X, p.Y, p.A, p.B) } // Eq returns true if the points are equal. func (p *Point) Eq(other *Point) bool { if p.X == nil { return other.X == nil } return p.X.Eq(other.X) && p.Y.Eq(other.Y) && p.A.Eq(other.A) && p.B.Eq(other.B) } // Ne returns true if the points are not equal. func (p *Point) Ne(other *Point) bool { return !p.Eq(other) } // Add p1 + p2 and return p. func (p *Point) Add(p1, p2 *Point) *Point { if p1.A.Ne(p2.A) || p1.B.Ne(p2.B) { panic(fmt.Sprintf("Points %v, %v are not on the same curve", p1, p2)) } a, b := p1.A, p1.B x1, y1, x2, y2 := p1.X, p1.Y, p2.X, p2.Y two := big.NewInt(2) if p1.X == nil { *p = Point{X: p2.X, Y: p2.Y, A: a, B: b} return p } if p2.X == nil { *p = Point{X: p1.X, Y: p1.Y, A: a, B: b} return p } // Case 1: p1.x == p2.x, p1.y != p2.y // Result is point at infinity if p1.X.Eq(p2.X) && p1.Y.Ne(p2.Y) { *p = Point{X: nil, Y: nil, A: a, B: b} return p } // Case 2: p1.x ≠ p2.x // Formula (x3,y3)==(x1,y1)+(x2,y2) // s=(y2-y1)/(x2-x1) // x3=s**2-x1-x2 // y3=s*(x1-x3)-y1 if x1.Ne(x2) { s := y2.Copy() s.Sub(s, y1) tmp := x2.Copy() tmp.Sub(tmp, x1) s.Div(s, tmp) x3 := s.Copy() x3.Pow(x3, two).Sub(x3, x1).Sub(x3, x2) y3 := tmp.Sub(x1, x3) y3.Mul(y3, s).Sub(y3, y1) *p = Point{X: x3, Y: y3, A: a, B: b} return p } // Case 4: if we are tangent to the vertical line, // we return the point at infinity // note instead of figuring out what 0 is for each type // we just use 0 * p.x zero := x1.Copy() zero.Cmul(zero, big.NewInt(0)) if p1.Eq(p2) && p1.Y.Eq(zero) { *p = Point{X: nil, Y: nil, A: a, B: b} return p } // Case 3: p1 == p2 // Formula (x3,y3)=(x1,y1)+(x1,y1) // s=(3*x1**2+a)/(2*y1) // x3=s**2-2*x1 // y3=s*(x1-x3)-y1 s := x1.Copy() s.Pow(s, two).Cmul(s, big.NewInt(3)).Add(s, a) tmp := y1.Copy() tmp.Cmul(tmp, two) s.Div(s, tmp) tmp.Cmul(x1, two) x3 := s.Copy() x3.Pow(x3, two).Sub(x3, tmp) y3 := s.Copy() tmp.Sub(x1, x3) y3.Mul(s, tmp).Sub(y3, y1) *p = Point{X: x3, Y: y3, A: a, B: b} return p } // Cmul sets p to c * r and return p. func (p *Point) Cmul(r *Point, coefficient *big.Int) *Point { coef := new(big.Int) coef.Set(coefficient) current := &Point{X: r.X, Y: r.Y, A: r.A, B: r.B} result := &Point{X: nil, Y: nil, A: r.A, B: r.B} for coef.Sign() > 0 { if coef.Bit(0) == 1 { result.Add(result, current) } current.Add(current, current) coef.Rsh(coef, 1) } *p = *result return p }
ecc/point.go
0.811489
0.653597
point.go
starcoder
package twodee import ( "github.com/go-gl/mathgl/mgl32" ) type Point struct { mgl32.Vec2 } func Pt(x, y float32) Point { return Point{mgl32.Vec2{x, y}} } func (p Point) Scale(a float32) Point { return Point{p.Vec2.Mul(a)} } func (p Point) Add(pt Point) Point { return Point{p.Vec2.Add(pt.Vec2)} } func (p Point) Sub(pt Point) Point { return Point{p.Vec2.Sub(pt.Vec2)} } func (p Point) DistanceTo(pt Point) float32 { return p.Sub(pt).Len() } type Rectangle struct { Min Point Max Point } func Rect(x1, y1, x2, y2 float32) Rectangle { return Rectangle{ Min: Pt(x1, y1), Max: Pt(x2, y2), } } func (r Rectangle) Midpoint() Point { return Pt((r.Max.X()+r.Min.X())/2.0, (r.Max.Y()+r.Min.Y())/2.0) } func (r Rectangle) Overlaps(s Rectangle) bool { return s.Min.X() < r.Max.X() && s.Max.X() > r.Min.X() && s.Min.Y() < r.Max.Y() && s.Max.Y() > r.Min.Y() } func (r Rectangle) ContainsPoint(a Point) bool { return r.Min.X() <= a.X() && r.Max.X() >= a.X() && r.Min.Y() <= a.Y() && r.Max.Y() >= a.Y() } // Returns true if r is intersection by the line a, b. func (r Rectangle) IntersectedBy(a, b Point) bool { if a.X() < r.Min.X() && b.X() < r.Min.X() { return false } else if a.X() > r.Max.X() && b.X() > r.Max.X() { return false } else if a.Y() < r.Min.Y() && b.Y() < r.Min.Y() { return false } else if a.Y() > r.Max.Y() && b.Y() > r.Max.Y() { return false } else { // The line is neither totally to the left, right, above, or below // the rectangle. There may be a collision. corners := []Point{ Pt(r.Min.X(), r.Min.Y()), Pt(r.Min.Y(), r.Max.Y()), Pt(r.Max.X(), r.Min.Y()), Pt(r.Max.X(), r.Max.Y()), } eq := GetVectorDeterminantEquation(a, b) lastEvalSide := eq(corners[0]) > 0 for _, corner := range corners[1:] { side := eq(corner) > 0 if side != lastEvalSide { return true } } } return false } func GetVectorDeterminantEquation(a, b Point) func(Point) float32 { return func(p Point) float32 { return (p.X()-a.X())*(b.Y()-a.Y()) - (p.Y()-a.Y())*(b.X()-a.X()) } }
geometry.go
0.852337
0.592755
geometry.go
starcoder
package FlatGeobuf import "strconv" type GeometryType byte const ( GeometryTypeUnknown GeometryType = 0 GeometryTypePoint GeometryType = 1 GeometryTypeLineString GeometryType = 2 GeometryTypePolygon GeometryType = 3 GeometryTypeMultiPoint GeometryType = 4 GeometryTypeMultiLineString GeometryType = 5 GeometryTypeMultiPolygon GeometryType = 6 GeometryTypeGeometryCollection GeometryType = 7 GeometryTypeCircularString GeometryType = 8 GeometryTypeCompoundCurve GeometryType = 9 GeometryTypeCurvePolygon GeometryType = 10 GeometryTypeMultiCurve GeometryType = 11 GeometryTypeMultiSurface GeometryType = 12 GeometryTypeCurve GeometryType = 13 GeometryTypeSurface GeometryType = 14 GeometryTypePolyhedralSurface GeometryType = 15 GeometryTypeTIN GeometryType = 16 GeometryTypeTriangle GeometryType = 17 ) var EnumNamesGeometryType = map[GeometryType]string{ GeometryTypeUnknown: "Unknown", GeometryTypePoint: "Point", GeometryTypeLineString: "LineString", GeometryTypePolygon: "Polygon", GeometryTypeMultiPoint: "MultiPoint", GeometryTypeMultiLineString: "MultiLineString", GeometryTypeMultiPolygon: "MultiPolygon", GeometryTypeGeometryCollection: "GeometryCollection", GeometryTypeCircularString: "CircularString", GeometryTypeCompoundCurve: "CompoundCurve", GeometryTypeCurvePolygon: "CurvePolygon", GeometryTypeMultiCurve: "MultiCurve", GeometryTypeMultiSurface: "MultiSurface", GeometryTypeCurve: "Curve", GeometryTypeSurface: "Surface", GeometryTypePolyhedralSurface: "PolyhedralSurface", GeometryTypeTIN: "TIN", GeometryTypeTriangle: "Triangle", } var EnumValuesGeometryType = map[string]GeometryType{ "Unknown": GeometryTypeUnknown, "Point": GeometryTypePoint, "LineString": GeometryTypeLineString, "Polygon": GeometryTypePolygon, "MultiPoint": GeometryTypeMultiPoint, "MultiLineString": GeometryTypeMultiLineString, "MultiPolygon": GeometryTypeMultiPolygon, "GeometryCollection": GeometryTypeGeometryCollection, "CircularString": GeometryTypeCircularString, "CompoundCurve": GeometryTypeCompoundCurve, "CurvePolygon": GeometryTypeCurvePolygon, "MultiCurve": GeometryTypeMultiCurve, "MultiSurface": GeometryTypeMultiSurface, "Curve": GeometryTypeCurve, "Surface": GeometryTypeSurface, "PolyhedralSurface": GeometryTypePolyhedralSurface, "TIN": GeometryTypeTIN, "Triangle": GeometryTypeTriangle, } func (v GeometryType) String() string { if s, ok := EnumNamesGeometryType[v]; ok { return s } return "GeometryType(" + strconv.FormatInt(int64(v), 10) + ")" }
src/go/FlatGeobuf/GeometryType.go
0.696165
0.587825
GeometryType.go
starcoder
package tf32 import ( "io/ioutil" "math" "os" "github.com/golang/protobuf/proto" pro "github.com/pointlander/gradient/tf32/proto_tf32" ) // LFSRMask is a LFSR mask with a maximum period const LFSRMask = 0x80000057 type ( // RNG is a random number generator RNG uint32 // V is a tensor value V struct { N string // the name Seed RNG Drop float64 X []float32 // the tensor D []float32 // the derivative S []int // the shape } // Set is a set of V Set struct { Weights []*V ByName map[string]*V } // Continuation is a continuation Continuation func(a *V) bool // Meta is a function that takes a continuation and return a continuation Meta func(k Continuation) Continuation // Unary is a unary function Unary func(k Continuation, a *V) bool // Binary is a binary function Binary func(k Continuation, a, b *V) bool // Operation is an operation that takes multiple parameters Operation func(k Continuation, a ...*V) bool ) func abs(a float32) float32 { return float32(math.Abs(float64(a))) } func sin(a float32) float32 { return float32(math.Sin(float64(a))) } func cos(a float32) float32 { return float32(math.Cos(float64(a))) } func exp(a float32) float32 { return float32(math.Exp(float64(a))) } func log(a float32) float32 { return float32(math.Log(float64(a))) } func sqrt(a float32) float32 { return float32(math.Sqrt(float64(a))) } var ( floatBits = math.Float32bits floatFrombits = math.Float32frombits ) const ( QuantizeMask = (1 << 32) - 1 FractionBits = 23 ) // Next returns the next random number func (r *RNG) Next() uint32 { lfsr := *r lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & LFSRMask) *r = lfsr return uint32(lfsr) } // NewV create a new tensor value func NewV(s ...int) V { if len(s) == 1 { s = []int{s[0], 1} } size := s[0] * s[1] return V{ X: make([]float32, 0, size), D: make([]float32, size), S: s, } } // NewV create a new identity tensor value func Identity(s ...int) V { if len(s) == 1 { s = []int{s[0], 1} } if s[0] != s[1] { panic("identity matrix must be square") } size := s[0] * s[1] identity := V{ X: make([]float32, size), D: make([]float32, size), S: s, } j := 0 for i := 0; i < size; i += s[0] { identity.X[i+j] = 1 j++ } return identity } // Panic marks a place we should never get to func Panic(a *V) bool { panic("should not be here") return false } // Copy copies the weights of the value func (a *V) Copy() V { return V{ N: a.N, X: a.X, D: make([]float32, len(a.D)), S: a.S, } } // Meta returns a meta for the value func (a *V) Meta() Meta { return func(k Continuation) Continuation { k(a) return Panic } } // Zero zeros the partial derivatives func (a *V) Zero() { for i := range a.D { a.D[i] = 0 } } // Set sets the values and zeros the partial derivatives func (a *V) Set(values []float32) { for i, value := range values { if i >= len(a.X) { a.X = append(a.X, value) continue } a.X[i] = value } a.Zero() } // NewSet creates a new weight set func NewSet() Set { return Set{ ByName: make(map[string]*V), } } // Add adds weights to a set func (s *Set) Add(name string, d ...int) { v := NewV(d...) v.N = name s.Weights = append(s.Weights, &v) s.ByName[name] = &v } // Get gets weights from the set by name func (s *Set) Get(name string) Meta { return s.ByName[name].Meta() } // Copy generates a copy of a set func (s *Set) Copy() Set { n := NewSet() for i := range s.Weights { cp := s.Weights[i].Copy() n.Weights = append(n.Weights, &cp) n.ByName[cp.N] = &cp } return n } // Zero zeros the partial derivatives func (s *Set) Zero() { for i := range s.Weights { s.Weights[i].Zero() } } // Save saves a set of weights func (s *Set) Save(file string, cost float32, epoch int) error { set := pro.Set{ Cost: float64(cost), Epoch: uint64(epoch), } for _, w := range s.Weights { shape := make([]int64, len(w.S)) for i := range shape { shape[i] = int64(w.S[i]) } weights := pro.Weights{ Name: w.N, Shape: shape, Values: w.X, } set.Weights = append(set.Weights, &weights) } out, err := proto.Marshal(&set) if err != nil { return err } output, err := os.Create(file) if err != nil { return err } defer output.Close() _, err = output.Write(out) if err != nil { return err } return nil } // Open opens a set of weights func (s *Set) Open(name string) (float32, int, error) { in, err := ioutil.ReadFile(name) if err != nil { return 0, 0, err } set := pro.Set{} err = proto.Unmarshal(in, &set) if err != nil { return 0, 0, err } for _, w := range set.Weights { shape := make([]int, len(w.Shape)) for i, s := range w.Shape { shape[i] = int(s) } v := V{ N: w.Name, X: w.Values, D: make([]float32, len(w.Values)), S: shape, } s.Weights = append(s.Weights, &v) s.ByName[v.N] = &v } return float32(set.Cost), int(set.Epoch), nil } // Context is a function context type Context struct { Quantize uint } // Add adds two tensors func (context *Context) Add(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } width, length := a.S[0], len(b.X) if width != b.S[0] || (a.S[1] != b.S[1] && b.S[1] != 1) { panic("dimensions are not the same") } c := NewV(a.S...) if a.Seed != 0 { dropout, index := uint32((1-a.Drop)*math.MaxUint32), 0 c.Seed, c.Drop = a.Seed, a.Drop for i := 0; i < a.S[1]; i++ { rng := a.Seed for j := 0; j < a.S[0]; j++ { if rng.Next() > dropout { c.X = append(c.X, 0) index++ continue } c.X = append(c.X, a.X[index]+b.X[index%length]) index++ } } if k(&c) { return true } index = 0 for i := 0; i < a.S[1]; i++ { rng := a.Seed for j := 0; j < a.S[0]; j++ { if rng.Next() > dropout { index++ continue } d := c.D[index] a.D[index] += d b.D[index%length] += d index++ } } return false } for i, j := range a.X { c.X = append(c.X, j+b.X[i%length]) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j b.D[i%length] += j } return false } // Sub subtracts two tensors func (context *Context) Sub(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } width, length := a.S[0], len(b.X) if width != b.S[0] || (a.S[1] != b.S[1] && b.S[1] != 1) { panic("dimensions are not the same") } c := NewV(a.S...) for i, j := range a.X { c.X = append(c.X, j-b.X[i%length]) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j b.D[i%length] -= j } return false } // Mul multiplies two tensors func (context *Context) Mul(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } width := a.S[0] if width != b.S[0] { panic("first dimension is not the same") } sizeA, sizeB, c, done := len(a.X), len(b.X), NewV(a.S[1], b.S[1]), make(chan bool, 8) c.X = c.X[:cap(c.X)] if a.Seed != 0 { c.Seed, c.Drop = a.Seed, a.Drop dropout := uint32((1 - a.Drop) * math.MaxUint32) mul := func(bv []float32, i int) { rng := a.Seed for j := 0; j < sizeA; j += width { if rng.Next() > dropout { i++ continue } av := a.X[j : j+width] sum := dot(av, bv) c.X[i] = sum i++ } done <- true } index, step := 0, sizeA/width for i := 0; i < sizeB; i += width { go mul(b.X[i:i+width], index) index += step } for i := 0; i < sizeB; i += width { <-done } if k(&c) { return true } done = make(chan bool, 8) // a derivatives go func() { derivativeDone := make(chan bool, 8) derivatives := func(index int, ad []float32) { rows, bi := a.S[1], 0 for i := 0; i < sizeB; i += width { bv, cd := b.X[i:i+width], c.D[index+bi*rows] axpy(cd, bv, ad) bi++ } derivativeDone <- true } index, rng := 0, a.Seed for j := 0; j < sizeA; j += width { if rng.Next() > dropout { index++ continue } ad := a.D[j : j+width] go derivatives(index, ad) index++ } rng = a.Seed for j := 0; j < sizeA; j += width { if rng.Next() > dropout { continue } <-derivativeDone } done <- true }() // b derivatives derivativeDone := make(chan bool, 8) derivatives := func(index int, bd []float32) { rng := a.Seed for j := 0; j < sizeA; j += width { if rng.Next() > dropout { index++ continue } av, cd := a.X[j:j+width], c.D[index] axpy(cd, av, bd) index++ } derivativeDone <- true } index, rows := 0, a.S[1] for i := 0; i < sizeB; i += width { bd := b.D[i : i+width] go derivatives(index, bd) index += rows } for i := 0; i < sizeB; i += width { <-derivativeDone } <-done return false } mul := func(bv []float32, i int) { for j := 0; j < sizeA; j += width { av, sum := a.X[j:j+width], float32(0.0) for k, bx := range bv { sum += av[k] * bx } c.X[i] = sum i++ } done <- true } index, step := 0, sizeA/width for i := 0; i < sizeB; i += width { go mul(b.X[i:i+width], index) index += step } for i := 0; i < sizeB; i += width { <-done } if k(&c) { return true } done = make(chan bool, 8) // a derivatives go func() { derivativeDone := make(chan bool, 8) derivatives := func(index int, ad []float32) { rows, bi := a.S[1], 0 for i := 0; i < sizeB; i += width { bv, cd := b.X[i:i+width], c.D[index+bi*rows] axpy(cd, bv, ad) bi++ } derivativeDone <- true } index := 0 for j := 0; j < sizeA; j += width { ad := a.D[j : j+width] go derivatives(index, ad) index++ } for j := 0; j < sizeA; j += width { <-derivativeDone } done <- true }() // b derivatives derivativeDone := make(chan bool, 8) derivatives := func(index int, bd []float32) { for j := 0; j < sizeA; j += width { av, cd := a.X[j:j+width], c.D[index] axpy(cd, av, bd) index++ } derivativeDone <- true } index, rows := 0, a.S[1] for i := 0; i < sizeB; i += width { bd := b.D[i : i+width] go derivatives(index, bd) index += rows } for i := 0; i < sizeB; i += width { <-derivativeDone } <-done return false } // Hadamard computes the hadamard product of two tensors func (context *Context) Hadamard(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } if a.S[0] != b.S[0] || a.S[1] != b.S[1] { panic("dimensions are not the same") } c := NewV(a.S...) for i, j := range a.X { c.X = append(c.X, j*b.X[i]) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j * b.X[i] b.D[i] += j * a.X[i] } return false } // T the transpose of the matrix func (context *Context) T(k Continuation, a *V) bool { c := NewV(a.S[1], a.S[0]) for p := 0; p < a.S[0]; p++ { for q := 0; q < a.S[1]; q++ { c.X = append(c.X, a.X[q*a.S[0]+p]) } } if k(&c) { return true } i := 0 for p := 0; p < a.S[0]; p++ { for q := 0; q < a.S[1]; q++ { a.D[q*a.S[0]+p] += c.D[i] i++ } } return false } // T the transpose of the matrix func (context *Context) Slice(k Continuation, a *V, b *V) bool { if b.S[0] != 2 && b.S[1] != 1 { panic("invalid size for slice") } width := a.S[0] begin, end := int(b.X[0]), int(b.X[1]) c, size := NewV(end-begin, a.S[1]), len(a.X) for i := 0; i < size; i += width { av := a.X[i+begin : i+end] for _, ax := range av { c.X = append(c.X, ax) } } if k(&c) { return true } index := 0 for i := 0; i < size; i += width { ad := a.D[i+begin : i+end] for j := range ad { ad[j] += c.D[index] index++ } } return false } // Concat concats two tensors func (context *Context) Concat(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } if a.S[1] != b.S[1] { panic("dimensions are not the same") } widthA, widthB := a.S[0], b.S[0] c, i, j := NewV(widthA+widthB, a.S[1]), 0, 0 for r := 0; r < a.S[1]; r++ { av, bv := a.X[i:i+widthA], b.X[j:j+widthB] c.X = append(c.X, av...) c.X = append(c.X, bv...) i += widthA j += widthB } if k(&c) { return true } index, i, j := 0, 0, 0 for r := 0; r < a.S[1]; r++ { ad, bd := a.D[i:i+widthA], b.D[j:j+widthB] for s := range ad { ad[s] = c.D[index] index++ } for s := range bd { bd[s] = c.D[index] index++ } i += widthA j += widthB } return false } // Sin the sine of a number func (context *Context) Sin(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { c.X = append(c.X, sin(j)) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j * cos(a.X[i]) } return false } // Cos the cosine of a tensor func (context *Context) Cos(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { c.X = append(c.X, cos(j)) } if k(&c) { return true } for i, j := range c.D { a.D[i] -= j * sin(a.X[i]) } return false } // Exp the base e exponential of a tensor func (context *Context) Exp(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { c.X = append(c.X, exp(j)) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j * c.X[i] } return false } // Log the natural logarithm of a tensor func (context *Context) Log(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { c.X = append(c.X, log(j)) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j / a.X[i] } return false } // Sigmoid computes the sigmoid of a vector func (context *Context) Sigmoid(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { e := exp(j) c.X = append(c.X, e/(e+1)) } if k(&c) { return true } for i, j := range c.D { cx := c.X[i] a.D[i] += j * cx * (1 - cx) } return false } // TanH the hyperbolic tangent of a tensor func (context *Context) TanH(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { e1, e2 := exp(j), exp(-j) c.X = append(c.X, (e1-e2)/(e1+e2)) } if k(&c) { return true } for i, j := range c.D { cx := c.X[i] a.D[i] += j * (1 - cx*cx) } return false } // Softplus the softplus activation function func (context *Context) Softplus(k Continuation, a *V) bool { c := NewV(a.S...) for _, j := range a.X { c.X = append(c.X, log(1+exp(j))) } if k(&c) { return true } for i, j := range c.D { a.D[i] += j / (1 + exp(-a.X[i])) } return false } // Everett computes the split reality activation function func (context *Context) Everett(k Continuation, a *V) bool { c := NewV(2*a.S[0], a.S[1]) if a.Seed != 0 { c.Seed, c.Drop = a.Seed, a.Drop index, dropout, factor := 0, uint32((1-a.Drop)*math.MaxUint32), float32(1/(1-a.Drop)) for i := 0; i < a.S[1]; i++ { rng := a.Seed for j := 0; j < a.S[0]; j++ { if rng.Next() > dropout { c.X = append(c.X, 0, 0) index++ continue } ax := a.X[index] min, max := ax, ax if min > 0 { min = 0 } if max < 0 { max = 0 } c.X = append(c.X, min*factor, max*factor) index++ } } if k(&c) { return true } index = 0 for i := 0; i < a.S[1]; i++ { rng := a.Seed for j := 0; j < a.S[0]; j++ { if rng.Next() > dropout { index += 2 continue } if c.X[index] != 0 || (c.X[index] == 0 && c.X[index+1] == 0) { a.D[index>>1] += c.D[index] } if c.X[index+1] != 0 || (c.X[index] == 0 && c.X[index+1] == 0) { a.D[index>>1] += c.D[index+1] } index += 2 } } return false } for _, j := range a.X { min, max := j, j if min > 0 { min = 0 } if max < 0 { max = 0 } c.X = append(c.X, min, max) } if k(&c) { return true } for i, j := range c.D { if c.X[i] != 0 || (c.X[i&^1] == 0 && c.X[i|1] == 0) { a.D[i>>1] += j } } return false } func (context *Context) EverettReLu(k Continuation, a *V) bool { c := NewV(2*a.S[0], a.S[1]) for _, j := range a.X { max := j if max < 0 { max = 0 } c.X = append(c.X, 0, max) } if k(&c) { return true } for i, j := range c.D { if c.X[i] != 0 { a.D[i>>1] += j } } return false } // Softmax is the softmax function func (context *Context) Softmax(k Continuation, a *V) bool { c, size, width := NewV(a.S...), len(a.X), a.S[0] for i := 0; i < size; i += width { sum := float32(0.0) for _, ax := range a.X[i : i+width] { e := exp(ax) sum += e c.X = append(c.X, e) } for j, cx := range c.X[i : i+width] { c.X[i+j] = cx / sum } } if k(&c) { return true } for i, d := range c.D { cx := c.X[i] a.D[i] += d * (cx - cx*cx) } return false } // Sum sums a vector func (context *Context) Sum(k Continuation, a *V) bool { c, sum := NewV(1), float32(0.0) for _, j := range a.X { sum += j } c.X = append(c.X, sum) if k(&c) { return true } d := c.D[0] for i := range a.D { a.D[i] += d } return false } // Quadratic computes the quadratic cost of two tensors func (context *Context) Quadratic(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } width := a.S[0] if width != b.S[0] || a.S[1] != b.S[1] { panic("dimensions are not the same") } c, size := NewV(a.S[1]), len(a.X) for i := 0; i < size; i += width { av, bv, sum := a.X[i:i+width], b.X[i:i+width], float32(0.0) for j, ax := range av { p := (ax - bv[j]) sum += p * p } c.X = append(c.X, .5*sum) } if k(&c) { return true } index := 0 for i := 0; i < size; i += width { av, bv, ad, bd, d := a.X[i:i+width], b.X[i:i+width], a.D[i:i+width], b.D[i:i+width], c.D[index] for j, ax := range av { ad[j] += (ax - bv[j]) * d bd[j] += (bv[j] - ax) * d } index++ } return false } // CrossEntropy computes the cross entropy cost of two tensors func (context *Context) CrossEntropy(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } width := a.S[0] if width != b.S[0] || a.S[1] != b.S[1] { panic("dimensions are not the same") } c, size := NewV(a.S[1]), len(a.X) for i := 0; i < size; i += width { av, bv, sum := a.X[i:i+width], b.X[i:i+width], float32(0.0) for j, ax := range av { bx := bv[j] if bx == 1 { sum += log(ax + .001) } else { sum += log(1 - ax + .001) } } c.X = append(c.X, -sum) } if k(&c) { return true } index := 0 for i := 0; i < size; i += width { av, bv, ad, bd, d := a.X[i:i+width], b.X[i:i+width], a.D[i:i+width], b.D[i:i+width], c.D[index] for j, ax := range av { bx := bv[j] if bx == 1 { ad[j] -= d / (ax + .001) bd[j] -= log(ax+.001) * d } else { ad[j] += d / (1 - ax + .001) bd[j] -= log(1-ax+.001) * d } } index++ } return false } // Similarity computes the cosine similarity cost of two tensors func (context *Context) Similarity(k Continuation, a, b *V) bool { if len(a.S) != 2 || len(b.S) != 2 { panic("tensor needs to have two dimensions") } width := a.S[0] if width != b.S[0] || a.S[1] != b.S[1] { panic("dimensions are not the same") } length := a.S[1] c, size := NewV(length), len(a.X) ab, aa, bb := make([]float32, 0, length), make([]float32, 0, length), make([]float32, 0, length) for i := 0; i < size; i += width { av, bv := a.X[i:i+width], b.X[i:i+width] sumAB, sumAA, sumBB := float32(0.0), float32(0.0), float32(0.0) for j, ax := range av { bx := bv[j] sumAB += ax * bx sumAA += ax * ax sumBB += bx * bx } c.X, ab, aa, bb = append(c.X, sumAB/(sqrt(sumAA)*sqrt(sumBB))), append(ab, sumAB), append(aa, sumAA), append(bb, sumBB) } if k(&c) { return true } index := 0 for i := 0; i < size; i += width { av, bv, ad, bd, cd := a.X[i:i+width], b.X[i:i+width], a.D[i:i+width], b.D[i:i+width], c.D[index] sumAB, sumAA, sumBB := ab[index], aa[index], bb[index] denominator := sqrt(sumAA) * sqrt(sumBB) for j, ax := range av { bx := bv[j] ad[j] += cd * (bx/denominator - ax*sumAB/(sumAA*denominator)) bd[j] += cd * (ax/denominator - bx*sumAB/(sumBB*denominator)) } index++ } return false } // Orthogonality computes the cosine similarity between all vectros func (context *Context) Orthogonality(k Continuation, a *V) bool { if len(a.S) != 2 { panic("tensor needs to have two dimensions") } length := ((a.S[1] - 1) * a.S[1]) / 2 c, size, width := NewV(length), len(a.X), a.S[0] ab, aa, bb := make([]float32, 0, length), make([]float32, 0, length), make([]float32, 0, length) for i := 0; i < size; i += width { for j := i + width; j < size; j += width { sumAB, sumAA, sumBB := float32(0.0), float32(0.0), float32(0.0) for k := 0; k < width; k++ { a, b := a.X[i+k], a.X[j+k] sumAB += a * b sumAA += a * a sumBB += b * b } c.X, ab, aa, bb = append(c.X, sumAB/(sqrt(sumAA)*sqrt(sumBB))), append(ab, sumAB), append(aa, sumAA), append(bb, sumBB) } } if k(&c) { return true } index := 0 for i := 0; i < size; i += width { for j := i + width; j < size; j += width { cd, sumAB, sumAA, sumBB := c.D[index], ab[index], aa[index], bb[index] denominator := sqrt(sumAA) * sqrt(sumBB) for k := 0; k < width; k++ { ax, bx := a.X[i+k], a.X[j+k] a.D[i+k] += cd * (bx/denominator - ax*sumAB/(sumAA*denominator)) a.D[j+k] += cd * (ax/denominator - bx*sumAB/(sumBB*denominator)) } index++ } } return false } // Entropy computes the entropy of the vectors func (context *Context) Entropy(k Continuation, a *V) bool { if len(a.S) != 2 { panic("tensor needs to have two dimensions") } c, size, width := NewV(a.S[1]), len(a.X), a.S[0] for i := 0; i < size; i += width { sum := float32(0.0) for k := 0; k < width; k++ { ax := a.X[i+k] sum += ax * log(ax) } c.X = append(c.X, -sum) } if k(&c) { return true } index := 0 for i := 0; i < size; i += width { cd := c.D[index] for k := 0; k < width; k++ { ax := a.X[i+k] a.D[i+k] -= cd * (log(ax) + 1) } index++ } return false } // Variance computes the variance of the vectors func (context *Context) Variance(k Continuation, a *V) bool { if len(a.S) != 2 { panic("tensor needs to have two dimensions") } length := a.S[1] c, size, width, means := NewV(length), len(a.X), a.S[0], make([]float32, 0, length) n := float32(width) for i := 0; i < size; i += width { sum := float32(0.0) for k := 0; k < width; k++ { sum += a.X[i+k] } mean := sum / n sum = float32(0.0) for k := 0; k < width; k++ { d := a.X[i+k] - mean sum += d * d } c.X, means = append(c.X, sum/n), append(means, mean) } if k(&c) { return true } index, nn := 0, n*n for i := 0; i < size; i += width { cd, mean := c.D[index], means[index] for j := 0; j < width; j++ { sum := float32(0.0) for k := 0; k < width; k++ { d := a.X[i+k] - mean if j == k { d *= (n - 1) } else { d *= -1 } sum += d } a.D[i+j] += cd * 2 * sum / nn } index++ } return false } // Abs computes the absolute value of the tensor func (context *Context) Abs(k Continuation, a *V) bool { c := NewV(a.S...) for _, ax := range a.X { c.X = append(c.X, abs(ax)) } if k(&c) { return true } for i, cd := range c.D { sign := float32(1) if a.X[i] < 0 { sign = -1 } a.D[i] += cd * sign } return false } // Quantize quantizes the values func (context *Context) Quant(k Continuation, a *V) bool { if context.Quantize > FractionBits { panic("too much quantization") } c := NewV(a.S...) for _, ax := range a.X { bits := floatBits(ax) bits &= QuantizeMask << context.Quantize c.X = append(c.X, floatFrombits(bits)) } if k(&c) { return true } for i, cd := range c.D { a.D[i] += cd } return false } // Avg computes the average of the tensor func (context *Context) Avg(k Continuation, a *V) bool { c, sum := NewV(1), float32(0.0) for _, j := range a.X { sum += j } total := float32(len(a.X)) c.X = append(c.X, sum/total) if k(&c) { return true } d := c.D[0] / total for i := range a.D { a.D[i] += d } return false } // Op is a operation func Op(op Operation) func(a ...Meta) Meta { return func(a ...Meta) Meta { return func(k Continuation) Continuation { var call func(a []Meta, b []*V) (bool, Continuation) call = func(a []Meta, b []*V) (bool, Continuation) { if len(a) == 0 { return op(k, b...), nil } derivatives := false continuation := a[0](func(c *V) bool { derivatives, _ = call(a[1:], append(b, c)) return derivatives }) return derivatives, continuation } _, continuation := call(a, make([]*V, 0, len(a))) return continuation } } } // B converts a binary function into an operator func B(op Binary) func(a, b Meta) Meta { return func(a, b Meta) Meta { return func(k Continuation) Continuation { return a(func(a *V) bool { derivatives := false b(func(b *V) bool { derivatives = op(k, a, b) return derivatives }) return derivatives }) } } } // U converts a unary function into an operator func U(op Unary) func(a Meta) Meta { return func(a Meta) Meta { return func(k Continuation) Continuation { return a(func(b *V) bool { return op(k, b) }) } } } var ( // Static is the static context Static Context // Add adds two tensors Add = B(Static.Add) // Sub subtracts two tensors Sub = B(Static.Sub) // Mul multiplies two tensors Mul = B(Static.Mul) // Hadamard computes the hadamard product of two tensors Hadamard = B(Static.Hadamard) // T the transpose of the matrix T = U(Static.T) // Slice slices the matrix Slice = B(Static.Slice) // Concat concats two tensors Concat = B(Static.Concat) // Sin the sin of a tensors Sin = U(Static.Sin) // Cos the cosine of a tensor Cos = U(Static.Cos) // Exp the base e exponential of a tensor Exp = U(Static.Exp) // Log the natural logarithm of a tensor Log = U(Static.Log) // Sigmoid the sigmoid of a tensors Sigmoid = U(Static.Sigmoid) // TanH the hyperbolic tangent of a tensor TanH = U(Static.TanH) // Softplus the softplus activation function Softplus = U(Static.Softplus) // Everett computes the split reality activation function Everett = U(Static.Everett) EverettReLu = U(Static.EverettReLu) // Softmax is the softmax function Softmax = U(Static.Softmax) // Sum sums a vector Sum = U(Static.Sum) // Quadratic computes the quadratic cost of two tensors Quadratic = B(Static.Quadratic) // CrossEntropy computes the cross entropy cost of two tensors CrossEntropy = B(Static.CrossEntropy) // Similarity computes the cosine similarity cost of two tensors Similarity = B(Static.Similarity) // Orthogonality computes the cosine similarity between all vectros Orthogonality = U(Static.Orthogonality) // Entropy computes the entropy of the vectors Entropy = U(Static.Entropy) // Variance computes the variance of the vectors Variance = U(Static.Variance) // Abs computes the absolute value of the tensor Abs = U(Static.Abs) // Quantize quantizes the values Quant = U(Static.Quant) // Avg computes the average of the tensor Avg = U(Static.Avg) ) // Gradient computes the gradient func Gradient(a Meta) (cost V) { a(func(a *V) bool { cost = *a a.D[0] = 1 return false }) return }
tf32/gradient.go
0.796728
0.420124
gradient.go
starcoder
package spin import ( "fmt" "io" "os" "sync/atomic" "time" ) // ClearLine go to the beginning of the line and clear it const ClearLine = "\r\033[K" // Spinner types. var ( Box1 = `⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏` Box2 = `⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓` Box3 = `⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆` Box4 = `⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋` Box5 = `⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁` Box6 = `⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈` Box7 = `⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈` Spin1 = `|/-\` Spin2 = `◴◷◶◵` Spin3 = `◰◳◲◱` Spin4 = `◐◓◑◒` Spin5 = `▉▊▋▌▍▎▏▎▍▌▋▊▉` Spin6 = `▌▄▐▀` Spin7 = `╫╪` Spin8 = `■□▪▫` Spin9 = `←↑→↓` Spin10 = `⦾⦿` Spin11 = `⌜⌝⌟⌞` Spin12 = `┤┘┴└├┌┬┐` Spin13 = `⇑⇗⇒⇘⇓⇙⇐⇖` Spin14 = `☰☱☳☷☶☴` Spin15 = `䷀䷪䷡䷊䷒䷗䷁䷖䷓䷋䷠䷫` Default = Box1 ) // Spinner main type type Spinner struct { frames []rune pos int active uint64 text string tpf time.Duration writer io.Writer } // Option describes an option to override a default // when creating a new Spinner. type Option func(s *Spinner) // New creates a Spinner object with the provided // text. By default, the Default spinner frames are // used, and new frames are rendered every 100 milliseconds. // Options can be provided to override these default // settings. func New(text string, opts ...Option) *Spinner { s := &Spinner{ text: ClearLine + text, frames: []rune(Default), tpf: 100 * time.Millisecond, writer: os.Stdout, } for _, o := range opts { o(s) } return s } // WithFrames sets the frames string. func WithFrames(frames string) Option { return func(s *Spinner) { s.Set(frames) } } // WithTimePerFrame sets how long each frame shall // be shown. func WithTimePerFrame(d time.Duration) Option { return func(s *Spinner) { s.tpf = d } } // WithWriter sets the writer to use for spinner's text. func WithWriter(w io.Writer) Option { return func(s *Spinner) { s.writer = w } } // Set frames to the given string which must not use spaces. func (s *Spinner) Set(frames string) { s.frames = []rune(frames) } // Start shows the spinner. func (s *Spinner) Start() *Spinner { if atomic.LoadUint64(&s.active) > 0 { return s } atomic.StoreUint64(&s.active, 1) go func() { for atomic.LoadUint64(&s.active) > 0 { fmt.Fprintf(s.writer, s.text, s.next()) time.Sleep(s.tpf) } }() return s } // Stop hides the spinner. func (s *Spinner) Stop() bool { if x := atomic.SwapUint64(&s.active, 0); x > 0 { fmt.Fprintf(s.writer, ClearLine) return true } return false } func (s *Spinner) next() string { r := s.frames[s.pos%len(s.frames)] s.pos++ return string(r) }
spin.go
0.602529
0.458106
spin.go
starcoder
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
lang/Go/solve-a-hopido-puzzle-1.go
0.571288
0.419945
solve-a-hopido-puzzle-1.go
starcoder
package xiso import ( "regexp" "strings" "time" ) // iso3166LastUpdate is used in tests to trigger an check to update the data. // This is the best thing for now, as there is no good way to check this online. var iso3166LastUpdate = time.Date(2021, 12, 5, 0, 0, 0, 0, time.UTC) type Country struct { Name string Alpha2 string Alpha3 string Numeric int } // ReCountryAlpha2 is a regular expression matching ISO 3166-1 Alpha-2 // country codes. This not checks it validity; merely the format. var ReCountryAlpha2 = regexp.MustCompile("(?i)^[A-Z]{2}$") // ReCountryAlpha3 is a regular expression matching ISO 3166-1 Alpha-3 // country codes. This not checks it validity; merely the format. var ReCountryAlpha3 = regexp.MustCompile("(?i)^[A-Z]{3}$") // IsEmpty returns whether c is empty. This can be used when looking up // a country, and country is not available. func (c Country) IsEmpty() bool { return c == (Country{}) } type countries []Country // CountryAlpha2 looks up country using its 2-letter code (Alpha-2). // If not found, the empty country is returned, which can be checked using // the method Country.IsEmpty. The look-up is case-insensitive. // The caller is responsible in implementing some kind of caching mechanism. func CountryAlpha2(code string) Country { if len(code) != 2 || !ReCountryAlpha2.MatchString(code) { return Country{} } code = strings.ToUpper(code) for _, c := range iso3166Countries { if c.Alpha2 == code { return c } } return Country{} } // CountryAlpha3 looks up country using its 3-letter code (Alpha-3). // If not found, the empty country is returned, which can be checked using // the method Country.IsEmpty. The look-up is case-insensitive. // The caller is responsible in implementing some kind of caching mechanism. func CountryAlpha3(code string) Country { if len(code) != 3 || !ReCountryAlpha3.MatchString(code) { return Country{} } code = strings.ToUpper(code) for _, c := range iso3166Countries { if c.Alpha3 == code { return c } } return Country{} } // iso3166Alpha2 holds ISO 3166 country information including the 2 and 3 letter code. // Source: https://www.iso.org/iso-3166-country-codes.html // 😉 // ([A-Z]{2})([A-Z]{3})(\d{3})\n -> $1\t$2\t$3\n // (.*?)\t.*?\t(.*) -> $1\t$2 // ^(.*?)\t([A-Z]{2})\t([A-Z]{3})\t0{0,2}(\d{1,3})$ -> {\nName: "$1",\nAlpha2:"$2",\nAlpha3:"$3",\nNumeric:$4,\n}, var iso3166Countries = countries{ { Name: "Afghanistan", Alpha2: "AF", Alpha3: "AFG", Numeric: 4, }, { Name: "Albania", Alpha2: "AL", Alpha3: "ALB", Numeric: 8, }, { Name: "Algeria", Alpha2: "DZ", Alpha3: "DZA", Numeric: 12, }, { Name: "American Samoa", Alpha2: "AS", Alpha3: "ASM", Numeric: 16, }, { Name: "Andorra", Alpha2: "AD", Alpha3: "AND", Numeric: 20, }, { Name: "Angola", Alpha2: "AO", Alpha3: "AGO", Numeric: 24, }, { Name: "Anguilla", Alpha2: "AI", Alpha3: "AIA", Numeric: 660, }, { Name: "Antarctica", Alpha2: "AQ", Alpha3: "ATA", Numeric: 10, }, { Name: "Antigua and Barbuda", Alpha2: "AG", Alpha3: "ATG", Numeric: 28, }, { Name: "Argentina", Alpha2: "AR", Alpha3: "ARG", Numeric: 32, }, { Name: "Armenia", Alpha2: "AM", Alpha3: "ARM", Numeric: 51, }, { Name: "Aruba", Alpha2: "AW", Alpha3: "ABW", Numeric: 533, }, { Name: "Australia", Alpha2: "AU", Alpha3: "AUS", Numeric: 36, }, { Name: "Austria", Alpha2: "AT", Alpha3: "AUT", Numeric: 40, }, { Name: "Azerbaijan", Alpha2: "AZ", Alpha3: "AZE", Numeric: 31, }, { Name: "Bahamas (the)", Alpha2: "BS", Alpha3: "BHS", Numeric: 44, }, { Name: "Bahrain", Alpha2: "BH", Alpha3: "BHR", Numeric: 48, }, { Name: "Bangladesh", Alpha2: "BD", Alpha3: "BGD", Numeric: 50, }, { Name: "Barbados", Alpha2: "BB", Alpha3: "BRB", Numeric: 52, }, { Name: "Belarus", Alpha2: "BY", Alpha3: "BLR", Numeric: 112, }, { Name: "Belgium", Alpha2: "BE", Alpha3: "BEL", Numeric: 56, }, { Name: "Belize", Alpha2: "BZ", Alpha3: "BLZ", Numeric: 84, }, { Name: "Benin", Alpha2: "BJ", Alpha3: "BEN", Numeric: 204, }, { Name: "Bermuda", Alpha2: "BM", Alpha3: "BMU", Numeric: 60, }, { Name: "Bhutan", Alpha2: "BT", Alpha3: "BTN", Numeric: 64, }, { Name: "Bolivia (Plurinational State of)", Alpha2: "BO", Alpha3: "BOL", Numeric: 68, }, { Name: "Bonaire, Sint Eustatius and Saba", Alpha2: "BQ", Alpha3: "BES", Numeric: 535, }, { Name: "Bosnia and Herzegovina", Alpha2: "BA", Alpha3: "BIH", Numeric: 70, }, { Name: "Botswana", Alpha2: "BW", Alpha3: "BWA", Numeric: 72, }, { Name: "Bouvet Island", Alpha2: "BV", Alpha3: "BVT", Numeric: 74, }, { Name: "Brazil", Alpha2: "BR", Alpha3: "BRA", Numeric: 76, }, { Name: "British Indian Ocean Territory (the)", Alpha2: "IO", Alpha3: "IOT", Numeric: 86, }, { Name: "<NAME>", Alpha2: "BN", Alpha3: "BRN", Numeric: 96, }, { Name: "Bulgaria", Alpha2: "BG", Alpha3: "BGR", Numeric: 100, }, { Name: "<NAME>", Alpha2: "BF", Alpha3: "BFA", Numeric: 854, }, { Name: "Burundi", Alpha2: "BI", Alpha3: "BDI", Numeric: 108, }, { Name: "<NAME>", Alpha2: "CV", Alpha3: "CPV", Numeric: 132, }, { Name: "Cambodia", Alpha2: "KH", Alpha3: "KHM", Numeric: 116, }, { Name: "Cameroon", Alpha2: "CM", Alpha3: "CMR", Numeric: 120, }, { Name: "Canada", Alpha2: "CA", Alpha3: "CAN", Numeric: 124, }, { Name: "Cayman Islands (the)", Alpha2: "KY", Alpha3: "CYM", Numeric: 136, }, { Name: "Central African Republic (the)", Alpha2: "CF", Alpha3: "CAF", Numeric: 140, }, { Name: "Chad", Alpha2: "TD", Alpha3: "TCD", Numeric: 148, }, { Name: "Chile", Alpha2: "CL", Alpha3: "CHL", Numeric: 152, }, { Name: "China", Alpha2: "CN", Alpha3: "CHN", Numeric: 156, }, { Name: "<NAME>", Alpha2: "CX", Alpha3: "CXR", Numeric: 162, }, { Name: "Cocos (Keeling) Islands (the)", Alpha2: "CC", Alpha3: "CCK", Numeric: 166, }, { Name: "Colombia", Alpha2: "CO", Alpha3: "COL", Numeric: 170, }, { Name: "Comoros (the)", Alpha2: "KM", Alpha3: "COM", Numeric: 174, }, { Name: "Congo (the Democratic Republic of the)", Alpha2: "CD", Alpha3: "COD", Numeric: 180, }, { Name: "Congo (the)", Alpha2: "CG", Alpha3: "COG", Numeric: 178, }, { Name: "Cook Islands (the)", Alpha2: "CK", Alpha3: "COK", Numeric: 184, }, { Name: "<NAME>", Alpha2: "CR", Alpha3: "CRI", Numeric: 188, }, { Name: "Croatia", Alpha2: "HR", Alpha3: "HRV", Numeric: 191, }, { Name: "Cuba", Alpha2: "CU", Alpha3: "CUB", Numeric: 192, }, { Name: "Curaçao", Alpha2: "CW", Alpha3: "CUW", Numeric: 531, }, { Name: "Cyprus", Alpha2: "CY", Alpha3: "CYP", Numeric: 196, }, { Name: "Czechia", Alpha2: "CZ", Alpha3: "CZE", Numeric: 203, }, { Name: "<NAME>", Alpha2: "CI", Alpha3: "CIV", Numeric: 384, }, { Name: "Denmark", Alpha2: "DK", Alpha3: "DNK", Numeric: 208, }, { Name: "Djibouti", Alpha2: "DJ", Alpha3: "DJI", Numeric: 262, }, { Name: "Dominica", Alpha2: "DM", Alpha3: "DMA", Numeric: 212, }, { Name: "Dominican Republic (the)", Alpha2: "DO", Alpha3: "DOM", Numeric: 214, }, { Name: "Ecuador", Alpha2: "EC", Alpha3: "ECU", Numeric: 218, }, { Name: "Egypt", Alpha2: "EG", Alpha3: "EGY", Numeric: 818, }, { Name: "<NAME>", Alpha2: "SV", Alpha3: "SLV", Numeric: 222, }, { Name: "Equatorial Guinea", Alpha2: "GQ", Alpha3: "GNQ", Numeric: 226, }, { Name: "Eritrea", Alpha2: "ER", Alpha3: "ERI", Numeric: 232, }, { Name: "Estonia", Alpha2: "EE", Alpha3: "EST", Numeric: 233, }, { Name: "Eswatini", Alpha2: "SZ", Alpha3: "SWZ", Numeric: 748, }, { Name: "Ethiopia", Alpha2: "ET", Alpha3: "ETH", Numeric: 231, }, { Name: "Falkland Islands (the) [Malvinas]", Alpha2: "FK", Alpha3: "FLK", Numeric: 238, }, { Name: "Faroe Islands (the)", Alpha2: "FO", Alpha3: "FRO", Numeric: 234, }, { Name: "Fiji", Alpha2: "FJ", Alpha3: "FJI", Numeric: 242, }, { Name: "Finland", Alpha2: "FI", Alpha3: "FIN", Numeric: 246, }, { Name: "France", Alpha2: "FR", Alpha3: "FRA", Numeric: 250, }, { Name: "French Guiana", Alpha2: "GF", Alpha3: "GUF", Numeric: 254, }, { Name: "French Polynesia", Alpha2: "PF", Alpha3: "PYF", Numeric: 258, }, { Name: "French Southern Territories (the)", Alpha2: "TF", Alpha3: "ATF", Numeric: 260, }, { Name: "Gabon", Alpha2: "GA", Alpha3: "GAB", Numeric: 266, }, { Name: "Gambia (the)", Alpha2: "GM", Alpha3: "GMB", Numeric: 270, }, { Name: "Georgia", Alpha2: "GE", Alpha3: "GEO", Numeric: 268, }, { Name: "Germany", Alpha2: "DE", Alpha3: "DEU", Numeric: 276, }, { Name: "Ghana", Alpha2: "GH", Alpha3: "GHA", Numeric: 288, }, { Name: "Gibraltar", Alpha2: "GI", Alpha3: "GIB", Numeric: 292, }, { Name: "Greece", Alpha2: "GR", Alpha3: "GRC", Numeric: 300, }, { Name: "Greenland", Alpha2: "GL", Alpha3: "GRL", Numeric: 304, }, { Name: "Grenada", Alpha2: "GD", Alpha3: "GRD", Numeric: 308, }, { Name: "Guadeloupe", Alpha2: "GP", Alpha3: "GLP", Numeric: 312, }, { Name: "Guam", Alpha2: "GU", Alpha3: "GUM", Numeric: 316, }, { Name: "Guatemala", Alpha2: "GT", Alpha3: "GTM", Numeric: 320, }, { Name: "Guernsey", Alpha2: "GG", Alpha3: "GGY", Numeric: 831, }, { Name: "Guinea", Alpha2: "GN", Alpha3: "GIN", Numeric: 324, }, { Name: "Guinea-Bissau", Alpha2: "GW", Alpha3: "GNB", Numeric: 624, }, { Name: "Guyana", Alpha2: "GY", Alpha3: "GUY", Numeric: 328, }, { Name: "Haiti", Alpha2: "HT", Alpha3: "HTI", Numeric: 332, }, { Name: "<NAME> and McDonald Islands", Alpha2: "HM", Alpha3: "HMD", Numeric: 334, }, { Name: "<NAME> (the)", Alpha2: "VA", Alpha3: "VAT", Numeric: 336, }, { Name: "Honduras", Alpha2: "HN", Alpha3: "HND", Numeric: 340, }, { Name: "<NAME>", Alpha2: "HK", Alpha3: "HKG", Numeric: 344, }, { Name: "Hungary", Alpha2: "HU", Alpha3: "HUN", Numeric: 348, }, { Name: "Iceland", Alpha2: "IS", Alpha3: "ISL", Numeric: 352, }, { Name: "India", Alpha2: "IN", Alpha3: "IND", Numeric: 356, }, { Name: "Indonesia", Alpha2: "ID", Alpha3: "IDN", Numeric: 360, }, { Name: "Iran (Islamic Republic of)", Alpha2: "IR", Alpha3: "IRN", Numeric: 364, }, { Name: "Iraq", Alpha2: "IQ", Alpha3: "IRQ", Numeric: 368, }, { Name: "Ireland", Alpha2: "IE", Alpha3: "IRL", Numeric: 372, }, { Name: "Isle of Man", Alpha2: "IM", Alpha3: "IMN", Numeric: 833, }, { Name: "Israel", Alpha2: "IL", Alpha3: "ISR", Numeric: 376, }, { Name: "Italy", Alpha2: "IT", Alpha3: "ITA", Numeric: 380, }, { Name: "Jamaica", Alpha2: "JM", Alpha3: "JAM", Numeric: 388, }, { Name: "Japan", Alpha2: "JP", Alpha3: "JPN", Numeric: 392, }, { Name: "Jersey", Alpha2: "JE", Alpha3: "JEY", Numeric: 832, }, { Name: "Jordan", Alpha2: "JO", Alpha3: "JOR", Numeric: 400, }, { Name: "Kazakhstan", Alpha2: "KZ", Alpha3: "KAZ", Numeric: 398, }, { Name: "Kenya", Alpha2: "KE", Alpha3: "KEN", Numeric: 404, }, { Name: "Kiribati", Alpha2: "KI", Alpha3: "KIR", Numeric: 296, }, { Name: "Korea (the Democratic People's Republic of)", Alpha2: "KP", Alpha3: "PRK", Numeric: 408, }, { Name: "Korea (the Republic of)", Alpha2: "KR", Alpha3: "KOR", Numeric: 410, }, { Name: "Kuwait", Alpha2: "KW", Alpha3: "KWT", Numeric: 414, }, { Name: "Kyrgyzstan", Alpha2: "KG", Alpha3: "KGZ", Numeric: 417, }, { Name: "Lao People's Democratic Republic (the)", Alpha2: "LA", Alpha3: "LAO", Numeric: 418, }, { Name: "Latvia", Alpha2: "LV", Alpha3: "LVA", Numeric: 428, }, { Name: "Lebanon", Alpha2: "LB", Alpha3: "LBN", Numeric: 422, }, { Name: "Lesotho", Alpha2: "LS", Alpha3: "LSO", Numeric: 426, }, { Name: "Liberia", Alpha2: "LR", Alpha3: "LBR", Numeric: 430, }, { Name: "Libya", Alpha2: "LY", Alpha3: "LBY", Numeric: 434, }, { Name: "Liechtenstein", Alpha2: "LI", Alpha3: "LIE", Numeric: 438, }, { Name: "Lithuania", Alpha2: "LT", Alpha3: "LTU", Numeric: 440, }, { Name: "Luxembourg", Alpha2: "LU", Alpha3: "LUX", Numeric: 442, }, { Name: "Macao", Alpha2: "MO", Alpha3: "MAC", Numeric: 446, }, { Name: "Madagascar", Alpha2: "MG", Alpha3: "MDG", Numeric: 450, }, { Name: "Malawi", Alpha2: "MW", Alpha3: "MWI", Numeric: 454, }, { Name: "Malaysia", Alpha2: "MY", Alpha3: "MYS", Numeric: 458, }, { Name: "Maldives", Alpha2: "MV", Alpha3: "MDV", Numeric: 462, }, { Name: "Mali", Alpha2: "ML", Alpha3: "MLI", Numeric: 466, }, { Name: "Malta", Alpha2: "MT", Alpha3: "MLT", Numeric: 470, }, { Name: "Marshall Islands (the)", Alpha2: "MH", Alpha3: "MHL", Numeric: 584, }, { Name: "Martinique", Alpha2: "MQ", Alpha3: "MTQ", Numeric: 474, }, { Name: "Mauritania", Alpha2: "MR", Alpha3: "MRT", Numeric: 478, }, { Name: "Mauritius", Alpha2: "MU", Alpha3: "MUS", Numeric: 480, }, { Name: "Mayotte", Alpha2: "YT", Alpha3: "MYT", Numeric: 175, }, { Name: "Mexico", Alpha2: "MX", Alpha3: "MEX", Numeric: 484, }, { Name: "Micronesia (Federated States of)", Alpha2: "FM", Alpha3: "FSM", Numeric: 583, }, { Name: "Moldova (the Republic of)", Alpha2: "MD", Alpha3: "MDA", Numeric: 498, }, { Name: "Monaco", Alpha2: "MC", Alpha3: "MCO", Numeric: 492, }, { Name: "Mongolia", Alpha2: "MN", Alpha3: "MNG", Numeric: 496, }, { Name: "Montenegro", Alpha2: "ME", Alpha3: "MNE", Numeric: 499, }, { Name: "Montserrat", Alpha2: "MS", Alpha3: "MSR", Numeric: 500, }, { Name: "Morocco", Alpha2: "MA", Alpha3: "MAR", Numeric: 504, }, { Name: "Mozambique", Alpha2: "MZ", Alpha3: "MOZ", Numeric: 508, }, { Name: "Myanmar", Alpha2: "MM", Alpha3: "MMR", Numeric: 104, }, { Name: "Namibia", Alpha2: "NA", Alpha3: "NAM", Numeric: 516, }, { Name: "Nauru", Alpha2: "NR", Alpha3: "NRU", Numeric: 520, }, { Name: "Nepal", Alpha2: "NP", Alpha3: "NPL", Numeric: 524, }, { Name: "Netherlands (the)", Alpha2: "NL", Alpha3: "NLD", Numeric: 528, }, { Name: "New Caledonia", Alpha2: "NC", Alpha3: "NCL", Numeric: 540, }, { Name: "New Zealand", Alpha2: "NZ", Alpha3: "NZL", Numeric: 554, }, { Name: "Nicaragua", Alpha2: "NI", Alpha3: "NIC", Numeric: 558, }, { Name: "Niger (the)", Alpha2: "NE", Alpha3: "NER", Numeric: 562, }, { Name: "Nigeria", Alpha2: "NG", Alpha3: "NGA", Numeric: 566, }, { Name: "Niue", Alpha2: "NU", Alpha3: "NIU", Numeric: 570, }, { Name: "Norfolk Island", Alpha2: "NF", Alpha3: "NFK", Numeric: 574, }, { Name: "North Macedonia", Alpha2: "MK", Alpha3: "MKD", Numeric: 807, }, { Name: "Northern Mariana Islands (the)", Alpha2: "MP", Alpha3: "MNP", Numeric: 580, }, { Name: "Norway", Alpha2: "NO", Alpha3: "NOR", Numeric: 578, }, { Name: "Oman", Alpha2: "OM", Alpha3: "OMN", Numeric: 512, }, { Name: "Pakistan", Alpha2: "PK", Alpha3: "PAK", Numeric: 586, }, { Name: "Palau", Alpha2: "PW", Alpha3: "PLW", Numeric: 585, }, { Name: "Palestine, State of", Alpha2: "PS", Alpha3: "PSE", Numeric: 275, }, { Name: "Panama", Alpha2: "PA", Alpha3: "PAN", Numeric: 591, }, { Name: "<NAME>", Alpha2: "PG", Alpha3: "PNG", Numeric: 598, }, { Name: "Paraguay", Alpha2: "PY", Alpha3: "PRY", Numeric: 600, }, { Name: "Peru", Alpha2: "PE", Alpha3: "PER", Numeric: 604, }, { Name: "Philippines (the)", Alpha2: "PH", Alpha3: "PHL", Numeric: 608, }, { Name: "Pitcairn", Alpha2: "PN", Alpha3: "PCN", Numeric: 612, }, { Name: "Poland", Alpha2: "PL", Alpha3: "POL", Numeric: 616, }, { Name: "Portugal", Alpha2: "PT", Alpha3: "PRT", Numeric: 620, }, { Name: "<NAME>", Alpha2: "PR", Alpha3: "PRI", Numeric: 630, }, { Name: "Qatar", Alpha2: "QA", Alpha3: "QAT", Numeric: 634, }, { Name: "Romania", Alpha2: "RO", Alpha3: "ROU", Numeric: 642, }, { Name: "Russian Federation (the)", Alpha2: "RU", Alpha3: "RUS", Numeric: 643, }, { Name: "Rwanda", Alpha2: "RW", Alpha3: "RWA", Numeric: 646, }, { Name: "Réunion", Alpha2: "RE", Alpha3: "REU", Numeric: 638, }, { Name: "<NAME>", Alpha2: "BL", Alpha3: "BLM", Numeric: 652, }, { Name: "<NAME>, Ascension and <NAME>", Alpha2: "SH", Alpha3: "SHN", Numeric: 654, }, { Name: "<NAME>", Alpha2: "KN", Alpha3: "KNA", Numeric: 659, }, { Name: "<NAME>", Alpha2: "LC", Alpha3: "LCA", Numeric: 662, }, { Name: "<NAME> (French part)", Alpha2: "MF", Alpha3: "MAF", Numeric: 663, }, { Name: "<NAME>", Alpha2: "PM", Alpha3: "SPM", Numeric: 666, }, { Name: "<NAME> and <NAME>", Alpha2: "VC", Alpha3: "VCT", Numeric: 670, }, { Name: "Samoa", Alpha2: "WS", Alpha3: "WSM", Numeric: 882, }, { Name: "<NAME>", Alpha2: "SM", Alpha3: "SMR", Numeric: 674, }, { Name: "<NAME> Principe", Alpha2: "ST", Alpha3: "STP", Numeric: 678, }, { Name: "<NAME>", Alpha2: "SA", Alpha3: "SAU", Numeric: 682, }, { Name: "Senegal", Alpha2: "SN", Alpha3: "SEN", Numeric: 686, }, { Name: "Serbia", Alpha2: "RS", Alpha3: "SRB", Numeric: 688, }, { Name: "Seychelles", Alpha2: "SC", Alpha3: "SYC", Numeric: 690, }, { Name: "<NAME>", Alpha2: "SL", Alpha3: "SLE", Numeric: 694, }, { Name: "Singapore", Alpha2: "SG", Alpha3: "SGP", Numeric: 702, }, { Name: "<NAME> (Dutch part)", Alpha2: "SX", Alpha3: "SXM", Numeric: 534, }, { Name: "Slovakia", Alpha2: "SK", Alpha3: "SVK", Numeric: 703, }, { Name: "Slovenia", Alpha2: "SI", Alpha3: "SVN", Numeric: 705, }, { Name: "Solomon Islands", Alpha2: "SB", Alpha3: "SLB", Numeric: 90, }, { Name: "Somalia", Alpha2: "SO", Alpha3: "SOM", Numeric: 706, }, { Name: "South Africa", Alpha2: "ZA", Alpha3: "ZAF", Numeric: 710, }, { Name: "South Georgia and the South Sandwich Islands", Alpha2: "GS", Alpha3: "SGS", Numeric: 239, }, { Name: "South Sudan", Alpha2: "SS", Alpha3: "SSD", Numeric: 728, }, { Name: "Spain", Alpha2: "ES", Alpha3: "ESP", Numeric: 724, }, { Name: "Sri Lanka", Alpha2: "LK", Alpha3: "LKA", Numeric: 144, }, { Name: "Sudan (the)", Alpha2: "SD", Alpha3: "SDN", Numeric: 729, }, { Name: "Suriname", Alpha2: "SR", Alpha3: "SUR", Numeric: 740, }, { Name: "Svalbard and <NAME>", Alpha2: "SJ", Alpha3: "SJM", Numeric: 744, }, { Name: "Sweden", Alpha2: "SE", Alpha3: "SWE", Numeric: 752, }, { Name: "Switzerland", Alpha2: "CH", Alpha3: "CHE", Numeric: 756, }, { Name: "Syrian Arab Republic (the)", Alpha2: "SY", Alpha3: "SYR", Numeric: 760, }, { Name: "Taiwan (Province of China)", Alpha2: "TW", Alpha3: "TWN", Numeric: 158, }, { Name: "Tajikistan", Alpha2: "TJ", Alpha3: "TJK", Numeric: 762, }, { Name: "Tanzania, the United Republic of", Alpha2: "TZ", Alpha3: "TZA", Numeric: 834, }, { Name: "Thailand", Alpha2: "TH", Alpha3: "THA", Numeric: 764, }, { Name: "Timor-Leste", Alpha2: "TL", Alpha3: "TLS", Numeric: 626, }, { Name: "Togo", Alpha2: "TG", Alpha3: "TGO", Numeric: 768, }, { Name: "Tokelau", Alpha2: "TK", Alpha3: "TKL", Numeric: 772, }, { Name: "Tonga", Alpha2: "TO", Alpha3: "TON", Numeric: 776, }, { Name: "Trinidad and Tobago", Alpha2: "TT", Alpha3: "TTO", Numeric: 780, }, { Name: "Tunisia", Alpha2: "TN", Alpha3: "TUN", Numeric: 788, }, { Name: "Turkey", Alpha2: "TR", Alpha3: "TUR", Numeric: 792, }, { Name: "Turkmenistan", Alpha2: "TM", Alpha3: "TKM", Numeric: 795, }, { Name: "Turks and Caicos Islands (the)", Alpha2: "TC", Alpha3: "TCA", Numeric: 796, }, { Name: "Tuvalu", Alpha2: "TV", Alpha3: "TUV", Numeric: 798, }, { Name: "Uganda", Alpha2: "UG", Alpha3: "UGA", Numeric: 800, }, { Name: "Ukraine", Alpha2: "UA", Alpha3: "UKR", Numeric: 804, }, { Name: "United Arab Emirates (the)", Alpha2: "AE", Alpha3: "ARE", Numeric: 784, }, { Name: "United Kingdom of Great Britain and Northern Ireland (the)", Alpha2: "GB", Alpha3: "GBR", Numeric: 826, }, { Name: "United States Minor Outlying Islands (the)", Alpha2: "UM", Alpha3: "UMI", Numeric: 581, }, { Name: "United States of America (the)", Alpha2: "US", Alpha3: "USA", Numeric: 840, }, { Name: "Uruguay", Alpha2: "UY", Alpha3: "URY", Numeric: 858, }, { Name: "Uzbekistan", Alpha2: "UZ", Alpha3: "UZB", Numeric: 860, }, { Name: "Vanuatu", Alpha2: "VU", Alpha3: "VUT", Numeric: 548, }, { Name: "Venezuela (Bolivarian Republic of)", Alpha2: "VE", Alpha3: "VEN", Numeric: 862, }, { Name: "<NAME>", Alpha2: "VN", Alpha3: "VNM", Numeric: 704, }, { Name: "Virgin Islands (British)", Alpha2: "VG", Alpha3: "VGB", Numeric: 92, }, { Name: "Virgin Islands (U.S.)", Alpha2: "VI", Alpha3: "VIR", Numeric: 850, }, { Name: "<NAME>", Alpha2: "WF", Alpha3: "WLF", Numeric: 876, }, { Name: "West<NAME>", Alpha2: "EH", Alpha3: "ESH", Numeric: 732, }, { Name: "Yemen", Alpha2: "YE", Alpha3: "YEM", Numeric: 887, }, { Name: "Zambia", Alpha2: "ZM", Alpha3: "ZMB", Numeric: 894, }, { Name: "Zimbabwe", Alpha2: "ZW", Alpha3: "ZWE", Numeric: 716, }, { Name: "Åland Islands", Alpha2: "AX", Alpha3: "ALA", Numeric: 248, }, }
xiso/iso_3166.go
0.514156
0.474327
iso_3166.go
starcoder
package bayes import ( "fmt" "math" s "gostat.googlecode.com/hg/stat" ) // Quantile, Flat prior func BinomFlatPriQtl(k, n int64, p float64) float64 { var α, β float64 if k>n { panic(fmt.Sprintf("The number of observed successes (k) must be <= number of trials (n)")) } α=float64(k+1) β=float64(n-k+1) if α<=0||β<=0 { panic(fmt.Sprintf("The parameters of the prior must be greater than zero")) } return s.BetaInv_CDF_For(α, β, p) } // Quantile, Beta prior func BinomBetaPriQtl(k, n int64, α, β, p float64) float64 { if k>n { panic(fmt.Sprintf("The number of observed successes (k) must be <= number of trials (n)")) } if α<=0||β<=0 { panic(fmt.Sprintf("The parameters of the prior must be greater than zero")) } return s.BetaInv_CDF_For(α+float64(k), β+float64(n-k), p) } // Quantile, Jeffrey's prior func BinomJeffPriQtl(k, n int64, p float64) float64 { var α, β float64 α=0.5 β=0.5 if k>n { panic(fmt.Sprintf("The number of observed successes (k) must be <= number of trials (n)")) } return s.BetaInv_CDF_For(α+float64(k), β+float64(n-k), p) } // Equivalent sample size of the prior func BinomEqvSize(α, β float64) int64 { return int64(math.Floor(α+β+1)) } // Posterior modus func BinomPostModus(α, β float64, n, k int64) float64 { var post_α, post_β float64 post_α=α+float64(k) post_β=β+float64(n-k) return (post_α-1)/(post_α+post_β-2.0) } // Posterior mean func BinomPostMean(α, β float64, n, k int64) float64 { var post_α, post_β float64 post_α=α+float64(k) post_β=β+float64(n-k) return((post_α)/(post_α+post_β)) } // Posterior median func BinomPostMedian(α, β float64, n, k int64) float64 { return 0 // to be implemented } // Posterior variance // Bolstad 2007 (2e): 151, eq. 8.5 func BinomPostVar(α, β float64, n, k int64) float64 { var post_α, post_β float64 post_α=α+float64(k) post_β=β+float64(n-k) return (post_α*post_β)/((post_α+post_β)*(post_α+post_β)*(post_α+post_β+1.0)) } // Posterior mean square of p // Bolstad 2007 (2e): 152-153, eq. 8.7 func BinomPMS(α, β float64, n, k, which_pi int64) float64 { const ( MEAN = 0 MEDIAN = 1 MODUS = 2 ) var post_mean, post_var, pi_hat float64 post_var=BinomPostVar(α, β , n, k ) post_mean = BinomPostMean(α, β , n, k ) switch(which_pi) { case MEAN : pi_hat=BinomPostMean(α, β , n, k) case MEDIAN : pi_hat=BinomPostMedian(α, β , n, k) case MODUS : pi_hat=BinomPostModus(α, β , n, k) } return post_var+ (post_mean-pi_hat)*(post_mean-pi_hat) } // Credible interval for unknown binomial proportion, and beta prior, equal tail area // Bolstad 2007 (2e): 153 // untested ... func BinomBetaPriCrI(α, β, alpha float64, n, k int64) (float64, float64) { /* k observed successes n total number of observations α beta prior a β beta prior b alpha posterior probability that the true proportion lies outside the credible interval */ var low, upp float64 low = s.BetaInv_CDF_For(alpha/2.0,α+float64(k),β+float64(n-k)) upp = s.BetaInv_CDF_For(1.0-alpha/2.0,α+float64(k),β+float64(n-k)) return low, upp } // Credible interval for unknown binomial proportion, and beta prior, equal tail area, normal approximation // Bolstad 2007 (2e): 154-155, eq. 8.8 // untested ... func BinomBetaPriCrIApprox(α, β, alpha float64, n, k int64) (float64, float64) { /* k observed successes n total number of observations a beta prior a b beta prior b alpha posterior probability that the true proportion lies outside the credible interval */ var post_mean, post_var, post_α, post_β, z, low, upp float64 post_α=α+float64(k) post_β=β+float64(n-k) post_mean = post_α/(post_α+post_β) post_var = (post_α*post_β)/((post_α+post_β)*(post_α+post_β)*(post_α+post_β+1.0)) z = s.ZInv_CDF_For(alpha/2) low = post_mean - z * math.Sqrt(post_var) upp = post_mean + z * math.Sqrt(post_var) return low, upp }
stat/bayes/binom_p.go
0.737253
0.507446
binom_p.go
starcoder
package calculator import ( "errors" "fmt" "go/token" "go/types" "math" "regexp" "strconv" "strings" ) // Precision is used to calculate when square root is satisfied. const Precision = 0.0000000001 // Add takes two or more numbers and returns the result of adding them together. func Add(a, b float64, extra ...float64) float64 { total := a + b for _, n := range extra { total += n } return total } // Subtract takes two or more numbers and returns the result of subtracting the // second and subsequent numbers from the first. func Subtract(a, b float64, extra ...float64) float64 { result := a - b for _, n := range extra { result -= n } return result } // Multiply takes two or more numbers and returns the result of multiplying them // together. func Multiply(a, b float64, extra ...float64) float64 { result := a * b for _, n := range extra { result *= n } return result } // Divide takes two or more numbers and returns the result of dividing the first // by the second and subsequent numbers, or an error if division by zero occurs. func Divide(a, b float64, extra []float64) (float64, error) { ErrDivideByZero := errors.New("Cannot divide by zero") if b == 0 { return 0, ErrDivideByZero } result := a / b for _, n := range extra { if n == 0 { return 0, ErrDivideByZero } result /= n } return result, nil } // Sqrt takes a number and returns its square root, or an error if the number is negative. func Sqrt(a float64) (float64, error) { if a < 0 { return 0, fmt.Errorf("bad input %f: square root of a negative number is not defined", a) } guess := 1.0 // Iterate until difference between newGuess and guess is smaller than precision for { // Newton root algorithm newGuess := guess - (((guess * guess) - a) / (2 * guess)) if math.Abs(newGuess-guess) < Precision { break } guess = newGuess } return guess, nil } var validExpression = regexp.MustCompile(`^(\d+)(\.\d+)?(\*|\/|\+|\-)(\d+)(\.\d+)?$`) // CalculateString takes math formula as string and returns the result in // float64 format func CalculateString(input string) (float64, error) { input = strings.ReplaceAll(input, " ", "") if !validExpression.MatchString(input) { return 0, fmt.Errorf("Invalid expression: %q", input) } input = validExpression.FindString(input) fs := token.NewFileSet() tr, err := types.Eval(fs, nil, token.NoPos, input) if err != nil { fmt.Printf("Cannot evaluate expression %s: %v", input, err) } evaluated, err := strconv.ParseFloat(tr.Value.String(), 64) if err != nil { fmt.Printf("Cannot convert %q from string to float64: %v", tr.Value.String(), err) } return evaluated, nil }
calculator.go
0.838548
0.492127
calculator.go
starcoder
package DG2D import "C" import ( "fmt" "math" "github.com/notargets/gocfd/types" "github.com/notargets/gocfd/readfiles" "github.com/notargets/gocfd/DG1D" "github.com/notargets/gocfd/utils" ) type NDG2D struct { Element *LagrangeElement2D K int NODETOL float64 VX, VY, VZ utils.Vector FMask, Fx, Fy utils.Matrix EToV, EToE, EToF utils.Matrix BCType utils.Matrix BCEdges types.BCMAP X, Y, FScale, LIFT utils.Matrix Rx, Ry, Sx, Sy utils.Matrix xs, xr, ys, yr utils.Matrix NX, NY utils.Matrix J, sJ utils.Matrix VmapM, VmapP, VmapB, VmapI, VmapO utils.Index MapB, MapI, MapO utils.Index FMaskI utils.Index } func NewNDG2D(N int, meshFile string) (ndg *NDG2D) { ndg = &NDG2D{ Element: NewLagrangeElement2D(N, Hesthaven), NODETOL: 1.e-6, } if N < 1 { panic(fmt.Errorf("Polynomial order must be >= 1, have %d", N)) } ndg.K, ndg.VX, ndg.VY, ndg.EToV, ndg.BCEdges = readfiles.ReadGambit2d(meshFile, false) ndg.Startup2D() return } func (ndg *NDG2D) Startup2D() { var ( R, S = ndg.Element.R, ndg.Element.S ) ndg.X, ndg.Y = CalculateElementLocalGeometry(ndg.EToV, ndg.VX, ndg.VY, ndg.Element.R, ndg.Element.S) fmask1 := S.Copy().AddScalar(1).Find(utils.Less, ndg.NODETOL, true) fmask2 := S.Copy().Add(R).Find(utils.Less, ndg.NODETOL, true) fmask3 := R.Copy().AddScalar(1).Find(utils.Less, ndg.NODETOL, true) if fmask1.Len() != 0 { ndg.FMask = utils.NewMatrix(ndg.Element.Nfp, 3) ndg.FMask.SetCol(0, fmask1.DataP) ndg.FMask.SetCol(1, fmask2.DataP) ndg.FMask.SetCol(2, fmask3.DataP) ndg.FMaskI = utils.NewIndex(len(ndg.FMask.DataP), ndg.FMask.DataP) ndg.Fx = utils.NewMatrix(3*ndg.Element.Nfp, ndg.K) for fp, val := range ndg.FMask.DataP { ind := int(val) ndg.Fx.M.SetRow(fp, ndg.X.M.RawRowView(ind)) } ndg.Fy = utils.NewMatrix(3*ndg.Element.Nfp, ndg.K) for fp, val := range ndg.FMask.DataP { ind := int(val) ndg.Fy.M.SetRow(fp, ndg.Y.M.RawRowView(ind)) } ndg.Lift2D() } ndg.GeometricFactors2D() ndg.Normals2D() ndg.FScale = ndg.sJ.ElDiv(ndg.J.Subset(ndg.GetFaces())) // Build connectivity matrices ndg.EToE, ndg.EToF = Connect2D(ndg.K, ndg.Element.NFaces, ndg.VX.Len(), ndg.EToV) // Mark fields read only ndg.LIFT.SetReadOnly("LIFT") ndg.X.SetReadOnly("X") ndg.Y.SetReadOnly("Y") ndg.Fx.SetReadOnly("Fx") ndg.Fy.SetReadOnly("Fy") ndg.FMask.SetReadOnly("FMask") ndg.NX.SetReadOnly("NX") ndg.NY.SetReadOnly("NY") ndg.FScale.SetReadOnly("FScale") ndg.EToE.SetReadOnly("EToE") ndg.EToF.SetReadOnly("EToF") return } func Connect2D(K, NFaces, Nv int, EToV utils.Matrix) (EToE, EToF utils.Matrix) { // Nv = total number of vertices var ( TotalFaces = NFaces * K ) SpFToVDOK := utils.NewDOK(TotalFaces, Nv) faces := utils.NewMatrix(3, 2, []float64{ 0, 1, 1, 2, 0, 2, }) var sk int for k := 0; k < K; k++ { for face := 0; face < NFaces; face++ { edge := faces.Range(face, ":") //fmt.Println("Nv, TotalFaces, k, face, edge, range = ", Nv, TotalFaces, k, face, edge, el.EToV.Range(k, edge)) SpFToVDOK.Equate(1, sk, EToV.Range(k, edge)) sk++ } } // Build global face to global face sparse array SpFToV := SpFToVDOK.ToCSR() SpFToF := utils.NewCSR(TotalFaces, TotalFaces) SpFToF.M.Mul(SpFToV, SpFToV.T()) for i := 0; i < TotalFaces; i++ { SpFToF.M.Set(i, i, SpFToF.At(i, i)-2) } // Find complete face to face connections F12 := utils.MatFind(SpFToF, utils.Equal, 2) element1 := F12.RI.Copy().Apply(func(val int) int { return val / NFaces }) face1 := F12.RI.Copy().Apply(func(val int) int { return int(math.Mod(float64(val), float64(NFaces))) }) element2 := F12.CI.Copy().Apply(func(val int) int { return val / NFaces }) face2 := F12.CI.Copy().Apply(func(val int) int { return int(math.Mod(float64(val), float64(NFaces))) }) // Rearrange into Nelements x Nfaces sized arrays EToE = utils.NewRangeOffset(1, K).Outer(utils.NewOnes(NFaces)) EToF = utils.NewOnes(K).Outer(utils.NewRangeOffset(1, NFaces)) var I2D utils.Index2D var err error nr, nc := EToE.Dims() if I2D, err = utils.NewIndex2D(nr, nc, element1, face1); err != nil { panic(err) } EToE.Assign(I2D.ToIndex(), element2) EToF.Assign(I2D.ToIndex(), face2) return } func (ndg *NDG2D) GetFaces() (aI utils.Index, NFacePts, K int) { var ( err error allFaces utils.Index2D ) NFacePts = ndg.Element.Nfp * ndg.Element.NFaces K = ndg.K allK := utils.NewRangeOffset(1, ndg.K) if allFaces, err = utils.NewIndex2D(ndg.Element.Np, ndg.K, ndg.FMaskI, allK, true); err != nil { panic(err) } aI = allFaces.ToIndex() return } func (ndg *NDG2D) Normals2D() { var ( f1, f2, f3 utils.Index2D err error ) allK := utils.NewRangeOffset(1, ndg.K) aI, NFacePts, _ := ndg.GetFaces() // interpolate geometric factors to face nodes fxr := ndg.xr.Subset(aI, NFacePts, ndg.K) fxs := ndg.xs.Subset(aI, NFacePts, ndg.K) fyr := ndg.yr.Subset(aI, NFacePts, ndg.K) fys := ndg.ys.Subset(aI, NFacePts, ndg.K) // build normals faces1 := utils.NewRangeOffset(1, ndg.Element.Nfp) faces2 := utils.NewRangeOffset(1+ndg.Element.Nfp, 2*ndg.Element.Nfp) faces3 := utils.NewRangeOffset(1+2*ndg.Element.Nfp, 3*ndg.Element.Nfp) if f1, err = utils.NewIndex2D(NFacePts, ndg.K, faces1, allK, true); err != nil { panic(err) } if f2, err = utils.NewIndex2D(NFacePts, ndg.K, faces2, allK, true); err != nil { panic(err) } if f3, err = utils.NewIndex2D(NFacePts, ndg.K, faces3, allK, true); err != nil { panic(err) } ndg.NX, ndg.NY = utils.NewMatrix(NFacePts, ndg.K), utils.NewMatrix(NFacePts, ndg.K) // Face 1 ndg.NX.Assign(f1.ToIndex(), fyr.Subset(f1.ToIndex(), f1.Len, 1)) ndg.NY.Assign(f1.ToIndex(), fxr.Subset(f1.ToIndex(), f1.Len, 1).Scale(-1)) // Face 2 ndg.NX.Assign(f2.ToIndex(), fys.Subset(f2.ToIndex(), f2.Len, 1).Subtract(fyr.Subset(f2.ToIndex(), f2.Len, 1))) ndg.NY.Assign(f2.ToIndex(), fxs.Subset(f2.ToIndex(), f2.Len, 1).Scale(-1).Add(fxr.Subset(f2.ToIndex(), f2.Len, 1))) // Face 3 ndg.NX.Assign(f3.ToIndex(), fys.Subset(f3.ToIndex(), f3.Len, 1).Scale(-1)) ndg.NY.Assign(f3.ToIndex(), fxs.Subset(f3.ToIndex(), f3.Len, 1)) ndg.sJ = ndg.NX.Copy().POW(2).Add(ndg.NY.Copy().POW(2)).Apply(func(val float64) (res float64) { res = math.Sqrt(val) return }) ndg.NX.ElDiv(ndg.sJ) ndg.NY.ElDiv(ndg.sJ) } func (ndg *NDG2D) GeometricFactors2D() { /* // function [rx,sx,ry,sy,J] = GeometricFactors2D(x,y,Dr,Ds) // Purpose : Compute the metric elements for the local // mappings of the elements DMat xr=Dr*x xs=Ds*x yr=Dr*y ys=Ds*y; J = xr.dm(ys) - xs.dm(yr); rx = ys.dd(J); sx = -yr.dd(J); ry = -xs.dd(J); sy = xr.dd(J); */ // Calculate geometric factors ndg.xr, ndg.xs = ndg.Element.Dr.Mul(ndg.X), ndg.Element.Ds.Mul(ndg.X) ndg.yr, ndg.ys = ndg.Element.Dr.Mul(ndg.Y), ndg.Element.Ds.Mul(ndg.Y) ndg.xr.SetReadOnly("xr") ndg.xs.SetReadOnly("xs") ndg.yr.SetReadOnly("yr") ndg.ys.SetReadOnly("ys") ndg.J = ndg.xr.Copy().ElMul(ndg.ys).Subtract(ndg.xs.Copy().ElMul(ndg.yr)) ndg.Rx = ndg.ys.Copy().ElDiv(ndg.J) ndg.Sx = ndg.yr.Copy().ElDiv(ndg.J).Scale(-1) ndg.Ry = ndg.xs.Copy().ElDiv(ndg.J).Scale(-1) ndg.Sy = ndg.xr.Copy().ElDiv(ndg.J) } func (ndg *NDG2D) Lift2D() { var ( err error I2 utils.Index2D massEdge utils.Matrix V1D utils.Matrix Emat utils.Matrix R, S = ndg.Element.R, ndg.Element.S ) Emat = utils.NewMatrix(ndg.Element.Np, ndg.Element.NFaces*ndg.Element.Nfp) faceMap := func(basis utils.Vector, faceNum int, Ind utils.Index) { faceBasis := basis.SubsetIndex(ndg.FMask.Col(faceNum).ToIndex()) V1D = DG1D.Vandermonde1D(ndg.Element.N, faceBasis) if massEdge, err = V1D.Mul(V1D.Transpose()).Inverse(); err != nil { panic(err) } if I2, err = utils.NewIndex2D(ndg.Element.Np, ndg.Element.NFaces*ndg.Element.Nfp, ndg.FMask.Col(faceNum).ToIndex(), Ind, true); err != nil { panic(err) } Emat.Assign(I2.ToIndex(), massEdge) } // face 1 faceMap(R, 0, utils.NewRangeOffset(1, ndg.Element.Nfp)) // face 2 faceMap(R, 1, utils.NewRangeOffset(ndg.Element.Nfp+1, 2*ndg.Element.Nfp)) // face 3 faceMap(S, 2, utils.NewRangeOffset(2*ndg.Element.Nfp+1, 3*ndg.Element.Nfp)) // inv(mass matrix)*\I_n (L_i,L_j)_{edge_n} ndg.LIFT = ndg.Element.V.Mul(ndg.Element.V.Transpose().Mul(Emat)) return } func (ndg *NDG2D) BuildMaps2D() { return } func (ndg *NDG2D) NewCube2D(COrder int) { // function [cubR,cubS,cubW, Ncub] = Cubature2D(COrder) // Purpose: provide multidimensional quadrature (i.e. cubature) // rules to integrate up to COrder polynomials if COrder > 28 { COrder = 28 } if COrder <= 28 { cub2d := getCub(COrder) nr := len(cub2d) / 3 cubMat := utils.NewMatrix(nr, 3, cub2d) ndg.Element.Cub = &Cubature{ r: cubMat.Col(0), s: cubMat.Col(1), w: cubMat.Col(2), } } else { err := fmt.Errorf("Cubature2D(%d): COrder > 28 not yet tested\n", COrder) panic(err) /* DVec cuba,cubwa, cubb,cubwb DMat cubA, cubB, cubR, cubS, cubW, tA,tB int cubNA=(int)ceil((COrder+1.0)/2.0) int cubNB=(int)ceil((COrder+1.0)/2.0) JacobiGQ(1.0, 0.0, cubNB-1, cubb,cubwb) cubA = outer( ones(cubNB), cuba ) cubB = outer( cubb, ones(cubNA) ) tA = 1.0+cubA tB = 1.0-cubB cubR = 0.5 * tA.dm(tB) - 1.0 cubS = cubB cubW = 0.5 * outer(cubwb, cubwa) cub.r = cubR cub.s = cubS cub.w = cubW cub.Ncub = cub.r.size() */ } return }
DG2D/ndg_startup.go
0.519765
0.433262
ndg_startup.go
starcoder
package codecs import ( "bytes" "time" ) // EncodedSize returns the number of bytes required to encode the value v. func EncodedSize(v interface{}) (int, error) { if v == nil { return 1, nil } switch t := v.(type) { case bool: return sizeBool, nil case uint8: return sizeUint8, nil case int8: return sizeInt8, nil case uint16: return sizeUint16, nil case int16: return sizeInt16, nil case int: if intsize == 4 { return sizeInt32, nil } return sizeInt64, nil case uint: if intsize == 4 { return sizeUint32, nil } return sizeUint64, nil case uint32: return sizeUint32, nil case int32: return sizeInt32, nil case uint64: return sizeUint64, nil case int64: return sizeInt64, nil case float32: return sizeFloat32, nil case float64: return sizeFloat64, nil case time.Time: return sizeTime, nil case string: return len(t) + 2, nil default: return 0, ErrUnknownType } } // SizeNext returns the number of bytes encompassing the next encoded value in // the byte slice. func SizeNext(b []byte) (int, error) { switch b[0] { case typeByteBool, typeByteBoolInverse: return sizeBool, nil case typeByteNil, typeByteNilInverse: return sizeNil, nil case typeByteUint8, typeByteUint8Inverse: return sizeUint8, nil case typeByteUint16, typeByteUint16Inverse: return sizeUint16, nil case typeByteUint32, typeByteUint32Inverse: return sizeUint32, nil case typeByteUint64, typeByteUint64Inverse: return sizeUint64, nil case typeByteInt8, typeByteInt8Inverse: return sizeInt8, nil case typeByteInt16, typeByteInt16Inverse: return sizeInt16, nil case typeByteInt32, typeByteInt32Inverse: return sizeInt32, nil case typeByteInt64, typeByteInt64Inverse: return sizeInt64, nil case typeByteFloat32, typeByteFloat32Inverse: return sizeFloat32, nil case typeByteFloat64, typeByteFloat64Inverse: return sizeFloat64, nil case typeByteTime, typeByteTimeInverse: return sizeTime, nil case typeByteString: return bytes.IndexByte(b, terminatorByte) + 1, nil case typeByteStringInverse: return bytes.IndexByte(b, terminatorByteInverse) + 1, nil default: return 0, ErrUnknownType } }
codecs/size.go
0.665737
0.441974
size.go
starcoder
package depot import "time" // Values contains the persistent column values for an entity either after reading // the values from the database to re-create the entity value or to persist the // entity's values in the database (either for insertion or update). type Values map[string]interface{} // IsNull returns true if the value store for key is the SQL value `NULL`. func (v Values) IsNull(key string) bool { return v[key] == nil } // GetTime returns the value associated with key as a time.Time. func (v Values) GetTime(key string) (time.Time, bool) { val, ok := v[key] if !ok { return time.Time{}, false } switch x := val.(type) { case time.Time: return x, ok default: return time.Time{}, false } } // GetBytes returns the value associated with key as a byte slice. func (v Values) GetBytes(key string) ([]byte, bool) { val, ok := v[key] if !ok { return nil, false } if val == nil { return nil, true } switch x := val.(type) { case []byte: return x, ok default: return nil, false } } // GetBool returns the value associated with key as a boolean. func (v Values) GetBool(key string) (bool, bool) { val, ok := v[key] if !ok { return false, false } switch x := val.(type) { case bool: return x, ok case int64: return x != 0, ok default: return false, false } } // GetFloat32 returns the value associated with key as a float32. func (v Values) GetFloat32(key string) (float32, bool) { val, ok := v[key] if !ok { return 0.0, false } switch x := val.(type) { case float32: return x, ok case float64: return float32(x), ok default: return 0.0, false } } // GetFloat64 returns the value associated with key as a float64. func (v Values) GetFloat64(key string) (float64, bool) { val, ok := v[key] if !ok { return 0.0, false } switch x := val.(type) { case float64: return x, ok default: return 0.0, false } } // GetInt returns the value associated with key as an int. func (v Values) GetInt(key string) (int, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return int(x), ok default: return 0, false } } // GetInt8 returns the value associated with key as an int8. func (v Values) GetInt8(key string) (int8, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return int8(x), ok default: return 0, false } } // GetInt16 returns the value associated with key as an int16. func (v Values) GetInt16(key string) (int16, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return int16(x), ok default: return 0, false } } // GetInt32 returns the value associated with key as an int32. func (v Values) GetInt32(key string) (int32, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return int32(x), ok default: return 0, false } } // GetInt64 returns the value associated with key as an int64. func (v Values) GetInt64(key string) (int64, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return x, ok default: return 0, false } } // GetUInt returns the value associated with key as an uint. func (v Values) GetUInt(key string) (uint, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return uint(x), ok default: return 0, false } } // GetUInt8 returns the value associated with key as an uint8. func (v Values) GetUInt8(key string) (uint8, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return uint8(x), ok default: return 0, false } } // GetUInt16 returns the value associated with key as a uint16. func (v Values) GetUInt16(key string) (uint16, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return uint16(x), ok default: return 0, false } } // GetUInt32 returns the value associated with key as an uint32. func (v Values) GetUInt32(key string) (uint32, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return uint32(x), ok default: return 0, false } } // GetUInt64 returns the value associated with key as an uint64. func (v Values) GetUInt64(key string) (uint64, bool) { val, ok := v[key] if !ok { return 0, false } switch x := val.(type) { case int64: return uint64(x), ok default: return 0, false } } // GetString returns the names value converted to a string. func (v Values) GetString(key string) (string, bool) { val, ok := v[key] if !ok { return "", false } switch x := val.(type) { case string: return x, ok case []byte: return string(x), ok default: return "", false } }
values.go
0.800965
0.566438
values.go
starcoder
package str import ( "errors" "math/rand" "sort" "strings" "time" ) var ( rnd = rand.New(rand.NewSource(time.Now().UnixNano())) ) type Vector []string func (vector Vector) FirstNonEmpty() string { for _, str := range vector { if str != "" { return str } } return "" } func (vector Vector) Len() int { return len(vector) } func (vector Vector) New() Vector { return make(Vector, 0, vector.Len()) } func (vector Vector) Copy() Vector { return append(vector.New(), vector...) } func (vector Vector) Filter(pred func(str string) bool) Vector { var filtered = vector.New() for _, str := range vector { if pred(str) { filtered = append(filtered, str) } } return filtered } func (vector Vector) Count() map[string]uint { var count = make(map[string]uint, vector.Len()) for _, str := range vector { count[str]++ } return count } func (vector Vector) Slice() []string { return []string(vector.Copy()) } func (vector Vector) Join(delim string) string { return strings.Join(vector, delim) } func (vector Vector) WriteToChan(ch chan<- string) { for _, str := range vector { ch <- str } } func (vector Vector) Append(strs ...string) Vector { return append(vector.Copy(), strs...) } func (vector Vector) Map(op func(str string) string) Vector { var mapped = vector.New() for _, str := range vector { mapped = append(mapped, op(str)) } return mapped } func (vector Vector) Populate(op func(str string) []string) Vector { var populated = vector.New() for _, str := range vector { populated = append(populated, op(str)...) } return populated } func (vector Vector) Fold(start string, op func(acc, str string) string) string { var acc = start for _, str := range vector { acc = op(acc, str) } return acc } func (vector Vector) Delete(i int) Vector { vector = vector.Copy() return append(vector[:i], vector[i+1:]...) } func (vector Vector) FirstFiltered(pred func(str string) bool) (string, bool) { for _, str := range vector { if pred(str) { return str, true } } return "", false } func (vector Vector) SortByKey(key func(str string) int) Vector { vector = vector.Copy() sort.Slice(vector, func(i, j int) bool { return key(vector[i]) < key(vector[j]) }) return vector } func (vector Vector) SortByLess(less func(a, b string) bool) Vector { vector = vector.Copy() sort.Slice(vector, func(i, j int) bool { return less(vector[i], vector[j]) }) return vector } func (vector Vector) Unique() Vector { var set = map[string]struct{}{} var unique = vector.New() for _, str := range vector { if _, ok := set[str]; !ok { unique = append(unique, str) set[str] = struct{}{} } } return unique } func (vector Vector) Shuffle() Vector { vector = vector.Copy() rnd.Shuffle(vector.Len(), func(i, j int) { vector[i], vector[j] = vector[j], vector[i] }) return vector } func (vector Vector) Sample(n uint) Vector { var sample = make(Vector, 0, n) var vLen = vector.Len() for i := uint(0); i < n; i++ { var ind = rnd.Intn(vLen) sample = append(sample, vector[ind]) } return sample } func (vector Vector) Top(n uint) Vector { var count = vector.Count() var sorted = vector.Unique().SortByKey(func(str string) int { return -int(count[str]) }) if uint(sorted.Len()) < n { return sorted } return sorted[:n].Copy() } func (vector Vector) Classify(key func(str string) string) map[string][]string { vector = vector.Unique() var classes = make(map[string][]string, len(vector)) for _, str := range vector { var k = key(str) classes[k] = append(classes[k], str) } return classes } func (vector Vector) Inverse() Vector { var inversed = vector.Copy() var vLen = vector.Len() for i := 0; i < vLen/2; i++ { inversed[i], inversed[vLen-i-1] = inversed[vLen-i-1], inversed[i] } return inversed } func (vector Vector) Eq(v Vector) bool { if vector.Len() != v.Len() { return false } for i, str := range vector { if v[i] != str { return false } } return true } func (vector Vector) Contains(str string) bool { for _, s := range vector { if s == str { return true } } return false } func (vector Vector) ToErrs() []error { var errs = make([]error, 0, vector.Len()) for _, str := range vector { errs = append(errs, errors.New(str)) } return errs } func (vector Vector) Head(n uint) Vector { if uint(vector.Len()) < n { return vector.Copy() } return vector[:n].Copy() } func (vector Vector) Tail(n uint) Vector { if uint(vector.Len()) <= n { return vector.Copy() } return vector[n:].Copy() } func (vector Vector) Get(i int) string { return vector[i] } func (vector Vector) GetDefault(i int, defaultStr string) string { if i >= 0 && i < vector.Len() { return vector.Get(i) } return defaultStr } func FromChan(ch <-chan string, timeout time.Duration) Vector { var vec = make(Vector, 0, 16) cycle: for { select { case s, ok := <-ch: if !ok { break cycle } vec = append(vec, s) case <-time.Tick(timeout): break cycle } } return vec } func (vector Vector) NonEmpty() Vector { return vector.Filter(Longer(0)) }
str/vector.go
0.612773
0.484685
vector.go
starcoder
package dealer import ( "context" "errors" "sync" "github.com/thrasher-corp/gocryptotrader/exchanges/fill" "github.com/thrasher-corp/gocryptotrader/exchanges/trade" exchange "github.com/thrasher-corp/gocryptotrader/exchanges" "github.com/thrasher-corp/gocryptotrader/exchanges/account" "github.com/thrasher-corp/gocryptotrader/exchanges/order" "github.com/thrasher-corp/gocryptotrader/exchanges/orderbook" "github.com/thrasher-corp/gocryptotrader/exchanges/stream" "github.com/thrasher-corp/gocryptotrader/exchanges/ticker" "go.uber.org/multierr" ) // This code will consist of a single RootStrategy data structure. This data structure would be the only one where Strategy Implementations are held. // A new RootStrategy object is created. This data structure will be passed down to the last implementation of Strategy. // After the Strategy Implementations are imported, the order are respective are important. // The order of import Strategy implementations is important because classes that depend on other classes don't rely on the root strategy in order to work // so in order to have a non-circular dependency, the classes should be called in a specific order. // Adding a new strategy is going to be returning two things. The RootStrategy itself, and a specific Strategy that is the type of the Strategy that was requested. // The ability to add a strategy will create a Map, Map[string] full of RootStrategies. When the end user adds a new strategy, they can give it a unique identifier // and when they do, we will add a new value to the map. Second, we have a function after the line where a new RootStrategy object is defined; a function called Get // which takes a string. To get a strategy from a Root Strategy, we simply use this function. We check if the given string matches the String identifier in the Map // returning the corresponding value in the map. Let's assume similarity with an exchange. Anytime a strategy needs to do something, it will do so through the Dealer, // which is passing necessary information. Just looking at this graph without talking about the internals, it is easy to see how this system can grow. // Any additional advanced features or algorithms can be added through additional Function calls, without changing the underlying code of the strategies. // This dynamic initialization system of functionality has several advantages. // It allows of the base Dealer to be generic and essentially allow for new additional functionality to be added to it at any time by just adding a new package to the folder structure. // By using this system it is possible to create a fully fledged Exchange or a versatile universal JSON constructor. Neither of the two situations would be possible using a static approach // as a static approach leads to a lot of increased code duplication and factoring. This allows for ideas and less explainable of the code. // Each strategy is instantiated as the variable `m`. Then each of the strategies is passed as a function and called. The function has a Void returned Void. // Each of the strategy will be called and setup inside their `OnInit()` functions and run their OnInit functions, to set themselves up. Next, each of the OnInit functions will pass a selection of code developers can customize, into their OnFunding() implementations. // We will then iterate over the variable `rootStrategy` and call each one to execute their function, allowing us to customize each strategy individually. var ( ErrStrategyNotFound = errors.New("strategy not found") ErrNotStrategy = errors.New("given object is not a strategy") ) // RootStrategy is a struct that contains a map of strategies. The map is a sync.Map, which is a thread safe map. The map is initialized with a sync.Map{} and then we can add strategies to it. // The map is a map of string to Strategy. The string is the name of the strategy and the Strategy is the implementation of the strategy. type RootStrategy struct { strategies sync.Map } // NewRootStrategy returns the RootStrategy object. The RootStrategy object has several functions (each). // creating a RootStrategy variable which is an object. Then we are iterating through each of the additional strategies and adding them to the NewRootStrategy, // so they are available as the final implementation is created after they have been created func NewRootStrategy() RootStrategy { return RootStrategy{ strategies: sync.Map{}, } } // Add function takes a string that identifies a implementation of the Strategy, and the implementation of the implementation of the Strategy implementation itself. // It stores an implementation of a strategy implementation under a string named after the strategy implementation. Which resolves to the correct implementation of the Strategy. func (m *RootStrategy) Add(name string, s Strategy) { m.strategies.Store(name, s) } // Delete the Strategy specified by name. You get an object, get the interface's value, and then determine the interface's value. func (m *RootStrategy) Delete(name string) (Strategy, error) { x, ok := m.strategies.LoadAndDelete(name) if !ok { return nil, ErrStrategyNotFound } return x.(Strategy), nil } // Get returns the strategy with the given name func (m *RootStrategy) Get(name string) (Strategy, error) { x, ok := m.strategies.Load(name) if !ok { return nil, ErrStrategyNotFound } return x.(Strategy), nil } // each function is a function that iterates over all of the current strategies and calls a specific function once for each strategy. // The closure of the function is the implementation of the Strategy. The function returns an error. func (m *RootStrategy) each(f func(Strategy) error) error { var err error m.strategies.Range(func(key, value interface{}) bool { s, ok := value.(Strategy) if !ok { err = multierr.Append(err, ErrNotStrategy) } else { err = multierr.Append(err, f(s)) } return true }) return err } // Init function loops through each of the imported Strategy implementations and calls their init functions to initialize them. // Ordering of implementations is important and if an implementation depends on something another requires you should order the strategy implementations. func (m *RootStrategy) Init(ctx context.Context, d *Dealer, e exchange.IBotExchange) error { return m.each(func(strategy Strategy) error { return strategy.Init(ctx, d, e) }) } // OnFunding function for the Root strategy. The first line of the function is to call the same function on each_ it is the interface method for the Strategy. // A new function is called, which is more of an interface for the Strategy called OnFunding. Which allows the user to choose how they want to pass this event to the strategy. func (m *RootStrategy) OnFunding(d *Dealer, e exchange.IBotExchange, x stream.FundingData) error { return m.each(func(strategy Strategy) error { return strategy.OnFunding(d, e, x) }) } // The OnPrice implementation of the Strategy is different from above. // It does not let the user choose how they want to use this information and passes all the information to the specific implementation of that data. func (m *RootStrategy) OnPrice(d *Dealer, e exchange.IBotExchange, x ticker.Price) error { return m.each(func(strategy Strategy) error { return strategy.OnPrice(d, e, x) }) } // OnKline listens to the Kline stream data events and execute optional action func (m *RootStrategy) OnKline(d *Dealer, e exchange.IBotExchange, x stream.KlineData) error { return m.each(func(strategy Strategy) error { return strategy.OnKline(d, e, x) }) } // OnOrderBook is called when initial orderbook is created or if the bids or asks change // Must pass in Dealer that created this strategy. Also pass in the Exchange used by the strategy // Call this function once per Strategy func (m *RootStrategy) OnOrderBook(d *Dealer, e exchange.IBotExchange, x orderbook.Base) error { return m.each(func(strategy Strategy) error { return strategy.OnOrderBook(d, e, x) }) } // OnOrder is called when changes occur to a specific order func (m *RootStrategy) OnOrder(d *Dealer, e exchange.IBotExchange, x order.Detail) error { return m.each(func(strategy Strategy) error { return strategy.OnOrder(d, e, x) }) } // OnModify is invoked when an order is modified. // The arguments passed are the original user message func (m *RootStrategy) OnModify(d *Dealer, e exchange.IBotExchange, x order.Modify) error { return m.each(func(strategy Strategy) error { return strategy.OnModify(d, e, x) }) } // OnBalanceChange iterates over each strategy, calling OnBalanceChange, logging an error if any fail // Returns nil on success, or Function specific error on failure func (m *RootStrategy) OnBalanceChange(d *Dealer, e exchange.IBotExchange, x account.Change) error { return m.each(func(strategy Strategy) error { return strategy.OnBalanceChange(d, e, x) }) } func (m *RootStrategy) OnTrade(d *Dealer, e exchange.IBotExchange, x []trade.Data) error { return m.each(func(s Strategy) error { return s.OnTrade(d, e, x) }) } func (m *RootStrategy) OnFill(d *Dealer, e exchange.IBotExchange, x []fill.Data) error { return m.each(func(s Strategy) error { return s.OnFill(d, e, x) }) } // OnUnrecognized is called on unrecognized data func (m *RootStrategy) OnUnrecognized(d *Dealer, e exchange.IBotExchange, x interface{}) error { return m.each(func(strategy Strategy) error { return strategy.OnUnrecognized(d, e, x) }) } // Deinit deinitializes strategies in a specific Dealer struct // For each strategy in a Dealer, calls Strategy.Deinit() func (m *RootStrategy) Deinit(d *Dealer, e exchange.IBotExchange) error { return m.each(func(strategy Strategy) error { return strategy.Deinit(d, e) }) }
internal/dealer/strategy_root.go
0.76908
0.472866
strategy_root.go
starcoder
package mem import ( "bufio" "os" "strconv" "strings" "github.com/alexdreptu/sysinfo/convert" "golang.org/x/sys/unix" ) type fetchFunc func(info *unix.Sysinfo_t) error type Mem struct { Procs uint16 TotalMem uint64 TotalHighMem uint64 FreeMem uint64 FreeHighMem uint64 AvailMem uint64 UsedMem uint64 TotalUsedMem uint64 BufferMem uint64 CachedMem uint64 SharedMem uint64 TotalSwap uint64 FreeSwap uint64 UsedSwap uint64 TotalUsed uint64 F fetchFunc } const memInfoPath = "/proc/meminfo" func (m *Mem) TotalMemInKibibytes() float64 { return (convert.Size(m.TotalMem) * convert.Byte).ToKibibytes() } func (m *Mem) TotalMemInMebibytes() float64 { return (convert.Size(m.TotalMem) * convert.Byte).ToMebibytes() } func (m *Mem) TotalMemInGibibytes() float64 { return (convert.Size(m.TotalMem) * convert.Byte).ToGibibytes() } func (m *Mem) TotalHighMemInKibibytes() float64 { return (convert.Size(m.TotalHighMem) * convert.Byte).ToKibibytes() } func (m *Mem) TotalHighMemInMebibytes() float64 { return (convert.Size(m.TotalHighMem) * convert.Byte).ToMebibytes() } func (m *Mem) TotalHighMemInGibibytes() float64 { return (convert.Size(m.TotalHighMem) * convert.Byte).ToGibibytes() } func (m *Mem) FreeMemInKibibytes() float64 { return (convert.Size(m.FreeMem) * convert.Byte).ToKibibytes() } func (m *Mem) FreeMemInMebibytes() float64 { return (convert.Size(m.FreeMem) * convert.Byte).ToMebibytes() } func (m *Mem) FreeMemInGibibytes() float64 { return (convert.Size(m.FreeMem) * convert.Byte).ToGibibytes() } func (m *Mem) FreeHighMemInKibibytes() float64 { return (convert.Size(m.FreeHighMem) * convert.Byte).ToKibibytes() } func (m *Mem) FreeHighMemInMebibytes() float64 { return (convert.Size(m.FreeHighMem) * convert.Byte).ToMebibytes() } func (m *Mem) FreeHighMemInGibibytes() float64 { return (convert.Size(m.FreeHighMem) * convert.Byte).ToGibibytes() } func (m *Mem) AvailMemInKibibytes() float64 { return (convert.Size(m.AvailMem) * convert.Byte).ToKibibytes() } func (m *Mem) AvailMemInMebibytes() float64 { return (convert.Size(m.AvailMem) * convert.Byte).ToMebibytes() } func (m *Mem) AvailMemInGibibytes() float64 { return (convert.Size(m.AvailMem) * convert.Byte).ToGibibytes() } func (m *Mem) CachedMemInKibibytes() float64 { return (convert.Size(m.CachedMem) * convert.Byte).ToKibibytes() } func (m *Mem) CachedMemInMebibytes() float64 { return (convert.Size(m.CachedMem) * convert.Byte).ToMebibytes() } func (m *Mem) CachedMemInGibibytes() float64 { return (convert.Size(m.CachedMem) * convert.Byte).ToGibibytes() } func (m *Mem) UsedMemInKibibytes() float64 { return (convert.Size(m.UsedMem) * convert.Byte).ToKibibytes() } func (m *Mem) UsedMemInMebibytes() float64 { return (convert.Size(m.UsedMem) * convert.Byte).ToMebibytes() } func (m *Mem) UsedMemInGibibytes() float64 { return (convert.Size(m.UsedMem) * convert.Byte).ToGibibytes() } func (m *Mem) TotalUsedMemInKibibytes() float64 { return (convert.Size(m.TotalUsedMem) * convert.Byte).ToKibibytes() } func (m *Mem) TotalUsedMemInMebibytes() float64 { return (convert.Size(m.TotalUsedMem) * convert.Byte).ToMebibytes() } func (m *Mem) TotalUsedMemInGibibytes() float64 { return (convert.Size(m.TotalUsedMem) * convert.Byte).ToGibibytes() } func (m *Mem) TotalUsedInKibibytes() float64 { return (convert.Size(m.TotalUsed) * convert.Byte).ToKibibytes() } func (m *Mem) TotalUsedInMebibytes() float64 { return (convert.Size(m.TotalUsed) * convert.Byte).ToMebibytes() } func (m *Mem) TotalUsedInGibibytes() float64 { return (convert.Size(m.TotalUsed) * convert.Byte).ToGibibytes() } func (m *Mem) BufferMemInKibibytes() float64 { return (convert.Size(m.BufferMem) * convert.Byte).ToKibibytes() } func (m *Mem) BufferMemInMebibytes() float64 { return (convert.Size(m.BufferMem) * convert.Byte).ToMebibytes() } func (m *Mem) BufferMemInGibibytes() float64 { return (convert.Size(m.BufferMem) * convert.Byte).ToGibibytes() } func (m *Mem) SharedMemInKibibytes() float64 { return (convert.Size(m.SharedMem) * convert.Byte).ToKibibytes() } func (m *Mem) SharedMemInMebibytes() float64 { return (convert.Size(m.SharedMem) * convert.Byte).ToMebibytes() } func (m *Mem) SharedMemInGibibytes() float64 { return (convert.Size(m.SharedMem) * convert.Byte).ToGibibytes() } func (m *Mem) TotalSwapInKibibytes() float64 { return (convert.Size(m.TotalSwap) * convert.Byte).ToKibibytes() } func (m *Mem) TotalSwapInMebibytes() float64 { return (convert.Size(m.TotalSwap) * convert.Byte).ToMebibytes() } func (m *Mem) TotalSwapInGibibytes() float64 { return (convert.Size(m.TotalSwap) * convert.Byte).ToGibibytes() } func (m *Mem) FreeSwapInKibibytes() float64 { return (convert.Size(m.FreeSwap) * convert.Byte).ToKibibytes() } func (m *Mem) FreeSwapInMebibytes() float64 { return (convert.Size(m.FreeSwap) * convert.Byte).ToMebibytes() } func (m *Mem) FreeSwapInGibibytes() float64 { return (convert.Size(m.FreeSwap) * convert.Byte).ToGibibytes() } func (m *Mem) UsedSwapInKibibytes() float64 { return (convert.Size(m.UsedSwap) * convert.Byte).ToKibibytes() } func (m *Mem) UsedSwapInMebibytes() float64 { return (convert.Size(m.UsedSwap) * convert.Byte).ToMebibytes() } func (m *Mem) UsedSwapInGibibytes() float64 { return (convert.Size(m.UsedSwap) * convert.Byte).ToGibibytes() } // Fetch updates the Mem struct woth new values func (m *Mem) Fetch() error { if m.F == nil { m.F = unix.Sysinfo } si := unix.Sysinfo_t{} if err := m.F(&si); err != nil { return err } if m.AvailMem == 0 && m.CachedMem == 0 { if err := m.readMemInfo(); err != nil { return err } } m.Procs = si.Procs m.TotalMem = si.Totalram m.TotalHighMem = si.Totalhigh m.FreeMem = si.Freeram m.FreeHighMem = si.Freehigh m.BufferMem = si.Bufferram m.SharedMem = si.Sharedram m.TotalSwap = si.Totalswap m.FreeSwap = si.Freeswap m.UsedMem = m.TotalMem - m.FreeMem - m.BufferMem - m.CachedMem m.TotalUsedMem = m.TotalMem - m.FreeMem m.TotalUsed = m.TotalMem - m.FreeMem + m.TotalSwap - m.FreeSwap m.UsedSwap = m.TotalSwap - m.FreeSwap return nil } func (m *Mem) readMemInfo() error { file, err := os.Open(memInfoPath) if err != nil { return err } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if line == "" { continue } fields := strings.Split(line, ":") key := strings.TrimSpace(fields[0]) value := strings.Fields(fields[1])[0] switch key { case "MemAvailable": n, err := strconv.Atoi(value) if err != nil { return err } m.AvailMem = uint64((convert.Size(n) * convert.Kibibyte).ToBytes()) case "Cached": n, err := strconv.Atoi(value) if err != nil { return err } m.CachedMem = uint64((convert.Size(n) * convert.Kibibyte).ToBytes()) } } return scanner.Err() } func New() (*Mem, error) { mem := &Mem{} if err := mem.Fetch(); err != nil { return &Mem{}, err } return mem, nil }
mem/mem.go
0.615666
0.403097
mem.go
starcoder
package nbs import ( "context" "encoding/binary" "errors" "io" "sort" "sync/atomic" "github.com/golang/snappy" "golang.org/x/sync/errgroup" "github.com/dolthub/dolt/go/store/chunks" "github.com/dolthub/dolt/go/store/hash" ) // Do not read more than 128MB at a time. const maxReadSize = 128 * 1024 * 1024 // CompressedChunk represents a chunk of data in a table file which is still compressed via snappy. type CompressedChunk struct { // H is the hash of the chunk H hash.Hash // FullCompressedChunk is the entirety of the compressed chunk data including the crc FullCompressedChunk []byte // CompressedData is just the snappy encoded byte buffer that stores the chunk data CompressedData []byte } // NewCompressedChunk creates a CompressedChunk func NewCompressedChunk(h hash.Hash, buff []byte) (CompressedChunk, error) { dataLen := uint64(len(buff)) - checksumSize chksum := binary.BigEndian.Uint32(buff[dataLen:]) compressedData := buff[:dataLen] if chksum != crc(compressedData) { return CompressedChunk{}, errors.New("checksum error") } return CompressedChunk{H: h, FullCompressedChunk: buff, CompressedData: compressedData}, nil } // ToChunk snappy decodes the compressed data and returns a chunks.Chunk func (cmp CompressedChunk) ToChunk() (chunks.Chunk, error) { data, err := snappy.Decode(nil, cmp.CompressedData) if err != nil { return chunks.Chunk{}, err } return chunks.NewChunkWithHash(cmp.H, data), nil } func ChunkToCompressedChunk(chunk chunks.Chunk) CompressedChunk { compressed := snappy.Encode(nil, chunk.Data()) length := len(compressed) compressed = append(compressed, []byte{0, 0, 0, 0}...) binary.BigEndian.PutUint32(compressed[length:], crc(compressed[:length])) return CompressedChunk{H: chunk.Hash(), FullCompressedChunk: compressed, CompressedData: compressed[:length]} } // Hash returns the hash of the data func (cmp CompressedChunk) Hash() hash.Hash { return cmp.H } // IsEmpty returns true if the chunk contains no data. func (cmp CompressedChunk) IsEmpty() bool { return len(cmp.CompressedData) == 0 || (len(cmp.CompressedData) == 1 && cmp.CompressedData[0] == 0) } var EmptyCompressedChunk CompressedChunk func init() { EmptyCompressedChunk = ChunkToCompressedChunk(chunks.EmptyChunk) } // ErrInvalidTableFile is an error returned when a table file is corrupt or invalid. var ErrInvalidTableFile = errors.New("invalid or corrupt table file") type indexEntry interface { Offset() uint64 Length() uint32 } type indexResult struct { o uint64 l uint32 } func (ir indexResult) Offset() uint64 { return ir.o } func (ir indexResult) Length() uint32 { return ir.l } type tableReaderAt interface { ReadAtWithStats(ctx context.Context, p []byte, off int64, stats *Stats) (n int, err error) } // tableReader implements get & has queries against a single nbs table. goroutine safe. // |blockSize| refers to the block-size of the underlying storage. We assume that, each // time we read data, we actually have to read in blocks of this size. So, we're willing // to tolerate up to |blockSize| overhead each time we read a chunk, if it helps us group // more chunks together into a single read request to backing storage. type tableReader struct { tableIndex prefixes []uint64 chunkCount uint32 totalUncompressedData uint64 r tableReaderAt blockSize uint64 } // newTableReader parses a valid nbs table byte stream and returns a reader. buff must end with an NBS index // and footer, though it may contain an unspecified number of bytes before that data. r should allow // retrieving any desired range of bytes from the table. func newTableReader(index tableIndex, r tableReaderAt, blockSize uint64) (tableReader, error) { p, err := index.Prefixes() if err != nil { return tableReader{}, err } return tableReader{ index, p, index.ChunkCount(), index.TotalUncompressedData(), r, blockSize, }, nil } // Scan across (logically) two ordered slices of address prefixes. func (tr tableReader) hasMany(addrs []hasRecord) (bool, error) { // TODO: Use findInIndex if (tr.chunkCount - len(addrs)*Log2(tr.chunkCount)) > (tr.chunkCount - len(addrs)) filterIdx := uint32(0) filterLen := uint32(tr.chunkCount) var remaining bool for i, addr := range addrs { if addr.has { continue } for filterIdx < filterLen && addr.prefix > tr.prefixes[filterIdx] { filterIdx++ } if filterIdx >= filterLen { return true, nil } if addr.prefix != tr.prefixes[filterIdx] { remaining = true continue } // prefixes are equal, so locate and compare against the corresponding suffix for j := filterIdx; j < filterLen && addr.prefix == tr.prefixes[j]; j++ { m, err := tr.EntrySuffixMatches(j, addr.a) if err != nil { return false, err } if m { addrs[i].has = true break } } if !addrs[i].has { remaining = true } } return remaining, nil } func (tr tableReader) count() (uint32, error) { return tr.chunkCount, nil } func (tr tableReader) uncompressedLen() (uint64, error) { return tr.totalUncompressedData, nil } func (tr tableReader) index() (tableIndex, error) { return tr.tableIndex, nil } // returns true iff |h| can be found in this table. func (tr tableReader) has(h addr) (bool, error) { _, ok, err := tr.Lookup(&h) return ok, err } // returns the storage associated with |h|, iff present. Returns nil if absent. On success, // the returned byte slice directly references the underlying storage. func (tr tableReader) get(ctx context.Context, h addr, stats *Stats) ([]byte, error) { e, found, err := tr.Lookup(&h) if err != nil { return nil, err } if !found { return nil, nil } offset := e.Offset() length := uint64(e.Length()) buff := make([]byte, length) // TODO: Avoid this allocation for every get n, err := tr.r.ReadAtWithStats(ctx, buff, int64(offset), stats) if err != nil { return nil, err } if n != int(length) { return nil, errors.New("failed to read all data") } cmp, err := NewCompressedChunk(hash.Hash(h), buff) if err != nil { return nil, err } if len(cmp.CompressedData) == 0 { return nil, errors.New("failed to get data") } chnk, err := cmp.ToChunk() if err != nil { return nil, err } return chnk.Data(), nil } type offsetRec struct { a *addr offset uint64 length uint32 } type offsetRecSlice []offsetRec func (hs offsetRecSlice) Len() int { return len(hs) } func (hs offsetRecSlice) Less(i, j int) bool { return hs[i].offset < hs[j].offset } func (hs offsetRecSlice) Swap(i, j int) { hs[i], hs[j] = hs[j], hs[i] } var _ chunkReadPlanner = tableReader{} var _ chunkReader = tableReader{} func (tr tableReader) readCompressedAtOffsets( ctx context.Context, rb readBatch, found func(context.Context, CompressedChunk), stats *Stats, ) error { return tr.readAtOffsetsWithCB(ctx, rb, stats, func(ctx context.Context, cmp CompressedChunk) error { found(ctx, cmp) return nil }) } func (tr tableReader) readAtOffsets( ctx context.Context, rb readBatch, found func(context.Context, *chunks.Chunk), stats *Stats, ) error { return tr.readAtOffsetsWithCB(ctx, rb, stats, func(ctx context.Context, cmp CompressedChunk) error { chk, err := cmp.ToChunk() if err != nil { return err } found(ctx, &chk) return nil }) } func (tr tableReader) readAtOffsetsWithCB( ctx context.Context, rb readBatch, stats *Stats, cb func(ctx context.Context, cmp CompressedChunk) error, ) error { readLength := rb.End() - rb.Start() buff := make([]byte, readLength) n, err := tr.r.ReadAtWithStats(ctx, buff, int64(rb.Start()), stats) if err != nil { return err } if uint64(n) != readLength { return errors.New("failed to read all data") } for i := range rb { cmp, err := rb.ExtractChunkFromRead(buff, i) if err != nil { return err } err = cb(ctx, cmp) if err != nil { return err } } return nil } // getMany retrieves multiple stored blocks and optimizes by attempting to read in larger physical // blocks which contain multiple stored blocks. |reqs| must be sorted by address prefix. func (tr tableReader) getMany( ctx context.Context, eg *errgroup.Group, reqs []getRecord, found func(context.Context, *chunks.Chunk), stats *Stats) (bool, error) { // Pass #1: Iterate over |reqs| and |tr.prefixes| (both sorted by address) and build the set // of table locations which must be read in order to satisfy the getMany operation. offsetRecords, remaining, err := tr.findOffsets(reqs) if err != nil { return false, err } err = tr.getManyAtOffsets(ctx, eg, offsetRecords, found, stats) return remaining, err } func (tr tableReader) getManyCompressed(ctx context.Context, eg *errgroup.Group, reqs []getRecord, found func(context.Context, CompressedChunk), stats *Stats) (bool, error) { // Pass #1: Iterate over |reqs| and |tr.prefixes| (both sorted by address) and build the set // of table locations which must be read in order to satisfy the getMany operation. offsetRecords, remaining, err := tr.findOffsets(reqs) if err != nil { return false, err } err = tr.getManyCompressedAtOffsets(ctx, eg, offsetRecords, found, stats) return remaining, err } func (tr tableReader) getManyCompressedAtOffsets(ctx context.Context, eg *errgroup.Group, offsetRecords offsetRecSlice, found func(context.Context, CompressedChunk), stats *Stats) error { return tr.getManyAtOffsetsWithReadFunc(ctx, eg, offsetRecords, stats, func( ctx context.Context, rb readBatch, stats *Stats) error { return tr.readCompressedAtOffsets(ctx, rb, found, stats) }) } func (tr tableReader) getManyAtOffsets( ctx context.Context, eg *errgroup.Group, offsetRecords offsetRecSlice, found func(context.Context, *chunks.Chunk), stats *Stats, ) error { return tr.getManyAtOffsetsWithReadFunc(ctx, eg, offsetRecords, stats, func( ctx context.Context, rb readBatch, stats *Stats) error { return tr.readAtOffsets(ctx, rb, found, stats) }) } type readBatch offsetRecSlice func (r readBatch) Start() uint64 { return r[0].offset } func (r readBatch) End() uint64 { last := r[len(r)-1] return last.offset + uint64(last.length) } func (s readBatch) ExtractChunkFromRead(buff []byte, idx int) (CompressedChunk, error) { rec := s[idx] chunkStart := rec.offset - s.Start() return NewCompressedChunk(hash.Hash(*rec.a), buff[chunkStart:chunkStart+uint64(rec.length)]) } func toReadBatches(offsets offsetRecSlice, blockSize uint64) []readBatch { res := make([]readBatch, 0) var batch readBatch for i := 0; i < len(offsets); { rec := offsets[i] if batch == nil { batch = readBatch{rec} i++ continue } if _, canRead := canReadAhead(rec, batch.Start(), batch.End(), blockSize); canRead { batch = append(batch, rec) i++ continue } res = append(res, batch) batch = nil } if batch != nil { res = append(res, batch) } return res } func (tr tableReader) getManyAtOffsetsWithReadFunc( ctx context.Context, eg *errgroup.Group, offsetRecords offsetRecSlice, stats *Stats, readAtOffsets func( ctx context.Context, rb readBatch, stats *Stats) error, ) error { batches := toReadBatches(offsetRecords, tr.blockSize) var idx int32 readBatches := func() error { for { if ctx.Err() != nil { return ctx.Err() } i := atomic.AddInt32(&idx, 1) - 1 if int(i) >= len(batches) { return nil } rb := batches[i] err := readAtOffsets(ctx, rb, stats) if err != nil { return err } } } ioParallelism := 4 for i := 0; i < ioParallelism; i++ { eg.Go(readBatches) } return nil } // findOffsets iterates over |reqs| and |tr.prefixes| (both sorted by // address) to build the set of table locations which must be read in order to // find each chunk specified by |reqs|. If this table contains all requested // chunks remaining will be set to false upon return. If some are not here, // then remaining will be true. The result offsetRecSlice is sorted in offset // order. func (tr tableReader) findOffsets(reqs []getRecord) (ors offsetRecSlice, remaining bool, err error) { filterIdx := uint32(0) filterLen := uint32(len(tr.prefixes)) ors = make(offsetRecSlice, 0, len(reqs)) // Iterate over |reqs| and |tr.prefixes| (both sorted by address) and build the set // of table locations which must be read in order to satisfy |reqs|. for i, req := range reqs { if req.found { continue } // advance within the prefixes until we reach one which is >= req.prefix for filterIdx < filterLen && tr.prefixes[filterIdx] < req.prefix { filterIdx++ } if filterIdx >= filterLen { remaining = true // last prefix visited. break } if req.prefix != tr.prefixes[filterIdx] { remaining = true continue } // record all offsets within the table which contain the data required. for j := filterIdx; j < filterLen && req.prefix == tr.prefixes[j]; j++ { m, err := tr.EntrySuffixMatches(j, req.a) if err != nil { return nil, false, err } if m { reqs[i].found = true entry, err := tr.IndexEntry(j, nil) if err != nil { return nil, false, err } ors = append(ors, offsetRec{req.a, entry.Offset(), entry.Length()}) break } } } sort.Sort(ors) return ors, remaining, nil } func canReadAhead(fRec offsetRec, curStart, curEnd, blockSize uint64) (newEnd uint64, canRead bool) { if fRec.offset < curEnd { // |offsetRecords| will contain an offsetRecord for *every* chunkRecord whose address // prefix matches the prefix of a requested address. If the set of requests contains // addresses which share a common prefix, then it's possible for multiple offsetRecords // to reference the same table offset position. In that case, we'll see sequential // offsetRecords with the same fRec.offset. return curEnd, true } if curEnd-curStart >= maxReadSize { return curEnd, false } if fRec.offset-curEnd > blockSize { return curEnd, false } return fRec.offset + uint64(fRec.length), true } func (tr tableReader) calcReads(reqs []getRecord, blockSize uint64) (reads int, remaining bool, err error) { var offsetRecords offsetRecSlice // Pass #1: Build the set of table locations which must be read in order to find all the elements of |reqs| which are present in this table. offsetRecords, remaining, err = tr.findOffsets(reqs) if err != nil { return 0, false, err } // Now |offsetRecords| contains all locations within the table which must // be searched (note that there may be duplicates of a particular // location). Scan forward, grouping sequences of reads into large physical // reads. var readStart, readEnd uint64 readStarted := false for i := 0; i < len(offsetRecords); { rec := offsetRecords[i] length := rec.length if !readStarted { readStarted = true reads++ readStart = rec.offset readEnd = readStart + uint64(length) i++ continue } if newReadEnd, canRead := canReadAhead(rec, readStart, readEnd, tr.blockSize); canRead { readEnd = newReadEnd i++ continue } readStarted = false } return } func (tr tableReader) extract(ctx context.Context, chunks chan<- extractRecord) error { sendChunk := func(or offsetRec) error { buff := make([]byte, or.length) n, err := tr.r.ReadAtWithStats(ctx, buff, int64(or.offset), &Stats{}) if err != nil { return err } if uint32(n) != or.length { return errors.New("did not read all data") } cmp, err := NewCompressedChunk(hash.Hash(*or.a), buff) if err != nil { return err } chnk, err := cmp.ToChunk() if err != nil { return err } chunks <- extractRecord{a: *or.a, data: chnk.Data()} return nil } var ors offsetRecSlice for i := uint32(0); i < tr.chunkCount; i++ { a := new(addr) e, err := tr.IndexEntry(i, a) if err != nil { return err } ors = append(ors, offsetRec{a, e.Offset(), e.Length()}) } sort.Sort(ors) for _, or := range ors { err := sendChunk(or) if err != nil { return err } } return nil } func (tr tableReader) reader(ctx context.Context) (io.Reader, error) { i, _ := tr.index() return io.LimitReader(&readerAdapter{tr.r, 0, ctx}, int64(i.TableFileSize())), nil } func (tr tableReader) size() (uint64, error) { i, _ := tr.index() return i.TableFileSize(), nil } func (tr tableReader) Close() error { return tr.tableIndex.Close() } func (tr tableReader) Clone() (tableReader, error) { ti, err := tr.tableIndex.Clone() if err != nil { return tableReader{}, err } return tableReader{ti, tr.prefixes, tr.chunkCount, tr.totalUncompressedData, tr.r, tr.blockSize}, nil } type readerAdapter struct { rat tableReaderAt off int64 ctx context.Context } func (ra *readerAdapter) Read(p []byte) (n int, err error) { n, err = ra.rat.ReadAtWithStats(ra.ctx, p, ra.off, &Stats{}) ra.off += int64(n) return }
go/store/nbs/table_reader.go
0.671147
0.465448
table_reader.go
starcoder
package bandersnatch import ( "math/big" "github.com/consensys/gnark/frontend" ) // Point point on a twisted Edwards curve in a Snark cs type Point struct { X, Y frontend.Variable } // MustBeOnCurve checks if a point is on the reduced twisted Edwards curve // a*x^2 + y^2 = 1 + d*x^2*y^2. func (p *Point) MustBeOnCurve(api frontend.API, curve EdCurve) { one := big.NewInt(1) xx := api.Mul(p.X, p.X) yy := api.Mul(p.Y, p.Y) axx := api.Mul(xx, &curve.A) lhs := api.Add(axx, yy) dxx := api.Mul(xx, &curve.D) dxxyy := api.Mul(dxx, yy) rhs := api.Add(dxxyy, one) api.AssertIsEqual(lhs, rhs) } // AddFixedPoint Adds two points, among which is one fixed point (the base), on a twisted edwards curve (eg jubjub) // p1, base, ecurve are respectively: the point to add, a known base point, and the parameters of the twisted edwards curve func (p *Point) AddFixedPoint(api frontend.API, p1 *Point /*basex*/, x /*basey*/, y interface{}, curve EdCurve) *Point { // https://eprint.iacr.org/2008/013.pdf n11 := api.Mul(p1.X, y) n12 := api.Mul(p1.Y, x) n1 := api.Add(n11, n12) n21 := api.Mul(p1.Y, y) n22 := api.Mul(p1.X, x) an22 := api.Mul(n22, &curve.A) n2 := api.Sub(n21, an22) d11 := api.Mul(curve.D, n11, n12) d1 := api.Add(1, d11) d2 := api.Sub(1, d11) p.X = api.DivUnchecked(n1, d1) p.Y = api.DivUnchecked(n2, d2) return p } // AddGeneric Adds two points on a twisted edwards curve (eg jubjub) // p1, p2, c are respectively: the point to add, a known base point, and the parameters of the twisted edwards curve func (p *Point) AddGeneric(api frontend.API, p1, p2 *Point, curve EdCurve) *Point { // https://eprint.iacr.org/2008/013.pdf n11 := api.Mul(p1.X, p2.Y) n12 := api.Mul(p1.Y, p2.X) n1 := api.Add(n11, n12) n21 := api.Mul(p1.Y, p2.Y) n22 := api.Mul(p1.X, p2.X) an22 := api.Mul(n22, &curve.A) n2 := api.Sub(n21, an22) d11 := api.Mul(curve.D, n11, n12) d1 := api.Add(1, d11) d2 := api.Sub(1, d11) p.X = api.DivUnchecked(n1, d1) p.Y = api.DivUnchecked(n2, d2) return p } // Double doubles a points in SNARK coordinates func (p *Point) Double(api frontend.API, p1 *Point, curve EdCurve) *Point { u := api.Mul(p1.X, p1.Y) v := api.Mul(p1.X, p1.X) w := api.Mul(p1.Y, p1.Y) z := api.Mul(v, w) n1 := api.Mul(2, u) av := api.Mul(v, &curve.A) n2 := api.Sub(w, av) d := api.Mul(z, curve.D) d1 := api.Add(1, d) d2 := api.Sub(1, d) p.X = api.DivUnchecked(n1, d1) p.Y = api.DivUnchecked(n2, d2) return p } // ScalarMulNonFixedBase computes the scalar multiplication of a point on a twisted Edwards curve // p1: base point (as snark point) // curve: parameters of the Edwards curve // scal: scalar as a SNARK constraint // Standard left to right double and add func (p *Point) ScalarMulNonFixedBase(api frontend.API, p1 *Point, scalar frontend.Variable, curve EdCurve) *Point { // first unpack the scalar b := api.ToBinary(scalar) res := Point{ 0, 1, } for i := len(b) - 1; i >= 0; i-- { res.Double(api, &res, curve) tmp := Point{} tmp.AddGeneric(api, &res, p1, curve) res.X = api.Select(b[i], tmp.X, res.X) res.Y = api.Select(b[i], tmp.Y, res.Y) } p.X = res.X p.Y = res.Y return p } // ScalarMulFixedBase computes the scalar multiplication of a point on a twisted Edwards curve // x, y: coordinates of the base point // curve: parameters of the Edwards curve // scal: scalar as a SNARK constraint // Standard left to right double and add func (p *Point) ScalarMulFixedBase(api frontend.API, x, y interface{}, scalar frontend.Variable, curve EdCurve) *Point { // first unpack the scalar b := api.ToBinary(scalar) res := Point{ 0, 1, } for i := len(b) - 1; i >= 0; i-- { res.Double(api, &res, curve) tmp := Point{} tmp.AddFixedPoint(api, &res, x, y, curve) res.X = api.Select(b[i], tmp.X, res.X) res.Y = api.Select(b[i], tmp.Y, res.Y) } p.X = res.X p.Y = res.Y return p } // Neg computes the negative of a point in SNARK coordinates func (p *Point) Neg(api frontend.API, p1 *Point) *Point { p.X = api.Neg(p1.X) p.Y = p1.Y return p }
std/algebra/twistededwards/bandersnatch/point.go
0.834542
0.429429
point.go
starcoder
package cmd import ( "fmt" "image" "image/color" "image/png" "math" "os" "github.com/disintegration/imaging" "github.com/spf13/cobra" ) var img *image.RGBA var col color.Color // HLine draws a horizontal line func HLine(x1, y, x2 int) { for ; x1 <= x2; x1++ { img.Set(x1, y, col) } } // VLine draws a veritcal line func VLine(x, y1, y2 int) { for ; y1 <= y2; y1++ { img.Set(x, y1, col) } } // Rect draws a rectangle utilizing HLine() and VLine() func RectDraw(x1, y1, x2, y2 int) { HLine(x1, y1, x2) HLine(x1, y2, x2) VLine(x1, y1, y2) VLine(x2, y1, y2) } type Rect struct { // left side AX float64 AY float64 BX float64 BY float64 // right side DX float64 DY float64 CX float64 CY float64 } type Point struct { X float64 Y float64 } var bottomLeftx float64 var bottomLefty float64 var height float64 var width float64 var x float64 var y float64 var imageOut string var boolOnly bool // checkpointCmd represents the checkrect command var checkpointCmd = &cobra.Command{ Use: "checkpoint", Short: "Check if a point falls within a 2D boundry of the given rectangle", Long: "", Run: func(cmd *cobra.Command, args []string) { if boolOnly { fmt.Println(checkPoint()) } else { if checkPoint() { fmt.Println("The point is inside the rectangle boundries") } else { fmt.Println("The point is outside the rectangle boundries") } } }, } func checkPoint() bool { rect := Rect{ AX: bottomLeftx, AY: bottomLefty, BX: bottomLeftx, BY: bottomLefty + height, CX: bottomLeftx + width, CY: bottomLefty + height, DX: bottomLeftx + width, DY: bottomLefty, } point := Point{ X: x, Y: y, } // Calculate the area of the original rectangle rectArea := 0.5 * math.Abs(((rect.AY-rect.CY)*(rect.DX-rect.BX))+((rect.BY-rect.DY)*(rect.AX-rect.CX))) // Calculate a rectangle area using our new point ABP := 0.5 * math.Abs((rect.AX*(rect.BY-point.Y) + rect.BX*(point.Y-rect.AY) + point.X*(rect.AY-rect.BY))) BCP := 0.5 * math.Abs((rect.BX*(rect.CY-point.Y) + rect.CX*(point.Y-rect.BY) + point.X*(rect.BY-rect.CY))) CDP := 0.5 * math.Abs((rect.CX*(rect.DY-point.Y) + rect.DX*(point.Y-rect.CY) + point.X*(rect.CY-rect.DY))) DAP := 0.5 * math.Abs((rect.DX*(rect.AY-point.Y) + rect.AX*(point.Y-rect.DY) + point.X*(rect.DY-rect.AY))) if imageOut != "" { makeImage(&rect) } return rectArea == (ABP + BCP + CDP + DAP) } func makeImage(rect *Rect) { // Draw the rectangle img = image.NewRGBA(image.Rect(0, 0, round(rect.AX)+round(width)+round(x)+100, round(rect.AY)+round(height)+round(y)+100)) col = color.RGBA{0, 255, 0, 255} // Green RectDraw(round(rect.AX)+100, round(rect.AY)+100, round(rect.CX)+100, round(rect.CY)+100) // Draw the point col = color.RGBA{255, 0, 0, 255} // Red HLine(round(x)+100, round(y)+100, round(x)+105) HLine(round(x)+95, round(y)+100, round(x)+100) VLine(round(x)+100, round(y)+100, round(y)+105) VLine(round(x)+100, round(y)+95, round(y)+100) // flip the image for a correct x/y axis imgR := imaging.FlipV(img) f, err := os.Create(imageOut) if err != nil { panic(err) } defer f.Close() png.Encode(f, imgR) } func round(num float64) int { return int(num + math.Copysign(0.5, num)) } func init() { checkpointCmd.Flags().Float64VarP(&bottomLeftx, "rect-bottom-left-x", "", 1, "Bottom Left X point of the rectangle") checkpointCmd.Flags().Float64VarP(&bottomLefty, "rect-bottom-left-y", "", 1, "Bottom Left Y point of the rectangle") checkpointCmd.Flags().Float64VarP(&height, "rect-height", "H", 1, "Height of the tectangle") checkpointCmd.Flags().Float64VarP(&width, "rect-width", "W", 1, "Width of the tectangle") checkpointCmd.Flags().Float64VarP(&x, "point-x", "X", 1, "Point X") checkpointCmd.Flags().Float64VarP(&y, "point-y", "Y", 1, "Point Y") checkpointCmd.Flags().StringVarP(&imageOut, "img-out", "i", "", "Output Image Path, if no image is specified the program will not make an image") checkpointCmd.Flags().BoolVarP(&boolOnly, "bool-out", "b", false, "Output bool instead of a message") rootCmd.AddCommand(checkpointCmd) }
cmd/checkpoint.go
0.712032
0.469399
checkpoint.go
starcoder
package telemetry // LocalQuery contains the serviceID for a local query const LocalQuery string = "weaviate.local.query" // LocalQueryMeta contains the serviceID for a local meta query const LocalQueryMeta string = "weaviate.local.query.meta" // NetworkQuery contains the serviceID for a network query const NetworkQuery string = "Weaviate.network.query" // NetworkQueryMeta contains the serviceID for a network meta query const NetworkQueryMeta string = "weaviate.network.query.meta" // LocalAdd contains the serviceID for a local add query const LocalAdd string = "weaviate.local.add" // LocalAddMeta contains the serviceID for a local add meta query const LocalAddMeta string = "weaviate.local.add.meta" // LocalManipulate contains the serviceID for a local manipulate query const LocalManipulate string = "weaviate.local.manipulate" // LocalManipulateMeta contains the serviceID for a local manipulate meta query const LocalManipulateMeta string = "weaviate.local.manipulate.meta" // LocalTools contains the serviceID for a local tools query const LocalTools string = "weaviate.local.tools" // NetworkToolsMap contains the serviceID for a network tools query const NetworkToolsMap string = "weaviate.network.tools.map" // TypeGQL contains the serviceID for a local query const TypeGQL string = "GQL" // TypeREST contains the serviceID for a local query const TypeREST string = "REST" // ReportPostFail contains the value used when a report is unable to be sent to the specified URL const ReportPostFail string = "[POST failed]" // ReportCBORFail contains the value used when a report fails to be converted to CBOR const ReportCBORFail string = "[CBOR conversion failed]" // DefaultLogging is the setting for the logging conf variable used when none is defined const DefaultLogging bool = true // DefaultInterval is the setting for the logging conf variable used when none is defined const DefaultInterval int = 300 // DefaultURL is the setting for the logging conf variable used when none is defined const DefaultURL string = "http://logs.semi.technology" // DefaultDebug is the setting for the logging conf variable used when none is defined const DefaultDebug bool = true
usecases/telemetry/constants.go
0.549157
0.422922
constants.go
starcoder
package digest import ( "fmt" ) // Type - Multihash algorithm ID. type Type uint64 // Source of constants: https://godoc.org/github.com/multiformats/go-multihash#pkg-constants const ( // Sha1 - SHA1 hashing algorithm. Sha1 Type = 0x11 // Sha2_256 - SHA2 256bit hashing algorithm. Sha2_256 Type = 0x12 // Sha2_512 - SHA2 512bit hashing algorithm. Sha2_512 Type = 0x13 // Sha3_224 - SHA3 224bit hashing algorithm. Sha3_224 Type = 0x17 // Sha3_256 - SHA3 256bit hashing algorithm. Sha3_256 Type = 0x16 // Sha3_384 - SHA3 384bit hashing algorithm. Sha3_384 Type = 0x15 // Sha3_512 - SHA3 512bit hashing algorithm. Sha3_512 Type = 0x14 // Keccak224 - Keccak 224bit hashing algorithm. Keccak224 Type = 0x1A // Keccak256 - Keccak 256bit hashing algorithm. Keccak256 Type = 0x1B // Keccak384 - Keccak 384bit hashing algorithm. Keccak384 Type = 0x1C // Keccak512 - Keccak 512bit hashing algorithm. Keccak512 Type = 0x1D // Shake128 - Shake 128bit hashing algorithm. Shake128 Type = 0x18 // Shake256 - Shake 256bit hashing algorithm. Shake256 Type = 0x19 // Blake2bMin - Blake2B MIN hashing algorithm. Blake2bMin Type = 0xb201 // Blake2bMax - Blake2B MAX hashing algorithm. Blake2bMax Type = 0xb240 // Blake2b_256 - Blake2B MAX hashing algorithm. Blake2b256 Type = 0xb220 // Blake2sMin - Blake2S MIN hashing algorithm. Blake2sMin Type = 0xb241 // Blake2sMax - Blake2S MAX hashing algorithm. Blake2sMax Type = 0xb260 // DoubleSha2_256 - Double SHA2 256bit hashing algorithm. DoubleSha2_256 Type = 0x56 // Murmur3 - MURMUR3 hashing algorithm. Murmur3 Type = 0x22 // UnknownType - Unknown hashing algorithm. UnknownType Type = 0 ) // Names - Multihash identifier names. var Names = map[Type]string{ Sha1: "sha1", Sha2_256: "sha2-256", Sha2_512: "sha2-512", Sha3_224: "sha3-224", Sha3_256: "sha3-256", Sha3_384: "sha3-384", Sha3_512: "sha3-512", DoubleSha2_256: "dbl-sha2-256", Murmur3: "murmur3", Keccak224: "keccak-224", Keccak256: "keccak-256", Keccak384: "keccak-384", Keccak512: "keccak-512", Shake128: "shake-128", Shake256: "shake-256", } // Types - Multihash identifier names. var Types = map[string]Type{ "sha1": Sha1, "sha2-256": Sha2_256, "sha2-512": Sha2_512, "sha3-224": Sha3_224, "sha3-256": Sha3_256, "sha3-384": Sha3_384, "sha3-512": Sha3_512, "dbl-sha2-256": DoubleSha2_256, "murmur3": Murmur3, "keccak-224": Keccak224, "keccak-256": Keccak256, "keccak-384": Keccak384, "keccak-512": Keccak512, "shake-128": Shake128, "shake-256": Shake256, } func init() { // Add blake2b (64 codes) for c := Blake2bMin; c <= Blake2bMax; c++ { n := c - Blake2bMin + 1 name := fmt.Sprintf("blake2b-%d", n*8) Names[c] = name Types[name] = c } // Add blake2s (32 codes) for c := Blake2sMin; c <= Blake2sMax; c++ { n := c - Blake2sMin + 1 name := fmt.Sprintf("blake2s-%d", n*8) Names[c] = name Types[name] = c } } // NewType - Creates new hash name from string. func NewType(name string) (Type, error) { if t, ok := Types[name]; ok { return t, nil } return UnknownType, fmt.Errorf("unknown hash identifier %q", name) } // Family - Returns algorithm family. func (t Type) Family() Family { switch t { case Sha1: return FamilySha1 case Sha2_256: return FamilySha2 case Sha2_512: return FamilySha2 case Sha3_224: return FamilySha3 case Sha3_256: return FamilySha3 case Sha3_384: return FamilySha3 case Sha3_512: return FamilySha3 case DoubleSha2_256: return FamilyDoubleSha2 case Murmur3: return FamilyMurmur3 case Keccak224: return FamilyKeccak case Keccak256: return FamilyKeccak case Keccak384: return FamilyKeccak case Keccak512: return FamilyKeccak case Shake128: return FamilyShake case Shake256: return FamilyShake default: if t > Blake2bMin && t < Blake2bMax { return FamilyBlake2b } if t > Blake2sMin && t < Blake2sMax { return FamilyBlake2s } return FamilyUnknown } } // Code - Returns algorithm multihash code. func (t Type) Code() uint64 { return uint64(t) } // String - Returns algorithm name. func (t Type) String() string { if name, ok := Names[t]; ok { return name } return "unknown" }
digest/type.go
0.590661
0.439146
type.go
starcoder
package calculator import ( "errors" "math" "strconv" "strings" ) // Add takes two numbers and returns the result of adding them together. func Add(a, b float64, c ...float64) float64 { total := a + b for _, num := range c { total += num } return total } // Subtract takes two numbers and returns the result of subtracting the second from the first. func Subtract(a, b float64, c ...float64) float64 { total := a - b for _, num := range c { total -= num } return total } // Multiply returns first times second func Multiply(a, b float64, c ...float64) float64 { total := a * b for _, num := range c { total *= num } return total } // Divide returns division result from a to b func Divide(a, b float64, c ...float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } total := a / b for _, num := range c { total /= num } return total, nil } // Calculate takes a string, which must parse into a float, then an operator then another float, and makes the apropriated arithmetic functionß func Calculate(str string) (float64, error) { i := strings.Index(str, "+") if i > 0 { firstFloat, err1 := strconv.ParseFloat(strings.TrimSpace(str[:i]), 64) secondFloat, err2 := strconv.ParseFloat(strings.TrimSpace(str[i+1:]), 64) if err1 != nil { return 0, err1 } if err2 != nil { return 0, err2 } return Add(firstFloat, secondFloat), nil } i = strings.Index(str, "-") if i > 0 { firstFloat, err1 := strconv.ParseFloat(strings.TrimSpace(str[:i]), 64) secondFloat, err2 := strconv.ParseFloat(strings.TrimSpace(str[i+1:]), 64) if err1 != nil { return 0, err1 } if err2 != nil { return 0, err2 } return Subtract(firstFloat, secondFloat), nil } i = strings.Index(str, "*") if i > 0 { firstFloat, err1 := strconv.ParseFloat(strings.TrimSpace(str[:i]), 64) secondFloat, err2 := strconv.ParseFloat(strings.TrimSpace(str[i+1:]), 64) if err1 != nil { return 0, err1 } if err2 != nil { return 0, err2 } return Multiply(firstFloat, secondFloat), nil } i = strings.Index(str, "/") if i > 0 { firstFloat, err1 := strconv.ParseFloat(strings.TrimSpace(str[:i]), 64) secondFloat, err2 := strconv.ParseFloat(strings.TrimSpace(str[i+1:]), 64) if err1 != nil { return 0, err1 } if err2 != nil { return 0, err2 } return Divide(firstFloat, secondFloat) } return 0, errors.New("Invalid operation") } // IsPrimo return boolean result for prime numbers func IsPrimo(number int) (bool, error) { isprime := true if number < 0 { return false, errors.New("cannot extract sqrt from negative integers") } if number == 0 { return false, errors.New("cannot extract sqrt from zero") } if number == 1 { return false, nil } if number == 2 { return true, nil } for numLoop := 2; numLoop < number; numLoop++ { got, err := Divide(float64(number), float64(numLoop)) receivedErr := err != nil if receivedErr == true { return false, errors.New("division error") } if got == math.Trunc(got) { isprime = false break } } return isprime, nil } // Remainder returns the remainder of division result from a to b func Remainder(a, b int64) int64 { return a % b } //Sqrt returns square root of number func Sqrt(number float64) (float64, error) { if number < 0 { return 0, errors.New("cannot accept negative numbers on square root") } sqrtresult := math.Sqrt(number) return sqrtresult, nil }
calculator.go
0.803714
0.559471
calculator.go
starcoder
package day24 import "strings" // Grid is a rectangular grid of bugs. type Grid struct { bugs uint64 width int height int } // EmptyGrid creates an empty bug grid of a given size. func EmptyGrid(width, height int) *Grid { return &Grid{ width: width, height: height, } } // GridFromString reads a string representation of a grid of bugs. func GridFromString(s string) *Grid { lines := strings.Split(s, "\n") h := len(lines) w := len(lines[0]) g := EmptyGrid(w, h) for y, line := range lines { for x, c := range line { if c == '#' { g.Infest(x, y) } } } return g } // SimulateOnce runs a simulation of the grid of bugs for one time step. func (g *Grid) SimulateOnce() { ng := *g for y := 0; y < ng.height; y++ { for x := 0; x < ng.width; x++ { if g.shouldBecomeInfested(x, y) { ng.Infest(x, y) } if g.shouldDie(x, y) { ng.Kill(x, y) } } } *g = ng } // Simulate runs a simulation of the grid until a layout of bugs repeats. // Returns the biodiversity rating of that layout. func (g *Grid) Simulate() uint64 { seen := make(map[uint64]interface{}) for i := 0; true; i++ { if _, ok := seen[g.bugs]; ok { return g.bugs } seen[g.bugs] = struct{}{} g.SimulateOnce() } panic("how did we get here?") } // Kill marks the tile at (x, y) as not having a bug. func (g *Grid) Kill(x, y int) { g.bugs &^= g.mask(x, y) } // Infest marks the tile at (x, y) has having a bug. func (g *Grid) Infest(x, y int) { g.bugs |= g.mask(x, y) } func (g *Grid) offset(x, y int) int { return y*g.width + x } func (g *Grid) mask(x, y int) uint64 { return 1 << g.offset(x, y) } func (g *Grid) hasBug(x, y int) bool { if x < 0 || x >= g.width || y < 0 || y >= g.height { return false } return g.bugs&g.mask(x, y) != 0 } func (g *Grid) neighborCount(x, y int) int { var n int if g.hasBug(x-1, y) { n++ } if g.hasBug(x+1, y) { n++ } if g.hasBug(x, y-1) { n++ } if g.hasBug(x, y+1) { n++ } return n } func (g *Grid) shouldBecomeInfested(x, y int) bool { if g.hasBug(x, y) { return false } n := g.neighborCount(x, y) return n == 1 || n == 2 } func (g *Grid) shouldDie(x, y int) bool { if !g.hasBug(x, y) { return false } return g.neighborCount(x, y) != 1 }
day24/grid.go
0.832611
0.536374
grid.go
starcoder
package config /** * Configuration for PQ policy resource. */ type Pqpolicy struct { /** * Name for the priority queuing policy. Must begin with a letter, number, or the underscore symbol (_). Other characters allowed, after the first character, are the hyphen (-), period (.) hash (#), space ( ), at (@), equals (=), and colon (:) characters. */ Policyname string `json:"policyname,omitempty"` /** * Expression or name of a named expression, against which the request is evaluated. The priority queuing policy is applied if the rule evaluates to true. Note: * On the command line interface, if the expression includes blank spaces, the entire expression must be enclosed in double quotation marks. * If the expression itself includes double quotation marks, you must escape the quotations by using the \ character. * Alternatively, you can use single quotation marks to enclose the rule, in which case you will not have to escape the double quotation marks. * Maximum length of a string literal in the expression is 255 characters. A longer string can be split into smaller strings of up to 255 characters each, and the smaller strings concatenated with the + operator. For example, you can create a 500-character string as follows: '"<string of 255 characters>" + "<string of 245 characters>"' */ Rule string `json:"rule,omitempty"` /** * Priority for queuing the request. If server resources are not available for a request that matches the configured rule, this option specifies a priority for queuing the request until the server resources are available again. Enter the value of positive_integer as 1, 2 or 3. The highest priority level is 1 and the lowest priority value is 3. */ Priority int `json:"priority,omitempty"` /** * Weight of the priority. Each priority is assigned a weight according to which it is served when server resources are available. The weight for a higher priority request must be set higher than that of a lower priority request. To prevent delays for low-priority requests across multiple priority levels, you can configure weighted queuing for serving requests. The default weights for the priorities are: * Gold - Priority 1 - Weight 3 * Silver - Priority 2 - Weight 2 * Bronze - Priority 3 - Weight 1 Specify the weights as 0 through 101. A weight of 0 indicates that the particular priority level should be served only when there are no requests in any of the priority queues. A weight of 101 specifies a weight of infinity. This means that this priority level is served irrespective of the number of clients waiting in other priority queues. */ Weight int `json:"weight,omitempty"` /** * Queue depth threshold value. When the queue size (number of requests in the queue) on the virtual server to which this policy is bound, increases to the specified qDepth value, subsequent requests are dropped to the lowest priority level. */ Qdepth int `json:"qdepth,omitempty"` /** * Policy queue depth threshold value. When the policy queue size (number of requests in all the queues belonging to this policy) increases to the specified polqDepth value, subsequent requests are dropped to the lowest priority level. */ Polqdepth int `json:"polqdepth,omitempty"` //------- Read only Parameter ---------; Hits string `json:"hits,omitempty"` }
resource/config/pqpolicy.go
0.82347
0.528229
pqpolicy.go
starcoder
package ternary // Int returns int on any condition value func Int(cond bool, onTrue int, onFalse int) int { if cond { return onTrue } return onFalse } // IntStr returns int on true or string on false condition func IntStr(cond bool, onTrue int, onFalse string) interface{} { if cond { return onTrue } return onFalse } // IntInt8 returns int on true or int8 on false condition func IntInt8(cond bool, onTrue int, onFalse int8) interface{} { if cond { return onTrue } return onFalse } // IntInt16 returns int on true or int16 on false condition func IntInt16(cond bool, onTrue int, onFalse int16) interface{} { if cond { return onTrue } return onFalse } // IntInt32 returns int on true or int32 on false condition func IntInt32(cond bool, onTrue int, onFalse int32) interface{} { if cond { return onTrue } return onFalse } // IntInt64 returns int on true or int64 on false condition func IntInt64(cond bool, onTrue int, onFalse int64) interface{} { if cond { return onTrue } return onFalse } // IntFloat32 returns int on true or float32 on false condition func IntFloat32(cond bool, onTrue int, onFalse float32) interface{} { if cond { return onTrue } return onFalse } // IntFloat64 returns int on true or float64 on false condition func IntFloat64(cond bool, onTrue int, onFalse float64) interface{} { if cond { return onTrue } return onFalse } // IntCmplx64 returns int on true or complex64 on false condition func IntCmplx64(cond bool, onTrue int, onFalse complex64) interface{} { if cond { return onTrue } return onFalse } // IntCmplx128 returns int on true or complex128 on false condition func IntCmplx128(cond bool, onTrue int, onFalse complex128) interface{} { if cond { return onTrue } return onFalse } // IntUint returns int on true or uint on false condition func IntUint(cond bool, onTrue int, onFalse uint) interface{} { if cond { return onTrue } return onFalse } // IntUint8 returns int on true or uint8 on false condition func IntUint8(cond bool, onTrue int, onFalse uint8) interface{} { if cond { return onTrue } return onFalse } // IntUint16 returns int on true or uint16 on false condition func IntUint16(cond bool, onTrue int, onFalse uint16) interface{} { if cond { return onTrue } return onFalse } // IntUint32 returns int on true or uint32 on false condition func IntUint32(cond bool, onTrue int, onFalse uint32) interface{} { if cond { return onTrue } return onFalse } // IntUint64 returns int on true or uint64 on false condition func IntUint64(cond bool, onTrue int, onFalse uint64) interface{} { if cond { return onTrue } return onFalse } // IntUintptr returns int on true or uintptr on false condition func IntUintptr(cond bool, onTrue int, onFalse uintptr) interface{} { if cond { return onTrue } return onFalse } // IntBool returns int on true or bool on false condition func IntBool(cond bool, onTrue int, onFalse bool) interface{} { if cond { return onTrue } return onFalse } // IntIface returns int on true or interface on false condition func IntIface(cond bool, onTrue int, onFalse interface{}) interface{} { if cond { return onTrue } return onFalse } // IntError returns int on true or interface on false condition func IntError(cond bool, onTrue int, onFalse error) interface{} { if cond { return onTrue } return onFalse }
int.go
0.667256
0.404978
int.go
starcoder
package ease import "math" var ( // Linear does a linear interpolation. Linear = &ease{ fp: func(t float64) float64 { return t }, fd: func(t float64) float64 { return 1 }, } // InCubic does a cubic interpolation. InCubic = &ease{ fp: func(t float64) float64 { return t * t * t }, fd: func(t float64) float64 { return 3 * t * t }, } // OutCubic does a cubic interpolation. OutCubic = &ease{ fp: func(t float64) float64 { t-- return t*t*t + 1 }, fd: func(t float64) float64 { t-- return 3 * t * t }, } // InOutCubic does a cubic interpolation. InOutCubic = &ease{ fp: func(t float64) float64 { t *= 2 if t < 1 { return t * t * t / 2 } t -= 2 return (t*t*t + 2) / 2 }, fd: func(t float64) float64 { t *= 2 if t < 1 { return 3 * t * t / 2 } t -= 2 return 3 * t * t / 2 }, } // InSine does a sine interpolation. InSine = &ease{ fp: func(t float64) float64 { return -math.Cos(t*math.Pi/2) + 1 }, } // OutSine does a sine interpolation. OutSine = &ease{ fp: func(t float64) float64 { return math.Sin(t * math.Pi / 2) }, } // InOutSine does a sine interpolation. InOutSine = &ease{ fp: func(t float64) float64 { return -(math.Cos(math.Pi*t) - 1) / 2 }, fd: func(t float64) float64 { return math.Pi * math.Sin(math.Pi*t) / 2 }, } // InBounce does a bouncing interpolation. InBounce = &ease{ fp: func(t float64) float64 { return 1 - OutBounce.fp(1-t) }, } // OutBounce does a bouncing interpolation. OutBounce = &ease{ fp: func(t float64) float64 { switch { case t < 0.3636: return 7.5625 * t * t case t < 0.7272: return 9.075*(t-0.5455)*(t-0.5455) + 0.7 case t < 0.9: return 12.0665*(t-0.8136)*(t-0.8136) + 0.91 } return 10.8*(t-0.95)*(t-0.95) + 0.973 }, } // InOutBounce does a bouncing interpolation. InOutBounce = &ease{ fp: func(t float64) float64 { if t < 0.5 { return InBounce.fp(2*t) / 2 } return OutBounce.fp(2*t-1)/2 + 0.5 }, } )
functions.go
0.685423
0.630685
functions.go
starcoder