text stringlengths 11 4.05M |
|---|
/*
* Copyright 2018 Haines Chan
*
* This program is free software; you can redistribute and/or modify it
* under the terms of the standard MIT license. See LICENSE for more details
*/
package anchor
import (
"fmt"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/plugins/pkg/ip"
"github.com/hainesc/anchor/pkg/allocator"
"github.com/hainesc/anchor/pkg/store"
"net"
"strings"
)
// Allocator is the allocator for anchor.
type Allocator struct {
store store.Store
pod string
namespace string
customized map[string]string
subnet *net.IPNet
gateway net.IP
}
const (
customizeGatewayKey = "cni.anchor.org/gateway"
customizeRoutesKey = "cni.anchor.org/routes"
customizeSubnetKey = "cni.anchor.org/subnet"
customizeRangeKey = "cni.anchor.org/range"
)
// AnchorAllocator implements the Allocator interface
var _ allocator.Allocator = &Allocator{}
// NewAllocator news a allocator
func NewAllocator(store store.Store,
pod, namespace string,
customized map[string]string) (*Allocator, error) {
var subnet *net.IPNet
var gw net.IP
var err error // declaration here for avoid := which also create a new var
if customized[customizeSubnetKey] != "" {
_, subnet, err = net.ParseCIDR(customized[customizeSubnetKey])
if err != nil {
return nil, fmt.Errorf("invalid format of subnet in annotations")
}
}
if customized[customizeRangeKey] != "" {
// TODO: Caculate the subnet
return nil, fmt.Errorf("customized range not implentmented")
}
if customized[customizeGatewayKey] != "" {
gw = net.ParseIP(customized[customizeSubnetKey])
if gw == nil {
return nil, fmt.Errorf("invalid format of gateway in annotations")
}
} else {
// Maybe no lock here is better.
store.Lock()
defer store.Unlock()
gw = store.RetrieveGateway(subnet)
if gw == nil {
return nil, fmt.Errorf("failed to retrieve gateway for %s", subnet.String())
}
}
if !subnet.Contains(gw) {
return nil, fmt.Errorf("gateway %s not in network %s", gw.String(), subnet.String())
}
return &Allocator{
store: store,
pod: pod,
namespace: namespace,
customized: customized,
subnet: subnet,
gateway: gw,
}, nil
}
// CustomizeGateway adds default route for pod if customizeGatewayKey is set.
func (a *Allocator) CustomizeGateway(ret *current.Result) (*current.Result, error) {
// We do nothing here because we has set gateway in func NewAllocator.
/*
if customizeGateway := net.ParseIP(a.customized[customizeGatewayKey]);
customizeGateway != nil {
ret.Routes = append(ret.Routes, &types.Route{
Dst: net.IPNet{
IP: net.IPv4zero,
Mask: net.IPv4Mask(0, 0, 0, 0),
},
GW: customizeGateway,
})
a.gatewayCustomized = true
}
*/
return ret, nil
}
// CustomizeRoutes adds routes if customizeRouteKey is set.
// The format of input should as: 10.0.1.0/24,10.0.1.1;10.0.5.0/24,10.0.5.1
// The outer delimiter is semicolon(;) and the inner delimiter is comma(,)
func (a *Allocator) CustomizeRoutes(ret *current.Result) (*current.Result, error) {
// Config route for default first
ret.Routes = append(ret.Routes, &types.Route{
Dst: net.IPNet{
IP: net.IPv4zero,
Mask: net.IPv4Mask(0, 0, 0, 0),
},
GW: a.gateway,
})
if customizeRoute := a.customized[customizeRoutesKey]; customizeRoute != "" {
routes := strings.Split(customizeRoute, ";")
for _, r := range routes {
_, dst, err := net.ParseCIDR(strings.Split(r, ",")[0])
if err != nil {
return nil, fmt.Errorf("invalid format of customized route in %s", r)
}
gw := net.ParseIP(strings.Split(r, ",")[1])
if gw == nil {
return nil, fmt.Errorf("invalid format of customized route in %s", r)
}
if !a.subnet.Contains(gw) {
return nil, fmt.Errorf("gateway %s not in network %s", gw.String(), a.subnet.String())
}
ret.Routes = append(ret.Routes, &types.Route{
Dst: *dst,
GW: gw,
})
}
}
return ret, nil
}
// CustomizeDNS configs the DNS for pod, but not implemented now.
func (a *Allocator) CustomizeDNS(ret *current.Result) (*current.Result, error) {
// Recently, k8s does nothing even our result contains DNS info.
// So we do nothing, just a function interface here.
return ret, nil
}
// AddServiceRoute adds route for serice cluster ip range.
func (a *Allocator) AddServiceRoute(ret *current.Result,
serviceClusterIPRange string,
nodeIPs []string) (*current.Result, error) {
if serviceClusterIPRange == "" {
return ret, nil
}
_, dst, err := net.ParseCIDR(serviceClusterIPRange)
if err != nil {
return nil, fmt.Errorf("invalid format of service cluster ip range %s", serviceClusterIPRange)
}
for _, nodeIP := range nodeIPs {
if a.subnet.Contains(net.ParseIP(nodeIP)) {
ret.Routes = append(ret.Routes, &types.Route{
Dst: *dst,
GW: net.ParseIP(nodeIP),
})
break
}
// If none of nodeIP contains in subnet, just break.
}
return ret, nil
}
// Allocate allocates IP for the pod.
func (a *Allocator) Allocate(id string) (*current.IPConfig, error) {
a.store.Lock()
defer a.store.Unlock()
ips, err := a.store.RetrieveAllocated(a.namespace, a.subnet)
if err != nil {
return nil, err
}
for _, ipRange := range *ips {
ipRange.Gateway = a.gateway
if err = ipRange.Canonicalize(); err != nil {
return nil, err
}
}
used, err := a.store.RetrieveUsed(a.namespace, a.subnet)
if err != nil {
return nil, err
}
for _, usedRange := range *used {
usedRange.Gateway = a.gateway
if err = usedRange.Canonicalize(); err != nil {
return nil, err
}
}
for _, r := range *ips {
var iter net.IP
for iter = r.RangeStart; !iter.Equal(ip.NextIP(r.RangeEnd)); iter = ip.NextIP(iter) {
avail := true
for _, usedRange := range *used {
var u net.IP
for u = usedRange.RangeStart; !u.Equal(ip.NextIP(usedRange.RangeEnd)); u = ip.NextIP(u) {
if iter.Equal(u) {
avail = false
break
}
}
}
if avail {
// Get subnet and gateway information
if err != nil {
// TODO: check
continue
}
if iter.Equal(a.gateway) {
// TODO: check
continue
}
// TODO:
controllerName := a.customized["cni.anchor.org/controller"]
if controllerName == "" {
controllerName = "unknown"
}
_, err = a.store.Reserve(id, iter, a.pod, a.namespace, controllerName)
if err != nil {
continue
}
return ¤t.IPConfig{
Version: "4",
Address: net.IPNet{IP: iter, Mask: a.subnet.Mask},
Gateway: a.gateway,
}, nil
}
}
}
return nil, fmt.Errorf("can not allcate IP for pod named, %s", a.pod)
}
// Cleaner is the cleaner for anchor.
type Cleaner struct {
store store.Store
pod string
namespace string
}
// AnchorCleaner implements the Cleaner interface
var _ allocator.Cleaner = &Cleaner{}
// NewCleaner news a cleaner for anchor.
func NewCleaner(store store.Store, pod, namespace string) (*Cleaner, error) {
return &Cleaner{
store: store,
pod: pod,
namespace: namespace,
}, nil
}
// Clean cleans the IP for the pod.
func (a *Cleaner) Clean(id string) error {
a.store.Lock()
defer a.store.Unlock()
return a.store.Release(id)
}
|
/*
You will be given a collection of five cards (representing a player's hand in poker).
If your hand contains at least one pair, return an array of two elements: true and the card number of the highest pair (trivial if there only exists a single pair).
Else, return false.
Examples
highestPair(["A", "A", "Q", "Q", "6" ]) ➞ [true, "A"]
highestPair(["J", "6", "3", "10", "8"]) ➞ false
highestPair(["K", "7", "3", "9", "3"]) ➞ [true, "3"]
highestPair(["K", "9", "10", "J", "Q"]) ➞ false
highestPair(["3", "5", "5", "5", "5"]) ➞ [true, "5"]
Notes
Hands with three or more of the same card still count as containing a pair (see the last example).
*/
package main
import (
"reflect"
)
func main() {
test([]string{"A", "A", "Q", "Q", "6"}, []interface{}{true, "A"})
test([]string{"J", "6", "3", "10", "8"}, false)
test([]string{"K", "7", "3", "9", "3"}, []interface{}{true, "3"})
test([]string{"K", "9", "10", "J", "Q"}, false)
test([]string{"3", "5", "5", "5", "5"}, []interface{}{true, "5"})
test([]string{"A", "A", "K", "K", "3"}, []interface{}{true, "A"})
test([]string{"A", "K", "Q", "J", "10"}, false)
test([]string{"A", "K", "K", "K", "Q"}, []interface{}{true, "K"})
test([]string{"A", "3", "3", "4", "4"}, []interface{}{true, "4"})
test([]string{"A", "K", "Q", "Q", "5"}, []interface{}{true, "Q"})
}
func test(a []string, r interface{}) {
p := highest(a)
assert(reflect.DeepEqual(p, r))
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func highest(a []string) interface{} {
m := make(map[string]int)
for _, v := range a {
m[v]++
}
var s string
for k, v := range m {
if v >= 2 && si(k) > si(s) {
s = k
}
}
if s == "" {
return false
}
return []interface{}{true, s}
}
func si(s string) int {
switch s {
case "A":
return 14
case "K":
return 13
case "Q":
return 12
case "J":
return 11
case "10":
return 10
case "9", "8", "7", "6", "5", "4", "3", "2", "1":
return int(s[0] - '0')
default:
return 0
case "":
return -1
}
}
|
package server
import (
"testing"
//"fmt"
"time"
)
//import "fmt"
func TestStart(t *testing.T) {
var a = 1
proc := QProc{}
proc.Start()
a++
time.Sleep(10 * time.Second)
//fmt.Println("before push")
proc.Push()
time.Sleep(10 * time.Second)
}
// func TestPush(){
// }
// func TestPop(){
// }
|
package unionfind
// Quick Find:查找快;union操作O(n)
// 元素 0 1 2 3 4 5 6 7 8 9
// -------------------
// id 0 1 0 1 0 1 0 1 0 1
// 每个连在一起的组有相同的id
type UnionFind1 struct {
id []int // id相同连接
count int // 元素个数
}
func NewUnionFind1(n int) *UnionFind1 {
uf := new(UnionFind1)
uf.count = n
uf.id = make([]int, n)
for i := 0; i < n; i++ {
// 初始化时每个元素独立一组,所有无连接
uf.id[i] = i
}
return uf
}
// 参数:元素;返回:id
// O(1)
func (uf UnionFind1) Find(p int) int {
if p >= 0 && p <= uf.count {
return uf.id[p]
}
return -1
}
// 参数:元素p和q
func (uf UnionFind1) IsConnected(p, q int) bool {
return uf.Find(p) == uf.Find(q)
}
// O(n):大数据量很慢
func (uf *UnionFind1) Union(p, q int) {
pId := uf.Find(p)
qId := uf.Find(q)
if pId == qId {
return
}
for i := 0; i < uf.count; i++ {
if uf.id[i] == pId {
uf.id[i] = qId
}
}
}
|
package driver
import (
"database/sql"
"embed"
"encoding/base64"
"fmt"
"io/fs"
"strconv"
"strings"
"github.com/friendsofgo/errors"
"github.com/go-sql-driver/mysql"
"github.com/volatiletech/strmangle"
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/volatiletech/sqlboiler/v4/importers"
)
//go:embed override
var templates embed.FS
func init() {
drivers.RegisterFromInit("mysql", &MySQLDriver{})
}
// Assemble is more useful for calling into the library so you don't
// have to instantiate an empty type.
func Assemble(config drivers.Config) (dbinfo *drivers.DBInfo, err error) {
driver := MySQLDriver{}
return driver.Assemble(config)
}
// MySQLDriver holds the database connection string and a handle
// to the database connection.
type MySQLDriver struct {
connStr string
conn *sql.DB
addEnumTypes bool
enumNullPrefix string
tinyIntAsInt bool
configForeignKeys []drivers.ForeignKey
}
// Templates that should be added/overridden
func (MySQLDriver) Templates() (map[string]string, error) {
tpls := make(map[string]string)
fs.WalkDir(templates, "override", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
b, err := fs.ReadFile(templates, path)
if err != nil {
return err
}
tpls[strings.Replace(path, "override/", "", 1)] = base64.StdEncoding.EncodeToString(b)
return nil
})
return tpls, nil
}
// Assemble all the information we need to provide back to the driver
func (m *MySQLDriver) Assemble(config drivers.Config) (dbinfo *drivers.DBInfo, err error) {
defer func() {
if r := recover(); r != nil && err == nil {
dbinfo = nil
err = r.(error)
}
}()
user := config.MustString(drivers.ConfigUser)
pass, _ := config.String(drivers.ConfigPass)
dbname := config.MustString(drivers.ConfigDBName)
host := config.MustString(drivers.ConfigHost)
port := config.DefaultInt(drivers.ConfigPort, 3306)
sslmode := config.DefaultString(drivers.ConfigSSLMode, "true")
schema := dbname
whitelist, _ := config.StringSlice(drivers.ConfigWhitelist)
blacklist, _ := config.StringSlice(drivers.ConfigBlacklist)
concurrency := config.DefaultInt(drivers.ConfigConcurrency, drivers.DefaultConcurrency)
tinyIntAsIntIntf, ok := config["tinyint_as_int"]
if ok {
if b, ok := tinyIntAsIntIntf.(bool); ok {
m.tinyIntAsInt = b
}
}
m.addEnumTypes, _ = config[drivers.ConfigAddEnumTypes].(bool)
m.enumNullPrefix = strmangle.TitleCase(config.DefaultString(drivers.ConfigEnumNullPrefix, "Null"))
m.connStr = MySQLBuildQueryString(user, pass, dbname, host, port, sslmode)
m.configForeignKeys = config.MustForeignKeys(drivers.ConfigForeignKeys)
m.conn, err = sql.Open("mysql", m.connStr)
if err != nil {
return nil, errors.Wrap(err, "sqlboiler-mysql failed to connect to database")
}
defer func() {
if e := m.conn.Close(); e != nil {
dbinfo = nil
err = e
}
}()
dbinfo = &drivers.DBInfo{
Dialect: drivers.Dialect{
LQ: '`',
RQ: '`',
UseLastInsertID: true,
UseSchema: false,
},
}
dbinfo.Tables, err = drivers.TablesConcurrently(m, schema, whitelist, blacklist, concurrency)
if err != nil {
return nil, err
}
return dbinfo, err
}
// MySQLBuildQueryString builds a query string for MySQL.
func MySQLBuildQueryString(user, pass, dbname, host string, port int, sslmode string) string {
config := mysql.NewConfig()
config.User = user
if len(pass) != 0 {
config.Passwd = pass
}
config.DBName = dbname
config.Net = "tcp"
config.Addr = host
if port == 0 {
port = 3306
}
config.Addr += ":" + strconv.Itoa(port)
config.TLSConfig = sslmode
// MySQL is a bad, and by default reads date/datetime into a []byte
// instead of a time.Time. Tell it to stop being a bad.
config.ParseTime = true
return config.FormatDSN()
}
// TableNames connects to the mysql database and
// retrieves all table names from the information_schema where the
// table schema is public.
func (m *MySQLDriver) TableNames(schema string, whitelist, blacklist []string) ([]string, error) {
var names []string
query := `select table_name from information_schema.tables where table_schema = ? and table_type = 'BASE TABLE'`
args := []interface{}{schema}
if len(whitelist) > 0 {
tables := drivers.TablesFromList(whitelist)
if len(tables) > 0 {
query += fmt.Sprintf(" and table_name in (%s)", strings.Repeat(",?", len(tables))[1:])
for _, w := range tables {
args = append(args, w)
}
}
} else if len(blacklist) > 0 {
tables := drivers.TablesFromList(blacklist)
if len(tables) > 0 {
query += fmt.Sprintf(" and table_name not in (%s)", strings.Repeat(",?", len(tables))[1:])
for _, b := range tables {
args = append(args, b)
}
}
}
query += ` order by table_name;`
rows, err := m.conn.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
names = append(names, name)
}
return names, nil
}
// ViewNames connects to the postgres database and
// retrieves all view names from the information_schema where the
// view schema is schema. It uses a whitelist and blacklist.
func (m *MySQLDriver) ViewNames(schema string, whitelist, blacklist []string) ([]string, error) {
var names []string
query := `select table_name from information_schema.views where table_schema = ?`
args := []interface{}{schema}
if len(whitelist) > 0 {
tables := drivers.TablesFromList(whitelist)
if len(tables) > 0 {
query += fmt.Sprintf(" and table_name in (%s)", strings.Repeat(",?", len(tables))[1:])
for _, w := range tables {
args = append(args, w)
}
}
} else if len(blacklist) > 0 {
tables := drivers.TablesFromList(blacklist)
if len(tables) > 0 {
query += fmt.Sprintf(" and table_name not in (%s)", strings.Repeat(",?", len(tables))[1:])
for _, b := range tables {
args = append(args, b)
}
}
}
query += ` order by table_name;`
rows, err := m.conn.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
names = append(names, name)
}
return names, nil
}
// ViewCapabilities return what actions are allowed for a view.
func (m *MySQLDriver) ViewCapabilities(schema, name string) (drivers.ViewCapabilities, error) {
capabilities := drivers.ViewCapabilities{
// No definite way to check if a view is insertable
// See: https://dba.stackexchange.com/questions/285451/does-mysql-have-a-built-in-way-to-tell-whether-a-view-is-insertable-not-just-up?newreg=e6c571353a0948638bec10cf7f8c6f6f
CanInsert: false,
CanUpsert: false,
}
return capabilities, nil
}
func (m *MySQLDriver) ViewColumns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {
return m.Columns(schema, tableName, whitelist, blacklist)
}
// Columns takes a table name and attempts to retrieve the table information
// from the database information_schema.columns. It retrieves the column names
// and column types and returns those as a []Column after TranslateColumnType()
// converts the SQL types to Go types, for example: "varchar" to "string"
func (m *MySQLDriver) Columns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {
var columns []drivers.Column
args := []interface{}{tableName, tableName, schema, schema, schema, schema, tableName, tableName, schema}
query := `
select
c.column_name,
c.column_type,
c.column_comment,
if(c.data_type = 'enum', c.column_type, c.data_type),
if(extra = 'auto_increment','auto_increment',
if(version() like '%MariaDB%' and c.column_default = 'NULL', '',
if(version() like '%MariaDB%' and c.data_type in ('varchar','char','binary','date','datetime','time'),
replace(substring(c.column_default,2,length(c.column_default)-2),'\'\'','\''),
c.column_default))),
c.is_nullable = 'YES',
(c.extra = 'STORED GENERATED' OR c.extra = 'VIRTUAL GENERATED') is_generated,
exists (
select c.column_name
from information_schema.table_constraints tc
inner join information_schema.key_column_usage kcu
on tc.constraint_name = kcu.constraint_name
where tc.table_name = ? and kcu.table_name = ? and tc.table_schema = ? and kcu.table_schema = ? and
c.column_name = kcu.column_name and
(tc.constraint_type = 'PRIMARY KEY' or tc.constraint_type = 'UNIQUE') and
(select count(*) from information_schema.key_column_usage where table_schema = ? and
constraint_schema = ? and table_name = ? and constraint_name = tc.constraint_name) = 1
) as is_unique
from information_schema.columns as c
where table_name = ? and table_schema = ?`
if len(whitelist) > 0 {
cols := drivers.ColumnsFromList(whitelist, tableName)
if len(cols) > 0 {
query += fmt.Sprintf(" and c.column_name in (%s)", strings.Repeat(",?", len(cols))[1:])
for _, w := range cols {
args = append(args, w)
}
}
} else if len(blacklist) > 0 {
cols := drivers.ColumnsFromList(blacklist, tableName)
if len(cols) > 0 {
query += fmt.Sprintf(" and c.column_name not in (%s)", strings.Repeat(",?", len(cols))[1:])
for _, w := range cols {
args = append(args, w)
}
}
}
query += ` order by c.ordinal_position;`
rows, err := m.conn.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var colName, colFullType, colComment, colType string
var nullable, generated, unique bool
var defaultValue *string
if err := rows.Scan(&colName, &colFullType, &colComment, &colType, &defaultValue, &nullable, &generated, &unique); err != nil {
return nil, errors.Wrapf(err, "unable to scan for table %s", tableName)
}
column := drivers.Column{
Name: colName,
Comment: colComment,
FullDBType: colFullType, // example: tinyint(1) instead of tinyint
DBType: colType,
Nullable: nullable,
Unique: unique,
AutoGenerated: generated,
}
if defaultValue != nil {
column.Default = *defaultValue
}
// A generated column technically has a default value
if column.Default == "" && column.AutoGenerated {
column.Default = "AUTO_GENERATED"
}
columns = append(columns, column)
}
return columns, nil
}
// PrimaryKeyInfo looks up the primary key for a table.
func (m *MySQLDriver) PrimaryKeyInfo(schema, tableName string) (*drivers.PrimaryKey, error) {
pkey := &drivers.PrimaryKey{}
var err error
query := `
select tc.constraint_name
from information_schema.table_constraints as tc
where tc.table_name = ? and tc.constraint_type = 'PRIMARY KEY' and tc.table_schema = ?;`
row := m.conn.QueryRow(query, tableName, schema)
if err = row.Scan(&pkey.Name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
queryColumns := `
select kcu.column_name
from information_schema.key_column_usage as kcu
where table_name = ? and constraint_name = ? and table_schema = ?
order by kcu.ordinal_position;`
var rows *sql.Rows
if rows, err = m.conn.Query(queryColumns, tableName, pkey.Name, schema); err != nil {
return nil, err
}
defer rows.Close()
var columns []string
for rows.Next() {
var column string
err = rows.Scan(&column)
if err != nil {
return nil, err
}
columns = append(columns, column)
}
if err = rows.Err(); err != nil {
return nil, err
}
pkey.Columns = columns
return pkey, nil
}
// ForeignKeyInfo retrieves the foreign keys for a given table name.
func (m *MySQLDriver) ForeignKeyInfo(schema, tableName string) ([]drivers.ForeignKey, error) {
dbForeignKeys, err := m.foreignKeyInfoFromDB(schema, tableName)
if err != nil {
return nil, errors.Wrap(err, "read foreign keys info from db")
}
return drivers.CombineConfigAndDBForeignKeys(m.configForeignKeys, tableName, dbForeignKeys), nil
}
func (m *MySQLDriver) foreignKeyInfoFromDB(schema, tableName string) ([]drivers.ForeignKey, error) {
var fkeys []drivers.ForeignKey
query := `
select constraint_name, table_name, column_name, referenced_table_name, referenced_column_name
from information_schema.key_column_usage
where table_schema = ? and referenced_table_schema = ? and table_name = ?
order by constraint_name, table_name, column_name, referenced_table_name, referenced_column_name
`
var rows *sql.Rows
var err error
if rows, err = m.conn.Query(query, schema, schema, tableName); err != nil {
return nil, err
}
for rows.Next() {
var fkey drivers.ForeignKey
var sourceTable string
fkey.Table = tableName
err = rows.Scan(&fkey.Name, &sourceTable, &fkey.Column, &fkey.ForeignTable, &fkey.ForeignColumn)
if err != nil {
return nil, err
}
fkeys = append(fkeys, fkey)
}
if err = rows.Err(); err != nil {
return nil, err
}
return fkeys, nil
}
// TranslateColumnType converts mysql database types to Go types, for example
// "varchar" to "string" and "bigint" to "int64". It returns this parsed data
// as a Column object.
// Deprecated: for MySQL enum types to be created properly TranslateTableColumnType method should be used instead.
func (m *MySQLDriver) TranslateColumnType(drivers.Column) drivers.Column {
panic("TranslateTableColumnType should be called")
}
// TranslateTableColumnType converts mysql database types to Go types, for example
// "varchar" to "string" and "bigint" to "int64". It returns this parsed data
// as a Column object.
func (m *MySQLDriver) TranslateTableColumnType(c drivers.Column, tableName string) drivers.Column {
unsigned := strings.Contains(c.FullDBType, "unsigned")
if c.Nullable {
switch c.DBType {
case "tinyint":
// map tinyint(1) to bool if TinyintAsBool is true
if !m.tinyIntAsInt && c.FullDBType == "tinyint(1)" {
c.Type = "null.Bool"
} else if unsigned {
c.Type = "null.Uint8"
} else {
c.Type = "null.Int8"
}
case "smallint":
if unsigned {
c.Type = "null.Uint16"
} else {
c.Type = "null.Int16"
}
case "mediumint":
if unsigned {
c.Type = "null.Uint32"
} else {
c.Type = "null.Int32"
}
case "int", "integer":
if unsigned {
c.Type = "null.Uint"
} else {
c.Type = "null.Int"
}
case "bigint":
if unsigned {
c.Type = "null.Uint64"
} else {
c.Type = "null.Int64"
}
case "float":
c.Type = "null.Float32"
case "double", "double precision", "real":
c.Type = "null.Float64"
case "boolean", "bool":
c.Type = "null.Bool"
case "date", "datetime", "timestamp":
c.Type = "null.Time"
case "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob":
c.Type = "null.Bytes"
case "numeric", "decimal", "dec", "fixed":
c.Type = "types.NullDecimal"
case "json":
c.Type = "null.JSON"
default:
if len(strmangle.ParseEnumVals(c.DBType)) > 0 && m.addEnumTypes {
c.Type = strmangle.TitleCase(tableName) + m.enumNullPrefix + strmangle.TitleCase(c.Name)
} else {
c.Type = "null.String"
}
}
} else {
switch c.DBType {
case "tinyint":
// map tinyint(1) to bool if TinyintAsBool is true
if !m.tinyIntAsInt && c.FullDBType == "tinyint(1)" {
c.Type = "bool"
} else if unsigned {
c.Type = "uint8"
} else {
c.Type = "int8"
}
case "smallint":
if unsigned {
c.Type = "uint16"
} else {
c.Type = "int16"
}
case "mediumint":
if unsigned {
c.Type = "uint32"
} else {
c.Type = "int32"
}
case "int", "integer":
if unsigned {
c.Type = "uint"
} else {
c.Type = "int"
}
case "bigint":
if unsigned {
c.Type = "uint64"
} else {
c.Type = "int64"
}
case "float":
c.Type = "float32"
case "double", "double precision", "real":
c.Type = "float64"
case "boolean", "bool":
c.Type = "bool"
case "date", "datetime", "timestamp":
c.Type = "time.Time"
case "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob":
c.Type = "[]byte"
case "numeric", "decimal", "dec", "fixed":
c.Type = "types.Decimal"
case "json":
c.Type = "types.JSON"
default:
if len(strmangle.ParseEnumVals(c.DBType)) > 0 && m.addEnumTypes {
c.Type = strmangle.TitleCase(tableName) + strmangle.TitleCase(c.Name)
} else {
c.Type = "string"
}
}
}
return c
}
// Imports returns important imports for the driver
func (MySQLDriver) Imports() (col importers.Collection, err error) {
col.All = importers.Set{
Standard: importers.List{
`"strconv"`,
},
}
col.Singleton = importers.Map{
"mysql_upsert": {
Standard: importers.List{
`"fmt"`,
`"strings"`,
},
ThirdParty: importers.List{
`"github.com/volatiletech/strmangle"`,
`"github.com/volatiletech/sqlboiler/v4/drivers"`,
},
},
}
col.TestSingleton = importers.Map{
"mysql_suites_test": {
Standard: importers.List{
`"testing"`,
},
},
"mysql_main_test": {
Standard: importers.List{
`"bytes"`,
`"database/sql"`,
`"fmt"`,
`"io"`,
`"os"`,
`"os/exec"`,
`"regexp"`,
`"strings"`,
},
ThirdParty: importers.List{
`"github.com/kat-co/vala"`,
`"github.com/friendsofgo/errors"`,
`"github.com/spf13/viper"`,
`"github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-mysql/driver"`,
`"github.com/volatiletech/randomize"`,
`_ "github.com/go-sql-driver/mysql"`,
},
},
}
col.BasedOnType = importers.Map{
"null.Float32": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Float64": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int8": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int16": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int32": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int64": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint8": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint16": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint32": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint64": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.String": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Bool": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Time": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Bytes": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.JSON": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"time.Time": {
Standard: importers.List{`"time"`},
},
"types.JSON": {
ThirdParty: importers.List{`"github.com/volatiletech/sqlboiler/v4/types"`},
},
"types.Decimal": {
ThirdParty: importers.List{`"github.com/volatiletech/sqlboiler/v4/types"`},
},
"types.NullDecimal": {
ThirdParty: importers.List{`"github.com/volatiletech/sqlboiler/v4/types"`},
},
}
return col, err
}
|
package models
import (
"github.com/astaxie/beego/orm"
"time"
)
//提币配置表
type TokenskyTibiConfigQueryParam struct {
BaseQueryParam
StartTime string `json:"startTime"` //开始时间
EndTime string `json:"endTime"` //截止时间
}
func (a *TokenskyTibiConfig) TableName() string {
return TokenskyTibiConfigTBName()
}
//提币配置表
type TokenskyTibiConfig struct {
Id int `orm:"pk;column(id)"json:"id"form:"id"`
CoinType string `orm:"column(coin_type)"json:"coinType"form:"coinType"`
//单次最小提币数量
Min float64 `orm:"column(min)"json:"min"form:"min"`
//单次最多提币数量
Max float64 `orm:"column(max)"json:"max"form:"max"`
//当日限额
CurDayQuantity float64 `orm:"column(cur_day_quantity)"json:"curDayQuantity"form:"curDayQuantity"`
//百分比手续费
ServiceCharge float64 `orm:"column(service_charge)"json:"serviceCharge"form:"serviceCharge"`
//基础手续费
BaseServiceCharge float64 `orm:"column(base_service_charge)"json:"baseServiceCharge"form:"baseServiceCharge"`
AdminId int `orm:"column(admin_id)"json:"-"form:"-"`
Status int `orm:"column(status)"json:"status"form:"status"`
CreateTime time.Time `orm:"auto_now_add;type(datetime);column(create_time)"json:"createTime"form:"createTime"`
}
func (a *TokenskyTibiConfigBak) TableName() string {
return TokenskyTibiConfigBakTBName()
}
type TokenskyTibiConfigBak struct {
TokenskyTibiConfig
}
//获取分页数据
func TokenskyTibiConfigPageList(params *TokenskyTibiConfigQueryParam) ([]*TokenskyTibiConfig, int64) {
o := orm.NewOrm()
query := o.QueryTable(TokenskyTibiConfigTBName())
data := make([]*TokenskyTibiConfig, 0)
//默认排序
sortorder := "id"
switch params.Sort {
case "id":
sortorder = "id"
}
if params.Order == "desc" {
sortorder = "-" + sortorder
}
total, _ := query.Count()
if total > 0 {
query.OrderBy(sortorder).Limit(params.Limit, (params.Offset-1)*params.Limit).All(&data)
}
return data, total
}
//获取最后一条数据 根据货币类型获取单条
func TokenskyTibiConfigGetLastOne(coinType string) *TokenskyTibiConfig {
o :=orm.NewOrm()
query := o.QueryTable(TokenskyTibiConfigTBName())
var obj TokenskyTibiConfig
if err := query.Filter("coin_type__iexact", coinType).One(&obj); err == nil {
return &obj
} else {
return nil
}
}
|
package processor
import (
"encoding/json"
"fmt"
"net"
)
type DnsInfo struct {
Upstream_dns []string
Upstream_dns_file string
Bootstrap_dns []string
Protection_enabled bool
Ratelimit int
Blocking_mode string
Blocking_ipv4 string
Blocking_ipv6 string
Edns_cs_enabled bool
Dnssec_enabled bool
Disable_ipv6 bool
Upstream_mode string
Cache_size int
Cache_ttl_min int
Cache_ttl_max int
}
func GenerateNew(old string, agh, dns []net.IP, containeronly, verbose bool) (bool, string) {
var dnsconf DnsInfo
json.Unmarshal([]byte(old), &dnsconf)
if verbose {
fmt.Println("Old DNS:")
PrintArr(dnsconf.Upstream_dns)
}
var dnsar []string
if containeronly {
dnsar = Clean(dnsconf.Upstream_dns)
} else {
dnsar = RemoveAll(dnsconf.Upstream_dns, agh)
}
dnsar = AddAll(dnsar, dns)
if verbose {
fmt.Println("New DNS:")
PrintArr(dnsar)
}
dnsconf.Upstream_dns = dnsar
b, err := json.Marshal(dnsconf)
if err != nil {
return false, ""
}
return true, string(b)
}
func Clean(cur []string) []string {
res := []string{}
for _, i := range cur {
if i[0] == '[' {
res = append(res, i)
}
}
return res
}
func RemoveAll(cur []string, agh []net.IP) []string {
res := []string{}
for _, i := range cur {
if !IContains(agh, i) {
res = append(res, i)
}
}
return res
}
func AddAll(cur []string, dns []net.IP) []string {
for _, i := range dns {
if !SContains(cur, i.String()) {
cur = append(cur, i.String())
}
}
return cur
}
func IContains(ia []net.IP, ci string) bool {
for _, i := range ia {
if i.String() == ci {
return true
}
}
return false
}
func SContains(ia []string, ci string) bool {
for _, i := range ia {
if i == ci {
return true
}
}
return false
}
func PrintArr(strar []string) {
for _, s := range strar {
fmt.Println(" ", s)
}
}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// 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 server
import (
"context"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/cloudbuildv2/alpha/cloudbuildv2_alpha_go_proto"
emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha"
)
// ConnectionServer implements the gRPC interface for Connection.
type ConnectionServer struct{}
// ProtoToConnectionInstallationStateStageEnum converts a ConnectionInstallationStateStageEnum enum from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionInstallationStateStageEnum(e alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum) *alpha.ConnectionInstallationStateStageEnum {
if e == 0 {
return nil
}
if n, ok := alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum_name[int32(e)]; ok {
e := alpha.ConnectionInstallationStateStageEnum(n[len("Cloudbuildv2AlphaConnectionInstallationStateStageEnum"):])
return &e
}
return nil
}
// ProtoToConnectionGithubConfig converts a ConnectionGithubConfig object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGithubConfig(p *alphapb.Cloudbuildv2AlphaConnectionGithubConfig) *alpha.ConnectionGithubConfig {
if p == nil {
return nil
}
obj := &alpha.ConnectionGithubConfig{
AuthorizerCredential: ProtoToCloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential(p.GetAuthorizerCredential()),
AppInstallationId: dcl.Int64OrNil(p.GetAppInstallationId()),
}
return obj
}
// ProtoToConnectionGithubConfigAuthorizerCredential converts a ConnectionGithubConfigAuthorizerCredential object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential(p *alphapb.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential) *alpha.ConnectionGithubConfigAuthorizerCredential {
if p == nil {
return nil
}
obj := &alpha.ConnectionGithubConfigAuthorizerCredential{
OAuthTokenSecretVersion: dcl.StringOrNil(p.GetOauthTokenSecretVersion()),
Username: dcl.StringOrNil(p.GetUsername()),
}
return obj
}
// ProtoToConnectionGithubEnterpriseConfig converts a ConnectionGithubEnterpriseConfig object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfig(p *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig) *alpha.ConnectionGithubEnterpriseConfig {
if p == nil {
return nil
}
obj := &alpha.ConnectionGithubEnterpriseConfig{
HostUri: dcl.StringOrNil(p.GetHostUri()),
AppId: dcl.Int64OrNil(p.GetAppId()),
AppSlug: dcl.StringOrNil(p.GetAppSlug()),
PrivateKeySecretVersion: dcl.StringOrNil(p.GetPrivateKeySecretVersion()),
WebhookSecretSecretVersion: dcl.StringOrNil(p.GetWebhookSecretSecretVersion()),
AppInstallationId: dcl.Int64OrNil(p.GetAppInstallationId()),
ServiceDirectoryConfig: ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig(p.GetServiceDirectoryConfig()),
SslCa: dcl.StringOrNil(p.GetSslCa()),
}
return obj
}
// ProtoToConnectionGithubEnterpriseConfigServiceDirectoryConfig converts a ConnectionGithubEnterpriseConfigServiceDirectoryConfig object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig(p *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig) *alpha.ConnectionGithubEnterpriseConfigServiceDirectoryConfig {
if p == nil {
return nil
}
obj := &alpha.ConnectionGithubEnterpriseConfigServiceDirectoryConfig{
Service: dcl.StringOrNil(p.GetService()),
}
return obj
}
// ProtoToConnectionGitlabConfig converts a ConnectionGitlabConfig object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGitlabConfig(p *alphapb.Cloudbuildv2AlphaConnectionGitlabConfig) *alpha.ConnectionGitlabConfig {
if p == nil {
return nil
}
obj := &alpha.ConnectionGitlabConfig{
HostUri: dcl.StringOrNil(p.GetHostUri()),
WebhookSecretSecretVersion: dcl.StringOrNil(p.GetWebhookSecretSecretVersion()),
ReadAuthorizerCredential: ProtoToCloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredential(p.GetReadAuthorizerCredential()),
AuthorizerCredential: ProtoToCloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredential(p.GetAuthorizerCredential()),
ServiceDirectoryConfig: ProtoToCloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfig(p.GetServiceDirectoryConfig()),
SslCa: dcl.StringOrNil(p.GetSslCa()),
ServerVersion: dcl.StringOrNil(p.GetServerVersion()),
}
return obj
}
// ProtoToConnectionGitlabConfigReadAuthorizerCredential converts a ConnectionGitlabConfigReadAuthorizerCredential object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredential(p *alphapb.Cloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredential) *alpha.ConnectionGitlabConfigReadAuthorizerCredential {
if p == nil {
return nil
}
obj := &alpha.ConnectionGitlabConfigReadAuthorizerCredential{
UserTokenSecretVersion: dcl.StringOrNil(p.GetUserTokenSecretVersion()),
Username: dcl.StringOrNil(p.GetUsername()),
}
return obj
}
// ProtoToConnectionGitlabConfigAuthorizerCredential converts a ConnectionGitlabConfigAuthorizerCredential object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredential(p *alphapb.Cloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredential) *alpha.ConnectionGitlabConfigAuthorizerCredential {
if p == nil {
return nil
}
obj := &alpha.ConnectionGitlabConfigAuthorizerCredential{
UserTokenSecretVersion: dcl.StringOrNil(p.GetUserTokenSecretVersion()),
Username: dcl.StringOrNil(p.GetUsername()),
}
return obj
}
// ProtoToConnectionGitlabConfigServiceDirectoryConfig converts a ConnectionGitlabConfigServiceDirectoryConfig object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfig(p *alphapb.Cloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfig) *alpha.ConnectionGitlabConfigServiceDirectoryConfig {
if p == nil {
return nil
}
obj := &alpha.ConnectionGitlabConfigServiceDirectoryConfig{
Service: dcl.StringOrNil(p.GetService()),
}
return obj
}
// ProtoToConnectionInstallationState converts a ConnectionInstallationState object from its proto representation.
func ProtoToCloudbuildv2AlphaConnectionInstallationState(p *alphapb.Cloudbuildv2AlphaConnectionInstallationState) *alpha.ConnectionInstallationState {
if p == nil {
return nil
}
obj := &alpha.ConnectionInstallationState{
Stage: ProtoToCloudbuildv2AlphaConnectionInstallationStateStageEnum(p.GetStage()),
Message: dcl.StringOrNil(p.GetMessage()),
ActionUri: dcl.StringOrNil(p.GetActionUri()),
}
return obj
}
// ProtoToConnection converts a Connection resource from its proto representation.
func ProtoToConnection(p *alphapb.Cloudbuildv2AlphaConnection) *alpha.Connection {
obj := &alpha.Connection{
Name: dcl.StringOrNil(p.GetName()),
CreateTime: dcl.StringOrNil(p.GetCreateTime()),
UpdateTime: dcl.StringOrNil(p.GetUpdateTime()),
GithubConfig: ProtoToCloudbuildv2AlphaConnectionGithubConfig(p.GetGithubConfig()),
GithubEnterpriseConfig: ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfig(p.GetGithubEnterpriseConfig()),
GitlabConfig: ProtoToCloudbuildv2AlphaConnectionGitlabConfig(p.GetGitlabConfig()),
InstallationState: ProtoToCloudbuildv2AlphaConnectionInstallationState(p.GetInstallationState()),
Disabled: dcl.Bool(p.GetDisabled()),
Reconciling: dcl.Bool(p.GetReconciling()),
Etag: dcl.StringOrNil(p.GetEtag()),
Project: dcl.StringOrNil(p.GetProject()),
Location: dcl.StringOrNil(p.GetLocation()),
}
return obj
}
// ConnectionInstallationStateStageEnumToProto converts a ConnectionInstallationStateStageEnum enum to its proto representation.
func Cloudbuildv2AlphaConnectionInstallationStateStageEnumToProto(e *alpha.ConnectionInstallationStateStageEnum) alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum {
if e == nil {
return alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum(0)
}
if v, ok := alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum_value["ConnectionInstallationStateStageEnum"+string(*e)]; ok {
return alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum(v)
}
return alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum(0)
}
// ConnectionGithubConfigToProto converts a ConnectionGithubConfig object to its proto representation.
func Cloudbuildv2AlphaConnectionGithubConfigToProto(o *alpha.ConnectionGithubConfig) *alphapb.Cloudbuildv2AlphaConnectionGithubConfig {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGithubConfig{}
p.SetAuthorizerCredential(Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredentialToProto(o.AuthorizerCredential))
p.SetAppInstallationId(dcl.ValueOrEmptyInt64(o.AppInstallationId))
return p
}
// ConnectionGithubConfigAuthorizerCredentialToProto converts a ConnectionGithubConfigAuthorizerCredential object to its proto representation.
func Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredentialToProto(o *alpha.ConnectionGithubConfigAuthorizerCredential) *alphapb.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential{}
p.SetOauthTokenSecretVersion(dcl.ValueOrEmptyString(o.OAuthTokenSecretVersion))
p.SetUsername(dcl.ValueOrEmptyString(o.Username))
return p
}
// ConnectionGithubEnterpriseConfigToProto converts a ConnectionGithubEnterpriseConfig object to its proto representation.
func Cloudbuildv2AlphaConnectionGithubEnterpriseConfigToProto(o *alpha.ConnectionGithubEnterpriseConfig) *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig{}
p.SetHostUri(dcl.ValueOrEmptyString(o.HostUri))
p.SetAppId(dcl.ValueOrEmptyInt64(o.AppId))
p.SetAppSlug(dcl.ValueOrEmptyString(o.AppSlug))
p.SetPrivateKeySecretVersion(dcl.ValueOrEmptyString(o.PrivateKeySecretVersion))
p.SetWebhookSecretSecretVersion(dcl.ValueOrEmptyString(o.WebhookSecretSecretVersion))
p.SetAppInstallationId(dcl.ValueOrEmptyInt64(o.AppInstallationId))
p.SetServiceDirectoryConfig(Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfigToProto(o.ServiceDirectoryConfig))
p.SetSslCa(dcl.ValueOrEmptyString(o.SslCa))
return p
}
// ConnectionGithubEnterpriseConfigServiceDirectoryConfigToProto converts a ConnectionGithubEnterpriseConfigServiceDirectoryConfig object to its proto representation.
func Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfigToProto(o *alpha.ConnectionGithubEnterpriseConfigServiceDirectoryConfig) *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig{}
p.SetService(dcl.ValueOrEmptyString(o.Service))
return p
}
// ConnectionGitlabConfigToProto converts a ConnectionGitlabConfig object to its proto representation.
func Cloudbuildv2AlphaConnectionGitlabConfigToProto(o *alpha.ConnectionGitlabConfig) *alphapb.Cloudbuildv2AlphaConnectionGitlabConfig {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGitlabConfig{}
p.SetHostUri(dcl.ValueOrEmptyString(o.HostUri))
p.SetWebhookSecretSecretVersion(dcl.ValueOrEmptyString(o.WebhookSecretSecretVersion))
p.SetReadAuthorizerCredential(Cloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredentialToProto(o.ReadAuthorizerCredential))
p.SetAuthorizerCredential(Cloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredentialToProto(o.AuthorizerCredential))
p.SetServiceDirectoryConfig(Cloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfigToProto(o.ServiceDirectoryConfig))
p.SetSslCa(dcl.ValueOrEmptyString(o.SslCa))
p.SetServerVersion(dcl.ValueOrEmptyString(o.ServerVersion))
return p
}
// ConnectionGitlabConfigReadAuthorizerCredentialToProto converts a ConnectionGitlabConfigReadAuthorizerCredential object to its proto representation.
func Cloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredentialToProto(o *alpha.ConnectionGitlabConfigReadAuthorizerCredential) *alphapb.Cloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredential {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGitlabConfigReadAuthorizerCredential{}
p.SetUserTokenSecretVersion(dcl.ValueOrEmptyString(o.UserTokenSecretVersion))
p.SetUsername(dcl.ValueOrEmptyString(o.Username))
return p
}
// ConnectionGitlabConfigAuthorizerCredentialToProto converts a ConnectionGitlabConfigAuthorizerCredential object to its proto representation.
func Cloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredentialToProto(o *alpha.ConnectionGitlabConfigAuthorizerCredential) *alphapb.Cloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredential {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGitlabConfigAuthorizerCredential{}
p.SetUserTokenSecretVersion(dcl.ValueOrEmptyString(o.UserTokenSecretVersion))
p.SetUsername(dcl.ValueOrEmptyString(o.Username))
return p
}
// ConnectionGitlabConfigServiceDirectoryConfigToProto converts a ConnectionGitlabConfigServiceDirectoryConfig object to its proto representation.
func Cloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfigToProto(o *alpha.ConnectionGitlabConfigServiceDirectoryConfig) *alphapb.Cloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfig {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionGitlabConfigServiceDirectoryConfig{}
p.SetService(dcl.ValueOrEmptyString(o.Service))
return p
}
// ConnectionInstallationStateToProto converts a ConnectionInstallationState object to its proto representation.
func Cloudbuildv2AlphaConnectionInstallationStateToProto(o *alpha.ConnectionInstallationState) *alphapb.Cloudbuildv2AlphaConnectionInstallationState {
if o == nil {
return nil
}
p := &alphapb.Cloudbuildv2AlphaConnectionInstallationState{}
p.SetStage(Cloudbuildv2AlphaConnectionInstallationStateStageEnumToProto(o.Stage))
p.SetMessage(dcl.ValueOrEmptyString(o.Message))
p.SetActionUri(dcl.ValueOrEmptyString(o.ActionUri))
return p
}
// ConnectionToProto converts a Connection resource to its proto representation.
func ConnectionToProto(resource *alpha.Connection) *alphapb.Cloudbuildv2AlphaConnection {
p := &alphapb.Cloudbuildv2AlphaConnection{}
p.SetName(dcl.ValueOrEmptyString(resource.Name))
p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))
p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))
p.SetGithubConfig(Cloudbuildv2AlphaConnectionGithubConfigToProto(resource.GithubConfig))
p.SetGithubEnterpriseConfig(Cloudbuildv2AlphaConnectionGithubEnterpriseConfigToProto(resource.GithubEnterpriseConfig))
p.SetGitlabConfig(Cloudbuildv2AlphaConnectionGitlabConfigToProto(resource.GitlabConfig))
p.SetInstallationState(Cloudbuildv2AlphaConnectionInstallationStateToProto(resource.InstallationState))
p.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))
p.SetReconciling(dcl.ValueOrEmptyBool(resource.Reconciling))
p.SetEtag(dcl.ValueOrEmptyString(resource.Etag))
p.SetProject(dcl.ValueOrEmptyString(resource.Project))
p.SetLocation(dcl.ValueOrEmptyString(resource.Location))
mAnnotations := make(map[string]string, len(resource.Annotations))
for k, r := range resource.Annotations {
mAnnotations[k] = r
}
p.SetAnnotations(mAnnotations)
return p
}
// applyConnection handles the gRPC request by passing it to the underlying Connection Apply() method.
func (s *ConnectionServer) applyConnection(ctx context.Context, c *alpha.Client, request *alphapb.ApplyCloudbuildv2AlphaConnectionRequest) (*alphapb.Cloudbuildv2AlphaConnection, error) {
p := ProtoToConnection(request.GetResource())
res, err := c.ApplyConnection(ctx, p)
if err != nil {
return nil, err
}
r := ConnectionToProto(res)
return r, nil
}
// applyCloudbuildv2AlphaConnection handles the gRPC request by passing it to the underlying Connection Apply() method.
func (s *ConnectionServer) ApplyCloudbuildv2AlphaConnection(ctx context.Context, request *alphapb.ApplyCloudbuildv2AlphaConnectionRequest) (*alphapb.Cloudbuildv2AlphaConnection, error) {
cl, err := createConfigConnection(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
return s.applyConnection(ctx, cl, request)
}
// DeleteConnection handles the gRPC request by passing it to the underlying Connection Delete() method.
func (s *ConnectionServer) DeleteCloudbuildv2AlphaConnection(ctx context.Context, request *alphapb.DeleteCloudbuildv2AlphaConnectionRequest) (*emptypb.Empty, error) {
cl, err := createConfigConnection(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
return &emptypb.Empty{}, cl.DeleteConnection(ctx, ProtoToConnection(request.GetResource()))
}
// ListCloudbuildv2AlphaConnection handles the gRPC request by passing it to the underlying ConnectionList() method.
func (s *ConnectionServer) ListCloudbuildv2AlphaConnection(ctx context.Context, request *alphapb.ListCloudbuildv2AlphaConnectionRequest) (*alphapb.ListCloudbuildv2AlphaConnectionResponse, error) {
cl, err := createConfigConnection(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
resources, err := cl.ListConnection(ctx, request.GetProject(), request.GetLocation())
if err != nil {
return nil, err
}
var protos []*alphapb.Cloudbuildv2AlphaConnection
for _, r := range resources.Items {
rp := ConnectionToProto(r)
protos = append(protos, rp)
}
p := &alphapb.ListCloudbuildv2AlphaConnectionResponse{}
p.SetItems(protos)
return p, nil
}
func createConfigConnection(ctx context.Context, service_account_file string) (*alpha.Client, error) {
conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
return alpha.NewClient(conf), nil
}
|
package tmp
const HubTmp = `package hub{{$module := .ModuleName}}
import (
"fmt"
"net/http" {{if gt (len .DBS) 0}}
{{printf "\"%v/core/database\"" $module}}{{end}} {{range $i,$k := .Handlers}}
{{printf "\"%v/handlers/%v_handler\"" $module $i}}
{{printf "\"%v/handlers/%v_handler/%v_helper\"" $module $i $i}}{{end}}
{{printf "\"%v/hub/hub_helper\"" $module}}
{{printf "\"%v/helper\"" $module}}
"github.com/gorilla/mux"
)
const ( {{range $i,$k := .Handlers}}
{{printf "_%v = \"%v\"" $i $i}}{{end}}
)
type Hub interface {
GetHandler() http.Handler
Close()
}
type hub struct {
helper hub_helper.Helper {{if gt (len .DBS) 0}}
database.DB{{end}}
router *mux.Router
handler http.Handler
config *helper.Config
{{range $i,$k := .Handlers}}
{{printf "_%v %v_helper.Handler" $i $i}}{{end}}
}
func InitHub({{if gt (len .DBS) 0}}db database.DB, {{end}}conf *helper.Config) (H Hub, err error) {
hh := &hub{ {{if gt (len .DBS) 0}}
DB: db,{{end}}
router: mux.NewRouter(),
config: conf,
}
hh.SetHandler(hh.router)
hh.helper = hub_helper.InitHelper(hh)
if err = hh.intiDefault(); err != nil {
helper.Log.Warningf("initializing default is failed: %v", err)
return nil, fmt.Errorf("handler not initializing: %v", err)
}
helper.Log.Service("initializing default")
{{range $i,$k := .Handlers}}
if v, ok := conf.Handlers[{{printf "_%v" $i}}]; ok {
hh.{{printf "_%v" $i}}, err = {{print $i}}_handler.InitHandler(hh, v)
if err != nil {
return nil, fmt.Errorf("handler not initializing: %v", err)
}
helper.Log.Servicef("handler %q initializing", {{printf "_%v" $i}})
}{{end}}
hh.Router().PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(helper.UploadDir))))
H = hh
helper.Log.Service("handler initializing")
return
}
func (h *hub) Config() *helper.Config { return h.config }
func (h *hub) Helper() hub_helper.Helper { return h.helper }
func (h *hub) Router() *mux.Router { return h.router }
func (h *hub) SetHandler(hh http.Handler) { h.handler = hh }
func (h *hub) GetHandler() http.Handler { return h.handler } {{range $i,$k := .Handlers}}
{{printf "func (h *hub) %v() %v_helper.Handler { return h._%v }" (title $i) $i $i}}{{end}}
func (h *hub) Close() {}
func (h *hub) intiDefault() error { return nil }`
|
package models
import (
"fmt"
)
// PostRepository handles the CRUD for post.
type PostRepository interface {
Create(*Post) error
Get(*Query) (*Post, error)
GetAll(*Query) (*[]Post, error)
Update(*Post) error
}
// DBPostRepository ...
type DBPostRepository struct {
DB *DB
}
// NewDBPostRepository ...
func NewDBPostRepository(db *DB) PostRepository {
return DBPostRepository{db}
}
// Create handles the creation of post.
func (repo DBPostRepository) Create(post *Post) error {
tx := repo.DB.MustBegin()
_, err := tx.NamedExec("INSERT INTO posts (body, caption, user_id, ctime, utime) VALUES (:body, :caption, :user_id, :ctime, :utime)", post)
if err != nil {
return err
}
return nil
}
// Get handles the fetching of a single post record.
func (repo DBPostRepository) Get(query *Query) (*Post, error) {
post := Post{}
queryString := "SELECT * FROM posts"
if query.ByColumn != nil {
queryString = queryString + fmt.Sprintf(" WHERE %v = %v", query.ByColumn.Column, query.ByColumn.Value)
}
err := repo.DB.Get(&post, queryString)
if err != nil {
return nil, err
}
return &post, nil
}
// GetAll handles the fetching ofpost records.
func (repo DBPostRepository) GetAll(query *Query) (*[]Post, error) {
posts := []Post{}
queryString := "SELECT * FROM posts"
if query.ByColumn != nil {
queryString = queryString + fmt.Sprintf(" WHERE %v = %v", query.ByColumn.Column, query.ByColumn.Value)
}
err := repo.DB.Select(&posts, queryString)
if err != nil {
return nil, err
}
return &posts, nil
}
// Update handles the updating of post.
func (repo DBPostRepository) Update(post *Post) error {
tx := repo.DB.MustBegin()
_, err := tx.NamedExec("UPDATE posts SET body = :body, caption = :caption, user_id = :user_id, ctime = :ctime, utime = :utime WHERE id = :id", post)
if err != nil {
return err
}
return nil
}
|
/*
A "guess-that-number" game is exactly what it sounds like: a number is guessed at random by the computer, and you must guess that number to win!
The only thing the computer tells you is if your guess is below or above the number.
Your goal is to write a program that, upon initialization, guesses a number between 1 and 100 (inclusive), and asks you for your guess.
If you type a number, the program must either tell you if you won (you guessed the computer's number), or if your guess was below the computer's number, or if your guess was above the computer's number. If the user ever types "exit", the program must terminate.
Formal Inputs & Outputs
Input Description
At run-time, expect the user to input a number from 1 to 100 (inclusive), or the string "exit", and treat all other conditions as a wrong guess.
Output Description
The program must print whether or not your guess was correct, otherwise print if your guess was below or above the computer's number.
Sample Inputs & Outputs
Let "C>" be the output from your applicatgion, and "U>" be what the user types:
C> Welcome to guess-that-numbers game! I have already picked a number in [1, 100]. Please make a guess. Type "exit" to quit.
U> 1
C> Wrong. That number is below my number.
U> 50
C> Wrong. That number is above my number.
...
U> 31
C> Correct! That is my number, you win! <Program terminates>
*/
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
play()
}
func play() {
x := 1 + rand.Intn(100)
s := bufio.NewScanner(os.Stdin)
fmt.Println("C> Welcome to guess-that-numbers game! I have already picked a number in [1, 100]. Please make a guess. Type \"exit\" to quit.")
loop:
for {
fmt.Printf("U> ")
if !s.Scan() {
break
}
l := s.Text()
y, err := strconv.Atoi(l)
if err != nil {
fmt.Println("Invalid input!")
continue
}
switch {
case x < y:
fmt.Println("C> Wrong. That number is above my number.")
case x > y:
fmt.Println("C> Wrong. That number is below my number.")
default:
fmt.Println("C> Correct! That is my number, you win!")
break loop
}
}
fmt.Println()
}
|
package main
import (
"github.com/atymkiv/echo_frame_learning/blog/cmd/subscribers/service"
"github.com/atymkiv/echo_frame_learning/blog/pkg/utl/config"
"github.com/atymkiv/echo_frame_learning/blog/pkg/utl/nats"
"sync"
)
func main() {
cfg, err := config.Load("./cmd/subscribers/config.json")
checkErr(err)
natsClient, err := nats.New(cfg.Nats)
checkErr(err)
service.Subscriber(natsClient, "users")
service.Subscriber(natsClient, "posts")
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
|
package main
/*
@Time : 2020-03-12 09:28
@Author : audiRStony
@File : 06_scan.go
@Software: GoLand
*/
import (
"fmt"
)
func main() {
var (
name string
age int
gender string
)
fmt.Println(name,age,gender)
//fmt.Scan(&name,&age,&gender) //Scan 扫描,默认以空白为分隔(空格,tab,回车)
/* 输入时需严格按照格式进行输入:name:LiyaTong age:12 gender:female */
fmt.Scanf("name:%s age:%d gender:%s\n",&name,&age,&gender) //name 与age之间如有2个空格,扫描输入时也必须有2个空格
//fmt.Scanln(&name,&age,&gender) //不能使用回车扫描
fmt.Println(name,age,gender)
}
|
package main
import (
"fmt"
"sync"
"time"
)
/**
golang中的 waitGroup,其实就是类似java中的CountDownLatch
*/
type Counters struct {
mu sync.Mutex
count uint64
}
// 给 Count类添加 Incr方法
func (c *Counters) Incr() {
c.mu.Lock()
c.count++
c.mu.Unlock()
}
func (c *Counters) Count() uint64 {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
func worker(c *Counters, wg *sync.WaitGroup) {
wg.Done() // 执行一次,减少1
time.Sleep(time.Second)
c.Incr()
}
func main() {
var counter Counters
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go worker(&counter, &wg)
}
// 检查点,等待gorouting都执行完毕
wg.Wait() // 阻塞等待 由10减少为0
fmt.Println("扣减完成", counter.Count())
}
|
// Package cache provides real connection to the cache.
package cache
|
package service
import (
"fmt"
"github.com/asdine/storm/v3"
"github.com/jschweizer78/fusion-ng/pkg/service/model"
"github.com/mitchellh/mapstructure"
)
// SrvUsers is a service for users
type SrvUsers struct {
DB storm.Node
metaData *model.UserQuestion
}
// NewSrvUsers for user CRUD
func NewSrvUsers(db storm.Node) *SrvUsers {
return &SrvUsers{
DB: db,
metaData: model.NewUserQuestions(),
}
}
// GetAll gets all users from storm DB
func (su *SrvUsers) GetAll() ([]*model.User, error) {
var users []*model.User
err := su.DB.All(&users)
if err != nil {
return nil, fmt.Errorf("coul not find users: %v", err)
}
return users, nil
}
// Name to comply with interface
func (su *SrvUsers) Name() string {
return DBUsers
}
// GetOne gets one user from storm DB by email
func (su *SrvUsers) GetOne(id string) (*model.User, error) {
var user model.User
err := su.DB.One("Email", id, &user)
if err != nil {
return nil, fmt.Errorf("coul not find user %s: %v", id, err)
}
return &user, nil
}
// GetLimit gets users from storm DB by email
func (su *SrvUsers) GetLimit(pagination map[string]interface{}) ([]*model.User, error) {
var users []*model.User
var options PaginationOptions
err := mapstructure.Decode(pagination, &options)
if err != nil {
return nil, fmt.Errorf("coul not unmarshal pagination: %v", err)
}
err = su.DB.All(&users, storm.Skip(options.Skip), storm.Limit(options.Limit))
if err != nil {
return nil, fmt.Errorf("coul not find users: %v", err)
}
return users, nil
}
// CreateOne creats one user, must have email
func (su *SrvUsers) CreateOne(obj map[string]interface{}) (string, error) {
var user *model.User
err := mapstructure.Decode(obj, &user)
if err != nil {
return "", fmt.Errorf("coul not unmarshal user: %v", err)
}
err = su.DB.Save(user)
if err != nil {
return "", fmt.Errorf("coul not create user %s: %v", user.Email, err)
}
return user.Email, nil
}
// DeleteOne deletes one user from storm by email
func (su *SrvUsers) DeleteOne(email string) error {
err := su.DB.Delete(DBUsers, email)
if err != nil {
return fmt.Errorf("coul not delete user %s: %v", email, err)
}
return nil
}
// MetaData to get the metadata regarding type's questions
func (su *SrvUsers) MetaData() *model.UserQuestion {
return su.metaData
}
|
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
var np sync.WaitGroup
fmt.Println("1st GR:", runtime.NumGoroutine())
increment := 0
ps := 100
np.Add(ps)
for i := 0; i < ps; i++ {
go func() {
v := increment
runtime.Gosched()
v++
increment = v
fmt.Println(increment)
np.Done()
}()
}
fmt.Println("2nd GR:", runtime.NumGoroutine())
np.Wait()
fmt.Println("3rd GR:", runtime.NumGoroutine())
fmt.Println("End value:", increment)
}
|
package main
//给定一个二叉树,找出其最大深度。
//
//二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
//
//说明: 叶子节点是指没有子节点的节点。
//
//示例:
//给定二叉树 [3,9,20,null,null,15,7],
//
//3
/// \
//9 20
/// \
//15 7
//返回它的最大深度 3 。
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func main() {
maxDepth(&TreeNode{})
}
// 递归
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
//迭代
func maxDepth2(root *TreeNode) int {
if root == nil {
return 0
}
dep := 0
q := make([]*TreeNode, 0)
q = append(q, root)
length := len(q)
for length > 0 {
dep++
for i := 0; i < length; i++ {
node := q[0]
q = q[1:]
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
length = len(q)
}
return dep
}
|
package parse
import (
"bytes"
"encoding/base32"
"io"
"io/ioutil"
"time"
"github.com/slotix/dataflowkit/scrape"
"github.com/spf13/viper"
"github.com/slotix/dataflowkit/storage"
)
//storageMiddleware caches Parsed results in storage.
type storageMiddleware struct {
//storage instance puts fetching results to a cache
storage storage.Store
Service
}
// StorageMiddleware Parsed results in storage.
func StorageMiddleware(storage storage.Store) ServiceMiddleware {
return func(next Service) Service {
return storageMiddleware{storage, next}
}
}
//Parse returns parsed results either from storage or directly from scraped web pages.
func (mw storageMiddleware) Parse(p scrape.Payload) (output io.ReadCloser, err error) {
//if parsed result is in storage return local copy
storageKey := string(p.PayloadMD5)
//Base32 encoded values are 100% safe for file/uri usage without replacing any characters and guarantees 1-to-1 mapping
sKey := base32.StdEncoding.EncodeToString([]byte(storageKey))
value, err := mw.storage.Read(sKey, storage.CACHE)
//check if item is expired.
if err == nil && !mw.storage.Expired(sKey) {
readCloser := ioutil.NopCloser(bytes.NewReader(value))
return readCloser, nil
}
//Parse if there is nothing in storage
parsed, err := mw.Service.Parse(p)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(parsed)
if err != nil {
logger.Error(err.Error())
}
//save parsed results after scraping to storage
//calculate expiration time. It is actual for Redis storage.
exp := time.Duration(viper.GetInt64("ITEM_EXPIRE_IN")) * time.Second
expiry := time.Now().UTC().Add(exp)
//logger.Info("Cache lifespan is %+v\n", expiry.Sub(time.Now().UTC()))
err = mw.storage.Write(sKey, &storage.Record{RecordType: storage.CACHE, Value: buf.Bytes()}, expiry.Unix())
if err != nil {
logger.Error(err.Error())
}
output = ioutil.NopCloser(buf)
return
}
|
package routers
import (
"lasti/controllers"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/index", &controllers.MainController{})
beego.Router("/login", &controllers.LoginController{})
beego.Router("/register", &controllers.RegController{})
beego.Router("/home", &controllers.HomeController{})
beego.Router("/katalog", &controllers.CatController{})
beego.Router("/chat", &controllers.ChatController{})
beego.Router("/form", &controllers.FormController{})
beego.Router("/tanya", &controllers.TanyaController{})
beego.Router("/faq", &controllers.FAQController{})
beego.Router("/cart", &controllers.CartController{})
beego.Router("/laptop", &controllers.LaptopController{})
beego.Router("/bayar", &controllers.BayarController{})
beego.Router("/logout", &controllers.LogoutController{})
}
|
package handlers_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/base64"
"encoding/json"
"math/rand"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/internal/deterministicecdsa"
"github.com/pomerium/pomerium/internal/handlers"
"github.com/pomerium/pomerium/pkg/cryptutil"
)
func TestJWKSHandler(t *testing.T) {
t.Parallel()
rnd := rand.New(rand.NewSource(1))
signingKey1, err := deterministicecdsa.GenerateKey(elliptic.P256(), rnd)
require.NoError(t, err)
signingKey2, err := deterministicecdsa.GenerateKey(elliptic.P256(), rnd)
require.NoError(t, err)
rawSigningKey1, err := cryptutil.EncodePrivateKey(signingKey1)
require.NoError(t, err)
rawSigningKey2, err := cryptutil.EncodePrivateKey(signingKey2)
require.NoError(t, err)
jwkSigningKey1, err := cryptutil.PublicJWKFromBytes(rawSigningKey1)
require.NoError(t, err)
jwkSigningKey2, err := cryptutil.PublicJWKFromBytes(rawSigningKey2)
require.NoError(t, err)
t.Run("cors", func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodOptions, "/", nil)
r.Header.Set("Origin", "https://www.example.com")
r.Header.Set("Access-Control-Request-Method", http.MethodGet)
handlers.JWKSHandler(nil).ServeHTTP(w, r)
assert.Equal(t, http.StatusNoContent, w.Result().StatusCode)
})
t.Run("keys", func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil)
handlers.JWKSHandler(append(rawSigningKey1, rawSigningKey2...)).ServeHTTP(w, r)
var expect any = map[string]any{
"keys": []any{
map[string]any{
"kty": "EC",
"kid": jwkSigningKey1.KeyID,
"crv": "P-256",
"alg": "ES256",
"use": "sig",
"x": base64.RawURLEncoding.EncodeToString(jwkSigningKey1.Key.(*ecdsa.PublicKey).X.Bytes()),
"y": base64.RawURLEncoding.EncodeToString(jwkSigningKey1.Key.(*ecdsa.PublicKey).Y.Bytes()),
},
map[string]any{
"kty": "EC",
"kid": jwkSigningKey2.KeyID,
"crv": "P-256",
"alg": "ES256",
"use": "sig",
"x": base64.RawURLEncoding.EncodeToString(jwkSigningKey2.Key.(*ecdsa.PublicKey).X.Bytes()),
"y": base64.RawURLEncoding.EncodeToString(jwkSigningKey2.Key.(*ecdsa.PublicKey).Y.Bytes()),
},
},
}
var actual any
err := json.Unmarshal(w.Body.Bytes(), &actual)
assert.NoError(t, err)
assert.Equal(t, expect, actual)
})
}
|
package uniseg
import (
"testing"
)
type testCase = struct {
original string
expected [][]rune
}
// The test cases for the simple test function.
var testCases = []testCase{
{original: "", expected: [][]rune{}},
{original: "x", expected: [][]rune{{0x78}}},
{original: "basic", expected: [][]rune{{0x62}, {0x61}, {0x73}, {0x69}, {0x63}}},
{original: "möp", expected: [][]rune{{0x6d}, {0x6f, 0x308}, {0x70}}},
{original: "\r\n", expected: [][]rune{{0xd, 0xa}}},
{original: "\n\n", expected: [][]rune{{0xa}, {0xa}}},
{original: "\t*", expected: [][]rune{{0x9}, {0x2a}}},
{original: "뢴", expected: [][]rune{{0x1105, 0x116c, 0x11ab}}},
{original: "ܐܒܓܕ", expected: [][]rune{{0x710}, {0x70f, 0x712}, {0x713}, {0x715}}},
{original: "ำ", expected: [][]rune{{0xe33}}},
{original: "ำำ", expected: [][]rune{{0xe33, 0xe33}}},
{original: "สระอำ", expected: [][]rune{{0xe2a}, {0xe23}, {0xe30}, {0xe2d, 0xe33}}},
{original: "*뢴*", expected: [][]rune{{0x2a}, {0x1105, 0x116c, 0x11ab}, {0x2a}}},
{original: "*👩❤️💋👩*", expected: [][]rune{{0x2a}, {0x1f469, 0x200d, 0x2764, 0xfe0f, 0x200d, 0x1f48b, 0x200d, 0x1f469}, {0x2a}}},
{original: "👩❤️💋👩", expected: [][]rune{{0x1f469, 0x200d, 0x2764, 0xfe0f, 0x200d, 0x1f48b, 0x200d, 0x1f469}}},
{original: "🏋🏽♀️", expected: [][]rune{{0x1f3cb, 0x1f3fd, 0x200d, 0x2640, 0xfe0f}}},
{original: "🙂", expected: [][]rune{{0x1f642}}},
{original: "🙂🙂", expected: [][]rune{{0x1f642}, {0x1f642}}},
{original: "🇩🇪", expected: [][]rune{{0x1f1e9, 0x1f1ea}}},
{original: "🏳️🌈", expected: [][]rune{{0x1f3f3, 0xfe0f, 0x200d, 0x1f308}}},
{original: "\t🏳️🌈", expected: [][]rune{{0x9}, {0x1f3f3, 0xfe0f, 0x200d, 0x1f308}}},
{original: "\t🏳️🌈\t", expected: [][]rune{{0x9}, {0x1f3f3, 0xfe0f, 0x200d, 0x1f308}, {0x9}}},
}
// decomposed returns a grapheme cluster decomposition.
func decomposed(s string) (runes [][]rune) {
gr := NewGraphemes(s)
for gr.Next() {
runes = append(runes, gr.Runes())
}
return
}
// Run the testCases slice above.
func TestSimple(t *testing.T) {
allCases := append(testCases, unicodeTestCases...)
for testNum, testCase := range allCases {
/*t.Logf(`Test case %d "%s": Expecting %x, getting %x, code points %x"`,
testNum,
strings.TrimSpace(testCase.original),
testCase.expected,
decomposed(testCase.original),
[]rune(testCase.original))*/
gr := NewGraphemes(testCase.original)
var index int
GraphemeLoop:
for index = 0; gr.Next(); index++ {
if index >= len(testCase.expected) {
t.Errorf(`Test case %d "%s" failed: More grapheme clusters returned than expected %d`,
testNum,
testCase.original,
len(testCase.expected))
break
}
cluster := gr.Runes()
if len(cluster) != len(testCase.expected[index]) {
t.Errorf(`Test case %d "%s" failed: Grapheme cluster at index %d has %d codepoints %x, %d expected %x`,
testNum,
testCase.original,
index,
len(cluster),
cluster,
len(testCase.expected[index]),
testCase.expected[index])
break
}
for i, r := range cluster {
if r != testCase.expected[index][i] {
t.Errorf(`Test case %d "%s" failed: Grapheme cluster at index %d is %x, expected %x`,
testNum,
testCase.original,
index,
cluster,
testCase.expected[index])
break GraphemeLoop
}
}
}
if index < len(testCase.expected) {
t.Errorf(`Test case %d "%s" failed: Fewer grapheme clusters returned (%d) than expected (%d)`,
testNum,
testCase.original,
index,
len(testCase.expected))
}
}
}
// Test the Str() function.
func TestStr(t *testing.T) {
gr := NewGraphemes("möp")
gr.Next()
gr.Next()
gr.Next()
if str := gr.Str(); str != "p" {
t.Errorf(`Expected "p", got "%s"`, str)
}
}
// Test the Bytes() function.
func TestBytes(t *testing.T) {
gr := NewGraphemes("A👩❤️💋👩B")
gr.Next()
gr.Next()
gr.Next()
b := gr.Bytes()
if len(b) != 1 {
t.Fatalf(`Expected len("B") == 1, got %d`, len(b))
}
if b[0] != 'B' {
t.Errorf(`Expected "B", got "%s"`, string(b[0]))
}
}
// Test the Positions() function.
func TestPositions(t *testing.T) {
gr := NewGraphemes("A👩❤️💋👩B")
gr.Next()
gr.Next()
from, to := gr.Positions()
if from != 1 || to != 28 {
t.Errorf(`Expected from=%d to=%d, got from=%d to=%d`, 1, 28, from, to)
}
}
// Test the Reset() function.
func TestReset(t *testing.T) {
gr := NewGraphemes("möp")
gr.Next()
gr.Next()
gr.Next()
gr.Reset()
gr.Next()
if str := gr.Str(); str != "m" {
t.Errorf(`Expected "m", got "%s"`, str)
}
}
// Test retrieving clusters before calling Next().
func TestEarly(t *testing.T) {
gr := NewGraphemes("test")
r := gr.Runes()
if r != nil {
t.Errorf(`Expected nil rune slice, got %x`, r)
}
str := gr.Str()
if str != "" {
t.Errorf(`Expected empty string, got "%s"`, str)
}
b := gr.Bytes()
if b != nil {
t.Errorf(`Expected byte rune slice, got %x`, b)
}
from, to := gr.Positions()
if from != 0 || to != 0 {
t.Errorf(`Expected from=%d to=%d, got from=%d to=%d`, 0, 0, from, to)
}
}
// Test retrieving more clusters after retrieving the last cluster.
func TestLate(t *testing.T) {
gr := NewGraphemes("x")
gr.Next()
gr.Next()
r := gr.Runes()
if r != nil {
t.Errorf(`Expected nil rune slice, got %x`, r)
}
str := gr.Str()
if str != "" {
t.Errorf(`Expected empty string, got "%s"`, str)
}
b := gr.Bytes()
if b != nil {
t.Errorf(`Expected byte rune slice, got %x`, b)
}
from, to := gr.Positions()
if from != 1 || to != 1 {
t.Errorf(`Expected from=%d to=%d, got from=%d to=%d`, 1, 1, from, to)
}
}
// Test the GraphemeClusterCount function.
func TestCount(t *testing.T) {
if n := GraphemeClusterCount("🇩🇪🏳️🌈"); n != 2 {
t.Errorf(`Expected 2 grapheme clusters, got %d`, n)
}
}
|
package cookie
import (
"crypto/rand"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/encoding/mock"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/pkg/cryptutil"
)
func TestNewStore(t *testing.T) {
key := cryptutil.NewKey()
encoder, err := jws.NewHS256Signer(key)
require.NoError(t, err)
tests := []struct {
name string
opts *Options
encoder encoding.MarshalUnmarshaler
want sessions.SessionStore
wantErr bool
}{
{"good", &Options{Name: "_cookie", Secure: true, HTTPOnly: true, Domain: "pomerium.io", Expire: 10 * time.Second}, encoder, &Store{getOptions: func() Options {
return Options{Name: "_cookie", Secure: true, HTTPOnly: true, Domain: "pomerium.io", Expire: 10 * time.Second}
}}, false},
{"missing encoder", &Options{Name: "_cookie", Secure: true, HTTPOnly: true, Domain: "pomerium.io", Expire: 10 * time.Second}, nil, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewStore(func() Options {
return *tt.opts
}, tt.encoder)
if (err != nil) != tt.wantErr {
t.Errorf("NewStore() error = %v, wantErr %v", err, tt.wantErr)
return
}
cmpOpts := []cmp.Option{
cmpopts.IgnoreUnexported(Store{}),
}
if diff := cmp.Diff(got, tt.want, cmpOpts...); diff != "" {
t.Errorf("NewStore() = %s", diff)
}
})
}
}
func TestNewCookieLoader(t *testing.T) {
key := cryptutil.NewKey()
encoder, err := jws.NewHS256Signer(key)
require.NoError(t, err)
tests := []struct {
name string
opts *Options
encoder encoding.MarshalUnmarshaler
want *Store
wantErr bool
}{
{"good", &Options{Name: "_cookie", Secure: true, HTTPOnly: true, Domain: "pomerium.io", Expire: 10 * time.Second}, encoder, &Store{getOptions: func() Options {
return Options{Name: "_cookie", Secure: true, HTTPOnly: true, Domain: "pomerium.io", Expire: 10 * time.Second}
}}, false},
{"missing encoder", &Options{Name: "_cookie", Secure: true, HTTPOnly: true, Domain: "pomerium.io", Expire: 10 * time.Second}, nil, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewCookieLoader(func() Options {
return *tt.opts
}, tt.encoder)
if (err != nil) != tt.wantErr {
t.Errorf("NewCookieLoader() error = %v, wantErr %v", err, tt.wantErr)
return
}
cmpOpts := []cmp.Option{
cmpopts.IgnoreUnexported(Store{}),
}
if diff := cmp.Diff(got, tt.want, cmpOpts...); diff != "" {
t.Errorf("NewCookieLoader() = %s", diff)
}
})
}
}
func TestStore_SaveSession(t *testing.T) {
key := cryptutil.NewKey()
encoder, err := jws.NewHS256Signer(key)
require.NoError(t, err)
hugeString := make([]byte, 4097)
if _, err := rand.Read(hugeString); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
State interface{}
encoder encoding.Marshaler
decoder encoding.Unmarshaler
wantErr bool
wantLoadErr bool
}{
{"good", &sessions.State{ID: "xyz"}, encoder, encoder, false, false},
{"bad cipher", &sessions.State{ID: "xyz"}, nil, nil, true, true},
{"huge cookie", &sessions.State{ID: "xyz", Subject: fmt.Sprintf("%x", hugeString)}, encoder, encoder, false, false},
{"marshal error", &sessions.State{ID: "xyz"}, mock.Encoder{MarshalError: errors.New("error")}, encoder, true, true},
{"nil encoder cannot save non string type", &sessions.State{ID: "xyz"}, nil, encoder, true, true},
{"good marshal string directly", cryptutil.NewBase64Key(), nil, encoder, false, true},
{"good marshal bytes directly", cryptutil.NewKey(), nil, encoder, false, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Store{
getOptions: func() Options {
return Options{
Name: "_pomerium",
Secure: true,
HTTPOnly: true,
Domain: "pomerium.io",
Expire: 10 * time.Second,
}
},
encoder: tt.encoder,
decoder: tt.decoder,
}
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
if err := s.SaveSession(w, r, tt.State); (err != nil) != tt.wantErr {
t.Errorf("Store.SaveSession() error = %v, wantErr %v", err, tt.wantErr)
}
r = httptest.NewRequest(http.MethodGet, "/", nil)
for _, cookie := range w.Result().Cookies() {
r.AddCookie(cookie)
}
jwt, err := s.LoadSession(r)
if (err != nil) != tt.wantLoadErr {
t.Errorf("LoadSession() error = %v, wantErr %v", err, tt.wantLoadErr)
return
}
var state sessions.State
encoder.Unmarshal([]byte(jwt), &state)
cmpOpts := []cmp.Option{
cmpopts.IgnoreUnexported(sessions.State{}),
}
if err == nil {
if diff := cmp.Diff(&state, tt.State, cmpOpts...); diff != "" {
t.Errorf("Store.LoadSession() got = %s", diff)
}
}
w = httptest.NewRecorder()
s.ClearSession(w, r)
x := w.Header().Get("Set-Cookie")
if !strings.Contains(x, "_pomerium=; Path=/;") {
t.Errorf(x)
}
})
}
}
|
package parser
import (
"fmt"
llp "github.com/romshark/llparser"
)
// Parser represents a boolean expression parser
type Parser struct {
prs *llp.Parser
}
// NewParser creates a new parser instance
func NewParser() (*Parser, error) {
parser, err := llp.NewParser(newGrammar(), nil)
if err != nil {
return nil, err
}
return &Parser{prs: parser}, nil
}
// Parse parses a boolean expression
func (pr *Parser) Parse(
fileName string,
src []rune,
) (*AST, error) {
if fileName == "" {
return nil, fmt.Errorf("invalid file name")
}
if len(src) < 1 {
return nil, fmt.Errorf("empty input")
}
mainFrag, err := pr.prs.Parse(&llp.SourceFile{
Name: fileName,
Src: src,
})
if err != nil {
return nil, err
}
ast := &AST{
Root: &ASTRoot{
Fragment: mainFrag,
Expression: parseExpr(mainFrag),
},
}
// Turn the parse tree into an AST
if err != nil {
return nil, err
}
return ast, nil
}
func findKind(
frags []llp.Fragment,
offset int,
kinds ...llp.FragmentKind,
) (int, llp.Fragment) {
for fix := offset; fix < len(frags); fix++ {
frag := frags[fix]
for _, kind := range kinds {
if frag.Kind() == kind {
return fix, frag
}
}
}
return -1, nil
}
func parseExpr(frag llp.Fragment) ASTExpression {
elems := frag.Elements()
terms := []ASTExpression{}
// Parse all terms
for ix := 0; ix < len(elems); ix++ {
elem := elems[ix]
if elem.Kind() == FrExprTerm {
terms = append(terms, parseTerm(elem))
}
}
// Check for or-statements
if _, fr := findKind(elems, 1, FrOprOr); fr == nil {
if len(terms) < 1 {
return nil
}
return terms[0]
}
return &ASTOr{
Fragment: frag,
Expressions: terms,
}
}
func parseTerm(frag llp.Fragment) ASTExpression {
elems := frag.Elements()
factors := []ASTExpression{}
// Parse all factors
for ix := 0; ix < len(elems); ix++ {
elem := elems[ix]
if elem.Kind() == FrExprFactor {
factors = append(factors, parseFactor(elem))
}
}
// Check for and-statements
if _, fr := findKind(elems, 1, FrOprAnd); fr == nil {
if len(factors) < 1 {
return nil
}
return factors[0]
}
return &ASTAnd{
Fragment: frag,
Expressions: factors,
}
}
func parseFactor(frag llp.Fragment) ASTExpression {
elems := frag.Elements()
firstElem := elems[0]
switch firstElem.Kind() {
case FrConstTrue:
// Constant bool value
return &ASTConstant{
Fragment: firstElem,
Value: true,
}
case FrConstFalse:
// Constant bool value
return &ASTConstant{
Fragment: firstElem,
Value: false,
}
case FrOprNeg:
// Negated factor
return &ASTNegated{
Fragment: frag,
Expression: parseFactor(elems[1]),
}
case FrExprParentheses:
// Expression enclosed in parentheses
_, expr := findKind(elems[0].Elements(), 1, FrExpr)
return &ASTParentheses{
Fragment: frag,
Expression: parseExpr(expr),
}
}
return nil
}
|
package manage
import (
"log"
)
type Manage interface {
Error()
}
func New() {
log.Print("ss")
}
|
package ehttp
import "testing"
func TestParameter_ToSwaggerParameters(t *testing.T) {
Parameters := map[string]Parameter{
"id": Parameter{
InPath: &ValueInfo{Type: "string"},
InHeader: &ValueInfo{Type: "string"},
InQuery: &ValueInfo{Type: "string"},
InFormData: &ValueInfo{Type: "string"},
},
"type": Parameter{
InPath: &ValueInfo{Type: "string", Enum: "TYPE1 TYPE2 TYPE3"},
InHeader: &ValueInfo{Type: "string", Enum: "TYPE1 TYPE2 TYPE3"},
InQuery: &ValueInfo{Type: "string", Enum: "TYPE1 TYPE2 TYPE3"},
InFormData: &ValueInfo{Type: "string", Enum: "TYPE1 TYPE2 TYPE3"},
},
"file1": Parameter{
InFormData: &ValueInfo{Type: "file"},
},
}
for name, parameter := range Parameters {
if _, err := parameter.ToSwaggerParameters(name); err != nil {
testError(t, err)
}
}
invalidParameters := map[string]Parameter{
"file1": Parameter{
InPath: &ValueInfo{Type: "file"}, // InPath ValueInfo.Type cann't be file
},
"file2": Parameter{
InHeader: &ValueInfo{Type: "file"}, // InHeader ValueInfo.Type cann't be file
},
"file3": Parameter{
InQuery: &ValueInfo{Type: "file"}, // InQuery ValueInfo.Type cann't be file
},
"&**&$#%$#%": Parameter{
InPath: &ValueInfo{Type: "string"}, // invalid name
},
}
for name, parameter := range invalidParameters {
if _, err := parameter.ToSwaggerParameters(name); err != nil {
testLog(t, err)
} else {
testError(t, "parameter.ToSwaggerParameters(name) err should not be nil")
}
}
}
|
// +build !linux
package mount
type Mounter struct {
}
func (m *Mounter) Umount(target string) error {
return nil
}
func (m *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {
return true, nil
}
|
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 install
import (
"bytes"
"fmt"
"os"
"strings"
"text/template"
"time"
"github.com/spf13/viper"
pb "github.com/CS-SI/SafeScale/broker"
brokerclient "github.com/CS-SI/SafeScale/broker/client"
"github.com/CS-SI/SafeScale/providers/metadata"
"github.com/CS-SI/SafeScale/system"
"github.com/CS-SI/SafeScale/utils/provideruse"
"github.com/CS-SI/SafeScale/utils/retry"
)
const (
featureScriptTemplateContent = `
rm -f /var/tmp/{{.reserved_Name}}.feature.{{.reserved_Action}}_{{.reserved_Step}}.log
exec 1<&-
exec 2<&-
exec 1<>/var/tmp/{{.reserved_Name}}.feature.{{.reserved_Action}}_{{.reserved_Step}}.log
exec 2>&1
{{ .reserved_BashLibrary }}
{{ .reserved_Content }}
`
)
var (
featureScriptTemplate *template.Template
)
// parseTargets validates targets on the cluster from the feature specification
// Without error, returns 'master target', 'private node target' and 'public node target'
func parseTargets(specs *viper.Viper) (string, string, string, error) {
if !specs.IsSet("feature.target.cluster") {
return "", "", "", fmt.Errorf("feature isn't suitable for a cluster")
}
master := strings.ToLower(strings.TrimSpace(specs.GetString("feature.target.cluster.master")))
switch master {
case "":
fallthrough
case "false":
fallthrough
case "no":
fallthrough
case "none":
fallthrough
case "0":
master = "0"
case "any":
fallthrough
case "one":
fallthrough
case "1":
master = "1"
case "all":
fallthrough
case "*":
master = "*"
default:
return "", "", "", fmt.Errorf("invalid value '%s' for field 'feature.target.cluster.master'", master)
}
privnode := strings.ToLower(strings.TrimSpace(specs.GetString("feature.target.cluster.node.private")))
switch privnode {
case "false":
fallthrough
case "no":
fallthrough
case "none":
privnode = "0"
case "any":
fallthrough
case "one":
fallthrough
case "1":
privnode = "1"
case "":
fallthrough
case "all":
fallthrough
case "*":
privnode = "*"
default:
return "", "", "", fmt.Errorf("invalid value '%s' for field 'feature.target.cluster.node.private'", privnode)
}
pubnode := strings.ToLower(strings.TrimSpace(specs.GetString("feature.target.cluster.node.public")))
switch pubnode {
case "":
fallthrough
case "false":
fallthrough
case "no":
fallthrough
case "none":
fallthrough
case "0":
pubnode = "0"
case "any":
fallthrough
case "one":
fallthrough
case "1":
pubnode = "1"
case "all":
fallthrough
case "*":
pubnode = "*"
default:
return "", "", "", fmt.Errorf("invalid value '%s' for field 'feature.target.cluster.node.public'", pubnode)
}
if master == "0" && privnode == "0" && pubnode == "0" {
return "", "", "", fmt.Errorf("invalid 'feature.target.cluster': no target designated")
}
return master, privnode, pubnode, nil
}
// UploadStringToRemoteFile creates a file 'filename' on remote 'host' with the content 'content'
func UploadStringToRemoteFile(content string, host *pb.Host, filename string, owner, group, rights string) error {
if content == "" {
panic("content is empty!")
}
if host == nil {
panic("host is nil!")
}
if filename == "" {
panic("filename is empty!")
}
f, err := system.CreateTempFileFromString(content, 0600)
if err != nil {
return fmt.Errorf("failed to create temporary file: %s", err.Error())
}
to := fmt.Sprintf("%s:%s", host.Name, filename)
broker := brokerclient.New().Ssh
retryErr := retry.WhileUnsuccessful(
func() error {
var retcode int
retcode, _, _, err = broker.Copy(f.Name(), to, 15*time.Second, brokerclient.DefaultExecutionTimeout)
if err != nil {
return err
}
if retcode != 0 {
// If retcode == 1 (general copy error), retry. It may be a temporary network incident
if retcode == 1 {
// File may exist on target, try to remote it
_, _, _, err = broker.Run(host.Name, fmt.Sprintf("sudo rm -f %s", filename), 15*time.Second, brokerclient.DefaultExecutionTimeout)
return fmt.Errorf("file may exist on remote with inappropriate access rights, deleted it and retrying")
}
if system.IsSCPRetryable(retcode) {
err = fmt.Errorf("failed to copy temporary file to '%s' (retcode: %d=%s)", to, retcode, system.SCPErrorString(retcode))
}
return nil
}
return nil
},
1*time.Second,
2*time.Minute,
)
os.Remove(f.Name())
if retryErr != nil {
switch retryErr.(type) {
case retry.ErrTimeout:
return fmt.Errorf("timeout trying to copy temporary file to '%s': %s", to, retryErr.Error())
}
return err
}
cmd := ""
if owner != "" {
cmd += "sudo chown " + owner + " " + filename
}
if group != "" {
if cmd != "" {
cmd += " && "
}
cmd += "sudo chgrp " + group + " " + filename
}
if rights != "" {
if cmd != "" {
cmd += " && "
}
cmd += "sudo chmod " + rights + " " + filename
}
retryErr = retry.WhileUnsuccessful(
func() error {
var retcode int
retcode, _, _, err = broker.Run(host.Name, cmd, 15*time.Second, brokerclient.DefaultExecutionTimeout)
if err != nil {
return err
}
if retcode != 0 {
err = fmt.Errorf("failed to change rights of file '%s' (retcode=%d)", to, retcode)
return nil
}
return nil
},
2*time.Second,
1*time.Minute,
)
if retryErr != nil {
switch retryErr.(type) {
case retry.ErrTimeout:
return fmt.Errorf("timeout trying to change rights of file '%s' on host '%s': %s", filename, host.Name, err.Error())
default:
return fmt.Errorf("failed to change rights of file '%s' on host '%s': %s", filename, host.Name, retryErr.Error())
}
}
return nil
}
// normalizeScript envelops the script with log redirection to /var/tmp/feature.<name>.<action>.log
// and ensures BashLibrary are there
func normalizeScript(params map[string]interface{}) (string, error) {
var err error
if featureScriptTemplate == nil {
// parse then execute the template
featureScriptTemplate, err = template.New("normalize_script").Parse(featureScriptTemplateContent)
if err != nil {
return "", fmt.Errorf("error parsing bash template: %s", err.Error())
}
}
// Configures BashLibrary template var
bashLibrary, err := system.GetBashLibrary()
if err != nil {
return "", err
}
params["reserved_BashLibrary"] = bashLibrary
dataBuffer := bytes.NewBufferString("")
err = featureScriptTemplate.Execute(dataBuffer, params)
if err != nil {
return "", err
}
return dataBuffer.String(), nil
}
func replaceVariablesInString(text string, v Variables) (string, error) {
tmpl, err := template.New("text").Parse(text)
if err != nil {
return "", fmt.Errorf("failed to parse: %s", err.Error())
}
dataBuffer := bytes.NewBufferString("")
err = tmpl.Execute(dataBuffer, v)
if err != nil {
return "", fmt.Errorf("failed to replace variables: %s", err.Error())
}
return dataBuffer.String(), nil
}
func findConcernedHosts(list []string, c *Feature) (string, error) {
// No metadata yet for features, first host is designated concerned host
if len(list) > 0 {
return list[0], nil
}
return "", fmt.Errorf("no hosts")
//for _, h := range list {
//}
}
// determineContext ...
func determineContext(t Target) (hT *HostTarget, cT *ClusterTarget, nT *NodeTarget) {
hT = nil
cT = nil
nT = nil
var ok bool
hT, ok = t.(*HostTarget)
if !ok {
cT, ok = t.(*ClusterTarget)
if !ok {
nT, ok = t.(*NodeTarget)
}
}
return
}
// Check if required parameters defined in specification file have been set in 'v'
func checkParameters(f *Feature, v Variables) error {
if f.specs.IsSet("feature.parameters") {
params := f.specs.GetStringSlice("feature.parameters")
for _, k := range params {
if _, ok := v[k]; !ok {
return fmt.Errorf("missing value for parameter '%s'", k)
}
}
}
return nil
}
// setImplicitParameters configures parameters that are implicitely defined, based on context
func setImplicitParameters(t Target, v Variables) {
hT, cT, nT := determineContext(t)
if cT != nil {
cluster := cT.cluster
config := cluster.GetConfig()
v["ClusterName"] = cluster.GetName()
v["ClusterComplexity"] = strings.ToLower(config.Complexity.String())
v["ClusterFlavor"] = strings.ToLower(config.Flavor.String())
v["GatewayIP"] = config.GatewayIP
v["MasterIDs"] = cluster.ListMasterIDs()
v["MasterIPs"] = cluster.ListMasterIPs()
if _, ok := v["Username"]; !ok {
v["Username"] = "cladm"
v["Password"] = config.AdminPassword
}
if _, ok := v["CIDR"]; !ok {
svc, err := provideruse.GetProviderService()
if err == nil {
mn, err := metadata.LoadNetwork(svc, config.NetworkID)
if err == nil {
n := mn.Get()
v["CIDR"] = n.CIDR
}
} else {
fmt.Fprintf(os.Stderr, "failed to determine network CIDR")
}
}
} else {
var host *pb.Host
if nT != nil {
host = nT.HostTarget.host
}
if hT != nil {
host = hT.host
}
v["Hostname"] = host.Name
v["HostIP"] = host.PrivateIP
gw := gatewayFromHost(host)
if gw != nil {
v["GatewayIP"] = gw.PrivateIP
}
if _, ok := v["Username"]; !ok {
v["Username"] = "gpac"
}
}
}
func gatewayFromHost(host *pb.Host) *pb.Host {
broker := brokerclient.New()
gwID := host.GetGatewayID()
// If host has no gateway, host is gateway
if gwID == "" {
return host
}
gw, err := broker.Host.Inspect(gwID, brokerclient.DefaultExecutionTimeout)
if err != nil {
return nil
}
return gw
}
|
package aws
import (
"os"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/stretchr/testify/assert"
)
var (
route53Secret string
route53Key string
route53Region string
domain string
ip string
liveTest bool
)
func init() {
route53Key = os.Getenv("AWS_ACCESS_KEY_ID")
route53Secret = os.Getenv("AWS_SECRET_ACCESS_KEY")
route53Region = os.Getenv("AWS_REGION")
domain = os.Getenv("AWS_DOMAIN")
ip = os.Getenv("AWS_IP")
if len(domain) > 0 {
liveTest = true
}
}
func restoreRoute53Env() {
os.Setenv("AWS_ACCESS_KEY_ID", route53Key)
os.Setenv("AWS_SECRET_ACCESS_KEY", route53Secret)
os.Setenv("AWS_REGION", route53Region)
}
func TestCredentialsFromEnv(t *testing.T) {
os.Setenv("AWS_ACCESS_KEY_ID", "123")
os.Setenv("AWS_SECRET_ACCESS_KEY", "123")
os.Setenv("AWS_REGION", "us-east-1")
config := &aws.Config{
CredentialsChainVerboseErrors: aws.Bool(true),
}
sess := session.New(config)
_, err := sess.Config.Credentials.Get()
assert.NoError(t, err, "Expected credentials to be set from environment")
restoreRoute53Env()
}
func TestRegionFromEnv(t *testing.T) {
os.Setenv("AWS_REGION", "us-east-1")
sess := session.New(aws.NewConfig())
assert.Equal(t, "us-east-1", *sess.Config.Region, "Expected Region to be set from environment")
restoreRoute53Env()
}
func TestLiveEnsureARecord(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
provider, err := Default()
assert.NoError(t, err)
err = provider.EnsureARecord(domain, ip)
assert.NoError(t, err)
}
func TestLiveDeleteARecords(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
provider, err := Default()
assert.NoError(t, err)
err = provider.DeleteARecords(domain)
assert.NoError(t, err)
}
func TestLiveDeleteARecord(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
provider, err := Default()
assert.NoError(t, err)
err = provider.DeleteARecord(domain, ip)
assert.NoError(t, err)
}
|
package spec
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/kaitai-io/kaitai_struct_go_runtime/kaitai"
. "test_formats"
)
func TestPositionAbs(t *testing.T) {
f, err := os.Open("../../src/position_abs.bin")
if err != nil {
t.Fatal(err)
}
s := kaitai.NewStream(f)
var h PositionAbs
err = h.Read(s, &h, &h)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, uint32(0x20), h.IndexOffset)
index, err := h.Index()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "foo", index.Entry)
}
|
package worker
import (
"encoding/json"
"io/ioutil"
"time"
)
// json: 序列化之后的别名
type Config struct {
EtcdEndpoints []string `json:"etcdEndpoints"`
EtcdDialTimeout int `json:"etcdDialTimeout"`
ScheduleSleepTime time.Duration `json:"scheduleSleepTime"`
WorkerSleepTime time.Duration `json:"workerSleepTime"`
BashDir string `json:"bashDir"`
}
var (
// 单例
G_config *Config
)
func InitConfig(filename string) (err error) {
var (
content []byte
conf Config
)
// 1 读取配置文件
if content, err = ioutil.ReadFile(filename); err != nil {
return
}
// 2 做json序列化
if err = json.Unmarshal(content, &conf); err != nil {
return
}
G_config = &conf
return
}
|
package vaultengine
import (
"fmt"
)
// SecretWrite is used for writing data to a Vault instance
func (client *Client) SecretWrite(path string, data map[string]interface{}) {
infix := "/data/"
if client.engineType == "kv1" {
infix = "/"
}
finalPath := client.engine + infix + path
finalData := make(map[string]interface{})
if client.engineType == "kv1" {
finalData = data
} else {
finalData["data"] = data
}
// If the data object has the json-object key
// it means that the secret is not in the default
// key/value format.
if jsonVal, ok := data["json-object"]; ok {
var jsonString string
// The kv2 engine needs the data wrapped in a "data" key
if client.engineType == "kv2" {
jsonString = fmt.Sprintf("{\"data\":%s}", jsonVal)
} else {
jsonString = jsonVal.(string)
}
_, err := client.vc.Logical().WriteBytes(finalPath, []byte(jsonString))
if err != nil {
fmt.Printf("Error while writing secret. %s\n", err)
} else {
fmt.Printf("Secret successfully written to Vault [%s] using path [%s]\n", client.addr, path)
}
} else {
_, err := client.vc.Logical().Write(finalPath, finalData)
if err != nil {
fmt.Printf("Error while writing secret. %s\n", err)
} else {
fmt.Printf("Secret successfully written to Vault [%s] using path [%s]\n", client.addr, path)
}
}
}
|
package queue
import "errors"
type Elem int
type Node struct {
data Elem
next *Node
}
type QueueLink struct {
front *Node // 对头
tail *Node // 队尾
length int
}
func (q *QueueLink) InitQueue() {
q.front = new(Node)
q.tail = q.front
q.length = 0
}
func (q *QueueLink) EnQueue(e Elem) {
node := new(Node)
node.data = e
node.next = nil
q.tail.next = node
q.tail = node
q.length++
}
func (q *QueueLink) OutQueue(e *Elem) error {
if q.Empty() {
return errors.New("empty queue.")
}
node := q.front.next
*e = node.data
q.front.next = node.next
// 如果弹出的是队尾元素那么队列就空了,这个时候队尾等于队列
if q.tail == node {
q.tail = q.front
}
q.length--
return nil
}
func (q *QueueLink) Empty() bool {
return q.front == q.tail
}
func (q *QueueLink) Length() int {
return q.length
}
func (q *QueueLink) Destroy() {
q.front = nil
q.tail = nil
}
|
package chat
import (
//"fmt"
"github.com/liangdas/mqant/module"
"github.com/liangdas/mqant/module/base"
"github.com/liangdas/mqant/conf"
"github.com/liangdas/mqant/gate"
)
//创建模块
var Module = func() module.Module {
chat := new(Chat)
return chat
}
//模块定义
type Chat struct{
basemodule.BaseModule
}
func (m *Chat) GetType() string {
//很关键,需要与配置文件中的Module配置对应
return "Chat"
}
func (m *Chat) Version() string {
//可以在监控时了解代码版本
return "1.0.0"
}
//初始化
func (m *Chat) OnInit(app module.App, settings *conf.ModuleSettings) {
m.BaseModule.OnInit(m, app, settings)
//注册远程调用/消息
m.GetServer().Register("HD_Chess", m.chat)
}
//返回一次
func (m *Chat) Run(closeSig chan bool) {
}
func (m *Chat) OnDestroy() {
//一定别忘了关闭RPC
m.GetServer().OnDestroy()
}
//消息回调
func (m *Chat) chat(session gate.Session,msg map[string]interface{}) (result string, err string) {
//time.Sleep(1)
return "sss",""
} |
package request
import (
"sort"
)
// RequestSlice attaches the methods of sort.Interface to []Request, sorting in increasing order.
type RequestSlice []Request
func (p RequestSlice) Len() int { return len(p) }
func (p RequestSlice) Less(i, j int) bool {
for k := 0; k < len(p[i]); k++ {
if p[i][k] == p[j][k] {
continue
}
return p[i][k] < p[j][k]
}
return false
}
func (p RequestSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// SortRequests sorts a slice of StoreService in increasing order.
func SortRequests(a []Request) { sort.Sort(RequestSlice(a)) }
// GetSortedKeys gets Views and transforms it`s keys to sorted slice ([]Request)
func GetSortedKeys(v Views) []Request {
if v == nil {
return nil
}
keys := make([]Request, 0, len(v))
for k := range v {
keys = append(keys, k)
}
SortRequests(keys)
return keys
}
|
package ruby
import (
"fmt"
"text/template"
"strings"
"bytes"
"log"
"unicode"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/golang/protobuf/protoc-gen-go/plugin"
)
var ClientTemplate = `require_relative "./protos/{{.BaseName}}"
class {{.ClassName}}Client
{{ with .Methods }}{{range .}} def {{ .Name }}(request)
return {{.Output}}.new
end{{ end }}{{ end }}
end
`
var TestTemplate = `require 'minitest/autorun'
require_relative './{{.BaseName}}_client'
require_relative './protos/{{.BaseName}}'
include {{.Namespace}}
class Test{{.ClassName}} < Minitest::Test
def setup
@client = {{.ClassName}}Client.new
end
{{ with .Methods }}{{range .}} def test_{{ .Name }}
assert_equal @client.{{.Name}}({{.Input}}.new), {{.Output}}.new
end{{ end }}{{ end }}
end`
// Method impl for python methods
type Method struct {
m *descriptor.MethodDescriptorProto
}
func (m *Method) Name() string {
return ToSnake(m.m.GetName())
}
func (m *Method) Input() string {
return TrimType(m.m.GetInputType())
}
func (m *Method) Output() string {
return TrimType(m.m.GetOutputType())
}
type RubyClient struct {
srv *descriptor.ServiceDescriptorProto
file *descriptor.FileDescriptorProto
methods []*Method
}
func New(srv *descriptor.ServiceDescriptorProto, file *descriptor.FileDescriptorProto) (c *RubyClient) {
c = &RubyClient{
srv: srv,
file: file,
}
for _, m := range srv.GetMethod() {
c.AppendMethod(m)
}
return
}
func (c *RubyClient) AppendMethod(m *descriptor.MethodDescriptorProto) {
c.methods = append(c.methods, &Method{m})
}
func (c *RubyClient) ClassName() string {
return *c.srv.Name
}
func (c *RubyClient) Methods() []*Method {
return c.methods
}
func (c *RubyClient) BaseName() string {
parts := strings.Split(c.file.GetName(), "/")
if len(parts) == 0 {
return ""
}
return strings.Replace(parts[len(parts)-1], ".proto", "", 1)
}
func (c *RubyClient) Namespace() string {
parts := strings.Split(c.file.GetPackage(), ".")
if len(parts) == 0 {
return ""
}
for i := 0; i < len(parts); i++ {
parts[i] = strings.Title(parts[i])
}
return strings.Join(parts, "::")
}
func (c *RubyClient) FileName() *string {
return proto.String(
fmt.Sprintf(
"%s/%s_client.rb", strings.Replace(c.file.GetPackage(), ".", "/", -1),
c.BaseName(),
),
)
}
func (c *RubyClient) TestFileName() *string {
return proto.String(
fmt.Sprintf(
"%s/%s_client_test.rb", strings.Replace(c.file.GetPackage(), ".", "/", -1),
c.BaseName(),
),
)
}
func (c *RubyClient) Content() *string {
t := template.New("ruby-tpl")
tpl, err := t.Parse(ClientTemplate)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
tpl.Execute(&buf, c)
return proto.String(buf.String())
}
func (c *RubyClient) TestContent() *string {
t := template.New("ruby-test-tpl")
tpl, err := t.Parse(TestTemplate)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
tpl.Execute(&buf, c)
return proto.String(buf.String())
}
func (c *RubyClient) File() *plugin_go.CodeGeneratorResponse_File {
return &plugin_go.CodeGeneratorResponse_File{
Content: c.Content(),
Name: c.FileName(),
}
}
func (c *RubyClient) TestFile() *plugin_go.CodeGeneratorResponse_File {
return &plugin_go.CodeGeneratorResponse_File{
Content: c.TestContent(),
Name: c.TestFileName(),
}
}
// ToSnake snake_cases CamelCase strings
func ToSnake(in string) string {
runes := []rune(in)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}
// TrimType returns the last part of a dotted namespace
func TrimType(it string) string {
parts := strings.Split(it, ".")
if len(parts) == 0 {
return ""
}
if len(parts) == 1 {
return parts[0]
}
return parts[len(parts)-1]
}
|
package event
import (
"log"
"github.com/streadway/amqp"
)
// queueName is the queue that the consumer listens to.
const queueName = "test_queue"
// RunEventlistenter consumes and logs events on the queue.
func RunEventlistener() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
_, err = ch.QueueDeclare(
queueName, // name
true, // durable
false, // delete when unused
true, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "faild to declare queue")
err = ch.QueueBind(
queueName, // queue name
"", // routing key
ExchangeName, // exchange
false,
nil,
)
failOnError(err, "faild to bind queue")
msgs, err := ch.Consume(
queueName, // queue
"testConsumer", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
for d := range msgs {
log.Printf("event recieved: %s", d.Body)
}
}
|
package main
import (
"fmt"
"github.com/user/stringutil"
)
func main() {
fmt.Printf("Hello, Go.\n")
fmt.Printf(stringutil.Reverse("Hello Go reveresed"))
}
|
package boltdb
import (
"github.com/boltdb/bolt"
)
func NewCache(dbFile string) *bolt.DB {
db, err := bolt.Open(dbFile, 0600, nil)
if err != nil {
panic(err)
}
return db
}
|
package test
import (
"fmt"
"math/rand"
"testing"
)
func TestMerge(t *testing.T) {
arr := rand.Perm(10)
t.Log(arr)
arr = mergeSort(arr)
t.Log(arr)
}
func mergeSort(arr []int) []int {
if len(arr) < 2 {
return arr
}
mid := len(arr) / 2
left := arr[:mid]
right := arr[mid:]
return merge(mergeSort(left), mergeSort(right))
}
func merge(a, b []int) []int {
result := make([]int, 0, len(a)+len(b))
for len(a) != 0 && len(b) != 0 {
if a[0] < b[0] {
result = append(result, a[0])
a = a[1:]
} else {
result = append(result, b[0])
b = b[1:]
}
}
result = append(result, a...)
result = append(result, b...)
return result
}
func TestQuick(t *testing.T) {
arr := []int{2, 2, 2}
//arr := rand.Perm(10)
t.Log(arr)
quickSort(arr, 0, len(arr)-1)
t.Log(arr)
}
func quickSort(arr []int, low, height int) {
if low >= height {
return
}
left := low
right := height
p := arr[(left+right)/2]
for left <= right {
for arr[left] < p {
left++
}
for arr[right] > p {
right--
}
if left <= right {
arr[left], arr[right] = arr[right], arr[left]
fmt.Println("---")
left++
right--
}
}
quickSort(arr, low, right)
quickSort(arr, left, height)
}
|
package iarnrod
import (
"encoding/xml"
"errors"
"math"
"net/http"
"github.com/marcinwyszynski/geopoint"
)
const (
API_ENDPOINT = "http://api.irishrail.ie/realtime/realtime.asmx/"
STATIONS_ENDPOINT = API_ENDPOINT + "getAllStationsXML"
)
var (
allStations *StationArray
)
// StationArray struct represents all Irish Rail stations.
type StationArray struct {
XMLName xml.Name `xml:"ArrayOfObjStation"`
Stations []Station `xml:"objStation"`
}
// Constructor, pulling all Irish Rail using their API.
func GetAllStations() (*StationArray, error) {
if allStations != nil {
return allStations, nil
}
var result StationArray
resp, err := http.Get(STATIONS_ENDPOINT)
if err != nil {
return nil, err
}
defer resp.Body.Close()
decoder := xml.NewDecoder(resp.Body)
decoder.Strict = false
err = decoder.Decode(&result)
if err != nil {
return nil, err
}
allStations = &result
return GetAllStations()
}
// Given a geographic location, find the nearest station and distance to it.
func (s *StationArray) ClosestTo(point *geopoint.GeoPoint) (
station Station, distance float64, err error) {
distance = math.Inf(1)
if len(s.Stations) == 0 {
err = errors.New("No stations")
return
}
for _, st := range s.Stations {
d := st.GeoPoint().DistanceTo(point, geopoint.Haversine)
if d < distance {
distance = d
station = st
}
}
return
}
// Station struct represents the Irish Rail station.
type Station struct {
Id int `xml:"StationId"`
Name string `xml:"StationDesc"`
Alias string `xml:"StationAlias"`
Code string `xml:"StationCode"`
Latitude float64 `xml:"StationLatitude"`
Longitude float64 `xml:"StationLongitude"`
}
// Return the geographic point for the station.
func (s *Station) GeoPoint() *geopoint.GeoPoint {
return geopoint.NewGeoPoint(s.Latitude, s.Longitude)
}
|
// Copyright 2020 Winfried Klum
//
// 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 main
import (
"bufio"
"bytes"
"compress/zlib"
"context"
"encoding/base64"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v4"
)
var conn *pgx.Conn
var states = []string{"ENQUEUED", "PROCESSING", "WAITING", "FINISHED", "INVALID", "ERROR", "ALL"}
var validClassName = regexp.MustCompile(`^(?:\w+|\w+\.\w+)+$`)
var validLike = regexp.MustCompile(`^[^"'%]+$`)
const pgTimestampFormat = "2006-01-02 15:04:05.999999999"
func main() {
var err error
var args []string
pArgs := readPipe()
if len(os.Args) > 2 {
args = os.Args[2:]
}
args = append(args, pArgs...)
countCommand := flag.NewFlagSet("count", flag.ExitOnError)
countStatePtr := countCommand.String("state", "ERROR", "workflow instance state. Possible states:"+fmt.Sprint(states))
brokenCommand := flag.NewFlagSet("broken", flag.ExitOnError)
brokenPatternPtr := brokenCommand.String("exception-pattern", "", "filter search pattern for broken workflow instance exception message")
brokenStartTimePtr := brokenCommand.String("error-time-start", "", "filter on workflow error time, intervall start time in timestamp format, e.g. 2020-04-25 11:40:40.78")
brokenEndTimePtr := brokenCommand.String("error-time-end", "", "filter on workflow error time, intervall end time in timestamp format, e.g. 2020-04-26 11:40:40.78")
brokenCountTimerPtr := brokenCommand.Bool("print-count", false, "Print number of (filtered) broken workflow instances")
brokenClassPtr := brokenCommand.String("workflow-class", "", "filter on workflow instance class, full package name required, e.g. org.foo.wf.MyWorkflow")
dataCommand := flag.NewFlagSet("data", flag.ExitOnError)
dataSelectorPtr := dataCommand.String("json-selector", "", "json selector, e.g. json->1='test', (only available for data in JSON format)")
dataStatePtr := dataCommand.String("state", "ERROR", "workflow instance state. Possible states:"+fmt.Sprint(states))
showCommand := flag.NewFlagSet("show", flag.ExitOnError)
showDataPtr := showCommand.Bool("workflow-data", false, "show workflow instance data (only available for data in JSON format)")
showAuditPtr := showCommand.Bool("audit-trail", false, "show audit trail messages")
showInstancePtr := showCommand.Bool("instance-details", false, "show workflow instance details")
showDataArrPtr := showCommand.Bool("print-data-array", false, "print workflow data list as json array, only valid in combination with -workflow-data flag")
deleteCommand := flag.NewFlagSet("delete", flag.ExitOnError)
restartCommand := flag.NewFlagSet("restart", flag.ExitOnError)
cleanupCommand := flag.NewFlagSet("cleanup", flag.ExitOnError)
cleanupAgePtr := cleanupCommand.String("age", "", "filter on age. Format as timestamp, days(d) or hours(h), e.g. 2006-01-02 15:04:05.99, 35d, 24h")
cleanupAuditPtr := cleanupCommand.Bool("audit-trail", false, "delete audit trail data older than age")
cleanupInstancePtr := cleanupCommand.Bool("workflow-instance", false, "delete workflow instance data older than age")
if len(os.Args) < 2 {
printHelp()
os.Exit(1)
}
switch os.Args[1] {
case "count":
countCommand.Parse(args)
case "broken":
brokenCommand.Parse(args)
case "delete":
deleteCommand.Parse(args)
case "show":
showCommand.Parse(args)
case "restart":
restartCommand.Parse(args)
case "data":
dataCommand.Parse(args)
case "cleanup":
cleanupCommand.Parse(args)
default:
printHelp()
os.Exit(1)
}
conn, err = pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
exitOnErr("Unable to connect to database: %v\nMake sure that DATABASE_URL environment variable is set", err)
}
if countCommand.Parsed() {
count(*countStatePtr)
}
if brokenCommand.Parsed() {
broken(*brokenPatternPtr, *brokenStartTimePtr, *brokenEndTimePtr, *brokenCountTimerPtr, *brokenClassPtr)
}
if deleteCommand.Parsed() {
args := deleteCommand.Args()
delete(args)
}
if showCommand.Parsed() {
args := showCommand.Args()
show(*showDataPtr, args, *showAuditPtr, *showInstancePtr, *showDataArrPtr)
}
if restartCommand.Parsed() {
args := restartCommand.Args()
restart(args)
}
if dataCommand.Parsed() {
jsonData(dataSelectorPtr, *dataStatePtr)
}
if cleanupCommand.Parsed() {
cleanup(*cleanupAgePtr, *cleanupAuditPtr, *cleanupInstancePtr)
}
}
func printHelp() {
fmt.Println("Copper Postgres Tool\nUsage:\n",
"count\n",
"broken\n",
"show\n",
"delete\n",
"restart\n",
"data (only available for Json format)\n",
"cleanup\n",
"add -help after command to get more information")
}
func count(state string) {
var count int64
var err error
stateIdx := stateIndex(state)
if stateIdx < 0 {
exitOnErr("Invalid state: %v. Allowed states are: %v ", state, fmt.Sprint(states))
}
if states[stateIdx] == "ALL" {
err = conn.QueryRow(context.Background(), "select count(id) as WORKFLOW_COUNT from cop_workflow_instance").Scan(&count)
} else {
err = conn.QueryRow(context.Background(), "select count(id) as WORKFLOW_COUNT from cop_workflow_instance where state=$1;", stateIdx).Scan(&count)
}
if err != nil {
exitOnErr("Error reading count: %v", err)
}
fmt.Fprintf(os.Stdout, "%v\n", count)
}
func broken(pattern string, stime string, etime string, count bool, classname string) {
var sqlBuffer bytes.Buffer
if count {
sqlBuffer.WriteString("select count(workflow_instance_id)")
} else {
sqlBuffer.WriteString("select workflow_instance_id")
}
sqlBuffer.WriteString("from cop_workflow_instance_error as e, cop_workflow_instance as i where e.workflow_instance_id=i.id")
if len(pattern) > 0 {
if validLike.MatchString(pattern) {
sqlBuffer.WriteString(" and e.exception like '%" + pattern + "%'")
} else {
exitOnErr("Invalid exception-pattern: %v", pattern)
}
}
if len(classname) > 0 {
if validClassName.MatchString(classname) {
sqlBuffer.WriteString(" and i.classname='" + classname + "'")
} else {
exitOnErr("Invalid workflow-classname: %v", classname)
}
}
if len(stime) > 0 {
sqlBuffer.WriteString(" and e.error_ts >= '" + stime + "'")
}
if len(etime) > 0 {
sqlBuffer.WriteString(" and e.error_ts <= '" + etime + "'")
}
sqlBuffer.WriteString(";")
if count {
var ids int64
err := conn.QueryRow(context.Background(), sqlBuffer.String()).Scan(&ids)
if err != nil {
fmt.Fprintf(os.Stderr, "Workflow instance error count failed: %v\n", err)
return
}
fmt.Println(ids)
return
}
rows, err := conn.Query(context.Background(), sqlBuffer.String())
if err != nil {
exitOnErr("Workflow instance error search failed: %v\n", err)
}
for rows.Next() {
var id string
err1 := rows.Scan(&id)
if err1 != nil {
fmt.Fprintf(os.Stderr, "Error reading workflow instance id, error: %v", err1)
}
fmt.Println(id)
}
}
func delete(args []string) {
var err error
for _, id := range args {
_, err = conn.Exec(context.Background(), "select 1 from cop_workflow_instance where id=$1 for update", id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error locking workflow instance id=%v, skipping...\n", id)
continue
}
_, err = conn.Exec(context.Background(), "delete from cop_response where correlation_id in (select correlation_id from cop_wait where workflow_instance_id=$1)", id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error deleteing workflow instance from COP_RESPONSE id=%v\n", id)
err = nil
}
_, err = conn.Exec(context.Background(), "delete from cop_wait where workflow_instance_id=$1", id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error deleting workflow instance from COP_WAIT id=%v\n", id)
err = nil
}
_, err = conn.Exec(context.Background(), "delete from cop_workflow_instance_error where workflow_instance_id=$1", id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error deleting workflow instance from COP_WORKFLOW_INSTANCE_ERROR, id=%v\n", id)
err = nil
}
_, err = conn.Exec(context.Background(), "delete from cop_workflow_instance where id=$1", id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error deleting workflow instance from COP_WORKFLOW_INSTANCE, id=%v\n", id)
}
}
}
func show(showData bool, args []string, audit bool, instance bool, asArray bool) {
var data, ppoolID, classname string
var state, priority, csWaitmode, minNumbOfResp, numbOfWaits int
var lastModTs, creationTs time.Time
var timeout *time.Time
if (!showData && !audit) && !instance {
exitOnErr("Use at least one of the following flags:[-workflow-data,-audit-trail,-instance-details]")
}
if (asArray && !showData) || (asArray && (audit || instance)) {
exitOnErr("Flag -print-data-array is only allowed together with -workflow-data flag")
}
if asArray {
instance = false
audit = false
fmt.Println("[")
}
for i, id := range args {
sql := "select data, state, priority, last_mod_ts, ppool_id,cs_waitmode, min_numb_of_resp, numb_of_waits, timeout, creation_ts, classname from cop_workflow_instance where id=$1"
err := conn.QueryRow(context.Background(), sql, id).Scan(&data, &state, &priority, &lastModTs, &ppoolID, &csWaitmode, &minNumbOfResp, &numbOfWaits, &timeout, &creationTs, &classname)
if err == nil {
if instance {
stateTxt, _ := indexState(state)
fmt.Println("Workflow Instance:")
fmt.Printf("id:%v, state:%v, priority:%v, creation time:%v, last modification:%v\n", id, stateTxt, priority, creationTs, lastModTs)
fmt.Printf("pool id:%v, wait mode:%v, number of waits:%v, class name:%v", ppoolID, csWaitmode, numbOfWaits, classname)
if timeout != nil {
fmt.Printf(", timeout:%v", *timeout)
}
fmt.Println("")
}
if showData && instance {
fmt.Println("Instance data:")
}
if showData {
fmt.Printf("%v\n", data)
}
}
if audit {
auditMsgs(id)
}
if i+1 < len(args) {
if asArray {
fmt.Println(",")
} else {
fmt.Println("--------------------------------------------------------------------------------------------------------------")
}
}
}
if asArray {
fmt.Println("]")
}
}
func auditMsgs(id string) {
first := true
sql := "select long_message,occurrence from cop_audit_trail_event where instance_id=$1 order by occurrence"
rows, err := conn.Query(context.Background(), sql, id)
if err != nil {
return
}
for rows.Next() {
if first {
fmt.Println("Audit Trail:")
}
first = false
var msg string
var occurrence time.Time
err1 := rows.Scan(&msg, &occurrence)
if err1 != nil {
fmt.Fprintf(os.Stderr, "Error retrieving audit entry:%v", err1)
continue
}
dmsg, err := decodeMsg(msg)
if err == nil {
fmt.Printf("Occurrence: %v, message: %v\n", occurrence, dmsg)
}
}
}
func restart(args []string) {
for _, id := range args {
now := time.Now()
sql := "insert into cop_queue (ppool_id, priority, last_mod_ts, workflow_instance_id) (select ppool_id, priority, $1, id from cop_workflow_instance where id=$2 and (state=4 or state=5))"
_, err := conn.Exec(context.Background(), sql, now, id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error restarting workflow instance: %v, %v", id, err)
continue
}
sql = "update cop_workflow_instance set state=0, last_mod_ts=$1 where id=$2 and (state=4 or state=4)"
_, err = conn.Exec(context.Background(), sql, now, id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error restarting workflow instance:%v, %v", id, err)
continue
}
_, err = conn.Exec(context.Background(), "delete from cop_workflow_instance_error where workflow_instance_id=$1", id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error removing workflow instance: %v from error table, %v", id, err)
}
}
}
func cleanup(age string, audit bool, instance bool) {
if len(age) < 1 {
exitOnErr("Flag -age is mandatory")
}
if !audit && !instance {
exitOnErr("Use at least one of the following flags: [-audit-trail,-workflow-instance]")
}
atime, err := parseAge(age)
if err != nil {
exitOnErr("Invalid age value %v. Use valid day(d), hours(h) or timestamp format", age)
}
if instance {
sql := "delete from cop_workflow_instance_error where error_ts < $1;"
conn.Exec(context.Background(), sql, atime)
sql = "delete from cop_response where response_ts < $1;"
conn.Exec(context.Background(), sql, atime)
sql = "delete from cop_wait where workflow_instance_id IN (select id from cop_workflow_instance where creation_ts < $1);"
conn.Exec(context.Background(), sql, atime)
sql = "delete from cop_adaptercall where workflowid IN (select id from cop_workflow_instance where creation_ts < $1);"
conn.Exec(context.Background(), sql, atime)
sql = "delete from cop_lock where workflow_instance_id IN (select id from cop_workflow_instance where creation_ts < $1);"
conn.Exec(context.Background(), sql, atime)
sql = "delete from cop_queue where workflow_instance_id IN (select id from cop_workflow_instance where creation_ts < $1);"
conn.Exec(context.Background(), sql, atime)
sql = "delete from cop_workflow_instance where creation_ts < $1;"
conn.Exec(context.Background(), sql, atime)
}
if audit {
sql := "delete from cop_audit_trail_event where occurrence < $1;"
conn.Exec(context.Background(), sql, atime)
}
fmt.Fprintf(os.Stdout, "deleted data older than %v", atime)
}
func readPipe() []string {
info, _ := os.Stdin.Stat()
if (info.Mode() & os.ModeCharDevice) == 0 {
reader := bufio.NewReader(os.Stdin)
var output []rune
for {
input, _, err := reader.ReadRune()
if err != nil && err == io.EOF {
break
}
output = append(output, input)
}
return strings.Split(strings.Trim(string(output), "\n"), "\n")
}
return nil
}
func stateIndex(state string) int {
aState := strings.ToUpper(state)
idx, _ := find(states, aState)
return idx
}
func indexState(idx int) (string, error) {
if idx > -1 && idx < len(states) {
return states[idx], nil
}
return "", errors.New("Invalid state index")
}
func find(slice []string, val string) (int, bool) {
for i, item := range slice {
if item == val {
return i, true
}
}
return -1, false
}
func decodeMsg(msg string) (string, error) {
var dmsg []byte
if msg[0] != 'C' && msg[0] != 'U' {
return msg, nil
}
r := base64.NewDecoder(base64.StdEncoding, strings.NewReader(msg[1:]))
dmsg, err := ioutil.ReadAll(r)
if err != nil {
return msg, err
}
if msg[0] == 'C' {
r, err := zlib.NewReader(bytes.NewReader(dmsg))
if err != nil {
return "", err
}
dmsg, err = ioutil.ReadAll(r)
if err != nil {
return "", err
}
}
return string(dmsg[7:]), err
}
func jsonData(selector *string, state string) {
var err error
var sql string
if selector == nil {
exitOnErr("Flag -json-selector is mandatory")
}
stateIdx := stateIndex(state)
stateInt := strconv.Itoa(stateIdx)
if stateIdx < 0 {
exitOnErr("Invalid state: %v. Allowed states are: %v", state, fmt.Sprint(states))
}
if states[stateIdx] == "ALL" {
sql = "select id from (select id,state, data::jsonb as json from cop_workflow_instance) as r where " + *selector
} else {
sql = "select id from (select id,state, data::jsonb as json from cop_workflow_instance) as r where state=" + stateInt + " and " + *selector
}
rows, err := conn.Query(context.Background(), sql)
if err != nil {
exitOnErr("Query Error:%v", err)
}
for rows.Next() {
var id string
err1 := rows.Scan(&id)
if err1 == nil {
fmt.Println(id)
}
}
}
func parseAge(age string) (time.Time, error) {
var dur string
var err error
var atime time.Time
if strings.HasSuffix(age, "d") {
days, err := strconv.Atoi(age[0 : len(age)-1])
if err != nil {
err = errors.New("Invalid day format " + age)
} else {
dur = strconv.Itoa(days*24) + "h"
}
} else if strings.HasSuffix(age, "h") {
dur = age
}
if err == nil {
if len(dur) > 0 {
var value time.Duration
value, err = time.ParseDuration(dur)
if value <= 0 {
err = errors.New("Invalid age value " + age)
}
if err == nil {
atime = time.Now().Add(-value)
}
} else {
atime, err = time.Parse(pgTimestampFormat, age)
}
}
return atime, err
}
func exitOnErr(msg string, val ...interface{}) {
if val != nil {
fmt.Fprintf(os.Stderr, msg+"\n", val...)
} else {
fmt.Fprintln(os.Stderr, msg)
}
os.Exit(1)
}
|
package retoil
import (
"time"
)
type internalDelayedLimitedStrategy struct{
retoilCount uint
maxRetoils uint
delay time.Duration
}
// DelayedLimitedStrategy returns an initialized retoil.Strategizer which will only
// cause a retoil on a panic() (and not on a return) at most 'maxRetoils' times with
// at least a delay of 'delay' between each retoil.
func DelayedLimitedStrategy(maxRetoils uint, delay time.Duration) Strategizer {
strategy := internalDelayedLimitedStrategy{
retoilCount:0,
maxRetoils:maxRetoils,
delay:delay,
}
return &strategy
}
func (strategy *internalDelayedLimitedStrategy) MayPanickedRetoil(interface{}) bool {
if strategy.retoilCount >= strategy.maxRetoils {
return false
}
time.Sleep(strategy.delay)
strategy.retoilCount++
return true
}
func (strategy *internalDelayedLimitedStrategy) MayReturnedRetoil() bool {
return false
}
|
package cmd
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const ToolName = "direktivctl"
var maxSize int64 = 1073741824
func ProjectFolder() (string, error) {
projectFile := viper.GetString("projectFile")
if projectFile != "" {
return path.Dir(projectFile), nil
}
return "", fmt.Errorf("project directory not found")
}
func Fail(cmd *cobra.Command, s string, x ...interface{}) {
cmd.PrintErrf(strings.TrimSuffix(s, "\n")+"\n", x...)
os.Exit(1)
}
func pingNamespace() error {
urlGetNode := fmt.Sprintf("%s/tree/", UrlPrefix)
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodGet,
urlGetNode,
nil,
)
if err != nil {
return fmt.Errorf("failed to create request file: %w", err)
}
AddAuthHeaders(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to ping namespace %s: %w", urlGetNode, err)
}
// it is either ok or forbidden which means the namespace exists
// but the user might not have access to the explorer
// it would be still ok to e.g. send events
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusForbidden {
// if resp.StatusCode == http.StatusUnauthorized {
// return fmt.Errorf("failed to ping namespace %s, request was unauthorized", urlGetNode)
// }
errBody, err := io.ReadAll(resp.Body)
if err == nil {
return fmt.Errorf("failed to ping namespace %s, server responded with %s\n------DUMPING ERROR BODY ------\n%s", urlGetNode, resp.Status, string(errBody))
}
return fmt.Errorf("failed to ping namespace %s, server responded with %s\n------DUMPING ERROR BODY ------\nCould read response body", urlGetNode, resp.Status)
}
return nil
}
func SafeLoadFile(filePath string) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
if filePath == "" {
// skip if filePath is empty
return buf, nil
}
fStat, err := os.Stat(filePath)
if err != nil {
return buf, err
}
if fStat.Size() > maxSize {
return buf,
fmt.Errorf("file is larger than maximum allowed size: %v. Set configfile 'max-size' to change",
maxSize)
}
fData, err := os.ReadFile(filePath)
if err != nil {
return buf, err
}
buf = bytes.NewBuffer(fData)
return buf, nil
}
func SafeLoadStdIn() (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
fi, err := os.Stdin.Stat()
if err != nil {
return buf, err
}
if fi.Mode()&os.ModeNamedPipe == 0 {
// No stdin
return buf, nil
}
if fi.Size() > maxSize {
return buf,
fmt.Errorf("stdin is larger than maximum allowed size: %v. Set configfile 'max-size' to change",
maxSize)
}
fData, err := io.ReadAll(os.Stdin)
if err != nil {
return buf, err
}
buf = bytes.NewBuffer(fData)
return buf, nil
}
func InitConfiguration(cmd *cobra.Command, args []string) {
err := initCLI(cmd)
if err != nil {
Fail(cmd, "Got an error while initializing: %v", err)
}
cmdPrepareSharedValues()
if err := pingNamespace(); err != nil {
log.Fatalf("%v", err)
}
}
func InitConfigurationAndProject(cmd *cobra.Command, args []string) {
InitConfiguration(cmd, args)
err := initProjectDir(cmd)
if err != nil {
Fail(cmd, "Got an error while initializing: %v", err)
}
err = InitWD()
if err != nil {
Fail(cmd, "Got an error while initializing: %v", err)
}
}
func InitWD() error {
directory := viper.GetString("directory")
if directory == "" {
pwd, err := os.Getwd()
if err != nil {
return err
}
viper.Set("directory", pwd)
}
return nil
}
func GetMaxSize() int64 {
if cfgMaxSize := viper.GetInt64("max-size"); cfgMaxSize > 0 {
return cfgMaxSize
}
return maxSize
}
|
package library
type Controller struct {
BaseUrl string
ActionName string
ControllerName string
methodMapping map[string]func()
Body string
}
func (c Controller) setBashUrl(url string){
c.BaseUrl = url
}
func (c Controller) setActionName(actionName string){
c.ActionName = actionName
}
func (c Controller) setControllerName(cName string) {
c.ControllerName = cName
}
|
package leetcode
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func minTimeToVisitAllPoints(points [][]int) int {
var prev *[]int
ans := 0
for _, p := range points {
if prev != nil {
ans += max(abs((*prev)[0]-p[0]), abs((*prev)[1]-p[1]))
}
prev = &[]int{p[0], p[1]}
}
return ans
}
|
package blog
import (
"github.com/jinzhu/gorm"
)
type (
User struct {
gorm.Model
Email string `json:"email" gorm:"type:varchar(100);unique_index"`
Password string `json:"password,omitempty"`
Token string `json:"token,omitempty"`
}
)
// AuthUser represents data stored in JWT token for user
type AuthUser struct {
ID int
Email string
}
// UpdateLastLogin updates last login field
func (u *User) UpdateLastLogin(token string) {
u.Token = token
}
|
package prediction
import (
"fmt"
"math/big"
"github.com/streamingfast/sparkle/entity"
pbcodec "github.com/streamingfast/sparkle/pb/dfuse/ethereum/codec/v1"
)
func (s *Subgraph) HandlePredictionLockRoundEvent(trace *pbcodec.TransactionTrace, ev *PredictionLockRoundEvent) error {
if s.StepBelow(2) {
return nil
}
round := NewRound(fmt.Sprintf("%d", ev.Epoch))
if err := s.Load(round); err != nil {
return err
}
if !round.Exists() {
return fmt.Errorf("Tried to lock round without an existing round (epoch: %s).", ev.Epoch)
}
round.LockAt = entity.NewInt(bi().SetInt64(s.Block().Timestamp().Unix())).Ptr()
round.LockBlock = entity.NewIntFromLiteral(int64(s.Block().Number())).Ptr()
round.LockHash = trace.Hash
round.LockPrice = entity.NewFloat(bf().Quo(
bf().SetInt(ev.Price),
big.NewFloat(1e8), // 8 decimals
)).Ptr()
if err := s.Save(round); err != nil {
return err
}
return nil
}
|
package main
import (
"net/http"
"os"
_ "github.com/joho/godotenv/autoload"
log "github.com/sirupsen/logrus"
"github.com/gorilla/handlers"
h "github.com/roger-king/go-ecommerce/pkg/handlers"
"github.com/roger-king/go-ecommerce/pkg/models"
)
func init() {
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.InfoLevel)
}
func main() {
port := os.Getenv("PORT")
// DB Connection
dbConnectionString := os.Getenv("DB_CONNECTION_STRING")
models.InitDB(dbConnectionString)
if port == "" {
log.Panic("$PORT is not defined")
}
router := h.NewRouter()
allowedOrigins := handlers.AllowedOrigins([]string{"*"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "DELETE", "PUT"})
log.Errorln(http.ListenAndServe(":"+port, handlers.CORS(allowedOrigins, allowedMethods)(router)))
log.Info("Application is running on port %s", port)
}
|
package crypt
import (
"golang.org/x/crypto/bcrypt"
)
func Check(hashed string, pass string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(pass))
if err == nil {
return true
} else {
return false
}
}
func Hash(pass string) string {
password := []byte(pass)
// Hashing the password with the default cost of 10
hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
panic(err)
}
return string(hashed)
}
|
package main
import (
"testing"
)
func TestMain(t *testing.T) {
inputCommand := []string{"create_parking_lot 6", "park KA-01-HH-1234 White",
"park KA-01-HH-9999 White",
"park KA-01-BB-0001 Black",
"park KA-01-HH-7777 Red",
"park KA-01-HH-2701 Blue",
"park KA-01-HH-3141 Black",
"leave 4",
"status",
"park KA-01-P-333 White",
"park DL-12-AA-9999 White",
"registration_numbers_for_cars_with_colour White",
"slot_numbers_for_cars_with_colour White",
"slot_number_for_registration_number KA-01-HH-3141",
"slot_number_for_registration_number MH-04-AY-1111",
}
ProcessInput(inputCommand)
}
func TestLeaveWithoutError(t *testing.T) {
stackList := make([]*Vehicle, 6)
removeID := 2
exists := true
for i, v := range stackList {
if v == nil {
vehicle := &Vehicle{
ID: (i + 1),
VehicleID: "KA-01-HH-1234",
Color: "White",
}
stackList = append(stackList, vehicle)
}
}
// error log
expected := ""
err := "vehicleID exists"
actual := Remove(stackList, removeID)
list := Remove(stackList, removeID)
for i, _ := range list {
if i == removeID-1 {
list[i] = nil
exists = false
}
}
if actual == nil && exists == false {
t.Errorf("Test failed, expected: '%s', got: '%s'", expected, err)
}
}
func TestCreateParkingLotWithoutError(t *testing.T) {
actualAllocated := 2
actualStackList := make([]*Vehicle, actualAllocated)
stackList := CreateSlice(actualAllocated)
if len(stackList) != len(actualStackList) {
t.Errorf("Test failed, expected: '%s', got: '%s'", "expected length of stackList", "different length of Vehicle")
}
}
func TestParkWithoutError(t *testing.T) {
stackList := make([]*Vehicle, 6)
exists := false
for i, v := range stackList {
if v == nil {
// dummy index 4 is nil
// this will bypass if there is nil in stackList, then will insert in Park()
if i != 3 {
vehicle := &Vehicle{
ID: (i + 1),
VehicleID: "KA-01-HH-1234",
Color: "White",
}
stackList = append(stackList, vehicle)
}
}
}
// error log
expected := ""
err := "vehicleID exists"
actualAllocated := 3
// actual, actualAllocated := Park(stackList, "KA-01-HH-3141", "Black")
list, allocated := Park(stackList, "KA-01-HH-3141", "Black")
for i, v := range list {
if i == allocated {
if v == nil {
exists = true
}
}
}
if actualAllocated != allocated {
if allocated != 3 && exists == false {
t.Errorf("Test failed, expected: '%s', got: '%s'", expected, err)
}
}
}
|
package token
const (
// ILLEGAL token
ILLEGAL = "ILLEGAL"
// EOF end of file
EOF = "EOF"
// IDENT indenfier
IDENT = "IDENT"
// INT integer
INT = "INT"
// ASSIGN operator
ASSIGN = "="
// PLUS operator
PLUS = "+"
// MINUS operator
MINUS = "-"
// BANG operator
BANG = "!"
// ASTERISK operator
ASTERISK = "*"
// SLASH operator
SLASH = "/"
// LT less than
LT = "<"
// GT greater than
GT = ">"
// COMMA delimiter
COMMA = ","
// SEMICOLON delimiter
SEMICOLON = ";"
// LPAREN left paren
LPAREN = "("
// RPAREN right paren
RPAREN = ")"
// LBRACE left curly brace
LBRACE = "{"
// RBRACE left curly brace
RBRACE = "}"
// FUNCTION keyword
FUNCTION = "FUNCTION"
// LET keyword
LET = "LET"
// TRUE keyword
TRUE = "TRUE"
// FALSE keyword
FALSE = "FALSE"
// IF keyword
IF = "IF"
// ELSE keyword
ELSE = "ELSE"
// RETURN keyword
RETURN = "RETURN"
// EQ equal
EQ = "=="
// NOT_EQ not equal
NOT_EQ = "!="
)
// TokenType is the type of token we are representing in our lexer
type TokenType string
// Token is the struct that holds both the type and the literal value
type Token struct {
Type TokenType
Literal string
}
var keywords = map[string]TokenType{
"fn": FUNCTION,
"let": LET,
"true": TRUE,
"false": FALSE,
"if": IF,
"else": ELSE,
"return": RETURN,
}
// LookupIdent checkes the keywords table to see whether the given
// identifier is, in fact, a keyword
func LookupIdent(ident string) TokenType {
if tok, ok := keywords[ident]; ok {
return tok
}
return IDENT
}
|
package main
import "fmt"
func main() {
var board [3][3]int
turn := 0
stop := false
// while the game has not ended
for stop == false {
fmt.Println("Turn", turn)
displayBoard(board[:])
fmt.Printf("Player %d, please enter move, or -1 -1 to quit: ", getPlayer(turn))
row, col := 0, 0
fmt.Scanf("%d %d", &row, &col)
if row == -1 || col == -1 {
stop = true
}
if (board[row][col] == 0) {
board[row][col] = getPlayer(turn)
// increase turn
turn++;
} else {
fmt.Println("Invalid move, please try again")
}
// has anyone won? (-1 is none, 0 or 1)
winner := gameEnded(board[:])
if winner != -1 {
stop = true
fmt.Printf("Player %d has won!", winner+1)
}
}
}
func getPlayer(turn int) int {
if turn % 2 == 0 {
return 1
} else {
return 2
}
}
func displayBoard(board [][3]int) {
for _, r := range board {
for _, c := range r {
fmt.Printf("%d ", c)
}
fmt.Println()
}
}
func gameEnded(board [][3]int) int {
// check if who have won
// check rows
for i :=0; i < 3; i++ {
if board[i][0] == board[i][1] && board[i][0] == board[i][2] {
return board[i][0]
}
}
// check cols
for j :=0; j < 3; j++ {
if board[0][j] == board[1][j] && board[0][j] == board[2][j] {
return board[0][j]
}
}
// check diagionals
if board[0][0] == board[1][1] && board[0][0 ]== board[2][2] {
return board[0][0]
}
if board[0][2] == board[1][1] && board[0][2] == board[2][0] {
return board[0][2]
}
// no result
return -1
}
|
package main
import "fmt"
func main() {
helloWorld() //1
}
func helloWorld() { //#1
fmt.Println("Hello World") //Penulisan Hello World
}
|
// Copyright (C) 2021 Cisco Systems 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 vpplink
import (
"fmt"
"io"
"github.com/projectcalico/vpp-dataplane/v3/vpplink/generated/bindings/interface_types"
"github.com/projectcalico/vpp-dataplane/v3/vpplink/generated/bindings/memif"
"github.com/projectcalico/vpp-dataplane/v3/vpplink/types"
)
func (v *VppLink) addDelMemifSocketFileName(socketFileName string, socketId uint32, isAdd bool) (socketID uint32, err error) {
client := memif.NewServiceClient(v.GetConnection())
response, err := client.MemifSocketFilenameAddDelV2(v.GetContext(), &memif.MemifSocketFilenameAddDelV2{
IsAdd: isAdd,
SocketFilename: socketFileName,
SocketID: socketId,
})
if err != nil {
return 0, fmt.Errorf("MemifSocketFilenameAddDel failed: %w", err)
}
return response.SocketID, nil
}
func (v *VppLink) AddMemifSocketFileName(socketFileName string) (uint32, error) {
socketId, err := v.addDelMemifSocketFileName(socketFileName, ^uint32(0), true /* isAdd */)
return socketId, err
}
func (v *VppLink) DelMemifSocketFileName(socketId uint32) error {
_, err := v.addDelMemifSocketFileName("", socketId, false /* isAdd */)
return err
}
func (v *VppLink) ListMemifSockets() ([]*types.MemifSocket, error) {
client := memif.NewServiceClient(v.GetConnection())
stream, err := client.MemifSocketFilenameDump(v.GetContext(), &memif.MemifSocketFilenameDump{})
if err != nil {
return nil, fmt.Errorf("failed to dump memif sockets: %w", err)
}
sockets := make([]*types.MemifSocket, 0)
for {
response, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("failed to dump memif sockets: %w", err)
}
sockets = append(sockets, &types.MemifSocket{
SocketID: response.SocketID,
SocketFilename: response.SocketFilename,
})
}
return sockets, nil
}
func (v *VppLink) DeleteMemif(swIfIndex uint32) error {
client := memif.NewServiceClient(v.GetConnection())
_, err := client.MemifDelete(v.GetContext(), &memif.MemifDelete{
SwIfIndex: interface_types.InterfaceIndex(swIfIndex),
})
if err != nil {
return fmt.Errorf("DeleteMemif failed: %w", err)
}
return nil
}
func (v *VppLink) CreateMemif(mif *types.Memif) error {
client := memif.NewServiceClient(v.GetConnection())
request := &memif.MemifCreate{
Role: memif.MemifRole(mif.Role),
Mode: memif.MemifMode(mif.Mode),
RxQueues: uint8(mif.NumRxQueues),
TxQueues: uint8(mif.NumTxQueues),
SocketID: mif.SocketId,
BufferSize: uint16(mif.QueueSize),
}
if mif.MacAddress != nil {
request.HwAddr = types.MacAddress(mif.MacAddress)
}
response, err := client.MemifCreate(v.GetContext(), request)
if err != nil {
return fmt.Errorf("MemifCreate failed: %w", err)
}
mif.SwIfIndex = uint32(response.SwIfIndex)
return nil
}
func (v *VppLink) ListMemifInterfaces() ([]*types.Memif, error) {
client := memif.NewServiceClient(v.GetConnection())
stream, err := client.MemifDump(v.GetContext(), &memif.MemifDump{})
if err != nil {
return nil, fmt.Errorf("failed to dump memif interfaces: %w", err)
}
memifs := make([]*types.Memif, 0)
for {
response, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("failed to dump memif interfaces: %w", err)
}
memifs = append(memifs, &types.Memif{
SwIfIndex: uint32(response.SwIfIndex),
Role: types.MemifRole(response.Role),
Mode: types.MemifMode(response.Mode),
SocketId: response.SocketID,
QueueSize: int(response.BufferSize),
Flags: types.MemifFlag(response.Flags),
})
}
return memifs, nil
}
func (v *VppLink) MemifsocketByID(socketID uint32) (*types.MemifSocket, error) {
sockets, err := v.ListMemifSockets()
if err != nil {
return nil, fmt.Errorf("error listing memif sockets: %w", err)
}
for _, socket := range sockets {
if socket.SocketID == socketID {
return socket, nil
}
}
return nil, fmt.Errorf("can't find socket with id %d", socketID)
}
|
// Copyright (C) 2017 Google 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 replay
import (
"context"
"io/ioutil"
"os"
gopath "path"
"github.com/golang/protobuf/proto"
"github.com/google/gapid/core/archive"
"github.com/google/gapid/core/data/id"
"github.com/google/gapid/core/log"
"github.com/google/gapid/core/os/device/bind"
gapir "github.com/google/gapid/gapir/client"
"github.com/google/gapid/gapis/capture"
"github.com/google/gapid/gapis/database"
"github.com/google/gapid/gapis/replay/builder"
"github.com/google/gapid/gapis/resolve/initialcmds"
"github.com/google/gapid/gapis/service/path"
)
// ExportReplay write replay commands and assets to path.
func ExportReplay(ctx context.Context, pCapture *path.Capture, pDevice *path.Device, outDir string) error {
if pDevice == nil {
return log.Errf(ctx, nil, "Unable to produce replay on unknown device.")
}
ctx = capture.Put(ctx, pCapture)
c, err := capture.Resolve(ctx)
if err != nil {
return err
}
// Capture can use multiple APIs.
// Iterate the APIs in use looking for those that support replay generation.
var generator Generator
for _, a := range c.APIs {
if a, ok := a.(Generator); ok {
generator = a
break
}
}
if generator == nil {
return log.Errf(ctx, nil, "Unable to find replay API.")
}
d := bind.GetRegistry(ctx).Device(pDevice.ID.ID())
if d == nil {
return log.Errf(ctx, nil, "Unknown device %v", pDevice.ID.ID())
}
ctx = log.V{
"capture": pCapture.ID.ID(),
"device": d.Instance().GetName(),
}.Bind(ctx)
cml := c.Header.ABI.MemoryLayout
ctx = log.V{"capture memory layout": cml}.Bind(ctx)
deviceABIs := d.Instance().GetConfiguration().GetABIs()
if len(deviceABIs) == 0 {
return log.Err(ctx, nil, "Replay device doesn't list any ABIs")
}
replayABI := findABI(cml, deviceABIs)
if replayABI == nil {
log.I(ctx, "Replay device does not have a memory layout matching device used to trace")
replayABI = deviceABIs[0]
}
ctx = log.V{"replay target ABI": replayABI}.Bind(ctx)
b := builder.New(replayABI.MemoryLayout)
_, ranges, err := initialcmds.InitialCommands(ctx, pCapture)
generatorReplayTimer.Time(func() {
err = generator.Replay(
ctx,
Intent{pDevice, pCapture},
Config(&struct{}{}),
[]RequestAndResult{{
Request: Request(generator.(interface{ ExportReplayRequest() Request }).ExportReplayRequest()),
Result: func(val interface{}, err error) {},
}},
d.Instance(),
c,
&adapter{
state: c.NewUninitializedState(ctx).ReserveMemory(ranges),
builder: b,
})
})
if err != nil {
return log.Err(ctx, err, "Replay returned error")
}
var payload gapir.Payload
var handlePost builder.PostDataHandler
var handleNotification builder.NotificationHandler
builderBuildTimer.Time(func() { payload, handlePost, handleNotification, err = b.Build(ctx) })
if err != nil {
return log.Err(ctx, err, "Failed to build replay payload")
}
err = os.MkdirAll(outDir, os.ModePerm)
if err != nil {
return log.Errf(ctx, err, "Failed to create output directory: %v", outDir)
}
payloadBytes, err := proto.Marshal(&payload)
if err != nil {
return log.Errf(ctx, err, "Failed to serialize replay payload.")
}
err = ioutil.WriteFile(gopath.Join(outDir, "payload.bin"), payloadBytes, 0644)
ar := archive.New(gopath.Join(outDir, "resources"))
defer ar.Dispose()
db := database.Get(ctx)
for _, ri := range payload.Resources {
rID, err := id.Parse(ri.Id)
if err != nil {
return log.Errf(ctx, err, "Failed to parse resource id: %v", ri.Id)
}
obj, err := db.Resolve(ctx, rID)
if err != nil {
return log.Errf(ctx, err, "Failed to parse resource id: %v", ri.Id)
}
ar.Write(ri.Id, obj.([]byte))
}
return nil
}
|
// Copyright 2021 PingCAP, 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 domain
import (
"fmt"
"path/filepath"
"testing"
"time"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/util/replayer"
"github.com/stretchr/testify/require"
)
func TestPlanReplayerDifferentGC(t *testing.T) {
dirName := replayer.GetPlanReplayerDirName()
time1 := time.Now().Add(-7 * 25 * time.Hour).UnixNano()
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField", fmt.Sprintf("return(%d)", time1)))
file1, fileName1, err := replayer.GeneratePlanReplayerFile(true, false, false)
require.NoError(t, err)
require.NoError(t, file1.Close())
filePath1 := filepath.Join(dirName, fileName1)
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField"))
time2 := time.Now().Add(-7 * 23 * time.Hour).UnixNano()
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField", fmt.Sprintf("return(%d)", time2)))
file2, fileName2, err := replayer.GeneratePlanReplayerFile(true, false, false)
require.NoError(t, err)
require.NoError(t, file2.Close())
filePath2 := filepath.Join(dirName, fileName2)
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField"))
time3 := time.Now().Add(-2 * time.Hour).UnixNano()
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField", fmt.Sprintf("return(%d)", time3)))
file3, fileName3, err := replayer.GeneratePlanReplayerFile(false, false, false)
require.NoError(t, err)
require.NoError(t, file3.Close())
filePath3 := filepath.Join(dirName, fileName3)
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField"))
time4 := time.Now().UnixNano()
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField", fmt.Sprintf("return(%d)", time4)))
file4, fileName4, err := replayer.GeneratePlanReplayerFile(false, false, false)
require.NoError(t, err)
require.NoError(t, file4.Close())
filePath4 := filepath.Join(dirName, fileName4)
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/util/replayer/InjectPlanReplayerFileNameTimeField"))
handler := &dumpFileGcChecker{
paths: []string{dirName},
}
handler.GCDumpFiles(time.Hour, time.Hour*24*7)
require.NoFileExists(t, filePath1)
require.FileExists(t, filePath2)
require.NoFileExists(t, filePath3)
require.FileExists(t, filePath4)
handler.GCDumpFiles(0, 0)
require.NoFileExists(t, filePath2)
require.NoFileExists(t, filePath4)
}
func TestDumpGCFileParseTime(t *testing.T) {
nowTime := time.Now()
name1 := fmt.Sprintf("replayer_single_xxxxxx_%v.zip", nowTime.UnixNano())
pt, err := parseTime(name1)
require.NoError(t, err)
require.True(t, pt.Equal(nowTime))
name2 := fmt.Sprintf("replayer_single_xxxxxx_%v1.zip", nowTime.UnixNano())
_, err = parseTime(name2)
require.NotNil(t, err)
name3 := fmt.Sprintf("replayer_single_xxxxxx_%v._zip", nowTime.UnixNano())
_, err = parseTime(name3)
require.NotNil(t, err)
name4 := "extract_-brq6zKMarD9ayaifkHc4A==_1678168728477502000.zip"
_, err = parseTime(name4)
require.NoError(t, err)
var pName string
pName, err = replayer.GeneratePlanReplayerFileName(false, false, false)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(true, false, false)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(false, true, false)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(true, true, false)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(false, false, true)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(true, false, true)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(false, true, true)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
pName, err = replayer.GeneratePlanReplayerFileName(true, true, true)
require.NoError(t, err)
_, err = parseTime(pName)
require.NoError(t, err)
}
|
package main
import (
"fmt"
)
func main() {
fmt.Println(singleNumber([]int{1, 1, 6, 1}))
}
func singleNumber(nums []int) int {
var ans int
for i := 0; i < 32; i++ {
x := 0
for j, v := range nums {
if v != 0 {
x += v & 1
nums[j] = v >> 1
}
}
ans += (x % 3) << i
}
return ans
}
|
package foreman
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/quilt/quilt/db"
"github.com/quilt/quilt/minion/pb"
)
type clients struct {
clients map[string]*fakeClient
newCalls int
}
func TestBoot(t *testing.T) {
conn, clients := startTest()
RunOnce(conn)
assert.Zero(t, clients.newCalls)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.PublicIP = "1.1.1.1"
m.PrivateIP = "1.1.1.1."
m.CloudID = "ID"
view.Commit(m)
return nil
})
RunOnce(conn)
assert.Equal(t, 1, clients.newCalls)
_, ok := clients.clients["1.1.1.1"]
assert.True(t, ok)
RunOnce(conn)
assert.Equal(t, 1, clients.newCalls)
_, ok = clients.clients["1.1.1.1"]
assert.True(t, ok)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.PublicIP = "2.2.2.2"
m.PrivateIP = "2.2.2.2"
m.CloudID = "ID2"
view.Commit(m)
return nil
})
RunOnce(conn)
assert.Equal(t, 2, clients.newCalls)
_, ok = clients.clients["2.2.2.2"]
assert.True(t, ok)
_, ok = clients.clients["1.1.1.1"]
assert.True(t, ok)
RunOnce(conn)
RunOnce(conn)
RunOnce(conn)
RunOnce(conn)
assert.Equal(t, 2, clients.newCalls)
_, ok = clients.clients["2.2.2.2"]
assert.True(t, ok)
_, ok = clients.clients["1.1.1.1"]
assert.True(t, ok)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
machines := view.SelectFromMachine(func(m db.Machine) bool {
return m.PublicIP == "1.1.1.1"
})
view.Remove(machines[0])
return nil
})
RunOnce(conn)
assert.Equal(t, 2, clients.newCalls)
_, ok = clients.clients["2.2.2.2"]
assert.True(t, ok)
_, ok = clients.clients["1.1.1.1"]
assert.False(t, ok)
RunOnce(conn)
RunOnce(conn)
RunOnce(conn)
RunOnce(conn)
assert.Equal(t, 2, clients.newCalls)
_, ok = clients.clients["2.2.2.2"]
assert.True(t, ok)
_, ok = clients.clients["1.1.1.1"]
assert.False(t, ok)
}
func TestBootEtcd(t *testing.T) {
conn, clients := startTest()
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.PublicIP = "m1-pub"
m.PrivateIP = "m1-priv"
m.CloudID = "ignored"
view.Commit(m)
m = view.InsertMachine()
m.Role = db.Worker
m.PublicIP = "w1-pub"
m.PrivateIP = "w1-priv"
m.CloudID = "ignored"
view.Commit(m)
return nil
})
RunOnce(conn)
assert.Equal(t, []string{"m1-priv"}, clients.clients["w1-pub"].mc.EtcdMembers)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.PublicIP = "m2-pub"
m.PrivateIP = "m2-priv"
m.CloudID = "ignored"
view.Commit(m)
return nil
})
RunOnce(conn)
etcdMembers := clients.clients["w1-pub"].mc.EtcdMembers
assert.Len(t, etcdMembers, 2)
assert.Contains(t, etcdMembers, "m1-priv")
assert.Contains(t, etcdMembers, "m2-priv")
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
var toDelete = view.SelectFromMachine(func(m db.Machine) bool {
return m.PrivateIP == "m1-priv"
})[0]
view.Remove(toDelete)
return nil
})
RunOnce(conn)
assert.Equal(t, []string{"m2-priv"},
clients.clients["w1-pub"].mc.EtcdMembers)
}
func TestInitForeman(t *testing.T) {
conn := startTestWithRole(pb.MinionConfig_WORKER)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.PublicIP = "2.2.2.2"
m.PrivateIP = "2.2.2.2"
m.CloudID = "ID2"
view.Commit(m)
return nil
})
Init(conn)
for _, m := range minions {
assert.Equal(t, db.Role(db.Worker), m.machine.Role)
}
conn = startTestWithRole(pb.MinionConfig_Role(-7))
Init(conn)
for _, m := range minions {
assert.Equal(t, db.None, m.machine.Role)
}
}
func TestConfigConsistency(t *testing.T) {
masterRole := db.RoleToPB(db.Master)
workerRole := db.RoleToPB(db.Worker)
conn, clients := startTest()
var master, worker db.Machine
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
master = view.InsertMachine()
master.PublicIP = "1.1.1.1"
master.PrivateIP = master.PublicIP
master.CloudID = "ID1"
view.Commit(master)
worker = view.InsertMachine()
worker.PublicIP = "2.2.2.2"
worker.PrivateIP = worker.PublicIP
worker.CloudID = "ID2"
view.Commit(worker)
return nil
})
Init(conn)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
master.Role = db.Master
worker.Role = db.Worker
view.Commit(master)
view.Commit(worker)
return nil
})
RunOnce(conn)
checkRoles := func() {
r := minions["1.1.1.1"].client.(*fakeClient).mc.Role
assert.Equal(t, masterRole, r)
r = minions["2.2.2.2"].client.(*fakeClient).mc.Role
assert.Equal(t, workerRole, r)
}
checkRoles()
minions = map[string]*minion{}
// Insert the clients into the client list to simulate fetching
// from the remote cluster
clients.clients["1.1.1.1"] = &fakeClient{clients, "1.1.1.1",
pb.MinionConfig{Role: masterRole}}
clients.clients["2.2.2.2"] = &fakeClient{clients, "2.2.2.2",
pb.MinionConfig{Role: workerRole}}
Init(conn)
RunOnce(conn)
checkRoles()
// After many runs, the roles should never change
for i := 0; i < 25; i++ {
RunOnce(conn)
}
checkRoles()
// Ensure that the DB machines have the correct roles as well.
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
machines := view.SelectFromMachine(nil)
for _, m := range machines {
if m.PublicIP == "1.1.1.1" {
assert.Equal(t, db.Role(db.Master), m.Role)
}
if m.PublicIP == "2.2.2.2" {
assert.Equal(t, db.Role(db.Worker), m.Role)
}
}
return nil
})
}
func startTest() (db.Conn, *clients) {
conn := db.New()
minions = map[string]*minion{}
clients := &clients{make(map[string]*fakeClient), 0}
newClient = func(ip string) (client, error) {
if fc, ok := clients.clients[ip]; ok {
return fc, nil
}
fc := &fakeClient{clients, ip, pb.MinionConfig{}}
clients.clients[ip] = fc
clients.newCalls++
return fc, nil
}
return conn, clients
}
func startTestWithRole(role pb.MinionConfig_Role) db.Conn {
clientInst := &clients{make(map[string]*fakeClient), 0}
newClient = func(ip string) (client, error) {
fc := &fakeClient{clientInst, ip, pb.MinionConfig{Role: role}}
clientInst.clients[ip] = fc
clientInst.newCalls++
return fc, nil
}
return db.New()
}
type fakeClient struct {
clients *clients
ip string
mc pb.MinionConfig
}
func (fc *fakeClient) setMinion(mc pb.MinionConfig) error {
fc.mc = mc
return nil
}
func (fc *fakeClient) getMinion() (pb.MinionConfig, error) {
return fc.mc, nil
}
func (fc *fakeClient) Close() {
delete(fc.clients.clients, fc.ip)
}
|
package geo
import (
"math"
)
// EarthRadius is the radius of the Earth in meter, UTM, WGS84
const EarthRadius = 6378137
const (
// MiddleSide ...
MiddleSide OnSide = 0
// LeftSide ...
LeftSide OnSide = 1
// RightSide ...
RightSide OnSide = -1
)
// OnSide ...
type OnSide int
// Rad ...
func Rad(degree float64) float64 {
return degree * math.Pi / 180.0
}
// Distance ...
func Distance(p1, p2 *Point) float64 {
rad1 := Rad(p1.Lat)
rad2 := Rad(p2.Lat)
a := rad1 - rad2
b := Rad(p1.Lon) - Rad(p2.Lon)
s := 2 * math.Asin(math.Sqrt(math.Pow(math.Sin(a/2), 2)+math.Cos(rad1)*math.Cos(rad2)*math.Pow(math.Sin(b/2), 2)))
return s * EarthRadius
}
// Angle calculates the angle <AOB>
// the angle value: [0, 180] in degree
//
// lat /|\
// | a *
// | /
// | /
// | o *------* b
// |
// +---------------> lon
//
func Angle(a, o, b *Point) float64 {
oa := Distance(o, a)
ob := Distance(o, b)
ab := Distance(a, b)
if oa == 0 || ob == 0 {
return 0
}
cos := (ob*ob + oa*oa - ab*ab) / (2 * ob * oa)
return math.Acos(cos) * 180 / math.Pi
}
// Side is calc point p on which side of (a->b)
//
// a *
// | \
// | \
// v \
// | * p
// |
// b *
//
// vector a->b: ab = b - a
// vector a->p: ap = p - a
// cross-product: m = ab x ap
// m > 0: p on the left
// m < 0: p on the right
// m = 0: p on the middle
func Side(a, b, p *Point) OnSide {
ab := &Point{
Lat: b.Lat - a.Lat,
Lon: b.Lon - a.Lon,
}
ap := &Point{
Lat: p.Lat - a.Lat,
Lon: p.Lon - a.Lon,
}
m := ab.Lon*ap.Lat - ab.Lat*ap.Lon
if m > 0 {
return LeftSide
}
if m < 0 {
return RightSide
}
return MiddleSide
}
|
package internal_service
import (
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/common/config"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
"context"
"strings"
)
func GetUserInfoClient(req *pbUser.GetUserInfoReq) (*pbUser.GetUserInfoResp, error) {
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
RpcResp, err := client.GetUserInfo(context.Background(), req)
return RpcResp, err
}
|
package main
import (
"testing"
)
func TestMultiplyVectors_Multiply(t *testing.T) {
err := load_if("glmcpp.dll")
if err != nil {
t.Fatal(err)
return
}
mv := MultiplyVectors{}
mv.Mat[0], mv.Mat[5], mv.Mat[10], mv.Mat[15] = 1, 1, 1, 1
mv.Mat[12] = 100
mv.Mat[13] = 50
mv.Vectors = append(mv.Vectors, Vector{1, 2, 3})
err = mv.Multiply()
if err != nil {
t.Error(err)
return
}
v := Vector{101, 52, 3}
if mv.Vectors[0] != v {
t.Errorf("Assumed 101, 52, 3, not %v", mv.Vectors[0])
}
}
func TestMultiplyVectors_FastMultiply(t *testing.T) {
err := load_if("glmcpp.dll")
if err != nil {
t.Fatal(err)
return
}
mv := MultiplyVectors{}
mv.Mat[0], mv.Mat[5], mv.Mat[10], mv.Mat[15] = 1, 1, 1, 1
mv.Mat[12] = 100
mv.Mat[13] = 50
mv.Vectors = append(mv.Vectors, Vector{1, 2, 3})
err = mv.FastMultiply()
if err != nil {
t.Error(err)
return
}
v := Vector{101, 52, 3}
if mv.Vectors[0] != v {
t.Errorf("Assumed 101, 52, 3, not %v", mv.Vectors[0])
}
}
func BenchmarkMultiplyVectors_Multiply(b *testing.B) {
err := load_if("glmcpp.dll")
if err != nil {
b.Fatal(err)
return
}
mv := MultiplyVectors{}
mv.Mat[0], mv.Mat[5], mv.Mat[10], mv.Mat[15] = 1, 1, 1, 1
mv.Mat[12] = 100
mv.Mat[13] = 50
for n := 0; n < b.N; n++ {
mv.Vectors = []Vector{Vector{1, 2, 3}}
err := mv.Multiply()
if err != nil {
b.Error(err)
}
}
}
func BenchmarkMultiplyVectors_FastMultiply(b *testing.B) {
err := load_if("glmcpp.dll")
if err != nil {
b.Fatal(err)
return
}
mv := MultiplyVectors{}
mv.Mat[0], mv.Mat[5], mv.Mat[10], mv.Mat[15] = 1, 1, 1, 1
mv.Mat[12] = 100
mv.Mat[13] = 50
for n := 0; n < b.N; n++ {
mv.Vectors = []Vector{Vector{1, 2, 3}}
err := mv.FastMultiply()
if err != nil {
b.Error(err)
}
}
}
|
package urlgen_test
import (
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/go-sink/sink/internal/pkg/urlgen"
)
const wantedLength = 6
func TestFunction(t *testing.T) {
t.Run("it generates a random string of fixed length", func(t *testing.T) {
random := rand.New(rand.NewSource(time.Now().Unix())) //nolint:gosec
randomStringGenerator := urlgen.NewRandomURLGenerator(random)
someString := randomStringGenerator.RandomString(wantedLength)
assert.Len(t, someString, wantedLength)
})
}
|
package Problem0395
import (
"strings"
)
func longestSubstring(s string, k int) int {
if len(s) < k {
return 0
}
// count 中,记录了每个字母出现的次数
count := make(map[byte]int, len(s))
// maxCount 出现最多字母的出现次数
maxCount := 0
for i := range s {
count[s[i]]++
maxCount = max(maxCount, count[s[i]])
}
if maxCount < k {
// 没有字母达到 k 次
return 0
}
var b byte
var c int
// useless 收集了没有达到 k 次的字母
useless := make([]string, 0, len(count))
for b, c = range count {
if c < k {
useless = append(useless, string(b))
}
}
if len(useless) == 0 {
// 所有的字母都达到了 k 次
return len(s)
}
var u string
for _, u = range useless {
s = strings.Replace(s, u, ",", -1)
}
ss := strings.Split(s, ",")
// 递归求解
maxLen := 0
for _, s = range ss {
maxLen = max(maxLen, longestSubstring(s, k))
}
return maxLen
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
package nameshake
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
abci "github.com/tendermint/tendermint/abci/types"
)
// ValidateGenesis validates the provided module genesis state to ensure the
// expected invariants holds. (i.e. params in correct bounds, no duplicate validators)
func ValidateGenesis(data GenesisState) error {
for _, record := range data.WhoisRecords {
if record.Owner == nil {
return fmt.Errorf("Invalid WhoisRecord: Value: %s. Error: Missing Owner", record.Value)
}
if record.Value == "" {
return fmt.Errorf("Invalid WhoisRecord: Owner: %s. Error: Missing Value", record.Owner)
}
if record.Price == nil {
return fmt.Errorf("Invalid WhoisRecord: Value: %s. Error: Missing Price", record.Value)
}
}
return nil
}
func DefaultGenesisState() GenesisState {
return GenesisState{
WhoisRecords: nil,
Params: DefaultParams(),
}
}
func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) []abci.ValidatorUpdate {
for _, record := range data.WhoisRecords {
keeper.SetWhois(ctx, record.Value, record)
}
return []abci.ValidatorUpdate{}
}
func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState {
panic("not implemented")
}
|
package data
// DoorPosition describes a door position an a maze
type DoorPosition struct {
side Direction
offset int
}
// NewDoorPosition creates new structure
func NewDoorPosition(side Direction, offset int) *DoorPosition {
return &DoorPosition{side, offset}
}
// Side returns a side
func (p *DoorPosition) Side() Direction {
return p.side
}
// Offset returns an offset
func (p *DoorPosition) Offset() int {
return p.offset
}
|
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 dnsrecord
import (
"context"
"fmt"
"time"
gcpclient "github.com/gardener/gardener-extension-provider-gcp/pkg/gcp/client"
extensionscontroller "github.com/gardener/gardener/extensions/pkg/controller"
"github.com/gardener/gardener/extensions/pkg/controller/common"
"github.com/gardener/gardener/extensions/pkg/controller/dnsrecord"
controllererror "github.com/gardener/gardener/extensions/pkg/controller/error"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
extensionsv1alpha1 "github.com/gardener/gardener/pkg/apis/extensions/v1alpha1"
extensionsv1alpha1helper "github.com/gardener/gardener/pkg/apis/extensions/v1alpha1/helper"
kutil "github.com/gardener/gardener/pkg/utils/kubernetes"
"github.com/go-logr/logr"
"k8s.io/client-go/util/retry"
)
const (
// requeueAfterOnProviderError is a value for RequeueAfter to be returned on provider errors
// in order to prevent quick retries that could quickly exhaust the account rate limits in case of e.g.
// configuration issues.
requeueAfterOnProviderError = 30 * time.Second
)
type actuator struct {
common.ClientContext
gcpClientFactory gcpclient.Factory
logger logr.Logger
}
func NewActuator(gcpClientFactory gcpclient.Factory, logger logr.Logger) dnsrecord.Actuator {
return &actuator{
gcpClientFactory: gcpClientFactory,
logger: logger.WithName("gcp-dnsrecord-actuator"),
}
}
// Reconcile reconciles the DNSRecord.
func (a *actuator) Reconcile(ctx context.Context, dns *extensionsv1alpha1.DNSRecord, cluster *extensionscontroller.Cluster) error {
// Create GCP DNS client
dnsClient, err := a.gcpClientFactory.NewDNSClient(ctx, a.Client(), dns.Spec.SecretRef)
if err != nil {
return err
}
// Determine DNS managed zone
managedZone, err := a.getManagedZone(ctx, dns, dnsClient)
if err != nil {
return err
}
// Create or update DNS recordset
ttl := extensionsv1alpha1helper.GetDNSRecordTTL(dns.Spec.TTL)
a.logger.Info("Creating or updating DNS recordset", "managedZone", managedZone, "name", dns.Spec.Name, "type", dns.Spec.RecordType, "rrdatas", dns.Spec.Values, "dnsrecord", kutil.ObjectName(dns))
if err := dnsClient.CreateOrUpdateRecordSet(ctx, managedZone, dns.Spec.Name, string(dns.Spec.RecordType), dns.Spec.Values, ttl); err != nil {
return &controllererror.RequeueAfterError{
Cause: fmt.Errorf("could not create or update DNS recordset in managed zone %s with name %s, type %s, and rrdatas %v: %+v", managedZone, dns.Spec.Name, dns.Spec.RecordType, dns.Spec.Values, err),
RequeueAfter: requeueAfterOnProviderError,
}
}
// Delete meta DNS recordset if exists
if dns.Status.LastOperation == nil || dns.Status.LastOperation.Type == gardencorev1beta1.LastOperationTypeCreate {
name, recordType := dnsrecord.GetMetaRecordName(dns.Spec.Name), "TXT"
a.logger.Info("Deleting meta DNS recordset", "managedZone", managedZone, "name", name, "type", recordType, "dnsrecord", kutil.ObjectName(dns))
if err := dnsClient.DeleteRecordSet(ctx, managedZone, name, recordType); err != nil {
return &controllererror.RequeueAfterError{
Cause: fmt.Errorf("could not delete meta DNS recordset in managed zone %s with name %s and type %s: %+v", managedZone, name, recordType, err),
RequeueAfter: requeueAfterOnProviderError,
}
}
}
// Update resource status
return extensionscontroller.TryUpdateStatus(ctx, retry.DefaultBackoff, a.Client(), dns, func() error {
dns.Status.Zone = &managedZone
return nil
})
}
// Delete deletes the DNSRecord.
func (a *actuator) Delete(ctx context.Context, dns *extensionsv1alpha1.DNSRecord, cluster *extensionscontroller.Cluster) error {
// Create GCP DNS client
dnsClient, err := a.gcpClientFactory.NewDNSClient(ctx, a.Client(), dns.Spec.SecretRef)
if err != nil {
return err
}
// Determine DNS managed zone
managedZone, err := a.getManagedZone(ctx, dns, dnsClient)
if err != nil {
return err
}
// Delete DNS recordset
a.logger.Info("Deleting DNS recordset", "managedZone", managedZone, "name", dns.Spec.Name, "type", dns.Spec.RecordType, "dnsrecord", kutil.ObjectName(dns))
if err := dnsClient.DeleteRecordSet(ctx, managedZone, dns.Spec.Name, string(dns.Spec.RecordType)); err != nil {
return &controllererror.RequeueAfterError{
Cause: fmt.Errorf("could not delete DNS recordset in managed zone %s with name %s and type %s: %+v", managedZone, dns.Spec.Name, dns.Spec.RecordType, err),
RequeueAfter: requeueAfterOnProviderError,
}
}
return nil
}
// Restore restores the DNSRecord.
func (a *actuator) Restore(ctx context.Context, dns *extensionsv1alpha1.DNSRecord, cluster *extensionscontroller.Cluster) error {
return a.Reconcile(ctx, dns, cluster)
}
// Migrate migrates the DNSRecord.
func (a *actuator) Migrate(context.Context, *extensionsv1alpha1.DNSRecord, *extensionscontroller.Cluster) error {
return nil
}
func (a *actuator) getManagedZone(ctx context.Context, dns *extensionsv1alpha1.DNSRecord, dnsClient gcpclient.DNSClient) (string, error) {
switch {
case dns.Spec.Zone != nil && *dns.Spec.Zone != "":
return *dns.Spec.Zone, nil
case dns.Status.Zone != nil && *dns.Status.Zone != "":
return *dns.Status.Zone, nil
default:
// The zone is not specified in the resource status or spec. Try to determine the zone by
// getting all managed zones of the account and searching for the longest zone name that is a suffix of dns.spec.Name
zones, err := dnsClient.GetManagedZones(ctx)
if err != nil {
return "", &controllererror.RequeueAfterError{
Cause: fmt.Errorf("could not get DNS managed zones: %+v", err),
RequeueAfter: requeueAfterOnProviderError,
}
}
a.logger.Info("Got DNS managed zones", "zones", zones, "dnsrecord", kutil.ObjectName(dns))
zone := dnsrecord.FindZoneForName(zones, dns.Spec.Name)
if zone == "" {
return "", fmt.Errorf("could not find DNS managed zone for name %s", dns.Spec.Name)
}
return zone, nil
}
}
|
package nominetuk
type Domain struct {
conn *Conn
}
// Get domain info
func (domain *Domain) Info(domainName string) (DomainInfoResponse, error) {
var domainInfoResponse DomainInfoResponse
err := domain.encodeDomainInfo(domainName)
if err != nil {
return domainInfoResponse, err
}
return domain.processDomainInfo(domainName)
}
|
package todocounter
import (
"sync"
)
// Counter records things remaining to process. It is needed for complicated
// cases where multiple goroutines are spawned to process items, and they may
// generate more items to process. For example, say a query over a set of nodes
// may yield either a result value, or more nodes to query. Signaling is subtly
// complicated, because the queue may be empty while items are being processed,
// that will end up adding more items to the queue.
//
// Use Counter like this:
//
// todos := make(chan int, 10)
// ctr := todoctr.NewCounter()
//
// process := func(item int) {
// fmt.Println("processing %d\n...", item)
//
// // this task may randomly generate more tasks
// if rand.Intn(5) == 0 {
// todos<- item + 1
// ctr.Increment(1) // increment counter for new task.
// }
//
// ctr.Decrement(1) // decrement one to signal the task being done.
// }
//
// // add some tasks.
// todos<- 1
// todos<- 2
// todos<- 3
// todos<- 4
// ctr.Increment(4)
//
// for {
// select {
// case item := <- todos:
// go process(item)
// case <-ctr.Done():
// fmt.Println("done processing everything.")
// close(todos)
// }
// }
type Counter interface {
// Incrememnt adds a number of todos to track.
// If the counter is **below** zero, it panics.
Increment(i uint32)
// Decrement removes a number of todos to track.
// If the count drops to zero, signals done and destroys the counter.
// If the count drops **below** zero, panics. It means you have tried to remove
// more things than you added, i.e. sync issues.
Decrement(i uint32)
// Done returns a channel to wait upon. Use it in selects:
//
// select {
// case <-ctr.Done():
// // done processing all items
// }
//
Done() <-chan struct{}
}
type todoCounter struct {
count int32
done chan struct{}
sync.RWMutex
}
// NewSyncCounter constructs a new counter
func NewSyncCounter() Counter {
return &todoCounter{
done: make(chan struct{}),
}
}
func (c *todoCounter) Increment(i uint32) {
c.Lock()
defer c.Unlock()
if c.count < 0 {
panic("counter already signaled done. use a new counter.")
}
// increment count
c.count += int32(i)
}
// Decrement removes a number of todos to track.
// If the count drops to zero, signals done and destroys the counter.
// If the count drops **below** zero, panics. It means you have tried to remove
// more things than you added, i.e. sync issues.
func (c *todoCounter) Decrement(i uint32) {
c.Lock()
defer c.Unlock()
if c.count < 0 {
panic("counter already signaled done. probably have sync issues.")
}
if int32(i) > c.count {
panic("decrement amount creater than counter. sync issues.")
}
c.count -= int32(i)
if c.count == 0 { // done! signal it.
c.count-- // set it to -1 to prevent reuse
close(c.done) // a closed channel will always return nil
}
}
func (c *todoCounter) Done() <-chan struct{} {
return c.done
}
|
package arangodb
import (
"fmt"
"encoding/json"
"github.com/apex/log"
"github.com/thedanielforum/arangodb/types"
)
type credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
type jwtCredentials struct {
jwt string `json:"jwt"`
mustChangePass bool `json:"must_change_pass"`
}
func (c *Connection) authenticate(user, pass string) error {
creds, err := json.Marshal(&credentials{
Username: user,
Password: pass,
});
if err != nil {
return err
}
body, err := c.post("_open/auth", creds)
if err != nil {
return err
}
// Assign token to connection for future use
auth := new(types.Auth)
if err = json.Unmarshal(body, auth); err != nil {
return err
}
c.token = fmt.Sprintf("bearer %s", auth.Jwt)
c.header.Set("Authorization", c.token)
if c.config.DebugMode {
log.Infof("connected to: %s using token: %s", c.host, auth.Jwt)
}
return nil
}
|
// Package evdev is a pure Go implementation of the Linux evdev API.
package evdev
import (
"context"
"fmt"
"os"
"sync"
"unsafe"
)
const (
// DefaultPollSize is the default number of events to poll.
DefaultPollSize = 64
)
// Evdev represents an evdev device.
type Evdev struct {
fd *os.File
pollSize int
id ID
name string
path string
serial string
version uint32
effectMax int32
events map[EventType]bool
syncs map[SyncType]bool
keys map[KeyType]bool
miscs map[MiscType]bool
absolutes map[AbsoluteType]Axis
relatives map[RelativeType]bool
switches map[SwitchType]bool
leds map[LEDType]bool
sounds map[SoundType]bool
effects map[EffectType]bool
powers map[PowerType]bool
effectss map[EffectStatusType]bool
properties map[PropertyType]bool
//repeats map[RepeatType]bool
out chan Event
cancel context.CancelFunc
}
// Open creates a device from an open file descriptor.
func Open(fd *os.File) *Evdev {
return &Evdev{fd: fd}
}
// OpenFile opens device from the file path (ie, /dev/input/event*).
func OpenFile(path string) (*Evdev, error) {
fd, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
return nil, err
}
return Open(fd), nil
}
// Close closes the underlying device file descriptor.
func (d *Evdev) Close() error {
if d.cancel != nil {
d.cancel()
}
if d.fd != nil {
d.Unlock()
err := d.fd.Close()
d.fd = nil
return err
}
return nil
}
// Lock attempts to gain exclusive access to the device.
//
// This means that we are the only ones receiving events from the device; other
// processes will not.
//
// This ability should be handled with care, especially when trying to lock
// keyboard access. If this is executed while we are running in something like
// X, this call will prevent X from receiving any and all keyboard events. All
// of them will only be sent to our own process. If we do not properly handle
// these key events, we may lock ourselves out of the system and a hard reset
// is required to restore it.
func (d *Evdev) Lock() error {
return ioctl(d.fd.Fd(), evGrab, 1)
}
// Unlock releases a lock, previously obtained through Lock.
func (d *Evdev) Unlock() error {
return ioctl(d.fd.Fd(), evGrab, 0)
}
// ID returns a device's identity information.
func (d *Evdev) ID() ID {
var once sync.Once
once.Do(func() {
_ = ioctl(d.fd.Fd(), evGetID, unsafe.Pointer(&d.id))
})
return d.id
}
// Name returns the name of the device.
func (d *Evdev) Name() string {
var once sync.Once
once.Do(func() {
d.name, _ = ioctlString(d.fd.Fd(), evGetName, 256)
})
return d.name
}
// Path returns the physical path of the device. For example:
//
// usb-00:01.2-2.1/input0
//
// To understand what this string is showing, you need to break it down into
// parts. `usb` means this is a physical topology from the USB system.
//
// `00:01.2` is the PCI bus information for the USB host controller (in this
// case, bus 0, slot 1, function 2).
//
// `2.1` shows the path from the root hub to the device. In this case, the
// upstream hub is plugged in to the second port on the root hub, and that
// device is plugged in to the first port on the upstream hub.
//
// `input0` means this is the first event interface on the device. Most
// devices have only one, but multimedia keyboards may present the normal
// keyboard on one interface and the multimedia function keys on a second
// interface.
func (d *Evdev) Path() string {
var once sync.Once
once.Do(func() {
d.path, _ = ioctlString(d.fd.Fd(), evGetPhys, 256)
})
return d.path
}
// Serial returns the unique serial for the device.
//
// Most devices do not have this and will return an empty string.
func (d *Evdev) Serial() string {
var once sync.Once
once.Do(func() {
d.serial, _ = ioctlString(d.fd.Fd(), evGetUniq, 256)
})
return d.serial
}
// Version returns the major, minor, and revision of the device driver.
func (d *Evdev) Version() (int, int, int) {
var once sync.Once
once.Do(func() {
_ = ioctl(d.fd.Fd(), evGetVersion, unsafe.Pointer(&d.version))
})
return int(d.version>>16) & 0xffff, int(d.version>>8) & 0xff, int(d.version) & 0xff
}
// EffectMax retrieves the maximum number of force feedback effects supported
// by the device.
//
// This is only applicable to devices with EventForceFeedback event support.
func (d *Evdev) EffectMax() int {
var once sync.Once
once.Do(func() {
_ = ioctl(d.fd.Fd(), evGetEffects, unsafe.Pointer(&d.effectMax))
})
return int(d.effectMax)
}
// eventTypes retrieves the specified event type, and passes it to f.
func (d *Evdev) eventTypes(typ, max int, f func(int)) error {
buf := make([]uint64, max/64+1*(max%64))
err := ioctl(d.fd.Fd(), evGetBit(typ, max), unsafe.Pointer(&buf[0]))
if err != nil {
return err
}
for i := 0; i <= max; i++ {
if (buf[i/64]>>uint(i%64))&1 == 1 {
f(i)
}
}
return nil
}
// EventTypes returns the device's supported event types.
func (d *Evdev) EventTypes() map[EventType]bool {
var once sync.Once
once.Do(func() {
d.events = make(map[EventType]bool)
d.eventTypes(int(EventSync), eventMax, func(i int) {
d.events[EventType(i)] = true
})
})
return d.events
}
// SyncTypes returns the sync events supported by the device.
//
// This is only applicable to devices with EventSync event support.
func (d *Evdev) SyncTypes() map[SyncType]bool {
var once sync.Once
once.Do(func() {
d.syncs = make(map[SyncType]bool)
d.eventTypes(int(EventSync), int(syncMax), func(i int) {
d.syncs[SyncType(i)] = true
})
})
return d.syncs
}
// KeyTypes returns the key events supported by the device.
//
// This is only applicable to devices with EventKey event support.
func (d *Evdev) KeyTypes() map[KeyType]bool {
var once sync.Once
once.Do(func() {
d.keys = make(map[KeyType]bool)
d.eventTypes(int(EventKey), int(keyMax), func(i int) {
d.keys[KeyType(i)] = true
})
})
return d.keys
}
// RelativeTypes returns a map of the supported relative axis types.
//
// This is only applicable to devices with EventRelative event support.
func (d *Evdev) RelativeTypes() map[RelativeType]bool {
var once sync.Once
once.Do(func() {
d.relatives = make(map[RelativeType]bool)
d.eventTypes(int(EventRelative), relativeMax, func(i int) {
d.relatives[RelativeType(i)] = true
})
})
return d.relatives
}
// AbsoluteTypes returns a map of the supported absolute axis types.
//
// This is only applicable to devices with EventAbsolute event support.
func (d *Evdev) AbsoluteTypes() map[AbsoluteType]Axis {
var once sync.Once
once.Do(func() {
d.absolutes = make(map[AbsoluteType]Axis)
d.eventTypes(int(EventAbsolute), absoluteMax, func(i int) {
typ := AbsoluteType(i)
d.absolutes[typ] = d.absoluteAxis(typ)
})
})
return d.absolutes
}
// MiscTypes returns the misc events supported by the device.
//
// This is only applicable to devices with EventMisc event support.
func (d *Evdev) MiscTypes() map[MiscType]bool {
var once sync.Once
once.Do(func() {
d.miscs = make(map[MiscType]bool)
d.eventTypes(int(EventMisc), int(miscMax), func(i int) {
d.miscs[MiscType(i)] = true
})
})
return d.miscs
}
// SwitchTypes returns the switch events supported by the device.
//
// This is only applicable to devices with EventSwitch event support.
func (d *Evdev) SwitchTypes() map[SwitchType]bool {
var once sync.Once
once.Do(func() {
d.switches = make(map[SwitchType]bool)
d.eventTypes(int(EventSwitch), int(switchMax), func(i int) {
d.switches[SwitchType(i)] = true
})
})
return d.switches
}
// LEDTypes returns the led events supported by the device.
//
// This is only applicable to devices with EventLED event support.
func (d *Evdev) LEDTypes() map[LEDType]bool {
var once sync.Once
once.Do(func() {
d.leds = make(map[LEDType]bool)
d.eventTypes(int(EventLED), int(ledMax), func(i int) {
d.leds[LEDType(i)] = true
})
})
return d.leds
}
// SoundTypes returns the sound events supported by the device.
//
// This is only applicable to devices with EventSound event support.
func (d *Evdev) SoundTypes() map[SoundType]bool {
var once sync.Once
once.Do(func() {
d.sounds = make(map[SoundType]bool)
d.eventTypes(int(EventSound), int(soundMax), func(i int) {
d.sounds[SoundType(i)] = true
})
})
return d.sounds
}
// EffectTypes returns the force feedback effects supported by the
// device.
//
// This is only applicable to devices with EventEffect event support.
func (d *Evdev) EffectTypes() map[EffectType]bool {
var once sync.Once
once.Do(func() {
d.effects = make(map[EffectType]bool)
d.eventTypes(int(EventEffect), int(effectMax), func(i int) {
d.effects[EffectType(i)] = true
})
})
return d.effects
}
// PowerTypes returns the power events supported by the device.
//
// This is only applicable to devices with EventPower event support.
func (d *Evdev) PowerTypes() map[PowerType]bool {
var once sync.Once
once.Do(func() {
d.powers = make(map[PowerType]bool)
d.eventTypes(int(EventPower), int(powerMax), func(i int) {
d.powers[PowerType(i)] = true
})
})
return d.powers
}
// EffectStatusTypes returns the effects events supported by the device.
//
// This is only applicable to devices with EventEffectStatus event support.
func (d *Evdev) EffectStatusTypes() map[EffectStatusType]bool {
var once sync.Once
once.Do(func() {
d.effectss = make(map[EffectStatusType]bool)
d.eventTypes(int(EventEffectStatus), int(effectStatusMax), func(i int) {
d.effectss[EffectStatusType(i)] = true
})
})
return d.effectss
}
// Properties returns the device properties.
func (d *Evdev) Properties() map[PropertyType]bool {
var once sync.Once
once.Do(func() {
})
return d.properties
}
// IsKeyboard returns true if the device qualifies as a keyboard.
func (d *Evdev) IsKeyboard() bool {
m := d.EventTypes()
return m[EventKey] && m[EventLED]
}
// IsMouse returns true if the device qualifies as a mouse.
func (d *Evdev) IsMouse() bool {
m := d.EventTypes()
return m[EventKey] && m[EventRelative]
}
// IsJoystick returns true if the device qualifies as a joystick.
func (d *Evdev) IsJoystick() bool {
m := d.EventTypes()
return m[EventKey] && m[EventAbsolute]
}
// absoluteAxis retrieves the state of the axis.
//
// If you want the global state for a device, you have to call the function for
// each axis present on the device.
//
// This is only applicable to devices with EventAbsolute event support.
func (d *Evdev) absoluteAxis(axis AbsoluteType) Axis {
var abs Axis
_ = ioctl(d.fd.Fd(), evGetAbs(int(axis)), unsafe.Pointer(&abs))
return abs
}
// RepeatState returns the current, global repeat state. This applies only to
// devices which have the EventRepeat capability defined. This can be determined
// through `Device.EventTypes()`.
//
// Refer to Device.SetRepeatState for an explanation on what the returned
// values mean.
//
// This is only applicable to devices with EventRepeat event support.
func (d *Evdev) RepeatState() (uint, uint) {
var rep [2]int32
_ = ioctl(d.fd.Fd(), evGetRep, unsafe.Pointer(&rep[0]))
return uint(rep[0]), uint(rep[1])
}
// RepeatStateSet sets the repeat state for the given device.
//
// The values indicate (in milliseconds) the delay before the device starts
// repeating and the delay between subsequent repeats. This might apply to a
// keyboard where the user presses and holds a key.
//
// E.g.: We see an initial character immediately, then another @initial
// milliseconds later and after that, once every @subsequent milliseconds,
// until the key is released.
//
// This returns false if the operation failed.
//
// This is only applicable to devices with EventRepeat event support.
func (d *Evdev) RepeatStateSet(initial, subsequent uint) bool {
rep := [2]int32{int32(initial), int32(subsequent)}
return ioctl(d.fd.Fd(), evSetRep, unsafe.Pointer(&rep[0])) == nil
}
// KeyState returns the current, global key- and button- states.
//
// This is only applicable to devices with EventKey event support.
/*func (d *Evdev) KeyState() Bitset {
b := NewBitset(keyMax)
buf := b.Bytes()
ioctl(d.fd.Fd(), evGetKEY(len(buf)), unsafe.Pointer(&buf[0]))
return b
}*/
// KeyMap retrieves the key mapping for the given key.
func (d *Evdev) KeyMap(key KeyType) KeyMap {
m := KeyMap{Key: uint32(key)}
_ = ioctl(d.fd.Fd(), evGetKeycode, unsafe.Pointer(&m))
return m
}
// KeyMapSet sets a key map.
//
// This allows us to rewire physical keys -- ie, pressing M, will input N into
// the input system.
//
// Some input drivers support variable mappings between the keys held down
// (which are interpreted by the keyboard scan and reported as scancodes) and
// the events sent to the input layer.
//
// You can change which key is associated with each scancode using this call.
// The value of the scancode is the first element in the integer array
// (list[n][0]), and the resulting input event key number (keycode) is the
// second element in the array. (list[n][1]).
//
// Be aware that the KeyMap functions may not work on every keyboard. This is
// only applicable to devices with EventKey event support.
func (d *Evdev) KeyMapSet(m KeyMap) error {
return ioctl(d.fd.Fd(), evSetKeycode, unsafe.Pointer(&m))
}
// Poll polls the device for incoming events.
//
// Change the buffer size by specifying PollSize.
//
// Polling continues to run until the context is closed.
func (d *Evdev) Poll(ctxt context.Context) <-chan *EventEnvelope {
count := d.pollSize
if count == 0 {
count = DefaultPollSize
}
ch := make(chan *EventEnvelope)
go func() {
defer close(ch)
buf := make([]byte, sizeofEvent*count)
for {
// check context
select {
case <-ctxt.Done():
return
default:
}
// read events
i, err := d.fd.Read(buf)
if err != nil {
return
}
events := (*(*[1<<27 - 1]Event)(unsafe.Pointer(&buf[0])))[:i/sizeofEvent]
for _, e := range events {
switch e.Type {
case EventSync:
ch <- &EventEnvelope{e, SyncType(e.Code)}
case EventKey:
ch <- &EventEnvelope{e, KeyType(e.Code)}
case EventRelative:
ch <- &EventEnvelope{e, RelativeType(e.Code)}
case EventAbsolute:
ch <- &EventEnvelope{e, AbsoluteType(e.Code)}
case EventMisc:
ch <- &EventEnvelope{e, MiscType(e.Code)}
case EventSwitch:
ch <- &EventEnvelope{e, SwitchType(e.Code)}
case EventLED:
ch <- &EventEnvelope{e, LEDType(e.Code)}
case EventSound:
ch <- &EventEnvelope{e, SoundType(e.Code)}
case EventRepeat:
ch <- &EventEnvelope{e, RepeatType(e.Code)}
case EventEffect:
ch <- &EventEnvelope{e, EffectType(e.Code)}
case EventPower:
ch <- &EventEnvelope{e, PowerType(e.Code)}
case EventEffectStatus:
ch <- &EventEnvelope{e, EffectStatusType(e.Code)}
default:
ch <- &EventEnvelope{e, nil}
}
}
}
}()
return ch
}
// Send sends an event to the device.
func (d *Evdev) Send(ev Event) error {
var once sync.Once
once.Do(func() {
var ctxt context.Context
ctxt, d.cancel = context.WithCancel(context.Background())
d.out = make(chan Event, 1)
go func() {
defer close(d.out)
var event Event
for {
select {
case event = <-d.out:
buf := (*(*[1<<27 - 1]byte)(unsafe.Pointer(&event)))[:sizeofEvent]
n, err := d.fd.Write(buf)
if err != nil {
return
}
if n < sizeofEvent {
fmt.Fprintf(os.Stderr, "poll outbox: short write\n")
}
case <-ctxt.Done():
break
}
}
}()
})
d.out <- ev
return nil
}
// EffectSet sends the Force Feedback effect to the device. The number of
// effects sent should not exceed the length of the device's EffectTypes.
//
// After this call completes, the effect.ID field will contain the effect's ID.
// The effect's ID must be used when playing or stopping the effect. It is also
// possible to reupload the same effect with the same ID later on with new
// parameters.
//
// This allows us to update a running effect, without first stopping it.
//
// This is only applicable to devices with EventForceFeedback event support.
func (d *Evdev) EffectSet(effect *Effect) error {
return ioctl(d.fd.Fd(), evSetFF, unsafe.Pointer(effect))
}
// EffectUnset deletes the given effects from the device. This makes room for
// new effects in the device's memory. Note that this also stops the effect if
// it was playing.
//
// This is only applicable to devices with EventForceFeedback event support.
func (d *Evdev) EffectUnset(effect *Effect) error {
return ioctl(d.fd.Fd(), evDelFF, int(effect.ID))
}
// effectSend sends the specified effect with the value.
func (d *Evdev) effectSend(id EffectType, value int32) {
d.Send(Event{
Type: EventEffect,
Code: uint16(id),
Value: value,
})
}
// EffectPlay plays a previously uploaded effect.
func (d *Evdev) EffectPlay(id EffectType) {
d.effectSend(id, 1)
}
// EffectStop stops a previously uploaded effect from playing.
func (d *Evdev) EffectStop(id EffectType) {
d.effectSend(id, 0)
}
// effectSet changes the given effect factor.
func (d *Evdev) effectPropSet(code EffectPropType, factor int) {
if factor < 0 {
factor = 0
}
if factor > 100 {
factor = 100
}
d.Send(Event{
Type: EventEffect,
Code: uint16(code),
Value: 0xffff * int32(factor) / 100,
})
}
// EffectGainSet changes the force feedback gain.
//
// Not all devices have the same effect strength. Therefore, users should set a
// gain factor depending on how strong they want effects to be. This setting is
// persistent across access to the driver.
//
// The specified gain should be in the range 0-100. This is only applicable to
// devices with EventForceFeedback event support.
func (d *Evdev) EffectGainSet(gain int) {
d.effectPropSet(EffectPropGain, gain)
}
// EffectAutoCenterSet changes the force feedback autocenter factor.
// The specified factor should be in the range 0-100.
// A value of 0 means: no autocenter.
//
// This is only applicable to devices with EventForceFeedback event support.
func (d *Evdev) EffectAutoCenterSet(factor int) {
d.effectPropSet(EffectPropAutoCenter, factor)
}
|
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. //
// //
// 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 cvl_test
import (
"testing"
"github.com/Azure/sonic-mgmt-common/cvl"
)
func TestValidateEditConfig_When_Exp_In_Choice_Negative(t *testing.T) {
depDataMap := map[string]interface{}{
"ACL_TABLE": map[string]interface{}{
"TestACL1": map[string]interface{}{
"stage": "INGRESS",
"type": "MIRROR",
},
},
}
loadConfigDB(rclient, depDataMap)
cvSess, _ := cvl.ValidationSessOpen()
cfgDataRule := []cvl.CVLEditConfigData{
cvl.CVLEditConfigData{
cvl.VALIDATE_ALL,
cvl.OP_CREATE,
"ACL_RULE|TestACL1|Rule1",
map[string]string{
"PACKET_ACTION": "FORWARD",
"IP_TYPE": "IPV6",
"SRC_IP": "10.1.1.1/32", //Invalid field
"L4_SRC_PORT": "1909",
"IP_PROTOCOL": "103",
"DST_IP": "20.2.2.2/32", //Invalid field
"L4_DST_PORT_RANGE": "9000-12000",
},
},
}
cvlErrInfo, err := cvSess.ValidateEditConfig(cfgDataRule)
cvl.ValidationSessClose(cvSess)
if err == cvl.CVL_SUCCESS {
//Should fail
t.Errorf("Config Validation failed -- error details %v", cvlErrInfo)
}
unloadConfigDB(rclient, depDataMap)
}
func TestValidateEditConfig_When_Exp_In_Leaf_Positive(t *testing.T) {
depDataMap := map[string]interface{}{
"STP": map[string]interface{}{
"GLOBAL": map[string]interface{}{
"mode": "rpvst",
},
},
}
loadConfigDB(rclient, depDataMap)
cvSess, _ := cvl.ValidationSessOpen()
cfgData := []cvl.CVLEditConfigData{
cvl.CVLEditConfigData{
cvl.VALIDATE_ALL,
cvl.OP_CREATE,
"STP_PORT|Ethernet4",
map[string]string{
"enabled": "true",
"edge_port": "true",
"link_type": "shared",
},
},
}
cvlErrInfo, err := cvSess.ValidateEditConfig(cfgData)
cvl.ValidationSessClose(cvSess)
if err != cvl.CVL_SUCCESS {
//Should succeed
t.Errorf("Config Validation failed -- error details %v", cvlErrInfo)
}
unloadConfigDB(rclient, depDataMap)
}
func TestValidateEditConfig_When_Exp_In_Leaf_Negative(t *testing.T) {
depDataMap := map[string]interface{}{
"STP": map[string]interface{}{
"GLOBAL": map[string]interface{}{
"mode": "mstp",
},
},
}
loadConfigDB(rclient, depDataMap)
cvSess, _ := cvl.ValidationSessOpen()
cfgData := []cvl.CVLEditConfigData{
cvl.CVLEditConfigData{
cvl.VALIDATE_ALL,
cvl.OP_CREATE,
"STP_PORT|Ethernet4",
map[string]string{
"enabled": "true",
"edge_port": "true",
"link_type": "shared",
},
},
}
cvlErrInfo, err := cvSess.ValidateEditConfig(cfgData)
cvl.ValidationSessClose(cvSess)
if err == cvl.CVL_SUCCESS {
//Should succeed
t.Errorf("Config Validation failed -- error details %v", cvlErrInfo)
}
unloadConfigDB(rclient, depDataMap)
}
|
package dto
type ArticleSaved struct {
Id int `json:"id" db:"Id"`
ArticleId int `json:"article_id" db:"ArticleId"`
UserId int `json:"user_id" db:"UserId"`
SaveDate *TimeJson `json:"save_date" db:"SaveDate"`
}
|
package rolling
import (
"sync"
"time"
)
const WINDOWSIZE=5
type Number struct {
Buckets map[int64]*bucket
Mu *sync.RWMutex
}
type bucket struct {
Value int64
}
func NewNumber() *Number {
rn := &Number{
Buckets: make(map[int64]*bucket),
Mu: &sync.RWMutex{},
}
return rn
}
func (rn *Number) getCurrentBucket() *bucket {
now := time.Now().Unix()
var b *bucket
var ok bool
if b, ok = rn.Buckets[now]; !ok {
b = &bucket{}
rn.Buckets[now] = b
}
return b
}
func (rn *Number) removeOldBuckets() {
expired := time.Now().Unix() - WINDOWSIZE
for timestamp := range rn.Buckets {
if timestamp <= expired {
delete(rn.Buckets, timestamp)
}
}
}
// Increment 累加最新桶的计数器
func (rn *Number) Increment(i int64) {
rn.Mu.Lock()
b := rn.getCurrentBucket()
b.Value += i
rn.removeOldBuckets()
rn.Mu.Unlock()
}
// UpdateMax 将最新桶的计数器置为某个最大值
func (rn *Number) UpdateMax(n int64) {
rn.Mu.Lock()
b := rn.getCurrentBucket()
if n > b.Value {
b.Value = n
}
rn.Mu.Unlock()
rn.removeOldBuckets()
}
// Sum 计算最新 5 个桶内计数器的和
func (rn *Number) Sum(now time.Time) int64 {
sum := int64(0)
rn.Mu.RLock()
defer rn.Mu.RUnlock()
for timestamp, bucket := range rn.Buckets {
if timestamp >= now.Unix()-WINDOWSIZE {
sum += bucket.Value
}
}
return sum
}
// Max 获取最新 5 个桶内计数器的最大值
func (rn *Number) Max(now time.Time) int64 {
var max int64
rn.Mu.RLock()
defer rn.Mu.RUnlock()
for timestamp, bucket := range rn.Buckets {
if timestamp >= now.Unix()-WINDOWSIZE {
if bucket.Value > max {
max = bucket.Value
}
}
}
return max
}
// Avg 计算最新 5 个桶内计数器的平均值
func (rn *Number) Avg(now time.Time) int64 {
return rn.Sum(now) / WINDOWSIZE
}
|
package direktivapps
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
const (
DirektivActionIDHeader = "Direktiv-ActionID"
DirektivInstanceIDHeader = "Direktiv-InstanceID"
DirektivExchangeKeyHeader = "Direktiv-ExchangeKey"
DirektivPingAddrHeader = "Direktiv-PingAddr"
DirektivTimeoutHeader = "Direktiv-Timeout"
DirektivStepHeader = "Direktiv-Step"
DirektivResponseHeader = "Direktiv-Response"
DirektivErrorCodeHeader = "Direktiv-ErrorCode"
DirektivErrorMessageHeader = "Direktiv-ErrorMessage"
)
// ActionError is a struct Direktiv uses to report application errors.
type ActionError struct {
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
}
const outPath = "/direktiv-data/data.out"
const dataInPath = "/direktiv-data/data.in"
const errorPath = "/direktiv-data/error.json"
// Respond with error
func RespondWithError(w http.ResponseWriter, code string, err string) {
w.Header().Set(DirektivErrorCodeHeader, code)
w.Header().Set(DirektivErrorMessageHeader, err)
}
// Respond writes out to the responsewriter the json marshalled data
func Respond(w http.ResponseWriter, data []byte) {
w.Write(data)
}
// Unmarshal reads the req body and unmarshals the data
func Unmarshal(obj interface{}, r *http.Request) (string, error) {
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return "", err
}
rdr := bytes.NewReader(data)
dec := json.NewDecoder(rdr)
dec.DisallowUnknownFields()
err = dec.Decode(obj)
if err != nil {
return "", err
}
return r.Header.Get(DirektivActionIDHeader), nil
}
// StartServer starts a new server
func StartServer(f func(w http.ResponseWriter, r *http.Request)) {
fmt.Println("Starting server")
mux := http.NewServeMux()
mux.HandleFunc("/", f)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM)
go func() {
<-sigs
ShutDown(srv)
}()
srv.ListenAndServe()
}
// ShutDown turns off the server
func ShutDown(srv *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
}
// Log sends a string to log via kubernetes
func Log(aid, l string) {
http.Post(fmt.Sprintf("http://localhost:8889/log?aid=%s", aid), "plain/text", strings.NewReader(l))
}
// LogDouble logs to direktiv and stdout
func LogDouble(aid, l string) {
fmt.Println(l)
http.Post(fmt.Sprintf("http://localhost:8889/log?aid=%s", aid), "plain/text", strings.NewReader(l))
}
// ReadIn reads data from dataInPath and returns struct provided with json fields
func ReadIn(obj interface{}, g ActionError) {
f, err := os.Open(dataInPath)
if err != nil {
g.ErrorMessage = err.Error()
WriteError(g)
}
defer f.Close()
dec := json.NewDecoder(f)
dec.DisallowUnknownFields()
err = dec.Decode(obj)
if err != nil {
g.ErrorMessage = err.Error()
WriteError(g)
}
}
// WriteError writes an error to errorPath
func WriteError(g ActionError) {
b, _ := json.Marshal(g)
ioutil.WriteFile(errorPath, b, 0755)
os.Exit(0)
}
// WriteOut writes out data to outPath
func WriteOut(by []byte, g ActionError) {
var err error
err = ioutil.WriteFile(outPath, by, 0755)
if err != nil {
g.ErrorMessage = err.Error()
WriteError(g)
}
os.Exit(0)
}
|
package main
import (
"bufio"
aesext "cm_liveme_im/libs/crypto/aes"
rsaext "cm_liveme_im/libs/crypto/rsa"
"cm_liveme_im/libs/define"
"cm_liveme_im/libs/proto"
"crypto/rsa"
"encoding/json"
"fmt"
"net"
"time"
pb "github.com/golang/protobuf/proto"
log "github.com/thinkboy/log4go"
)
func initMsgTCP() {
status := ST_INIT
var err error
AddRoutinue()
defer SubRoutinue()
myuid := fmt.Sprintf("%s_%d", Conf.SubKey, GetUserSeqId())
log.Debug("%s init-------->", myuid)
// prepare auth
var (
AuthVerion uint32 = 1
pubKey *rsa.PublicKey
tokenTupleJson []byte
aesKey []byte = []byte("1234567890123456")
)
authScrt := &proto.AuthSecret{Version: &AuthVerion}
if pubKey, err = rsaext.PublicKey([]byte(PubkeyStr)); err != nil {
log.Error("%v\n", err)
return
}
if authScrt.AesKey, err = rsaext.Encrypt(aesKey, pubKey); err != nil {
log.Error("%v\n", err)
return
}
authInfo := &proto.AuthInfo{Uid: myuid, Token: "XXb9a9b3289ae171010cf25043b68eb2c3"}
if tokenTupleJson, err = json.Marshal(authInfo); err != nil {
log.Error("%v\n", err)
return
}
if authScrt.AuthInfo, err = aesext.CbcEncryptWithPKCS7Padding(aesKey, tokenTupleJson); err != nil {
log.Error("%v\n", err)
return
}
//// connect server
conn, err := net.Dial("tcp", Conf.TCPAddr)
if err != nil {
log.Error(" %s net.Dial(\"%s\") error(%v)", myuid, Conf.TCPAddr, err)
return
}
defer conn.Close()
wr := bufio.NewWriter(conn)
rd := bufio.NewReader(conn)
status = ST_CONNECTED
//req
prt := new(proto.Proto)
prt.Ver = 1
prt.Operation = define.OP_AUTH
prt.SeqId = GetSeqId()
prt.Body, _ = pb.Marshal(authScrt)
if err = tcpWriteProto(wr, prt); err != nil {
log.Error("%s tcpWriteProto() error(%v)", myuid, err)
return
}
//resp
if err = tcpReadProto(rd, prt); err != nil {
log.Error("%s tcpReadProto() error(%v)", myuid, err)
return
}
if prt.Operation == define.OP_AUTH_REPLY {
log.Debug("%s auth ok, proto: %v", myuid, prt)
} else {
log.Debug("%s auth err proto: %v", myuid, prt)
}
status = ST_AUTH
////enter room
//req
prt.SeqId = GetSeqId()
prt.Operation = define.OP_ROOM_EVENT
prt.Body, _ = pb.Marshal(&proto.RoomDoorBell{RoomId: &Conf.RoomId, Uid: &myuid, Type: &EnterRoom})
if err = tcpWriteProto(wr, prt); err != nil {
log.Error(" %s tcpWriteProto() error(%v)", myuid, err)
return
}
//resp
if err = tcpReadProto(rd, prt); err != nil {
log.Error("%s tcpReadProto() error(%v)", myuid, err)
return
}
if prt.Operation == define.OP_ROOM_EVENT_REPLY {
log.Debug("%s enter room ok, proto: %v", myuid, prt)
} else {
log.Debug("%s enter room err proto: %v", myuid, prt)
}
msg := new(proto.RoomDoorBell)
pb.Unmarshal(prt.Body, msg)
status = ST_ENTER_ROOM
log.Info("%s enter room ,wait for msg:%d", myuid, status)
//write routine
go func() {
timermsg := time.NewTimer(time.Millisecond * 40)
timerheart := time.NewTimer(time.Second * 30)
proto1 := new(proto.Proto)
for {
select {
case <-timermsg.C:
// heartbeat
timermsg.Reset(MsgSendGap)
proto1.SeqId = GetSeqId()
//proto1.Operation = define.OP_HEARTBEAT
//proto1.Body = nil
proto1.Operation = define.OP_SEND_SMS
proto1.Body, _ = pb.Marshal(&proto.Msg{ToId: &Conf.RoomId, FromId: &myuid, RouteType: &RoomMsg, ContentType: &RoomMsgCType, Msg: MsgBodyToSend})
if err = tcpWriteProto(wr, proto1); err != nil {
log.Error("%s tcpWriteProto() error(%v)", myuid, err)
return
} else {
log.Debug("%s send msg", myuid)
}
case <-timerheart.C:
// heartbeat
timerheart.Reset(time.Second * 30)
proto1.SeqId = GetSeqId()
proto1.Operation = define.OP_HEARTBEAT
proto1.Body = nil
//proto1.Operation = define.OP_SEND_SMS
//proto1.Body, _ = pb.Marshal(&proto.Msg{ToId: &Conf.RoomId, FromId: &myuid, RouteType: &RoomMsg, ContentType: &RoomMsgCType, Msg: []byte("hello world")})
if err = tcpWriteProto(wr, proto1); err != nil {
log.Error("%s tcpWriteProto() error(%v)", myuid, err)
return
} else {
log.Debug("%s send heart", myuid)
}
}
}
log.Debug("heart routine exits eeeee")
}()
// reader routine
for {
//read msg
if err = tcpReadProto(rd, prt); err != nil {
log.Error("%s tcpReadProto() error(%v)", myuid, err)
break
}
switch prt.Operation {
case define.OP_HEARTBEAT_REPLY:
log.Debug("OP_HEARTBEAT_REPLY")
if err = conn.SetReadDeadline(time.Now().Add(60 * time.Second)); err != nil {
log.Error("%s conn.SetReadDeadline() error(%v)", myuid, err)
break
}
case define.OP_SEND_SMS_REPLY:
log.Debug("OP_SEND_SMS_REPLY")
case define.OP_TEST_REPLY:
log.Debug("%s body: %s", myuid, string(prt.Body))
case define.OP_SEND_SMS_DELIVER:
msg := &proto.Msg{}
pb.Unmarshal(prt.Body, msg)
log.Debug("OP_SEND_SMS_DELIVER len: %d", len(msg.Msg))
}
}
log.Debug("%s read routine exits xxxxx", myuid)
}
|
// Triangle package prvoides a function for determining whether 3 sides form a triangle and if so what kind
package triangle
import "math"
type Kind int
const (
NaT = iota // not a triangle
Equ // equilateral
Iso // isosceles
Sca // scalene
)
// KindFromSides takes 3 sides and determines the Kind of triangle
func KindFromSides(a, b, c float64) Kind {
switch {
case isNotTriangle(a, b, c):
return NaT
case a == b && b == c:
return Equ
case a != b && a != c && b != c:
return Sca
default:
return Iso
}
}
func isNotTriangle(a, b, c float64) bool {
return hasNonExistantSide(a, b, c) ||
hasSidesNotGreaterThanThird(a, b, c) ||
hasInfSide(a, b, c) ||
hasNaNSide(a, b, c)
}
func hasSidesNotGreaterThanThird(a, b, c float64) bool {
return (a+b) < c || (a+c) < b || (b+c) < a
}
func hasNonExistantSide(a, b, c float64) bool {
return a <= 0 || b <= 0 || c <= 0
}
func hasNaNSide(a, b, c float64) bool {
return math.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c)
}
func hasInfSide(a, b, c float64) bool {
return math.IsInf(a, 1) || math.IsInf(b, 1) || math.IsInf(c, 1)
}
|
package main
import (
"fmt"
"log"
"net"
"strings"
"time"
)
type simpleServer struct {
listener
userlist *userlist
msgsChan chan message // channel of messages inbound from clients
commands map[string]commandHandler
startTime time.Time
roomlist []int
}
func (s simpleServer) roomExists(id int) bool {
for _, i := range s.roomlist {
if i == id {
return true
}
}
return false
}
func (s simpleServer) usersInRoom(id int) []*user {
result := []*user{}
for _, u := range s.userlist.users {
if u.room == id {
result = append(result, u)
}
}
return result
}
func (s simpleServer) handleMsgs() {
for {
msg := <-s.msgsChan
msg.txt = strings.TrimSpace(msg.txt)
fmt.Printf("From %s: %+s (%q) (%+v)\n", msg.src.name, msg.txt, msg.txt, msg)
if strings.HasPrefix(msg.txt, "/") {
s.handleCommand(msg)
}
_, err := fmt.Fprintf(msg.src, "> ")
if err != nil {
log.Fatal(err)
}
}
}
func (s simpleServer) handleCommand(msg message) {
cmd := strings.Split(msg.txt, " ")
handler, ok := s.commands[strings.Trim(cmd[0], "/")]
if ok {
handler(msg, &s)
return
}
_, err := fmt.Fprintf(msg.src, "Huh, what?\n")
if err != nil {
log.Fatal(err)
}
}
func newSimpleServer(c config) *simpleServer {
addr := &net.TCPAddr{
IP: net.ParseIP(c.ip),
Port: c.port,
}
commands := make(map[string]commandHandler)
commands["who"] = whoCmdHandler
commands["uptime"] = uptimeCmdHandler
commands["rooms"] = roomsCmdHandler
commands["here"] = hereCmdHandler
commands["say"] = sayCmdHandler
commands["name"] = nameCmdHandler
return &simpleServer{
userlist: &userlist{},
commands: commands,
msgsChan: make(chan message),
listener: listener{
addr: addr,
newConns: make(chan *net.Conn),
},
roomlist: []int{0},
}
}
func (s *simpleServer) run() error {
s.startTime = time.Now()
id := int(0)
go s.listen()
go s.handleMsgs()
for {
conn := <-s.newConns
u := newUser(id, conn, s.msgsChan)
s.addToUserList(u)
go u.process()
id++
}
return nil
}
func (s *simpleServer) listen() {
log.Printf("listening on %s", s.addr)
listener, err := net.ListenTCP("tcp", s.addr)
if err != nil {
log.Panic(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Panic(err)
}
log.Printf("Client connected: %s...\n", conn.RemoteAddr())
s.newConns <- &conn
}
}
func (s *simpleServer) addToUserList(u *user) {
s.userlist.lock.Lock()
s.userlist.users = append(s.userlist.users, u)
s.userlist.lock.Unlock()
}
func (s *simpleServer) removeFromUserList(u *user) {
results := []*user{}
for _, each := range s.userlist.users {
if each.id != u.id {
results = append(results, each)
}
}
s.userlist.lock.Lock()
s.userlist.users = results
s.userlist.lock.Unlock()
}
|
package main
import (
"fmt"
"sync/atomic"
"time"
)
var totalOperations int32 = 0
func increment() {
atomic.AddInt32(&totalOperations, 1)
}
func main() {
for i := 0; i < 1000; i++{
go increment()
}
time.Sleep(2 * time.Millisecond)
//expecting totalOperations = 1000, but in fact...
fmt.Println("totalOperations = ", totalOperations)
}
|
package main
import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
func SendKeyboard(u *User, text string) {
message := tgbotapi.NewMessage(u.ChatID, text)
switch u.State {
case InitState:
btnStart := tgbotapi.NewKeyboardButton("Start")
btnAbout := tgbotapi.NewKeyboardButton("About")
btnRow1 := tgbotapi.NewKeyboardButtonRow(btnStart, btnAbout)
btnRate := tgbotapi.NewKeyboardButton("Please give us five Stars!")
btnRow2 := tgbotapi.NewKeyboardButtonRow(btnRate)
keyboard := tgbotapi.NewReplyKeyboard(btnRow1, btnRow2)
keyboard.OneTimeKeyboard = true
message.ReplyMarkup = keyboard
_, err := u.Send(message)
if err != nil {
u.Println("Error sending Init keyboard:" + err.Error())
}
case ConfigState:
btnHost := tgbotapi.NewKeyboardButton("Host")
btnPort := tgbotapi.NewKeyboardButton("Port")
btnRow1 := tgbotapi.NewKeyboardButtonRow(btnHost, btnPort)
btnUser := tgbotapi.NewKeyboardButton("User")
btnPass := tgbotapi.NewKeyboardButton("Pass")
btnRow2 := tgbotapi.NewKeyboardButtonRow(btnUser, btnPass)
btnReady := tgbotapi.NewKeyboardButton("Start sending commands!")
btnRow3 := tgbotapi.NewKeyboardButtonRow(btnReady)
keyboard := tgbotapi.NewReplyKeyboard(btnRow1, btnRow2, btnRow3)
keyboard.OneTimeKeyboard = true
message.ReplyMarkup = keyboard
_, err := u.Send(message)
if err != nil {
u.Println("Error sending Config keyboard:" + err.Error())
}
case ReadyState:
}
}
func SendRateInline(u *User) {
u.Println("It's an opensource project, help us!")
u.Println("Please access the link below and give us five Stars!")
message := tgbotapi.NewMessage(u.ChatID, "https://telegram.me/storebot?start=sshclientbot")
message.DisableWebPagePreview = true
_, err := u.Send(message)
if err != nil {
u.Println("Error sending Rate keyboard: " + err.Error())
}
}
|
package seeders
import (
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
"github.com/tespo/satya/v2/types"
)
var reminders = types.Reminders{
{
ID: uuid.FromStringOrNil("0b703c2b-72c6-43ef-a089-4ce85e06519a"),
UserID: uuid.FromStringOrNil("8c8aa229-3959-4a40-bbe6-67c2eeace5cb"),
RegimenID: uuid.FromStringOrNil("8ba3049b-17a1-4eae-b2bc-db7d18596d28"),
Minute: 750,
},
}
func seedReminders(db *gorm.DB) error {
if !db.HasTable(&types.Reminder{}) {
if err := db.AutoMigrate(&types.Reminder{}).Error; err != nil {
return err
}
}
for _, reminder := range reminders {
if err := reminder.Create(db); err != nil {
return err
}
}
return nil
}
|
package requestargs
import (
"bytes"
"fmt"
"github.com/iotaledger/wasp/packages/dbprovider"
"github.com/iotaledger/wasp/packages/hashing"
"github.com/iotaledger/wasp/packages/kv"
"github.com/iotaledger/wasp/packages/kv/kvdecoder"
"github.com/iotaledger/wasp/packages/registry"
"github.com/iotaledger/wasp/packages/testutil"
"github.com/iotaledger/wasp/packages/util"
"github.com/stretchr/testify/require"
"testing"
)
func TestRequestArguments1(t *testing.T) {
r := New(nil)
r.AddEncodeSimple("arg1", []byte("data1"))
r.AddEncodeSimple("arg2", []byte("data2"))
r.AddEncodeSimple("arg3", []byte("data3"))
r.AddAsBlobRef("arg4", []byte("data4"))
require.Len(t, r, 4)
require.EqualValues(t, r["-arg1"], "data1")
require.EqualValues(t, r["-arg2"], "data2")
require.EqualValues(t, r["-arg3"], "data3")
h := hashing.HashStrings("data4")
require.EqualValues(t, r["*arg4"], h[:])
var buf bytes.Buffer
err := r.Write(&buf)
require.NoError(t, err)
rdr := bytes.NewReader(buf.Bytes())
back := New(nil)
err = back.Read(rdr)
require.NoError(t, err)
}
func TestRequestArguments2(t *testing.T) {
r := New(nil)
r.AddEncodeSimple("arg1", []byte("data1"))
r.AddEncodeSimple("arg2", []byte("data2"))
r.AddEncodeSimple("arg3", []byte("data3"))
r.AddAsBlobRef("arg4", []byte("data4"))
h := hashing.HashStrings("data4")
require.Len(t, r, 4)
require.EqualValues(t, r["-arg1"], "data1")
require.EqualValues(t, r["-arg2"], "data2")
require.EqualValues(t, r["-arg3"], "data3")
require.EqualValues(t, r["*arg4"], h[:])
var buf bytes.Buffer
err := r.Write(&buf)
require.NoError(t, err)
rdr := bytes.NewReader(buf.Bytes())
back := New(nil)
err = back.Read(rdr)
require.NoError(t, err)
require.Len(t, back, 4)
require.EqualValues(t, back["-arg1"], "data1")
require.EqualValues(t, back["-arg2"], "data2")
require.EqualValues(t, back["-arg3"], "data3")
require.EqualValues(t, back["*arg4"], h[:])
}
func TestRequestArguments3(t *testing.T) {
r := New(nil)
r.AddEncodeSimple("arg1", []byte("data1"))
r.AddEncodeSimple("arg2", []byte("data2"))
r.AddEncodeSimple("arg3", []byte("data3"))
require.Len(t, r, 3)
require.EqualValues(t, r["-arg1"], "data1")
require.EqualValues(t, r["-arg2"], "data2")
require.EqualValues(t, r["-arg3"], "data3")
log := testutil.NewLogger(t)
db := dbprovider.NewInMemoryDBProvider(log)
reg := registry.NewRegistry(nil, log, db)
d, ok, err := r.SolidifyRequestArguments(reg)
require.NoError(t, err)
require.True(t, ok)
dec := kvdecoder.New(d)
var s1, s2, s3 string
require.NotPanics(t, func() {
s1 = dec.MustGetString("arg1")
s2 = dec.MustGetString("arg2")
s3 = dec.MustGetString("arg3")
})
require.Len(t, d, 3)
require.EqualValues(t, "data1", s1)
require.EqualValues(t, "data2", s2)
require.EqualValues(t, "data3", s3)
}
func TestRequestArguments4(t *testing.T) {
r := New(nil)
r.AddEncodeSimple("arg1", []byte("data1"))
r.AddEncodeSimple("arg2", []byte("data2"))
r.AddEncodeSimple("arg3", []byte("data3"))
data := []byte("data4")
r.AddAsBlobRef("arg4", data)
h := hashing.HashData(data)
require.Len(t, r, 4)
require.EqualValues(t, r["-arg1"], "data1")
require.EqualValues(t, r["-arg2"], "data2")
require.EqualValues(t, r["-arg3"], "data3")
require.EqualValues(t, r["*arg4"], h[:])
log := testutil.NewLogger(t)
db := dbprovider.NewInMemoryDBProvider(log)
reg := registry.NewRegistry(nil, log, db)
_, ok, err := r.SolidifyRequestArguments(reg)
require.NoError(t, err)
require.False(t, ok)
}
func TestRequestArguments5(t *testing.T) {
r := New(nil)
r.AddEncodeSimple("arg1", []byte("data1"))
r.AddEncodeSimple("arg2", []byte("data2"))
r.AddEncodeSimple("arg3", []byte("data3"))
data := []byte("data4-data4-data4-data4-data4-data4-data4")
r.AddAsBlobRef("arg4", data)
h := hashing.HashData(data)
require.Len(t, r, 4)
require.EqualValues(t, r["-arg1"], "data1")
require.EqualValues(t, r["-arg2"], "data2")
require.EqualValues(t, r["-arg3"], "data3")
require.EqualValues(t, r["*arg4"], h[:])
log := testutil.NewLogger(t)
db := dbprovider.NewInMemoryDBProvider(log)
reg := registry.NewRegistry(nil, log, db)
hback, err := reg.PutBlob(data)
require.NoError(t, err)
require.EqualValues(t, h, hback)
back, ok, err := r.SolidifyRequestArguments(reg)
require.NoError(t, err)
require.True(t, ok)
require.Len(t, back, 4)
require.EqualValues(t, back["arg1"], "data1")
require.EqualValues(t, back["arg2"], "data2")
require.EqualValues(t, back["arg3"], "data3")
require.EqualValues(t, back["arg4"], data)
}
const N = 50
func TestRequestArgumentsDeterminism(t *testing.T) {
data := []byte("data4-data4-data4-data4-data4-data4-data4")
perm := util.NewPermutation16(N, data).GetArray()
darr1 := make([]string, N)
darr2 := make([]string, N)
for i := range darr1 {
darr1[i] = fmt.Sprintf("arg%d", i)
}
for i := range darr2 {
darr2[i] = darr1[perm[i]]
}
r1 := New(nil)
for i, s := range darr1 {
r1.AddEncodeSimple(kv.Key(s), []byte(darr2[i]))
}
r1.AddAsBlobRef("---", data)
r2 := New(nil)
r1.AddAsBlobRef("---", data)
for i := range darr1 {
r2.AddEncodeSimple(kv.Key(darr1[perm[i]]), []byte(darr2[perm[i]]))
}
h1 := hashing.HashData(util.MustBytes(r1))
h2 := hashing.HashData(util.MustBytes(r1))
require.EqualValues(t, h1, h2)
}
|
package router
import (
"net/http"
"github.com/gorilla/mux"
)
type Route struct {
Pattern string
Method string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter(routes Routes) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
handler := Logger(JsonResponse(route.HandlerFunc))
router.HandleFunc(route.Pattern, handler).Methods(route.Method)
}
return router
}
|
package main
import (
"context"
"fmt"
"os"
"os/signal"
. "web-layout/utils/gin/gate"
)
func main() {
g := NewGate(8080)
g.POST("/test", test)
g.AddGroup("/group1")
g.GET("/test1", test1, "/group1")
g.GET("/test2", test2, "/group1")
g.AddGroup("/group2")
g.GET("/test1", test3, "/group2")
g.GET("/test2", test4, "/group2")
g.Start()
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
g.Shutdown()
}
func test(ctx context.Context, req *map[string]interface{}) map[string]interface{} {
fmt.Println(req)
return map[string]interface{}{"func": "test"}
}
func test1(ctx context.Context) map[string]interface{} { return map[string]interface{}{"func": "test1"} }
func test2(ctx context.Context) map[string]interface{} { return map[string]interface{}{"func": "test2"} }
func test3(ctx context.Context) map[string]interface{} { return map[string]interface{}{"func": "test3"} }
func test4(ctx context.Context) map[string]interface{} { return map[string]interface{}{"func": "test4"} }
|
/*
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
sum:=&ListNode{}
p:=sum
var num int
for l1!=nil || l2!=nil{
sum.Next=new(ListNode)
sum=sum.Next
if l1!=nil{
if l2!=nil{
sum.Val=l1.Val+l2.Val+num
}else{
sum.Val=l1.Val+num
}
}else{
sum.Val=l2.Val+num
}
num= sum.Val/10
sum.Val=sum.Val%10
if l1!=nil{
l1=l1.Next
}
if l2!=nil{
l2=l2.Next
}
}
if num!=0{
sum.Next=new(ListNode)
sum=sum.Next
sum.Val=num
}
return p.Next
} |
package metadata
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/root-gg/plik/server/common"
)
func TestBackend_GetUploadStatistics(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
uploads, files, totalSize, err := b.GetUploadStatistics(nil, nil)
require.NoError(t, err, "unexpected error")
require.Equal(t, 100, uploads, "invalid upload count")
require.Equal(t, 1000, files, "invalid file count")
require.Equal(t, int64(2000), totalSize, "invalid file size")
}
func TestBackend_GetUploadNoFiles(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
createUpload(t, b, upload)
}
uploads, files, totalSize, err := b.GetUploadStatistics(nil, nil)
require.NoError(t, err, "unexpected error")
require.Equal(t, 100, uploads, "invalid upload count")
require.Equal(t, 0, files, "invalid file count")
require.Equal(t, int64(0), totalSize, "invalid file size")
}
func TestBackend_GetUploadStatistics_User(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
userID := "user"
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
upload.User = userID
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
uploads, files, totalSize, err := b.GetUploadStatistics(&userID, nil)
require.NoError(t, err, "unexpected error")
require.Equal(t, 100, uploads, "invalid upload count")
require.Equal(t, 1000, files, "invalid file count")
require.Equal(t, int64(2000), totalSize, "invalid file size")
}
func TestBackend_GetUploadStatistics_Token(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
userID := "user"
tokenStr := "token"
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
upload.User = userID
if i%2 == 0 {
upload.Token = tokenStr
}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
uploads, files, totalSize, err := b.GetUploadStatistics(&userID, &tokenStr)
require.NoError(t, err, "unexpected error")
require.Equal(t, 50, uploads, "invalid upload count")
require.Equal(t, 500, files, "invalid file count")
require.Equal(t, int64(1000), totalSize, "invalid file size")
}
func TestBackend_GetUploadStatistics_Anonymous(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 3
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
userID := "user"
tokenStr := "token"
for i := 1; i <= 100; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
upload.User = userID
if i%2 == 0 {
upload.Token = tokenStr
}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
userID = ""
tokenStr = ""
uploads, files, totalSize, err := b.GetUploadStatistics(&userID, &tokenStr)
require.NoError(t, err, "unexpected error")
require.Equal(t, 100, uploads, "invalid upload count")
require.Equal(t, 1000, files, "invalid file count")
require.Equal(t, int64(3000), totalSize, "invalid file size")
}
func TestBackend_GetUserStatistics(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 100; i++ {
upload := &common.Upload{User: "user_id", Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
stats, err := b.GetUserStatistics("user_id", nil)
require.NoError(t, err, "unexpected error")
require.Equal(t, 100, stats.Uploads, "invalid upload count")
require.Equal(t, 1000, stats.Files, "invalid file count")
require.Equal(t, int64(2000), stats.TotalSize, "invalid file size")
}
func TestBackend_GetServerStatistics(t *testing.T) {
b := newTestMetadataBackend()
defer shutdownTestMetadataBackend(b)
for i := 1; i <= 10; i++ {
upload := &common.Upload{Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
for i := 1; i <= 10; i++ {
upload := &common.Upload{User: "user_id", Comments: fmt.Sprintf("%d", i)}
for j := 1; j <= 10; j++ {
file := upload.NewFile()
file.Size = 2
file.Status = common.FileUploaded
}
createUpload(t, b, upload)
}
stats, err := b.GetServerStatistics()
require.NoError(t, err, "unexpected error")
require.Equal(t, 20, stats.Uploads, "invalid upload count")
require.Equal(t, 200, stats.Files, "invalid file count")
require.Equal(t, int64(400), stats.TotalSize, "invalid file size")
}
|
/*
Copyright 2011 Google 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 dbimpl defines interfaces to be implemented by database
// drivers as used by package db.
//
// Code simply using databases should use package db.
package dbimpl
import (
"os"
)
// must only deal with values:
// int64 (no uint64 support, for now?)
// float64
// bool
// nil
// []byte
// Driver is the interface that must be implemented by database
// driver.
type Driver interface {
// Open returns a new or cached connection to the database.
// The dsn parameter, the Data Source Name, contains a
// driver-specific string containing the database name,
// connection parameters, authentication parameters, etc.
//
// The returned connection is only used by one goroutine at a
// time.
Open(dsn string) (Conn, os.Error)
}
// Execer is an optional interface that may be implemented by a Driver
// or a Conn.
//
// If not implemented by a Driver, the db package's DB.Exec method
// first obtains a free connection from its free pool or from the
// driver's Open method. Execer should only be implemented by drivers
// which can provide a more effcient implementation.
//
// If not implemented by a Conn, the db package's DB.Exec will first
// prepare a query, execute the statement, and then close the
// statement.
type Execer interface {
Exec(query string, args []interface{}) (Result, os.Error)
}
type Conn interface {
// Prepare returns a prepared statement, bound to this connection.
Prepare(query string) (Stmt, os.Error)
// Close invalidates and potentially stops any current
// prepared statements and transactions, marking this
// connection as no longer in use. The driver may cache or
// close its underlying connection to its database.
Close() os.Error
// Begin starts and returns a new transaction.
Begin() (Tx, os.Error)
}
type Result interface {
AutoIncrementId() (int64, os.Error)
RowsAffected() (int64, os.Error)
}
// Stmt is a prepared statement. It is bound to a Conn and not
// used by multiple goroutines concurrently.
type Stmt interface {
Close() os.Error
NumInput() int
Exec(args []interface{}) (Result, os.Error)
Query(args []interface{}) (Rows, os.Error)
}
// ColumnConverter may be optionally implemented by Stmt to signal
// to the db package to do type conversions.
type ColumnConverter interface {
ColumnCoverter(idx int) ValueConverter
}
type ValueConverter interface {
ConvertValue(v interface{}) (interface{}, os.Error)
}
type Rows interface {
Columns() []string
Close() os.Error
// Returns os.EOF at end of cursor
Next(dest []interface{}) os.Error
}
type Tx interface {
Commit() os.Error
Rollback() os.Error
}
type RowsAffected int64
func (RowsAffected) AutoIncrementId() (int64, os.Error) {
return 0, os.NewError("no AutoIncrementId available")
}
func (v RowsAffected) RowsAffected() (int64, os.Error) {
return int64(v), nil
}
type ddlSuccess struct{}
var DDLSuccess Result = ddlSuccess{}
func (ddlSuccess) AutoIncrementId() (int64, os.Error) {
return 0, os.NewError("no AutoIncrementId available after DDL statement")
}
func (ddlSuccess) RowsAffected() (int64, os.Error) {
return 0, os.NewError("no RowsAffected available after DDL statement")
}
|
package main
import (
"database/sql"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"time"
"golang.org/x/crypto/bcrypt"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/sessions"
)
var (
db *sql.DB
store = sessions.NewCookieStore([]byte("something-very-secret"))
)
func main() {
_db, err := sql.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("DB Error! --> ", err.Error())
os.Exit(1)
}
db = _db
defer db.Close()
http.HandleFunc("/", top)
http.HandleFunc("/signup", signup)
http.HandleFunc("/login", login)
http.HandleFunc("/upload", upload)
http.HandleFunc("/comment", comment)
http.HandleFunc("/commentdel", commentdel)
http.HandleFunc("/logout", logout)
http.Handle("/img/", http.FileServer(http.Dir("./")))
http.Handle("/css/", http.FileServer(http.Dir("./")))
http.ListenAndServe(":8080", nil)
}
type post struct {
PostID int
NameText string
ImgPath string
Comments []string
}
type contents []*post
//topページ
func top(w http.ResponseWriter, r *http.Request) {
tmp := template.Must(template.ParseFiles("template/top.html.tpl"))
rows, err := db.Query("SELECT posts.id, name, img_name FROM posts INNER JOIN users ON posts.user_id=users.id ORDER BY posts.id DESC limit 50")
if err != nil {
log.Println("querry request", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
var posts contents
for rows.Next() {
var (
postID int
userName string
imgName string
comments []string
)
if err := rows.Scan(&postID, &userName, &imgName); err != nil {
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
//コメント読み込み
commentsRows, err := db.Query("SELECT users.name ,comment_body FROM comments LEFT JOIN posts ON comments.post_id=posts.id LEFT JOIN users ON comments.user_id=users.id WHERE comments.post_id =?", postID)
if err != nil {
log.Println("read comment", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
//このループが何故か複数回される??
for commentsRows.Next() {
var commenterName string
var comment string
if err := commentsRows.Scan(&commenterName, &comment); err != nil {
fmt.Println("comment db Err!!!")
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
//fmt.Println(comment)
commentStr := commenterName + ": " + comment
comments = append(comments, commentStr)
}
posts = append(posts, &post{postID, userName, imgName, comments})
}
if err := tmp.ExecuteTemplate(w, "top.html.tpl", posts); err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
//signupページ
func signup(w http.ResponseWriter, r *http.Request) {
tmp := template.Must(template.ParseFiles("template/signup.html.tpl"))
message := ""
if r.Method == http.MethodPost {
//レスポンスの解析
r.ParseForm()
userName := fmt.Sprint(r.Form.Get("username"))
password := fmt.Sprint(r.Form.Get("password"))
if (userName == "") || (password == "") {
message = "Input Form!"
w.WriteHeader(http.StatusNotAcceptable)
if err := tmp.ExecuteTemplate(w, "signup.html.tpl", message); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
// signup時の処理
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
fmt.Println("Hash Error!")
w.WriteHeader(http.StatusInternalServerError)
return
}
//DBに追加
if _, err := db.Exec(`
INSERT INTO users(name, password) VALUES(?, ?)`, userName, hash); err != nil {
fmt.Println("Error! User didn't add.", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
//ユーザー名のディレクトリを作成
dirPath := "./img/" + userName
if err := os.Mkdir(dirPath, 0777); err != nil {
fmt.Println(err.Error())
}
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if err := tmp.ExecuteTemplate(w, "signup.html.tpl", message); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
//loginページ
func login(w http.ResponseWriter, r *http.Request) {
tmp := template.Must(template.ParseFiles("template/login.html.tpl"))
if r.Method == http.MethodPost {
//リクエストの解析
r.ParseForm()
inputUserName := fmt.Sprint(r.Form.Get("username"))
inputPassword := fmt.Sprint(r.Form.Get("password"))
if (inputUserName == "") || (inputPassword == "") {
message := "Input Form!"
w.WriteHeader(http.StatusNotAcceptable)
if err := tmp.ExecuteTemplate(w, "login.html.tpl", message); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
return
}
// login時の処理
//DBから読み出し
rows, err := db.Query("SELECT id, name, password FROM users WHERE name=?", inputUserName)
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
readUserName := ""
readPassword := ""
var id int
for rows.Next() {
if err := rows.Scan(&id, &readUserName, &readPassword); err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
//password確認
if err := bcrypt.CompareHashAndPassword([]byte(readPassword), []byte(inputPassword)); err != nil {
fmt.Println(err.Error())
message := "Something is wrong."
w.WriteHeader(http.StatusNotAcceptable)
if err := tmp.ExecuteTemplate(w, "login.html.tpl", message); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
fmt.Println("Success!")
//session書き込み
session, err := store.Get(r, "user-session")
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
session.Values["userID"] = id
session.Values["userName"] = readUserName
// Save it before we write to the response/return from the handler.
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
message := ""
if err := tmp.ExecuteTemplate(w, "login.html.tpl", message); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func upload(w http.ResponseWriter, r *http.Request) {
tmp := template.Must(template.ParseFiles("template/upload.html.tpl"))
//session 読み出し
session, err := store.Get(r, "user-session")
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
userID, ok := session.Values["userID"]
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
userName := fmt.Sprint(session.Values["userName"])
//画像の受け取り
if r.Method == http.MethodPost {
imgFile, header, err := r.FormFile("upload")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if header.Size == 0 {
if err := tmp.ExecuteTemplate(w, "upload.html.tpl", userName); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
return
}
defer imgFile.Close()
//ファイルの作成
imgPath := fmt.Sprintf("./img/%s/%d.jpg", userName, time.Now().Unix())
f, err := os.Create(imgPath)
defer f.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.Copy(f, imgFile)
//DBに書き込み
if _, err := db.Exec(`
INSERT INTO posts(user_id, img_name) VALUES(?, ?)`, userID, imgPath); err != nil {
fmt.Println("Error! Post didn't add.", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
if err := tmp.ExecuteTemplate(w, "upload.html.tpl", userName); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func comment(w http.ResponseWriter, r *http.Request) {
//session 読み出し
session, err := store.Get(r, "user-session")
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
userID, ok := session.Values["userID"]
//ログインしてない場合はリダイレクト
if ok == false {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
//URLのパラメーターの解析
param, ok := r.URL.Query()["id"]
if !ok || param[0] == "" {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
postID := param[0]
commnenNum := 0
if err := db.QueryRow(`SELECT COUNT(*) FROM comments INNER JOIN posts ON comments.post_id=posts.id WHERE comments.post_id =?`, postID).Scan(&commnenNum); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if commnenNum == 5 {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
if r.Method == http.MethodPost {
r.ParseForm()
commentBody := fmt.Sprint(r.Form.Get("comment_text"))
fmt.Print(postID)
//DBに書き込み
if _, err := db.Exec(`
INSERT INTO comments(post_id, user_id, comment_body) VALUES(?, ?, ?)`, postID, userID, commentBody); err != nil {
fmt.Println("Error! Post didn't add.", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
}
//logoutの処理
func logout(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "user-session")
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
session.Values["userID"] = ""
session.Values["userName"] = ""
// Save it before we write to the response/return from the handler.
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
func commentdel(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "user-session")
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
_, ok := session.Values["userID"]
//ログインしてない場合はリダイレクト
if ok == false {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
//URLのパラメーターの解析
param, ok := r.URL.Query()["id"]
if !ok || param[0] == "" {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
commentID := param[0]
//if r.Method == http.MethodPost {
r.ParseForm()
fmt.Print(commentID)
//DBに書き込み
if _, err := db.Exec(`DELETE FROM comments WHERE id =?`, commentID); err != nil {
fmt.Println("Error! Comment didn't delete.", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
//}
}
|
package middleware
import (
"net/http"
"regexp"
"strings"
"docktor/server/storage"
"docktor/server/types"
jwt "github.com/dgrijalva/jwt-go"
typesDocker "github.com/docker/docker/api/types"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
)
// WithUser check if user is auth
func WithUser(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user, err := AuthUser(c)
if err != nil {
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
c.Set("user", user)
return next(c)
}
}
// WithAdmin (need WithUser) check if user is admin
func WithAdmin(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user").(types.User)
if !user.IsAdmin() {
return echo.NewHTTPError(http.StatusForbidden, "Admin permission required")
}
return next(c)
}
}
// WithGroup (need WithUser) check if it's user group
func WithGroup(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user").(types.User)
db := c.Get("DB").(*storage.Docktor)
group, err := db.Groups().FindByID(c.Param(types.GROUP_ID_PARAM))
if err != nil {
log.WithFields(log.Fields{
"groupID": c.Param(types.GROUP_ID_PARAM),
"error": err,
}).Error("Error when retrieving group")
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
log.WithFields(log.Fields{
"group": group.Name,
"user": user.Username,
}).Debug("Check if group is yours")
if !group.IsMyGroup(&user) {
return echo.NewHTTPError(http.StatusForbidden, "This is not your group")
}
c.Set("group", group)
return next(c)
}
}
// WithGroupAdmin (need WithUser, WithGroup or WithDaemonContainer) check if user is admin on this group
func WithGroupAdmin(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user").(types.User)
group := c.Get("group").(types.Group)
if !group.IsAdmin(&user) {
return echo.NewHTTPError(http.StatusForbidden, "Group admin permission required")
}
return next(c)
}
}
// WithDaemon (need WithUser) check if user has permission on the daemon
func WithDaemon(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user").(types.User)
if user.IsAdmin() {
return next(c)
}
db := c.Get("DB").(*storage.Docktor)
groups, err := db.Groups().FindByUser(user)
if err != nil {
log.WithFields(log.Fields{
"user": user.Username,
"error": err,
}).Error("Error when retrieving user groups")
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
for _, group := range groups {
if group.Daemon.Hex() == c.Param(types.DAEMON_ID_PARAM) {
return next(c)
}
}
return echo.NewHTTPError(http.StatusForbidden, "No group permission on this daemon")
}
}
// WithDaemonContainer (need WithUser) check if user has permission on the daemon and container
func WithDaemonContainer(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user").(types.User)
if user.IsAdmin() {
return next(c)
}
db := c.Get("DB").(*storage.Docktor)
groups, err := db.Groups().FindByUser(user)
if err != nil {
log.WithFields(log.Fields{
"user": user.Username,
"error": err,
}).Error("Error when retrieving user groups")
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
// Remove group which don't have the right daemon id
for i := 0; i < len(groups); i++ {
if groups[i].Daemon.Hex() != c.Param(types.DAEMON_ID_PARAM) {
groups = append(groups[:i], groups[i+1:]...)
}
}
if len(groups) == 0 {
log.WithFields(log.Fields{
"Daemon": c.Param(types.DAEMON_ID_PARAM),
"Username": user.Username,
}).Error("Error when retrieving group")
return echo.NewHTTPError(http.StatusForbidden, "No group permission on this daemon")
}
// Check by container name
for _, group := range groups {
if strings.HasPrefix(types.NormalizeName(c.Param(types.CONTAINER_ID_PARAM)), types.NormalizeName(group.Name)) {
c.Set("group", group)
return next(c)
}
}
// Check by container id
daemon, err := db.Daemons().FindByID(c.Param(types.DAEMON_ID_PARAM))
if err != nil {
log.WithFields(log.Fields{
"Daemon": c.Param(types.DAEMON_ID_PARAM),
"error": err,
}).Error("Error when retrieving daemon")
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
containers, err := daemon.InspectContainers(c.Param(types.CONTAINER_ID_PARAM))
if len(containers) == 0 {
log.WithFields(log.Fields{
"Container": c.Param(types.CONTAINER_ID_PARAM),
"Daemon": daemon.Name,
"error": err,
}).Error("Error when retrieving container")
return echo.NewHTTPError(http.StatusForbidden, "Container doesn't exist")
}
for _, group := range groups {
if strings.HasPrefix(types.NormalizeName(containers[0].Name), types.NormalizeName(group.Name)) {
c.Set("group", group)
return next(c)
}
}
c.Set("container", containers[0])
return echo.NewHTTPError(http.StatusForbidden, "You don't have permission on this container")
}
}
// WithIsAllowShellContainer (need WithUser, WithDaemonContainer) check if user has webshell permission on the container
func WithIsAllowShellContainer(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user").(types.User)
if user.IsAdmin() {
return next(c)
}
container := c.Get("container").(typesDocker.Container)
db := c.Get("DB").(*storage.Docktor)
images, err := db.Images().FindAll()
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Error when retrieving images")
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
for _, image := range images {
if match, _ := regexp.MatchString(image.Image.Pattern, container.Image); match && image.IsAllowShell {
return next(c)
}
}
return echo.NewHTTPError(http.StatusForbidden, "You don't have shell permission on this container")
}
}
// AuthUser return the jwt authed user
func AuthUser(c echo.Context) (types.User, error) {
log.Info("Getting user from token")
user := c.Get("user").(*jwt.Token)
log.WithField("user", user).Info("Getting claims")
claims := user.Claims.(*types.Claims)
log.WithField("claims", claims).Info("Getting db user")
db := c.Get("DB").(*storage.Docktor)
return db.Users().FindByUsername(claims.Username)
}
|
/*
A company conducted a coding test to hire candidates. N candidates appeared for the test, and each of them faced M problems.
Each problem was either unsolved by a candidate (denoted by 'U'), solved partially (denoted by 'P'), or solved completely (denoted by 'F').
To pass the test, each candidate needs to either solve X or more problems completely, or solve (X−1) problems completely, and Y or more problems partially.
Given the above specifications as input, print a line containing N integers. The ith integer should be 1 if the ith candidate has passed the test, else it should be 0.
Input:
The first line of the input contains an integer T, denoting the number of test cases.
The first line of each test case contains two space-separated integers, N and M, denoting the number of candidates who appeared for the test, and the number of problems in the test, respectively.
The second line of each test case contains two space-separated integers, X and Y, as described above, respectively.
The next N lines contain M characters each. The jth character of the ith line denotes the result of the ith candidate in the jth problem.
'F' denotes that the problem was solved completely, 'P' denotes partial solve, and 'U' denotes that the problem was not solved by the candidate.
Output:
For each test case, print a single line containing N integers. The ith integer denotes the result of the ith candidate. 1 denotes that the candidate passed the test, while 0 denotes that he/she failed the test.
Constraints
1≤T≤100
1≤N≤100
2≤M≤100
1≤X,Y≤M
1≤(X−1)+Y≤M
*/
package main
import (
"bytes"
"fmt"
)
func main() {
test([]string{
"FUFFP",
"PFPFU",
"UPFFU",
"PPPFP",
}, 3, 2, "1100")
test([]string{
"PUPP",
"UUUU",
"UFUU",
}, 1, 3, "101")
test([]string{
"PPP",
}, 2, 2, "0")
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(s []string, x, y int, r string) {
p := candidates(s, x, y)
fmt.Println(p)
assert(p == r)
}
func candidates(s []string, x, y int) string {
w := new(bytes.Buffer)
for i := range s {
f, p := 0, 0
for j := range s[i] {
switch s[i][j] {
case 'F':
f++
case 'P':
p++
}
}
if f >= x || (f == x-1 && p >= y) {
w.WriteByte('1')
} else {
w.WriteByte('0')
}
}
return w.String()
}
|
package rpn
import (
"unicode"
)
func splitExpression(expression string) (result []string) {
var token string
for _, char := range expression {
if _, ok := operations[char]; ok || !unicode.IsNumber(char) {
if len(token) > 0 {
result = append(result, token)
}
if !unicode.IsSpace(char) {
result = append(result, string(char))
}
token = ""
} else {
token += string(char)
}
}
if len(token) > 0 {
result = append(result, token)
}
return
}
|
package board
type Player struct {
TotalMoney int
Hands Hands
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//139. Word Break
//Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
//Note:
//The same word in the dictionary may be reused multiple times in the segmentation.
//You may assume the dictionary does not contain duplicate words.
//Example 1:
//Input: s = "leetcode", wordDict = ["leet", "code"]
//Output: true
//Explanation: Return true because "leetcode" can be segmented as "leet code".
//Example 2:
//Input: s = "applepenapple", wordDict = ["apple", "pen"]
//Output: true
//Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
// Note that you are allowed to reuse a dictionary word.
//Example 3:
//Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
//Output: false
//func wordBreak(s string, wordDict []string) bool {
//}
// Time Is Money |
package main
import (
"gopkg.in/mgo.v2"
"fmt"
"gopkg.in/mgo.v2/bson"
"strings"
"encoding/json"
)
var jobs chan NewUserRecord
var done chan bool
var counter int64
var activeCounter int64
var inactiveCounter int64
var c1 *mgo.Collection
var c *mgo.Collection
func main(){
jobs = make(chan NewUserRecord, 10000)
//done = make(chan bool, 1)
session1, err1 := mgo.Dial("10.15.0.145")
if err1 != nil {
panic(err1)
}
defer session1.Close()
c1 = session1.DB("userlist").C("newuserdata")
session, err := mgo.Dial("10.15.0.75")
if err != nil {
panic(err)
}
defer session.Close()
c = session.DB("userdb").C("users")
var result bson.M
for w := 1; w <= 500; w++ {
go workerPool()
}
find := c.Find(bson.M{})
items := find.Iter()
for items.Next(&result) {
var resultRecord NewUserRecord
jsonResp, _ := json.Marshal(result)
json.Unmarshal(jsonResp, &resultRecord)
jobs <- resultRecord
activeCounter++
}
<-done
}
func workerPool() {
for (true) {
select {
case result, ok := <-jobs:
if ok {
if result.Status == 0 && len(result.Msisdn) > 0 {
var userdata UserInfo
if len(result.Devices) > 0 {
userdata.UserData.Msisdn = result.Msisdn[0]
if result.Devices[0].Token != "" && result.RewardToken != "" {
userdata.UserData.UID = strings.Split(result.RewardToken, ":")[0]
userdata.UserData.Token = result.Devices[0].Token
userdata.Flag = false
userdata.Active = true
err := c1.Insert(userdata)
fmt.Println(err)
counter++
fmt.Println("Total Active User records --- >", counter)
}
}
}
fmt.Println("Total Crawled User records --- >", activeCounter)
}
case <-done:
done <- true
}
}
}
type UserRecord struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Addressbook struct{} `json:"addressbook"`
BackupToken string `json:"backup_token"`
Connect int `json:"connect"`
Country string `json:"country"`
Devices []DeviceDetails `json:"devices"`
Gender string `json:"gender"`
Icon string `json:"icon"`
InvitedJoined []interface{} `json:"invited_joined"`
Invitetoken string `json:"invitetoken"`
Locale string `json:"locale"`
Msisdn []string `json:"msisdn"`
Name string `json:"name"`
PaUID string `json:"pa_uid"`
Referredby []string `json:"referredby"`
RewardToken string `json:"reward_token"`
Status int `json:"status"`
Sus int `json:"sus"`
Uls int `json:"uls"`
Version int `json:"version"`
}
type DeviceDetails struct {
Sound string `json:"sound"`
DevID string `json:"dev_id"`
RegTime int `json:"reg_time"`
Preview bool `json:"preview"`
Staging bool `json:"staging"`
Os string `json:"os"`
DevToken string `json:"dev_token"`
DevVersion string `json:"dev_version"`
Msisdn string `json:"msisdn"`
UpgradeTime int `json:"upgrade_time"`
Pdm string `json:"pdm"`
DevType string `json:"dev_type"`
Token string `json:"token"`
OsVersion string `json:"os_version"`
Resolution string `json:"resolution"`
DeviceKey interface{} `json:"device_key"`
LastActivityTime int `json:"last_activity_time"`
AppVersion string `json:"app_version"`
DevTokenUpdateTs int `json:"dev_token_update_ts"`
}
type UserInfo struct {
ID bson.ObjectId `bson:"_id,omitempty"`
UserData UserData `json:"UserData"`
Flag bool `json:"flag"`
Active bool `json:"active"`
}
//type UserData struct {
// Msisdn string `json:"msisdn"`
// Token string `json:"token"`
// UID string `json:"uid"`
//}
type UserData struct {
Msisdn string `json:"msisdn"`
Token string `json:"token"`
UID string `json:"uid"`
Platformuid string `json:"platformuid"`
Platformtoken string `json:"platformtoken"`
}
type NewUserRecord struct {
ID string `json:"_id"`
Msisdn []string `json:"msisdn"`
Country string `json:"country"`
Devices []struct {
DevID string `json:"dev_id"`
RegTime int `json:"reg_time"`
DevTokenUpdateTs int `json:"dev_token_update_ts"`
DevToken string `json:"dev_token"`
DevVersion string `json:"dev_version"`
Msisdn string `json:"msisdn"`
Resolution string `json:"resolution"`
Token string `json:"token"`
PhL string `json:"ph_l"`
DevType string `json:"dev_type"`
Pdm string `json:"pdm"`
OsVersion string `json:"os_version"`
DeviceKey string `json:"device_key"`
LastActivityTime int `json:"last_activity_time"`
AppVersion string `json:"app_version"`
Os string `json:"os"`
ApL string `json:"ap_l"`
} `json:"devices"`
Rewards4 struct {
Tt int `json:"tt"`
Total int `json:"total"`
} `json:"rewards4"`
RewardToken string `json:"reward_token"`
BackupToken string `json:"backup_token"`
Gender string `json:"gender"`
Name string `json:"name"`
Invitetoken string `json:"invitetoken"`
Md struct {
UID string `json:"uid"`
} `json:"md"`
Locale string `json:"locale"`
PaUID string `json:"pa_uid"`
Addressbook struct {
} `json:"addressbook"`
InvitedJoined []interface{} `json:"invited_joined"`
Sus int `json:"sus"`
Setting string `json:"setting"`
Uls int `json:"uls"`
Lastseen bool `json:"lastseen"`
Avatar int `json:"avatar"`
Status int `json:"status"`
Dob struct {
Year int `json:"year"`
Day int `json:"day"`
Month int `json:"month"`
} `json:"dob"`
Connect int `json:"connect"`
Version int `json:"version"`
S3 string `json:"s3"`
Icon string `json:"icon"`
TnKey string `json:"tn_key"`
}
|
package conn
import "database/sql"
import "fmt"
import "time"
import _ "github.com/bmizerany/pq"
type PgSql struct {
db *sql.DB
result *sql.Result
rows *sql.Rows
}
func GetPgSql() *PgSql {
var pg *PgSql
if pg == nil {
globalDB, err := sql.Open("postgres", "")
if err != nil {
fmt.Println(err.Error())
}
globalDB.SetMaxOpenConns(2000)
globalDB.SetMaxIdleConns(1000)
globalDB.SetConnMaxLifetime(time.Duration(time.Second * 64))
pg = &PgSql{
db: globalDB,
}
}
return pg
}
func (pg *PgSql) Insert(sql string, params ...interface{}) sql.Result {
stmt, err := pg.db.Prepare(sql)
if err != nil {
fmt.Println(err.Error())
return nil
}
res, err := stmt.Exec(params...)
if err != nil {
fmt.Println(err.Error())
return nil
}
return res
}
func (pg *PgSql) Update(sql string, params ...interface{}) sql.Result {
stmt, err := pg.db.Prepare(sql)
if err != nil {
fmt.Println(err.Error())
return nil
}
res, err := stmt.Exec(params...)
if err != nil {
fmt.Println(err.Error())
return nil
}
return res
}
func (pg *PgSql) Query(sql string, params ...interface{}) *sql.Rows {
db := pg.db
rows, err := db.Query(sql, params...)
fmt.Println(rows)
if err != nil {
fmt.Println(err.Error())
return nil
}
pg.rows = rows
return rows
}
func (pg *PgSql) Close() {
if pg.db != nil {
pg.db.Close()
}
}
|
package _268_Missing_Number
func missingNumber(nums []int) int {
// return missingNumberWithAdd(nums)
return missingNumberWithXor(nums)
}
func missingNumberWithAdd(nums []int) int {
var (
rightSum int
realSum int
)
rightSum = len(nums) * (len(nums) + 1) / 2
for _, n := range nums {
realSum += n
}
return rightSum - realSum
}
func missingNumberWithXor(nums []int) int {
var ret = len(nums)
for i, n := range nums {
ret ^= n
ret ^= i
}
return ret
}
|
package logic
import (
"context"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type GetOtherConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetOtherConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) GetOtherConfigLogic {
return GetOtherConfigLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetOtherConfigLogic) GetOtherConfig() (*types.GetOtherConfigResponse, error) {
payTradeTypeSlice, err := model.NewGlobalConfigModel(l.svcCtx.DbEngine).FindValueByKey(model.ConfigPayTradeTypeSlice)
if err != nil {
logx.Errorf("查询代收交易类型出错,key:%v, err:%v", model.ConfigPayTradeTypeSlice, err)
return nil, common.NewCodeError(common.SysDBGet)
}
transferTradeTypeSlice, err := model.NewGlobalConfigModel(l.svcCtx.DbEngine).FindValueByKey(model.ConfigTransferTradeTypeSlice)
if err != nil {
logx.Errorf("查询代付交易类型出错,key:%v, err:%v", model.ConfigTransferTradeTypeSlice, err)
return nil, common.NewCodeError(common.SysDBGet)
}
return &types.GetOtherConfigResponse{
PayTradeTypeSlice: payTradeTypeSlice,
TransferTradeTypeSlice: transferTradeTypeSlice,
}, nil
}
|
/*
Input
A list of nonnegative integers.
Output
The largest nonnegative integer h such that at least h of the numbers in the list are greater than or equal to h.
Test Cases
[0,0,0,0] -> 0
[12,312,33,12] -> 4
[1,2,3,4,5,6,7] -> 4
[22,33,1,2,4] -> 3
[1000,2,2,2] -> 2
[23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] -> 20
Rules
You can write either a full program or a function, and anonymous functions are allowed too. This is code-golf, so the fewest byte count wins. Standard loopholes are disallowed.
Background
The h-index is a notion used in academia which aims to capture the impact and productivity of a researcher.
According to Wikipedia, a researcher has index h, if he or she has published h scientific articles, each of which has been cited in other articles at least h times.
Thus, this challenge is about computing the h-index from a list of citation counts.
*/
package main
import (
"sort"
)
func main() {
assert(hindex([]int{0, 0, 0, 0}) == 0)
assert(hindex([]int{12, 312, 33, 12}) == 4)
assert(hindex([]int{1, 2, 3, 4, 5, 6, 7}) == 4)
assert(hindex([]int{22, 33, 1, 2, 4}) == 3)
assert(hindex([]int{1000, 2, 2, 2}) == 2)
assert(hindex([]int{23, 42, 12, 92, 39, 46, 23, 56, 31, 12, 43, 23, 54, 23, 56, 73, 35, 73, 42, 12, 10, 15, 35, 23, 12, 42}) == 20)
assert(hindex([]int{3, 0, 6, 1, 5}) == 3)
assert(hindex([]int{0}) == 0)
assert(hindex([]int{1}) == 1)
assert(hindex([]int{1, 2, 2}) == 2)
assert(hindex([]int{2, 2}) == 2)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func hindex(a []int) int {
h := 0
sort.Slice(a, func(i, j int) bool { return a[i] > a[j] })
sort.Search(len(a), func(i int) bool {
b := a[i] >= i+1
if b {
h = i + 1
}
return !b
})
return h
}
|
package notifier
import (
"fmt"
multierror "github.com/hashicorp/go-multierror"
"github.com/nlopes/slack"
)
// SlackAPIClient describes the methods we use on slack.Client
type SlackAPIClient interface {
PostMessage(channel, text string, params slack.PostMessageParameters) (string, string, error)
}
// SlackBackend is an object that uses API to send notifications to Users and Channels
type SlackBackend struct {
Username, IconURL string
API SlackAPIClient
Users, Channels []string
}
var _ Backend = &SlackBackend{}
// Send broadcasts n to all configured users/channels
func (sb *SlackBackend) Send(n Notification) error {
p, err := sb.render(n)
if err != nil || p == nil {
return fmt.Errorf("error rendering notification: %w", err)
}
p.Username = sb.Username
p.IconURL = sb.IconURL
var merr *multierror.Error
for _, c := range sb.Channels {
if len(c) > 0 {
_, _, err = sb.API.PostMessage(c, p.Text, *p)
if err != nil {
merr = multierror.Append(merr, err)
}
}
}
for _, u := range sb.Users {
if len(u) > 0 {
_, _, err = sb.API.PostMessage("@"+u, p.Text, *p)
if err != nil {
merr = multierror.Append(merr, err)
}
}
}
return merr.ErrorOrNil()
}
func (sb *SlackBackend) render(n Notification) (*slack.PostMessageParameters, error) {
rn, err := n.Template.Render(n.Data)
if err != nil {
return nil, fmt.Errorf("error rendering template: %w", err)
}
out := &slack.PostMessageParameters{Text: rn.Title, Attachments: make([]slack.Attachment, len(rn.Sections))}
for i, s := range rn.Sections {
if s.Title == "" {
s.Title = "<empty>"
}
if s.Text == "" {
s.Text = "<empty>"
}
out.Attachments[i].Title = s.Title
out.Attachments[i].Text = s.Text
out.Attachments[i].Color = s.Style
}
return out, nil
}
|
package core
import (
"sync"
"time"
)
func InStrList(value string, list []string) bool {
for _, item := range list {
if value == item {
return true
}
}
return false
}
func Retry(retries uint, f func() error) error {
err := f()
if err == nil {
return nil
}
if retries == 0 {
return err
}
return Retry(retries-1, f)
}
func CallWithTimeout(dur time.Duration, f func() error) (error, bool) {
var err error
doneCh := make(chan struct{})
go func() {
err = f()
doneCh <- struct{}{}
}()
select {
case <-doneCh:
break
case <-time.After(dur):
return nil, false
}
return err, true
}
func pluginManagersToInterfaces(items []PluginManager) []interface{} {
if items == nil {
return []interface{}(nil)
}
output := make([]interface{}, len(items))
for idx, item := range items {
output[idx] = item
}
return output
}
func CallWith(items []interface{}, f func(i interface{}) error) error {
if items == nil {
return nil
}
errs := NewMultiError()
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(item interface{}) {
defer wg.Done()
if err := f(item); err != nil {
errs.Add(err)
}
}(item)
}
wg.Wait()
return errs.ToErr()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.