<commit_before>package prometheus

import (
	"fmt"
	"runtime"
	"runtime/debug"
	"time"
)

type goCollector struct {
	goroutinesDesc *Desc
	threadsDesc    *Desc
	gcDesc         *Desc
	goInfoDesc     *Desc

	// metrics to describe and collect
	metrics memStatsMetrics
}

// NewGoCollector returns a collector which exports metrics about the current
// go process.
func NewGoCollector() Collector {
	return &goCollector{
		goroutinesDesc: NewDesc(
			"go_goroutines",
			"Number of goroutines that currently exist.",
			nil, nil),
		threadsDesc: NewDesc(
			"go_threads",
			"Number of OS threads created.",
			nil, nil),
		gcDesc: NewDesc(
			"go_gc_duration_seconds",
			"A summary of the GC invocation durations.",
			nil, nil),
		goInfoDesc: NewDesc(
			"go_info",
			"Information about the Go environment.",
			nil, Labels{"version": runtime.Version()}),
		metrics: memStatsMetrics{
			{
				desc: NewDesc(
					memstatNamespace("alloc_bytes"),
					"Number of bytes allocated and still in use.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Alloc) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("alloc_bytes_total"),
					"Total number of bytes allocated, even if freed.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.TotalAlloc) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("sys_bytes"),
					"Number of bytes obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Sys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("lookups_total"),
					"Total number of pointer lookups.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Lookups) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mallocs_total"),
					"Total number of mallocs.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Mallocs) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("frees_total"),
					"Total number of frees.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Frees) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_alloc_bytes"),
					"Number of heap bytes allocated and still in use.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapAlloc) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_sys_bytes"),
					"Number of heap bytes obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_idle_bytes"),
					"Number of heap bytes waiting to be used.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapIdle) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_inuse_bytes"),
					"Number of heap bytes that are in use.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_released_bytes"),
					"Number of heap bytes released to OS.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapReleased) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_objects"),
					"Number of allocated objects.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapObjects) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("stack_inuse_bytes"),
					"Number of bytes in use by the stack allocator.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.StackInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("stack_sys_bytes"),
					"Number of bytes obtained from system for stack allocator.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.StackSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mspan_inuse_bytes"),
					"Number of bytes in use by mspan structures.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MSpanInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mspan_sys_bytes"),
					"Number of bytes used for mspan structures obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MSpanSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mcache_inuse_bytes"),
					"Number of bytes in use by mcache structures.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MCacheInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mcache_sys_bytes"),
					"Number of bytes used for mcache structures obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MCacheSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("buck_hash_sys_bytes"),
					"Number of bytes used by the profiling bucket hash table.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.BuckHashSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("gc_sys_bytes"),
					"Number of bytes used for garbage collection system metadata.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.GCSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("other_sys_bytes"),
					"Number of bytes used for other system allocations.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.OtherSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("next_gc_bytes"),
					"Number of heap bytes when next garbage collection will take place.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.NextGC) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("last_gc_time_seconds"),
					"Number of seconds since 1970 of last garbage collection.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.LastGC) / 1e9 },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("gc_cpu_fraction"),
					"The fraction of this program's available CPU time used by the GC since the program started.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction },
				valType: GaugeValue,
			},
		},
	}
}

func memstatNamespace(s string) string {
	return fmt.Sprintf("go_memstats_%s", s)
}

// Describe returns all descriptions of the collector.
func (c *goCollector) Describe(ch chan<- *Desc) {
	ch <- c.goroutinesDesc
	ch <- c.threadsDesc
	ch <- c.gcDesc
	ch <- c.goInfoDesc
	for _, i := range c.metrics {
		ch <- i.desc
	}
}

// Collect returns the current state of all metrics of the collector.
func (c *goCollector) Collect(ch chan<- Metric) {
	ch <- MustNewConstMetric(c.goroutinesDesc, GaugeValue, float64(runtime.NumGoroutine()))
	n, _ := runtime.ThreadCreateProfile(nil)
	ch <- MustNewConstMetric(c.threadsDesc, GaugeValue, float64(n))

	var stats debug.GCStats
	stats.PauseQuantiles = make([]time.Duration, 5)
	debug.ReadGCStats(&stats)

	quantiles := make(map[float64]float64)
	for idx, pq := range stats.PauseQuantiles[1:] {
		quantiles[float64(idx+1)/float64(len(stats.PauseQuantiles)-1)] = pq.Seconds()
	}
	quantiles[0.0] = stats.PauseQuantiles[0].Seconds()
	ch <- MustNewConstSummary(c.gcDesc, uint64(stats.NumGC), float64(stats.PauseTotal.Seconds()), quantiles)

	ch <- MustNewConstMetric(c.goInfoDesc, GaugeValue, 1)

	ms := &runtime.MemStats{}
	runtime.ReadMemStats(ms)
	for _, i := range c.metrics {
		ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
	}
}

// memStatsMetrics provide description, value, and value type for memstat metrics.
type memStatsMetrics []struct {
	desc    *Desc
	eval    func(*runtime.MemStats) float64
	valType ValueType
}
<commit_msg>Remove unnecessary conversion<commit_after>package prometheus

import (
	"fmt"
	"runtime"
	"runtime/debug"
	"time"
)

type goCollector struct {
	goroutinesDesc *Desc
	threadsDesc    *Desc
	gcDesc         *Desc
	goInfoDesc     *Desc

	// metrics to describe and collect
	metrics memStatsMetrics
}

// NewGoCollector returns a collector which exports metrics about the current
// go process.
func NewGoCollector() Collector {
	return &goCollector{
		goroutinesDesc: NewDesc(
			"go_goroutines",
			"Number of goroutines that currently exist.",
			nil, nil),
		threadsDesc: NewDesc(
			"go_threads",
			"Number of OS threads created.",
			nil, nil),
		gcDesc: NewDesc(
			"go_gc_duration_seconds",
			"A summary of the GC invocation durations.",
			nil, nil),
		goInfoDesc: NewDesc(
			"go_info",
			"Information about the Go environment.",
			nil, Labels{"version": runtime.Version()}),
		metrics: memStatsMetrics{
			{
				desc: NewDesc(
					memstatNamespace("alloc_bytes"),
					"Number of bytes allocated and still in use.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Alloc) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("alloc_bytes_total"),
					"Total number of bytes allocated, even if freed.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.TotalAlloc) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("sys_bytes"),
					"Number of bytes obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Sys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("lookups_total"),
					"Total number of pointer lookups.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Lookups) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mallocs_total"),
					"Total number of mallocs.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Mallocs) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("frees_total"),
					"Total number of frees.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.Frees) },
				valType: CounterValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_alloc_bytes"),
					"Number of heap bytes allocated and still in use.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapAlloc) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_sys_bytes"),
					"Number of heap bytes obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_idle_bytes"),
					"Number of heap bytes waiting to be used.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapIdle) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_inuse_bytes"),
					"Number of heap bytes that are in use.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_released_bytes"),
					"Number of heap bytes released to OS.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapReleased) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("heap_objects"),
					"Number of allocated objects.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.HeapObjects) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("stack_inuse_bytes"),
					"Number of bytes in use by the stack allocator.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.StackInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("stack_sys_bytes"),
					"Number of bytes obtained from system for stack allocator.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.StackSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mspan_inuse_bytes"),
					"Number of bytes in use by mspan structures.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MSpanInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mspan_sys_bytes"),
					"Number of bytes used for mspan structures obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MSpanSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mcache_inuse_bytes"),
					"Number of bytes in use by mcache structures.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MCacheInuse) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("mcache_sys_bytes"),
					"Number of bytes used for mcache structures obtained from system.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.MCacheSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("buck_hash_sys_bytes"),
					"Number of bytes used by the profiling bucket hash table.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.BuckHashSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("gc_sys_bytes"),
					"Number of bytes used for garbage collection system metadata.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.GCSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("other_sys_bytes"),
					"Number of bytes used for other system allocations.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.OtherSys) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("next_gc_bytes"),
					"Number of heap bytes when next garbage collection will take place.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.NextGC) },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("last_gc_time_seconds"),
					"Number of seconds since 1970 of last garbage collection.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return float64(ms.LastGC) / 1e9 },
				valType: GaugeValue,
			}, {
				desc: NewDesc(
					memstatNamespace("gc_cpu_fraction"),
					"The fraction of this program's available CPU time used by the GC since the program started.",
					nil, nil,
				),
				eval:    func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction },
				valType: GaugeValue,
			},
		},
	}
}

func memstatNamespace(s string) string {
	return fmt.Sprintf("go_memstats_%s", s)
}

// Describe returns all descriptions of the collector.
func (c *goCollector) Describe(ch chan<- *Desc) {
	ch <- c.goroutinesDesc
	ch <- c.threadsDesc
	ch <- c.gcDesc
	ch <- c.goInfoDesc
	for _, i := range c.metrics {
		ch <- i.desc
	}
}

// Collect returns the current state of all metrics of the collector.
func (c *goCollector) Collect(ch chan<- Metric) {
	ch <- MustNewConstMetric(c.goroutinesDesc, GaugeValue, float64(runtime.NumGoroutine()))
	n, _ := runtime.ThreadCreateProfile(nil)
	ch <- MustNewConstMetric(c.threadsDesc, GaugeValue, float64(n))

	var stats debug.GCStats
	stats.PauseQuantiles = make([]time.Duration, 5)
	debug.ReadGCStats(&stats)

	quantiles := make(map[float64]float64)
	for idx, pq := range stats.PauseQuantiles[1:] {
		quantiles[float64(idx+1)/float64(len(stats.PauseQuantiles)-1)] = pq.Seconds()
	}
	quantiles[0.0] = stats.PauseQuantiles[0].Seconds()
	ch <- MustNewConstSummary(c.gcDesc, uint64(stats.NumGC), stats.PauseTotal.Seconds(), quantiles)

	ch <- MustNewConstMetric(c.goInfoDesc, GaugeValue, 1)

	ms := &runtime.MemStats{}
	runtime.ReadMemStats(ms)
	for _, i := range c.metrics {
		ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
	}
}

