<commit_before>package dukedb

import (
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/theduke/go-apperror"
)

type BackendQueryMixin interface {
	GetBackend() Backend
	SetBackend(Backend)

	Find(targetSlice ...interface{}) ([]interface{}, apperror.Error)
	First(targetModel ...interface{}) (interface{}, apperror.Error)
	Last(targetModel ...interface{}) (interface{}, apperror.Error)
	Count() (int, apperror.Error)
	Delete() apperror.Error
}

type Query interface {
	BackendQueryMixin

	GetCollection() string

	GetName() string
	SetName(name string)

	Limit(int) Query
	GetLimit() int

	Offset(int) Query
	GetOffset() int

	Fields(...string) Query
	AddFields(...string) Query
	LimitFields(...string) Query
	GetFields() []string

	Order(name string, asc bool) Query
	SetOrders(...OrderSpec) Query
	GetOrders() []OrderSpec

	// Filters.

	FilterQ(...Filter) Query
	Filter(field string, val interface{}) Query
	FilterCond(field string, condition string, val interface{}) Query

	AndQ(filters ...Filter) Query
	And(field string, val interface{}) Query
	AndCond(field, condition string, val interface{}) Query

	OrQ(filters ...Filter) Query
	Or(field string, val interface{}) Query
	OrCond(field string, condition string, val interface{}) Query

	NotQ(...Filter) Query
	Not(field string, val interface{}) Query
	NotCond(field string, condition string, val interface{}) Query

	GetFilters() []Filter
	SetFilters(f ...Filter) Query

	// Joins.

	JoinQ(jq ...RelationQuery) Query
	Join(fieldName string) Query
	GetJoin(field string) RelationQuery
	GetJoins() []RelationQuery

	// GetJoinType specifies the type of join that is fullfilled by this query.
	GetJoinType() string

	// SetJoinType sets the type of join that is fullfilled by this query.
	SetJoinType(typ string)

	// Can return a function that takes care of assigning join results.
	GetJoinResultAssigner() JoinAssigner

	// Specify a function that takes care of assigning join results.
	// Needed for example in the sql backend for M2M joins.
	SetJoinResultAssigner(assigner JoinAssigner)

	// Related.

	Related(name string) RelationQuery
	RelatedCustom(name, collection, joinKey, foreignKey, typ string) RelationQuery
}

type RelationQuery interface {
	// RelationQuery specific methods.

	GetCollection() string

	GetName() string
	SetName(name string)

	GetBaseQuery() Query
	SetBaseQuery(Query)

	GetRelationName() string
	SetRelationName(name string)

	GetJoinType() string

	GetJoinFieldName() string
	SetJoinFieldName(string)

	GetForeignFieldName() string
	SetForeignFieldName(string)

	Build() (Query, apperror.Error)

	// BackendQuery methods.
	BackendQueryMixin

	Limit(int) RelationQuery
	GetLimit() int

	Offset(int) RelationQuery
	GetOffset() int

	Fields(...string) RelationQuery
	AddFields(...string) RelationQuery
	LimitFields(...string) RelationQuery
	GetFields() []string

	Order(name string, asc bool) RelationQuery
	SetOrders(...OrderSpec) RelationQuery
	GetOrders() []OrderSpec

	// Filters.

	FilterQ(...Filter) RelationQuery
	Filter(field string, val interface{}) RelationQuery
	FilterCond(field string, condition string, val interface{}) RelationQuery

	AndQ(filters ...Filter) RelationQuery
	And(field string, val interface{}) RelationQuery
	AndCond(field, condition string, val interface{}) RelationQuery

	OrQ(filters ...Filter) RelationQuery
	Or(field string, val interface{}) RelationQuery
	OrCond(field string, condition string, val interface{}) RelationQuery

	NotQ(...Filter) RelationQuery
	Not(field string, val interface{}) RelationQuery
	NotCond(field string, condition string, val interface{}) RelationQuery

	GetFilters() []Filter
	SetFilters(f ...Filter) RelationQuery

	// Joins.

	JoinQ(jq ...RelationQuery) RelationQuery
	Join(fieldName string) RelationQuery
	GetJoin(field string) RelationQuery
	GetJoins() []RelationQuery

	// Related.

	Related(name string) RelationQuery
	RelatedCustom(name, collection, joinKey, foreignKey, typ string) RelationQuery
}

type Backend interface {
	// Returns the name of the backend.
	Name() string
	SetName(name string)

	// Returns true if the backend uses string IDs like MongoDB.
	HasStringIDs() bool

	GetDebug() bool
	SetDebug(bool)

	GetLogger() *logrus.Logger
	SetLogger(*logrus.Logger)

	// Duplicate the backend.
	Copy() Backend

	// Register a model type.
	RegisterModel(model interface{})

	// Get the model info for a collection.
	ModelInfo(collection string) *ModelInfo

	// Retrieve the ModelInfo for a model.
	InfoForModel(model interface{}) (*ModelInfo, apperror.Error)
	InfoForCollection(collection string) (*ModelInfo, apperror.Error)

	SetModelInfo(collection string, info *ModelInfo)

	// Get model info for all registered collections.
	AllModelInfo() map[string]*ModelInfo
	SetAllModelInfo(map[string]*ModelInfo)

	// Determine if a model collection is registered with the backend.
	HasCollection(collection string) bool

	ModelToMap(model interface{}, marshal bool, includeRelations bool) (map[string]interface{}, apperror.Error)

	// After all models have been registered, build the relationship
	// info.
	BuildRelationshipInfo()

	// Get a new struct instance to a model struct based on model Collection.
	CreateModel(collection string) (interface{}, apperror.Error)

	// Same as CreateModel(), but panics on error.
	MustCreateModel(collection string) interface{}

	// "Merge" a model that implements Model interface by setting backend and info data.
	MergeModel(model Model)

	// Build a slice of a model for model Collection.
	CreateModelSlice(collection string) (interface{}, apperror.Error)

	// Determine the ID for a model.
	ModelID(model interface{}) (interface{}, apperror.Error)

	// Determine the ID for a model, and panic on error.
	MustModelID(model interface{}) interface{}

	// Set the id field on a model.
	SetModelID(model interface{}, id interface{}) apperror.Error

	// Set the id  field on a model and panic on error.
	MustSetModelID(model interface{}, id interface{})

	// Determine the  ID for a model and convert it to string.
	ModelStrID(model interface{}) (string, apperror.Error)

	// Determine the  ID for a model and convert it to string. Panics on error.
	MustModelStrID(model interface{}) string

	// Create the specified collection in the backend.
	// (eg the table or the mongo collection)
	CreateCollection(collection string) apperror.Error
	CreateCollections(collection ...string) apperror.Error
	DropCollection(collection string) apperror.Error
	DropAllCollections() apperror.Error

	// Create a new query for a collection.
	Q(collection string) Query

	// Perform a query.
	Query(q Query, targetSlice ...interface{}) ([]interface{}, apperror.Error)

	// Perform a query and get the first result.
	QueryOne(q Query, targetModel ...interface{}) (interface{}, apperror.Error)

	// Perform a query and get the last result.
	Last(q Query, targetModel ...interface{}) (interface{}, apperror.Error)

	// Find first model with primary key ID.
	FindBy(collection, field string, value interface{}, targetSlice ...interface{}) ([]interface{}, apperror.Error)

	// Find a model in a collection by ID.
	FindOne(collection string, id interface{}, targetModel ...interface{}) (interface{}, apperror.Error)

	// Find a model  in a collection based on a field value.
	FindOneBy(collection, field string, value interface{}, targetModel ...interface{}) (interface{}, apperror.Error)

	// Count by a query.
	Count(Query) (int, apperror.Error)

	// Based on a RelationQuery, return a query for the specified
	// relation.
	// The third skip parameter is true when the base query does not contain any results.
	BuildRelationQuery(q RelationQuery) (Query, apperror.Error)

	// Retrieve a query for a relationship.
	Related(model interface{}, name string) (RelationQuery, apperror.Error)

	// Return a M2MCollection instance for a model, which allows
	// to add/remove/clear items in the m2m relationship.
	M2M(model interface{}, name string) (M2MCollection, apperror.Error)

	// Convenience methods.

	Create(model interface{}) apperror.Error
	Update(model interface{}) apperror.Error
	Save(model interface{}) apperror.Error
	UpdateByMap(model interface{}, data map[string]interface{}) apperror.Error
	Delete(model interface{}) apperror.Error
	DeleteMany(Query) apperror.Error

	// Hooks.

	// RegisterHook registers a hook function that will be called for a model.
	// The available hooks are: (before/after)_(create/update/delete).
	RegisterHook(hook string, handler HookHandler)

	// GetHooks returns a slice with all hooks of the hook type.
	GetHooks(hook string) []HookHandler
}

type HookHandler func(backend Backend, obj interface{}) apperror.Error

type M2MCollection interface {
	Add(models ...interface{}) apperror.Error
	Delete(models ...interface{}) apperror.Error
	Clear() apperror.Error
	Replace(models []interface{}) apperror.Error

	Count() int
	Contains(model interface{}) bool
	ContainsID(id interface{}) bool
	GetByID(id interface{}) interface{}
	All() []interface{}
}

type Transaction interface {
	Backend
	Rollback() apperror.Error
	Commit() apperror.Error
}

