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

// +build ignore

// gen runs go generate on Unicode- and CLDR-related package in the text
// repositories, taking into account dependencies and versions.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"unicode"

	"golang.org/x/text/internal/gen"
)

var (
	verbose     = flag.Bool("v", false, "verbose output")
	force       = flag.Bool("force", false, "ignore failing dependencies")
	excludeList = flag.String("exclude", "",
		"comma-separated list of packages to exclude")

	// The user can specify a selection of packages to build on the command line.
	args []string
)

func exclude(pkg string) bool {
	if len(args) > 0 {
		return !contains(args, pkg)
	}
	return contains(strings.Split(*excludeList, ","), pkg)
}

// TODO:
// - Better version handling.
// - Generate tables for the core unicode package?
// - Add generation for encodings. This requires some retooling here and there.
// - Running repo-wide "long" tests.

var vprintf = fmt.Printf

func main() {
	gen.Init()
	args = flag.Args()
	if !*verbose {
		// Set vprintf to a no-op.
		vprintf = func(string, ...interface{}) (int, error) { return 0, nil }
	}

	if gen.UnicodeVersion() != unicode.Version {
		fmt.Printf("Requested Unicode version %s; core unicode version is %s.\n",
			gen.UnicodeVersion,
			unicode.Version)
		// TODO: use collate to compare. Simple comparison will work, though,
		// until Unicode reaches version 10. To avoid circular dependencies, we
		// could use the NumericWeighter without using package collate using a
		// trivial Weighter implementation.
		if gen.UnicodeVersion() < unicode.Version && !*force {
			os.Exit(2)
		}
	}
	var (
		cldr     = generate("unicode/cldr")
		language = generate("language", cldr)
		internal = generate("internal", language)
		norm     = generate("unicode/norm")
		_        = generate("unicode/rangetable")
		_        = generate("width")
		_        = generate("currency", cldr, language, internal)
		_        = generate("language/display", cldr, language)
		_        = generate("cases", norm)
		_        = generate("collate", norm, cldr, language)
		_        = generate("search", norm, cldr, language)
	)
	all.Wait()

	if hasErrors {
		fmt.Println("FAIL")
		os.Exit(1)
	}
	vprintf("SUCCESS\n")
}

var (
	all       sync.WaitGroup
	hasErrors bool
)

type dependency struct {
	sync.WaitGroup
	hasErrors bool
}

func generate(pkg string, deps ...*dependency) *dependency {
	var wg dependency
	if exclude(pkg) {
		return &wg
	}
	wg.Add(1)
	all.Add(1)
	go func() {
		defer wg.Done()
		defer all.Done()
		// Wait for dependencies to finish.
		for _, d := range deps {
			d.Wait()
			if d.hasErrors && !*force {
				fmt.Printf("--- ABORT: %s\n", pkg)
				wg.hasErrors = true
				return
			}
		}
		vprintf("=== GENERATE %s\n", pkg)
		args := []string{"generate"}
		if *verbose {
			args = append(args, "-v")
		}
		args = append(args, "./"+pkg)
		cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
		w := &bytes.Buffer{}
		cmd.Stderr = w
		cmd.Stdout = w
		if err := cmd.Run(); err != nil {
			fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(w), err)
			hasErrors = true
			wg.hasErrors = true
			return
		}
		vprintf("--- SUCCESS: %s\n\t%v\n", pkg, indent(w))
	}()
	return &wg
}

func contains(a []string, s string) bool {
	for _, e := range a {
		if s == e {
			return true
		}
	}
	return false
}

func indent(b *bytes.Buffer) string {
	return strings.Replace(strings.TrimSpace(b.String()), "\n", "\n\t", -1)
}
<commit_msg>: added bidi and htmlindex packages to gen.go<commit_after>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

// gen runs go generate on Unicode- and CLDR-related package in the text
// repositories, taking into account dependencies and versions.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"unicode"

	"golang.org/x/text/internal/gen"
)

var (
	verbose     = flag.Bool("v", false, "verbose output")
	force       = flag.Bool("force", false, "ignore failing dependencies")
	excludeList = flag.String("exclude", "",
		"comma-separated list of packages to exclude")

	// The user can specify a selection of packages to build on the command line.
	args []string
)

func exclude(pkg string) bool {
	if len(args) > 0 {
		return !contains(args, pkg)
	}
	return contains(strings.Split(*excludeList, ","), pkg)
}

// TODO:
// - Better version handling.
// - Generate tables for the core unicode package?
// - Add generation for encodings. This requires some retooling here and there.
// - Running repo-wide "long" tests.

var vprintf = fmt.Printf

func main() {
	gen.Init()
	args = flag.Args()
	if !*verbose {
		// Set vprintf to a no-op.
		vprintf = func(string, ...interface{}) (int, error) { return 0, nil }
	}

	if gen.UnicodeVersion() != unicode.Version {
		fmt.Printf("Requested Unicode version %s; core unicode version is %s.\n",
			gen.UnicodeVersion,
			unicode.Version)
		// TODO: use collate to compare. Simple comparison will work, though,
		// until Unicode reaches version 10. To avoid circular dependencies, we
		// could use the NumericWeighter without using package collate using a
		// trivial Weighter implementation.
		if gen.UnicodeVersion() < unicode.Version && !*force {
			os.Exit(2)
		}
	}
	var (
		cldr     = generate("unicode/cldr")
		language = generate("language", cldr)
		internal = generate("internal", language)
		norm     = generate("unicode/norm")
		_        = generate("unicode/rangetable")
		_        = generate("unicode/bidi", norm)
		_        = generate("encoding/htmlindex")
		_        = generate("width")
		_        = generate("currency", cldr, language, internal)
		_        = generate("language/display", cldr, language)
		_        = generate("cases", norm)
		_        = generate("collate", norm, cldr, language)
		_        = generate("search", norm, cldr, language)
	)
	all.Wait()

	if hasErrors {
		fmt.Println("FAIL")
		os.Exit(1)
	}
	vprintf("SUCCESS\n")
}

var (
	all       sync.WaitGroup
	hasErrors bool
)

type dependency struct {
	sync.WaitGroup
	hasErrors bool
}

func generate(pkg string, deps ...*dependency) *dependency {
	var wg dependency
	if exclude(pkg) {
		return &wg
	}
	wg.Add(1)
	all.Add(1)
	go func() {
		defer wg.Done()
		defer all.Done()
		// Wait for dependencies to finish.
		for _, d := range deps {
			d.Wait()
			if d.hasErrors && !*force {
				fmt.Printf("--- ABORT: %s\n", pkg)
				wg.hasErrors = true
				return
			}
		}
		vprintf("=== GENERATE %s\n", pkg)
		args := []string{"generate"}
		if *verbose {
			args = append(args, "-v")
		}
		args = append(args, "./"+pkg)
		cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
		w := &bytes.Buffer{}
		cmd.Stderr = w
		cmd.Stdout = w
		if err := cmd.Run(); err != nil {
			fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(w), err)
			hasErrors = true
			wg.hasErrors = true
			return
		}
		vprintf("--- SUCCESS: %s\n\t%v\n", pkg, indent(w))
	}()
	return &wg
}

func contains(a []string, s string) bool {
	for _, e := range a {
		if s == e {
			return true
		}
	}
	return false
}

func indent(b *bytes.Buffer) string {
	return strings.Replace(strings.TrimSpace(b.String()), "\n", "\n\t", -1)
}
<|endoftext|>


<commit_before>package golib

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httputil"
	"sync"

	"github.com/gin-gonic/gin"
)

var initGinOnce sync.Once

func InitGin() {
	initGinOnce.Do(func() {
		gin.SetMode(gin.ReleaseMode)
	})
}

func NewGinEngine() *gin.Engine {
	return NewGinEngineWithHandler(nil)
}

func NewGinEngineWithHandler(logHandler *GinLogHandler) *gin.Engine {
	InitGin()
	engine := gin.New()
	if logHandler == nil {
		logHandler = DefaultGinLogHandler
	}
	engine.Use(logHandler.LogRequest, ginRecover)
	engine.NoRoute(func(c *gin.Context) {
		c.Writer.WriteHeader(http.StatusNotFound)
		_, _ = c.Writer.WriteString("404 page not found\n")
	})
	return engine
}

func ginRecover(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			stack := stack(3)
			httpRequest, _ := httputil.DumpRequest(c.Request, false)
			Log.Errorf("[Recovery] panic recovered:\n%s\n%s\n%s", string(httpRequest), err, stack)
			c.AbortWithStatus(500)
		}
	}()
	c.Next()
}

type GinTask struct {
	*gin.Engine
	Endpoint     string
	ShutdownHook func()

	server      *http.Server
	c           StopChan
	shutdownErr error
}

func NewGinTask(endpoint string) *GinTask {
	return NewGinTaskWithHandler(endpoint, nil)
}

func NewGinTaskWithHandler(endpoint string, logHandler *GinLogHandler) *GinTask {
	return &GinTask{
		Engine:   NewGinEngineWithHandler(logHandler),
		Endpoint: endpoint,
	}
}

func (task *GinTask) Start(wg *sync.WaitGroup) StopChan {
	task.c = NewStopChan()
	if wg != nil {
		wg.Add(1)
	}
	go func() {
		if wg != nil {
			defer wg.Done()
		}
		task.server = &http.Server{Addr: task.Endpoint, Handler: task.Engine}
		Log.Infoln("Starting", task)
		err := task.server.ListenAndServe()
		if hook := task.ShutdownHook; hook != nil {
			hook()
		}
		if err == http.ErrServerClosed {
			err = nil
		}
		if task.shutdownErr != nil {
			if err == nil {
				err = task.shutdownErr
			} else {
				err = MultiError([]error{task.shutdownErr, err})
			}
		}
		task.c.StopErr(err)
	}()
	return task.c
}

func (task *GinTask) Stop() {
	server := task.server
	if server != nil {
		Log.Infoln("Shutting down", task)
		task.shutdownErr = server.Shutdown(context.Background())
	}
}

func (task *GinTask) String() string {
	return fmt.Sprintf("HTTP server on " + task.Endpoint)
}

func ToUtf8(iso8859 string) string {
	iso8859bytes := []byte(iso8859)
	buf := make([]rune, len(iso8859bytes))
	for i, b := range iso8859bytes {
		buf[i] = rune(b)
	}
	return string(buf)
}

// This function implements gin.HandlerFunc.
// Decode HTTP header keys and values from ISO-8859-1 to UTF-8
func DecodeHeadersToUtf8(ctx *gin.Context) {
	for key, values := range ctx.Request.Header {
		changed := false
		decodedKey := ToUtf8(key)
		for i, value := range values {
			decodedValue := ToUtf8(value)
			if value != decodedValue {
				values[i] = decodedValue
				changed = true
			}
		}
		if decodedKey != key {
			changed = true
		}
		if changed {
			delete(ctx.Request.Header, key)
			ctx.Request.Header[decodedKey] = values
		}
	}
}
<commit_msg>Bugfix<commit_after>package golib

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httputil"
	"sync"

	"github.com/gin-gonic/gin"
)

var initGinOnce sync.Once

func InitGin() {
	initGinOnce.Do(func() {
		gin.SetMode(gin.ReleaseMode)
	})
}

func NewGinEngine() *gin.Engine {
	return NewGinEngineWithHandler(nil)
}

func NewGinEngineWithHandler(logHandler *GinLogHandler) *gin.Engine {
	InitGin()
	engine := gin.New()
	if logHandler == nil {
		logHandler = DefaultGinLogHandler
	}
	engine.Use(logHandler.LogRequest, ginRecover)
	engine.NoRoute(func(c *gin.Context) {
		c.Writer.WriteHeader(http.StatusNotFound)
		_, _ = c.Writer.WriteString("404 page not found\n")
	})
	return engine
}

func ginRecover(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			stack := stack(3)
			httpRequest, _ := httputil.DumpRequest(c.Request, false)
			Log.Errorf("[Recovery] panic recovered:\n%s\n%s\n%s", string(httpRequest), err, stack)
			c.AbortWithStatus(500)
		}
	}()
	c.Next()
}

type GinTask struct {
	*gin.Engine
	Endpoint     string
	ShutdownHook func()

	server      *http.Server
	c           StopChan
	shutdownErr error
}

func NewGinTask(endpoint string) *GinTask {
	return NewGinTaskWithHandler(endpoint, nil)
}

func NewGinTaskWithHandler(endpoint string, logHandler *GinLogHandler) *GinTask {
	return &GinTask{
		Engine:   NewGinEngineWithHandler(logHandler),
		Endpoint: endpoint,
	}
}

func (task *GinTask) Start(wg *sync.WaitGroup) StopChan {
	task.c = NewStopChan()
	if wg != nil {
		wg.Add(1)
	}
	go func() {
		if wg != nil {
			defer wg.Done()
		}
		task.server = &http.Server{Addr: task.Endpoint, Handler: task.Engine}
		Log.Infoln("Starting", task)
		err := task.server.ListenAndServe()
		if hook := task.ShutdownHook; hook != nil {
			hook()
		}
		if err == http.ErrServerClosed {
			err = nil
		}
		if task.shutdownErr != nil {
			if err == nil {
				err = task.shutdownErr
			} else {
				err = MultiError([]error{task.shutdownErr, err})
			}
		}
		task.c.StopErr(err)
	}()
	return task.c
}

func (task *GinTask) Stop() {
	server := task.server
	if server != nil {
		Log.Infoln("Shutting down", task)
		task.shutdownErr = server.Shutdown(context.Background())
	}
}

func (task *GinTask) String() string {
	return fmt.Sprintf("HTTP server on " + task.Endpoint)
}

func ToUtf8(iso8859 string) string {
	iso8859bytes := []byte(iso8859)
	buf := make([]rune, len(iso8859bytes))
	for i, b := range iso8859bytes {
		buf[i] = rune(b)
	}
	return string(buf)
}

