text stringlengths 11 4.05M |
|---|
package utils
import "encoding/base64"
// basic64 解码
func DecodeBasic64(s string) ([]byte, error) {
var (
b []byte
err error
)
b, err = base64.StdEncoding.DecodeString(s)
return b, err
}
|
package main
import (
"bufio"
"fmt"
"os"
"runtime/pprof"
"sort"
)
var stdin *bufio.Reader
var stdout *bufio.Writer
func init() {
stdin = bufio.NewReader(os.Stdin)
stdout = bufio.NewWriter(os.Stdout)
}
func scan(args ...interface{}) (int, error) {
return fmt.Fscan(stdin, args...)
}
func printf(format string, args ...interface{}) {
fmt.Fprintf(stdout, format, args...)
}
func MinInt(args ...int) int {
res := 0
for i, v := range args {
if i == 0 {
res = v
} else if res > v {
res = v
}
}
return res
}
type Candidate struct {
r, c int
cost int64
}
type CandidateArray []Candidate
func (s CandidateArray) Len() int {
return len(s)
}
func (s CandidateArray) Less(i, j int) bool {
if s[i].cost != s[j].cost {
return s[i].cost < s[j].cost
}
if s[i].r != s[j].r {
return s[i].r < s[j].r
}
return s[i].c < s[j].c
}
func (s CandidateArray) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type MinHeap struct {
a []int
size int
count_map map[int]int
}
func NewMinHeap() *MinHeap {
return &MinHeap{count_map: make(map[int]int)}
}
func (h *MinHeap) Push(value int) {
h.count_map[value]++
if h.count_map[value] > 1 {
return
}
if h.size == len(h.a) {
h.a = append(h.a, value)
} else {
h.a[h.size] = value
}
h.size++
k := h.size - 1
for k > 0 {
p := (k - 1) / 2
if h.a[p] <= h.a[k] {
break
}
h.a[k], h.a[p] = h.a[p], h.a[k]
k = p
}
}
func (h *MinHeap) Remove(value int) {
h.count_map[value]--
if h.count_map[value] > 0 {
return
}
}
func (h *MinHeap) GetMin() int {
for true {
if h.count_map[h.a[0]] > 0 {
return h.a[0]
}
h.a[0] = h.a[h.size - 1]
h.size--
k := 0
for k * 2 + 1 < h.size {
child := k * 2 + 1
if child + 1 < h.size && h.a[child + 1] < h.a[child] {
child++
}
if h.a[k] <= h.a[child] {
break
}
h.a[k], h.a[child] = h.a[child], h.a[k]
k = child
}
}
return -1
}
var n, m, a, b int
// original map
var s [1000][1000]int32
// rangeSum map, rangeSum[i][j] is the sum of s[0..i][0..j]
var rangeSum [1000][1000]int64
// rangeMin map, rangeMin[i][j] is the min of s[0..i][0..j]
var rangeMin [1000][1000]int32
// help structures for rangeMin
// rangeMinPerC[c][jr][ir] is the min of s[ir..(ir + (1<<jr) - 1)][c]
var rangeMinPerC [1000][10][1000]int32
// sort candidates
var candidates [1000000]Candidate
// visited map
var visited [1000][1000]bool
func log2(n int) uint {
i := uint(0)
for t := 1; t * 2 <= n; t *= 2 {
i++
}
return i
}
func initRangeMinPerC() {
for c := 0; c < m; c++ {
for r := 0; r < n; r++ {
rangeMinPerC[c][0][r] = s[r][c]
}
maxJr := log2(n)
for jr := uint(1); jr <= maxJr; jr++ {
for r := 0; r < n; r++ {
t := int(rangeMinPerC[c][jr-1][r])
if r + (1 << (jr - 1)) < n {
t = MinInt(t, int(rangeMinPerC[c][jr-1][r + (1 << (jr - 1))]))
}
rangeMinPerC[c][jr][r] = int32(t)
}
}
}
}
func getRangeMinPerC(c, r1, r2 int) int {
length := r2 - r1 + 1
level := log2(length)
return MinInt(int(rangeMinPerC[c][level][r1]), int(rangeMinPerC[c][level][r2 - (1<<level) + 1]))
}
func preprocessRangeMin() {
initRangeMinPerC()
var row [10000]int
for i := 0; i <= n - a; i++ {
for j := 0; j < m; j++ {
row[j] = getRangeMinPerC(j, i, i + a - 1)
}
h := NewMinHeap()
for j := 0; j < b; j++ {
h.Push(row[j])
}
for j := 0; j <= m - b; j++ {
rangeMin[i][j] = int32(h.GetMin())
if j < m - b {
h.Push(row[j + b])
h.Remove(row[j])
}
}
}
}
func getRangeMin(r1, r2, c1, c2 int) int {
return int(rangeMin[r1][c1])
}
func getRangeSum(x1, x2, y1, y2 int) int64 {
t := rangeSum[x2][y2]
if x1 > 0 {
t -= rangeSum[x1 - 1][y2]
}
if y1 > 0 {
t -= rangeSum[x2][y1 - 1]
}
if x1 > 0 && y1 > 0 {
t += rangeSum[x1-1][y1-1]
}
return t
}
func isVisited(c Candidate) bool {
return visited[c.r][c.c] || visited[c.r][c.c + b - 1] ||
visited[c.r + a - 1][c.c] || visited[c.r + a - 1][c.c + b - 1]
}
func main() {
if true {
f, _ := os.Create("profile")
defer f.Close()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
for true {
if _, err := scan(&n, &m, &a, &b); err != nil {
break
}
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
scan(&s[i][j])
}
}
for i := 0; i < n; i++ {
prevInLine := int64(0)
for j := 0; j < m; j++ {
rangeSum[i][j] = int64(s[i][j]) + prevInLine
prevInLine += int64(s[i][j])
if i > 0 {
rangeSum[i][j] += rangeSum[i-1][j]
}
}
}
preprocessRangeMin()
k := 0
for i := 0; i <= n - a; i++ {
for j := 0; j <= m - b; j++ {
sum := getRangeSum(i, i + a - 1, j, j + b - 1)
min := getRangeMin(i, i + a - 1, j, j + b - 1)
//printf("i %d, j %d, sum %d, min %d\n", i, j, sum, min)
candidates[k].cost = sum - int64(min) * int64(a * b)
candidates[k].r = i
candidates[k].c = j
k++
}
}
sort.Sort(CandidateArray(candidates[0:k]))
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
visited[i][j] = false
}
}
var res []Candidate
for t := 0; t < k; t++ {
if isVisited(candidates[t]) {
continue
}
for i := 0; i < a; i++ {
for j := 0; j < b; j++ {
visited[i+candidates[t].r][j+candidates[t].c] = true
}
}
res = append(res, candidates[t])
}
printf("%d\n", len(res))
for i := 0; i < len(res); i++ {
printf("%d %d %d\n", res[i].r + 1, res[i].c + 1, res[i].cost)
}
stdout.Flush()
}
} |
package insert_sort
func InsertSort(a []int) {
var length = len(a)
for i := 1; i < length; i++ {
if a[i] < a[i-1] {
x := i
for j := i - 1; j >= 0; j-- {
if a[x] < a[j] {
a[x], a[j] = a[j], a[x]
x = j
}
}
}
}
}
|
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"github.com/NYTimes/gziphandler"
"github.com/gorilla/mux"
)
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "UI server up and running!")
}
func main() {
// Use default API url or read from environment variable
apiURLParam := "http://localhost:8080"
if os.Getenv("API_URL") != "" {
apiURLParam = os.Getenv("API_URL")
}
apiURL, err := url.Parse(apiURLParam)
if err != nil {
log.Fatalf("Invalid api url (Error: %s).", err)
}
log.Printf("Starting UI server for %s ...\n", apiURL)
router := mux.NewRouter()
// Health check
router.HandleFunc("/health", healthCheckHandler)
// Proxy all requests to the API
router.HandleFunc("/api/{wildcard:.*}", func(w http.ResponseWriter, r *http.Request) {
proxy := httputil.NewSingleHostReverseProxy(apiURL)
proxy.ServeHTTP(w, r)
})
// Serve static assets (gzipped)
fileServer := http.FileServer(http.Dir("."))
fileServerWithGz := gziphandler.GzipHandler(fileServer)
router.Handle("/{wildcard:.*}", fileServerWithGz)
log.Fatal(http.ListenAndServe(":3000", router))
}
|
package main
import (
"bytes"
"os"
"testing"
)
func TestTokenizer_HasMoreTokens(t *testing.T) {
tk := NewTokenizer(bytes.NewBufferString(`
// comment1
/* Foo class */
class Foo {
function void main() {
var int i;
var String s;
let i = 100;
let s = "hello world";
}
}
`))
for tk.HasMoreTokens() {
t.Logf("Token: %#v, TokenType: %s", tk.token, tk.tokenType)
}
}
func TestTokenizer_HasMoreTokens2(t *testing.T) {
f, err := os.Open("test/ArrayTest/Main.jack")
if err != nil {
t.Fatal(err)
}
tk := NewTokenizer(f)
for tk.HasMoreTokens() {
t.Logf("Token: %#v, TokenType: %s", tk.token, tk.tokenType)
}
}
|
// print random 10 numbers
package main
import (
"fmt"
"math/rand"
)
func main() {
var count = 0
for count < 10 {
var num = rand.Intn(10) + 1
fmt.Println(num, "->", count)
count++
}
}
// 2 -> 0
// 8 -> 1
// 8 -> 2
// 10 -> 3
// 2 -> 4
// 9 -> 5
// 6 -> 6
// 1 -> 7
// 7 -> 8
// 1 -> 9
|
package controllers
import (
"errors"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
"log"
"net/http"
"strings"
"telego/app/limiters"
"telego/app/models"
"telego/app/services"
"telego/app/utils"
"telego/app/validators"
)
var GetCollaboratorsByProjectId = func(c echo.Context) error {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
return echo.ErrBadRequest
}
db := c.Get("db").(*gorm.DB)
authUser := c.Get("account").(*models.Account)
var collab models.Collaborator
db.Model(&models.Collaborator{}).Where(&models.Collaborator{AccountID: &authUser.Id, ProjectID: id}).First(&collab)
return c.JSON(http.StatusOK, collab)
}
var AddCollaborator = func(c echo.Context) error {
collab := c.Get("body").(*validators.CollaboratorCreate)
db := c.Get("db").(*gorm.DB)
authUser := c.Get("account").(*models.Account)
if authUser.Email == collab.Email {
return c.JSON(http.StatusBadRequest, utils.JsonError{
Message: "Account cannot invite himself",
})
}
var project models.Project
result := db.First(&project, collab.ProjectId)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return echo.ErrNotFound
}
var inviteAccount models.Account
newCollab := models.Collaborator{ProjectID: collab.ProjectId}
result = db.Model(&inviteAccount).Where(&models.Account{Email: collab.Email}).First(&inviteAccount)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
// We should set invitedEmail field only when inviteAccountId is not provided
newCollab.InvitedEmail = collab.Email
} else {
newCollab.AccountID = &inviteAccount.Id
}
if err := db.Transaction(func(tx *gorm.DB) error {
if err := limiters.LimitCollaborators(tx, project.Id, authUser); err != nil{
return err
}
if err := tx.Where(&newCollab).
Attrs(&models.Collaborator{AccessType: collab.AccessType}).
FirstOrCreate(&newCollab).Error; err != nil {
return err
}
return nil
}); err != nil {
if errors.Is(err, utils.LimitCollabReached){
return c.JSON(http.StatusBadRequest, utils.JsonError{Message: err.Error()})
}
log.Println(err)
return echo.ErrInternalServerError
}
invitedByName := authUser.Name
if invitedByName == "" {
invitedByName = strings.Split(authUser.Email, "@")[0]
}
services.SendCollaborationInvitationMail(collab.Email, inviteAccount.Name, invitedByName, project.Name)
return c.JSON(http.StatusOK, newCollab)
//TODO: notify on websocket that a new collab was added
}
var UpdateCollaborator = func(c echo.Context) error {
v := c.Get("body").(*validators.CollaboratorUpdate)
db := c.Get("db").(*gorm.DB)
authUser := c.Get("account").(*models.Account)
collab := &models.Collaborator{Meta: v.Meta}
db.Model(&collab).Debug().
Where(&models.Collaborator{AccountID: &authUser.Id, ProjectID: v.ProjectId}).
Updates(&collab)
return c.JSON(http.StatusOK, collab)
}
var ChangeAccess = func(c echo.Context) error {
v := c.Get("body").(*validators.CollaboratorChangeAccess)
db := c.Get("db").(*gorm.DB)
collab := models.Collaborator{AccessType: v.AccessType}
if result := db.Model(&models.Collaborator{}).
Where(&models.Collaborator{ID: v.CollaboratorId, ProjectID: v.ProjectId}).
Updates(&collab); result.Error != nil {
return echo.ErrInternalServerError
}
c.JSON(http.StatusOK, collab)
if len(collab.InvitedEmail) > 0 {
return nil
}
//TODO: notify shareDB to change the collaborator from the active websocket connections
return nil
}
var RemoveCollaborator = func(c echo.Context) error {
v := c.Get("body").(*validators.CollaboratorDelete)
db := c.Get("db").(*gorm.DB)
var collab models.Collaborator
result := db.Model(&models.Collaborator{}).Where(&models.Collaborator{ID: v.CollaboratorId}).First(&collab)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return echo.ErrNotFound
}
if collab.AccessType == models.OwnerCollaborator {
return echo.ErrForbidden
}
// it's important to pass both projectId and collaboratorId
// in order to delete collaborators only from that specific project
result = db.
Where(&models.Collaborator{ProjectID: v.ProjectId, ID: collab.ID}).
Delete(&models.Collaborator{})
if result.Error != nil {
return echo.ErrInternalServerError
}
if result.RowsAffected == 0 {
return echo.ErrNotFound
}
c.JSON(http.StatusOK, true)
//TODO: notify shareDB to remove the collaborator from the active websocket connections
return nil
}
|
package main
import (
"fmt"
"sort"
)
type Node struct {
id int
weight int
visited bool
children []*Node
}
func main() {
var q int // number of queries
fmt.Scanln(&q)
for i := 0; i < q; i++ {
var nodes = make(map[int]*Node)
var n int // number of nodes
var m int // number of edges
fmt.Scan(&n, &m)
for j := 0; j < m; j++ {
var n1, n2 int
fmt.Scan(&n1, &n2)
// create both nodes if they don't exist
if _, ok := nodes[n1]; !ok {
nodes[n1] = &Node{id: n1, weight: 0, visited: false, children: make([]*Node, n)}
}
if _, ok := nodes[n2]; !ok {
nodes[n2] = &Node{id: n2, weight: 0, visited: false, children: make([]*Node, n)}
}
node1 := nodes[n1]
node2 := nodes[n2]
node1.children = append(node1.children, node2)
node2.children = append(node2.children, node1)
}
var startNode int
fmt.Scan(&startNode)
bfs(startNode, nodes)
// fill in the gaps for nodes not mentioned in the queries
for k := 1; k <= n; k++ {
if _, ok := nodes[k]; !ok {
nodes[k] = &Node{id: k, weight: 0, visited: false, children: make([]*Node, n)}
}
}
// sort nodes by id (key)
var keys []int
for k := range nodes {
keys = append(keys, k)
}
sort.Ints(keys)
// print all distances
for _, k := range keys {
if k == startNode {
continue
}
n := nodes[k]
if n.weight <= 0 {
fmt.Print("-1")
} else {
fmt.Print(n.weight)
}
fmt.Print(" ")
}
fmt.Println() // new line for the next query to start clean
}
}
func bfs(startNode int, nodes map[int]*Node) {
// fmt.Printf("[bfs] startNode = %d, nodes = %v\n", startNode, nodes)
var queue []*Node
start := nodes[startNode]
queue = append(queue, start)
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node != nil {
node.visited = true
for _, child := range node.children {
if child == nil || child.visited {
continue
}
child.visited = true
child.weight += node.weight + 6
queue = append(queue, child)
}
}
}
}
|
// Package worker implements the function to handle different jobs concurrently.
package worker
import (
"fmt"
"sync"
"sync/atomic"
)
// JobFunc is a func that makes some job and returns an error if it's failed.
type JobFunc func() error
// Handle handles concurrently the jobFuncs at the same time, depending on provided maxConcurrentJobsCount.
// maxErrCount shows how many errors are acceptable. If there are more errors than the maxErrCount then
// the function will return an error.
func Handle(jobFuncs []JobFunc, maxConcurrentJobsCount, maxErrCount int) error {
// To make sure that all jobs will be finished..
var wg sync.WaitGroup
// Channel to quit when the max error count is reached.
errorQuit := make(chan struct{})
// errCount shows how many jobs already have returned errors. If errCount will be same or greater
// than the maxErrCount then the handling will be stopped.
var errCount int32
// To control maximum concurrent jobs handling at the same time.
queue := make(chan struct{}, maxConcurrentJobsCount)
for _, jobFunc := range jobFuncs {
queue <- struct{}{}
wg.Add(1)
go func(job JobFunc, queue <-chan struct{}) {
if atomic.LoadInt32(&errCount) > int32(maxErrCount) {
errorQuit <- struct{}{}
return
}
err := job()
if err != nil {
atomic.AddInt32(&errCount, 1)
}
<-queue
wg.Done()
}(jobFunc, queue)
}
// The goroutine waits until all jobs will be handled.
done := make(chan struct{})
go func() {
wg.Wait()
close(queue)
done <- struct{}{}
}()
select {
case <-errorQuit:
// The handling is failed due to too many errors.
return getMaxCountReachedError(maxErrCount)
case <-done:
// The handling is finished.
return nil
}
}
func getMaxCountReachedError(maxErrCount int) error {
return fmt.Errorf("error stack overflow. Max acceptable count is %d", maxErrCount)
}
|
package main
import "fmt"
// Multiple Aggregation: Bird & Lizard types with Age fields combine into a Dragon; Introduce Aged interface
// Decorator: Shape interface with Render method; Circle & Square types; Make them have color as well; Introduce ColoredShape and OpacityShape type
func greetingPrinter(printFn func(string)) func(string) {
return func(name string) {
fmt.Print("Hello, ")
printFn(name)
}
}
func print(name string) {
fmt.Println("My name is:", name)
}
func main() {
greetingPrinter(print)("Gaurav")
}
|
package smartling
import (
"fmt"
"io"
)
const (
endpointDownloadTranslation = "/files-api/v2/projects/%s/locales/%s/file"
)
// DownloadTranslation downloads specified translated file for specified
// locale. Check FileDownloadRequest for more options.
func (client *Client) DownloadTranslation(
projectID string,
localeID string,
request FileDownloadRequest,
) (io.Reader, error) {
reader, _, err := client.Get(
fmt.Sprintf(endpointDownloadTranslation, projectID, localeID),
request.GetQuery(),
)
if err != nil {
return nil, fmt.Errorf(
"failed to download translated file: %s", err,
)
}
return reader, nil
}
|
package injector
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"k8s.io/api/admission/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes"
)
// Injector interface that starts a web server listening on MutatingAdmissionWebHooks
// of Kubernetes (MutatingAdmissionController)
type Injector interface {
Init(cfg Config, kubeClient *kubernetes.Clientset) error
Run(ctx context.Context) error
}
type injector struct {
server *http.Server
config Config
deserializer runtime.Decoder
kubeClient *kubernetes.Clientset
}
// NewInjector creates a new Injector
func NewInjector() Injector {
mux := http.NewServeMux()
i := &injector{
server: &http.Server{
Addr: fmt.Sprintf(":%d", 8443),
Handler: mux,
},
deserializer: serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer(),
}
mux.HandleFunc("/mutate", i.handleRequest)
return i
}
func (i *injector) Init(cfg Config, kubeClient *kubernetes.Clientset) error {
i.config = cfg
i.kubeClient = kubeClient
return nil
}
func (i *injector) Run(ctx context.Context) error {
doneChannel := make(chan struct{})
go func() {
select {
case <-ctx.Done():
log.Println("injector: shutting down")
shwdctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
i.server.Shutdown(shwdctx) // nolint: errcheck
case <-doneChannel:
}
}()
log.Printf("injector: starting server on port %v\n", i.server.Addr)
if err := i.server.ListenAndServeTLS(i.config.TLSCertFile, i.config.TLSKeyFile); err != http.ErrServerClosed {
log.Printf("injector: can't start server: %s\n", err)
close(doneChannel)
return err
}
close(doneChannel)
return nil
}
func (i *injector) handleRequest(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var data []byte
var admissionResponse *v1beta1.AdmissionResponse
var patchOps []PatchOperation
var err error
admissionReview := v1beta1.AdmissionReview{}
// read and check body
if r.Body != nil {
if d, err := ioutil.ReadAll(r.Body); err == nil {
data = d
}
}
if len(data) == 0 {
log.Println("injector: empty request body received")
http.Error(w, "Empty request body", http.StatusBadRequest)
return
}
// check Content-Type
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
log.Printf("injector: request Content-Type=%s, expect application/json\n", contentType)
http.Error(w, "invalid Content-Type, expect `application/json`", http.StatusUnsupportedMediaType)
return
}
// deserialize review
if _, _, err = i.deserializer.Decode(data, nil, &admissionReview); err != nil {
log.Printf("injector: Can't decode body: %v\n", err)
respondWithError(nil, w, err)
return
}
if admissionReview.Request.Kind.Kind != "Pod" {
log.Printf("injector: invalid kind for review: %s", admissionReview.Kind)
respondWithError(&admissionReview, w, fmt.Errorf("invalid kind of review: %s", admissionReview.Kind))
return
}
pod, err := deserializePod(admissionReview.Request)
if err != nil {
respondWithError(&admissionReview, w, err)
return
}
patchOps = i.patchPod(pod, i.config.Namespace)
if len(patchOps) == 0 {
admissionResponse = &v1beta1.AdmissionResponse{
Allowed: true,
}
admissionResponse.Result = &metav1.Status{
Status: "Success",
}
} else {
patchType := v1beta1.PatchTypeJSONPatch
jsonPatch, err := json.Marshal(patchOps)
if err != nil {
respondWithError(&admissionReview, w, err)
return
}
log.Printf("Containers patched: %v", string(jsonPatch))
admissionResponse = &v1beta1.AdmissionResponse{
Allowed: true,
PatchType: &patchType,
Patch: jsonPatch,
}
admissionResponse.Result = &metav1.Status{
Status: "Success",
}
}
arResponse := v1beta1.AdmissionReview{}
arResponse.Response = admissionResponse
if admissionReview.Request != nil {
arResponse.Response.UID = admissionReview.Request.UID
}
writeAdmissionResponse(&arResponse, w, http.StatusOK)
}
func toAdmissionResponse(err error) *v1beta1.AdmissionResponse {
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
func respondWithError(ar *v1beta1.AdmissionReview, w http.ResponseWriter, err error) {
response := toAdmissionResponse(err)
review := v1beta1.AdmissionReview{}
review.Response = response
if nil != ar && ar.Request != nil {
review.Response.UID = ar.Request.UID
}
writeAdmissionResponse(&review, w, http.StatusInternalServerError)
}
func writeAdmissionResponse(ar *v1beta1.AdmissionReview, w http.ResponseWriter, statusCode int) {
json, err := json.Marshal(ar)
if err != nil {
log.Printf("injector: can't serialize response AdmissionReview: %s", err)
http.Error(w, fmt.Sprintf("can't serialize response: %s", err), http.StatusInternalServerError)
return
}
w.WriteHeader(statusCode)
_, err = w.Write(json)
if err != nil {
log.Printf("injector: cant write AdmissionReview response: %s", err)
http.Error(w, fmt.Sprintf("can't write AdmissionReview response %s", err), http.StatusInternalServerError)
}
}
func deserializePod(req *v1beta1.AdmissionRequest) (*corev1.Pod, error) {
pod := &corev1.Pod{}
if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
log.Printf("can't deserialize pod from json: %v", err)
return nil, err
}
return pod, nil
}
|
package netxmocks
import (
"crypto/tls"
"errors"
"reflect"
"testing"
)
func TestTLSConnConnectionState(t *testing.T) {
state := tls.ConnectionState{Version: tls.VersionTLS12}
c := &TLSConn{
MockConnectionState: func() tls.ConnectionState {
return state
},
}
out := c.ConnectionState()
if !reflect.DeepEqual(out, state) {
t.Fatal("not the result we expected")
}
}
func TestTLSConnHandshake(t *testing.T) {
expected := errors.New("mocked error")
c := &TLSConn{
MockHandshake: func() error {
return expected
},
}
err := c.Handshake()
if !errors.Is(err, expected) {
t.Fatal("not the error we expected", err)
}
}
|
// Generated by ntoolkit/futures
package cparser
import "ntoolkit/futures"
import "ntoolkit/commands"
type DeferredCommand struct {
DeferredValue futures.Promise
}
func (promise *DeferredCommand) init() {
if promise.DeferredValue == nil {
promise.DeferredValue = &futures.DeferredValue{}
}
}
func (promise *DeferredCommand) Resolve(result commands.Command) {
promise.init()
promise.DeferredValue.PResolve(result)
}
func (promise *DeferredCommand) Reject(err error) {
promise.init()
promise.DeferredValue.PReject(err)
}
func (promise *DeferredCommand) Errors() []error {
promise.init()
return promise.DeferredValue.PErrors()
}
func (promise *DeferredCommand) Then(resolve func(commands.Command), reject func(error)) *DeferredCommand {
promise.init()
promise.DeferredValue.PThen(func(value interface{}) {
if v, ok := value.(commands.Command); ok {
resolve(v)
} else {
panic("Invalid value used to resolve DeferredCommand")
}
}, reject)
return promise
}
func (promise *DeferredCommand) PThen(result func(interface{}), reject func(error)) futures.Promise {
promise.init()
return promise.DeferredValue.PThen(result, reject)
}
func (promise *DeferredCommand) PErrors() []error {
promise.init()
return promise.DeferredValue.PErrors()
}
func (promise *DeferredCommand) PResolve(result interface{}) {
promise.init()
promise.DeferredValue.PResolve(result)
}
func (promise *DeferredCommand) PReject(err error) {
promise.init()
promise.DeferredValue.PReject(err)
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package power
import (
"bufio"
"context"
"os"
"strconv"
"time"
"chromiumos/tast/common/action"
"chromiumos/tast/errors"
)
// readFirstLine reads the first line from a file.
// Line feed character will be removed to ease converting the string
// into other types.
func readFirstLine(ctx context.Context, filePath string) (string, error) {
var result string
err := action.Retry(3, func(ctx context.Context) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
if scanner.Scan() {
result = scanner.Text()
return nil
}
if err := scanner.Err(); err != nil {
return err
}
return errors.Errorf("found no content in %q", filePath)
}, 100*time.Millisecond)(ctx)
return result, err
}
// readFloat64 reads a line from a file and converts it into float64.
func readFloat64(ctx context.Context, filePath string) (float64, error) {
str, err := readFirstLine(ctx, filePath)
if err != nil {
return 0., err
}
return strconv.ParseFloat(str, 64)
}
// readInt64 reads a line from a file and converts it into int64.
func readInt64(ctx context.Context, filePath string) (int64, error) {
str, err := readFirstLine(ctx, filePath)
if err != nil {
return 0, err
}
return strconv.ParseInt(str, 10, 64)
}
|
package main
import (
"fmt"
"net/http"
"os"
"sync"
"github.com/gorilla/handlers"
)
func main() {
mux := http.NewServeMux()
newHandler := func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("hello world!"))
}
mux.HandleFunc("/hello", newHandler)
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/", fs)
wrap := handlers.LoggingHandler(os.Stdout, mux)
var wg sync.WaitGroup
wg.Add(1)
go func() {
err := http.ListenAndServe(":3030", wrap)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
wg.Done()
}()
fmt.Println("vim-go")
wg.Wait()
}
|
package main
import (
"log"
"net/http"
"github.com/gorilla/mux" // Trying Gorilla Mux
)
func YourHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Gorilla!\n"))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", YourHandler)
log.Printf("Serving on port 8080")
err := http.ListenAndServe(":8080", r)
log.Fatal(err)
}
|
package main
import (
"fmt"
"github.com/slasyz/wundercli/api"
"github.com/slasyz/wundercli/config"
"os"
)
// Gets parameters from command-line arguments or set them empty if not present.
func getParams(count int) (result []string) {
result = make([]string, count)
// From command-line arguments
for i := 0; i < len(os.Args)-3; i++ {
result[i] = os.Args[i+3]
}
// Empty parameters
for i := len(os.Args) - 3; i < count; i++ {
result[i] = ""
}
fmt.Println()
return result
}
func main() {
exists, err := config.OpenConfig()
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
os.Exit(1)
}
if !exists {
api.DoAuth()
config.SaveConfig()
}
// Parse command-line arguments.
if len(os.Args) <= 2 {
cmdHelp()
}
switch os.Args[1] {
case "list":
switch os.Args[2] {
case "all":
err = cmdListAll()
case "show":
params := getParams(1)
err = cmdListShow(params[0])
case "create":
params := getParams(1)
err = cmdListCreate(params[0])
case "remove":
params := getParams(1)
err = cmdListRemove(params[0])
default:
cmdHelp()
}
case "task":
switch os.Args[2] {
case "create":
params := getParams(2)
err = cmdTaskCreate(params[0], params[1])
case "check":
params := getParams(1)
err = cmdTaskCheck(params[0])
case "edit":
params := getParams(1)
err = cmdTaskEdit(params[0])
default:
cmdHelp()
}
default:
cmdHelp()
}
if err != nil {
fmt.Printf("Error: %s\n\n", err.Error())
os.Exit(1)
}
}
|
package domainbinding
import (
catalog "catalog-controller/pkg/apis/catalogcontroller/v1alpha1"
catalogClient "catalog-controller/pkg/client/clientset/versioned"
goErrors "errors"
"alauda.io/diablo/src/backend/api"
"alauda.io/diablo/src/backend/errors"
"alauda.io/diablo/src/backend/resource/dataselect"
)
// DomainBindingList struct
type DomainBindingList struct {
ListMeta api.ListMeta `json:"listMeta"`
DomainBindings []DomainBindingDetail `json:"domainBindings"`
Errors []error `json:"errors"`
}
// GetDomainBindingList func
func GetDomainBindingList(client catalogClient.Interface, dsQuery *dataselect.DataSelectQuery) (dbl *DomainBindingList, e error) {
db, err := client.CatalogControllerV1alpha1().Domains().List(api.ListEverything)
if db == nil {
return nil, goErrors.New("get nil domain list")
}
nonCriticalErrors, criticalError := errors.HandleError(err)
if criticalError != nil {
return nil, criticalError
}
domainMap := make(map[string]*catalog.Domain)
for _, item := range db.Items {
domainMap[item.Name] = item.DeepCopy()
}
dbs, err := client.CatalogControllerV1alpha1().DomainBindings().List(api.ListEverything)
nonCriticalErrors, criticalError = errors.HandleError(err)
if criticalError != nil {
return nil, criticalError
}
domainBindings := make([]DomainBindingDetail, 0, len(dbs.Items))
for _, item := range dbs.Items {
dName := item.Spec.DomainRef.Name
if domainMap[dName] == nil {
continue
}
detail := generateDomainBindingDetail(domainMap[dName], &item)
domainBindings = append(domainBindings, *detail)
}
domainBindingCells, filteredTotal := dataselect.GenericDataSelectWithFilter(toCells(domainBindings), dsQuery)
items := fromCells(domainBindingCells)
return &DomainBindingList{
ListMeta: api.ListMeta{TotalItems: filteredTotal},
DomainBindings: items,
Errors: nonCriticalErrors,
}, nil
}
|
package main
import (
"github.com/sodhigagan/MyPractice/I/Constants"
"github.com/sodhigagan/MyPractice/I/Variables"
)
func main() {
Constants.Myname()
Constants.DOB()
Variables.Old()
//fmt.Println("so that makes me .... years old") //will add calulation using package variables once I figure out how to calculate
}
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2020 Datadog, Inc.
package main
import (
"os"
"github.com/DataDog/datadog-operator/cmd/kubectl-datadog/datadog"
"github.com/spf13/pflag"
"k8s.io/cli-runtime/pkg/genericclioptions"
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
func main() {
flags := pflag.NewFlagSet("kubectl-datadog", pflag.ExitOnError)
pflag.CommandLine = flags
root := datadog.NewCmd(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})
if err := root.Execute(); err != nil {
os.Exit(1)
}
}
|
/*
Copyright 2020 The Tilt Dev Authors
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 v1alpha1
import (
"context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/tilt-dev/tilt-apiserver/pkg/server/builder/resource"
"github.com/tilt-dev/tilt-apiserver/pkg/server/builder/resource/resourcerest"
"github.com/tilt-dev/tilt-apiserver/pkg/server/builder/resource/resourcestrategy"
)
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ConfigMap stores unstructured data that other controllers can read and write.
//
// Useful for sharing data from one system and subscribing to it from another.
//
// +k8s:openapi-gen=true
// +tilt:starlark-gen=true
type ConfigMap struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Data contains the configuration data.
// Each key must consist of alphanumeric characters, '-', '_' or '.'.
// +optional
Data map[string]string `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"`
}
// ConfigMapList
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type ConfigMapList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
Items []ConfigMap `json:"items" protobuf:"bytes,2,rep,name=items"`
}
var _ resource.Object = &ConfigMap{}
var _ resourcerest.SingularNameProvider = &ConfigMap{}
var _ resourcestrategy.Validater = &ConfigMap{}
var _ resourcerest.ShortNamesProvider = &ConfigMap{}
func (in *ConfigMap) GetSingularName() string {
return "configmap"
}
func (in *ConfigMap) GetObjectMeta() *metav1.ObjectMeta {
return &in.ObjectMeta
}
func (in *ConfigMap) NamespaceScoped() bool {
return false
}
func (in *ConfigMap) GetSpec() interface{} {
return nil
}
func (in *ConfigMap) ShortNames() []string {
return []string{"cm"}
}
func (in *ConfigMap) New() runtime.Object {
return &ConfigMap{}
}
func (in *ConfigMap) NewList() runtime.Object {
return &ConfigMapList{}
}
func (in *ConfigMap) GetGroupVersionResource() schema.GroupVersionResource {
return schema.GroupVersionResource{
Group: "tilt.dev",
Version: "v1alpha1",
Resource: "configmaps",
}
}
func (in *ConfigMap) IsStorageVersion() bool {
return true
}
func (in *ConfigMap) Validate(ctx context.Context) field.ErrorList {
// TODO(user): Modify it, adding your API validation here.
return nil
}
var _ resource.ObjectList = &ConfigMapList{}
func (in *ConfigMapList) GetListMeta() *metav1.ListMeta {
return &in.ListMeta
}
|
package main
import (
"database/sql"
"log"
"os"
"github.com/FrankYang0529/geekbang-golang-training-week2/storage"
)
func main() {
// init db
mysqlURL := os.Getenv("mysql")
db, err := sql.Open("mysql", mysqlURL)
if err != nil {
log.Fatalf("main: can't connect mysql, err: %+v", err)
}
defer db.Close()
// init item storage
itemStorage, err := storage.NewItemStorage(db)
if err != nil {
log.Fatalf("main: can't init item storage, err: %+v", err)
}
// get item
item, err := itemStorage.GetItem("testItemID")
if err != nil {
log.Fatalf("main: can't get item, err: %+v", err)
}
log.Printf("item: %+v", item)
}
|
package main
import (
"bufio"
"errors"
"fmt"
"log"
"net"
"os"
"os/exec"
"os/signal"
"regexp"
"syscall"
"text/template"
"time"
"github.com/appcelerator/amp/pkg/docker"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/spf13/cobra"
"golang.org/x/net/context"
)
const (
defaultTemplate = "/etc/prometheus/prometheus.tpl"
defaultConfiguration = "/etc/prometheus/prometheus.yml"
defaultHost = docker.DefaultURL
defaultPeriod = 1
dockerForMacIP = "192.168.65.1"
dockerEngineMetricsPort = 9323
systemMetricsPort = 9100 // node-exporter
prometheusCmd = "/bin/prometheus"
)
var prometheusArgs = []string{
"-config.file=/etc/prometheus/prometheus.yml",
"-storage.local.path=/prometheus",
"-web.console.libraries=/usr/share/prometheus/console_libraries",
"-web.console.templates=/usr/share/prometheus/consoles",
"-alertmanager.url=http://alertmanager:9093",
}
type Inventory struct {
Hostnames []string
DockerEngineMetricsPort int
SystemMetricsPort int
}
func update(pid int, client *docker.Docker, configurationTemplate string, configuration string) error {
var configurationFile *os.File
var hostnames []string
// connect to the engine API
if err := client.Connect(); err != nil {
return err
}
filter := filters.NewArgs()
filter.Add("name", "ingress")
networkResources, err := client.GetClient().NetworkList(context.Background(), types.NetworkListOptions{Filters: filter})
if err != nil {
return err
}
if len(networkResources) != 1 {
return errors.New("ingress network lookup failed")
}
networkId := networkResources[0].ID
// when the vendors are updated to docker 17.06:
//networkResource, err := client.GetClient().NetworkInspect(context.Background(), networkId, types.NetworkInspectOptions{})
networkResource, err := client.GetClient().NetworkInspect(context.Background(), networkId, false)
for _, peer := range networkResource.Peers {
if peer.Name == "moby" && peer.IP == "127.0.0.1" {
// DockerForMac
hostnames = append(hostnames, dockerForMacIP)
} else if peer.IP == "127.0.0.1" || peer.IP == "0.0.0.0" {
// non addressable, let's hope the hostname is a better option
hostnames = append(hostnames, peer.Name)
} else {
if _, err = net.LookupHost(peer.Name); err != nil {
// can't resolve host, will use IP
hostnames = append(hostnames, peer.IP)
} else {
hostnames = append(hostnames, peer.Name)
}
}
}
if len(hostnames) == 0 {
return errors.New("host list is empty")
}
inventory := &Inventory{Hostnames: hostnames, DockerEngineMetricsPort: dockerEngineMetricsPort, SystemMetricsPort: systemMetricsPort}
// prepare the configuration
t := template.Must(template.New("prometheus.tpl").ParseFiles(configurationTemplate))
configurationFile, err = os.Create(configuration)
if err != nil {
return err
}
err = t.Execute(configurationFile, inventory)
if err != nil {
return err
}
configurationFile.Close()
// reload prometheus
cmd := exec.Command("/usr/bin/killall", "-HUP", "prometheus")
err = cmd.Run()
if err != nil {
log.Println("Prometheus reload failed, error message follows")
return err
}
return nil
}
func main() {
var client *docker.Docker
var configuration string
var configurationTemplate string
var host string
var period int32
var prometheusPID int
var RootCmd = &cobra.Command{
Use: "promctl",
Short: "Prometheus controller",
Long: `Keep the Prometheus configuration up to date with swarm discovery`,
RunE: func(cmd *cobra.Command, args []string) error {
// Docker client init
hasAScheme, err := regexp.MatchString(".*://.*", host)
if err != nil {
return err
}
if !hasAScheme {
host = "tcp://" + host
}
hasAPort, err := regexp.MatchString(".*(:[0-9]+|sock)", host)
if err != nil {
return err
}
if !hasAPort {
host = host + ":2375"
}
client = docker.NewClient(host, docker.DefaultVersion)
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
tick := time.Tick(time.Duration(period) * time.Minute)
time.Sleep(5 * time.Second)
if err := update(prometheusPID, client, configurationTemplate, configuration); err != nil {
return err
}
loop:
for {
select {
case <-tick:
update(prometheusPID, client, configurationTemplate, configuration)
case sig := <-stop:
log.Printf("%v signal trapped\n", sig)
break loop
}
}
log.Println("Stopping Prometheus")
stopCmd := exec.Command("/usr/bin/killall", "prometheus")
if err := stopCmd.Run(); err != nil {
log.Println("unable to stop Prometheus, error message follows")
return err
}
return nil
},
}
RootCmd.PersistentFlags().StringVarP(&configuration, "config", "c", defaultConfiguration, "config file")
RootCmd.PersistentFlags().StringVarP(&configurationTemplate, "template", "t", defaultTemplate, "template file")
RootCmd.PersistentFlags().StringVar(&host, "host", defaultHost, "host")
RootCmd.PersistentFlags().Int32VarP(&period, "period", "p", defaultPeriod, "reload period in minute")
// start Prometheus
proc := exec.Command(prometheusCmd, prometheusArgs...)
stdout, err := proc.StdoutPipe()
if err != nil {
log.Fatalln(err)
}
stderr, err := proc.StderrPipe()
if err != nil {
log.Fatalln(err)
}
outscanner := bufio.NewScanner(stdout)
errscanner := bufio.NewScanner(stderr)
go func() {
for outscanner.Scan() {
fmt.Println(outscanner.Text())
}
}()
go func() {
for errscanner.Scan() {
fmt.Println(errscanner.Text())
}
}()
go func() {
err := proc.Start()
if err != nil {
log.Fatalln(err)
}
}()
if err := RootCmd.Execute(); err != nil {
log.Fatalln(err)
}
}
|
package templates
var CustomInfrastructure = `
terraform {
required_version = ">= 0.8.7"
}
provider "aws" {
access_key = "${var.AWS_ACCESS_KEY_ID}"
secret_key = "${var.AWS_SECRET_ACCESS_KEY}"
region = "${var.AWS_DEFAULT_REGION}"
}
data "aws_availability_zones" "available" {}
/*
* Calling modules who create the initial AWS VPC / AWS ELB
* and AWS IAM Roles for Kubernetes Deployment
*/
module "aws-vpc" {
source = "modules/vpc"
aws_cluster_name = "${var.aws_cluster_name}"
aws_vpc_cidr_block = "${var.aws_vpc_cidr_block}"
aws_avail_zones="${slice(data.aws_availability_zones.available.names,0,2)}"
aws_cidr_subnets_private="${var.aws_cidr_subnets_private}"
aws_cidr_subnets_public="${var.aws_cidr_subnets_public}"
default_tags="${var.default_tags}"
}
module "aws-elb" {
source = "modules/elb"
aws_cluster_name="${var.aws_cluster_name}"
aws_vpc_id="${module.aws-vpc.aws_vpc_id}"
aws_avail_zones="${slice(data.aws_availability_zones.available.names,0,2)}"
aws_subnet_ids_public="${module.aws-vpc.aws_subnet_ids_public}"
aws_elb_api_port = "${var.aws_elb_api_port}"
k8s_secure_api_port = "${var.k8s_secure_api_port}"
default_tags="${var.default_tags}"
}
module "aws-iam" {
source = "modules/iam"
aws_cluster_name="${var.aws_cluster_name}"
}
/*
* Create Bastion Instances in AWS
*
*/
resource "aws_instance" "bastion-server" {
ami = "{{.AmiOwner}}"
instance_type = "${var.aws_bastion_size}"
count = "${length(var.aws_cidr_subnets_public)}"
associate_public_ip_address = true
availability_zone = "${element(slice(data.aws_availability_zones.available.names,0,2),count.index)}"
subnet_id = "${element(module.aws-vpc.aws_subnet_ids_public,count.index)}"
vpc_security_group_ids = [ "${module.aws-vpc.aws_security_group}" ]
key_name = "${var.AWS_SSH_KEY_NAME}"
tags = "${merge(var.default_tags, map(
"Name", "kubernetes-${var.aws_cluster_name}-bastion-${count.index}",
"Cluster", "${var.aws_cluster_name}",
"Role", "bastion-${var.aws_cluster_name}-${count.index}"
))}"
}
/*
* Create K8s Master and worker nodes and etcd instances
*
*/
resource "aws_instance" "k8s-master" {
ami = "{{.Ami}}"
instance_type = "${var.aws_kube_master_size}"
count = "${var.aws_kube_master_num}"
availability_zone = "${element(slice(data.aws_availability_zones.available.names,0,2),count.index)}"
subnet_id = "${element(module.aws-vpc.aws_subnet_ids_private,count.index)}"
vpc_security_group_ids = [ "${module.aws-vpc.aws_security_group}" ]
iam_instance_profile = "${module.aws-iam.kube-master-profile}"
key_name = "${var.AWS_SSH_KEY_NAME}"
tags = "${merge(var.default_tags, map(
"Name", "kubernetes-${var.aws_cluster_name}-master${count.index}",
"kubernetes.io/cluster/${var.aws_cluster_name}", "member",
"Role", "master"
))}"
}
resource "aws_elb_attachment" "attach_master_nodes" {
count = "${var.aws_kube_master_num}"
elb = "${module.aws-elb.aws_elb_api_id}"
instance = "${element(aws_instance.k8s-master.*.id,count.index)}"
}
resource "aws_instance" "k8s-etcd" {
ami = "{{.Ami}}"
instance_type = "${var.aws_etcd_size}"
count = "${var.aws_etcd_num}"
availability_zone = "${element(slice(data.aws_availability_zones.available.names,0,2),count.index)}"
subnet_id = "${element(module.aws-vpc.aws_subnet_ids_private,count.index)}"
vpc_security_group_ids = [ "${module.aws-vpc.aws_security_group}" ]
key_name = "${var.AWS_SSH_KEY_NAME}"
tags = "${merge(var.default_tags, map(
"Name", "kubernetes-${var.aws_cluster_name}-etcd${count.index}",
"kubernetes.io/cluster/${var.aws_cluster_name}", "member",
"Role", "etcd"
))}"
}
resource "aws_instance" "k8s-worker" {
ami = "{{.Ami}}"
instance_type = "${var.aws_kube_worker_size}"
count = "${var.aws_kube_worker_num}"
availability_zone = "${element(slice(data.aws_availability_zones.available.names,0,2),count.index)}"
subnet_id = "${element(module.aws-vpc.aws_subnet_ids_private,count.index)}"
vpc_security_group_ids = [ "${module.aws-vpc.aws_security_group}" ]
iam_instance_profile = "${module.aws-iam.kube-worker-profile}"
key_name = "${var.AWS_SSH_KEY_NAME}"
tags = "${merge(var.default_tags, map(
"Name", "kubernetes-${var.aws_cluster_name}-worker${count.index}",
"kubernetes.io/cluster/${var.aws_cluster_name}", "member",
"Role", "worker"
))}"
}
/*
* Create Kubespray Inventory File
*
*/
data "template_file" "inventory" {
template = "${file("${path.module}/templates/inventory.tpl")}"
vars {
public_ip_address_bastion = "${join("\n",formatlist("bastion ansible_host=%s" , aws_instance.bastion-server.*.public_ip))}"
connection_strings_master = "${join("\n",formatlist("%s ansible_host=%s",aws_instance.k8s-master.*.tags.Name, aws_instance.k8s-master.*.private_ip))}"
connection_strings_node = "${join("\n", formatlist("%s ansible_host=%s", aws_instance.k8s-worker.*.tags.Name, aws_instance.k8s-worker.*.private_ip))}"
connection_strings_etcd = "${join("\n",formatlist("%s ansible_host=%s", aws_instance.k8s-etcd.*.tags.Name, aws_instance.k8s-etcd.*.private_ip))}"
list_master = "${join("\n",aws_instance.k8s-master.*.tags.Name)}"
list_node = "${join("\n",aws_instance.k8s-worker.*.tags.Name)}"
list_etcd = "${join("\n",aws_instance.k8s-etcd.*.tags.Name)}"
elb_api_fqdn = "apiserver_loadbalancer_domain_name=\"${module.aws-elb.aws_elb_api_fqdn}\""
}
}
resource "null_resource" "inventories" {
provisioner "local-exec" {
command = "echo '${data.template_file.inventory.rendered}' > ../../../inventory/hosts"
}
triggers {
template = "${data.template_file.inventory.rendered}"
}
}
`
|
package pattern
import (
"fmt"
"github.com/layer5io/meshery/mesheryctl/pkg/utils"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var (
availableSubcommands []*cobra.Command
file string
tokenPath string
)
// PatternCmd represents the root command for pattern commands
var PatternCmd = &cobra.Command{
Use: "pattern",
Short: "Service Mesh Patterns Management",
Long: `Manage service meshes using predefined patterns`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if ok := utils.IsValidSubcommand(availableSubcommands, args[0]); !ok {
return errors.New(utils.SystemError(fmt.Sprintf("invalid command: \"%s\"", args[0])))
}
return nil
},
}
func init() {
PatternCmd.PersistentFlags().StringVarP(&tokenPath, "token", "t", "", "Path to token file default from current context")
availableSubcommands = []*cobra.Command{applyCmd, deleteCmd, viewCmd, listCmd}
PatternCmd.AddCommand(availableSubcommands...)
}
|
package User
import (
"encoding/json"
"io/ioutil"
"log"
"os"
)
type User struct {
Username string
Password string
Email string
SponsorMeeting []string
ParticipantMeeting []string
}
//register an user with name, password, email
func RegisterAnUser(user *User) {
AllUserInfo := GetAllUserInfo()
flog, err := os.OpenFile("data/input_output.log", os.O_APPEND|os.O_WRONLY, 0600)
defer flog.Close()
check(err)
logger := log.New(flog, "", log.LstdFlags)
logger.Printf("agenda register -u %s -p %s -e %s", user.Username, user.Password, user.Email)
if _, ok := AllUserInfo[user.Username]; !ok {
AllUserInfo[user.Username] = *user
os.Stdout.WriteString("register succeed!\n")
logger.Print("register succeed!\n")
} else {
os.Stdout.WriteString("The userName have been registered\n")
logger.Print("The userName have been registered\n")
}
}
//Get all user infomation
func GetAllUserInfo() map[string]User {
byteIn, err := ioutil.ReadFile("data/User.json")
check(err)
var allUserInfo map[string]User
json.Unmarshal(byteIn, &allUserInfo)
return allUserInfo
}
func check(r error) {
if r != nil {
log.Fatal(r)
}
}
func LogIn(user *User){
AllUserInformation := GetAllUserInfo()
flog, err := os.OpenFile("data/input_output.log", os.O_APPEND|os.O_WRONLY, 0600)
defer flog.Close()
if(err != nil){
log.Fatal(err)
}
logger := log.New(flog, "", log.LstdFlags)
logger.Printf("agenda login -u %s -p %s", user.Username, user.Password)
//get current username
fin, err1 := os.Open("data/current.txt")
if(err1 != nil){
log.Fatal(err1)
}
defer fin.Close()
reader := bufio.NewReader(fin)
name, _ := reader.ReadString('\n')
if name != "" {
os.Stdout.WriteString("You have log in already.\n")
logger.Print("You have log in already.\n")
return
}
_, ok := AllUserInformation[user.Username]
if !ok {
os.Stdout.WriteString("Username is not correct.\n")
logger.Print("Username is not correct.\n")
} else {
correctPassword := AllUserInformation[user.Username].Password
if correctPassword == user.Password {
fout, _ := os.Create("data/current.txt")
defer fout.Close()
fout.WriteString(user.Username)
os.Stdout.WriteString("You have logged in successfully.\n")
logger.Print("You have logged in successfully.\n")
} else {
os.Stdout.WriteString("Password is incorrect!\n")
logger.Print("Password is incorrect!\n")
}
}
}
func LogOut() {
flog, err := os.OpenFile("data/input_output.log", os.O_APPEND|os.O_WRONLY, 0600)
defer flog.Close()
if(err != nil){
log.Fatal(err)
}
logger := log.New(flog, "", log.LstdFlags)
logger.Printf("Agenda logout")
fin, err1 := os.Open("data/current.txt")
if(err1 != nil){
log.Fatal(err1)
}
defer fin.Close()
reader := bufio.NewReader(fin)
name, _ := reader.ReadString('\n')
if name == "" {
os.Stdout.WriteString("You have not logged in.\n")
logger.Print("You have not logged in.\n")
} else {
fout, _ := os.Create("data/current.txt")
defer fout.Close()
fout.WriteString("")
os.Stdout.WriteString("You have logged out successfully.\n")
logger.Print("You have logged out successfully.\n")
}
}
|
package presto
import (
"errors"
)
// ErrNoMore no more error
var ErrNoMore = errors.New("no more")
// ErrNoData no data when parse rows data
var ErrNoData = errors.New("no data")
// Error presto error
type Error struct {
line int
column int
msg string
}
func newError(line, column int, msg string) *Error {
return &Error{
line: line,
column: column,
msg: msg,
}
}
func (e *Error) Error() string {
return e.msg
}
|
package plugins
import (
"testing"
)
func TestNewMultiPlugin(t *testing.T) {
if _, ok := NewMultiPlugin().(*MultiPlugin); !ok {
t.Fail()
}
}
func TestMultiPluginConfigure(t *testing.T) {
m := NewMultiPlugin().(*MultiPlugin)
m.Configure("test", nil)
if m.name != "test" {
t.Fail()
}
}
|
package template
import "gorm.io/gorm"
type templateRepository struct {
db *gorm.DB
}
func NewTemplateRepository(db *gorm.DB) TemplateRepository {
return &templateRepository{
db: db,
}
}
|
package node
import (
"context"
"fmt"
"time"
"github.com/zdnscloud/cement/log"
"github.com/zdnscloud/cluster-agent/monitor/event"
"github.com/zdnscloud/gok8s/client"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
metricsapi "k8s.io/metrics/pkg/apis/metrics"
)
type Monitor struct {
cli client.Client
stopCh chan struct{}
eventCh chan interface{}
}
type Node struct {
Name string
Cpu int64
CpuUsed int64
Memory int64
MemoryUsed int64
Pod int64
PodUsed int64
}
func New(cli client.Client, ch chan interface{}) *Monitor {
return &Monitor{
cli: cli,
stopCh: make(chan struct{}),
eventCh: ch,
}
}
func (m *Monitor) Stop() {
log.Infof("stop node monitor")
m.stopCh <- struct{}{}
<-m.stopCh
}
func (m *Monitor) Start(cfg *event.MonitorConfig) {
log.Infof("start node monitor")
for {
select {
case <-m.stopCh:
m.stopCh <- struct{}{}
return
default:
}
m.check(GetNodes(m.cli), cfg)
time.Sleep(time.Duration(event.CheckInterval) * time.Second)
}
}
func (m *Monitor) check(nodes []*Node, cfg *event.MonitorConfig) {
for _, node := range nodes {
if node.Cpu > 0 && cfg.Cpu > 0 {
if ratio := (node.CpuUsed * event.Denominator) / node.Cpu; ratio > (cfg.Cpu) {
m.eventCh <- event.Event{
Kind: event.NodeKind,
Name: node.Name,
Message: fmt.Sprintf("High cpu utilization %d%%", ratio),
}
log.Infof("The CPU utilization of node %s is %d%%, higher than the threshold set by the user %d%%", node.Name, ratio, cfg.Cpu)
}
}
if node.Memory > 0 && cfg.Memory > 0 {
if ratio := (node.MemoryUsed * event.Denominator) / node.Memory; ratio > (cfg.Memory) {
m.eventCh <- event.Event{
Kind: event.NodeKind,
Name: node.Name,
Message: fmt.Sprintf("High memory utilization %d%%", ratio),
}
log.Infof("The memory utilization of node %s is %d%%, higher than the threshold set by the user %d%%", node.Name, ratio, cfg.Memory)
}
}
}
}
func GetNodes(cli client.Client) []*Node {
var nodes []*Node
k8sNodes := corev1.NodeList{}
if err := cli.List(context.TODO(), nil, &k8sNodes); err != nil {
log.Warnf("Get nodes failed:%s", err.Error())
return nodes
}
podCountOnNode := getPodCountOnNode(cli, "")
nodeMetrics := getNodeMetrics(cli, "")
for _, k8sNode := range k8sNodes.Items {
nodes = append(nodes, k8sNodeToNode(&k8sNode, nodeMetrics, podCountOnNode))
}
return nodes
}
func getPodCountOnNode(cli client.Client, name string) map[string]int {
podCountOnNode := make(map[string]int)
pods := corev1.PodList{}
err := cli.List(context.TODO(), nil, &pods)
if err == nil {
for _, p := range pods.Items {
if p.Status.Phase != corev1.PodRunning {
continue
}
n := p.Spec.NodeName
if name != "" && n != name {
continue
}
podCountOnNode[n] += 1
}
} else {
log.Warnf("Get pods failed:%s", err.Error())
}
return podCountOnNode
}
func getNodeMetrics(cli client.Client, name string) map[string]metricsapi.NodeMetrics {
nodeMetricsByName := make(map[string]metricsapi.NodeMetrics)
nodeMetricsList, err := cli.GetNodeMetrics(name, labels.Everything())
if err == nil {
for _, metrics := range nodeMetricsList.Items {
nodeMetricsByName[metrics.Name] = metrics
}
} else {
log.Warnf("Get node meterics failed:%s", err.Error())
}
return nodeMetricsByName
}
func k8sNodeToNode(k8sNode *corev1.Node, nodeMetrics map[string]metricsapi.NodeMetrics, podCountOnNode map[string]int) *Node {
status := &k8sNode.Status
cpuAva := status.Allocatable.Cpu().MilliValue()
memoryAva := status.Allocatable.Memory().Value()
podAva := status.Allocatable.Pods().Value()
usageMetrics := nodeMetrics[k8sNode.Name]
cpuUsed := usageMetrics.Usage.Cpu().MilliValue()
memoryUsed := usageMetrics.Usage.Memory().Value()
podUsed := int64(podCountOnNode[k8sNode.Name])
return &Node{
Name: k8sNode.Name,
Cpu: cpuAva,
CpuUsed: cpuUsed,
Memory: memoryAva,
MemoryUsed: memoryUsed,
Pod: podAva,
PodUsed: podUsed,
}
}
|
package app
import (
"conflict-template/internal/app/hello"
"conflict-template/internal/service/log"
)
func Init() {
hello.Init()
log.Info("appService init successfully")
}
|
// Copyright 2020 SEQSENSE, 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 tunnel
import (
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"time"
"golang.org/x/net/websocket"
"github.com/seqsense/aws-iot-device-sdk-go/v6/internal/ioterr"
)
const (
defaultEndpointHostFormat = "data.tunneling.iot.%s.amazonaws.com"
defaultPingPeriod = 5 * time.Second
websocketProtocol = "aws.iot.securetunneling-1.0"
userAgent = "aws-iot-device-sdk-go/tunnel"
)
// ErrUnsupportedScheme indicate that the requested protocol scheme is not supported.
var ErrUnsupportedScheme = errors.New("unsupported scheme")
func endpointHost(region string) string {
return fmt.Sprintf(defaultEndpointHostFormat, region)
}
// Dialer is a proxy destination dialer.
type Dialer func() (io.ReadWriteCloser, error)
// ProxyDestination proxies TCP connection from remote source device to
// the local destination application via IoT secure tunneling.
// This is usually used on IoT things.
func ProxyDestination(dialer Dialer, endpoint, token string, opts ...ProxyOption) error {
ws, opt, err := openProxyConn(endpoint, "destination", token, opts...)
if err != nil {
return ioterr.New(err, "opening proxy destination")
}
pingCancel := newPinger(ws, opt.PingPeriod)
defer pingCancel()
return proxyDestination(ws, dialer, opt.ErrorHandler, opt.Stat)
}
// ProxySource proxies TCP connection from local socket to
// remote destination application via IoT secure tunneling.
// This is usually used on a computer or bastion server.
func ProxySource(listener net.Listener, endpoint, token string, opts ...ProxyOption) error {
ws, opt, err := openProxyConn(endpoint, "source", token, opts...)
if err != nil {
return ioterr.New(err, "opening proxy source")
}
pingCancel := newPinger(ws, opt.PingPeriod)
defer pingCancel()
return proxySource(ws, listener, opt.ErrorHandler, opt.Stat)
}
func openProxyConn(endpoint, mode, token string, opts ...ProxyOption) (*websocket.Conn, *ProxyOptions, error) {
opt := &ProxyOptions{
Scheme: "wss",
PingPeriod: defaultPingPeriod,
}
for _, o := range opts {
if err := o(opt); err != nil {
return nil, nil, ioterr.New(err, "applying options")
}
}
if err := opt.validate(); err != nil {
return nil, nil, err
}
wsc, err := websocket.NewConfig(
fmt.Sprintf("%s://%s/tunnel?local-proxy-mode=%s", opt.Scheme, endpoint, mode),
fmt.Sprintf("https://%s", endpoint),
)
if err != nil {
return nil, nil, ioterr.New(err, "creating ws config")
}
if opt.Scheme == "wss" {
wsc.TlsConfig = &tls.Config{
// Remove protocol default port number from the URI to avoid TLS certificate validation error.
ServerName: serverNameFromEndpoint(opt.Scheme, endpoint),
InsecureSkipVerify: opt.InsecureSkipVerify,
}
}
wsc.Header = http.Header{
"Access-Token": []string{token},
"User-Agent": []string{userAgent},
}
wsc.Protocol = append(wsc.Protocol, websocketProtocol)
ws, err := websocket.DialConfig(wsc)
if err != nil {
return nil, nil, ioterr.New(err, "creating ws dial config")
}
ws.PayloadType = websocket.BinaryFrame
return ws, opt, nil
}
// ErrorHandler is an interface to handler error.
type ErrorHandler interface {
HandleError(error)
}
// ErrorHandlerFunc type is an adapter to use handler function as ErrorHandler.
type ErrorHandlerFunc func(error)
// HandleError implements ErrorHandler interface.
func (f ErrorHandlerFunc) HandleError(err error) {
f(err)
}
// ProxyOption is a type of functional options.
type ProxyOption func(*ProxyOptions) error
// ProxyOptions stores options of the proxy.
type ProxyOptions struct {
InsecureSkipVerify bool
Scheme string
ErrorHandler ErrorHandler
PingPeriod time.Duration
Stat Stat
}
func (o *ProxyOptions) validate() error {
switch o.Scheme {
case "wss", "ws":
default:
return ioterr.New(ErrUnsupportedScheme, o.Scheme)
}
return nil
}
// WithErrorHandler sets a ErrorHandler.
func WithErrorHandler(h ErrorHandler) ProxyOption {
return func(opt *ProxyOptions) error {
opt.ErrorHandler = h
return nil
}
}
// WithPingPeriod sets ping send period.
func WithPingPeriod(d time.Duration) ProxyOption {
return func(opt *ProxyOptions) error {
opt.PingPeriod = d
return nil
}
}
// WithStat enables statistics.
func WithStat(stat Stat) ProxyOption {
return func(opt *ProxyOptions) error {
opt.Stat = stat
return nil
}
}
|
package pkg2
//
type SA struct {
num int
}
func (sa *SA) Get() int {
return sa.num
}
func (sa *SA) Set(n int) {
sa.num = n
}
type ISA interface {
Get() int
Set(int)
}
|
// Copyright (C) 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package remotessh
import (
"encoding/json"
"io"
"os/user"
)
// Configuration represents a configuration for connecting
// to an SSH remote client.
// The SSH agent is first used to attempt connection,
// followed by the given Keyfile
type Configuration struct {
// The name to use for this connection
Name string
// The hostname to connect to
Host string `json:"host"`
// User is the username to use for login
User string `json:"user"`
// Which port should be used
Port uint16 `json:"port,string"`
// The pem encoded public key file to use for the connection.
// If not specified uses ~/.ssh/id_rsa
Keyfile string `json:"keyPath"`
// The known_hosts file to use for authentication. Defaults to
// ~/.ssh/known_hosts
KnownHosts string `json:"knownHostsPath"`
// Environment variables to set on the connection
Env []string
}
// ReadConfigurations reads a set of configurations from then
// given reader, and returns the configurations to the user.
func ReadConfigurations(r io.Reader) ([]Configuration, error) {
u, err := user.Current()
if err != nil {
return nil, err
}
cfgs := []Configuration{}
d := json.NewDecoder(r)
if _, err := d.Token(); err != nil {
return nil, err
}
for d.More() {
cfg := Configuration{
Name: "",
Host: "",
User: u.Username,
Port: 22,
Keyfile: u.HomeDir + "/.ssh/id_rsa",
KnownHosts: u.HomeDir + "/.ssh/known_hosts",
}
if err := d.Decode(&cfg); err != nil {
return nil, err
}
cfgs = append(cfgs, cfg)
}
if _, err := d.Token(); err != nil {
return nil, err
}
return cfgs, nil
}
|
package application
import (
"fmt"
"net/http"
"github.com/Sirikon/Unfollowers2/domain"
goTwitter "github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"github.com/dghubble/oauth1/twitter"
)
// UnfollowersApplication .
type UnfollowersApplication struct {
Config domain.Config
WebServer domain.IWebServer
}
func (app *UnfollowersApplication) buildCallbackURL() string {
return fmt.Sprintf("http://%s:%s%s", app.Config.Web.Host, app.Config.Web.Port, app.Config.Twitter.CallbackPath)
}
func (app *UnfollowersApplication) buildOAuthConfig() oauth1.Config {
return oauth1.Config{
ConsumerKey: app.Config.Twitter.ConsumerKey,
ConsumerSecret: app.Config.Twitter.ConsumerSecret,
CallbackURL: app.buildCallbackURL(),
Endpoint: twitter.AuthorizeEndpoint,
}
}
// Run .
func (app *UnfollowersApplication) Run() {
app.WebServer.Init()
app.WebServer.Get("/login", func(c domain.IWebServerRequestContext) {
oAuthConfig := app.buildOAuthConfig()
requestToken, _, _ := oAuthConfig.RequestToken()
authorizationURL, _ := oAuthConfig.AuthorizationURL(requestToken)
c.Redirect(http.StatusTemporaryRedirect, authorizationURL.String())
})
app.WebServer.Get(app.Config.Twitter.CallbackPath, func(c domain.IWebServerRequestContext) {
requestToken, verifier, _ := oauth1.ParseAuthorizationCallback(c.GetRequest())
oAuthConfig := app.buildOAuthConfig()
_, requestSecret, _ := oAuthConfig.RequestToken()
accessToken, accessSecret, err := oAuthConfig.AccessToken(requestToken, requestSecret, verifier)
if err != nil {
c.ReplyString(http.StatusOK, err.Error())
return
}
// handle error
token := oauth1.NewToken(accessToken, accessSecret)
httpClient := oAuthConfig.Client(oauth1.NoContext, token)
// Twitter client
client := goTwitter.NewClient(httpClient)
// Home Timeline
tweets, _, _ := client.Timelines.HomeTimeline(&goTwitter.HomeTimelineParams{
Count: 20,
})
c.ReplyJSON(http.StatusOK, tweets)
})
app.WebServer.Listen()
}
|
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// SimilarityLMJelinekMercer similarity that uses the LM Jelinek Mercer. The algorithm attempts to
// capture important patterns in the text, while leaving out noise.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/index-modules-similarity.html#lm_jelinek_mercer
// for details.
type SimilarityLMJelinekMercer struct {
Similarity
name string
// fields specific to lm jelinek mercer similarity
lambda *float32
}
// NewSimilarityLMJelinekMercer initializes a new SimilarityLMJelinekMercer.
func NewSimilarityLMJelinekMercer(name string) *SimilarityLMJelinekMercer {
return &SimilarityLMJelinekMercer{
name: name,
}
}
// Name returns field key for the Similarity.
func (s *SimilarityLMJelinekMercer) Name() string {
return s.name
}
// Lambda sets the optimal value depends on both the collection and query. The optimal value is
// around 0.1 for title queries and 0.7 for long queries. When value approaches 0, documents that
// match more query terms will be ranked higher than those that match fewer terms.
// Defaults to 0.1.
func (s *SimilarityLMJelinekMercer) Lambda(lambda float32) *SimilarityLMJelinekMercer {
s.lambda = &lambda
return s
}
// Validate validates SimilarityLMJelinekMercer.
func (s *SimilarityLMJelinekMercer) Validate(includeName bool) error {
var invalid []string
if includeName && s.name == "" {
invalid = append(invalid, "Name")
}
if len(invalid) > 0 {
return fmt.Errorf("missing required fields: %v", invalid)
}
return nil
}
// Source returns the serializable JSON for the source builder.
func (s *SimilarityLMJelinekMercer) Source(includeName bool) (interface{}, error) {
// {
// "test": {
// "type": "LMJelinekMercer",
// "lambda": 0.1
// }
// }
options := make(map[string]interface{})
options["type"] = "LMJelinekMercer"
if s.lambda != nil {
options["lambda"] = s.lambda
}
if !includeName {
return options, nil
}
source := make(map[string]interface{})
source[s.name] = options
return source, nil
}
|
package distinct
import "testing"
func TestDistinct(t *testing.T) {
entries := []struct {
input []int
result int
}{
{[]int{1, 3, 5, 6, 1, 2, 3, 2, 4, 5, 5, 1}, 6},
}
for _, entry := range entries {
result := Distinct(entry.input)
// check if result and expected result are same
if entry.result != result {
t.Errorf("Distinct for %d failed, expected result %d, got, %d", entry.input, entry.result, result)
}
}
}
|
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wilco
import (
"context"
"chromiumos/tast/errors"
"chromiumos/tast/local/bundles/cros/wilco/pre"
"chromiumos/tast/local/wilco"
"chromiumos/tast/testing"
dtcpb "chromiumos/wilco_dtc"
)
func init() {
testing.AddTest(&testing.Test{
Func: APIGetOsVersion,
Desc: "Test sending GetOsVersion gRPC request from Wilco DTC VM to the Wilco DTC Support Daemon",
Contacts: []string{
"chromeos-oem-services@google.com", // Use team email for tickets.
"bkersting@google.com",
"lamzin@google.com",
},
Attr: []string{"group:mainline"},
SoftwareDeps: []string{"vm_host", "wilco"},
Pre: pre.WilcoDtcSupportdAPI,
})
}
func APIGetOsVersion(ctx context.Context, s *testing.State) {
request := dtcpb.GetOsVersionRequest{}
response := dtcpb.GetOsVersionResponse{}
if err := wilco.DPSLSendMessage(ctx, "GetOsVersion", &request, &response); err != nil {
s.Fatal("Unable to get OS version: ", err)
}
// Error conditions defined by the proto definition.
if len(response.Version) == 0 {
s.Fatal(errors.Errorf("OS Version is blank: %s", response.String()))
}
if response.Milestone == 0 {
s.Fatal(errors.Errorf("OS Milestone is 0: %s", response.String()))
}
}
|
/*
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 v1
import (
"github.com/operator-framework/operator-lib/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// ImageReplicateStatusType is status type of external registry
type ImageReplicateStatusType string
const (
// ImageReplicateSuccess is a status that replicating image is finished successfully
ImageReplicateSuccess ImageReplicateStatusType = "Success"
// ImageReplicateFail is a failed status while copying image
ImageReplicateFail ImageReplicateStatusType = "Fail"
// ImageReplicatePending is an initial status
ImageReplicatePending ImageReplicateStatusType = "Pending"
// ImageReplicateProcessing is status that replicating is started
ImageReplicateProcessing ImageReplicateStatusType = "Processing"
)
// ImageReplicateSpec defines the desired state of ImageReplicate
type ImageReplicateSpec struct {
// Source image information
FromImage ImageInfo `json:"fromImage"`
// Destination image information
ToImage ImageInfo `json:"toImage"`
// The name of the signer to sign the image you moved. This field is available only if destination registry's `RegistryType` is `HpcdRegistry`
Signer string `json:"signer,omitempty"`
}
// ImageInfo consists of registry information and image information.
type ImageInfo struct {
// +kubebuilder:validation:Enum=HpcdRegistry;DockerHub;Docker;HarborV2
// Registry type like HarborV2
RegistryType RegistryType `json:"registryType"`
// metadata name of external registry or hpcd registry
RegistryName string `json:"registryName"`
// metadata namespace of external registry or hpcd registry
RegistryNamespace string `json:"registryNamespace"`
// Image path (example: library/alpine:3)
Image string `json:"image"`
}
// ImageReplicateStatus defines the observed state of ImageReplicate
type ImageReplicateStatus struct {
// Conditions are status of subresources
Conditions status.Conditions `json:"conditions,omitempty"`
// ImageSignRequestName is ImageSignRequest's name if exists
ImageSignRequestName string `json:"imageSignRequestName,omitempty"`
// State is a status of external registry
State ImageReplicateStatusType `json:"state,omitempty"`
// StateChangedAt is the time when state was changed
StateChangedAt metav1.Time `json:"stateChangedAt,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:shortName=imgrepl
// +kubebuilder:printcolumn:name="STATUS",type=string,JSONPath=`.status.state`
// +kubebuilder:printcolumn:name="AGE",type=date,JSONPath=`.metadata.creationTimestamp`
// ImageReplicate is the Schema for the imagereplicates API
type ImageReplicate struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ImageReplicateSpec `json:"spec,omitempty"`
Status ImageReplicateStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// ImageReplicateList contains a list of ImageReplicate
type ImageReplicateList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []ImageReplicate `json:"items"`
}
func init() {
SchemeBuilder.Register(&ImageReplicate{}, &ImageReplicateList{})
}
|
package main
import (
"fmt"
"net/http"
"time"
)
// When we create a program, one 'Go routine' is automatically created (Main Routine), when there is a blocking call (like http request), it will wait
// By default Go use only one CPU core and Go Scheduler runs one thread on each 'logical' core
// Concurency is not Parallelism! Concurency means multiple threads executing code but Parallelism means multiple threads executed at he exact same time and requires multiple CPUs
func main() {
links := []string{
"http://google.com",
"http://amazon.com",
"http://stackoverflow.com",
}
// use Channels to communicate between routines
channel := make(chan string) // create Channel
for _, link := range links {
// create new routine with 'go'
// when Main Routine is completed, all Child Routines will be stopped
go checkLink(link, channel)
}
// infinite loop
for link := range channel {
// Function Literal (Anonymous funcs)
go func(link string) {
time.Sleep(10 * time.Second) // 'time' package; to sleep routine
checkLink(link, channel)
}(link)
}
}
func checkLink(link string, channel chan string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down...")
channel <- link // sending data to channel
return
}
fmt.Println(link, "is up")
channel <- link // sending data to channel
}
|
package main
import (
"fmt"
"github.com/daischio/daischeme/codemodel"
"io/ioutil"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
// Generate a model from a schema
m := codemodel.New("main", "MyModel", "./assets/json_example_schema.json")
// Obtain the mapped model code
code := m.GetCode()
fmt.Println(code)
// Write model to disk
err := ioutil.WriteFile("./model.go", []byte(m.GetCode()), 0644)
check(err)
}
|
package values
var (
Name = "myapp"
Namespace = "csip-dns"
Replicas int32 = 1
Labels = map[string]string{
"app": "myapp",
}
Image = "nginx:latest"
)
|
package config
import (
"gin-proyek/models"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var DB *gorm.DB
func InitDB() {
var err error
DB, err = gorm.Open("postgres", "host=127.0.0.1 port=5432 user=priantikonuradipratama password=admin dbname=gorm sslmode=disable")
if err != nil {
panic("database cannot connect, sorry")
}
DB.AutoMigrate(&models.Article{})
}
|
package v1
import (
"github.com/shiv3/slackube/app/controller/api/v1/slack"
"go.uber.org/zap"
"github.com/brpaz/echozap"
"github.com/labstack/echo/v4"
"github.com/shiv3/slackube/app/controller/api/v1/ping"
)
const (
V1Prefix = "/v1"
)
type Router interface {
Dispatch(e *echo.Echo) error
}
// RouterImpl v1パスに来た際のRouteを記述する。
type RouterImpl struct {
pingEndpoint string
slackEventsEndpoint string
slackActionEndpoint string
slackEventsHandler slack.Handler
pingHandler ping.Handler
}
// NewRouter V1Routerの作成
func NewV1Router(
pingEndpoint string,
slackEventsEndpoint string,
slackActionEndpoint string,
slackHandler slack.Handler,
pingHandler ping.Handler,
) RouterImpl {
return RouterImpl{
pingEndpoint: pingEndpoint,
slackEventsEndpoint: slackEventsEndpoint,
slackActionEndpoint: slackActionEndpoint,
slackEventsHandler: slackHandler,
pingHandler: pingHandler,
}
}
// Dispatch V1RouterへHandlerを登録する。
func (r RouterImpl) Dispatch(e *echo.Echo) error {
group := e.Group(V1Prefix)
group.GET(r.pingEndpoint, r.pingHandler.GetPing)
group.POST(r.slackEventsEndpoint, r.slackEventsHandler.SlackEvents)
group.POST(r.slackActionEndpoint, r.slackEventsHandler.SlackActions)
zapLogger, _ := zap.NewProduction()
e.Use(echozap.ZapLogger(zapLogger))
return nil
}
|
package engine
import (
"time"
)
// Engine Game engine
// Only 1 should be initialised
type Engine struct {
Managers []IManager
running bool
simulationSpeed float64
}
// Initialise the engine, and attached managers
func (engine *Engine) Initialise() {
}
// Run the engine
func (engine *Engine) Run() {
engine.running = true
// Begin the event manager thread in the background
//event.Manager().ProcessQueue()
// Anything that runs concurrently can start now
for _, manager := range engine.Managers {
manager.RunConcurrent()
}
dt := 0.0
startingTime := time.Now().UTC()
for engine.running {
for _, manager := range engine.Managers {
manager.Update(dt)
}
for _, manager := range engine.Managers {
manager.PostUpdate()
}
dt = (float64(time.Now().UTC().Sub(startingTime).Nanoseconds()/1000000) / 1000) * engine.simulationSpeed
startingTime = time.Now().UTC()
}
for _, manager := range engine.Managers {
manager.Unregister()
}
}
// AddManager Adds a new manager to the engine
func (engine *Engine) AddManager(manager IManager) {
engine.Managers = append(engine.Managers, manager)
manager.Register()
}
// Close marks the engine to exit at the end of the current loop
func (engine *Engine) Close() {
engine.running = false
}
// SetSimulationSpeed allows for speeding up and slowing down the game clock
func (engine *Engine) SetSimulationSpeed(multiplier float64) {
if multiplier < 0 {
return
}
engine.simulationSpeed = multiplier
}
// NewEngine returns a new engine instance
func NewEngine() *Engine {
return &Engine{
simulationSpeed: 1.0,
}
}
|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
/*
LetterReplacer replaces the google language letters to translate words to English
*/
var LetterReplacer = strings.NewReplacer(
"a", "y",
"b", "h",
"c", "e",
"d", "s",
"e", "o",
"f", "c",
"g", "v",
"h", "x",
"i", "d",
"j", "u",
"k", "i",
"l", "g",
"m", "l",
"n", "b",
"o", "k",
"p", "r",
"q", "z",
"r", "t",
"s", "n",
"t", "w",
"u", "j",
"v", "p",
"w", "f",
"x", "m",
"y", "a",
"z", "q")
func main() {
input := make([]string, 0)
output := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
numberOfCases, err := strconv.Atoi(scanner.Text())
if err != nil {
panic(err)
}
for i := 0; i < numberOfCases; i++ {
scanner.Scan()
text := scanner.Text()
input = append(input, text)
}
err = scanner.Err()
if err != nil {
panic(err)
}
for i, v := range input {
output = append(output, getSolution(i+1, v))
}
for _, v := range output {
fmt.Println(v)
}
}
func getSolution(caseNumber int, input string) string {
output := "Case #" + strconv.Itoa(caseNumber) + ": "
output += LetterReplacer.Replace(input)
return output
}
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package execbuilder
import (
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
type buildScalarCtx struct {
ivh tree.IndexedVarHelper
// ivarMap is a map from opt.ColumnID to the index of an IndexedVar.
// If a ColumnID is not in the map, it cannot appear in the expression.
ivarMap opt.ColMap
}
type buildFunc func(b *Builder, ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error)
var scalarBuildFuncMap [opt.NumOperators]buildFunc
func init() {
// This code is not inline to avoid an initialization loop error (some of
// the functions depend on scalarBuildFuncMap which in turn depends on the
// functions).
scalarBuildFuncMap = [opt.NumOperators]buildFunc{
opt.VariableOp: (*Builder).buildVariable,
opt.ConstOp: (*Builder).buildTypedExpr,
opt.NullOp: (*Builder).buildNull,
opt.PlaceholderOp: (*Builder).buildTypedExpr,
opt.TupleOp: (*Builder).buildTuple,
opt.FunctionOp: (*Builder).buildFunction,
opt.CaseOp: (*Builder).buildCase,
opt.CastOp: (*Builder).buildCast,
opt.CoalesceOp: (*Builder).buildCoalesce,
opt.ColumnAccessOp: (*Builder).buildColumnAccess,
opt.ArrayOp: (*Builder).buildArray,
opt.AnyOp: (*Builder).buildAny,
opt.AnyScalarOp: (*Builder).buildAnyScalar,
opt.IndirectionOp: (*Builder).buildIndirection,
opt.CollateOp: (*Builder).buildCollate,
opt.ArrayFlattenOp: (*Builder).buildArrayFlatten,
opt.IfErrOp: (*Builder).buildIfErr,
opt.UnsupportedExprOp: (*Builder).buildUnsupportedExpr,
// Item operators.
opt.ProjectionsItemOp: (*Builder).buildItem,
opt.AggregationsItemOp: (*Builder).buildItem,
// Subquery operators.
opt.ExistsOp: (*Builder).buildExistsSubquery,
opt.SubqueryOp: (*Builder).buildSubquery,
}
for _, op := range opt.BoolOperators {
if scalarBuildFuncMap[op] == nil {
scalarBuildFuncMap[op] = (*Builder).buildBoolean
}
}
for _, op := range opt.ComparisonOperators {
scalarBuildFuncMap[op] = (*Builder).buildComparison
}
for _, op := range opt.BinaryOperators {
scalarBuildFuncMap[op] = (*Builder).buildBinary
}
for _, op := range opt.UnaryOperators {
scalarBuildFuncMap[op] = (*Builder).buildUnary
}
}
// buildScalar converts a scalar expression to a TypedExpr. Variables are mapped
// according to ctx.
func (b *Builder) buildScalar(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
fn := scalarBuildFuncMap[scalar.Op()]
if fn == nil {
return nil, errors.AssertionFailedf("unsupported op %s", log.Safe(scalar.Op()))
}
return fn(b, ctx, scalar)
}
func (b *Builder) buildScalarWithMap(
colMap opt.ColMap, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
ctx := buildScalarCtx{
ivh: tree.MakeIndexedVarHelper(nil /* container */, numOutputColsInMap(colMap)),
ivarMap: colMap,
}
return b.buildScalar(&ctx, scalar)
}
func (b *Builder) buildTypedExpr(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
return scalar.Private().(tree.TypedExpr), nil
}
func (b *Builder) buildNull(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
if scalar.DataType().Family() == types.TupleFamily {
// See comment in buildCast.
return tree.DNull, nil
}
return tree.ReType(tree.DNull, scalar.DataType()), nil
}
func (b *Builder) buildVariable(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
return b.indexedVar(ctx, b.mem.Metadata(), *scalar.Private().(*opt.ColumnID)), nil
}
func (b *Builder) indexedVar(
ctx *buildScalarCtx, md *opt.Metadata, colID opt.ColumnID,
) tree.TypedExpr {
idx, ok := ctx.ivarMap.Get(int(colID))
if !ok {
panic(errors.AssertionFailedf("cannot map variable %d to an indexed var", log.Safe(colID)))
}
return ctx.ivh.IndexedVarWithType(idx, md.ColumnMeta(colID).Type)
}
func (b *Builder) buildTuple(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
if memo.CanExtractConstTuple(scalar) {
return memo.ExtractConstDatum(scalar), nil
}
tup := scalar.(*memo.TupleExpr)
typedExprs := make(tree.Exprs, len(tup.Elems))
var err error
for i, elem := range tup.Elems {
typedExprs[i], err = b.buildScalar(ctx, elem)
if err != nil {
return nil, err
}
}
return tree.NewTypedTuple(tup.Typ, typedExprs), nil
}
func (b *Builder) buildBoolean(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
switch scalar.Op() {
case opt.FiltersOp:
if scalar.ChildCount() == 0 {
// This can happen if the expression is not normalized (build tests).
return tree.DBoolTrue, nil
}
fallthrough
case opt.AndOp, opt.OrOp:
expr, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
for i, n := 1, scalar.ChildCount(); i < n; i++ {
right, err := b.buildScalar(ctx, scalar.Child(i).(opt.ScalarExpr))
if err != nil {
return nil, err
}
if scalar.Op() == opt.OrOp {
expr = tree.NewTypedOrExpr(expr, right)
} else {
expr = tree.NewTypedAndExpr(expr, right)
}
}
return expr, nil
case opt.NotOp:
expr, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
return tree.NewTypedNotExpr(expr), nil
case opt.TrueOp:
return tree.DBoolTrue, nil
case opt.FalseOp:
return tree.DBoolFalse, nil
case opt.FiltersItemOp:
return b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
case opt.RangeOp:
return b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
case opt.IsTupleNullOp:
expr, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
return tree.NewTypedIsNullExpr(expr), nil
case opt.IsTupleNotNullOp:
expr, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
return tree.NewTypedIsNotNullExpr(expr), nil
default:
panic(errors.AssertionFailedf("invalid op %s", log.Safe(scalar.Op())))
}
}
func (b *Builder) buildComparison(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
left, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
right, err := b.buildScalar(ctx, scalar.Child(1).(opt.ScalarExpr))
if err != nil {
return nil, err
}
// When the operator is an IsOp, the right is NULL, and the left is not a
// tuple, return the unary tree.IsNullExpr.
if scalar.Op() == opt.IsOp && right == tree.DNull && left.ResolvedType().Family() != types.TupleFamily {
return tree.NewTypedIsNullExpr(left), nil
}
// When the operator is an IsNotOp, the right is NULL, and the left is not a
// tuple, return the unary tree.IsNotNullExpr.
if scalar.Op() == opt.IsNotOp && right == tree.DNull && left.ResolvedType().Family() != types.TupleFamily {
return tree.NewTypedIsNotNullExpr(left), nil
}
operator := opt.ComparisonOpReverseMap[scalar.Op()]
return tree.NewTypedComparisonExpr(operator, left, right), nil
}
func (b *Builder) buildUnary(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
input, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
operator := opt.UnaryOpReverseMap[scalar.Op()]
return tree.NewTypedUnaryExpr(operator, input, scalar.DataType()), nil
}
func (b *Builder) buildBinary(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
left, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
right, err := b.buildScalar(ctx, scalar.Child(1).(opt.ScalarExpr))
if err != nil {
return nil, err
}
operator := opt.BinaryOpReverseMap[scalar.Op()]
return tree.NewTypedBinaryExpr(operator, left, right, scalar.DataType()), nil
}
func (b *Builder) buildFunction(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
fn := scalar.(*memo.FunctionExpr)
exprs := make(tree.TypedExprs, len(fn.Args))
var err error
for i := range exprs {
exprs[i], err = b.buildScalar(ctx, fn.Args[i])
if err != nil {
return nil, err
}
}
funcRef := tree.WrapFunction(fn.Name)
return tree.NewTypedFuncExpr(
funcRef,
0, /* aggQualifier */
exprs,
nil, /* filter */
nil, /* windowDef */
fn.Typ,
fn.Properties,
fn.Overload,
), nil
}
func (b *Builder) buildCase(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
cas := scalar.(*memo.CaseExpr)
input, err := b.buildScalar(ctx, cas.Input)
if err != nil {
return nil, err
}
// A searched CASE statement is represented by the optimizer with input=True.
// The executor expects searched CASE statements to have nil inputs.
if input == tree.DBoolTrue {
input = nil
}
// Extract the list of WHEN ... THEN ... clauses.
whens := make([]*tree.When, len(cas.Whens))
for i, expr := range cas.Whens {
whenExpr := expr.(*memo.WhenExpr)
cond, err := b.buildScalar(ctx, whenExpr.Condition)
if err != nil {
return nil, err
}
val, err := b.buildScalar(ctx, whenExpr.Value)
if err != nil {
return nil, err
}
whens[i] = &tree.When{Cond: cond, Val: val}
}
elseExpr, err := b.buildScalar(ctx, cas.OrElse)
if err != nil {
return nil, err
}
if elseExpr == tree.DNull {
elseExpr = nil
}
return tree.NewTypedCaseExpr(input, whens, elseExpr, cas.Typ)
}
func (b *Builder) buildCast(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
cast := scalar.(*memo.CastExpr)
input, err := b.buildScalar(ctx, cast.Input)
if err != nil {
return nil, err
}
if cast.Typ.Family() == types.TupleFamily {
// TODO(radu): casts to Tuple are not supported (they can't be serialized
// for distsql). This should only happen when the input is always NULL so
// the expression should still be valid without the cast (though there could
// be cornercases where the type does matter).
return input, nil
}
return tree.NewTypedCastExpr(input, cast.Typ), nil
}
func (b *Builder) buildCoalesce(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
coalesce := scalar.(*memo.CoalesceExpr)
exprs := make(tree.TypedExprs, len(coalesce.Args))
var err error
for i := range exprs {
exprs[i], err = b.buildScalar(ctx, coalesce.Args[i])
if err != nil {
return nil, err
}
}
return tree.NewTypedCoalesceExpr(exprs, coalesce.Typ), nil
}
func (b *Builder) buildColumnAccess(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
colAccess := scalar.(*memo.ColumnAccessExpr)
input, err := b.buildScalar(ctx, colAccess.Input)
if err != nil {
return nil, err
}
childTyp := colAccess.Input.DataType()
colIdx := int(colAccess.Idx)
// Find a label if there is one. It's OK if there isn't.
lbl := ""
if childTyp.TupleLabels() != nil {
lbl = childTyp.TupleLabels()[colIdx]
}
return tree.NewTypedColumnAccessExpr(input, tree.Name(lbl), colIdx), nil
}
func (b *Builder) buildArray(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
arr := scalar.(*memo.ArrayExpr)
if memo.CanExtractConstDatum(scalar) {
return memo.ExtractConstDatum(scalar), nil
}
exprs := make(tree.TypedExprs, len(arr.Elems))
var err error
for i := range exprs {
exprs[i], err = b.buildScalar(ctx, arr.Elems[i])
if err != nil {
return nil, err
}
}
return tree.NewTypedArray(exprs, arr.Typ), nil
}
func (b *Builder) buildAnyScalar(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
any := scalar.(*memo.AnyScalarExpr)
left, err := b.buildScalar(ctx, any.Left)
if err != nil {
return nil, err
}
right, err := b.buildScalar(ctx, any.Right)
if err != nil {
return nil, err
}
cmp := opt.ComparisonOpReverseMap[any.Cmp]
return tree.NewTypedComparisonExprWithSubOp(tree.Any, cmp, left, right), nil
}
func (b *Builder) buildIndirection(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
expr, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
index, err := b.buildScalar(ctx, scalar.Child(1).(opt.ScalarExpr))
if err != nil {
return nil, err
}
return tree.NewTypedIndirectionExpr(expr, index, scalar.DataType()), nil
}
func (b *Builder) buildCollate(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
expr, err := b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
return tree.NewTypedCollateExpr(expr, scalar.(*memo.CollateExpr).Locale), nil
}
func (b *Builder) buildArrayFlatten(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
af := scalar.(*memo.ArrayFlattenExpr)
// The subquery here should always be uncorrelated: if it were not, we would
// have converted it to an aggregation.
if !af.Input.Relational().OuterCols.Empty() {
panic(errors.AssertionFailedf("input to ArrayFlatten should be uncorrelated"))
}
root, err := b.buildRelational(af.Input)
if err != nil {
return nil, err
}
typ := b.mem.Metadata().ColumnMeta(af.RequestedCol).Type
e := b.addSubquery(exec.SubqueryAllRows, typ, root.root, af.OriginalExpr)
return tree.NewTypedArrayFlattenExpr(e), nil
}
func (b *Builder) buildIfErr(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
ifErr := scalar.(*memo.IfErrExpr)
cond, err := b.buildScalar(ctx, ifErr.Cond.(opt.ScalarExpr))
if err != nil {
return nil, err
}
var orElse tree.TypedExpr
if ifErr.OrElse.ChildCount() > 0 {
orElse, err = b.buildScalar(ctx, ifErr.OrElse.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
}
var errCode tree.TypedExpr
if ifErr.ErrCode.ChildCount() > 0 {
errCode, err = b.buildScalar(ctx, ifErr.ErrCode.Child(0).(opt.ScalarExpr))
if err != nil {
return nil, err
}
}
return tree.NewTypedIfErrExpr(cond, orElse, errCode), nil
}
func (b *Builder) buildUnsupportedExpr(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
return scalar.(*memo.UnsupportedExprExpr).Value, nil
}
func (b *Builder) buildItem(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
return b.buildScalar(ctx, scalar.Child(0).(opt.ScalarExpr))
}
func (b *Builder) buildAny(ctx *buildScalarCtx, scalar opt.ScalarExpr) (tree.TypedExpr, error) {
any := scalar.(*memo.AnyExpr)
// We cannot execute correlated subqueries.
if !any.Input.Relational().OuterCols.Empty() {
return nil, b.decorrelationError()
}
// Build the execution plan for the input subquery.
plan, err := b.buildRelational(any.Input)
if err != nil {
return nil, err
}
// Construct tuple type of columns in the row.
contents := make([]*types.T, plan.numOutputCols())
plan.outputCols.ForEach(func(key, val int) {
contents[val] = b.mem.Metadata().ColumnMeta(opt.ColumnID(key)).Type
})
typs := types.MakeTuple(contents)
subqueryExpr := b.addSubquery(exec.SubqueryAnyRows, typs, plan.root, any.OriginalExpr)
// Build the scalar value that is compared against each row.
scalarExpr, err := b.buildScalar(ctx, any.Scalar)
if err != nil {
return nil, err
}
cmp := opt.ComparisonOpReverseMap[any.Cmp]
return tree.NewTypedComparisonExprWithSubOp(tree.Any, cmp, scalarExpr, subqueryExpr), nil
}
func (b *Builder) buildExistsSubquery(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
exists := scalar.(*memo.ExistsExpr)
// We cannot execute correlated subqueries.
if !exists.Input.Relational().OuterCols.Empty() {
return nil, b.decorrelationError()
}
// Build the execution plan for the subquery. Note that the subquery could
// have subqueries of its own which are added to b.subqueries.
plan, err := b.buildRelational(exists.Input)
if err != nil {
return nil, err
}
return b.addSubquery(exec.SubqueryExists, types.Bool, plan.root, exists.OriginalExpr), nil
}
func (b *Builder) buildSubquery(
ctx *buildScalarCtx, scalar opt.ScalarExpr,
) (tree.TypedExpr, error) {
subquery := scalar.(*memo.SubqueryExpr)
input := subquery.Input
// TODO(radu): for now we only support the trivial projection.
cols := input.Relational().OutputCols
if cols.Len() != 1 {
return nil, errors.Errorf("subquery input with multiple columns")
}
// We cannot execute correlated subqueries.
if !input.Relational().OuterCols.Empty() {
return nil, b.decorrelationError()
}
// Build the execution plan for the subquery. Note that the subquery could
// have subqueries of its own which are added to b.subqueries.
plan, err := b.buildRelational(input)
if err != nil {
return nil, err
}
return b.addSubquery(exec.SubqueryOneRow, subquery.Typ, plan.root, subquery.OriginalExpr), nil
}
// addSubquery adds an entry to b.subqueries and creates a tree.Subquery
// expression node associated with it.
func (b *Builder) addSubquery(
mode exec.SubqueryMode, typ *types.T, root exec.Node, originalExpr *tree.Subquery,
) *tree.Subquery {
var originalSelect tree.SelectStatement
if originalExpr != nil {
originalSelect = originalExpr.Select
}
exprNode := &tree.Subquery{
Select: originalSelect,
Exists: mode == exec.SubqueryExists,
}
exprNode.SetType(typ)
b.subqueries = append(b.subqueries, exec.Subquery{
ExprNode: exprNode,
Mode: mode,
Root: root,
})
// Associate the tree.Subquery expression node with this subquery
// by index (1-based).
exprNode.Idx = len(b.subqueries)
return exprNode
}
|
// Sia uses Reed-Solomon coding for error correction. This package has no
// method for error detection however, so error detection must be performed
// elsewhere.
//
// We use the repository 'Siacoin/longhair' to handle the erasure coding.
// As far as I'm aware, it's the fastest library that's open source.
// It is a fork of 'catid/longhair', and we inted to merge all changes from
// the original.
//
// Longhair is a c++ library. Here, it is cast to a C library and then called
// using cgo.
package erasure
// #include "erasure.c"
import "C"
import (
"common"
"fmt"
"unsafe"
)
// EncodeRing takes data and produces a set of common.QuorumSize pieces that include redundancy.
// 'k' indiciates the number of non-redundant segments, and 'bytesPerSegment' indicates the size of each segment.
// 'originalData' must be 'k' * 'bytesPerSegment' in size, and should be padded before calling 'EncodeRing'.
//
// The return value is a set of strings common.QuorumSize in length.
// Each string is bytesPerSegment large.
// The first 'k' strings are the original data split up.
// The remaining strings are newly generated redundant data.
func EncodeRing(k int, bytesPerSegment int, originalData []byte) (segmentdData []string, err error) {
// check that 'k' is legal
if k <= 0 || k >= common.QuorumSize {
err = fmt.Errorf("k must be greater than 0 and smaller than %v", common.QuorumSize)
return
}
// check that bytesPerSegment is not too big or small
if bytesPerSegment < common.MinSegmentSize || bytesPerSegment > common.MaxSegmentSize {
err = fmt.Errorf("bytesPerSegment must be greater than %v and smaller than %v", common.MinSegmentSize, common.MaxSegmentSize)
return
}
// check that bytesPerSegment is divisible by 64
if bytesPerSegment%64 != 0 {
err = fmt.Errorf("bytesPerSegment must be divisible by 64")
return
}
// check that originalData is the correct size
if len(originalData) != bytesPerSegment*k {
err = fmt.Errorf("originalData incorrectly padded, must be of size 'bytesPerSegment' * %v - 'm'", common.QuorumSize)
return
}
// call c library to encode data
m := common.QuorumSize - k
redundantChunk := C.encodeRedundancy(C.int(k), C.int(m), C.int(bytesPerSegment), (*C.char)(unsafe.Pointer(&originalData[0])))
redundantString := C.GoStringN(redundantChunk, C.int(m*bytesPerSegment))
segmentdData = make([]string, common.QuorumSize)
// split originalData into segmentdData
for i := 0; i < k; i++ {
segmentdData[i] = string(originalData[i*bytesPerSegment : i*bytesPerSegment+bytesPerSegment])
}
// split redundantString into segmentdData
for i := k; i < common.QuorumSize; i++ {
segmentdData[i] = redundantString[(i-k)*bytesPerSegment : ((i-k)*bytesPerSegment)+bytesPerSegment]
}
// free the memory allocated by the C file
C.free(unsafe.Pointer(redundantChunk))
return
}
// RebuildSector takes a set of 'k' strings, each 'bytesPerSegment' in size, and recovers the original data.
// 'k' must be equal to the number of non-redundant segments when the file was originally built.
// Because recovery is just a bunch of matrix operations, there is no way to tell if the data has been corrupted
// or if an incorrect value of 'k' has been chosen. This error checking must happen before calling RebuildSector.
// The set of 'untaintedSegments' will have corresponding indicies from when they were encoded.
// There is no way to tell what the indicies are, so they must be supplied in the 'segmentIndicies' slice.
// This must be a uint8 because the C library uses a char.
//
// The output is a single byteslice that is equivalent to the data used when initially calling EncodeRing()
func RebuildSector(k int, bytesPerSegment int, untaintedSegments []string, segmentIndicies []uint8) (originalData []byte, err error) {
// check for legal size of k and m
m := common.QuorumSize - k
if k > common.QuorumSize || k < 1 {
err = fmt.Errorf("k must be greater than 0 but smaller than %v", common.QuorumSize)
return
}
// check for legal size of bytesPerSegment
if bytesPerSegment < common.MinSegmentSize || bytesPerSegment > common.MaxSegmentSize {
err = fmt.Errorf("bytesPerSegment must be greater than %v and smaller than %v", common.MinSegmentSize, common.MaxSegmentSize)
return
}
// check that input data is correct number of slices.
if len(untaintedSegments) != k {
err = fmt.Errorf("there must be k elements in untaintedSegments")
return
}
// check that input indicies are correct number of indicies
if len(segmentIndicies) != k {
err = fmt.Errorf("there must be k elements in segmentIndicies")
return
}
// move all data into a single slice for C
originalData = make([]byte, 0, k*bytesPerSegment)
for _, segment := range untaintedSegments {
byteSlice := []byte(segment)
// verify that each string is the correct length
if len(byteSlice) != bytesPerSegment {
err = fmt.Errorf("at least 1 of 'untaintedSegments' is the wrong length")
return
}
originalData = append(originalData, byteSlice...)
}
// call the recovery option
C.recoverData(C.int(k), C.int(m), C.int(bytesPerSegment), (*C.uchar)(unsafe.Pointer(&originalData[0])), (*C.uchar)(unsafe.Pointer(&segmentIndicies[0])))
return
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package policy
import (
"context"
"time"
"chromiumos/tast/common/fixture"
"chromiumos/tast/common/pci"
"chromiumos/tast/common/policy"
"chromiumos/tast/common/policy/fakedms"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/chrome/browser/browserfixt"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/chrome/uiauto/role"
"chromiumos/tast/local/policyutil"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: HistoryClustersVisible,
LacrosStatus: testing.LacrosVariantExists,
Desc: "Behavior of HistoryClustersVisible policy",
Contacts: []string{
"rodmartin@google.com", // Test author
},
SoftwareDeps: []string{"chrome"},
Attr: []string{"group:mainline"},
Params: []testing.Param{{
Fixture: fixture.ChromePolicyLoggedInFeatureJourneys,
Val: browser.TypeAsh,
}, {
Name: "lacros",
ExtraSoftwareDeps: []string{"lacros"},
ExtraAttr: []string{"informational"},
Fixture: fixture.LacrosPolicyLoggedInFeatureJourneys,
Val: browser.TypeLacros,
}},
SearchFlags: []*testing.StringPair{
pci.SearchFlag(&policy.HistoryClustersVisible{}, pci.VerifiedFunctionalityUI),
},
})
}
func HistoryClustersVisible(ctx context.Context, s *testing.State) {
cr := s.FixtValue().(chrome.HasChrome).Chrome()
fdms := s.FixtValue().(fakedms.HasFakeDMS).FakeDMS()
// Reserve ten seconds for cleanup.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
defer cancel()
// Connect to Test API to use it with the UI library.
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to create Test API connection: ", err)
}
for _, param := range []struct {
// name is the subtest name.
name string
// value is the policy value.
value *policy.HistoryClustersVisible
}{
{
name: "true",
value: &policy.HistoryClustersVisible{Val: true},
},
{
name: "false",
value: &policy.HistoryClustersVisible{Val: false},
}, {
name: "unset",
value: &policy.HistoryClustersVisible{Stat: policy.StatusUnset},
},
} {
s.Run(ctx, param.name, func(ctx context.Context, s *testing.State) {
// Perform cleanup.
if err := policyutil.ResetChrome(ctx, fdms, cr); err != nil {
s.Fatal("Failed to clean up: ", err)
}
// Update policies.
if err := policyutil.ServeAndVerify(ctx, fdms, cr, []policy.Policy{param.value}); err != nil {
s.Fatal("Failed to update policies: ", err)
}
// Setup browser based on the chrome type.
br, closeBrowser, err := browserfixt.SetUp(ctx, cr, s.Param().(browser.Type))
if err != nil {
s.Fatal("Failed to open the browser: ", err)
}
defer closeBrowser(cleanupCtx)
defer faillog.DumpUITreeWithScreenshotOnError(ctx, s.OutDir(), s.HasError, cr, "ui_tree_"+param.name)
conn, err := br.NewConn(ctx, "chrome://history/journeys")
if err != nil {
s.Fatal("Failed to connect to chrome: ", err)
}
defer conn.Close()
// Create a uiauto.Context with default timeout.
ui := uiauto.New(tconn)
journeys := nodewith.Name("Journeys").Role(role.Tab)
var isVisible = true
if err := ui.WithTimeout(2 * time.Second).WaitUntilExists(journeys.First())(ctx); err != nil {
if !param.value.Val {
// The Journeys tab shouldn't exist because policy is set to false.
isVisible = false
} else {
// The Journeys tab should exist because policy is set to true or it's unset.
s.Fatal("Failed to find the prompt window for authentication: ", err)
}
}
expectedVisibility := param.value.Stat == policy.StatusUnset || param.value.Val
if isVisible != expectedVisibility {
s.Errorf("Unexpected visibility behavior: got %t; want %t for policy", isVisible, expectedVisibility)
}
})
}
}
|
package main
import (
"encoding/json"
"net/http"
"github.com/google/uuid"
"github.com/nats-io/nats.go"
"github.com/sirupsen/logrus"
)
// publisher
type publisher interface {
Publish(string, []byte) error
}
// Service represent еру service structure.
type Service struct {
publisher publisher
}
// User represents the user structure.
type User struct {
ID uuid.UUID
Name string
}
// newService create new Service instance.
func newService(pub publisher) *Service {
return &Service{publisher: pub}
}
func main() {
logrus.Infoln("user service is starting on port 8080..")
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
logrus.WithError(err).Fatalln("nats connection error")
}
srv := newService(nc)
http.HandleFunc("/users", srv.AddUser)
if err = http.ListenAndServe(":8080", nil); err != nil {
logrus.WithError(err).Fatalln("listenAndServe error")
}
}
// AddUser add new user to db.
func (s Service) AddUser(w http.ResponseWriter, req *http.Request) {
var user User
// FIXME: all errors was ignored for clarity.
// TODO: allow only POST method.
// decode user request body into our structure.
decoder := json.NewDecoder(req.Body)
_ = decoder.Decode(&user)
// TODO: validate user data.
user.ID = uuid.New()
// TODO: save model into db.
data, _ := json.Marshal(user)
// asynchronously notify services that need to know about creating a user.
const eventSubject = "user:created"
_ = s.publisher.Publish(eventSubject, data)
// creating a new entity width 201 http code (REST).
w.WriteHeader(http.StatusCreated)
_, _ = w.Write(data)
}
|
package main
import "fmt"
func sum(numbers ...int) int {
ret := 0
for _, num := range numbers {
ret += num
}
return ret
}
func nameStudents(names ...string) {
for _, name := range names {
fmt.Println(name)
}
}
func main() {
nameStudents("maria", "Carlos", "Jose", "Diego", "Joana", "Bianca", "Brendon")
fmt.Println(sum(1, 2, 5, 7, 2, 5, 2, 9, 28723, -1722, -20000, 845))
}
|
package colorable_wrapper
import (
"fmt"
"github.com/mattn/go-colorable"
"io"
)
var coloredOut = colorable.NewColorableStdout()
func ColorPrint(a ...interface{}) {
_, err := io.WriteString(coloredOut, fmt.Sprint(a...))
if err != nil {
fmt.Print(a...)
}
}
func ColorPrintln(a ...interface{}) {
_, err := io.WriteString(coloredOut, fmt.Sprintln(a...))
if err != nil {
fmt.Println(a...)
}
}
func ColorPrintf(format string, a ...interface{}) {
_, err := io.WriteString(coloredOut, fmt.Sprintf(format, a...))
if err != nil {
fmt.Printf(format, a...)
}
}
|
package rock
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"
)
func init() {
if IsClient {
Addr = DefaultClientAddr
} else {
Addr = DefaultServerAddr
}
}
func getAndOrPostIfServer() {
if IsClient {
return
}
// consider commenting out? idk
http.Handle("/", http.FileServer(http.Dir("www")))
http.HandleFunc("/"+POST, func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
b, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
delayedError(w, http.StatusBadRequest)
return
}
parts := bytes.Split(b, v)
t, name, body := parts[0][0], string(parts[1]), parts[2]
switch t {
case Terror:
errorDict.RLock()
E, found := errorDict.m[name]
errorDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
E.p.r.Do(E.makeR)
E.p.r.c <- body
case Tbool:
boolDict.RLock()
B, found := boolDict.m[name]
boolDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
B.p.r.Do(B.makeR)
B.p.r.c <- body
case Tint:
intDict.RLock()
I, found := intDict.m[name]
intDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
I.p.r.Do(I.makeR)
I.p.r.c <- body
case Tstring:
stringDict.RLock()
S, found := stringDict.m[name]
stringDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
S.p.r.Do(S.makeR)
S.p.r.c <- body
case Tbytes:
bytesDict.RLock()
B, found := bytesDict.m[name]
bytesDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
B.p.r.Do(B.makeR)
B.p.r.c <- body
default:
delayedError(w, http.StatusBadRequest)
}
})
http.HandleFunc("/"+GET, func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
b, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
delayedError(w, http.StatusBadRequest)
return
}
parts := bytes.Split(b, v)
t, name := parts[0][0], string(parts[1])
switch t {
case Terror:
errorDict.RLock()
E, found := errorDict.m[name]
errorDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
E.p.n.Do(E.makeNIfServer)
E.p.n.c <- 1
E.p.w.Do(E.makeW)
b = <-E.p.w.c
case Tbool:
boolDict.RLock()
B, found := boolDict.m[name]
boolDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
B.p.n.Do(B.makeNIfServer)
B.p.n.c <- 1
B.p.w.Do(B.makeW)
b = <-B.p.w.c
case Tint:
intDict.RLock()
I, found := intDict.m[name]
intDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
I.p.n.Do(I.makeNIfServer)
I.p.n.c <- 1
I.p.w.Do(I.makeW)
b = <-I.p.w.c
case Tstring:
stringDict.RLock()
S, found := stringDict.m[name]
stringDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
S.p.n.Do(S.makeNIfServer)
S.p.n.c <- 1
S.p.w.Do(S.makeW)
b = <-S.p.w.c
case Tbytes:
bytesDict.RLock()
B, found := bytesDict.m[name]
bytesDict.RUnlock()
if !found {
delayedError(w, http.StatusNotFound)
return
}
B.p.n.Do(B.makeNIfServer)
B.p.n.c <- 1
B.p.w.Do(B.makeW)
b = <-B.p.w.c
default:
delayedError(w, http.StatusBadRequest)
return
}
w.Write(b)
})
log.Fatal(http.ListenAndServe(Addr, nil))
}
func delayedError(w http.ResponseWriter, code int) {
time.Sleep(ErrorDelay)
http.Error(w, "", code)
}
func postIfClient(w chan []byte, t byte, name string) {
if !IsClient {
return
}
if len(Addr) == 0 || Addr[len(Addr)-1] != '/' {
Addr += "/"
}
for {
pkt := bytes.Join([][]byte{[]byte{t}, []byte(name), <-w}, v)
for {
resp, err := http.Post(Addr+POST, "text/plain", bytes.NewReader(pkt))
if err == nil && resp.StatusCode < 300 {
break
}
}
}
}
func getIfClient(r chan []byte, t byte, name string) {
if !IsClient {
return
}
if len(Addr) == 0 || Addr[len(Addr)-1] != '/' {
Addr += "/"
}
for {
pkt := bytes.Join([][]byte{[]byte{t}, []byte(name)}, v)
for {
resp, err := http.Post(Addr+GET, "text/plain", bytes.NewReader(pkt))
if err != nil || resp.StatusCode > 299 {
continue
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err == nil {
r <- b
break
}
}
}
}
|
package hamming
import (
"errors"
"strings"
)
func Distance(a, b string) (int, error) {
i,err := diff(strings.Split(strings.ToLower(a), ""), strings.Split(strings.ToLower(b), ""))
return i, err
}
func diff(a []string, b []string) (int, error) {
if len(a) != len(b) {
return 0, errors.New("different lengths")
}
count := 0
for i, v1 := range a {
v2 := b[i]
if v1 != v2 {
count++
}
}
return count, nil
}
|
package go_micro_srv_user
import (
"github.com/jinzhu/gorm"
"github.com/pborman/uuid"
)
func (model *User) BeforeCreate(scope *gorm.Scope) error {
u := uuid.NewRandom()
return scope.SetColumn("Id", u.String())
}
|
package main
import (
"net/http"
"fmt"
)
func handler(){
fmt.Println("df")
}
func main() {
http.ListenAndServe(":80",http.HandlerFunc(handler))
}
|
package main
import "fmt"
func change(s ...int) {
s = append(s, 3)
}
func main() {
slice := make([]int, 5, 5)
slice[0] = 1
slice[1] = 2
change(slice...)
fmt.Println(slice) //[1,2,0,0,0]
change(slice[0:2]...)
fmt.Println(slice) //[1,2,3,0,0]
}
|
/**
*
* By So http://sooo.site
* -----
* Don't panic.
* -----
*
*/
package models
import (
"github.com/wonderivan/logger"
)
// Link 友情链接
type Link struct {
ID uint
URI string
AvatarURI string
Nickname string
Title string
}
// Info 友链详情
func (lk *Link) Info() (err error) {
return db.Where(&lk).Last(&lk).Error
}
// Create 创建友链
func (lk *Link) Create() (err error) {
logger.Debug("sos")
return db.Create(&lk).Error
}
// Update 更新友链
func (lk *Link) Update() (err error) {
return db.Save(&lk).Error
}
// Delete 删除友链
func (lk *Link) Delete() (err error) {
return db.Delete(&lk).Error
}
// List 友链列表
func (lk *Link) List(pageNum, pageSize uint) (linkLink []*Link, count int, err error) {
err = db.Model(&lk).Count(&count).Limit(pageSize).Offset(pageNum*pageSize - pageSize).Find(&linkLink).Error
return
}
// Total 友链统计
func (lk *Link) Total(condition []interface{}) (count uint, err error) {
err = db.Scopes(
where(condition),
).Model(&lk).Count(&count).Error
return
}
|
package scraper_test
import (
"fmt"
"strings"
"github.com/mh-orange/scraper"
)
func ExampleUnmarshal() {
// Parse and unmarshal an HTML document into a very basic Go struct
document := `<html><body><h1 id="name">Hello Scraper!</h1><a href="https://github.org/mh-orange/scraper">Scraper</a> is Grrrrrreat!</body></html>`
v := &struct {
// Name is assigned the text content from the element with the ID "name"
Name string `scraper:"#name"`
// URL is assigned the HREF attribute of the first A element found
URL string `scraper:"a" scrapeType:"attr:href"`
}{}
err := scraper.Unmarshal([]byte(document), v)
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", v)
// Output: &{Name:Hello Scraper! URL:https://github.org/mh-orange/scraper}
}
func ExampleUnmarshal_slice() {
// Scraper can be used to unmarshal structs with slices
// of things as well
document := `
<html>
<body>
<h1 id="name">Hello Scraper!</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>`
v := &struct {
// Name is assigned the text content from the element with the ID "name"
Name string `scraper:"#name"`
// Items is appended with the text content of each element matching the
// "ul li" CSS selector
Items []string `scraper:"ul li"`
}{}
err := scraper.Unmarshal([]byte(document), v)
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", v)
// Output: &{Name:Hello Scraper! Items:[Item 1 Item 2 Item 3]}
}
func ExampleUnmarshal_nested() {
// Scraper can be used to unmarshal structs with other structs
// in them
document := `
<html>
<body>
<h1 id="name">Hello Scraper!</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>`
v := &struct {
// Name is assigned the text content from the element with the ID "name"
Name string `scraper:"#name"`
// Items is matched with the ul tag and then names is matched by the
// li tags within. Nested structs will be unmarshaled with the matching
// _subtree_ not the entire document
Items struct {
Names []string `scraper:"li"`
} `scraper:"ul"`
}{}
err := scraper.Unmarshal([]byte(document), v)
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", v)
// Output: &{Name:Hello Scraper! Items:{Names:[Item 1 Item 2 Item 3]}}
}
func ExampleDecoder() {
// Decoder is useful for unmarshaling from an input stream
document := `<html><body><h1 id="name">Hello Scraper!</h1></body></html>`
v := &struct {
// Name is assigned the text content from the element with the ID "name"
Name string `scraper:"#name"`
}{}
reader := strings.NewReader(document)
scraper.NewDecoder(reader).Decode(v)
fmt.Printf("%+v\n", v)
// Output: &{Name:Hello Scraper!}
}
|
package main
const color_bold = "\x1b[1m"
const color_green = "\x1b[32m"
const color_normal = "\x1b[0m"
func Green(s string) string {
return color_green + s + color_normal
}
func Bold(s string) string {
return color_bold + s + color_normal
}
func Paint(str string, indexes [][]int, color func(s string) string) string {
move_right := 0
for _, k := range indexes {
k[0] += move_right
k[1] += move_right
first := str[0:k[0]]
last := str[k[1]:]
match := str[k[0]:k[1]]
color_match := color(match)
str = first + color_match + last
move_right += len(color_match) - len(match)
}
return str
}
func onlyNiceCaracters(s string) string {
var new_s string
for i := 0; i < len(s); i++ {
if s[i] < 32 || s[i] > 126 {
new_s += "."
} else {
new_s += string(s[i])
}
}
return new_s
}
|
package requests
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
"github.com/atomicjolt/canvasapi/models"
"github.com/atomicjolt/string_utils"
)
// ListModules A paginated list of the modules in a course
// https://canvas.instructure.com/doc/api/modules.html
//
// Path Parameters:
// # Path.CourseID (Required) ID
//
// Query Parameters:
// # Query.Include (Optional) . Must be one of items, content_details- "items": Return module items inline if possible.
// This parameter suggests that Canvas return module items directly
// in the Module object JSON, to avoid having to make separate API
// requests for each module when enumerating modules and items. Canvas
// is free to omit 'items' for any particular module if it deems them
// too numerous to return inline. Callers must be prepared to use the
// {api:ContextModuleItemsApiController#index List Module Items API}
// if items are not returned.
// - "content_details": Requires 'items'. Returns additional
// details with module items specific to their associated content items.
// Includes standard lock information for each item.
// # Query.SearchTerm (Optional) The partial name of the modules (and module items, if 'items' is
// specified with include[]) to match and return.
// # Query.StudentID (Optional) Returns module completion information for the student with this id.
//
type ListModules struct {
Path struct {
CourseID string `json:"course_id" url:"course_id,omitempty"` // (Required)
} `json:"path"`
Query struct {
Include []string `json:"include" url:"include,omitempty"` // (Optional) . Must be one of items, content_details
SearchTerm string `json:"search_term" url:"search_term,omitempty"` // (Optional)
StudentID string `json:"student_id" url:"student_id,omitempty"` // (Optional)
} `json:"query"`
}
func (t *ListModules) GetMethod() string {
return "GET"
}
func (t *ListModules) GetURLPath() string {
path := "courses/{course_id}/modules"
path = strings.ReplaceAll(path, "{course_id}", fmt.Sprintf("%v", t.Path.CourseID))
return path
}
func (t *ListModules) GetQuery() (string, error) {
v, err := query.Values(t.Query)
if err != nil {
return "", err
}
return v.Encode(), nil
}
func (t *ListModules) GetBody() (url.Values, error) {
return nil, nil
}
func (t *ListModules) GetJSON() ([]byte, error) {
return nil, nil
}
func (t *ListModules) HasErrors() error {
errs := []string{}
if t.Path.CourseID == "" {
errs = append(errs, "'Path.CourseID' is required")
}
for _, v := range t.Query.Include {
if v != "" && !string_utils.Include([]string{"items", "content_details"}, v) {
errs = append(errs, "Include must be one of items, content_details")
}
}
if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, ", "))
}
return nil
}
func (t *ListModules) Do(c *canvasapi.Canvas, next *url.URL) ([]*models.Module, *canvasapi.PagedResource, error) {
var err error
var response *http.Response
if next != nil {
response, err = c.Send(next, t.GetMethod(), nil)
} else {
response, err = c.SendRequest(t)
}
if err != nil {
return nil, nil, err
}
if err != nil {
return nil, nil, err
}
body, err := ioutil.ReadAll(response.Body)
response.Body.Close()
if err != nil {
return nil, nil, err
}
ret := []*models.Module{}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, nil, err
}
pagedResource, err := canvasapi.ExtractPagedResource(response.Header)
if err != nil {
return nil, nil, err
}
return ret, pagedResource, nil
}
|
package printer
import (
"fmt"
"github.com/pterm/pterm"
)
const (
dfcBGHeader = pterm.BgBlue
)
type CLIPrinter interface {
PrintInfo(text string)
PrintDebug(text string)
PrintError(text string)
PrintSummary(data [][]string)
IntroScreen()
}
type CLIPrinterConfigs struct {
}
func NewCLIPrinter() CLIPrinter {
return new(CLIPrinterConfigs)
}
func (ref *CLIPrinterConfigs) PrintInfo(text string) {
pterm.Info.Println(text)
}
func (ref *CLIPrinterConfigs) PrintDebug(text string) {
pterm.Debug.Println(text)
}
func (ref *CLIPrinterConfigs) PrintError(text string) {
pterm.Error.Println(text)
}
func (ref *CLIPrinterConfigs) IntroScreen() {
fmt.Sprintln()
logo, _ := pterm.DefaultBigText.WithLetters(
pterm.NewLettersFromStringWithStyle("CSV:", pterm.NewStyle(pterm.FgLightGreen)),
pterm.NewLettersFromStringWithStyle(":parser", pterm.NewStyle(pterm.FgLightWhite))).
Srender()
pterm.DefaultCenter.Print(logo)
pterm.DefaultCenter.Print(pterm.DefaultHeader.WithFullWidth().WithBackgroundStyle(pterm.NewStyle(pterm.BgGreen)).WithMargin(0).Sprint("WELCOME!"))
}
func (ref *CLIPrinterConfigs) PrintSummary(data [][]string) {
pterm.Info.Println("Execution summary:")
td := pterm.TableData{}
for _, o := range data {
td = append(td, o)
}
pterm.DefaultTable.WithHasHeader().WithData(td).Render()
}
func clear() {
print("\033[H\033[2J")
}
|
package main
import (
"fmt"
"github.com/bwmarrin/discordgo"
"noah/idc-bot/util"
"strings"
)
var (
componentHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
"status_restore": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
guild, _ := client.Guild(i.GuildID)
if i.Member.User.ID != guild.OwnerID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: 1 << 6,
Content: "You are not the owner and are therefore not allowed to restore this server.",
},
})
return
}
if util.UserPerms(s, s.State.User.ID, i.GuildID)&discordgo.PermissionAdministrator != discordgo.PermissionAdministrator {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "**ALERT** \n *I don't have adequate permissions to restore!*",
},
})
return
}
p := nukePredictors[i.GuildID]
if !p.Triggered {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: 1 << 6,
Content: "Server not in lockdown.",
},
})
return
}
if p.Restoring {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Server already attempting to restore.",
},
})
return
}
strikes := strings.Join(p.Strikes, "\n")
fmt.Println(p.Strikes)
var embed *discordgo.MessageEmbed
if len(strings.Split(strikes, "")) > 1000 {
embed = &discordgo.MessageEmbed{
Title: "Order Restored",
Color: BrandedColor,
Fields: []*discordgo.MessageEmbedField{
{
Name: "Too Many Strikes From Last Raid",
Value: "```diff\n\n\nDue to there being too many strikes, we cannot show them here....```",
},
},
Footer: &discordgo.MessageEmbedFooter{
Text: "This bot is not wick",
IconURL: "https://cdn.discordapp.com/attachments/781803550598627341/782155510429909012/pfp2.png",
},
}
} else {
embed = &discordgo.MessageEmbed{
Title: "Order Restored",
Color: BrandedColor,
Fields: []*discordgo.MessageEmbedField{
{
Name: "Strikes From Previous Raid: ",
Value: fmt.Sprintf("```diff\n\n%s```", strikes),
},
},
Footer: &discordgo.MessageEmbedFooter{
Text: "This bot is not wick.",
IconURL: "https://cdn.discordapp.com/attachments/781803550598627341/782155510429909012/pfp2.png",
},
}
}
go p.Restore(func() {
s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
Content: "Restoration Complete",
})
})
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{embed},
},
})
},
}
)
|
package main
import (
"fmt"
)
// 简单的一个函数,实现了参数+1的操作
func add1(a *int)int{
*a=*a+1 // 修改了a的值
return *a // 返回新值
}
func main(){
x:=3
fmt.Println("x = ",x) // 应该输出 “x=3”
x1 := add1(&x) // 调用 add1(&x) 传x的地址
fmt.Println("x+1 = ", x1) // 应该输出 "x+1 = 4"
fmt.Println("x = ", x) // 应该输出 "x = 4"
}
/**
PS D:\goLang\github\go-web\Go语言基础\流程和函数> go run 1.go
x = 3
x+1 = 4
x = 4
*/ |
// Copyright 2020 The VectorSQL Authors.
//
// Code is licensed under Apache License, Version 2.0.
package executors
import (
"databases"
"planners"
)
type CreateTableExecutor struct {
ctx *ExecutorContext
plan *planners.CreateTablePlan
}
func NewCreateTableExecutor(ctx *ExecutorContext, plan planners.IPlan) IExecutor {
return &CreateTableExecutor{
ctx: ctx,
plan: plan.(*planners.CreateTablePlan),
}
}
func (executor *CreateTableExecutor) Execute() (*Result, error) {
ectx := executor.ctx
ast := executor.plan.Ast
schema := ectx.session.GetDatabase()
if !ast.Table.Qualifier.IsEmpty() {
schema = ast.Table.Qualifier.String()
}
database, err := databases.GetDatabase(schema)
if err != nil {
return nil, err
}
if err := database.Executor().CreateTable(ast); err != nil {
return nil, err
}
result := NewResult()
return result, nil
}
func (executor *CreateTableExecutor) String() string {
return ""
}
|
package main
import (
"fmt"
"gitee.com/jntse/gotoolkit/log"
"gitee.com/jntse/gotoolkit/net"
"gitee.com/jntse/gotoolkit/redis"
"gitee.com/jntse/gotoolkit/util"
"gitee.com/jntse/gotoolkit/eventqueue"
"gitee.com/jntse/minehero/pbmsg"
"gitee.com/jntse/minehero/server/tbl"
_"gitee.com/jntse/minehero/server/def"
pb "github.com/gogo/protobuf/proto"
//"gitee.com/jntse/minehero/server/def"
_"github.com/go-redis/redis"
"strconv"
_"strings"
_"time"
)
//const (
// StayHall = 1 // 待在大厅
// RoomCreating = 2 // 创建房间中
// RoomCreateFail = 3 // 失败
// GamePlaying = 4 // 游戏中
// )
// --------------------------------------------------------------------------
/// @brief 玩家房间简单数据
// --------------------------------------------------------------------------
type RoomBase struct {
roomid int64
sid_room int
kind int32
tm_closing int64 // 房间关闭超时
creating bool
}
func (this *RoomBase) Reset() {
this.roomid = 0
this.sid_room = 0
this.kind = 0
this.tm_closing = 0
this.creating = false
}
// --------------------------------------------------------------------------
/// @brief db数据管理
// --------------------------------------------------------------------------
type DBUserData struct {
bin *msg.Serialize // db二进制数据
tm_login int64
tm_logout int64
money uint32
coupon uint32
yuanbao uint32
level uint32
exp uint32
continuelogin uint32
nocountlogin uint32
signreward uint32
signtime uint32
addrlist []*msg.UserAddress
freestep int32
givestep int64
wechatopenid string
presentcount int32
presentrecord int64
invitationcode string
luckydraw []*msg.LuckyDrawItem
}
// --------------------------------------------------------------------------
/// @brief 玩家
// --------------------------------------------------------------------------
type GateUser struct {
DBUserData
client network.IBaseNetSession
account string
verifykey string
online bool
tickers UserTicker
bag UserBag // 背包
task UserTask
tm_disconnect int64
tm_heartbeat int64 // 心跳时间
tm_asynsave int64 // 异步存盘超时
savedone bool // 存盘标记
cleanup bool // 清理标记
roomdata RoomBase // 房间信息
token string // token
asynev eventque.AsynEventQueue // 异步事件处理
broadcastbuffer []uint64 // 广播消息缓存
}
func NewGateUser(account, key, token string) *GateUser {
u := &GateUser{account: account, verifykey: key}
u.bag.Init(u)
u.task.Init(u)
u.tickers.Init(u.OnTicker10ms, u.OnTicker100ms, u.OnTicker1s, u.OnTicker5s, u.OnTicker1m)
u.cleanup = false
u.tm_disconnect = 0
u.continuelogin = 1
u.tm_asynsave = 0
u.savedone = false
u.token = token
u.broadcastbuffer = make([]uint64,0)
return u
}
func (this *GateUser) Account() string {
return this.account
}
func (this *GateUser) EntityBase() *msg.EntityBase {
return this.bin.GetEntity()
}
func (this *GateUser) UserBase() *msg.UserBase {
return this.bin.GetBase()
}
func (this *GateUser) Name() string {
return this.EntityBase().GetName()
}
func (this *GateUser) Id() uint64 {
return this.EntityBase().GetId()
}
func (this *GateUser) Face() string {
return this.EntityBase().GetFace()
}
func (this *GateUser) SetFace(f string) {
this.EntityBase().Face = pb.String(f)
}
func (this *GateUser) Sid() int {
if this.client != nil { return this.client.Id() }
return 0
}
func (this *GateUser) Level() uint32 {
return this.level
}
func (this *GateUser) Exp() uint32 {
return this.exp
}
func (this *GateUser) Token() string {
return this.token
}
func (this *GateUser) SetToken(t string) {
this.token = t
}
func (this *GateUser) GetDefaultAddress() *msg.UserAddress {
if this.GetAddressSize() != 0 { return this.addrlist[0] }
return nil
}
func (this *GateUser) SetDefaultAddress(index int32) {
//this.address = addr
}
func (this *GateUser) AddAddress(receiver, phone, address string) {
addr := &msg.UserAddress{Receiver:pb.String(receiver), Phone:pb.String(phone), Address:pb.String(address)}
this.addrlist = append(this.addrlist, addr)
}
func (this *GateUser) ClearAddress() {
this.addrlist = make([]*msg.UserAddress, 0)
}
func (this *GateUser) GetAddressSize() uint32 {
return uint32(len(this.addrlist))
}
func (this *GateUser) SendAddress() {
send := &msg.GW2C_SendDeliveryAddressList{ List:make([]*msg.UserAddress, 0) }
for _ ,v := range this.addrlist {
send.List = append(send.List, v)
}
this.SendMsg(send)
}
func (this *GateUser) Verifykey() string {
return this.verifykey
}
func (this *GateUser) IsOnline() bool {
return this.online
}
func (this *GateUser) GameKind() int32 {
return this.roomdata.kind
}
// 房间id
func (this *GateUser) RoomId() int64 {
return this.roomdata.roomid
}
// 房间服务器 sid
func (this *GateUser) RoomSid() int {
return this.roomdata.sid_room
}
// 是否有房间
func (this *GateUser) IsInRoom() bool {
if this.RoomId() != 0 {
return true
}
return false
}
// 正在创建房间
func (this *GateUser) IsRoomCreating() bool {
return this.roomdata.creating
}
// 房间关闭中
func (this *GateUser) IsRoomClosing() bool {
return this.roomdata.tm_closing != 0
}
// 关闭超时, 10秒
func (this *GateUser) IsRoomCloseTimeOut() bool {
return util.CURTIMEMS() > (this.roomdata.tm_closing + 10000)
}
func (this *GateUser) SetWechatOpenId(id string) {
this.wechatopenid = id
}
func (this *GateUser) WechatOpenId() string {
return this.wechatopenid
}
// 自己邀请码
func (this *GateUser) MyInvitationCode() string {
return fmt.Sprintf("TJ%d",this.Id())
}
// 邀请人邀请码
func (this *GateUser) InvitationCode() string {
return this.invitationcode
}
// 邀请人
func (this *GateUser) Inviter() uint64 {
if code := this.InvitationCode(); len(code) > 2 {
inviter , _ := strconv.ParseUint(code[2:], 10, 64)
return inviter
}
return 0
}
func (this *GateUser) GetMoneyCost() int64 {
userbase := this.UserBase()
return userbase.GetScounter().GetMoneyCost()
}
func (this *GateUser) GetMoneyCostReset() int64 {
userbase := this.UserBase()
return userbase.GetScounter().GetMoneyCostReset()
}
func (this *GateUser) SetMoneyCost(cost int64) {
userbase := this.UserBase()
userbase.GetScounter().MoneyCost = pb.Int64(cost)
}
func (this *GateUser) SetMoneyCostReset(reset int64) {
userbase := this.UserBase()
userbase.GetScounter().MoneyCostReset = pb.Int64(reset)
}
func (this *GateUser) IsCleanUp() bool {
return this.cleanup
}
func (this *GateUser) SendMsg(msg pb.Message) {
if this.online == false {
log.Info("账户[%s] [%d %s] 不在线", this.Account(), this.Id(), this.Name())
return
}
this.client.SendCmd(msg)
}
// 广播缓存
func (this *GateUser) AddBroadCastMsg(uuid uint64) {
this.broadcastbuffer = append(this.broadcastbuffer, uuid)
}
// 玩家全部数据
func (this *GateUser) SendUserBase() {
send := &msg.GW2C_SendUserInfo{}
entity, base, item := this.bin.GetEntity(), this.bin.GetBase(), this.bin.GetItem()
// clone类似c++的copyfrom
send.Entity = pb.Clone(entity).(*msg.EntityBase)
send.Base = pb.Clone(base).(*msg.UserBase)
send.Item = pb.Clone(item).(*msg.ItemBin)
this.SendMsg(send)
}
func (this *GateUser) IsLoadDB() bool {
return this.bin != nil
}
func (this *GateUser) LoadDB() bool {
key, info := fmt.Sprintf("accounts_%s", this.account), &msg.AccountInfo{}
if err := utredis.GetProtoBin(Redis(), key, info); err != nil {
log.Error("账户%s 获取账户数据失败,err: %s", this.account, err)
return false
}
// 获取游戏数据
this.bin = new(msg.Serialize)
userkey := fmt.Sprintf("userbin_%d", info.GetUserid())
if err := utredis.GetProtoBin(Redis(), userkey, this.bin); err != nil {
log.Error("账户%s 获取玩家数据失败,err: %s", this.account, err)
return false
}
this.OnLoadDB("登陆")
return true
}
func (this *GateUser) OnLoadDB(way string) {
log.Info("玩家数据: ==========")
log.Info("账户%s 加载DB数据成功 方式[%s]", this.account, way)
log.Info("%v", this.bin)
log.Info("玩家数据: ==========")
// 没有名字取个名字
entity := this.bin.GetEntity()
if entity == nil {
this.bin.Entity = &msg.EntityBase{}
}
if entity.GetName() == "" {
entity.Name = pb.String(fmt.Sprintf("%d_name", this.Id()))
}
// proto对象变量初始化
if this.bin.Base == nil { this.bin.Base = &msg.UserBase{} }
if this.bin.Base.Scounter == nil { this.bin.Base.Scounter = &msg.SimpleCounter{} }
if this.bin.Base.Wechat == nil { this.bin.Base.Wechat = &msg.UserWechat{} }
if this.bin.Item == nil { this.bin.Item = &msg.ItemBin{} }
if this.bin.Base.Addrlist == nil { this.bin.Base.Addrlist = make([]*msg.UserAddress,0) }
if this.bin.Base.Freepresent == nil { this.bin.Base.Freepresent = &msg.FreePresentMoney{} }
if this.bin.Base.Task == nil { this.bin.Base.Task = &msg.UserTask{} }
if this.bin.Base.Luckydraw == nil { this.bin.Base.Luckydraw = &msg.LuckyDrawHistory{ Drawlist:make([]*msg.LuckyDrawItem,0) } }
// 加载二进制
this.LoadBin()
// 新用户回调
if this.tm_login == 0 {
this.OnCreateNew()
}
}
// 打包数据到二进制结构
func (this *GateUser) PackBin() *msg.Serialize {
bin := &msg.Serialize{}
// 基础信息
bin.Entity = pb.Clone(this.bin.GetEntity()).(*msg.EntityBase)
// 玩家信息
bin.Base = pb.Clone(this.bin.GetBase()).(*msg.UserBase)
//bin.Base = &msg.UserBase{}
//bin.Base.Scounter = &msg.SimpleCounter{}
//bin.Base.Wechat = &msg.UserWechat{}
//bin.Base.Addrlist = make([]*msg.UserAddress,0)
//bin.Base.Freepresent = &msg.FreePresentMoney{}
userbase := bin.GetBase()
userbase.Tmlogin = pb.Int64(this.tm_login)
userbase.Tmlogout = pb.Int64(this.tm_logout)
userbase.Money = pb.Uint32(this.money)
userbase.Coupon = pb.Uint32(this.coupon)
userbase.Yuanbao = pb.Uint32(this.yuanbao)
userbase.Level = pb.Uint32(this.level)
userbase.Exp = pb.Uint32(this.exp)
userbase.Continuelogin = pb.Uint32(this.continuelogin)
userbase.Nocountlogin = pb.Uint32(this.nocountlogin)
userbase.Signreward = pb.Uint32(this.signreward)
userbase.Signtime = pb.Uint32(this.signtime)
userbase.Addrlist = this.addrlist[:]
userbase.GetScounter().Freestep = pb.Int32(this.freestep)
userbase.GetScounter().Givestep = pb.Int64(this.givestep)
userbase.Wechat.Openid = pb.String(this.wechatopenid)
userbase.GetFreepresent().Count = pb.Int32(this.presentcount)
userbase.GetFreepresent().Tmrecord = pb.Int64(this.presentrecord)
userbase.Invitationcode = pb.String(this.invitationcode)
// 幸运抽奖
userbase.Luckydraw.Drawlist = make([]*msg.LuckyDrawItem,0)
for _, v := range this.luckydraw {
userbase.Luckydraw.Drawlist = append(userbase.Luckydraw.Drawlist, v)
}
// 道具信息
this.bag.PackBin(bin)
this.task.PackBin(bin)
//
return bin
}
// 将二进制解析出来
func (this *GateUser) LoadBin() {
// 基础信息
// 玩家信息
userbase := this.bin.GetBase()
this.tm_login = userbase.GetTmlogin()
this.tm_logout = userbase.GetTmlogout()
this.money = userbase.GetMoney()
this.coupon = userbase.GetCoupon()
this.yuanbao = userbase.GetYuanbao()
this.level = userbase.GetLevel()
this.exp = userbase.GetExp()
this.continuelogin = userbase.GetContinuelogin()
this.nocountlogin = userbase.GetNocountlogin()
this.signreward = userbase.GetSignreward()
this.signtime = userbase.GetSigntime()
this.addrlist = userbase.GetAddrlist()[:]
this.freestep = userbase.GetScounter().GetFreestep()
this.givestep = userbase.GetScounter().GetGivestep()
this.wechatopenid = userbase.GetWechat().GetOpenid()
this.presentcount = userbase.GetFreepresent().GetCount()
this.presentrecord = userbase.GetFreepresent().GetTmrecord()
this.invitationcode = userbase.GetInvitationcode()
// 幸运抽奖
for _, v := range userbase.Luckydraw.Drawlist {
this.luckydraw = append(this.luckydraw, v)
}
// 道具信息
this.bag.Clean()
this.bag.LoadBin(this.bin)
// 任务
this.task.LoadBin(this.bin)
}
// TODO: 存盘可以单独协程
func (this *GateUser) Save() {
key := fmt.Sprintf("userbin_%d", this.Id())
if err := utredis.SetProtoBin(Redis(), key, this.PackBin()); err != nil {
log.Error("保存玩家[%s %d]数据失败", this.Name(), this.Id())
return
}
log.Info("保存玩家[%s %d]数据成功", this.Name(), this.Id())
}
// 异步存盘完成回调
func (this *GateUser) AsynSaveFeedback() {
this.savedone = true
}
// 新用户回调
func (this* GateUser) OnCreateNew() {
}
// 上线回调,玩家数据在LoginOk中发送
func (this *GateUser) Online(session network.IBaseNetSession) bool {
if this.online == true {
log.Error("Sid[%d] 账户[%s] 玩家[%d %s] Online失败,已经处于在线状态", this.Sid(), this.account, this.Id(), this.Name())
return false
}
curtime := util.CURTIME()
this.tickers.Start()
this.asynev.Start(int64(this.Id()), 100)
this.LoginStatistics()
this.online = true
this.client = session
this.tm_login = curtime
this.tm_disconnect = 0
this.tm_heartbeat = util.CURTIMEMS()
this.savedone = false
this.roomdata.Reset()
log.Info("Sid[%d] 账户[%s] 玩家[%d] 名字[%s] 登录成功", this.Sid(), this.account, this.Id(), this.Name())
// 免费赠送金币
this.CheckFreePresentMoney(false)
// 上线任务检查
this.OnlineTaskCheck()
// 同步数据到客户端
this.Syn()
return true
}
func (this *GateUser) Syn(){
this.SendUserBase()
this.SendSign()
//this.CheckGiveFreeStep(util.CURTIME(), "上线跨整点")
this.CheckHaveCompensation()
this.SyncBigRewardPickNum()
//this.QueryPlatformCoins()
}
// 断开连接回调
func (this *GateUser) OnDisconnect() {
log.Info("sid[%d] 账户%s 玩家[%s %d] 断开连接", this.Sid(), this.account, this.Name(), this.Id())
if this.online == false {
return
}
this.online = false
this.client = nil
this.tm_disconnect = util.CURTIMEMS()
if this.IsInRoom() == true { this.SendRsUserDisconnect() }
//this.PlatformPushUserOnlineTime()
}
// 服务器下线玩家
func (this *GateUser) KickOut(way string) {
log.Info("sid[%d] 账户[%s] [%d %s] KickOut 原因[%s]", this.Sid(), this.account, this.Id(), this.Name(), way)
if this.online == false {
return
}
this.online = false
this.client.Close()
this.client = nil
this.tm_disconnect = util.CURTIMEMS()
if this.IsInRoom() == true { this.SendRsUserDisconnect() }
//this.PlatformPushUserOnlineTime()
}
// 检查下线存盘
func (this *GateUser) CheckDisconnectTimeOut(now int64) {
if this.tm_disconnect == 0 {
return
}
// 延迟存盘清理
if now < this.tm_disconnect + tbl.Global.Disconclean {
return
}
// 等待房间关闭
if this.IsInRoom() && !this.IsRoomCloseTimeOut() {
return
}
// 异步事件未处理完
if this.asynev.EventSize() != 0 || this.asynev.FeedBackSize() != 0 {
return
}
// 异步存盘,最大延迟1秒
//if this.tm_asynsave == 0 {
// this.tm_asynsave = now + 1000
// event := NewUserSaveEvent(this.Save)
// this.AsynEventInsert(event)
//}
//if now < this.tm_asynsave {
// return
//}
this.Logout()
}
// 真下线(存盘,从Gate清理玩家数据)
func (this *GateUser) Logout() {
this.online = false
this.tm_logout = util.CURTIME()
this.cleanup = true
this.Save()
UnBindingAccountGateWay(this.account)
this.asynev.Shutdown()
log.Info("账户%s 玩家[%s %d] 存盘下线", this.account, this.Name(), this.Id())
}
// logout完成,做最后清理
func (this* GateUser) OnCleanUp() {
this.tickers.Stop()
}
// 发送个人通知
func (this *GateUser) SendNotify(text string) {
send := &msg.GW2C_MsgNotify{Text: pb.String(text)}
this.SendMsg(send)
}
// 发送房间消息
func (this *GateUser) SendRoomMsg(msg pb.Message) {
if this.IsInRoom() == false {
log.Error("玩家[%s %d]没有房间信息", this.Name(), this.Id())
return
}
RoomSvrMgr().SendMsg(this.roomdata.sid_room, msg)
}
// 转发消息到roomserver(效率不是最理想的方式)
func (this *GateUser) TransferRoomMsg(m pb.Message) {
name := pb.MessageName(m)
msgbuf, _ := pb.Marshal(m)
send := &msg.GW2RS_MsgTransfer{ Uid:pb.Uint64(this.Id()), Name:pb.String(name), Buf:msgbuf }
this.SendRoomMsg(send)
}
// 回复客户端
func (this *GateUser) ReplyStartGame(err string, roomid int64) {
send := &msg.GW2C_RetStartGame{Errcode: pb.String(err), Roomid: pb.Int64(roomid)}
this.SendMsg(send)
if err != "" {
log.Info("玩家[%s %d] 开始游戏失败: roomid=%d errcode=%s", this.Name(), this.Id(), roomid, err)
}
}
// 请求开始游戏
func (this *GateUser) ReqStartGame(gamekind int32) (errcode string) {
// 检查游戏类型是否有效
//dunconfig , findid := tbl.DungeonsBase.TDungeonsById[gamekind]
//if findid == false {
// errcode = "无效的游戏类型"
// return
//}
if Match() == nil {
log.Error("玩家[%s %d] 匹配服务器未连接", this.Name(), this.Id())
errcode = "创建房间服务器不可用"
return
}
//
if RoomSvrMgr().Num() == 0 {
log.Error("玩家[%s %d] 请求开房间,但是没有房间服务器", this.Name(), this.Id())
errcode = "房间服务器不可用"
return
}
// 创建中
if this.IsRoomCreating() {
log.Error("玩家[%s %d] 重复创建房间,正在创建房间中", this.Name(), this.Id())
errcode = "正在创建房间中"
return
}
// 有房间
if this.IsInRoom() {
log.Error("玩家[%s %d] 重复创建房间,已经有一个房间[%d]", this.Name(), this.Id(), this.RoomId())
errcode = "重复创建房间"
return
}
// 请求创建房间
this.roomdata.kind = gamekind
this.roomdata.creating = true
//
send := &msg.GW2MS_ReqCreateRoom{
Userid: pb.Uint64(this.Id()),
Gamekind: pb.Int32(gamekind),
}
Match().SendCmd(send)
log.Info("玩家[%s %d] 请求创建房间类型:%d ts[%d]", this.Name(), this.Id(), gamekind, util.CURTIMEMS())
return
}
// 开启游戏房间成功
func (this *GateUser) StartGameOk(servername string, roomid int64) {
var agent *RoomAgent = RoomSvrMgr().FindByName(servername)
if agent == nil {
log.Error("玩家[%s %d] 开房间成功,但找不到RoomServer[%s]", this.Name(), this.Id(), servername)
return
}
this.roomdata.roomid = roomid
this.roomdata.sid_room = agent.Id()
// TODO: 将个人信息上传到Room
send := &msg.BT_UploadGameUser{}
send.Roomid = pb.Int64(roomid)
//send.Bin = pb.Clone(this.PackBin()).(*msg.Serialize)
send.Bin = this.PackBin()
agent.SendMsg(send)
log.Info("玩家[%s %d] 创建房间[%d]成功 向RS上传玩家个人数据 ts[%d]", this.Name(), this.Id(), roomid, util.CURTIMEMS())
}
// 开启游戏房间失败
func (this *GateUser) StartGameFail(err string) {
this.roomdata.Reset()
}
// 房间关闭
func (this *GateUser) GameEnd(bin *msg.Serialize, reason string) {
// 重置房间数据
log.Info("玩家[%s %d] 房间关闭 房间[%d] 原因[%s]", this.Name(), this.Id(), this.RoomId(), reason)
this.roomdata.Reset()
// 加载玩家最新数据
if bin != nil {
this.bin = pb.Clone(bin).(*msg.Serialize)
this.OnLoadDB("房间结束")
if this.IsOnline() {
this.SendUserBase()
//this.CheckGiveFreeStep(util.CURTIME(), "回大厅跨整点")
this.SyncBigRewardPickNum()
//this.QueryPlatformCoins()
}
}
}
// 通知RS 玩家已经断开连接了
func (this *GateUser) SendRsUserDisconnect() {
if this.roomdata.tm_closing != 0 { return }
this.roomdata.tm_closing = util.CURTIMEMS()
msgclose := &msg.GW2RS_UserDisconnect{Roomid: pb.Int64(this.roomdata.roomid), Userid: pb.Uint64(this.Id())}
this.SendRoomMsg(msgclose)
log.Info("玩家[%d %s] 通知RoomServer关闭房间", this.Id(), this.Name())
}
// 插入新异步事件
func (this *GateUser) AsynEventInsert(event eventque.IEvent) {
this.asynev.Push(event)
}
// 上线任务检查
func (this *GateUser) OnlineTaskCheck() {
// 账户注册任务
if this.task.IsTaskFinish(int32(msg.TaskId_RegistAccount)) == false {
this.task.TaskFinish(int32(msg.TaskId_RegistAccount))
}
// 被自己邀请人达成积分任务
keyinviter := fmt.Sprintf("TaskInviteeTopScoreFinish_%d", this.Id())
sumfinish, _ := Redis().SCard(keyinviter).Result()
if sumfinish != 0 && this.task.IsTaskFinish(int32(msg.TaskId_InviteeTopScore)) == false {
this.task.TaskFinish(int32(msg.TaskId_InviteeTopScore))
}
}
|
package actions
import "log"
import "cointhink/mailer"
import "cointhink/proto"
import "cointhink/model/account"
import gproto "github.com/golang/protobuf/proto"
func DoNotify(notify *proto.Notify, accountId string) []gproto.Message {
resp := []gproto.Message{}
account_, err := account.Find(accountId)
if err != nil {
resp = append(resp, &proto.NotifyResponse{Ok: false, ErrMessage: "bad accountId"})
} else {
log.Printf("%+v", notify)
notify.Recipient = account_.Email
mailer.MailNotify(notify)
resp = append(resp, &proto.NotifyResponse{Ok: true})
}
return resp
}
|
package routes
import (
"context"
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"strings"
"math/rand"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"github.com/yashjjw/apiMeetings/main/models"
)
type RouteHandler struct {
Meeting *mongo.Collection
}
func NewRouteHandler(Meeting *mongo.Collection) *RouteHandler {
return &RouteHandler{
Meeting: Meeting,
}
}
//******************generate random string for ID *****************
var seededRand *rand.Rand = rand.New(
rand.NewSource(time.Now().UnixNano()))
func StringWithCharset(length int, charset string) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}
//*****************function to get meeting details of a participant or meetings within a time frame **************
func (router *RouteHandler) getMeeting(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
startArr, noneStart := query["start"]
endArr, noneEnd := query["end"]
if (!noneStart || !noneEnd || len(startArr) <=0 || len(endArr) <=0){
participantArr, noneParticipant := query["participant"]
if (!noneParticipant || len(participantArr) <=0) {
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
participant := participantArr[0]
participantUnwind := bson.D{{
"$unwind", "$participants",
}}
matching := bson.D{{
"$match", bson.M{
"participants.email": participant,
},
}}
meetingsEx, err := router.Meeting.Aggregate(context.TODO(), mongo.Pipeline{participantUnwind, matching})
var meetings []bson.M
if err = meetingsEx.All(context.TODO(), &meetings); err != nil {
log.Fatal(err.Error())
http.Error(w, "Server Error", http.StatusInternalServerError)
}
if len(meetings) != 0 {
json.NewEncoder(w).Encode(meetings)
return
}
}
start, _ := strconv.Atoi(startArr[0])
end, _ := strconv.Atoi(endArr[0])
meetingsEx, err := router.Meeting.Find(context.TODO(), bson.D{
{
"startTime",
bson.D{{
"$gte", start,
}}},
{
"endTime",
bson.D{{
"$lte", end,
}},
}})
if err != nil {
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
var meetings []bson.M
if err = meetingsEx.All(context.TODO(), &meetings); err != nil {
log.Fatal(err.Error())
http.Error(w, "Server Error", http.StatusInternalServerError)
}
json.NewEncoder(w).Encode(meetings)
return
}
//*****************function to schedule meetings******************************
func (router *RouteHandler) scheduleMeeting(w http.ResponseWriter, r *http.Request) {
var meet models.Meeting
w.Header().Set("Content-Type", "application/json")
err := json.NewDecoder(r.Body).Decode(&meet)
meet.CreationTime = time.Now().Unix()
const charset = "abcdefghijklmnopqrstuvwxyz" + "0123456789"
meet.ID=StringWithCharset(10, charset)
if err != nil {
http.Error(w, "Invalid Request", http.StatusBadRequest)
return
}
if meet.StartTime > meet.EndTime {
http.Error(w, "startTime can not be lesser than endTime", http.StatusBadRequest)
}
emails := make(bson.A, len(meet.Participants))
for i := 0; i < len(meet.Participants); i++ {
emails[i] = meet.Participants[i].Email
}
participantUnwind := bson.D{{
"$unwind", "$participants",
}}
//To check overlapping meetings **match if start or end time of new meeting lies between start and end of exising meeting
timeOverlap := bson.D{{
"$match", bson.M{
"$or": bson.A{
bson.M{
"startTime": bson.M{"$lte": meet.StartTime},
"endTime": bson.M{"$gte": meet.StartTime},
},
bson.M{
"startTime": bson.M{"$lte": meet.EndTime},
"endTime": bson.M{"$gte": meet.EndTime},
},
},
},
}}
// To check participants with rspv yes in other meetings
matchingParticipant := bson.D{{
"$match", bson.M{
"participants.rsvp": bson.M{
"$in": bson.A{"Yes"},
},
"participants.email": bson.M{
"$in": emails,
},
},
}}
meetingsEx, err := router.Meeting.Aggregate(context.TODO(), mongo.Pipeline{participantUnwind, timeOverlap, matchingParticipant})
var meetings []bson.M
if err = meetingsEx.All(context.TODO(), &meetings); err != nil {
http.Error(w, "Server Error", http.StatusInternalServerError)
}
if len(meetings) != 0 {
json.NewEncoder(w).Encode("The meeting timing is overlapping with other meetings of participants")
return
}
_ , err = router.Meeting.InsertOne(context.TODO(), meet)
if err != nil {
log.Fatal(err)
return
}
json.NewEncoder(w).Encode(meet)
}
//*****************function to get meeting details by ID *****************************
func (router *RouteHandler) getMeetingByID(w http.ResponseWriter, r *http.Request) {
p := strings.Split(r.URL.Path, "/")
id := p[len(p)-1]
var meeting bson.M
err := router.Meeting.FindOne(context.TODO(), bson.D{{
"id", id,
}}).Decode(&meeting)
if err != nil {
log.Println(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(meeting)
}
func (router *RouteHandler) MeetingRoutes(w http.ResponseWriter, r *http.Request) {
p:=r.URL.Path
if(p=="/meetings"){
switch r.Method{
case "GET":
router.getMeeting(w,r)
case "POST":
router.scheduleMeeting(w,r)
default:
http.Error(w, "Method Not Found", http.StatusMethodNotAllowed)
}
} else{
switch r.Method {
case "GET":
router.getMeetingByID(w, r)
default:
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
}
}
|
package dto
type ToDoList struct {
Id int `json:"Id"`
Task string `json:"Task"`
Status bool `json:"Status"`
}
|
package notificationqueue_test
import (
"strconv"
"sync"
"testing"
"github.com/herb-go/notification"
)
type testDraft struct {
locker sync.Mutex
data []*notification.Notification
}
func (d *testDraft) Open() error {
return nil
}
func (d *testDraft) Close() error {
return nil
}
func (d *testDraft) Save(notification *notification.Notification) error {
locker.Lock()
defer locker.Unlock()
for k := range d.data {
if d.data[k].ID == notification.ID {
d.data[k] = notification
return nil
}
}
d.data = append(d.data, notification)
return nil
}
func (d *testDraft) List(condition []*notification.Condition, iter string, asc bool, count int) (result []*notification.Notification, newiter string, err error) {
locker.Lock()
defer locker.Unlock()
var start int
var step int
var end int
var batch = ""
for _, v := range condition {
if v.Keyword == notification.ConditionBatch {
batch = v.Value
} else {
return nil, "", notification.NewErrConditionNotSupported(v.Keyword)
}
}
if asc {
start = 0
step = 1
end = len(d.data)
} else {
start = len(d.data) - 1
step = -1
end = -1
}
result = []*notification.Notification{}
var i = start
iterpos, _ := strconv.Atoi(iter)
for {
var skiped bool
if iter != "" {
if asc {
if iterpos >= i {
skiped = true
}
} else {
if iterpos <= i {
skiped = true
}
}
}
if !skiped {
data := d.data[i]
if batch != "" {
if data.Header.Get(notification.HeaderNameBatch) == batch {
result = append(result, data)
}
} else {
result = append(result, data)
}
if count > 0 && len(result) == count {
return result, strconv.Itoa(i), nil
}
}
i = i + step
if i == end {
break
}
}
return result, "", nil
}
func (d *testDraft) Count(condition []*notification.Condition) (int, error) {
locker.Lock()
defer locker.Unlock()
var batch = ""
for _, v := range condition {
if v.Keyword == notification.ConditionBatch {
batch = v.Value
} else {
return 0, notification.NewErrConditionNotSupported(v.Keyword)
}
}
var count int
for k := range d.data {
if batch == "" {
count = count + 1
} else {
if d.data[k].Header.Get(notification.HeaderNameBatch) == batch {
count = count + 1
}
}
}
return count, nil
}
func (d *testDraft) SupportedConditions() ([]string, error) {
return []string{notification.ConditionBatch}, nil
}
func (d *testDraft) Remove(id string) (*notification.Notification, error) {
for k := range d.data {
if d.data[k].ID == id {
n := d.data[k]
d.data = append(d.data[:k], d.data[k:]...)
return n, nil
}
}
return nil, notification.NewErrNotificationIDNotFound(id)
}
func newTestDraft() *testDraft {
return &testDraft{}
}
func TestCondition(t *testing.T) {
var n *notification.Notification
initLog()
p := newTestPublisher()
err := p.Start()
if err != nil {
panic(err)
}
defer func() {
err := p.Stop()
if err != nil {
panic(err)
}
}()
n = notification.New()
n.Header.Set(notification.HeaderNameDraftMode, "1")
n.ID = mustID()
_, ok, err := p.PublishNotification(n)
if ok || err != nil {
t.Fatal(ok, err)
}
n = notification.New()
n.Header.Set(notification.HeaderNameDraftMode, "1")
n.Header.Set(notification.HeaderNameBatch, "12345")
n.ID = mustID()
_, ok, err = p.PublishNotification(n)
if ok || err != nil {
t.Fatal(ok, err)
}
n = notification.New()
n.Header.Set(notification.HeaderNameDraftMode, "1")
n.Header.Set(notification.HeaderNameBatch, "12345")
n.ID = mustID()
_, ok, err = p.PublishNotification(n)
if ok || err != nil {
t.Fatal(ok, err)
}
count, err := p.Draftbox.Count(nil)
if count != 3 || err != nil {
t.Fatal(count, err)
}
result, iter, err := p.Draftbox.List(nil, "", true, 0)
if len(result) != 3 || iter != "" || err != nil {
t.Fatal(result, iter, err)
}
result, iter, err = p.Draftbox.List(nil, "", true, 2)
if len(result) != 2 || iter != "1" || err != nil {
t.Fatal(result, iter, err)
}
result, iter, err = p.Draftbox.List(nil, "", false, 1)
if len(result) != 1 || iter != "2" || err != nil {
t.Fatal(result, iter, err)
}
result, iter, err = p.Draftbox.List(nil, "2", false, 1)
if len(result) != 1 || iter != "1" || err != nil {
t.Fatal(result, iter, err)
}
result, iter, err = p.Draftbox.List(nil, "1", false, 1)
if len(result) != 1 || iter != "0" || err != nil {
t.Fatal(result, iter, err)
}
result, iter, err = p.Draftbox.List(nil, "0", false, 1)
if len(result) != 0 || iter != "" || err != nil {
t.Fatal(result, iter, err)
}
cond := []*notification.Condition{¬ification.Condition{
Keyword: notification.ConditionBatch,
Value: "12345",
}}
count, err = p.Draftbox.Count(cond)
if count != 2 || err != nil {
t.Fatal(count, err)
}
result, iter, err = p.Draftbox.List(cond, "", true, 0)
if len(result) != 2 || iter != "" || err != nil {
t.Fatal(result, iter, err)
}
cond = []*notification.Condition{¬ification.Condition{
Keyword: notification.ConditionBatch,
Value: "notfound",
}}
count, err = p.Draftbox.Count(cond)
if count != 0 || err != nil {
t.Fatal(count, err)
}
result, iter, err = p.Draftbox.List(cond, "", true, 0)
if len(result) != 0 || iter != "" || err != nil {
t.Fatal(result, iter, err)
}
cond = []*notification.Condition{¬ification.Condition{
Keyword: "notfound",
Value: "notfound",
}}
count, err = p.Draftbox.Count(cond)
if !notification.IsErrConditionNotSupported(err) {
t.Fatal(result, iter, err)
}
result, iter, err = p.Draftbox.List(cond, "", true, 0)
if !notification.IsErrConditionNotSupported(err) {
t.Fatal(result, iter, err)
}
}
|
package tyVpnProtocol
import (
"github.com/tachyon-protocol/udw/udwErr"
"github.com/tachyon-protocol/udw/udwFile"
"github.com/tachyon-protocol/udw/udwRand"
"github.com/tachyon-protocol/udw/udwStrconv"
"strconv"
)
const Debug = false
const (
overheadEncrypt = 0
overheadVpnHeader = 1
overheadIpHeader = 20
overheadUdpHeader = 8
overheadTcpHeaderMax = 60
Mtu = 1460 - (overheadEncrypt + overheadVpnHeader + overheadIpHeader + overheadUdpHeader)
Mss = Mtu - (overheadTcpHeaderMax - overheadUdpHeader)
)
const VpnPort = 29444
const (
CmdData byte = 1
CmdForward byte = 2
CmdHandshake byte = 3
CmdPing byte = 4
CmdKeepAlive byte = 5
)
const PublicRouteServerAddr = "35.223.105.46:24587"
type VpnPacket struct {
Cmd byte
ClientIdSender uint64
ClientIdReceiver uint64
Data []byte
}
func (packet *VpnPacket) Reset() {
packet.Cmd = 0
packet.ClientIdSender = 0
packet.ClientIdReceiver = 0
packet.Data = packet.Data[:0]
}
func GetClientId(index int) uint64 {
clientIdPath := "/usr/local/etc/tachyonClientId" + strconv.Itoa(index)
var id uint64
udwErr.PanicToErrorMsgWithStackAndLog(func() {
b := udwFile.MustReadFile(clientIdPath)
id = udwStrconv.MustParseUint64(string(b))
})
if id == 0 {
id = udwRand.MustCryptoRandUint64()
udwFile.MustWriteFileWithMkdir(clientIdPath, []byte(udwStrconv.FormatUint64(id)))
}
return id
}
|
package main
import cgo_help_dir "go_demo/for_c_lang/cross_package/cgo_helper_dir"
//static const char* cs = "hello";
import "C"
func main() {
//运行将会报错,因为C.cs是*main.C.char,而方法接受*cgo_helper_dir.C.char
cgo_help_dir.PrintCString(C.cs)
}
|
package bufferpool
import (
"log"
"time"
"unsafe"
)
var gbp *bufferpool
var locker uint32
func init() {
gbp = New()
}
func Alloc(length int) []byte {
b, e := gbp.Alloc(length)
if e != nil {
log.Println(e)
}
return b
}
func Realloc(src []byte, length int) []byte {
dst := Alloc(length)
copy(dst, src)
Free(src)
return dst
}
func Free(buf []byte) {
gbp.Free(buf)
}
func AllocPointer(length int) unsafe.Pointer {
ptr, e := gbp.AllocPointer(length)
if e != nil {
log.Println(e)
}
return ptr
}
func FreePointer(ptr unsafe.Pointer) {
gbp.FreePointer(ptr)
}
func static() {
tick := time.NewTicker(time.Second)
for {
select {
case <-tick.C:
log.Println(3, gbp.memCap[3])
}
}
}
|
// Copyright 2018 The gVisor Authors.
//
// 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 syserr contains sandbox-internal errors. These errors are distinct
// from both the errors returned by host system calls and the errors returned
// to sandboxed applications.
package syserr
import (
"fmt"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/abi/linux/errno"
"gvisor.dev/gvisor/pkg/errors"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/safecopy"
)
// Error represents an internal error.
type Error struct {
// message is the human readable form of this Error.
message string
// noTranslation indicates that this Error cannot be translated to a
// errno.Errno.
noTranslation bool
// errno is the errno.Errno this Error should be translated to.
errno errno.Errno
}
// New creates a new Error and adds a translation for it.
//
// New must only be called at init.
func New(message string, linuxTranslation errno.Errno) *Error {
err := &Error{message: message, errno: linuxTranslation}
// TODO(b/34162363): Remove this.
if int(err.errno) >= len(linuxBackwardsTranslations) {
panic(fmt.Sprint("invalid errno: ", err.errno))
}
e := error(unix.Errno(err.errno))
// linuxerr.ErrWouldBlock gets translated to linuxerr.EWOULDBLOCK and
// enables proper blocking semantics. This should temporary address the
// class of blocking bugs that keep popping up with the current state of
// the error space.
if err.errno == linuxerr.EWOULDBLOCK.Errno() {
e = linuxerr.ErrWouldBlock
}
linuxBackwardsTranslations[err.errno] = linuxBackwardsTranslation{err: e, ok: true}
return err
}
// NewDynamic creates a new error with a dynamic error message and an errno
// translation.
//
// NewDynamic should only be used sparingly and not be used for static error
// messages. Errors with static error messages should be declared with New as
// global variables.
func NewDynamic(message string, linuxTranslation errno.Errno) *Error {
return &Error{message: message, errno: linuxTranslation}
}
func newWithHost(message string, linuxTranslation errno.Errno, hostErrno unix.Errno) *Error {
e := New(message, linuxTranslation)
addHostTranslation(hostErrno, e)
return e
}
// String implements fmt.Stringer.String.
func (e *Error) String() string {
if e == nil {
return "<nil>"
}
return e.message
}
type linuxBackwardsTranslation struct {
err error
ok bool
}
// TODO(b/34162363): Remove this.
var linuxBackwardsTranslations [maxErrno]linuxBackwardsTranslation
// ToError translates an Error to a corresponding error value.
//
// TODO(b/34162363): Remove this.
func (e *Error) ToError() error {
if e == nil {
return nil
}
if e.noTranslation {
panic(fmt.Sprintf("error %q does not support translation", e.message))
}
err := int(e.errno)
if err == errno.NOERRNO {
return nil
}
if err >= len(linuxBackwardsTranslations) || !linuxBackwardsTranslations[err].ok {
panic(fmt.Sprintf("unknown error %q (%d)", e.message, err))
}
return linuxBackwardsTranslations[err].err
}
// ToLinux converts the Error to a Linux ABI error that can be returned to the
// application.
func (e *Error) ToLinux() errno.Errno {
if e.noTranslation {
panic(fmt.Sprintf("No Linux ABI translation available for %q", e.message))
}
return e.errno
}
// TODO(b/34162363): Remove or replace most of these errors.
//
// Some of the errors should be replaced with package specific errors and
// others should be removed entirely.
//
// Note that some errors are declared in platform-specific files.
var (
ErrNotPermitted = newWithHost("operation not permitted", errno.EPERM, unix.EPERM)
ErrNoFileOrDir = newWithHost("no such file or directory", errno.ENOENT, unix.ENOENT)
ErrNoProcess = newWithHost("no such process", errno.ESRCH, unix.ESRCH)
ErrInterrupted = newWithHost("interrupted system call", errno.EINTR, unix.EINTR)
ErrIO = newWithHost("I/O error", errno.EIO, unix.EIO)
ErrDeviceOrAddress = newWithHost("no such device or address", errno.ENXIO, unix.ENXIO)
ErrTooManyArgs = newWithHost("argument list too long", errno.E2BIG, unix.E2BIG)
ErrEcec = newWithHost("exec format error", errno.ENOEXEC, unix.ENOEXEC)
ErrBadFD = newWithHost("bad file number", errno.EBADF, unix.EBADF)
ErrNoChild = newWithHost("no child processes", errno.ECHILD, unix.ECHILD)
ErrTryAgain = newWithHost("try again", errno.EAGAIN, unix.EAGAIN)
ErrNoMemory = newWithHost("out of memory", errno.ENOMEM, unix.ENOMEM)
ErrPermissionDenied = newWithHost("permission denied", errno.EACCES, unix.EACCES)
ErrBadAddress = newWithHost("bad address", errno.EFAULT, unix.EFAULT)
ErrNotBlockDevice = newWithHost("block device required", errno.ENOTBLK, unix.ENOTBLK)
ErrBusy = newWithHost("device or resource busy", errno.EBUSY, unix.EBUSY)
ErrExists = newWithHost("file exists", errno.EEXIST, unix.EEXIST)
ErrCrossDeviceLink = newWithHost("cross-device link", errno.EXDEV, unix.EXDEV)
ErrNoDevice = newWithHost("no such device", errno.ENODEV, unix.ENODEV)
ErrNotDir = newWithHost("not a directory", errno.ENOTDIR, unix.ENOTDIR)
ErrIsDir = newWithHost("is a directory", errno.EISDIR, unix.EISDIR)
ErrInvalidArgument = newWithHost("invalid argument", errno.EINVAL, unix.EINVAL)
ErrFileTableOverflow = newWithHost("file table overflow", errno.ENFILE, unix.ENFILE)
ErrTooManyOpenFiles = newWithHost("too many open files", errno.EMFILE, unix.EMFILE)
ErrNotTTY = newWithHost("not a typewriter", errno.ENOTTY, unix.ENOTTY)
ErrTestFileBusy = newWithHost("text file busy", errno.ETXTBSY, unix.ETXTBSY)
ErrFileTooBig = newWithHost("file too large", errno.EFBIG, unix.EFBIG)
ErrNoSpace = newWithHost("no space left on device", errno.ENOSPC, unix.ENOSPC)
ErrIllegalSeek = newWithHost("illegal seek", errno.ESPIPE, unix.ESPIPE)
ErrReadOnlyFS = newWithHost("read-only file system", errno.EROFS, unix.EROFS)
ErrTooManyLinks = newWithHost("too many links", errno.EMLINK, unix.EMLINK)
ErrBrokenPipe = newWithHost("broken pipe", errno.EPIPE, unix.EPIPE)
ErrDomain = newWithHost("math argument out of domain of func", errno.EDOM, unix.EDOM)
ErrRange = newWithHost("math result not representable", errno.ERANGE, unix.ERANGE)
ErrNameTooLong = newWithHost("file name too long", errno.ENAMETOOLONG, unix.ENAMETOOLONG)
ErrNoLocksAvailable = newWithHost("no record locks available", errno.ENOLCK, unix.ENOLCK)
ErrInvalidSyscall = newWithHost("invalid system call number", errno.ENOSYS, unix.ENOSYS)
ErrDirNotEmpty = newWithHost("directory not empty", errno.ENOTEMPTY, unix.ENOTEMPTY)
ErrLinkLoop = newWithHost("too many symbolic links encountered", errno.ELOOP, unix.ELOOP)
ErrNoMessage = newWithHost("no message of desired type", errno.ENOMSG, unix.ENOMSG)
ErrIdentifierRemoved = newWithHost("identifier removed", errno.EIDRM, unix.EIDRM)
ErrNotStream = newWithHost("device not a stream", errno.ENOSTR, unix.ENOSTR)
ErrNoDataAvailable = newWithHost("no data available", errno.ENODATA, unix.ENODATA)
ErrTimerExpired = newWithHost("timer expired", errno.ETIME, unix.ETIME)
ErrStreamsResourceDepleted = newWithHost("out of streams resources", errno.ENOSR, unix.ENOSR)
ErrIsRemote = newWithHost("object is remote", errno.EREMOTE, unix.EREMOTE)
ErrNoLink = newWithHost("link has been severed", errno.ENOLINK, unix.ENOLINK)
ErrProtocol = newWithHost("protocol error", errno.EPROTO, unix.EPROTO)
ErrMultihopAttempted = newWithHost("multihop attempted", errno.EMULTIHOP, unix.EMULTIHOP)
ErrInvalidDataMessage = newWithHost("not a data message", errno.EBADMSG, unix.EBADMSG)
ErrOverflow = newWithHost("value too large for defined data type", errno.EOVERFLOW, unix.EOVERFLOW)
ErrIllegalByteSequence = newWithHost("illegal byte sequence", errno.EILSEQ, unix.EILSEQ)
ErrTooManyUsers = newWithHost("too many users", errno.EUSERS, unix.EUSERS)
ErrNotASocket = newWithHost("socket operation on non-socket", errno.ENOTSOCK, unix.ENOTSOCK)
ErrDestinationAddressRequired = newWithHost("destination address required", errno.EDESTADDRREQ, unix.EDESTADDRREQ)
ErrMessageTooLong = newWithHost("message too long", errno.EMSGSIZE, unix.EMSGSIZE)
ErrWrongProtocolForSocket = newWithHost("protocol wrong type for socket", errno.EPROTOTYPE, unix.EPROTOTYPE)
ErrProtocolNotAvailable = newWithHost("protocol not available", errno.ENOPROTOOPT, unix.ENOPROTOOPT)
ErrProtocolNotSupported = newWithHost("protocol not supported", errno.EPROTONOSUPPORT, unix.EPROTONOSUPPORT)
ErrSocketNotSupported = newWithHost("socket type not supported", errno.ESOCKTNOSUPPORT, unix.ESOCKTNOSUPPORT)
ErrEndpointOperation = newWithHost("operation not supported on transport endpoint", errno.EOPNOTSUPP, unix.EOPNOTSUPP)
ErrProtocolFamilyNotSupported = newWithHost("protocol family not supported", errno.EPFNOSUPPORT, unix.EPFNOSUPPORT)
ErrAddressFamilyNotSupported = newWithHost("address family not supported by protocol", errno.EAFNOSUPPORT, unix.EAFNOSUPPORT)
ErrAddressInUse = newWithHost("address already in use", errno.EADDRINUSE, unix.EADDRINUSE)
ErrAddressNotAvailable = newWithHost("cannot assign requested address", errno.EADDRNOTAVAIL, unix.EADDRNOTAVAIL)
ErrNetworkDown = newWithHost("network is down", errno.ENETDOWN, unix.ENETDOWN)
ErrNetworkUnreachable = newWithHost("network is unreachable", errno.ENETUNREACH, unix.ENETUNREACH)
ErrNetworkReset = newWithHost("network dropped connection because of reset", errno.ENETRESET, unix.ENETRESET)
ErrConnectionAborted = newWithHost("software caused connection abort", errno.ECONNABORTED, unix.ECONNABORTED)
ErrConnectionReset = newWithHost("connection reset by peer", errno.ECONNRESET, unix.ECONNRESET)
ErrNoBufferSpace = newWithHost("no buffer space available", errno.ENOBUFS, unix.ENOBUFS)
ErrAlreadyConnected = newWithHost("transport endpoint is already connected", errno.EISCONN, unix.EISCONN)
ErrNotConnected = newWithHost("transport endpoint is not connected", errno.ENOTCONN, unix.ENOTCONN)
ErrShutdown = newWithHost("cannot send after transport endpoint shutdown", errno.ESHUTDOWN, unix.ESHUTDOWN)
ErrTooManyRefs = newWithHost("too many references: cannot splice", errno.ETOOMANYREFS, unix.ETOOMANYREFS)
ErrTimedOut = newWithHost("connection timed out", errno.ETIMEDOUT, unix.ETIMEDOUT)
ErrConnectionRefused = newWithHost("connection refused", errno.ECONNREFUSED, unix.ECONNREFUSED)
ErrHostDown = newWithHost("host is down", errno.EHOSTDOWN, unix.EHOSTDOWN)
ErrHostUnreachable = newWithHost("no route to host", errno.EHOSTUNREACH, unix.EHOSTUNREACH)
ErrAlreadyInProgress = newWithHost("operation already in progress", errno.EALREADY, unix.EALREADY)
ErrInProgress = newWithHost("operation now in progress", errno.EINPROGRESS, unix.EINPROGRESS)
ErrStaleFileHandle = newWithHost("stale file handle", errno.ESTALE, unix.ESTALE)
ErrQuotaExceeded = newWithHost("quota exceeded", errno.EDQUOT, unix.EDQUOT)
ErrCanceled = newWithHost("operation canceled", errno.ECANCELED, unix.ECANCELED)
ErrOwnerDied = newWithHost("owner died", errno.EOWNERDEAD, unix.EOWNERDEAD)
ErrNotRecoverable = newWithHost("state not recoverable", errno.ENOTRECOVERABLE, unix.ENOTRECOVERABLE)
// ErrWouldBlock translates to EWOULDBLOCK which is the same as EAGAIN
// on Linux.
ErrWouldBlock = New("operation would block", errno.EWOULDBLOCK)
)
// FromError converts a generic error to an *Error.
//
// TODO(b/34162363): Remove this function.
func FromError(err error) *Error {
if err == nil {
return nil
}
switch e := err.(type) {
case unix.Errno:
return FromHost(e)
case *errors.Error:
return FromHost(unix.Errno(e.Errno()))
case safecopy.SegvError, safecopy.BusError, safecopy.AlignmentError:
return FromHost(unix.EFAULT)
}
msg := fmt.Sprintf("err: %s type: %T", err.Error(), err)
panic(msg)
}
|
package geoip2
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
backoff "github.com/cenkalti/backoff/v4"
geoip2_golang "github.com/oschwald/geoip2-golang"
maxminddb "github.com/oschwald/maxminddb-golang"
)
type fileReader struct {
*geoip2_golang.Reader
}
type downloadReader struct {
sync.RWMutex
db *geoip2_golang.Reader
cfg *downloadConfig
runDownloadClose chan bool
backoff *backoff.ExponentialBackOff
}
// ASN is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) ASN(ipAddress net.IP) (*geoip2_golang.ASN, error) {
r.RLock()
defer r.RUnlock()
return r.db.ASN(ipAddress)
}
// AnonymousIP is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) AnonymousIP(ipAddress net.IP) (*geoip2_golang.AnonymousIP, error) {
r.RLock()
defer r.RUnlock()
return r.db.AnonymousIP(ipAddress)
}
// City is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) City(ipAddress net.IP) (*geoip2_golang.City, error) {
r.RLock()
defer r.RUnlock()
return r.db.City(ipAddress)
}
// ConnectionType is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) ConnectionType(ipAddress net.IP) (*geoip2_golang.ConnectionType, error) {
r.RLock()
defer r.RUnlock()
return r.db.ConnectionType(ipAddress)
}
// Country is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) Country(ipAddress net.IP) (*geoip2_golang.Country, error) {
r.RLock()
defer r.RUnlock()
return r.db.Country(ipAddress)
}
// Domain is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) Domain(ipAddress net.IP) (*geoip2_golang.Domain, error) {
r.RLock()
defer r.RUnlock()
return r.db.Domain(ipAddress)
}
// Enterprise is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) Enterprise(ipAddress net.IP) (*geoip2_golang.Enterprise, error) {
r.RLock()
defer r.RUnlock()
return r.db.Enterprise(ipAddress)
}
// ISP is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) ISP(ipAddress net.IP) (*geoip2_golang.ISP, error) {
r.RLock()
defer r.RUnlock()
return r.db.ISP(ipAddress)
}
// Metadata is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) Metadata() maxminddb.Metadata {
r.RLock()
defer r.RUnlock()
return r.db.Metadata()
}
// Close is the same method as that "github.com/oschwald/geoip2-golang" is.
func (r *downloadReader) Close() error {
r.Lock()
defer r.Unlock()
close(r.runDownloadClose)
return r.db.Close()
}
func (r *downloadReader) runDownloadURL() {
for {
// getting checksum
var remoteChecksum string
for i := 0; i < r.cfg.retries; i++ {
// wait for backoff interval.
time.Sleep(r.backoff.NextBackOff())
c, err := r.downloadChecksum()
if err != nil {
r.cfg.errorFunc(fmt.Errorf("[err] runDownloadURL %w", err))
continue
}
remoteChecksum = strings.TrimSpace(c)
}
// reset backoff.
r.backoff.Reset()
if remoteChecksum == "" {
r.cfg.errorFunc(fmt.Errorf("[err] runDownloadURL checksum download fail"))
} else {
// if local checksum is equal to remote checksum, updating maxmind database.
if remoteChecksum != r.cfg.checksum {
for i := 0; i < r.cfg.retries; i++ {
// wait for backoff interval.
time.Sleep(r.backoff.NextBackOff())
// downloading database.
tempPath, err := r.downloadDatabase()
if err != nil {
r.cfg.errorFunc(fmt.Errorf("[err] runDownloadURL %w", err))
continue
}
// reload new database.
if err := r.databaseReload(tempPath, remoteChecksum); err != nil {
r.cfg.errorFunc(fmt.Errorf("[err] runDownloadURL %w", err))
continue
}
// call a success function.
r.cfg.successFunc()
break
}
// reset backoff.
r.backoff.Reset()
} else {
fmt.Println("[pass][geoip2] remote-checksum equals local-checksum.")
}
}
select {
case <-r.runDownloadClose:
return
case <-time.After(r.cfg.updateInterval):
}
}
}
// databaseReload reloads maxmind database.
func (r *downloadReader) databaseReload(tempPath, checksum string) error {
if tempPath == "" {
return fmt.Errorf("[err] databaseReload %w", ErrInvalidParameters)
}
if _, err := os.Stat(tempPath); os.IsNotExist(err) {
return fmt.Errorf("[err] databaseReload %w", ErrNotFoundDatabase)
}
r.Lock()
defer r.Unlock()
// make directory.
if _, err := os.Stat(r.cfg.storeDir); os.IsNotExist(err) {
if err := os.MkdirAll(r.cfg.storeDir, os.ModePerm); err != nil {
return fmt.Errorf("[err] databaseReload %w", err)
}
}
// backup old database.
dbpath := r.cfg.dbPath()
dbBackupPath := r.cfg.dbBackupPath()
checksumPath := r.cfg.checksumPath()
if info, err := os.Stat(dbpath); info != nil || os.IsExist(err) {
if dbpath != tempPath {
// make backup old database
os.Rename(dbpath, dbBackupPath)
}
}
// move tempPath to dbpath.
if err := os.Rename(tempPath, dbpath); err != nil {
// delete new database
os.RemoveAll(tempPath)
// rollback old database
os.Rename(dbBackupPath, dbpath)
return fmt.Errorf("[err] databaseReload %w", err)
}
// open new database.
db, err := geoip2_golang.Open(dbpath)
if err != nil {
// delete new database
os.RemoveAll(dbpath)
// rollback old database
os.Rename(dbBackupPath, dbpath)
return fmt.Errorf("[err] databaseReload %w", err)
}
// delete back old database
if info, err := os.Stat(dbBackupPath); info != nil || os.IsExist(err) {
os.RemoveAll(dbBackupPath)
}
// release old database
if r.db != nil {
if err := r.db.Close(); err != nil {
fmt.Printf("[err] databaseReload old database close %v", err)
}
r.db = nil
r.cfg.checksum = ""
}
if checksum == "" {
// read md5 file.
if bys, err := ioutil.ReadFile(checksumPath); err == nil {
checksum = string(bys)
}
} else {
// write md5 to file.
if cpath, err := os.Create(r.cfg.checksumPath()); err == nil {
cpath.WriteString(checksum)
cpath.Close()
}
}
r.db = db
r.cfg.checksum = checksum
return nil
}
// requestChecksum requests checksum data.
func (r *downloadReader) downloadChecksum() (checksum string, err error) {
resp, suberr := http.Get(r.cfg.checksumURL)
if resp != nil {
defer resp.Body.Close()
} else {
err = fmt.Errorf("[err] downloadChecksum resp nil")
return
}
if suberr != nil {
err = fmt.Errorf("[err] downloadChecksum %w", suberr)
return
}
status := resp.StatusCode
if resp.StatusCode/100 != 2 {
err = fmt.Errorf("[err] downloadChecksum status %d", status)
return
}
data, suberr := ioutil.ReadAll(resp.Body)
if suberr != nil {
err = fmt.Errorf("[err] downloadChecksum status %w", suberr)
return
}
checksum = string(data)
return
}
// request requests checksum data.
func (r *downloadReader) downloadDatabase() (tempPath string, err error) {
// download database
resp, suberr := http.Get(r.cfg.downloadURL)
if resp != nil {
defer resp.Body.Close()
} else {
err = fmt.Errorf("[err] downloadDatabase resp nil")
return
}
if suberr != nil {
err = fmt.Errorf("[err] downloadDatabase %w", suberr)
return
}
status := resp.StatusCode
if resp.StatusCode/100 != 2 {
err = fmt.Errorf("[err] downloadDatabase status %d", status)
return
}
// save database to temporary path
fpath := filepath.Join(os.TempDir(), fmt.Sprintf("maxmind-%d.mmdb", time.Now().UnixNano()))
f, suberr := os.Create(fpath)
if suberr != nil {
err = fmt.Errorf("[err] downloadDatabase %w", suberr)
return
}
defer f.Close()
// wrapping unzip reader
gr, suberr := gzip.NewReader(resp.Body)
if suberr != nil {
err = fmt.Errorf("[err] downloadDatabase %w", suberr)
return
}
defer gr.Close()
// wrapping tar reader
tr := tar.NewReader(gr)
Search:
for {
header, suberr := tr.Next()
// check error
switch {
case suberr == io.EOF:
err = fmt.Errorf("[err] downloadDatabase not found mmdb in gzip.")
return
case suberr != nil:
err = fmt.Errorf("[err] downloadDatabase read gzip %w", suberr)
return
case header == nil:
continue
}
// search mmdb
switch header.Typeflag {
case tar.TypeReg:
if strings.HasSuffix(strings.ToLower(header.Name), "mmdb") {
if _, suberr := io.Copy(f, gr); suberr != nil {
err = fmt.Errorf("[err] downloadDatabase read gzip %w", suberr)
return
}
break Search
}
}
}
tempPath = fpath
return
}
|
//table 映射器
package service
import (
"dc/models"
"github.com/mitchellh/mapstructure"
)
//table - model的映射
var TableBindToModel = map[string]func(args Args)interface{}{
tablePrefix+"thread": BindThread,
tablePrefix+"thread_roadbook": BindThreadRoadbook,
tablePrefix+"2handcar_apply": Bind2handcarApply,
tablePrefix+"2handcar_booth":Bind2handcarBooth,
tablePrefix+"2handcar_complain":Bind2handcarComplain,
tablePrefix+"2handcar_config":Bind2handcarConfig,
tablePrefix+"2handcar_debit_list":Bind2handcarDebitList,
tablePrefix+"2handcar_intention":Bind2handcarIntention,
tablePrefix+"2handcar_list":Bind2handcarList,
tablePrefix+"2handcar_order":Bind2handcarOrder,
tablePrefix+"2handcar_park":Bind2handcarPark,
tablePrefix+"2handcar_park_time":Bind2handcarParkTime,
tablePrefix+"2handcar_park_type":Bind2handcarParkType,
tablePrefix+"2handcar_plan":Bind2handcarPlan,
tablePrefix+"2handcar_time":Bind2handcarTime,
tablePrefix+"2handcar_wx_fail":Bind2handcarWxFail,
tablePrefix+"account_manage":BindAccountManage,
tablePrefix+"action_log":BindActionLog,
tablePrefix+"activity_area":BindActivityArea,
tablePrefix+"activity_forward":BindActivityForward,
tablePrefix+"activity_forward_content":BindActivityForwardContent,
tablePrefix+"activity_forward_prize":BindActivityForwardPrize,
tablePrefix+"activity_forward_record":BindActivityForwardRecord,
tablePrefix+"activity_forward_record_details":BindActivityForwardRecordDetails,
tablePrefix+"activity_line":BindActivityLine,
tablePrefix+"activity_line_node_related":BindActivityLineNodeRelated,
tablePrefix+"activity_lottery_attendance":BindActivityLotteryAttendance,
tablePrefix+"activity_lottery_auth":BindActivityLotteryAuth,
tablePrefix+"activity_lottery_code":BindActivityLotteryCode,
tablePrefix+"activity_lottery_prize":BindActivityLotteryPrize,
tablePrefix+"activity_lottery_rotary":BindActivityLotteryRotary,
tablePrefix+"activity_lottery_sms":BindActivityLotterySms,
tablePrefix+"activity_lottery_status":BindActivityLotteryStatus,
tablePrefix+"activity_table":BindActivityTable,
tablePrefix+"activity_tags":BindActivityTags,
tablePrefix+"activity_turntable":BindActivityTurntable,
tablePrefix+"activity_turntable_content":BindActivityTurntableContent,
tablePrefix+"activity_turntable_prize":BindActivityTurntablePrize,
tablePrefix+"activity_turntable_qrcodetag":BindActivityTurntableQrcodetag,
tablePrefix+"activity_turntable_record":BindActivityTurntableRecord,
tablePrefix+"activity_turntable_result":BindActivityTurntableResult,
tablePrefix+"activity_turntable_saddress":BindActivityTurntableSaddress,
tablePrefix+"activity_turntable_share":BindActivityTurntableShare,
tablePrefix+"activity_turntable_user":BindActivityTurntableUser,
tablePrefix+"activity_vote_refer_opt":BindActivityVoteReferOpt,
tablePrefix+"activity_vote_rules":BindActivityVoteRules,
tablePrefix+"activity_vote_user_limit":BindActivityVoteUserLimit,
tablePrefix+"activity_vote_user_table":BindActivityVoteUserTable,
tablePrefix+"activity_vote_user_ticketcert":BindActivityVoteUserTicketcert,
tablePrefix+"admin_auth_project_xc":BindAdminAuthProjectXc,
tablePrefix+"admin_auth_project_xc_copy":BindAdminAuthProjectXcCopy,
tablePrefix+"admin_auth_user":BindAdminAuthUser,
tablePrefix+"admin_auth_user_copy":BindAdminAuthUserCopy,
tablePrefix+"admin_menu":BindAdminMenu,
tablePrefix+"admin_report":BindAdminReport,
tablePrefix+"admin_role":BindAdminRole,
tablePrefix+"admin_user":BindAdminUser,
tablePrefix+"admin_user2area":BindAdminUser2area,
tablePrefix+"admin_user2area_org":BindAdminUser2areaOrg,
tablePrefix+"admin_user2org":BindAdminUser2org,
tablePrefix+"admin_user2org_copy":BindAdminUser2orgCopy,
tablePrefix+"admin_user2org_setting":BindAdminUser2orgSetting,
tablePrefix+"admin_user_alltags":BindAdminUserAlltags,
tablePrefix+"admin_user_auth":BindAdminUserAuth,
tablePrefix+"admin_user_auth_copy":BindAdminUserAuthCopy,
tablePrefix+"admin_user_avatar":BindAdminUserAvatar,
tablePrefix+"admin_user_copy1":BindAdminUserCopy1,
tablePrefix+"admin_user_department":BindAdminUserDepartment,
tablePrefix+"admin_user_doyen":BindAdminUserDoyen,
tablePrefix+"admin_user_favor":BindAdminUserFavor,
tablePrefix+"admin_user_impression":BindAdminUserImpression,
tablePrefix+"admin_user_lock":BindAdminUserLock,
tablePrefix+"admin_user_login_fail":BindAdminUserLoginFail,
tablePrefix+"admin_user_money":BindAdminUserMoney,
tablePrefix+"admin_user_money_bill":BindAdminUserMoneyBill,
tablePrefix+"admin_user_money_recharge":BindAdminUserMoneyRecharge,
tablePrefix+"admin_user_money_withdraw":BindAdminUserMoneyWithdraw,
tablePrefix+"admin_user_org":BindAdminUserOrg,
tablePrefix+"admin_user_position":BindAdminUserPosition,
tablePrefix+"admin_user_punish":BindAdminUserPunish,
tablePrefix+"admin_user_real_name_auth":BindAdminUserRealNameAuth,
tablePrefix+"admin_user_role":BindAdminUserRole,
tablePrefix+"admin_user_tags":BindAdminUserTags,
tablePrefix+"admin_user_type":BindAdminUserType,
tablePrefix+"advertisement_admin_log":BindAdvertisementAdminLog,
tablePrefix+"advertisement_content":BindAdvertisementContent,
tablePrefix+"advertisement_org_strategy":BindAdvertisementOrgStrategy,
tablePrefix+"advertisement_position":BindAdvertisementPosition,
tablePrefix+"agreement":BindAgreement,
tablePrefix+"agreement_place":BindAgreementPlace,
tablePrefix+"album":BindAlbum,
tablePrefix+"alltags":BindAlltags,
tablePrefix+"alltags_article":BindAlltagsArticle,
tablePrefix+"alltags_category":BindAlltagsCategory,
tablePrefix+"alltags_category_activity":BindAlltagsCategoryActivity,
tablePrefix+"area":BindArea,
tablePrefix+"area_bak":BindAreaBak,
tablePrefix+"area_hot":BindAreaHot,
tablePrefix+"article":BindArticle,
tablePrefix+"article_category":BindArticleCategory,
tablePrefix+"article_data":BindArticleData,
tablePrefix+"article_tag":BindArticleTag,
tablePrefix+"ask_cate":BindAskCate,
tablePrefix+"ask_expert":BindAskExpert,
tablePrefix+"async_task":BindAsyncTask,
tablePrefix+"attachment":BindAttachment,
tablePrefix+"auth_action":BindAuthAction,
tablePrefix+"auth_role":BindAuthRole,
tablePrefix+"auth_role_action":BindAuthRoleAction,
tablePrefix+"auth_role_source":BindAuthRoleSource,
tablePrefix+"auth_user_role":BindAuthUserRole,
tablePrefix+"baidu_config":BindBaiduConfig,
tablePrefix+"baidu_notice":BindBaiduNotice,
tablePrefix+"baidu_share":BindBaiduShare,
tablePrefix+"benefit":BindBenefit,
tablePrefix+"benefit_access":BindBenefitAccess,
tablePrefix+"benefit_store":BindBenefitStore,
tablePrefix+"bid_keyword":BindBidKeyword,
tablePrefix+"bid_keyword_copy":BindBidKeywordCopy,
tablePrefix+"brand":BindBrand,
tablePrefix+"browse_history":BindBrowseHistory,
tablePrefix+"call_audience":BindCallAudience,
tablePrefix+"call_audience_access":BindCallAudienceAccess,
tablePrefix+"call_audience_conf":BindCallAudienceConf,
tablePrefix+"call_audience_conf_val":BindCallAudienceConfVal,
tablePrefix+"call_audience_review":BindCallAudienceReview,
tablePrefix+"call_audience_review_log":BindCallAudienceReviewLog,
tablePrefix+"call_audience_smstask":BindCallAudienceSmstask,
tablePrefix+"call_audience_smstask_content":BindCallAudienceSmstaskContent,
tablePrefix+"call_audience_smstask_record":BindCallAudienceSmstaskRecord,
tablePrefix+"call_audience_user":BindCallAudienceUser,
tablePrefix+"call_audience_visit":BindCallAudienceVisit,
tablePrefix+"call_datatype":BindCallDatatype,
tablePrefix+"call_draw":BindCallDraw,
tablePrefix+"call_event_auth":BindCallEventAuth,
tablePrefix+"call_privacy":BindCallPrivacy,
tablePrefix+"call_questionnaire":BindCallQuestionnaire,
tablePrefix+"call_questionnaire_conf":BindCallQuestionnaireConf,
tablePrefix+"call_questionnaire_user":BindCallQuestionnaireUser,
tablePrefix+"call_questionnaire_val":BindCallQuestionnaireVal,
tablePrefix+"call_record":BindCallRecord,
tablePrefix+"call_user_auth":BindCallUserAuth,
tablePrefix+"car":BindCar,
tablePrefix+"car2conf":BindCar2conf,
tablePrefix+"car_color":BindCarColor,
tablePrefix+"car_conf":BindCarConf,
tablePrefix+"car_conf_val":BindCarConfVal,
tablePrefix+"car_copy":BindCarCopy,
tablePrefix+"car_custom_made":BindCarCustomMade,
tablePrefix+"car_find":BindCarFind,
tablePrefix+"car_love":BindCarLove,
tablePrefix+"car_order":BindCarOrder,
tablePrefix+"car_order_config":BindCarOrderConfig,
tablePrefix+"car_order_list":BindCarOrderList,
tablePrefix+"car_order_msg":BindCarOrderMsg,
tablePrefix+"car_order_offer":BindCarOrderOffer,
tablePrefix+"car_order_offer_count":BindCarOrderOfferCount,
tablePrefix+"car_order_push_list":BindCarOrderPushList,
tablePrefix+"car_order_tags":BindCarOrderTags,
tablePrefix+"car_pic":BindCarPic,
tablePrefix+"car_search_log":BindCarSearchLog,
tablePrefix+"car_series":BindCarSeries,
tablePrefix+"car_series_color":BindCarSeriesColor,
tablePrefix+"carorder":BindCarorder,
tablePrefix+"carorder_config":BindCarorderConfig,
tablePrefix+"carorder_list":BindCarorderList,
tablePrefix+"carorder_lovecar":BindCarorderLovecar,
tablePrefix+"carorder_offer":BindCarorderOffer,
tablePrefix+"carorder_offer_record":BindCarorderOfferRecord,
tablePrefix+"carorder_push_list":BindCarorderPushList,
tablePrefix+"carorder_record":BindCarorderRecord,
tablePrefix+"carorder_tactics":BindCarorderTactics,
tablePrefix+"carorder_tactics_config":BindCarorderTacticsConfig,
tablePrefix+"carorder_tactics_gift":BindCarorderTacticsGift,
tablePrefix+"carorder_tactics_record":BindCarorderTacticsRecord,
tablePrefix+"carousel":BindCarousel,
tablePrefix+"carousel_item":BindCarouselItem,
tablePrefix+"carousel_object":BindCarouselObject,
tablePrefix+"carousel_org_plan":BindCarouselOrgPlan,
tablePrefix+"carousel_org_right":BindCarouselOrgRight,
tablePrefix+"carousel_originality":BindCarouselOriginality,
tablePrefix+"carousel_scheduling":BindCarouselScheduling,
tablePrefix+"carousel_scheduling_authorize":BindCarouselSchedulingAuthorize,
tablePrefix+"carousel_strategy":BindCarouselStrategy,
tablePrefix+"carousel_subject_item":BindCarouselSubjectItem,
tablePrefix+"cert":BindCert,
tablePrefix+"cert_apply":BindCertApply,
tablePrefix+"cert_content":BindCertContent,
tablePrefix+"cert_handout":BindCertHandout,
tablePrefix+"cert_nums_record":BindCertNumsRecord,
tablePrefix+"cert_user":BindCertUser,
tablePrefix+"cert_user_copy":BindCertUserCopy,
tablePrefix+"cert_user_record":BindCertUserRecord,
tablePrefix+"cert_user_record_act":BindCertUserRecordAct,
tablePrefix+"chicken_soup":BindChickenSoup,
tablePrefix+"collect":BindCollect,
tablePrefix+"collect_mapping":BindCollectMapping,
tablePrefix+"comment":BindComment,
tablePrefix+"comment_log":BindCommentLog,
tablePrefix+"config":BindConfig,
tablePrefix+"country":BindCountry,
tablePrefix+"coupon":BindCoupon,
tablePrefix+"coupon_car":BindCouponCar,
tablePrefix+"coupon_category":BindCouponCategory,
tablePrefix+"coupon_check":BindCouponCheck,
tablePrefix+"coupon_code":BindCouponCode,
tablePrefix+"coupon_dealers":BindCouponDealers,
tablePrefix+"coupon_distribute":BindCouponDistribute,
tablePrefix+"coupon_distribute_list":BindCouponDistributeList,
tablePrefix+"coupon_distribute_list_reissue":BindCouponDistributeListReissue,
tablePrefix+"coupon_distribute_reissue":BindCouponDistributeReissue,
tablePrefix+"coupon_issue":BindCouponIssue,
tablePrefix+"coupon_order":BindCouponOrder,
tablePrefix+"coupon_push":BindCouponPush,
tablePrefix+"coupon_push_log":BindCouponPushLog,
tablePrefix+"coupon_refund":BindCouponRefund,
tablePrefix+"coupon_replace":BindCouponReplace,
tablePrefix+"coupon_replace_distribute":BindCouponReplaceDistribute,
tablePrefix+"coupon_replace_reissue":BindCouponReplaceReissue,
tablePrefix+"coupon_share_log":BindCouponShareLog,
tablePrefix+"coupon_ticket":BindCouponTicket,
tablePrefix+"coupon_warehouse":BindCouponWarehouse,
tablePrefix+"coupon_warehouse_code":BindCouponWarehouseCode,
tablePrefix+"crawler_data":BindCrawlerData,
tablePrefix+"danger":BindDanger,
tablePrefix+"dshow_banner":BindDshowBanner,
tablePrefix+"dshow_base":BindDshowBase,
tablePrefix+"dshow_gift":BindDshowGift,
tablePrefix+"dshow_share":BindDshowShare,
tablePrefix+"dshow_text":BindDshowText,
tablePrefix+"easemob_messages":BindEasemobMessages,
tablePrefix+"easemob_messages_num":BindEasemobMessagesNum,
tablePrefix+"easemob_messages_payload":BindEasemobMessagesPayload,
tablePrefix+"emoji":BindEmoji,
tablePrefix+"emoji_group":BindEmojiGroup,
tablePrefix+"emoji_user_access":BindEmojiUserAccess,
tablePrefix+"entrance_way":BindEntranceWay,
tablePrefix+"event":BindEvent,
tablePrefix+"event_activity":BindEventActivity,
tablePrefix+"event_activity_data":BindEventActivityData,
tablePrefix+"event_ad":BindEventAd,
tablePrefix+"event_bdconfig":BindEventBdconfig,
tablePrefix+"event_booth":BindEventBooth,
tablePrefix+"event_brand":BindEventBrand,
tablePrefix+"event_brand_merge":BindEventBrandMerge,
tablePrefix+"event_business":BindEventBusiness,
tablePrefix+"event_desc_img":BindEventDescImg,
tablePrefix+"event_examine":BindEventExamine,
tablePrefix+"event_guest":BindEventGuest,
tablePrefix+"event_hall":BindEventHall,
tablePrefix+"event_img_config":BindEventImgConfig,
tablePrefix+"event_img_unshow":BindEventImgUnshow,
tablePrefix+"event_information":BindEventInformation,
tablePrefix+"event_model":BindEventModel,
tablePrefix+"event_navigation":BindEventNavigation,
tablePrefix+"event_navigation_conf":BindEventNavigationConf,
tablePrefix+"event_newcar":BindEventNewcar,
tablePrefix+"event_schedule":BindEventSchedule,
tablePrefix+"event_showcar":BindEventShowcar,
tablePrefix+"event_staff":BindEventStaff,
tablePrefix+"event_staff_auth":BindEventStaffAuth,
tablePrefix+"event_staff_auth_area":BindEventStaffAuthArea,
tablePrefix+"event_staff_auth_brand":BindEventStaffAuthBrand,
tablePrefix+"event_staff_auth_user":BindEventStaffAuthUser,
tablePrefix+"event_user":BindEventUser,
tablePrefix+"fab":BindFab,
tablePrefix+"factory":BindFactory,
tablePrefix+"failed_jobs":BindFailedJobs,
tablePrefix+"feedback":BindFeedback,
tablePrefix+"feeds_ignore":BindFeedsIgnore,
tablePrefix+"feeds_topic":BindFeedsTopic,
tablePrefix+"feeds_user":BindFeedsUser,
tablePrefix+"follow_group":BindFollowGroup,
tablePrefix+"friend":BindFriend,
tablePrefix+"friend_buyinfo":BindFriendBuyinfo,
tablePrefix+"friend_group":BindFriendGroup,
tablePrefix+"friend_group_access":BindFriendGroupAccess,
tablePrefix+"friend_latent":BindFriendLatent,
tablePrefix+"friend_manage_log":BindFriendManageLog,
tablePrefix+"friend_org":BindFriendOrg,
tablePrefix+"gallery":BindGallery,
tablePrefix+"group":BindGroup,
tablePrefix+"group_authentication":BindGroupAuthentication,
tablePrefix+"group_blacklist":BindGroupBlacklist,
tablePrefix+"group_category":BindGroupCategory,
tablePrefix+"group_invitation":BindGroupInvitation,
tablePrefix+"group_notification":BindGroupNotification,
tablePrefix+"group_notification_read":BindGroupNotificationRead,
tablePrefix+"group_qrcode":BindGroupQrcode,
tablePrefix+"group_tag":BindGroupTag,
tablePrefix+"group_tag_access":BindGroupTagAccess,
tablePrefix+"group_user":BindGroupUser,
tablePrefix+"group_user_kick_out":BindGroupUserKickOut,
tablePrefix+"help_question":BindHelpQuestion,
tablePrefix+"hot_search":BindHotSearch,
tablePrefix+"hot_search_ext":BindHotSearchExt,
tablePrefix+"img":BindImg,
tablePrefix+"img_tag":BindImgTag,
tablePrefix+"img_type":BindImgType,
tablePrefix+"industry":BindIndustry,
tablePrefix+"industry_user":BindIndustryUser,
tablePrefix+"koubei":BindKoubei,
tablePrefix+"koubei_album":BindKoubeiAlbum,
tablePrefix+"koubei_spider":BindKoubeiSpider,
tablePrefix+"latent_autoset":BindLatentAutoset,
tablePrefix+"latent_dispense":BindLatentDispense,
tablePrefix+"line":BindLine,
tablePrefix+"line_node":BindLineNode,
tablePrefix+"line_node_album":BindLineNodeAlbum,
tablePrefix+"line_node_comment":BindLineNodeComment,
tablePrefix+"line_node_comment_minutia":BindLineNodeCommentMinutia,
tablePrefix+"line_node_comment_text":BindLineNodeCommentText,
tablePrefix+"line_node_punch_census":BindLineNodePunchCensus,
tablePrefix+"line_node_related":BindLineNodeRelated,
tablePrefix+"live_message":BindLiveMessage,
tablePrefix+"live_user":BindLiveUser,
tablePrefix+"log_admin_login":BindLogAdminLogin,
tablePrefix+"log_admin_work":BindLogAdminWork,
tablePrefix+"lottery":BindLottery,
tablePrefix+"lottery_auth":BindLotteryAuth,
tablePrefix+"lottery_config":BindLotteryConfig,
tablePrefix+"lottery_cron":BindLotteryCron,
tablePrefix+"lottery_new":BindLotteryNew,
tablePrefix+"lottery_new_auth":BindLotteryNewAuth,
tablePrefix+"lottery_new_code_bill":BindLotteryNewCodeBill,
tablePrefix+"lottery_new_config":BindLotteryNewConfig,
tablePrefix+"lottery_new_cron":BindLotteryNewCron,
tablePrefix+"lottery_new_lucky_code":BindLotteryNewLuckyCode,
tablePrefix+"lottery_new_order":BindLotteryNewOrder,
tablePrefix+"lottery_new_org_code":BindLotteryNewOrgCode,
tablePrefix+"lottery_new_prize":BindLotteryNewPrize,
tablePrefix+"lottery_new_record":BindLotteryNewRecord,
tablePrefix+"lottery_new_set":BindLotteryNewSet,
tablePrefix+"lottery_new_user":BindLotteryNewUser,
tablePrefix+"lottery_new_user_code":BindLotteryNewUserCode,
tablePrefix+"lottery_org_code":BindLotteryOrgCode,
tablePrefix+"lottery_part":BindLotteryPart,
tablePrefix+"lottery_prize":BindLotteryPrize,
tablePrefix+"lottery_record":BindLotteryRecord,
tablePrefix+"lottery_thread":BindLotteryThread,
tablePrefix+"lottery_user":BindLotteryUser,
tablePrefix+"lottery_user_code":BindLotteryUserCode,
tablePrefix+"love_chicken":BindLoveChicken,
tablePrefix+"lover_user":BindLoverUser,
tablePrefix+"main_work":BindMainWork,
tablePrefix+"management_type":BindManagementType,
tablePrefix+"manual_code":BindManualCode,
tablePrefix+"manual_code_operation_record":BindManualCodeOperationRecord,
tablePrefix+"menu":BindMenu,
tablePrefix+"menu_copy":BindMenuCopy,
tablePrefix+"message":BindMessage,
tablePrefix+"message_app":BindMessageApp,
tablePrefix+"message_event":BindMessageEvent,
tablePrefix+"message_event_user":BindMessageEventUser,
tablePrefix+"message_extend":BindMessageExtend,
tablePrefix+"message_img":BindMessageImg,
tablePrefix+"message_interact":BindMessageInteract,
tablePrefix+"message_interact_user":BindMessageInteractUser,
tablePrefix+"message_jike":BindMessageJike,
tablePrefix+"message_jike_user":BindMessageJikeUser,
tablePrefix+"message_label":BindMessageLabel,
tablePrefix+"message_lovecar":BindMessageLovecar,
tablePrefix+"message_lovecar_user":BindMessageLovecarUser,
tablePrefix+"message_record":BindMessageRecord,
tablePrefix+"message_setting":BindMessageSetting,
tablePrefix+"message_store":BindMessageStore,
tablePrefix+"message_store_user":BindMessageStoreUser,
tablePrefix+"message_type":BindMessageType,
tablePrefix+"message_type_content":BindMessageTypeContent,
tablePrefix+"message_type_copy":BindMessageTypeCopy,
tablePrefix+"message_url":BindMessageUrl,
tablePrefix+"msg_broker":BindMsgBroker,
tablePrefix+"music":BindMusic,
tablePrefix+"music1":BindMusic1,
tablePrefix+"music_type":BindMusicType,
tablePrefix+"node_punch_auth":BindNodePunchAuth,
tablePrefix+"node_punch_confirm":BindNodePunchConfirm,
tablePrefix+"onlineservice_mute":BindOnlineserviceMute,
tablePrefix+"onlineservice_order":BindOnlineserviceOrder,
tablePrefix+"operate_activity":BindOperateActivity,
tablePrefix+"operate_activity_check":BindOperateActivityCheck,
tablePrefix+"order":BindOrder,
tablePrefix+"order_main":BindOrderMain,
tablePrefix+"org_bank_card":BindOrgBankCard,
tablePrefix+"org_money":BindOrgMoney,
tablePrefix+"org_money_bill":BindOrgMoneyBill,
tablePrefix+"org_money_recharge":BindOrgMoneyRecharge,
tablePrefix+"org_money_withdraw":BindOrgMoneyWithdraw,
tablePrefix+"organization":BindOrganization,
tablePrefix+"organization_activity":BindOrganizationActivity,
tablePrefix+"organization_car":BindOrganizationCar,
tablePrefix+"organization_check":BindOrganizationCheck,
tablePrefix+"organization_check_info":BindOrganizationCheckInfo,
tablePrefix+"organization_conf":BindOrganizationConf,
tablePrefix+"organization_conf_val":BindOrganizationConfVal,
tablePrefix+"organization_copy":BindOrganizationCopy,
tablePrefix+"organization_copy_copy":BindOrganizationCopyCopy,
tablePrefix+"organization_focus":BindOrganizationFocus,
tablePrefix+"organization_log":BindOrganizationLog,
tablePrefix+"organization_order":BindOrganizationOrder,
tablePrefix+"organization_orderpoints_record":BindOrganizationOrderpointsRecord,
tablePrefix+"organization_privilege":BindOrganizationPrivilege,
tablePrefix+"organization_privilege_shop":BindOrganizationPrivilegeShop,
tablePrefix+"organization_privilege_store":BindOrganizationPrivilegeStore,
tablePrefix+"organization_time":BindOrganizationTime,
tablePrefix+"organization_type":BindOrganizationType,
tablePrefix+"partner":BindPartner,
tablePrefix+"partner_blacklist":BindPartnerBlacklist,
tablePrefix+"partner_invite":BindPartnerInvite,
tablePrefix+"partner_log":BindPartnerLog,
tablePrefix+"partner_period":BindPartnerPeriod,
tablePrefix+"partner_qrcode":BindPartnerQrcode,
tablePrefix+"partner_register":BindPartnerRegister,
tablePrefix+"partner_results":BindPartnerResults,
tablePrefix+"partner_task":BindPartnerTask,
tablePrefix+"pay_alipay_log":BindPayAlipayLog,
tablePrefix+"pay_wx_log":BindPayWxLog,
tablePrefix+"phone":BindPhone,
tablePrefix+"photo":BindPhoto,
tablePrefix+"points_data":BindPointsData,
tablePrefix+"points_exceed":BindPointsExceed,
tablePrefix+"points_exp_records":BindPointsExpRecords,
tablePrefix+"points_exp_rules":BindPointsExpRules,
tablePrefix+"points_goods":BindPointsGoods,
tablePrefix+"points_goods_pay":BindPointsGoodsPay,
tablePrefix+"points_log":BindPointsLog,
tablePrefix+"points_product":BindPointsProduct,
tablePrefix+"points_product_records":BindPointsProductRecords,
tablePrefix+"points_ranking":BindPointsRanking,
tablePrefix+"points_sale_rules":BindPointsSaleRules,
tablePrefix+"praise":BindPraise,
tablePrefix+"project_examine":BindProjectExamine,
tablePrefix+"punch":BindPunch,
tablePrefix+"purchase":BindPurchase,
tablePrefix+"purchase_factory":BindPurchaseFactory,
tablePrefix+"purchase_fail":BindPurchaseFail,
tablePrefix+"purchase_img":BindPurchaseImg,
tablePrefix+"purchase_records":BindPurchaseRecords,
tablePrefix+"purchase_sms":BindPurchaseSms,
tablePrefix+"purchase_user":BindPurchaseUser,
tablePrefix+"push_sms_config":BindPushSmsConfig,
tablePrefix+"questionnaire":BindQuestionnaire,
tablePrefix+"questionnaire_answer":BindQuestionnaireAnswer,
tablePrefix+"questionnaire_main":BindQuestionnaireMain,
tablePrefix+"questionnaire_user":BindQuestionnaireUser,
tablePrefix+"rabbit_msg":BindRabbitMsg,
tablePrefix+"recommend":BindRecommend,
tablePrefix+"recommend_auth":BindRecommendAuth,
tablePrefix+"recommend_content":BindRecommendContent,
tablePrefix+"recommend_detail_201905":BindRecommendDetail201905,
tablePrefix+"recommend_detail_201906":BindRecommendDetail201906,
tablePrefix+"recommend_detail_201907":BindRecommendDetail201907,
tablePrefix+"recommend_detail_201908":BindRecommendDetail201908,
tablePrefix+"recommend_detail_201909":BindRecommendDetail201909,
tablePrefix+"recommend_detail_201910":BindRecommendDetail201910,
tablePrefix+"recommend_detail_201911":BindRecommendDetail201911,
tablePrefix+"recommend_detail_201912":BindRecommendDetail201912,
tablePrefix+"recommend_org":BindRecommendOrg,
tablePrefix+"recommend_position":BindRecommendPosition,
tablePrefix+"recommend_position_config":BindRecommendPositionConfig,
tablePrefix+"recommend_record":BindRecommendRecord,
tablePrefix+"recommend_time":BindRecommendTime,
tablePrefix+"recommend_time_extend":BindRecommendTimeExtend,
tablePrefix+"recommend_tongji_day":BindRecommendTongjiDay,
tablePrefix+"recommend_tongji_month":BindRecommendTongjiMonth,
tablePrefix+"redpack":BindRedpack,
tablePrefix+"redpack_area":BindRedpackArea,
tablePrefix+"redpack_check_record":BindRedpackCheckRecord,
tablePrefix+"redpack_content":BindRedpackContent,
tablePrefix+"redpack_msg_record":BindRedpackMsgRecord,
tablePrefix+"redpack_org":BindRedpackOrg,
tablePrefix+"redpack_position":BindRedpackPosition,
tablePrefix+"redpack_prize":BindRedpackPrize,
tablePrefix+"redpack_record":BindRedpackRecord,
tablePrefix+"redpack_record_temp":BindRedpackRecordTemp,
tablePrefix+"redpack_time":BindRedpackTime,
tablePrefix+"redpack_user_card":BindRedpackUserCard,
tablePrefix+"redpack_user_card_record":BindRedpackUserCardRecord,
tablePrefix+"region":BindRegion,
tablePrefix+"report":BindReport,
tablePrefix+"report_img":BindReportImg,
tablePrefix+"report_record":BindReportRecord,
tablePrefix+"ride":BindRide,
tablePrefix+"ride_check":BindRideCheck,
tablePrefix+"ride_check_notes":BindRideCheckNotes,
tablePrefix+"ride_line":BindRideLine,
tablePrefix+"ride_node":BindRideNode,
tablePrefix+"road_book":BindRoadBook,
tablePrefix+"road_book_line":BindRoadBookLine,
tablePrefix+"road_book_line_content":BindRoadBookLineContent,
tablePrefix+"road_book_meet":BindRoadBookMeet,
tablePrefix+"road_book_recommend":BindRoadBookRecommend,
tablePrefix+"roadbook_arouse":BindRoadbookArouse,
tablePrefix+"roadbook_arouse_abnormal":BindRoadbookArouseAbnormal,
tablePrefix+"roadbook_arouse_account":BindRoadbookArouseAccount,
tablePrefix+"roadbook_arouse_attend":BindRoadbookArouseAttend,
tablePrefix+"roadbook_arouse_attend_census":BindRoadbookArouseAttendCensus,
tablePrefix+"roadbook_arouse_flow":BindRoadbookArouseFlow,
tablePrefix+"roadbook_arouse_log":BindRoadbookArouseLog,
tablePrefix+"roadbook_arouse_real_account":BindRoadbookArouseRealAccount,
tablePrefix+"roadbook_arouse_related":BindRoadbookArouseRelated,
tablePrefix+"roadbook_line":BindRoadbookLine,
tablePrefix+"roadbook_merchant":BindRoadbookMerchant,
tablePrefix+"roadbook_merchant_apply":BindRoadbookMerchantApply,
tablePrefix+"roadbook_merchant_invite":BindRoadbookMerchantInvite,
tablePrefix+"roadbook_node_punch_census":BindRoadbookNodePunchCensus,
tablePrefix+"roulette_lottery":BindRouletteLottery,
tablePrefix+"roulette_lottery_attend":BindRouletteLotteryAttend,
tablePrefix+"roulette_lottery_award":BindRouletteLotteryAward,
tablePrefix+"saleinfo_org":BindSaleinfoOrg,
tablePrefix+"saler_star":BindSalerStar,
tablePrefix+"search_log":BindSearchLog,
tablePrefix+"series":BindSeries,
tablePrefix+"service_city":BindServiceCity,
tablePrefix+"sms_api_log":BindSmsApiLog,
tablePrefix+"sms_template":BindSmsTemplate,
tablePrefix+"sms_template_log":BindSmsTemplateLog,
tablePrefix+"sms_total":BindSmsTotal,
tablePrefix+"sms_verify_code":BindSmsVerifyCode,
tablePrefix+"special":BindSpecial,
tablePrefix+"spm_app_download_log":BindSpmAppDownloadLog,
tablePrefix+"spm_baidureferer_log":BindSpmBaidurefererLog,
tablePrefix+"spm_cate":BindSpmCate,
tablePrefix+"spm_designation":BindSpmDesignation,
tablePrefix+"spm_keywords":BindSpmKeywords,
tablePrefix+"spm_log":BindSpmLog,
tablePrefix+"spm_log_copy":BindSpmLogCopy,
tablePrefix+"spm_parameter":BindSpmParameter,
tablePrefix+"spm_place":BindSpmPlace,
tablePrefix+"spm_promoter":BindSpmPromoter,
tablePrefix+"staff":BindStaff,
tablePrefix+"statistics":BindStatistics,
tablePrefix+"supertopic_apply":BindSupertopicApply,
tablePrefix+"tag_car":BindTagCar,
tablePrefix+"tag_cart_specific":BindTagCartSpecific,
tablePrefix+"tags":BindTags,
tablePrefix+"tags_category":BindTagsCategory,
tablePrefix+"tagscategory":BindTagscategory,
tablePrefix+"thread_activity":BindThreadActivity,
tablePrefix+"thread_activity_apply":BindThreadActivityApply,
tablePrefix+"thread_activity_car":BindThreadActivityCar,
tablePrefix+"thread_activity_master":BindThreadActivityMaster,
tablePrefix+"thread_activity_scene":BindThreadActivityScene,
tablePrefix+"thread_activity_type":BindThreadActivityType,
tablePrefix+"thread_activity_user":BindThreadActivityUser,
tablePrefix+"thread_ask":BindThreadAsk,
tablePrefix+"thread_ask_answer":BindThreadAskAnswer,
tablePrefix+"thread_ask_answer_follow":BindThreadAskAnswerFollow,
tablePrefix+"thread_census_ranking":BindThreadCensusRanking,
tablePrefix+"thread_cycle":BindThreadCycle,
tablePrefix+"thread_delete_reason":BindThreadDeleteReason,
tablePrefix+"thread_evaluate":BindThreadEvaluate,
tablePrefix+"thread_evaluate_car":BindThreadEvaluateCar,
tablePrefix+"thread_goods":BindThreadGoods,
tablePrefix+"thread_goods_category":BindThreadGoodsCategory,
tablePrefix+"thread_integral_log":BindThreadIntegralLog,
tablePrefix+"thread_mastersay":BindThreadMastersay,
tablePrefix+"thread_mastersay_car":BindThreadMastersayCar,
tablePrefix+"thread_mood":BindThreadMood,
tablePrefix+"thread_play":BindThreadPlay,
tablePrefix+"thread_roadbook_annex":BindThreadRoadbookAnnex,
tablePrefix+"thread_roadbook_line_been":BindThreadRoadbookLineBeen,
tablePrefix+"thread_roadbook_line_related":BindThreadRoadbookLineRelated,
tablePrefix+"thread_roadbook_note_user":BindThreadRoadbookNoteUser,
tablePrefix+"thread_roadbook_punch_census":BindThreadRoadbookPunchCensus,
tablePrefix+"thread_show":BindThreadShow,
tablePrefix+"thread_topic":BindThreadTopic,
tablePrefix+"thread_topic_access":BindThreadTopicAccess,
tablePrefix+"thread_topic_apply":BindThreadTopicApply,
tablePrefix+"thread_topic_fans":BindThreadTopicFans,
tablePrefix+"thread_visible":BindThreadVisible,
tablePrefix+"thread_word_column":BindThreadWordColumn,
tablePrefix+"thread_words":BindThreadWords,
tablePrefix+"ticket":BindTicket,
tablePrefix+"ticket_api_log":BindTicketApiLog,
tablePrefix+"ticket_apply_user":BindTicketApplyUser,
tablePrefix+"ticket_check_record":BindTicketCheckRecord,
tablePrefix+"ticket_checkout_auth":BindTicketCheckoutAuth,
tablePrefix+"ticket_free":BindTicketFree,
tablePrefix+"ticket_free_handout":BindTicketFreeHandout,
tablePrefix+"ticket_nums_record":BindTicketNumsRecord,
tablePrefix+"ticket_paper_record":BindTicketPaperRecord,
tablePrefix+"ticket_qd":BindTicketQd,
tablePrefix+"ticket_qd_sale":BindTicketQdSale,
tablePrefix+"ticket_redpack":BindTicketRedpack,
tablePrefix+"ticket_redpack_log":BindTicketRedpackLog,
tablePrefix+"ticket_refund":BindTicketRefund,
tablePrefix+"ticket_refund_log":BindTicketRefundLog,
tablePrefix+"ticket_send_record":BindTicketSendRecord,
tablePrefix+"ticket_third_party":BindTicketThirdParty,
tablePrefix+"ticket_user":BindTicketUser,
tablePrefix+"tmp_data":BindTmpData,
tablePrefix+"topic_category":BindTopicCategory,
tablePrefix+"topic_exp_log":BindTopicExpLog,
tablePrefix+"topic_log":BindTopicLog,
tablePrefix+"topic_scompere":BindTopicScompere,
tablePrefix+"topic_signin":BindTopicSignin,
tablePrefix+"traffic_statistics":BindTrafficStatistics,
tablePrefix+"traffic_statistics_log":BindTrafficStatisticsLog,
tablePrefix+"traffic_statistics_log_group":BindTrafficStatisticsLogGroup,
tablePrefix+"twitter":BindTwitter,
tablePrefix+"twitter_album":BindTwitterAlbum,
tablePrefix+"twitter_source":BindTwitterSource,
tablePrefix+"twitter_topic_access":BindTwitterTopicAccess,
tablePrefix+"twitter_visibility":BindTwitterVisibility,
tablePrefix+"upload_apk":BindUploadApk,
tablePrefix+"user_bank_card":BindUserBankCard,
tablePrefix+"user_behaviour":BindUserBehaviour,
tablePrefix+"user_car":BindUserCar,
tablePrefix+"user_follow":BindUserFollow,
tablePrefix+"user_points":BindUserPoints,
tablePrefix+"user_recommend":BindUserRecommend,
tablePrefix+"user_setting":BindUserSetting,
tablePrefix+"video":BindVideo,
tablePrefix+"video_attach":BindVideoAttach,
tablePrefix+"video_attach_receive":BindVideoAttachReceive,
tablePrefix+"video_log":BindVideoLog,
tablePrefix+"video_notice":BindVideoNotice,
tablePrefix+"video_recommend_table":BindVideoRecommendTable,
tablePrefix+"video_visible":BindVideoVisible,
tablePrefix+"virtual_nickname":BindVirtualNickname,
tablePrefix+"virtual_record":BindVirtualRecord,
tablePrefix+"wanna_buy":BindWannaBuy,
tablePrefix+"weather_citys":BindWeatherCitys,
tablePrefix+"weather_today":BindWeatherToday,
tablePrefix+"weixin_config":BindWeixinConfig,
tablePrefix+"weixin_custom_send":BindWeixinCustomSend,
tablePrefix+"weixin_kerword":BindWeixinKerword,
tablePrefix+"weixin_material":BindWeixinMaterial,
tablePrefix+"weixin_menu":BindWeixinMenu,
tablePrefix+"weixin_push":BindWeixinPush,
tablePrefix+"weixin_push_auto":BindWeixinPushAuto,
tablePrefix+"weixin_push_config":BindWeixinPushConfig,
tablePrefix+"weixin_push_interactive":BindWeixinPushInteractive,
tablePrefix+"weixin_push_material":BindWeixinPushMaterial,
tablePrefix+"weixin_push_record":BindWeixinPushRecord,
tablePrefix+"weixin_push_tag":BindWeixinPushTag,
tablePrefix+"weixin_qrcode":BindWeixinQrcode,
tablePrefix+"weixin_qrcode_scan_log":BindWeixinQrcodeScanLog,
tablePrefix+"weixin_template":BindWeixinTemplate,
tablePrefix+"xc1_jurisdiction":BindXc1Jurisdiction,
tablePrefix+"xc1_manage_object":BindXc1ManageObject,
tablePrefix+"xc1_org2scene":BindXc1Org2scene,
tablePrefix+"xc1_worker2guest":BindXc1Worker2guest,
tablePrefix+"xc_app_message":BindXcAppMessage,
tablePrefix+"xc_app_message_count":BindXcAppMessageCount,
tablePrefix+"xc_apply_item":BindXcApplyItem,
tablePrefix+"xc_apply_type":BindXcApplyType,
tablePrefix+"xc_area":BindXcArea,
tablePrefix+"xc_auth_mapping":BindXcAuthMapping,
tablePrefix+"xc_authorise":BindXcAuthorise,
tablePrefix+"xc_check_course":BindXcCheckCourse,
tablePrefix+"xc_check_table":BindXcCheckTable,
tablePrefix+"xc_checker2object":BindXcChecker2object,
tablePrefix+"xc_friends":BindXcFriends,
tablePrefix+"xc_guest2object":BindXcGuest2object,
tablePrefix+"xc_job_type":BindXcJobType,
tablePrefix+"xc_message":BindXcMessage,
tablePrefix+"xc_message_addtask":BindXcMessageAddtask,
tablePrefix+"xc_message_apply":BindXcMessageApply,
tablePrefix+"xc_message_content":BindXcMessageContent,
tablePrefix+"xc_message_rectification":BindXcMessageRectification,
tablePrefix+"xc_message_setting":BindXcMessageSetting,
tablePrefix+"xc_message_unqualifiedcheck":BindXcMessageUnqualifiedcheck,
tablePrefix+"xc_object":BindXcObject,
tablePrefix+"xc_object2dispose":BindXcObject2dispose,
tablePrefix+"xc_object_organization":BindXcObjectOrganization,
tablePrefix+"xc_object_type":BindXcObjectType,
tablePrefix+"xc_offset_trigger_time":BindXcOffsetTriggerTime,
tablePrefix+"xc_order":BindXcOrder,
tablePrefix+"xc_order_progress":BindXcOrderProgress,
tablePrefix+"xc_organization":BindXcOrganization,
tablePrefix+"xc_pay_log":BindXcPayLog,
tablePrefix+"xc_permission":BindXcPermission,
tablePrefix+"xc_scene":BindXcScene,
tablePrefix+"xc_scene_review":BindXcSceneReview,
tablePrefix+"xc_staff2object":BindXcStaff2object,
tablePrefix+"xc_task":BindXcTask,
tablePrefix+"xc_task_copy":BindXcTaskCopy,
tablePrefix+"xc_task_dis":BindXcTaskDis,
tablePrefix+"xc_task_disimg":BindXcTaskDisimg,
tablePrefix+"xc_task_log":BindXcTaskLog,
tablePrefix+"xc_task_package":BindXcTaskPackage,
tablePrefix+"xc_top_up_log":BindXcTopUpLog,
tablePrefix+"xc_user2scene":BindXcUser2scene,
tablePrefix+"xc_usercoordinate":BindXcUsercoordinate,
tablePrefix+"xc_worker":BindXcWorker,
tablePrefix+"xc_worker2area":BindXcWorker2area,
tablePrefix+"xc_worker_yanghuan_back":BindXcWorkerYanghuanBack,
tablePrefix+"yaoyiyao":BindYaoyiyao,
tablePrefix+"yaoyiyao_auth":BindYaoyiyaoAuth,
tablePrefix+"yaoyiyao_awards":BindYaoyiyaoAwards,
tablePrefix+"yaoyiyao_awards_copy":BindYaoyiyaoAwardsCopy,
tablePrefix+"yaoyiyao_cacheawards":BindYaoyiyaoCacheawards,
tablePrefix+"yaoyiyao_end_log":BindYaoyiyaoEndLog,
tablePrefix+"yaoyiyao_not_win":BindYaoyiyaoNotWin,
tablePrefix+"yaoyiyao_pass_log":BindYaoyiyaoPassLog,
tablePrefix+"yaoyiyao_rank":BindYaoyiyaoRank,
tablePrefix+"yaoyiyao_rotary":BindYaoyiyaoRotary,
tablePrefix+"yaoyiyao_signin":BindYaoyiyaoSignin,
tablePrefix+"yaoyiyao_status":BindYaoyiyaoStatus,
}
//绑定thread
func BindThread(args Args) interface{} {
model := models.TgThread{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
//绑定thread_roadbook
func Bind2handcarApply(args Args) interface{} {
model := models.Tg2handcarApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
//绑定thread_roadbook
func BindThreadRoadbook(args Args) interface{} {
model := models.TgThreadRoadbook{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarBooth(args Args) interface{} {
model := models.Tg2handcarBooth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarComplain(args Args) interface{} {
model := models.Tg2handcarComplain{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarConfig(args Args) interface{} {
model := models.Tg2handcarConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarDebitList(args Args) interface{} {
model := models.Tg2handcarDebitList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarIntention(args Args) interface{} {
model := models.Tg2handcarIntention{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarList(args Args) interface{} {
model := models.Tg2handcarList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarOrder(args Args) interface{} {
model := models.Tg2handcarOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarPark(args Args) interface{} {
model := models.Tg2handcarPark{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarParkTime(args Args) interface{} {
model := models.Tg2handcarParkTime{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarParkType(args Args) interface{} {
model := models.Tg2handcarParkType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarPlan(args Args) interface{} {
model := models.Tg2handcarPlan{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarTime(args Args) interface{} {
model := models.Tg2handcarTime{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func Bind2handcarWxFail(args Args) interface{} {
model := models.Tg2handcarWxFail{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAccountManage(args Args) interface{} {
model := models.TgAccountManage{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActionLog(args Args) interface{} {
model := models.TgActionLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityArea(args Args) interface{} {
model := models.TgActivityArea{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityForward(args Args) interface{} {
model := models.TgActivityForward{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityForwardContent(args Args) interface{} {
model := models.TgActivityForwardContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityForwardPrize(args Args) interface{} {
model := models.TgActivityForwardPrize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityForwardRecord(args Args) interface{} {
model := models.TgActivityForwardRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityForwardRecordDetails(args Args) interface{} {
model := models.TgActivityForwardRecordDetails{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLine(args Args) interface{} {
model := models.TgActivityLine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLineNodeRelated(args Args) interface{} {
model := models.TgActivityLineNodeRelated{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotteryAttendance(args Args) interface{} {
model := models.TgActivityLotteryAttendance{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotteryAuth(args Args) interface{} {
model := models.TgActivityLotteryAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotteryCode(args Args) interface{} {
model := models.TgActivityLotteryCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotteryPrize(args Args) interface{} {
model := models.TgActivityLotteryPrize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotteryRotary(args Args) interface{} {
model := models.TgActivityLotteryRotary{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotterySms(args Args) interface{} {
model := models.TgActivityLotterySms{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityLotteryStatus(args Args) interface{} {
model := models.TgActivityLotteryStatus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTable(args Args) interface{} {
model := models.TgActivityTable{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTags(args Args) interface{} {
model := models.TgActivityTags{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntable(args Args) interface{} {
model := models.TgActivityTurntable{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableContent(args Args) interface{} {
model := models.TgActivityTurntableContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntablePrize(args Args) interface{} {
model := models.TgActivityTurntablePrize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableQrcodetag(args Args) interface{} {
model := models.TgActivityTurntableQrcodetag{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableRecord(args Args) interface{} {
model := models.TgActivityTurntableRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableResult(args Args) interface{} {
model := models.TgActivityTurntableResult{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableSaddress(args Args) interface{} {
model := models.TgActivityTurntableSaddress{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableShare(args Args) interface{} {
model := models.TgActivityTurntableShare{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityTurntableUser(args Args) interface{} {
model := models.TgActivityTurntableUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityVoteReferOpt(args Args) interface{} {
model := models.TgActivityVoteReferOpt{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityVoteRules(args Args) interface{} {
model := models.TgActivityVoteRules{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityVoteUserLimit(args Args) interface{} {
model := models.TgActivityVoteUserLimit{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityVoteUserTable(args Args) interface{} {
model := models.TgActivityVoteUserTable{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindActivityVoteUserTicketcert(args Args) interface{} {
model := models.TgActivityVoteUserTicketcert{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminAuthProjectXc(args Args) interface{} {
model := models.TgAdminAuthProjectXc{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminAuthProjectXcCopy(args Args) interface{} {
model := models.TgAdminAuthProjectXcCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminAuthUser(args Args) interface{} {
model := models.TgAdminAuthUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminAuthUserCopy(args Args) interface{} {
model := models.TgAdminAuthUserCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminMenu(args Args) interface{} {
model := models.TgAdminMenu{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminReport(args Args) interface{} {
model := models.TgAdminReport{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminRole(args Args) interface{} {
model := models.TgAdminRole{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUser(args Args) interface{} {
model := models.TgAdminUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUser2area(args Args) interface{} {
model := models.TgAdminUser2area{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUser2areaOrg(args Args) interface{} {
model := models.TgAdminUser2areaOrg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUser2org(args Args) interface{} {
model := models.TgAdminUser2org{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUser2orgCopy(args Args) interface{} {
model := models.TgAdminUser2orgCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUser2orgSetting(args Args) interface{} {
model := models.TgAdminUser2orgSetting{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserAlltags(args Args) interface{} {
model := models.TgAdminUserAlltags{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserAuth(args Args) interface{} {
model := models.TgAdminUserAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserAuthCopy(args Args) interface{} {
model := models.TgAdminUserAuthCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserAvatar(args Args) interface{} {
model := models.TgAdminUserAvatar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserCopy1(args Args) interface{} {
model := models.TgAdminUserCopy1{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserDepartment(args Args) interface{} {
model := models.TgAdminUserDepartment{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserDoyen(args Args) interface{} {
model := models.TgAdminUserDoyen{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserFavor(args Args) interface{} {
model := models.TgAdminUserFavor{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserImpression(args Args) interface{} {
model := models.TgAdminUserImpression{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserLock(args Args) interface{} {
model := models.TgAdminUserLock{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserLoginFail(args Args) interface{} {
model := models.TgAdminUserLoginFail{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserMoney(args Args) interface{} {
model := models.TgAdminUserMoney{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserMoneyBill(args Args) interface{} {
model := models.TgAdminUserMoneyBill{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserMoneyRecharge(args Args) interface{} {
model := models.TgAdminUserMoneyRecharge{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserMoneyWithdraw(args Args) interface{} {
model := models.TgAdminUserMoneyWithdraw{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserOrg(args Args) interface{} {
model := models.TgAdminUserOrg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserPosition(args Args) interface{} {
model := models.TgAdminUserPosition{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserPunish(args Args) interface{} {
model := models.TgAdminUserPunish{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserRealNameAuth(args Args) interface{} {
model := models.TgAdminUserRealNameAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserRole(args Args) interface{} {
model := models.TgAdminUserRole{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserTags(args Args) interface{} {
model := models.TgAdminUserTags{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdminUserType(args Args) interface{} {
model := models.TgAdminUserType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdvertisementAdminLog(args Args) interface{} {
model := models.TgAdvertisementAdminLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdvertisementContent(args Args) interface{} {
model := models.TgAdvertisementContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdvertisementOrgStrategy(args Args) interface{} {
model := models.TgAdvertisementOrgStrategy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAdvertisementPosition(args Args) interface{} {
model := models.TgAdvertisementPosition{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAgreement(args Args) interface{} {
model := models.TgAgreement{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAgreementPlace(args Args) interface{} {
model := models.TgAgreementPlace{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAlbum(args Args) interface{} {
model := models.TgAlbum{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAlltags(args Args) interface{} {
model := models.TgAlltags{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAlltagsArticle(args Args) interface{} {
model := models.TgAlltagsArticle{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAlltagsCategory(args Args) interface{} {
model := models.TgAlltagsCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAlltagsCategoryActivity(args Args) interface{} {
model := models.TgAlltagsCategoryActivity{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindArea(args Args) interface{} {
model := models.TgArea{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAreaBak(args Args) interface{} {
model := models.TgAreaBak{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAreaHot(args Args) interface{} {
model := models.TgAreaHot{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindArticle(args Args) interface{} {
model := models.TgArticle{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindArticleCategory(args Args) interface{} {
model := models.TgArticleCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindArticleData(args Args) interface{} {
model := models.TgArticleData{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindArticleTag(args Args) interface{} {
model := models.TgArticleTag{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAskCate(args Args) interface{} {
model := models.TgAskCate{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAskExpert(args Args) interface{} {
model := models.TgAskExpert{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAsyncTask(args Args) interface{} {
model := models.TgAsyncTask{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAttachment(args Args) interface{} {
model := models.TgAttachment{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAuthAction(args Args) interface{} {
model := models.TgAuthAction{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAuthRole(args Args) interface{} {
model := models.TgAuthRole{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAuthRoleAction(args Args) interface{} {
model := models.TgAuthRoleAction{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAuthRoleSource(args Args) interface{} {
model := models.TgAuthRoleSource{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindAuthUserRole(args Args) interface{} {
model := models.TgAuthUserRole{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBaiduConfig(args Args) interface{} {
model := models.TgBaiduConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBaiduNotice(args Args) interface{} {
model := models.TgBaiduNotice{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBaiduShare(args Args) interface{} {
model := models.TgBaiduShare{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBenefit(args Args) interface{} {
model := models.TgBenefit{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBenefitAccess(args Args) interface{} {
model := models.TgBenefitAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBenefitStore(args Args) interface{} {
model := models.TgBenefitStore{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBidKeyword(args Args) interface{} {
model := models.TgBidKeyword{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBidKeywordCopy(args Args) interface{} {
model := models.TgBidKeywordCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBrand(args Args) interface{} {
model := models.TgBrand{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindBrowseHistory(args Args) interface{} {
model := models.TgBrowseHistory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudience(args Args) interface{} {
model := models.TgCallAudience{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceAccess(args Args) interface{} {
model := models.TgCallAudienceAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceConf(args Args) interface{} {
model := models.TgCallAudienceConf{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceConfVal(args Args) interface{} {
model := models.TgCallAudienceConfVal{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceReview(args Args) interface{} {
model := models.TgCallAudienceReview{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceReviewLog(args Args) interface{} {
model := models.TgCallAudienceReviewLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceSmstask(args Args) interface{} {
model := models.TgCallAudienceSmstask{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceSmstaskContent(args Args) interface{} {
model := models.TgCallAudienceSmstaskContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceSmstaskRecord(args Args) interface{} {
model := models.TgCallAudienceSmstaskRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceUser(args Args) interface{} {
model := models.TgCallAudienceUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallAudienceVisit(args Args) interface{} {
model := models.TgCallAudienceVisit{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallDatatype(args Args) interface{} {
model := models.TgCallDatatype{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallDraw(args Args) interface{} {
model := models.TgCallDraw{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallEventAuth(args Args) interface{} {
model := models.TgCallEventAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallPrivacy(args Args) interface{} {
model := models.TgCallPrivacy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallQuestionnaire(args Args) interface{} {
model := models.TgCallQuestionnaire{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallQuestionnaireConf(args Args) interface{} {
model := models.TgCallQuestionnaireConf{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallQuestionnaireUser(args Args) interface{} {
model := models.TgCallQuestionnaireUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallQuestionnaireVal(args Args) interface{} {
model := models.TgCallQuestionnaireVal{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallRecord(args Args) interface{} {
model := models.TgCallRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCallUserAuth(args Args) interface{} {
model := models.TgCallUserAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCar(args Args) interface{} {
model := models.TgCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCar2conf(args Args) interface{} {
model := models.TgCar2conf{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarColor(args Args) interface{} {
model := models.TgCarColor{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarConf(args Args) interface{} {
model := models.TgCarConf{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarConfVal(args Args) interface{} {
model := models.TgCarConfVal{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarCopy(args Args) interface{} {
model := models.TgCarCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarCustomMade(args Args) interface{} {
model := models.TgCarCustomMade{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarFind(args Args) interface{} {
model := models.TgCarFind{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarLove(args Args) interface{} {
model := models.TgCarLove{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrder(args Args) interface{} {
model := models.TgCarOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderConfig(args Args) interface{} {
model := models.TgCarOrderConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderList(args Args) interface{} {
model := models.TgCarOrderList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderMsg(args Args) interface{} {
model := models.TgCarOrderMsg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderOffer(args Args) interface{} {
model := models.TgCarOrderOffer{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderOfferCount(args Args) interface{} {
model := models.TgCarOrderOfferCount{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderPushList(args Args) interface{} {
model := models.TgCarOrderPushList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarOrderTags(args Args) interface{} {
model := models.TgCarOrderTags{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarPic(args Args) interface{} {
model := models.TgCarPic{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarSearchLog(args Args) interface{} {
model := models.TgCarSearchLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarSeries(args Args) interface{} {
model := models.TgCarSeries{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarSeriesColor(args Args) interface{} {
model := models.TgCarSeriesColor{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorder(args Args) interface{} {
model := models.TgCarorder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderConfig(args Args) interface{} {
model := models.TgCarorderConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderList(args Args) interface{} {
model := models.TgCarorderList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderLovecar(args Args) interface{} {
model := models.TgCarorderLovecar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderOffer(args Args) interface{} {
model := models.TgCarorderOffer{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderOfferRecord(args Args) interface{} {
model := models.TgCarorderOfferRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderPushList(args Args) interface{} {
model := models.TgCarorderPushList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderRecord(args Args) interface{} {
model := models.TgCarorderRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderTactics(args Args) interface{} {
model := models.TgCarorderTactics{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderTacticsConfig(args Args) interface{} {
model := models.TgCarorderTacticsConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderTacticsGift(args Args) interface{} {
model := models.TgCarorderTacticsGift{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarorderTacticsRecord(args Args) interface{} {
model := models.TgCarorderTacticsRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarousel(args Args) interface{} {
model := models.TgCarousel{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselItem(args Args) interface{} {
model := models.TgCarouselItem{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselObject(args Args) interface{} {
model := models.TgCarouselObject{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselOrgPlan(args Args) interface{} {
model := models.TgCarouselOrgPlan{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselOrgRight(args Args) interface{} {
model := models.TgCarouselOrgRight{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselOriginality(args Args) interface{} {
model := models.TgCarouselOriginality{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselScheduling(args Args) interface{} {
model := models.TgCarouselScheduling{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselSchedulingAuthorize(args Args) interface{} {
model := models.TgCarouselSchedulingAuthorize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselStrategy(args Args) interface{} {
model := models.TgCarouselStrategy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCarouselSubjectItem(args Args) interface{} {
model := models.TgCarouselSubjectItem{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCert(args Args) interface{} {
model := models.TgCert{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertApply(args Args) interface{} {
model := models.TgCertApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertContent(args Args) interface{} {
model := models.TgCertContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertHandout(args Args) interface{} {
model := models.TgCertHandout{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertNumsRecord(args Args) interface{} {
model := models.TgCertNumsRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertUser(args Args) interface{} {
model := models.TgCertUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertUserCopy(args Args) interface{} {
model := models.TgCertUserCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertUserRecord(args Args) interface{} {
model := models.TgCertUserRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCertUserRecordAct(args Args) interface{} {
model := models.TgCertUserRecordAct{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindChickenSoup(args Args) interface{} {
model := models.TgChickenSoup{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCollect(args Args) interface{} {
model := models.TgCollect{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCollectMapping(args Args) interface{} {
model := models.TgCollectMapping{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindComment(args Args) interface{} {
model := models.TgComment{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCommentLog(args Args) interface{} {
model := models.TgCommentLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindConfig(args Args) interface{} {
model := models.TgConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCountry(args Args) interface{} {
model := models.TgCountry{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCoupon(args Args) interface{} {
model := models.TgCoupon{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponCar(args Args) interface{} {
model := models.TgCouponCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponCategory(args Args) interface{} {
model := models.TgCouponCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponCheck(args Args) interface{} {
model := models.TgCouponCheck{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponCode(args Args) interface{} {
model := models.TgCouponCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponDealers(args Args) interface{} {
model := models.TgCouponDealers{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponDistribute(args Args) interface{} {
model := models.TgCouponDistribute{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponDistributeList(args Args) interface{} {
model := models.TgCouponDistributeList{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponDistributeListReissue(args Args) interface{} {
model := models.TgCouponDistributeListReissue{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponDistributeReissue(args Args) interface{} {
model := models.TgCouponDistributeReissue{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponIssue(args Args) interface{} {
model := models.TgCouponIssue{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponOrder(args Args) interface{} {
model := models.TgCouponOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponPush(args Args) interface{} {
model := models.TgCouponPush{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponPushLog(args Args) interface{} {
model := models.TgCouponPushLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponRefund(args Args) interface{} {
model := models.TgCouponRefund{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponReplace(args Args) interface{} {
model := models.TgCouponReplace{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponReplaceDistribute(args Args) interface{} {
model := models.TgCouponReplaceDistribute{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponReplaceReissue(args Args) interface{} {
model := models.TgCouponReplaceReissue{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponShareLog(args Args) interface{} {
model := models.TgCouponShareLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponTicket(args Args) interface{} {
model := models.TgCouponTicket{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponWarehouse(args Args) interface{} {
model := models.TgCouponWarehouse{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCouponWarehouseCode(args Args) interface{} {
model := models.TgCouponWarehouseCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindCrawlerData(args Args) interface{} {
model := models.TgCrawlerData{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindDanger(args Args) interface{} {
model := models.TgDanger{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindDshowBanner(args Args) interface{} {
model := models.TgDshowBanner{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindDshowBase(args Args) interface{} {
model := models.TgDshowBase{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindDshowGift(args Args) interface{} {
model := models.TgDshowGift{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindDshowShare(args Args) interface{} {
model := models.TgDshowShare{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindDshowText(args Args) interface{} {
model := models.TgDshowText{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEasemobMessages(args Args) interface{} {
model := models.TgEasemobMessages{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEasemobMessagesNum(args Args) interface{} {
model := models.TgEasemobMessagesNum{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEasemobMessagesPayload(args Args) interface{} {
model := models.TgEasemobMessagesPayload{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEmoji(args Args) interface{} {
model := models.TgEmoji{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEmojiGroup(args Args) interface{} {
model := models.TgEmojiGroup{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEmojiUserAccess(args Args) interface{} {
model := models.TgEmojiUserAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEntranceWay(args Args) interface{} {
model := models.TgEntranceWay{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEvent(args Args) interface{} {
model := models.TgEvent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventActivity(args Args) interface{} {
model := models.TgEventActivity{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventActivityData(args Args) interface{} {
model := models.TgEventActivityData{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventAd(args Args) interface{} {
model := models.TgEventAd{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventBdconfig(args Args) interface{} {
model := models.TgEventBdconfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventBooth(args Args) interface{} {
model := models.TgEventBooth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventBrand(args Args) interface{} {
model := models.TgEventBrand{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventBrandMerge(args Args) interface{} {
model := models.TgEventBrandMerge{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventBusiness(args Args) interface{} {
model := models.TgEventBusiness{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventDescImg(args Args) interface{} {
model := models.TgEventDescImg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventExamine(args Args) interface{} {
model := models.TgEventExamine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventGuest(args Args) interface{} {
model := models.TgEventGuest{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventHall(args Args) interface{} {
model := models.TgEventHall{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventImgConfig(args Args) interface{} {
model := models.TgEventImgConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventImgUnshow(args Args) interface{} {
model := models.TgEventImgUnshow{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventInformation(args Args) interface{} {
model := models.TgEventInformation{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventModel(args Args) interface{} {
model := models.TgEventModel{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventNavigation(args Args) interface{} {
model := models.TgEventNavigation{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventNavigationConf(args Args) interface{} {
model := models.TgEventNavigationConf{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventNewcar(args Args) interface{} {
model := models.TgEventNewcar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventSchedule(args Args) interface{} {
model := models.TgEventSchedule{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventShowcar(args Args) interface{} {
model := models.TgEventShowcar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventStaff(args Args) interface{} {
model := models.TgEventStaff{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventStaffAuth(args Args) interface{} {
model := models.TgEventStaffAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventStaffAuthArea(args Args) interface{} {
model := models.TgEventStaffAuthArea{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventStaffAuthBrand(args Args) interface{} {
model := models.TgEventStaffAuthBrand{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventStaffAuthUser(args Args) interface{} {
model := models.TgEventStaffAuthUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindEventUser(args Args) interface{} {
model := models.TgEventUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFab(args Args) interface{} {
model := models.TgFab{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFactory(args Args) interface{} {
model := models.TgFactory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFailedJobs(args Args) interface{} {
model := models.TgFailedJobs{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFeedback(args Args) interface{} {
model := models.TgFeedback{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFeedsIgnore(args Args) interface{} {
model := models.TgFeedsIgnore{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFeedsTopic(args Args) interface{} {
model := models.TgFeedsTopic{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFeedsUser(args Args) interface{} {
model := models.TgFeedsUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFollowGroup(args Args) interface{} {
model := models.TgFollowGroup{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriend(args Args) interface{} {
model := models.TgFriend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriendBuyinfo(args Args) interface{} {
model := models.TgFriendBuyinfo{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriendGroup(args Args) interface{} {
model := models.TgFriendGroup{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriendGroupAccess(args Args) interface{} {
model := models.TgFriendGroupAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriendLatent(args Args) interface{} {
model := models.TgFriendLatent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriendManageLog(args Args) interface{} {
model := models.TgFriendManageLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindFriendOrg(args Args) interface{} {
model := models.TgFriendOrg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGallery(args Args) interface{} {
model := models.TgGallery{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroup(args Args) interface{} {
model := models.TgGroup{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupAuthentication(args Args) interface{} {
model := models.TgGroupAuthentication{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupBlacklist(args Args) interface{} {
model := models.TgGroupBlacklist{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupCategory(args Args) interface{} {
model := models.TgGroupCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupInvitation(args Args) interface{} {
model := models.TgGroupInvitation{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupNotification(args Args) interface{} {
model := models.TgGroupNotification{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupNotificationRead(args Args) interface{} {
model := models.TgGroupNotificationRead{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupQrcode(args Args) interface{} {
model := models.TgGroupQrcode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupTag(args Args) interface{} {
model := models.TgGroupTag{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupTagAccess(args Args) interface{} {
model := models.TgGroupTagAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupUser(args Args) interface{} {
model := models.TgGroupUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindGroupUserKickOut(args Args) interface{} {
model := models.TgGroupUserKickOut{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindHelpQuestion(args Args) interface{} {
model := models.TgHelpQuestion{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindHotSearch(args Args) interface{} {
model := models.TgHotSearch{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindHotSearchExt(args Args) interface{} {
model := models.TgHotSearchExt{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindImg(args Args) interface{} {
model := models.TgImg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindImgTag(args Args) interface{} {
model := models.TgImgTag{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindImgType(args Args) interface{} {
model := models.TgImgType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindIndustry(args Args) interface{} {
model := models.TgIndustry{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindIndustryUser(args Args) interface{} {
model := models.TgIndustryUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindKoubei(args Args) interface{} {
model := models.TgKoubei{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindKoubeiAlbum(args Args) interface{} {
model := models.TgKoubeiAlbum{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindKoubeiSpider(args Args) interface{} {
model := models.TgKoubeiSpider{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLatentAutoset(args Args) interface{} {
model := models.TgLatentAutoset{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLatentDispense(args Args) interface{} {
model := models.TgLatentDispense{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLine(args Args) interface{} {
model := models.TgLine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNode(args Args) interface{} {
model := models.TgLineNode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNodeAlbum(args Args) interface{} {
model := models.TgLineNodeAlbum{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNodeComment(args Args) interface{} {
model := models.TgLineNodeComment{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNodeCommentMinutia(args Args) interface{} {
model := models.TgLineNodeCommentMinutia{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNodeCommentText(args Args) interface{} {
model := models.TgLineNodeCommentText{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNodePunchCensus(args Args) interface{} {
model := models.TgLineNodePunchCensus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLineNodeRelated(args Args) interface{} {
model := models.TgLineNodeRelated{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLiveMessage(args Args) interface{} {
model := models.TgLiveMessage{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLiveUser(args Args) interface{} {
model := models.TgLiveUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLogAdminLogin(args Args) interface{} {
model := models.TgLogAdminLogin{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLogAdminWork(args Args) interface{} {
model := models.TgLogAdminWork{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLottery(args Args) interface{} {
model := models.TgLottery{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryAuth(args Args) interface{} {
model := models.TgLotteryAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryConfig(args Args) interface{} {
model := models.TgLotteryConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryCron(args Args) interface{} {
model := models.TgLotteryCron{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNew(args Args) interface{} {
model := models.TgLotteryNew{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewAuth(args Args) interface{} {
model := models.TgLotteryNewAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewCodeBill(args Args) interface{} {
model := models.TgLotteryNewCodeBill{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewConfig(args Args) interface{} {
model := models.TgLotteryNewConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewCron(args Args) interface{} {
model := models.TgLotteryNewCron{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewLuckyCode(args Args) interface{} {
model := models.TgLotteryNewLuckyCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewOrder(args Args) interface{} {
model := models.TgLotteryNewOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewOrgCode(args Args) interface{} {
model := models.TgLotteryNewOrgCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewPrize(args Args) interface{} {
model := models.TgLotteryNewPrize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewRecord(args Args) interface{} {
model := models.TgLotteryNewRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewSet(args Args) interface{} {
model := models.TgLotteryNewSet{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewUser(args Args) interface{} {
model := models.TgLotteryNewUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryNewUserCode(args Args) interface{} {
model := models.TgLotteryNewUserCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryOrgCode(args Args) interface{} {
model := models.TgLotteryOrgCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryPart(args Args) interface{} {
model := models.TgLotteryPart{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryPrize(args Args) interface{} {
model := models.TgLotteryPrize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryRecord(args Args) interface{} {
model := models.TgLotteryRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryThread(args Args) interface{} {
model := models.TgLotteryThread{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryUser(args Args) interface{} {
model := models.TgLotteryUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLotteryUserCode(args Args) interface{} {
model := models.TgLotteryUserCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLoveChicken(args Args) interface{} {
model := models.TgLoveChicken{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindLoverUser(args Args) interface{} {
model := models.TgLoverUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMainWork(args Args) interface{} {
model := models.TgMainWork{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindManagementType(args Args) interface{} {
model := models.TgManagementType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindManualCode(args Args) interface{} {
model := models.TgManualCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindManualCodeOperationRecord(args Args) interface{} {
model := models.TgManualCodeOperationRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMenu(args Args) interface{} {
model := models.TgMenu{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMenuCopy(args Args) interface{} {
model := models.TgMenuCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessage(args Args) interface{} {
model := models.TgMessage{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageApp(args Args) interface{} {
model := models.TgMessageApp{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageEvent(args Args) interface{} {
model := models.TgMessageEvent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageEventUser(args Args) interface{} {
model := models.TgMessageEventUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageExtend(args Args) interface{} {
model := models.TgMessageExtend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageImg(args Args) interface{} {
model := models.TgMessageImg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageInteract(args Args) interface{} {
model := models.TgMessageInteract{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageInteractUser(args Args) interface{} {
model := models.TgMessageInteractUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageJike(args Args) interface{} {
model := models.TgMessageJike{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageJikeUser(args Args) interface{} {
model := models.TgMessageJikeUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageLabel(args Args) interface{} {
model := models.TgMessageLabel{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageLovecar(args Args) interface{} {
model := models.TgMessageLovecar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageLovecarUser(args Args) interface{} {
model := models.TgMessageLovecarUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageRecord(args Args) interface{} {
model := models.TgMessageRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageSetting(args Args) interface{} {
model := models.TgMessageSetting{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageStore(args Args) interface{} {
model := models.TgMessageStore{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageStoreUser(args Args) interface{} {
model := models.TgMessageStoreUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageType(args Args) interface{} {
model := models.TgMessageType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageTypeContent(args Args) interface{} {
model := models.TgMessageTypeContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageTypeCopy(args Args) interface{} {
model := models.TgMessageTypeCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMessageUrl(args Args) interface{} {
model := models.TgMessageUrl{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMsgBroker(args Args) interface{} {
model := models.TgMsgBroker{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMusic(args Args) interface{} {
model := models.TgMusic{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMusic1(args Args) interface{} {
model := models.TgMusic1{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindMusicType(args Args) interface{} {
model := models.TgMusicType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindNodePunchAuth(args Args) interface{} {
model := models.TgNodePunchAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindNodePunchConfirm(args Args) interface{} {
model := models.TgNodePunchConfirm{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOnlineserviceMute(args Args) interface{} {
model := models.TgOnlineserviceMute{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOnlineserviceOrder(args Args) interface{} {
model := models.TgOnlineserviceOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOperateActivity(args Args) interface{} {
model := models.TgOperateActivity{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOperateActivityCheck(args Args) interface{} {
model := models.TgOperateActivityCheck{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrder(args Args) interface{} {
model := models.TgOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrderMain(args Args) interface{} {
model := models.TgOrderMain{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrgBankCard(args Args) interface{} {
model := models.TgOrgBankCard{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrgMoney(args Args) interface{} {
model := models.TgOrgMoney{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrgMoneyBill(args Args) interface{} {
model := models.TgOrgMoneyBill{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrgMoneyRecharge(args Args) interface{} {
model := models.TgOrgMoneyRecharge{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrgMoneyWithdraw(args Args) interface{} {
model := models.TgOrgMoneyWithdraw{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganization(args Args) interface{} {
model := models.TgOrganization{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationActivity(args Args) interface{} {
model := models.TgOrganizationActivity{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationCar(args Args) interface{} {
model := models.TgOrganizationCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationCheck(args Args) interface{} {
model := models.TgOrganizationCheck{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationCheckInfo(args Args) interface{} {
model := models.TgOrganizationCheckInfo{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationConf(args Args) interface{} {
model := models.TgOrganizationConf{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationConfVal(args Args) interface{} {
model := models.TgOrganizationConfVal{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationCopy(args Args) interface{} {
model := models.TgOrganizationCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationCopyCopy(args Args) interface{} {
model := models.TgOrganizationCopyCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationFocus(args Args) interface{} {
model := models.TgOrganizationFocus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationLog(args Args) interface{} {
model := models.TgOrganizationLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationOrder(args Args) interface{} {
model := models.TgOrganizationOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationOrderpointsRecord(args Args) interface{} {
model := models.TgOrganizationOrderpointsRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationPrivilege(args Args) interface{} {
model := models.TgOrganizationPrivilege{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationPrivilegeShop(args Args) interface{} {
model := models.TgOrganizationPrivilegeShop{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationPrivilegeStore(args Args) interface{} {
model := models.TgOrganizationPrivilegeStore{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationTime(args Args) interface{} {
model := models.TgOrganizationTime{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindOrganizationType(args Args) interface{} {
model := models.TgOrganizationType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartner(args Args) interface{} {
model := models.TgPartner{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerBlacklist(args Args) interface{} {
model := models.TgPartnerBlacklist{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerInvite(args Args) interface{} {
model := models.TgPartnerInvite{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerLog(args Args) interface{} {
model := models.TgPartnerLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerPeriod(args Args) interface{} {
model := models.TgPartnerPeriod{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerQrcode(args Args) interface{} {
model := models.TgPartnerQrcode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerRegister(args Args) interface{} {
model := models.TgPartnerRegister{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerResults(args Args) interface{} {
model := models.TgPartnerResults{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPartnerTask(args Args) interface{} {
model := models.TgPartnerTask{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPayAlipayLog(args Args) interface{} {
model := models.TgPayAlipayLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPayWxLog(args Args) interface{} {
model := models.TgPayWxLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPhone(args Args) interface{} {
model := models.TgPhone{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPhoto(args Args) interface{} {
model := models.TgPhoto{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsData(args Args) interface{} {
model := models.TgPointsData{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsExceed(args Args) interface{} {
model := models.TgPointsExceed{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsExpRecords(args Args) interface{} {
model := models.TgPointsExpRecords{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsExpRules(args Args) interface{} {
model := models.TgPointsExpRules{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsGoods(args Args) interface{} {
model := models.TgPointsGoods{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsGoodsPay(args Args) interface{} {
model := models.TgPointsGoodsPay{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsLog(args Args) interface{} {
model := models.TgPointsLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsProduct(args Args) interface{} {
model := models.TgPointsProduct{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsProductRecords(args Args) interface{} {
model := models.TgPointsProductRecords{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsRanking(args Args) interface{} {
model := models.TgPointsRanking{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPointsSaleRules(args Args) interface{} {
model := models.TgPointsSaleRules{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPraise(args Args) interface{} {
model := models.TgPraise{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindProjectExamine(args Args) interface{} {
model := models.TgProjectExamine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPunch(args Args) interface{} {
model := models.TgPunch{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchase(args Args) interface{} {
model := models.TgPurchase{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchaseFactory(args Args) interface{} {
model := models.TgPurchaseFactory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchaseFail(args Args) interface{} {
model := models.TgPurchaseFail{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchaseImg(args Args) interface{} {
model := models.TgPurchaseImg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchaseRecords(args Args) interface{} {
model := models.TgPurchaseRecords{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchaseSms(args Args) interface{} {
model := models.TgPurchaseSms{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPurchaseUser(args Args) interface{} {
model := models.TgPurchaseUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindPushSmsConfig(args Args) interface{} {
model := models.TgPushSmsConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindQuestionnaire(args Args) interface{} {
model := models.TgQuestionnaire{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindQuestionnaireAnswer(args Args) interface{} {
model := models.TgQuestionnaireAnswer{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindQuestionnaireMain(args Args) interface{} {
model := models.TgQuestionnaireMain{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindQuestionnaireUser(args Args) interface{} {
model := models.TgQuestionnaireUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRabbitMsg(args Args) interface{} {
model := models.TgRabbitMsg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommend(args Args) interface{} {
model := models.TgRecommend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendAuth(args Args) interface{} {
model := models.TgRecommendAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendContent(args Args) interface{} {
model := models.TgRecommendContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201905(args Args) interface{} {
model := models.TgRecommendDetail201905{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201906(args Args) interface{} {
model := models.TgRecommendDetail201906{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201907(args Args) interface{} {
model := models.TgRecommendDetail201907{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201908(args Args) interface{} {
model := models.TgRecommendDetail201908{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201909(args Args) interface{} {
model := models.TgRecommendDetail201909{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201910(args Args) interface{} {
model := models.TgRecommendDetail201910{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201911(args Args) interface{} {
model := models.TgRecommendDetail201911{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendDetail201912(args Args) interface{} {
model := models.TgRecommendDetail201912{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendOrg(args Args) interface{} {
model := models.TgRecommendOrg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendPosition(args Args) interface{} {
model := models.TgRecommendPosition{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendPositionConfig(args Args) interface{} {
model := models.TgRecommendPositionConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendRecord(args Args) interface{} {
model := models.TgRecommendRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendTime(args Args) interface{} {
model := models.TgRecommendTime{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendTimeExtend(args Args) interface{} {
model := models.TgRecommendTimeExtend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendTongjiDay(args Args) interface{} {
model := models.TgRecommendTongjiDay{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRecommendTongjiMonth(args Args) interface{} {
model := models.TgRecommendTongjiMonth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpack(args Args) interface{} {
model := models.TgRedpack{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackArea(args Args) interface{} {
model := models.TgRedpackArea{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackCheckRecord(args Args) interface{} {
model := models.TgRedpackCheckRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackContent(args Args) interface{} {
model := models.TgRedpackContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackMsgRecord(args Args) interface{} {
model := models.TgRedpackMsgRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackOrg(args Args) interface{} {
model := models.TgRedpackOrg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackPosition(args Args) interface{} {
model := models.TgRedpackPosition{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackPrize(args Args) interface{} {
model := models.TgRedpackPrize{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackRecord(args Args) interface{} {
model := models.TgRedpackRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackRecordTemp(args Args) interface{} {
model := models.TgRedpackRecordTemp{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackTime(args Args) interface{} {
model := models.TgRedpackTime{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackUserCard(args Args) interface{} {
model := models.TgRedpackUserCard{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRedpackUserCardRecord(args Args) interface{} {
model := models.TgRedpackUserCardRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRegion(args Args) interface{} {
model := models.TgRegion{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindReport(args Args) interface{} {
model := models.TgReport{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindReportImg(args Args) interface{} {
model := models.TgReportImg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindReportRecord(args Args) interface{} {
model := models.TgReportRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRide(args Args) interface{} {
model := models.TgRide{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRideCheck(args Args) interface{} {
model := models.TgRideCheck{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRideCheckNotes(args Args) interface{} {
model := models.TgRideCheckNotes{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRideLine(args Args) interface{} {
model := models.TgRideLine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRideNode(args Args) interface{} {
model := models.TgRideNode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadBook(args Args) interface{} {
model := models.TgRoadBook{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadBookLine(args Args) interface{} {
model := models.TgRoadBookLine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadBookLineContent(args Args) interface{} {
model := models.TgRoadBookLineContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadBookMeet(args Args) interface{} {
model := models.TgRoadBookMeet{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadBookRecommend(args Args) interface{} {
model := models.TgRoadBookRecommend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouse(args Args) interface{} {
model := models.TgRoadbookArouse{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseAbnormal(args Args) interface{} {
model := models.TgRoadbookArouseAbnormal{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseAccount(args Args) interface{} {
model := models.TgRoadbookArouseAccount{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseAttend(args Args) interface{} {
model := models.TgRoadbookArouseAttend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseAttendCensus(args Args) interface{} {
model := models.TgRoadbookArouseAttendCensus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseFlow(args Args) interface{} {
model := models.TgRoadbookArouseFlow{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseLog(args Args) interface{} {
model := models.TgRoadbookArouseLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseRealAccount(args Args) interface{} {
model := models.TgRoadbookArouseRealAccount{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookArouseRelated(args Args) interface{} {
model := models.TgRoadbookArouseRelated{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookLine(args Args) interface{} {
model := models.TgRoadbookLine{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookMerchant(args Args) interface{} {
model := models.TgRoadbookMerchant{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookMerchantApply(args Args) interface{} {
model := models.TgRoadbookMerchantApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookMerchantInvite(args Args) interface{} {
model := models.TgRoadbookMerchantInvite{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRoadbookNodePunchCensus(args Args) interface{} {
model := models.TgRoadbookNodePunchCensus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRouletteLottery(args Args) interface{} {
model := models.TgRouletteLottery{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRouletteLotteryAttend(args Args) interface{} {
model := models.TgRouletteLotteryAttend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindRouletteLotteryAward(args Args) interface{} {
model := models.TgRouletteLotteryAward{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSaleinfoOrg(args Args) interface{} {
model := models.TgSaleinfoOrg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSalerStar(args Args) interface{} {
model := models.TgSalerStar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSearchLog(args Args) interface{} {
model := models.TgSearchLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSeries(args Args) interface{} {
model := models.TgSeries{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindServiceCity(args Args) interface{} {
model := models.TgServiceCity{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSmsApiLog(args Args) interface{} {
model := models.TgSmsApiLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSmsTemplate(args Args) interface{} {
model := models.TgSmsTemplate{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSmsTemplateLog(args Args) interface{} {
model := models.TgSmsTemplateLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSmsTotal(args Args) interface{} {
model := models.TgSmsTotal{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSmsVerifyCode(args Args) interface{} {
model := models.TgSmsVerifyCode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpecial(args Args) interface{} {
model := models.TgSpecial{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmAppDownloadLog(args Args) interface{} {
model := models.TgSpmAppDownloadLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmBaidurefererLog(args Args) interface{} {
model := models.TgSpmBaidurefererLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmCate(args Args) interface{} {
model := models.TgSpmCate{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmDesignation(args Args) interface{} {
model := models.TgSpmDesignation{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmKeywords(args Args) interface{} {
model := models.TgSpmKeywords{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmLog(args Args) interface{} {
model := models.TgSpmLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmLogCopy(args Args) interface{} {
model := models.TgSpmLogCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmParameter(args Args) interface{} {
model := models.TgSpmParameter{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmPlace(args Args) interface{} {
model := models.TgSpmPlace{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSpmPromoter(args Args) interface{} {
model := models.TgSpmPromoter{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindStaff(args Args) interface{} {
model := models.TgStaff{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindStatistics(args Args) interface{} {
model := models.TgStatistics{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindSupertopicApply(args Args) interface{} {
model := models.TgSupertopicApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTagCar(args Args) interface{} {
model := models.TgTagCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTagCartSpecific(args Args) interface{} {
model := models.TgTagCartSpecific{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTags(args Args) interface{} {
model := models.TgTags{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTagsCategory(args Args) interface{} {
model := models.TgTagsCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTagscategory(args Args) interface{} {
model := models.TgTagscategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivity(args Args) interface{} {
model := models.TgThreadActivity{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivityApply(args Args) interface{} {
model := models.TgThreadActivityApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivityCar(args Args) interface{} {
model := models.TgThreadActivityCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivityMaster(args Args) interface{} {
model := models.TgThreadActivityMaster{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivityScene(args Args) interface{} {
model := models.TgThreadActivityScene{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivityType(args Args) interface{} {
model := models.TgThreadActivityType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadActivityUser(args Args) interface{} {
model := models.TgThreadActivityUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadAsk(args Args) interface{} {
model := models.TgThreadAsk{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadAskAnswer(args Args) interface{} {
model := models.TgThreadAskAnswer{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadAskAnswerFollow(args Args) interface{} {
model := models.TgThreadAskAnswerFollow{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadCensusRanking(args Args) interface{} {
model := models.TgThreadCensusRanking{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadCycle(args Args) interface{} {
model := models.TgThreadCycle{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadDeleteReason(args Args) interface{} {
model := models.TgThreadDeleteReason{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadEvaluate(args Args) interface{} {
model := models.TgThreadEvaluate{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadEvaluateCar(args Args) interface{} {
model := models.TgThreadEvaluateCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadGoods(args Args) interface{} {
model := models.TgThreadGoods{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadGoodsCategory(args Args) interface{} {
model := models.TgThreadGoodsCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadIntegralLog(args Args) interface{} {
model := models.TgThreadIntegralLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadMastersay(args Args) interface{} {
model := models.TgThreadMastersay{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadMastersayCar(args Args) interface{} {
model := models.TgThreadMastersayCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadMood(args Args) interface{} {
model := models.TgThreadMood{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadPlay(args Args) interface{} {
model := models.TgThreadPlay{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadRoadbookAnnex(args Args) interface{} {
model := models.TgThreadRoadbookAnnex{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadRoadbookLineBeen(args Args) interface{} {
model := models.TgThreadRoadbookLineBeen{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadRoadbookLineRelated(args Args) interface{} {
model := models.TgThreadRoadbookLineRelated{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadRoadbookNoteUser(args Args) interface{} {
model := models.TgThreadRoadbookNoteUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadRoadbookPunchCensus(args Args) interface{} {
model := models.TgThreadRoadbookPunchCensus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadShow(args Args) interface{} {
model := models.TgThreadShow{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadTopic(args Args) interface{} {
model := models.TgThreadTopic{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadTopicAccess(args Args) interface{} {
model := models.TgThreadTopicAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadTopicApply(args Args) interface{} {
model := models.TgThreadTopicApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadTopicFans(args Args) interface{} {
model := models.TgThreadTopicFans{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadVisible(args Args) interface{} {
model := models.TgThreadVisible{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadWordColumn(args Args) interface{} {
model := models.TgThreadWordColumn{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindThreadWords(args Args) interface{} {
model := models.TgThreadWords{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicket(args Args) interface{} {
model := models.TgTicket{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketApiLog(args Args) interface{} {
model := models.TgTicketApiLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketApplyUser(args Args) interface{} {
model := models.TgTicketApplyUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketCheckRecord(args Args) interface{} {
model := models.TgTicketCheckRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketCheckoutAuth(args Args) interface{} {
model := models.TgTicketCheckoutAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketFree(args Args) interface{} {
model := models.TgTicketFree{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketFreeHandout(args Args) interface{} {
model := models.TgTicketFreeHandout{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketNumsRecord(args Args) interface{} {
model := models.TgTicketNumsRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketPaperRecord(args Args) interface{} {
model := models.TgTicketPaperRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketQd(args Args) interface{} {
model := models.TgTicketQd{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketQdSale(args Args) interface{} {
model := models.TgTicketQdSale{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketRedpack(args Args) interface{} {
model := models.TgTicketRedpack{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketRedpackLog(args Args) interface{} {
model := models.TgTicketRedpackLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketRefund(args Args) interface{} {
model := models.TgTicketRefund{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketRefundLog(args Args) interface{} {
model := models.TgTicketRefundLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketSendRecord(args Args) interface{} {
model := models.TgTicketSendRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketThirdParty(args Args) interface{} {
model := models.TgTicketThirdParty{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTicketUser(args Args) interface{} {
model := models.TgTicketUser{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTmpData(args Args) interface{} {
model := models.TgTmpData{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTopicCategory(args Args) interface{} {
model := models.TgTopicCategory{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTopicExpLog(args Args) interface{} {
model := models.TgTopicExpLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTopicLog(args Args) interface{} {
model := models.TgTopicLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTopicScompere(args Args) interface{} {
model := models.TgTopicScompere{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTopicSignin(args Args) interface{} {
model := models.TgTopicSignin{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTrafficStatistics(args Args) interface{} {
model := models.TgTrafficStatistics{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTrafficStatisticsLog(args Args) interface{} {
model := models.TgTrafficStatisticsLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTrafficStatisticsLogGroup(args Args) interface{} {
model := models.TgTrafficStatisticsLogGroup{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTwitter(args Args) interface{} {
model := models.TgTwitter{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTwitterAlbum(args Args) interface{} {
model := models.TgTwitterAlbum{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTwitterSource(args Args) interface{} {
model := models.TgTwitterSource{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTwitterTopicAccess(args Args) interface{} {
model := models.TgTwitterTopicAccess{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindTwitterVisibility(args Args) interface{} {
model := models.TgTwitterVisibility{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUploadApk(args Args) interface{} {
model := models.TgUploadApk{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserBankCard(args Args) interface{} {
model := models.TgUserBankCard{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserBehaviour(args Args) interface{} {
model := models.TgUserBehaviour{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserCar(args Args) interface{} {
model := models.TgUserCar{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserFollow(args Args) interface{} {
model := models.TgUserFollow{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserPoints(args Args) interface{} {
model := models.TgUserPoints{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserRecommend(args Args) interface{} {
model := models.TgUserRecommend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindUserSetting(args Args) interface{} {
model := models.TgUserSetting{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideo(args Args) interface{} {
model := models.TgVideo{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideoAttach(args Args) interface{} {
model := models.TgVideoAttach{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideoAttachReceive(args Args) interface{} {
model := models.TgVideoAttachReceive{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideoLog(args Args) interface{} {
model := models.TgVideoLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideoNotice(args Args) interface{} {
model := models.TgVideoNotice{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideoRecommendTable(args Args) interface{} {
model := models.TgVideoRecommendTable{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVideoVisible(args Args) interface{} {
model := models.TgVideoVisible{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVirtualNickname(args Args) interface{} {
model := models.TgVirtualNickname{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindVirtualRecord(args Args) interface{} {
model := models.TgVirtualRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWannaBuy(args Args) interface{} {
model := models.TgWannaBuy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeatherCitys(args Args) interface{} {
model := models.TgWeatherCitys{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeatherToday(args Args) interface{} {
model := models.TgWeatherToday{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinConfig(args Args) interface{} {
model := models.TgWeixinConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinCustomSend(args Args) interface{} {
model := models.TgWeixinCustomSend{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinKerword(args Args) interface{} {
model := models.TgWeixinKerword{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinMaterial(args Args) interface{} {
model := models.TgWeixinMaterial{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinMenu(args Args) interface{} {
model := models.TgWeixinMenu{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPush(args Args) interface{} {
model := models.TgWeixinPush{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPushAuto(args Args) interface{} {
model := models.TgWeixinPushAuto{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPushConfig(args Args) interface{} {
model := models.TgWeixinPushConfig{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPushInteractive(args Args) interface{} {
model := models.TgWeixinPushInteractive{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPushMaterial(args Args) interface{} {
model := models.TgWeixinPushMaterial{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPushRecord(args Args) interface{} {
model := models.TgWeixinPushRecord{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinPushTag(args Args) interface{} {
model := models.TgWeixinPushTag{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinQrcode(args Args) interface{} {
model := models.TgWeixinQrcode{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinQrcodeScanLog(args Args) interface{} {
model := models.TgWeixinQrcodeScanLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindWeixinTemplate(args Args) interface{} {
model := models.TgWeixinTemplate{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXc1Jurisdiction(args Args) interface{} {
model := models.TgXc1Jurisdiction{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXc1ManageObject(args Args) interface{} {
model := models.TgXc1ManageObject{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXc1Org2scene(args Args) interface{} {
model := models.TgXc1Org2scene{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXc1Worker2guest(args Args) interface{} {
model := models.TgXc1Worker2guest{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcAppMessage(args Args) interface{} {
model := models.TgXcAppMessage{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcAppMessageCount(args Args) interface{} {
model := models.TgXcAppMessageCount{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcApplyItem(args Args) interface{} {
model := models.TgXcApplyItem{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcApplyType(args Args) interface{} {
model := models.TgXcApplyType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcArea(args Args) interface{} {
model := models.TgXcArea{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcAuthMapping(args Args) interface{} {
model := models.TgXcAuthMapping{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcAuthorise(args Args) interface{} {
model := models.TgXcAuthorise{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcCheckCourse(args Args) interface{} {
model := models.TgXcCheckCourse{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcCheckTable(args Args) interface{} {
model := models.TgXcCheckTable{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcChecker2object(args Args) interface{} {
model := models.TgXcChecker2object{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcFriends(args Args) interface{} {
model := models.TgXcFriends{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcGuest2object(args Args) interface{} {
model := models.TgXcGuest2object{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcJobType(args Args) interface{} {
model := models.TgXcJobType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessage(args Args) interface{} {
model := models.TgXcMessage{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessageAddtask(args Args) interface{} {
model := models.TgXcMessageAddtask{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessageApply(args Args) interface{} {
model := models.TgXcMessageApply{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessageContent(args Args) interface{} {
model := models.TgXcMessageContent{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessageRectification(args Args) interface{} {
model := models.TgXcMessageRectification{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessageSetting(args Args) interface{} {
model := models.TgXcMessageSetting{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcMessageUnqualifiedcheck(args Args) interface{} {
model := models.TgXcMessageUnqualifiedcheck{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcObject(args Args) interface{} {
model := models.TgXcObject{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcObject2dispose(args Args) interface{} {
model := models.TgXcObject2dispose{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcObjectOrganization(args Args) interface{} {
model := models.TgXcObjectOrganization{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcObjectType(args Args) interface{} {
model := models.TgXcObjectType{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcOffsetTriggerTime(args Args) interface{} {
model := models.TgXcOffsetTriggerTime{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcOrder(args Args) interface{} {
model := models.TgXcOrder{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcOrderProgress(args Args) interface{} {
model := models.TgXcOrderProgress{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcOrganization(args Args) interface{} {
model := models.TgXcOrganization{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcPayLog(args Args) interface{} {
model := models.TgXcPayLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcPermission(args Args) interface{} {
model := models.TgXcPermission{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcScene(args Args) interface{} {
model := models.TgXcScene{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcSceneReview(args Args) interface{} {
model := models.TgXcSceneReview{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcStaff2object(args Args) interface{} {
model := models.TgXcStaff2object{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTask(args Args) interface{} {
model := models.TgXcTask{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTaskCopy(args Args) interface{} {
model := models.TgXcTaskCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTaskDis(args Args) interface{} {
model := models.TgXcTaskDis{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTaskDisimg(args Args) interface{} {
model := models.TgXcTaskDisimg{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTaskLog(args Args) interface{} {
model := models.TgXcTaskLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTaskPackage(args Args) interface{} {
model := models.TgXcTaskPackage{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcTopUpLog(args Args) interface{} {
model := models.TgXcTopUpLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcUser2scene(args Args) interface{} {
model := models.TgXcUser2scene{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcUsercoordinate(args Args) interface{} {
model := models.TgXcUsercoordinate{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcWorker(args Args) interface{} {
model := models.TgXcWorker{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcWorker2area(args Args) interface{} {
model := models.TgXcWorker2area{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindXcWorkerYanghuanBack(args Args) interface{} {
model := models.TgXcWorkerYanghuanBack{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyao(args Args) interface{} {
model := models.TgYaoyiyao{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoAuth(args Args) interface{} {
model := models.TgYaoyiyaoAuth{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoAwards(args Args) interface{} {
model := models.TgYaoyiyaoAwards{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoAwardsCopy(args Args) interface{} {
model := models.TgYaoyiyaoAwardsCopy{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoCacheawards(args Args) interface{} {
model := models.TgYaoyiyaoCacheawards{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoEndLog(args Args) interface{} {
model := models.TgYaoyiyaoEndLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoNotWin(args Args) interface{} {
model := models.TgYaoyiyaoNotWin{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoPassLog(args Args) interface{} {
model := models.TgYaoyiyaoPassLog{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoRank(args Args) interface{} {
model := models.TgYaoyiyaoRank{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoRotary(args Args) interface{} {
model := models.TgYaoyiyaoRotary{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoSignin(args Args) interface{} {
model := models.TgYaoyiyaoSignin{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
}
func BindYaoyiyaoStatus(args Args) interface{} {
model := models.TgYaoyiyaoStatus{}
if args != nil{
mapstructure.Decode(args, &model)
}
return model
} |
package main
import (
"errors"
"github.com/sirupsen/logrus"
"github.com/snwfdhmp/errlog"
)
var (
debug = errlog.NewLogger(&errlog.Config{
PrintFunc: logrus.Errorf,
LinesBefore: 6,
LinesAfter: 3,
PrintError: true,
PrintSource: true,
PrintStack: true,
ExitOnDebugSuccess: true,
})
)
func main() {
logrus.Print("Start of the program")
wrapingFunc()
logrus.Print("End of the program")
}
func wrapingFunc() {
someBigFunction()
}
func someBigFunction() {
someDumbFunction()
someSmallFunction()
err := someNastyFunction()
someDumbFunction()
if debug.Debug(err) {
return
}
someSmallFunction()
someDumbFunction()
}
func someSmallFunction() {
logrus.Print("I do things !")
}
func someNastyFunction() error {
return errors.New("I'm failing for no reason")
}
func someDumbFunction() bool {
return false
}
|
package cmd
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"reflect"
"time"
"github.com/Azure/azure-pipeline-go/pipeline"
"github.com/Azure/azure-storage-azcopy/azbfs"
"github.com/Azure/azure-storage-blob-go/2016-05-31/azblob"
"github.com/Azure/azure-storage-file-go/2017-07-29/azfile"
"github.com/JeffreyRichter/enum/enum"
"github.com/spf13/cobra"
)
var EResourceType = ResourceType(0)
// ResourceType defines the different types of credentials
type ResourceType uint8
func (ResourceType) SingleFile() ResourceType { return ResourceType(0) }
func (ResourceType) Bucket() ResourceType { return ResourceType(1) }
func (ResourceType) Account() ResourceType { return ResourceType(2) } // For SAS or public.
func (ct ResourceType) String() string {
return enum.StringInt(ct, reflect.TypeOf(ct))
}
func (ct *ResourceType) Parse(s string) error {
val, err := enum.ParseInt(reflect.TypeOf(ct), s, true, true)
if err == nil {
*ct = val.(ResourceType)
}
return err
}
var EServiceType = ServiceType(0)
// ServiceType defines the different types of credentials
type ServiceType uint8
func (ServiceType) Blob() ServiceType { return ServiceType(0) }
func (ServiceType) File() ServiceType { return ServiceType(1) }
func (ServiceType) BlobFS() ServiceType { return ServiceType(2) } // For SAS or public.
func (ct ServiceType) String() string {
return enum.StringInt(ct, reflect.TypeOf(ct))
}
func (ct *ServiceType) Parse(s string) error {
val, err := enum.ParseInt(reflect.TypeOf(ct), s, true, true)
if err == nil {
*ct = val.(ServiceType)
}
return err
}
// initializes the clean command, its aliases and description.
func init() {
resourceURL := ""
serviceType := EServiceType.Blob()
resourceType := EResourceType.SingleFile()
var serviceTypeStr string
var resourceTypeStr string
cleanCmd := &cobra.Command{
Use: "clean",
Aliases: []string{"clean"},
Short: "clean deletes everything inside the container.",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("invalid arguments for clean command")
}
resourceURL = args[0]
return nil
},
Run: func(cmd *cobra.Command, args []string) {
err := (&serviceType).Parse(serviceTypeStr)
if err != nil {
panic(fmt.Errorf("fail to parse service type %q, %v", serviceTypeStr, err))
}
err = (&resourceType).Parse(resourceTypeStr)
if err != nil {
panic(fmt.Errorf("fail to parse resource type %q, %v", resourceTypeStr, err))
}
switch serviceType {
case EServiceType.Blob():
switch resourceType {
case EResourceType.Bucket():
cleanContainer(resourceURL)
case EResourceType.SingleFile():
cleanBlob(resourceURL)
case EResourceType.Account():
cleanBlobAccount(resourceURL)
}
case EServiceType.File():
switch resourceType {
case EResourceType.Bucket():
cleanShare(resourceURL)
case EResourceType.SingleFile():
cleanFile(resourceURL)
case EResourceType.Account():
cleanFileAccount(resourceURL)
}
case EServiceType.BlobFS():
switch resourceType {
case EResourceType.Bucket():
cleanFileSystem(resourceURL)
case EResourceType.SingleFile():
cleanBfsFile(resourceURL)
case EResourceType.Account():
cleanBfsAccount(resourceURL)
}
default:
panic(fmt.Errorf("illegal resourceType %q", resourceType))
}
},
}
rootCmd.AddCommand(cleanCmd)
cleanCmd.PersistentFlags().StringVar(&resourceTypeStr, "resourceType", "SingleFile", "Resource type, could be single file, bucket or account currently.")
cleanCmd.PersistentFlags().StringVar(&serviceTypeStr, "serviceType", "Blob", "Account type, could be blob, file or blobFS currently.")
}
func cleanContainer(container string) {
containerSas, err := url.Parse(container)
if err != nil {
fmt.Println("error parsing the container sas, ", err)
os.Exit(1)
}
p := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{})
containerUrl := azblob.NewContainerURL(*containerSas, p)
// perform a list blob
for marker := (azblob.Marker{}); marker.NotDone(); {
// look for all blobs that start with the prefix, so that if a blob is under the virtual directory, it will show up
listBlob, err := containerUrl.ListBlobs(context.Background(), marker, azblob.ListBlobsOptions{})
if err != nil {
fmt.Println("error listing blobs inside the container. Please check the container sas")
os.Exit(1)
}
// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
for _, blobInfo := range listBlob.Blobs.Blob {
_, err := containerUrl.NewBlobURL(blobInfo.Name).Delete(context.Background(), "include", azblob.BlobAccessConditions{})
if err != nil {
fmt.Println("error deleting the blob from container ", blobInfo.Name)
os.Exit(1)
}
}
marker = listBlob.NextMarker
}
}
func cleanBlob(blob string) {
blobSas, err := url.Parse(blob)
if err != nil {
fmt.Println("error parsing the container sas ", err)
os.Exit(1)
}
p := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{})
blobUrl := azblob.NewBlobURL(*blobSas, p)
_, err = blobUrl.Delete(context.Background(), "include", azblob.BlobAccessConditions{})
if err != nil {
fmt.Println("error deleting the blob ", err)
os.Exit(1)
}
}
func cleanShare(shareURLStr string) {
u, err := url.Parse(shareURLStr)
if err != nil {
fmt.Println("error parsing the share URL with SAS ", err)
os.Exit(1)
}
p := azfile.NewPipeline(azfile.NewAnonymousCredential(), azfile.PipelineOptions{})
shareURL := azfile.NewShareURL(*u, p)
_, err = shareURL.Delete(context.Background(), azfile.DeleteSnapshotsOptionInclude)
if err != nil {
sErr := err.(azfile.StorageError)
if sErr != nil && sErr.Response().StatusCode != http.StatusNotFound {
fmt.Fprintf(os.Stdout, "error deleting the share for clean share, error '%v'\n", err)
os.Exit(1)
}
}
// Sleep seconds to wait the share deletion got succeeded
time.Sleep(45 * time.Second)
_, err = shareURL.Create(context.Background(), azfile.Metadata{}, 0)
if err != nil {
fmt.Fprintf(os.Stdout, "error creating the share for clean share, error '%v'\n", err)
os.Exit(1)
}
}
func cleanFile(fileURLStr string) {
u, err := url.Parse(fileURLStr)
if err != nil {
fmt.Println("error parsing the file URL with SAS", err)
os.Exit(1)
}
p := azfile.NewPipeline(azfile.NewAnonymousCredential(), azfile.PipelineOptions{})
fileURL := azfile.NewFileURL(*u, p)
_, err = fileURL.Delete(context.Background())
if err != nil {
fmt.Println("error deleting the file ", err)
os.Exit(1)
}
}
func createBlobFSPipeline() pipeline.Pipeline {
// Get the Account Name and Key variables from environment
name := os.Getenv("ACCOUNT_NAME")
key := os.Getenv("ACCOUNT_KEY")
// If the ACCOUNT_NAME and ACCOUNT_KEY are not set in environment variables
if name == "" || key == "" {
fmt.Println("ACCOUNT_NAME and ACCOUNT_KEY should be set before cleaning the file system")
os.Exit(1)
}
// create the blob fs pipeline
c := azbfs.NewSharedKeyCredential(name, key)
return azbfs.NewPipeline(c, azbfs.PipelineOptions{})
}
func cleanFileSystem(fsURLStr string) {
ctx := context.Background()
u, err := url.Parse(fsURLStr)
if err != nil {
fmt.Println("error parsing the file system URL", err)
os.Exit(1)
}
fsURL := azbfs.NewFileSystemURL(*u, createBlobFSPipeline())
_, err = fsURL.Delete(ctx)
if err != nil {
sErr := err.(azbfs.StorageError)
if sErr != nil && sErr.Response().StatusCode != http.StatusNotFound {
fmt.Println(fmt.Sprintf("error deleting the file system for cleaning, %v", err))
os.Exit(1)
}
}
// Sleep seconds to wait the share deletion got succeeded
time.Sleep(45 * time.Second)
_, err = fsURL.Create(ctx)
if err != nil {
fmt.Println(fmt.Fprintf(os.Stdout, "error creating the file system for cleaning, %v", err))
os.Exit(1)
}
}
func cleanBfsFile(fileURLStr string) {
ctx := context.Background()
u, err := url.Parse(fileURLStr)
if err != nil {
fmt.Println("error parsing the file system URL, ", err)
os.Exit(1)
}
fileURL := azbfs.NewFileURL(*u, createBlobFSPipeline())
_, err = fileURL.Delete(ctx)
if err != nil {
fmt.Println(fmt.Sprintf("error deleting the blob FS file, %v", err))
os.Exit(1)
}
}
func cleanBlobAccount(resourceURL string) {
accountSAS, err := url.Parse(resourceURL)
if err != nil {
fmt.Println("error parsing the account sas ", err)
os.Exit(1)
}
p := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{})
accountURL := azblob.NewServiceURL(*accountSAS, p)
// perform a list account
for marker := (azblob.Marker{}); marker.NotDone(); {
// look for all blobs that start with the prefix, so that if a blob is under the virtual directory, it will show up
lResp, err := accountURL.ListContainers(context.Background(), marker, azblob.ListContainersOptions{})
if err != nil {
fmt.Println("error listing containers inside the container. Please check the container sas")
os.Exit(1)
}
for _, containerItem := range lResp.Containers {
_, err := accountURL.NewContainerURL(containerItem.Name).Delete(context.Background(), azblob.ContainerAccessConditions{})
if err != nil {
fmt.Println("error deleting the container from account, ", err)
os.Exit(1)
}
}
marker = lResp.NextMarker
}
}
func cleanFileAccount(resourceURL string) {
panic("not implemented")
}
func cleanBfsAccount(resourceURL string) {
panic("not implemented")
}
|
package main
import (
"encoding/json"
"errors"
"flag"
"net/http"
"os"
"reflect"
"sort"
"time"
"github.com/unixpickle/essentials"
"github.com/unixpickle/pecunia/pecunia"
)
type Server struct {
Storage pecunia.Storage
}
func main() {
var addr string
var assets string
var dataDir string
flag.StringVar(&addr, "addr", ":8080", "address to listen on")
flag.StringVar(&assets, "assets", "./assets", "asset directory")
flag.StringVar(&dataDir, "data-dir", "pecunia_data", "directory to store data")
flag.Parse()
if _, err := os.Stat(dataDir); os.IsNotExist(err) {
essentials.Must(os.Mkdir(dataDir, 0755))
}
server := &Server{Storage: &pecunia.DirStorage{Dir: dataDir}}
fs := http.FileServer(http.Dir(assets))
http.Handle("/", fs)
http.HandleFunc("/accounts", DisableCache(server.ServeAccounts))
http.HandleFunc("/account", DisableCache(server.ServeAccount))
http.HandleFunc("/add_account", DisableCache(server.ServeAddAccount))
http.HandleFunc("/delete_account", DisableCache(server.ServeDeleteAccount))
http.HandleFunc("/clear_account", DisableCache(server.ServeClearAccount))
http.HandleFunc("/all_transactions", DisableCache(server.ServeAllTransactions))
http.HandleFunc("/transactions", DisableCache(server.ServeTransactions))
http.HandleFunc("/upload_transactions", DisableCache(server.ServeUploadTransactions))
http.HandleFunc("/account_filters", DisableCache(server.ServeAccountFilters))
http.HandleFunc("/set_account_filters", DisableCache(server.ServeSetAccountFilters))
http.HandleFunc("/global_filters", DisableCache(server.ServeGlobalFilters))
http.HandleFunc("/set_global_filters", DisableCache(server.ServeSetGlobalFilters))
essentials.Must(http.ListenAndServe(addr, nil))
}
func (s *Server) ServeAccounts(w http.ResponseWriter, r *http.Request) {
accounts, err := s.Storage.Accounts()
if err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
s.serveObject(w, accounts)
}
func (s *Server) ServeAccount(w http.ResponseWriter, r *http.Request) {
accountID := r.FormValue("account_id")
if account, err := pecunia.AccountForID(s.Storage, accountID); err != nil {
s.serveError(w, err, http.StatusBadRequest)
} else {
s.serveObject(w, account)
}
}
func (s *Server) ServeAddAccount(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
importer := r.FormValue("importer")
if name == "" {
s.serveError(w, errors.New("name is empty"), http.StatusBadRequest)
return
}
if _, err := pecunia.ImporterForID(importer); err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
if account, err := s.Storage.AddAccount(name, importer); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
} else {
s.serveObject(w, account)
}
}
func (s *Server) ServeDeleteAccount(w http.ResponseWriter, r *http.Request) {
accountID := r.FormValue("account_id")
if err := s.Storage.DeleteAccount(accountID); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
} else {
s.serveObject(w, "ok")
}
}
func (s *Server) ServeClearAccount(w http.ResponseWriter, r *http.Request) {
accountID := r.FormValue("account_id")
if err := s.Storage.SetTransactions(accountID, []*pecunia.Transaction{}); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
} else {
s.serveObject(w, []*pecunia.Transaction{})
}
}
func (s *Server) ServeAllTransactions(w http.ResponseWriter, r *http.Request) {
transactions := []*pecunia.Transaction{}
accts, err := s.Storage.Accounts()
if err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
for _, acct := range accts {
trans, err := s.Storage.Transactions(acct.ID)
if err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
filter, err := s.Storage.AccountFilters(acct.ID)
if err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
for t := range filter.Filter(pecunia.TransactionsToChan(trans)) {
transactions = append(transactions, t)
}
}
sort.SliceStable(transactions, func(i, j int) bool {
return transactions[i].Time.UnixNano() < transactions[j].Time.UnixNano()
})
globalFilters, err := s.Storage.GlobalFilters()
if err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
transactions = pecunia.TransactionsToSlice(
globalFilters.Filter(pecunia.TransactionsToChan(transactions)),
)
s.serveObject(w, transactions)
}
func (s *Server) ServeTransactions(w http.ResponseWriter, r *http.Request) {
accountID := r.FormValue("account_id")
if trans, err := s.Storage.Transactions(accountID); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
} else {
s.serveObject(w, trans)
}
}
func (s *Server) ServeUploadTransactions(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(2000000)
accountID := r.FormValue("account_id")
account, err := pecunia.AccountForID(s.Storage, accountID)
if err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
importer, err := pecunia.ImporterForID(account.ImporterID)
if err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
file, _, err := r.FormFile("document")
if err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
defer file.Close()
existing, err := s.Storage.Transactions(accountID)
if err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
trans, err := importer.Merge(file, existing)
if err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
if err := s.Storage.SetTransactions(accountID, trans); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
s.serveObject(w, trans)
}
func (s *Server) ServeAccountFilters(w http.ResponseWriter, r *http.Request) {
accountID := r.FormValue("account_id")
if filters, err := s.Storage.AccountFilters(accountID); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
} else {
s.serveObject(w, filters)
}
}
func (s *Server) ServeSetAccountFilters(w http.ResponseWriter, r *http.Request) {
accountID := r.FormValue("account_id")
filterJSON := r.FormValue("filters")
var filters pecunia.MultiFilter
if err := json.Unmarshal([]byte(filterJSON), &filters); err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
if err := s.Storage.SetAccountFilters(accountID, &filters); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
s.serveObject(w, &filters)
}
func (s *Server) ServeGlobalFilters(w http.ResponseWriter, r *http.Request) {
if filters, err := s.Storage.GlobalFilters(); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
} else {
s.serveObject(w, filters)
}
}
func (s *Server) ServeSetGlobalFilters(w http.ResponseWriter, r *http.Request) {
filterJSON := r.FormValue("filters")
var filters pecunia.MultiFilter
if err := json.Unmarshal([]byte(filterJSON), &filters); err != nil {
s.serveError(w, err, http.StatusBadRequest)
return
}
if err := s.Storage.SetGlobalFilters(&filters); err != nil {
s.serveError(w, err, http.StatusInternalServerError)
return
}
s.serveObject(w, &filters)
}
func (s *Server) serveError(w http.ResponseWriter, err error, status int) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
"status": status,
"result": nil,
})
}
func (s *Server) serveObject(w http.ResponseWriter, obj interface{}) {
value := reflect.ValueOf(obj)
if value.Type().Kind() == reflect.Slice {
if value.Len() == 0 {
// Prevent null values in JSON object.
obj = []interface{}{}
}
}
w.Header().Set("content-type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"error": nil,
"status": http.StatusOK,
"result": obj,
})
}
func DisableCache(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// https://stackoverflow.com/questions/33880343/go-webserver-dont-cache-files-using-timestamp
// https://gist.github.com/alxshelepenok/0d5c2fb110e19203655e04f4a52e9d87
headers := map[string]string{
"Expires": time.Unix(0, 0).Format(time.RFC1123),
"Cache-Control": "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
}
for k, v := range headers {
w.Header().Set(k, v)
}
f(w, r)
}
}
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/google/subcommands"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/runsc/cmd/util"
"gvisor.dev/gvisor/runsc/config"
"gvisor.dev/gvisor/runsc/container"
"gvisor.dev/gvisor/runsc/flag"
)
// Kill implements subcommands.Command for the "kill" command.
type Kill struct {
all bool
pid int
}
// Name implements subcommands.Command.Name.
func (*Kill) Name() string {
return "kill"
}
// Synopsis implements subcommands.Command.Synopsis.
func (*Kill) Synopsis() string {
return "sends a signal to the container"
}
// Usage implements subcommands.Command.Usage.
func (*Kill) Usage() string {
return `kill <container id> [signal]`
}
// SetFlags implements subcommands.Command.SetFlags.
func (k *Kill) SetFlags(f *flag.FlagSet) {
f.BoolVar(&k.all, "all", false, "send the specified signal to all processes inside the container")
f.IntVar(&k.pid, "pid", 0, "send the specified signal to a specific process. pid is relative to the root PID namespace")
}
// Execute implements subcommands.Command.Execute.
func (k *Kill) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcommands.ExitStatus {
if f.NArg() == 0 || f.NArg() > 2 {
f.Usage()
return subcommands.ExitUsageError
}
id := f.Arg(0)
conf := args[0].(*config.Config)
if k.pid != 0 && k.all {
util.Fatalf("it is invalid to specify both --all and --pid")
}
c, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})
if err != nil {
util.Fatalf("loading container: %v", err)
}
// The OCI command-line spec says that the signal should be specified
// via a flag, but runc (and things that call runc) pass it as an
// argument.
signal := f.Arg(1)
if signal == "" {
signal = "TERM"
}
sig, err := parseSignal(signal)
if err != nil {
util.Fatalf("%v", err)
}
if k.pid != 0 {
if err := c.SignalProcess(sig, int32(k.pid)); err != nil {
util.Fatalf("failed to signal pid %d: %v", k.pid, err)
}
} else {
if err := c.SignalContainer(sig, k.all); err != nil {
util.Fatalf("%v", err)
}
}
return subcommands.ExitSuccess
}
func parseSignal(s string) (unix.Signal, error) {
n, err := strconv.Atoi(s)
if err == nil {
sig := unix.Signal(n)
for _, msig := range signalMap {
if sig == msig {
return sig, nil
}
}
return -1, fmt.Errorf("unknown signal %q", s)
}
if sig, ok := signalMap[strings.TrimPrefix(strings.ToUpper(s), "SIG")]; ok {
return sig, nil
}
return -1, fmt.Errorf("unknown signal %q", s)
}
var signalMap = map[string]unix.Signal{
"ABRT": unix.SIGABRT,
"ALRM": unix.SIGALRM,
"BUS": unix.SIGBUS,
"CHLD": unix.SIGCHLD,
"CLD": unix.SIGCLD,
"CONT": unix.SIGCONT,
"FPE": unix.SIGFPE,
"HUP": unix.SIGHUP,
"ILL": unix.SIGILL,
"INT": unix.SIGINT,
"IO": unix.SIGIO,
"IOT": unix.SIGIOT,
"KILL": unix.SIGKILL,
"PIPE": unix.SIGPIPE,
"POLL": unix.SIGPOLL,
"PROF": unix.SIGPROF,
"PWR": unix.SIGPWR,
"QUIT": unix.SIGQUIT,
"SEGV": unix.SIGSEGV,
"STKFLT": unix.SIGSTKFLT,
"STOP": unix.SIGSTOP,
"SYS": unix.SIGSYS,
"TERM": unix.SIGTERM,
"TRAP": unix.SIGTRAP,
"TSTP": unix.SIGTSTP,
"TTIN": unix.SIGTTIN,
"TTOU": unix.SIGTTOU,
"URG": unix.SIGURG,
"USR1": unix.SIGUSR1,
"USR2": unix.SIGUSR2,
"VTALRM": unix.SIGVTALRM,
"WINCH": unix.SIGWINCH,
"XCPU": unix.SIGXCPU,
"XFSZ": unix.SIGXFSZ,
}
|
package directmessages
import (
"encoding/json"
"io/ioutil"
"testing"
)
func TestItUnmarchalsAEventsJson(t *testing.T) {
data, err := ioutil.ReadFile("testdata/events.json")
if err != nil {
t.Error("Failed to parse attachment.json", err)
}
var events Events
json.Unmarshal(data, &events)
if events.NextCursor != "SomeCursor" {
t.Error("NextCursor expected", "SomeCursor", "got", events.NextCursor)
}
if len(events.Events) != 1 {
t.Error("Events expected to be 1 got", len(events.Events))
}
}
|
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package ui
import (
"context"
"chromiumos/tast/local/bundles/cros/ui/chromecrash"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/crash"
"chromiumos/tast/testing"
)
type chromeCrashNotLoggedInDirectParams struct {
fileType chromecrash.CrashFileType
handler chromecrash.CrashHandler
}
func init() {
testing.AddTest(&testing.Test{
Func: ChromeCrashNotLoggedInDirect,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Checks that Chrome writes crash dumps while not logged in; old version that does not invoke crash_reporter",
Contacts: []string{"iby@chromium.org", "chromeos-ui@google.com", "cros-telemetry@google.com"},
SoftwareDeps: []string{"chrome"},
Attr: []string{"group:mainline"},
Params: []testing.Param{{
Name: "breakpad",
Val: chromeCrashNotLoggedInDirectParams{
handler: chromecrash.Breakpad,
fileType: chromecrash.BreakpadDmp,
},
ExtraSoftwareDeps: []string{"breakpad"},
}, {
Name: "crashpad",
Val: chromeCrashNotLoggedInDirectParams{
handler: chromecrash.Crashpad,
fileType: chromecrash.MetaFile,
},
ExtraSoftwareDeps: []string{"crashpad"},
}},
})
}
// ChromeCrashNotLoggedInDirect tests that Chrome crashes that happen during tast
// tests are properly captured (that is, during tast tests which are testing
// something other than the crash system).
//
// The other Chrome crash tests cover cases that we expect to occur on end-user
// machines, by simulating user consent. This test covers the tast case, where
// we bypass consent by telling the crash system that we are in a test
// environment. In particular, breakpad goes through a very different code path
// which doesn't involve crash_reporter at all, and we want that to keep working.
//
// Note: The name is a misnomer; the 'Direct' refers to the old days when both
// breakpad and crashpad bypassed crash_reporter and wrote the crashes directly
// onto disk during this test. Crashpad no longer does that; the test should be
// named "TastMode". TODO(https://crbug.com/1201467): Rename to
// ChromeCrashNotLoggedInTastMode
func ChromeCrashNotLoggedInDirect(ctx context.Context, s *testing.State) {
params := s.Param().(chromeCrashNotLoggedInDirectParams)
ct, err := chromecrash.NewCrashTester(ctx, chromecrash.GPUProcess, params.fileType)
if err != nil {
s.Fatal("NewCrashTester failed: ", err)
}
defer ct.Close()
cr, err := chrome.New(ctx, chrome.NoLogin(), chrome.ExtraArgs(chromecrash.GetExtraArgs(params.handler, crash.MockConsent)...))
if err != nil {
s.Fatal("Chrome startup failed: ", err)
}
defer cr.Close(ctx)
// We use crash.DevImage() here because this test still uses the testing
// command-line flags on crash_reporter to bypass metrics consent and such.
// Those command-line flags only work if the crash-test-in-progress does not
// exist.
if err := crash.SetUpCrashTest(ctx, crash.DevImage()); err != nil {
s.Fatal("SetUpCrashTest failed: ", err)
}
defer crash.TearDownCrashTest(ctx)
var files []string
if files, err = ct.KillAndGetCrashFiles(ctx); err != nil {
s.Fatal("Couldn't kill Chrome or get dumps: ", err)
}
if params.fileType == chromecrash.MetaFile {
if err := chromecrash.FindCrashFilesIn(crash.LocalCrashDir, files); err != nil {
s.Errorf("Crash files weren't written to %s after crashing process: %v", crash.LocalCrashDir, err)
}
} else {
if err := chromecrash.FindBreakpadDmpFilesIn(crash.LocalCrashDir, files); err != nil {
s.Errorf(".dmp files weren't written to %s after crashing process: %v", crash.LocalCrashDir, err)
}
}
}
|
package tools
import (
"divsperf/script/parse"
"sync"
)
func RstoInt(rs []rune) (int, error) {
res := 0
for _, c := range rs {
res = res * 10 + (int(c) - 48)
}
return res, nil
}
func TKtoInt(tk parse.Token, name string, idx int) (int, error) {
if tk.Ctype != parse.INT {
return 0, parse.UnmatchError_parameter_type{
name,
idx+1,
parse.INT,
tk.Ctype,
}
}
return RstoInt(*tk.Content)
}
func TkContent(wg *sync.WaitGroup,tk parse.Token) (*[]rune, error) {
switch tk.Ctype {
case parse.SBR:
fallthrough
case parse.INT:
fallthrough
case parse.FLO:
fallthrough
case parse.STR:
return tk.Content, nil
default:
data, err := tk.Sb.LetActionandReturn(wg)
if err!= nil {
return nil, err
}
return data, nil
}
} |
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package rpccalls
import (
"github.com/bitmark-inc/bitmarkd/rpc/node"
)
// BlockDecodeData - the parameters for a blockDecode request
type BlockDecodeData struct {
Packed []byte
}
// DecodeBlock - retrieve some blocks
func (client *Client) DecodeBlock(blockDecodeConfig *BlockDecodeData) (*node.BlockDecodeReply, error) {
blockDecodeArgs := node.BlockDecodeArguments{
Packed: blockDecodeConfig.Packed,
}
client.printJson("BlockDecode Request", blockDecodeArgs)
reply := &node.BlockDecodeReply{}
err := client.client.Call("Node.BlockDecode", blockDecodeArgs, reply)
if nil != err {
return nil, err
}
client.printJson("BlockDecode Reply", reply)
return reply, nil
}
|
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package colexecutils
import (
"context"
"testing"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/col/coldatatestutils"
"github.com/cockroachdb/cockroach/pkg/sql/colcontainer"
"github.com/cockroachdb/cockroach/pkg/sql/colexecop"
"github.com/cockroachdb/cockroach/pkg/sql/colmem"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/testutils/colcontainerutils"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/stretchr/testify/require"
)
func TestSpillingQueue(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
queueCfg, cleanup := colcontainerutils.NewTestingDiskQueueCfg(t, true /* inMem */)
defer cleanup()
ctx := context.Background()
rng, _ := randutil.NewPseudoRand()
for _, rewindable := range []bool{false, true} {
for _, memoryLimit := range []int64{
10 << 10, /* 10 KiB */
1<<20 + int64(rng.Intn(63<<20)), /* 1 MiB up to 64 MiB */
1 << 30, /* 1 GiB */
} {
alwaysCompress := rng.Float64() < 0.5
diskQueueCacheMode := colcontainer.DiskQueueCacheModeDefault
var dequeuedProbabilityBeforeAllEnqueuesAreDone float64
// testReuseCache will test the reuse cache modes.
testReuseCache := rng.Float64() < 0.5
if testReuseCache {
dequeuedProbabilityBeforeAllEnqueuesAreDone = 0
if rng.Float64() < 0.5 {
diskQueueCacheMode = colcontainer.DiskQueueCacheModeReuseCache
} else {
diskQueueCacheMode = colcontainer.DiskQueueCacheModeClearAndReuseCache
}
} else if rng.Float64() < 0.5 {
dequeuedProbabilityBeforeAllEnqueuesAreDone = 0.5
}
prefix := ""
if rewindable {
dequeuedProbabilityBeforeAllEnqueuesAreDone = 0
prefix = "Rewindable/"
}
numBatches := int(spillingQueueInitialItemsLen)*(1+rng.Intn(2)) + rng.Intn(int(spillingQueueInitialItemsLen))
inputBatchSize := 1 + rng.Intn(coldata.BatchSize())
const maxNumTuples = 10000
if numBatches*inputBatchSize > maxNumTuples {
// When we happen to choose very large value for
// coldata.BatchSize() and for spillingQueueInitialItemsLen, the
// test might take non-trivial amount of time, so we'll limit
// the number of tuples.
inputBatchSize = maxNumTuples / numBatches
}
// Add a limit on the number of batches added to the in-memory
// buffer of the spilling queue. We will set it to half of the total
// number of batches which allows us to exercise the case when the
// spilling to disk queue occurs after some batches were added to
// the in-memory buffer.
setInMemEnqueuesLimit := rng.Float64() < 0.5
log.Infof(context.Background(), "%sMemoryLimit=%s/DiskQueueCacheMode=%d/AlwaysCompress=%t/NumBatches=%d/InMemEnqueuesLimited=%t",
prefix, humanizeutil.IBytes(memoryLimit), diskQueueCacheMode, alwaysCompress, numBatches, setInMemEnqueuesLimit)
// Since the spilling queue coalesces tuples to fill-in the batches
// up to their capacity, we cannot use the batches we get when
// dequeueing directly. Instead, we are tracking all of the input
// tuples and will be comparing against a window into them.
var tuples *AppendOnlyBufferedBatch
// Create random input.
op := coldatatestutils.NewRandomDataOp(testAllocator, rng, coldatatestutils.RandomDataOpArgs{
NumBatches: numBatches,
BatchSize: inputBatchSize,
Nulls: true,
BatchAccumulator: func(b coldata.Batch, typs []*types.T) {
if b.Length() == 0 {
return
}
if tuples == nil {
tuples = NewAppendOnlyBufferedBatch(testAllocator, typs, nil /* colsToStore */)
}
tuples.AppendTuples(b, 0 /* startIdx */, b.Length())
},
})
typs := op.Typs()
queueCfg.CacheMode = diskQueueCacheMode
queueCfg.SetDefaultBufferSizeBytesForCacheMode()
queueCfg.TestingKnobs.AlwaysCompress = alwaysCompress
// We need to create a separate unlimited allocator for the spilling
// queue so that it could measure only its own memory usage
// (testAllocator might account for other things, thus confusing the
// spilling queue).
memAcc := testMemMonitor.MakeBoundAccount()
defer memAcc.Close(ctx)
spillingQueueUnlimitedAllocator := colmem.NewAllocator(ctx, &memAcc, testColumnFactory)
// Create queue.
var q *SpillingQueue
if rewindable {
q = NewRewindableSpillingQueue(
&NewSpillingQueueArgs{
UnlimitedAllocator: spillingQueueUnlimitedAllocator,
Types: typs,
MemoryLimit: memoryLimit,
DiskQueueCfg: queueCfg,
FDSemaphore: colexecop.NewTestingSemaphore(2),
DiskAcc: testDiskAcc,
},
)
} else {
q = NewSpillingQueue(
&NewSpillingQueueArgs{
UnlimitedAllocator: spillingQueueUnlimitedAllocator,
Types: typs,
MemoryLimit: memoryLimit,
DiskQueueCfg: queueCfg,
FDSemaphore: colexecop.NewTestingSemaphore(2),
DiskAcc: testDiskAcc,
},
)
}
if setInMemEnqueuesLimit {
q.testingKnobs.maxNumBatchesEnqueuedInMemory = numBatches / 2
}
// Run verification.
var (
b coldata.Batch
err error
numAlreadyDequeuedTuples int
// Apart from tracking all input tuples we will be tracking all
// of the dequeued batches and their lengths separately (without
// deep-copying them).
// The implementation of Dequeue() method is such that if the
// queue doesn't spill to disk, we can safely keep the
// references to the dequeued batches because a new batch is
// allocated whenever it is kept in the in-memory buffer (which
// is not the case when dequeueing from disk).
dequeuedBatches []coldata.Batch
dequeuedBatchLengths []int
)
windowedBatch := coldata.NewMemBatchNoCols(typs, coldata.BatchSize())
getNextWindowIntoTuples := func(windowLen int) coldata.Batch {
// MakeWindowIntoBatch creates a window into tuples in the range
// [numAlreadyDequeuedTuples; tuples.length), but we want the
// range [numAlreadyDequeuedTuples; numAlreadyDequeuedTuples +
// windowLen), so we'll temporarily set the length of tuples to
// the desired value and restore it below.
numTuples := tuples.Length()
tuples.SetLength(numAlreadyDequeuedTuples + windowLen)
MakeWindowIntoBatch(windowedBatch, tuples, numAlreadyDequeuedTuples, typs)
tuples.SetLength(numTuples)
numAlreadyDequeuedTuples += windowLen
return windowedBatch
}
for {
b = op.Next(ctx)
q.Enqueue(ctx, b)
if b.Length() == 0 {
break
}
if rng.Float64() < dequeuedProbabilityBeforeAllEnqueuesAreDone {
if b, err = q.Dequeue(ctx); err != nil {
t.Fatal(err)
} else if b.Length() == 0 {
t.Fatal("queue incorrectly considered empty")
}
coldata.AssertEquivalentBatches(t, getNextWindowIntoTuples(b.Length()), b)
dequeuedBatches = append(dequeuedBatches, b)
dequeuedBatchLengths = append(dequeuedBatchLengths, b.Length())
}
}
numDequeuedTuplesBeforeReading := numAlreadyDequeuedTuples
numDequeuedBatchesBeforeReading := len(dequeuedBatches)
numReadIterations := 1
if rewindable {
numReadIterations = 2
}
for i := 0; i < numReadIterations; i++ {
for {
if b, err = q.Dequeue(ctx); err != nil {
t.Fatal(err)
} else if b == nil {
t.Fatal("unexpectedly dequeued nil batch")
} else if b.Length() == 0 {
break
}
coldata.AssertEquivalentBatches(t, getNextWindowIntoTuples(b.Length()), b)
dequeuedBatches = append(dequeuedBatches, b)
dequeuedBatchLengths = append(dequeuedBatchLengths, b.Length())
}
if !q.Spilled() {
// Let's verify that all of the dequeued batches equal to
// all of the input tuples. We need to unset
// numAlreadyDequeuedTuples so that we start getting
// "windows" from the very beginning.
numAlreadyDequeuedTuples = 0
for i, b := range dequeuedBatches {
coldata.AssertEquivalentBatches(t, getNextWindowIntoTuples(dequeuedBatchLengths[i]), b)
}
}
if rewindable {
require.NoError(t, q.Rewind())
numAlreadyDequeuedTuples = numDequeuedTuplesBeforeReading
dequeuedBatches = dequeuedBatches[:numDequeuedBatchesBeforeReading]
dequeuedBatchLengths = dequeuedBatchLengths[:numDequeuedBatchesBeforeReading]
}
}
// Close queue.
require.NoError(t, q.Close(ctx))
// Verify no directories are left over.
directories, err := queueCfg.FS.List(queueCfg.GetPather.GetPath(ctx))
require.NoError(t, err)
require.Equal(t, 0, len(directories))
}
}
}
// TestSpillingQueueDidntSpill verifies that in a scenario when every Enqueue()
// is followed by Dequeue() the non-rewindable spilling queue doesn't actually
// spill to disk.
func TestSpillingQueueDidntSpill(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
queueCfg, cleanup := colcontainerutils.NewTestingDiskQueueCfg(t, true /* inMem */)
defer cleanup()
queueCfg.CacheMode = colcontainer.DiskQueueCacheModeDefault
rng, _ := randutil.NewPseudoRand()
numBatches := int(spillingQueueInitialItemsLen)*(1+rng.Intn(4)) + rng.Intn(int(spillingQueueInitialItemsLen))
op := coldatatestutils.NewRandomDataOp(testAllocator, rng, coldatatestutils.RandomDataOpArgs{
// TODO(yuzefovich): for some types (e.g. types.MakeArray(types.Int))
// the memory estimation diverges from 0 after Enqueue() / Dequeue()
// sequence. Figure it out.
DeterministicTyps: []*types.T{types.Int},
NumBatches: numBatches,
BatchSize: 1 + rng.Intn(coldata.BatchSize()),
Nulls: true,
})
typs := op.Typs()
// Choose a memory limit such that at most two batches can be kept in the
// in-memory buffer at a time (single batch is not enough because the queue
// delays the release of the memory by one batch).
memoryLimit := int64(2 * colmem.EstimateBatchSizeBytes(typs, coldata.BatchSize()))
if memoryLimit < mon.DefaultPoolAllocationSize {
memoryLimit = mon.DefaultPoolAllocationSize
}
// We need to create a separate unlimited allocator for the spilling queue
// so that it could measure only its own memory usage (testAllocator might
// account for other things, thus confusing the spilling queue).
memAcc := testMemMonitor.MakeBoundAccount()
defer memAcc.Close(ctx)
spillingQueueUnlimitedAllocator := colmem.NewAllocator(ctx, &memAcc, testColumnFactory)
q := NewSpillingQueue(
&NewSpillingQueueArgs{
UnlimitedAllocator: spillingQueueUnlimitedAllocator,
Types: typs,
MemoryLimit: memoryLimit,
DiskQueueCfg: queueCfg,
FDSemaphore: colexecop.NewTestingSemaphore(2),
DiskAcc: testDiskAcc,
},
)
for {
b := op.Next(ctx)
q.Enqueue(ctx, b)
b, err := q.Dequeue(ctx)
require.NoError(t, err)
if b.Length() == 0 {
break
}
}
// Ensure that the spilling didn't occur.
require.False(t, q.Spilled())
// Close queue.
require.NoError(t, q.Close(ctx))
// Verify no directories are left over.
directories, err := queueCfg.FS.List(queueCfg.GetPather.GetPath(ctx))
require.NoError(t, err)
require.Equal(t, 0, len(directories))
}
const defaultMemoryLimit = 64 << 20 /* 64 MiB */
// TestSpillingQueueMemoryAccounting is a simple check of the memory accounting
// of the spilling queue that performs a series of Enqueue() and Dequeue()
// operations and verifies that the reported memory usage is as expected.
//
// Note that this test intentionally doesn't randomize many things (e.g. the
// size of input batches, the types of the vectors) since those randomizations
// would make it hard to compute the expected memory usage (the spilling queue
// has coalescing logic, etc). Thus, the test is more of a sanity check, yet it
// should be sufficient to catch any regressions.
func TestSpillingQueueMemoryAccounting(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
rng, _ := randutil.NewPseudoRand()
typs := []*types.T{types.Int}
queueCfg, cleanup := colcontainerutils.NewTestingDiskQueueCfg(t, true /* inMem */)
defer cleanup()
for _, rewindable := range []bool{false, true} {
for _, dequeueProbability := range []float64{0, 0.2} {
if rewindable && dequeueProbability != 0 {
// For rewindable queues we require that all enqueues occur
// before any Dequeue() call.
continue
}
// We need to create a separate unlimited allocator for the spilling
// queue so that it could measure only its own memory usage
// (testAllocator might account for other things, thus confusing the
// spilling queue).
memAcc := testMemMonitor.MakeBoundAccount()
defer memAcc.Close(ctx)
spillingQueueUnlimitedAllocator := colmem.NewAllocator(ctx, &memAcc, testColumnFactory)
newQueueArgs := &NewSpillingQueueArgs{
UnlimitedAllocator: spillingQueueUnlimitedAllocator,
Types: typs,
MemoryLimit: defaultMemoryLimit,
DiskQueueCfg: queueCfg,
FDSemaphore: colexecop.NewTestingSemaphore(2),
DiskAcc: testDiskAcc,
}
var q *SpillingQueue
if rewindable {
q = NewRewindableSpillingQueue(newQueueArgs)
} else {
q = NewSpillingQueue(newQueueArgs)
}
numInputBatches := int(spillingQueueInitialItemsLen)*(1+rng.Intn(4)) + rng.Intn(int(spillingQueueInitialItemsLen))
numDequeuedBatches := 0
batch := coldatatestutils.RandomBatch(testAllocator, rng, typs, coldata.BatchSize(), coldata.BatchSize(), 0.1 /* nullProbability */)
batchSize := colmem.GetBatchMemSize(batch)
getExpectedMemUsage := func(numEnqueuedBatches int) int64 {
batchesAccountedFor := numEnqueuedBatches
if !rewindable && numDequeuedBatches > 0 {
// We release the memory under the dequeued batches only
// from the non-rewindable queue, and that release is
// lagging by one batch, so we have -1 here.
//
// Note that this logic also works correctly when zero batch
// has been dequeued once.
batchesAccountedFor -= numDequeuedBatches - 1
}
return int64(batchesAccountedFor) * batchSize
}
for numEnqueuedBatches := 1; numEnqueuedBatches <= numInputBatches; numEnqueuedBatches++ {
q.Enqueue(ctx, batch)
if rng.Float64() < dequeueProbability {
b, err := q.Dequeue(ctx)
require.NoError(t, err)
coldata.AssertEquivalentBatches(t, batch, b)
numDequeuedBatches++
}
require.Equal(t, getExpectedMemUsage(numEnqueuedBatches), q.unlimitedAllocator.Used())
}
q.Enqueue(ctx, coldata.ZeroBatch)
for {
b, err := q.Dequeue(ctx)
require.NoError(t, err)
numDequeuedBatches++
require.Equal(t, getExpectedMemUsage(numInputBatches), q.unlimitedAllocator.Used())
if b.Length() == 0 {
break
}
coldata.AssertEquivalentBatches(t, batch, b)
}
// Some sanity checks.
require.False(t, q.Spilled())
require.NoError(t, q.Close(ctx))
directories, err := queueCfg.FS.List(queueCfg.GetPather.GetPath(ctx))
require.NoError(t, err)
require.Equal(t, 0, len(directories))
}
}
}
// TestSpillingQueueMovingTailWhenSpilling verifies that the spilling queue
// correctly moves the tail of the in-memory buffer onto the disk queue when the
// memory limit is exceeded. It sets such a memory limit and buffer size bytes
// that all enqueued batches have to be moved, so the in-memory buffer becomes
// empty.
func TestSpillingQueueMovingTailWhenSpilling(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
rng, _ := randutil.NewPseudoRand()
typs := []*types.T{types.Int}
queueCfg, cleanup := colcontainerutils.NewTestingDiskQueueCfg(t, true /* inMem */)
defer cleanup()
numInputBatches := 1 + rng.Intn(int(spillingQueueInitialItemsLen))
batch := testAllocator.NewMemBatchWithFixedCapacity(typs, coldata.BatchSize())
batch.SetLength(coldata.BatchSize())
batchSize := colmem.GetBatchMemSize(batch)
memoryLimit := int64(numInputBatches) * batchSize
if memoryLimit < mon.DefaultPoolAllocationSize {
memoryLimit = mon.DefaultPoolAllocationSize
numInputBatches = int(memoryLimit / batchSize)
}
queueCfg.BufferSizeBytes = int(memoryLimit)
// Our memory accounting is delayed by one batch, so we need to append an
// extra to exceed the memory limit.
numInputBatches++
for _, enqueueExtra := range []bool{false, true} {
// We need to create a separate unlimited allocator for the spilling
// queue so that it could measure only its own memory usage
// (testAllocator might account for other things, thus confusing the
// spilling queue).
memAcc := testMemMonitor.MakeBoundAccount()
defer memAcc.Close(ctx)
spillingQueueUnlimitedAllocator := colmem.NewAllocator(ctx, &memAcc, testColumnFactory)
newQueueArgs := &NewSpillingQueueArgs{
UnlimitedAllocator: spillingQueueUnlimitedAllocator,
Types: typs,
MemoryLimit: memoryLimit,
DiskQueueCfg: queueCfg,
FDSemaphore: colexecop.NewTestingSemaphore(2),
DiskAcc: testDiskAcc,
}
q := NewSpillingQueue(newQueueArgs)
var expectedBatchSequence []int64
for i := 0; i < numInputBatches; i++ {
// Enqueue deeply copies the batch, so we can reuse the same
// one.
sequenceValue := rng.Int63()
batch.ColVec(0).Int64()[0] = sequenceValue
expectedBatchSequence = append(expectedBatchSequence, sequenceValue)
q.Enqueue(ctx, batch)
}
// All enqueued batches should fit under the memory limit (to be
// precise, the last enqueued batch has just crossed the limit, but
// the spilling hasn't occurred yet).
require.False(t, q.Spilled())
numExtraInputBatches := 0
if enqueueExtra {
sequenceValue := rng.Int63()
batch.ColVec(0).Int64()[0] = sequenceValue
expectedBatchSequence = append(expectedBatchSequence, sequenceValue)
q.Enqueue(ctx, batch)
numExtraInputBatches = 1
} else {
require.NoError(t, q.maybeSpillToDisk(ctx))
}
// Now the spilling must have occurred with all batches moved to the
// disk queue.
require.True(t, q.Spilled())
require.Equal(t, 0, q.numInMemoryItems)
require.Equal(t, int64(0), q.unlimitedAllocator.Used())
require.Equal(t, numInputBatches+numExtraInputBatches, q.numOnDiskItems)
q.Enqueue(ctx, coldata.ZeroBatch)
// Now check that all the batches are in the correct order.
batchCount := 0
for {
b, err := q.Dequeue(ctx)
require.NoError(t, err)
if b.Length() == 0 {
break
}
require.Equal(t, expectedBatchSequence[batchCount], b.ColVec(0).Int64()[0])
batchCount++
}
require.Equal(t, batchCount, numInputBatches+numExtraInputBatches)
// Some sanity checks.
require.NoError(t, q.Close(ctx))
directories, err := queueCfg.FS.List(queueCfg.GetPather.GetPath(ctx))
require.NoError(t, err)
require.Equal(t, 0, len(directories))
}
}
|
package course
import(
//"github.com/codebuff95/uafm"
//"github.com/codebuff95/uafm/usersession"
"github.com/codebuff95/uafm/formsession"
"feedback-admin/user"
"feedback-admin/database"
"feedback-admin/templates"
"feedback-admin/college"
"net/http"
"time"
"log"
"errors"
"html/template"
"gopkg.in/mgo.v2/bson"
)
type Course struct{
Courseid string `bson:"courseid"`
Coursename string `bson:"coursename"`
Addedon string `bson:"addedon"`
}
type CoursePage struct{
Courses *[]Course
FormSid *string
Collegename *string
}
func GetCourses() (*[]Course,error){
log.Println("Getting Courses Slice")
var myCourseSlice []Course
err := database.CourseCollection.Find(nil).All(&myCourseSlice)
if err != nil{
log.Println("Error finding courses:",err)
return nil,err
}
log.Println("Success getting courseSlice of size:",len(myCourseSlice))
if len(myCourseSlice) == 0{
return nil,nil
}
return &myCourseSlice,nil
}
func GetCourse(cid string) (*Course,error){
log.Println("Getting course with courseid:",cid)
var myCourse *Course = &Course{}
err := database.CourseCollection.Find(bson.M{"courseid" : cid}).Limit(1).One(myCourse)
if err != nil{
log.Println("Could not get course.")
return nil,err
}
return myCourse,err
}
func displayCoursePage(w http.ResponseWriter, r *http.Request){
log.Println("Displaying course page to user.")
var myCoursePage CoursePage
formSid, err := formsession.CreateSession("0",time.Minute*10) //Form created will be valid for 10 minutes.
if err != nil{
log.Println("Error creating new session for course form:",err)
displayBadPage(w,r,err)
return
}
myCoursePage.FormSid = formSid
myCoursePage.Collegename = &college.GlobalDetails.Collegename
log.Println("Creating new course page to client",r.RemoteAddr,"with formSid:",*myCoursePage.FormSid) //Enter client ip address and new form SID.
myCoursePage.Courses,_ = GetCourses()
templates.CoursePageTemplate.Execute(w,myCoursePage)
}
func displayBadPage(w http.ResponseWriter, r *http.Request, err error){
templates.BadPageTemplate.Execute(w,err.Error())
}
func CourseHandler(w http.ResponseWriter, r *http.Request){
log.Println("***COURSE HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic")
displayCoursePage(w,r)
}
func AddCourseHandler(w http.ResponseWriter, r *http.Request){
log.Println("***ADD COURSE HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic. Validating form and Parsing form for new course data.")
if r.Method != "POST"{
displayBadPage(w,r,errors.New("Please add new course properly"))
return
}
r.ParseForm()
_,err = formsession.ValidateSession(r.Form.Get("formsid"))
if err != nil{
log.Println("Error validating formSid:",err,". Displaying badpage.")
displayBadPage(w,r,err)
return
}
enteredCourseId := template.HTMLEscapeString(r.Form.Get("courseid"))
enteredCourseName := template.HTMLEscapeString(r.Form.Get("coursename"))
addedOn := time.Now().Format("2006-01-02 15:04:05")
myNewCourse := &Course{Courseid : enteredCourseId, Coursename : enteredCourseName, Addedon : addedOn}
log.Println("Adding new course with details:",*myNewCourse)
err = AddCourse(myNewCourse)
if err != nil{
displayBadPage(w,r,err)
return
}
log.Println("Successfully added new course with Id:",enteredCourseId,", name:",enteredCourseName)
http.Redirect(w, r, "/course", http.StatusSeeOther)
}
func RemoveCourseHandler(w http.ResponseWriter,r *http.Request){
log.Println("***REMOVE COURSE HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic. Validating remove course request.")
if r.Method != "GET"{
displayBadPage(w,r,errors.New("Please remove course properly"))
return
}
myCourseId := template.HTMLEscapeString(r.URL.Path[len("/removecourse/"):])
_,err = RemoveCourse(myCourseId)
if err != nil{
log.Println("Problem removing course:",err)
displayBadPage(w,r,err)
return
}
log.Println("Success removing course:",myCourseId)
http.Redirect(w, r, "/course", http.StatusSeeOther)
}
func AddCourse(mycourse *Course) error{
return database.CourseCollection.Insert(mycourse)
}
func RemoveCourse(id string) (int,error){
changeinfo,err := database.CourseCollection.RemoveAll(bson.M{"courseid":id})
if changeinfo == nil{
return 0,err
}
return changeinfo.Removed,err
}
|
package command
import (
"github.com/continuul/random-names/pkg/stream"
"io"
)
// Cli represents the command line client.
type Cli interface {
Out() *stream.OutStream
Err() io.Writer
In() *stream.InStream
SetIn(in *stream.InStream)
}
// CliInstance is an instance the command line client.
// Instances of the client can be returned from NewCliInstance.
type CliInstance struct {
in *stream.InStream
out *stream.OutStream
err io.Writer
}
// NewCliInstance returns a Cli instance with IO output and error streams set by in, out and err.
func NewCliInstance(in io.ReadCloser, out, err io.Writer) *CliInstance {
return &CliInstance{in: stream.NewInStream(in), out: stream.NewOutStream(out), err: err}
}
// Out returns the writer used for stdout
func (cli *CliInstance) Out() *stream.OutStream {
return cli.out
}
// Err returns the writer used for stderr
func (cli *CliInstance) Err() io.Writer {
return cli.err
}
// SetIn sets the reader used for stdin
func (cli *CliInstance) SetIn(in *stream.InStream) {
cli.in = in
}
// In returns the reader used for stdin
func (cli *CliInstance) In() *stream.InStream {
return cli.in
}
|
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
const eventString = `_e{16,24}:Request handled|Received an HTTP request|p:low|#tag1:value,tag2,origin:master`
const counterString = `page.views:1|c`
const gaugeString = `coolant.temperature:160|g`
func handler(_ http.ResponseWriter, _ *http.Request) {
fmt.Println(eventString)
fmt.Println(counterString)
fmt.Println(gaugeString)
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package ui
import (
"context"
"time"
"github.com/golang/protobuf/ptypes/empty"
"google.golang.org/grpc"
"chromiumos/tast/errors"
"chromiumos/tast/local/audio"
"chromiumos/tast/local/audio/crastestclient"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/uiauto/filesapp"
"chromiumos/tast/local/input"
"chromiumos/tast/services/cros/ui"
"chromiumos/tast/testing"
)
func init() {
testing.AddService(&testing.Service{
Register: func(srv *grpc.Server, s *testing.ServiceState) {
ui.RegisterAudioServiceServer(srv, &AudioService{s: s})
},
})
}
// AudioService implements tast.cros.ui.AudioService.
type AudioService struct {
s *testing.ServiceState
cr *chrome.Chrome
}
// New logs into a Chrome session as a fake user. Close must be called later
// to clean up the associated resources.
func (as *AudioService) New(ctx context.Context, req *empty.Empty) (*empty.Empty, error) {
if as.cr != nil {
return nil, errors.New("Chrome already available")
}
cr, err := chrome.New(ctx)
if err != nil {
return nil, err
}
as.cr = cr
return &empty.Empty{}, nil
}
// Close releases the resources obtained by New.
func (as *AudioService) Close(ctx context.Context, req *empty.Empty) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
err := as.cr.Close(ctx)
as.cr = nil
return &empty.Empty{}, err
}
// OpenDirectoryAndFile performs launching filesapp and opening particular file
// in given directory.
func (as *AudioService) OpenDirectoryAndFile(ctx context.Context, req *ui.AudioServiceRequest) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
tconn, err := as.cr.TestAPIConn(ctx)
if err != nil {
return nil, err
}
filesTitlePrefix := "Files - "
files, err := filesapp.Launch(ctx, tconn)
if err != nil {
return nil, errors.Wrap(err, "failed to launch the Files App")
}
if err := files.OpenDir(req.DirectoryName, filesTitlePrefix+req.DirectoryName)(ctx); err != nil {
return nil, errors.Wrapf(err, "failed to open %q folder in files app", req.DirectoryName)
}
if req.FileName != "" {
if err := files.OpenFile(req.FileName)(ctx); err != nil {
return nil, errors.Wrapf(err, "failed to open the audio file %q", req.FileName)
}
}
return &empty.Empty{}, nil
}
// GenerateTestRawData generates test raw data file.
func (as *AudioService) GenerateTestRawData(ctx context.Context, req *ui.AudioServiceRequest) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
// Generate sine raw input file that lasts 30 seconds.
rawFile := audio.TestRawData{
Path: req.FilePath,
BitsPerSample: 16,
Channels: 2,
Rate: 48000,
Frequencies: []int{440, 440},
Volume: 0.05,
Duration: int(req.DurationInSecs),
}
if err := audio.GenerateTestRawData(ctx, rawFile); err != nil {
return nil, errors.Wrap(err, "failed to generate audio test data")
}
return &empty.Empty{}, nil
}
// ConvertRawToWav will convert raw data file to wav file format.
func (as *AudioService) ConvertRawToWav(ctx context.Context, req *ui.AudioServiceRequest) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
if err := audio.ConvertRawToWav(ctx, req.FilePath, req.FileName, 48000, 2); err != nil {
return nil, errors.Wrap(err, "failed to convert raw to wav")
}
return &empty.Empty{}, nil
}
// KeyboardAccel will create keyboard event and performs keyboard
// key press with Accel().
func (as *AudioService) KeyboardAccel(ctx context.Context, req *ui.AudioServiceRequest) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
kb, err := input.Keyboard(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to find keyboard")
}
defer kb.Close()
if err := kb.Accel(ctx, req.Expr); err != nil {
return nil, errors.Wrapf(err, "failed to press %q using keyboard", req.Expr)
}
return &empty.Empty{}, nil
}
// AudioCrasSelectedOutputDevice will return selected audio device name
// and audio device type.
func (as *AudioService) AudioCrasSelectedOutputDevice(ctx context.Context, req *empty.Empty) (*ui.AudioServiceResponse, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
// Get Current active node.
cras, err := audio.NewCras(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create Cras object")
}
outDeviceName, outDeviceType, err := cras.SelectedOutputDevice(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get the selected audio device")
}
return &ui.AudioServiceResponse{DeviceName: outDeviceName, DeviceType: outDeviceType}, nil
}
// VerifyFirstRunningDevice will check for audio routing device status.
func (as *AudioService) VerifyFirstRunningDevice(ctx context.Context, req *ui.AudioServiceRequest) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
if err := testing.Poll(ctx, func(ctx context.Context) error {
devName, err := crastestclient.FirstRunningDevice(ctx, audio.OutputStream)
if err != nil {
return errors.Wrap(err, "failed to detect running output device")
}
if deviceName := req.Expr; deviceName != devName {
return errors.Wrapf(err, "failed to route the audio through expected audio node: got %q; want %q", devName, deviceName)
}
return nil
}, &testing.PollOptions{Timeout: 10 * time.Second}); err != nil {
return nil, errors.Wrap(err, "failed to check audio running device")
}
return &empty.Empty{}, nil
}
// SetActiveNodeByType will set the provided audio node as Active audio node.
func (as *AudioService) SetActiveNodeByType(ctx context.Context, req *ui.AudioServiceRequest) (*empty.Empty, error) {
if as.cr == nil {
return nil, errors.New("Chrome not available")
}
var cras *audio.Cras
if err := cras.SetActiveNodeByType(ctx, req.Expr); err != nil {
return nil, errors.Wrapf(err, "failed to select active device %s", req.Expr)
}
return &empty.Empty{}, nil
}
|
package parser
import (
"encoding/json"
"fmt"
"goassignment/record"
"strconv"
)
func GetJsonFromRecordObjects(records []record.Record) string {
jsonString, err := json.Marshal(records)
if err != nil {
fmt.Println(err)
}
return string(jsonString)
}
func convertRecordToObject(csvRecords []string) record.Record {
var recordObj = record.Record{}
phone, _ := strconv.Atoi(csvRecords[3])
isActive, _ := strconv.ParseBool(csvRecords[4])
recordObj = record.Record{
Id: csvRecords[0],
Name: csvRecords[1],
Email: csvRecords[2],
Phone: phone,
IsActive: isActive,
}
recordObj.ProcessRecordId()
if !recordObj.IsRecordCorrect() {
recordObj = record.Record{}
}
return recordObj
}
func GetRecordObjectsFromCSVReader(csvRecords [][]string) []record.Record {
var records []record.Record
for i := 0; i < len(csvRecords)-1; i++ {
recordObj := convertRecordToObject(csvRecords[i])
if(record.Record{} != recordObj){
records = append(records, recordObj)
}
}
return records
}
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"io/ioutil"
"os"
"strings"
)
var flagType = flag.String("t", "", "default arguments and results to `type`")
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s -t type file.go [file2.go...]\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
os.Exit(2)
}
if !strings.HasSuffix(flag.Arg(0), ".go") {
fmt.Fprintf(os.Stderr, "not a .go file: %s\n", flag.Arg(0))
os.Exit(1)
}
nfilename := flag.Arg(0)[:len(flag.Arg(0))-3] + ".wrap.go"
// Emit prologue.
var out bytes.Buffer
fmt.Fprintf(&out, `// Generated by genwrap.go. DO NOT EDIT
package z3
import "runtime"
/*
#cgo LDFLAGS: -lz3
#include <z3.h>
#include <stdlib.h>
*/
import "C"
`)
// Emit common methods.
genCommon(&out)
for _, filename := range flag.Args() {
code, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Process the file one line at a time.
lines := bytes.Split(code, []byte("\n"))
// Process lines.
doc := [][]byte{}
for i, line := range lines {
if len(line) >= 2 && line[0] == '/' && line[1] == '/' {
label := fmt.Sprintf("%s:%d", filename, i+1)
process(&out, line, doc, label)
doc = append(doc, line)
} else {
doc = nil
}
}
}
// Produce the output code.
ncode, err := format.Source(out.Bytes())
if err != nil {
fmt.Fprintln(os.Stderr, out.String())
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := ioutil.WriteFile(nfilename, ncode, 0666); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func genCommon(w *bytes.Buffer) {
fmt.Fprintln(w, "// Eq returns a Value that is true if l and r are equal.")
dir := parseDirective(strings.Fields("//wrap:expr Eq:Bool Z3_mk_eq l r"))
genMethod(w, dir, "")
fmt.Fprintf(w, `// NE returns a Value that is true if l and r are not equal.
func (l %s) NE(r %s) Bool {
return l.ctx.Distinct(l, r)
}
`, *flagType, *flagType)
}
type directive struct {
goFn, cFn string
goArgs, cArgs []*arg
isDDD bool
hasRM bool
resType string
}
type arg struct {
name, goTyp, cExpr, cCode, setup string
}
func (a arg) c(varName string) string {
if a.cCode != "" {
return a.cCode
}
return fmt.Sprintf(a.cExpr, varName)
}
func split(x, def string) (a, b string) {
if i := strings.Index(x, ":"); i >= 0 {
return x[:i], x[i+1:]
}
return x, def
}
func parseDirective(parts []string) *directive {
defType := *flagType
colon, cPos := -1, 2
for i, p := range parts {
if p == ":" {
colon, cPos = i, i+1
break
}
}
goFn, resType := split(parts[1], defType)
dir := &directive{
goFn: goFn, cFn: parts[cPos],
resType: resType,
}
cArgs := parts[cPos+1:]
goArgs := append([]string(nil), cArgs...)
if colon >= 0 {
goArgs = parts[2:colon]
}
// Strip @rm from goArgs since it's implied from ctx.
for i := 0; i < len(goArgs); i++ {
if goArgs[i] == "@rm" {
copy(goArgs[i:], goArgs[i+1:])
goArgs = goArgs[:len(goArgs)-1]
i--
}
}
for _, a := range cArgs {
if a == "@rm" {
dir.hasRM = true
}
}
argMap := make(map[string]*arg)
for _, goArg := range goArgs {
name, goTyp := split(goArg, defType)
argMap[name] = &arg{name, goTyp, "", "", ""}
dir.goArgs = append(dir.goArgs, argMap[name])
}
for _, cArg := range cArgs {
if cArg[0] == '"' {
// Literal code.
cCode := cArg[1 : len(cArg)-1]
dir.cArgs = append(dir.cArgs, &arg{cCode: cCode})
continue
}
if cArg == "@rm" {
// Rounding mode from ctx.
dir.cArgs = append(dir.cArgs, &arg{cCode: "rm.c"})
continue
}
name, cTyp := split(cArg, "")
arg := argMap[name]
if arg == nil {
fmt.Fprintf(os.Stderr, "reference to unknown argument %q", name)
os.Exit(1)
}
if cTyp == "" && arg.goTyp == "Value" {
arg.cExpr = "%s.impl().c" // Value interface
} else if cTyp == "" && arg.goTyp == "RoundingMode" {
arg.setup = "rmc := " + arg.name + ".ast(ctx)"
arg.cCode = "rmc.c"
} else if cTyp == "" {
arg.cExpr = "%s.c" // expr wrapper
} else {
arg.cExpr = "C." + cTyp + "(%s)" // basic type
}
dir.cArgs = append(dir.cArgs, arg)
}
if strings.HasSuffix(dir.goArgs[len(dir.goArgs)-1].name, "...") {
dir.isDDD = true
}
return dir
}
func process(w *bytes.Buffer, line []byte, doc [][]byte, label string) {
if !bytes.Contains(line, []byte("//wrap:expr")) {
return
}
parts := strings.Fields(string(line))
if parts[0] != "//wrap:expr" {
return
}
// Found wrap directive.
dir := parseDirective(parts)
// Function documentation.
if len(doc) > 0 && string(doc[len(doc)-1]) == "//" {
doc = doc[:len(doc)-1]
}
for _, line := range doc {
fmt.Fprintf(w, "%s\n", line)
}
genMethod(w, dir, label)
}
func genMethod(w *bytes.Buffer, dir *directive, label string) {
// Function declaration.
fmt.Fprintf(w, "func (%s %s) %s(", dir.goArgs[0].name, dir.goArgs[0].goTyp, dir.goFn)
for i, a := range dir.goArgs[1:] {
if i > 0 {
fmt.Fprintf(w, ", ")
}
fmt.Fprintf(w, "%s %s", a.name, a.goTyp)
}
fmt.Fprintf(w, ") %s {\n", dir.resType)
if label != "" {
fmt.Fprintf(w, " // Generated from %s.\n", label)
}
if dir.goArgs[0].goTyp != "*Context" {
// Context is implied by the receiver.
fmt.Fprintf(w, " ctx := %s.ctx\n", dir.goArgs[0].name)
}
if dir.isDDD {
// Convert arguments to C array.
arg := dir.cArgs[len(dir.cArgs)-1]
ddd := arg.name
ddd = ddd[:len(ddd)-3]
fmt.Fprintf(w, " cargs := make([]C.Z3_ast, len(%s)+%d)\n", ddd, len(dir.cArgs)-1)
for i, arg := range dir.cArgs[:len(dir.cArgs)-1] {
fmt.Fprintf(w, " cargs[%d] = %s\n", i, arg.c(arg.name))
}
fmt.Fprintf(w, " for i, arg := range %s { cargs[i+%d] = %s }\n", ddd, len(dir.cArgs)-1, arg.c("arg"))
}
if dir.hasRM {
// Get the rounding mode before we take the ctx lock.
fmt.Fprintf(w, "rm := ctx.rm()\n")
}
// Perform any setup code.
for _, a := range dir.cArgs {
if a.setup != "" {
fmt.Fprintf(w, "%s\n", a.setup)
}
}
// Construct the AST.
fmt.Fprintf(w, " val := wrapValue(ctx, func() C.Z3_ast {\n")
fmt.Fprintf(w, " return C.%s(ctx.c", dir.cFn)
if !dir.isDDD {
for _, a := range dir.cArgs {
fmt.Fprintf(w, ", %s", a.c(a.name))
}
} else {
fmt.Fprintf(w, ", C.uint(len(cargs)), &cargs[0]")
}
fmt.Fprintf(w, ")\n")
fmt.Fprintf(w, " })\n")
// Keep arguments alive.
if !dir.isDDD {
for _, a := range dir.goArgs {
if a.goTyp != "int" && a.name != "ctx" {
fmt.Fprintf(w, " runtime.KeepAlive(%s)\n", a.name)
}
}
} else {
fmt.Fprintf(w, " runtime.KeepAlive(&cargs[0])\n")
}
// Wrap the final C result in a Go result.
if dir.resType == "Value" {
// Determine the concrete type dynamically.
fmt.Fprintf(w, " return val.lift(KindUnknown)")
} else {
fmt.Fprintf(w, " return %s(val)\n", dir.resType)
}
fmt.Fprintf(w, "}\n")
fmt.Fprintf(w, "\n")
}
|
package main
import (
"github.com/gragas/woobloo-frontend/config"
"html/template"
"io/ioutil"
"net/http"
)
var templates map[string]*template.Template
func main() {
// load the config file
config := config.LoadConfig("config.json")
// initialize maps, etc.
templates = make(map[string]*template.Template)
// setup static handlers
const (
cssPath = "/static/css/"
imagesPath = "/static/images/"
)
http.Handle(cssPath,
http.StripPrefix(cssPath, http.FileServer(http.Dir("."+cssPath))))
http.Handle(imagesPath,
http.StripPrefix(imagesPath, http.FileServer(http.Dir("."+imagesPath))))
// setup dynamic handlers
http.HandleFunc("/", indexHandler)
http.ListenAndServe(config.ServerAddr, nil)
}
// Handlers
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
return
}
data := struct {
Title string
TestString string
}{Title: "Woobloo Civilizations", TestString: "Hello, World!"}
getTemplate("html/index.html").Execute(w, data)
}
func getTemplate(htmlPath string) *template.Template {
var t *template.Template
if templates[htmlPath] == nil {
// if the template is not in the cache, generate it
bytes, err := ioutil.ReadFile(htmlPath)
if err != nil {
panic(err)
}
t, err = template.New(htmlPath).Parse(string(bytes))
if err != nil {
panic(err)
}
// and add it to the cache
templates[htmlPath] = t
} else {
// otherwise, grab it from the cache
t = templates[htmlPath]
}
return t
}
|
package udid_service
import (
"fmt"
uuid "github.com/satori/go.uuid"
"go.uber.org/zap"
"os"
"super-signature/model"
"super-signature/util/ali"
"super-signature/util/apple"
"super-signature/util/conf"
"super-signature/util/errno"
"super-signature/util/tools"
)
func AnalyzeUDID(udid, id string) (string, error) {
// 判断IPA id是否存在账号下
applePackage, err := model.GetApplePackageByID(id)
if err != nil {
return "", err
}
if applePackage == nil {
//IPA包不存在数据库中
return "", errno.ErrNotIPA
}
// 判断udid是否已存在数据库某账号下
appleDevices, err := model.GetAppleDeviceByUDID(udid)
if err != nil {
return "", err
}
if len(appleDevices) != 0 {
// UDID已经存在某账号下
// 同一udid可能绑定过多个开发者账号
for i, ad := range appleDevices {
appleAccount, err := model.GetAppleAccountByIss(ad.AccountIss)
if err != nil {
return "", err
}
if appleAccount == nil {
//udid绑定的开发者账号已不存在 下一个
//删除数据库设备表中绑定过该账户的所有记录
err = model.DeleteAppleDeviceByAccountIss(ad.AccountIss)
if err != nil {
return "", err
}
if i == len(appleDevices)-1 {
plistPath, err := bindingAppleAccount(udid, *applePackage)
if err != nil {
return "", err
}
return plistPath, nil
} else {
continue
}
}
// 验证账号可用性
_, err = apple.Authorize{
P8: appleAccount.P8,
Iss: appleAccount.Iss,
Kid: appleAccount.Kid,
}.GetAvailableDevices()
if err != nil {
return "", err
}
// 重签名
plistPath, err := signature(*appleAccount, ad.DeviceId, *applePackage)
if err != nil {
return "", err
}
return plistPath, nil
}
} else {
plistPath, err := bindingAppleAccount(udid, *applePackage)
if err != nil {
return "", err
}
return plistPath, nil
}
return "", nil
}
func bindingAppleAccount(udid string, applePackage model.ApplePackage) (string, error) {
// 直到获取一个可用账号
for {
appleAccount, err := model.GetAvailableAppleAccount()
if err != nil {
return "", err
}
if appleAccount == nil {
return "", errno.ErrNotAppleAccount
}
// 验证账号可用性
devicesResponseList, err := apple.Authorize{
P8: appleAccount.P8,
Iss: appleAccount.Iss,
Kid: appleAccount.Kid,
}.GetAvailableDevices()
if err != nil {
return "", err
}
if devicesResponseList.Meta.Paging.Total < 100 {
appleDevice, err := insertDevice(*appleAccount, udid)
if err != nil {
return "", err
}
//重签名
plistPath, err := signature(*appleAccount, appleDevice.DeviceId, applePackage)
if err != nil {
return "", err
}
return plistPath, nil
} else {
//更新数据库账号
err = model.UpdateAppleAccountCount(appleAccount.Iss, devicesResponseList.Meta.Paging.Total)
if err != nil {
return "", err
}
continue
}
}
}
func insertDevice(appleAccount model.AppleAccount, udid string) (model.AppleDevice, error) {
// 将udid添加到对应可用的开发者账号中心
devicesResponse, err := apple.Authorize{
P8: appleAccount.P8,
Iss: appleAccount.Iss,
Kid: appleAccount.Kid,
}.AddAvailableDevice(udid)
if err != nil {
return model.AppleDevice{}, err
}
// 将udid添加到数据库
appleDevice := model.AppleDevice{
AccountIss: appleAccount.Iss,
Udid: devicesResponse.Data.Attributes.Udid,
DeviceId: devicesResponse.Data.ID,
}
if err = appleDevice.InsertAppleDevice(); err != nil {
return model.AppleDevice{}, err
}
// +1可用设备库存
if err = appleAccount.AddAppleAccountCount(); err != nil {
return model.AppleDevice{}, err
}
return appleDevice, nil
}
func signature(appleAccount model.AppleAccount, devicesId string, applePackage model.ApplePackage) (string, error) {
// 获取描述文件mobileprovision
var fileName = fmt.Sprintf("%s", uuid.Must(uuid.NewV4(), nil))
profileResponse, err := apple.Authorize{
P8: appleAccount.P8,
Iss: appleAccount.Iss,
Kid: appleAccount.Kid,
}.CreateProfile(fileName, appleAccount.BundleIds, appleAccount.CerId, devicesId)
if err != nil {
return "", err
}
var mobileprovisionPath = conf.Config.ApplePath.TemporaryDownloadPath + fileName + ".mobileprovision"
err = tools.Base64ToFile(profileResponse.Data.Attributes.ProfileContent, mobileprovisionPath)
if err != nil {
return "", err
}
ipaPath := conf.Config.ApplePath.TemporaryDownloadPath + fileName + ".ipa"
ipaDownloadHost := ""
// 开启 oss
if conf.Config.EnableOSS {
ipaDownloadHost = ali.GetHost(fileName + ".ipa")
} else {
ipaID, err := model.InsertDownloadPath(ipaPath)
if err != nil {
return "", err
}
ipaDownloadHost = conf.Config.ApplePath.URL + "/api/v1/download?id=" + ipaID
}
// 生成IPA下载plist
var plistContent = fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>items</key>
<array>
<dict>
<key>assets</key>
<array>
<dict>
<key>kind</key>
<string>software-package</string>
<key>url</key>
<string>%s</string>
</dict>
</array>
<key>metadata</key>
<dict>
<key>bundle-identifier</key>
<string>%s</string>
<key>bundle-version</key>
<string>%s</string>
<key>kind</key>
<string>software</string>
<key>title</key>
<string>App</string>
</dict>
</dict>
</array>
</dict>
</plist>`, ipaDownloadHost, applePackage.BundleIdentifier, applePackage.Version)
var plistPath = conf.Config.ApplePath.TemporaryDownloadPath + fileName + ".plist"
err = tools.CreateFile(plistContent, plistPath)
if err != nil {
return "", err
}
plistID, err := model.InsertDownloadPath(plistPath)
if err != nil {
return "", err
}
//下载量+1
err = applePackage.AddApplePackageCount()
if err != nil {
return "", err
}
// 拿到账号下对应的pem证书、保存的key私钥、获取到的描述文件mobileprovision对IPA签名
go func(fileName, newIPAPath, pemPath, mobileprovisionPath, LocalIPAPath, plistID string) {
defer func() {
if err := recover(); err != nil {
zap.S().Error("签名失败", err)
}
}()
zap.S().Info(newIPAPath, "正在签名中")
err = tools.Command("zsign", "-c", pemPath,
"-k", conf.CSRSetting.KeyPath,
"-m", mobileprovisionPath,
"-o", newIPAPath,
"-z", "9",
LocalIPAPath)
if err != nil {
zap.S().Error("签名失败", err.Error())
conf.Config.IPASign.Store(plistID, []string{"fail", err.Error()})
return
}
if conf.Config.EnableOSS {
err := ali.UploadFile(fileName+".ipa", newIPAPath)
if err != nil {
zap.S().Error("oss上传失败", err.Error())
conf.Config.IPASign.Store(plistID, []string{"fail", err.Error()})
return
}
_ = os.Remove(newIPAPath)
}
conf.Config.IPASign.Store(plistID, []string{"success"})
zap.S().Info(newIPAPath, "签名成功")
}(fileName, ipaPath, appleAccount.PemPath, mobileprovisionPath, applePackage.IPAPath, plistID)
return fmt.Sprintf("%s/api/v1/getApp?plistID=%s&packageId=%d", conf.Config.ApplePath.URL, plistID, applePackage.ID), nil
}
func GetApplePackageByID(packageId string) (applePackage *model.ApplePackage, err error) {
applePackage, err = model.GetApplePackageByID(packageId)
if err != nil {
return nil, err
}
if applePackage == nil {
return nil, errno.ErrNotIPA
}
return applePackage, nil
}
|
package cacheutil
import (
"fmt"
"testing"
)
func TestNewLRUCache(t *testing.T) {
lru := NewLRUCache(3)
lru.Set(10, "value1")
lru.Set(20, "value2")
lru.Set(30, "value3")
lru.Set(10, "value4")
lru.Set(50, "value5")
fmt.Println("LRU Size:", lru.Size())
v, ret, _ := lru.Get(30)
if ret {
fmt.Println("Get(30) : ", v)
}
if lru.Remove(30) {
fmt.Println("Remove(30) : true ")
} else {
fmt.Println("Remove(30) : false ")
}
fmt.Println("LRU Size:", lru.Size())
}
|
package main
import (
"fmt"
)
var afl = [4]float64{1, 2, 3, 4}
//8 characters long using starting at -1 and going to -8
func squareroot(x float64) float64 {
z := 1.0
con := false
var eplace int
for index := 0; con != true; index++ {
z -= (z*z - x) / (2 * z)
afl[eplace] = z
count := 0
for i := range afl {
if afl[i] == z {
count++
} else {
count = 0
break
}
if count == 4 {
con = true
}
}
fmt.Printf("round: %v\n", index+1)
fmt.Println(z)
if eplace < 3 {
eplace++
} else {
eplace = 0
}
}
return z
}
func main() {
squareroot(333333874390895374209857304982502)
}
|
package Week_02
func inorderTraversal(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
resRight := inorderTraversal(root.Right)
resLeft := inorderTraversal(root.Left)
return append(append(resLeft, root.Val), resRight...)
}
|
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
strfmt "github.com/go-openapi/strfmt"
)
// NewDeletePermissionsEntryPointParams creates a new DeletePermissionsEntryPointParams object
// with the default values initialized.
func NewDeletePermissionsEntryPointParams() *DeletePermissionsEntryPointParams {
var ()
return &DeletePermissionsEntryPointParams{
timeout: cr.DefaultTimeout,
}
}
// NewDeletePermissionsEntryPointParamsWithTimeout creates a new DeletePermissionsEntryPointParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewDeletePermissionsEntryPointParamsWithTimeout(timeout time.Duration) *DeletePermissionsEntryPointParams {
var ()
return &DeletePermissionsEntryPointParams{
timeout: timeout,
}
}
/*DeletePermissionsEntryPointParams contains all the parameters to send to the API endpoint
for the delete permissions entry point operation typically these are written to a http.Request
*/
type DeletePermissionsEntryPointParams struct {
/*URI*/
URI *string
timeout time.Duration
}
// WithURI adds the uri to the delete permissions entry point params
func (o *DeletePermissionsEntryPointParams) WithURI(URI *string) *DeletePermissionsEntryPointParams {
o.URI = URI
return o
}
// WriteToRequest writes these params to a swagger request
func (o *DeletePermissionsEntryPointParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.URI != nil {
// query param uri
var qrURI string
if o.URI != nil {
qrURI = *o.URI
}
qURI := qrURI
if qURI != "" {
if err := r.SetQueryParam("uri", qURI); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
package webgl3d
import "github.com/go4orward/gowebgl/wcommon"
type Scene struct {
bkgcolor [3]float32 // background color of the scene
objects []*SceneObject // SceneObjects in the scene
overlays []Overlay // list of Overlay (interface) layers
}
func NewScene(bkg_color string) *Scene {
var scene Scene
scene.SetBkgColor(bkg_color)
scene.objects = make([]*SceneObject, 0)
scene.overlays = make([]Overlay, 0)
return &scene
}
// ----------------------------------------------------------------------------
// Background Color
// ----------------------------------------------------------------------------
func (self *Scene) SetBkgColor(color string) *Scene {
rgba := wcommon.ParseHexColor(color)
self.bkgcolor = [3]float32{rgba[0], rgba[1], rgba[2]}
return self
}
func (self *Scene) GetBkgColor() [3]float32 {
return self.bkgcolor
}
// ----------------------------------------------------------------------------
// Handling SceneObject
// ----------------------------------------------------------------------------
func (self *Scene) Add(scnobj ...*SceneObject) *Scene {
for i := 0; i < len(scnobj); i++ {
self.objects = append(self.objects, scnobj[i])
}
return self
}
func (self *Scene) Get(indices ...int) *SceneObject {
// Find a SceneObject using the list of indices
// (multiple indices refers to children[i] of SceneObject)
scene_object_list := self.objects
for i := 0; i < len(indices); i++ {
index := indices[i]
if index < 0 || index >= len(scene_object_list) {
return nil
} else if i == len(indices)-1 {
scene_object := scene_object_list[index]
return scene_object
} else {
scene_object := scene_object_list[index]
scene_object_list = scene_object.children
}
}
return nil
}
// ----------------------------------------------------------------------------
// Managing OverlayLayers
// ----------------------------------------------------------------------------
func (self *Scene) AddOverlay(overlay ...Overlay) *Scene {
for i := 0; i < len(overlay); i++ {
self.overlays = append(self.overlays, overlay[i])
}
return self
}
|
package leypaPractUtil
import ()
const AddUrl = "http://127.0.0.1:5001/api/v0/add"
const AddCode = 0
const CatUrl = "http://127.0.0.1:5001/api/v0/cat"
const CatCode = 1
const ListUrl = "http://127.0.0.1:5001/api/v0/files/ls"
const ListCode = 2
const MkdirUrl = "http://127.0.0.1:5001/api/v0/files/mkdir"
const MkdirCode = 3
const ReadUrl = "http://127.0.0.1:5001/api/v0/files/read"
const ReadCode = 4
const StatusUrl = "http://127.0.0.1:5001/api/v0/files/stat"
const StatusCode = 5
const RemoveUrl = "http://127.0.0.1:5001/api/v0/files/rm"
const RemoveCode = 6
const CopyUrl = "http://127.0.0.1:5001/api/v0/files/cp"
const CopyCode = 7
const MoveUrl = "http://127.0.0.1:5001/api/v0/files/mv"
const MoveCode = 8
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.