type TransactionBackend interface {
	Backend
	Begin() Transaction
}

type MigrationAttempt interface {
	GetVersion() int
	SetVersion(int)

	GetStartedAt() time.Time
	SetStartedAt(time.Time)

	GetFinishedAt() time.Time
	SetFinishedAt(time.Time)

	GetComplete() bool
	SetComplete(bool)
}

type MigrationBackend interface {
	Backend
	GetMigrationHandler() *MigrationHandler

	MigrationsSetup() apperror.Error

	IsMigrationLocked() (bool, apperror.Error)
	DetermineMigrationVersion() (int, apperror.Error)

	NewMigrationAttempt() MigrationAttempt
}

type Model interface {
	ModelCollectionHook
	ModelBackendNameHook
	ModelIDGetterHook
	ModelIDSetterHook
	ModelStrIDGetterHook
	ModelStrIDSetterHook

	Info() *ModelInfo
	SetInfo(info *ModelInfo)

	Backend() Backend
	SetBackend(backend Backend)
}

type ModelCollectionHook interface {
	Collection() string
}

type ModelBackendNameHook interface {
	BackendName() string
}

type ModelIDGetterHook interface {
	GetID() interface{}
}

type ModelIDSetterHook interface {
	SetID(id interface{}) error
}

type ModelStrIDGetterHook interface {
	GetStrID() string
}

type ModelStrIDSetterHook interface {
	SetStrID(id string) error
}

type ModelValidateHook interface {
	Validate() error
}

type ModelBeforeCreateHook interface {
	BeforeCreate(Backend) error
}

type ModelAfterCreateHook interface {
	AfterCreate(Backend)
}

type ModelBeforeUpdateHook interface {
	BeforeUpdate(Backend) error
}

type ModelAfterUpdateHook interface {
	AfterUpdate(Backend)
}

type ModelBeforeDeleteHook interface {
	BeforeDelete(Backend) error
}

type ModelAfterDeleteHook interface {
	AfterDelete(Backend)
}

type ModelAfterQueryHook interface {
	AfterQuery(Backend)
}
<commit_msg>Started rewrite of query/statement system<commit_after>package dukedb

import (
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/theduke/go-apperror"
)

type BackendQueryMixin interface {
	GetBackend() Backend
	SetBackend(Backend)

	Find(targetSlice ...interface{}) ([]interface{}, apperror.Error)
	First(targetModel ...interface{}) (interface{}, apperror.Error)
	Last(targetModel ...interface{}) (interface{}, apperror.Error)
	Count() (int, apperror.Error)
	Delete() apperror.Error
}

type Query interface {
	BackendQueryMixin

	GetStatement() *SelectStatement

	GetCollection() string

	GetName() string
	SetName(name string)

	Limit(int) Query
	GetLimit() int

	Offset(int) Query
	GetOffset() int

	Field(fields ...string) Query
	FieldExpr(expressions ...Expression) Query
	SetFields(fields []string) Query
	SetFieldExpressions(expressions []Expression) Query
	LimitFields(fields ...string) Query

	Sort(field string, asc bool) Query
	SortExpr(expressions ...SortExpression)
	SetSorts(sorts []SortExpression) Query

	// Filters.

	FilterQ(...Filter) Query
	Filter(field string, val interface{}) Query
	FilterCond(field string, condition string, val interface{}) Query

	AndQ(filters ...Filter) Query
	And(field string, val interface{}) Query
	AndCond(field, condition string, val interface{}) Query

	OrQ(filters ...Filter) Query
	Or(field string, val interface{}) Query
	OrCond(field string, condition string, val interface{}) Query

	NotQ(...Filter) Query
	Not(field string, val interface{}) Query
	NotCond(field string, condition string, val interface{}) Query

	GetFilters() []Filter
	SetFilters(f ...Filter) Query

	// Joins.

	JoinQ(jq ...RelationQuery) Query
	Join(fieldName string) Query
	GetJoin(field string) RelationQuery
	GetJoins() []RelationQuery

	// GetJoinType specifies the type of join that is fullfilled by this query.
	GetJoinType() string

	// SetJoinType sets the type of join that is fullfilled by this query.
	SetJoinType(typ string)

	// Can return a function that takes care of assigning join results.
	GetJoinResultAssigner() JoinAssigner

	// Specify a function that takes care of assigning join results.
	// Needed for example in the sql backend for M2M joins.
	SetJoinResultAssigner(assigner JoinAssigner)

	// Related.

	Related(name string) RelationQuery
	RelatedCustom(name, collection, joinKey, foreignKey, typ string) RelationQuery
}

type RelationQuery interface {
	// RelationQuery specific methods.

	GetStatement() *JoinStatement

	GetCollection() string

	GetName() string
	SetName(name string)

	GetBaseQuery() Query
	SetBaseQuery(Query)

	GetRelationName() string
	SetRelationName(name string)

	GetJoinType() string

	Build() (Query, apperror.Error)

	// BackendQuery methods.
	BackendQueryMixin

	Limit(int) RelationQuery
	GetLimit() int

	Offset(int) RelationQuery
	GetOffset() int

	Fields(...string) RelationQuery
	AddFields(...string) RelationQuery
	LimitFields(...string) RelationQuery
	GetFields() []string

	Order(name string, asc bool) RelationQuery
	SetOrders(...OrderSpec) RelationQuery
	GetOrders() []OrderSpec

	// Filters.

	FilterQ(...Filter) RelationQuery
	Filter(field string, val interface{}) RelationQuery
	FilterCond(field string, condition string, val interface{}) RelationQuery

	AndQ(filters ...Filter) RelationQuery
	And(field string, val interface{}) RelationQuery
	AndCond(field, condition string, val interface{}) RelationQuery

	OrQ(filters ...Filter) RelationQuery
	Or(field string, val interface{}) RelationQuery
	OrCond(field string, condition string, val interface{}) RelationQuery

	NotQ(...Filter) RelationQuery
	Not(field string, val interface{}) RelationQuery
	NotCond(field string, condition string, val interface{}) RelationQuery

	GetFilters() []Filter
	SetFilters(f ...Filter) RelationQuery

	// Joins.

	JoinQ(jq ...RelationQuery) RelationQuery
	Join(fieldName string) RelationQuery
	GetJoin(field string) RelationQuery
	GetJoins() []RelationQuery

	// Related.

	Related(name string) RelationQuery
	RelatedCustom(name, collection, joinKey, foreignKey, typ string) RelationQuery
}

type Backend interface {
	// Returns the name of the backend.
	Name() string
	SetName(name string)

	// Returns true if the backend uses string IDs like MongoDB.
	HasStringIDs() bool

	GetDebug() bool
	SetDebug(bool)

	GetLogger() *logrus.Logger
	SetLogger(*logrus.Logger)

	// Duplicate the backend.
	Copy() Backend

	// Register a model type.
	RegisterModel(model interface{})

	// Get the model info for a collection.
	ModelInfo(collection string) *ModelInfo

	// Retrieve the ModelInfo for a model.
	InfoForModel(model interface{}) (*ModelInfo, apperror.Error)
	InfoForCollection(collection string) (*ModelInfo, apperror.Error)

	SetModelInfo(collection string, info *ModelInfo)

	// Get model info for all registered collections.
	AllModelInfo() map[string]*ModelInfo
	SetAllModelInfo(map[string]*ModelInfo)

	// Determine if a model collection is registered with the backend.
	HasCollection(collection string) bool

	ModelToMap(model interface{}, marshal bool, includeRelations bool) (map[string]interface{}, apperror.Error)

	// After all models have been registered, build the relationship
	// info.
	BuildRelationshipInfo()

	// Get a new struct instance to a model struct based on model Collection.
	CreateModel(collection string) (interface{}, apperror.Error)

	// Same as CreateModel(), but panics on error.
	MustCreateModel(collection string) interface{}

	// "Merge" a model that implements Model interface by setting backend and info data.
	MergeModel(model Model)

	// Build a slice of a model for model Collection.
	CreateModelSlice(collection string) (interface{}, apperror.Error)

	// Determine the ID for a model.
	ModelID(model interface{}) (interface{}, apperror.Error)

	// Determine the ID for a model, and panic on error.
	MustModelID(model interface{}) interface{}

	// Set the id field on a model.
	SetModelID(model interface{}, id interface{}) apperror.Error

	// Set the id  field on a model and panic on error.
	MustSetModelID(model interface{}, id interface{})

	// Determine the  ID for a model and convert it to string.
	ModelStrID(model interface{}) (string, apperror.Error)

	// Determine the  ID for a model and convert it to string. Panics on error.
	MustModelStrID(model interface{}) string

	// Create the specified collection in the backend.
	// (eg the table or the mongo collection)
	CreateCollection(collection string) apperror.Error
	CreateCollections(collection ...string) apperror.Error
	DropCollection(collection string) apperror.Error
	DropAllCollections() apperror.Error

	// Create a new query for a collection.
	Q(collection string) Query

	// Perform a query.
	Query(q Query, targetSlice ...interface{}) ([]interface{}, apperror.Error)

	// Perform a query and get the first result.
	QueryOne(q Query, targetModel ...interface{}) (interface{}, apperror.Error)

	// Perform a query and get the last result.
	Last(q Query, targetModel ...interface{}) (interface{}, apperror.Error)

	// Find first model with primary key ID.
	FindBy(collection, field string, value interface{}, targetSlice ...interface{}) ([]interface{}, apperror.Error)

	// Find a model in a collection by ID.
	FindOne(collection string, id interface{}, targetModel ...interface{}) (interface{}, apperror.Error)

	// Find a model  in a collection based on a field value.
	FindOneBy(collection, field string, value interface{}, targetModel ...interface{}) (interface{}, apperror.Error)

	// Count by a query.
	Count(Query) (int, apperror.Error)

	// Based on a RelationQuery, return a query for the specified
	// relation.
	// The third skip parameter is true when the base query does not contain any results.
	BuildRelationQuery(q RelationQuery) (Query, apperror.Error)

	// Retrieve a query for a relationship.
	Related(model interface{}, name string) (RelationQuery, apperror.Error)

	// Return a M2MCollection instance for a model, which allows
	// to add/remove/clear items in the m2m relationship.
	M2M(model interface{}, name string) (M2MCollection, apperror.Error)

	// Convenience methods.

	Create(model interface{}) apperror.Error
	Update(model interface{}) apperror.Error
	Save(model interface{}) apperror.Error
	UpdateByMap(model interface{}, data map[string]interface{}) apperror.Error
	Delete(model interface{}) apperror.Error
	DeleteQ(Query) apperror.Error

	// Hooks.

	// RegisterHook registers a hook function that will be called for a model.
	// The available hooks are: (before/after)_(create/update/delete).
	RegisterHook(hook string, handler HookHandler)

	// GetHooks returns a slice with all hooks of the hook type.
	GetHooks(hook string) []HookHandler
}