// memStatsMetrics provide description, value, and value type for memstat metrics.
type memStatsMetrics []struct {
	desc    *Desc
	eval    func(*runtime.MemStats) float64
	valType ValueType
}
<|endoftext|>


<commit_before>package gozfs

import (
	"bytes"
	"syscall"

	"github.com/mistifyio/gozfs/nv"
)

func exists(name string) error {
	m := map[string]interface{}{
		"cmd":     "zfs_exists",
		"version": uint64(0),
	}

	encoded := &bytes.Buffer{}
	err := nv.NewNativeEncoder(encoded).Encode(m)
	if err != nil {
		return err
	}

	return ioctl(zfs, name, encoded.Bytes(), nil)
}

// Exists determines whether a dataset exists or not.
func Exists(name string) (bool, error) {
	if err := exists(name); err != nil {
		if err.Error() == syscall.ENOENT.Error() {
			err = nil
		}
		return false, err
	}
	return true, nil
}
<commit_msg>Compare exist errors directly<commit_after>package gozfs

import (
	"bytes"
	"syscall"

	"github.com/mistifyio/gozfs/nv"
)

func exists(name string) error {
	m := map[string]interface{}{
		"cmd":     "zfs_exists",
		"version": uint64(0),
	}

	encoded := &bytes.Buffer{}
	err := nv.NewNativeEncoder(encoded).Encode(m)
	if err != nil {
		return err
	}

	return ioctl(zfs, name, encoded.Bytes(), nil)
}

// Exists determines whether a dataset exists or not.
func Exists(name string) (bool, error) {
	if err := exists(name); err != nil {
		if err == syscall.ENOENT {
			err = nil
		}
		return false, err
	}
	return true, nil
}
<|endoftext|>


<commit_before>package vm

import "testing"

func TestCreateBaseClass(t *testing.T) {
	className := "Integer"
	c := createBaseClass(className)
	if c.Name != className {
		t.Fatalf("Expect createBaseClass(\"%v\") to return a %v class", className, className)
	}
}

func TestMonkeyPatchBuiltInClass(t *testing.T) {
	input := `
	class String
	  def buz
	    "buz"
	  end
	end

	"123".buz
	`

	evaluated := testEval(t, input)
	checkExpected(t, evaluated, "buz")
}

func TestRequireRelative(t *testing.T) {
	input := `
	require_relative("../test_fixtures/require_test/foo")

	fifty = Foo.bar(5)

	Foo.baz do |hundred|
	  hundred + fifty + Bar.baz
	end
	`

	evaluated := testEval(t, input)
	testIntegerObject(t, evaluated, 160)
}

func TestDefSingletonMethtod(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{`
		class Foo
		  def self.bar
		    10
		  end
		end

		Foo.bar
		`, 10},
		{`
		module Foo
		  def self.bar
		    10
		  end
		end

		Foo.bar
		`, 10},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s.\n Input %s", evaluated.(*Error).Message, tt.input)
		}

		testIntegerObject(t, evaluated, tt.expected)
	}
}

func TestAttrReaderAndWriter(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{`
		class Foo
		  attr_reader("bar")

		  def set_bar(bar)
		    @bar = bar
		  end
		end

		f = Foo.new
		f.set_bar(10)
		f.bar

		`, 10},
		{`
		class Foo
		  attr_writer("bar")

		  def bar
		    @bar
		  end
		end

		f = Foo.new
		f.bar = 10
		f.bar

		`, 10},
		{`
		class Foo
		  attr_writer("bar")
		  attr_reader("bar")
		end

		f = Foo.new
		f.bar = 10
		f.bar

		`, 10},
		{`
		class Foo
		  attr_accessor("bar")
		end

		f = Foo.new
		f.bar = 10
		f.bar

		`, 10},
		{`
		class Foo
		  attr_accessor("foo", "bar")
		end

		f = Foo.new
		f.bar = 10
		f.foo = 100
		f.bar + f.foo

		`, 110},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s.\n Input %s", evaluated.(*Error).Message, tt.input)
		}

		testIntegerObject(t, evaluated, tt.expected)
	}
}

func TestNamespace(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{`
		module Foo
		  class Bar
		    def bar
		      10
		    end
		  end
		end

		Foo::Bar.new.bar
		`, 10},
		{`
		class Foo
		  class Bar
		    def bar
		      10
		    end
		  end
		end

		Foo::Bar.new.bar
		`, 10},
		{`
		class Foo
		  def bar
		    100
		  end

		  class Bar
		    def bar
		      10
		    end
		  end
		end

		Foo.new.bar + Foo::Bar.new.bar
		`, 110},
		{`
		class Foo
		  def bar
		    100
		  end
		end

		module Baz
		  class Bar
		    def bar
		      Foo.new.bar
		    end
		  end
		end

		Baz::Bar.new.bar
		`, 100},
		{`
		module Baz
		  class Bar
		    class Foo
		      def bar
			100
		      end
		    end
		  end
		end

		Baz::Bar::Foo.new.bar
		`, 100},
		{`
		module Baz
		  class Foo
		    def bar
		      100
		    end
		  end

		  class Bar
		    def bar
		      Foo.new.bar
		    end
		  end
		end

		Baz::Bar.new.bar
		`, 100},
		{`
		module Baz
		  class Bar
		    def bar
		      Foo.new.bar
		    end

		    class Foo
		      def bar
			100
		      end
		    end
		  end
		end

		Baz::Bar.new.bar
		`, 100},
		{`
		module Foo
		  class Bar
		    def bar
		      10
		    end
		  end
		end

		module Baz
		  class Bar < Foo::Bar
		    def foo
		      100
		    end
		  end
		end

		b = Baz::Bar.new
		b.foo + b.bar
		`, 110},
		{`
		module A
		  class B
		    class C
		      class D
		        def e
		          10
		        end
		      end
		    end
		  end
		end

		A::B::C::D.new.e
		`, 10},
		{`
		class Foo
		  def self.bar
		    10
		  end
		end

		Object::Foo.bar
		`, 10},

		{`
		Foo = 10

		Object::Foo
		`, 10},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s.\n Input %s", evaluated.(*Error).Message, tt.input)
		}

		testIntegerObject(t, evaluated, tt.expected)
	}
}

func TestRequireSuccess(t *testing.T) {
	input := `
	require "file"

	File.extname("foo.rb")
	`
	evaluated := testEval(t, input)

	if isError(evaluated) {
		t.Fatalf("got Error: %s", evaluated.(*Error).Message)
	}

	testStringObject(t, evaluated, ".rb")

}

func TestRequireFail(t *testing.T) {
	input := `
	require "bar"
	`
	expected := `Can't require "bar"`

	evaluated := testEval(t, input)

	if !isError(evaluated) {
		t.Fatalf("Should return an error")
	}

	if evaluated.(*Error).Message != expected {
		t.Fatalf("Error message should be '%s'", expected)
	}
}

func TestPrimitiveType(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{
			`100.class.name
			`,
			"Integer",
		},
		{
			`Integer.name
			`,
			"Integer",
		},
		{
			`"123".class.name
			`,
			"String",
		},
		{
			`String.name
			`,
			"String",
		},
		{
			`true.class.name
			`,
			"Boolean",
		},
		{
			`Boolean.name
			`,
			"Boolean",
		},
		{
			`
			nil.class.name
			`,
			"Null",
		},
		{
			`
			Integer.name
			`,
			"Integer",
		},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s", evaluated.(*Error).Message)
		}

		testStringObject(t, evaluated, tt.expected)
	}
}

func TestEvalCustomConstructor(t *testing.T) {
	input := `
		class Foo
			def initialize(x, y)
				@x = x
				@y = y
			end

			def bar
				@x + @y
			end
		end

		f = Foo.new(10, 20)
		f.bar
	`

	evaluated := testEval(t, input)

	if isError(evaluated) {
		t.Fatalf("got Error: %s", evaluated.(*Error).Message)
	}

	result, ok := evaluated.(*IntegerObject)

	if !ok {
		t.Errorf("expect result to be an integer. got=%T", evaluated)
	}

	if result.Value != 30 {
		t.Errorf("expect result to be 30. got=%d", result.Value)
	}
}

func TestClassInheritModule(t *testing.T) {
	input := `
module Foo
end

class Bar < Foo
end

a = Bar.new()
	`
	expected := `Module inheritance is not supported: Foo`

	evaluated := testEval(t, input)

	if !isError(evaluated) {
		t.Fatalf("Should return an error when a class inherits a module")
	}

	if evaluated.(*Error).Message != expected {
		t.Fatalf("Error message should be '%s'\n result %s", expected, evaluated)
	}
}
<commit_msg>Update attribute reader/writer test case's syntax.<commit_after>package vm

import "testing"

func TestCreateBaseClass(t *testing.T) {
	className := "Integer"
	c := createBaseClass(className)
	if c.Name != className {
		t.Fatalf("Expect createBaseClass(\"%v\") to return a %v class", className, className)
	}
}

func TestMonkeyPatchBuiltInClass(t *testing.T) {
	input := `
	class String
	  def buz
	    "buz"
	  end
	end

	"123".buz
	`

	evaluated := testEval(t, input)
	checkExpected(t, evaluated, "buz")
}

func TestRequireRelative(t *testing.T) {
	input := `
	require_relative("../test_fixtures/require_test/foo")

	fifty = Foo.bar(5)

	Foo.baz do |hundred|
	  hundred + fifty + Bar.baz
	end
	`

	evaluated := testEval(t, input)
	testIntegerObject(t, evaluated, 160)
}

func TestDefSingletonMethtod(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{`
		class Foo
		  def self.bar
		    10
		  end
		end

		Foo.bar
		`, 10},
		{`
		module Foo
		  def self.bar
		    10
		  end
		end

		Foo.bar
		`, 10},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s.\n Input %s", evaluated.(*Error).Message, tt.input)
		}

		testIntegerObject(t, evaluated, tt.expected)
	}
}

