<commit_before>package database

import (
	"errors"
	"fmt"
	"net/url"
	"sync"

	"github.com/coreos/go-iptables/iptables"
	"github.com/nanobox-io/golang-lvs"

	"github.com/nanopack/portal/config"
)

type (
	Backender interface {
		GetServices() ([]lvs.Service, error)
		GetService(lvs.Service) (lvs.Service, error)
		SetServices([]lvs.Service) error
		SetService(lvs.Service) error
		DeleteService(lvs.Service) error
		Init() error
	}
)

var (
	Backend        Backender
	ipvsLock       *sync.RWMutex
	NoServiceError = errors.New("No Service Found")
	NoServerError  = errors.New("No Server Found")
	tab            *iptables.IPTables
)

func Init() error {
	ipvsLock = &sync.RWMutex{}
	var err error
	var u *url.URL
	u, err = url.Parse(config.DatabaseConnection)
	if err != nil {
		return err
	}
	switch u.Scheme {
	case "scribble":
		Backend = &ScribbleDatabase{}
	default:
		Backend = nil
	}
	if Backend != nil {
		err = Backend.Init()
		if err != nil {
			Backend = nil
		}
	}
	tab, err = iptables.New()
	if err != nil {
		tab = nil
	}
	if tab != nil {
		tab.Delete("filter", "INPUT", "-j", "portal")
		tab.ClearChain("filter", "portal")
		tab.DeleteChain("filter", "portal")
		err = tab.NewChain("filter", "portal")
		if err != nil {
			return err
		}
		err = tab.AppendUnique("filter", "portal", "-j", "RETURN")
		if err != nil {
			return err
		}
		err = tab.AppendUnique("filter", "INPUT", "-j", "portal")
		if err != nil {
			return err
		}
	}
	return nil
}

// GetServer
func GetServer(service lvs.Service, server lvs.Server) *lvs.Server {
	ipvsLock.RLock()
	defer ipvsLock.RUnlock()
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return nil
	}
	return s.FindServer(server)
}

// SetServer
func SetServer(service lvs.Service, server lvs.Server) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// add to lvs
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return NoServiceError
	}
	err := s.AddServer(server)
	if err != nil {
		return err
	}
	// save to backend
	if Backend != nil {
		err = Backend.SetService(*s)
		if err != nil {
			return err
		}
	}
	return nil
}

// DeleteServer
func DeleteServer(service lvs.Service, server lvs.Server) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// remove from lvs
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return nil
	}
	s.RemoveServer(server)
	// remove from backend
	if Backend != nil {
		err := Backend.SetService(*s)
		if err != nil {
			return err
		}
	}
	return nil
}

// GetServers
// func GetServers(service lvs.Service) []lvs.servers {
// 	return service.Servers
// }

// SetServers
func SetServers(service lvs.Service, servers []lvs.Server) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// add to lvs
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return NoServiceError
	}
	// Add Servers
AddServers:
	for i := range servers {
		for j := range s.Servers {
			if servers[i].Host == s.Servers[j].Host && servers[i].Port == s.Servers[j].Port {
				continue AddServers
			}
		}
		s.AddServer(servers[i])
	}
	// Remove Servers
RemoveServers:
	for i := range s.Servers {
		for j := range servers {
			if s.Servers[i].Host == servers[j].Host && s.Servers[i].Port == servers[j].Port {
				continue RemoveServers
			}
		}
		s.RemoveServer(s.Servers[i])
	}
	return nil
}

// GetService
func GetService(service lvs.Service) *lvs.Service {
	ipvsLock.RLock()
	defer ipvsLock.RUnlock()
	return lvs.DefaultIpvs.FindService(service)
}

// SetService
func SetService(service lvs.Service) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// add to lvs
	err := lvs.DefaultIpvs.AddService(service)
	if err != nil {
		return err
	}
	// save to backend
	if Backend != nil {
		err := Backend.SetService(service)
		if err != nil {
			return err
		}
	}
	if tab != nil {
		err := tab.Insert("filter", "portal", 1, "-p", service.Type, "-d", service.Host, "--dport", fmt.Sprintf("%d", service.Port), "-j", "ACCEPT")
		if err != nil {
			return err
		}
	}
	return nil
}

// DeleteService
func DeleteService(service lvs.Service) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// remove from lvs
	err := lvs.DefaultIpvs.RemoveService(service)
	if err != nil {
		return err
	}
	// remove from backend
	if Backend != nil {
		err := Backend.DeleteService(service)
		if err != nil {
			return err
		}
	}
	if tab != nil {
		err := tab.Delete("filter", "portal", "-p", service.Type, "-d", service.Host, "--dport", fmt.Sprintf("%d", service.Port), "-j", "ACCEPT")
		if err != nil {
			return err
		}
	}
	return nil
}

// GetServices
func GetServices() []lvs.Service {
	ipvsLock.RLock()
	defer ipvsLock.RUnlock()
	return lvs.DefaultIpvs.Services
}

// SetServices
func SetServices(services []lvs.Service) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	if tab != nil {
		tab.RenameChain("filter", "portal", "portal-old")
	}
	lvs.DefaultIpvs.Restore(services)
	if Backend != nil {
		err := Backend.SetServices(services)
		if err != nil {
			if tab != nil {
				tab.RenameChain("filter", "portal-old", "portal")
			}
			return err
		}
	}
	if tab != nil {
		tab.NewChain("filter", "portal")
		tab.ClearChain("filter", "portal")
		tab.AppendUnique("filter", "portal", "-j", "RETURN")
		for i := range services {
			err := tab.Insert("filter", "portal", 1, "-p", services[i].Type, "-d", services[i].Host, "--dport", fmt.Sprintf("%d", services[i].Port), "-j", "ACCEPT")
			if err != nil {
				tab.ClearChain("filter", "portal")
				tab.DeleteChain("filter", "portal")
				tab.RenameChain("filter", "portal-old", "portal")
				return err
			}
		}
		tab.AppendUnique("filter", "INPUT", "-j", "portal")
		tab.Delete("filter", "INPUT", "-j", "portal-old")
		tab.ClearChain("filter", "portal-old")
		tab.DeleteChain("filter", "portal-old")
	}
	return nil
}

// SyncLvs
func SyncToLvs() error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	if tab != nil {
		tab.RenameChain("filter", "portal", "portal-old")
	}
	var err error
	var services []lvs.Service
	if Backend != nil {
		services, err = Backend.GetServices()
		if err != nil {
			if tab != nil {
				tab.RenameChain("filter", "portal-old", "portal")
			}
			return err
		}
	} else {
		services = []lvs.Service{}
	}
	err = lvs.Clear()
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	err = lvs.Restore(services)
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	if tab != nil {
		tab.NewChain("filter", "portal")
		tab.ClearChain("filter", "portal")
		tab.AppendUnique("filter", "portal", "-j", "RETURN")
		for i := range services {
			err := tab.Insert("filter", "portal", 1, "-p", services[i].Type, "-d", services[i].Host, "--dport", fmt.Sprintf("%d", services[i].Port), "-j", "ACCEPT")
			if err != nil {
				tab.ClearChain("filter", "portal")
				tab.DeleteChain("filter", "portal")
				tab.RenameChain("filter", "portal-old", "portal")
				return err
			}
		}
		tab.AppendUnique("filter", "INPUT", "-j", "portal")
		tab.Delete("filter", "INPUT", "-j", "portal-old")
		tab.ClearChain("filter", "portal-old")
		tab.DeleteChain("filter", "portal-old")
	}
	return nil
}

// SyncToPortal
func SyncToPortal() error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	if tab != nil {
		tab.RenameChain("filter", "portal", "portal-old")
	}
	err := lvs.Save()
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	if Backend != nil {
		err := Backend.SetServices(lvs.DefaultIpvs.Services)
		if err != nil {
			if tab != nil {
				tab.RenameChain("filter", "portal-old", "portal")
			}
			return err
		}
	}
	if tab != nil {
		tab.NewChain("filter", "portal")
		tab.ClearChain("filter", "portal")
		tab.AppendUnique("filter", "portal", "-j", "RETURN")
		for i := range lvs.DefaultIpvs.Services {
			err := tab.Insert("filter", "portal", 1, "-p", lvs.DefaultIpvs.Services[i].Type, "-d", lvs.DefaultIpvs.Services[i].Host, "--dport", fmt.Sprintf("%d", lvs.DefaultIpvs.Services[i].Port), "-j", "ACCEPT")
			if err != nil {
				tab.ClearChain("filter", "portal")
				tab.DeleteChain("filter", "portal")
				tab.RenameChain("filter", "portal-old", "portal")
				return err
			}
		}
		tab.AppendUnique("filter", "INPUT", "-j", "portal")
		tab.Delete("filter", "INPUT", "-j", "portal-old")
		tab.ClearChain("filter", "portal-old")
		tab.DeleteChain("filter", "portal-old")
	}
	return nil
}
<commit_msg>Clear the ipvsadm data before running the restore<commit_after>package database

import (
	"errors"
	"fmt"
	"net/url"
	"sync"

	"github.com/coreos/go-iptables/iptables"
	"github.com/nanobox-io/golang-lvs"

	"github.com/nanopack/portal/config"
)

type (
	Backender interface {
		GetServices() ([]lvs.Service, error)
		GetService(lvs.Service) (lvs.Service, error)
		SetServices([]lvs.Service) error
		SetService(lvs.Service) error
		DeleteService(lvs.Service) error
		Init() error
	}
)

var (
	Backend        Backender
	ipvsLock       *sync.RWMutex
	NoServiceError = errors.New("No Service Found")
	NoServerError  = errors.New("No Server Found")
	tab            *iptables.IPTables
)

func Init() error {
	ipvsLock = &sync.RWMutex{}
	var err error
	var u *url.URL
	u, err = url.Parse(config.DatabaseConnection)
	if err != nil {
		return err
	}
	switch u.Scheme {
	case "scribble":
		Backend = &ScribbleDatabase{}
	default:
		Backend = nil
	}
	if Backend != nil {
		err = Backend.Init()
		if err != nil {
			Backend = nil
		}
	}
	tab, err = iptables.New()
	if err != nil {
		tab = nil
	}
	if tab != nil {
		tab.Delete("filter", "INPUT", "-j", "portal")
		tab.ClearChain("filter", "portal")
		tab.DeleteChain("filter", "portal")
		err = tab.NewChain("filter", "portal")
		if err != nil {
			return err
		}
		err = tab.AppendUnique("filter", "portal", "-j", "RETURN")
		if err != nil {
			return err
		}
		err = tab.AppendUnique("filter", "INPUT", "-j", "portal")
		if err != nil {
			return err
		}
	}
	return nil
}

// GetServer
func GetServer(service lvs.Service, server lvs.Server) *lvs.Server {
	ipvsLock.RLock()
	defer ipvsLock.RUnlock()
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return nil
	}
	return s.FindServer(server)
}

// SetServer
func SetServer(service lvs.Service, server lvs.Server) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// add to lvs
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return NoServiceError
	}
	err := s.AddServer(server)
	if err != nil {
		return err
	}
	// save to backend
	if Backend != nil {
		err = Backend.SetService(*s)
		if err != nil {
			return err
		}
	}
	return nil
}

// DeleteServer
func DeleteServer(service lvs.Service, server lvs.Server) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// remove from lvs
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return nil
	}
	s.RemoveServer(server)
	// remove from backend
	if Backend != nil {
		err := Backend.SetService(*s)
		if err != nil {
			return err
		}
	}
	return nil
}

// GetServers
// func GetServers(service lvs.Service) []lvs.servers {
// 	return service.Servers
// }

// SetServers
func SetServers(service lvs.Service, servers []lvs.Server) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// add to lvs
	s := lvs.DefaultIpvs.FindService(service)
	if s == nil {
		return NoServiceError
	}
	// Add Servers
AddServers:
	for i := range servers {
		for j := range s.Servers {
			if servers[i].Host == s.Servers[j].Host && servers[i].Port == s.Servers[j].Port {
				continue AddServers
			}
		}
		s.AddServer(servers[i])
	}
	// Remove Servers
RemoveServers:
	for i := range s.Servers {
		for j := range servers {
			if s.Servers[i].Host == servers[j].Host && s.Servers[i].Port == servers[j].Port {
				continue RemoveServers
			}
		}
		s.RemoveServer(s.Servers[i])
	}
	return nil
}

// GetService
func GetService(service lvs.Service) *lvs.Service {
	ipvsLock.RLock()
	defer ipvsLock.RUnlock()
	return lvs.DefaultIpvs.FindService(service)
}