type HookHandler func(backend Backend, obj interface{}) apperror.Error

type M2MCollection interface {
	Add(models ...interface{}) apperror.Error
	Delete(models ...interface{}) apperror.Error
	Clear() apperror.Error
	Replace(models []interface{}) apperror.Error

	Count() int
	Contains(model interface{}) bool
	ContainsID(id interface{}) bool
	GetByID(id interface{}) interface{}
	All() []interface{}
}

type Transaction interface {
	Backend
	Rollback() apperror.Error
	Commit() apperror.Error
}

type TransactionBackend interface {
	Backend
	Begin() Transaction
}

type MigrationAttempt interface {
	GetVersion() int
	SetVersion(int)

	GetStartedAt() time.Time
	SetStartedAt(time.Time)

	GetFinishedAt() time.Time
	SetFinishedAt(time.Time)

	GetComplete() bool
	SetComplete(bool)
}

type MigrationBackend interface {
	Backend
	GetMigrationHandler() *MigrationHandler

	MigrationsSetup() apperror.Error

	IsMigrationLocked() (bool, apperror.Error)
	DetermineMigrationVersion() (int, apperror.Error)

	NewMigrationAttempt() MigrationAttempt
}

type Model interface {
	ModelCollectionHook
	ModelBackendNameHook
	ModelIDGetterHook
	ModelIDSetterHook
	ModelStrIDGetterHook
	ModelStrIDSetterHook

	Info() *ModelInfo
	SetInfo(info *ModelInfo)

	Backend() Backend
	SetBackend(backend Backend)
}

type ModelCollectionHook interface {
	Collection() string
}

type ModelBackendNameHook interface {
	BackendName() string
}

type ModelIDGetterHook interface {
	GetID() interface{}
}

type ModelIDSetterHook interface {
	SetID(id interface{}) error
}

type ModelStrIDGetterHook interface {
	GetStrID() string
}

type ModelStrIDSetterHook interface {
	SetStrID(id string) error
}

type ModelValidateHook interface {
	Validate() error
}

type ModelBeforeCreateHook interface {
	BeforeCreate(Backend) error
}

type ModelAfterCreateHook interface {
	AfterCreate(Backend)
}

type ModelBeforeUpdateHook interface {
	BeforeUpdate(Backend) error
}

type ModelAfterUpdateHook interface {
	AfterUpdate(Backend)
}

type ModelBeforeDeleteHook interface {
	BeforeDelete(Backend) error
}

type ModelAfterDeleteHook interface {
	AfterDelete(Backend)
}

type ModelAfterQueryHook interface {
	AfterQuery(Backend)
}
<|endoftext|>


<commit_before>package main

type Encrypter interface {
	Encrypt([]byte) ([]byte, error)
}

type Decrypter interface {
	Decrypt([]byte) ([]byte, error)
}

type SymmetricEncrypter interface {
	Encrypter
}

type SymmetricDecrypter interface {
	Decrypter
}

type AsymmetricEncrypter interface {
	Encrypter
}

type AsymmetricDecrypter interface {
	Decrypter
}
<commit_msg>Document interfaces<commit_after>package main

// Encrypter is the interface that wraps the basic Encrypt method
//
// Encrypt reads up plain data bytes contained in pd, encrypts
// them and returns the resulting bytes as well as any potential errors.
//
// Implementations of Encrypter are let free to implement their own
// Symmetric/Asymmetric algorithm needs management (public/private keys,
// passphrase, etc...).
// For a real-world implementation example, please refer to
// serrure.openpgp.OpenPGPEncrypter or serrure.aes.AES256Encrypter.
type Encrypter interface {
	Encrypt(pd []byte) (ed []byte, err error)
}

// Decrypter is the interface that wraps the basice Decrypt method
//
// Decrypts reads up the encrypted data bytes from ed,
// decrypts them and returns the resulting plain data bytes as well
// as any potential errors.
//
// Implementations of Decrypter are let free to implement their own
// Symmetric/Asymmetric algorithm needs management (public/private keys,
// passphrase, etc...)
// For a real-world implementation example, please refer to
// serrure.openpgp OpenPGPDecrypter or serrure.aes.AES256Decrypter.
type Decrypter interface {
	Decrypt(ed []byte) (pd []byte, err error)
}
<|endoftext|>


<commit_before><commit_msg>Fetch data from Yahoo finance API<commit_after>package main

import (
    "fmt"
	"strconv"
	"log"
	"bufio"
    //"net/url"
	"net/http"
	"os"
	"io/ioutil"
	//"encoding/json"
	"github.com/jeffail/gabs"
	//"github.com/wenxiang/go-nestedjson"
	"strings"
)

func main() {

	var closingValue float64

	// Read stock symbols from a file
	symbolFile, err := os.Open("symbols.txt")
	if err != nil {
        log.Fatal(err)
	}
	defer symbolFile.Close()

	scanner := bufio.NewScanner(symbolFile)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

	// Yahoo historic data YQL formats
	// https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22aapl%22%20and%20startDate%20%3D%20%222014-10-10%22%20and%20endDate%20%3D%20%222014-10-10%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=
	// https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.historicaldata where symbol = "aapl" and startDate = "2014-10-10" and endDate = "2014-10-10"&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=
	// https://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+yahoo.finance.historicaldata+where+symbol+%3D+%22aapl%22+and+startDate+%3D+%222014-10-10%22+and+endDate+%3D+%222014-10-10%22
	// select * from yahoo.finance.historicaldata where symbol = "aapl" and startDate = "2014-10-10" and endDate = "2014-10-10"

	// Initialize the URL
	baserurl := "https://query.yahooapis.com/v1/public/yql?"
	var param map[string]string
	param = make(map[string]string)
	param["q"] = "select * from yahoo.finance.historicaldata where symbol = \"aapl\" and startDate = \"2014-10-10\" and endDate = \"2014-10-10\""
	param["format"] = "json"
	param["diagnostics"] = "true"
	param["env"] = "store://datatables.org/alltableswithkeys"
	param["callback"] = ""

	finalURL := baserurl + "q=" + yahooURL(param["q"]) + "&format=" + param["format"] + "&diagnostics=" + param["diagnostics"] + "&env=" + yahooURL(param["env"]) + "&callback=" + param["callback"]

	// Make a GET request to Yahoo get the results
    response, err := http.Get(finalURL)
    if err != nil {
        log.Fatal(err)
    } else {
        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        if err != nil {
            log.Fatal(err)
        }

		// Parse the JSON data received from Yahoo
		jsonParsed, err := gabs.ParseJSON([]byte(contents))

		//closingValue = jsonParsed.Search("query", "results", "quote", "Close").Data().(float64)
		//fmt.Printf("%s\n", jsonParsed.Search("query", "results", "quote", "Close").Data().(float64))
		closingValue, err = strconv.ParseFloat(jsonParsed.Search("query", "results", "quote", "Close").Data().(string), 64)
        if err != nil {
            log.Fatal(err)
        }
		fmt.Printf("%s\n", closingValue)
    }
}

// Convert a given url string to a format accepted by Yahoo API
func yahooURL(str string) string {
	// Replacement rules :
	// space => %20
	// = => %3D
	// " => %22
	// : => %3A
	// / => %2F

	str = strings.Replace(str, " ", "%20", -1)
	str = strings.Replace(str, "=", "%3D", -1)
	str = strings.Replace(str, "\"", "%22", -1)
	str = strings.Replace(str, ":", "%3A", -1)
	str = strings.Replace(str, "/", "%2F", -1)

	return str
}<|endoftext|>