func TestAttrReaderAndWriter(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{`
		class Foo
		  attr_reader :bar

		  def set_bar(bar)
		    @bar = bar
		  end
		end

		f = Foo.new
		f.set_bar(10)
		f.bar

		`, 10},
		{`
		class Foo
		  attr_writer :bar

		  def bar
		    @bar
		  end
		end

		f = Foo.new
		f.bar = 10
		f.bar

		`, 10},
		{`
		class Foo
		  attr_writer :bar
		  attr_reader :bar
		end

		f = Foo.new
		f.bar = 10
		f.bar

		`, 10},
		{`
		class Foo
		  attr_accessor :bar
		end

		f = Foo.new
		f.bar = 10
		f.bar

		`, 10},
		{`
		class Foo
		  attr_accessor :foo, :bar
		end

		f = Foo.new
		f.bar = 10
		f.foo = 100
		f.bar + f.foo

		`, 110},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s.\n Input %s", evaluated.(*Error).Message, tt.input)
		}

		testIntegerObject(t, evaluated, tt.expected)
	}
}

func TestNamespace(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{`
		module Foo
		  class Bar
		    def bar
		      10
		    end
		  end
		end

		Foo::Bar.new.bar
		`, 10},
		{`
		class Foo
		  class Bar
		    def bar
		      10
		    end
		  end
		end

		Foo::Bar.new.bar
		`, 10},
		{`
		class Foo
		  def bar
		    100
		  end

		  class Bar
		    def bar
		      10
		    end
		  end
		end

		Foo.new.bar + Foo::Bar.new.bar
		`, 110},
		{`
		class Foo
		  def bar
		    100
		  end
		end

		module Baz
		  class Bar
		    def bar
		      Foo.new.bar
		    end
		  end
		end

		Baz::Bar.new.bar
		`, 100},
		{`
		module Baz
		  class Bar
		    class Foo
		      def bar
			100
		      end
		    end
		  end
		end

		Baz::Bar::Foo.new.bar
		`, 100},
		{`
		module Baz
		  class Foo
		    def bar
		      100
		    end
		  end

		  class Bar
		    def bar
		      Foo.new.bar
		    end
		  end
		end

		Baz::Bar.new.bar
		`, 100},
		{`
		module Baz
		  class Bar
		    def bar
		      Foo.new.bar
		    end

		    class Foo
		      def bar
			100
		      end
		    end
		  end
		end

		Baz::Bar.new.bar
		`, 100},
		{`
		module Foo
		  class Bar
		    def bar
		      10
		    end
		  end
		end

		module Baz
		  class Bar < Foo::Bar
		    def foo
		      100
		    end
		  end
		end

		b = Baz::Bar.new
		b.foo + b.bar
		`, 110},
		{`
		module A
		  class B
		    class C
		      class D
		        def e
		          10
		        end
		      end
		    end
		  end
		end

		A::B::C::D.new.e
		`, 10},
		{`
		class Foo
		  def self.bar
		    10
		  end
		end

		Object::Foo.bar
		`, 10},

		{`
		Foo = 10

		Object::Foo
		`, 10},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s.\n Input %s", evaluated.(*Error).Message, tt.input)
		}

		testIntegerObject(t, evaluated, tt.expected)
	}
}

func TestRequireSuccess(t *testing.T) {
	input := `
	require "file"

	File.extname("foo.rb")
	`
	evaluated := testEval(t, input)

	if isError(evaluated) {
		t.Fatalf("got Error: %s", evaluated.(*Error).Message)
	}

	testStringObject(t, evaluated, ".rb")

}

func TestRequireFail(t *testing.T) {
	input := `
	require "bar"
	`
	expected := `Can't require "bar"`

	evaluated := testEval(t, input)

	if !isError(evaluated) {
		t.Fatalf("Should return an error")
	}

	if evaluated.(*Error).Message != expected {
		t.Fatalf("Error message should be '%s'", expected)
	}
}

func TestPrimitiveType(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{
			`100.class.name
			`,
			"Integer",
		},
		{
			`Integer.name
			`,
			"Integer",
		},
		{
			`"123".class.name
			`,
			"String",
		},
		{
			`String.name
			`,
			"String",
		},
		{
			`true.class.name
			`,
			"Boolean",
		},
		{
			`Boolean.name
			`,
			"Boolean",
		},
		{
			`
			nil.class.name
			`,
			"Null",
		},
		{
			`
			Integer.name
			`,
			"Integer",
		},
	}

	for _, tt := range tests {
		evaluated := testEval(t, tt.input)

		if isError(evaluated) {
			t.Fatalf("got Error: %s", evaluated.(*Error).Message)
		}

		testStringObject(t, evaluated, tt.expected)
	}
}

func TestEvalCustomConstructor(t *testing.T) {
	input := `
		class Foo
			def initialize(x, y)
				@x = x
				@y = y
			end

			def bar
				@x + @y
			end
		end

		f = Foo.new(10, 20)
		f.bar
	`

	evaluated := testEval(t, input)

	if isError(evaluated) {
		t.Fatalf("got Error: %s", evaluated.(*Error).Message)
	}

	result, ok := evaluated.(*IntegerObject)

	if !ok {
		t.Errorf("expect result to be an integer. got=%T", evaluated)
	}

	if result.Value != 30 {
		t.Errorf("expect result to be 30. got=%d", result.Value)
	}
}

func TestClassInheritModule(t *testing.T) {
	input := `
module Foo
end

class Bar < Foo
end

a = Bar.new()
	`
	expected := `Module inheritance is not supported: Foo`

	evaluated := testEval(t, input)

	if !isError(evaluated) {
		t.Fatalf("Should return an error when a class inherits a module")
	}

	if evaluated.(*Error).Message != expected {
		t.Fatalf("Error message should be '%s'\n result %s", expected, evaluated)
	}
}
<|endoftext|>


<commit_before>package models

import (
	"github.com/jinzhu/gorm"
	"net/url"
	"time"
)

type Image struct {
	gorm.Model
	Src    string    `json:"src"`
	Tags   []Tag     `sql:"many2many:images_tags"`
	Date   time.Time `sql:"not null" json:"date"`
	ChatID uint64    `sql:"not null" json:"-"`
	//OtherID uint64
	Chat Chat `gorm:"ForeignKey:TGID;AssociationForeignKey:ChatID"`
}

func (img *Image) GetImgByParams(db *gorm.DB, params url.Values) ([]Image, error) {
	img_slice := []Image{}
	q_tmp := db.Model(&Image{}).Preload("Tags").Preload("Chat")

	chat_id, ok := params["chat_id"]
	if ok {
		q_tmp = q_tmp.Where("chat_id = ?", chat_id[0])
	}
	date_from, ok := params["date_to"]
	if ok {
		q_tmp = q_tmp.Where("date > ?", date_from[0])
	}
	date_to, ok := params["date_to"]
	if ok {
		q_tmp = q_tmp.Where("date < ?", date_to[0])
	}

	if q_tmp.Find(&img_slice).RecordNotFound() {
		return nil, db.Error
	}

	if err := db.Error; err != nil {
		return nil, err
	}

	return img_slice, nil
}
<commit_msg>aftercommit-fix<commit_after>package models

import (
	"github.com/jinzhu/gorm"
	"net/url"
	"time"
)

type Image struct {
	gorm.Model
	Src    string    `json:"src"`
	Tags   []Tag     `sql:"many2many:images_tags"`
	Date   time.Time `sql:"not null" json:"date"`
	ChatID uint64    `sql:"not null" json:"-"`
	//OtherID uint64
	Chat Chat `gorm:"ForeignKey:TGID;AssociationForeignKey:ChatID"`
}

func (img *Image) GetImgByParams(db *gorm.DB, params url.Values) ([]Image, error) {
	img_slice := []Image{}
	q_tmp := db.Model(&Image{}).Preload("Tags").Preload("Chat")

	chat_id, ok := params["chat_id"]
	if ok {
		q_tmp = q_tmp.Where("chat_id = ?", chat_id[0])
	}
	date_from, ok := params["date_to"]
	if ok {
		q_tmp = q_tmp.Where("date > ?", date_from[0])
	}
	date_to, ok := params["date_to"]
	if ok {
		q_tmp = q_tmp.Where("date < ?", date_to[0])
	}

	if q_tmp.Find(&img_slice).RecordNotFound() {
		return nil, db.Error
	}

	if err := db.Error; err != nil {
		return nil, err
	}

	return img_slice, nil
}

//TODO: call exorcist on this pile of unholy shit
func (img *Image) CreateImageWithTags(db *gorm.DB, ts []string) error{
	var tags []*Tag
	for _, t := range ts {
		tags = append(tags, &Tag{Name: t})
	}
	tx := db.Begin()
	for _,t := range tags{
		if err := db.Set("gorm:insert_options", "ON CONFLICT (name) DO NOTHING").Save(t).Error;
			err != nil{
			tx.Rollback()
			return err
		}
		img.Tags = append(img.Tags, *t)
	}
	if err := db.Save(img).Error; err != nil{
		tx.Rollback()
		return err
	}
	return nil
}<|endoftext|>


<commit_before>package models

import (
	"github.com/eirka/eirka-libs/config"
	"github.com/eirka/eirka-libs/db"
	e "github.com/eirka/eirka-libs/errors"

	u "github.com/eirka/eirka-get/utils"
)

// IndexModel holds the parameters from the request and also the key for the cache
type IndexModel struct {
	Ib      uint
	Page    uint
	Threads uint
	Posts   uint
	Result  IndexType
}

// ThreadIds holds all the thread ids for the loop that gets the posts
type ThreadIds struct {
	Id     uint
	Title  string
	Closed bool
	Sticky bool
	Total  uint
	Images uint
}

// IndexType is the top level of the JSON response
type IndexType struct {
	Body u.PagedResponse `json:"index"`
}

// IndexThreadHeader holds the information for the threads
type IndexThreadHeader struct {
	Id     uint          `json:"id"`
	Title  string        `json:"title"`
	Closed bool          `json:"closed"`
	Sticky bool          `json:"sticky"`
	Total  uint          `json:"total"`
	Images uint          `json:"images"`
	Pages  uint          `json:"pages"`
	Posts  []ThreadPosts `json:"posts"`
}