// SetService
func SetService(service lvs.Service) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// add to lvs
	err := lvs.DefaultIpvs.AddService(service)
	if err != nil {
		return err
	}
	// save to backend
	if Backend != nil {
		err := Backend.SetService(service)
		if err != nil {
			return err
		}
	}
	if tab != nil {
		err := tab.Insert("filter", "portal", 1, "-p", service.Type, "-d", service.Host, "--dport", fmt.Sprintf("%d", service.Port), "-j", "ACCEPT")
		if err != nil {
			return err
		}
	}
	return nil
}

// DeleteService
func DeleteService(service lvs.Service) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	// remove from lvs
	err := lvs.DefaultIpvs.RemoveService(service)
	if err != nil {
		return err
	}
	// remove from backend
	if Backend != nil {
		err := Backend.DeleteService(service)
		if err != nil {
			return err
		}
	}
	if tab != nil {
		err := tab.Delete("filter", "portal", "-p", service.Type, "-d", service.Host, "--dport", fmt.Sprintf("%d", service.Port), "-j", "ACCEPT")
		if err != nil {
			return err
		}
	}
	return nil
}

// GetServices
func GetServices() []lvs.Service {
	ipvsLock.RLock()
	defer ipvsLock.RUnlock()
	return lvs.DefaultIpvs.Services
}

// SetServices
func SetServices(services []lvs.Service) error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	if tab != nil {
		tab.RenameChain("filter", "portal", "portal-old")
	}
	err := lvs.DefaultIpvs.Clear()
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	err = lvs.DefaultIpvs.Restore(services)
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	if Backend != nil {
		err := Backend.SetServices(services)
		if err != nil {
			if tab != nil {
				tab.RenameChain("filter", "portal-old", "portal")
			}
			return err
		}
	}
	if tab != nil {
		tab.NewChain("filter", "portal")
		tab.ClearChain("filter", "portal")
		tab.AppendUnique("filter", "portal", "-j", "RETURN")
		for i := range services {
			err := tab.Insert("filter", "portal", 1, "-p", services[i].Type, "-d", services[i].Host, "--dport", fmt.Sprintf("%d", services[i].Port), "-j", "ACCEPT")
			if err != nil {
				tab.ClearChain("filter", "portal")
				tab.DeleteChain("filter", "portal")
				tab.RenameChain("filter", "portal-old", "portal")
				return err
			}
		}
		tab.AppendUnique("filter", "INPUT", "-j", "portal")
		tab.Delete("filter", "INPUT", "-j", "portal-old")
		tab.ClearChain("filter", "portal-old")
		tab.DeleteChain("filter", "portal-old")
	}
	return nil
}

// SyncLvs
func SyncToLvs() error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	if tab != nil {
		tab.RenameChain("filter", "portal", "portal-old")
	}
	var err error
	var services []lvs.Service
	if Backend != nil {
		services, err = Backend.GetServices()
		if err != nil {
			if tab != nil {
				tab.RenameChain("filter", "portal-old", "portal")
			}
			return err
		}
	} else {
		services = []lvs.Service{}
	}
	err = lvs.Clear()
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	err = lvs.Restore(services)
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	if tab != nil {
		tab.NewChain("filter", "portal")
		tab.ClearChain("filter", "portal")
		tab.AppendUnique("filter", "portal", "-j", "RETURN")
		for i := range services {
			err := tab.Insert("filter", "portal", 1, "-p", services[i].Type, "-d", services[i].Host, "--dport", fmt.Sprintf("%d", services[i].Port), "-j", "ACCEPT")
			if err != nil {
				tab.ClearChain("filter", "portal")
				tab.DeleteChain("filter", "portal")
				tab.RenameChain("filter", "portal-old", "portal")
				return err
			}
		}
		tab.AppendUnique("filter", "INPUT", "-j", "portal")
		tab.Delete("filter", "INPUT", "-j", "portal-old")
		tab.ClearChain("filter", "portal-old")
		tab.DeleteChain("filter", "portal-old")
	}
	return nil
}

// SyncToPortal
func SyncToPortal() error {
	ipvsLock.Lock()
	defer ipvsLock.Unlock()
	if tab != nil {
		tab.RenameChain("filter", "portal", "portal-old")
	}
	err := lvs.Save()
	if err != nil {
		if tab != nil {
			tab.RenameChain("filter", "portal-old", "portal")
		}
		return err
	}
	if Backend != nil {
		err := Backend.SetServices(lvs.DefaultIpvs.Services)
		if err != nil {
			if tab != nil {
				tab.RenameChain("filter", "portal-old", "portal")
			}
			return err
		}
	}
	if tab != nil {
		tab.NewChain("filter", "portal")
		tab.ClearChain("filter", "portal")
		tab.AppendUnique("filter", "portal", "-j", "RETURN")
		for i := range lvs.DefaultIpvs.Services {
			err := tab.Insert("filter", "portal", 1, "-p", lvs.DefaultIpvs.Services[i].Type, "-d", lvs.DefaultIpvs.Services[i].Host, "--dport", fmt.Sprintf("%d", lvs.DefaultIpvs.Services[i].Port), "-j", "ACCEPT")
			if err != nil {
				tab.ClearChain("filter", "portal")
				tab.DeleteChain("filter", "portal")
				tab.RenameChain("filter", "portal-old", "portal")
				return err
			}
		}
		tab.AppendUnique("filter", "INPUT", "-j", "portal")
		tab.Delete("filter", "INPUT", "-j", "portal-old")
		tab.ClearChain("filter", "portal-old")
		tab.DeleteChain("filter", "portal-old")
	}
	return nil
}
<|endoftext|>


<commit_before>package database

import "github.com/kadirahq/kadiyadb/block"

// DB is a database
type DB struct {
	// TODO add fields
}

// Params is used when creating a new database
type Params struct {
	// TODO add fields
}

// Info has db info
type Info struct {
	// TODO add fields
}

// New creates a new database with given params
func New(p Params) (d *DB, err error) {
	return nil, nil
}

// Track records a measurement
func (d *DB) Track(pid int64, fields []string, total float64, count uint64) (err error) {
	return nil
}

// Fetch fetches data from database
func (d *DB) Fetch(from, to int64, fields []string) (res []block.Point, err error) {
	res = block.Empty[:0]
	return res, nil
}

// Sync flushes pending writes to the filesystem
func (d *DB) Sync() (err error) {
	return nil
}

// Info returns database information
func (d *DB) Info() (info *Info, err error) {
	return nil, nil
}
<commit_msg>Use timestamps with database<commit_after>package database

import "github.com/kadirahq/kadiyadb/block"

// DB is a database
type DB struct {
	// TODO add fields
}

// Params is used when creating a new database
type Params struct {
	// TODO add fields
}

// Info has db info
type Info struct {
	// TODO add fields
}

// New creates a new database with given params
func New(p Params) (d *DB, err error) {
	return nil, nil
}

// Track records a measurement
func (d *DB) Track(ts int64, fields []string, total float64, count uint64) (err error) {
	return nil
}

// Fetch fetches data from database
func (d *DB) Fetch(from, to int64, fields []string) (res []block.Point, err error) {
	res = block.Empty[:0]
	return res, nil
}

// Sync flushes pending writes to the filesystem
func (d *DB) Sync() (err error) {
	return nil
}

// Info returns database information
func (d *DB) Info() (info *Info, err error) {
	return nil, nil
}
<|endoftext|>


<commit_before>package database

import (
	"github.com/danjac/podbaby/models"
	"github.com/jmoiron/sqlx"
)

const maxSearchRows = 20

// PodcastDB manages DB queries to podcasts
type PodcastDB interface {
	GetByID(int64) (*models.Podcast, error)
	SelectAll(int64) (*models.PodcastList, error)
	SelectSubscribed(int64, int64) (*models.PodcastList, error)
	SelectByChannelID(int64, int64) (*models.PodcastList, error)
	SelectBookmarked(int64, int64) (*models.PodcastList, error)
	SelectPlayed(int64, int64) (*models.PodcastList, error)
	Search(string) ([]models.Podcast, error)
	SearchBookmarked(string, int64) ([]models.Podcast, error)
	SearchByChannelID(string, int64) ([]models.Podcast, error)
	Create(*models.Podcast) error
}

type defaultPodcastDBImpl struct {
	*sqlx.DB
}

func (db *defaultPodcastDBImpl) GetByID(id int64) (*models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN channels c ON c.id = p.channel_id
    WHERE p.id=$1`

	podcast := &models.Podcast{}
	err := db.Get(podcast, sql, id)
	return podcast, err
}

func (db *defaultPodcastDBImpl) Search(query string) ([]models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p, plainto_tsquery($1) as q, channels c
    WHERE (p.tsv @@ q) AND p.channel_id = c.id
    ORDER BY ts_rank_cd(p.tsv, plainto_tsquery($1)) DESC LIMIT $2`

	var podcasts []models.Podcast
	return podcasts, db.Select(&podcasts, sql, query, maxSearchRows)

}

func (db *defaultPodcastDBImpl) SearchByChannelID(query string, channelID int64) ([]models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p, plainto_tsquery($2) as q, channels c
    WHERE (p.tsv @@ q) AND p.channel_id = c.id AND c.id=$1
    ORDER BY ts_rank_cd(p.tsv, plainto_tsquery($2)) DESC LIMIT $3`

	var podcasts []models.Podcast
	return podcasts, db.Select(&podcasts, sql, channelID, query, maxSearchRows)

}

func (db *defaultPodcastDBImpl) SearchBookmarked(query string, userID int64) ([]models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p, plainto_tsquery($2) as q, channels c, bookmarks b
    WHERE (p.tsv @@ q OR c.tsv @@ q) AND p.channel_id = c.id AND b.podcast_id = p.id AND b.user_id=$1
    ORDER BY ts_rank_cd(p.tsv, plainto_tsquery($2)) DESC LIMIT $3`

	var podcasts []models.Podcast
	return podcasts, db.Select(&podcasts, sql, userID, query, maxSearchRows)

}