<commit_before><commit_msg>Add random stroke example (#2)<commit_after><|endoftext|>


<commit_before>package goarmorapi

import "github.com/pkg/errors"

type Conformance struct {
	Name   string             `json:"name"`
	Server *ConformanceServer `json:"server"`
	API    *ConformanceClient `json:"api"`
}

type ConformanceServer struct {
	Type         string `json:"type"`
	ID           uint64 `json:"id"`
	Version      uint64 `json:"version"`
	Sharded      bool   `json:"sharded,omitempty"`
	ShardsCount  uint64 `json:"shardsCount,omitempty"`
	StartedAt    string `json:"startedAt,omitempty"`
	Architecture string `json:"architecture"`
}

type ConformanceClient struct {
	Version string `json:"version"`
}

func NewConformance(
	apiVersion string,
	infrastructureVersion uint64,
	serverTitle, serverName, serverArchitecture string,
	serverID uint64,
	shardsCount int,
	startedAt string) (*Conformance, error) {
	if shardsCount < 0 {
		return nil, errors.New("unexpected shard servers count")
	}

	v := &Conformance{
		Name: serverTitle,
		API:  &ConformanceClient{Version: apiVersion},
		Server: &ConformanceServer{
			Type:         serverName,
			ID:           serverID,
			Version:      infrastructureVersion,
			Sharded:      shardsCount > 0,
			ShardsCount:  uint64(shardsCount),
			Architecture: serverArchitecture,
			StartedAt:    startedAt}}

	return v, nil
}
<commit_msg>api "conformance" provide release stage name<commit_after>package goarmorapi

import "github.com/pkg/errors"

type Conformance struct {
	Name   string             `json:"name"`
	Server *ConformanceServer `json:"server"`
	API    *ConformanceClient `json:"api"`
}

type ConformanceServer struct {
	Type         string `json:"type"`
	ID           uint64 `json:"id"`
	Version      uint64 `json:"version"`
	ReleaseStage string `json:"releaseStage"`
	Sharded      bool   `json:"sharded,omitempty"`
	ShardsCount  uint64 `json:"shardsCount,omitempty"`
	StartedAt    string `json:"startedAt,omitempty"`
	Architecture string `json:"architecture"`
}

type ConformanceClient struct {
	Version string `json:"version"`
}

func NewConformance(
	apiVersion string,
	infrastructureVersion uint64,
	releaseStageName string,
	serverTitle, serverName, serverArchitecture string,
	serverID uint64,
	shardsCount int,
	startedAt string) (*Conformance, error) {
	if shardsCount < 0 {
		return nil, errors.New("unexpected shard servers count")
	}

	v := &Conformance{
		Name: serverTitle,
		API:  &ConformanceClient{Version: apiVersion},
		Server: &ConformanceServer{
			Type:         serverName,
			ID:           serverID,
			Version:      infrastructureVersion,
			ReleaseStage: releaseStageName,
			Sharded:      shardsCount > 0,
			ShardsCount:  uint64(shardsCount),
			Architecture: serverArchitecture,
			StartedAt:    startedAt}}

	return v, nil
}
<|endoftext|>


<commit_before>// Copyright 2012 The Walk 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 declarative

import (
	"github.com/lxn/walk"
)

type Dialog struct {
	AssignTo         **walk.Dialog
	Name             string
	Enabled          Property
	Visible          Property
	Font             Font
	MinSize          Size
	MaxSize          Size
	ContextMenuItems []MenuItem
	OnKeyDown        walk.KeyEventHandler
	OnKeyPress       walk.KeyEventHandler
	OnKeyUp          walk.KeyEventHandler
	OnMouseDown      walk.MouseEventHandler
	OnMouseMove      walk.MouseEventHandler
	OnMouseUp        walk.MouseEventHandler
	OnSizeChanged    walk.EventHandler
	Title            string
	Size             Size
	DataBinder       DataBinder
	Layout           Layout
	Children         []Widget
	DefaultButton    **walk.PushButton
	CancelButton     **walk.PushButton
}

func (d Dialog) Create(owner walk.RootWidget) error {
	w, err := walk.NewDialog(owner)
	if err != nil {
		return err
	}

	tlwi := topLevelWindowInfo{
		Name:             d.Name,
		Font:             d.Font,
		ToolTipText:      "",
		MinSize:          d.MinSize,
		MaxSize:          d.MaxSize,
		ContextMenuItems: d.ContextMenuItems,
		DataBinder:       d.DataBinder,
		Layout:           d.Layout,
		Children:         d.Children,
		OnKeyDown:        d.OnKeyDown,
		OnKeyPress:       d.OnKeyPress,
		OnKeyUp:          d.OnKeyUp,
		OnMouseDown:      d.OnMouseDown,
		OnMouseMove:      d.OnMouseMove,
		OnMouseUp:        d.OnMouseUp,
		OnSizeChanged:    d.OnSizeChanged,
	}

	var db *walk.DataBinder
	if d.DataBinder.AssignTo == nil {
		d.DataBinder.AssignTo = &db
	}

	builder := NewBuilder(nil)

	return builder.InitWidget(tlwi, w, func() error {
		if err := w.SetTitle(d.Title); err != nil {
			return err
		}

		if err := w.SetSize(d.Size.toW()); err != nil {
			return err
		}

		if d.DefaultButton != nil {
			if err := w.SetDefaultButton(*d.DefaultButton); err != nil {
				return err
			}

			if db := *d.DataBinder.AssignTo; db != nil {
				db.CanSubmitChanged().Attach(func() {
					(*d.DefaultButton).SetEnabled(db.CanSubmit())
				})
			}
		}
		if d.CancelButton != nil {
			if err := w.SetCancelButton(*d.CancelButton); err != nil {
				return err
			}
		}

		if d.AssignTo != nil {
			*d.AssignTo = w
		}

		return nil
	})
}

func (d Dialog) Run(owner walk.RootWidget) (int, error) {
	var w *walk.Dialog

	if d.AssignTo == nil {
		d.AssignTo = &w
	}

	if err := d.Create(owner); err != nil {
		return 0, err
	}

	return (*d.AssignTo).Run(), nil
}
<commit_msg>declarative/Dialog: Add initial SetEnabled call for default button when data-binding<commit_after>// Copyright 2012 The Walk 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 declarative

import (
	"github.com/lxn/walk"
)

type Dialog struct {
	AssignTo         **walk.Dialog
	Name             string
	Enabled          Property
	Visible          Property
	Font             Font
	MinSize          Size
	MaxSize          Size
	ContextMenuItems []MenuItem
	OnKeyDown        walk.KeyEventHandler
	OnKeyPress       walk.KeyEventHandler
	OnKeyUp          walk.KeyEventHandler
	OnMouseDown      walk.MouseEventHandler
	OnMouseMove      walk.MouseEventHandler
	OnMouseUp        walk.MouseEventHandler
	OnSizeChanged    walk.EventHandler
	Title            string
	Size             Size
	DataBinder       DataBinder
	Layout           Layout
	Children         []Widget
	DefaultButton    **walk.PushButton
	CancelButton     **walk.PushButton
}

func (d Dialog) Create(owner walk.RootWidget) error {
	w, err := walk.NewDialog(owner)
	if err != nil {
		return err
	}

	tlwi := topLevelWindowInfo{
		Name:             d.Name,
		Font:             d.Font,
		ToolTipText:      "",
		MinSize:          d.MinSize,
		MaxSize:          d.MaxSize,
		ContextMenuItems: d.ContextMenuItems,
		DataBinder:       d.DataBinder,
		Layout:           d.Layout,
		Children:         d.Children,
		OnKeyDown:        d.OnKeyDown,
		OnKeyPress:       d.OnKeyPress,
		OnKeyUp:          d.OnKeyUp,
		OnMouseDown:      d.OnMouseDown,
		OnMouseMove:      d.OnMouseMove,
		OnMouseUp:        d.OnMouseUp,
		OnSizeChanged:    d.OnSizeChanged,
	}

	var db *walk.DataBinder
	if d.DataBinder.AssignTo == nil {
		d.DataBinder.AssignTo = &db
	}

	builder := NewBuilder(nil)

	return builder.InitWidget(tlwi, w, func() error {
		if err := w.SetTitle(d.Title); err != nil {
			return err
		}

		if err := w.SetSize(d.Size.toW()); err != nil {
			return err
		}

		if d.DefaultButton != nil {
			if err := w.SetDefaultButton(*d.DefaultButton); err != nil {
				return err
			}

			if db := *d.DataBinder.AssignTo; db != nil {
				(*d.DefaultButton).SetEnabled(db.CanSubmit())

				db.CanSubmitChanged().Attach(func() {
					(*d.DefaultButton).SetEnabled(db.CanSubmit())
				})
			}
		}
		if d.CancelButton != nil {
			if err := w.SetCancelButton(*d.CancelButton); err != nil {
				return err
			}
		}

		if d.AssignTo != nil {
			*d.AssignTo = w
		}

		return nil
	})
}

func (d Dialog) Run(owner walk.RootWidget) (int, error) {
	var w *walk.Dialog

	if d.AssignTo == nil {
		d.AssignTo = &w
	}

	if err := d.Create(owner); err != nil {
		return 0, err
	}

	return (*d.AssignTo).Run(), nil
}
<|endoftext|>


<commit_before>package spi

import (
	"encoding/xml"
)

// Attributes & Aspects --------------------------------------------------------

type ExperimentAspect struct {
	Data string `xml:"data"`
	Type string `xml:"type"`
}

type Attribute interface {
	GetName() string
}

type DescriptionAttr struct {
	Name  string `xml:"name"`
	Value string `xml:"value"`
}

func (d DescriptionAttr) GetName() string {
	return d.Name
}

// Create Experiment -----------------------------------------------------------

type CreateExperimentEnvelope struct {
	Envelope
	Body struct {
		Body
		CreateExperiment struct {
			XMLName xml.Name           `xml:"http://api.testbed.deterlab.net/xsd createExperiment"`
			EID     string             `xml:"eid"`
			Owner   string             `xml:"owner"`
			Aspects []ExperimentAspect `xml:"aspects"`
			Profile []Attribute        `xml:"profile"`
		}
	}
}

type CreateExperimentResponse struct {
	Return bool `xml:"return"`
}

type CreateExperimentResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		CreateExperimentResponse CreateExperimentResponse `xml:"createExperimentResponse"`
	}
}

