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 main import "math" type Located interface { GetXY() Point } type Sized interface { GetWH() Size } type GeoSized interface { GetWH() GeoSize } type GeoPoint struct { X, Y int } type GeoSize struct { W, H int } type Point struct { X, Y float64 } func (receiver Point) Equal(to Point, precision float64) bool { if math.Abs(receiver.X-to.X) <= precision && math.Abs(receiver.Y-to.Y) <= precision { return true } return false } func (receiver Point) Plus(to Point) Point { return Point{ X: receiver.X + to.X, Y: receiver.Y + to.Y, } } func (receiver Point) Minus(to Point) Point { return Point{ X: receiver.X - to.X, Y: receiver.Y - to.Y, } } func (receiver Point) Divide(to Point) Point { return Point{ X: receiver.X / to.X, Y: receiver.Y / to.Y, } } func (receiver Point) Abs() Point { return Point{ X: math.Abs(receiver.X), Y: math.Abs(receiver.Y), } } type Size struct { W, H float64 } func (receiver Size) Equal(to Size, precision float64) bool { if math.Abs(receiver.W-to.W) <= precision && math.Abs(receiver.H-to.H) <= precision { return true } return false } func (receiver Size) Plus(to Size) Size { return Size{ W: receiver.W + to.W, H: receiver.H + to.H, } } func (receiver Size) Minus(to Size) Size { return Size{ W: receiver.W - to.W, H: receiver.H - to.H, } } func (receiver Size) Divide(to Size) Size { return Size{ W: receiver.W / to.W, H: receiver.H / to.H, } } func (receiver Size) Abs() Size { return Size{ W: math.Abs(receiver.W), H: math.Abs(receiver.H), } } type Center struct { X float64 Y float64 } func (receiver Center) Equal(to Center, precision float64) bool { if math.Abs(receiver.X-to.X) <= precision && math.Abs(receiver.Y-to.Y) <= precision { return true } return false } func (receiver Center) Plus(to Center) Center { return Center{ X: receiver.X + to.X, Y: receiver.Y + to.Y, } } func (receiver Center) Minus(to Center) Center { return Center{ X: receiver.X - to.X, Y: receiver.Y - to.Y, } } func (receiver Center) Divide(to Center) Center { return Center{ X: receiver.X / to.X, Y: receiver.Y / to.Y, } } func (receiver Center) Abs() Center { return Center{ X: math.Abs(receiver.X), Y: math.Abs(receiver.Y), } } func (receiver Center) Round() Center { return Center{ X: math.Round(receiver.X), Y: math.Round(receiver.Y), } } type Box struct { Point Size } type Zone struct { X, Y int } func (receiver Zone) Equal(to Zone) bool { return receiver == to } func (receiver Zone) Plus(to Zone) Zone { return Zone{ X: receiver.X + to.X, Y: receiver.Y + to.Y, } } func (receiver Zone) Minus(to Zone) Zone { return Zone{ X: receiver.X - to.X, Y: receiver.Y - to.Y, } } func (receiver Zone) Abs() Zone { return Zone{ X: absInt(receiver.X), Y: absInt(receiver.Y), } }
geomentry.go
0.841142
0.416797
geomentry.go
starcoder
package formencoded import ( "encoding/base64" "strconv" "github.com/jexia/semaphore/v2/pkg/specs/types" ) // AddTypeKey encodes the given value into the given encoder func castType(typed types.Type, value interface{}) string { var casted string switch typed { case types.Double: casted = Float64Empty(value) case types.Int64: casted = Int64Empty(value) case types.Uint64: casted = Uint64Empty(value) case types.Fixed64: casted = Uint64Empty(value) case types.Int32: casted = Int32Empty(value) case types.Uint32: casted = Uint32Empty(value) case types.Fixed32: casted = Uint32Empty(value) case types.Float: casted = Float32Empty(value) case types.String: casted = StringEmpty(value) case types.Enum: casted = StringEmpty(value) case types.Bool: casted = BoolEmpty(value) case types.Bytes: casted = BytesBase64Empty(value) case types.Sfixed32: casted = Int32Empty(value) case types.Sfixed64: casted = Int64Empty(value) case types.Sint32: casted = Int32Empty(value) case types.Sint64: casted = Int64Empty(value) } return casted } // StringEmpty returns the given value as a string or a empty string if the value is nil func StringEmpty(val interface{}) string { if val == nil { return "" } return val.(string) } // BoolEmpty returns the given value as a bool or a empty bool if the value is nil func BoolEmpty(val interface{}) string { if val == nil { return "" } return strconv.FormatBool(val.(bool)) } // Int32Empty returns the given value as a int32 or a empty int32 if the value is nil func Int32Empty(val interface{}) string { if val == nil { return "" } return strconv.FormatInt(int64(val.(int32)), 10) } // Uint32Empty returns the given value as a uint32 or a empty uint32 if the value is nil func Uint32Empty(val interface{}) string { if val == nil { return "" } return strconv.FormatUint(uint64(val.(uint32)), 10) } // Int64Empty returns the given value as a int64 or a empty int64 if the value is nil func Int64Empty(val interface{}) string { if val == nil { return "" } return strconv.FormatInt(val.(int64), 10) } // Uint64Empty returns the given value as a uint64 or a empty uint64 if the value is nil func Uint64Empty(val interface{}) string { if val == nil { return "" } return strconv.FormatUint(val.(uint64), 10) } // Float64Empty returns the given value as a float64 or a empty float64 if the value is nil func Float64Empty(val interface{}) string { if val == nil { return "" } return strconv.FormatFloat(val.(float64), 'E', -1, 64) } // Float32Empty returns the given value as a float32 or a empty float32 if the value is nil func Float32Empty(val interface{}) string { if val == nil { return "" } return strconv.FormatFloat(float64(val.(float32)), 'E', -1, 32) } // BytesBase64Empty returns the given bytes buffer as a base64 string or a empty string if the value is nil func BytesBase64Empty(val interface{}) string { if val == nil { return "" } return base64.StdEncoding.EncodeToString(val.([]byte)) }
pkg/codec/www-form-urlencoded/types.go
0.814828
0.490785
types.go
starcoder
package schemax import "sync" /* AttributeTypeCollection describes all of the following types: • AttributeTypes • RequiredAttributeTypes • PermittedAttributeTypes • ProhibitedAttributeTypes • ApplicableAttributeTypes */ type AttributeTypeCollection interface { // Get returns the *AttributeType instance retrieved as a result // of a term search, based on Name or OID. If no match is found, // nil is returned. Get(interface{}) *AttributeType // Index returns the *AttributeType instance stored at the nth // index within the receiver, or nil. Index(int) *AttributeType // Equal performs a deep-equal between the receiver and the // interface AttributeTypeCollection provided. Equal(AttributeTypeCollection) bool // Set returns an error instance based on an attempt to add // the provided *AttributeType instance to the receiver. Set(*AttributeType) error // Contains returns the index number and presence boolean that // reflects the result of a term search within the receiver. Contains(interface{}) (int, bool) // String returns a properly-delimited sequence of string // values, either as a Name or OID, for the receiver type. String() string // Label returns the field name associated with the interface // types, or a zero string if no label is appropriate. Label() string // IsZero returns a boolean value indicative of whether the // receiver is considered zero, or undefined. IsZero() bool // Len returns an integer value indicative of the current // number of elements stored within the receiver. Len() int // SetSpecifier assigns a string value to all definitions within // the receiver. This value is used in cases where a definition // type name (e.g.: attributetype, objectclass, etc.) is required. // This value will be displayed at the beginning of the definition // value during the unmarshal or unsafe stringification process. SetSpecifier(string) // SetUnmarshaler assigns the provided DefinitionUnmarshaler // signature to all definitions within the receiver. The provided // function shall be executed during the unmarshal or unsafe // stringification process. SetUnmarshaler(DefinitionUnmarshaler) } /* Usage describes the intended usage of an AttributeType definition as a single text value. This can be one of four constant values, the first of which (userApplication) is implied in the absence of any other value and is not necessary to reveal in such a case. */ type Usage uint8 const ( UserApplication Usage = iota DirectoryOperation DistributedOperation DSAOperation ) /* AttributeType conforms to the specifications of RFC4512 Section 4.1.2. Boolean values, e.g: 'OBSOLETE', are supported internally and are not explicit fields. */ type AttributeType struct { OID OID Name Name Description Description SuperType SuperiorAttributeType Equality Equality Ordering Ordering Substring Substring Syntax *LDAPSyntax Usage Usage Extensions Extensions flags definitionFlags mub uint ufn DefinitionUnmarshaler spec string info []byte } /* Type returns the formal name of the receiver in order to satisfy signature requirements of the Definition interface type. */ func (r *AttributeType) Type() string { return `AttributeType` } /* String is an unsafe convenience wrapper for Unmarshal(r). If an error is encountered, an empty string definition is returned. If reliability and error handling are important, use Unmarshal. */ func (r *AttributeType) String() (def string) { def, _ = r.unmarshal() return } /* SuperiorAttributeType contains an embedded instance of *AttributeType. This alias type reflects the SUP field of an attributeType definition. */ type SuperiorAttributeType struct { *AttributeType } /* AttributeTypes is a thread-safe collection of *AttributeType slice instances. */ type AttributeTypes struct { mutex *sync.Mutex slice collection macros *Macros } /* ApplicableAttributeTypes contains an embedded instance of *AttributeTypes. This alias type reflects the APPLIES field of a matchingRuleUse definition. */ type ApplicableAttributeTypes struct { *AttributeTypes } /* String returns a properly-delimited sequence of string values, either as a Name or OID, for the receiver type. */ func (r ApplicableAttributeTypes) String() string { return r.slice.attrs_oids_string() } /* RequiredAttributeTypes contains an embedded instance of *AttributeTypes. This alias type reflects the MUST fields of a dITContentRule or objectClass definitions. */ type RequiredAttributeTypes struct { *AttributeTypes } /* String returns a properly-delimited sequence of string values, either as a Name or OID, for the receiver type. */ func (r RequiredAttributeTypes) String() string { return r.slice.attrs_oids_string() } /* PermittedAttributeTypes contains an embedded instance of *AttributeTypes. This alias type reflects the MAY fields of a dITContentRule or objectClass definitions. */ type PermittedAttributeTypes struct { *AttributeTypes } /* String returns a properly-delimited sequence of string values, either as a Name or OID, for the receiver type. */ func (r PermittedAttributeTypes) String() string { return r.slice.attrs_oids_string() } /* ProhibitedAttributeTypes contains an embedded instance of *AttributeTypes. This alias type reflects the NOT field of a dITContentRule definition. */ type ProhibitedAttributeTypes struct { *AttributeTypes } /* String returns a properly-delimited sequence of string values, either as a Name or OID, for the receiver type. */ func (r ProhibitedAttributeTypes) String() string { return r.slice.attrs_oids_string() } /* SetMacros assigns the *Macros instance to the receiver, allowing subsequent OID resolution capabilities during the addition of new slice elements. */ func (r *AttributeTypes) SetMacros(macros *Macros) { r.macros = macros } /* SetSpecifier is a convenience method that executes the SetSpecifier method in iterative fashion for all definitions within the receiver. */ func (r *AttributeTypes) SetSpecifier(spec string) { for i := 0; i < r.Len(); i++ { r.Index(i).SetSpecifier(spec) } } /* SetUnmarshaler is a convenience method that executes the SetUnmarshaler method in iterative fashion for all definitions within the receiver. */ func (r *AttributeTypes) SetUnmarshaler(fn DefinitionUnmarshaler) { for i := 0; i < r.Len(); i++ { r.Index(i).SetUnmarshaler(fn) } } /* String is a stringer method that returns the string-form of the receiver instance. */ func (r Usage) String() string { switch r { case DirectoryOperation: return `directoryOperation` case DistributedOperation: return `distributedOperation` case DSAOperation: return `dSAOperation` } return `` // default is userApplication, but it need not be stated literally } /* Contains is a thread-safe method that returns a collection slice element index integer and a presence-indicative boolean value based on a term search conducted within the receiver. */ func (r *AttributeTypes) Contains(x interface{}) (int, bool) { r.mutex.Lock() defer r.mutex.Unlock() if !r.macros.IsZero() { if oid, resolved := r.macros.Resolve(x); resolved { return r.slice.contains(oid) } } return r.slice.contains(x) } /* Index is a thread-safe method that returns the nth collection slice element if defined, else nil. This method supports use of negative indices which should be used with special care. */ func (r *AttributeTypes) Index(idx int) *AttributeType { r.mutex.Lock() defer r.mutex.Unlock() assert, _ := r.slice.index(idx).(*AttributeType) return assert } /* Get combines Contains and Index method executions to return an entry based on a term search conducted within the receiver. */ func (r *AttributeTypes) Get(x interface{}) *AttributeType { idx, found := r.Contains(x) if !found { return nil } return r.Index(idx) } /* Len is a thread-safe method that returns the effective length of the receiver slice collection. */ func (r *AttributeTypes) Len() int { return r.slice.len() } /* String is a non-functional stringer method needed to satisfy interface type requirements and should not be used. See the String() method for ApplicableAttributeTypes, RequiredAttributeTypes, PermittedAttributeTypes and ProhibitedAttributeTypes instead. */ func (r *AttributeTypes) String() string { return `` } /* IsZero returns a boolean value indicative of whether the receiver is considered empty or uninitialized. */ func (r *AttributeTypes) IsZero() bool { if r != nil { return r.slice.isZero() } return r == nil } /* IsZero returns a boolean value indicative of whether the receiver is considered empty or uninitialized. */ func (r *AttributeType) IsZero() bool { return r == nil } /* IsZero returns a boolean value indicative of whether the receiver is considered empty or uninitialized. */ func (r SuperiorAttributeType) IsZero() bool { return r.AttributeType.IsZero() } /* Set is a thread-safe append method that returns an error instance indicative of whether the append operation failed in some manner. Uniqueness is enforced for new elements based on Object Identifier and not the effective Name of the definition, if defined. */ func (r *AttributeTypes) Set(x *AttributeType) error { if _, exists := r.Contains(x.OID); exists { return nil //silent } r.mutex.Lock() defer r.mutex.Unlock() return r.slice.append(x) } /* SetSpecifier assigns a string value to the receiver, useful for placement into configurations that require a type name (e.g.: attributetype). This will be displayed at the beginning of the definition value during the unmarshal or unsafe stringification process. */ func (r *AttributeType) SetSpecifier(spec string) { r.spec = spec } /* Equal performs a deep-equal between the receiver and the provided collection type. */ func (r *AttributeTypes) Equal(x AttributeTypeCollection) bool { return r.slice.equal(x.(*AttributeTypes).slice) } /* Equal performs a deep-equal between the receiver and the provided definition type. Description text is ignored. */ func (r *AttributeType) Equal(x interface{}) (equals bool) { var z *AttributeType switch tv := x.(type) { case *AttributeType: z = tv case SuperiorAttributeType: z = tv.AttributeType default: return } if z.IsZero() && r.IsZero() { equals = true return } else if z.IsZero() || r.IsZero() { return } if !z.Name.Equal(r.Name) { return } if !r.OID.Equal(z.OID) { return } if z.Usage != r.Usage { return } if z.flags != r.flags { return } if !z.SuperType.IsZero() && !r.SuperType.IsZero() { if !z.SuperType.OID.Equal(r.SuperType.OID) { return } } if !r.Syntax.Equal(z.Syntax) { return } if !r.Equality.Equal(z.Equality) { return } if !r.Ordering.Equal(z.Ordering) { return } if !r.Substring.Equal(z.Substring) { return } equals = r.Extensions.Equal(z.Extensions) return } /* NewAttributeTypes initializes and returns a new AttributeTypeCollection interface object. */ func NewAttributeTypes() AttributeTypeCollection { var x interface{} = &AttributeTypes{ mutex: &sync.Mutex{}, slice: make(collection, 0, 0), } return x.(AttributeTypeCollection) } /* NewApplicableAttributeTypes initializes an embedded instance of *AttributeTypes within the return value. */ func NewApplicableAttributeTypes() AttributeTypeCollection { var z *AttributeTypes = &AttributeTypes{ mutex: &sync.Mutex{}, slice: make(collection, 0, 0), } var x interface{} = &ApplicableAttributeTypes{z} return x.(AttributeTypeCollection) } /* NewRequiredAttributeTypes initializes an embedded instance of *AttributeTypes within the return value. */ func NewRequiredAttributeTypes() AttributeTypeCollection { var z *AttributeTypes = &AttributeTypes{ mutex: &sync.Mutex{}, slice: make(collection, 0, 0), } var x interface{} = &RequiredAttributeTypes{z} return x.(AttributeTypeCollection) } /* NewPermittedAttributeTypes initializes an embedded instance of *AttributeTypes within the return value. */ func NewPermittedAttributeTypes() AttributeTypeCollection { var z *AttributeTypes = &AttributeTypes{ mutex: &sync.Mutex{}, slice: make(collection, 0, 0), } var x interface{} = &PermittedAttributeTypes{z} return x.(AttributeTypeCollection) } /* NewProhibitedAttributeTypes initializes an embedded instance of *AttributeTypes within the return value. */ func NewProhibitedAttributeTypes() AttributeTypeCollection { var z *AttributeTypes = &AttributeTypes{ mutex: &sync.Mutex{}, slice: make(collection, 0, 0), } var x interface{} = &ProhibitedAttributeTypes{z} return x.(AttributeTypeCollection) } func newUsage(x interface{}) Usage { switch tv := x.(type) { case string: switch toLower(tv) { case toLower(DirectoryOperation.String()): return DirectoryOperation case toLower(DistributedOperation.String()): return DistributedOperation case toLower(DSAOperation.String()): return DSAOperation } case uint: switch tv { case 0x1: return DirectoryOperation case 0x2: return DistributedOperation case 0x3: return DSAOperation } case int: if tv >= 0 { return newUsage(uint(tv)) } } return UserApplication } /* MaxLength returns the integer value, if one was specified, that defines the maximum acceptable value size supported by this *AttributeType per its associated *LDAPSyntax. If not applicable, a 0 is returned. */ func (r *AttributeType) MaxLength() int { return int(r.mub) } /* SetMaxLength sets the minimum upper bounds, or maximum length, of the receiver instance. The argument must be a positive, non-zero integer. This will only apply to *AttributeTypes that use a human-readable syntax. */ func (r *AttributeType) SetMaxLength(max int) { r.setMUB(max) } /* setMUB assigns the number (or string) as the minimum upper bounds value for the receiver. */ func (r *AttributeType) setMUB(mub interface{}) { switch tv := mub.(type) { case string: n, err := atoi(tv) if err != nil || n < 0 { return } r.mub = uint(n) case int: if tv > 0 { r.mub = uint(tv) } case uint: r.mub = tv } } /* is returns a boolean value indicative of whether the provided interface argument is either an enabled definitionFlags value, or an associated *MatchingRule or *LDAPSyntax. In the case of an *LDAPSyntax argument, if the receiver is in fact a sub type of another *AttributeType instance, a reference to that super type is chased and analyzed accordingly. */ func (r *AttributeType) is(b interface{}) bool { switch tv := b.(type) { case definitionFlags: return r.flags.is(tv) case *MatchingRule: switch { case tv.Equal(r.Equality.OID): return true case tv.Equal(r.Ordering.OID): return true case tv.Equal(r.Substring.OID): return true } case *LDAPSyntax: if r.Syntax != nil { return r.Syntax.OID.Equal(tv.OID) } else if !r.SuperType.IsZero() { return r.SuperType.is(tv) } } return false } /* getSyntax will traverse the supertype chain upwards until it finds an explicit SYNTAX definition */ func (r *AttributeType) getSyntax() *LDAPSyntax { if r.IsZero() { return nil } if r.Syntax.IsZero() { return r.SuperType.getSyntax() } return r.Syntax } /* Validate returns an error that reflects any fatal condition observed regarding the receiver configuration. */ func (r *AttributeType) Validate() (err error) { return r.validate() } func (r *AttributeType) validate() (err error) { if r.IsZero() { return raise(isZero, "%T.validate", r) } if err = validateFlag(r.flags); err != nil { return } var ls *LDAPSyntax if ls, err = r.validateSyntax(); err != nil { return } if err = r.validateMatchingRules(ls); err != nil { return } if err = validateNames(r.Name.strings()...); err != nil { return } if err = validateDesc(r.Description); err != nil { return } if !r.SuperType.IsZero() { err = r.SuperType.Validate() } else { if r.Syntax.IsZero() { err = raise(invalidUnmarshal, "%T.unmarshal: %T.%T: %s (not sub-typed)", r, r, r.Syntax, isZero.Error()) } } return } func (r *AttributeType) validateSyntax() (ls *LDAPSyntax, err error) { ls = r.getSyntax() if ls.IsZero() { err = raise(invalidSyntax, "checkMatchingRules: %T is missing a syntax", r) } return } func (r *AttributeType) validateMatchingRules(ls *LDAPSyntax) (err error) { if err = r.validateEquality(ls); err != nil { return err } if err = r.validateOrdering(ls); err != nil { return err } if err = r.validateSubstr(ls); err != nil { return err } return } func (r *AttributeType) validateEquality(ls *LDAPSyntax) error { if !r.Equality.IsZero() { if contains(toLower(r.Equality.Name.Index(0)), `ordering`) || contains(toLower(r.Equality.Name.Index(0)), `substring`) { return raise(invalidMatchingRule, "validateEquality: %T.Equality uses non-equality %T syntax (%s)", r, r.Equality, r.Equality.Syntax.OID.String()) } } return nil } func (r *AttributeType) validateSubstr(ls *LDAPSyntax) error { if !r.Substring.IsZero() { if !contains(toLower(r.Substring.Name.Index(0)), `substring`) { return raise(invalidMatchingRule, "validateSubstr: %T.Substring uses non-substring %T syntax (%s)", r, r.Substring, r.Substring.Syntax.OID.String()) } } return nil } func (r *AttributeType) validateOrdering(ls *LDAPSyntax) error { if !r.Ordering.IsZero() { if !contains(toLower(r.Ordering.Name.Index(0)), `ordering`) { return raise(invalidMatchingRule, "validateOrdering: %T.Ordering uses non-substring %T syntax (%s)", r, r.Ordering, r.Ordering.Syntax.OID.String()) } } return nil } /* SetUnmarshaler assigns the provided DefinitionUnmarshaler signature value to the receiver. The provided function shall be executed during the unmarshal or unsafe stringification process. */ func (r *AttributeType) SetUnmarshaler(fn DefinitionUnmarshaler) { r.ufn = fn } /* SetInfo assigns the byte slice to the receiver. This is a user-leveraged field intended to allow arbitrary information (documentation?) to be assigned to the definition. */ func (r *AttributeType) SetInfo(info []byte) { r.info = info } /* Info returns the assigned informational byte slice instance stored within the receiver. */ func (r *AttributeType) Info() []byte { return r.info } /* Map is a convenience method that returns a map[string][]string instance containing the effective contents of the receiver. */ func (r *AttributeType) Map() (def map[string][]string) { if err := r.Validate(); err != nil { return } def = make(map[string][]string, 14) def[`RAW`] = []string{r.String()} def[`OID`] = []string{r.OID.String()} def[`TYPE`] = []string{r.Type()} if len(r.info) > 0 { def[`INFO`] = []string{string(r.info)} } if !r.Name.IsZero() { def[`NAME`] = make([]string, 0) for i := 0; i < r.Name.Len(); i++ { def[`NAME`] = append(def[`NAME`], r.Name.Index(i)) } } if r.Usage != UserApplication { def[`USAGE`] = []string{r.Usage.String()} } if len(r.Description) > 0 { def[`DESC`] = []string{r.Description.String()} } if !r.Syntax.IsZero() { syn := r.Syntax.OID.String() def[`SYNTAX`] = []string{syn} if r.MaxLength() > 0 { def[`MUB`] = []string{itoa(r.MaxLength())} } } if !r.Equality.IsZero() { term := r.Equality.Name.Index(0) if len(term) == 0 { term = r.Equality.OID.String() } def[`EQUALITY`] = []string{term} } if !r.Substring.IsZero() { term := r.Substring.Name.Index(0) if len(term) == 0 { term = r.Substring.OID.String() } def[`SUBSTR`] = []string{term} } if !r.Ordering.IsZero() { term := r.Ordering.Name.Index(0) if len(term) == 0 { term = r.Ordering.OID.String() } def[`ORDERING`] = []string{term} } if !r.SuperType.IsZero() { term := r.SuperType.Name.Index(0) if len(term) == 0 { term = r.SuperType.OID.String() } def[`SUP`] = []string{term} } if !r.Extensions.IsZero() { for k, v := range r.Extensions { def[k] = v } } if r.Obsolete() { def[`OBSOLETE`] = []string{`TRUE`} } if r.Collective() { def[`COLLECTIVE`] = []string{`TRUE`} } if r.NoUserModification() { def[`NO-USER-MODIFICATION`] = []string{`TRUE`} } if r.SingleValue() { def[`SINGLE-VALUE`] = []string{`TRUE`} } return def } /* AttributeTypeUnmarshaler is a package-included function that honors the signature of the first class (closure) DefinitionUnmarshaler type. The purpose of this function, and similar user-devised ones, is to unmarshal a definition with specific formatting included, such as linebreaks, leading specifier declarations and indenting. */ func AttributeTypeUnmarshaler(x interface{}) (def string, err error) { var r *AttributeType switch tv := x.(type) { case *AttributeType: if tv.IsZero() { err = raise(isZero, "%T is nil", tv) return } r = tv default: err = raise(unexpectedType, "Bad type for unmarshal (%T)", tv) return } var ( WHSP string = ` ` idnt string = "\n\t" head string = `(` tail string = `)` ) if len(r.spec) > 0 { head = r.spec + WHSP + head } def += head + WHSP + r.OID.String() if !r.Name.IsZero() { def += idnt + r.Name.Label() def += WHSP + r.Name.String() } if !r.Description.IsZero() { def += idnt + r.Description.Label() def += WHSP + r.Description.String() } if r.Obsolete() { def += idnt + Obsolete.String() } if !r.SuperType.IsZero() { def += idnt + r.SuperType.Label() def += WHSP + r.SuperType.Name.Index(0) } if !r.Equality.IsZero() { def += idnt + r.Equality.Label() def += WHSP + r.Equality.Name.Index(0) } if !r.Ordering.IsZero() { def += idnt + r.Ordering.Label() def += WHSP + r.Ordering.Name.Index(0) } if !r.Substring.IsZero() { def += idnt + r.Substring.Label() def += WHSP + r.Substring.Name.Index(0) } if !r.Syntax.IsZero() { def += idnt + r.Syntax.Label() def += WHSP + r.Syntax.OID.String() if r.MaxLength() > 0 { def += `{` + itoa(r.MaxLength()) + `}` } } if r.SingleValue() { def += idnt + SingleValue.String() } if r.Collective() { def += idnt + Collective.String() } if r.NoUserModification() { def += idnt + NoUserModification.String() } if r.Usage != UserApplication { def += idnt + r.Usage.Label() def += WHSP + r.Usage.String() } if !r.Extensions.IsZero() { def += idnt + r.Extensions.String() } def += WHSP + tail return } func (r *AttributeType) unmarshal() (string, error) { if err := r.validate(); err != nil { err = raise(invalidUnmarshal, err.Error()) return ``, err } if r.ufn != nil { return r.ufn(r) } return r.unmarshalBasic() } func (r *AttributeType) unmarshalBasic() (def string, err error) { var ( WHSP string = ` ` head string = `(` tail string = `)` ) if len(r.spec) > 0 { head = r.spec + WHSP + head } def += head + WHSP + r.OID.String() if !r.Name.IsZero() { def += WHSP + r.Name.Label() def += WHSP + r.Name.String() } if !r.Description.IsZero() { def += WHSP + r.Description.Label() def += WHSP + r.Description.String() } if r.Obsolete() { def += WHSP + Obsolete.String() } if !r.SuperType.IsZero() { def += WHSP + r.SuperType.Label() def += WHSP + r.SuperType.Name.Index(0) } if !r.Equality.IsZero() { def += WHSP + r.Equality.Label() def += WHSP + r.Equality.Name.Index(0) } if !r.Ordering.IsZero() { def += WHSP + r.Ordering.Label() def += WHSP + r.Ordering.Name.Index(0) } if !r.Substring.IsZero() { def += WHSP + r.Substring.Label() def += WHSP + r.Substring.Name.Index(0) } if !r.Syntax.IsZero() { def += WHSP + r.Syntax.Label() def += WHSP + r.Syntax.OID.String() if r.MaxLength() > 0 { def += `{` + itoa(r.MaxLength()) + `}` } } if r.SingleValue() { def += WHSP + SingleValue.String() } if r.Collective() { def += WHSP + Collective.String() } if r.NoUserModification() { def += WHSP + NoUserModification.String() } if r.Usage != UserApplication { def += WHSP + r.Usage.Label() def += WHSP + r.Usage.String() } if !r.Extensions.IsZero() { def += WHSP + r.Extensions.String() } def += WHSP + tail return }
at.go
0.770119
0.568895
at.go
starcoder
package gohttpspeedtest import ( "fmt" "io" "net/http" "net/url" "strings" "time" ) // Provider is a struct to hold the data need to speed test, download and upload Urls type Provider struct { DownloadURL string UploadURL string } const ( // magic number to fit the tests under 30 seconds numMeasures = 5 ) // MeasureDownloadAnUpload receive a provider with a downloadURL and an uploadURL. // Both downloadURL and uploadURL are used numMeasures times, defined by the constant. // After each download or upload, the Mbits transfered and time consumed are saved to calculate the value of speed in Mbps. func MeasureDownloadAndUpload(provider *Provider) (download float64, upload float64, err error) { download, err = measureDownload(provider.DownloadURL, numMeasures) if err != nil { return 0.0, 0.0, fmt.Errorf("error on measure download: %s", err) } upload, err = measureUpload(provider.UploadURL, numMeasures) if err != nil { return 0.0, 0.0, fmt.Errorf("error on measure upload: %s", err) } return download, upload, nil } func measureDownload(downloadUrl string, num int) (float64, error) { var totalMBits float64 // In Mbit var totalTime float64 // In seconds for i := 0; i < num; i++ { size, elapsed, err := singleDownload(http.DefaultClient, downloadUrl) if err != nil { return 0.0, fmt.Errorf("error on download: %s", err) } // size is in bytes, should convert to Mbits totalMBits += 8 * float64(size) / (1024.0 * 1024.0) totalTime += elapsed.Seconds() } // Mbits/seconds = Mbps return totalMBits / totalTime, nil } func measureUpload(uploadUrl string, num int) (float64, error) { var totalMBits float64 // In Mbit var totalTime float64 // In seconds for i := 0; i < num; i++ { size, elapsed, err := singleUpload(http.DefaultClient, uploadUrl) if err != nil { return 0.0, fmt.Errorf("error on upload: %s", err) } // size is in bytes, should convert to Mbits totalMBits += 8 * float64(size) / (1024.0 * 1024.0) totalTime += elapsed.Seconds() } // Mbits/seconds = Mbps return totalMBits / totalTime, nil } // singleDownload get the resource in downloadUrl and measure the size of the resource and elapsed time. func singleDownload(client *http.Client, downloadUrl string) (size int, elapsed time.Duration, err error) { start := time.Now() res, err := client.Get(downloadUrl) if err != nil || res.StatusCode != http.StatusOK { return 0, time.Duration(0), fmt.Errorf("error on get request to %s: %s", downloadUrl, err) } defer res.Body.Close() // read the body to get the size of resource body, err := io.ReadAll(res.Body) if err != nil { return 0, time.Duration(0), fmt.Errorf("error on read body: %s", err) } elapsed = time.Since(start) return len(body), elapsed, nil } // singleDownload send 25MB to uploadUrl and measure the elapsed time. func singleUpload(client *http.Client, uploadUrl string) (size int, elapsed time.Duration, err error) { v := url.Values{} // generate a 25MB object by repeasing 1M times 25 chars. v.Add("content", strings.Repeat("0123456789012345678901234", 1024*1024)) start := time.Now() res, err := client.PostForm(uploadUrl, v) if err != nil || res.StatusCode != http.StatusOK { return 0, time.Duration(0), fmt.Errorf("error on get request to %s: %s", uploadUrl, err) } defer res.Body.Close() elapsed = time.Since(start) return len(v.Get("content")), elapsed, nil }
speedtest.go
0.674801
0.40987
speedtest.go
starcoder
package planbuilder /* The two core primitives built by this package are Route and Join. The Route primitive executes a query and returns the result. This can be either to a single keyspace or shard, or it can be a scatter query that spans multiple shards. In the case of a scatter, the rows can be returned in any order. The Join primitive can perform a normal or a left join. If there is a join condition, it's actually executed as a constraint on the second (RHS) query. The Join primitive specifies the join variables (bind vars) that need to be built from the results of the first (LHS) query. For example: select ... from a join b on b.col = a.col will be executed as: select ..., a.col from a (produce "a_col" from a.col) select ... from b where b.col = :a_col The planbuilder tries to push all the constructs of the original request into a Route. If it's not possible, we see if we can build a primitive for it. If none exist, we return an error. The central design element for analyzing queries and building plans is the symbol table (symtab). This data structure contains tabsym and colsym elements. A tabsym element represents a table alias defined in the FROM clause. A tabsym must always point to a route, which is responsible for building the SELECT statement for that alias. A colsym represents a result column. It can optionally point to a tabsym if it's a plain column reference of that alias. A colsym must always point to a route. One symtab is created per SELECT statement. tabsym names must be unique within each symtab. Currently, duplicates are allowed among colsyms, just like MySQL does. Different databases implement different rules about whether colsym symbols can hide the tabsym symbols. The rules used by MySQL are not well documented. Therefore, we use the conservative rule that no tabsym can be seen if colsyms are present. The symbol table is modified as various sections of the query are parsed. The parsing of the FROM clause populates the table aliases. These are then used by the WHERE and SELECT clauses. The SELECT clause produces the colsyms, which are added to the symtab after the analysis is done. Consequently, the GROUP BY, HAVING and ORDER BY clauses can only see the colsyms. They're not allowed to reference the table aliases. These access rules transitively apply to subqueries in those clauses, which is the intended behavior. The plan is built in two phases. In the first phase (break-up and push-down), the query is broken into smaller parts and pushed down into Join or Route primitives. In the second phase (wire-up), external references are wired up using bind vars, and the individual ASTs are converted into actual queries. Since the symbol table evolved during the first phase, the wire-up phase cannot reuse it. In order to address this, we save a pointer to the resolved symbol inside every column reference, which we can reuse during the wire-up. The Route for each symbol is used to determine if a reference is local or not. Anything external is converted to a bind var. A route can be merged with another one. If this happens, we should ideally repoint all symbols of that route to the new one. This gets complicated because each route would need to know the symbols that point to it. Instead, we mark the current route as defunct by redirecting to point to the new one. During symbol resolution we chase this pointer until we reach a non-defunct route. The VSchema currently doesn't contain the full list of columns in the tables. For the sake of convenience, if a query references only one table, then we implicitly assume that all column references are against that table. However, in the case of a join, the query must qualify every column reference (table.col). Otherwise, we can't know which tables they're referring to. This same rule applies to subqueries. There is one possibility that's worth mentioning, because it may become relevant in the future: A subquery in the HAVING clause may refer to an unqualified symbol. If that subquery references only one table, then that symbol is automatically presumed to be part of that table. However, in reality, it may actually be a reference to a select expression of the outer query. Fortunately, such use cases are virtually non-exisitent. So, we don't have to worry about it right now. Due to the absence of the column list, we assume that any qualified or implicit column reference of a table is valid. In terms of data structure, the Metadata only points to the table alias. Therefore, a unique column reference is a pointer to a table alias and a column name. This is the basis for the definition of the colref type. If the colref points to a colsym, then the column name is irrelevant. Variable naming: The AST, planbuilder and engine are three different worlds that use overloaded names that are contextually similar, but different. For example a join is: Join is the AST node that represents the SQL construct join is a builder in the current package Join is a primitive in the engine package In order to disambiguate, we'll use the 'a' prefix for AST vars, and the 'e' prefix for engine vars. So, 'ajoin' would be of type *sqlparser.Join, and 'ejoin' would be of type *engine.Join. For the planbuilder join we'll use 'jb'. */
vendor/github.com/youtube/vitess/go/vt/vtgate/planbuilder/doc.go
0.795777
0.848502
doc.go
starcoder
package count import ( "unsafe" ) // Bool returns count of value in list. func Bool(list []bool, value bool) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // BoolD2 returns count of value in list. func BoolD2(list [][]bool, value bool) int { valueCount := 0 for _, listValue := range list { valueCount += Bool(listValue, value) } return valueCount } // BoolD3 returns count of value in list. func BoolD3(list [][][]bool, value bool) int { valueCount := 0 for _, listValue := range list { valueCount += BoolD2(listValue, value) } return valueCount } // BoolD4 returns count of value in list. func BoolD4(list [][][][]bool, value bool) int { valueCount := 0 for _, listValue := range list { valueCount += BoolD3(listValue, value) } return valueCount } // BoolD5 returns count of value in list. func BoolD5(list [][][][][]bool, value bool) int { valueCount := 0 for _, listValue := range list { valueCount += BoolD4(listValue, value) } return valueCount } // Byte returns count of value in list. func Byte(list []byte, value byte) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // ByteD2 returns count of value in list. func ByteD2(list [][]byte, value byte) int { valueCount := 0 for _, listValue := range list { valueCount += Byte(listValue, value) } return valueCount } // ByteD3 returns count of value in list. func ByteD3(list [][][]byte, value byte) int { valueCount := 0 for _, listValue := range list { valueCount += ByteD2(listValue, value) } return valueCount } // ByteD4 returns count of value in list. func ByteD4(list [][][][]byte, value byte) int { valueCount := 0 for _, listValue := range list { valueCount += ByteD3(listValue, value) } return valueCount } // ByteD5 returns count of value in list. func ByteD5(list [][][][][]byte, value byte) int { valueCount := 0 for _, listValue := range list { valueCount += ByteD4(listValue, value) } return valueCount } // Complex64 returns count of value in list. func Complex64(list []complex64, value complex64) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Complex64D2 returns count of value in list. func Complex64D2(list [][]complex64, value complex64) int { valueCount := 0 for _, listValue := range list { valueCount += Complex64(listValue, value) } return valueCount } // Complex64D3 returns count of value in list. func Complex64D3(list [][][]complex64, value complex64) int { valueCount := 0 for _, listValue := range list { valueCount += Complex64D2(listValue, value) } return valueCount } // Complex64D4 returns count of value in list. func Complex64D4(list [][][][]complex64, value complex64) int { valueCount := 0 for _, listValue := range list { valueCount += Complex64D3(listValue, value) } return valueCount } // Complex64D5 returns count of value in list. func Complex64D5(list [][][][][]complex64, value complex64) int { valueCount := 0 for _, listValue := range list { valueCount += Complex64D4(listValue, value) } return valueCount } // Complex128 returns count of value in list. func Complex128(list []complex128, value complex128) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Complex128D2 returns count of value in list. func Complex128D2(list [][]complex128, value complex128) int { valueCount := 0 for _, listValue := range list { valueCount += Complex128(listValue, value) } return valueCount } // Complex128D3 returns count of value in list. func Complex128D3(list [][][]complex128, value complex128) int { valueCount := 0 for _, listValue := range list { valueCount += Complex128D2(listValue, value) } return valueCount } // Complex128D4 returns count of value in list. func Complex128D4(list [][][][]complex128, value complex128) int { valueCount := 0 for _, listValue := range list { valueCount += Complex128D3(listValue, value) } return valueCount } // Complex128D5 returns count of value in list. func Complex128D5(list [][][][][]complex128, value complex128) int { valueCount := 0 for _, listValue := range list { valueCount += Complex128D4(listValue, value) } return valueCount } // Error returns count of value in list. func Error(list []error, value error) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // ErrorD2 returns count of value in list. func ErrorD2(list [][]error, value error) int { valueCount := 0 for _, listValue := range list { valueCount += Error(listValue, value) } return valueCount } // ErrorD3 returns count of value in list. func ErrorD3(list [][][]error, value error) int { valueCount := 0 for _, listValue := range list { valueCount += ErrorD2(listValue, value) } return valueCount } // ErrorD4 returns count of value in list. func ErrorD4(list [][][][]error, value error) int { valueCount := 0 for _, listValue := range list { valueCount += ErrorD3(listValue, value) } return valueCount } // ErrorD5 returns count of value in list. func ErrorD5(list [][][][][]error, value error) int { valueCount := 0 for _, listValue := range list { valueCount += ErrorD4(listValue, value) } return valueCount } // Float32 returns count of value in list. func Float32(list []float32, value float32) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Float32D2 returns count of value in list. func Float32D2(list [][]float32, value float32) int { valueCount := 0 for _, listValue := range list { valueCount += Float32(listValue, value) } return valueCount } // Float32D3 returns count of value in list. func Float32D3(list [][][]float32, value float32) int { valueCount := 0 for _, listValue := range list { valueCount += Float32D2(listValue, value) } return valueCount } // Float32D4 returns count of value in list. func Float32D4(list [][][][]float32, value float32) int { valueCount := 0 for _, listValue := range list { valueCount += Float32D3(listValue, value) } return valueCount } // Float32D5 returns count of value in list. func Float32D5(list [][][][][]float32, value float32) int { valueCount := 0 for _, listValue := range list { valueCount += Float32D4(listValue, value) } return valueCount } // Float64 returns count of value in list. func Float64(list []float64, value float64) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Float64D2 returns count of value in list. func Float64D2(list [][]float64, value float64) int { valueCount := 0 for _, listValue := range list { valueCount += Float64(listValue, value) } return valueCount } // Float64D3 returns count of value in list. func Float64D3(list [][][]float64, value float64) int { valueCount := 0 for _, listValue := range list { valueCount += Float64D2(listValue, value) } return valueCount } // Float64D4 returns count of value in list. func Float64D4(list [][][][]float64, value float64) int { valueCount := 0 for _, listValue := range list { valueCount += Float64D3(listValue, value) } return valueCount } // Float64D5 returns count of value in list. func Float64D5(list [][][][][]float64, value float64) int { valueCount := 0 for _, listValue := range list { valueCount += Float64D4(listValue, value) } return valueCount } // Int returns count of value in list. func Int(list []int, value int) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // IntD2 returns count of value in list. func IntD2(list [][]int, value int) int { valueCount := 0 for _, listValue := range list { valueCount += Int(listValue, value) } return valueCount } // IntD3 returns count of value in list. func IntD3(list [][][]int, value int) int { valueCount := 0 for _, listValue := range list { valueCount += IntD2(listValue, value) } return valueCount } // IntD4 returns count of value in list. func IntD4(list [][][][]int, value int) int { valueCount := 0 for _, listValue := range list { valueCount += IntD3(listValue, value) } return valueCount } // IntD5 returns count of value in list. func IntD5(list [][][][][]int, value int) int { valueCount := 0 for _, listValue := range list { valueCount += IntD4(listValue, value) } return valueCount } // Int8 returns count of value in list. func Int8(list []int8, value int8) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Int8D2 returns count of value in list. func Int8D2(list [][]int8, value int8) int { valueCount := 0 for _, listValue := range list { valueCount += Int8(listValue, value) } return valueCount } // Int8D3 returns count of value in list. func Int8D3(list [][][]int8, value int8) int { valueCount := 0 for _, listValue := range list { valueCount += Int8D2(listValue, value) } return valueCount } // Int8D4 returns count of value in list. func Int8D4(list [][][][]int8, value int8) int { valueCount := 0 for _, listValue := range list { valueCount += Int8D3(listValue, value) } return valueCount } // Int8D5 returns count of value in list. func Int8D5(list [][][][][]int8, value int8) int { valueCount := 0 for _, listValue := range list { valueCount += Int8D4(listValue, value) } return valueCount } // Int16 returns count of value in list. func Int16(list []int16, value int16) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Int16D2 returns count of value in list. func Int16D2(list [][]int16, value int16) int { valueCount := 0 for _, listValue := range list { valueCount += Int16(listValue, value) } return valueCount } // Int16D3 returns count of value in list. func Int16D3(list [][][]int16, value int16) int { valueCount := 0 for _, listValue := range list { valueCount += Int16D2(listValue, value) } return valueCount } // Int16D4 returns count of value in list. func Int16D4(list [][][][]int16, value int16) int { valueCount := 0 for _, listValue := range list { valueCount += Int16D3(listValue, value) } return valueCount } // Int16D5 returns count of value in list. func Int16D5(list [][][][][]int16, value int16) int { valueCount := 0 for _, listValue := range list { valueCount += Int16D4(listValue, value) } return valueCount } // Int32 returns count of value in list. func Int32(list []int32, value int32) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Int32D2 returns count of value in list. func Int32D2(list [][]int32, value int32) int { valueCount := 0 for _, listValue := range list { valueCount += Int32(listValue, value) } return valueCount } // Int32D3 returns count of value in list. func Int32D3(list [][][]int32, value int32) int { valueCount := 0 for _, listValue := range list { valueCount += Int32D2(listValue, value) } return valueCount } // Int32D4 returns count of value in list. func Int32D4(list [][][][]int32, value int32) int { valueCount := 0 for _, listValue := range list { valueCount += Int32D3(listValue, value) } return valueCount } // Int32D5 returns count of value in list. func Int32D5(list [][][][][]int32, value int32) int { valueCount := 0 for _, listValue := range list { valueCount += Int32D4(listValue, value) } return valueCount } // Int64 returns count of value in list. func Int64(list []int64, value int64) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // Int64D2 returns count of value in list. func Int64D2(list [][]int64, value int64) int { valueCount := 0 for _, listValue := range list { valueCount += Int64(listValue, value) } return valueCount } // Int64D3 returns count of value in list. func Int64D3(list [][][]int64, value int64) int { valueCount := 0 for _, listValue := range list { valueCount += Int64D2(listValue, value) } return valueCount } // Int64D4 returns count of value in list. func Int64D4(list [][][][]int64, value int64) int { valueCount := 0 for _, listValue := range list { valueCount += Int64D3(listValue, value) } return valueCount } // Int64D5 returns count of value in list. func Int64D5(list [][][][][]int64, value int64) int { valueCount := 0 for _, listValue := range list { valueCount += Int64D4(listValue, value) } return valueCount } // Interface returns count of value in list. func Interface(list []interface{}, value interface{}) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // InterfaceD2 returns count of value in list. func InterfaceD2(list [][]interface{}, value interface{}) int { valueCount := 0 for _, listValue := range list { valueCount += Interface(listValue, value) } return valueCount } // InterfaceD3 returns count of value in list. func InterfaceD3(list [][][]interface{}, value interface{}) int { valueCount := 0 for _, listValue := range list { valueCount += InterfaceD2(listValue, value) } return valueCount } // InterfaceD4 returns count of value in list. func InterfaceD4(list [][][][]interface{}, value interface{}) int { valueCount := 0 for _, listValue := range list { valueCount += InterfaceD3(listValue, value) } return valueCount } // InterfaceD5 returns count of value in list. func InterfaceD5(list [][][][][]interface{}, value interface{}) int { valueCount := 0 for _, listValue := range list { valueCount += InterfaceD4(listValue, value) } return valueCount } // Pointer returns count of value in list. func Pointer(list []unsafe.Pointer, value unsafe.Pointer) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // PointerD2 returns count of value in list. func PointerD2(list [][]unsafe.Pointer, value unsafe.Pointer) int { valueCount := 0 for _, listValue := range list { valueCount += Pointer(listValue, value) } return valueCount } // PointerD3 returns count of value in list. func PointerD3(list [][][]unsafe.Pointer, value unsafe.Pointer) int { valueCount := 0 for _, listValue := range list { valueCount += PointerD2(listValue, value) } return valueCount } // PointerD4 returns count of value in list. func PointerD4(list [][][][]unsafe.Pointer, value unsafe.Pointer) int { valueCount := 0 for _, listValue := range list { valueCount += PointerD3(listValue, value) } return valueCount } // PointerD5 returns count of value in list. func PointerD5(list [][][][][]unsafe.Pointer, value unsafe.Pointer) int { valueCount := 0 for _, listValue := range list { valueCount += PointerD4(listValue, value) } return valueCount } // Rune returns count of value in list. func Rune(list []rune, value rune) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // RuneD2 returns count of value in list. func RuneD2(list [][]rune, value rune) int { valueCount := 0 for _, listValue := range list { valueCount += Rune(listValue, value) } return valueCount } // RuneD3 returns count of value in list. func RuneD3(list [][][]rune, value rune) int { valueCount := 0 for _, listValue := range list { valueCount += RuneD2(listValue, value) } return valueCount } // RuneD4 returns count of value in list. func RuneD4(list [][][][]rune, value rune) int { valueCount := 0 for _, listValue := range list { valueCount += RuneD3(listValue, value) } return valueCount } // RuneD5 returns count of value in list. func RuneD5(list [][][][][]rune, value rune) int { valueCount := 0 for _, listValue := range list { valueCount += RuneD4(listValue, value) } return valueCount } // String returns count of value in list. func String(list []string, value string) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // StringD2 returns count of value in list. func StringD2(list [][]string, value string) int { valueCount := 0 for _, listValue := range list { valueCount += String(listValue, value) } return valueCount } // StringD3 returns count of value in list. func StringD3(list [][][]string, value string) int { valueCount := 0 for _, listValue := range list { valueCount += StringD2(listValue, value) } return valueCount } // StringD4 returns count of value in list. func StringD4(list [][][][]string, value string) int { valueCount := 0 for _, listValue := range list { valueCount += StringD3(listValue, value) } return valueCount } // StringD5 returns count of value in list. func StringD5(list [][][][][]string, value string) int { valueCount := 0 for _, listValue := range list { valueCount += StringD4(listValue, value) } return valueCount } // UInt returns count of value in list. func UInt(list []uint, value uint) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // UIntD2 returns count of value in list. func UIntD2(list [][]uint, value uint) int { valueCount := 0 for _, listValue := range list { valueCount += UInt(listValue, value) } return valueCount } // UIntD3 returns count of value in list. func UIntD3(list [][][]uint, value uint) int { valueCount := 0 for _, listValue := range list { valueCount += UIntD2(listValue, value) } return valueCount } // UIntD4 returns count of value in list. func UIntD4(list [][][][]uint, value uint) int { valueCount := 0 for _, listValue := range list { valueCount += UIntD3(listValue, value) } return valueCount } // UIntD5 returns count of value in list. func UIntD5(list [][][][][]uint, value uint) int { valueCount := 0 for _, listValue := range list { valueCount += UIntD4(listValue, value) } return valueCount } // UInt8 returns count of value in list. func UInt8(list []uint8, value uint8) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // UInt8D2 returns count of value in list. func UInt8D2(list [][]uint8, value uint8) int { valueCount := 0 for _, listValue := range list { valueCount += UInt8(listValue, value) } return valueCount } // UInt8D3 returns count of value in list. func UInt8D3(list [][][]uint8, value uint8) int { valueCount := 0 for _, listValue := range list { valueCount += UInt8D2(listValue, value) } return valueCount } // UInt8D4 returns count of value in list. func UInt8D4(list [][][][]uint8, value uint8) int { valueCount := 0 for _, listValue := range list { valueCount += UInt8D3(listValue, value) } return valueCount } // UInt8D5 returns count of value in list. func UInt8D5(list [][][][][]uint8, value uint8) int { valueCount := 0 for _, listValue := range list { valueCount += UInt8D4(listValue, value) } return valueCount } // UInt16 returns count of value in list. func UInt16(list []uint16, value uint16) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // UInt16D2 returns count of value in list. func UInt16D2(list [][]uint16, value uint16) int { valueCount := 0 for _, listValue := range list { valueCount += UInt16(listValue, value) } return valueCount } // UInt16D3 returns count of value in list. func UInt16D3(list [][][]uint16, value uint16) int { valueCount := 0 for _, listValue := range list { valueCount += UInt16D2(listValue, value) } return valueCount } // UInt16D4 returns count of value in list. func UInt16D4(list [][][][]uint16, value uint16) int { valueCount := 0 for _, listValue := range list { valueCount += UInt16D3(listValue, value) } return valueCount } // UInt16D5 returns count of value in list. func UInt16D5(list [][][][][]uint16, value uint16) int { valueCount := 0 for _, listValue := range list { valueCount += UInt16D4(listValue, value) } return valueCount } // UInt32 returns count of value in list. func UInt32(list []uint32, value uint32) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // UInt32D2 returns count of value in list. func UInt32D2(list [][]uint32, value uint32) int { valueCount := 0 for _, listValue := range list { valueCount += UInt32(listValue, value) } return valueCount } // UInt32D3 returns count of value in list. func UInt32D3(list [][][]uint32, value uint32) int { valueCount := 0 for _, listValue := range list { valueCount += UInt32D2(listValue, value) } return valueCount } // UInt32D4 returns count of value in list. func UInt32D4(list [][][][]uint32, value uint32) int { valueCount := 0 for _, listValue := range list { valueCount += UInt32D3(listValue, value) } return valueCount } // UInt32D5 returns count of value in list. func UInt32D5(list [][][][][]uint32, value uint32) int { valueCount := 0 for _, listValue := range list { valueCount += UInt32D4(listValue, value) } return valueCount } // UInt64 returns count of value in list. func UInt64(list []uint64, value uint64) int { valueCount := 0 for _, listValue := range list { if listValue == value { valueCount++ } } return valueCount } // UInt64D2 returns count of value in list. func UInt64D2(list [][]uint64, value uint64) int { valueCount := 0 for _, listValue := range list { valueCount += UInt64(listValue, value) } return valueCount } // UInt64D3 returns count of value in list. func UInt64D3(list [][][]uint64, value uint64) int { valueCount := 0 for _, listValue := range list { valueCount += UInt64D2(listValue, value) } return valueCount } // UInt64D4 returns count of value in list. func UInt64D4(list [][][][]uint64, value uint64) int { valueCount := 0 for _, listValue := range list { valueCount += UInt64D3(listValue, value) } return valueCount } // UInt64D5 returns count of value in list. func UInt64D5(list [][][][][]uint64, value uint64) int { valueCount := 0 for _, listValue := range list { valueCount += UInt64D4(listValue, value) } return valueCount }
count/count.go
0.715523
0.46132
count.go
starcoder
package iplookuptree import ( "encoding/binary" "math" "net" ) // bitslen contstant must be a power of 2. It indicates how much space // will be taken by a tree and maximum number of hops (treenode accesses). When bitslen is 4, // the maximum number of hops will be 32 / bitslen and one node takes // 1<< bitslen * (sizeof SID and *treenode). So current constant (4) will make maximum 8 hops and // every node consumes 256 bytes. const bitslen = 4 // SID type contains a list of corresponding service indexes. // Every nth bit indicates nth service. So 0x1 stores (0), // 0x2 stores (1), 0x3 stores (0, 1) services and etc. // So you can handle up to 64 services. // 0 indicates that there are no service. // Example: service has index 6, then its SID representation will be 1<<6 type SID uint64 type Tree struct { root *treenode } type treenode struct { srvs [1<<bitslen]SID ptrs [1<<bitslen]*treenode } // isEmpty checks if node is empty. Used to determine whether to delete node // Reminder: don't accidentally remove root node func (node *treenode) isEmpty() bool { for i := 0; i < 1<<bitslen; i++ { if node.srvs[i] != 0 || node.ptrs[i] != nil { return false } } return true } // New creates new IP subnet tree. It only works with IP v4 func New() *Tree { tree := &Tree{&treenode{}} return tree } // Add adds ip subnet to the tree. // service should contain only one true bit (anyway it works well with multiple bits). // ipnet.IP must be of the length 4 (IP v4). // It is up to you to handle this. // This method does not compress subnets - if you put 1.1.1.1/24 and 1.1.1.1/23 // of the same service, it will hold both subnets. func (tree *Tree) Add(service SID, ipnet net.IPNet) { node := tree.root prefixLen, _ := ipnet.Mask.Size() curLen := bitslen for i := 0; i < 32 / bitslen; i++ { if curLen >= prefixLen { start := getSubstring(ipnet.IP, uint8(i)) end := start + (1<<uint(curLen - prefixLen)) - 1 for j := start; j <= end; j++ { node.srvs[j] = node.srvs[j] | service } break } ind := getSubstring(ipnet.IP, uint8(i)) if node.ptrs[ind] != nil { node = node.ptrs[ind] } else { node.ptrs[ind] = &treenode{} node = node.ptrs[ind] } curLen += bitslen } } // Get returns SID which corresponds to this ip v4 // ipv4 must be of length 4 and it is up to you to // handle this. func (tree *Tree) Get(ipv4 []byte) SID { var ans SID cur := tree.root for i := 0; i < 32 / bitslen; i++ { ind := getSubstring(ipv4, uint8(i)) ans = ans | cur.srvs[ind] if cur = cur.ptrs[ind]; cur == nil { break } } return ans } // getSubstring is helper function that returns substring of // bits placed in range [index * bitslen, index * bitslen + bitslen) func getSubstring(ipv4 []byte, index uint8) uint32 { var ans = binary.BigEndian.Uint32(ipv4) ans = ans <<(bitslen * index) ans = ans >>(32 - bitslen) return ans } // Remove removes subnet from the tree. It works properly if you add // and remove the same subnet. However, it will lead to undefined behaviour, if // you remove subnet which was not added before. func (tree *Tree) Remove(service SID, ipnet net.IPNet) { reversedService := math.MaxUint64 ^ service node := tree.root path := make([]*treenode, 32 / bitslen, 32 / bitslen) indpath := make([]uint32, 32 / bitslen, 32 / bitslen) pathlen := 0 prefixLen, _ := ipnet.Mask.Size() curLen := bitslen for i := 0; i < 32 / bitslen; i++ { path[pathlen] = node pathlen++ if curLen >= prefixLen { start := getSubstring(ipnet.IP, uint8(i)) end := start + (1<<uint(curLen - prefixLen)) - 1 for j := start; j <= end; j++ { node.srvs[j] = node.srvs[j] & reversedService } break } ind := getSubstring(ipnet.IP, uint8(i)) indpath[pathlen] = ind if node.ptrs[ind] != nil { node = node.ptrs[ind] } curLen += bitslen } for i := pathlen - 1; i > 0; i-- { node = path[i] parent := path[i - 1] ind := indpath[i] if node.isEmpty() { parent.ptrs[ind] = nil } } }
iplookuptree.go
0.578805
0.415432
iplookuptree.go
starcoder
package nonogram import ( "fmt" "math/rand" ) type Board interface { Size() int32 Count(Cell) int Percent(Cell) float32 Get(x, y int32) Cell Set(x, y int32, cell Cell) error Column(x int32) []uint8 ColumnStr(x int32) string Line(x int32) []uint8 LineStr(x int32) string RevealColumn(x int32) RevealLine(y int32) Eq(other Board) bool } type board struct { size int32 data []Cell } func NewBoard(size int32) Board { return &board{ size: size, data: make([]Cell, size*size), } } func (b board) Count(cell Cell) int { count := 0 for _, c := range b.data { if c == cell { count++ } } return count } func (b board) Percent(cell Cell) float32 { count := b.Count(cell) return float32(count) / float32(b.size*b.size) } func NewRandomBoard(size int32, checked float64) Board { b := NewBoard(size) for y := int32(0); y < size; y++ { for x := int32(0); x < size; x++ { if rand.Float64() < checked { b.Set(x, y, CellSet) } else { b.Set(x, y, CellUnset) } } } return b } func (b board) Size() int32 { return b.size } func (b board) Get(x, y int32) Cell { if x < 0 || x >= b.size || y < 0 || y >= b.size { return CellUnknown } return Cell(b.data[y*b.size+x]) } func (b *board) Set(x, y int32, cell Cell) error { if x < 0 || x >= b.size || y < 0 || y >= b.size { return fmt.Errorf("out of bounds") } b.data[y*b.size+x] = cell return nil } func (b board) Column(x int32) []uint8 { column := make([]uint8, 0) counter := uint8(0) for y := int32(0); y < b.size; y++ { if b.Get(x, y).IsSet() { counter++ } else { if counter > uint8(0) { column = append(column, counter) counter = uint8(0) } } } if counter > 0 || len(column) == 0 { column = append(column, counter) } return column } func (b board) ColumnStr(x int32) string { column := b.Column(x) res := make([]byte, len(column)) for i, c := range column { res[i] = c + 0x30 } return string(res) } func (b board) Line(y int32) []uint8 { line := make([]uint8, 0) counter := uint8(0) for x := int32(0); x < b.size; x++ { if b.Get(x, y).IsSet() { counter++ } else { if counter > uint8(0) { line = append(line, counter) counter = uint8(0) } } } if counter > 0 || len(line) == 0 { line = append(line, counter) } return line } func (b board) LineStr(y int32) string { line := b.Line(y) res := make([]byte, len(line)) for i, c := range line { res[i] = c + 0x30 } return string(res) } func (b *board) RevealColumn(x int32) { for y := int32(0); y < b.size; y++ { if b.Get(x, y).IsUnknown() { b.Set(x, y, CellUnset) } } } func (b *board) RevealLine(y int32) { for x := int32(0); x < b.size; x++ { if b.Get(x, y).IsUnknown() { b.Set(x, y, CellUnset) } } } func (b board) Eq(other Board) bool { if b.size != other.Size() { return false } for x := int32(0); x < b.size; x++ { if b.ColumnStr(x) != other.ColumnStr(x) { return false } } for y := int32(0); y < b.size; y++ { if b.LineStr(y) != other.LineStr(y) { return false } } return true }
nonogram/board.go
0.560734
0.466846
board.go
starcoder
package intersect import "math" // Vector defines a struct for a 2d vector, or a point type Vector struct { X float64 Y float64 } // NewVector creates a new vector func NewVector(x, y float64) Vector { return Vector{x, y} } // NewVectorMagDir creates a new vector by specifying the magnitude and direction func NewVectorMagDir(mag, dir float64) Vector { return Vector{mag * math.Cos(dir), mag * math.Sin(dir)} } // Equals returns true if the x and y components of the vectors are within 1E-9 of each other func (v1 Vector) Equals(v2 Vector) bool { return floatEquals(v1.X, v2.X) && floatEquals(v1.Y, v2.Y) } // Len returns the dot product of the vector with another func (v1 Vector) Dot(v2 Vector) float64 { return v1.X*v2.X + v1.Y*v2.Y } // Len2 returns the length of the vector func (v1 Vector) Len() float64 { return math.Sqrt(v1.Len2()) } // Len2 returns the length of the vector squared. This is faster then Len, and useful for comparisons func (v1 Vector) Len2() float64 { return v1.X*v1.X + v1.Y*v1.Y } // Add returns the addition of one vector with another func (v1 Vector) Add(v2 Vector) Vector { return Vector{v1.X + v2.X, v1.Y + v2.Y} } // Sub returns the subtraction of one vector with another func (v1 Vector) Sub(v2 Vector) Vector { return Vector{v1.X - v2.X, v1.Y - v2.Y} } // Norm return a vector of the same angle, but whose length is no 1 func (v1 Vector) Norm() Vector { l := v1.Len() return Vector{v1.X / l, v1.Y / l} } // Lim return a vector of the same angle, but whose length is no longer then the maximum func (v1 Vector) Lim(max float64) Vector { l := v1.Len() if l > max { return v1.Norm().Scale(max) } return v1 } // Rotate return a vector rotated by the given angle in radians counter clockwise func (v1 Vector) Rotate(ang float64) Vector { return NewVectorMagDir(v1.Len(), v1.Angle()+ang) } // Angle return an angle in radians the vector is at func (v1 Vector) Angle() float64 { a := math.Mod(math.Atan2(v1.Y, v1.X), 2*math.Pi) if a < 0 { a += math.Pi * 2 } return a } // Scale return a vector in the same direction, but with the magnitude multiplied by the scaling factor func (v1 Vector) Scale(sf float64) Vector { return Vector{v1.X * sf, v1.Y * sf} } // Collinear return true iff a, b, and c all lie on the same line." func Collinear(a, b, c Vector) bool { return (b.X-a.X)*(c.Y-a.Y) == (c.X-a.X)*(b.Y-a.Y) } const fEPSILON float64 = 1e-9 func floatEquals(a, b float64) bool { if math.Abs(a-b) < fEPSILON { return true } return false }
vector.go
0.947064
0.820937
vector.go
starcoder
package ptp const ptpVersion = uint8(5) const ( floatBytes = 4 uint32Bytes = 4 ) // segments with all dimension deltas smaller than this will be skipped const skipThreshold = 0.01 // tolerance used by collinearity-checking functions const collinearityEpsilon = 10e-5 // in-file header only contains version information // (buffer offsets and sizes are now stored in the legend file) const headerSize = 4 var ( colorWhite = [3]float32{0xff / 255.0, 0xff / 255.0, 0xff / 255.0} // #ffffff colorGreen = [3]float32{0x6b / 255.0, 0xa7 / 255.0, 0x31 / 255.0} // #6ba731 colorDarkGrey = [3]float32{0x32 / 255.0, 0x29 / 255.0, 0x2f / 255.0} // #32292f colorYellow = [3]float32{0xf7 / 255.0, 0xb5 / 255.0, 0x38 / 255.0} // #f7b538 colorPurple = [3]float32{0x3d / 255.0, 0x31 / 255.0, 0x5b / 255.0} // #3d315b colorLilac = [3]float32{0x97 / 255.0, 0x89 / 255.0, 0xba / 255.0} // #9789ba colorLightGreen = [3]float32{0x71 / 255.0, 0xb5 / 255.0, 0x98 / 255.0} // #71b598 colorTeal = [3]float32{0x3b / 255.0, 0x8e / 255.0, 0xa5 / 255.0} // #3b8ea5 colorRed = [3]float32{0xdb / 255.0, 0x32 / 255.0, 0x4d / 255.0} // #db324d colorPink = [3]float32{0xd6 / 255.0, 0x7a / 255.0, 0x89 / 255.0} // #d67a89 colorOrange = [3]float32{0xd5 / 255.0, 0x57 / 255.0, 0x3b / 255.0} // #d5573b colorSky = [3]float32{0xd4 / 255.0, 0xde / 255.0, 0xff / 255.0} // #d4deff colorLightGrey = [3]float32{0xd1 / 255.0, 0xd1 / 255.0, 0xd1 / 255.0} // #d1d1d1 ) type PathType int const ( PathTypeUnknown PathType = iota PathTypeStartSequence PathTypeEndSequence PathTypeRaft PathTypeBrim PathTypeSupport PathTypeSupportInterface PathTypeInnerPerimeter PathTypeOuterPerimeter PathTypeSolidLayer PathTypeInfill PathTypeGapFill PathTypeBridge PathTypeIroning PathTypeTransition PathTypePing pathTypeCount ) var pathTypeNames = map[PathType]string{ PathTypeUnknown: "Unknown", PathTypeStartSequence: "Start Sequence", PathTypeEndSequence: "End Sequence", PathTypeRaft: "Raft", PathTypeBrim: "Skirt/Brim", PathTypeSupport: "Support", PathTypeSupportInterface: "Support Interface", PathTypeInnerPerimeter: "Inner Perimeter", PathTypeOuterPerimeter: "Outer Perimeter", PathTypeSolidLayer: "Solid Layer", PathTypeInfill: "Infill", PathTypeGapFill: "Gap Fill", PathTypeBridge: "Bridge", PathTypeIroning: "Ironing", PathTypeTransition: "Transition", PathTypePing: "Ping", } var pathTypeColors = map[PathType][3]float32{ PathTypeUnknown: colorWhite, PathTypeStartSequence: colorDarkGrey, PathTypeEndSequence: colorDarkGrey, PathTypeRaft: colorLilac, PathTypeBrim: colorSky, PathTypeSupport: colorPurple, PathTypeSupportInterface: colorLilac, PathTypeInnerPerimeter: colorLightGreen, PathTypeOuterPerimeter: colorTeal, PathTypeSolidLayer: colorRed, PathTypeInfill: colorYellow, PathTypeGapFill: colorOrange, PathTypeBridge: colorSky, PathTypeIroning: colorPink, PathTypeTransition: colorLightGrey, PathTypePing: colorLightGrey, } var pathTypeColorStrings = map[PathType]string{ PathTypeUnknown: "#ffffff", PathTypeStartSequence: "#32292f", PathTypeEndSequence: "#32292f", PathTypeRaft: "#9789ba", PathTypeBrim: "#d4deff", PathTypeSupport: "#3d315b", PathTypeSupportInterface: "#9789ba", PathTypeInnerPerimeter: "#71b598", PathTypeOuterPerimeter: "#3b8ea5", PathTypeSolidLayer: "#db324d", PathTypeInfill: "#f7b538", PathTypeGapFill: "#d5573b", PathTypeBridge: "#bcd4de", PathTypeIroning: "#d67a89", PathTypeTransition: "#d1d1d1", PathTypePing: "#d1d1d1", } var feedrateColorMin = colorRed var feedrateColorMax = colorTeal var fanColorMin = colorRed var fanColorMax = colorGreen var temperatureColorMin = colorTeal var temperatureColorMax = colorRed var layerHeightColorMin = colorTeal var layerHeightColorMax = colorOrange
ptp/constants.go
0.504394
0.491761
constants.go
starcoder
package convnet import ( "encoding/json" "math" "math/rand" ) // Layers that implement a loss. Currently these are the layers that // can initiate a backward() pass. In future we probably want a more // flexible system that can accomodate multiple losses to do multi-task // learning, and stuff like that. But for now, one of the layers in this // file must be the final layer in a Net. // This is a classifier, with N discrete classes from 0 to N-1 // it gets a stream of N incoming numbers and computes the softmax // function (exponentiate and normalize to sum to 1 as probabilities should) type SoftmaxLayer struct { outDepth int inAct *Vol outAct *Vol es []float64 } var _ LossLayer = (*SoftmaxLayer)(nil) func (l *SoftmaxLayer) OutSx() int { return 1 } func (l *SoftmaxLayer) OutSy() int { return 1 } func (l *SoftmaxLayer) OutDepth() int { return l.outDepth } func (l *SoftmaxLayer) fromDef(def LayerDef, r *rand.Rand) { l.outDepth = def.InSx * def.InSy * def.InDepth } func (l *SoftmaxLayer) Forward(v *Vol, isTraining bool) *Vol { a := NewVol(1, 1, l.outDepth, 0.0) // compute max activation as := v.W amax := v.W[0] for i := 1; i < l.outDepth; i++ { if as[i] > amax { amax = as[i] } } // compute exponentials (carefully to not blow up) es := make([]float64, l.outDepth) esum := 0.0 for i := 0; i < l.outDepth; i++ { e := math.Exp(as[i] - amax) esum += e es[i] = e } // normalize and output to sum to one for i := 0; i < l.outDepth; i++ { es[i] /= esum a.W[i] = es[i] } l.es = es // save these for backprop l.outAct = a return l.outAct } func (l *SoftmaxLayer) Backward() {} func (l *SoftmaxLayer) BackwardLoss(y LossData) float64 { // compute and accumulate gradient wrt weights and bias of this layer x := l.inAct // zero out the gradient of input Vol x.Dw = make([]float64, len(x.W)) for i := 0; i < l.outDepth; i++ { indicator := 0.0 if i == y.Dim { indicator = 1.0 } mul := -(indicator - l.es[i]) x.Dw[i] = mul } // loss is the class negative log likelihood return -math.Log(l.es[y.Dim]) } func (l *SoftmaxLayer) ParamsAndGrads() []ParamsAndGrads { return nil } func (l *SoftmaxLayer) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { OutDepth int `json:"out_depth"` OutSx int `json:"out_sx"` OutSy int `json:"out_sy"` LayerType string `json:"layer_type"` NumInputs int `json:"num_inputs"` }{ OutDepth: l.outDepth, OutSx: 1, OutSy: 1, LayerType: LayerSoftmax.String(), NumInputs: l.outDepth, }) } func (l *SoftmaxLayer) UnmarshalJSON(b []byte) error { var data struct { OutDepth int `json:"out_depth"` OutSx int `json:"out_sx"` OutSy int `json:"out_sy"` LayerType string `json:"layer_type"` NumInputs int `json:"num_inputs"` } if err := json.Unmarshal(b, &data); err != nil { return err } l.outDepth = data.OutDepth return nil } // implements an L2 regression cost layer, // so penalizes \sum_i(||x_i - y_i||^2), where x is its input // and y is the user-provided array of "correct" values. type RegressionLayer struct { numInputs int act *Vol } var _ LossLayer = (*RegressionLayer)(nil) func (l *RegressionLayer) OutDepth() int { return l.numInputs } func (l *RegressionLayer) OutSx() int { return 1 } func (l *RegressionLayer) OutSy() int { return 1 } func (l *RegressionLayer) fromDef(def LayerDef, r *rand.Rand) { // computed l.numInputs = def.InSx * def.InSy * def.InDepth } func (l *RegressionLayer) Forward(v *Vol, isTraining bool) *Vol { l.act = v return v // identity function } func (l *RegressionLayer) Backward() {} func (l *RegressionLayer) BackwardLoss(y LossData) float64 { // compute and accumulate gradient wrt weights and bias of this layer x := l.act x.Dw = make([]float64, len(x.W)) // zero out the gradient of input Vol i, yi := y.Dim, y.Val dy := x.W[i] - yi x.Dw[i] = dy return 0.5 * dy * dy } func (l *RegressionLayer) ParamsAndGrads() []ParamsAndGrads { return nil } func (l *RegressionLayer) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { OutDepth int `json:"out_depth"` OutSx int `json:"out_sx"` OutSy int `json:"out_sy"` LayerType string `json:"layer_type"` NumInputs int `json:"num_inputs"` }{ OutDepth: l.numInputs, OutSx: 1, OutSy: 1, LayerType: LayerRegression.String(), NumInputs: l.numInputs, }) } func (l *RegressionLayer) UnmarshalJSON(b []byte) error { var data struct { OutDepth int `json:"out_depth"` OutSx int `json:"out_sx"` OutSy int `json:"out_sy"` LayerType string `json:"layer_type"` NumInputs int `json:"num_inputs"` } if err := json.Unmarshal(b, &data); err != nil { return err } l.numInputs = data.NumInputs return nil } type SVMLayer struct { numInputs int act *Vol } var _ LossLayer = (*SVMLayer)(nil) func (l *SVMLayer) OutDepth() int { return l.numInputs } func (l *SVMLayer) OutSx() int { return 1 } func (l *SVMLayer) OutSy() int { return 1 } func (l *SVMLayer) fromDef(def LayerDef, r *rand.Rand) { // computed l.numInputs = def.InSx * def.InSy * def.InDepth } func (l *SVMLayer) Forward(v *Vol, isTraining bool) *Vol { l.act = v // nothing to do, output raw scores return v } func (l *SVMLayer) Backward() {} func (l *SVMLayer) BackwardLoss(y LossData) float64 { // compute and accumulate gradient wrt weights and bias of this layer x := l.act x.Dw = make([]float64, len(x.W)) // zero out the gradient of input Vol // we're using structured loss here, which means that the score // of the ground truth should be higher than the score of any other // class, by a margin yscore := x.W[y.Dim] // score of ground truth margin := 1.0 loss := 0.0 for i := 0; i < l.numInputs; i++ { if y.Dim == i { continue } ydiff := -yscore + x.W[i] + margin if ydiff > 0 { // violating dimension, apply loss x.Dw[i] += 1 x.Dw[y.Dim] -= 1 loss += ydiff } } return loss } func (l *SVMLayer) ParamsAndGrads() []ParamsAndGrads { return nil } func (l *SVMLayer) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { OutDepth int `json:"out_depth"` OutSx int `json:"out_sx"` OutSy int `json:"out_sy"` LayerType string `json:"layer_type"` NumInputs int `json:"num_inputs"` }{ OutDepth: l.numInputs, OutSx: 1, OutSy: 1, LayerType: LayerSVM.String(), NumInputs: l.numInputs, }) } func (l *SVMLayer) UnmarshalJSON(b []byte) error { var data struct { OutDepth int `json:"out_depth"` OutSx int `json:"out_sx"` OutSy int `json:"out_sy"` LayerType string `json:"layer_type"` NumInputs int `json:"num_inputs"` } if err := json.Unmarshal(b, &data); err != nil { return err } l.numInputs = data.NumInputs return nil }
layers-loss.go
0.738763
0.469824
layers-loss.go
starcoder
package v1alpha1 import ( internalinterfaces "kubeform.dev/provider-google-api/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // DataTransferConfigs returns a DataTransferConfigInformer. DataTransferConfigs() DataTransferConfigInformer // Datasets returns a DatasetInformer. Datasets() DatasetInformer // DatasetAccesses returns a DatasetAccessInformer. DatasetAccesses() DatasetAccessInformer // DatasetIamBindings returns a DatasetIamBindingInformer. DatasetIamBindings() DatasetIamBindingInformer // DatasetIamMembers returns a DatasetIamMemberInformer. DatasetIamMembers() DatasetIamMemberInformer // DatasetIamPolicies returns a DatasetIamPolicyInformer. DatasetIamPolicies() DatasetIamPolicyInformer // Jobs returns a JobInformer. Jobs() JobInformer // Reservations returns a ReservationInformer. Reservations() ReservationInformer // Routines returns a RoutineInformer. Routines() RoutineInformer // Tables returns a TableInformer. Tables() TableInformer // TableIamBindings returns a TableIamBindingInformer. TableIamBindings() TableIamBindingInformer // TableIamMembers returns a TableIamMemberInformer. TableIamMembers() TableIamMemberInformer // TableIamPolicies returns a TableIamPolicyInformer. TableIamPolicies() TableIamPolicyInformer } type version struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // DataTransferConfigs returns a DataTransferConfigInformer. func (v *version) DataTransferConfigs() DataTransferConfigInformer { return &dataTransferConfigInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Datasets returns a DatasetInformer. func (v *version) Datasets() DatasetInformer { return &datasetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // DatasetAccesses returns a DatasetAccessInformer. func (v *version) DatasetAccesses() DatasetAccessInformer { return &datasetAccessInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // DatasetIamBindings returns a DatasetIamBindingInformer. func (v *version) DatasetIamBindings() DatasetIamBindingInformer { return &datasetIamBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // DatasetIamMembers returns a DatasetIamMemberInformer. func (v *version) DatasetIamMembers() DatasetIamMemberInformer { return &datasetIamMemberInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // DatasetIamPolicies returns a DatasetIamPolicyInformer. func (v *version) DatasetIamPolicies() DatasetIamPolicyInformer { return &datasetIamPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Jobs returns a JobInformer. func (v *version) Jobs() JobInformer { return &jobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Reservations returns a ReservationInformer. func (v *version) Reservations() ReservationInformer { return &reservationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Routines returns a RoutineInformer. func (v *version) Routines() RoutineInformer { return &routineInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Tables returns a TableInformer. func (v *version) Tables() TableInformer { return &tableInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // TableIamBindings returns a TableIamBindingInformer. func (v *version) TableIamBindings() TableIamBindingInformer { return &tableIamBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // TableIamMembers returns a TableIamMemberInformer. func (v *version) TableIamMembers() TableIamMemberInformer { return &tableIamMemberInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // TableIamPolicies returns a TableIamPolicyInformer. func (v *version) TableIamPolicies() TableIamPolicyInformer { return &tableIamPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
client/informers/externalversions/bigquery/v1alpha1/interface.go
0.796015
0.433802
interface.go
starcoder
package httpsrv import ( "html/template" "reflect" "strings" "time" ) var TemplateFuncs = map[string]interface{}{ "eq": tfEqual, // Skips sanitation on the parameter. Do not use with dynamic data. "raw": func(text string) template.HTML { return template.HTML(text) }, // Returns a copy of the string s with the old replaced by new "replace": func(s, old, new string) string { return strings.Replace(s, old, new, -1) }, // Format a date according to the application's default date(time) format. "date": func(t time.Time) string { return t.Format("2006-01-02") }, "datetime": func(t time.Time) string { //t, _ := time.Parse("2006-01-02 15:04:05.000 -0700", fmttime) return t.Format("2006-01-02 15:04") }, // upper returns a copy of the string s with all Unicode letters mapped to their upper case "upper": func(s string) string { return strings.ToUpper(s) }, // lower returns a copy of the string s with all Unicode letters mapped to their lower case "lower": func(s string) string { return strings.ToLower(s) }, // Perform a message look-up for the given locale and message using the given arguments "T": func(lang map[string]interface{}, msg string, args ...interface{}) string { return i18nTranslate(lang["LANG"].(string), msg, args...) }, // "set": func(renderArgs map[string]interface{}, key string, value interface{}) { // renderArgs[key] = value // }, } // Equal is a helper for comparing value equality, following these rules: // - Values with equivalent types are compared with reflect.DeepEqual // - int, uint, and float values are compared without regard to the type width. // for example, Equal(int32(5), int64(5)) == true // - strings and byte slices are converted to strings before comparison. // - else, return false. func tfEqual(a, b interface{}) bool { if reflect.TypeOf(a) == reflect.TypeOf(b) { return reflect.DeepEqual(a, b) } switch a.(type) { case int, int8, int16, int32, int64: switch b.(type) { case int, int8, int16, int32, int64: return reflect.ValueOf(a).Int() == reflect.ValueOf(b).Int() } case uint, uint8, uint16, uint32, uint64: switch b.(type) { case uint, uint8, uint16, uint32, uint64: return reflect.ValueOf(a).Uint() == reflect.ValueOf(b).Uint() } case float32, float64: switch b.(type) { case float32, float64: return reflect.ValueOf(a).Float() == reflect.ValueOf(b).Float() } case string: switch b.(type) { case []byte: return a.(string) == string(b.([]byte)) } case []byte: switch b.(type) { case string: return b.(string) == string(a.([]byte)) } } return false } // NotEqual evaluates the comparison a != b func tfNotEqual(a, b interface{}) bool { return !tfEqual(a, b) } // LessThan evaluates the comparison a < b func tfLessThan(a, b interface{}) bool { switch a.(type) { case int, int8, int16, int32, int64: switch b.(type) { case int, int8, int16, int32, int64: return reflect.ValueOf(a).Int() < reflect.ValueOf(b).Int() } case uint, uint8, uint16, uint32, uint64: switch b.(type) { case uint, uint8, uint16, uint32, uint64: return reflect.ValueOf(a).Uint() < reflect.ValueOf(b).Uint() } case float32, float64: switch b.(type) { case float32, float64: return reflect.ValueOf(a).Float() < reflect.ValueOf(b).Float() } } return false } // LessEqual evaluates the comparison a <= b func tfLessEqual(a, b interface{}) bool { return tfLessThan(a, b) || tfEqual(a, b) } // GreaterThan evaluates the comparison a > b func tfGreaterThan(a, b interface{}) bool { return !tfLessEqual(a, b) } // GreaterEqual evaluates the comparison a >= b func tfGreaterEqual(a, b interface{}) bool { return !tfLessThan(a, b) }
vendor/github.com/hooto/httpsrv/template-func.go
0.738669
0.447219
template-func.go
starcoder
package nred // FieldType defines the possible field types in nred definitions. type FieldType int const ( // ConstField identifies a field with a name and a constant value. ConstField FieldType = iota // GenericField identifies a field with a name and any arbitrary value as receieved from the backend // (or an underlying definition or rule). GenericField // OpaqueNumberField identifies a field with a numeric value that is not parsed by Netreduce, and it // can be float, decimal or integer, and of arbitrary size. OpaqueNumberField // IntField identifies a field with an integer value, whose size depends on the compiler architecture. // Probably 64 bit. IntField // FloatField identifies a field with a 64 bit floating point numeric value. FloatField // StringField identifies a field with a string value. StringField // BoolField identifies a field with a value of either true or false. BoolField // ContainsField identifies a field in a definition that contains another definition. ContainsField ) var fieldStrings = []string{ "const", "generic", "number", "int", "float", "string", "bool", "contains", } // OpaqueNumber represents an unparsed numeric value, either int, float or decimal, and of any arbitrary size. type OpaqueNumber string // Field represents a field in a definition. type Field struct { typ FieldType name string value interface{} } // RuleSpec represents a rule in a definition or a query. E.g. the URL of a simple http GET query. type RuleSpec struct { name string args []interface{} } // QuerySpec represents a query for backend data. Its actual behavior depends on the contained rules. type QuerySpec struct { rules []RuleSpec } // Definition describes a Netreduce request handler. Definitions may contain further Definitions. A definition // can have a single scalar value or a set of fields. The value or the fields are populated from the responses // of the contained queries, typically responses from requests made to backend services. The value or the fields // can be altered, or even generated, by the contained rules. type Definition struct { name string value interface{} queries []QuerySpec fields []Field rules []RuleSpec } // NilValue represents the 'null' data. E.g. the JSON null value. var NilValue = &struct{}{} // String returns the string name associated with the FieldTyep. It's also used as the field declaration in the // nred DSL. func (l FieldType) String() string { return enumString(int(l), fieldStrings) } // Const declares a const field. func Const(name string, value interface{}) Field { return Field{ typ: ConstField, name: name, value: value, } } // Generic declares a generic field whose value type is depends on the response of the used query. func Generic(name string) Field { return Field{ typ: GenericField, name: name, } } // Number declares an opaque number field. func Number(name string) Field { return Field{ typ: OpaqueNumberField, name: name, } } // Int declares an int field. func Int(name string) Field { return Field{ typ: IntField, name: name, } } // Float declares a floating point field. func Float(name string) Field { return Field{ typ: FloatField, name: name, } } // String declares a string field. func String(name string) Field { return Field{ typ: StringField, name: name, } } // Contains declares a field that contains a child definition. func Contains(name string, d Definition) Field { return Field{ typ: ContainsField, name: name, value: d, } } // Rule declares a rule either for a query or a definition. func Rule(name string, args ...interface{}) RuleSpec { return RuleSpec{ name: name, args: args, } } // Query declares a query for a definition. func Query(r ...RuleSpec) QuerySpec { return QuerySpec{ rules: r, } } // Define declares a Netreduce definition. The arguments may be of the type QuerySpec, Field, RuleSpec, // Definition, or any arbitrary value. When an argument is a query, it will be used to propagate the fields of // the definition, or if no fields were defined, the result of the query will be used as received. Fields // describe the shape of the data returned by a definition, and filter the response received from the queries. // Rules apply changes to the data and fields returned by the definition. Definition arguments are merged into // the new definition forming a union. Values passed in as arguments to a new definition define the response of // a definition alone. Only the last value is considered as the value of the definition and the rest is ignored. // It is undefined what a definition will return when both a value or a combination of fields and queries are // defined. Netreduce will do best effort to serialize those values in the response that are not plain data // objects. func Define(a ...interface{}) Definition { var d Definition for i := range a { switch at := a[i].(type) { case QuerySpec: d.queries = append(d.queries, at) case Field: d.fields = append(d.fields, at) case RuleSpec: d.rules = append(d.rules, at) case Definition: d.queries = append(d.queries, at.queries...) d.fields = append(d.fields, at.fields...) d.rules = append(d.rules, at.rules...) if at.value != nil { d.value = at.value } default: d.value = a[i] } } return d } // Export declares a standalone exported (not contained or shared) definition. Only exported definitions can // represent a Netreduce endpoint. func Export(name string, d Definition) Definition { d.name = name return d } // Name returns the exported name of a definition. func (d Definition) Name() string { return d.name }
nred/nred.go
0.829077
0.637793
nred.go
starcoder
Schob is a client for "shovey", a mechanism for pushing jobs to client nodes. Currently it's specific to goiardi, but a more general implementation is planned. Dependencies Running schob requires a goiardi server (both to send jobs to the schob client, and for the schob client to send reports to) and serf running with the goiardi server and on every client node that will run shovey jobs. The `knife-shove` plugin from https://github.com/ctdk/knife-shove is required to submit and administer shovey jobs. Schob has the following golang dependencies outside of the standard library: go-flags, toml, logger, the go-chef chef library, serf, go-uuid, and the chefcrypto library from goiardi (only for tests). The easiest way to install these dependencies is to include the `-t` flag when using `go get` to install schob. Installation The easiest way to install schob is with the shovey-jobs cookbook, located at https://github.com/ctdk/shovey-jobs. At the moment it only supports Debian, though, so for now installing on non-Debian platforms will have to install schob by hand. If you already have a binary you can skip to number 2. 0. Set up go and configure go. (http://golang.org/doc/install.html) 1. Download schob and its dependencies. go get -t github.com/ctdk/schob 2. Install the schob binary. go install github.com/ctdk/schob Alternately, if you downloaded a precompiled binary, put that binary somewhere in your PATH. 3. Make sure goiardi is running on its server, along with serf, and that it's configured to use serf and shovey. You will also need to make the RSA public/private key pair for signing and verifying shovey jobs. 4. Start up serf on the node, making sure that it joins the same serf cluster goairdi's serf is running in. 5. Make sure the shovey signing public RSA key is installed on the node. 6. Create a whitelist.json file for the node, with whitelisted jobs that are allowed to run on the node. See the example whitelist.json file in `test/whitelist.json` for guidance. 7. Run schob. Schob can take a configuration file (an example is provided in `test/schob-example.conf`, or it can use the following command line options: -v, --version Print version info. -V, --verbose Show verbose debug information. Repeat for more verbosity. -c, --config= Specify a configuration file. -L, --log-file= Log to this file. -s, --syslog Use syslog for logging. Incompatible with -L/--log-file. -e, --endpoint= Server endpoint -n, --node-name= This node's name -k, --key-file= Path to node client private key -m, --time-slew= Time difference allowed between the node's clock and the time sent in the serf command from the server. Formatted like 5m, 150s, etc. Defaults to 15m. -w, --whitelist= Path to JSON file containing whitelisted commands -t, --run-timeout= The time, in minutes, to wait before stopping a job. Separate from the timeout set from the server, this is a fallback. Defaults to 45 minutes. -p, --sign-pub-key= Path to public key used to verify signed requests from the server. --serf-addr= IP anddress and port to use for RPC communication with the serf agent. Defaults to 127.0.0.1:7373. -q, --queue-save-file= File to save running job status to recover jobs that didn't finish if schob is suddenly shut down without a chance to clean up. Options specified on the command line override options in the config file. A typical command line invocation of schob looks like `schob -VVVV -e http://chef-server.local:4545 -n node-name.local -k /path/to/node.key -w /path/to/schob/test/whitelist.json -p /path/to/public.key --serf-addr=127.0.0.1:7373`. Usage Once schob is running on a node, run jobs on it with the `knife-shove` plugin. The full documentation for that can be found at https://github.com/ctdk/knife-shove, but here's a cheat sheet: * To start a job: knife goiardi start <command> node1, node2,... * To start a job on all nodes in the webapp role, where 90% of the nodes must be up: knife goiardi job start -quorum 90% 'chef-client' --search 'role:webapp' * To see a job's status: knife goiardi job status <job id> * To get detailed information on a job on one node: knife goiardi job info <job id> <node name> * To stream a running job: knife goiardi job stream <job id> <node name> * To cancel a job: knife goiardi job cancel <job id> <node name> * To get a node's status: knife goiardi node status Contributing 1. Fork the repository on Github 2. Create a named feature branch (like `add_component_x`) 3. Write your change 4. Write tests for your change (if applicable) 5. Run the tests, ensuring they all pass 6. Submit a Pull Request using Github See Also * goiardi (https://github.com/ctdk/goiardi) * knife-shove (https://github.com/ctdk/knife-shove) * shovey-jobs cookbook (https://github.com/ctdk/shovey-jobs) * Goiardi's shovey documentation (https://github.com/ctdk/goiardi/blob/serfing/README.md#shovey) * Shovey API documentation (https://github.com/ctdk/goiardi/blob/serfing/shovey_api.md) Author <NAME> (<<EMAIL>>) Copyright Copyright 2014, <NAME> License Schob is licensed under the Apache 2.0 License. See the LICENSE file for details. "Schob" is German for "shoved". */ package main
doc.go
0.652795
0.597021
doc.go
starcoder
package util import ( "encoding/json" "fmt" "reflect" "strconv" "strings" ) func ToBool(v interface{}) bool { switch val := v.(type) { case bool: return val case float32, float64: // direct type conversion may cause data loss, use reflection instead return reflect.ValueOf(v).Float() != 0 case int, int8, int16, int32, int64: return reflect.ValueOf(v).Int() != 0 case uint, uint8, uint16, uint32, uint64: return reflect.ValueOf(v).Uint() != 0 case string: return str2bool(val) case []byte: return str2bool(string(val)) case nil: return false default: rv := reflect.ValueOf(v) if rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface { rv = rv.Elem() } // none empty array/slice/map convert to true, otherwise false if rv.Kind() == reflect.Array || rv.Kind() == reflect.Slice || rv.Kind() == reflect.Map { return rv.Len() != 0 } // valid value convert to true, otherwise false return rv.IsValid() } } func ToInt(v interface{}) int { switch val := v.(type) { case bool: if val { return 1 } else { return 0 } case float32, float64: // direct type conversion may cause data loss, use reflection instead return int(reflect.ValueOf(v).Float()) case int, int8, int16, int32, int64: return int(reflect.ValueOf(v).Int()) case uint, uint8, uint16, uint32, uint64: return int(reflect.ValueOf(v).Uint()) case string: return str2int(val) case []byte: return str2int(string(val)) case nil: return 0 default: panic(fmt.Sprintf("ToInt: invalid type: %T", v)) } } func ToInt64(v interface{}) int64 { switch val := v.(type) { case bool: if val { return 1 } else { return 0 } case float32, float64: // direct type conversion may cause data loss, use reflection instead return int64(reflect.ValueOf(v).Float()) case int, int8, int16, int32, int64: return int64(reflect.ValueOf(v).Int()) case uint, uint8, uint16, uint32, uint64: return int64(reflect.ValueOf(v).Uint()) case string: return str2int64(val) case []byte: return str2int64(string(val)) case nil: return 0 default: panic(fmt.Sprintf("ToInt: invalid type: %T", v)) } } func ToFloat(v interface{}) float64 { switch val := v.(type) { case bool: if val { return 1 } else { return 0 } case float32, float64: // direct type conversion may cause data loss, use reflection instead return reflect.ValueOf(v).Float() case int, int8, int16, int32, int64: return float64(reflect.ValueOf(v).Int()) case uint, uint8, uint16, uint32, uint64: return float64(reflect.ValueOf(v).Uint()) case string: return str2float(val) case []byte: return str2float(string(val)) case nil: return 0 default: panic(fmt.Sprintf("ToFloat: invalid type: %T", v)) } } func ToString(v interface{}) string { switch val := v.(type) { case bool: return strconv.FormatBool(val) case int, int8, int16, int32, int64: return strconv.FormatInt(reflect.ValueOf(v).Int(), 10) case uint, uint8, uint16, uint32, uint64: return strconv.FormatUint(reflect.ValueOf(v).Uint(), 10) case float32, float64: return strconv.FormatFloat(reflect.ValueOf(v).Float(), 'f', -1, 64) case []byte: return string(val) case string: return val case error: return val.Error() case fmt.Stringer: return val.String() default: // convert to json encoded string if j, e := json.Marshal(v); e == nil { return string(j) } // convert to default print string return fmt.Sprintf("%+v", v) } } func str2bool(s string) bool { s = strings.TrimSpace(s) if b, e := strconv.ParseBool(s); e == nil { return b } return len(s) != 0 } func str2int(s string) int { s = strings.TrimSpace(s) if i64, e := strconv.ParseInt(s, 0, 0); e == nil { // convert int string(decimal, hexadecimal, octal) return int(i64) } else if f64, e := strconv.ParseFloat(s, 64); e == nil { // convert float string return int(f64) } else { return 0 } } func str2int64(s string) int64 { s = strings.TrimSpace(s) if i64, e := strconv.ParseInt(s, 0, 0); e == nil { // convert int string(decimal, hexadecimal, octal) return i64 } else if f64, e := strconv.ParseFloat(s, 64); e == nil { // convert float string return int64(f64) } else { return 0 } } func str2float(s string) float64 { s = strings.TrimSpace(s) if f64, e := strconv.ParseFloat(s, 64); e == nil { // convert float string return f64 } else if i64, e := strconv.ParseInt(s, 0, 0); e == nil { // convert int string(decimal, hexadecimal, octal) return float64(i64) } else { return 0 } }
util/conv.go
0.539226
0.419588
conv.go
starcoder
package keyseq type TernaryTrie struct { root TernaryNode } func NewTernaryTrie() *TernaryTrie { return &TernaryTrie{} } func (t *TernaryTrie) Root() Node { return &t.root } func (t *TernaryTrie) GetList(k KeyList) Node { return Get(t, k) } func (t *TernaryTrie) Get(k Key) Node { return Get(t, KeyList{k}) } func (t *TernaryTrie) Put(k KeyList, v interface{}) Node { return Put(t, k, v) } func (t *TernaryTrie) Size() int { count := 0 EachDepth(t, func(Node) bool { count++ return true }) return count } func (t *TernaryTrie) Balance() { EachDepth(t, func(n Node) bool { n.(*TernaryNode).Balance() return true }) t.root.Balance() } type TernaryNode struct { label Key firstChild *TernaryNode low, high *TernaryNode value interface{} } func NewTernaryNode(l Key) *TernaryNode { return &TernaryNode{label: l} } func (n *TernaryNode) GetList(k KeyList) Node { return n.Get(k[0]) } func (n *TernaryNode) Get(k Key) Node { curr := n.firstChild for curr != nil { switch k.Compare(curr.label) { case 0: // equal return curr case -1: // less curr = curr.low default: //more curr = curr.high } } return nil } func (n *TernaryNode) Dig(k Key) (node Node, isnew bool) { curr := n.firstChild if curr == nil { n.firstChild = NewTernaryNode(k) return n.firstChild, true } for { switch k.Compare(curr.label) { case 0: return curr, false case -1: if curr.low == nil { curr.low = NewTernaryNode(k) return curr.low, true } curr = curr.low default: if curr.high == nil { curr.high = NewTernaryNode(k) return curr.high, true } curr = curr.high } } } func (n *TernaryNode) FirstChild() *TernaryNode { return n.firstChild } func (n *TernaryNode) HasChildren() bool { return n.firstChild != nil } func (n *TernaryNode) Size() int { if n.firstChild == nil { return 0 } count := 0 n.Each(func(Node) bool { count++ return true }) return count } func (n *TernaryNode) Each(proc func(Node) bool) { var f func(*TernaryNode) bool f = func(n *TernaryNode) bool { if n != nil { if !f(n.low) || !proc(n) || !f(n.high) { return false } } return true } f(n.firstChild) } func (n *TernaryNode) RemoveAll() { n.firstChild = nil } func (n *TernaryNode) Label() Key { return n.label } func (n *TernaryNode) Value() interface{} { return n.value } func (n *TernaryNode) SetValue(v interface{}) { n.value = v } func (n *TernaryNode) children() []*TernaryNode { children := make([]*TernaryNode, n.Size()) if n.firstChild == nil { return children } idx := 0 n.Each(func(child Node) bool { children[idx] = child.(*TernaryNode) idx++ return true }) return children } func (n *TernaryNode) Balance() { if n.firstChild == nil { return } children := n.children() for _, child := range children { child.low = nil child.high = nil } n.firstChild = balance(children, 0, len(children)) } func balance(nodes []*TernaryNode, s, e int) *TernaryNode { count := e - s if count <= 0 { return nil } else if count == 1 { return nodes[s] } else if count == 2 { nodes[s].high = nodes[s+1] return nodes[s] } else { mid := (s + e) / 2 n := nodes[mid] n.low = balance(nodes, s, mid) n.high = balance(nodes, mid+1, e) return n } }
internal/keyseq/ternary.go
0.598195
0.522019
ternary.go
starcoder
package bitset // Bits is a lightweight bitset implementation based on a uint64 number, // it's not safety for concurrent. type Bits uint64 func NewBits() *Bits { var s Bits return &s } // BitsList create a Bits, set all bits in list to 1 func BitsList(bits ...uint) *Bits { var s uint64 for _, b := range bits { s |= uint64(1 << b) } return ((*Bits)(&s)) } // BitsFrom create a Bits, all bits of number is copied func BitsFrom(b uint) *Bits { var s Bits = Bits(b) return &s } // Set bit at given index to 1 func (s *Bits) Set(index uint) { *s |= 1 << index } // SetAll set all bits to 1 func (s *Bits) SetAll() { *s = 1<<64 - 1 } // Unset set bit at given index to 0 func (s *Bits) Unset(index uint) { *s &= ^(1 << index) } // UnsetAll set all bits to 0 func (s *Bits) UnsetAll() { *s = 0 } // IsSet chech whether bit at given index is set to 1 func (s *Bits) IsSet(index uint) bool { return *s&(1<<index) != 0 } // SetTo set bit at given index to 1 if val is true, else set to 0 func (s *Bits) SetTo(index uint, val bool) { if val { s.Set(index) } else { s.Unset(index) } } // Flip bit at given index func (s *Bits) Flip(index uint) { *s ^= (1 << index) } // FlipAll flip all bits func (s *Bits) FlipAll() { *s = ^(*s) } // SetBefore set all bits before index to 1, index bit is not included func (s *Bits) SetBefore(index uint) { *s |= (1<<index - 1) } // SetSince set all bits since index to 1, index bit is include func (s *Bits) SetSince(index uint) { *s |= ^(1<<index - 1) } // UnsetBefore set all bits before index to 0, index bit is not included func (s *Bits) UnsetBefore(index uint) { *s &= ^(1<<index - 1) } // UnsetSince set all bits since index to 0, index bit is include func (s *Bits) UnsetSince(index uint) { *s &= (1<<index - 1) } // Uint return uint display of Bits func (s *Bits) Uint() uint { return uint(*s) } // Uint64 return uint64 display of Bits func (s *Bits) Uint64() uint64 { return uint64(*s) } // BitCount return the count of bits set to 1 func (s *Bits) BitCount() int { return BitCount(uint64(*s)) } // BitCount return count of 1 bit in uint64 func BitCount(n uint64) int { n -= (n >> 1) & 0x5555555555555555 n = (n>>2)&0x3333333333333333 + n&0x3333333333333333 n += n >> 4 n &= 0x0f0f0f0f0f0f0f0f n *= 0x0101010101010101 return int(n >> 56) } // BitCountUint return count of 1 bit in uint func BitCountUint(x uint) int { var n = uint64(x) n -= (n >> 1) & 0x5555555555555555 n = (n>>2)&0x3333333333333333 + n&0x3333333333333333 n += n >> 4 n &= 0x0f0f0f0f0f0f0f0f n *= 0x0101010101010101 return int(n >> 56) }
ds/bitset/bits.go
0.704058
0.431285
bits.go
starcoder
package document import ( "baliance.com/gooxml/color" "baliance.com/gooxml/measurement" "baliance.com/gooxml/schema/soo/wml" ) // CellBorders are the borders for an individual type CellBorders struct { x *wml.CT_TcBorders } // X returns the inner wrapped type func (b CellBorders) X() *wml.CT_TcBorders { return b.x } // SetAll sets all of the borders to a given value. func (b CellBorders) SetAll(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.SetBottom(t, c, thickness) b.SetLeft(t, c, thickness) b.SetRight(t, c, thickness) b.SetTop(t, c, thickness) b.SetInsideHorizontal(t, c, thickness) b.SetInsideVertical(t, c, thickness) } // SetBottom sets the bottom border to a specified type, color and thickness. func (b CellBorders) SetBottom(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.x.Bottom = wml.NewCT_Border() setBorder(b.x.Bottom, t, c, thickness) } // SetTop sets the top border to a specified type, color and thickness. func (b CellBorders) SetTop(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.x.Top = wml.NewCT_Border() setBorder(b.x.Top, t, c, thickness) } // SetLeft sets the left border to a specified type, color and thickness. func (b CellBorders) SetLeft(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.x.Left = wml.NewCT_Border() setBorder(b.x.Left, t, c, thickness) } // SetRight sets the right border to a specified type, color and thickness. func (b CellBorders) SetRight(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.x.Right = wml.NewCT_Border() setBorder(b.x.Right, t, c, thickness) } // SetInsideHorizontal sets the interior horizontal borders to a specified type, color and thickness. func (b CellBorders) SetInsideHorizontal(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.x.InsideH = wml.NewCT_Border() setBorder(b.x.InsideH, t, c, thickness) } // SetInsideVertical sets the interior vertical borders to a specified type, color and thickness. func (b CellBorders) SetInsideVertical(t wml.ST_Border, c color.Color, thickness measurement.Distance) { b.x.InsideV = wml.NewCT_Border() setBorder(b.x.InsideV, t, c, thickness) }
document/cellborders.go
0.807195
0.456591
cellborders.go
starcoder
package immutable import ( "github.com/pkg/errors" "github.com/chris-tomich/immutability-benchmarking" ) // Matrix is an immutable matrix with non-mutating operations. type Matrix struct { matrix [immutabilitybenchmarking.MatrixHeight][immutabilitybenchmarking.MatrixWidth]int } // New creates a new immutable matrix with the given initial values. func New(matrix [immutabilitybenchmarking.MatrixHeight][immutabilitybenchmarking.MatrixWidth]int) Matrix { return Matrix{matrix: matrix} } // NewEmpty createas a new empty matrix with the given dimensions. func NewEmpty(width int, height int) Matrix { if width == 0 || height == 0 { panic(errors.New("width and height must both be non-zero")) } m := Matrix{} return m } // Width returns the number of columns in the matrix. func (m1 Matrix) Width() int { return len(m1.matrix[0]) } // Height returns the number of rows in the matrix. func (m1 Matrix) Height() int { return len(m1.matrix) } // Get returns the integer at the provided coordinates. func (m1 Matrix) Get(row int, col int) int { return m1.matrix[row][col] } // Equals will compare a matrix against this matrix and return if they are equal. func (m1 Matrix) Equals(m2 immutabilitybenchmarking.Matrix) bool { if m1.Height() != m2.Height() { return false } if m1.Width() != m2.Width() { return false } for r := 0; r < m1.Height(); r++ { for c := 0; c < len(m1.matrix[r]); c++ { if m1.matrix[r][c] != m2.Get(r, c) { return false } } } return true } // Add will add the values of a matrix to this matrix. func (m1 Matrix) Add(m2 immutabilitybenchmarking.Matrix) (immutabilitybenchmarking.Matrix, error) { if m1.Height() != m2.Height() { return Matrix{}, errors.New("width of both matrices are not the same") } if m1.Width() != m2.Width() { return Matrix{}, errors.New("height of both matrices are not the same") } m := NewEmpty(m1.Height(), m1.Width()) for r := 0; r < m.Height(); r++ { for c := 0; c < len(m.matrix[r]); c++ { m.matrix[r][c] = m1.matrix[r][c] + m2.Get(r, c) } } return m, nil } // Subtract will subtract the values of a matrix from this matrix. func (m1 Matrix) Subtract(m2 immutabilitybenchmarking.Matrix) (immutabilitybenchmarking.Matrix, error) { if m1.Height() != m2.Height() { return Matrix{}, errors.New("width of both matrices are not the same") } if m1.Width() != m2.Width() { return Matrix{}, errors.New("height of both matrices are not the same") } m := NewEmpty(m1.Height(), m1.Width()) for r := 0; r < m.Height(); r++ { for c := 0; c < len(m.matrix[r]); c++ { m.matrix[r][c] = m1.matrix[r][c] - m2.Get(r, c) } } return m, nil } // ScalarMultiply will multiply this matrix by a given scalar value. func (m1 Matrix) ScalarMultiply(s int) immutabilitybenchmarking.Matrix { m := NewEmpty(m1.Height(), m1.Width()) for r := 0; r < m1.Height(); r++ { for c := 0; c < len(m1.matrix[r]); c++ { m.matrix[r][c] = m1.matrix[r][c] * s } } return m } // Transpose will transpose this matrix. func (m1 Matrix) Transpose() immutabilitybenchmarking.Matrix { m := NewEmpty(m1.Width(), m1.Height()) for rt := 0; rt < m.Height(); rt++ { for ct := 0; ct < m1.Height(); ct++ { m.matrix[rt][ct] = m1.matrix[ct][rt] } } return m } // MatrixMultiply will multiple the given matrix against this matrix. func (m1 Matrix) MatrixMultiply(m2 immutabilitybenchmarking.Matrix) (immutabilitybenchmarking.Matrix, error) { if m1.Width() != m2.Height() { return Matrix{}, errors.New("the dimensions of the matrices are incompatible, try transposing one first") } m := NewEmpty(m2.Width(), m1.Height()) for rm := 0; rm < m1.Height(); rm++ { for cm2 := 0; cm2 < m2.Width(); cm2++ { product := 0 for cm := 0; cm < len(m1.matrix[rm]); cm++ { product = product + m1.matrix[rm][cm]*m2.Get(cm, cm2) } m.matrix[rm][cm2] = product } } return m, nil }
array/immutable/matrix.go
0.900244
0.736756
matrix.go
starcoder
// hubbub provides an advanced in-memory search for GitHub using state machines package hubbub import ( "sync" "time" "github.com/google/triage-party/pkg/constants" "github.com/google/triage-party/pkg/persist" "github.com/google/triage-party/pkg/provider" "k8s.io/klog/v2" ) // Config is how to configure a new hubbub engine type Config struct { Cache persist.Cacher // Cacher is a cache interface Repos []string // Repos is the repositories to search // MinSimilarity is how close two items need to be to each other to be called similar MinSimilarity float64 // The furthest we will query back for information on closed issues MaxClosedUpdateAge time.Duration // DebugNumbers is used when you want to debug why a single item is being handled in a certain wait DebugNumbers map[int]bool // MemberRoles are which roles to consider as members // https://developer.github.com/v4/enum/commentauthorassociation/ MemberRoles []string // Members are which specific users to consider as members Members []string // Providers GitHub provider.Provider GitLab provider.Provider } // Engine is the search engine interface for hubbub type Engine struct { cache persist.Cacher // Must be settable from config MinSimilarity float64 // The furthest we will query back for information on closed issues MaxClosedUpdateAge time.Duration debug map[int]bool titleToURLs sync.Map similarTitles sync.Map memberRoles map[string]bool members map[string]bool // Data source providers github provider.Provider gitlab provider.Provider // Workaround because GitHub doesn't update issues if cross-references occur updatedAt map[string]time.Time // indexes used for similarity matching & conversation caching seen map[string]*Conversation } // ConversationsTotal returns the number of conversations we've seen so far func (e *Engine) ConversationsTotal() int { return len(e.seen) } func (e *Engine) provider(hostname string) provider.Provider { if hostname == constants.GitLabProviderHost { return e.gitlab } return e.github } func New(cfg Config) *Engine { e := &Engine{ cache: cfg.Cache, MaxClosedUpdateAge: cfg.MaxClosedUpdateAge, seen: map[string]*Conversation{}, MinSimilarity: cfg.MinSimilarity, debug: cfg.DebugNumbers, updatedAt: map[string]time.Time{}, memberRoles: map[string]bool{}, members: map[string]bool{}, github: cfg.GitHub, gitlab: cfg.GitLab, } klog.Infof("considering users as members: %v", cfg.Members) for _, user := range cfg.Members { e.members[user] = true } klog.Infof("considering roles as members: %v", cfg.MemberRoles) for _, role := range cfg.MemberRoles { e.memberRoles[role] = true } if len(e.members) == 0 && len(e.memberRoles) == 0 { e.memberRoles = map[string]bool{"collaborator": true, "member": true, "owner": true} klog.Warningf("No memberships defined, using default: %v", e.memberRoles) } // This value is typically programmed on the fly, but lets give it a good enough default if e.MaxClosedUpdateAge == 0 { e.MaxClosedUpdateAge = 24 * 3 * time.Hour } return e }
pkg/hubbub/hubbub.go
0.556159
0.411229
hubbub.go
starcoder
package main import ( "errors" "fmt" "github.com/go-gl/gl/v4.2-core/gl" "github.com/hexaflex/wireworldgpu/math" ) // SimulationState is an offscreen render target (framebuffer) which functions // as the simulation state and applies the simulation rules. type SimulationState struct { size math.Vec2 fbo uint32 rbo uint32 tex uint32 } // Init initializes the framebuffer with the given size. func (ss *SimulationState) Init(size math.Vec2) error { ss.size = size if size[0] < 1 || size[1] < 1 { return errors.New("framebuffer: invalid dimensions") } ss.Release() // Create framebuffer object. gl.GenFramebuffers(1, &ss.fbo) gl.BindFramebuffer(gl.FRAMEBUFFER, ss.fbo) // Create a texture object to store colour info. gl.GenTextures(1, &ss.tex) gl.BindTexture(gl.TEXTURE_2D, ss.tex) gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RED, int32(ss.size[0]), int32(ss.size[1]), 0, gl.RED, gl.UNSIGNED_BYTE, nil) gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, ss.tex, 0) // Create a render buffer object to store depth info. gl.GenRenderbuffers(1, &ss.rbo) gl.BindRenderbuffer(gl.RENDERBUFFER, ss.rbo) gl.RenderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT, int32(ss.size[0]), int32(ss.size[1])) gl.FramebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, ss.rbo) err := ss.checkStatus() gl.BindRenderbuffer(gl.RENDERBUFFER, 0) gl.BindTexture(gl.TEXTURE_2D, 0) gl.BindFramebuffer(gl.FRAMEBUFFER, 0) return err } // Release clears framebuffer resources. func (ss *SimulationState) Release() { gl.DeleteTextures(1, &ss.tex) gl.DeleteRenderbuffers(1, &ss.rbo) gl.DeleteFramebuffers(1, &ss.fbo) } // Size returns the framebuffer dimensions. func (ss *SimulationState) Size() math.Vec2 { return ss.size } // BindTexture sets the framebuffer texture as the active texture. // Call after rendering to the buffer is complete and you wish to // use the buffer contents as a sampler in another drawing operation. func (ss *SimulationState) BindTexture() { gl.BindTexture(gl.TEXTURE_2D, ss.tex) } // UnbindTexture unbinds the active texture. func (ss *SimulationState) UnbindTexture() { gl.BindTexture(gl.TEXTURE_2D, 0) } // BindBuffer sets the buffer as the active render target. func (ss *SimulationState) BindBuffer() { gl.BindFramebuffer(gl.FRAMEBUFFER, ss.fbo) } // UnbindBuffer unsets the buffer as the active render target. func (ss *SimulationState) UnbindBuffer() { gl.BindFramebuffer(gl.FRAMEBUFFER, 0) } // SetData writes the given state data into the framebuffer's color buffer. // Sets the framebuffer dimensions to the given size. func (ss *SimulationState) SetData(pix []byte, size math.Vec2) { ss.size = size gl.BindTexture(gl.TEXTURE_2D, ss.tex) gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1) gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RED, int32(ss.size[0]), int32(ss.size[1]), 0, gl.RED, gl.UNSIGNED_BYTE, gl.Ptr(pix)) gl.BindTexture(gl.TEXTURE_2D, 0) } // Data reads state state from the framebuffer's color buffer. // This uses glReadPixels and is therefore rather slow, so use with care. func (ss *SimulationState) Data() []byte { p := make([]byte, int32(ss.size[0])*int32(ss.size[1])) gl.BindFramebuffer(gl.READ_FRAMEBUFFER, ss.fbo) gl.ReadPixels(0, 0, int32(ss.size[0]), int32(ss.size[1]), gl.RED, gl.UNSIGNED_BYTE, gl.Ptr(p)) gl.BindFramebuffer(gl.READ_FRAMEBUFFER, 0) return p } func (ss *SimulationState) checkStatus() error { status := gl.CheckFramebufferStatus(gl.FRAMEBUFFER) switch status { case gl.FRAMEBUFFER_COMPLETE: case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return errors.New("framebuffer error: Attachment is not complete") case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return errors.New("framebuffer error: no image attachment") case gl.FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: return errors.New("framebuffer error: draw buffer error") case gl.FRAMEBUFFER_INCOMPLETE_READ_BUFFER: return errors.New("framebuffer error: read buffer error") case gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return errors.New("framebuffer error: incomplete multisample") case gl.FRAMEBUFFER_UNSUPPORTED: return errors.New("framebuffer error: FBO not supported") default: return fmt.Errorf("framebuffer error: unknown error %d", status) } return nil }
simulationstate.go
0.711832
0.47658
simulationstate.go
starcoder
package series import ( "fmt" "math" "strconv" ) type intElement struct { e int nan bool } func (e *intElement) Set(value interface{}) { e.nan = false switch value.(type) { case string: if value.(string) == "NaN" { e.nan = true return } i, err := strconv.Atoi(value.(string)) if err != nil { e.nan = true return } e.e = i case int: e.e = int(value.(int)) case float64: f := value.(float64) if math.IsNaN(f) || math.IsInf(f, 0) || math.IsInf(f, 1) { e.nan = true return } e.e = int(f) case bool: b := value.(bool) if b { e.e = 1 } else { e.e = 0 } case Element: v, err := value.(Element).Int() if err != nil { e.nan = true return } e.e = v default: e.nan = true return } return } func (e intElement) Copy() Element { if e.IsNA() { return &intElement{0, true} } return &intElement{e.e, false} } func (e intElement) IsNA() bool { if e.nan { return true } return false } func (e intElement) Type() Type { return Int } func (e intElement) Val() ElementValue { if e.IsNA() { return nil } return int(e.e) } func (e intElement) String() string { if e.IsNA() { return "NaN" } return fmt.Sprint(e.e) } func (e intElement) Int() (int, error) { if e.IsNA() { return 0, fmt.Errorf("can't convert NaN to int") } return int(e.e), nil } func (e intElement) Float() float64 { if e.IsNA() { return math.NaN() } return float64(e.e) } func (e intElement) Bool() (bool, error) { if e.IsNA() { return false, fmt.Errorf("can't convert NaN to bool") } switch e.e { case 1: return true, nil case 0: return false, nil } return false, fmt.Errorf("can't convert Int \"%v\" to bool", e.e) } func (e intElement) Eq(elem Element) bool { i, err := elem.Int() if err != nil || e.IsNA() { return false } return e.e == i } func (e intElement) Neq(elem Element) bool { i, err := elem.Int() if err != nil || e.IsNA() { return false } return e.e != i } func (e intElement) Less(elem Element) bool { i, err := elem.Int() if err != nil || e.IsNA() { return false } return e.e < i } func (e intElement) LessEq(elem Element) bool { i, err := elem.Int() if err != nil || e.IsNA() { return false } return e.e <= i } func (e intElement) Greater(elem Element) bool { i, err := elem.Int() if err != nil || e.IsNA() { return false } return e.e > i } func (e intElement) GreaterEq(elem Element) bool { i, err := elem.Int() if err != nil || e.IsNA() { return false } return e.e >= i }
vendor/github.com/kniren/gota/series/type-int.go
0.586404
0.440048
type-int.go
starcoder
package goglbackend import ( "image" "image/color" "unsafe" "github.com/tfriedel6/canvas/backend/goglbackend/gl" ) // GetImageData returns an RGBA image of the current image func (b *GoGLBackend) GetImageData(x, y, w, h int) *image.RGBA { b.activate() if x < 0 { w += x x = 0 } if y < 0 { h += y y = 0 } if w > b.w { w = b.w } if h > b.h { h = b.h } if len(b.imageBuf) < w*h*3 { b.imageBuf = make([]byte, w*h*3) } gl.ReadPixels(int32(x), int32(y), int32(w), int32(h), gl.RGB, gl.UNSIGNED_BYTE, gl.Ptr(&b.imageBuf[0])) rgba := image.NewRGBA(image.Rect(x, y, x+w, y+h)) bp := 0 for cy := y; cy < y+h; cy++ { for cx := x; cx < x+w; cx++ { rgba.SetRGBA(cx, y+h-1-cy, color.RGBA{R: b.imageBuf[bp], G: b.imageBuf[bp+1], B: b.imageBuf[bp+2], A: 255}) bp += 3 } } return rgba } // PutImageData puts the given image at the given x/y coordinates func (b *GoGLBackend) PutImageData(img *image.RGBA, x, y int) { b.activate() gl.ActiveTexture(gl.TEXTURE0) if b.imageBufTex == 0 { gl.GenTextures(1, &b.imageBufTex) gl.BindTexture(gl.TEXTURE_2D, b.imageBufTex) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) } else { gl.BindTexture(gl.TEXTURE_2D, b.imageBufTex) } w, h := img.Bounds().Dx(), img.Bounds().Dy() if img.Stride == img.Bounds().Dx()*4 { gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(w), int32(h), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(&img.Pix[0])) } else { data := make([]uint8, 0, w*h*4) for cy := 0; cy < h; cy++ { start := cy * img.Stride end := start + w*4 data = append(data, img.Pix[start:end]...) } gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(w), int32(h), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(&data[0])) } dx, dy := float32(x), float32(y) dw, dh := float32(w), float32(h) gl.BindBuffer(gl.ARRAY_BUFFER, b.buf) data := [16]float32{dx, dy, dx + dw, dy, dx + dw, dy + dh, dx, dy + dh, 0, 0, 1, 0, 1, 1, 0, 1} gl.BufferData(gl.ARRAY_BUFFER, len(data)*4, unsafe.Pointer(&data[0]), gl.STREAM_DRAW) gl.UseProgram(b.ir.ID) gl.Uniform1i(b.ir.Image, 0) gl.Uniform2f(b.ir.CanvasSize, float32(b.fw), float32(b.fh)) gl.Uniform1f(b.ir.GlobalAlpha, 1) gl.VertexAttribPointer(b.ir.Vertex, 2, gl.FLOAT, false, 0, nil) gl.VertexAttribPointer(b.ir.TexCoord, 2, gl.FLOAT, false, 0, gl.PtrOffset(8*4)) gl.EnableVertexAttribArray(b.ir.Vertex) gl.EnableVertexAttribArray(b.ir.TexCoord) gl.DrawArrays(gl.TRIANGLE_FAN, 0, 4) gl.DisableVertexAttribArray(b.ir.Vertex) gl.DisableVertexAttribArray(b.ir.TexCoord) }
backend/goglbackend/imagedata.go
0.656438
0.412708
imagedata.go
starcoder
package main import ( "fmt" "math" "strconv" "sync" ) func main() { /* Maps are a data structure that holds key-value pairs. Keys need to be unique, but the same value can be assigned to multiple keys. maps need to have a defined key type and value type - they can be different between the two, but need to be consistent internally. For example, a valid map could have integer keys and string values, but all keys must be integers and all values must be strings. Let's define that map below using make(): */ m := make(map[int]string) m[1] = "foo" m[2] = "bar" m[4] = "baz" // maps support the len() function to find the amount of items in them l := len(m) fmt.Printf("%s: %d\n", "m len", l) // access map values fmt.Println(m[1]) fmt.Println(m[2]) // won't print anything fmt.Println(m[3]) /* Goroutines are a pretty special Go implementation of concurrency and multithreading - however, goroutines do not use as many resources as an extra thread or process. Goroutines behave like functions (and in fact DO execute functions), but do it in concert with the main execution thread. The 'go' keyword signifies a goroutine, and the argument afterwards should be the function to start in the goroutine. Goroutines also allow for channels to be used. */ // use a WaitGroup to wait for all goroutines to finish executing var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) // this is an anonymous function - it's not declared globally and doesn't // have a calling name. It's simply used here as a quick function not // intended to be reused go func(val int) { // close WorkGroup for this routine when done defer wg.Done() fmt.Println("Hello " + strconv.Itoa(val)) }(i) } // wait here wg.Wait() fmt.Println("Hello 5") /* Channels are data flow agents that allow you to send and receive data. Channels can be assigned to a variable and send and receive data in multiple functions or routines simultaneously, allowing for a good use in distributed workloads and messaging queues. */ c := make(chan int) /* defer calls will execute when the function had ended execution - this is useful for things like open files, channels, etc that should be closed before the program ends. */ defer close(c) /* Arrow notation (<-) denotes if data is being inserted or taken out of the channel, depending on what side the arguments are on. c <- var : send var into channel c var <-c : receive from channel c and assign to var */ go square(c, 4) // Receive value from channel and assign to v v := <-c fmt.Println(v) } func square(c chan int, val int) { c <- int(math.Pow(float64(val), 2.0)) }
maps-channels-goroutines/mcg.go
0.524882
0.401746
mcg.go
starcoder
package html const ( bitRectTop = 1 << iota bitRectTopPercentage bitRectBottom bitRectBottomPercentage bitRectHeight bitRectHeightPercentage bitRectLeft bitRectLeftPercentage bitRectRight bitRectRightPercentage bitRectWidth bitRectWidthPercentage bitRectAll = bitRectTop | bitRectBottom | bitRectHeight | bitRectLeft | bitRectRight | bitRectWidth ) type Rect struct { Top int Bottom int Height int Left int Right int Width int flags uint16 } func (rect *Rect) SetTop(top int, unit Unit) *Rect { rect.Top = top rect.flags |= bitRectTop if unit == Percentage { rect.flags |= bitRectTopPercentage } else { rect.flags = rect.flags &^ bitRectTopPercentage } return rect } func (rect Rect) WithTop(top int, unit Unit) Rect { return *rect.SetTop(top, unit) } func (rect *Rect) SetBottom(bottom int, unit Unit) *Rect { rect.Bottom = bottom rect.flags |= bitRectBottom if unit == Percentage { rect.flags |= bitRectBottomPercentage } else { rect.flags = rect.flags &^ bitRectBottomPercentage } return rect } func (rect Rect) WithBottom(bottom int, unit Unit) Rect { return *rect.SetBottom(bottom, unit) } func (rect *Rect) SetHeight(height int, unit Unit) *Rect { rect.Height = height rect.flags |= bitRectHeight if unit == Percentage { rect.flags |= bitRectHeightPercentage } else { rect.flags = rect.flags &^ bitRectHeightPercentage } return rect } func (rect Rect) WithHeight(height int, unit Unit) Rect { return *rect.SetHeight(height, unit) } func (rect *Rect) SetLeft(left int, unit Unit) *Rect { rect.Left = left rect.flags |= bitRectLeft if unit == Percentage { rect.flags |= bitRectLeftPercentage } else { rect.flags = rect.flags &^ bitRectLeftPercentage } return rect } func (rect Rect) WithLeft(left int, unit Unit) Rect { return *rect.SetLeft(left, unit) } func (rect *Rect) SetRight(right int, unit Unit) *Rect { rect.Right = right rect.flags |= bitRectRight if unit == Percentage { rect.flags |= bitRectRightPercentage } else { rect.flags = rect.flags &^ bitRectRightPercentage } return rect } func (rect Rect) WithRight(right int, unit Unit) Rect { return *rect.SetRight(right, unit) } func (rect *Rect) SetWidth(width int, unit Unit) *Rect { rect.Width = width rect.flags |= bitRectWidth if unit == Percentage { rect.flags |= bitRectWidthPercentage } else { rect.flags = rect.flags &^ bitRectWidthPercentage } return rect } func (rect Rect) WithWidth(width int, unit Unit) Rect { return *rect.SetWidth(width, unit) } func (rect *Rect) HasAny() bool { return rect.flags&bitRectAll != 0 } func (rect *Rect) HasTop() bool { return rect.flags&bitRectTop == bitRectTop } func (rect *Rect) TopUnit() Unit { if rect.flags&bitRectTopPercentage == bitRectTopPercentage { return Percentage } return Pixel } func (rect *Rect) HasBottom() bool { return rect.flags&bitRectBottom == bitRectBottom } func (rect *Rect) BottomUnit() Unit { if rect.flags&bitRectBottomPercentage == bitRectBottomPercentage { return Percentage } return Pixel } func (rect *Rect) HasHeight() bool { return rect.flags&bitRectHeight == bitRectHeight } func (rect *Rect) HeightUnit() Unit { if rect.flags&bitRectHeightPercentage == bitRectHeightPercentage { return Percentage } return Pixel } func (rect *Rect) HasLeft() bool { return rect.flags&bitRectLeft == bitRectLeft } func (rect *Rect) LeftUnit() Unit { if rect.flags&bitRectLeftPercentage == bitRectLeftPercentage { return Percentage } return Pixel } func (rect *Rect) HasRight() bool { return rect.flags&bitRectRight == bitRectRight } func (rect *Rect) RightUnit() Unit { if rect.flags&bitRectRightPercentage == bitRectRightPercentage { return Percentage } return Pixel } func (rect *Rect) HasWidth() bool { return rect.flags&bitRectWidth == bitRectWidth } func (rect *Rect) WidthUnit() Unit { if rect.flags&bitRectWidthPercentage == bitRectWidthPercentage { return Percentage } return Pixel } func (rect *Rect) Impose(el *Element) { if el != nil { if rect.HasTop() { el.Style.Set("top", rect.TopUnit().Format(rect.Top)) } if rect.HasBottom() { el.Style.Set("bottom", rect.BottomUnit().Format(rect.Bottom)) } if rect.HasHeight() { el.Style.Set("height", rect.HeightUnit().Format(rect.Height)) } if rect.HasLeft() { el.Style.Set("left", rect.LeftUnit().Format(rect.Left)) } if rect.HasRight() { el.Style.Set("right", rect.RightUnit().Format(rect.Right)) } if rect.HasWidth() { el.Style.Set("width", rect.WidthUnit().Format(rect.Width)) } } }
html/rect.go
0.832441
0.610657
rect.go
starcoder
package simplifier import "github.com/twtiger/gosecco/tree" // AcceptComparison implements Visitor func (s *fullArgumentSplitterSimplifier) AcceptComparison(a tree.Comparison) { l := s.Transform(a.Left) r := s.Transform(a.Right) pral, okal := potentialExtractFullArgument(l) prnlLow, prnlHi, oknl := potentialExtractValueParts(l) prar, okar := potentialExtractFullArgument(r) prnrLow, prnrHi, oknr := potentialExtractValueParts(r) if okal && oknr { switch a.Op { case tree.EQL: s.Result = tree.And{ Left: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.NumericLiteral{prnrLow}}, Right: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.NumericLiteral{prnrHi}}, } case tree.BITSET: s.Result = tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.NumericLiteral{prnrLow}}, Right: tree.NumericLiteral{prnrLow}}, Right: tree.Comparison{Op: tree.EQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.NumericLiteral{prnrHi}}, Right: tree.NumericLiteral{prnrHi}}, } case tree.NEQL: s.Result = tree.Or{ Left: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.NumericLiteral{prnrLow}}, Right: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.NumericLiteral{prnrHi}}, } case tree.GT, tree.GTE: s.Result = tree.Or{ Left: tree.Comparison{Op: tree.GT, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.NumericLiteral{prnrHi}}, Right: tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.NumericLiteral{prnrHi}}, Right: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.NumericLiteral{prnrLow}}, }, } default: panic("shouldn't happen") } } else if okar && oknl { switch a.Op { case tree.EQL: s.Result = tree.And{ Left: tree.Comparison{Op: a.Op, Left: tree.NumericLiteral{prnlLow}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Comparison{Op: a.Op, Left: tree.NumericLiteral{prnlHi}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, } case tree.BITSET: s.Result = tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.NumericLiteral{prnlLow}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Comparison{Op: tree.EQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.NumericLiteral{prnlHi}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, } case tree.NEQL: s.Result = tree.Or{ Left: tree.Comparison{Op: a.Op, Left: tree.NumericLiteral{prnlLow}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Comparison{Op: a.Op, Left: tree.NumericLiteral{prnlHi}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, } case tree.GT, tree.GTE: s.Result = tree.Or{ Left: tree.Comparison{Op: tree.GT, Left: tree.NumericLiteral{prnlHi}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, Right: tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.NumericLiteral{prnlHi}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, Right: tree.Comparison{Op: a.Op, Left: tree.NumericLiteral{prnlLow}, Right: tree.Argument{Type: tree.Low, Index: prar}}, }, } default: panic("shouldn't happen") } } else if okal && okar { switch a.Op { case tree.EQL: s.Result = tree.And{ Left: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, } case tree.BITSET: s.Result = tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Comparison{Op: tree.EQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, } case tree.NEQL: s.Result = tree.Or{ Left: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.Argument{Type: tree.Low, Index: prar}}, Right: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, } case tree.GT, tree.GTE: s.Result = tree.Or{ Left: tree.Comparison{Op: tree.GT, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, Right: tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.Argument{Type: tree.Hi, Index: prar}}, Right: tree.Comparison{Op: a.Op, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: tree.Argument{Type: tree.Low, Index: prar}}, }, } default: panic("shouldn't happen") } } else if okal && a.Op == tree.BITSET { s.Result = tree.And{ Left: tree.Comparison{Op: tree.EQL, Left: tree.Argument{Type: tree.Hi, Index: pral}, Right: tree.NumericLiteral{0}}, Right: tree.Comparison{Op: tree.NEQL, Left: tree.Arithmetic{Op: tree.BINAND, Left: tree.Argument{Type: tree.Low, Index: pral}, Right: a.Right}, Right: tree.NumericLiteral{0}}, } } else { s.Result = tree.Comparison{Op: a.Op, Left: l, Right: r} } } // fullArgumentSplitterSimplifier simplifies full argument references in such a way that // after this has run, there will be no references to full arguments // this simplifier is expected to run after the inclusion simplifiers and the LT and LTE simplifiers // since it will not deal well with those situations // It can compare full arguments against each other // It can also deal well with arguments on one side and numbers on the other side // If the result on one side is the result of a calculation, this simplifier // will default to assume the wanted behavior is that the upper half of the other side is // all zeroes. Everything else is obvious. // It deals specifically with the cases for EQL, NEQL, GT, GTE and BITSET type fullArgumentSplitterSimplifier struct { tree.EmptyTransformer } func createFullArgumentSplitterSimplifier() tree.Transformer { s := &fullArgumentSplitterSimplifier{} s.RealSelf = s return s }
vendor/github.com/twtiger/gosecco/simplifier/full_argument_splitter_simplifier.go
0.648355
0.446736
full_argument_splitter_simplifier.go
starcoder
package settings import ( "encoding/json" "fmt" "testing" "github.com/ingrammicro/cio/api/types" "github.com/ingrammicro/cio/utils" "github.com/stretchr/testify/assert" ) // ListAssignmentsMocked test mocked function func ListAssignmentsMocked( t *testing.T, cloudAccountID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentsIn) assert.Nil(err, "PolicyAssignments test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathSettingsCloudAccountPolicyAssignments, cloudAccountID)).Return(dIn, 200, nil) policyAssignmentsOut, err := ds.ListAssignments(cloudAccountID) assert.Nil(err, "Error getting policy assignments") assert.Equal(policyAssignmentsIn, policyAssignmentsOut, "ListAssignments returned different policy assignments") return policyAssignmentsOut } // ListAssignmentsFailErrMocked test mocked function func ListAssignmentsFailErrMocked( t *testing.T, cloudAccountID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentsIn) assert.Nil(err, "PolicyAssignments test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathSettingsCloudAccountPolicyAssignments, cloudAccountID)). Return(dIn, 200, fmt.Errorf("mocked error")) policyAssignmentsOut, err := ds.ListAssignments(cloudAccountID) assert.NotNil(err, "We are expecting an error") assert.Nil(policyAssignmentsOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyAssignmentsOut } // ListAssignmentsFailStatusMocked test mocked function func ListAssignmentsFailStatusMocked( t *testing.T, cloudAccountID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentsIn) assert.Nil(err, "PolicyAssignments test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathSettingsCloudAccountPolicyAssignments, cloudAccountID)).Return(dIn, 499, nil) policyAssignmentsOut, err := ds.ListAssignments(cloudAccountID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyAssignmentsOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyAssignmentsOut } // ListAssignmentsFailJSONMocked test mocked function func ListAssignmentsFailJSONMocked( t *testing.T, cloudAccountID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathSettingsCloudAccountPolicyAssignments, cloudAccountID)).Return(dIn, 200, nil) policyAssignmentsOut, err := ds.ListAssignments(cloudAccountID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyAssignmentsOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyAssignmentsOut } // GetAssignmentMocked test mocked function func GetAssignmentMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 200, nil) policyAssignmentOut, err := ds.GetAssignment(policyAssignmentIn.ID) assert.Nil(err, "Error getting policy assignment") assert.Equal(*policyAssignmentIn, *policyAssignmentOut, "GetAssignment returned different policy assignment") return policyAssignmentOut } // GetAssignmentFailErrMocked test mocked function func GetAssignmentFailErrMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)). Return(dIn, 200, fmt.Errorf("mocked error")) policyAssignmentOut, err := ds.GetAssignment(policyAssignmentIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyAssignmentOut } // GetAssignmentFailStatusMocked test mocked function func GetAssignmentFailStatusMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 499, nil) policyAssignmentOut, err := ds.GetAssignment(policyAssignmentIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyAssignmentOut } // GetAssignmentFailJSONMocked test mocked function func GetAssignmentFailJSONMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 200, nil) policyAssignmentOut, err := ds.GetAssignment(policyAssignmentIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyAssignmentOut } // CreateAssignmentMocked test mocked function func CreateAssignmentMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // to json dOut, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathPolicyDefinitionAssignments, policyAssignmentIn.DefinitionID), mapIn). Return(dOut, 200, nil) policyAssignmentOut, err := ds.CreateAssignment(policyAssignmentIn.DefinitionID, mapIn) assert.Nil(err, "Error creating policy assignment") assert.Equal(policyAssignmentIn, policyAssignmentOut, "CreateAssignment returned different policy assignment") return policyAssignmentOut } // CreateAssignmentFailErrMocked test mocked function func CreateAssignmentFailErrMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // to json dOut, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathPolicyDefinitionAssignments, policyAssignmentIn.DefinitionID), mapIn). Return(dOut, 200, fmt.Errorf("mocked error")) policyAssignmentOut, err := ds.CreateAssignment(policyAssignmentIn.DefinitionID, mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyAssignmentOut } // CreateAssignmentFailStatusMocked test mocked function func CreateAssignmentFailStatusMocked( t *testing.T, policyAssignmentIn *types.PolicyAssignment, ) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // to json dOut, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathPolicyDefinitionAssignments, policyAssignmentIn.DefinitionID), mapIn). Return(dOut, 499, nil) policyAssignmentOut, err := ds.CreateAssignment(policyAssignmentIn.DefinitionID, mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyAssignmentOut } // CreateAssignmentFailJSONMocked test mocked function func CreateAssignmentFailJSONMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Post", fmt.Sprintf(APIPathPolicyDefinitionAssignments, policyAssignmentIn.DefinitionID), mapIn). Return(dIn, 200, nil) policyAssignmentOut, err := ds.CreateAssignment(policyAssignmentIn.DefinitionID, mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyAssignmentOut } // UpdateAssignmentMocked test mocked function func UpdateAssignmentMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID), mapIn).Return(dIn, 200, nil) policyAssignmentOut, err := ds.UpdateAssignment(policyAssignmentIn.ID, mapIn) assert.Nil(err, "Error updating assignment") assert.Equal(*policyAssignmentIn, *policyAssignmentOut, "UpdateAssignment returned different policy assignment") return policyAssignmentOut } // UpdateAssignmentFailErrMocked test mocked function func UpdateAssignmentFailErrMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID), mapIn). Return(dIn, 200, fmt.Errorf("mocked error")) policyAssignmentOut, err := ds.UpdateAssignment(policyAssignmentIn.ID, mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyAssignmentOut } // UpdateAssignmentFailStatusMocked test mocked function func UpdateAssignmentFailStatusMocked( t *testing.T, policyAssignmentIn *types.PolicyAssignment, ) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID), mapIn).Return(dIn, 499, nil) policyAssignmentOut, err := ds.UpdateAssignment(policyAssignmentIn.ID, mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyAssignmentOut } // UpdateAssignmentFailJSONMocked test mocked function func UpdateAssignmentFailJSONMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Put", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID), mapIn).Return(dIn, 200, nil) policyAssignmentOut, err := ds.UpdateAssignment(policyAssignmentIn.ID, mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyAssignmentOut } // DeleteAssignmentMocked test mocked function func DeleteAssignmentMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 200, nil) policyAssignmentOut, err := ds.DeleteAssignment(policyAssignmentIn.ID) assert.Nil(err, "Error deleting policy assignment") assert.Equal(policyAssignmentIn, policyAssignmentOut, "DeleteAssignment returned different assignment") } // DeleteAssignmentFailErrMocked test mocked function func DeleteAssignmentFailErrMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)). Return(dIn, 200, fmt.Errorf("mocked error")) policyAssignmentOut, err := ds.DeleteAssignment(policyAssignmentIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") } // DeleteAssignmentFailStatusMocked test mocked function func DeleteAssignmentFailStatusMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // to json dIn, err := json.Marshal(policyAssignmentIn) assert.Nil(err, "PolicyAssignment test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 499, nil) policyAssignmentOut, err := ds.DeleteAssignment(policyAssignmentIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") } // DeleteAssignmentFailJSONMocked test mocked function func DeleteAssignmentFailJSONMocked(t *testing.T, policyAssignmentIn *types.PolicyAssignment) *types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyAssignmentService(cs) assert.Nil(err, "Couldn't load policyAssignment service") assert.NotNil(ds, "PolicyAssignment service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyAssignment, policyAssignmentIn.ID)).Return(dIn, 200, nil) policyAssignmentOut, err := ds.DeleteAssignment(policyAssignmentIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyAssignmentOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyAssignmentOut }
api/settings/policy_assignments_api_mocked.go
0.686055
0.522994
policy_assignments_api_mocked.go
starcoder
package gocb // RemoveMt performs a Remove operation and includes MutationToken in the results. func (b *Bucket) RemoveMt(key string, cas Cas) (Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.remove(key, cas) } // UpsertMt performs a Upsert operation and includes MutationToken in the results. func (b *Bucket) UpsertMt(key string, value interface{}, expiry uint32) (Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.upsert(key, value, expiry) } // InsertMt performs a Insert operation and includes MutationToken in the results. func (b *Bucket) InsertMt(key string, value interface{}, expiry uint32) (Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.insert(key, value, expiry) } // ReplaceMt performs a Replace operation and includes MutationToken in the results. func (b *Bucket) ReplaceMt(key string, value interface{}, cas Cas, expiry uint32) (Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.replace(key, value, cas, expiry) } // AppendMt performs a Append operation and includes MutationToken in the results. func (b *Bucket) AppendMt(key, value string) (Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.append(key, value) } // PrependMt performs a Prepend operation and includes MutationToken in the results. func (b *Bucket) PrependMt(key, value string) (Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.prepend(key, value) } // CounterMt performs a Counter operation and includes MutationToken in the results. func (b *Bucket) CounterMt(key string, delta, initial int64, expiry uint32) (uint64, Cas, MutationToken, error) { if !b.mtEnabled { panic("You must use OpenBucketMt with Mt operation variants.") } return b.counter(key, delta, initial, expiry) }
bucket_token.go
0.78695
0.449936
bucket_token.go
starcoder
package bolt import ( "fmt" "math" ) // Bolt - base property of bolt type Bolt struct { bc Class bd Diameter } // New - create a new bolt func New(bd Diameter, bc Class) Bolt { return Bolt{bc: bc, bd: bd} } // Fyb - return Fyb stress. // unit: Pa func (b Bolt) Fyb() Fyb { return Fyb{BoltClass: b.bc} } // Fub - return Fub stress. // unit: Pa func (b Bolt) Fub() Fub { return Fub{BoltClass: b.bc} } // D - diameter of bolt. // unit: meter func (b Bolt) D() Diameter { return b.bd } // Do - diameter of bolt hole. // unit: meter func (b Bolt) Do() HoleDiameter { return HoleDiameter{Dia: b.bd} } // Cl - class of bolt func (b Bolt) Cl() Class { return b.bc } // As - area of As func (b Bolt) As() AreaAs { return AreaAs{Dia: b.bd} } // A - area of A func (b Bolt) A() AreaA { return AreaA{Dia: b.bd} } // Class is class of bolt type Class string // Typical names of bolt classes const ( G4p6 Class = "4.6" G4p8 Class = "4.8" G5p6 Class = "5.6" G5p8 Class = "5.8" G6p8 Class = "6.8" G8p8 Class = "8.8" G10p9 Class = "10.9" ) // GetBoltClassList - list of all allowable bolt classes func GetBoltClassList() []Class { return []Class{G4p6, G4p8, G5p6, G5p8, G6p8, G8p8, G10p9} } func (bc Class) String() string { return fmt.Sprintf("Cl%s", string(bc)) } // Diameter is diameter of bolt // unit: meter type Diameter float64 // Typical bolt diameters const ( D12 Diameter = 12.e-3 D16 Diameter = 16.e-3 D20 Diameter = 20.e-3 D24 Diameter = 24.e-3 D30 Diameter = 30.e-3 D36 Diameter = 36.e-3 D42 Diameter = 42.e-3 D48 Diameter = 48.e-3 ) // GetBoltDiameterList - list of all allowable bolt classes func GetBoltDiameterList() []Diameter { return []Diameter{D12, D16, D20, D24, D30, D36, D42, D48} } func (bd Diameter) String() string { return fmt.Sprintf("HM%.0f", float64(bd)*1e3) } // HoleDiameter - struct of bolt hole type HoleDiameter struct { Dia Diameter } var holeDiameter = map[Diameter]DiameterDimension{ D12: 13e-3, D16: 18e-3, D20: 22e-3, D24: 26e-3, D30: 33e-3, D36: 39e-3, D42: 45e-3, D48: 51e-3, } // Value - return value diameter of hole for bolt func (hd HoleDiameter) Value() DiameterDimension { return holeDiameter[hd.Dia] } func (hd HoleDiameter) String() string { return fmt.Sprintf("For bolt %s hole is %s", hd.Dia, hd.Value()) } // DiameterDimension - dimension of diameter type DiameterDimension float64 func (dia DiameterDimension) String() string { return fmt.Sprintf("Ø%s", Dimension(float64(dia))) } // Table of Fyb. // unit: Pa var fyb = map[Class]Stress{ G4p6: 240.e6, G4p8: 320.e6, G5p6: 300.e6, G5p8: 400.e6, G6p8: 480.e6, G8p8: 640.e6, G10p9: 900.e6, } // Table of Fub. // unit: Pa var fub = map[Class]Stress{ G4p6: 400.e6, G4p8: 400.e6, G5p6: 500.e6, G5p8: 500.e6, G6p8: 600.e6, G8p8: 800.e6, G10p9: 1000.e6, } // Fyb - stress of bolt in according to table 3.1. EN1993-1-8. // unit: Pa type Fyb struct { Stress BoltClass Class } // Value - return value of Fyb func (f Fyb) Value() Stress { return fyb[f.BoltClass] } func (f Fyb) String() string { return fmt.Sprintf("In according to table 3.1 EN1993-1-8 value Fyb is %s", f.Value()) } // Fub - stress of bolt in according to table 3.1. EN1993-1-8. // unit: Pa type Fub struct { Stress BoltClass Class } // Value - return value of Fub func (f Fub) Value() Stress { return fub[f.BoltClass] } func (f Fub) String() string { return fmt.Sprintf("In according to table 3.1 EN1993-1-8 value Fub is %s", f.Value()) } // Stress - struct of float64 for Stress values. // unit: Pa type Stress float64 func (s Stress) String() string { return fmt.Sprintf("%.1f MPa", float64(s)*1.e-6) } // Pinch - struct of bolt pinch type Pinch struct { Dia Diameter } var boltPinch = map[Diameter]Dimension{ D12: 1.75e-3, D16: 2.00e-3, D20: 2.50e-3, D24: 3.00e-3, D30: 3.50e-3, D36: 4.00e-3, D42: 4.50e-3, D48: 5.00e-3, } // Value - return value of bolt pinch func (bp Pinch) Value() Dimension { return boltPinch[bp.Dia] } // Dimension - type for linear dimension sizes (height, thk, width) type Dimension float64 func (d Dimension) String() string { return fmt.Sprintf("%.1f mm", float64(d)*1.e3) } // Area - type of area. // unit - sq.meter type Area float64 func (a Area) String() string { return fmt.Sprintf("%.1f mm\u00B2", float64(a)*1.e6) } // AreaAs tension stress area of the bolt type AreaAs struct { Dia Diameter } // Value - return value of area As (tension stress area of the bolt) func (as AreaAs) Value() Area { var pd = Pinch(as) // Use a type conversion p := float64(pd.Value()) dia := float64(as.Dia) return Area(math.Pi / 4. * math.Pow(dia-0.935229*p, 2.0)) } func (as AreaAs) String() string { return fmt.Sprintf("Tension stress area of the bolt %s is %s", as.Dia, as.Value()) } // AreaA - the gross cross-section area of bolt type AreaA struct { Dia Diameter } // Value - return value of area A (the gross cross-section area of bolt) func (aa AreaA) Value() Area { dia := float64(aa.Dia) return Area(math.Pi / 4. * math.Pow(dia, 2.0)) } func (aa AreaA) String() string { return fmt.Sprintf("The gross cross-section area of the bolt %s is %s", aa.Dia, aa.Value()) }
bolt.go
0.845049
0.536556
bolt.go
starcoder
package main import ( "image" "image/color" "image/png" "os" "path/filepath" "github.com/unidoc/unipdf/v3/common" ) const imageDir = "artificial.images" // Where image segments are stored. func main() { if _, err := os.Stat(imageDir); os.IsNotExist(err) { os.Mkdir(imageDir, 0777) } if err := create("tricolor.png", tricolor); err != nil { panic(err) } if err := create("left.png", left); err != nil { panic(err) } if err := create("right.png", right); err != nil { panic(err) } if err := create("top.png", top); err != nil { panic(err) } if err := create("bottom.png", bottom); err != nil { panic(err) } if err := create("white.png", whiteBox); err != nil { panic(err) } if err := create("black.png", blackBox); err != nil { panic(err) } } func create(filename string, rectList []RectCol) error { filename = filepath.Join(imageDir, filename) img := createImage(rectList) return saveGoImage(filename, img) } func createImage(rectList []RectCol) image.Image { b := union(rectList).bounds() rgba := image.NewRGBA(b) for _, r := range rectList { fillRect(rgba, r.Rect, r.Col) } return rgba } var ( red = image.NewUniform(color.RGBA{R: 0xFF, G: 0x00, B: 0x00, A: 0xFF}) blue = image.NewUniform(color.RGBA{R: 0x00, G: 0x00, B: 0xFF, A: 0xFF}) yellow = image.NewUniform(color.RGBA{R: 0xFF, G: 0xFF, B: 0x00, A: 0xFF}) white = image.NewUniform(color.RGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF}) black = image.NewUniform(color.RGBA{R: 0x00, G: 0x00, B: 0x00, A: 0xFF}) tricolor = []RectCol{ RectCol{Rect{0, 0, 2, 6}, red}, RectCol{Rect{2, 0, 4, 6}, blue}, RectCol{Rect{4, 0, 6, 6}, yellow}, } left = []RectCol{ RectCol{Rect{0, 0, 3, 6}, white}, RectCol{Rect{3, 0, 6, 6}, black}, } right = []RectCol{ RectCol{Rect{0, 0, 3, 6}, black}, RectCol{Rect{3, 0, 6, 6}, white}, } top = []RectCol{ RectCol{Rect{0, 0, 6, 3}, white}, RectCol{Rect{0, 3, 6, 6}, black}, } bottom = []RectCol{ RectCol{Rect{0, 0, 6, 3}, black}, RectCol{Rect{0, 3, 6, 6}, white}, } whiteBox = []RectCol{ RectCol{Rect{0, 0, 6, 6}, white}, } blackBox = []RectCol{ RectCol{Rect{0, 0, 6, 6}, black}, } ) type RectCol struct { Rect Col *image.Uniform } type Rect struct { X0, Y0, X1, Y1 int } func union(rectList []RectCol) Rect { var u Rect for _, r := range rectList { if r.X0 < u.X0 { u.X0 = r.X0 } if r.Y0 < u.Y0 { u.Y0 = r.Y0 } if r.X1 > u.X1 { u.X1 = r.X1 } if r.Y1 > u.Y1 { u.Y1 = r.Y1 } } return u } func (r Rect) bounds() image.Rectangle { return image.Rect(r.X0, r.Y0, r.X1, r.Y1) } func (r Rect) position() image.Point { return image.Point{r.X0, r.Y0} } func (r Rect) zpBounds() image.Rectangle { return image.Rect(0, 0, r.X1-r.X0, r.Y1-r.Y0) } func fillRect(img *image.RGBA, r Rect, col *image.Uniform) { for y := r.Y0; y < r.Y1; y++ { for x := r.X0; x < r.X1; x++ { img.Set(x, y, col) } } } // saveGoImage saves Go image `img` to file `filename` with imageEncoding `enc`. func saveGoImage(filename string, img image.Image) error { out, err := os.Create(filename) if err != nil { return err } defer out.Close() return png.Encode(out, img) } // loadGoImage loads the image in file `pagePath` and returns it as a Go image. func loadGoImage(pagePath string) (image.Image, error) { imgfile, err := os.Open(pagePath) if err != nil { return nil, err } defer imgfile.Close() img, _, err := image.Decode(imgfile) return img, err } func makeGrayImage(img image.Image) image.Image { common.Log.Info("makeGrayImage: %v", img.Bounds()) x0, x1 := img.Bounds().Min.X, img.Bounds().Max.X y0, y1 := img.Bounds().Min.Y, img.Bounds().Max.Y grayImg := image.NewGray(img.Bounds()) for y := y0; y < y1; y++ { for x := x0; x < x1; x++ { grayImg.Set(x, y, img.At(x, y)) g := grayImg.GrayAt(x, y).Y if g < 127 { g = 0 } else { g = 255 } grayImg.SetGray(x, y, color.Gray{g}) } } return grayImg }
segmentation/create_images.go
0.647798
0.406096
create_images.go
starcoder
package fileseq import ( "fmt" "regexp" "strconv" "strings" ) type PadStyle int const ( // Constants defining the style of padding to use // when converting between padding characters ('#', '##', '@@@') // and their equivalent numeric padding width PadStyleHash1 PadStyle = 0 // '#' char == 1 PadStyleHash4 PadStyle = 1 // '#' char == 4 PadStyleDefault = PadStyleHash4 ) var ( defaultPadding paddingMapper padders map[PadStyle]paddingMapper ) func init() { padders = map[PadStyle]paddingMapper{ PadStyleHash1: newSingleHashPad(), PadStyleHash4: newMultiHashPad(), } defaultPadding = padders[PadStyleDefault] } // paddingMapper defines behavior for converting between // padding characters and their pad width type paddingMapper interface { // Return all supported padding characters AllChars() []string // Return the padding string sequence representing a width PaddingChars(int) string // Return a width for a string of pad characters PaddingCharsSize(string) int } // multiHashPad is a paddingMapper that uses a single # to // represent a width of 4 (i.e. Katana) type multiHashPad struct { *paddingMap } func newMultiHashPad() multiHashPad { padMap := &paddingMap{ charToSize: map[string]int{"#": 4, "@": 1}, defaultChar: "@", } return multiHashPad{padMap} } func (m multiHashPad) PaddingChars(pad int) string { switch { case pad <= 0: return m.defaultChar case pad%4 == 0: return strings.Repeat("#", pad/4) default: return strings.Repeat("@", pad) } } // singleHashPad is a paddingMapper that uses a single # to // represent a width of 1 (i.e. Nuke) type singleHashPad struct { *paddingMap } func newSingleHashPad() singleHashPad { padMap := &paddingMap{ charToSize: map[string]int{"#": 1, "@": 1}, defaultChar: "#", } return singleHashPad{padMap} } func (m singleHashPad) PaddingChars(pad int) string { if pad <= 0 { return m.defaultChar } return strings.Repeat(m.defaultChar, pad) } type paddingMap struct { charToSize map[string]int cachedKeys []string defaultChar string } func (m *paddingMap) AllChars() []string { if m.cachedKeys == nil { m.cachedKeys = make([]string, len(m.charToSize)) i := 0 for k := range m.charToSize { m.cachedKeys[i] = k i++ } } return m.cachedKeys } func (m *paddingMap) PaddingCharsSize(chars string) int { if len(chars) == 0 { return 0 } // check for alternate padding syntax var match []string for _, rx := range []*regexp.Regexp{printfPattern, houdiniPattern} { if match = rx.FindStringSubmatch(chars); len(match) == 0 { continue } intVal, err := strconv.Atoi(match[1]) if err != nil || intVal < 1 { return 1 } return intVal } // standard pad chars var size int for _, char := range chars { size += m.charToSize[string(char)] } return size } // PaddingChars returns the proper padding characters, // given an amount of padding. Uses PadStyleDefault. func PaddingChars(pad int) string { return defaultPadding.PaddingChars(pad) } // PadFrameRange takes a frame range string and returns a // new range with each number padded out with zeros to a given width func PadFrameRange(frange string, pad int) string { // We don't need to do anything if they gave us // an invalid pad number if pad < 2 { return frange } size := strings.Count(frange, ",") + 1 parts := make([]string, size, size) for i, part := range strings.Split(frange, ",") { didMatch := false for _, rx := range rangePatterns { matched := rx.FindStringSubmatch(part) if len(matched) == 0 { continue } matched = matched[1:] size = len(matched) switch size { case 1: parts[i] = zfillString(matched[0], pad) case 2: parts[i] = fmt.Sprintf("%s-%s", zfillString(matched[0], pad), zfillString(matched[1], pad)) case 4: parts[i] = fmt.Sprintf("%s-%s%s%s", zfillString(matched[0], pad), zfillString(matched[1], pad), matched[2], matched[3]) default: // No match. Try the next pattern continue } // If we got here, we matched a case and can stop // checking the rest of the patterns didMatch = true break } // If we didn't match one of our expected patterns // then just take the original part and add it unmodified if !didMatch { parts = append(parts, part) } } return strings.Join(parts, ",") } // Left pads a string to a given with, using "0". // If the string begins with a negative "-" character, then // padding is inserted between the "-" and the remaining characters. func zfillString(src string, z int) string { size := len(src) if size >= z { return src } fill := strings.Repeat("0", z-size) if strings.HasPrefix(src, "-") { return fmt.Sprintf("-%s%s", fill, src[1:]) } return fmt.Sprintf("%s%s", fill, src) } // Left pads an int to a given with, using "0". // If the string begins with a negative "-" character, then // padding is inserted between the "-" and the remaining characters. func zfillInt(src int, z int) string { if z < 2 { return strconv.Itoa(src) } return fmt.Sprintf(fmt.Sprintf("%%0%dd", z), src) }
pad.go
0.70069
0.40439
pad.go
starcoder
package three import ( "math" "math/rand" "strconv" ) // NewVector2 : func NewVector2(x, y float64) *Vector2 { return &Vector2{x, y, true} } // Vector2 : type Vector2 struct { X float64 Y float64 IsVector2 bool } // Width : func (v Vector2) Width() float64 { return v.X } // SetWidth : func (v Vector2) SetWidth(value float64) { v.X = value } // Height : func (v Vector2) Height() float64 { return v.Y } // SetHeight : func (v Vector2) SetHeight(value float64) { v.Y = value } // Set : func (v Vector2) Set(x, y float64) *Vector2 { v.X = x v.Y = y return &v } // SetScalar : func (v Vector2) SetScalar(scalar float64) *Vector2 { v.X = scalar v.Y = scalar return &v } // SetX : func (v Vector2) SetX(x float64) *Vector2 { v.X = x return &v } // SetY : func (v Vector2) SetY(y float64) *Vector2 { v.Y = y return &v } // SetComponent : func (v Vector2) SetComponent(index int, value float64) *Vector2 { switch index { default: panic("index is out of range: " + strconv.Itoa(index)) case 0: v.X = value case 1: v.Y = value } return &v } // GetComponent : func (v Vector2) GetComponent(index int) float64 { switch index { default: panic("index is out of range: " + strconv.Itoa(index)) case 0: return v.X case 1: return v.Y } } // Clone : func (v Vector2) Clone() *Vector2 { return NewVector2(v.X, v.Y) } // Copy : func (v Vector2) Copy(w Vector2) *Vector2 { v.X = w.X v.Y = w.Y return &v } // Add : func (v Vector2) Add(w Vector2) *Vector2 { v.X += w.X v.Y += w.Y return &v } // AddScalar : func (v Vector2) AddScalar(s float64) *Vector2 { v.X += s v.Y += s return &v } // AddVectors : func (v Vector2) AddVectors(a, b Vector2) *Vector2 { v.X = a.X + b.X v.Y = a.Y + b.Y return &v } // AddScaledVector : func (v Vector2) AddScaledVector(w Vector2, s float64) *Vector2 { v.X += w.X * s v.Y += w.Y * s return &v } // Sub : func (v Vector2) Sub(w Vector2) *Vector2 { v.X -= w.X v.Y -= w.Y return &v } // SubScalar : func (v Vector2) SubScalar(s float64) *Vector2 { v.X -= s v.Y -= s return &v } // SubVectors : func (v Vector2) SubVectors(a, b Vector2) *Vector2 { v.X = a.X - b.X v.Y = a.Y - b.Y return &v } // Multiply : func (v Vector2) Multiply(w Vector2) *Vector2 { v.X *= w.X v.Y *= w.Y return &v } // MultiplyScalar : func (v Vector2) MultiplyScalar(scalar float64) *Vector2 { v.X *= scalar v.Y *= scalar return &v } // Divide : func (v Vector2) Divide(w Vector2) *Vector2 { v.X /= w.X v.Y /= w.Y return &v } // DivideScalar : func (v Vector2) DivideScalar(scalar float64) *Vector2 { return v.MultiplyScalar(1 / scalar) } // ApplyMatrix3 : func (v Vector2) ApplyMatrix3(m Matrix3) *Vector2 { x, y := v.X, v.Y e := m.Elements v.X = e[0]*x + e[3]*y + e[6] v.Y = e[1]*x + e[4]*y + e[7] return &v } // Min : func (v Vector2) Min(w Vector2) *Vector2 { v.X = math.Min(v.X, w.X) v.Y = math.Min(v.Y, w.Y) return &v } // Max : func (v Vector2) Max(w Vector2) *Vector2 { v.X = math.Max(v.X, w.X) v.Y = math.Max(v.Y, w.Y) return &v } // Clamp : func (v Vector2) Clamp(min, max Vector2) *Vector2 { // assumes min < max, componentwise v.X = math.Max(min.X, math.Min(max.X, v.X)) v.Y = math.Max(min.Y, math.Min(max.Y, v.Y)) return &v } // ClampScalar : func (v Vector2) ClampScalar(minVal, maxVal float64) *Vector2 { v.X = math.Max(minVal, math.Min(maxVal, v.X)) v.Y = math.Max(minVal, math.Min(maxVal, v.Y)) return &v } // ClampLength : func (v Vector2) ClampLength(min, max float64) *Vector2 { length := v.Length() if length == 0 { length = 1 } return v.DivideScalar(length).MultiplyScalar(math.Max(min, math.Min(max, length))) } // Floor : func (v Vector2) Floor() *Vector2 { v.X = math.Floor(v.X) v.Y = math.Floor(v.Y) return &v } // Ceil : func (v Vector2) Ceil() *Vector2 { v.X = math.Ceil(v.X) v.Y = math.Ceil(v.Y) return &v } // Round : func (v Vector2) Round() *Vector2 { v.X = math.Round(v.X) v.Y = math.Round(v.Y) return &v } // RoundToZero : func (v Vector2) RoundToZero() *Vector2 { if v.X < 0 { v.X = math.Ceil(v.X) } else { v.X = math.Floor(v.X) } if v.Y < 0 { v.Y = math.Ceil(v.X) } else { v.Y = math.Floor(v.X) } return &v } // Negate : func (v Vector2) Negate() *Vector2 { v.X = -v.X v.Y = -v.Y return &v } // Dot : func (v Vector2) Dot(w Vector2) float64 { return v.X*w.X + v.Y*w.Y } // Cross : func (v Vector2) Cross(w Vector2) float64 { return v.X*w.Y - v.Y*w.X } // LengthSq : func (v Vector2) LengthSq() float64 { return v.X*v.X + v.Y*v.Y } // Length : func (v Vector2) Length() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } // ManhattanLength : func (v Vector2) ManhattanLength() float64 { return math.Abs(v.X) + math.Abs(v.Y) } // Normalize : func (v Vector2) Normalize() *Vector2 { length := v.Length() if length == 0 { length = 1 } return v.DivideScalar(length) } // Angle : func (v Vector2) Angle() float64 { // computes the angle in radians with respect to the positive x-axis var angle = math.Atan2(-v.Y, -v.X) + math.Pi return angle } // DistanceTo : func (v Vector2) DistanceTo(w Vector2) float64 { return math.Sqrt(v.DistanceToSquared(w)) } // DistanceToSquared : func (v Vector2) DistanceToSquared(w Vector2) float64 { dx, dy := v.X-w.X, v.Y-w.Y return dx*dx + dy*dy } // ManhattanDistanceTo : func (v Vector2) ManhattanDistanceTo(w Vector2) float64 { return math.Abs(v.X-w.X) + math.Abs(v.Y-w.Y) } // SetLength : func (v Vector2) SetLength(length float64) *Vector2 { return v.Normalize().MultiplyScalar(length) } // Lerp : func (v Vector2) Lerp(w Vector2, alpha float64) *Vector2 { v.X += (w.X - v.X) * alpha v.Y += (w.Y - v.Y) * alpha return &v } // LerpVectors : func (v Vector2) LerpVectors(v1, v2 Vector2, alpha float64) *Vector2 { v.X = v1.X + (v2.X-v1.X)*alpha v.Y = v1.Y + (v2.Y-v1.Y)*alpha return &v } // Equals : func (v Vector2) Equals(w Vector2) bool { return ((w.X == v.X) && (w.Y == v.Y)) } // FromArray : func (v Vector2) FromArray(array []float64, offset int) *Vector2 { if len(array) < offset+2 { panic("array length should be greater than offset+2") } v.X = array[offset] v.Y = array[offset+1] return &v } // ToArray : func (v Vector2) ToArray(array []float64, offset int) []float64 { if len(array) < offset+2 { panic("array length should be greater than offset+2") } array[offset] = v.X array[offset+1] = v.Y return array } // RotateAround : func (v Vector2) RotateAround(center Vector2, angle float64) *Vector2 { c, s := math.Cos(angle), math.Sin(angle) var x = v.X - center.X var y = v.Y - center.Y v.X = x*c - y*s + center.X v.Y = x*s + y*c + center.Y return &v } // Random : func (v Vector2) Random() *Vector2 { v.X = rand.Float64() v.Y = rand.Float64() return &v }
server/three/vector2.go
0.827201
0.740644
vector2.go
starcoder
package helper import "github.com/eriklupander/rt/internal/pkg/mat" var white = mat.NewColor(1, 1, 1) // RenderPointAt transforms the passed world coordinate point into view coords and projects it onto the 2D canvas. func RenderPointAt(canvas *mat.Canvas, camera mat.Camera, worldPoint mat.Tuple4, color mat.Tuple4) { // TransformRay point into camera space mat.MultiplyByTuplePtr(&camera.Transform, &worldPoint, &worldPoint) // View is always 1 unit away, divide by translated pixel z to get 3D -> 2D translation factor. dDividedByZ := 1 / worldPoint.Get(2) // Multiply x and y by translation factor to get 2D coords on the projection surface x := worldPoint.Get(0) * dDividedByZ y := worldPoint.Get(1) * dDividedByZ // transform from projection surface space into actual X/Y pixels based on pixelsize. // note that this translation isn't quite correct since I think I've gotten the offset // calculation wrong. Possibly, the raw col float should be rounded rather than floored. col := int(((camera.HalfWidth + x) / camera.PixelSize) - 0.5) row := int(((camera.HalfHeight + y) / camera.PixelSize) - 0.5) canvas.WritePixel(col, row, color) } func RenderReferenceAxises(canvas *mat.Canvas, camera mat.Camera) { xVec := mat.NewVector(1, 0, 0) yVec := mat.NewVector(0, 1, 0) zVec := mat.NewVector(0, 0, 1) point := mat.NewPoint(0, 0, 0) rx := mat.NewRay(point, xVec) ry := mat.NewRay(point, yVec) rz := mat.NewRay(point, zVec) for i := 0.0; i < 1.0; i += 0.005 { RenderPointAt(canvas, camera, mat.Position(rx, i), mat.NewColor(1, 0, 0)) RenderPointAt(canvas, camera, mat.Position(ry, i), mat.NewColor(0, 1, 0)) RenderPointAt(canvas, camera, mat.Position(rz, i), mat.NewColor(0, 0, 1)) } } func RenderLine(canvas *mat.Canvas, camera mat.Camera, from, to mat.Tuple4) { vec := mat.Sub(to, from) magn := mat.Magnitude(vec) ray := mat.NewRay(from, mat.Normalize(vec)) for i := 0.0; i < magn; i += 0.01 { RenderPointAt(canvas, camera, mat.Position(ray, i), white) } } func RenderWireframeBox(canvas *mat.Canvas, camera mat.Camera, o *mat.Group) { bb := mat.TransformBoundingBox(o.BoundingBox, o.Transform) min := bb.Min max := bb.Max a := mat.NewTupleOf(min[0], min[1], min[2], 1) b := mat.NewTupleOf(min[0], max[1], min[2], 1) c := mat.NewTupleOf(min[0], min[1], max[2], 1) d := mat.NewTupleOf(min[0], max[1], max[2], 1) e := mat.NewTupleOf(max[0], min[1], min[2], 1) f := mat.NewTupleOf(max[0], max[1], min[2], 1) g := mat.NewTupleOf(max[0], min[1], max[2], 1) h := mat.NewTupleOf(max[0], max[1], max[2], 1) RenderLine(canvas, camera, a, e) RenderLine(canvas, camera, b, f) RenderLine(canvas, camera, c, g) RenderLine(canvas, camera, d, h) RenderLine(canvas, camera, e, f) RenderLine(canvas, camera, f, h) RenderLine(canvas, camera, h, g) RenderLine(canvas, camera, g, e) RenderLine(canvas, camera, a, b) RenderLine(canvas, camera, b, d) RenderLine(canvas, camera, d, c) RenderLine(canvas, camera, c, a) } func RenderLineBetweenShapes(canvas *mat.Canvas, s1, s2 mat.Shape, camera mat.Camera) { origin := mat.NewPoint(s1.GetTransform().Get(0, 3), s1.GetTransform().Get(1, 3), s1.GetTransform().Get(2, 3)) target := mat.NewPoint(s2.GetTransform().Get(0, 3), s2.GetTransform().Get(1, 3), s2.GetTransform().Get(2, 3)) vec := mat.Sub(target, origin) magn := mat.Magnitude(vec) ray := mat.NewRay(origin, mat.Normalize(vec)) for i := 0.0; i < magn; i += 0.01 { RenderPointAt(canvas, camera, mat.Position(ray, i), white) } }
internal/pkg/helper/helper.go
0.736401
0.755163
helper.go
starcoder
package main import ( "fmt" "reflect" ) type Employee struct { Name string Age int Vacation int Salary int } func Transform(slice, function interface{}) interface{} { return transform(slice, function, false) } func TransformInPlace(slice, function interface{}) interface{} { return transform(slice, function, true) } func transform(slice, function interface{}, inPlace bool) interface{} { //check the `slice` type is Slice sliceInType := reflect.ValueOf(slice) if sliceInType.Kind() != reflect.Slice { panic("transform: not slice") } //check the function signature fn := reflect.ValueOf(function) elemType := sliceInType.Type().Elem() if !verifyFuncSignature(fn, elemType, nil) { panic("trasform: function must be of type func(" + sliceInType.Type().Elem().String() + ") outputElemType") } sliceOutType := sliceInType if !inPlace { sliceOutType = reflect.MakeSlice(reflect.SliceOf(fn.Type().Out(0)), sliceInType.Len(), sliceInType.Len()) } for i := 0; i < sliceInType.Len(); i++ { sliceOutType.Index(i).Set(fn.Call([]reflect.Value{sliceInType.Index(i)})[0]) } return sliceOutType.Interface() } func verifyFuncSignature(fn reflect.Value, types ...reflect.Type) bool { //Check it is a funciton if fn.Kind() != reflect.Func { return false } // NumIn() - returns a function type's input parameter count. // NumOut() - returns a function type's output parameter count. if (fn.Type().NumIn() != len(types)-1) || (fn.Type().NumOut() != 1) { return false } // In() - returns the type of a function type's i'th input parameter. for i := 0; i < len(types)-1; i++ { if fn.Type().In(i) != types[i] { return false } } // Out() - returns the type of a function type's i'th output parameter. outType := types[len(types)-1] if outType != nil && fn.Type().Out(0) != outType { return false } return true } func main() { // array of string list := []string{"1", "2", "3", "4", "5", "6"} result := Transform(list, func(a string) string { return a + a + a }) fmt.Println(result) //{"111","222","333","444","555","666"} // array of int int_list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} TransformInPlace(int_list, func(a int) int { return a * 3 }) fmt.Println(int_list) //{3, 6, 9, 12, 15, 18, 21, 24, 27} employee_list := []Employee{ {"Hao", 44, 0, 8000}, {"Bob", 34, 10, 5000}, {"Alice", 23, 5, 9000}, {"Jack", 26, 0, 4000}, {"Tom", 48, 9, 7500}, } employee_result := TransformInPlace(employee_list, func(e Employee) Employee { e.Salary += 1000 e.Age += 1 return e }) fmt.Println(employee_result) // [{Hao 45 0 9000} {Bob 35 10 6000} {Alice 24 5 10000} {Jack 27 0 5000} {Tom 49 9 8500}] }
src/go/go-patterns/src/map_reduce/robust_generic_map.go
0.690768
0.442637
robust_generic_map.go
starcoder
package lunar import ( "time" c "github.com/rtovey/astro-lib/common" o "github.com/rtovey/astro-lib/orbit" t "github.com/rtovey/astro-lib/time" ) type LunarRiseSetTime struct { Rise time.Time Set time.Time Debug LunarRiseSetTimeDebug } type LunarRiseSetTimeDebug struct { date time.Time observer c.Observer midnightPosition LunarPosition middayPosition LunarPosition midnightRiseSetTime o.RiseSetTime middayRiseSetTime o.RiseSetTime T00 t.GST T000 t.GST GST1r t.GST GST1s t.GST GST2r t.GST GST2s t.GST GSTr t.GST GSTs t.GST dd o.Equatorial pi float64 th float64 x float64 phi float64 y float64 dt float64 GSTra t.GST GSTsa t.GST UTr time.Time UTs time.Time } func RiseSetTime(observer c.Observer, date time.Time) LunarRiseSetTime { midnightPosition := Position(time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.UTC)) middayPosition := Position(time.Date(date.Year(), date.Month(), date.Day(), 12, 0, 0, 0, time.UTC)) midnightRiseSetTime := midnightPosition.Ecliptic.ToEquatorial(date).GetRiseSetTime(observer) middayRiseSetTime := middayPosition.Ecliptic.ToEquatorial(date).GetRiseSetTime(observer) UTdate := date.In(time.UTC) T00 := t.UTToGst(time.Date(UTdate.Year(), UTdate.Month(), UTdate.Day(), 0, 0, 0, 0, time.UTC)) T000 := t.GetT000(T00, observer) GST1r := calculateAdjustedGST(midnightRiseSetTime.LSTr, observer, T000) GST1s := calculateAdjustedGST(midnightRiseSetTime.LSTs, observer, T000) GST2r := calculateAdjustedGST(middayRiseSetTime.LSTr, observer, T000) GST2s := calculateAdjustedGST(middayRiseSetTime.LSTs, observer, T000) GSTr := interpolateGST(GST1r, GST2r, T00) GSTs := interpolateGST(GST1s, GST2s, T00) dd := meanPosition(midnightPosition, middayPosition, date) pi := horizontalParallax(midnightPosition) th := apparentAngularDiameter(midnightPosition) x := (-1.0 * pi) + (th / 2.0) + atmosphericRefraction phi := o.AngleAtHorizon(observer, dd) y := o.Y(x, phi) dt := o.RiseSetTimeShiftSeconds(y, dd) / 3600.0 GSTra := t.GST(GSTr.Value() - dt) GSTsa := t.GST(GSTs.Value() + dt) UTr := GSTra.ToUT(date) UTs := GSTsa.ToUT(date) debug := LunarRiseSetTimeDebug{ date: date, observer: observer, midnightPosition: midnightPosition, middayPosition: middayPosition, midnightRiseSetTime: midnightRiseSetTime, middayRiseSetTime: middayRiseSetTime, T00: T00, T000: T000, GST1r: GST1r, GST1s: GST1s, GST2r: GST2r, GST2s: GST2s, GSTr: GSTr, GSTs: GSTs, dd: dd, pi: pi, th: th, x: x, phi: phi, y: y, dt: dt, GSTra: GSTra, GSTsa: GSTsa, UTr: UTr, UTs: UTs, } return LunarRiseSetTime{ Rise: UTr.In(observer.Location), Set: UTs.In(observer.Location), Debug: debug, } } func calculateAdjustedGST(LST t.LST, observer c.Observer, T000 t.GST) t.GST { GSTvalue := LST.ToGst(observer).Value() if GSTvalue < T000.Value() { GSTvalue += 24.0 } return t.GST(GSTvalue) } func interpolateGST(GST1 t.GST, GST2 t.GST, T00 t.GST) t.GST { GST := ((12.03 * GST1.Value()) - (T00.Value() * (GST2.Value() - GST1.Value()))) / (12.03 + GST1.Value() - GST2.Value()) return t.GST(GST) } func meanPosition(p1 LunarPosition, p2 LunarPosition, date time.Time) o.Equatorial { return o.MeanEquatorialPosition(p1.Ecliptic.ToEquatorial(date), p2.Ecliptic.ToEquatorial(date)) }
lunar/lunarRiseSetTime.go
0.630116
0.54952
lunarRiseSetTime.go
starcoder
package api // GatewayIntents is an extension of the Bit structure used when identifying with discord type GatewayIntents int64 // Constants for the different bit offsets of GatewayIntents const ( GatewayIntentsGuilds GatewayIntents = 1 << iota GatewayIntentsGuildMembers GatewayIntentsGuildBans GatewayIntentsGuildEmojis GatewayIntentsGuildIntegrations GatewayIntentsGuildWebhooks GatewayIntentsGuildInvites GatewayIntentsGuildVoiceStates GatewayIntentsGuildPresences GatewayIntentsGuildMessages GatewayIntentsGuildMessageReactions GatewayIntentsGuildMessageTyping GatewayIntentsDirectMessages GatewayIntentsDirectMessageReactions GatewayIntentsDirectMessageTyping GatewayIntentsNonPrivileged = GatewayIntentsGuilds | GatewayIntentsGuildBans | GatewayIntentsGuildEmojis | GatewayIntentsGuildIntegrations | GatewayIntentsGuildWebhooks | GatewayIntentsGuildInvites | GatewayIntentsGuildVoiceStates | GatewayIntentsGuildMessages | GatewayIntentsGuildMessageReactions | GatewayIntentsGuildMessageTyping | GatewayIntentsDirectMessages | GatewayIntentsDirectMessageReactions | GatewayIntentsDirectMessageTyping GatewayIntentsPrivileged = GatewayIntentsGuildMembers | GatewayIntentsGuildPresences GatewayIntentsAll = GatewayIntentsNonPrivileged | GatewayIntentsPrivileged GatewayIntentsNone GatewayIntents = 0 ) // Add allows you to add multiple bits together, producing a new bit func (p GatewayIntents) Add(bits ...GatewayIntents) GatewayIntents { total := GatewayIntents(0) for _, bit := range bits { total |= bit } p |= total return p } // Remove allows you to subtract multiple bits from the first, producing a new bit func (p GatewayIntents) Remove(bits ...GatewayIntents) GatewayIntents { total := GatewayIntents(0) for _, bit := range bits { total |= bit } p &^= total return p } // HasAll will ensure that the bit includes all of the bits entered func (p GatewayIntents) HasAll(bits ...GatewayIntents) bool { for _, bit := range bits { if !p.Has(bit) { return false } } return true } // Has will check whether the Bit contains another bit func (p GatewayIntents) Has(bit GatewayIntents) bool { return (p & bit) == bit } // MissingAny will check whether the bit is missing any one of the bits func (p GatewayIntents) MissingAny(bits ...GatewayIntents) bool { for _, bit := range bits { if !p.Has(bit) { return true } } return false } // Missing will do the inverse of Bit.Has func (p GatewayIntents) Missing(bit GatewayIntents) bool { return !p.Has(bit) }
api/gateway_intents.go
0.645343
0.540803
gateway_intents.go
starcoder
package day219 import "fmt" // Possible winning positions. // Vertical: 7 columns * 3 positions per column = 21 vertical winning positions. // Horizontal: 6 rows * 4 positions per column = 24 horizontal winning positions. // DiagUp: 12 // DiagDown: 12 // Total == 69 winning positions checking 4 positions == 276 checks // Player represents a ConnectFour player or none. type Player int const ( // None is neither player. None Player = iota // Red is a position owned by the 'red' player. Red // Black is a position owned by the 'black' player. Black ) // Column is zero-based from left to right. type Column int // Row is zero-based from bottom to top. type Row int // ConnectFourBoard represents a column-major board since // moves are played by column. // 7 vertical columns and 6 horizontal rows. type ConnectFourBoard struct { board map[Column]map[Row]Player } // Move is a piece played by a player. // Player must be either 'Red' or 'Black' to play a valid move. func (cfb *ConnectFourBoard) Move(player Player, col Column) error { if player != Red && player != Black { return fmt.Errorf("must play either Red or Black, you tried %v", player) } if cfb.board == nil { cfb.board = make(map[Column]map[Row]Player) } valid := false for row := Row(0); row < 6; row++ { if cfb.board[col] == nil { cfb.board[col] = make(map[Row]Player) } if _, found := cfb.board[col][row]; !found { cfb.board[col][row] = player valid = true break } } if !valid { return fmt.Errorf("column full. can't play in this column") } return nil } // Winner returns the winner of the current board. // If there is no winner yet, then Player=None is returned. func (cfb *ConnectFourBoard) Winner() Player { height := Row(6) width := Column(7) for row := Row(0); row < height; row++ { for col := Column(0); col < width; col++ { player := cfb.board[col][row] if player == None { continue } if col+3 < width && isHorizontal(cfb.board, row, col, player) { return player } if row+3 < height { if isVertical(cfb.board, row, col, player) { return player } if col+3 < width && isDiagonalUpRight(cfb.board, row, col, player) { return player } if col-3 >= 0 && isDiagonalUpLeft(cfb.board, row, col, player) { return player } } } } return None } func isHorizontal(board map[Column]map[Row]Player, r Row, c Column, p Player) bool { return p == board[c+1][r] && p == board[c+2][r] && p == board[c+3][r] } func isVertical(board map[Column]map[Row]Player, r Row, c Column, p Player) bool { return p == board[c][r+1] && p == board[c][r+2] && p == board[c][r+3] } func isDiagonalUpRight(board map[Column]map[Row]Player, r Row, c Column, p Player) bool { return p == board[c+1][r+1] && p == board[c+2][r+2] && p == board[c+3][r+3] } func isDiagonalUpLeft(board map[Column]map[Row]Player, r Row, c Column, p Player) bool { return p == board[c-1][r+1] && p == board[c-2][r+2] && p == board[c-3][r+3] }
day219/problem.go
0.784278
0.50531
problem.go
starcoder
package sprites import ( "github.com/go-gl/mathgl/mgl32" "github.com/wieku/danser-go/animation" "github.com/wieku/danser-go/bmath" "github.com/wieku/danser-go/render/batches" "github.com/wieku/danser-go/render/texture" "math" "sort" ) const ( storyboardArea = 640.0 * 480.0 maxLoad = 1.3328125 //480*480*(16/9)/(640*480) ) type Sprite struct { texture []*texture.TextureRegion frameDelay float64 loopForever bool currentFrame int transforms []*animation.Transformation startTime, endTime, depth float64 position bmath.Vector2d positionRelative bmath.Vector2d origin bmath.Vector2d scale bmath.Vector2d flip bmath.Vector2d rotation float64 color bmath.Color dirty bool additive bool showForever bool } func NewSpriteSingle(tex *texture.TextureRegion, depth float64, position bmath.Vector2d, origin bmath.Vector2d) *Sprite { textures := []*texture.TextureRegion{tex} sprite := &Sprite{texture: textures, frameDelay: 0.0, loopForever: true, depth: depth, position: position, origin: origin, scale: bmath.NewVec2d(1, 1), flip: bmath.NewVec2d(1, 1), color: bmath.Color{1, 1, 1, 1}, showForever:true} sprite.transforms = make([]*animation.Transformation, 0) return sprite } /* func NewSpriteSingle(texture []*texture.TextureRegion, frameDelay float64, loopForever bool, depth float64, position bmath.Vector2d, origin bmath.Vector2d) *Sprite { sprite := &Sprite{texture: texture, frameDelay: frameDelay, loopForever: loopForever, zIndex: zIndex, position: position, origin: origin, scale: bmath.NewVec2d(1, 1), flip: bmath.NewVec2d(1, 1), color: color{1, 1, 1, 1}} sprite.transform = NewTransformations(sprite) var currentLoop *Loop = nil loopDepth := -1 for _, subCommand := range subCommands { command := strings.Split(subCommand, ",") var removed int command[0], removed = cutWhites(command[0]) if command[0] == "T" { continue } if removed == 1 { if currentLoop != nil { sprite.loopQueue = append(sprite.loopQueue, currentLoop) loopDepth = -1 } if command[0] != "L" { sprite.transform.Add(NewCommand(command)) } } if command[0] == "L" { currentLoop = NewLoop(command, sprite) loopDepth = removed + 1 } else if removed == loopDepth { currentLoop.Add(NewCommand(command)) } } if currentLoop != nil { sprite.loopQueue = append(sprite.loopQueue, currentLoop) loopDepth = -1 } sprite.transform.Finalize() sprite.startTime = sprite.transform.startTime sprite.endTime = sprite.transform.endTime for _, loop := range sprite.loopQueue { if loop.start < sprite.startTime { sprite.startTime = loop.start } if loop.end > sprite.endTime { sprite.endTime = loop.end } } return sprite } */ func (sprite *Sprite) Update(time int64) { sprite.currentFrame = 0 if len(sprite.texture) > 1 { frame := int(math.Floor((float64(time) - sprite.startTime) / sprite.frameDelay)) if !sprite.loopForever { if frame >= len(sprite.texture) { frame = len(sprite.texture) - 1 } sprite.currentFrame = frame } else { sprite.currentFrame = frame % len(sprite.texture) } } for i := 0; i < len(sprite.transforms); i++ { transform := sprite.transforms[i] if float64(time) < transform.GetStartTime() { break } switch transform.GetType() { case animation.Fade, animation.Scale, animation.Rotate, animation.MoveX, animation.MoveY: value := transform.GetSingle(float64(time)) switch transform.GetType() { case animation.Fade: sprite.color.A = value case animation.Scale: sprite.scale.X = value sprite.scale.Y = value case animation.Rotate: sprite.rotation = value case animation.MoveX: sprite.position.X = value case animation.MoveY: sprite.position.Y = value } case animation.Move, animation.ScaleVector: x, y := transform.GetDouble(float64(time)) switch transform.GetType() { case animation.Move: sprite.position.X = x sprite.position.Y = y case animation.ScaleVector: sprite.scale.X = x sprite.scale.Y = y } case animation.Additive, animation.HorizontalFlip, animation.VerticalFlip: value := transform.GetBoolean(float64(time)) va1 := 1.0 if value { va1 = -1 } switch transform.GetType() { case animation.Additive: sprite.additive = value case animation.HorizontalFlip: sprite.flip.X = va1 case animation.VerticalFlip: sprite.flip.Y = va1 } case animation.Color3, animation.Color4: color := transform.GetColor(float64(time)) sprite.color.R = color.R sprite.color.G = color.G sprite.color.B = color.B if transform.GetType() == animation.Color4 { sprite.color.A = color.A } } if float64(time) >= transform.GetEndTime() { sprite.transforms = append(sprite.transforms[:i], sprite.transforms[i+1:]...) i-- } } } func (sprite *Sprite) AddTransform(transformation *animation.Transformation, sortAfter bool) { sprite.transforms = append(sprite.transforms, transformation) if sortAfter { sprite.SortTransformations() } } func (sprite *Sprite) SortTransformations() { sort.Slice(sprite.transforms, func(i, j int) bool { return sprite.transforms[i].GetStartTime() < sprite.transforms[j].GetStartTime() }) } func (sprite *Sprite) AdjustTimesToTransformations() { startTime := math.MaxFloat64 endTime := -math.MaxFloat64 for _, t := range sprite.transforms { startTime = math.Min(startTime, t.GetStartTime()) endTime = math.Max(endTime, t.GetEndTime()) } sprite.startTime = startTime sprite.endTime = endTime } func (sprite *Sprite) ShowForever(value bool) { sprite.showForever = value } func (sprite *Sprite) UpdateAndDraw(time int64, batch *batches.SpriteBatch) { sprite.Update(time) sprite.Draw(time, batch) } func (sprite *Sprite) Draw(time int64, batch *batches.SpriteBatch) { if (!sprite.showForever && float64(time) < sprite.startTime && float64(time) >= sprite.endTime) || sprite.color.A < 0.01 { return } alpha := sprite.color.A if alpha > 1.001 { alpha -= math.Ceil(sprite.color.A) - 1 } batch.DrawStObject(sprite.position, sprite.origin, sprite.scale.Abs(), sprite.flip, sprite.rotation, mgl32.Vec4{float32(sprite.color.R), float32(sprite.color.G), float32(sprite.color.B), float32(alpha)}, sprite.additive, *sprite.texture[sprite.currentFrame], false) } func (sprite *Sprite) GetPosition() bmath.Vector2d { return sprite.position } func (sprite *Sprite) SetPosition(vec bmath.Vector2d) { sprite.position = vec sprite.dirty = true } func (sprite *Sprite) GetScale() bmath.Vector2d { return sprite.scale } func (sprite *Sprite) SetScale(scale float64) { sprite.scale.X = scale sprite.scale.Y = scale sprite.dirty = true } func (sprite *Sprite) SetScaleV(vec bmath.Vector2d) { sprite.scale = vec sprite.dirty = true } func (sprite *Sprite) GetRotation() float64 { return sprite.rotation } func (sprite *Sprite) SetRotation(rad float64) { sprite.rotation = rad sprite.dirty = true } func (sprite *Sprite) GetColor() mgl32.Vec3 { return mgl32.Vec3{float32(sprite.color.R), float32(sprite.color.G), float32(sprite.color.B)} } func (sprite *Sprite) SetColor(color bmath.Color) { sprite.color.R, sprite.color.G, sprite.color.B = color.R, color.G, color.B sprite.dirty = true } func (sprite *Sprite) GetAlpha() float64 { return sprite.color.A } func (sprite *Sprite) SetAlpha(alpha float64) { sprite.color.A = alpha sprite.dirty = true } func (sprite *Sprite) SetHFlip(on bool) { j := 1.0 if on { j = -1 } sprite.flip.X = j sprite.dirty = true } func (sprite *Sprite) SetVFlip(on bool) { j := 1.0 if on { j = -1 } sprite.flip.Y = j sprite.dirty = true } func (sprite *Sprite) SetAdditive(on bool) { sprite.additive = on sprite.dirty = true } func (sprite *Sprite) GetStartTime() float64 { return sprite.startTime } func (sprite *Sprite) GetEndTime() float64 { return sprite.endTime } func (sprite *Sprite) GetDepth() float64 { return sprite.depth } func (sprite *Sprite) GetLoad() float64 { if sprite.color.A >= 0.01 { return math.Min((float64(sprite.texture[0].Width)*sprite.scale.X*float64(sprite.texture[0].Height)*sprite.scale.Y)/storyboardArea, maxLoad) } return 0 }
render/sprites/sprite.go
0.620622
0.480722
sprite.go
starcoder
package rui import "strconv" const ( // ImageLoading is the image loading status: in the process of loading ImageLoading = 0 // ImageReady is the image loading status: the image is loaded successfully ImageReady = 1 // ImageLoadingError is the image loading status: an error occurred while loading ImageLoadingError = 2 ) // Image defines the image that is used for drawing operations on the Canvas. type Image interface { // URL returns the url of the image URL() string // LoadingStatus returns the status of the image loading: ImageLoading (0), ImageReady (1), ImageLoadingError (2) LoadingStatus() int // LoadingError: if LoadingStatus() == ImageLoadingError then returns the error text, "" otherwise LoadingError() string setLoadingError(err string) // Width returns the width of the image in pixels. While LoadingStatus() != ImageReady returns 0 Width() float64 // Height returns the height of the image in pixels. While LoadingStatus() != ImageReady returns 0 Height() float64 } type imageData struct { url string loadingStatus int loadingError string width, height float64 listener func(Image) } type imageManager struct { images map[string]*imageData } func (image *imageData) URL() string { return image.url } func (image *imageData) LoadingStatus() int { return image.loadingStatus } func (image *imageData) LoadingError() string { return image.loadingError } func (image *imageData) setLoadingError(err string) { image.loadingError = err } func (image *imageData) Width() float64 { return image.width } func (image *imageData) Height() float64 { return image.height } func (manager *imageManager) loadImage(url string, onLoaded func(Image), session Session) Image { if manager.images == nil { manager.images = make(map[string]*imageData) } if image, ok := manager.images[url]; ok && image.loadingStatus == ImageReady { return image } image := new(imageData) image.url = url image.listener = onLoaded image.loadingStatus = ImageLoading manager.images[url] = image session.runScript("loadImage('" + url + "');") return image } func (manager *imageManager) imageLoaded(obj DataObject, session Session) { if manager.images == nil { manager.images = make(map[string]*imageData) return } if url, ok := obj.PropertyValue("url"); ok { if image, ok := manager.images[url]; ok { image.loadingStatus = ImageReady if width, ok := obj.PropertyValue("width"); ok { if w, err := strconv.ParseFloat(width, 64); err == nil { image.width = w } } if height, ok := obj.PropertyValue("height"); ok { if h, err := strconv.ParseFloat(height, 64); err == nil { image.height = h } } if image.listener != nil { image.listener(image) } } } } func (manager *imageManager) imageLoadError(obj DataObject, session Session) { if manager.images == nil { manager.images = make(map[string]*imageData) return } if url, ok := obj.PropertyValue("url"); ok { if image, ok := manager.images[url]; ok { delete(manager.images, url) text, _ := obj.PropertyValue("message") image.setLoadingError(text) if image.listener != nil { image.listener(image) } } } } // LoadImage starts the async image loading by url func LoadImage(url string, onLoaded func(Image), session Session) Image { return session.imageManager().loadImage(url, onLoaded, session) }
image.go
0.719482
0.45647
image.go
starcoder
package reflect import ( "log" "reflect" ) // TypeMatcher represents a type that describes itself as a matcher of reflect.Type. type TypeMatcher interface { // MatchType returns true if matching was successful. MatchType(reflect.Type) bool } // FuncMatcher matches in/out sections of the functions. type FuncMatcher struct { // In is a list of argument matchers. In []TypeMatcher // Out is a list of result matchers. Out []TypeMatcher } // MatchType matches functions, arguments and return values. func (m FuncMatcher) MatchType(t reflect.Type) bool { if t.Kind() != reflect.Func { log.Printf("FuncMatcher: Kind=%v, want Func", t.Kind()) return false } if t.NumIn() != len(m.In) { log.Printf("FuncMatcher: NumIn=%v, want %v", t.NumIn(), len(m.In)) return false } if t.NumOut() != len(m.Out) { log.Printf("FuncMatcher: NumOut=%v, want %v", t.NumOut(), len(m.Out)) return false } for i, in := range m.In { if !in.MatchType(t.In(i)) { log.Printf("FuncMatcher: In[%d].Match=false, want true", i) return false } } for i, out := range m.Out { if !out.MatchType(t.Out(i)) { log.Printf("FuncMatcher: Out[%d].Match=false, want true", i) return false } } return true } // KindMatcher matches Kind. It is expected to be used with basic types e.g. reflect.Int. type KindMatcher struct { // Kind is an expected type. Kind reflect.Kind } // MatchType matches kind of the object. func (m KindMatcher) MatchType(o reflect.Type) bool { if o.Kind() == m.Kind { return true } log.Printf("KindMatcher: Kind=%v, want %v", o.Kind(), m.Kind) return false } // ArrayMatcher matches arrays and applies provided matcher to the element type. // If the matching is successful, the array's length is stored in Len. type ArrayMatcher struct { // M is a matcher that is applied to the element type. M TypeMatcher // Len is set with the array size. Len int } // MatchType matches arrays and its type. func (m *ArrayMatcher) MatchType(t reflect.Type) bool { if t.Kind() != reflect.Array { log.Printf("ArrayMatcher: Kind=%v, want Array", t.Kind()) return false } if !m.M.MatchType(t.Elem()) { log.Printf("ArrayMatcher: M.Match=false, want true") return false } m.Len = t.Len() return true }
reflect/matchers.go
0.645343
0.554651
matchers.go
starcoder
package plotter import ( "errors" "math" "sort" "code.google.com/p/plotinum/plot" "code.google.com/p/plotinum/vg" ) // fiveStatPlot contains the shared fields for quartile // and box-whisker plots. type fiveStatPlot struct { // Values is a copy of the values of the values used to // create this box plot. Values // Location is the location of the box along its axis. Location float64 // Median is the median value of the data. Median float64 // Quartile1 and Quartile3 are the first and // third quartiles of the data respectively. Quartile1, Quartile3 float64 // AdjLow and AdjHigh are the `adjacent' values // on the low and high ends of the data. The // adjacent values are the points to which the // whiskers are drawn. AdjLow, AdjHigh float64 // Min and Max are the extreme values of the data. Min, Max float64 // Outside are the indices of Vs for the outside points. Outside []int } // BoxPlot implements the Plotter interface, drawing // a boxplot to represent the distribution of values. type BoxPlot struct { fiveStatPlot // Offset is added to the x location of each box. // When the Offset is zero, the boxes are drawn // centered at their x location. Offset vg.Length // Width is the width used to draw the box. Width vg.Length // CapWidth is the width of the cap used to top // off a whisker. CapWidth vg.Length // GlyphStyle is the style of the outside point glyphs. GlyphStyle plot.GlyphStyle // BoxStyle is the line style for the box. BoxStyle plot.LineStyle // MedianStyle is the line style for the median line. MedianStyle plot.LineStyle // WhiskerStyle is the line style used to draw the // whiskers. WhiskerStyle plot.LineStyle } // NewBoxPlot returns a new BoxPlot that represents // the distribution of the given values. The style of // the box plot is that used for Tukey's schematic // plots is ``Exploratory Data Analysis.'' // // An error is returned if the boxplot is created with // no values. // // The fence values are 1.5x the interquartile before // the first quartile and after the third quartile. Any // value that is outside of the fences are drawn as // Outside points. The adjacent values (to which the // whiskers stretch) are the minimum and maximum // values that are not outside the fences. func NewBoxPlot(w vg.Length, loc float64, values Valuer) (*BoxPlot, error) { if w < 0 { return nil, errors.New("Negative boxplot width") } b := new(BoxPlot) var err error if b.fiveStatPlot, err = newFiveStat(w, loc, values); err != nil { return nil, err } b.Width = w b.CapWidth = 3 * w / 4 b.GlyphStyle = DefaultGlyphStyle b.BoxStyle = DefaultLineStyle b.MedianStyle = DefaultLineStyle b.WhiskerStyle = plot.LineStyle{ Width: vg.Points(0.5), Dashes: []vg.Length{vg.Points(4), vg.Points(2)}, } if len(b.Values) == 0 { b.Width = 0 b.GlyphStyle.Radius = 0 b.BoxStyle.Width = 0 b.MedianStyle.Width = 0 b.WhiskerStyle.Width = 0 } return b, nil } func newFiveStat(w vg.Length, loc float64, values Valuer) (fiveStatPlot, error) { var b fiveStatPlot b.Location = loc var err error if b.Values, err = CopyValues(values); err != nil { return fiveStatPlot{}, err } sorted := make(Values, len(b.Values)) copy(sorted, b.Values) sort.Float64s(sorted) if len(sorted) == 1 { b.Median = sorted[0] b.Quartile1 = sorted[0] b.Quartile3 = sorted[0] } else { b.Median = median(sorted) b.Quartile1 = median(sorted[:len(sorted)/2]) b.Quartile3 = median(sorted[len(sorted)/2:]) } b.Min = sorted[0] b.Max = sorted[len(sorted)-1] low := b.Quartile1 - 1.5*(b.Quartile3-b.Quartile1) high := b.Quartile3 + 1.5*(b.Quartile3-b.Quartile1) b.AdjLow = math.Inf(1) b.AdjHigh = math.Inf(-1) for i, v := range b.Values { if v > high || v < low { b.Outside = append(b.Outside, i) continue } if v < b.AdjLow { b.AdjLow = v } if v > b.AdjHigh { b.AdjHigh = v } } return b, nil } // median returns the median value from a // sorted Values. func median(vs Values) float64 { if len(vs) == 1 { return vs[0] } med := vs[len(vs)/2] if len(vs)%2 == 0 { med += vs[len(vs)/2-1] med /= 2 } return med } func (b *BoxPlot) Plot(da plot.DrawArea, plt *plot.Plot) { trX, trY := plt.Transforms(&da) x := trX(b.Location) if !da.ContainsX(x) { return } x += b.Offset med := trY(b.Median) q1 := trY(b.Quartile1) q3 := trY(b.Quartile3) aLow := trY(b.AdjLow) aHigh := trY(b.AdjHigh) box := da.ClipLinesY([]plot.Point{ {x - b.Width/2, q1}, {x - b.Width/2, q3}, {x + b.Width/2, q3}, {x + b.Width/2, q1}, {x - b.Width/2 - b.BoxStyle.Width/2, q1}, }) da.StrokeLines(b.BoxStyle, box...) medLine := da.ClipLinesY([]plot.Point{ {x - b.Width/2, med}, {x + b.Width/2, med}, }) da.StrokeLines(b.MedianStyle, medLine...) cap := b.CapWidth / 2 whisks := da.ClipLinesY([]plot.Point{{x, q3}, {x, aHigh}}, []plot.Point{{x - cap, aHigh}, {x + cap, aHigh}}, []plot.Point{{x, q1}, {x, aLow}}, []plot.Point{{x - cap, aLow}, {x + cap, aLow}}) da.StrokeLines(b.WhiskerStyle, whisks...) for _, out := range b.Outside { y := trY(b.Value(out)) if da.ContainsY(y) { da.DrawGlyphNoClip(b.GlyphStyle, plot.Pt(x, y)) } } } // DataRange returns the minimum and maximum x // and y values, implementing the plot.DataRanger // interface. func (b *BoxPlot) DataRange() (float64, float64, float64, float64) { return b.Location, b.Location, b.Min, b.Max } // GlyphBoxes returns a slice of GlyphBoxes for the // points and for the median line of the boxplot, // implementing the plot.GlyphBoxer interface func (b *BoxPlot) GlyphBoxes(plt *plot.Plot) []plot.GlyphBox { bs := make([]plot.GlyphBox, len(b.Outside)+1) for i, out := range b.Outside { bs[i].X = plt.X.Norm(b.Location) bs[i].Y = plt.Y.Norm(b.Value(out)) bs[i].Rect = b.GlyphStyle.Rect() } bs[len(bs)-1].X = plt.X.Norm(b.Location) bs[len(bs)-1].Y = plt.Y.Norm(b.Median) bs[len(bs)-1].Rect = plot.Rect{ Min: plot.Point{X: b.Offset - (b.Width/2 + b.BoxStyle.Width/2)}, Size: plot.Point{X: b.Width + b.BoxStyle.Width}, } return bs } // OutsideLabels returns a *Labels that will plot // a label for each of the outside points. The // labels are assumed to correspond to the // points used to create the box plot. func (b *BoxPlot) OutsideLabels(labels Labeller) (*Labels, error) { strs := make([]string, len(b.Outside)) for i, out := range b.Outside { strs[i] = labels.Label(out) } o := boxPlotOutsideLabels{b, strs} ls, err := NewLabels(o) if err != nil { return nil, err } ls.XOffset += b.GlyphStyle.Radius / 2 ls.YOffset += b.GlyphStyle.Radius / 2 return ls, nil } type boxPlotOutsideLabels struct { box *BoxPlot labels []string } func (o boxPlotOutsideLabels) Len() int { return len(o.box.Outside) } func (o boxPlotOutsideLabels) XY(i int) (float64, float64) { return o.box.Location, o.box.Value(o.box.Outside[i]) } func (o boxPlotOutsideLabels) Label(i int) string { return o.labels[i] } // HorizBoxPlot is like a regular BoxPlot, however, // it draws horizontally instead of Vertically. type HorizBoxPlot struct{ *BoxPlot } // MakeHorizBoxPlot returns a HorizBoxPlot, // plotting the values in a horizontal box plot // centered along a fixed location of the y axis. func MakeHorizBoxPlot(w vg.Length, loc float64, vs Valuer) (HorizBoxPlot, error) { b, err := NewBoxPlot(w, loc, vs) return HorizBoxPlot{b}, err } func (b HorizBoxPlot) Plot(da plot.DrawArea, plt *plot.Plot) { trX, trY := plt.Transforms(&da) y := trY(b.Location) if !da.ContainsY(y) { return } y += b.Offset med := trX(b.Median) q1 := trX(b.Quartile1) q3 := trX(b.Quartile3) aLow := trX(b.AdjLow) aHigh := trX(b.AdjHigh) box := da.ClipLinesX([]plot.Point{ {q1, y - b.Width/2}, {q3, y - b.Width/2}, {q3, y + b.Width/2}, {q1, y + b.Width/2}, {q1, y - b.Width/2 - b.BoxStyle.Width/2}, }) da.StrokeLines(b.BoxStyle, box...) medLine := da.ClipLinesX([]plot.Point{ {med, y - b.Width/2}, {med, y + b.Width/2}, }) da.StrokeLines(b.MedianStyle, medLine...) cap := b.CapWidth / 2 whisks := da.ClipLinesX([]plot.Point{{q3, y}, {aHigh, y}}, []plot.Point{{aHigh, y - cap}, {aHigh, y + cap}}, []plot.Point{{q1, y}, {aLow, y}}, []plot.Point{{aLow, y - cap}, {aLow, y + cap}}) da.StrokeLines(b.WhiskerStyle, whisks...) for _, out := range b.Outside { x := trX(b.Value(out)) if da.ContainsX(x) { da.DrawGlyphNoClip(b.GlyphStyle, plot.Pt(x, y)) } } } // DataRange returns the minimum and maximum x // and y values, implementing the plot.DataRanger // interface. func (b HorizBoxPlot) DataRange() (float64, float64, float64, float64) { return b.Min, b.Max, b.Location, b.Location } // GlyphBoxes returns a slice of GlyphBoxes for the // points and for the median line of the boxplot, // implementing the plot.GlyphBoxer interface func (b HorizBoxPlot) GlyphBoxes(plt *plot.Plot) []plot.GlyphBox { bs := make([]plot.GlyphBox, len(b.Outside)+1) for i, out := range b.Outside { bs[i].X = plt.X.Norm(b.Value(out)) bs[i].Y = plt.Y.Norm(b.Location) bs[i].Rect = b.GlyphStyle.Rect() } bs[len(bs)-1].X = plt.X.Norm(b.Median) bs[len(bs)-1].Y = plt.Y.Norm(b.Location) bs[len(bs)-1].Rect = plot.Rect{ Min: plot.Point{Y: b.Offset - (b.Width/2 + b.BoxStyle.Width/2)}, Size: plot.Point{Y: b.Width + b.BoxStyle.Width}, } return bs } // OutsideLabels returns a *Labels that will plot // a label for each of the outside points. The // labels are assumed to correspond to the // points used to create the box plot. func (b *HorizBoxPlot) OutsideLabels(labels Labeller) (*Labels, error) { strs := make([]string, len(b.Outside)) for i, out := range b.Outside { strs[i] = labels.Label(out) } o := horizBoxPlotOutsideLabels{ boxPlotOutsideLabels{b.BoxPlot, strs}, } ls, err := NewLabels(o) if err != nil { return nil, err } ls.XOffset += b.GlyphStyle.Radius / 2 ls.YOffset += b.GlyphStyle.Radius / 2 return ls, nil } type horizBoxPlotOutsideLabels struct { boxPlotOutsideLabels } func (o horizBoxPlotOutsideLabels) XY(i int) (float64, float64) { return o.box.Value(o.box.Outside[i]), o.box.Location }
src/code.google.com/p/plotinum/plotter/boxplot.go
0.779238
0.557845
boxplot.go
starcoder
package utils import ( "math" ) func Prod(values *SlidingWindow) (float64, error) { result := 1.0 for i := 0; i < values.Count(); i++ { result *= values.Data()[i] } return result, nil } func Add(x float64, values *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values.Count()) if err != nil { return nil, err } for i := 0; i < values.Count(); i++ { result.Add(values.Data()[i] + x) } return result, nil } func Add2(values1 *SlidingWindow, values2 *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values1.Count()) if err != nil { return nil, err } for i := 0; i < values1.Count(); i++ { result.Add(values1.Data()[i] + values2.Data()[i]) } return result, nil } func Sub(values1 *SlidingWindow, values2 *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values1.Count()) if err != nil { return nil, err } for i := 0; i < values1.Count(); i++ { result.Add(values1.Data()[i] - values2.Data()[i]) } return result, nil } func Multi(x float64, values *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values.Count()) if err != nil { return nil, err } for i := 0; i < values.Count(); i++ { result.Add(values.Data()[i] * x) } return result, nil } func Power(values *SlidingWindow, x float64) (*SlidingWindow, error) { result, err := NewSlidingWindow(values.Count()) if err != nil { return nil, err } for i := 0; i < values.Count(); i++ { result.Add(math.Pow(values.Data()[i], x)) } return result, nil } func CreateList(value float64, length int) (*SlidingWindow, error) { result, err := NewSlidingWindow(length) if err != nil { return nil, err } for i := 0; i < length; i++ { result.Add(value) } return result, nil } func Negative(values *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values.Count()) if err != nil { return nil, err } for i := 0; i < values.Count(); i++ { result.Add(-values.Data()[i]) } return result, nil } func ElementMulti(values1 *SlidingWindow, values2 *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values1.Count()) if err != nil { return nil, err } for i := 0; i < values1.Count(); i++ { result.Add(values1.Data()[i] * values2.Data()[i]) } return result, nil } func Log(values *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values.Count()) if err != nil { return nil, err } for i := 0; i < values.Count(); i++ { result.Add(math.Log(values.Data()[i])) } return result, nil } func Abs(values *SlidingWindow) (*SlidingWindow, error) { result, err := NewSlidingWindow(values.Count()) if err != nil { return nil, err } for i := 0; i < values.Count(); i++ { result.Add(math.Abs(values.Data()[i])) } return result, nil } // find out positive and negtive values func PosNegValues(values *SlidingWindow) (positivevalues, negativevalues *SlidingWindow, err error) { positivevalues, err = NewSlidingWindow(values.Count()) if err != nil { return } negativevalues, err = NewSlidingWindow(values.Count()) if err != nil { return } for i := 0; i < values.Count(); i++ { if values.Data()[i] > 0 { positivevalues.Add(values.Data()[i]) } else { negativevalues.Add(values.Data()[i]) } } return } func AboveValue(Ra *SlidingWindow, v float64) (*SlidingWindow, error) { r, err := NewSlidingWindow(Ra.Count()) if err != nil { return nil, err } for i := 0; i < Ra.Count(); i++ { if Ra.Data()[i] > v { r.Add(Ra.Data()[i]) } } return r, nil }
performance/utils/sliceoperation.go
0.524638
0.421135
sliceoperation.go
starcoder
package utils import ( "math/big" ) // this library provides a golang equivalent of the "BMath" contracts // see https://github.com/indexed-finance/indexed-core/blob/master/contracts/balancer/BNum.sol var ( // BONE ... bONE = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) // BPOWPRECISION ... BPOWPRECISION = new(big.Int).Div( BONE(), new(big.Int).Exp(big.NewInt(10), big.NewInt(10), nil), ) ) // BONE ... func BONE() *big.Int { return new(big.Int).Set(bONE) } // Btoi ... func Btoi(a *big.Int) *big.Int { return new(big.Int).Div(a, BONE()) } // Bfloor ... func Bfloor(a *big.Int) *big.Int { return new(big.Int).Mul(Btoi(a), BONE()) } // Badd ... func Badd(a, b *big.Int) *big.Int { return new(big.Int).Add(a, b) } // Bsub ... func Bsub(a, b *big.Int) *big.Int { c, _ := Bsubsign(a, b) return c } // Bsubsign ... func Bsubsign(a, b *big.Int) (*big.Int, bool) { compared := a.Cmp(b) if compared == 0 || compared == 1 { return new(big.Int).Sub(a, b), false } return new(big.Int).Sub(b, a), true } // Bmul ... func Bmul(a, b *big.Int) *big.Int { c0 := new(big.Int).Mul(a, b) c1 := new(big.Int).Add( c0, new(big.Int).Div(BONE(), big.NewInt(2)), ) return new(big.Int).Div(c1, BONE()) } // Bdiv ... // TODO(bonedaddy): right now we check for division by 0 and return 0 however this may not be good func Bdiv(a, b *big.Int) *big.Int { if b.Cmp(big.NewInt(0)) == 0 { return big.NewInt(0) } c0 := new(big.Int).Mul(a, BONE()) c1 := new(big.Int).Add( c0, new(big.Int).Div(b, big.NewInt(2)), ) return new(big.Int).Div(c1, b) } // Bpowi ... func Bpowi(a, n *big.Int) *big.Int { // s if n % 2 is not equal to 0, set z to a otherwise set z to BONE // uint256 z = n % 2 != 0 ? a : BONE; var z *big.Int compared := new(big.Int).Mod(n, big.NewInt(2)).Cmp(big.NewInt(0)) if compared != 0 { z = new(big.Int).Set(a) } else { z = new(big.Int).Set(BONE()) } for n.Div(n, big.NewInt(2)); n.Cmp(big.NewInt(0)) != 0; n.Div(n, big.NewInt(2)) { a = Bmul(a, a) if new(big.Int).Mod(n, big.NewInt(2)).Cmp(big.NewInt(0)) != 0 { z = Bmul(z, a) } } return z } // Bpow ... func Bpow(base, exp *big.Int) *big.Int { // TODO: error check according to // https://github.com/indexed-finance/indexed-core/blob/master/contracts/balancer/BNum.sol#L87-L88 whole := Bfloor(exp) remain := Bsub(exp, whole) wholePow := Bpowi(base, Btoi(whole)) if remain.Cmp(big.NewInt(0)) == 0 { return wholePow } partialResult := Bpowapprox(base, remain, BPOWPRECISION) return Bmul(wholePow, partialResult) } // Bpowapprox ... func Bpowapprox(base, exp, precision *big.Int) *big.Int { a := new(big.Int).Set(exp) x, xneg := Bsubsign(base, BONE()) term := new(big.Int).Set(BONE()) sum := new(big.Int).Set(term) negative := false for i := big.NewInt(1); term.Cmp(precision) == 0 || term.Cmp(precision) == 1; i.Add(i, big.NewInt(1)) { bigK := new(big.Int).Mul(i, BONE()) c, cneg := Bsubsign(a, Bsub(bigK, BONE())) term = Bmul(term, Bmul(c, x)) term = Bdiv(term, bigK) if term.Cmp(big.NewInt(0)) == 0 { break } if xneg { negative = !negative } if cneg { negative = !negative } if negative { sum = Bsub(sum, term) } else { sum = Badd(sum, term) } } return sum }
utils/bmath.go
0.603348
0.519156
bmath.go
starcoder
package ionossdk import ( "encoding/json" ) // KubernetesAutoScaling struct for KubernetesAutoScaling type KubernetesAutoScaling struct { // The minimum number of worker nodes that the managed node group can scale in. Should be set together with 'maxNodeCount'. Value for this attribute must be greater than equal to 1 and less than equal to maxNodeCount. MinNodeCount *int32 `json:"minNodeCount,omitempty"` // The maximum number of worker nodes that the managed node pool can scale-out. Should be set together with 'minNodeCount'. Value for this attribute must be greater than equal to 1 and minNodeCount. MaxNodeCount *int32 `json:"maxNodeCount,omitempty"` } // GetMinNodeCount returns the MinNodeCount field value // If the value is explicit nil, the zero value for int32 will be returned func (o *KubernetesAutoScaling) GetMinNodeCount() *int32 { if o == nil { return nil } return o.MinNodeCount } // GetMinNodeCountOk returns a tuple with the MinNodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *KubernetesAutoScaling) GetMinNodeCountOk() (*int32, bool) { if o == nil { return nil, false } return o.MinNodeCount, true } // SetMinNodeCount sets field value func (o *KubernetesAutoScaling) SetMinNodeCount(v int32) { o.MinNodeCount = &v } // HasMinNodeCount returns a boolean if a field has been set. func (o *KubernetesAutoScaling) HasMinNodeCount() bool { if o != nil && o.MinNodeCount != nil { return true } return false } // GetMaxNodeCount returns the MaxNodeCount field value // If the value is explicit nil, the zero value for int32 will be returned func (o *KubernetesAutoScaling) GetMaxNodeCount() *int32 { if o == nil { return nil } return o.MaxNodeCount } // GetMaxNodeCountOk returns a tuple with the MaxNodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *KubernetesAutoScaling) GetMaxNodeCountOk() (*int32, bool) { if o == nil { return nil, false } return o.MaxNodeCount, true } // SetMaxNodeCount sets field value func (o *KubernetesAutoScaling) SetMaxNodeCount(v int32) { o.MaxNodeCount = &v } // HasMaxNodeCount returns a boolean if a field has been set. func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { if o != nil && o.MaxNodeCount != nil { return true } return false } func (o KubernetesAutoScaling) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.MinNodeCount != nil { toSerialize["minNodeCount"] = o.MinNodeCount } if o.MaxNodeCount != nil { toSerialize["maxNodeCount"] = o.MaxNodeCount } return json.Marshal(toSerialize) } type NullableKubernetesAutoScaling struct { value *KubernetesAutoScaling isSet bool } func (v NullableKubernetesAutoScaling) Get() *KubernetesAutoScaling { return v.value } func (v *NullableKubernetesAutoScaling) Set(val *KubernetesAutoScaling) { v.value = val v.isSet = true } func (v NullableKubernetesAutoScaling) IsSet() bool { return v.isSet } func (v *NullableKubernetesAutoScaling) Unset() { v.value = nil v.isSet = false } func NewNullableKubernetesAutoScaling(val *KubernetesAutoScaling) *NullableKubernetesAutoScaling { return &NullableKubernetesAutoScaling{value: val, isSet: true} } func (v NullableKubernetesAutoScaling) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableKubernetesAutoScaling) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
cluster-autoscaler/cloudprovider/ionoscloud/ionos-cloud-sdk-go/model_kubernetes_auto_scaling.go
0.705582
0.441613
model_kubernetes_auto_scaling.go
starcoder
package tree import ( "fmt" "github.com/anchore/stereoscope/pkg/tree/node" ) // Tree represents a simple Tree data structure. type Tree struct { nodes map[node.ID]node.Node children map[node.ID]map[node.ID]node.Node parent map[node.ID]node.Node } // NewTree returns an instance of a Tree. func NewTree() *Tree { return &Tree{ nodes: make(map[node.ID]node.Node), children: make(map[node.ID]map[node.ID]node.Node), parent: make(map[node.ID]node.Node), } } func (t *Tree) Copy() *Tree { ct := NewTree() for k, v := range t.nodes { if v == nil { ct.nodes[k] = nil continue } ct.nodes[k] = v.Copy() } for k, v := range t.parent { if v == nil { ct.parent[k] = nil continue } ct.parent[k] = v.Copy() } for from, lookup := range t.children { if _, exists := ct.children[from]; !exists { ct.children[from] = make(map[node.ID]node.Node) } for to, v := range lookup { if v == nil { ct.children[from][to] = nil continue } ct.children[from][to] = v.Copy() } } return ct } // Roots is all of the nodes with no parents. func (t *Tree) Roots() node.Nodes { var nodes = make([]node.Node, 0) for _, n := range t.nodes { if parent := t.parent[n.ID()]; parent == nil { nodes = append(nodes, n) } } return nodes } // HasNode indicates is the given node ID exists in the Tree. func (t *Tree) HasNode(id node.ID) bool { if _, exists := t.nodes[id]; exists { return true } return false } // Node returns a node object for the given ID. func (t *Tree) Node(id node.ID) node.Node { return t.nodes[id] } // Nodes returns all nodes in the Tree. func (t *Tree) Nodes() node.Nodes { if len(t.nodes) == 0 { return nil } nodes := make([]node.Node, len(t.nodes)) i := 0 for _, n := range t.nodes { nodes[i] = n i++ } return nodes } // addNode adds the node to the Tree; returns an error on node ID collisions. func (t *Tree) addNode(n node.Node) error { if _, exists := t.nodes[n.ID()]; exists { return fmt.Errorf("node ID collision: %+v", n.ID()) } t.nodes[n.ID()] = n t.children[n.ID()] = make(map[node.ID]node.Node) t.parent[n.ID()] = nil return nil } // Replace takes the given old node and replaces it with the given new one. func (t *Tree) Replace(old node.Node, new node.Node) error { if !t.HasNode(old.ID()) { return fmt.Errorf("cannot replace node not in the Tree") } if old.ID() == new.ID() { // the underlying objects may be different, but the ID's match. Simply track the new [already existing] node // and keep all existing relationships. t.nodes[new.ID()] = new return nil } // add the new node err := t.addNode(new) if err != nil { return err } // set the new node parent to the old node parent t.parent[new.ID()] = t.parent[old.ID()] for cid := range t.children[old.ID()] { // replace the parent entry for each child t.parent[cid] = new // add child entries to the new node t.children[new.ID()][cid] = t.nodes[cid] } // replace the child entry for the old parents node delete(t.children[t.parent[old.ID()].ID()], old.ID()) t.children[t.parent[old.ID()].ID()][new.ID()] = new // remove the old node (if not already overwritten) if old.ID() != new.ID() { delete(t.children, old.ID()) delete(t.nodes, old.ID()) delete(t.parent, old.ID()) } return nil } // AddRoot adds a node to the Tree (with no parent). func (t *Tree) AddRoot(n node.Node) error { return t.addNode(n) } // AddChild adds a node to the Tree under the given parent. func (t *Tree) AddChild(from, to node.Node) error { var ( fid = from.ID() tid = to.ID() err error ) if fid == tid { return fmt.Errorf("should not add self edge") } if _, ok := t.nodes[fid]; !ok { err = t.addNode(from) if err != nil { return err } } else { t.nodes[fid] = from } if _, ok := t.nodes[tid]; !ok { err = t.addNode(to) if err != nil { return err } } else { t.nodes[tid] = to } t.children[fid][tid] = to t.parent[tid] = from return nil } // RemoveNode deletes the node from the Tree and returns the removed node. func (t *Tree) RemoveNode(n node.Node) (node.Nodes, error) { removedNodes := make([]node.Node, 0) nid := n.ID() if _, ok := t.nodes[nid]; !ok { return nil, fmt.Errorf("unable to remove node: %+v", nid) } for _, child := range t.children[nid] { subNodes, err := t.RemoveNode(child) for _, sn := range subNodes { removedNodes = append(removedNodes, sn) } if err != nil { return nil, err } } removedNodes = append(removedNodes, t.nodes[nid]) delete(t.children, nid) if t.parent[nid] != nil { delete(t.children[t.parent[nid].ID()], nid) } delete(t.parent, nid) delete(t.nodes, nid) return removedNodes, nil } // Children returns all children of the given node. func (t *Tree) Children(n node.Node) node.Nodes { nid := n.ID() if _, ok := t.children[nid]; !ok { return nil } if len(t.children) == 0 { return nil } from := make([]node.Node, len(t.children[nid])) i := 0 for vid := range t.children[nid] { from[i] = t.nodes[vid] i++ } return from } // Parent returns the parent of the given node (or nil if it is a root) func (t *Tree) Parent(n node.Node) node.Node { if parent, ok := t.parent[n.ID()]; ok { return parent } return nil } func (t *Tree) Length() int { return len(t.nodes) }
pkg/tree/tree.go
0.776708
0.545709
tree.go
starcoder
package trisnake import ( tl "github.com/JoelOtter/termloop" ) // NewSnake will create a new snake and is called when the game is initialized. func NewSnake() *Snake { snake := new(Snake) // Create a new entity for a 1x1 pixel. snake.Entity = tl.NewEntity(5, 5, 1, 1) // Sets a standard direction to right, do not change this to up or left as the snake. // will crash into a wall right after the game starts. snake.Direction = right // Creates a snake containing of 3 entities with the given coordinates. snake.Bodylength = []Coordinates{ {1, 6}, // Tail (The tail of the snake will stay the same unless the snake is not colliding with food) {2, 6}, // Body (The body will grow taller when a new head is created, the last piece of the body will become the tail if there is no collision with food) {3, 6}, // Head (Will become a piece of the body when a new head is created) } return snake } // Head is the snake head which is used to move the snake around. // The head is also the hitbox for food, border and the snake itself. func (snake *Snake) Head() *Coordinates { return &snake.Bodylength[len(snake.Bodylength)-1] } // BorderCollision checks if the arena border contains the snakes head, if so it will return true. func (snake *Snake) BorderCollision() bool { return gs.ArenaEntity.Contains(*snake.Head()) } // FoodCollision checks if the food contains the snakes head, if so it will return true. func (snake *Snake) FoodCollision() bool { return gs.FoodEntity.Contains(*snake.Head()) } // SnakeCollision checks if the snakes body contains its head, if so it will return true. func (snake *Snake) SnakeCollision() bool { return snake.Contains() } // Draw will check every tick and draw the snake on the screen, it also checks if the snake has any collisions // using the funtions above. func (snake *Snake) Draw(screen *tl.Screen) { // This will create a new head give the direction the snake is heading. nHead := *snake.Head() // Checks the current direction of the snake. switch snake.Direction { // If the snakedirection is up, the snake will move up every tick. case up: // The Y coorddinates will be lowered, making the snake move up. nHead.Y-- // If the snakedirection is down, the snake will move down every tick. case down: // The Y coorddinates will be incresed, making the snake move down. nHead.Y++ // If the snakedirection is left, the snake will move left every tick. case left: // The X coorddinates will be lowered, making the snake move left. nHead.X-- // If the snakedirection is right, the snake will move right every tick. case right: // The X coorddinates will be incresed, making the snake move right. nHead.X++ } // Checks for a food collision using the collision function. if snake.FoodCollision() { // This switch case checks if the food emoji is a special kind of food switch gs.FoodEntity.Emoji { case 'R': switch ts.GameDifficulty { case easy: if gs.FPS-3 <= 8 { UpdateScore(5) } else { gs.FPS -= 3 UpdateScore(5) UpdateFPS() } case normal: if gs.FPS-2 <= 12 { UpdateScore(5) } else { gs.FPS -= 2 UpdateScore(5) UpdateFPS() } case hard: if gs.FPS-1 <= 20 { UpdateScore(5) } else { gs.FPS-- UpdateScore(5) UpdateFPS() } } snake.Bodylength = append(snake.Bodylength, nHead) case 'S': switch ts.GameDifficulty { case easy: gs.FPS++ case normal: gs.FPS += 3 case hard: gs.FPS += 5 } UpdateFPS() default: UpdateScore(1) snake.Bodylength = append(snake.Bodylength, nHead) } // If there is a food collision the food it will call the MoveFood function to move the food gs.FoodEntity.MoveFood() } else { // If there is no collision with food the snake will add the new head but exclude the tail from the body // keeping the snake the same size as before. snake.Bodylength = append(snake.Bodylength[1:], nHead) } // The position of the snake will be moved after the new heads coordinates. snake.SetPosition(nHead.X, nHead.Y) // Check if the snake is colliding with the border or itself using the collision functions. if snake.BorderCollision() || snake.SnakeCollision() { // Calls the GameOver function to take the player to the game over screen. Gameover() } // This for loop will range over the snakebody and print out the snake given the body coordinates. // This will update every tick so the snake keeps moving. for _, c := range snake.Bodylength { screen.RenderCell(c.X, c.Y, &tl.Cell{ Fg: CheckSelectedColor(counterSnake), Ch: '░', }) } } // Contains checks if the snake contains the head of the snake, if so it will return true. func (snake *Snake) Contains() bool { // This for loop will check if the head is in any part of the body. for i := 0; i < len(snake.Bodylength)-1; i++ { // If the head is in any part of the body, it will return true. if *snake.Head() == snake.Bodylength[i] { return true } } // It will return false if the snake is not colliding with itself. return false }
game/snake.go
0.78838
0.41745
snake.go
starcoder
package models import ( "encoding/json" "fmt" "time" ) type ( // DeviceDisconnectBehavior defines the disconnection behavior of the simulated device. DeviceDisconnectBehavior string // TelemetryFormat defines the format of the telemetry messages sent from the simulated device. TelemetryFormat string // SimulationStatus specifies the current status of the simulation. SimulationStatus string // SimulationDeviceConfig defines the device configuration for a simulation. SimulationDeviceConfig struct { ID string `json:"id"` // the id of the configuration ModelID string `json:"modelId"` // the model to simulate. DeviceCount int `json:"deviceCount"` // the total no. of devices to simulate. } // Simulation definition. Simulation struct { ID string `json:"id"` // the id of the simulation. Name string `json:"name"` // the name of the simulation. TargetID string `json:"targetId"` // the id of the target application against which the simulation is running. Status SimulationStatus `json:"status"` // current status of the simulation. WaveGroupCount int `json:"waveGroupCount"` // no. of device groups in a wave in which the total devices are distributed. WaveGroupInterval int `json:"waveGroupInterval"` // interval between wave groups when simulating. TelemetryBatchSize int `json:"telemetryBatchSize"` // batch of telemetry messages that each device will send. TelemetryInterval int `json:"telemetryInterval"` // interval to wait between sending telemetry messages. ReportedPropsInterval int `json:"reportedPropertyInterval"` // interval to wait between sending reported properties. DisconnectBehavior DeviceDisconnectBehavior `json:"disconnectBehavior"` // device connection behavior. TelemetryFormat TelemetryFormat `json:"telemetryFormat"` // format of telemetry messages. LastUpdatedTime time.Time `json:"lastUpdatedTime"` // when the status was last updated } // SimulationViewDeviceConfig defines the device configuration for a simulation view. SimulationViewDeviceConfig struct { ID string `json:"id"` // the id of the configuration ModelID string `json:"modelId"` // the model to simulate. ProvisionedCount int `json:"provisionedCount"` // number of provisioned devices. SimulatedCount int `json:"simulatedCount"` // number of devices to simulate. ConnectedCount int `json:"connectedCount"` // number of devices currently connected. } SimulationView struct { Simulation // simulation configuration Devices []SimulationViewDeviceConfig `json:"devices"` // devices configurations } ) const ( // SimulationStatusReady specifies that the simulation is ready to run or provision devices. SimulationStatusReady SimulationStatus = "ready" // SimulationStatusRunning specifies that the simulation is running. SimulationStatusRunning SimulationStatus = "running" // SimulationStatusProvisioning specifies that the simulation is provisioning devices. SimulationStatusProvisioning SimulationStatus = "provisioning" // SimulationStatusDeleting specifies that the devices in the simulation are getting deleted. SimulationStatusDeleting SimulationStatus = "deleting" // DeviceDisconnectNever specifies that the device should never disconnect. DeviceDisconnectNever DeviceDisconnectBehavior = "never" // DeviceDisconnectAfterTelemetrySend specifies that the device should disconnect after sending telemetry. DeviceDisconnectAfterTelemetrySend DeviceDisconnectBehavior = "telemetry" // TelemetryFormatDefault specifies that the device sends telemetry in default JSON format. TelemetryFormatDefault TelemetryFormat = "default" // TelemetryFormatOpcua specifies that the device sends telemetry in opcua JSON format. TelemetryFormatOpcua TelemetryFormat = "opcua" ) // UnmarshalJSON handles the un-marshalling of simulation status func (status *SimulationStatus) UnmarshalJSON(b []byte) error { var p string if err := json.Unmarshal(b, &p); err != nil { return err } if p == "" { return nil } // backward compat if p == "created" || p == "stopped" { p = "ready" } s := SimulationStatus(p) switch s { case SimulationStatusReady, SimulationStatusRunning, SimulationStatusProvisioning, SimulationStatusDeleting: *status = s return nil default: return fmt.Errorf("invalid simulation status type %s", p) } } // UnmarshalJSON handles the un-marshalling of device disconnect behavior. func (d *DeviceDisconnectBehavior) UnmarshalJSON(b []byte) error { var p string if err := json.Unmarshal(b, &p); err != nil { return err } if p == "" { return nil } s := DeviceDisconnectBehavior(p) switch s { case DeviceDisconnectNever, DeviceDisconnectAfterTelemetrySend: *d = s return nil default: return fmt.Errorf("invalid device disconnect type %s", p) } } // UnmarshalJSON handles the un-marshalling of telemetry format func (tf *TelemetryFormat) UnmarshalJSON(b []byte) error { var p string if err := json.Unmarshal(b, &p); err != nil { return err } if p == "" { return nil } s := TelemetryFormat(p) switch s { case TelemetryFormatDefault, TelemetryFormatOpcua: *tf = s return nil default: return fmt.Errorf("invalid telemetry format type %s", p) } }
pkg/models/simulation.go
0.743541
0.40751
simulation.go
starcoder
package asyncjobs import ( "context" "math/rand" "time" ) // RetryPolicy defines a period that failed jobs will be retried against type RetryPolicy struct { // Intervals is a range of time periods backoff will be based off Intervals []time.Duration // Jitter is a factor applied to the specific interval avoid repeating same backoff periods Jitter float64 } var ( // RetryLinearTenMinutes is a 20-step policy between 1 and 10 minutes RetryLinearTenMinutes = linearPolicy(20, 0.90, time.Minute, 10*time.Minute) // RetryLinearOneHour is a 50-step policy between 10 minutes and 1 hour RetryLinearOneHour = linearPolicy(20, 0.90, 10*time.Minute, 60*time.Minute) // RetryLinearOneMinute is a 20-step policy between 1 second and 1 minute RetryLinearOneMinute = linearPolicy(20, 0.5, time.Second, time.Minute) // RetryDefault is the default retry policy RetryDefault = RetryLinearTenMinutes retryLinearTenSeconds = linearPolicy(20, 0.1, 500*time.Millisecond, 10*time.Second) retryForTesting = linearPolicy(1, 0.1, time.Millisecond, 10*time.Millisecond) ) // Duration is the period to sleep for try n, it includes a jitter func (b RetryPolicy) Duration(n int) time.Duration { if n >= len(b.Intervals) { n = len(b.Intervals) - 1 } delay := b.jitter(b.Intervals[n]) if delay == 0 { delay = b.Intervals[0] } return delay } // Sleep attempts to sleep for the relevant duration for n, interruptable by ctx func (b RetryPolicy) Sleep(ctx context.Context, n int) error { timer := time.NewTimer(b.Duration(n)) select { case <-timer.C: return nil case <-ctx.Done(): timer.Stop() return ctx.Err() } } func linearPolicy(steps uint64, jitter float64, min time.Duration, max time.Duration) RetryPolicy { if max < min { max, min = min, max } p := RetryPolicy{ Intervals: []time.Duration{}, Jitter: jitter, } stepSize := uint64(max-min) / steps for i := uint64(0); i < steps; i += 1 { p.Intervals = append(p.Intervals, time.Duration(uint64(min)+(i*stepSize))) } return p } func (b RetryPolicy) jitter(d time.Duration) time.Duration { if d == 0 { return 0 } jf := (float64(d) * b.Jitter) + float64(rand.Int63n(int64(d))) return time.Duration(jf).Round(time.Millisecond) }
retrypolicy.go
0.727685
0.543469
retrypolicy.go
starcoder
package execute import ( "context" "fmt" "github.com/influxdata/flux" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/plan" ) // Transformation represents functions that stream a set of tables, performs // data processing on them and produces an output stream of tables type Transformation interface { RetractTable(id DatasetID, key flux.GroupKey) error // Process takes in one flux Table, performs data processing on it and // writes that table to a DataCache Process(id DatasetID, tbl flux.Table) error UpdateWatermark(id DatasetID, t Time) error UpdateProcessingTime(id DatasetID, t Time) error // Finish indicates that the Transformation is done processing. It is // the last method called on the Transformation Finish(id DatasetID, err error) } // TransformationSet is a group of transformations. type TransformationSet []Transformation func (ts TransformationSet) RetractTable(id DatasetID, key flux.GroupKey) error { for _, t := range ts { if err := t.RetractTable(id, key); err != nil { return err } } return nil } func (ts TransformationSet) Process(id DatasetID, tbl flux.Table) error { if len(ts) == 0 { return nil } else if len(ts) == 1 { return ts[0].Process(id, tbl) } // There is more than one transformation so we need to // copy the table for each transformation. bufTable, err := CopyTable(tbl) if err != nil { return err } defer bufTable.Done() for _, t := range ts { if err := t.Process(id, bufTable.Copy()); err != nil { return err } } return nil } func (ts TransformationSet) UpdateWatermark(id DatasetID, time Time) error { for _, t := range ts { if err := t.UpdateWatermark(id, time); err != nil { return err } } return nil } func (ts TransformationSet) UpdateProcessingTime(id DatasetID, time Time) error { for _, t := range ts { if err := t.UpdateProcessingTime(id, time); err != nil { return err } } return nil } func (ts TransformationSet) Finish(id DatasetID, err error) { for _, t := range ts { t.Finish(id, err) } } // StreamContext represents necessary context for a single stream of // query data. type StreamContext interface { Bounds() *Bounds } type Administration interface { Context() context.Context ResolveTime(qt flux.Time) Time StreamContext() StreamContext Allocator() memory.Allocator Parents() []DatasetID ParallelOpts() ParallelOpts } type CreateTransformation func(id DatasetID, mode AccumulationMode, spec plan.ProcedureSpec, a Administration) (Transformation, Dataset, error) var procedureToTransformation = make(map[plan.ProcedureKind]CreateTransformation) // RegisterTransformation adds a new registration mapping of procedure kind to transformation. func RegisterTransformation(k plan.ProcedureKind, c CreateTransformation) { if procedureToTransformation[k] != nil { panic(fmt.Errorf("duplicate registration for transformation with procedure kind %v", k)) } procedureToTransformation[k] = c } // ReplaceTransformation changes an existing transformation registration. func ReplaceTransformation(k plan.ProcedureKind, c CreateTransformation) { if procedureToTransformation[k] == nil { panic(fmt.Errorf("missing registration for transformation with procedure kind %v", k)) } procedureToTransformation[k] = c }
execute/transformation.go
0.705785
0.403038
transformation.go
starcoder
package mysql_db import ( "sort" "strings" "github.com/dolthub/go-mysql-server/sql" ) // PrivilegeSet is a set containing privileges. Due to the nested sets potentially returning empty sets, this also acts // as the singular location to modify all nested sets. type PrivilegeSet struct { globalStatic map[sql.PrivilegeType]struct{} globalDynamic map[string]struct{} databases map[string]PrivilegeSetDatabase } // NewPrivilegeSet returns a new PrivilegeSet. func NewPrivilegeSet() PrivilegeSet { return PrivilegeSet{ make(map[sql.PrivilegeType]struct{}), make(map[string]struct{}), make(map[string]PrivilegeSetDatabase), } } // newPrivilegeSetWithAllPrivileges returns a new PrivilegeSet with every global static privilege added. func newPrivilegeSetWithAllPrivileges() PrivilegeSet { return PrivilegeSet{ map[sql.PrivilegeType]struct{}{ sql.PrivilegeType_Select: {}, sql.PrivilegeType_Insert: {}, sql.PrivilegeType_Update: {}, sql.PrivilegeType_Delete: {}, sql.PrivilegeType_Create: {}, sql.PrivilegeType_Drop: {}, sql.PrivilegeType_Reload: {}, sql.PrivilegeType_Shutdown: {}, sql.PrivilegeType_Process: {}, sql.PrivilegeType_File: {}, sql.PrivilegeType_Grant: {}, sql.PrivilegeType_References: {}, sql.PrivilegeType_Index: {}, sql.PrivilegeType_Alter: {}, sql.PrivilegeType_ShowDB: {}, sql.PrivilegeType_Super: {}, sql.PrivilegeType_CreateTempTable: {}, sql.PrivilegeType_LockTables: {}, sql.PrivilegeType_Execute: {}, sql.PrivilegeType_ReplicationSlave: {}, sql.PrivilegeType_ReplicationClient: {}, sql.PrivilegeType_CreateView: {}, sql.PrivilegeType_ShowView: {}, sql.PrivilegeType_CreateRoutine: {}, sql.PrivilegeType_AlterRoutine: {}, sql.PrivilegeType_CreateUser: {}, sql.PrivilegeType_Event: {}, sql.PrivilegeType_Trigger: {}, sql.PrivilegeType_CreateTablespace: {}, sql.PrivilegeType_CreateRole: {}, sql.PrivilegeType_DropRole: {}, }, make(map[string]struct{}), make(map[string]PrivilegeSetDatabase), } } // AddGlobalStatic adds the given global static privilege(s). func (ps PrivilegeSet) AddGlobalStatic(privileges ...sql.PrivilegeType) { for _, priv := range privileges { ps.globalStatic[priv] = struct{}{} } } // AddGlobalDynamic adds the given global dynamic privilege(s). func (ps PrivilegeSet) AddGlobalDynamic(privileges ...string) { for _, priv := range privileges { ps.globalDynamic[priv] = struct{}{} } } // AddDatabase adds the given database privilege(s). func (ps PrivilegeSet) AddDatabase(dbName string, privileges ...sql.PrivilegeType) { dbSet := ps.getUseableDb(dbName) for _, priv := range privileges { dbSet.privs[priv] = struct{}{} } } // AddTable adds the given table privilege(s). func (ps PrivilegeSet) AddTable(dbName string, tblName string, privileges ...sql.PrivilegeType) { tblSet := ps.getUseableDb(dbName).getUseableTbl(tblName) for _, priv := range privileges { tblSet.privs[priv] = struct{}{} } } // AddColumn adds the given column privilege(s). func (ps PrivilegeSet) AddColumn(dbName string, tblName string, colName string, privileges ...sql.PrivilegeType) { colSet := ps.getUseableDb(dbName).getUseableTbl(tblName).getUseableCol(colName) for _, priv := range privileges { colSet.privs[priv] = struct{}{} } } // RemoveGlobalStatic removes the given global static privilege(s). func (ps PrivilegeSet) RemoveGlobalStatic(privileges ...sql.PrivilegeType) { for _, priv := range privileges { delete(ps.globalStatic, priv) } } // RemoveGlobalDynamic removes the given global dynamic privilege(s). func (ps PrivilegeSet) RemoveGlobalDynamic(privileges ...string) { for _, priv := range privileges { delete(ps.globalDynamic, priv) } } // RemoveDatabase removes the given database privilege(s). func (ps PrivilegeSet) RemoveDatabase(dbName string, privileges ...sql.PrivilegeType) { // We don't use the getUseableDb function since we don't want to create a new map if it doesn't already exist dbSet := ps.Database(dbName) if len(dbSet.privs) > 0 { for _, priv := range privileges { delete(dbSet.privs, priv) } } } // RemoveTable removes the given table privilege(s). func (ps PrivilegeSet) RemoveTable(dbName string, tblName string, privileges ...sql.PrivilegeType) { // We don't use the getUseable functions since we don't want to create new maps if they don't already exist tblSet := ps.Database(dbName).Table(tblName) if len(tblSet.privs) > 0 { for _, priv := range privileges { delete(tblSet.privs, priv) } } } // RemoveColumn removes the given column privilege(s). func (ps PrivilegeSet) RemoveColumn(dbName string, tblName string, colName string, privileges ...sql.PrivilegeType) { // We don't use the getUseable functions since we don't want to create new maps if they don't already exist colSet := ps.Database(dbName).Table(tblName).Column(colName) if len(colSet.privs) > 0 { for _, priv := range privileges { delete(colSet.privs, priv) } } } // Has returns whether the given global static privilege(s) exists. func (ps PrivilegeSet) Has(privileges ...sql.PrivilegeType) bool { for _, priv := range privileges { if _, ok := ps.globalStatic[priv]; !ok { return false } } return true } // HasPrivileges returns whether this PrivilegeSet has any privileges at any level. func (ps PrivilegeSet) HasPrivileges() bool { if len(ps.globalStatic) > 0 || len(ps.globalDynamic) > 0 { return true } for _, dbSet := range ps.databases { if dbSet.HasPrivileges() { return true } } return false } // GlobalCount returns the combined number of global static and global dynamic privileges. func (ps PrivilegeSet) GlobalCount() int { return len(ps.globalStatic) + len(ps.globalDynamic) } // StaticCount returns the number of global static privileges, while not including global dynamic privileges. func (ps PrivilegeSet) StaticCount() int { return len(ps.globalStatic) } // Database returns the set of privileges for the given database. Returns an empty set if the database does not exist. func (ps PrivilegeSet) Database(dbName string) PrivilegeSetDatabase { dbSet, ok := ps.databases[strings.ToLower(dbName)] if ok { return dbSet } return PrivilegeSetDatabase{name: dbName} } // GetDatabases returns all databases. func (ps PrivilegeSet) GetDatabases() []PrivilegeSetDatabase { dbSets := make([]PrivilegeSetDatabase, len(ps.databases)) i := 0 for _, dbSet := range ps.databases { // Only return databases that have a database-level privilege, or a privilege on an underlying table or column. // Otherwise, there is no difference between the returned database and the zero-value for any database. if dbSet.HasPrivileges() { dbSets[i] = dbSet i++ } } sort.Slice(dbSets, func(i, j int) bool { return dbSets[i].name < dbSets[j].name }) return dbSets } // UnionWith merges the given set of privileges to the calling set of privileges. func (ps PrivilegeSet) UnionWith(other PrivilegeSet) { for priv := range other.globalStatic { ps.globalStatic[priv] = struct{}{} } for priv := range other.globalDynamic { ps.globalDynamic[priv] = struct{}{} } for _, otherDbSet := range other.databases { ps.getUseableDb(otherDbSet.name).unionWith(otherDbSet) } } // ClearGlobal removes all global privileges. func (ps *PrivilegeSet) ClearGlobal() { ps.globalStatic = make(map[sql.PrivilegeType]struct{}) ps.globalDynamic = make(map[string]struct{}) } // ClearDatabase removes all privileges for the given database. func (ps PrivilegeSet) ClearDatabase(dbName string) { ps.getUseableDb(dbName).clear() } // ClearTable removes all privileges for the given table. func (ps PrivilegeSet) ClearTable(dbName string, tblName string) { ps.getUseableDb(dbName).getUseableTbl(tblName).clear() } // ClearColumn removes all privileges for the given column. func (ps PrivilegeSet) ClearColumn(dbName string, tblName string, colName string) { ps.getUseableDb(dbName).getUseableTbl(tblName).getUseableCol(colName).clear() } // ClearAll removes all privileges. func (ps *PrivilegeSet) ClearAll() { ps.globalStatic = make(map[sql.PrivilegeType]struct{}) ps.globalDynamic = make(map[string]struct{}) ps.databases = make(map[string]PrivilegeSetDatabase) } // Equals returns whether the given set of privileges is equivalent to the calling set. func (ps PrivilegeSet) Equals(otherPs PrivilegeSet) bool { if len(ps.globalStatic) != len(otherPs.globalStatic) || len(ps.globalDynamic) != len(otherPs.globalDynamic) || len(ps.databases) != len(otherPs.databases) { return false } for priv := range ps.globalStatic { if _, ok := otherPs.globalStatic[priv]; !ok { return false } } for priv := range ps.globalDynamic { if _, ok := otherPs.globalDynamic[priv]; !ok { return false } } for dbName, dbSet := range ps.databases { if !dbSet.Equals(otherPs.databases[dbName]) { return false } } return true } // Copy returns a duplicate of the calling PrivilegeSet. func (ps PrivilegeSet) Copy() PrivilegeSet { newPs := NewPrivilegeSet() newPs.UnionWith(ps) return newPs } // ToSlice returns all of the global static privileges contained as a slice. Some operations do not care about sort // order, therefore this is presented as an alternative to skip the unnecessary sort operation. func (ps PrivilegeSet) ToSlice() []sql.PrivilegeType { privs := make([]sql.PrivilegeType, len(ps.globalStatic)) i := 0 for priv := range ps.globalStatic { privs[i] = priv i++ } return privs } // ToSortedSlice returns all of the global static privileges contained as a slice, sorted by their internal ID. func (ps PrivilegeSet) ToSortedSlice() []sql.PrivilegeType { privs := ps.ToSlice() sort.Slice(privs, func(i, j int) bool { return privs[i] < privs[j] }) return privs } // getUseableDb is used internally to either retrieve an existing database, or create a new one that is returned. func (ps PrivilegeSet) getUseableDb(dbName string) PrivilegeSetDatabase { lowerDbName := strings.ToLower(dbName) dbSet, ok := ps.databases[lowerDbName] if !ok { dbSet = PrivilegeSetDatabase{ name: dbName, privs: make(map[sql.PrivilegeType]struct{}), tables: make(map[string]PrivilegeSetTable), } ps.databases[lowerDbName] = dbSet } return dbSet } // PrivilegeSetDatabase is a set containing database-level privileges. type PrivilegeSetDatabase struct { name string privs map[sql.PrivilegeType]struct{} tables map[string]PrivilegeSetTable } // Name returns the name of the database that this privilege set belongs to. func (ps PrivilegeSetDatabase) Name() string { return ps.name } // Has returns whether the given database privilege(s) exists. func (ps PrivilegeSetDatabase) Has(privileges ...sql.PrivilegeType) bool { for _, priv := range privileges { if _, ok := ps.privs[priv]; !ok { return false } } return true } // HasPrivileges returns whether this database has either database-level privileges, or privileges on a table or column // contained within this database. func (ps PrivilegeSetDatabase) HasPrivileges() bool { if len(ps.privs) > 0 { return true } for _, tblSet := range ps.tables { if tblSet.HasPrivileges() { return true } } return false } // Count returns the number of database privileges. func (ps PrivilegeSetDatabase) Count() int { return len(ps.privs) } // Table returns the set of privileges for the given table. Returns an empty set if the table does not exist. func (ps PrivilegeSetDatabase) Table(tblName string) PrivilegeSetTable { tblSet, ok := ps.tables[strings.ToLower(tblName)] if ok { return tblSet } return PrivilegeSetTable{name: tblName} } // GetTables returns all tables. func (ps PrivilegeSetDatabase) GetTables() []PrivilegeSetTable { tblSets := make([]PrivilegeSetTable, len(ps.tables)) i := 0 for _, tblSet := range ps.tables { // Only return tables that have a table-level privilege, or a privilege on an underlying column. // Otherwise, there is no difference between the returned table and the zero-value for any table. if tblSet.HasPrivileges() { tblSets[i] = tblSet i++ } } sort.Slice(tblSets, func(i, j int) bool { return tblSets[i].name < tblSets[j].name }) return tblSets } // Equals returns whether the given set of privileges is equivalent to the calling set. func (ps PrivilegeSetDatabase) Equals(otherPs PrivilegeSetDatabase) bool { if len(ps.privs) != len(otherPs.privs) || len(ps.tables) != len(otherPs.tables) { return false } for priv := range ps.privs { if _, ok := otherPs.privs[priv]; !ok { return false } } for tblName, tblSet := range ps.tables { if !tblSet.Equals(otherPs.tables[tblName]) { return false } } return true } // ToSlice returns all of the database privileges contained as a slice. Some operations do not care about sort order, // therefore this is presented as an alternative to skip the unnecessary sort operation. func (ps PrivilegeSetDatabase) ToSlice() []sql.PrivilegeType { privs := make([]sql.PrivilegeType, len(ps.privs)) i := 0 for priv := range ps.privs { privs[i] = priv i++ } return privs } // ToSortedSlice returns all of the database privileges contained as a slice, sorted by their internal ID. func (ps PrivilegeSetDatabase) ToSortedSlice() []sql.PrivilegeType { privs := ps.ToSlice() sort.Slice(privs, func(i, j int) bool { return privs[i] < privs[j] }) return privs } // getUseableTbl is used internally to either retrieve an existing table, or create a new one that is returned. func (ps PrivilegeSetDatabase) getUseableTbl(tblName string) PrivilegeSetTable { lowerTblName := strings.ToLower(tblName) tblSet, ok := ps.tables[lowerTblName] if !ok { tblSet = PrivilegeSetTable{ name: tblName, privs: make(map[sql.PrivilegeType]struct{}), columns: make(map[string]PrivilegeSetColumn), } ps.tables[lowerTblName] = tblSet } return tblSet } // unionWith merges the given set of privileges to the calling set of privileges. func (ps PrivilegeSetDatabase) unionWith(otherPs PrivilegeSetDatabase) { for priv := range otherPs.privs { ps.privs[priv] = struct{}{} } for _, otherTblSet := range otherPs.tables { ps.getUseableTbl(otherTblSet.name).unionWith(otherTblSet) } } // clear removes all database privileges. func (ps PrivilegeSetDatabase) clear() { for priv := range ps.privs { delete(ps.privs, priv) } } // PrivilegeSetTable is a set containing table-level privileges. type PrivilegeSetTable struct { name string privs map[sql.PrivilegeType]struct{} columns map[string]PrivilegeSetColumn } // Name returns the name of the table that this privilege set belongs to. func (ps PrivilegeSetTable) Name() string { return ps.name } // Has returns whether the given table privilege(s) exists. func (ps PrivilegeSetTable) Has(privileges ...sql.PrivilegeType) bool { for _, priv := range privileges { if _, ok := ps.privs[priv]; !ok { return false } } return true } // HasPrivileges returns whether this table has either table-level privileges, or privileges on a column contained // within this table. func (ps PrivilegeSetTable) HasPrivileges() bool { if len(ps.privs) > 0 { return true } for _, colSet := range ps.columns { if colSet.Count() > 0 { return true } } return false } // Count returns the number of table privileges. func (ps PrivilegeSetTable) Count() int { return len(ps.privs) } // Column returns the set of privileges for the given column. Returns an empty set if the column does not exist. func (ps PrivilegeSetTable) Column(colName string) PrivilegeSetColumn { colSet, ok := ps.columns[strings.ToLower(colName)] if ok { return colSet } return PrivilegeSetColumn{name: colName} } // GetColumns returns all columns. func (ps PrivilegeSetTable) GetColumns() []PrivilegeSetColumn { colSets := make([]PrivilegeSetColumn, len(ps.columns)) i := 0 for _, colSet := range ps.columns { // Only return columns that have privileges. Otherwise, there is no difference between the returned column and // the zero-value for any column. if colSet.Count() > 0 { colSets[i] = colSet i++ } } sort.Slice(colSets, func(i, j int) bool { return colSets[i].name < colSets[j].name }) return colSets } // Equals returns whether the given set of privileges is equivalent to the calling set. func (ps PrivilegeSetTable) Equals(otherPs PrivilegeSetTable) bool { if len(ps.privs) != len(otherPs.privs) || len(ps.columns) != len(otherPs.columns) { return false } for priv := range ps.privs { if _, ok := otherPs.privs[priv]; !ok { return false } } for colName, colSet := range ps.columns { if !colSet.Equals(otherPs.columns[colName]) { return false } } return true } // ToSlice returns all of the table privileges contained as a slice. Some operations do not care about sort order, // therefore this is presented as an alternative to skip the unnecessary sort operation. func (ps PrivilegeSetTable) ToSlice() []sql.PrivilegeType { privs := make([]sql.PrivilegeType, len(ps.privs)) i := 0 for priv := range ps.privs { privs[i] = priv i++ } return privs } // ToSortedSlice returns all of the table privileges contained as a slice, sorted by their internal ID. func (ps PrivilegeSetTable) ToSortedSlice() []sql.PrivilegeType { privs := ps.ToSlice() sort.Slice(privs, func(i, j int) bool { return privs[i] < privs[j] }) return privs } // getUseableCol is used internally to either retrieve an existing column, or create a new one that is returned. func (ps PrivilegeSetTable) getUseableCol(colName string) PrivilegeSetColumn { lowerColName := strings.ToLower(colName) colSet, ok := ps.columns[lowerColName] if !ok { colSet = PrivilegeSetColumn{ name: colName, privs: make(map[sql.PrivilegeType]struct{}), } ps.columns[lowerColName] = colSet } return colSet } // unionWith merges the given set of privileges to the calling set of privileges. func (ps PrivilegeSetTable) unionWith(otherPs PrivilegeSetTable) { for priv := range otherPs.privs { ps.privs[priv] = struct{}{} } for _, otherColSet := range otherPs.columns { ps.getUseableCol(otherColSet.name).unionWith(otherColSet) } } // clear removes all table privileges. func (ps PrivilegeSetTable) clear() { for priv := range ps.privs { delete(ps.privs, priv) } } // PrivilegeSetColumn is a set containing column privileges. type PrivilegeSetColumn struct { name string privs map[sql.PrivilegeType]struct{} } // Name returns the name of the column that this privilege set belongs to. func (ps PrivilegeSetColumn) Name() string { return ps.name } // Has returns whether the given column privilege(s) exists. func (ps PrivilegeSetColumn) Has(privileges ...sql.PrivilegeType) bool { for _, priv := range privileges { if _, ok := ps.privs[priv]; !ok { return false } } return true } // Count returns the number of column privileges. func (ps PrivilegeSetColumn) Count() int { return len(ps.privs) } // Equals returns whether the given set of privileges is equivalent to the calling set. func (ps PrivilegeSetColumn) Equals(otherPs PrivilegeSetColumn) bool { if len(ps.privs) != len(otherPs.privs) { return false } for priv := range ps.privs { if _, ok := otherPs.privs[priv]; !ok { return false } } return true } // ToSlice returns all of the column privileges contained as a slice. Some operations do not care about sort order, // therefore this is presented as an alternative to skip the unnecessary sort operation. func (ps PrivilegeSetColumn) ToSlice() []sql.PrivilegeType { privs := make([]sql.PrivilegeType, len(ps.privs)) i := 0 for priv := range ps.privs { privs[i] = priv i++ } return privs } // ToSortedSlice returns all of the column privileges contained as a slice, sorted by their internal ID. func (ps PrivilegeSetColumn) ToSortedSlice() []sql.PrivilegeType { privs := ps.ToSlice() sort.Slice(privs, func(i, j int) bool { return privs[i] < privs[j] }) return privs } // unionWith merges the given set of privileges to the calling set of privileges. func (ps PrivilegeSetColumn) unionWith(otherPs PrivilegeSetColumn) { for priv := range otherPs.privs { ps.privs[priv] = struct{}{} } } // clear removes all column privileges. func (ps PrivilegeSetColumn) clear() { for priv := range ps.privs { delete(ps.privs, priv) } }
sql/mysql_db/privilege_set.go
0.713232
0.518302
privilege_set.go
starcoder
package mesh import ( "crypto/sha256" "fmt" "log" "os" "strconv" "github.com/9elements/autorev/tracelog" "github.com/emicklei/dot" lcs "github.com/yudai/golcs" ) // MeshNode - Describes a node in the Mesh type MeshNode struct { // Id is incremented for each node added. It's unique in the mesh. Id uint64 // Propability is incremented with each merged path if the node is part // of the merged path. By dividing it with Mesh.Pathes it gives the // propability Propability uint64 Next, Prev []*MeshNode Hash string TLE tracelog.TraceLogEntry FirmwareOptions []map[string]uint64 // a Noop meshnode doesn't generate code. It just makes the code generation prettier IsNoop bool } // a Mesh connects Nodes, using one or more pathes type Mesh struct { Start MeshNode // Pathes is incremented on each merge Pathes uint64 Nodes []*MeshNode // IDcounter, increment on new MeshNode ID uint64 } // a Branch is a Mesh, but only has one path type Branch Mesh func lcsMeshNodes(left []*MeshNode, right []*MeshNode) []interface{} { var leftIface []interface{} = make([]interface{}, len(left)) var rightIface []interface{} = make([]interface{}, len(right)) for i, d := range left { leftIface[i] = d.Hash } for i, d := range right { rightIface[i] = d.Hash } return lcs.New(leftIface, rightIface).Values() } // comparePrev- Compares Previous nodes if they are equal func (mn *MeshNode) comparePrev(other *MeshNode) bool { if len(mn.Prev) != len(other.Prev) { return false } for _, v1 := range mn.Prev { found := false for _, v2 := range other.Prev { if v1.Id == v2.Id { found = true break } } if !found { return false } } return true } // returns likliest path starting at the children of the given node func (mn *MeshNode) likelyPath() []*MeshNode { i := mn var list []*MeshNode for true { if len(i.Next) == 0 { break } var p uint64 var l *MeshNode for j := range i.Next { if i.Next[j].Propability >= p { p = i.Next[j].Propability l = i.Next[j] } } // use the one with the highest propability i = l list = append(list, i) } return list } // FirstPath - returns first path starting at the children of the given node func (mn *MeshNode) FirstPath() []*MeshNode { i := mn var list []*MeshNode for true { if len(i.Next) == 0 { break } i = i.Next[0] list = append(list, i) } return list } // LenFirstPath - Returns the length of the first path through the mesh func (mn *MeshNode) LenFirstPath() uint { i := mn length := uint(0) for true { if len(i.Next) == 0 { break } i = i.Next[0] length++ } return length } // NextPath - returns the next path starting at the children of the given node. // You have to pass the last path (returned by FirstPath or NextPath) as argument func (mn *MeshNode) NextPath(lastPath []*MeshNode) []*MeshNode { var last *MeshNode var list []*MeshNode if len(lastPath) <= 1 { return nil } lastPath = append([]*MeshNode{mn}, lastPath...) // set last element last = lastPath[len(lastPath)-1] // remove one from queue lastPath = lastPath[:len(lastPath)-1] for len(lastPath) > 0 { n := lastPath[len(lastPath)-1] if len(n.Next) > 1 { // branch found := -1 for idx := range n.Next { if n.Next[idx].Hash == last.Hash { found = idx break } } if found == -1 { // error return nil } // more branches? if found+1 != len(n.Next) { list = append(lastPath, n.Next[found+1]) break } } last = lastPath[len(lastPath)-1] lastPath = lastPath[:len(lastPath)-1] } if list == nil { return list } // cut of first element list = list[1:] n := list[len(list)-1] for len(n.Next) > 0 { list = append(list, n.Next[0]) n = n.Next[0] } return list } // AnyPathesContainNode - returns true if one of the pathes contains the meshnode to find func (mn *MeshNode) AnyPathesContainNode(find *MeshNode) bool { for p := mn.FirstPath(); p != nil; p = mn.NextPath(p) { for _, i := range p { if i.Id == find.Id { return true } } } return false } // CommonMergePoint - returns the merge point of all branches starting from this node func (mn *MeshNode) CommonMergePoint() *MeshNode { var n *MeshNode for i, first := range mn.Next { for j := i; j < len(mn.Next); j++ { second := mn.Next[j] for left := first.FirstPath(); left != nil; left = first.NextPath(left) { for right := second.FirstPath(); right != nil; right = first.NextPath(right) { /* Compare all pathes between left and right and find the mergepoint */ for i := 0; i < len(left); i++ { found := false for j := 0; j < len(right); j++ { if left[i].Id == right[j].Id { if n != nil { // The new merge point is after current mergepoint // Use the new merge point if n.AnyPathesContainNode(left[i]) { n = left[i] } } else { n = left[i] } found = true break } } if found { break } } } } } } return n } // LastNode - returns the last node in a mesh // The last node is the last element of the likeliest path func (m *Mesh) LastNode() *MeshNode { l := m.Start.likelyPath() return l[len(l)-1] } // convertDot - Convert the mesh to a dot and return as string func (m *Mesh) convertDot(simple bool) string { g := dot.NewGraph(dot.Directed) var start = g.Node("Start") for i := range m.Start.Next { str := "" str += m.Start.Next[i].TLE.String() str += "\n" str += m.Start.Next[i].Hash str += "\n" for u := range m.Start.Next[i].FirmwareOptions { for k, v := range m.Start.Next[i].FirmwareOptions[u] { str += k + "=" + strconv.FormatUint(v, 10) + " " } str += "\n" } n := g.Node(strconv.FormatInt(int64(m.Start.Next[i].Id), 10)) if simple { str = strconv.FormatInt(int64(m.Start.Next[i].Id), 10) n.Attr("color", "#"+m.Start.Next[i].Hash[0:6]) n.Attr("fillcolor", "#"+m.Start.Next[i].Hash[0:6]) n.Attr("style", "filled") } n.Label(str) g.Edge(start, n) } for i := range m.Nodes { //n := g.Node(string(self.Nodes[i].Hash)) str := "" str += string(m.Nodes[i].TLE.String()) str += "\n" str += m.Nodes[i].Hash str += "\n" for u := range m.Nodes[i].FirmwareOptions { for k, v := range m.Nodes[i].FirmwareOptions[u] { str += k + "=" + strconv.FormatUint(v, 10) + " " } str += "\n" } n := g.Node(strconv.FormatInt(int64(m.Nodes[i].Id), 10)) if simple { str = strconv.FormatInt(int64(m.Nodes[i].Id), 10) n.Attr("color", "#"+m.Nodes[i].Hash[0:6]) n.Attr("fillcolor", "#"+m.Nodes[i].Hash[0:6]) n.Attr("style", "filled") } n.Label(str) for j := range m.Nodes[i].Next { m := g.Node(strconv.FormatInt(int64(m.Nodes[i].Next[j].Id), 10)) g.Edge(n, m) } } return g.String() } // CreateNode - Create a new node, but don't add it to the mesh func (m *Mesh) CreateNode(nop bool) *MeshNode { var n MeshNode n.IsNoop = nop n.Id = m.ID n.FirmwareOptions = []map[string]uint64{} m.ID++ return &n } // WriteDot - Convert mesh to dot and write it to file func (m *Mesh) WriteDot(filename string) error { f, err := os.Create(filename) if err != nil { return err } defer f.Close() _, err = f.WriteString(m.convertDot(true)) if err != nil { return err } f.Sync() return nil } // merge b into m func mergeNodes(b *MeshNode, m *MeshNode) { // marked nodes on path as used m.Propability++ m.Hash = b.Hash m.TLE = b.TLE if len(b.FirmwareOptions) > 0 { m.FirmwareOptions = append(m.FirmwareOptions, b.FirmwareOptions[0]) } } // Merge branch into mesh as long as there're equal nodes in the branches // Returns merged count // Returns true, nil on sucessful merge // Returns false, branchNode (left), branchNode parent (right) once a branch point is dectected func mergeSimple(branch *Mesh, branchStart *MeshNode, mesh *Mesh, meshStart *MeshNode) (uint, bool, *MeshNode, *MeshNode) { var merged uint if branchStart == nil { branchStart = &branch.Start } if meshStart == nil { meshStart = &mesh.Start } var left = branchStart var right = meshStart if len(left.Next) == 0 { // Done return merged, true, nil, nil } for len(left.Next) > 0 { var path = -1 // traverse mesh and follow nodes equal those on branch for i := range right.Next { if right.Next[i].Hash == left.Next[0].Hash { path = i break } } if path == -1 { //log.Printf("Merge: l %s / ^r %s are not equal\n", left.Next[0].Hash, right.Hash) // detected a branch return 0, false, left.Next[0], right } else { //log.Printf("Merge: l %s / r %s are equal\n", left.Next[0].Hash, right.Next[path].Hash) } mergeNodes(left.Next[0], right.Next[path]) right = right.Next[path] left = left.Next[0] merged++ } return merged, true, nil, nil } func mergeGetLCS(l *MeshNode, r *MeshNode) (int, []*MeshNode, []interface{}) { // merge tail using LCS var rpath = r.FirstPath() var bestLcs = -1 var bestPath []*MeshNode var lcsResult []interface{} // One up to make use of firstPath method var lpath = l.FirstPath() // do LCS for all path in the mesh for true { log.Printf("l ") for i := range lpath { log.Printf("%s ", lpath[i].Hash) } log.Printf("\nr ") for i := range rpath { log.Printf("%s ", rpath[i].Hash) } log.Printf("\n") lcs := lcsMeshNodes(lpath, rpath) i := len(lcs) log.Printf("lcs %v\n", lcs) if i > bestLcs { lcsResult = lcs bestLcs = i bestPath = rpath } rpath = r.NextPath(rpath) if rpath == nil { break } } return bestLcs, bestPath, lcsResult } func merge(branch *Mesh, mesh *Mesh) { left := &branch.Start right := &mesh.Start var leftcur uint = 0 var leftlen uint = left.LenFirstPath() log.Printf("Merging...\n") mesh.Pathes++ for true { mergedcount, done, bl, br := mergeSimple(branch, left, mesh, right) leftcur += mergedcount log.Printf("merge progress [%d/%d]\n", leftcur, leftlen) if done { return } if len(bl.Prev) == 0 { log.Fatal("Internal error. Left node has no previous element!") return } bestLcs, bestPath, lcsResult := mergeGetLCS(bl.Prev[0], br) if bestLcs == -1 { log.Fatal("Internal error. Got no LCS result!") return } log.Printf("bestLcs %d\n", bestLcs) log.Printf("lcsResult %v\n", lcsResult) left = bl right = br if len(lcsResult) == 0 { old := right // no match, merge everything into new branch for true { var m = mesh.CreateNode(false) m.Propability = 1 mergeNodes(left, m) mesh.insertNode(old, m) old = m if len(left.Next) == 0 { log.Printf("merge progress [%d/%d]\n", leftcur, leftlen) return } left = left.Next[0] leftcur++ } } else { old := right // match, merge partial tree into mesh var j = 0 // 1. iterate left until LCS match adding nodes onto mesh // 2. iterate right until LCS match // 3. merge left into right // 4. iterate right until no LCS match // 5. branch into new left // 6. goto 1 var LCSLeftFound = false for true { if left.Hash == lcsResult[0] { log.Printf("M: Found left reentry point %s\n", left.Hash) LCSLeftFound = true break } else { log.Printf("M: Creating branch node for %s\n", left.Hash) var m = mesh.CreateNode(false) m.Propability = 1 mergeNodes(left, m) mesh.insertNode(old, m) old = m leftlen++ } if len(left.Next) > 0 { left = left.Next[0] } else { break } } var LCSRightFound = false for ; j < len(bestPath); j++ { if bestPath[j].Hash == lcsResult[0] { log.Printf("M: Found right reentry point %s\n", bestPath[j].Hash) right = bestPath[j] LCSRightFound = true break } } if LCSLeftFound && LCSRightFound { mergeNodes(left, right) // old is a new node created with CreateNode // Merge it into mesh old.Next = append(old.Next, right) right.Prev = append(right.Prev, old) leftlen++ } } } } // appendNode - Adds the node to end of the first branch func (m *Mesh) appendNode(newNode *MeshNode) { i := &m.Start for len(i.Next) > 0 { i = i.Next[0] } i.Next = append(i.Next, newNode) newNode.Prev = append(newNode.Prev, i) m.Nodes = append(m.Nodes, newNode) } // insertNode - Adds the node to an existing node of the mesh func (m *Mesh) insertNode(existNode *MeshNode, newNode *MeshNode) { existNode.Next = append(existNode.Next, newNode) newNode.Prev = append(newNode.Prev, existNode) m.Nodes = append(m.Nodes, newNode) } // MeshNodeFromTraceLogEntry - Generate mesh node ftom tracelog entry func (m *Mesh) MeshNodeFromTraceLogEntry(tle tracelog.TraceLogEntry) (*MeshNode, error) { var a = m.CreateNode(false) a.TLE = tle sha := sha256.Sum256([]byte(fmt.Sprintf("%v", tle))) a.Hash = "" for _, i := range sha { a.Hash += fmt.Sprintf("%x", i) } //log.Printf("node hash %s\n", a.Hash) m.Nodes = append(m.Nodes, a) return a, nil } // InsertTraceLogIntoMesh - Inserts a complete tracelog into the mesh // It first creates a new branch and then merges the branch into the mesh using LCS // Every created node on the branch gets assigned a FirmwareOptions slice // On merge FirmwareOptions slices are also merged func (m *Mesh) InsertTraceLogIntoMesh(tles []tracelog.TraceLogEntry, FirmwareOptions map[string]uint64) error { var b = Mesh{Start: MeshNode{Id: 0}, ID: 1} // Create a branch for i := range tles { n, err := b.MeshNodeFromTraceLogEntry(tles[i]) if err != nil { return err } // make a deep copy newmap := map[string]uint64{} for k, v := range FirmwareOptions { newmap[k] = v } n.FirmwareOptions = []map[string]uint64{newmap} b.appendNode(n) } merge(&b, m) return nil } // Compares two unsorted slices if those have equal contents func equalSlice(a, b []uint64) bool { if len(a) != len(b) { return false } for _, v1 := range a { found := false for _, v2 := range b { if v1 == v2 { found = true break } } if !found { return false } } return true } // Compares two unsorted slices if those have equal contents func equalMap(a, b map[string]uint64) bool { if len(a) != len(b) { return false } for k, v1 := range a { if b[k] != v1 { return false } } return true } // Compares two unsorted slices if those have equal contents func intInSlice(a uint64, b []uint64) bool { for _, v1 := range b { if v1 == a { return true } } return false } func (self *MeshNode) containsEqualFirmwareOption(FirmwareOption map[string]uint64) bool { for i := range self.FirmwareOptions { if equalMap(FirmwareOption, self.FirmwareOptions[i]) { return true } } return false } func deepCopyMap(c map[string]uint64) map[string]uint64 { new := map[string]uint64{} for k, v := range c { new[k] = v } return new } // OptimiseNodeByRemovingFirmwareOptions - If a node has all options a FirmwareOption can have, remove it as it doesn't depend on the config func (mn *MeshNode) OptimiseNodeByRemovingFirmwareOptions(allFirmwareOptions map[string][]uint64) error { for k := range allFirmwareOptions { for i := range mn.FirmwareOptions { copy := deepCopyMap(mn.FirmwareOptions[i]) foundAllFirmwareOptions := true for _, v := range allFirmwareOptions[k] { copy[k] = v // search if !mn.containsEqualFirmwareOption(copy) { foundAllFirmwareOptions = false break } } if !foundAllFirmwareOptions { continue } for _, v := range allFirmwareOptions[k] { copy[k] = v // search for j := range mn.FirmwareOptions { if equalMap(copy, mn.FirmwareOptions[j]) { delete(mn.FirmwareOptions[j], k) } } } } } // Remove duplicated lines for true { idx := -1 for i := 0; i < len(mn.FirmwareOptions)-1; i++ { for j := i + 1; j < len(mn.FirmwareOptions); j++ { if equalMap(mn.FirmwareOptions[i], mn.FirmwareOptions[j]) { idx = j break } } if idx >= 0 { copy(mn.FirmwareOptions[idx:], mn.FirmwareOptions[idx+1:]) mn.FirmwareOptions = mn.FirmwareOptions[:len(mn.FirmwareOptions)-1] break } } if idx < 0 { break } } return nil } // OptimiseMeshByRemovingFirmwareOptions - If a node has all options a FirmwareOption can have, remove it as it doesn't depend on the config func (m *Mesh) OptimiseMeshByRemovingFirmwareOptions(allFirmwareOptions map[string][]uint64) error { for i := range m.Nodes { m.Nodes[i].OptimiseNodeByRemovingFirmwareOptions(allFirmwareOptions) } return nil } // MergeMeshNodesAndUnlink - merge b into m func (m *Mesh) MergeMeshNodesAndUnlink(b *MeshNode, keep *MeshNode) { mergeNodes(b, keep) // Merge Next pointer into m for _, i := range b.Prev { found := false for _, j := range keep.Prev { if i.Id == j.Id { found = true break } } if !found { keep.Prev = append(keep.Prev, i) i.Next = append(i.Next, keep) } } // Remove Next pointer to b for _, i := range b.Prev { var nodes []*MeshNode for _, j := range i.Next { if b.Id == j.Id { continue } nodes = append(nodes, j) } i.Next = nodes } // Merge Next pointer into m for _, i := range b.Next { found := false for _, j := range keep.Next { if i.Id == j.Id { found = true break } } if !found { keep.Next = append(keep.Next, i) i.Prev = append(i.Prev, keep) } } // Remove Prev pointer to b for _, i := range b.Next { var nodes []*MeshNode for _, j := range i.Prev { if b.Id == j.Id { continue } nodes = append(nodes, j) } i.Prev = nodes } // Unlink node from mesh var nodes []*MeshNode for _, j := range m.Nodes { if b.Id == j.Id { continue } nodes = append(nodes, j) } m.Nodes = nodes } // OptimiseMeshByRemovingNodes - Try to remove duplicated nodes. // The branch merging only working for all pathes below the branch point // Start at the end of the mesh and merge duplicated nodes into one func (m *Mesh) OptimiseMeshByRemovingNodes() error { log.Printf("Optimising mesh by removing nodes...\n") iteration := 0 for true { log.Printf("Analysing tree, iteration %d\n", iteration) found := false for p := m.Start.FirstPath(); p != nil; p = m.Start.NextPath(p) { for i := range p { j := len(p) - i - 1 if len(p[j].Prev) > 1 { for n := range p[j].Prev { if n == 0 { continue } if p[j].Prev[n-1].Hash == p[j].Prev[n].Hash && len(p[j].Prev[n-1].Next) == 1 && len(p[j].Prev[n].Next) == 1 { log.Printf("Removing node Id %s\n", strconv.FormatInt(int64(p[j].Prev[n-1].Id), 10)) m.MergeMeshNodesAndUnlink(p[j].Prev[n-1], p[j].Prev[n]) found = true break } } } if found { break } } if found { break } } if !found { break } iteration++ } return nil } // OptimiseMeshByAddingNops - Try to insert nops to reduce the number of edges // This leads to prettier code generation func (m *Mesh) OptimiseMeshByAddingNops() error { log.Printf("Optimising mesh by iserting noop nodes...\n") iteration := 0 for true { log.Printf("Analysing tree, iteration %d\n", iteration) var nodes []*MeshNode for n1 := range m.Nodes { if len(m.Nodes[n1].Prev) < 2 { continue } if len(m.Nodes[n1].Prev) > 0 && m.Nodes[n1].Prev[0].IsNoop { continue } if m.Nodes[n1].IsNoop { continue } for n2 := range m.Nodes { // comparing the same node, skip if m.Nodes[n1].Id == m.Nodes[n2].Id { continue } if m.Nodes[n2].IsNoop { continue } if len(m.Nodes[n2].Prev) > 0 && m.Nodes[n2].Prev[0].IsNoop { continue } if m.Nodes[n1].comparePrev(m.Nodes[n2]) { log.Printf("n1\n") for i := range m.Nodes[n1].Prev { log.Printf("Prev %s\n", strconv.FormatInt(int64(m.Nodes[n1].Prev[i].Id), 10)) } log.Printf("n2\n") for i := range m.Nodes[n2].Prev { log.Printf("Prev %s\n", strconv.FormatInt(int64(m.Nodes[n2].Prev[i].Id), 10)) } log.Printf("Nodes %s and %s have the same prev\n", strconv.FormatInt(int64(m.Nodes[n1].Id), 10), strconv.FormatInt(int64(m.Nodes[n2].Id), 10)) // only add n1, n2 will be added later nodes = append(nodes, m.Nodes[n1]) } } } if len(nodes) == 0 { break } /* Create dummy instruction */ noop := m.CreateNode(true) noop.Prev = nodes[0].Prev noop.Next = nodes noop.Hash = fmt.Sprintf("ffffff noop id=%d", noop.Id) m.Nodes = append(m.Nodes, noop) // Insert the single noop for j := range nodes[0].Prev { nodes[0].Prev[j].Next = append(nodes[0].Prev[j].Next, noop) } /* Unlink old prev / next */ for i := range nodes { for j := range nodes[i].Prev { // remove n from n.Prev[i].Next var newNext []*MeshNode for x := range nodes[i].Prev[j].Next { if nodes[i].Prev[j].Next[x].Id != nodes[i].Id { newNext = append(newNext, nodes[i].Prev[j].Next[x]) } } nodes[i].Prev[j].Next = newNext } } // Now insert the single noop for i := range nodes { nodes[i].Prev = []*MeshNode{noop} } iteration++ } return nil }
mesh/mesh.go
0.592313
0.415314
mesh.go
starcoder
package streamer import ( "fmt" "time" "github.com/lyraproj/dgo/dgo" "github.com/lyraproj/dgo/tf" "github.com/lyraproj/dgo/vf" ) type dataDecoder struct { BasicCollector dialect Dialect aliasMap dgo.AliasAdder } // DataDecoder returns a decoder capable of decoding a stream of rich data representations into the corresponding values. func DataDecoder(aliasMap dgo.AliasAdder, d Dialect) Collector { c := &dataDecoder{aliasMap: aliasMap, dialect: d} c.Init() return c } func (d *dataDecoder) Init() { d.BasicCollector.Init() if d.dialect == nil { d.dialect = DgoDialect() } } // AddMap initializes and adds a new map and then calls the function with is supposed to // add an even number of elements as a sequence of key, value, [key, value, ...] func (d *dataDecoder) AddMap(cap int, doer dgo.Doer) { d.BasicCollector.AddMap(cap, doer) m := d.PeekLast().(dgo.Map) dl := d.dialect if ts, ok := m.Get(dl.TypeKey()).(dgo.String); ok { d.ReplaceLast(d.decode(ts, m)) } } func (d *dataDecoder) decode(ts dgo.String, m dgo.Map) dgo.Value { dl := d.dialect if m.Len() == 1 { return dl.ParseType(nil, ts) } mv := m.Get(dl.ValueKey()) if mv == nil { mv = m.Without(dl.TypeKey()) } var v dgo.Value switch { case ts.Equals(dl.MapTypeName()): nm := mv.(dgo.Array).ToMap() // Replace all occurrences of m in the new map recursively with the new map as it // might contain references to itself replaceInstance(m, nm, nm) v = nm case ts.Equals(dl.SensitiveTypeName()): v = vf.Sensitive(mv) case ts.Equals(dl.BinaryTypeName()): v = vf.BinaryFromString(mv.(dgo.String).GoString()) case ts.Equals(dl.TimeTypeName()): t, err := time.Parse(time.RFC3339Nano, mv.(dgo.String).GoString()) if err != nil { panic(err) } v = vf.Time(t) case ts.Equals(dl.AliasTypeName()): ad := mv.(dgo.Array) v = dl.ParseType(nil, ad.Get(1).(dgo.String)) if d.aliasMap != nil { d.aliasMap.Add(v.(dgo.Type), ad.Get(0).(dgo.String)) } default: tp := tf.Named(ts.GoString()) if tp == nil { panic(fmt.Errorf(`unable to decode %s: %s`, dl.TypeKey(), ts)) } v = tp.New(mv) } return v } func replaceInstance(orig, repl, in dgo.Value) (dgo.Value, bool) { if in == orig { return repl, true } replaceHappened := false switch iv := in.(type) { case dgo.Map: iv.EachEntry(func(v dgo.MapEntry) { if re, rh := replaceInstance(orig, repl, v.Value()); rh { replaceHappened = true iv.Put(v.Key(), re) } }) case dgo.Array: iv.EachWithIndex(func(v dgo.Value, i int) { if re, rh := replaceInstance(orig, repl, v); rh { replaceHappened = true iv.Set(i, re) } }) case dgo.Sensitive: if rw, rh := replaceInstance(orig, repl, iv.Unwrap()); rh { replaceHappened = true in = vf.Sensitive(rw) } } return in, replaceHappened }
streamer/decoder.go
0.656438
0.492615
decoder.go
starcoder
package spectral import ( "math" "github.com/ArkaGPL/gonum/graph" "github.com/ArkaGPL/gonum/mat" ) // Laplacian is a graph Laplacian matrix. type Laplacian struct { // Matrix holds the Laplacian matrix. mat.Matrix // Nodes holds the input graph nodes. Nodes []graph.Node // Index is a mapping from the graph // node IDs to row and column indices. Index map[int64]int } // NewLaplacian returns a Laplacian matrix for the simple undirected graph g. // The Laplacian is defined as D-A where D is a diagonal matrix holding the // degree of each node and A is the graph adjacency matrix of the input graph. // If g contains self edges, NewLaplacian will panic. func NewLaplacian(g graph.Undirected) Laplacian { nodes := graph.NodesOf(g.Nodes()) indexOf := make(map[int64]int, len(nodes)) for i, n := range nodes { id := n.ID() indexOf[id] = i } l := mat.NewSymDense(len(nodes), nil) for j, u := range nodes { uid := u.ID() to := graph.NodesOf(g.From(uid)) l.SetSym(j, j, float64(len(to))) for _, v := range to { vid := v.ID() if uid == vid { panic("network: self edge in graph") } if uid < vid { l.SetSym(indexOf[vid], j, -1) } } } return Laplacian{Matrix: l, Nodes: nodes, Index: indexOf} } // NewSymNormLaplacian returns a symmetric normalized Laplacian matrix for the // simple undirected graph g. // The normalized Laplacian is defined as I-D^(-1/2)AD^(-1/2) where D is a // diagonal matrix holding the degree of each node and A is the graph adjacency // matrix of the input graph. // If g contains self edges, NewSymNormLaplacian will panic. func NewSymNormLaplacian(g graph.Undirected) Laplacian { nodes := graph.NodesOf(g.Nodes()) indexOf := make(map[int64]int, len(nodes)) for i, n := range nodes { id := n.ID() indexOf[id] = i } l := mat.NewSymDense(len(nodes), nil) for j, u := range nodes { uid := u.ID() to := graph.NodesOf(g.From(uid)) if len(to) == 0 { continue } l.SetSym(j, j, 1) squdeg := math.Sqrt(float64(len(to))) for _, v := range to { vid := v.ID() if uid == vid { panic("network: self edge in graph") } if uid < vid { to := g.From(vid) k := to.Len() if k < 0 { k = len(graph.NodesOf(to)) } l.SetSym(indexOf[vid], j, -1/(squdeg*math.Sqrt(float64(k)))) } } } return Laplacian{Matrix: l, Nodes: nodes, Index: indexOf} } // NewRandomWalkLaplacian returns a damp-scaled random walk Laplacian matrix for // the simple graph g. // The random walk Laplacian is defined as I-D^(-1)A where D is a diagonal matrix // holding the degree of each node and A is the graph adjacency matrix of the input // graph. // If g contains self edges, NewRandomWalkLaplacian will panic. func NewRandomWalkLaplacian(g graph.Graph, damp float64) Laplacian { nodes := graph.NodesOf(g.Nodes()) indexOf := make(map[int64]int, len(nodes)) for i, n := range nodes { id := n.ID() indexOf[id] = i } l := mat.NewDense(len(nodes), len(nodes), nil) for j, u := range nodes { uid := u.ID() to := graph.NodesOf(g.From(uid)) if len(to) == 0 { continue } l.Set(j, j, 1-damp) rudeg := (damp - 1) / float64(len(to)) for _, v := range to { vid := v.ID() if uid == vid { panic("network: self edge in graph") } l.Set(indexOf[vid], j, rudeg) } } return Laplacian{Matrix: l, Nodes: nodes, Index: indexOf} }
graph/spectral/laplacian.go
0.795857
0.555013
laplacian.go
starcoder
package datalog import ( "fmt" ) // Flags define atom flags type Flags int // Known atom flags. const ( FlagPersistent Flags = 1 << iota ) // Atom implements datalog atoms. type Atom struct { Predicate Symbol Terms []Term Flags Flags } // AtomID defines atom IDs. type AtomID uint64 func (id AtomID) String() string { return fmt.Sprintf("%s/%d", id.Symbol(), id.Arity()) } // Symbol returns the atom symbol. func (id AtomID) Symbol() Symbol { return Symbol(id >> 32) } // Arity returns the atom arity. func (id AtomID) Arity() int { return int(id & 0xffffffff) } // NewAtom creates a new atom. func NewAtom(predicate Symbol, terms []Term) *Atom { return &Atom{ Predicate: predicate, Terms: terms, } } // ID returns the atom ID. func (a *Atom) ID() AtomID { return AtomID((uint64(a.Predicate) << 32) | uint64(len(a.Terms))) } func (a *Atom) String() string { if a.Predicate.IsExpr() { return a.Terms[0].String() } str := a.Predicate.String() if len(a.Terms) > 0 { str += "(" for idx, term := range a.Terms { if idx > 0 { str += ", " } str += term.String() } str += ")" } return str } // Equals tests if the atoms are equal. func (a *Atom) Equals(o *Atom) bool { return a.EqualsWithMapping(o, make(map[Symbol]Symbol)) } // EqualsWithMapping tests if the atoms are equal. The mappings are // updated during the operation. func (a *Atom) EqualsWithMapping(o *Atom, mapping map[Symbol]Symbol) bool { if a.Predicate != o.Predicate { return false } if len(a.Terms) != len(o.Terms) { return false } for idx, t := range a.Terms { ot := o.Terms[idx] switch t.Type() { case Variable: if ot.Type() != Variable { return false } mapped, ok := mapping[t.Variable()] if ok { if mapped != ot.Variable() { return false } } else { mapping[t.Variable()] = ot.Variable() } case Constant: if !t.Equals(ot) { return false } } } return true } // Rename renames the atom with the env bindings. func (a *Atom) Rename(env *Bindings) { for _, term := range a.Terms { term.Rename(env) } } // Unify unifies the atoms with the env bindings. The function returns // true if the atoms can be unified and false otherwise. func (a *Atom) Unify(o *Atom, env *Bindings) bool { if a.Predicate != o.Predicate { return false } if len(a.Terms) != len(o.Terms) { return false } for i, t := range a.Terms { at := env.Map(t) ot := env.Map(o.Terms[i]) if at.Equals(ot) { continue } if !at.Unify(ot, env) { return false } } return true } // Clone creates a new independent copy of the atom. func (a *Atom) Clone() *Atom { n := &Atom{ Predicate: a.Predicate, Terms: make([]Term, len(a.Terms)), Flags: a.Flags, } for i, term := range a.Terms { n.Terms[i] = term.Clone() } return n } // Substitute applies the bindings to the atom in-place and returns // the modified atom. func (a *Atom) Substitute(env *Bindings) *Atom { for i, term := range a.Terms { a.Terms[i] = term.Substitute(env) } return a }
atom.go
0.785597
0.402539
atom.go
starcoder
package assert import ( "fmt" "path/filepath" "reflect" "runtime" "testing" "time" ) func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { if len(msgAndArgs) == 0 || msgAndArgs == nil { return "" } if len(msgAndArgs) == 1 { return msgAndArgs[0].(string) } if len(msgAndArgs) > 1 { return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) } return "" } func equal(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } if reflect.DeepEqual(expected, actual) { return true } if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { return true } return false } func isnil(actual interface{}) bool { if actual == nil { return true } value := reflect.ValueOf(actual) kind := value.Kind() if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { return true } return false } var numericZeros = []interface{}{ int(0), int8(0), int16(0), int32(0), int64(0), uint(0), uint8(0), uint16(0), uint32(0), uint64(0), float32(0), float64(0), } func empty(actual interface{}) bool { if isnil(actual) { return true } if actual == "" { return true } if actual == false { return true } for _, v := range numericZeros { if actual == v { return true } } actValue := reflect.ValueOf(actual) switch actValue.Kind() { case reflect.Map: fallthrough case reflect.Slice, reflect.Chan: return (actValue.Len() == 0) case reflect.Struct: switch actual.(type) { case time.Time: return actual.(time.Time).IsZero() } case reflect.Ptr: if actValue.IsNil() { return true } switch actual.(type) { case *time.Time: return actual.(*time.Time).IsZero() default: return false } } return false } // Fail logs a failed message. func Fail(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { message := messageFromMsgAndArgs(msgAndArgs...) _, file, line, _ := runtime.Caller(2) if message > "" { message = fmt.Sprintf("(%s)", message) } t.Errorf("\r\033[39m%s:%d \033[31m%v == %v\033[39m %s\n", filepath.Base(file), line, expected, actual, message) } // Equal compare the expected value with the actual value and determine if the values are the same. func Equal(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool { success := equal(expected, actual) if !success { Fail(t, expected, actual, msgAndArgs...) } return success } // NotEqual compare the expected value with the actual value and determine if the values are not the same. func NotEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool { success := !equal(expected, actual) if !success { Fail(t, expected, actual, msgAndArgs...) } return success } // True checks if the given value is true or not. func True(t *testing.T, actual bool, msgAndArgs ...interface{}) bool { success := actual == true if !success { Fail(t, true, actual, msgAndArgs...) } return success } // False checks if the given value is false or not. func False(t *testing.T, actual bool, msgAndArgs ...interface{}) bool { success := actual == false if !success { Fail(t, false, actual, msgAndArgs...) } return success } // NotNil checks if the given value is not nil or not. func NotNil(t *testing.T, actual interface{}, msgAndArgs ...interface{}) bool { success := !isnil(actual) if !success { Fail(t, nil, actual, msgAndArgs...) } return success } // Nil checks if the given value is nil or not. func Nil(t *testing.T, actual interface{}, msgAndArgs ...interface{}) bool { success := isnil(actual) if !success { Fail(t, nil, actual, msgAndArgs...) } return success } // Empty checks if the given value is empty or not. func Empty(t *testing.T, actual interface{}, msgAndArgs ...interface{}) bool { if empty(actual) { return true } Fail(t, "empty", actual, msgAndArgs...) return false } // NotEmpty checks if the given value is not empty or not. func NotEmpty(t *testing.T, actual interface{}, msgAndArgs ...interface{}) bool { if !empty(actual) { return true } Fail(t, "not empty", actual, msgAndArgs...) return false }
vendor/github.com/frozzare/go-assert/assert.go
0.631708
0.434881
assert.go
starcoder
package bloom import ( "github.com/ioeX/ioeX.Utility/common" ) // MBlock is used to house intermediate information needed to generate a // MerkleBlock according to a filter. type MBlock struct { NumTx uint32 AllHashes []*common.Uint256 FinalHashes []*common.Uint256 MatchedBits []byte Bits []byte } // calcTreeWidth calculates and returns the the number of nodes (width) or a // merkle tree at the given depth-first height. func (m *MBlock) CalcTreeWidth(height uint32) uint32 { return (m.NumTx + (1 << height) - 1) >> height } // calcHash returns the hash for a sub-tree given a depth-first height and // node position. func (m *MBlock) CalcHash(height, pos uint32) *common.Uint256 { if height == 0 { return m.AllHashes[pos] } var right *common.Uint256 left := m.CalcHash(height-1, pos*2) if pos*2+1 < m.CalcTreeWidth(height-1) { right = m.CalcHash(height-1, pos*2+1) } else { right = left } return HashMerkleBranches(left, right) } // HashMerkleBranches takes two hashes, treated as the left and right tree // nodes, and returns the hash of their concatenation. This is a helper // function used to aid in the generation of a merkle tree. func HashMerkleBranches(left *common.Uint256, right *common.Uint256) *common.Uint256 { // Concatenate the left and right nodes. var hash [common.UINT256SIZE * 2]byte copy(hash[:common.UINT256SIZE], left[:]) copy(hash[common.UINT256SIZE:], right[:]) newHash := common.Uint256(common.Sha256D(hash[:])) return &newHash } // traverseAndBuild builds a partial merkle tree using a recursive depth-first // approach. As it calculates the hashes, it also saves whether or not each // node is a parent node and a list of final hashes to be included in the // merkle block. func (m *MBlock) TraverseAndBuild(height, pos uint32) { // Determine whether this node is a parent of a matched node. var isParent byte for i := pos << height; i < (pos+1)<<height && i < m.NumTx; i++ { isParent |= m.MatchedBits[i] } m.Bits = append(m.Bits, isParent) // When the node is a leaf node or not a parent of a matched node, // append the hash to the list that will be part of the final merkle // block. if height == 0 || isParent == 0x00 { m.FinalHashes = append(m.FinalHashes, m.CalcHash(height, pos)) return } // At this point, the node is an internal node and it is the parent of // of an included leaf node. // Descend into the left child and process its sub-tree. m.TraverseAndBuild(height-1, pos*2) // Descend into the right child and process its sub-tree if // there is one. if pos*2+1 < m.CalcTreeWidth(height-1) { m.TraverseAndBuild(height-1, pos*2+1) } }
bloom/mblock.go
0.752286
0.494446
mblock.go
starcoder
package parser const ( DEVICE_TYPE_INVALID = -1 DEVICE_TYPE_DESKTOP = 0 DEVICE_TYPE_SMARTPHONE = 1 DEVICE_TYPE_TABLET = 2 DEVICE_TYPE_FEATURE_PHONE = 3 DEVICE_TYPE_CONSOLE = 4 DEVICE_TYPE_TV = 5 // including set top boxes, blu-ray players,... DEVICE_TYPE_CAR_BROWSER = 6 DEVICE_TYPE_SMART_DISPLAY = 7 DEVICE_TYPE_CAMERA = 8 DEVICE_TYPE_PORTABLE_MEDIA_PAYER = 9 DEVICE_TYPE_PHABLET = 10 DEVICE_TYPE_SMART_SPEAKER = 11 DEVICE_TYPE_WEARABLE = 12 // including set watches, headsets ) // Detectable device types var deviceTypes = map[string]int{ `desktop`: DEVICE_TYPE_DESKTOP, `smartphone`: DEVICE_TYPE_SMARTPHONE, `tablet`: DEVICE_TYPE_TABLET, `feature phone`: DEVICE_TYPE_FEATURE_PHONE, `console`: DEVICE_TYPE_CONSOLE, `tv`: DEVICE_TYPE_TV, `car browser`: DEVICE_TYPE_CAR_BROWSER, `smart display`: DEVICE_TYPE_SMART_DISPLAY, `camera`: DEVICE_TYPE_CAMERA, `portable media player`: DEVICE_TYPE_PORTABLE_MEDIA_PAYER, `phablet`: DEVICE_TYPE_PHABLET, `smart speaker`: DEVICE_TYPE_SMART_SPEAKER, `wearable`: DEVICE_TYPE_WEARABLE, } // Known device brands // Note: Before using a new brand in on of the regex files, it needs to be added here var deviceBrands = map[string]string{ `3Q`: `3Q`, `4G`: `4Good`, `AE`: `Ace`, `AA`: `AllCall`, `AC`: `Acer`, `A9`: `Advan`, `AD`: `Advance`, `A3`: `AGM`, `AZ`: `Ainol`, `AI`: `Airness`, `0A`: `AIS`, `AW`: `Aiwa`, `AK`: `Akai`, `1A`: `Alba`, `AL`: `Alcatel`, `4A`: `Aligator`, `3A`: `AllDocube`, `A2`: `Allview`, `A7`: `Allwinner`, `A1`: `Altech UEC`, `A5`: `altron`, `AN`: `Arnova`, `5A`: `ArmPhone`, `2A`: `Atom`, `KN`: `Amazon`, `AG`: `AMGOO`, `AO`: `Amoi`, `AP`: `Apple`, `AR`: `Archos`, `AS`: `ARRIS`, `AB`: `Arian Space`, `AT`: `Airties`, `A6`: `Ark`, `A4`: `Ask`, `A8`: `Assistant`, `A0`: `ANS`, `AU`: `Asus`, `AH`: `AVH`, `AV`: `Avvio`, `AX`: `Audiovox`, `AY`: `Axxion`, `AM`: `Azumi Mobile`, `BB`: `BBK`, `BE`: `Becker`, `B5`: `Beeline`, `BI`: `Bird`, `BT`: `Bitel`, `B7`: `Bitmore`, `BG`: `BGH`, `BL`: `Beetel`, `BP`: `Blaupunkt`, `B3`: `Bluboo`, `BF`: `Black Fox`, `B6`: `BDF`, `BM`: `Bmobile`, `BN`: `Barnes & Noble`, `BO`: `BangOlufsen`, `BQ`: `BenQ`, `BS`: `BenQ-Siemens`, `BU`: `Blu`, `BD`: `Bluegood`, `B2`: `Blackview`, `B4`: `bogo`, `BW`: `Boway`, `BZ`: `Bezkam`, `BX`: `bq`, `BV`: `Bravis`, `BR`: `Brondi`, `B1`: `Bush`, `CB`: `CUBOT`, `CF`: `Carrefour`, `CP`: `Captiva`, `CS`: `Casio`, `R4`: `Casper`, `CA`: `Cat`, `C9`: `CAGI`, `CE`: `Celkon`, `CC`: `ConCorde`, `C2`: `Changhong`, `2C`: `Ghong`, `CH`: `Cherry Mobile`, `1C`: `Chuwi`, `L8`: `Clarmin`, `CK`: `Cricket`, `C1`: `Crosscall`, `CL`: `Compal`, `CN`: `CnM`, `CM`: `Crius Mea`, `C3`: `China Mobile`, `CR`: `CreNova`, `CT`: `Capitel`, `CQ`: `Compaq`, `CO`: `Coolpad`, `C5`: `Condor`, `CW`: `Cowon`, `CU`: `Cube`, `CY`: `Coby Kyros`, `C6`: `Comio`, `C7`: `ComTrade Tesla`, `C8`: `Concord`, `CX`: `Crescent`, `C4`: `Cyrus`, `CV`: `CVTE`, `D5`: `Daewoo`, `DA`: `Danew`, `DT`: `Datang`, `D7`: `Datawind`, `D1`: `Datsun`, `DE`: `Denver`, `DW`: `DeWalt`, `DX`: `DEXP`, `DS`: `Desay`, `DB`: `Dbtel`, `DC`: `DoCoMo`, `DG`: `Dialog`, `DI`: `Dicam`, `D4`: `Digi`, `D3`: `Digicel`, `DD`: `Digiland`, `D2`: `Digma`, `D6`: `Divisat`, `DL`: `Dell`, `DN`: `DNS`, `DM`: `DMM`, `DO`: `Doogee`, `DV`: `Doov`, `DP`: `Dopod`, `DR`: `Doro`, `D8`: `Droxio`, `DU`: `Dune HD`, `EB`: `E-Boda`, `EA`: `EBEST`, `EC`: `Ericsson`, `E7`: `Ergo`, `ED`: `Energizer`, `E4`: `Echo Mobiles`, `ES`: `ECS`, `E6`: `EE`, `EI`: `Ezio`, `EM`: `Eks Mobility`, `EL`: `Elephone`, `L0`: `Element`, `EG`: `Elenberg`, `EP`: `Easypix`, `EK`: `EKO`, `E1`: `Energy Sistem`, `ER`: `Ericy`, `EE`: `Essential`, `EN`: `Eton`, `E2`: `Essentielb`, `1E`: `Etuline`, `ET`: `eTouch`, `EV`: `Evertek`, `E3`: `Evolio`, `EO`: `Evolveo`, `EX`: `Explay`, `E0`: `EvroMedia`, `E5`: `Extrem`, `EZ`: `Ezze`, `E8`: `E-tel`, `E9`: `Evercoss`, `EU`: `Eurostar`, `FA`: `Fairphone`, `FM`: `Famoco`, `FE`: `Fengxiang`, `FI`: `FiGO`, `FL`: `Fly`, `F1`: `FinePower`, `FT`: `Freetel`, `FR`: `Forstar`, `FO`: `Foxconn`, `F2`: `FORME`, `FN`: `FNB`, `FU`: `Fujitsu`, `FD`: `Fondi`, `GT`: `G-TiDE`, `GM`: `Garmin-Asus`, `GA`: `Gateway`, `GD`: `Gemini`, `GN`: `General Mobile`, `GE`: `Geotel`, `GH`: `Ghia`, `GI`: `Gionee`, `GG`: `Gigabyte`, `GS`: `Gigaset`, `GZ`: `Ginzzu`, `G4`: `Globex`, `GC`: `GOCLEVER`, `GL`: `Goly`, `GO`: `Google`, `G5`: `Gome`, `G1`: `GoMobile`, `GR`: `Gradiente`, `GP`: `Grape`, `G0`: `Goophone`, `GU`: `Grundig`, `HF`: `Hafury`, `HA`: `Haier`, `HS`: `Hasee`, `HE`: `HannSpree`, `HI`: `Hisense`, `HL`: `Hi-Level`, `H2`: `Highscreen`, `H1`: `Hoffmann`, `HM`: `Homtom`, `HO`: `Hosin`, `HZ`: `Hoozo`, `HP`: `HP`, `HT`: `HTC`, `HD`: `Huadoo`, `HU`: `Huawei`, `HX`: `Humax`, `HY`: `Hyrican`, `HN`: `Hyundai`, `IG`: `iGet`, `IA`: `Ikea`, `IB`: `iBall`, `IJ`: `i-Joy`, `IY`: `iBerry`, `IH`: `iHunt`, `IK`: `iKoMo`, `IE`: `iView`, `I8`: `iVA`, `IM`: `i-mate`, `I1`: `iOcean`, `I2`: `IconBIT`, `IL`: `IMO Mobile`, `I7`: `iLA`, `IW`: `iNew`, `IP`: `iPro`, `IF`: `Infinix`, `I0`: `InFocus`, `I5`: `InnJoo`, `IN`: `Innostream`, `IS`: `Insignia`, `I4`: `Inoi`, `IR`: `iRola`, `IU`: `iRulu`, `I6`: `Irbis`, `II`: `Inkti`, `IX`: `Intex`, `IO`: `i-mobile`, `IQ`: `INQ`, `IT`: `Intek`, `IV`: `Inverto`, `I3`: `Impression`, `IZ`: `iTel`, `I9`: `iZotron`, `JA`: `JAY-Tech`, `JI`: `Jiayu`, `JO`: `Jolla`, `J5`: `Just5`, `JF`: `JFone`, `KL`: `Kalley`, `K4`: `Kaan`, `K7`: `Kaiomy`, `K6`: `Kanji`, `KA`: `Karbonn`, `K5`: `KATV1`, `KD`: `KDDI`, `K1`: `Kiano`, `KV`: `Kivi`, `KI`: `Kingsun`, `KC`: `Kocaso`, `KG`: `Kogan`, `KO`: `Konka`, `KM`: `Komu`, `KB`: `Koobee`, `KT`: `K-Touch`, `KH`: `KT-Tech`, `KK`: `Kodak`, `KP`: `KOPO`, `KW`: `Konrow`, `KR`: `Koridy`, `K2`: `KRONO`, `KS`: `Kempler & Strauss`, `K3`: `Keneksi`, `K8`: `Kuliao`, `KU`: `Kumai`, `KY`: `Kyocera`, `KZ`: `Kazam`, `KE`: `Krüger&Matz`, `LQ`: `LAIQ`, `L2`: `Landvo`, `L6`: `Land Rover`, `LV`: `Lava`, `LA`: `Lanix`, `LK`: `Lark`, `LC`: `LCT`, `L5`: `Leagoo`, `LD`: `Ledstar`, `L1`: `LeEco`, `L4`: `Lemhoov`, `LE`: `Lenovo`, `LN`: `Lenco`, `LT`: `Leotec`, `L7`: `Lephone`, `LP`: `Le Pan`, `LG`: `LG`, `LI`: `Lingwin`, `LO`: `Loewe`, `LM`: `Logicom`, `L3`: `Lexand`, `LX`: `Lexibook`, `LY`: `LYF`, `LU`: `Lumus`, `L9`: `Luna`, `MN`: `M4tel`, `MJ`: `Majestic`, `MA`: `Manta Multimedia`, `5M`: `Mann`, `2M`: `Masstel`, `MW`: `Maxwest`, `7M`: `Maxcom`, `M0`: `Maze`, `MB`: `Mobistel`, `0M`: `Mecool`, `M3`: `Mecer`, `MD`: `Medion`, `M2`: `MEEG`, `M1`: `Meizu`, `3M`: `Meitu`, `ME`: `Metz`, `MX`: `MEU`, `MI`: `MicroMax`, `M5`: `MIXC`, `MH`: `Mobiola`, `4M`: `Mobicel`, `M6`: `Mobiistar`, `MC`: `Mediacom`, `MK`: `MediaTek`, `MO`: `Mio`, `M7`: `Miray`, `MM`: `Mpman`, `M4`: `Modecom`, `MF`: `Mofut`, `MR`: `Motorola`, `MV`: `Movic`, `MS`: `Microsoft`, `M9`: `MTC`, `MP`: `MegaFon`, `MZ`: `MSI`, `MU`: `Memup`, `MT`: `Mitsubishi`, `ML`: `MLLED`, `MQ`: `M.T.T.`, `N4`: `MTN`, `MY`: `MyPhone`, `1M`: `MYFON`, `MG`: `MyWigo`, `M8`: `Myria`, `6M`: `Mystery`, `N3`: `Navon`, `N7`: `National`, `N5`: `NOA`, `NE`: `NEC`, `NF`: `Neffos`, `NA`: `Netgear`, `NU`: `NeuImage`, `NG`: `NGM`, `NZ`: `NG Optics`, `N6`: `Nobby`, `NO`: `Nous`, `NI`: `Nintendo`, `N1`: `Noain`, `N2`: `Nextbit`, `NK`: `Nokia`, `NV`: `Nvidia`, `NB`: `Noblex`, `NM`: `Nomi`, `N0`: `Nuvo`, `NL`: `NUU Mobile`, `NY`: `NYX Mobile`, `NN`: `Nikon`, `NW`: `Newgen`, `NS`: `NewsMy`, `NX`: `Nexian`, `N8`: `NEXON`, `NT`: `NextBook`, `O3`: `O+`, `OB`: `Obi`, `O1`: `Odys`, `OD`: `Onda`, `ON`: `OnePlus`, `OP`: `OPPO`, `O4`: `ONN`, `OR`: `Orange`, `OS`: `Ordissimo`, `OT`: `O2`, `OK`: `Ouki`, `OE`: `Oukitel`, `OU`: `OUYA`, `OO`: `Opsson`, `OV`: `Overmax`, `OY`: `Oysters`, `OW`: `öwn`, `PN`: `Panacom`, `PA`: `Panasonic`, `PB`: `PCBOX`, `PC`: `PCD`, `PD`: `PCD Argentina`, `PE`: `PEAQ`, `PG`: `Pentagram`, `PH`: `Philips`, `1P`: `Phicomm`, `PI`: `Pioneer`, `PX`: `Pixus`, `PL`: `Polaroid`, `P5`: `Polytron`, `P9`: `Primepad`, `P6`: `Proline`, `PM`: `Palm`, `PO`: `phoneOne`, `PT`: `Pantech`, `PY`: `Ployer`, `P4`: `Plum`, `P8`: `PocketBook`, `PV`: `Point of View`, `PP`: `PolyPad`, `P2`: `Pomp`, `P3`: `PPTV`, `PS`: `Positivo`, `PR`: `Prestigio`, `P7`: `Protruly`, `P1`: `ProScan`, `PU`: `PULID`, `QB`: `Q.Bell`, `QI`: `Qilive`, `QT`: `Qtek`, `QH`: `Q-Touch`, `QM`: `QMobile`, `QA`: `Quantum`, `QU`: `Quechua`, `QO`: `Qumo`, `RA`: `Ramos`, `RE`: `Realme`, `RZ`: `Razer`, `RC`: `RCA Tablets`, `RB`: `Readboy`, `RI`: `Rikomagic`, `RN`: `Rinno`, `RV`: `Riviera`, `RM`: `RIM`, `RK`: `Roku`, `RO`: `Rover`, `R6`: `RoverPad`, `RR`: `Roadrover`, `R1`: `Rokit`, `R3`: `Rombica`, `RT`: `RT Project`, `RX`: `Ritmix`, `R7`: `Ritzviva`, `R5`: `Ross&Moor`, `R2`: `R-TV`, `RG`: `RugGear`, `RU`: `Runbo`, `RY`: `Ryte`, `SQ`: `Santin`, `SA`: `Samsung`, `S0`: `Sanei`, `SD`: `Sega`, `SL`: `Selfix`, `SE`: `<NAME>`, `S1`: `Sencor`, `SF`: `Softbank`, `SX`: `SFR`, `SG`: `Sagem`, `SH`: `Sharp`, `7S`: `Shift Phones`, `3S`: `Shuttle`, `SI`: `Siemens`, `SJ`: `Silent Circle`, `1S`: `Sigma`, `SN`: `Sendo`, `S6`: `Senseit`, `EW`: `Senwa`, `SW`: `Sky`, `SK`: `Skyworth`, `SC`: `Smartfren`, `SO`: `Sony`, `OI`: `Sonim`, `8S`: `Soyes`, `SP`: `Spice`, `6S`: `Spectrum`, `9S`: `Sugar`, `5S`: `Sunvell`, `SU`: `SuperSonic`, `S5`: `Supra`, `SV`: `Selevision`, `SY`: `Sanyo`, `SM`: `Symphony`, `4S`: `Syrox`, `SR`: `Smart`, `S7`: `Smartisan`, `S4`: `Star`, `SB`: `STF Mobile`, `S8`: `STK`, `S9`: `Savio`, `2S`: `Starway`, `ST`: `Storex`, `S2`: `Stonex`, `S3`: `SunVan`, `SZ`: `Sumvision`, `SS`: `SWISSMOBILITY`, `10`: `Simbans`, `X1`: `Safaricom`, `TA`: `Tesla`, `T5`: `TB Touch`, `TC`: `TCL`, `T7`: `Teclast`, `TE`: `Telit`, `T4`: `ThL`, `TH`: `TiPhone`, `TB`: `Tecno Mobile`, `TP`: `TechPad`, `TD`: `Tesco`, `TI`: `TIANYU`, `TG`: `Telego`, `TL`: `Telefunken`, `T2`: `Telenor`, `TM`: `T-Mobile`, `TN`: `Thomson`, `TQ`: `Timovi`, `TY`: `Tooky`, `T1`: `Tolino`, `T9`: `Top House`, `TO`: `Toplux`, `T8`: `Touchmate`, `TS`: `Toshiba`, `TT`: `TechnoTrend`, `T6`: `TrekStor`, `T3`: `Trevi`, `TU`: `Tunisie Telecom`, `TR`: `Turbo-X`, `1T`: `Turbo`, `11`: `True`, `TV`: `TVC`, `TX`: `TechniSat`, `TZ`: `teXet`, `UC`: `U.S. Cellular`, `UH`: `Uhappy`, `U1`: `Uhans`, `UG`: `Ugoos`, `UL`: `Ulefone`, `UO`: `Unnecto`, `UN`: `Unowhy`, `US`: `Uniscope`, `UX`: `Unimax`, `UM`: `UMIDIGI`, `UU`: `Unonu`, `UK`: `UTOK`, `UA`: `Umax`, `UT`: `UTStarcom`, `UZ`: `Unihertz`, `VA`: `Vastking`, `VD`: `Videocon`, `VE`: `Vertu`, `VN`: `Venso`, `V5`: `Vivax`, `VI`: `Vitelcom`, `V7`: `Vinga`, `VK`: `VK Mobile`, `VS`: `ViewSonic`, `V9`: `Vsun`, `V8`: `Vesta`, `VT`: `Vestel`, `VR`: `Vernee`, `V4`: `Verizon`, `VL`: `Verykool`, `V6`: `VGO TEL`, `VV`: `Vivo`, `VX`: `Vertex`, `V3`: `Vinsoc`, `V2`: `Vonino`, `1V`: `Vontar`, `VG`: `Vorago`, `2V`: `Vorke`, `V1`: `Voto`, `VO`: `Voxtel`, `VF`: `Vodafone`, `VY`: `Voyo`, `VZ`: `Vizio`, `VW`: `Videoweb`, `VU`: `Vulcan`, `WA`: `Walton`, `WF`: `Wileyfox`, `WN`: `Wink`, `WM`: `Weimei`, `WE`: `WellcoM`, `WY`: `Wexler`, `W2`: `Wigor`, `WI`: `Wiko`, `WP`: `Wieppo`, `WL`: `Wolder`, `WG`: `Wolfgang`, `WO`: `Wonu`, `W1`: `Woo`, `WX`: `Woxter`, `XV`: `X-View`, `XI`: `Xiaomi`, `XL`: `Xiaolajiao`, `XN`: `Xion`, `XO`: `Xolo`, `XR`: `Xoro`, `YA`: `Yarvik`, `YD`: `Yandex`, `Y2`: `Yes`, `YE`: `Yezz`, `Y1`: `Yu`, `YU`: `Yuandao`, `YS`: `Yusun`, `YO`: `Yota`, `YT`: `Ytone`, `YX`: `Yxtel`, `ZE`: `Zeemi`, `ZK`: `Zenek`, `ZF`: `Zfiner`, `ZO`: `Zonda`, `ZI`: `Zidoo`, `ZP`: `Zopo`, `ZT`: `ZTE`, `ZU`: `Zuum`, `ZN`: `Zen`, `ZY`: `Zync`, `ZQ`: `ZYQ`, `XS`: `Xshitou`, `XT`: `X-TIGI`, `XB`: `NEXBOX`, // legacy brands, might be removed in future versions `WB`: `Web TV`, `XX`: `Unknown`, } // Returns names of all available device types func GetAvailableDeviceTypeNames() []string { keys := make([]string, 0, len(deviceTypes)) for k, _ := range deviceTypes { keys = append(keys, k) } return keys } // Returns the name of the given device type func GetDeviceName(deviceType int) string { for k, v := range deviceTypes { if v == deviceType { return k } } return "" } func GetDeviceType(deviceName string) int { if i, ok := deviceTypes[deviceName]; ok { return i } return DEVICE_TYPE_INVALID } // Returns the full brand name for the given short name func GetFullName(brandId string) string { v, _ := deviceBrands[brandId] return v } func GetShortName(name string) string { for k, v := range deviceBrands { if v == name { return k } } return name } func FindBrand(key string) string { for k, v := range deviceBrands { if v == key { return k } } return "" }
parser/device.go
0.597608
0.555616
device.go
starcoder
package tree import ( "github.com/timtadh/data-structures/types" ) func pop(stack []types.TreeNode) ([]types.TreeNode, types.TreeNode) { if len(stack) <= 0 { return stack, nil } else { return stack[0 : len(stack)-1], stack[len(stack)-1] } } func btn_expose_nil(node types.BinaryTreeNode) types.BinaryTreeNode { if types.IsNil(node) { return nil } return node } func tn_expose_nil(node types.TreeNode) types.TreeNode { if types.IsNil(node) { return nil } return node } func TraverseBinaryTreeInOrder(node types.BinaryTreeNode) types.TreeNodeIterator { stack := make([]types.TreeNode, 0, 10) var cur types.TreeNode = btn_expose_nil(node) var tn_iterator types.TreeNodeIterator tn_iterator = func() (tn types.TreeNode, next types.TreeNodeIterator) { if len(stack) > 0 || cur != nil { for cur != nil { stack = append(stack, cur) cur = cur.(types.BinaryTreeNode).Left() } stack, cur = pop(stack) tn = cur cur = cur.(types.BinaryTreeNode).Right() return tn, tn_iterator } else { return nil, nil } } return tn_iterator } func TraverseTreePreOrder(node types.TreeNode) types.TreeNodeIterator { stack := append(make([]types.TreeNode, 0, 10), tn_expose_nil(node)) var tn_iterator types.TreeNodeIterator tn_iterator = func() (tn types.TreeNode, next types.TreeNodeIterator) { if len(stack) <= 0 { return nil, nil } stack, tn = pop(stack) kid_count := 1 if tn.ChildCount() >= 0 { kid_count = tn.ChildCount() } kids := make([]types.TreeNode, 0, kid_count) for child, next := tn.Children()(); next != nil; child, next = next() { kids = append(kids, child) } for i := len(kids) - 1; i >= 0; i-- { stack = append(stack, kids[i]) } return tn, tn_iterator } return tn_iterator } func TraverseTreePostOrder(node types.TreeNode) types.TreeNodeIterator { type entry struct { tn types.TreeNode i int } pop := func(stack []entry) ([]entry, types.TreeNode, int) { if len(stack) <= 0 { return stack, nil, 0 } else { e := stack[len(stack)-1] return stack[0 : len(stack)-1], e.tn, e.i } } stack := append(make([]entry, 0, 10), entry{tn_expose_nil(node), 0}) var tn_iterator types.TreeNodeIterator tn_iterator = func() (tn types.TreeNode, next types.TreeNodeIterator) { var i int if len(stack) <= 0 { return nil, nil } stack, tn, i = pop(stack) for i < tn.ChildCount() { kid := tn.GetChild(i) stack = append(stack, entry{tn, i + 1}) tn = kid i = 0 } return tn, tn_iterator } return tn_iterator }
vendor/github.com/timtadh/data-structures/tree/util.go
0.520496
0.446133
util.go
starcoder
package plaid import ( "encoding/json" ) // StudentLoan Contains details about a student loan account type StudentLoan struct { // The ID of the account that this liability belongs to. AccountId NullableString `json:"account_id"` // The account number of the loan. For some institutions, this may be a masked version of the number (e.g., the last 4 digits instead of the entire number). AccountNumber NullableString `json:"account_number"` // The dates on which loaned funds were disbursed or will be disbursed. These are often in the past. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). DisbursementDates []string `json:"disbursement_dates"` // The date when the student loan is expected to be paid off. Availability for this field is limited. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). ExpectedPayoffDate NullableString `json:"expected_payoff_date"` // The guarantor of the student loan. Guarantor NullableString `json:"guarantor"` // The interest rate on the loan as a percentage. InterestRatePercentage float32 `json:"interest_rate_percentage"` // `true` if a payment is currently overdue. Availability for this field is limited. IsOverdue NullableBool `json:"is_overdue"` // The amount of the last payment. LastPaymentAmount NullableFloat32 `json:"last_payment_amount"` // The date of the last payment. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). LastPaymentDate NullableString `json:"last_payment_date"` // The date of the last statement. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). LastStatementIssueDate NullableString `json:"last_statement_issue_date"` // The type of loan, e.g., \"Consolidation Loans\". LoanName NullableString `json:"loan_name"` LoanStatus StudentLoanStatus `json:"loan_status"` // The minimum payment due for the next billing cycle. There are some exceptions: Some institutions require a minimum payment across all loans associated with an account number. Our API presents that same minimum payment amount on each loan. The institutions that do this are: Great Lakes ( `ins_116861`), Firstmark (`ins_116295`), Commonbond Firstmark Services (`ins_116950`), Nelnet (`ins_116528`), EdFinancial Services (`ins_116304`), Granite State (`ins_116308`), and Oklahoma Student Loan Authority (`ins_116945`). Firstmark (`ins_116295` ) will display as $0 if there is an autopay program in effect. MinimumPaymentAmount NullableFloat32 `json:"minimum_payment_amount"` // The due date for the next payment. The due date is `null` if a payment is not expected. A payment is not expected if `loan_status.type` is `deferment`, `in_school`, `consolidated`, `paid in full`, or `transferred`. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). NextPaymentDueDate NullableString `json:"next_payment_due_date"` // The date on which the loan was initially lent. Dates are returned in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). OriginationDate NullableString `json:"origination_date"` // The original principal balance of the loan. OriginationPrincipalAmount NullableFloat32 `json:"origination_principal_amount"` // The total dollar amount of the accrued interest balance. For Sallie Mae ( `ins_116944`), this amount is included in the current balance of the loan, so this field will return as `null`. OutstandingInterestAmount NullableFloat32 `json:"outstanding_interest_amount"` // The relevant account number that should be used to reference this loan for payments. In the majority of cases, `payment_reference_number` will match a`ccount_number,` but in some institutions, such as Great Lakes (`ins_116861`), it will be different. PaymentReferenceNumber NullableString `json:"payment_reference_number"` PslfStatus PSLFStatus `json:"pslf_status"` RepaymentPlan StudentRepaymentPlan `json:"repayment_plan"` // The sequence number of the student loan. Heartland ECSI (`ins_116948`) does not make this field available. SequenceNumber NullableString `json:"sequence_number"` ServicerAddress ServicerAddressData `json:"servicer_address"` // The year to date (YTD) interest paid. Availability for this field is limited. YtdInterestPaid NullableFloat32 `json:"ytd_interest_paid"` // The year to date (YTD) principal paid. Availability for this field is limited. YtdPrincipalPaid NullableFloat32 `json:"ytd_principal_paid"` AdditionalProperties map[string]interface{} } type _StudentLoan StudentLoan // NewStudentLoan instantiates a new StudentLoan 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 NewStudentLoan(accountId NullableString, accountNumber NullableString, disbursementDates []string, expectedPayoffDate NullableString, guarantor NullableString, interestRatePercentage float32, isOverdue NullableBool, lastPaymentAmount NullableFloat32, lastPaymentDate NullableString, lastStatementIssueDate NullableString, loanName NullableString, loanStatus StudentLoanStatus, minimumPaymentAmount NullableFloat32, nextPaymentDueDate NullableString, originationDate NullableString, originationPrincipalAmount NullableFloat32, outstandingInterestAmount NullableFloat32, paymentReferenceNumber NullableString, pslfStatus PSLFStatus, repaymentPlan StudentRepaymentPlan, sequenceNumber NullableString, servicerAddress ServicerAddressData, ytdInterestPaid NullableFloat32, ytdPrincipalPaid NullableFloat32) *StudentLoan { this := StudentLoan{} this.AccountId = accountId this.AccountNumber = accountNumber this.DisbursementDates = disbursementDates this.ExpectedPayoffDate = expectedPayoffDate this.Guarantor = guarantor this.InterestRatePercentage = interestRatePercentage this.IsOverdue = isOverdue this.LastPaymentAmount = lastPaymentAmount this.LastPaymentDate = lastPaymentDate this.LastStatementIssueDate = lastStatementIssueDate this.LoanName = loanName this.LoanStatus = loanStatus this.MinimumPaymentAmount = minimumPaymentAmount this.NextPaymentDueDate = nextPaymentDueDate this.OriginationDate = originationDate this.OriginationPrincipalAmount = originationPrincipalAmount this.OutstandingInterestAmount = outstandingInterestAmount this.PaymentReferenceNumber = paymentReferenceNumber this.PslfStatus = pslfStatus this.RepaymentPlan = repaymentPlan this.SequenceNumber = sequenceNumber this.ServicerAddress = servicerAddress this.YtdInterestPaid = ytdInterestPaid this.YtdPrincipalPaid = ytdPrincipalPaid return &this } // NewStudentLoanWithDefaults instantiates a new StudentLoan 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 NewStudentLoanWithDefaults() *StudentLoan { this := StudentLoan{} return &this } // GetAccountId returns the AccountId field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetAccountId() string { if o == nil || o.AccountId.Get() == nil { var ret string return ret } return *o.AccountId.Get() } // GetAccountIdOk returns a tuple with the AccountId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetAccountIdOk() (*string, bool) { if o == nil { return nil, false } return o.AccountId.Get(), o.AccountId.IsSet() } // SetAccountId sets field value func (o *StudentLoan) SetAccountId(v string) { o.AccountId.Set(&v) } // GetAccountNumber returns the AccountNumber field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetAccountNumber() string { if o == nil || o.AccountNumber.Get() == nil { var ret string return ret } return *o.AccountNumber.Get() } // GetAccountNumberOk returns a tuple with the AccountNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetAccountNumberOk() (*string, bool) { if o == nil { return nil, false } return o.AccountNumber.Get(), o.AccountNumber.IsSet() } // SetAccountNumber sets field value func (o *StudentLoan) SetAccountNumber(v string) { o.AccountNumber.Set(&v) } // GetDisbursementDates returns the DisbursementDates field value // If the value is explicit nil, the zero value for []string will be returned func (o *StudentLoan) GetDisbursementDates() []string { if o == nil { var ret []string return ret } return o.DisbursementDates } // GetDisbursementDatesOk returns a tuple with the DisbursementDates field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetDisbursementDatesOk() (*[]string, bool) { if o == nil || o.DisbursementDates == nil { return nil, false } return &o.DisbursementDates, true } // SetDisbursementDates sets field value func (o *StudentLoan) SetDisbursementDates(v []string) { o.DisbursementDates = v } // GetExpectedPayoffDate returns the ExpectedPayoffDate field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetExpectedPayoffDate() string { if o == nil || o.ExpectedPayoffDate.Get() == nil { var ret string return ret } return *o.ExpectedPayoffDate.Get() } // GetExpectedPayoffDateOk returns a tuple with the ExpectedPayoffDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetExpectedPayoffDateOk() (*string, bool) { if o == nil { return nil, false } return o.ExpectedPayoffDate.Get(), o.ExpectedPayoffDate.IsSet() } // SetExpectedPayoffDate sets field value func (o *StudentLoan) SetExpectedPayoffDate(v string) { o.ExpectedPayoffDate.Set(&v) } // GetGuarantor returns the Guarantor field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetGuarantor() string { if o == nil || o.Guarantor.Get() == nil { var ret string return ret } return *o.Guarantor.Get() } // GetGuarantorOk returns a tuple with the Guarantor field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetGuarantorOk() (*string, bool) { if o == nil { return nil, false } return o.Guarantor.Get(), o.Guarantor.IsSet() } // SetGuarantor sets field value func (o *StudentLoan) SetGuarantor(v string) { o.Guarantor.Set(&v) } // GetInterestRatePercentage returns the InterestRatePercentage field value func (o *StudentLoan) GetInterestRatePercentage() float32 { if o == nil { var ret float32 return ret } return o.InterestRatePercentage } // GetInterestRatePercentageOk returns a tuple with the InterestRatePercentage field value // and a boolean to check if the value has been set. func (o *StudentLoan) GetInterestRatePercentageOk() (*float32, bool) { if o == nil { return nil, false } return &o.InterestRatePercentage, true } // SetInterestRatePercentage sets field value func (o *StudentLoan) SetInterestRatePercentage(v float32) { o.InterestRatePercentage = v } // GetIsOverdue returns the IsOverdue field value // If the value is explicit nil, the zero value for bool will be returned func (o *StudentLoan) GetIsOverdue() bool { if o == nil || o.IsOverdue.Get() == nil { var ret bool return ret } return *o.IsOverdue.Get() } // GetIsOverdueOk returns a tuple with the IsOverdue field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetIsOverdueOk() (*bool, bool) { if o == nil { return nil, false } return o.IsOverdue.Get(), o.IsOverdue.IsSet() } // SetIsOverdue sets field value func (o *StudentLoan) SetIsOverdue(v bool) { o.IsOverdue.Set(&v) } // GetLastPaymentAmount returns the LastPaymentAmount field value // If the value is explicit nil, the zero value for float32 will be returned func (o *StudentLoan) GetLastPaymentAmount() float32 { if o == nil || o.LastPaymentAmount.Get() == nil { var ret float32 return ret } return *o.LastPaymentAmount.Get() } // GetLastPaymentAmountOk returns a tuple with the LastPaymentAmount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetLastPaymentAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.LastPaymentAmount.Get(), o.LastPaymentAmount.IsSet() } // SetLastPaymentAmount sets field value func (o *StudentLoan) SetLastPaymentAmount(v float32) { o.LastPaymentAmount.Set(&v) } // GetLastPaymentDate returns the LastPaymentDate field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetLastPaymentDate() string { if o == nil || o.LastPaymentDate.Get() == nil { var ret string return ret } return *o.LastPaymentDate.Get() } // GetLastPaymentDateOk returns a tuple with the LastPaymentDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetLastPaymentDateOk() (*string, bool) { if o == nil { return nil, false } return o.LastPaymentDate.Get(), o.LastPaymentDate.IsSet() } // SetLastPaymentDate sets field value func (o *StudentLoan) SetLastPaymentDate(v string) { o.LastPaymentDate.Set(&v) } // GetLastStatementIssueDate returns the LastStatementIssueDate field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetLastStatementIssueDate() string { if o == nil || o.LastStatementIssueDate.Get() == nil { var ret string return ret } return *o.LastStatementIssueDate.Get() } // GetLastStatementIssueDateOk returns a tuple with the LastStatementIssueDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetLastStatementIssueDateOk() (*string, bool) { if o == nil { return nil, false } return o.LastStatementIssueDate.Get(), o.LastStatementIssueDate.IsSet() } // SetLastStatementIssueDate sets field value func (o *StudentLoan) SetLastStatementIssueDate(v string) { o.LastStatementIssueDate.Set(&v) } // GetLoanName returns the LoanName field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetLoanName() string { if o == nil || o.LoanName.Get() == nil { var ret string return ret } return *o.LoanName.Get() } // GetLoanNameOk returns a tuple with the LoanName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetLoanNameOk() (*string, bool) { if o == nil { return nil, false } return o.LoanName.Get(), o.LoanName.IsSet() } // SetLoanName sets field value func (o *StudentLoan) SetLoanName(v string) { o.LoanName.Set(&v) } // GetLoanStatus returns the LoanStatus field value func (o *StudentLoan) GetLoanStatus() StudentLoanStatus { if o == nil { var ret StudentLoanStatus return ret } return o.LoanStatus } // GetLoanStatusOk returns a tuple with the LoanStatus field value // and a boolean to check if the value has been set. func (o *StudentLoan) GetLoanStatusOk() (*StudentLoanStatus, bool) { if o == nil { return nil, false } return &o.LoanStatus, true } // SetLoanStatus sets field value func (o *StudentLoan) SetLoanStatus(v StudentLoanStatus) { o.LoanStatus = v } // GetMinimumPaymentAmount returns the MinimumPaymentAmount field value // If the value is explicit nil, the zero value for float32 will be returned func (o *StudentLoan) GetMinimumPaymentAmount() float32 { if o == nil || o.MinimumPaymentAmount.Get() == nil { var ret float32 return ret } return *o.MinimumPaymentAmount.Get() } // GetMinimumPaymentAmountOk returns a tuple with the MinimumPaymentAmount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetMinimumPaymentAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.MinimumPaymentAmount.Get(), o.MinimumPaymentAmount.IsSet() } // SetMinimumPaymentAmount sets field value func (o *StudentLoan) SetMinimumPaymentAmount(v float32) { o.MinimumPaymentAmount.Set(&v) } // GetNextPaymentDueDate returns the NextPaymentDueDate field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetNextPaymentDueDate() string { if o == nil || o.NextPaymentDueDate.Get() == nil { var ret string return ret } return *o.NextPaymentDueDate.Get() } // GetNextPaymentDueDateOk returns a tuple with the NextPaymentDueDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetNextPaymentDueDateOk() (*string, bool) { if o == nil { return nil, false } return o.NextPaymentDueDate.Get(), o.NextPaymentDueDate.IsSet() } // SetNextPaymentDueDate sets field value func (o *StudentLoan) SetNextPaymentDueDate(v string) { o.NextPaymentDueDate.Set(&v) } // GetOriginationDate returns the OriginationDate field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetOriginationDate() string { if o == nil || o.OriginationDate.Get() == nil { var ret string return ret } return *o.OriginationDate.Get() } // GetOriginationDateOk returns a tuple with the OriginationDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetOriginationDateOk() (*string, bool) { if o == nil { return nil, false } return o.OriginationDate.Get(), o.OriginationDate.IsSet() } // SetOriginationDate sets field value func (o *StudentLoan) SetOriginationDate(v string) { o.OriginationDate.Set(&v) } // GetOriginationPrincipalAmount returns the OriginationPrincipalAmount field value // If the value is explicit nil, the zero value for float32 will be returned func (o *StudentLoan) GetOriginationPrincipalAmount() float32 { if o == nil || o.OriginationPrincipalAmount.Get() == nil { var ret float32 return ret } return *o.OriginationPrincipalAmount.Get() } // GetOriginationPrincipalAmountOk returns a tuple with the OriginationPrincipalAmount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetOriginationPrincipalAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.OriginationPrincipalAmount.Get(), o.OriginationPrincipalAmount.IsSet() } // SetOriginationPrincipalAmount sets field value func (o *StudentLoan) SetOriginationPrincipalAmount(v float32) { o.OriginationPrincipalAmount.Set(&v) } // GetOutstandingInterestAmount returns the OutstandingInterestAmount field value // If the value is explicit nil, the zero value for float32 will be returned func (o *StudentLoan) GetOutstandingInterestAmount() float32 { if o == nil || o.OutstandingInterestAmount.Get() == nil { var ret float32 return ret } return *o.OutstandingInterestAmount.Get() } // GetOutstandingInterestAmountOk returns a tuple with the OutstandingInterestAmount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetOutstandingInterestAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.OutstandingInterestAmount.Get(), o.OutstandingInterestAmount.IsSet() } // SetOutstandingInterestAmount sets field value func (o *StudentLoan) SetOutstandingInterestAmount(v float32) { o.OutstandingInterestAmount.Set(&v) } // GetPaymentReferenceNumber returns the PaymentReferenceNumber field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetPaymentReferenceNumber() string { if o == nil || o.PaymentReferenceNumber.Get() == nil { var ret string return ret } return *o.PaymentReferenceNumber.Get() } // GetPaymentReferenceNumberOk returns a tuple with the PaymentReferenceNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetPaymentReferenceNumberOk() (*string, bool) { if o == nil { return nil, false } return o.PaymentReferenceNumber.Get(), o.PaymentReferenceNumber.IsSet() } // SetPaymentReferenceNumber sets field value func (o *StudentLoan) SetPaymentReferenceNumber(v string) { o.PaymentReferenceNumber.Set(&v) } // GetPslfStatus returns the PslfStatus field value func (o *StudentLoan) GetPslfStatus() PSLFStatus { if o == nil { var ret PSLFStatus return ret } return o.PslfStatus } // GetPslfStatusOk returns a tuple with the PslfStatus field value // and a boolean to check if the value has been set. func (o *StudentLoan) GetPslfStatusOk() (*PSLFStatus, bool) { if o == nil { return nil, false } return &o.PslfStatus, true } // SetPslfStatus sets field value func (o *StudentLoan) SetPslfStatus(v PSLFStatus) { o.PslfStatus = v } // GetRepaymentPlan returns the RepaymentPlan field value func (o *StudentLoan) GetRepaymentPlan() StudentRepaymentPlan { if o == nil { var ret StudentRepaymentPlan return ret } return o.RepaymentPlan } // GetRepaymentPlanOk returns a tuple with the RepaymentPlan field value // and a boolean to check if the value has been set. func (o *StudentLoan) GetRepaymentPlanOk() (*StudentRepaymentPlan, bool) { if o == nil { return nil, false } return &o.RepaymentPlan, true } // SetRepaymentPlan sets field value func (o *StudentLoan) SetRepaymentPlan(v StudentRepaymentPlan) { o.RepaymentPlan = v } // GetSequenceNumber returns the SequenceNumber field value // If the value is explicit nil, the zero value for string will be returned func (o *StudentLoan) GetSequenceNumber() string { if o == nil || o.SequenceNumber.Get() == nil { var ret string return ret } return *o.SequenceNumber.Get() } // GetSequenceNumberOk returns a tuple with the SequenceNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetSequenceNumberOk() (*string, bool) { if o == nil { return nil, false } return o.SequenceNumber.Get(), o.SequenceNumber.IsSet() } // SetSequenceNumber sets field value func (o *StudentLoan) SetSequenceNumber(v string) { o.SequenceNumber.Set(&v) } // GetServicerAddress returns the ServicerAddress field value func (o *StudentLoan) GetServicerAddress() ServicerAddressData { if o == nil { var ret ServicerAddressData return ret } return o.ServicerAddress } // GetServicerAddressOk returns a tuple with the ServicerAddress field value // and a boolean to check if the value has been set. func (o *StudentLoan) GetServicerAddressOk() (*ServicerAddressData, bool) { if o == nil { return nil, false } return &o.ServicerAddress, true } // SetServicerAddress sets field value func (o *StudentLoan) SetServicerAddress(v ServicerAddressData) { o.ServicerAddress = v } // GetYtdInterestPaid returns the YtdInterestPaid field value // If the value is explicit nil, the zero value for float32 will be returned func (o *StudentLoan) GetYtdInterestPaid() float32 { if o == nil || o.YtdInterestPaid.Get() == nil { var ret float32 return ret } return *o.YtdInterestPaid.Get() } // GetYtdInterestPaidOk returns a tuple with the YtdInterestPaid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetYtdInterestPaidOk() (*float32, bool) { if o == nil { return nil, false } return o.YtdInterestPaid.Get(), o.YtdInterestPaid.IsSet() } // SetYtdInterestPaid sets field value func (o *StudentLoan) SetYtdInterestPaid(v float32) { o.YtdInterestPaid.Set(&v) } // GetYtdPrincipalPaid returns the YtdPrincipalPaid field value // If the value is explicit nil, the zero value for float32 will be returned func (o *StudentLoan) GetYtdPrincipalPaid() float32 { if o == nil || o.YtdPrincipalPaid.Get() == nil { var ret float32 return ret } return *o.YtdPrincipalPaid.Get() } // GetYtdPrincipalPaidOk returns a tuple with the YtdPrincipalPaid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StudentLoan) GetYtdPrincipalPaidOk() (*float32, bool) { if o == nil { return nil, false } return o.YtdPrincipalPaid.Get(), o.YtdPrincipalPaid.IsSet() } // SetYtdPrincipalPaid sets field value func (o *StudentLoan) SetYtdPrincipalPaid(v float32) { o.YtdPrincipalPaid.Set(&v) } func (o StudentLoan) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["account_id"] = o.AccountId.Get() } if true { toSerialize["account_number"] = o.AccountNumber.Get() } if o.DisbursementDates != nil { toSerialize["disbursement_dates"] = o.DisbursementDates } if true { toSerialize["expected_payoff_date"] = o.ExpectedPayoffDate.Get() } if true { toSerialize["guarantor"] = o.Guarantor.Get() } if true { toSerialize["interest_rate_percentage"] = o.InterestRatePercentage } if true { toSerialize["is_overdue"] = o.IsOverdue.Get() } if true { toSerialize["last_payment_amount"] = o.LastPaymentAmount.Get() } if true { toSerialize["last_payment_date"] = o.LastPaymentDate.Get() } if true { toSerialize["last_statement_issue_date"] = o.LastStatementIssueDate.Get() } if true { toSerialize["loan_name"] = o.LoanName.Get() } if true { toSerialize["loan_status"] = o.LoanStatus } if true { toSerialize["minimum_payment_amount"] = o.MinimumPaymentAmount.Get() } if true { toSerialize["next_payment_due_date"] = o.NextPaymentDueDate.Get() } if true { toSerialize["origination_date"] = o.OriginationDate.Get() } if true { toSerialize["origination_principal_amount"] = o.OriginationPrincipalAmount.Get() } if true { toSerialize["outstanding_interest_amount"] = o.OutstandingInterestAmount.Get() } if true { toSerialize["payment_reference_number"] = o.PaymentReferenceNumber.Get() } if true { toSerialize["pslf_status"] = o.PslfStatus } if true { toSerialize["repayment_plan"] = o.RepaymentPlan } if true { toSerialize["sequence_number"] = o.SequenceNumber.Get() } if true { toSerialize["servicer_address"] = o.ServicerAddress } if true { toSerialize["ytd_interest_paid"] = o.YtdInterestPaid.Get() } if true { toSerialize["ytd_principal_paid"] = o.YtdPrincipalPaid.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *StudentLoan) UnmarshalJSON(bytes []byte) (err error) { varStudentLoan := _StudentLoan{} if err = json.Unmarshal(bytes, &varStudentLoan); err == nil { *o = StudentLoan(varStudentLoan) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "account_id") delete(additionalProperties, "account_number") delete(additionalProperties, "disbursement_dates") delete(additionalProperties, "expected_payoff_date") delete(additionalProperties, "guarantor") delete(additionalProperties, "interest_rate_percentage") delete(additionalProperties, "is_overdue") delete(additionalProperties, "last_payment_amount") delete(additionalProperties, "last_payment_date") delete(additionalProperties, "last_statement_issue_date") delete(additionalProperties, "loan_name") delete(additionalProperties, "loan_status") delete(additionalProperties, "minimum_payment_amount") delete(additionalProperties, "next_payment_due_date") delete(additionalProperties, "origination_date") delete(additionalProperties, "origination_principal_amount") delete(additionalProperties, "outstanding_interest_amount") delete(additionalProperties, "payment_reference_number") delete(additionalProperties, "pslf_status") delete(additionalProperties, "repayment_plan") delete(additionalProperties, "sequence_number") delete(additionalProperties, "servicer_address") delete(additionalProperties, "ytd_interest_paid") delete(additionalProperties, "ytd_principal_paid") o.AdditionalProperties = additionalProperties } return err } type NullableStudentLoan struct { value *StudentLoan isSet bool } func (v NullableStudentLoan) Get() *StudentLoan { return v.value } func (v *NullableStudentLoan) Set(val *StudentLoan) { v.value = val v.isSet = true } func (v NullableStudentLoan) IsSet() bool { return v.isSet } func (v *NullableStudentLoan) Unset() { v.value = nil v.isSet = false } func NewNullableStudentLoan(val *StudentLoan) *NullableStudentLoan { return &NullableStudentLoan{value: val, isSet: true} } func (v NullableStudentLoan) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableStudentLoan) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_student_loan.go
0.765155
0.66889
model_student_loan.go
starcoder
package iso20022 // Information used to calculate the tax. type TaxCalculationInformation4 struct { // Specifies whether capital gain is in the scope of the European directive on taxation of savings income in the form of interest payments (Council Directive 2003/48/EC 3 June), or an income realised upon sale, a refund or redemption of shares and units, etc. EUCapitalGain *EUCapitalGain2Code `xml:"EUCptlGn,omitempty"` // Specifies whether capital gain is in the scope of the European directive on taxation of savings income in the form of interest payments (Council Directive 2003/48/EC 3 June), or an income realised upon sale, a refund or redemption of shares and units, etc. ExtendedEUCapitalGain *Extended350Code `xml:"XtndedEUCptlGn,omitempty"` // Percentage of the underlying assets of the funds that represents a debt and is in the scope of the European directive on taxation of savings income in the form of interest payments (Council Directive 2003/48/EC 3 June). PercentageOfDebtClaim *PercentageRate `xml:"PctgOfDebtClm,omitempty"` // Percentage of grandfathered debt claim. PercentageGrandfatheredDebt *PercentageRate `xml:"PctgGrdfthdDebt,omitempty"` // Amount included in the dividend that corresponds to gains directly or indirectly derived from interest payment in the scope of the European Directive on taxation of savings income in the form of interest payments. TaxableIncomePerDividend *ActiveOrHistoricCurrencyAnd13DecimalAmount `xml:"TaxblIncmPerDvdd,omitempty"` // Specifies whether dividend is in the scope of the European directive on taxation of savings income in the form of interest payments (Council Directive 2003/48/EC 3 June), or an income realised upon sale, a refund or redemption of shares and units, etc. EUDividendStatus *EUDividendStatus1Code `xml:"EUDvddSts,omitempty"` // Specifies whether dividend is in the scope of the European directive on taxation of savings income in the form of interest payments (Council Directive 2003/48/EC 3 June), or an income realised upon sale, a refund or redemption of shares and units, etc. ExtendedEUDividendStatus *Extended350Code `xml:"XtndedEUDvddSts,omitempty"` } func (t *TaxCalculationInformation4) SetEUCapitalGain(value string) { t.EUCapitalGain = (*EUCapitalGain2Code)(&value) } func (t *TaxCalculationInformation4) SetExtendedEUCapitalGain(value string) { t.ExtendedEUCapitalGain = (*Extended350Code)(&value) } func (t *TaxCalculationInformation4) SetPercentageOfDebtClaim(value string) { t.PercentageOfDebtClaim = (*PercentageRate)(&value) } func (t *TaxCalculationInformation4) SetPercentageGrandfatheredDebt(value string) { t.PercentageGrandfatheredDebt = (*PercentageRate)(&value) } func (t *TaxCalculationInformation4) SetTaxableIncomePerDividend(value, currency string) { t.TaxableIncomePerDividend = NewActiveOrHistoricCurrencyAnd13DecimalAmount(value, currency) } func (t *TaxCalculationInformation4) SetEUDividendStatus(value string) { t.EUDividendStatus = (*EUDividendStatus1Code)(&value) } func (t *TaxCalculationInformation4) SetExtendedEUDividendStatus(value string) { t.ExtendedEUDividendStatus = (*Extended350Code)(&value) }
TaxCalculationInformation4.go
0.729905
0.682197
TaxCalculationInformation4.go
starcoder
// Package table allows read and write sorted key/value. package table import ( "encoding/binary" ) /* Table: Table is consist of one or more data blocks, an optional filter block a metaindex block, an index block and a table footer. Metaindex block is a special block used to keep parameters of the table, such as filter block name and its block handle. Index block is a special block used to keep record of data blocks offset and length, index block use one as restart interval. The key used by index block are the last key of preceding block, shorter separator of adjacent blocks or shorter successor of the last key of the last block. Filter block is an optional block contains sequence of filter data generated by a filter generator. Table data structure: + optional / +--------------+--------------+--------------+------+-------+-----------------+-------------+--------+ | data block 1 | ... | data block n | filter block | metaindex block | index block | footer | +--------------+--------------+--------------+--------------+-----------------+-------------+--------+ Each block followed by a 5-bytes trailer contains compression type and checksum. Table block trailer: +---------------------------+-------------------+ | compression type (1-byte) | checksum (4-byte) | +---------------------------+-------------------+ The checksum is a CRC-32 computed using Castagnoli's polynomial. Compression type also included in the checksum. Table footer: +------------------- 40-bytes -------------------+ / \ +------------------------+--------------------+------+-----------------+ | metaindex block handle / index block handle / ---- | magic (8-bytes) | +------------------------+--------------------+------+-----------------+ The magic are first 64-bit of SHA-1 sum of "http://code.google.com/p/leveldb/". NOTE: All fixed-length integer are little-endian. */ /* Block: Block is consist of one or more key/value entries and a block trailer. Block entry shares key prefix with its preceding key until a restart point reached. A block should contains at least one restart point. First restart point are always zero. Block data structure: + restart point + restart point (depends on restart interval) / / +---------------+---------------+---------------+---------------+---------+ | block entry 1 | block entry 2 | ... | block entry n | trailer | +---------------+---------------+---------------+---------------+---------+ Key/value entry: +---- key len ----+ / \ +-------+---------+-----------+---------+--------------------+--------------+----------------+ | shared (varint) | not shared (varint) | value len (varint) | key (varlen) | value (varlen) | +-----------------+---------------------+--------------------+--------------+----------------+ Block entry shares key prefix with its preceding key: Conditions: restart_interval=2 entry one : key=deck,value=v1 entry two : key=dock,value=v2 entry three: key=duck,value=v3 The entries will be encoded as follow: + restart point (offset=0) + restart point (offset=16) / / +-----+-----+-----+----------+--------+-----+-----+-----+---------+--------+-----+-----+-----+----------+--------+ | 0 | 4 | 2 | "deck" | "v1" | 1 | 3 | 2 | "ock" | "v2" | 0 | 4 | 2 | "duck" | "v3" | +-----+-----+-----+----------+--------+-----+-----+-----+---------+--------+-----+-----+-----+----------+--------+ \ / \ / \ / +----------- entry one -----------+ +----------- entry two ----------+ +---------- entry three ----------+ The block trailer will contains two restart points: +------------+-----------+--------+ | 0 | 16 | 2 | +------------+-----------+---+----+ \ / \ +-- restart points --+ + restart points length Block trailer: +-- 4-bytes --+ / \ +-----------------+-----------------+-----------------+------------------------------+ | restart point 1 | .... | restart point n | restart points len (4-bytes) | +-----------------+-----------------+-----------------+------------------------------+ NOTE: All fixed-length integer are little-endian. */ /* Filter block: Filter block consist of one or more filter data and a filter block trailer. The trailer contains filter data offsets, a trailer offset and a 1-byte base Lg. Filter block data structure: + offset 1 + offset 2 + offset n + trailer offset / / / / +---------------+---------------+---------------+---------+ | filter data 1 | ... | filter data n | trailer | +---------------+---------------+---------------+---------+ Filter block trailer: +- 4-bytes -+ / \ +---------------+---------------+---------------+-------------------------+------------------+ | offset 1 | .... | offset n | filter offset (4-bytes) | base Lg (1-byte) | +-------------- +---------------+---------------+-------------------------+------------------+ NOTE: All fixed-length integer are little-endian. */ const ( blockTrailerLen = 5 footerLen = 48 magic = "\x57\xfb\x80\x8b\x24\x75\x47\xdb" // The block type gives the per-block compression format. // These constants are part of the file format and should not be changed. blockTypeNoCompression = 0 blockTypeSnappyCompression = 1 // Generate new filter every 2KB of data filterBaseLg = 11 filterBase = 1 << filterBaseLg ) type blockHandle struct { offset, length uint64 } func decodeBlockHandle(src []byte) (blockHandle, int) { offset, n := binary.Uvarint(src) length, m := binary.Uvarint(src[n:]) if n == 0 || m == 0 { return blockHandle{}, 0 } return blockHandle{offset, length}, n + m } func encodeBlockHandle(dst []byte, b blockHandle) int { n := binary.PutUvarint(dst, b.offset) m := binary.PutUvarint(dst[n:], b.length) return n + m }
third_party/github.com/syndtr/goleveldb/leveldb/table/table.go
0.787359
0.614972
table.go
starcoder
package ksh import "github.com/ContextLogic/cldr" var calendar = cldr.Calendar{ Formats: cldr.CalendarFormats{ Date: cldr.CalendarDateFormat{Full: "EEEE, 'dä' d. MMMM y", Long: "d. MMMM y", Medium: "d. MMM. y", Short: "d. M. y"}, Time: cldr.CalendarDateFormat{Full: "HH:mm:ss zzzz", Long: "HH:mm:ss z", Medium: "HH:mm:ss", Short: "HH:mm"}, DateTime: cldr.CalendarDateFormat{}, }, FormatNames: cldr.CalendarFormatNames{ Months: cldr.CalendarMonthFormatNames{ Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "Jan.", Feb: "Fäb.", Mar: "Mäz.", Apr: "Apr.", May: "Mäi", Jun: "Jun.", Jul: "Jul.", Aug: "Ouj.", Sep: "Säp.", Oct: "Okt.", Nov: "Nov.", Dec: "Dez."}, Narrow: cldr.CalendarMonthFormatNameValue{Jan: "J", 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: "Jannewa", Feb: "Fäbrowa", Mar: "Määz", Apr: "Aprell", May: "Mäi", Jun: "Juuni", Jul: "Juuli", Aug: "Oujoß", Sep: "Septämber", Oct: "Oktoober", Nov: "Novämber", Dec: "Dezämber"}, }, Days: cldr.CalendarDayFormatNames{ Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "Su.", Mon: "Mo.", Tue: "Di.", Wed: "Me.", Thu: "Du.", Fri: "Fr.", Sat: "Sa."}, Narrow: cldr.CalendarDayFormatNameValue{Sun: "S", Mon: "M", Tue: "D", Wed: "M", Thu: "D", Fri: "F", Sat: "S"}, Short: cldr.CalendarDayFormatNameValue{Sun: "Su", Mon: "Mo", Tue: "Di", Wed: "Me", Thu: "Du", Fri: "Fr", Sat: "Sa"}, Wide: cldr.CalendarDayFormatNameValue{Sun: "Sunndaach", Mon: "Moondaach", Tue: "Dinnsdaach", Wed: "Metwoch", Thu: "Dunnersdaach", Fri: "Friidaach", Sat: "Samsdaach"}, }, Periods: cldr.CalendarPeriodFormatNames{ Abbreviated: cldr.CalendarPeriodFormatNameValue{AM: "v.m.", PM: "n.m."}, Narrow: cldr.CalendarPeriodFormatNameValue{}, Short: cldr.CalendarPeriodFormatNameValue{}, Wide: cldr.CalendarPeriodFormatNameValue{AM: "Vormittag", PM: "Nachmittag"}, }, }, }
resources/locales/ksh/calendar.go
0.510496
0.436202
calendar.go
starcoder
package trakt import ( "fmt" "net/url" "strconv" ) // All the all constant, this is shared between different types // so cant be allocated to a specific filter. const All string = `all` type ExtendedType string func (e ExtendedType) String() string { return string(e) } const ( ExtendedTypeGuestStars ExtendedType = `guest_stars` ExtendedTypeEpisodes ExtendedType = `episodes` ExtendedTypeCollectionMetadata ExtendedType = `metadata` ExtendedTypeNoSeasons ExtendedType = `noseasons` ExtendedTypeVip ExtendedType = `vip` ExtendedTypeFull ExtendedType = `full` ) type TimePeriod string func (t TimePeriod) String() string { return string(t) } const ( TimePeriodWeekly TimePeriod = "weekly" TimePeriodMonthly TimePeriod = "monthly" TimePeriodYearly TimePeriod = "yearly" TimePeriodAll = TimePeriod(All) ) type SortType string func (s SortType) String() string { return string(s) } const ( // these sort types are used for comment sorting. SortTypeNewest SortType = "newest" SortTypeOldest SortType = "oldest" SortTypeReplies SortType = "replies" SortTypeHighest SortType = "highest" SortTypeLowest SortType = "lowest" SortTypePlays SortType = "plays" // these sort types are used for list sorting. SortTypePopular SortType = "popular" SortTypeLikes SortType = "likes" SortTypeComments SortType = "comments" SortTypeItems SortType = "items" SortTypeAdded SortType = "added" SortTypeUpdated SortType = "updated" // these sort types are used for watchlist sorting. SortTypeRank SortType = "rank" SortTypeTitle SortType = "title" SortTypeReleased SortType = "released" SortTypeRuntime SortType = "runtime" SortTypePopularity SortType = "popularity" SortTypePercentage SortType = "percentage" SortTypeVotes SortType = "votes" ) type SortDirection string const ( SortDirectionAsc SortDirection = "asc" SortDirectionDesc SortDirection = "desc" ) // Range represents a range type filter. type Range struct { To int64 From int64 } // format formats the range into the correct form which is: // "<from>-<to>". func (r *Range) format() string { if r.From == 0 && r.To == 0 { return "" } if r.To == 0 { return strconv.Itoa(int(r.From)) } return fmt.Sprintf(`%d-%d`, r.From, r.To) } // EncodeValues implements Encoder interface // takes a range and encodes it as a string in the form "<from>-<to>" func (r *Range) EncodeValues(key string, v *url.Values) error { s := r.format() if s == "" { return nil } v.Set(key, s) return nil } // Filters represents the set of filters which can be applied to certain API // endpoints. type Filters struct { // Common filters. Query string `url:"query,omitempty" json:"-"` Years []int64 `url:"years,comma,omitempty" json:"-"` Genres []string `url:"genres,comma,omitempty" json:"-"` Languages []string `url:"languages,comma,omitempty" json:"-"` Countries []string `url:"countries,comma,omitempty" json:"-"` Runtime *Range `url:"runtimes,omitempty" json:"-"` Rating *Range `url:"ratings,comma,omitempty" json:"-"` // filters specific for movies and shows Certifications []string `url:"certifications,comma,omitempty" json:"-"` // filters specific for shows Networks []string `url:"networks,comma,omitempty" json:"-"` Statuses []Status `url:"statuses,comma,omitempty" json:"-"` }
filter.go
0.74158
0.454654
filter.go
starcoder
package constant import ( "fmt" "github.com/llir/llvm/ir/types" ) // --- [ Vector expressions ] -------------------------------------------------- // ~~~ [ extractelement ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ExprExtractElement is an LLVM IR extractelement expression. type ExprExtractElement struct { // Vector. X Constant // Element index. Index Constant // extra. // Type of result produced by the constant expression. Typ types.Type } // NewExtractElement returns a new extractelement expression based on the given // vector and element index. func NewExtractElement(x, index Constant) *ExprExtractElement { e := &ExprExtractElement{X: x, Index: index} // Compute type. e.Type() return e } // String returns the LLVM syntax representation of the constant expression as a // type-value pair. func (e *ExprExtractElement) String() string { return fmt.Sprintf("%s %s", e.Type(), e.Ident()) } // Type returns the type of the constant expression. func (e *ExprExtractElement) Type() types.Type { // Cache type if not present. if e.Typ == nil { t, ok := e.X.Type().(*types.VectorType) if !ok { panic(fmt.Errorf("invalid vector type; expected *types.VectorType, got %T", e.X.Type())) } e.Typ = t.ElemType } return e.Typ } // Ident returns the identifier associated with the constant expression. func (e *ExprExtractElement) Ident() string { // 'extractelement' '(' X=TypeConst ',' Index=TypeConst ')' return fmt.Sprintf("extractelement (%s, %s)", e.X, e.Index) } // ~~~ [ insertelement ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ExprInsertElement is an LLVM IR insertelement expression. type ExprInsertElement struct { // Vector. X Constant // Element to insert. Elem Constant // Element index. Index Constant // extra. // Type of result produced by the constant expression. Typ types.Type } // NewInsertElement returns a new insertelement expression based on the given // vector, element and element index. func NewInsertElement(x, elem, index Constant) *ExprInsertElement { e := &ExprInsertElement{X: x, Elem: elem, Index: index} // Compute type. e.Type() return e } // String returns the LLVM syntax representation of the constant expression as a // type-value pair. func (e *ExprInsertElement) String() string { return fmt.Sprintf("%s %s", e.Type(), e.Ident()) } // Type returns the type of the constant expression. func (e *ExprInsertElement) Type() types.Type { // Cache type if not present. if e.Typ == nil { t, ok := e.X.Type().(*types.VectorType) if !ok { panic(fmt.Errorf("invalid vector type; expected *types.VectorType, got %T", e.X.Type())) } e.Typ = t } return e.Typ } // Ident returns the identifier associated with the constant expression. func (e *ExprInsertElement) Ident() string { // 'insertelement' '(' X=TypeConst ',' Elem=TypeConst ',' Index=TypeConst ')' return fmt.Sprintf("insertelement (%s, %s, %s)", e.X, e.Elem, e.Index) } // ~~~ [ shufflevector ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ExprShuffleVector is an LLVM IR shufflevector expression. type ExprShuffleVector struct { // Vectors. X, Y Constant // Shuffle mask. Mask Constant // extra. // Type of result produced by the constant expression. Typ types.Type } // NewShuffleVector returns a new shufflevector expression based on the given // vectors and shuffle mask. func NewShuffleVector(x, y, mask Constant) *ExprShuffleVector { e := &ExprShuffleVector{X: x, Y: y, Mask: mask} // Compute type. e.Type() return e } // String returns the LLVM syntax representation of the constant expression as a // type-value pair. func (e *ExprShuffleVector) String() string { return fmt.Sprintf("%s %s", e.Type(), e.Ident()) } // Type returns the type of the constant expression. func (e *ExprShuffleVector) Type() types.Type { // Cache type if not present. if e.Typ == nil { xType, ok := e.X.Type().(*types.VectorType) if !ok { panic(fmt.Errorf("invalid vector type; expected *types.VectorType, got %T", e.X.Type())) } maskType, ok := e.Mask.Type().(*types.VectorType) if !ok { panic(fmt.Errorf("invalid vector type; expected *types.VectorType, got %T", e.Mask.Type())) } e.Typ = types.NewVector(maskType.Len, xType.ElemType) } return e.Typ } // Ident returns the identifier associated with the constant expression. func (e *ExprShuffleVector) Ident() string { // 'shufflevector' '(' X=TypeConst ',' Y=TypeConst ',' Mask=TypeConst ')' return fmt.Sprintf("shufflevector (%s, %s, %s)", e.X, e.Y, e.Mask) }
ir/constant/expr_vector.go
0.73659
0.545346
expr_vector.go
starcoder
package slice import ( "fmt" "math" "math/rand" ) // IndexOfString gets the index of a string element in a string slice func IndexOfString(x []string, y string) int { for i, v := range x { if v == y { return i } } return -1 } // ContainsString checks whether a string element is in a string slice func ContainsString(x []string, y string) bool { return IndexOfString(x, y) != -1 } // EqualsStrings checks whether two string slice has the same elements func EqualsStrings(x []string, y []string) bool { if len(x) != len(y) { return false } for i := 0; i < len(x); i++ { if x[i] != y[i] { return false } } return true } // CopyStrings makes a new string slice that copies the content of the given string slice func CopyStrings(x []string) []string { return append([]string{}, x...) } // CutStrings cuts a string slice by removing the elements starts from i and ends at j-1 func CutStrings(x []string, i, j int) ([]string, error) { if i < 0 || j > len(x) { return x, fmt.Errorf("out of bound") } if i >= j { return x, fmt.Errorf("%d must be smaller than %d", i, j) } return append(x[:i], x[j:]...), nil } // RemoveString removes a string from a given string slice by value func RemoveString(x []string, y string) []string { index := IndexOfString(x, y) if index != -1 { return append(x[:index], x[(index+1):]...) } return x } // RemoveStringAt removes a string from a given string slice by index func RemoveStringAt(x []string, index int) ([]string, error) { if index < 0 || index > len(x) { return x, fmt.Errorf("out of bound") } return append(x[:index], x[(index+1):]...), nil } // InsertStringAt inserts a string value stringo a given string slice at given index func InsertStringAt(x []string, y string, index int) ([]string, error) { if index < 0 || index > len(x) { return x, fmt.Errorf("out of bound") } x = append(x, "") copy(x[index+1:], x[index:]) x[index] = y return x, nil } // InsertStringsAt inserts a string slice stringo a given string slice at given index func InsertStringsAt(x []string, y []string, index int) ([]string, error) { if index < 0 || index > len(x) { return x, fmt.Errorf("out of bound") } return append(x[:index], append(y, x[index:]...)...), nil } // PopFirstString pops the first value of a string slice func PopFirstString(x []string) (string, []string, error) { if len(x) == 0 { return "", nil, fmt.Errorf("no value to pop") } return x[0], x[1:], nil } // PopLastString pops the last value of a string slice func PopLastString(x []string) (string, []string, error) { if len(x) == 0 { return "", nil, fmt.Errorf("no value to pop") } return x[len(x)-1], x[:len(x)-1], nil } // FilterStrings filters a string slice by the given filter function func FilterStrings(x []string, filter func(string) bool) []string { y := x[:0] for _, v := range x { if filter(v) { y = append(y, v) } } return y } // ReverseStrings reverses a string slice func ReverseStrings(x []string) []string { for i := len(x)/2 - 1; i >= 0; i-- { opp := len(x) - 1 - i x[i], x[opp] = x[opp], x[i] } return x } // ShuffleStrings shuffles a string slice func ShuffleStrings(x []string) []string { for i := len(x) - 1; i > 0; i-- { j := rand.Intn(i + 1) x[i], x[j] = x[j], x[i] } return x } // MergeStrings merges two string slice with specific excluded values func MergeStrings(x []string, y []string, excludes ...string) []string { traceMap := make(map[string]bool) result := make([]string, 0) for _, ex := range excludes { traceMap[ex] = true } // We preserve the order by x and then y for _, v := range x { if !traceMap[v] { traceMap[v] = true result = append(result, v) } } for _, v := range y { if !traceMap[v] { traceMap[v] = true result = append(result, v) } } return result } // UniqueStrings removes the duplicates from the string slice func UniqueStrings(x []string) []string { traceMap := make(map[string]bool) result := make([]string, 0) for _, v := range x { if _, value := traceMap[v]; !value { traceMap[v] = true result = append(result, v) } } return result } // TransformStrings helps figure out how to transform current to target slice by returning the ones to add and remove func TransformStrings(target, current []string) (add, remove []string) { add = make([]string, 0) remove = make([]string, 0) // Process statusMap := make(map[string]int) // the int is the status, -1: to be removed, 0: stay there, 1: to be added. length := int(math.Max(float64(len(target)), float64(len(current)))) for i := 0; i < length; i++ { if i <= len(target)-1 { if _, ok := statusMap[target[i]]; ok { statusMap[target[i]]++ } else { statusMap[target[i]] = 1 } } if i <= len(current)-1 { if _, ok := statusMap[current[i]]; ok { statusMap[current[i]]-- } else { statusMap[current[i]] = -1 } } } for v, status := range statusMap { if status < 0 { remove = append(remove, v) } else if status > 0 { add = append(add, v) } } return }
slice/string.go
0.729423
0.484685
string.go
starcoder
// The precise format and contents of this file are depended // on by parse/helpgen.go. Do not edit without verifying that // )help still works properly. /* Ivy is an interpreter for an APL-like language. It is a plaything and a work in progress. Unlike APL, the input is ASCII and the results are exact (but see the next paragraph). It uses exact rational arithmetic so it can handle arbitrary precision. Values to be input may be integers (3, -1), rationals (1/3, -45/67) or floating point values (1e3, -1.5 (representing 1000 and -3/2)). Some functions such as sqrt are irrational. When ivy evaluates an irrational function, the result is stored in a high-precision floating-point number (default 256 bits of mantissa). Thus when using irrational functions, the values have high precision but are not exact. Unlike in most other languages, operators always have the same precedence and expressions are evaluated in right-associative order. That is, unary operators apply to everything to the right, and binary operators apply to the operand immediately to the left and to everything to the right. Thus, 3*4+5 is 27 (it groups as 3*(4+5)) and iota 3+2 is 1 2 3 4 5 while 3+iota 2 is 4 5. A vector is a single operand, so 1 2 3 + 3 + 3 4 5 is (1 2 3) + 3 + (3 4 5), or 7 9 11. As a special but important case, note that 1/3, with no intervening spaces, is a single rational number, not the expression 1 divided by 3. This can affect precedence: 3/6*4 is 2 while 3 / 6*4 is 1/8 since the spacing turns the / into a division operator. Use parentheses or spaces to disambiguate: 3/(6*4) or 3 /6*4. Indexing uses [] notation: x[1], x[1][2], and so on. Indexing by a vector selects multiple elements: x[1 2] creates a new item from x[1] and x[2]. Only a subset of APL's functionality is implemented, but the intention is to have most numerical operations supported eventually. Semicolons separate multiple statements on a line. Variables are alphanumeric and are assigned with the = operator. Assignment is an expression. After each successful expression evaluation, the result is stored in the variable called _ (underscore) so it can be used in the next expression. The APL operators, adapted from https://en.wikipedia.org/wiki/APL_syntax_and_symbols, and their correspondence are listed here. The correspondence is incomplete and inexact. Unary operators Name APL Ivy Meaning Roll ?B ? One integer selected randomly from the first B integers Ceiling ⌈B ceil Least integer greater than or equal to B Floor ⌊B floor Greatest integer less than or equal to B Shape ⍴B rho Number of components in each dimension of B Not ∼B not Logical: not 1 is 0, not 0 is 1 Absolute value ∣B abs Magnitude of B Index generator ⍳B iota Vector of the first B integers Exponential ⋆B ** e to the B power Negation −B - Changes sign of B Identity +B + No change to B Signum ×B sgn ¯1 if B<0; 0 if B=0; 1 if B>0 Reciprocal ÷B / 1 divided by B Ravel ,B , Reshapes B into a vector Matrix inverse ⌹B Inverse of matrix B Pi times ○B Multiply by π Logarithm ⍟B log Natural logarithm of B Reversal ⌽B rot Reverse elements of B along last axis Reversal ⊖B flip Reverse elements of B along first axis Grade up ⍋B up Indices of B which will arrange B in ascending order Grade down ⍒B down Indices of B which will arrange B in descending order Execute ⍎B ivy Execute an APL (ivy) expression Monadic format ⍕B text A character representation of B Monadic transpose ⍉B transp Reverse the axes of B Factorial !B ! Product of integers 1 to B Bitwise not ^ Bitwise complement of B (integer only) Square root B⋆.5 sqrt Square root of B. Sine sin sin(A); APL uses binary ○ (see below) Cosine cos cos(A); ditto Tangent tan tan(A); ditto Binary operators Name APL Ivy Meaning Add A+B + Sum of A and B Subtract A−B - A minus B Multiply A×B * A multiplied by B Divide A÷B / A divided by B (exact rational division) div A divided by B (Euclidean) idiv A divided by B (Go) Exponentiation A⋆B ** A raised to the B power Circle A○B Trigonometric functions of B selected by A A=1: sin(B) A=2: cos(B) A=3: tan(B); ¯A for inverse sin sin(B); ivy uses traditional name. cos cos(B); ivy uses traditional name. tan tan(B); ivy uses traditional name. asin arcsin(B); ivy uses traditional name. acos arccos(B); ivy uses traditional name. atan arctan(B); ivy uses traditional name. Deal A?B ? A distinct integers selected randomly from the first B integers Membership A∈B in 1 for elements of A present in B; 0 where not. Maximum A⌈B max The greater value of A or B Minimum A⌊B min The smaller value of A or B Reshape A⍴B rho Array of shape A with data B Take A↑B take Select the first (or last) A elements of B according to ×A Drop A↓B drop Remove the first (or last) A elements of B according to ×A Decode A⊥B decode Value of a polynomial whose coefficients are B at A Encode A⊤B encode Base-A representation of the value of B Residue A∣B B modulo A mod A modulo B (Euclidean) imod A modulo B (Go) Catenation A,B , Elements of B appended to the elements of A Expansion A\B fill Insert zeros (or blanks) in B corresponding to zeros in A In ivy: abs(A) gives count, A <= 0 inserts zero (or blank) Compression A/B sel Select elements in B corresponding to ones in A In ivy: abs(A) gives count, A <= 0 inserts zero Index of A⍳B iota The location (index) of B in A; 1+⌈/⍳⍴A if not found In ivy: origin-1 if not found (i.e. 0 if one-indexed) Matrix divide A⌹B Solution to system of linear equations Ax = B Rotation A⌽B rot The elements of B are rotated A positions left Rotation A⊖B flip The elements of B are rotated A positions along the first axis Logarithm A⍟B log Logarithm of B to base A Dyadic format A⍕B text Format B into a character matrix according to A A is the textual format (see format special command); otherwise result depends on length of A: 1 gives decimal count, 2 gives width and decimal count, 3 gives width, decimal count, and style ('d', 'e', 'f', etc.). General transpose A⍉B transp The axes of B are ordered by A Combinations A!B ! Number of combinations of B taken A at a time Less than A<B < Comparison: 1 if true, 0 if false Less than or equal A≤B <= Comparison: 1 if true, 0 if false Equal A=B == Comparison: 1 if true, 0 if false Greater than or equal A≥B >= Comparison: 1 if true, 0 if false Greater than A>B > Comparison: 1 if true, 0 if false Not equal A≠B != Comparison: 1 if true, 0 if false Or A∨B or Logic: 0 if A and B are 0; 1 otherwise And A∧B and Logic: 1 if A and B are 1; 0 otherwise Nor A⍱B nor Logic: 1 if both A and B are 0; otherwise 0 Nand A⍲B nand Logic: 0 if both A and B are 1; otherwise 1 Xor xor Logic: 1 if A != B; otherwise 0 Bitwise and & Bitwise A and B (integer only) Bitwise or | Bitwise A or B (integer only) Bitwise xor ^ Bitwise A exclusive or B (integer only) Left shift << A shifted left B bits (integer only) Right Shift >> A shifted right B bits (integer only) Operators and axis indicator Name APL Ivy APL Example Ivy Example Meaning (of example) Reduce (last axis) / / +/B +/B Sum across B Reduce (first axis) ⌿ +⌿B Sum down B Scan (last axis) \ \ +\B +\B Running sum across B Scan (first axis) ⍀ +⍀B Running sum down B Inner product . . A+.×B A +.* B Matrix product of A and B Outer product ∘. o. A∘.×B A o.* B Outer product of A and B (lower case o; may need preceding space) Type-converting operations Name APL Ivy Meaning Code code B The integer Unicode value of char B Char char B The character with integer Unicode value B Float float B The floating-point representation of B Pre-defined constants The constants e (base of natural logarithms) and pi (π) are pre-defined to high precision, about 3000 decimal digits truncated according to the floating point precision setting. Character data Strings are vectors of "chars", which are Unicode code points (not bytes). Syntactically, string literals are very similar to those in Go, with back-quoted raw strings and double-quoted interpreted strings. Unlike Go, single-quoted strings are equivalent to double-quoted, a nod to APL syntax. A string with a single char is just a singleton char value; all others are vectors. Thus ``, "", and '' are empty vectors, `a`, "a", and 'a' are equivalent representations of a single char, and `ab`, `a` `b`, "ab", "a" "b", 'ab', and 'a' 'b' are equivalent representations of a two-char vector. Unlike in Go, a string in ivy comprises code points, not bytes; as such it can contain only valid Unicode values. Thus in ivy "\x80" is illegal, although it is a legal one-byte string in Go. Strings can be printed. If a vector contains only chars, it is printed without spaces between them. Chars have restricted operations. Printing, comparison, indexing and so on are legal but arithmetic is not, and chars cannot be converted automatically into other singleton values (ints, floats, and so on). The unary operators char and code enable transcoding between integer and char values. User-defined operators Users can define unary and binary operators, which then behave just like built-in operators. Both a unary and a binary operator may be defined for the same name. The syntax of a definition is the 'op' keyword, the operator and formal arguments, an equals sign, and then the body. The names of the operator and its arguments must be identifiers. For unary operators, write "op name arg"; for binary write "op leftarg name rightarg". The final expression in the body is the return value. Operators may have recursive definitions; see the paragraph about conditional execution for an example. The body may be a single line (possibly containing semicolons) on the same line as the 'op', or it can be multiple lines. For a multiline entry, there is a newline after the '=' and the definition ends at the first blank line (ignoring spaces). Conditional execution is done with the ":" binary conditional return operator, which is valid only within the code for a user-defined operator. The left operand must be a scalar. If it is non-zero, the right operand is returned as the value of the function. Otherwise, execution continues normally. The ":" operator has a lower precedence than any other operator; in effect it breaks the line into two separate expressions. Example: average of a vector (unary): op avg x = (+/x)/rho x avg iota 11 result: 6 Example: n largest entries in a vector (binary): op n largest x = n take x[down x] 3 largest 7 1 3 24 1 5 12 5 51 result: 51 24 12 Example: multiline operator definition (binary): op a sum b = a = a+b a iota 3 sum 4 result: 1 2 3 4 5 6 7 Example: primes less than N (unary): op primes N = (not T in T o.* T) sel T = 1 drop iota N primes 50 result: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Example: greatest common divisor (binary): op a gcd b = a == b: a a > b: b gcd a-b a gcd b-a 1562 gcd !11 result: 22 On mobile platforms only, due to I/O restrictions, user-defined operators must be presented on a single line. Use semicolons to separate expressions: op a gcd b = a == b: a; a > b: b gcd a-b; a gcd b-a To declare an operator but not define it, omit the equals sign and what follows. op foo x op bar x = foo x op foo x = -x bar 3 result: -3 op foo x = /x bar 3 result: 1/3 Within a user-defined operator, identifiers are local to the invocation unless they are undefined in the operator but defined globally, in which case they refer to the global variable. A mechanism to declare locals may come later. Special commands Ivy accepts a number of special commands, introduced by a right paren at the beginning of the line. Most report the current value if a new value is not specified. For these commands, numbers are always read and printed base 10 and must be non-negative on input. ) help Describe the special commands. Run )help <topic> to learn more about a topic, )help <op> to learn more about an operator. ) base 0 Set the number base for input and output. The commands ibase and obase control setting of the base for input and output alone, respectively. Base 0 allows C-style input: decimal, with 037 being octal and 0x10 being hexadecimal. If the base is greater than 10, any identifier formed from valid numerals in the base system, such as abe for base 16, is taken to be a number. TODO: To output large integers and rationals, base must be one of 0 2 8 10 16. Floats are always printed base 10. ) cpu Print the duration of the last interactive calculation. ) debug name 0|1 Toggle or set the named debugging flag. With no argument, lists the settings. ) demo Run a line-by-line interactive demo. On mobile platforms, use the Demo menu option instead. ) format "" Set the format for printing values. If empty, the output is printed using the output base. If non-empty, the format determines the base used in printing. The format is in the style of golang.org/pkg/fmt. For floating-point formats, flags and width are ignored. ) get "save.ivy" Read input from the named file; return to interactive execution afterwards. If no file is specified, read from "save.ivy". (Unimplemented on mobile.) ) maxbits 1e6 To avoid consuming too much memory, if an integer result would require more than this many bits to store, abort the calculation. If maxbits is 0, there is no limit; the default is 1e6. ) maxdigits 1e4 To avoid overwhelming amounts of output, if an integer has more than this many digits, print it using the defined floating-point format. If maxdigits is 0, integers are always printed as integers. ) maxstack 1e5 To avoid using too much stack, the number of nested active calls to user-defined operators is limited to maxstack. ) op X If X is absent, list all user-defined operators. Otherwise, show the definition of the user-defined operator X. Inside the definition, numbers are always shown base 10, ignoring the ibase and obase. ) origin 1 Set the origin for indexing a vector or matrix. ) prec 256 Set the precision (mantissa length) for floating-point values. The value is in bits. The exponent always has 32 bits. ) prompt "" Set the interactive prompt. ) save "save.ivy" Write definitions of user-defined operators and variables to the named file, as ivy textual source. If no file is specified, save to "save.ivy". (Unimplemented on mobile.) ) seed 0 Set the seed for the ? operator. */ package main
doc.go
0.703651
0.704745
doc.go
starcoder
package pickle import ( "encoding/binary" "fmt" "github.com/jingxil/leaves/util" ) // SklearnNode represents tree node data structure type SklearnNode struct { LeftChild int RightChild int Feature int Threshold float64 Impurity float64 NNodeSamples int WeightedNNodeSamples float64 } // SklearnNodeFromBytes converts 56 raw bytes into SklearnNode struct // The rule described in https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_tree.pyx#L70 (NODE_DTYPE) // 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', 'n_node_samples', 'weighted_n_node_samples'], // 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, np.float64] func SklearnNodeFromBytes(bytes []byte) SklearnNode { offset := 0 size := 8 node := SklearnNode{} node.LeftChild = int(binary.LittleEndian.Uint64(bytes[offset : offset+size])) offset += size node.RightChild = int(binary.LittleEndian.Uint64(bytes[offset : offset+size])) offset += size node.Feature = int(binary.LittleEndian.Uint64(bytes[offset : offset+size])) offset += size node.Threshold = util.Float64FromBytes(bytes[offset:offset+size], true) offset += size node.Impurity = util.Float64FromBytes(bytes[offset:offset+size], true) offset += size node.NNodeSamples = int(binary.LittleEndian.Uint64(bytes[offset : offset+size])) offset += size node.WeightedNNodeSamples = util.Float64FromBytes(bytes[offset:offset+size], true) return node } // SklearnTree represents parsed tree struct type SklearnTree struct { NOutputs int Classes []int NNodes int Nodes []SklearnNode Values []float64 } func (t *SklearnTree) Reduce(reduce Reduce) (err error) { _, err = toGlobal(reduce.Callable, "sklearn.tree._tree", "Tree") if err != nil { return } if len(reduce.Args) != 3 { return fmt.Errorf("expected len(reduce.Args) = 3 (got %d)", len(reduce.Args)) } var ok bool t.NOutputs, ok = reduce.Args[2].(int) if !ok { return fmt.Errorf("expected int (got %T)", reduce.Args[2]) } arr := NumpyArrayRaw{} err = ParseClass(&arr, reduce.Args[1]) if err != nil { return err } if len(arr.Shape) != 1 && arr.Shape[0] != t.NOutputs { return fmt.Errorf("expected 1 dim array with %d values (got: %v)", t.NOutputs, arr.Shape) } if arr.Type.Type != "i8" || arr.Type.LittleEndinan != true { return fmt.Errorf("expected ndtype \"i8\" little endian (got: %#v)", arr.Type) } t.Classes = make([]int, 0, t.NOutputs) err = arr.Data.Iterate(8, func(b []byte) error { t.Classes = append(t.Classes, int(binary.LittleEndian.Uint64(b))) return nil }) if err != nil { return } return } func (t *SklearnTree) Build(build Build) (err error) { dict, err := toDict(build.Args) if err != nil { return } t.NNodes, err = dict.toInt("node_count") if err != nil { return } nodesObj, err := dict.value("nodes") if err != nil { return } arr := NumpyArrayRaw{} err = ParseClass(&arr, nodesObj) if err != nil { return } if arr.Type.Type != "V56" { return fmt.Errorf("expected arr.Type.Type = \"V56\" (got: %s)", arr.Type.Type) } err = arr.Data.Iterate(56, func(b []byte) error { t.Nodes = append(t.Nodes, SklearnNodeFromBytes(b)) return nil }) if err != nil { return } valuesObj, err := dict.value("values") if err != nil { return } arr = NumpyArrayRaw{} err = ParseClass(&arr, valuesObj) if err != nil { return } if arr.Type.Type != "f8" { return fmt.Errorf("expected ndtype \"f8\" (got: %#v)", arr.Type) } err = arr.Data.Iterate(8, func(b []byte) error { t.Values = append(t.Values, util.Float64FromBytes(b, arr.Type.LittleEndinan)) return nil }) if err != nil { return } return } type SklearnDecisionTreeRegressor struct { Tree SklearnTree NClasses int MaxFeatures int NOutputs int } func (t *SklearnDecisionTreeRegressor) Reduce(reduce Reduce) (err error) { _, err = toGlobal(reduce.Callable, "copy_reg", "_reconstructor") if err != nil { return } if len(reduce.Args) != 3 { return fmt.Errorf("not expected tuple: %#v", reduce.Args) } _, err = toGlobal(reduce.Args[0], "sklearn.tree.tree", "DecisionTreeRegressor") if err != nil { return } return } func (t *SklearnDecisionTreeRegressor) Build(build Build) (err error) { dict, err := toDict(build.Args) if err != nil { return } nClassesRaw := NumpyScalarRaw{} nClassesObj, err := dict.value("n_classes_") if err != nil { return } err = ParseClass(&nClassesRaw, nClassesObj) if err != nil { return } if nClassesRaw.Type.Type != "i8" || !nClassesRaw.Type.LittleEndinan { return fmt.Errorf("expected little endian i8, got (%#v)", nClassesRaw.Type) } t.NClasses = int(binary.LittleEndian.Uint64(nClassesRaw.Data)) t.MaxFeatures, err = dict.toInt("max_features_") if err != nil { return } t.NOutputs, err = dict.toInt("n_outputs_") if err != nil { return } treeObj, err := dict.value("tree_") if err != nil { return } err = ParseClass(&t.Tree, treeObj) if err != nil { return } return } type SklearnGradientBoosting struct { NClasses int Classes []int NEstimators int MaxFeatures int Estimators []SklearnDecisionTreeRegressor LearningRate float64 InitEstimator SKlearnInitEstimator } func (t *SklearnGradientBoosting) Reduce(reduce Reduce) (err error) { _, err = toGlobal(reduce.Callable, "copy_reg", "_reconstructor") if err != nil { return } if len(reduce.Args) != 3 { return fmt.Errorf("not expected tuple: %#v", reduce.Args) } _, err = toGlobal(reduce.Args[0], "sklearn.ensemble.gradient_boosting", "GradientBoostingClassifier") if err != nil { return } return } func (t *SklearnGradientBoosting) Build(build Build) (err error) { dict, err := toDict(build.Args) if err != nil { return } t.NClasses, err = dict.toInt("n_classes_") if err != nil { return } t.LearningRate, err = dict.toFloat("learning_rate") if err != nil { return } obj, err := dict.value("loss") if err != nil { return } _ /* loss */, err = toUnicode(obj, -1) if err != nil { return } obj, err = dict.value("init_") if err != nil { return } err = ParseClass(&t.InitEstimator, obj) if err != nil { return } arr := NumpyArrayRaw{} classesObj, err := dict.value("classes_") if err != nil { return err } err = ParseClass(&arr, classesObj) if err != nil { return err } if len(arr.Shape) != 1 && arr.Shape[0] != t.NClasses { return fmt.Errorf("expected 1 dim array with %d values (got: %v)", t.NClasses, arr.Shape) } if arr.Type.Type != "i8" || arr.Type.LittleEndinan != true { return fmt.Errorf("expected ndtype \"i8\" little endian (got: %#v)", arr.Type) } t.Classes = make([]int, 0, t.NClasses) err = arr.Data.Iterate(8, func(b []byte) error { t.Classes = append(t.Classes, int(binary.LittleEndian.Uint64(b))) return nil }) if err != nil { return } t.MaxFeatures, err = dict.toInt("max_features_") if err != nil { return } t.NEstimators, err = dict.toInt("n_estimators") if err != nil { return } // estimators_ : ndarray of DecisionTreeRegressor,\ // shape (n_estimators, ``loss_.K``) // The collection of fitted sub-estimators. ``loss_.K`` is 1 for binary // classification, otherwise n_classes. arr = NumpyArrayRaw{} obj, err = dict.value("estimators_") if err != nil { return } err = ParseClass(&arr, obj) if err != nil { return } adjNClasses := t.NClasses if t.NClasses == 2 { adjNClasses = 1 } if len(arr.Shape) != 2 || arr.Shape[0] != t.NEstimators || arr.Shape[1] != adjNClasses { return fmt.Errorf("unexpected shape: %#v", arr.Shape) } if len(arr.DataList) != arr.Shape[0]*arr.Shape[1] { return fmt.Errorf("unexpected array list length") } t.Estimators = make([]SklearnDecisionTreeRegressor, arr.Shape[0]*arr.Shape[1]) for i := range arr.DataList { err = ParseClass(&t.Estimators[i], arr.DataList[i]) if err != nil { return } } return } type SKlearnInitEstimator struct { Name string Prior []float64 } func (e *SKlearnInitEstimator) Reduce(reduce Reduce) (err error) { _, err = toGlobal(reduce.Callable, "copy_reg", "_reconstructor") if err != nil { return } if len(reduce.Args) != 3 { return fmt.Errorf("not expected tuple: %#v", reduce.Args) } classDesc, err := toGlobal(reduce.Args[0], "sklearn.ensemble.gradient_boosting", "") if err != nil { return } e.Name = classDesc.Name return } func (e *SKlearnInitEstimator) Build(build Build) (err error) { if e.Name == "LogOddsEstimator" { dict, err := toDict(build.Args) if err != nil { return err } priorObj, err := dict.value("prior") if err != nil { return err } numpyScalar := NumpyScalarRaw{} err = ParseClass(&numpyScalar, priorObj) if err != nil { return err } if numpyScalar.Type.Type != "f8" { return fmt.Errorf("expected f8, got (%#v)", numpyScalar.Type) } e.Prior = append(e.Prior, util.Float64FromBytes(numpyScalar.Data, numpyScalar.Type.LittleEndinan)) } else if e.Name == "PriorProbabilityEstimator" { dict, err := toDict(build.Args) if err != nil { return err } priorObj, err := dict.value("priors") if err != nil { return err } numpyArray := NumpyArrayRaw{} err = ParseClass(&numpyArray, priorObj) if err != nil { return err } if numpyArray.Type.Type != "f8" { return fmt.Errorf("expected f8, got (%#v)", numpyArray.Type) } numpyArray.Data.Iterate(8, func(bytes []byte) error { e.Prior = append(e.Prior, util.Float64FromBytes(bytes, numpyArray.Type.LittleEndinan)) return nil }) } else { return fmt.Errorf("unknown init estimator class: %s", e.Name) } return }
internal/pickle/sklearn.go
0.70028
0.500122
sklearn.go
starcoder
package segmentation import ( "fmt" "github.com/miguelfrde/image-segmentation/disjointset" "github.com/miguelfrde/image-segmentation/graph" "github.com/miguelfrde/image-segmentation/imagenoise" "github.com/miguelfrde/image-segmentation/utils" "math" "sort" "time" ) /** * Performs the image segmentation using the "Heuristic for Minimum Spanning * Forests" algorithm. It uses the weightfn to compute the weight of the * graph edges. minWeight is the only parameter. * For more information on this algorithm refer to either my report which link * is on the repo's README or to: * http://algo2.iti.kit.edu/wassenberg/wassenberg09parallelSegmentation.pdf */ func (s *Segmenter) SegmentHMSF(sigmaSmooth, minWeight float64) { start := time.Now() sigma := imagenoise.EstimateStdev(s.img) s.smoothImage(sigmaSmooth) s.buildGraph() fmt.Printf("segment... ") start = time.Now() s.resultset = disjointset.New(s.graph.TotalVertices()) edges := s.graph.Edges() sort.Sort(edges) setll := s.hmsfMergeEdgesByWeight(edges, minWeight) regionCredit := s.hmsfComputeCredit(setll, sigma) s.hmsfMergeRegionsByCredit(edges, regionCredit) regionCredit[0] = 1 fmt.Println(time.Since(start)) fmt.Println("Components:", s.resultset.Components()) } /** * First part of HMSF algorithm. Given a minimum weight, merge edges until that * region exceeds that minimum weight */ func (s *Segmenter) hmsfMergeEdgesByWeight(edges graph.EdgeList, minWeight float64) *disjointset.DisjointSetLL { setll := disjointset.NewDisjointSetLL(s.graph.TotalVertices()) for _, edge := range edges { u := s.resultset.Find(edge.U()) v := s.resultset.Find(edge.V()) if u != v && edge.Weight() < minWeight { root := s.resultset.Union(u, v) if root == u { setll.Union(root, v) } else { setll.Union(root, u) } } } return setll } /** * Compute the credit for each region. The credit is defined as: * Credit(R) = contrast(R) * sqrt(4 * pi * |R|) * where contrast(R) = minWeightInTheRegionBorder - 2 * sigma * where sigma is the previously computed standard deviation of the additive * white gaussian noise of the image. */ func (s *Segmenter) hmsfComputeCredit(setll *disjointset.DisjointSetLL, sigma float64) []float64 { regionCredit := make([]float64, s.graph.TotalVertices(), s.graph.TotalVertices()) minWeights := s.hmfsMinWeights(setll) for i := 0; i < s.graph.TotalVertices(); i++ { contrast := minWeights[s.resultset.Find(i)] - 2*sigma regionCredit[i] = contrast * math.Sqrt(4*math.Pi*float64(s.resultset.Size(i))) } return regionCredit } /** * Compute the minimum weight in the border of each region. */ func (s *Segmenter) hmfsMinWeights(setll *disjointset.DisjointSetLL) []float64 { minWeights := make([]float64, s.graph.TotalVertices(), s.graph.TotalVertices()) computed := make([]bool, s.graph.TotalVertices(), s.graph.TotalVertices()) for v := 0; v < s.graph.TotalVertices(); v++ { region := s.resultset.Find(v) if !computed[region] { minWeights[region] = math.Inf(1) for w := range setll.Elements(region) { for n := range s.graph.Neighbors(w) { if s.resultset.Find(n) != region && s.graph.Weight(w, n) < minWeights[region] { minWeights[region] = s.graph.Weight(w, n) } } } computed[region] = true } } return minWeights } /** * Last part of the HMSF algorithm, merge regions if the credit of any of them * exceeds the weight of the edge connecting them. */ func (s *Segmenter) hmsfMergeRegionsByCredit(edges graph.EdgeList, regionCredit []float64) { for _, edge := range edges { u := s.resultset.Find(edge.U()) v := s.resultset.Find(edge.V()) if u != v { credit := utils.MinF(regionCredit[u], regionCredit[v]) if credit > edge.Weight() { s.resultset.Union(u, v) survivor := s.resultset.Find(u) regionCredit[survivor] = credit - edge.Weight() } } } }
segmentation/hmsf.go
0.741487
0.468061
hmsf.go
starcoder
package gobrain import ( "fmt" "log" "math" ) // FeedForwad struct is used to represent a simple neural network type FeedForward struct { // Number of input, hidden and output nodes NInputs, NHiddens, NOutputs int // Whether it is regression or not Regression bool // Activations for nodes InputActivations, HiddenActivations, OutputActivations []float64 // ElmanRNN contexts Contexts [][]float64 // Weights InputWeights, OutputWeights [][]float64 // Last change in weights for momentum InputChanges, OutputChanges [][]float64 } /* Initialize the neural network; the 'inputs' value is the number of inputs the network will have, the 'hiddens' value is the number of hidden nodes and the 'outputs' value is the number of the outputs of the network. */ func (nn *FeedForward) Init(inputs, hiddens, outputs int) { nn.NInputs = inputs + 1 // +1 for bias nn.NHiddens = hiddens + 1 // +1 for bias nn.NOutputs = outputs nn.InputActivations = vector(nn.NInputs, 1.0) nn.HiddenActivations = vector(nn.NHiddens, 1.0) nn.OutputActivations = vector(nn.NOutputs, 1.0) nn.InputWeights = matrix(nn.NInputs, nn.NHiddens) nn.OutputWeights = matrix(nn.NHiddens, nn.NOutputs) for i := 0; i < nn.NInputs; i++ { for j := 0; j < nn.NHiddens; j++ { nn.InputWeights[i][j] = random(-1, 1) } } for i := 0; i < nn.NHiddens; i++ { for j := 0; j < nn.NOutputs; j++ { nn.OutputWeights[i][j] = random(-1, 1) } } nn.InputChanges = matrix(nn.NInputs, nn.NHiddens) nn.OutputChanges = matrix(nn.NHiddens, nn.NOutputs) } /* Set the number of contexts to add to the network. By default the network do not have any context so it is a simple Feed Forward network, when contexts are added the network behaves like an Elman's SRN (Simple Recurrent Network). The first parameter (nContexts) is used to indicate the number of contexts to be used, the second parameter (initValues) can be used to create custom initialized contexts. If 'initValues' is set, the first parameter 'nContexts' is ignored and the contexts provided in 'initValues' are used. When using 'initValues' note that contexts must have the same size of hidden nodes + 1 (bias node). */ func (nn *FeedForward) SetContexts(nContexts int, initValues [][]float64) { if initValues == nil { initValues = make([][]float64, nContexts) for i := 0; i < nContexts; i++ { initValues[i] = vector(nn.NHiddens, 0.5) } } nn.Contexts = initValues } /* The Update method is used to activate the Neural Network. Given an array of inputs, it returns an array, of length equivalent of number of outputs, with values ranging from 0 to 1. */ func (nn *FeedForward) Update(inputs []float64) []float64 { if len(inputs) != nn.NInputs-1 { log.Fatal("Error: wrong number of inputs") } for i := 0; i < nn.NInputs-1; i++ { nn.InputActivations[i] = inputs[i] } for i := 0; i < nn.NHiddens-1; i++ { var sum float64 for j := 0; j < nn.NInputs; j++ { sum += nn.InputActivations[j] * nn.InputWeights[j][i] } // compute contexts sum for k := 0; k < len(nn.Contexts); k++ { for j := 0; j < nn.NHiddens-1; j++ { sum += nn.Contexts[k][j] } } nn.HiddenActivations[i] = sigmoid(sum) } // update the contexts if len(nn.Contexts) > 0 { for i := len(nn.Contexts) - 1; i > 0; i-- { nn.Contexts[i] = nn.Contexts[i-1] } nn.Contexts[0] = nn.HiddenActivations } for i := 0; i < nn.NOutputs; i++ { var sum float64 for j := 0; j < nn.NHiddens; j++ { sum += nn.HiddenActivations[j] * nn.OutputWeights[j][i] } nn.OutputActivations[i] = sigmoid(sum) } return nn.OutputActivations } /* The BackPropagate method is used, when training the Neural Network, to back propagate the errors from network activation. */ func (nn *FeedForward) BackPropagate(targets []float64, lRate, mFactor float64) float64 { if len(targets) != nn.NOutputs { log.Fatal("Error: wrong number of target values") } outputDeltas := vector(nn.NOutputs, 0.0) for i := 0; i < nn.NOutputs; i++ { outputDeltas[i] = dsigmoid(nn.OutputActivations[i]) * (targets[i] - nn.OutputActivations[i]) } hiddenDeltas := vector(nn.NHiddens, 0.0) for i := 0; i < nn.NHiddens; i++ { var e float64 for j := 0; j < nn.NOutputs; j++ { e += outputDeltas[j] * nn.OutputWeights[i][j] } hiddenDeltas[i] = dsigmoid(nn.HiddenActivations[i]) * e } for i := 0; i < nn.NHiddens; i++ { for j := 0; j < nn.NOutputs; j++ { change := outputDeltas[j] * nn.HiddenActivations[i] nn.OutputWeights[i][j] = nn.OutputWeights[i][j] + lRate*change + mFactor*nn.OutputChanges[i][j] nn.OutputChanges[i][j] = change } } for i := 0; i < nn.NInputs; i++ { for j := 0; j < nn.NHiddens; j++ { change := hiddenDeltas[j] * nn.InputActivations[i] nn.InputWeights[i][j] = nn.InputWeights[i][j] + lRate*change + mFactor*nn.InputChanges[i][j] nn.InputChanges[i][j] = change } } var e float64 for i := 0; i < len(targets); i++ { e += 0.5 * math.Pow(targets[i]-nn.OutputActivations[i], 2) } return e } /* This method is used to train the Network, it will run the training operation for 'iterations' times and return the computed errors when training. */ func (nn *FeedForward) Train(patterns [][][]float64, iterations int, lRate, mFactor float64, debug bool) []float64 { errors := make([]float64, iterations) for i := 0; i < iterations; i++ { var e float64 for _, p := range patterns { nn.Update(p[0]) tmp := nn.BackPropagate(p[1], lRate, mFactor) e += tmp } errors[i] = e if debug && i%1000 == 0 { fmt.Println(i, e) } } return errors } func (nn *FeedForward) Test(patterns [][][]float64) { for _, p := range patterns { fmt.Println(p[0], "->", nn.Update(p[0]), " : ", p[1]) } }
vendor/github.com/axamon/gobrain/feedforward.go
0.616128
0.460046
feedforward.go
starcoder
package gohorizon import ( "encoding/json" ) // DatastoreSpaceRequirementInfo Information about Datastore Space Requirement. type DatastoreSpaceRequirementInfo struct { // Indicates the type of disk used for storage. * OS: Disk to store operating system related data. * REPLICA: Disk for placement of replica VMs created by instant clone engine. DiskType *string `json:"disk_type,omitempty"` // Indicates maximum recommended disk space, in GB. MaxSizeDiskGb *float64 `json:"max_size_disk_gb,omitempty"` // Indicates recommended disk space with 50% utilization, in GB. MidSizeDiskGb *float64 `json:"mid_size_disk_gb,omitempty"` // Indicates minimum recommended disk space, in GB. MinSizeDiskGb *float64 `json:"min_size_disk_gb,omitempty"` } // NewDatastoreSpaceRequirementInfo instantiates a new DatastoreSpaceRequirementInfo 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 NewDatastoreSpaceRequirementInfo() *DatastoreSpaceRequirementInfo { this := DatastoreSpaceRequirementInfo{} return &this } // NewDatastoreSpaceRequirementInfoWithDefaults instantiates a new DatastoreSpaceRequirementInfo 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 NewDatastoreSpaceRequirementInfoWithDefaults() *DatastoreSpaceRequirementInfo { this := DatastoreSpaceRequirementInfo{} return &this } // GetDiskType returns the DiskType field value if set, zero value otherwise. func (o *DatastoreSpaceRequirementInfo) GetDiskType() string { if o == nil || o.DiskType == nil { var ret string return ret } return *o.DiskType } // GetDiskTypeOk returns a tuple with the DiskType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DatastoreSpaceRequirementInfo) GetDiskTypeOk() (*string, bool) { if o == nil || o.DiskType == nil { return nil, false } return o.DiskType, true } // HasDiskType returns a boolean if a field has been set. func (o *DatastoreSpaceRequirementInfo) HasDiskType() bool { if o != nil && o.DiskType != nil { return true } return false } // SetDiskType gets a reference to the given string and assigns it to the DiskType field. func (o *DatastoreSpaceRequirementInfo) SetDiskType(v string) { o.DiskType = &v } // GetMaxSizeDiskGb returns the MaxSizeDiskGb field value if set, zero value otherwise. func (o *DatastoreSpaceRequirementInfo) GetMaxSizeDiskGb() float64 { if o == nil || o.MaxSizeDiskGb == nil { var ret float64 return ret } return *o.MaxSizeDiskGb } // GetMaxSizeDiskGbOk returns a tuple with the MaxSizeDiskGb field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DatastoreSpaceRequirementInfo) GetMaxSizeDiskGbOk() (*float64, bool) { if o == nil || o.MaxSizeDiskGb == nil { return nil, false } return o.MaxSizeDiskGb, true } // HasMaxSizeDiskGb returns a boolean if a field has been set. func (o *DatastoreSpaceRequirementInfo) HasMaxSizeDiskGb() bool { if o != nil && o.MaxSizeDiskGb != nil { return true } return false } // SetMaxSizeDiskGb gets a reference to the given float64 and assigns it to the MaxSizeDiskGb field. func (o *DatastoreSpaceRequirementInfo) SetMaxSizeDiskGb(v float64) { o.MaxSizeDiskGb = &v } // GetMidSizeDiskGb returns the MidSizeDiskGb field value if set, zero value otherwise. func (o *DatastoreSpaceRequirementInfo) GetMidSizeDiskGb() float64 { if o == nil || o.MidSizeDiskGb == nil { var ret float64 return ret } return *o.MidSizeDiskGb } // GetMidSizeDiskGbOk returns a tuple with the MidSizeDiskGb field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DatastoreSpaceRequirementInfo) GetMidSizeDiskGbOk() (*float64, bool) { if o == nil || o.MidSizeDiskGb == nil { return nil, false } return o.MidSizeDiskGb, true } // HasMidSizeDiskGb returns a boolean if a field has been set. func (o *DatastoreSpaceRequirementInfo) HasMidSizeDiskGb() bool { if o != nil && o.MidSizeDiskGb != nil { return true } return false } // SetMidSizeDiskGb gets a reference to the given float64 and assigns it to the MidSizeDiskGb field. func (o *DatastoreSpaceRequirementInfo) SetMidSizeDiskGb(v float64) { o.MidSizeDiskGb = &v } // GetMinSizeDiskGb returns the MinSizeDiskGb field value if set, zero value otherwise. func (o *DatastoreSpaceRequirementInfo) GetMinSizeDiskGb() float64 { if o == nil || o.MinSizeDiskGb == nil { var ret float64 return ret } return *o.MinSizeDiskGb } // GetMinSizeDiskGbOk returns a tuple with the MinSizeDiskGb field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DatastoreSpaceRequirementInfo) GetMinSizeDiskGbOk() (*float64, bool) { if o == nil || o.MinSizeDiskGb == nil { return nil, false } return o.MinSizeDiskGb, true } // HasMinSizeDiskGb returns a boolean if a field has been set. func (o *DatastoreSpaceRequirementInfo) HasMinSizeDiskGb() bool { if o != nil && o.MinSizeDiskGb != nil { return true } return false } // SetMinSizeDiskGb gets a reference to the given float64 and assigns it to the MinSizeDiskGb field. func (o *DatastoreSpaceRequirementInfo) SetMinSizeDiskGb(v float64) { o.MinSizeDiskGb = &v } func (o DatastoreSpaceRequirementInfo) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.DiskType != nil { toSerialize["disk_type"] = o.DiskType } if o.MaxSizeDiskGb != nil { toSerialize["max_size_disk_gb"] = o.MaxSizeDiskGb } if o.MidSizeDiskGb != nil { toSerialize["mid_size_disk_gb"] = o.MidSizeDiskGb } if o.MinSizeDiskGb != nil { toSerialize["min_size_disk_gb"] = o.MinSizeDiskGb } return json.Marshal(toSerialize) } type NullableDatastoreSpaceRequirementInfo struct { value *DatastoreSpaceRequirementInfo isSet bool } func (v NullableDatastoreSpaceRequirementInfo) Get() *DatastoreSpaceRequirementInfo { return v.value } func (v *NullableDatastoreSpaceRequirementInfo) Set(val *DatastoreSpaceRequirementInfo) { v.value = val v.isSet = true } func (v NullableDatastoreSpaceRequirementInfo) IsSet() bool { return v.isSet } func (v *NullableDatastoreSpaceRequirementInfo) Unset() { v.value = nil v.isSet = false } func NewNullableDatastoreSpaceRequirementInfo(val *DatastoreSpaceRequirementInfo) *NullableDatastoreSpaceRequirementInfo { return &NullableDatastoreSpaceRequirementInfo{value: val, isSet: true} } func (v NullableDatastoreSpaceRequirementInfo) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableDatastoreSpaceRequirementInfo) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_datastore_space_requirement_info.go
0.779657
0.409221
model_datastore_space_requirement_info.go
starcoder
package vfs // Help contains text describing file and directory caching to add to // the command help. var Help = ` ### Directory Cache Using the ` + "`--dir-cache-time`" + ` flag, you can set how long a directory should be considered up to date and not refreshed from the backend. Changes made locally in the mount may appear immediately or invalidate the cache. However, changes done on the remote will only be picked up once the cache expires. Alternatively, you can send a ` + "`SIGHUP`" + ` signal to rclone for it to flush all directory caches, regardless of how old they are. Assuming only one rclone instance is running, you can reset the cache like this: kill -SIGHUP $(pidof rclone) ### File Caching **NB** File caching is **EXPERIMENTAL** - use with care! These flags control the VFS file caching options. The VFS layer is used by rclone mount to make a cloud storage system work more like a normal file system. You'll need to enable VFS caching if you want, for example, to read and write simultaneously to a file. See below for more details. Note that the VFS cache works in addition to the cache backend and you may find that you need one or the other or both. --cache-dir string Directory rclone will use for caching. --vfs-cache-max-age duration Max age of objects in the cache. (default 1h0m0s) --vfs-cache-mode string Cache mode off|minimal|writes|full (default "off") --vfs-cache-poll-interval duration Interval to poll the cache for stale objects. (default 1m0s) If run with ` + "`-vv`" + ` rclone will print the location of the file cache. The files are stored in the user cache file area which is OS dependent but can be controlled with ` + "`--cache-dir`" + ` or setting the appropriate environment variable. The cache has 4 different modes selected by ` + "`--vfs-cache-mode`" + `. The higher the cache mode the more compatible rclone becomes at the cost of using disk space. Note that files are written back to the remote only when they are closed so if rclone is quit or dies with open files then these won't get written back to the remote. However they will still be in the on disk cache. #### --vfs-cache-mode off In this mode the cache will read directly from the remote and write directly to the remote without caching anything on disk. This will mean some operations are not possible * Files can't be opened for both read AND write * Files opened for write can't be seeked * Existing files opened for write must have O_TRUNC set * Files open for read with O_TRUNC will be opened write only * Files open for write only will behave as if O_TRUNC was supplied * Open modes O_APPEND, O_TRUNC are ignored * If an upload fails it can't be retried #### --vfs-cache-mode minimal This is very similar to "off" except that files opened for read AND write will be buffered to disks. This means that files opened for write will be a lot more compatible, but uses the minimal disk space. These operations are not possible * Files opened for write only can't be seeked * Existing files opened for write must have O_TRUNC set * Files opened for write only will ignore O_APPEND, O_TRUNC * If an upload fails it can't be retried #### --vfs-cache-mode writes In this mode files opened for read only are still read directly from the remote, write only and read/write files are buffered to disk first. This mode should support all normal file system operations. If an upload fails it will be retried up to --low-level-retries times. #### --vfs-cache-mode full In this mode all reads and writes are buffered to and from disk. When a file is opened for read it will be downloaded in its entirety first. This may be appropriate for your needs, or you may prefer to look at the cache backend which does a much more sophisticated job of caching, including caching directory hierarchies and chunks of files. In this mode, unlike the others, when a file is written to the disk, it will be kept on the disk after it is written to the remote. It will be purged on a schedule according to ` + "`--vfs-cache-max-age`" + `. This mode should support all normal file system operations. If an upload or download fails it will be retried up to --low-level-retries times. `
vfs/help.go
0.739516
0.461381
help.go
starcoder
package other import ( "time" "github.com/kasworld/h4o/_examples/app" "github.com/kasworld/h4o/geometry" "github.com/kasworld/h4o/gls" "github.com/kasworld/h4o/graphic" "github.com/kasworld/h4o/material" "github.com/kasworld/h4o/math32" ) func init() { app.DemoMap["other.curves"] = &Curves2{} } type Curves2 struct { points *graphic.Points } // Start is called once at the start of the demo. func (t *Curves2) Start(a *app.App) { // Create geometry for continued curves geom1 := geometry.NewGeometry() positions := math32.NewArrayF32(0, 0) colors := math32.NewArrayF32(0, 0) controlPoints := []*math32.Vector3{} quadBezier := math32.NewBezierQuadratic( math32.NewVector3(-1, 0, 0), math32.NewVector3(-1, -1, 0), math32.NewVector3(0, -1, 0), 30) controlPoints = append(controlPoints, math32.NewVector3(-1, -1, 0), ) cubeBezier := math32.NewBezierCubic( math32.NewVector3(0, -1, 0), math32.NewVector3(1, -1, 0), math32.NewVector3(1, 1, 0), math32.NewVector3(0, 1, 0), 30) controlPoints = append(controlPoints, math32.NewVector3(1, -1, 0), math32.NewVector3(1, 1, 0), ) hermiteSpline := math32.NewHermiteSpline( math32.NewVector3(0, 1, 0), math32.NewVector3(0, 2, 0), math32.NewVector3(-1, 0, 0), math32.NewVector3(-2, 0, 0), 30) controlPoints = append(controlPoints, math32.NewVector3(0, 2, 0), math32.NewVector3(-2, 0, 0), ) continuedCurve := quadBezier.Continue(cubeBezier).Continue(hermiteSpline) continuedPoints := continuedCurve.GetPoints() // 91 points for i := 0; i < len(continuedPoints); i++ { positions.AppendVector3(&continuedPoints[i]) if i < 30 { colors.Append(1, 0, 0) } else if i <= 60 { colors.Append(0, 1, 0) } else { colors.Append(0, 0, 1) } } geom1.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition)) geom1.AddVBO(gls.NewVBO(colors).AddAttrib(gls.VertexColor)) mat1 := material.NewBasic() lines1 := graphic.NewLineStrip(geom1, mat1) a.Scene().Add(lines1) // Points from curve controls pointsGeom := geometry.NewGeometry() positions = math32.NewArrayF32(0, 0) for i := 0; i < len(controlPoints); i++ { positions.AppendVector3(controlPoints[i].Clone()) } pointsGeom.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition)) mat11 := material.NewPoint(&math32.Color{0, 0, 0}) mat11.SetSize(50) points1 := graphic.NewPoints(pointsGeom, mat11) a.Scene().Add(points1) // CatmullRom Spline through control points geom2 := geometry.NewGeometry() positions = math32.NewArrayF32(0, 0) colors = math32.NewArrayF32(0, 0) catmullRom := math32.NewCatmullRomSpline(controlPoints, 30, true) catmullPoints := catmullRom.GetPoints() for i := 0; i < len(catmullPoints); i++ { positions.AppendVector3(&catmullPoints[i]) if i%3 == 0 { colors.Append(1, 0, 0) colors.Append(0, 1, 0) colors.Append(0, 0, 1) } } geom2.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition)) geom2.AddVBO(gls.NewVBO(colors).AddAttrib(gls.VertexColor)) mat2 := material.NewBasic() lines2 := graphic.NewLineStrip(geom2, mat2) a.Scene().Add(lines2) } // Update is called every frame. func (t *Curves2) Update(a *app.App, deltaTime time.Duration) {} // Cleanup is called once at the end of the demo. func (t *Curves2) Cleanup(a *app.App) {}
_examples/demos/other/curves.go
0.534127
0.606149
curves.go
starcoder
package core // Buffer interface type Buffer interface { Push(elemt Elemt, running bool) error Data() []Elemt Apply() error } // DataBuffer that stores data. // In synchronous mode, when pushed() is called data are stored. // In asynchronous mode, when pushed() is called data are staged. // Staged data are stored when apply() is called. type DataBuffer struct { pipe chan Elemt data []Elemt strategy bufferSizeStrategy } // Maximal default pipe size const pipeSize = 2000 // NewDataBuffer creates a fixed size buffer if given size > 0. // Otherwise creates an infinite size buffer. func NewDataBuffer(data []Elemt, size int) Buffer { var db = DataBuffer{ pipe: make(chan Elemt, pipeSize), } switch { case size > len(data): // fixed size buffer, less data than buffer size db.strategy = &fixedSizeStrategy{size, len(data)} db.data = make([]Elemt, len(data), size) copy(db.data[:len(data)], data) case size > 0: // fixed size buffer, more data than buffer size db.strategy = &fixedSizeStrategy{size, size} db.data = make([]Elemt, size) copy(db.data, data[len(data)-size:]) default: // infinite buffer db.strategy = &infiniteSizeStrategy{} db.data = make([]Elemt, len(data)) copy(db.data, data) } return &db } // Push stores or stages an element depending on synchronous / asynchronous mode. func (b *DataBuffer) Push(elmt Elemt, running bool) (err error) { if running { b.pipe <- elmt } else { b.data = b.strategy.push(b.data, elmt) } return } // Data returns buffer data func (b *DataBuffer) Data() (data []Elemt) { return b.data } // Apply all staged data in asynchronous mode, otherwise do nothing func (b *DataBuffer) Apply() (err error) { for b.applyNext() { } return } // Applies next staged data if available and returns true. // Otherwise returns false. func (b *DataBuffer) applyNext() (ok bool) { var elmt Elemt select { case elmt, ok = <-b.pipe: if ok { b.data = b.strategy.push(b.data, elmt) } default: } return } // Handle the way data are stored, i.e. infinite or fixed size buffer. type bufferSizeStrategy interface { push(data []Elemt, elemt Elemt) []Elemt } // Fixed size buffer type fixedSizeStrategy struct { size int position int } func (s *fixedSizeStrategy) push(data []Elemt, elemt Elemt) []Elemt { if s.position == s.size { s.position = 0 } if s.position < len(data) { data[s.position] = elemt } else { data = append(data, elemt) } s.position++ return data } // Infinite size buffer type infiniteSizeStrategy struct { } func (s *infiniteSizeStrategy) push(data []Elemt, elemt Elemt) []Elemt { return append(data, elemt) }
core/buffer.go
0.688887
0.414306
buffer.go
starcoder
package gographviz import ( "github.com/awalterschulze/gographviz/ast" ) //Creates a Graph structure by analysing an Abstract Syntax Tree representing a parsed graph. func NewAnalysedGraph(graph *ast.Graph) *Graph { g := NewGraph() Analyse(graph, g) return g } //Analyses an Abstract Syntax Tree representing a parsed graph into a newly created graph structure Interface. func Analyse(graph *ast.Graph, g Interface) { graph.Walk(&graphVisitor{g}) } type nilVisitor struct { } func (this *nilVisitor) Visit(v ast.Elem) ast.Visitor { return this } type graphVisitor struct { g Interface } func (this *graphVisitor) Visit(v ast.Elem) ast.Visitor { graph, ok := v.(*ast.Graph) if !ok { return this } this.g.SetStrict(graph.Strict) this.g.SetDir(graph.Type == ast.DIGRAPH) graphName := graph.Id.String() this.g.SetName(graphName) return newStmtVisitor(this.g, graphName) } func newStmtVisitor(g Interface, graphName string) *stmtVisitor { return &stmtVisitor{g, graphName, make(Attrs), make(Attrs), make(Attrs)} } type stmtVisitor struct { g Interface graphName string currentNodeAttrs Attrs currentEdgeAttrs Attrs currentGraphAttrs Attrs } func (this *stmtVisitor) Visit(v ast.Elem) ast.Visitor { switch s := v.(type) { case ast.NodeStmt: return this.nodeStmt(s) case ast.EdgeStmt: return this.edgeStmt(s) case ast.NodeAttrs: return this.nodeAttrs(s) case ast.EdgeAttrs: return this.edgeAttrs(s) case ast.GraphAttrs: return this.graphAttrs(s) case *ast.SubGraph: return this.subGraph(s) case *ast.Attr: return this.attr(s) case ast.AttrList: return &nilVisitor{} default: //fmt.Fprintf(os.Stderr, "unknown stmt %T\n", v) } return this } func ammend(attrs Attrs, add Attrs) Attrs { for key, value := range add { if _, ok := attrs[key]; !ok { attrs[key] = value } } return attrs } func overwrite(attrs Attrs, overwrite Attrs) Attrs { for key, value := range overwrite { attrs[key] = value } return attrs } func (this *stmtVisitor) nodeStmt(stmt ast.NodeStmt) ast.Visitor { attrs := Attrs(stmt.Attrs.GetMap()) attrs = ammend(attrs, this.currentNodeAttrs) this.g.AddNode(this.graphName, stmt.NodeId.String(), attrs) return &nilVisitor{} } func (this *stmtVisitor) edgeStmt(stmt ast.EdgeStmt) ast.Visitor { attrs := stmt.Attrs.GetMap() attrs = ammend(attrs, this.currentEdgeAttrs) src := stmt.Source.GetId() srcName := src.String() if stmt.Source.IsNode() { this.g.AddNode(this.graphName, srcName, this.currentNodeAttrs.Copy()) } srcPort := stmt.Source.GetPort() for i := range stmt.EdgeRHS { directed := bool(stmt.EdgeRHS[i].Op) dst := stmt.EdgeRHS[i].Destination.GetId() dstName := dst.String() if stmt.EdgeRHS[i].Destination.IsNode() { this.g.AddNode(this.graphName, dstName, this.currentNodeAttrs.Copy()) } dstPort := stmt.EdgeRHS[i].Destination.GetPort() this.g.AddPortEdge(srcName, srcPort.String(), dstName, dstPort.String(), directed, attrs) src = dst srcPort = dstPort srcName = dstName } return this } func (this *stmtVisitor) nodeAttrs(stmt ast.NodeAttrs) ast.Visitor { this.currentNodeAttrs = overwrite(this.currentNodeAttrs, ast.AttrList(stmt).GetMap()) return &nilVisitor{} } func (this *stmtVisitor) edgeAttrs(stmt ast.EdgeAttrs) ast.Visitor { this.currentEdgeAttrs = overwrite(this.currentEdgeAttrs, ast.AttrList(stmt).GetMap()) return &nilVisitor{} } func (this *stmtVisitor) graphAttrs(stmt ast.GraphAttrs) ast.Visitor { attrs := ast.AttrList(stmt).GetMap() for key, value := range attrs { this.g.AddAttr(this.graphName, key, value) } this.currentGraphAttrs = overwrite(this.currentGraphAttrs, attrs) return &nilVisitor{} } func (this *stmtVisitor) subGraph(stmt *ast.SubGraph) ast.Visitor { subGraphName := stmt.Id.String() this.g.AddSubGraph(this.graphName, subGraphName, this.currentGraphAttrs) return newStmtVisitor(this.g, subGraphName) } func (this *stmtVisitor) attr(stmt *ast.Attr) ast.Visitor { this.g.AddAttr(this.graphName, stmt.Field.String(), stmt.Value.String()) return this }
vendor/github.com/awalterschulze/gographviz/analyse.go
0.670824
0.411939
analyse.go
starcoder
package zipfian import ( "math" "math/rand" "time" ) /** * Used to generate zipfian distributed random numbers where the distribution is * skewed toward the lower integers; e.g. 0 will be the most popular, 1 the next * most popular, etc. * * This class implements the core algorithm from YCSB's ZipfianGenerator; it, in * turn, uses the algorithm from "Quickly Generating Billion-Record Synthetic * Databases", <NAME> et al, SIGMOD 1994. */ type ZipfianGenerator struct { n float64 // Range of numbers to be generated. theta float64 // Parameter of the zipfian distribution. alpha float64 // Special intermediate result used for generation. zetan float64 // Special intermediate result used for generation. eta float64 // Special intermediate result used for generation. r *rand.Rand } /** * Construct a generator. This may be expensive if n is large. * * \param n * The generator will output random numbers between 0 and n-1. * \param theta * The zipfian parameter where 0 < theta < 1 defines the skew; the * smaller the value the more skewed the distribution will be. Default * value of 0.99 comes from the YCSB default value. */ func NewZipfianGenerator(n uint64, theta float64) ZipfianGenerator { zetan := Zeta(n, theta) return ZipfianGenerator{ n: float64(n), theta: theta, alpha: (1.0 / (1.0 - theta)), zetan: zetan, eta: (1.0 - math.Pow(2.0/float64(n), 1.0-theta)) / (1.0 - Zeta(2.0, theta)/zetan), r: rand.New(rand.NewSource(time.Now().UnixNano())), } } /** * Return the zipfian distributed random number between 0 and n-1. * Partially inspired by https://github.com/cockroachdb/cockroach/blob/2eebbddbb133eea7102a47fbe7f5d13ec6f8f670/pkg/workload/ycsb/zipfgenerator.go */ func (z ZipfianGenerator) NextNumber() uint64 { u := z.r.Float64() uz := u * z.zetan if uz < 1 { return 0 } if uz < 1+math.Pow(0.5, z.theta) { return 1 } return 0 + uint64(float64(z.n)*math.Pow(z.eta*u-z.eta+1.0, z.alpha)) } /** * Returns the nth harmonic number with parameter theta; e.g. H_{n,theta}. */ func Zeta(n uint64, theta float64) float64 { // Some of these take quite a while to compute, so return // common results immediately if theta == 0.99 { if n == 1e9 { return 23.60336399999999912324710749089717864990234375 } } if theta == 0.95 { if n == 1e9 { return 36.94122142977597178514770348556339740753173828125 } } if theta == 0.90 { if n == 1e9 { return 70.0027094570042294208178645931184291839599609375 } } if theta == 0.85 { if n == 1e9 { return 143.14759472538497675486723892390727996826171875 } } if theta == 0.80 { if n == 1e9 { return 311.04113385576732753179385326802730560302734375 } } if theta == 0.75 { if n == 1e9 { return 707.87047871782715446897782385349273681640625 } } if theta == 0.70 { if n == 1e9 { return 1667.845723895596393049345351755619049072265625 } } if theta == 0.65 { if n == 1e9 { return 4033.51556666213946300558745861053466796875 } } if theta == 0.60 { if n == 1e9 { return 9950.726604378511183313094079494476318359375 } } if theta == 0.55 { if n == 1e9 { return 24932.0647149890646687708795070648193359375 } } if theta == 0.50 { if n == 1e9 { return 63244.092864672114956192672252655029296875 } } var sum float64 = 0 var i float64 for i = 0; i < float64(n); i++ { sum = sum + 1.0/(math.Pow(i+1.0, theta)) } return sum }
src/zipfian/zipfian.go
0.766468
0.502136
zipfian.go
starcoder
package main import ( "container/heap" "fmt" ) /* You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. You are running a simulation system that will shut down after all tasks are processed. Each server can only process one task at a time. You will be able to process the jth task starting from the jth second beginning with the 0th task at second 0. To process task j, you assign it to the server with the smallest weight that is free, and in case of a tie, choose the server with the smallest index. If a free server gets assigned task j at second t,​​​​​​ it will be free again at the second t + tasks[j]. If there are no free servers, you must wait until one is free and execute the free tasks as soon as possible. If multiple tasks need to be assigned, assign them in order of increasing index. You may assign multiple tasks at the same second if there are multiple free servers. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​. Example 1: Input: servers = [3,3,2], tasks = [1,2,3,2,1,2] Output: [2,2,0,2,1,2] Explanation: Events in chronological order go as follows: - At second 0, task 0 is added and processed using server 2 until second 1. - At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3. - At second 2, task 2 is added and processed using server 0 until second 5. - At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5. - At second 4, task 4 is added and processed using server 1 until second 5. - At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7. Example 2: Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1] Output: [1,4,1,4,1,3,2] Explanation: Events in chronological order go as follows: - At second 0, task 0 is added and processed using server 1 until second 2. - At second 1, task 1 is added and processed using server 4 until second 2. - At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. - At second 3, task 3 is added and processed using server 4 until second 7. - At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. - At second 5, task 5 is added and processed using server 3 until second 7. - At second 6, task 6 is added and processed using server 2 until second 7. Constraints: servers.length == n tasks.length == m 1 <= n, m <= 2 * 105 1 <= servers[i], tasks[j] <= 2 * 105 */ type AvailableServer struct { weight int index int } type AvailableServersPriorityQueue []*AvailableServer func (pq AvailableServersPriorityQueue) Len() int { return len(pq) } func (pq AvailableServersPriorityQueue) Less(i, j int) bool { if pq[i].weight == pq[j].weight { return pq[i].index < pq[j].index } return pq[i].weight < pq[j].weight } func (pq AvailableServersPriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *AvailableServersPriorityQueue) Push(x interface{}) { item := x.(*AvailableServer) *pq = append(*pq, item) } func (pq *AvailableServersPriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] old[n-1] = nil *pq = old[0 : n-1] return item } type UnavailableServer struct { availableAt int weight int index int } type UnavailableServersPriorityQueue []*UnavailableServer func (pq UnavailableServersPriorityQueue) Len() int { return len(pq) } func (pq UnavailableServersPriorityQueue) Less(i, j int) bool { if pq[i].availableAt == pq[j].availableAt { return pq[i].index < pq[j].index } return pq[i].availableAt < pq[j].availableAt } func (pq UnavailableServersPriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *UnavailableServersPriorityQueue) Push(x interface{}) { item := x.(*UnavailableServer) *pq = append(*pq, item) } func (pq *UnavailableServersPriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] old[n-1] = nil *pq = old[0 : n-1] return item } // time O(n log n) // space O(n). func assignTasks(servers []int, tasks []int) []int { availableServers := make(AvailableServersPriorityQueue, 0, len(servers)) for index, serverWeight := range servers { availableServers = append(availableServers, &AvailableServer{ weight: serverWeight, index: index, }) } heap.Init(&availableServers) unavailableServers := make(UnavailableServersPriorityQueue, 0) assignments := make([]int, 0, len(tasks)) t := 0 for _, timeToCompleteTask := range tasks { if len(availableServers) == 0 { t = unavailableServers[0].availableAt } for len(unavailableServers) > 0 && unavailableServers[0].availableAt <= t { unavailableServer := heap.Pop(&unavailableServers).(*UnavailableServer) heap.Push(&availableServers, &AvailableServer{ weight: unavailableServer.weight, index: unavailableServer.index, }) } serverThatWillExecuteTask := heap.Pop(&availableServers).(*AvailableServer) assignments = append(assignments, serverThatWillExecuteTask.index) heap.Push(&unavailableServers, &UnavailableServer{ weight: serverThatWillExecuteTask.weight, index: serverThatWillExecuteTask.index, availableAt: t + timeToCompleteTask, }) t++ } return assignments } func main() { // Output: [2,2,0,2,1,2] fmt.Println(assignTasks([]int{3, 3, 2}, []int{1, 2, 3, 2, 1, 2})) // Output: [1,4,1,4,1,3,2] fmt.Println(assignTasks([]int{5, 1, 4, 3, 2}, []int{2, 1, 2, 4, 5, 2, 1})) }
golang/algorithms/others/process_tasks_using_servers/main.go
0.655336
0.603932
main.go
starcoder
package sergeant import ( "bytes" "fmt" "path/filepath" "strings" "time" "github.com/albatross-org/go-albatross/entries" "gopkg.in/yaml.v3" ) // Card is the basic unit of the program. It's an abstraction over an Albatross entry and represents a question-answer pair. type Card struct { ID string Path string Date time.Time Tags []string Notes string CompletionsPerfect []Completion CompletionsMinor []Completion CompletionsMajor []Completion QuestionPath string AnswerPath string } // Completion is a mark specifying that a card was completed at a certain date in a certain amount of time. type Completion struct { Date time.Time `yaml:"date"` Duration time.Duration `yaml:"time"` } // PathParent returns the path to the parent of the card. You could think of this as the card category. func (card *Card) PathParent() string { return filepath.Dir(card.Path) } // QuestionImage returns the data URI of the question image, created by converting the file to base64. func (card *Card) QuestionImage() (string, error) { return encodeAsDataURI(card.QuestionPath) } // AnswerImage returns the data URI of the answer image, created by converting the file to base64. func (card *Card) AnswerImage() (string, error) { return encodeAsDataURI(card.AnswerPath) } // TotalCompletions returns the total number of completions for this card. func (card *Card) TotalCompletions() int { return len(card.CompletionsMajor) + len(card.CompletionsMinor) + len(card.CompletionsPerfect) } // Content returns how the card is represented as an entry. Think of it like the opposite of cardFromEntry. func (card *Card) Content() (string, error) { type frontmatter struct { Title string `yaml:"title"` Type string `yaml:"type"` Tags []string `yaml:"tags"` Date string `yaml:"date"` Completions map[string][]map[string]string } entryFrontmatter := frontmatter{ Title: "Question " + card.ID, Type: "question", Tags: card.Tags, Completions: map[string][]map[string]string{ "perfect": completionToStringMap(card.CompletionsPerfect), "minor": completionToStringMap(card.CompletionsMinor), "major": completionToStringMap(card.CompletionsMajor), }, Date: card.Date.Format("2006-01-02 15:04"), } frontmatterBytes, err := yaml.Marshal(entryFrontmatter) if err != nil { return "", fmt.Errorf("couldn't marshal new entry frontmatter: %w", err) } var out bytes.Buffer out.WriteString("---\n") out.Write(frontmatterBytes) out.WriteString("---\n") out.WriteString(card.Notes) return out.String(), nil } // cardFromEntry creates a Card from an *entries.Entry. // Since a card is an abstraction over an entry, we have to painstakingly go through each individual piece of metadata // rather than unmarshalling it to a struct. The card follows this pattern: // --- // title: "Question <random 16-character string>" // 16 character string becomes ID // type: "question" // Used to verify this is in fact a question. // tags: ["@?any-tags"] // This becomes the .Tags field. // completions: // perfect: // This becomes the .CompletionsPerfect field. // - date: 2021-02-16 10:18 // time: 7m10s // minor: // This becomes the .CompletionsMinor field. // - date: 2021-02-16 10:18 // time: 5m51s // major: // This becomes the .CompletionsMajor field. // - date: 2021-02-16 10:18 // time: 5m53s // - date: 2021-02-16 10:18 // time: 5m53s // --- // Any additional notes about the card (This becomes the .Notes field). func cardFromEntry(entry *entries.Entry) (*Card, error) { var card = &Card{} // Check the entry is nil, we want to error instead of panicing with a nil pointer dereference. if entry == nil { return nil, fmt.Errorf("entry is nil") } // Verify that the entry's type field is correct. // Still not sure how I feel about this, is this is an unnecceasy step? entryType, ok := entry.Metadata["type"].(string) if !ok { return nil, fmt.Errorf("missing required 'type' field in card entry metadata") } if entryType != "question" { return nil, fmt.Errorf("expected metadata field 'type' to be 'question', not %q", entryType) } // Get the path of the question. card.Path = entry.Path // Copy accross any tags. card.Tags = entry.Tags // Copy across the date. card.Date = entry.Date // Copy across the content/notes. card.Notes = entry.Contents // Get the ID of the question. if !strings.HasPrefix(entry.Title, "Question ") { return nil, fmt.Errorf("expected card title to start with 'Question', it is %q", entry.Title) } card.ID = strings.TrimPrefix(entry.Title, "Question ") // Get the completions. // This is a map of completion types ("perfect", "minor", "major") to lists of completions ("date", "time"). completionsMapInterface, ok := entry.Metadata["completions"].(map[interface{}]interface{}) if !ok { return nil, fmt.Errorf("couldn't parse 'completions' completions in card entry metadata") } completionsMap, err := completionsMapInterfaceToTypedMap(completionsMapInterface) if err != nil { return nil, err } completionsPerfect, completionsMinor, completionsMajor, err := completionsMapToStruct(completionsMap) if err != nil { return nil, err } card.CompletionsPerfect = completionsPerfect card.CompletionsMinor = completionsMinor card.CompletionsMajor = completionsMajor // Verify that a question and answer are attached and set them. var questionPath, answerPath string for _, attachment := range entry.Attachments { if strings.HasPrefix(attachment.Name, "question.") { questionPath = attachment.AbsPath } else if strings.HasPrefix(attachment.Name, "answer.") { answerPath = attachment.AbsPath } } if questionPath == "" { return nil, fmt.Errorf("card entry has no 'question' attachment") } if answerPath == "" { return nil, fmt.Errorf("card entry has no 'answer' attachment") } card.QuestionPath = questionPath card.AnswerPath = answerPath return card, nil } // completionsMapInterfaceToTypedMap converts a map[interface{}]interface{} to a map[string][]map[string]string, the format ready to be used // by the rest of the program. // I feel like there's a much better way of doing this and the variable names make me want to be sick. Is it really neccessary to cast this many // times or can you combine them somehow? func completionsMapInterfaceToTypedMap(mapInterface map[interface{}]interface{}) (map[string][]map[string]string, error) { stringToSlice := map[string][]interface{}{} // In this first step, we turn the overall map[interface{}]interface{} into a map[string][]interface{}{} for key, value := range mapInterface { keyString, ok := key.(string) if !ok { return nil, fmt.Errorf("couldn't convert completions metadata to typed map, %q not a string, got %T instead", key, key) } valueSlice, ok := value.([]interface{}) if !ok { return nil, fmt.Errorf("coulnd't convert completions metadata to typed map, %q not a slice of interface{}, got %T instead", value, value) } stringToSlice[keyString] = valueSlice } stringToInterfaceMap := map[string][]map[interface{}]interface{}{} // In this step, we turn the map[string][]interface{} into a map[string][]map[interface{}]interface{}. // We need two loops here because Go can't do a type assertion on a []interface{}, only an interface{}. for key, value := range stringToSlice { interfaceMaps := []map[interface{}]interface{}{} for _, subValue := range value { subValueInterfaceMap, ok := subValue.(map[interface{}]interface{}) if !ok { return nil, fmt.Errorf("couln't convert completions metadata to typed map, %q not a map of interfaces, got %T instead", value, value) } interfaceMaps = append(interfaceMaps, subValueInterfaceMap) } stringToInterfaceMap[key] = interfaceMaps } stringToStringMap := map[string][]map[string]string{} // In this final step, we turn the map[string][]map[interface{}] into what we want, a map[string][]map[string]string. for key, value := range stringToInterfaceMap { stringMaps := []map[string]string{} for _, subInterfaceMap := range value { stringMap := map[string]string{} for subKey, subValue := range subInterfaceMap { keyString, ok := subKey.(string) if !ok { return nil, fmt.Errorf("couldn't convert completions metadata to typed map, subkey %q not a string, got %T instead", subKey, subKey) } valueString, ok := subValue.(string) if !ok { return nil, fmt.Errorf("couldn't convert completions metadata to typed map, subvalue %q not a string, got %T instead", subValue, subValue) } stringMap[keyString] = valueString } stringMaps = append(stringMaps, stringMap) } stringToStringMap[key] = stringMaps } return stringToStringMap, nil } // completionsMapToStruct converts a map consisting of completion types ("perfect", "minor", "major") mapped lists of completions ("date", "time") to // three lists of completion types. The order for return is perfect, minor and finally major completions. func completionsMapToStruct(completionsMap map[string][]map[string]string) (completionsPerfect []Completion, completionsMinor []Completion, completionsMajor []Completion, err error) { for completionType, completionList := range completionsMap { if completionType != "perfect" && completionType != "minor" && completionType != "major" { return nil, nil, nil, fmt.Errorf("not expecting completions field %q in card metadata", completionType) } for _, completionMap := range completionList { if completionMap["date"] == "" { return nil, nil, nil, fmt.Errorf("'date' field in %q completion list is empty", completionType) } if completionMap["time"] == "" { return nil, nil, nil, fmt.Errorf("'time' field in %q completion list is empty", completionType) } date, err := time.Parse("2006-01-02 15:04", completionMap["date"]) if err != nil { return nil, nil, nil, fmt.Errorf("'date' field %q in %q completion list not a valid '2006-01-02 15:04' date: %w", completionMap["date"], completionType, err) } duration, err := time.ParseDuration(completionMap["time"]) if err != nil { return nil, nil, nil, fmt.Errorf("'time' field %q in %q completion list not a valid duration: %w", completionMap["time"], completionType, err) } completion := Completion{ Date: date, Duration: duration, } switch completionType { case "perfect": completionsPerfect = append(completionsPerfect, completion) case "minor": completionsMinor = append(completionsMinor, completion) case "major": completionsMajor = append(completionsMajor, completion) } } } return completionsPerfect, completionsMinor, completionsMajor, nil } // completionToStringMap converts a []Completion to a []map[string]string. This is needed because by default YAML will unmarshal // time.Time fields using a different format to the one the program expects. By manually converting it to a map[string]string first, // we can use our own custom date format. func completionToStringMap(completions []Completion) []map[string]string { out := []map[string]string{} for _, completion := range completions { stringMap := map[string]string{} stringMap["date"] = completion.Date.Format("2006-01-02 15:04") stringMap["time"] = completion.Duration.String() out = append(out, stringMap) } return out }
card.go
0.750187
0.436442
card.go
starcoder
package constants var WORDS = map[string]bool{ "which": true, "there": true, "their": true, "about": true, "would": true, "these": true, "other": true, "words": true, "could": true, "write": true, "first": true, "water": true, "after": true, "where": true, "right": true, "think": true, "three": true, "years": true, "place": true, "sound": true, "great": true, "again": true, "still": true, "every": true, "small": true, "found": true, "those": true, "never": true, "under": true, "might": true, "while": true, "house": true, "world": true, "below": true, "asked": true, "going": true, "large": true, "until": true, "along": true, "shall": true, "being": true, "often": true, "earth": true, "began": true, "since": true, "study": true, "night": true, "light": true, "above": true, "paper": true, "parts": true, "young": true, "story": true, "point": true, "times": true, "heard": true, "whole": true, "white": true, "given": true, "means": true, "music": true, "miles": true, "thing": true, "today": true, "later": true, "using": true, "money": true, "lines": true, "order": true, "group": true, "among": true, "learn": true, "known": true, "space": true, "table": true, "early": true, "trees": true, "short": true, "hands": true, "state": true, "black": true, "shown": true, "stood": true, "front": true, "voice": true, "kinds": true, "makes": true, "comes": true, "close": true, "power": true, "lived": true, "vowel": true, "taken": true, "built": true, "heart": true, "ready": true, "quite": true, "class": true, "bring": true, "round": true, "horse": true, "shows": true, "piece": true, "green": true, "stand": true, "birds": true, "start": true, "river": true, "tried": true, "least": true, "field": true, "whose": true, "girls": true, "leave": true, "added": true, "color": true, "third": true, "hours": true, "moved": true, "plant": true, "doing": true, "names": true, "forms": true, "heavy": true, "ideas": true, "cried": true, "check": true, "floor": true, "begin": true, "woman": true, "alone": true, "plane": true, "spell": true, "watch": true, "carry": true, "wrote": true, "clear": true, "named": true, "books": true, "child": true, "glass": true, "human": true, "takes": true, "party": true, "build": true, "seems": true, "blood": true, "sides": true, "seven": true, "mouth": true, "solve": true, "north": true, "value": true, "death": true, "maybe": true, "happy": true, "tells": true, "gives": true, "looks": true, "shape": true, "lives": true, "steps": true, "areas": true, "sense": true, "speak": true, "force": true, "ocean": true, "speed": true, "women": true, "metal": true, "south": true, "grass": true, "scale": true, "cells": true, "lower": true, "sleep": true, "wrong": true, "pages": true, "ships": true, "needs": true, "rocks": true, "eight": true, "major": true, "level": true, "total": true, "ahead": true, "reach": true, "stars": true, "store": true, "sight": true, "terms": true, "catch": true, "works": true, "board": true, "cover": true, "songs": true, "equal": true, "stone": true, "waves": true, "guess": true, "dance": true, "spoke": true, "break": true, "cause": true, "radio": true, "weeks": true, "lands": true, "basic": true, "liked": true, "trade": true, "fresh": true, "final": true, "fight": true, "meant": true, "drive": true, "spent": true, "local": true, "waxes": true, "knows": true, "train": true, "bread": true, "homes": true, "teeth": true, "coast": true, "thick": true, "brown": true, "clean": true, "quiet": true, "sugar": true, "facts": true, "steel": true, "forth": true, "rules": true, "notes": true, "units": true, "peace": true, "month": true, "verbs": true, "seeds": true, "helps": true, "sharp": true, "visit": true, "woods": true, "chief": true, "walls": true, "cross": true, "wings": true, "grown": true, "cases": true, "foods": true, "crops": true, "fruit": true, "stick": true, "wants": true, "stage": true, "sheep": true, "nouns": true, "plain": true, "drink": true, "bones": true, "apart": true, "turns": true, "moves": true, "touch": true, "angle": true, "based": true, "range": true, "marks": true, "tired": true, "older": true, "farms": true, "spend": true, "shoes": true, "goods": true, "chair": true, "twice": true, "cents": true, "empty": true, "alike": true, "style": true, "broke": true, "pairs": true, "count": true, "enjoy": true, "score": true, "shore": true, "roots": true, "paint": true, "heads": true, "shook": true, "serve": true, "angry": true, "crowd": true, "wheel": true, "quick": true, "dress": true, "share": true, "alive": true, "noise": true, "solid": true, "cloth": true, "signs": true, "hills": true, "types": true, "drawn": true, "worth": true, "truck": true, "piano": true, "upper": true, "loved": true, "usual": true, "faces": true, "drove": true, "cabin": true, "boats": true, "towns": true, "proud": true, "court": true, "model": true, "prime": true, "fifty": true, "plans": true, "yards": true, "prove": true, "tools": true, "price": true, "sheet": true, "smell": true, "boxes": true, "raise": true, "match": true, "truth": true, "roads": true, "threw": true, "enemy": true, "lunch": true, "chart": true, "scene": true, "graph": true, "doubt": true, "guide": true, "winds": true, "block": true, "grain": true, "smoke": true, "mixed": true, "games": true, "wagon": true, "sweet": true, "topic": true, "extra": true, "plate": true, "title": true, "knife": true, "fence": true, "falls": true, "cloud": true, "wheat": true, "plays": true, "enter": true, "broad": true, "steam": true, "atoms": true, "press": true, "lying": true, "basis": true, "clock": true, "taste": true, "grows": true, "thank": true, "storm": true, "agree": true, "brain": true, "track": true, "smile": true, "funny": true, "beach": true, "stock": true, "hurry": true, "saved": true, "sorry": true, "giant": true, "trail": true, "offer": true, "ought": true, "rough": true, "daily": true, "avoid": true, "keeps": true, "throw": true, "allow": true, "cream": true, "laugh": true, "edges": true, "teach": true, "frame": true, "bells": true, "dream": true, "magic": true, "occur": true, "ended": true, "chord": true, "false": true, "skill": true, "holes": true, "dozen": true, "brave": true, "apple": true, "climb": true, "outer": true, "pitch": true, "ruler": true, "holds": true, "fixed": true, "costs": true, "calls": true, "blank": true, "staff": true, "labor": true, "eaten": true, "youth": true, "tones": true, "honor": true, "globe": true, "gases": true, "doors": true, "poles": true, "loose": true, "apply": true, "tears": true, "exact": true, "brush": true, "chest": true, "layer": true, "whale": true, "minor": true, "faith": true, "tests": true, "judge": true, "items": true, "worry": true, "waste": true, "hoped": true, "strip": true, "begun": true, "aside": true, "lakes": true, "bound": true, "depth": true, "candy": true, "event": true, "worse": true, "aware": true, "shell": true, "rooms": true, "ranch": true, "image": true, "snake": true, "aloud": true, "dried": true, "likes": true, "motor": true, "pound": true, "knees": true, "refer": true, "fully": true, "chain": true, "shirt": true, "flour": true, "drops": true, "spite": true, "orbit": true, "banks": true, "shoot": true, "curve": true, "tribe": true, "tight": true, "blind": true, "slept": true, "shade": true, "claim": true, "flies": true, "theme": true, "queen": true, "fifth": true, "union": true, "hence": true, "straw": true, "entry": true, "issue": true, "birth": true, "feels": true, "anger": true, "brief": true, "rhyme": true, "glory": true, "guard": true, "flows": true, "flesh": true, "owned": true, "trick": true, "yours": true, "sizes": true, "noted": true, "width": true, "burst": true, "route": true, "lungs": true, "uncle": true, "bears": true, "royal": true, "kings": true, "forty": true, "trial": true, "cards": true, "brass": true, "opera": true, "chose": true, "owner": true, "vapor": true, "beats": true, "mouse": true, "tough": true, "wires": true, "meter": true, "tower": true, "finds": true, "inner": true, "stuck": true, "arrow": true, "poems": true, "label": true, "swing": true, "solar": true, "truly": true, "tense": true, "beans": true, "split": true, "rises": true, "weigh": true, "hotel": true, "stems": true, "pride": true, "swung": true, "grade": true, "digit": true, "badly": true, "boots": true, "pilot": true, "sales": true, "swept": true, "lucky": true, "prize": true, "stove": true, "tubes": true, "acres": true, "wound": true, "steep": true, "slide": true, "trunk": true, "error": true, "porch": true, "slave": true, "exist": true, "faced": true, "mines": true, "marry": true, "juice": true, "raced": true, "waved": true, "goose": true, "trust": true, "fewer": true, "favor": true, "mills": true, "views": true, "joint": true, "eager": true, "spots": true, "blend": true, "rings": true, "adult": true, "index": true, "nails": true, "horns": true, "balls": true, "flame": true, "rates": true, "drill": true, "trace": true, "skins": true, "waxed": true, "seats": true, "stuff": true, "ratio": true, "minds": true, "dirty": true, "silly": true, "coins": true, "hello": true, "trips": true, "leads": true, "rifle": true, "hopes": true, "bases": true, "shine": true, "bench": true, "moral": true, "fires": true, "meals": true, "shake": true, "shops": true, "cycle": true, "movie": true, "slope": true, "canoe": true, "teams": true, "folks": true, "fired": true, "bands": true, "thumb": true, "shout": true, "canal": true, "habit": true, "reply": true, "ruled": true, "fever": true, "crust": true, "shelf": true, "walks": true, "midst": true, "crack": true, "print": true, "tales": true, "coach": true, "stiff": true, "flood": true, "verse": true, "awake": true, "rocky": true, "march": true, "fault": true, "swift": true, "faint": true, "civil": true, "ghost": true, "feast": true, "blade": true, "limit": true, "germs": true, "reads": true, "ducks": true, "dairy": true, "worst": true, "gifts": true, "lists": true, "stops": true, "rapid": true, "brick": true, "claws": true, "beads": true, "beast": true, "skirt": true, "cakes": true, "lions": true, "frogs": true, "tries": true, "nerve": true, "grand": true, "armed": true, "treat": true, "honey": true, "moist": true, "legal": true, "penny": true, "crown": true, "shock": true, "taxes": true, "sixty": true, "altar": true, "pulls": true, "sport": true, "drums": true, "talks": true, "dying": true, "dates": true, "drank": true, "blows": true, "lever": true, "wages": true, "proof": true, "drugs": true, "tanks": true, "sings": true, "tails": true, "pause": true, "herds": true, "arose": true, "hated": true, "clues": true, "novel": true, "shame": true, "burnt": true, "races": true, "flash": true, "weary": true, "heels": true, "token": true, "coats": true, "spare": true, "shiny": true, "alarm": true, "dimes": true, "sixth": true, "clerk": true, "mercy": true, "sunny": true, "guest": true, "float": true, "shone": true, "pipes": true, "worms": true, "bills": true, "sweat": true, "suits": true, "smart": true, "upset": true, "rains": true, "sandy": true, "rainy": true, "parks": true, "sadly": true, "fancy": true, "rider": true, "unity": true, "bunch": true, "rolls": true, "crash": true, "craft": true, "newly": true, "gates": true, "hatch": true, "paths": true, "funds": true, "wider": true, "grace": true, "grave": true, "tides": true, "admit": true, "shift": true, "sails": true, "pupil": true, "tiger": true, "angel": true, "cruel": true, "agent": true, "drama": true, "urged": true, "patch": true, "nests": true, "vital": true, "sword": true, "blame": true, "weeds": true, "screw": true, "vocal": true, "bacon": true, "chalk": true, "cargo": true, "crazy": true, "acted": true, "goats": true, "arise": true, "witch": true, "loves": true, "queer": true, "dwell": true, "backs": true, "ropes": true, "shots": true, "merry": true, "phone": true, "cheek": true, "peaks": true, "ideal": true, "beard": true, "eagle": true, "creek": true, "cries": true, "ashes": true, "stall": true, "yield": true, "mayor": true, "opens": true, "input": true, "fleet": true, "tooth": true, "cubic": true, "wives": true, "burns": true, "poets": true, "apron": true, "spear": true, "organ": true, "cliff": true, "stamp": true, "paste": true, "rural": true, "baked": true, "chase": true, "slice": true, "slant": true, "knock": true, "noisy": true, "sorts": true, "stays": true, "wiped": true, "blown": true, "piled": true, "clubs": true, "cheer": true, "widow": true, "twist": true, "tenth": true, "hides": true, "comma": true, "sweep": true, "spoon": true, "stern": true, "crept": true, "maple": true, "deeds": true, "rides": true, "muddy": true, "crime": true, "jelly": true, "ridge": true, "drift": true, "dusty": true, "devil": true, "tempo": true, "humor": true, "sends": true, "steal": true, "tents": true, "waist": true, "roses": true, "reign": true, "noble": true, "cheap": true, "dense": true, "linen": true, "geese": true, "woven": true, "posts": true, "hired": true, "wrath": true, "salad": true, "bowed": true, "tires": true, "shark": true, "belts": true, "grasp": true, "blast": true, "polar": true, "fungi": true, "tends": true, "pearl": true, "loads": true, "jokes": true, "veins": true, "frost": true, "hears": true, "loses": true, "hosts": true, "diver": true, "phase": true, "toads": true, "alert": true, "tasks": true, "seams": true, "coral": true, "focus": true, "naked": true, "puppy": true, "jumps": true, "spoil": true, "quart": true, "macro": true, "fears": true, "flung": true, "spark": true, "vivid": true, "brook": true, "steer": true, "spray": true, "decay": true, "ports": true, "socks": true, "urban": true, "goals": true, "grant": true, "minus": true, "films": true, "tunes": true, "shaft": true, "firms": true, "skies": true, "bride": true, "wreck": true, "flock": true, "stare": true, "hobby": true, "bonds": true, "dared": true, "faded": true, "thief": true, "crude": true, "pants": true, "flute": true, "votes": true, "tonal": true, "radar": true, "wells": true, "skull": true, "hairs": true, "argue": true, "wears": true, "dolls": true, "voted": true, "caves": true, "cared": true, "broom": true, "scent": true, "panel": true, "fairy": true, "olive": true, "bends": true, "prism": true, "lamps": true, "cable": true, "peach": true, "ruins": true, "rally": true, "schwa": true, "lambs": true, "sells": true, "cools": true, "draft": true, "charm": true, "limbs": true, "brake": true, "gazed": true, "cubes": true, "delay": true, "beams": true, "fetch": true, "ranks": true, "array": true, "harsh": true, "camel": true, "vines": true, "picks": true, "naval": true, "purse": true, "rigid": true, "crawl": true, "toast": true, "soils": true, "sauce": true, "basin": true, "ponds": true, "twins": true, "wrist": true, "fluid": true, "pools": true, "brand": true, "stalk": true, "robot": true, "reeds": true, "hoofs": true, "buses": true, "sheer": true, "grief": true, "bloom": true, "dwelt": true, "melts": true, "risen": true, "flags": true, "knelt": true, "fiber": true, "roofs": true, "freed": true, "armor": true, "piles": true, "aimed": true, "algae": true, "twigs": true, "lemon": true, "ditch": true, "drunk": true, "rests": true, "chill": true, "slain": true, "panic": true, "cords": true, "tuned": true, "crisp": true, "ledge": true, "dived": true, "swamp": true, "clung": true, "stole": true, "molds": true, "yarns": true, "liver": true, "gauge": true, "breed": true, "stool": true, "gulls": true, "awoke": true, "gross": true, "diary": true, "rails": true, "belly": true, "trend": true, "flask": true, "stake": true, "fried": true, "draws": true, "actor": true, "handy": true, "bowls": true, "haste": true, "scope": true, "deals": true, "knots": true, "moons": true, "essay": true, "thump": true, "hangs": true, "bliss": true, "dealt": true, "gains": true, "bombs": true, "clown": true, "palms": true, "cones": true, "roast": true, "tidal": true, "bored": true, "chant": true, "acids": true, "dough": true, "camps": true, "swore": true, "lover": true, "hooks": true, "males": true, "cocoa": true, "punch": true, "award": true, "reins": true, "ninth": true, "noses": true, "links": true, "drain": true, "fills": true, "nylon": true, "lunar": true, "pulse": true, "flown": true, "elbow": true, "fatal": true, "sites": true, "moths": true, "meats": true, "foxes": true, "mined": true, "attic": true, "fiery": true, "mount": true, "usage": true, "swear": true, "snowy": true, "rusty": true, "scare": true, "traps": true, "relax": true, "react": true, "valid": true, "robin": true, "cease": true, "gills": true, "prior": true, "safer": true, "polio": true, "loyal": true, "swell": true, "salty": true, "marsh": true, "vague": true, "weave": true, "mound": true, "seals": true, "mules": true, "virus": true, "scout": true, "acute": true, "windy": true, "stout": true, "folds": true, "seize": true, "hilly": true, "joins": true, "pluck": true, "stack": true, "lords": true, "dunes": true, "burro": true, "hawks": true, "trout": true, "feeds": true, "scarf": true, "halls": true, "coals": true, "towel": true, "souls": true, "elect": true, "buggy": true, "pumps": true, "loans": true, "spins": true, "files": true, "oxide": true, "pains": true, "photo": true, "rival": true, "flats": true, "syrup": true, "rodeo": true, "sands": true, "moose": true, "pints": true, "curly": true, "comic": true, "cloak": true, "onion": true, "clams": true, "scrap": true, "didst": true, "couch": true, "codes": true, "fails": true, "ounce": true, "lodge": true, "greet": true, "gypsy": true, "utter": true, "paved": true, "zones": true, "fours": true, "alley": true, "tiles": true, "bless": true, "crest": true, "elder": true, "kills": true, "yeast": true, "erect": true, "bugle": true, "medal": true, "roles": true, "hound": true, "snail": true, "alter": true, "ankle": true, "relay": true, "loops": true, "zeros": true, "bites": true, "modes": true, "debts": true, "realm": true, "glove": true, "rayon": true, "swims": true, "poked": true, "stray": true, "lifts": true, "maker": true, "lumps": true, "graze": true, "dread": true, "barns": true, "docks": true, "masts": true, "pours": true, "wharf": true, "curse": true, "plump": true, "robes": true, "seeks": true, "cedar": true, "curls": true, "jolly": true, "myths": true, "cages": true, "gloom": true, "locks": true, "pedal": true, "beets": true, "crows": true, "anode": true, "slash": true, "creep": true, "rowed": true, "chips": true, "fists": true, "wines": true, "cares": true, "valve": true, "newer": true, "motel": true, "ivory": true, "necks": true, "clamp": true, "barge": true, "blues": true, "alien": true, "frown": true, "strap": true, "crews": true, "shack": true, "gonna": true, "saves": true, "stump": true, "ferry": true, "idols": true, "cooks": true, "juicy": true, "glare": true, "carts": true, "alloy": true, "bulbs": true, "lawns": true, "lasts": true, "fuels": true, "oddly": true, "crane": true, "filed": true, "weird": true, "shawl": true, "slips": true, "troop": true, "bolts": true, "suite": true, "sleek": true, "quilt": true, "tramp": true, "blaze": true, "atlas": true, "odors": true, "scrub": true, "crabs": true, "probe": true, "logic": true, "adobe": true, "exile": true, "rebel": true, "grind": true, "sting": true, "spine": true, "cling": true, "desks": true, "grove": true, "leaps": true, "prose": true, "lofty": true, "agony": true, "snare": true, "tusks": true, "bulls": true, "moods": true, "humid": true, "finer": true, "dimly": true, "plank": true, "china": true, "pines": true, "guilt": true, "sacks": true, "brace": true, "quote": true, "lathe": true, "gaily": true, "fonts": true, "scalp": true, "adopt": true, "foggy": true, "ferns": true, "grams": true, "clump": true, "perch": true, "tumor": true, "teens": true, "crank": true, "fable": true, "hedge": true, "genes": true, "sober": true, "boast": true, "tract": true, "cigar": true, "unite": true, "owing": true, "thigh": true, "haiku": true, "swish": true, "dikes": true, "wedge": true, "booth": true, "eased": true, "frail": true, "cough": true, "tombs": true, "darts": true, "forts": true, "choir": true, "pouch": true, "pinch": true, "hairy": true, "buyer": true, "torch": true, "vigor": true, "waltz": true, "heats": true, "herbs": true, "users": true, "flint": true, "click": true, "madam": true, "bleak": true, "blunt": true, "aided": true, "lacks": true, "masks": true, "waded": true, "risks": true, "nurse": true, "chaos": true, "sewed": true, "cured": true, "ample": true, "lease": true, "steak": true, "sinks": true, "merit": true, "bluff": true, "bathe": true, "gleam": true, "bonus": true, "colts": true, "shear": true, "gland": true, "silky": true, "skate": true, "birch": true, "anvil": true, "sleds": true, "groan": true, "maids": true, "meets": true, "speck": true, "hymns": true, "hints": true, "drown": true, "bosom": true, "slick": true, "quest": true, "coils": true, "spied": true, "snows": true, "stead": true, "snack": true, "plows": true, "blond": true, "tamed": true, "thorn": true, "waits": true, "glued": true, "banjo": true, "tease": true, "arena": true, "bulky": true, "carve": true, "stunt": true, "warms": true, "shady": true, "razor": true, "folly": true, "leafy": true, "notch": true, "fools": true, "otter": true, "pears": true, "flush": true, "genus": true, "ached": true, "fives": true, "flaps": true, "spout": true, "smote": true, "fumes": true, "adapt": true, "cuffs": true, "tasty": true, "stoop": true, "clips": true, "disks": true, "sniff": true, "lanes": true, "brisk": true, "imply": true, "demon": true, "super": true, "furry": true, "raged": true, "growl": true, "texts": true, "hardy": true, "stung": true, "typed": true, "hates": true, "wiser": true, "timid": true, "serum": true, "beaks": true, "rotor": true, "casts": true, "baths": true, "glide": true, "plots": true, "trait": true, "resin": true, "slums": true, "lyric": true, "puffs": true, "decks": true, "brood": true, "mourn": true, "aloft": true, "abuse": true, "whirl": true, "edged": true, "ovary": true, "quack": true, "heaps": true, "slang": true, "await": true, "civic": true, "saint": true, "bevel": true, "sonar": true, "aunts": true, "packs": true, "froze": true, "tonic": true, "corps": true, "swarm": true, "frank": true, "repay": true, "gaunt": true, "wired": true, "niece": true, "cello": true, "needy": true, "chuck": true, "stony": true, "media": true, "surge": true, "hurts": true, "repel": true, "husky": true, "dated": true, "hunts": true, "mists": true, "exert": true, "dries": true, "mates": true, "sworn": true, "baker": true, "spice": true, "oasis": true, "boils": true, "spurs": true, "doves": true, "sneak": true, "paces": true, "colon": true, "siege": true, "strum": true, "drier": true, "cacao": true, "humus": true, "bales": true, "piped": true, "nasty": true, "rinse": true, "boxer": true, "shrub": true, "amuse": true, "tacks": true, "cited": true, "slung": true, "delta": true, "laden": true, "larva": true, "rents": true, "yells": true, "spool": true, "spill": true, "crush": true, "jewel": true, "snaps": true, "stain": true, "kicks": true, "tying": true, "slits": true, "rated": true, "eerie": true, "smash": true, "plums": true, "zebra": true, "earns": true, "bushy": true, "scary": true, "squad": true, "tutor": true, "silks": true, "slabs": true, "bumps": true, "evils": true, "fangs": true, "snout": true, "peril": true, "pivot": true, "yacht": true, "lobby": true, "jeans": true, "grins": true, "viola": true, "liner": true, "comet": true, "scars": true, "chops": true, "raids": true, "eater": true, "slate": true, "skips": true, "soles": true, "misty": true, "urine": true, "knobs": true, "sleet": true, "holly": true, "pests": true, "forks": true, "grill": true, "trays": true, "pails": true, "borne": true, "tenor": true, "wares": true, "carol": true, "woody": true, "canon": true, "wakes": true, "kitty": true, "miner": true, "polls": true, "shaky": true, "nasal": true, "scorn": true, "chess": true, "taxis": true, "crate": true, "shyly": true, "tulip": true, "forge": true, "nymph": true, "budge": true, "lowly": true, "abide": true, "depot": true, "oases": true, "asses": true, "sheds": true, "fudge": true, "pills": true, "rivet": true, "thine": true, "groom": true, "lanky": true, "boost": true, "broth": true, "heave": true, "gravy": true, "beech": true, "timed": true, "quail": true, "inert": true, "gears": true, "chick": true, "hinge": true, "trash": true, "clash": true, "sighs": true, "renew": true, "bough": true, "dwarf": true, "slows": true, "quill": true, "shave": true, "spore": true, "sixes": true, "chunk": true, "madly": true, "paced": true, "braid": true, "fuzzy": true, "motto": true, "spies": true, "slack": true, "mucus": true, "magma": true, "awful": true, "discs": true, "erase": true, "posed": true, "asset": true, "cider": true, "taper": true, "theft": true, "churn": true, "satin": true, "slots": true, "taxed": true, "bully": true, "sloth": true, "shale": true, "tread": true, "raked": true, "curds": true, "manor": true, "aisle": true, "bulge": true, "loins": true, "stair": true, "tapes": true, "leans": true, "bunks": true, "squat": true, "towed": true, "lance": true, "panes": true, "sakes": true, "heirs": true, "caste": true, "dummy": true, "pores": true, "fauna": true, "crook": true, "poise": true, "epoch": true, "risky": true, "warns": true, "fling": true, "berry": true, "grape": true, "flank": true, "drags": true, "squid": true, "pelts": true, "icing": true, "irony": true, "irons": true, "barks": true, "whoop": true, "choke": true, "diets": true, "whips": true, "tally": true, "dozed": true, "twine": true, "kites": true, "bikes": true, "ticks": true, "riots": true, "roars": true, "vault": true, "looms": true, "scold": true, "blink": true, "dandy": true, "pupae": true, "sieve": true, "spike": true, "ducts": true, "lends": true, "pizza": true, "brink": true, "widen": true, "plumb": true, "pagan": true, "feats": true, "bison": true, "soggy": true, "scoop": true, "argon": true, "nudge": true, "skiff": true, "amber": true, "sexes": true, "rouse": true, "salts": true, "hitch": true, "exalt": true, "leash": true, "dined": true, "chute": true, "snort": true, "gusts": true, "melon": true, "cheat": true, "reefs": true, "llama": true, "lasso": true, "debut": true, "quota": true, "oaths": true, "prone": true, "mixes": true, "rafts": true, "dives": true, "stale": true, "inlet": true, "flick": true, "pinto": true, "brows": true, "untie": true, "batch": true, "greed": true, "chore": true, "stirs": true, "blush": true, "onset": true, "barbs": true, "volts": true, "beige": true, "swoop": true, "paddy": true, "laced": true, "shove": true, "jerky": true, "poppy": true, "leaks": true, "fares": true, "dodge": true, "godly": true, "squaw": true, "affix": true, "brute": true, "nicer": true, "undue": true, "snarl": true, "merge": true, "doses": true, "showy": true, "daddy": true, "roost": true, "vases": true, "swirl": true, "petty": true, "colds": true, "curry": true, "cobra": true, "genie": true, "flare": true, "messy": true, "cores": true, "soaks": true, "ripen": true, "whine": true, "amino": true, "plaid": true, "spiny": true, "mowed": true, "baton": true, "peers": true, "vowed": true, "pious": true, "swans": true, "exits": true, "afoot": true, "plugs": true, "idiom": true, "chili": true, "rites": true, "serfs": true, "cleft": true, "berth": true, "grubs": true, "annex": true, "dizzy": true, "hasty": true, "latch": true, "wasps": true, "mirth": true, "baron": true, "plead": true, "aloof": true, "aging": true, "pixel": true, "bared": true, "mummy": true, "hotly": true, "auger": true, "buddy": true, "chaps": true, "badge": true, "stark": true, "fairs": true, "gully": true, "mumps": true, "emery": true, "filly": true, "ovens": true, "drone": true, "gauze": true, "idiot": true, "fussy": true, "annoy": true, "shank": true, "gouge": true, "bleed": true, "elves": true, "roped": true, "unfit": true, "baggy": true, "mower": true, "scant": true, "grabs": true, "fleas": true, "lousy": true, "album": true, "sawed": true, "cooky": true, "murky": true, "infer": true, "burly": true, "waged": true, "dingy": true, "brine": true, "kneel": true, "creak": true, "vanes": true, "smoky": true, "spurt": true, "combs": true, "easel": true, "laces": true, "humps": true, "rumor": true, "aroma": true, "horde": true, "swiss": true, "leapt": true, "opium": true, "slime": true, "afire": true, "pansy": true, "mares": true, "soaps": true, "husks": true, "snips": true, "hazel": true, "lined": true, "cafes": true, "naive": true, "wraps": true, "sized": true, "piers": true, "beset": true, "agile": true, "tongs": true, "steed": true, "fraud": true, "booty": true, "valor": true, "downy": true, "witty": true, "mossy": true, "psalm": true, "scuba": true, "tours": true, "polka": true, "milky": true, "gaudy": true, "shrug": true, "tufts": true, "wilds": true, "laser": true, "truss": true, "hares": true, "creed": true, "lilac": true, "siren": true, "tarry": true, "bribe": true, "swine": true, "muted": true, "flips": true, "cures": true, "sinew": true, "boxed": true, "hoops": true, "gasps": true, "hoods": true, "niche": true, "yucca": true, "glows": true, "sewer": true, "whack": true, "fuses": true, "gowns": true, "droop": true, "bucks": true, "pangs": true, "mails": true, "whisk": true, "haven": true, "clasp": true, "sling": true, "stint": true, "urges": true, "champ": true, "piety": true, "chirp": true, "pleat": true, "posse": true, "sunup": true, "menus": true, "howls": true, "quake": true, "knack": true, "plaza": true, "fiend": true, "caked": true, "bangs": true, "erupt": true, "poker": true, "olden": true, "cramp": true, "voter": true, "poses": true, "manly": true, "slump": true, "fined": true, "grips": true, "gaped": true, "purge": true, "hiked": true, "maize": true, "fluff": true, "strut": true, "sloop": true, "prowl": true, "roach": true, "cocks": true, "bland": true, "dials": true, "plume": true, "slaps": true, "soups": true, "dully": true, "wills": true, "foams": true, "solos": true, "skier": true, "eaves": true, "totem": true, "fused": true, "latex": true, "veils": true, "mused": true, "mains": true, "myrrh": true, "racks": true, "galls": true, "gnats": true, "bouts": true, "sisal": true, "shuts": true, "hoses": true, "dryly": true, "hover": true, "gloss": true, "seeps": true, "denim": true, "putty": true, "guppy": true, "leaky": true, "dusky": true, "filth": true, "oboes": true, "spans": true, "fowls": true, "adorn": true, "glaze": true, "haunt": true, "dares": true, "obeys": true, "bakes": true, "abyss": true, "smelt": true, "gangs": true, "aches": true, "trawl": true, "claps": true, "undid": true, "spicy": true, "hoist": true, "fades": true, "vicar": true, "acorn": true, "pussy": true, "gruff": true, "musty": true, "tarts": true, "snuff": true, "hunch": true, "truce": true, "tweed": true, "dryer": true, "loser": true, "sheaf": true, "moles": true, "lapse": true, "tawny": true, "vexed": true, "autos": true, "wager": true, "domes": true, "sheen": true, "clang": true, "spade": true, "sowed": true, "broil": true, "slyly": true, "studs": true, "grunt": true, "donor": true, "slugs": true, "aspen": true, "homer": true, "croak": true, "tithe": true, "halts": true, "avert": true, "havoc": true, "hogan": true, "glint": true, "ruddy": true, "jeeps": true, "flaky": true, "ladle": true, "taunt": true, "snore": true, "fines": true, "props": true, "prune": true, "pesos": true, "radii": true, "pokes": true, "tiled": true, "daisy": true, "heron": true, "villa": true, "farce": true, "binds": true, "cites": true, "fixes": true, "jerks": true, "livid": true, "waked": true, "inked": true, "booms": true, "chews": true, "licks": true, "hyena": true, "scoff": true, "lusty": true, "sonic": true, "smith": true, "usher": true, "tucks": true, "vigil": true, "molts": true, "sects": true, "spars": true, "dumps": true, "scaly": true, "wisps": true, "sores": true, "mince": true, "panda": true, "flier": true, "axles": true, "plied": true, "booby": true, "patio": true, "rabbi": true, "petal": true, "polyp": true, "tints": true, "grate": true, "troll": true, "tolls": true, "relic": true, "phony": true, "bleat": true, "flaws": true, "flake": true, "snags": true, "aptly": true, "drawl": true, "ulcer": true, "soapy": true, "bossy": true, "monks": true, "crags": true, "caged": true, "twang": true, "diner": true, "taped": true, "cadet": true, "grids": true, "spawn": true, "guile": true, "noose": true, "mores": true, "girth": true, "slimy": true, "aides": true, "spasm": true, "burrs": true, "alibi": true, "lymph": true, "saucy": true, "muggy": true, "liter": true, "joked": true, "goofy": true, "exams": true, "enact": true, "stork": true, "lured": true, "toxic": true, "omens": true, "nears": true, "covet": true, "wrung": true, "forum": true, "venom": true, "moody": true, "alder": true, "sassy": true, "flair": true, "guild": true, "prays": true, "wrens": true, "hauls": true, "stave": true, "tilts": true, "pecks": true, "stomp": true, "gales": true, "tempt": true, "capes": true, "mesas": true, "omits": true, "tepee": true, "harry": true, "wring": true, "evoke": true, "limes": true, "cluck": true, "lunge": true, "highs": true, "canes": true, "giddy": true, "lithe": true, "verge": true, "khaki": true, "queue": true, "loath": true, "foyer": true, "outdo": true, "fared": true, "deter": true, "crumb": true, "astir": true, "spire": true, "jumpy": true, "extol": true, "buoys": true, "stubs": true, "lucid": true, "thong": true, "afore": true, "whiff": true, "maxim": true, "hulls": true, "clogs": true, "slats": true, "jiffy": true, "arbor": true, "cinch": true, "igloo": true, "goody": true, "gazes": true, "dowel": true, "calms": true, "bitch": true, "scowl": true, "gulps": true, "coded": true, "waver": true, "mason": true, "lobes": true, "ebony": true, "flail": true, "isles": true, "clods": true, "dazed": true, "adept": true, "oozed": true, "sedan": true, "clays": true, "warts": true, "ketch": true, "skunk": true, "manes": true, "adore": true, "sneer": true, "mango": true, "fiord": true, "flora": true, "roomy": true, "minks": true, "thaws": true, "watts": true, "freer": true, "exult": true, "plush": true, "paled": true, "twain": true, "clink": true, "scamp": true, "pawed": true, "grope": true, "bravo": true, "gable": true, "stink": true, "sever": true, "waned": true, "rarer": true, "regal": true, "wards": true, "fawns": true, "babes": true, "unify": true, "amend": true, "oaken": true, "glade": true, "visor": true, "hefty": true, "nines": true, "throb": true, "pecan": true, "butts": true, "pence": true, "sills": true, "jails": true, "flyer": true, "saber": true, "nomad": true, "miter": true, "beeps": true, "domed": true, "gulfs": true, "curbs": true, "heath": true, "moors": true, "aorta": true, "larks": true, "tangy": true, "wryly": true, "cheep": true, "rages": true, "evade": true, "lures": true, "freak": true, "vogue": true, "tunic": true, "slams": true, "knits": true, "dumpy": true, "mania": true, "spits": true, "firth": true, "hikes": true, "trots": true, "nosed": true, "clank": true, "dogma": true, "bloat": true, "balsa": true, "graft": true, "middy": true, "stile": true, "keyed": true, "finch": true, "sperm": true, "chaff": true, "wiles": true, "amigo": true, "copra": true, "amiss": true, "eying": true, "twirl": true, "lurch": true, "popes": true, "chins": true, "smock": true, "tines": true, "guise": true, "grits": true, "junks": true, "shoal": true, "cache": true, "tapir": true, "atoll": true, "deity": true, "toils": true, "spree": true, "mocks": true, "scans": true, "shorn": true, "revel": true, "raven": true, "hoary": true, "reels": true, "scuff": true, "mimic": true, "weedy": true, "corny": true, "truer": true, "rouge": true, "ember": true, "floes": true, "torso": true, "wipes": true, "edict": true, "sulky": true, "recur": true, "groin": true, "baste": true, "kinks": true, "surer": true, "piggy": true, "moldy": true, "franc": true, "liars": true, "inept": true, "gusty": true, "facet": true, "jetty": true, "equip": true, "leper": true, "slink": true, "soars": true, "cater": true, "dowry": true, "sided": true, "yearn": true, "decoy": true, "taboo": true, "ovals": true, "heals": true, "pleas": true, "beret": true, "spilt": true, "gayly": true, "rover": true, "endow": true, "pygmy": true, "carat": true, "abbey": true, "vents": true, "waken": true, "chimp": true, "fumed": true, "sodas": true, "vinyl": true, "clout": true, "wades": true, "mites": true, "smirk": true, "bores": true, "bunny": true, "surly": true, "frock": true, "foray": true, "purer": true, "milks": true, "query": true, "mired": true, "blare": true, "froth": true, "gruel": true, "navel": true, "paler": true, "puffy": true, "casks": true, "grime": true, "derby": true, "mamma": true, "gavel": true, "teddy": true, "vomit": true, "moans": true, "allot": true, "defer": true, "wield": true, "viper": true, "louse": true, "erred": true, "hewed": true, "abhor": true, "wrest": true, "waxen": true, "adage": true, "ardor": true, "stabs": true, "pored": true, "rondo": true, "loped": true, "fishy": true, "bible": true, "hires": true, "foals": true, "feuds": true, "jambs": true, "thuds": true, "jeers": true, "knead": true, "quirk": true, "rugby": true, "expel": true, "greys": true, "rigor": true, "ester": true, "lyres": true, "aback": true, "glues": true, "lotus": true, "lurid": true, "rungs": true, "hutch": true, "thyme": true, "valet": true, "tommy": true, "yokes": true, "epics": true, "trill": true, "pikes": true, "ozone": true, "caper": true, "chime": true, "frees": true, "famed": true, "leech": true, "smite": true, "neigh": true, "erode": true, "robed": true, "hoard": true, "salve": true, "conic": true, "gawky": true, "craze": true, "jacks": true, "gloat": true, "mushy": true, "rumps": true, "fetus": true, "wince": true, "pinks": true, "shalt": true, "toots": true, "glens": true, "cooed": true, "rusts": true, "stews": true, "shred": true, "parka": true, "chugs": true, "winks": true, "clots": true, "shrew": true, "booed": true, "filmy": true, "juror": true, "dents": true, "gummy": true, "grays": true, "hooky": true, "butte": true, "dogie": true, "poled": true, "reams": true, "fifes": true, "spank": true, "gayer": true, "tepid": true, "spook": true, "taint": true, "flirt": true, "rogue": true, "spiky": true, "opals": true, "miser": true, "cocky": true, "coyly": true, "balmy": true, "slosh": true, "brawl": true, "aphid": true, "faked": true, "hydra": true, "brags": true, "chide": true, "yanks": true, "allay": true, "video": true, "altos": true, "eases": true, "meted": true, "chasm": true, "longs": true, "excel": true, "taffy": true, "impel": true, "savor": true, "koala": true, "quays": true, "dawns": true, "proxy": true, "clove": true, "duets": true, "dregs": true, "tardy": true, "briar": true, "grimy": true, "ultra": true, "meaty": true, "halve": true, "wails": true, "suede": true, "mauve": true, "envoy": true, "arson": true, "coves": true, "gooey": true, "brews": true, "sofas": true, "chums": true, "amaze": true, "zooms": true, "abbot": true, "halos": true, "scour": true, "suing": true, "cribs": true, "sagas": true, "enema": true, "wordy": true, "harps": true, "coupe": true, "molar": true, "flops": true, "weeps": true, "mints": true, "ashen": true, "felts": true, "askew": true, "munch": true, "mewed": true, "divan": true, "vices": true, "jumbo": true, "blobs": true, "blots": true, "spunk": true, "acrid": true, "topaz": true, "cubed": true, "clans": true, "flees": true, "slurs": true, "gnaws": true, "welds": true, "fords": true, "emits": true, "agate": true, "pumas": true, "mends": true, "darks": true, "dukes": true, "plies": true, "canny": true, "hoots": true, "oozes": true, "lamed": true, "fouls": true, "clefs": true, "nicks": true, "mated": true, "skims": true, "brunt": true, "tuber": true, "tinge": true, "fates": true, "ditty": true, "thins": true, "frets": true, "eider": true, "bayou": true, "mulch": true, "fasts": true, "amass": true, "damps": true, "morns": true, "friar": true, "palsy": true, "vista": true, "croon": true, "conch": true, "udder": true, "tacos": true, "skits": true, "mikes": true, "quits": true, "preen": true, "aster": true, "adder": true, "elegy": true, "pulpy": true, "scows": true, "baled": true, "hovel": true, "lavas": true, "crave": true, "optic": true, "welts": true, "busts": true, "knave": true, "razed": true, "shins": true, "totes": true, "scoot": true, "dears": true, "crock": true, "mutes": true, "trims": true, "skein": true, "doted": true, "shuns": true, "veers": true, "fakes": true, "yoked": true, "wooed": true, "hacks": true, "sprig": true, "wands": true, "lulls": true, "seers": true, "snobs": true, "nooks": true, "pined": true, "perky": true, "mooed": true, "frill": true, "dines": true, "booze": true, "tripe": true, "prong": true, "drips": true, "odder": true, "levee": true, "antic": true, "sidle": true, "pithy": true, "corks": true, "yelps": true, "joker": true, "fleck": true, "buffs": true, "scram": true, "tiers": true, "bogey": true, "doled": true, "irate": true, "vales": true, "coped": true, "hails": true, "elude": true, "bulks": true, "aired": true, "vying": true, "stags": true, "strew": true, "cocci": true, "pacts": true, "scabs": true, "silos": true, "dusts": true, "yodel": true, "terse": true, "jaded": true, "baser": true, "jibes": true, "foils": true, "sways": true, "forgo": true, "slays": true, "preys": true, "treks": true, "quell": true, "peeks": true, "assay": true, "lurks": true, "eject": true, "boars": true, "trite": true, "belch": true, "gnash": true, "wanes": true, "lutes": true, "whims": true, "dosed": true, "chewy": true, "snipe": true, "umbra": true, "teems": true, "dozes": true, "kelps": true, "upped": true, "brawn": true, "doped": true, "shush": true, "rinds": true, "slush": true, "moron": true, "voile": true, "woken": true, "fjord": true, "sheik": true, "jests": true, "kayak": true, "slews": true, "toted": true, "saner": true, "drape": true, "patty": true, "raves": true, "sulfa": true, "grist": true, "skied": true, "vixen": true, "civet": true, "vouch": true, "tiara": true, "homey": true, "moped": true, "runts": true, "serge": true, "kinky": true, "rills": true, "corns": true, "brats": true, "pries": true, "amble": true, "fries": true, "loons": true, "tsars": true, "datum": true, "musky": true, "pigmy": true, "gnome": true, "ravel": true, "ovule": true, "icily": true, "liken": true, "lemur": true, "frays": true, "silts": true, "sifts": true, "plods": true, "ramps": true, "tress": true, "earls": true, "dudes": true, "waive": true, "karat": true, "jolts": true, "peons": true, "beers": true, "horny": true, "pales": true, "wreak": true, "lairs": true, "lynch": true, "stank": true, "swoon": true, "idler": true, "abort": true, "blitz": true, "ensue": true, "atone": true, "bingo": true, "roves": true, "kilts": true, "scald": true, "adios": true, "cynic": true, "dulls": true, "memos": true, "elfin": true, "dales": true, "peels": true, "peals": true, "bares": true, "sinus": true, "crone": true, "sable": true, "hinds": true, "shirk": true, "enrol": true, "wilts": true, "roams": true, "duped": true, "cysts": true, "mitts": true, "safes": true, "spats": true, "coops": true, "filet": true, "knell": true, "refit": true, "covey": true, "punks": true, "kilns": true, "fitly": true, "abate": true, "talcs": true, "heeds": true, "duels": true, "wanly": true, "ruffs": true, "gauss": true, "lapel": true, "jaunt": true, "whelp": true, "cleat": true, "gauzy": true, "dirge": true, "edits": true, "wormy": true, "moats": true, "smear": true, "prods": true, "bowel": true, "frisk": true, "vests": true, "bayed": true, "rasps": true, "tames": true, "delve": true, "embed": true, "befit": true, "wafer": true, "ceded": true, "novas": true, "feign": true, "spews": true, "larch": true, "huffs": true, "doles": true, "mamas": true, "hulks": true, "pried": true, "brims": true, "irked": true, "aspic": true, "swipe": true, "mealy": true, "skimp": true, "bluer": true, "slake": true, "dowdy": true, "penis": true, "brays": true, "pupas": true, "egret": true, "flunk": true, "phlox": true, "gripe": true, "peony": true, "douse": true, "blurs": true, "darns": true, "slunk": true, "lefts": true, "chats": true, "inane": true, "vials": true, "stilt": true, "rinks": true, "woofs": true, "wowed": true, "bongs": true, "frond": true, "ingot": true, "evict": true, "singe": true, "shyer": true, "flied": true, "slops": true, "dolts": true, "drool": true, "dells": true, "whelk": true, "hippy": true, "feted": true, "ether": true, "cocos": true, "hives": true, "jibed": true, "mazes": true, "trios": true, "sirup": true, "squab": true, "laths": true, "leers": true, "pasta": true, "rifts": true, "lopes": true, "alias": true, "whirs": true, "diced": true, "slags": true, "lodes": true, "foxed": true, "idled": true, "prows": true, "plait": true, "malts": true, "chafe": true, "cower": true, "toyed": true, "chefs": true, "keels": true, "sties": true, "racer": true, "etude": true, "sucks": true, "sulks": true, "micas": true, "czars": true, "copse": true, "ailed": true, "abler": true, "rabid": true, "golds": true, "croup": true, "snaky": true, "visas": true, "palls": true, "mopes": true, "boned": true, "wispy": true, "raved": true, "swaps": true, "junky": true, "doily": true, "pawns": true, "tamer": true, "poach": true, "baits": true, "damns": true, "gumbo": true, "daunt": true, "prank": true, "hunks": true, "buxom": true, "heres": true, "honks": true, "stows": true, "unbar": true, "idles": true, "routs": true, "sages": true, "goads": true, "remit": true, "copes": true, "deign": true, "culls": true, "girds": true, "haves": true, "lucks": true, "stunk": true, "dodos": true, "shams": true, "snubs": true, "icons": true, "usurp": true, "dooms": true, "hells": true, "soled": true, "comas": true, "paves": true, "maths": true, "perks": true, "limps": true, "wombs": true, "blurb": true, "daubs": true, "cokes": true, "sours": true, "stuns": true, "cased": true, "musts": true, "coeds": true, "cowed": true, "aping": true, "zoned": true, "rummy": true, "fetes": true, "skulk": true, "quaff": true, "rajah": true, "deans": true, "reaps": true, "galas": true, "tills": true, "roved": true, "kudos": true, "toned": true, "pared": true, "scull": true, "vexes": true, "punts": true, "snoop": true, "bails": true, "dames": true, "hazes": true, "lores": true, "marts": true, "voids": true, "ameba": true, "rakes": true, "adzes": true, "harms": true, "rears": true, "satyr": true, "swill": true, "hexes": true, "colic": true, "leeks": true, "hurls": true, "yowls": true, "ivies": true, "plops": true, "musks": true, "papaw": true, "jells": true, "bused": true, "cruet": true, "bided": true, "filch": true, "zests": true, "rooks": true, "laxly": true, "rends": true, "loams": true, "basks": true, "sires": true, "carps": true, "pokey": true, "flits": true, "muses": true, "bawls": true, "shuck": true, "viler": true, "lisps": true, "peeps": true, "sorer": true, "lolls": true, "prude": true, "diked": true, "floss": true, "flogs": true, "scums": true, "dopes": true, "bogie": true, "pinky": true, "leafs": true, "tubas": true, "scads": true, "lowed": true, "yeses": true, "biked": true, "qualm": true, "evens": true, "caned": true, "gawks": true, "whits": true, "wooly": true, "gluts": true, "romps": true, "bests": true, "dunce": true, "crony": true, "joist": true, "tunas": true, "boner": true, "malls": true, "parch": true, "avers": true, "crams": true, "pares": true, "dally": true, "bigot": true, "kales": true, "flays": true, "leach": true, "gushy": true, "pooch": true, "huger": true, "slyer": true, "golfs": true, "mires": true, "flues": true, "loafs": true, "arced": true, "acnes": true, "neons": true, "fiefs": true, "dints": true, "dazes": true, "pouts": true, "cored": true, "yules": true, "lilts": true, "beefs": true, "mutts": true, "fells": true, "cowls": true, "spuds": true, "lames": true, "jawed": true, "dupes": true, "deads": true, "bylaw": true, "noons": true, "nifty": true, "clued": true, "vireo": true, "gapes": true, "metes": true, "cuter": true, "maims": true, "droll": true, "cupid": true, "mauls": true, "sedge": true, "papas": true, "wheys": true, "eking": true, "loots": true, "hilts": true, "meows": true, "beaus": true, "dices": true, "peppy": true, "riper": true, "fogey": true, "gists": true, "yogas": true, "gilts": true, "skews": true, "cedes": true, "zeals": true, "alums": true, "okays": true, "elope": true, "grump": true, "wafts": true, "soots": true, "blimp": true, "hefts": true, "mulls": true, "hosed": true, "cress": true, "doffs": true, "ruder": true, "pixie": true, "waifs": true, "ousts": true, "pucks": true, "biers": true, "gulch": true, "suets": true, "hobos": true, "lints": true, "brans": true, "teals": true, "garbs": true, "pewee": true, "helms": true, "turfs": true, "quips": true, "wends": true, "banes": true, "napes": true, "icier": true, "swats": true, "bagel": true, "hexed": true, "ogres": true, "goner": true, "gilds": true, "pyres": true, "lards": true, "bides": true, "paged": true, "talon": true, "flout": true, "medic": true, "veals": true, "putts": true, "dirks": true, "dotes": true, "tippy": true, "blurt": true, "piths": true, "acing": true, "barer": true, "whets": true, "gaits": true, "wools": true, "dunks": true, "heros": true, "swabs": true, "dirts": true, "jutes": true, "hemps": true, "surfs": true, "okapi": true, "chows": true, "shoos": true, "dusks": true, "parry": true, "decal": true, "furls": true, "cilia": true, "sears": true, "novae": true, "murks": true, "warps": true, "slues": true, "lamer": true, "saris": true, "weans": true, "purrs": true, "dills": true, "togas": true, "newts": true, "meany": true, "bunts": true, "razes": true, "goons": true, "wicks": true, "ruses": true, "vends": true, "geode": true, "drake": true, "judos": true, "lofts": true, "pulps": true, "lauds": true, "mucks": true, "vises": true, "mocha": true, "oiled": true, "roman": true, "ethyl": true, "gotta": true, "fugue": true, "smack": true, "gourd": true, "bumpy": true, "radix": true, "fatty": true, "borax": true, "cubit": true, "cacti": true, "gamma": true, "focal": true, "avail": true, "papal": true, "golly": true, "elite": true, "versa": true, "billy": true, "adieu": true, "annum": true, "howdy": true, "rhino": true, "norms": true, "bobby": true, "axiom": true, "setup": true, "yolks": true, "terns": true, "mixer": true, "genre": true, "knoll": true, "abode": true, "junta": true, "gorge": true, "combo": true, "alpha": true, "overt": true, "kinda": true, "spelt": true, "prick": true, "nobly": true, "ephod": true, "audio": true, "modal": true, "veldt": true, "warty": true, "fluke": true, "bonny": true, "bream": true, "rosin": true, "bolls": true, "doers": true, "downs": true, "beady": true, "motif": true, "humph": true, "fella": true, "mould": true, "crepe": true, "kerns": true, "aloha": true, "glyph": true, "azure": true, "riser": true, "blest": true, "locus": true, "lumpy": true, "beryl": true, "wanna": true, "brier": true, "tuner": true, "rowdy": true, "mural": true, "timer": true, "canst": true, "krill": true, "quoth": true, "lemme": true, "triad": true, "tenon": true, "amply": true, "deeps": true, "padre": true, "leant": true, "pacer": true, "octal": true, "dolly": true, "trans": true, "sumac": true, "foamy": true, "lolly": true, "giver": true, "quipu": true, "codex": true, "manna": true, "unwed": true, "vodka": true, "ferny": true, "salon": true, "duple": true, "boron": true, "revue": true, "crier": true, "alack": true, "inter": true, "dilly": true, "whist": true, "cults": true, "spake": true, "reset": true, "loess": true, "decor": true, "mover": true, "verve": true, "ethic": true, "gamut": true, "lingo": true, "dunno": true, "align": true, "sissy": true, "incur": true, "reedy": true, "avant": true, "piper": true, "waxer": true, "calyx": true, "basil": true, "coons": true, "seine": true, "piney": true, "lemma": true, "trams": true, "winch": true, "whirr": true, "saith": true, "ionic": true, "heady": true, "harem": true, "tummy": true, "sally": true, "shied": true, "dross": true, "farad": true, "saver": true, "tilde": true, "jingo": true, "bower": true, "serif": true, "facto": true, "belle": true, "inset": true, "bogus": true, "caved": true, "forte": true, "sooty": true, "bongo": true, "toves": true, "credo": true, "basal": true, "yella": true, "aglow": true, "glean": true, "gusto": true, "hymen": true, "ethos": true, "terra": true, "brash": true, "scrip": true, "swash": true, "aleph": true, "tinny": true, "itchy": true, "wanta": true, "trice": true, "jowls": true, "gongs": true, "garde": true, "boric": true, "twill": true, "sower": true, "henry": true, "awash": true, "libel": true, "spurn": true, "sabre": true, "rebut": true, "penal": true, "obese": true, "sonny": true, "quirt": true, "mebbe": true, "tacit": true, "greek": true, "xenon": true, "hullo": true, "pique": true, "roger": true, "negro": true, "hadst": true, "gecko": true, "beget": true, "uncut": true, "aloes": true, "louis": true, "quint": true, "clunk": true, "raped": true, "salvo": true, "diode": true, "matey": true, "hertz": true, "xylem": true, "kiosk": true, "apace": true, "cawed": true, "peter": true, "wench": true, "cohos": true, "sorta": true, "gamba": true, "bytes": true, "tango": true, "nutty": true, "axial": true, "aleck": true, "natal": true, "clomp": true, "gored": true, "siree": true, "bandy": true, "gunny": true, "runic": true, "whizz": true, "rupee": true, "fated": true, "wiper": true, "bards": true, "briny": true, "staid": true, "hocks": true, "ochre": true, "yummy": true, "gents": true, "soupy": true, "roper": true, "swath": true, "cameo": true, "edger": true, "spate": true, "gimme": true, "ebbed": true, "breve": true, "theta": true, "deems": true, "dykes": true, "servo": true, "telly": true, "tabby": true, "tares": true, "blocs": true, "welch": true, "ghoul": true, "vitae": true, "cumin": true, "dinky": true, "bronc": true, "tabor": true, "teeny": true, "comer": true, "borer": true, "sired": true, "privy": true, "mammy": true, "deary": true, "gyros": true, "sprit": true, "conga": true, "quire": true, "thugs": true, "furor": true, "bloke": true, "runes": true, "bawdy": true, "cadre": true, "toxin": true, "annul": true, "egged": true, "anion": true, "nodes": true, "picky": true, "stein": true, "jello": true, "audit": true, "echos": true, "fagot": true, "letup": true, "eyrie": true, "fount": true, "caped": true, "axons": true, "amuck": true, "banal": true, "riled": true, "petit": true, "umber": true, "miler": true, "fibre": true, "agave": true, "bated": true, "bilge": true, "vitro": true, "feint": true, "pudgy": true, "mater": true, "manic": true, "umped": true, "pesky": true, "strep": true, "slurp": true, "pylon": true, "puree": true, "caret": true, "temps": true, "newel": true, "yawns": true, "seedy": true, "treed": true, "coups": true, "rangy": true, "brads": true, "mangy": true, "loner": true, "circa": true, "tibia": true, "afoul": true, "mommy": true, "titer": true, "carne": true, "kooky": true, "motes": true, "amity": true, "suave": true, "hippo": true, "curvy": true, "samba": true, "newsy": true, "anise": true, "imams": true, "tulle": true, "aways": true, "liven": true, "hallo": true, "wales": true, "opted": true, "canto": true, "idyll": true, "bodes": true, "curio": true, "wrack": true, "hiker": true, "chive": true, "yokel": true, "dotty": true, "demur": true, "cusps": true, "specs": true, "quads": true, "laity": true, "toner": true, "decry": true, "writs": true, "saute": true, "clack": true, "aught": true, "logos": true, "tipsy": true, "natty": true, "ducal": true, "bidet": true, "bulgy": true, "metre": true, "lusts": true, "unary": true, "goeth": true, "baler": true, "sited": true, "shies": true, "hasps": true, "brung": true, "holed": true, "swank": true, "looky": true, "melee": true, "huffy": true, "loamy": true, "pimps": true, "titan": true, "binge": true, "shunt": true, "femur": true, "libra": true, "seder": true, "honed": true, "annas": true, "coypu": true, "shims": true, "zowie": true, "jihad": true, "savvy": true, "nadir": true, "basso": true, "monic": true, "maned": true, "mousy": true, "omega": true, "laver": true, "prima": true, "picas": true, "folio": true, "mecca": true, "reals": true, "troth": true, "testy": true, "balky": true, "crimp": true, "chink": true, "abets": true, "splat": true, "abaci": true, "vaunt": true, "cutie": true, "pasty": true, "moray": true, "levis": true, "ratty": true, "islet": true, "joust": true, "motet": true, "viral": true, "nukes": true, "grads": true, "comfy": true, "voila": true, "woozy": true, "blued": true, "whomp": true, "sward": true, "metro": true, "skeet": true, "chine": true, "aerie": true, "bowie": true, "tubby": true, "emirs": true, "coati": true, "unzip": true, "slobs": true, "trike": true, "funky": true, "ducat": true, "dewey": true, "skoal": true, "wadis": true, "oomph": true, "taker": true, "minim": true, "getup": true, "stoic": true, "synod": true, "runty": true, "flyby": true, "braze": true, "inlay": true, "venue": true, "louts": true, "peaty": true, "orlon": true, "humpy": true, "radon": true, "beaut": true, "raspy": true, "unfed": true, "crick": true, "nappy": true, "vizor": true, "yipes": true, "rebus": true, "divot": true, "kiwis": true, "vetch": true, "squib": true, "sitar": true, "kiddo": true, "dyers": true, "cotta": true, "matzo": true, "lager": true, "zebus": true, "crass": true, "dacha": true, "kneed": true, "dicta": true, "fakir": true, "knurl": true, "runny": true, "unpin": true, "julep": true, "globs": true, "nudes": true, "sushi": true, "tacky": true, "stoke": true, "kaput": true, "butch": true, "hulas": true, "croft": true, "achoo": true, "genii": true, "nodal": true, "outgo": true, "spiel": true, "viols": true, "fetid": true, "cagey": true, "fudgy": true, "epoxy": true, "leggy": true, "hanky": true, "lapis": true, "felon": true, "beefy": true, "coots": true, "melba": true, "caddy": true, "segue": true, "betel": true, "frizz": true, "drear": true, "kooks": true, "turbo": true, "hoagy": true, "moult": true, "helix": true, "zonal": true, "arias": true, "nosey": true, "paean": true, "lacey": true, "banns": true, "swain": true, "fryer": true, "retch": true, "tenet": true, "gigas": true, "whiny": true, "ogled": true, "rumen": true, "begot": true, "cruse": true, "abuts": true, "riven": true, "balks": true, "sines": true, "sigma": true, "abase": true, "ennui": true, "gores": true, "unset": true, "augur": true, "sated": true, "odium": true, "latin": true, "dings": true, "moire": true, "scion": true, "henna": true, "kraut": true, "dicks": true, "lifer": true, "prigs": true, "bebop": true, "gages": true, "gazer": true, "fanny": true, "gibes": true, "aural": true, "tempi": true, "hooch": true, "rapes": true, "snuck": true, "harts": true, "techs": true, "emend": true, "ninny": true, "guava": true, "scarp": true, "liege": true, "tufty": true, "sepia": true, "tomes": true, "carob": true, "emcee": true, "prams": true, "poser": true, "verso": true, "hubba": true, "joule": true, "baize": true, "blips": true, "scrim": true, "cubby": true, "clave": true, "winos": true, "rearm": true, "liens": true, "lumen": true, "chump": true, "nanny": true, "trump": true, "fichu": true, "chomp": true, "homos": true, "purty": true, "maser": true, "woosh": true, "patsy": true, "shill": true, "rusks": true, "avast": true, "swami": true, "boded": true, "ahhhh": true, "lobed": true, "natch": true, "shish": true, "tansy": true, "snoot": true, "payer": true, "altho": true, "sappy": true, "laxer": true, "hubby": true, "aegis": true, "riles": true, "ditto": true, "jazzy": true, "dingo": true, "quasi": true, "septa": true, "peaky": true, "lorry": true, "heerd": true, "bitty": true, "payee": true, "seamy": true, "apses": true, "imbue": true, "belie": true, "chary": true, "spoof": true, "phyla": true, "clime": true, "babel": true, "wacky": true, "sumps": true, "skids": true, "khans": true, "crypt": true, "inure": true, "nonce": true, "outen": true, "faire": true, "hooey": true, "anole": true, "kazoo": true, "calve": true, "limbo": true, "argot": true, "ducky": true, "faker": true, "vibes": true, "gassy": true, "unlit": true, "nervy": true, "femme": true, "biter": true, "fiche": true, "boors": true, "gaffe": true, "saxes": true, "recap": true, "synch": true, "facie": true, "dicey": true, "ouija": true, "hewer": true, "legit": true, "gurus": true, "edify": true, "tweak": true, "caron": true, "typos": true, "rerun": true, "polly": true, "surds": true, "hamza": true, "nulls": true, "hater": true, "lefty": true, "mogul": true, "mafia": true, "debug": true, "pates": true, "blabs": true, "splay": true, "talus": true, "porno": true, "moola": true, "nixed": true, "kilos": true, "snide": true, "horsy": true, "gesso": true, "jaggy": true, "trove": true, "nixes": true, "creel": true, "pater": true, "iotas": true, "cadge": true, "skyed": true, "hokum": true, "furze": true, "ankhs": true, "curie": true, "nutsy": true, "hilum": true, "remix": true, "angst": true, "burls": true, "jimmy": true, "veiny": true, "tryst": true, "codon": true, "befog": true, "gamed": true, "flume": true, "axman": true, "doozy": true, "lubes": true, "rheas": true, "bozos": true, "butyl": true, "kelly": true, "mynah": true, "jocks": true, "donut": true, "avian": true, "wurst": true, "chock": true, "quash": true, "quals": true, "hayed": true, "bombe": true, "cushy": true, "spacy": true, "puked": true, "leery": true, "thews": true, "prink": true, "amens": true, "tesla": true, "intro": true, "fiver": true, "frump": true, "capos": true, "opine": true, "coder": true, "namer": true, "jowly": true, "pukes": true, "haled": true, "chard": true, "duffs": true, "bruin": true, "reuse": true, "whang": true, "toons": true, "frats": true, "silty": true, "telex": true, "cutup": true, "nisei": true, "neato": true, "decaf": true, "softy": true, "bimbo": true, "adlib": true, "loony": true, "shoed": true, "agues": true, "peeve": true, "noway": true, "gamey": true, "sarge": true, "reran": true, "epact": true, "potty": true, "coned": true, "upend": true, "narco": true, "ikats": true, "whorl": true, "jinks": true, "tizzy": true, "weepy": true, "posit": true, "marge": true, "vegan": true, "clops": true, "numbs": true, "reeks": true, "rubes": true, "rower": true, "biped": true, "tiffs": true, "hocus": true, "hammy": true, "bunco": true, "fixit": true, "tykes": true, "chaws": true, "yucky": true, "hokey": true, "resew": true, "maven": true, "adman": true, "scuzz": true, "slogs": true, "souse": true, "nacho": true, "mimed": true, "melds": true, "boffo": true, "debit": true, "pinup": true, "vagus": true, "gulag": true, "randy": true, "bosun": true, "educe": true, "faxes": true, "auras": true, "pesto": true, "antsy": true, "betas": true, "fizzy": true, "dorky": true, "snits": true, "moxie": true, "thane": true, "mylar": true, "nobby": true, "gamin": true, "gouty": true, "esses": true, "goyim": true, "paned": true, "druid": true, "jades": true, "rehab": true, "gofer": true, "tzars": true, "octet": true, "homed": true, "socko": true, "dorks": true, "eared": true, "anted": true, "elide": true, "fazes": true, "oxbow": true, "dowse": true, "situs": true, "macaw": true, "scone": true, "drily": true, "hyper": true, "salsa": true, "mooch": true, "gated": true, "unjam": true, "lipid": true, "mitre": true, "venal": true, "knish": true, "ritzy": true, "divas": true, "torus": true, "mange": true, "dimer": true, "recut": true, "meson": true, "wined": true, "fends": true, "phage": true, "fiats": true, "caulk": true, "cavil": true, "panty": true, "roans": true, "bilks": true, "hones": true, "botch": true, "estop": true, "sully": true, "sooth": true, "gelds": true, "ahold": true, "raper": true, "pager": true, "fixer": true, "infix": true, "hicks": true, "tuxes": true, "plebe": true, "twits": true, "abash": true, "twixt": true, "wacko": true, "primp": true, "nabla": true, "girts": true, "miffs": true, "emote": true, "xerox": true, "rebid": true, "shahs": true, "rutty": true, "grout": true, "grift": true, "deify": true, "biddy": true, "kopek": true, "semis": true, "bries": true, "acmes": true, "piton": true, "hussy": true, "torts": true, "disco": true, "whore": true, "boozy": true, "gibed": true, "vamps": true, "amour": true, "soppy": true, "gonzo": true, "durst": true, "wader": true, "tutus": true, "perms": true, "catty": true, "glitz": true, "brigs": true, "nerds": true, "barmy": true, "gizmo": true, "owlet": true, "sayer": true, "molls": true, "shard": true, "whops": true, "comps": true, "corer": true, "colas": true, "matte": true, "droid": true, "ploys": true, "vapid": true, "cairn": true, "deism": true, "mixup": true, "yikes": true, "prosy": true, "raker": true, "flubs": true, "whish": true, "reify": true, "craps": true, "shags": true, "clone": true, "hazed": true, "macho": true, "recto": true, "refix": true, "drams": true, "biker": true, "aquas": true, "porky": true, "doyen": true, "exude": true, "goofs": true, "divvy": true, "noels": true, "jived": true, "hulky": true, "cager": true, "harpy": true, "oldie": true, "vivas": true, "admix": true, "codas": true, "zilch": true, "deist": true, "orcas": true, "retro": true, "pilaf": true, "parse": true, "rants": true, "zingy": true, "toddy": true, "chiff": true, "micro": true, "veeps": true, "girly": true, "nexus": true, "demos": true, "bibbs": true, "antes": true, "lulus": true, "gnarl": true, "zippy": true, "ivied": true, "epees": true, "wimps": true, "tromp": true, "grail": true, "yoyos": true, "poufs": true, "hales": true, "roust": true, "cabal": true, "rawer": true, "pampa": true, "mosey": true, "kefir": true, "burgs": true, "unmet": true, "cuspy": true, "boobs": true, "boons": true, "hypes": true, "dynes": true, "nards": true, "lanai": true, "yogis": true, "sepal": true, "quark": true, "toked": true, "prate": true, "ayins": true, "hawed": true, "swigs": true, "vitas": true, "toker": true, "doper": true, "bossa": true, "linty": true, "foist": true, "mondo": true, "stash": true, "kayos": true, "twerp": true, "zesty": true, "capon": true, "wimpy": true, "rewed": true, "fungo": true, "tarot": true, "frosh": true, "kabob": true, "pinko": true, "redid": true, "mimeo": true, "heist": true, "tarps": true, "lamas": true, "sutra": true, "dinar": true, "whams": true, "busty": true, "spays": true, "mambo": true, "nabob": true, "preps": true, "odour": true, "cabby": true, "conks": true, "sluff": true, "dados": true, "houri": true, "swart": true, "balms": true, "gutsy": true, "faxed": true, "egads": true, "pushy": true, "retry": true, "agora": true, "drubs": true, "daffy": true, "chits": true, "mufti": true, "karma": true, "lotto": true, "toffs": true, "burps": true, "deuce": true, "zings": true, "kappa": true, "clads": true, "doggy": true, "duper": true, "scams": true, "ogler": true, "mimes": true, "throe": true, "zetas": true, "waled": true, "promo": true, "blats": true, "muffs": true, "oinks": true, "viand": true, "coset": true, "finks": true, "faddy": true, "minis": true, "snafu": true, "sauna": true, "usury": true, "muxes": true, "craws": true, "stats": true, "condo": true, "coxes": true, "loopy": true, "dorms": true, "ascot": true, "dippy": true, "execs": true, "dopey": true, "envoi": true, "umpty": true, "gismo": true, "fazed": true, "strop": true, "jives": true, "slims": true, "batik": true, "pings": true, "sonly": true, "leggo": true, "pekoe": true, "prawn": true, "luaus": true, "campy": true, "oodle": true, "prexy": true, "proms": true, "touts": true, "ogles": true, "tweet": true, "toady": true, "naiad": true, "hider": true, "nuked": true, "fatso": true, "sluts": true, "obits": true, "narcs": true, "tyros": true, "delis": true, "wooer": true, "hyped": true, "poset": true, "byway": true, "texas": true, "scrod": true, "avows": true, "futon": true, "torte": true, "tuple": true, "carom": true, "kebab": true, "tamps": true, "jilts": true, "duals": true, "artsy": true, "repro": true, "modem": true, "toped": true, "psych": true, "sicko": true, "klutz": true, "tarns": true, "coxed": true, "drays": true, "cloys": true, "anded": true, "piker": true, "aimer": true, "suras": true, "limos": true, "flack": true, "hapax": true, "dutch": true, "mucky": true, "shire": true, "klieg": true, "staph": true, "layup": true, "tokes": true, "axing": true, "toper": true, "duvet": true, "cowry": true, "profs": true, "blahs": true, "addle": true, "sudsy": true, "batty": true, "coifs": true, "suety": true, "gabby": true, "hafta": true, "pitas": true, "gouda": true, "deice": true, "taupe": true, "topes": true, "duchy": true, "nitro": true, "carny": true, "limey": true, "orals": true, "hirer": true, "taxer": true, "roils": true, "ruble": true, "elate": true, "dolor": true, "wryer": true, "snots": true, "quais": true, "coked": true, "gimel": true, "gorse": true, "minas": true, "goest": true, "agape": true, "manta": true, "jings": true, "iliac": true, "admen": true, "offen": true, "cills": true, "offal": true, "lotta": true, "bolas": true, "thwap": true, "alway": true, "boggy": true, "donna": true, "locos": true, "belay": true, "gluey": true, "bitsy": true, "mimsy": true, "hilar": true, "outta": true, "vroom": true, "fetal": true, "raths": true, "renal": true, "dyads": true, "crocs": true, "vires": true, "culpa": true, "kivas": true, "feist": true, "teats": true, "thats": true, "yawls": true, "whens": true, "abaca": true, "ohhhh": true, "aphis": true, "fusty": true, "eclat": true, "perdu": true, "mayst": true, "exeat": true, "molly": true, "supra": true, "wetly": true, "plasm": true, "buffa": true, "semen": true, "pukka": true, "tagua": true, "paras": true, "stoat": true, "secco": true, "carte": true, "haute": true, "molal": true, "shads": true, "forma": true, "ovoid": true, "pions": true, "modus": true, "bueno": true, "rheum": true, "scurf": true, "parer": true, "ephah": true, "doest": true, "sprue": true, "flams": true, "molto": true, "dieth": true, "choos": true, "miked": true, "bronx": true, "goopy": true, "bally": true, "plumy": true, "moony": true, "morts": true, "yourn": true, "bipod": true, "spume": true, "algal": true, "ambit": true, "mucho": true, "spued": true, "dozer": true, "harum": true, "groat": true, "skint": true, "laude": true, "thrum": true, "pappy": true, "oncet": true, "rimed": true, "gigue": true, "limed": true, "plein": true, "redly": true, "humpf": true, "lites": true, "seest": true, "grebe": true, "absit": true, "thanx": true, "pshaw": true, "yawps": true, "plats": true, "payed": true, "areal": true, "tilth": true, "youse": true, "gwine": true, "thees": true, "watsa": true, "lento": true, "spitz": true, "yawed": true, "gipsy": true, "sprat": true, "cornu": true, "amahs": true, "blowy": true, "wahoo": true, "lubra": true, "mecum": true, "whooo": true, "coqui": true, "sabra": true, "edema": true, "mrads": true, "dicot": true, "astro": true, "kited": true, "ouzel": true, "didos": true, "grata": true, "bonne": true, "axmen": true, "klunk": true, "summa": true, "laves": true, "purls": true, "yawny": true, "teary": true, "masse": true, "largo": true, "bazar": true, "pssst": true, "sylph": true, "lulab": true, "toque": true, "fugit": true, "plunk": true, "ortho": true, "lucre": true, "cooch": true, "whipt": true, "folky": true, "tyres": true, "wheee": true, "corky": true, "injun": true, "solon": true, "didot": true, "kerfs": true, "rayed": true, "wassa": true, "chile": true, "begat": true, "nippy": true, "litre": true, "magna": true, "rebox": true, "hydro": true, "milch": true, "brent": true, "gyves": true, "lazed": true, "feued": true, "mavis": true, "inapt": true, "baulk": true, "casus": true, "scrum": true, "wised": true, "fossa": true, "dower": true, "kyrie": true, "bhoys": true, "scuse": true, "feuar": true, "ohmic": true, "juste": true, "ukase": true, "beaux": true, "tusky": true, "orate": true, "musta": true, "lardy": true, "intra": true, "quiff": true, "epsom": true, "neath": true, "ocher": true, "tared": true, "homme": true, "mezzo": true, "corms": true, "psoas": true, "beaky": true, "terry": true, "infra": true, "spivs": true, "tuans": true, "belli": true, "bergs": true, "anima": true, "weirs": true, "mahua": true, "scops": true, "manse": true, "titre": true, "curia": true, "kebob": true, "cycad": true, "talky": true, "fucks": true, "tapis": true, "amide": true, "dolce": true, "sloes": true, "jakes": true, "russe": true, "blash": true, "tutti": true, "pruta": true, "panga": true, "blebs": true, "tench": true, "swarf": true, "herem": true, "missy": true, "merse": true, "pawky": true, "limen": true, "vivre": true, "chert": true, "unsee": true, "tiros": true, "brack": true, "foots": true, "welsh": true, "fosse": true, "knops": true, "ileum": true, "noire": true, "firma": true, "podgy": true, "laird": true, "thunk": true, "shute": true, "rowan": true, "shoji": true, "poesy": true, "uncap": true, "fames": true, "glees": true, "costa": true, "turps": true, "fores": true, "solum": true, "imago": true, "byres": true, "fondu": true, "coney": true, "polis": true, "dictu": true, "kraal": true, "sherd": true, "mumbo": true, "wroth": true, "chars": true, "unbox": true, "vacuo": true, "slued": true, "weest": true, "hades": true, "wiled": true, "syncs": true, "muser": true, "excon": true, "hoars": true, "sibyl": true, "passe": true, "joeys": true, "lotsa": true, "lepta": true, "shays": true, "bocks": true, "endue": true, "darer": true, "nones": true, "ileus": true, "plash": true, "busby": true, "wheal": true, "buffo": true, "yobbo": true, "biles": true, "poxes": true, "rooty": true, "licit": true, "terce": true, "bromo": true, "hayey": true, "dweeb": true, "imbed": true, "saran": true, "bruit": true, "punky": true, "softs": true, "biffs": true, "loppy": true, "agars": true, "aquae": true, "livre": true, "biome": true, "bunds": true, "shews": true, "diems": true, "ginny": true, "degum": true, "polos": true, "desex": true, "unman": true, "dungy": true, "vitam": true, "wedgy": true, "glebe": true, "apers": true, "ridgy": true, "roids": true, "wifey": true, "vapes": true, "whoas": true, "bunko": true, "yolky": true, "ulnas": true, "reeky": true, "bodge": true, "brant": true, "davit": true, "deque": true, "liker": true, "jenny": true, "tacts": true, "fulls": true, "treap": true, "ligne": true, "acked": true, "refry": true, "vower": true, "aargh": true, "churl": true, "momma": true, "gaols": true, "whump": true, "arras": true, "marls": true, "tiler": true, "grogs": true, "memes": true, "midis": true, "tided": true, "haler": true, "duces": true, "twiny": true, "poste": true, "unrig": true, "prise": true, "drabs": true, "quids": true, "facer": true, "spier": true, "baric": true, "geoid": true, "remap": true, "trier": true, "gunks": true, "steno": true, "stoma": true, "airer": true, "ovate": true, "torah": true, "apian": true, "smuts": true, "pocks": true, "yurts": true, "exurb": true, "defog": true, "nuder": true, "bosky": true, "nimbi": true, "mothy": true, "joyed": true, "labia": true, "pards": true, "jammy": true, "bigly": true, "faxer": true, "hoppy": true, "nurbs": true, "cotes": true, "dishy": true, "vised": true, "celeb": true, "pismo": true, "casas": true, "withs": true, "dodgy": true, "scudi": true, "mungs": true, "muons": true, "ureas": true, "ioctl": true, "unhip": true, "krone": true, "sager": true, "verst": true, "expat": true, "gronk": true, "uvula": true, "shawm": true, "bilgy": true, "braes": true, "cento": true, "webby": true, "lippy": true, "gamic": true, "lordy": true, "mazed": true, "tings": true, "shoat": true, "faery": true, "wirer": true, "diazo": true, "carer": true, "rater": true, "greps": true, "rente": true, "zloty": true, "viers": true, "unapt": true, "poops": true, "fecal": true, "kepis": true, "taxon": true, "eyers": true, "wonts": true, "spina": true, "stoae": true, "yenta": true, "pooey": true, "buret": true, "japan": true, "bedew": true, "hafts": true, "selfs": true, "oared": true, "herby": true, "pryer": true, "oakum": true, "dinks": true, "titty": true, "sepoy": true, "penes": true, "fusee": true, "winey": true, "gimps": true, "nihil": true, "rille": true, "giber": true, "ousel": true, "umiak": true, "cuppy": true, "hames": true, "shits": true, "azine": true, "glads": true, "tacet": true, "bumph": true, "coyer": true, "honky": true, "gamer": true, "gooky": true, "waspy": true, "sedgy": true, "bents": true, "varia": true, "djinn": true, "junco": true, "pubic": true, "wilco": true, "lazes": true, "idyls": true, "lupus": true, "rives": true, "snood": true, "schmo": true, "spazz": true, "finis": true, "noter": true, "pavan": true, "orbed": true, "bates": true, "pipet": true, "baddy": true, "goers": true, "shako": true, "stets": true, "sebum": true, "seeth": true, "lobar": true, "raver": true, "ajuga": true, "riced": true, "velds": true, "dribs": true, "ville": true, "dhows": true, "unsew": true, "halma": true, "krona": true, "limby": true, "jiffs": true, "treys": true, "bauds": true, "pffft": true, "mimer": true, "plebs": true, "caner": true, "jiber": true, "cuppa": true, "washy": true, "chuff": true, "unarm": true, "yukky": true, "styes": true, "waker": true, "flaks": true, "maces": true, "rimes": true, "gimpy": true, "guano": true, "liras": true, "kapok": true, "scuds": true, "bwana": true, "oring": true, "aider": true, "prier": true, "klugy": true, "monte": true, "golem": true, "velar": true, "firer": true, "pieta": true, "umbel": true, "campo": true, "unpeg": true, "fovea": true, "abeam": true, "boson": true, "asker": true, "goths": true, "vocab": true, "vined": true, "trows": true, "tikis": true, "loper": true, "indie": true, "boffs": true, "spang": true, "grapy": true, "tater": true, "ichor": true, "kilty": true, "lochs": true, "supes": true, "degas": true, "flics": true, "torsi": true, "beths": true, "weber": true, "resaw": true, "lawny": true, "coven": true, "mujik": true, "relet": true, "therm": true, "heigh": true, "shnor": true, "trued": true, "zayin": true, "liest": true, "barfs": true, "bassi": true, "qophs": true, "roily": true, "flabs": true, "punny": true, "okras": true, "hanks": true, "dipso": true, "nerfs": true, "fauns": true, "calla": true, "pseud": true, "lurer": true, "magus": true, "obeah": true, "atria": true, "twink": true, "palmy": true, "pocky": true, "pends": true, "recta": true, "plonk": true, "slaws": true, "keens": true, "nicad": true, "pones": true, "inker": true, "whews": true, "groks": true, "mosts": true, "trews": true, "ulnar": true, "gyppy": true, "cocas": true, "expos": true, "eruct": true, "oiler": true, "vacua": true, "dreck": true, "dater": true, "arums": true, "tubal": true, "voxel": true, "dixit": true, "beery": true, "assai": true, "lades": true, "actin": true, "ghoti": true, "buzzy": true, "meads": true, "grody": true, "ribby": true, "clews": true, "creme": true, "email": true, "pyxie": true, "kulak": true, "bocci": true, "rived": true, "duddy": true, "hoper": true, "lapin": true, "wonks": true, "petri": true, "phial": true, "fugal": true, "holon": true, "boomy": true, "duomo": true, "musos": true, "shier": true, "hayer": true, "porgy": true, "hived": true, "litho": true, "fisty": true, "stagy": true, "luvya": true, "maria": true, "smogs": true, "asana": true, "yogic": true, "slomo": true, "fawny": true, "amine": true, "wefts": true, "gonad": true, "twirp": true, "brava": true, "plyer": true, "fermi": true, "loges": true, "niter": true, "revet": true, "unate": true, "gyved": true, "totty": true, "zappy": true, "honer": true, "giros": true, "dicer": true, "calks": true, "luxes": true, "monad": true, "cruft": true, "quoin": true, "fumer": true, "amped": true, "shlep": true, "vinca": true, "yahoo": true, "vulva": true, "zooey": true, "dryad": true, "nixie": true, "moper": true, "iambs": true, "lunes": true, "nudie": true, "limns": true, "weals": true, "nohow": true, "miaow": true, "gouts": true, "mynas": true, "mazer": true, "kikes": true, "oxeye": true, "stoup": true, "jujus": true, "debar": true, "pubes": true, "taels": true, "defun": true, "rands": true, "blear": true, "paver": true, "goosy": true, "sprog": true, "oleos": true, "toffy": true, "pawer": true, "maced": true, "crits": true, "kluge": true, "tubed": true, "sahib": true, "ganef": true, "scats": true, "sputa": true, "vaned": true, "acned": true, "taxol": true, "plink": true, "oweth": true, "tribs": true, "resay": true, "boule": true, "thous": true, "haply": true, "glans": true, "maxis": true, "bezel": true, "antis": true, "porks": true, "quoit": true, "alkyd": true, "glary": true, "beamy": true, "hexad": true, "bonks": true, "tecum": true, "kerbs": true, "filar": true, "frier": true, "redux": true, "abuzz": true, "fader": true, "shoer": true, "couth": true, "trues": true, "guyed": true, "goony": true, "booky": true, "fuzes": true, "hurly": true, "genet": true, "hodad": true, "calix": true, "filer": true, "pawls": true, "iodic": true, "utero": true, "henge": true, "unsay": true, "liers": true, "piing": true, "weald": true, "sexed": true, "folic": true, "poxed": true, "cunts": true, "anile": true, "kiths": true, "becks": true, "tatty": true, "plena": true, "rebar": true, "abled": true, "toyer": true, "attar": true, "teaks": true, "aioli": true, "awing": true, "anent": true, "feces": true, "redip": true, "wists": true, "prats": true, "mesne": true, "muter": true, "smurf": true, "owest": true, "bahts": true, "lossy": true, "ftped": true, "hunky": true, "hoers": true, "slier": true, "sicks": true, "fatly": true, "delft": true, "hiver": true, "himbo": true, "pengo": true, "busks": true, "loxes": true, "zonks": true, "ilium": true, "aport": true, "ikons": true, "mulct": true, "reeve": true, "civvy": true, "canna": true, "barfy": true, "kaiak": true, "scudo": true, "knout": true, "gaper": true, "bhang": true, "pease": true, "uteri": true, "lases": true, "paten": true, "rasae": true, "axels": true, "stoas": true, "ombre": true, "styli": true, "gunky": true, "hazer": true, "kenaf": true, "ahoys": true, "ammos": true, "weeny": true, "urger": true, "kudzu": true, "paren": true, "bolos": true, "fetor": true, "nitty": true, "techy": true, "lieth": true, "somas": true, "darky": true, "villi": true, "gluon": true, "janes": true, "cants": true, "farts": true, "socle": true, "jinns": true, "ruing": true, "slily": true, "ricer": true, "hadda": true, "wowee": true, "rices": true, "nerts": true, "cauls": true, "swive": true, "lilty": true, "micks": true, "arity": true, "pasha": true, "finif": true, "oinky": true, "gutty": true, "tetra": true, "wises": true, "wolds": true, "balds": true, "picot": true, "whats": true, "shiki": true, "bungs": true, "snarf": true, "legos": true, "dungs": true, "stogy": true, "berms": true, "tangs": true, "vails": true, "roods": true, "morel": true, "sware": true, "elans": true, "latus": true, "gules": true, "razer": true, "doxie": true, "buena": true, "overs": true, "gutta": true, "zincs": true, "nates": true, "kirks": true, "tikes": true, "donee": true, "jerry": true, "mohel": true, "ceder": true, "doges": true, "unmap": true, "folia": true, "rawly": true, "snark": true, "topoi": true, "ceils": true, "immix": true, "yores": true, "diest": true, "bubba": true, "pomps": true, "forky": true, "turdy": true, "lawzy": true, "poohs": true, "worts": true, "gloms": true, "beano": true, "muley": true, "barky": true, "tunny": true, "auric": true, "funks": true, "gaffs": true, "cordy": true, "curdy": true, "lisle": true, "toric": true, "soyas": true, "reman": true, "mungy": true, "carpy": true, "apish": true, "oaten": true, "gappy": true, "aurae": true, "bract": true, "rooky": true, "axled": true, "burry": true, "sizer": true, "proem": true, "turfy": true, "impro": true, "mashy": true, "miens": true, "nonny": true, "olios": true, "grook": true, "sates": true, "agley": true, "corgi": true, "dashy": true, "doser": true, "dildo": true, "apsos": true, "xored": true, "laker": true, "playa": true, "selah": true, "malty": true, "dulse": true, "frigs": true, "demit": true, "whoso": true, "rials": true, "sawer": true, "spics": true, "bedim": true, "snugs": true, "fanin": true, "azoic": true, "icers": true, "suers": true, "wizen": true, "koine": true, "topos": true, "shirr": true, "rifer": true, "feral": true, "laded": true, "lased": true, "turds": true, "swede": true, "easts": true, "cozen": true, "unhit": true, "pally": true, "aitch": true, "sedum": true, "coper": true, "ruche": true, "geeks": true, "swags": true, "etext": true, "algin": true, "offed": true, "ninja": true, "holer": true, "doter": true, "toter": true, "besot": true, "dicut": true, "macer": true, "peens": true, "pewit": true, "redox": true, "poler": true, "yecch": true, "fluky": true, "doeth": true, "twats": true, "cruds": true, "bebug": true, "bider": true, "stele": true, "hexer": true, "wests": true, "gluer": true, "pilau": true, "abaft": true, "whelm": true, "lacer": true, "inode": true, "tabus": true, "gator": true, "cuing": true, "refly": true, "luted": true, "cukes": true, "bairn": true, "bight": true, "arses": true, "crump": true, "loggy": true, "blini": true, "spoor": true, "toyon": true, "harks": true, "wazoo": true, "fenny": true, "naves": true, "keyer": true, "tufas": true, "morph": true, "rajas": true, "typal": true, "spiff": true, "oxlip": true, "unban": true, "mussy": true, "finny": true, "rimer": true, "login": true, "molas": true, "cirri": true, "huzza": true, "agone": true, "unsex": true, "unwon": true, "peats": true, "toile": true, "zombi": true, "dewed": true, "nooky": true, "alkyl": true, "ixnay": true, "dovey": true, "holey": true, "cuber": true, "amyls": true, "podia": true, "chino": true, "apnea": true, "prims": true, "lycra": true, "johns": true, "primo": true, "fatwa": true, "egger": true, "hempy": true, "snook": true, "hying": true, "fuzed": true, "barms": true, "crink": true, "moots": true, "yerba": true, "rhumb": true, "unarc": true, "direr": true, "munge": true, "eland": true, "nares": true, "wrier": true, "noddy": true, "atilt": true, "jukes": true, "ender": true, "thens": true, "unfix": true, "doggo": true, "zooks": true, "diddy": true, "shmoo": true, "brusk": true, "prest": true, "curer": true, "pasts": true, "kelpy": true, "bocce": true, "kicky": true, "taros": true, "lings": true, "dicky": true, "nerdy": true, "abend": true, "stela": true, "biggy": true, "laved": true, "baldy": true, "pubis": true, "gooks": true, "wonky": true, "stied": true, "hypos": true, "assed": true, "spumy": true, "osier": true, "roble": true, "rumba": true, "biffy": true, "pupal": true, }
constants/wordlists.go
0.5083
0.444022
wordlists.go
starcoder
Matrix Operations */ //----------------------------------------------------------------------------- package sdf import ( "math" ) //----------------------------------------------------------------------------- type M44 struct { x00, x01, x02, x03 float64 x10, x11, x12, x13 float64 x20, x21, x22, x23 float64 x30, x31, x32, x33 float64 } type M33 struct { x00, x01, x02 float64 x10, x11, x12 float64 x20, x21, x22 float64 } type M22 struct { x00, x01 float64 x10, x11 float64 } //----------------------------------------------------------------------------- func RandomM22(a, b float64) M22 { m := M22{random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b)} return m } func RandomM33(a, b float64) M33 { m := M33{random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b)} return m } func RandomM44(a, b float64) M44 { m := M44{ random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b), random_range(a, b)} return m } //----------------------------------------------------------------------------- func Identity3d() M44 { return M44{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} } func Identity2d() M33 { return M33{ 1, 0, 0, 0, 1, 0, 0, 0, 1} } func Identity() M22 { return M22{ 1, 0, 0, 1} } func Translate3d(v V3) M44 { return M44{ 1, 0, 0, v.X, 0, 1, 0, v.Y, 0, 0, 1, v.Z, 0, 0, 0, 1} } func Translate2d(v V2) M33 { return M33{ 1, 0, v.X, 0, 1, v.Y, 0, 0, 1} } func Scale3d(v V3) M44 { return M44{ v.X, 0, 0, 0, 0, v.Y, 0, 0, 0, 0, v.Z, 0, 0, 0, 0, 1} } func Scale2d(v V2) M33 { return M33{ v.X, 0, 0, 0, v.Y, 0, 0, 0, 1} } // Return an orthographic 3d rotation matrix (right hand rule) func Rotate3d(v V3, a float64) M44 { v = v.Normalize() s := math.Sin(a) c := math.Cos(a) m := 1 - c return M44{ m*v.X*v.X + c, m*v.X*v.Y - v.Z*s, m*v.Z*v.X + v.Y*s, 0, m*v.X*v.Y + v.Z*s, m*v.Y*v.Y + c, m*v.Y*v.Z - v.X*s, 0, m*v.Z*v.X - v.Y*s, m*v.Y*v.Z + v.X*s, m*v.Z*v.Z + c, 0, 0, 0, 0, 1} } // Rotate about the X axis. func RotateX(a float64) M44 { return Rotate3d(V3{1, 0, 0}, a) } // Rotate about the Y axis. func RotateY(a float64) M44 { return Rotate3d(V3{0, 1, 0}, a) } // Rotate about the Z axis. func RotateZ(a float64) M44 { return Rotate3d(V3{0, 0, 1}, a) } // TODO - generalise for other mirror planes // Mirror across the YZ plane func MirrorYZ() M44 { return M44{ -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} } // Return an orthographic 2d rotation matrix (right hand rule) func Rotate2d(a float64) M33 { s := math.Sin(a) c := math.Cos(a) return M33{ c, -s, 0, s, c, 0, 0, 0, 1} } func Rotate(a float64) M22 { s := math.Sin(a) c := math.Cos(a) return M22{ c, -s, s, c, } } //----------------------------------------------------------------------------- func (a M44) Equals(b M44, tolerance float64) bool { return (Abs(a.x00-b.x00) < tolerance && Abs(a.x01-b.x01) < tolerance && Abs(a.x02-b.x02) < tolerance && Abs(a.x03-b.x03) < tolerance && Abs(a.x10-b.x10) < tolerance && Abs(a.x11-b.x11) < tolerance && Abs(a.x12-b.x12) < tolerance && Abs(a.x13-b.x13) < tolerance && Abs(a.x20-b.x20) < tolerance && Abs(a.x21-b.x21) < tolerance && Abs(a.x22-b.x22) < tolerance && Abs(a.x23-b.x23) < tolerance && Abs(a.x30-b.x30) < tolerance && Abs(a.x31-b.x31) < tolerance && Abs(a.x32-b.x32) < tolerance && Abs(a.x33-b.x33) < tolerance) } func (a M33) Equals(b M33, tolerance float64) bool { return (Abs(a.x00-b.x00) < tolerance && Abs(a.x01-b.x01) < tolerance && Abs(a.x02-b.x02) < tolerance && Abs(a.x10-b.x10) < tolerance && Abs(a.x11-b.x11) < tolerance && Abs(a.x12-b.x12) < tolerance && Abs(a.x20-b.x20) < tolerance && Abs(a.x21-b.x21) < tolerance && Abs(a.x22-b.x22) < tolerance) } func (a M22) Equals(b M22, tolerance float64) bool { return (Abs(a.x00-b.x00) < tolerance && Abs(a.x01-b.x01) < tolerance && Abs(a.x10-b.x10) < tolerance && Abs(a.x11-b.x11) < tolerance) } //----------------------------------------------------------------------------- func (a M44) MulPosition(b V3) V3 { return V3{a.x00*b.X + a.x01*b.Y + a.x02*b.Z + a.x03, a.x10*b.X + a.x11*b.Y + a.x12*b.Z + a.x13, a.x20*b.X + a.x21*b.Y + a.x22*b.Z + a.x23} } func (a M33) MulPosition(b V2) V2 { return V2{a.x00*b.X + a.x01*b.Y + a.x02, a.x10*b.X + a.x11*b.Y + a.x12} } func (a M22) MulPosition(b V2) V2 { return V2{a.x00*b.X + a.x01*b.Y, a.x10*b.X + a.x11*b.Y} } //----------------------------------------------------------------------------- func (v V2Set) MulVertices(a M33) { for i, _ := range v { v[i] = a.MulPosition(v[i]) } } func (v V3Set) MulVertices(a M44) { for i, _ := range v { v[i] = a.MulPosition(v[i]) } } //----------------------------------------------------------------------------- func (a M44) Mul(b M44) M44 { m := M44{} m.x00 = a.x00*b.x00 + a.x01*b.x10 + a.x02*b.x20 + a.x03*b.x30 m.x10 = a.x10*b.x00 + a.x11*b.x10 + a.x12*b.x20 + a.x13*b.x30 m.x20 = a.x20*b.x00 + a.x21*b.x10 + a.x22*b.x20 + a.x23*b.x30 m.x30 = a.x30*b.x00 + a.x31*b.x10 + a.x32*b.x20 + a.x33*b.x30 m.x01 = a.x00*b.x01 + a.x01*b.x11 + a.x02*b.x21 + a.x03*b.x31 m.x11 = a.x10*b.x01 + a.x11*b.x11 + a.x12*b.x21 + a.x13*b.x31 m.x21 = a.x20*b.x01 + a.x21*b.x11 + a.x22*b.x21 + a.x23*b.x31 m.x31 = a.x30*b.x01 + a.x31*b.x11 + a.x32*b.x21 + a.x33*b.x31 m.x02 = a.x00*b.x02 + a.x01*b.x12 + a.x02*b.x22 + a.x03*b.x32 m.x12 = a.x10*b.x02 + a.x11*b.x12 + a.x12*b.x22 + a.x13*b.x32 m.x22 = a.x20*b.x02 + a.x21*b.x12 + a.x22*b.x22 + a.x23*b.x32 m.x32 = a.x30*b.x02 + a.x31*b.x12 + a.x32*b.x22 + a.x33*b.x32 m.x03 = a.x00*b.x03 + a.x01*b.x13 + a.x02*b.x23 + a.x03*b.x33 m.x13 = a.x10*b.x03 + a.x11*b.x13 + a.x12*b.x23 + a.x13*b.x33 m.x23 = a.x20*b.x03 + a.x21*b.x13 + a.x22*b.x23 + a.x23*b.x33 m.x33 = a.x30*b.x03 + a.x31*b.x13 + a.x32*b.x23 + a.x33*b.x33 return m } func (a M33) Mul(b M33) M33 { m := M33{} m.x00 = a.x00*b.x00 + a.x01*b.x10 + a.x02*b.x20 m.x10 = a.x10*b.x00 + a.x11*b.x10 + a.x12*b.x20 m.x20 = a.x20*b.x00 + a.x21*b.x10 + a.x22*b.x20 m.x01 = a.x00*b.x01 + a.x01*b.x11 + a.x02*b.x21 m.x11 = a.x10*b.x01 + a.x11*b.x11 + a.x12*b.x21 m.x21 = a.x20*b.x01 + a.x21*b.x11 + a.x22*b.x21 m.x02 = a.x00*b.x02 + a.x01*b.x12 + a.x02*b.x22 m.x12 = a.x10*b.x02 + a.x11*b.x12 + a.x12*b.x22 m.x22 = a.x20*b.x02 + a.x21*b.x12 + a.x22*b.x22 return m } func (a M22) Mul(b M22) M22 { m := M22{} m.x00 = a.x00*b.x00 + a.x01*b.x10 m.x01 = a.x00*b.x01 + a.x01*b.x11 m.x10 = a.x10*b.x00 + a.x11*b.x10 m.x11 = a.x10*b.x01 + a.x11*b.x11 return m } //----------------------------------------------------------------------------- // Transform bounding boxes - keep them axis aligned // http://dev.theomader.com/transform-bounding-boxes/ func (a M44) MulBox(box Box3) Box3 { r := V3{a.x00, a.x10, a.x20} u := V3{a.x01, a.x11, a.x21} b := V3{a.x02, a.x12, a.x22} t := V3{a.x03, a.x13, a.x23} xa := r.MulScalar(box.Min.X) xb := r.MulScalar(box.Max.X) ya := u.MulScalar(box.Min.Y) yb := u.MulScalar(box.Max.Y) za := b.MulScalar(box.Min.Z) zb := b.MulScalar(box.Max.Z) xa, xb = xa.Min(xb), xa.Max(xb) ya, yb = ya.Min(yb), ya.Max(yb) za, zb = za.Min(zb), za.Max(zb) min := xa.Add(ya).Add(za).Add(t) max := xb.Add(yb).Add(zb).Add(t) return Box3{min, max} } func (a M33) MulBox(box Box2) Box2 { r := V2{a.x00, a.x10} u := V2{a.x01, a.x11} t := V2{a.x02, a.x12} xa := r.MulScalar(box.Min.X) xb := r.MulScalar(box.Max.X) ya := u.MulScalar(box.Min.Y) yb := u.MulScalar(box.Max.Y) xa, xb = xa.Min(xb), xa.Max(xb) ya, yb = ya.Min(yb), ya.Max(yb) min := xa.Add(ya).Add(t) max := xb.Add(yb).Add(t) return Box2{min, max} } //----------------------------------------------------------------------------- func (a M44) Determinant() float64 { return (a.x00*a.x11*a.x22*a.x33 - a.x00*a.x11*a.x23*a.x32 + a.x00*a.x12*a.x23*a.x31 - a.x00*a.x12*a.x21*a.x33 + a.x00*a.x13*a.x21*a.x32 - a.x00*a.x13*a.x22*a.x31 - a.x01*a.x12*a.x23*a.x30 + a.x01*a.x12*a.x20*a.x33 - a.x01*a.x13*a.x20*a.x32 + a.x01*a.x13*a.x22*a.x30 - a.x01*a.x10*a.x22*a.x33 + a.x01*a.x10*a.x23*a.x32 + a.x02*a.x13*a.x20*a.x31 - a.x02*a.x13*a.x21*a.x30 + a.x02*a.x10*a.x21*a.x33 - a.x02*a.x10*a.x23*a.x31 + a.x02*a.x11*a.x23*a.x30 - a.x02*a.x11*a.x20*a.x33 - a.x03*a.x10*a.x21*a.x32 + a.x03*a.x10*a.x22*a.x31 - a.x03*a.x11*a.x22*a.x30 + a.x03*a.x11*a.x20*a.x32 - a.x03*a.x12*a.x20*a.x31 + a.x03*a.x12*a.x21*a.x30) } func (a M33) Determinant() float64 { return (a.x00*(a.x11*a.x22-a.x21*a.x12) - a.x01*(a.x10*a.x22-a.x20*a.x12) + a.x02*(a.x10*a.x21-a.x20*a.x11)) } func (a M22) Determinant() float64 { return a.x00*a.x11 - a.x01*a.x10 } //----------------------------------------------------------------------------- func (a M44) Inverse() M44 { m := M44{} d := 1 / a.Determinant() m.x00 = (a.x12*a.x23*a.x31 - a.x13*a.x22*a.x31 + a.x13*a.x21*a.x32 - a.x11*a.x23*a.x32 - a.x12*a.x21*a.x33 + a.x11*a.x22*a.x33) * d m.x01 = (a.x03*a.x22*a.x31 - a.x02*a.x23*a.x31 - a.x03*a.x21*a.x32 + a.x01*a.x23*a.x32 + a.x02*a.x21*a.x33 - a.x01*a.x22*a.x33) * d m.x02 = (a.x02*a.x13*a.x31 - a.x03*a.x12*a.x31 + a.x03*a.x11*a.x32 - a.x01*a.x13*a.x32 - a.x02*a.x11*a.x33 + a.x01*a.x12*a.x33) * d m.x03 = (a.x03*a.x12*a.x21 - a.x02*a.x13*a.x21 - a.x03*a.x11*a.x22 + a.x01*a.x13*a.x22 + a.x02*a.x11*a.x23 - a.x01*a.x12*a.x23) * d m.x10 = (a.x13*a.x22*a.x30 - a.x12*a.x23*a.x30 - a.x13*a.x20*a.x32 + a.x10*a.x23*a.x32 + a.x12*a.x20*a.x33 - a.x10*a.x22*a.x33) * d m.x11 = (a.x02*a.x23*a.x30 - a.x03*a.x22*a.x30 + a.x03*a.x20*a.x32 - a.x00*a.x23*a.x32 - a.x02*a.x20*a.x33 + a.x00*a.x22*a.x33) * d m.x12 = (a.x03*a.x12*a.x30 - a.x02*a.x13*a.x30 - a.x03*a.x10*a.x32 + a.x00*a.x13*a.x32 + a.x02*a.x10*a.x33 - a.x00*a.x12*a.x33) * d m.x13 = (a.x02*a.x13*a.x20 - a.x03*a.x12*a.x20 + a.x03*a.x10*a.x22 - a.x00*a.x13*a.x22 - a.x02*a.x10*a.x23 + a.x00*a.x12*a.x23) * d m.x20 = (a.x11*a.x23*a.x30 - a.x13*a.x21*a.x30 + a.x13*a.x20*a.x31 - a.x10*a.x23*a.x31 - a.x11*a.x20*a.x33 + a.x10*a.x21*a.x33) * d m.x21 = (a.x03*a.x21*a.x30 - a.x01*a.x23*a.x30 - a.x03*a.x20*a.x31 + a.x00*a.x23*a.x31 + a.x01*a.x20*a.x33 - a.x00*a.x21*a.x33) * d m.x22 = (a.x01*a.x13*a.x30 - a.x03*a.x11*a.x30 + a.x03*a.x10*a.x31 - a.x00*a.x13*a.x31 - a.x01*a.x10*a.x33 + a.x00*a.x11*a.x33) * d m.x23 = (a.x03*a.x11*a.x20 - a.x01*a.x13*a.x20 - a.x03*a.x10*a.x21 + a.x00*a.x13*a.x21 + a.x01*a.x10*a.x23 - a.x00*a.x11*a.x23) * d m.x30 = (a.x12*a.x21*a.x30 - a.x11*a.x22*a.x30 - a.x12*a.x20*a.x31 + a.x10*a.x22*a.x31 + a.x11*a.x20*a.x32 - a.x10*a.x21*a.x32) * d m.x31 = (a.x01*a.x22*a.x30 - a.x02*a.x21*a.x30 + a.x02*a.x20*a.x31 - a.x00*a.x22*a.x31 - a.x01*a.x20*a.x32 + a.x00*a.x21*a.x32) * d m.x32 = (a.x02*a.x11*a.x30 - a.x01*a.x12*a.x30 - a.x02*a.x10*a.x31 + a.x00*a.x12*a.x31 + a.x01*a.x10*a.x32 - a.x00*a.x11*a.x32) * d m.x33 = (a.x01*a.x12*a.x20 - a.x02*a.x11*a.x20 + a.x02*a.x10*a.x21 - a.x00*a.x12*a.x21 - a.x01*a.x10*a.x22 + a.x00*a.x11*a.x22) * d return m } func (a M33) Inverse() M33 { m := M33{} d := 1 / a.Determinant() m.x00 = (a.x11*a.x22 - a.x12*a.x21) * d m.x01 = (a.x21*a.x02 - a.x01*a.x22) * d m.x02 = (a.x01*a.x12 - a.x11*a.x02) * d m.x10 = (a.x12*a.x20 - a.x22*a.x10) * d m.x11 = (a.x22*a.x00 - a.x20*a.x02) * d m.x12 = (a.x02*a.x10 - a.x12*a.x00) * d m.x20 = (a.x10*a.x21 - a.x20*a.x11) * d m.x21 = (a.x20*a.x01 - a.x00*a.x21) * d m.x22 = (a.x00*a.x11 - a.x01*a.x10) * d return m } func (a M22) Inverse() M22 { m := M22{} d := 1 / a.Determinant() m.x00 = a.x11 * d m.x01 = -a.x01 * d m.x10 = -a.x10 * d m.x11 = a.x00 * d return m } //-----------------------------------------------------------------------------
sdf/matrix.go
0.745769
0.603465
matrix.go
starcoder
package gojay import "strconv" // EncodeFloat encodes a float64 to JSON func (enc *Encoder) EncodeFloat(n float64) error { if enc.isPooled == 1 { panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder")) } _, _ = enc.encodeFloat(n) _, err := enc.Write() if err != nil { return err } return nil } // encodeFloat encodes a float64 to JSON func (enc *Encoder) encodeFloat(n float64) ([]byte, error) { enc.buf = strconv.AppendFloat(enc.buf, n, 'f', -1, 64) return enc.buf, nil } // EncodeFloat32 encodes a float32 to JSON func (enc *Encoder) EncodeFloat32(n float32) error { if enc.isPooled == 1 { panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder")) } _, _ = enc.encodeFloat32(n) _, err := enc.Write() if err != nil { return err } return nil } func (enc *Encoder) encodeFloat32(n float32) ([]byte, error) { enc.buf = strconv.AppendFloat(enc.buf, float64(n), 'f', -1, 32) return enc.buf, nil } // AddFloat adds a float64 to be encoded, must be used inside a slice or array encoding (does not encode a key) func (enc *Encoder) AddFloat(v float64) { enc.Float64(v) } // AddFloatOmitEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) AddFloatOmitEmpty(v float64) { enc.Float64OmitEmpty(v) } // AddFloatNullEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) AddFloatNullEmpty(v float64) { enc.Float64NullEmpty(v) } // Float adds a float64 to be encoded, must be used inside a slice or array encoding (does not encode a key) func (enc *Encoder) Float(v float64) { enc.Float64(v) } // FloatOmitEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) FloatOmitEmpty(v float64) { enc.Float64OmitEmpty(v) } // FloatNullEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) FloatNullEmpty(v float64) { enc.Float64NullEmpty(v) } // AddFloatKey adds a float64 to be encoded, must be used inside an object as it will encode a key func (enc *Encoder) AddFloatKey(key string, v float64) { enc.Float64Key(key, v) } // AddFloatKeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) AddFloatKeyOmitEmpty(key string, v float64) { enc.Float64KeyOmitEmpty(key, v) } // AddFloatKeyNullEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) AddFloatKeyNullEmpty(key string, v float64) { enc.Float64KeyNullEmpty(key, v) } // FloatKey adds a float64 to be encoded, must be used inside an object as it will encode a key func (enc *Encoder) FloatKey(key string, v float64) { enc.Float64Key(key, v) } // FloatKeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) FloatKeyOmitEmpty(key string, v float64) { enc.Float64KeyOmitEmpty(key, v) } // FloatKeyNullEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) FloatKeyNullEmpty(key string, v float64) { enc.Float64KeyNullEmpty(key, v) } // AddFloat64 adds a float64 to be encoded, must be used inside a slice or array encoding (does not encode a key) func (enc *Encoder) AddFloat64(v float64) { enc.Float(v) } // AddFloat64OmitEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) AddFloat64OmitEmpty(v float64) { enc.FloatOmitEmpty(v) } // Float64 adds a float64 to be encoded, must be used inside a slice or array encoding (does not encode a key) func (enc *Encoder) Float64(v float64) { enc.grow(10) r := enc.getPreviousRune() if r != '[' { enc.writeByte(',') } enc.buf = strconv.AppendFloat(enc.buf, v, 'f', -1, 64) } // Float64OmitEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) Float64OmitEmpty(v float64) { if v == 0 { return } enc.grow(10) r := enc.getPreviousRune() if r != '[' { enc.writeByte(',') } enc.buf = strconv.AppendFloat(enc.buf, v, 'f', -1, 64) } // Float64NullEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) Float64NullEmpty(v float64) { enc.grow(10) r := enc.getPreviousRune() if r != '[' { enc.writeByte(',') } if v == 0 { enc.writeBytes(nullBytes) return } enc.buf = strconv.AppendFloat(enc.buf, v, 'f', -1, 64) } // AddFloat64Key adds a float64 to be encoded, must be used inside an object as it will encode a key func (enc *Encoder) AddFloat64Key(key string, v float64) { enc.FloatKey(key, v) } // AddFloat64KeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) AddFloat64KeyOmitEmpty(key string, v float64) { enc.FloatKeyOmitEmpty(key, v) } // Float64Key adds a float64 to be encoded, must be used inside an object as it will encode a key func (enc *Encoder) Float64Key(key string, value float64) { r := enc.getPreviousRune() if r != '{' { enc.writeByte(',') } enc.grow(10) enc.writeByte('"') enc.writeStringEscape(key) enc.writeBytes(objKey) enc.buf = strconv.AppendFloat(enc.buf, value, 'f', -1, 64) } // Float64KeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) Float64KeyOmitEmpty(key string, v float64) { if v == 0 { return } enc.grow(10 + len(key)) r := enc.getPreviousRune() if r != '{' { enc.writeByte(',') } enc.writeByte('"') enc.writeStringEscape(key) enc.writeBytes(objKey) enc.buf = strconv.AppendFloat(enc.buf, v, 'f', -1, 64) } // Float64KeyNullEmpty adds a float64 to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) Float64KeyNullEmpty(key string, v float64) { enc.grow(10 + len(key)) r := enc.getPreviousRune() if r != '{' { enc.writeByte(',') } enc.writeByte('"') enc.writeStringEscape(key) enc.writeBytes(objKey) if v == 0 { enc.writeBytes(nullBytes) return } enc.buf = strconv.AppendFloat(enc.buf, v, 'f', -1, 64) } // AddFloat32 adds a float32 to be encoded, must be used inside a slice or array encoding (does not encode a key) func (enc *Encoder) AddFloat32(v float32) { enc.Float32(v) } // AddFloat32OmitEmpty adds an int to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) AddFloat32OmitEmpty(v float32) { enc.Float32OmitEmpty(v) } // AddFloat32NullEmpty adds an int to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) AddFloat32NullEmpty(v float32) { enc.Float32NullEmpty(v) } // Float32 adds a float32 to be encoded, must be used inside a slice or array encoding (does not encode a key) func (enc *Encoder) Float32(v float32) { r := enc.getPreviousRune() if r != '[' { enc.writeByte(',') } enc.buf = strconv.AppendFloat(enc.buf, float64(v), 'f', -1, 32) } // Float32OmitEmpty adds an int to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) Float32OmitEmpty(v float32) { if v == 0 { return } enc.grow(10) r := enc.getPreviousRune() if r != '[' { enc.writeByte(',') } enc.buf = strconv.AppendFloat(enc.buf, float64(v), 'f', -1, 32) } // Float32NullEmpty adds an int to be encoded and skips it if its value is 0, // must be used inside a slice or array encoding (does not encode a key). func (enc *Encoder) Float32NullEmpty(v float32) { enc.grow(10) r := enc.getPreviousRune() if r != '[' { enc.writeByte(',') } if v == 0 { enc.writeBytes(nullBytes) return } enc.buf = strconv.AppendFloat(enc.buf, float64(v), 'f', -1, 32) } // AddFloat32Key adds a float32 to be encoded, must be used inside an object as it will encode a key func (enc *Encoder) AddFloat32Key(key string, v float32) { enc.Float32Key(key, v) } // AddFloat32KeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) AddFloat32KeyOmitEmpty(key string, v float32) { enc.Float32KeyOmitEmpty(key, v) } // AddFloat32KeyNullEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) AddFloat32KeyNullEmpty(key string, v float32) { enc.Float32KeyNullEmpty(key, v) } // Float32Key adds a float32 to be encoded, must be used inside an object as it will encode a key func (enc *Encoder) Float32Key(key string, v float32) { enc.grow(10 + len(key)) r := enc.getPreviousRune() if r != '{' { enc.writeByte(',') } enc.writeByte('"') enc.writeStringEscape(key) enc.writeByte('"') enc.writeByte(':') enc.buf = strconv.AppendFloat(enc.buf, float64(v), 'f', -1, 32) } // Float32KeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) Float32KeyOmitEmpty(key string, v float32) { if v == 0 { return } enc.grow(10 + len(key)) r := enc.getPreviousRune() if r != '{' { enc.writeByte(',') } enc.writeByte('"') enc.writeStringEscape(key) enc.writeBytes(objKey) enc.buf = strconv.AppendFloat(enc.buf, float64(v), 'f', -1, 32) } // Float32KeyNullEmpty adds a float64 to be encoded and skips it if its value is 0. // Must be used inside an object as it will encode a key func (enc *Encoder) Float32KeyNullEmpty(key string, v float32) { enc.grow(10 + len(key)) r := enc.getPreviousRune() if r != '{' { enc.writeByte(',') } enc.writeByte('"') enc.writeStringEscape(key) enc.writeBytes(objKey) if v == 0 { enc.writeBytes(nullBytes) return } enc.buf = strconv.AppendFloat(enc.buf, float64(v), 'f', -1, 32) }
encode_number_float.go
0.869035
0.45944
encode_number_float.go
starcoder
package fitter import "strings" type sequenceKind int const ( plainSequenceKind = iota controlSequenceKind ) type sequence struct { data string kind sequenceKind } func newSequence(data string) *sequence { s := &sequence{} s.data = data s.kind = plainSequenceKind return s } func (s *sequence) Append(data string) { s.data += data } func (s *sequence) SetKind(kind sequenceKind) { s.kind = kind } func (s *sequence) String() string { return s.data } func (s *sequence) TWidth() int { if s.kind == controlSequenceKind { if s.data == "\b" { return -1 } return 0 } return len([]rune(s.data)) } func (s *sequence) Slice(maxTWidth int) (string, int) { var result string var rest int difference := maxTWidth - s.TWidth() if difference <= 0 { result = s.data[:maxTWidth] s.data = s.data[maxTWidth:] rest = 0 } else { result = s.data s.data = "" rest = difference } return result, rest } func (s *sequence) IsEmpty() bool { return len(s.data) == 0 } type sequenceStack struct { sequences []*sequence } func newSequenceStack() sequenceStack { return sequenceStack{} } func (ss *sequenceStack) String() string { var result string for _, s := range ss.sequences { result += s.String() } return result } func (ss *sequenceStack) TWidth() int { var result int for _, s := range ss.sequences { result += s.TWidth() } return result } func (ss *sequenceStack) CommitTopSequenceAsPlain() { ss.CommitTopSequence(plainSequenceKind) } func (ss *sequenceStack) CommitTopSequenceAsControl() { ss.CommitTopSequence(controlSequenceKind) } func (ss *sequenceStack) CommitTopSequence(kind sequenceKind) { ss.commitTopSequence(kind) _ = ss.NewSequence("") } func (ss *sequenceStack) commitTopSequence(kind sequenceKind) { ss.TopSequence().SetKind(kind) } func (ss *sequenceStack) NewSequence(data string) *sequence { topSequence := newSequence(data) ss.sequences = append(ss.sequences, topSequence) return topSequence } func (ss *sequenceStack) WritePlainData(data string) { ss.WriteData(data) ss.CommitTopSequenceAsPlain() } func (ss *sequenceStack) WriteControlData(data string) { ss.WriteData(data) ss.CommitTopSequenceAsControl() } func (ss *sequenceStack) WriteData(data string) { if len(ss.sequences) == 0 || ss.TopSequence().IsEmpty() { ss.NewSequence(data) } else { ss.TopSequence().Append(data) } } func (ss *sequenceStack) DivideLastSign() { if len(ss.sequences) == 0 { panic("empty sequence stack") } data := ss.TopSequence().data if len(data) == 0 { panic("empty top sequence") } sign := data[len(data)-1] ss.TopSequence().data = data[:len(data)-1] ss.CommitTopSequenceAsPlain() ss.WriteData(string(sign)) } func (ss *sequenceStack) Merge(ss2 sequenceStack) { if !ss.IsEmpty() { ss.commitTopSequence(plainSequenceKind) } if !ss2.IsEmpty() { ss2.commitTopSequence(plainSequenceKind) } ss.sequences = append(ss.sequences, ss2.sequences...) ss.NewSequence("") } func (ss *sequenceStack) TopSequence() *sequence { if ss.IsEmpty() { return ss.NewSequence("") } return ss.sequences[len(ss.sequences)-1] } func (ss *sequenceStack) IsEmpty() bool { return len(ss.sequences) == 0 } func (ss *sequenceStack) Slice(sliceTWidth int) (string, int) { var result string var newSequences []*sequence rest := sliceTWidth for ind, s := range ss.sequences { if s.TWidth() == 0 { result += s.String() continue } if rest == 0 { newSequences = append(newSequences, ss.sequences[ind:]...) break } else { if s.TWidth() > rest && s.TWidth() <= sliceTWidth { newSequences = append(newSequences, ss.sequences[ind:]...) break } var part string part, rest = s.Slice(rest) result += part if !s.IsEmpty() { newSequences = append(newSequences, ss.sequences[ind:]...) break } } } ss.sequences = newSequences if len(ss.sequences) == 0 { ss.NewSequence("") } return result, rest } func (ss *sequenceStack) Slices(sliceTWidth int) ([]string, int) { var result []string if ss.IsEmpty() { return result, sliceTWidth } for { slice, rest := ss.Slice(sliceTWidth) if ss.TWidth() == 0 { result = append(result, slice) return result, rest } else { result = append(result, slice+strings.Repeat(" ", rest)) } } }
internal/stream/fitter/sequence.go
0.657648
0.423995
sequence.go
starcoder
package assertions import ( "fmt" "reflect" ) // ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality. func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } first := reflect.TypeOf(actual) second := reflect.TypeOf(expected[0]) if equal := ShouldEqual(first, second); equal != success { return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first)) } return success } // ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality. func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } first := reflect.TypeOf(actual) second := reflect.TypeOf(expected[0]) if equal := ShouldEqual(first, second); equal == success { return fmt.Sprintf(shouldNotHaveBeenA, actual, second) } return success } // ShouldImplement receives exactly two parameters and ensures // that the first implements the interface type of the second. func ShouldImplement(actual interface{}, expectedList ...interface{}) string { if fail := need(1, expectedList); fail != success { return fail } expected := expectedList[0] if fail := ShouldBeNil(expected); fail != success { return shouldCompareWithInterfacePointer } expectedType := reflect.TypeOf(expected) if fail := ShouldNotBeNil(expectedType); fail != success { return shouldCompareWithInterfacePointer } expectedInterface := expectedType.Elem() actualType := reflect.TypeOf(actual) if actualType == nil { return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual) } if fail := ShouldEqual(actualType.Kind(), reflect.Ptr); fail != success { return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual) } if !actualType.Implements(expectedInterface) { return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType) } return success } // ShouldNotImplement receives exactly two parameters and ensures // that the first does NOT implement the interface type of the second. func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string { if fail := need(1, expectedList); fail != success { return fail } expected := expectedList[0] if fail := ShouldBeNil(expected); fail != success { return shouldCompareWithInterfacePointer } expectedType := reflect.TypeOf(expected) if fail := ShouldNotBeNil(expectedType); fail != success { return shouldCompareWithInterfacePointer } expectedInterface := expectedType.Elem() actualType := reflect.TypeOf(actual) if actualType == nil { return success } if actualType.Implements(expectedInterface) { return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface) } return success }
Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions/type.go
0.794903
0.556821
type.go
starcoder
package influxql import ( "net/http" "github.com/influxdata/flux" ) const DialectType = "influxql" // AddDialectMappings adds the influxql specific dialect mappings. func AddDialectMappings(mappings flux.DialectMappings) error { return mappings.Add(DialectType, func() flux.Dialect { return new(Dialect) }) } // Dialect describes the output format of InfluxQL queries. type Dialect struct { TimeFormat TimeFormat // TimeFormat is the format of the timestamp; defaults to RFC3339Nano. Encoding EncodingFormat // Encoding is the format of the results; defaults to JSON. ChunkSize int // Chunks is the number of points per chunk encoding batch; defaults to 0 or no chunking. Compression CompressionFormat // Compression is the compression of the result output; defaults to None. } func (d *Dialect) SetHeaders(w http.ResponseWriter) { switch d.Encoding { case JSON, JSONPretty: w.Header().Set("Content-Type", "application/json") case CSV: w.Header().Set("Content-Type", "text/csv") case Msgpack: w.Header().Set("Content-Type", "application/x-msgpack") } } func (d *Dialect) Encoder() flux.MultiResultEncoder { switch d.Encoding { case JSON, JSONPretty: return new(MultiResultEncoder) default: panic("not implemented") } } func (d *Dialect) DialectType() flux.DialectType { return DialectType } // TimeFormat specifies the format of the timestamp in the query results. type TimeFormat int const ( // RFC3339Nano is the default format for timestamps for InfluxQL. RFC3339Nano TimeFormat = iota // Hour formats time as the number of hours in the unix epoch. Hour // Minute formats time as the number of minutes in the unix epoch. Minute // Second formats time as the number of seconds in the unix epoch. Second // Millisecond formats time as the number of milliseconds in the unix epoch. Millisecond // Microsecond formats time as the number of microseconds in the unix epoch. Microsecond // Nanosecond formats time as the number of nanoseconds in the unix epoch. Nanosecond ) // CompressionFormat is the format to compress the query results. type CompressionFormat int const ( // None does not compress the results and is the default. None CompressionFormat = iota // Gzip compresses the query results with gzip. Gzip ) // EncodingFormat is the output format for the query response content. type EncodingFormat int const ( // JSON marshals the response to JSON octets. JSON EncodingFormat = iota // JSONPretty marshals the response to JSON octets with idents. JSONPretty // CSV marshals the response to CSV. CSV // Msgpack has a similar structure as the JSON response. Used? Msgpack )
query/influxql/dialect.go
0.780913
0.534127
dialect.go
starcoder
package cmd import ( "time" ) //go:generate msgp -file $GOFILE // ReplicationLatency holds information of bucket operations latency, such us uploads type ReplicationLatency struct { // Single & Multipart PUTs latency UploadHistogram LastMinuteLatencies } // Merge two replication latency into a new one func (rl ReplicationLatency) merge(other ReplicationLatency) (newReplLatency ReplicationLatency) { newReplLatency.UploadHistogram = rl.UploadHistogram.Merge(other.UploadHistogram) return } // Get upload latency of each object size range func (rl ReplicationLatency) getUploadLatency() (ret map[string]uint64) { ret = make(map[string]uint64) avg := rl.UploadHistogram.GetAvgData() for k, v := range avg { // Convert nanoseconds to milliseconds ret[sizeTagToString(k)] = v.avg() / uint64(time.Millisecond) } return } // Update replication upload latency with a new value func (rl *ReplicationLatency) update(size int64, duration time.Duration) { rl.UploadHistogram.Add(size, duration) } // BucketStats bucket statistics type BucketStats struct { ReplicationStats BucketReplicationStats } // BucketReplicationStats represents inline replication statistics // such as pending, failed and completed bytes in total for a bucket type BucketReplicationStats struct { Stats map[string]*BucketReplicationStat // Pending size in bytes PendingSize int64 `json:"pendingReplicationSize"` // Completed size in bytes ReplicatedSize int64 `json:"completedReplicationSize"` // Total Replica size in bytes ReplicaSize int64 `json:"replicaSize"` // Failed size in bytes FailedSize int64 `json:"failedReplicationSize"` // Total number of pending operations including metadata updates PendingCount int64 `json:"pendingReplicationCount"` // Total number of failed operations including metadata updates FailedCount int64 `json:"failedReplicationCount"` } // Empty returns true if there are no target stats func (brs *BucketReplicationStats) Empty() bool { return len(brs.Stats) == 0 && brs.ReplicaSize == 0 } // Clone creates a new BucketReplicationStats copy func (brs BucketReplicationStats) Clone() (c BucketReplicationStats) { // This is called only by replicationStats cache and already holds a // read lock before calling Clone() c = brs // We need to copy the map, so we do not reference the one in `brs`. c.Stats = make(map[string]*BucketReplicationStat, len(brs.Stats)) for arn, st := range brs.Stats { // make a copy of `*st` s := *st c.Stats[arn] = &s } return c } // BucketReplicationStat represents inline replication statistics // such as pending, failed and completed bytes in total for a bucket // remote target type BucketReplicationStat struct { // Pending size in bytes PendingSize int64 `json:"pendingReplicationSize"` // Completed size in bytes ReplicatedSize int64 `json:"completedReplicationSize"` // Total Replica size in bytes ReplicaSize int64 `json:"replicaSize"` // Failed size in bytes FailedSize int64 `json:"failedReplicationSize"` // Total number of pending operations including metadata updates PendingCount int64 `json:"pendingReplicationCount"` // Total number of failed operations including metadata updates FailedCount int64 `json:"failedReplicationCount"` // Replication latency information Latency ReplicationLatency `json:"replicationLatency"` } func (bs *BucketReplicationStat) hasReplicationUsage() bool { return bs.FailedSize > 0 || bs.ReplicatedSize > 0 || bs.ReplicaSize > 0 || bs.FailedCount > 0 || bs.PendingCount > 0 || bs.PendingSize > 0 }
cmd/bucket-stats.go
0.637257
0.429968
bucket-stats.go
starcoder
package ssm import ( "errors" "fmt" ) // State represents a single state of the system. type State struct { // Name is the name of the state, give it something meaningful Name string } // Trigger is a trigger that can move from one state to another. type Trigger struct { // Key is a unique key for the trigger Key string } // String returns a useful debug string for the trigger. func (t Trigger) String() string { return fmt.Sprintf(t.Key) } // StateMachine is a simple state machine that allows a caller to specify states, triggers // and edges between states via triggers. See the examples and test files for more examples. type StateMachine struct { current *StateConfig stateToConfig map[State]*StateConfig } // NewStateMachine returns an initialized StateMachine instance. func NewStateMachine(initial State) *StateMachine { sm := &StateMachine{ stateToConfig: make(map[State]*StateConfig), } cfg := sm.registerStateConfig(initial) sm.current = cfg return sm } // Configure is used to configure a state, such as setting OnEnter/OnExit // handlers, defining valid triggers etc. func (sm *StateMachine) Configure(s State) *StateConfig { return sm.registerStateConfig(s) } // State returns the current state of the state machine. func (sm *StateMachine) State() State { return sm.current.state } // Fire fires the specified trigger. If the trigger is not valid for the current // state an error is returned. func (sm *StateMachine) Fire(triggerKey string, ctx interface{}) error { if !sm.CanFire(triggerKey) { return errors.New("unsupported trigger") } edge := sm.current.permitted[triggerKey] // If the state we are transitioning to is not a substate of the current // state then fire all of the exit handlers up the chain targetParent := sm.stateToConfig[edge.state].parent if targetParent == nil || (targetParent.state != sm.current.state) { current := sm.current for current != nil { if current.onExit != nil { current.onExit() } current = current.parent } } sm.current = sm.stateToConfig[edge.state] enterFrom, ok := sm.current.onEnterFrom[edge.trigger] if ok { enterFrom(ctx) } if sm.current.onEnter != nil { sm.current.onEnter() } return nil } // CanFire returns true if the specified trigger is valid for the State Machines // current state. func (sm *StateMachine) CanFire(triggerKey string) bool { next, ok := sm.current.permitted[triggerKey] if !ok { return false } // If the transtion is guarded, loop to see if we can find a predicate that // returns true, indicating this is a valid transition at this time if len(next.preds) > 0 { found := false for _, pred := range next.preds { found = pred() if found { break } } if !found { return false } } return true } // IsInState returns true if the current state matches the specified state. It will // also return true if the current state is a substate of the specified state. func (sm *StateMachine) IsInState(s State) bool { current := sm.current for current != nil { if current.state == s { return true } current = current.parent } return false } // GoToState sets the current state to a new one and optionally trigger the onEnter function func (sm *StateMachine) GoToState(s State, triggerOnEnter bool) error { cfg, ok := sm.stateToConfig[s] if !ok { return errors.New("state does not exist") } sm.current = cfg if triggerOnEnter && sm.current.onEnter != nil { sm.current.onEnter() } return nil } // GetNextStates lists the next available states starting from current state. func (sm *StateMachine) GetNextStates() []State { nextStates := []State{} for _, edge := range sm.current.permitted { nextStates = append(nextStates, edge.state) } return nextStates } // GetNextTriggers lists the next available triggers starting from current state. func (sm *StateMachine) GetNextTriggers() []Trigger { nextTriggers := []Trigger{} for _, edge := range sm.current.permitted { nextTriggers = append(nextTriggers, edge.trigger) } return nextTriggers } // registerStateConfig registers the state with a blank configuration. func (sm *StateMachine) registerStateConfig(s State) *StateConfig { cfg, ok := sm.stateToConfig[s] if !ok { cfg = NewStateConfig(sm, s) sm.stateToConfig[s] = cfg } return cfg }
state_machine.go
0.753285
0.420243
state_machine.go
starcoder
package box2d import ( "math" ) // Compute contact points for edge versus circle. // This accounts for edge connectivity. func B2CollideEdgeAndCircle(manifold *B2Manifold, edgeA *B2EdgeShape, xfA B2Transform, circleB *B2CircleShape, xfB B2Transform) { manifold.PointCount = 0 // Compute circle in frame of edge Q := B2TransformVec2MulT(xfA, B2TransformVec2Mul(xfB, circleB.M_p)) A := edgeA.M_vertex1 B := edgeA.M_vertex2 e := B2Vec2Sub(B, A) // Normal points to the right for a CCW winding n := MakeB2Vec2(e.Y, -e.X) offset := B2Vec2Dot(n, B2Vec2Sub(Q, A)) oneSided := edgeA.M_oneSided if oneSided && offset < 0.0 { return } // Barycentric coordinates u := B2Vec2Dot(e, B2Vec2Sub(B, Q)) v := B2Vec2Dot(e, B2Vec2Sub(Q, A)) radius := edgeA.M_radius + circleB.M_radius cf := MakeB2ContactFeature() cf.IndexB = 0 cf.TypeB = B2ContactFeature_Type.E_vertex // Region A if v <= 0.0 { P := A d := B2Vec2Sub(Q, P) dd := B2Vec2Dot(d, d) if dd > radius*radius { return } // Is there an edge connected to A? if edgeA.M_oneSided { A1 := edgeA.M_vertex0 B1 := A e1 := B2Vec2Sub(B1, A1) u1 := B2Vec2Dot(e1, B2Vec2Sub(B1, Q)) // Is the circle in Region AB of the previous edge? if u1 > 0.0 { return } } cf.IndexA = 0 cf.TypeA = B2ContactFeature_Type.E_vertex manifold.PointCount = 1 manifold.Type = B2Manifold_Type.E_circles manifold.LocalNormal.SetZero() manifold.LocalPoint = P manifold.Points[0].Id.SetKey(0) manifold.Points[0].Id.IndexA = cf.IndexA manifold.Points[0].Id.IndexB = cf.IndexB manifold.Points[0].Id.TypeA = cf.TypeA manifold.Points[0].Id.TypeB = cf.TypeB manifold.Points[0].LocalPoint = circleB.M_p return } // Region B if u <= 0.0 { P := B d := B2Vec2Sub(Q, P) dd := B2Vec2Dot(d, d) if dd > radius*radius { return } // Is there an edge connected to B? if edgeA.M_oneSided { B2 := edgeA.M_vertex3 A2 := B e2 := B2Vec2Sub(B2, A2) v2 := B2Vec2Dot(e2, B2Vec2Sub(Q, A2)) // Is the circle in Region AB of the next edge? if v2 > 0.0 { return } } cf.IndexA = 1 cf.TypeA = B2ContactFeature_Type.E_vertex manifold.PointCount = 1 manifold.Type = B2Manifold_Type.E_circles manifold.LocalNormal.SetZero() manifold.LocalPoint = P manifold.Points[0].Id.SetKey(0) manifold.Points[0].Id.IndexA = cf.IndexA manifold.Points[0].Id.IndexB = cf.IndexB manifold.Points[0].Id.TypeA = cf.TypeA manifold.Points[0].Id.TypeB = cf.TypeB manifold.Points[0].LocalPoint = circleB.M_p return } // Region AB den := B2Vec2Dot(e, e) B2Assert(den > 0.0) P := B2Vec2MulScalar(1.0/den, B2Vec2Add(B2Vec2MulScalar(u, A), B2Vec2MulScalar(v, B))) d := B2Vec2Sub(Q, P) dd := B2Vec2Dot(d, d) if dd > radius*radius { return } if offset < 0.0 { n.Set(-n.X, -n.Y) } n.Normalize() cf.IndexA = 0 cf.TypeA = B2ContactFeature_Type.E_face manifold.PointCount = 1 manifold.Type = B2Manifold_Type.E_faceA manifold.LocalNormal = n manifold.LocalPoint = A manifold.Points[0].Id.SetKey(0) manifold.Points[0].Id.IndexA = cf.IndexA manifold.Points[0].Id.IndexB = cf.IndexB manifold.Points[0].Id.TypeA = cf.TypeA manifold.Points[0].Id.TypeB = cf.TypeB manifold.Points[0].LocalPoint = circleB.M_p } // This structure is used to keep track of the best separating axis. var B2EPAxis_Type = struct { E_unknown uint8 E_edgeA uint8 E_edgeB uint8 }{ E_unknown: 0, E_edgeA: 1, E_edgeB: 2, } type B2EPAxis struct { Normal B2Vec2 Type uint8 Index int Separation float64 } func MakeB2EPAxis() B2EPAxis { return B2EPAxis{} } // This holds polygon B expressed in frame A. type B2TempPolygon struct { Vertices [B2_maxPolygonVertices]B2Vec2 Normals [B2_maxPolygonVertices]B2Vec2 Count int } // Reference face used for clipping type B2ReferenceFace struct { I1, I2 int V1, V2 B2Vec2 Normal B2Vec2 SideNormal1 B2Vec2 SideOffset1 float64 SideNormal2 B2Vec2 SideOffset2 float64 } func MakeB2ReferenceFace() B2ReferenceFace { return B2ReferenceFace{} } func B2ComputeEdgeSeparation(polygonB B2TempPolygon, v1 B2Vec2, normal1 B2Vec2) B2EPAxis { axis := MakeB2EPAxis() axis.Type = B2EPAxis_Type.E_edgeA axis.Index = -1 axis.Separation = -B2_maxFloat axis.Normal.SetZero() var axes [2]B2Vec2 = [2]B2Vec2{normal1, normal1.OperatorNegate()} // Find axis with least overlap (min-max problem) for j := 0; j < 2; j++ { sj := B2_maxFloat // Find deepest polygon vertex along axis j for i := 0; i < polygonB.Count; i++ { si := B2Vec2Dot(axes[j], B2Vec2Sub(polygonB.Vertices[i], v1)) if si < sj { sj = si } } if sj > axis.Separation { axis.Index = j axis.Separation = sj axis.Normal = axes[j] } } return axis } func B2ComputePolygonSeparation(polygonB B2TempPolygon, v1 B2Vec2, v2 B2Vec2) B2EPAxis { axis := MakeB2EPAxis() axis.Type = B2EPAxis_Type.E_unknown axis.Index = -1 axis.Separation = -B2_maxFloat axis.Normal.SetZero() for i := 0; i < polygonB.Count; i++ { n := polygonB.Normals[i].OperatorNegate() s1 := B2Vec2Dot(n, B2Vec2Sub(polygonB.Vertices[i], v1)) s2 := B2Vec2Dot(n, B2Vec2Sub(polygonB.Vertices[i], v2)) s := math.Min(s1, s2) if s > axis.Separation { axis.Type = B2EPAxis_Type.E_edgeB axis.Index = i axis.Separation = s axis.Normal = n } } return axis } /// Compute the collision manifold between an edge and a polygon. func B2CollideEdgeAndPolygon(manifold *B2Manifold, edgeA *B2EdgeShape, xfA B2Transform, polygonB *B2PolygonShape, xfB B2Transform) { manifold.PointCount = 0 xf := B2TransformMulT(xfA, xfB) centroidB := B2TransformVec2Mul(xf, polygonB.M_centroid) v1 := edgeA.M_vertex1 v2 := edgeA.M_vertex2 edge1 := B2Vec2Sub(v2, v1) edge1.Normalize() // Normal points to the right for a CCW winding normal1 := MakeB2Vec2(edge1.Y, -edge1.X) offset1 := B2Vec2Dot(normal1, B2Vec2Sub(centroidB, v1)) oneSided := edgeA.M_oneSided if oneSided && offset1 < 0.0 { return } // Get polygonB in frameA var tempPolygonB B2TempPolygon tempPolygonB.Count = polygonB.M_count for i := 0; i < polygonB.M_count; i++ { tempPolygonB.Vertices[i] = B2TransformVec2Mul(xf, polygonB.M_vertices[i]) tempPolygonB.Normals[i] = B2RotVec2Mul(xf.Q, polygonB.M_normals[i]) } radius := polygonB.M_radius + edgeA.M_radius edgeAxis := B2ComputeEdgeSeparation(tempPolygonB, v1, normal1) if edgeAxis.Separation > radius { return } polygonAxis := B2ComputePolygonSeparation(tempPolygonB, v1, v2) if polygonAxis.Separation > radius { return } // Use hysteresis for jitter reduction. k_relativeTol := 0.98 k_absoluteTol := 0.001 primaryAxis := MakeB2EPAxis() if polygonAxis.Separation-radius > k_relativeTol*(edgeAxis.Separation-radius)+k_absoluteTol { primaryAxis = polygonAxis } else { primaryAxis = edgeAxis } if oneSided { // Smooth collision // See https://box2d.org/posts/2020/06/ghost-collisions/ edge0 := B2Vec2Sub(v1, edgeA.M_vertex0) edge0.Normalize() normal0 := MakeB2Vec2(edge0.Y, -edge0.X) convex1 := B2Vec2Cross(edge0, edge1) >= 0.0 edge2 := B2Vec2Sub(edgeA.M_vertex3, v2) edge2.Normalize() normal2 := MakeB2Vec2(edge2.Y, -edge2.X) convex2 := B2Vec2Cross(edge1, edge2) >= 0.0 sinTol := 0.1 side1 := B2Vec2Dot(primaryAxis.Normal, edge1) <= 0.0 // Check Gauss Map if side1 { if convex1 { if B2Vec2Cross(primaryAxis.Normal, normal0) > sinTol { // Skip region return } // Admit region } else { // Snap region primaryAxis = edgeAxis } } else { if convex2 { if B2Vec2Cross(normal2, primaryAxis.Normal) > sinTol { // Skip region return } // Admit region } else { // Snap region primaryAxis = edgeAxis } } } clipPoints := make([]B2ClipVertex, 2) ref := MakeB2ReferenceFace() if primaryAxis.Type == B2EPAxis_Type.E_edgeA { manifold.Type = B2Manifold_Type.E_faceA // Search for the polygon normal that is most anti-parallel to the edge normal. bestIndex := 0 bestValue := B2Vec2Dot(primaryAxis.Normal, tempPolygonB.Normals[0]) for i := 1; i < tempPolygonB.Count; i++ { value := B2Vec2Dot(primaryAxis.Normal, tempPolygonB.Normals[i]) if value < bestValue { bestValue = value bestIndex = i } } i1 := bestIndex i2 := 0 if i1+1 < tempPolygonB.Count { i2 = i1 + 1 } clipPoints[0].V = tempPolygonB.Vertices[i1] clipPoints[0].Id.IndexA = 0 clipPoints[0].Id.IndexB = uint8(i1) clipPoints[0].Id.TypeA = B2ContactFeature_Type.E_face clipPoints[0].Id.TypeB = B2ContactFeature_Type.E_vertex clipPoints[1].V = tempPolygonB.Vertices[i2] clipPoints[1].Id.IndexA = 0 clipPoints[1].Id.IndexB = uint8(i2) clipPoints[1].Id.TypeA = B2ContactFeature_Type.E_face clipPoints[1].Id.TypeB = B2ContactFeature_Type.E_vertex ref.I1 = 0 ref.I2 = 1 ref.V1 = v1 ref.V2 = v2 ref.Normal = primaryAxis.Normal ref.SideNormal1 = edge1.OperatorNegate() ref.SideNormal2 = edge1 } else { manifold.Type = B2Manifold_Type.E_faceB clipPoints[0].V = v2 clipPoints[0].Id.IndexA = 1 clipPoints[0].Id.IndexB = uint8(primaryAxis.Index) clipPoints[0].Id.TypeA = B2ContactFeature_Type.E_vertex clipPoints[0].Id.TypeB = B2ContactFeature_Type.E_face clipPoints[1].V = v1 clipPoints[1].Id.IndexA = 0 clipPoints[1].Id.IndexB = uint8(primaryAxis.Index) clipPoints[1].Id.TypeA = B2ContactFeature_Type.E_vertex clipPoints[1].Id.TypeB = B2ContactFeature_Type.E_face ref.I1 = primaryAxis.Index ref.I2 = 0 if ref.I1+1 < tempPolygonB.Count { ref.I2 = ref.I1 + 1 } ref.V1 = tempPolygonB.Vertices[ref.I1] ref.V2 = tempPolygonB.Vertices[ref.I2] ref.Normal = tempPolygonB.Normals[ref.I1] // CCW winding ref.SideNormal1.Set(ref.Normal.Y, -ref.Normal.X) ref.SideNormal2 = ref.SideNormal1.OperatorNegate() } ref.SideOffset1 = B2Vec2Dot(ref.SideNormal1, ref.V1) ref.SideOffset2 = B2Vec2Dot(ref.SideNormal2, ref.V2) // Clip incident edge against reference face side planes clipPoints1 := make([]B2ClipVertex, 2) clipPoints2 := make([]B2ClipVertex, 2) np := 0 // Clip to side 1 np = B2ClipSegmentToLine(clipPoints1, clipPoints, ref.SideNormal1, ref.SideOffset1, ref.I1) if np < B2_maxManifoldPoints { return } // Clip to side 2 np = B2ClipSegmentToLine(clipPoints2, clipPoints1, ref.SideNormal2, ref.SideOffset2, ref.I2) if np < B2_maxManifoldPoints { return } // Now clipPoints2 contains the clipped points. if primaryAxis.Type == B2EPAxis_Type.E_edgeA { manifold.LocalNormal = ref.Normal manifold.LocalPoint = ref.V1 } else { manifold.LocalNormal = polygonB.M_normals[ref.I1] manifold.LocalPoint = polygonB.M_vertices[ref.I1] } pointCount := 0 for i := 0; i < B2_maxManifoldPoints; i++ { separation := 0.0 separation = B2Vec2Dot(ref.Normal, B2Vec2Sub(clipPoints2[i].V, ref.V1)) if separation <= radius { cp := &manifold.Points[pointCount] if primaryAxis.Type == B2EPAxis_Type.E_edgeA { cp.LocalPoint = B2TransformVec2MulT(xf, clipPoints2[i].V) cp.Id = clipPoints2[i].Id } else { cp.LocalPoint = clipPoints2[i].V cp.Id.TypeA = clipPoints2[i].Id.TypeB cp.Id.TypeB = clipPoints2[i].Id.TypeA cp.Id.IndexA = clipPoints2[i].Id.IndexB cp.Id.IndexB = clipPoints2[i].Id.IndexA } pointCount++ } } manifold.PointCount = pointCount }
CollisionB2CollideEdge.go
0.804905
0.691654
CollisionB2CollideEdge.go
starcoder
package cluster import ( "errors" "math" ) // UpdateNN calculates the row/column to add to a distance matrix for a new node. // Methods supported: average, complete, mcquitty or ward. func UpdateNN(method string) (updateFunc func(matrix [][]float64, a, b int, nodeSize []int) (newRow []float64), err error) { if method == "average" { average := func(matrix [][]float64, a, b int, nodeSize []int) (newRow []float64) { x := matrix[a] y := matrix[b] dim := len(x) newRow = make([]float64, dim+1) for i := 0; i < dim; i++ { numerator := (float64(nodeSize[a]) * x[i]) + (float64(nodeSize[b]) * y[i]) denominator := float64(nodeSize[a] + nodeSize[b]) newRow[i] = numerator / denominator } // Set self distance to zero. newRow[dim] = 0 return } return average, nil } else if method == "complete" { complete := func(matrix [][]float64, a, b int, nodeSize []int) (newRow []float64) { x := matrix[a] y := matrix[b] dim := len(x) newRow = make([]float64, dim+1) for i := 0; i < dim; i++ { newRow[i] = math.Max(x[i], y[i]) } // Set self distance to zero. newRow[dim] = 0 return } return complete, nil } else if method == "mcquitty" { mcquitty := func(matrix [][]float64, a, b int, nodeSize []int) (newRow []float64) { x := matrix[a] y := matrix[b] dim := len(x) newRow = make([]float64, dim+1) for i := 0; i < dim; i++ { newRow[i] = (x[i] + y[i]) / float64(2) } // Set self distance to zero. newRow[dim] = 0 return } return mcquitty, nil } else if method == "ward" { ward := func(matrix [][]float64, a, b int, nodeSize []int) (newRow []float64) { x := matrix[a] y := matrix[b] dim := len(x) newRow = make([]float64, dim+1) for i := 0; i < dim; i++ { numerator := float64(nodeSize[a]+nodeSize[i]) * x[i] numerator += float64(nodeSize[b]+nodeSize[i]) * y[i] numerator -= float64(nodeSize[i]) * x[b] denominator := float64(nodeSize[a] + nodeSize[b] + nodeSize[i]) newRow[i] = numerator / denominator } // Set self distance to zero. newRow[dim] = 0 return } return ward, nil } err = errors.New("Unknown linkage method") return }
cluster/updatenn.go
0.626924
0.511534
updatenn.go
starcoder
package java const numConstTpl = `{{ $f := .Field }}{{ $r := .Rules -}} {{- if $r.Const }} private final {{ javaTypeFor .}} {{ constantName . "Const" }} = {{ $r.GetConst }}{{ javaTypeLiteralSuffixFor . }}; {{- end -}} {{- if $r.Lt }} private final {{ javaTypeFor .}} {{ constantName . "Lt" }} = {{ $r.GetLt }}{{ javaTypeLiteralSuffixFor . }}; {{- end -}} {{- if $r.Lte }} private final {{ javaTypeFor .}} {{ constantName . "Lte" }} = {{ $r.GetLte }}{{ javaTypeLiteralSuffixFor . }}; {{- end -}} {{- if $r.Gt }} private final {{ javaTypeFor .}} {{ constantName . "Gt" }} = {{ $r.GetGt }}{{ javaTypeLiteralSuffixFor . }}; {{- end -}} {{- if $r.Gte }} private final {{ javaTypeFor .}} {{ constantName . "Gte" }} = {{ $r.GetGte }}{{ javaTypeLiteralSuffixFor . }}; {{- end -}} {{- if $r.In }} private final {{ javaTypeFor . }}[] {{ constantName . "In" }} = new {{ javaTypeFor . }}[]{ {{- range $r.In -}} {{- sprintf "%v" . -}}{{ javaTypeLiteralSuffixFor $ }}, {{- end -}} }; {{- end -}} {{- if $r.NotIn }} private final {{ javaTypeFor . }}[] {{ constantName . "NotIn" }} = new {{ javaTypeFor . }}[]{ {{- range $r.NotIn -}} {{- sprintf "%v" . -}}{{ javaTypeLiteralSuffixFor $ }}, {{- end -}} }; {{- end -}}` const numTpl = `{{ $f := .Field }}{{ $r := .Rules -}} {{- if $r.GetIgnoreEmpty }} if ( {{ accessor . }} != 0 ) { {{- end -}} {{- if $r.Const }} io.envoyproxy.pgv.ConstantValidation.constant("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "Const" }}); {{- end -}} {{- if and (or $r.Lt $r.Lte) (or $r.Gt $r.Gte)}} io.envoyproxy.pgv.ComparativeValidation.range("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ if $r.Lt }}{{ constantName . "Lt" }}{{ else }}null{{ end }}, {{ if $r.Lte }}{{ constantName . "Lte" }}{{ else }}null{{ end }}, {{ if $r.Gt }}{{ constantName . "Gt" }}{{ else }}null{{ end }}, {{ if $r.Gte }}{{ constantName . "Gte" }}{{ else }}null{{ end }}, java.util.Comparator.naturalOrder()); {{- else -}} {{- if $r.Lt }} io.envoyproxy.pgv.ComparativeValidation.lessThan("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "Lt" }}, java.util.Comparator.naturalOrder()); {{- end -}} {{- if $r.Lte }} io.envoyproxy.pgv.ComparativeValidation.lessThanOrEqual("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "Lte" }}, java.util.Comparator.naturalOrder()); {{- end -}} {{- if $r.Gt }} io.envoyproxy.pgv.ComparativeValidation.greaterThan("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "Gt" }}, java.util.Comparator.naturalOrder()); {{- end -}} {{- if $r.Gte }} io.envoyproxy.pgv.ComparativeValidation.greaterThanOrEqual("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "Gte" }}, java.util.Comparator.naturalOrder()); {{- end -}} {{- end -}} {{- if $r.In }} io.envoyproxy.pgv.CollectiveValidation.in("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "In" }}); {{- end -}} {{- if $r.NotIn }} io.envoyproxy.pgv.CollectiveValidation.notIn("{{ $f.FullyQualifiedName }}", {{ accessor . }}, {{ constantName . "NotIn" }}); {{- end -}} {{- if $r.GetIgnoreEmpty }} } {{- end -}} `
templates/java/num.go
0.549882
0.440048
num.go
starcoder
package component import ( "encoding/json" "github.com/pkg/errors" ) // Operator represents a key's relationship to a set of values. // Valid operators are In, NotIn, Exists and DoesNotExist. type Operator string const ( // OperatorIn means a key value is in a set of possible values OperatorIn Operator = "In" // OperatorNotIn means a key value is not in a set of exclusionary values OperatorNotIn Operator = "NotIn" // OperatorExists means a key exists on the selected resource OperatorExists Operator = "Exists" // OperatorDoesNotExist means a key does not exists on the selected resource OperatorDoesNotExist Operator = "DoesNotExist" ) // MatchOperator matches an operator. func MatchOperator(s string) (Operator, error) { operators := []Operator{OperatorIn, OperatorNotIn, OperatorExists, OperatorExists} for _, o := range operators { if string(o) == s { return o, nil } } return Operator("invalid"), errors.Errorf("operator %q is not valid", s) } // ExpressionSelector is a component for a single expression within a selector type ExpressionSelector struct { base Config ExpressionSelectorConfig `json:"config"` } // NewExpressionSelector creates a expressionSelector component func NewExpressionSelector(k string, o Operator, values []string) *ExpressionSelector { return &ExpressionSelector{ base: newBase(typeExpressionSelector, nil), Config: ExpressionSelectorConfig{ Key: k, Operator: o, Values: values, }, } } // Name is the name of the ExpressionSelector. func (t *ExpressionSelector) Name() string { return t.Config.Key } // ExpressionSelectorConfig is the contents of ExpressionSelector type ExpressionSelectorConfig struct { Key string `json:"key"` Operator Operator `json:"operator"` Values []string `json:"values"` } // GetMetadata accesses the components metadata. Implements Component. func (t *ExpressionSelector) GetMetadata() Metadata { return t.Metadata } // IsSelector marks the component as selector flavor. Implements Selector. func (t *ExpressionSelector) IsSelector() { } type expressionSelectorMarshal ExpressionSelector // MarshalJSON implements json.Marshaler func (t *ExpressionSelector) MarshalJSON() ([]byte, error) { m := expressionSelectorMarshal(*t) m.Metadata.Type = typeExpressionSelector return json.Marshal(&m) }
pkg/view/component/expression_selector.go
0.783409
0.425009
expression_selector.go
starcoder
package projectron import "math" import "errors" type impl interface { Projection init(paramset) error } func lookupImpl(pin *pj) impl { switch pin.proj { case "latlong", "longlat", "latlon", "lonlat": return &LngLat{pin} case "merc": return &Mercator{pin} case "lcc": return &LCC{pj: pin} case "eqc": return &Equirectangular{pj: pin} } return nil } type LngLat struct { *pj } func (ll *LngLat) init(params paramset) error { ll.x0 = 0 ll.y0 = 0 return nil } func (ll *LngLat) IsLngLat() bool { return true } func (ll *LngLat) Forward(lng, lat float64) (x, y float64, err error) { return ll.commonFwd(lng, lat, ll.fwd) } func (ll *LngLat) Inverse(x, y float64) (lng, lat float64, err error) { return ll.commonInv(x, y, ll.inv) } func (ll *LngLat) fwd(lam, phi float64) (float64, float64, error) { x := lam / ll.a y := phi / ll.a return x, y, nil } func (ll *LngLat) inv(x, y float64) (lng, lat float64, err error) { lat = y * ll.a lng = x * ll.a return lng, lat, nil } type Mercator struct { *pj } func (m *Mercator) IsLngLat() bool { return true } func (m *Mercator) ToMeter() float64 { return m.to_meter } func (m *Mercator) FromGreenwich() float64 { return m.from_greenwich } func (m *Mercator) init(params paramset) error { var phits float64 var isPhits bool if phits, isPhits = params.degree("lat_ts"); isPhits { phits = math.Abs(phits) } if m.e != 0 && isPhits { m.k0 = msfn(math.Sin(phits), math.Cos(phits), m.es) } else if isPhits { m.k0 = math.Cos(phits) } return nil } func (m *Mercator) Forward(lng, lat float64) (x, y float64, err error) { return m.commonFwd(lng, lat, m.fwd) } func (m *Mercator) Inverse(x, y float64) (lng, lat float64, err error) { return m.commonInv(x, y, m.inv) } func (m *Mercator) fwd(lam, phi float64) (x float64, y float64, err error) { if m.es != 0 { x = m.k0 * lam y = -m.k0 * math.Log(tsfn(phi, math.Sin(phi), m.e)) } else { x = m.k0 * lam y = m.k0 * math.Log(math.Tan(fort_pi+0.5*phi)) } return x, y, nil } func (m *Mercator) inv(x, y float64) (lng, lat float64, err error) { if m.es != 0 { lat, err = phi2(math.Exp(-y/m.k0), m.e) lng = x * m.k0 } else { lng = x / m.k0 lat = half_pi - 2*math.Atan(math.Exp(-y/m.k0)) } return lng, lat, err } type LCC struct { *pj c, n, rho0 float64 phi2, phi1 float64 ellips bool } func (lcc *LCC) IsLngLat() bool { return false } func (ll *LCC) init(params paramset) error { ll.phi1, _ = params.degree("lat_1") if phi2, ok := params.degree("lat_2"); ok { ll.phi2 = phi2 } else { ll.phi2 = ll.phi1 if _, ok := params.string("lat_0"); !ok { ll.phi0 = ll.phi1 } } if math.Abs(ll.phi1 + ll.phi2) <= epsln { return errors.New("these can't be the same") } sinphi := math.Sin(ll.phi1) ll.n = sinphi cosphi := math.Cos(ll.phi1) secant := math.Abs(ll.phi1 - ll.phi2) >= epsln ll.ellips = ll.es != 0 if ll.ellips { ll.e = math.Sqrt(ll.es) m1 := msfn(sinphi, cosphi, ll.es) ml1 := tsfn(ll.phi1, sinphi, ll.e) if secant { sinphi = math.Sin(ll.phi2) ll.n = math.Log(m1/msfn(sinphi, math.Cos(ll.phi2), ll.es)) ll.n /= math.Log(ml1 / tsfn(ll.phi2, sinphi, ll.e)) } ll.c = m1 * math.Pow(ml1, -ll.n) / ll.n if math.Abs(math.Abs(ll.phi0) - half_pi) < epsln { ll.rho0 = 0 } else { ll.rho0 = ll.c * math.Pow(tsfn(ll.phi0, math.Sin(ll.phi0), ll.e), ll.n) } } else { if secant { ll.n = math.Log(cosphi / math.Cos(ll.phi2)) / math.Log(math.Tan(fort_pi + .5 * ll.phi2) / math.Tan(fort_pi + .5 * ll.phi1)) } ll.c = cosphi * math.Pow(math.Tan(fort_pi + .5 * ll.phi1), ll.n) / ll.n if math.Abs(math.Abs(ll.phi0) - half_pi) < epsln { ll.rho0 = 0 } else { ll.rho0 = ll.c * math.Pow(math.Tan(fort_pi + 0.5 * ll.phi0), -ll.n) } } // println(ll.phi1, ll.phi2, ll.n, ll.rho0, ll.c,) return nil } func (ll *LCC) Forward(lng, lat float64) (x, y float64, err error) { return ll.commonFwd(lng, lat, ll.fwd) } func (ll *LCC) Inverse(x, y float64) (lng, lat float64, err error) { return ll.commonInv(x, y, ll.inv) } func (ll *LCC) fwd(lam, phi float64) (x float64, y float64, err error) { var rho float64 if math.Abs(math.Abs(phi)-half_pi) < epsln { if phi*ll.n <= 0 { return hugeVal, hugeVal, errors.New("something") } } else { if ll.ellips { rho = ll.c * math.Pow(tsfn(phi, math.Sin(phi), ll.e), ll.n) } else { rho = ll.c * math.Pow(math.Tan(fort_pi + 0.5 * phi), -ll.n) } } lam *= ll.n x = ll.k0 * (rho * math.Sin(lam)) y = ll.k0 * (ll.rho0 - rho*math.Cos(lam)) return x, y, nil } func (ll *LCC) inv(x, y float64) (lng, lat float64, err error) { panic("don't call this") } type Equirectangular struct { *pj phi1 float64 } func (eqc *Equirectangular) init(params paramset) error { eqc.phi1, _ = params.degree("lat_1") return nil } func (eqc *Equirectangular) IsLngLat() bool { return false } func (eqc *Equirectangular) Forward(lng, lat float64) (x, y float64, err error) { return eqc.commonFwd(lng, lat, eqc.fwd) } func (eqc *Equirectangular) Inverse(x, y float64) (lng, lat float64, err error) { return eqc.commonInv(x, y, eqc.inv) } func (eqc *Equirectangular) fwd(lam, phi float64) (float64, float64, error) { x := lam / eqc.a y := phi / eqc.a return x, y, nil } func (eqc *Equirectangular) inv(x, y float64) (lng, lat float64, err error) { lat = y * eqc.a lng = x * math.Cos(eqc.phi1) * eqc.a return lng, lat, nil }
projections.go
0.628407
0.483709
projections.go
starcoder
package monitoring import ( "fmt" "github.com/gravitational/trace" humanize "github.com/dustin/go-humanize" ) // StorageConfig describes checker configuration type StorageConfig struct { // Path represents volume to be checked Path string // WillBeCreated when true, then all checks will be applied to first existing dir, or fail otherwise WillBeCreated bool // MinBytesPerSecond is minimum write speed for probe to succeed MinBytesPerSecond uint64 // Filesystems define list of supported filesystems, or any if empty Filesystems []string // MinFreeBytes define minimum free volume capacity MinFreeBytes uint64 // LowWatermark is the disk occupancy percentage that will trigger a warning probe LowWatermark uint // HighWatermark is the disk occupancy percentage that will trigger a critical probe. // Disk usage check will be skipped if HighWatermark is unspecified or 0. HighWatermark uint // UID is the expected user owner of the path. UID *uint32 // GID is the expected group owner of the path. GID *uint32 } // CheckAndSetDefaults validates that this configuration is correct and sets // value defaults where necessary. func (c *StorageConfig) CheckAndSetDefaults() error { var errors []error if c.Path == "" { errors = append(errors, trace.BadParameter("volume path must be provided")) } if c.LowWatermark > 100 { errors = append(errors, trace.BadParameter("low watermark must be 0-100")) } if c.HighWatermark > 100 { errors = append(errors, trace.BadParameter("high watermark must be 0-100")) } if c.LowWatermark > c.HighWatermark { c.LowWatermark = c.HighWatermark } return trace.NewAggregate(errors...) } // HighWatermarkCheckerData is attached to high watermark check results type HighWatermarkCheckerData struct { // LowWatermark is the low watermark percentage value LowWatermark uint `json:"low_watermark"` // HighWatermark is the high watermark percentage value HighWatermark uint `json:"high_watermark"` // Path is the absolute path to check Path string `json:"path"` // TotalBytes is the total disk capacity TotalBytes uint64 `json:"total_bytes"` // AvailableBytes is the available disk capacity AvailableBytes uint64 `json:"available_bytes"` } // WarningMessage returns warning watermark check message func (d HighWatermarkCheckerData) WarningMessage() string { diskUsage := float64(d.TotalBytes-d.AvailableBytes) / float64(d.TotalBytes) * 100 return fmt.Sprintf("disk utilization on %s exceeds %v%%, currently at %v%% (%s is available out of %s), cluster will degrade if usage exceeds %v%%, see https://gravitational.com/gravity/docs/cluster/#garbage-collection", d.Path, d.LowWatermark, diskUsage, humanize.Bytes(d.AvailableBytes), humanize.Bytes(d.TotalBytes), d.HighWatermark) } // CriticalMessage returns critical watermark check message func (d HighWatermarkCheckerData) CriticalMessage() string { diskUsage := float64(d.TotalBytes-d.AvailableBytes) / float64(d.TotalBytes) * 100 return fmt.Sprintf("disk utilization on %s exceeds %v%%, currently at %v%% (%s is available out of %s), see https://gravitational.com/gravity/docs/cluster/#garbage-collection", d.Path, d.HighWatermark, diskUsage, humanize.Bytes(d.AvailableBytes), humanize.Bytes(d.TotalBytes)) } // SuccessMessage returns success watermark check message func (d HighWatermarkCheckerData) SuccessMessage() string { return fmt.Sprintf("disk utilization on %s is below %v%% (%s is available out of %s)", d.Path, d.HighWatermark, humanize.Bytes(d.AvailableBytes), humanize.Bytes(d.TotalBytes)) } // DiskSpaceCheckerID is the checker that checks disk space utilization const DiskSpaceCheckerID = "disk-space" // PathUIDCheckerData is attached to path UID check results. type PathUIDCheckerData struct { // ExpectedUID is the expected path UID. ExpectedUID uint32 `json:"expected_uid"` // ActualUID is the actual path UID. ActualUID uint32 `json:"actual_uid"` // Path is the path being checked. Path string } // SuccessMessage returns success UID check message. func (d PathUIDCheckerData) SuccessMessage() string { return fmt.Sprintf("path %s owner UID is %v", d.Path, d.ActualUID) } // FailureMessage return failure UID check message. func (d PathUIDCheckerData) FailureMessage() string { return fmt.Sprintf("path %s owner UID is %v but is expected to be %v", d.Path, d.ActualUID, d.ExpectedUID) } // PathGIDCheckerData is attached to path GID check results. type PathGIDCheckerData struct { // ExpectedGID is the expected path GID. ExpectedGID uint32 `json:"expected_gid"` // ActualGID is the actual path GID. ActualGID uint32 `json:"actual_gid"` // Path is the path being checked. Path string } // SuccessMessage returns success GID check message. func (d PathGIDCheckerData) SuccessMessage() string { return fmt.Sprintf("path %s owner GID is %v", d.Path, d.ActualGID) } // FailureMessage return failure GID check message. func (d PathGIDCheckerData) FailureMessage() string { return fmt.Sprintf("path %s owner GID is %v but is expected to be %v", d.Path, d.ActualGID, d.ExpectedGID) } // PathUIDCheckerID is the checker that verifies path owner UID. const PathUIDCheckerID = "path-uid" // PathGIDCheckerID is the checker that verifies path owner GID. const PathGIDCheckerID = "path-gid"
vendor/github.com/gravitational/satellite/monitoring/storage.go
0.71889
0.50769
storage.go
starcoder
package stringsmoar import ( "bytes" "errors" "sort" "strings" "unicode/utf8" ) // Runes returns a slice of runes from a string func Runes(s string) []rune { var runes []rune for _, r := range s { runes = append(runes, r) } return runes } // RuneFrequency returns a map of the count of each rune in the string func RuneFrequency(s string) map[rune]int { m := make(map[rune]int) for _, r := range s { m[r]++ } return m } // Set returns a string where each rune from the original string only occurs once, in the order that they first appear func Set(s string) string { var uniques string m := make(map[rune]struct{}) for _, r := range s { _, ok := m[r] if !ok { m[r] = struct{}{} // TODO: benchmark to compare performance of various string creation techniques uniques = uniques + string(r) } } return uniques } // Exclusive returns a string which contains only the runes that are in the map func Exclusive(s string, runes map[rune]bool) string { var result string for _, v := range s { if runes[v] { result += string(v) } } return result } // removeWhenAdjacentRunes will remove runes that repeat, i.e. aaabccd will become bd func removeWhenAdjacentRunes(s string) string { if utf8.RuneCountInString(s) < 2 { return s } runes := Runes(s) duplicates := getAdjacentRunes(runes) reduced := s for _, r := range duplicates { reduced = strings.Replace(reduced, string(r), "", -1) } return reduced } // getAdjacentRunes returns a slice of all runes that repeat at least once func getAdjacentRunes(runes []rune) []rune { var duplicates []rune for i := 1; i < len(runes); i++ { if runes[i-1] == runes[i] { duplicates = append(duplicates, runes[i]) i++ } } return duplicates } // ConsecutiveIndex returns the last place where consecutive runes appear func ConsecutiveIndex(a []rune, start int) int { index := 0 switch { case start >= len(a): return index // TODO better error handling, raise an exception? case len(a) == 0 || len(a) == 1: return index case start == len(a)-1: return start } index = start for i := start; i < len(a)-1; i++ { if a[i] == a[i+1] { index++ } else { break } } return index } // RemoveNthRune removes a specific rune from the string by it's index location (i.e. the value returned by range s) func RemoveNthRune(s string, n int) string { if s == "" { return s } buffer := bytes.NewBuffer(nil) for i, r := range s { if i != n { buffer.WriteRune(r) } } return buffer.String() } // RemoveNthItemSlow returns a completely new copy of the slice with a specific item (by index location) removed func RemoveNthItemSlow(a []string, target int) []string { result := []string{} for i := 0; i < len(a); i++ { if i != target { result = append(result, a[i]) } } return result } // RemoveNthItem returns a completey new copy of the slice with a specific item (by index location) removed func RemoveNthItem(a []string, target int) []string { if target > len(a) || target < 0 { return a } if len(a) <= 1 { return []string{} } result := make([]string, len(a)-1) for i := 0; i < len(a); i++ { if i < target { result[i] = a[i] } else if i > target { result[i-1] = a[i] } } return result } // Sorted returns a string where each rune from the original is now sorted func Sorted(s string) string { runes := []rune(s) sort.Slice(runes, func(i, k int) bool { return runes[i] < runes[k] }) // TODO: benchmark an alternative of strings.Split() -> sort.Strings -> strings.Join() return string(runes) } // Permutations generates all the permutations of the runes in a string https://en.wikipedia.org/wiki/Permutation func Permutations(s string) []string { if utf8.RuneCountInString(s) <= 1 { return []string{s} } var result []string for i, v := range s { p := Permutations(RemoveNthRune(s, i)) for _, c := range p { result = append(result, string(v)+c) } } return result } // PermutationsSlices returns a slice of each permutation of the list of elements func PermutationsSlices(s []string) [][]string { var result [][]string if len(s) <= 1 { return append(result, s) } for i, item := range s { subset := RemoveNthItemSlow(s, i) p := PermutationsSlices(subset) for _, sublists := range p { temp := []string{} temp = append(temp, item) // prepend for "stability" temp = append(temp, sublists...) result = append(result, temp) } } return result } // PermutePick generates the permutations when only subset N of S is picked func PermutePick(s string, n int) []string { return permutePickInternal(s, n, 0) } func permutePickInternal(s string, n int, current int) []string { if utf8.RuneCountInString(s) <= 1 { return []string{s} } var result []string current++ for i, v := range s { if current == n { result = append(result, string(v)) } else { smaller := RemoveNthRune(s, i) p := permutePickInternal(smaller, n, current) for _, c := range p { result = append(result, string(v)+c) } } } return result } // Combinations chooses the subset N of S without regards to order , https://en.wikipedia.org/wiki/Combination func Combinations(s string, n int) []string { if utf8.RuneCountInString(s) <= n { return []string{s} } var result []string p := permutePickInternal(s, n, 0) result = DeduplicateRuneCombinations(p) return result } // DeduplicateRuneCombinations returns a slice of strings where each one is a unique (sorted) rune combination (aka a set) func DeduplicateRuneCombinations(strings []string) []string { var uniques []string m := make(map[string]struct{}) for _, s := range strings { sSorted := Sorted(s) _, ok := m[sSorted] if !ok { m[sSorted] = struct{}{} uniques = append(uniques, sSorted) } } return uniques } func replaceNthRune(s string, n int, newR rune) (string, error) { if !utf8.ValidRune(newR) { return "", errors.New("Invalid Rune") } buffer := bytes.NewBuffer(nil) for i, r := range s { if i == n { buffer.WriteRune(newR) } else { buffer.WriteRune(r) } } return buffer.String(), nil }
stringsmoar.go
0.547222
0.415788
stringsmoar.go
starcoder
package main import ( "bytes" "flag" "fmt" "log" "math/rand" "os" "strconv" "time" ) // FieldLocation reifies the concept of identifying where a cell exists // within a Field. This takes the distinct data points of row/column or // x/y and forces them into a single entity, i.e. "reifies" them. type FieldLocation struct { X, Y int } // Creates a new FieldLocation for the given row and column coordinates. func NewFieldLocation(x, y int) *FieldLocation { return &FieldLocation{X: x, Y: y} } func (f FieldLocation) String() string { return fmt.Sprintf("[row:%v, col:%v]", f.Y, f.X) } // LocationProvider defines what a provider of FieldLocations can do. type LocationProvider interface { // NextLocation returns the next FieldLocation a provider has to give. NextLocation() (loc *FieldLocation) // MoreLocations reports if a provider has more FieldLocations to give out. MoreLocations() bool // MinimumBounds defines the minumum dimensions of a field that will be // able to accommodate all FieldLocations a provider can give. MinimumBounds() (width, height int) } // Seeder wraps a LocationProvider and provides a template for their use // by the Life program. type Seeder struct { provider LocationProvider } func NewSeeder(lp LocationProvider) *Seeder { return &Seeder{provider: lp} } // nextLocation is a template method that first ensures that the wrapped // LocationProvider has more locations to give. func (s *Seeder) nextLocation() *FieldLocation { s.assertMoreLocations() return s.provider.NextLocation() } func (s *Seeder) moreLocations() bool { return s.provider.MoreLocations() } // assertMoreLocations enforces contract that LocationProvider.NextLocation() // can only be called when LocationProvider.MoreLocations() is true. func (s *Seeder) assertMoreLocations() { if !s.provider.MoreLocations() { log.Fatal("Illegal state: no more locations available") } } var ( // Used to set up the initial Field population seeder *Seeder // flag option variables fieldWidth int fieldHeight int gens int gensPerSec int startGen int seed int64 seedflag string initPath string iconName string ) // RandomLocationProvider provides random FieldLocations. type RandomLocationProvider struct { i int width, height int } // NewRandomLocationProvider creates a LocationProvider that gives // random locations within a Field with the given dimensions. The // number of locations provided will cover roughly a quarter of the // entire area of the Field. func NewRandomLocationProvider(w, h int) *RandomLocationProvider { return &RandomLocationProvider{width: w, height: h} } // NextLocation gives the next random location. There is no guarantee // that the locations provided will be unique. func (r *RandomLocationProvider) NextLocation() (loc *FieldLocation) { r.i++ return NewFieldLocation(rand.Intn(r.width), rand.Intn(r.height)) } // MoreLocations reports whether a RandomLocationProvider has more locations // to give. Since there is no guarantee that locations provided are unique, // this implementation sets the upper bound to roughly a quarter of the entire // area of the Field covered by a RandomLocationProvider. func (r RandomLocationProvider) MoreLocations() bool { return r.i < r.width*r.height/4 } // MinimumBounds reports the minimum dimensions of a Field so that it // can accommodate any location that can be given by a RandomLocationProvider. func (r RandomLocationProvider) MinimumBounds() (width, height int) { return r.width, r.height } // Field represents a two-dimensional field of cells. type Field struct { state [][]bool width, height int } // NewField returns an empty field of the specified width and height. func NewField(w, h int) *Field { s := make([][]bool, h) for i := range s { s[i] = make([]bool, w) } return &Field{state: s, width: w, height: h} } // set assigns a state to the specified cell. func (f *Field) set(loc *FieldLocation, alive bool) { if !f.contains(loc) { log.Printf("Out of bounds: %v", loc) return } f.state[loc.Y][loc.X] = alive } // contains checks if a Field includes a FieldLocation. // Returns true if the give FieldLocation is within the // boundaries of the receiving Field func (f *Field) contains(loc *FieldLocation) bool { return loc.X < f.width && loc.Y < f.height } // alive reports whether the specified cell is alive. // If the x or y coordinates are outside the field boundaries they are wrapped // toroidally. For instance, an x value of -1 is treated as width-1. func (f *Field) alive(x, y int) bool { x += f.width x %= f.width y += f.height y %= f.height return f.state[y][x] // && !f.BlackHoled(y, x) } // next returns the state of the specified cell at the next time step. func (f *Field) next(x, y int) bool { // Count the adjacent cells that are alive. neighbors := 0 for i := -1; i <= 1; i++ { for j := -1; j <= 1; j++ { if (j != 0 || i != 0) && f.alive(x+i, y+j) { neighbors++ } } } // Return next state according to the game rules: // exactly 3 neighbors: on, // exactly 2 neighbors: maintain current state, // otherwise: off. return neighbors == 3 || neighbors == 2 && f.alive(x, y) } // Life stores the state of a round of Conway's Game of Life. type Life struct { thisGen, nextGen *Field width, height, genCount int } // NewLife returns a new Life game state with initial state provided by Seeder func NewLife(w, h int) *Life { firstGen := NewField(w, h) for seeder.moreLocations() { firstGen.set(seeder.nextLocation(), true) } return &Life{ thisGen: firstGen, nextGen: NewField(w, h), width: w, height: h, } } func (l *Life) prepareNextGeneration() { for y := 0; y < l.height; y++ { for x := 0; x < l.width; x++ { l.nextGen.set(NewFieldLocation(x, y), l.thisGen.next(x, y)) } } } func (l *Life) instateNextGeneration() { l.thisGen, l.nextGen = l.nextGen, l.thisGen l.genCount++ } // Step advances the game to the next generation func (l *Life) step() { l.prepareNextGeneration() l.instateNextGeneration() } // String returns the game board as a string. func (l *Life) String() string { const deadcell = " " var buf bytes.Buffer for y := 0; y < l.height; y++ { for x := 0; x < l.width; x++ { cell := []byte(deadcell) if l.thisGen.alive(x, y) { cell = livecell } buf.Write(cell) } buf.WriteByte('\n') } return buf.String() } func (l *Life) showCurrentGeneration(nth int) { fmt.Printf("\n\nGeneration %v (%v of %v):\n%v", l.genCount+1, nth-startGen+1, gens, l) } func (l *Life) showRunInfo() { fmt.Printf("%v generations calculated.\n\n", l.genCount) fmt.Printf("To continue: %v -y %v -x %v %v -icon %v -s %v -n %v\n", os.Args[0], l.height, l.width, seedflag, iconName, l.genCount, gens, ) } func (l *Life) stepThroughAll(gens int) { delay := time.Second / time.Duration(gensPerSec) maxgen := gens + startGen for i := 0; i < maxgen; i++ { if startGen <= i { l.showCurrentGeneration(i) time.Sleep(delay) } l.step() } } // simulate calculates the specified number of generations func (l *Life) simulate(gens int) { fmt.Printf("\nConway's Game of Life\n") l.stepThroughAll(gens) l.showRunInfo() } func initStartGen() { if startGen > 1 { fmt.Printf("\nStarting from generation %v...", startGen) startGen-- } else { startGen = 0 } } func max(a, b int) int { if a > b { return a } return b } // initSeed initializes the Seeder and seed-related vars func initSeed() { // -f option if initPath != "" { flp, err := NewFileLocationProvider(initPath) if err == nil { minX, minY := flp.MinimumBounds() fieldWidth = max(fieldWidth, minX) fieldHeight = max(fieldHeight, minY) seeder = NewSeeder(flp) seedflag = "-f " + initPath } } // default / fallback if seeder == nil { if seed == 0 { seed = time.Now().UnixNano() } rand.Seed(seed) seeder = NewSeeder(NewRandomLocationProvider(fieldWidth, fieldHeight)) seedflag = "-seed " + strconv.FormatInt(seed, 10) } } var livecell []byte func initDisplay() { s, ok := icon[iconName] if !ok { iconName = "blue-circle" // DEVELOPER: if you edit this, edit usage(), too! s = icon[iconName] } livecell = []byte(" " + s) } var icon = map[string]string{ "aster-1": "\u2731", "aster-2": "\u2749", "blue-circle": "\u23FA", "blue-square": "\u23F9", "bug": "\u2603", "circle-plus": "\u2A01", "circle-x": "\u2A02", "dot-star": "\u272A", "fat-x": "\u2716", "flower": "\u273F", "green-x": "\u274E", "man-dribble": "\u26F9", "man-yellow": "\u26B1", "no-entry": "\u26D4", "redhat": "\u26D1", "skull-x": "\u2620", "snowflake": "\u274A", "snowman": "\u26C4", "square-big": "\u2B1C", "square-small": "\u25A9", "star-yellow": "\u2B50", "star-white": "\u2605", "star-6pt": "\u2736", "star-8pt": "\u2738", "whitedot": "\u26AA", } func init() { flag.Usage = usage flag.Int64Var(&seed, "seed", 0, "seed for initial population (default random)\n\tignored if -f option specified and valid") flag.StringVar(&initPath, "f", "", "read initial population from `filename`\n\tif valid, -seed option is ignored") flag.IntVar(&fieldHeight, "y", 30, "height of simulation field") flag.IntVar(&fieldWidth, "x", 30, "width of simulation field") flag.IntVar(&gens, "n", 20, "display up to `N` generations") flag.IntVar(&gensPerSec, "r", 5, "display `N` generations per second") flag.IntVar(&startGen, "s", 0, "start displaying from generation `N`") flag.StringVar(&iconName, "icon", "", "`name` of icon to use for live cells (default blue-circle)") } func usage() { fmt.Fprintf(os.Stderr, "Usage: %s [-x] [-y] [-r] [-n] [-s] [-f] [-seed] [-icon]\n\n"+ "Options:\n\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\nAvailable icons for live cells:\n\n"+ "Icon\tName\t\tDescription\n"+ "----\t--------\t-----------\n"+ icon["aster-1"]+"\taster-1\t\tAsterisk 1\n"+ icon["aster-2"]+"\taster-2\t\tAsterisk 2\n"+ icon["blue-circle"]+"\tblue-circle\tBlue tile, white circle (default)\n"+ icon["blue-square"]+"\tblue-square\tBlue tile, white square\n"+ icon["bug"]+"\tbug\t\tBug\n"+ icon["circle-plus"]+"\tcircle-plus\tCircle with a '+'\n"+ icon["circle-x"]+"\tcircle-x\tCircle with an 'x'\n"+ icon["dot-star"]+"\tdot-star\tDot with star\n"+ icon["fat-x"]+"\tfat-x\t\tFat white X\n"+ icon["flower"]+"\tflower\t\tFlower\n"+ icon["green-x"]+"\tgreen-x\t\tGreen tile with white X\n"+ icon["man-dribble"]+"\tman-dribble\tMan dribbling ball\n"+ icon["man-yellow"]+"\tman-yellow\tLittle yellow man\n"+ icon["no-entry"]+"\tno-entry\tNo entry sign\n"+ icon["redhat"]+"\tredhat\t\tRed hardhat with white cross\n"+ icon["skull-x"]+"\tskull-x\t\tSkull and crossbones\n"+ icon["snowflake"]+"\tsnowflake\tSnowflake\n"+ icon["snowman"]+"\tsnowman\t\tSnowman\n"+ icon["square-big"]+"\tsquare-big\tBig square\n"+ icon["square-small"]+"\tsquare-small\tSmall square\n"+ icon["star-yellow"]+"\tstar-yellow\tYellow 5-point star\n"+ icon["star-white"]+"\tstar-white\tWhite 5-point star\n"+ icon["star-6pt"]+"\tstar-6pt\t6-point star\n"+ icon["star-8pt"]+"\tstar-8pt\t8-point star\n"+ icon["whitedot"]+"\twhitedot\tWhite dot\n", ) } // processArgs processes command line arguments func processArgs() { flag.Parse() initSeed() initStartGen() initDisplay() } func main() { processArgs() NewLife(fieldWidth, fieldHeight).simulate(gens) }
life/life.go
0.75101
0.401336
life.go
starcoder
package types import ( "fmt" "math" "sort" "strconv" sdk "github.com/cosmos/cosmos-sdk/types" ) // VoteForTally is a convinience wrapper to reduct redundant lookup cost type VoteForTally struct { ExchangeRateVote Power int64 } // NewVoteForTally returns a new VoteForTally instance func NewVoteForTally(vote ExchangeRateVote, power int64) VoteForTally { return VoteForTally{ vote, power, } } // ExchangeRateBallot is a convinience wrapper around a ExchangeRateVote slice type ExchangeRateBallot []VoteForTally // ToMap return organized exchange rate map by validator func (pb ExchangeRateBallot) ToMap() map[string]sdk.Dec { exchangeRateMap := make(map[string]sdk.Dec) for _, vote := range pb { if vote.ExchangeRate.IsPositive() { exchangeRateMap[string(vote.Voter)] = vote.ExchangeRate } } return exchangeRateMap } // ToCrossRate return cross_rate(base/exchange_rate) ballot func (pb ExchangeRateBallot) ToCrossRate(bases map[string]sdk.Dec) (cb ExchangeRateBallot) { for i := range pb { vote := pb[i] if exchangeRateRT, ok := bases[string(vote.Voter)]; ok && vote.ExchangeRate.IsPositive() { vote.ExchangeRate = exchangeRateRT.Quo(vote.ExchangeRate) } else { // If we can't get reference terra exhcnage rate, we just convert the vote as abstain vote vote.ExchangeRate = sdk.ZeroDec() vote.Power = 0 } cb = append(cb, vote) } return } // Power returns the total amount of voting power in the ballot func (pb ExchangeRateBallot) Power() int64 { totalPower := int64(0) for _, vote := range pb { totalPower += vote.Power } return totalPower } // WeightedMedian returns the median weighted by the power of the ExchangeRateVote. func (pb ExchangeRateBallot) WeightedMedian() sdk.Dec { totalPower := pb.Power() if pb.Len() > 0 { if !sort.IsSorted(pb) { sort.Sort(pb) } pivot := int64(0) for _, v := range pb { votePower := v.Power pivot += votePower if pivot >= (totalPower / 2) { return v.ExchangeRate } } } return sdk.ZeroDec() } // StandardDeviation returns the standard deviation by the power of the ExchangeRateVote. func (pb ExchangeRateBallot) StandardDeviation() (standardDeviation sdk.Dec) { if len(pb) == 0 { return sdk.ZeroDec() } median := pb.WeightedMedian() sum := sdk.ZeroDec() for _, v := range pb { deviation := v.ExchangeRate.Sub(median) sum = sum.Add(deviation.Mul(deviation)) } variance := sum.QuoInt64(int64(len(pb))) floatNum, _ := strconv.ParseFloat(variance.String(), 64) floatNum = math.Sqrt(floatNum) standardDeviation, _ = sdk.NewDecFromStr(fmt.Sprintf("%f", floatNum)) return } // Len implements sort.Interface func (pb ExchangeRateBallot) Len() int { return len(pb) } // Less reports whether the element with // index i should sort before the element with index j. func (pb ExchangeRateBallot) Less(i, j int) bool { return pb[i].ExchangeRate.LTE(pb[j].ExchangeRate) } // Swap implements sort.Interface. func (pb ExchangeRateBallot) Swap(i, j int) { pb[i], pb[j] = pb[j], pb[i] }
x/oracle/internal/types/ballot.go
0.784236
0.510374
ballot.go
starcoder
package structmapper // Original was https://github.com/jinzhu/copier // extend mapping by struct tag import ( "database/sql" "fmt" "reflect" "strings" "sync" "github.com/pkg/errors" ) // New Mapper func New() Mapper { return &mapper{ transformerRepository: newTransformerRepository(), logger: newNopLogger(), } } // Mapper Struct mapper type Mapper interface { // Copy struct to other struct. Field mapping by `structmapper` tag, `json` tag, or field name. From(fromValue interface{}) CopyCommand // Register Transformer matches by TargerMatcher RegisterTransformer(matcher TypeMatcher, transformer Transformer) Mapper // Register Transformer matches by TargerMatcher RegisterTransformerFunc(matcher TypeMatcherFunc, transformer Transformer) Mapper // Install Module Install(Module) Mapper EnableLogging() Mapper } // Mapper installable module type Module func(Mapper) // Copy to ... type CopyCommand interface { // Copy struct to other struct. Field mapping by `structmapper` tag, `json` tag, or field name. CopyTo(toValue interface{}) error } // Matcher of Transformer target type TypeMatcher interface { // Matches Matches(Target) bool } // TypeMatcher func type TypeMatcherFunc func(Target) bool // Matches of TypeMatcher func (f TypeMatcherFunc) Matches(target Target) bool { return f(target) } // Pair of Transformer target type Target struct { // From type From reflect.Type // To type To reflect.Type } // Matches of TypeMatcher func (t Target) Matches(target Target) bool { return t == target } // String of Stringer func (t Target) String() string { return fmt.Sprintf("%+v -> %+v", t.From, t.To) } // Value transformer type Transformer func(from reflect.Value, toType reflect.Type) (reflect.Value, error) type copyCommand struct { *mapper fromValue interface{} } func (c *copyCommand) CopyTo(toValue interface{}) (err error) { return c.mapper.Copy(toValue, c.fromValue) } type mapper struct { transformerRepository *transformerRepository logger Logger } func (m *mapper) Install(module Module) Mapper { module(m) return m } func (m *mapper) EnableLogging() Mapper { m.logger = newStdLogger() return m } func (m *mapper) From(fromValue interface{}) CopyCommand { return &copyCommand{mapper: m, fromValue: fromValue} } func (m *mapper) Copy(toValue, fromValue interface{}) error { return m.copyValue(reflect.ValueOf(toValue), reflect.ValueOf(fromValue)) } func (m *mapper) copyValue(to, from reflect.Value) error { // Return if invalid if !from.IsValid() { return nil } if from.Kind() == reflect.Ptr && to.Kind() == reflect.Ptr && from.IsNil() { //set `to` to nil if from is nil to.Set(reflect.Zero(to.Type())) return nil } v, err := m.convert(indirect(from), indirectType(to.Type())) if err != nil { return err } indirectAsNonNil(to).Set(v) return nil } func (m *mapper) convertSlice(from reflect.Value, toType reflect.Type) (reflect.Value, error) { amount := from.Len() destType := toType.Elem() to := reflect.MakeSlice(toType, 0, amount) for i := 0; i < amount; i++ { source := from.Index(i) m.logger.Printf("convertSlice[%d](%+v -> %+v)", i, source, destType) dest, err := m.convert(source, indirectType(destType)) if err != nil { return to, err } if destType.Kind() == reflect.Ptr { to = reflect.Append(to, forceAddr(dest)) } else { to = reflect.Append(to, dest) } } return to, nil } func (m *mapper) convertStruct(from reflect.Value, toType reflect.Type) (reflect.Value, error) { to := reflect.New(toType).Elem() toFields := asNamesToFieldMap(deepFields(to.Type())) // Copy from field to field copied := make(map[string]struct{}) for _, fromField := range deepFields(from.Type()) { if fromValue := from.FieldByName(fromField.Name); fromValue.IsValid() { for _, name := range namesOf(fromField) { if toField, found := toFields[name]; found { // has field if _, ok := copied[toField.Name]; !ok { if toValue := to.FieldByName(toField.Name); toValue.IsValid() && toValue.CanSet() { m.logger.Printf("copyValue(%s:%+v -> %s:%+v)", fromField.Name, fromValue.Kind(), toField.Name, toValue.Kind()) if err := m.copyValue(toValue, fromValue); err != nil { return to, err } } copied[toField.Name] = struct{}{} } } } } } return to, nil } func deepFields(reflectType reflect.Type) []reflect.StructField { var fields []reflect.StructField if reflectType = indirectType(reflectType); reflectType.Kind() == reflect.Struct { for i := 0; i < reflectType.NumField(); i++ { v := reflectType.Field(i) if v.Anonymous { fields = append(fields, deepFields(v.Type)...) } else { fields = append(fields, v) } } } return fields } func indirect(reflectValue reflect.Value) reflect.Value { for reflectValue.Kind() == reflect.Ptr { reflectValue = reflectValue.Elem() } return reflectValue } func indirectAsNonNil(v reflect.Value) reflect.Value { if v.Kind() == reflect.Ptr { if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } return v.Elem() } return v } func indirectType(reflectType reflect.Type) reflect.Type { for reflectType.Kind() == reflect.Ptr { reflectType = reflectType.Elem() } return reflectType } func (m *mapper) convert(from reflect.Value, toType reflect.Type) (reflect.Value, error) { if !from.IsValid() { return reflect.Zero(toType), nil } if transformer := m.transformerRepository.Get(Target{To: toType, From: from.Type()}); transformer != nil { return transformer(from, toType) } else if from.Type().ConvertibleTo(toType) { return from.Convert(toType), nil } else if m.canScan(toType) { return m.scan(from, toType) } else if from.Kind() == reflect.Ptr { return m.convert(from.Elem(), toType) } else if from.Kind() == reflect.Struct && toType.Kind() == reflect.Struct { return m.convertStruct(from, toType) } else if from.Kind() == reflect.Slice && toType.Kind() == reflect.Slice { return m.convertSlice(from, toType) } else { return reflect.Zero(toType), errors.Errorf("can't convert data %+v -> %+v", from, toType) } } func (m *mapper) canScan(t reflect.Type) bool { return reflect.PtrTo(t).Implements(scannerType) } func (m *mapper) scan(from reflect.Value, toType reflect.Type) (reflect.Value, error) { v := reflect.New(toType) scanner := v.Interface().(sql.Scanner) err := scanner.Scan(from.Interface()) if err != nil { return reflect.Zero(toType), err } return v.Elem(), nil } var scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem() func forceAddr(v reflect.Value) reflect.Value { if v.Kind() == reflect.Ptr { return v } else if v.CanAddr() { return v.Addr() } // copy to CanAddr ptr := reflect.New(v.Type()) ptr.Elem().Set(v) return ptr } func namesOf(field reflect.StructField) []string { names := make([]string, 0, 2) for _, tagName := range tagNames { if tag := field.Tag.Get(tagName); tag != "" { name := strings.SplitN(tag, ",", 2)[0] if name != "-" { names = append(names, name) } } } return append(names, field.Name) } func asNamesToFieldMap(fields []reflect.StructField) map[string]reflect.StructField { m := make(map[string]reflect.StructField) for _, field := range fields { for _, name := range namesOf(field) { if _, found := m[name]; !found { m[name] = field } } } return m } func (m *mapper) RegisterTransformer(matcher TypeMatcher, transformer Transformer) Mapper { m.transformerRepository.Put(matcher, transformer) return m } func (m *mapper) RegisterTransformerFunc(matcherFunc TypeMatcherFunc, transformer Transformer) Mapper { return m.RegisterTransformer(matcherFunc, transformer) } var tagNames = []string{"structmapper", "json"} type transformerPair struct { Matcher TypeMatcher Transformer Transformer } type transformerRepository struct { transformers []transformerPair cache map[Target]Transformer mutex sync.Mutex } func newTransformerRepository() *transformerRepository { return &transformerRepository{ transformers: nil, cache: make(map[Target]Transformer), } } func (r *transformerRepository) Put(matcher TypeMatcher, transformer Transformer) { r.transformers = append(r.transformers, transformerPair{matcher, transformer}) } func (r *transformerRepository) Get(target Target) Transformer { r.mutex.Lock() defer r.mutex.Unlock() if cached, ok := r.cache[target]; ok { return cached } for _, pair := range r.transformers { matches := pair.Matcher.Matches(target) if matches { return pair.Transformer } } return nil }
structmapper.go
0.739893
0.410756
structmapper.go
starcoder
package graph import ( i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time" i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization" ) // EducationAssignment type EducationAssignment struct { Entity // Optional field to control the assignment behavior for students who are added after the assignment is published. If not specified, defaults to none value. Currently supports only two values: none or assignIfOpen. addedStudentAction *EducationAddedStudentAction; // Optional field to control the assignment behavior for adding assignments to students' and teachers' calendars when the assignment is published. The possible values are: none, studentsAndPublisher, studentsAndTeamOwners, unknownFutureValue, and studentsOnly. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: studentsOnly. The default value is none. addToCalendarAction *EducationAddToCalendarOptions; // Identifies whether students can submit after the due date. If this property isn't specified during create, it defaults to true. allowLateSubmissions *bool; // Identifies whether students can add their own resources to a submission or if they can only modify resources added by the teacher. allowStudentsToAddResourcesToSubmission *bool; // The date when the assignment should become active. If in the future, the assignment isn't shown to the student until this date. The Timestamp 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 assignDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // The moment that the assignment was published to students and the assignment shows up on the students timeline. The Timestamp 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 assignedDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // Which users, or whole class should receive a submission object once the assignment is published. assignTo *EducationAssignmentRecipient; // When set, enables users to easily find assignments of a given type. Read-only. Nullable. categories []EducationCategory; // Class which this assignment belongs. classId *string; // Date when the assignment will be closed for submissions. This is an optional field that can be null if the assignment does not allowLateSubmissions or when the closeDateTime is the same as the dueDateTime. But if specified, then the closeDateTime must be greater than or equal to the dueDateTime. The Timestamp 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 closeDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // Who created the assignment. createdBy *IdentitySet; // Moment when the assignment was created. The Timestamp 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 createdDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // Name of the assignment. displayName *string; // Date when the students assignment is due. The Timestamp 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 dueDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // How the assignment will be graded. grading *EducationAssignmentGradeType; // Instructions for the assignment. This along with the display name tell the student what to do. instructions *EducationItemBody; // Who last modified the assignment. lastModifiedBy *IdentitySet; // Moment when the assignment was last modified. The Timestamp 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 lastModifiedDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time; // Optional field to specify the URL of the channel to post the assignment publish notification. If not specified or null, defaults to the General channel. This field only applies to assignments where the assignTo value is educationAssignmentClassRecipient. Updating the notificationChannelUrl isn't allowed after the assignment has been published. notificationChannelUrl *string; // Learning objects that are associated with this assignment. Only teachers can modify this list. Nullable. resources []EducationAssignmentResource; // Folder URL where all the file resources for this assignment are stored. resourcesFolderUrl *string; // When set, the grading rubric attached to this assignment. rubric *EducationRubric; // Status of the Assignment. You can't PATCH this value. Possible values are: draft, scheduled, published, assigned. status *EducationAssignmentStatus; // Once published, there is a submission object for each student representing their work and grade. Read-only. Nullable. submissions []EducationSubmission; // The deep link URL for the given assignment. webUrl *string; } // NewEducationAssignment instantiates a new educationAssignment and sets the default values. func NewEducationAssignment()(*EducationAssignment) { m := &EducationAssignment{ Entity: *NewEntity(), } return m } // GetAddedStudentAction gets the addedStudentAction property value. Optional field to control the assignment behavior for students who are added after the assignment is published. If not specified, defaults to none value. Currently supports only two values: none or assignIfOpen. func (m *EducationAssignment) GetAddedStudentAction()(*EducationAddedStudentAction) { if m == nil { return nil } else { return m.addedStudentAction } } // GetAddToCalendarAction gets the addToCalendarAction property value. Optional field to control the assignment behavior for adding assignments to students' and teachers' calendars when the assignment is published. The possible values are: none, studentsAndPublisher, studentsAndTeamOwners, unknownFutureValue, and studentsOnly. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: studentsOnly. The default value is none. func (m *EducationAssignment) GetAddToCalendarAction()(*EducationAddToCalendarOptions) { if m == nil { return nil } else { return m.addToCalendarAction } } // GetAllowLateSubmissions gets the allowLateSubmissions property value. Identifies whether students can submit after the due date. If this property isn't specified during create, it defaults to true. func (m *EducationAssignment) GetAllowLateSubmissions()(*bool) { if m == nil { return nil } else { return m.allowLateSubmissions } } // GetAllowStudentsToAddResourcesToSubmission gets the allowStudentsToAddResourcesToSubmission property value. Identifies whether students can add their own resources to a submission or if they can only modify resources added by the teacher. func (m *EducationAssignment) GetAllowStudentsToAddResourcesToSubmission()(*bool) { if m == nil { return nil } else { return m.allowStudentsToAddResourcesToSubmission } } // GetAssignDateTime gets the assignDateTime property value. The date when the assignment should become active. If in the future, the assignment isn't shown to the student until this date. The Timestamp 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 *EducationAssignment) GetAssignDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.assignDateTime } } // GetAssignedDateTime gets the assignedDateTime property value. The moment that the assignment was published to students and the assignment shows up on the students timeline. The Timestamp 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 *EducationAssignment) GetAssignedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.assignedDateTime } } // GetAssignTo gets the assignTo property value. Which users, or whole class should receive a submission object once the assignment is published. func (m *EducationAssignment) GetAssignTo()(*EducationAssignmentRecipient) { if m == nil { return nil } else { return m.assignTo } } // GetCategories gets the categories property value. When set, enables users to easily find assignments of a given type. Read-only. Nullable. func (m *EducationAssignment) GetCategories()([]EducationCategory) { if m == nil { return nil } else { return m.categories } } // GetClassId gets the classId property value. Class which this assignment belongs. func (m *EducationAssignment) GetClassId()(*string) { if m == nil { return nil } else { return m.classId } } // GetCloseDateTime gets the closeDateTime property value. Date when the assignment will be closed for submissions. This is an optional field that can be null if the assignment does not allowLateSubmissions or when the closeDateTime is the same as the dueDateTime. But if specified, then the closeDateTime must be greater than or equal to the dueDateTime. The Timestamp 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 *EducationAssignment) GetCloseDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.closeDateTime } } // GetCreatedBy gets the createdBy property value. Who created the assignment. func (m *EducationAssignment) GetCreatedBy()(*IdentitySet) { if m == nil { return nil } else { return m.createdBy } } // GetCreatedDateTime gets the createdDateTime property value. Moment when the assignment was created. The Timestamp 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 *EducationAssignment) GetCreatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.createdDateTime } } // GetDisplayName gets the displayName property value. Name of the assignment. func (m *EducationAssignment) GetDisplayName()(*string) { if m == nil { return nil } else { return m.displayName } } // GetDueDateTime gets the dueDateTime property value. Date when the students assignment is due. The Timestamp 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 *EducationAssignment) GetDueDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.dueDateTime } } // GetGrading gets the grading property value. How the assignment will be graded. func (m *EducationAssignment) GetGrading()(*EducationAssignmentGradeType) { if m == nil { return nil } else { return m.grading } } // GetInstructions gets the instructions property value. Instructions for the assignment. This along with the display name tell the student what to do. func (m *EducationAssignment) GetInstructions()(*EducationItemBody) { if m == nil { return nil } else { return m.instructions } } // GetLastModifiedBy gets the lastModifiedBy property value. Who last modified the assignment. func (m *EducationAssignment) GetLastModifiedBy()(*IdentitySet) { if m == nil { return nil } else { return m.lastModifiedBy } } // GetLastModifiedDateTime gets the lastModifiedDateTime property value. Moment when the assignment was last modified. The Timestamp 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 *EducationAssignment) GetLastModifiedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.lastModifiedDateTime } } // GetNotificationChannelUrl gets the notificationChannelUrl property value. Optional field to specify the URL of the channel to post the assignment publish notification. If not specified or null, defaults to the General channel. This field only applies to assignments where the assignTo value is educationAssignmentClassRecipient. Updating the notificationChannelUrl isn't allowed after the assignment has been published. func (m *EducationAssignment) GetNotificationChannelUrl()(*string) { if m == nil { return nil } else { return m.notificationChannelUrl } } // GetResources gets the resources property value. Learning objects that are associated with this assignment. Only teachers can modify this list. Nullable. func (m *EducationAssignment) GetResources()([]EducationAssignmentResource) { if m == nil { return nil } else { return m.resources } } // GetResourcesFolderUrl gets the resourcesFolderUrl property value. Folder URL where all the file resources for this assignment are stored. func (m *EducationAssignment) GetResourcesFolderUrl()(*string) { if m == nil { return nil } else { return m.resourcesFolderUrl } } // GetRubric gets the rubric property value. When set, the grading rubric attached to this assignment. func (m *EducationAssignment) GetRubric()(*EducationRubric) { if m == nil { return nil } else { return m.rubric } } // GetStatus gets the status property value. Status of the Assignment. You can't PATCH this value. Possible values are: draft, scheduled, published, assigned. func (m *EducationAssignment) GetStatus()(*EducationAssignmentStatus) { if m == nil { return nil } else { return m.status } } // GetSubmissions gets the submissions property value. Once published, there is a submission object for each student representing their work and grade. Read-only. Nullable. func (m *EducationAssignment) GetSubmissions()([]EducationSubmission) { if m == nil { return nil } else { return m.submissions } } // GetWebUrl gets the webUrl property value. The deep link URL for the given assignment. func (m *EducationAssignment) GetWebUrl()(*string) { if m == nil { return nil } else { return m.webUrl } } // GetFieldDeserializers the deserialization information for the current model func (m *EducationAssignment) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["addedStudentAction"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetEnumValue(ParseEducationAddedStudentAction) if err != nil { return err } if val != nil { m.SetAddedStudentAction(val.(*EducationAddedStudentAction)) } return nil } res["addToCalendarAction"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetEnumValue(ParseEducationAddToCalendarOptions) if err != nil { return err } if val != nil { m.SetAddToCalendarAction(val.(*EducationAddToCalendarOptions)) } return nil } res["allowLateSubmissions"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowLateSubmissions(val) } return nil } res["allowStudentsToAddResourcesToSubmission"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowStudentsToAddResourcesToSubmission(val) } return nil } res["assignDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetAssignDateTime(val) } return nil } res["assignedDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetAssignedDateTime(val) } return nil } res["assignTo"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationAssignmentRecipient() }) if err != nil { return err } if val != nil { m.SetAssignTo(val.(*EducationAssignmentRecipient)) } return nil } res["categories"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetCollectionOfObjectValues(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationCategory() }) if err != nil { return err } if val != nil { res := make([]EducationCategory, len(val)) for i, v := range val { res[i] = *(v.(*EducationCategory)) } m.SetCategories(res) } return nil } res["classId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetClassId(val) } return nil } res["closeDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetCloseDateTime(val) } return nil } res["createdBy"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewIdentitySet() }) if err != nil { return err } if val != nil { m.SetCreatedBy(val.(*IdentitySet)) } return nil } res["createdDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetCreatedDateTime(val) } return nil } res["displayName"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetDisplayName(val) } return nil } res["dueDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetDueDateTime(val) } return nil } res["grading"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationAssignmentGradeType() }) if err != nil { return err } if val != nil { m.SetGrading(val.(*EducationAssignmentGradeType)) } return nil } res["instructions"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationItemBody() }) if err != nil { return err } if val != nil { m.SetInstructions(val.(*EducationItemBody)) } return nil } res["lastModifiedBy"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewIdentitySet() }) if err != nil { return err } if val != nil { m.SetLastModifiedBy(val.(*IdentitySet)) } return nil } res["lastModifiedDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetLastModifiedDateTime(val) } return nil } res["notificationChannelUrl"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetNotificationChannelUrl(val) } return nil } res["resources"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetCollectionOfObjectValues(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationAssignmentResource() }) if err != nil { return err } if val != nil { res := make([]EducationAssignmentResource, len(val)) for i, v := range val { res[i] = *(v.(*EducationAssignmentResource)) } m.SetResources(res) } return nil } res["resourcesFolderUrl"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetResourcesFolderUrl(val) } return nil } res["rubric"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationRubric() }) if err != nil { return err } if val != nil { m.SetRubric(val.(*EducationRubric)) } return nil } res["status"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetEnumValue(ParseEducationAssignmentStatus) if err != nil { return err } if val != nil { m.SetStatus(val.(*EducationAssignmentStatus)) } return nil } res["submissions"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetCollectionOfObjectValues(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewEducationSubmission() }) if err != nil { return err } if val != nil { res := make([]EducationSubmission, len(val)) for i, v := range val { res[i] = *(v.(*EducationSubmission)) } m.SetSubmissions(res) } return nil } res["webUrl"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetWebUrl(val) } return nil } return res } func (m *EducationAssignment) IsNil()(bool) { return m == nil } // Serialize serializes information the current object func (m *EducationAssignment) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } if m.GetAddedStudentAction() != nil { cast := (*m.GetAddedStudentAction()).String() err = writer.WriteStringValue("addedStudentAction", &cast) if err != nil { return err } } if m.GetAddToCalendarAction() != nil { cast := (*m.GetAddToCalendarAction()).String() err = writer.WriteStringValue("addToCalendarAction", &cast) if err != nil { return err } } { err = writer.WriteBoolValue("allowLateSubmissions", m.GetAllowLateSubmissions()) if err != nil { return err } } { err = writer.WriteBoolValue("allowStudentsToAddResourcesToSubmission", m.GetAllowStudentsToAddResourcesToSubmission()) if err != nil { return err } } { err = writer.WriteTimeValue("assignDateTime", m.GetAssignDateTime()) if err != nil { return err } } { err = writer.WriteTimeValue("assignedDateTime", m.GetAssignedDateTime()) if err != nil { return err } } { err = writer.WriteObjectValue("assignTo", m.GetAssignTo()) if err != nil { return err } } if m.GetCategories() != nil { cast := make([]i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, len(m.GetCategories())) for i, v := range m.GetCategories() { temp := v cast[i] = i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable(&temp) } err = writer.WriteCollectionOfObjectValues("categories", cast) if err != nil { return err } } { err = writer.WriteStringValue("classId", m.GetClassId()) if err != nil { return err } } { err = writer.WriteTimeValue("closeDateTime", m.GetCloseDateTime()) if err != nil { return err } } { err = writer.WriteObjectValue("createdBy", m.GetCreatedBy()) if err != nil { return err } } { err = writer.WriteTimeValue("createdDateTime", m.GetCreatedDateTime()) if err != nil { return err } } { err = writer.WriteStringValue("displayName", m.GetDisplayName()) if err != nil { return err } } { err = writer.WriteTimeValue("dueDateTime", m.GetDueDateTime()) if err != nil { return err } } { err = writer.WriteObjectValue("grading", m.GetGrading()) if err != nil { return err } } { err = writer.WriteObjectValue("instructions", m.GetInstructions()) if err != nil { return err } } { err = writer.WriteObjectValue("lastModifiedBy", m.GetLastModifiedBy()) if err != nil { return err } } { err = writer.WriteTimeValue("lastModifiedDateTime", m.GetLastModifiedDateTime()) if err != nil { return err } } { err = writer.WriteStringValue("notificationChannelUrl", m.GetNotificationChannelUrl()) if err != nil { return err } } if m.GetResources() != nil { cast := make([]i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, len(m.GetResources())) for i, v := range m.GetResources() { temp := v cast[i] = i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable(&temp) } err = writer.WriteCollectionOfObjectValues("resources", cast) if err != nil { return err } } { err = writer.WriteStringValue("resourcesFolderUrl", m.GetResourcesFolderUrl()) if err != nil { return err } } { err = writer.WriteObjectValue("rubric", m.GetRubric()) if err != nil { return err } } if m.GetStatus() != nil { cast := (*m.GetStatus()).String() err = writer.WriteStringValue("status", &cast) if err != nil { return err } } if m.GetSubmissions() != nil { cast := make([]i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, len(m.GetSubmissions())) for i, v := range m.GetSubmissions() { temp := v cast[i] = i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable(&temp) } err = writer.WriteCollectionOfObjectValues("submissions", cast) if err != nil { return err } } { err = writer.WriteStringValue("webUrl", m.GetWebUrl()) if err != nil { return err } } return nil } // SetAddedStudentAction sets the addedStudentAction property value. Optional field to control the assignment behavior for students who are added after the assignment is published. If not specified, defaults to none value. Currently supports only two values: none or assignIfOpen. func (m *EducationAssignment) SetAddedStudentAction(value *EducationAddedStudentAction)() { if m != nil { m.addedStudentAction = value } } // SetAddToCalendarAction sets the addToCalendarAction property value. Optional field to control the assignment behavior for adding assignments to students' and teachers' calendars when the assignment is published. The possible values are: none, studentsAndPublisher, studentsAndTeamOwners, unknownFutureValue, and studentsOnly. Note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: studentsOnly. The default value is none. func (m *EducationAssignment) SetAddToCalendarAction(value *EducationAddToCalendarOptions)() { if m != nil { m.addToCalendarAction = value } } // SetAllowLateSubmissions sets the allowLateSubmissions property value. Identifies whether students can submit after the due date. If this property isn't specified during create, it defaults to true. func (m *EducationAssignment) SetAllowLateSubmissions(value *bool)() { if m != nil { m.allowLateSubmissions = value } } // SetAllowStudentsToAddResourcesToSubmission sets the allowStudentsToAddResourcesToSubmission property value. Identifies whether students can add their own resources to a submission or if they can only modify resources added by the teacher. func (m *EducationAssignment) SetAllowStudentsToAddResourcesToSubmission(value *bool)() { if m != nil { m.allowStudentsToAddResourcesToSubmission = value } } // SetAssignDateTime sets the assignDateTime property value. The date when the assignment should become active. If in the future, the assignment isn't shown to the student until this date. The Timestamp 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 *EducationAssignment) SetAssignDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.assignDateTime = value } } // SetAssignedDateTime sets the assignedDateTime property value. The moment that the assignment was published to students and the assignment shows up on the students timeline. The Timestamp 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 *EducationAssignment) SetAssignedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.assignedDateTime = value } } // SetAssignTo sets the assignTo property value. Which users, or whole class should receive a submission object once the assignment is published. func (m *EducationAssignment) SetAssignTo(value *EducationAssignmentRecipient)() { if m != nil { m.assignTo = value } } // SetCategories sets the categories property value. When set, enables users to easily find assignments of a given type. Read-only. Nullable. func (m *EducationAssignment) SetCategories(value []EducationCategory)() { if m != nil { m.categories = value } } // SetClassId sets the classId property value. Class which this assignment belongs. func (m *EducationAssignment) SetClassId(value *string)() { if m != nil { m.classId = value } } // SetCloseDateTime sets the closeDateTime property value. Date when the assignment will be closed for submissions. This is an optional field that can be null if the assignment does not allowLateSubmissions or when the closeDateTime is the same as the dueDateTime. But if specified, then the closeDateTime must be greater than or equal to the dueDateTime. The Timestamp 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 *EducationAssignment) SetCloseDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.closeDateTime = value } } // SetCreatedBy sets the createdBy property value. Who created the assignment. func (m *EducationAssignment) SetCreatedBy(value *IdentitySet)() { if m != nil { m.createdBy = value } } // SetCreatedDateTime sets the createdDateTime property value. Moment when the assignment was created. The Timestamp 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 *EducationAssignment) SetCreatedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.createdDateTime = value } } // SetDisplayName sets the displayName property value. Name of the assignment. func (m *EducationAssignment) SetDisplayName(value *string)() { if m != nil { m.displayName = value } } // SetDueDateTime sets the dueDateTime property value. Date when the students assignment is due. The Timestamp 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 *EducationAssignment) SetDueDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.dueDateTime = value } } // SetGrading sets the grading property value. How the assignment will be graded. func (m *EducationAssignment) SetGrading(value *EducationAssignmentGradeType)() { if m != nil { m.grading = value } } // SetInstructions sets the instructions property value. Instructions for the assignment. This along with the display name tell the student what to do. func (m *EducationAssignment) SetInstructions(value *EducationItemBody)() { if m != nil { m.instructions = value } } // SetLastModifiedBy sets the lastModifiedBy property value. Who last modified the assignment. func (m *EducationAssignment) SetLastModifiedBy(value *IdentitySet)() { if m != nil { m.lastModifiedBy = value } } // SetLastModifiedDateTime sets the lastModifiedDateTime property value. Moment when the assignment was last modified. The Timestamp 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 *EducationAssignment) SetLastModifiedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.lastModifiedDateTime = value } } // SetNotificationChannelUrl sets the notificationChannelUrl property value. Optional field to specify the URL of the channel to post the assignment publish notification. If not specified or null, defaults to the General channel. This field only applies to assignments where the assignTo value is educationAssignmentClassRecipient. Updating the notificationChannelUrl isn't allowed after the assignment has been published. func (m *EducationAssignment) SetNotificationChannelUrl(value *string)() { if m != nil { m.notificationChannelUrl = value } } // SetResources sets the resources property value. Learning objects that are associated with this assignment. Only teachers can modify this list. Nullable. func (m *EducationAssignment) SetResources(value []EducationAssignmentResource)() { if m != nil { m.resources = value } } // SetResourcesFolderUrl sets the resourcesFolderUrl property value. Folder URL where all the file resources for this assignment are stored. func (m *EducationAssignment) SetResourcesFolderUrl(value *string)() { if m != nil { m.resourcesFolderUrl = value } } // SetRubric sets the rubric property value. When set, the grading rubric attached to this assignment. func (m *EducationAssignment) SetRubric(value *EducationRubric)() { if m != nil { m.rubric = value } } // SetStatus sets the status property value. Status of the Assignment. You can't PATCH this value. Possible values are: draft, scheduled, published, assigned. func (m *EducationAssignment) SetStatus(value *EducationAssignmentStatus)() { if m != nil { m.status = value } } // SetSubmissions sets the submissions property value. Once published, there is a submission object for each student representing their work and grade. Read-only. Nullable. func (m *EducationAssignment) SetSubmissions(value []EducationSubmission)() { if m != nil { m.submissions = value } } // SetWebUrl sets the webUrl property value. The deep link URL for the given assignment. func (m *EducationAssignment) SetWebUrl(value *string)() { if m != nil { m.webUrl = value } }
models/microsoft/graph/education_assignment.go
0.793666
0.411761
education_assignment.go
starcoder
package pac import ( "fmt" "gopkg.in/jcmturner/gokrb5.v5/mstypes" "gopkg.in/jcmturner/rpc.v0/ndr" ) // DeviceInfo implements https://msdn.microsoft.com/en-us/library/hh536402.aspx type DeviceInfo struct { UserID uint32 // A 32-bit unsigned integer that contains the RID of the account. If the UserId member equals 0x00000000, the first group SID in this member is the SID for this account. PrimaryGroupID uint32 // A 32-bit unsigned integer that contains the RID for the primary group to which this account belongs. AccountDomainID mstypes.RPCSID // A SID structure that contains the SID for the domain of the account.This member is used in conjunction with the UserId, and GroupIds members to create the user and group SIDs for the client. AccountGroupCount uint32 // A 32-bit unsigned integer that contains the number of groups within the account domain to which the account belongs AccountGroupIDs []mstypes.GroupMembership // A pointer to a list of GROUP_MEMBERSHIP (section 2.2.2) structures that contains the groups to which the account belongs in the account domain. The number of groups in this list MUST be equal to GroupCount. SIDCount uint32 // A 32-bit unsigned integer that contains the total number of SIDs present in the ExtraSids member. ExtraSIDs []mstypes.KerbSidAndAttributes // A pointer to a list of KERB_SID_AND_ATTRIBUTES structures that contain a list of SIDs corresponding to groups not in domains. If the UserId member equals 0x00000000, the first group SID in this member is the SID for this account. DomainGroupCount uint32 // A 32-bit unsigned integer that contains the number of domains with groups to which the account belongs. DomainGroup []mstypes.DomainGroupMembership // A pointer to a list of DOMAIN_GROUP_MEMBERSHIP structures (section 2.2.3) that contains the domains to which the account belongs to a group. The number of sets in this list MUST be equal to DomainCount. } // Unmarshal bytes into the DeviceInfo struct func (k *DeviceInfo) Unmarshal(b []byte) error { ch, _, p, err := ndr.ReadHeaders(&b) if err != nil { return fmt.Errorf("error parsing byte stream headers: %v", err) } e := &ch.Endianness //The next 4 bytes are an RPC unique pointer referent. We just skip these p += 4 k.UserID = ndr.ReadUint32(&b, &p, e) k.PrimaryGroupID = ndr.ReadUint32(&b, &p, e) k.AccountDomainID, err = mstypes.ReadRPCSID(&b, &p, e) if err != nil { return err } k.AccountGroupCount = ndr.ReadUint32(&b, &p, e) if k.AccountGroupCount > 0 { ag := make([]mstypes.GroupMembership, k.AccountGroupCount, k.AccountGroupCount) for i := range ag { ag[i] = mstypes.ReadGroupMembership(&b, &p, e) } k.AccountGroupIDs = ag } k.SIDCount = ndr.ReadUint32(&b, &p, e) var ah ndr.ConformantArrayHeader if k.SIDCount > 0 { ah, err = ndr.ReadUniDimensionalConformantArrayHeader(&b, &p, e) if ah.MaxCount != int(k.SIDCount) { return fmt.Errorf("error with size of ExtraSIDs list. expected: %d, Actual: %d", k.SIDCount, ah.MaxCount) } es := make([]mstypes.KerbSidAndAttributes, k.SIDCount, k.SIDCount) attr := make([]uint32, k.SIDCount, k.SIDCount) ptr := make([]uint32, k.SIDCount, k.SIDCount) for i := range attr { ptr[i] = ndr.ReadUint32(&b, &p, e) attr[i] = ndr.ReadUint32(&b, &p, e) } for i := range es { if ptr[i] != 0 { s, err := mstypes.ReadRPCSID(&b, &p, e) es[i] = mstypes.KerbSidAndAttributes{SID: s, Attributes: attr[i]} if err != nil { return ndr.Malformed{EText: fmt.Sprintf("could not read ExtraSIDs: %v", err)} } } } k.ExtraSIDs = es } k.DomainGroupCount = ndr.ReadUint32(&b, &p, e) if k.DomainGroupCount > 0 { dg := make([]mstypes.DomainGroupMembership, k.DomainGroupCount, k.DomainGroupCount) for i := range dg { dg[i], _ = mstypes.ReadDomainGroupMembership(&b, &p, e) } k.DomainGroup = dg } //Check that there is only zero padding left if len(b) >= p { for _, v := range b[p:] { if v != 0 { return ndr.Malformed{EText: "non-zero padding left over at end of data stream"} } } } return nil }
vendor/gopkg.in/jcmturner/gokrb5.v5/pac/device_info.go
0.557123
0.432842
device_info.go
starcoder
package finverse import ( "encoding/json" ) // SingleSourceIncomeIncomeTotal struct for SingleSourceIncomeIncomeTotal type SingleSourceIncomeIncomeTotal struct { EstmatedMonthlyIncome *IncomeEstimate `json:"estmated_monthly_income,omitempty"` // Number of transactions counted towards income TransactionCount *float32 `json:"transaction_count,omitempty"` MonthlyHistory []MonthlyIncomeEstimate `json:"monthly_history,omitempty"` } // NewSingleSourceIncomeIncomeTotal instantiates a new SingleSourceIncomeIncomeTotal 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 NewSingleSourceIncomeIncomeTotal() *SingleSourceIncomeIncomeTotal { this := SingleSourceIncomeIncomeTotal{} return &this } // NewSingleSourceIncomeIncomeTotalWithDefaults instantiates a new SingleSourceIncomeIncomeTotal 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 NewSingleSourceIncomeIncomeTotalWithDefaults() *SingleSourceIncomeIncomeTotal { this := SingleSourceIncomeIncomeTotal{} return &this } // GetEstmatedMonthlyIncome returns the EstmatedMonthlyIncome field value if set, zero value otherwise. func (o *SingleSourceIncomeIncomeTotal) GetEstmatedMonthlyIncome() IncomeEstimate { if o == nil || o.EstmatedMonthlyIncome == nil { var ret IncomeEstimate return ret } return *o.EstmatedMonthlyIncome } // GetEstmatedMonthlyIncomeOk returns a tuple with the EstmatedMonthlyIncome field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SingleSourceIncomeIncomeTotal) GetEstmatedMonthlyIncomeOk() (*IncomeEstimate, bool) { if o == nil || o.EstmatedMonthlyIncome == nil { return nil, false } return o.EstmatedMonthlyIncome, true } // HasEstmatedMonthlyIncome returns a boolean if a field has been set. func (o *SingleSourceIncomeIncomeTotal) HasEstmatedMonthlyIncome() bool { if o != nil && o.EstmatedMonthlyIncome != nil { return true } return false } // SetEstmatedMonthlyIncome gets a reference to the given IncomeEstimate and assigns it to the EstmatedMonthlyIncome field. func (o *SingleSourceIncomeIncomeTotal) SetEstmatedMonthlyIncome(v IncomeEstimate) { o.EstmatedMonthlyIncome = &v } // GetTransactionCount returns the TransactionCount field value if set, zero value otherwise. func (o *SingleSourceIncomeIncomeTotal) GetTransactionCount() float32 { if o == nil || o.TransactionCount == nil { var ret float32 return ret } return *o.TransactionCount } // GetTransactionCountOk returns a tuple with the TransactionCount field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SingleSourceIncomeIncomeTotal) GetTransactionCountOk() (*float32, bool) { if o == nil || o.TransactionCount == nil { return nil, false } return o.TransactionCount, true } // HasTransactionCount returns a boolean if a field has been set. func (o *SingleSourceIncomeIncomeTotal) HasTransactionCount() bool { if o != nil && o.TransactionCount != nil { return true } return false } // SetTransactionCount gets a reference to the given float32 and assigns it to the TransactionCount field. func (o *SingleSourceIncomeIncomeTotal) SetTransactionCount(v float32) { o.TransactionCount = &v } // GetMonthlyHistory returns the MonthlyHistory field value if set, zero value otherwise. func (o *SingleSourceIncomeIncomeTotal) GetMonthlyHistory() []MonthlyIncomeEstimate { if o == nil || o.MonthlyHistory == nil { var ret []MonthlyIncomeEstimate return ret } return o.MonthlyHistory } // GetMonthlyHistoryOk returns a tuple with the MonthlyHistory field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SingleSourceIncomeIncomeTotal) GetMonthlyHistoryOk() ([]MonthlyIncomeEstimate, bool) { if o == nil || o.MonthlyHistory == nil { return nil, false } return o.MonthlyHistory, true } // HasMonthlyHistory returns a boolean if a field has been set. func (o *SingleSourceIncomeIncomeTotal) HasMonthlyHistory() bool { if o != nil && o.MonthlyHistory != nil { return true } return false } // SetMonthlyHistory gets a reference to the given []MonthlyIncomeEstimate and assigns it to the MonthlyHistory field. func (o *SingleSourceIncomeIncomeTotal) SetMonthlyHistory(v []MonthlyIncomeEstimate) { o.MonthlyHistory = v } func (o SingleSourceIncomeIncomeTotal) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.EstmatedMonthlyIncome != nil { toSerialize["estmated_monthly_income"] = o.EstmatedMonthlyIncome } if o.TransactionCount != nil { toSerialize["transaction_count"] = o.TransactionCount } if o.MonthlyHistory != nil { toSerialize["monthly_history"] = o.MonthlyHistory } return json.Marshal(toSerialize) } type NullableSingleSourceIncomeIncomeTotal struct { value *SingleSourceIncomeIncomeTotal isSet bool } func (v NullableSingleSourceIncomeIncomeTotal) Get() *SingleSourceIncomeIncomeTotal { return v.value } func (v *NullableSingleSourceIncomeIncomeTotal) Set(val *SingleSourceIncomeIncomeTotal) { v.value = val v.isSet = true } func (v NullableSingleSourceIncomeIncomeTotal) IsSet() bool { return v.isSet } func (v *NullableSingleSourceIncomeIncomeTotal) Unset() { v.value = nil v.isSet = false } func NewNullableSingleSourceIncomeIncomeTotal(val *SingleSourceIncomeIncomeTotal) *NullableSingleSourceIncomeIncomeTotal { return &NullableSingleSourceIncomeIncomeTotal{value: val, isSet: true} } func (v NullableSingleSourceIncomeIncomeTotal) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSingleSourceIncomeIncomeTotal) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
finverse/model_single_source_income_income_total.go
0.742608
0.467514
model_single_source_income_income_total.go
starcoder
package main // A demonstration of Strassen's subcubic runtime matrix multiplication // algorithm on square matrices using the divide and conquer model. import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { m1 := mat.NewDense(2, 2, []float64{ 1, 2, 3, 4, }) m2 := mat.NewDense(2, 2, []float64{ 5, 6, 7, 8, }) // Expected output var o mat.Dense o.Mul(m1, m2) // Prefix number of spaces = 5, the number "m1 = " takes up. fmt.Println("m1 =", mat.Formatted(m1, mat.Prefix(" "), mat.Squeeze())) fmt.Println("m2 =", mat.Formatted(m2, mat.Prefix(" "), mat.Squeeze())) fmt.Println("Expected output:") fmt.Println(mat.Formatted(&o, mat.Squeeze())) fmt.Println("Strassen's algorithm output:") outputMatrix := strassensAlgorithm(m1, m2) fmt.Println(mat.Formatted(outputMatrix, mat.Squeeze())) } func strassensAlgorithm(m1, m2 *mat.Dense) *mat.Dense { var productMatrix mat.Dense rows, _ := m1.Dims() // Base case: A square matrix of dimension 1x1 is solved by default. if rows == 1 { productMatrix.Mul(m1, m2) return &productMatrix } // Break up m1 into submatrices from quadrant blocks // |a b| // |c d| a := m1.Slice(0, rows/2, 0, rows/2) b := m1.Slice(0, rows/2, rows/2, rows) c := m1.Slice(rows/2, rows, 0, rows/2) d := m1.Slice(rows/2, rows, rows/2, rows) // Break up m2 into submatrices from quadrant blocks // |e f| // |g h| e := m2.Slice(0, rows/2, 0, rows/2) f := m2.Slice(0, rows/2, rows/2, rows) g := m2.Slice(rows/2, rows, 0, rows/2) h := m2.Slice(rows/2, rows, rows/2, rows) // Calculate the 7 products: (elements matrix 1)*(elements matrix 2). // Resultants are used for intermediate step calculations, add/subtract. var resultant1 mat.Dense var resultant2 mat.Dense // p1 = a * (f-h) resultant1.Sub(f, h) p1 := strassensAlgorithm(a.(*mat.Dense), &resultant1) // p2 = (a+b) * h resultant1.Add(a, b) p2 := strassensAlgorithm(&resultant1, h.(*mat.Dense)) // p3 = (c+d) * e resultant1.Add(c, d) p3 := strassensAlgorithm(&resultant1, e.(*mat.Dense)) // p4 = d * (g-e) resultant1.Sub(g, e) p4 := strassensAlgorithm(d.(*mat.Dense), &resultant1) // p5 = (a+d) * (e+h) resultant1.Add(a, d) resultant2.Add(e, h) p5 := strassensAlgorithm(&resultant1, &resultant2) // p6 = (b-d) * (g+h) resultant1.Sub(b, d) resultant2.Add(g, h) p6 := strassensAlgorithm(&resultant1, &resultant2) // p7 = (a-c) * (e+f) resultant1.Sub(a, c) resultant2.Add(e, f) p7 := strassensAlgorithm(&resultant1, &resultant2) // Product matrix quadrants // |i j| // |k l| var i, j, k, l mat.Dense // i = p5 + p4 - p2 + p6 resultant1.Add(p5, p4) resultant2.Sub(&resultant1, p2) i.Add(&resultant2, p6) // j = p1 + p2 j.Add(p1, p2) // k = p3 + p4 k.Add(p3, p4) // l = p1 + p5 - p3 - p7 resultant1.Add(p1, p5) resultant2.Sub(&resultant1, p3) l.Sub(&resultant2, p7) // Build the product matrix var topHalf, bottomHalf mat.Dense topHalf.Augment(&i, &j) bottomHalf.Augment(&k, &l) productMatrix.Stack(&topHalf, &bottomHalf) return &productMatrix }
Stanford/03_DivideAndConquerModel/3B_StrassensSubcubicMatrixMultiplication/main.go
0.615088
0.425486
main.go
starcoder