func (db *defaultPodcastDBImpl) SelectPlayed(userID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(DISTINCT(p.id)) FROM podcasts p
    JOIN plays pl ON pl.podcast_id = p.id
    WHERE pl.user_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, userID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p
    JOIN plays pl ON pl.podcast_id = p.id
    JOIN channels c ON c.id = p.channel_id
    WHERE pl.user_id=$1
    GROUP BY p.id, c.title, c.image, pl.created_at
    ORDER BY pl.created_at DESC
    OFFSET $2 LIMIT $3`

	err := db.Select(
		&result.Podcasts,
		sql,
		userID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err

}

func (db *defaultPodcastDBImpl) SelectAll(page int64) (*models.PodcastList, error) {

	sql := "SELECT COUNT(id) FROM podcasts"

	var numRows int64

	if err := db.QueryRow(sql).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN channels c ON c.id = p.channel_id
    ORDER BY p.pub_date DESC
    OFFSET $1 LIMIT $2`
	err := db.Select(
		&result.Podcasts,
		sql,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) SelectSubscribed(userID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(DISTINCT(p.id)) FROM podcasts p
  JOIN subscriptions s ON s.channel_id = p.channel_id
  WHERE s.user_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, userID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN subscriptions s ON s.channel_id = p.channel_id
    JOIN channels c ON c.id = p.channel_id
    WHERE s.user_id=$1
    GROUP BY p.id, p.title, c.image, c.title
    ORDER BY p.pub_date DESC
    OFFSET $2 LIMIT $3`
	err := db.Select(
		&result.Podcasts,
		sql,
		userID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) SelectBookmarked(userID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(DISTINCT(p.id)) FROM podcasts p
  JOIN bookmarks b ON b.podcast_id = p.id
  WHERE b.user_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, userID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN channels c ON c.id = p.channel_id
    JOIN bookmarks b ON b.podcast_id = p.id
    WHERE b.user_id=$1
    GROUP BY p.id, p.title, c.title, c.image
    ORDER BY c.title, p.title
    OFFSET $2 LIMIT $3`

	err := db.Select(
		&result.Podcasts,
		sql,
		userID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) SelectByChannelID(channelID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(id) FROM podcasts WHERE channel_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, channelID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT id, title, enclosure_url, description, pub_date
    FROM podcasts
    WHERE channel_id=$1
    ORDER BY pub_date DESC
    OFFSET $2 LIMIT $3`

	err := db.Select(
		&result.Podcasts,
		sql,
		channelID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) Create(pc *models.Podcast) error {
	query, args, err := sqlx.Named(`
        SELECT insert_podcast(
            :channel_id,
            :guid,
            :title,
            :description,
            :enclosure_url,
            :pub_date)`, pc)
	if err != nil {
		return err
	}
	return db.QueryRow(db.Rebind(query), args...).Scan(&pc.ID)
}
<commit_msg>Btn styling in player<commit_after>package database

import (
	"github.com/danjac/podbaby/models"
	"github.com/jmoiron/sqlx"
)

const maxSearchRows = 20

// PodcastDB manages DB queries to podcasts
type PodcastDB interface {
	GetByID(int64) (*models.Podcast, error)
	SelectAll(int64) (*models.PodcastList, error)
	SelectSubscribed(int64, int64) (*models.PodcastList, error)
	SelectByChannelID(int64, int64) (*models.PodcastList, error)
	SelectBookmarked(int64, int64) (*models.PodcastList, error)
	SelectPlayed(int64, int64) (*models.PodcastList, error)
	Search(string) ([]models.Podcast, error)
	SearchBookmarked(string, int64) ([]models.Podcast, error)
	SearchByChannelID(string, int64) ([]models.Podcast, error)
	Create(*models.Podcast) error
}

type defaultPodcastDBImpl struct {
	*sqlx.DB
}

func (db *defaultPodcastDBImpl) GetByID(id int64) (*models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN channels c ON c.id = p.channel_id
    WHERE p.id=$1`

	podcast := &models.Podcast{}
	err := db.Get(podcast, sql, id)
	return podcast, err
}

func (db *defaultPodcastDBImpl) Search(query string) ([]models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p, plainto_tsquery($1) as q, channels c
    WHERE (p.tsv @@ q) AND p.channel_id = c.id
    ORDER BY ts_rank_cd(p.tsv, plainto_tsquery($1)) DESC LIMIT $2`

	var podcasts []models.Podcast
	return podcasts, db.Select(&podcasts, sql, query, maxSearchRows)

}

func (db *defaultPodcastDBImpl) SearchByChannelID(query string, channelID int64) ([]models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p, plainto_tsquery($2) as q, channels c
    WHERE (p.tsv @@ q) AND p.channel_id = c.id AND c.id=$1
    ORDER BY ts_rank_cd(p.tsv, plainto_tsquery($2)) DESC LIMIT $3`

	var podcasts []models.Podcast
	return podcasts, db.Select(&podcasts, sql, channelID, query, maxSearchRows)

}

func (db *defaultPodcastDBImpl) SearchBookmarked(query string, userID int64) ([]models.Podcast, error) {

	sql := `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p, plainto_tsquery($2) as q, channels c, bookmarks b
    WHERE (p.tsv @@ q OR c.tsv @@ q) AND p.channel_id = c.id AND b.podcast_id = p.id AND b.user_id=$1
    ORDER BY ts_rank_cd(p.tsv, plainto_tsquery($2)) DESC LIMIT $3`

	var podcasts []models.Podcast
	return podcasts, db.Select(&podcasts, sql, userID, query, maxSearchRows)

}

func (db *defaultPodcastDBImpl) SelectPlayed(userID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(DISTINCT(p.id)) FROM podcasts p
    JOIN plays pl ON pl.podcast_id = p.id
    WHERE pl.user_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, userID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, p.pub_date, c.title AS name, c.image
    FROM podcasts p
    JOIN plays pl ON pl.podcast_id = p.id
    JOIN channels c ON c.id = p.channel_id
    WHERE pl.user_id=$1
    GROUP BY p.id, c.title, c.image, pl.created_at
    ORDER BY pl.created_at DESC
    OFFSET $2 LIMIT $3`

	err := db.Select(
		&result.Podcasts,
		sql,
		userID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err

}

func (db *defaultPodcastDBImpl) SelectAll(page int64) (*models.PodcastList, error) {

	sql := "SELECT COUNT(id) FROM podcasts"

	var numRows int64

	if err := db.QueryRow(sql).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN channels c ON c.id = p.channel_id
    ORDER BY p.pub_date DESC
    OFFSET $1 LIMIT $2`
	err := db.Select(
		&result.Podcasts,
		sql,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) SelectSubscribed(userID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(DISTINCT(p.id)) FROM podcasts p
  JOIN subscriptions s ON s.channel_id = p.channel_id
  WHERE s.user_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, userID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN subscriptions s ON s.channel_id = p.channel_id
    JOIN channels c ON c.id = p.channel_id
    WHERE s.user_id=$1
    GROUP BY p.id, p.title, c.image, c.title
    ORDER BY p.pub_date DESC
    OFFSET $2 LIMIT $3`
	err := db.Select(
		&result.Podcasts,
		sql,
		userID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) SelectBookmarked(userID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(DISTINCT(p.id)) FROM podcasts p
  JOIN bookmarks b ON b.podcast_id = p.id
  WHERE b.user_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, userID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT p.id, p.title, p.enclosure_url, p.description,
    p.channel_id, c.title AS name, c.image, p.pub_date
    FROM podcasts p
    JOIN channels c ON c.id = p.channel_id
    JOIN bookmarks b ON b.podcast_id = p.id
    WHERE b.user_id=$1
    GROUP BY p.id, p.title, c.title, c.image, b.id
    ORDER BY b.id DESC
    OFFSET $2 LIMIT $3`

	err := db.Select(
		&result.Podcasts,
		sql,
		userID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) SelectByChannelID(channelID, page int64) (*models.PodcastList, error) {

	sql := `SELECT COUNT(id) FROM podcasts WHERE channel_id=$1`

	var numRows int64

	if err := db.QueryRow(sql, channelID).Scan(&numRows); err != nil {
		return nil, err
	}

	result := &models.PodcastList{
		Page: models.NewPage(page, numRows),
	}

	sql = `SELECT id, title, enclosure_url, description, pub_date
    FROM podcasts
    WHERE channel_id=$1
    ORDER BY pub_date DESC
    OFFSET $2 LIMIT $3`

	err := db.Select(
		&result.Podcasts,
		sql,
		channelID,
		result.Page.Offset,
		result.Page.PageSize)
	return result, err
}

func (db *defaultPodcastDBImpl) Create(pc *models.Podcast) error {
	query, args, err := sqlx.Named(`
        SELECT insert_podcast(
            :channel_id,
            :guid,
            :title,
            :description,
            :enclosure_url,
            :pub_date)`, pc)
	if err != nil {
		return err
	}
	return db.QueryRow(db.Rebind(query), args...).Scan(&pc.ID)
}
<|endoftext|>


<commit_before>package ghtoc

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

func Test_httpGet(t *testing.T) {
	expected := "dummy data"
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := fmt.Fprint(w, expected)
		if err != nil {
			println(err)
		}
	}))
	defer srv.Close()

	body, _, err := httpGet(srv.URL)
	got := string(body)

	if err != nil {
		t.Error("Should not be err", err)
	}
	if got != expected {
		t.Error("\nGot :", got, "\nWant:", expected)
	}
}
<commit_msg>Add Test_httpGetForbidden<commit_after>package ghtoc

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

func Test_httpGet(t *testing.T) {
	expected := "dummy data"
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := fmt.Fprint(w, expected)
		if err != nil {
			println(err)
		}
	}))
	defer srv.Close()

	body, _, err := httpGet(srv.URL)
	got := string(body)

	if err != nil {
		t.Error("Should not be err", err)
	}
	if got != expected {
		t.Error("\nGot :", got, "\nWant:", expected)
	}
}

func Test_httpGetForbidden(t *testing.T) {
	txt := "please, do not try"
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusForbidden)
		_, err := fmt.Fprint(w, txt)
		if err != nil {
			println(err)
		}
	}))
	defer srv.Close()

	_, _, err := httpGet(srv.URL)
	if err == nil {
		t.Error("Should not not be nil")
	}
}
<|endoftext|>


<commit_before>package v5

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"

	"github.com/golang/glog"

	"github.com/jetstack/navigator/pkg/apis/navigator/v1alpha1"
)

// InstallPlugins will install the plugins listed on the Pilot resource. It
// will not uninstall any plugins that are already installed, but are not
// listed on the Pilot resource.
func (p *Pilot) InstallPlugins(pilot *v1alpha1.Pilot) error {
	installed, err := p.getInstalledPlugins(pilot)
	if err != nil {
		return fmt.Errorf("error listing installed plugins: %s", err.Error())
	}
	glog.V(4).Infof("There are %d plugins already installed: %v", len(installed), installed)
	for _, plugin := range p.Options.ElasticsearchOptions.Plugins {
		if _, ok := installed[plugin]; ok {
			glog.V(4).Infof("Skipping already installed plugin '%s'", plugin)
			continue
		}

		err := p.installPlugin(pilot, plugin)
		if err != nil {
			glog.V(4).Infof("Error installing plugin '%s': %s", plugin, err.Error())
			return err
		}

		glog.V(4).Infof("Successfully installed plugin '%s'", plugin)
	}
	return nil
}

// installPlugin will attempt to install a single plugin on this Elasticsearch
// node.
func (p *Pilot) installPlugin(pilot *v1alpha1.Pilot, plugin string) error {
	cmd := exec.Command(p.Options.ElasticsearchOptions.PluginBinary, "install", plugin)
	cmd.Env = p.env().Strings()
	cmd.Stdout = p.Options.StdOut
	cmd.Stderr = p.Options.StdErr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

// getInstalledPlugins will return a list of installed plugins for this Pilot
// by shelling out to the elasticsearch-plugins binary and running 'list'. It
// returns a map containing the plugins name as the key, and an empty struct as
// the value for more efficient indexing.
func (p *Pilot) getInstalledPlugins(pilot *v1alpha1.Pilot) (map[string]struct{}, error) {
	stdout := new(bytes.Buffer)
	cmd := exec.Command(p.Options.ElasticsearchOptions.PluginBinary, "list")
	cmd.Env = p.env().Strings()
	cmd.Stdout = stdout
	cmd.Stderr = p.Options.StdErr
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	strOutput := stdout.String()
	plugins := strings.Split(strOutput, "\n")
	pluginsMap := make(map[string]struct{})
	for _, plugin := range plugins {
		if len(plugin) == 0 {
			continue
		}
		pluginsMap[plugin] = struct{}{}
	}
	return pluginsMap, nil
}
<commit_msg>Use k8s sets package in install_plugins.go<commit_after>package v5

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"

	"github.com/golang/glog"
	"k8s.io/apimachinery/pkg/util/sets"

	"github.com/jetstack/navigator/pkg/apis/navigator/v1alpha1"
)

// InstallPlugins will install the plugins listed on the Pilot resource. It
// will not uninstall any plugins that are already installed, but are not
// listed on the Pilot resource.
func (p *Pilot) InstallPlugins(pilot *v1alpha1.Pilot) error {
	installed, err := p.getInstalledPlugins(pilot)
	if err != nil {
		return fmt.Errorf("error listing installed plugins: %s", err.Error())
	}
	glog.V(4).Infof("There are %d plugins already installed: %v", len(installed), installed)
	for _, plugin := range p.Options.ElasticsearchOptions.Plugins {
		if installed.Has(plugin) {
			glog.V(4).Infof("Skipping already installed plugin '%s'", plugin)
			continue
		}

		err := p.installPlugin(pilot, plugin)
		if err != nil {
			glog.V(4).Infof("Error installing plugin '%s': %s", plugin, err.Error())
			return err
		}

		glog.V(4).Infof("Successfully installed plugin '%s'", plugin)
	}
	return nil
}