// Realize Experiment ----------------------------------------------------------

type RealizeExperimentEnvelope struct {
	Envelope
	Body struct {
		Body
		RealizeExperiment struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd realizeExperiment"`
			UID     string   `xml:"uid"`
			EID     string   `xml:"eid"`
			CID     string   `xml:"cid"`
		}
	}
}

type RealizeExperimentResponse struct {
	Return RealizationDescription `xml:"return"`
}

type RealizeExperimentResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		RealizeExperimentResponse RealizeExperimentResponse `xml:"realizeExperimentResponse"`
	}
}

type RealizationContainment struct {
	XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd RealizationContainment"`
	Inner   string   `xml:"inner"`
	Outer   string   `xml:"outer"`
}

type RealizationMap struct {
	XMLName      xml.Name `xml:"http://api.testbed.deterlab.net/xsd RealizationMap"`
	Resource     string   `xml:"resource"`
	TopologyName string   `xml:"topologyName"`
}

type RealizationDescription struct {
	//XMLName     xml.Name                 `xml:"http://api.testbed.deterlab.net/xsd RealizationDescription"`
	XMLName     xml.Name                 `xml:"http://api.testbed.deterlab.net/xsd return"`
	Circle      string                   `xml:"circle"`
	Experiment  string                   `xml:"experiment"`
	Name        string                   `xml:"name"`
	Staus       string                   `xml:"status"`
	Containment []RealizationContainment `xml:"containment"`
	Mapping     []RealizationMap         `xml:"mapping"`
	Perms       []string                 `xml:"perms"`
}

// Remove Realization ---------------------------------------------------------

type RemoveRealizationEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveRealization struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd removeRealization"`
			Name    string   `xml:"name"`
		}
	}
}

type RemoveRealizationResponse struct {
	Return bool `xml:"return"`
}

type RemoveRealizationResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveRealizationResponse RemoveRealizationResponse `xml:"removeRealizationResponse"`
	}
}

// Release Realization --------------------------------------------------------

type ReleaseRealizationEnvelope struct {
	Envelope
	Body struct {
		Body
		ReleaseRealization struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd releaseRealization"`
			Name    string   `xml:"name"`
		}
	}
}

type ReleaseRealizationResponse struct {
	Return bool `xml:"return"`
}

type ReleaseRealizationResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		ReleaseRealizationResponse ReleaseRealizationResponse `xml:"releaseRealizationResponse"`
	}
}

// View Realizations -----------------------------------------------------------

type ViewRealizationsEnvelope struct {
	Envelope
	Body struct {
		Body
		ViewRealizations struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd viewRealizations"`
			UID     string   `xml:"uid"`
			Regex   string   `xml:"regex"`
		}
	}
}

type ViewRealizationsResponse struct {
	Return []RealizationDescription `xml:"return"`
}

type ViewRealizationsResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		ViewRealizationsResponse ViewRealizationsResponse `xml:"viewRealizationsResponse"`
	}
}

// Remove Experiment -----------------------------------------------------------

type RemoveExperimentEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveExperiment struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd removeExperiment"`
			EID     string   `xml:"eid"`
		}
	}
}

type RemoveExperimentResponse struct {
	XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd removeExperimentResponse"`
	Return  bool     `xml:"return"`
}

type RemoveExperimentResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveExperimentResponse RemoveExperimentResponse
	}
}
<commit_msg>reticulating realization<commit_after>package spi

import (
	"encoding/xml"
)

// Attributes & Aspects --------------------------------------------------------

type ExperimentAspect struct {
	Data string `xml:"data"`
	Type string `xml:"type"`
}

type Attribute interface {
	GetName() string
}

type DescriptionAttr struct {
	Name  string `xml:"name"`
	Value string `xml:"value"`
}

func (d DescriptionAttr) GetName() string {
	return d.Name
}

// Create Experiment -----------------------------------------------------------

type CreateExperimentEnvelope struct {
	Envelope
	Body struct {
		Body
		CreateExperiment struct {
			XMLName xml.Name           `xml:"http://api.testbed.deterlab.net/xsd createExperiment"`
			EID     string             `xml:"eid"`
			Owner   string             `xml:"owner"`
			Aspects []ExperimentAspect `xml:"aspects"`
			Profile []Attribute        `xml:"profile"`
		}
	}
}

type CreateExperimentResponse struct {
	Return bool `xml:"return"`
}

type CreateExperimentResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		CreateExperimentResponse CreateExperimentResponse `xml:"createExperimentResponse"`
	}
}

// Realize Experiment ----------------------------------------------------------

type RealizeExperimentEnvelope struct {
	Envelope
	Body struct {
		Body
		RealizeExperiment struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd realizeExperiment"`
			UID     string   `xml:"uid"`
			EID     string   `xml:"eid"`
			CID     string   `xml:"cid"`
		}
	}
}

type RealizeExperimentResponse struct {
	Return RealizationDescription `xml:"return"`
}

type RealizeExperimentResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		RealizeExperimentResponse RealizeExperimentResponse `xml:"realizeExperimentResponse"`
	}
}

type RealizationContainment struct {
	XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd containment"`
	Inner   string   `xml:"inner"`
	Outer   string   `xml:"outer"`
}

type RealizationMap struct {
	XMLName      xml.Name `xml:"http://api.testbed.deterlab.net/xsd" mapping`
	Resource     string   `xml:"resource"`
	TopologyName string   `xml:"topologyName"`
}

type RealizationDescription struct {
	//XMLName     xml.Name                 `xml:"http://api.testbed.deterlab.net/xsd RealizationDescription"`
	XMLName     xml.Name                 `xml:"http://api.testbed.deterlab.net/xsd return"`
	Circle      string                   `xml:"circle"`
	Experiment  string                   `xml:"experiment"`
	Name        string                   `xml:"name"`
	Staus       string                   `xml:"status"`
	Containment []RealizationContainment `xml:"containment"`
	Mapping     []RealizationMap         `xml:"mapping"`
	Perms       []string                 `xml:"perms"`
}

// Remove Realization ---------------------------------------------------------

type RemoveRealizationEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveRealization struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd removeRealization"`
			Name    string   `xml:"name"`
		}
	}
}

type RemoveRealizationResponse struct {
	Return bool `xml:"return"`
}

type RemoveRealizationResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveRealizationResponse RemoveRealizationResponse `xml:"removeRealizationResponse"`
	}
}

// Release Realization --------------------------------------------------------

type ReleaseRealizationEnvelope struct {
	Envelope
	Body struct {
		Body
		ReleaseRealization struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd releaseRealization"`
			Name    string   `xml:"name"`
		}
	}
}

type ReleaseRealizationResponse struct {
	Return bool `xml:"return"`
}

type ReleaseRealizationResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		ReleaseRealizationResponse ReleaseRealizationResponse `xml:"releaseRealizationResponse"`
	}
}

// View Realizations -----------------------------------------------------------

type ViewRealizationsEnvelope struct {
	Envelope
	Body struct {
		Body
		ViewRealizations struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd viewRealizations"`
			UID     string   `xml:"uid"`
			Regex   string   `xml:"regex"`
		}
	}
}

type ViewRealizationsResponse struct {
	Return []RealizationDescription `xml:"return"`
}

type ViewRealizationsResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		ViewRealizationsResponse ViewRealizationsResponse `xml:"viewRealizationsResponse"`
	}
}

// Remove Experiment -----------------------------------------------------------

type RemoveExperimentEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveExperiment struct {
			XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd removeExperiment"`
			EID     string   `xml:"eid"`
		}
	}
}

type RemoveExperimentResponse struct {
	XMLName xml.Name `xml:"http://api.testbed.deterlab.net/xsd removeExperimentResponse"`
	Return  bool     `xml:"return"`
}

type RemoveExperimentResponseEnvelope struct {
	Envelope
	Body struct {
		Body
		RemoveExperimentResponse RemoveExperimentResponse
	}
}
<|endoftext|>


<commit_before>package main

import (
        "errors"
        "fmt"

        "encoding/json"
        "github.com/hyperledger/fabric/core/chaincode/shim"
)