// This function implements gin.HandlerFunc.
// Decode HTTP header keys and values from ISO-8859-1 to UTF-8
func DecodeHeadersToUtf8(ctx *gin.Context) {
	defer ctx.Next()
	for key, values := range ctx.Request.Header {
		changed := false
		decodedKey := ToUtf8(key)
		for i, value := range values {
			decodedValue := ToUtf8(value)
			if value != decodedValue {
				values[i] = decodedValue
				changed = true
			}
		}
		if decodedKey != key {
			changed = true
		}
		if changed {
			delete(ctx.Request.Header, key)
			ctx.Request.Header[decodedKey] = values
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2012 The go-gl 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 glu

// #cgo darwin LDFLAGS: -framework Carbon -framework OpenGL -framework GLUT
// #cgo linux LDFLAGS: -lGLU
// #cgo windows LDFLAGS: -lglu32
//
// #ifdef __APPLE__
//   #include <OpenGL/glu.h>
// #else
//   #include <GL/glu.h>
// #endif
import "C"
import (
	"errors"
	"reflect"
	"unsafe"

	"github.com/go-gl/gl"
)

func ptr(v interface{}) unsafe.Pointer {

	if v == nil {
		return unsafe.Pointer(nil)
	}

	rv := reflect.ValueOf(v)
	var et reflect.Value
	switch rv.Type().Kind() {
	case reflect.Uintptr:
		offset, _ := v.(uintptr)
		return unsafe.Pointer(offset)
	case reflect.Ptr:
		et = rv.Elem()
	case reflect.Slice:
		et = rv.Index(0)
	default:
		panic("type must be a pointer, a slice, uintptr or nil")
	}

	return unsafe.Pointer(et.UnsafeAddr())
}

func ErrorString(error gl.GLenum) (string, error) {
	e := unsafe.Pointer(C.gluErrorString(C.GLenum(error)))
	if e == nil {
		return "", errors.New("Invalid GL error code")
	}
	return C.GoString((*C.char)(e)), nil
}

func Build2DMipmaps(target gl.GLenum, internalFormat int, width, height int, format, typ gl.GLenum, data interface{}) int {
	return int(C.gluBuild2DMipmaps(
		C.GLenum(target),
		C.GLint(internalFormat),
		C.GLsizei(width),
		C.GLsizei(height),
		C.GLenum(format),
		C.GLenum(typ),
		ptr(data),
	))
}

func Perspective(fovy, aspect, zNear, zFar float64) {
	C.gluPerspective(
		C.GLdouble(fovy),
		C.GLdouble(aspect),
		C.GLdouble(zNear),
		C.GLdouble(zFar),
	)
}

func LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64) {
	C.gluLookAt(
		C.GLdouble(eyeX),
		C.GLdouble(eyeY),
		C.GLdouble(eyeZ),
		C.GLdouble(centerX),
		C.GLdouble(centerY),
		C.GLdouble(centerZ),
		C.GLdouble(upX),
		C.GLdouble(upY),
		C.GLdouble(upZ),
	)
}

func UnProject(winX, winY, winZ float64, model, proj *[16]float64, view *[4]int32) (float64, float64, float64) {
	var ox, oy, oz C.GLdouble

	m := (*C.GLdouble)(unsafe.Pointer(model))
	p := (*C.GLdouble)(unsafe.Pointer(proj))
	v := (*C.GLint)(unsafe.Pointer(view))

	C.gluUnProject(
		C.GLdouble(winX),
		C.GLdouble(winY),
		C.GLdouble(winZ),
		m,
		p,
		v,
		&ox,
		&oy,
		&oz,
	)

	return float64(ox), float64(oy), float64(oz)
}

func Project(projX, projY, projZ float64, model, proj *[16]float64, view *[4]int32) (float64, float64, float64) {
	var ox, oy, oz C.GLdouble

	m := (*C.GLdouble)(unsafe.Pointer(model))
	p := (*C.GLdouble)(unsafe.Pointer(proj))
	v := (*C.GLint)(unsafe.Pointer(view))

	C.gluProject(
		C.GLdouble(projX),
		C.GLdouble(projY),
		C.GLdouble(projZ),
		m,
		p,
		v,
		&ox,
		&oy,
		&oz,
	)

	return float64(ox), float64(oy), float64(oz)
}

func NewQuadric() unsafe.Pointer {
	return unsafe.Pointer(C.gluNewQuadric())
}

func Sphere(q unsafe.Pointer, radius float32, slices, stacks int) {
	C.gluSphere((*[0]byte)(q), C.GLdouble(radius), C.GLint(slices), C.GLint(stacks))
}

func Cylinder(q unsafe.Pointer, base, top, height float32, slices, stacks int) {
	C.gluCylinder((*[0]byte)(q), C.GLdouble(base), C.GLdouble(top), C.GLdouble(height), C.GLint(slices), C.GLint(stacks))
}

func Disk(q unsafe.Pointer, inner, outer float32, slices, loops int) {
	C.gluDisk((*[0]byte)(q), C.GLdouble(inner), C.GLdouble(outer), C.GLint(slices), C.GLint(loops))
}

func PartialDisk(q unsafe.Pointer, inner, outer float32, slices, loops int, startAngle, sweepAngle float32) {
	C.gluPartialDisk((*[0]byte)(q), C.GLdouble(inner), C.GLdouble(outer), C.GLint(slices), C.GLint(loops), C.GLdouble(startAngle), C.GLdouble(sweepAngle))
}
<commit_msg>Fixes https://github.com/go-gl/glu/issues/21<commit_after>// Copyright 2012 The go-gl 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 glu

// #cgo darwin LDFLAGS: -framework Carbon -framework OpenGL -framework GLUT
// #cgo linux LDFLAGS: -lGLU
// #cgo windows LDFLAGS: -lglu32
//
// #ifdef __APPLE__
//   #include <OpenGL/glu.h>
// #else
//   #include <GL/glu.h>
// #endif
import "C"
import (
	"errors"
	"reflect"
	"unsafe"

	"github.com/go-gl/gl"
)

func ptr(v interface{}) unsafe.Pointer {

	if v == nil {
		return unsafe.Pointer(nil)
	}

	rv := reflect.ValueOf(v)
	var et reflect.Value
	switch rv.Type().Kind() {
	case reflect.Uintptr:
		offset, _ := v.(uintptr)
		return unsafe.Pointer(offset)
	case reflect.Ptr:
		et = rv.Elem()
	case reflect.Slice:
		et = rv.Index(0)
	default:
		panic("type must be a pointer, a slice, uintptr or nil")
	}

	return unsafe.Pointer(et.UnsafeAddr())
}

func ErrorString(error gl.GLenum) (string, error) {
	e := unsafe.Pointer(C.gluErrorString(C.GLenum(error)))
	if e == nil {
		return "", errors.New("Invalid GL error code")
	}
	return C.GoString((*C.char)(e)), nil
}

func Build2DMipmaps(target gl.GLenum, internalFormat int, width, height int, format, typ gl.GLenum, data interface{}) int {
	return int(C.gluBuild2DMipmaps(
		C.GLenum(target),
		C.GLint(internalFormat),
		C.GLsizei(width),
		C.GLsizei(height),
		C.GLenum(format),
		C.GLenum(typ),
		ptr(data),
	))
}

func Perspective(fovy, aspect, zNear, zFar float64) {
	C.gluPerspective(
		C.GLdouble(fovy),
		C.GLdouble(aspect),
		C.GLdouble(zNear),
		C.GLdouble(zFar),
	)
}

func LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64) {
	C.gluLookAt(
		C.GLdouble(eyeX),
		C.GLdouble(eyeY),
		C.GLdouble(eyeZ),
		C.GLdouble(centerX),
		C.GLdouble(centerY),
		C.GLdouble(centerZ),
		C.GLdouble(upX),
		C.GLdouble(upY),
		C.GLdouble(upZ),
	)
}

func UnProject(winX, winY, winZ float64, model, proj *[16]float64, view *[4]int32) (float64, float64, float64) {
	var ox, oy, oz C.GLdouble

	m := (*C.GLdouble)(unsafe.Pointer(model))
	p := (*C.GLdouble)(unsafe.Pointer(proj))
	v := (*C.GLint)(unsafe.Pointer(view))

	C.gluUnProject(
		C.GLdouble(winX),
		C.GLdouble(winY),
		C.GLdouble(winZ),
		m,
		p,
		v,
		&ox,
		&oy,
		&oz,
	)

	return float64(ox), float64(oy), float64(oz)
}

func Project(projX, projY, projZ float64, model, proj *[16]float64, view *[4]int32) (float64, float64, float64) {
	var ox, oy, oz C.GLdouble

	m := (*C.GLdouble)(unsafe.Pointer(model))
	p := (*C.GLdouble)(unsafe.Pointer(proj))
	v := (*C.GLint)(unsafe.Pointer(view))

	C.gluProject(
		C.GLdouble(projX),
		C.GLdouble(projY),
		C.GLdouble(projZ),
		m,
		p,
		v,
		&ox,
		&oy,
		&oz,
	)

	return float64(ox), float64(oy), float64(oz)
}

func NewQuadric() unsafe.Pointer {
	return unsafe.Pointer(C.gluNewQuadric())
}

func Sphere(q unsafe.Pointer, radius float32, slices, stacks int) {
	C.gluSphere((*C.GLUquadric)(q), C.GLdouble(radius), C.GLint(slices), C.GLint(stacks))
}

func Cylinder(q unsafe.Pointer, base, top, height float32, slices, stacks int) {
	C.gluCylinder((*C.GLUquadric)(q), C.GLdouble(base), C.GLdouble(top), C.GLdouble(height), C.GLint(slices), C.GLint(stacks))
}

func Disk(q unsafe.Pointer, inner, outer float32, slices, loops int) {
	C.gluDisk((*C.GLUquadric)(q), C.GLdouble(inner), C.GLdouble(outer), C.GLint(slices), C.GLint(loops))
}

func PartialDisk(q unsafe.Pointer, inner, outer float32, slices, loops int, startAngle, sweepAngle float32) {
	C.gluPartialDisk((*C.GLUquadric)(q), C.GLdouble(inner), C.GLdouble(outer), C.GLint(slices), C.GLint(loops), C.GLdouble(startAngle), C.GLdouble(sweepAngle))
}
<|endoftext|>


<commit_before>package main

import (
	_ "errors"
	"flag"
	_ "fmt"
	_ "gmq/queue"
	"os"
)

var configfile string
var message = []byte("TEST Message: you know, for testing...")

func main() {

	flag.StringVar(&configfile, "f", "gmq.conf", "Location of configuation file")
	flag.Parse()

	//	if err := parseConfigFile(configfile); err != nil {
	//		panic(errors.New("Unable to parse configuration file %s"))
	//	}
}

func parseConfigFile(f string) error {
	//TODO
	_, err := os.Open(f)
	return err
}
<commit_msg>Cleaned<commit_after>package main

import (
	_ "errors"
	"flag"
	_ "fmt"
	_ "gmq/queue"
	"os"
)

var configfile string

func main() {

	flag.StringVar(&configfile, "f", "gmq.conf", "Configuration file")
	flag.Parse()

	//	if err := parseConfigFile(configfile); err != nil {
	//		panic(errors.New("Unable to parse configuration file %s"))
	//	}
}

func parseConfigFile(f string) error {
	//TODO
	_, err := os.Open(f)
	return err
}
<|endoftext|>


<commit_before>package main

import (
    "flag"
    "fmt"
    "gor/listener"
    "gor/replay"
    "os"
)

var mode string

func main() {
    if len(os.Args) > 1 {
        mode = os.Args[1]
    }

    if mode != "listen" && mode != "replay" {
        fmt.Println("Usage: \n\tgor listen -h\n\tgor replay -h")
        return
    }

    // Remove mode attr
    os.Args = append(os.Args[:1], os.Args[2:]...)

    flag.Parse()

    switch mode {
    case "listen":
        listener.Run()
    case "replay":
        replay.Run()
    }

}
<commit_msg>Updated import paths (changed dirrectories)<commit_after>package main

import (
    "flag"
    "fmt"
    "github.com/buger/gor/listener"
    "github.com/buger/gor/replay"
    "os"
)

var mode string

func main() {
    if len(os.Args) > 1 {
        mode = os.Args[1]
    }

    if mode != "listen" && mode != "replay" {
        fmt.Println("Usage: \n\tgor listen -h\n\tgor replay -h")
        return
    }

    // Remove mode attr
    os.Args = append(os.Args[:1], os.Args[2:]...)

    flag.Parse()

    switch mode {
    case "listen":
        listener.Run()
    case "replay":
        replay.Run()
    }

}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"github.com/scott-linder/irc"
	"log"
	"os"
	"strconv"
	"strings"
	"sync"
)

const (
	configFilename = "hal.json"
)

// config is the main bot config struct.
var config = struct {
	Host string
	Chan string
}{
	Host: "127.0.0.1:6667",
	Chan: "#bots",
}

// loadConfig attempts to load config from configFilename.
func loadConfig() error {
	file, err := os.Open(configFilename)
	if err != nil {
		return err
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&config); err != nil {
		return err
	}
	return nil
}

// Pong plays your game.
type Pong struct{}

func (pong Pong) Accept(msg *irc.Msg) bool { return msg.Cmd == "PING" }
func (pong Pong) Handle(msg *irc.Msg, send chan<- *irc.Msg) {
	send <- &irc.Msg{Cmd: "PONG", Params: msg.Params}
}

// Echo talks back.
type Echo struct{}

func (echo Echo) Accept(msg *irc.Msg) bool { return msg.Cmd == "PRIVMSG" }
func (echo Echo) Handle(msg *irc.Msg, send chan<- *irc.Msg) {
	send <- &irc.Msg{Cmd: "PRIVMSG", Params: msg.Params}
}

// Words counts words.
type Words struct {
	count      *int
	countMutex *sync.Mutex
}