// Get will gather the information from the database and return it as JSON serialized data
func (i *IndexModel) Get() (err error) {

	if i.Ib == 0 || i.Page == 0 {
		return e.ErrNotFound
	}

	// Initialize response header
	response := IndexType{}

	// Initialize struct for pagination
	paged := u.PagedResponse{}
	// Set current page to parameter
	paged.CurrentPage = i.Page
	// Set threads per index page to config setting
	paged.PerPage = i.Threads

	// Initialize struct for all thread ids
	thread_ids := []ThreadIds{}

	// Get Database handle
	dbase, err := db.GetDb()
	if err != nil {
		return
	}

	var ibs uint

	// Get total thread count and put it in pagination struct
	err = dbase.QueryRow(`SELECT (SELECT count(*) FROM imageboards) as imageboards,
    (select count(*) from threads where ib_id = ? AND thread_deleted != 1) as threads`, i.Ib).Scan(&ibs, &paged.Total)
	if err != nil {
		return
	}

	// Calculate Limit and total Pages
	paged.Get()

	// Return 404 if page requested is larger than actual pages
	if i.Page > paged.Pages || i.Ib > ibs {
		return e.ErrNotFound
	}

	// Get all thread ids with limit
	thread_id_rows, err := dbase.Query(`SELECT thread_id,thread_title,thread_closed,thread_sticky,posts,images FROM
    (SELECT threads.thread_id,thread_title,thread_closed,thread_sticky,count(posts.post_id) as posts,count(image_id) as images,
    (select max(post_time) from posts where thread_id=threads.thread_id AND post_deleted != 1) as thread_last_post
    FROM threads
    INNER JOIN posts on threads.thread_id = posts.thread_id
    LEFT JOIN images on posts.post_id = images.post_id
    WHERE ib_id = ? AND thread_deleted != 1 AND post_deleted != 1
    GROUP BY threads.thread_id
    ORDER BY thread_sticky = 1 DESC, thread_last_post DESC LIMIT ?,?) as threads`, i.Ib, paged.Limit, i.Threads)
	if err != nil {
		return
	}
	defer thread_id_rows.Close()

	for thread_id_rows.Next() {
		// Initialize posts struct
		thread_id_row := ThreadIds{}
		// Scan rows and place column into struct
		err := thread_id_rows.Scan(&thread_id_row.Id, &thread_id_row.Title, &thread_id_row.Closed, &thread_id_row.Sticky, &thread_id_row.Total, &thread_id_row.Images)
		if err != nil {
			return err
		}
		// Append rows to info struct
		thread_ids = append(thread_ids, thread_id_row)
	}
	if thread_id_rows.Err() != nil {
		return
	}

	//Get last thread posts
	ps1, err := dbase.Prepare(`SELECT * FROM
    (SELECT posts.post_id,post_num,user_name,users.user_id,
    COALESCE((SELECT MAX(role_id) FROM user_ib_role_map WHERE user_ib_role_map.user_id = users.user_id AND ib_id = ?),user_role_map.role_id) as role,
    post_time,post_text,image_id,image_file,image_thumbnail,image_tn_height,image_tn_width
    FROM posts
    LEFT JOIN images ON (posts.post_id = images.post_id)
    INNER JOIN users ON (posts.user_id = users.user_id)
    INNER JOIN user_role_map ON (user_role_map.user_id = users.user_id)
    WHERE posts.thread_id = ? AND post_deleted != 1
    ORDER BY post_num DESC LIMIT ?) AS p
    ORDER BY post_num ASC`)
	if err != nil {
		return
	}
	defer ps1.Close()

	// Initialize slice for threads
	threads := []IndexThreadHeader{}

	// Loop over the values of thread_ids
	for _, id := range thread_ids {

		// Get last page from thread
		postpages := u.PagedResponse{}
		postpages.Total = id.Total
		postpages.CurrentPage = 1
		postpages.PerPage = config.Settings.Limits.PostsPerPage
		postpages.Get()

		// Set thread fields
		thread := IndexThreadHeader{
			Id:     id.Id,
			Title:  id.Title,
			Closed: id.Closed,
			Sticky: id.Sticky,
			Total:  id.Total,
			Images: id.Images,
			Pages:  postpages.Pages,
		}

		e1, err := ps1.Query(i.Ib, id.Id, i.Posts)
		if err != nil {
			return err
		}
		defer e1.Close()

		for e1.Next() {
			// Initialize posts struct
			post := ThreadPosts{}
			// Scan rows and place column into struct
			err := e1.Scan(&post.Id, &post.Num, &post.Name, &post.Uid, &post.Group, &post.Time, &post.Text, &post.ImgId, &post.File, &post.Thumb, &post.ThumbHeight, &post.ThumbWidth)
			if err != nil {
				return err
			}
			// Append rows to info struct
			thread.Posts = append(thread.Posts, post)
		}
		if e1.Err() != nil {
			return e1.Err()
		}

		threads = append(threads, thread)
	}

	// Add threads slice to items interface
	paged.Items = threads

	// Add pagedresponse to the response struct
	response.Body = paged

	// This is the data we will serialize
	i.Result = response

	return

}
<commit_msg>sort index posts by post_id<commit_after>package models

import (
	"github.com/eirka/eirka-libs/config"
	"github.com/eirka/eirka-libs/db"
	e "github.com/eirka/eirka-libs/errors"

	u "github.com/eirka/eirka-get/utils"
)

// IndexModel holds the parameters from the request and also the key for the cache
type IndexModel struct {
	Ib      uint
	Page    uint
	Threads uint
	Posts   uint
	Result  IndexType
}

// ThreadIds holds all the thread ids for the loop that gets the posts
type ThreadIds struct {
	Id     uint
	Title  string
	Closed bool
	Sticky bool
	Total  uint
	Images uint
}

// IndexType is the top level of the JSON response
type IndexType struct {
	Body u.PagedResponse `json:"index"`
}

// IndexThreadHeader holds the information for the threads
type IndexThreadHeader struct {
	Id     uint          `json:"id"`
	Title  string        `json:"title"`
	Closed bool          `json:"closed"`
	Sticky bool          `json:"sticky"`
	Total  uint          `json:"total"`
	Images uint          `json:"images"`
	Pages  uint          `json:"pages"`
	Posts  []ThreadPosts `json:"posts"`
}

// Get will gather the information from the database and return it as JSON serialized data
func (i *IndexModel) Get() (err error) {

	if i.Ib == 0 || i.Page == 0 {
		return e.ErrNotFound
	}

	// Initialize response header
	response := IndexType{}

	// Initialize struct for pagination
	paged := u.PagedResponse{}
	// Set current page to parameter
	paged.CurrentPage = i.Page
	// Set threads per index page to config setting
	paged.PerPage = i.Threads

	// Initialize struct for all thread ids
	thread_ids := []ThreadIds{}

	// Get Database handle
	dbase, err := db.GetDb()
	if err != nil {
		return
	}

	var ibs uint

	// Get total thread count and put it in pagination struct
	err = dbase.QueryRow(`SELECT (SELECT count(*) FROM imageboards) as imageboards,
    (select count(*) from threads where ib_id = ? AND thread_deleted != 1) as threads`, i.Ib).Scan(&ibs, &paged.Total)
	if err != nil {
		return
	}

	// Calculate Limit and total Pages
	paged.Get()

	// Return 404 if page requested is larger than actual pages
	if i.Page > paged.Pages || i.Ib > ibs {
		return e.ErrNotFound
	}

	// Get all thread ids with limit
	thread_id_rows, err := dbase.Query(`SELECT thread_id,thread_title,thread_closed,thread_sticky,posts,images FROM
    (SELECT threads.thread_id,thread_title,thread_closed,thread_sticky,count(posts.post_id) as posts,count(image_id) as images,
    (select max(post_time) from posts where thread_id=threads.thread_id AND post_deleted != 1) as thread_last_post
    FROM threads
    INNER JOIN posts on threads.thread_id = posts.thread_id
    LEFT JOIN images on posts.post_id = images.post_id
    WHERE ib_id = ? AND thread_deleted != 1 AND post_deleted != 1
    GROUP BY threads.thread_id
    ORDER BY thread_sticky = 1 DESC, thread_last_post DESC LIMIT ?,?) as threads`, i.Ib, paged.Limit, i.Threads)
	if err != nil {
		return
	}
	defer thread_id_rows.Close()

	for thread_id_rows.Next() {
		// Initialize posts struct
		thread_id_row := ThreadIds{}
		// Scan rows and place column into struct
		err := thread_id_rows.Scan(&thread_id_row.Id, &thread_id_row.Title, &thread_id_row.Closed, &thread_id_row.Sticky, &thread_id_row.Total, &thread_id_row.Images)
		if err != nil {
			return err
		}
		// Append rows to info struct
		thread_ids = append(thread_ids, thread_id_row)
	}
	if thread_id_rows.Err() != nil {
		return
	}

	//Get last thread posts
	ps1, err := dbase.Prepare(`SELECT * FROM
    (SELECT posts.post_id,post_num,user_name,users.user_id,
    COALESCE((SELECT MAX(role_id) FROM user_ib_role_map WHERE user_ib_role_map.user_id = users.user_id AND ib_id = ?),user_role_map.role_id) as role,
    post_time,post_text,image_id,image_file,image_thumbnail,image_tn_height,image_tn_width
    FROM posts
    LEFT JOIN images ON (posts.post_id = images.post_id)
    INNER JOIN users ON (posts.user_id = users.user_id)
    INNER JOIN user_role_map ON (user_role_map.user_id = users.user_id)
    WHERE posts.thread_id = ? AND post_deleted != 1
    ORDER BY post_id DESC LIMIT ?) AS p
    ORDER BY post_id ASC`)
	if err != nil {
		return
	}
	defer ps1.Close()

	// Initialize slice for threads
	threads := []IndexThreadHeader{}

	// Loop over the values of thread_ids
	for _, id := range thread_ids {

		// Get last page from thread
		postpages := u.PagedResponse{}
		postpages.Total = id.Total
		postpages.CurrentPage = 1
		postpages.PerPage = config.Settings.Limits.PostsPerPage
		postpages.Get()

		// Set thread fields
		thread := IndexThreadHeader{
			Id:     id.Id,
			Title:  id.Title,
			Closed: id.Closed,
			Sticky: id.Sticky,
			Total:  id.Total,
			Images: id.Images,
			Pages:  postpages.Pages,
		}

		e1, err := ps1.Query(i.Ib, id.Id, i.Posts)
		if err != nil {
			return err
		}
		defer e1.Close()

		for e1.Next() {
			// Initialize posts struct
			post := ThreadPosts{}
			// Scan rows and place column into struct
			err := e1.Scan(&post.Id, &post.Num, &post.Name, &post.Uid, &post.Group, &post.Time, &post.Text, &post.ImgId, &post.File, &post.Thumb, &post.ThumbHeight, &post.ThumbWidth)
			if err != nil {
				return err
			}
			// Append rows to info struct
			thread.Posts = append(thread.Posts, post)
		}
		if e1.Err() != nil {
			return e1.Err()
		}

		threads = append(threads, thread)
	}

	// Add threads slice to items interface
	paged.Items = threads

	// Add pagedresponse to the response struct
	response.Body = paged

	// This is the data we will serialize
	i.Result = response

	return

}
<|endoftext|>