// CrowdFundChaincode implementation
type CrowdFundChaincode struct {
}
//var index int
type StudentInfo struct {
        StudentRollNo     string  `json:"Studentrollno"`
        StudentName        string   `json:"Studentname"`
        StudentBadge       []string  `json:"Studentbadge"`
        StudentMarks       []string   `json:"Studentmarks"`
        StudentSem         []string   `json:"Studentsem"`
        IssuedBy        []string   `json:"Issuedby"`

}
type BadgeInfo struct {

        BadgeName       []string   `json:"Badgeame"`
        BadgeUrl        []string `json:"Badgeurl"`
        BadgeIssuedBy   []string   `json:"Badgeissuedby"`
        BadgeIssuedTo   []string `json:"Badgeissuedto"`
        //time
}

type Issuer struct {

        IssuerInfo      []string   `json:"Issuerinfo"`
        IssuerName        string `json:"Issuername"`
       // time            string   `json:"sem"`

}
//
// Init creates the state variable with name "account" and stores the value
// from the incoming request into this variable. We now have a key/value pair
// for account --> accountValue.
//
func (t *CrowdFundChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

        var err error

        if len(args) != 2 {
                return nil, errors.New("Incorrect number of arguments. Expecting 2.")
        }

     if err!=nil {
                        return nil, err
                }
         record := StudentInfo{}

       record.StudentRollNo ="MT2916";
       record.StudentName ="aarushi";

        //record.StudentRollNo=append(record.StudentRollNo,"MT2016001");
        //record.StudentName=append(record.StudentName,"Aarushi");
        record.StudentBadge=append(record.StudentBadge,"Mtech");
        record.StudentMarks=append(record.StudentMarks,"78");
        record.StudentSem=append(record.StudentSem,"1st");
        record.IssuedBy=append(record.IssuedBy,"RC Sir");

        newrecordByte, err := json.Marshal(record);
        if err!=nil {

            return nil, err
        }
                err=stub.PutState("default",newrecordByte);
         if err!=nil {
                        return nil, err
            }

        return nil, nil
}

