text stringlengths 11 4.05M |
|---|
package main
/*
Pensar em semaforo com sua sinalização sendo flags
É uma alternativa ao waitGroup
*/
import (
"fmt"
)
func main() {
// dois channels
channel := make(chan int)
ok := make(chan bool) // flag
// sempre que puder channel recebe um valor
go func() {
for i := 0; i < 10; i++ {
channel <- i
}
// flag
ok <- true
}()
// func duplicata
go func() {
for i := 0; i < 10; i++ {
channel <- i
}
// flag
ok <- true
}()
go func() {
// vai apagar ok duas vezes antes de fechar o channel
// flags antes de encerrar channel
<-ok
<-ok
close(channel)
}()
// vai lendo enquanto existir valor em channel
// retira o valor sempre que é lido
for number := range channel {
fmt.Println(number)
}
}
|
// +build mysql
package main
import (
"database/sql"
"fmt"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
)
const MYSQL_DATE_FORMAT = "2006-01-02 15:04:05"
func (scsdb *SCSDB) GetDBType() string {
return "MySQL"
}
func (scsdb *SCSDB) init() error {
mysqlhost := os.Getenv("SCS_MYSQL_HOST") //SCS_MYSQL_HOST
mysqluser := os.Getenv("SCS_MYSQL_USER") //SCS_MYSQL_USER
mysqlpass := os.Getenv("SCS_MYSQL_PASS") //SCS_MYSQL_PASS
mysqldb := os.Getenv("SCS_MYSQL_DB") //SCS_MYSQL_DB
log.Infof("HOST: %s", mysqlhost)
log.Debugf("Connecting to DB %s@tcp(%s)/%s?charset=utf8&collation=utf8_general_ci&loc=Europe%%2FRome",
mysqluser, mysqlhost, mysqldb)
db, err := sql.Open("mysql",
fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&collation=utf8_general_ci&loc=Europe%%2FRome",
mysqluser, mysqlpass, mysqlhost, mysqldb))
if err != nil {
log.Errorf("Database connection init error: %s", err.Error())
os.Exit(-2)
}
err = db.Ping()
if err != nil {
log.Errorf("Database connection error: %s", err.Error())
os.Exit(-2)
}
log.Info("MySQL server connected")
db.SetConnMaxLifetime(10 * time.Second)
db.SetMaxIdleConns(0)
scsdb.conn = db
return nil
}
func (db *SCSDB) Close() {
db.conn.Close()
}
func (db *SCSDB) newSequence(dev SeismoCloudSensor, tsstart time.Time) error {
loc, _ := time.LoadLocation("Europe/Rome")
tsstart = tsstart.In(loc)
return db.ForcedStatement(
"INSERT INTO sequenze (deviceid, tsstart, lat, lon, `date`) VALUES (?, ?, ?, ?, ?)",
dev.DeviceId, tsstart.Unix()*1000, dev.Lat, dev.Lng, tsstart.Format(MYSQL_DATE_FORMAT),
)
}
func (db *SCSDB) createDevice(dev SeismoCloudSensor) error {
loc, _ := time.LoadLocation("Europe/Rome")
lastact := dev.LastActivity.In(loc)
return db.ForcedStatement(
"INSERT INTO devices (deviceid, model, version, lastactivity, lat, lon, batteryon, regdate) "+
"VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
dev.DeviceId,
dev.Model,
dev.Version,
lastact.Format(MYSQL_DATE_FORMAT),
dev.Lat,
dev.Lng,
dev.BatteryOn,
)
}
func (db *SCSDB) updateModelVersion(dev SeismoCloudSensor) error {
return db.ForcedStatement(
"UPDATE devices SET model=?, version=? WHERE deviceid=?",
dev.Model,
dev.Version,
dev.DeviceId,
)
}
func (db *SCSDB) setDeviceLastActivity(deviceid string, lastactivity *time.Time, batteryon uint32,
aliveincrement int32) error {
loc, _ := time.LoadLocation("Europe/Rome")
if lastactivity != nil {
lastact := lastactivity.In(loc)
return db.ForcedStatement("UPDATE devices SET lastactivity=?,batteryon=?,alivetime=alivetime+? WHERE deviceid=?",
lastact.Format(MYSQL_DATE_FORMAT), batteryon, aliveincrement, deviceid)
} else {
return db.ForcedStatement("UPDATE devices SET lastactivity=NULL,batteryon=?,alivetime=alivetime+? WHERE deviceid=?",
batteryon, aliveincrement, deviceid)
}
}
func (db *SCSDB) getDevice(deviceid string) (*SeismoCloudSensor, error) {
ret := SeismoCloudSensor{
DeviceId: deviceid,
}
var lastactivity sql.NullString
err := db.ForcedQueryRowWithOneParameter(
"SELECT sigma, lat, lon, version, model, lastactivity FROM devices WHERE deviceid = ?",
deviceid,
&ret.Sigma, &ret.Lat, &ret.Lng, &ret.Version, &ret.Model, &lastactivity,
)
if err == sql.ErrNoRows {
return nil, nil
} else if err != nil {
return nil, err
} else {
if lastactivity.Valid {
loc, _ := time.LoadLocation("Europe/Rome")
lastact, _ := time.ParseInLocation(MYSQL_DATE_FORMAT, lastactivity.String, loc)
ret.LastActivity = &lastact
} else {
ret.LastActivity = nil
}
return &ret, nil
}
}
func (db *SCSDB) getConfig(deviceid string) (sigma float32, server string, path string,
trace bool, err error) {
err = db.ForcedQueryRowWithOneParameter("SELECT sigma, trace FROM devices WHERE deviceid = ?", deviceid,
&sigma, &trace)
if err != nil {
return 0, "", "", false, err
}
return sigma, "", "", trace, nil
}
func (db *SCSDB) addAliveSlot(dev *SeismoCloudSensor, batteryoff uint32, reason string) (int32, error) {
alivetime := int32(time.Now().Unix() - dev.LastActivity.Unix())
if alivetime > 900 {
alivetime = 900
} else if alivetime < 0 {
// TODO: does make sense??
log.Warningf("[%s] Alive time is negative... %d - %d = %d", dev.DeviceId, time.Now().Unix(),
dev.LastActivity.Unix(), alivetime)
alivetime = 0
}
loc, _ := time.LoadLocation("Europe/Rome")
lastact := dev.LastActivity.In(loc)
curtime := time.Now().In(loc)
return alivetime, db.ForcedStatement(
"INSERT INTO devlog (deviceid, lat, lon, ip, `on`, off, alivetime, batteryon, batteryoff, reason) "+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
dev.DeviceId, dev.Lat, dev.Lng, "", lastact.Format(MYSQL_DATE_FORMAT), curtime.Format(MYSQL_DATE_FORMAT), alivetime, dev.BatteryOn,
batteryoff, reason,
)
}
func (db *SCSDB) updateDevicePosition(deviceid string, lat float32, lng float32) error {
return db.ForcedStatement("UPDATE devices SET lat=?,lon=? WHERE deviceid=?", lat, lng, deviceid)
}
|
package tmp
const ModTmp = `module {{print .ModuleName}}
go {{print .GoVersion}}
require (
github.com/0LuigiCode0/logger v0.0.1 {{if isOneMQTT}}
github.com/eclipse/paho.mqtt.golang v1.3.4 // indirect {{end}} {{if isOneWS}}
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.0.4 // indirect {{end}} {{if isOneTCP}}
github.com/gorilla/handlers v1.5.1 // indirect
github.com/gorilla/mux v1.8.0 {{end}} {{if isOnePostgres}}
github.com/lib/pq v1.10.1 {{end}} {{if isOneMongo}}
go.mongodb.org/mongo-driver v1.5.1 {{end}}
)`
|
package resources
import (
"errors"
"net/http"
"github.com/manyminds/api2go"
"gopkg.in/mgo.v2/bson"
"themis/utils"
"themis/models"
"themis/database"
)
// UserResource for api2go routes.
type UserResource struct {
UserStorage *database.UserStorage
SpaceStorage *database.SpaceStorage
WorkItemStorage *database.WorkItemStorage
}
func (c UserResource) getFilterFromRequest(r api2go.Request) (bson.M, error) {
var filter bson.M
// Getting reference context
// TODO: find a more elegant way, maybe using function literals.
sourceContext, sourceContextID, thisContext := utils.ParseContext(r)
switch sourceContext {
case models.SpaceName:
space, err := c.SpaceStorage.GetOne(bson.ObjectIdHex(sourceContextID))
if (err != nil) {
return nil, err
}
if thisContext == "owned-by" {
filter = bson.M{"_id": space.OwnerID}
}
if thisContext == "collaborators" {
filter = bson.M{"_id": bson.M{"$in":space.CollaboratorIDs}}
}
case models.WorkItemName:
workItem, err := c.WorkItemStorage.GetOne(bson.ObjectIdHex(sourceContextID))
if (err != nil) {
return nil, err
}
if thisContext == "creator" {
filter = bson.M{"_id": workItem.CreatorID}
}
if thisContext == "assignees" {
filter = bson.M{"_id": bson.M{"$in":workItem.Assignees}}
}
default:
// build standard filter expression
filter = utils.BuildDbFilterFromRequest(r)
}
return filter, nil
}
// FindAll Users.
func (c UserResource) FindAll(r api2go.Request) (api2go.Responder, error) {
// get filter expression
filter, err := c.getFilterFromRequest(r)
if err != nil {
return api2go.Response{}, err
}
// do query
users, err := c.UserStorage.GetAll(filter)
if err != nil {
return api2go.Response{}, err
}
return &api2go.Response{Res: users}, nil
}
// PaginatedFindAll can be used to load users in chunks.
// Possible success status code 200.
func (c UserResource) PaginatedFindAll(r api2go.Request) (uint, api2go.Responder, error) {
// get filter expression
filter, err := c.getFilterFromRequest(r)
if err != nil {
return 0, api2go.Response{}, err
}
// parse out offset and limit
queryOffset, queryLimit, err := utils.ParsePaging(r)
if err!=nil {
return 0, &api2go.Response{}, err
}
// get the paged data from storage
result, err := c.UserStorage.GetAllPaged(filter, queryOffset, queryLimit)
if err!=nil {
return 0, &api2go.Response{}, err
}
// get total count for paging
allCount, err := c.UserStorage.GetAllCount(filter)
if err!=nil {
return 0, &api2go.Response{}, err
}
// return everything
return uint(allCount), &api2go.Response{Res: result}, nil
}
// FindOne User.
// Possible success status code 200
func (c UserResource) FindOne(id string, r api2go.Request) (api2go.Responder, error) {
utils.DebugLog.Printf("Received FindOne with ID %s.", id)
res, err := c.UserStorage.GetOne(bson.ObjectIdHex(id))
return &api2go.Response{Res: res}, err
}
// Create a new User.
// Possible status codes are:
// - 201 Created: Resource was created and needs to be returned
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Resource created with a client generated ID, and no fields were modified by
// the server
func (c UserResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
user, ok := obj.(models.User)
if !ok {
return &api2go.Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id, _ := c.UserStorage.Insert(user)
user.ID = id
return &api2go.Response{Res: user, Code: http.StatusCreated}, nil
}
// Delete a User.
// Possible status codes are:
// - 200 OK: Deletion was a success, returns meta information, currently not implemented! Do not use this
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Deletion was successful, return nothing
func (c UserResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {
err := c.UserStorage.Delete(bson.ObjectIdHex(id))
return &api2go.Response{Code: http.StatusOK}, err
}
// Update a User.
// Possible status codes are:
// - 200 OK: Update successful, however some field(s) were changed, returns updates source
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Update was successful, no fields were changed by the server, return nothing
func (c UserResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
user, ok := obj.(models.User)
if !ok {
return &api2go.Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := c.UserStorage.Update(user)
return &api2go.Response{Res: user, Code: http.StatusNoContent}, err
}
|
package main
import "fmt"
func main() {
slice := []int{99: 99}
fmt.Println(slice[0])
}
|
package keycloak
import "fmt"
func (keycloakClient *KeycloakClient) GetUserRoleMappings(realmId string, userId string) (*RoleMapping, error) {
var roleMapping *RoleMapping
err := keycloakClient.get(fmt.Sprintf("/realms/%s/users/%s/role-mappings", realmId, userId), &roleMapping, nil)
if err != nil {
return nil, err
}
return roleMapping, nil
}
func (keycloakClient *KeycloakClient) AddRealmRolesToUser(realmId, userId string, roles []*Role) error {
_, _, err := keycloakClient.post(fmt.Sprintf("/realms/%s/users/%s/role-mappings/realm", realmId, userId), roles)
return err
}
func (keycloakClient *KeycloakClient) AddClientRolesToUser(realmId, userId, clientId string, roles []*Role) error {
_, _, err := keycloakClient.post(fmt.Sprintf("/realms/%s/users/%s/role-mappings/clients/%s", realmId, userId, clientId), roles)
return err
}
func (keycloakClient *KeycloakClient) RemoveRealmRolesFromUser(realmId, userId string, roles []*Role) error {
err := keycloakClient.delete(fmt.Sprintf("/realms/%s/users/%s/role-mappings/realm", realmId, userId), roles)
return err
}
func (keycloakClient *KeycloakClient) RemoveClientRolesFromUser(realmId, userId, clientId string, roles []*Role) error {
err := keycloakClient.delete(fmt.Sprintf("/realms/%s/users/%s/role-mappings/clients/%s", realmId, userId, clientId), roles)
return err
}
|
package main
import (
"os"
"text/template"
)
func main() {
//START new OMIT
// Create a new, empty template
tmpl := template.New("hello")
//END new OMIT
//START parse OMIT
// Parse the template code into the new template
tmpl, err := tmpl.Parse(`Hello from {{ . }}`)
// ^ the first returned arg is a pointer to `tmpl` itself
// so this assignment is essentially pointless here
if err != nil {
// NOTE: This error is not reachable in this example
panic(err)
}
//END parse OMIT OMIT
//START execute OMIT
// Execute the template with a simple string as data
err = tmpl.Execute(os.Stdout, "go templates!")
if err != nil {
// NOTE: This error is not reachable in this example
panic(err)
}
//END execute OMIT
}
|
package Core
type Event struct {
EventId int
ComponentName string
MsgBody interface{}
}
func (event Event) GetEventId() int {
return event.EventId
}
func (event Event) GetComponentName() string {
return event.ComponentName
}
func (event Event) GetMsg() interface{} {
return event.MsgBody
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//423. Reconstruct Original Digits from English
//Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.
//Note:
//Input contains only lowercase English letters.
//Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
//Input length is less than 50,000.
//Example 1:
//Input: "owoztneoer"
//Output: "012"
//Example 2:
//Input: "fviefuro"
//Output: "45"
//func originalDigits(s string) string {
//}
// Time Is Money |
// Package solution Reverse Integer of LeetCode.
// Problem:
//
// Given a 32-bit signed integer, reverse digits of an integer.
//
// Example 1:
// Input: 123
// Output: 321
//
// Example 2:
// Input: -123
// Output: -321
//
// Example 3:
// Input: 120
// Output: 21
//
// [Note]:
// Assume we are dealing with an environment whichcould only store integers within
// the 32-bit signed integer range: '[−2^31, 2^31 − 1]'.
// For the purpose of this problem, assume that your function returns 0 when the 'reversed' integer overflows.
package solution
import (
"strconv"
)
func reverseString(s string) string {
rns := []rune(s)
for i, j := 0, len(rns)-1; i < j; i, j = i+1, j-1 {
rns[i], rns[j] = rns[j], rns[i]
}
return string(rns)
}
func outOfRange(x int) bool {
if x > 1<<31-1 || x < -1<<31 {
return true
}
return false
}
// reverse solution here
func reverse(x int) int {
if outOfRange(x) {
return 0
}
xCopy := x
if x < 0 {
xCopy = xCopy * -1
}
result, err := strconv.Atoi(reverseString(strconv.Itoa(xCopy)))
if err != nil {
return 0
}
if x < 0 {
result = result * -1
}
// 2020-08-17 檢查 32-bit signed integer 範圍,不只輸入要檢查,輸出的答案也要檢查(我忘記檢查輸出的範圍,導致錯了三次)。
if outOfRange(result) {
return 0
}
return result
}
// reverseBetter is an improvement of reverse function
func reverseBetter(x int) int {
if outOfRange(x) {
return 0
}
result := 0 // 紀錄反轉過後的數字
for x != 0 {
result = result*10 + x%10 // 利用餘數除法取得最小位數的值,並將之推前一位
x = x / 10 // 去掉算過的位數
}
if outOfRange(result) {
return 0
}
return result
}
// the best
func reverse2(x int) int {
result := 0
for x != 0 {
result = result*10 + x%10
x = x / 10
}
if outOfRange(result) {
return 0
}
return result
}
func getIntLen(x int) int {
vLen := 0
for x != 0 {
x = x / 10
vLen++
}
return vLen
}
func x10(n int) int {
r := 1
for n != 0 {
r *= 10
n--
}
return r
}
func reverse3(x int) int {
vlen := getIntLen(x)
result := 0
for vlen != 0 {
result = result + (x%10)*x10(vlen-1)
x /= 10
vlen--
}
if outOfRange(result) {
return 0
}
return result
}
|
package rpclib
import (
"fmt"
"github.com/zcong1993/telnetor/manager"
)
// AddArgs is rpc args for add addr
type AddArgs struct {
// Addr is watching address
Addr string
// D is telnet interval
D int
}
// DelArgs is rpc args for del addr
type DelArgs struct {
// Addr is remove watching address
Addr string
}
// Reply is rpc reply message type
type Reply struct {
// OK is reply status
OK bool
// Msg is reply message
Msg string
}
// ListReply is rpc reply message type for list method
type ListReply struct {
// List is addrs watching now
List map[string]int
}
// T is rpc struct
type T struct {
m *manager.Manager
}
// NewT is constructor for T
func NewT(m *manager.Manager) *T {
return &T{m: m}
}
// Add is rpc Add method
func (t *T) Add(args *AddArgs, reply *Reply) error {
err := t.m.Add(args.Addr, args.D)
if err != nil {
*reply = Reply{false, err.Error()}
return nil
}
*reply = Reply{true, fmt.Sprintf("add success %s ", args.Addr)}
return nil
}
// Del is rpc Del method
func (t *T) Del(args *AddArgs, reply *Reply) error {
err := t.m.Rm(args.Addr)
if err != nil {
*reply = Reply{false, err.Error()}
return nil
}
*reply = Reply{true, fmt.Sprintf("del success %s ", args.Addr)}
return nil
}
// List is rpc list method, show all active watchers
func (t *T) List(_ *interface{}, reply *ListReply) error {
*reply = ListReply{t.m.List()}
return nil
}
|
package ecc
import (
"math/big"
)
func (E *EccKeyPair) EccDH(q *Point) *big.Int {
key := new(Point)
key.Mul(E.d, q, E.C)
return key.x
}
|
package sql
import (
"time"
)
// Reduce evaluates expr using the available values in valuer.
// References that don't exist in valuer are ignored.
func Reduce(expr Expr, valuer Valuer) Expr {
expr = reduce(expr, valuer)
// Unwrap parens at top level.
if expr, ok := expr.(*ParenExpr); ok {
return expr.Expr
}
return expr
}
func reduce(expr Expr, valuer Valuer) Expr {
if expr == nil {
return nil
}
switch expr := expr.(type) {
case *BinaryExpr:
return reduceBinaryExpr(expr, valuer)
case *Call:
return reduceCall(expr, valuer)
case *ParenExpr:
return reduceParenExpr(expr, valuer)
case *VarRef:
return reduceVarRef(expr, valuer)
default:
return CloneExpr(expr)
}
}
func reduceBinaryExpr(expr *BinaryExpr, valuer Valuer) Expr {
// Reduce both sides first.
op := expr.Op
lhs := reduce(expr.LHS, valuer)
rhs := reduce(expr.RHS, valuer)
// Do not evaluate if one side is nil.
if lhs == nil || rhs == nil {
return &BinaryExpr{LHS: lhs, RHS: rhs, Op: expr.Op}
}
// If we have a logical operator (AND, OR) and one side is a boolean literal
// then we need to have special handling.
if op == AND {
if isFalseLiteral(lhs) || isFalseLiteral(rhs) {
return &BooleanLiteral{Val: false}
} else if isTrueLiteral(lhs) {
return rhs
} else if isTrueLiteral(rhs) {
return lhs
}
} else if op == OR {
if isTrueLiteral(lhs) || isTrueLiteral(rhs) {
return &BooleanLiteral{Val: true}
} else if isFalseLiteral(lhs) {
return rhs
} else if isFalseLiteral(rhs) {
return lhs
}
}
// Evaluate if both sides are simple types.
switch lhs := lhs.(type) {
case *BooleanLiteral:
return reduceBinaryExprBooleanLHS(op, lhs, rhs)
case *DurationLiteral:
return reduceBinaryExprDurationLHS(op, lhs, rhs)
case *nilLiteral:
return reduceBinaryExprNilLHS(op, lhs, rhs)
case *NumberLiteral:
return reduceBinaryExprNumberLHS(op, lhs, rhs)
case *StringLiteral:
return reduceBinaryExprStringLHS(op, lhs, rhs)
case *TimeLiteral:
return reduceBinaryExprTimeLHS(op, lhs, rhs)
default:
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
}
func reduceBinaryExprBooleanLHS(op Token, lhs *BooleanLiteral, rhs Expr) Expr {
switch rhs := rhs.(type) {
case *BooleanLiteral:
switch op {
case EQ:
return &BooleanLiteral{Val: lhs.Val == rhs.Val}
case NEQ:
return &BooleanLiteral{Val: lhs.Val != rhs.Val}
case AND:
return &BooleanLiteral{Val: lhs.Val && rhs.Val}
case OR:
return &BooleanLiteral{Val: lhs.Val || rhs.Val}
}
case *nilLiteral:
return &BooleanLiteral{Val: false}
}
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
func reduceBinaryExprDurationLHS(op Token, lhs *DurationLiteral, rhs Expr) Expr {
switch rhs := rhs.(type) {
case *DurationLiteral:
switch op {
case ADD:
return &DurationLiteral{Val: lhs.Val + rhs.Val}
case SUB:
return &DurationLiteral{Val: lhs.Val - rhs.Val}
case EQ:
return &BooleanLiteral{Val: lhs.Val == rhs.Val}
case NEQ:
return &BooleanLiteral{Val: lhs.Val != rhs.Val}
case GT:
return &BooleanLiteral{Val: lhs.Val > rhs.Val}
case GTE:
return &BooleanLiteral{Val: lhs.Val >= rhs.Val}
case LT:
return &BooleanLiteral{Val: lhs.Val < rhs.Val}
case LTE:
return &BooleanLiteral{Val: lhs.Val <= rhs.Val}
}
case *NumberLiteral:
switch op {
case MUL:
return &DurationLiteral{Val: lhs.Val * time.Duration(rhs.Val)}
case DIV:
if rhs.Val == 0 {
return &DurationLiteral{Val: 0}
}
return &DurationLiteral{Val: lhs.Val / time.Duration(rhs.Val)}
}
case *TimeLiteral:
switch op {
case ADD:
return &TimeLiteral{Val: rhs.Val.Add(lhs.Val)}
}
case *nilLiteral:
return &BooleanLiteral{Val: false}
}
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
func reduceBinaryExprNilLHS(op Token, lhs *nilLiteral, rhs Expr) Expr {
switch op {
case EQ, NEQ:
return &BooleanLiteral{Val: false}
}
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
func reduceBinaryExprNumberLHS(op Token, lhs *NumberLiteral, rhs Expr) Expr {
switch rhs := rhs.(type) {
case *NumberLiteral:
switch op {
case ADD:
return &NumberLiteral{Val: lhs.Val + rhs.Val}
case SUB:
return &NumberLiteral{Val: lhs.Val - rhs.Val}
case MUL:
return &NumberLiteral{Val: lhs.Val * rhs.Val}
case DIV:
if rhs.Val == 0 {
return &NumberLiteral{Val: 0}
}
return &NumberLiteral{Val: lhs.Val / rhs.Val}
case EQ:
return &BooleanLiteral{Val: lhs.Val == rhs.Val}
case NEQ:
return &BooleanLiteral{Val: lhs.Val != rhs.Val}
case GT:
return &BooleanLiteral{Val: lhs.Val > rhs.Val}
case GTE:
return &BooleanLiteral{Val: lhs.Val >= rhs.Val}
case LT:
return &BooleanLiteral{Val: lhs.Val < rhs.Val}
case LTE:
return &BooleanLiteral{Val: lhs.Val <= rhs.Val}
}
case *nilLiteral:
return &BooleanLiteral{Val: false}
}
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
func reduceBinaryExprStringLHS(op Token, lhs *StringLiteral, rhs Expr) Expr {
switch rhs := rhs.(type) {
case *StringLiteral:
switch op {
case EQ:
return &BooleanLiteral{Val: lhs.Val == rhs.Val}
case NEQ:
return &BooleanLiteral{Val: lhs.Val != rhs.Val}
case ADD:
return &StringLiteral{Val: lhs.Val + rhs.Val}
}
case *nilLiteral:
switch op {
case EQ, NEQ:
return &BooleanLiteral{Val: false}
}
}
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
func reduceBinaryExprTimeLHS(op Token, lhs *TimeLiteral, rhs Expr) Expr {
switch rhs := rhs.(type) {
case *DurationLiteral:
switch op {
case ADD:
return &TimeLiteral{Val: lhs.Val.Add(rhs.Val)}
case SUB:
return &TimeLiteral{Val: lhs.Val.Add(-rhs.Val)}
}
case *TimeLiteral:
switch op {
case SUB:
return &DurationLiteral{Val: lhs.Val.Sub(rhs.Val)}
case EQ:
return &BooleanLiteral{Val: lhs.Val.Equal(rhs.Val)}
case NEQ:
return &BooleanLiteral{Val: !lhs.Val.Equal(rhs.Val)}
case GT:
return &BooleanLiteral{Val: lhs.Val.After(rhs.Val)}
case GTE:
return &BooleanLiteral{Val: lhs.Val.After(rhs.Val) || lhs.Val.Equal(rhs.Val)}
case LT:
return &BooleanLiteral{Val: lhs.Val.Before(rhs.Val)}
case LTE:
return &BooleanLiteral{Val: lhs.Val.Before(rhs.Val) || lhs.Val.Equal(rhs.Val)}
}
case *nilLiteral:
return &BooleanLiteral{Val: false}
}
return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
}
func reduceCall(expr *Call, valuer Valuer) Expr {
// Evaluate "now()" if valuer is set.
if expr.Name == "now" && len(expr.Args) == 0 && valuer != nil {
if v, ok := valuer.Value("now()"); ok {
v, _ := v.(time.Time)
return &TimeLiteral{Val: v}
}
}
// Otherwise reduce arguments.
args := make([]Expr, len(expr.Args))
for i, arg := range expr.Args {
args[i] = reduce(arg, valuer)
}
return &Call{Name: expr.Name, Args: args}
}
func reduceParenExpr(expr *ParenExpr, valuer Valuer) Expr {
subexpr := reduce(expr.Expr, valuer)
if subexpr, ok := subexpr.(*BinaryExpr); ok {
return &ParenExpr{Expr: subexpr}
}
return subexpr
}
func reduceVarRef(expr *VarRef, valuer Valuer) Expr {
// Ignore if there is no valuer.
if valuer == nil {
return &VarRef{Val: expr.Val}
}
// Retrieve the value of the ref.
// Ignore if the value doesn't exist.
v, ok := valuer.Value(expr.Val)
if !ok {
return &VarRef{Val: expr.Val}
}
// Return the value as a literal.
switch v := v.(type) {
case bool:
return &BooleanLiteral{Val: v}
case time.Duration:
return &DurationLiteral{Val: v}
case float64:
return &NumberLiteral{Val: v}
case string:
return &StringLiteral{Val: v}
case time.Time:
return &TimeLiteral{Val: v}
default:
return &nilLiteral{}
}
}
|
package geometry
import "math"
type Shape interface {
Area() float64
}
type Rectangle struct {
Length float64
Breadth float64
}
func (r Rectangle) Area() float64 {
return r.Length * r.Breadth
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * math.Pow(c.Radius, 2.0)
}
type Triangle struct {
Base float64
Height float64
}
func (t Triangle) Area() float64 {
return 0.5 * t.Base * t.Height
}
func Perimeter(rectangle Rectangle) float64 {
return 2 * (rectangle.Length + rectangle.Breadth)
}
func Area() float64 {
return 0
}
|
package channels
import (
"context"
"fmt"
"time"
)
// Printer will print anything sent on the ch chan
// and will print tock every 200 milliseconds
// this will repeat forever until a context is
// Done, i.e. timed out or cancelled
func Printer(ctx context.Context, ch chan string) {
t := time.Tick(200 * time.Millisecond)
for {
select {
case <-ctx.Done():
fmt.Println("printer done.")
return
case res := <-ch:
fmt.Println(res)
case <-t:
fmt.Println("tock")
}
}
}
|
/*
Task
Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.
Examples
! → 1
Ciao → 1 1 1 1
tʃaʊ → 1 2 1 2
Adám → 1 1 2 1
ĉaŭ → 2 1 2 (single characters)
ĉaŭ → 1 2 1 1 2 (uses combining overlays)
チャオ → 3 3 3
(empty input) → (empty output)
!±≡𩸽 → 1 2 3 4
� (a null byte) → 1
Null bytes
If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).
If your language cannot handle null bytes at all, you may assume the input does not contain nulls.
*/
package main
import (
"fmt"
"reflect"
"unicode/utf8"
)
func main() {
test("!", []int{1})
test("Ciao", []int{1, 1, 1, 1})
test("tʃaʊ", []int{1, 2, 1, 2})
test("Adám", []int{1, 1, 2, 1})
test("ĉaŭ", []int{2, 1, 2})
test("ĉaŭ", []int{1, 2, 1, 1, 2})
test("チャオ", []int{3, 3, 3})
test("", []int{})
test("!±≡𩸽", []int{1, 2, 3, 4})
test("\x00", []int{1})
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(s string, r []int) {
p := width(s)
fmt.Println(s, p, r)
assert(reflect.DeepEqual(p, r))
}
func width(s string) []int {
p := []int{}
for {
_, w := utf8.DecodeRuneInString(s)
if w == 0 {
break
}
p, s = append(p, w), s[w:]
}
return p
}
|
package main
import (
"code.google.com/p/go.exp/fsnotify"
"code.google.com/p/go.net/websocket"
"encoding/json"
"log"
"time"
)
type Event struct {
Path string `json:"path"`
Done chan error `json:"-"`
}
// 監視ディレクトリひとつを表す
type Entry struct {
w *fsnotify.Watcher
dir string
clients []chan *Event
Subscribed chan chan *Event
rule *Rule
}
func NewEntry(dir string, rule *Rule) (*Entry, error) {
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
if err := w.Watch(dir); err != nil {
return nil, err
}
return &Entry{
w: w,
dir: dir,
clients: make([]chan *Event, 0, 10),
Subscribed: make(chan chan *Event),
rule: rule,
}, nil
}
func (entry *Entry) eventLoop() {
que := make(map[string]*fsnotify.FileEvent)
for {
select {
case c := <-entry.Subscribed:
entry.addClient(c)
case ev := <-entry.w.Event:
if ev.IsDelete() {
continue
}
que[ev.Name] = ev
case err := <-entry.w.Error:
log.Fatal(err)
case <-time.After(100 * time.Millisecond):
for key, ev := range que {
entry.notifyAll(ev.Name)
delete(que, key)
}
}
}
}
func (entry *Entry) addClient(nc chan *Event) {
for i, c := range entry.clients {
// websocketの通信でエラーになった場合は、
// notifyAll()がnilにしているので再利用する。
if c == nil {
entry.clients[i] = nc
return
}
}
entry.clients = append(entry.clients, nc)
}
func (entry *Entry) notifyAll(file string) {
target, err := entry.rule.Eval(file)
if err == ErrNotCovered {
// 監視対象外なので何もしない
return
}
if err != nil {
log.Printf("Eval(%v) = %v", file, err)
return
}
for i, c := range entry.clients {
if c == nil {
continue
}
event := &Event{target, make(chan error)}
c <- event
if err := <-event.Done; err != nil {
log.Print(err)
entry.clients[i] = nil
}
}
}
func (entry *Entry) Serve(ws *websocket.Conn) {
c := make(chan *Event, 1)
entry.Subscribed <- c
fout := json.NewEncoder(ws)
for ev := range c {
log.Print(ev)
if err := fout.Encode(ev); err != nil {
ev.Done <- err
break
}
ev.Done <- nil
}
}
|
package server
import (
"github.com/GoACK/Service/config"
"github.com/GoACK/Service/controller"
)
// Package packs the initialized packages into a single pack so we can pass it around the other packages.
type Package struct {
Config config.Config
Controller controller.Controller
}
// Pack the initialized packages.
func Pack(c config.Config, ctrl controller.Controller) Package {
return Package{Config: c, Controller: ctrl}
}
func Register() {
}
|
package main
import (
"fmt"
"sync"
)
func Distance(s, t string,wg *sync.WaitGroup) int {
var (
n = len(s)
m = len(t)
)
switch {
case n == 0:
return m
case m == 0:
return n
}
d := buildMatrix(n, m)
defer wg.Done()
for i := 1; i <= n; i++ {
for j := 1; j <= m; j++ {
cost := 0
if s[i-1] != t[j-1] {
cost = 1
}
d[j][i] = minimum(d[j-1][i]+1, d[j][i-1]+1, d[j-1][i-1]+cost)
}
}
return d[m][n]
}
// helper function to build a matrix
func buildMatrix(n, m int) [][]int {
matrix := make([][]int, m+1)
for i := 0; i <= m; i++ {
matrix[i] = append(matrix[i], make([]int, n+1)...)
matrix[i][0] = i
}
for i := 0; i <= n; i++ {
matrix[0][i] = i
}
return matrix
}
// helper function to determine the minimum among 3 integers
func minimum(a, b, c int) int {
switch {
case a < b && a < c:
return a
case b < a && b < c:
return b
}
return c
}
func main() {
// create two example strings, calculate the edit distance between them
//fmt.Print("Enter text: ")
var wg sync.WaitGroup
var str1 string
var str2 string
fmt.Scanln(&str1)
fmt.Scanln(&str2)
wg.Add(1);
fmt.Println(Distance(str1, str2,&wg))
}
|
package main
import (
"flag"
"fmt"
"github.com/Mindslave/skade/backend/internal/engine"
"github.com/Mindslave/skade/backend/internal/log/zap"
)
func main() {
var logger engine.Logger
//there is only zap at the moment, but there might be more in the future
loggerType := "zap"
switch loggerType {
case "zap":
//engine.logger is now a zaplogger
logger = zaplogger.NewEngineZapLogger()
default:
panic("no logger")
}
fmt.Println(logger)
//engine := engine.NewAnalysisService(logger)
//fileName := flag.String("File", "", "Name of the suspicious file")
//flag.Parse()
//engine.Scan(*fileName)
}
|
package main
import (
"bufio"
"io"
"log"
"net"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
const (
// LogFlag 控制日志的前缀
LogFlag = log.LstdFlags | log.Lmicroseconds | log.Lshortfile
// MaxConnectionNum 表示最大连接数
MaxConnectionNum = 10000
)
var (
errLogger = log.New(os.Stderr, "ERROR ", LogFlag)
infoLogger = log.New(os.Stdout, "INFO ", LogFlag)
)
func main() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM)
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("net.Listen failed, error: %s.", err)
}
infoLogger.Printf("net.Listen() %s...", ":8080")
throttle := make(chan struct{}, MaxConnectionNum)
var wg sync.WaitGroup
running := true
for running {
conn, err := ln.Accept()
if err != nil {
errLogger.Printf("ln.Accept failed, error: %s.", err)
} else {
infoLogger.Printf("Accept a connection, RemoteAddr: %s.", conn.RemoteAddr())
wg.Add(1)
throttle <- struct{}{}
go func(conn net.Conn) {
defer wg.Done()
handle(conn, quit, throttle)
}(conn)
}
select {
case signal := <-quit:
infoLogger.Printf("Receive a signal: %d, and I will shutdown gracefully...", signal)
running = false
default:
infoLogger.Printf("Ready for another connection.")
}
}
wg.Wait()
infoLogger.Print("Shutdown gracefully.")
}
func handle(conn io.ReadWriteCloser, quit chan os.Signal, throttle <-chan struct{}) {
defer func() {
if err := conn.Close(); err != nil {
errLogger.Printf("conn.Close() failed, error: %s.", err)
}
}()
buf := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
running := true
for running {
s, err := buf.ReadString('\n')
if err != nil {
errLogger.Printf("buf.ReadString() failed, error: %s.", err)
running = false
}
infoLogger.Printf("Read a message: %s.", strings.TrimSpace(s))
n, err := buf.WriteString(s)
if err != nil {
errLogger.Printf("buf.WriteString() failed, error: %s.", err)
running = false
}
if err = buf.Flush(); err != nil {
errLogger.Printf("buf.Flush() failed, error: %s.", err)
running = false
}
infoLogger.Printf("Write a response: %s, length: %d bytes.", strings.TrimSpace(s), n)
select {
case signal := <-quit:
infoLogger.Printf("Receive a signal: %d, and I will shutdown gracefully...", signal)
running = false
quit <- signal
default:
infoLogger.Printf("Ready for another message.")
}
}
<-throttle
}
|
package day4_2018
import (
loader "aoc/dataloader"
"aoc/test"
"testing"
)
func TestPart1(t *testing.T) {
cases := []test.Case[[]string, int]{
{loader.Load("test_input.txt"), 240},
{loader.Load("input.txt"), 39584},
}
err := test.Execute(cases, Part1)
if err != nil {
t.Error(err)
}
}
func TestPart2(t *testing.T) {
cases := []test.Case[[]string, int]{
{loader.Load("test_input.txt"), 4455},
{loader.Load("input.txt"), 55053},
}
err := test.Execute(cases, Part2)
if err != nil {
t.Error(err)
}
}
|
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/urbanairship/go-iapclient"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
cid = kingpin.Flag("client-id", "OAuth Client ID").Required().String()
uri = kingpin.Flag("uri", "URI to get").Required().String()
caFile = kingpin.Flag("ca-file", "Custom CA PEM file").Required().ExistingFile()
)
func getCustomTransport() (transport *http.Transport, err error) {
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
pemData, err := ioutil.ReadFile(*caFile)
if err != nil {
return nil, err
}
ok := rootCAs.AppendCertsFromPEM(pemData)
if !ok {
return nil, err
}
tlsConfig := &tls.Config{RootCAs: rootCAs}
return &http.Transport{TLSClientConfig: tlsConfig}, nil
}
func main() {
kingpin.Parse()
req, err := http.NewRequest("GET", *uri, nil)
if err != nil {
log.Fatalf("Failed create HTTP request: %v", err)
}
// customize the trusted CA list to support talking to prom
transport, err := getCustomTransport()
if err != nil {
log.Fatalf("Couldn't get custom transport: %v", err)
}
iap, err := iapclient.NewIAP(*cid, &iapclient.Config{Transport: transport})
if err != nil {
log.Fatalf("Failed to create new IAP object: %v", err)
}
httpClient := &http.Client{Transport: iap}
resp, err := httpClient.Do(req)
if err != nil {
log.Fatalf("HTTP request failed: %v", err)
}
respBody, _ := ioutil.ReadAll(resp.Body)
msg := fmt.Sprintf("HTTP Request: %v\n%v", resp.Status, string(respBody))
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
log.Printf("Successful %v", msg)
} else {
log.Fatalf("Failed %v", msg)
}
}
|
/**
* @author liangbo
* @email liangbogopher87@gmail.com
* @date 2017/10/11 23:32
*/
package model
// 活动表
type Activity struct {
} |
package trees
import (
"strings"
"github.com/Nv7-Github/Nv7Haven/eod/types"
)
type SizeTree struct {
Size int
dat types.ServerData
added map[string]types.Empty
}
func (s *SizeTree) AddElem(name string, notoplevel ...bool) (bool, string) {
_, exists := s.added[name]
if exists {
return true, ""
}
if len(notoplevel) == 0 {
s.dat.Lock.RLock()
defer s.dat.Lock.RUnlock()
}
el, res := s.dat.GetElement(name, true)
if !res.Exists {
return false, res.Message
}
for _, par := range el.Parents {
suc, msg := s.AddElem(par, true)
if !suc {
return false, msg
}
}
s.added[strings.ToLower(name)] = types.Empty{}
s.Size++
return true, ""
}
func NewSizeTree(dat types.ServerData) *SizeTree {
return &SizeTree{Size: 0, dat: dat, added: make(map[string]types.Empty)}
}
func ElemCreateSize(parents []string, dat types.ServerData) (int, bool, string) {
size := NewSizeTree(dat)
for _, par := range parents {
suc, msg := size.AddElem(par)
if !suc {
return 0, false, msg
}
}
return size.Size + 1, true, ""
}
|
package main
// import (
// "fmt"
// rotatelogs "github.com/lestrrat/go-file-rotatelogs"
// "go.uber.org/zap"
// "go.uber.org/zap/zapcore"
// "io"
// "net/http"
// "time"
// )
// var sugarLogger *zap.SugaredLogger
// func main() {
// fmt.Println("begin main")
// InitLogger()
// defer sugarLogger.Sync()
// simpleHttpGet("www.cnblogs.com")
// simpleHttpGet("https://www.baidu.com")
// }
// //例子,http访问url,返回状态
// func simpleHttpGet(url string) {
// fmt.Println("begin simpleHttpGet:" + url)
// sugarLogger.Debugf("Trying to hit GET request for %s", url)
// resp, err := http.Get(url)
// if err != nil {
// sugarLogger.Errorf("Error fetching URL %s : Error = %s", url, err)
// } else {
// sugarLogger.Infof("Success! statusCode = %s for URL %s", resp.Status, url)
// resp.Body.Close()
// }
// }
// func InitLogger() {
// encoder := getEncoder()
// //两个interface,判断日志等级
// //warnlevel以下归到info日志
// infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
// return lvl < zapcore.WarnLevel
// })
// //warnlevel及以上归到warn日志
// warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
// return lvl >= zapcore.WarnLevel
// })
// infoWriter := getLogWriter("/data/liuhongdi/logs/zaplog2info")
// warnWriter := getLogWriter("/data/liuhongdi/logs/zaplog2warn")
// //创建zap.Core,for logger
// core := zapcore.NewTee(
// zapcore.NewCore(encoder, infoWriter, infoLevel),
// zapcore.NewCore(encoder, warnWriter, warnLevel),
// )
// //生成Logger
// logger := zap.New(core, zap.AddCaller())
// sugarLogger = logger.Sugar()
// }
// //getEncoder
// func getEncoder() zapcore.Encoder {
// encoderConfig := zap.NewProductionEncoderConfig()
// encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
// encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
// return zapcore.NewConsoleEncoder(encoderConfig)
// }
// //得到LogWriter
// func getLogWriter(filePath string) zapcore.WriteSyncer {
// warnIoWriter := getWriter(filePath)
// return zapcore.AddSync(warnIoWriter)
// }
// //日志文件切割
// func getWriter(filename string) io.Writer {
// // 保存日志30天,每24小时分割一次日志
// /*
// hook, err := rotatelogs.New(
// filename+"_%Y%m%d.log",
// rotatelogs.WithLinkName(filename),
// rotatelogs.WithMaxAge(time.Hour*24*30),
// rotatelogs.WithRotationTime(time.Hour*24),
// )
// */
// //保存日志30天,每1分钟分割一次日志
// hook, err := rotatelogs.New(
// filename+"_%Y%m%d%H%M.log",
// rotatelogs.WithLinkName(filename),
// rotatelogs.WithMaxAge(time.Hour*24*30),
// rotatelogs.WithRotationTime(time.Minute*1),
// )
// if err != nil {
// panic(err)
// }
// return hook
// }
|
package dice
import "github.com/jcheng31/diceroller/roller"
type regular struct {
roller roller.Roller
max int
}
// Regular returns a normal die.
func Regular(r roller.Roller, max int) Die {
return regular{r, max}
}
// RollN returns the total result of rolling n die.
func (r regular) RollN(n int) RollResults {
result := RollResults{0, make([]int, n)}
for i := 0; i < n; i++ {
r := r.roller.Roll(r.max)
result.Total += r
result.Rolls[i] = r
}
return result
}
|
// Copyright 2023 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 external
import (
"bytes"
"context"
"path"
"slices"
"testing"
"time"
"github.com/cockroachdb/pebble"
"github.com/pingcap/tidb/br/pkg/lightning/backend/kv"
"github.com/pingcap/tidb/br/pkg/lightning/common"
"github.com/pingcap/tidb/br/pkg/storage"
"github.com/pingcap/tidb/util/codec"
"github.com/stretchr/testify/require"
"golang.org/x/exp/rand"
)
func TestIter(t *testing.T) {
seed := time.Now().Unix()
rand.Seed(uint64(seed))
t.Logf("seed: %d", seed)
totalKV := 300
kvPairs := make([]common.KvPair, totalKV)
for i := range kvPairs {
keyBuf := make([]byte, rand.Intn(10)+1)
rand.Read(keyBuf)
// make sure the key is unique
kvPairs[i].Key = append(keyBuf, byte(i/255), byte(i%255))
valBuf := make([]byte, rand.Intn(10)+1)
rand.Read(valBuf)
kvPairs[i].Val = valBuf
}
sortedKVPairs := make([]common.KvPair, totalKV)
copy(sortedKVPairs, kvPairs)
slices.SortFunc(sortedKVPairs, func(i, j common.KvPair) int {
return bytes.Compare(i.Key, j.Key)
})
ctx := context.Background()
store := storage.NewMemStorage()
for i := 0; i < 3; i++ {
w := NewWriterBuilder().
SetMemorySizeLimit(uint64(rand.Intn(100)+1)).
SetPropSizeDistance(uint64(rand.Intn(50)+1)).
SetPropKeysDistance(uint64(rand.Intn(10)+1)).
Build(store, "/subtask", i)
kvStart := i * 100
kvEnd := (i + 1) * 100
err := w.AppendRows(ctx, nil, kv.MakeRowsFromKvPairs(kvPairs[kvStart:kvEnd]))
require.NoError(t, err)
_, err = w.Close(ctx)
require.NoError(t, err)
}
dataFiles, statFiles, err := GetAllFileNames(ctx, store, "/subtask")
require.NoError(t, err)
engine := Engine{
storage: store,
dataFiles: dataFiles,
statsFiles: statFiles,
}
iter, err := engine.createMergeIter(ctx, sortedKVPairs[0].Key)
require.NoError(t, err)
got := make([]common.KvPair, 0, totalKV)
for iter.Next() {
got = append(got, common.KvPair{
Key: iter.Key(),
Val: iter.Value(),
})
}
require.NoError(t, iter.Error())
require.Equal(t, sortedKVPairs, got)
pickStartIdx := rand.Intn(len(sortedKVPairs))
startKey := sortedKVPairs[pickStartIdx].Key
iter, err = engine.createMergeIter(ctx, startKey)
require.NoError(t, err)
got = make([]common.KvPair, 0, totalKV)
for iter.Next() {
got = append(got, common.KvPair{
Key: iter.Key(),
Val: iter.Value(),
})
}
require.NoError(t, iter.Error())
// got keys must be ascending
for i := 1; i < len(got); i++ {
require.True(t, bytes.Compare(got[i-1].Key, got[i].Key) < 0)
}
// the first key must be less than or equal to startKey
require.True(t, bytes.Compare(got[0].Key, startKey) <= 0)
}
func testGetFirstAndLastKey(
t *testing.T,
data common.IngestData,
lowerBound, upperBound []byte,
expectedFirstKey, expectedLastKey []byte,
) {
firstKey, lastKey, err := data.GetFirstAndLastKey(lowerBound, upperBound)
require.NoError(t, err)
require.Equal(t, expectedFirstKey, firstKey)
require.Equal(t, expectedLastKey, lastKey)
}
func testNewIter(
t *testing.T,
data common.IngestData,
lowerBound, upperBound []byte,
expectedKeys, expectedValues [][]byte,
) {
ctx := context.Background()
iter := data.NewIter(ctx, lowerBound, upperBound)
var (
keys, values [][]byte
)
for iter.First(); iter.Valid(); iter.Next() {
require.NoError(t, iter.Error())
key := make([]byte, len(iter.Key()))
copy(key, iter.Key())
keys = append(keys, key)
value := make([]byte, len(iter.Value()))
copy(value, iter.Value())
values = append(values, value)
}
require.NoError(t, iter.Error())
require.NoError(t, iter.Close())
require.Equal(t, expectedKeys, keys)
require.Equal(t, expectedValues, values)
}
func checkDupDB(t *testing.T, db *pebble.DB, expectedKeys, expectedValues [][]byte) {
iter := db.NewIter(nil)
var (
gotKeys, gotValues [][]byte
)
for iter.First(); iter.Valid(); iter.Next() {
key := make([]byte, len(iter.Key()))
copy(key, iter.Key())
gotKeys = append(gotKeys, key)
value := make([]byte, len(iter.Value()))
copy(value, iter.Value())
gotValues = append(gotValues, value)
}
require.NoError(t, iter.Close())
require.Equal(t, expectedKeys, gotKeys)
require.Equal(t, expectedValues, gotValues)
err := db.DeleteRange([]byte{0}, []byte{255}, nil)
require.NoError(t, err)
}
func TestMemoryIngestData(t *testing.T) {
keys := [][]byte{
[]byte("key1"),
[]byte("key2"),
[]byte("key3"),
[]byte("key4"),
[]byte("key5"),
}
values := [][]byte{
[]byte("value1"),
[]byte("value2"),
[]byte("value3"),
[]byte("value4"),
[]byte("value5"),
}
data := &MemoryIngestData{
keyAdapter: common.NoopKeyAdapter{},
keys: keys,
values: values,
ts: 123,
}
require.EqualValues(t, 123, data.GetTS())
testGetFirstAndLastKey(t, data, nil, nil, []byte("key1"), []byte("key5"))
testGetFirstAndLastKey(t, data, []byte("key1"), []byte("key6"), []byte("key1"), []byte("key5"))
testGetFirstAndLastKey(t, data, []byte("key2"), []byte("key5"), []byte("key2"), []byte("key4"))
testGetFirstAndLastKey(t, data, []byte("key25"), []byte("key35"), []byte("key3"), []byte("key3"))
testGetFirstAndLastKey(t, data, []byte("key25"), []byte("key26"), nil, nil)
testGetFirstAndLastKey(t, data, []byte("key0"), []byte("key1"), nil, nil)
testGetFirstAndLastKey(t, data, []byte("key6"), []byte("key9"), nil, nil)
testNewIter(t, data, nil, nil, keys, values)
testNewIter(t, data, []byte("key1"), []byte("key6"), keys, values)
testNewIter(t, data, []byte("key2"), []byte("key5"), keys[1:4], values[1:4])
testNewIter(t, data, []byte("key25"), []byte("key35"), keys[2:3], values[2:3])
testNewIter(t, data, []byte("key25"), []byte("key26"), nil, nil)
testNewIter(t, data, []byte("key0"), []byte("key1"), nil, nil)
testNewIter(t, data, []byte("key6"), []byte("key9"), nil, nil)
dir := t.TempDir()
db, err := pebble.Open(path.Join(dir, "duplicate"), nil)
require.NoError(t, err)
keyAdapter := common.DupDetectKeyAdapter{}
data = &MemoryIngestData{
keyAdapter: keyAdapter,
duplicateDetection: true,
duplicateDB: db,
ts: 234,
}
encodedKeys := make([][]byte, 0, len(keys)*2)
encodedValues := make([][]byte, 0, len(values)*2)
encodedZero := codec.EncodeInt(nil, 0)
encodedOne := codec.EncodeInt(nil, 1)
duplicatedKeys := make([][]byte, 0, len(keys)*2)
duplicatedValues := make([][]byte, 0, len(values)*2)
for i := range keys {
encodedKey := keyAdapter.Encode(nil, keys[i], encodedZero)
encodedKeys = append(encodedKeys, encodedKey)
encodedValues = append(encodedValues, values[i])
if i%2 == 0 {
continue
}
// duplicatedKeys will be like key2_0, key2_1, key4_0, key4_1
duplicatedKeys = append(duplicatedKeys, encodedKey)
duplicatedValues = append(duplicatedValues, values[i])
encodedKey = keyAdapter.Encode(nil, keys[i], encodedOne)
encodedKeys = append(encodedKeys, encodedKey)
newValues := make([]byte, len(values[i])+1)
copy(newValues, values[i])
newValues[len(values[i])] = 1
encodedValues = append(encodedValues, newValues)
duplicatedKeys = append(duplicatedKeys, encodedKey)
duplicatedValues = append(duplicatedValues, newValues)
}
data.keys = encodedKeys
data.values = encodedValues
require.EqualValues(t, 234, data.GetTS())
testGetFirstAndLastKey(t, data, nil, nil, []byte("key1"), []byte("key5"))
testGetFirstAndLastKey(t, data, []byte("key1"), []byte("key6"), []byte("key1"), []byte("key5"))
testGetFirstAndLastKey(t, data, []byte("key2"), []byte("key5"), []byte("key2"), []byte("key4"))
testGetFirstAndLastKey(t, data, []byte("key25"), []byte("key35"), []byte("key3"), []byte("key3"))
testGetFirstAndLastKey(t, data, []byte("key25"), []byte("key26"), nil, nil)
testGetFirstAndLastKey(t, data, []byte("key0"), []byte("key1"), nil, nil)
testGetFirstAndLastKey(t, data, []byte("key6"), []byte("key9"), nil, nil)
testNewIter(t, data, nil, nil, keys, values)
checkDupDB(t, db, duplicatedKeys, duplicatedValues)
testNewIter(t, data, []byte("key1"), []byte("key6"), keys, values)
checkDupDB(t, db, duplicatedKeys, duplicatedValues)
testNewIter(t, data, []byte("key1"), []byte("key3"), keys[:2], values[:2])
checkDupDB(t, db, duplicatedKeys[:2], duplicatedValues[:2])
testNewIter(t, data, []byte("key2"), []byte("key5"), keys[1:4], values[1:4])
checkDupDB(t, db, duplicatedKeys, duplicatedValues)
testNewIter(t, data, []byte("key25"), []byte("key35"), keys[2:3], values[2:3])
checkDupDB(t, db, nil, nil)
testNewIter(t, data, []byte("key25"), []byte("key26"), nil, nil)
checkDupDB(t, db, nil, nil)
testNewIter(t, data, []byte("key0"), []byte("key1"), nil, nil)
checkDupDB(t, db, nil, nil)
testNewIter(t, data, []byte("key6"), []byte("key9"), nil, nil)
checkDupDB(t, db, nil, nil)
}
|
package mosquito
import (
"io"
"regexp"
"io/ioutil"
"html/template"
"path/filepath"
)
type FileSystemRenderer struct {
Root string
}
func (renderer *FileSystemRenderer) Render(w io.Writer, file string, data interface{}) error {
var tmpl *template.Template
if err := renderer.parse(file, tmpl); err != nil {
return err
}
tmpl.ExecuteTemplate(w, file, data)
return nil
}
func (renderer *FileSystemRenderer) parse(file string, output *template.Template) error {
path := filepath.Join(renderer.Root, file)
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
if _, err := output.New(file).Parse(string(content)); err != nil {
return err
}
reg := regexp.MustCompile("{{[ ]*template[ ]+\"([^\"]+)\"")
matches := reg.FindAllStringSubmatch(string(content), -1)
for _, match := range matches {
if t := output.Lookup(match[1]); t != nil {
continue
}
if err := renderer.parse(match[1], output); err != nil {
return err
}
}
return nil
}
|
package middleware
import (
"context"
"net/http"
"strconv"
)
// ContextID is our type to retrieve our context
// objects
type ContextID int
// ID is the only ID we've defined
const ID ContextID = 0
// SetID updates context with the id then
// increments it
func SetID(start int64) Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ID, strconv.FormatInt(start, 10))
start++
r = r.WithContext(ctx)
next(w, r)
}
}
}
// GetID grabs an ID from a context if set
// otherwise it returns an empty string
func GetID(ctx context.Context) string {
if val, ok := ctx.Value(ID).(string); ok {
return val
}
return ""
}
|
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
credpb "google.golang.org/genproto/googleapis/iam/credentials/v1"
credentials "cloud.google.com/go/iam/credentials/apiv1"
"cloud.google.com/go/storage"
)
var (
projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
serviceAccount = fmt.Sprintf("%s@appspot.gserviceaccount.com", projectID)
bucket = os.Getenv("GCS_BUCKET")
)
func main() {
http.HandleFunc("/uploadurl", func(w http.ResponseWriter, r *http.Request) {
fileName := r.FormValue("name")
if fileName == "" {
http.Error(w, "name parameter is required", http.StatusBadRequest)
return
}
ctx := r.Context()
client, err := credentials.NewIamCredentialsClient(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer client.Close()
// 署名付きURLの生成
uploadURL, err := storage.SignedURL(bucket, fileName, &storage.SignedURLOptions{
GoogleAccessID: serviceAccount,
Method: http.MethodPut,
ContentType: "image/png",
SignBytes: func(b []byte) ([]byte, error) {
// Cloud IAM APIでサービスアカウントを利用して署名を生成する
resp, err := client.SignBlob(ctx, &credpb.SignBlobRequest{
Name: fmt.Sprintf("projects/-/serviceAccounts/%s", serviceAccount),
Payload: b,
})
if err != nil {
log.Printf("Failed to signe blob: %v", err)
return nil, err
}
return resp.GetSignedBlob(), nil
},
Expires: time.Now().Add(15 * time.Minute),
})
if err != nil {
log.Printf("Failed to signe url: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
body, _ := json.Marshal(map[string]string{
"url": uploadURL,
})
w.Header().Set("Content-Type", "application/json")
w.Write(body)
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.ListenAndServe(":"+port, nil)
}
|
package service
import (
"ConfCenter_web_Admin/initialization"
"errors"
"fmt"
"github.com/astaxie/beego/logs"
"gopkg.in/square/go-jose.v1/json"
"io/ioutil"
"net/http"
)
var (
scheme = "http://"
client = &http.Client{}
)
type OperationsResult struct {
Result []*Operations `json:"result"`
}
type Operations struct {
Id uint64 `json:"id"`
Route string `json:"route"`
Service string `json:"service"`
ServiceName string `json:"servicename"`
ServiceAddr []string `json:"serviceaddr"`
RegisterTime string `json:"registertime"`
Balance string `json:"Balance"`
}
type Service struct {
ServiceAddr []string `json:"serviceaddr"` //服务地址 [ip:port]
//RegisterName string `json:"registername"` //谁注册的服务 这里的名字是登录的名字,不能让人填写,这里先空着,等登录注册完成之后再说补充
RegisterTime string `json:"registertime"` //注册时间
//AltTime string `json:"alttime"` //修改时间 这里的名字是登录的名字,不能让人填写,这里先空着,等登录注册完成之后再说补充
AltReason string `json:"altreason"` //修改原因
ServiceName string `json:"servicename"`
Balance string `json:"Balance"`
}
func NewOperationsResult() *OperationsResult {
return &OperationsResult{
Result: make([]*Operations, 0, 60),
}
}
func (o *OperationsResult) Get() error {
var service = &Service{}
req, err := http.NewRequest("GET", scheme+initialization.ConfCenterService.Addr+"/quick_operation", nil)
if err != nil {
logs.Error("get confCenter service err %v", err)
return errors.New(fmt.Sprintf("get ConfCenter err %v", err))
}
resp, err := client.Do(req)
if err != nil {
logs.Error("get ConfCenter response err %v", err)
return errors.New(fmt.Sprintf("get ConfCenter response err %v", err))
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
logs.Error("readAll Operations service config body err %v", err)
return errors.New(fmt.Sprintf("readAll Operations service config body err %v", err))
}
if o == nil {
o = NewOperationsResult()
}
err = json.Unmarshal(body, o)
if err != nil {
logs.Error("unmarshal configCenter service body err %v", err)
return errors.New(fmt.Sprintf("marshal configCenter service body err %v", err))
}
for _, v := range o.Result {
err = json.Unmarshal([]byte(v.Service), service)
if err != nil {
logs.Error("unmarshal o.result.service err %v", err)
return errors.New(fmt.Sprintf("unmarshal o.result.service err %v", err))
}
v.ServiceAddr = service.ServiceAddr
v.RegisterTime = service.RegisterTime
v.Balance = service.Balance
}
for _, v := range o.Result {
logs.Debug("operations-----", v.RegisterTime, v.ServiceAddr, v.Balance)
}
for _, v := range o.Result {
switch {
case v.Balance == "random":
v.Balance = "轮询"
case v.Balance == "poling":
v.Balance = "随机"
}
}
return nil
}
|
package foundation
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestPanic runs
func TestPanic(t *testing.T) {
assert := assert.New(t)
assert.Panics(func() {
Panic("foo", "bar", 1, true)
Panicf("%s=%d", "bar", 1)
})
ProdModeClosure(func() {
assert.NotPanics(func() {
Panic("foo", "bar", 1, true)
Panicf("%s=%d", "bar", 1)
})
})
}
|
package commands
import (
"golang.org/x/sys/windows"
"path/filepath"
)
func workdir() string {
if programData, err := windows.KnownFolderPath(windows.FOLDERID_ProgramData, windows.KF_FLAG_DEFAULT); err != nil {
return `C:\uhppoted`
} else {
return filepath.Join(programData, "uhppoted")
}
}
|
package response
import (
"time"
)
// TitUserBaseinfoTraining, 数据已经转化过了,可以直接在页面展示
type TitUserBaseinfoTraining struct {
// 教学背景
School string `json:"school" form:"school" `
MajorsStudied string `json:"majorsStudied" form:"majorsStudied" `
HighestEducation string `json:"highestEducation" form:"highestEducation" `
SchoolSystem string `json:"schoolSystem" form:"schoolSystem" `
// 工作单位
WorkingState string `json:"workingState" form:"workingState" `
Company string `json:"company" form:"company" `
Area string `json:"area" form:"area" `
JobTitle string `json:"jobTitle" form:"jobTitle" `
ServiceType string `json:"serviceType" form:"serviceType" `
Income string `json:"income" form:"income" `
Benefits string `json:"benefits" form:"benefits" `
ChildType string `json:"childType" form:"childType" `
ChildAge string `json:"childAge" form:"childAge" `
// 培训经历
TrainingNumber string `json:"trainingNumber" form:"trainingNumber" `
TrainingFee string `json:"trainingFee" form:"trainingFee" `
TrainingInfos []TrainingInfo `json:"trainingInfos" form:"trainingInfos" `
}
type TrainingInfo struct {
TrainingCourse string `json:"trainingCourse" form:"trainingCourse" `
BeginTime time.Time `json:"beginTime" form:"beginTime" `
EndTime time.Time `json:"endTime" form:"endTime" `
PaymentWay string `json:"paymentWay" form:"paymentWay" `
}
// TitUserBase, 该类型为表里面的原始数据 ,拿来修改数据使用
type TitUserBase struct {
ID uint `json:"id"`
TitUserId uint `json:"titUserId" form:"titUserId" `
School string `json:"school" form:"school" `
MajorsStudied int `json:"majorsStudied" form:"majorsStudied" `
HighestEducation int `json:"highestEducation" form:"highestEducation" `
SchoolSystem int `json:"schoolSystem" form:"schoolSystem" `
WorkingState int `json:"workingState" form:"workingState" `
Company string `json:"company" form:"company" `
Area string `json:"area" form:"area" `
JobTitle string `json:"jobTitle" form:"jobTitle" `
ServiceType int `json:"serviceType" form:"serviceType" `
Income int `json:"income" form:"income" `
Benefits string `json:"benefits" form:"benefits" `
ChildType string `json:"childType" form:"childType" `
ChildAge int `json:"childAge" form:"childAge" `
TrainingNumber string `json:"trainingNumber" form:"trainingNumber" `
TrainingFee int `json:"trainingFee" form:"trainingFee" `
TrainingInfo []TitTrainingInfo `json:"trainingInfos" form:"trainingInfos" `
}
type TitTrainingInfo struct {
TitUserBaseinfoId int `json:"titUserBaseinfoId" form:"titUserBaseinfoId" `
TrainingCourse string `json:"trainingCourse" form:"trainingCourse" `
BeginTime time.Time `json:"beginTime" form:"beginTime" `
EndTime time.Time `json:"endTime" form:"endTime" `
PaymentWay int `json:"paymentWay" form:"paymentWay" `
}
|
package yousign
import (
"net/http"
"time"
)
type UserService struct {
client *Client
}
type User struct {
ID *string `json:"id,omitempty"`
Firstname *string `json:"firstname,omitempty"`
Lastname *string `json:"lastname,omitempty"`
FullName *string `json:"fullName,omitempty"`
Title *string `json:"title,omitempty"`
Email *string `json:"email,omitempty"`
Phone *string `json:"phone,omitempty"`
Status *string `json:"status,omitempty"`
Company *string `json:"company,omitempty"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
Config interface{} `json:"config,omitempty"`
SamlNameID *string `json:"samlNameId,omitempty"`
DefaultSignImage *string `json:"defaultSignImage,omitempty"`
FastSign *bool `json:"fastSign,omitempty"`
Group *UserGroup `json:"group,omitempty"`
Notifications interface{} `json:"notifications,omitempty"`
Deleted *bool `json:"deleted,omitempty"`
DeletedAt *time.Time `json:"deletedAt,omitempty"`
}
type UserRequest struct {
Firstname *string `json:"firstname,omitempty"`
Lastname *string `json:"lastname,omitempty"`
Title *string `json:"title,omitempty"`
Phone *string `json:"phone,omitempty"`
Company *string `json:"company,omitempty"`
Config interface{} `json:"config,omitempty"`
Group *string `json:"group,omitempty"`
DefaultSignImage *string `json:"defaultSignImage,omitempty"`
Notifications *string `json:"notifications,omitempty"`
}
func (s *UserService) All() ([]User, *http.Response, error) {
req, err := s.client.NewRequest("GET", "users", nil, nil)
if err != nil {
return nil, nil, err
}
var users []User
resp, err := s.client.Do(req, &users)
return users, resp, err
}
|
/*
Given a string, return a new string where the first and last chars have been exchanged.
*/
package main
import (
"fmt"
)
func front_back(s string) string {
if len(s) == 1 {
return s
}
var buf = []byte(s)
str := make([]byte, len(s))
if len(s) == 2 {
str[0] = buf[1]
str[1] = buf[0]
} else {
str[0] = buf[len(s)- 1]
for i := 1; i <= (len(s)-2); i++ {
str[i] = buf[i]
}
str[len(s) - 1] = buf[0]
}
return string(str)
}
func main(){
var status int = 0
if front_back("code") == "eodc" {
status += 1
}
if front_back("a") == "a" {
status += 1
}
if front_back("ee") == "ee" {
status += 1
}
if front_back("ba") == "ab" {
status += 1
}
if status == 4 {
fmt.Println("OK")
} else {
fmt.Println("NOT OK")
}
}
|
package main
import (
"github.com/gorilla/mux"
// inner package dependencies
"github.com/The-Music-Network/TMN-API/middleware"
"github.com/The-Music-Network/TMN-API/components/users"
)
func initRoutes(metaDb *middleware.MetaDb, router *mux.Router) {
initUserRoutes(metaDb, router)
}
func initUserRoutes(metaDb *middleware.MetaDb, router *mux.Router) {
router.Handle("/users/{id}", metaDb.Handler(users.ShowUser)).Methods("GET")
router.Handle("/users", metaDb.Handler(users.GetUsers)).Methods("GET")
router.Handle("/users", metaDb.Handler(users.CreateUser)).Methods("POST")
router.Handle("/users/{id}", metaDb.Handler(users.UpdateUser)).Methods("PUT")
router.Handle("/users/{id}", metaDb.Handler(users.DeleteUser)).Methods("DELETE")
}
|
package server
import (
"log"
"net/http"
"github.com/PECHIVKO/anagram-finder/api/router"
"github.com/PECHIVKO/anagram-finder/service"
)
func Run(port string, d *service.Dictionary) {
// Init Session
Session := &http.Server{
Addr: port,
Handler: router.NewRouter(d),
}
log.Fatal(Session.ListenAndServe())
}
|
package utils
import "testing"
func TestI18ns_ToFile(t *testing.T) {
//i18ns := new(I18ns)
//i18ns.AddI18n(I18n{Id: "1", Zh_CN: "你好", En_US: "hello"})
//i18ns.AddI18n(I18n{"2", "我", "me", "我"})
//i18ns.WriteToFile(".")
}
|
package command
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/jixwanwang/jixbot/channel"
"github.com/jixwanwang/jixbot/nlp"
)
type newQuestion struct {
timestamp time.Time
username string
question string
}
type questions struct {
cp *CommandPool
questionRgx *regexp.Regexp
cleanRgx *regexp.Regexp
mentionRgx *regexp.Regexp
qa *nlp.QuestionAnswerer
newQuestions map[string]newQuestion
storeAnswer *subCommand
lastQuestionAnswered time.Time
}
func (T *questions) Init() {
qas, err := T.cp.db.RetrieveQuestionAnswers(T.cp.channel.GetChannelName())
if err != nil {
log.Printf("Failed to lookup question answers!")
}
T.questionRgx, _ = regexp.Compile(`^(who|what|when|where|why)`)
T.cleanRgx, _ = regexp.Compile(`[^A-Za-z0-9\?\ ]+`)
T.mentionRgx, _ = regexp.Compile(`@[a-zA-Z0-9_]+`)
T.qa = nlp.NewQuestionAnswerer()
for _, qa := range qas {
T.qa.AddQuestionAndAnswer(qa.Q, qa.A)
}
T.lastQuestionAnswered = time.Now()
T.newQuestions = map[string]newQuestion{}
T.storeAnswer = &subCommand{
command: "!q",
numArgs: 1,
cooldown: 5 * time.Second,
clearance: channel.MOD,
}
}
func (T *questions) ID() string {
return "questions"
}
func (T *questions) Response(username, message string, whisper bool) {
if whisper {
return
}
message = strings.TrimSpace(message)
clearance := T.cp.channel.GetLevel(username)
args, err := T.storeAnswer.parse(message, clearance)
if err == nil {
user := strings.TrimPrefix(args[0], "@")
q, ok := T.newQuestions[user]
if ok {
qa, err := T.cp.db.AddQuestionAnswer(T.cp.channel.GetChannelName(), q.question, args[1])
if err == nil {
T.qa.AddQuestionAndAnswer(qa.Q, qa.A)
T.cp.Say(fmt.Sprintf("@%s question has been answered!", username))
}
return
}
}
message = strings.ToLower(message)
// Check for questionness
if !(T.questionRgx.MatchString(message) || message[len(message)-1:] == "?") {
return
}
// clean up old stuff in questions list
for k, v := range T.newQuestions {
if time.Since(v.timestamp) > 1*time.Minute {
delete(T.newQuestions, k)
}
}
// Remove all mentions and punctuation
message = T.mentionRgx.ReplaceAllString(message, "")
message = T.cleanRgx.ReplaceAllString(message, "")
// Trim ?, don't want that in the question body
message = strings.TrimSuffix(message, "?")
T.newQuestions[username] = newQuestion{
timestamp: time.Now(),
username: username,
question: message,
}
if time.Since(T.lastQuestionAnswered) > 15*time.Second {
// Check if the question has an answer
answer, score := T.qa.AnswerQuestion(message)
if len(answer) > 0 && score > 0.8 {
T.lastQuestionAnswered = time.Now()
T.cp.Say(fmt.Sprintf("@%s %s", username, answer))
return
}
}
}
|
// web server
package main
import (
"fmt"
"log"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal("listen error tcp :8080")
}
defer ln.Close()
log.Println("START LISTEN: ", ln.Addr())
for {
conn, err := ln.Accept()
if err != nil {
log.Println("ln.Accept error:", err)
continue
}
log.Println("conn.RemoteAddr().String()", conn.RemoteAddr().String())
log.Println("conn.RemoteAddr().Network()", conn.RemoteAddr().Network())
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer func() {
conn.Close()
log.Println(conn.LocalAddr(), " | ", conn.RemoteAddr(), " IS CLOSED")
}()
fmt.Println("CONNECTION: ", conn.LocalAddr(), " | ", conn.RemoteAddr())
if err := conn.SetDeadline(time.Now().Add(time.Second*2)); err != nil {
log.Println("conn.SetDeadline: ", err)
return
}
if _, err := conn.Write([]byte("FROM SERVER: hello world!\n")); err != nil {
log.Println(err)
return
}
buf := make([]byte, 128)
time.Sleep(time.Second)
if _, err := conn.Read(buf); err != nil {
log.Println(err)
return
}
fmt.Printf("%s\n%s\n", "--- BUFFER ---", string(buf))
fmt.Printf("\n%s\n% x\n", "-- BUFFER BYTE ---", buf)
fmt.Println("echo")
time.Sleep(time.Second)
conn.Write([]byte("--- FROM SERVER ECHO ---\n" + string(buf) + "\n"))
fmt.Println("time waite 5s")
time.Sleep(time.Second*5)
}
|
package secret
import (
"crypto/rand"
"errors"
"io"
"golang.org/x/crypto/nacl/secretbox"
)
const (
KeySize = 32
NonceSize = 24
)
var (
ErrEncrypt = errors.New("secret: encryption failed")
ErrDecrypt = errors.New("secret: decryption failed")
)
// GenerateKey creates a new random secret key.
func GenerateKey() (*[KeySize]byte, error) {
key := new([KeySize]byte)
_, err := io.ReadFull(rand.Reader, key[:])
if err != nil {
return nil, err
}
return key, nil
}
// GenerateNonce reates a new random nonce.
func GenerateNonce() (*[NonceSize]byte, error) {
nonce := new([NonceSize]byte)
_, err := io.ReadFull(rand.Reader, nonce[:])
if err != nil {
return nil, err
}
return nonce, nil
}
// Encrypt generates a random nonce and encrypts the input using NaCl's
// secretbox (symmetric encryption) package. The nonce is prepended to the
// ciphertext. A ealed message will be the same size as the original message
// plus secretbox.Overhead bytes long.
func Encrypt(key *[KeySize]byte, message []byte) ([]byte, error) {
nonce, err := GenerateNonce()
if err != nil {
return nil, ErrEncrypt
}
out := make([]byte, len(nonce))
copy(out, nonce[:])
out = secretbox.Seal(out, message, nonce, key)
return out, nil
}
// Decrypt extracts the nonce from the ciphertext, and attempts to ecrypt with
// NaCl's secretbox.
func Decrypt(key *[KeySize]byte, message []byte) ([]byte, error) {
if len(message) < (NonceSize + secretbox.Overhead) {
return nil, errors.New("something") //ErrDecrypt
}
var nonce [NonceSize]byte
copy(nonce[:], message[:NonceSize])
out, ok := secretbox.Open(nil, message[NonceSize:], &nonce, key)
if !ok {
return nil, ErrDecrypt
}
return out, nil
}
|
// This file was generated for SObject FeedRevision, API Version v43.0 at 2018-07-30 03:47:37.645128955 -0400 EDT m=+23.988635511
package sobjects
import (
"fmt"
"strings"
)
type FeedRevision struct {
BaseSObject
Action string `force:",omitempty"`
CreatedById string `force:",omitempty"`
CreatedDate string `force:",omitempty"`
EditedAttribute string `force:",omitempty"`
FeedEntityId string `force:",omitempty"`
Id string `force:",omitempty"`
IsDeleted bool `force:",omitempty"`
IsValueRichText bool `force:",omitempty"`
Revision int `force:",omitempty"`
SystemModstamp string `force:",omitempty"`
Value string `force:",omitempty"`
}
func (t *FeedRevision) ApiName() string {
return "FeedRevision"
}
func (t *FeedRevision) String() string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("FeedRevision #%s - %s\n", t.Id, t.Name))
builder.WriteString(fmt.Sprintf("\tAction: %v\n", t.Action))
builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById))
builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate))
builder.WriteString(fmt.Sprintf("\tEditedAttribute: %v\n", t.EditedAttribute))
builder.WriteString(fmt.Sprintf("\tFeedEntityId: %v\n", t.FeedEntityId))
builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id))
builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted))
builder.WriteString(fmt.Sprintf("\tIsValueRichText: %v\n", t.IsValueRichText))
builder.WriteString(fmt.Sprintf("\tRevision: %v\n", t.Revision))
builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp))
builder.WriteString(fmt.Sprintf("\tValue: %v\n", t.Value))
return builder.String()
}
type FeedRevisionQueryResponse struct {
BaseQuery
Records []FeedRevision `json:"Records" force:"records"`
}
|
package americanise
import "testing"
func TestTranslate(t *testing.T) {
Translate(input, output)
}
|
// set project doc.go
/*
set document
*/
package set
|
package server
import "github.com/spf13/viper"
// Config holds the server configuration
type Config struct {
// ListenPort speicifies the port server will bind to
ListenPort int `mapstructure:"server.ListenPort"`
// listenAddress specifies address on which server should listen for new connnections
ListenAddress string `mapstructure:"server.ListenAddress"`
}
// LoadDefaults will set the default for the server configuration
func LoadDefaults() {
viper.SetDefault("server.ListenAddress", "")
viper.SetDefault("server.ListenPort", 8080)
}
|
package aedatastore
import (
"testing"
"github.com/favclip/testerator/v2"
_ "github.com/favclip/testerator/v2/datastore"
_ "github.com/favclip/testerator/v2/memcache"
"go.mercari.io/datastore/testsuite"
_ "go.mercari.io/datastore/testsuite/dsmiddleware/dslog"
_ "go.mercari.io/datastore/testsuite/dsmiddleware/fishbone"
_ "go.mercari.io/datastore/testsuite/dsmiddleware/localcache"
_ "go.mercari.io/datastore/testsuite/dsmiddleware/rpcretry"
_ "go.mercari.io/datastore/testsuite/favcliptools"
_ "go.mercari.io/datastore/testsuite/realworld/recursivebatch"
_ "go.mercari.io/datastore/testsuite/realworld/tbf"
"go.mercari.io/datastore/dsmiddleware/aememcache"
"google.golang.org/appengine"
)
func TestAEDatastoreTestSuite(t *testing.T) {
for name, test := range testsuite.TestSuite {
t.Run(name, func(t *testing.T) {
_, ctx, err := testerator.SpinUp()
if err != nil {
t.Fatal(err.Error())
}
defer testerator.SpinDown()
ctx = testsuite.WrapAEFlag(ctx)
datastore, err := FromContext(ctx)
if err != nil {
t.Fatal(err)
}
test(ctx, t, datastore)
})
}
}
func TestAEDatastoreWithAEMemcacheTestSuite(t *testing.T) {
for name, test := range testsuite.TestSuite {
t.Run(name, func(t *testing.T) {
switch name {
// Skip the failure that happens when you firstly appended another middleware layer.
case
"LocalCache_Basic",
"LocalCache_WithIncludeKinds",
"LocalCache_WithExcludeKinds",
"LocalCache_WithKeyFilter",
"FishBone_QueryWithoutTx":
t.SkipNow()
// It's annoying to avoid failure test. I think there is no problem in practical use. I believe...
case "PutAndGet_TimeTime":
t.SkipNow()
}
_, ctx, err := testerator.SpinUp()
if err != nil {
t.Fatal(err.Error())
}
defer testerator.SpinDown()
ctx = testsuite.WrapAEFlag(ctx)
datastore, err := FromContext(ctx)
if err != nil {
t.Fatal(err)
}
ch := aememcache.New()
datastore.AppendMiddleware(ch)
test(ctx, t, datastore)
})
}
}
func TestAEDatastoreTestSuiteWithNamespace(t *testing.T) {
for name, test := range testsuite.TestSuite {
t.Run(name, func(t *testing.T) {
_, ctx, err := testerator.SpinUp()
if err != nil {
t.Fatal(err.Error())
}
defer testerator.SpinDown()
// Namespaceを設定する
// 本ライブラリでは appengine.Namespace による設定の影響をうけない設計であり、これを確認する
ctx, err = appengine.Namespace(ctx, "TestSuite")
if err != nil {
t.Fatal(err.Error())
}
ctx = testsuite.WrapAEFlag(ctx)
datastore, err := FromContext(ctx)
if err != nil {
t.Fatal(err)
}
test(ctx, t, datastore)
})
}
}
|
package service
type PubService struct {
}
|
package jsonstream
import (
"bufio"
"encoding/json"
"errors"
"io"
)
var ErrClosed = errors.New("json: stream closed")
func isArray(br *bufio.Reader) (bool, error) {
for {
b, err := br.Peek(1)
if err != nil {
return false, err
}
switch b[0] {
// Ignore whitespace.
case ' ', '\n', '\t':
case '[':
return true, nil
case '{':
return false, nil
default:
return false, errors.New("JSON must be an object or array of objects")
}
}
}
type Encoder struct {
w io.Writer
json *json.Encoder
first bool
closed bool
}
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
w: w,
json: json.NewEncoder(w),
first: true,
}
}
func (e *Encoder) Encode(v interface{}) error {
if e.closed {
return ErrClosed
}
if e.first {
e.w.Write([]byte("["))
e.first = false
} else {
e.w.Write([]byte(","))
}
return e.json.Encode(v)
}
// Close closes the stream. This _does not_ close the underlying io.Writer.
func (e *Encoder) Close() error {
if e.closed {
return ErrClosed
}
// In case no elements are written, open the brace.
if e.first {
e.w.Write([]byte("["))
}
e.w.Write([]byte("]"))
e.closed = true
return nil
}
type Decoder struct {
br *bufio.Reader
json *json.Decoder
first bool
err error
}
func NewDecoder(r io.Reader) *Decoder {
br := bufio.NewReader(r)
return &Decoder{
br: br,
json: json.NewDecoder(br),
first: true,
}
}
func (e *Decoder) init() {
if e.first {
e.first = false
ok, err := isArray(e.br)
if err != nil {
e.err = err
}
// If this is an array, read the bracket.
if ok {
if _, err := e.json.Token(); err != nil {
e.err = err
}
}
}
}
func (e *Decoder) More() bool {
if e.first {
e.init()
}
return e.json.More()
}
func (e *Decoder) Decode(v interface{}) error {
if e.first {
e.init()
}
if e.err != nil {
return e.err
}
err := e.json.Decode(v)
if err != nil {
return err
}
// Read closing bracket.
if !e.json.More() {
if _, err := e.json.Token(); err != nil {
return err
}
}
return nil
}
|
package agent
import (
"context"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/dline"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
miner3 "github.com/filecoin-project/specs-actors/v4/actors/builtin/miner"
"github.com/filecoin-project/specs-actors/v4/actors/util/adt"
cid "github.com/ipfs/go-cid"
)
type MinerStateV2 struct {
Root cid.Cid
Ctx context.Context
st *miner2.State
}
func (m *MinerStateV2) state(store adt.Store) (*miner2.State, error) {
if m.st == nil {
var st miner2.State
err := store.Get(m.Ctx, m.Root, &st)
if err != nil {
return nil, err
}
m.st = &st
}
return m.st, nil
}
func (m *MinerStateV2) HasSectorNo(store adt.Store, sectorNo abi.SectorNumber) (bool, error) {
st, err := m.state(store)
if err != nil {
return false, err
}
return st.HasSectorNo(store, sectorNo)
}
func (m *MinerStateV2) FindSector(store adt.Store, sectorNo abi.SectorNumber) (uint64, uint64, error) {
st, err := m.state(store)
if err != nil {
return 0, 0, err
}
return st.FindSector(store, sectorNo)
}
func (m *MinerStateV2) ProvingPeriodStart(store adt.Store) (abi.ChainEpoch, error) {
st, err := m.state(store)
if err != nil {
return 0, err
}
return st.ProvingPeriodStart, nil
}
func (m *MinerStateV2) LoadSectorInfo(store adt.Store, sectorNo uint64) (SimSectorInfo, error) {
st, err := m.state(store)
if err != nil {
return nil, err
}
sectors, err := st.LoadSectorInfos(store, bitfield.NewFromSet([]uint64{uint64(sectorNo)}))
if err != nil {
return nil, err
}
return &SectorInfoV2{info: sectors[0]}, nil
}
func (m *MinerStateV2) DeadlineInfo(store adt.Store, currEpoch abi.ChainEpoch) (*dline.Info, error) {
st, err := m.state(store)
if err != nil {
return nil, err
}
return st.DeadlineInfo(currEpoch), nil
}
func (m *MinerStateV2) FeeDebt(store adt.Store) (abi.TokenAmount, error) {
st, err := m.state(store)
if err != nil {
return big.Zero(), err
}
return st.FeeDebt, nil
}
func (m *MinerStateV2) LoadDeadlineState(store adt.Store, dlIdx uint64) (SimDeadlineState, error) {
st, err := m.state(store)
if err != nil {
return nil, err
}
dls, err := st.LoadDeadlines(store)
if err != nil {
return nil, err
}
dline, err := dls.LoadDeadline(store, dlIdx)
if err != nil {
return nil, err
}
return &DeadlineStateV2{deadline: dline}, nil
}
type DeadlineStateV2 struct {
deadline *miner2.Deadline
}
func (d *DeadlineStateV2) LoadPartition(store adt.Store, partIdx uint64) (SimPartitionState, error) {
part, err := d.deadline.LoadPartition(store, partIdx)
if err != nil {
return nil, err
}
return &PartitionStateV2{partition: part}, nil
}
type PartitionStateV2 struct {
partition *miner2.Partition
}
func (p *PartitionStateV2) Terminated() bitfield.BitField {
return p.partition.Terminated
}
type SectorInfoV2 struct {
info *miner2.SectorOnChainInfo
}
func (s *SectorInfoV2) Expiration() abi.ChainEpoch {
return s.info.Expiration
}
type MinerStateV3 struct {
Root cid.Cid
st *miner3.State
Ctx context.Context
}
func (m *MinerStateV3) state(store adt.Store) (*miner3.State, error) {
if m.st == nil {
var st miner3.State
err := store.Get(m.Ctx, m.Root, &st)
if err != nil {
return nil, err
}
m.st = &st
}
return m.st, nil
}
func (m *MinerStateV3) HasSectorNo(store adt.Store, sectorNo abi.SectorNumber) (bool, error) {
st, err := m.state(store)
if err != nil {
return false, err
}
return st.HasSectorNo(store, sectorNo)
}
func (m *MinerStateV3) FindSector(store adt.Store, sectorNo abi.SectorNumber) (uint64, uint64, error) {
st, err := m.state(store)
if err != nil {
return 0, 0, err
}
return st.FindSector(store, sectorNo)
}
func (m *MinerStateV3) ProvingPeriodStart(store adt.Store) (abi.ChainEpoch, error) {
st, err := m.state(store)
if err != nil {
return 0, err
}
return st.ProvingPeriodStart, nil
}
func (m *MinerStateV3) LoadSectorInfo(store adt.Store, sectorNo uint64) (SimSectorInfo, error) {
st, err := m.state(store)
if err != nil {
return nil, err
}
sectors, err := st.LoadSectorInfos(store, bitfield.NewFromSet([]uint64{uint64(sectorNo)}))
if err != nil {
return nil, err
}
return &SectorInfoV3{info: sectors[0]}, nil
}
func (m *MinerStateV3) DeadlineInfo(store adt.Store, currEpoch abi.ChainEpoch) (*dline.Info, error) {
st, err := m.state(store)
if err != nil {
return nil, err
}
return st.DeadlineInfo(currEpoch), nil
}
func (m *MinerStateV3) FeeDebt(store adt.Store) (abi.TokenAmount, error) {
st, err := m.state(store)
if err != nil {
return big.Zero(), err
}
return st.FeeDebt, nil
}
func (m *MinerStateV3) LoadDeadlineState(store adt.Store, dlIdx uint64) (SimDeadlineState, error) {
st, err := m.state(store)
if err != nil {
return nil, err
}
dls, err := st.LoadDeadlines(store)
if err != nil {
return nil, err
}
dline, err := dls.LoadDeadline(store, dlIdx)
if err != nil {
return nil, err
}
return &DeadlineStateV3{deadline: dline}, nil
}
type DeadlineStateV3 struct {
deadline *miner3.Deadline
}
func (d *DeadlineStateV3) LoadPartition(store adt.Store, partIdx uint64) (SimPartitionState, error) {
part, err := d.deadline.LoadPartition(store, partIdx)
if err != nil {
return nil, err
}
return &PartitionStateV3{partition: part}, nil
}
type PartitionStateV3 struct {
partition *miner3.Partition
}
func (p *PartitionStateV3) Terminated() bitfield.BitField {
return p.partition.Terminated
}
type SectorInfoV3 struct {
info *miner3.SectorOnChainInfo
}
func (s *SectorInfoV3) Expiration() abi.ChainEpoch {
return s.info.Expiration
}
|
/*
Given an input string S, print S followed by a non-empty separator in the following way:
Step 1: S has a 1/2 chance of being printed, and a 1/2 chance for the program to terminate.
Step 2: S has a 2/3 chance of being printed, and a 1/3 chance for the program to terminate.
Step 3: S has a 3/4 chance of being printed, and a 1/4 chance for the program to terminate.
…
Step n: S has a n/(n+1) chance of being printed, and a 1/(n+1) chance for the program to terminate.
Notes
The input string will only consist of characters that are acceptable in your language's string type.
Any non-empty separator can be used, as long as it is always the same. It is expected that the separator is printed after the last print of S before the program terminates.
The program has a 1/2 chance of terminating before printing anything.
A trailing new line is acceptable.
Your answer must make a genuine attempt at respecting the probabilities described. Obviously, when n is big this will be less and less true. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.
Scoring
This is code-golf, so the shortest answer in bytes wins.
*/
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
sim("Hello World")
}
func sim(s string) {
for n := 2.0; ; n++ {
fmt.Println(s)
if rand.Float64() < 1/n {
break
}
}
}
|
package easypost
import (
"encoding/json"
)
// UnmarshalJSONObject attempts to unmarshal an easypost object from JSON data.
// An error is only returned if data is non-zero length and JSON decoding fails.
// If data contains a valid JSON object with an "object" key/value that matches
// a known object type, it will return a pointer to the corresponding object
// type from this package, e.g. *Address, *Batch, *Refund, etc. If the decoded
// JSON doesn't match, the return value will be the default type stored by
// json.Unmarshal.
func UnmarshalJSONObject(data []byte) (interface{}, error) {
if len(data) == 0 {
return nil, nil
}
var obj struct {
Object string `json:"object"`
}
if err := json.Unmarshal(data, &obj); err != nil {
return nil, err
}
var result interface{}
switch obj.Object {
case "Address":
result = new(Address)
case "ApiKey":
result = new(APIKey)
case "Batch":
result = new(Batch)
case "CarrierAccount":
result = new(CarrierAccount)
case "CarrierDetail":
result = new(TrackingCarrierDetail)
case "CarrierType":
result = new(CarrierType)
case "CustomsInfo":
result = new(CustomsInfo)
case "CustomsItem":
result = new(CustomsItem)
case "Event":
result = new(Event)
case "Form":
result = new(Form)
case "Insurance":
result = new(Insurance)
case "Order":
result = new(Order)
case "Parcel":
result = new(Parcel)
case "Payload":
result = new(EventPayload)
case "PaymentLog":
result = new(PaymentLog)
case "PaymentLogReport":
result = new(Report)
case "Pickup":
result = new(Pickup)
case "PostageLabel":
result = new(PostageLabel)
case "Rate":
result = new(Rate)
case "Refund":
result = new(Refund)
case "RefundReport":
result = new(Report)
case "ScanForm":
result = new(ScanForm)
case "Shipment":
result = new(Shipment)
case "ShipmentInvoiceReport":
result = new(Report)
case "ShipmentReport":
result = new(Report)
case "Tracker":
result = new(Tracker)
case "TrackerReport":
result = new(Report)
case "TrackingDetail":
result = new(TrackingDetail)
case "TrackingLocation":
result = new(TrackingLocation)
case "User":
result = new(User)
case "Webhook":
result = new(Webhook)
}
// If 'obj' didn't match one of the types above, result will be a nil
// interface type. This will cause Unmarshal to use the default Go type for
// the JSON value, like map[string]interface{}.
if err := json.Unmarshal(data, &result); err != nil {
return nil, err
}
return result, nil
}
|
package ttlib
import (
"github.com/johnnylee/util"
)
// ServerConfig: A configuration file for a server.
type ServerConfig struct {
ListenAddr string // The address to pass to Listen.
PublicAddr string // The address to use to connect to the server.
}
// LoadServerConfig: Load the server's configuration from the given baseDir.
func LoadServerConfig(baseDir string) (*ServerConfig, error) {
sc := new(ServerConfig)
return sc, util.JsonUnmarshal(ServerConfigPath(baseDir), sc)
}
// Save: Save the server's configuration to the given baseDir.
func (sc ServerConfig) Save(baseDir string) error {
return util.JsonMarshal(ServerConfigPath(baseDir), &sc)
}
|
package wechat
import (
"strconv"
"gopkg.in/chanxuehong/wechat.v2/mch/mmpaymkttransfers/promotion"
"github.com/golang/glog"
"github.com/chanxuehong/util"
"bytes"
"encoding/xml"
"strings"
"gopkg.in/chanxuehong/wechat.v2/mch/mmpaymkttransfers"
"gopkg.in/chanxuehong/wechat.v2/mch/core"
"common-utilities/utilities"
)
// 微信转款到零钱
func TransferToChange(req *TransferToChangeReq,client *core.Client) (*TransferToChangeResp,error){
nonce := utilities.GetRandomStr(32)
params := map[string]string{
"mch_appid": client.AppId(),
"mchid": client.MchId(),
"openid": req.OpenID,
"partner_trade_no": req.PartnerTradeNo,
"nonce_str": nonce,
"amount": strconv.Itoa(req.Amount),
"desc": req.Desc,
"spbill_create_ip": req.IP,
}
receiverName := strings.Trim(req.ReceiverName," ")
if len(receiverName) == 0 {
params["check_name"] = "NO_CHECK"
} else {
params["check_name"] = "FORCE_CHECK"
params["re_user_name"] = receiverName
}
respMap,err := promotion.Transfers(client,params)
resp := &TransferToChangeResp{}
if err != nil {
glog.Errorln("TransferToChange Transfers error!",err)
if err2 := xml.Unmarshal([]byte(err.Error()),resp);err2 == nil {
return resp,nil
}
return nil,err
}
err = toRespFromMap(&respMap,resp,"TransferToChange")
return resp,nil
}
//商户账号appid mch_appid 是 wx8888888888888888 String 申请商户号的appid或商户号绑定的appid
//商户号 mchid 是 1900000109 String(32) 微信支付分配的商户号
//设备号 device_info 否 013467007045764 String(32) 微信支付分配的终端设备号
//随机字符串 nonce_str 是 5K8264ILTKCH16CQ2502SI8ZNMTM67VS String(32) 随机字符串,不长于32位
//签名 sign 是 C380BEC2BFD727A4B6845133519F3AD6 String(32) 签名,详见签名算法
//商户订单号 partner_trade_no 是 10000098201411111234567890 String 商户订单号,需保持唯一性
//(只能是字母或者数字,不能包含有符号)
//用户openid openid 是 oxTWIuGaIt6gTKsQRLau2M0yL16E String 商户appid下,某用户的openid
//校验用户姓名选项 check_name 是 FORCE_CHECK String NO_CHECK:不校验真实姓名
//FORCE_CHECK:强校验真实姓名
//收款用户姓名 re_user_name 可选 王小王 String 收款用户真实姓名。
//如果check_name设置为FORCE_CHECK,则必填用户真实姓名
//金额 amount 是 10099 int 企业付款金额,单位为分
//企业付款描述信息 desc 是 理赔 String 企业付款操作说明信息。必填。
//Ip地址 spbill_create_ip 是 192.168.0.1 String(32) 该IP同在商户平台设置的IP白名单中的IP没有关联,该IP可传用户端或者服务端的IP。
// 转款到零钱请求
type TransferToChangeReq struct {
OpenID string //用户的OpenID,必填
PartnerTradeNo string //订单编号,要确保一个商户下唯一 必填
Amount int //金额,单位为分 必填
ReceiverName string //收款人真实姓名,可不用填写,也不建议填写
Desc string //描述 必填
IP string //必填,该IP可传用户端或者服务端的IP。
}
// 转款到零钱响应
type TransferToChangeResp struct {
ReturnCode string `xml:"return_code"`//SUCCESS/FAIL 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
ReturnMsg string `xml:"return_msg"` //返回信息,如非空,为错误原因 签名失败 参数格式校验错误
// SUCCESS/FAIL,注意:当状态为FAIL时,存在业务结果未明确的情况,
// 所以如果状态FAIL,请务必再请求一次查询接口[请务必关注错误代码(err_code字段),通过查询查询接口确认此次付款的结果。],以确认此次付款的结果。
ResultCode string `xml:"result_code"`
ErrCode string `xml:"err_code"` //错误码
ErrCodeDes string `xml:"err_code_des"` //错误码文字描述
MchAppID string `xml:"mch_appid"` //申请商户号的appid或商户号绑定的appid(企业号corpid即为此appId)
MchID string `xml:"mchid"` //微信支付分配的商户号
DeviceInfo string `xml:"device_info"` // 微信支付分配的终端设备号,
NonceStr string `xml:"nonce_str"` //随机字符串,不长于32位
//以下字段在return_code 和result_code都为SUCCESS的时候有返回
PartnerTradeNo string `xml:"partner_trade_no"` //
PaymentNo string `xml:"payment_no"`
PaymentTime string `xml:"payment_time"`
}
// 查询
func GetTransferToChangeInfo(req *GetTransferToChangeInfoReq,client *core.Client) (*GetTransferToChangeInfoResp,error) {
nonce := utilities.GetRandomStr(32)
params := map[string]string{
"appid":client.AppId(),
"mch_id":client.MchId(),
"nonce_str":nonce,
"partner_trade_no":req.PartnerTradeNo,
}
respMap,err := mmpaymkttransfers.GetTransferInfo(client,params)
resp := &GetTransferToChangeInfoResp{}
if err != nil {
glog.Errorln("GetTransferToChangeInfo GetTransferInfo error:",err)
if err2 := xml.Unmarshal([]byte(err.Error()),resp);err2 == nil {
return resp,nil
}
return nil,err
}
err = toRespFromMap(&respMap,resp,"GetTransferToChangeInfo")
return resp,err
}
//随机字符串 nonce_str 是 5K8264ILTKCH16CQ2502SI8ZNMTM67VS String(32) 随机字符串,不长于32位
//签名 sign 是 C380BEC2BFD727A4B6845133519F3AD6 String(32) 生成签名方式查看3.2.1节
//商户订单号 partner_trade_no 是 10000098201411111234567890 String(28) 商户调用企业付款API时使用的商户订单号
//商户号 mch_id 是 10000098 String(32) 微信支付分配的商户号
//Appid appid 是 wxe062425f740d30d8 String(32) 商户号的appid
// 查询转打款到零钱息请求
type GetTransferToChangeInfoReq struct {
PartnerTradeNo string //必填
}
type GetTransferToChangeInfoResp struct {
ReturnCode string `xml:"return_code"` //SUCCESS/FAIL 此字段是通信标识,非付款标识,付款是否成功需要查看result_code来判断
ReturnMsg string `xml:"return_msg"` //返回信息,如非空,为错误原因 签名失败 参数格式校验错误
//以下信息会在ReturnCode为SUCCESS时返回
ResultCode string `xml:"result_code"` //SUCCESS/FAIL ,非付款标识,付款是否成功需要查看status字段来判断
ErrorCode string `xml:"err_code"` //错误码信息
ErrCodeDes string `xml:"err_code_des"` //错误信息描述
AppID string `xml:"appid"` //微信AppID
MchID string `xml:"mch_id"` //微信支付分配的商户号
DetailID string `xml:"detail_id"` //调用企业付款API时,微信系统内部产生的单号
PartnerTradeNo string `xml:"partner_trade_no"` //商户单号 商户使用查询API填写的单号的原路返回
Status string `xml:"status"` //转账状态 SUCCESS:转账成功 FAILED:转账失败 PROCESSING:处理中
Reason string `xml:"reason"` //失败原因,如失败则有个失败原因,文字描述
PaymentAmount int `xml:"payment_amount"` //付款金额 单位为分
OpenID string `xml:"openid"` //收款人的openid
TransferName string `xml:"transfer_name"` //收款人用户姓名
TransferTime string `xml:"transfer_time"` //发起转账的时间
Desc string `xml:"desc"` //付款时的描述
}
func toRespFromMap(respMap *map[string]string,pointer interface{},logFlag string) error{
glog.Infoln(logFlag + "resp map:",respMap)
buffer := bytes.NewBuffer(make([]byte, 0, 4<<10))
err := util.EncodeXMLFromMap(buffer,*respMap,"xml")
if err != nil {
glog.Errorln(logFlag + " EncodeXMLFromMap err:",err)
return err
}
glog.Infoln(logFlag + " resp xml:",buffer.String())
err = xml.Unmarshal(buffer.Bytes(),pointer)
if err != nil {
glog.Errorln(logFlag + " xml.Unmarshal error:",err)
return err
}
return nil
}
|
package trie
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestVLenArray_get(t *testing.T) {
ta := require.New(t)
// Fixed size
{
elts := [][]byte{
{'a', 'b'},
{}, // empty
{},
{'c', 'd'},
{'e', 'f'},
{},
}
va := newVLenArray(elts)
ta.Equal(int32(6), va.N)
ta.Equal(int32(3), va.EltCnt)
ta.Equal(int32(2), va.FixedSize)
ta.Equal([]byte{'a', 'b'}, va.get(0))
ta.Equal([]byte{}, va.get(1))
ta.Equal([]byte{}, va.get(2))
ta.Equal([]byte{'c', 'd'}, va.get(3))
ta.Equal([]byte{'e', 'f'}, va.get(4))
ta.Equal([]byte{}, va.get(5))
}
// Var-len size
{
elts := [][]byte{
{'a', 'b', 'c'},
{}, // empty
{},
{'c', 'd'},
{'e', 'f'},
{},
}
va := newVLenArray(elts)
ta.Equal(int32(6), va.N)
ta.Equal(int32(3), va.EltCnt)
ta.Equal(int32(0), va.FixedSize)
ta.Equal([]byte{'a', 'b', 'c'}, va.get(0))
ta.Equal([]byte{}, va.get(1))
ta.Equal([]byte{}, va.get(2))
ta.Equal([]byte{'c', 'd'}, va.get(3))
ta.Equal([]byte{'e', 'f'}, va.get(4))
ta.Equal([]byte{}, va.get(5))
}
// dd(st)
}
|
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document02800105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.028.001.05 Document"`
Message *SecuritiesSettlementTransactionAllegementNotificationV05 `xml:"SctiesSttlmTxAllgmtNtfctn"`
}
func (d *Document02800105) AddMessage() *SecuritiesSettlementTransactionAllegementNotificationV05 {
d.Message = new(SecuritiesSettlementTransactionAllegementNotificationV05)
return d.Message
}
// Scope
// An account servicer sends a SecuritiesSettlementTransactionAllegementNotification to an account owner to advise the account owner that a counterparty has alleged an instruction against the account owner's account at the account servicer and that the account servicer could not find the corresponding instruction of the account owner.
// The account servicer/owner relationship may be:
// - a central securities depository or another settlement market infrastructure acting on behalf of their participants
// - an agent (sub-custodian) acting on behalf of their global custodian customer, or
// - a custodian acting on behalf of an investment management institution or a broker/dealer.
//
// Usage
// The message may also be used to:
// - re-send a message previously sent,
// - provide a third party with a copy of a message for information,
// - re-send to a third party a copy of a message for information
// using the relevant elements in the Business Application Header.
type SecuritiesSettlementTransactionAllegementNotificationV05 struct {
// Unambiguous identification of the transaction as know by the instructing party.
TransactionIdentification *iso20022.Max35Text `xml:"TxId"`
// Provides settlement type and identification information.
SettlementTypeAndAdditionalParameters *iso20022.SettlementTypeAndAdditionalParameters12 `xml:"SttlmTpAndAddtlParams"`
// Identification of a transaction assigned by a market infrastructure other than a central securities depository, for example, Target2-Securities.
MarketInfrastructureTransactionIdentification *iso20022.Identification14 `xml:"MktInfrstrctrTxId,omitempty"`
// Details of the trade.
TradeDetails *iso20022.SecuritiesTradeDetails54 `xml:"TradDtls"`
// Financial instrument representing a sum of rights of the investor vis-a-vis the issuer.
FinancialInstrumentIdentification *iso20022.SecurityIdentification19 `xml:"FinInstrmId"`
// Elements characterising a financial instrument.
FinancialInstrumentAttributes *iso20022.FinancialInstrumentAttributes64 `xml:"FinInstrmAttrbts,omitempty"`
// Details related to the account and quantity involved in the transaction.
QuantityAndAccountDetails *iso20022.QuantityAndAccount42 `xml:"QtyAndAcctDtls"`
// Details of the closing of the securities financing transaction.
SecuritiesFinancingDetails *iso20022.SecuritiesFinancingTransactionDetails29 `xml:"SctiesFincgDtls,omitempty"`
// Parameters which explicitly state the conditions that must be fulfilled before a particular transaction of a financial instrument can be settled. These parameters are defined by the instructing party in compliance with settlement rules in the market the transaction will settle in.
SettlementParameters *iso20022.SettlementDetails99 `xml:"SttlmParams"`
// Identifies the chain of delivering settlement parties.
DeliveringSettlementParties *iso20022.SettlementParties36 `xml:"DlvrgSttlmPties,omitempty"`
// Identifies the chain of receiving settlement parties.
ReceivingSettlementParties *iso20022.SettlementParties36 `xml:"RcvgSttlmPties,omitempty"`
// Specifies cash parties in the framework of a corporate action event.
CashParties *iso20022.CashParties25 `xml:"CshPties,omitempty"`
// Total amount of money to be paid or received in exchange for the securities.
SettlementAmount *iso20022.AmountAndDirection48 `xml:"SttlmAmt,omitempty"`
// Other amounts than the settlement amount.
OtherAmounts *iso20022.OtherAmounts32 `xml:"OthrAmts,omitempty"`
// Other business parties relevant to the transaction.
OtherBusinessParties *iso20022.OtherParties28 `xml:"OthrBizPties,omitempty"`
// Additional information that cannot be captured in the structured elements and/or any other specific block.
SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) SetTransactionIdentification(value string) {
s.TransactionIdentification = (*iso20022.Max35Text)(&value)
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddSettlementTypeAndAdditionalParameters() *iso20022.SettlementTypeAndAdditionalParameters12 {
s.SettlementTypeAndAdditionalParameters = new(iso20022.SettlementTypeAndAdditionalParameters12)
return s.SettlementTypeAndAdditionalParameters
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddMarketInfrastructureTransactionIdentification() *iso20022.Identification14 {
s.MarketInfrastructureTransactionIdentification = new(iso20022.Identification14)
return s.MarketInfrastructureTransactionIdentification
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddTradeDetails() *iso20022.SecuritiesTradeDetails54 {
s.TradeDetails = new(iso20022.SecuritiesTradeDetails54)
return s.TradeDetails
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddFinancialInstrumentIdentification() *iso20022.SecurityIdentification19 {
s.FinancialInstrumentIdentification = new(iso20022.SecurityIdentification19)
return s.FinancialInstrumentIdentification
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddFinancialInstrumentAttributes() *iso20022.FinancialInstrumentAttributes64 {
s.FinancialInstrumentAttributes = new(iso20022.FinancialInstrumentAttributes64)
return s.FinancialInstrumentAttributes
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddQuantityAndAccountDetails() *iso20022.QuantityAndAccount42 {
s.QuantityAndAccountDetails = new(iso20022.QuantityAndAccount42)
return s.QuantityAndAccountDetails
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddSecuritiesFinancingDetails() *iso20022.SecuritiesFinancingTransactionDetails29 {
s.SecuritiesFinancingDetails = new(iso20022.SecuritiesFinancingTransactionDetails29)
return s.SecuritiesFinancingDetails
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddSettlementParameters() *iso20022.SettlementDetails99 {
s.SettlementParameters = new(iso20022.SettlementDetails99)
return s.SettlementParameters
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddDeliveringSettlementParties() *iso20022.SettlementParties36 {
s.DeliveringSettlementParties = new(iso20022.SettlementParties36)
return s.DeliveringSettlementParties
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddReceivingSettlementParties() *iso20022.SettlementParties36 {
s.ReceivingSettlementParties = new(iso20022.SettlementParties36)
return s.ReceivingSettlementParties
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddCashParties() *iso20022.CashParties25 {
s.CashParties = new(iso20022.CashParties25)
return s.CashParties
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddSettlementAmount() *iso20022.AmountAndDirection48 {
s.SettlementAmount = new(iso20022.AmountAndDirection48)
return s.SettlementAmount
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddOtherAmounts() *iso20022.OtherAmounts32 {
s.OtherAmounts = new(iso20022.OtherAmounts32)
return s.OtherAmounts
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddOtherBusinessParties() *iso20022.OtherParties28 {
s.OtherBusinessParties = new(iso20022.OtherParties28)
return s.OtherBusinessParties
}
func (s *SecuritiesSettlementTransactionAllegementNotificationV05) AddSupplementaryData() *iso20022.SupplementaryData1 {
newValue := new(iso20022.SupplementaryData1)
s.SupplementaryData = append(s.SupplementaryData, newValue)
return newValue
}
|
package g2util
import (
"image/color"
"github.com/mojocn/base64Captcha"
)
// Captcha ...
type Captcha struct {
cap *base64Captcha.Captcha
}
// Cap ...
func (c *Captcha) Cap() *base64Captcha.Captcha { return c.cap }
// SetCap ...
func (c *Captcha) SetCap(cap *base64Captcha.Captcha) { c.cap = cap }
// Constructor ...
func (c *Captcha) Constructor() {
//driver := base64Captcha.NewDriverDigit(70, 150, 4, 0.0, 1)
driver := base64Captcha.NewDriverString(60, 150, 0,
base64Captcha.OptionShowHollowLine,
4, "1234567890",
&color.RGBA{R: 0, G: 0, B: 0, A: 0},
base64Captcha.DefaultEmbeddedFonts,
[]string{"wqy-microhei.ttc"},
)
c.cap = base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
}
// Generate ...
func (c *Captcha) Generate() (id, b64s string, err error) { return c.cap.Generate() }
// Verify ...
func (c *Captcha) Verify(id, answer string) (match bool) { return c.cap.Verify(id, answer, true) }
|
package models
import (
"github.com/jinzhu/gorm"
)
// City Model
type City struct {
gorm.Model
ProvinceID int `json:"province_id" gorm:"not null" binding:"required"`
Name string `json:"name" gorm:"not null" binding:"required"`
Status bool `json:"status" gorm:"not null; default:true"`
}
|
//Implementation of Wiener's attack https://en.wikipedia.org/wiki/Wiener%27s_attack
package wiener
import (
"math/big"
"github.com/vveiln/crypto/wiener/fraction"
)
func solveQuadraticEquation(phi, n *big.Int) (*big.Int, *big.Int) {
b := new(big.Int).Sub(n, phi)
b.Add(b, big.NewInt(1))
b.Neg(b)
c := new(big.Int).Set(n)
discr := new(big.Int).Mul(b, b)
discr.Sub(discr, new(big.Int).Mul(big.NewInt(4), c))
if discr.Cmp(big.NewInt(0)) == -1 {
return nil, nil
}
discr.Sqrt(discr)
x1 := new(big.Int).Neg(b)
x1.Add(x1, discr)
x1.Rsh(x1, 1)
x2 := new(big.Int).Neg(b)
x2.Sub(x2, discr)
x2.Rsh(x2, 1)
return x1, x2
}
func FindKey(e, n *big.Int) *big.Int {
cf := fraction.NewContinuedFraction(fraction.NewFraction(e, n))
convergents := cf.Convergents()
for i := 0; i < len(convergents); i++ {
conv := convergents[i]
//Check if we can compute phi
if conv.Numerator().Cmp(big.NewInt(0)) == 0 {
continue
}
probable_phi := new(big.Int).Mul(e, conv.Denominator())
probable_phi.Sub(probable_phi, big.NewInt(1))
//Checks if probable_phi is integer
divisible := new(big.Int).Mod(probable_phi, conv.Numerator())
if divisible.Cmp(big.NewInt(0)) == 0 {
//Integer phi candidate
probable_phi := probable_phi.Div(probable_phi, conv.Numerator())
p, q := solveQuadraticEquation(probable_phi, n)
if p != nil && q != nil && new(big.Int).Mul(p, q).Cmp(n) == 0 {
return conv.Denominator()
}
}
}
return nil
}
|
package compoundsplitting
import (
"context"
"fmt"
"time"
)
// minCompoundWordLength prevents the splitting into very small (often not real) words
// to prevent a bloated tree
const minCompoundWordLength = 4
// maxWordLength prevents a tree from growing too big when adding very long strings
const maxWordLength = 100
// maxNumberTreeNodes
const maxNumberTreeNodes = 20
const cancelSplittingAfter = 500 * time.Millisecond
type Dictionary interface {
// Score receives a phrase of words and gives a score on how "good" this phrase is.
// If a compound word can be splitted into multiple phrases it will choose the one with the highest score.
Score(phrase []string) float64
// Contains is true if the word is in the dictionary
Contains(word string) bool
}
// Splitter builds a tree of compound splits and selects
// the best option based on a scoring mechanism
type Splitter struct {
dict Dictionary
cancelAfter time.Duration
}
// New Splitter recognizing words given by dict and
// selecting split phrases based on scoring
func NewSplitter(dict Dictionary) *Splitter {
return &Splitter{
dict: dict,
cancelAfter: cancelSplittingAfter,
}
}
type CompoundSplit struct {
// Combinations of compound combinations in a phrase
combinations []*Node
}
// Split a compound word into its compounds
func (sp *Splitter) Split(word string) ([]string, error) {
if len(word) > maxWordLength {
return []string{}, nil
}
compoundSplit := CompoundSplit{}
// spawn a new context that cancels the recursion if we are spending too much
// time on it
ctx, cancel := context.WithTimeout(context.Background(), sp.cancelAfter)
defer cancel()
err := sp.findAllWordCombinations(ctx, word, &compoundSplit)
if err != nil {
return nil, err
}
combinations := compoundSplit.getAllWordCombinations(ctx)
maxScore := 0.0
maxPhrase := []string{}
for _, combination := range combinations {
currentScore := sp.dict.Score(combination)
if len(maxPhrase) == 0 {
// Initialize if score is negative
maxScore = currentScore
maxPhrase = combination
}
if currentScore > maxScore {
maxScore = currentScore
maxPhrase = combination
}
}
return maxPhrase, nil
}
func (cs *CompoundSplit) insertCompound(ctx context.Context, word string,
startIndex int) error {
compound := NewNode(word, startIndex)
appended := false
for _, combination := range cs.combinations {
// For all possible combinations
leaves := combination.RecursivelyFindLeavesBeforeIndex(ctx, startIndex)
for _, leave := range leaves {
// Append the new compound to the leaves
appended = true
err := leave.AddChild(compound)
if err != nil {
return err
}
}
}
if !appended {
// if compound was not added to any leave add it to combinations
cs.combinations = append(cs.combinations, compound)
}
return nil
}
func (sp *Splitter) findAllWordCombinations(ctx context.Context, str string, compoundSplit *CompoundSplit) error {
compoundsUsed := 0
for offset, _ := range str {
// go from left to right and choose offsetted substring
offsetted := str[offset:]
for i := 1; i <= len(offsetted); i++ {
// go from left to right to find a word
word := offsetted[:i]
if len(word) < minCompoundWordLength {
continue
}
if sp.dict.Contains(word) {
compoundsUsed += 1
if compoundsUsed == maxNumberTreeNodes {
// Tree is getting out of bounds stopping for performance
return nil
}
err := compoundSplit.insertCompound(ctx, word, offset)
if err != nil {
return err
}
}
}
}
return nil
}
func (cs *CompoundSplit) getAllWordCombinations(ctx context.Context) [][]string {
wordCombinations := [][]string{}
for _, combination := range cs.combinations {
wordCombinations = append(wordCombinations,
combination.RecursivelyBuildNames(ctx)...)
}
return wordCombinations
}
// Node for of the word tree
type Node struct {
name string
children []*Node
startIndex int // inclusiv
endIndex int // exclusive
}
// NewNode from node name and in compoundword index
func NewNode(name string, startIndex int) *Node {
return &Node{
name: name,
children: []*Node{},
startIndex: startIndex,
endIndex: startIndex + len(name),
}
}
// AddChild node to node
func (node *Node) AddChild(newChildNode *Node) error {
if newChildNode.startIndex < node.endIndex {
return fmt.Errorf("Child starts at %v but this node ends at %v can't add as child", newChildNode.startIndex, node.endIndex)
}
node.children = append(node.children, newChildNode)
return nil
}
func (node *Node) findChildNodesBeforeIndex(index int) []*Node {
childrensThatEndBeforeIndex := []*Node{}
for _, child := range node.children {
if child.endIndex <= index {
childrensThatEndBeforeIndex = append(childrensThatEndBeforeIndex, child)
}
}
return childrensThatEndBeforeIndex
}
// RecursivelyBuildNames of compounds
func (node *Node) RecursivelyBuildNames(ctx context.Context) [][]string {
compoundName := [][]string{}
if ctx.Err() != nil {
// we've been going recursively too long, abort!
compoundName = append(compoundName, []string{node.name})
return compoundName
}
for _, child := range node.children {
childNames := child.RecursivelyBuildNames(ctx)
for _, childName := range childNames {
// Add the name of this node first
fullName := []string{node.name}
fullName = append(fullName, childName...)
compoundName = append(compoundName, fullName)
}
}
if len(compoundName) == 0 {
// This is a leave node
compoundName = append(compoundName, []string{node.name})
}
return compoundName
}
// RecursivelyFindLeavesBeforeIndex where to add a new node
func (node *Node) RecursivelyFindLeavesBeforeIndex(ctx context.Context, index int) []*Node {
foundLeaves := []*Node{}
if ctx.Err() != nil {
// we've been going recursively too long, abort!
return foundLeaves
}
children := node.findChildNodesBeforeIndex(index)
for _, child := range children {
leaves := child.RecursivelyFindLeavesBeforeIndex(ctx, index)
if len(leaves) == 0 {
// There are no leaves this means the child node is already a leave
foundLeaves = append(foundLeaves, child)
} else {
// Found leaves use them instead of direct child
foundLeaves = append(foundLeaves, leaves...)
}
}
if len(foundLeaves) == 0 && node.endIndex <= index {
// This node is the leave
foundLeaves = append(foundLeaves, node)
}
return foundLeaves
}
// NewEmptyTestSplitter creates a splitter,
// that does not know any words and
// thus is not able to split any words
func NewEmptyTestSplitter() *Splitter {
dictMock := &DictMock{
scores: map[string]float64{},
}
return &Splitter{
dict: dictMock,
}
}
func NewTestSplitter(wordScoreMapping map[string]float64) *Splitter {
dict := &DictMock{
scores: wordScoreMapping,
}
return &Splitter{
dict: dict,
}
}
|
package virtualgateway
import (
"context"
appmesh "github.com/aws/aws-app-mesh-controller-for-k8s/apis/appmesh/v1beta2"
"github.com/aws/aws-app-mesh-controller-for-k8s/pkg/equality"
"github.com/aws/aws-app-mesh-controller-for-k8s/pkg/k8s"
"github.com/aws/aws-sdk-go/aws"
appmeshsdk "github.com/aws/aws-sdk-go/service/appmesh"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
testclient "sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/log"
"testing"
)
func Test_defaultResourceManager_updateCRDVirtualGateway(t *testing.T) {
type args struct {
vg *appmesh.VirtualGateway
sdkVG *appmeshsdk.VirtualGatewayData
}
tests := []struct {
name string
args args
wantVG *appmesh.VirtualGateway
wantErr error
}{
{
name: "virtualGateway needs to patch both arn and condition",
args: args{
vg: &appmesh.VirtualGateway{
ObjectMeta: metav1.ObjectMeta{
Name: "vg-1",
},
Status: appmesh.VirtualGatewayStatus{},
},
sdkVG: &appmeshsdk.VirtualGatewayData{
Metadata: &appmeshsdk.ResourceMetadata{
Arn: aws.String("arn-1"),
},
Status: &appmeshsdk.VirtualGatewayStatus{
Status: aws.String(appmeshsdk.VirtualGatewayStatusCodeActive),
},
},
},
wantVG: &appmesh.VirtualGateway{
ObjectMeta: metav1.ObjectMeta{
Name: "vg-1",
},
Status: appmesh.VirtualGatewayStatus{
VirtualGatewayARN: aws.String("arn-1"),
Conditions: []appmesh.VirtualGatewayCondition{
{
Type: appmesh.VirtualGatewayActive,
Status: corev1.ConditionTrue,
},
},
},
},
},
{
name: "virtualGateway needs to patch condition only",
args: args{
vg: &appmesh.VirtualGateway{
ObjectMeta: metav1.ObjectMeta{
Name: "vg-1",
},
Status: appmesh.VirtualGatewayStatus{
VirtualGatewayARN: aws.String("arn-1"),
Conditions: []appmesh.VirtualGatewayCondition{
{
Type: appmesh.VirtualGatewayActive,
Status: corev1.ConditionTrue,
},
},
},
},
sdkVG: &appmeshsdk.VirtualGatewayData{
Metadata: &appmeshsdk.ResourceMetadata{
Arn: aws.String("arn-1"),
},
Status: &appmeshsdk.VirtualGatewayStatus{
Status: aws.String(appmeshsdk.VirtualGatewayStatusCodeInactive),
},
},
},
wantVG: &appmesh.VirtualGateway{
ObjectMeta: metav1.ObjectMeta{
Name: "vg-1",
},
Status: appmesh.VirtualGatewayStatus{
VirtualGatewayARN: aws.String("arn-1"),
Conditions: []appmesh.VirtualGatewayCondition{
{
Type: appmesh.VirtualGatewayActive,
Status: corev1.ConditionFalse,
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
k8sSchema := runtime.NewScheme()
clientgoscheme.AddToScheme(k8sSchema)
appmesh.AddToScheme(k8sSchema)
k8sClient := testclient.NewFakeClientWithScheme(k8sSchema)
m := &defaultResourceManager{
k8sClient: k8sClient,
log: log.NullLogger{},
}
err := k8sClient.Create(ctx, tt.args.vg.DeepCopy())
assert.NoError(t, err)
err = m.updateCRDVirtualGateway(ctx, tt.args.vg, tt.args.sdkVG)
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
assert.NoError(t, err)
gotVG := &appmesh.VirtualGateway{}
err = k8sClient.Get(ctx, k8s.NamespacedName(tt.args.vg), gotVG)
assert.NoError(t, err)
opts := cmp.Options{
equality.IgnoreFakeClientPopulatedFields(),
cmpopts.IgnoreTypes((*metav1.Time)(nil)),
}
assert.True(t, cmp.Equal(tt.wantVG, gotVG, opts), "diff", cmp.Diff(tt.wantVG, gotVG, opts))
}
})
}
}
func Test_defaultResourceManager_isSDKVirtualGatewayControlledByCRDVirtualGateway(t *testing.T) {
type fields struct {
accountID string
}
type args struct {
sdkVG *appmeshsdk.VirtualGatewayData
vg *appmesh.VirtualGateway
}
tests := []struct {
name string
fields fields
args args
want bool
}{
{
name: "sdkVG is controlled by crdVG",
fields: fields{accountID: "222222222"},
args: args{
sdkVG: &appmeshsdk.VirtualGatewayData{
Metadata: &appmeshsdk.ResourceMetadata{
ResourceOwner: aws.String("222222222"),
},
},
vg: &appmesh.VirtualGateway{},
},
want: true,
},
{
name: "sdkVG isn't controlled by crdVG",
fields: fields{accountID: "222222222"},
args: args{
sdkVG: &appmeshsdk.VirtualGatewayData{
Metadata: &appmeshsdk.ResourceMetadata{
ResourceOwner: aws.String("33333333"),
},
},
vg: &appmesh.VirtualGateway{},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
m := &defaultResourceManager{
accountID: tt.fields.accountID,
log: &log.NullLogger{},
}
got := m.isSDKVirtualGatewayControlledByCRDVirtualGateway(ctx, tt.args.sdkVG, tt.args.vg)
assert.Equal(t, tt.want, got)
})
}
}
func Test_defaultResourceManager_isSDKVirtualGatewayOwnedByCRDVirtualGateway(t *testing.T) {
type fields struct {
accountID string
}
type args struct {
sdkVG *appmeshsdk.VirtualGatewayData
vg *appmesh.VirtualGateway
}
tests := []struct {
name string
fields fields
args args
want bool
}{
{
name: "sdkVG is owned by crdVG",
fields: fields{accountID: "222222222"},
args: args{
sdkVG: &appmeshsdk.VirtualGatewayData{
Metadata: &appmeshsdk.ResourceMetadata{
ResourceOwner: aws.String("222222222"),
},
},
vg: &appmesh.VirtualGateway{},
},
want: true,
},
{
name: "sdkVG isn't owned by crdVG",
fields: fields{accountID: "222222222"},
args: args{
sdkVG: &appmeshsdk.VirtualGatewayData{
Metadata: &appmeshsdk.ResourceMetadata{
ResourceOwner: aws.String("33333333"),
},
},
vg: &appmesh.VirtualGateway{},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
m := &defaultResourceManager{
accountID: tt.fields.accountID,
log: &log.NullLogger{},
}
got := m.isSDKVirtualGatewayOwnedByCRDVirtualGateway(ctx, tt.args.sdkVG, tt.args.vg)
assert.Equal(t, tt.want, got)
})
}
}
|
package controller
import (
"chirpper_backend/models"
"chirpper_backend/utils"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
"cloud.google.com/go/firestore"
)
//postWithImage handle post feed request when storing an image file is needed
func (x *EndPoints) PostWithImage(client *firestore.Client) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
defer func() {
utils.ResOK(res, "OK")
return
}()
valid := verifyToken(req)
if valid != true {
utils.ResClearSite(&res)
utils.ResError(res, http.StatusUnauthorized, errors.New("INVALID TOKEN"))
return
}
if err := req.ParseMultipartForm(1024); err != nil {
utils.ResError(res, http.StatusInternalServerError, err)
return
}
var payload models.MsgPayload = models.MsgPayload{
Conn: onlineMap[req.FormValue("ID")],
Type: req.FormValue("Type"),
Client: client,
ID: req.FormValue("ID"),
Username: req.FormValue("Username"),
Email: req.FormValue("Email"),
AvatarURL: req.FormValue("AvatarURL"),
Text: req.FormValue("Text"),
Bearer: req.FormValue("Bearer"),
}
//implement store image in server and retrieve img directory location
imgLocation, err := storeImage(res, req, "Image", "post")
if err != nil {
utils.ResError(res, http.StatusInternalServerError, err)
return
}
payload.ImageURL = imgLocation
go postFromClient(payload)
}
}
//storeImage will store image file and return image file path/dir
func storeImage(res http.ResponseWriter, req *http.Request, formfilename string, foldername string) (string, error) {
uploadedFile, handler, err := req.FormFile(formfilename)
if err != nil {
return "", err
}
defer uploadedFile.Close()
dir, err := os.Getwd()
if err != nil {
return "", err
}
filename := handler.Filename
folderpath := filepath.Join(dir, os.Getenv("STATICPATH"), "assets", foldername)
fileLocation := filepath.Join(folderpath, filename)
err = createNewFolderIfNotExist(folderpath)
if err != nil {
return "", err
}
targetFile, err := os.OpenFile(fileLocation, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return "", err
}
defer targetFile.Close()
if _, err := io.Copy(targetFile, uploadedFile); err != nil {
return "", err
}
return fmt.Sprintf("assets/%s/%s", foldername, filename), nil
}
//createNewFolderIfNotExist will check folder directory and create new folder if not exist
func createNewFolderIfNotExist(path string) error {
_, err := os.Stat(path)
if os.IsNotExist(err) {
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
} else {
return nil
}
} else {
return nil
}
}
//postFromClient is a function to create a new post
func postFromClient(payload models.MsgPayload) {
valid := verifyTokenString(payload.Bearer)
if valid == false {
payload.Conn.Close()
return
}
payload.Date = time.Now().Format("02-Jan-2006")
db := NewDBRepo(payload.Client)
insertedID, err := db.InsertOne("chirps", map[string]interface{}{
"ID": payload.ID,
"Username": payload.Username,
"ImageURL": payload.ImageURL,
"Text": payload.Text,
"Date": payload.Date,
"AvatarURL": payload.AvatarURL,
})
payload.PostID = insertedID
go postFeedByIDID(payload.ID, payload)
result, err := db.FindOneByID("users", payload.ID)
if err != nil {
return
}
followers := result["followers"].([]interface{})
// payload.PostID = insertedID
go sendSelfPayload(payload)
if followers == nil {
return
}
go broadcastPostFeed(payload, followers)
go afterPostFeed(payload, followers)
//post chirp and ref it to user's feed
//post ref to user's followers
//send update to user's followers that online
}
//postFeedByID is intended for afterPostFeed alias insert new feed to user's followers's feed
func postFeedByIDID(ID string, payload models.MsgPayload) {
db := NewDBRepo(payload.Client)
err := db.InsertOneSubColByIDID("users", ID, "feed", payload.PostID, map[string]interface{}{
"ID": payload.ID,
"PostID": payload.PostID,
"Username": payload.Username,
"ImageURL": payload.ImageURL,
"Text": payload.Text,
"Date": payload.Date,
"AvatarURL": payload.AvatarURL,
})
if err != nil {
return
}
}
//afterPostFeed is update every user's followers feed
func afterPostFeed(payload models.MsgPayload, followers []interface{}) {
var folIDChan chan string = make(chan string)
ctx, cancel := context.WithCancel(context.Background())
go folIDSender(followers, cancel, folIDChan)
go folIDAfterPostHandler(ctx, folIDChan, payload)
}
//brodcastNewFeed broadcasts new post to online followers
func broadcastPostFeed(payload models.MsgPayload, followers []interface{}) {
var folIDChan chan string = make(chan string)
ctx, cancel := context.WithCancel(context.Background())
go folIDSender(followers, cancel, folIDChan)
go folIDBroadcastPostHandler(ctx, folIDChan, payload)
}
//folIDSender will send follower ID to channel
func folIDSender(followers []interface{}, cancel context.CancelFunc, folIDChan chan string) {
defer cancel()
for _, v := range followers {
folIDChan <- v.(string)
}
}
//receiveUpdate receive follower ID and send payload to correspondingID
func folIDBroadcastPostHandler(ctx context.Context, folIDChan chan string, payload models.MsgPayload) {
defer func() {
close(folIDChan)
}()
for {
select {
case ID := <-folIDChan:
sendPayload(ID, payload)
case <-ctx.Done():
return
}
}
}
func folIDAfterPostHandler(ctx context.Context, folIDChan chan string, payload models.MsgPayload) {
defer func() {
close(folIDChan)
}()
for {
select {
case ID := <-folIDChan:
postFeedByIDID(ID, payload)
case <-ctx.Done():
return
}
}
}
//sendPayload will send payload to online user
func sendPayload(folID string, payload models.MsgPayload) {
ws, res := onlineMap[folID]
if res != true {
return
}
ws.WriteJSON(struct {
Type string
ID string
PostID string
Username string
ImageURL string
Text string
Date string
AvatarURL string
}{
Type: "postFromServer",
ID: payload.ID,
PostID: payload.PostID,
Username: payload.Username,
ImageURL: payload.ImageURL,
Text: payload.Text,
Date: payload.Date,
AvatarURL: payload.AvatarURL,
})
}
func sendSelfPayload(payload models.MsgPayload) {
payload.Conn.WriteJSON(struct {
Type string
ID string
PostID string
Username string
ImageURL string
Text string
Date string
AvatarURL string
}{
Type: "postFromServer",
ID: payload.ID,
PostID: payload.PostID,
Username: payload.Username,
ImageURL: payload.ImageURL,
Text: payload.Text,
Date: payload.Date,
AvatarURL: payload.AvatarURL,
})
}
|
/**
* @Author: yanKoo
* @Date: 2019/3/25 14:57
* @Description:
*/
package main
import (
pb "api/talk_cloud"
"context"
"google.golang.org/grpc"
"log"
"sync"
"time"
)
const GROUP_PORT = "9999"
var maps sync.Map
func main() {
//host := "113.105.153.240"
host := "127.0.0.1"
conn, err := grpc.Dial(host+":9001", grpc.WithInsecure())
if err != nil {
log.Printf("grpc.Dial err : %v", err)
}
defer conn.Close()
userClient := pb.NewTalkCloudClient(conn)
//res, err := webCli.ImportDeviceByRoot(context.Background(), &pb.ImportDeviceReq{
// DeviceImei:[]string{"1234567897777777"},
// AccountId: 1,
//})
// 调用调用GRPC接口,转发数据
/*for i := 0; i <1000; i++ {
go func() {
res, err := webCli.ImMessagePublish(context.Background(), &pb.ImMsgReqData{
Id: 8,
SenderName: "xiaoliu",
ReceiverType: 2,
ReceiverId: 229,
ResourcePath: "SOSOS",
MsgType: 6,
ReceiverName: "xx group",
SendTime: strconv.FormatInt(time.Now().Unix(), 10),
})
log.Printf("res:%+v err : %+v",res, err)
}()
}
select {}*/
/*webCli := pb.NewTalkCloudClient(conn)
for i:= 0; i < 1500; i++ {
time.Sleep(time.Microsecond*300)
go func() {
res, err := webCli.ImMessagePublish(context.Background(), &pb.ImMsgReqData{
Id: 8,
SenderName: "iron man",
ReceiverType: 2,
ReceiverId: 229,
ResourcePath: "SOS",
MsgType: 3,
ReceiverName: "boot",
SendTime: "hhhhh",
MsgCode: strconv.FormatInt(time.Now().Unix(), 10),
})
log.Printf("%+v, err:%+v",res.Result.Msg, err)
}()
}*/
/*res, err := userClient.AppRegister(context.Background(), &pb.AppRegReq{
Name: "355172100003878",
Password: "123456",
})
log.Printf(res.String())*/
/*res, err := webCli.DeleteGroup(context.Background(), &pb.Group{
Id: 102,
})*/
/*res, err := userClient.AddFriend(context.Background(), &pb.FriendNewReq{
Uid:333,
Fuid:500,
})*/
log.Println("---------------------------------------Login Start-------------------------------------------")
res, err := userClient.Login(context.Background(), &pb.LoginReq{
Name: "264333",
Passwd: "123456",
})
log.Println(res.GroupList)
time.Sleep(time.Second*3)
/*
for _, v := range res.GroupList {
if v.GroupManager == -1 {
log.Printf("find a no mannage group: %d", v.Gid)
}
}*/
log.Printf("this user groups:%d, all:%+v", len(res.GroupList), res)
/* res, err := userClient.InviteUserIntoGroup(context.Background(), &pb.InviteUserReq{
Uids:"1536",
Gid:208,
})
log.Println(ress, "---------------++++++", err)*/
/*res, err := userClient.SearchUserByKey(context.Background(), &pb.UserSearchReq{
Uid:uint64(333),
Target:"",
})*/
/*res, err := userClient.GetFriendList(context.Background(), &pb.FriendsReq{
Uid:333,
})*/
/*for i := 0; i < 3000; i++ {
go func(i int) {
*/
log.Println("---------------------------------------GetGroupList Start-------------------------------------------")
resss, err := userClient.GetGroupList(context.Background(), &pb.GrpListReq{
Uid:int32(333),
})
log.Printf("%+v Get group list **************************** # %+v",err, resss)/*
}(i)
go func() {
ress, err := userClient.InviteUserIntoGroup(context.Background(), &pb.InviteUserReq{
Uids:"457",
Gid:210,
})
log.Println(ress, "*******---------++++++", err)
log.Printf("InviteUserIntoGroup **************************** # %d", i)
}()
}*/
log.Println("---------------------------------------Create group Start-------------------------------------------")
create, err := userClient.CreateGroup(context.Background(), &pb.CreateGroupReq{
DeviceIds: "1482,333,1003,1004",
DeviceInfos: nil,
GroupName:"trsss组",
AccountId: 333,
GroupInfo: &pb.Group{
Id:0,
GroupName:"trsss组",
AccountId: 333,
Status: 1,
}})
log.Printf("%+v>>>>>>>>>>>>>>>>>>>>>create:%+v",err, create)
time.Sleep(time.Second*2)
log.Println("---------------------------------------GetGroupList again Start-------------------------------------------")
glAgain, err := userClient.GetGroupList(context.Background(), &pb.GrpListReq{
Uid:int32(333),
})
log.Printf("%+v Get group list **************************** # %+v",err, glAgain)
/*res, err := userClient.SearchGroup(context.Background(), &pb.GrpSearchReq{
Uid:uint64(333),
Target:"雷坤",
})
*/
/*res , err := userClient.SearchUserByKey(context.Background(), &pb.UserSearchReq{
Uid:333,
Target:"121422",
})*/
/*res, err := userClient.JoinGroup(context.Background(), &pb.GrpUserAddReq{
Uid: 1514,
Gid: 151,
})*/
//log.Println(res, "---------------", err)
/*res, err := userClient.SetLockGroupId(context.Background(), &pb.SetLockGroupIdReq{
UId:333,
GId:215,
})*/
// GPS 数据
/*deviceCli := pb.NewTalkCloudLocationClient(conn)
res, err := deviceCli.ReportGPSData(context.Background(), &pb.ReportDataReq{
DataType: 2,
DeviceInfo:&pb.Device{
Id:1501,
},
LocationInfo: &pb.Location{
GpsInfo: &pb.GPS{
LocalTime: uint64(time.Now().Unix()),
Longitude: float64( 113.13795866213755),
Latitude: float64(22.480194593114472),
Course: 123,
Speed: float32(123.456457),
},
BSInfo: &pb.BaseStation{
Country: 460,
Operator: 1,
Lac:42705,
Cid: 228408571,
FirstBs: -49,
},
BtInfo: &pb.BlueTooth{
FirstBt: -93,
SecondBt: -89,
ThirdBt:-98,
},
WifiInfo: &pb.Wifi{
FirstWifi: 3,
SecondWifi: 3,
ThirdWifi: 3,
},
},
})
log.Printf("%+v", res)*/
//if err != nil {
// log.Println(err)
//} else {
// log.Printf("%+v", len(res.GroupList))
//}
// TODO 服务端 客户端 双向流
//allStr, _ := userClient.DataPublish(context.Background())
/*
go func() {
for {
log.Println("start send heartbeat")
if err := allStr.Send(&pb.StreamRequest{
Uid: 334,
DataType: 3,
ACK: 334,
}); err != nil {
}
time.Sleep(time.Second * 3)
}
}()*/
//i := 335
//for ; i < 1500 ; i++ {
/*go func(i int) {
log.Printf("%d start send get offline msg", i)
if err := allStr.Send(&pb.StreamRequest{
Uid: int32(i),
DataType: 2,
}); err != nil {
}
}(i)
time.Sleep(time.Microsecond*300)*/
//}
const (
FIRST_LOGIN_DATA = 1 // 初次登录返回的数据。比如用户列表,群组列表,该用户的个人信息
OFFLINE_IM_MSG = 2 // 用户离线时的IM数据
IM_MSG_FROM_UPLOAD_OR_WS_OR_APP = 3 // APP和web通过httpClient上传的文件信息、在线时通信的im数据
KEEP_ALIVE_MSG = 4 // 用户登录后,每隔interval秒向stream发送一个消息,测试能不能连通
LOGOUT_NOTIFY_MSG = 5 // 用户掉线之后,通知和他在一个组的其他成员
LOGIN_NOTIFY_MSG = 6 // 用户上线之后,通知和他在一个组的其他成员
IM_MSG_FROM_UPLOAD_RECEIVER_IS_USER = 1 // APP和web通过httpClient上传的IM信息是发给个人
IM_MSG_FROM_UPLOAD_RECEIVER_IS_GROUP = 2 // APP和web通过httpClient上传的IM信息是发给群组
USER_OFFLINE = 1 // 用户离线
USER_ONLINE = 2 // 用户在线
UNREAD_OFFLINE_IM_MSG = 1 // 用户离线消息未读
READ_OFFLINE_IM_MSG = 2 // 用户离线消息已读
CLIENT_EXCEPTION_EXIT = -1 // 客户端异常终止
NOTIFY = 1 // 通知完一个
)
/*go func(allStr *pb.TalkCloud_DataPublishClient) {
for {
_, _ = (*allStr).Recv()
//if data.DataType == KEEP_ALIVE_MSG {
// log.Println("client receive: 5 ", data.KeepAlive)
//} else if data.DataType == OFFLINE_IM_MSG {
// log.Println("client receive: 2", data.OfflineImMsgResp)
//} else if data.DataType == IM_MSG_FROM_UPLOAD_OR_WS_OR_APP {
// log.Println("client receive: 2", data.ImMsgData)
//}
}
}(&allStr)*/
}
|
package main
import (
"os"
"os/signal"
"strings"
"syscall"
"testing"
)
func TestMagalixAgent(t *testing.T) {
var (
args []string
covurl = os.Getenv("CODECOV_URL")
)
if covurl == "" {
t.Skip("codecov url is not provided")
}
for _, arg := range os.Args {
switch {
case strings.HasPrefix(arg, "-test"):
case strings.HasPrefix(arg, "DEVEL"):
default:
args = append(args, arg)
}
}
waitCh := make(chan int, 1)
os.Args = args
go func() {
main()
close(waitCh)
}()
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGHUP)
select {
case <-signalCh:
return
case <-waitCh:
return
}
}
|
package yaml
import (
"bytes"
"testing"
)
func TestEscapeKey(t *testing.T) {
s := "\\'\""
t.Log(s)
t.Log(EscapeKey(s))
}
func TestEscapeText(t *testing.T) {
facts := map[string]string{
":": "|2-\n :",
"a:": "|2-\n a:",
"a:b": "a:b",
":a:": "|2-\n :a:",
"a: b": "|2-\n a: b",
"#": "|2-\n #",
"a#": "|2-\n a#",
"|a": "|2-\n |a",
"a|": "a|",
}
for k, v := range facts {
var b bytes.Buffer
OutputText("", k, &b)
if b.String() != v {
t.Error(b.String())
t.Error(k)
t.Error(v)
}
}
}
|
package account
import (
"github.com/bitmaelum/bitmaelum-suite/internal/message"
"github.com/bitmaelum/bitmaelum-suite/pkg/address"
"github.com/bitmaelum/bitmaelum-suite/pkg/bmcrypto"
"io"
"time"
)
// Message is a simple message structure that we return as a list
type Message struct {
ID string `json:"id"`
Header message.Header `json:"h"`
Catalog []byte `json:"c"`
}
// MessageList is a list of messages we return
type MessageList struct {
Total int `json:"total"`
Returned int `json:"returned"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Messages []Message `json:"messages"`
}
// BoxInfo returns information about the given message box
type BoxInfo struct {
ID int `json:"id"`
Total int `json:"total"`
}
// Repository is the main repository that needs to be implemented. It's pretty big
type Repository interface {
AddressRepository
KeyRepository
BoxRepository
MessageRepository
}
// AddressRepository creates, checks or deletes complete accounts. Address is not the correct word for this.
type AddressRepository interface {
Create(addr address.HashAddress, pubKey bmcrypto.PubKey) error
Exists(addr address.HashAddress) bool
Delete(addr address.HashAddress) error
}
// KeyRepository gets and sets public keys into an account
type KeyRepository interface {
// Public key
StoreKey(addr address.HashAddress, key bmcrypto.PubKey) error
FetchKeys(addr address.HashAddress) ([]bmcrypto.PubKey, error)
}
// BoxRepository deals with message boxes insides an account
type BoxRepository interface {
CreateBox(addr address.HashAddress, parentBox int) error
ExistsBox(addr address.HashAddress, box int) bool
DeleteBox(addr address.HashAddress, box int) error
GetBoxInfo(addr address.HashAddress, box int) (*BoxInfo, error)
GetAllBoxes(addr address.HashAddress) ([]BoxInfo, error)
}
// MessageRepository deals with message within boxes
type MessageRepository interface {
SendToBox(addr address.HashAddress, box int, msgID string) error
MoveToBox(addr address.HashAddress, srcBox, dstBox int, msgID string) error
// Message boxes
FetchListFromBox(addr address.HashAddress, box int, since time.Time, offset, limit int) (*MessageList, error)
// Fetch specific message contents
FetchMessageHeader(addr address.HashAddress, box int, messageID string) (*message.Header, error)
FetchMessageCatalog(addr address.HashAddress, box int, messageID string) ([]byte, error)
FetchMessageBlock(addr address.HashAddress, box int, messageID, blockID string) ([]byte, error)
FetchMessageAttachment(addr address.HashAddress, box int, messageID, attachmentID string) (r io.ReadCloser, size int64, err error)
}
|
package notice
import (
"github.com/devfeel/dotweb"
"master/define"
"master/api"
"strconv"
"master/utils"
)
func DelNoticeHander(ctx dotweb.Context)error{
defer ctx.End()
token:=ctx.FormValue("token")
id,_:= strconv.Atoi(ctx.FormValue("noticeID"))
if api.CheckTokenValid(token){
api.DelNoticeInfo(id)
userInfo:=api.QueryUserInfoByToken(token)
if !api.CheckPermission(userInfo.Permission,define.Permission_Notice_OP){
return ctx.WriteJson(&define.ResponseData{Code:define.Code_NO_Permission})
}
api.PushLog(userInfo.Id,define.Action_DeleteNotice,"noticeID="+ctx.FormValue("noticeID"))
//mynsq.Instance().PushResult(token,"删除公告成功!")
utils.GetResultMgr().PushResult(token,"删除渠道成功!")
return ctx.WriteJson(&define.ResponseData{Code:define.Code_Successed})
}else {
return ctx.WriteJson(&define.ResponseData{Code:define.Code_TokenExpired})
}
}
|
package prototype
import (
"errors"
"fmt"
)
// ShirtCloner TODO
type ShirtCloner interface {
GetClone(s int) (ItemInfoGetter, error)
}
// TODO
const (
White = 1
Black = 2
Blue = 3
)
// ShirtCache TODO
type ShirtCache struct{}
// GetClone returns cached shirts sample by cloning them
func (s *ShirtCache) GetClone(d int) (ItemInfoGetter, error) {
switch d {
case Black:
newItem := *blackPrototype
return &newItem, nil
case White:
newItem := *whitePrototype
return &newItem, nil
default:
return nil, errors.New("Shirt model not reconized")
}
}
// ItemInfoGetter TODO
type ItemInfoGetter interface {
GetInfo() string
}
// ShirtColor Describes shirts color
type ShirtColor byte
// Shirt TODO
type Shirt struct {
Price float32
SKU string
Color ShirtColor
}
// GetInfo TODO
func (s *Shirt) GetInfo() string {
return fmt.Sprintf("Shirt with SKU '%s' and color id %d that cost '%f'", s.SKU, s.Color, s.Price)
}
// GetPrice TODO
func (s *Shirt) GetPrice() float32 {
return s.Price
}
// GetShirtsCloner TODO
func GetShirtsCloner() ShirtCloner {
return new(ShirtCache)
}
var whitePrototype = &Shirt{
Price: 15.00,
SKU: "empty",
Color: White,
}
var blackPrototype = &Shirt{
Price: 16.00,
SKU: "Empty",
Color: Black,
}
var bluePrototype = &Shirt{
Price: 17.00,
SKU: "empty",
Color: Blue,
}
|
package flow_test
import (
"fmt"
"github.com/BaritoLog/barito-flow/flow"
"github.com/go-redis/redis/v8"
"github.com/go-redis/redismock/v8"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"os"
"sync"
"testing"
"time"
)
const (
distributedRateLimiterDefaultTopic string = "foo"
distributedRateLimiterDefaultCount int = 2
distributedRateLimiterDefaultMaxToken int32 = 3
distributedRateLimiterNumOfWorkers int = 2
distributedRateLimiterDuration time.Duration = time.Second * 2
)
var (
// run 3 times more than the cap to check is limitation reached
distributedRateLimiterNumOfIteration int = 3 + int(distributedRateLimiterDefaultMaxToken)*int(distributedRateLimiterDuration.Seconds())
)
func init() {
log.SetLevel(log.DebugLevel)
}
// getKey returns formatted topic with iteration
func getKey(t *testing.T, iteration int) string {
t.Helper()
return fmt.Sprintf("%s:%d", distributedRateLimiterDefaultTopic, iteration)
}
// configureMock sets expectations
func configureMock(t *testing.T, mock redismock.ClientMock) {
t.Helper()
mock.MatchExpectationsInOrder(false)
// redismock limitation: expectation should be set for different topics
for i := 1; i <= distributedRateLimiterNumOfIteration; i++ {
key := getKey(t, i)
mock.ExpectIncrBy(key, int64(distributedRateLimiterDefaultCount)).
SetVal(int64(i + distributedRateLimiterDefaultCount))
mock.ExpectExpire(key, distributedRateLimiterDuration).RedisNil()
}
}
// work check isHitLimit
func work(t *testing.T, idx int, limiter flow.RateLimiter, iterationCh <-chan int, wg *sync.WaitGroup) {
t.Helper()
r := require.New(t)
max := int(distributedRateLimiterDefaultMaxToken) * int(distributedRateLimiterDuration.Seconds())
log.Debug("max:", max)
for i := range iterationCh {
key := getKey(t, i)
isReachedLimit := limiter.IsHitLimit(
key,
distributedRateLimiterDefaultCount,
distributedRateLimiterDefaultMaxToken,
)
log.Debugf("worker-%v got signal for iteration: %v, is reached limit? %v", idx, i, isReachedLimit)
if i+distributedRateLimiterDefaultCount > max && isReachedLimit != true {
r.Equalf(true, isReachedLimit, "at iteration: %v", i)
}
if i+distributedRateLimiterDefaultCount < max && isReachedLimit != false {
r.Equalf(false, isReachedLimit, "at iteration: %v", i)
}
wg.Done()
}
}
// TestDistributedRateLimiter_IsHitLimit tests rate limiter with multiple replicas
// simulated by goroutine
func TestDistributedRateLimiter_IsHitLimit(t *testing.T) {
db, mock := redismock.NewClientMock()
defer db.Close()
configureMock(t, mock)
limiter := flow.NewRedisRateLimiter(db,
flow.WithDuration(distributedRateLimiterDuration),
flow.WithTimeout(time.Second),
flow.WithMutex(),
)
iterationCh := make(chan int, distributedRateLimiterNumOfWorkers)
defer close(iterationCh)
wg := &sync.WaitGroup{}
go func() {
timeout := 10 * time.Second
time.Sleep(timeout)
close(iterationCh)
log.Debugf("iteration stucks for %vs, something wrong with the worker / redis", timeout.Seconds())
os.Exit(1)
}()
// simulate multiple replicas
for i := 0; i < distributedRateLimiterNumOfWorkers; i++ {
go work(t, i, limiter, iterationCh, wg)
}
for i := 1; i <= distributedRateLimiterNumOfIteration; i++ {
iterationCh <- i
wg.Add(1)
}
wg.Wait()
}
type mockRateLimiter struct {
IsStartAttr bool
IsStop bool
IsHitLimitCounter int
}
func (m *mockRateLimiter) IsHitLimit(topic string, count int, maxTokenIfNotExist int32) bool {
m.IsHitLimitCounter++
return false
}
func (m *mockRateLimiter) Start() {
m.IsStartAttr = true
}
func (m *mockRateLimiter) Stop() {
m.IsStartAttr = false
m.IsStop = true
}
func (m *mockRateLimiter) IsStart() bool {
return m.IsStartAttr
}
func (m *mockRateLimiter) PutBucket(_ string, _ *flow.LeakyBucket) {
}
func (m *mockRateLimiter) Bucket(_ string) *flow.LeakyBucket {
return nil
}
func TestDistributedRateLimiter_LocalRateLimiter(t *testing.T) {
r := require.New(t)
// simulate connection refused
db := redis.NewClient(&redis.Options{Addr: "[::1]:14045"})
mock := &mockRateLimiter{}
var localLimiter flow.RateLimiter = mock
limiter := flow.NewRedisRateLimiter(db,
flow.WithFallbackToLocal(localLimiter),
)
r.Equal(false, limiter.IsStart())
r.Equal(false, mock.IsStop)
limiter.Start()
r.Equal(true, limiter.IsStart())
limiter.Stop()
r.Equal(false, limiter.IsStart())
r.Equal(true, mock.IsStop)
}
func TestDistributedRateLimiter_LocalRateLimiter_IsHitLimit(t *testing.T) {
r := require.New(t)
// simulate connection refused
db := redis.NewClient(&redis.Options{Addr: "[::1]:14045"})
mock := &mockRateLimiter{}
var localLimiter flow.Limiter = mock
limiter := flow.NewRedisRateLimiter(db,
flow.WithFallbackToLocal(localLimiter),
)
r.Equal(0, mock.IsHitLimitCounter)
isHitLimit := limiter.IsHitLimit("random", 1, 1)
// first hit will got limit
r.Equal(true, isHitLimit)
r.Equal(0, mock.IsHitLimitCounter)
isHitLimit = limiter.IsHitLimit("random", 1, 1)
// second hit will use local rate limiter
r.Equal(false, isHitLimit)
r.Equal(1, mock.IsHitLimitCounter)
}
|
package models
type HttpConfig struct {
Server struct {
Name string `json:"name"`
DocumentRoot string `json:"documentroot"`
EntryPoint string `json:"entrypoint"`
} `json:"server"`
}
|
package leetcode
/*Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
func findTheDifference(s string, t string) byte {
sMap := [26]int{}
tMap := [26]int{}
for i := 0; i < len(s); i++ {
sMap[int(s[i]-'a')]++
tMap[int(t[i]-'a')]++
}
tMap[int(t[len(t)-1]-'a')]++
for i := 0; i < 26; i++ {
if sMap[i] != tMap[i] {
return 'a' + byte(i)
}
}
return '#'
}
|
package pathfileops
import (
"errors"
"fmt"
)
// FileOps - This type is used to manage and coordinate various
// operations performed on files. Hence the name, File Operations.
//
type FileOps struct {
isInitialized bool
source FileMgr
destination FileMgr
opToExecute FileOperationCode
}
// CopyOut - Returns a deep copy of the current
// FileOps instance.
//
func (fops *FileOps) CopyOut() FileOps {
if !fops.isInitialized {
return FileOps{}
}
newFOps := FileOps{}
newFOps.source = fops.source.CopyOut()
newFOps.destination = fops.destination.CopyOut()
newFOps.opToExecute = fops.opToExecute
newFOps.isInitialized = true
return newFOps
}
// Equal - Returns 'true' if source, destination and opToExecute are
// equivalent. In other words both the current File Operations instance
// and the File Operations instance passed as an input parameter must
// have data fields which are equal in all respects.
//
// If any data field is found to be unequal, this method returns 'false'.
func (fops *FileOps) Equal(fops2 *FileOps) bool {
if !fops.source.Equal(&fops2.source) {
return false
}
if !fops.destination.Equal(&fops2.destination) {
return false
}
if fops.opToExecute != fops2.opToExecute {
return false
}
return true
}
// EqualPathFileNameExt - Compares two File Operations Types, 'FileOps'. The method
// returns 'true' if source and destination absolute paths, file
// names and file extensions are equivalent. Data Field 'opToExecute' is
// not included in the comparison.
//
// The absolute path, file name and file extension comparisons are case
// insensitive. This means that all strings used in the comparisons are
// first converted to lower case before testing for equivalency.
//
// If the absolute paths, file names and file extensions are NOT equal,
// this method returns 'false'.
func (fops *FileOps) EqualPathFileNameExt(fops2 *FileOps) bool {
if !fops.source.EqualPathFileNameExt(&fops2.source) {
return false
}
if !fops.destination.EqualPathFileNameExt(&fops2.destination) {
return false
}
return true
}
// IsInitialized - Returns a boolean value indicating whether
// this FileOps instance has been properly initialized.
//
func (fops *FileOps) IsInitialized() bool {
return fops.isInitialized
}
// ExecuteFileOperation - Executes specific operations on the source
// and/or destination files configured and identified in the current
// FileOps instance.
//
// ------------------------------------------------------------------------
//
// Input Parameters:
//
// FileOperationCode
//
// The FileOperationCode type consists of the following
// constants.
//
// FileOperationCode(0).MoveSourceFileToDestinationFile()
// Moves the source file to the destination file and
// then deletes the original source file
//
// FileOperationCode(0).DeleteDestinationFile()
// Deletes the Destination file if it exists
//
// FileOperationCode(0).DeleteSourceFile()
// Deletes the Source file if it exists
//
// FileOperationCode(0).DeleteSourceAndDestinationFiles
// Deletes both the Source and Destination files
// if they exist.
//
// FileOperationCode(0).CopySourceToDestinationByHardLinkByIo()
// Copies the Source File to the Destination
// using two copy attempts. The first copy is
// by Hard Link. If the first copy attempt fails,
// a second copy attempt is initiated/ by creating
// a new file and copying the contents by 'io.Copy'.
// An error is returned only if both copy attempts
// fail. The source file is unaffected.
//
// See: https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
//
//
// FileOperationCode(0).CopySourceToDestinationByIoByHardLink()
// Copies the Source File to the Destination
// using two copy attempts. The first copy is
// by 'io.Copy' which creates a new file and copies
// the contents to the new file. If the first attempt
// fails, a second copy attempt is initiated using
// 'copy by hard link'. An error is returned only
// if both copy attempts fail. The source file is
// unaffected.
//
// See: https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
//
//
// FileOperationCode(0).CopySourceToDestinationByHardLink()
// Copies the Source File to the Destination
// using one copy mode. The only copy attempt
// utilizes 'Copy by Hard Link'. If this fails
// an error is returned. The source file is
// unaffected.
//
// FileOperationCode(0).CopySourceToDestinationByIo()
// Copies the Source File to the Destination
// using only one copy mode. The only copy
// attempt is initiated using 'Copy by IO' or
// 'io.Copy'. If this fails an error is returned.
// The source file is unaffected.
//
// FileOperationCode(0).CreateSourceDir()
// Creates the Source Directory
//
// FileOperationCode(0).CreateSourceDirAndFile()
// Creates the Source Directory and File
//
// FileOperationCode(0).CreateSourceFile()
// Creates the Source File
//
// FileOperationCode(0).CreateDestinationDir()
// Creates the Destination Directory
//
// FileOperationCode(0).CreateDestinationDirAndFile()
// Creates the Destination Directory and File
//
// FileOperationCode(0).CreateDestinationFile()
// Creates the Destination File
//
func (fops *FileOps) ExecuteFileOperation(fileOp FileOperationCode) error {
ePrefix := "FileOps.ExecuteFileOperation() "
fops.opToExecute = fileOp
var err error
err = nil
switch fops.opToExecute {
case fileOpCode.None():
err = errors.New("Error: Input parameter 'fileOp' is 'NONE' or No Operation!")
case fileOpCode.MoveSourceFileToDestinationDir():
err = fops.moveSourceFileToDestinationDir()
case fileOpCode.MoveSourceFileToDestinationFile():
err = fops.moveSourceFileToDestinationFile()
case fileOpCode.DeleteDestinationFile():
err = fops.deleteDestinationFile()
case fileOpCode.DeleteSourceFile():
err = fops.deleteSourceFile()
case fileOpCode.DeleteSourceAndDestinationFiles():
err = fops.deleteSourceAndDestinationFiles()
case fileOpCode.CopySourceToDestinationByHardLinkByIo():
err = fops.copySrcToDestByHardLinkByIo()
case fileOpCode.CopySourceToDestinationByIoByHardLink():
err = fops.copySrcToDestByIoByHardLink()
case fileOpCode.CopySourceToDestinationByHardLink():
err = fops.copySrcToDestByHardLink()
case fileOpCode.CopySourceToDestinationByIo():
err = fops.copySrcToDestByIo()
case fileOpCode.CreateSourceDir():
err = fops.createSrcDirectory()
case fileOpCode.CreateSourceDirAndFile():
err = fops.createSrcDirectoryAndFile()
case fileOpCode.CreateSourceFile():
err = fops.createSrcFile()
case fileOpCode.CreateDestinationDir():
err = fops.createDestDirectory()
case fileOpCode.CreateDestinationDirAndFile():
err = fops.createDestDirectoryAndFile()
case fileOpCode.CreateDestinationFile():
err = fops.createDestFile()
default:
err = errors.New("Invalid 'FileOperationCode' Execution Command! ")
}
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// GetSource - Returns a deep copy of the
// source FileMgr instance.
func (fops *FileOps) GetSource() FileMgr {
return fops.source.CopyOut()
}
// GetSource - Returns a deep copy of the
// destination FileMgr instance.
func (fops *FileOps) GetDestination() FileMgr {
return fops.destination.CopyOut()
}
// NewByFileMgrs - Creates and returns a new FileOps
// instance based on input parameters 'source' and
// 'destination' File Managers.
//
func (fops FileOps) NewByFileMgrs(
source,
destination FileMgr) (FileOps, error) {
ePrefix := "FileOps.NewByFileMgrs() "
err := source.IsFileMgrValid(ePrefix + "sourceFileMgr Error: ")
if err != nil {
return FileOps{},
fmt.Errorf("Source File Manager INVALID!\n%v", err.Error())
}
err = destination.IsFileMgrValid(ePrefix + "destinationFileMgr Error: ")
if err != nil {
return FileOps{},
fmt.Errorf("Destination File Manager INVALID!\n%v", err.Error())
}
fOpsNew := FileOps{}
fOpsNew.source = source.CopyOut()
fOpsNew.destination = destination.CopyOut()
fOpsNew.isInitialized = true
return fOpsNew, nil
}
// NewByDirMgrFileName - Creates and returns a new FileOps instance
// based on input parameters, source Directory Manger, source file name
// and extension string, destination Directory Manager and destination
// file name and extension string.
//
// If the destinationFileNameExt string is an empty string, it will default
// to the 'sourceFileNameExt'
func (fops FileOps) NewByDirMgrFileName(
sourceDir DirMgr,
sourceFileNameExt string,
destinationDir DirMgr,
destinationFileNameExt string) (FileOps, error) {
ePrefix := "FileOps.NewByDirMgrFileName() "
var err error
fOpsNew := FileOps{}
err = sourceDir.IsDirMgrValid(ePrefix + "sourceDir Error: ")
if err != nil {
return FileOps{}, err
}
fOpsNew.source, err = FileMgr{}.NewFromDirMgrFileNameExt(sourceDir, sourceFileNameExt)
if err != nil {
return FileOps{},
fmt.Errorf(ePrefix+"Source File Error:\n%v\n", err.Error())
}
if len(destinationFileNameExt) == 0 {
destinationFileNameExt = sourceFileNameExt
}
err = destinationDir.IsDirMgrValid(ePrefix + "destinationDir Error: ")
if err != nil {
return FileOps{}, err
}
fOpsNew.destination, err = FileMgr{}.NewFromDirMgrFileNameExt(destinationDir, destinationFileNameExt)
if err != nil {
return FileOps{},
fmt.Errorf(ePrefix+"Destination File Error: %v", err.Error())
}
fOpsNew.isInitialized = true
return fOpsNew, nil
}
// NewByDirStrsAndFileNameExtStrs - Creates and returns a new FileOps instance
// based on source and destination input parameters which consist of two pairs
// of directory or path strings and file name and extension strings.
//
// If the input parameter, 'destinationFileNameExtStr' is an empty string, it
// will be defaulted to a string value equal to 'sourceFileNameExtStr'.
//
func (fops FileOps) NewByDirStrsAndFileNameExtStrs(
sourceDirStr string,
sourceFileNameExtStr string,
destinationDirStr string,
destinationFileNameExtStr string) (FileOps, error) {
ePrefix := "FileOps.NewByPathFileNameExtStrs() "
fOpsNew := FileOps{}
var err error
if len(sourceDirStr) == 0 {
return FileOps{}, errors.New(ePrefix + "Error: 'sourceDirStr' is an EMPTY STRING!")
}
if len(sourceFileNameExtStr) == 0 {
return FileOps{}, errors.New(ePrefix + "Error: 'sourceFileNameExtStr' is an EMPTY STRING!")
}
if len(destinationFileNameExtStr) == 0 {
destinationFileNameExtStr = sourceFileNameExtStr
}
fOpsNew.source, err = FileMgr{}.NewFromDirStrFileNameStr(sourceDirStr, sourceFileNameExtStr)
if err != nil {
return FileOps{},
fmt.Errorf(ePrefix+"Source File Error: %v", err.Error())
}
fOpsNew.destination, err = FileMgr{}.NewFromDirStrFileNameStr(destinationDirStr, destinationFileNameExtStr)
if err != nil {
return FileOps{},
fmt.Errorf(ePrefix+"Destination File Error: %v", err.Error())
}
fOpsNew.isInitialized = true
return fOpsNew, nil
}
// NewByPathFileNameExtStrs - Creates and returns a new FileOps instance
// based on two string input parameters. The first represents the path name,
// file name and extension of the source file. The second represents the
// path name, file name and extension of the destination file.
//
func (fops FileOps) NewByPathFileNameExtStrs(
sourcePathFileNameExt string,
destinationPathFileNameExt string) (FileOps, error) {
ePrefix := "FileOps.NewByPathFileNameExtStrs() "
fOpsNew := FileOps{}
var err error
fOpsNew.source, err = FileMgr{}.NewFromPathFileNameExtStr(sourcePathFileNameExt)
if err != nil {
return FileOps{},
fmt.Errorf(ePrefix+"Source File Error: %v", err.Error())
}
fOpsNew.destination, err = FileMgr{}.NewFromPathFileNameExtStr(destinationPathFileNameExt)
if err != nil {
return FileOps{},
fmt.Errorf(ePrefix+"Destination File Error: %v", err.Error())
}
fOpsNew.isInitialized = true
return fOpsNew, nil
}
// SetFileOpsCode - Sets the File Operations code for the current FileOps
// instance.
//
func (fops *FileOps) SetFileOpsCode(fOpCode FileOperationCode) error {
err := fOpCode.IsValid()
if err != nil {
return fmt.Errorf("FileOps.SetFileOpsCode()\n" +
"Error returned by fOpCode.IsValid()\nError='%v'", err.Error())
}
fops.opToExecute = fOpCode
return nil
}
// deleteDestinationFile - Deletes the destination file in the
// current FileOps instance.
func (fops *FileOps) deleteDestinationFile() error {
ePrefix := "FileOps.deleteDestinationFile() Destination Deletion Failed: "
err := fops.destination.DeleteThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// deleteSourceFile - Deletes the source file in the current
// FileOps instance.
func (fops *FileOps) deleteSourceFile() error {
ePrefix := "FileOps.FileOperationCode(0).DeleteSourceFile()() Source Deletion Failed: "
err := fops.source.DeleteThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// deleteSourceAndDestinationFiles - Deletes both the source
// and destination files configured in the current FileOps
// instance.
func (fops *FileOps) deleteSourceAndDestinationFiles() error {
cumErrMsg := "FileOps.FileOperationCode(0).DeleteSourceAndDestinationFiles()- "
cumErrLen := len(cumErrMsg)
err := fops.destination.DeleteThisFile()
if err != nil {
cumErrMsg += "Destination Deletion Failed: " + err.Error() + "\n"
}
err = fops.source.DeleteThisFile()
if err != nil {
cumErrMsg += "Source Deletion Failed: " + err.Error() + "\n"
}
if len(cumErrMsg) != cumErrLen {
return errors.New(cumErrMsg)
}
return nil
}
func (fops *FileOps) copySrcToDestByIoByHardLink() error {
ePrefix := "FileOps.copySrcToDestByIoByHardLink() "
err := fops.source.CopyFileMgrByIoByLink(&fops.destination)
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
func (fops *FileOps) copySrcToDestByHardLinkByIo() error {
ePrefix := "FileOps.copySrcToDestByHardLinkByIo() "
err := fops.source.CopyFileMgrByLinkByIo(&fops.destination)
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// copySrcToDestByIo - Copies source file to destination
// using IO.
//
func (fops *FileOps) copySrcToDestByIo() error {
ePrefix := "FileOps.copySrcToDestByIo() "
err := fops.source.CopyFileMgrByIo(&fops.destination)
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
func (fops *FileOps) copySrcToDestByHardLink() error {
ePrefix := "FileOps.copySrcToDestByHardLink() "
err := fops.source.CopyFileMgrByLink(&fops.destination)
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// createSrcDirectory - Creates the source directory using
// information from the FileOps source file manager.
//
func (fops *FileOps) createSrcDirectory() error {
ePrefix := "FileOps.createSrcDirectory() "
err := fops.source.CreateDir()
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// createSrcDirectoryAndFile - Creates the source file
// and directory using information from the FileOps
// source file manager.
//
func (fops *FileOps) createSrcDirectoryAndFile() error {
ePrefix := "FileOps.createSrcDirectoryAndFile() "
err := fops.source.CreateDirAndFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
err = fops.source.CloseThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
// createSrcFile - Creates the source file using
// information from the FileOps source file manager.
//
func (fops *FileOps) createSrcFile() error {
ePrefix := "FileOps.createSrcFile() "
err := fops.source.CreateThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
err = fops.source.CloseThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
// createDestDirectory - Creates the destination
// directory using information from the FileOps
// destination file manager.
//
func (fops *FileOps) createDestDirectory() error {
ePrefix := "FileOps.createSrcDirectory() "
err := fops.destination.CreateDir()
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
return nil
}
// createDestDirectoryAndFile - Creates the destination
// directory and file using information from the FileOps
// destination file manager.
//
func (fops *FileOps) createDestDirectoryAndFile() error {
ePrefix := "FileOps.createDestDirectoryAndFile() "
err := fops.destination.CreateDirAndFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
err = fops.destination.CloseThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
// createDestFile - Creates the destination file using
// information from the FileOps destination file manager.
//
func (fops *FileOps) createDestFile() error {
ePrefix := "FileOps.createDestFile() "
err := fops.destination.CreateThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v", err.Error())
}
err = fops.destination.CloseThisFile()
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
// moveSourceFileFileToDestinationDir - Moves the source file
// to the destination directory. The file name will be designated
// by the destination file name.
//
func (fops *FileOps) moveSourceFileToDestinationDir() error {
ePrefix := "FileOps.moveSourceFileToDestinationDir() "
_, err := fops.source.MoveFileToNewDirMgr(fops.destination.GetDirMgr())
if err != nil {
return fmt.Errorf(ePrefix + "%v\n",
err.Error())
}
return nil
}
// moveSourceFileToDestinationFile - Moves the source file
// to the destination by fist copying the source file
// to the destination and then deleting the source file.
//
// The final final name will be the destination file in the
// destination directory.
//
func (fops *FileOps) moveSourceFileToDestinationFile() error {
ePrefix := "FileOps.moveSourceFileToDestinationFile() "
err := fops.source.MoveFileToFileMgr(fops.destination)
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//674. Longest Continuous Increasing Subsequence
//Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
//Example 1:
//Input: [1,3,5,4,7]
//Output: 3
//Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
//Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.
//Example 2:
//Input: [2,2,2,2,2]
//Output: 1
//Explanation: The longest continuous increasing subsequence is [2], its length is 1.
//Note: Length of the array will not exceed 10,000.
//func findLengthOfLCIS(nums []int) int {
//}
// Time Is Money |
package main
import (
"sort"
"sync"
"time"
)
var (
popularHoldTime = int64(5)
popularWordMgr = &PopularWordMgr{
popularWords: map[int64](map[string]int){},
}
)
type WordUnit struct {
Word string
Count int
}
type PopularWordMgr struct {
sync.RWMutex
popularWords map[int64](map[string]int)
}
func (mgr *PopularWordMgr) clear() {
curTime := time.Now().Unix()
if len(mgr.popularWords) > int(popularHoldTime) {
oldTime := curTime - 1
mgr.Lock()
_, have := mgr.popularWords[oldTime]
if have {
delete(mgr.popularWords, oldTime)
}
mgr.Unlock()
}
}
func (mgr *PopularWordMgr) add(msg string) {
curTime := time.Now().Unix()
mgr.Lock()
words, have := mgr.popularWords[curTime]
if have {
words[msg] += 1
} else {
mgr.popularWords[curTime] = map[string]int{msg: 1}
}
mgr.Unlock()
mgr.clear()
}
func (mgr *PopularWordMgr) get() []string {
curTime := time.Now().Unix()
start := curTime - popularHoldTime
tempWord := map[string]int{}
mgr.Lock()
for i := start + 1; i <= curTime; i++ {
words, have := mgr.popularWords[i]
if have {
for word, sum := range words {
_, have := tempWord[word]
if have {
tempWord[word] += sum
} else {
tempWord[word] = sum
}
}
}
}
mgr.Unlock()
if len(tempWord) == 0 {
return nil
}
verb := []WordUnit{}
for word, sum := range tempWord {
verb = append(verb, WordUnit{Word: word, Count: sum})
}
sort.Slice(verb, func(i, j int) bool {
return verb[i].Count > verb[j].Count
})
top10 := []string{}
for i := 0; i < len(verb) && i < 10; i++ {
top10 = append(top10, verb[i].Word)
}
return top10
}
|
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package ircsetup
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"syscall"
"golang.org/x/crypto/ssh/terminal"
"github.com/fatih/color"
"github.com/goshuirc/bnc/lib"
)
var (
CbBlue = color.New(color.Bold, color.FgHiBlue).SprintfFunc()
CbCyan = color.New(color.Bold, color.FgHiCyan).SprintfFunc()
CbYellow = color.New(color.Bold, color.FgHiYellow).SprintfFunc()
CbRed = color.New(color.Bold, color.FgHiRed).SprintfFunc()
)
// Section displays a section to the user
func Section(text string) {
Note("")
fmt.Println(CbBlue("["), CbYellow("**"), CbBlue("]"), "--", text, "--")
Note("")
}
// Note displays a note to the user
func Note(text string) {
fmt.Println(CbBlue("["), CbYellow("**"), CbBlue("]"), text)
}
// Query asks for a value from the user
func Query(prompt string) (string, error) {
fmt.Print(CbBlue("[ "), CbYellow("??"), CbBlue(" ] "), prompt)
in := bufio.NewReader(os.Stdin)
response, err := in.ReadString('\n')
return strings.TrimRight(response, "\r\n"), err
}
// QueryNoEcho asks for a value from the user without echoing what they type
func QueryNoEcho(prompt string) (string, error) {
fmt.Print(CbBlue("[ "), CbYellow("??"), CbBlue(" ] "), prompt)
response, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Print("\n")
return string(response), err
}
// QueryDefault asks for a value, falling back to a default
func QueryDefault(prompt string, defaultValue string) (string, error) {
response, err := Query(prompt)
if err != nil {
return "", err
}
if len(strings.TrimSpace(response)) < 1 {
return defaultValue, nil
}
return response, nil
}
// QueryBool asks for a true/false value from the user
func QueryBool(prompt string) (bool, error) {
for {
response, err := Query(prompt)
if err != nil {
return false, err
}
response = strings.ToLower(strings.TrimSpace(response))
if len(response) < 1 {
continue
}
// check for yes/true/1 or no/false/0
if strings.Contains("yt1", string(response[0])) {
return true, nil
} else if strings.Contains("nf0", string(response[0])) {
return false, nil
}
}
}
// Warn warns the user about something
func Warn(text string) {
fmt.Println(CbBlue("["), CbRed("**"), CbBlue("]"), text)
}
// Error shows the user an error
func Error(text string) {
fmt.Println(CbBlue("["), CbRed("!!"), CbBlue("]"), CbRed(text))
}
// InitialSetup performs the initial GoshuBNC setup
func InitialSetup(manager *ircbnc.Manager) {
fmt.Println(CbBlue("["), CbCyan("~~"), CbBlue("]"), "Welcome to", CbCyan("GoshuBNC"))
Note("We will now run through basic setup.")
data := manager.Ds
var err error
data.Setup()
Section("Admin user settings")
var username string
var password string
var ircNick string
var ircFbNick string // fallback nick
var ircUser string
var ircReal string
for {
inputUsername, err := Query("Username: ")
if err != nil {
log.Fatal(err.Error())
}
inputUsername = strings.TrimSpace(inputUsername)
inputUsername, err = ircbnc.BncName(inputUsername)
if err == nil {
username = inputUsername
Note(fmt.Sprintf("Username is %s.", username))
break
} else {
Error(err.Error())
}
}
// Read the password
for {
newPassword, err := QueryNoEcho("Enter password: ")
if err != nil {
Error(fmt.Sprintf("Error reading input line: %s", err.Error()))
continue
}
passwordCompare, err := QueryNoEcho("Confirm password: ")
if err != nil {
Error(fmt.Sprintf("Error reading input line: %s", err.Error()))
continue
}
if newPassword != passwordCompare {
Warn("The supplied passwords do not match")
continue
}
password = newPassword
break
}
// Get IRC details
for {
ircNick, err = QueryDefault(fmt.Sprintf("Enter Nickname [%s]: ", username), username)
if err != nil {
log.Fatal(err.Error())
}
ircNick, err = ircbnc.IrcName(ircNick, false)
if err == nil {
break
} else {
Error(err.Error())
}
}
defaultFallbackNick := fmt.Sprintf("%s_", ircNick)
for {
ircFbNick, err = QueryDefault(fmt.Sprintf("Enter Fallback Nickname [%s]: ", defaultFallbackNick), defaultFallbackNick)
if err != nil {
log.Fatal(err.Error())
}
ircFbNick, err = ircbnc.IrcName(ircFbNick, false)
if err == nil {
break
} else {
Error(err.Error())
}
}
for {
ircUser, err = QueryDefault(fmt.Sprintf("Enter Username [%s]: ", username), username)
if err != nil {
log.Fatal(err.Error())
}
ircUser, err = ircbnc.IrcName(ircUser, false)
if err == nil {
break
} else {
Error(err.Error())
}
}
ircReal, err = Query("Enter Realname: ")
if err != nil {
log.Fatal(err.Error())
}
user := ircbnc.NewUser(manager)
user.Name = username
user.Role = "Owner"
user.DefaultNick = ircNick
user.DefaultFbNick = ircFbNick
user.DefaultUser = ircUser
user.DefaultReal = ircReal
user.Permissions = []string{"*"}
data.SetUserPassword(user, password)
err = data.SaveUser(user)
if err != nil {
log.Fatal(fmt.Sprintf("Could not create user info in database: %s", err.Error()))
return
}
// now setup default networks for that user
Section("Network Setup")
for {
setupNewNet, err := QueryBool("Set up a network? (y/n) ")
if err != nil {
log.Fatal(err.Error())
}
if !setupNewNet {
break
}
var goodNetName string
for {
netName, err := Query("Name (e.g. freenode): ")
if err != nil {
log.Fatal(err.Error())
}
goodNetName, err = ircbnc.BncName(netName)
if err == nil {
Note(fmt.Sprintf("Network name is %s. Will be stored internally as %s.", netName, goodNetName))
break
} else {
Error(err.Error())
}
}
var serverAddress string
for {
serverAddress, err = Query("Server host (e.g. chat.freenode.net): ")
if err != nil {
log.Fatal(err.Error())
}
if len(strings.TrimSpace(serverAddress)) < 1 {
Error("Hostname must have at least one character!")
continue
}
break
}
serverUseTLS, err := QueryBool("Server uses SSL/TLS? (y/n) ")
if err != nil {
log.Fatal(err.Error())
}
var serverVerifyTLS bool
if serverUseTLS {
serverVerifyTLS, err = QueryBool("Verify SSL/TLS certificates? (y/n) ")
if err != nil {
log.Fatal(err.Error())
}
}
var defaultPort int
if serverUseTLS {
defaultPort = 6697
} else {
defaultPort = 6667
}
var serverPort int
for {
portString, err := QueryDefault(fmt.Sprintf("Server Port [%d]: ", defaultPort), strconv.Itoa(defaultPort))
if err != nil {
log.Fatal(err.Error())
}
serverPort, err = strconv.Atoi(portString)
if err != nil {
Error(err.Error())
continue
}
if (serverPort < 1) || (serverPort > 65535) {
Error("Port number can be 1 - 65535")
continue
}
break
}
serverPass, err := Query("Server connection password (probably empty): ")
if err != nil {
log.Fatal(err.Error())
}
//TODO(dan): this should be NewServerConnectionBuffers()
serverChannels := make(ircbnc.ServerConnectionBuffers)
for {
serverChannelsString, err := Query("Channels to autojoin (separated by spaces): ")
if err != nil {
log.Fatal(err.Error())
}
for _, channel := range strings.Fields(serverChannelsString) {
channel, err := ircbnc.IrcName(channel, true)
if err != nil {
break
}
serverChannels.Add(&ircbnc.ServerConnectionBuffer{
Channel: true,
Name: channel,
})
}
if err != nil {
Error(err.Error())
continue
}
break
}
connection := ircbnc.NewServerConnection()
connection.User = user
connection.Name = goodNetName
connection.Password = serverPass
newAddress := ircbnc.ServerConnectionAddress{
Host: serverAddress,
Port: serverPort,
UseTLS: serverUseTLS,
VerifyTLS: serverVerifyTLS,
}
connection.Addresses = append(connection.Addresses, newAddress)
for _, channel := range serverChannels {
connection.Buffers[channel.Name] = channel
}
err = connection.Save()
if err != nil {
log.Fatal(fmt.Sprintf("Could not create server connection [%s] in database: %s", goodNetName, err.Error()))
return
}
}
fmt.Println(CbBlue("["), CbCyan("~~"), CbBlue("]"), CbCyan("GoshuBNC"), "is now configured!")
Note("You can now launch GoshuBNC and connect to it with your IRC client")
}
|
package main
import "fmt"
type Weight int
type Edges []EdgeStructure
type EdgeStructure struct {
v, w int
weight Weight
}
type Graph struct { // adj array graph
vertexNum int
edgeArray [][]Weight
}
func (e Edges) QuickSort(left, right int) {
pivot := right
l := left
r := right - 1
swap := func(a, b int) {
temp := e[a]
e[a] = e[b]
e[b] = temp
}
fmt.Println("function called", l, r)
for l <= r {
fmt.Println(l, r)
for l <= r && e[l].weight < e[pivot].weight {
l++
fmt.Println("l :", l)
}
for r >= l && e[r].weight > e[pivot].weight {
r--
fmt.Println("r :", r)
}
if l < r {
swap(l, r)
l++
r--
fmt.Println("swap", l, r)
}
}
swap(l, pivot)
if left < l-1 {
e.QuickSort(left, l-1)
}
if right > l+1 {
e.QuickSort(l+1, right)
}
}
func (e Edges) testQuicksort() {
e.QuickSort(0, len(e)-1)
fmt.Println(e)
}
func (g *Graph) Graph(n int) {
g.vertexNum = n
g.edgeArray = make([][]Weight, n)
for i := 0; i < n; i++ {
g.edgeArray[i] = make([]Weight, n)
}
}
func MinMax(x, y int) (min, max int) {
if x > y {
max = x
min = y
} else {
max = y
min = x
}
return
}
func (g *Graph) InsertEdge(v, w int, weight Weight) {
if v == w {
fmt.Printf(" %d == %d", v, w)
return
}
min, max := MinMax(v, w)
g.edgeArray[min][max] = weight
}
func (g Graph) kruskal() (mst Graph) {
mst.Graph(g.vertexNum)
//================================================================================
edges := Edges{}
for i := 0; i < g.vertexNum; i++ {
for j := 0; j < g.vertexNum; j++ {
if g.edgeArray[i][j] != 0 {
edges = append(edges, EdgeStructure{i, j, g.edgeArray[i][j]})
}
}
}
//edges sort ascending
fmt.Println(edges)
edges.QuickSort(0, len(edges)-1)
fmt.Println("sorting done")
//================================================================================
// 힙으로 바꿀 것
//union-find
var edgeCount int
var parent = []int{}
var setSize = []int{}
const (
ROOT = -1
)
func() {
for i := 0; i < mst.vertexNum; i++ {
parent = append(parent, ROOT)
setSize = append(setSize, 1)
}
}()
find := func(a int) int {
root := a
for parent[root] != ROOT {
root = parent[root]
}
var p int
i := a
for parent[i] != ROOT {
p = parent[i]
parent[i] = root
i = p
}
return root
}
union := func(a, b int) {
if setSize[a] > setSize[b] {
parent[b] = a
setSize[a] += setSize[b]
} else {
parent[a] = b
setSize[b] += setSize[a]
}
}
for i := 0; edgeCount < mst.vertexNum-1; i++ {
if find(edges[i].v) != find(edges[i].w) {
mst.InsertEdge(edges[i].v, edges[i].w, edges[i].weight)
union(edges[i].v, edges[i].w)
edgeCount++
}
}
return
}
func main() {
var g Graph
g.Graph(5)
fmt.Println("graph init")
g.InsertEdge(0, 1, 10)
g.InsertEdge(0, 3, 8)
g.InsertEdge(0, 2, 5)
g.InsertEdge(1, 4, 9)
g.InsertEdge(1, 3, 3)
g.InsertEdge(2, 4, 6)
g.InsertEdge(3, 4, 2)
fmt.Println(g)
fmt.Println("edge insertion done")
mst := g.kruskal()
fmt.Println(mst)
}
|
/*
Write the shortest code that traverses a directory tree and outputs a flat list of all files.
It should traverse the whole directory tree
The order in which it enters sub-directories doesn't matter
The directories should not be output
The output should be a plain list — the definition is flexible, but it shouldn't contain irrelevant data
You are free to use any programming technique
*/
package main
import (
"flag"
"fmt"
"io/fs"
"os"
"path/filepath"
)
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
usage()
}
filepath.Walk(flag.Arg(0), walk)
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [options] <path>")
flag.PrintDefaults()
os.Exit(2)
}
func walk(path string, info fs.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
} else {
fmt.Println(path)
}
return nil
}
|
package catm
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00400104 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catm.004.001.04 Document"`
Message *TerminalManagementRejectionV04 `xml:"TermnlMgmtRjctn"`
}
func (d *Document00400104) AddMessage() *TerminalManagementRejectionV04 {
d.Message = new(TerminalManagementRejectionV04)
return d.Message
}
// The TerminalManagementRejection message is sent by the terminal manager to reject a message request sent by an acceptor, to indicate that the received message could not be processed.
type TerminalManagementRejectionV04 struct {
// Rejection message management information.
Header *iso20022.Header28 `xml:"Hdr"`
// Information related to the reject.
Reject *iso20022.AcceptorRejection3 `xml:"Rjct"`
}
func (t *TerminalManagementRejectionV04) AddHeader() *iso20022.Header28 {
t.Header = new(iso20022.Header28)
return t.Header
}
func (t *TerminalManagementRejectionV04) AddReject() *iso20022.AcceptorRejection3 {
t.Reject = new(iso20022.AcceptorRejection3)
return t.Reject
}
|
package main
import "fmt"
func main() {
loop(3)
fmt.Println(c())
}
func c() (i int) {
x := 0
defer func() { x++ }()
return 2
}
func loop(x int) {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i)
if(i == x) {
return
}
}
defer fmt.Println("done")
}
|
package handlers
import (
"net/http"
"github.com/saurabmish/Coffee-Shop/data"
)
func (p Products) Add(w http.ResponseWriter, r *http.Request) {
p.l.Println("[INFO] Endpoint for POST request")
product := r.Context().Value(KeyProduct{}).(data.Product)
p.l.Println("[DEBUG] Adding product to list")
data.AddProduct(&product)
w.WriteHeader(http.StatusCreated)
data.ToJSON(&GenericError{Message: "Product created successfully!"}, w)
}
|
package example
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ocsp"
"io/ioutil"
"testing"
"time"
)
var (
pwd = "123456"
caKeyPem = `-----BEGIN ECC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,57600d03c7bc2b496c3e301ad1037b89
8EoWxS2hyM9ftM8Q4R7vM3zuMt2q8QpiFP7irOY9jgmSSHBDO21uDyW93V+59O8c
6UR9NpNi8F0w5lP4xXkjdtDb6S25tEitrPMBGWnbnIGkqrUl1PLXa9dLtRxVMxYM
IJfC9eLFFIqcQVAEU6VJ2tD7oikFd89/RhZQ9F5rVFs=
-----END ECC PRIVATE KEY-----
-----BEGIN ECC PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEUQMFuiWK6enMEZuGr7yoMXxaJ2OF42be
ufKu/XTDIwNEFjf64iaTgdlfinWQ1fcRQOypoyEulQhSjxw0E8Nauw==
-----END ECC PUBLIC KEY-----
`
caCertPem = `-----BEGIN CERTIFICATE-----
MIIB0TCCAXigAwIBAgIRANz9PDono0ejr34Uad02c+MwCgYIKoZIzj0EAwIwSjEP
MA0GA1UEBgwG5Lit5Zu9MQ8wDQYDVQQKDAbnu4Tnu4cxFTATBgNVBAsMDOe7hOe7
h+WNleS9jTEPMA0GA1UEAwwG5L2g5aW9MB4XDTIwMDcxNzA1MjcyNloXDTMwMDcx
NTA1MjcyNlowSjEPMA0GA1UEBgwG5Lit5Zu9MQ8wDQYDVQQKDAbnu4Tnu4cxFTAT
BgNVBAsMDOe7hOe7h+WNleS9jTEPMA0GA1UEAwwG5L2g5aW9MFYwEAYHKoZIzj0C
AQYFK4EEAAoDQgAEUQMFuiWK6enMEZuGr7yoMXxaJ2OF42beufKu/XTDIwNEFjf6
4iaTgdlfinWQ1fcRQOypoyEulQhSjxw0E8Nau6NCMEAwDgYDVR0PAQH/BAQDAgGW
MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0RBBYwFIESY2MxNDUxNEBpY2xvdWQuY29t
MAoGCCqGSM49BAMCA0cAMEQCIFc5QiMK73yh3NoU96sEGYwDmLhKvS+ZrchZWyAh
lT10AiACJH/zgPVYzul5zhsOq9vc3vuRSZ+fX7FS7TFDBMuTWA==
-----END CERTIFICATE-----
`
userKeyPem = `-----BEGIN ECC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,909ca5b2066d18932a3074058e20f1fd
VSEu1tS4jKptoXO8AByRvRBTGx6NZMCBliwT4DlmsbkJXv6EZQBVqnkxr8DM8mOp
P94NS7z2IYxPjDT/t5wG7KIYts/hIwo6BvM7kzEkMws2cpBlMTkWLTPvmarkl54p
JWI3OZOFCPYPpsgTnKgYpB0Kq/MU7EYgFkBTqXZdYp8=
-----END ECC PRIVATE KEY-----
-----BEGIN ECC PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEmrgTlwGqepeCgGjg+HIryk9NqsG3hLp4
LXMHorL17955PjDRiubxJooDIJGNsqfxfeeq0UFEzRzbc1F60JM0Xw==
-----END ECC PUBLIC KEY-----
`
userCertPem = `-----BEGIN CERTIFICATE-----
MIIBtjCCAVygAwIBAgIRALcgBnxhpEA0r3XC1OcL4iEwCgYIKoZIzj0EAwIwSjEP
MA0GA1UEBgwG5Lit5Zu9MQ8wDQYDVQQKDAbnu4Tnu4cxFTATBgNVBAsMDOe7hOe7
h+WNleS9jTEPMA0GA1UEAwwG5L2g5aW9MB4XDTIwMDcxNzA1MjcyNloXDTMwMDcx
NTA1MjcyNlowRzEPMA0GA1UEBgwG5Lit5Zu9MRIwEAYDVQQKDAnnsr7mrabpl6gx
DzANBgNVBAsMBuaxn+a5ljEPMA0GA1UEAwwG6ZmI55yfMFYwEAYHKoZIzj0CAQYF
K4EEAAoDQgAEmrgTlwGqepeCgGjg+HIryk9NqsG3hLp4LXMHorL17955PjDRiubx
JooDIJGNsqfxfeeq0UFEzRzbc1F60JM0X6MpMCcwDgYDVR0PAQH/BAQDAgSwMBUG
A1UdEQQOMAyBCmN6QGp3bS5jb20wCgYIKoZIzj0EAwIDSAAwRQIgIaFwCJChgxSM
y7m8b0vNK6tC9ySpq9NifMk2UPqa090CIQDRRllF+O3UGaLwTEBGkyoIl2fBaqdY
wicfuwjfHeYr8A==
-----END CERTIFICATE-----
`
kt = NewKeytool()
prvkeyByPem = func(keyPem, pwd string) *ecdsa.PrivateKey {
prvBlk, _ := pem.Decode([]byte(keyPem))
prvBuf, err := x509.DecryptPEMBlock(prvBlk, []byte(pwd))
if err != nil {
panic(err)
}
prv, err := x509.ParseECPrivateKey(prvBuf)
if err != nil {
panic(err)
}
return prv
}
)
// 创建一个 ECC S256K1 私钥,用于生成证书,以 PEM 格式返回
func TestECCKeytool_GenKey(t *testing.T) {
prv, pub := kt.GenKey(elliptic.S256(), pwd)
fmt.Println(string(prv))
fmt.Println(string(pub))
}
func TestECCKeytool_GenCertForPubkeyForCA(t *testing.T) {
prv := prvkeyByPem(caKeyPem, pwd)
caCert := kt.GenCertForPubkey(prv, nil, prv.Public(), &Subject{
Country: "中国",
OrganizationalUnit: "组织单位",
Organization: "组织",
CommonName: "你好",
Email: "cc14514@icloud.com",
})
fmt.Println(string(caCert))
}
func TestECCKeytool_GenCertForPubkeyForUser(t *testing.T) {
userPrv, userPub := kt.GenKey(elliptic.S256(), pwd)
// 输出用户密钥 >>>>>>>>
fmt.Println(string(userPrv))
fmt.Println(string(userPub))
// 输出用户密钥 <<<<<<<<
// 解析 PEM 公钥 >>>>>>
userPubBlk, _ := pem.Decode(userPub)
ipub, err := x509.ParsePKIXPublicKey(userPubBlk.Bytes)
if err != nil {
panic(err)
}
upub := ipub.(crypto.PublicKey)
t.Log("user pubkey :", upub)
// 解析 PEM 公钥 <<<<<<
// 解析 CA 证书和密钥并对用户 pubkey 签发证书 >>>>
caCertBlk, _ := pem.Decode([]byte(caCertPem))
caCert, err := x509.ParseCertificate(caCertBlk.Bytes)
if err != nil {
panic(err)
}
caPrv := prvkeyByPem(caKeyPem, pwd)
userCertPem := kt.GenCertForPubkey(caPrv, caCert, upub, &Subject{
Country: "中国",
OrganizationalUnit: "江湖",
Organization: "精武门",
CommonName: "陈真",
Email: "cz@jwm.com",
})
fmt.Println(string(userCertPem))
// 解析 CA 证书和密钥并对用户 pubkey 签发证书 <<<<
}
func TestVerifyUserCert(t *testing.T) {
// 加载用户证书 >>>>
userCertBlk, _ := pem.Decode([]byte(userCertPem))
userCert, err := x509.ParseCertificate(userCertBlk.Bytes)
if err != nil {
panic(err)
}
// 加载用户证书 <<<<
// 加载 CA 证书 >>>>
caCertBlk, _ := pem.Decode([]byte(caCertPem))
caCert, err := x509.ParseCertificate(caCertBlk.Bytes)
if err != nil {
panic(err)
}
// 加载 CA 证书 <<<<
opts := x509.VerifyOptions{
Roots: x509.NewCertPool(),
Intermediates: x509.NewCertPool(),
CurrentTime: time.Now(),
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
}
opts.Roots.AddCert(caCert)
// 使用证书链来验证证书 >>>>
ret, err := userCert.Verify(opts)
fmt.Println("keychain verify : ", err, ret)
// 使用证书链来验证证书 <<<<
// 验证父证书签名 >>>>
err = userCert.CheckSignatureFrom(caCert)
fmt.Println(caCert.IsCA)
fmt.Println("check sign :", err)
// 验证父证书签名 <<<<
}
func TestAll(t *testing.T) {
caKeyPem, pub := kt.GenKey(elliptic.P256(), pwd)
fmt.Println("==================================================================== ca key")
fmt.Println(string(caKeyPem))
fmt.Println(string(pub))
ioutil.WriteFile("/tmp/ca.key", caKeyPem, 0644)
ioutil.WriteFile("/tmp/ca.pass", []byte(pwd), 0644)
fmt.Println("==================================================================== ca cert")
prv := prvkeyByPem(string(caKeyPem), pwd)
caCertPem := kt.GenCertForPubkey(prv, nil, prv.Public(), &Subject{
Country: "中国",
OrganizationalUnit: "组织单位",
Organization: "组织",
CommonName: "你好",
Email: "cc14514@icloud.com",
})
fmt.Println(string(caCertPem))
ioutil.WriteFile("/tmp/ca.pem", caCertPem, 0644)
fmt.Println("==================================================================== user key")
userPrv, userPub := kt.GenKey(elliptic.P256(), pwd)
// 输出用户密钥 >>>>>>>>
fmt.Println(string(userPrv))
fmt.Println(string(userPub))
ioutil.WriteFile("/tmp/user.key", userPrv, 0644)
ioutil.WriteFile("/tmp/user.pass", []byte(pwd), 0644)
// 输出用户密钥 <<<<<<<<
// 解析 PEM 公钥 >>>>>>
fmt.Println("==================================================================== user cert")
userPubBlk, _ := pem.Decode(userPub)
ipub, err := x509.ParsePKIXPublicKey(userPubBlk.Bytes)
if err != nil {
panic(err)
}
upub := ipub.(crypto.PublicKey)
// 解析 PEM 公钥 <<<<<<
// 解析 CA 证书和密钥并对用户 pubkey 签发证书 >>>>
caCertBlk, _ := pem.Decode([]byte(caCertPem))
caCert, err := x509.ParseCertificate(caCertBlk.Bytes)
if err != nil {
panic(err)
}
caPrv := prvkeyByPem(string(caKeyPem), pwd)
userCertPem := kt.GenCertForPubkey(caPrv, caCert, upub, &Subject{
Country: "中国",
OrganizationalUnit: "江湖",
Organization: "精武门",
CommonName: "helloworld.com",
Email: "cz@jwm.com",
})
fmt.Println(string(userCertPem))
ioutil.WriteFile("/tmp/user.pem", userCertPem, 0644)
// 解析 CA 证书和密钥并对用户 pubkey 签发证书 <<<<
userCertPemBlk, _ := pem.Decode(userCertPem)
userCert, err := x509.ParseCertificate(userCertPemBlk.Bytes)
t.Log(err, userCert.OCSPServer)
}
func TestOcsp(t *testing.T) {
// 加载用户证书 >>>>
userCertBlk, _ := pem.Decode([]byte(userCertPem))
userCert, err := x509.ParseCertificate(userCertBlk.Bytes)
if err != nil {
panic(err)
}
// 加载用户证书 <<<<
// 加载 CA 证书 >>>>
caCertBlk, _ := pem.Decode([]byte(caCertPem))
caCert, err := x509.ParseCertificate(caCertBlk.Bytes)
if err != nil {
panic(err)
}
// 加载 CA 证书 <<<<
t.Log("user", userCert.SerialNumber, "ca", caCert.SerialNumber, caCert.Subject.String())
ocspReq, err := ocsp.CreateRequest(userCert, caCert, nil)
t.Log(err, ocspReq)
req, _ := ocsp.ParseRequest(ocspReq)
// IssuerNameHash = Hash(DN) , DN = RawSubject
// IssuerKeyHash = Hash(Publickey) , Publickey = RawSubjectPublicKeyInfo.PublicKey
t.Log(req.IssuerNameHash, req.IssuerKeyHash, req.SerialNumber)
hasher := req.HashAlgorithm.New()
hasher.Write(caCert.RawSubject)
h1 := hasher.Sum(nil)
var publicKeyInfo struct {
Algorithm pkix.AlgorithmIdentifier
PublicKey asn1.BitString
}
if _, err := asn1.Unmarshal(caCert.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
t.Error(err)
}
hasher.Reset()
hasher.Write(publicKeyInfo.PublicKey.RightAlign())
h2 := hasher.Sum(nil)
t.Log(h1, h2)
}
func TestSignCert(t *testing.T) {
caKeyPem, err := ioutil.ReadFile("/Users/liangc/certs/ca.key")
if err != nil {
panic(err)
}
caPrv := prvkeyByPem(string(caKeyPem), pwd)
fmt.Println("==================================================================== client key")
userPrv, userPub := kt.GenKey(elliptic.S256(), pwd)
// 输出用户密钥 >>>>>>>>
fmt.Println(string(userPrv))
fmt.Println(string(userPub))
ioutil.WriteFile("/tmp/client.key", userPrv, 0644)
ioutil.WriteFile("/tmp/client.pass", []byte(pwd), 0644)
// 输出用户密钥 <<<<<<<<
// 解析 PEM 公钥 >>>>>>
fmt.Println("==================================================================== client cert")
userPubBlk, _ := pem.Decode(userPub)
ipub, err := x509.ParsePKIXPublicKey(userPubBlk.Bytes)
if err != nil {
panic(err)
}
upub := ipub.(crypto.PublicKey)
// 解析 PEM 公钥 <<<<<<
// 解析 CA 证书和密钥并对用户 pubkey 签发证书 >>>>
caCertBlk, _ := pem.Decode([]byte(caCertPem))
caCert, err := x509.ParseCertificate(caCertBlk.Bytes)
if err != nil {
panic(err)
}
userCertPem := kt.GenCertForPubkey(caPrv, caCert, upub, &Subject{
Country: "中国",
OrganizationalUnit: "江湖",
Organization: "精武门",
CommonName: "liangc-client-test",
Email: "cz@jwm.com",
})
fmt.Println(string(userCertPem))
ioutil.WriteFile("/tmp/client.pem", userCertPem, 0644)
// 解析 CA 证书和密钥并对用户 pubkey 签发证书 <<<<
userCertPemBlk, _ := pem.Decode(userCertPem)
userCert, err := x509.ParseCertificate(userCertPemBlk.Bytes)
t.Log(err, userCert.OCSPServer)
}
func TestLoadKey(t *testing.T) {
userPrv, err := ioutil.ReadFile("/tmp/user.key")
if err != nil {
panic(err)
}
userPrvBlk, _ := pem.Decode(userPrv)
userPrvBuf, err := x509.DecryptPEMBlock(userPrvBlk, []byte(pwd))
if err != nil {
panic(err)
}
uprv, err := x509.ParseECPrivateKey(userPrvBuf)
if err != nil {
panic(err)
}
fmt.Println(uprv)
}
func TestShow(t *testing.T) {
data, err := ioutil.ReadFile("/Users/liangc/certs/user.pem")
if err != nil {
panic(err)
}
blk, _ := pem.Decode(data)
crt, err := x509.ParseCertificate(blk.Bytes)
if err != nil {
panic(err)
}
t.Log(crt.SerialNumber)
}
|
package db
import (
"fmt"
"github.com/swjang1214/bookstore_oauth-api/src/db/mysql_db"
"github.com/swjang1214/bookstore_oauth-api/src/domain/access_token"
"github.com/swjang1214/bookstore_oauth-api/src/logger"
"github.com/swjang1214/bookstore_oauth-api/src/utils/errors"
)
const (
queryCreateAccessToken = "INSERT INTO access_tokens(access_token, user_id, client_id, expires) VALUES (?,?,?,?);"
queryGetAccessToken = "SELECT access_token, user_id, client_id, expires FROM access_tokens WHERE access_token=?;"
queryUpdateExpires = "UPDATE access_tokens SET expires=? WHERE access_token=?;"
)
type IDBRepository interface {
Create(*access_token.AccessToken) *errors.RestError
GetById(string) (*access_token.AccessToken, *errors.RestError)
UpdateExpirationTime(*access_token.AccessToken) *errors.RestError
}
type dbRepository struct {
}
func NewRepository() IDBRepository {
return &dbRepository{}
}
func (*dbRepository) GetById(id string) (*access_token.AccessToken, *errors.RestError) {
stmt, err := mysql_db.Client.Prepare(queryGetAccessToken)
if err != nil {
logger.Error("error when trying to prepare queryGetAccessToken statement", err)
return nil, errors.NewInternalServerError("database error")
}
defer stmt.Close()
result := stmt.QueryRow(id)
if result == nil {
logger.Error(fmt.Sprintf("error when trying to QueryRow by %s", id), nil)
return nil, errors.NewInternalServerError("database error")
}
var at access_token.AccessToken
if err := result.Scan(&at.AccessToken, &at.UserId, &at.ClientId, &at.Expires); err != nil {
logger.Error("error when trying to get AccessToken by id", err)
return nil, errors.NewInternalServerError("database error")
}
return &at, nil
}
func (*dbRepository) Create(token *access_token.AccessToken) *errors.RestError {
stmt, err := mysql_db.Client.Prepare(queryCreateAccessToken)
if err != nil {
logger.Error("error when trying to prepare queryGetAccessToken statement", err)
return errors.NewInternalServerError("database error")
}
defer stmt.Close()
insertResult, err := stmt.Exec(token.AccessToken, token.UserId, token.ClientId, token.Expires)
if err != nil {
logger.Error("error when trying to save token", err)
return errors.NewInternalServerError("database error")
}
_, err = insertResult.LastInsertId()
if err != nil {
logger.Error("error when trying to get last insert id after creating a new token", err)
return errors.NewInternalServerError("database error")
}
return nil
}
func (*dbRepository) UpdateExpirationTime(token *access_token.AccessToken) *errors.RestError {
stmt, err := mysql_db.Client.Prepare(queryUpdateExpires)
if err != nil {
logger.Error("error when trying to prepare queryUpdateExpires statement", err)
return errors.NewInternalServerError("database error")
}
defer stmt.Close()
_, err = stmt.Exec(token.Expires, token.AccessToken)
if err != nil {
logger.Error("error when trying to update token", err)
return errors.NewInternalServerError("database error")
}
return nil
}
|
// Copyright 2019-present Open Networking Foundation.
//
// 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 gnmi
import (
"context"
"fmt"
"io"
"strings"
"testing"
"time"
configapi "github.com/onosproject/onos-api/go/onos/config/v2"
toposdk "github.com/onosproject/onos-ric-sdk-go/pkg/topo"
"github.com/onosproject/onos-api/go/onos/topo"
"github.com/onosproject/onos-lib-go/pkg/errors"
"github.com/onosproject/onos-test/pkg/onostest"
"github.com/golang/protobuf/proto"
"github.com/onosproject/helmit/pkg/helm"
"github.com/onosproject/helmit/pkg/kubernetes"
v1 "github.com/onosproject/helmit/pkg/kubernetes/core/v1"
"github.com/onosproject/helmit/pkg/util/random"
"github.com/onosproject/onos-api/go/onos/config/admin"
"github.com/onosproject/onos-api/go/onos/config/v2"
"github.com/onosproject/onos-config/pkg/utils"
protoutils "github.com/onosproject/onos-config/test/utils/proto"
"github.com/onosproject/onos-lib-go/pkg/grpc/retry"
gnmiclient "github.com/openconfig/gnmi/client"
gclient "github.com/openconfig/gnmi/client/gnmi"
gpb "github.com/openconfig/gnmi/proto/gnmi"
"github.com/openconfig/gnmi/proto/gnmi_ext"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const (
// SimulatorTargetVersion default version for simulated target
SimulatorTargetVersion = "1.0.0"
// SimulatorTargetType type for simulated target
SimulatorTargetType = "devicesim"
defaultTimeout = time.Second * 30
)
// RetryOption specifies if a client should retry request errors
type RetryOption int
const (
// NoRetry do not attempt to retry
NoRetry RetryOption = iota
// WithRetry adds a retry option to the client
WithRetry
)
// MakeContext returns a new context for use in GNMI requests
func MakeContext() context.Context {
ctx := context.Background()
return ctx
}
func getService(release *helm.HelmRelease, serviceName string) (*v1.Service, error) {
releaseClient := kubernetes.NewForReleaseOrDie(release)
service, err := releaseClient.CoreV1().Services().Get(context.Background(), serviceName)
if err != nil {
return nil, err
}
return service, nil
}
func connectComponent(releaseName string, deploymentName string) (*grpc.ClientConn, error) {
release := helm.Chart(releaseName).Release(releaseName)
return connectService(release, deploymentName)
}
func connectService(release *helm.HelmRelease, deploymentName string) (*grpc.ClientConn, error) {
service, err := getService(release, deploymentName)
if err != nil {
return nil, err
}
tlsConfig, err := getClientCredentials()
if err != nil {
return nil, err
}
return grpc.Dial(service.Ports()[0].Address(true), grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
// GetSimulatorTarget queries topo to find the topo object for a simulator target
func GetSimulatorTarget(simulator *helm.HelmRelease) (*topo.Object, error) {
client, err := NewTopoClient()
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
obj, err := client.Get(ctx, topo.ID(simulator.Name()))
if err != nil {
return nil, err
}
return obj, nil
}
// NewSimulatorTargetEntity creates a topo entity for a device simulator target
func NewSimulatorTargetEntity(simulator *helm.HelmRelease, targetType string, targetVersion string) (*topo.Object, error) {
simulatorClient := kubernetes.NewForReleaseOrDie(simulator)
services, err := simulatorClient.CoreV1().Services().List(context.Background())
if err != nil {
return nil, err
}
service := services[0]
return NewTargetEntity(simulator.Name(), targetType, targetVersion, service.Ports()[0].Address(true))
}
// NewTargetEntity creates a topo entity with the specified target name, type, version and service address
func NewTargetEntity(name string, targetType string, targetVersion string, serviceAddress string) (*topo.Object, error) {
o := topo.Object{
ID: topo.ID(name),
Type: topo.Object_ENTITY,
Obj: &topo.Object_Entity{
Entity: &topo.Entity{
KindID: topo.ID(targetType),
},
},
}
if err := o.SetAspect(&topo.TLSOptions{Insecure: true, Plain: true}); err != nil {
return nil, err
}
timeout := defaultTimeout
if err := o.SetAspect(&topo.Configurable{
Type: targetType,
Address: serviceAddress,
Version: targetVersion,
Timeout: &timeout,
}); err != nil {
return nil, err
}
return &o, nil
}
// NewTopoClient creates a topology client
func NewTopoClient() (toposdk.Client, error) {
return toposdk.NewClient()
}
// NewAdminServiceClient :
func NewAdminServiceClient() (admin.ConfigAdminServiceClient, error) {
conn, err := connectComponent("onos-umbrella", "onos-config")
if err != nil {
return nil, err
}
return admin.NewConfigAdminServiceClient(conn), nil
}
// NewTransactionServiceClient :
func NewTransactionServiceClient() (admin.TransactionServiceClient, error) {
conn, err := connectComponent("onos-umbrella", "onos-config")
if err != nil {
return nil, err
}
return admin.NewTransactionServiceClient(conn), nil
}
// NewConfigurationServiceClient returns configuration store client
func NewConfigurationServiceClient() (admin.ConfigurationServiceClient, error) {
conn, err := connectComponent("onos-umbrella", "onos-config")
if err != nil {
return nil, err
}
return admin.NewConfigurationServiceClient(conn), nil
}
// AddTargetToTopo adds a new target to topo
func AddTargetToTopo(targetEntity *topo.Object) error {
client, err := NewTopoClient()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err = client.Create(ctx, targetEntity)
return err
}
func getKindFilter(kind string) *topo.Filters {
kindFilter := &topo.Filters{
KindFilter: &topo.Filter{
Filter: &topo.Filter_Equal_{
Equal_: &topo.EqualFilter{
Value: kind,
},
},
},
}
return kindFilter
}
func getControlRelationFilter() *topo.Filters {
return getKindFilter(topo.CONTROLS)
}
// WaitForControlRelation waits to create control relation for a given target
func WaitForControlRelation(t *testing.T, predicate func(*topo.Relation, topo.Event) bool, timeout time.Duration) bool {
cl, err := NewTopoClient()
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
stream := make(chan topo.Event)
err = cl.Watch(ctx, stream, toposdk.WithWatchFilters(getControlRelationFilter()))
assert.NoError(t, err)
for event := range stream {
if predicate(event.Object.GetRelation(), event) {
return true
} // Otherwise, loop and wait for the next topo event
}
return false
}
// WaitForTargetAvailable waits for a target to become available
func WaitForTargetAvailable(t *testing.T, objectID topo.ID, timeout time.Duration) bool {
return WaitForControlRelation(t, func(rel *topo.Relation, event topo.Event) bool {
if rel.TgtEntityID != objectID {
t.Logf("Topo %v event from %s (expected %s). Discarding\n", event.Type, rel.TgtEntityID, objectID)
return false
}
if event.Type == topo.EventType_ADDED || event.Type == topo.EventType_UPDATED || event.Type == topo.EventType_NONE {
cl, err := NewTopoClient()
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, err = cl.Get(ctx, event.Object.ID)
if err == nil {
t.Logf("Target %s is available", objectID)
return true
}
}
return false
}, timeout)
}
// WaitForTargetUnavailable waits for a target to become available
func WaitForTargetUnavailable(t *testing.T, objectID topo.ID, timeout time.Duration) bool {
return WaitForControlRelation(t, func(rel *topo.Relation, event topo.Event) bool {
if rel.TgtEntityID != objectID {
t.Logf("Topo %v event from %s (expected %s). Discarding\n", event, rel.TgtEntityID, objectID)
return false
}
if event.Type == topo.EventType_REMOVED || event.Type == topo.EventType_NONE {
cl, err := NewTopoClient()
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, err = cl.Get(ctx, event.Object.ID)
if errors.IsNotFound(err) {
t.Logf("Target %s is unavailable", objectID)
return true
}
}
return false
}, timeout)
}
// WaitForConfigurationCompleteOrFail wait for a configuration to complete or fail
func WaitForConfigurationCompleteOrFail(t *testing.T, configurationID configapi.ConfigurationID, wait time.Duration) error {
client, err := NewConfigurationServiceClient()
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
response, err := client.WatchConfigurations(ctx, &admin.WatchConfigurationsRequest{
ConfigurationID: configurationID,
Noreplay: false,
})
assert.NoError(t, err)
for {
resp, err := response.Recv()
configuration := resp.ConfigurationEvent.GetConfiguration()
if err == io.EOF {
break
} else if err != nil {
return errors.NewInvalid(err.Error())
} else {
configStatus := configuration.GetStatus()
if configStatus.GetState() == configapi.ConfigurationStatus_SYNCHRONIZED {
return nil
}
}
}
return errors.NewInvalid("configuration %s failed", configurationID)
}
// WaitForRollback waits for a COMPLETED status on the most recent rollback transaction
func WaitForRollback(t *testing.T, transactionIndex v2.Index, wait time.Duration) bool {
client, err := NewTransactionServiceClient()
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
stream, err := client.WatchTransactions(ctx, &admin.WatchTransactionsRequest{})
assert.NoError(t, err)
assert.NotNil(t, stream)
start := time.Now()
for {
resp, err := stream.Recv()
if err != nil {
return false
}
assert.NotNil(t, resp)
fmt.Printf("%v\n", resp.TransactionEvent)
t := resp.TransactionEvent.Transaction
if rt := t.GetRollback(); rt != nil {
if rt.RollbackIndex == transactionIndex {
return true
}
}
if time.Since(start) > wait {
return false
}
}
}
// NoPaths can be used on a request that does not need path values
var NoPaths = make([]protoutils.TargetPath, 0)
// NoExtensions can be used on a request that does not need extension values
var NoExtensions = make([]*gnmi_ext.Extension, 0)
// SyncExtension returns list of extensions with just the transaction mode extension set to sync and atomic.
func SyncExtension(t *testing.T) []*gnmi_ext.Extension {
return []*gnmi_ext.Extension{TransactionStrategyExtension(t, configapi.TransactionStrategy_SYNCHRONOUS, 0)}
}
// TransactionStrategyExtension returns a transaction strategy extension populated with the specified fields
func TransactionStrategyExtension(t *testing.T,
synchronicity configapi.TransactionStrategy_Synchronicity,
isolation configapi.TransactionStrategy_Isolation) *gnmi_ext.Extension {
ext := v2.TransactionStrategy{
Synchronicity: synchronicity,
Isolation: isolation,
}
b, err := ext.Marshal()
assert.NoError(t, err)
return &gnmi_ext.Extension{
Ext: &gnmi_ext.Extension_RegisteredExt{
RegisteredExt: &gnmi_ext.RegisteredExtension{
Id: v2.TransactionStrategyExtensionID,
Msg: b,
},
},
}
}
func convertGetResults(response *gpb.GetResponse) ([]protoutils.TargetPath, []*gnmi_ext.Extension, error) {
entryCount := len(response.Notification)
result := make([]protoutils.TargetPath, entryCount)
for index, notification := range response.Notification {
value := notification.Update[0].Val
result[index].TargetName = notification.Update[0].Path.Target
pathString := ""
for _, elem := range notification.Update[0].Path.Elem {
pathString = pathString + "/" + elem.Name
}
result[index].Path = pathString
result[index].PathDataType = "string_val"
if value != nil {
result[index].PathDataValue = utils.StrVal(value)
} else {
result[index].PathDataValue = ""
}
}
return result, response.Extension, nil
}
func extractSetTransactionID(response *gpb.SetResponse) string {
return string(response.Extension[0].GetRegisteredExt().Msg)
}
// GetGNMIValue generates a GET request on the given client for a Path on a target
func GetGNMIValue(ctx context.Context, c gnmiclient.Impl, paths []protoutils.TargetPath, encoding gpb.Encoding) ([]protoutils.TargetPath, []*gnmi_ext.Extension, error) {
protoString := ""
for _, targetPath := range paths {
protoString = protoString + MakeProtoPath(targetPath.TargetName, targetPath.Path)
}
getTZRequest := &gpb.GetRequest{}
if err := proto.UnmarshalText(protoString, getTZRequest); err != nil {
fmt.Printf("unable to parse gnmi.GetRequest from %q : %v\n", protoString, err)
return nil, nil, err
}
getTZRequest.Encoding = encoding
response, err := c.(*gclient.Client).Get(ctx, getTZRequest)
if err != nil || response == nil {
return nil, nil, err
}
return convertGetResults(response)
}
// SetGNMIValue generates a SET request on the given client for update and delete paths on a target
func SetGNMIValue(ctx context.Context, c gnmiclient.Impl, updatePaths []protoutils.TargetPath, deletePaths []protoutils.TargetPath, extensions []*gnmi_ext.Extension) (string, []*gnmi_ext.Extension, error) {
var protoBuilder strings.Builder
for _, updatePath := range updatePaths {
protoBuilder.WriteString(protoutils.MakeProtoUpdatePath(updatePath))
}
for _, deletePath := range deletePaths {
protoBuilder.WriteString(protoutils.MakeProtoDeletePath(deletePath.TargetName, deletePath.Path))
}
setTZRequest := &gpb.SetRequest{}
if err := proto.UnmarshalText(protoBuilder.String(), setTZRequest); err != nil {
return "", nil, err
}
setTZRequest.Extension = extensions
setResult, err := c.(*gclient.Client).Set(ctx, setTZRequest)
if err != nil {
return "", nil, err
}
return extractSetTransactionID(setResult), setResult.Extension, nil
}
// GetTargetPath creates a target path
func GetTargetPath(target string, path string) []protoutils.TargetPath {
return GetTargetPathWithValue(target, path, "", "")
}
// GetTargetPathWithValue creates a target path with a value to set
func GetTargetPathWithValue(target string, path string, value string, valueType string) []protoutils.TargetPath {
targetPath := make([]protoutils.TargetPath, 1)
targetPath[0].TargetName = target
targetPath[0].Path = path
targetPath[0].PathDataValue = value
targetPath[0].PathDataType = valueType
return targetPath
}
// GetTargetPaths creates multiple target paths
func GetTargetPaths(targets []string, paths []string) []protoutils.TargetPath {
var targetPaths = make([]protoutils.TargetPath, len(paths)*len(targets))
pathIndex := 0
for _, dev := range targets {
for _, path := range paths {
targetPaths[pathIndex].TargetName = dev
targetPaths[pathIndex].Path = path
pathIndex++
}
}
return targetPaths
}
// GetTargetPathsWithValues creates multiple target paths with values to set
func GetTargetPathsWithValues(targets []string, paths []string, values []string) []protoutils.TargetPath {
var targetPaths = GetTargetPaths(targets, paths)
valueIndex := 0
for range targets {
for _, value := range values {
targetPaths[valueIndex].PathDataValue = value
targetPaths[valueIndex].PathDataType = protoutils.StringVal
valueIndex++
}
}
return targetPaths
}
// CheckTargetValue makes sure a value has been assigned properly to a target path by querying GNMI
func CheckTargetValue(t *testing.T, targetGnmiClient gnmiclient.Impl, targetPaths []protoutils.TargetPath, expectedValue string) {
targetValues, extensions, err := GetGNMIValue(MakeContext(), targetGnmiClient, targetPaths, gpb.Encoding_JSON)
if err == nil {
assert.NoError(t, err, "GNMI get operation to target returned an error")
assert.Equal(t, expectedValue, targetValues[0].PathDataValue, "Query after set returned the wrong value: %s\n", expectedValue)
assert.Equal(t, 0, len(extensions))
} else {
assert.Fail(t, "Failed to query target: %v", err)
}
}
// CheckTargetValueDeleted makes sure target path is missing when queried via GNMI
func CheckTargetValueDeleted(t *testing.T, targetGnmiClient gnmiclient.Impl, targetPaths []protoutils.TargetPath) {
_, _, err := GetGNMIValue(MakeContext(), targetGnmiClient, targetPaths, gpb.Encoding_JSON)
if err == nil {
assert.Fail(t, "Path not deleted", targetPaths)
} else if !strings.Contains(err.Error(), "NotFound") {
assert.Fail(t, "Incorrect error received", err)
}
}
// GetTargetGNMIClientOrFail creates a GNMI client to a target. If there is an error, the test is failed
func GetTargetGNMIClientOrFail(t *testing.T, simulator *helm.HelmRelease) gnmiclient.Impl {
t.Helper()
simulatorClient := kubernetes.NewForReleaseOrDie(simulator)
services, err := simulatorClient.CoreV1().Services().List(context.Background())
assert.NoError(t, err)
service := services[0]
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
dest := gnmiclient.Destination{
Addrs: []string{service.Ports()[0].Address(true)},
Target: service.Name,
Timeout: 10 * time.Second,
}
client, err := gclient.New(ctx, dest)
assert.NoError(t, err)
assert.True(t, client != nil, "Fetching target client returned nil")
return client
}
// GetOnosConfigDestination :
func GetOnosConfigDestination() (gnmiclient.Destination, error) {
creds, err := getClientCredentials()
if err != nil {
return gnmiclient.Destination{}, err
}
configRelease := helm.Release("onos-umbrella")
configClient := kubernetes.NewForReleaseOrDie(configRelease)
configService, err := configClient.CoreV1().Services().Get(context.Background(), "onos-config")
if err != nil || configService == nil {
return gnmiclient.Destination{}, errors.NewNotFound("can't find service for onos-config")
}
return gnmiclient.Destination{
Addrs: []string{configService.Ports()[0].Address(true)},
Target: configService.Name,
TLS: creds,
Timeout: 10 * time.Second,
}, nil
}
// GetGNMIClientWithContextOrFail makes a GNMI client to use for requests. If creating the client fails, the test is failed.
func GetGNMIClientWithContextOrFail(ctx context.Context, t *testing.T, retryOption RetryOption) gnmiclient.Impl {
t.Helper()
gCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
dest, err := GetOnosConfigDestination()
if !assert.NoError(t, err) {
t.Fail()
}
opts := make([]grpc.DialOption, 0)
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(dest.TLS)))
if retryOption == WithRetry {
opts = append(opts, grpc.WithUnaryInterceptor(retry.RetryingUnaryClientInterceptor()))
}
conn, err := grpc.DialContext(gCtx, dest.Addrs[0], opts...)
assert.NoError(t, err)
client, err := gclient.NewFromConn(gCtx, conn, dest)
assert.NoError(t, err)
assert.True(t, client != nil, "Fetching target client returned nil")
return client
}
// GetGNMIClientOrFail makes a GNMI client to use for requests. If creating the client fails, the test is failed.
func GetGNMIClientOrFail(t *testing.T) gnmiclient.Impl {
t.Helper()
return GetGNMIClientWithContextOrFail(context.Background(), t, WithRetry)
}
// CheckGNMIValueWithContext makes sure a value has been assigned properly by querying the onos-config northbound API
func CheckGNMIValueWithContext(ctx context.Context, t *testing.T, gnmiClient gnmiclient.Impl, paths []protoutils.TargetPath, expectedValue string, expectedExtensions int, failMessage string) {
t.Helper()
value, extensions, err := GetGNMIValue(ctx, gnmiClient, paths, gpb.Encoding_PROTO)
assert.NoError(t, err, "Get operation returned an unexpected error")
assert.Equal(t, expectedExtensions, len(extensions))
assert.Equal(t, expectedValue, value[0].PathDataValue, "%s: %s", failMessage, value)
}
// CheckGNMIValue makes sure a value has been assigned properly by querying the onos-config northbound API
func CheckGNMIValue(t *testing.T, gnmiClient gnmiclient.Impl, paths []protoutils.TargetPath, expectedValue string, expectedExtensions int, failMessage string) {
t.Helper()
CheckGNMIValueWithContext(MakeContext(), t, gnmiClient, paths, expectedValue, expectedExtensions, failMessage)
}
// CheckGNMIValues makes sure a list of values has been assigned properly by querying the onos-config northbound API
func CheckGNMIValues(t *testing.T, gnmiClient gnmiclient.Impl, paths []protoutils.TargetPath, expectedValues []string, expectedExtensions int, failMessage string) {
t.Helper()
value, extensions, err := GetGNMIValue(MakeContext(), gnmiClient, paths, gpb.Encoding_PROTO)
assert.NoError(t, err, "Get operation returned unexpected error")
assert.Equal(t, expectedExtensions, len(extensions))
for index, expectedValue := range expectedValues {
assert.Equal(t, expectedValue, value[index].PathDataValue, "%s: %s", failMessage, value)
}
}
// SetGNMIValueWithContextOrFail does a GNMI set operation to the given client, and fails the test if there is an error
func SetGNMIValueWithContextOrFail(ctx context.Context, t *testing.T, gnmiClient gnmiclient.Impl,
updatePaths []protoutils.TargetPath, deletePaths []protoutils.TargetPath,
extensions []*gnmi_ext.Extension) (configapi.TransactionID, v2.Index) {
t.Helper()
transactionID, transactionIndex, err := SetGNMIValueWithContext(ctx, t, gnmiClient, updatePaths, deletePaths, extensions)
assert.NoError(t, err, "Set operation returned unexpected error")
return transactionID, transactionIndex
}
// SetGNMIValueWithContext does a GNMI set operation to the given client, and fails the test if there is an error
func SetGNMIValueWithContext(ctx context.Context, t *testing.T, gnmiClient gnmiclient.Impl,
updatePaths []protoutils.TargetPath, deletePaths []protoutils.TargetPath,
extensions []*gnmi_ext.Extension) (configapi.TransactionID, v2.Index, error) {
t.Helper()
_, extensionsSet, err := SetGNMIValue(ctx, gnmiClient, updatePaths, deletePaths, extensions)
if err != nil {
return "", 0, err
}
var transactionInfo *configapi.TransactionInfo
for _, extension := range extensionsSet {
if ext, ok := extension.Ext.(*gnmi_ext.Extension_RegisteredExt); ok &&
ext.RegisteredExt.Id == configapi.TransactionInfoExtensionID {
bytes := ext.RegisteredExt.Msg
transactionInfo = &configapi.TransactionInfo{}
err := proto.Unmarshal(bytes, transactionInfo)
assert.NoError(t, err)
}
}
if transactionInfo == nil {
return "", 0, errors.NewNotFound("transaction ID extension not found")
}
return transactionInfo.ID, transactionInfo.Index, err
}
// SetGNMIValueOrFail does a GNMI set operation to the given client, and fails the test if there is an error
func SetGNMIValueOrFail(t *testing.T, gnmiClient gnmiclient.Impl,
updatePaths []protoutils.TargetPath, deletePaths []protoutils.TargetPath,
extensions []*gnmi_ext.Extension) (configapi.TransactionID, v2.Index) {
return SetGNMIValueWithContextOrFail(MakeContext(), t, gnmiClient, updatePaths, deletePaths, extensions)
}
// MakeProtoPath returns a Path: element for a given target and Path
func MakeProtoPath(target string, path string) string {
var protoBuilder strings.Builder
protoBuilder.WriteString("path: ")
gnmiPath := protoutils.MakeProtoTarget(target, path)
protoBuilder.WriteString(gnmiPath)
return protoBuilder.String()
}
// CreateSimulator creates a device simulator
func CreateSimulator(t *testing.T) *helm.HelmRelease {
return CreateSimulatorWithName(t, random.NewPetName(2), true)
}
// CreateSimulatorWithName creates a device simulator
func CreateSimulatorWithName(t *testing.T, name string, createTopoEntity bool) *helm.HelmRelease {
simulator := helm.
Chart("device-simulator", onostest.OnosChartRepo).
Release(name).
Set("image.tag", "latest")
err := simulator.Install(true)
assert.NoError(t, err, "could not install device simulator %v", err)
time.Sleep(2 * time.Second)
if createTopoEntity {
simulatorTarget, err := NewSimulatorTargetEntity(simulator, SimulatorTargetType, SimulatorTargetVersion)
assert.NoError(t, err, "could not make target for simulator %v", err)
err = AddTargetToTopo(simulatorTarget)
assert.NoError(t, err, "could not add target to topo for simulator %v", err)
}
return simulator
}
// DeleteSimulator shuts down the simulator pod and removes the target from topology
func DeleteSimulator(t *testing.T, simulator *helm.HelmRelease) {
assert.NoError(t, simulator.Uninstall())
}
|
package main
import (
"fmt"
"ms/sun_old/base"
"ms/sun/shared/x"
)
func main() {
n := 0
next := func() int {
n++
return n
}
work := func() {
for {
//_, err := x.HomeFanoutByOrderId(base.DB, rand.Intn(40000))
_, err := x.HomeFanoutByOrderId(base.DB, 1000)
if n := next(); n%10000 == 0 {
fmt.Println(n , err)
}
}
}
for i := 0; i < 9; i++ {
go work()
}
work()
}
|
package options
var CONFIG string
type ConfigOptions struct {
}
func (c *ConfigOptions) Init() {
}
|
// Copyright 2017 Thibault Chataigner <thibault.chataigner@gmail.com>
// 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 graphite
import (
"encoding/json"
"github.com/criteo/graphite-remote-adapter/utils"
)
// make it mockable in tests
var (
fetchURL = utils.FetchURL
prepareURL = utils.PrepareURL
)
// ExpandResponse is a parsed response of graphite expand endpoint.
type ExpandResponse struct {
Results []string `yaml:"results,omitempty" json:"results,omitempty"`
}
// RenderResponse is a single parsed element of graphite render endpoint.
type RenderResponse struct {
Target string `yaml:"target,omitempty" json:"target,omitempty"`
Datapoints []*Datapoint `yaml:"datapoints,omitempty" json:"datapoints,omitempty"`
Tags Tags `yaml:"tags,omitempty" json:"tags,omitempty"`
}
// Datapoint pairs a timestamp to a value.
type Datapoint struct {
Value *float64
Timestamp int64
}
// Tags mapping.
type Tags map[string]string
// UnmarshalJSON unmarshals a Datapoint from json
func (d *Datapoint) UnmarshalJSON(b []byte) error {
var x []*interface{}
err := json.Unmarshal(b, &x)
if err != nil {
return err
}
if x[0] != nil {
val := new(float64)
*val = (*x[0]).(float64)
d.Value = val
}
d.Timestamp = int64((*x[1]).(float64))
return nil
}
|
/*
Recreational languages win at code golf too much. This challenge is simple, when using higher level functions.
The task is as follows:
Given any valid url, which is guaranteed to result in a valid HTML document (for example https://en.wikipedia.org/wiki/Ruby_on_Rails, which has 9 images), count the number of images displayed from the resultant webpage.
Only images visible in the HTML code are counted, marked by the HTML <img> tag.
Websites that can continually load images (Google Images) are not valid tests.
*/
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"golang.org/x/net/html"
)
func main() {
log.SetFlags(0)
log.SetPrefix("get-number-of-images: ")
parseflags()
url := flag.Arg(0)
data, err := get(url)
ck(err)
images, err := count(data)
ck(err)
fmt.Println(images)
}
func ck(err error) {
if err != nil {
log.Fatal(err)
}
}
func parseflags() {
flag.Usage = usage
flag.Parse()
if flag.NArg() < 1 {
usage()
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [options] url")
flag.PrintDefaults()
os.Exit(2)
}
func get(url string) (b []byte, err error) {
r, err := http.Get(url)
if err != nil {
return
}
return io.ReadAll(r.Body)
}
func count(b []byte) (x int, err error) {
r := bytes.NewReader(b)
d, err := html.Parse(r)
if err != nil {
return
}
walk(d, &x)
return
}
func walk(n *html.Node, x *int) {
if n.Type == html.ElementNode && n.Data == "img" {
*x += 1
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c, x)
}
}
|
package shape
import (
"math"
"testing"
"github.com/calbim/ray-tracer/src/material"
"github.com/calbim/ray-tracer/src/transforms"
"github.com/calbim/ray-tracer/src/matrix"
"github.com/calbim/ray-tracer/src/ray"
"github.com/calbim/ray-tracer/src/tuple"
)
func TestSphereIntersection(t *testing.T) {
s := NewSphere()
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
xs := Intersect(s, r)
if len(xs) != 2 || xs[0].Value != 4 || xs[1].Value != 6 {
t.Errorf("wanted intersection points to be %v and %v, got %v and %v", 4.0, 6.0, xs[0], xs[1])
}
}
func TestSphereIntersectionTangent(t *testing.T) {
s := NewSphere()
r := ray.New(tuple.Point(0, 1, -5), tuple.Vector(0, 0, 1))
xs := Intersect(s, r)
if len(xs) != 2 || xs[0].Value != 5 || xs[1].Value != 5 {
t.Errorf("wanted intersection points to be %v and %v, got %v and %v", 5.0, 5.0, xs[0], xs[1])
}
}
func TestSphereRayMisses(t *testing.T) {
s := NewSphere()
r := ray.New(tuple.Point(0, 2, -5), tuple.Vector(0, 0, 1))
xs := Intersect(s, r)
if len(xs) != 0 {
t.Errorf("wamted 0 intersections, got %v", len(xs))
}
}
func TestRayInsideSphere(t *testing.T) {
s := NewSphere()
r := ray.New(tuple.Point(0, 0, 0), tuple.Vector(0, 0, 1))
xs := Intersect(s, r)
if len(xs) != 2 || xs[0].Value != -1 || xs[1].Value != 1 {
t.Errorf("wanted intersections points to be %v and %v, got %v and %v", -1, 1, xs[0], xs[1])
}
}
func TestSphereBehindRay(t *testing.T) {
s := NewSphere()
r := ray.New(tuple.Point(0, 0, 5), tuple.Vector(0, 0, 1))
xs := Intersect(s, r)
if len(xs) != 2 || xs[0].Value != -6 || xs[1].Value != -4 {
t.Errorf("wanted intersections points to be %v and %v, got %v and %v", -6, -4, xs[0], xs[1])
}
}
func TestIntersection(t *testing.T) {
s := NewSphere()
i := NewIntersection(3.5, s)
if i.Value != 3.5 {
t.Errorf("wanted intersection point=%v, got %v", 3.5, i.Value)
}
if i.Object != s {
t.Errorf("wanted intersected object=%v, got %v", s, i.Object)
}
}
func TestIntersections(t *testing.T) {
s := NewSphere()
i1 := Intersection{1, s}
i2 := Intersection{2, s}
xs := Intersections(i1, i2)
if len(xs) != 2 {
t.Errorf("wanted %v intersections, got %v", 2, len(xs))
}
if xs[0].Value != 1 || xs[1].Value != 2 {
t.Errorf("wanted %v and %v, got %v and %v", 1, 2, xs[0], xs[1])
}
}
func TestIntersectionSetsObject(t *testing.T) {
r := ray.New(tuple.Point(0, 0, 5), tuple.Vector(0, 0, 1))
s := NewSphere()
xs := Intersect(s, r)
if len(xs) != 2 {
t.Errorf("wanted %v intersections, got %v", 2, len(xs))
}
if xs[0].Object != s || xs[1].Object != s {
t.Errorf("wanted object to be %v, got %v", s, xs[0])
}
}
func TestHitAllPositive(t *testing.T) {
s := NewSphere()
i1 := Intersection{1, s}
i2 := Intersection{2, s}
xs := Intersections(i1, i2)
i := Hit(xs)
if *i != i1 {
t.Errorf("wanted hit=%v, got %v", i1, i)
}
}
func TestHitSomePositive(t *testing.T) {
s := NewSphere()
i1 := Intersection{-1, s}
i2 := Intersection{1, s}
xs := Intersections(i1, i2)
i := Hit(xs)
if *i != i2 {
t.Errorf("hit should be %v, gpt %v", i2, i)
}
}
func TestHitAllNegative(t *testing.T) {
s := NewSphere()
i1 := Intersection{-2, s}
i2 := Intersection{-1, s}
xs := Intersections(i1, i2)
i := Hit(xs)
if i != nil {
t.Errorf("hit should be %v, got %v", nil, i)
}
}
func TestHitMultipleIntersections(t *testing.T) {
s := NewSphere()
i1 := Intersection{5, s}
i2 := Intersection{7, s}
i3 := Intersection{-3, s}
i4 := Intersection{2, s}
xs := Intersections(i1, i2, i3, i4)
i := Hit(xs)
if *i != i4 {
t.Errorf("hit should be %v", i4)
}
}
func TestIntersectScaledSphere(t *testing.T) {
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
s := NewSphere()
s.SetTransform(transforms.Scaling(2, 2, 2))
xs := Intersect(s, r)
if len(xs) != 2 {
t.Errorf("wanted %v intersections, got %v", 2, len(xs))
}
if xs[0].Value != 3 || xs[1].Value != 7 {
t.Errorf("wanted intersection points to be %v and %v, got %v and %v", 3, 7, xs[0].Value, xs[1].Value)
}
}
func TestIntersectTranslatedSphere(t *testing.T) {
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
s := NewSphere()
s.SetTransform(transforms.Translation(5, 0, 0))
xs := Intersect(s, r)
if len(xs) != 0 {
t.Errorf("wanted %v intersections, got %v", 0, len(xs))
}
}
func TestNormalXAxis(t *testing.T) {
s := NewSphere()
n := NormalAt(s, tuple.Point(1, 0, 0))
if n == nil {
t.Errorf("normal is nil")
}
if !n.Equals(tuple.Vector(1, 0, 0)) {
t.Errorf("wanted n=%v, got %v", tuple.Vector(1, 0, 0), n)
}
}
func TestNormalYAxis(t *testing.T) {
s := NewSphere()
n := NormalAt(s, tuple.Point(0, 1, 0))
if n == nil {
t.Errorf("normal is nil")
}
if !n.Equals(tuple.Vector(0, 1, 0)) {
t.Errorf("wanted n=%v, got %v", tuple.Vector(0, 1, 0), n)
}
}
func TestNormalZAxis(t *testing.T) {
s := NewSphere()
n := NormalAt(s, tuple.Point(0, 0, 1))
if n == nil {
t.Errorf("normal is nil")
}
if !n.Equals(tuple.Vector(0, 0, 1)) {
t.Errorf("wanted n=%v, got %v", tuple.Vector(0, 0, 1), n)
}
}
func TestNormalNonAxial(t *testing.T) {
s := NewSphere()
n := NormalAt(s, tuple.Point(math.Sqrt(3)/3, math.Sqrt(3)/3, math.Sqrt(3)/3))
if n == nil {
t.Errorf("normal is nil")
}
v := tuple.Vector(math.Sqrt(3)/3, math.Sqrt(3)/3, math.Sqrt(3)/3)
if !n.Equals(v) {
t.Errorf("wanted n=%v, got %v", v, n)
}
}
func TestNormalIsNormalized(t *testing.T) {
s := NewSphere()
p := tuple.Point(math.Sqrt(3)/3, math.Sqrt(3)/3, math.Sqrt(3)/3)
n := NormalAt(s, p)
if !n.Equals(n.Normalize()) {
t.Errorf("wanted n=%v, got %v", n.Normalize(), n)
}
}
func TestNormalTranslatedSphere(t *testing.T) {
s := NewSphere()
s.SetTransform(transforms.Translation(0, 1, 0))
n := NormalAt(s, tuple.Point(0, 1.70711, -0.70711))
if !n.Equals(tuple.Vector(0, 0.70711, -0.70711)) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 0.70711, -0.70711), n)
}
}
func TestNormalTransformedSphere(t *testing.T) {
s := NewSphere()
s.SetTransform(transforms.Chain(transforms.RotationZ(math.Pi/5), transforms.Scaling(1, 0.5, 1)))
n := NormalAt(s, tuple.Point(0, math.Sqrt(2)/2, -math.Sqrt(2)/2))
expected := tuple.Vector(0, 0.97014, -0.24254)
if !n.Equals(expected) {
t.Errorf("wanted normal=%v, got %v", expected, n)
}
}
func TestPrepareComputations(t *testing.T) {
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
s := NewSphere()
i := &Intersection{
Value: 4,
Object: s,
}
comps := i.PrepareComputations(r)
if comps.Value != i.Value {
t.Errorf("wanted value=%v, got %v", i.Value, comps.Value)
}
if comps.Object != i.Object {
t.Errorf("wanted object value=%v, got %v", i.Object, comps.Object)
}
if comps.Point != tuple.Point(0, 0, -1) {
t.Errorf("wanted point=%v, got %v", tuple.Point(0, 0, -1), comps.Point)
}
if comps.Eyev != tuple.Vector(0, 0, -1) {
t.Errorf("wanted eyev=%v, got %v", tuple.Vector(0, 0, -1), comps.Eyev)
}
if comps.Normal != tuple.Vector(0, 0, -1) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 0, -1), comps.Normal)
}
}
func TestInsideFlagWhenIntersectionOutside(t *testing.T) {
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
s := NewSphere()
i := &Intersection{Value: 4.0, Object: s}
comp := i.PrepareComputations(r)
if comp.Inside == true {
t.Errorf("wanted hit to be outside the object")
}
}
func TestHitWhenIntersectionInside(t *testing.T) {
r := ray.New(tuple.Point(0, 0, 0), tuple.Vector(0, 0, 1))
s := NewSphere()
i := &Intersection{Value: 1.0, Object: s}
comp := i.PrepareComputations(r)
if comp.Inside != true {
t.Errorf("wanted hit to be inside the object")
}
if comp.Point != tuple.Point(0, 0, 1) {
t.Errorf("wanted point=%v, got %v", tuple.Point(0, 0, 1), comp.Point)
}
if comp.Eyev != tuple.Vector(0, 0, -1) {
t.Errorf("wanted point=%v, got %v", tuple.Point(0, 0, -1), comp.Eyev)
}
if comp.Normal != tuple.Vector(0, 0, -1) {
t.Errorf("wanted normal=%v, got %v", tuple.Point(0, 0, -1), comp.Point)
}
}
type TestShape struct {
Transform *matrix.Matrix
Material *material.Material
SavedRay *ray.Ray
}
func NewTestShape() *TestShape {
m := material.New()
return &TestShape{
Transform: matrix.Identity,
Material: &m,
}
}
func (ts *TestShape) GetMaterial() *material.Material {
return ts.Material
}
func (ts *TestShape) GetTransform() *matrix.Matrix {
return ts.Transform
}
func (ts *TestShape) SetTransform(m *matrix.Matrix) {
ts.Transform = m
}
func (ts *TestShape) SetMaterial(m *material.Material) {
ts.Material = m
}
func (ts *TestShape) LocalNormalAt(p tuple.Tuple) *tuple.Tuple {
n := tuple.Vector(p.X, p.Y, p.Z)
return &n
}
func (ts *TestShape) LocalIntersect(r ray.Ray) []Intersection {
ts.SavedRay = &r
return nil
}
func TestDefaultTestShape(t *testing.T) {
ts := NewTestShape()
if !ts.Transform.Equals(matrix.Identity) {
t.Errorf("wanted default transform=%v, got %v", matrix.Identity, ts.Transform)
}
}
func TestAssignTransformToTestShape(t *testing.T) {
ts := NewTestShape()
trans := transforms.Translation(2, 3, 4)
ts.SetTransform(trans)
if !ts.Transform.Equals(trans) {
t.Errorf("wanted assigned transform=%v, got %v", trans, ts.Transform)
}
}
func TestMaterialDefaultTestShape(t *testing.T) {
ts := NewTestShape()
m := material.New()
if *ts.Material != m {
t.Errorf("wanted default transform=%v, got %v", m, ts.Material)
}
}
func TestAssignMaterialTestShape(t *testing.T) {
ts := NewTestShape()
m := material.New()
m.Ambient = 1
ts.SetMaterial(&m)
if *ts.Material != m {
t.Errorf("wanted assigned transform=%v, got %v", m, ts.Material)
}
}
func TestIntersectScaledShapeWithRay(t *testing.T) {
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
s := NewTestShape()
s.SetTransform(transforms.Scaling(2, 2, 2))
_ = Intersect(s, r)
if s.SavedRay.Origin != tuple.Point(0, 0, -2.5) {
t.Errorf("wanted saved ray origin=%v, got %v", tuple.Point(0, 0, -2.5), s.SavedRay.Origin)
}
if s.SavedRay.Direction != tuple.Vector(0, 0, 0.5) {
t.Errorf("wanted saved ray direction=%v, got %v", tuple.Vector(0, 0, 0.5), s.SavedRay.Direction)
}
}
func TestIntersectTranslatedShapeWithRay(t *testing.T) {
r := ray.New(tuple.Point(0, 0, -5), tuple.Vector(0, 0, 1))
s := NewTestShape()
s.SetTransform(transforms.Translation(5, 0, 0))
_ = Intersect(s, r)
if s.SavedRay.Origin != tuple.Point(-5, 0, -5) {
t.Errorf("wanted saved ray origin=%v, got %v", tuple.Point(-5, 0, -5), s.SavedRay.Origin)
}
if s.SavedRay.Direction != tuple.Vector(0, 0, 1) {
t.Errorf("wanted saved ray direction=%v, got %v", tuple.Vector(0, 0, 1), s.SavedRay.Direction)
}
}
func TestNormalOnTranslatedSphere(t *testing.T) {
s := NewTestShape()
s.SetTransform(transforms.Translation(0, 1, 0))
n := NormalAt(s, tuple.Point(0, 1.70711, -0.70711))
if !n.Equals(tuple.Vector(0, 0.70711, -0.70711)) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 0.70711, -0.70711), n)
}
}
func TestNormalOnTranformedSphere(t *testing.T) {
s := NewTestShape()
m := transforms.Chain(transforms.RotationZ(math.Pi/5), transforms.Scaling(1, 0.5, 1))
s.SetTransform(m)
n := NormalAt(s, tuple.Point(0, math.Sqrt2/2, -math.Sqrt2/2))
if !n.Equals(tuple.Vector(0, 0.97014, -0.24254)) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 0.97014, -0.24254), n)
}
}
func TestPlaneNormalIsConstantEverywhere(t *testing.T) {
p := NewPlane()
n1 := p.LocalNormalAt(tuple.Point(0, 0, 0))
n2 := p.LocalNormalAt(tuple.Point(10, 0, -10))
n3 := p.LocalNormalAt(tuple.Point(-5, 0, 150))
if !n1.Equals(tuple.Vector(0, 1, 0)) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 1, 0), n1)
}
if !n2.Equals(tuple.Vector(0, 1, 0)) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 1, 0), n2)
}
if !n3.Equals(tuple.Vector(0, 1, 0)) {
t.Errorf("wanted normal=%v, got %v", tuple.Vector(0, 1, 0), n3)
}
}
func TestIntersectRayParallelToPlane(t *testing.T) {
p := NewPlane()
r := ray.New(tuple.Point(0, 10, 0), tuple.Vector(0, 0, 1))
xs := p.LocalIntersect(r)
if len(xs) != 0 {
t.Errorf("wanted 0 intersections, got %v", len(xs))
}
}
func TestIntersectCoplanarRay(t *testing.T) {
p := NewPlane()
r := ray.New(tuple.Point(0, 0, 0), tuple.Vector(0, 0, 1))
xs := p.LocalIntersect(r)
if len(xs) != 0 {
t.Errorf("wanted 0 intersections, got %v", len(xs))
}
}
func TestRayIntersectPlaneFromAbove(t *testing.T) {
p := NewPlane()
r := ray.New(tuple.Point(0, 1, 0), tuple.Vector(0, -1, 0))
xs := p.LocalIntersect(r)
if len(xs) != 1 {
t.Errorf("wanted 1 intersection, got %v", len(xs))
}
if xs[0].Value != 1 {
t.Errorf("wanted intersection value=%v, got %v", 1, xs[0].Value)
}
if xs[0].Object != p {
t.Errorf("wanted intersection value=%v, got %v", 1, xs[0].Object)
}
}
func TestRayIntersectPlaneFromBelow(t *testing.T) {
p := NewPlane()
r := ray.New(tuple.Point(0, -1, 0), tuple.Vector(0, 1, 0))
xs := p.LocalIntersect(r)
if len(xs) != 1 {
t.Errorf("wanted 1 intersection, got %v", len(xs))
}
if xs[0].Value != 1 {
t.Errorf("wanted intersection value=%v, got %v", 1, xs[0].Value)
}
if xs[0].Object != p {
t.Errorf("wanted intersection value=%v, got %v", 1, xs[0].Object)
}
}
func TestPrecomputeReflectionVector(t *testing.T) {
s := NewPlane()
r := ray.New(tuple.Point(0, 1, -1), tuple.Vector(0, -math.Sqrt2/2, math.Sqrt2/2))
i := NewIntersection(math.Sqrt2/2.0, s)
comps := i.PrepareComputations(r)
if !comps.Reflectv.Equals(tuple.Vector(0, math.Sqrt2/2, math.Sqrt2/2)) {
t.Errorf("wanted reflectv=%v, got %v", tuple.Vector(0, math.Sqrt2/2, math.Sqrt2/2), comps.Reflectv)
}
}
|
// Package loadtest provides services and mechanics for handling loadtests.
package loadtest
import (
"context"
"errors"
"math/rand"
"sync"
"time"
chromedpexecutor "github.com/dkorittki/loago/internal/pkg/worker/executor/browser"
"github.com/dkorittki/loago/pkg/worker/runner"
"github.com/rs/zerolog/log"
)
var (
// ErrInvalidRunnerType indicates an error when an unknown runner type is given.
ErrInvalidRunnerType = errors.New("invalid runner type")
// ErrInvalidWaitBoundaries indicates an error when the minimum wait duration takes longer than the max duration.
ErrInvalidWaitBoundaries = errors.New("min wait duration is longer than max wait duration")
)
// Service handles the execution of load tests.
type Service struct{}
// New returns a new Service.
func New() *Service {
return &Service{}
}
// Run performs continues requests on endpoints.
// It starts a given amount of runners of type browserType (i.e. Chrome or Fake).
// amount controls how many runners are spawned,
// endpoints control where and how often to perform requests,
// results is a channel on which response metrics are written into.
//
// This function runs as long as the context ctx is not closed.
// Closing the context aborts running request and closes each runner.
func (s *Service) Run(ctx context.Context,
browserType BrowserType,
endpoints []*Endpoint,
minWait, maxWait time.Duration,
amount int,
results chan EndpointResult) error {
log.Info().Str("component", "loadtest_service").Msg("starting a new loadtest")
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// create temporary slice random selection of endpoints.
var e []*Endpoint
for i, v := range endpoints {
for j := 0; j < int(v.Weight); j++ {
e = append(e, endpoints[i])
}
}
errChan := make(chan error, amount)
wgDone := make(chan bool)
var wg sync.WaitGroup
wg.Add(amount)
for i := 0; i < amount; i++ {
var r runner.Runner
switch browserType {
case BrowserTypeFake:
r = runner.NewFakeRunner(i)
case BrowserTypeChrome:
e := chromedpexecutor.New()
r = runner.NewChromeRunner(i, e)
default:
return ErrInvalidRunnerType
}
runnerCtx := r.WithContext(ctx)
// Start a new schedule for this specific runner.
id := i
go func() {
err := schedule(runnerCtx, id, e, minWait, maxWait, results, &wg)
if err != nil {
errChan <- err
}
}()
}
go func() {
wg.Wait()
close(wgDone)
}()
select {
case <-wgDone:
log.Info().Msg("schedules finished work successfully")
return nil
case err := <-errChan:
return err
}
}
// schedule repeatedly runs one runner, writing it's result in results.
// It is meant to be used in it's own goroutine and stops
// when the context is canceled.
func schedule(ctx context.Context, id int, endpoints []*Endpoint, minWait, maxWait time.Duration, results chan EndpointResult, wg *sync.WaitGroup) error {
log.Info().
Str("component", "schedule").
Int("id", id).
Msg("start new schedule")
defer wg.Done()
for {
err := sleepBetween(minWait, maxWait)
if err != nil {
return err
}
select {
default:
url := endpoints[rand.Intn(len(endpoints))].URL
ttfb, code, msg, cached, err := runner.Call(ctx, url)
if err != nil {
if err == context.Canceled {
log.Debug().
Str("component", "schedule").
Int("id", id).
Msg("context canceld mid request")
return nil
} else if err == context.DeadlineExceeded {
log.Warn().
Str("component", "schedule").
Int("id", id).
Msg("request timed out")
continue
}
return err
}
results <- EndpointResult{
URL: url,
HTTPStatusCode: code,
HTTPStatusMessage: msg,
TTFB: ttfb,
Cached: cached,
}
case <-ctx.Done():
log.Info().
Str("component", "schedule").
Int("id", id).
Msg("stop schedule")
return nil
}
}
}
// Block for something between min and max duration.
func sleepBetween(min, max time.Duration) error {
var z time.Duration
if min == max {
z = min
} else if min > max {
return ErrInvalidWaitBoundaries
} else {
z = time.Duration(int64(min) + rand.Int63n(int64(max-min)))
}
time.Sleep(z)
return nil
}
|
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHandler(t *testing.T) {
// Sending new request first argument is method, 2nd - route, 3rd - body
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatal(err)
}
// Recorder is like mini-browser that records all our requests
recorder := httptest.NewRecorder()
// Defining the handler func we want to test
hf := http.HandlerFunc(handler)
//Serve the HTTP request to out recorder
hf.ServeHTTP(recorder, req)
//Check the status code is what we expect
if status := recorder.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
//check the response body is what we expect.
expected := `Hello World!`
actual := recorder.Body.String()
if actual != expected {
t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
}
} |
package main
import (
"encoding/json"
"log"
"net/http"
pilot "github.com/bwireman/tuple/pilot/pkg"
)
var p = pilot.NewPilot()
var versions = map[string]map[string]string{}
func handlerWrapper(path string, APIVersion string, handler func(http.ResponseWriter, *http.Request)) (string, func(http.ResponseWriter, *http.Request)) {
fullPath := "/" + APIVersion + path
log.Println("Registered: ", fullPath)
return fullPath, func(rw http.ResponseWriter, rq *http.Request) {
log.Println(rq.Method, " on ", rq.RequestURI)
handler(rw, rq)
}
}
func main() {
port := ":5001"
apiVersion := "v0-1"
versions["versions"] = map[string]string{"v0-1": "/v0-1"}
http.HandleFunc("/", summary)
http.HandleFunc(handlerWrapper("/", apiVersion, root))
http.HandleFunc(handlerWrapper("/register", apiVersion, registerNode))
http.HandleFunc(handlerWrapper("/launch", apiVersion, launchContainer))
log.Print("Listening on ", port)
err := http.ListenAndServe(port, nil)
log.Fatal(err.Error())
}
func summary(rw http.ResponseWriter, rq *http.Request) {
b, _ := json.Marshal(versions)
rw.Write(b)
}
func root(rw http.ResponseWriter, rq *http.Request) {
b, err := p.Serialize()
resp := b
if err != nil {
resp = []byte(err.Error())
}
rw.Write(resp)
}
func registerNode(rw http.ResponseWriter, rq *http.Request) {
if rq.Method == "POST" {
defer rq.Body.Close()
var nr pilot.NodeRegistry
if err := json.NewDecoder(rq.Body).Decode(&nr); err != nil {
log.Println(err.Error())
rw.Write([]byte(err.Error()))
return
}
p.RegisterNode(&nr)
}
rw.Write([]byte("200 OK"))
}
func launchContainer(rw http.ResponseWriter, rq *http.Request) {
if rq.Method == "POST" {
defer rq.Body.Close()
var c pilot.Container
if err := json.NewDecoder(rq.Body).Decode(&c); err != nil {
log.Println(err.Error())
rw.Write([]byte(err.Error()))
return
}
err := p.LaunchContainer(&c)
if err != nil {
log.Println(err.Error())
rw.Write([]byte("500 Error"))
}
}
rw.Write([]byte("200 OK"))
}
|
package main
import (
"github.com/gin-gonic/gin"
"github.com/im-adarsh/text-resource/text-resource/service"
"github.com/im-adarsh/text-resource/text-resource/service/endpoint"
)
func main() {
r := gin.Default()
t := service.NewTranslationService()
endpoint.MakeEndPoint(r, t)
err := r.Run() // listen and serve on 0.0.0.0:8080
if err != nil {
panic("unable to start text resource server")
}
}
|
// Copyright 2023 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 column
import (
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/charset"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/types"
)
// ConvertColumnInfo converts `*ast.ResultField` to `*Info`
func ConvertColumnInfo(fld *ast.ResultField) (ci *Info) {
ci = &Info{
Name: fld.ColumnAsName.O,
OrgName: fld.Column.Name.O,
Table: fld.TableAsName.O,
Schema: fld.DBName.O,
Flag: uint16(fld.Column.GetFlag()),
Charset: uint16(mysql.CharsetNameToID(fld.Column.GetCharset())),
Type: fld.Column.GetType(),
DefaultValue: fld.Column.GetDefaultValue(),
}
if fld.EmptyOrgName {
ci.OrgName = ""
}
if fld.Table != nil {
ci.OrgTable = fld.Table.Name.O
}
if fld.Column.GetFlen() != types.UnspecifiedLength {
ci.ColumnLength = uint32(fld.Column.GetFlen())
}
if fld.Column.GetType() == mysql.TypeNewDecimal {
// Consider the negative sign.
ci.ColumnLength++
if fld.Column.GetDecimal() > types.DefaultFsp {
// Consider the decimal point.
ci.ColumnLength++
}
} else if types.IsString(fld.Column.GetType()) ||
fld.Column.GetType() == mysql.TypeEnum || fld.Column.GetType() == mysql.TypeSet { // issue #18870
// Fix issue #4540.
// The flen is a hint, not a precise value, so most client will not use the value.
// But we found in rare MySQL client, like Navicat for MySQL(version before 12) will truncate
// the `show create table` result. To fix this case, we must use a large enough flen to prevent
// the truncation, in MySQL, it will multiply bytes length by a multiple based on character set.
// For examples:
// * latin, the multiple is 1
// * gb2312, the multiple is 2
// * Utf-8, the multiple is 3
// * utf8mb4, the multiple is 4
// We used to check non-string types to avoid the truncation problem in some MySQL
// client such as Navicat. Now we only allow string type enter this branch.
charsetDesc, err := charset.GetCharsetInfo(fld.Column.GetCharset())
if err != nil {
ci.ColumnLength *= 4
} else {
ci.ColumnLength *= uint32(charsetDesc.Maxlen)
}
}
if fld.Column.GetDecimal() == types.UnspecifiedLength {
if fld.Column.GetType() == mysql.TypeDuration {
ci.Decimal = uint8(types.DefaultFsp)
} else {
ci.Decimal = mysql.NotFixedDec
}
} else {
ci.Decimal = uint8(fld.Column.GetDecimal())
}
// Keep things compatible for old clients.
// Refer to mysql-server/sql/protocol.cc send_result_set_metadata()
if ci.Type == mysql.TypeVarchar {
ci.Type = mysql.TypeVarString
}
return
}
|
package e2e
import (
"testing"
"time"
framework "github.com/operator-framework/operator-sdk/pkg/test"
"github.com/operator-framework/operator-sdk/pkg/test/e2eutil"
)
var (
retryInterval = time.Second * 5
timeout = time.Second * 60
cleanupRetryInterval = time.Second * 1
cleanupTimeout = time.Second * 5
)
// InitController used to initialize the InitController for test purposes
func InitController(t *testing.T) (*framework.Framework, *framework.TestCtx, error) {
ctx := framework.NewTestCtx(t)
err := ctx.InitializeClusterResources(&framework.CleanupOptions{TestContext: ctx, Timeout: cleanupTimeout, RetryInterval: cleanupRetryInterval})
if err != nil {
t.Fatalf("failed to initialize cluster resources: %v", err)
}
t.Log("Initialized cluster resources")
namespace, err := ctx.GetNamespace()
if err != nil {
t.Fatal(err)
}
// get global framework variables
f := framework.Global
// wait for operator to be ready
err = e2eutil.WaitForDeployment(t, f.KubeClient, namespace, "k8s-dns-exposer", 1, retryInterval, timeout)
return f, ctx, err
}
|
package leetcode
import "testing"
func TestNumPairsDivisibleBy60(t *testing.T) {
if numPairsDivisibleBy60([]int{30, 20, 150, 100, 40}) != 3 {
t.Fatal()
}
}
|
// https://en.wikipedia.org/wiki/Linked_list
package main
import (
"errors"
"fmt"
)
// Node have it's value, links to previoues and next element
type Node struct {
Value interface{}
prev, next *Node
list *List
}
// List have links to first and last element
type List struct {
head, tail *Node
}
// Front return head node
func (l *List) Front() *Node {
return l.head
}
// Front return tail node
func (l *List) Back() *Node {
return l.tail
}
// Prev return next node
func (n *Node) Next() *Node {
if nxt := n.next; n.list != nil {
return nxt
}
return nil
}
// Prev return previous node
func (n *Node) Prev() *Node {
if prv := n.prev; n.list != nil {
return prv
}
return nil
}
// Init list with first node
func (l *List) Init(v interface{}) *Node {
node := &Node{Value: v, list: l}
l.head = node
l.tail = node
return node
}
// Insert new node after "at" node
func (l *List) InsertAfter(v interface{}, at *Node) *Node {
node := &Node{Value: v, list: l}
if at == nil {
l.Init(v)
} else {
n := at.next
if n != nil {
n.prev = node
node.next = n
} else {
l.tail = node
}
at.next = node
node.prev = at
node.list = l
}
return node
}
// Insert new node before "at" node
func (l *List) InsertBefore(v interface{}, at *Node) *Node {
node := &Node{Value: v, list: l}
if at == nil {
l.Init(v)
} else {
p := at.prev
if p != nil {
p.next = node
node.prev = p
} else {
l.head = node
}
at.prev = node
node.next = at
node.list = l
}
return node
}
// Push new node after list tail
func (l *List) PushTail(v interface{}) *Node {
return l.InsertAfter(v, l.Front())
}
// Push new node before list head
func (l *List) PushHead(v interface{}) *Node {
return l.InsertBefore(v, l.Front())
}
var errEmpty = errors.New("List is empty")
// Pop standart function
func (l *List) Pop() (v interface{}, err error) {
if l.tail == nil {
err = errEmpty
} else {
v = l.tail.Value
l.tail = l.tail.prev
if l.tail == nil {
l.head = nil
}
}
return v, err
}
// In main only tests
func main() {
l := new(List)
l.PushTail(7)
n0 := l.PushHead(3)
n1 := l.PushTail(4)
l.InsertAfter(6, n1)
l.InsertAfter(5, n1)
l.InsertBefore(1, n0)
l.InsertBefore(2, n0)
for n := l.Front(); n != nil; n = n.Next() {
// fmt.Printf("ME %v | PREV %v | NEXT %v\n", n.Value.(int))
fmt.Printf("%v\n", n)
// fmt.Printf("%v\n", n.Value.(int))
}
fmt.Println()
for v, err := l.Pop(); err == nil; v, err = l.Pop() {
fmt.Printf("%v\n", v)
}
}
|
package main
import (
f "fmt"
"strings"
)
func main() {
s := "Hello, Lucas"
r := strings.NewReader(s)
var s1, s2 string
n, _ := f.Fscanf(r, "%s %s", &s1, &s2)
f.Println("입력 개수 : ", n)
f.Println(s1)
f.Println(s2)
}
|
package controller
import (
"net/http"
"time"
"feeyashop/models"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type productInput struct {
Name string `json:"name"`
Description string `json:"description"`
Price uint `json:"price"`
CategoryID uint `json:"category_id"`
}
// GetAllProduct godoc
// @Summary Get all Product.
// @Description Get a list of Product.
// @Tags Product
// @Produce json
// @Success 200 {object} []models.Product
// @Router /product [get]
func GetAllProduct(c *gin.Context) {
// get db from gin context
db := c.MustGet("db").(*gorm.DB)
var products []models.Product
db.Find(&products)
c.JSON(http.StatusOK, gin.H{"data": products})
}
// CreateProduct godoc
// @Summary Create New Product.
// @Description Creating a new Product.
// @Tags Product
// @Param Body body productInput true "the body to create a new Product"
// @Produce json
// @Success 200 {object} models.Product
// @Router /product [post]
// @Security ApiKeyAuth
// @Param Authorization header string true "Insert your access token" default(Bearer )
func CreateProduct(c *gin.Context) {
// Validate input
var input productInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Create Product
product := models.Product{Name: input.Name}
db := c.MustGet("db").(*gorm.DB)
db.Create(&product)
c.JSON(http.StatusOK, gin.H{"data": product})
}
// UpdateProduct godoc
// @Summary Update Product.
// @Description Update Product by id.
// @Tags Product
// @Produce json
// @Param id path string true "Product id"
// @Param Body body productInput true "the body to update product"
// @Success 200 {object} models.Product
// @Router /product/{id} [patch]
// @Security ApiKeyAuth
// @Param Authorization header string true "Insert your access token" default(Bearer )
func UpdateProduct(c *gin.Context) {
db := c.MustGet("db").(*gorm.DB)
// Get model if exist
var product models.Product
if err := db.Where("id = ?", c.Param("id")).First(&product).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
// Validate input
var input productInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var updatedInput models.Product
updatedInput.Name = input.Name
updatedInput.Description = input.Description
updatedInput.Price = input.Price
updatedInput.CategoryID = input.CategoryID
updatedInput.UpdatedAt = time.Now()
db.Model(&product).Updates(updatedInput)
c.JSON(http.StatusOK, gin.H{"data": product})
}
// DeleteProduct godoc
// @Summary Delete one Product.
// @Description Delete a Product by id.
// @Tags Product
// @Produce json
// @Param id path string true "Product id"
// @Success 200 {object} map[string]boolean
// @Router /product/{id} [delete]
// @Security ApiKeyAuth
// @Param Authorization header string true "Insert your access token" default(Bearer )
func DeleteProduct(c *gin.Context) {
// Get model if exist
db := c.MustGet("db").(*gorm.DB)
var product models.Product
if err := db.Where("id = ?", c.Param("id")).First(&product).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
db.Delete(&product)
c.JSON(http.StatusOK, gin.H{"data": true})
}
|
/*
Lets define a pointer sequence to be any sequence such that a(n) = a((n-1)-(a(n-1))) forall n greater than some finite number. For example if our sequence begun with
3 2 1
Our next term would be 2, because a(n-1) = 1, (n-1)-1 = 1, a(1) = 2 (this example is zero index however it does not matter what index you use the calculation will always be the same.). If we repeat the process we get the infinite sequence
3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2
Task
Given some initial array of positive integers output the pointer sequence starting with that array.
Output types
Output is intended to be flexible, if you choose to write a function as your program it can return, either an infinite list of integers or a function that indexes the sequence. If you choose to write a full program you may output terms of the sequence indefinitely.
You may also choose to take two inputs, the starting array and an index. If you choose to do this you need only output the term of the sequence at that index.
You will never be given a sequence that requires indexing before the beginning of the sequence. For example 3 is not a valid input because you would need terms before the 3 to resolve the next term.
This is code-golf so your score will be the number of bytes in your program with a lower score being better.
Test Cases
test cases are truncated for simplicity
2 1 -> 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 ...
2 3 1 -> 2 3 1 3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 ...
3 3 1 -> 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 ...
4 3 1 -> 4 3 1 3 4 4 3 3 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 ...
*/
package main
import (
"fmt"
"reflect"
)
func main() {
test([]int{2, 1}, []int{2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2})
test([]int{2, 3, 1}, []int{2, 3, 1, 3, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2})
test([]int{3, 3, 1}, []int{3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3})
test([]int{4, 3, 1}, []int{4, 3, 1, 3, 4, 4, 3, 3, 4, 4, 4, 3, 4, 4, 4, 4, 3, 4, 4, 4, 4, 3, 4, 4, 4, 4, 3, 4})
}
func test(a, r []int) {
p := seq(a, len(r))
fmt.Printf("%v\n%v\n\n", p, r)
assert(reflect.DeepEqual(p, r))
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func seq(a []int, n int) []int {
r := make([]int, n)
for i := 0; i < n; i++ {
if i < len(a) {
r[i] = a[i]
} else {
r[i] = r[(i-1)-r[i-1]]
}
}
return r
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.