<commit_before>package models

import (
	"github.com/Luncher/go-rest/db"
	"github.com/Luncher/go-rest/forms"
	"gopkg.in/mgo.v2/bson"
)

type Movie struct {
	Id     bson.ObjectId `json:"id"		bson:"_id,omiempty"`
	Name   string        `json:name`
	Rating float32       `json:rating`
	Desc   string        `json:desc`
}

type MovieModel struct{}

var dbConnect = db.NewConnection("localhost")

func (m *MovieModel) Create(data forms.CreateMovieCommand) error {
	collection := dbConnect.Use("test-mgo", "movies")
	err := collection.Insert(bson.M{"name": data.Name, "rating": data.Rating, "desc": data.Desc})
	return err
}

func (m *MovieModel) Get(id string) (movie Movie, err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.FindId(id).One(&movie)
	return movie, err
}

func (m *MovieModel) Find() (list []Movie, err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.Find(bson.M{}).All(&list)
	return list, err
}

func (m *MovieModel) Update(id string, data forms.UpdateMovieCommand) (err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.UpdateId(id, data)

	return err
}

func (m *MovieModel) Delete(id string) (err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.RemoveId(id)

	return err
}
<commit_msg>sync latest code<commit_after>package models

import (
	"github.com/Luncher/go-rest/db"
	"github.com/Luncher/go-rest/forms"
	"gopkg.in/mgo.v2/bson"
)

type Movie struct {
	Id     bson.ObjectId `json:"_id"		bson:"_id,omitempty"`
	Name   string        `json:name`
	Rating float32       `json:rating`
	Desc   string        `json:desc`
}

type MovieModel struct{}

var dbConnect = db.NewConnection("localhost")

func (m *MovieModel) Create(data forms.CreateMovieCommand) error {
	collection := dbConnect.Use("test-mgo", "movies")
	err := collection.Insert(bson.M{"name": data.Name, "rating": data.Rating, "desc": data.Desc})
	return err
}

func (m *MovieModel) Get(id string) (movie Movie, err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.FindId(id).One(&movie)
	return movie, err
}

func (m *MovieModel) Find() (list []Movie, err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.Find(bson.M{}).All(&list)
	return list, err
}

func (m *MovieModel) Update(id string, data forms.UpdateMovieCommand) (err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.UpdateId(id, data)

	return err
}

func (m *MovieModel) Delete(id string) (err error) {
	collection := dbConnect.Use("test-mgo", "movies")
	err = collection.RemoveId(id)

	return err
}
<|endoftext|>


<commit_before>package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"encoding/json"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// Route route
// swagger:model Route
type Route struct {

	// Route configuration - overrides application configuration
	Config map[string]string `json:"config,omitempty"`

	// Payload format sent into function.
	Format interface{} `json:"format,omitempty"`

	// Map of http headers that will be sent with the response
	Headers map[string][]string `json:"headers,omitempty"`

	// Hot functions idle timeout before termination. Value in Seconds
	IDLETimeout *int64 `json:"idle_timeout,omitempty"`

	// Name of Docker image to use in this route. You should include the image tag, which should be a version number, to be more accurate. Can be overridden on a per route basis with route.image.
	Image string `json:"image,omitempty"`

	// Maximum number of hot functions concurrency
	MaxConcurrency int32 `json:"max_concurrency,omitempty"`

	// Max usable memory for this route (MiB).
	Memory int64 `json:"memory,omitempty"`

	// URL path that will be matched to this route
	// Read Only: true
	Path string `json:"path,omitempty"`

	// Timeout for executions of this route. Value in Seconds
	Timeout *int64 `json:"timeout,omitempty"`

	// Route type
	Type interface{} `json:"type,omitempty"`
}