func (t *CrowdFundChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
    if function == "write" {

fmt.Printf("-----------------------------------inside write function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)
record := StudentInfo{}

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentSem,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

            newrecordByte, err := json.Marshal(record);

 if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
        return nil, nil

 } else {
if (function == "update") {
fmt.Printf("-----------------------------------inside update function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)

         recordByte, err := stub.GetState(account);
        fmt.Println(recordByte);
        if err != nil {

            return nil, err
        }
        record := StudentInfo{}
        if recordByte != nil {
        errrecordmarshal := json.Unmarshal(recordByte,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentSem,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

        /*record.Rollno = append(record.Rollno,args[0]);
        record.Name = append(record.Name,args[1]);
        record.Sem=append(record.Sem,args[2]);
        record.Marks=append(record.Marks,args[3]);
*/
        fmt.Printf(" record structure rollno is : %s" ,  record.StudentRollNo)
        fmt.Printf(" record structure name is   : %s" ,  record.StudentName)
        fmt.Printf(" record structure badge is : %s" ,   record.StudentBadge)
        fmt.Printf(" record structure marks is : : %s" , record.StudentMarks)
        fmt.Printf(" record structure sem is : %s" ,     record.StudentSem)
        fmt.Printf(" record structure issuedby is : %s" ,record.IssuedBy)

        newrecordByte, err := json.Marshal(record);//result comes in bytes

        stringNewRecordByte := string(newrecordByte)

        fmt.Printf(" the marshall function output is : %s" , stringNewRecordByte)

        if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
}
}
        return nil, nil

}

func (t *CrowdFundChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
  if function != "read" {
                return nil, errors.New("Invalid query function name. Expecting \"query\".")
        }
else {
        fmt.Printf("-----------------------------------inside read function-------------------------------------------------------------");

       var err error

         if len(args) != 1 {
                return nil, errors.New("Incorrect number of arguments. Expecting name of the state variable to query.")
        }

     var   account = args[0]

      fmt.Printf("----------------------------inside read function--------value of account is  %s--------------------------------, account");

        accountValueBytes ,err := stub.GetState(account)

if err != nil {

                 return nil, err
        }
 record := StudentInfo{}
        if accountValueBytes != nil {
        errrecordmarshal := json.Unmarshal(accountValueBytes,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        return accountValueBytes, nil
    }
}

func main() {
        err := shim.Start(new(CrowdFundChaincode))

        if err != nil {
                fmt.Printf("Error starting CrowdFundChaincode: %s", err)
        }
}
<commit_msg>Update chaincode_start.go<commit_after>package main

import (
        "errors"
        "fmt"

        "encoding/json"
        "github.com/hyperledger/fabric/core/chaincode/shim"
)

// CrowdFundChaincode implementation
type CrowdFundChaincode struct {
}
//var index int
type StudentInfo struct {
        StudentRollNo     string  `json:"Studentrollno"`
        StudentName        string   `json:"Studentname"`
        StudentBadge       []string  `json:"Studentbadge"`
        StudentMarks       []string   `json:"Studentmarks"`
        StudentSem         []string   `json:"Studentsem"`
        IssuedBy        []string   `json:"Issuedby"`

}
type BadgeInfo struct {

        BadgeName       []string   `json:"Badgeame"`
        BadgeUrl        []string `json:"Badgeurl"`
        BadgeIssuedBy   []string   `json:"Badgeissuedby"`
        BadgeIssuedTo   []string `json:"Badgeissuedto"`
        //time
}

type Issuer struct {

        IssuerInfo      []string   `json:"Issuerinfo"`
        IssuerName        string `json:"Issuername"`
       // time            string   `json:"sem"`

}
//
// Init creates the state variable with name "account" and stores the value
// from the incoming request into this variable. We now have a key/value pair
// for account --> accountValue.
//
func (t *CrowdFundChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

        var err error

        if len(args) != 2 {
                return nil, errors.New("Incorrect number of arguments. Expecting 2.")
        }

     if err!=nil {
                        return nil, err
                }
         record := StudentInfo{}

       record.StudentRollNo ="MT2916";
       record.StudentName ="aarushi";

        //record.StudentRollNo=append(record.StudentRollNo,"MT2016001");
        //record.StudentName=append(record.StudentName,"Aarushi");
        record.StudentBadge=append(record.StudentBadge,"Mtech");
        record.StudentMarks=append(record.StudentMarks,"78");
        record.StudentSem=append(record.StudentSem,"1st");
        record.IssuedBy=append(record.IssuedBy,"RC Sir");

        newrecordByte, err := json.Marshal(record);
        if err!=nil {

            return nil, err
        }
                err=stub.PutState("default",newrecordByte);
         if err!=nil {
                        return nil, err
            }

        return nil, nil
}

func (t *CrowdFundChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
    if function == "write" {

fmt.Printf("-----------------------------------inside write function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)
record := StudentInfo{}

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentSem,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

            newrecordByte, err := json.Marshal(record);

 if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
        return nil, nil

 } else {
if (function == "update") {
fmt.Printf("-----------------------------------inside update function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)

         recordByte, err := stub.GetState(account);
        fmt.Println(recordByte);
        if err != nil {

            return nil, err
        }
        record := StudentInfo{}
        if recordByte != nil {
        errrecordmarshal := json.Unmarshal(recordByte,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentSem,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

        /*record.Rollno = append(record.Rollno,args[0]);
        record.Name = append(record.Name,args[1]);
        record.Sem=append(record.Sem,args[2]);
        record.Marks=append(record.Marks,args[3]);
*/
        fmt.Printf(" record structure rollno is : %s" ,  record.StudentRollNo)
        fmt.Printf(" record structure name is   : %s" ,  record.StudentName)
        fmt.Printf(" record structure badge is : %s" ,   record.StudentBadge)
        fmt.Printf(" record structure marks is : : %s" , record.StudentMarks)
        fmt.Printf(" record structure sem is : %s" ,     record.StudentSem)
        fmt.Printf(" record structure issuedby is : %s" ,record.IssuedBy)

        newrecordByte, err := json.Marshal(record);//result comes in bytes

        stringNewRecordByte := string(newrecordByte)

        fmt.Printf(" the marshall function output is : %s" , stringNewRecordByte)

        if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
}
}
        return nil, nil

}

func (t *CrowdFundChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
  if function != "read" {
                return nil, errors.New("Invalid query function name. Expecting \"query\".")
        } else {
        fmt.Printf("-----------------------------------inside read function-------------------------------------------------------------");

       var err error

         if len(args) != 1 {
                return nil, errors.New("Incorrect number of arguments. Expecting name of the state variable to query.")
        }

     var   account = args[0]

      fmt.Printf("----------------------------inside read function--------value of account is  %s--------------------------------, account");

        accountValueBytes ,err := stub.GetState(account)

if err != nil {

                 return nil, err
        }
 record := StudentInfo{}
        if accountValueBytes != nil {
        errrecordmarshal := json.Unmarshal(accountValueBytes,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        return accountValueBytes, nil
    }
}

func main() {
        err := shim.Start(new(CrowdFundChaincode))

        if err != nil {
                fmt.Printf("Error starting CrowdFundChaincode: %s", err)
        }
}
<|endoftext|>


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

// +build ignore

// Build this command explicitly: go build gotype.go

/*
The gotype command does syntactic and semantic analysis of Go files
and packages like the front-end of a Go compiler. Errors are reported
if the analysis fails; otherwise gotype is quiet (unless -v is set).

Without a list of paths, gotype reads from standard input, which
must provide a single Go source file defining a complete package.

If a single path is specified that is a directory, gotype checks
the Go files in that directory; they must all belong to the same
package.

Otherwise, each path must be the filename of Go file belonging to
the same package.

Imports are processed by importing directly from the source of
imported packages (default), or by importing from compiled and
installed packages (by setting -c to the respective compiler).

Usage:
	gotype [flags] [path...]

The flags are:
	-a
		use all (incl. _test.go) files when processing a directory
	-e
		report all errors (not just the first 10)
	-v
		verbose mode
	-c
		compiler used for installed packages (gc, gccgo, or source); default: source

Debugging flags:
	-seq
		parse sequentially, rather than in parallel
	-ast
		print AST (forces -seq)
	-trace
		print parse trace (forces -seq)
	-comments
		parse comments (ignored unless -ast or -trace is provided)

Examples:

To check the files a.go, b.go, and c.go:

	gotype a.go b.go c.go

To check an entire package in the directory dir and print the processed files:

	gotype -v dir

To check an entire package including tests in the local directory:

	gotype -a .

To verify the output of a pipe:

	echo "package foo" | gotype

*/
package main

import (
	"flag"
	"fmt"
	"go/ast"
	"go/build"
	"go/importer"
	"go/parser"
	"go/scanner"
	"go/token"
	"go/types"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"
)

var (
	// main operation modes
	allFiles  = flag.Bool("a", false, "use all (incl. _test.go) files when processing a directory")
	allErrors = flag.Bool("e", false, "report all errors (not just the first 10)")
	verbose   = flag.Bool("v", false, "verbose mode")
	compiler  = flag.String("c", "source", "compiler used for installed packages (gc, gccgo, or source)")

	// debugging support
	sequential    = flag.Bool("seq", false, "parse sequentially, rather than in parallel")
	printAST      = flag.Bool("ast", false, "print AST (forces -seq)")
	printTrace    = flag.Bool("trace", false, "print parse trace (forces -seq)")
	parseComments = flag.Bool("comments", false, "parse comments (ignored unless -ast or -trace is provided)")
)

var (
	fset       = token.NewFileSet()
	errorCount = 0
	parserMode parser.Mode
)

func initParserMode() {
	if *allErrors {
		parserMode |= parser.AllErrors
	}
	if *printTrace {
		parserMode |= parser.Trace
	}
	if *parseComments && (*printAST || *printTrace) {
		parserMode |= parser.ParseComments
	}
}

func usage() {
	fmt.Fprintln(os.Stderr, "usage: gotype [flags] [path ...]")
	flag.PrintDefaults()
	os.Exit(2)
}

func report(err error) {
	scanner.PrintError(os.Stderr, err)
	if list, ok := err.(scanner.ErrorList); ok {
		errorCount += len(list)
		return
	}
	errorCount++
}

// parse may be called concurrently
func parse(filename string, src interface{}) (*ast.File, error) {
	if *verbose {
		fmt.Println(filename)
	}
	file, err := parser.ParseFile(fset, filename, src, parserMode) // ok to access fset concurrently
	if *printAST {
		ast.Print(fset, file)
	}
	return file, err
}

func parseStdin() (*ast.File, error) {
	src, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return nil, err
	}
	return parse("<standard input>", src)
}

func parseFiles(filenames []string) ([]*ast.File, error) {
	files := make([]*ast.File, len(filenames))

	if *sequential {
		for i, filename := range filenames {
			var err error
			files[i], err = parse(filename, nil)
			if err != nil {
				return nil, err // leave unfinished goroutines hanging
			}
		}
	} else {
		type parseResult struct {
			file *ast.File
			err  error
		}

		out := make(chan parseResult)
		for _, filename := range filenames {
			go func(filename string) {
				file, err := parse(filename, nil)
				out <- parseResult{file, err}
			}(filename)
		}

		for i := range filenames {
			res := <-out
			if res.err != nil {
				return nil, res.err // leave unfinished goroutines hanging
			}
			files[i] = res.file
		}
	}

	return files, nil
}

func parseDir(dirname string) ([]*ast.File, error) {
	ctxt := build.Default
	pkginfo, err := ctxt.ImportDir(dirname, 0)
	if _, nogo := err.(*build.NoGoError); err != nil && !nogo {
		return nil, err
	}
	filenames := append(pkginfo.GoFiles, pkginfo.CgoFiles...)
	if *allFiles {
		filenames = append(filenames, pkginfo.TestGoFiles...)
	}

	// complete file names
	for i, filename := range filenames {
		filenames[i] = filepath.Join(dirname, filename)
	}

	return parseFiles(filenames)
}

func getPkgFiles(args []string) ([]*ast.File, error) {
	if len(args) == 0 {
		// stdin
		file, err := parseStdin()
		if err != nil {
			return nil, err
		}
		return []*ast.File{file}, nil
	}

	if len(args) == 1 {
		// possibly a directory
		path := args[0]
		info, err := os.Stat(path)
		if err != nil {
			return nil, err
		}
		if info.IsDir() {
			return parseDir(path)
		}
	}

	// list of files
	return parseFiles(args)
}

func checkPkgFiles(files []*ast.File) {
	type bailout struct{}

	// if checkPkgFiles is called multiple times, set up conf only once
	conf := types.Config{
		FakeImportC: true,
		Error: func(err error) {
			if !*allErrors && errorCount >= 10 {
				panic(bailout{})
			}
			report(err)
		},
		Importer: importer.For(*compiler, nil),
		Sizes:    types.SizesFor(build.Default.Compiler, build.Default.GOARCH),
	}

	defer func() {
		switch p := recover().(type) {
		case nil, bailout:
			// normal return or early exit
		default:
			// re-panic
			panic(p)
		}
	}()

	const path = "pkg" // any non-empty string will do for now
	conf.Check(path, fset, files, nil)
}

func printStats(d time.Duration) {
	fileCount := 0
	lineCount := 0
	fset.Iterate(func(f *token.File) bool {
		fileCount++
		lineCount += f.LineCount()
		return true
	})

	fmt.Printf(
		"%s (%d files, %d lines, %d lines/s)\n",
		d, fileCount, lineCount, int64(float64(lineCount)/d.Seconds()),
	)
}

func main() {
	flag.Usage = usage
	flag.Parse()
	if *printAST || *printTrace {
		*sequential = true
	}
	initParserMode()

	start := time.Now()

	files, err := getPkgFiles(flag.Args())
	if err != nil {
		report(err)
		os.Exit(2)
	}

	checkPkgFiles(files)
	if errorCount > 0 {
		os.Exit(2)
	}

	if *verbose {
		printStats(time.Since(start))
	}
}
<commit_msg>go/types: gotype to always report the same first error now<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

// Build this command explicitly: go build gotype.go

/*
The gotype command does syntactic and semantic analysis of Go files
and packages like the front-end of a Go compiler. Errors are reported
if the analysis fails; otherwise gotype is quiet (unless -v is set).

Without a list of paths, gotype reads from standard input, which
must provide a single Go source file defining a complete package.

If a single path is specified that is a directory, gotype checks
the Go files in that directory; they must all belong to the same
package.

Otherwise, each path must be the filename of Go file belonging to
the same package.

Imports are processed by importing directly from the source of
imported packages (default), or by importing from compiled and
installed packages (by setting -c to the respective compiler).

Usage:
	gotype [flags] [path...]

The flags are:
	-a
		use all (incl. _test.go) files when processing a directory
	-e
		report all errors (not just the first 10)
	-v
		verbose mode
	-c
		compiler used for installed packages (gc, gccgo, or source); default: source

Flags controlling additional output:
	-ast
		print AST (forces -seq)
	-trace
		print parse trace (forces -seq)
	-comments
		parse comments (ignored unless -ast or -trace is provided)

Examples:

To check the files a.go, b.go, and c.go:

	gotype a.go b.go c.go

To check an entire package in the directory dir and print the processed files:

	gotype -v dir

To check an entire package including tests in the local directory:

	gotype -a .

To verify the output of a pipe:

	echo "package foo" | gotype

*/
package main

import (
	"flag"
	"fmt"
	"go/ast"
	"go/build"
	"go/importer"
	"go/parser"
	"go/scanner"
	"go/token"
	"go/types"
	"io/ioutil"
	"os"
	"path/filepath"
	"sync"
	"time"
)

var (
	// main operation modes
	allFiles  = flag.Bool("a", false, "use all (incl. _test.go) files when processing a directory")
	allErrors = flag.Bool("e", false, "report all errors (not just the first 10)")
	verbose   = flag.Bool("v", false, "verbose mode")
	compiler  = flag.String("c", "source", "compiler used for installed packages (gc, gccgo, or source)")

	// debugging support
	printAST      = flag.Bool("ast", false, "print AST (forces -seq)")
	printTrace    = flag.Bool("trace", false, "print parse trace (forces -seq)")
	parseComments = flag.Bool("comments", false, "parse comments (ignored unless -ast or -trace is provided)")
)

var (
	fset       = token.NewFileSet()
	errorCount = 0
	sequential = false
	parserMode parser.Mode
)

func initParserMode() {
	if *allErrors {
		parserMode |= parser.AllErrors
	}
	if *printAST {
		sequential = true
	}
	if *printTrace {
		parserMode |= parser.Trace
		sequential = true
	}
	if *parseComments && (*printAST || *printTrace) {
		parserMode |= parser.ParseComments
	}
}

func usage() {
	fmt.Fprintln(os.Stderr, "usage: gotype [flags] [path ...]")
	flag.PrintDefaults()
	os.Exit(2)
}

func report(err error) {
	scanner.PrintError(os.Stderr, err)
	if list, ok := err.(scanner.ErrorList); ok {
		errorCount += len(list)
		return
	}
	errorCount++
}

// parse may be called concurrently
func parse(filename string, src interface{}) (*ast.File, error) {
	if *verbose {
		fmt.Println(filename)
	}
	file, err := parser.ParseFile(fset, filename, src, parserMode) // ok to access fset concurrently
	if *printAST {
		ast.Print(fset, file)
	}
	return file, err
}

func parseStdin() (*ast.File, error) {
	src, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return nil, err
	}
	return parse("<standard input>", src)
}

func parseFiles(dir string, filenames []string) ([]*ast.File, error) {
	files := make([]*ast.File, len(filenames))
	errors := make([]error, len(filenames))

	var wg sync.WaitGroup
	for i, filename := range filenames {
		wg.Add(1)
		go func(i int, filepath string) {
			defer wg.Done()
			files[i], errors[i] = parse(filepath, nil)
		}(i, filepath.Join(dir, filename))
		if sequential {
			wg.Wait()
		}
	}
	wg.Wait()

	// if there are errors, return the first one for deterministic results
	for _, err := range errors {
		if err != nil {
			return nil, err
		}
	}

	return files, nil
}

func parseDir(dir string) ([]*ast.File, error) {
	ctxt := build.Default
	pkginfo, err := ctxt.ImportDir(dir, 0)
	if _, nogo := err.(*build.NoGoError); err != nil && !nogo {
		return nil, err
	}
	filenames := append(pkginfo.GoFiles, pkginfo.CgoFiles...)
	if *allFiles {
		filenames = append(filenames, pkginfo.TestGoFiles...)
	}

	return parseFiles(dir, filenames)
}

func getPkgFiles(args []string) ([]*ast.File, error) {
	if len(args) == 0 {
		// stdin
		file, err := parseStdin()
		if err != nil {
			return nil, err
		}
		return []*ast.File{file}, nil
	}

	if len(args) == 1 {
		// possibly a directory
		path := args[0]
		info, err := os.Stat(path)
		if err != nil {
			return nil, err
		}
		if info.IsDir() {
			return parseDir(path)
		}
	}

	// list of files
	return parseFiles("", args)
}

func checkPkgFiles(files []*ast.File) {
	type bailout struct{}

	// if checkPkgFiles is called multiple times, set up conf only once
	conf := types.Config{
		FakeImportC: true,
		Error: func(err error) {
			if !*allErrors && errorCount >= 10 {
				panic(bailout{})
			}
			report(err)
		},
		Importer: importer.For(*compiler, nil),
		Sizes:    types.SizesFor(build.Default.Compiler, build.Default.GOARCH),
	}

	defer func() {
		switch p := recover().(type) {
		case nil, bailout:
			// normal return or early exit
		default:
			// re-panic
			panic(p)
		}
	}()

	const path = "pkg" // any non-empty string will do for now
	conf.Check(path, fset, files, nil)
}

func printStats(d time.Duration) {
	fileCount := 0
	lineCount := 0
	fset.Iterate(func(f *token.File) bool {
		fileCount++
		lineCount += f.LineCount()
		return true
	})

	fmt.Printf(
		"%s (%d files, %d lines, %d lines/s)\n",
		d, fileCount, lineCount, int64(float64(lineCount)/d.Seconds()),
	)
}

func main() {
	flag.Usage = usage
	flag.Parse()
	initParserMode()

	start := time.Now()

	files, err := getPkgFiles(flag.Args())
	if err != nil {
		report(err)
		os.Exit(2)
	}

	checkPkgFiles(files)
	if errorCount > 0 {
		os.Exit(2)
	}

	if *verbose {
		printStats(time.Since(start))
	}
}
<|endoftext|>


<commit_before>/*
 * Minio Client (C) 2017 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cmd

import (
	"encoding/json"
	"os"

	"github.com/fatih/color"
	"github.com/minio/cli"
	"github.com/minio/mc/pkg/console"
	"github.com/minio/mc/pkg/probe"
)

var adminConfigSetCmd = cli.Command{
	Name:   "set",
	Usage:  "Set new config file to a Minio server/cluster.",
	Before: setGlobalsFromContext,
	Action: mainAdminConfigSet,
	Flags:  globalFlags,
	CustomHelpTemplate: `NAME:
  {{.HelpName}} - {{.Usage}}

USAGE:
  {{.HelpName}} TARGET

FLAGS:
  {{range .VisibleFlags}}{{.}}
  {{end}}
EXAMPLES:
  1. Set server configuration of a Minio server/cluster.
     $ cat myconfig | {{.HelpName}} myminio/

`,
}

// configSetMessage container to hold locks information.
type configSetMessage struct {
	Status          string `json:"status"`
	setConfigStatus bool
}

// String colorized service status message.
func (u configSetMessage) String() (msg string) {
	// Print the general set config status
	if u.setConfigStatus {
		msg += console.Colorize("SetConfigSuccess",
			"Setting new Minio configuration file has been successful.\n")
		msg += console.Colorize("SetConfigSuccess",
			"Please restart your server with `mc admin restart`.\n")
	} else {
		msg += console.Colorize("SetConfigFailure",
			"Setting new Minio configuration file has failed.\n")
	}
	return
}

// JSON jsonified service status Message message.
func (u configSetMessage) JSON() string {
	if u.setConfigStatus {
		u.Status = "success"
	} else {
		u.Status = "error"
	}
	statusJSONBytes, e := json.Marshal(u)
	fatalIf(probe.NewError(e), "Unable to marshal into JSON.")

	return string(statusJSONBytes)
}

// checkAdminConfigSetSyntax - validate all the passed arguments
func checkAdminConfigSetSyntax(ctx *cli.Context) {
	if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
		cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
	}
}

// main config set function
func mainAdminConfigSet(ctx *cli.Context) error {

	// Check command arguments
	checkAdminConfigSetSyntax(ctx)

	// Set color preference of command outputs
	console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
	console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))

	// Get the alias parameter from cli
	args := ctx.Args()
	aliasedURL := args.Get(0)

	// Create a new Minio Admin Client
	client, err := newAdminClient(aliasedURL)
	fatalIf(err, "Cannot get a configured admin connection.")

	// Call get config API
	fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")

	// Print set config result
	printMsg(configSetMessage{
		setConfigStatus: true,
	})

	return nil
}
<commit_msg>Fix a typo in config set success message (#2588)<commit_after>/*
 * Minio Client (C) 2017 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cmd

import (
	"encoding/json"
	"os"

	"github.com/fatih/color"
	"github.com/minio/cli"
	"github.com/minio/mc/pkg/console"
	"github.com/minio/mc/pkg/probe"
)

var adminConfigSetCmd = cli.Command{
	Name:   "set",
	Usage:  "Set new config file to a Minio server/cluster.",
	Before: setGlobalsFromContext,
	Action: mainAdminConfigSet,
	Flags:  globalFlags,
	CustomHelpTemplate: `NAME:
  {{.HelpName}} - {{.Usage}}

USAGE:
  {{.HelpName}} TARGET

FLAGS:
  {{range .VisibleFlags}}{{.}}
  {{end}}
EXAMPLES:
  1. Set server configuration of a Minio server/cluster.
     $ cat myconfig | {{.HelpName}} myminio/

`,
}

// configSetMessage container to hold locks information.
type configSetMessage struct {
	Status          string `json:"status"`
	setConfigStatus bool
}

// String colorized service status message.
func (u configSetMessage) String() (msg string) {
	// Print the general set config status
	if u.setConfigStatus {
		msg += console.Colorize("SetConfigSuccess",
			"Setting new Minio configuration file has been successful.\n")
		msg += console.Colorize("SetConfigSuccess",
			"Please restart your server with `mc admin service restart`.\n")
	} else {
		msg += console.Colorize("SetConfigFailure",
			"Setting new Minio configuration file has failed.\n")
	}
	return
}

// JSON jsonified service status Message message.
func (u configSetMessage) JSON() string {
	if u.setConfigStatus {
		u.Status = "success"
	} else {
		u.Status = "error"
	}
	statusJSONBytes, e := json.Marshal(u)
	fatalIf(probe.NewError(e), "Unable to marshal into JSON.")

	return string(statusJSONBytes)
}

// checkAdminConfigSetSyntax - validate all the passed arguments
func checkAdminConfigSetSyntax(ctx *cli.Context) {
	if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
		cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
	}
}

// main config set function
func mainAdminConfigSet(ctx *cli.Context) error {

	// Check command arguments
	checkAdminConfigSetSyntax(ctx)

	// Set color preference of command outputs
	console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
	console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))

	// Get the alias parameter from cli
	args := ctx.Args()
	aliasedURL := args.Get(0)

	// Create a new Minio Admin Client
	client, err := newAdminClient(aliasedURL)
	fatalIf(err, "Cannot get a configured admin connection.")

	// Call get config API
	fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")

	// Print set config result
	printMsg(configSetMessage{
		setConfigStatus: true,
	})

	return nil
}
<|endoftext|>