// installPlugin will attempt to install a single plugin on this Elasticsearch
// node.
func (p *Pilot) installPlugin(pilot *v1alpha1.Pilot, plugin string) error {
	cmd := exec.Command(p.Options.ElasticsearchOptions.PluginBinary, "install", plugin)
	cmd.Env = p.env().Strings()
	cmd.Stdout = p.Options.StdOut
	cmd.Stderr = p.Options.StdErr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

// getInstalledPlugins will return a list of installed plugins for this Pilot
// by shelling out to the elasticsearch-plugins binary and running 'list'.
func (p *Pilot) getInstalledPlugins(pilot *v1alpha1.Pilot) (sets.String, error) {
	stdout := new(bytes.Buffer)
	cmd := exec.Command(p.Options.ElasticsearchOptions.PluginBinary, "list")
	cmd.Env = p.env().Strings()
	cmd.Stdout = stdout
	cmd.Stderr = p.Options.StdErr
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	strOutput := stdout.String()
	pluginsSlice := strings.Split(strOutput, "\n")
	return sets.NewString(pluginsSlice...), nil
}
<|endoftext|>


<commit_before>package gads

import (
	"encoding/xml"
	"fmt"
	"strings"
)

type OperationError struct {
	Code      int64  `xml:"OperationError>Code"`
	Details   string `xml:"OperationError>Details"`
	ErrorCode string `xml:"OperationError>ErrorCode"`
	Message   string `xml:"OperationError>Message"`
}

type BudgetError struct {
	Path    string `xml:"fieldPath"`
	String  string `xml:"errorString"`
	Trigger string `xml:"trigger"`
	Reason  string `xml:"reason"`
}

type CriterionError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type TargetError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type AdGroupServiceError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type NotEmptyError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type AdError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

// if you exceed the quota given by google
type RateExceededError struct {
	RateName          string `xml:"rateName"`  // For example OperationsByMinute
	RateScope         string `xml:"rateScope"` // ACCOUNT or DEVELOPER
	ErrorString       string `xml:"errorString"`
	Reason            string `xml:"reason"`
	RetryAfterSeconds uint   `xml:"retryAfterSeconds"` // Try again in...
}

type ApiExceptionFault struct {
	Message string        `xml:"message"`
	Type    string        `xml:"ApplicationException.Type"`
	Errors  []interface{} `xml:"errors"`
}

func (aes *ApiExceptionFault) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) (err error) {
	for token, err := dec.Token(); err == nil; token, err = dec.Token() {
		switch start := token.(type) {
		case xml.StartElement:
			switch start.Name.Local {
			case "message":
				if err := dec.DecodeElement(&aes.Message, &start); err != nil {
					return err
				}
			case "ApplicationException.Type":
				if err := dec.DecodeElement(&aes.Type, &start); err != nil {
					return err
				}
			case "errors":
				errorType, _ := findAttr(start.Attr, xml.Name{Space: "http://www.w3.org/2001/XMLSchema-instance", Local: "type"})
				switch errorType {
				case "CriterionError":
					e := CriterionError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "TargetError":
					e := TargetError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "BudgetError":
					e := BudgetError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "AdGroupServiceError":
					e := AdGroupServiceError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "NotEmptyError":
					e := NotEmptyError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "AdError":
					e := AdError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "RateExceededError":
					e := RateExceededError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				default:
					return fmt.Errorf("Unknown error type -> %s", start)
				}
			case "reason":
				break
			default:
				return fmt.Errorf("Unknown error field -> %s", start)
			}
		}
	}
	return err
}

type ErrorsType struct {
	ApiExceptionFaults []ApiExceptionFault `xml:"ApiExceptionFault"`
}

func (f ErrorsType) Error() string {
	errors := []string{}
	for _, e := range f.ApiExceptionFaults {
		errors = append(errors, fmt.Sprintf("%s", e.Message))
	}
	return strings.Join(errors, "\n")
}

type Fault struct {
	XMLName     xml.Name   `xml:"Fault"`
	FaultCode   string     `xml:"faultcode"`
	FaultString string     `xml:"faultstring"`
	Errors      ErrorsType `xml:"detail"`
}

func (f Fault) Error() string {
	return f.FaultString + " - " + f.Errors.Error()
}
<commit_msg>adding unknown error<commit_after>package gads

import (
	"encoding/xml"
	"fmt"
	"strings"
)

type OperationError struct {
	Code      int64  `xml:"OperationError>Code"`
	Details   string `xml:"OperationError>Details"`
	ErrorCode string `xml:"OperationError>ErrorCode"`
	Message   string `xml:"OperationError>Message"`
}

type BudgetError struct {
	Path    string `xml:"fieldPath"`
	String  string `xml:"errorString"`
	Trigger string `xml:"trigger"`
	Reason  string `xml:"reason"`
}

type CriterionError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type TargetError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type AdGroupServiceError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type NotEmptyError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type AdError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

// if you exceed the quota given by google
type RateExceededError struct {
	RateName          string `xml:"rateName"`  // For example OperationsByMinute
	RateScope         string `xml:"rateScope"` // ACCOUNT or DEVELOPER
	ErrorString       string `xml:"errorString"`
	Reason            string `xml:"reason"`
	RetryAfterSeconds uint   `xml:"retryAfterSeconds"` // Try again in...
}

type UnknownError struct {
	FieldPath   string `xml:"fieldPath"`
	Trigger     string `xml:"trigger"`
	ErrorString string `xml:"errorString"`
	Reason      string `xml:"reason"`
}

type ApiExceptionFault struct {
	Message string        `xml:"message"`
	Type    string        `xml:"ApplicationException.Type"`
	Errors  []interface{} `xml:"errors"`
}

func (aes *ApiExceptionFault) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) (err error) {
	for token, err := dec.Token(); err == nil; token, err = dec.Token() {
		switch start := token.(type) {
		case xml.StartElement:
			switch start.Name.Local {
			case "message":
				if err := dec.DecodeElement(&aes.Message, &start); err != nil {
					return err
				}
			case "ApplicationException.Type":
				if err := dec.DecodeElement(&aes.Type, &start); err != nil {
					return err
				}
			case "errors":
				errorType, _ := findAttr(start.Attr, xml.Name{Space: "http://www.w3.org/2001/XMLSchema-instance", Local: "type"})
				switch errorType {
				case "CriterionError":
					e := CriterionError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "TargetError":
					e := TargetError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "BudgetError":
					e := BudgetError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "AdGroupServiceError":
					e := AdGroupServiceError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "NotEmptyError":
					e := NotEmptyError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "AdError":
					e := AdError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				case "RateExceededError":
					e := RateExceededError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				default:
					e := UnknownError{}
					dec.DecodeElement(&e, &start)
					aes.Errors = append(aes.Errors, e)
				}
			case "reason":
				break
			default:
				return fmt.Errorf("Unknown error field -> %s", start)
			}
		}
	}
	return err
}

type ErrorsType struct {
	ApiExceptionFaults []ApiExceptionFault `xml:"ApiExceptionFault"`
}

func (f ErrorsType) Error() string {
	errors := []string{}
	for _, e := range f.ApiExceptionFaults {
		errors = append(errors, fmt.Sprintf("%s", e.Message))
	}
	return strings.Join(errors, "\n")
}

type Fault struct {
	XMLName     xml.Name   `xml:"Fault"`
	FaultCode   string     `xml:"faultcode"`
	FaultString string     `xml:"faultstring"`
	Errors      ErrorsType `xml:"detail"`
}

func (f Fault) Error() string {
	return f.FaultString + " - " + f.Errors.Error()
}
<|endoftext|>


<commit_before>/**
 *
 * @author  chosen0ne(louzhenlin86@126.com)
 * @date    2014/11/28 11:51:28
 */

package goutils

import (
	"bytes"
	"errors"
	"fmt"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
)

// wrapedError is uesed to wrap an error, and show the stacktrace
// information.
type wrapedError struct {
	depth int // nested depth
	err   error
	fname string // file name the error occurs
	lno   int    // line number the error occurs
}

// Error provides more information about the error stacktrace.
func (we wrapedError) Error() (e string) {
	switch we.err.(type) {
	case wrapedError:
		e = we.err.Error() + "\n" + strings.Repeat("  ", we.depth) + "=> " + position(we.fname, we.lno)
	default:
		e = position(we.fname, we.lno) + " => " + we.err.Error()
	}
	return
}

// NewErr will create an error which contains the postion information
// of the error.
func NewErr(format string, args ...interface{}) error {
	var buf bytes.Buffer
	_, fname, lno, ok := runtime.Caller(1)
	if !ok {
		fname, lno = "unkown", -1
	}

	fmt.Fprintf(&buf, format, args...)

	// errors.go:15 => some error
	return errors.New(position(fname, lno) + " => " + string(buf.Bytes()))
}

func WrapErr(err error) error {
	_, fname, lno, ok := runtime.Caller(1)
	if !ok {
		fname, lno = "unkown", -1
	}

	switch err.(type) {
	case wrapedError:
		we := err.(wrapedError)
		return &wrapedError{we.depth + 1, err, fname, lno}
	case *wrapedError:
		we := err.(*wrapedError)
		return &wrapedError{we.depth + 1, err, fname, lno}
	default:
		return &wrapedError{0, err, fname, lno}
	}
}

func position(fname string, lno int) string {
	return filepath.Base(fname) + ":" + strconv.Itoa(lno)
}
<commit_msg>- support WrapErrorf<commit_after>/**
 *
 * @author  chosen0ne(louzhenlin86@126.com)
 * @date    2014/11/28 11:51:28
 */

package goutils

import (
	"bytes"
	"errors"
	"fmt"
	"path/filepath"
	"runtime"
	"strconv"
)

// wrapedError is uesed to wrap an error, and show the stacktrace
// information.
type wrapedError struct {
	depth int // nested depth
	err   error
	fname string // file name the error occurs
	lno   int    // line number the error occurs
	msg   string
}

// Error provides more information about the error stacktrace.
func (we wrapedError) Error() string {
	b := bytes.Buffer{}

	// msg for current error: we
	b.WriteString(position(we.fname, we.lno))
	b.WriteString(" => ")
	b.WriteString(we.msg)

	switch we.err.(type) {
	case wrapedError:
		b.WriteString("\r\n")
	case *wrapedError:
		b.WriteString("\r\n")
	case error:
		b.WriteString("=> ")
	}

	// msg for nested error
	b.WriteString(we.err.Error())

	return string(b.Bytes())
}

// NewErr will create an error which contains the postion information
// of the error.
func NewErr(format string, args ...interface{}) error {
	var buf bytes.Buffer
	_, fname, lno, ok := runtime.Caller(1)
	if !ok {
		fname, lno = "unkown", -1
	}

	fmt.Fprintf(&buf, format, args...)

	// errors.go:15 => some error
	return errors.New(position(fname, lno) + " => " + string(buf.Bytes()))
}

func WrapErr(err error) error {
	_, fname, lno, ok := runtime.Caller(1)
	if !ok {
		fname, lno = "unkown", -1
	}

	return newWrapErr(err, fname, lno, "")
}

func WrapErrorf(err error, format string, args ...interface{}) error {
	buf := &bytes.Buffer{}
	fmt.Fprintf(buf, format, args...)
	msg := string(buf.Bytes())

	_, fname, lno, ok := runtime.Caller(1)
	if !ok {
		fname, lno = "unkown", -1
	}

	return newWrapErr(err, fname, lno, msg)
}

func newWrapErr(err error, fname string, lno int, msg string) error {
	switch err.(type) {
	case wrapedError:
		we := err.(wrapedError)
		return &wrapedError{we.depth + 1, err, fname, lno, msg}
	case *wrapedError:
		we := err.(*wrapedError)
		return &wrapedError{we.depth + 1, err, fname, lno, msg}
	default:
		return &wrapedError{0, err, fname, lno, msg}
	}
}

func position(fname string, lno int) string {
	return filepath.Base(fname) + ":" + strconv.Itoa(lno)
}
<|endoftext|>


<commit_before>// Copyright ©2014 The gonum 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 optimize

import (
	"errors"
	"fmt"
)

var (
	// ErrInf signifies the initial function value is Inf.
	ErrInf = errors.New("optimize: initial function value is Inf")

	// ErrGradInf signifies the initial function value is Inf.
	ErrGradInf = errors.New("optimize: initial gradient is Inf")

	// ErrLinesearchFailure signifies the linesearch has iterated too many
	// times. This may occur if the gradient tolerance is set too low.
	ErrLinesearchFailure = errors.New("linesearch: failed to converge")

	// ErrNaN signifies the initial function value is NaN.
	ErrNaN = errors.New("optimize: initial function value is NaN")

	// ErrGradNaN signifies the initial function value is NaN.
	ErrGradNaN = errors.New("optimize: initial gradient is NaN")

	// ErrNonNegativeStepDirection signifies that the linesearch has received a
	// step direction in which the gradient is not negative.
	ErrNonNegativeStepDirection = errors.New("linesearch: projected gradient not negative")

	// ErrZeroDimensional signifies an optimization was called with an input of length 0.
	ErrZeroDimensional = errors.New("optimize: zero dimensional input")
)

// ErrMismatch signifies that the optimization function did not implement the
// interfaces necessary for the supplied optimization method.
type ErrMismatch struct {
	Type EvaluationType
}

func (e ErrMismatch) Error() string {
	return fmt.Sprintf("optimizer wanted to use evaluation type %v, but the user supplied function does not implement it", e.Type)
}
<commit_msg>Add ErrNoProgress error<commit_after>// Copyright ©2014 The gonum 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 optimize