// Validate validates this route
func (m *Route) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateFormat(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateHeaders(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateType(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

var routeTypeFormatPropEnum []interface{}

func init() {
	var res []interface{}
	if err := json.Unmarshal([]byte(`["default","http","json"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		routeTypeFormatPropEnum = append(routeTypeFormatPropEnum, v)
	}
}

// prop value enum
func (m *Route) validateFormatEnum(path, location string, value interface{}) error {
	if err := validate.Enum(path, location, value, routeTypeFormatPropEnum); err != nil {
		return err
	}
	return nil
}

func (m *Route) validateFormat(formats strfmt.Registry) error {

	if swag.IsZero(m.Format) { // not required
		return nil
	}

	return nil
}

func (m *Route) validateHeaders(formats strfmt.Registry) error {

	if swag.IsZero(m.Headers) { // not required
		return nil
	}

	if swag.IsZero(m.Headers) { // not required
		return nil
	}

	return nil
}

var routeTypeTypePropEnum []interface{}

func init() {
	var res []interface{}
	if err := json.Unmarshal([]byte(`["sync","async"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		routeTypeTypePropEnum = append(routeTypeTypePropEnum, v)
	}
}

// prop value enum
func (m *Route) validateTypeEnum(path, location string, value interface{}) error {
	if err := validate.Enum(path, location, value, routeTypeTypePropEnum); err != nil {
		return err
	}
	return nil
}

func (m *Route) validateType(formats strfmt.Registry) error {

	if swag.IsZero(m.Type) { // not required
		return nil
	}

	return nil
}

// MarshalBinary interface implementation
func (m *Route) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *Route) UnmarshalBinary(b []byte) error {
	var res Route
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}
<commit_msg>Get rid of *int64 and use int64<commit_after>package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"encoding/json"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// Route route
// swagger:model Route
type Route struct {

	// Route configuration - overrides application configuration
	Config map[string]string `json:"config,omitempty"`

	// Payload format sent into function.
	Format interface{} `json:"format,omitempty"`

	// Map of http headers that will be sent with the response
	Headers map[string][]string `json:"headers,omitempty"`

	// Hot functions idle timeout before termination. Value in Seconds
	IDLETimeout int64 `json:"idle_timeout,omitempty"`

	// Name of Docker image to use in this route. You should include the image tag, which should be a version number, to be more accurate. Can be overridden on a per route basis with route.image.
	Image string `json:"image,omitempty"`

	// Maximum number of hot functions concurrency
	MaxConcurrency int32 `json:"max_concurrency,omitempty"`

	// Max usable memory for this route (MiB).
	Memory int64 `json:"memory,omitempty"`

	// URL path that will be matched to this route
	// Read Only: true
	Path string `json:"path,omitempty"`

	// Timeout for executions of this route. Value in Seconds
	Timeout int64 `json:"timeout,omitempty"`

	// Route type
	Type interface{} `json:"type,omitempty"`
}

// Validate validates this route
func (m *Route) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateFormat(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateHeaders(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateType(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

var routeTypeFormatPropEnum []interface{}

func init() {
	var res []interface{}
	if err := json.Unmarshal([]byte(`["default","http","json"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		routeTypeFormatPropEnum = append(routeTypeFormatPropEnum, v)
	}
}

// prop value enum
func (m *Route) validateFormatEnum(path, location string, value interface{}) error {
	if err := validate.Enum(path, location, value, routeTypeFormatPropEnum); err != nil {
		return err
	}
	return nil
}

func (m *Route) validateFormat(formats strfmt.Registry) error {

	if swag.IsZero(m.Format) { // not required
		return nil
	}

	return nil
}

func (m *Route) validateHeaders(formats strfmt.Registry) error {

	if swag.IsZero(m.Headers) { // not required
		return nil
	}

	if swag.IsZero(m.Headers) { // not required
		return nil
	}

	return nil
}

var routeTypeTypePropEnum []interface{}

func init() {
	var res []interface{}
	if err := json.Unmarshal([]byte(`["sync","async"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		routeTypeTypePropEnum = append(routeTypeTypePropEnum, v)
	}
}

// prop value enum
func (m *Route) validateTypeEnum(path, location string, value interface{}) error {
	if err := validate.Enum(path, location, value, routeTypeTypePropEnum); err != nil {
		return err
	}
	return nil
}

func (m *Route) validateType(formats strfmt.Registry) error {

	if swag.IsZero(m.Type) { // not required
		return nil
	}

	return nil
}

// MarshalBinary interface implementation
func (m *Route) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *Route) UnmarshalBinary(b []byte) error {
	var res Route
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}
<|endoftext|>


<commit_before>package native

import (
	"syscall"
	"unsafe"

	"github.com/twtiger/gosecco/data"
)

// #include <linux/seccomp.h>
// #include <sys/prctl.h>
import "C"

// seccomp is a wrapper for the 'seccomp' system call.
// See <linux/seccomp.h> for valid op and flag values.
// uargs is typically a pointer to struct sock_fprog.
func seccomp(op, flags uintptr, uargs unsafe.Pointer) error {
	_, _, e := syscall.Syscall(syscall.PR_GET_SECCOMP, op, flags, uintptr(uargs))
	if e != 0 {
		return e
	}
	return nil
}

// InstallSeccomp will install seccomp using native methods
func InstallSeccomp(prog *data.SockFprog) error {
	return seccomp(C.SECCOMP_SET_MODE_FILTER, C.SECCOMP_FILTER_FLAG_TSYNC, unsafe.Pointer(prog))
}

// prctl is a wrapper for the 'prctl' system call.
// See 'man prctl' for details.
func prctl(option uintptr, args ...uintptr) error {
	if len(args) > 4 {
		return syscall.E2BIG
	}
	var arg [4]uintptr
	copy(arg[:], args)
	_, _, e := syscall.Syscall6(syscall.SYS_PRCTL, option, arg[0], arg[1], arg[2], arg[3], 0)
	if e != 0 {
		return e
	}
	return nil
}

// NoNewPrivs will use prctl to stop new privileges using native methods
func NoNewPrivs() error {
	return prctl(C.PR_SET_NO_NEW_PRIVS, 1)
}

// CheckGetSeccomp will check if we have seccomp available
func CheckGetSeccomp() error {
	return prctl(syscall.PR_GET_SECCOMP)
}

// CheckSetSeccompModeFilter will check if we have seccomp mode filter available
func CheckSetSeccompModeFilter() error {
	return prctl(syscall.PR_SET_SECCOMP, C.SECCOMP_MODE_FILTER, 0)
}

// CheckSetSeccompModeFilterWithSeccomp will check if we have the seccomp syscall available
func CheckSetSeccompModeFilterWithSeccomp() error {
	return seccomp(C.SECCOMP_SET_MODE_FILTER, 0, nil)
}

// CheckSetSeccompModeTsync will check that we can set tsync
func CheckSetSeccompModeTsync() error {
	return seccomp(C.SECCOMP_SET_MODE_FILTER, C.SECCOMP_FILTER_FLAG_TSYNC, nil)
}
<commit_msg>Use the correct syscall for installing seccomp<commit_after>package native

import (
	"syscall"
	"unsafe"

	"github.com/twtiger/gosecco/constants"
	"github.com/twtiger/gosecco/data"
)

// #include <linux/seccomp.h>
// #include <sys/prctl.h>
import "C"

// seccomp is a wrapper for the 'seccomp' system call.
// See <linux/seccomp.h> for valid op and flag values.
// uargs is typically a pointer to struct sock_fprog.
func seccomp(op, flags uintptr, uargs unsafe.Pointer) error {
	nr, _ := constants.GetSyscall("seccomp")
	_, _, e := syscall.Syscall(uintptr(nr), op, flags, uintptr(uargs))
	if e != 0 {
		return e
	}
	return nil
}

// InstallSeccomp will install seccomp using native methods
func InstallSeccomp(prog *data.SockFprog) error {
	return seccomp(C.SECCOMP_SET_MODE_FILTER, C.SECCOMP_FILTER_FLAG_TSYNC, unsafe.Pointer(prog))
}

// prctl is a wrapper for the 'prctl' system call.
// See 'man prctl' for details.
func prctl(option uintptr, args ...uintptr) error {
	if len(args) > 4 {
		return syscall.E2BIG
	}
	var arg [4]uintptr
	copy(arg[:], args)
	_, _, e := syscall.Syscall6(syscall.SYS_PRCTL, option, arg[0], arg[1], arg[2], arg[3], 0)
	if e != 0 {
		return e
	}
	return nil
}

// NoNewPrivs will use prctl to stop new privileges using native methods
func NoNewPrivs() error {
	return prctl(C.PR_SET_NO_NEW_PRIVS, 1)
}

// CheckGetSeccomp will check if we have seccomp available
func CheckGetSeccomp() error {
	return prctl(syscall.PR_GET_SECCOMP)
}

// CheckSetSeccompModeFilter will check if we have seccomp mode filter available
func CheckSetSeccompModeFilter() error {
	return prctl(syscall.PR_SET_SECCOMP, C.SECCOMP_MODE_FILTER, 0)
}

// CheckSetSeccompModeFilterWithSeccomp will check if we have the seccomp syscall available
func CheckSetSeccompModeFilterWithSeccomp() error {
	return seccomp(C.SECCOMP_SET_MODE_FILTER, 0, nil)
}

// CheckSetSeccompModeTsync will check that we can set tsync
func CheckSetSeccompModeTsync() error {
	return seccomp(C.SECCOMP_SET_MODE_FILTER, C.SECCOMP_FILTER_FLAG_TSYNC, nil)
}
<|endoftext|>


<commit_before>package neko

// #include <malloc.h>
// #include "redirect.h"
// #include "neko/neko_vm.h"
import "C"

import (
	"fmt"
	"unsafe"
)

type VM struct {
	vm *C.neko_vm
}

func bool_to_int(b bool) int {
	if b {
		return 1
	}

	return 0
}

func GlobalInit() {
	C.neko_global_init()
}

func GlobalFree() {
	C.neko_vm_select(nil)
	C.neko_global_free()
}

func GcMajor() {
	C.neko_gc_major()
}

func GcLoop() {
	C.neko_gc_loop()
}

func GcStats() (heap, free int) {
	var h, f C.int
	C.neko_gc_stats(&h, &f)
	return int(h), int(f)
}

/// TODO param  neko "thread_main_func" init
/// TODO param  neko "thread_main_func" main
/// TODO param "void *" pparam
/// TODO param "void **" handle
/// TODO return "int"
func ThreadCreate() {
}

/// TODO param  neko "thread_main_func" f
/// TODO param "void *" p
func ThreadBlocking() {
}

func ThreadRegister(t bool) bool {
	return C.neko_thread_register(C.bool(bool_to_int(t))) == 1
}

func NewVM() (*VM, Error) {
	vm := vmAlloc()
	if vm == nil {
		return nil, fmt.Errorf("Unable to allocate VM")
	}

	return &VM{vm}, nil
}

func vmAlloc() *C.neko_vm {
	return C.neko_vm_alloc(nil)
}

func CurrentVM() (*VM, Error) {
	vm := C.neko_vm_current()
	if vm == nil {
		return nil, fmt.Errorf("Unable to get current VM")
	}

	return &VM{vm}, nil
}

func (vm *VM) ExecStack() Value {
	return inlineCvalToValue(C.neko_exc_stack(vm.vm))
}

func (vm *VM) CallStack() Value {
	return inlineCvalToValue(C.neko_call_stack(vm.vm))
}

/// FIXME
func (vm *VM) Custom(k Kind) interface{} {
	return nil
	//return C.neko_vm_custom(vm.vm, *(*C.vkind)(unsafe.Pointer(&k)))
}

/// FIXME
func (vm *VM) SetCustom(k Kind, v interface{}) {
	//C.neko_vm_set_custom(vm.vm, *(*C.vkind)(unsafe.Pointer(&k)), unsafe.Pointer(&v))
}

func (vm *VM) Execute(module interface{}) Value {
	return inlineCvalToValue(C.neko_vm_execute(vm.vm, unsafe.Pointer(&module)))
}

func (vm *VM) Select() {
	C.neko_vm_select(vm.vm)
}

func (vm *VM) Jit(enable bool) int {
	return int(C.neko_vm_jit(vm.vm, C.int(bool_to_int(enable))))
}

func (vm *VM) Trusted(trusted bool) int {
	return int(C.neko_vm_trusted(vm.vm, C.int(bool_to_int(trusted))))
}

func (vm *VM) Redirect(printer Printer, param interface{}) {
	redirectFunc = printer
	C.setRedirectFunc(vm.vm, unsafe.Pointer(&param))
}

/// TODO param "neko_stat_func" fstats
/// TODO param "neko_stat_func" pstats
func (vm *VM) SetStats() {
}

func (vm *VM) DebugStack() {
	C.neko_vm_dump_stack(vm.vm)
}

func DefaultLoader(argv []string) Value {
	strs := make([]*C.char, len(argv))
	for i, s := range argv {
		strs[i] = C.CString(s)
		defer C.free(unsafe.Pointer(strs[i]))
	}

	// Respect passing nil as a valid argument
	var cargv **C.char
	if len(argv) != 0 {
		cargv = (**C.char)(unsafe.Pointer(&strs[0]))
	}

	return inlineCvalToValue(C.neko_default_loader(cargv, C.int(len(argv))))
}

func IsBigEndian() bool {
	return C.neko_is_big_endian() == 1
}
<commit_msg>Use a map to convert to C.{int,bool} from a Go bool<commit_after>package neko

// #include <malloc.h>
// #include "redirect.h"
// #include "neko/neko_vm.h"
import "C"

import (
	"fmt"
	"unsafe"
)

type VM struct {
	vm *C.neko_vm
}

var gobool = map[bool] C.bool {
	false: C.false,
	true: C.true,
}

var gointbool = map[bool] C.int {
	false: 0,
	true: 1,
}

func GlobalInit() {
	C.neko_global_init()
}

func GlobalFree() {
	C.neko_vm_select(nil)
	C.neko_global_free()
}

func GcMajor() {
	C.neko_gc_major()
}

func GcLoop() {
	C.neko_gc_loop()
}

func GcStats() (heap, free int) {
	var h, f C.int
	C.neko_gc_stats(&h, &f)
	return int(h), int(f)
}

/// TODO param  neko "thread_main_func" init
/// TODO param  neko "thread_main_func" main
/// TODO param "void *" pparam
/// TODO param "void **" handle
/// TODO return "int"
func ThreadCreate() {
}

/// TODO param  neko "thread_main_func" f
/// TODO param "void *" p
func ThreadBlocking() {
}

func ThreadRegister(t bool) bool {
	return C.neko_thread_register(gobool[t]) == 1
}

func NewVM() (*VM, Error) {
	vm := vmAlloc()
	if vm == nil {
		return nil, fmt.Errorf("Unable to allocate VM")
	}

	return &VM{vm}, nil
}

func vmAlloc() *C.neko_vm {
	return C.neko_vm_alloc(nil)
}

func CurrentVM() (*VM, Error) {
	vm := C.neko_vm_current()
	if vm == nil {
		return nil, fmt.Errorf("Unable to get current VM")
	}

	return &VM{vm}, nil
}

func (vm *VM) ExecStack() Value {
	return inlineCvalToValue(C.neko_exc_stack(vm.vm))
}

func (vm *VM) CallStack() Value {
	return inlineCvalToValue(C.neko_call_stack(vm.vm))
}

/// FIXME
func (vm *VM) Custom(k Kind) interface{} {
	return nil
	//return C.neko_vm_custom(vm.vm, *(*C.vkind)(unsafe.Pointer(&k)))
}

/// FIXME
func (vm *VM) SetCustom(k Kind, v interface{}) {
	//C.neko_vm_set_custom(vm.vm, *(*C.vkind)(unsafe.Pointer(&k)), unsafe.Pointer(&v))
}

func (vm *VM) Execute(module interface{}) Value {
	return inlineCvalToValue(C.neko_vm_execute(vm.vm, unsafe.Pointer(&module)))
}

func (vm *VM) Select() {
	C.neko_vm_select(vm.vm)
}

func (vm *VM) Jit(enable bool) int {
	return int(C.neko_vm_jit(vm.vm, gointbool[enable]))
}

func (vm *VM) Trusted(trusted bool) int {
	return int(C.neko_vm_trusted(vm.vm, gointbool[trusted]))
}

func (vm *VM) Redirect(printer Printer, param interface{}) {
	redirectFunc = printer
	C.setRedirectFunc(vm.vm, unsafe.Pointer(&param))
}

/// TODO param "neko_stat_func" fstats
/// TODO param "neko_stat_func" pstats
func (vm *VM) SetStats() {
}

func (vm *VM) DebugStack() {
	C.neko_vm_dump_stack(vm.vm)
}

func DefaultLoader(argv []string) Value {
	strs := make([]*C.char, len(argv))
	for i, s := range argv {
		strs[i] = C.CString(s)
		defer C.free(unsafe.Pointer(strs[i]))
	}

	// Respect passing nil as a valid argument
	var cargv **C.char
	if len(argv) != 0 {
		cargv = (**C.char)(unsafe.Pointer(&strs[0]))
	}

	return inlineCvalToValue(C.neko_default_loader(cargv, C.int(len(argv))))
}

func IsBigEndian() bool {
	return C.neko_is_big_endian() == 1
}
<|endoftext|>


<commit_before>package jigo

import "testing"

type tokenTest struct {
	typ itemType
	val string
}

var (
	ttCommentBegin  = tokenTest{tokenCommentBegin, "{#"}
	ttCommentEnd    = tokenTest{tokenCommentEnd, "#}"}
	ttBlockBegin    = tokenTest{tokenBlockBegin, "{%"}
	ttBlockEnd      = tokenTest{tokenBlockEnd, "%}"}
	ttVariableBegin = tokenTest{tokenVariableBegin, "{{"}
	ttVariableEnd   = tokenTest{tokenVariableEnd, "}}"}
	ttEOF           = tokenTest{tokenEOF, ""}
)

func tokenize(l *lexer) []item {
	items := make([]item, 0, 50)
	for t := range l.items {
		items = append(items, t)
		// fmt.Printf("%#v\n", t)
	}
	return items
}

type lextest struct{ *testing.T }

func (lt *lextest) Test(input string, tests []tokenTest) {
	t := lt.T
	e := NewEnvironment()
	l := e.lex(input, "test", "test.jigo")
	tokens := tokenize(l)
	if len(tokens) != len(tests) {
		t.Fatalf("Expected %d tokens, got %d\n", len(tests), len(tokens))
	}
	for i, tok := range tokens {
		test := tests[i]
		if test.typ != tok.typ {
			t.Errorf("Expecting %d token type to be %d, got %d\n", i, test.typ, tok.typ)
		}
		if test.val != tok.val {
			t.Errorf("Expecting %d token val to be `%s`, got `%s`\n", i, test.val, tok.val)
		}
	}
}

func TestLexer(t *testing.T) {
	tester := lextest{t}

	// Testing simple text with no jigo syntax
	tester.Test(
		`Hello, world`,
		[]tokenTest{{tokenText, `Hello, world`}, ttEOF},
	)

	// Testing simple text with single jigo comment
	tester.Test(
		`{# comment #}`,
		[]tokenTest{
			ttCommentBegin,
			{tokenText, " comment "},
			ttCommentEnd,
			ttEOF,
		},
	)

	tester.Test(
		`Hello, {# comment #}World`,
		[]tokenTest{
			{tokenText, "Hello, "},
			ttCommentBegin,
			{tokenText, " comment "},
			ttCommentEnd,
			{tokenText, "World"},
			ttEOF,
		},
	)

	sp := tokenTest{tokenWhitespace, " "}

	tester.Test(
		`{{ foo }}`,
		[]tokenTest{
			ttVariableBegin, sp,
			{tokenName, "foo"}, sp,
			ttVariableEnd,
			ttEOF,
		},
	)

	tester.Test(
		`{{ (a - b) + c }}`,
		[]tokenTest{
			ttVariableBegin, sp,
			{tokenLparen, "("},
			{tokenName, "a"}, sp,
			{tokenSub, "-"}, sp,
			{tokenName, "b"},
			{tokenRparen, ")"}, sp,
			{tokenAdd, "+"}, sp,
			{tokenName, "c"}, sp,
			ttVariableEnd,
			ttEOF,
		},
	)
}
<commit_msg>some more advanced block lex tests<commit_after>package jigo

import "testing"

type tokenTest struct {
	typ itemType
	val string
}

var (
	ttCommentBegin  = tokenTest{tokenCommentBegin, "{#"}
	ttCommentEnd    = tokenTest{tokenCommentEnd, "#}"}
	ttBlockBegin    = tokenTest{tokenBlockBegin, "{%"}
	ttBlockEnd      = tokenTest{tokenBlockEnd, "%}"}
	ttVariableBegin = tokenTest{tokenVariableBegin, "{{"}
	ttVariableEnd   = tokenTest{tokenVariableEnd, "}}"}
	ttEOF           = tokenTest{tokenEOF, ""}
)

func tokenize(l *lexer) []item {
	items := make([]item, 0, 50)
	for t := range l.items {
		items = append(items, t)
		// fmt.Printf("%#v\n", t)
	}
	return items
}

type lextest struct{ *testing.T }

func (lt *lextest) Test(input string, tests []tokenTest) {
	t := lt.T
	e := NewEnvironment()
	l := e.lex(input, "test", "test.jigo")
	tokens := tokenize(l)
	if len(tokens) != len(tests) {
		t.Fatalf("Expected %d tokens, got %d\n", len(tests), len(tokens))
	}
	for i, tok := range tokens {
		test := tests[i]
		if test.typ != tok.typ {
			t.Errorf("Expecting %d token type to be %d, got %d\n", i, test.typ, tok.typ)
		}
		if test.val != tok.val {
			t.Errorf("Expecting %d token val to be `%s`, got `%s`\n", i, test.val, tok.val)
		}
	}
}

func TestLexer(t *testing.T) {
	tester := lextest{t}

	// Testing simple text with no jigo syntax
	tester.Test(
		`Hello, world`,
		[]tokenTest{{tokenText, `Hello, world`}, ttEOF},
	)

	// Testing simple text with single jigo comment
	tester.Test(
		`{# comment #}`,
		[]tokenTest{
			ttCommentBegin,
			{tokenText, " comment "},
			ttCommentEnd,
			ttEOF,
		},
	)

	tester.Test(
		`Hello, {# comment #}World`,
		[]tokenTest{
			{tokenText, "Hello, "},
			ttCommentBegin,
			{tokenText, " comment "},
			ttCommentEnd,
			{tokenText, "World"},
			ttEOF,
		},
	)

	sp := tokenTest{tokenWhitespace, " "}

	tester.Test(
		`{{ foo }}`,
		[]tokenTest{
			ttVariableBegin, sp,
			{tokenName, "foo"}, sp,
			ttVariableEnd,
			ttEOF,
		},
	)

	tester.Test(
		`{{ (a - b) + c }}`,
		[]tokenTest{
			ttVariableBegin, sp,
			{tokenLparen, "("},
			{tokenName, "a"}, sp,
			{tokenSub, "-"}, sp,
			{tokenName, "b"},
			{tokenRparen, ")"}, sp,
			{tokenAdd, "+"}, sp,
			{tokenName, "c"}, sp,
			ttVariableEnd,
			ttEOF,
		},
	)

	tester.Test(
		`Hello.  {% if true %}World{% else %}Nobody{% endif %}`,
		[]tokenTest{
			{tokenText, "Hello.  "},
			ttBlockBegin, sp,
			{tokenName, "if"}, sp,
			{tokenBool, "true"}, sp, ttBlockEnd,
			{tokenText, "World"}, ttBlockBegin, sp,
			{tokenName, "else"}, sp, ttBlockEnd,
			{tokenText, "Nobody"}, ttBlockBegin, sp,
			{tokenName, "endif"}, sp, ttBlockEnd, ttEOF,
		},
	)

	tester.Test(
		`<html>{# ignore {% tags %} in comments ##}</html>`,
		[]tokenTest{
			{tokenText, "<html>"}, ttCommentBegin,
			{tokenText, " ignore {% tags %} in comments #"}, ttCommentEnd,
			{tokenText, "</html>"}, ttEOF,
		},
	)
}
<|endoftext|>


<commit_before>// Copyright 2015 go-dockerclient authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package docker

import (
	"encoding/json"
	"net/http"
	"net/url"
	"reflect"
	"testing"
)

func TestListNetworks(t *testing.T) {
	jsonNetworks := `[
     {
             "ID": "8dfafdbc3a40",
             "Name": "blah",
             "Type": "bridge",
             "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}]
     },
     {
             "ID": "9fb1e39c",
             "Name": "foo",
             "Type": "bridge",
             "Endpoints":[{"ID": "c080be979dda", "Name": "lllll2222", "Network": "9fb1e39c"}]
     }
]`
	var expected []Network
	err := json.Unmarshal([]byte(jsonNetworks), &expected)
	if err != nil {
		t.Fatal(err)
	}
	client := newTestClient(&FakeRoundTripper{message: jsonNetworks, status: http.StatusOK})
	containers, err := client.ListNetworks()
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(containers, expected) {
		t.Errorf("ListNetworks: Expected %#v. Got %#v.", expected, containers)
	}
}

func TestNetworkInfo(t *testing.T) {
	jsonNetwork := `{
             "ID": "8dfafdbc3a40",
             "Name": "blah",
             "Type": "bridge",
             "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}]
        }`
	var expected Network
	err := json.Unmarshal([]byte(jsonNetwork), &expected)
	if err != nil {
		t.Fatal(err)
	}
	fakeRT := &FakeRoundTripper{message: jsonNetwork, status: http.StatusOK}
	client := newTestClient(fakeRT)
	id := "8dfafdbc3a40"
	network, err := client.NetworkInfo(id)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(*network, expected) {
		t.Errorf("NetworkInfo(%q): Expected %#v. Got %#v.", id, expected, network)
	}
	expectedURL, _ := url.Parse(client.getURL("/networks/8dfafdbc3a40"))
	if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path {
		t.Errorf("NetworkInfo(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath)
	}
}

func TestNetworkCreate(t *testing.T) {
	jsonID := `{"ID": "8dfafdbc3a40"}`
	jsonNetwork := `{
             "ID": "8dfafdbc3a40",
             "Name": "foobar",
             "Driver": "bridge"
        }`
	var expected Network
	err := json.Unmarshal([]byte(jsonNetwork), &expected)
	if err != nil {
		t.Fatal(err)
	}

	client := newTestClient(&FakeRoundTripper{message: jsonID, status: http.StatusOK})
	opts := CreateNetworkOptions{"foobar", false, "bridge", IPAMOptions{}, nil}
	network, err := client.CreateNetwork(opts)
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(*network, expected) {
		t.Errorf("CreateNetwork: Expected %#v. Got %#v.", expected, network)
	}
}

func TestNetworkRemove(t *testing.T) {
	id := "8dfafdbc3a40"
	fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}
	client := newTestClient(fakeRT)
	err := client.RemoveNetwork(id)
	if err != nil {
		t.Fatal(err)
	}
	req := fakeRT.requests[0]
	expectedMethod := "DELETE"
	if req.Method != expectedMethod {
		t.Errorf("RemoveNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method)
	}
	u, _ := url.Parse(client.getURL("/networks/" + id))
	if req.URL.Path != u.Path {
		t.Errorf("RemoveNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path)
	}
}

func TestNetworkConnect(t *testing.T) {
	id := "8dfafdbc3a40"
	fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}
	client := newTestClient(fakeRT)
	opts := NetworkConnectionOptions{"foobar"}
	err := client.ConnectNetwork(id, opts)
	if err != nil {
		t.Fatal(err)
	}
	req := fakeRT.requests[0]
	expectedMethod := "POST"
	if req.Method != expectedMethod {
		t.Errorf("ConnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method)
	}
	u, _ := url.Parse(client.getURL("/networks/" + id + "/connect"))
	if req.URL.Path != u.Path {
		t.Errorf("ConnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path)
	}
}

func TestNetworkConnectNotFound(t *testing.T) {
	client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound})
	opts := NetworkConnectionOptions{"foobar"}
	err := client.ConnectNetwork("8dfafdbc3a40", opts)
	if serr, ok := err.(*model.ModelMissingError); !ok {
		t.Errorf("ConnectNetwork: wrong error type: %s.", serr)
	}
}

func TestNetworkDisconnect(t *testing.T) {
	id := "8dfafdbc3a40"
	fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}
	client := newTestClient(fakeRT)
	opts := NetworkConnectionOptions{"foobar"}
	err := client.DisonnectNetwork(id, opts)
	if err != nil {
		t.Fatal(err)
	}
	req := fakeRT.requests[0]
	expectedMethod := "POST"
	if req.Method != expectedMethod {
		t.Errorf("DisconnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method)
	}
	u, _ := url.Parse(client.getURL("/networks/" + id + "/disconnect"))
	if req.URL.Path != u.Path {
		t.Errorf("DisconnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path)
	}
}

func TestNetworkDisconnectNotFound(t *testing.T) {
	client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound})
	opts := NetworkConnectionOptions{"foobar"}
	err := client.DisconnectNetwork("8dfafdbc3a40", opts)
	if serr, ok := err.(*model.ModelMissingError); !ok {
		t.Errorf("DisconnectNetwork: wrong error type: %s.", serr)
	}
}
<commit_msg>Fix error being checked<commit_after>// Copyright 2015 go-dockerclient authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package docker

import (
	"encoding/json"
	"net/http"
	"net/url"
	"reflect"
	"testing"
)

func TestListNetworks(t *testing.T) {
	jsonNetworks := `[
     {
             "ID": "8dfafdbc3a40",
             "Name": "blah",
             "Type": "bridge",
             "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}]
     },
     {
             "ID": "9fb1e39c",
             "Name": "foo",
             "Type": "bridge",
             "Endpoints":[{"ID": "c080be979dda", "Name": "lllll2222", "Network": "9fb1e39c"}]
     }
]`
	var expected []Network
	err := json.Unmarshal([]byte(jsonNetworks), &expected)
	if err != nil {
		t.Fatal(err)
	}
	client := newTestClient(&FakeRoundTripper{message: jsonNetworks, status: http.StatusOK})
	containers, err := client.ListNetworks()
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(containers, expected) {
		t.Errorf("ListNetworks: Expected %#v. Got %#v.", expected, containers)
	}
}

func TestNetworkInfo(t *testing.T) {
	jsonNetwork := `{
             "ID": "8dfafdbc3a40",
             "Name": "blah",
             "Type": "bridge",
             "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}]
        }`
	var expected Network
	err := json.Unmarshal([]byte(jsonNetwork), &expected)
	if err != nil {
		t.Fatal(err)
	}
	fakeRT := &FakeRoundTripper{message: jsonNetwork, status: http.StatusOK}
	client := newTestClient(fakeRT)
	id := "8dfafdbc3a40"
	network, err := client.NetworkInfo(id)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(*network, expected) {
		t.Errorf("NetworkInfo(%q): Expected %#v. Got %#v.", id, expected, network)
	}
	expectedURL, _ := url.Parse(client.getURL("/networks/8dfafdbc3a40"))
	if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path {
		t.Errorf("NetworkInfo(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath)
	}
}

func TestNetworkCreate(t *testing.T) {
	jsonID := `{"ID": "8dfafdbc3a40"}`
	jsonNetwork := `{
             "ID": "8dfafdbc3a40",
             "Name": "foobar",
             "Driver": "bridge"
        }`
	var expected Network
	err := json.Unmarshal([]byte(jsonNetwork), &expected)
	if err != nil {
		t.Fatal(err)
	}

	client := newTestClient(&FakeRoundTripper{message: jsonID, status: http.StatusOK})
	opts := CreateNetworkOptions{"foobar", false, "bridge", IPAMOptions{}, nil}
	network, err := client.CreateNetwork(opts)
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(*network, expected) {
		t.Errorf("CreateNetwork: Expected %#v. Got %#v.", expected, network)
	}
}

func TestNetworkRemove(t *testing.T) {
	id := "8dfafdbc3a40"
	fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}
	client := newTestClient(fakeRT)
	err := client.RemoveNetwork(id)
	if err != nil {
		t.Fatal(err)
	}
	req := fakeRT.requests[0]
	expectedMethod := "DELETE"
	if req.Method != expectedMethod {
		t.Errorf("RemoveNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method)
	}
	u, _ := url.Parse(client.getURL("/networks/" + id))
	if req.URL.Path != u.Path {
		t.Errorf("RemoveNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path)
	}
}

func TestNetworkConnect(t *testing.T) {
	id := "8dfafdbc3a40"
	fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}
	client := newTestClient(fakeRT)
	opts := NetworkConnectionOptions{"foobar"}
	err := client.ConnectNetwork(id, opts)
	if err != nil {
		t.Fatal(err)
	}
	req := fakeRT.requests[0]
	expectedMethod := "POST"
	if req.Method != expectedMethod {
		t.Errorf("ConnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method)
	}
	u, _ := url.Parse(client.getURL("/networks/" + id + "/connect"))
	if req.URL.Path != u.Path {
		t.Errorf("ConnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path)
	}
}

func TestNetworkConnectNotFound(t *testing.T) {
	client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound})
	opts := NetworkConnectionOptions{"foobar"}
	err := client.ConnectNetwork("8dfafdbc3a40", opts)
	if serr, ok := err.(*NoSuchNetworkOrContainer); !ok {
		t.Errorf("ConnectNetwork: wrong error type: %s.", serr)
	}
}

func TestNetworkDisconnect(t *testing.T) {
	id := "8dfafdbc3a40"
	fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}
	client := newTestClient(fakeRT)
	opts := NetworkConnectionOptions{"foobar"}
	err := client.DisconnectNetwork(id, opts)
	if err != nil {
		t.Fatal(err)
	}
	req := fakeRT.requests[0]
	expectedMethod := "POST"
	if req.Method != expectedMethod {
		t.Errorf("DisconnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method)
	}
	u, _ := url.Parse(client.getURL("/networks/" + id + "/disconnect"))
	if req.URL.Path != u.Path {
		t.Errorf("DisconnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path)
	}
}

func TestNetworkDisconnectNotFound(t *testing.T) {
	client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound})
	opts := NetworkConnectionOptions{"foobar"}
	err := client.DisconnectNetwork("8dfafdbc3a40", opts)
	if serr, ok := err.(*NoSuchNetworkOrContainer); !ok {
		t.Errorf("DisconnectNetwork: wrong error type: %s.", serr)
	}
}
<|endoftext|>