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 assert
import (
"testing"
)
// Assertion是对testing.T进行了简单的封装。
// 可以以对象的方式调用包中的各个断言函数,
// 减少了参数t的传递。
type Assertion struct {
t *testing.T
}
// 返回Assertion对象。
func New(t *testing.T) *Assertion {
return &Assertion{t: t}
}
// 返回testing.T对象
func (a *Assertion) T() *testing.T {
return a.t
}
func (a *Assertion) True(expr bool, msg ...interface{}) *Assertion {
True(a.t, expr, msg...)
return a
}
func (a *Assertion) False(expr bool, msg ...interface{}) *Assertion {
False(a.t, expr, msg...)
return a
}
func (a *Assertion) Nil(expr interface{}, msg ...interface{}) *Assertion {
Nil(a.t, expr, msg...)
return a
}
func (a *Assertion) NotNil(expr interface{}, msg ...interface{}) *Assertion {
NotNil(a.t, expr, msg...)
return a
}
func (a *Assertion) Equal(v1, v2 interface{}, msg ...interface{}) *Assertion {
Equal(a.t, v1, v2, msg...)
return a
}
func (a *Assertion) NotEqual(v1, v2 interface{}, msg ...interface{}) *Assertion {
NotEqual(a.t, v1, v2, msg...)
return a
}
func (a *Assertion) Empty(expr interface{}, msg ...interface{}) *Assertion {
Empty(a.t, expr, msg...)
return a
}
func (a *Assertion) NotEmpty(expr interface{}, msg ...interface{}) *Assertion {
NotEmpty(a.t, expr, msg...)
return a
}
func (a *Assertion) Error(expr interface{}, msg ...interface{}) *Assertion {
Error(a.t, expr, msg...)
return a
}
func (a *Assertion) NotError(expr interface{}, msg ...interface{}) *Assertion {
NotError(a.t, expr, msg...)
return a
}
func (a *Assertion) FileExists(path string, msg ...interface{}) *Assertion {
FileExists(a.t, path, msg...)
return a
}
func (a *Assertion) FileNotExists(path string, msg ...interface{}) *Assertion {
FileNotExists(a.t, path, msg...)
return a
}
func (a *Assertion) Panic(fn func(), msg ...interface{}) *Assertion {
Panic(a.t, fn, msg...)
return a
}
func (a *Assertion) NotPanic(fn func(), msg ...interface{}) *Assertion {
NotPanic(a.t, fn, msg...)
return a
}
func (a *Assertion) Contains(container, item interface{}, msg ...interface{}) *Assertion {
Contains(a.t, container, item, msg...)
return a
}
func (a *Assertion) NotContains(container, item interface{}, msg ...interface{}) *Assertion {
NotContains(a.t, container, item, msg...)
return a
}
func (a *Assertion) StringEqual(s1, s2 string, style int, msg ...interface{}) *Assertion {
StringEqual(a.t, s1, s2, style, msg...)
return a
}
func (a *Assertion) StringNotEqual(s1, s2 string, style int, msg ...interface{}) *Assertion {
StringNotEqual(a.t, s1, s2, style, msg...)
return a
} | at-web/vendor/github.com/caixw/lib.go/assert/assertion.go | 0.507324 | 0.481393 | assertion.go | starcoder |
package ast
// Visitor defines the interface for iterating AST elements. The Visit function
// can return a Visitor w which will be used to visit the children of the AST
// element v. If the Visit function returns nil, the children will not be
// visited.
type Visitor interface {
Visit(v interface{}) (w Visitor)
}
// BeforeAndAfterVisitor wraps Visitor to provie hooks for being called before
// and after the AST has been visited.
type BeforeAndAfterVisitor interface {
Visitor
Before(x interface{})
After(x interface{})
}
// Walk iterates the AST by calling the Visit function on the Visitor
// v for x before recursing.
func Walk(v Visitor, x interface{}) {
wrapped, ok := v.(BeforeAndAfterVisitor)
if !ok {
wrapped = noopBeforeAndAfterVisitor{v}
}
WalkBeforeAndAfter(wrapped, x)
}
// WalkBeforeAndAfter iterates the AST by calling the Visit function on the
// Visitor v for x before recursing.
func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{}) {
v.Before(x)
defer v.After(x)
w := v.Visit(x)
if w == nil {
return
}
switch x := x.(type) {
case *Module:
Walk(w, x.Package)
for _, i := range x.Imports {
Walk(w, i)
}
for _, r := range x.Rules {
Walk(w, r)
}
for _, c := range x.Comments {
Walk(w, c)
}
case *Package:
Walk(w, x.Path)
case *Import:
Walk(w, x.Path)
Walk(w, x.Alias)
case *Rule:
Walk(w, x.Head)
Walk(w, x.Body)
if x.Else != nil {
Walk(w, x.Else)
}
case *Head:
Walk(w, x.Name)
Walk(w, x.Args)
if x.Key != nil {
Walk(w, x.Key)
}
if x.Value != nil {
Walk(w, x.Value)
}
case Body:
for _, e := range x {
Walk(w, e)
}
case Args:
for _, t := range x {
Walk(w, t)
}
case *Expr:
switch ts := x.Terms.(type) {
case *SomeDecl:
Walk(w, ts)
case []*Term:
for _, t := range ts {
Walk(w, t)
}
case *Term:
Walk(w, ts)
}
for i := range x.With {
Walk(w, x.With[i])
}
case *With:
Walk(w, x.Target)
Walk(w, x.Value)
case *Term:
Walk(w, x.Value)
case Ref:
for _, t := range x {
Walk(w, t)
}
case Object:
x.Foreach(func(k, v *Term) {
Walk(w, k)
Walk(w, v)
})
case Array:
for _, t := range x {
Walk(w, t)
}
case Set:
x.Foreach(func(t *Term) {
Walk(w, t)
})
case *ArrayComprehension:
Walk(w, x.Term)
Walk(w, x.Body)
case *ObjectComprehension:
Walk(w, x.Key)
Walk(w, x.Value)
Walk(w, x.Body)
case *SetComprehension:
Walk(w, x.Term)
Walk(w, x.Body)
case Call:
for _, t := range x {
Walk(w, t)
}
}
}
// WalkVars calls the function f on all vars under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkVars(x interface{}, f func(Var) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if v, ok := x.(Var); ok {
return f(v)
}
return false
}}
Walk(vis, x)
}
// WalkClosures calls the function f on all closures under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkClosures(x interface{}, f func(interface{}) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
switch x.(type) {
case *ArrayComprehension, *ObjectComprehension, *SetComprehension:
return f(x)
}
return false
}}
Walk(vis, x)
}
// WalkRefs calls the function f on all references under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkRefs(x interface{}, f func(Ref) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if r, ok := x.(Ref); ok {
return f(r)
}
return false
}}
Walk(vis, x)
}
// WalkTerms calls the function f on all terms under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkTerms(x interface{}, f func(*Term) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if term, ok := x.(*Term); ok {
return f(term)
}
return false
}}
Walk(vis, x)
}
// WalkWiths calls the function f on all with modifiers under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkWiths(x interface{}, f func(*With) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if w, ok := x.(*With); ok {
return f(w)
}
return false
}}
Walk(vis, x)
}
// WalkExprs calls the function f on all expressions under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkExprs(x interface{}, f func(*Expr) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if r, ok := x.(*Expr); ok {
return f(r)
}
return false
}}
Walk(vis, x)
}
// WalkBodies calls the function f on all bodies under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkBodies(x interface{}, f func(Body) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if b, ok := x.(Body); ok {
return f(b)
}
return false
}}
Walk(vis, x)
}
// WalkRules calls the function f on all rules under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkRules(x interface{}, f func(*Rule) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if r, ok := x.(*Rule); ok {
stop := f(r)
// NOTE(tsandall): since rules cannot be embedded inside of queries
// we can stop early if there is no else block.
if stop || r.Else == nil {
return true
}
}
return false
}}
Walk(vis, x)
}
// WalkNodes calls the function f on all nodes under x. If the function f
// returns true, AST nodes under the last node will not be visited.
func WalkNodes(x interface{}, f func(Node) bool) {
vis := &GenericVisitor{func(x interface{}) bool {
if n, ok := x.(Node); ok {
return f(n)
}
return false
}}
Walk(vis, x)
}
// GenericVisitor implements the Visitor interface to provide
// a utility to walk over AST nodes using a closure. If the closure
// returns true, the visitor will not walk over AST nodes under x.
type GenericVisitor struct {
f func(x interface{}) bool
}
// NewGenericVisitor returns a new GenericVisitor that will invoke the function
// f on AST nodes.
func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor {
return &GenericVisitor{f}
}
// Visit calls the function f on the GenericVisitor.
func (vis *GenericVisitor) Visit(x interface{}) Visitor {
if vis.f(x) {
return nil
}
return vis
}
// VarVisitor walks AST nodes under a given node and collects all encountered
// variables. The collected variables can be controlled by specifying
// VarVisitorParams when creating the visitor.
type VarVisitor struct {
params VarVisitorParams
vars VarSet
}
// VarVisitorParams contains settings for a VarVisitor.
type VarVisitorParams struct {
SkipRefHead bool
SkipRefCallHead bool
SkipObjectKeys bool
SkipClosures bool
SkipWithTarget bool
SkipSets bool
}
// NewVarVisitor returns a new VarVisitor object.
func NewVarVisitor() *VarVisitor {
return &VarVisitor{
vars: NewVarSet(),
}
}
// WithParams sets the parameters in params on vis.
func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor {
vis.params = params
return vis
}
// Vars returns a VarSet that contains collected vars.
func (vis *VarVisitor) Vars() VarSet {
return vis.vars
}
// Visit is called to walk the AST node v.
func (vis *VarVisitor) Visit(v interface{}) Visitor {
if vis.params.SkipObjectKeys {
if o, ok := v.(Object); ok {
o.Foreach(func(_, v *Term) {
Walk(vis, v)
})
return nil
}
}
if vis.params.SkipRefHead {
if r, ok := v.(Ref); ok {
for _, t := range r[1:] {
Walk(vis, t)
}
return nil
}
}
if vis.params.SkipClosures {
switch v.(type) {
case *ArrayComprehension, *ObjectComprehension, *SetComprehension:
return nil
}
}
if vis.params.SkipWithTarget {
if v, ok := v.(*With); ok {
Walk(vis, v.Value)
return nil
}
}
if vis.params.SkipSets {
if _, ok := v.(Set); ok {
return nil
}
}
if vis.params.SkipRefCallHead {
switch v := v.(type) {
case *Expr:
if terms, ok := v.Terms.([]*Term); ok {
for _, t := range terms[0].Value.(Ref)[1:] {
Walk(vis, t)
}
for i := 1; i < len(terms); i++ {
Walk(vis, terms[i])
}
for _, w := range v.With {
Walk(vis, w)
}
return nil
}
case Call:
operator := v[0].Value.(Ref)
for i := 1; i < len(operator); i++ {
Walk(vis, operator[i])
}
for i := 1; i < len(v); i++ {
Walk(vis, v[i])
}
return nil
}
}
if v, ok := v.(Var); ok {
vis.vars.Add(v)
}
return vis
}
type noopBeforeAndAfterVisitor struct {
Visitor
}
func (noopBeforeAndAfterVisitor) Before(interface{}) {}
func (noopBeforeAndAfterVisitor) After(interface{}) {} | vendor/github.com/open-policy-agent/opa/ast/visit.go | 0.722135 | 0.576184 | visit.go | starcoder |
Vitess
Vitess is an SQL middleware which turns MySQL/MariaDB into a fast, scalable and
highly-available distributed database.
For more information, visit http://www.vitess.io.
Example
Using this SQL driver is as simple as:
import (
"time"
"github.com/gitql/vitess/go/vt/vitessdriver"
)
func main() {
// Connect to vtgate.
db, err := vitessdriver.Open("localhost:15991", "keyspace", "master", 30*time.Second)
// Use "db" via the Golang sql interface.
}
For a full example, please see: https://github.com/gitql/vitess/blob/master/examples/local/client.go
The full example is based on our tutorial for running Vitess locally: http://vitess.io/getting-started/local-instance.html
Vtgate
This driver connects to a vtgate process. In Vitess, vtgate is a proxy server
that routes queries to the appropriate shards.
By decoupling the routing logic from the application, vtgate enables Vitess
features like consistent, application-transparent resharding:
When you scale up the number of shards, vtgate becomes aware of the new shards.
You do not have to update your application at all.
VTGate is capable of breaking up your query into parts, routing them to the
appropriate shards and combining the results, thereby giving the semblance
of a unified database.
The driver uses the V3 API which doesn't require you to specify routing
information. You just send the query as if Vitess was a regular database.
VTGate analyzes the query and uses additional metadata called VSchema
to perform the necessary routing. See the vtgate v3 Features doc for an overview:
https://github.com/gitql/vitess/blob/master/doc/VTGateV3Features.md
As of 12/2015, the VSchema creation is not documented yet as we are in the
process of simplifying the VSchema definition and the overall process for
creating one.
If you want to create your own VSchema, we recommend to have a
look at the VSchema from the vtgate v3 demo:
https://github.com/gitql/vitess/blob/master/examples/demo/schema
(The demo itself is interactive and can be run by executing "./run.py" in the
"examples/demo/" directory.)
The vtgate v3 design doc, which we will also update and simplify in the future,
contains more details on the VSchema:
https://github.com/gitql/vitess/blob/master/doc/V3VindexDesign.md
Isolation levels
The Vitess isolation model is different from the one exposed by a traditional database.
Isolation levels are controlled by connection parameters instead of Go's IsolationLevel.
You can perform master, replica or rdonly reads. Master reads give you read-after-write
consistency. Replica and rdonly reads give you eventual consistency. Replica reads
are for satisfying OLTP workloads while rdonly is for OLAP.
All transactions must be sent to the master where writes are allowed.
Replica and rdonly reads can only be performed outside of a transaction. So, there is
no concept of a read-only transaction in Vitess.
Consequently, no IsolationLevel must be specified while calling BeginContext. Doing so
will result in an error.
Named arguments
Vitess supports positional or named arguments. However, intermixing is not allowed
within a statement. If using named arguments, the ':' and '@' prefixes are optional.
If they're specified, the driver will strip them off before sending the request over
to VTGate.
*/
package vitessdriver | go/vt/vitessdriver/doc.go | 0.842215 | 0.656823 | doc.go | starcoder |
package qb
import (
"bytes"
)
// op specifies Cmd operation type.
type op byte
const (
eq op = iota
lt
leq
gt
geq
in
cnt
cntKey
like
)
// Cmp if a filtering comparator that is used in WHERE and IF clauses.
type Cmp struct {
op op
column string
value value
}
func (c Cmp) writeCql(cql *bytes.Buffer) (names []string) {
cql.WriteString(c.column)
switch c.op {
case eq:
cql.WriteByte('=')
case lt:
cql.WriteByte('<')
case leq:
cql.WriteByte('<')
cql.WriteByte('=')
case gt:
cql.WriteByte('>')
case geq:
cql.WriteByte('>')
cql.WriteByte('=')
case in:
cql.WriteString(" IN ")
case cnt:
cql.WriteString(" CONTAINS ")
case cntKey:
cql.WriteString(" CONTAINS KEY ")
case like:
cql.WriteString(" LIKE ")
}
return c.value.writeCql(cql)
}
// Eq produces column=?.
func Eq(column string) Cmp {
return Cmp{
op: eq,
column: column,
value: param(column),
}
}
// EqNamed produces column=? with a custom parameter name.
func EqNamed(column, name string) Cmp {
return Cmp{
op: eq,
column: column,
value: param(name),
}
}
// EqLit produces column=literal and does not add a parameter to the query.
func EqLit(column, literal string) Cmp {
return Cmp{
op: eq,
column: column,
value: lit(literal),
}
}
// EqFunc produces column=someFunc(?...).
func EqFunc(column string, fn *Func) Cmp {
return Cmp{
op: eq,
column: column,
value: fn,
}
}
// Lt produces column<?.
func Lt(column string) Cmp {
return Cmp{
op: lt,
column: column,
value: param(column),
}
}
// LtNamed produces column<? with a custom parameter name.
func LtNamed(column, name string) Cmp {
return Cmp{
op: lt,
column: column,
value: param(name),
}
}
// LtLit produces column<literal and does not add a parameter to the query.
func LtLit(column, literal string) Cmp {
return Cmp{
op: lt,
column: column,
value: lit(literal),
}
}
// LtFunc produces column<someFunc(?...).
func LtFunc(column string, fn *Func) Cmp {
return Cmp{
op: lt,
column: column,
value: fn,
}
}
// LtOrEq produces column<=?.
func LtOrEq(column string) Cmp {
return Cmp{
op: leq,
column: column,
value: param(column),
}
}
// LtOrEqNamed produces column<=? with a custom parameter name.
func LtOrEqNamed(column, name string) Cmp {
return Cmp{
op: leq,
column: column,
value: param(name),
}
}
// LtOrEqLit produces column<=literal and does not add a parameter to the query.
func LtOrEqLit(column, literal string) Cmp {
return Cmp{
op: leq,
column: column,
value: lit(literal),
}
}
// LtOrEqFunc produces column<=someFunc(?...).
func LtOrEqFunc(column string, fn *Func) Cmp {
return Cmp{
op: leq,
column: column,
value: fn,
}
}
// Gt produces column>?.
func Gt(column string) Cmp {
return Cmp{
op: gt,
column: column,
value: param(column),
}
}
// GtNamed produces column>? with a custom parameter name.
func GtNamed(column, name string) Cmp {
return Cmp{
op: gt,
column: column,
value: param(name),
}
}
// GtLit produces column>literal and does not add a parameter to the query.
func GtLit(column, literal string) Cmp {
return Cmp{
op: gt,
column: column,
value: lit(literal),
}
}
// GtFunc produces column>someFunc(?...).
func GtFunc(column string, fn *Func) Cmp {
return Cmp{
op: gt,
column: column,
value: fn,
}
}
// GtOrEq produces column>=?.
func GtOrEq(column string) Cmp {
return Cmp{
op: geq,
column: column,
value: param(column),
}
}
// GtOrEqNamed produces column>=? with a custom parameter name.
func GtOrEqNamed(column, name string) Cmp {
return Cmp{
op: geq,
column: column,
value: param(name),
}
}
// GtOrEqLit produces column>=literal and does not add a parameter to the query.
func GtOrEqLit(column, literal string) Cmp {
return Cmp{
op: geq,
column: column,
value: lit(literal),
}
}
// GtOrEqFunc produces column>=someFunc(?...).
func GtOrEqFunc(column string, fn *Func) Cmp {
return Cmp{
op: geq,
column: column,
value: fn,
}
}
// In produces column IN ?.
func In(column string) Cmp {
return Cmp{
op: in,
column: column,
value: param(column),
}
}
// InNamed produces column IN ? with a custom parameter name.
func InNamed(column, name string) Cmp {
return Cmp{
op: in,
column: column,
value: param(name),
}
}
// InLit produces column IN literal and does not add a parameter to the query.
func InLit(column, literal string) Cmp {
return Cmp{
op: in,
column: column,
value: lit(literal),
}
}
// Contains produces column CONTAINS ?.
func Contains(column string) Cmp {
return Cmp{
op: cnt,
column: column,
value: param(column),
}
}
// ContainsKey produces column CONTAINS KEY ?.
func ContainsKey(column string) Cmp {
return Cmp{
op: cntKey,
column: column,
value: param(column),
}
}
// ContainsNamed produces column CONTAINS ? with a custom parameter name.
func ContainsNamed(column, name string) Cmp {
return Cmp{
op: cnt,
column: column,
value: param(name),
}
}
// ContainsKeyNamed produces column CONTAINS KEY ? with a custom parameter name.
func ContainsKeyNamed(column, name string) Cmp {
return Cmp{
op: cntKey,
column: column,
value: param(name),
}
}
// ContainsLit produces column CONTAINS literal and does not add a parameter to the query.
func ContainsLit(column, literal string) Cmp {
return Cmp{
op: cnt,
column: column,
value: lit(literal),
}
}
// Like produces column LIKE ?.
func Like(column string) Cmp {
return Cmp{
op: like,
column: column,
value: param(column),
}
}
type cmps []Cmp
func (cs cmps) writeCql(cql *bytes.Buffer) (names []string) {
for i, c := range cs {
names = append(names, c.writeCql(cql)...)
if i < len(cs)-1 {
cql.WriteString(" AND ")
}
}
cql.WriteByte(' ')
return
}
type where cmps
func (w where) writeCql(cql *bytes.Buffer) (names []string) {
if len(w) == 0 {
return
}
cql.WriteString("WHERE ")
return cmps(w).writeCql(cql)
}
type _if cmps
func (w _if) writeCql(cql *bytes.Buffer) (names []string) {
if len(w) == 0 {
return
}
cql.WriteString("IF ")
return cmps(w).writeCql(cql)
} | qb/cmp.go | 0.613237 | 0.417093 | cmp.go | starcoder |
package flate
// We limit how far copy back-references can go, the same as the C++ code.
const maxOffset = 1 << 15
// emitLiteral writes a literal chunk and returns the number of bytes written.
func emitLiteral(dst *tokens, lit []byte) {
ol := dst.n
for i, v := range lit {
dst.tokens[i+ol] = token(v)
}
dst.n += len(lit)
}
// emitCopy writes a copy chunk and returns the number of bytes written.
func emitCopy(dst *tokens, offset, length int) {
dst.tokens[dst.n] = matchToken(uint32(length-3), uint32(offset-minOffsetSize))
dst.n++
}
// snappyEncode uses Snappy-like compression, but stores as Huffman
// blocks.
func snappyEncode(dst *tokens, src []byte) {
// Return early if src is short.
if len(src) <= 4 {
if len(src) != 0 {
emitLiteral(dst, src)
}
return
}
// Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
const maxTableSize = 1 << 14
shift, tableSize := uint(32-8), 1<<8
for tableSize < maxTableSize && tableSize < len(src) {
shift--
tableSize *= 2
}
var table [maxTableSize]int
var misses int
// Iterate over the source bytes.
var (
s int // The iterator position.
t int // The last position with the same hash as s.
lit int // The start position of any pending literal bytes.
)
for s+3 < len(src) {
// Update the hash table.
b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
p := &table[(h*0x1e35a7bd)>>shift]
// We need to to store values in [-1, inf) in table. To save
// some initialization time, (re)use the table's zero value
// and shift the values against this zero: add 1 on writes,
// subtract 1 on reads.
t, *p = *p-1, s+1
// If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
if t < 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
misses++
// Skip 1 byte for 16 consecutive missed.
s += 1 + (misses >> 4)
continue
}
// Otherwise, we have a match. First, emit any pending literal bytes.
if lit != s {
emitLiteral(dst, src[lit:s])
}
// Extend the match to be as long as possible.
s0 := s
s1 := s + maxMatchLength
if s1 > len(src) {
s1 = len(src)
}
s, t = s+4, t+4
for s < s1 && src[s] == src[t] {
s++
t++
}
misses = 0
// Emit the copied bytes.
// inlined: emitCopy(dst, s-t, s-s0)
dst.tokens[dst.n] = matchToken(uint32(s-s0-3), uint32(s-t-minOffsetSize))
dst.n++
lit = s
}
// Emit any final pending literal bytes and return.
if lit != len(src) {
emitLiteral(dst, src[lit:])
}
} | Godeps/_workspace/src/github.com/klauspost/compress/flate/snappy.go | 0.72086 | 0.538437 | snappy.go | starcoder |
以下为基本格式,
File header section
The file header contains the basic properties of the image.
Table 2–7: File header
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Length | Name | Description |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 4 bytes | Signature | Always equal to 8BPS. Do not try to read the file if the signature does not match this value. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 2 bytes | Version | Always equal to 1. Do not try to read the file if the version does not match this value. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 6 bytes | Reserved | Must be zero. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 2 bytes | Channels | The number of channels in the image, including any alpha chan-nels. Supported range is 1 to 24. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 4 bytes | Rows | The height of the image in pixels. Supported range is 1 to 30,000. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 4 bytes | Columns | The width of the image in pixels. Supported range is 1 to 30,000. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 2 bytes | Depth | The number of bits per channel. Supported values are 1, 8, and 16. |
|-----------|---------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 2 bytes | Mode | The color mode of the file. Supported values are: Bitmap=0; Grayscale=1; Indexed=2; RGB=3; CMYK=4; Multichannel=7; Duotone=8; Lab=9. |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
Table 2–8: Color mode data
|---------------------------------------------------------------------|
| Length | Name | Description |
|----------|-------------|--------------------------------------------|
| 4 bytes | Length | The length of the following color data. |
|----------|-------------|--------------------------------------------|
| Variable | Color data | The color data. |
|---------------------------------------------------------------------|
Table 2–9: Image resources
|---------------------------------------------------------------------|
| Length | Name | Description |
|-----------|------------|--------------------------------------------|
| 4 bytes | Length | Length of image resource section. |
|-----------|------------|--------------------------------------------|
| Variable | Resources Image resources |
|---------------------------------------------------------------------|
Table 2–10: Layer and mask information
|--------------------------------------------------------------------------|
| Length | Name | Description |
|-----------|------------|-------------------------------------------------|
| 4 bytes | Length | Length of the miscellaneous information section.|
|-----------|------------|-------------------------------------------------|
| Variable | Layers | Layer info. See table 2–12. |
|-----------|------------|-------------------------------------------------|
| Variable | Global | Global layer mask info. See table 2–19. |
| | layer mask | |
|--------------------------------------------------------------------------|
Table 2–11: Image data
|----------------------------------------------------------------------------------|
| Length | Name | Description |
|-----------|--------------|-------------------------------------------------------|
| 2 bytes | Compression | Compression method. Raw data = 0, RLE compressed = 1. |
|-----------|--------------|-------------------------------------------------------|
| Variable | Data | The image data. Planar order = RRR GGG BBB, etc |
|----------------------------------------------------------------------------------|
*/
package main
import (
"bytes"
"encoding/binary"
"io"
"io/ioutil"
"unsafe"
"runtime"
"errors"
"github.com/dollarkillerx/govcl/vcl"
"github.com/dollarkillerx/govcl/vcl/types"
)
// psd文件读取,将psd转为一个TBitmap
const (
MODE_BITMAP = 0
MODE_GRAYSCALE = 1
MODE_INDEXED = 2
MODE_RGB = 3
MODE_CMYK = 4
MODE_MULTICHANNEL = 7
MODE_DUOTONE = 8
MODE_LAB = 9
MAX_PSD_CHANNELS = 24
)
// PsdToBitmap psd文件转bmp格式
func PsdToBitmap(aFileName string, bmp *vcl.TBitmap) error {
if bmp == nil || !bmp.IsValid() {
return errors.New("bmp不能为空!")
}
// 文件签名
var psdSignature = []byte{0x38, 0x42, 0x50, 0x53} // 8BPS
// 读入文件
bs, err := ioutil.ReadFile(aFileName)
if err != nil {
return err
}
buffer := bytes.NewReader(bs)
// 签名
signature := make([]byte, 4)
binary.Read(buffer, binary.BigEndian, signature)
if bytes.Compare(signature, psdSignature) != 0 {
return errors.New("签名错误!")
}
// 版本
var version uint16
binary.Read(buffer, binary.BigEndian, &version)
if version != 1 {
return errors.New("版本错误,必须等于1!")
}
// 跳过
buffer.Seek(6, io.SeekCurrent)
// 通道 支持 1 to 24.
var ChannelCount uint16
binary.Read(buffer, binary.BigEndian, &ChannelCount)
if ChannelCount <= 0 || ChannelCount > MAX_PSD_CHANNELS {
return errors.New("通道总数不正确!")
}
// 读size
var width, height uint32
binary.Read(buffer, binary.BigEndian, &height)
binary.Read(buffer, binary.BigEndian, &width)
if width <= 0 || height <= 0 {
return errors.New("读宽度或者高度错误!")
}
// 每个通道的位数, 支持1,8和16
var bitsPerChannel uint16
binary.Read(buffer, binary.BigEndian, &bitsPerChannel)
if bitsPerChannel != 8 {
return errors.New("每个通道的位数错误,只支持8!")
}
// 颜色模式
var colorMode uint16
binary.Read(buffer, binary.BigEndian, &colorMode)
if colorMode != MODE_RGB {
return errors.New("颜色模式错误,只支持RGB!")
}
// 颜色数据,跳过
var colorDataLen uint32
binary.Read(buffer, binary.BigEndian, &colorDataLen)
buffer.Seek(int64(colorDataLen), io.SeekCurrent)
// 图片资源,跳过
var imageResoucesLen uint32
binary.Read(buffer, binary.BigEndian, &imageResoucesLen)
buffer.Seek(int64(imageResoucesLen), io.SeekCurrent)
// 全局层掩码信息,跳过
var globalLayerMaskInfoLen uint32
binary.Read(buffer, binary.BigEndian, &globalLayerMaskInfoLen)
buffer.Seek(int64(globalLayerMaskInfoLen), io.SeekCurrent)
// 压缩模式 Raw=0, RLE=1
var compressionType uint16
binary.Read(buffer, binary.BigEndian, &compressionType)
if compressionType != 0 && compressionType != 1 {
return errors.New("不支持的压缩格式,当前只支持模式为0或者1")
}
// 读数据
psdPixels := make([]byte, width*height*4)
unPackPSD(buffer, width, height, psdPixels, ChannelCount, compressionType)
bmp.SetPixelFormat(types.Pf32bit)
bmp.SetSize(int32(width), int32(height))
if runtime.GOOS == "windows" || runtime.GOOS == "linux" {
for h := int(height - 1); h >= 0; h-- {
ptr := bmp.ScanLine(int32(h))
for w := 0; w < int(width*4); w++ {
index := h*(int(width)*4) + w
*(*byte)(unsafe.Pointer(ptr + uintptr(w))) = psdPixels[index]
}
}
} else {
// 填充,左下角为起点
for h := int(height - 1); h >= 0; h-- {
ptr := bmp.ScanLine(int32(h))
for w := 0; w < int(width); w++ {
index := (h*int(width) + w) * 4
*(*byte)(unsafe.Pointer(ptr + uintptr(w*4))) = psdPixels[index+3]
*(*byte)(unsafe.Pointer(ptr + uintptr(w*4+1))) = psdPixels[index+2]
*(*byte)(unsafe.Pointer(ptr + uintptr(w*4+2))) = psdPixels[index+1]
*(*byte)(unsafe.Pointer(ptr + uintptr(w*4+3))) = psdPixels[index]
}
}
}
return nil
}
// 解包psd文件
func unPackPSD(buffer *bytes.Reader, width, height uint32, pixels []byte, channelCount, compressionType uint16) {
var (
channelArr = []byte{2, 1, 0, 3}
defaultArr = []byte{0, 0, 0, 255}
)
pixelCount := width * height
if compressionType == 1 {
buffer.Seek(int64(height*uint32(channelCount)*2), io.SeekCurrent)
for c := 0; c <= 3; c++ {
n := 0
channel := channelArr[c]
if uint16(channel) >= channelCount {
for n = 0; n < int(pixelCount); n++ {
pixels[n*4+int(channel)] = defaultArr[channel]
}
} else { // 非压缩
count := 0
for count < int(pixelCount) {
nlen, _ := buffer.ReadByte()
if nlen == 128 {
// 啥也不做
} else if nlen < 128 { // 非RLE
nlen++
count += int(nlen)
for nlen != 0 {
pixels[n*4+int(channel)], _ = buffer.ReadByte()
n++
nlen--
}
} else if nlen > 128 { // RLE
nlen = nlen ^ 0xFF
nlen += 2
val, _ := buffer.ReadByte()
count += int(nlen)
for nlen != 0 {
pixels[n*4+int(channel)] = val
n++
nlen--
}
}
}
}
}
} else {
for c := 0; c <= 3; c++ {
channel := channelArr[c]
if uint16(channel) > channelCount {
for n := 0; n < int(pixelCount); n++ {
pixels[n*4+int(channel)] = defaultArr[channel]
}
} else {
for n := 0; n < int(pixelCount); n++ {
pixels[n*4+int(channel)], _ = buffer.ReadByte()
}
}
}
}
} | imageviewer/psdReader.go | 0.58261 | 0.605391 | psdReader.go | starcoder |
package SQLParser
func (this *StatementsParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitStatementsParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *StatementParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitStatementParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QueryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQueryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *WithParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitWithParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TableElementParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTableElementParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ColumnDefinitionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitColumnDefinitionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *LikeClauseParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitLikeClauseParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TablePropertiesParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTablePropertiesParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TablePropertyParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTablePropertyParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QueryNoWithParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQueryNoWithParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QueryTermParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQueryTermParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QueryPrimaryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQueryPrimaryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SortItemParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSortItemParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QuerySpecificationParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQuerySpecificationParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *GroupByParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitGroupByParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *GroupingElementParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitGroupingElementParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *GroupingExpressionsParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitGroupingExpressionsParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *GroupingSetParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitGroupingSetParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *NamedQueryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitNamedQueryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SelectItemParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSelectItemParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *RelationParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitRelationParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *JoinCriteriaParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitJoinCriteriaParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SampledRelationParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSampledRelationParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *AliasedRelationParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitAliasedRelationParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ColumnAliasesParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitColumnAliasesParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *RelationPrimaryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitRelationPrimaryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ExpressionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitExpressionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *BooleanExpressionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitBooleanExpressionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *PredicateParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitPredicateParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ComparisonParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitComparisonParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QuantifiedComparisonParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQuantifiedComparisonParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *BetweenParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitBetweenParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *InListParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitInListParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *InSubqueryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitInSubqueryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *LikeParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitLikeParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *NullPredicateParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitNullPredicateParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *DistinctFromParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitDistinctFromParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ValueExpressionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitValueExpressionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *AtTimeZoneParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitAtTimeZoneParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ArithmeticUnaryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitArithmeticUnaryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ArithmeticBinaryParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitArithmeticBinaryParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ConcatenationParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitConcatenationParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *PrimaryExpressionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitPrimaryExpressionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *FunctionCallParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitFunctionCallParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *LambdaParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitLambdaParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SimpleCaseParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSimpleCaseParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SearchedCaseParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSearchedCaseParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *CastParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitCastParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SubscriptParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSubscriptParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *DereferenceParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitDereferenceParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SpecialDateTimeFunctionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSpecialDateTimeFunctionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *SubstringParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitSubstringParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *NormalizeParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitNormalizeParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ExtractParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitExtractParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TimeZoneSpecifierParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTimeZoneSpecifierParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ComparisonOperatorParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitComparisonOperatorParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ComparisonQuantifierParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitComparisonQuantifierParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *IntervalParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitIntervalParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *IntervalFieldParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitIntervalFieldParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TypeTParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTypeTParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TypeParameterParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTypeParameterParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *BaseTypeParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitBaseTypeParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *WhenParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitWhenParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *FilterParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitFilterParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *OverParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitOverParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *WindowFrameParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitWindowFrameParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *FrameBoundParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitFrameBoundParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *ExplainOptionParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitExplainOptionParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *TransactionModeParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitTransactionModeParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *LevelOfIsolationParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitLevelOfIsolationParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *CallArgParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitCallArgParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *PrivilegeParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitPrivilegeParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *QualifiedNameParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitQualifiedNameParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *IDParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitIDParse(this)
default:
return t.VisitChildren(this)
}
}
func (this *NonReservedParse) Accept(visitor IMSTreeVisitor) interface{} {
switch t := visitor.(type) {
case ISQLQueryTreeVisitor:
return t.VisitNonReservedParse(this)
default:
return t.VisitChildren(this)
}
}
type ISQLQueryTreeVisitor interface {
IMSTreeVisitor
VisitStatementsParse(ctx *StatementsParse) interface{}
VisitStatementParse(ctx *StatementParse) interface{}
VisitQueryParse(ctx *QueryParse) interface{}
VisitWithParse(ctx *WithParse) interface{}
VisitTableElementParse(ctx *TableElementParse) interface{}
VisitColumnDefinitionParse(ctx *ColumnDefinitionParse) interface{}
VisitLikeClauseParse(ctx *LikeClauseParse) interface{}
VisitTablePropertiesParse(ctx *TablePropertiesParse) interface{}
VisitTablePropertyParse(ctx *TablePropertyParse) interface{}
VisitQueryNoWithParse(ctx *QueryNoWithParse) interface{}
VisitQueryTermParse(ctx *QueryTermParse) interface{}
VisitQueryPrimaryParse(ctx *QueryPrimaryParse) interface{}
VisitSortItemParse(ctx *SortItemParse) interface{}
VisitQuerySpecificationParse(ctx *QuerySpecificationParse) interface{}
VisitGroupByParse(ctx *GroupByParse) interface{}
VisitGroupingElementParse(ctx *GroupingElementParse) interface{}
VisitGroupingExpressionsParse(ctx *GroupingExpressionsParse) interface{}
VisitGroupingSetParse(ctx *GroupingSetParse) interface{}
VisitNamedQueryParse(ctx *NamedQueryParse) interface{}
VisitSelectItemParse(ctx *SelectItemParse) interface{}
VisitRelationParse(ctx *RelationParse) interface{}
VisitJoinCriteriaParse(ctx *JoinCriteriaParse) interface{}
VisitSampledRelationParse(ctx *SampledRelationParse) interface{}
VisitAliasedRelationParse(ctx *AliasedRelationParse) interface{}
VisitColumnAliasesParse(ctx *ColumnAliasesParse) interface{}
VisitRelationPrimaryParse(ctx *RelationPrimaryParse) interface{}
VisitExpressionParse(ctx *ExpressionParse) interface{}
VisitBooleanExpressionParse(ctx *BooleanExpressionParse) interface{}
VisitPredicateParse(ctx *PredicateParse) interface{}
VisitComparisonParse(ctx *ComparisonParse) interface{}
VisitQuantifiedComparisonParse(ctx *QuantifiedComparisonParse) interface{}
VisitBetweenParse(ctx *BetweenParse) interface{}
VisitInListParse(ctx *InListParse) interface{}
VisitInSubqueryParse(ctx *InSubqueryParse) interface{}
VisitLikeParse(ctx *LikeParse) interface{}
VisitNullPredicateParse(ctx *NullPredicateParse) interface{}
VisitDistinctFromParse(ctx *DistinctFromParse) interface{}
VisitValueExpressionParse(ctx *ValueExpressionParse) interface{}
VisitAtTimeZoneParse(ctx *AtTimeZoneParse) interface{}
VisitArithmeticUnaryParse(ctx *ArithmeticUnaryParse) interface{}
VisitArithmeticBinaryParse(ctx *ArithmeticBinaryParse) interface{}
VisitConcatenationParse(ctx *ConcatenationParse) interface{}
VisitPrimaryExpressionParse(ctx *PrimaryExpressionParse) interface{}
VisitFunctionCallParse(ctx *FunctionCallParse) interface{}
VisitLambdaParse(ctx *LambdaParse) interface{}
VisitSimpleCaseParse(ctx *SimpleCaseParse) interface{}
VisitSearchedCaseParse(ctx *SearchedCaseParse) interface{}
VisitCastParse(ctx *CastParse) interface{}
VisitSubscriptParse(ctx *SubscriptParse) interface{}
VisitDereferenceParse(ctx *DereferenceParse) interface{}
VisitSpecialDateTimeFunctionParse(ctx *SpecialDateTimeFunctionParse) interface{}
VisitSubstringParse(ctx *SubstringParse) interface{}
VisitNormalizeParse(ctx *NormalizeParse) interface{}
VisitExtractParse(ctx *ExtractParse) interface{}
VisitTimeZoneSpecifierParse(ctx *TimeZoneSpecifierParse) interface{}
VisitComparisonOperatorParse(ctx *ComparisonOperatorParse) interface{}
VisitComparisonQuantifierParse(ctx *ComparisonQuantifierParse) interface{}
VisitIntervalParse(ctx *IntervalParse) interface{}
VisitIntervalFieldParse(ctx *IntervalFieldParse) interface{}
VisitTypeTParse(ctx *TypeTParse) interface{}
VisitTypeParameterParse(ctx *TypeParameterParse) interface{}
VisitBaseTypeParse(ctx *BaseTypeParse) interface{}
VisitWhenParse(ctx *WhenParse) interface{}
VisitFilterParse(ctx *FilterParse) interface{}
VisitOverParse(ctx *OverParse) interface{}
VisitWindowFrameParse(ctx *WindowFrameParse) interface{}
VisitFrameBoundParse(ctx *FrameBoundParse) interface{}
VisitExplainOptionParse(ctx *ExplainOptionParse) interface{}
VisitTransactionModeParse(ctx *TransactionModeParse) interface{}
VisitLevelOfIsolationParse(ctx *LevelOfIsolationParse) interface{}
VisitCallArgParse(ctx *CallArgParse) interface{}
VisitPrivilegeParse(ctx *PrivilegeParse) interface{}
VisitQualifiedNameParse(ctx *QualifiedNameParse) interface{}
VisitIDParse(ctx *IDParse) interface{}
VisitNonReservedParse(ctx *NonReservedParse) interface{}
}
type BaseSQLQueryTreeVisitor struct {
*BaseMSTreeVisitor
}
var _ ISQLQueryTreeVisitor = &BaseSQLQueryTreeVisitor{}
func (this *BaseSQLQueryTreeVisitor) Visit(tree IMSTree) interface{} {
return tree.Accept(this)
}
func (this *BaseSQLQueryTreeVisitor) VisitChildren(tree IMSTree) interface{} {
for _, child := range tree.GetChildren() {
retval := child.Accept(this)
if retval != nil {
return retval
}
}
return nil
}
func (this *BaseSQLQueryTreeVisitor) VisitStatementsParse(ctx *StatementsParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitStatementParse(ctx *StatementParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQueryParse(ctx *QueryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitWithParse(ctx *WithParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTableElementParse(ctx *TableElementParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitColumnDefinitionParse(ctx *ColumnDefinitionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitLikeClauseParse(ctx *LikeClauseParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTablePropertiesParse(ctx *TablePropertiesParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTablePropertyParse(ctx *TablePropertyParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQueryNoWithParse(ctx *QueryNoWithParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQueryTermParse(ctx *QueryTermParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQueryPrimaryParse(ctx *QueryPrimaryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSortItemParse(ctx *SortItemParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQuerySpecificationParse(ctx *QuerySpecificationParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitGroupByParse(ctx *GroupByParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitGroupingElementParse(ctx *GroupingElementParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitGroupingExpressionsParse(ctx *GroupingExpressionsParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitGroupingSetParse(ctx *GroupingSetParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitNamedQueryParse(ctx *NamedQueryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSelectItemParse(ctx *SelectItemParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitRelationParse(ctx *RelationParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitJoinCriteriaParse(ctx *JoinCriteriaParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSampledRelationParse(ctx *SampledRelationParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitAliasedRelationParse(ctx *AliasedRelationParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitColumnAliasesParse(ctx *ColumnAliasesParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitRelationPrimaryParse(ctx *RelationPrimaryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitExpressionParse(ctx *ExpressionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitBooleanExpressionParse(ctx *BooleanExpressionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitPredicateParse(ctx *PredicateParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitComparisonParse(ctx *ComparisonParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQuantifiedComparisonParse(ctx *QuantifiedComparisonParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitBetweenParse(ctx *BetweenParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitInListParse(ctx *InListParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitInSubqueryParse(ctx *InSubqueryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitLikeParse(ctx *LikeParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitNullPredicateParse(ctx *NullPredicateParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitDistinctFromParse(ctx *DistinctFromParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitValueExpressionParse(ctx *ValueExpressionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitAtTimeZoneParse(ctx *AtTimeZoneParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitArithmeticUnaryParse(ctx *ArithmeticUnaryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitArithmeticBinaryParse(ctx *ArithmeticBinaryParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitConcatenationParse(ctx *ConcatenationParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitPrimaryExpressionParse(ctx *PrimaryExpressionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitFunctionCallParse(ctx *FunctionCallParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitLambdaParse(ctx *LambdaParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSimpleCaseParse(ctx *SimpleCaseParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSearchedCaseParse(ctx *SearchedCaseParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitCastParse(ctx *CastParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSubscriptParse(ctx *SubscriptParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitDereferenceParse(ctx *DereferenceParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSpecialDateTimeFunctionParse(ctx *SpecialDateTimeFunctionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitSubstringParse(ctx *SubstringParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitNormalizeParse(ctx *NormalizeParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitExtractParse(ctx *ExtractParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTimeZoneSpecifierParse(ctx *TimeZoneSpecifierParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitComparisonOperatorParse(ctx *ComparisonOperatorParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitComparisonQuantifierParse(ctx *ComparisonQuantifierParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitIntervalParse(ctx *IntervalParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitIntervalFieldParse(ctx *IntervalFieldParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTypeTParse(ctx *TypeTParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTypeParameterParse(ctx *TypeParameterParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitBaseTypeParse(ctx *BaseTypeParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitWhenParse(ctx *WhenParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitFilterParse(ctx *FilterParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitOverParse(ctx *OverParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitWindowFrameParse(ctx *WindowFrameParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitFrameBoundParse(ctx *FrameBoundParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitExplainOptionParse(ctx *ExplainOptionParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitTransactionModeParse(ctx *TransactionModeParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitLevelOfIsolationParse(ctx *LevelOfIsolationParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitCallArgParse(ctx *CallArgParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitPrivilegeParse(ctx *PrivilegeParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitQualifiedNameParse(ctx *QualifiedNameParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitIDParse(ctx *IDParse) interface{} {
return this.VisitChildren(ctx)
}
func (this *BaseSQLQueryTreeVisitor) VisitNonReservedParse(ctx *NonReservedParse) interface{} {
return this.VisitChildren(ctx)
} | SQLParser/visitorcodegenerated.go | 0.661267 | 0.441191 | visitorcodegenerated.go | starcoder |
package redis
import (
_mock "github.com/stretchr/testify/mock"
)
type Mock struct {
_mock.Mock
}
func (r *Mock) Ping() error {
return r.Called().Error(0)
}
//--- Keys
func (r *Mock) Exists(key string) bool {
return r.Called(key).Bool(0)
}
func (r *Mock) Keys(pattern string) []string {
return r.Called(pattern).Get(0).([]string)
}
func (r *Mock) Expire(key string, seconds int64) error {
return r.Called(key, seconds).Error(0)
}
func (r *Mock) Persist(key string) error {
return r.Called(key).Error(0)
}
func (r *Mock) Del(key string) error {
return r.Called(key).Error(0)
}
func (r *Mock) Dump(key string) string {
return r.Called(key).String(0)
}
//--- Strings
func (r *Mock) Get(key string) string {
return r.Called(key).String(0)
}
func (r *Mock) Set(key string, value interface{}) error {
return r.Called(key, value).Error(0)
}
func (r *Mock) Setex(key string, value interface{}, seconds int64) error {
return r.Called(key, value, seconds).Error(0)
}
func (r *Mock) SetNX(key string, value interface{}) error {
return r.Called(key, value).Error(0)
}
func (r *Mock) SetNXex(key string, value interface{}, seconds int64) error {
return r.Called(key, value, seconds).Error(0)
}
func (r *Mock) Increment(key string) error {
return r.Called(key).Error(0)
}
func (r *Mock) Decrement(key string) error {
return r.Called(key).Error(0)
}
//--- Hashes
func (r *Mock) HGet(key, field string) string {
return r.Called(key, field).String(0)
}
func (r *Mock) HGetAll(key string) map[string]string {
return r.Called(key).Get(0).(map[string]string)
}
func (r *Mock) HSet(key string, fieldvalue ...interface{}) error {
return r.Called(key, fieldvalue).Error(0)
}
func (r *Mock) HSetNX(key, field string, value interface{}) error {
return r.Called(key, field, value).Error(0)
}
func (r *Mock) HVals(key string) []string {
return r.Called(key).Get(0).([]string)
}
func (r *Mock) HDel(key, field string) error {
return r.Called(key, field).Error(0)
}
func (r *Mock) HExists(key, field string) bool {
return r.Called(key, field).Bool(0)
}
//--- Sets
func (r *Mock) SAdd(key string, values ...interface{}) error {
return r.Called(key, values).Error(0)
}
func (r *Mock) SMembers(key string) []string {
return r.Called(key).Get(0).([]string)
}
func (r *Mock) SRem(key string, members ...interface{}) error {
return r.Called(key, members).Error(0)
}
func (r *Mock) ZAdd(key string, values ...interface{}) error {
return r.Called(key, values).Error(0)
}
func (r *Mock) ZMembers(key string) []string {
return r.Called(key).Get(0).([]string)
}
func (r *Mock) ZRem(key string, members ...interface{}) error {
return r.Called(key, members).Error(0)
} | cache/redis/redis_mock.go | 0.7874 | 0.487612 | redis_mock.go | starcoder |
package pixelate
import (
"image"
"image/color"
"math"
"hawx.me/code/img/channel"
"hawx.me/code/img/utils"
)
// Vxl pixelates the Image into isometric cubes. It averages the colours and
// naïvely darkens and lightens the colours to mimic highlight and shade.
func Vxl(img image.Image, height int, flip bool, top, left, right float64) image.Image {
b := img.Bounds()
pixelHeight := height
pixelWidth := int(math.Sqrt(3.0) * float64(pixelHeight) / 2.0)
cols := b.Dx() / pixelWidth
rows := b.Dy() / pixelHeight
// intersection of lines
c := float64(pixelHeight) / 2
// gradient of lines
k := math.Sqrt(3.0) / 3.0
o := image.NewRGBA(image.Rect(0, 0, pixelWidth*cols, pixelHeight*rows))
// See: http://www.flickr.com/photos/hawx-/8466236036/
inTopSquare := func(x, y float64) bool {
if !flip {
y *= -1
}
return y <= -k*x+c && y >= k*x && y >= -k*x && y <= k*x+c
}
inBottomRight := func(x, y float64) bool {
if !flip {
y *= -1
}
return x >= 0 && y <= k*x && y >= k*x-c
}
inBottomLeft := func(x, y float64) bool {
if !flip {
y *= -1
}
return x <= 0 && y <= -k*x && y >= -k*x-c
}
inHexagon := func(x, y float64) bool {
return inTopSquare(x, y) || inBottomRight(x, y) || inBottomLeft(x, y)
}
topL := channel.AdjustC(utils.Multiplier(top), channel.Lightness)
rightL := channel.AdjustC(utils.Multiplier(right), channel.Lightness)
leftL := channel.AdjustC(utils.Multiplier(left), channel.Lightness)
for col := 0; col < cols; col++ {
for row := 0; row < rows; row++ {
seen := []color.Color{}
for y := 0; y < pixelHeight; y++ {
for x := 0; x < pixelWidth; x++ {
realY := row*(pixelHeight+int(c)) + y
realX := col*pixelWidth + x
pixel := img.At(realX, realY)
yOrigin := float64(y - pixelHeight/2)
xOrigin := float64(x - pixelWidth/2)
if inHexagon(xOrigin, yOrigin) {
seen = append(seen, pixel)
}
}
}
average := utils.Average(seen...)
for y := 0; y < pixelHeight; y++ {
for x := 0; x < pixelWidth; x++ {
realY := row*(pixelHeight+int(c)) + y
realX := col*pixelWidth + x
yOrigin := float64(y - pixelHeight/2)
xOrigin := float64(x - pixelWidth/2)
// This stops white bits showing above the top squares. It does mean
// the dimensions aren't perfect, but what did you expect with pixels
// and trig. It is inefficient though, maybe fix that later?
if (!flip && yOrigin < 0) || (flip && yOrigin > 0) {
o.Set(realX, realY, topL(average))
} else {
if xOrigin > 0 {
o.Set(realX, realY, rightL(average))
} else {
o.Set(realX, realY, leftL(average))
}
}
if inTopSquare(xOrigin, yOrigin) {
o.Set(realX, realY, topL(average))
}
if inBottomRight(xOrigin, yOrigin) {
o.Set(realX, realY, rightL(average))
}
if inBottomLeft(xOrigin, yOrigin) {
o.Set(realX, realY, leftL(average))
}
}
}
}
}
offsetY := (pixelHeight + int(c)) / 2.0
offsetX := pixelWidth / 2
for col := -1; col < cols; col++ {
for row := -1; row < rows; row++ {
seen := []color.Color{}
for y := 0; y < pixelHeight; y++ {
for x := 0; x < pixelWidth; x++ {
realY := row*(pixelHeight+int(c)) + y + offsetY
realX := col*pixelWidth + x + offsetX
if image.Pt(realX, realY).In(b) {
pixel := img.At(realX, realY)
yOrigin := float64(y - pixelHeight/2)
xOrigin := float64(x - pixelWidth/2)
if inHexagon(xOrigin, yOrigin) {
seen = append(seen, pixel)
}
}
}
}
if len(seen) <= 0 {
continue
}
average := utils.Average(seen...)
for y := 0; y < pixelHeight; y++ {
for x := 0; x < pixelWidth; x++ {
realY := row*(pixelHeight+int(c)) + y + offsetY
realX := col*pixelWidth + x + offsetX
yOrigin := float64(y - pixelHeight/2)
xOrigin := float64(x - pixelWidth/2)
if inTopSquare(xOrigin, yOrigin) {
o.Set(realX, realY, topL(average))
}
if inBottomRight(xOrigin, yOrigin) {
o.Set(realX, realY, rightL(average))
}
if inBottomLeft(xOrigin, yOrigin) {
o.Set(realX, realY, leftL(average))
}
}
}
}
}
return o
} | pixelate/vxl.go | 0.724481 | 0.495911 | vxl.go | starcoder |
package iso20022
// Specifies rates related to a corporate action option.
type CorporateActionRate5 struct {
// Rate used for additional tax that cannot be categorised.
AdditionalTax *RateAndAmountFormat3Choice `xml:"AddtlTax,omitempty"`
// Rate used to calculate the amount of the charges/fees that cannot be categorised.
ChargesFees *RateAndAmountFormat3Choice `xml:"ChrgsFees,omitempty"`
// Dividend is final.
FinalDividendRate *RateAndAmountFormat4Choice `xml:"FnlDvddRate,omitempty"`
// Percentage of fiscal tax to apply.
FiscalStamp *RateFormat2Choice `xml:"FsclStmp,omitempty"`
// Rate resulting from a fully franked dividend paid by a company; rate includes tax credit for companies that have made sufficient tax payments during fiscal period.
FullyFrankedRate *RateAndAmountFormat3Choice `xml:"FullyFrnkdRate,omitempty"`
// Cash dividend amount per equity before deductions or allowances have been made.
GrossDividendRate []*GrossDividendRateFormat1Choice `xml:"GrssDvddRate,omitempty"`
// Rate of the cash premium made available if the securities holder consents or participates to an event, for example, consent fees.
CashIncentiveRate *RateFormat2Choice `xml:"CshIncntivRate,omitempty"`
// Public index rate applied to the amount paid to adjust it to inflation.
IndexFactor *RateAndAmountFormat3Choice `xml:"IndxFctr,omitempty"`
// The actual interest rate used for the payment of the interest for the specified interest period.
// Usage guideline: It is used to provide the applicable rate for the current payment, after all calculations have been performed, that is, application of period and method of interest computation.
InterestRateUsedForPayment []*InterestRateUsedForPaymentFormat1Choice `xml:"IntrstRateUsdForPmt,omitempty"`
// Cash dividend amount per equity after deductions or allowances have been made.
NetDividendRate []*NetDividendRateFormat1Choice `xml:"NetDvddRate,omitempty"`
// Rate per share to which a non-resident is entitled.
NonResidentRate *RateAndAmountFormat3Choice `xml:"NonResdtRate,omitempty"`
// Maximum percentage of shares available through the over subscription privilege, usually a percentage of the basic subscription shares, for example, an account owner subscribing to 100 shares may over subscribe to a maximum of 50 additional shares when the over subscription maximum is 50 percent.
MaximumAllowedOversubscriptionRate *RateFormat2Choice `xml:"MaxAllwdOvrsbcptRate,omitempty"`
// Dividend is provisional.
ProvisionalDividendRate *RateAndAmountFormat4Choice `xml:"PrvsnlDvddRate,omitempty"`
// Amount of money per equity allocated as the result of a tax credit.
TaxCreditRate []*TaxCreditRateFormat1Choice `xml:"TaxCdtRate,omitempty"`
// Proportionate allocation used for the offer.
ProrationRate *RateFormat2Choice `xml:"PrratnRate,omitempty"`
// Cash rate made available in an offer in order to encourage participation in the offer.
SolicitationFeeRate *SolicitationFeeRateFormat1Choice `xml:"SlctnFeeRate,omitempty"`
// Cash rate made available, as an incentive, in addition to the solicitation fee, in order to encourage early participation in an offer.
EarlySolicitationFeeRate *SolicitationFeeRateFormat1Choice `xml:"EarlySlctnFeeRate,omitempty"`
// Percentage of a cash distribution that will be withheld by a tax authority.
WithholdingTaxRate *RateFormat2Choice `xml:"WhldgTaxRate,omitempty"`
// Taxation applied on an amount clearly identified as an income.
TaxOnIncome *RateFormat2Choice `xml:"TaxOnIncm,omitempty"`
// Taxation applied on an amount clearly identified as capital profits, capital gains.
TaxOnProfits *RateFormat2Choice `xml:"TaxOnPrfts,omitempty"`
// Percentage of cash that was paid in excess of actual tax obligation and was reclaimed.
TaxReclaimRate *RateFormat2Choice `xml:"TaxRclmRate,omitempty"`
// Rate at which the income will be withheld by the jurisdiction in which the income was originally paid, for which relief at source and/or reclaim may be possible.
WithholdingOfForeignTax *RateAndAmountFormat3Choice `xml:"WhldgOfFrgnTax,omitempty"`
// Rate at which the income will be withheld by the jurisdiction in which the account owner is located, for which relief at source and/or reclaim may be possible.
WithholdingOfLocalTax *RateAndAmountFormat3Choice `xml:"WhldgOfLclTax,omitempty"`
// Percentage of the gross dividend rate on which tax must be paid .
TaxRelatedRate []*RateTypeAndAmountAndStatus6 `xml:"TaxRltdRate,omitempty"`
// Rate applicable to the event announced, for example, redemption rate for a redemption event.
ApplicableRate *RateFormat2Choice `xml:"AplblRate,omitempty"`
}
func (c *CorporateActionRate5) AddAdditionalTax() *RateAndAmountFormat3Choice {
c.AdditionalTax = new(RateAndAmountFormat3Choice)
return c.AdditionalTax
}
func (c *CorporateActionRate5) AddChargesFees() *RateAndAmountFormat3Choice {
c.ChargesFees = new(RateAndAmountFormat3Choice)
return c.ChargesFees
}
func (c *CorporateActionRate5) AddFinalDividendRate() *RateAndAmountFormat4Choice {
c.FinalDividendRate = new(RateAndAmountFormat4Choice)
return c.FinalDividendRate
}
func (c *CorporateActionRate5) AddFiscalStamp() *RateFormat2Choice {
c.FiscalStamp = new(RateFormat2Choice)
return c.FiscalStamp
}
func (c *CorporateActionRate5) AddFullyFrankedRate() *RateAndAmountFormat3Choice {
c.FullyFrankedRate = new(RateAndAmountFormat3Choice)
return c.FullyFrankedRate
}
func (c *CorporateActionRate5) AddGrossDividendRate() *GrossDividendRateFormat1Choice {
newValue := new (GrossDividendRateFormat1Choice)
c.GrossDividendRate = append(c.GrossDividendRate, newValue)
return newValue
}
func (c *CorporateActionRate5) AddCashIncentiveRate() *RateFormat2Choice {
c.CashIncentiveRate = new(RateFormat2Choice)
return c.CashIncentiveRate
}
func (c *CorporateActionRate5) AddIndexFactor() *RateAndAmountFormat3Choice {
c.IndexFactor = new(RateAndAmountFormat3Choice)
return c.IndexFactor
}
func (c *CorporateActionRate5) AddInterestRateUsedForPayment() *InterestRateUsedForPaymentFormat1Choice {
newValue := new (InterestRateUsedForPaymentFormat1Choice)
c.InterestRateUsedForPayment = append(c.InterestRateUsedForPayment, newValue)
return newValue
}
func (c *CorporateActionRate5) AddNetDividendRate() *NetDividendRateFormat1Choice {
newValue := new (NetDividendRateFormat1Choice)
c.NetDividendRate = append(c.NetDividendRate, newValue)
return newValue
}
func (c *CorporateActionRate5) AddNonResidentRate() *RateAndAmountFormat3Choice {
c.NonResidentRate = new(RateAndAmountFormat3Choice)
return c.NonResidentRate
}
func (c *CorporateActionRate5) AddMaximumAllowedOversubscriptionRate() *RateFormat2Choice {
c.MaximumAllowedOversubscriptionRate = new(RateFormat2Choice)
return c.MaximumAllowedOversubscriptionRate
}
func (c *CorporateActionRate5) AddProvisionalDividendRate() *RateAndAmountFormat4Choice {
c.ProvisionalDividendRate = new(RateAndAmountFormat4Choice)
return c.ProvisionalDividendRate
}
func (c *CorporateActionRate5) AddTaxCreditRate() *TaxCreditRateFormat1Choice {
newValue := new (TaxCreditRateFormat1Choice)
c.TaxCreditRate = append(c.TaxCreditRate, newValue)
return newValue
}
func (c *CorporateActionRate5) AddProrationRate() *RateFormat2Choice {
c.ProrationRate = new(RateFormat2Choice)
return c.ProrationRate
}
func (c *CorporateActionRate5) AddSolicitationFeeRate() *SolicitationFeeRateFormat1Choice {
c.SolicitationFeeRate = new(SolicitationFeeRateFormat1Choice)
return c.SolicitationFeeRate
}
func (c *CorporateActionRate5) AddEarlySolicitationFeeRate() *SolicitationFeeRateFormat1Choice {
c.EarlySolicitationFeeRate = new(SolicitationFeeRateFormat1Choice)
return c.EarlySolicitationFeeRate
}
func (c *CorporateActionRate5) AddWithholdingTaxRate() *RateFormat2Choice {
c.WithholdingTaxRate = new(RateFormat2Choice)
return c.WithholdingTaxRate
}
func (c *CorporateActionRate5) AddTaxOnIncome() *RateFormat2Choice {
c.TaxOnIncome = new(RateFormat2Choice)
return c.TaxOnIncome
}
func (c *CorporateActionRate5) AddTaxOnProfits() *RateFormat2Choice {
c.TaxOnProfits = new(RateFormat2Choice)
return c.TaxOnProfits
}
func (c *CorporateActionRate5) AddTaxReclaimRate() *RateFormat2Choice {
c.TaxReclaimRate = new(RateFormat2Choice)
return c.TaxReclaimRate
}
func (c *CorporateActionRate5) AddWithholdingOfForeignTax() *RateAndAmountFormat3Choice {
c.WithholdingOfForeignTax = new(RateAndAmountFormat3Choice)
return c.WithholdingOfForeignTax
}
func (c *CorporateActionRate5) AddWithholdingOfLocalTax() *RateAndAmountFormat3Choice {
c.WithholdingOfLocalTax = new(RateAndAmountFormat3Choice)
return c.WithholdingOfLocalTax
}
func (c *CorporateActionRate5) AddTaxRelatedRate() *RateTypeAndAmountAndStatus6 {
newValue := new (RateTypeAndAmountAndStatus6)
c.TaxRelatedRate = append(c.TaxRelatedRate, newValue)
return newValue
}
func (c *CorporateActionRate5) AddApplicableRate() *RateFormat2Choice {
c.ApplicableRate = new(RateFormat2Choice)
return c.ApplicableRate
} | CorporateActionRate5.go | 0.895717 | 0.58818 | CorporateActionRate5.go | starcoder |
package benchmark
import (
"reflect"
"testing"
)
func isBoolToUint8FuncCalibrated(supplier func() bool) bool {
return isCalibrated(reflect.Bool, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isIntToUint8FuncCalibrated(supplier func() int) bool {
return isCalibrated(reflect.Int, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isInt8ToUint8FuncCalibrated(supplier func() int8) bool {
return isCalibrated(reflect.Int8, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isInt16ToUint8FuncCalibrated(supplier func() int16) bool {
return isCalibrated(reflect.Int16, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isInt32ToUint8FuncCalibrated(supplier func() int32) bool {
return isCalibrated(reflect.Int32, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isInt64ToUint8FuncCalibrated(supplier func() int64) bool {
return isCalibrated(reflect.Int64, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isUintToUint8FuncCalibrated(supplier func() uint) bool {
return isCalibrated(reflect.Uint, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isUint8ToUint8FuncCalibrated(supplier func() uint8) bool {
return isCalibrated(reflect.Uint8, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isUint16ToUint8FuncCalibrated(supplier func() uint16) bool {
return isCalibrated(reflect.Uint16, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isUint32ToUint8FuncCalibrated(supplier func() uint32) bool {
return isCalibrated(reflect.Uint32, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isUint64ToUint8FuncCalibrated(supplier func() uint64) bool {
return isCalibrated(reflect.Uint64, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setBoolToUint8FuncCalibrated(supplier func() bool) {
setCalibrated(reflect.Bool, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setIntToUint8FuncCalibrated(supplier func() int) {
setCalibrated(reflect.Int, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setInt8ToUint8FuncCalibrated(supplier func() int8) {
setCalibrated(reflect.Int8, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setInt16ToUint8FuncCalibrated(supplier func() int16) {
setCalibrated(reflect.Int16, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setInt32ToUint8FuncCalibrated(supplier func() int32) {
setCalibrated(reflect.Int32, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setInt64ToUint8FuncCalibrated(supplier func() int64) {
setCalibrated(reflect.Int64, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setUintToUint8FuncCalibrated(supplier func() uint) {
setCalibrated(reflect.Uint, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setUint8ToUint8FuncCalibrated(supplier func() uint8) {
setCalibrated(reflect.Uint8, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setUint16ToUint8FuncCalibrated(supplier func() uint16) {
setCalibrated(reflect.Uint16, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setUint32ToUint8FuncCalibrated(supplier func() uint32) {
setCalibrated(reflect.Uint32, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func setUint64ToUint8FuncCalibrated(supplier func() uint64) {
setCalibrated(reflect.Uint64, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
// BoolToUint8Func benchmarks a function with the signature:
// func(bool) uint8
// ID: B-8-1
func BoolToUint8Func(b *testing.B, supplier func() bool, toUint8Func func(bool) uint8) {
if !isBoolSupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isBoolToUint8FuncCalibrated(supplier) {
panic("BoolToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// IntToUint8Func benchmarks a function with the signature:
// func(int) uint8
// ID: B-8-2
func IntToUint8Func(b *testing.B, supplier func() int, toUint8Func func(int) uint8) {
if !isIntSupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isIntToUint8FuncCalibrated(supplier) {
panic("IntToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Int8ToUint8Func benchmarks a function with the signature:
// func(int8) uint8
// ID: B-8-3
func Int8ToUint8Func(b *testing.B, supplier func() int8, toUint8Func func(int8) uint8) {
if !isInt8SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isInt8ToUint8FuncCalibrated(supplier) {
panic("Int8ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Int16ToUint8Func benchmarks a function with the signature:
// func(int16) uint8
// ID: B-8-4
func Int16ToUint8Func(b *testing.B, supplier func() int16, toUint8Func func(int16) uint8) {
if !isInt16SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isInt16ToUint8FuncCalibrated(supplier) {
panic("Int16ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Int32ToUint8Func benchmarks a function with the signature:
// func(int32) uint8
// ID: B-8-5
func Int32ToUint8Func(b *testing.B, supplier func() int32, toUint8Func func(int32) uint8) {
if !isInt32SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isInt32ToUint8FuncCalibrated(supplier) {
panic("Int32ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Int64ToUint8Func benchmarks a function with the signature:
// func(int64) uint8
// ID: B-8-6
func Int64ToUint8Func(b *testing.B, supplier func() int64, toUint8Func func(int64) uint8) {
if !isInt64SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isInt64ToUint8FuncCalibrated(supplier) {
panic("Int64ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// UintToUint8Func benchmarks a function with the signature:
// func(uint) uint8
// ID: B-8-7
func UintToUint8Func(b *testing.B, supplier func() uint, toUint8Func func(uint) uint8) {
if !isUintSupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isUintToUint8FuncCalibrated(supplier) {
panic("UintToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Uint8ToUint8Func benchmarks a function with the signature:
// func(uint8) uint8
// ID: B-8-8
func Uint8ToUint8Func(b *testing.B, supplier func() uint8, toUint8Func func(uint8) uint8) {
if !isUint8SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isUint8ToUint8FuncCalibrated(supplier) {
panic("Uint8ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Uint16ToUint8Func benchmarks a function with the signature:
// func(uint16) uint8
// ID: B-8-9
func Uint16ToUint8Func(b *testing.B, supplier func() uint16, toUint8Func func(uint16) uint8) {
if !isUint16SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isUint16ToUint8FuncCalibrated(supplier) {
panic("Uint16ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Uint32ToUint8Func benchmarks a function with the signature:
// func(uint32) uint8
// ID: B-8-10
func Uint32ToUint8Func(b *testing.B, supplier func() uint32, toUint8Func func(uint32) uint8) {
if !isUint32SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isUint32ToUint8FuncCalibrated(supplier) {
panic("Uint32ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
}
// Uint64ToUint8Func benchmarks a function with the signature:
// func(uint8) uint8
// ID: B-8-11
func Uint64ToUint8Func(b *testing.B, supplier func() uint64, toUint8Func func(uint64) uint8) {
if !isUint64SupplierCalibrated(supplier) {
panic("supplier function not calibrated")
}
if !isUint64ToUint8FuncCalibrated(supplier) {
panic("Uint64ToUint8Func not calibrated with this supplier")
}
for i, count := 0, b.N; i < count; i++ {
toUint8Func(supplier())
}
} | common/benchmark/08_to_uint8_func.go | 0.708717 | 0.612484 | 08_to_uint8_func.go | starcoder |
package faker
import (
"math"
"reflect"
"time"
)
type Date struct {
time.Time
}
// Past_ Generate past date It takes two argument yearsAgo and ref date
func (d *Date) Pastʹ(params ...interface{}) time.Time {
//years, ref := d.validate(params...)
years := 1
ref := time.Now()
types := typeOf(params...)
if len(types) >= 1 && types[0] == reflect.TypeOf(years) {
years = params[0].(int)
}
if len(types) >= 2 && types[1] == reflect.TypeOf(ref) {
ref = params[0].(time.Time)
}
past := ref.AddDate(-years, 0, 0)
return past
}
func (d *Date) Futureʹ(params ...interface{}) time.Time {
years := 1
ref := time.Now()
types := typeOf(params...)
if len(types) >= 1 && types[0] == reflect.TypeOf(years) {
years = params[0].(int)
}
if len(types) >= 2 && types[1] == reflect.TypeOf(ref) {
ref = params[0].(time.Time)
}
future := ref.AddDate(years, 0, 0)
return future
}
func (d *Date) Betweenʹ(from, to string, params ...interface{}) time.Time {
layout := "02-02-2006"
kinds := kindOf(params...)
if len(kinds) >= 1 && kinds[0] == reflect.String {
layout = params[0].(string)
}
fromTime, err := time.Parse(layout, from)
if err != nil {
fromTime = time.Unix(time.Now().Unix()-30, 0)
}
toTime, err := time.Parse(layout, to)
if err != nil {
toTime = time.Now()
}
delta := toTime.Unix() - fromTime.Unix()
newDate := fromTime.Unix() + int64(random(0, int(delta)))
return time.Unix(newDate, 0)
}
func (d *Date) Recentʹ(params ...interface{}) time.Time {
days := 1
date := time.Now()
kinds := kindOf(params...)
if len(kinds) >= 1 && kinds[0] == reflect.Int {
days = params[0].(int)
}
min := int(math.Pow(10, 9))
if days <= 1 {
days = 1
}
max := days * 24 * 3600 * min
rnd := random(min, max)
future := date.UnixNano() - int64(rnd)
return time.Unix(0, future)
}
func (d *Date) typCtx(options ...interface{}) string {
typ := "Wide"
context := false
types := kindOf(options...)
if len(types) >= 1 {
if types[0] == reflect.String {
v := options[0].(string)
if v == "Abbr" {
typ = v
}
}
}
if len(types) > 1 {
if types[1] == reflect.Bool {
v := options[1].(bool)
if v {
context = v
}
}
}
if context {
typ += "Context"
}
return typ
}
func (d *Date) Monthʹ(options ...interface{}) string {
typ := d.typCtx(options...)
source := getData("Date", "Month", typ)
return sample(source)
}
func (d *Date) Weekdayʹ(options ...interface{}) string {
typ := d.typCtx(options...)
source := getData("Date", "Weekday", typ)
return sample(source)
}
// ToJSON Encode name and its fields to JSON.
func (d *Date) ToJSON() (string, error) {
return ToJSON(d)
}
// ToXML Encode name and its fields to XML.
func (d *Date) ToXML() (string, error) {
return ToXML(d)
} | date.go | 0.626924 | 0.469277 | date.go | starcoder |
package mem
import (
"errors"
"io"
)
// MultiPager is a memory device that can be composed of multiple memory devices.
type MultiPager struct {
rws []io.ReadWriteSeeker
devMax []int
devLastPos int
devPos int
devIdx int
pos int
maxLen int
}
// Join will join the given memory devices into a single device.
func Join(rws ...io.ReadWriteSeeker) io.ReadWriteSeeker {
if len(rws) == 1 {
return rws[0]
}
m := &MultiPager{rws: rws, devLastPos: -1}
for _, rw := range rws {
l, err := rw.Seek(0, io.SeekEnd)
if err != nil {
panic(err)
}
m.maxLen += int(l)
m.devMax = append(m.devMax, int(l))
_, err = rw.Seek(0, 0)
if err != nil {
panic(err)
}
}
return m
}
func (m *MultiPager) eof() bool {
return m.devIdx == len(m.rws)
}
func (m *MultiPager) needSeek() bool {
return m.devPos != m.devLastPos
}
func (m *MultiPager) remBytes() int {
return m.maxLen - m.pos
}
func (m *MultiPager) remDevBytes() int {
return m.devMax[m.devIdx] - m.devPos
}
func (m *MultiPager) dev() io.ReadWriteSeeker { return m.rws[m.devIdx] }
func (m *MultiPager) incrPos(n int) {
m.pos += n
m.devPos += n
m.devLastPos += n
if m.remDevBytes() > 0 {
return
}
if m.remDevBytes() != 0 {
panic("unaligned position")
}
m.devLastPos = -1
m.devIdx++
m.devPos = 0
}
func (m *MultiPager) Read(p []byte) (n int, err error) {
if m.eof() {
return 0, io.EOF
}
if len(p) > m.remDevBytes() {
return m.Read(p[:m.remDevBytes()])
}
if m.needSeek() {
if ra, ok := m.dev().(io.ReaderAt); ok {
n, err = ra.ReadAt(p, int64(m.devPos))
m.incrPos(n)
return n, err
}
np, err := m.dev().Seek(int64(m.devPos), 0)
m.devLastPos = int(np)
if err != nil {
return 0, err
}
}
n, err = m.dev().Read(p)
m.incrPos(n)
return n, err
}
func (m *MultiPager) ReadAt(p []byte, offset int64) (_ int, err error) {
if offset != int64(m.pos) {
_, err = m.Seek(offset, io.SeekStart)
if err != nil {
return 0, err
}
}
return m.Read(p)
}
func (m *MultiPager) WriteAt(p []byte, offset int64) (_ int, err error) {
if offset != int64(m.pos) {
_, err = m.Seek(offset, io.SeekStart)
if err != nil {
return 0, err
}
}
return m.Write(p)
}
func (m *MultiPager) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekEnd:
return m.Seek(int64(m.maxLen)-offset, io.SeekStart)
case io.SeekCurrent:
return m.Seek(int64(m.pos)+offset, io.SeekStart)
case io.SeekStart:
default:
return 0, errors.New("invalid whence")
}
if offset < 0 {
return 0, errors.New("out of bounds")
}
if offset >= int64(m.maxLen) {
m.devIdx = len(m.rws)
m.pos = int(offset)
m.devPos = 0
m.devLastPos = -1
return offset, nil
}
m.pos = int(offset)
m.devIdx = 0
for offset >= int64(m.devMax[m.devIdx]) {
offset -= int64(m.devMax[m.devIdx])
m.devIdx++
}
m.devPos = int(offset)
m.devLastPos = -1
return int64(m.pos), nil
}
func (m *MultiPager) Write(p []byte) (n int, err error) {
if m.eof() {
return 0, io.EOF
}
if len(p) > m.remBytes() {
p = p[:m.remBytes()]
n, err = m.Write(p)
if err != nil {
return n, err
}
return n, io.ErrShortWrite
}
buf := p
for len(buf) > m.remDevBytes() {
n, err = m.Write(buf[:m.remDevBytes()])
if err != nil {
return n + len(p) - len(buf), err
}
buf = buf[n:]
}
if m.needSeek() {
if wa, ok := m.dev().(io.WriterAt); ok {
n, err = wa.WriteAt(buf, int64(m.devPos))
m.incrPos(n)
return n + len(p) - len(buf), err
}
_, err = m.dev().Seek(int64(m.devPos), 0)
if err != nil {
return len(p) - len(buf), err
}
}
n, err = m.dev().Write(buf)
m.incrPos(n)
return n + len(p) - len(buf), err
} | driver/mem/multipager.go | 0.559049 | 0.42925 | multipager.go | starcoder |
package react
// basic represents a simple value with no other properties
type basic struct {
value int // the value of this given cell
e *engine // the pointer back to our main engine
}
// Value simply returns the set value for this basic cell
func (b basic) Value() int {
return b.value
}
// input represents a basic cell which has a settable value
type input struct {
basic
}
// SetValue simply returns the set value for this basic cell
func (i *input) SetValue(update int) {
if i.value == update {
return
}
i.value = update
i.e.trigger(i)
}
// derived represents a cell whose value is dependent on a other inputs
type derived struct {
basic // we also are a basic cell
updateCallback func() // the callback we use to update our basic value
callbacks map[CallbackHandle]func(int) // a map of all the callbacks registered to this
handleGen ident // the next id for our callback handle
}
// RemoveCallback removes a callback from a derived cell
func (d *derived) RemoveCallback(handle CallbackHandle) {
delete(d.callbacks, handle)
}
// nextHandle gets the next id for a callback for this derived struct
func (d *derived) nextHandle() CallbackHandle {
id := d.handleGen
d.handleGen++
return id
}
// AddCallback inserts an additional callback to be triggered when the value of derived changes
func (d *derived) AddCallback(cb func(int)) CallbackHandle {
handle := d.nextHandle()
d.callbacks[handle] = cb
return handle
}
// trigger is run when a derived value is triggered, we update our value, and propogate any changes
func (d *derived) trigger() {
prev := d.value
d.updateCallback()
curr := d.value
//only if the value actually changed do we run our update callbacks
if curr != prev {
for _, cb := range d.callbacks {
cb(curr)
}
}
}
// newDerived returns an initialized pointer to a derived cell
func newDerived(e *engine) *derived {
d := &derived{
callbacks: make(map[CallbackHandle]func(int)),
}
d.e = e
return d
} | react/cells.go | 0.826712 | 0.532425 | cells.go | starcoder |
package storetest
import (
"math/rand"
"reflect"
"testing"
"time"
"github.com/savaki/kstreams"
"github.com/tj/assert"
)
const (
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func alphaN(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Int63()%int64(len(letters))]
}
return string(b)
}
type encoder string
func (e encoder) Encode() ([]byte, error) {
return []byte(e), nil
}
func TestStore(t *testing.T, store kstreams.KeyValueStore) {
t.Run("get nonexistent key", func(t *testing.T) {
key := encoder(alphaN(8))
_, err := store.Get(key)
assert.Equal(t, kstreams.ErrKeyNotFound, err)
})
t.Run("put then get", func(t *testing.T) {
key := encoder(alphaN(8))
value := encoder("world")
assert.Nil(t, store.Put(key, value))
data, err := store.Get(key)
assert.Nil(t, err)
assert.EqualValues(t, value, encoder(data))
})
t.Run("put if absent doesn't overwrite value, then get", func(t *testing.T) {
key := encoder(alphaN(8))
value1 := encoder("world1")
value2 := encoder("world2")
assert.Nil(t, store.Put(key, value1))
assert.Nil(t, store.PutIfAbsent(key, value2))
data, err := store.Get(key)
assert.Nil(t, err)
assert.EqualValues(t, value1, encoder(data))
})
t.Run("put if absent, then get", func(t *testing.T) {
key := encoder(alphaN(8))
value := encoder("world1")
assert.Nil(t, store.PutIfAbsent(key, value))
data, err := store.Get(key)
assert.Nil(t, err)
assert.EqualValues(t, value, encoder(data))
})
t.Run("put all followed by get range and all", func(t *testing.T) {
key := alphaN(10)
key1 := encoder(key + "1")
key2 := encoder(key + "2")
key3 := encoder(key + "3")
value := encoder("blah")
err := store.PutAll(
kstreams.KeyValue{
Key: key1,
Value: value,
},
kstreams.KeyValue{
Key: key2,
Value: value,
},
kstreams.KeyValue{
Key: key3,
Value: value,
},
)
assert.Nil(t, err)
t.Run("and retrieved via Range", func(t *testing.T) {
count := 0
store.Range(key1, key3, func(k, v []byte) error {
count++
switch count {
case 1:
assert.Equal(t, key1, encoder(k))
case 2:
assert.Equal(t, key2, encoder(k))
case 3:
assert.Equal(t, key3, encoder(k))
}
assert.Equal(t, value, encoder(v))
return nil
})
assert.Equal(t, 3, count)
})
t.Run("and retrieved via All", func(t *testing.T) {
counts := map[int]struct{}{}
store.All(func(k, v []byte) error {
if key := encoder(k); reflect.DeepEqual(key, key1) {
counts[1] = struct{}{}
} else if reflect.DeepEqual(key, key2) {
counts[2] = struct{}{}
} else if reflect.DeepEqual(key, key3) {
counts[3] = struct{}{}
}
return nil
})
assert.Equal(t, 3, len(counts))
})
})
t.Run("put one, get range with keys that don't exist", func(t *testing.T) {
key := alphaN(12)
key0 := encoder(key + "0")
key1 := encoder(key + "1")
key2 := encoder(key + "2")
value := encoder("blah")
err := store.PutAll(
kstreams.KeyValue{
Key: key1,
Value: value,
},
)
assert.Nil(t, err)
count := 0
store.Range(key0, key2, func(k, v []byte) error {
count++
return nil
})
assert.Equal(t, 1, count)
})
t.Run("delete", func(t *testing.T) {
key := encoder(alphaN(8))
value := encoder("world1")
assert.Nil(t, store.Put(key, value))
found, err := store.Delete(key)
assert.Nil(t, err)
assert.Equal(t, value, encoder(found))
_, err = store.Get(key)
assert.Equal(t, kstreams.ErrKeyNotFound, err)
})
t.Run("delete non-existent key", func(t *testing.T) {
key := encoder(alphaN(10))
_, err := store.Delete(key)
assert.Equal(t, kstreams.ErrKeyNotFound, err)
})
t.Run("implements StateStore", func(t *testing.T) {
stateStore, ok := store.(kstreams.StateStore)
assert.True(t, ok, "expected store to implement kstreams.StateStore")
t.Run("and name is set", func(t *testing.T) {
assert.NotZero(t, stateStore.Name())
})
t.Run("and IsOpen", func(t *testing.T) {
assert.True(t, stateStore.IsOpen())
})
})
} | storetest/storetest.go | 0.623148 | 0.664357 | storetest.go | starcoder |
package scene
import "github.com/mokiat/gomath/dprec"
type Triangle struct {
P1 dprec.Vec3
P2 dprec.Vec3
P3 dprec.Vec3
TextureName string
}
func (t Triangle) Line1() Line {
return Line{
P1: t.P1,
P2: t.P2,
}
}
func (t Triangle) Line2() Line {
return Line{
P1: t.P2,
P2: t.P3,
}
}
func (t Triangle) Line3() Line {
return Line{
P1: t.P3,
P2: t.P1,
}
}
func (t Triangle) Normal() dprec.Vec3 {
return dprec.UnitVec3(dprec.Vec3Cross(
dprec.Vec3Diff(t.P1, t.P3),
dprec.Vec3Diff(t.P2, t.P3),
))
}
func (t Triangle) Center() dprec.Vec3 {
var center dprec.Vec3
center = dprec.Vec3Sum(center, t.P1)
center = dprec.Vec3Sum(center, t.P2)
center = dprec.Vec3Sum(center, t.P3)
return dprec.Vec3Quot(center, 3)
}
func (t Triangle) Left() VerticalLine {
leftward := dprec.Vec3Cross(
t.Normal(),
dprec.BasisYVec3(),
)
center := t.Center()
flatDistance := func(p dprec.Vec3) float64 {
return dprec.Vec3Dot(
leftward,
dprec.Vec3Diff(p, center),
)
}
bestFlatDistance := 0.0
result := VerticalLine{}
if distance1 := flatDistance(t.P1); distance1 > bestFlatDistance {
bestFlatDistance = distance1
result = VerticalLine{X: t.P1.X, Z: t.P1.Z}
}
if distance2 := flatDistance(t.P2); distance2 > bestFlatDistance {
bestFlatDistance = distance2
result = VerticalLine{X: t.P2.X, Z: t.P2.Z}
}
if distance3 := flatDistance(t.P3); distance3 > bestFlatDistance {
result = VerticalLine{X: t.P3.X, Z: t.P3.Z}
}
return result
}
func (t Triangle) Right() VerticalLine {
leftward := dprec.Vec3Cross(
dprec.BasisYVec3(),
t.Normal(),
)
center := t.Center()
flatDistance := func(p dprec.Vec3) float64 {
return dprec.Vec3Dot(
leftward,
dprec.Vec3Diff(p, center),
)
}
bestFlatDistance := 0.0
result := VerticalLine{}
if distance1 := flatDistance(t.P1); distance1 > bestFlatDistance {
bestFlatDistance = distance1
result = VerticalLine{X: t.P1.X, Z: t.P1.Z}
}
if distance2 := flatDistance(t.P2); distance2 > bestFlatDistance {
bestFlatDistance = distance2
result = VerticalLine{X: t.P2.X, Z: t.P2.Z}
}
if distance3 := flatDistance(t.P3); distance3 > bestFlatDistance {
result = VerticalLine{X: t.P3.X, Z: t.P3.Z}
}
return result
}
func (t Triangle) IsFloor(precision float64) bool {
normal := t.Normal()
return dprec.EqEps(normal.Y, 1.0, precision)
}
func (t Triangle) IsCeiling(precision float64) bool {
normal := t.Normal()
return dprec.EqEps(normal.Y, -1.0, precision)
}
func (t Triangle) IsVertical(precision float64) bool {
normal := t.Normal()
return dprec.EqEps(normal.Y, 0.0, precision)
}
type TriangleList []Triangle | cmd/softgfx-lvlgen/internal/scene/triangle.go | 0.80502 | 0.658352 | triangle.go | starcoder |
package text
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
)
type Cell struct {
contents string
feed bool
}
type GridWriter struct {
ColumnPadding int
MinWidth int
Grid [][]Cell
CurrentRow int
colWidths []int
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// init() makes the initial row if this is the first time any data is being written.
// otherwise, no-op.
func (gw *GridWriter) init() {
if len(gw.Grid) <= gw.CurrentRow {
gw.Grid = append(gw.Grid, []Cell{})
}
}
// WriteCell writes the given string into the next cell in the current row.
func (gw *GridWriter) WriteCell(data string) {
gw.init()
gw.Grid[gw.CurrentRow] = append(gw.Grid[gw.CurrentRow], Cell{data, false})
}
// WriteCells writes multiple cells by calling WriteCell for each argument.
func (gw *GridWriter) WriteCells(data ...string) {
for _, s := range data {
gw.WriteCell(s)
}
}
// Feed writes the given string into the current cell but allowing the cell contents
// to extend past the width of the current column, and ends the row.
func (gw *GridWriter) Feed(data string) {
gw.init()
gw.Grid[gw.CurrentRow] = append(gw.Grid[gw.CurrentRow], Cell{data, true})
gw.EndRow()
}
// EndRow terminates the row of cells and begins a new row in the grid.
func (gw *GridWriter) EndRow() {
gw.CurrentRow++
if len(gw.Grid) <= gw.CurrentRow {
gw.Grid = append(gw.Grid, []Cell{})
}
}
// Reset discards any grid data and resets the current row.
func (gw *GridWriter) Reset() {
gw.CurrentRow = 0
gw.Grid = [][]Cell{}
}
// updateWidths sets the column widths in the Grid. For each column in the Grid,
// it updates the cached width if its value is less than the current width.
func (gw *GridWriter) updateWidths(colWidths []int) {
if gw.colWidths == nil {
gw.colWidths = make([]int, len(colWidths))
copy(gw.colWidths, colWidths)
}
for i, cw := range colWidths {
if gw.colWidths[i] < cw {
gw.colWidths[i] = cw
}
}
}
// calculateWidths returns an array containing the correct padded size for
// each column in the grid.
func (gw *GridWriter) calculateWidths() []int {
colWidths := []int{}
// Loop over each column
for j := 0; ; j++ {
found := false
// Examine all the rows at column 'j'
for i := range gw.Grid {
if len(gw.Grid[i]) <= j {
continue
}
found = true
if len(colWidths) <= j {
colWidths = append(colWidths, 0)
}
if gw.Grid[i][j].feed {
// we're at a row-terminating cell - skip over the rest of this row
continue
}
// Set the size for the row to be the largest
// of all the cells in the column
newMin := max(gw.MinWidth, len(gw.Grid[i][j].contents))
if newMin > colWidths[j] {
colWidths[j] = newMin
}
}
// This column did not have any data in it at all, so we've hit the
// end of the grid - stop.
if !found {
break
}
}
return colWidths
}
// Flush writes the fully-formatted grid to the given io.Writer.
func (gw *GridWriter) Flush(w io.Writer) {
colWidths := gw.calculateWidths()
// invalidate all cached widths if new cells are added/removed
if len(gw.colWidths) != len(colWidths) {
gw.colWidths = make([]int, len(colWidths))
copy(gw.colWidths, colWidths)
} else {
gw.updateWidths(colWidths)
}
for i, row := range gw.Grid {
lastRow := i == (len(gw.Grid) - 1)
for j, cell := range row {
lastCol := (j == len(row)-1)
fmt.Fprintf(w, fmt.Sprintf("%%%vs", gw.colWidths[j]), cell.contents)
if gw.ColumnPadding > 0 && !lastCol {
fmt.Fprint(w, strings.Repeat(" ", gw.ColumnPadding))
}
}
if !lastRow {
fmt.Fprint(w, "\n")
}
}
}
// FlushRows writes the fully-formatted grid to the given io.Writer, but
// gives each row its own Write() call instead of using newlines.
func (gw *GridWriter) FlushRows(w io.Writer) {
gridBuff := &bytes.Buffer{}
gw.Flush(gridBuff)
lineScanner := bufio.NewScanner(gridBuff)
for lineScanner.Scan() {
w.Write(lineScanner.Bytes())
}
} | src/mongo/gotools/common/text/grid.go | 0.63273 | 0.420838 | grid.go | starcoder |
package main
import (
"fmt"
"strings"
)
//Index returns the first index of the target string, or -1 if no match is found.
func Index(values []string, target string) int {
for index, value := range values {
if value == target {
return index
}
}
return -1
}
//Include returns true if the target string is in the slice
func Include(values []string, target string) bool {
return Index(values, target) >= 0
}
//Any returns true if one of the strings in the slice satisfies the predicate.
func Any(values []string, predicate func(string) bool) bool {
for _, value := range values {
if predicate(value) {
return true
}
}
return false
}
//All returns true if all of the strings in the slice satisfy the predicate.
func All(values []string, predicate func(string) bool) bool {
for _, value := range values {
if !predicate(value) {
return false
}
}
return true
}
//Filter returns a new slice containing all strings in the slice that satisfy the predicate.
func Filter(values []string, predicate func(string) bool) []string {
predicateValues := make([]string, 0)
for _, value := range values {
if predicate(value) {
predicateValues = append(predicateValues, value)
}
}
return predicateValues
}
//Map returns a new slice containing the results of applying the function f to each string in the original slice.
func Map(values []string, function func(string) string) []string {
vsm := make([]string, len(values))
for i, v := range values {
vsm[i] = function(v)
}
return vsm
}
func main() {
strs := []string{"peach", "apple", "pear", "plum"}
fmt.Println(Index(strs, "pear"))
fmt.Println(Include(strs, "grape"))
fmt.Println(Any(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))
fmt.Println(All(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))
fmt.Println(Filter(strs, func(v string) bool {
return strings.Contains(v, "e")
}))
fmt.Println(Map(strs, strings.ToUpper))
} | 41-collection-functions.go | 0.845481 | 0.48054 | 41-collection-functions.go | starcoder |
package pair
import (
"fmt"
"reflect"
"sort"
)
// Pair is a struct combines two variables
// variables could be distinct type
// motivation comes from pair in STL utility in C++
type Pair struct {
First interface{}
Second interface{}
}
// Pairs is a wrapper for slice of pair
// has basic sort method
type Pairs []Pair
// NewPair generates a pair
func NewPair(first, second interface{}) Pair {
return Pair{first, second}
}
// MakePairs generates a Pairs
func MakePairs(pairs []Pair) Pairs {
return Pairs(pairs)
}
// Sort func sorts the slice of pair
func Sort(pairs []Pair) {
var ppairs = MakePairs(pairs)
ppairs.Sort()
}
// SortReverse func sorts the slice of pair, but reverse
func SortReverse(pairs []Pair) {
var ppairs = MakePairs(pairs)
ppairs.SortReserve()
}
// SortFirst func sort the slice of pair with the first variable.
func SortFirst(pairs []Pair) {
var ppairs = MakePairs(pairs)
ppairs.SortFirst()
}
// SortFirstReverse func sort with first variable, but reverse
func SortFirstReverse(pairs []Pair) {
var ppairs = MakePairs(pairs)
ppairs.SortFirstReverse()
}
// SortSecond func sort the slice of pair with second variable.
func SortSecond(pairs []Pair) {
var ppairs = MakePairs(pairs)
ppairs.SortSecond()
}
// SortSecondReverse func sort the slice of pair with second variable, but reverse
func SortSecondReverse(pairs []Pair) {
var ppairs = MakePairs(pairs)
ppairs.SortSecondReverse()
}
// FString get the first variable as string
func (this *Pair) FString() string {
return tostring(this.First)
}
// SString get the second variable as string
func (this *Pair) SString() string {
return tostring(this.Second)
}
// FUint64 get the first variable as uint64
func (this *Pair) FUint64() uint64 {
return touint64(this.First)
}
// SUint64 get the second variable as uint64
func (this *Pair) SUint64() uint64 {
return touint64(this.Second)
}
// FInt64 get the first variable as int64
func (this *Pair) FInt64() int64 {
return toint64(this.First)
}
// SInt64 get the second variable as int64
func (this *Pair) SInt64() int64 {
return toint64(this.Second)
}
// FUint get the first variable as uint64
func (this *Pair) FUint() uint {
return touint(this.First)
}
// SUint get the second variable as uint
func (this *Pair) SUint() uint {
return touint(this.Second)
}
// FInt get the first variable as int
func (this *Pair) FInt() int {
return toint(this.First)
}
// SInt get the second variable as int
func (this *Pair) SInt() int {
return toint(this.Second)
}
// FFloat64 get the first variable as float64
func (this *Pair) FFloat64() float64 {
return tofloat64(this.First)
}
// SInt get the second variable as float64
func (this *Pair) SFloat64() float64 {
return tofloat64(this.Second)
}
// FFloat64 get the first variable as float32
func (this *Pair) FFloat32() float32 {
return tofloat32(this.First)
}
// SInt get the second variable as float32
func (this *Pair) SFloat32() float32 {
return tofloat32(this.Second)
}
// SortFirst is the native SortFirst method on Pairs
func (this *Pairs) SortFirst() {
sortPairsByFirst(this, false)
}
// SortFirstReverse is the native SortFirstReverse method on Pairs
func (this *Pairs) SortFirstReverse() {
sortPairsByFirst(this, true)
}
// SortSecond is the native SortSecond method on Pairs
func (this *Pairs) SortSecond() {
sortPairsBySecond(this, false)
}
// SortSecondReverse is the native SortSecondReverse method on Paris
func (this *Pairs) SortSecondReverse() {
sortPairsBySecond(this, true)
}
// Sort is the native Sort method on Pairs
func (this *Pairs) Sort() {
sortPairs(this, false)
}
// SortReverse is the native SortReverse method on Pairs
func (this *Pairs) SortReserve() {
sortPairs(this, true)
}
// ForEach iterates through pairs
func (this *Pairs) ForEach(iterator func(index int, item Pair)) {
if len(*this) <= 0 {
return
}
for i, v := range *this {
iterator(i, v)
}
}
// Filter supplies a filter for pairs with your iterator
func (this *Pairs) Filter(iterator func(index int, item Pair) bool) Pairs {
var res = Pairs{}
if len(*this) <= 0 {
return res
}
for i, v := range *this {
if iterator(i, v) {
res = append(res, v)
}
}
return res
}
func sortPairs(this *Pairs, reverse bool) {
if len(*this) <= 0 {
return
}
var _1stfunc = lessfunc(this, "First")
var _2ndfunc = lessfunc(this, "Second")
var cond1 = (true != reverse)
var cond2 = (false != reverse)
sort.Slice(*this, func(i, j int) bool {
var res1st = _1stfunc(i, j)
if res1st != 0 {
return tenary(res1st < 0, cond1, cond2)
}
var res2nd = _2ndfunc(i, j)
return tenary(res2nd < 0, cond1, cond2)
})
}
func sortPairsByFirst(this *Pairs, reverse bool) {
if len(*this) <= 0 {
return
}
var _1stfunc = lessfunc(this, "First")
var cond1 = (true != reverse)
var cond2 = (false != reverse)
sort.Slice(*this, func(i, j int) bool {
var res1st = _1stfunc(i, j)
return tenary(res1st < 0, cond1, cond2)
})
}
func sortPairsBySecond(this *Pairs, reverse bool) {
if len(*this) <= 0 {
return
}
var _2ndfunc = lessfunc(this, "Second")
var cond1 = (true != reverse)
var cond2 = (false != reverse)
sort.Slice(*this, func(i, j int) bool {
var res2nd = _2ndfunc(i, j)
return tenary(res2nd < 0, cond1, cond2)
})
}
func lessfunc(pairs *Pairs, fieldName string) func(i, j int) int {
var sample = (*pairs)[0]
var field = reflect.ValueOf(sample).FieldByName(fieldName).Interface()
var kind = reflect.ValueOf(field).Kind()
var common = func(i, j int) (interface{}, interface{}) {
var vi = reflect.ValueOf((*pairs)[i]).FieldByName(fieldName).Interface()
var vj = reflect.ValueOf((*pairs)[j]).FieldByName(fieldName).Interface()
return vi, vj
}
switch kind {
case reflect.Float64:
return func(i, j int) int {
var vi, vj = common(i, j)
var vvi, oi = vi.(float64)
var vvj, oj = vj.(float64)
if !oi || !oj {
pn(fieldName)
}
if vvi == vvj {
return 0
} else if vvi < vvj {
return -1
} else {
return 1
}
}
case reflect.Float32:
return func(i, j int) int {
var vi, vj = common(i, j)
var vvi, oi = vi.(float32)
var vvj, oj = vj.(float32)
if !oi || !oj {
pn(fieldName)
}
if vvi == vvj {
return 0
} else if vvi < vvj {
return -1
} else {
return 1
}
}
case reflect.Int64:
return func(i, j int) int {
var vi, vj = common(i, j)
var vvi, oi = vi.(int64)
var vvj, oj = vj.(int64)
if !oi || !oj {
pn(fieldName)
}
if vvi == vvj {
return 0
} else if vvi < vvj {
return -1
} else {
return 1
}
}
case reflect.Int32:
return func(i, j int) int {
var vi, vj = common(i, j)
var vvi, oi = vi.(int32)
var vvj, oj = vj.(int32)
if !oi || !oj {
pn(fieldName)
}
if vvi == vvj {
return 0
} else if vvi < vvj {
return -1
} else {
return 1
}
}
case reflect.Int:
return func(i, j int) int {
var vi, vj = common(i, j)
var vvi, oi = vi.(int)
var vvj, oj = vj.(int)
if !oi || !oj {
pn(fieldName)
}
if vvi == vvj {
return 0
} else if vvi < vvj {
return -1
} else {
return 1
}
}
case reflect.String:
return func(i, j int) int {
var vi, vj = common(i, j)
var vvi, oi = vi.(string)
var vvj, oj = vj.(string)
if !oi || !oj {
pn(fieldName)
}
if vvi == vvj {
return 0
} else if vvi < vvj {
return -1
} else {
return 1
}
}
default:
panic(fmt.Sprintf("%s kind is not supported yet", kind.String()))
}
}
func tenary(condition bool, yes, no bool) bool {
if condition {
return yes
}
return no
}
func tostring(x interface{}) string {
var s = x.(string)
return s
}
func touint64(x interface{}) uint64 {
var i = x.(uint64)
return i
}
func toint64(x interface{}) int64 {
var i = x.(int64)
return i
}
func touint(x interface{}) uint {
var i = x.(uint)
return i
}
func toint(x interface{}) int {
var i = x.(int)
return i
}
func tofloat64(x interface{}) float64 {
var i = x.(float64)
return i
}
func tofloat32(x interface{}) float32 {
var i = x.(float32)
return i
}
func pn(fieldname string) {
var e = fmt.Sprintf("The %s field for sort should always be a same type", fieldname)
panic(e)
} | pair.go | 0.669637 | 0.402451 | pair.go | starcoder |
package tilepix
import (
"fmt"
"math"
"github.com/faiface/pixel"
)
/*
_____ _ _
|_ _(_) |___
| | | | / -_)
|_| |_|_\___|
*/
// Tile is a TMX file structure which holds a Tiled tile.
type Tile struct {
ID ID `xml:"id,attr"`
Image *Image `xml:"image"`
// ObjectGroup is set if objects have been added to individual sprites in Tiled.
ObjectGroup *ObjectGroup `xml:"objectgroup,omitempty"`
// parentMap is the map which contains this object
parentMap *Map
}
func (t *Tile) String() string {
return fmt.Sprintf("Tile{ID: %d}", t.ID)
}
func (t *Tile) setParent(m *Map) {
t.parentMap = m
if t.Image != nil {
t.Image.setParent(m)
}
}
// DecodedTile is a convenience struct, which stores the decoded data from a Tile.
type DecodedTile struct {
ID ID
Tileset *Tileset
HorizontalFlip bool
VerticalFlip bool
DiagonalFlip bool
Nil bool
sprite *pixel.Sprite
transform pixel.Matrix
// parentMap is the map which contains this object
parentMap *Map
}
// Draw will draw the tile to the target provided. This will calculate the sprite from the provided tileset and set the
// DecodedTiles' internal `sprite` property; this is so it is only calculated the first time.
func (t *DecodedTile) Draw(ind, columns, numRows int, ts *Tileset, target pixel.Target, offset pixel.Vec) {
if t.IsNil() {
return
}
if t.sprite == nil {
t.setSprite(columns, numRows, ts)
// Calculate the framing for the tile within its tileset's source image
pos := t.Position(ind, ts)
transform := pixel.IM.Moved(pos)
if t.DiagonalFlip {
transform = transform.Rotated(pos, math.Pi/2)
transform = transform.ScaledXY(pos, pixel.V(1, -1))
}
if t.HorizontalFlip {
transform = transform.ScaledXY(pos, pixel.V(-1, 1))
}
if t.VerticalFlip {
transform = transform.ScaledXY(pos, pixel.V(1, -1))
}
t.transform = transform
}
t.sprite.Draw(target, t.transform.Moved(offset))
}
// Position returns the relative game position.
func (t DecodedTile) Position(ind int, ts *Tileset) pixel.Vec {
gamePos := indexToGamePos(ind, t.parentMap.Width, t.parentMap.Height)
return gamePos.ScaledXY(pixel.V(float64(ts.TileWidth), float64(ts.TileHeight))).Add(pixel.V(float64(ts.TileWidth), float64(ts.TileHeight)).Scaled(0.5))
}
func (t *DecodedTile) String() string {
return fmt.Sprintf("DecodedTile{ID: %d, Is nil: %t}", t.ID, t.Nil)
}
// IsNil returns whether this tile is nil. If so, it means there is nothing set for the tile, and should be skipped in
// drawing.
func (t *DecodedTile) IsNil() bool {
return t.Nil
}
func (t *DecodedTile) setParent(m *Map) {
t.parentMap = m
}
func (t *DecodedTile) setSprite(columns, numRows int, ts *Tileset) {
if t.IsNil() {
return
}
if t.sprite == nil {
// Calculate the framing for the tile within its tileset's source image
x, y := tileIDToCoord(t.ID, columns, numRows)
iX := float64(x)*float64(ts.TileWidth) + float64(ts.Margin+ts.Spacing*(x-1))
fX := iX + float64(ts.TileWidth)
iY := float64(y)*float64(ts.TileHeight) + float64(ts.Margin+ts.Spacing*(y-1))
fY := iY + float64(ts.TileHeight)
t.sprite = pixel.NewSprite(ts.setSprite(), pixel.R(iX, iY, fX, fY))
}
} | tile.go | 0.757077 | 0.463019 | tile.go | starcoder |
package engine
import "time"
var (
position1FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
position1Table = []PerftData{
PerftData{depth: 0, nodes: 1, captures: 0, enPassants: 0, castles: 0, promotions: 0, checks: 0, mates: 0},
PerftData{depth: 1, nodes: 20, captures: 0, enPassants: 0, castles: 0, promotions: 0, checks: 0, mates: 0},
PerftData{depth: 2, nodes: 400, captures: 0, enPassants: 0, castles: 0, promotions: 0, checks: 0, mates: 0},
PerftData{depth: 3, nodes: 8902, captures: 34, enPassants: 0, castles: 0, promotions: 0, checks: 12, mates: 0},
PerftData{depth: 4, nodes: 197281, captures: 1576, enPassants: 0, castles: 0, promotions: 0, checks: 469, mates: 8},
PerftData{depth: 5, nodes: 4865609, captures: 82719, enPassants: 258, castles: 0, promotions: 0, checks: 27351, mates: 347},
PerftData{depth: 6, nodes: 119060324, captures: 2812008, enPassants: 5248, castles: 0, promotions: 0, checks: 809099, mates: 10828},
}
position2FEN = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -"
position2Table = []PerftData{
PerftData{depth: 0, nodes: 1},
PerftData{depth: 1, nodes: 48, captures: 8, enPassants: 0, castles: 2, promotions: 0, checks: 0, mates: 0},
PerftData{depth: 2, nodes: 2039, captures: 351, enPassants: 1, castles: 91, promotions: 0, checks: 3, mates: 0},
PerftData{depth: 3, nodes: 97862, captures: 17102, enPassants: 45, castles: 3162, promotions: 0, checks: 993, mates: 1},
PerftData{depth: 4, nodes: 4085603, captures: 757163, enPassants: 1929, castles: 128013, promotions: 15172, checks: 25523, mates: 43},
PerftData{depth: 5, nodes: 193690690, captures: 35043416, enPassants: 73365, castles: 4993637, promotions: 8392, checks: 3309887, mates: 30171},
}
)
// PerftData aggregates performance test data in a structure
type PerftData struct {
depth int
nodes int64
captures int64
enPassants int64
castles int64
promotions int64
checks int64
mates int64
elapsed time.Duration
}
// Perft runs a performance test against a given FEN and expected results
func Perft(fen string, expected []PerftData) {
printPerftData(NewBoard(fen), expected)
}
func perft(depth int, board *Board) PerftData {
data := PerftData{depth: depth}
generator := NewGenerator(board)
start := time.Now()
if depth == 0 {
data.depth = 0
data.nodes = 1
return data
}
moves := generator.GenerateMoves()
if len(moves) == 0 {
data.mates++
}
if generator.kingUnderCheck {
data.checks++
}
for _, move := range moves {
board.MakeMove(move)
res := perft(depth-1, board)
data.nodes += res.nodes
data.captures += res.captures
data.enPassants += res.enPassants
data.castles += res.castles
data.promotions += res.promotions
data.checks += res.checks
data.mates += res.mates
switch move.Special {
case moveCastelingShort:
data.castles++
case moveCastelingLong:
data.castles++
case movePromotion:
data.promotions++
case moveEnPassant:
data.enPassants++
}
if move.Content != Empty {
data.captures++
}
switch board.status {
case statusCheck:
data.checks++
case statusBlackMates:
data.mates++
case statusWhiteMates:
data.mates++
}
board.UndoMove()
}
data.elapsed = time.Since(start)
return data
} | engine/perft.go | 0.620047 | 0.483587 | perft.go | starcoder |
package executetest
import (
"errors"
"github.com/influxdata/flux"
"github.com/influxdata/flux/execute"
"github.com/influxdata/flux/plan"
)
// ToTestKind represents an side-effect producing kind for testing
const ToTestKind = "to-test"
// ToProcedureSpec defines an output operation. That is, an
// operation that does not transform its input data but performs a
// side effect while passing its input data through to the next op.
type ToProcedureSpec struct{}
func NewToProcedure(flux.OperationSpec, plan.Administration) (plan.ProcedureSpec, error) {
return &ToProcedureSpec{}, nil
}
func (s *ToProcedureSpec) Kind() plan.ProcedureKind {
return ToTestKind
}
func (s *ToProcedureSpec) Copy() plan.ProcedureSpec {
return s
}
func (s *ToProcedureSpec) Cost(inStats []plan.Statistics) (plan.Cost, plan.Statistics) {
return plan.Cost{}, plan.Statistics{}
}
// ToTransformation simulates an output or an identity transformation
type ToTransformation struct {
execute.ExecutionNode
d execute.Dataset
c execute.TableBuilderCache
}
func CreateToTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
c := execute.NewTableBuilderCache(a.Allocator())
d := execute.NewDataset(id, mode, c)
return &ToTransformation{d: d, c: c}, d, nil
}
func (t *ToTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
if builder, new := t.c.TableBuilder(tbl.Key()); new {
if err := execute.AddTableCols(tbl, builder); err != nil {
return err
}
if err := execute.AppendTable(tbl, builder); err != nil {
return err
}
return nil
}
return errors.New("duplicate group key")
}
func (t *ToTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return t.d.RetractTable(key)
}
func (t *ToTransformation) UpdateWatermark(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateWatermark(pt)
}
func (t *ToTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *ToTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
} | execute/executetest/output.go | 0.701406 | 0.455986 | output.go | starcoder |
package draw2d
import (
"code.google.com/p/freetype-go/freetype/raster"
)
type VertexAdder struct {
command VertexCommand
adder raster.Adder
}
func NewVertexAdder(adder raster.Adder) *VertexAdder {
return &VertexAdder{VertexNoCommand, adder}
}
func (vertexAdder *VertexAdder) NextCommand(cmd VertexCommand) {
vertexAdder.command = cmd
}
func (vertexAdder *VertexAdder) Vertex(x, y float64) {
switch vertexAdder.command {
case VertexStartCommand:
vertexAdder.adder.Start(raster.Point{raster.Fix32(x * 256), raster.Fix32(y * 256)})
default:
vertexAdder.adder.Add1(raster.Point{raster.Fix32(x * 256), raster.Fix32(y * 256)})
}
vertexAdder.command = VertexNoCommand
}
type PathAdder struct {
adder raster.Adder
firstPoint raster.Point
ApproximationScale float64
}
func NewPathAdder(adder raster.Adder) *PathAdder {
return &PathAdder{adder, raster.Point{0, 0}, 1}
}
func (pathAdder *PathAdder) Convert(paths ...*PathStorage) {
for _, path := range paths {
j := 0
for _, cmd := range path.commands {
switch cmd {
case MoveTo:
pathAdder.firstPoint = raster.Point{raster.Fix32(path.vertices[j] * 256), raster.Fix32(path.vertices[j+1] * 256)}
pathAdder.adder.Start(pathAdder.firstPoint)
j += 2
case LineTo:
pathAdder.adder.Add1(raster.Point{raster.Fix32(path.vertices[j] * 256), raster.Fix32(path.vertices[j+1] * 256)})
j += 2
case QuadCurveTo:
pathAdder.adder.Add2(raster.Point{raster.Fix32(path.vertices[j] * 256), raster.Fix32(path.vertices[j+1] * 256)}, raster.Point{raster.Fix32(path.vertices[j+2] * 256), raster.Fix32(path.vertices[j+3] * 256)})
j += 4
case CubicCurveTo:
pathAdder.adder.Add3(raster.Point{raster.Fix32(path.vertices[j] * 256), raster.Fix32(path.vertices[j+1] * 256)}, raster.Point{raster.Fix32(path.vertices[j+2] * 256), raster.Fix32(path.vertices[j+3] * 256)}, raster.Point{raster.Fix32(path.vertices[j+4] * 256), raster.Fix32(path.vertices[j+5] * 256)})
j += 6
case ArcTo:
lastPoint := arcAdder(pathAdder.adder, path.vertices[j], path.vertices[j+1], path.vertices[j+2], path.vertices[j+3], path.vertices[j+4], path.vertices[j+5], pathAdder.ApproximationScale)
pathAdder.adder.Add1(lastPoint)
j += 6
case Close:
pathAdder.adder.Add1(pathAdder.firstPoint)
}
}
}
} | draw2d/path_adder.go | 0.582966 | 0.428473 | path_adder.go | starcoder |
package inference
// Simple internationalization, get TB description.
func getTBDescription(locale string) string {
if locale == "id" {
return "Tuberculosis (TB) adalah infeksi bakteri yang menyebar dengan cara menghirup droplet ringan dari bekas batuk atau bersin dari seseorang yang sudah terinfeksi. Biasanya, TB menyerang paru-paru, tetapi TB bisa menyerang bagian tubuh lain, seperti perut, kelenjar, tulang, dan sistem saraf pusat. TB adalah kondisi yang berpotensi menjadi serius, tetapi dapat diobati apabila menggunakan antibiotik yang benar. TB menyebar melalui udara. Ketika orang yang menderita TB paru-paru batuk, meludah, atau bersin, mereka mengeluarkan bakteri TB ke udara. Seseorang hanya perlu menghirup sedikit dari bakteri ini untuk menjadi terinfeksi. Sekitar satu per empat populasi dunia menderita TB, yang menandakan bahwa ada orang sudah terinfeksi dengan bakteri TB tetapi belum sakit dan tidak bisa menularkannya."
}
return "Tuberculosis (TB) is a bacterial infection spread through inhaling tiny droplets from the coughs or sneezes of an infected person. It mainly affects the lungs, but it can affect any part of the body, including the tummy (abdomen), glands, bones and nervous system. TB is a potentially serious condition, but it can be cured if it is treated with the right antibiotics. TB is spread from person to person through the air. When people with lung TB cough, sneeze or spit, they propel the TB germs into the air. A person needs to inhale only a few of these germs to become infected. About one-quarter of the world's population has a TB infection, which means people have been infected by TB bacteria but are not (yet) ill with the disease and cannot transmit it."
}
// Simple internationalization, get TB treatment.
func getTBTreatment(locale string) string {
if locale == "id" {
return "TB adalah penyakit yang bisa disembuhkan. Biasanya, diperlukan antibiotik yang berdurasi enam bulan. Biasanya, ada empat buah antibiotik yang diberikan dengan informasi dan dukungan pada pasien oleh petugas kesehatan. Tanpa antibiotik, pengobatan TB menjadi lebih sulit. Sejak 2000, estimasi 66 juta jiwa sudah terselamatkan dari TB karena melakukan diagnosis dan perawatan."
}
return "TB is a treatable and curable disease. Active, drug-susceptible TB disease is treated with a standard 6-month course of 4 antimicrobial drugs that are provided with information and support to the patient by a health worker or trained volunteer. Without such support, treatment adherence is more difficult. Since 2000, an estimated 66 million lives were saved through TB diagnosis and treatment."
}
// Simple internationalization, get TB prevention.
func getTBPrevention(locale string) string {
if locale == "id" {
return "Anda dapat melakukan pencegahan dengan cara menyiapkan ventilasi yang baik, cahaya natural, dan menjaga agar kondisi lingkungan Anda tetap bersih. Direkomendasikan untuk mendapatkan vaksin untuk TB sebagai salah satu pencegahan yang paling efektif. Vaksin membuat sistem imun Anda lebih kuat, yang dapat membuat Anda menjadi lebih terjaga dari terserang TB (ada yang hingga 15 tahun). Karena beberapa faktor eksternal, ada beberapa orang yang memiliki risiko yang lebih besar untuk terkena dan sakit karena TB."
}
return "You can perform several precautions by providing good ventilation, natural light, and keeping everything clean. It is recommended to take vaccinations of TB as well. Vaccinations help you to keep your immune system in prime condition, thus allowing you to resist the virus for a longer time (some up to 15 years). Depending on some external factors, some people are more at risk for being exposed into developing the TB disease."
}
// All diseases that are in this expert system.
// Data is processed from https://www.kaggle.com/victorcaelina/tuberculosis-symptoms.
func getDiseases(locale string) []Disease {
diseases := []Disease{
{
ID: "D01",
Name: "Tuberculosis",
Description: getTBDescription(locale),
Treatment: getTBTreatment(locale),
Prevention: getTBPrevention(locale),
Source: []SourceAndLink{
{
Name: "NHS",
Link: "https://www.nhs.uk/conditions/tuberculosis-tb/",
},
{
Name: "WHO",
Link: "https://www.who.int/news-room/fact-sheets/detail/tuberculosis",
},
{
Name: "TBAlert",
Link: "https://www.tbalert.org/about-tb/what-is-tb/prevention/",
},
{
Name: "CDC Government",
Link: "https://www.cdc.gov/tb/topic/basics/tbprevention.htm",
},
},
Symptoms: []Symptom{
{
ID: "S1",
Name: "Fever for two weeks or more",
Weight: 0.513,
},
{
ID: "S2",
Name: "Coughing blood",
Weight: 0.475,
},
{
ID: "S3",
Name: "Sputum mixed with blood",
Weight: 0.519,
},
{
ID: "S4",
Name: "Night sweats",
Weight: 0.514,
},
{
ID: "S5",
Name: "Chest pain",
Weight: 0.494,
},
{
ID: "S6",
Name: "Pleuritic pain",
Weight: 0.511,
},
{
ID: "S7",
Name: "Shortness of breath",
Weight: 0.487,
},
{
ID: "S8",
Name: "Weight loss",
Weight: 0.521,
},
{
ID: "S9",
Name: "Body feels tired",
Weight: 0.496,
},
{
ID: "S10",
Name: "Lumps that appear around the armpits and neck",
Weight: 0.484,
},
{
ID: "S11",
Name: "Cough and phlegm continuously for two weeks to four weeks",
Weight: 0.493,
},
{
ID: "S12",
Name: "Swollen lymph nodes",
Weight: 0.478,
},
{
ID: "S13",
Name: "Loss of apetite",
Weight: 0.488,
},
},
},
}
return diseases
} | pkg/inference/knowledge.go | 0.589244 | 0.412353 | knowledge.go | starcoder |
package bif
import "github.com/zzossig/rabbit/object"
func opNumericEqual(ctx *object.Context, args ...object.Item) object.Item {
arg1 := args[0]
arg2 := args[1]
switch {
case arg1.Type() == object.IntegerType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal == rightVal)
case arg1.Type() == object.IntegerType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(float64(leftVal) == rightVal)
case arg1.Type() == object.IntegerType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(float64(leftVal) == rightVal)
case arg1.Type() == object.DecimalType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal == float64(rightVal))
case arg1.Type() == object.DecimalType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(leftVal == rightVal)
case arg1.Type() == object.DecimalType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(leftVal == rightVal)
case arg1.Type() == object.DoubleType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal == float64(rightVal))
case arg1.Type() == object.DoubleType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(leftVal == rightVal)
case arg1.Type() == object.DoubleType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(leftVal == rightVal)
}
return NewError("cannot eqaul types: %s, %s", arg1.Type(), arg2.Type())
}
func opNumericLessThan(ctx *object.Context, args ...object.Item) object.Item {
arg1 := args[0]
arg2 := args[1]
switch {
case arg1.Type() == object.IntegerType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal < rightVal)
case arg1.Type() == object.IntegerType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(float64(leftVal) < rightVal)
case arg1.Type() == object.IntegerType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(float64(leftVal) < rightVal)
case arg1.Type() == object.DecimalType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal < float64(rightVal))
case arg1.Type() == object.DecimalType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(leftVal < rightVal)
case arg1.Type() == object.DecimalType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(leftVal < rightVal)
case arg1.Type() == object.DoubleType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal < float64(rightVal))
case arg1.Type() == object.DoubleType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(leftVal < rightVal)
case arg1.Type() == object.DoubleType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(leftVal < rightVal)
}
return NewError("cannot less than types: %s, %s", arg1.Type(), arg2.Type())
}
func opNumericGreaterThan(ctx *object.Context, args ...object.Item) object.Item {
arg1 := args[0]
arg2 := args[1]
switch {
case arg1.Type() == object.IntegerType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal > rightVal)
case arg1.Type() == object.IntegerType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(float64(leftVal) > rightVal)
case arg1.Type() == object.IntegerType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Integer).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(float64(leftVal) > rightVal)
case arg1.Type() == object.DecimalType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal > float64(rightVal))
case arg1.Type() == object.DecimalType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(leftVal > rightVal)
case arg1.Type() == object.DecimalType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Decimal).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(leftVal > rightVal)
case arg1.Type() == object.DoubleType && arg2.Type() == object.IntegerType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Integer).Value()
return NewBoolean(leftVal > float64(rightVal))
case arg1.Type() == object.DoubleType && arg2.Type() == object.DecimalType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Decimal).Value()
return NewBoolean(leftVal > rightVal)
case arg1.Type() == object.DoubleType && arg2.Type() == object.DoubleType:
leftVal := arg1.(*object.Double).Value()
rightVal := arg2.(*object.Double).Value()
return NewBoolean(leftVal > rightVal)
}
return NewError("cannot greater than types: %s, %s", arg1.Type(), arg2.Type())
} | bif/bif_4.3.go | 0.644896 | 0.532425 | bif_4.3.go | starcoder |
package advent2021
import (
"sort"
)
// Stack used as our Stack construct
type Stack struct {
stack []rune
}
// Push adds a new value to the Stack
func (s *Stack) Push(value rune) {
s.stack = append(s.stack, value)
}
// Pop returns the last value on the Stack and updates to reomve the value from the Stack
func (s *Stack) Pop() (value rune) {
// Returns a blank rune if there are no rune's on the Stack
if len(s.stack) == 0 {
return ' '
}
// Gets the popped value
value = s.stack[len(s.stack)-1]
// Removes the value from the Stack
s.stack = s.stack[:len(s.stack)-1]
return
}
// isOpenning returns if the bracket is an openning
func isOpenning(r rune) bool {
return r == '{' || r == '(' || r == '<' || r == '['
}
// isClosing returns if the bracket is a closing
func isClosing(ending, popped rune) (closing bool) {
switch ending {
case ')':
if popped == '(' {
closing = true
}
case '}':
if popped == '{' {
closing = true
}
case ']':
if popped == '[' {
closing = true
}
case '>':
if popped == '<' {
closing = true
}
}
return
}
// isLineCorrupted returns if the line is corrupted or not and the braket that starts the corruption
func (s Stack) isLineCorrupted(input string) (rune, bool) {
for _, char := range input {
charRune := rune(char)
if isOpenning(charRune) {
s.Push(char)
} else {
if popped := s.Pop(); !isClosing(charRune, popped) {
return charRune, true
}
}
}
return ' ', false
}
// calculateCharScore returns the score based on the provided rune
func calculateCharScore(r rune) (s int) {
switch r {
case ')':
s = 3
case ']':
s = 57
case '}':
s = 1197
case '>':
s = 25137
}
return
}
// completeLine returns the remainder of a partial line based on the remaining unmatched portions in the Stack
func (s Stack) completeLine(input string) string {
for _, char := range input {
charRune := rune(char)
if isOpenning(charRune) {
s.Push(char)
} else {
s.Pop()
}
}
remainingChars := []rune{}
for _, charRune := range s.stack {
switch charRune {
case '(':
remainingChars = append(remainingChars, ')')
case '[':
remainingChars = append(remainingChars, ']')
case '{':
remainingChars = append(remainingChars, '}')
case '<':
remainingChars = append(remainingChars, '>')
}
}
orderedChars := []rune{}
for i := len(remainingChars) - 1; i >= 0; i-- {
orderedChars = append(orderedChars, remainingChars[i])
}
return string(orderedChars)
}
// calculateLineScore returns the score based on the provided remainder of the line
func calculateLineScore(line string) (score int) {
for _, char := range line {
score *= 5
switch char {
case ')':
score++
case ']':
score += 2
case '}':
score += 3
case '>':
score += 4
}
}
return
}
// Day10Part1 returns the cumalative score of all the corrupted lines based on the individual char scores
func Day10Part1(inputs []string) (score int) {
stack := Stack{}
for _, input := range inputs {
if char, corrupted := stack.isLineCorrupted(input); corrupted {
score += calculateCharScore(char)
}
}
return
}
// Day10Part2 returns the middle score from all the incomplete scores after sorting
func Day10Part2(inputs []string) (middleScore int) {
stack := Stack{}
scores := []int{}
for _, input := range inputs {
if _, corrupted := stack.isLineCorrupted(input); !corrupted {
// Note: This is an imperfect solution as it runs through some of the input line twice but will do for now
stack := Stack{}
lineScore := calculateLineScore(stack.completeLine(input))
scores = append(scores, lineScore)
}
}
sort.Sort(sort.IntSlice(scores))
return scores[(len(scores))/2]
} | internal/pkg/advent2021/day10.go | 0.679391 | 0.605916 | day10.go | starcoder |
package xmorph
import (
"fmt"
"math"
"strconv"
"strings"
)
// A Point is a float64-valued (x, y) coordinate. The axes increase right and
// down.
type Point struct {
X float64
Y float64
}
// Add adds one Point to another to produce a third Point.
func (p Point) Add(q Point) Point {
return Point{
X: p.X + q.X,
Y: p.Y + q.Y,
}
}
// Sub subtracts one Point from another to produce a third Point.
func (p Point) Sub(q Point) Point {
return Point{
X: p.X - q.X,
Y: p.Y - q.Y,
}
}
// Mul multiplies a Point by a scalar to produce a new Point.
func (p Point) Mul(k float64) Point {
return Point{
X: p.X * k,
Y: p.Y * k,
}
}
// Div divides a Point by a scalar to produce a new Point.
func (p Point) Div(k float64) Point {
return Point{
X: p.X / k,
Y: p.Y / k,
}
}
// Eq reports whether two Points are equal within a given tolerance. The
// tolerance is applied separately to the x and y coordinates; both must be
// within tolerance for the function to return true.
func (p Point) Eq(q Point, tol float64) bool {
if tol < 0.0 {
panic("Eq tolerance must be non-negative")
}
dx := math.Abs(p.X - q.X)
dy := math.Abs(p.Y - q.Y)
return dx <= tol && dy <= tol
}
// formatString performs most of the work for Format. The difference is that
// it returns a string, which Format sends to the correct receiver.
func (p Point) formatString(st fmt.State, verb rune) string {
type RawPoint Point // Fresh method set
switch verb {
case 'v':
if st.Flag('#') {
str := fmt.Sprintf("%#v", RawPoint(p))
str = strings.Replace(str, "RawPoint", "Point", 1)
return str
}
return fmt.Sprintf("[%v, %v]", p.X, p.Y)
case 'b', 'e', 'E', 'f', 'F', 'g', 'G', 'x', 'X':
// Propagate all known flags when provided.
fstr := "%"
fl := make([]rune, 0, 5)
for _, c := range "+-# 0" {
if st.Flag(int(c)) {
fl = append(fl, c)
}
}
fstr += string(fl)
// Propagate the width and precision when provided.
if wd, ok := st.Width(); ok {
fstr += strconv.Itoa(wd)
}
if prec, ok := st.Precision(); ok {
fstr += "." + strconv.Itoa(prec)
}
// Retain the verb as is.
fstr += string(verb)
// Apply the format to X and Y.
return fmt.Sprintf("["+fstr+", "+fstr+"]", p.X, p.Y)
}
return "%![invalid Point format]"
}
// Format applies standard numeric formatting to a Point's coordinates when
// outputting it via fmt.Printf et al.
func (p Point) Format(st fmt.State, verb rune) {
fmt.Fprintf(st, p.formatString(st, verb))
} | point.go | 0.881806 | 0.503174 | point.go | starcoder |
package mp4
import (
"encoding/binary"
"errors"
)
// SliceReader - read integers from a slice
type SliceReader struct {
slice []byte
pos int
}
// NewSliceReader - create a new slice reader reading from data
func NewSliceReader(data []byte) *SliceReader {
return &SliceReader{
slice: data,
pos: 0,
}
}
// ReadUint8 - read uint8 from slice
func (s *SliceReader) ReadUint8() byte {
res := s.slice[s.pos]
s.pos++
return res
}
// ReadUint16 - read uint16 from slice
func (s *SliceReader) ReadUint16() uint16 {
res := binary.BigEndian.Uint16(s.slice[s.pos : s.pos+2])
s.pos += 2
return res
}
// ReadInt16 - read int16 from slice
func (s *SliceReader) ReadInt16() int16 {
res := binary.BigEndian.Uint16(s.slice[s.pos : s.pos+2])
s.pos += 2
return int16(res)
}
// ReadUint24 - read uint24 from slice
func (s *SliceReader) ReadUint24() uint32 {
p1 := s.ReadUint8()
p2 := s.ReadUint16()
return (uint32(p1) << 16) + uint32(p2)
}
// ReadUint32 - read uint32 from slice
func (s *SliceReader) ReadUint32() uint32 {
res := binary.BigEndian.Uint32(s.slice[s.pos : s.pos+4])
s.pos += 4
return res
}
// ReadInt32 - read int32 from slice
func (s *SliceReader) ReadInt32() int32 {
res := binary.BigEndian.Uint32(s.slice[s.pos : s.pos+4])
s.pos += 4
return int32(res)
}
// ReadUint64 - read uint64 from slice
func (s *SliceReader) ReadUint64() uint64 {
res := binary.BigEndian.Uint64(s.slice[s.pos : s.pos+8])
s.pos += 8
return res
}
// ReadInt64 - read int64 from slice
func (s *SliceReader) ReadInt64() int64 {
res := binary.BigEndian.Uint64(s.slice[s.pos : s.pos+8])
s.pos += 8
return int64(res)
}
// ReadFixedLengthString - read string of specified length
func (s *SliceReader) ReadFixedLengthString(length int) string {
res := string(s.slice[s.pos : s.pos+length])
s.pos += length
return res
}
// ReadZeroTerminatedString - read string until zero
func (s *SliceReader) ReadZeroTerminatedString() (string, error) {
startPos := s.pos
for {
c := s.slice[s.pos]
if c == 0 {
str := string(s.slice[startPos:s.pos])
s.pos++ // Next position to read
return str, nil
}
s.pos++
if s.pos >= len(s.slice) {
return "", errors.New("Did not find terminating zero")
}
}
}
// ReadBytes - read a slice of bytes
func (s *SliceReader) ReadBytes(n int) []byte {
res := s.slice[s.pos : s.pos+n]
s.pos += n
return res
}
// RemainingBytes - return remaining bytes of this slice
func (s *SliceReader) RemainingBytes() []byte {
res := s.slice[s.pos:]
s.pos = s.Length()
return res
}
// NrRemaingingByts - return number of bytes remaining
func (s *SliceReader) NrRemainingBytes() int {
return s.Length() - s.GetPos()
}
// SkipBytes - skip passed n bytes
func (s *SliceReader) SkipBytes(n int) {
if s.pos+n > s.Length() {
panic("Skipping past end of box")
}
s.pos += n
}
// SetPos - set read position is slice
func (s *SliceReader) SetPos(pos int) {
s.pos = pos
}
// GetPos - get read position is slice
func (s *SliceReader) GetPos() int {
return s.pos
}
// Length - get length of slice
func (s *SliceReader) Length() int {
return len(s.slice)
} | mp4/slicereader.go | 0.731251 | 0.420897 | slicereader.go | starcoder |
package gm
import (
"math"
"github.com/cpmech/gosl/chk"
"github.com/cpmech/gosl/num"
)
// BezierQuad implements a quadratic Bezier curve
// C(t) = (1-t)² Q0 + 2 t (1-t) Q1 + t² Q2
// = t² A + 2 t B + Q0
// A = Q2 - 2 Q1 + Q0
// B = Q1 - Q0
type BezierQuad struct {
// input
Q [][]float64 // control points; can be set outside
// auxiliary
P []float64 // a point on curve
}
// Point returns the x-y-z coordinates of a point on Bezier curve
func (o *BezierQuad) Point(C []float64, t float64) {
if len(o.Q) != 3 {
chk.Panic("Point: quadratic Bezier must be initialised first (with 3 control points)")
}
ndim := len(o.Q[0])
chk.IntAssert(len(C), ndim)
for i := 0; i < ndim; i++ {
C[i] = (1.0-t)*(1.0-t)*o.Q[0][i] + 2.0*t*(1.0-t)*o.Q[1][i] + t*t*o.Q[2][i]
}
return
}
// GetPoints returns points along the curve for given parameter values
func (o *BezierQuad) GetPoints(T []float64) (X, Y, Z []float64) {
if len(o.Q) != 3 {
chk.Panic("GetPoints: quadratic Bezier must be initialised first (with 3 control points)")
}
ndim := len(o.Q[0])
C := make([]float64, ndim)
X = make([]float64, len(T))
Y = make([]float64, len(T))
if ndim > 2 {
Z = make([]float64, len(T))
}
for i := 0; i < len(T); i++ {
o.Point(C, T[i])
X[i] = C[0]
Y[i] = C[1]
if ndim > 2 {
Z[i] = C[2]
}
}
return
}
// GetControlCoords returns the coordinates of control points as 1D arrays (e.g. for plotting)
func (o *BezierQuad) GetControlCoords() (X, Y, Z []float64) {
if len(o.Q) != 3 {
chk.Panic("GetControlCoords: quadratic Bezier must be initialised first (with 3 control points)")
}
ndim := len(o.Q[0])
X = make([]float64, len(o.Q))
Y = make([]float64, len(o.Q))
if ndim > 2 {
Z = make([]float64, len(o.Q))
}
for i := 0; i < len(o.Q); i++ {
X[i] = o.Q[i][0]
Y[i] = o.Q[i][1]
if ndim > 2 {
Z[i] = o.Q[i][2]
}
}
return
}
// DistPoint returns the distance from a point to this Bezier curve
// It finds the closest projection which is stored in P
func (o *BezierQuad) DistPoint(X []float64) float64 {
// TODO:
// 1) split this into closest projections finding
// 2) finish distance computation
// check
if len(o.Q) != 3 {
chk.Panic("DistPoint: quadratic Bezier must be initialised first (with 3 control points)")
}
ndim := len(o.Q[0])
chk.IntAssert(len(X), ndim)
// solve cubic equation
var Ai, Bi, Mi, a, b, c, d float64
for i := 0; i < ndim; i++ {
Ai = o.Q[2][i] - 2.0*o.Q[1][i] + o.Q[0][i]
Bi = o.Q[1][i] - o.Q[0][i]
Mi = o.Q[0][i] - X[i]
a += Ai * Ai
b += 3.0 * Ai * Bi
c += 2.0*Bi*Bi + Mi*Ai
d += Mi * Bi
}
if math.Abs(a) < 1e-7 {
chk.Panic("DistPoint does not yet work with this type of Bezier (straight line?):\nQ=%v\n", o.Q)
}
x1, x2, x3, nx := num.EqCubicSolveReal(b/a, c/a, d/a)
// auxiliary
if len(o.P) != ndim {
o.P = make([]float64, ndim)
}
// closest projections
t := x1
if nx == 2 {
chk.Panic("nx=2 => not implemented yet")
}
if nx == 3 {
T := []float64{x1, x2, x3}
D := []float64{-1, -1, -1}
ok := []bool{
!(x1 < 0.0 || x1 > 1.0),
!(x2 < 0.0 || x2 > 1.0),
!(x3 < 0.0 || x3 > 1.0),
}
for i, t := range T {
if ok[i] {
o.Point(o.P, t)
D[i] = ppdist(X, o.P)
}
}
}
o.Point(o.P, t)
return 0
}
// ppdist computes point-point distance
func ppdist(a, b []float64) (d float64) {
for i := 0; i < len(a); i++ {
d += (a[i] - b[i]) * (a[i] - b[i])
}
return math.Sqrt(d)
} | gm/bezier.go | 0.672224 | 0.515498 | bezier.go | starcoder |
package image
import (
"image"
"github.com/goplus/interp"
)
func init() {
interp.RegisterPackage("image", extMap, typList)
}
var extMap = map[string]interface{}{
"(*image.Alpha).AlphaAt": (*image.Alpha).AlphaAt,
"(*image.Alpha).At": (*image.Alpha).At,
"(*image.Alpha).Bounds": (*image.Alpha).Bounds,
"(*image.Alpha).ColorModel": (*image.Alpha).ColorModel,
"(*image.Alpha).Opaque": (*image.Alpha).Opaque,
"(*image.Alpha).PixOffset": (*image.Alpha).PixOffset,
"(*image.Alpha).Set": (*image.Alpha).Set,
"(*image.Alpha).SetAlpha": (*image.Alpha).SetAlpha,
"(*image.Alpha).SubImage": (*image.Alpha).SubImage,
"(*image.Alpha16).Alpha16At": (*image.Alpha16).Alpha16At,
"(*image.Alpha16).At": (*image.Alpha16).At,
"(*image.Alpha16).Bounds": (*image.Alpha16).Bounds,
"(*image.Alpha16).ColorModel": (*image.Alpha16).ColorModel,
"(*image.Alpha16).Opaque": (*image.Alpha16).Opaque,
"(*image.Alpha16).PixOffset": (*image.Alpha16).PixOffset,
"(*image.Alpha16).Set": (*image.Alpha16).Set,
"(*image.Alpha16).SetAlpha16": (*image.Alpha16).SetAlpha16,
"(*image.Alpha16).SubImage": (*image.Alpha16).SubImage,
"(*image.CMYK).At": (*image.CMYK).At,
"(*image.CMYK).Bounds": (*image.CMYK).Bounds,
"(*image.CMYK).CMYKAt": (*image.CMYK).CMYKAt,
"(*image.CMYK).ColorModel": (*image.CMYK).ColorModel,
"(*image.CMYK).Opaque": (*image.CMYK).Opaque,
"(*image.CMYK).PixOffset": (*image.CMYK).PixOffset,
"(*image.CMYK).Set": (*image.CMYK).Set,
"(*image.CMYK).SetCMYK": (*image.CMYK).SetCMYK,
"(*image.CMYK).SubImage": (*image.CMYK).SubImage,
"(*image.Gray).At": (*image.Gray).At,
"(*image.Gray).Bounds": (*image.Gray).Bounds,
"(*image.Gray).ColorModel": (*image.Gray).ColorModel,
"(*image.Gray).GrayAt": (*image.Gray).GrayAt,
"(*image.Gray).Opaque": (*image.Gray).Opaque,
"(*image.Gray).PixOffset": (*image.Gray).PixOffset,
"(*image.Gray).Set": (*image.Gray).Set,
"(*image.Gray).SetGray": (*image.Gray).SetGray,
"(*image.Gray).SubImage": (*image.Gray).SubImage,
"(*image.Gray16).At": (*image.Gray16).At,
"(*image.Gray16).Bounds": (*image.Gray16).Bounds,
"(*image.Gray16).ColorModel": (*image.Gray16).ColorModel,
"(*image.Gray16).Gray16At": (*image.Gray16).Gray16At,
"(*image.Gray16).Opaque": (*image.Gray16).Opaque,
"(*image.Gray16).PixOffset": (*image.Gray16).PixOffset,
"(*image.Gray16).Set": (*image.Gray16).Set,
"(*image.Gray16).SetGray16": (*image.Gray16).SetGray16,
"(*image.Gray16).SubImage": (*image.Gray16).SubImage,
"(*image.NRGBA).At": (*image.NRGBA).At,
"(*image.NRGBA).Bounds": (*image.NRGBA).Bounds,
"(*image.NRGBA).ColorModel": (*image.NRGBA).ColorModel,
"(*image.NRGBA).NRGBAAt": (*image.NRGBA).NRGBAAt,
"(*image.NRGBA).Opaque": (*image.NRGBA).Opaque,
"(*image.NRGBA).PixOffset": (*image.NRGBA).PixOffset,
"(*image.NRGBA).Set": (*image.NRGBA).Set,
"(*image.NRGBA).SetNRGBA": (*image.NRGBA).SetNRGBA,
"(*image.NRGBA).SubImage": (*image.NRGBA).SubImage,
"(*image.NRGBA64).At": (*image.NRGBA64).At,
"(*image.NRGBA64).Bounds": (*image.NRGBA64).Bounds,
"(*image.NRGBA64).ColorModel": (*image.NRGBA64).ColorModel,
"(*image.NRGBA64).NRGBA64At": (*image.NRGBA64).NRGBA64At,
"(*image.NRGBA64).Opaque": (*image.NRGBA64).Opaque,
"(*image.NRGBA64).PixOffset": (*image.NRGBA64).PixOffset,
"(*image.NRGBA64).Set": (*image.NRGBA64).Set,
"(*image.NRGBA64).SetNRGBA64": (*image.NRGBA64).SetNRGBA64,
"(*image.NRGBA64).SubImage": (*image.NRGBA64).SubImage,
"(*image.NYCbCrA).AOffset": (*image.NYCbCrA).AOffset,
"(*image.NYCbCrA).At": (*image.NYCbCrA).At,
"(*image.NYCbCrA).Bounds": (*image.NYCbCrA).Bounds,
"(*image.NYCbCrA).COffset": (*image.NYCbCrA).COffset,
"(*image.NYCbCrA).ColorModel": (*image.NYCbCrA).ColorModel,
"(*image.NYCbCrA).NYCbCrAAt": (*image.NYCbCrA).NYCbCrAAt,
"(*image.NYCbCrA).Opaque": (*image.NYCbCrA).Opaque,
"(*image.NYCbCrA).SubImage": (*image.NYCbCrA).SubImage,
"(*image.NYCbCrA).YCbCrAt": (*image.NYCbCrA).YCbCrAt,
"(*image.NYCbCrA).YOffset": (*image.NYCbCrA).YOffset,
"(*image.Paletted).At": (*image.Paletted).At,
"(*image.Paletted).Bounds": (*image.Paletted).Bounds,
"(*image.Paletted).ColorIndexAt": (*image.Paletted).ColorIndexAt,
"(*image.Paletted).ColorModel": (*image.Paletted).ColorModel,
"(*image.Paletted).Opaque": (*image.Paletted).Opaque,
"(*image.Paletted).PixOffset": (*image.Paletted).PixOffset,
"(*image.Paletted).Set": (*image.Paletted).Set,
"(*image.Paletted).SetColorIndex": (*image.Paletted).SetColorIndex,
"(*image.Paletted).SubImage": (*image.Paletted).SubImage,
"(*image.RGBA).At": (*image.RGBA).At,
"(*image.RGBA).Bounds": (*image.RGBA).Bounds,
"(*image.RGBA).ColorModel": (*image.RGBA).ColorModel,
"(*image.RGBA).Opaque": (*image.RGBA).Opaque,
"(*image.RGBA).PixOffset": (*image.RGBA).PixOffset,
"(*image.RGBA).RGBAAt": (*image.RGBA).RGBAAt,
"(*image.RGBA).Set": (*image.RGBA).Set,
"(*image.RGBA).SetRGBA": (*image.RGBA).SetRGBA,
"(*image.RGBA).SubImage": (*image.RGBA).SubImage,
"(*image.RGBA64).At": (*image.RGBA64).At,
"(*image.RGBA64).Bounds": (*image.RGBA64).Bounds,
"(*image.RGBA64).ColorModel": (*image.RGBA64).ColorModel,
"(*image.RGBA64).Opaque": (*image.RGBA64).Opaque,
"(*image.RGBA64).PixOffset": (*image.RGBA64).PixOffset,
"(*image.RGBA64).RGBA64At": (*image.RGBA64).RGBA64At,
"(*image.RGBA64).Set": (*image.RGBA64).Set,
"(*image.RGBA64).SetRGBA64": (*image.RGBA64).SetRGBA64,
"(*image.RGBA64).SubImage": (*image.RGBA64).SubImage,
"(*image.Uniform).At": (*image.Uniform).At,
"(*image.Uniform).Bounds": (*image.Uniform).Bounds,
"(*image.Uniform).ColorModel": (*image.Uniform).ColorModel,
"(*image.Uniform).Convert": (*image.Uniform).Convert,
"(*image.Uniform).Opaque": (*image.Uniform).Opaque,
"(*image.Uniform).RGBA": (*image.Uniform).RGBA,
"(*image.YCbCr).At": (*image.YCbCr).At,
"(*image.YCbCr).Bounds": (*image.YCbCr).Bounds,
"(*image.YCbCr).COffset": (*image.YCbCr).COffset,
"(*image.YCbCr).ColorModel": (*image.YCbCr).ColorModel,
"(*image.YCbCr).Opaque": (*image.YCbCr).Opaque,
"(*image.YCbCr).SubImage": (*image.YCbCr).SubImage,
"(*image.YCbCr).YCbCrAt": (*image.YCbCr).YCbCrAt,
"(*image.YCbCr).YOffset": (*image.YCbCr).YOffset,
"(image.Image).At": (image.Image).At,
"(image.Image).Bounds": (image.Image).Bounds,
"(image.Image).ColorModel": (image.Image).ColorModel,
"(image.PalettedImage).At": (image.PalettedImage).At,
"(image.PalettedImage).Bounds": (image.PalettedImage).Bounds,
"(image.PalettedImage).ColorIndexAt": (image.PalettedImage).ColorIndexAt,
"(image.PalettedImage).ColorModel": (image.PalettedImage).ColorModel,
"(image.Point).Add": (image.Point).Add,
"(image.Point).Div": (image.Point).Div,
"(image.Point).Eq": (image.Point).Eq,
"(image.Point).In": (image.Point).In,
"(image.Point).Mod": (image.Point).Mod,
"(image.Point).Mul": (image.Point).Mul,
"(image.Point).String": (image.Point).String,
"(image.Point).Sub": (image.Point).Sub,
"(image.Rectangle).Add": (image.Rectangle).Add,
"(image.Rectangle).At": (image.Rectangle).At,
"(image.Rectangle).Bounds": (image.Rectangle).Bounds,
"(image.Rectangle).Canon": (image.Rectangle).Canon,
"(image.Rectangle).ColorModel": (image.Rectangle).ColorModel,
"(image.Rectangle).Dx": (image.Rectangle).Dx,
"(image.Rectangle).Dy": (image.Rectangle).Dy,
"(image.Rectangle).Empty": (image.Rectangle).Empty,
"(image.Rectangle).Eq": (image.Rectangle).Eq,
"(image.Rectangle).In": (image.Rectangle).In,
"(image.Rectangle).Inset": (image.Rectangle).Inset,
"(image.Rectangle).Intersect": (image.Rectangle).Intersect,
"(image.Rectangle).Overlaps": (image.Rectangle).Overlaps,
"(image.Rectangle).Size": (image.Rectangle).Size,
"(image.Rectangle).String": (image.Rectangle).String,
"(image.Rectangle).Sub": (image.Rectangle).Sub,
"(image.Rectangle).Union": (image.Rectangle).Union,
"(image.YCbCrSubsampleRatio).String": (image.YCbCrSubsampleRatio).String,
"image.Black": &image.Black,
"image.Decode": image.Decode,
"image.DecodeConfig": image.DecodeConfig,
"image.ErrFormat": &image.ErrFormat,
"image.NewAlpha": image.NewAlpha,
"image.NewAlpha16": image.NewAlpha16,
"image.NewCMYK": image.NewCMYK,
"image.NewGray": image.NewGray,
"image.NewGray16": image.NewGray16,
"image.NewNRGBA": image.NewNRGBA,
"image.NewNRGBA64": image.NewNRGBA64,
"image.NewNYCbCrA": image.NewNYCbCrA,
"image.NewPaletted": image.NewPaletted,
"image.NewRGBA": image.NewRGBA,
"image.NewRGBA64": image.NewRGBA64,
"image.NewUniform": image.NewUniform,
"image.NewYCbCr": image.NewYCbCr,
"image.Opaque": &image.Opaque,
"image.Pt": image.Pt,
"image.Rect": image.Rect,
"image.RegisterFormat": image.RegisterFormat,
"image.Transparent": &image.Transparent,
"image.White": &image.White,
"image.ZP": &image.ZP,
"image.ZR": &image.ZR,
}
var typList = []interface{}{
(*image.Alpha)(nil),
(*image.Alpha16)(nil),
(*image.CMYK)(nil),
(*image.Config)(nil),
(*image.Gray)(nil),
(*image.Gray16)(nil),
(*image.Image)(nil),
(*image.NRGBA)(nil),
(*image.NRGBA64)(nil),
(*image.NYCbCrA)(nil),
(*image.Paletted)(nil),
(*image.PalettedImage)(nil),
(*image.Point)(nil),
(*image.RGBA)(nil),
(*image.RGBA64)(nil),
(*image.Rectangle)(nil),
(*image.Uniform)(nil),
(*image.YCbCr)(nil),
(*image.YCbCrSubsampleRatio)(nil),
} | pkg/image/export.go | 0.539469 | 0.605595 | export.go | starcoder |
package testdata
//GPS is a binary encoded GPS 3D point of interest
var gpsSlice = []byte{
/* Fix3D */ 0x03,
/* Latitude: float32(55.69147) -> 0x42, 0x5e, 0xc4, 0x11 */
0x42, 0x5e, 0xc4, 0x11,
/* Longitude: float32(12.61681) -> 0x41, 0x49, 0xde, 0x74 */
0x41, 0x49, 0xde, 0x74,
/* Altitude: float32(2.01) -> 0x40, 0x00, 0xa3, 0xd7 */
0x40, 0x00, 0xa3, 0xd7,
}
//GPS retuns a byte slice with the GPS POI:
//FixMode: Fix3D, Latitude: 55.69147, Longitude: 12.61681, Altitude: 2.01
func GPS() []byte {
s := make([]byte, 0, len(gpsSlice))
s = append(s, gpsSlice...)
return s
}
//ts is a binary encoded time, where the refence time is
//"2305-01-01T00:00:00Z" (RFC3339 encoded string).
//A dataTimeStamp is a 64-bit 2's complement big-endian encoded
//value of nanoseconds relative to the reference time:
var ts = []byte{
/* "2015-11-21T08:41:55Z" -> 0x81, 0x62, 0xf2, 0xa9, 0x91, 0x2f, 0x7e, 0x00 */
0x81, 0x62, 0xf2, 0xa9, 0x91, 0x2f, 0x7e, 0x00,
}
//TimeStamp returns a byte slice with a binary encoded time, which is relative
//to the refence time which is "2305-01-01T00:00:00Z" (RFC3339 encoded string).
//It is a 64-bit 2's complement big-endian encoded value of nanoseconds
//relative to the reference time.
func TimeStamp() []byte {
s := make([]byte, 0, len(ts))
s = append(s, ts...)
return s
}
//MessageOctets returns a byte slice, which contains GPS() immediately followed
//by TimeStamp().
func MessageOctets() []byte {
s := make([]byte, 0, 256)
s = append(s, gpsSlice...)
timeStampSlice := TimeStamp()
s = append(s, timeStampSlice...)
return s
}
var bogusGpsSlice = []byte{
/*FixMode 3D: changed to bogus value 0x04 */
0x04,
/* Latitude: float32(55.69147) -> 0x42, 0x5e, 0xc4, 0x11, but 1st byte
changed to bugus value: 0xaa */
0x42, 0x5e, 0xc4, 0x11,
/* Longitude: float32(12.61681) -> 0x41, 0x49, 0xde, 0x74 */
0x41, 0x49, 0xde, 0x74,
/* Altitude: float32(2.01) -> 0x40, 0x00, 0xa3, 0xd7 */
0x40, 0x00, 0xa3, 0xd7,
}
//BogusMessageOctets returns a byte slice, which contains BogusGPS() immediately
// followed by TimeStamp().
func BogusMessageOctets() []byte {
s := make([]byte, 0, 256)
s = append(s, bogusGpsSlice...)
timeStampSlice := TimeStamp()
s = append(s, timeStampSlice...)
return s
} | testdata/message-octets.go | 0.665519 | 0.418222 | message-octets.go | starcoder |
package calldata
import (
"fmt"
"math/rand"
"strconv"
"time"
"github.com/Pallinder/go-randomdata"
"github.com/google/uuid"
)
const (
minLen = 2
maxLen = 64
defaultCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
type Func struct {
Name string
Desc string
Func interface{}
}
var (
funcs = []Func{
{
"randomNumber",
"Generate a number in range [min=0, max)",
randomdata.Number,
},
{
"randomDecimal",
"Generate a number in range [min=0, max) with decimal point x",
randomdata.Decimal,
},
{
"randomBoolean",
"Generate a bool",
randomdata.Boolean,
},
{
"randomString",
"Generate a string from a-zA-Z0-9. Accepts a length parameter",
randomString,
},
{
"randomStringWithCharset",
"Generate a string from charset",
randomStringWithCharset,
},
{
"randomStringSample",
"Generate a string sampled from a list of strings",
randomdata.StringSample,
},
{
"randomSillyName",
"Generate a silly name",
randomdata.SillyName,
},
{
"randomMaleName",
"Generate a male name",
func() string {
return randomdata.FirstName(randomdata.Male)
},
},
{
"randomFemaleName",
"Generate a female name",
func() string {
return randomdata.FirstName(randomdata.Female)
},
},
{
"randomName",
"Generate a human name",
func() string {
return randomdata.FirstName(randomdata.RandomGender)
},
},
{
"randomMaleFullName",
"Generate a male full name",
func() string {
return randomdata.FullName(randomdata.Male)
},
},
{
"randomFemaleFullName",
"Generate a female full name",
func() string {
return randomdata.FullName(randomdata.Female)
},
},
{
"randomFullName",
"Generate a human full name",
func() string {
return randomdata.FullName(randomdata.RandomGender)
},
},
{
"randomEmail",
"Generate a email",
randomdata.Email,
},
{
"randomIpV4Address",
"Generate a valid random IPv4 address",
randomdata.IpV4Address,
},
{
"randomIpV6Address",
"Generate a valid random IPv6 address",
randomdata.IpV6Address,
},
{
"randomDateInRange",
"Generate a full date in range",
randomdata.FullDateInRange,
},
{
"randomPhoneNumber",
"Generate a phone number",
randomdata.PhoneNumber,
},
{
"string",
"Return the string representation of argument",
func(arg interface{}) string {
return fmt.Sprintf("%v", arg)
},
},
{
"quote",
"Return a double-quoted string literal representing string",
strconv.Quote,
},
{
"uuid",
"Generate a new UUID",
uuid.NewString,
},
}
random *rand.Rand
)
// SetSeeder sets seed for pseudo-random generator.
func SetSeeder(seed int64) {
if seed == 0 {
seed = time.Now().UnixNano()
}
random = rand.New(rand.NewSource(seed)) //nolint:gosec
randomdata.CustomRand(random)
}
func randomStringWithCharset(charset string, length int) string {
if length <= 0 {
length = randomdata.Number(maxLen-minLen+1) + minLen
}
if charset == "" {
charset = defaultCharset
}
runes := []rune(charset)
count := len(runes)
data := make([]rune, 0, length)
for i := 0; i < length; i++ {
data = append(data, runes[randomdata.Number(count)])
}
return string(data)
}
func randomString(length int) string {
return randomStringWithCharset(defaultCharset, length)
} | internal/calldata/functions.go | 0.542379 | 0.434341 | functions.go | starcoder |
package sims
import (
"fmt"
"math"
"github.com/NebulousLabs/Sia/siacrypto"
)
// bucketSim helps try to answer the question of variance between results when
// trying to determine what percentage of a data set someone is storing.
func bucketSim() {
fmt.Println("Bucket Variance Sim")
// Create N buckets and fill them with M objects.
n := 1000000
m := 1000
buckets0 := make([][]struct{}, n)
for i := 0; i < m; i++ {
// Put the object in a random bucket.
index := siacrypto.RandomInt(n)
buckets0[index] = append(buckets0[index], struct{}{})
// fmt.Println("Object in bucket", index)
}
// Find the closest object at the back --> makes sim more efficient.
backClosest := 0
for i := n - 1; backClosest == 0 && i != 0; i-- {
if len(buckets0[i]) != 0 {
backClosest = i
}
}
// fmt.Println("backClosest:", backClosest)
// Find the front closest object.
frontClosest := n
for i := 0; frontClosest == n && i != n; i++ {
if len(buckets0[i]) != 0 {
frontClosest = i
}
}
// fmt.Println("frontClosest:", frontClosest)
// Mean can be assumed (n / (2*m)) for large datasets.
mean := float64(n) / (2 * float64(m))
fmt.Println("Assumed Mean:", mean)
// Find the variance of the closest object.
sumVariance := float64(0)
for i := 0; i < n; i++ {
frontDistance := frontClosest - i
if frontDistance < 0 {
frontDistance = i - frontClosest
}
backDistance := i - backClosest
if backDistance < 0 {
backDistance = backClosest - i
}
if frontDistance < backDistance {
sumVariance += (float64(frontDistance) - mean) * (float64(frontDistance) - mean)
} else {
sumVariance += (float64(backDistance) - mean) * (float64(backDistance) - mean)
}
// Update frontClosest and backClosest if the closest object is the current bucket.
if frontDistance == 0 {
// After we step forward, the back closest will be this index.
backClosest = i
// Search forward for the next front closest.
for j := i + 1; frontClosest == i && j != i; j++ {
// Wrap around to the front if needed.
if j == n {
j = 0
}
if len(buckets0[j]) != 0 {
frontClosest = j
}
}
// fmt.Println("New front closest:", frontClosest)
}
}
variance := sumVariance / float64(n)
sd := math.Sqrt(variance)
// fmt.Println("Variance:", variance)
fmt.Println("Standard Deviation:", sd)
sigma := float64(4)
// Calculate the bad-luck data represented on 1 trial.
rm0 := float64(n) / (2 * ((sigma * mean)+mean))
bld0 := rm0 / float64(m)
fmt.Println(sigma, "Sigma Bad Luck, 1 Trial:", bld0)
// Calculate the bad-luck data represented on 10 trials.
rm1 := float64(n) / (2 * ((sigma * mean / math.Sqrt(10)+mean)))
bld1 := rm1 / float64(m)
fmt.Println(sigma, "Sigma Bad Luck, 10 Trial:", bld1)
// Calculate the bad-luck data represented on 100 trials.
rm2 := float64(n) / (2 * ((sigma * mean / math.Sqrt(100)+mean)))
bld2 := rm2 / float64(m)
fmt.Println(sigma, "Sigma Bad Luck, 10 Trial:", bld2)
} | sims/proofofcapacity.go | 0.66628 | 0.403802 | proofofcapacity.go | starcoder |
package assert
import (
"fmt"
"github.com/kr/pretty"
"reflect"
"runtime"
"strings"
"testing"
"time"
)
var errorPrefix = "\U0001F4A9 "
// -- Assertion handlers
func assert(t *testing.T, success bool, f func(), callDepth int) {
if !success {
_, file, line, _ := runtime.Caller(callDepth + 1)
t.Errorf("%s:%d", file, line)
f()
t.FailNow()
}
}
func equal(t *testing.T, expected, got interface{}, callDepth int, messages ...interface{}) {
fn := func() {
for _, desc := range pretty.Diff(expected, got) {
t.Error(errorPrefix, desc)
}
if len(messages) > 0 {
t.Error(errorPrefix, "-", fmt.Sprint(messages...))
}
}
assert(t, isEqual(expected, got), fn, callDepth+1)
}
func notEqual(t *testing.T, expected, got interface{}, callDepth int, messages ...interface{}) {
fn := func() {
t.Errorf("%s Unexpected: %#v", errorPrefix, got)
if len(messages) > 0 {
t.Error(errorPrefix, "-", fmt.Sprint(messages...))
}
}
assert(t, !isEqual(expected, got), fn, callDepth+1)
}
func contains(t *testing.T, expected, got string, callDepth int, messages ...interface{}) {
fn := func() {
t.Errorf("%s Expected to find: %#v", errorPrefix, expected)
t.Errorf("%s in: %#v", errorPrefix, got)
if len(messages) > 0 {
t.Error(errorPrefix, "-", fmt.Sprint(messages...))
}
}
assert(t, strings.Contains(got, expected), fn, callDepth+1)
}
func notContains(t *testing.T, unexpected, got string, callDepth int, messages ...interface{}) {
fn := func() {
t.Errorf("%s Expected not to find: %#v", errorPrefix, unexpected)
t.Errorf("%s in: %#v", errorPrefix, got)
if len(messages) > 0 {
t.Error(errorPrefix, "-", fmt.Sprint(messages...))
}
}
assert(t, !strings.Contains(got, unexpected), fn, callDepth+1)
}
func withinDuration(t *testing.T, duration time.Duration, goalTime, gotTime time.Time, callDepth int, messages ...interface{}) {
fn := func() {
t.Errorf("%s Expected %v to be within %v of %v", errorPrefix, gotTime, duration, goalTime)
if len(messages) > 0 {
t.Error(errorPrefix, "-", fmt.Sprint(messages...))
}
}
actualDuration := goalTime.Sub(gotTime)
if actualDuration < time.Duration(0) {
actualDuration = -actualDuration
}
assert(t, actualDuration <= duration, fn, callDepth+1)
}
// -- Matching
func isEqual(expected, got interface{}) bool {
if expected == nil {
return isNil(got)
} else {
return reflect.DeepEqual(expected, got)
}
}
func isNil(got interface{}) bool {
if got == nil {
return true
}
value := reflect.ValueOf(got)
switch value.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return value.IsNil()
default:
return false
}
}
// -- Public API
func Equal(t *testing.T, expected, got interface{}, messages ...interface{}) {
equal(t, expected, got, 1, messages...)
}
func NotEqual(t *testing.T, expected, got interface{}, messages ...interface{}) {
notEqual(t, expected, got, 1, messages...)
}
func True(t *testing.T, got interface{}, messages ...interface{}) {
equal(t, true, got, 1, messages...)
}
func False(t *testing.T, got interface{}, messages ...interface{}) {
equal(t, false, got, 1, messages...)
}
func Nil(t *testing.T, got interface{}, messages ...interface{}) {
equal(t, nil, got, 1, messages...)
}
func NotNil(t *testing.T, got interface{}, messages ...interface{}) {
notEqual(t, nil, got, 1, messages...)
}
func Contains(t *testing.T, expected, got string, messages ...interface{}) {
contains(t, expected, got, 1, messages...)
}
func NotContains(t *testing.T, unexpected, got string, messages ...interface{}) {
notContains(t, unexpected, got, 1, messages...)
}
func WithinDuration(t *testing.T, duration time.Duration, goalTime, gotTime time.Time, messages ...interface{}) {
withinDuration(t, duration, goalTime, gotTime, 1, messages...)
} | _workspace/src/github.com/stvp/assert/assert.go | 0.601008 | 0.523968 | assert.go | starcoder |
package tavis
import (
"context"
"os"
"os/signal"
"time"
"github.com/noriah/tavis/fftw"
"github.com/noriah/tavis/portaudio"
"github.com/pkg/errors"
)
type Device struct {
// Name is the name of the Device we want to listen to
Name string
// SampleRate is the rate at which samples are read
SampleRate float64
//LoCutFrqq is the low end of our audio spectrum
LoCutFreq float64
// HiCutFreq is the high end of our audio spectrum
HiCutFreq float64
// MonstercatFactor is how much we want to look like Monstercat
MonstercatFactor float64
// FalloffWeight is the fall-off weight
FalloffWeight float64
// BarWidth is the width of bars, in columns
BarWidth int
// SpaceWidth is the width of spaces, in columns
SpaceWidth int
// TargetFPS is how fast we want to redraw. Play with it
TargetFPS int
// ChannelCount is the number of channels we want to look at. DO NOT TOUCH
ChannelCount int
}
// NewZeroDevice creates a new Device with the default variables.
func NewZeroDevice() Device {
return Device{
Name: "default",
SampleRate: 44100,
LoCutFreq: 20,
HiCutFreq: 8000,
MonstercatFactor: 8.75,
FalloffWeight: 0.910,
BarWidth: 2,
SpaceWidth: 1,
TargetFPS: 60,
ChannelCount: 2,
}
}
// Run starts to draw the visualizer on the tcell Screen.
func (d Device) Run() error {
var (
// SampleSize is the number of frames per channel we want per read
sampleSize = int(d.SampleRate / float64(d.TargetFPS))
// FFTWDataSize is the number of data points in an fftw data set return
fftwDataSize = (sampleSize / 2) + 1
// BufferSize is the total size of our buffer (SampleSize * FrameSize)
sampleBufferSize = sampleSize * d.ChannelCount
// FFTWBufferSize is the total size of our fftw complex128 buffer
fftwBufferSize = fftwDataSize * d.ChannelCount
// DrawDelay is the time we wait between ticks to draw.
drawDelay = time.Second / time.Duration(d.TargetFPS)
)
// MAIN LOOP PREP
var (
winWidth int
winHeight int
vIterStart time.Time
vSince time.Duration
)
var audioInput = &Portaudio{
DeviceName: d.Name,
FrameSize: d.ChannelCount,
SampleSize: sampleSize,
SampleRate: d.SampleRate,
}
if err := audioInput.Init(); err != nil {
return err
}
defer audioInput.Close()
tmpBuf := make([]float64, sampleBufferSize)
//FFTW complex data
fftwBuffer := make([]complex128, fftwBufferSize)
audioBuf := audioInput.Buffer()
// Our FFTW calculator
var fftwPlan = fftw.New(
tmpBuf, fftwBuffer,
d.ChannelCount, sampleSize,
fftw.Estimate,
)
defer fftwPlan.Destroy()
// Make a spectrum
var spectrum = NewSpectrum(d.SampleRate, d.ChannelCount, sampleSize)
for xSet, vSet := range spectrum.DataSets() {
vSet.DataBuf = fftwBuffer[xSet*fftwDataSize : (xSet+1)*fftwDataSize]
}
var display = NewDisplay(spectrum.DataSets())
defer display.Close()
var barCount = display.SetWidths(d.BarWidth, d.SpaceWidth)
// Set it up with our values
spectrum.Recalculate(barCount, d.LoCutFreq, d.HiCutFreq)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// TODO(noriah): remove temprorary variables
displayChan := make(chan bool, 1)
// Handle fanout of cancel
go func() {
endSig := make(chan os.Signal, 3)
signal.Notify(endSig, os.Interrupt)
select {
case <-ctx.Done():
case <-displayChan:
case <-endSig:
}
cancel()
}()
// MAIN LOOP
display.Start(displayChan)
defer display.Stop()
audioInput.Start()
defer audioInput.Stop()
mainTicker := time.NewTicker(drawDelay)
defer mainTicker.Stop()
RunForRest: // , run!!!
for range mainTicker.C {
if vSince = time.Since(vIterStart); vSince < drawDelay {
time.Sleep(drawDelay - vSince)
}
select {
case <-ctx.Done():
break RunForRest
default:
}
vIterStart = time.Now()
winWidth, winHeight = display.Size()
if barCount != winWidth {
barCount = winWidth
spectrum.Recalculate(barCount, d.LoCutFreq, d.HiCutFreq)
}
if audioInput.ReadyRead() >= sampleSize {
if err := audioInput.Read(ctx); err != nil {
if err != portaudio.InputOverflowed {
return errors.Wrap(err, "failed to read audio input")
}
}
deFrame(tmpBuf, audioBuf, d.ChannelCount, sampleSize)
fftwPlan.Execute()
spectrum.Generate()
spectrum.Monstercat(d.MonstercatFactor)
// winHeight = winHeight / 2
spectrum.Scale(winHeight / 2)
spectrum.Falloff(d.FalloffWeight)
display.Draw(winHeight/2, 1)
}
}
return nil
}
func deFrame(dest []float64, src []float32, count, size int) {
// This "fix" is because the portaudio interface we are using does not
// work properly. I have to de-interleave the array
for xBuf, xOffset := 0, 0; xOffset < count*size; xOffset += size {
for xCnt := 0; xCnt < size; xCnt++ {
dest[xOffset+xCnt] = float64(src[xBuf])
xBuf++
}
}
} | tavis.go | 0.58522 | 0.421076 | tavis.go | starcoder |
package env
import (
"strconv"
"github.com/go-pogo/errors"
)
type Value string
// Bool tries to parse Value as a bool with strconv.ParseBool and returns it
// and any errors that occur.
func (v Value) Bool() (bool, error) {
b, err := strconv.ParseBool(string(v))
return b, errors.Trace(err)
}
// Int tries to parse Value as an int with strconv.ParseInt and returns it and
// any errors that occur.
func (v Value) Int() (int, error) {
i, err := strconv.ParseInt(string(v), 0, strconv.IntSize)
return int(i), errors.Trace(err)
}
// Int8 tries to parse Value as an int8 with strconv.ParseInt and returns it
// and any errors that occur.
func (v Value) Int8() (int8, error) {
i, err := strconv.ParseInt(string(v), 0, 8)
return int8(i), errors.Trace(err)
}
// Int16 tries to parse Value as an int16 with strconv.ParseInt and returns it
// and any errors that occur.
func (v Value) Int16() (int16, error) {
i, err := strconv.ParseInt(string(v), 0, 16)
return int16(i), errors.Trace(err)
}
// Int32 tries to parse Value as an int32 with strconv.ParseInt and returns it
// and any errors that occur.
func (v Value) Int32() (int32, error) {
i, err := strconv.ParseInt(string(v), 0, 32)
return int32(i), errors.Trace(err)
}
// Int64 tries to parse Value as an int64 with strconv.ParseInt and returns it
// and any errors that occur.
func (v Value) Int64() (int64, error) {
i, err := strconv.ParseInt(string(v), 0, 64)
return i, errors.Trace(err)
}
// Uint tries to parse Value as an uint with strconv.ParseUint and returns it
// and any errors that occur.
func (v Value) Uint() (uint, error) {
i, err := strconv.ParseUint(string(v), 0, strconv.IntSize)
return uint(i), errors.Trace(err)
}
// Uint8 tries to parse Value as an uint8 with strconv.ParseUint and returns it
// and any errors that occur.
func (v Value) Uint8() (uint8, error) {
i, err := strconv.ParseUint(string(v), 0, 8)
return uint8(i), errors.Trace(err)
}
// Uint16 tries to parse Value as an uint16 with strconv.ParseUint and returns
// it and any errors that occur.
func (v Value) Uint16() (uint16, error) {
i, err := strconv.ParseUint(string(v), 0, 16)
return uint16(i), errors.Trace(err)
}
// Uint32 tries to parse Value as an uint32 with strconv.ParseUint and returns
// it and any errors that occur.
func (v Value) Uint32() (uint32, error) {
i, err := strconv.ParseUint(string(v), 0, 32)
return uint32(i), errors.Trace(err)
}
// Uint64 tries to parse Value as an uint64 with strconv.ParseUint and returns
// it and any errors that occur.
func (v Value) Uint64() (uint64, error) {
i, err := strconv.ParseUint(string(v), 0, 64)
return i, errors.Trace(err)
}
// Float32 tries to parse Value as a float32 with strconv.ParseFloat and
// returns it and any errors that occur.
func (v Value) Float32() (float32, error) {
f, err := strconv.ParseFloat(string(v), 32)
return float32(f), errors.Trace(err)
}
// Float64 tries to parse Value as a float64 with strconv.ParseFloat and
// returns it and any errors that occur.
func (v Value) Float64() (float64, error) {
f, err := strconv.ParseFloat(string(v), 32)
return f, errors.Trace(err)
}
// Strings returns Value as a string.
func (v Value) String() string { return string(v) } | env/value.go | 0.746786 | 0.601242 | value.go | starcoder |
package lpd
// the descriptions copied from https://www.ietf.org/rfc/rfc1179.txt
var (
Separator = " "
LineEnding = "\n"
)
var (
// the server has to acknowledge all commands with a octet of zero bytes
Acknowledge byte = 0x0
)
type DaemonCommand byte
const (
/*
+----+-------+----+
| 01 | Queue | LF |
+----+-------+----+
Command code - 1
Operand - Printer queue name
This command starts the printing process if it not already running.
*/
PrintJobs DaemonCommand = 0x01
/*
+----+-------+----+
| 02 | Queue | LF |
+----+-------+----+
Command code - 2
Operand - Printer queue name
Receiving a job is controlled by a second level of commands. The
daemon is given commands by sending them over the same connection.
The commands are described in the next section (6).
After this command is sent, the client must read an acknowledgement
octet from the daemon. A positive acknowledgement is an octet of
zero bits. A negative acknowledgement is an octet of any other
pattern.
*/
ReceiveJob DaemonCommand = 0x02
/*
+----+-------+----+------+----+
| 03 | Queue | SP | List | LF |
+----+-------+----+------+----+
Command code - 3
Operand 1 - Printer queue name
Other operands - User names or job numbers
If the user names or job numbers or both are supplied then only those
jobs for those users or with those numbers will be sent.
The response is an ASCII stream which describes the printer queue.
The stream continues until the connection closes. Ends of lines are
indicated with ASCII LF control characters. The lines may also
contain ASCII HT control characters.
*/
QueueStatsShort DaemonCommand = 0x03
/*
+----+-------+----+------+----+
| 04 | Queue | SP | List | LF |
+----+-------+----+------+----+
Command code - 4
Operand 1 - Printer queue name
Other operands - User names or job numbers
If the user names or job numbers or both are supplied then only those
jobs for those users or with those numbers will be sent.
The response is an ASCII stream which describes the printer queue.
The stream continues until the connection closes. Ends of lines are
indicated with ASCII LF control characters. The lines may also
contain ASCII HT control characters.
*/
QueueStatsLong DaemonCommand = 0x04
/*
+----+-------+----+-------+----+------+----+
| 05 | Queue | SP | Agent | SP | List | LF |
+----+-------+----+-------+----+------+----+
Command code - 5
Operand 1 - Printer queue name
Operand 2 - User name making request (the agent)
Other operands - User names or job numbers
This command deletes the print jobs from the specified queue which
are listed as the other operands. If only the agent is given, the
command is to delete the currently active job. Unless the agent is
"root", it is not possible to delete a job which is not owned by the
user. This is also the case for specifying user names instead of
numbers. That is, agent "root" can delete jobs by user name but no
other agents can.
*/
RemoveJobs DaemonCommand = 0x05
)
type SubCommand byte
const (
/*
Command code - 1
+----+----+
| 01 | LF |
+----+----+
No operands should be supplied. This subcommand will remove any
files which have been created during this "Receive job" command.
*/
AbortJob SubCommand = 0x01
/*
+----+-------+----+------+----+
| 02 | Count | SP | Name | LF |
+----+-------+----+------+----+
Command code - 2
Operand 1 - Number of bytes in control file
Operand 2 - Name of control file
The control file must be an ASCII stream with the ends of lines
indicated by ASCII LF. The total number of bytes in the stream is
sent as the first operand. The name of the control file is sent as
the second. It should start with ASCII "cfA", followed by a three
digit job number, followed by the host name which has constructed the
control file. Acknowledgement processing must occur as usual after
the command is sent.
The next "Operand 1" octets over the same TCP connection are the
intended contents of the control file. Once all of the contents have
been delivered, an octet of zero bits is sent as an indication that
the file being sent is complete. A second level of acknowledgement
processing must occur at this point.
*/
SendControlFile SubCommand = 0x02
/*
+----+-------+----+------+----+
| 03 | Count | SP | Name | LF |
+----+-------+----+------+----+
Command code - 3
Operand 1 - Number of bytes in data file
Operand 2 - Name of data file
The data file may contain any 8 bit values at all. The total number
of bytes in the stream may be sent as the first operand, otherwise
the field should be cleared to 0. The name of the data file should
start with ASCII "dfA". This should be followed by a three digit job
number. The job number should be followed by the host name which has
constructed the data file. Interpretation of the contents of the
data file is determined by the contents of the corresponding control
file. If a data file length has been specified, the next "Operand 1"
octets over the same TCP connection are the intended contents of the
data file. In this case, once all of the contents have been
delivered, an octet of zero bits is sent as an indication that the
file being sent is complete. A second level of acknowledgement
processing must occur at this point.
*/
SendDataFile SubCommand = 0x03
)
// the control file commands are defined as string, i defined them as ascii hex values
type ControlFileCommand byte
const (
/*
+---+-------+----+
| C | Class | LF |
+---+-------+----+
Command code - 'C'
Operand - Name of class for banner pages
This command sets the class name to be printed on the banner page.
The name must be 31 or fewer octets. The name can be omitted. If it
is, the name of the host on which the file is printed will be used.
The class is conventionally used to display the host from which the
printing job originated. It will be ignored unless the print banner
command ('L') is also used.
*/
BannerClass ControlFileCommand = 0x43
/*
+---+------+----+
| H | Host | LF |
+---+------+----+
Command code - 'H'
Operand - Name of host
This command specifies the name of the host which is to be treated as
the source of the print job. The command must be included in the
control file. The name of the host must be 31 or fewer octets.
*/
Hostname ControlFileCommand = 0x48
/*
+---+-------+----+
| I | count | LF |
+---+-------+----+
Command code - 'I'
Operand - Indenting count
This command specifies that, for files which are printed with the
'f', of columns given. (It is ignored for other output generating
commands.) The identing count operand must be all decimal digits.
*/
Indent ControlFileCommand = 0x49
/*
+---+----------+----+
| J | Job name | LF |
+---+----------+----+
Command code - 'J'
Operand - Job name
This command sets the job name to be printed on the banner page. The
name of the job must be 99 or fewer octets. It can be omitted. The
job name is conventionally used to display the name of the file or
files which were "printed". It will be ignored unless the print
banner command ('L') is also used.
*/
JobName ControlFileCommand = 0x4a
/*
+---+------+----+
| L | User | LF |
+---+------+----+
Command code - 'L'
Operand - Name of user for burst pages
This command causes the banner page to be printed. The user name can
be omitted. The class name for banner page and job name for banner
page commands must precede this command in the control file to be
effective.
*/
PrintBanner ControlFileCommand = 0x4c
/*
+---+------+----+
| M | user | LF |
+---+------+----+
Command code - 'M'
Operand - User name
This entry causes mail to be sent to the user given as the operand at
the host specified by the 'H' entry when the printing operation ends
(successfully or unsuccessfully).
*/
MailWhenPrinted ControlFileCommand = 0x4d
/*
+---+------+----+
| N | Name | LF |
+---+------+----+
Command code - 'N'
Operand - File name
This command specifies the name of the file from which the data file
was constructed. It is returned on a query and used in printing with
the 'p' command when no title has been given. It must be 131 or
fewer octets.
*/
SourceFileName ControlFileCommand = 0x4e
/*
+---+------+----+
| P | Name | LF |
+---+------+----+
Command code - 'P'
Operand - User id
This command specifies the user identification of the entity
requesting the printing job. This command must be included in the
control file. The user identification must be 31 or fewer octets.
*/
UserID ControlFileCommand = 0x50
/*
+---+--------+----+-------+----+
| S | device | SP | inode | LF |
+---+--------+----+-------+----+
Command code - 'S'
Operand 1 - Device number
Operand 2 - Inode number
This command is used to record symbolic link data on a Unix system so
that changing a file's directory entry after a file is printed will
not print the new file. It is ignored if the data file is not
symbolically linked.
*/
SymbolicLink ControlFileCommand = 0x53
/*
+---+-------+----+
| T | title | LF |
+---+-------+----+
Command code - 'T'
Operand - Title text
This command provides a title for a file which is to be printed with
either the 'p' command. (It is ignored by all of the other printing
commands.) The title must be 79 or fewer octets.
*/
Title ControlFileCommand = 0x54
/*
+---+------+----+
| U | file | LF |
+---+------+----+
Command code - 'U'
Operand - File to unlink
This command indicates that the specified file is no longer needed.
This should only be used for data files.
*/
UnlinkDataFile ControlFileCommand = 0x55
/*
+---+-------+----+
| W | width | LF |
+---+-------+----+
Command code - 'W'
Operand - Width count
This command limits the output to the specified number of columns for
the 'f', 'l', and 'p' commands. (It is ignored for other output
generating commands.) The width count operand must be all decimal
digits. It may be silently reduced to some lower value. The default
value for the width is 132.
*/
WidthOfOutput ControlFileCommand = 0x57
/*
+---+------+----+
| 1 | file | LF |
+---+------+----+
Command code - '1'
Operand - File name
This command specifies the file name for the troff R font. [1] This
is the font which is printed using Times Roman by default.
*/
TroffRFont ControlFileCommand = 0x31
/*
+---+------+----+
| 2 | file | LF |
+---+------+----+
Command code - '2'
Operand - File name
This command specifies the file name for the troff I font. [1] This
is the font which is printed using Times Italic by default.
*/
TroffIFont ControlFileCommand = 0x32
/*
+---+------+----+
| 3 | file | LF |
+---+------+----+
Command code - '3'
Operand - File name
This command specifies the file name for the troff B font. [1] This
is the font which is printed using Times Bold by default.
*/
TroffBFont ControlFileCommand = 0x33
/*
+---+------+----+
| 4 | file | LF |
+---+------+----+
Command code - '4'
Operand - File name
This command specifies the file name for the troff S font. [1] This
is the font which is printed using Special Mathematical Font by
default.
*/
TroffSFont ControlFileCommand = 0x34
)
type OutputFormat byte
const(
/*
+---+------+----+
| c | file | LF |
+---+------+----+
Command code - 'c'
Operand - File to plot
This command causes the data file to be plotted, treating the data as
CIF (CalTech Intermediate Form) graphics language. [2]
*/
CIFFile OutputFormat = 0x63
/*
+---+------+----+
| d | file | LF |
+---+------+----+
Command code - 'd'
Operand - File to print
This command causes the data file to be printed, treating the data as
DVI (TeX output). [3]
*/
DVIFile OutputFormat = 0x64
/*
+---+------+----+
| f | file | LF |
+---+------+----+
Command code - 'f'
Operand - File to print
This command cause the data file to be printed as a plain text file,
providing page breaks as necessary. Any ASCII control characters
which are not in the following list are discarded: HT, CR, FF, LF,
and BS.
*/
PlainTextFile OutputFormat = 0x66
/*
+---+------+----+
| g | file | LF |
+---+------+----+
Command code - 'g'
Operand - File to plot
This command causes the data file to be plotted, treating the data as
output from the Berkeley Unix plot library. [1]
*/
PlotFile OutputFormat = 0x67
/*
+---+------+----+
| l | file | LF |
+---+------+----+
Command code - 'l' (lower case L)
Operand - File to print
This command causes the specified data file to printed without
filtering the control characters (as is done with the 'f' command).
*/
PrintWithLeavingControlCharacters OutputFormat = 0x6c
/*
+---+------+----+
| n | file | LF |
+---+------+----+
Command code - 'n'
Operand - File to print
This command prints the data file to be printed, treating the data as
ditroff output. [4]
*/
DitroffFile OutputFormat = 0x6e
/*
+---+------+----+
| o | file | LF |
+---+------+----+
Command code - 'o'
Operand - File to print
This command prints the data file to be printed, treating the data as
standard Postscript input.
*/
PostscriptFile OutputFormat = 0x6f
/*
+---+------+----+
| p | file | LF |
+---+------+----+
Command code - 'p'
Operand - File to print
This command causes the data file to be printed with a heading, page
numbers, and pagination. The heading should include the date and
time that printing was started, the title, and a page number
identifier followed by the page number. The title is the name of
file as specified by the 'N' command, unless the 'T' command (title)
has been given. After a page of text has been printed, a new page is
started with a new page number. (There is no way to specify the
length of the page.)
*/
PRFormat OutputFormat = 0x70
/*
+---+------+----+
| r | file | LF |
+---+------+----+
Command code - 'r'
Operand - File to print
This command causes the data file to be printed, interpreting the
first column of each line as FORTRAN carriage control. The FORTRAN
standard limits this to blank, "1", "0", and "+" carriage controls.
Most FORTRAN programmers also expect "-" (triple space) to work as
well.
*/
FortranCarriageControlFormat OutputFormat = 0x72
/*
+---+------+----+
| t | file | LF |
+---+------+----+
Command code - 't'
Operand - File to print
This command prints the data file as Graphic Systems C/A/T
phototypesetter input. [5] This is the standard output of the Unix
"troff" command.
*/
TroffFormat OutputFormat = 0x74
/*
+---+------+----+
| v | file | LF |
+---+------+----+
Command code - 'v'
Operand - File to print
This command prints a Sun raster format file. [6]
*/
RasterFormat OutputFormat = 0x76
) | constants.go | 0.531453 | 0.500305 | constants.go | starcoder |
package main
import (
"math"
"math/rand"
)
type Material interface {
Scatter(ray Ray, hit *Hit) (Vec3, Ray)
}
/**
From Wikipedia:
Lambertian reflectance is the property that defines an ideal "matte" or diffusely reflecting surface.
The apparent brightness of a Lambertian surface to an observer is the same regardless of the observer's
angle of view.
*/
type Lambertian struct {
Albedo Vec3
}
func NewLambertian(albedo Vec3) *Lambertian {
return &Lambertian{Albedo: albedo}
}
func (l *Lambertian) Scatter(_ Ray, hit *Hit) (Vec3, Ray) {
// Since apparent brightness is the same regardless of the observers angle, the
// incoming ray is not needed.
// Our bounce is just the normal plus some random direction
scattered := NewRay(hit.Point, hit.Normal.AddVec3(randomInUnitSphere()))
return l.Albedo, scattered
}
type Metal struct {
Albedo Vec3
Fuzz float64
}
func NewMetal(albedo Vec3, fuzz float64) *Metal {
return &Metal{Albedo: albedo, Fuzz: fuzz}
}
func (m *Metal) Scatter(ray Ray, hit *Hit) (Vec3, Ray) {
reflected := ray.Direction.UnitVector().Reflect(hit.Normal)
scattered := NewRay(hit.Point, reflected.AddVec3(randomInUnitSphere().MultiplyScalar(m.Fuzz)))
if scattered.Direction.Dot(hit.Normal) <= 0 {
// There is no scatter
return NewVec3(0.0, 0.0, 0.0), scattered
}
return m.Albedo, scattered
}
type Dieletric struct {
Albedo Vec3
RefractionIndex float64
}
func NewDieletric(albedo Vec3, refractionIndex float64) *Dieletric {
return &Dieletric{
Albedo: albedo,
RefractionIndex: refractionIndex,
}
}
func (d *Dieletric) Scatter(ray Ray, hit *Hit) (Vec3, Ray) {
reflected := ray.Direction.Reflect(hit.Normal)
var outwardNormal Vec3
var niOverNt float64
var cosine float64
if ray.Direction.Dot(hit.Normal) > 0 {
outwardNormal = hit.Normal.Negate()
niOverNt = d.RefractionIndex
//cosine = ray.Direction.Dot(hit.Normal) * d.RefractionIndex / ray.Direction.Length()
cosine = ray.Direction.Dot(hit.Normal) / ray.Direction.Length()
cosine = math.Sqrt(1 - d.RefractionIndex*d.RefractionIndex*(1-cosine*cosine))
} else {
outwardNormal = hit.Normal
niOverNt = 1.0 / d.RefractionIndex
cosine = -ray.Direction.Dot(hit.Normal) / ray.Direction.Length()
}
if refracts, refracted := ray.Direction.Refract(outwardNormal, niOverNt); refracts {
if rand.Float64() > schlick(cosine, d.RefractionIndex) {
return d.Albedo, NewRay(hit.Point, refracted)
}
}
return d.Albedo, NewRay(hit.Point, reflected)
}
func schlick(cosine, refractionIndex float64) float64 {
r0 := (1.0 - refractionIndex) / (1 + refractionIndex)
r0 = r0 * r0
return r0 + (1-r0)*math.Pow((1-cosine), 5)
}
/**
Create a random direction in a unit sphere.
*/
func randomInUnitSphere() Vec3 {
var unit Vec3
// go doesn't support do/while loops
done := false
for !done {
// Find a random point in a cube
x := rand.Float64()*2.0 - 1.0
y := rand.Float64()*2.0 - 1.0
z := rand.Float64()*2.0 - 1.0
// Check if the point is within a unit sphere where x^2 + y^2 + z^2 <= 1
if x*x+y*y+z*z < 1.0 {
unit = NewVec3(x, y, z)
done = true
}
}
return unit
} | cmd/weekend/material.go | 0.872293 | 0.494812 | material.go | starcoder |
package auth0fga
import (
"encoding/json"
)
// TypeDefinitions struct for TypeDefinitions
type TypeDefinitions struct {
TypeDefinitions *[]TypeDefinition `json:"type_definitions,omitempty"`
}
// NewTypeDefinitions instantiates a new TypeDefinitions 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 NewTypeDefinitions() *TypeDefinitions {
this := TypeDefinitions{}
return &this
}
// NewTypeDefinitionsWithDefaults instantiates a new TypeDefinitions 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 NewTypeDefinitionsWithDefaults() *TypeDefinitions {
this := TypeDefinitions{}
return &this
}
// GetTypeDefinitions returns the TypeDefinitions field value if set, zero value otherwise.
func (o *TypeDefinitions) GetTypeDefinitions() []TypeDefinition {
if o == nil || o.TypeDefinitions == nil {
var ret []TypeDefinition
return ret
}
return *o.TypeDefinitions
}
// GetTypeDefinitionsOk returns a tuple with the TypeDefinitions field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *TypeDefinitions) GetTypeDefinitionsOk() (*[]TypeDefinition, bool) {
if o == nil || o.TypeDefinitions == nil {
return nil, false
}
return o.TypeDefinitions, true
}
// HasTypeDefinitions returns a boolean if a field has been set.
func (o *TypeDefinitions) HasTypeDefinitions() bool {
if o != nil && o.TypeDefinitions != nil {
return true
}
return false
}
// SetTypeDefinitions gets a reference to the given []TypeDefinition and assigns it to the TypeDefinitions field.
func (o *TypeDefinitions) SetTypeDefinitions(v []TypeDefinition) {
o.TypeDefinitions = &v
}
func (o TypeDefinitions) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.TypeDefinitions != nil {
toSerialize["type_definitions"] = o.TypeDefinitions
}
return json.Marshal(toSerialize)
}
type NullableTypeDefinitions struct {
value *TypeDefinitions
isSet bool
}
func (v NullableTypeDefinitions) Get() *TypeDefinitions {
return v.value
}
func (v *NullableTypeDefinitions) Set(val *TypeDefinitions) {
v.value = val
v.isSet = true
}
func (v NullableTypeDefinitions) IsSet() bool {
return v.isSet
}
func (v *NullableTypeDefinitions) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableTypeDefinitions(val *TypeDefinitions) *NullableTypeDefinitions {
return &NullableTypeDefinitions{value: val, isSet: true}
}
func (v NullableTypeDefinitions) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableTypeDefinitions) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | model_type_definitions.go | 0.706798 | 0.49292 | model_type_definitions.go | starcoder |
package convutil
import (
"fmt"
"github.com/ghetzel/go-stockutil/mathutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/martinlindhe/unit"
)
var ConvertRoundToPlaces = 6
func parseUnit(in interface{}) Unit {
out := Invalid
if v, ok := in.(Unit); ok {
out = v
} else if vS, ok := in.(string); ok {
if v, err := ParseUnit(vS); err == nil {
out = v
} else {
panic(err.Error())
}
} else if vS, ok := in.(fmt.Stringer); ok {
if v, err := ParseUnit(vS.String()); err == nil {
out = v
} else {
panic(err.Error())
}
}
return out
}
func MustConvert(in interface{}, from interface{}, to interface{}) float64 {
if value, err := Convert(in, from, to); err == nil {
return value
} else {
panic(err.Error())
}
}
func Convert(in interface{}, from interface{}, to interface{}) (float64, error) {
if v, err := ExactConvert(in, from, to); err == nil {
return mathutil.RoundPlaces(v, ConvertRoundToPlaces), nil
} else {
return 0, err
}
}
func MustExactConvert(in interface{}, from interface{}, to interface{}) float64 {
if value, err := Convert(in, from, to); err == nil {
return value
} else {
panic(err.Error())
}
}
func ExactConvert(in interface{}, from interface{}, to interface{}) (float64, error) {
fromU := parseUnit(from)
toU := parseUnit(to)
if !fromU.IsValid() {
return 0, fmt.Errorf("invalid 'from' unit")
}
if !toU.IsValid() {
return 0, fmt.Errorf("invalid 'to' unit")
}
if v, err := stringutil.ConvertToFloat(in); err == nil {
if from == to {
return v, nil
}
if fromU.Family() != toU.Family() {
return 0, fmt.Errorf("units '%v' and '%v' are not convertible to each other", fromU, toU)
}
baseConvert := func() interface{} {
switch fromU.Family() {
case TemperatureUnits:
return convertTemperature(v, fromU, toU)
case SpeedUnits:
return convertSpeed(v, fromU, toU)
case LengthUnits:
return convertDistance(v, fromU, toU)
}
return fmt.Errorf("cannot convert from %v to %v", from, to)
}
converted := baseConvert()
if vF, ok := converted.(float64); ok {
return vF, nil
} else if err, ok := converted.(error); ok {
return 0, err
} else {
return 0, fmt.Errorf("unspecified error")
}
} else {
return 0, err
}
}
func convertTemperature(v float64, from Unit, to Unit) float64 {
var c unit.Temperature
switch from {
case Celsius:
c = unit.FromCelsius(v)
case Fahrenheit:
c = unit.FromFahrenheit(v)
case Kelvin:
c = unit.FromKelvin(v)
default:
return 0
}
switch to {
case Fahrenheit:
return c.Fahrenheit()
case Celsius:
return c.Celsius()
case Kelvin:
return c.Kelvin()
}
return 0
}
func convertSpeed(v float64, from Unit, to Unit) float64 {
c := unit.Speed(v)
switch from {
case MilesPerHour:
c *= unit.MilesPerHour
case KilometersPerHour:
c *= unit.KilometersPerHour
}
switch to {
case MetersPerSecond:
return c.MetersPerSecond()
case MilesPerHour:
return c.MilesPerHour()
case KilometersPerHour:
return c.KilometersPerHour()
}
return 0
}
func convertDistance(v float64, from Unit, to Unit) float64 {
c := unit.Length(v)
switch from {
case Feet:
c *= unit.Foot
case Miles:
c *= unit.Mile
case NauticalMiles:
c *= unit.NauticalMile
case AU:
c *= unit.AstronomicalUnit
case Lightyears, Lightminutes, Lightseconds:
c *= unit.LightYear
}
switch to {
case Meters:
return c.Meters()
case Feet:
return c.Feet()
case Miles:
return c.Miles()
case NauticalMiles:
return c.NauticalMiles()
case AU:
return c.AstronomicalUnits()
case Lightyears:
return c.LightYears()
case Lightminutes:
return (c.LightYears() * 525600)
case Lightseconds:
return (c.LightYears() * 31536000)
}
return 0
} | convutil/convutil.go | 0.694303 | 0.432902 | convutil.go | starcoder |
package template
import (
"fmt"
"html/template"
"os"
"path"
"regexp"
"strings"
m "github.com/gsiems/db-dictionary/model"
)
// T contains the tempate snippets that get concatenated to create the page template
type T struct {
sectionCount int
snippets []string
}
// C is the empty interface used for allowing the different page type
// structures (contexts) to use the same page generation function
type C interface {
}
// AddSnippet add a template snippet to the template source accumulator
func (t *T) AddSnippet(s string) {
switch s {
case "Schemas":
t.snippets = append(t.snippets, tpltSchemas())
case "SchemaTables":
t.snippets = append(t.snippets, tpltSchemaTables())
case "SchemaDomains":
t.snippets = append(t.snippets, tpltSchemaDomains())
case "SchemaColumns":
t.snippets = append(t.snippets, tpltSchemaColumns())
case "SchemaConstraintsHeader":
t.snippets = append(t.snippets, tpltSchemaConstraintsHeader())
case "SchemaCheckConstraints":
t.snippets = append(t.snippets, tpltSchemaCheckConstraints())
case "SchemaDependencies":
t.snippets = append(t.snippets, tpltSchemaDependencies())
case "SchemaUniqueConstraints":
t.snippets = append(t.snippets, tpltSchemaUniqueConstraints())
case "SchemaFKConstraints":
t.snippets = append(t.snippets, tpltSchemaFKConstraints())
case "TableConstraintsHeader":
t.snippets = append(t.snippets, tpltTableConstraintsHeader())
case "TableConstraintsFooter":
t.snippets = append(t.snippets, tpltTableConstraintsFooter())
case "TableCheckConstraints":
t.snippets = append(t.snippets, tpltTableCheckConstraints())
case "TablePrimaryKey":
t.snippets = append(t.snippets, tpltTablePrimaryKey())
case "TableUniqueConstraints":
t.snippets = append(t.snippets, tpltTableUniqueConstraints())
case "TableIndexes":
t.snippets = append(t.snippets, tpltTableIndexes())
case "TableParentKeys":
t.snippets = append(t.snippets, tpltTableParentKeys())
case "TableChildKeys":
t.snippets = append(t.snippets, tpltTableChildKeys())
case "TableDependencies":
t.snippets = append(t.snippets, tpltTableDependencies())
case "TableDependents":
t.snippets = append(t.snippets, tpltTableDependents())
case "TableFDW":
t.snippets = append(t.snippets, tpltTableFDW())
case "TableQuery":
t.snippets = append(t.snippets, tpltTableQuery())
case "OddHeader":
t.snippets = append(t.snippets, tpltOddHeader())
case "OddTables":
t.snippets = append(t.snippets, tpltOddTables())
case "OddColumns":
t.snippets = append(t.snippets, tpltOddColumns())
default:
// Assertion: if the string does not match the known snippets then it
// must be the actual string to append
t.snippets = append(t.snippets, s)
}
}
// AddTableHead adds the snippet for a table report header (based on the table type)
func (t *T) AddTableHead(tabType string) {
t.snippets = append(t.snippets, tpltTableHead(tabType))
}
// AddTableColumns adds the snippet for the columns list for a table page
// (displayed columns depend on table type: table, view, etc.)
func (t *T) AddTableColumns(tabType string) {
t.snippets = append(t.snippets, tpltTableColumns(tabType))
}
// AddPageHeader adds the initial snippet for the page to create (HTML head
// plus navigation menu bar)
func (t *T) AddPageHeader(i int, md *m.MetaData) {
t.AddSnippet(pageHeader(i, md))
}
// AddPageFooter adds the final snippet for generating the end of the page to create
func (t *T) AddPageFooter(i int, md *m.MetaData) {
t.AddSnippet(pageFooter(i, md))
}
// AddSectionHeader adds a section header for pages with multiple sections
func (t *T) AddSectionHeader(s string) {
if t.sectionCount > 0 {
t.AddSnippet("<hr/>")
}
t.sectionCount++
t.AddSnippet(sectionHeader(s))
}
// RenderPage takes the supplied view context and renders/writes the html file
func (t *T) RenderPage(dirName, fileName string, context C, minify bool) error {
ft := strings.Join(t.snippets, "")
if minify {
/*
Simple minify
running `du -s` on output
2192: pre-minification
1932: remove leading spaces -- 11.86% reduction
1920: remove line breaks -- ~ 12.41% reduction
*/
re := regexp.MustCompile(` *\n+ *`)
ft = re.ReplaceAllString(ft, "\n")
ft = strings.ReplaceAll(ft, ">\n<", "><")
ft = strings.ReplaceAll(ft, "}\n<", "}<")
}
// parse the template
templates, err := template.New("doc").Funcs(template.FuncMap{
"safeHTML": func(u string) template.HTML { return template.HTML(u) },
"fmtRownum": func(i int) string { return fmt.Sprintf("%06d", i) },
"checkMark": func(u string) string {
switch strings.ToUpper(u) {
case "X", "YES", "Y":
return "✓"
}
return ""
},
}).Parse(ft)
if err != nil {
return err
}
// ensure that the file directory exists
_, err = os.Stat(dirName)
if os.IsNotExist(err) {
err = os.MkdirAll(dirName, 0745)
if err != nil {
return err
}
}
// create the file
outfile, err := os.Create(path.Join(dirName, fileName+".html"))
if err != nil {
return err
}
defer outfile.Close()
// render and write the file
err = templates.Lookup("doc").Execute(outfile, context)
if err != nil {
return err
}
return err
} | template/template.go | 0.512205 | 0.4436 | template.go | starcoder |
package layout
import (
"fmt"
"gomatcha.io/matcha/comm"
pblayout "gomatcha.io/matcha/proto/layout"
)
// Axis represents a direction along the coordinate plane.
type Axis int
const (
AxisY Axis = 1 << iota
AxisX
)
// Edge represents a side of a rectangle.
type Edge int
const (
EdgeTop Edge = 1 << iota
EdgeBottom
EdgeLeft
EdgeRight
)
// Rect represents a 2D rectangle with the top left corner at Min and the bottom
// right corner at Max.
type Rect struct {
Min, Max Point
}
// Rt creates a rectangle with the min at X0, Y0 and the max at X1, Y1.
func Rt(x0, y0, x1, y1 float64) Rect {
return Rect{Min: Point{X: x0, Y: y0}, Max: Point{X: x1, Y: y1}}
}
// MarshalProtobuf serializes r into a protobuf object.
func (r *Rect) MarshalProtobuf() *pblayout.Rect {
return &pblayout.Rect{
Min: r.Min.MarshalProtobuf(),
Max: r.Max.MarshalProtobuf(),
}
}
// UnmarshalProtobuf deserializes r from a protobuf object.
func (r *Rect) UnmarshalProtobuf(pbrect *pblayout.Rect) {
r.Min.UnmarshalProtobuf(pbrect.Min)
r.Max.UnmarshalProtobuf(pbrect.Max)
}
// Add translates rect r by p.
func (r Rect) Add(p Point) Rect {
n := r
n.Min.X += p.X
n.Min.Y += p.Y
n.Max.X += p.X
n.Max.Y += p.Y
return n
}
// String returns a string description of r.
func (r Rect) String() string {
return fmt.Sprintf("{%v, %v, %v, %v}", r.Min.X, r.Min.Y, r.Max.X, r.Max.Y)
}
// Point represents a point on the XY coordinate system.
type Point struct {
X float64
Y float64
}
// Pt creates a point with x and y.
func Pt(x, y float64) Point {
return Point{X: x, Y: y}
}
// String returns a string description of r.
func (p Point) String() string {
return fmt.Sprintf("{%v, %v}", p.X, p.Y)
}
// MarshalProtobuf serializes p into a protobuf object.
func (p *Point) MarshalProtobuf() *pblayout.Point {
return &pblayout.Point{
X: p.X,
Y: p.Y,
}
}
// UnmarshalProtobuf deserializes p from a protobuf object.
func (p *Point) UnmarshalProtobuf(pbpoint *pblayout.Point) {
p.X = pbpoint.X
p.Y = pbpoint.Y
}
// PointNotifier wraps the comm.Notifier interface with an additional Value() method which returns a Point.
type PointNotifier interface {
comm.Notifier
Value() Point
} | layout/geometry.go | 0.86891 | 0.506469 | geometry.go | starcoder |
package spogoto
import (
"regexp"
"strings"
)
// Instruction is a unit of code signifying the type it operates on,
// the value literal of the instruction, the function to call if present,
// and the number of runs or executions that the instruction has been called.
type Instruction struct {
Type string
Value string
Function string
Runs int
}
// NewInstruction creates a new Instruction.
func NewInstruction(t string, val string, fn string) Instruction {
return Instruction{t, val, fn, 0}
}
// InstructionSet is a list of Instructions.
type InstructionSet []Instruction
// Parser parses string codes into an InstructionSet.
type Parser struct {
Functions map[string]map[string]bool
symbols []string
}
// FunctionRegistered returns true if a function of a type has been registered.
func (p *Parser) FunctionRegistered(t string, fn string) bool {
funcs, ok := p.Functions[t]
if ok {
return funcs[fn]
}
return false
}
// Parse parses string into an InstructionSet.
func (p *Parser) Parse(code Code) InstructionSet {
i := InstructionSet{}
for _, item := range code {
parsed := p.ParseItem(item)
if parsed.Type != "" {
i = append(i, parsed)
}
}
return i
}
// ParseItem parses a single string instruction into an Instruciton.
func (p *Parser) ParseItem(item string) Instruction {
var t string
var fn string
if item == "true" || item == "false" {
t = "boolean"
} else if regexp.MustCompile(`^\-?\d+$`).MatchString(item) {
t = "integer"
} else if regexp.MustCompile(`^\-?\d+\.\d+$`).MatchString(item) {
t = "float"
} else if regexp.MustCompile(`^\w+\.[^\.]+$`).MatchString(item) {
s := strings.Split(item, ".")
t = s[0]
fn = s[1]
if !p.FunctionRegistered(t, fn) {
t = ""
fn = ""
}
}
return NewInstruction(t, item, fn)
}
// RegisterFunction registers a function of a type t and adds it to its
// list of available functions.
func (p *Parser) RegisterFunction(t string, fn string) {
m, ok := p.Functions[t]
if !ok {
p.Functions[t] = map[string]bool{}
m = p.Functions[t]
}
m[fn] = true
p.symbols = append(p.symbols, t+"."+fn)
}
// Symbols return all available symbols/functions.
func (p *Parser) Symbols() []string {
return p.symbols
}
// NewParser creates a new Parser.
func NewParser() *Parser {
return &Parser{make(map[string]map[string]bool), []string{}}
} | parser.go | 0.629319 | 0.418935 | parser.go | starcoder |
package half
import (
"errors"
"math"
"strconv"
)
// A Float16 represents a 16-bit floating point number.
type Float16 uint16
//String satisfies the fmt Stringer interface
func (f Float16) String() string {
return strconv.FormatFloat(float64(f.Float32()), 'f', -1, 32)
}
// NewFloat16 allocates and returns a new Float16 set to f.
func NewFloat16(f float32) Float16 {
i := math.Float32bits(f)
sign := uint16((i >> 31) & 0x1)
exp := (i >> 23) & 0xff
exp16 := int16(exp) - 112
frac := uint16(i>>13) & 0x3ff
switch exp {
case 0:
exp16 = 0
case 0xff:
exp16 = 0x1f
default:
if exp16 > 0x1e {
exp16 = 0x1f
frac = 0
} else if exp16 < 0x01 {
exp16 = 0
frac = 0
}
}
return (Float16)((sign << 15) | uint16(exp16<<10) | frac)
}
//NewFloat16Array creates a Float16 array from a float32 array
func NewFloat16Array(array []float32) []Float16 {
var (
i uint32
sign uint16
exp uint32
exp16 int16
frac uint16
)
array16 := make([]Float16, len(array))
for idx := range array {
i = math.Float32bits(array[idx])
sign = uint16((i >> 31) & 0x1)
exp = (i >> 23) & 0xff
exp16 = int16(exp) - 112
frac = uint16(i>>13) & 0x3ff
switch exp {
case 0:
exp16 = 0
case 0xff:
exp16 = 0x1f
default:
if exp16 > 0x1e {
exp16 = 0x1f
frac = 0
} else if exp16 < 0x01 {
exp16 = 0
frac = 0
}
}
array16[idx] = (Float16)((sign << 15) | uint16(exp16<<10) | frac)
}
return array16
}
// Float32 returns the float32 representation of f.
func (f Float16) Float32() float32 {
sign := uint32((f >> 15) & 0x1)
exp := (f >> 10) & 0x1f
exp32 := uint32(exp) + 127 - 15
if exp == 0 {
exp32 = 0
} else if exp == 0x1f {
exp32 = 0xff
}
return math.Float32frombits((sign << 31) | (exp32 << 23) | ((uint32)(f&0x3ff) << 13))
}
//FillFloat32Slice will fill dest with converted src Float16 to float32 values. if len(dest)!=len(src) an error will be returned
func FillFloat32Slice(dest []float32, src []Float16) (err error) {
if len(dest) != len(src) {
return errors.New("FillFloat32Slice(dest []float32,src []float16) len(dest)!=len(src) ")
}
for i := range dest {
dest[i] = src[i].Float32()
}
return nil
}
//ToFloat32 takes an []Float16 and returns a []float32
func ToFloat32(array []Float16) []float32 {
var (
sign uint32
exp uint16
exp32 uint32
f uint16
)
array32 := make([]float32, len(array))
for i := range array32 {
f = (uint16)(array[i])
sign = uint32((f >> 15) & 0x1)
exp = (f >> 10) & 0x1f
exp32 = uint32(exp) + 127 - 15
if exp == 0 {
exp32 = 0
} else if exp == 0x1f {
exp32 = 0xff
}
array32[i] = math.Float32frombits((sign << 31) | (exp32 << 23) | ((uint32)(f&0x3ff) << 13))
}
return array32
} | float16.go | 0.695958 | 0.41117 | float16.go | starcoder |
package challenge
import (
"encoding/base64"
"sort"
)
// HammingDistance takes two strings and returns the number of bits
// that differ in their byte representation.
func HammingDistance(left, right string) int {
dist := 0
if len(left) > len(right) {
dist += (len(left) - len(right)) * ByteBitSize
left = left[:len(right)]
} else if len(right) > len(left) {
dist += (len(right) - len(left)) * ByteBitSize
right = right[:len(left)]
}
for i := 0; i < len(left); i++ {
diff := left[i] ^ right[i]
for shift := 0; shift < 8; shift++ {
if (diff>>shift)&1 == 1 {
dist++
}
}
}
return dist
}
// Base64ToBytes takes a string containing base64-encoded bytes and
// returns those bytes and any decoding error that occurred.
func Base64ToBytes(encoded string) ([]byte, error) {
return base64.StdEncoding.DecodeString(encoded)
}
// KeysizeDist is a structure containing the combination of a given
// Keysize and a measure of its Distance.
type KeysizeDist struct {
Keysize int
Dist float64
}
// FindProbableKeysize takes a []byte ciphertext encrypted using a
// repeating key XOR cipher and finds the probable keysize.
func FindProbableKeysize(inputBytes []byte) int {
const (
minKeysize = 1
maxKeysize = 60
topNKeysizes = 10
partsToInvestigate = 10
)
ndists := []KeysizeDist{}
// Let KEYSIZE be the guessed length of the key; try values from 2
// to (say) 40.
for KEYSIZE := minKeysize; KEYSIZE <= maxKeysize; KEYSIZE++ {
// For each KEYSIZE, take the first KEYSIZE worth of bytes,
// and the second KEYSIZE worth of bytes, and find the edit
// distance between them. Normalize this result by dividing by
// KEYSIZE.
firstPart := inputBytes[:KEYSIZE]
secondPart := inputBytes[KEYSIZE : KEYSIZE*2]
dist := HammingDistance(string(firstPart), string(secondPart))
ndist := float64(dist) / float64(KEYSIZE)
ndists = append(ndists, KeysizeDist{KEYSIZE, ndist})
}
// The KEYSIZE with the smallest normalized edit distance is
// probably the key.
sort.SliceStable(ndists, func(i, j int) bool {
return ndists[i].Dist < ndists[j].Dist
})
// Take the most likely N KEYSIZEs
mostLikelyKeysizes := []int{}
for i := 0; i < topNKeysizes; i++ {
mostLikelyKeysizes = append(mostLikelyKeysizes, ndists[i].Keysize)
}
// For each of these most likely KEYSIZEs, take more KEYSIZE
// blocks and compute the average hamming distance between them.
avgNdists := []KeysizeDist{}
for _, KEYSIZE := range mostLikelyKeysizes {
parts := [][]byte{}
for i := 0; i < partsToInvestigate; i++ {
parts = append(parts, inputBytes[KEYSIZE*i:KEYSIZE*(i+1)])
}
ndists := []float64{}
for i, part := range parts {
for j := i + 1; j < len(parts); j++ {
dist := HammingDistance(
string(part), string(parts[j]),
)
ndists = append(ndists, float64(dist)/float64(KEYSIZE))
}
}
var avgNdist float64
for _, ndist := range ndists {
avgNdist += ndist / float64(len(ndists))
}
avgNdists = append(avgNdists, KeysizeDist{KEYSIZE, avgNdist})
}
// The KEYSIZE with the smallest normalized edit distance is
// probably the key.
sort.SliceStable(avgNdists, func(i, j int) bool {
return avgNdists[i].Dist < avgNdists[j].Dist
})
return avgNdists[0].Keysize
} | set/1/challenge/6.go | 0.831793 | 0.59972 | 6.go | starcoder |
package ggrenderer
import (
"github.com/EngoEngine/glm"
"github.com/oyberntzen/gogame/ggdebug"
)
type OrthographicCamera struct {
projectionMatrix glm.Mat4
viewMatrix glm.Mat4
viewProjectionMatrix glm.Mat4
position glm.Vec3
rotation float32
}
func NewOrthographicCamera(left, right, bottom, top float32) *OrthographicCamera {
defer ggdebug.Stop(ggdebug.Start())
camera := OrthographicCamera{
projectionMatrix: glm.Ortho2D(left, right, bottom, top),
viewMatrix: glm.Ident4(),
}
camera.viewProjectionMatrix = camera.projectionMatrix.Mul4(&camera.viewMatrix)
return &camera
}
func (camera *OrthographicCamera) SetProjection(left, right, bottom, top float32) {
defer ggdebug.Stop(ggdebug.Start())
camera.projectionMatrix = glm.Ortho2D(left, right, bottom, top)
camera.viewProjectionMatrix = camera.projectionMatrix.Mul4(&camera.viewMatrix)
}
func (camera *OrthographicCamera) SetPosition(position *glm.Vec3) {
defer ggdebug.Stop(ggdebug.Start())
camera.position = *position
camera.recalculateViewMatrix()
}
func (camera *OrthographicCamera) GetPosition() *glm.Vec3 { return &camera.position }
func (camera *OrthographicCamera) SetRotation(rotation float32) {
defer ggdebug.Stop(ggdebug.Start())
camera.rotation = glm.DegToRad(rotation)
camera.recalculateViewMatrix()
}
func (camera *OrthographicCamera) GetRotation() float32 { return glm.RadToDeg(camera.rotation) }
func (camera *OrthographicCamera) GetProjectionMatrix() *glm.Mat4 { return &camera.projectionMatrix }
func (camera *OrthographicCamera) GetViewMatrix() *glm.Mat4 { return &camera.viewMatrix }
func (camera *OrthographicCamera) GetViewProjectionMatrix() *glm.Mat4 {
return &camera.viewProjectionMatrix
}
func (camera *OrthographicCamera) recalculateViewMatrix() {
defer ggdebug.Stop(ggdebug.Start())
position := glm.Translate3D(camera.position.X(), camera.position.Y(), camera.position.Z())
rotation := glm.HomogRotate3DZ(camera.rotation)
transform := position.Mul4(&rotation)
camera.viewMatrix = transform.Inverse()
camera.viewProjectionMatrix = camera.projectionMatrix.Mul4(&camera.viewMatrix)
} | ggrenderer/orthographicCamera.go | 0.756537 | 0.448245 | orthographicCamera.go | starcoder |
package analyze
import (
"math"
intr "github.com/phil-mansfield/shellfish/math/interpolate"
)
var (
kernels = make(map[int]*intr.Kernel)
derivKernels = make(map[int]*intr.Kernel)
)
type smoothParams struct {
vals, derivs []float64
}
type internalSmoothOption func(*smoothParams)
// SmoothOption is an abstract data type which allows for the customization of
// calls to Smooth without cluttering the call signature in the common case.
// This works similarly to kwargs in other languages.
type SmoothOption internalSmoothOption
func (p *smoothParams) loadOptions(opts []SmoothOption) {
for _, opt := range opts {
opt(p)
}
}
// Vals supplies Smooth with a slice which smoothed values can be written to.
func Vals(vals []float64) SmoothOption {
return func(p *smoothParams) { p.vals = vals }
}
// Derivs supplies Smooth with a slice which smoothed derivatives can be
// written to.
func Derivs(derivs []float64) SmoothOption {
return func(p *smoothParams) { p.derivs = derivs }
}
// Smooth returns a smoothed 1D series as well as the derivative of that series
// using a Savitzky-Golay filter of the given size. It also takes optional
// arguments which allow the smoothing to be done in-place.
func Smooth(
xs, ys []float64, window int, opts ...SmoothOption,
) (vals, derivs []float64, ok bool) {
if len(xs) != len(ys) {
panic("Length of xs and ys must be the same.")
} else if len(xs) <= window {
return nil, nil, false
}
p := new(smoothParams)
p.loadOptions(opts)
vals = p.vals
derivs = p.derivs
if vals == nil {
vals = make([]float64, len(xs))
}
if derivs == nil {
derivs = make([]float64, len(xs))
}
dx := math.Log(xs[1]) - math.Log(xs[0])
k, kd := getSmoothingKernel(window, dx)
for i := range ys {
ys[i] = math.Log(ys[i])
}
k.ConvolveAt(ys, intr.Extension, vals)
kd.ConvolveAt(ys, intr.Extension, derivs)
for i := range ys {
ys[i] = math.Exp(ys[i])
}
for i := range vals {
vals[i] = math.Exp(vals[i])
}
return vals, derivs, true
}
// TODO: mutexes
func getSmoothingKernel(window int, dx float64) (k, kd *intr.Kernel) {
k, ok := kernels[window]
kd, _ = derivKernels[window]
if ok {
return k, kd
}
k = intr.NewSavGolKernel(4, window)
kd = intr.NewSavGolDerivKernel(dx, 1, 4, window)
kernels[window] = k
derivKernels[window] = kd
return k, kd
} | los/analyze/smooth.go | 0.697403 | 0.442757 | smooth.go | starcoder |
package rest
import (
"fmt"
"time"
)
// Payload is the unmarshalled request body.
type Payload map[string]interface{}
// Get returns the value with the given key as an interface{}. If the key doesn't
// exist, nil is returned with an error.
func (p Payload) Get(key string) (interface{}, error) {
if value, ok := p[key]; ok {
return value, nil
}
return nil, fmt.Errorf("No value with key '%s'", key)
}
// GetInt returns the value with the given key as an int. If the key doesn't
// exist or is not an int, the zero value is returned with an error.
func (p Payload) GetInt(key string) (int, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(int); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not an int", key)
}
// GetInt8 returns the value with the given key as an int8. If the key doesn't
// exist or is not an int8, the zero value is returned with an error.
func (p Payload) GetInt8(key string) (int8, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(int8); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not an int8", key)
}
// GetInt16 returns the value with the given key as an int16. If the key doesn't
// exist or is not an int16, the zero value is returned with an error.
func (p Payload) GetInt16(key string) (int16, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(int16); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not an int16", key)
}
// GetInt32 returns the value with the given key as an int32. If the key doesn't
// exist or is not an int32, the zero value is returned with an error.
func (p Payload) GetInt32(key string) (int32, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(int32); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not an int32", key)
}
// GetInt64 returns the value with the given key as an int64. If the key doesn't
// exist or is not an int64, the zero value is returned with an error.
func (p Payload) GetInt64(key string) (int64, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(int64); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not an int64", key)
}
// GetUint returns the value with the given key as a uint. If the key doesn't
// exist or is not a uint, the zero value is returned with an error.
func (p Payload) GetUint(key string) (uint, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(uint); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a uint", key)
}
// GetUint8 returns the value with the given key as a uint8. If the key doesn't
// exist or is not a uint8, the zero value is returned with an error.
func (p Payload) GetUint8(key string) (uint8, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(uint8); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a uint8", key)
}
// GetUint16 returns the value with the given key as a uint16. If the key doesn't
// exist or is not a uint16, the zero value is returned with an error.
func (p Payload) GetUint16(key string) (uint16, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(uint16); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a uint16", key)
}
// GetUint32 returns the value with the given key as a uint32. If the key doesn't
// exist or is not a uint32, the zero value is returned with an error.
func (p Payload) GetUint32(key string) (uint32, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(uint32); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a uint32", key)
}
// GetUint64 returns the value with the given key as a uint64. If the key doesn't
// exist or is not a uint64, the zero value is returned with an error.
func (p Payload) GetUint64(key string) (uint64, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(uint64); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a uint64", key)
}
// GetFloat32 returns the value with the given key as a Float32. If the key doesn't
// exist or is not a Float32, the zero value is returned with an error.
func (p Payload) GetFloat32(key string) (float32, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(float32); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a float32", key)
}
// GetFloat64 returns the value with the given key as a Float64. If the key doesn't
// exist or is not a Float32, the zero value is returned with an error.
func (p Payload) GetFloat64(key string) (float64, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(float64); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a float64", key)
}
// GetByte returns the value with the given key as a byte. If the key doesn't
// exist or is not a byte, the zero value is returned with an error.
func (p Payload) GetByte(key string) (byte, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(byte); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a byte", key)
}
// GetString returns the value with the given key as a string. If the key doesn't
// exist or is not a string, the zero value is returned with an error.
func (p Payload) GetString(key string) (string, error) {
value, err := p.Get(key)
if err != nil {
return "", err
}
if value, ok := value.(string); ok {
return value, nil
}
return "", fmt.Errorf("Value with key '%s' not a string", key)
}
// GetBool returns the value with the given key as a bool. If the key doesn't
// exist or is not a bool, false is returned with an error.
func (p Payload) GetBool(key string) (bool, error) {
value, err := p.Get(key)
if err != nil {
return false, err
}
if value, ok := value.(bool); ok {
return value, nil
}
return false, fmt.Errorf("Value with key '%s' not a bool", key)
}
// GetSlice returns the value with the given key as an []interface{}. If the value
// doesn't exist or is not an []interface{}, nil is returned with an error.
func (p Payload) GetSlice(key string) ([]interface{}, error) {
value, err := p.Get(key)
if err != nil {
return nil, err
}
if value, ok := value.([]interface{}); ok {
return value, nil
}
return nil, fmt.Errorf("Value with key '%s' not a slice", key)
}
// GetMap returns the value with the given key as a map[string]interface{}. If the
// key doesn't exist or is not a map[string]interface{}, nil is returned with an
// error.
func (p Payload) GetMap(key string) (map[string]interface{}, error) {
value, err := p.Get(key)
if err != nil {
return nil, err
}
if value, ok := value.(map[string]interface{}); ok {
return value, nil
}
return nil, fmt.Errorf("Value with key '%s' not a map", key)
}
// GetDuration returns the value with the given key as a time.Duration. If the key
// doesn't exist or is not a time.Duration, the zero value is returned with an
// error.
func (p Payload) GetDuration(key string) (time.Duration, error) {
value, err := p.Get(key)
if err != nil {
return 0, err
}
if value, ok := value.(time.Duration); ok {
return value, nil
}
return 0, fmt.Errorf("Value with key '%s' not a time.Duration", key)
}
// GetTime returns the value with the given key as a time.Time. If the key doesn't
// exist or is not a time.Time, the zero value is returned with an error.
func (p Payload) GetTime(key string) (time.Time, error) {
value, err := p.Get(key)
if err != nil {
return time.Time{}, err
}
if value, ok := value.(time.Time); ok {
return value, nil
}
return time.Time{}, fmt.Errorf("Value with key '%s' not a time.Time", key)
} | rest/payload.go | 0.781539 | 0.417925 | payload.go | starcoder |
package jsonpath
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/PaesslerAG/jsonpath"
"io"
"io/ioutil"
"reflect"
"strings"
)
func Contains(expression string, expected interface{}, data io.Reader) error {
value, err := JsonPath(data, expression)
if err != nil {
return err
}
ok, found := IncludesElement(value, expected)
if !ok {
return errors.New(fmt.Sprintf("\"%s\" could not be applied builtin len()", expected))
}
if !found {
return errors.New(fmt.Sprintf("\"%s\" does not contain \"%s\"", value, expected))
}
return nil
}
func Equal(expression string, expected interface{}, data io.Reader) error {
value, err := JsonPath(data, expression)
if err != nil {
return err
}
if !ObjectsAreEqual(value, expected) {
return errors.New(fmt.Sprintf("\"%s\" not equal to \"%s\"", value, expected))
}
return nil
}
func NotEqual(expression string, expected interface{}, data io.Reader) error {
value, err := JsonPath(data, expression)
if err != nil {
return err
}
if ObjectsAreEqual(value, expected) {
return errors.New(fmt.Sprintf("\"%s\" value is equal to \"%s\"", expression, expected))
}
return nil
}
func Length(expression string, expectedLength int, data io.Reader) error {
value, err := JsonPath(data, expression)
if err != nil {
return err
}
v := reflect.ValueOf(value)
if v.Len() != expectedLength {
return errors.New(fmt.Sprintf("\"%d\" not equal to \"%d\"", v.Len(), expectedLength))
}
return nil
}
func GreaterThan(expression string, minimumLength int, data io.Reader) error {
value, err := JsonPath(data, expression)
if err != nil {
return err
}
v := reflect.ValueOf(value)
if v.Len() < minimumLength {
return errors.New(fmt.Sprintf("\"%d\" is greater than \"%d\"", v.Len(), minimumLength))
}
return nil
}
func LessThan(expression string, maximumLength int, data io.Reader) error {
value, err := JsonPath(data, expression)
if err != nil {
return err
}
v := reflect.ValueOf(value)
if v.Len() > maximumLength {
return errors.New(fmt.Sprintf("\"%d\" is less than \"%d\"", v.Len(), maximumLength))
}
return nil
}
func Present(expression string, data io.Reader) error {
value, _ := JsonPath(data, expression)
if isEmpty(value) {
return errors.New(fmt.Sprintf("value not present for expression: '%s'", expression))
}
return nil
}
func NotPresent(expression string, data io.Reader) error {
value, _ := JsonPath(data, expression)
if !isEmpty(value) {
return errors.New(fmt.Sprintf("value present for expression: '%s'", expression))
}
return nil
}
func JsonPath(reader io.Reader, expression string) (interface{}, error) {
v := interface{}(nil)
b, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &v)
if err != nil {
return nil, err
}
value, err := jsonpath.Get(expression, v)
if err != nil {
return nil, fmt.Errorf("evaluating '%s' resulted in error: '%s'", expression, err)
}
return value, nil
}
// courtesy of github.com/stretchr/testify
func IncludesElement(list interface{}, element interface{}) (ok, found bool) {
listValue := reflect.ValueOf(list)
elementValue := reflect.ValueOf(element)
defer func() {
if e := recover(); e != nil {
ok = false
found = false
}
}()
if reflect.TypeOf(list).Kind() == reflect.String {
return true, strings.Contains(listValue.String(), elementValue.String())
}
if reflect.TypeOf(list).Kind() == reflect.Map {
mapKeys := listValue.MapKeys()
for i := 0; i < len(mapKeys); i++ {
if ObjectsAreEqual(mapKeys[i].Interface(), element) {
return true, true
}
}
return true, false
}
for i := 0; i < listValue.Len(); i++ {
if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
return true, true
}
}
return true, false
}
func ObjectsAreEqual(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
exp, ok := expected.([]byte)
if !ok {
return reflect.DeepEqual(expected, actual)
}
act, ok := actual.([]byte)
if !ok {
return false
}
if exp == nil || act == nil {
return exp == nil && act == nil
}
return bytes.Equal(exp, act)
}
func isEmpty(object interface{}) bool {
if object == nil {
return true
}
objValue := reflect.ValueOf(object)
switch objValue.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
return objValue.Len() == 0
case reflect.Ptr:
if objValue.IsNil() {
return true
}
deref := objValue.Elem().Interface()
return isEmpty(deref)
default:
zero := reflect.Zero(objValue.Type())
return reflect.DeepEqual(object, zero.Interface())
}
} | vendor/github.com/steinfletcher/apitest-jsonpath/jsonpath/jsonpath.go | 0.539226 | 0.475605 | jsonpath.go | starcoder |
package machine_learning
import (
"os"
"bufio"
"strings"
"strconv"
"sort"
"math"
"math/rand"
"time"
stat "github.com/gonum/stat"
)
//----------------------------------------------------------------------------------------------------------------------
type DataSet struct {
SamplesByFeature [][]float64
//Samples [][]float64
Classes []int
ClassesNum int
FeaturesNum int
SamplesNum int
ArgOrderedByFeature [][]int
}
type DataSetLoaderParams struct {
ClassesFirst, ClassesFromZero bool
Splitter string
}
func DataSetLoaderParams_Defaults() DataSetLoaderParams {
return DataSetLoaderParams{
ClassesFirst: true,
ClassesFromZero: false,
Splitter: ",",
}
}
func LoadDataSetFromFile(fileName string, params DataSetLoaderParams) (ds *DataSet) {
ds = new(DataSet)
file, err := os.Open(fileName)
if err != nil { panic(err) }
defer file.Close()
fileScanner := bufio.NewScanner(file)
//cur_sample := 0
for fileScanner.Scan() {
numbers := strings.Split(fileScanner.Text(), params.Splitter)
sample := make([]float64, len(numbers)-1)
if ds.FeaturesNum == 0 {
ds.FeaturesNum = len(sample)
ds.SamplesByFeature = make([][]float64, ds.FeaturesNum)
}
j := 0
var class_val int64
for i, element := range numbers {
if (params.ClassesFirst && i == 0) || (!params.ClassesFirst && i == len(numbers)-1) {
class_val, _ = strconv.ParseInt(element, 10, 32)
continue
}
sample[j], _ = strconv.ParseFloat(element, 64)
j += 1
}
if !params.ClassesFromZero {
class_val -= 1
}
if int(class_val) >= ds.ClassesNum {
ds.ClassesNum = int(class_val) + 1
}
for i := range sample {
ds.SamplesByFeature[i] = append(ds.SamplesByFeature[i], sample[i])
}
ds.Classes = append(ds.Classes, int(class_val))
}
ds.SamplesNum = len(ds.SamplesByFeature[0])
return
}
func (ds *DataSet) GetSample(id int) []float64 {
sample := make([]float64, ds.FeaturesNum)
ds.GetSampleInplace(id, sample)
return sample
}
func (ds *DataSet) GetSampleInplace(id int, sample []float64) {
for i := range ds.SamplesByFeature {
sample[i] = ds.SamplesByFeature[i][id]
}
}
// sort helper used to sort samples by feature
type argSortByFeature struct {
Samples []float64
Indices []int
}
func (by argSortByFeature) Len() int {
return len(by.Samples)
}
func (by argSortByFeature) Swap(i, j int) {
by.Indices[i], by.Indices[j] = by.Indices[j], by.Indices[i]
}
func (by argSortByFeature) Less(i, j int) bool {
return by.Samples[by.Indices[i]] < by.Samples[by.Indices[j]]
}
func (data_set *DataSet) GenerateArgOrderByFeatures() {
arg_sorted_samples := make([][]int, data_set.FeaturesNum)
straight_order_indices := make([]int, data_set.SamplesNum)
for i := 0; i < data_set.SamplesNum; i++ {
straight_order_indices[i] = i
}
for j := 0; j < data_set.FeaturesNum; j++ {
indices := make([]int, len(straight_order_indices))
copy(indices, straight_order_indices)
sort.Sort(argSortByFeature{ Samples: data_set.SamplesByFeature[j], Indices: indices })
arg_sorted_samples[j] = indices
}
data_set.ArgOrderedByFeature = arg_sorted_samples
}
func calculateCFS(features_correlation [][]float64, answer_correlation []float64, features_subset []int) float64 {
var ans_corr_sum float64
for _, id := range features_subset {
ans_corr_sum += math.Abs(answer_correlation[id])
}
var features_corr_sum float64
for _, idi := range features_subset {
for _, idj := range features_subset {
features_corr_sum += features_correlation[idi][idj]
}
}
d := float64(len(features_subset))
return ans_corr_sum / math.Sqrt(d + features_corr_sum)
}
func (data_set *DataSet) recursivelyMaximizeCSF(features_correlation [][]float64, answer_correlation []float64,
features_subset []int, features_count int, bestCSF float64) (float64, []int) {
if len(features_subset) == features_count {
return calculateCFS(features_correlation, answer_correlation, features_subset), features_subset
}
var best_features_subset []int
for i := features_subset[features_count-1]+1; i < data_set.FeaturesNum; i++ {
features_subset[features_count] = i
csf, next_features_subset :=
data_set.recursivelyMaximizeCSF(features_correlation, answer_correlation, features_subset, features_count+1, bestCSF)
if csf > bestCSF {
bestCSF = csf
if best_features_subset == nil {
best_features_subset = make([]int, len(features_subset))
}
copy(best_features_subset, next_features_subset)
}
}
return bestCSF, best_features_subset
}
func (data_set *DataSet) calculateCorrelations() (features_correlation [][]float64, answer_correlation []float64) {
// prepare data
features_correlation = make([][]float64, data_set.FeaturesNum)
for i := range features_correlation {
features_correlation[i] = make([]float64, data_set.FeaturesNum)
}
answer_correlation = make([]float64, data_set.FeaturesNum)
answers := make([]float64, len(data_set.Classes))
for i := range data_set.Classes {
answers[i] = float64(data_set.Classes[i])
}
// calculate correlations
for i := range data_set.SamplesByFeature {
for j := 0; j < i; j++ {
corr := math.Abs(stat.Correlation(data_set.SamplesByFeature[i], data_set.SamplesByFeature[j], nil))
features_correlation[i][j] = corr
features_correlation[j][i] = corr
}
}
for i := range data_set.SamplesByFeature {
answer_correlation[i] = math.Abs(stat.Correlation(data_set.SamplesByFeature[i], answers, nil))
}
return
}
func (data_set *DataSet) SelectFeaturesWithCFS(features_count int) []int {
features_correlation, answer_correlation := data_set.calculateCorrelations()
features_subset := make([]int, features_count)
for i := range features_subset {
features_subset[i] = i
}
_, best_features_subset := data_set.recursivelyMaximizeCSF(features_correlation, answer_correlation, features_subset, 1, 0)
return best_features_subset
}
func (data_set *DataSet) SelectFeaturesWithDispersion(dispersion float64) []int {
return make([]int, 1)
}
func (data_set *DataSet) SubsetFeatures(features_subset []int) {
newSamplesByFeatures := make([][]float64, len(features_subset))
for i, id := range features_subset {
newSamplesByFeatures[i] = data_set.SamplesByFeature[id]
}
data_set.SamplesByFeature = newSamplesByFeatures
if data_set.ArgOrderedByFeature != nil {
newArgOrderedByFeature := make([][]int, len(features_subset))
for i, id := range features_subset {
newArgOrderedByFeature[i] = data_set.ArgOrderedByFeature[id]
}
data_set.ArgOrderedByFeature = newArgOrderedByFeature
}
data_set.FeaturesNum = len(features_subset)
}
func randomShuffleInts(a []int) {
for i := range a {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
}
func subsetFloats(data []float64, indices []int) []float64 {
subset := make([]float64, len(indices))
for i, id := range indices {
subset[i] = data[id]
}
return subset
}
func subsetInts(data []int, indices []int) []int {
subset := make([]int, len(indices))
for i, id := range indices {
subset[i] = data[id]
}
return subset
}
func (data_set *DataSet) SubsetRandomSamples(percent float64) {
if percent >= 1.0 { return }
if data_set.ArgOrderedByFeature != nil {
panic("Not implemented")
}
indices := make([]int, data_set.SamplesNum)
for i := range indices {
indices[i] = i
}
rand.Seed(time.Now().UnixNano())
randomShuffleInts(indices)
indices_subset := indices[:int(float64(len(indices)) * percent)]
for j := range data_set.SamplesByFeature {
data_set.SamplesByFeature[j] = subsetFloats(data_set.SamplesByFeature[j], indices_subset)
}
data_set.Classes = subsetInts(data_set.Classes, indices_subset)
data_set.SamplesNum = len(indices_subset)
} | machine_learning/data_set.go | 0.702836 | 0.434161 | data_set.go | starcoder |
package ish
import "image"
// Lookup tables using BT.601 constants for colour channel to grayscale
// conversion.
var redToGray = grayscaleTable(0.2989)
var greenToGray = grayscaleTable(0.5870)
var blueToGray = grayscaleTable(0.1140)
// Grayscale converts an image to the grayscale colour space, using optimised
// algorithms for common source colour spaces.
func Grayscale(img image.Image) *image.Gray {
switch img := img.(type) {
case *image.RGBA:
return grayscaleRGBA(img)
case *image.NRGBA:
return grayscaleNRGBA(img)
case *image.Gray:
return img
default:
gray := image.NewGray(img.Bounds())
for y := gray.Rect.Min.Y; y <= gray.Rect.Max.Y; y++ {
for x := gray.Rect.Min.X; x <= gray.Rect.Max.X; x++ {
gray.Set(x, y, img.At(x, y))
}
}
return gray
}
}
// grayscaleRGBA implements an optimised algorithm for converting images from
// the RGBA colour space to grayscale.
func grayscaleRGBA(img *image.RGBA) *image.Gray {
gray := image.NewGray(img.Bounds())
p := 0
for q := 0; q < len(img.Pix); q += 4 {
r := img.Pix[q]
g := img.Pix[q+1]
b := img.Pix[q+2]
// Grayscale conversion using BT.601 lookup tables.
gray.Pix[p] = uint8(redToGray[r] + greenToGray[g] + blueToGray[b])
p++
}
return gray
}
// grayscaleNRGBA implements an optimised algorithm for converting images from
// the NRGBA colour space to grayscale.
func grayscaleNRGBA(img *image.NRGBA) *image.Gray {
gray := image.NewGray(img.Bounds())
p := 0
for q := 0; q < len(img.Pix); q += 4 {
// Alpha premultiplication.
alpha := float32(img.Pix[q+3]) / 255.0
r := uint8(float32(img.Pix[q]) * alpha)
g := uint8(float32(img.Pix[q+1]) * alpha)
b := uint8(float32(img.Pix[q+2]) * alpha)
// Grayscale conversion using BT.601 lookup tables.
gray.Pix[p] = uint8(redToGray[r] + greenToGray[g] + blueToGray[b])
p++
}
return gray
}
// grayscaleTable implements an algorithm to generate lookup tables for colour
// to grayscale conversion.
func grayscaleTable(factor float64) [256]uint8 {
var output [256]uint8
for i := 0; i < 256; i++ {
output[i] = uint8(float64(i) * factor)
}
return output
} | grayscale.go | 0.833189 | 0.627124 | grayscale.go | starcoder |
package series
import (
"github.com/WinPooh32/math"
)
// Mean returns mean of data's values.
func Mean(data Data) float32 {
var (
count int
mean float32
items = data.Data()
inv = 1.0 / float32(len(items))
)
for _, v := range items {
if math.IsNaN(v) {
continue
}
mean += v * inv
count++
}
if count == 0 {
return math.NaN()
}
return mean
}
// Sum returns sum of data's values.
func Sum(data Data) float32 {
var (
sum float32
count int
items = data.Data()
)
for _, v := range items {
if math.IsNaN(v) {
continue
}
sum += v
count++
}
if count == 0 {
return math.NaN()
}
return sum
}
// Min returns minimum value.
func Min(data Data) float32 {
var (
min float32 = math.MaxFloat32
count int
items = data.Data()
)
for _, v := range items {
if math.IsNaN(v) {
continue
}
if v < min {
min = v
}
count++
}
if count == 0 {
return math.NaN()
}
return min
}
// Max returns maximum value.
func Max(data Data) float32 {
var (
max float32 = -math.MaxFloat32
count int
items = data.Data()
)
for _, v := range items {
if math.IsNaN(v) {
continue
}
if v > max {
max = v
}
count++
}
if count == 0 {
return math.NaN()
}
return max
}
// Argmin returns index of the smallest value of series data.
// If the minimum is achieved in multiple locations, the first row position is returned.
func Argmin(data Data) int {
var (
min float32 = math.MaxFloat32
pos int
items = data.Data()
)
for i, v := range items {
if math.IsNaN(v) {
continue
}
if v < min {
min = v
pos = i
}
}
return pos
}
// Argmax returns index of the biggest value of series data.
// If the maximum is achieved in multiple locations, the first row position is returned.
func Argmax(data Data) int {
var (
max float32 = -math.MaxFloat32
pos int = -1
items = data.Data()
)
for i, v := range items {
if math.IsNaN(v) {
continue
}
if v > max {
max = v
pos = i
}
}
return pos
}
// Std returns standard deviation.
// Normalized by n-1.
func Std(data Data) float32 {
var (
count int
items = data.Data()
mean = Mean(data)
inv = 1.0 / float32(len(items)-1)
stdDev float32
)
for _, v := range items {
if math.IsNaN(v) {
continue
}
d := v - mean
stdDev += (d * d) * inv
count++
}
if count == 0 {
return math.NaN()
}
return math.Sqrt(stdDev)
} | aggregation.go | 0.774583 | 0.480966 | aggregation.go | starcoder |
package pearl
import (
"math"
"reflect"
)
// The Vector2 struct
type Vector2 struct {
X float64
Y float64
}
// Returns the magnitude of a Vector2 type
func (v *Vector2) Magnitude() float64 {
return math.Sqrt(v.X * v.X + v.Y * v.Y)
}
// Normalizes Vector2
func (v *Vector2) Normalize() {
magnitude := v.Magnitude()
if magnitude > 0 {
v.Divide(magnitude)
}
}
// Adds Vector2 and other (changes Vector2)
func (v *Vector2) Add(other interface {}) {
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
v.X += otherVector.X
v.Y += otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
v.X += otherValue
v.Y += otherValue
}
}
// Subtracts Vector2 and other (changes Vector2)
func (v *Vector2) Subtract(other interface {}) {
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
v.X -= otherVector.X
v.Y -= otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
v.X -= otherValue
v.Y -= otherValue
}
}
// Multiplies Vector2 and other (changes Vector2)
func (v *Vector2) Multiply(other interface {}) {
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
v.X *= otherVector.X
v.Y *= otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
v.X *= otherValue
v.Y *= otherValue
}
}
// Divides Vector2 and other (changes Vector2)
func (v *Vector2) Divide(other interface {}) {
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
v.X /= otherVector.X
v.Y /= otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
v.X /= otherValue
v.Y /= otherValue
}
}
// Floors Vector2 (changes Vector2)
func (v *Vector2) Vector2Floor() {
v.X = float64(int64(v.X))
v.Y = float64(int64(v.Y))
}
// Returns a copy of the Vector2 normalized (doesn't change Vector2)
func Normalized(v Vector2) Vector2 {
v.Normalize()
return v
}
// Adds b to vector. returns result
func Vector2Add(vector Vector2, other interface {}) Vector2 {
result := Vector2 { vector.X, vector.Y }
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
result.X += otherVector.X
result.Y += otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
result.X += otherValue
result.Y += otherValue
}
return result
}
// Subtracts a and b (doesn't change variables)
func Vector2Subtract(vector Vector2, other interface {}) Vector2 {
result := Vector2 { vector.X, vector.Y }
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
result.X -= otherVector.X
result.Y -= otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
result.X -= otherValue
result.Y -= otherValue
}
return result
}
// Multiplies a and b (doesn't change variables)
func Vector2Multiply(vector Vector2, other interface {}) Vector2 {
result := Vector2 { vector.X, vector.Y }
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
result.X *= otherVector.X
result.Y *= otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
result.X *= otherValue
result.Y *= otherValue
}
return result
}
// Divides a and b (doesn't change variables)
func Vector2Divide(vector Vector2, other interface {}) Vector2 {
result := Vector2 { vector.X, vector.Y }
t := reflect.TypeOf(other).String()
if t == "pearl.Vector2" {
otherVector := other.(Vector2)
result.X /= otherVector.X
result.Y /= otherVector.Y
} else {
val := reflect.Indirect(reflect.ValueOf(other))
otherValue := val.Convert(reflect.TypeOf(float64(0))).Float()
result.X /= otherValue
result.Y /= otherValue
}
return result
}
// Returns Vector2 floored (doesn't change Vector2)
func Vector2Floor(vector Vector2) Vector2 {
return Vector2 { float64(int64(vector.X)), float64(int64(vector.Y)) }
}
var (
// Shorthand for 0, 0
VZERO = Vector2 { 0, 0 }
// Shorthand for 1, 1
VONE = Vector2 { 1, 1 }
// Shorthand for 0, -1
VUP = Vector2 { 0, -1 }
// Shorthand for 0, 1
VDOWN = Vector2 { 0, 1 }
// Shorthand for -1, 0
VLEFT = Vector2 { -1, 0 }
// Shorthand for 1, 0
VRIGHT = Vector2 { 1, 0 }
) | vector2.go | 0.889583 | 0.760517 | vector2.go | starcoder |
package proto
import (
"bytes"
"errors"
"io"
"math"
"github.com/google/uuid"
)
// Type represents a Minecraft protocol data type.
// Implements io.ReaderFrom and io.WriterTo.
type Type interface {
io.ReaderFrom
io.WriterTo
}
// --- Boolean ---
// Boolean is either false or true.
// Implements proto.Type interface (Minecraft protocol data type).
type Boolean bool
// ReadFrom reads Boolean data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (b *Boolean) ReadFrom(r io.Reader) (n int64, err error) {
v, err := readByte(r)
if err != nil {
return 1, err
}
*b = v != 0
return 1, nil
}
// WriteTo writes Boolean data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (b Boolean) WriteTo(w io.Writer) (int64, error) {
var v byte
if b {
v = 0x01
} else {
v = 0x00
}
nn, err := w.Write([]byte{v})
return int64(nn), err
}
// --- Byte ---
// Byte is a signed 8-bit integer, two's complement.
// Implements proto.Type interface (Minecraft protocol data type).
type Byte int8
// ReadFrom reads Byte data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (b *Byte) ReadFrom(r io.Reader) (n int64, err error) {
v, err := readByte(r)
if err != nil {
return 0, err
}
*b = Byte(v)
return 1, nil
}
// WriteTo writes Byte data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (b Byte) WriteTo(w io.Writer) (n int64, err error) {
nn, err := w.Write([]byte{byte(b)})
return int64(nn), err
}
// --- UsignedByte ---
// UnsignedByte is an unsigned 8-bit integer.
// Implements proto.Type interface (Minecraft protocol data type).
type UnsignedByte uint8
// ReadFrom reads UnsignedByte data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (u *UnsignedByte) ReadFrom(r io.Reader) (n int64, err error) {
v, err := readByte(r)
if err != nil {
return 0, err
}
*u = UnsignedByte(v)
return 1, nil
}
// WriteTo writes UnsignedByte data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (u UnsignedByte) WriteTo(w io.Writer) (n int64, err error) {
nn, err := w.Write([]byte{byte(u)})
return int64(nn), err
}
// --- Short ---
// Short is a signed 16-bit integer, two's complement.
// Implements proto.Type interface (Minecraft protocol data type).
type Short int16
// ReadFrom reads Short data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (s *Short) ReadFrom(r io.Reader) (n int64, err error) {
var bs [2]byte
if nn, err := io.ReadFull(r, bs[:]); err != nil {
return int64(nn), err
} else {
n += int64(nn)
}
*s = Short(int16(bs[0])<<8 | int16(bs[1]))
return
}
// WriteTo writes Short data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (s Short) WriteTo(w io.Writer) (int64, error) {
n := uint16(s)
nn, err := w.Write([]byte{byte(n >> 8), byte(n)})
return int64(nn), err
}
// --- UnsignedShort ---
// UnsignedShort is an unsigned 16-bit integer.
// Implements proto.Type interface (Minecraft protocol data type).
type UnsignedShort uint16
// ReadFrom reads UnsignedShort data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (us *UnsignedShort) ReadFrom(r io.Reader) (n int64, err error) {
var bs [2]byte
if nn, err := io.ReadFull(r, bs[:]); err != nil {
return int64(nn), err
} else {
n += int64(nn)
}
*us = UnsignedShort(int16(bs[0])<<8 | int16(bs[1]))
return
}
// WriteTo writes UnsignedShort data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (us UnsignedShort) WriteTo(w io.Writer) (int64, error) {
n := uint16(us)
nn, err := w.Write([]byte{byte(n >> 8), byte(n)})
return int64(nn), err
}
// --- Int ---
// Int is a signed 32-bit integer, two's complement.
// Implements proto.Type interface (Minecraft protocol data type).
type Int int32
// ReadFrom reads Int data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (i *Int) ReadFrom(r io.Reader) (n int64, err error) {
var bs [4]byte
if nn, err := io.ReadFull(r, bs[:]); err != nil {
return int64(nn), err
} else {
n += int64(nn)
}
*i = Int(int32(bs[0])<<24 | int32(bs[1])<<16 | int32(bs[2])<<8 | int32(bs[3]))
return
}
// Write Int data to w
func (i Int) WriteTo(w io.Writer) (int64, error) {
n := uint32(i)
nn, err := w.Write([]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)})
return int64(nn), err
}
// --- Long ---
// Long is a signed 64-bit integer, two's complement.
// Implements proto.Type interface (Minecraft protocol data type).
type Long int64
// ReadFrom reads Long data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (l *Long) ReadFrom(r io.Reader) (n int64, err error) {
var bs [8]byte
if nn, err := io.ReadFull(r, bs[:]); err != nil {
return int64(nn), err
} else {
n += int64(nn)
}
*l = Long(int64(bs[0])<<56 | int64(bs[1])<<48 | int64(bs[2])<<40 | int64(bs[3])<<32 |
int64(bs[4])<<24 | int64(bs[5])<<16 | int64(bs[6])<<8 | int64(bs[7]))
return
}
// WriteTo writes Long data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (l Long) WriteTo(w io.Writer) (int64, error) {
n := uint64(l)
nn, err := w.Write([]byte{
byte(n >> 56), byte(n >> 48), byte(n >> 40), byte(n >> 32),
byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
})
return int64(nn), err
}
// --- Float ---
// Float is a single-precision 32-bit IEEE 754 floating point number.
// Implements proto.Type interface (Minecraft protocol data type).
type Float float32
// ReadFrom reads Float data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (f *Float) ReadFrom(r io.Reader) (n int64, err error) {
var v Int
n, err = v.ReadFrom(r)
if err != nil {
return
}
*f = Float(math.Float32frombits(uint32(v)))
return
}
// WriteTo writes Float data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (f Float) WriteTo(w io.Writer) (n int64, err error) {
return Int(math.Float32bits(float32(f))).WriteTo(w)
}
// --- Double ---
// Double is a double-precision 64-bit IEEE 754 floating point number.
// Implements proto.Type interface (Minecraft protocol data type).
type Double float64
// ReadFrom reads Double data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (d *Double) ReadFrom(r io.Reader) (n int64, err error) {
var v Long
n, err = v.ReadFrom(r)
if err != nil {
return
}
*d = Double(math.Float64frombits(uint64(v)))
return
}
// WriteTo writes Double data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (d Double) WriteTo(w io.Writer) (n int64, err error) {
return Long(math.Float64bits(float64(d))).WriteTo(w)
}
// --- String ---
// String is a sequence of Unicode scalar values.
// Implements proto.Type interface (Minecraft protocol data type).
type String string
// ReadFrom reads String data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (s *String) ReadFrom(r io.Reader) (n int64, err error) {
var l VarInt //String length
nn, err := l.ReadFrom(r)
if err != nil {
return nn, err
}
n += nn
bs := make([]byte, l)
if _, err := io.ReadFull(r, bs); err != nil {
return n, err
}
n += int64(l)
*s = String(bs)
return n, nil
}
// WriteTo writes String data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (s String) WriteTo(w io.Writer) (int64, error) {
byteStr := []byte(s)
n1, err := VarInt(len(byteStr)).WriteTo(w)
if err != nil {
return n1, err
}
n2, err := w.Write(byteStr)
return n1 + int64(n2), err
}
// --- Chat ---
// Chat supports two-way chat communication.
// Implements proto.Type interface (Minecraft protocol data type).
type Chat = String
// --- Identifier ---
// Identifier is a namespaced location.
// Implements proto.Type interface (Minecraft protocol data type).
type Identifier = String
// --- VarInt ---
// VarInt is variable-length data encoding a two's complement signed 32-bit integer.
// Implements proto.Type interface (Minecraft protocol data type).
type VarInt int32
// MaxVarIntLen is Maximum VarInt length.
const MaxVarIntLen = 5
// ReadFrom reads VarInt data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (v *VarInt) ReadFrom(r io.Reader) (n int64, err error) {
var vi uint32
for sec := byte(0x80); sec&0x80 != 0; n++ {
if n > MaxVarIntLen {
return n, errors.New("VarInt is too big")
}
sec, err = readByte(r)
if err != nil {
return n, err
}
vi |= uint32(sec&0x7F) << uint32(7*n)
}
*v = VarInt(vi)
return
}
// WriteTo writes VarInt data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (v VarInt) WriteTo(w io.Writer) (n int64, err error) {
var vi = make([]byte, 0, MaxVarIntLen)
num := uint32(v)
for {
b := num & 0x7F
num >>= 7
if num != 0 {
b |= 0x80
}
vi = append(vi, byte(b))
if num == 0 {
break
}
}
nn, err := w.Write(vi)
return int64(nn), err
}
// --- VarLong ---
// VarLong is variable-length data encoding a two's complement signed 64-bit integer.
// Implements proto.Type interface (Minecraft protocol data type).
type VarLong int64
// MaxVarLongLen is Maximum VarLong length.
const MaxVarLongLen = 10
// ReadFrom reads VarLong data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (v *VarLong) ReadFrom(r io.Reader) (n int64, err error) {
var V uint64
for sec := byte(0x80); sec&0x80 != 0; n++ {
if n >= MaxVarLongLen {
return n, errors.New("VarLong is too big")
}
sec, err = readByte(r)
if err != nil {
return
}
V |= uint64(sec&0x7F) << uint64(7*n)
}
*v = VarLong(V)
return
}
// WriteTo writes VarLong data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (v VarLong) WriteTo(w io.Writer) (n int64, err error) {
var vi = make([]byte, 0, MaxVarLongLen)
num := uint64(v)
for {
b := num & 0x7F
num >>= 7
if num != 0 {
b |= 0x80
}
vi = append(vi, byte(b))
if num == 0 {
break
}
}
nn, err := w.Write(vi)
return int64(nn), err
}
// --- EntityMetadata ---
// EntityMetadata represents miscellaneous information about an entity
// Implements proto.Type interface (Minecraft protocol data type).
// WARNING: EntityMetadata is not implemented in proto.
type EntityMetadata struct{}
// ReadFrom reads EntityMetadata data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
// WARNING: EntityMetadata is not implemented in proto.
func (e *EntityMetadata) ReadFrom(r io.Reader) (n int64, err error) {
return 0, errors.New("proto.EntityMetadata is not implemented")
}
// WriteTo writes EntityMetadata data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
// WARNING: EntityMetadata is not implemented in proto.
func (e *EntityMetadata) WriteTo(w io.Writer) (n int64, err error) {
return 0, errors.New("proto.EntityMetadata is not implemented")
}
// --- Slot ---
// Slot represents an item stack in an inventory or container.
// Implements proto.Type interface (Minecraft protocol data type).
// WARNING: Slot is not implemented in proto.
type Slot struct{}
// ReadFrom reads Slot data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
// WARNING: Slot is not implemented in proto.
func (s *Slot) ReadFrom(r io.Reader) (n int64, err error) {
return 0, errors.New("proto.Slot is not implemented")
}
// WriteTo writes Slot data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
// WARNING: Slot is not implemented in proto.
func (s *Slot) WriteTo(w io.Writer) (n int64, err error) {
return 0, errors.New("proto.Slot is not implemented")
}
// --- NBTTag ---
// NBTTag represents an item and its associated data.
// Implements proto.Type interface (Minecraft protocol data type).
// WARNING: NBTTag is not implemented in proto.
type NBTTag struct{}
// ReadFrom reads NBTTag data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
// WARNING: NBTTag is not implemented in proto.
func (t *NBTTag) ReadFrom(r io.Reader) (n int64, err error) {
return 0, errors.New("proto.NBTTag is not implemented")
}
// WriteTo writes NBTTag data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
// WARNING: NBTTag is not implemented in proto.
func (t *NBTTag) WriteTo(w io.Writer) (n int64, err error) {
return 0, errors.New("proto.NBTTag is not implemented")
}
// --- Position ---
// Position is an integer/block position: x,y,z.
// Implements proto.Type interface (Minecraft protocol data type).
type Position struct {
X, Y, Z int
}
// ReadFrom reads Position data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (p *Position) ReadFrom(r io.Reader) (n int64, err error) {
var v Long
nn, err := v.ReadFrom(r)
if err != nil {
return nn, err
}
n += nn
x := int(v >> 38)
y := int(v & 0xFFF)
z := int(v << 26 >> 38)
if x >= 1<<25 {
x -= 1 << 26
}
if y >= 1<<11 {
y -= 1 << 12
}
if z >= 1<<25 {
z -= 1 << 26
}
p.X, p.Y, p.Z = x, y, z
return
}
// WriteTo writes Position data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (p Position) WriteTo(w io.Writer) (n int64, err error) {
var b [8]byte
position := uint64(p.X&0x3FFFFFF)<<38 | uint64((p.Z&0x3FFFFFF)<<12) | uint64(p.Y&0xFFF)
for i := 7; i >= 0; i-- {
b[i] = byte(position)
position >>= 8
}
nn, err := w.Write(b[:])
return int64(nn), err
}
// --- Angle ---
// Angle is rotation angle in steps of 1/256 of a full turn.
// Implements proto.Type interface (Minecraft protocol data type).
type Angle Byte
// ReadFrom reads Angle data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (a *Angle) ReadFrom(r io.Reader) (int64, error) {
return (*Byte)(a).ReadFrom(r)
}
// WriteTo writes Angle data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (a Angle) WriteTo(w io.Writer) (int64, error) {
return Byte(a).WriteTo(w)
}
// ToDeg convert Angle to Degree
func (a Angle) ToDeg() float64 {
return 360 * float64(a) / 256
}
// ToRad convert Angle to Radian
func (a Angle) ToRad() float64 {
return 2 * math.Pi * float64(a) / 256
}
// --- UUID ---
// UUID is an uuid.
// Implements proto.Type interface (Minecraft protocol data type).
type UUID uuid.UUID
// ReadFrom reads UUID data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (u *UUID) ReadFrom(r io.Reader) (n int64, err error) {
nn, err := io.ReadFull(r, (*u)[:])
return int64(nn), err
}
// WriteTo writes UUID data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (u UUID) WriteTo(w io.Writer) (n int64, err error) {
nn, err := w.Write(u[:])
return int64(nn), err
}
// --- ByteArray ---
// ByteArray is just a sequence of zero or more bytes.
// Its meaning should be explained somewhere else (e.g. in the packet description).
// Implements proto.Type interface (Minecraft protocol data type).
type ByteArray []byte
// ReadFrom reads ByteArray data from r until an error occurs.
// The return value n is the number of bytes read.
// Any error encountered during the read is also returned.
func (b *ByteArray) ReadFrom(r io.Reader) (n int64, err error) {
var Len VarInt
n1, err := Len.ReadFrom(r)
if err != nil {
return n1, err
}
buf := bytes.NewBuffer(*b)
buf.Reset()
n2, err := io.CopyN(buf, r, int64(Len))
*b = buf.Bytes()
return n1 + n2, err
}
// WriteTo writes ByteArray data to w until an error occurs.
// The return value n is the number of bytes written.
// Any error encountered during the write is also returned.
func (b ByteArray) WriteTo(w io.Writer) (n int64, err error) {
n1, err := VarInt(len(b)).WriteTo(w)
if err != nil {
return n1, err
}
n2, err := w.Write(b)
return n1 + int64(n2), err
} | type.go | 0.770767 | 0.424054 | type.go | starcoder |
package ring
import (
"fmt"
"image/color"
"math"
)
// Layer represents a drawable layer of the LED ring.
type Layer struct {
pixels []color.Color
pixArc float64 // pixel arc in radians
rotFloat float64 // float part of rotation in radians
rotInt int // integer part of rotation in radians
opt *LayerOptions
buffer []color.Color
}
// LayerOptions is the list of options of a layer.
type LayerOptions struct {
// Resolution sets the number of pixels a layer has. Usually, this is set
// to the same number of LEDs the ring has.
Resolution int
// ContentMode sets how the layer will be rendered (default: Tile).
ContentMode ContentMode
}
// ContentMode defines how the layer will be rendered.
type ContentMode uint8
const (
// ContentTile sets the layer to crop its content if it is larger that the ring
// and to repeat the content.
ContentTile ContentMode = iota
// ContentCrop sets the layer to crop its content if it is larger than the ring
// and does not repeat the content.
ContentCrop
// ContentScale sets the layer to scale up or down its content to fit the ring.
ContentScale
)
// NewLayer creates a new drawable layer.
func NewLayer(options *LayerOptions) (*Layer, error) {
if options.Resolution == 0 {
return nil, fmt.Errorf("ring: resolution of new layer is 0")
}
l := &Layer{
pixels: make([]color.Color, options.Resolution),
buffer: make([]color.Color, options.Resolution),
pixArc: 2 * math.Pi / float64(options.Resolution),
opt: options,
}
l.SetAll(color.Transparent)
l.update()
return l, nil
}
// SetAll sets all the pixels of a layer to an uniform color.
func (l *Layer) SetAll(c color.Color) {
for i := range l.pixels {
l.pixels[i] = c
}
l.update()
}
// SetPixel sets the color of a single pixel in the layer.
func (l *Layer) SetPixel(i int, c color.Color) {
l.pixels[i] = c
l.update()
}
// Rotate sets the rotation of the layer. A positive angle makes a counter-clockwise rotation.
func (l *Layer) Rotate(angle float64) {
rotArc := angle / l.pixArc
rotInt := math.Floor(rotArc)
l.rotFloat = rotArc - rotInt
l.rotInt = int(rotInt)
l.update()
}
// pixelRotated returns the color of the pixel at position i adjusted for the
// rotation of the layer.
func (l *Layer) pixelRotated(i int) (c color.Color) {
i += l.rotInt
c = blendLerp(l.pixelRaw(i), l.pixelRaw(i+1), l.rotFloat)
return c
}
// Pixel returns the color of the pixel at position i, with layer
// transformations.
func (l *Layer) Pixel(i int) (c color.Color) {
return l.buffer[mod(i, l.opt.Resolution)]
}
// Options returns the options of the layer.
func (l *Layer) Options() *LayerOptions {
return l.opt
}
func (l *Layer) update() {
for i := range l.pixels {
l.buffer[i] = l.pixelRotated(i)
}
}
// pixelRaw returns the color of the pixelRaw at position i.
func (l *Layer) pixelRaw(i int) (c color.Color) {
return l.pixels[mod(i, l.opt.Resolution)]
}
func mod(p, n int) (r int) {
r = p % n
if r < 0 {
r += n
}
return r
} | layer.go | 0.865124 | 0.551936 | layer.go | starcoder |
package world
import (
"github.com/go-gl/glfw/v3.3/glfw"
"github.com/go-gl/mathgl/mgl32"
)
type Movement int
var PlayerID = int32(1)
const (
MoveForward Movement = iota
MoveBackward
MoveLeft
MoveRight
)
type AI interface {
Think(p *Player)
}
type Physics interface {
GetSpeed() mgl32.Vec3
Speed(a mgl32.Vec3)
Update(p *Player, dt float64)
}
type Position struct {
mgl32.Vec3
Rx, Ry float32
T float64
}
func (p *Position) Front() mgl32.Vec3 {
front := mgl32.Vec3{
cos(radian(p.Ry)) * cos(radian(p.Rx)),
sin(radian(p.Ry)),
cos(radian(p.Ry)) * sin(radian(p.Rx)),
}
return front.Normalize()
}
type Player struct {
Position
ID int
Sens float32
pre Position
flying bool
ai AI
Physics Physics
}
func (c *Player) Update(dt float64) {
if c.Physics != nil {
c.Physics.Update(c, dt)
}
if c.ai != nil {
c.ai.Think(c)
}
}
func (c *Player) Head() Vec3 {
return NearBlock(c.Pos())
}
func (c *Player) Foot() Vec3 {
return c.Head().Down()
}
func (c *Player) State() Position {
return c.Position
}
func (c *Player) Move(dir Movement, delta float32) {
if c.flying {
delta = 5 * delta
}
c.pre = c.Position
c.Position.T = glfw.GetTime()
switch dir {
case MoveForward:
if c.flying {
c.Position.Vec3 = c.Position.Add(c.Front().Mul(delta))
} else {
c.Position.Vec3 = c.Position.Add(c.WalkFront().Mul(delta))
}
case MoveBackward:
if c.flying {
c.Position.Vec3 = c.Position.Sub(c.Front().Mul(delta))
} else {
c.Position.Vec3 = c.Position.Sub(c.WalkFront().Mul(delta))
}
case MoveLeft:
c.Position.Vec3 = c.Position.Sub(c.Right().Mul(delta))
case MoveRight:
c.Position.Vec3 = c.Position.Add(c.Right().Mul(delta))
}
c.Position.T = glfw.GetTime()
c.UpdateState(c.Position)
}
func (c *Player) ChangeAngle(dx, dy float32) {
if mgl32.Abs(dx) > 200 || mgl32.Abs(dy) > 200 {
return
}
c.pre = c.Position
c.Position.T = glfw.GetTime()
c.Position.Rx += dx * c.Sens
c.Position.Ry += dy * c.Sens
if c.Position.Ry > 89 {
c.Position.Ry = 89
}
if c.Position.Ry < -89 {
c.Position.Ry = -89
}
}
func NewPlayer(pos mgl32.Vec3, ai AI, phy Physics) *Player {
p := &Player{
//front: mgl32.Vec3{0, 0, -1},
ai: ai,
Physics: phy,
Sens: 0.14,
flying: false,
}
//r.players[id] = p
p.Position = Position{Vec3: pos, T: glfw.GetTime(), Rx: -90, Ry: 0}
p.pre = p.Position
return p
}
func (c *Player) Matrix() mgl32.Mat4 {
return mgl32.LookAtV(c.Position.Vec3, c.Position.Add(c.Front()), c.Up())
}
// 线性插值计算玩家位置
func (p *Player) ComputeFootMat() mgl32.Mat4 {
body_pos := p.Position
front := p.WalkFront()
right := p.Right()
up := right.Cross(front).Normalize()
pos := mgl32.Vec3{body_pos.X(), body_pos.Y() - 1, body_pos.Z()}
return mgl32.LookAtV(pos, pos.Add(front), up).Inv()
}
// 线性插值计算玩家位置
func (p *Player) ComputeMat() mgl32.Mat4 {
t1 := p.Position.T - p.pre.T
t2 := glfw.GetTime() - p.Position.T
t := min(float32(t2/t1), 1)
x := mix(p.Position.X(), p.pre.X(), t)
y := mix(p.Position.Y(), p.pre.Y(), t)
z := mix(p.Position.Z(), p.pre.Z(), t)
rx := mix(p.Position.Rx, p.pre.Rx, t)
ry := mix(p.Position.Ry, p.pre.Ry, t)
front := mgl32.Vec3{
cos(radian(ry)) * cos(radian(rx)),
sin(radian(ry)),
cos(radian(ry)) * sin(radian(rx)),
}.Normalize()
right := front.Cross(mgl32.Vec3{0, 1, 0})
up := right.Cross(front).Normalize()
pos := mgl32.Vec3{x, y, z}
return mgl32.LookAtV(pos, pos.Add(front), up).Inv()
}
func (p *Player) UpdateState(s Position) {
p.pre, p.Position = p.Position, s
}
func (c *Player) Restore(state Position) {
c.Position = state //= mgl32.Vec3{state.X, state.Y, state.Z,RX:state.RX}
}
func (c *Player) SetPos(pos mgl32.Vec3) {
c.pre = c.Position
c.Position.Vec3 = pos
c.Position.T = glfw.GetTime()
}
func (c *Player) Pos() mgl32.Vec3 {
return c.Position.Vec3
}
func (c *Player) Up() mgl32.Vec3 {
return c.Right().Cross(c.Front()).Normalize()
}
func (c *Player) WalkFront() mgl32.Vec3 {
return mgl32.Vec3{0, 1, 0}.Cross(c.Right()).Normalize()
}
func (c *Player) Right() mgl32.Vec3 {
front := c.Front()
return front.Cross(mgl32.Vec3{0, 1, 0}).Normalize()
}
func (c *Player) Front() mgl32.Vec3 {
front := mgl32.Vec3{
cos(radian(c.Position.Ry)) * cos(radian(c.Position.Rx)),
sin(radian(c.Position.Ry)),
cos(radian(c.Position.Ry)) * sin(radian(c.Position.Rx)),
}
return front.Normalize()
}
func (c *Player) FlipFlying() {
c.flying = !c.flying
}
func (c *Player) Flying() bool {
return c.flying
} | world/player.go | 0.620966 | 0.478224 | player.go | starcoder |
package calculator
import (
"errors"
"fmt"
"math"
"strings"
)
// Add takes two or more float64 values and returns their sum.
func Add(a float64, b float64, nums ...float64) float64 {
sum := a + b
for _, n := range nums {
sum += n
}
return sum
}
// Subtract takes two or more float64 values and returns the result of subtracting all the other values from the first.
func Subtract(a float64, b float64, nums ...float64) float64 {
result := a - b
for _, n := range nums {
result -= n
}
return result
}
// Multiply takes a variable number of float64 and returns their product.
func Multiply(a float64, b float64, nums ...float64) float64 {
product := a * b
for _, n := range nums {
product *= n
}
return product
}
// Divide takes a variable number of float64 and returns their quotient, or
// an error if the divisor is zero.
func Divide(a float64, b float64, nums ...float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
quotient := a / b
for _, n := range nums {
if n == 0 {
return 0, errors.New("cannot divide by zero")
}
quotient /= n
}
return quotient, nil
}
// Sqrt takes a number and returns its square root provided it has one, otherwise it returns an error.
func Sqrt(a float64) (float64, error) {
if a < 0 {
return 0, errors.New("cannot get square root of negative number")
}
return math.Sqrt(a), nil
}
// EvaluateExpr takes in an expression as a string and parses it to evaluate it. Ex: "10 + 5" returns 15
func EvaluateExpr(expr string) (float64, error) {
var a, b float64
var op rune
_, err := fmt.Sscanf(expr, "%f%c%f", &a, &op, &b)
if err != nil {
return 0, err
}
switch op {
case '+':
return Add(a, b), nil
case '-':
return Subtract(a, b), nil
case '*':
return Multiply(a, b), nil
case '/':
return Divide(a, b)
}
return 0, errors.New(
"no valid operators found (should be one of +, -, *, or /",
)
}
func getOperator(ops []string, s string) (string, error) {
for _, v := range ops {
if strings.Contains(s, v) {
return v, nil
}
}
return "", errors.New("invalid operator")
} | calculator.go | 0.796094 | 0.624723 | calculator.go | starcoder |
package types
import (
"errors"
"io"
"sync"
"runtime"
"github.com/attic-labs/noms/go/d"
)
// Blob represents a list of Blobs.
type Blob struct {
sequence
}
func newBlob(seq sequence) Blob {
return Blob{seq}
}
func NewEmptyBlob(vrw ValueReadWriter) Blob {
return Blob{newBlobLeafSequence(vrw, []byte{})}
}
func (b Blob) Edit() *BlobEditor {
return NewBlobEditor(b)
}
// ReadAt implements the ReaderAt interface. Eagerly loads requested byte-range from the blob p-tree.
func (b Blob) ReadAt(p []byte, off int64) (n int, err error) {
// TODO: Support negative off?
d.PanicIfTrue(off < 0)
startIdx := uint64(off)
if startIdx >= b.Len() {
return 0, io.EOF
}
endIdx := startIdx + uint64(len(p))
if endIdx > b.Len() {
endIdx = b.Len()
}
if endIdx == b.Len() {
err = io.EOF
}
if startIdx == endIdx {
return
}
leaves, localStart := LoadLeafNodes([]Collection{b}, startIdx, endIdx)
endIdx = localStart + endIdx - startIdx
startIdx = localStart
for _, leaf := range leaves {
bl := leaf.asSequence().(blobLeafSequence)
localEnd := endIdx
data := bl.data()
leafLength := uint64(len(data))
if localEnd > leafLength {
localEnd = leafLength
}
src := data[startIdx:localEnd]
copy(p[n:], src)
n += len(src)
endIdx -= localEnd
startIdx = 0
}
return
}
func (b Blob) Reader() *BlobReader {
return &BlobReader{b, 0}
}
func (b Blob) Copy(w io.Writer) (n int64) {
return b.CopyReadAhead(w, 1<<23 /* 8MB */, 6)
}
// CopyReadAhead copies the entire contents of |b| to |w|, and attempts to stay
// |concurrency| |chunkSize| blocks of bytes ahead of the last byte written to
// |w|.
func (b Blob) CopyReadAhead(w io.Writer, chunkSize uint64, concurrency int) (n int64) {
bChan := make(chan chan []byte, concurrency)
go func() {
for idx, len := uint64(0), b.Len(); idx < len; {
bc := make(chan []byte)
bChan <- bc
start := idx
blockLength := b.Len() - start
if blockLength > chunkSize {
blockLength = chunkSize
}
idx += blockLength
go func() {
buff := make([]byte, blockLength)
b.ReadAt(buff, int64(start))
bc <- buff
}()
}
close(bChan)
}()
// Ensure read-ahead goroutines can exit
defer func() {
for range bChan {
}
}()
for b := range bChan {
ln, err := w.Write(<-b)
n += int64(ln)
if err != nil {
return
}
}
return
}
// Concat returns a new Blob comprised of this joined with other. It only needs
// to visit the rightmost prolly tree chunks of this Blob, and the leftmost
// prolly tree chunks of other, so it's efficient.
func (b Blob) Concat(other Blob) Blob {
seq := concat(b.sequence, other.sequence, func(cur *sequenceCursor, vrw ValueReadWriter) *sequenceChunker {
return b.newChunker(cur, vrw)
})
return newBlob(seq)
}
func (b Blob) newChunker(cur *sequenceCursor, vrw ValueReadWriter) *sequenceChunker {
return newSequenceChunker(cur, 0, vrw, makeBlobLeafChunkFn(vrw), newIndexedMetaSequenceChunkFn(BlobKind, vrw), hashValueByte)
}
func (b Blob) asSequence() sequence {
return b.sequence
}
// Value interface
func (b Blob) Value() Value {
return b
}
func (b Blob) WalkValues(cb ValueCallback) {
}
type BlobReader struct {
b Blob
pos int64
}
func (cbr *BlobReader) Read(p []byte) (n int, err error) {
n, err = cbr.b.ReadAt(p, cbr.pos)
cbr.pos += int64(n)
return
}
func (cbr *BlobReader) Seek(offset int64, whence int) (int64, error) {
abs := int64(cbr.pos)
switch whence {
case 0:
abs = offset
case 1:
abs += offset
case 2:
abs = int64(cbr.b.Len()) + offset
default:
return 0, errors.New("Blob.Reader.Seek: invalid whence")
}
if abs < 0 {
return 0, errors.New("Blob.Reader.Seek: negative position")
}
cbr.pos = int64(abs)
return abs, nil
}
func makeBlobLeafChunkFn(vrw ValueReadWriter) makeChunkFn {
return func(level uint64, items []sequenceItem) (Collection, orderedKey, uint64) {
d.PanicIfFalse(level == 0)
buff := make([]byte, len(items))
for i, v := range items {
buff[i] = v.(byte)
}
return chunkBlobLeaf(vrw, buff)
}
}
func chunkBlobLeaf(vrw ValueReadWriter, buff []byte) (Collection, orderedKey, uint64) {
blob := newBlob(newBlobLeafSequence(vrw, buff))
return blob, orderedKeyFromInt(len(buff)), uint64(len(buff))
}
// NewBlob creates a Blob by reading from every Reader in rs and
// concatenating the result. NewBlob uses one goroutine per Reader.
func NewBlob(vrw ValueReadWriter, rs ...io.Reader) Blob {
return readBlobsP(vrw, rs...)
}
func readBlobsP(vrw ValueReadWriter, rs ...io.Reader) Blob {
switch len(rs) {
case 0:
return NewEmptyBlob(vrw)
case 1:
return readBlob(rs[0], vrw)
}
blobs := make([]Blob, len(rs))
wg := &sync.WaitGroup{}
wg.Add(len(rs))
for i, r := range rs {
i2, r2 := i, r
go func() {
blobs[i2] = readBlob(r2, vrw)
wg.Done()
}()
}
wg.Wait()
b := blobs[0]
for i := 1; i < len(blobs); i++ {
b = b.Concat(blobs[i])
}
return b
}
func readBlob(r io.Reader, vrw ValueReadWriter) Blob {
sc := newEmptySequenceChunker(vrw, makeBlobLeafChunkFn(vrw), newIndexedMetaSequenceChunkFn(BlobKind, vrw), func(item sequenceItem, rv *rollingValueHasher) {
rv.HashByte(item.(byte))
})
// TODO: The code below is temporary. It's basically a custom leaf-level chunker for blobs. There are substational perf gains by doing it this way as it avoids the cost of boxing every single byte which is chunked.
chunkBuff := [8192]byte{}
chunkBytes := chunkBuff[:]
rv := newRollingValueHasher(0)
offset := 0
addByte := func(b byte) bool {
if offset >= len(chunkBytes) {
tmp := make([]byte, len(chunkBytes)*2)
copy(tmp, chunkBytes)
chunkBytes = tmp
}
chunkBytes[offset] = b
offset++
rv.HashByte(b)
return rv.crossedBoundary
}
mtChan := make(chan chan metaTuple, runtime.NumCPU())
makeChunk := func() {
rv.Reset()
cp := make([]byte, offset)
copy(cp, chunkBytes[0:offset])
ch := make(chan metaTuple)
mtChan <- ch
go func(ch chan metaTuple, cp []byte) {
col, key, numLeaves := chunkBlobLeaf(vrw, cp)
ch <- newMetaTuple(vrw.WriteValue(col), key, numLeaves)
}(ch, cp)
offset = 0
}
go func() {
readBuff := [8192]byte{}
for {
n, err := r.Read(readBuff[:])
for i := 0; i < n; i++ {
if addByte(readBuff[i]) {
makeChunk()
}
}
if err != nil {
if err != io.EOF {
panic(err)
}
if offset > 0 {
makeChunk()
}
close(mtChan)
break
}
}
}()
for ch := range mtChan {
mt := <-ch
if sc.parent == nil {
sc.createParent()
}
sc.parent.Append(mt)
}
return newBlob(sc.Done())
} | go/types/blob.go | 0.542136 | 0.431944 | blob.go | starcoder |
package ast
import (
"fmt"
"strconv"
)
type Program struct {
Assignments []Assignment
}
func (p Program) String() string {
var s string
for _, a := range p.Assignments {
s += a.String() + "\n"
}
return s
}
type Assignment struct {
LHS Variable
RHS Expression
}
func (a Assignment) String() string {
return fmt.Sprintf("%s = %s", a.LHS, a.RHS)
}
func (a Assignment) Operands() []Operand {
return append([]Operand{a.LHS}, a.RHS.Inputs()...)
}
type Expression interface {
Inputs() []Operand
fmt.Stringer
}
type Pow struct {
X Variable
N Constant
}
func (p Pow) Inputs() []Operand { return []Operand{p.X} }
func (p Pow) String() string { return fmt.Sprintf("%s^%s", p.X, p.N) }
type Inv struct{ X Operand }
func (i Inv) Inputs() []Operand { return []Operand{i.X} }
func (i Inv) String() string { return fmt.Sprintf("1/%s", i.X) }
type Mul struct{ X, Y Operand }
func (m Mul) Inputs() []Operand { return []Operand{m.X, m.Y} }
func (m Mul) String() string { return fmt.Sprintf("%s*%s", m.X, m.Y) }
type Neg struct{ X Operand }
func (n Neg) Inputs() []Operand { return []Operand{n.X} }
func (n Neg) String() string { return fmt.Sprintf("-%s", n.X) }
type Add struct{ X, Y Operand }
func (a Add) Inputs() []Operand { return []Operand{a.X, a.Y} }
func (a Add) String() string { return fmt.Sprintf("%s+%s", a.X, a.Y) }
type Sub struct{ X, Y Operand }
func (s Sub) Inputs() []Operand { return []Operand{s.X, s.Y} }
func (s Sub) String() string { return fmt.Sprintf("%s-%s", s.X, s.Y) }
type Cond struct{ X, C Variable }
func (c Cond) Inputs() []Operand { return []Operand{c.X, c.C} }
func (c Cond) String() string { return fmt.Sprintf("%s?%s", c.X, c.C) }
type Operand interface {
fmt.Stringer
}
type Variable string
func Variables(operands []Operand) []Variable {
vs := make([]Variable, 0, len(operands))
for _, operand := range operands {
if v, ok := operand.(Variable); ok {
vs = append(vs, v)
}
}
return vs
}
func (v Variable) Inputs() []Operand { return []Operand{v} }
func (v Variable) String() string { return string(v) }
func (v Variable) GoString() string { return fmt.Sprintf("ast.Variable(%q)", v) }
type Constant uint
func (c Constant) Inputs() []Operand { return []Operand{c} }
func (c Constant) String() string { return strconv.FormatUint(uint64(c), 10) }
func (c Constant) GoString() string { return fmt.Sprintf("ast.Constant(%d)", c) } | efd/op3/ast/ast.go | 0.669745 | 0.437884 | ast.go | starcoder |
package v1
import (
"encoding/json"
)
// BgpSessionNeighbors struct for BgpSessionNeighbors
type BgpSessionNeighbors struct {
// A list of BGP session neighbor data
BgpNeighbors *[]BgpNeighborData `json:"bgp_neighbors,omitempty"`
}
// NewBgpSessionNeighbors instantiates a new BgpSessionNeighbors 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 NewBgpSessionNeighbors() *BgpSessionNeighbors {
this := BgpSessionNeighbors{}
return &this
}
// NewBgpSessionNeighborsWithDefaults instantiates a new BgpSessionNeighbors 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 NewBgpSessionNeighborsWithDefaults() *BgpSessionNeighbors {
this := BgpSessionNeighbors{}
return &this
}
// GetBgpNeighbors returns the BgpNeighbors field value if set, zero value otherwise.
func (o *BgpSessionNeighbors) GetBgpNeighbors() []BgpNeighborData {
if o == nil || o.BgpNeighbors == nil {
var ret []BgpNeighborData
return ret
}
return *o.BgpNeighbors
}
// GetBgpNeighborsOk returns a tuple with the BgpNeighbors field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BgpSessionNeighbors) GetBgpNeighborsOk() (*[]BgpNeighborData, bool) {
if o == nil || o.BgpNeighbors == nil {
return nil, false
}
return o.BgpNeighbors, true
}
// HasBgpNeighbors returns a boolean if a field has been set.
func (o *BgpSessionNeighbors) HasBgpNeighbors() bool {
if o != nil && o.BgpNeighbors != nil {
return true
}
return false
}
// SetBgpNeighbors gets a reference to the given []BgpNeighborData and assigns it to the BgpNeighbors field.
func (o *BgpSessionNeighbors) SetBgpNeighbors(v []BgpNeighborData) {
o.BgpNeighbors = &v
}
func (o BgpSessionNeighbors) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.BgpNeighbors != nil {
toSerialize["bgp_neighbors"] = o.BgpNeighbors
}
return json.Marshal(toSerialize)
}
type NullableBgpSessionNeighbors struct {
value *BgpSessionNeighbors
isSet bool
}
func (v NullableBgpSessionNeighbors) Get() *BgpSessionNeighbors {
return v.value
}
func (v *NullableBgpSessionNeighbors) Set(val *BgpSessionNeighbors) {
v.value = val
v.isSet = true
}
func (v NullableBgpSessionNeighbors) IsSet() bool {
return v.isSet
}
func (v *NullableBgpSessionNeighbors) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBgpSessionNeighbors(val *BgpSessionNeighbors) *NullableBgpSessionNeighbors {
return &NullableBgpSessionNeighbors{value: val, isSet: true}
}
func (v NullableBgpSessionNeighbors) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBgpSessionNeighbors) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | v1/model_bgp_session_neighbors.go | 0.789193 | 0.511778 | model_bgp_session_neighbors.go | starcoder |
package geometry
import (
"math"
)
// 2d vector
type Vector struct {
X, Y float64
}
var (
// Zero Vector
ZeroVector = Vector{0, 0}
)
// Check if v1 is Equals to v2
func (v1 Vector) Equals(v2 Vector) bool {
return v1.X == v2.X && v1.Y == v2.Y
}
// Check if v1 is Nearly Equals to v2 (against an epsilon defined in NearlyZero constant)
func (v1 Vector) NearlyEquals(v2 Vector) bool {
return math.Abs(v1.X-v2.X) < NearlyZero && math.Abs(v1.Y-v2.Y) < NearlyZero
}
// Add two vectors
func (v1 Vector) Add(v2 Vector) Vector {
return Vector{v1.X + v2.Y, v1.Y + v2.Y}
}
// Substract two vector (v1 - v2)
func (v1 Vector) Sub(v2 Vector) Vector {
return Vector{v1.X - v2.X, v1.Y - v2.Y}
}
// Opposite vector
func (v Vector) Opposite() Vector {
return Vector{-v.X, -v.Y}
}
// float64 multiplication
func (v Vector) Mult(s float64) Vector {
return Vector{v.X * s, v.Y * s}
}
// Vector dot product
func (v1 Vector) Dot(v2 Vector) float64 {
return v1.X*v2.X + v1.Y*v2.Y
}
// Length Square of v
func (v Vector) Length() float64 {
return math.Hypot(v.X, v.Y)
}
// Length Square of v
func (v Vector) LengthSquare() float64 {
return v.Dot(v)
}
// Perpendicular vector. (90 degree rotation)
func (v Vector) Normal() Vector {
return Vector{-v.Y, v.X}
}
// Returns the vector projection of v1 onto v2.
func (v1 Vector) Projection(v2 Vector) Vector {
return v2.Mult(v1.Dot(v2) / v2.Dot(v2))
}
// Rotate v1 by v2. Scaling will occur if v1 is not a unit vector.
func (v1 Vector) Rotate(v2 Vector) Vector {
return Vector{v1.X*v2.X - v1.Y*v2.Y, v1.Y*v2.X + v1.X*v2.Y}
}
// Inverse of Rotate().
func (v1 Vector) UnRotate(v2 Vector) Vector {
return Vector{v1.X*v2.X + v1.Y*v2.Y, v1.Y*v2.X - v1.X*v2.Y}
}
// Return the vector between v1 and v2
func (v1 Vector) Center(v2 Vector) Vector {
return Vector{(v1.X + v2.X) / 2, (v1.Y + v2.Y) / 2}
}
// Return the vector between v1 and v2 and interpolated by t (0, 1)
// v*(1-t)+v2*t
func (v1 Vector) Lerp(v2 Vector, t float64) Vector {
return v1.Mult(1 - t).Add(v2.Mult(t))
}
// Return the unit Vector of v
func (v Vector) Normalize() Vector {
if v.X == 0 && v.Y == 0 {
return ZeroVector
}
return v.Mult(1 / v.Length())
}
// Create a vector parallel to v that have d length
func (v Vector) SetLength(d float64) Vector {
if v.X == 0 && v.Y == 0 {
return ZeroVector
}
return v.Mult(d / v.Length())
}
// Create a vector parallel to v that have d length vector length is greater than d
func (v Vector) Clamp(d float64) Vector {
lensq := v.LengthSquare()
if lensq <= d*d {
return v
}
return v.Mult(d / math.Sqrt(lensq))
}
// Returns the distance between v1 and v2.
func (v1 Vector) Distance(v2 Vector) float64 {
return v1.Sub(v2).Length()
}
func (v1 Vector) DistanceSquare(v2 Vector) float64 {
return v1.Sub(v2).LengthSquare()
}
// Returns the unit length vector for the given angle (in radians).
func AngleToVector(a float64) Vector {
return Vector{math.Cos(a), math.Sin(a)}
}
// Returns the angular direction v is pointing in (in radians).
func (v Vector) Angle() float64 {
return math.Atan2(v.Y, v.X)
} | geometry/vector.go | 0.90377 | 0.714117 | vector.go | starcoder |
package chacha20
import (
"encoding/binary"
"errors"
"unsafe"
)
func Encrypt(plain []byte, key []byte, nonce []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.New("unexpected key length")
}
if len(nonce) != 12 {
return nil, errors.New("unexpected nonce length")
}
var counter uint32
encrypted := []byte{}
for i := 0; i < len(plain)/64; i++ {
bytes := make([]byte, 4)
binary.BigEndian.PutUint32(bytes, counter)
stream := keyStream(key, nonce, bytes)
if len(plain) <= i*64 {
break
}
for j := 0; j < 64; j++ {
if len(plain) > i*64+j {
s := stream[j]
p := plain[i*64+j]
encrypted = append(encrypted, p^s)
}
}
}
return encrypted, nil
}
func keyStream(key []byte, nonce []byte, counter []byte) []byte {
state := []uint32{0x61707865, 0x3320646e, 0x79622d32, 0x6b206574}
state = append(state, binary.BigEndian.Uint32(key[0:4]))
state = append(state, binary.BigEndian.Uint32(key[4:8]))
state = append(state, binary.BigEndian.Uint32(key[8:12]))
state = append(state, binary.BigEndian.Uint32(key[12:16]))
state = append(state, binary.BigEndian.Uint32(key[16:20]))
state = append(state, binary.BigEndian.Uint32(key[20:24]))
state = append(state, binary.BigEndian.Uint32(key[24:28]))
state = append(state, binary.BigEndian.Uint32(key[28:32]))
state = append(state, binary.BigEndian.Uint32(counter))
state = append(state, binary.BigEndian.Uint32(nonce[0:4]))
state = append(state, binary.BigEndian.Uint32(nonce[4:8]))
state = append(state, binary.BigEndian.Uint32(nonce[8:12]))
for i := 0; i < 10; i++ {
round(state)
}
stream := []byte{}
for _, s := range state {
stream = append(stream, (*[4]byte)(unsafe.Pointer(&s))[:]...)
}
return stream
}
func round(state []uint32) []uint32 {
state[0], state[4], state[8], state[12] = qr(state[0], state[4], state[8], state[12])
state[1], state[5], state[9], state[13] = qr(state[1], state[5], state[9], state[13])
state[2], state[6], state[10], state[14] = qr(state[2], state[6], state[10], state[14])
state[3], state[7], state[11], state[15] = qr(state[3], state[7], state[11], state[15])
state[0], state[5], state[10], state[15] = qr(state[0], state[5], state[10], state[15])
state[1], state[6], state[11], state[12] = qr(state[1], state[6], state[11], state[12])
state[2], state[7], state[8], state[13] = qr(state[2], state[7], state[8], state[13])
state[3], state[4], state[9], state[14] = qr(state[3], state[4], state[9], state[14])
return state
}
func qr(a uint32, b uint32, c uint32, d uint32) (uint32, uint32, uint32, uint32) {
a = a + b
d = d ^ a
d = rotLeft(d, 16)
c = c + d
b = b ^ c
b = rotLeft(b, 12)
a = a + b
d = d ^ a
d = rotLeft(d, 8)
c = c + d
b = b ^ c
b = rotLeft(b, 7)
return a, b, c, d
}
func rotLeft(v uint32, o int) uint32 {
return v>>o | v<<(32-o)
} | chacha20/chacha20.go | 0.512693 | 0.423935 | chacha20.go | starcoder |
package main
import (
"errors"
"fmt"
"log"
"sort"
"strconv"
"github.com/theatlasroom/advent-of-code/go/2019/utils"
)
/**
--- Day 5: Binary Boarding ---
You board your plane only to discover a new problem: you dropped your boarding pass!
You aren't sure which seat is yours, and all of the flight attendants are busy with the
flood of people that suddenly made it through passport control.
You write a quick program to use your phone's camera to scan all of the nearby
boarding passes (your puzzle input); perhaps you can find your seat through process of elimination.
Instead of zones or groups, this airline uses binary space partitioning to seat people.
A seat might be specified like FBFBBFFRLR, where F means "front", B means "back", L means "left", and R means "right".
The first 7 characters will either be F or B; these specify exactly one of the 128 rows on
the plane (numbered 0 through 127). Each letter tells you which half of a region the given seat is in.
Start with the whole list of rows; the first letter indicates whether the seat is in the front (0 through 63)
or the back (64 through 127).
The next letter indicates which half of that region the seat is in, and so on until you're left with exactly one row.
For example, consider just the first seven characters of FBFBBFFRLR:
Start by considering the whole range, rows 0 through 127.
F means to take the lower half, keeping rows 0 through 63.
B means to take the upper half, keeping rows 32 through 63.
F means to take the lower half, keeping rows 32 through 47.
B means to take the upper half, keeping rows 40 through 47.
B keeps rows 44 through 47.
F keeps rows 44 through 45.
The final F keeps the lower of the two, row 44.
The last three characters will be either L or R; these specify exactly one of the 8 columns of seats on the plane (numbered 0 through 7).
The same process as above proceeds again, this time with only three steps. L means to keep the lower half, while R means to keep the upper half.
For example, consider just the last 3 characters of FBFBBFFRLR:
Start by considering the whole range, columns 0 through 7.
R means to take the upper half, keeping columns 4 through 7.
L means to take the lower half, keeping columns 4 through 5.
The final R keeps the upper of the two, column 5.
So, decoding FBFBBFFRLR reveals that it is the seat at row 44, column 5.
Every seat also has a unique seat ID: multiply the row by 8, then add the column. In this example, the seat has ID 44 * 8 + 5 = 357.
Here are some other boarding passes:
BFFFBBFRRR: row 70, column 7, seat ID 567.
FFFBBBFRRR: row 14, column 7, seat ID 119.
BBFFBBFRLL: row 102, column 4, seat ID 820.
As a sanity check, look through your list of boarding passes. What is the highest seat ID on a boarding pass?
*/
type seat struct {
seatID, row, column int
}
type seats []seat
// implement the sort.Interface
func (s seats) Len() int { return len(s) }
func (s seats) Less(i, j int) bool { return s[i].seatID < s[j].seatID }
func (s seats) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s seat) toString() string {
return fmt.Sprintf("Row: %v Column: %v SeatID: %v", s.row, s.column, s.seatID)
}
func generateSeatID(row, column int) int {
return (row * 8) + column
}
func parse(str, leftSymbol, rightSymbol string) int {
var char string
bits := ""
for _, c := range str {
char = string(c)
switch char {
case leftSymbol:
bits += "0"
break
case rightSymbol:
bits += "1"
break
default:
break
}
}
i, err := strconv.ParseInt(bits, 2, 64)
if err != nil {
log.Fatal(err)
}
return int(i)
}
func findSeat(str string) seat {
row := parse(str[:7], "F", "B")
column := parse(str[7:], "L", "R")
seatID := generateSeatID(row, column)
return seat{seatID, row, column}
}
func calculateAllSeats(data []string) seats {
var s seats
for _, str := range data {
s = append(s, findSeat(str))
}
return s
}
func part01(data []string) seat {
s := calculateAllSeats(data)
sort.Sort(sort.Reverse(s))
return s[0]
}
func part02(data []string) (int, error) {
s := calculateAllSeats(data)
sort.Sort(s)
prevSeatID := s[0].seatID
for i := 1; i < s.Len(); i++ {
if s[i].seatID-prevSeatID > 1 {
return ((s[i].seatID + prevSeatID) / 2), nil
}
prevSeatID = s[i].seatID
}
return -1, errors.New("Couldnt find the seat")
}
func main() {
utils.Banner(utils.BannerConfig{Year: 2020, Day: 5})
data := utils.LoadData("5.txt")
fmt.Println(part01(data).toString())
seatID, err := part02(data)
if err != nil {
log.Fatal(err)
}
fmt.Println("Missing seat", seatID)
} | go/2020/5.go | 0.615203 | 0.605158 | 5.go | starcoder |
package pars
import (
"bytes"
"errors"
"io"
)
const (
bufferReadSize = 4096
)
// State represents a parser state, which is a convenience wrapper for an
// io.Reader object with buffering and backtracking.
type State struct {
rd io.Reader
buf []byte
off int
end int
err error
pos Position
stk *stack
}
// NewState creates a new state from the given io.Reader.
func NewState(r io.Reader) *State {
switch rd := r.(type) {
case *State:
return rd
default:
return &State{
rd: r,
buf: make([]byte, 0),
off: 0,
end: -1,
err: nil,
pos: Position{0, 0},
stk: newStack(),
}
}
}
// FromBytes creates a new state from the given bytes.
func FromBytes(p []byte) *State {
return &State{
rd: &bytes.Buffer{},
buf: p,
off: 0,
end: -1,
err: nil,
pos: Position{0, 0},
stk: newStack(),
}
}
// FromString creates a new state from the given string.
func FromString(s string) *State {
return FromBytes([]byte(s))
}
// Read satisfies the io.Reader interface.
func (s *State) Read(p []byte) (int, error) {
err := s.Request(len(p))
n := copy(p, s.Buffer())
s.Advance()
return n, err
}
// ReadByte satisfies the io.ByteReader interace.
func (s *State) ReadByte() (byte, error) {
if err := s.Request(1); err != nil {
return 0, err
}
c := s.buf[s.off]
s.Advance()
return c, nil
}
// Request checks if the state contains at least the given number of bytes,
// additionally reading from the io.Reader object as necessary when the
// internal buffer is exhausted. If the call to Read for the io.Reader object
// returns an error, Request will return the corresponding error. A subsequent
// call to Advance will advance the state offset as far as possible.
func (s *State) Request(n int) error {
for len(s.buf) < s.off+n && s.err == nil {
p := make([]byte, bufferReadSize)
var m int
m, s.err = s.rd.Read(p)
s.buf = append(s.buf, p[:m]...)
}
switch {
case len(s.buf) < s.off+n:
s.end = len(s.buf)
return s.err
default:
s.end = s.off + n
return nil
}
}
// Advance the state by the amount given in a previous Request call.
func (s *State) Advance() {
if s.end < 0 {
panic("no previous call to Request")
}
for _, b := range s.buf[s.off:s.end] {
if b == '\n' {
s.pos.Line++
s.pos.Byte = 0
} else {
s.pos.Byte++
}
}
s.off, s.end = s.end, -1
s.autoclear()
}
// Buffer returns the range of bytes guaranteed by a Request call.
func (s State) Buffer() []byte { return s.buf[s.off:s.end] }
// Dump returns the entire remaining buffer content. Note that the returned
// byte slice will not always contain the entirety of the bytes that can be
// read by the io.Reader object.
func (s State) Dump() []byte { return s.buf[s.off:] }
// Offset returns the current state offset.
func (s State) Offset() int { return s.off }
// Position returns the current line and byte position of the state.
func (s State) Position() Position { return s.pos }
// Push the current state position for backtracking.
func (s *State) Push() { s.stk.Push(s.off, s.pos) }
// Pushed tests if the state has been pushed at least once.
func (s State) Pushed() bool { return !s.stk.Empty() }
// Pop will backtrack to the most recently pushed state.
func (s *State) Pop() {
if !s.stk.Empty() {
s.off, s.pos = s.stk.Pop()
s.autoclear()
}
}
// Drop will discard the most recently pushed state.
func (s *State) Drop() {
if !s.stk.Empty() {
s.stk.Pop()
s.autoclear()
}
}
func (s *State) autoclear() {
if s.stk.Empty() {
s.Clear()
}
}
// Clear will discard the buffer contents prior to the current state offset
// and drop all pushed states.
func (s *State) Clear() {
s.buf = s.buf[s.off:]
s.off = 0
s.stk.Reset()
}
// Skip the given state for the given number of bytes.
func Skip(state *State, n int) error {
if err := state.Request(n); err != nil {
return err
}
state.Advance()
return nil
}
// Next attempts to retrieve the next byte in the given state.
func Next(state *State) (byte, error) {
if err := state.Request(1); err != nil {
return 0, err
}
return state.Buffer()[0], nil
}
// Trail will return the extent of the state buffer spanning from the most
// recently pushed state position to the current state position.
func Trail(state *State) ([]byte, error) {
if !state.Pushed() {
return nil, errors.New("failed to backtrack")
}
off := state.Offset()
state.Pop()
n := off - state.Offset()
state.Request(n)
p := state.Buffer()
state.Advance()
return p, nil
} | state.go | 0.688364 | 0.452415 | state.go | starcoder |
package ipv6
import (
"encoding/csv"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/tidwall/buntdb"
)
const collection = "address"
const expectedCSVColumns = 10
const coordinatePrecision = "%f"
var data map[string]int32 // lat,long:count
var buntdbValueRegex = regexp.MustCompile(`\[([\d-\.]+) ([\d-\.]+)\]`) // parses `lat` `long` info from `[lat long]`
// List fetches a list of IPv6 models according to the specified (optional) `Filters`.
func List(db *buntdb.DB, f Filters) (ListResult, error) {
result := ListResult{}
var maxCount int32
err := db.View(func(tx *buntdb.Tx) error {
// Fetch results from our buntdb index using the supplied filters.
query := fmt.Sprintf("[%f %f],[%f %f]", f.MinLongitude, f.MinLatitude, f.MaxLongitude, f.MaxLatitude)
err := tx.Intersects(collection, query, func(key, value string) bool {
matches := buntdbValueRegex.FindStringSubmatch(value)
longitude, _ := strconv.ParseFloat(matches[1], 64)
latitude, _ := strconv.ParseFloat(matches[2], 64)
count := data[fmt.Sprintf("%f,%f", latitude, longitude)]
// Keep track of the max count for this result set.
if count > maxCount {
maxCount = count
}
result.Results = append(result.Results, &Address{
Latitude: latitude,
Longitude: longitude,
Count: count,
})
return true
})
return err
})
if err != nil {
return result, errors.Wrap(err, "failed running intersection query")
}
result.MaxCount = maxCount
return result, err
}
// LoadData parses the data from the supplied source and populates our "persistence" layer.
func LoadData(db *buntdb.DB, source io.Reader) error {
// Reset our "database".
data = map[string]int32{}
// Ensure we have a spatial index on our geo coords.
db.CreateSpatialIndex(collection, fmt.Sprintf("%s:*:coords", collection), buntdb.IndexRect)
// Setup a CSV reader on our data source.
reader := csv.NewReader(source)
if reader == nil {
return errors.New("nil reader returned")
}
// Throwaway the first header line.
_, err := reader.Read()
if err != nil {
return errors.Wrap(err, "failed reading from CSV reader")
}
// Populate our `data` with a map of `latitude,longitude : count`
for {
// Read the record.
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return errors.Wrap(err, "failed reading from CSV reader")
}
if len(record) != expectedCSVColumns {
return errors.Wrapf(fmt.Errorf("failed while reading record"), "expected %d columns in record, found %d", expectedCSVColumns, len(record))
}
// Grab the lat/long from the record.
latitude, err := strconv.ParseFloat(record[7], 64)
if err != nil {
return errors.Wrap(err, "failed while parsing latitude float")
}
longitude, err := strconv.ParseFloat(record[8], 64)
if err != nil {
return errors.Wrap(err, "failed while parsing longitude float")
}
// Increment the count for this lat/long combo.
key := fmt.Sprintf(coordinatePrecision+","+coordinatePrecision, latitude, longitude)
data[key] = data[key] + 1
}
// Now that we have our `data` populated, index the coordinates in buntdb for fast lookups.
err = db.Update(func(tx *buntdb.Tx) error {
i := 0
for coords := range data {
key := fmt.Sprintf("%s:%d:coords", collection, i)
latitude := strings.Split(coords, ",")[0]
longitude := strings.Split(coords, ",")[1]
value := fmt.Sprintf("[%s %s]", longitude, latitude)
_, _, err := tx.Set(key, value, nil)
if err != nil {
return errors.Wrapf(err, "failed while indexing %s : %s", key, value)
}
i++
}
return nil
})
return nil
} | internal/ipv6/ipv6.go | 0.7413 | 0.403949 | ipv6.go | starcoder |
package crc16
import (
"errors"
"hash"
)
// Hash16 is the common interface implemented by all 16-bit hash functions.
type Hash16 interface {
hash.Hash
Sum16() uint16
}
// New creates a new Hash16 computing the CRC-16 checksum
// using the polynomial represented by the Table.
func New(tab *Table) Hash16 { return &digest{0, tab} }
// NewIBM creates a new Hash16 computing the CRC-16 checksum
// using the IBM polynomial.
func NewIBM() Hash16 { return New(IBMTable) }
// NewCCITT creates a new hash.Hash16 computing the CRC-16 checksum
// using the CCITT polynomial.
func NewCCITT() Hash16 { return New(CCITTTable) }
// NewSCSI creates a new Hash16 computing the CRC-16 checksum
// using the SCSI polynomial.
func NewSCSI() Hash16 { return New(SCSITable) }
// digest represents the partial evaluation of a checksum.
type digest struct {
crc uint16
tab *Table
}
func (d *digest) Size() int { return 2 }
func (d *digest) BlockSize() int { return 1 }
func (d *digest) Reset() { d.crc = 0 }
func (d *digest) Write(p []byte) (n int, err error) {
d.crc = Update(d.crc, d.tab, p)
return len(p), nil
}
func (d *digest) Sum16() uint16 { return d.crc }
func (d *digest) Sum(in []byte) []byte {
s := d.Sum16()
return append(in, byte(s>>8), byte(s))
}
const (
magic = "crc16\x01"
marshaledSize = len(magic) + 2 + 2 + 1
)
func (d *digest) MarshalBinary() ([]byte, error) {
b := make([]byte, 0, marshaledSize)
b = append(b, magic...)
b = appendUint16(b, tableSum(d.tab))
b = appendUint16(b, d.crc)
if d.tab.reversed {
b = append(b, byte(0x01))
} else {
b = append(b, byte(0x00))
}
return b, nil
}
func (d *digest) UnmarshalBinary(b []byte) error {
if len(b) < len(magic) || string(b[:len(magic)]) != magic {
return errors.New("hash/crc16: invalid hash state identifier")
}
if len(b) != marshaledSize {
return errors.New("hash/crc16: invalid hash state size")
}
if tableSum(d.tab) != readUint16(b[6:]) {
return errors.New("hash/crc16: tables do not match")
}
d.crc = readUint16(b[8:])
if b[10] == 0x01 {
d.tab.reversed = true
}
return nil
}
func appendUint16(b []byte, x uint16) []byte {
a := [2]byte{
byte(x >> 8),
byte(x),
}
return append(b, a[:]...)
}
func readUint16(b []byte) uint16 {
_ = b[1]
return uint16(b[1]) | uint16(b[0])<<8
}
// tableSum returns the IBM checksum of table t.
func tableSum(t *Table) uint16 {
var a [1024]byte
b := a[:0]
if t != nil {
for _, x := range t.entries {
b = appendUint16(b, x)
}
}
return ChecksumIBM(b)
} | vendor/github.com/howeyc/crc16/hash.go | 0.681727 | 0.420719 | hash.go | starcoder |
package hyperbolic
import (
"math"
"github.com/calummccain/coxeter/vector"
)
type HPoint struct {
H vector.Vec4
K vector.Vec3
P vector.Vec3
U vector.Vec3
Norm float64
}
func InitHPoint(w, x, y, z float64) HPoint {
return HPoint{H: vector.Vec4{W: w, X: x, Y: y, Z: z}}
}
func InitHPointVec4(v vector.Vec4) HPoint {
return HPoint{H: v}
}
func Scale3(p vector.Vec3, a float64) vector.Vec3 {
return vector.Vec3{X: p.X * a, Y: p.Y * a, Z: p.Z * a}
}
func Scale4(p vector.Vec4, a float64) vector.Vec4 {
return vector.Vec4{W: p.W * a, X: p.X * a, Y: p.Y * a, Z: p.Z * a}
}
func Sum4(p, q vector.Vec4) vector.Vec4 {
return vector.Vec4{W: p.W + q.W, X: p.X + q.X, Y: p.Y + q.Y, Z: p.Z + q.Z}
}
func Diff4(p, q vector.Vec4) vector.Vec4 {
return vector.Vec4{W: p.W - q.W, X: p.X - q.X, Y: p.Y - q.Y, Z: p.Z - q.Z}
}
func (p *HPoint) HyperboloidInnerProduct(q HPoint) float64 {
return p.H.W*q.H.W - p.H.X*q.H.X - p.H.Y*q.H.Y - p.H.Z*q.H.Z
}
func (p *HPoint) HyperbolicNorm() {
p.Norm = p.H.W*p.H.W - p.H.X*p.H.X - p.H.Y*p.H.Y - p.H.Z*p.H.Z
}
func (p *HPoint) HyperboloidToKlein() {
inv := 1.0 / p.H.W
p.K.X = p.H.X * inv
p.K.Y = p.H.Y * inv
p.K.Z = p.H.Z * inv
}
func (p *HPoint) HyperboloidToPoincare() {
eps := HyperboloidToPoincareEps
var inv float64
if math.Abs(p.Norm) < eps {
inv = 1.0 / p.H.W
} else if p.Norm > eps {
inv = 1.0 / (1.0 + p.H.W)
} else {
inv = 1.0 / (p.H.X*p.H.X + p.H.Y*p.H.Y + p.H.Z*p.H.Z)
}
p.P.X = p.H.X * inv
p.P.Y = p.H.Y * inv
p.P.Z = p.H.Z * inv
}
func (p *HPoint) HyperboloidToUHP() {
eps := HyperboloidToUHPEps
if math.Abs(p.H.W-p.H.Z) < eps {
p.U.X = p.H.X / p.H.W
p.U.Y = p.H.Y / p.H.W
p.U.Z = math.Inf(1)
} else if p.Norm < eps {
p.U.X = p.H.X / (p.H.W - p.H.Z)
p.U.Y = p.H.Y / (p.H.W - p.H.Z)
p.U.Z = 0.0
} else {
p.U.X = p.H.X / (p.H.W - p.H.Z)
p.U.Y = p.H.Y / (p.H.W - p.H.Z)
p.U.Z = 1.0 / (p.H.W - p.H.Z)
}
}
func (p *HPoint) KleinToHyperboloid() {
inv := 1.0 / (1.0 - p.K.NormSquared())
p.H.W = inv
p.H.X = p.K.X * inv
p.H.Y = p.K.Y * inv
p.H.Z = p.K.Z * inv
}
func (p *HPoint) KleinToPoincare() {
eps := KleinToPoincareEps
if p.K.NormSquared() < 1-eps {
p.P = p.K
} else {
p.P = Scale3(p.K, 1.0/(1.0+math.Sqrt(1.0-p.K.NormSquared())))
}
}
func (p *HPoint) KleinToUHP() {
p.U = Scale3(vector.Vec3{X: p.K.X, Y: p.K.Y, Z: math.Sqrt(1.0 - p.K.NormSquared())}, 1.0/(1.0-p.K.Z))
}
func (p *HPoint) PoincareToHyperboloid() {
eps := PoincareToHyperboloidEps
r := p.P.NormSquared()
if math.Abs(r-1) < eps {
p.H = vector.Vec4{W: 1, X: p.P.X, Y: p.P.Y, Z: p.P.Z}
} else {
p.H = Scale4(vector.Vec4{W: (1.0 + r) * 0.5, X: p.P.X, Y: p.P.Y, Z: p.P.Z}, 2.0/(1.0-r))
}
}
func (p *HPoint) PoincareToKlein() {
p.K = Scale3(p.P, 2.0/(1.0+p.P.NormSquared()))
}
func (p *HPoint) PoincareToUHP() {
eps := PoincareToUHPEps
r := p.P.NormSquared()
s := 1 / (r + 1.0 - 2.0*p.P.Z)
if s < eps {
p.U = vector.Vec3{X: p.P.X, Y: p.P.Y, Z: math.Inf(1)}
} else if r > 1-eps {
p.U = Scale3(vector.Vec3{X: p.P.X, Y: p.P.Y, Z: 0}, 2.0*s)
} else {
p.U = Scale3(vector.Vec3{X: p.P.X, Y: p.P.Y, Z: (1.0 - r) * 0.5}, 2.0*s)
}
}
func (p *HPoint) UHPToHyperboloid() {
eps := UHPToHyperboloidEps
r := p.U.NormSquared()
if p.U.Z < eps {
p.H = vector.Vec4{W: (r + 1.0) * 0.5, X: p.U.X, Y: p.U.Y, Z: (r - 1.0) * 0.5}
} else {
p.H = Scale4(vector.Vec4{W: (r + 1.0) * 0.5, X: p.U.X, Y: p.U.Y, Z: (r - 1.0) * 0.5}, 1.0/p.U.Z)
}
}
func (p *HPoint) UHPToKlein() {
r := p.U.NormSquared()
p.K = Scale3(vector.Vec3{X: p.U.X, Y: p.U.Y, Z: (r - 1.0) * 0.5}, 2.0/(r+1.0))
}
func (p *HPoint) UHPToPoincare() {
r := p.U.NormSquared()
p.P = Scale3(vector.Vec3{X: p.U.X, Y: p.U.Y, Z: (r - 1.0) * 0.5}, 2.0/(r+1.0+2.0*p.U.Z))
} | hyperbolic/hyperbolicPoint.go | 0.636918 | 0.750587 | hyperbolicPoint.go | starcoder |
package gglm
import (
"fmt"
"math"
)
var _ Mat = &TrMat{}
var _ fmt.Stringer = &TrMat{}
//TrMat represents a transformation matrix
type TrMat struct {
Mat4
}
//Translate adds v to the translation components of the transformation matrix
func (t *TrMat) Translate(v *Vec3) *TrMat {
t.Data[3][0] += v.Data[0]
t.Data[3][1] += v.Data[1]
t.Data[3][2] += v.Data[2]
return t
}
//Scale multiplies the scale components of the transformation matrix by v
func (t *TrMat) Scale(v *Vec3) *TrMat {
t.Data[0][0] *= v.Data[0]
t.Data[1][1] *= v.Data[1]
t.Data[2][2] *= v.Data[2]
return t
}
//Rotate takes a *normalized* axis and angles in radians to rotate around the given axis
func (t *TrMat) Rotate(rads float32, axis *Vec3) *TrMat {
s := Sin32(rads)
c := Cos32(rads)
axis = axis.Normalize()
temp := axis.Clone().Scale(1 - c)
rotate := TrMat{}
rotate.Data[0][0] = c + temp.Data[0]*axis.Data[0]
rotate.Data[0][1] = temp.Data[0]*axis.Data[1] + s*axis.Data[2]
rotate.Data[0][2] = temp.Data[0]*axis.Data[2] - s*axis.Data[1]
rotate.Data[1][0] = temp.Data[1]*axis.Data[0] - s*axis.Data[2]
rotate.Data[1][1] = c + temp.Data[1]*axis.Data[1]
rotate.Data[1][2] = temp.Data[1]*axis.Data[2] + s*axis.Data[0]
rotate.Data[2][0] = temp.Data[2]*axis.Data[0] + s*axis.Data[1]
rotate.Data[2][1] = temp.Data[2]*axis.Data[1] - s*axis.Data[0]
rotate.Data[2][2] = c + temp.Data[2]*axis.Data[2]
result := &Mat4{}
result.Data[0] = t.Col(0).Scale(rotate.Data[0][0]).
Add(t.Col(1).Scale(rotate.Data[0][1])).
Add(t.Col(2).Scale(rotate.Data[0][2])).
Data
result.Data[1] = t.Col(0).Scale(rotate.Data[1][0]).
Add(t.Col(1).Scale(rotate.Data[1][1])).
Add(t.Col(2).Scale(rotate.Data[1][2])).
Data
result.Data[2] = t.Col(0).Scale(rotate.Data[2][0]).
Add(t.Col(1).Scale(rotate.Data[2][1])).
Add(t.Col(2).Scale(rotate.Data[2][2])).
Data
t.Data[0] = result.Data[0]
t.Data[1] = result.Data[1]
t.Data[2] = result.Data[2]
return t
}
func (t *TrMat) Mul(m *TrMat) *TrMat {
t.Mat4.Mul(&m.Mat4)
return t
}
func (t *TrMat) Eq(m *TrMat) bool {
return t.Data == m.Data
}
func (t *TrMat) Clone() *TrMat {
return &TrMat{
Mat4: *t.Mat4.Clone(),
}
}
func NewTranslationMat(v *Vec3) *TrMat {
return &TrMat{
Mat4: Mat4{
Data: [4][4]float32{
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{v.Data[0], v.Data[1], v.Data[2], 1},
},
},
}
}
func NewScaleMat(v *Vec3) *TrMat {
return &TrMat{
Mat4: Mat4{
Data: [4][4]float32{
{v.Data[0], 0, 0, 0},
{0, v.Data[1], 0, 0},
{0, 0, v.Data[2], 0},
{0, 0, 0, 1},
},
},
}
}
func NewRotMat(q *Quat) *TrMat {
//Based on: https://www.weizmann.ac.il/sci-tea/benari/sites/sci-tea.benari/files/uploads/softwareAndLearningMaterials/quaternion-tutorial-2-0-1.pdf
//Note: in the reference p0,p1,p2,p3 == w,x,y,z
xx := q.Data[0] * q.Data[0]
yy := q.Data[1] * q.Data[1]
zz := q.Data[2] * q.Data[2]
ww := q.Data[3] * q.Data[3]
xy := q.Data[0] * q.Data[1]
xz := q.Data[0] * q.Data[2]
xw := q.Data[0] * q.Data[3]
yz := q.Data[1] * q.Data[2]
yw := q.Data[1] * q.Data[3]
zw := q.Data[2] * q.Data[3]
return &TrMat{
Mat4: Mat4{
Data: [4][4]float32{
{2*(ww+xx) - 1, 2 * (zw + xy), 2 * (xz - yw), 0},
{2 * (xy - zw), 2*(ww+yy) - 1, 2 * (xw + yz), 0},
{2 * (yw + xz), 2 * (yz - xw), 2*(ww+zz) - 1, 0},
{0, 0, 0, 1},
},
},
}
}
func LookAt(pos, targetPos, worldUp *Vec3) *TrMat {
forward := SubVec3(targetPos, pos).Normalize()
right := Cross(worldUp, forward).Normalize()
up := Cross(forward, right)
return &TrMat{
Mat4: Mat4{
Data: [4][4]float32{
{right.Data[0], up.Data[0], forward.Data[0], 0},
{right.Data[1], up.Data[1], forward.Data[1], 0},
{right.Data[2], up.Data[2], forward.Data[2], 0},
{-DotVec3(pos, right), -DotVec3(pos, up), DotVec3(pos, forward), 1},
},
},
}
}
//Perspective creates a perspective projection matrix
func Perspective(fov, aspectRatio, nearClip, farClip float32) *Mat4 {
halfFovTan := float32(math.Tan(float64(fov * 0.5)))
return &Mat4{
Data: [4][4]float32{
{1 / (aspectRatio * halfFovTan), 0, 0, 0},
{0, 1 / halfFovTan, 0, 0},
{0, 0, -(nearClip + farClip) / (farClip - nearClip), -1},
{0, 0, -(2 * farClip * nearClip) / (farClip - nearClip), 0},
},
}
}
//Perspective creates an orthographic projection matrix
func Ortho(left, right, top, bottom, nearClip, farClip float32) *TrMat {
return &TrMat{
Mat4: Mat4{
Data: [4][4]float32{
{2 / (right - left), 0, 0, 0},
{0, 2 / (top - bottom), 0, 0},
{0, 0, -2 / (farClip - nearClip), 0},
{-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(farClip + nearClip) / (farClip - nearClip), 1},
},
},
}
}
func NewTrMatId() *TrMat {
return &TrMat{
Mat4: *NewMat4Id(),
}
} | gglm/transform.go | 0.732783 | 0.58519 | transform.go | starcoder |
Currently it makes not much sense to try to solve the problem
as it obviousely needs something like the math/big package.
The current solution works for sequences up to S(49) only.
However, I'll keep this for further investigations.
*/
package main
import (
"fmt"
)
// main is the entry point of the clocksequence app
func main() {
n := 49 // n in S(n)
var stub int // stub of digits
var total int // sum of all stubs
p := 1 // Next position in the sequence of digits
for i := 1; i <= n; i++ {
stub, p = getNextStub(i, p)
fmt.Println(i, stub)
total += stub
}
fmt.Printf("The resulting total of S(%d) is %d\n", n, total)
fmt.Printf("The resulting total of S(%d) mod 123454321 is %d\n",
n, total%123454321)
}
// getNextStub returns a stub of digits from the sequence of digits.
// It starts at position p in the sequence of digits and returns the
// stub of digits that builds the sum of n. It also returns the next
// position in the thought sequence of digits.
func getNextStub(n, p int) (int, int) {
var sum int // sum of digits in the stub
var digit int // digit at current position
var stub int // stub to return
for sum < n {
digit = getDigit(p)
p++
sum += digit
if sum < n {
stub += digit
stub = stub * 10
} else {
stub += digit
}
}
return stub, p
}
// getDigit returns the value of a given position from a thought
// infinitive repeating sequence of digits 123432123432...
// The position is based on 1; e.g. getDigit(5) == 3.
func getDigit(p int) int {
i := (p - 1) % 6
return []int{1, 2, 3, 4, 3, 2}[i]
}
/*
Clock sequence
Problem 506
Published on Sunday, 8th March 2015, 04:00 am;
Solved by 522; Difficulty rating: 30%
Consider the infinite repeating sequence of digits:
1234321234321234321...
Amazingly, you can break this sequence of digits into a sequence of
integers such that the sum of the digits in the n'th value is n.
The sequence goes as follows:
1, 2, 3, 4, 32, 123, 43, 2123, 432, 1234, 32123, ...
Let vn be the n'th value in this sequence.
For example, v2 = 2, v5 = 32 and v11 = 32123.
Let S(n) be v1 + v2 + ... + vn.
For example, S(11) = 36120, and S(1000) mod 123454321 = 18232686.
Find S(1014) mod 123454321.
*/ | problem_506/main.go | 0.580352 | 0.450601 | main.go | starcoder |
package floatgeom
import (
"github.com/oakmound/oak/v3/alg"
)
// A Polygon2 is a series of points in 2D space.
type Polygon2 struct {
// Bounding is a cached bounding box calculated from the input points
// It is exported for convenience, but should be modified with care
Bounding Rect2
// The component points of the polygon. If modified, Bounding should
// be updated with NewBoundingRect2.
Points []Point2
rectangular bool
}
// NewPolygon2 is a helper method to construct a valid polygon. Polygons
// cannot contain less than 3 points.
func NewPolygon2(p1, p2, p3 Point2, pn ...Point2) Polygon2 {
pts := append([]Point2{p1, p2, p3}, pn...)
bounding := NewBoundingRect2(pts...)
return Polygon2{
Bounding: bounding,
Points: pts,
rectangular: isRectangular(pts...),
}
}
// Contains returns whether or not the current Polygon contains the passed in Point.
// If it is known that the polygon is convex, ConvexContains should be preferred for
// performance.
func (pg Polygon2) Contains(x, y float64) (contains bool) {
if !pg.Bounding.Contains(Point2{x, y}) {
return
}
j := len(pg.Points) - 1
for i := 0; i < len(pg.Points); i++ {
tp1 := pg.Points[i]
tp2 := pg.Points[j]
if (tp1.Y() > y) != (tp2.Y() > y) { // Three comparisons
if x < (tp2.X()-tp1.X())*(y-tp1.Y())/(tp2.Y()-tp1.Y())+tp1.X() { // One Comparison, Four add/sub, Two mult/div
contains = !contains
}
}
j = i
}
return
}
// ConvexContains returns whether the given point is contained by the input polygon.
// It assumes the polygon is convex.
func (pg Polygon2) ConvexContains(x, y float64) bool {
p := Point2{x, y}
if !pg.Bounding.Contains(p) {
return false
}
prev := 0
for i := 0; i < len(pg.Points); i++ {
tp1 := pg.Points[i]
tp2 := pg.Points[(i+1)%len(pg.Points)]
tp3 := tp2.Sub(tp1)
tp4 := p.Sub(tp1)
cur := getSide(tp3, tp4)
if cur == 0 {
return false
} else if prev == 0 {
} else if prev != cur {
return false
}
prev = cur
}
return true
}
// TODO: rename this to its real math name, export it
func getSide(a, b Point2) int {
x := a.X()*b.Y() - a.Y()*b.X()
if x == 0 {
return 0
} else if x < 1 {
return -1
} else {
return 1
}
}
// OverlappingRectCollides returns whether a Rect2 intersects or is contained by this Polygon.
// This method differs from RectCollides because it assumes that we already know r overlaps with pg.Bounding.
// It is only valid for convex polygons.
func (pg Polygon2) OverlappingRectCollides(r Rect2) bool {
if pg.rectangular {
return true
}
diags := [][2]Point2{
{
{r.Min.X(), r.Max.Y()},
{r.Max.X(), r.Min.Y()},
}, {
r.Min,
r.Max,
},
}
last := pg.Points[len(pg.Points)-1]
for i := 0; i < len(pg.Points); i++ {
next := pg.Points[i]
if r.Contains(next) {
return true
}
// Checking line segment from last to next
for _, diag := range diags {
if orient(diag[0], diag[1], last) != orient(diag[0], diag[1], next) &&
orient(next, last, diag[0]) != orient(next, last, diag[1]) {
return true
}
}
last = next
}
return false
}
// RectCollides returns whether a Rect2 intersects or is contained by this Polygon.
// It is only valid for convex polygons.
func (pg Polygon2) RectCollides(r Rect2) bool {
x := float64(r.Min.X())
y := float64(r.Min.Y())
x2 := float64(r.Max.X())
y2 := float64(r.Max.Y())
dx := pg.Bounding.Min.X()
dy := pg.Bounding.Min.Y()
dx2 := pg.Bounding.Max.X()
dy2 := pg.Bounding.Max.Y()
overlapX := false
if x > dx {
if x < dx2 {
overlapX = true
}
} else {
if dx < x2 {
overlapX = true
}
}
if !overlapX {
return false
}
if y > dy {
if y < dy2 {
return pg.OverlappingRectCollides(r)
}
} else {
if dy < y2 {
return pg.OverlappingRectCollides(r)
}
}
return false
}
func isRectangular(pts ...Point2) bool {
last := pts[len(pts)-1]
for _, pt := range pts {
// The last point needs to share an x or y value with this point
if !alg.F64eq(pt.X(), last.X()) && !alg.F64eq(pt.Y(), last.Y()) {
return false
}
last = pt
}
return true
}
func orient(p1, p2, p3 Point2) int8 {
val := (p2.Y()-p1.Y())*(p3.X()-p2.X()) -
(p2.X()-p1.X())*(p3.Y()-p2.Y())
switch {
case val < 0:
return 2
case val > 0:
return 1
default:
return 0
}
} | alg/floatgeom/polygon.go | 0.734024 | 0.659433 | polygon.go | starcoder |
package iso20022
// Amount of money for which goods or services are offered, sold, or bought.
type UnitPrice6 struct {
// Type and information about a price.
Type *PriceType2 `xml:"Tp"`
// Type of pricing calculation method.
PriceMethod *PriceMethod1Code `xml:"PricMtd,omitempty"`
// Value of the price, eg, as a currency and value.
ValueInInvestmentCurrency []*PriceValue1 `xml:"ValInInvstmtCcy"`
// Value of the price, eg, as a currency and value.
ValueInAlternativeCurrency []*PriceValue1 `xml:"ValInAltrntvCcy,omitempty"`
// Indicates whether the price information can be used for the execution of a transaction.
ForExecutionIndicator *YesNoIndicator `xml:"ForExctnInd"`
// Indicates whether the dividend is included, ie, cum-dividend, in the price. When the dividend is not included, the price will be ex-dividend.
CumDividendIndicator *YesNoIndicator `xml:"CumDvddInd"`
// Ratio applied on the non-adjusted price.
CalculationBasis *PercentageRate `xml:"ClctnBsis,omitempty"`
// Specifies the number of days from trade date that the counterparty on the other side of the trade should "given up" or divulged.
NumberOfDaysAccrued *Number `xml:"NbOfDaysAcrd,omitempty"`
// Amount included in the NAV 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.
TaxableIncomePerShare *AmountPrice1Choice `xml:"TaxblIncmPerShr,omitempty"`
// Specifies whether the fund calculates a taxable interest per share (TIS).
TaxableIncomePerShareCalculated *TaxableIncomePerShareCalculated1 `xml:"TaxblIncmPerShrClctd,omitempty"`
// Amount of money associated with a service.
ChargeDetails []*Charge9 `xml:"ChrgDtls,omitempty"`
// Information related to taxes that are due.
TaxLiabilityDetails []*Tax8 `xml:"TaxLbltyDtls,omitempty"`
// Information related to taxes that are paid back.
TaxRefundDetails []*Tax8 `xml:"TaxRfndDtls,omitempty"`
}
func (u *UnitPrice6) AddType() *PriceType2 {
u.Type = new(PriceType2)
return u.Type
}
func (u *UnitPrice6) SetPriceMethod(value string) {
u.PriceMethod = (*PriceMethod1Code)(&value)
}
func (u *UnitPrice6) AddValueInInvestmentCurrency() *PriceValue1 {
newValue := new (PriceValue1)
u.ValueInInvestmentCurrency = append(u.ValueInInvestmentCurrency, newValue)
return newValue
}
func (u *UnitPrice6) AddValueInAlternativeCurrency() *PriceValue1 {
newValue := new (PriceValue1)
u.ValueInAlternativeCurrency = append(u.ValueInAlternativeCurrency, newValue)
return newValue
}
func (u *UnitPrice6) SetForExecutionIndicator(value string) {
u.ForExecutionIndicator = (*YesNoIndicator)(&value)
}
func (u *UnitPrice6) SetCumDividendIndicator(value string) {
u.CumDividendIndicator = (*YesNoIndicator)(&value)
}
func (u *UnitPrice6) SetCalculationBasis(value string) {
u.CalculationBasis = (*PercentageRate)(&value)
}
func (u *UnitPrice6) SetNumberOfDaysAccrued(value string) {
u.NumberOfDaysAccrued = (*Number)(&value)
}
func (u *UnitPrice6) AddTaxableIncomePerShare() *AmountPrice1Choice {
u.TaxableIncomePerShare = new(AmountPrice1Choice)
return u.TaxableIncomePerShare
}
func (u *UnitPrice6) AddTaxableIncomePerShareCalculated() *TaxableIncomePerShareCalculated1 {
u.TaxableIncomePerShareCalculated = new(TaxableIncomePerShareCalculated1)
return u.TaxableIncomePerShareCalculated
}
func (u *UnitPrice6) AddChargeDetails() *Charge9 {
newValue := new (Charge9)
u.ChargeDetails = append(u.ChargeDetails, newValue)
return newValue
}
func (u *UnitPrice6) AddTaxLiabilityDetails() *Tax8 {
newValue := new (Tax8)
u.TaxLiabilityDetails = append(u.TaxLiabilityDetails, newValue)
return newValue
}
func (u *UnitPrice6) AddTaxRefundDetails() *Tax8 {
newValue := new (Tax8)
u.TaxRefundDetails = append(u.TaxRefundDetails, newValue)
return newValue
} | UnitPrice6.go | 0.79649 | 0.486697 | UnitPrice6.go | starcoder |
package helpers
import (
"fmt"
"strings"
"github.com/noxer/tinkerforge"
)
// Version represents a bricklet version number
type Version [3]byte
// NewVersion creates a new Version array
func NewVersion(main, sub, patch byte) Version {
return Version{main, sub, patch}
}
// String prints a version array
func (v Version) String() string {
return fmt.Sprintf("%d.%d.%d", v[0], v[1], v[2])
}
var (
// DeviceIdentifiers is a map from the device ID to the name of the bricklet
DeviceIdentifiers = map[uint16]string{
11: "Brick DC",
13: "Brick Master",
14: "Brick Servo",
15: "Brick Stepper",
16: "Brick IMU",
17: "Brick RED",
21: "Bricklet Ambient Light",
23: "Bricklet Current12",
24: "Bricklet Current25",
25: "Bricklet Distance IR",
26: "Bricklet Dual Relay",
27: "Bricklet Humidity",
28: "Bricklet IO-16",
29: "Bricklet IO-4",
210: "Bricklet Joystick",
211: "Bricklet LCD 16x2",
212: "Bricklet LCD 20x4",
213: "Bricklet Linear Poti",
214: "Bricklet Piezo Buzzer",
215: "Bricklet Rotary Poti",
216: "Bricklet Temperature",
217: "Bricklet Temperature IR",
218: "Bricklet Voltage",
219: "Bricklet Analog In",
220: "Bricklet Analog Out",
221: "Bricklet Barometer",
222: "Bricklet GPS",
223: "Bricklet Industrial Digital In 4",
224: "Bricklet Industrial Digital Out 4",
225: "Bricklet Industrial Quad Relay",
226: "Bricklet PTC",
227: "Bricklet Voltage/Current",
228: "Bricklet Industrial Dual 0-20mA",
229: "Bricklet Distance US",
230: "Bricklet Dual Button",
231: "Bricklet LED Strip",
232: "Bricklet Moisture",
233: "Bricklet Motion Detector",
234: "Bricklet Multi Touch",
235: "Bricklet Remote Switch",
236: "Bricklet Rotary Encoder",
237: "Bricklet Segment Display 4x7",
238: "Bricklet Sound Intensity",
239: "Bricklet Tilt",
240: "Bricklet Hall Effect",
241: "Bricklet Line",
242: "Bricklet Piezo Speaker",
243: "Bricklet Color",
244: "Bricklet Solid State Relay",
245: "Bricklet Heart Rate",
246: "Bricklet NFC/RFID",
}
)
// BrickletIdentity holds identity information of a bricklet
type BrickletIdentity struct {
UID string
ConnectedUID string
Position byte
HardwareVersion Version
FirmwareVersion Version
DeviceIdentifier uint16
}
// GetIdentity queries idenitity information from a bricklet
func GetIdentity(t tinkerforge.Tinkerforge, uid uint32) (*BrickletIdentity, error) {
p, err := tinkerforge.NewPacket(uid, 255, true)
if err != nil {
return nil, err
}
res, err := t.Send(p)
if err != nil {
return nil, err
}
i := &BrickletIdentity{}
displayUID := make([]byte, 8)
connectedDisplayUID := make([]byte, 8)
if err = res.Decode(&displayUID, &connectedDisplayUID, &i.Position, &i.HardwareVersion, &i.FirmwareVersion, &i.DeviceIdentifier); err != nil {
return nil, err
}
i.UID = strings.TrimSpace(string(displayUID))
i.ConnectedUID = strings.TrimSpace(string(connectedDisplayUID))
return i, nil
}
// DeviceName translates the device ID into a human readable name
func (i *BrickletIdentity) DeviceName() string {
return DeviceIdentifiers[i.DeviceIdentifier]
} | helpers/helpers.go | 0.603698 | 0.555194 | helpers.go | starcoder |
This implementation draws from the Daisuke Maki's Perl module, which itself is
based on the original libketama code. That code was licensed under the GPLv2,
and thus so is this.
The major API change from libketama is that Algorithm::ConsistentHash::Ketama allows hashing
arbitrary strings, instead of just memcached server IP addresses.
Original source: https://github.com/dgryski/go-ketama/blob/master/ketama.go
Modified to store integers directly to avoid a pointer lookup and type coercion
*/
package distribution
import (
"crypto/md5"
"fmt"
"sort"
)
type Bucket struct {
Label string
Weight int
// Index of the client to use
Data int
}
type continuumPoint struct {
bucket Bucket
point uint32
}
type KetamaContinuum struct {
ring points
}
type points []continuumPoint
func (c points) Less(i, j int) bool { return c[i].point < c[j].point }
func (c points) Len() int { return len(c) }
func (c points) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func md5Digest(in string) []byte {
h := md5.New()
h.Write([]byte(in))
return h.Sum(nil)
}
func NewKetama(buckets []Bucket) (*KetamaContinuum, error) {
numbuckets := len(buckets)
if numbuckets == 0 {
// let them error when they try to use it
return nil, nil
}
ring := make(points, 0, numbuckets*160)
totalweight := 0
for _, b := range buckets {
totalweight += b.Weight
}
for i, b := range buckets {
pct := float32(b.Weight) / float32(totalweight)
// this is the equivalent of C's promotion rules, but in Go, to maintain exact compatibility with the C library
limit := int(float32(float64(pct) * 40.0 * float64(numbuckets)))
for k := 0; k < limit; k++ {
/* 40 hashes, 4 numbers per hash = 160 points per bucket */
ss := fmt.Sprintf("%s-%d", b.Label, k)
digest := md5Digest(ss)
for h := 0; h < 4; h++ {
point := continuumPoint{
point: uint32(digest[3+h*4])<<24 | uint32(digest[2+h*4])<<16 | uint32(digest[1+h*4])<<8 | uint32(digest[h*4]),
bucket: buckets[i],
}
ring = append(ring, point)
}
}
}
sort.Sort(ring)
return &KetamaContinuum{
ring: ring,
}, nil
}
// Retrieves the Data for a uint32 value generated by another algorithm.
func (c KetamaContinuum) Get(h uint32) int {
if len(c.ring) == 0 {
panic("Expected ring to be non-empty")
}
// the above md5 is way more expensive than this branch
var i uint
i = uint(sort.Search(len(c.ring), func(i int) bool { return c.ring[i].point >= h }))
if i >= uint(len(c.ring)) {
i = 0
}
return c.ring[i].bucket.Data
} | sharded/distribution/ketama.go | 0.828315 | 0.486575 | ketama.go | starcoder |
// In alcuni linguaggi è idiomatico l'utilizzo di
// strutture di dati e algoritmi [generici](http://en.wikipedia.org/wiki/Generic_programming).
// Go non supporta algoritmi/strutture generiche: in
// genere si forniscono funzioni per collezioni se sono
// specificamente necessari per il tuo programma e per i
// tuoi tipi.
// A seguire un po' di esempi di funzioni che agiscono su
// slice di `string`. Puoi usare questi esempi per
// costruire le tue proprie funzioni. Nota che in alcuni
// casi può essere più chiaro scrivere il corpo della
// funzione direttamente nel tuo codice stesso, piuttosto
// che creare e chiamare una funzione helper.
package main
import "strings"
import "fmt"
// Restituisce il primo indice del valore in `vs`
// corrispondente a `t`, o -1 se nessuna corrispondenza
// viene trovata.
func Indice(vs []string, t string) int {
for i, v := range vs {
if v == t {
return i
}
}
return -1
}
// Restituisce `true` se la stringa `t` è nello slice `vs`.
func Incluso(vs []string, t string) bool {
return Indice(vs, t) >= 0
}
// Restituisce `true` se una delle stringhe nello slice
// soddisfa la funzione condizionale `f`.
func AlmenoUno(vs []string, f func(string) bool) bool {
for _, v := range vs {
if f(v) {
return true
}
}
return false
}
// Restituisce `true` se tutte le `string` nello slice
// soddisfano la funzione condizionale `f`.
func Tutti(vs []string, f func(string) bool) bool {
for _, v := range vs {
if !f(v) {
return false
}
}
return true
}
// Restituisce un nuovo slice che contiene tutte le stringhe
// nello slice `vs` che soddisfano la funzione
// condizionale `f`.
func Filtra(vs []string, f func(string) bool) []string {
vsf := make([]string, 0)
for _, v := range vs {
if f(v) {
vsf = append(vsf, v)
}
}
return vsf
}
// Restituisce un nuovo slice che contiene i risultati
// dell'applicazione della funzione `f` su ogni stringa
// dello slice `vs`.
func Applica(vs []string,
f func(string) string) []string {
vsa := make([]string, len(vs))
for i, v := range vs {
vsa[i] = f(v)
}
return vsa
}
func main() {
// Di seguito proviamo ad utilizzare le nostre varie
// funzioni di collezione.
var strs = []string{"pesca", "mela", "pera", "prugna"}
fmt.Println(Indice(strs, "pera"))
fmt.Println(Incluso(strs, "uva"))
fmt.Println(AlmenoUno(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))
fmt.Println(Tutti(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))
fmt.Println(Filtra(strs, func(v string) bool {
return strings.Contains(v, "r")
}))
// Gli esempi sovrastanti usavano tutti funzioni
// anonime, ma puoi anche usare funzioni pre-esistenti
// (non anonime) con il tipo corretto.
fmt.Println(Applica(strs, strings.ToUpper))
} | examples/funzioni-per-collezioni/funzioni-per-collezioni.go | 0.574395 | 0.451266 | funzioni-per-collezioni.go | starcoder |
package packed
// Efficient sequential read/write of packed integers.
type BulkOperationPacked7 struct {
*BulkOperationPacked
}
func newBulkOperationPacked7() BulkOperation {
return &BulkOperationPacked7{newBulkOperationPacked(7)}
}
func (op *BulkOperationPacked7) decodeLongToInt(blocks []int64, values []int32, iterations int) {
blocksOffset, valuesOffset := 0, 0
for i := 0; i < iterations; i ++ {
block0 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 57)); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 50) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 43) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 36) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 29) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 22) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 15) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 8) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block0) >> 1) & 127); valuesOffset++
block1 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(((block0 & 1) << 6) | (int64(uint64(block1) >> 58))); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 51) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 44) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 37) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 30) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 23) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 16) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 9) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block1) >> 2) & 127); valuesOffset++
block2 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(((block1 & 3) << 5) | (int64(uint64(block2) >> 59))); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 52) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 45) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 38) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 31) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 24) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 17) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 10) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block2) >> 3) & 127); valuesOffset++
block3 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(((block2 & 7) << 4) | (int64(uint64(block3) >> 60))); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 53) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 46) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 39) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 32) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 25) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 18) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 11) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block3) >> 4) & 127); valuesOffset++
block4 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(((block3 & 15) << 3) | (int64(uint64(block4) >> 61))); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 54) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 47) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 40) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 33) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 26) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 19) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 12) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block4) >> 5) & 127); valuesOffset++
block5 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(((block4 & 31) << 2) | (int64(uint64(block5) >> 62))); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 55) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 48) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 41) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 34) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 27) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 20) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 13) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block5) >> 6) & 127); valuesOffset++
block6 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int32(((block5 & 63) << 1) | (int64(uint64(block6) >> 63))); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 56) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 49) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 42) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 35) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 28) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 21) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 14) & 127); valuesOffset++
values[valuesOffset] = int32(int64(uint64(block6) >> 7) & 127); valuesOffset++
values[valuesOffset] = int32(block6 & 127); valuesOffset++
}
}
func (op *BulkOperationPacked7) decodeByteToInt(blocks []byte, values []int32, iterations int) {
blocksOffset, valuesOffset := 0, 0
for i := 0; i < iterations; i ++ {
byte0 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32( int64(uint8(byte0) >> 1))
valuesOffset++
byte1 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32((int64(byte0 & 1) << 6) | int64(uint8(byte1) >> 2))
valuesOffset++
byte2 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32((int64(byte1 & 3) << 5) | int64(uint8(byte2) >> 3))
valuesOffset++
byte3 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32((int64(byte2 & 7) << 4) | int64(uint8(byte3) >> 4))
valuesOffset++
byte4 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32((int64(byte3 & 15) << 3) | int64(uint8(byte4) >> 5))
valuesOffset++
byte5 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32((int64(byte4 & 31) << 2) | int64(uint8(byte5) >> 6))
valuesOffset++
byte6 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int32((int64(byte5 & 63) << 1) | int64(uint8(byte6) >> 7))
valuesOffset++
values[valuesOffset] = int32( int64(byte6) & 127)
valuesOffset++
}
}
func (op *BulkOperationPacked7) decodeLongToLong(blocks []int64, values []int64, iterations int) {
blocksOffset, valuesOffset := 0, 0
for i := 0; i < iterations; i ++ {
block0 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = int64(uint64(block0) >> 57); valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 50) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 43) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 36) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 29) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 22) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 15) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 8) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block0) >> 1) & 127; valuesOffset++
block1 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = ((block0 & 1) << 6) | (int64(uint64(block1) >> 58)); valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 51) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 44) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 37) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 30) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 23) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 16) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 9) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block1) >> 2) & 127; valuesOffset++
block2 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = ((block1 & 3) << 5) | (int64(uint64(block2) >> 59)); valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 52) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 45) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 38) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 31) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 24) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 17) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 10) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block2) >> 3) & 127; valuesOffset++
block3 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = ((block2 & 7) << 4) | (int64(uint64(block3) >> 60)); valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 53) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 46) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 39) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 32) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 25) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 18) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 11) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block3) >> 4) & 127; valuesOffset++
block4 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = ((block3 & 15) << 3) | (int64(uint64(block4) >> 61)); valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 54) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 47) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 40) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 33) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 26) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 19) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 12) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block4) >> 5) & 127; valuesOffset++
block5 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = ((block4 & 31) << 2) | (int64(uint64(block5) >> 62)); valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 55) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 48) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 41) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 34) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 27) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 20) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 13) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block5) >> 6) & 127; valuesOffset++
block6 := blocks[blocksOffset]; blocksOffset++
values[valuesOffset] = ((block5 & 63) << 1) | (int64(uint64(block6) >> 63)); valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 56) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 49) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 42) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 35) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 28) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 21) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 14) & 127; valuesOffset++
values[valuesOffset] = int64(uint64(block6) >> 7) & 127; valuesOffset++
values[valuesOffset] = block6 & 127; valuesOffset++
}
}
func (op *BulkOperationPacked7) decodeByteToLong(blocks []byte, values []int64, iterations int) {
blocksOffset, valuesOffset := 0, 0
for i := 0; i < iterations; i ++ {
byte0 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64( int64(uint8(byte0) >> 1))
valuesOffset++
byte1 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64((int64(byte0 & 1) << 6) | int64(uint8(byte1) >> 2))
valuesOffset++
byte2 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64((int64(byte1 & 3) << 5) | int64(uint8(byte2) >> 3))
valuesOffset++
byte3 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64((int64(byte2 & 7) << 4) | int64(uint8(byte3) >> 4))
valuesOffset++
byte4 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64((int64(byte3 & 15) << 3) | int64(uint8(byte4) >> 5))
valuesOffset++
byte5 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64((int64(byte4 & 31) << 2) | int64(uint8(byte5) >> 6))
valuesOffset++
byte6 := blocks[blocksOffset]
blocksOffset++
values[valuesOffset] = int64((int64(byte5 & 63) << 1) | int64(uint8(byte6) >> 7))
valuesOffset++
values[valuesOffset] = int64( int64(byte6) & 127)
valuesOffset++
}
} | vendor/github.com/balzaczyy/golucene/core/util/packed/bulkOperation7.go | 0.52975 | 0.702517 | bulkOperation7.go | starcoder |
package wirepath
import "google.golang.org/protobuf/reflect/protoreflect"
// Value is like protoreflect.Value, but it preserves the protobuf kind of the
// value.
type Value struct {
kind protoreflect.Kind
v protoreflect.Value
}
func ValueOf(v interface{}, kind protoreflect.Kind) Value {
panic("unsupported")
}
func ValueOfEnum(v protoreflect.EnumNumber) Value {
return Value{protoreflect.EnumKind, protoreflect.ValueOfEnum(v)}
}
func ValueOfInt32(v int32) Value { return Value{protoreflect.Int32Kind, protoreflect.ValueOfInt32(v)} }
func ValueOfSint32(v int32) Value {
return Value{protoreflect.Sint32Kind, protoreflect.ValueOfInt32(v)}
}
func ValueOfUint32(v uint32) Value {
return Value{protoreflect.Uint32Kind, protoreflect.ValueOfUint32(v)}
}
func ValueOfInt64(v int64) Value { return Value{protoreflect.Int64Kind, protoreflect.ValueOfInt64(v)} }
func ValueOfSint64(v int64) Value {
return Value{protoreflect.Sint64Kind, protoreflect.ValueOfInt64(v)}
}
func ValueOfUint64(v uint64) Value {
return Value{protoreflect.Uint64Kind, protoreflect.ValueOfUint64(v)}
}
func ValueOfSfixed32(v int32) Value {
return Value{protoreflect.Sfixed32Kind, protoreflect.ValueOfInt32(v)}
}
func ValueOfFixed32(v uint32) Value {
return Value{protoreflect.Fixed32Kind, protoreflect.ValueOfUint32(v)}
}
func ValueOfFloat(v float32) Value {
return Value{protoreflect.FloatKind, protoreflect.ValueOfFloat32(v)}
}
func ValueOfSfixed64(v int64) Value {
return Value{protoreflect.Sfixed64Kind, protoreflect.ValueOfInt64(v)}
}
func ValueOfFixed64(v uint64) Value {
return Value{protoreflect.Fixed64Kind, protoreflect.ValueOfUint64(v)}
}
func ValueOfDouble(v float64) Value {
return Value{protoreflect.DoubleKind, protoreflect.ValueOfFloat64(v)}
}
func ValueOfString(v string) Value {
return Value{protoreflect.StringKind, protoreflect.ValueOfString(v)}
}
func ValueOfBytes(v []byte) Value { return Value{protoreflect.BytesKind, protoreflect.ValueOfBytes(v)} }
func ValueOfMessage(v protoreflect.Message) Value {
return Value{protoreflect.MessageKind, protoreflect.ValueOfMessage(v)}
}
func ValueOfList(v protoreflect.List, kind protoreflect.Kind) Value {
return Value{kind, protoreflect.ValueOfList(v)}
}
// func ValueOf(v interface{}) Value
// func ValueOfBool(v bool) Value
// func ValueOfBytes(v []byte) Value
// func ValueOfEnum(v protoreflect.EnumNumber) Value
// func ValueOfFloat32(v float32) Value
// func ValueOfFloat64(v float64) Value
// func ValueOfInt32(v int32) Value
// func ValueOfInt64(v int64) Value
// func ValueOfList(v protoreflect.List) Value
// func ValueOfMap(v protoreflect.Map) Value
// func ValueOfMessage(v protoreflect.Message) Value
// func ValueOfString(v string) Value
// func ValueOfUint32(v uint32) Value
// func ValueOfUint64(v uint64) Value
func (v Value) Kind() protoreflect.Kind { return v.kind }
func (v Value) Bool() bool { return v.v.Bool() }
func (v Value) Bytes() []byte { return v.v.Bytes() }
func (v Value) Enum() protoreflect.EnumNumber { return v.v.Enum() }
func (v Value) Float() float64 { return v.v.Float() }
func (v Value) Int() int64 { return v.v.Int() }
func (v Value) Interface() interface{} { return v.v.Interface() }
func (v Value) IsValid() bool { return v.v.IsValid() }
func (v Value) List() protoreflect.List { return v.v.List() }
func (v Value) Map() protoreflect.Map { return v.v.Map() }
func (v Value) MapKey() protoreflect.MapKey { return v.v.MapKey() }
func (v Value) Message() protoreflect.Message { return v.v.Message() }
func (v Value) String() string { return v.v.String() }
func (v Value) Uint() uint64 { return v.v.Uint() } | wirepath/wirepath_value.go | 0.742235 | 0.499512 | wirepath_value.go | starcoder |
package main
import (
"fmt"
"math"
)
// Node is a node in a tree
type Node struct {
value int
freq int
height int
left *Node
right *Node
}
// AVLTree is Avl tree implementation
type AVLTree struct {
root *Node
}
// Height returs the height of a node
func Height(node *Node) int {
if node == nil {
return 0
}
return node.height
}
// BalancingFactor returns a balancing factor of a node
func BalancingFactor(node *Node) int {
if node == nil {
return 0
}
return Height(node.left) - Height(node.right)
}
// Insert inserts a node preserving avl
func Insert(node *Node, value int) *Node {
if node == nil {
nn := &Node{value: value, height: 1, freq: 1}
return nn
}
if value > node.value {
node.right = Insert(node.right, value)
} else if value < node.value {
node.left = Insert(node.left, value)
} else if value == node.value {
node.freq++
}
node.height = int(math.Max(float64(Height(node.left)), float64(Height(node.right))) + 1)
bf := BalancingFactor(node)
// LL case
if bf > 1 && value < node.left.value {
return rightRotate(node)
}
// RR case
if bf < -1 && value > node.right.value {
return leftRotate(node)
}
// LR case
if bf > 1 && value > node.left.value {
node.left = leftRotate(node.left)
return rightRotate(node)
}
// RL case
if bf < -1 && value < node.right.value {
node.right = rightRotate(node.right)
return leftRotate(node)
}
return node
}
// leftRotate rotates a given node to left
func leftRotate(node *Node) *Node {
b := node.right
t := b.left
b.left = node
node.right = t
node.height = int(math.Max(float64(Height(node.left)), float64(Height(node.right))) + 1)
b.height = int(math.Max(float64(Height(b.left)), float64(Height(b.right))) + 1)
return b
}
// rightRotate rotates a given node to right
func rightRotate(node *Node) *Node {
b := node.left
t := b.right
b.right = node
node.left = t
node.height = int(math.Max(float64(Height(node.left)), float64(Height(node.right))) + 1)
b.height = int(math.Max(float64(Height(b.left)), float64(Height(b.right))) + 1)
return b
}
// Find finds a key from the avl
func (avl *AVLTree) Find(value int) {
current := avl.root
for {
if value < current.value {
if current.left == nil {
fmt.Println("\n-- Key not found. --")
return
} else if value == current.left.value {
fmt.Println("\n-- Key found. --")
fmt.Println("Parent is: ", current.value)
fmt.Println("Sibling is: ", current.right)
fmt.Println("Left child is: ", current.left.left)
fmt.Println("Right child is: ", current.left.right)
return
}
current = current.left
} else if value > current.value {
if current.right == nil {
fmt.Println("\n-- Key not found. --")
return
}
if value == current.right.value {
fmt.Println("\n-- Key found. --")
fmt.Println("Parent is: ", current.value)
fmt.Println("Sibling is: ", current.left)
fmt.Println("Left child is: ", current.right.left)
fmt.Println("Right child is: ", current.right.right)
return
}
current = current.right
} else if value == current.value {
fmt.Println("\n-- Key is root itself. --")
fmt.Println("Left child is: ", current.left)
fmt.Println("Right child is: ", current.right)
return
}
}
}
var avl *AVLTree
func init() {
avl = &AVLTree{}
}
func main() {
i := 0
for i == 0 {
fmt.Println("\n1. INSERT")
fmt.Println("2. DISPLAY using BFS")
fmt.Println("3. DISPLAY using DFS Pre-order")
fmt.Println("4. DISPLAY using DFS In-order")
fmt.Println("5. DISPLAY using DFS Post-order")
fmt.Println("6. FIND")
fmt.Println("7. EXIT")
var choice int
fmt.Print("Enter your choice: ")
fmt.Scanf("%d\n", &choice)
switch choice {
case 1:
insNode()
case 2:
fmt.Println("\n", avl.BFS())
case 3:
fmt.Println("\n", avl.DFS("pre"))
case 4:
fmt.Println("\n", avl.DFS("in"))
case 5:
fmt.Println("\n", avl.DFS("pos"))
case 6:
findNode()
case 7:
i = 1
default:
fmt.Println("Command not recognized.")
}
}
}
func insNode() {
var element int
fmt.Print("Enter the node value that you want to insert: ")
fmt.Scanf("%d\n", &element)
avl.root = Insert(avl.root, element)
}
func findNode() {
var element int
fmt.Print("Enter the value of the key: ")
fmt.Scanf("%d\n", &element)
avl.Find(element)
} | trees/avl_tree_using_ll/avl_tree_using_ll.go | 0.728941 | 0.480174 | avl_tree_using_ll.go | starcoder |
package tool
import (
"math"
"strconv"
"strings"
"time"
)
// DateFormat pattern rules.
// Golang 格式化时间默认字符 2006-01-02 15:04:05
var datePatterns = []string{
// year
"Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
"y", "06", //A two digit representation of a year Examples: 99 or 03
// month
"m", "01", // Numeric representation of a month, with leading zeros 01 through 12
"n", "1", // Numeric representation of a month, without leading zeros 1 through 12
"M", "Jan", // A short textual representation of a month, three letters Jan through Dec
"F", "January", // A full textual representation of a month, such as January or March January through December
// day
"d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
"j", "2", // Day of the month without leading zeros 1 to 31
// week
"D", "Mon", // A textual representation of a day, three letters Mon through Sun
"l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
// time
"g", "3", // 12-hour format of an hour without leading zeros 1 through 12
"G", "15", // 24-hour format of an hour without leading zeros 0 through 23
"h", "03", // 12-hour format of an hour with leading zeros 01 through 12
"H", "15", // 24-hour format of an hour with leading zeros 00 through 23
"a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
"A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
"i", "04", // Minutes with leading zeros 00 to 59
"s", "05", // Seconds, with leading zeros 00 through 59
// time zone
"T", "MST",
"P", "-07:00",
"O", "-0700",
// RFC 2822
"r", time.RFC1123Z,
}
// 本日起始时间
func TodayTime() time.Time {
return TimeDayBegin(time.Now())
}
// 本周起始时间
func WeekTime() time.Time {
return TimeWeekBegin(TodayTime())
}
// 本周结束时间
func WeekEndTime() time.Time {
return TimeWeekEnd(TodayTime())
}
// 本月起始时间
func MonthTime() time.Time {
return TimeMonthBegin(TodayTime())
}
// UnixToTime 将时间戳转为time
func UnixToTime(sec int64) time.Time {
return time.Unix(sec, 0)
}
// Datetime 将时间戳转为字符串日期
func Datetime(sec int64, format ...string) string {
var ft string
if len(format) > 0 {
ft = format[0]
} else {
ft = "Y-m-d H:i:s"
}
return TimeFormat(time.Unix(sec, 0), ft)
}
// StrToUnix 将日期字符串转为时间戳
func StrToUnix(datetime string, format ...string) int64 {
var ft string
if len(format) > 0 {
ft = format[0]
} else {
ft = "Y-m-d H:i:s"
}
t, err := StrToTime(datetime, ft)
if err != nil {
return 0
}
return t.Unix()
}
// StrToTime 将日期字符串转为时间对象
func StrToTime(datetime, format string) (time.Time, error) {
replacer := strings.NewReplacer(datePatterns...)
format = replacer.Replace(format)
return time.ParseInLocation(format, datetime, time.Local)
}
// TimeFormat 格式化时间戳为字符串时间
func TimeFormat(t time.Time, format string) string {
replacer := strings.NewReplacer(datePatterns...)
format = replacer.Replace(format)
return t.Format(format)
}
// FormatDate 输出time对象的日期字符串
func FormatDate(t time.Time) string {
return TimeFormat(t, "Y-m-d")
}
// FormatTime 输出time对象的时间字符串
func FormatTime(t time.Time) string {
return TimeFormat(t, "H:i:s")
}
// FormatDatetime 输出time对象的日期时间字符串
func FormatDatetime(t time.Time) string {
return TimeFormat(t, "Y-m-d H:i:s")
}
// TimeUnix 获取当前时区的系统时间戳
func TimeUnix() int64 {
return time.Now().Unix()
}
// TimeUnixNano 获取纳秒时间戳
func TimeUnixNano() int64 {
return time.Now().UnixNano()
}
// TimeUnixNano 获取毫秒时间戳
func TimeUnixMill() int64 {
return TimeUnixNano() / 1e6
}
// DiffDays 获取两个时间相隔天数
func DiffDays(to, from time.Time) int {
return int(to.Sub(from).Hours()) / 24
}
// IsSameDay 是否同年同月同日
func IsSameDay(t1, t2 time.Time) bool {
return IsSameYear(t1, t2) && t1.YearDay() == t2.YearDay()
}
// IsSameMonth 是否同年同月
func IsSameMonth(t1, t2 time.Time) bool {
return IsSameYear(t1, t2) && t1.Month() == t2.Month()
}
// IsSameDay 是否同年
func IsSameYear(t1, t2 time.Time) bool {
return t1.Year() == t2.Year()
}
// 取一天的起始时间(当天的00:00:00)
func TimeDayBegin(t time.Time) time.Time {
r := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
return r
}
// 取一天的特定hour小时的时间(当天的HH:00:00)
func TimeDayHour(t time.Time, hour int) time.Time {
r := time.Date(t.Year(), t.Month(), t.Day(), hour, 0, 0, 0, time.Local)
return r
}
// 取一周的起始时间(当周的周一)
func TimeWeekBegin(t time.Time) time.Time {
wDay := int(t.Weekday())
// sunday
if wDay == 0 {
wDay = 7
}
wDay--
r := t.AddDate(0, 0, -wDay)
return r
}
func TimeWeekEnd(t time.Time) time.Time {
cur := int(t.Weekday())
// sunday
if cur == 0 {
cur = 7
}
cur--
r := t.AddDate(0, 0, 7-cur)
return r
}
// 取一月的起始时间(当月1日)
func TimeMonthBegin(t time.Time) time.Time {
r := t.AddDate(0, 0, -t.Day()+1)
return r
}
// 取当月最后一天(当月1日)
func TimeMonthEnd(t time.Time) time.Time {
r := t.AddDate(0, 1, -t.Day())
return r
}
// 取指定月的第X个周Y日期
func TimeFindWeekDay(t time.Time, whichWeek int, whichWDay time.Weekday) time.Time {
if whichWeek < 1 {
return time.Now()
}
// 当月第一天
firstOfMonth := TimeMonthBegin(t)
firstOfWDay := firstOfMonth.Weekday()
offsetDay := int(whichWDay - firstOfWDay)
if offsetDay < 0 {
// 差了一轮,补一周天数
offsetDay += 7
}
destTime := firstOfMonth.AddDate(0, 0, offsetDay+(whichWeek-1)*7)
return destTime
}
// 取指定月的倒数第X个周Y日期
func TimeRFindWeekDay(t time.Time, whichWeek int, whichWDay time.Weekday) time.Time {
if whichWeek < 1 {
return time.Now()
}
// 当月最后一天
endOfMonth := TimeMonthEnd(t)
endOfWDay := endOfMonth.Weekday()
offsetDay := int(endOfWDay - whichWDay)
if offsetDay < 0 {
// 差了一轮,补一周天数
offsetDay += 7
}
destTime := endOfMonth.AddDate(0, 0, -(offsetDay + (whichWeek-1)*7))
return destTime
}
// 时间戳转字符串切片[YYYY,MM,DD,hh,mm,ss]
func TimeToStrSlice(u int64) []string {
t := time.Unix(u, 0)
timeArgs := make([]string, 6)
timeArgs[0] = strconv.Itoa(t.Year())
timeArgs[1] = strconv.Itoa(int(t.Month()))
timeArgs[2] = strconv.Itoa(t.Day())
timeArgs[3] = strconv.Itoa(t.Hour())
timeArgs[4] = strconv.Itoa(t.Minute())
timeArgs[5] = strconv.Itoa(t.Second())
return timeArgs
}
// 时间戳转成剩余多少分钟,结果向上取整
func TimeToMinute(u int64) int64 {
return int64(math.Ceil(float64(u) / float64(60)))
}
//获取传入的时间所在月份的第一天,即某月第一天的0点。如传入time.Now(), 返回当前月份的第一天0点时间。
func GetFirstDateOfMonth(d time.Time) time.Time {
d = d.AddDate(0, 0, -d.Day()+1)
return GetZeroTime(d)
}
//获取传入的时间所在月份的最后一天,即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。
func GetLastDateOfMonth(d time.Time) time.Time {
return GetFirstDateOfMonth(d).AddDate(0, 1, -1)
}
//获取某一天的0点时间
func GetZeroTime(d time.Time) time.Time {
return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
} | utils/tool/time.go | 0.516352 | 0.55911 | time.go | starcoder |
package geojson
import (
"encoding/binary"
"math"
"strconv"
"unsafe"
"github.com/tidwall/gjson"
"github.com/quesurifn/tile38/pkg/geojson/geo"
"github.com/quesurifn/tile38/pkg/geojson/poly"
)
const sizeofPosition = 24 // (X,Y,Z) * 8
// Position is a simple point
type Position poly.Point
func pointPositions(positions []Position) []poly.Point {
return *(*[]poly.Point)(unsafe.Pointer(&positions))
}
func polyPositions(positions []Position) poly.Polygon {
return *(*poly.Polygon)(unsafe.Pointer(&positions))
}
func polyMultiPositions(positions [][]Position) []poly.Polygon {
return *(*[]poly.Polygon)(unsafe.Pointer(&positions))
}
func polyExteriorHoles(positions [][]Position) (exterior poly.Polygon, holes []poly.Polygon) {
switch len(positions) {
case 0:
case 1:
exterior = polyPositions(positions[0])
default:
exterior = polyPositions(positions[0])
holes = polyMultiPositions(positions[1:])
}
return
}
func appendPositionJSON(json []byte, p Position, isCordZ bool) []byte {
json = strconv.AppendFloat(json, p.X, 'f', -1, 64)
json = append(json, ',')
json = strconv.AppendFloat(json, p.Y, 'f', -1, 64)
if isCordZ {
json = append(json, ',')
json = strconv.AppendFloat(json, p.Z, 'f', -1, 64)
}
return json
}
const earthRadius = 6371e3
func toRadians(deg float64) float64 { return deg * math.Pi / 180 }
func toDegrees(rad float64) float64 { return rad * 180 / math.Pi }
// DistanceTo calculates the distance to a position
func (p Position) DistanceTo(position Position) float64 {
return geo.DistanceTo(p.Y, p.X, position.Y, position.X)
}
// Destination calculates a new position based on the distance and bearing.
func (p Position) Destination(meters, bearingDegrees float64) Position {
lat, lon := geo.DestinationPoint(p.Y, p.X, meters, bearingDegrees)
return Position{X: lon, Y: lat, Z: 0}
}
func fillPosition(coords gjson.Result) (Position, error) {
var p Position
v := coords.Array()
switch len(v) {
case 0:
return p, errInvalidNumberOfPositionValues
case 1:
if v[0].Type != gjson.Number {
return p, errInvalidPositionValue
}
return p, errInvalidNumberOfPositionValues
}
for i := 0; i < len(v); i++ {
if v[i].Type != gjson.Number {
return p, errInvalidPositionValue
}
}
p.X = v[0].Float()
p.Y = v[1].Float()
if len(v) > 2 {
p.Z = v[2].Float()
} else {
p.Z = nilz
}
return p, nil
}
func fillPositionBytes(b []byte, isCordZ bool) (Position, []byte, error) {
var p Position
if len(b) < 8 {
return p, b, errNotEnoughData
}
p.X = math.Float64frombits(binary.LittleEndian.Uint64(b))
b = b[8:]
if len(b) < 8 {
return p, b, errNotEnoughData
}
p.Y = math.Float64frombits(binary.LittleEndian.Uint64(b))
b = b[8:]
if isCordZ {
if len(b) < 8 {
return p, b, errNotEnoughData
}
p.Z = math.Float64frombits(binary.LittleEndian.Uint64(b))
b = b[8:]
} else {
p.Z = nilz
}
return p, b, nil
}
// ExternalJSON is the simple json representation of the position used for external applications.
func (p Position) ExternalJSON() string {
if p.Z != 0 {
return `{"lat":` + strconv.FormatFloat(p.Y, 'f', -1, 64) + `,"lon":` + strconv.FormatFloat(p.X, 'f', -1, 64) + `,"z":` + strconv.FormatFloat(p.Z, 'f', -1, 64) + `}`
}
return `{"lat":` + strconv.FormatFloat(p.Y, 'f', -1, 64) + `,"lon":` + strconv.FormatFloat(p.X, 'f', -1, 64) + `}`
} | pkg/geojson/position.go | 0.701713 | 0.483039 | position.go | starcoder |
package fp
func (a BoolOption) Equals(b BoolOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return BoolEquals(Bool(*a.value), Bool(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a StringOption) Equals(b StringOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return StringEquals(String(*a.value), String(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a IntOption) Equals(b IntOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return IntEquals(Int(*a.value), Int(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Int64Option) Equals(b Int64Option) bool {
if a.IsDefined() {
if b.IsDefined() {
return Int64Equals(Int64(*a.value), Int64(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a ByteOption) Equals(b ByteOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return ByteEquals(Byte(*a.value), Byte(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a RuneOption) Equals(b RuneOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return RuneEquals(Rune(*a.value), Rune(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float32Option) Equals(b Float32Option) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float32Equals(Float32(*a.value), Float32(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float64Option) Equals(b Float64Option) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float64Equals(Float64(*a.value), Float64(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a AnyOption) Equals(b AnyOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return AnyEquals(Any(*a.value), Any(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Tuple2Option) Equals(b Tuple2Option) bool {
if a.IsDefined() {
if b.IsDefined() {
return Tuple2Equals(Tuple2(*a.value), Tuple2(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a BoolOptionOption) Equals(b BoolOptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return BoolOptionEquals(BoolOption(*a.value), BoolOption(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a StringOptionOption) Equals(b StringOptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return StringOptionEquals(StringOption(*a.value), StringOption(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a IntOptionOption) Equals(b IntOptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return IntOptionEquals(IntOption(*a.value), IntOption(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Int64OptionOption) Equals(b Int64OptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Int64OptionEquals(Int64Option(*a.value), Int64Option(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a ByteOptionOption) Equals(b ByteOptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return ByteOptionEquals(ByteOption(*a.value), ByteOption(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a RuneOptionOption) Equals(b RuneOptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return RuneOptionEquals(RuneOption(*a.value), RuneOption(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float32OptionOption) Equals(b Float32OptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float32OptionEquals(Float32Option(*a.value), Float32Option(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float64OptionOption) Equals(b Float64OptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float64OptionEquals(Float64Option(*a.value), Float64Option(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a AnyOptionOption) Equals(b AnyOptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return AnyOptionEquals(AnyOption(*a.value), AnyOption(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Tuple2OptionOption) Equals(b Tuple2OptionOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Tuple2OptionEquals(Tuple2Option(*a.value), Tuple2Option(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a BoolArrayOption) Equals(b BoolArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return BoolArrayEquals(BoolArray(*a.value), BoolArray(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a StringArrayOption) Equals(b StringArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return StringArrayEquals(StringArray(*a.value), StringArray(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a IntArrayOption) Equals(b IntArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return IntArrayEquals(IntArray(*a.value), IntArray(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Int64ArrayOption) Equals(b Int64ArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Int64ArrayEquals(Int64Array(*a.value), Int64Array(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a ByteArrayOption) Equals(b ByteArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return ByteArrayEquals(ByteArray(*a.value), ByteArray(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a RuneArrayOption) Equals(b RuneArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return RuneArrayEquals(RuneArray(*a.value), RuneArray(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float32ArrayOption) Equals(b Float32ArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float32ArrayEquals(Float32Array(*a.value), Float32Array(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float64ArrayOption) Equals(b Float64ArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float64ArrayEquals(Float64Array(*a.value), Float64Array(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a AnyArrayOption) Equals(b AnyArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return AnyArrayEquals(AnyArray(*a.value), AnyArray(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Tuple2ArrayOption) Equals(b Tuple2ArrayOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Tuple2ArrayEquals(Tuple2Array(*a.value), Tuple2Array(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a BoolListOption) Equals(b BoolListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return BoolListEquals(BoolList(*a.value), BoolList(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a StringListOption) Equals(b StringListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return StringListEquals(StringList(*a.value), StringList(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a IntListOption) Equals(b IntListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return IntListEquals(IntList(*a.value), IntList(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Int64ListOption) Equals(b Int64ListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Int64ListEquals(Int64List(*a.value), Int64List(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a ByteListOption) Equals(b ByteListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return ByteListEquals(ByteList(*a.value), ByteList(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a RuneListOption) Equals(b RuneListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return RuneListEquals(RuneList(*a.value), RuneList(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float32ListOption) Equals(b Float32ListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float32ListEquals(Float32List(*a.value), Float32List(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Float64ListOption) Equals(b Float64ListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Float64ListEquals(Float64List(*a.value), Float64List(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a AnyListOption) Equals(b AnyListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return AnyListEquals(AnyList(*a.value), AnyList(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } }
func (a Tuple2ListOption) Equals(b Tuple2ListOption) bool {
if a.IsDefined() {
if b.IsDefined() {
return Tuple2ListEquals(Tuple2List(*a.value), Tuple2List(*b.value))
} else { return false}
} else if b.IsDefined() { return false } else { return true } } | fp/bootstrap_option_equals.go | 0.669096 | 0.424173 | bootstrap_option_equals.go | starcoder |
package utils
import (
"fmt"
"reflect"
"github.com/Applifier/go-tensorflow/internal/typeconv"
"github.com/Applifier/go-tensorflow/types/tensorflow/core/example"
)
// An Example is a mostly-normalized data format for storing data for
// training and inference. It contains a key-value store (features); where
// each key (string) maps to a Feature message (which is oneof packed BytesList,
// FloatList, or Int64List).
type Example = example.Example
// Feature contains Lists which may hold zero or more values.
type Feature = example.Feature
// NewExampleFromMap returns a new Example based on a given map of go values
func NewExampleFromMap(m map[string]interface{}) (*Example, error) {
featureMap := make(map[string]*example.Feature, len(m))
example := &Example{
Features: &example.Features{
Feature: featureMap,
},
}
for name, val := range m {
f, err := NewFeature(val)
if err != nil {
return nil, err
}
featureMap[name] = f
}
return example, nil
}
// NewFeature returns a Feature from a given go value
func NewFeature(val interface{}) (*Feature, error) {
switch v := val.(type) {
case []byte:
return &Feature{
Kind: &example.Feature_BytesList{
BytesList: &example.BytesList{
Value: [][]byte{v},
},
},
}, nil
case [][]byte:
return &Feature{
Kind: &example.Feature_BytesList{
BytesList: &example.BytesList{
Value: v,
},
},
}, nil
case string:
return &Feature{
Kind: &example.Feature_BytesList{
BytesList: &example.BytesList{
Value: [][]byte{[]byte(v)},
},
},
}, nil
case []string:
byteSliceSlice := make([][]byte, 0, len(v))
for _, str := range v {
byteSliceSlice = append(byteSliceSlice, []byte(str))
}
return NewFeature(byteSliceSlice)
case float64:
return &Feature{
Kind: &example.Feature_FloatList{
FloatList: &example.FloatList{
Value: []float32{float32(v)},
},
},
}, nil
case []float64:
vals := make([]float32, len(v))
for i, f64Val := range v {
vals[i] = float32(f64Val)
// TODO trough error if truncated
}
return &Feature{
Kind: &example.Feature_FloatList{
FloatList: &example.FloatList{
Value: vals,
},
},
}, nil
case float32:
return &Feature{
Kind: &example.Feature_FloatList{
FloatList: &example.FloatList{
Value: []float32{v},
},
},
}, nil
case []float32:
return &Feature{
Kind: &example.Feature_FloatList{
FloatList: &example.FloatList{
Value: v,
},
},
}, nil
case int64:
return &Feature{
Kind: &example.Feature_Int64List{
Int64List: &example.Int64List{
Value: []int64{v},
},
},
}, nil
case []int64:
return &Feature{
Kind: &example.Feature_Int64List{
Int64List: &example.Int64List{
Value: v,
},
},
}, nil
case int32:
return &Feature{
Kind: &example.Feature_Int64List{
Int64List: &example.Int64List{
Value: []int64{int64(v)},
},
},
}, nil
case []int32:
vals := make([]int64, len(v))
for i, i64Val := range v {
vals[i] = int64(i64Val)
}
return &Feature{
Kind: &example.Feature_Int64List{
Int64List: &example.Int64List{
Value: vals,
},
},
}, nil
case bool:
if v {
return NewFeature(int64(1))
}
return NewFeature(int64(0))
case []bool:
vals := make([]int64, len(v))
for i, bVal := range v {
if bVal {
vals[i] = 1
} else {
vals[i] = 0
}
}
return NewFeature(vals)
case map[string]interface{}:
ex, err := NewExampleFromMap(v)
if err != nil {
return nil, err
}
b, err := ex.Marshal()
if err != nil {
return nil, err
}
return &Feature{
Kind: &example.Feature_BytesList{
BytesList: &example.BytesList{
Value: [][]byte{b},
},
},
}, nil
case []map[string]interface{}:
values := make([][]byte, len(v))
for i, m := range v {
ex, err := NewExampleFromMap(m)
if err != nil {
return nil, err
}
b, err := ex.Marshal()
if err != nil {
return nil, err
}
values[i] = b
}
return &Feature{
Kind: &example.Feature_BytesList{
BytesList: &example.BytesList{
Value: values,
},
},
}, nil
case []interface{}:
arr, err := typeconv.ConvertInterfaceSliceToTypedSlice(v)
if err != nil {
return nil, err
}
return NewFeature(arr)
default:
return nil, fmt.Errorf("unsupported type %v", reflect.TypeOf(val))
}
} | utils/example.go | 0.601008 | 0.506774 | example.go | starcoder |
package quadtree
import "math"
// Undilate deinterleaves word using shift-or algorithm.
func Undilate(x uint32) uint32 {
x = (x | (x >> 1)) & 0x33333333
x = (x | (x >> 2)) & 0x0F0F0F0F
x = (x | (x >> 4)) & 0x00FF00FF
x = (x | (x >> 8)) & 0x0000FFFF
return (x & 0x0000FFFF)
}
// Decode retrieves column major position and level from word.
func Decode(key uint32) (x, y, level uint32) {
x = Undilate((key >> 4) & 0x05555555)
y = Undilate((key >> 5) & 0x55555555)
level = key & 0xF
return
}
// Children generates nodes from a quadtree encoded word.
func Children(key uint32) (uint32, uint32, uint32, uint32) {
key = ((key + 1) & 0xF) | ((key & 0xFFFFFFF0) << 2)
return key, key | 0x10, key | 0x20, key | 0x30
}
// Parent generates node from quadtree encoded word.
func Parent(key uint32) uint32 {
return ((key - 1) & 0xF) | ((key >> 2) & 0x3FFFFFF0)
}
// IsUpperLeft determines if node represents the upper-left child of its parent.
func IsUpperLeft(key uint32) bool {
return ((key & 0x30) == 0x00)
}
// IsUpperRight determines if node represents the upper-right child of its parent.
func IsUpperRight(key uint32) bool {
return ((key & 0x30) == 0x10)
}
// IsLowerLeft determines if node represents the lower-left child of its parent.
func IsLowerLeft(key uint32) bool {
return ((key & 0x30) == 0x20)
}
// IsLowerRight determines if node represents the lower-right child of its parent.
func IsLowerRight(key uint32) bool {
return ((key & 0x30) == 0x30)
}
// Cell retrieves normalized coordinates and size.
func Cell(key uint32) (nx, ny, size float32) {
x, y, level := Decode(key)
size = 1 / float32(uint32(1<<level))
nx = float32(x) * size
ny = float32(y) * size
return
}
// Cap calculates the required capacity to hold all nodes of a given level.
func Cap(lvl int) int {
return int(math.Pow(4, float64(lvl)))
}
// Split recursively collects children at the given level into nodes pointer.
func Split(key uint32, lvl int, nodes *[]uint32) {
if key&0xF == uint32(lvl) {
*nodes = append(*nodes, key)
} else {
a, b, c, d := Children(key)
Split(a, lvl, nodes)
Split(b, lvl, nodes)
Split(c, lvl, nodes)
Split(d, lvl, nodes)
}
}
// ProjectMercator converts normalized coordinates to mercator projection, just for fun.
func ProjectMercator(nx, ny float32, radius float32) (x, y, z float32) {
nx = math.Pi / 4 * (2*nx - 1)
ny = math.Pi / 4 * (4*ny + 1)
x = radius * cos(ny) * cos(nx)
y = radius * cos(ny) * sin(nx)
z = radius * sin(ny)
return
}
func cos(x float32) float32 { return float32(math.Cos(float64(x))) }
func sin(x float32) float32 { return float32(math.Sin(float64(x))) } | quadtree/quadtree.go | 0.847684 | 0.765133 | quadtree.go | starcoder |
package fmts
import "github.com/google/gapid/core/stream"
var (
RGBA_U4_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U4,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U4,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U4,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U4,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U5U5U5U1_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U5,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U5,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U5,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U1,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U8 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U8,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U8,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U8,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U8,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S8 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S8,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S8,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S8,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S8,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U8_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S8_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
SRGBA_U8_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U8,
Sampling: stream.SRGBNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U8,
Sampling: stream.SRGBNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U8,
Sampling: stream.SRGBNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U10U10U10U2_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U10,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U10,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U10,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U2,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U10U10U10U2 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U10,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U10,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U10,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U2,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S10S10S10S2_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S10,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S10,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S10,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S2,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S10S10S10S2 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S10,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S10,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S10,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S2,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_sRGBU8N_sRGBU8N_sRGBU8_NU8N = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U8,
Sampling: stream.SRGBNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U8,
Sampling: stream.SRGBNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U8,
Sampling: stream.SRGBNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U8,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U16 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U16,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U16,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U16,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U16,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S16 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S16,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S16,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S16,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S16,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U16_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S16_NORM = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S16,
Sampling: stream.LinearNormalized,
Channel: stream.Channel_Alpha,
}},
}
RGBA_F16 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.F16,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.F16,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.F16,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.F16,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U32 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U32,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U32,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U32,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U32,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S32 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S32,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S32,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S32,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S32,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_F32 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.F32,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.F32,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.F32,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.F32,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_U64 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.U64,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.U64,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.U64,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.U64,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_S64 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.S64,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.S64,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.S64,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.S64,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
RGBA_F64 = &stream.Format{
Components: []*stream.Component{{
DataType: &stream.F64,
Sampling: stream.Linear,
Channel: stream.Channel_Red,
}, {
DataType: &stream.F64,
Sampling: stream.Linear,
Channel: stream.Channel_Green,
}, {
DataType: &stream.F64,
Sampling: stream.Linear,
Channel: stream.Channel_Blue,
}, {
DataType: &stream.F64,
Sampling: stream.Linear,
Channel: stream.Channel_Alpha,
}},
}
) | core/stream/fmts/rgba.go | 0.541651 | 0.452536 | rgba.go | starcoder |
package main
import (
"fmt"
"math"
)
// d = x^y
// p(n;d) ~ 1-((d-1)/d)^n(n-1)/2
// p(n;d) is the probability that at least two numbers are the same.
func collisionP(n, x, y float64) (p float64, d float64, err error) {
errPrefix := "can't calculate the probability of at least 2 elements colliding"
if n <= 0 {
return 0, 0, fmt.Errorf("%s: n must be > 0", errPrefix)
}
if x <= 0 {
return 0, 0, fmt.Errorf("%s: base must be > 0", errPrefix)
}
if y == 0 {
return 0, 0, fmt.Errorf("%s: if the base is to be used as the upper-end of the range, use 1 as the value of the exponent", errPrefix)
}
d = math.Pow(x, y)
return 1.0 - math.Pow(((d-1.0)/d), (n*(n-1.0))/2.0), d, nil
}
// d = x^y
// n(p;d) ~ SQRT(2d * ln(1/(1-p)))
// n(p;d) is the number of random integers drawn from [1,d] to obtain the
// probility that at least 2 numbers are the same.
func collisionN(p, x, y float64) (n int64, d float64, err error) {
errPrefix := "can't calculate the number of elements required to obtain the probability that at least 2 elements are the same"
if p <= 0 {
return 0, 0, fmt.Errorf("%s: p must be > 0", errPrefix)
}
if x <= 0.0 {
return 0, 0, fmt.Errorf("%s: base must be > 0", errPrefix)
}
if y == 0.0 {
return 0, 0, fmt.Errorf("%s: if the base is to be used as the upper-end of the range, use 1 as the value of the exponent", errPrefix)
}
d = math.Pow(x, y)
// We add 1 because int conversion truncates and if there is a decimal portion
// it should be the next greater int as minimum n is a whole number.
return int64(math.Sqrt(2*d*(math.Log((1 / (1 - p))))) + 1.0), d, nil
}
// https://math.dartmouth.edu/archive/m19w03/public_html/Section6-5.pdf
// Theorem 6.15
//In hashing n items into a hash table with k locations, the expected number
// of collisions is: n − k + k(1 − 1/k)^n
func nCollisions(n, x, y float64) (c, d float64, err error) {
errPrefix := "can't calculate the expected number of collisions when hashing n items into d slots"
if n <= 0 {
return 0, 0, fmt.Errorf("%s: n must be > 0", errPrefix)
}
if x <= 0 {
return 0, 0, fmt.Errorf("%s: base must be > 0", errPrefix)
}
if y == 0 {
return 0, 0, fmt.Errorf("%s: if the base is to be used as the number of slots, use 1 as the value of the exponent", errPrefix)
}
d = math.Pow(x, y)
return n - d + (d * math.Pow(1-(1.0/d), n)), d, nil
} | bday.go | 0.652684 | 0.511412 | bday.go | starcoder |
package gohome
import (
"github.com/PucklaMotzer09/mathgl/mgl32"
)
// The different parts of a shader
const (
VERTEX uint8 = 0
FRAGMENT uint8 = 1
GEOMETRY uint8 = 2
TESSELLETION uint8 = 3
EVELUATION uint8 = 4
COMPUTE uint8 = 5
)
// A shader controls how a mesh is rendered
type Shader interface {
// Adds a shader of shader_type with its source code to this shader
AddShader(shader_type uint8, src string) error
// Links all shaders
Link() error
// Sets all values up
Setup() error
// Cleans everything up
Terminate()
// Use this shader for the following draw calls
Use()
// Don't use this shader anymore
Unuse()
// Sets the value of a uniform Vec2
SetUniformV2(name string, value mgl32.Vec2)
// Sets the value of a uniform Vec3
SetUniformV3(name string, value mgl32.Vec3)
// Sets the value of a uniform Vec4
SetUniformV4(name string, value mgl32.Vec4)
// Sets the value of a uniform ivec2
SetUniformIV2(name string, value []int32)
// Sets the value of a uniform ivec3
SetUniformIV3(name string, value []int32)
// Sets the value of a uniform ivec4
SetUniformIV4(name string, value []int32)
// Sets the value of a uniform float
SetUniformF(name string, value float32)
// Sets the value of a uniform int
SetUniformI(name string, value int32)
// Sets the value of a uniform unsigned int
SetUniformUI(name string, value uint32)
// Sets the value of a uniform bool
SetUniformB(name string, value uint8)
// Sets the value of a uniform Mat2
SetUniformM2(name string, value mgl32.Mat2)
// Sets the value of a uniform Mat3
SetUniformM3(name string, value mgl32.Mat3)
// Sets the value of a uniform Mat4
SetUniformM4(name string, value mgl32.Mat4)
// Sets the value of a uniform material
SetUniformMaterial(mat Material)
// Sets the value of all uniforms of lights
SetUniformLights(lightCollectionIndex int)
// Returns the name of this shader
GetName() string
// Adds a vertex attribute
AddAttribute(name string, location uint32)
}
// An implementation of Shader that does nothing
type NilShader struct {
}
func (*NilShader) AddShader(shader_type uint8, src string) error {
return nil
}
func (*NilShader) Link() error {
return nil
}
func (*NilShader) Setup() error {
return nil
}
func (*NilShader) Terminate() {
}
func (*NilShader) Use() {
}
func (*NilShader) Unuse() {
}
func (*NilShader) SetUniformV2(name string, value mgl32.Vec2) {
}
func (*NilShader) SetUniformV3(name string, value mgl32.Vec3) {
}
func (*NilShader) SetUniformV4(name string, value mgl32.Vec4) {
}
func (*NilShader) SetUniformIV2(name string, value []int32) {
}
func (*NilShader) SetUniformIV3(name string, value []int32) {
}
func (*NilShader) SetUniformIV4(name string, value []int32) {
}
func (*NilShader) SetUniformF(name string, value float32) {
}
func (*NilShader) SetUniformI(name string, value int32) {
}
func (*NilShader) SetUniformUI(name string, value uint32) {
}
func (*NilShader) SetUniformB(name string, value uint8) {
}
func (*NilShader) SetUniformM2(name string, value mgl32.Mat2) {
}
func (*NilShader) SetUniformM3(name string, value mgl32.Mat3) {
}
func (*NilShader) SetUniformM4(name string, value mgl32.Mat4) {
}
func (*NilShader) SetUniformMaterial(mat Material) {
}
func (*NilShader) SetUniformLights(lightCollectionIndex int) {
}
func (*NilShader) GetName() string {
return ""
}
func (*NilShader) AddAttribute(name string, location uint32) {
} | src/gohome/shader.go | 0.713631 | 0.474266 | shader.go | starcoder |
package assert
import (
"reflect"
"github.com/google/gapid/core/data/compare"
)
// OnMap is the result of calling ThatMap on an Assertion.
// It provides assertion tests that are specific to map types.
type OnMap struct {
Assertion
mp interface{}
}
// ThatMap returns an OnMap for assertions on map type objects.
// Calling this with a non map type will result in panics.
func (a Assertion) ThatMap(mp interface{}) OnMap {
return OnMap{Assertion: a, mp: mp}
}
// IsEmpty asserts that the map was of length 0
func (o OnMap) IsEmpty() bool {
value := reflect.ValueOf(o.mp)
return o.CompareRaw(value.Len(), "is", "empty").Test(value.Len() == 0)
}
// IsNotEmpty asserts that the map has elements
func (o OnMap) IsNotEmpty() bool {
value := reflect.ValueOf(o.mp)
return o.Compare(value.Len(), "length >", 0).Test(value.Len() > 0)
}
// IsLength asserts that the map has exactly the specified number of elements
func (o OnMap) IsLength(length int) bool {
value := reflect.ValueOf(o.mp)
return o.Compare(value.Len(), "length ==", length).Test(value.Len() == length)
}
// Equals asserts the array or map matches expected.
func (o OnMap) Equals(expected interface{}) bool {
return o.mapsEqual(expected, func(a, b interface{}) bool { return a == b })
}
// EqualsWithComparator asserts the array or map matches expected using a comparator function
func (o OnMap) EqualsWithComparator(expected interface{}, same func(a, b interface{}) bool) bool {
return o.mapsEqual(expected, same)
}
// DeepEquals asserts the array or map matches expected using a deep-equal comparison.
func (o OnMap) DeepEquals(expected interface{}) bool {
return o.mapsEqual(expected, compare.DeepEqual)
}
func (o OnMap) mapsEqual(expected interface{}, same func(a, b interface{}) bool) bool {
return o.Test(func() bool {
gs := reflect.ValueOf(o.mp)
es := reflect.ValueOf(expected)
equal := true
for _, k := range gs.MapKeys() {
gv := gs.MapIndex(k)
ev := es.MapIndex(k)
if !ev.IsValid() {
o.Printf("\tExtra key: %#v\n", k.Interface())
equal = false
continue
}
if !same(gv.Interface(), ev.Interface()) {
o.Printf("\tKey: %#v, %#v differs from expected: %#v\n", k.Interface(), gv.Interface(), ev.Interface())
equal = false
}
}
for _, k := range es.MapKeys() {
if !gs.MapIndex(k).IsValid() {
o.Printf("\tKey missing: %#v\n", k.Interface())
equal = false
}
}
return equal
}())
} | core/assert/map.go | 0.725649 | 0.465813 | map.go | starcoder |
package chart
import (
"fmt"
)
// Interface Assertions.
var (
_ Series = (*LinearSeries)(nil)
_ FirstValuesProvider = (*LinearSeries)(nil)
_ LastValuesProvider = (*LinearSeries)(nil)
)
// LinearSeries is a series that plots a line in a given domain.
type LinearSeries struct {
Name string
Style Style
YAxis YAxisType
XValues []float64
InnerSeries LinearCoefficientProvider
m float64
b float64
stdev float64
avg float64
}
// GetName returns the name of the time series.
func (ls LinearSeries) GetName() string {
return ls.Name
}
// GetStyle returns the line style.
func (ls LinearSeries) GetStyle() Style {
return ls.Style
}
// GetYAxis returns which YAxis the series draws on.
func (ls LinearSeries) GetYAxis() YAxisType {
return ls.YAxis
}
// Len returns the number of elements in the series.
func (ls LinearSeries) Len() int {
return len(ls.XValues)
}
// GetEndIndex returns the effective limit end.
func (ls LinearSeries) GetEndIndex() int {
return len(ls.XValues) - 1
}
// GetValues gets a value at a given index.
func (ls *LinearSeries) GetValues(index int) (x, y float64) {
if ls.InnerSeries == nil || len(ls.XValues) == 0 {
return
}
if ls.IsZero() {
ls.computeCoefficients()
}
x = ls.XValues[index]
y = (ls.m * ls.normalize(x)) + ls.b
return
}
// GetFirstValues computes the first linear regression value.
func (ls *LinearSeries) GetFirstValues() (x, y float64) {
if ls.InnerSeries == nil || len(ls.XValues) == 0 {
return
}
if ls.IsZero() {
ls.computeCoefficients()
}
x, y = ls.GetValues(0)
return
}
// GetLastValues computes the last linear regression value.
func (ls *LinearSeries) GetLastValues() (x, y float64) {
if ls.InnerSeries == nil || len(ls.XValues) == 0 {
return
}
if ls.IsZero() {
ls.computeCoefficients()
}
x, y = ls.GetValues(ls.GetEndIndex())
return
}
// Render renders the series.
func (ls *LinearSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) {
Draw.LineSeries(r, canvasBox, xrange, yrange, ls.Style.InheritFrom(defaults), ls)
}
// Validate validates the series.
func (ls LinearSeries) Validate() error {
if ls.InnerSeries == nil {
return fmt.Errorf("linear regression series requires InnerSeries to be set")
}
return nil
}
// IsZero returns if the linear series has computed coefficients or not.
func (ls LinearSeries) IsZero() bool {
return ls.m == 0 && ls.b == 0
}
// computeCoefficients computes the `m` and `b` terms in the linear formula given by `y = mx+b`.
func (ls *LinearSeries) computeCoefficients() {
ls.m, ls.b, ls.stdev, ls.avg = ls.InnerSeries.Coefficients()
}
func (ls *LinearSeries) normalize(xvalue float64) float64 {
if ls.avg > 0 && ls.stdev > 0 {
return (xvalue - ls.avg) / ls.stdev
}
return xvalue
} | vendor/github.com/wcharczuk/go-chart/v2/linear_series.go | 0.844249 | 0.646544 | linear_series.go | starcoder |
* ============================================================================
* Usage:
* $ curl -sO http://rgolubtsov.github.io/srcs/find_equil_index.go && \
chmod 700 find_equil_index.go && \
./find_equil_index.go; echo $?
* ============================================================================
* This is a demo script. It has to be run as a Go script using the Go tool's
* runtime facility. Tested and known to run exactly the same way
* on modern versions of OpenBSD/amd64, Ubuntu Server LTS x86-64, Arch Linux /
* Arch Linux 32 operating systems.
*
* A zero-indexed array A consisting of N integers is given. An equilibrium
* index of this array is any integer P such that 0 <= P < N and the sum
* of elements of lower indices is equal to the sum of elements of higher
* indices, i.e.
*
* A[0] + A[1] + ... + A[P-1] = A[P+1] + ... + A[N-2] + A[N-1].
*
* Sum of zero elements is assumed to be equal to 0. This can happen if P = 0
* or if P = N-1.
*
* For example, consider the following array A consisting of N = 8 elements:
*
* A[0] = -1
* A[1] = 3
* A[2] = -4
* A[3] = 5
* A[4] = 1
* A[5] = -6
* A[6] = 2
* A[7] = 1
*
* P = 1 is an equilibrium index of this array, because:
*
* A[0] = -1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]
*
* P = 3 is an equilibrium index of this array, because:
*
* A[0] + A[1] + A[2] = -2 = A[4] + A[5] + A[6] + A[7]
*
* P = 7 is also an equilibrium index, because:
*
* A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0
*
* and there are no elements with indices greater than 7.
*
* P = 8 is not an equilibrium index, because it does not fulfill
* the condition 0 <= P < N.
*
* Write a function:
*
* function solution(A);
*
* that, given a zero-indexed array A consisting of N integers, returns any
* of its equilibrium indices. The function should return -1 if no equilibrium
* index exists.
*
* For example, given array A shown above, the function may return 1, 3 or 7,
* as explained above.
*
* Assume that:
*
* N is an integer within the range [0..100,000];
* each element of array A is an integer within the range
* [-2,147,483,648..2,147,483,647].
*
* Complexity:
*
* expected worst-case time complexity is O(N);
* expected worst-case space complexity is O(N), beyond input storage
* (not counting the storage required for input arguments).
*
* Elements of input arrays can be modified.
* ============================================================================
* Copyright (C) 2017-2021 <NAME>) Golubtsov
*
* (See the LICENSE file at the top of the source tree.)
*/
package main
import "fmt"
// Helper constants.
const (
NEW_LINE string = "\n"
EQUIL_INDEX_MSG string = "==> The equilibrium index of A is %d"
)
// The solution function.
func solution(A []int) int {
num_of_A := len(A)
sum_of_A := 0 // <== The complete sum of elements of A.
sum_of_A_1 := 0 // <== The sum of elements of lower indices of A.
sum_of_A_2 := 0 // <== The sum of elements of higher indices of A.
// Calculating the complete sum of elements of A.
for i := 0; i < num_of_A; i++ {
sum_of_A += A[i]
}
// Searching for the equilibrium index of A.
for i := 0; i < num_of_A; i++ {
sum_of_A_2 = sum_of_A - sum_of_A_1
sum_of_A_2 -= A[i]
fmt.Printf("==> sum_of_A_1: %d" +
" ==> sum_of_A_2: %d" +
" ==> i: %d" +
" ==> A[%d]: %d" +
NEW_LINE, sum_of_A_1, sum_of_A_2, i, i, A[i])
if (sum_of_A_1 == sum_of_A_2) {
return i // Okay, the equilibrium index found.
}
sum_of_A_1 += A[i]
}
return -1 // Returning -1 if there's no such an equilibrium index exists.
}
// The script entry point.
func main() {
A := []int{-1, 3, -4, 5, 1, -6, 2, 1}
i := solution(A)
fmt.Printf(NEW_LINE + EQUIL_INDEX_MSG + NEW_LINE + NEW_LINE, i)
}
// vim:set nu et ts=4 sw=4: | content/src/find_equil_index.go | 0.756088 | 0.602179 | find_equil_index.go | starcoder |
package format
import (
"strings"
"github.com/bvaudour/kcp/pkgbuild/atom"
"github.com/bvaudour/kcp/pkgbuild/standard"
)
//MapFunc is a function which apply
//transformations to a slice of atoms
//and returns the result of these transformations.
type MapFunc func(atom.Slice) atom.Slice
//Formatter is an interface
//which implements a transformation method
type Formatter interface {
Map(atom.Slice) atom.Slice
}
type StdFormatter int
const (
RemoveExtraSpaces StdFormatter = iota
RemoveBlankLinesExceptFirst
RemoveAllBlankLines
RemoveAdjacentDuplicateBlankLines
RemoveCommentLines
RemoveTrailingComments
RemoveVariableComments
RemoveDuplicateVariables
RemoveDuplicateFunctions
FormatValues
BeautifulValues
ReorderFuncsAndVars
AddBlankLineBeforeVariables
AddBlankLineBeforeFunctions
)
var mstd = map[StdFormatter]MapFunc{
RemoveExtraSpaces: func(in atom.Slice) (out atom.Slice) {
cb := func(a atom.Atom) atom.Atom {
switch a.GetType() {
case atom.Function:
a.(*atom.AtomFunc).FormatSpaces(true)
case atom.VarArray, atom.VarString:
a.(*atom.AtomVar).FormatSpaces(true)
case atom.Group:
a.(*atom.AtomGroup).FormatSpaces(true)
default:
raw := strings.TrimSpace(a.GetRaw())
a.SetRaw(raw)
atom.RecomputePosition(a)
}
return a
}
return in.Map(cb)
},
RemoveBlankLinesExceptFirst: func(in atom.Slice) (out atom.Slice) {
check := atom.NewMatcher(atom.Blank)
for i, a := range in {
if i == 0 || !check(a) {
out.Push(a)
}
}
return
},
RemoveAllBlankLines: func(in atom.Slice) (out atom.Slice) {
check := atom.NewRevMatcher(atom.Blank)
return in.Search(check)
},
RemoveAdjacentDuplicateBlankLines: func(in atom.Slice) (out atom.Slice) {
check := atom.NewMatcher(atom.Blank)
for i, a := range in {
if !(i > 0 && check(a) && check(in[i-1])) {
out.Push(a)
}
}
return
},
RemoveCommentLines: func(in atom.Slice) (out atom.Slice) {
check := atom.NewRevMatcher(atom.Comment)
return in.Search(check)
},
RemoveTrailingComments: func(in atom.Slice) (out atom.Slice) {
check := atom.NewMatcher(atom.Group)
cc := atom.NewMatcher(atom.Comment)
for _, a := range in {
if check(a) {
e := a.(*atom.AtomGroup)
last := len(e.Childs) - 1
for last >= 0 && cc(e.Childs[last]) {
e.Childs.Pop()
last--
}
if last < 0 {
continue
} else if last == 0 {
out.Push(e.Childs[0])
continue
}
}
out.Push(a)
}
return
},
RemoveVariableComments: func(in atom.Slice) (out atom.Slice) {
cb := func(a atom.Atom) {
if e, ok := a.(*atom.AtomVar); ok {
e.RemoveComments(true)
}
}
out = make(atom.Slice, len(in))
for i, a := range in {
if info, ok := atom.NewInfo(a); ok && info.IsVar() {
cb(info.AtomNamed)
}
out[i] = a
}
return
},
RemoveDuplicateVariables: func(in atom.Slice) (out atom.Slice) {
done := make(map[string]bool)
check := func(a atom.Atom) bool {
info, ok := atom.NewInfo(a)
if ok && info.IsVar() {
if name := info.Name(); done[name] {
return false
} else {
done[name] = true
}
}
return true
}
out = in.Search(check)
return
},
RemoveDuplicateFunctions: func(in atom.Slice) (out atom.Slice) {
done := make(map[string]bool)
check := func(a atom.Atom) bool {
info, ok := atom.NewInfo(a)
if ok && info.IsFunc() {
if name := info.Name(); done[name] {
return false
} else {
done[name] = true
}
}
return true
}
out = in.Search(check)
return
},
FormatValues: func(in atom.Slice) (out atom.Slice) {
cb := func(a atom.Atom) atom.Atom {
info, ok := atom.NewInfo(a)
if !ok {
return a
}
e, ok := info.Variable()
if !ok {
return a
}
name := info.Name()
qn := standard.IsQuotedVariable(name)
var t []atom.AtomType
if standard.IsStandardVariable(name) {
if standard.IsArrayVariable(name) {
t = append(t, atom.VarArray)
} else {
t = append(t, atom.VarString)
}
}
e.FormatVariables(true, qn, t...)
return a
}
out = in.Map(cb)
return
},
BeautifulValues: func(in atom.Slice) (out atom.Slice) {
cb := func(a atom.Atom) atom.Atom {
info, ok := atom.NewInfo(a)
if !ok {
return a
}
e, ok := info.Variable()
if !ok {
return a
}
name := info.Name()
qn := standard.IsQuotedVariable(name)
var t []atom.AtomType
if standard.IsStandardVariable(name) {
if standard.IsArrayVariable(name) {
t = append(t, atom.VarArray)
} else {
t = append(t, atom.VarString)
}
}
e.RemoveComments(false)
e.FormatVariables(false, qn, t...)
e.FormatSpaces(true)
return a
}
out = in.Map(cb)
return
},
ReorderFuncsAndVars: func(in atom.Slice) (out atom.Slice) {
var header, block atom.Slice
fo, vo := make(fOrder), make(vOrder)
for _, a := range in {
info, ok := atom.NewInfo(a)
if !ok {
block.Push(a)
continue
}
if len(header) == 0 && len(fo) == 0 && len(vo) == 0 {
header.Push(block...)
block = nil
}
block.Push(a)
name := info.Name()
if info.IsFunc() {
f := fo[name]
f.Push(block...)
fo[name] = f
} else {
v := vo[name]
vo[name] = append(v, newVBlock(info, block))
}
block = nil
}
out.Push(header...)
out.Push(vo.order()...)
out.Push(fo.order()...)
out.Push(block...)
return
},
AddBlankLineBeforeVariables: func(in atom.Slice) (out atom.Slice) {
cl := atom.NewMatcher(atom.Blank)
check := func(a atom.Atom) bool {
info, ok := atom.NewInfo(a)
return ok && info.IsVar()
}
for i, a := range in {
if i > 0 && !cl(in[i-1]) && check(a) {
out.Push(atom.NewBlank())
}
out.Push(a)
}
return
},
AddBlankLineBeforeFunctions: func(in atom.Slice) (out atom.Slice) {
cl := atom.NewMatcher(atom.Blank)
check := func(a atom.Atom) bool {
info, ok := atom.NewInfo(a)
return ok && info.IsFunc()
}
for i, a := range in {
if i > 0 && !cl(in[i-1]) && check(a) {
out.Push(atom.NewBlank())
}
out.Push(a)
}
return
},
}
func (f StdFormatter) Map(in atom.Slice) atom.Slice {
if cb, ok := mstd[f]; ok {
return cb(in)
}
return in
}
func Format(formats ...Formatter) MapFunc {
return func(atoms atom.Slice) atom.Slice {
for _, f := range formats {
atoms = f.Map(atoms)
}
return atoms
}
} | pkgbuild/format/format.go | 0.58747 | 0.458591 | format.go | starcoder |
package main
import (
"log"
"os"
"sort"
"strconv"
"github.com/TomasCruz/projecteuler"
)
/*
Distinct powers
Problem 29
Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
*/
func main() {
var limit int
if len(os.Args) > 1 {
limit64, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil {
log.Fatal("bad argument")
}
limit = int(limit64)
} else {
limit = 101
}
projecteuler.Timed(calc, limit)
}
func calc(args ...interface{}) (result string, err error) {
limit := args[0].(int)
factorizationSlice := make([]map[int]int, 0)
resultMap := make(map[int]map[int]struct{})
primes := projecteuler.Primes(limit, nil)
for a := 2; a < limit; a++ {
factA, _ := projecteuler.Factorize(a, primes)
currIndex, baseExponent := addFactorization(factA, &factorizationSlice)
if _, ok := resultMap[currIndex]; !ok {
resultMap[currIndex] = make(map[int]struct{})
}
for b := 2; b < limit; b++ {
resultMap[currIndex][b*baseExponent] = struct{}{}
}
}
sum := 0
for _, v := range resultMap {
sum += len(v)
}
result = strconv.Itoa(sum)
return
}
type intSlice []int
func (a intSlice) Len() int { return len(a) }
func (a intSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a intSlice) Swap(i, j int) { temp := a[i]; a[i], a[j] = a[j], temp }
func addFactorization(factors map[int]int, factorizationSlice *[]map[int]int) (index, baseExponent int) {
powers := make([]int, len(factors))
i := 0
for _, v := range factors {
powers[i] = v
i++
}
sort.Sort(intSlice(powers))
baseExponent = makePowersCoprime(powers)
if baseExponent != 1 {
for k, v := range factors {
factors[k] = v / baseExponent
}
}
for i := 0; i < len(*factorizationSlice); i++ {
if projecteuler.CompareFactors(factors, (*factorizationSlice)[i]) {
index = i
return
}
}
*factorizationSlice = append(*factorizationSlice, factors)
index = len(*factorizationSlice) - 1
return
}
func makePowersCoprime(powers []int) (baseExponent int) {
length := len(powers)
if length == 1 {
baseExponent = powers[0]
powers[0] = 1
return
}
baseExponent = 1
doBreak := false
for i := 2; i <= powers[length-1]; i++ {
var j int
for j = 0; j < length && powers[j]%i == 0; j++ {
}
if j == length {
baseExponent *= i
for k := 0; k < length; k++ {
powers[k] /= i
if powers[k] == 1 {
doBreak = true
}
}
if doBreak {
break
}
}
}
return
} | 001-100/021-030/029/main.go | 0.548674 | 0.414543 | main.go | starcoder |
package weathercloud
import (
"github.com/ebarkie/http/query"
"github.com/ebarkie/weatherlink/units"
)
// Wx represents weather observations.
type Wx struct {
query.Data
}
func tens(f float64) int {
return int(f * 10.0)
}
// Bar is atmospheric pressure in inches.
func (w *Wx) Bar(in float64) {
w.SetInt("bar", tens(units.Pressure(in*units.Inches).Hectopascals()))
}
// DailyRain is rain so far today (local time) in inches.
func (w *Wx) DailyRain(in float64) {
w.SetInt("rain", tens(units.Length(in*units.Inches).Millimeters()))
}
// DailyET is the evapotranspiration so far today (local time) in
// inches.
func (w *Wx) DailyET(in float64) {
w.SetInt("et", tens(units.Length(in*units.Inches).Millimeters()))
}
// DewPoint is the outdoor dew point in degrees Fahrenheit.
func (w *Wx) DewPoint(f float64) {
w.SetInt("dew", tens(units.Fahrenheit(f).Celsius()))
}
// HeatIndex is the outdoor heat index in degrees Fahrenheit.
func (w *Wx) HeatIndex(f float64) {
w.SetInt("heat", tens(units.Fahrenheit(f).Celsius()))
}
// InHumidity is the indoor humidity percentage (0-100).
func (w *Wx) InHumidity(p int) {
w.SetInt("humin", p)
}
// InTemp is the indoor temperature in degrees Fahrenheit.
func (w *Wx) InTemp(f float64) {
w.SetInt("tempin", tens(units.Fahrenheit(f).Celsius()))
}
// LeafWetness is the leaf wetness index.
func (w *Wx) LeafWetness(p int) {
w.SetIntf(query.Indexed{Format: "leafwet#", Begin: 1, Width: 2}, p)
}
// OutHumidity is the outdoor humidity percentage (0-100).
func (w *Wx) OutHumidity(p int) {
w.SetIntf(query.Indexed{Format: "hum#", Begin: 1, Zero: 1, Width: 2}, p)
}
// OutTemp is outdoor temperature in degrees Fahrenheit.
func (w *Wx) OutTemp(f float64) {
w.SetIntf(query.Indexed{Format: "temp#", Begin: 1, Zero: 1, Width: 2}, tens(units.Fahrenheit(f).Celsius()))
}
// RainRate is rain over the past hour or the accumulated
// rainfall for the past 60 minutes in inches.
func (w *Wx) RainRate(in float64) {
w.SetInt("rainrate", tens(units.Length(in*units.Inches).Millimeters()))
}
// SolarRad is solar radiation in watts per square meter.
func (w *Wx) SolarRad(wm2 int) {
w.SetInt("solarrad", wm2*10)
}
// SoilMoist is the soil moisture in centibars of tension.
func (w *Wx) SoilMoist(cb int) {
w.SetIntf(query.Indexed{Format: "soilmoist#", Begin: 1, Width: 2}, cb)
}
// UVIndex is the UltraViolet light index.
func (w *Wx) UVIndex(i float64) {
w.SetInt("uvi", tens(i))
}
// WindChill is the wind chill in degrees Fahrenheit.
func (w *Wx) WindChill(f float64) {
w.SetInt("chill", tens(units.Fahrenheit(f).Celsius()))
}
// WindDir is instantaneous wind direction in degrees (0-359).
func (w *Wx) WindDir(deg int) {
w.SetIntf(query.Indexed{Format: "wdir#", Begin: 1, Zero: 1, Width: 2}, deg)
}
// WindDirAvg is the 10 minute average wind direction in
// degrees (0-359).
func (w *Wx) WindDirAvg(deg int) {
w.SetIntf(query.Indexed{Format: "wdiravg#", Begin: 1, Zero: 1, Width: 2}, deg)
}
// WindGustSpeed is the 10 minute wind gust speed in miles per hour.
func (w *Wx) WindGustSpeed(mph float64) {
w.SetIntf(query.Indexed{Format: "wspdhi#", Begin: 1, Zero: 1, Width: 2}, tens(units.Speed(mph*units.MPH).MPS()))
}
// WindSpeed is the instantaneous wind speed in miles per hour.
func (w *Wx) WindSpeed(mph float64) {
w.SetIntf(query.Indexed{Format: "wspd#", Begin: 1, Zero: 1, Width: 2}, tens(units.Speed(mph*units.MPH).MPS()))
}
// WindSpeedAvg is the 10 minute average wind speed in miles
// per hour.
func (w *Wx) WindSpeedAvg(mph float64) {
w.SetIntf(query.Indexed{Format: "wspdavg#", Begin: 1, Zero: 1, Width: 2}, tens(units.Speed(mph*units.MPH).MPS()))
} | wx.go | 0.806586 | 0.646083 | wx.go | starcoder |
package samples
func init() {
sampleDataProposalCreateOperation[51] = `{
"expiration_time": "2016-09-19T23:18:14",
"extensions": [],
"fee": {
"amount": 2420020,
"asset_id": "1.3.0"
},
"fee_paying_account": "1.2.125573",
"proposed_ops": [
{
"op": [
6,
{
"account": "1.2.32567",
"active": {
"account_auths": [
[
"1.2.112930",
2
]
],
"address_auths": [],
"key_auths": [
[
"<KEY>",
1
]
],
"weight_threshold": 1
},
"extensions": {},
"fee": {
"amount": 43268,
"asset_id": "1.3.0"
},
"new_options": {
"extensions": [],
"memo_key": "<KEY>",
"num_committee": 10,
"num_witness": 23,
"votes": [
"1:22",
"1:23",
"1:24",
"1:25",
"1:26",
"1:27",
"1:28",
"1:30",
"1:31",
"1:32",
"1:34",
"1:35",
"1:36",
"1:37",
"1:38",
"1:40",
"1:44",
"1:45",
"1:51",
"1:56",
"1:60",
"0:76",
"0:84",
"0:85",
"0:87",
"0:88",
"0:91",
"0:112",
"0:141",
"0:147",
"1:165",
"1:166",
"0:173",
"2:179",
"2:188"
],
"voting_account": "1.2.5"
},
"owner": {
"account_auths": [],
"address_auths": [],
"key_auths": [
[
"<KEY>",
1
]
],
"weight_threshold": 1
}
}
]
}
]
}`
}
//end of file | gen/samples/proposalcreateoperation_51.go | 0.566139 | 0.438424 | proposalcreateoperation_51.go | starcoder |
package goflat
import (
"sort"
"strconv"
"strings"
)
// UMap takes a flattened map and recreates it with nested objects and lists.
// Remember to use the same delimiter when you first flattened it.
// If the options parameter is nil or delimiter is an empty string this method will use the default delimiter ".".
func UMap(flatmap map[string]interface{}, options *Options) interface{} {
if len(flatmap) == 0 {
return nil
}
options = createDefultOptionsIfNil(options)
keyArrays := sortKeys(flatmap, options)
if isList(keyArrays, keyArrays[0], 0, 0) {
wrapper := make(map[string]interface{})
for key, value := range flatmap {
wrapper[concatKey("wrapper", key, options)] = value
}
return unflatWrapper(wrapper, make(map[string]interface{}), sortKeys(wrapper, options), options).(map[string]interface{})["wrapper"]
}
return unflatWrapper(flatmap, make(map[string]interface{}), keyArrays, options)
}
func unflatWrapper(flat map[string]interface{}, result interface{}, keyArrays [][]string, options *Options) interface{} {
for keyArrayIdx, keyArray := range keyArrays {
unflat(keyArrays, result, flat[strings.Join(keyArray, options.Delimiter)], keyArray, keyArrayIdx, 0)
}
return result
}
func unflat(keyArrays [][]string, currValue interface{}, value interface{}, path []string, keyArrayIdx, depth int) interface{} {
switch m := currValue.(type) {
case []interface{}:
return unflatList(keyArrays, m, value, path, keyArrayIdx, depth)
default:
return unflatObject(keyArrays, m.(map[string]interface{}), value, path, keyArrayIdx, depth)
}
}
func unflatList(keyArrays [][]string, currValue []interface{}, value interface{}, path []string, keyArrayIdx, depth int) interface{} {
if _, err := strconv.Atoi(path[depth]); err == nil && len(path[depth:]) == 1 {
return append(currValue, value)
}
idx, _ := strconv.Atoi(path[depth])
if idx >= 0 && idx < len(currValue) {
currValue[idx] = unflat(keyArrays, currValue[idx], value, path, keyArrayIdx, depth+1)
return currValue
}
if isList(keyArrays, path, keyArrayIdx, depth+1) {
return append(currValue, unflat(keyArrays, make([]interface{}, 0), value, path, keyArrayIdx, depth+1))
}
return append(currValue, unflat(keyArrays, make(map[string]interface{}), value, path, keyArrayIdx, depth+1))
}
func unflatObject(keyArrays [][]string, currValue map[string]interface{}, value interface{}, path []string, keyArrayIdx, depth int) interface{} {
if (depth + 1) >= len(path) {
currValue[path[depth]] = value
return currValue
}
if isList(keyArrays, path, keyArrayIdx, depth+1) {
if val, ok := currValue[path[depth]]; ok {
currValue[path[depth]] = unflat(keyArrays, val, value, path, keyArrayIdx, depth+1)
} else {
currValue[path[depth]] = unflat(keyArrays, make([]interface{}, 0), value, path, keyArrayIdx, depth+1)
}
return currValue
}
if val, ok := currValue[path[depth]]; ok {
currValue[path[depth]] = unflat(keyArrays, val, value, path, keyArrayIdx, depth+1)
} else {
currValue[path[depth]] = unflat(keyArrays, make(map[string]interface{}), value, path, keyArrayIdx, depth+1)
}
return currValue
}
func isList(keyArrays [][]string, currKey []string, keyArrayIdx, depth int) bool {
if _, err := strconv.Atoi(currKey[depth]); err != nil {
return false
}
for idx, keyArray := range keyArrays {
if idx == keyArrayIdx {
continue
}
for i := 0; i <= depth; i++ {
if i == depth && len(keyArray) >= depth {
if _, err := strconv.Atoi(keyArray[i]); err != nil {
return false
}
}
if !strings.EqualFold(keyArray[i], currKey[i]) {
break
}
}
}
return true
}
func sortKeys(flatmap map[string]interface{}, options *Options) [][]string {
keys := make([]string, len(flatmap))
i := 0
for k := range flatmap {
keys[i] = k
i++
}
sort.Strings(keys)
result := make([][]string, len(keys))
for idx, key := range keys {
result[idx] = strings.Split(key, options.Delimiter)
}
return result
} | unflat.go | 0.620852 | 0.447702 | unflat.go | starcoder |
package strings
type inflection struct {
rule string
replacement string
}
type inflections struct{}
func (i *inflections) plural() []inflection {
return []inflection{
inflection{rule: `$`, replacement: "s"},
inflection{rule: `(?i)s$`, replacement: "s"},
inflection{rule: `(?i)^(ax|test)is$`, replacement: "\\1es"},
inflection{rule: `(?i)(octop|vir)us$`, replacement: "\\1i"},
inflection{rule: `(?i)(octop|vir)i$`, replacement: "\\1i"},
inflection{rule: `(?i)(alias|status)$`, replacement: "\\1es"},
inflection{rule: `(?i)(bu)s$`, replacement: "\\1ses"},
inflection{rule: `(?i)(buffal|tomat)o$`, replacement: "\\1oes"},
inflection{rule: `(?i)([ti])um$`, replacement: "\\1a"},
inflection{rule: `(?i)([ti])a$`, replacement: "\\1a"},
inflection{rule: `(?i)sis$`, replacement: "ses"},
inflection{rule: `(?i)(?:([^f])fe|([lr])f)$`, replacement: "\\1\\2ves"},
inflection{rule: `(?i)(hive)$`, replacement: "\\1s"},
inflection{rule: `(?i)([^aeiouy]|qu)y$`, replacement: "\\1ies"},
inflection{rule: `(?i)(x|ch|ss|sh)$`, replacement: "\\1es"},
inflection{rule: `(?i)(matr|vert|ind)(?:ix|ex)$`, replacement: "\\1ices"},
inflection{rule: `(?i)^(m|l)ouse$`, replacement: "\\1ice"},
inflection{rule: `(?i)^(m|l)ice$`, replacement: "\\1ice"},
inflection{rule: `(?i)^(ox)$`, replacement: "\\1en"},
inflection{rule: `(?i)^(oxen)$`, replacement: "\\1"},
inflection{rule: `(?i)(quiz)$`, replacement: "\\1zes"},
}
}
func (i *inflections) singular() []inflection {
return []inflection{}
}
func (i *inflections) irregular() []inflection {
return []inflection{}
}
func (i *inflections) uncountable() []string {
return []string{"equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "jeans", "police"}
}
// inflect.singular(/s$/i, "")
// inflect.singular(/(ss)$/i, '\1')
// inflect.singular(/(n)ews$/i, '\1ews')
// inflect.singular(/([ti])a$/i, '\1um')
// inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
// inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
// inflect.singular(/([^f])ves$/i, '\1fe')
// inflect.singular(/(hive)s$/i, '\1')
// inflect.singular(/(tive)s$/i, '\1')
// inflect.singular(/([lr])ves$/i, '\1f')
// inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
// inflect.singular(/(s)eries$/i, '\1eries')
// inflect.singular(/(m)ovies$/i, '\1ovie')
// inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
// inflect.singular(/^(m|l)ice$/i, '\1ouse')
// inflect.singular(/(bus)(es)?$/i, '\1')
// inflect.singular(/(o)es$/i, '\1')
// inflect.singular(/(shoe)s$/i, '\1')
// inflect.singular(/(cris|test)(is|es)$/i, '\1is')
// inflect.singular(/^(a)x[ie]s$/i, '\1xis')
// inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
// inflect.singular(/(alias|status)(es)?$/i, '\1')
// inflect.singular(/^(ox)en/i, '\1')
// inflect.singular(/(vert|ind)ices$/i, '\1ex')
// inflect.singular(/(matr)ices$/i, '\1ix')
// inflect.singular(/(quiz)zes$/i, '\1')
// inflect.singular(/(database)s$/i, '\1')
// inflect.irregular("person", "people")
// inflect.irregular("man", "men")
// inflect.irregular("child", "children")
// inflect.irregular("sex", "sexes")
// inflect.irregular("move", "moves")
// inflect.irregular("zombie", "zombies")
// inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police)) | strings/inflections.go | 0.529507 | 0.486819 | inflections.go | starcoder |
package slicex
//合并
func MergeComplex64(slices ...[]complex64) []complex64 {
ln := len(slices)
index := 0
total := 0
for index < ln {
total += len(slices[index])
index++
}
rs := make([]complex64, total)
rsIndex := 0
for index = 0; index < ln; index++ {
copy(rs[rsIndex:], slices[index])
rsIndex += len(slices[index])
}
return rs
}
//按位置插入
func InsertComplex64(slice []complex64, pos int, target ...complex64) []complex64 {
ln := len(slice)
if pos < 0 {
pos = 0
goto Start
}
if pos > ln {
pos = ln
}
Start:
tl := len(target)
rs := make([]complex64, ln+tl)
copy(rs, slice[:pos])
copy(rs[pos:], target)
copy(rs[pos+tl:], slice[pos:])
return rs
}
//头插入
func InsertHeadComplex64(slice []complex64, target ...complex64) []complex64 {
return InsertComplex64(slice, 0, target...)
}
//尾插入
func InsertTailComplex64(slice []complex64, target ...complex64) []complex64 {
return InsertComplex64(slice, len(slice), target...)
}
//按值删除
func RemoveValueComplex64(slice []complex64, target complex64) ([]complex64, bool) {
if len(slice) == 0 {
return nil, false
}
index, ok := IndexComplex64(slice, target)
if ok {
rs, _, ok2 := RemoveAtComplex64(slice, index)
if ok2 {
return rs, true
}
return nil, false
}
return nil, false
}
//按值删除
func RemoveAllValueComplex64(slice []complex64, target complex64) ([]complex64, bool) {
sl := len(slice)
if sl == 0 {
return nil, false
}
cp := make([]complex64, sl)
index := 0
for _, value := range slice {
if value != target {
cp[index] = value
index++
}
}
return cp[:index], true
}
//按点删除
func RemoveAtComplex64(slice []complex64, pos int) ([]complex64, complex64, bool) {
ln := len(slice)
if pos < 0 || pos >= ln {
return nil, 0, false
}
obj := slice[pos]
rs := make([]complex64, ln-1)
copy(rs, slice[:pos])
copy(rs[pos:], slice[pos+1:])
return rs, obj, true
}
//删除头
func RemoveHeadComplex64(slice []complex64) ([]complex64, complex64, bool) {
return RemoveAtComplex64(slice, 0)
}
//删除尾
func RemoveTailComplex64(slice []complex64) ([]complex64, complex64, bool) {
return RemoveAtComplex64(slice, len(slice)-1)
}
//删除区间
func RemoveFromComplex64(slice []complex64, startPos int, length int) (result []complex64, removed []complex64, ok bool) {
endPos := startPos + length
return RemoveRangeComplex64(slice, startPos, endPos)
}
//删除区间
func RemoveRangeComplex64(slice []complex64, startPos int, endPos int) (result []complex64, removed []complex64, ok bool) {
if startPos > endPos {
startPos, endPos = endPos, startPos
}
sl := len(slice)
if startPos < 0 || endPos >= sl || startPos == endPos || sl == 0 {
return nil, nil, false
}
rs := make([]complex64, sl-endPos+startPos)
copy(rs, slice[:startPos])
copy(rs[startPos:], slice[endPos:])
return rs, slice[startPos:endPos], true
}
//包含
func ContainsComplex64(slice []complex64, target complex64) bool {
_, ok := IndexComplex64(slice, target)
return ok
}
//从头部查找
func IndexComplex64(slice []complex64, target complex64) (int, bool) {
if nil == slice || len(slice) == 0 {
return -1, false
}
for index, value := range slice {
if value == target {
return index, true
}
}
return -1, false
}
//从尾部查找
func LastIndexComplex64(slice []complex64, target complex64) (int, bool) {
if nil == slice || len(slice) == 0 {
return -1, false
}
for index := len(slice) - 1; index >= 0; index-- {
if slice[index] == target {
return index, true
}
}
return -1, false
}
//倒序
func ReverseComplex64(slice []complex64) {
ln := len(slice)
if 0 == ln {
return
}
for i, j := 0, ln-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}
}
//比较
func EqualComplex64(a, b []complex64) bool {
if len(a) != len(b) {
return false
}
for index, val := range a {
if val != b[index] {
return false
}
}
return true
} | slicex/slicecomplex64.go | 0.508788 | 0.613526 | slicecomplex64.go | starcoder |
package validation
import (
"math"
"reflect"
"regexp"
"strings"
"github.com/pkg/errors"
)
// CompareFunc is the function definition of test comparator without type-system
type CompareFunc func(value interface{}, expected interface{}) error
// Comparators is a collection of compare functions
type Comparators struct {
comparators map[string]CompareFunc
}
type NotExpectedError struct {
message string
}
func (e *NotExpectedError) Error() string {
return e.message
}
func NewNotExpectedError() error {
return &NotExpectedError{"is not expected error"}
}
func IsNotExpectedError(err error) bool {
if _, ok := err.(*NotExpectedError); ok {
return true
}
return false
}
// NewComparators will return Comparators
func NewComparators() Comparators {
comparators := map[string]CompareFunc{
"eq": eq,
"equals": eq,
"==": eq,
"abs_eq": absEq,
"abs_equals": absEq,
"lt": lt,
"less_than": lt,
"le": le,
"less_than_or_equals": le,
"gt": gt,
"greater_than": gt,
"ge": ge,
"greater_than_or_equals": ge,
"ne": ne,
"not_equals": ne,
"str_eq": strEq,
"string_equals": strEq,
"float_eq": floatEq,
"float_equals": floatEq,
"len_eq": lenEq,
"length_equals": lenEq,
"count_eq": lenEq,
"len_gt": lenGt,
"count_gt": lenGt,
"length_greater_than": lenGt,
"count_greater_than": lenGt,
"len_ge": lenGe,
"count_ge": lenGe,
"length_greater_than_or_equals": lenGe,
"count_greater_than_or_equals": lenGe,
"len_lt": lenLt,
"count_lt": lenLt,
"length_less_than": lenLt,
"count_less_than": lenLt,
"len_le": lenLe,
"count_le": lenLe,
"length_less_than_or_equals": lenLe,
"count_less_than_or_equals": lenLe,
"contains": contains,
"contained_by": containedBy,
"type": typeEq,
"regex": regexMatch,
"startswith": startsWith,
"endswith": endsWith,
"object_contains": objectContains,
"object_not_contains": objectNotContains,
}
return Comparators{comparators}
}
// Get will return a comparator function by name
func (c *Comparators) Get(name string) CompareFunc {
if fn, ok := c.comparators[name]; ok {
return fn
}
return nil
}
func eq(a, b interface{}) error {
return strEq(a, b)
}
func ne(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
if aVal == bVal {
return NewNotExpectedError()
}
return nil
})
}
func absEq(a, b interface{}) error {
return checkFloats(a, b, func(aVal, bVal float64) error {
if math.Abs(aVal) != math.Abs(bVal) {
return NewNotExpectedError()
}
return nil
})
}
func lt(a, b interface{}) error {
return checkFloats(a, b, func(aVal, bVal float64) error {
if aVal >= bVal {
return NewNotExpectedError()
}
return nil
})
}
func le(a, b interface{}) error {
return checkFloats(a, b, func(aVal, bVal float64) error {
if aVal > bVal {
return NewNotExpectedError()
}
return nil
})
}
func gt(a, b interface{}) error {
return checkFloats(a, b, func(aVal, bVal float64) error {
if aVal <= bVal {
return NewNotExpectedError()
}
return nil
})
}
func ge(a, b interface{}) error {
return checkFloats(a, b, func(aVal, bVal float64) error {
if aVal < bVal {
return NewNotExpectedError()
}
return nil
})
}
func floatEq(a, b interface{}) error {
return checkFloats(a, b, func(aVal, bVal float64) error {
if aVal != bVal {
return NewNotExpectedError()
}
return nil
})
}
func strEq(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
if aVal != bVal {
return NewNotExpectedError()
}
return nil
})
}
func lenEq(a, b interface{}) error {
return checkLens(a, b, func(aVal, bVal int) error {
if aVal != bVal {
return NewNotExpectedError()
}
return nil
})
}
func lenGt(a, b interface{}) error {
return checkLens(a, b, func(aVal, bVal int) error {
if aVal <= bVal {
return NewNotExpectedError()
}
return nil
})
}
func lenGe(a, b interface{}) error {
return checkLens(a, b, func(aVal, bVal int) error {
if aVal < bVal {
return NewNotExpectedError()
}
return nil
})
}
func lenLt(a, b interface{}) error {
return checkLens(a, b, func(aVal, bVal int) error {
if aVal >= bVal {
return NewNotExpectedError()
}
return nil
})
}
func lenLe(a, b interface{}) error {
return checkLens(a, b, func(aVal, bVal int) error {
if aVal > bVal {
return NewNotExpectedError()
}
return nil
})
}
func contains(a, b interface{}) error {
f := reflect.ValueOf(a)
switch f.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < f.Len(); i++ {
item := f.Index(i)
for item.Kind() == reflect.Ptr || item.Kind() == reflect.Interface {
if f.IsNil() {
break
}
item = item.Elem()
}
err := strEq(item.String(), b)
if err != nil {
if !IsNotExpectedError(err) {
return err
} else {
continue
}
}
return nil
}
return NewNotExpectedError()
case reflect.String:
return checkStrings(a, b, func(aVal, bVal string) error {
if !strings.Contains(aVal, bVal) {
return NewNotExpectedError()
}
return nil
})
default:
return errors.Errorf("val must be contained by an iterable type, got %s", f.String())
}
}
func containedBy(a, b interface{}) error {
return contains(b, a)
}
func typeEq(a, b interface{}) error {
typeVal, _ := toString(b)
if reflect.ValueOf(a).Type().String() != typeVal {
return NewNotExpectedError()
}
return nil
}
func regexMatch(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
matched, err := regexp.MatchString(bVal, aVal)
if err != nil {
return err
}
if !matched {
return NewNotExpectedError()
}
return nil
})
}
func startsWith(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
if !strings.HasPrefix(aVal, bVal) {
return NewNotExpectedError()
}
return nil
})
}
func endsWith(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
if !strings.HasSuffix(aVal, bVal) {
return NewNotExpectedError()
}
return nil
})
}
func objectContains(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
if !strings.Contains(aVal, bVal) {
return NewNotExpectedError()
}
return nil
})
}
func objectNotContains(a, b interface{}) error {
return checkStrings(a, b, func(aVal, bVal string) error {
if strings.Contains(aVal, bVal) {
return NewNotExpectedError()
}
return nil
})
}
var DefaultComparators = NewComparators() | ucloud/utest/validation/comparators.go | 0.687315 | 0.419826 | comparators.go | starcoder |
package datamodel
import (
"bytes"
"strconv"
)
type CustomDataType interface {
getLength() int
writeToBytes(b []byte) int
Copy() CustomDataType
}
type DataNull interface {
CustomDataType
isNull()
}
type DataBool interface {
CustomDataType
Get() bool
Set(Value bool)
}
type DataInt interface {
CustomDataType
Get() int
Set(Value int)
}
type DataReal interface {
CustomDataType
Get() float64
Set(Value float64)
}
type DataString interface {
CustomDataType
Get() string
Set(Value string)
IsError() bool
IsSimple() bool
}
type DataArray interface {
CustomDataType
Count() int
Add(NewElement ...CustomDataType) int
Insert(Index int, NewElement CustomDataType) int
Remove(Index int)
Get(Index int) CustomDataType
IsNull() bool
}
type DataDictionary interface {
CustomDataType
Count() int
Add(Key string, Value CustomDataType)
Delete(Key string)
Value(Key string) CustomDataType
Keys() DataArray
}
func DataObjectToString(obj CustomDataType) string {
if obj == nil {
return ""
}
l := obj.getLength()
m := make([]byte, l)
obj.writeToBytes(m)
return string(m)
}
// Null section
type dataNull struct{}
var storageNull = dataNull{}
func CreateNull() DataNull {
return &storageNull
}
func (obj *dataNull) Copy() CustomDataType {
return obj
}
func (*dataNull) isNull() {}
func (*dataNull) getLength() int { return 4 }
func (*dataNull) writeToBytes(b []byte) int {
b[0] = 'n'
b[1] = 'u'
b[2] = 'l'
b[3] = 'l'
return 4
}
// Boolean section
type dataBool struct {
val bool
}
func CreateBool(val bool) DataBool {
return &dataBool{val: val}
}
func (obj *dataBool) Get() bool {
return obj.val
}
func (obj *dataBool) Set(Value bool) {
obj.val = Value
}
func (obj *dataBool) getLength() int {
if obj.val {
return 4
}
return 5
}
func (obj *dataBool) writeToBytes(b []byte) int {
if obj.val {
b[0] = 't'
b[1] = 'r'
b[2] = 'u'
b[3] = 'e'
return 4
}
b[0] = 'f'
b[1] = 'a'
b[2] = 'l'
b[3] = 's'
b[4] = 'e'
return 5
}
func (obj *dataBool) Copy() CustomDataType {
return CreateBool(obj.val)
}
// Int section
func getIntSize(x int) int {
p := 10
count := 1
for x >= p {
count++
p *= 10
}
return count
}
type dataInt struct {
val int
}
func CreateInt(val int) DataInt {
return &dataInt{val: val}
}
func (obj *dataInt) Get() int {
return obj.val
}
func (obj *dataInt) Set(Value int) {
obj.val = Value
}
func (obj *dataInt) getLength() int {
if obj.val >= 0 {
return getIntSize(obj.val)
}
return getIntSize(-obj.val) + 1
}
func (obj *dataInt) writeToBytes(b []byte) int {
var tot [20]byte
i := 0
var k int
if obj.val < 0 {
k = -obj.val
} else {
k = obj.val
}
for k >= 10 {
q := k / 10
tot[i] = byte(k - q*10 + '0')
k = q
i++
}
tot[i] = byte(k + '0')
ln := i
if obj.val < 0 {
ln++
}
j := 0
if obj.val < 0 {
b[0] = '-'
j++
}
for i >= 0 {
b[j] = tot[i]
j++
i--
}
return ln + 1
}
func (obj *dataInt) Copy() CustomDataType {
return CreateInt(obj.val)
}
// real section
func getRealSize(x float64) int {
return len(strconv.FormatFloat(x, 'f', -1, 64))
}
type dataReal struct {
val float64
}
func CreateReal(val float64) DataReal {
return &dataReal{val: val}
}
func (obj *dataReal) Get() float64 {
return obj.val
}
func (obj *dataReal) Set(Value float64) {
obj.val = Value
}
func (obj *dataReal) getLength() int {
return getRealSize(obj.val)
}
func (obj *dataReal) writeToBytes(b []byte) int {
str := strconv.FormatFloat(obj.val, 'f', -1, 64)
return copy(b, []byte(str))
}
func (obj *dataReal) Copy() CustomDataType {
return CreateReal(obj.val)
}
// string section
const (
dsBulk = iota
dsSimple
dsError
)
type dataString struct {
val string
tp int
}
func CreateSimpleString(str string) DataString {
return &dataString{val: str, tp: dsSimple}
}
func CreateError(str string) DataString {
return &dataString{val: str, tp: dsError}
}
func CreateString(str string) DataString {
return &dataString{val: str}
}
var hex = []byte("01234567890abcdef")
func writeToBytes(str string, b []byte) int {
src := []byte(str)
b[0] = '"'
offset := 1
for _, ch := range src {
switch ch {
case 9:
b[offset] = '\\'
b[offset+1] = 't'
offset += 2
case 8:
b[offset] = '\\'
b[offset+1] = 'b'
offset += 2
case 10:
b[offset] = '\\'
b[offset+1] = 'n'
offset += 2
case 12:
b[offset] = '\\'
b[offset+1] = 'f'
offset += 2
case 13:
b[offset] = '\\'
b[offset+1] = 'r'
offset += 2
case '/':
b[offset] = '\\'
b[offset+1] = '/'
offset += 2
case '"':
b[offset] = '\\'
b[offset+1] = '"'
offset += 2
case '\\':
b[offset] = '\\'
b[offset+1] = '\\'
offset += 2
default:
if ch < 0x1f {
b[offset] = '\\'
b[offset+1] = 'u'
b[offset+2] = '0'
b[offset+3] = '0'
b[offset+4] = hex[ch>>4]
b[offset+5] = hex[ch&0xf]
offset += 6
} else {
b[offset] = ch
offset++
}
}
}
b[offset] = '"'
return offset + 1
}
func (obj *dataString) writeToBytes(b []byte) int {
return writeToBytes(obj.val, b)
}
func getLength(str string) int {
cnt := 0
d := []byte(str)
for _, c := range d {
switch c {
case 8, 9, 10, 12, 13, '"', '\\', '/':
cnt += 2
default:
if c < 0x1f {
cnt += 6
} else {
cnt++
}
}
}
return cnt + 2
}
func (obj *dataString) getLength() int {
return getLength(obj.val)
}
func (obj *dataString) Get() string {
return obj.val
}
func (obj *dataString) Set(Value string) {
obj.val = Value
}
func (obj *dataString) Copy() CustomDataType {
return &dataString{val: obj.val, tp: obj.tp}
}
func (obj *dataString) IsError() bool {
return obj.tp == dsError
}
func (obj *dataString) IsSimple() bool {
return obj.tp == dsSimple
}
// array section
type dataArray struct {
list []CustomDataType
cnt int
isNull bool
}
func CreateArray(initialSize int) DataArray {
return &dataArray{
list: make([]CustomDataType, initialSize),
cnt: 0,
}
}
func (obj *dataArray) writeToBytes(b []byte) int {
b[0] = '['
offset := 1
for i := 0; i < obj.cnt; i++ {
wrt := obj.list[i].writeToBytes(b[offset:])
offset += wrt
if i < obj.cnt-1 {
b[offset] = ','
b[offset+1] = ' '
offset += 2
}
}
b[offset] = ']'
return offset + 1
}
func (obj *dataArray) getLength() int {
cnt := 2
for i := 0; i < obj.cnt; i++ {
cnt += obj.list[i].getLength()
}
if obj.cnt > 1 {
cnt += (obj.cnt - 1) * 2
}
return cnt
}
func (obj *dataArray) Count() int {
return obj.cnt
}
func (obj *dataArray) Add(NewElements ...CustomDataType) int {
i := 0
for _, item := range NewElements {
i = obj.Insert(obj.cnt, item)
}
return i
}
func (obj *dataArray) setCapacity(newCapacity int) {
tmp := make([]CustomDataType, newCapacity)
copy(tmp, obj.list)
obj.list = tmp
}
func (obj *dataArray) grow() {
var Delta int
Cap := len(obj.list)
if Cap > 64 {
Delta = Cap / 4
} else {
if Cap > 8 {
Delta = 16
} else {
Delta = 4
}
}
obj.setCapacity(Cap + Delta)
}
func (obj *dataArray) Insert(Index int, NewElement CustomDataType) int {
if obj.cnt == len(obj.list) {
obj.grow()
}
cnt := obj.cnt
if Index < 0 || Index >= cnt {
obj.list[cnt] = NewElement
obj.cnt++
return cnt
}
copy(obj.list[Index+1:], obj.list[Index:])
obj.list[Index] = NewElement
obj.cnt++
return Index
}
func (obj *dataArray) Remove(Index int) {
if Index < 0 || Index >= obj.cnt {
return
}
copy(obj.list[Index:], obj.list[Index+1:])
obj.cnt--
}
func (obj *dataArray) Get(Index int) CustomDataType {
if Index < 0 || Index >= obj.cnt {
return CreateNull()
}
return obj.list[Index]
}
func (obj *dataArray) Copy() CustomDataType {
tmp := CreateArray(obj.cnt)
for i := 0; i < obj.cnt; i++ {
tmp.Add(obj.list[i].Copy())
}
tmp.(*dataArray).isNull = obj.isNull
return tmp
}
func (obj *dataArray) IsNull() bool {
return obj.isNull
}
// dictionary section
type dataDictionary struct {
dict map[string]CustomDataType
}
func CreateDictionary(initialSize int) DataDictionary {
return &dataDictionary{
dict: make(map[string]CustomDataType, initialSize),
}
}
func (obj *dataDictionary) writeToBytes(b []byte) int {
b[0] = '{'
offset := 1
i := 0
maplen := len(obj.dict)
for k, v := range obj.dict {
off := writeToBytes(k, b[offset:])
offset += off
b[offset] = ':'
offset++
off = v.writeToBytes(b[offset:])
offset += off
if i < maplen-1 {
b[offset] = ','
b[offset+1] = ' '
offset += 2
}
i++
}
b[offset] = '}'
return offset + 1
}
func (obj *dataDictionary) getLength() int {
cnt := 2
for k, v := range obj.dict {
cnt += getLength(k) + 1 + v.getLength()
}
if len(obj.dict) > 1 {
cnt += (len(obj.dict) - 1) * 2
}
return cnt
}
func (obj *dataDictionary) Count() int {
return len(obj.dict)
}
func (obj *dataDictionary) Add(Key string, Value CustomDataType) {
_, isNull := Value.(DataNull)
if isNull {
obj.Delete(Key)
return
}
obj.dict[Key] = Value
}
func (obj *dataDictionary) Delete(Key string) {
delete(obj.dict, Key)
}
func (obj *dataDictionary) Value(Key string) CustomDataType {
Value, ok := obj.dict[Key]
if !ok {
return CreateNull()
}
return Value
}
func (obj *dataDictionary) Keys() DataArray {
arr := CreateArray(len(obj.dict))
for key := range obj.dict {
arr.Add(CreateString(key))
}
return arr
}
func (obj *dataDictionary) Copy() CustomDataType {
l := len(obj.dict)
tmp := CreateDictionary(l)
for k, v := range obj.dict {
tmp.Add(k, v.Copy())
}
return tmp
}
func ConvertToRASP(data CustomDataType) []byte {
switch value := data.(type) {
case DataNull:
return []byte("$-1\r\n")
case DataReal:
str := DataObjectToString(value)
return []byte("$" + strconv.Itoa(len(str)) + "\r\n" + str + "\r\n")
case DataDictionary:
str := DataObjectToString(value)
return []byte("$" + strconv.Itoa(len(str)) + "\r\n" + str + "\r\n")
case DataBool:
str := DataObjectToString(value)
return []byte("$" + strconv.Itoa(len(str)) + "\r\n" + str + "\r\n")
case *dataString:
switch value.tp {
case dsSimple:
return []byte("+" + value.val + "\r\n")
case dsError:
return []byte("-" + value.val + "\r\n")
}
return []byte("$" + strconv.Itoa(len(value.val)) + "\r\n" + value.val + "\r\n")
case *dataInt:
return []byte(":" + strconv.Itoa(value.val) + "\r\n")
case *dataArray:
if value.isNull {
return []byte("*-1\r\n")
}
a := bytes.NewBufferString("*" + strconv.Itoa(value.cnt) + "\r\n")
for i := 0; i < value.cnt; i++ {
a.Write(ConvertToRASP(value.list[i]))
}
return a.Bytes()
}
return []byte("$-1\r\n")
}
func ConvertCommandToRASP(Command string, arguments ...CustomDataType) []byte {
arr := CreateArray(1 + len(arguments))
arr.Add(CreateString(Command))
arr.Add(arguments...)
return ConvertToRASP(arr)
} | datamodel/model.go | 0.503174 | 0.478894 | model.go | starcoder |
package core
import (
"fmt"
"github.com/j3ssie/osmedeus/execution"
"github.com/j3ssie/osmedeus/utils"
"github.com/robertkrimen/otto"
"path"
"time"
)
func (r *Runner) LoadExternalScripts() string {
var output string
vm := r.VM
// special scripts
vm.Set(Cleaning, func(call otto.FunctionCall) otto.Value {
if r.Opt.NoClean {
utils.InforF("Disabled Cleaning")
return otto.Value{}
}
execution.Cleaning(call.Argument(0).String(), r.Reports)
return otto.Value{}
})
// scripts for cleaning modules
vm.Set(CleanAmass, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanAmass(src, dest)
return otto.Value{}
})
vm.Set(CleanRustScan, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanRustScan(src, dest)
return otto.Value{}
})
vm.Set(CleanGoBuster, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanGoBuster(src, dest)
return otto.Value{}
})
vm.Set(CleanMassdns, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanMassdns(src, dest)
return otto.Value{}
})
vm.Set(CleanSWebanalyze, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanSWebanalyze(src, dest)
return otto.Value{}
})
vm.Set(CleanJSONDnsx, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanJSONDnsx(src, dest)
return otto.Value{}
})
vm.Set(CleanJSONHttpx, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanJSONHttpx(src, dest)
return otto.Value{}
})
// Deprecated
vm.Set(CleanWebanalyze, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
args := call.ArgumentList
techSum := path.Join(path.Dir(dest), fmt.Sprintf("tech-overview-%v.txt", r.Target["Workspace"]))
if len(args) > 3 {
techSum = args[2].String()
}
execution.CleanWebanalyze(src, dest, techSum)
return otto.Value{}
})
vm.Set(CleanArjun, func(call otto.FunctionCall) otto.Value {
// src mean folder contain arjun output
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanArjun(src, dest)
return otto.Value{}
})
vm.Set(CleanFFUFJson, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
execution.CleanFFUFJson(src, dest)
return otto.Value{}
})
vm.Set(GenNucleiReport, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
args := call.ArgumentList
templateFile := ""
if len(args) >= 3 {
templateFile = args[2].String()
}
execution.GenNucleiReport(r.Opt, src, dest, templateFile)
return otto.Value{}
})
return output
}
func (r *Runner) LoadGitScripts() string {
var output string
vm := r.VM
options := r.Opt
// Clone("git@xxx.git", "/tmp/dest")
vm.Set(Clone, func(call otto.FunctionCall) otto.Value {
execution.GitClone(call.Argument(0).String(), call.Argument(1).String(), false, options)
return otto.Value{}
})
// like clone but delete the destination folder first
vm.Set(FClone, func(call otto.FunctionCall) otto.Value {
execution.GitClone(call.Argument(0).String(), call.Argument(1).String(), true, options)
return otto.Value{}
})
vm.Set(PushResult, func(call otto.FunctionCall) otto.Value {
for folder := range options.Storages {
execution.PullResult(folder, options)
time.Sleep(3 * time.Second)
execution.PullResult(folder, options)
commitMess := fmt.Sprintf("%v|%v|%v", options.Module.Name, options.Scan.ROptions["Workspace"], utils.GetCurrentDay())
execution.PushResult(folder, commitMess, options)
}
return otto.Value{}
})
// push result but specific folder
vm.Set(PushFolder, func(call otto.FunctionCall) otto.Value {
folder := call.Argument(0).String()
execution.PullResult(folder, options)
time.Sleep(3 * time.Second)
execution.PullResult(folder, options)
commitMess := fmt.Sprintf("%v|%v|%v", options.Module.Name, options.Scan.ROptions["Workspace"], utils.GetCurrentDay())
execution.PushResult(folder, commitMess, options)
return otto.Value{}
})
// push result but specific folder
vm.Set(PullFolder, func(call otto.FunctionCall) otto.Value {
folder := call.Argument(0).String()
execution.PullResult(folder, options)
time.Sleep(3 * time.Second)
execution.PullResult(folder, options)
return otto.Value{}
})
vm.Set(DiffCompare, func(call otto.FunctionCall) otto.Value {
src := call.Argument(0).String()
dest := call.Argument(1).String()
output := call.Argument(2).String()
execution.DiffCompare(src, dest, output, options)
return otto.Value{}
})
vm.Set(GitDiff, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
src := args[0].String()
output := call.Argument(1).String()
history := "1"
if len(args) < 2 {
history = call.Argument(2).String()
}
execution.GitDiff(src, output, history, options)
return otto.Value{}
})
vm.Set(LoopGitDiff, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
src := args[0].String()
output := call.Argument(1).String()
execution.LoopGitDiff(src, output, options)
return otto.Value{}
})
vm.Set(GetFileFromCDN, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
src := args[0].String()
output := args[1].String()
execution.GetFileFromCDN(options, src, output)
return otto.Value{}
})
vm.Set(GetWSFromCDN, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
src := args[0].String()
output := args[1].String()
execution.GetWSFromCDN(options, src, output)
return otto.Value{}
})
vm.Set(DownloadFile, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
src := args[0].String()
output := args[1].String()
execution.DownloadFile(options, src, output)
return otto.Value{}
})
/* --- Gitlab API --- */
// CreateRepo("repo-name")
// CreateRepo("repo-name", "tags")
vm.Set(CreateRepo, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
repoName := args[0].String()
tags := ""
if len(args) > 1 {
tags = args[1].String()
}
execution.CreateGitlabRepo(repoName, tags, options)
return otto.Value{}
})
vm.Set(DeleteRepo, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
repoName := args[0].String()
execution.DeleteRepo(repoName, 0, options)
return otto.Value{}
})
vm.Set(DeleteRepoByPid, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
pid, err := args[0].ToInteger()
if err != nil {
return otto.Value{}
}
execution.DeleteRepo("", int(pid), options)
return otto.Value{}
})
vm.Set(ListProjects, func(call otto.FunctionCall) otto.Value {
args := call.ArgumentList
if len(args) > 0 {
uid, err := args[0].ToInteger()
if err == nil {
execution.ListProjects(int(uid), options)
}
return otto.Value{}
}
execution.ListProjects(0, options)
return otto.Value{}
})
return output
} | core/external.go | 0.521715 | 0.424293 | external.go | starcoder |
package objs
import (
"fmt"
"strconv"
)
func ParseBool(data []byte) (bool, error) {
if len(data) == 0 {
return false, nil
}
if data[0] == 0x00 {
return false, nil
}
if data[0] == 0x01 {
return true, nil
}
return strconv.ParseBool(string(data))
}
// float32 - 3.14 => float64 - 3.140000104904175
func ParseFloat(value interface{}) (float64, error) {
switch value.(type) {
case float64:
return value.(float64), nil
case float32:
return float64(value.(float32)), nil
case int:
return float64(value.(int)), nil
case uint:
return float64(value.(uint)), nil
case int8:
return float64(value.(int8)), nil
case uint8:
return float64(value.(uint8)), nil
case int16:
return float64(value.(int16)), nil
case uint16:
return float64(value.(uint16)), nil
case int32:
return float64(value.(int32)), nil
case uint32:
return float64(value.(uint32)), nil
case int64:
return float64(value.(int64)), nil
case uint64:
return float64(value.(uint64)), nil
case string:
return strconv.ParseFloat(value.(string), 64)
case []byte:
return strconv.ParseFloat(string(value.([]byte)), 64)
default:
return 0, fmt.Errorf("unsupported type %v", value)
}
}
func ParseUint(value interface{}) (uint64, error) {
if value == nil {
return 0, nil
}
switch value.(type) {
case uint64:
return value.(uint64), nil
case int:
return uint64(value.(int)), nil
case uint:
return uint64(value.(uint)), nil
case int8:
return uint64(value.(int8)), nil
case uint8:
return uint64(value.(uint8)), nil
case int16:
return uint64(value.(int16)), nil
case uint16:
return uint64(value.(uint16)), nil
case int32:
return uint64(value.(int32)), nil
case uint32:
return uint64(value.(uint32)), nil
case int64:
return uint64(value.(int64)), nil
case float32:
return uint64(value.(float32)), nil
case float64:
return uint64(value.(float64)), nil
case string:
return strconv.ParseUint(value.(string), 10, 64)
case []byte:
return strconv.ParseUint(string(value.([]byte)), 10, 64)
case bool:
if value.(bool) {
return 1, nil
} else {
return 0, nil
}
default:
return 0, fmt.Errorf("unsupported type %v", value)
}
} | objs/parse.go | 0.546254 | 0.478712 | parse.go | starcoder |
package TestUtils
import (
"YusLabCore/src/ObjectModule"
"math"
"reflect"
)
const float64EqualityThreshold = 1e-4 // this value can't be too precise, as the excel calculation has different precision.
func AlmostEqualsInputSheet(a ObjectModule.InputDataSheet, b ObjectModule.InputDataSheet) bool {
return reflect.DeepEqual(a.RowTitles, b.RowTitles) &&
reflect.DeepEqual(a.DataColumnTitles, b.DataColumnTitles) &&
AlmostEqualsMatrix(a.Data, b.Data)
}
func AlmostEqualsOutputSheet(a ObjectModule.OutputDataSheet, b ObjectModule.OutputDataSheet) bool {
return reflect.DeepEqual(a.ColumnTitles, b.ColumnTitles) &&
reflect.DeepEqual(a.RowTitles, b.RowTitles) &&
AlmostEqualsMatrix(a.Data, b.Data) &&
reflect.DeepEqual(a.BaseGeneA, b.BaseGeneA)
}
func AlmostEqualsCalculationSheet(a ObjectModule.CalculationDataSheet, b ObjectModule.CalculationDataSheet) bool {
return a.CurrentDividingTarget == b.CurrentDividingTarget &&
AlmostEqualsArray(a.Mean, b.Mean) &&
AlmostEqualsArray(a.Se, b.Se) &&
AlmostEqualsArray(a.SeMean, b.SeMean) &&
AlmostEqualsMatrix(a.Data, b.Data)
}
func AlmostEqualsMatrix(a [][]float64, b [][]float64) bool {
if len(a) != len(b) {
return false
}
if len(a[0]) != len(b[0]) {
return false
}
equals := true
for i, _ := range a {
equals = equals && AlmostEqualsArray(a[i], b[i])
}
return equals
}
func AlmostEqualsArray(a []float64, b []float64) bool {
if len(a) != len(b) {
return false
}
for i, _ := range a {
if !AlmostEqualsFloat(a[i], b[i]) {
return false
}
}
return true
}
func AlmostEqualsFloat(a float64, b float64) bool {
if math.IsNaN(a) {
return AlmostEqualsFloat(0.0, b)
}
if math.IsNaN(b) {
return AlmostEqualsFloat(a, 0.0)
}
return math.Abs(a-b) <= float64EqualityThreshold
}
func GetInputMatrix() [][]float64 {
return [][]float64{
{50, 51, 8, 17, 54},
{5, 4, 2, 2, 4},
{143, 159, 44, 67, 165},
{417, 476, 123, 249, 431},
{110, 124, 49, 83, 201},
{249, 452, 81, 142, 310},
{265, 254, 63, 161, 323},
{557, 555, 197, 283, 540},
{1795, 1537, 477, 648, 1483},
{670, 743, 227, 347, 758},
}
}
func GetSeMatrix(rowNum int) []float64 {
return [][]float64{
{0.0, 0.032451081, 0.487753954, 1.601793734, 0.741290993, 0.971019076, 0.851110879, 2.753418229, 5.677179904, 2.845795479},
{1.699264547, 0.0, 3.565340096, 11.78167645, 5.307777313, 12.61723425, 9.23904757, 8.510340769, 26.18437034, 15.08476052},
{0.030704828, 0.00388212, 0.0, 0.188732159, 0.10401625, 0.199456261, 0.166734128, 0.223083896, 0.627457964, 0.127975252},
{0.012795214, 0.001532047, 0.018956462, 0.0, 0.039652153, 0.067744193, 0.042823987, 0.083410156, 0.289174552, 0.078797035},
{0.057011689, 0.004829121, 0.111124584, 0.338007953, 0.0, 0.390940893, 0.191984687, 0.412801625, 1.654824435, 0.472659209},
{0.019631613, 0.002797343, 0.039402746, 0.123384288, 0.068522108, 0.0, 0.107176705, 0.20959054, 0.645060599, 0.202751957},
{0.018117622, 0.003585775, 0.048487755, 0.113486864, 0.062995348, 0.168098231, 0.0, 0.258726788, 0.66185136, 0.256586785},
{0.011232174, 0.000604345, 0.015257092, 0.045563935, 0.030681814, 0.071657591, 0.048970901, 0.0, 0.162101975, 0.046233057},
{0.00336747, 0.000291508, 0.005495132, 0.025991625, 0.013996101, 0.026245017, 0.02196804, 0.022056863, 0.0, 0.027734306},
{0.007578798, 0.00069072, 0.005336863, 0.03056705, 0.01985959, 0.045516759, 0.032687591, 0.028441734, 0.142311729, 0.0},
}[rowNum]
}
func GetSeMeanMatrix(rowNum int) []float64 {
return [][]float64{
{0.0, 0.261637909, 0.132008213, 0.143847313, 0.191439749, 0.127559468, 0.126625284, 0.187832753, 0.148428542, 0.156719867},
{0.174283543, 0.0, 0.107975169, 0.118730993, 0.156802875, 0.179323966, 0.149378295, 0.06806639, 0.078092366, 0.094723771},
{0.107117789, 0.121567008, 0.0, 0.062769328, 0.101583744, 0.095679675, 0.090194712, 0.057615977, 0.060659658, 0.026342757},
{0.131732688, 0.141943463, 0.056197606, 0.0, 0.115110093, 0.096922043, 0.069580309, 0.064233103, 0.082835055, 0.048250316},
{0.189713026, 0.148564724, 0.108767767, 0.110575016, 0.0, 0.18074028, 0.103329608, 0.105006216, 0.15427189, 0.095806587},
{0.138972601, 0.173513108, 0.079654093, 0.083478785, 0.134150022, 0.0, 0.11701229, 0.108801155, 0.124792062, 0.084298314},
{0.114781313, 0.196657034, 0.086864342, 0.068523012, 0.111738255, 0.143757145, 0.0, 0.119300395, 0.114063647, 0.094620703},
{0.146887903, 0.074042516, 0.058283278, 0.058285528, 0.114900306, 0.130359507, 0.101168244, 0.0, 0.060263828, 0.036555109},
{0.119876822, 0.09486399, 0.056071258, 0.088121889, 0.137674013, 0.127306477, 0.120541473, 0.058498432, 0.0, 0.058285449},
{0.126845513, 0.105622458, 0.025856281, 0.049444202, 0.094453101, 0.105606965, 0.085793702, 0.035783692, 0.066669249, 0.0},
}[rowNum]
}
func GetMeanMatrix(rowNum int) []float64 {
return [][]float64{
{0.0, 0.124030501, 3.694875817, 11.13537473, 3.872189542, 7.612285403, 6.721492375, 14.65888235, 38.24857298, 18.15848584},
{9.75, 0.0, 33.02, 99.23, 33.85, 70.36, 61.85, 125.03, 335.3, 159.25},
{0.286645464, 0.031933997, 0.0, 3.006757655, 1.023945827, 2.084625198, 1.848602029, 3.871910306, 10.34390878, 4.858081088},
{0.09713014, 0.010793361, 0.337317956, 0.0, 0.344471559, 0.698955477, 0.615461295, 1.298554047, 3.490968327, 1.633088489},
{0.300515415, 0.032505164, 1.021668337, 3.056820291, 0.0, 2.162998162, 1.8579833, 3.931211339, 10.72667507, 4.933472961},
{0.141262472, 0.016121794, 0.494673205, 1.478031673, 0.510787152, 0.0, 0.915944002, 1.926363179, 5.169083592, 2.405172152},
{0.1578447, 0.01823365, 0.558200915, 1.656186156, 0.563776013, 1.169320877, 0.0, 2.168700178, 5.802474114, 2.711740414},
{0.076467661, 0.008162139, 0.261774782, 0.781736689, 0.267029873, 0.549692098, 0.484054074, 0.0, 2.68987186, 1.26474953},
{0.028091082, 0.003072903, 0.098002644, 0.294950838, 0.101661168, 0.20615618, 0.182244664, 0.377050503, 0.0, 0.47583584},
{0.059748252, 0.006539515, 0.206404883, 0.618213029, 0.210258741, 0.431001482, 0.381002216, 0.794823889, 2.13459325, 0.0},
}[rowNum]
}
func GetDividingResultMatrix(rowNum int) [][]float64 {
return [][][]float64{
{
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.1, 0.078431373, 0.25, 0.117647059, 0.074074074},
{2.86, 3.117647059, 5.5, 3.941176471, 3.055555556},
{8.34, 9.333333333, 15.375, 14.64705882, 7.981481481},
{2.2, 2.431372549, 6.125, 4.882352941, 3.722222222},
{4.98, 8.862745098, 10.125, 8.352941176, 5.740740741},
{5.3, 4.980392157, 7.875, 9.470588235, 5.981481481},
{11.14, 10.88235294, 24.625, 16.64705882, 10},
{35.9, 30.1372549, 59.625, 38.11764706, 27.46296296},
{13.4, 14.56862745, 28.375, 20.41176471, 14.03703704},
},
{
{10, 12.75, 4, 8.5, 13.5},
{0.0, 0.0, 0.0, 0.0, 0.0},
{28.6, 39.75, 22, 33.5, 41.25},
{83.4, 119, 61.5, 124.5, 107.75},
{22, 31, 24.5, 41.5, 50.25},
{49.8, 113, 40.5, 71, 77.5},
{53, 63.5, 31.5, 80.5, 80.75},
{111.4, 138.75, 98.5, 141.5, 135},
{359, 384.25, 238.5, 324, 370.75},
{134, 185.75, 113.5, 173.5, 189.5},
},
{
{0.34965035, 0.320754717, 0.181818182, 0.253731343, 0.327272727},
{0.034965035, 0.025157233, 0.045454545, 0.029850746, 0.024242424},
{0.0, 0.0, 0.0, 0.0, 0.0},
{2.916083916, 2.993710692, 2.795454545, 3.71641791, 2.612121212},
{0.769230769, 0.779874214, 1.113636364, 1.23880597, 1.218181818},
{1.741258741, 2.842767296, 1.840909091, 2.119402985, 1.878787879},
{1.853146853, 1.597484277, 1.431818182, 2.402985075, 1.957575758},
{3.895104895, 3.490566038, 4.477272727, 4.223880597, 3.272727273},
{12.55244755, 9.666666667, 10.84090909, 9.671641791, 8.987878788},
{4.685314685, 4.672955975, 5.159090909, 5.179104478, 4.593939394},
},
{
{0.119904077, 0.107142857, 0.06504065, 0.068273092, 0.125290023},
{0.011990408, 0.008403361, 0.016260163, 0.008032129, 0.009280742},
{0.342925659, 0.334033613, 0.357723577, 0.269076305, 0.382830626},
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.263788969, 0.260504202, 0.398373984, 0.333333333, 0.466357309},
{0.597122302, 0.949579832, 0.658536585, 0.570281124, 0.719257541},
{0.635491607, 0.533613445, 0.512195122, 0.646586345, 0.749419954},
{1.335731415, 1.165966387, 1.601626016, 1.136546185, 1.252900232},
{4.304556355, 3.228991597, 3.87804878, 2.602409639, 3.440835267},
{1.606714628, 1.56092437, 1.845528455, 1.393574297, 1.758700696},
},
{
{0.454545455, 0.411290323, 0.163265306, 0.204819277, 0.268656716},
{0.045454545, 0.032258065, 0.040816327, 0.024096386, 0.019900498},
{1.3, 1.282258065, 0.897959184, 0.807228916, 0.820895522},
{3.790909091, 3.838709677, 2.510204082, 3, 2.144278607},
{0.0, 0.0, 0.0, 0.0, 0.0},
{2.263636364, 3.64516129, 1.653061224, 1.710843373, 1.542288557},
{2.409090909, 2.048387097, 1.285714286, 1.939759036, 1.606965174},
{5.063636364, 4.475806452, 4.020408163, 3.409638554, 2.686567164},
{16.31818182, 12.39516129, 9.734693878, 7.807228916, 7.378109453},
{6.090909091, 5.991935484, 4.632653061, 4.180722892, 3.771144279},
},
{
{0.200803213, 0.112831858, 0.098765432, 0.11971831, 0.174193548},
{0.020080321, 0.008849558, 0.024691358, 0.014084507, 0.012903226},
{0.574297189, 0.351769912, 0.543209877, 0.471830986, 0.532258065},
{1.674698795, 1.053097345, 1.518518519, 1.753521127, 1.390322581},
{0.441767068, 0.274336283, 0.604938272, 0.584507042, 0.648387097},
{0.0, 0.0, 0.0, 0.0, 0.0},
{1.064257028, 0.561946903, 0.777777778, 1.133802817, 1.041935484},
{2.236947791, 1.227876106, 2.432098765, 1.992957746, 1.741935484},
{7.208835341, 3.400442478, 5.888888889, 4.563380282, 4.783870968},
{2.690763052, 1.64380531, 2.802469136, 2.443661972, 2.44516129},
},
{
{0.188679245, 0.200787402, 0.126984127, 0.105590062, 0.167182663},
{0.018867925, 0.015748031, 0.031746032, 0.01242236, 0.012383901},
{0.539622642, 0.625984252, 0.698412698, 0.416149068, 0.510835913},
{1.573584906, 1.874015748, 1.952380952, 1.546583851, 1.334365325},
{0.41509434, 0.488188976, 0.777777778, 0.51552795, 0.622291022},
{0.939622642, 1.779527559, 1.285714286, 0.881987578, 0.959752322},
{0.0, 0.0, 0.0, 0.0, 0.0},
{2.101886792, 2.18503937, 3.126984127, 1.757763975, 1.671826625},
{6.773584906, 6.051181102, 7.571428571, 4.02484472, 4.591331269},
{2.528301887, 2.92519685, 3.603174603, 2.155279503, 2.346749226},
},
{
{0.089766607, 0.091891892, 0.040609137, 0.060070671, 0.1},
{0.008976661, 0.007207207, 0.010152284, 0.007067138, 0.007407407},
{0.256732496, 0.286486486, 0.223350254, 0.236749117, 0.305555556},
{0.748653501, 0.857657658, 0.624365482, 0.879858657, 0.798148148},
{0.197486535, 0.223423423, 0.248730964, 0.293286219, 0.372222222},
{0.447037702, 0.814414414, 0.411167513, 0.501766784, 0.574074074},
{0.475763016, 0.457657658, 0.319796954, 0.568904594, 0.598148148},
{0.0, 0.0, 0.0, 0.0, 0.0},
{3.222621185, 2.769369369, 2.421319797, 2.28975265, 2.746296296},
{1.202872531, 1.338738739, 1.152284264, 1.22614841, 1.403703704},
},
{
{0.027855153, 0.033181522, 0.016771488, 0.026234568, 0.036412677},
{0.002785515, 0.002602472, 0.004192872, 0.00308642, 0.002697235},
{0.079665738, 0.103448276, 0.092243187, 0.103395062, 0.111260958},
{0.232311978, 0.309694209, 0.257861635, 0.384259259, 0.290627107},
{0.061281337, 0.080676643, 0.102725367, 0.12808642, 0.135536076},
{0.138718663, 0.294079375, 0.169811321, 0.219135802, 0.209035738},
{0.147632312, 0.165256994, 0.132075472, 0.24845679, 0.217801753},
{0.310306407, 0.361093038, 0.412997904, 0.436728395, 0.36412677},
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.373259053, 0.483409239, 0.475890985, 0.535493827, 0.511126096},
},
{
{0.074626866, 0.068640646, 0.035242291, 0.048991354, 0.071240106},
{0.007462687, 0.00538358, 0.008810573, 0.005763689, 0.005277045},
{0.213432836, 0.213997308, 0.193832599, 0.193083573, 0.2176781},
{0.62238806, 0.64064603, 0.54185022, 0.717579251, 0.568601583},
{0.164179104, 0.166890983, 0.215859031, 0.239193084, 0.265171504},
{0.371641791, 0.608344549, 0.356828194, 0.409221902, 0.408970976},
{0.395522388, 0.341857335, 0.27753304, 0.463976945, 0.426121372},
{0.831343284, 0.746971736, 0.86784141, 0.81556196, 0.712401055},
{2.679104478, 2.068640646, 2.101321586, 1.867435159, 1.95646438},
{0.0, 0.0, 0.0, 0.0, 0.0},
},
}[rowNum]
}
func GetMinSeMeanMatrix(rowNum int) float64 {
return []float64{
0.126625284, 0.06806639, 0.026342757, 0.048250316, 0.095806587, 0.079654093, 0.068523012, 0.036555109, 0.056071258, 0.025856281,
}[rowNum]
} | src/TestUtils/utils.go | 0.667148 | 0.632389 | utils.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.