import (
	"errors"
	"fmt"
)

var (
	// ErrInf signifies the initial function value is Inf.
	ErrInf = errors.New("optimize: initial function value is Inf")

	// ErrGradInf signifies the initial function value is Inf.
	ErrGradInf = errors.New("optimize: initial gradient is Inf")

	// ErrLinesearchFailure signifies the linesearch has iterated too many
	// times. This may occur if the gradient tolerance is set too low.
	ErrLinesearchFailure = errors.New("linesearch: failed to converge")

	// ErrNaN signifies the initial function value is NaN.
	ErrNaN = errors.New("optimize: initial function value is NaN")

	// ErrGradNaN signifies the initial function value is NaN.
	ErrGradNaN = errors.New("optimize: initial gradient is NaN")

	// ErrNonNegativeStepDirection signifies that the linesearch has received a
	// step direction in which the gradient is not negative.
	ErrNonNegativeStepDirection = errors.New("linesearch: projected gradient not negative")

	// ErrZeroDimensional signifies an optimization was called with an input of length 0.
	ErrZeroDimensional = errors.New("optimize: zero dimensional input")

	// ErrNoProgress signifies that Linesearch cannot make further progress
	// because there is no change in location after LinesearchMethod step due
	// to floating-point arithmetic.
	ErrNoProgress = errors.New("linesearch: no change in location after linesearch step")
)

// ErrMismatch signifies that the optimization function did not implement the
// interfaces necessary for the supplied optimization method.
type ErrMismatch struct {
	Type EvaluationType
}

func (e ErrMismatch) Error() string {
	return fmt.Sprintf("optimizer wanted to use evaluation type %v, but the user supplied function does not implement it", e.Type)
}
<|endoftext|>


<commit_before>package kinds

import (
	"context"

	"github.com/creativesoftwarefdn/weaviate/database"
	"github.com/creativesoftwarefdn/weaviate/database/schema"
	"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
	"github.com/creativesoftwarefdn/weaviate/models"
	"github.com/creativesoftwarefdn/weaviate/validation"
	"github.com/go-openapi/strfmt"
)

type addRepo interface {
	// The validation package needs to be able to get existing classes as well
	getRepo

	// methods to add new items
	AddAction(ctx context.Context, class *models.Action, id strfmt.UUID) error
	AddThing(ctx context.Context, class *models.Thing, id strfmt.UUID) error
}

// AddAction Class Instance to the connected DB. If the class contains a network
// ref, it has a side-effect on the schema: The schema will be updated to
// include this particular network ref class.
func (m *Manager) AddAction(ctx context.Context, class *models.Action) (*models.Action, error) {
	schemaLock, err := m.db.SchemaLock()
	if err != nil {
		return nil, newErrInternal("could not aquire lock: %v", err)
	}
	defer unlock(schemaLock)
	dbConnector := schemaLock.Connector()
	schemaManager := schemaLock.SchemaManager()

	return m.addActionToConnectorAndSchema(ctx, class, dbConnector, schemaManager)
}

func (m *Manager) addActionToConnectorAndSchema(ctx context.Context, class *models.Action,
	addRepo addRepo, schemaManager database.SchemaManager) (*models.Action, error) {
	class.ID = generateUUID()
	err := m.validateAction(ctx, schemaManager.GetSchema(), class, addRepo)
	if err != nil {
		return nil, newErrInvalidUserInput("invalid action: %v", err)
	}

	err = m.addNetworkDataTypesForAction(ctx, schemaManager, class)
	if err != nil {
		return nil, newErrInternal("could not update schema for network refs: %v", err)
	}

	addRepo.AddAction(ctx, class, class.ID)
	if err != nil {
		return nil, newErrInternal("could not store action: %v", err)
	}

	return class, nil
}

func (m *Manager) validateAction(ctx context.Context, dbschema schema.Schema,
	class *models.Action, getRepo getRepo) error {
	// Validate schema given in body with the weaviate schema
	databaseSchema := schema.HackFromDatabaseSchema(dbschema)
	return validation.ValidateActionBody(
		ctx, class, databaseSchema, getRepo, m.network, m.config)
}

// AddThing Class Instance to the connected DB. If the class contains a network
// ref, it has a side-effect on the schema: The schema will be updated to
// include this particular network ref class.
func (m *Manager) AddThing(ctx context.Context, class *models.Thing) (*models.Thing, error) {
	schemaLock, err := m.db.SchemaLock()
	if err != nil {
		return nil, newErrInternal("could not aquire lock: %v", err)
	}
	defer unlock(schemaLock)
	dbConnector := schemaLock.Connector()
	schemaManager := schemaLock.SchemaManager()

	return m.addThingToConnectorAndSchema(ctx, class, dbConnector, schemaManager)
}

func (m *Manager) addThingToConnectorAndSchema(ctx context.Context, class *models.Thing,
	addRepo addRepo, schemaManager database.SchemaManager) (*models.Thing, error) {
	class.ID = generateUUID()
	err := m.validateThing(ctx, schemaManager.GetSchema(), class, addRepo)
	if err != nil {
		return nil, newErrInvalidUserInput("invalid thing: %v", err)
	}

	err = m.addNetworkDataTypesForThing(ctx, schemaManager, class)
	if err != nil {
		return nil, newErrInternal("could not update schema for network refs: %v", err)
	}

	addRepo.AddThing(ctx, class, class.ID)
	if err != nil {
		return nil, newErrInternal("could not store thing: %v", err)
	}

	return class, nil
}

func (m *Manager) validateThing(ctx context.Context, dbschema schema.Schema,
	class *models.Thing, getRepo getRepo) error {
	// Validate schema given in body with the weaviate schema
	databaseSchema := schema.HackFromDatabaseSchema(dbschema)
	return validation.ValidateThingBody(
		ctx, class, databaseSchema, getRepo, m.network, m.config)
}

func (m *Manager) addNetworkDataTypesForThing(ctx context.Context, sm database.SchemaManager, class *models.Thing) error {
	refSchemaUpdater := newReferenceSchemaUpdater(ctx, sm, m.network, class.Class, kind.THING_KIND)
	return refSchemaUpdater.addNetworkDataTypes(class.Schema)
}

func (m *Manager) addNetworkDataTypesForAction(ctx context.Context, sm database.SchemaManager, class *models.Action) error {
	refSchemaUpdater := newReferenceSchemaUpdater(ctx, sm, m.network, class.Class, kind.ACTION_KIND)
	return refSchemaUpdater.addNetworkDataTypes(class.Schema)
}
<commit_msg>gh-836: add more local interfaces to remove hard dependencies on db<commit_after>package kinds

import (
	"context"

	"github.com/creativesoftwarefdn/weaviate/database/schema"
	"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
	"github.com/creativesoftwarefdn/weaviate/models"
	"github.com/creativesoftwarefdn/weaviate/validation"
	"github.com/go-openapi/strfmt"
)

type addRepo interface {
	// The validation package needs to be able to get existing classes as well
	getRepo

	// methods to add new items
	AddAction(ctx context.Context, class *models.Action, id strfmt.UUID) error
	AddThing(ctx context.Context, class *models.Thing, id strfmt.UUID) error
}

// TODO: Can we use the schema manager UC here instead of the "whole thing"?
type schemaManager interface {
	UpdatePropertyAddDataType(context.Context, kind.Kind, string, string, string) error
	GetSchema() schema.Schema
}

// AddAction Class Instance to the connected DB. If the class contains a network
// ref, it has a side-effect on the schema: The schema will be updated to
// include this particular network ref class.
func (m *Manager) AddAction(ctx context.Context, class *models.Action) (*models.Action, error) {
	schemaLock, err := m.db.SchemaLock()
	if err != nil {
		return nil, newErrInternal("could not aquire lock: %v", err)
	}
	defer unlock(schemaLock)
	dbConnector := schemaLock.Connector()
	schemaManager := schemaLock.SchemaManager()

	return m.addActionToConnectorAndSchema(ctx, class, dbConnector, schemaManager)
}

func (m *Manager) addActionToConnectorAndSchema(ctx context.Context, class *models.Action,
	addRepo addRepo, schemaManager schemaManager) (*models.Action, error) {
	class.ID = generateUUID()
	err := m.validateAction(ctx, schemaManager.GetSchema(), class, addRepo)
	if err != nil {
		return nil, newErrInvalidUserInput("invalid action: %v", err)
	}

	err = m.addNetworkDataTypesForAction(ctx, schemaManager, class)
	if err != nil {
		return nil, newErrInternal("could not update schema for network refs: %v", err)
	}

	addRepo.AddAction(ctx, class, class.ID)
	if err != nil {
		return nil, newErrInternal("could not store action: %v", err)
	}

	return class, nil
}

func (m *Manager) validateAction(ctx context.Context, dbschema schema.Schema,
	class *models.Action, getRepo getRepo) error {
	// Validate schema given in body with the weaviate schema
	databaseSchema := schema.HackFromDatabaseSchema(dbschema)
	return validation.ValidateActionBody(
		ctx, class, databaseSchema, getRepo, m.network, m.config)
}

// AddThing Class Instance to the connected DB. If the class contains a network
// ref, it has a side-effect on the schema: The schema will be updated to
// include this particular network ref class.
func (m *Manager) AddThing(ctx context.Context, class *models.Thing) (*models.Thing, error) {
	schemaLock, err := m.db.SchemaLock()
	if err != nil {
		return nil, newErrInternal("could not aquire lock: %v", err)
	}
	defer unlock(schemaLock)
	dbConnector := schemaLock.Connector()
	schemaManager := schemaLock.SchemaManager()

	return m.addThingToConnectorAndSchema(ctx, class, dbConnector, schemaManager)
}

func (m *Manager) addThingToConnectorAndSchema(ctx context.Context, class *models.Thing,
	addRepo addRepo, schemaManager schemaManager) (*models.Thing, error) {
	class.ID = generateUUID()
	err := m.validateThing(ctx, schemaManager.GetSchema(), class, addRepo)
	if err != nil {
		return nil, newErrInvalidUserInput("invalid thing: %v", err)
	}

	err = m.addNetworkDataTypesForThing(ctx, schemaManager, class)
	if err != nil {
		return nil, newErrInternal("could not update schema for network refs: %v", err)
	}

	addRepo.AddThing(ctx, class, class.ID)
	if err != nil {
		return nil, newErrInternal("could not store thing: %v", err)
	}

	return class, nil
}

func (m *Manager) validateThing(ctx context.Context, dbschema schema.Schema,
	class *models.Thing, getRepo getRepo) error {
	// Validate schema given in body with the weaviate schema
	databaseSchema := schema.HackFromDatabaseSchema(dbschema)
	return validation.ValidateThingBody(
		ctx, class, databaseSchema, getRepo, m.network, m.config)
}

func (m *Manager) addNetworkDataTypesForThing(ctx context.Context, sm schemaManager, class *models.Thing) error {
	refSchemaUpdater := newReferenceSchemaUpdater(ctx, sm, m.network, class.Class, kind.THING_KIND)
	return refSchemaUpdater.addNetworkDataTypes(class.Schema)
}

func (m *Manager) addNetworkDataTypesForAction(ctx context.Context, sm schemaManager, class *models.Action) error {
	refSchemaUpdater := newReferenceSchemaUpdater(ctx, sm, m.network, class.Class, kind.ACTION_KIND)
	return refSchemaUpdater.addNetworkDataTypes(class.Schema)
}
<|endoftext|>


<commit_before>package dom

import (
	"time"

	"github.com/gopherjs/gopherjs/js"
)

func WrapEvent(o js.Object) Event {
	return wrapEvent(o)
}