func NewWords() Words {
	return Words{count: new(int), countMutex: new(sync.Mutex)}
}
func (words Words) Accept(msg *irc.Msg) bool { return msg.Cmd == "PRIVMSG" }
func (words Words) Handle(msg *irc.Msg, send chan<- *irc.Msg) {
	source, body, err := msg.ExtractPrivmsg()
	if err != nil {
		return
	}
	if body == "!words" {
		words.countMutex.Lock()
		params := []string{source, strconv.Itoa(*words.count)}
		words.countMutex.Unlock()
		send <- &irc.Msg{Cmd: "PRIVMSG", Params: params}
	} else {
		words.countMutex.Lock()
		for _, _ = range strings.Fields(body) {
			*words.count += 1
		}
		words.countMutex.Unlock()
	}
}

func main() {
	fmt.Println("I am a HAL 9001 computer.")
	if err := loadConfig(); err != nil {
		log.Printf("error loading config file %v: %v", configFilename, err)
	}
	client, err := irc.Dial(config.Host)
	if err != nil {
		log.Fatal(err)
	}
	client.Register(Pong{})
	client.Register(Echo{})
	client.Register(NewWords())
	client.Nick("hal")
	client.Join(config.Chan)
	client.Listen()
}
<commit_msg>Made Echo prefixed.<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"github.com/scott-linder/irc"
	"log"
	"os"
	"strconv"
	"strings"
	"sync"
)

const (
	configFilename = "hal.json"
)

// config is the main bot config struct.
var config = struct {
	Host string
	Chan string
}{
	Host: "127.0.0.1:6667",
	Chan: "#bots",
}

// loadConfig attempts to load config from configFilename.
func loadConfig() error {
	file, err := os.Open(configFilename)
	if err != nil {
		return err
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&config); err != nil {
		return err
	}
	return nil
}

// Pong plays your game.
type Pong struct{}

func (pong Pong) Accept(msg *irc.Msg) bool { return msg.Cmd == "PING" }
func (pong Pong) Handle(msg *irc.Msg, send chan<- *irc.Msg) {
	send <- &irc.Msg{Cmd: "PONG", Params: msg.Params}
}

// Echo talks back.
type Echo struct{}

func (echo Echo) Accept(msg *irc.Msg) bool { return msg.Cmd == "PRIVMSG" }
func (echo Echo) Handle(msg *irc.Msg, send chan<- *irc.Msg) {
	source, body, err := msg.ExtractPrivmsg()
	if err != nil {
		log.Println(err)
		return
	}
	if strings.HasPrefix(body, "!echo ") {
		params := []string{source, strings.TrimPrefix(body, "!echo ")}
		send <- &irc.Msg{Cmd: "PRIVMSG", Params: params}
	}
}

// Words counts words.
type Words struct {
	count      *int
	countMutex *sync.Mutex
}

func NewWords() Words {
	return Words{count: new(int), countMutex: new(sync.Mutex)}
}
func (words Words) Accept(msg *irc.Msg) bool { return msg.Cmd == "PRIVMSG" }
func (words Words) Handle(msg *irc.Msg, send chan<- *irc.Msg) {
	source, body, err := msg.ExtractPrivmsg()
	if err != nil {
		log.Println(err)
		return
	}
	if body == "!words" {
		words.countMutex.Lock()
		params := []string{source, strconv.Itoa(*words.count)}
		words.countMutex.Unlock()
		send <- &irc.Msg{Cmd: "PRIVMSG", Params: params}
	} else {
		words.countMutex.Lock()
		for _, _ = range strings.Fields(body) {
			*words.count += 1
		}
		words.countMutex.Unlock()
	}
}

func main() {
	fmt.Println("I am a HAL 9001 computer.")
	if err := loadConfig(); err != nil {
		log.Printf("error loading config file %v: %v", configFilename, err)
	}
	client, err := irc.Dial(config.Host)
	if err != nil {
		log.Fatal(err)
	}
	client.Register(Pong{})
	client.Register(Echo{})
	client.Register(NewWords())
	client.Nick("hal")
	client.Join(config.Chan)
	client.Listen()
}
<|endoftext|>


<commit_before>// Copyright 2014 Nicolas Vellon.  All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// Package hal implements encoding of structs into HAL as defined in
// http://stateless.co/hal_specification.html.
//
// See the basic example for an introduction to this package:
// https://github.com/nvellon/hal/blob/master/examples/basic.go

package hal

import (
	"encoding/json"
	"reflect"
)

type (
	Entry map[string]interface{}

	// Mapper is the interface implemented by the objects
	// that can be converted into HAL format.
	Mapper interface {
		GetMap() Entry
	}

	Relation string

	CurieHandle struct {
		Name string
		*Resource
	}

	// Link types that store hyperlinks and its attributes.
	LinkAttr       map[string]interface{}
	Link           LinkAttr
	LinkCollection []Link
	LinkRelations  map[Relation]interface{}

	// Resource is a struct that stores a resource data.
	// It represents a converted object in the HAL spec by
	// containing all its fields and also a set of related links
	// and a sub-set of recursively related resources.
	Resource struct {
		Payload  interface{}
		Links    LinkRelations
		Embedded Embedded
		Curies   map[string]*CurieHandle
	}
	ResourceCollection []*Resource

	Embedded map[Relation]interface{}
)

// AddNewLink adds a link to the resources_link collection
// prepended with the curie Name
func (c CurieHandle) AddNewLink(rel Relation, href string) {
	rel = Relation(c.Name) + ":" + rel
	c.Resource.AddLink(rel, NewLink(href, nil))
}

// AddCollection appends the resource into the list of embedded
// resources with the specified relation.
// r should be  a ResourceCollection
func (e Embedded) AddCollection(rel Relation, r ResourceCollection) {
	n := e[rel]
	if n == nil {
		//new embed
		e[rel] = r
		return
	}

	if nc, ok := n.([]*Resource); ok {
		e[rel] = append(nc, r...)
		return
	}

	if nr, ok := n.(*Resource); ok {
		e[rel] = append([]*Resource{nr}, r...)
	}

}

// Add appends the resource into the list of embedded
// resources with the specified relation.
// r should be a Resource
func (e Embedded) Add(rel Relation, r *Resource) {
	n := e[rel]
	if n == nil {
		//new embed
		e[rel] = r
		return
	}

	if nec, ok := n.([]*Resource); ok {
		e[rel] = append(nec, r)
		return
	}

	if nee, ok := n.(*Resource); ok {
		e[rel] = append([]*Resource{nee}, r)
		return
	}

	//something went wrong.. replace what is there with what is new
	e[rel] = []*Resource{r}
}

// Set sets the resource into the list of embedded
// resources with the specified relation. It replaces
// any existing resources associated with the relation.
// r should be a pointer to a Resource
func (e Embedded) Set(rel Relation, r *Resource) {
	e[rel] = r
}

// Set sets the resource into the list of embedded
// resources with the specified relation. It replaces
// any existing resources associated with the relation.
// r should be a ResourceCollection
func (e Embedded) SetCollection(rel Relation, r ResourceCollection) {
	e[rel] = r
}

// Get gets the resources associated with the
// given relation.
//func (e Embedded) Get(rel Relation) []*Resource {
//	return e[rel]
//}

// Del deletes the resources associated with the
// given relation.
func (e Embedded) Del(rel Relation) {
	delete(e, rel)
}

// NewResource creates a Resource object for a given struct
// and its link.
func NewResource(p interface{}, selfUri string) *Resource {
	var r Resource

	r.Payload = p

	r.Links = make(LinkRelations)
	r.AddNewLink("self", selfUri)

	r.Embedded = make(Embedded)
	r.Curies = make(map[string]*CurieHandle)

	return &r
}

// AddLinkCollection appends a LinkCollection to the resource.
// l should be a LinkCollection
func (r *Resource) AddLinkCollection(rel Relation, l LinkCollection) {
	n := r.Links[rel]
	if n == nil {
		//new link
		r.Links[rel] = l
		return
	}

	if nc, ok := n.(LinkCollection); ok {
		r.Links[rel] = append(nc, l...)
		return
	}

	if nl, ok := n.(Link); ok {
		//prepend existing link to collection
		r.Links[rel] = append(LinkCollection{nl}, l...)
	}
}

// AddLink appends a Link to the resource.
// l should be a Link
func (r *Resource) AddLink(rel Relation, l Link) {
	n := r.Links[rel]
	if n == nil {
		//new link
		r.Links[rel] = l
		return
	}

	if nc, ok := n.(LinkCollection); ok {
		r.Links[rel] = append(nc, l)
		return
	}

	if nl, ok := n.(Link); ok {
		r.Links[rel] = append(LinkCollection{nl}, l)
		return
	}

	//something went wrong.. replace what is there with what is new
	r.Links[rel] = LinkCollection{l}
}

// AddNewLink appends a new Link object based on
// the rel and href params.
func (r *Resource) AddNewLink(rel Relation, href string) {
	r.AddLink(rel, NewLink(href, nil))
}

// RegisterCurie adds a Link relation of type 'curies' and returns a CurieHandle
// to allow users to fluently add new links that have this curie relation definition
func (r *Resource) RegisterCurie(name, href string, templated bool) *CurieHandle {
	l := LinkCollection{
		NewLink(href, LinkAttr{"name": name}, LinkAttr{"templated": templated}),
	}
	r.AddLinkCollection("curies", l)

	handle := &CurieHandle{Name: name, Resource: r}

	r.Curies[name] = handle
	return handle
}

// Embed appends a Resource to the array of
// embedded resources.
// re should be a pointer to a Resource
func (r *Resource) Embed(rel Relation, re *Resource) {
	r.Embedded.Add(rel, re)
}

// EmbedCollection appends a ResourceCollection to the array of
// embedded resources.
// re should be a ResourceCollection
func (r *Resource) EmbedCollection(rel Relation, re ResourceCollection) {
	r.Embedded.AddCollection(rel, re)
}

// Map implements the interface Mapper.
func (r Resource) GetMap() Entry {
	mapped := make(Entry)

	var mp Entry
	// Check if payload implements Mapper interface
	if mapper, ok := r.Payload.(Mapper); ok {
		mp = mapper.GetMap()
	} else {
		mp = r.getPayloadMap()
	}

	for k, v := range mp {
		mapped[k] = v
	}

	mapped["_links"] = r.Links

	if len(r.Embedded) > 0 {
		mapped["_embedded"] = r.Embedded
	}

	return mapped
}

func (r *Resource) getPayloadMap() Entry {

	val := reflect.ValueOf(r.Payload)
	payloadMap := Entry{}

	for i := 0; i < val.NumField(); i++ {

		typeField := val.Type().Field(i)
		tag := typeField.Tag
		tagValue := tag.Get("json")
		if tagValue != "-" {
			valueField := val.Field(i)

			if tagValue == "" {
				tagValue = typeField.Name
			}

			payloadMap[tagValue] = valueField.Interface()
		}
	}

	return payloadMap
}

// MarshalJSON is a Marshaler interface implementation
// for Resource struct
func (r Resource) MarshalJSON() ([]byte, error) {
	return json.Marshal(r.GetMap())
}

// NewLink returns a new Link object.
func NewLink(href string, attrs ...LinkAttr) Link {
	l := make(Link)

	l["href"] = href

	for _, attr := range attrs {
		for k, v := range attr {
			l[k] = v
		}
	}

	return l
}
<commit_msg>added omitempty management<commit_after>// Copyright 2014 Nicolas Vellon.  All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// Package hal implements encoding of structs into HAL as defined in
// http://stateless.co/hal_specification.html.
//
// See the basic example for an introduction to this package:
// https://github.com/nvellon/hal/blob/master/examples/basic.go

package hal

import (
	"encoding/json"
	"reflect"
	"strings"
)

type (
	Entry map[string]interface{}

	// Mapper is the interface implemented by the objects
	// that can be converted into HAL format.
	Mapper interface {
		GetMap() Entry
	}

	Relation string

	CurieHandle struct {
		Name string
		*Resource
	}

	// Link types that store hyperlinks and its attributes.
	LinkAttr       map[string]interface{}
	Link           LinkAttr
	LinkCollection []Link
	LinkRelations  map[Relation]interface{}

	// Resource is a struct that stores a resource data.
	// It represents a converted object in the HAL spec by
	// containing all its fields and also a set of related links
	// and a sub-set of recursively related resources.
	Resource struct {
		Payload  interface{}
		Links    LinkRelations
		Embedded Embedded
		Curies   map[string]*CurieHandle
	}
	ResourceCollection []*Resource

	Embedded map[Relation]interface{}
)

// AddNewLink adds a link to the resources_link collection
// prepended with the curie Name
func (c CurieHandle) AddNewLink(rel Relation, href string) {
	rel = Relation(c.Name) + ":" + rel
	c.Resource.AddLink(rel, NewLink(href, nil))
}

// AddCollection appends the resource into the list of embedded
// resources with the specified relation.
// r should be  a ResourceCollection
func (e Embedded) AddCollection(rel Relation, r ResourceCollection) {
	n := e[rel]
	if n == nil {
		//new embed
		e[rel] = r
		return
	}

	if nc, ok := n.([]*Resource); ok {
		e[rel] = append(nc, r...)
		return
	}

	if nr, ok := n.(*Resource); ok {
		e[rel] = append([]*Resource{nr}, r...)
	}

}

// Add appends the resource into the list of embedded
// resources with the specified relation.
// r should be a Resource
func (e Embedded) Add(rel Relation, r *Resource) {
	n := e[rel]
	if n == nil {
		//new embed
		e[rel] = r
		return
	}

	if nec, ok := n.([]*Resource); ok {
		e[rel] = append(nec, r)
		return
	}

	if nee, ok := n.(*Resource); ok {
		e[rel] = append([]*Resource{nee}, r)
		return
	}

	//something went wrong.. replace what is there with what is new
	e[rel] = []*Resource{r}
}