func wrapEvent(o js.Object) Event {
	if o.IsNull() || o.IsUndefined() {
		return nil
	}
	ev := &BasicEvent{o}
	c := o.Get("constructor")
	switch c {
	case js.Global.Get("AnimationEvent"):
		return &AnimationEvent{ev}
	case js.Global.Get("AudioProcessingEvent"):
		return &AudioProcessingEvent{ev}
	case js.Global.Get("BeforeInputEvent"):
		return &BeforeInputEvent{ev}
	case js.Global.Get("BeforeUnloadEvent"):
		return &BeforeUnloadEvent{ev}
	case js.Global.Get("BlobEvent"):
		return &BlobEvent{ev}
	case js.Global.Get("ClipboardEvent"):
		return &ClipboardEvent{ev}
	case js.Global.Get("CloseEvent"):
		return &CloseEvent{BasicEvent: ev}
	case js.Global.Get("CompositionEvent"):
		return &CompositionEvent{ev}
	case js.Global.Get("CSSFontFaceLoadEvent"):
		return &CSSFontFaceLoadEvent{ev}
	case js.Global.Get("CustomEvent"):
		return &CustomEvent{ev}
	case js.Global.Get("DeviceLightEvent"):
		return &DeviceLightEvent{ev}
	case js.Global.Get("DeviceMotionEvent"):
		return &DeviceMotionEvent{ev}
	case js.Global.Get("DeviceOrientationEvent"):
		return &DeviceOrientationEvent{ev}
	case js.Global.Get("DeviceProximityEvent"):
		return &DeviceProximityEvent{ev}
	case js.Global.Get("DOMTransactionEvent"):
		return &DOMTransactionEvent{ev}
	case js.Global.Get("DragEvent"):
		return &DragEvent{ev}
	case js.Global.Get("EditingBeforeInputEvent"):
		return &EditingBeforeInputEvent{ev}
	case js.Global.Get("ErrorEvent"):
		return &ErrorEvent{ev}
	case js.Global.Get("FocusEvent"):
		return &FocusEvent{ev}
	case js.Global.Get("GamepadEvent"):
		return &GamepadEvent{ev}
	case js.Global.Get("HashChangeEvent"):
		return &HashChangeEvent{ev}
	case js.Global.Get("IDBVersionChangeEvent"):
		return &IDBVersionChangeEvent{ev}
	case js.Global.Get("KeyboardEvent"):
		return &KeyboardEvent{BasicEvent: ev}
	case js.Global.Get("MediaStreamEvent"):
		return &MediaStreamEvent{ev}
	case js.Global.Get("MessageEvent"):
		return &MessageEvent{BasicEvent: ev}
	case js.Global.Get("MouseEvent"):
		return &MouseEvent{UIEvent: &UIEvent{ev}}
	case js.Global.Get("MutationEvent"):
		return &MutationEvent{ev}
	case js.Global.Get("OfflineAudioCompletionEvent"):
		return &OfflineAudioCompletionEvent{ev}
	case js.Global.Get("PageTransitionEvent"):
		return &PageTransitionEvent{ev}
	case js.Global.Get("PointerEvent"):
		return &PointerEvent{ev}
	case js.Global.Get("PopStateEvent"):
		return &PopStateEvent{ev}
	case js.Global.Get("ProgressEvent"):
		return &ProgressEvent{ev}
	case js.Global.Get("RelatedEvent"):
		return &RelatedEvent{ev}
	case js.Global.Get("RTCPeerConnectionIceEvent"):
		return &RTCPeerConnectionIceEvent{ev}
	case js.Global.Get("SensorEvent"):
		return &SensorEvent{ev}
	case js.Global.Get("StorageEvent"):
		return &StorageEvent{ev}
	case js.Global.Get("SVGEvent"):
		return &SVGEvent{ev}
	case js.Global.Get("SVGZoomEvent"):
		return &SVGZoomEvent{ev}
	case js.Global.Get("TimeEvent"):
		return &TimeEvent{ev}
	case js.Global.Get("TouchEvent"):
		return &TouchEvent{ev}
	case js.Global.Get("TrackEvent"):
		return &TrackEvent{ev}
	case js.Global.Get("TransitionEvent"):
		return &TransitionEvent{ev}
	case js.Global.Get("UIEvent"):
		return &UIEvent{ev}
	case js.Global.Get("UserProximityEvent"):
		return &UserProximityEvent{ev}
	case js.Global.Get("WheelEvent"):
		return &WheelEvent{BasicEvent: ev}
	default:
		return ev
	}
}

const (
	EvPhaseNone      = 0
	EvPhaseCapturing = 1
	EvPhaseAtTarget  = 2
	EvPhaseBubbling  = 3
)

type Event interface {
	Bubbles() bool
	Cancelable() bool
	CurrentTarget() Element
	DefaultPrevented() bool
	EventPhase() int
	Target() Element
	Timestamp() time.Time
	Type() string
	PreventDefault()
	StopImmediatePropagation()
	StopPropagation()
}

// Type BasicEvent implements the Event interface and is embedded by
// concrete event types.
type BasicEvent struct{ js.Object }

func (ev *BasicEvent) Bubbles() bool {
	return ev.Get("bubbles").Bool()
}

func (ev *BasicEvent) Cancelable() bool {
	return ev.Get("cancelable").Bool()
}

func (ev *BasicEvent) CurrentTarget() Element {
	return wrapElement(ev.Get("currentTarget"))
}

func (ev *BasicEvent) DefaultPrevented() bool {
	return ev.Get("defaultPrevented").Bool()
}

func (ev *BasicEvent) EventPhase() int {
	return ev.Get("eventPhase").Int()
}

func (ev *BasicEvent) Target() Element {
	return wrapElement(ev.Get("target"))
}

func (ev *BasicEvent) Timestamp() time.Time {
	ms := ev.Get("timeStamp").Int()
	s := ms / 1000
	ns := (ms % 1000 * 1e6)
	return time.Unix(int64(s), int64(ns))
}

func (ev *BasicEvent) Type() string {
	return ev.Get("type").Str()
}

func (ev *BasicEvent) PreventDefault() {
	ev.Call("preventDefault")
}

func (ev *BasicEvent) StopImmediatePropagation() {
	ev.Call("stopImmediatePropagation")
}

func (ev *BasicEvent) StopPropagation() {
	ev.Call("stopPropagation")
}

type AnimationEvent struct{ *BasicEvent }
type AudioProcessingEvent struct{ *BasicEvent }
type BeforeInputEvent struct{ *BasicEvent }
type BeforeUnloadEvent struct{ *BasicEvent }
type BlobEvent struct{ *BasicEvent }
type ClipboardEvent struct{ *BasicEvent }

type CloseEvent struct {
	*BasicEvent
	Code     int    `js:"code"`
	Reason   string `js:"reason"`
	WasClean bool   `js:"wasClean"`
}

type CompositionEvent struct{ *BasicEvent }
type CSSFontFaceLoadEvent struct{ *BasicEvent }
type CustomEvent struct{ *BasicEvent }
type DeviceLightEvent struct{ *BasicEvent }
type DeviceMotionEvent struct{ *BasicEvent }
type DeviceOrientationEvent struct{ *BasicEvent }
type DeviceProximityEvent struct{ *BasicEvent }
type DOMTransactionEvent struct{ *BasicEvent }
type DragEvent struct{ *BasicEvent }
type EditingBeforeInputEvent struct{ *BasicEvent }
type ErrorEvent struct{ *BasicEvent }
type FocusEvent struct{ *BasicEvent }
type GamepadEvent struct{ *BasicEvent }
type HashChangeEvent struct{ *BasicEvent }
type IDBVersionChangeEvent struct{ *BasicEvent }

const (
	KeyLocationStandard = 0
	KeyLocationLeft     = 1
	KeyLocationRight    = 2
	KeyLocationNumpad   = 3
)

type KeyboardEvent struct {
	*BasicEvent
	AltKey   bool   `js:"altKey"`
	CharCode int    `js:"charCode"`
	CtrlKey  bool   `js:"ctrlKey"`
	Key      string `js:"key"`
	Locale   string `js:"locale"`
	Location int    `js:"location"`
	MetaKey  bool   `js:"metaKey"`
	Repeat   bool   `js:"repeat"`
	ShiftKey bool   `js:"shiftKey"`
}