// Set sets the resource into the list of embedded
// resources with the specified relation. It replaces
// any existing resources associated with the relation.
// r should be a pointer to a Resource
func (e Embedded) Set(rel Relation, r *Resource) {
	e[rel] = r
}

// Set sets the resource into the list of embedded
// resources with the specified relation. It replaces
// any existing resources associated with the relation.
// r should be a ResourceCollection
func (e Embedded) SetCollection(rel Relation, r ResourceCollection) {
	e[rel] = r
}

// Get gets the resources associated with the
// given relation.
//func (e Embedded) Get(rel Relation) []*Resource {
//	return e[rel]
//}

// Del deletes the resources associated with the
// given relation.
func (e Embedded) Del(rel Relation) {
	delete(e, rel)
}

// NewResource creates a Resource object for a given struct
// and its link.
func NewResource(p interface{}, selfUri string) *Resource {
	var r Resource

	r.Payload = p

	r.Links = make(LinkRelations)
	r.AddNewLink("self", selfUri)

	r.Embedded = make(Embedded)
	r.Curies = make(map[string]*CurieHandle)

	return &r
}

// AddLinkCollection appends a LinkCollection to the resource.
// l should be a LinkCollection
func (r *Resource) AddLinkCollection(rel Relation, l LinkCollection) {
	n := r.Links[rel]
	if n == nil {
		//new link
		r.Links[rel] = l
		return
	}

	if nc, ok := n.(LinkCollection); ok {
		r.Links[rel] = append(nc, l...)
		return
	}

	if nl, ok := n.(Link); ok {
		//prepend existing link to collection
		r.Links[rel] = append(LinkCollection{nl}, l...)
	}
}

// AddLink appends a Link to the resource.
// l should be a Link
func (r *Resource) AddLink(rel Relation, l Link) {
	n := r.Links[rel]
	if n == nil {
		//new link
		r.Links[rel] = l
		return
	}

	if nc, ok := n.(LinkCollection); ok {
		r.Links[rel] = append(nc, l)
		return
	}

	if nl, ok := n.(Link); ok {
		r.Links[rel] = append(LinkCollection{nl}, l)
		return
	}

	//something went wrong.. replace what is there with what is new
	r.Links[rel] = LinkCollection{l}
}

// AddNewLink appends a new Link object based on
// the rel and href params.
func (r *Resource) AddNewLink(rel Relation, href string) {
	r.AddLink(rel, NewLink(href, nil))
}

// RegisterCurie adds a Link relation of type 'curies' and returns a CurieHandle
// to allow users to fluently add new links that have this curie relation definition
func (r *Resource) RegisterCurie(name, href string, templated bool) *CurieHandle {
	l := LinkCollection{
		NewLink(href, LinkAttr{"name": name}, LinkAttr{"templated": templated}),
	}
	r.AddLinkCollection("curies", l)

	handle := &CurieHandle{Name: name, Resource: r}

	r.Curies[name] = handle
	return handle
}

// Embed appends a Resource to the array of
// embedded resources.
// re should be a pointer to a Resource
func (r *Resource) Embed(rel Relation, re *Resource) {
	r.Embedded.Add(rel, re)
}

// EmbedCollection appends a ResourceCollection to the array of
// embedded resources.
// re should be a ResourceCollection
func (r *Resource) EmbedCollection(rel Relation, re ResourceCollection) {
	r.Embedded.AddCollection(rel, re)
}

// Map implements the interface Mapper.
func (r Resource) GetMap() Entry {
	mapped := make(Entry)

	var mp Entry
	// Check if payload implements Mapper interface
	if mapper, ok := r.Payload.(Mapper); ok {
		mp = mapper.GetMap()
	} else {
		mp = r.getPayloadMap()
	}

	for k, v := range mp {
		mapped[k] = v
	}

	mapped["_links"] = r.Links

	if len(r.Embedded) > 0 {
		mapped["_embedded"] = r.Embedded
	}

	return mapped
}

func (r *Resource) getPayloadMap() Entry {

	val := reflect.ValueOf(r.Payload)
	payloadMap := Entry{}

	for i := 0; i < val.NumField(); i++ {
		typeField := val.Type().Field(i)
		tag := typeField.Tag
		tagValue := tag.Get("json")
		if strings.Contains(tagValue, "omitempty") {

			l := strings.Split(tagValue, ",")
			for i, el := range l {
				if el == "omitempty" {
					l = append(l[:i], l[i+1:]...)
					break
				}
			}
			tagValue = strings.Join(l, ",")

		}
		if tagValue != "-" {
			valueField := val.Field(i)

			if tagValue == "" {
				tagValue = typeField.Name
			}

			payloadMap[tagValue] = valueField.Interface()
		}
	}

	return payloadMap
}

// MarshalJSON is a Marshaler interface implementation
// for Resource struct
func (r Resource) MarshalJSON() ([]byte, error) {
	return json.Marshal(r.GetMap())
}

// NewLink returns a new Link object.
func NewLink(href string, attrs ...LinkAttr) Link {
	l := make(Link)

	l["href"] = href

	for _, attr := range attrs {
		for k, v := range attr {
			l[k] = v
		}
	}

	return l
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
)

func main() {
	var s string
	var cFile bool = (filepath.Ext(os.Args[1]) == "c")
	var lastLine bool
	if len(os.Args) > 2 && os.Args[2] == "--lastline=true" {
		lastLine = true
	}

	//MakeFile()
	s = Removecomments(Format(os.Args[1]))
	splitFile := strings.Split(s, "\n")
	splitFile = RemoveNewlines(splitFile)
	lineSlice := CreateLines(splitFile)
	MarkInvalid(lineSlice)
	debugFile, _ := os.Create("testfiles/c++/debug.cpp")

	for i := 0; i < len(lineSlice); i++ {
		AddPrint(debugFile, lineSlice[i], cFile)
	}
	debugFile.Close()
	CompileAndRun(lastLine)
}

type lineType struct {
	s    string
	code int
	info string
}

func AddPrint(file *os.File, line lineType, cFile bool) {
	if cFile {
		if line.code == 0 {
			file.WriteString("printf(\"" + line.s + "\n\");\n")
			file.WriteString(line.s + "\n")
		}
	} else {
		whiteSpaceSize := len(line.s) - len(strings.TrimLeft(line.s, "\t"))
		if whiteSpaceSize == 0 {
			whiteSpaceSize = 4
		}
		whiteSpaceIf := strings.Repeat("\t", whiteSpaceSize+1)
		whiteSpaceLoop := strings.Repeat("\t", whiteSpaceSize)
		switch line.code {
		case 0:
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
		case 343: //function
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + "Entering " + line.info + "\" << std::endl;\n")
		case 666: //if
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceIf + "if statement: " + line.info + " evaluates to true\" << std::endl;\n")
		case 752: //else if
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceIf + "else if statement: " + line.info + " evaluates to true\" << std::endl;\n")
		case 580: //else
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" +  whiteSpaceIf + "else statement:\" << std::endl;\n")
		case 4: //for
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceLoop + "looping: " + line.info + "\" << std::endl;\n")
		case 603: //while
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceLoop + line.info + " evaluates to true\" << std::endl;\n")
		case 1:
			file.WriteString(line.s + "\n")
		}
	}
}
func MarkInvalid(lineSlice []lineType) {

	elseifR, _ := regexp.Compile(`(\s*)\}(\s*)else(\s*)if(\s*)\((.*)\)(\s*)\{(\s*)`)
	ifR, _ := regexp.Compile(`(\s*)if(\s*)\((.*)\)(\s*)\{(\s*)`)
	forR, _ := regexp.Compile(`(\s*)for(\s*)\((.*)\)(\s*)\{(\s*)`)
	whileR, _ := regexp.Compile(`(\s*)while(\s*)\((.*)\)(\s*)\{(\s*)`)
	funcR, _ := regexp.Compile(`(.*)\((.*)\)(\s*)\{(\s*)`)

	classR, _ := regexp.Compile(`(\s*)class(.*)\{`)
	structR, _ := regexp.Compile(`(\s*)struct(.*)\{`)
	elseR, _ := regexp.Compile(`(\s*)\}(\s*)else(\s*)\{`)
	scopeR, _ := regexp.Compile(`(\s*)\{(\s*)`)
	closeR, _ := regexp.Compile(`(\s*)\}(\s*)`)

	stack := []int{}

	for i := 0; i < len(lineSlice); i++ {
		if elseifR.MatchString(lineSlice[i].s) {
			//elseif
			lineSlice[i].code = 752
			PopStack(stack)
			stack = append(stack, 752)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if ifR.MatchString(lineSlice[i].s) {
			//if
			lineSlice[i].code = 666
			stack = append(stack, 666)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if forR.MatchString(lineSlice[i].s) {
			//for
			lineSlice[i].code = 4
			stack = append(stack, 4)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if whileR.MatchString(lineSlice[i].s) {
			//while
			lineSlice[i].code = 603
			stack = append(stack, 603)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if funcR.MatchString(lineSlice[i].s) {
			//func
			lineSlice[i].code = 343
			stack = append(stack, 343)
			drill := strings.SplitN(lineSlice[i].s, "(", 2)[0]
			drillList := strings.Fields(drill)
			lineSlice[i].info = drillList[len(drillList)-1]
		} else if classR.MatchString(lineSlice[i].s) {
			//class
			lineSlice[i].code = 1
			stack = append(stack, 1)
		} else if structR.MatchString(lineSlice[i].s) {
			//struct
			lineSlice[i].code = 1
			stack = append(stack, 1)
		} else if elseR.MatchString(lineSlice[i].s) {
			//else
			lineSlice[i].code = 580
			PopStack(stack)
			stack = append(stack, 580)
		} else if scopeR.MatchString(lineSlice[i].s) {
			//scope
			lineSlice[i].code = 0
			stack = append(stack, 0)
		} else if closeR.MatchString(lineSlice[i].s) {
			//close
			lineSlice[i].code = 1
			PopStack(stack)
		} else {
			if InFunction(stack) {
				lineSlice[i].code = 0
			} else {
				lineSlice[i].code = 1
			}
		}
	}
}

func GetParenContents(line string) string {
	parensR, _ := regexp.Compile(`\((.*)\)`)
	parensR.Longest()
	return parensR.FindString(line)
}

func InFunction(stack []int) (exists bool) {
	for i := 0; i < len(stack); i++ {
		if stack[i] == 343 {
			return true
		}
	}
	return false
}

func PopStack(stack []int) {
	stack = stack[:len(stack)-1]
}

func CreateLines(stringSlice []string) []lineType {
	var lineSlice []lineType
	for i := 0; i < len(stringSlice); i++ {
		lineSlice = append(lineSlice, lineType{stringSlice[i], 0, ""})
	}
	return lineSlice
}

func RemoveNewlines(stringSlice []string) []string {
	var newSlice []string
	for i := 0; i < len(stringSlice); i++ {
		if stringSlice[i] != "" && strings.TrimLeft(stringSlice[i], " ") != "" && strings.TrimLeft(stringSlice[i], " ")[0] != 10 {
			newSlice = append(newSlice, stringSlice[i])
		}
	}
	return newSlice
}

func CompileAndRun(lastLine bool) {
	gccCmd := exec.Command("g++", "-Wall", "testfiles/c++/debug.cpp", "-o", "testfiles/c++/out")
	gccCmd.Run()
	runCmd := exec.Command("./testfiles/c++/out")
	output, err := runCmd.Output()
	if !lastLine {
		fmt.Println(string(output))
	} else {
		outSlice := strings.Split(strings.TrimSpace(string(output)), "\n")
		fmt.Println(outSlice[len(outSlice)-1])
	}
	fmt.Println(err)
}

func Removecomments(s string) string {
	r, _ := regexp.Compile(`/\*(.*?)\*/|//(.*?)\n`)
	ret := r.ReplaceAllString(s, "\n")
	fmt.Println("TEST\n" + ret + "\nENDTEST\n")
	return ret
}

/*
func MakeFile() {
	makeCmd := exec.Command("make", "-f", "astyle/build/gcc/Makefile")
	err := makeCmd.Run()
	if err != nil {
		panic(err)
	}
}
*/

func Format(f string) string {
	var s string
	filename := os.Args[1]
	out, err := exec.Command("uncrustify/src/uncrustify","-c","uncrustify/etc/hdb.cfg","-f",filename).Output()
	if err !=nil {
		panic(err)
	}
	s = string(out)
	return s
}
<commit_msg>Tracking variables in for loops<commit_after>package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
)

func main() {
	var s string
	var cFile bool = (filepath.Ext(os.Args[1]) == "c")
	var lastLine bool
	if len(os.Args) > 2 && os.Args[2] == "--lastline=true" {
		lastLine = true
	}

	//MakeFile()
	s = Removecomments(Format(os.Args[1]))
	splitFile := strings.Split(s, "\n")
	splitFile = RemoveNewlines(splitFile)
	lineSlice := CreateLines(splitFile)
	MarkInvalid(lineSlice)
	debugFile, _ := os.Create("testfiles/c++/debug.cpp")

	for i := 0; i < len(lineSlice); i++ {
		AddPrint(debugFile, lineSlice[i], cFile)
	}
	debugFile.Close()
	CompileAndRun(lastLine)
}

type lineType struct {
	s    string
	code int
	info string
}

func AddPrint(file *os.File, line lineType, cFile bool) {
	if cFile {
		if line.code == 0 {
			file.WriteString("printf(\"" + line.s + "\n\");\n")
			file.WriteString(line.s + "\n")
		}
	} else {
		whiteSpaceSize := len(line.s) - len(strings.TrimLeft(line.s, "\t"))
		if whiteSpaceSize == 0 {
			whiteSpaceSize = 4
		}
		whiteSpaceIf := strings.Repeat("\t", whiteSpaceSize+1)
		whiteSpaceLoop := strings.Repeat("\t", whiteSpaceSize)
		switch line.code {
		case 0:
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
		case 343: //function
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + "Entering " + line.info + "\" << std::endl;\n")
		case 666: //if
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceIf + "if statement: " + line.info + " evaluates to true\" << std::endl;\n")
		case 752: //else if
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceIf + "else if statement: " + line.info + " evaluates to true\" << std::endl;\n")
		case 580: //else
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" +  whiteSpaceIf + "else statement:\" << std::endl;\n")
		case 4: //for
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
			forArgs := strings.Split(line.info, ";")
			if strings.Contains(forArgs[0], "int ") {
				index := strings.Split(forArgs[0], " ")[1]
				file.WriteString("std::cout << \"" + whiteSpaceLoop + "looping: " + "\" << " + index + " << std::endl;\n")
			} else {
				file.WriteString("std::cout << \"" + whiteSpaceLoop + "looping: " + line.info + "\" << std::endl;\n")
			}
		case 603: //while
			file.WriteString("std::cout << \"" + line.s + "\" << std::endl;\n")
			file.WriteString(line.s + "\n")
			file.WriteString("std::cout << \"" + whiteSpaceLoop + line.info + " evaluates to true\" << std::endl;\n")
		case 1:
			file.WriteString(line.s + "\n")
		}
	}
}
func MarkInvalid(lineSlice []lineType) {

	elseifR, _ := regexp.Compile(`(\s*)\}(\s*)else(\s*)if(\s*)\((.*)\)(\s*)\{(\s*)`)
	ifR, _ := regexp.Compile(`(\s*)if(\s*)\((.*)\)(\s*)\{(\s*)`)
	forR, _ := regexp.Compile(`(\s*)for(\s*)\((.*)\)(\s*)\{(\s*)`)
	whileR, _ := regexp.Compile(`(\s*)while(\s*)\((.*)\)(\s*)\{(\s*)`)
	funcR, _ := regexp.Compile(`(.*)\((.*)\)(\s*)\{(\s*)`)

	classR, _ := regexp.Compile(`(\s*)class(.*)\{`)
	structR, _ := regexp.Compile(`(\s*)struct(.*)\{`)
	elseR, _ := regexp.Compile(`(\s*)\}(\s*)else(\s*)\{`)
	scopeR, _ := regexp.Compile(`(\s*)\{(\s*)`)
	closeR, _ := regexp.Compile(`(\s*)\}(\s*)`)

	stack := []int{}

	for i := 0; i < len(lineSlice); i++ {
		if elseifR.MatchString(lineSlice[i].s) {
			//elseif
			lineSlice[i].code = 752
			PopStack(stack)
			stack = append(stack, 752)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if ifR.MatchString(lineSlice[i].s) {
			//if
			lineSlice[i].code = 666
			stack = append(stack, 666)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if forR.MatchString(lineSlice[i].s) {
			//for
			lineSlice[i].code = 4
			stack = append(stack, 4)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if whileR.MatchString(lineSlice[i].s) {
			//while
			lineSlice[i].code = 603
			stack = append(stack, 603)
			lineSlice[i].info = GetParenContents(lineSlice[i].s)
		} else if funcR.MatchString(lineSlice[i].s) {
			//func
			lineSlice[i].code = 343
			stack = append(stack, 343)
			drill := strings.SplitN(lineSlice[i].s, "(", 2)[0]
			drillList := strings.Fields(drill)
			lineSlice[i].info = drillList[len(drillList)-1]
		} else if classR.MatchString(lineSlice[i].s) {
			//class
			lineSlice[i].code = 1
			stack = append(stack, 1)
		} else if structR.MatchString(lineSlice[i].s) {
			//struct
			lineSlice[i].code = 1
			stack = append(stack, 1)
		} else if elseR.MatchString(lineSlice[i].s) {
			//else
			lineSlice[i].code = 580
			PopStack(stack)
			stack = append(stack, 580)
		} else if scopeR.MatchString(lineSlice[i].s) {
			//scope
			lineSlice[i].code = 0
			stack = append(stack, 0)
		} else if closeR.MatchString(lineSlice[i].s) {
			//close
			lineSlice[i].code = 1
			PopStack(stack)
		} else {
			if InFunction(stack) {
				lineSlice[i].code = 0
			} else {
				lineSlice[i].code = 1
			}
		}
	}
}

func GetParenContents(line string) string {
	parensR, _ := regexp.Compile(`\((.*)\)`)
	parensR.Longest()
	return parensR.FindString(line)
}

func InFunction(stack []int) (exists bool) {
	for i := 0; i < len(stack); i++ {
		if stack[i] == 343 {
			return true
		}
	}
	return false
}

func PopStack(stack []int) {
	stack = stack[:len(stack)-1]
}

func CreateLines(stringSlice []string) []lineType {
	var lineSlice []lineType
	for i := 0; i < len(stringSlice); i++ {
		lineSlice = append(lineSlice, lineType{stringSlice[i], 0, ""})
	}
	return lineSlice
}

func RemoveNewlines(stringSlice []string) []string {
	var newSlice []string
	for i := 0; i < len(stringSlice); i++ {
		if stringSlice[i] != "" && strings.TrimLeft(stringSlice[i], " ") != "" && strings.TrimLeft(stringSlice[i], " ")[0] != 10 {
			newSlice = append(newSlice, stringSlice[i])
		}
	}
	return newSlice
}

func CompileAndRun(lastLine bool) {
	gccCmd := exec.Command("g++", "-Wall", "testfiles/c++/debug.cpp", "-o", "testfiles/c++/out")
	gccCmd.Run()
	runCmd := exec.Command("./testfiles/c++/out")
	output, err := runCmd.Output()
	if !lastLine {
		fmt.Println(string(output))
	} else {
		outSlice := strings.Split(strings.TrimSpace(string(output)), "\n")
		fmt.Println(outSlice[len(outSlice)-1])
	}
	fmt.Println(err)
}

func Removecomments(s string) string {
	r, _ := regexp.Compile(`/\*(.*?)\*/|//(.*?)\n`)
	ret := r.ReplaceAllString(s, "\n")
	fmt.Println("TEST\n" + ret + "\nENDTEST\n")
	return ret
}

/*
func MakeFile() {
	makeCmd := exec.Command("make", "-f", "astyle/build/gcc/Makefile")
	err := makeCmd.Run()
	if err != nil {
		panic(err)
	}
}
*/

func Format(f string) string {
	var s string
	filename := os.Args[1]
	out, err := exec.Command("uncrustify/src/uncrustify","-c","uncrustify/etc/hdb.cfg","-f",filename).Output()
	if err !=nil {
		panic(err)
	}
	s = string(out)
	return s
}
<|endoftext|>


<commit_before>// Copyright 2013 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package id3

import (
	"bufio"
	"io/ioutil"
	"os"
)

// Tagger represents the metadata of a tag
type Tagger interface {
	Title() string
	Artist() string
	Album() string
	Year() string
	Genre() string
	Comments() []string
	SetTitle(string)
	SetArtist(string)
	SetAlbum(string)
	SetYear(string)
	SetGenre(string)
	AllFrames() []Framer
	Frames(string) []Framer
	Frame(string) Framer
	DeleteFrames(string) []Framer
	AddFrame(Framer)
	Bytes() []byte
	Padding() uint
	Version() string
}

// File represents the tagged file
type File struct {
	Tagger
	name string
	data []byte
}

// Opens a new tagged file
func Open(name string) (*File, error) {
	fi, err := os.Open(name)
	defer fi.Close()
	if err != nil {
		return nil, err
	}

	rd := bufio.NewReader(fi)
	tag := NewTag(rd)
	data, err := ioutil.ReadAll(rd)
	if err != nil {
		return nil, err
	}

	return &File{
		tag,
		name,
		data,
	}, nil
}

// Saves any edits to the tagged file
func (f *File) Close() {
	fi, err := os.Create(f.name)
	defer fi.Close()
	if err != nil {
		panic(err)
	}

	wr := bufio.NewWriter(fi)
	wr.Write(f.Tagger.Bytes())
	wr.Write(f.data)
}
<commit_msg>Resolve #3 Allow partial rewrite with padding<commit_after>// Copyright 2013 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package id3

import (
	"bufio"
	"io/ioutil"
	"os"
)

// Tagger represents the metadata of a tag
type Tagger interface {
	Title() string
	Artist() string
	Album() string
	Year() string
	Genre() string
	Comments() []string
	SetTitle(string)
	SetArtist(string)
	SetAlbum(string)
	SetYear(string)
	SetGenre(string)
	AllFrames() []Framer
	Frames(string) []Framer
	Frame(string) Framer
	DeleteFrames(string) []Framer
	AddFrame(Framer)
	Bytes() []byte
	Padding() uint
	Size() int
	Version() string
}

// File represents the tagged file
type File struct {
	Tagger
	originalSize int
	name         string
	data         []byte
}

// Opens a new tagged file
func Open(name string) (*File, error) {
	fi, err := os.Open(name)
	defer fi.Close()
	if err != nil {
		return nil, err
	}

	rd := bufio.NewReader(fi)
	tag := NewTag(rd)
	data, err := ioutil.ReadAll(rd)
	if err != nil {
		return nil, err
	}

	return &File{
		tag,
		tag.Size(),
		name,
		data,
	}, nil
}

// Saves any edits to the tagged file
func (f *File) Close() {
	fi, err := os.OpenFile(f.name, os.O_RDWR, 0666)
	defer fi.Close()
	if err != nil {
		panic(err)
	}

	wr := bufio.NewWriter(fi)
	wr.Write(f.Tagger.Bytes())

	if f.Size() > f.originalSize {
		wr.Write(f.data)
	}
}
<|endoftext|>


<commit_before>package rabbitgo

import (
  //"errors"
  "time"
  "fmt"
  "github.com/streadway/amqp"
  log "github.com/koding/logging"
)

type Consumer struct {
	conn        *Connection
	ch          *amqp.Channel
  e           *Exchange
  q           *Queue
	deliveries  <-chan amqp.Delivery
  handler     func(amqp.Delivery)
	handlerRPC  func(amqp.Delivery)([]byte, string)
  cc          *ConsumerConfig
  bc          *BindingConfig
  closed      bool
	// A notifiyng channel for publishings
	// will be used for sync. between close channel and consume handler
	done        chan error
}

type ConsumerConfig struct {
	Tag            string
  PrefetchCount  int
  PrefetchSize   int
  Timeout        int
	AutoAck        bool
	Exclusive      bool
	NoLocal        bool
	NoWait         bool
	Args           amqp.Table
}

type BindingConfig struct {
	RoutingKey string
	NoWait bool
	Args amqp.Table
}

func (c *Consumer) Deliveries() <-chan amqp.Delivery {
	return c.deliveries
}

// NewConsumer is a constructor for consumer creation
// Accepts Exchange, Queue, BindingOptions and ConsumerOptions
func (c *Connection) NewConsumer(e *Exchange, q *Queue, bc *BindingConfig, cc *ConsumerConfig) (*Consumer, error) {
  ch, err := c.conn.Channel()
  if err != nil {
    return nil, err
  }
	consumer := &Consumer {
    conn: c,
    ch:   ch,
		done: make(chan error),
    cc:   cc,
    bc:   bc,
		e:    e,
    q:    q,
	}
	if err := consumer.connect(); err != nil {
		return nil, err
	}
	return consumer, nil
}

// connect internally declares the exchanges and queues
func (c *Consumer) connect() error {
	_, err := c.ch.QueueDeclare(
		c.q.Name,       // name of the queue
		c.q.Durable,    // durable
		c.q.AutoDelete, // delete when usused
		c.q.Exclusive,  // exclusive
		c.q.NoWait,     // noWait
		c.q.Args,       // arguments
	)
	if err != nil {
		return err
	}
  err = c.ch.Qos(
    c.cc.PrefetchCount,     // prefetch count
    c.cc.PrefetchSize,     // prefetch size
    false,               // global
  )
  if err != nil {
    return err
  }
  if c.e != nil {
    err := c.ch.ExchangeDeclare(
      c.e.Name,       // name of the exchange
      c.e.Type,       // type
      c.e.Durable,    // durable
      c.e.AutoDelete, // delete when complete
      c.e.Internal,   // internal
      c.e.NoWait,     // noWait
      c.e.Args,       // arguments
    )
    if err != nil {
      return err
    }
    err = c.ch.QueueBind(
  		// bind to real queue
  		c.q.Name,        // name of the queue
  		c.bc.RoutingKey, // bindingKey
  		c.e.Name,        // sourceExchange
  		c.bc.NoWait,     // noWait
  		c.bc.Args,       // arguments
  	)
    if err != nil {
  		return err
  	}
  }
	return nil
}

func (c *Consumer) consume() error {
  deliveries, err := c.ch.Consume(
    c.q.Name,       // name
    c.cc.Tag,       // consumerTag,
    c.cc.AutoAck,   // autoAck
    c.cc.Exclusive, // exclusive
    c.cc.NoLocal,   // noLocal
    c.cc.NoWait,    // noWait
    c.cc.Args,      // arguments
  )
  // should we stop streaming, in order not to consume from server?
  c.deliveries = deliveries
  return err
}

// Consume accepts a handler function for every message streamed from RabbitMq
// will be called within this handler func
func (c *Consumer) Consume(handler func(delivery amqp.Delivery)) error {
  err := c.consume()
  if err != nil {
    return err
  }
  go func() {
    if timeout := c.cc.Timeout; timeout > 0 {
      time.Sleep(time.Duration(timeout) * time.Millisecond)
      if c.closed == false {
        c.Shutdown()
        log.Error("Timeout")
      }
    }
  }()
	c.handler = handler
	log.Info("handle: deliveries channel starting")
	// handle all consumer errors, if required re-connect
	// there are problems with reconnection logic for now
  for delivery := range c.deliveries {
		handler(delivery)
	}
	log.Info("handle: deliveries channel closed")
  //This was blocking the flow. Not sure how needed is.
	//c.done <- nil
	return nil
}

// ConsumeRPC accepts a handler function for every message streamed from RabbitMq
// will be called within this handler func.
// It returns the message to send and the content type.
func (c *Consumer) ConsumeRPC(handler func(delivery amqp.Delivery)([]byte, string)) error {
	deliveries, err := c.ch.Consume(
		c.q.Name,       // name
		c.cc.Tag,       // consumerTag,
		c.cc.AutoAck,   // autoAck
		c.cc.Exclusive, // exclusive
		c.cc.NoLocal,   // noLocal
		c.cc.NoWait,    // noWait
		c.cc.Args,      // arguments
	)
	if err != nil {
		return err
	}

	// should we stop streaming, in order not to consume from server?
	c.deliveries = deliveries
	c.handlerRPC = handler

	log.Info("handle: deliveries channel starting")

	// handle all consumer errors, if required re-connect
	// there are problems with reconnection logic for now
	for delivery := range c.deliveries {
		body, contentType := handler(delivery)
    replyTo := delivery.ReplyTo
    if replyTo != "" {
      err := c.ch.Publish(
    		"",
    		replyTo,
    		false,
    		false,
    		amqp.Publishing{
    			ContentType:   contentType,
    			CorrelationId: delivery.CorrelationId,
    			Body:          body,
    		},
    	)
      if err != nil {
        // TODO: What if err != nil?
      }
    }
	}

	log.Info("handle: deliveries channel closed")
	c.done <- nil
	return nil
}

// QOS controls how many messages the server will try to keep on the network for
// consumers before receiving delivery acks.  The intent of Qos is to make sure
// the network buffers stay full between the server and client.
func (c *Consumer) QOS(messageCount int) error {
	return c.ch.Qos(messageCount, 0, false)
}

// ConsumeMessage accepts a handler function and only consumes one message
// stream from RabbitMq
func (c *Consumer) Get(handler func(delivery amqp.Delivery)) error {
	message, ok, err := c.ch.Get(c.q.Name, c.cc.AutoAck)
	if err != nil {
		return err
	}
	c.handler = handler
	if ok {
		fmt.Println("Message received")
		handler(message)
	} else {
		fmt.Println("No message received")
	}
	// TODO maybe we should return ok too?
	return nil
}

func (c *Consumer) Shutdown() error {
	co := c.cc
	if err := shutdownChannel(c.ch, co.Tag); err != nil {
		return err
	}
	fmt.Println("Waiting for Consumer handler to exit")
	// if we have not called the Consume yet, we can return here
	if c.deliveries == nil {
		close(c.done)
	}
  fmt.Printf("deliveries %s", c.deliveries)
  c.closed = true
  fmt.Println("Consumer shutdown OK")
	// this channel is here for finishing the consumer's ranges of
	// delivery chans.  We need every delivery to be processed, here make
	// sure to wait for all consumers goroutines to finish before exiting our
	// process.
	return nil
}
<commit_msg>Modified timeout error message. It displays the chosen time limit.<commit_after>package rabbitgo

import (
  //"errors"
  "time"
  "fmt"
  "github.com/streadway/amqp"
  log "github.com/koding/logging"
)

type Consumer struct {
	conn        *Connection
	ch          *amqp.Channel
  e           *Exchange
  q           *Queue
	deliveries  <-chan amqp.Delivery
  handler     func(amqp.Delivery)
	handlerRPC  func(amqp.Delivery)([]byte, string)
  cc          *ConsumerConfig
  bc          *BindingConfig
  closed      bool
	// A notifiyng channel for publishings
	// will be used for sync. between close channel and consume handler
	done        chan error
}

type ConsumerConfig struct {
	Tag            string
  PrefetchCount  int
  PrefetchSize   int
  Timeout        int
	AutoAck        bool
	Exclusive      bool
	NoLocal        bool
	NoWait         bool
	Args           amqp.Table
}

type BindingConfig struct {
	RoutingKey string
	NoWait bool
	Args amqp.Table
}

func (c *Consumer) Deliveries() <-chan amqp.Delivery {
	return c.deliveries
}

// NewConsumer is a constructor for consumer creation
// Accepts Exchange, Queue, BindingOptions and ConsumerOptions
func (c *Connection) NewConsumer(e *Exchange, q *Queue, bc *BindingConfig, cc *ConsumerConfig) (*Consumer, error) {
  ch, err := c.conn.Channel()
  if err != nil {
    return nil, err
  }
	consumer := &Consumer {
    conn: c,
    ch:   ch,
		done: make(chan error),
    cc:   cc,
    bc:   bc,
		e:    e,
    q:    q,
	}
	if err := consumer.connect(); err != nil {
		return nil, err
	}
	return consumer, nil
}

// connect internally declares the exchanges and queues
func (c *Consumer) connect() error {
	_, err := c.ch.QueueDeclare(
		c.q.Name,       // name of the queue
		c.q.Durable,    // durable
		c.q.AutoDelete, // delete when usused
		c.q.Exclusive,  // exclusive
		c.q.NoWait,     // noWait
		c.q.Args,       // arguments
	)
	if err != nil {
		return err
	}
  err = c.ch.Qos(
    c.cc.PrefetchCount,     // prefetch count
    c.cc.PrefetchSize,     // prefetch size
    false,               // global
  )
  if err != nil {
    return err
  }
  if c.e != nil {
    err := c.ch.ExchangeDeclare(
      c.e.Name,       // name of the exchange
      c.e.Type,       // type
      c.e.Durable,    // durable
      c.e.AutoDelete, // delete when complete
      c.e.Internal,   // internal
      c.e.NoWait,     // noWait
      c.e.Args,       // arguments
    )
    if err != nil {
      return err
    }
    err = c.ch.QueueBind(
  		// bind to real queue
  		c.q.Name,        // name of the queue
  		c.bc.RoutingKey, // bindingKey
  		c.e.Name,        // sourceExchange
  		c.bc.NoWait,     // noWait
  		c.bc.Args,       // arguments
  	)
    if err != nil {
  		return err
  	}
  }
	return nil
}

func (c *Consumer) consume() error {
  deliveries, err := c.ch.Consume(
    c.q.Name,       // name
    c.cc.Tag,       // consumerTag,
    c.cc.AutoAck,   // autoAck
    c.cc.Exclusive, // exclusive
    c.cc.NoLocal,   // noLocal
    c.cc.NoWait,    // noWait
    c.cc.Args,      // arguments
  )
  // should we stop streaming, in order not to consume from server?
  c.deliveries = deliveries
  return err
}

// Consume accepts a handler function for every message streamed from RabbitMq
// will be called within this handler func
func (c *Consumer) Consume(handler func(delivery amqp.Delivery)) error {
  err := c.consume()
  if err != nil {
    return err
  }
  go func() {
    if timeout := c.cc.Timeout; timeout > 0 {
      time.Sleep(time.Duration(timeout) * time.Millisecond)
      if c.closed == false {
        log.Error(fmt.Sprintf("Timeout in %d ms", timeout))
        c.Shutdown()
      }
    }
  }()
	c.handler = handler
	log.Info("handle: deliveries channel starting")
	// handle all consumer errors, if required re-connect
	// there are problems with reconnection logic for now
  for delivery := range c.deliveries {
		handler(delivery)
	}
	log.Info("handle: deliveries channel closed")
  //This was blocking the flow. Not sure how needed is.
	//c.done <- nil
	return nil
}

// ConsumeRPC accepts a handler function for every message streamed from RabbitMq
// will be called within this handler func.
// It returns the message to send and the content type.
func (c *Consumer) ConsumeRPC(handler func(delivery amqp.Delivery)([]byte, string)) error {
	deliveries, err := c.ch.Consume(
		c.q.Name,       // name
		c.cc.Tag,       // consumerTag,
		c.cc.AutoAck,   // autoAck
		c.cc.Exclusive, // exclusive
		c.cc.NoLocal,   // noLocal
		c.cc.NoWait,    // noWait
		c.cc.Args,      // arguments
	)
	if err != nil {
		return err
	}

	// should we stop streaming, in order not to consume from server?
	c.deliveries = deliveries
	c.handlerRPC = handler

	log.Info("handle: deliveries channel starting")

	// handle all consumer errors, if required re-connect
	// there are problems with reconnection logic for now
	for delivery := range c.deliveries {
    body, contentType := handler(delivery)
    replyTo := delivery.ReplyTo
    if replyTo != "" {
      err := c.ch.Publish(
    		"",
    		replyTo,
    		false,
    		false,
    		amqp.Publishing{
    			ContentType:   contentType,
    			CorrelationId: delivery.CorrelationId,
    			Body:          body,
    		},
    	)
      if err != nil {
        // TODO: What if err != nil?
      }
    }
	}

	log.Info("handle: deliveries channel closed")
	c.done <- nil
	return nil
}

// QOS controls how many messages the server will try to keep on the network for
// consumers before receiving delivery acks.  The intent of Qos is to make sure
// the network buffers stay full between the server and client.
func (c *Consumer) QOS(messageCount int) error {
	return c.ch.Qos(messageCount, 0, false)
}

// ConsumeMessage accepts a handler function and only consumes one message
// stream from RabbitMq
func (c *Consumer) Get(handler func(delivery amqp.Delivery)) error {
	message, ok, err := c.ch.Get(c.q.Name, c.cc.AutoAck)
	if err != nil {
		return err
	}
	c.handler = handler
	if ok {
		fmt.Println("Message received")
		handler(message)
	} else {
		fmt.Println("No message received")
	}
	// TODO maybe we should return ok too?
	return nil
}

func (c *Consumer) Shutdown() error {
	co := c.cc
	if err := shutdownChannel(c.ch, co.Tag); err != nil {
		return err
	}
	fmt.Println("Waiting for Consumer handler to exit")
	// if we have not called the Consume yet, we can return here
	if c.deliveries == nil {
		close(c.done)
	}
  fmt.Printf("deliveries %s", c.deliveries)
  c.closed = true
  fmt.Println("Consumer shutdown OK")
	// this channel is here for finishing the consumer's ranges of
	// delivery chans.  We need every delivery to be processed, here make
	// sure to wait for all consumers goroutines to finish before exiting our
	// process.
	return nil
}
<|endoftext|>


<commit_before>package zenhan

import (
	"strings"
)

type flag uint

const (
	// ASCII converts only ascii
	ASCII flag = 1 << iota
	// DIGIT converts only digit
	DIGIT
	// KANA converts only kana
	KANA
	// ALL converts ascii, digit, and kana
	ALL = ASCII | DIGIT | KANA
)

const (
	dakuten    = "ﾞ"
	handakuten = "ﾟ"
)

var (
	zhASCII map[string]string
	hzASCII map[string]string
	zhDIGIT map[string]string
	hzDIGIT map[string]string
	zhKANA  map[string]string
	hzKANA  map[string]string
)

func join(m1 map[string]string, m2 map[string]string) map[string]string {
	m := make(map[string]string)
	for k, v := range m1 {
		m[k] = v
	}
	for k, v := range m2 {
		m[k] = v
	}
	return m
}

func init() {
	zASCII := []string{"ａ", "ｂ", "ｃ", "ｄ", "ｅ", "ｆ", "ｇ", "ｈ", "ｉ",
		"ｊ", "ｋ", "ｌ", "ｍ", "ｎ", "ｏ", "ｐ", "ｑ", "ｒ",
		"ｓ", "ｔ", "ｕ", "ｖ", "ｗ", "ｘ", "ｙ", "ｚ",
		"Ａ", "Ｂ", "Ｃ", "Ｄ", "Ｅ", "Ｆ", "Ｇ", "Ｈ", "Ｉ",
		"Ｊ", "Ｋ", "Ｌ", "Ｍ", "Ｎ", "Ｏ", "Ｐ", "Ｑ", "Ｒ",
		"Ｓ", "Ｔ", "Ｕ", "Ｖ", "Ｗ", "Ｘ", "Ｙ", "Ｚ",
		"！", "”", "＃", "＄", "％", "＆", "’", "（", "）",
		"＊", "＋", "，", "−", "．", "／", "：", "；", "＜",
		"＝", "＞", "？", "＠", "［", "￥", "］", "＾", "＿",
		"‘", "｛", "｜", "｝", "〜", "　"}
	zDigit := []string{"０", "１", "２", "３", "４",
		"５", "６", "７", "８", "９"}
	zKana := []string{"ア", "イ", "ウ", "エ", "オ",
		"カ", "キ", "ク", "ケ", "コ",
		"サ", "シ", "ス", "セ", "ソ",
		"タ", "チ", "ツ", "テ", "ト",
		"ナ", "ニ", "ヌ", "ネ", "ノ",
		"ハ", "ヒ", "フ", "ヘ", "ホ",
		"マ", "ミ", "ム", "メ", "モ",
		"ヤ", "ユ", "ヨ",
		"ラ", "リ", "ル", "レ", "ロ",
		"ワ", "ヲ", "ン",
		"ァ", "ィ", "ゥ", "ェ", "ォ",
		"ッ", "ャ", "ュ", "ョ", "ヴ",
		"ガ", "ギ", "グ", "ゲ", "ゴ",
		"ザ", "ジ", "ズ", "ゼ", "ゾ",
		"ダ", "ヂ", "ヅ", "デ", "ド",
		"バ", "ビ", "ブ", "ベ", "ボ",
		"パ", "ピ", "プ", "ペ", "ポ",
		"。", "、", "・", "゛", "゜", "「", "」", "ー"}
	hASCII := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i",
		"j", "k", "l", "m", "n", "o", "p", "q", "r",
		"s", "t", "u", "v", "w", "x", "y", "z",
		"A", "B", "C", "D", "E", "F", "G", "H", "I",
		"J", "K", "L", "M", "N", "O", "P", "Q", "R",
		"S", "T", "U", "V", "W", "X", "Y", "Z",
		"!", `"`, "#", "$", "%", "&", "'", "(", ")",
		"*", "+", ",", "-", ".", "/", ":", ";", "<",
		"=", ">", "?", "@", "[", "\\", "]", "^", "_",
		"`", "{", "|", "}", "~", " "}
	hDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
	hKana := []string{"ｱ", "ｲ", "ｳ", "ｴ", "ｵ",
		"ｶ", "ｷ", "ｸ", "ｹ", "ｺ",
		"ｻ", "ｼ", "ｽ", "ｾ", "ｿ",
		"ﾀ", "ﾁ", "ﾂ", "ﾃ", "ﾄ",
		"ﾅ", "ﾆ", "ﾇ", "ﾈ", "ﾉ",
		"ﾊ", "ﾋ", "ﾌ", "ﾍ", "ﾎ",
		"ﾏ", "ﾐ", "ﾑ", "ﾒ", "ﾓ",
		"ﾔ", "ﾕ", "ﾖ",
		"ﾗ", "ﾘ", "ﾙ", "ﾚ", "ﾛ",
		"ﾜ", "ｦ", "ﾝ",
		"ｧ", "ｨ", "ｩ", "ｪ", "ｫ",
		"ｯ", "ｬ", "ｭ", "ｮ", "ｳﾞ",
		"ｶﾞ", "ｷﾞ", "ｸﾞ", "ｹﾞ", "ｺﾞ",
		"ｻﾞ", "ｼﾞ", "ｽﾞ", "ｾﾞ", "ｿﾞ",
		"ﾀﾞ", "ﾁﾞ", "ﾂﾞ", "ﾃﾞ", "ﾄﾞ",
		"ﾊﾞ", "ﾋﾞ", "ﾌﾞ", "ﾍﾞ", "ﾎﾞ",
		"ﾊﾟ", "ﾋﾟ", "ﾌﾟ", "ﾍﾟ", "ﾎﾟ",
		"｡", "､", "･", "ﾞ", "ﾟ", "｢", "｣", "ｰ"}

	zhASCII = make(map[string]string)
	for i, s := range zASCII {
		zhASCII[s] = hASCII[i]
	}
	hzASCII = make(map[string]string)
	for i, s := range hASCII {
		hzASCII[s] = zASCII[i]
	}

	zhDIGIT = make(map[string]string)
	for i, s := range zDigit {
		zhDIGIT[s] = hDigit[i]
	}
	hzDIGIT = make(map[string]string)
	for i, s := range hDigit {
		hzDIGIT[s] = zDigit[i]
	}

	zhKANA = make(map[string]string)
	for i, s := range zKana {
		zhKANA[s] = hKana[i]
	}
	hzKANA = make(map[string]string)
	for i, s := range hKana {
		hzKANA[s] = zKana[i]
	}
}

func makeHan2zenDict(mode flag) map[string]string {
	m := make(map[string]string)
	if mode&ASCII == ASCII {
		m = join(m, hzASCII)
	}
	if mode&DIGIT == DIGIT {
		m = join(m, hzDIGIT)
	}
	if mode&KANA == KANA {
		m = join(m, hzKANA)
	}
	return m
}

func makeZen2hanDict(mode flag) map[string]string {
	m := make(map[string]string)
	if mode&ASCII == ASCII {
		m = join(m, zhASCII)
	}
	if mode&DIGIT == DIGIT {
		m = join(m, zhDIGIT)
	}
	if mode&KANA == KANA {
		m = join(m, zhKANA)
	}
	return m
}

func getValueFromMap(m map[string]string, key string, defaultValue string) string {
	if v, ok := m[key]; ok {
		return v
	} else {
		return defaultValue
	}
}

// H2z converts string from hankaku to zenkaku
func H2z(text string, mode flag) string {
	m := makeHan2zenDict(mode)
	t := []rune(text)
	converted := make([]string, 0, len(t))
	for i, v := range t {
		curr := string(v)
		if curr == dakuten || curr == handakuten && i > 0 {
			pref := string(t[i-1])
			if z, ok := m[pref+curr]; ok {
				converted = converted[:len(converted)-1]
				converted = append(converted, z)
			} else {
				converted = append(converted, getValueFromMap(m, curr, curr))
			}
		} else {
			converted = append(converted, getValueFromMap(m, curr, curr))
		}
	}
	return strings.Join(converted, "")
}

// Z2h converts string from zenkaku to hankaku
func Z2h(text string, mode flag) string {
	m := makeZen2hanDict(mode)
	t := []rune(text)
	converted := make([]string, 0, len(t))
	for _, v := range t {
		curr := string(v)
		converted = append(converted, getValueFromMap(m, curr, curr))
	}
	return strings.Join(converted, "")
}
<commit_msg>Fix typo<commit_after>package zenhan

import (
	"strings"
)

type flag uint

const (
	// ASCII converts only ascii
	ASCII flag = 1 << iota
	// DIGIT converts only digit
	DIGIT
	// KANA converts only kana
	KANA
	// ALL converts ascii, digit, and kana
	ALL = ASCII | DIGIT | KANA
)

const (
	dakuten    = "ﾞ"
	handakuten = "ﾟ"
)

var (
	zhASCII map[string]string
	hzASCII map[string]string
	zhDIGIT map[string]string
	hzDIGIT map[string]string
	zhKANA  map[string]string
	hzKANA  map[string]string
)

func join(m1 map[string]string, m2 map[string]string) map[string]string {
	m := make(map[string]string)
	for k, v := range m1 {
		m[k] = v
	}
	for k, v := range m2 {
		m[k] = v
	}
	return m
}

func init() {
	zASCII := []string{"ａ", "ｂ", "ｃ", "ｄ", "ｅ", "ｆ", "ｇ", "ｈ", "ｉ",
		"ｊ", "ｋ", "ｌ", "ｍ", "ｎ", "ｏ", "ｐ", "ｑ", "ｒ",
		"ｓ", "ｔ", "ｕ", "ｖ", "ｗ", "ｘ", "ｙ", "ｚ",
		"Ａ", "Ｂ", "Ｃ", "Ｄ", "Ｅ", "Ｆ", "Ｇ", "Ｈ", "Ｉ",
		"Ｊ", "Ｋ", "Ｌ", "Ｍ", "Ｎ", "Ｏ", "Ｐ", "Ｑ", "Ｒ",
		"Ｓ", "Ｔ", "Ｕ", "Ｖ", "Ｗ", "Ｘ", "Ｙ", "Ｚ",
		"！", "”", "＃", "＄", "％", "＆", "’", "（", "）",
		"＊", "＋", "，", "−", "．", "／", "：", "；", "＜",
		"＝", "＞", "？", "＠", "［", "￥", "］", "＾", "＿",
		"‘", "｛", "｜", "｝", "〜", "　"}
	zDigit := []string{"０", "１", "２", "３", "４",
		"５", "６", "７", "８", "９"}
	zKana := []string{"ア", "イ", "ウ", "エ", "オ",
		"カ", "キ", "ク", "ケ", "コ",
		"サ", "シ", "ス", "セ", "ソ",
		"タ", "チ", "ツ", "テ", "ト",
		"ナ", "ニ", "ヌ", "ネ", "ノ",
		"ハ", "ヒ", "フ", "ヘ", "ホ",
		"マ", "ミ", "ム", "メ", "モ",
		"ヤ", "ユ", "ヨ",
		"ラ", "リ", "ル", "レ", "ロ",
		"ワ", "ヲ", "ン",
		"ァ", "ィ", "ゥ", "ェ", "ォ",
		"ッ", "ャ", "ュ", "ョ", "ヴ",
		"ガ", "ギ", "グ", "ゲ", "ゴ",
		"ザ", "ジ", "ズ", "ゼ", "ゾ",
		"ダ", "ヂ", "ヅ", "デ", "ド",
		"バ", "ビ", "ブ", "ベ", "ボ",
		"パ", "ピ", "プ", "ペ", "ポ",
		"。", "、", "・", "゛", "゜", "「", "」", "ー"}
	hASCII := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i",
		"j", "k", "l", "m", "n", "o", "p", "q", "r",
		"s", "t", "u", "v", "w", "x", "y", "z",
		"A", "B", "C", "D", "E", "F", "G", "H", "I",
		"J", "K", "L", "M", "N", "O", "P", "Q", "R",
		"S", "T", "U", "V", "W", "X", "Y", "Z",
		"!", `"`, "#", "$", "%", "&", "'", "(", ")",
		"*", "+", ",", "-", ".", "/", ":", ";", "<",
		"=", ">", "?", "@", "[", "\\", "]", "^", "_",
		"`", "{", "|", "}", "~", " "}
	hDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
	hKana := []string{"ｱ", "ｲ", "ｳ", "ｴ", "ｵ",
		"ｶ", "ｷ", "ｸ", "ｹ", "ｺ",
		"ｻ", "ｼ", "ｽ", "ｾ", "ｿ",
		"ﾀ", "ﾁ", "ﾂ", "ﾃ", "ﾄ",
		"ﾅ", "ﾆ", "ﾇ", "ﾈ", "ﾉ",
		"ﾊ", "ﾋ", "ﾌ", "ﾍ", "ﾎ",
		"ﾏ", "ﾐ", "ﾑ", "ﾒ", "ﾓ",
		"ﾔ", "ﾕ", "ﾖ",
		"ﾗ", "ﾘ", "ﾙ", "ﾚ", "ﾛ",
		"ﾜ", "ｦ", "ﾝ",
		"ｧ", "ｨ", "ｩ", "ｪ", "ｫ",
		"ｯ", "ｬ", "ｭ", "ｮ", "ｳﾞ",
		"ｶﾞ", "ｷﾞ", "ｸﾞ", "ｹﾞ", "ｺﾞ",
		"ｻﾞ", "ｼﾞ", "ｽﾞ", "ｾﾞ", "ｿﾞ",
		"ﾀﾞ", "ﾁﾞ", "ﾂﾞ", "ﾃﾞ", "ﾄﾞ",
		"ﾊﾞ", "ﾋﾞ", "ﾌﾞ", "ﾍﾞ", "ﾎﾞ",
		"ﾊﾟ", "ﾋﾟ", "ﾌﾟ", "ﾍﾟ", "ﾎﾟ",
		"｡", "､", "･", "ﾞ", "ﾟ", "｢", "｣", "ｰ"}

	zhASCII = make(map[string]string)
	for i, s := range zASCII {
		zhASCII[s] = hASCII[i]
	}
	hzASCII = make(map[string]string)
	for i, s := range hASCII {
		hzASCII[s] = zASCII[i]
	}

	zhDIGIT = make(map[string]string)
	for i, s := range zDigit {
		zhDIGIT[s] = hDigit[i]
	}
	hzDIGIT = make(map[string]string)
	for i, s := range hDigit {
		hzDIGIT[s] = zDigit[i]
	}

	zhKANA = make(map[string]string)
	for i, s := range zKana {
		zhKANA[s] = hKana[i]
	}
	hzKANA = make(map[string]string)
	for i, s := range hKana {
		hzKANA[s] = zKana[i]
	}
}

func makeHan2zenDict(mode flag) map[string]string {
	m := make(map[string]string)
	if mode&ASCII == ASCII {
		m = join(m, hzASCII)
	}
	if mode&DIGIT == DIGIT {
		m = join(m, hzDIGIT)
	}
	if mode&KANA == KANA {
		m = join(m, hzKANA)
	}
	return m
}

func makeZen2hanDict(mode flag) map[string]string {
	m := make(map[string]string)
	if mode&ASCII == ASCII {
		m = join(m, zhASCII)
	}
	if mode&DIGIT == DIGIT {
		m = join(m, zhDIGIT)
	}
	if mode&KANA == KANA {
		m = join(m, zhKANA)
	}
	return m
}

func getValueFromMap(m map[string]string, key string, defaultValue string) string {
	if v, ok := m[key]; ok {
		return v
	} else {
		return defaultValue
	}
}

// H2z converts string from hankaku to zenkaku
func H2z(text string, mode flag) string {
	m := makeHan2zenDict(mode)
	t := []rune(text)
	converted := make([]string, 0, len(t))
	for i, v := range t {
		curr := string(v)
		if curr == dakuten || curr == handakuten && i > 0 {
			prev := string(t[i-1])
			if z, ok := m[prev+curr]; ok {
				converted = converted[:len(converted)-1]
				converted = append(converted, z)
			} else {
				converted = append(converted, getValueFromMap(m, curr, curr))
			}
		} else {
			converted = append(converted, getValueFromMap(m, curr, curr))
		}
	}
	return strings.Join(converted, "")
}

// Z2h converts string from zenkaku to hankaku
func Z2h(text string, mode flag) string {
	m := makeZen2hanDict(mode)
	t := []rune(text)
	converted := make([]string, 0, len(t))
	for _, v := range t {
		curr := string(v)
		converted = append(converted, getValueFromMap(m, curr, curr))
	}
	return strings.Join(converted, "")
}
<|endoftext|>


<commit_before>// Copyright 2009 Thomas Jager <mail@jager.no>  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package irc

import (
	"bufio"
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"time"
)

const (
	VERSION = "go-ircevent v2.0"
)

func (irc *Connection) readLoop() {
	br := bufio.NewReader(irc.socket)

	for {
		msg, err := br.ReadString('\n')
		if err != nil {
			irc.Error <- err
			break
		}

		irc.lastMessage = time.Now()
		msg = msg[0 : len(msg)-2] //Remove \r\n
		event := &Event{Raw: msg}
		if msg[0] == ':' {
			if i := strings.Index(msg, " "); i > -1 {
				event.Source = msg[1:i]
				msg = msg[i+1 : len(msg)]

			} else {
				irc.log.Printf("Misformed msg from server: %#s\n", msg)
			}

			if i, j := strings.Index(event.Source, "!"), strings.Index(event.Source, "@"); i > -1 && j > -1 {
				event.Nick = event.Source[0:i]
				event.User = event.Source[i+1 : j]
				event.Host = event.Source[j+1 : len(event.Source)]
			}
		}

		args := strings.SplitN(msg, " :", 2)
		if len(args) > 1 {
			event.Message = args[1]
		}

		args = strings.Split(args[0], " ")
		event.Code = strings.ToUpper(args[0])

		if len(args) > 1 {
			event.Arguments = args[1:len(args)]
		}
		/* XXX: len(args) == 0: args should be empty */

		irc.RunCallbacks(event)
	}

	irc.syncreader <- true
}

func (irc *Connection) writeLoop() {
	b, ok := <-irc.pwrite
	for ok {
		if b == "" || irc.socket == nil {
			break
		}
		irc.log.Printf("--> %s\n", b)
		_, err := irc.socket.Write([]byte(b))
		if err != nil {
			irc.log.Printf("%s\n", err)
			irc.Error <- err
			break
		}

		b, ok = <-irc.pwrite
	}
	irc.syncwriter <- true
}

//Pings the server if we have not recived any messages for 5 minutes
func (irc *Connection) pingLoop() {
	irc.ticker = time.NewTicker(1 * time.Minute)   //Tick every minute.
	irc.ticker2 = time.NewTicker(15 * time.Minute) //Tick every 15 minutes.
	for {
		select {
		case <-irc.ticker.C:
			//Ping if we haven't recived anything from the server within 4 minutes
			if time.Since(irc.lastMessage) >= (4 * time.Minute) {
				irc.SendRawf("PING %d", time.Now().UnixNano())
			}
		case <-irc.ticker2.C:
			//Ping every 15 minutes.
			irc.SendRawf("PING %d", time.Now().UnixNano())
			//Try to recapture nickname if it's not as configured.
			if irc.nick != irc.nickcurrent {
				irc.nickcurrent = irc.nick
				irc.SendRawf("NICK %s", irc.nick)
			}
		case <-irc.endping:
			irc.ticker.Stop()
			irc.ticker2.Stop()
			break
		}
	}
	irc.syncpinger <- true
}

func (irc *Connection) Cycle() {
	irc.SendRaw("QUIT")
	irc.Reconnect()
}

func (irc *Connection) Quit() {
	irc.quitting = true
	irc.SendRaw("QUIT")
}

func (irc *Connection) Join(channel string) {
	irc.pwrite <- fmt.Sprintf("JOIN %s\r\n", channel)
}

func (irc *Connection) Part(channel string) {
	irc.pwrite <- fmt.Sprintf("PART %s\r\n", channel)
}

func (irc *Connection) Notice(target, message string) {
	irc.pwrite <- fmt.Sprintf("NOTICE %s :%s\r\n", target, message)
}

func (irc *Connection) Noticef(target, format string, a ...interface{}) {
	irc.Notice(target, fmt.Sprintf(format, a...))
}

func (irc *Connection) Privmsg(target, message string) {
	irc.pwrite <- fmt.Sprintf("PRIVMSG %s :%s\r\n", target, message)
}

func (irc *Connection) Privmsgf(target, format string, a ...interface{}) {
	irc.Privmsg(target, fmt.Sprintf(format, a...))
}

func (irc *Connection) SendRaw(message string) {
	irc.pwrite <- fmt.Sprintf("%s\r\n", message)
}

func (irc *Connection) SendRawf(format string, a ...interface{}) {
	irc.SendRaw(fmt.Sprintf(format, a...))
}

func (irc *Connection) GetNick() string {
	return irc.nickcurrent
}

func (irc *Connection) Reconnect() error {
	close(irc.pwrite)
	close(irc.pread)
	irc.endping <- true
	irc.log.Printf("Syncing Threads\n")
	irc.log.Printf("Syncing Reader\n")
	<-irc.syncreader
	irc.log.Printf("Syncing Writer\n")
	<-irc.syncwriter
	irc.log.Printf("Syncing Pinger\n")
	<-irc.syncpinger
	irc.log.Printf("Syncing Threads Done\n")
	for {
		irc.log.Printf("Reconnecting to %s\n", irc.server)
		var err error
		irc.Connect(irc.server)
		if err == nil {
			break
		}
		irc.log.Printf("Error: %s\n", err)
	}
	return nil
}

func (irc *Connection) Loop() {
	for !irc.quitting {
		e := <-irc.Error
		if irc.quitting {
			break
		}
		irc.log.Printf("Error: %s\n", e)
		irc.Reconnect()
	}

	close(irc.pwrite)
	close(irc.pread)
	irc.endping <- true
	<-irc.syncreader
	<-irc.syncwriter
	<-irc.syncpinger
}

func (irc *Connection) Connect(server string) error {
	irc.server = server
	var err error
	irc.log.Printf("Connecting to %s\n", irc.server)
	if irc.UseTLS {
		irc.socket, err = tls.Dial("tcp", irc.server, irc.TLSConfig)
	} else {
		irc.socket, err = net.Dial("tcp", irc.server)
	}
	if err != nil {
		return err
	}
	irc.log.Printf("Connected to %s (%s)\n", irc.server, irc.socket.RemoteAddr())
	return irc.postConnect()
}

func (irc *Connection) postConnect() error {
	irc.pread = make(chan string, 100)
	irc.pwrite = make(chan string, 100)
	irc.Error = make(chan error, 10)
	irc.syncreader = make(chan bool)
	irc.syncwriter = make(chan bool)
	irc.syncpinger = make(chan bool)
	irc.endping = make(chan bool)
	go irc.readLoop()
	go irc.writeLoop()
	go irc.pingLoop()

	if len(irc.Password) > 0 {
		irc.pwrite <- fmt.Sprintf("PASS %s\r\n", irc.Password)
	}
	irc.pwrite <- fmt.Sprintf("NICK %s\r\n", irc.nick)
	irc.pwrite <- fmt.Sprintf("USER %s 0.0.0.0 0.0.0.0 :%s\r\n", irc.user, irc.user)
	return nil
}

func IRC(nick, user string) *Connection {
	irc := new(Connection)
	irc.registered = false
	irc.pread = make(chan string, 100)
	irc.pwrite = make(chan string, 100)
	irc.Error = make(chan error)
	irc.nick = nick
	irc.user = user
	irc.VerboseCallbackHandler = false
	irc.log = log.New(os.Stdout, "", log.LstdFlags)
	irc.setupCallbacks()
	return irc
}
<commit_msg>Fix pinger<commit_after>// Copyright 2009 Thomas Jager <mail@jager.no>  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package irc

import (
	"bufio"
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"time"
)

const (
	VERSION = "go-ircevent v2.0"
)

func (irc *Connection) readLoop() {
	br := bufio.NewReader(irc.socket)

	for {
		msg, err := br.ReadString('\n')
		if err != nil {
			irc.Error <- err
			break
		}

		irc.lastMessage = time.Now()
		msg = msg[0 : len(msg)-2] //Remove \r\n
		event := &Event{Raw: msg}
		if msg[0] == ':' {
			if i := strings.Index(msg, " "); i > -1 {
				event.Source = msg[1:i]
				msg = msg[i+1 : len(msg)]

			} else {
				irc.log.Printf("Misformed msg from server: %#s\n", msg)
			}

			if i, j := strings.Index(event.Source, "!"), strings.Index(event.Source, "@"); i > -1 && j > -1 {
				event.Nick = event.Source[0:i]
				event.User = event.Source[i+1 : j]
				event.Host = event.Source[j+1 : len(event.Source)]
			}
		}

		args := strings.SplitN(msg, " :", 2)
		if len(args) > 1 {
			event.Message = args[1]
		}

		args = strings.Split(args[0], " ")
		event.Code = strings.ToUpper(args[0])

		if len(args) > 1 {
			event.Arguments = args[1:len(args)]
		}
		/* XXX: len(args) == 0: args should be empty */

		irc.RunCallbacks(event)
	}

	irc.syncreader <- true
}

func (irc *Connection) writeLoop() {
	b, ok := <-irc.pwrite
	for ok {
		if b == "" || irc.socket == nil {
			break
		}
		irc.log.Printf("--> %s\n", b)
		_, err := irc.socket.Write([]byte(b))
		if err != nil {
			irc.log.Printf("%s\n", err)
			irc.Error <- err
			break
		}

		b, ok = <-irc.pwrite
	}
	irc.syncwriter <- true
}

//Pings the server if we have not recived any messages for 5 minutes
func (irc *Connection) pingLoop() {
	irc.ticker = time.NewTicker(1 * time.Minute)   //Tick every minute.
	irc.ticker2 = time.NewTicker(15 * time.Minute) //Tick every 15 minutes.
	for {
		select {
		case <-irc.ticker.C:
			//Ping if we haven't recived anything from the server within 4 minutes
			if time.Since(irc.lastMessage) >= (4 * time.Minute) {
				irc.SendRawf("PING %d", time.Now().UnixNano())
			}
		case <-irc.ticker2.C:
			//Ping every 15 minutes.
			irc.SendRawf("PING %d", time.Now().UnixNano())
			//Try to recapture nickname if it's not as configured.
			if irc.nick != irc.nickcurrent {
				irc.nickcurrent = irc.nick
				irc.SendRawf("NICK %s", irc.nick)
			}
		case <-irc.endping:
			irc.ticker.Stop()
			irc.ticker2.Stop()
			irc.syncpinger <- true
			return
		}
	}
}

func (irc *Connection) Cycle() {
	irc.SendRaw("QUIT")
	irc.Reconnect()
}

func (irc *Connection) Quit() {
	irc.quitting = true
	irc.SendRaw("QUIT")
}

func (irc *Connection) Join(channel string) {
	irc.pwrite <- fmt.Sprintf("JOIN %s\r\n", channel)
}

func (irc *Connection) Part(channel string) {
	irc.pwrite <- fmt.Sprintf("PART %s\r\n", channel)
}

func (irc *Connection) Notice(target, message string) {
	irc.pwrite <- fmt.Sprintf("NOTICE %s :%s\r\n", target, message)
}

func (irc *Connection) Noticef(target, format string, a ...interface{}) {
	irc.Notice(target, fmt.Sprintf(format, a...))
}

func (irc *Connection) Privmsg(target, message string) {
	irc.pwrite <- fmt.Sprintf("PRIVMSG %s :%s\r\n", target, message)
}

func (irc *Connection) Privmsgf(target, format string, a ...interface{}) {
	irc.Privmsg(target, fmt.Sprintf(format, a...))
}

func (irc *Connection) SendRaw(message string) {
	irc.pwrite <- fmt.Sprintf("%s\r\n", message)
}

func (irc *Connection) SendRawf(format string, a ...interface{}) {
	irc.SendRaw(fmt.Sprintf(format, a...))
}

func (irc *Connection) GetNick() string {
	return irc.nickcurrent
}

func (irc *Connection) Reconnect() error {
	close(irc.pwrite)
	close(irc.pread)
	irc.endping <- true
	irc.log.Printf("Syncing Threads\n")
	irc.log.Printf("Syncing Reader\n")
	<-irc.syncreader
	irc.log.Printf("Syncing Writer\n")
	<-irc.syncwriter
	irc.log.Printf("Syncing Pinger\n")
	<-irc.syncpinger
	irc.log.Printf("Syncing Threads Done\n")
	for {
		irc.log.Printf("Reconnecting to %s\n", irc.server)
		var err error
		irc.Connect(irc.server)
		if err == nil {
			break
		}
		irc.log.Printf("Error: %s\n", err)
	}
	return nil
}

func (irc *Connection) Loop() {
	for !irc.quitting {
		e := <-irc.Error
		if irc.quitting {
			break
		}
		irc.log.Printf("Error: %s\n", e)
		irc.Reconnect()
	}

	close(irc.pwrite)
	close(irc.pread)
	irc.endping <- true
	irc.log.Printf("Syncing Threads\n")
	irc.log.Printf("Syncing Reader\n")
	<-irc.syncreader
	irc.log.Printf("Syncing Writer\n")
	<-irc.syncwriter
	irc.log.Printf("Syncing Pinger\n")
	<-irc.syncpinger
	irc.log.Printf("Syncing Threads Done\n")
}

func (irc *Connection) Connect(server string) error {
	irc.server = server
	var err error
	irc.log.Printf("Connecting to %s\n", irc.server)
	if irc.UseTLS {
		irc.socket, err = tls.Dial("tcp", irc.server, irc.TLSConfig)
	} else {
		irc.socket, err = net.Dial("tcp", irc.server)
	}
	if err != nil {
		return err
	}
	irc.log.Printf("Connected to %s (%s)\n", irc.server, irc.socket.RemoteAddr())
	return irc.postConnect()
}

func (irc *Connection) postConnect() error {
	irc.pread = make(chan string, 100)
	irc.pwrite = make(chan string, 100)
	irc.Error = make(chan error, 10)
	irc.syncreader = make(chan bool)
	irc.syncwriter = make(chan bool)
	irc.syncpinger = make(chan bool)
	irc.endping = make(chan bool)
	go irc.readLoop()
	go irc.writeLoop()
	go irc.pingLoop()

	if len(irc.Password) > 0 {
		irc.pwrite <- fmt.Sprintf("PASS %s\r\n", irc.Password)
	}
	irc.pwrite <- fmt.Sprintf("NICK %s\r\n", irc.nick)
	irc.pwrite <- fmt.Sprintf("USER %s 0.0.0.0 0.0.0.0 :%s\r\n", irc.user, irc.user)
	return nil
}

func IRC(nick, user string) *Connection {
	irc := new(Connection)
	irc.registered = false
	irc.pread = make(chan string, 100)
	irc.pwrite = make(chan string, 100)
	irc.Error = make(chan error)
	irc.nick = nick
	irc.user = user
	irc.VerboseCallbackHandler = false
	irc.log = log.New(os.Stdout, "", log.LstdFlags)
	irc.setupCallbacks()
	return irc
}
<|endoftext|>