func (ev *KeyboardEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MediaStreamEvent struct{ *BasicEvent }

type MessageEvent struct {
	*BasicEvent
	Data js.Object `js:"data"`
}

type MouseEvent struct {
	*UIEvent
	AltKey    bool `js:"altKey"`
	Button    int  `js:"button"`
	ClientX   int  `js:"clientX"`
	ClientY   int  `js:"clientY"`
	CtrlKey   bool `js:"ctrlKey"`
	MetaKey   bool `js:"metaKey"`
	MovementX int  `js:"movementX"`
	MovementY int  `js:"movementY"`
	ScreenX   int  `js:"screenX"`
	ScreenY   int  `js:"screenY"`
	ShiftKey  bool `js:"shiftKey"`
}

func (ev *MouseEvent) RelatedTarget() Element {
	return wrapElement(ev.Get("target"))
}

func (ev *MouseEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MutationEvent struct{ *BasicEvent }
type OfflineAudioCompletionEvent struct{ *BasicEvent }
type PageTransitionEvent struct{ *BasicEvent }
type PointerEvent struct{ *BasicEvent }
type PopStateEvent struct{ *BasicEvent }
type ProgressEvent struct{ *BasicEvent }
type RelatedEvent struct{ *BasicEvent }
type RTCPeerConnectionIceEvent struct{ *BasicEvent }
type SensorEvent struct{ *BasicEvent }
type StorageEvent struct{ *BasicEvent }
type SVGEvent struct{ *BasicEvent }
type SVGZoomEvent struct{ *BasicEvent }
type TimeEvent struct{ *BasicEvent }
type TouchEvent struct{ *BasicEvent }
type TrackEvent struct{ *BasicEvent }
type TransitionEvent struct{ *BasicEvent }
type UIEvent struct{ *BasicEvent }
type UserProximityEvent struct{ *BasicEvent }

const (
	DeltaPixel = 0
	DeltaLine  = 1
	DeltaPage  = 2
)

type WheelEvent struct {
	*BasicEvent
	DeltaX    float64 `js:"deltaX"`
	DeltaY    float64 `js:"deltaY"`
	DeltaZ    float64 `js:"deltaZ"`
	DeltaMode int     `js:"deltaMode"`
}

type EventTarget interface {
	// AddEventListener adds a new event listener and returns the
	// wrapper function it generated. If using RemoveEventListener,
	// that wrapper has to be used.
	AddEventListener(typ string, useCapture bool, listener func(Event)) func(js.Object)
	RemoveEventListener(typ string, useCapture bool, listener func(js.Object))
	// DispatchEvent() // TODO
}
<commit_msg>add various key-related fields to KeyboardEvent<commit_after>package dom

import (
	"time"

	"github.com/gopherjs/gopherjs/js"
)

func WrapEvent(o js.Object) Event {
	return wrapEvent(o)
}

func wrapEvent(o js.Object) Event {
	if o.IsNull() || o.IsUndefined() {
		return nil
	}
	ev := &BasicEvent{o}
	c := o.Get("constructor")
	switch c {
	case js.Global.Get("AnimationEvent"):
		return &AnimationEvent{ev}
	case js.Global.Get("AudioProcessingEvent"):
		return &AudioProcessingEvent{ev}
	case js.Global.Get("BeforeInputEvent"):
		return &BeforeInputEvent{ev}
	case js.Global.Get("BeforeUnloadEvent"):
		return &BeforeUnloadEvent{ev}
	case js.Global.Get("BlobEvent"):
		return &BlobEvent{ev}
	case js.Global.Get("ClipboardEvent"):
		return &ClipboardEvent{ev}
	case js.Global.Get("CloseEvent"):
		return &CloseEvent{BasicEvent: ev}
	case js.Global.Get("CompositionEvent"):
		return &CompositionEvent{ev}
	case js.Global.Get("CSSFontFaceLoadEvent"):
		return &CSSFontFaceLoadEvent{ev}
	case js.Global.Get("CustomEvent"):
		return &CustomEvent{ev}
	case js.Global.Get("DeviceLightEvent"):
		return &DeviceLightEvent{ev}
	case js.Global.Get("DeviceMotionEvent"):
		return &DeviceMotionEvent{ev}
	case js.Global.Get("DeviceOrientationEvent"):
		return &DeviceOrientationEvent{ev}
	case js.Global.Get("DeviceProximityEvent"):
		return &DeviceProximityEvent{ev}
	case js.Global.Get("DOMTransactionEvent"):
		return &DOMTransactionEvent{ev}
	case js.Global.Get("DragEvent"):
		return &DragEvent{ev}
	case js.Global.Get("EditingBeforeInputEvent"):
		return &EditingBeforeInputEvent{ev}
	case js.Global.Get("ErrorEvent"):
		return &ErrorEvent{ev}
	case js.Global.Get("FocusEvent"):
		return &FocusEvent{ev}
	case js.Global.Get("GamepadEvent"):
		return &GamepadEvent{ev}
	case js.Global.Get("HashChangeEvent"):
		return &HashChangeEvent{ev}
	case js.Global.Get("IDBVersionChangeEvent"):
		return &IDBVersionChangeEvent{ev}
	case js.Global.Get("KeyboardEvent"):
		return &KeyboardEvent{BasicEvent: ev}
	case js.Global.Get("MediaStreamEvent"):
		return &MediaStreamEvent{ev}
	case js.Global.Get("MessageEvent"):
		return &MessageEvent{BasicEvent: ev}
	case js.Global.Get("MouseEvent"):
		return &MouseEvent{UIEvent: &UIEvent{ev}}
	case js.Global.Get("MutationEvent"):
		return &MutationEvent{ev}
	case js.Global.Get("OfflineAudioCompletionEvent"):
		return &OfflineAudioCompletionEvent{ev}
	case js.Global.Get("PageTransitionEvent"):
		return &PageTransitionEvent{ev}
	case js.Global.Get("PointerEvent"):
		return &PointerEvent{ev}
	case js.Global.Get("PopStateEvent"):
		return &PopStateEvent{ev}
	case js.Global.Get("ProgressEvent"):
		return &ProgressEvent{ev}
	case js.Global.Get("RelatedEvent"):
		return &RelatedEvent{ev}
	case js.Global.Get("RTCPeerConnectionIceEvent"):
		return &RTCPeerConnectionIceEvent{ev}
	case js.Global.Get("SensorEvent"):
		return &SensorEvent{ev}
	case js.Global.Get("StorageEvent"):
		return &StorageEvent{ev}
	case js.Global.Get("SVGEvent"):
		return &SVGEvent{ev}
	case js.Global.Get("SVGZoomEvent"):
		return &SVGZoomEvent{ev}
	case js.Global.Get("TimeEvent"):
		return &TimeEvent{ev}
	case js.Global.Get("TouchEvent"):
		return &TouchEvent{ev}
	case js.Global.Get("TrackEvent"):
		return &TrackEvent{ev}
	case js.Global.Get("TransitionEvent"):
		return &TransitionEvent{ev}
	case js.Global.Get("UIEvent"):
		return &UIEvent{ev}
	case js.Global.Get("UserProximityEvent"):
		return &UserProximityEvent{ev}
	case js.Global.Get("WheelEvent"):
		return &WheelEvent{BasicEvent: ev}
	default:
		return ev
	}
}

const (
	EvPhaseNone      = 0
	EvPhaseCapturing = 1
	EvPhaseAtTarget  = 2
	EvPhaseBubbling  = 3
)

type Event interface {
	Bubbles() bool
	Cancelable() bool
	CurrentTarget() Element
	DefaultPrevented() bool
	EventPhase() int
	Target() Element
	Timestamp() time.Time
	Type() string
	PreventDefault()
	StopImmediatePropagation()
	StopPropagation()
}

// Type BasicEvent implements the Event interface and is embedded by
// concrete event types.
type BasicEvent struct{ js.Object }

func (ev *BasicEvent) Bubbles() bool {
	return ev.Get("bubbles").Bool()
}

func (ev *BasicEvent) Cancelable() bool {
	return ev.Get("cancelable").Bool()
}

func (ev *BasicEvent) CurrentTarget() Element {
	return wrapElement(ev.Get("currentTarget"))
}

func (ev *BasicEvent) DefaultPrevented() bool {
	return ev.Get("defaultPrevented").Bool()
}

func (ev *BasicEvent) EventPhase() int {
	return ev.Get("eventPhase").Int()
}

func (ev *BasicEvent) Target() Element {
	return wrapElement(ev.Get("target"))
}

func (ev *BasicEvent) Timestamp() time.Time {
	ms := ev.Get("timeStamp").Int()
	s := ms / 1000
	ns := (ms % 1000 * 1e6)
	return time.Unix(int64(s), int64(ns))
}

func (ev *BasicEvent) Type() string {
	return ev.Get("type").Str()
}

func (ev *BasicEvent) PreventDefault() {
	ev.Call("preventDefault")
}

func (ev *BasicEvent) StopImmediatePropagation() {
	ev.Call("stopImmediatePropagation")
}

func (ev *BasicEvent) StopPropagation() {
	ev.Call("stopPropagation")
}

type AnimationEvent struct{ *BasicEvent }
type AudioProcessingEvent struct{ *BasicEvent }
type BeforeInputEvent struct{ *BasicEvent }
type BeforeUnloadEvent struct{ *BasicEvent }
type BlobEvent struct{ *BasicEvent }
type ClipboardEvent struct{ *BasicEvent }

type CloseEvent struct {
	*BasicEvent
	Code     int    `js:"code"`
	Reason   string `js:"reason"`
	WasClean bool   `js:"wasClean"`
}

type CompositionEvent struct{ *BasicEvent }
type CSSFontFaceLoadEvent struct{ *BasicEvent }
type CustomEvent struct{ *BasicEvent }
type DeviceLightEvent struct{ *BasicEvent }
type DeviceMotionEvent struct{ *BasicEvent }
type DeviceOrientationEvent struct{ *BasicEvent }
type DeviceProximityEvent struct{ *BasicEvent }
type DOMTransactionEvent struct{ *BasicEvent }
type DragEvent struct{ *BasicEvent }
type EditingBeforeInputEvent struct{ *BasicEvent }
type ErrorEvent struct{ *BasicEvent }
type FocusEvent struct{ *BasicEvent }
type GamepadEvent struct{ *BasicEvent }
type HashChangeEvent struct{ *BasicEvent }
type IDBVersionChangeEvent struct{ *BasicEvent }

const (
	KeyLocationStandard = 0
	KeyLocationLeft     = 1
	KeyLocationRight    = 2
	KeyLocationNumpad   = 3
)

type KeyboardEvent struct {
	*BasicEvent
	AltKey        bool   `js:"altKey"`
	CharCode      int    `js:"charCode"`
	CtrlKey       bool   `js:"ctrlKey"`
	Key           string `js:"key"`
	KeyIdentifier string `js:"keyIdentifier"`
	KeyCode       int    `js:"keyCode"`
	Locale        string `js:"locale"`
	Location      int    `js:"location"`
	KeyLocation   int    `js:"keyLocation"`
	MetaKey       bool   `js:"metaKey"`
	Repeat        bool   `js:"repeat"`
	ShiftKey      bool   `js:"shiftKey"`
}

func (ev *KeyboardEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MediaStreamEvent struct{ *BasicEvent }

type MessageEvent struct {
	*BasicEvent
	Data js.Object `js:"data"`
}

type MouseEvent struct {
	*UIEvent
	AltKey    bool `js:"altKey"`
	Button    int  `js:"button"`
	ClientX   int  `js:"clientX"`
	ClientY   int  `js:"clientY"`
	CtrlKey   bool `js:"ctrlKey"`
	MetaKey   bool `js:"metaKey"`
	MovementX int  `js:"movementX"`
	MovementY int  `js:"movementY"`
	ScreenX   int  `js:"screenX"`
	ScreenY   int  `js:"screenY"`
	ShiftKey  bool `js:"shiftKey"`
}

func (ev *MouseEvent) RelatedTarget() Element {
	return wrapElement(ev.Get("target"))
}

func (ev *MouseEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MutationEvent struct{ *BasicEvent }
type OfflineAudioCompletionEvent struct{ *BasicEvent }
type PageTransitionEvent struct{ *BasicEvent }
type PointerEvent struct{ *BasicEvent }
type PopStateEvent struct{ *BasicEvent }
type ProgressEvent struct{ *BasicEvent }
type RelatedEvent struct{ *BasicEvent }
type RTCPeerConnectionIceEvent struct{ *BasicEvent }
type SensorEvent struct{ *BasicEvent }
type StorageEvent struct{ *BasicEvent }
type SVGEvent struct{ *BasicEvent }
type SVGZoomEvent struct{ *BasicEvent }
type TimeEvent struct{ *BasicEvent }
type TouchEvent struct{ *BasicEvent }
type TrackEvent struct{ *BasicEvent }
type TransitionEvent struct{ *BasicEvent }
type UIEvent struct{ *BasicEvent }
type UserProximityEvent struct{ *BasicEvent }

const (
	DeltaPixel = 0
	DeltaLine  = 1
	DeltaPage  = 2
)

type WheelEvent struct {
	*BasicEvent
	DeltaX    float64 `js:"deltaX"`
	DeltaY    float64 `js:"deltaY"`
	DeltaZ    float64 `js:"deltaZ"`
	DeltaMode int     `js:"deltaMode"`
}

type EventTarget interface {
	// AddEventListener adds a new event listener and returns the
	// wrapper function it generated. If using RemoveEventListener,
	// that wrapper has to be used.
	AddEventListener(typ string, useCapture bool, listener func(Event)) func(js.Object)
	RemoveEventListener(typ string, useCapture bool, listener func(js.Object))
	// DispatchEvent() // TODO
}
<|endoftext|>


<commit_before>package expect

import (
	"testing"
)

type Expect struct {
	To  *To
	Not *not
}

type not struct {
	To *To
}

func New(t *testing.T) func(v interface{}) *Expect {
	return func(v interface{}) *Expect {
		// Be, Not.Be
		var be, nbe Be
		be = Be{t, &be, v, true}
		nbe = Be{t, &nbe, v, false}
		// Have, Not.Have
		var have, nhave Have
		have = Have{t, &have, v, true}
		nhave = Have{t, &nhave, v, false}
		// To, Not.To
		var to, nto To
		to = To{t, &be, &have, &to, v, true}
		nto = To{t, &nbe, &nhave, &nto, v, false}
		return &Expect{
			To:  &to,
			Not: &not{&nto},
		}
	}
}
<commit_msg>docs(expect): *<commit_after>// Minimalistic BDD-style assertions for Go (inspired by expect.js)
package expect

import (
	"testing"
)

type Expect struct {
	To  *To
	Not *not
}

type not struct {
	To *To
}

// Return new expect function with `To, To.Be, To.Have` assertions
func New(t *testing.T) func(v interface{}) *Expect {
	return func(v interface{}) *Expect {
		// Be, Not.Be
		var be, nbe Be
		be = Be{t, &be, v, true}
		nbe = Be{t, &nbe, v, false}
		// Have, Not.Have
		var have, nhave Have
		have = Have{t, &have, v, true}
		nhave = Have{t, &nhave, v, false}
		// To, Not.To
		var to, nto To
		to = To{t, &be, &have, &to, v, true}
		nto = To{t, &nbe, &nhave, &nto, v, false}
		return &Expect{
			To:  &to,
			Not: &not{&nto},
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"

	"github.com/mitchellh/goamz/aws"
	"github.com/mitchellh/goamz/s3"
)

type Album struct {
	Id          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Link        string `json:"link"`
	CoverPhoto  string `json:"cover_photo"`
	Privacy     string `json:"everyone"`
	CreatedTime string `json:"created_time"`
}

func Export(accessToken, bucketName string, finished chan struct{}) error {
	albums := struct {
		Albums []Album `json:"data"`
	}{}

	resp, err := http.Get()
}

func ExportAlbums(accessToken, bucketName string, finished chan struct{}) {
	auth := aws.EnvAuth()
	api := s3.New(auth, aws.USEast)
	bucket := api.Bucket(bucketName)
	//bucket.Put(path, data, "application/json", "public-read")
	// https://graph.facebook.com/v2.2/beatsforboobs/albums?access_token=...
	// https://graph.facebook.com/v2.2/10152035682934317/photos?access_token=...
}
<commit_msg>- moar wip<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"github.com/mitchellh/goamz/aws"
	"github.com/mitchellh/goamz/s3"
)

type Album struct {
	Id          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Link        string `json:"link"`
	CoverPhoto  string `json:"cover_photo"`
	Privacy     string `json:"everyone"`
	CreatedTime string `json:"created_time"`
}

func ExportAlbums(accessToken string) ([]Album, error) {
	albums := struct {
		Albums []Album `json:"data"`
	}{}

	resp, err := http.Get("https://graph.facebook.com/v2.2/beatsforboobs/albums?access_token=" + url.QueryEscape(accessToken))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(albums)
	return albums, err
}

func ExportPhotos(accessToken, albumId string) ([]byte, error) {
	uri := fmt.Sprintf("https://graph.facebook.com/v2.2/%s/photos?access_token%s", albumId, url.QueryEscape(accessToken))
	resp, err := http.Get(uri)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	buffer := bytes.NewBuffer()
	err = io.Copy(buffer, resp.Body)
	return buffer.Bytes(), err
}

func Export(accessToken, bucketName string, finished chan struct{}) {
	albums := ExportAlbums(accessToken)
	for _, albumId := range albums {

	}
	auth := aws.EnvAuth()
	api := s3.New(auth, aws.USEast)
	bucket := api.Bucket(bucketName)
	//bucket.Put(path, data, "application/json", "public-read")
	// https://graph.facebook.com/v2.2/beatsforboobs/albums?access_token=...
	// https://graph.facebook.com/v2.2/10152035682934317/photos?access_token=...
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)

package samples

import (
	"github.com/jacobsa/fuse"
	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcsfuse/timeutil"
	"golang.org/x/net/context"
)

// A file system with a fixed structure that looks like this:
//
//     hello
//     dir/
//         world
//
// Each file contains the string "Hello, world!".
type HelloFS struct {
	fuseutil.NotImplementedFileSystem
	Clock timeutil.Clock
}

var _ fuse.FileSystem = &HelloFS{}

const (
	rootInode fuse.InodeID = fuse.RootInodeID + iota
	helloInode
	dirInode
	worldInode
)

func (fs *HelloFS) OpenDir(
	ctx context.Context,
	req *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {
	// We always allow opening the root directory.
	if req.Inode == rootInode {
		resp = &fuse.OpenDirResponse{}
		return
	}

	// TODO(jacobsa): Handle others.
	err = fuse.ENOSYS
	return
}

// We have a fixed directory structure.
var gDirectoryEntries = map[fuse.InodeID][]fuseutil.Dirent{
	// root
	rootInode: []fuseutil.Dirent{
		fuseutil.Dirent{
			Offset: 1,
			Inode:  helloInode,
			Name:   "hello",
			Type:   fuseutil.DT_File,
		},
		fuseutil.Dirent{
			Offset: 2,
			Inode:  dirInode,
			Name:   "dir",
			Type:   fuseutil.DT_Directory,
		},
	},
}

func (fs *HelloFS) ReadDir(
	ctx context.Context,
	req *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {
	resp = &fuse.ReadDirResponse{}

	// Find the entries for this inode.
	entries, ok := gDirectoryEntries[req.Inode]
	if !ok {
		err = fuse.ENOENT
		return
	}

	// Check the offset.
	if req.Offset >= fuse.DirOffset(len(entries)) {
		err = fuse.EIO
		return
	}

	// Resume at the specified offset into the array.
	for _, e := range entries {
		resp.Data = fuseutil.AppendDirent(resp.Data, e)
		if len(resp.Data) > req.Size {
			resp.Data = resp.Data[:req.Size]
			break
		}
	}

	return
}
<commit_msg>Fixed a bug.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)

package samples

import (
	"github.com/jacobsa/fuse"
	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcsfuse/timeutil"
	"golang.org/x/net/context"
)

// A file system with a fixed structure that looks like this:
//
//     hello
//     dir/
//         world
//
// Each file contains the string "Hello, world!".
type HelloFS struct {
	fuseutil.NotImplementedFileSystem
	Clock timeutil.Clock
}

var _ fuse.FileSystem = &HelloFS{}

const (
	rootInode fuse.InodeID = fuse.RootInodeID + iota
	helloInode
	dirInode
	worldInode
)

func (fs *HelloFS) OpenDir(
	ctx context.Context,
	req *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {
	// We always allow opening the root directory.
	if req.Inode == rootInode {
		resp = &fuse.OpenDirResponse{}
		return
	}

	// TODO(jacobsa): Handle others.
	err = fuse.ENOSYS
	return
}

// We have a fixed directory structure.
var gDirectoryEntries = map[fuse.InodeID][]fuseutil.Dirent{
	// root
	rootInode: []fuseutil.Dirent{
		fuseutil.Dirent{
			Offset: 1,
			Inode:  helloInode,
			Name:   "hello",
			Type:   fuseutil.DT_File,
		},
		fuseutil.Dirent{
			Offset: 2,
			Inode:  dirInode,
			Name:   "dir",
			Type:   fuseutil.DT_Directory,
		},
	},
}

func (fs *HelloFS) ReadDir(
	ctx context.Context,
	req *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {
	resp = &fuse.ReadDirResponse{}

	// Find the entries for this inode.
	entries, ok := gDirectoryEntries[req.Inode]
	if !ok {
		err = fuse.ENOENT
		return
	}

	// Grab the range of interest.
	if req.Offset > fuse.DirOffset(len(entries)) {
		err = fuse.EIO
		return
	}

	entries = entries[req.Offset:]

	// Resume at the specified offset into the array.
	for _, e := range entries {
		resp.Data = fuseutil.AppendDirent(resp.Data, e)
		if len(resp.Data) > req.Size {
			resp.Data = resp.Data[:req.Size]
			break
		}
	}

	return
}
<|endoftext|>


<commit_before>package scale

import (
	"testing"

	nomad "github.com/hashicorp/nomad/api"
	"github.com/jrasell/levant/levant/structs"
)

func TestScale_updateTaskGroup(t *testing.T) {

	sOut := structs.ScalingDirectionOut
	sIn := structs.ScalingDirectionIn
	sCount := structs.ScalingDirectionTypeCount
	sPercent := structs.ScalingDirectionTypePercent

	cases := []struct {
		Config   *structs.ScalingConfig
		Group    *nomad.TaskGroup
		EndCount int
	}{
		{
			buildScalingConfig(sOut, sCount, 100),
			buildTaskGroup(1000),
			1100,
		},
		{
			buildScalingConfig(sOut, sPercent, 25),
			buildTaskGroup(100),
			125,
		},
		{
			buildScalingConfig(sIn, sCount, 900),
			buildTaskGroup(901),
			1,
		},
		{
			buildScalingConfig(sIn, sPercent, 90),
			buildTaskGroup(100),
			10,
		},
	}

	for _, tc := range cases {
		updateTaskGroup(tc.Config, tc.Group)

		if tc.EndCount != *tc.Group.Count {
			t.Fatalf("got: %#v, expected %#v", *tc.Group.Count, tc.EndCount)
		}
	}
}

func TestScale_calculateCountBasedOnPercent(t *testing.T) {

	cases := []struct {
		Count   int
		Percent int
		Output  int
	}{
		{
			100,
			50,
			50,
		},
		{
			3,
			33,
			1,
		},
		{
			3,
			10,
			0,
		},
	}

	for _, tc := range cases {
		output := calculateCountBasedOnPercent(tc.Count, tc.Percent)

		if output != tc.Output {
			t.Fatalf("got: %#v, expected %#v", output, tc.Output)
		}
	}
}

func buildScalingConfig(direction, dType string, number int) *structs.ScalingConfig {

	c := &structs.ScalingConfig{}
	c.Direction = direction
	c.DirectionType = dType

	switch dType {
	case structs.ScalingDirectionTypeCount:
		c.Count = number
	case structs.ScalingDirectionTypePercent:
		c.Percent = number
	}

	return c
}

func buildTaskGroup(count int) *nomad.TaskGroup {

	n := "LevantTest"
	c := count

	t := &nomad.TaskGroup{}
	t.Name = &n
	t.Count = &c

	return t
}
<commit_msg>Also commit scale_test.go fixes based on previous commit.<commit_after>package scale

import (
	"testing"

	nomad "github.com/hashicorp/nomad/api"
	"github.com/jrasell/levant/levant/structs"
)

func TestScale_updateTaskGroup(t *testing.T) {

	sOut := structs.ScalingDirectionOut
	sIn := structs.ScalingDirectionIn
	sCount := structs.ScalingDirectionTypeCount
	sPercent := structs.ScalingDirectionTypePercent

	cases := []struct {
		Config   *Config
		Group    *nomad.TaskGroup
		EndCount int
	}{
		{
			buildScalingConfig(sOut, sCount, 100),
			buildTaskGroup(1000),
			1100,
		},
		{
			buildScalingConfig(sOut, sPercent, 25),
			buildTaskGroup(100),
			125,
		},
		{
			buildScalingConfig(sIn, sCount, 900),
			buildTaskGroup(901),
			1,
		},
		{
			buildScalingConfig(sIn, sPercent, 90),
			buildTaskGroup(100),
			10,
		},
	}

	for _, tc := range cases {
		updateTaskGroup(tc.Config, tc.Group)

		if tc.EndCount != *tc.Group.Count {
			t.Fatalf("got: %#v, expected %#v", *tc.Group.Count, tc.EndCount)
		}
	}
}

func TestScale_calculateCountBasedOnPercent(t *testing.T) {

	cases := []struct {
		Count   int
		Percent int
		Output  int
	}{
		{
			100,
			50,
			50,
		},
		{
			3,
			33,
			1,
		},
		{
			3,
			10,
			0,
		},
	}

	for _, tc := range cases {
		output := calculateCountBasedOnPercent(tc.Count, tc.Percent)

		if output != tc.Output {
			t.Fatalf("got: %#v, expected %#v", output, tc.Output)
		}
	}
}

func buildScalingConfig(direction, dType string, number int) *Config {

	c := &Config{
		Scale: &structs.ScaleConfig{
			Direction:     direction,
			DirectionType: dType,
		},
	}

	switch dType {
	case structs.ScalingDirectionTypeCount:
		c.Scale.Count = number
	case structs.ScalingDirectionTypePercent:
		c.Scale.Percent = number
	}

	return c
}

func buildTaskGroup(count int) *nomad.TaskGroup {

	n := "LevantTest"
	c := count

	t := &nomad.TaskGroup{
		Name:  &n,
		Count: &c,
	}

	return t
}
<|endoftext|>


<commit_before>package filler

import (
	"reflect"
	"strings"
)

const (
	tagName   = "fill"
	ignoreTag = "-"
	emptyTag  = ""
)

var fillers []Filler

type Filler struct {
	// Tag is the prefix inside fill tag ie. "fill:mytag"
	Tag string
	// Fn function to call - helps us to fill the gaps
	Fn func(obj interface{}) (interface{}, error)
}

// RegFiller - register new filler into []fillers
func RegFiller(f Filler) {
	fillers = append(fillers, f)
}

// Fill - fill the object with all the current fillers
func Fill(obj interface{}) {
	v := reflect.TypeOf(obj).Elem()
	s := reflect.ValueOf(obj).Elem()
	for i := 0; i < v.NumField(); i++ {
		tag := v.Field(i).Tag.Get(tagName)
		if tag == emptyTag || tag == ignoreTag {
			continue
		}
		t, elm := parseTag(tag)
		for _, filter := range fillers {
			var elmValue interface{} = nil
			if filter.Tag == t {
				if elm != "" {
					elmValue = s.FieldByName(elm).Interface()
				}
				res, err := filter.Fn(elmValue)
				if err != nil {
					continue
				}
				s.FieldByName(v.Field(i).Name).Set(reflect.ValueOf(res))
			}
		}
	}
}

// parseTag split the string by ":" and return two strings
func parseTag(tag string) (string, string) {
	x := strings.Split(tag, ":")
	if len(x) != 2 {
		return x[0], ""
	}
	return x[0], x[1]
}
<commit_msg>can set ?<commit_after>package filler

import (
	"reflect"
	"strings"
)

const (
	tagName   = "fill"
	ignoreTag = "-"
	emptyTag  = ""
)

var fillers []Filler

type Filler struct {
	// Tag is the prefix inside fill tag ie. "fill:mytag"
	Tag string
	// Fn function to call - helps us to fill the gaps
	Fn func(obj interface{}) (interface{}, error)
}

// RegFiller - register new filler into []fillers
func RegFiller(f Filler) {
	fillers = append(fillers, f)
}

// Fill - fill the object with all the current fillers
func Fill(obj interface{}) {
	v := reflect.TypeOf(obj).Elem()
	s := reflect.ValueOf(obj).Elem()
	for i := 0; i < v.NumField(); i++ {
		currentField := v.Field(i)
		tag := currentField.Tag.Get(tagName)
		if tag == emptyTag || tag == ignoreTag {
			continue
		}
		t, elm := parseTag(tag)
		for _, filter := range fillers {
			var elmValue interface{} = nil
			if filter.Tag == t {
				if elm != "" {
					elmValue = s.FieldByName(elm).Interface()
				}
				res, err := filter.Fn(elmValue)
				if err != nil {
					continue
				}
				if s.FieldByName(currentField.Name).CanSet(){
					s.FieldByName(currentField.Name).Set(reflect.ValueOf(res))
				}
			}
		}
	}
}

// parseTag split the string by ":" and return two strings
func parseTag(tag string) (string, string) {
	x := strings.Split(tag, ":")
	if len(x) != 2 {
		return x[0], ""
	}
	return x[0], x[1]
}
<|endoftext|>