text
stringlengths 11
4.05M
|
|---|
package model
import (
"fmt"
"glog/utils"
"log"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
var (
db *gorm.DB
err error
)
func InitDb() {
dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
utils.DbUser,
utils.DbPassWord,
utils.DbHost,
utils.DbPort,
utils.DbName,
)
db, err = gorm.Open(mysql.Open(dns), &gorm.Config{
// gorm日志模式:silent
Logger: logger.Default.LogMode(logger.Silent),
// 外键约束
DisableForeignKeyConstraintWhenMigrating: true,
// 禁用默认事务(提高运行速度)
SkipDefaultTransaction: true,
NamingStrategy: schema.NamingStrategy{
// 使用单数表名,启用该选项,此时,`User` 的表名应该是 `user`
SingularTable: true,
},
})
if err != nil {
log.Println("Connect Mysql err:", err)
}
// _ = db.AutoMigrate(&User{}, &Article{}, &Category{}, Profile{}, Comment{})
sqlDB, _ := db.DB()
// SetMaxIdleCons 设置连接池中的最大闲置连接数。
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenCons 设置数据库的最大连接数量。
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetiment 设置连接的最大可复用时间。
sqlDB.SetConnMaxLifetime(10 * time.Second)
}
|
// Copyright 2017 Mirantis
//
// 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 extensions
import (
"bytes"
"encoding/json"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/rest"
)
// WrapClientsetWithExtensions function
func WrapClientsetWithExtensions(clientset *kubernetes.Clientset, config *rest.Config) (*WrappedClientset, error) {
restConfig := &rest.Config{}
*restConfig = *config
rest, err := extensionClient(restConfig)
if err != nil {
return nil, err
}
return &WrappedClientset{
Client: rest,
}, nil
}
func extensionClient(config *rest.Config) (*rest.RESTClient, error) {
config.APIPath = "/apis"
config.ContentConfig = rest.ContentConfig{
GroupVersion: &schema.GroupVersion{
Group: GroupName,
Version: Version,
},
NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: api.Codecs},
ContentType: runtime.ContentTypeJSON,
}
return rest.RESTClientFor(config)
}
// Clientset interface
type Clientset interface {
Agents() AgentsInterface
}
// WrappedClientset structure
type WrappedClientset struct {
Client *rest.RESTClient
}
// AgentsInterface interface
type AgentsInterface interface {
Create(*Agent) (*Agent, error)
Get(name string) (*Agent, error)
List(api.ListOptions) (*AgentList, error)
Watch(api.ListOptions) (watch.Interface, error)
Update(*Agent) (*Agent, error)
Delete(string, *api.DeleteOptions) error
}
// Agents function
func (w *WrappedClientset) Agents() AgentsInterface {
return &AgentsClient{w.Client}
}
// AgentsClient structure
type AgentsClient struct {
client *rest.RESTClient
}
func decodeResponseInto(resp []byte, obj interface{}) error {
return json.NewDecoder(bytes.NewReader(resp)).Decode(obj)
}
// Create agent function
func (c *AgentsClient) Create(agent *Agent) (result *Agent, err error) {
result = &Agent{}
resp, err := c.client.Post().
Namespace(api.NamespaceDefault).
Resource("agents").
Body(agent).
DoRaw()
if err != nil {
return result, err
}
return result, decodeResponseInto(resp, result)
}
// List agents function
func (c *AgentsClient) List(opts api.ListOptions) (result *AgentList, err error) {
result = &AgentList{}
resp, err := c.client.Get().
Namespace(api.NamespaceDefault).
Resource("agents").
LabelsSelectorParam(opts.LabelSelector).
DoRaw()
if err != nil {
return result, err
}
return result, decodeResponseInto(resp, result)
}
// Watch agents function
func (c *AgentsClient) Watch(opts api.ListOptions) (watch.Interface, error) {
return c.client.Get().
Namespace(api.NamespaceDefault).
Prefix("watch").
Resource("agents").
VersionedParams(&opts, api.ParameterCodec).
Watch()
}
// Update agents function
func (c *AgentsClient) Update(agent *Agent) (result *Agent, err error) {
result = &Agent{}
resp, err := c.client.Put().
Namespace(api.NamespaceDefault).
Resource("agents").
Name(agent.Metadata.Name).
Body(agent).
DoRaw()
if err != nil {
return result, err
}
return result, decodeResponseInto(resp, result)
}
// Delete agent function
func (c *AgentsClient) Delete(name string, options *api.DeleteOptions) error {
return c.client.Delete().
Namespace(api.NamespaceDefault).
Resource("agents").
Name(name).
Body(options).
Do().
Error()
}
// Get agent function
func (c *AgentsClient) Get(name string) (result *Agent, err error) {
result = &Agent{}
resp, err := c.client.Get().
Namespace(api.NamespaceDefault).
Resource("agents").
Name(name).
DoRaw()
if err != nil {
return result, err
}
return result, decodeResponseInto(resp, result)
}
|
/*
The MIT License (MIT)
Copyright (c) 2014 Chris Grieger
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"syscall"
)
// CreatePidfile creates a pidfile.
// If the file already exists, it checks if the process is already running and terminates.
func CreatePidfile(pidFile string) {
if pidFile != "" {
if err := os.MkdirAll(filepath.Dir(pidFile), os.FileMode(0755)); err != nil {
log.Fatalf("Could not create path to pidfile %v", err)
}
if _, err := os.Stat(pidFile); err != nil && !os.IsNotExist(err) {
log.Fatalf("Failed to stat pidfile %v", err)
}
f, err := os.OpenFile(pidFile, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
log.Fatalf("Failed to open pidfile %v", err)
}
defer f.Close()
if pidBytes, err := ioutil.ReadAll(f); err != nil {
log.Fatalf("Failed to read from pidfile %v", err)
} else {
if len(pidBytes) == 0 {
goto foo
}
pid, err := strconv.Atoi(string(pidBytes))
if err != nil {
log.Fatalf("Invalid pid %v", err)
}
process, err := os.FindProcess(pid)
if err != nil {
log.Fatalf("Failed to find process %v, please delete the pid file %s manually", err, pidFile)
}
if err := process.Signal(syscall.Signal(0)); err == nil {
log.Fatalf("Process %d still running, please stop the process and delete the pid file %s manually", pid, pidFile)
}
}
foo:
if err = f.Truncate(0); err != nil {
log.Fatalf("Failed to truncate pidfile %v", err)
}
if _, err = f.Seek(0, 0); err != nil {
log.Fatalf("Failed to seek pidfile %v", err)
}
_, err = fmt.Fprintf(f, "%d", os.Getpid())
if err != nil {
log.Fatalf("Failed to write pidfile %v", err)
}
}
}
|
/*
* Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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 adatypes
import (
"bytes"
"fmt"
"math"
"reflect"
"strconv"
)
type byteValue struct {
adaValue
value int8
}
func newByteValue(initType IAdaType) *byteValue {
value := byteValue{adaValue: adaValue{adatype: initType}}
return &value
}
func (value *byteValue) ByteValue() byte {
return byte(value.value)
}
func (value *byteValue) String() string {
return fmt.Sprintf("%d", value.value)
}
func (value *byteValue) Value() interface{} {
return value.value
}
func (value *byteValue) Bytes() []byte {
return []byte{byte(value.value)}
}
func (value *byteValue) SetStringValue(stValue string) {
iv, err := strconv.ParseInt(stValue, 0, 64)
if err == nil {
if iv < math.MinInt8 || iv > math.MaxInt8 {
return
}
value.value = int8(iv)
}
}
func (value *byteValue) SetValue(v interface{}) error {
switch reflect.TypeOf(v).Kind() {
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
intValue := reflect.ValueOf(v).Int()
if intValue < math.MinInt8 || intValue > math.MaxInt8 {
return NewGenericError(117, intValue)
}
value.value = int8(intValue)
return nil
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
uintValue := reflect.ValueOf(v).Uint()
if uintValue > math.MaxInt8 {
return NewGenericError(117, uintValue)
}
value.value = int8(uintValue)
return nil
// }
// switch v.(type) {
// case byte, int8:
// value.value = v.(int8)
// return nil
// case int, int32:
// val := v.(int)
// value.value = int8(val)
// return nil
// case int64:
// val := v.(int64)
// value.value = int8(val)
// return nil
// case string:
case reflect.String:
sv := v.(string)
ba, err := strconv.ParseInt(sv, 0, 64)
if err != nil {
return err
}
if ba < math.MinInt8 || ba > math.MaxInt8 {
return NewGenericError(117, ba)
}
value.value = int8(ba)
return nil
case reflect.Slice:
value.value = convertByteToInt8(v.([]byte)[0])
return nil
}
return NewGenericError(103, fmt.Sprintf("%T", v), value.Type().Name())
}
func (value *byteValue) FormatBuffer(buffer *bytes.Buffer, option *BufferOption) uint32 {
return value.commonFormatBuffer(buffer, option, value.Type().Length())
}
func (value *byteValue) StoreBuffer(helper *BufferHelper, option *BufferOption) error {
// Skip normal fields in second call
if option != nil && option.SecondCall > 0 {
return nil
}
return helper.putByte(byte(value.value))
}
func (value *byteValue) parseBuffer(helper *BufferHelper, option *BufferOption) (res TraverseResult, err error) {
value.value, err = helper.ReceiveInt8()
Central.Log.Debugf("Buffer get byte offset=%d %s", helper.offset, value.Type().Name())
return
}
func (value *byteValue) Int8() (int8, error) {
return int8(value.value), nil
}
func (value *byteValue) UInt8() (uint8, error) {
return uint8(value.value), nil
}
func (value *byteValue) Int16() (int16, error) {
return int16(value.value), nil
}
func (value *byteValue) UInt16() (uint16, error) {
return uint16(value.value), nil
}
func (value *byteValue) Int32() (int32, error) {
return int32(value.value), nil
}
func (value *byteValue) UInt32() (uint32, error) {
return uint32(value.value), nil
}
func (value *byteValue) Int64() (int64, error) {
return int64(value.value), nil
}
func (value *byteValue) UInt64() (uint64, error) {
return uint64(value.value), nil
}
func (value *byteValue) Float() (float64, error) {
return float64(value.value), nil
}
// unsigned byte value definition used to read 8-bit unsigned
type ubyteValue struct {
adaValue
value uint8
}
func newUByteValue(initType IAdaType) *ubyteValue {
value := ubyteValue{adaValue: adaValue{adatype: initType}}
return &value
}
func (value *ubyteValue) ByteValue() byte {
return value.value
}
func (value *ubyteValue) String() string {
if value.Type().FormatType() == 'L' {
if value.value == 0 {
return "false"
}
return "true"
}
return fmt.Sprintf("%d", value.value)
}
func (value *ubyteValue) Value() interface{} {
return value.value
}
func (value *ubyteValue) Bytes() []byte {
return []byte{value.value}
}
func (value *ubyteValue) SetStringValue(stValue string) {
iv, err := strconv.ParseInt(stValue, 0, 64)
if err == nil {
if iv < 0 || iv > math.MaxUint8 {
return // NewGenericError(117, val)
}
value.value = uint8(iv)
}
}
func (value *ubyteValue) SetValue(v interface{}) error {
if value.Type().Type() == FieldTypeCharacter {
switch s := v.(type) {
case string:
sb := []byte(s)
if len(sb) > 1 {
return NewGenericError(108)
}
value.value = sb[0]
return nil
default:
}
}
val, err := value.commonUInt64Convert(v)
if err != nil {
return err
}
if val > math.MaxUint8 {
return NewGenericError(117, val)
}
value.value = uint8(val)
return nil
}
func (value *ubyteValue) FormatBuffer(buffer *bytes.Buffer, option *BufferOption) uint32 {
return value.commonFormatBuffer(buffer, option, value.Type().Length())
}
func (value *ubyteValue) StoreBuffer(helper *BufferHelper, option *BufferOption) error {
// Skip normal fields in second call
if option != nil && option.SecondCall > 0 {
return nil
}
return helper.putByte(value.value)
}
func (value *ubyteValue) parseBuffer(helper *BufferHelper, option *BufferOption) (res TraverseResult, err error) {
value.value, err = helper.ReceiveUInt8()
return
}
func (value *ubyteValue) Int8() (int8, error) {
return int8(value.value), nil
}
func (value *ubyteValue) UInt8() (uint8, error) {
return uint8(value.value), nil
}
func (value *ubyteValue) Int16() (int16, error) {
return int16(value.value), nil
}
func (value *ubyteValue) UInt16() (uint16, error) {
return uint16(value.value), nil
}
func (value *ubyteValue) Int32() (int32, error) {
return int32(value.value), nil
}
func (value *ubyteValue) UInt32() (uint32, error) {
return uint32(value.value), nil
}
func (value *ubyteValue) Int64() (int64, error) {
return int64(value.value), nil
}
func (value *ubyteValue) UInt64() (uint64, error) {
return uint64(value.value), nil
}
func (value *ubyteValue) Float() (float64, error) {
return float64(value.value), nil
}
|
// Lock is an implementation of the github.com/kaepora/miniLock encrypted container.
// This is a simple CLI interface to decrypt minilock container.
package main
import (
"flag"
"fmt"
"os"
"github.com/sycamoreone/lock/minilock"
"golang.org/x/crypto/ssh/terminal"
)
var (
ourPublic, ourSecret *[32]byte // Our own long-term keys.
)
func main() {
flag.Parse()
oldState, err := terminal.MakeRaw(0)
if err != nil {
panic(err.Error())
}
defer terminal.Restore(0, oldState)
term := terminal.NewTerminal(os.Stdin, "")
file, err := os.Open(flag.Arg(0))
if err != nil {
fmt.Printf("Error opening file: %s\n", flag.Arg(0))
return
}
defer file.Close()
term.SetPrompt("Email address (i.e. user@example.com, enter to quit): ")
mailaddr, err := term.ReadLine()
if err != nil || len(mailaddr) == 0 {
return
}
passwd, err := term.ReadPassword(fmt.Sprint("Passphrase (will not be saved to disk): "))
if err != nil {
term.Write([]byte("Failed to read passphrase: " + err.Error() + "\n"))
return
}
ourPublic, ourSecret, err := minilock.DeriveKeys([]byte(passwd), []byte(mailaddr))
if err != nil {
fmt.Printf("Error deriving key: %v\n", err)
return
}
term.Write([]byte("Your minilock ID is " + minilock.ID(ourPublic) + "\n"))
// Check for -d and -e flags. Else print usage()
filename, content, err := minilock.Open(file, ourPublic, ourSecret)
if err != nil {
fmt.Printf("Error decrypting file: %v\n", err)
return
}
term.Write([]byte("Writing decrypted content to " + filename + "\n"))
file, err = os.Create(filename)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
n, err := file.Write(content)
if n < len(content) || err != nil {
fmt.Printf("Error writing to file: %v\n", err)
return
}
}
|
package main
import (
"net/http"
"strings"
"text/template"
"encoding/json"
"io/ioutil"
"path"
"path/filepath"
"os"
"fmt"
"github.com/spf13/hugo/parser"
//"github.com/op/go-logging"
)
var (
//log = logging.MustGetLogger("main")
)
func isEditable(value interface{}) bool {
t := value.(string)
return strings.HasSuffix(strings.ToLower(t),".json") || strings.HasSuffix(strings.ToLower(t),".md")
}
func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func findArchetype(root, file string) string {
base := strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
dir := strings.Split(filepath.Dir(file), "/")
for _ , target := range dir {
targetFileName := path.Join(root, "archetypes", target + ".json")
if _, err := os.Stat(targetFileName); os.IsNotExist(err) {
// path/to/whatever does not exist
} else {
return target
}
}
targetFileName := path.Join(root, "archetypes", base + ".json")
if _, err := os.Stat(targetFileName); os.IsNotExist(err) {
return "" // path/to/whatever does not exist
} else {
return base
}
}
type editHandler struct {
root string
tmpl string
}
func editServer(root, template string) http.Handler {
return &editHandler{root, template}
}
var defaultSchema = `{
type: "object",
//format: "grid",
title: "Blog Post",
properties: {
frontmatter: {
type: "object",
properties: {
title: {
type: "string"
}
}
},
body: {
type: "string",
format: "html",
//format: "markdown",
options: {
wysiwyg: true
}
}
}
}
`
func (u *editHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
dir := strings.TrimPrefix(r.URL.Path, cfgRoot + "/edit/")
filename := r.FormValue("filename")
if filename != "" {
dir = path.Join(dir, filename)
}
schema := defaultSchema
archetype := findArchetype(u.root, dir)
if archetype != "" {
log.Info("Found archetype: %s", archetype)
schemaFileName := path.Join(u.root, "archetypes", archetype + ".json")
targetSchema, err := ioutil.ReadFile(schemaFileName)
if err != nil {
log.Error(err)
} else {
schema = string(targetSchema)
}
} else {
log.Info("Archetype not found")
}
var body []byte
targetfilename := path.Join(u.root, dir)
extension := filepath.Ext(targetfilename)
if stringInSlice(extension, []string{".jpg",".gif"}) {
http.ServeFile(w, r, targetfilename)
return
}
if r.Method == "POST" {
var y map[string]interface{}
body, _ = ioutil.ReadAll(r.Body)
json.Unmarshal(body, &y)
//log.Info(extension)
//log.Info(body)
switch {
case extension == ".json":
var z interface{}
err2 := json.Unmarshal(body, &z)
if err2 != nil {
log.Error(err2)
}
log.Info("%v", z)
body, _ = json.MarshalIndent(z, "", " ")
err:=ioutil.WriteFile(targetfilename, body, 0644)
if err != nil {
log.Warning(err)
}
case extension == ".md":
var z interface{}
if val, ok := y["frontmatter"]; ok {
z = val
} else {
z = y
}
body, err := json.Marshal(z)
if err != nil {
log.Warning(err)
}
newbody := y["body"]
body, _ = json.MarshalIndent(z, "", " ")
result := fmt.Sprintf("%s\n\n%s", body, newbody)
err=ioutil.WriteFile(targetfilename, []byte(result), 0644)
if err != nil {
log.Warning(err)
}
}
} else {
if _, err := os.Stat(targetfilename); os.IsNotExist(err) {
// path/to/whatever does not exist
} else {
switch {
case extension == ".json":
body, err =ioutil.ReadFile(targetfilename)
if err != nil {
log.Error(err)
}
case extension == ".md":
f, err := os.Open(targetfilename)
if err != nil {
log.Warning(err)
}
defer f.Close()
//body, err=ioutil.ReadFile(targetfilename)
p, err := parser.ReadFrom(f)
if err != nil {
log.Warning(err)
}
log.Warning(string(p.Content()))
log.Warning(string(p.FrontMatter()))
metadata, err := p.Metadata()
if err != nil {
log.Warning(err)
}
j := make(map[string]interface{})
j["frontmatter"]=metadata
j["body"]=string(p.Content())
body, _ = json.Marshal(j)
default:
http.ServeFile(w, r, targetfilename)
return
}
}
}
html, _ := Asset(u.tmpl)
funcMap := template.FuncMap{
/*
"humanizeBytes": humanizeBytes,
"humanizeTime": humanizeTime,
"isZip": isZip,
*/
}
t, err := template.New("").Funcs(funcMap).Parse(string(html))
if err != nil {
log.Warning("error %s", err)
}
//files, err := ioutil.ReadDir(path.Join(v.root, r.URL.Path))
//sort.Sort(byName(files))
//url := r.Header.Get("Referer")
url := path.Join(cfgRoot + "/ui" , path.Dir(dir))
t.Execute(w, struct {
FileName string
StartValue string
Referer string
Schema string
RootUrl string
}{
dir,
string(body),
url,
schema,
cfgRoot,
})
}
|
package invoker
import (
"context"
"github.com/pkg/errors"
"google.golang.org/grpc"
v1 "github.com/mee6aas/zeep/pkg/api/invoker/v1"
)
// Connect connects to the agent with the specified address.
func Connect(ctx context.Context, addr string) (e error) {
if conn, e = grpc.Dial(addr, grpc.WithInsecure(), grpc.WithBlock()); e != nil {
e = errors.Wrap(e, "Failed to dial")
return
}
client = v1.NewInvokerClient(conn)
return
}
|
package main
import (
"github.com/docker/docker-credential-helpers/credentials"
"github.com/rancher-sandbox/rancher-desktop/src/go/docker-credential-none/dcnone"
)
func main() {
credentials.Serve(dcnone.DCNone{})
}
|
package message
import "fmt"
// Message ...
type Message string
// String ...
func (m Message) String() string {
return string(m)
}
// Format ...
func (m Message) Format(args ...interface{}) string {
return fmt.Sprintf(string(m), args...)
}
// Equal ...
func (m Message) Equal(src string) bool {
return string(m) == src
}
|
package main
import (
"flag"
"mqtt-adapter/src/adapter"
"mqtt-adapter/src/config"
"mqtt-adapter/src/logger"
)
var (
configFlag = flag.String("conf", "./package.json", "Path to package.json file")
subsFlag = flag.String("subs", "./service-processor/subscriptions.txt", "Path to subscriptions.txt file")
listFlag = flag.String("list", "/run/secrets/mqtt_listener.json", "Path to mqtt_listener.json file")
pubFlag = flag.String("pub", "/run/secrets/mqtt_publisher.json", "Path to mqtt_publisher.json file")
)
func main() {
setConfigs()
logger.Log.Infoln("Start MicroService MQTT adapter ...")
err := config.Load()
if err != nil {
logger.Log.Error(err)
return
}
ms, err := adapter.New()
if err != nil {
logger.Log.Error(err)
return
}
ms.Run()
}
// setConfigs sets paths to files from command line
func setConfigs() {
flag.Parse()
config.ConfigPath = *configFlag
config.SubscriptionsPath = *subsFlag
config.ListCredoPath = *listFlag
config.PubCredoPath = *pubFlag
}
|
package task
import (
"fmt"
"strings"
"tcc_transaction/constant"
"tcc_transaction/global/config"
"tcc_transaction/global/various"
"tcc_transaction/send"
"tcc_transaction/send/email"
"tcc_transaction/store/data"
)
func taskToSend(needRollbackData []*data.RequestInfo, subject string) {
var s send.Send = email.NewEmailSender(*config.EmailUsername, subject, strings.Split(*config.EmailTo, ","))
for _, v := range needRollbackData {
if v.Times >= constant.RetryTimes && v.IsSend != constant.SendSuccess {
err := s.Send([]byte(fmt.Sprintf("this data is wrong, please check it. information: %+v", v)))
if err == nil {
various.C.UpdateRequestInfoSend(v.Id)
}
}
}
if len(needRollbackData) > *config.MaxExceptionalData {
s.Send([]byte(fmt.Sprintf("The exceptional data is too much [%d], please check it.", len(needRollbackData))))
}
}
|
package deezer
import (
"fmt"
"log"
"net/http"
"github.com/doctori/music-migrator/utils"
"github.com/go-resty/resty/v2"
)
const baseAddress = "https://api.deezer.com"
const tokenPath = ".deez"
// Client is a client for working with the Deezer Web API.
// To create an authenticated client, use the `Authenticator.NewClient` method.
type Client struct {
http *resty.Client
baseURL string
token string
AutoRetry bool
}
// deezerRedirectURI is the OAuth redirect URI for the application.
// You must register an application at Spotify's developer portal
// and enter this value.
const deezerRedirectURI = "http://localhost:8080/deezer-callback"
// Deezer holds deezer related infos
type Deezer struct {
// Connected is true if the login phase has appened
auth Authenticator
Client *Client
authURL string
Connected bool
ch chan *Client
state string
}
// Init will initial the deezer client
func (d *Deezer) Init() (err error) {
d.auth = NewAuthenticator(deezerRedirectURI, ScopeBasic, ScopeOfflineAccess, ScopeManageLibrary)
d.Connected = false
d.ch = make(chan *Client)
d.state, err = utils.GenerateRandomString(32)
if err != nil {
return err
}
d.authURL = d.auth.AuthURL(d.state)
return
}
func (d *Deezer) Connect() {
tok, err := utils.ReadToken(tokenPath)
if err != nil {
fmt.Println("Please log in to Deezer by visiting the following page in your browser:", d.authURL)
// wait for auth to complete
d.Client = <-d.ch
} else {
client := d.auth.NewClient(tok)
d.Client = &client
}
// use the client to make calls that require authorization
user, err := d.Client.CurrentUser()
d.Connected = true
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("You are logged in as:", user.Name)
}
func (d Deezer) CompleteAuth(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Got request for: %s\n", r.URL.String())
tok, err := d.auth.Token(d.state, r)
if err != nil {
fmt.Printf("Couldn't get the token because %s", err)
http.Error(w, "Couldn't get token", http.StatusForbidden)
log.Fatal(err)
}
/*
if st := r.FormValue("state"); st != d.state {
http.NotFound(w, r)
log.Fatalf("State mismatch: %s != %s\n", st, d.state)
}
*/
// use the token to get an authenticated client
client := d.auth.NewClient(tok)
utils.SaveToken(tok, tokenPath)
fmt.Fprintf(w, "Login Completed!")
d.ch <- &client
}
|
package handlers
import (
"github.com/button-tech/BNBTextWallet/UI"
"github.com/bwmarrin/discordgo"
"strings"
)
func MainBotHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore all messages created by the bot itself
if m.Author.ID == s.State.User.ID {
return
}
ctx := UI.Pages{
Update: m,
}
content := strings.ToLower(m.Content)
if strings.Contains(content, "/help") {
ctx.HelpView()
} else if strings.Contains(content, "/create") {
ctx.CreateView()
} else if strings.Contains(content, "/address") {
ctx.AddressView()
} else if strings.Contains(content, "/balance") {
ctx.BalanceView()
} else if strings.Contains(content, "/import") {
ctx.ImportView()
} else if strings.Contains(content, "/clean") {
ctx.CleanAccountView()
} else if strings.Contains(content, "/send") {
ctx.SendView()
} else if strings.Contains(content, "/delete") {
ctx.DeleteAccountView()
}
}
//func ChangeStatus(s *discordgo.Session, ready *discordgo.Ready) {
// discordClient.Client.UpdateStatus()
//}
func InitBotHandlers(s *discordgo.Session) {
s.AddHandler(MainBotHandler)
//s.AddHandler(ChangeStatus)
}
|
package admin
import (
"context"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type GetPlatformBankCardListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetPlatformBankCardListLogic(ctx context.Context, svcCtx *svc.ServiceContext) GetPlatformBankCardListLogic {
return GetPlatformBankCardListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetPlatformBankCardListLogic) GetPlatformBankCardList(req types.GetPlatformBankCardListRequest) (*types.GetPlatformBankCardListResponse, error) {
f := model.FindPlatformBankCardList{
Search: req.Search,
Currency: req.Currency,
Page: req.Page,
PageSize: req.PageSize,
}
list, total, err := model.NewPlatformBankCardModel(l.svcCtx.DbEngine).FindList(f)
if err != nil {
l.Errorf("查询平台收款卡列表失败, err=%v", err)
return nil, common.NewCodeError(common.SysDBGet)
}
var cardList []types.PlatformBankCardList
for _, v := range list {
cardList = append(cardList, types.PlatformBankCardList{
CardId: v.Id,
BankName: v.BankName,
AccountName: v.AccountName,
CreateTime: v.CreateTime,
CardNumber: v.CardNumber,
BranchName: v.BranchName,
Currency: v.Currency,
MaxAmount: v.MaxAmount,
Remark: v.Remark,
ReceivedToday: v.TodayReceived,
Status: v.Status,
})
}
return &types.GetPlatformBankCardListResponse{
Total: total,
List: cardList,
}, nil
}
|
package find
import (
"testing"
)
func TestFind(t *testing.T) {
a := "orlorlworlworl"
b := "worl"
t.Log(Find(a, b))
}
func TestGenerateBC(t *testing.T) {
b := "orlorlworlworl"
t.Log(generateBC(b))
}
func TestGenerateGS(t *testing.T) {
b := "orlorlworlworl"
t.Log(generateGS(b))
}
func BenchmarkFind(b *testing.B) {
m := "o vosld! hello world!"
p := "worl"
for i := 0; i < b.N; i++ {
Find(m, p)
}
}
|
package main
import "math"
func main() {
}
func minPathSum(grid [][]int) int {
res := 0
up := 0
left := 0
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if i == 0 {
up = math.MaxInt64
} else {
up = grid[i-1][j]
}
if j == 0 {
left = math.MaxInt64
} else {
left = grid[i][j-1]
}
if up > left {
grid[i][j] += left
} else if up < left {
grid[i][j] += up
} else {
if up != math.MaxInt64 {
grid[i][j] += up
}
}
}
}
res = grid[len(grid)-1][len(grid[0])-1]
return res
}
|
// Copyright (c) 2023 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package zedrouter
import (
"bytes"
"context"
"fmt"
"math"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/insomniacslk/dhcp/dhcpv4/nclient4"
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
)
func init() {
logger = logrus.StandardLogger()
log = base.NewSourceLogObject(logger, "zedrouter", 1234)
}
type dnsmasqConfigletParams struct {
ctx *zedrouterContext
bridgeName string
bridgeIPAddr string
netstatus *types.NetworkInstanceStatus
hostsDir string
ipsetHosts []string
uplink string
dnsServers []net.IP
ntpServers []net.IP
}
func exampleDnsmasqConfigletParams() dnsmasqConfigletParams {
var dcp dnsmasqConfigletParams
dcp.bridgeName = "br0"
dcp.bridgeIPAddr = "10.0.0.1"
var netstatus types.NetworkInstanceStatus
netstatus.DhcpRange.Start = net.IP{10, 0, 0, 2}
netstatus.DhcpRange.End = net.IP{10, 0, 0, 123}
dcp.netstatus = &netstatus
dcp.hostsDir = "/etc/hosts.d"
dcp.ipsetHosts = []string{"zededa.com", "example.com"}
dcp.uplink = "up0"
dcp.dnsServers = []net.IP{{1, 1, 1, 1}, {141, 1, 1, 1}, {208, 67, 220, 220}}
dcp.ntpServers = []net.IP{{94, 130, 35, 4}, {94, 16, 114, 254}}
return dcp
}
func runCreateDnsmasqConfiglet(dcp dnsmasqConfigletParams) string {
var buf bytes.Buffer
createDnsmasqConfigletToWriter(&buf, dcp.ctx, dcp.bridgeName, dcp.bridgeIPAddr, dcp.netstatus, dcp.hostsDir, dcp.ipsetHosts, dcp.uplink, dcp.dnsServers, dcp.ntpServers)
return buf.String()
}
type dnsmasqReturn struct {
output string
err error
exitErr *exec.ExitError
}
func runDnsmasq(args []string) (chan<- struct{}, <-chan dnsmasqReturn) {
var err error
endChan := make(chan struct{})
dnsmasqOutputChan := make(chan dnsmasqReturn)
var bufOut bytes.Buffer
cmd := exec.Command(args[0], args[1:]...) // TODO: make args to string...
cmd.Stdout = &bufOut
cmd.Stderr = &bufOut
go func() {
leasesDir := "/run/zedrouter/dnsmasq.leases"
os.MkdirAll(leasesDir, 0750)
defer os.RemoveAll(leasesDir)
err = cmd.Start()
if err != nil {
panic(fmt.Sprintf("could not run dnsmasq: %+v", err))
}
<-endChan
err = cmd.Process.Kill()
if err != nil {
panic(err)
}
err = cmd.Wait() // ignoring the exit status code / signal
var dr dnsmasqReturn
dr.output = bufOut.String()
dr.err = err
switch e := dr.err.(type) {
case *exec.ExitError:
dr.exitErr = e
}
dnsmasqOutputChan <- dr
}()
return endChan, dnsmasqOutputChan
}
func requestDhcp(mac net.HardwareAddr, vethPeerName string, timeout time.Duration) *net.IP {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
dhcpOptions := []nclient4.ClientOpt{
nclient4.WithRetry(4),
nclient4.WithHWAddr(mac),
nclient4.WithTimeout(timeout),
}
if testing.Verbose() {
dhcpOptions = append(dhcpOptions, nclient4.WithSummaryLogger())
}
client, err := nclient4.New(vethPeerName, dhcpOptions...)
if err != nil {
panic(err)
}
defer client.Close()
lease, err := client.Request(ctx)
if err != nil {
//panic(err)
return nil
}
if lease != nil && lease.Offer != nil {
return &lease.Offer.YourIPAddr
} else {
return nil
}
}
func incByteArray(arr []byte) {
changed := false
for i := len(arr) - 1; i >= 0; i-- {
// byte is just an alias for uint8 (https://go.dev/ref/spec#Numeric_types)
if arr[i] == math.MaxUint8 {
arr[i] = 0
continue
}
arr[i]++
changed = true
break
}
if !changed {
for i := range arr {
arr[i] = 0
}
}
}
func multiRequestDhcp(macs []net.HardwareAddr, vethPeerName string, timeout time.Duration) mac2Ip {
var m2ip mac2Ip
var m2ipMutex sync.Mutex
var wg sync.WaitGroup
for _, mac := range macs {
wg.Add(1)
go func(mac net.HardwareAddr) {
ip := requestDhcp(mac, vethPeerName, timeout)
m2ipMutex.Lock()
if ip != nil {
m2ip.add(mac, *ip)
}
m2ipMutex.Unlock()
wg.Done()
}(mac)
}
wg.Wait()
return m2ip
}
func TestIncByteArray(t *testing.T) {
t.Parallel()
v := []byte{1, 2}
incByteArray(v)
if v[0] != 1 || v[1] != 3 {
t.Fatalf("incByteArray failed: %+v", v)
}
v = []byte{255, 255}
incByteArray(v)
if v[0] != 0 || v[1] != 0 {
t.Fatalf("incByteArray failed: %+v", v)
}
v = []byte{250, 255}
incByteArray(v)
if v[0] != 251 || v[1] != 0 {
t.Fatalf("incByteArray failed: %+v", v)
}
}
type dhcpNetworkEnv struct {
vethName string
vethPeerName string
bridgeName string
pathToDnsmasqConf string
}
// create different interfaces if running tests in parallel
var networkInterfacesID uint32
func createDhcpNetworkEnv(bridgeAddr *netlink.Addr) (dhcpNetworkEnv, bool) {
var dnEnv dhcpNetworkEnv
networkInterfaceID := atomic.AddUint32(&networkInterfacesID, 1)
dnEnv.vethName = fmt.Sprintf("veth-%d", networkInterfaceID)
dnEnv.vethPeerName = fmt.Sprintf("vpeer-%d", networkInterfaceID)
dnEnv.bridgeName = fmt.Sprintf("br-%d", networkInterfaceID)
la := netlink.NewLinkAttrs()
la.Name = dnEnv.bridgeName
dnsmasqBridge := &netlink.Bridge{LinkAttrs: la}
err := netlink.LinkAdd(dnsmasqBridge)
if err != nil && err.Error() == "operation not permitted" {
return dnEnv, false
} else if err != nil {
panic(err)
}
err = netlink.AddrAdd(dnsmasqBridge, bridgeAddr)
if err != nil {
panic(err)
}
// add veth device and connect to bridge
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{
Name: dnEnv.vethName,
MTU: dnsmasqBridge.Attrs().MTU,
},
PeerName: dnEnv.vethPeerName,
}
err = netlink.LinkAdd(veth)
if err != nil {
panic(err)
}
vethPeerLink, err := netlink.LinkByName(dnEnv.vethPeerName)
if err != nil {
panic(err)
}
vethLink, err := netlink.LinkByName(dnEnv.vethName)
if err != nil {
panic(err)
}
err = netlink.LinkSetMaster(vethLink, dnsmasqBridge)
if err != nil {
panic(err)
}
for _, ifname := range []netlink.Link{dnsmasqBridge, vethPeerLink, vethLink} {
err := netlink.LinkSetUp(ifname)
if err != nil {
panic(fmt.Sprintf("Setting up %s failed: %+v", ifname, err))
}
}
return dnEnv, true
}
func (dnEnv *dhcpNetworkEnv) Stop() {
for _, ifname := range []string{dnEnv.vethName, dnEnv.bridgeName} {
link, err := netlink.LinkByName(ifname)
if err != nil {
panic(fmt.Sprintf("LinkByName of %s: %+v", ifname, err))
}
netlink.LinkDel(link)
}
}
type mac2Ip struct {
macs []net.HardwareAddr
ips []net.IP
}
func compareMac2Ip(a, b mac2Ip) bool {
if len(a.macs) != len(b.macs) || len(a.ips) != len(b.ips) || len(a.ips) != len(a.macs) {
return false
}
mac2ipToString := func(mac net.HardwareAddr, ip net.IP) string {
return fmt.Sprintf("%s->%s", mac, ip)
}
aMap := make(map[string]struct{})
for i := 0; i < len(a.macs); i++ {
mac := a.macs[i]
ip := a.ips[i]
aMap[mac2ipToString(mac, ip)] = struct{}{}
}
for i := 0; i < len(b.macs); i++ {
mac := b.macs[i]
ip := b.ips[i]
_, ok := aMap[mac2ipToString(mac, ip)]
if !ok {
return false
}
}
return true
}
func (m2ip *mac2Ip) add(mac net.HardwareAddr, ip net.IP) {
m2ip.macs = append(m2ip.macs, mac)
m2ip.ips = append(m2ip.ips, ip)
if len(m2ip.macs) != len(m2ip.ips) {
panic("length wrong")
}
}
func createMac2Ip(count int, startIPAddr net.IP) mac2Ip {
var ret mac2Ip
ip := make(net.IP, len(startIPAddr))
copy(ip, startIPAddr)
startMac := net.HardwareAddr{0x00, 0xC, 0xA, 0xB, 0x1, 0xE}
for i := 0; i < count; i++ {
mac := make(net.HardwareAddr, len(startMac))
copy(mac, startMac)
ip := make(net.IP, len(startIPAddr))
copy(ip, startIPAddr)
ret.add(mac, ip)
incByteArray(startIPAddr)
incByteArray(startMac)
}
return ret
}
func createDhcpHostsDirFile(path string, mi mac2Ip) {
dhcpHostsDirFile, err := os.Create(path)
if err != nil {
panic(err)
}
defer dhcpHostsDirFile.Close()
for i := 0; i < len(mi.ips); i++ {
mac := mi.macs[i]
ip := mi.ips[i]
line := fmt.Sprintf("%s,%s\n", mac, ip)
dhcpHostsDirFile.WriteString(line)
}
}
func TestRunDnsmasq(t *testing.T) {
if testing.Short() {
t.Skipf("Running dnsmasq skipped as this is rather a component test")
}
t.Parallel()
dhcpTimeout := 30 * time.Second
f, err := os.CreateTemp("", "dnsmasq.conf-")
if err != nil {
panic(err)
}
dcp := exampleDnsmasqConfigletParams()
dcp.netstatus.DhcpRange.Start = net.IP{10, 0, 0, 2}
dcp.netstatus.DhcpRange.End = net.IP{10, 0, 0, 4}
bridgeAddr, err := netlink.ParseAddr(fmt.Sprintf("%s/24", dcp.bridgeIPAddr))
if err != nil {
panic(err)
}
dnEnv, ok := createDhcpNetworkEnv(bridgeAddr)
if !ok {
t.Skipf("Could not create bridge device, probably not enough permissions")
}
defer dnEnv.Stop()
dcp.bridgeName = dnEnv.bridgeName
conf := runCreateDnsmasqConfiglet(dcp)
pathToConf := f.Name()
f.WriteString(conf)
f.Close()
defer os.Remove(pathToConf)
dhcpHostsDir := filepath.Join("/", "run", "zedrouter", fmt.Sprintf("dhcp-hosts.%s", dnEnv.bridgeName))
os.MkdirAll(dhcpHostsDir, 0750)
defer os.RemoveAll(dhcpHostsDir)
countClients := 5
m2ip := createMac2Ip(countClients, dcp.netstatus.DhcpRange.Start)
hostsFilePath := filepath.Join(dhcpHostsDir, "test.hosts")
createDhcpHostsDirFile(hostsFilePath, m2ip)
dhcpEndChan, dnsmasqOutputChan := runDnsmasq([]string{
"dnsmasq",
"-d",
"-C",
pathToConf},
)
unregisteredClientIP := requestDhcp(net.HardwareAddr{0x00, 0x09, 0x45, 0x5d, 0x8b, 0x08}, dnEnv.vethPeerName, dhcpTimeout)
if unregisteredClientIP != nil {
t.Fatalf("unknown clients should not receive IP address from dnsmasq, but got %+v", unregisteredClientIP)
}
dhcpM2Ip := multiRequestDhcp(m2ip.macs, dnEnv.vethPeerName, dhcpTimeout)
dhcpEndChan <- struct{}{}
dnsmasqReturn := <-dnsmasqOutputChan
// ignoring if dnsmasq got killed as we killed it
if dnsmasqReturn.exitErr != nil && dnsmasqReturn.exitErr.Exited() && !dnsmasqReturn.exitErr.Success() {
t.Logf("dnsmasq failed: %+v\noutput: %s", dnsmasqReturn.err, dnsmasqReturn.output)
}
if !compareMac2Ip(m2ip, dhcpM2Ip) {
hostsFileContent, err := os.ReadFile(hostsFilePath)
if err != nil {
t.Logf("could not even read hosts file %s: %+v", hostsFilePath, err)
}
t.Fatalf("requested ips/macs(len %d):\n%+v\ndiffer from provided ips/macs(len %d):\n%+v\nhostsFile:\n%s", len(dhcpM2Ip.ips), dhcpM2Ip, len(m2ip.ips), m2ip, hostsFileContent)
}
}
func TestCreateDnsmasqConfigletWithoutDhcpRangeEnd(t *testing.T) {
t.Parallel()
dcp := exampleDnsmasqConfigletParams()
dcp.netstatus.DhcpRange.End = nil
config := runCreateDnsmasqConfiglet(dcp)
dhcpRangeRex := "(?m)^dhcp-range=10.0.0.2,static,255.255.255.0,60m$"
ok, err := regexp.MatchString(dhcpRangeRex, config)
if err != nil {
panic(err)
}
if !ok {
t.Fatalf("expected to match '%s', but got '%s'", dhcpRangeRex, config)
}
}
func TestCreateDnsmasqConfigletWithDhcpRangeEnd(t *testing.T) {
t.Parallel()
dcp := exampleDnsmasqConfigletParams()
config := runCreateDnsmasqConfiglet(dcp)
configExpected := `
# Automatically generated by zedrouter
except-interface=lo
bind-interfaces
quiet-dhcp
quiet-dhcp6
no-hosts
no-ping
bogus-priv
neg-ttl=10
dhcp-ttl=600
dhcp-leasefile=/run/zedrouter/dnsmasq.leases//br0
server=1.1.1.1@up0
server=141.1.1.1@up0
server=208.67.220.220@up0
no-resolv
ipset=/zededa.com/ipv4.zededa.com,ipv6.zededa.com
ipset=/example.com/ipv4.example.com,ipv6.example.com
pid-file=/run/dnsmasq.br0.pid
interface=br0
listen-address=10.0.0.1
hostsdir=/etc/hosts.d
dhcp-hostsdir=/run/zedrouter/dhcp-hosts.br0
dhcp-option=option:ntp-server,94.130.35.4,94.16.114.254
dhcp-option=option:router
dhcp-option=option:dns-server
dhcp-range=10.0.0.2,10.0.0.123,255.255.255.0,60m
`
if configExpected != config {
t.Fatalf("expected '%s', but got '%s'", configExpected, config)
}
}
func TestRunDnsmasqInvalidDhcpRange(t *testing.T) {
t.Parallel()
line, err := dhcpv4RangeConfig(nil, nil)
if err != nil {
panic(err)
}
if line != "" {
t.Fatalf("dhcp-range is '%s', expected ''", line)
}
line, err = dhcpv4RangeConfig(net.IP{10, 0, 0, 5}, net.IP{10, 0, 0, 3})
if err == nil {
t.Fatalf("expected dhcp range to fail, but got %s", line)
}
}
|
package main
import (
"crypto/rand"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"text/template"
)
// Login request JSON
type User struct {
UserName string `json:"username"`
Password string `json:"password"`
}
// Users a struct of user
type Users struct {
Users []User `json:"users"`
}
type Username struct {
UserName string `json:"username"`
}
type Response struct {
Status string `json:"status"`
Code int `json:"code"`
Message string `json:"message"`
}
// AuthResponse: Sent to Auth
type AuthResponse struct {
AccessToken string `json:"accessToken"`
UserName string `json:"username"`
}
const error = "ERROR"
const success = "SUCCESS"
func main() {
http.HandleFunc("/", HandleIndex)
http.HandleFunc("/v1/account/", account)
http.HandleFunc("/v1/session/", currentSession)
listenPort := "8888"
log.Println("Listening on Port: " + listenPort)
http.ListenAndServe(fmt.Sprintf(":%s", listenPort), nil)
}
// Get environment variable. Return default if not set.
func getenv(name string, dflt string) (val string) {
val = os.Getenv(name)
if val == "" {
val = dflt
}
return val
}
func account(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "application/json")
rw.Header().Set("Access-Control-Allow-Origin", "*")
switch req.Method {
case "GET":
// Logout
file, e := ioutil.ReadFile("./session.json")
if e != nil {
log.Printf("File error: %v\n", e)
os.Exit(1)
}
// Load JSON File
var user User
json.Unmarshal(file, &user)
if user.UserName != "" {
// Response
rw.WriteHeader(http.StatusAccepted)
success := response(success, http.StatusAccepted, "Logged out user "+user.UserName)
rw.Write(success)
log.Println("Succesfully logged out user " + user.UserName)
// Clean up
os.Remove("session.json")
os.Create("session.json")
} else {
// No session
rw.WriteHeader(http.StatusAccepted)
err := response(error, http.StatusAccepted, "No user logged in")
rw.Write(err)
log.Println("No user logged in")
}
case "POST":
// Login
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Println(err)
return
}
// log.Println(string(body))
var t User
err = json.Unmarshal(body, &t)
if err != nil {
log.Println(err)
return
}
log.Println(t.UserName)
// Store Login
loginIsSuccessful := verify(t.UserName, t.Password)
if loginIsSuccessful {
// Return Token Instead ** Always return JSON, Also have response Code
rw.WriteHeader(http.StatusAccepted)
success := AuthResponse{randToken(), t.UserName}
response, _ := json.MarshalIndent(success, "", " ")
rw.Write(response)
log.Println("Succesfully logged in user " + t.UserName)
} else {
rw.WriteHeader(http.StatusUnauthorized)
error := response(error, http.StatusUnauthorized, "Login "+t.UserName+" failed.")
rw.Write(error)
log.Println("Login failed" + t.UserName)
}
case "PUT", "DELETE", "OPTIONS":
// Update an existing record.
rw.WriteHeader(http.StatusMethodNotAllowed)
err := response(error, http.StatusMethodNotAllowed, req.Method+" not allowed")
rw.Write(err)
default:
// Give an error message.
rw.WriteHeader(http.StatusBadRequest)
err := response(error, http.StatusBadRequest, "Bad request")
rw.Write(err)
}
}
func currentSession(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "application/json")
rw.Header().Set("Access-Control-Allow-Origin", "*")
switch req.Method {
case "POST":
// Get UserDB
file, e := ioutil.ReadFile("users.json")
if e != nil {
fmt.Printf("File error: %v\n", e)
os.Exit(1)
}
var jsontype Users
err := json.Unmarshal(file, &jsontype)
if err != nil {
fmt.Println(err)
}
// Read User
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Println(err)
return
}
var user Username
err = json.Unmarshal(body, &user)
if err != nil {
log.Println(err)
return
}
log.Println(user.UserName)
for i := 0; i < len(jsontype.Users); i++ {
if jsontype.Users[i].UserName == user.UserName {
// Login
rw.WriteHeader(http.StatusOK)
success := response(success, http.StatusOK, "User found")
rw.Write(success)
return
}
}
// No session
rw.WriteHeader(http.StatusNoContent)
errors := response(error, http.StatusNoContent, "No user logged in")
rw.Write(errors)
log.Println("No user logged in")
case "PUT", "DELETE", "OPTIONS", "GET":
rw.WriteHeader(http.StatusMethodNotAllowed)
err := response(error, http.StatusMethodNotAllowed, req.Method+" not allowed")
rw.Write(err)
default:
// Give an error message.
rw.WriteHeader(http.StatusBadRequest)
err := response(error, http.StatusBadRequest, "Bad request")
rw.Write(err)
}
}
func verify(username string, password string) bool {
file, e := ioutil.ReadFile("users.json")
if e != nil {
fmt.Printf("File error: %v\n", e)
os.Exit(1)
}
var jsontype Users
err := json.Unmarshal(file, &jsontype)
if err != nil {
fmt.Println(err)
}
for i := 0; i < len(jsontype.Users); i++ {
if jsontype.Users[i].UserName == username && jsontype.Users[i].Password == password {
// Save Login
session(jsontype.Users[i], true)
return true
}
}
return false
}
func response(status string, code int, message string) []byte {
resp := Response{status, code, message}
log.Println(resp.Message)
response, _ := json.MarshalIndent(resp, "", " ")
return response
}
func session(user User, login bool) {
// Clear File
os.Remove("session.json")
os.Create("session.json")
file, e := os.OpenFile("session.json", os.O_RDWR|os.O_APPEND, 0660)
defer file.Close()
if e != nil {
log.Printf("File error: %v\n", e)
return
}
if login {
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
d1 := []byte(b)
file.Write(d1)
}
}
func randToken() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
// HandleIndex this is the index endpoint will return 200
func HandleIndex(rw http.ResponseWriter, req *http.Request) {
lp := path.Join("templates", "layout.html")
fp := path.Join("templates", "index.html")
// Note that the layout file must be the first parameter in ParseFiles
tmpl, err := template.ParseFiles(lp, fp)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(rw, nil); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
// Give a success message.
rw.WriteHeader(http.StatusOK)
success := response(success, http.StatusOK, "Ready for request.")
rw.Write(success)
}
|
package mt
import "image/color"
type Param1Type uint8
const (
P1Nothing Param1Type = iota
P1Light
)
//go:generate stringer -trimprefix P1 -type Param1Type
type Param2Type uint8
const (
P2Nibble Param2Type = iota
P2Byte
P2Flowing
P2FaceDir
P2Mounted
P2Leveled
P2Rotation
P2Mesh
P2Color
P2ColorFaceDir
P2ColorMounted
P2GlassLikeLevel
)
//go:generate stringer -trimprefix P2 -type Param2Type
// A DrawType specifies how a node is drawn.
type DrawType uint8
const (
DrawCube DrawType = iota
DrawNothing
DrawLiquid
DrawFlowing
DrawLikeGlass
DrawAllFaces
DrawAllFacesOpt
DrawTorch
DrawSign
DrawPlant
DrawFence
DrawRail
DrawNodeBox
DrawGlassFrame
DrawFire
DrawGlassFrameOpt
DrawMesh
DrawRootedPlant
)
//go:generate stringer -trimprefix Draw -type DrawType
type WaveType uint8
const (
NotWaving WaveType = iota
PlantWaving // Only top waves from side to side.
LeafWaving // Wave side to side.
LiquidWaving // Wave up and down.
)
//go:generate stringer -type WaveType
type LiquidType uint8
const (
NotALiquid LiquidType = iota
FlowingLiquid
LiquidSrc
)
//go:generate stringer -type LiquidType
// AlphaUse specifies how the alpha channel of a texture is used.
type AlphaUse uint8
const (
Blend AlphaUse = iota
Mask // "Rounded" to either fully opaque or transparent.
Opaque
Legacy
)
//go:generate stringer -type AlphaUse
type NodeDef struct {
Param0 Content
//mt:lenhdr 16
//mt:const uint8(13)
Name string
Groups []Group
P1Type Param1Type
P2Type Param2Type
DrawType DrawType
Mesh string
Scale float32
//mt:const uint8(6)
Tiles [6]TileDef
OverlayTiles [6]TileDef
//mt:const uint8(6)
SpecialTiles [6]TileDef
Color color.NRGBA
Palette Texture
Waving WaveType
ConnectSides uint8
ConnectTo []Content
InsideTint color.NRGBA
Level uint8 // Must be < 128.
Translucent bool // Sunlight is scattered and becomes normal light.
Transparent bool // Sunlight isn't scattered.
LightSrc uint8
GndContent bool
Collides bool
Pointable bool
Diggable bool
Climbable bool
Replaceable bool
OnRightClick bool
DmgPerSec int32
LiquidType LiquidType
FlowingAlt string
SrcAlt string
Viscosity uint8 // 0-7
LiqRenewable bool
FlowRange uint8
DrownDmg uint8
Floodable bool
DrawBox, ColBox, SelBox NodeBox
FootstepSnd, DiggingSnd, DugSnd SoundDef
LegacyFaceDir bool
LegacyMounted bool
DigPredict string
MaxLvl uint8
AlphaUse
//mt:end
}
func BuiltinNodeDefs(n int) map[Content]NodeDef {
defs := make(map[Content]NodeDef, 3+n)
defs[Unknown] = NodeDef{
Name: "unknown",
}
defs[Air] = NodeDef{
Name: "air",
DrawType: DrawNothing,
P1Type: P1Light,
Translucent: true,
Transparent: true,
Replaceable: true,
Floodable: true,
GndContent: true,
}
defs[Ignore] = NodeDef{
Name: "ignore",
DrawType: DrawNothing,
Replaceable: true,
GndContent: true,
}
return defs
}
|
package main
import (
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type Codec struct {
}
func Constructor() Codec {
return Codec{}
}
// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
res := ""
if root == nil {
return res
}
queue := []*TreeNode{root}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node != nil {
res += strconv.Itoa(node.Val) + ","
queue = append(queue, node.Left)
queue = append(queue, node.Right)
} else {
res += "null,"
}
}
return res[:len(res)-1]
}
// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
if data == "" {
return nil
}
vals, i := strings.Split(data, ","), 1
rootVal, _ := strconv.Atoi(vals[0])
root := &TreeNode{Val: rootVal}
queue := []*TreeNode{root}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if vals[i] != "null" {
nodeVal, _ := strconv.Atoi(vals[i])
node.Left = &TreeNode{Val: nodeVal}
queue = append(queue, node.Left)
}
i++
if vals[i] != "null" {
nodeVal, _ := strconv.Atoi(vals[i])
node.Right = &TreeNode{Val: nodeVal}
queue = append(queue, node.Right)
}
i++
}
return root
}
/**
* Your Codec object will be instantiated and called as such:
* obj := Constructor();
* data := obj.serialize(root);
* ans := obj.deserialize(data);
*/
|
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 options xxx
package options
import (
"github.com/Tencent/bk-bcs/bcs-common/common/conf"
registry "github.com/Tencent/bk-bcs/bcs-common/pkg/registryv4"
)
// UserManagerOptions cmd option for user-manager
type UserManagerOptions struct {
conf.FileConfig
conf.ServiceConfig
conf.MetricConfig
conf.CertConfig
conf.LogConfig
conf.LocalConfig
conf.ProcessConfig
JWTKeyConfig
VerifyClientTLS bool `json:"verify_client_tls" value:"false" usage:"verify client when brings up a tls server" mapstructure:"verify_client_tls"`
RedisDSN string `json:"redis_dsn" value:"" usage:"dsn for connect to redis"`
DSN string `json:"mysql_dsn" value:"" usage:"dsn for connect to mysql"`
BootStrapUsers []BootStrapUser `json:"bootstrap_users"`
TKE TKEOptions `json:"tke"`
PeerToken string `json:"peer_token" value:"" usage:"peer token to authorize with each other, only used to websocket peer"`
// go-micro etcd registry feature support
Etcd registry.CMDOptions `json:"etcdRegistry"`
InsecureEtcd bool `json:"insecure_etcd" value:"false" usage:"if true, will use insecure etcd registry"`
// token notify feature
TokenNotify TokenNotifyOptions `json:"token_notify"`
ClusterConfig ClusterManagerConfig `json:"cluster_config"`
IAMConfig IAMConfig `json:"iam_config"`
PermissionSwitch bool `json:"permission_switch"`
Cmdb CmdbConfig `json:"cmdb"`
CommunityEdition bool `json:"community_edition"`
PassCC PassCCConfig `json:"passcc"`
TracingConf TracingConf `json:"tracing_conf"`
BcsAPI BcsAPI `json:"bcs_api"`
Encrypt Encrypt `json:"encrypt" yaml:"encrypt"`
}
// TracingConf tracing config
type TracingConf struct {
Enabled bool `json:"enabled" usage:"enable trace"`
Endpoint string `json:"endpoint" usage:"Collector service endpoint"`
Token string `json:"token" usage:"token for collector service"`
ResourceAttrs map[string]string `json:"resource_attrs" usage:"attributes of traced service"`
}
// PassCCConfig pass-cc config
type PassCCConfig struct {
AuthServer string `json:"auth_server"`
PassServer string `json:"pass_server"`
AppCode string `json:"app_code"`
AppSecret string `json:"app_secret"`
Enable bool `json:"enable"`
}
// ClusterManagerConfig cluster-manager config
type ClusterManagerConfig struct {
Module string `json:"module"`
}
// IAMConfig iam config
type IAMConfig struct {
SystemID string `json:"system_id"`
AppCode string `json:"app_code"`
AppSecret string `json:"app_secret"`
External bool `json:"external"`
GateWayHost string `json:"gateWay_host"`
IAMHost string `json:"iam_host"`
BkiIAMHost string `json:"bki_iam_host"`
Metric bool `json:"metric"`
ServerDebug bool `json:"server_debug"`
}
// TKEOptions tke api option
type TKEOptions struct {
SecretID string `json:"secret_id" value:"" usage:"tke user account secret id"`
SecretKey string `json:"secret_key" value:"" usage:"tke user account secret key"`
CcsHost string `json:"ccs_host" value:"" usage:"tke ccs host domain"`
CcsPath string `json:"ccs_path" value:"" usage:"tke ccs path"`
}
// BootStrapUser system admin user
type BootStrapUser struct {
Name string `json:"name"`
UserType string `json:"user_type" usage:"optional type: admin, saas, plain"`
Token string `json:"token"`
}
// TokenNotifyOptions token notify option
type TokenNotifyOptions struct {
Feature bool `json:"feature" value:"false" usage:"if true, will enable token notify feature"`
DryRun bool `json:"dry_run" value:"false" usage:"if true, will not send notification"`
NotifyCron string `json:"notify_cron" value:"0 10 * * *" usage:"cron expression for notify"`
EmailTitle string `json:"email_title" value:"" usage:"email title"`
EmailContent string `json:"email_content" value:"" usage:"email content with html format"`
RtxTitle string `json:"rtx_title" value:"" usage:"rtx title"`
RtxContent string `json:"rtx_content" value:"" usage:"rtx content with format"`
ESBConfig ESBConfig `json:"esb_config"`
}
// ESBConfig esb config
type ESBConfig struct {
AppCode string `json:"app_code" value:"" usage:"app code"`
AppSecret string `json:"app_secret" value:"" usage:"app secret"`
APIHost string `json:"api_host" value:"" usage:"api host"`
SendEmailPath string `json:"send_email_path" value:"/api/c/compapi/v2/cmsi/send_mail/" usage:"send email path"`
SendRtxPath string `json:"send_rtx_path" value:"/api/c/compapi/v2/cmsi/send_rtx/" usage:"send rtx path"`
}
// JWTKeyConfig config jwt sign key
type JWTKeyConfig struct {
JWTPublicKeyFile string `json:"jwt_public_key_file" value:"" usage:"JWT public key file" mapstructure:"jwt_public_key_file"`
JWTPrivateKeyFile string `json:"jwt_private_key_file" value:"" usage:"JWT private key file" mapstructure:"jwt_private_key_file"`
}
// CmdbConfig for cmdb
type CmdbConfig struct {
Enable bool `json:"enable"`
AppCode string `json:"app_code"`
AppSecret string `json:"app_secret"`
BkUserName string `json:"bk_user_name"`
Host string `json:"host"`
}
// BcsAPI bcs api config
type BcsAPI struct {
Host string `json:"host" usage:"enable http host"`
InnerHost string `json:"inner_host" usage:"enable http host"`
Token string `json:"token" usage:"token for calling service"`
}
// Encrypt define encrypt config
type Encrypt struct {
Enable bool `json:"enable" yaml:"enable"`
Algorithm string `json:"algorithm" yaml:"algorithm"`
Secret EncryptSecret `json:"secret" yaml:"secret"`
}
// EncryptSecret define encrypt secret
type EncryptSecret struct {
Key string `json:"key" yaml:"key"`
Secret string `json:"secret" yaml:"secret"`
}
|
package ginplugin
import (
"github.com/gin-gonic/gin"
)
const defaultSessionManagerKey = "github.com/goodplayer/Princess"
func SessionHandler(sessionDomainService *SessionDomainService) func(ctx *gin.Context) {
return func(ctx *gin.Context) {
sessionDomainService.initSessionManager(ctx)
ctx.Next()
}
}
func Session(ctx *gin.Context) SessionManager {
return session(ctx)
}
type SessionManager interface {
Set(key string, value []byte)
Get(key string) []byte
Delete(key string)
SaveAndFreeze() error
}
|
package solver
import (
"context"
"github.com/go-air/gini/inter"
"github.com/go-air/gini/z"
)
type choice struct {
prev, next *choice
index int // index of next unguessed literal
candidates []z.Lit
}
type guess struct {
m z.Lit // if z.LitNull, this choice was satisfied by a previous assumption
index int // index of guessed literal in candidates
children int // number of choices introduced by making this guess
candidates []z.Lit
}
type search struct {
s inter.S
lits *litMapping
assumptions map[z.Lit]struct{} // set of assumed lits - duplicates guess stack - for fast lookup
guesses []guess // stack of assumed guesses
headChoice, tailChoice *choice // deque of unmade choices
tracer Tracer
result int
buffer []z.Lit
}
func (h *search) PushGuess() {
c := h.PopChoiceFront()
g := guess{
m: z.LitNull,
index: c.index,
candidates: c.candidates,
}
if g.index < len(g.candidates) {
g.m = g.candidates[g.index]
}
// Check whether or not this choice can be satisfied by an
// existing assumption.
for _, m := range g.candidates {
if _, ok := h.assumptions[m]; ok {
g.m = z.LitNull
break
}
}
h.guesses = append(h.guesses, g)
if g.m == z.LitNull {
return
}
variable := h.lits.VariableOf(g.m)
for _, constraint := range variable.Constraints() {
var ms []z.Lit
for _, dependency := range constraint.order() {
ms = append(ms, h.lits.LitOf(dependency))
}
if len(ms) > 0 {
h.guesses[len(h.guesses)-1].children++
h.PushChoiceBack(choice{candidates: ms})
}
}
if h.assumptions == nil {
h.assumptions = make(map[z.Lit]struct{})
}
h.assumptions[g.m] = struct{}{}
h.s.Assume(g.m)
h.result, h.buffer = h.s.Test(h.buffer)
}
func (h *search) PopGuess() {
g := h.guesses[len(h.guesses)-1]
h.guesses = h.guesses[:len(h.guesses)-1]
if g.m != z.LitNull {
delete(h.assumptions, g.m)
h.result = h.s.Untest()
}
for g.children > 0 {
g.children--
h.PopChoiceBack()
}
c := choice{
index: g.index,
candidates: g.candidates,
}
if g.m != z.LitNull {
c.index++
}
h.PushChoiceFront(c)
}
func (h *search) PushChoiceFront(c choice) {
if h.headChoice == nil {
h.headChoice = &c
h.tailChoice = &c
return
}
h.headChoice.prev = &c
c.next = h.headChoice
h.headChoice = &c
}
func (h *search) PopChoiceFront() choice {
c := h.headChoice
if c.next != nil {
c.next.prev = nil
} else {
h.tailChoice = nil
}
h.headChoice = c.next
return *c
}
func (h *search) PushChoiceBack(c choice) {
if h.tailChoice == nil {
h.headChoice = &c
h.tailChoice = &c
return
}
h.tailChoice.next = &c
c.prev = h.tailChoice
h.tailChoice = &c
}
func (h *search) PopChoiceBack() choice {
c := h.tailChoice
if c.prev != nil {
c.prev.next = nil
} else {
h.headChoice = nil
}
h.tailChoice = c.prev
return *c
}
func (h *search) Result() int {
return h.result
}
func (h *search) Lits() []z.Lit {
result := make([]z.Lit, 0, len(h.guesses))
for _, g := range h.guesses {
if g.m != z.LitNull {
result = append(result, g.m)
}
}
return result
}
func (h *search) Do(ctx context.Context, anchors []z.Lit) (int, []z.Lit, map[z.Lit]struct{}) {
for _, m := range anchors {
h.PushChoiceBack(choice{candidates: []z.Lit{m}})
}
for {
// Need to have a definitive result once all choices
// have been made to decide whether to end or
// backtrack.
if h.headChoice == nil && h.result == unknown {
h.result = h.s.Solve()
}
// Backtrack if possible, otherwise end.
if h.result == unsatisfiable {
h.tracer.Trace(h)
if len(h.guesses) == 0 {
break
}
h.PopGuess()
continue
}
// Satisfiable and no decisions left!
if h.headChoice == nil {
break
}
// Possibly SAT, keep guessing.
h.PushGuess()
}
lits := h.Lits()
set := make(map[z.Lit]struct{}, len(lits))
for _, m := range lits {
set[m] = struct{}{}
}
result := h.Result()
// Go back to the initial test scope.
for len(h.guesses) > 0 {
h.PopGuess()
}
return result, lits, set
}
func (h *search) Variables() []Variable {
result := make([]Variable, 0, len(h.guesses))
for _, g := range h.guesses {
if g.m != z.LitNull {
result = append(result, h.lits.VariableOf(g.candidates[g.index]))
}
}
return result
}
func (h *search) Conflicts() []AppliedConstraint {
return h.lits.Conflicts(h.s)
}
|
package log
import (
"fmt"
"math"
"gopkg.in/cheggaaa/pb.v1"
)
const (
NOCOLOR = 0
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 36
GRAY = 37
UNICODE_FULL_BLOCK = "█"
UNICODE_HALF_BLOCK = "▌"
)
type Report struct {
O float64
Chunk float64
ProgressBar *pb.ProgressBar
}
func NewReport() Report {
return Report{}
}
func (r *Report) ErrorMessage(err error) {
msg := fmt.Sprintf("\x1b[%dmERROR : %s\x1b[%dm", RED, err, NOCOLOR)
fmt.Println(msg)
}
func (r *Report) PrintMessage(msg string) {
fmt.Println(msg)
}
func (r *Report) FormatMessage(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
r.PrintMessage(msg)
}
func (r *Report) CMessage(msg string) {
fmt.Print(msg, " ... ")
}
func (r *Report) FormatCMessage(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
r.CMessage(msg)
}
func (r *Report) NewProgressBar(prefix string, o int) {
bar := pb.New(o).Prefix(prefix).SetMaxWidth(100)
bar.SetUnits(pb.U_BYTES_DEC)
bar.Format("|" + UNICODE_FULL_BLOCK + UNICODE_HALF_BLOCK + " |")
bar.ShowCounters = false
bar.ShowSpeed = true
r.ProgressBar = bar.Start()
r.O = float64(o)
}
func (r *Report) ProgressTick(c float64) {
r.Chunk = r.Chunk + c
chunk := math.Trunc(r.Chunk)
if c > 0.0 {
r.ProgressBar.Add(int(chunk))
r.Chunk = r.Chunk - chunk
}
r.O = r.O - c
}
func (r *Report) ProgressDone() {
r.ProgressBar.Finish()
}
func (r *Report) CreateChunk(m int) float64 {
return r.O / float64(m)
}
|
/*
* Copyright (c) 2020. Denis Rendler <connect@rendler.me>
*
* 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 note
import (
"fmt"
"gopkg.in/go-playground/validator.v9"
)
// InputMessage is an API representation of incoming note data and options
type InputMessage struct {
Content string `json:"content" validate:"required,min=1"`
AutoExpire string `json:"auto-expire,omitempty" validate:"omitempty,expire-interval"`
}
// InputMessage.IsValid is used to validate data passed from the client
func (in *InputMessage) IsValid() (bool, []string) {
v := validator.New()
v.RegisterAlias("expire-interval", "oneof=on-read 5m 30m 1h 24h 48h 168h")
err := v.Struct(in)
if err == nil {
return true, make([]string, 0)
}
var failed []string
for _, errs := range err.(validator.ValidationErrors) {
failed = append(failed, fmt.Sprintf("invalid input for: [%s/%s] with value: [%v]", errs.Namespace(), errs.Tag(), errs.Value()))
}
return false, failed
}
func (in *InputMessage) IsAutoExpire() bool {
switch in.AutoExpire {
case EXPIRE_AFTER_5M,
EXPIRE_AFTER_30M,
EXPIRE_AFTER_1H,
EXPIRE_AFTER_1DAY,
EXPIRE_AFTER_2DAY,
EXPIRE_AFTER_7DAY:
return true
default:
return false
}
}
// LinkMessage is an API representation of successful storage of note and options
type LinkMessage struct {
Status bool `json:"complete"`
Id string `json:"note-id"`
}
// ContentMessage is an API representation of note content stored
type ContentMessage struct {
Status bool `json:"complete"`
Content string `json:"content"`
}
|
/*
* @lc app=leetcode.cn id=70 lang=golang
*
* [70] 爬楼梯
*/
// @lc code=start
package main
import "fmt"
func climbStairs(n int) int {
p, q := 0, 0
r := 1
for i := 1; i <= n; i++ {
p = q
q = r
r = p + q
}
return r
}
func climbStairs2(n int) int {
if n == 2 {
return 2
}
if n == 1 {
return 1
}
return climbStairs(n-1) + climbStairs(n-2)
}
func climbStairs1(n int) int {
ways := 0
var dfs func(int)
// map1 := map[int]bool{}
dfs = func(i int) {
if i == n {
ways += 1
return
}
// if _, ok := map1[i] ; ok {
// return
// } else{
// map1[i] = true
// }
if i+1 <= n {
dfs(i + 1)
}
if i+2 <= n {
dfs(i + 2)
}
}
dfs(0)
return ways
}
// @lc code=end
func main() {
var a int
a = 2
fmt.Printf("%d, %d\n", a, climbStairs(a))
a = 3
fmt.Printf("%d, %d\n", a, climbStairs(a))
a = 4
fmt.Printf("%d, %d\n", a, climbStairs(a))
a = 44
fmt.Printf("%d, %d\n", a, climbStairs(a))
}
|
package anansi
import (
"errors"
"fmt"
"image"
"os"
"syscall"
)
var errAttrNoFile = errors.New("anansi.Attr.ioctl: no File set")
// Attr implements Context-ual manipulation and interrogation of terminal
// state, using the termios IOCTLs and ANSI control sequences where possible.
type Attr struct {
file *os.File // XXX re-export
ownFile bool
orig syscall.Termios
cur syscall.Termios
raw bool
echo bool
}
// IsTerminal returns true only if the given file is attached to an interactive
// terminal.
func IsTerminal(f *os.File) bool {
return Attr{file: f}.IsTerminal()
}
// IsTerminal returns true only if both terminal input and output file handles
// are both connected to a valid terminal.
func (term *Term) IsTerminal() bool {
return IsTerminal(term.Input.File) &&
IsTerminal(term.Output.File)
}
// IsTerminal returns true only if the underlying file is attached to an
// interactive terminal.
func (at Attr) IsTerminal() bool {
_, err := at.getAttr()
return err == nil
}
// Size reads and returns the current terminal size.
func (at Attr) Size() (size image.Point, err error) {
return at.getSize()
}
// SetRaw controls whether the terminal should be in raw mode.
//
// Raw mode is suitable for full-screen terminal user interfaces, eliminating
// keyboard shortcuts for job control, echo, line buffering, and escape key
// debouncing.
func (at *Attr) SetRaw(raw bool) error {
if raw == at.raw {
return nil
}
at.raw = raw
if at.file == nil {
return nil
}
at.cur = at.modifyTermios(at.orig)
if err := at.setAttr(at.cur); err != nil {
return fmt.Errorf("failed to set termios attr: %v", err)
}
return nil
}
// SetEcho toggles input echoing mode, which is off by default in raw mode, and
// on in normal mode.
func (at *Attr) SetEcho(echo bool) error {
if echo == at.echo {
return nil
}
at.echo = echo
if at.file == nil {
return nil
}
if echo {
at.cur.Lflag |= syscall.ECHO
} else {
at.cur.Lflag &^= syscall.ECHO
}
if err := at.setAttr(at.cur); err != nil {
return fmt.Errorf("failed to set termios attr: %v", err)
}
return nil
}
func (at Attr) modifyTermios(attr syscall.Termios) syscall.Termios {
if at.raw {
// TODO read things like antirez's kilo notes again
// TODO naturalize / decompose
attr.Iflag &^= syscall.BRKINT | syscall.ICRNL | syscall.INPCK | syscall.ISTRIP | syscall.IXON
attr.Oflag &^= syscall.OPOST
attr.Cflag &^= syscall.CSIZE | syscall.PARENB
attr.Cflag |= syscall.CS8
attr.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG
attr.Cc[syscall.VMIN] = 1
attr.Cc[syscall.VTIME] = 0
}
if at.echo {
attr.Lflag |= syscall.ECHO
} else {
attr.Lflag &^= syscall.ECHO
}
return attr
}
// Enter default the Attr's file to the term's Output File, records its
// original termios attributes, and then applies termios attributes.
func (at *Attr) Enter(term *Term) (err error) {
if at.file == nil {
at.file = term.Output.File
at.ownFile = false
} else {
at.ownFile = true
}
if at.file == nil {
return nil
}
at.orig, err = at.getAttr()
if err != nil {
return fmt.Errorf("failed to get termios attrs: %v", err)
}
at.cur = at.modifyTermios(at.orig)
if err = at.setAttr(at.cur); err != nil {
return fmt.Errorf("failed to set termios attr: %v", err)
}
return nil
}
// Exit restores termios attributes, and clears the File pointer if it was set
// by Enter
func (at *Attr) Exit(term *Term) error {
if at.file == nil {
return nil
}
if err := at.setAttr(at.orig); err != nil {
return fmt.Errorf("failed to set termios attr: %v", err)
}
if !at.ownFile {
at.file = nil
at.ownFile = false
}
return nil
}
func (at Attr) ioctl(request, arg1, arg2, arg3, arg4 uintptr) error {
if at.file == nil {
return errAttrNoFile
}
if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, at.file.Fd(), request, arg1, arg2, arg3, arg4); e != 0 {
return e
}
return nil
}
|
package handlers
import (
"log"
"net/http"
"github.com/danielhood/quest.server.api/services"
)
// Ping holds handler structure
type Ping struct {
svc services.Ping
}
// NewPing creates an instance of Ping
func NewPing() *Ping {
return &Ping{services.NewPing()}
}
func (h *Ping) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case "GET":
log.Print("/ping:GET")
s := h.svc.Get()
h.enableCors(&w)
w.Write([]byte(s))
default:
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
}
func (h *Ping) enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
|
package leetcode
type ListNode struct {
Val int
Next *ListNode
}
type List struct {
Head *ListNode
Tail *ListNode
}
func (l *List) AddNode(n *ListNode) {
if l.Head == nil {
l.Head = n
}
if l.Tail != nil {
l.Tail.Next = n
}
l.Tail = n
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var list List
var sum, carry, val int
n1, n2 := l1, l2
for n1 != nil || n2 != nil || carry > 0 {
sum = carry
if n1 != nil {
sum += n1.Val
}
if n2 != nil {
sum += n2.Val
}
val, carry = sum%10, sum/10
list.AddNode(&ListNode{Val: val})
if n1 != nil {
n1 = n1.Next
}
if n2 != nil {
n2 = n2.Next
}
}
return list.Head
}
|
package model
import (
_ "fmt"
)
type Choice struct {
comment string
condition string
code Code
}
func NewChoice() *Choice {
return &Choice{}
}
func (this *Choice) AcceptAsFirst(visitor CodeVisitor) {
visitor.VisitChoiceFirstBegin(this)
this.code.Accept(visitor)
visitor.VisitChoiceFirstEnd(this)
}
func (this *Choice) AcceptAsFirstMacro(visitor CodeVisitor) {
visitor.VisitMacroChoiceFirstBegin(this)
this.code.Accept(visitor)
visitor.VisitMacroChoiceFirstEnd(this)
}
func (this *Choice) AcceptAsNonFirst(visitor CodeVisitor) {
visitor.VisitChoiceNonFirstBegin(this)
this.code.Accept(visitor)
visitor.VisitChoiceNonFirstEnd(this)
}
func (this *Choice) AcceptAsNonFirstMacro(visitor CodeVisitor) {
visitor.VisitMacroChoiceNonFirstBegin(this)
this.code.Accept(visitor)
visitor.VisitMacroChoiceNonFirstEnd(this)
}
func (this *Choice) AcceptAsChoiceGropuItem(visitor CodeVisitor) {
visitor.VisitChoiceGroupItemBegin(this)
this.code.Accept(visitor)
visitor.VisitChoiceGroupItemEnd(this)
}
func (this *Choice) SetCode(code Code) {
this.code = code
}
func (this *Choice) SetComment(comment string) {
this.comment = comment
}
func (this *Choice) GetComment() string {
return this.comment
}
func (this *Choice) SetCondition(condition string) {
this.condition = condition
}
func (this *Choice) GetCondition() string {
return this.condition
}
type MultiChoice struct {
comment string
choices []*Choice
lastCode Code
}
func NewMultiChoice() *MultiChoice {
return &MultiChoice{}
}
func (this *MultiChoice) SetComment(comment string) {
this.comment = comment
}
func (this *MultiChoice) GetComment() string {
return this.comment
}
func (this *MultiChoice) AppendChoice(choice ...*Choice) *MultiChoice {
this.choices = append(this.choices, choice...)
return this
}
func (this *MultiChoice) SetLastCode(code Code) {
this.lastCode = code
}
func (this *MultiChoice) ChoiceLen() int {
return len(this.choices)
}
func (this *MultiChoice) Accept(visitor CodeVisitor) {
if len(this.choices) <= 0 {
return
}
visitor.VisitMultiChoiceBegin(this)
this.choices[0].AcceptAsFirst(visitor)
for i := 1; i < len(this.choices); i++ {
this.choices[i].AcceptAsNonFirst(visitor)
}
visitor.VisitMultiChoiceLastCode(this.lastCode)
visitor.VisitMultiChoiceEnd(this)
}
func (this *MultiChoice) AcceptAsMacro(visitor CodeVisitor) {
if len(this.choices) <= 0 {
return
}
visitor.VisitMacroMultiChoiceBegin(this)
this.choices[0].AcceptAsFirstMacro(visitor)
for i := 1; i < len(this.choices); i++ {
this.choices[i].AcceptAsNonFirstMacro(visitor)
}
visitor.VisitMacroMultiChoiceLastCode(this.lastCode)
visitor.VisitMacroMultiChoiceEnd(this)
}
type ChoiceGroup struct {
comment string
condition string
hasDefault bool
choices []*Choice
defaultCode Code
}
func NewChoiceGroup() *ChoiceGroup {
ret := &ChoiceGroup{}
ret.choices = make([]*Choice, 0)
return ret
}
func (this *ChoiceGroup) SetComment(comment string) {
this.comment = comment
}
func (this *ChoiceGroup) GetComment() string {
return this.comment
}
func (this *ChoiceGroup) SetCondition(condition string) {
this.condition = condition
}
func (this *ChoiceGroup) GetCondition() string {
return this.condition
}
func (this *ChoiceGroup) AppendChoice(choice ...*Choice) *ChoiceGroup {
this.choices = append(this.choices, choice...)
return this
}
func (this *ChoiceGroup) SetDefaultCode(code Code) {
this.defaultCode = code
this.hasDefault = true
}
func (this *ChoiceGroup) Accept(visitor CodeVisitor) {
if len(this.choices) <= 0 {
return
}
visitor.VisitChoiceGroupBegin(this)
for i := 0; i < len(this.choices); i++ {
this.choices[i].AcceptAsChoiceGropuItem(visitor)
}
if this.hasDefault {
visitor.VisitChoiceGroupDefaultBegin(this.defaultCode)
this.defaultCode.Accept(visitor)
visitor.VisitChoiceGroupDefaultEnd(this.defaultCode)
}
visitor.VisitChoiceGroupEnd(this)
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
// Data struct
type Data struct {
Coords Coord `json:"coord"`
Weathers map[Weather]interface{} `json:"weather"`
Base string
Mains MainData `json:"main"`
Visibility int
}
// Coord struct
type Coord struct {
Lon float64
Lat float64
}
// Weather struct
type Weather struct {
Id int
Main string
Description string
Icon string
}
// MainData struct
type MainData struct {
Temp float64
FeelsLike int
TempMin int
TempMax int
Pressure int
Humidity int
}
func main() {
url := os.Getenv("API_URL")
r, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
res, err := client.Do(r)
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
data := Data{}
err = json.Unmarshal(body, &data)
if err != nil {
fmt.Println(err)
}
fmt.Println(data)
// fmt.Println("Current Weather:", data.Weathers[0].Main, "\n" +
// "Description:", data.Weathers[0].Description)
}
|
package api
import (
"testing"
"unsafe"
"github.com/stretchr/testify/require"
)
func TestMakeView(t *testing.T) {
data := []byte{0xaa, 0xbb, 0x64}
dataView := makeView(data)
require.Equal(t, cbool(false), dataView.is_nil)
require.Equal(t, cusize(3), dataView.len)
empty := []byte{}
emptyView := makeView(empty)
require.Equal(t, cbool(false), emptyView.is_nil)
require.Equal(t, cusize(0), emptyView.len)
nilView := makeView(nil)
require.Equal(t, cbool(true), nilView.is_nil)
}
func TestCreateAndDestroyUnmanagedVector(t *testing.T) {
// non-empty
{
original := []byte{0xaa, 0xbb, 0x64}
unmanaged := newUnmanagedVector(original)
require.Equal(t, cbool(false), unmanaged.is_none)
require.Equal(t, 3, int(unmanaged.len))
require.GreaterOrEqual(t, 3, int(unmanaged.cap)) // Rust implementation decides this
copy := copyAndDestroyUnmanagedVector(unmanaged)
require.Equal(t, original, copy)
}
// empty
{
original := []byte{}
unmanaged := newUnmanagedVector(original)
require.Equal(t, cbool(false), unmanaged.is_none)
require.Equal(t, 0, int(unmanaged.len))
require.GreaterOrEqual(t, 0, int(unmanaged.cap)) // Rust implementation decides this
copy := copyAndDestroyUnmanagedVector(unmanaged)
require.Equal(t, original, copy)
}
// none
{
var original []byte
unmanaged := newUnmanagedVector(original)
require.Equal(t, cbool(true), unmanaged.is_none)
// We must not make assumtions on the other fields in this case
copy := copyAndDestroyUnmanagedVector(unmanaged)
require.Nil(t, copy)
}
}
// Like the test above but without `newUnmanagedVector` calls.
// Since only Rust can actually create them, we only test edge cases here.
//go:nocheckptr
func TestCopyDestroyUnmanagedVector(t *testing.T) {
{
// ptr, cap and len broken. Do not access those values when is_none is true
invalid_ptr := unsafe.Pointer(uintptr(42))
uv := constructUnmanagedVector(cbool(true), cu8_ptr(invalid_ptr), cusize(0xBB), cusize(0xAA))
copy := copyAndDestroyUnmanagedVector(uv)
require.Nil(t, copy)
}
{
// Capacity is 0, so no allocation happened. Do not access the pointer.
invalid_ptr := unsafe.Pointer(uintptr(42))
uv := constructUnmanagedVector(cbool(false), cu8_ptr(invalid_ptr), cusize(0), cusize(0))
copy := copyAndDestroyUnmanagedVector(uv)
require.Equal(t, []byte{}, copy)
}
}
|
package spec
import (
"github.com/agiledragon/trans-dsl"
"github.com/agiledragon/trans-dsl/test/context"
)
type IsAbcExist struct {
}
func (this *IsAbcExist) Ok(transInfo *transdsl.TransInfo) bool {
stubInfo := transInfo.AppInfo.(*context.StubInfo)
return stubInfo.Abc == "abc"
}
|
package secrets
import (
"context"
"github.com/pkg/errors"
core_ca "github.com/kumahq/kuma/pkg/core/ca"
core_mesh "github.com/kumahq/kuma/pkg/core/resources/apis/mesh"
core_xds "github.com/kumahq/kuma/pkg/core/xds"
)
type CaProvider interface {
// Get returns all PEM encoded CAs, a list of CAs that were used to generate a secret and an error.
Get(context.Context, *core_mesh.MeshResource) (*core_xds.CaSecret, []string, error)
}
func NewCaProvider(caManagers core_ca.Managers) CaProvider {
return &meshCaProvider{
caManagers: caManagers,
}
}
type meshCaProvider struct {
caManagers core_ca.Managers
}
func (s *meshCaProvider) Get(ctx context.Context, mesh *core_mesh.MeshResource) (*core_xds.CaSecret, []string, error) {
backend := mesh.GetEnabledCertificateAuthorityBackend()
if backend == nil {
return nil, nil, errors.New("CA backend is nil")
}
caManager, exist := s.caManagers[backend.Type]
if !exist {
return nil, nil, errors.Errorf("CA manager of type %s not exist", backend.Type)
}
certs, err := caManager.GetRootCert(ctx, mesh.GetMeta().GetName(), backend)
if err != nil {
return nil, nil, errors.Wrap(err, "could not get root certs")
}
return &core_xds.CaSecret{
PemCerts: certs,
}, []string{backend.Name}, nil
}
|
package endpoint
import (
"context"
"fmt"
// "github.com/feng/future/go-kit/agfun/agfun-server/entity"
"github.com/feng/future/go-kit/agfun/agfun-server/protocol"
"github.com/feng/future/go-kit/agfun/agfun-server/service"
// "github.com/go-kit/kit/endpoint"
)
//MakeAccountEndpoint 生成Account断点
func MakeAccountEndpoint(svc service.AppService) Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(protocol.AccountReq)
var resp protocol.Resp
resp, _ = svc.Account(req)
return resp, nil
}
}
//MakeCreateAccountEndpoint 生成CreateAccount端点
func MakeCreateAccountEndpoint(svc service.AppService) Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(protocol.CreateAccountReq)
var resp protocol.Resp
resp, _ = svc.CreateAccount(req)
return resp, nil
}
}
//MakeUpdateAccountEndpoint 更新账户端点
func MakeUpdateAccountEndpoint(svc service.AppService) Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(protocol.UpdateAccountReq)
var resp protocol.Resp
fmt.Println(req)
return resp, nil
}
}
//MakeLoginEndpoint 登录端点
func MakeLoginEndpoint(svc service.AppService) Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(protocol.LoginReq)
var resp protocol.Resp
resp, _ = svc.Login(req)
return resp, nil
}
}
|
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2p
import (
"context"
"fmt"
"github.com/aergoio/aergo/config"
"github.com/aergoio/aergo/p2p/p2pkey"
"reflect"
"strings"
"testing"
"time"
"github.com/aergoio/aergo/p2p/p2pcommon"
"github.com/aergoio/aergo/p2p/p2pmock"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/aergoio/aergo-lib/log"
"github.com/aergoio/aergo/types"
)
const (
sampleKeyFile = "../test/sample.key"
)
var (
// sampleID matches the key defined in test config file
sampleID types.PeerID
)
func init() {
sampleID = "16Uiu2HAmP2iRDpPumUbKhNnEngoxAUQWBmCyn7FaYUrkaDAMXJPJ"
baseCfg := &config.BaseConfig{AuthDir: "test"}
p2pCfg := &config.P2PConfig{NPKey: sampleKeyFile}
p2pkey.InitNodeInfo(baseCfg, p2pCfg, "0.0.1-test", logger)
}
func TestPeerHandshaker_handshakeOutboundPeerTimeout(t *testing.T) {
var myChainID = &types.ChainID{Magic: "itSmain1"}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
logger = log.NewLogger("test")
// dummyStatusMsg := &types.Status{}
tests := []struct {
name string
delay time.Duration
want *types.Status
wantErr bool
}{
// {"TNormal", time.Millisecond, dummyStatusMsg, false},
{"TWriteTimeout", time.Millisecond * 100, nil, true},
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockActor := p2pmock.NewMockActorService(ctrl)
mockPM := p2pmock.NewMockPeerManager(ctrl)
mockCA := p2pmock.NewMockChainAccessor(ctrl)
if !tt.wantErr {
// these will be called if timeout is not happen, so version handshake is called.
mockPM.EXPECT().SelfMeta().Return(dummyMeta).Times(2)
mockActor.EXPECT().GetChainAccessor().Return(mockCA)
mockCA.EXPECT().GetBestBlock().Return(dummyBestBlock, nil)
}
h := newHandshaker(mockPM, mockActor, logger, myChainID, samplePeerID)
mockReader := p2pmock.NewMockReadWriteCloser(ctrl)
mockReader.EXPECT().Read(gomock.Any()).DoAndReturn(func(p []byte) (int, error) {
time.Sleep(tt.delay)
return 0, fmt.Errorf("must not reach")
}).AnyTimes()
mockReader.EXPECT().Write(gomock.Any()).DoAndReturn(func(p []byte) (int, error) {
time.Sleep(tt.delay)
return len(p), nil
})
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
defer cancel()
_, got, err := h.handshakeOutboundPeer(ctx, mockReader)
//_, got, err := h.handshakeOutboundPeerTimeout(mockReader, mockWriter, time.Millisecond*50)
if !strings.Contains(err.Error(), "context deadline exceeded") {
t.Errorf("LegacyWireHandshaker.handshakeOutboundPeer() error = %v, wantErr %v", err, "context deadline exceeded")
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("LegacyWireHandshaker.handshakeOutboundPeer() = %v, want %v", got, tt.want)
}
})
}
}
func TestPeerHandshaker_Select(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
logger = log.NewLogger("test")
mockActor := p2pmock.NewMockActorService(ctrl)
mockPM := p2pmock.NewMockPeerManager(ctrl)
tests := []struct {
name string
hsHeader p2pcommon.HSHeader
wantErr bool
}{
{"TVer030", p2pcommon.HSHeader{p2pcommon.MAGICMain, p2pcommon.P2PVersion030}, false},
{"Tver020", p2pcommon.HSHeader{p2pcommon.MAGICMain, 0x00000200}, true},
{"TInvalid", p2pcommon.HSHeader{p2pcommon.MAGICMain, 0x000001}, true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mockReader := p2pmock.NewMockReadWriteCloser(ctrl)
h := newHandshaker(mockPM, mockActor, logger, nil, samplePeerID)
actual, err := h.selectProtocolVersion(test.hsHeader.Version, mockReader)
assert.Equal(t, test.wantErr, err != nil)
if !test.wantErr {
assert.NotNil(t, actual)
}
})
}
}
|
package cmd
import (
"bytes"
"fmt"
"os"
"os/exec"
"github.com/spf13/cobra"
)
var (
pipelinesGHOAuthKey string
pipelinesGHOAuthSecret string
pipelinesGHOAuthTeam string
pipelinesUsername string
pipelinesPassword string
pipelinesDev bool
)
// initPipelinesCmd represents the initpipelines command
var initPipelinesCmd = &cobra.Command{
Use: "pipelines",
Short: "Init a pipelines server",
Long: `Use docker to run a pipelines server`,
Run: func(cmd *cobra.Command, args []string) {
if pipelinesDev {
pipelinesUsername = "admin"
pipelinesPassword = "admin"
}
if pipelinesUsername != "" && pipelinesPassword != "" {
var stdout, stderr bytes.Buffer
command := fmt.Sprintf(`docker run -d \
--name wcladmin-pipelines \
-p 8888:8888 \
-e ADMIN_USER=%s \
-e ADMIN_PASS=%s \
-v /data/pipelines:/workspace \
-v /data:/data \
boratbot/pipelines`, pipelinesUsername, pipelinesPassword)
prepare := exec.Command("sh", "-c", command)
prepare.Stdout = &stdout
prepare.Stderr = &stderr
if err := prepare.Run(); err != nil {
fmt.Println(stdout.String())
fmt.Println(stderr.String())
fmt.Println(err)
fmt.Println("Start Pipelines failed")
os.Exit(1)
}
return
}
if pipelinesGHOAuthSecret != "" && pipelinesGHOAuthKey != "" && pipelinesGHOAuthTeam != "" {
var stdout, stderr bytes.Buffer
command := fmt.Sprintf(`docker run -d \
--name wcladmin-pipelines \
-p 8888 -e GH_OAUTH_KEY=%s \
-e GH_OAUTH_SECRET=%s \
boratbot/pipelines \
pipelines server \
--github-auth=%s \
--host 0.0.0.0`,
pipelinesGHOAuthKey, pipelinesGHOAuthSecret, pipelinesGHOAuthTeam)
prepare := exec.Command("sh", "-c", command)
prepare.Stdout = &stdout
prepare.Stderr = &stderr
if err := prepare.Run(); err != nil {
fmt.Println(stdout.String())
fmt.Println(stderr.String())
fmt.Println(err)
fmt.Println("Start Pipelines failed")
os.Exit(1)
}
}
},
}
func init() {
initCmd.AddCommand(initPipelinesCmd)
initPipelinesCmd.Flags().StringVar(&pipelinesGHOAuthKey, "gh-oauth-key", "", "Github OAuth key")
initPipelinesCmd.Flags().StringVar(&pipelinesGHOAuthSecret, "gh-oauth-secret", "", "Github OAuth Secret")
initPipelinesCmd.Flags().StringVar(&pipelinesGHOAuthTeam, "gh-oauth-team", "Wiredcraft/core-members,Wiredcraft/leaders", "Github OAuth Team")
initPipelinesCmd.Flags().StringVar(&pipelinesUsername, "username", "admin", "amdin username")
initPipelinesCmd.Flags().StringVar(&pipelinesPassword, "password", "", "admin password")
initPipelinesCmd.Flags().BoolVar(&pipelinesDev, "dev", false, "init pipelines for dev mode(simple pass)")
}
|
package main
import (
"html/template"
"net/http"
"regexp"
"fmt"
"runtime"
"strconv"
"radio"
"flag"
"encoding/json"
"log"
)
var templates = template.Must(template.ParseFiles("index.html"))
var playValidPath = regexp.MustCompile("^/(play)/(\\d)/*(.*)$")
func indexHandler(entryPoint string) func(w http.ResponseWriter, r *http.Request) {
fn := func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, entryPoint)
}
return http.HandlerFunc(fn)
}
func playHandler(w http.ResponseWriter, r *http.Request) {
matchedPath := playValidPath.FindStringSubmatch(r.URL.Path)
fmt.Println(matchedPath[2])
stationId, _ := strconv.Atoi(matchedPath[2])
station := radio.ChooseById(radio.Status.Stations, stationId)
fmt.Println("In play handler of " + station.Name)
if (radio.Status.NowPlaying.Id == station.Id) {
http.Redirect(w, r, "/index/" + string(station.Id) + "/" + station.Name, http.StatusFound)
return
}
go radio.Play(station.Name, station.StreamIpAddress)
radio.Status.NowPlaying = station
data, err := json.Marshal(radio.Status)
if err != nil {
http.Error(w, err.Error(), 400)
}
w.Write(data)
//indexHandler("/index.html")
//http.Redirect(w, r, "/index/" + string(stationId) + "/" + stationName, http.StatusFound)
}
func stopHandler(w http.ResponseWriter, r *http.Request) {
radio.Quit()
radio.Status.NowPlaying = radio.StationInfo{}
data, err := json.Marshal(radio.Status)
if err != nil {
http.Error(w, err.Error(), 400)
}
w.Write(data)
//http.Redirect(w, r, "/index/", http.StatusFound)
}
func radioHandler(w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(radio.Status)
if err != nil {
http.Error(w, err.Error(), 400)
}
w.Write(data)
}
func main() {
entry := flag.String("entry", "./index.html", "Entrypoint")
// static := flag.String("static", ".", "Directory to serve static files from")
port := flag.Int("port", 8080, "Port")
flag.Parse()
radio.Initialize()
filename := "stations.json"
radio.Status.Stations = radio.LoadStations(filename)
runtime.GOMAXPROCS(2)
ww := make(chan bool)
go func() {
//var chttp = http.NewServeMux()
//chttp.Handle("/", http.FileServer(http.Dir("./")))
// http.Handle("/dist/", http.FileServer(http.Dir("./dist/")))
//http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("./dist/"))))
http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("./dist/"))))
http.HandleFunc("/api/v1/radio", radioHandler);
http.HandleFunc("/index/", indexHandler(*entry))
http.HandleFunc("/api/v1/play/", playHandler)
http.HandleFunc("/api/v1/stop/", stopHandler)
http.HandleFunc("/play/", playHandler)
http.HandleFunc("/stop/", stopHandler)
portString := strconv.Itoa(*port)
fmt.Println("Listening on port ", portString)
log.Fatal(http.ListenAndServe(":" + portString, nil))
}()
<- ww
}
|
package main
import (
"github.com/javinc/go-space-shooter"
"github.com/javinc/go-space-shooter/system"
)
const (
title = "Shoot-em-Up"
screenWidth = 450
screenHeight = 600
)
var engine *ecs.Engine
func init() {
engine = ecs.New(title, screenWidth, screenHeight)
}
func main() {
engine.Start()
// Register entities.
engine.AddEntity(newEnemy())
engine.AddEntity(newPlayer())
newEntityPool(newBullet, 1000)
// Register systems.
engine.AddSystems(
system.NewControl(screenWidth, screenHeight),
system.NewMotion(),
system.NewRender(engine.Renderer),
)
engine.Run()
engine.Stop()
}
func newEntityPool(fn func() *ecs.Entity, count int) {
for i := 0; i < count; i++ {
engine.AddEntity(fn())
}
}
|
package chapter14
import (
"fmt"
"testing"
)
func inOrderTraversal(root *TreeNode) {
if root == nil {
return
} else {
inOrderTraversal(root.Left)
fmt.Println(root.Value)
inOrderTraversal(root.Right)
}
}
func TestRebuildBSTPreorder(t *testing.T) {
root := RebuildBSTPreorder([]int{19, 7, 3, 2, 5, 11, 17, 13, 43, 23, 37, 29, 31, 41, 47})
fmt.Println("TestRebuildBSTPreorder:")
inOrderTraversal(root)
fmt.Println()
}
func TestRebuildBSTPreorderBetter(t *testing.T) {
root := RebuildBSTPreorderBetter([]int{19, 7, 3, 2, 5, 11, 17, 13, 43, 23, 37, 29, 31, 41, 47})
fmt.Println("TestRebuildBSTPreorderBetter:")
inOrderTraversal(root)
fmt.Println()
}
|
package main
import "fmt"
func main() {
type NoKtp string
type Married bool
var noKtp NoKtp = "3212902929221"
var status Married = true
fmt.Println(noKtp)
fmt.Println(status)
}
|
package guest
import (
"context"
"github.com/angryronald/guestlist/internal/guest/domain"
"github.com/angryronald/guestlist/internal/guest/public"
)
func (s *Service) ListGuests(ctx context.Context, isArrivedOnly bool) ([]*public.Guest, error) {
guestsRepo, err := s.repository.FindAll(ctx, isArrivedOnly)
if err != nil {
return nil, err
}
result := []*public.Guest{}
for _, guestRepo := range guestsRepo {
guestDomain := &domain.Guest{}
guestDomain.FromRepositoryModel(guestRepo)
result = append(result, guestDomain.ToPublicModel())
}
return result, nil
}
|
package api
import (
"fmt"
"octlink/mirage/src/modules/usergroup"
"octlink/mirage/src/utils"
"octlink/mirage/src/utils/merrors"
"octlink/mirage/src/utils/octlog"
"octlink/mirage/src/utils/uuid"
)
func APIAddUserGroup(paras *ApiParas) *ApiResponse {
resp := new(ApiResponse)
newGroup := usergroup.FindGroupByName(paras.Db, paras.InParas.Paras["name"].(string))
if newGroup != nil {
logger.Errorf("user %s already exist\n", newGroup.Name)
resp.Error = merrors.ERR_SEGMENT_ALREADY_EXIST
return resp
}
newGroup = new(usergroup.UserGroup)
newGroup.Id = uuid.Generate().Simple()
newGroup.Name = paras.InParas.Paras["name"].(string)
newGroup.Desc = paras.InParas.Paras["desc"].(string)
newGroup.AccountId = paras.InParas.Paras["accountId"].(string)
resp.Error = newGroup.Add(paras.Db)
return resp
}
func APIShowUserGroup(paras *ApiParas) *ApiResponse {
octlog.Debug("running in APIShowUser\n")
resp := new(ApiResponse)
groupId := paras.InParas.Paras["id"].(string)
temp := usergroup.FindGroup(paras.Db, groupId)
if temp == nil {
resp.Error = merrors.ERR_SEGMENT_NOT_EXIST
resp.ErrorLog = fmt.Sprintf("group %s not found", groupId)
return resp
}
resp.Data = temp
octlog.Debug("found User %s", temp.Name)
return resp
}
func APIUpdateUserGroup(paras *ApiParas) *ApiResponse {
resp := new(ApiResponse)
id := paras.InParas.Paras["id"].(string)
g := usergroup.FindGroup(paras.Db, id)
if g == nil {
resp.Error = merrors.ERR_USERGROUP_NOT_EXIST
resp.ErrorLog = "User group " + id + "Not Exist"
return resp
}
g.Name = paras.InParas.Paras["name"].(string)
g.Desc = paras.InParas.Paras["desc"].(string)
ret := g.Update(paras.Db)
if ret != 0 {
resp.Error = ret
return resp
}
return resp
}
func APIShowAllUserGroup(paras *ApiParas) *ApiResponse {
resp := new(ApiResponse)
offset := utils.ParasInt(paras.InParas.Paras["start"])
limit := utils.ParasInt(paras.InParas.Paras["limit"])
rows, err := paras.Db.Query("SELECT ID,UG_Name,UG_AccountId,"+
"UG_CreateTime,UG_LastSync,UG_Description "+
"FROM tb_usergroup LIMIT ?,?", offset, limit)
if err != nil {
logger.Errorf("query user group error %s\n", err.Error())
resp.Error = merrors.ERR_DB_ERR
return resp
}
defer rows.Close()
groupList := make([]usergroup.UserGroup, 0)
for rows.Next() {
var group usergroup.UserGroup
err = rows.Scan(&group.Id, &group.Name, &group.AccountId,
&group.CreateTime, &group.LastSync, &group.Desc)
if err == nil {
logger.Debugf("query result: %s:%s\n", group.Id, group.Name)
} else {
logger.Errorf("query usergroup list error %s\n", err.Error())
}
groupList = append(groupList, group)
}
count := usergroup.GetGroupCount(paras.Db)
result := make(map[string]interface{}, 3)
result["total"] = count
result["count"] = len(groupList)
result["data"] = groupList
resp.Data = result
return resp
}
func APIDeleteUserGroup(paras *ApiParas) *ApiResponse {
resp := new(ApiResponse)
id := paras.InParas.Paras["id"].(string)
group := usergroup.FindGroup(paras.Db, id)
if group == nil {
resp.Error = merrors.ERR_USERGROUP_NOT_EXIST
return resp
}
resp.Error = group.Delete(paras.Db)
if resp.Error != 0 {
octlog.Error("remove user group \"%s\" error", group.Name)
resp.ErrorLog = fmt.Sprintf("User Group %s CANNOT be removed", group.Name)
}
return resp
}
func APIShowUserGroupList(paras *ApiParas) *ApiResponse {
resp := new(ApiResponse)
rows, err := paras.Db.Query("SELECT ID,UG_Name FROM tb_usergroup")
if err != nil {
logger.Errorf("query user group list error %s\n", err.Error())
resp.Error = merrors.ERR_DB_ERR
return resp
}
defer rows.Close()
groupList := make([]map[string]string, 0)
for rows.Next() {
var group usergroup.UserGroup
err = rows.Scan(&group.Id, &group.Name)
if err == nil {
logger.Debugf("query result: %s:%s\n", group.Id, group.Name)
} else {
logger.Errorf("query usergroup list error %s\n", err.Error())
}
groupList = append(groupList, group.Brief())
}
resp.Data = groupList
return resp
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package transform
import (
"os"
"testing"
"github.com/Jeffail/gabs"
. "github.com/onsi/gomega"
)
func TestAPIModelMergerMapValues(t *testing.T) {
RegisterTestingT(t)
m := make(map[string]APIModelValue)
values := []string{
"masterProfile.count=5",
"agentPoolProfiles[0].name=agentpool1",
"linuxProfile.adminUsername=admin",
"servicePrincipalProfile.clientId='123a1238-c6eb-4b61-9d6f-7db6f1e14123',servicePrincipalProfile.secret='=!,Test$^='",
"certificateProfile.etcdPeerCertificates[0]=certificate-value",
}
MapValues(m, values)
Expect(m["masterProfile.count"].value).To(BeIdenticalTo(int64(5)))
Expect(m["agentPoolProfiles[0].name"].arrayValue).To(BeTrue())
Expect(m["agentPoolProfiles[0].name"].arrayIndex).To(BeIdenticalTo(0))
Expect(m["agentPoolProfiles[0].name"].arrayProperty).To(BeIdenticalTo("name"))
Expect(m["agentPoolProfiles[0].name"].arrayName).To(BeIdenticalTo("agentPoolProfiles"))
Expect(m["agentPoolProfiles[0].name"].value).To(BeIdenticalTo("agentpool1"))
Expect(m["linuxProfile.adminUsername"].value).To(BeIdenticalTo("admin"))
Expect(m["servicePrincipalProfile.secret"].value).To(BeIdenticalTo("=!,Test$^="))
Expect(m["servicePrincipalProfile.clientId"].value).To(BeIdenticalTo("123a1238-c6eb-4b61-9d6f-7db6f1e14123"))
Expect(m["certificateProfile.etcdPeerCertificates[0]"].arrayValue).To(BeTrue())
Expect(m["certificateProfile.etcdPeerCertificates[0]"].arrayIndex).To(BeIdenticalTo(0))
Expect(m["certificateProfile.etcdPeerCertificates[0]"].arrayProperty).To(BeEmpty())
Expect(m["certificateProfile.etcdPeerCertificates[0]"].arrayName).To(BeIdenticalTo("certificateProfile.etcdPeerCertificates"))
Expect(m["certificateProfile.etcdPeerCertificates[0]"].value).To(BeIdenticalTo("certificate-value"))
}
func TestMergeValuesWithAPIModel(t *testing.T) {
RegisterTestingT(t)
m := make(map[string]APIModelValue)
values := []string{
"masterProfile.count=5",
"agentPoolProfiles[0].name=agentpool1",
"linuxProfile.adminUsername=admin",
"certificateProfile.etcdPeerCertificates[0]=certificate-value",
}
MapValues(m, values)
tmpFile, _ := MergeValuesWithAPIModel("../testdata/simple/kubernetes.json", m)
jsonFileContent, err := os.ReadFile(tmpFile)
Expect(err).To(BeNil())
jsonAPIModel, err := gabs.ParseJSON(jsonFileContent)
Expect(err).To(BeNil())
masterProfileCount := jsonAPIModel.Path("properties.masterProfile.count").Data()
Expect(masterProfileCount).To(BeIdenticalTo(float64(5)))
adminUsername := jsonAPIModel.Path("properties.linuxProfile.adminUsername").Data()
Expect(adminUsername).To(BeIdenticalTo("admin"))
agentPoolProfileName := jsonAPIModel.Path("properties.agentPoolProfiles").Index(0).Path("name").Data().(string)
Expect(agentPoolProfileName).To(BeIdenticalTo("agentpool1"))
etcdPeerCertificates := jsonAPIModel.Path("properties.certificateProfile.etcdPeerCertificates").Index(0).Data()
Expect(etcdPeerCertificates).To(BeIdenticalTo("certificate-value"))
}
|
package sqlconnector
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
"os"
)
func connectCloudSql() (*gorm.DB, error) {
connectionName := os.Getenv("CLOUDSQL_CONNECTION_NAME")
if len(connectionName) == 0 {
return nil, nil
}
user := os.Getenv("CLOUDSQL_USER")
password := os.Getenv("CLOUDSQL_PASSWORD")
socket := os.Getenv("CLOUDSQL_SOCKET")
if len(socket) == 0 {
socket = "/cloudsql"
}
log.Printf("Connecting to database at '%s:[PASSWORD]@unix(%s%s/)/avocado?parseTime=true'.", user, socket, connectionName)
connection := fmt.Sprintf("%s:%s@unix(%s/%s)/avocado?parseTime=true", user, password, socket, connectionName)
db, err := sql.Open("mysql", connection)
if err != nil {
return nil, err
}
return gorm.Open("mysql", db)
}
|
package main
import "fmt"
func main() {
fmt.Println(equalFrequency("abcc"))
fmt.Println(equalFrequency("bac"))
fmt.Println(equalFrequency("ddaccb"))
fmt.Println(equalFrequency("aca"))
}
func equalFrequency(word string) bool {
bs := []byte(word)
var dfs func(idx int) bool
dfs = func(idx int) bool {
m := make(map[byte]int)
for i := 0; i < len(bs); i++ {
if i != idx {
m[bs[i]]++
}
}
mm := make(map[int]int)
for _, v := range m {
mm[v]++
}
if len(mm) == 1 {
return true
}
return false
}
for i := 0; i < len(bs); i++ {
if dfs(i) {
return true
}
}
return false
}
|
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/strava/go.strava"
"gopkg.in/natefinch/lumberjack.v2"
"log"
"os"
"path/filepath"
)
// Main function.
func main() {
appDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
log.SetOutput(&lumberjack.Logger{
Filename: filepath.Join(appDir, "service.log"),
MaxSize: 500, // megabytes
MaxBackups: 3,
})
defaultSettingsPath := filepath.Join(appDir, "settings.default.json")
localSettingsPath := filepath.Join(appDir, "settings.local.json")
settings, err := LoadSettings(defaultSettingsPath, localSettingsPath)
if err != nil {
log.Fatalf("Can't load settings: %v\n", err)
}
db, err := gorm.Open("mysql", settings.DatabaseUri)
if err != nil {
log.Fatalf("Can't connect to the database: %v\n", err)
}
err = runMigrations(db)
if err != nil {
log.Fatalf("Can't execute database migrations: %v\n", err)
}
repo := NewRepository(db.Debug())
fixMissingStravaUsersId(repo)
fixMissingStravaUserNames(repo)
server := NewServer(settings, repo, appDir)
server.Run()
}
// Run database migrations.
func runMigrations(db *gorm.DB) error {
res := db.AutoMigrate(&AccessDetails{}, &BotDetails{}, &JobDetails{}, &SentDetails{}, &ClubDetails{}, &UserDetails{}, &UserClubDetails{}, &PendingUnlock{})
return res.Error
}
func fixMissingStravaUsersId(repo *Repository) {
accessDetails, err := repo.AccessDetails.List()
if err != nil {
log.Fatal(err)
}
for _, access := range accessDetails {
if access.StravaUserId == 0 {
client := strava.NewClient(access.StravaToken)
service := strava.NewCurrentAthleteService(client)
athlete, err := service.Get().Do()
if err == nil {
repo.AccessDetails.Update(access, map[string]interface{}{"StravaUserId": athlete.Id})
}
}
}
}
func fixMissingStravaUserNames(repo *Repository) {
userDetails, err := repo.UserDetails.List()
if err != nil {
log.Fatal(err)
}
for _, user := range userDetails {
if user.UserName == "" {
access, err := repo.AccessDetails.GetByStravaUserId(user.StravaUserId)
if err == nil {
client := strava.NewClient(access.StravaToken)
service := strava.NewCurrentAthleteService(client)
athlete, err := service.Get().Do()
if err == nil {
repo.UserDetails.Update(user, map[string]interface{}{"UserName": athlete.FirstName + " " + athlete.LastName})
}
}
}
}
}
|
package promise
import (
"encoding/json"
"errors"
"fmt"
"log"
"gopkg.in/confluentinc/confluent-kafka-go.v1/kafka"
)
// KafkaConfig is a config for using kafka
type KafkaConfig struct {
BoostrapServers string
}
// KafkaClient is a client that can consumes and produces messages
type KafkaClient struct {
producer map[string]*kafka.Producer
consumer map[string]*kafka.Consumer
config KafkaConfig
}
// Message is a Kafka messages to be send to the producer
type Message struct {
Topic *string
Headers map[string]string
Value interface{}
}
// CreateKafkaClient creates a kaka client from config
func CreateKafkaClient(config KafkaConfig) *KafkaClient {
return &KafkaClient{config: config}
}
func (client *KafkaClient) ensureProducer() {
if client.producer == nil {
client.producer = make(map[string]*kafka.Producer)
}
if len(client.producer) > 0 {
for k, producer := range client.producer {
if producer == nil {
p, err := kafka.NewProducer(&kafka.ConfigMap{"bootstrap.servers": client.config.BoostrapServers})
if err == nil {
client.producer[k] = p
} else {
panic("Couldn't create a producer for " + k)
}
}
}
}
}
func (client *KafkaClient) addProducer(topic string) {
fmt.Println(topic)
if _, exists := client.producer[topic]; exists {
return
}
client.ensureProducer()
p, err := kafka.NewProducer(&kafka.ConfigMap{"bootstrap.servers": client.config.BoostrapServers})
if err == nil {
client.producer[topic] = p
} else {
fmt.Println(err)
panic("Couldn't create a producer for " + topic)
}
}
// PublishMessage publishes messages to a kafka stream then returns a promise
func (client *KafkaClient) PublishMessage(message Message) Promise {
return FromFunc(func() (interface{}, error) {
client.addProducer(*message.Topic)
payload, err := stringify(message.Value)
if err != nil {
return nil, err
}
return Message{Topic: message.Topic, Headers: message.Headers, Value: payload}, nil
}).Then(func(msg interface{}) (interface{}, error) {
topic := *msg.(Message).Topic
if producer, ok := client.producer[topic]; ok {
deliveryChan := make(chan kafka.Event)
err := producer.Produce(createMessage(msg.(Message)), deliveryChan)
if err != nil {
return nil, err
}
return deliveryChan, nil
}
return nil, errors.New("Topic doesn't exist " + topic)
}).Then(func(msg interface{}) (interface{}, error) {
deliveryChan := msg.(chan kafka.Event)
e := <-deliveryChan
m := e.(*kafka.Message)
close(deliveryChan)
if m.TopicPartition.Error != nil {
return nil, fmt.Errorf("Delivery failed: %v\n", m.TopicPartition.Error)
}
log.Printf("Delivered message to topic %s [%d] at offset %v\n",
*m.TopicPartition.Topic, m.TopicPartition.Partition, m.TopicPartition.Offset)
return m, nil
})
}
func stringify(value interface{}) ([]byte, error) {
switch v := value.(type) {
case string:
return []byte(v), nil
default:
return json.Marshal(v)
}
}
func createMessage(msg Message) *kafka.Message {
// headers map[string]string, value []byte, topic *string
if msg.Headers == nil {
return &kafka.Message{TopicPartition: kafka.TopicPartition{Topic: msg.Topic, Partition: kafka.PartitionAny}, Value: msg.Value.([]byte)}
}
lis := make([]kafka.Header, 0)
for name, value := range msg.Headers {
lis = append(lis, kafka.Header{Key: name, Value: []byte(value)})
}
return &kafka.Message{TopicPartition: kafka.TopicPartition{Topic: msg.Topic, Partition: kafka.PartitionAny}, Value: msg.Value.([]byte), Headers: lis}
}
|
package arangodb
import (
"fmt"
"github.com/apex/log"
"github.com/thedanielforum/arangodb/errc"
)
func (c *Connection) Delete(collectionName string ,docHandle string) error {
endPoint := fmt.Sprintf("_db/%s/_api/document/%s/%s", c.db, collectionName,docHandle)
_,err := c.del(endPoint, nil)
if err != nil {
//log.WithError(err).Info(arangodb.ErrorCodeInvalidEdgeAttribute.Error().Error())
return errc.ErrorCodeNoResult.Error()
}
if c.config.DebugMode {
log.Infof("Deleted document %s in: %s", docHandle,collectionName)
}
return nil
}
|
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
package commands
import (
"strings"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func ExampleRunImages() {
ctx := testCommandContext()
args := ImagesArgs{}
RunImages(ctx, args)
}
func ExampleRunImages_complex() {
ctx := testCommandContext()
args := ImagesArgs{
All: false,
NoTrunc: false,
Quiet: false,
}
RunImages(ctx, args)
}
func ExampleRunImages_quiet() {
ctx := testCommandContext()
args := ImagesArgs{
All: false,
NoTrunc: false,
Quiet: true,
}
RunImages(ctx, args)
}
func ExampleRunImages_all() {
ctx := testCommandContext()
args := ImagesArgs{
All: true,
NoTrunc: false,
Quiet: false,
}
RunImages(ctx, args)
}
func ExampleRunImages_notrunc() {
ctx := testCommandContext()
args := ImagesArgs{
All: false,
NoTrunc: true,
Quiet: false,
}
RunImages(ctx, args)
}
func TestRunImages_realAPI(t *testing.T) {
ctx := RealAPIContext()
if ctx == nil {
t.Skip()
}
Convey("Testing RunImages() on real API", t, func() {
Convey("no options", func() {
args := ImagesArgs{
All: false,
NoTrunc: false,
Quiet: false,
}
scopedCtx, scopedStdout, scopedStderr := getScopedCtx(ctx)
err := RunImages(*scopedCtx, args)
So(err, ShouldBeNil)
So(scopedStderr.String(), ShouldBeEmpty)
lines := strings.Split(scopedStdout.String(), "\n")
So(len(lines), ShouldBeGreaterThan, 0)
firstLine := lines[0]
colNames := strings.Fields(firstLine)
So(colNames, ShouldResemble, []string{"REPOSITORY", "TAG", "IMAGE", "ID", "CREATED", "REGION", "ARCH"})
// FIXME: test public images
})
Convey("--all", func() {
args := ImagesArgs{
All: true,
NoTrunc: false,
Quiet: false,
}
scopedCtx, scopedStdout, scopedStderr := getScopedCtx(ctx)
err := RunImages(*scopedCtx, args)
So(err, ShouldBeNil)
So(scopedStderr.String(), ShouldBeEmpty)
lines := strings.Split(scopedStdout.String(), "\n")
So(len(lines), ShouldBeGreaterThan, 0)
firstLine := lines[0]
colNames := strings.Fields(firstLine)
So(colNames, ShouldResemble, []string{"REPOSITORY", "TAG", "IMAGE", "ID", "CREATED", "REGION", "ARCH"})
// FIXME: test public images
// FIXME: test bootscripts
// FIXME: test snapshots
})
Convey("--quiet", func() {
args := ImagesArgs{
All: false,
NoTrunc: false,
Quiet: true,
}
scopedCtx, scopedStdout, scopedStderr := getScopedCtx(ctx)
err := RunImages(*scopedCtx, args)
So(err, ShouldBeNil)
So(scopedStderr.String(), ShouldBeEmpty)
lines := strings.Split(scopedStdout.String(), "\n")
// So(len(lines), ShouldBeGreaterThan, 0)
if len(lines) > 0 {
firstLine := lines[0]
colNames := strings.Fields(firstLine)
So(colNames, ShouldNotResemble, []string{"REPOSITORY", "TAG", "IMAGE", "ID", "CREATED"})
// FIXME: test public images
// FIXME: test bootscripts
// FIXME: test snapshots
}
})
})
}
|
package sdk
import (
"context"
"encoding/json"
"net/http"
rm "github.com/brigadecore/brigade/sdk/v3/internal/restmachinery"
"github.com/brigadecore/brigade/sdk/v3/meta"
"github.com/brigadecore/brigade/sdk/v3/restmachinery"
)
const (
// RoleAssignmentKind represents the canonical RoleAssignment kind string
RoleAssignmentKind = "RoleAssignment"
// RoleAssignmentListKind represents the canonical RoleAssignmentList kind
// string
RoleAssignmentListKind = "RoleAssignmentList"
// PrincipalTypeServiceAccount represents a principal that is a
// ServiceAccount.
PrincipalTypeServiceAccount PrincipalType = "SERVICE_ACCOUNT"
// PrincipalTypeUser represents a principal that is a User.
PrincipalTypeUser PrincipalType = "USER"
)
// RoleAssignment represents the assignment of a Role to a principal such as a
// User or ServiceAccount.
type RoleAssignment struct {
// Role assigns a Role to the specified principal.
Role Role `json:"role"`
// Principal specifies the principal to whom the Role is assigned.
Principal PrincipalReference `json:"principal"`
// Scope qualifies the scope of the Role. The value is opaque and has meaning
// only in relation to a specific Role.
Scope string `json:"scope,omitempty"`
}
// MarshalJSON amends RoleAssignment instances with type metadata so that
// clients do not need to be concerned with the tedium of doing so.
func (r RoleAssignment) MarshalJSON() ([]byte, error) {
type Alias RoleAssignment
return json.Marshal(
struct {
meta.TypeMeta `json:",inline"`
Alias `json:",inline"`
}{
TypeMeta: meta.TypeMeta{
APIVersion: meta.APIVersion,
Kind: RoleAssignmentKind,
},
Alias: (Alias)(r),
},
)
}
// RoleAssignmentList is an ordered and pageable list of RoleAssignments.
type RoleAssignmentList struct {
// ListMeta contains list metadata.
meta.ListMeta `json:"metadata"`
// Items is a slice of RoleAssignments.
Items []RoleAssignment `json:"items,omitempty"`
}
// MarshalJSON amends RoleAssignmentList instances with type metadata so that
// clients do not need to be concerned with the tedium of doing so.
func (r RoleAssignmentList) MarshalJSON() ([]byte, error) {
type Alias RoleAssignmentList
return json.Marshal(
struct {
meta.TypeMeta `json:",inline"`
Alias `json:",inline"`
}{
TypeMeta: meta.TypeMeta{
APIVersion: meta.APIVersion,
Kind: RoleAssignmentListKind,
},
Alias: (Alias)(r),
},
)
}
// RoleAssignmentsSelector represents useful filter criteria when selecting
// multiple RoleAssignments for API group operations like list.
type RoleAssignmentsSelector struct {
// Principal specifies that only RoleAssignments for the specified Principal
// should be selected.
Principal *PrincipalReference
// Role specifies that only RoleAssignments for the specified Role should be
// selected.
Role Role
}
// RoleAssignmentGrantOptions represents useful, optional settings for granting
// a Role to a Principal. It currently has no fields, but exists to preserve the
// possibility of future expansion without having to change client function
// signatures.
type RoleAssignmentGrantOptions struct{}
// RoleAssignmentRevokeOptions represents useful, optional settings for revoking
// a Role from a Principal. It currently has no fields, but exists to preserve
// the possibility of future expansion without having to change client function
// signatures.
type RoleAssignmentRevokeOptions struct{}
// RoleAssignmentsClient is the specialized client for managing RoleAssignments
// with the Brigade API.
type RoleAssignmentsClient interface {
// Grant grants the system-level Role specified by the RoleAssignment to the
// principal also specified by the RoleAssignment.
Grant(
context.Context,
RoleAssignment,
*RoleAssignmentGrantOptions,
) error
// List returns a RoleAssignmentsList, with its Items (RoleAssignments)
// ordered by principal type, principalID, role, and scope. Criteria for which
// RoleAssignments should be retrieved can be specified using the
// RoleAssignmentsSelector parameter.
List(
context.Context,
*RoleAssignmentsSelector,
*meta.ListOptions,
) (RoleAssignmentList, error)
// Revoke revokes the system-level Role specified by the RoleAssignment for
// the principal also specified by the RoleAssignment.
Revoke(
context.Context,
RoleAssignment,
*RoleAssignmentRevokeOptions,
) error
}
type roleAssignmentsClient struct {
*rm.BaseClient
}
// NewRoleAssignmentsClient returns a specialized client for managing
// RoleAssignments.
func NewRoleAssignmentsClient(
apiAddress string,
apiToken string,
opts *restmachinery.APIClientOptions,
) RoleAssignmentsClient {
return &roleAssignmentsClient{
BaseClient: rm.NewBaseClient(apiAddress, apiToken, opts),
}
}
func (r *roleAssignmentsClient) Grant(
ctx context.Context,
roleAssignment RoleAssignment,
_ *RoleAssignmentGrantOptions,
) error {
return r.ExecuteRequest(
ctx,
rm.OutboundRequest{
Method: http.MethodPost,
Path: "v2/role-assignments",
ReqBodyObj: roleAssignment,
SuccessCode: http.StatusOK,
},
)
}
func (r *roleAssignmentsClient) List(
ctx context.Context,
selector *RoleAssignmentsSelector,
opts *meta.ListOptions,
) (RoleAssignmentList, error) {
queryParams := map[string]string{}
if selector != nil {
if selector.Principal != nil {
queryParams["principalType"] = string(selector.Principal.Type)
queryParams["principalID"] = selector.Principal.ID
}
if selector.Role != "" {
queryParams["role"] = string(selector.Role)
}
}
roleAssignments := RoleAssignmentList{}
return roleAssignments, r.ExecuteRequest(
ctx,
rm.OutboundRequest{
Method: http.MethodGet,
Path: "v2/role-assignments",
QueryParams: r.AppendListQueryParams(queryParams, opts),
SuccessCode: http.StatusOK,
RespObj: &roleAssignments,
},
)
}
func (r *roleAssignmentsClient) Revoke(
ctx context.Context,
roleAssignment RoleAssignment,
_ *RoleAssignmentRevokeOptions,
) error {
queryParams := map[string]string{
"role": string(roleAssignment.Role),
"principalType": string(roleAssignment.Principal.Type),
"principalID": roleAssignment.Principal.ID,
}
if roleAssignment.Scope != "" {
queryParams["scope"] = roleAssignment.Scope
}
return r.ExecuteRequest(
ctx,
rm.OutboundRequest{
Method: http.MethodDelete,
Path: "v2/role-assignments",
QueryParams: queryParams,
SuccessCode: http.StatusOK,
},
)
}
|
package sys
import "easyctl/util"
// 查询端口监听
func SearchPortStatus(port string) (result string, err error) {
cmd := "ss -alnpt|grep " + port
return util.ExecuteCmdAcceptResult(cmd)
}
|
package models
import (
"github.com/jinzhu/gorm"
// psql driver only w/Initializers
_ "github.com/jinzhu/gorm/dialects/postgres"
// sqlite driver only w/Initializers
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
// Database - namespace
type Database struct {
*gorm.DB
}
// NewPostgresDatabase - postgres database creation
func NewPostgresDatabase(dataSourceName string) *Database {
db, err := gorm.Open("postgres", dataSourceName)
if err != nil {
panic(err)
}
if err = db.DB().Ping(); err != nil {
panic(err)
}
//db.LogMode(true)
return &Database{db}
}
// NewSqliteDatabase - sqlite database creation
func NewSqliteDatabase(databaseName string) *Database {
db, err := gorm.Open("sqlite3", databaseName)
if err != nil {
panic(err)
}
if err = db.DB().Ping(); err != nil {
panic(err)
}
//db.LogMode(true)
return &Database{db}
}
|
package app
import (
"github.com/gin-gonic/gin"
"github.com/mvrsss/go-todo-api/app/controllers"
)
func SetRouters() *gin.Engine {
r := gin.Default()
v1 := r.Group("/v1")
{
v1.GET("todo", controllers.GetAllTasks)
v1.POST("todo", controllers.AddTask)
v1.GET("todo/:id", controllers.GetATask)
v1.PUT("todo/:id", controllers.UpdateTasks)
v1.DELETE("todo/:id", controllers.DeleteTasks)
}
return r
}
|
package quicksort
import (
"log"
"math/rand"
)
// Basic quicksort algorithm (Hoore circa 1961)
// Sort the array in-place
func Sort(a []int, strategy PivotChoice) (count int) {
if len(a) <= 1 {
return
}
// Swap pivot to the first position in a[left]
strategy.Pivot(a)
index := Partition(a)
count += len(a) -1
left := a[:index - 1]
count += Sort(left, strategy)
right := a[index:]
count += Sort(right, strategy)
return count
}
// Insert the first element between all elements < and > the element
func Partition(a []int) (split int) {
// Can be done in linear time with no extra overhead (memory)
// reduces problem size (allows divide and conquer algorithm)
// Partitioning at the base case is equivalent to sorting
// Single scan of array - keep track of 'read' and 'unread'
// 'read' is split into less than and greater than pivot 'p'
// [p, < p | > p | unread ]
// [0, ^split ^edge ]
split = 1
p := a[0]
for edge, next_value := range a {
// edge is the right-boundary of partiotioned, read sub-array
if next_value < p {
// insert a[edge] into the left partition (bounded by split)
// First item to the right of split can be moved to the edge.
if edge > split {
Swap(a, split, edge)
}
// increment split
split += 1
}
edge++
}
// The Swap the last element in the < p section with p.
if split > 1 {
Swap(a, 0, split -1)
}
return split
}
// Chooses a pivot for the array - swaps the pivot to the first element
type PivotChoice func([]int)
// Calls the function provided by the type
func (f PivotChoice) Pivot(a []int) {
f(a)
}
// PivotLeft does nothing (but does it well)
func PivotLeft(_ []int) {
// No-op
}
// PivotMedian uses the median value of the first, middle, and last
// element in the given array as the pivot
func PivotMedian(a []int) {
var median int
n := len(a)
if n < 3 {
return
}
left, mid, right := a[0], a[(n - 1)/2], a[n-1]
switch {
case right > left && left > mid || mid > left && left > right:
return
case left > mid && mid > right || right > mid && mid > left:
median = (n - 1)/2
case mid > right && right > left || left > right && right > mid:
median = n-1
default:
log.Print(a)
log.Panicf("left: %v, mid %v, right %v",
left, mid, right)
}
Swap(a, 0, median)
}
// PivotRight uses the last element in the slice as the pivot
func PivotRight(a []int) {
Swap(a, 0, len(a) - 1)
}
func PivotRand(a []int) {
i := rand.Intn(len(a))
Swap(a, 0, i)
}
// Swap two indeces in place in a slice
func Swap(a []int, left, right int) {
a[left], a[right] = a[right], a[left]
}
|
/*
* @lc app=leetcode.cn id=12 lang=golang
*
* [12] 整数转罗马数字
*/
// @lc code=start
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
var a int
a = 90
fmt.Printf("%d, %s\n", a, intToRoman(a))
a = 1049
fmt.Printf("%d, %s\n", a, intToRoman(a))
a = 100049
fmt.Printf("%d, %s\n", a, intToRoman(a))
}
func intToRoman(num int) string {
roman := []string{"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"}
intSlice := []int{1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000}
size := len(intSlice) - 1
res := ""
for num > 0 {
a := strconv.Itoa(num)
x := len(a) - 1
// 算有几个罗马数字的倍数
b := (num / int(math.Pow10(x))) * int(math.Pow10(x))
// 循环
for size >= 0 {
if b >= intSlice[size] {
res += roman[size]
num -= intSlice[size]
break
} else {
size--
}
}
}
return res
}
// @lc code=end
|
// Copyright © 2018 Sunface <CTO@188.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/mafanr/g"
"github.com/weaveworks/mesh"
"go.uber.org/zap"
)
type cluster struct {
bk *Broker
closed chan struct{}
peer *peer
}
func (c *cluster) Init() {
c.closed = make(chan struct{})
peers := stringset{}
hwaddr := c.bk.conf.Cluster.HwAddr
meshListen := net.JoinHostPort("0.0.0.0", c.bk.conf.Cluster.Port)
channel := "default"
nickname := mustHostname()
for _, peer := range c.bk.conf.Cluster.SeedPeers {
peers[peer] = struct{}{}
}
host, portStr, err := net.SplitHostPort(meshListen)
if err != nil {
g.L.Fatal("cluster address invalid", zap.Error(err), zap.String("listen_addr", meshListen))
}
port, err := strconv.Atoi(portStr)
if err != nil {
g.L.Fatal("cluter port invalid", zap.Error(err), zap.String("listen_port", portStr))
}
name, err := mesh.PeerNameFromString(hwaddr)
if err != nil {
g.L.Fatal("hardware addr invalid", zap.Error(err), zap.String("hardware_addr", hwaddr))
}
router, err := mesh.NewRouter(mesh.Config{
Host: host,
Port: port,
ProtocolMinVersion: mesh.ProtocolMinVersion,
ConnLimit: 64,
PeerDiscovery: true,
TrustedSubnets: []*net.IPNet{},
}, name, nickname, mesh.NullOverlay{}, log.New(ioutil.Discard, "", 0))
if err != nil {
g.L.Fatal("Could not create cluster", zap.Error(err))
}
peer := newPeer(name, c.bk)
gossip, err := router.NewGossip(channel, peer)
if err != nil {
g.L.Fatal("Could not create cluster gossip", zap.Error(err))
}
peer.register(gossip)
c.peer = peer
// if the memory mode is using, we need to init nodes's synchronization for memory data
ms, ok := c.bk.store.(*MemStore)
if ok {
fmt.Println("init mem cluster-channel")
ms.pn = name
g1, err := router.NewGossip("mem-store", ms)
if err != nil {
g.L.Fatal("Could not create cluster gossip", zap.Error(err))
}
ms.register(g1)
}
// start topics sync
// c.bk.topics.pn = name
// t, err := router.NewGossip("topics", c.bk.topics)
// if err != nil {
// g.L.Fatal("Could not create cluster gossip", zap.Error(err))
// }
// c.bk.topics.register(t)
go func() {
g.L.Debug("cluster starting", zap.String("listen_addr", meshListen))
router.Start()
}()
defer func() {
g.L.Debug("cluster stopping", zap.String("listen_addr", meshListen))
router.Stop()
}()
router.ConnectionMaker.InitiateConnections(peers.slice(), true)
// loop to get the running time of other nodes
go func() {
submsg := SubMessage{CLUSTER_RUNNING_TIME_REQ, nil, 0, []byte("")}
syncmsg := make([]byte, 5)
syncmsg[4] = CLUSTER_SUBS_SYNC_REQ
c.bk.cluster.peer.longestRunningTime = uint64(c.bk.runningTime.Unix())
n := 0
for {
if n > 3 {
break
}
time.Sleep(5 * time.Second)
if c.bk.subSynced {
break
}
c.bk.cluster.peer.send.GossipBroadcast(submsg)
time.Sleep(3 * time.Second)
// sync the subs from the longest running node
if c.bk.cluster.peer.longestRunningTime < uint64(c.bk.runningTime.Unix()) {
c.bk.cluster.peer.send.GossipUnicast(c.bk.cluster.peer.longestRunningName, syncmsg)
continue
}
// 没有节点比本地节点运行时间更久,为了以防万一,我们做4次循环
n++
}
}()
select {
case <-c.closed:
}
}
func (c *cluster) Close() {
c.closed <- struct{}{}
}
// Peer encapsulates state and implements mesh.Gossiper.
// It should be passed to mesh.Router.NewGossip,
// and the resulting Gossip registered in turn,
// before calling mesh.Router.Start.
type peer struct {
name mesh.PeerName
bk *Broker
send mesh.Gossip
longestRunningName mesh.PeerName
longestRunningTime uint64
}
// peer implements mesh.Gossiper.
var _ mesh.Gossiper = &peer{}
// Construct a peer with empty state.
// Be sure to register a channel, later,
// so we can make outbound communication.
func newPeer(pn mesh.PeerName, b *Broker) *peer {
p := &peer{
name: pn,
bk: b,
send: nil, // must .register() later
}
return p
}
// register the result of a mesh.Router.NewGossip.
func (p *peer) register(send mesh.Gossip) {
p.send = send
}
func (p *peer) stop() {
}
// Return a copy of our complete state.
func (p *peer) Gossip() (complete mesh.GossipData) {
return
}
// Merge the gossiped data represented by buf into our state.
// Return the state information that was modified.
func (p *peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) {
return
}
// Merge the gossiped data represented by buf into our state.
// Return the state information that was modified.
func (p *peer) OnGossipBroadcast(src mesh.PeerName, buf []byte) (received mesh.GossipData, err error) {
var msg SubMessage
err = gob.NewDecoder(bytes.NewReader(buf)).Decode(&msg)
if err != nil {
g.L.Info("on gossip broadcast decode error", zap.Error(err))
return
}
switch msg.TP {
case CLUSTER_SUB:
p.bk.subtrie.Subscribe(msg.Topic, msg.Cid, src, msg.UserName)
case CLUSTER_UNSUB:
p.bk.subtrie.UnSubscribe(msg.Topic, msg.Cid, src)
case CLUSTER_RUNNING_TIME_REQ:
t := make([]byte, 13)
t[4] = CLUSTER_RUNNING_TIME_RESP
binary.PutUvarint(t[5:], uint64(p.bk.runningTime.Unix()))
p.send.GossipUnicast(src, t)
}
return
}
// Merge the gossiped data represented by buf into our state.
func (p *peer) OnGossipUnicast(src mesh.PeerName, buf []byte) error {
switch buf[4] {
case CLUSTER_RUNNING_TIME_RESP:
t, _ := binary.Uvarint(buf[5:])
if t < p.longestRunningTime {
p.longestRunningName = src
p.longestRunningTime = t
}
case CLUSTER_SUBS_SYNC_REQ:
b := p.bk.subtrie.Encode()[0]
p.send.GossipUnicast(src, b)
case CLUSTER_SUBS_SYNC_RESP:
set := NewSubTrie()
err := gob.NewDecoder(bytes.NewReader(buf[5:])).Decode(&set)
if err != nil {
g.L.Info("on gossip decode error", zap.Error(err))
return err
}
p.bk.subtrie = set
p.bk.subSynced = true
case CLUSTER_MSG_ROUTE:
p.bk.router.recvRoute(src, buf[5:])
}
return nil
}
type stringset map[string]struct{}
func (ss stringset) Set(value string) error {
ss[value] = struct{}{}
return nil
}
func (ss stringset) String() string {
return strings.Join(ss.slice(), ",")
}
func (ss stringset) slice() []string {
slice := make([]string, 0, len(ss))
for k := range ss {
slice = append(slice, k)
}
sort.Strings(slice)
return slice
}
func mustHardwareAddr() string {
ifaces, err := net.Interfaces()
if err != nil {
panic(err)
}
for _, iface := range ifaces {
if s := iface.HardwareAddr.String(); s != "" {
return s
}
}
panic("no valid network interfaces")
}
func mustHostname() string {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
return hostname
}
|
package main
import "fmt"
func searchMatrix(matrix [][]int, target int) bool {
return searchMatrix3(matrix, target)
}
// https://leetcode-cn.com/problems/search-a-2d-matrix/
func searchMatrix1(matrix [][]int, target int) bool {
n := len(matrix)
if n == 0 {
return false
}
m := len(matrix[0])
if m == 0 {
return false
}
get := func(i int) int { return matrix[i/m][i%m] }
l, h := 0, m*n-1
for l <= h {
mid := (l + h) / 2
if get(mid) == target {
return true
}
if get(mid) > target {
h = mid - 1
} else {
l = mid + 1
}
}
return false
}
// https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
func searchMatrix2(matrix [][]int, target int) bool {
n := len(matrix)
if n == 0 {
return false
}
m := len(matrix[0])
if m == 0 {
return false
}
var find func(rowStart, rowEnd, colStart, colEnd int) bool
find = func(rs, re, cs, ce int) bool {
if rs > re || cs > ce {
return false
}
rowMid, colMid := (rs+re)/2, (cs+ce)/2
v := matrix[rowMid][colMid]
if v == target {
return true
}
if v < target {
// cs cm ce
// +---+
// rs L L L|? ?|
// L L L|? ?| -> find
// rm L L v|G G|
// +-----+---+
// |? ? G G G|
// re |? ? G G G| -> find
// +---------+
return find(rs, rowMid, colMid+1, ce) ||
find(rowMid+1, re, cs, ce)
} else {
// cs cm ce
// +---------+
// rs |L L L ? ?|
// |L L L ? ?| -> find
// +---+-----+
// rm |L L|v G G
// |? ?|G G G
// re |? ?|G G G -> find
// +---+
return find(rs, rowMid-1, cs, ce) ||
find(rowMid, re, cs, colMid-1)
}
}
return find(0, n-1, 0, m-1)
}
func searchMatrix3(matrix [][]int, target int) bool {
n := len(matrix)
if n == 0 {
return false
}
m := len(matrix[0])
if m == 0 {
return false
}
for i, j := m-1, 0; i >= 0 && j < n; {
if matrix[i][j] == target {
return true
}
if matrix[i][j] > target {
i--
} else {
j++
}
}
return false
}
func main() {
cases := []struct {
t int
m [][]int
}{
{
t: 5,
m: [][]int{
{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},
{10, 13, 14, 17, 24},
{18, 21, 23, 26, 30},
},
},
}
realCase := cases[0:]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(searchMatrix(c.m, c.t))
}
}
|
package main
import (
"bufio"
"fmt"
"log"
"net"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatal(err)
}
/*
fmt.Fprintf(conn, "GET /HTTP/1.0\r\n\n")
status, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
log.Fatal(err)
}
fmt.Println(status)*/
go conn.Write([]byte("I am cli\n"))
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
|
package erroneous
import (
"time"
"github.com/twinj/uuid"
)
// Guid is an alias for uuid.UUID. Indluded to reduce repetition of external package
type Guid uuid.UUID
// Store is an interface to abstract storage of error data.
type Store interface {
ProtectError(Guid) error
DeleteError(Guid) error
DeleteAllErrors(appName string) error
LogError(*Error) error
GetError(Guid) (*Error, error)
GetAllErrors(appName string) ([]*Error, error)
GetErrorCount(appName string, since time.Time) (int, error)
}
|
package leetcode
import "testing"
func TestHashMap(t *testing.T) {
hm := Constructor()
hm.Put(1, 1)
hm.Put(2, 2)
if hm.Get(1) != 1 {
t.Fatal()
}
if hm.Get(3) != -1 {
t.Fatal()
}
hm.Put(2, 1)
if hm.Get(2) != 1 {
t.Fatal()
}
hm.Remove(2)
if hm.Get(2) != -1 {
t.Fatal()
}
}
|
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
fmt.Println(compareVersion("1.01", "1.001"))
fmt.Println(compareVersion("1.0", "1.0.0"))
fmt.Println(compareVersion("0.1", "1.1"))
}
// leetcode submit region begin(Prohibit modification and deletion)
func compareVersion(version1 string, version2 string) int {
v1 := strings.Split(version1, ".")
v2 := strings.Split(version2, ".")
i := 0
for {
vi1, _ := strconv.Atoi(v1[i])
vi2, _ := strconv.Atoi(v2[i])
if vi1 < vi2 {
return -1
} else if vi1 > vi2 {
return 1
} else {
i++
if i == len(v1) && i == len(v2) {
return 0
}
if i == len(v1) {
v1 = append(v1, "0")
}
if i == len(v2) {
v2 = append(v2, "0")
}
}
}
return 0
}
//leetcode submit region end(Prohibit modification and deletion)
|
package main
import (
"fmt"
)
func main() {
var1 := 10
var2 := 10.5
// illegal
// var3 := var1 + var2
// legal
var3 := var1 + int(var2)
var4 := float64(var1) + var2
fmt.Println("int: ", var1, "+", var2, "=", var3)
fmt.Println("float64: ", var1, "+", var2, "=", var4)
}
|
package engine
import (
"github.com/d5/tengo/v2"
"github.com/pkg/errors"
)
/*
factorValue := factor(domain_id, "bridgeCode name")
*/
func factorGetInTengo(runtimeCtx domainStatus) func(args ...tengo.Object) (ret tengo.Object, err error) {
return func(args ...tengo.Object) (ret tengo.Object, err error) {
if len(args) != 2{
return nil, errors.New("factor() 参数数量不为 2")
}
var ok bool
var ds domainStatus
factor_code, ok := tengo.ToString(args[1])
if !ok {
return nil, errors.New("tengo fn factor() 参数 factor_code 非 string 类型")
}
if tengo.ToInterface(args[0]) == nil{
ds = runtimeCtx
}else{
path, ok := tengo.ToInterface(args[0]).([]interface{})
if !ok {
return nil, errors.New("tengo fn factor() 参数 path 非 Array 类型")
}
path2, err := utilArrTo(path)
if err != nil {
return nil, err
}
ds, err = runtimeCtx.getDomain(path2)
if err != nil {
return nil, err
}
}
f,err := ds.getFactor(factor_code)
if err != nil {
return nil, err
}
return tengo.FromInterface(f.value)
}
}
func utilArrTo(arr []interface{}) ([]string, error){
if len(arr) == 0{
return nil, nil
}
var s []string
for _, a := range arr{
if s2, ok := a.(string);ok {
s = append(s, s2)
}else{
return nil, errors.New("utilArrTo failed")
}
}
return s, nil
}
|
package discovery
import (
"strings"
"sync"
"time"
"github.com/appootb/grc"
"github.com/appootb/substratum/discovery"
)
func Init() {
if discovery.Implementor() == nil {
debug, _ := grc.New(grc.WithDebugProvider())
Register(debug)
}
}
func Register(rc *grc.RemoteConfig) {
discovery.RegisterImplementor(&GRCWrapper{
rc: rc,
})
}
type Node struct {
UniqueID int64
Address string
}
type GRCWrapper struct {
lc sync.Map
rc *grc.RemoteConfig
}
// RegisteredNode returns service unique ID and rpc address registered for the component.
func (m *GRCWrapper) RegisteredNode(component string) (int64, string) {
if addr, ok := m.lc.Load(component); ok {
node := addr.(*Node)
return node.UniqueID, node.Address
}
return 0, ""
}
// RegisterNode registers rpc address of the component node.
func (m *GRCWrapper) RegisterNode(component, rpcAddr string, rpcSvc []string, ttl time.Duration) (int64, error) {
uniqueID, err := m.rc.RegisterNode(component, rpcAddr, grc.WithNodeTTL(ttl),
grc.WithNodeMetadata(map[string]string{"services": strings.Join(rpcSvc, ",")}))
if err != nil {
return 0, err
}
m.lc.Store(component, &Node{
UniqueID: uniqueID,
Address: rpcAddr,
})
return uniqueID, nil
}
// GetNodes returns rpc service nodes.
func (m *GRCWrapper) GetNodes(svc string) map[string]int {
parts := strings.Split(svc, ".")
component := parts[0]
nodes := m.rc.GetNodes(component)
result := make(map[string]int, len(nodes))
if len(parts) > 1 {
for _, node := range nodes {
if node.Metadata == nil || len(node.Metadata) == 0 {
continue
}
services := strings.Split(node.Metadata["services"], ",")
for _, name := range services {
if svc == name {
result[node.Address] = node.Weight
}
}
}
if len(result) > 0 {
return result
}
}
// Get component by default
for _, node := range nodes {
result[node.Address] = node.Weight
}
return result
}
|
package main
// "fmt"
// User sds
type User struct {
ID int64
Name string
Avatar string
}
// GetUserInfo dsd
func GetUserInfo() *User {
return &User{ID: 13746731, Name: "EDDYCJY", Avatar: "https://avatars0.githubusercontent.com/u/13746731"}
}
// GetUserInfos dsa
func GetUserInfos(u *User) *User {
return u
}
func main() {
// _ = GetUserInfo()
_ = GetUserInfos(&User{ID: 13746731, Name: "EDDYCJY", Avatar: "https://avatars0.githubusercontent.com/u/13746731"})
// str := new(string)
// *str = "EDDYCJY"
// fmt.Println(str)
}
|
package models
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"strconv"
"time"
)
type Admin struct {
Id int64
Username string
Password string
Time time.Time
}
type Web struct {
Id int64
Url string
Icon string
Title string
Desc string
Time time.Time
Del bool
Type int8 //0 home 1 blog
}
func RegisterDB() {
cnf, err := config.NewConfig("ini", "conf/hello.conf")
if err != nil {
beego.Error(err)
}
db := cnf.String("hello::db")
ali_db := cnf.String("hello::ali_db")
db_url := db + "?charset=utf8&loc=Local"
// 本地 local 阿里 ali
hello_runenv := cnf.String("hello::hello_runenv")
beego.Debug("hello_runenv:", hello_runenv)
if hello_runenv == "ali" {
db_url = ali_db + "?charset=utf8&loc=Local"
}
beego.Debug("---db_url:", db_url)
orm.RegisterDataBase("default", "mysql", db_url)
// register model
orm.RegisterModel(new(Admin)) //官网管理员表
orm.RegisterModel(new(Web)) //产品
}
func GetOneAdmin(account string) (*Admin, error) {
o := orm.NewOrm()
var admins []Admin
_, err := o.Raw("SELECT * FROM admin WHERE username = ? ", account).QueryRows(&admins)
admin := &Admin{}
if len(admins) > 0 {
admin = &admins[0]
}
return admin, err
}
func AddWeb(title string, weburl string, desc string, icon string, wtype int8) (*Web, error) {
time := time.Now()
o := orm.NewOrm()
obj := &Web{Title: title, Url: weburl, Icon: icon, Desc: desc, Type: wtype, Time: time}
// 插入数据
_, err := o.Insert(obj)
if err != nil {
return nil, err
}
return obj, nil
}
func GetWebFid(id string) (*Web, error) {
cid, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return nil, err
}
o := orm.NewOrm()
var webs []Web
_, err = o.Raw("SELECT * FROM web WHERE id = ? ", cid).QueryRows(&webs)
web := &Web{}
if len(webs) > 0 {
web = &webs[0]
}
return web, err
}
func GetWebs() ([]Web, error) {
o := orm.NewOrm()
var objs []Web
_, err := o.Raw("SELECT * FROM web WHERE del = false ORDER BY id DESC").QueryRows(&objs)
return objs, err
}
func GetFTypeWebs(ftype int8) ([]Web, error) {
o := orm.NewOrm()
var objs []Web
_, err := o.Raw("SELECT * FROM web WHERE type = ? AND del = false ORDER BY id DESC", ftype).QueryRows(&objs)
return objs, err
}
func UpWebInfo(id, title, weburl, desc string, wtype int8) error {
cid, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return err
}
o := orm.NewOrm()
obj := &Web{Id: cid}
obj.Title = title
obj.Url = weburl
obj.Desc = desc
obj.Type = wtype
_, err = o.Update(obj, "title", "url", "desc", "type")
return err
}
func UpWebIcon(id, icon string) error {
cid, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return err
}
o := orm.NewOrm()
obj := &Web{Id: cid}
obj.Icon = icon
_, err = o.Update(obj, "icon")
return err
}
func DelWebFid(id string) error {
cid, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return err
}
o := orm.NewOrm()
obj := &Web{Id: cid}
obj.Del = true
_, err = o.Update(obj, "del")
return err
}
|
package stop
//go:generate stringer -type=EvalType eval_type.go
// EvalType represents the type of the output returned from a STOP
// evaluation.
type EvalType uint32
const (
TUnsupported EvalType = 0
TString EvalType = 1 << iota
TList
TMap
TBool
)
|
// +build !race
package consul
import (
"context"
"testing"
"time"
"github.com/square/p2/pkg/store/consul/transaction"
"github.com/square/p2/pkg/util"
)
const (
lockMessage = "Locked by lock_test.go"
)
func TestSession(t *testing.T) {
fixture := NewConsulTestFixture(t)
defer fixture.Close()
sessionRenewalCh := make(chan time.Time)
session, _, err := fixture.Store.NewSession(lockMessage, sessionRenewalCh)
if err != nil {
t.Fatalf("Unable to create session: %s", err)
}
defer session.Destroy()
key := "some_key"
_, err = session.Lock(key)
if err != nil {
t.Fatalf("Unable to acquire lock: %s", err)
}
bytes := fixture.GetKV(key)
if string(bytes) != lockMessage {
t.Errorf("Expected lock message for '%s' to be '%s', was '%s'", key, lockMessage, string(bytes))
}
select {
case sessionRenewalCh <- time.Now():
case <-time.After(1 * time.Second):
t.Fatalf("Sending to renewal channel blocked, session renewal is probably broken")
}
}
func TestLockExclusion(t *testing.T) {
fixture := NewConsulTestFixture(t)
defer fixture.Close()
session, _, err := fixture.Store.NewSession(lockMessage, make(chan time.Time))
if err != nil {
t.Fatalf("Unable to create session: %s", err)
}
defer session.Destroy()
key := "some_key"
_, err = session.Lock(key)
if err != nil {
t.Fatalf("Unable to acquire lock: %s", err)
}
// Now try to create a new session and lock the same key, which
// should fail
session2, _, err := fixture.Store.NewSession(lockMessage, make(chan time.Time))
if err != nil {
t.Fatalf("Unable to create second session: %s", err)
}
defer session2.Destroy()
_, err = session2.Lock(key)
if err == nil {
t.Fatalf("Should have failed to acquire the same lock using a second session")
}
}
func TestRenewalFailsWhen404(t *testing.T) {
fixture := NewConsulTestFixture(t)
defer fixture.Close()
session, _, err := fixture.Store.NewSession(lockMessage, make(chan time.Time))
if err != nil {
t.Fatalf("Unable to create session: %s", err)
}
err = session.Renew()
if err != nil {
t.Errorf("Renewal should have succeeded: %s", err)
}
session.Destroy()
err = session.Renew()
if err == nil {
t.Errorf("Renewing a destroyed session should have failed, but it succeeded")
}
}
func TestLockTxn(t *testing.T) {
fixture := NewConsulTestFixture(t)
defer fixture.Close()
session, renewalErrCh, err := NewSession(fixture.Client, "session-name", nil)
if err != nil {
t.Fatal(err)
}
errCh := make(chan error)
go func() {
defer close(errCh)
lockCtx, lockCtxCancel := transaction.New(context.Background())
defer lockCtxCancel()
unlocker, err := session.LockTxn(lockCtx, "some_key")
if err != nil {
errCh <- err
return
}
checkLockedCtx, checkLockedCtxCancel := transaction.New(context.Background())
defer checkLockedCtxCancel()
err = unlocker.CheckLockedTxn(checkLockedCtx)
if err != nil {
t.Fatal(err)
}
// confirm that the checkLockedCtx transaction fails to apply
// (because it checks the locks are held but we haven't
// committed the locking transaction yet)
ok, _, err := transaction.Commit(checkLockedCtx, fixture.Client.KV())
if err != nil {
errCh <- err
return
}
if ok {
errCh <- util.Errorf("checkLockedCtx transaction should have been rolled back since the locks aren't held yet")
return
}
unlockCtx, unlockCtxCancel := transaction.New(context.Background())
defer unlockCtxCancel()
err = unlocker.UnlockTxn(unlockCtx)
if err != nil {
t.Fatal(err)
}
// confirm that the unlockCtx transaction fails to apply because we don't hold the locks yet
ok, _, err = transaction.Commit(unlockCtx, fixture.Client.KV())
if err != nil {
errCh <- err
return
}
if ok {
errCh <- util.Errorf("unlockCtx transaction should have been rolled back since the locks aren't held yet")
return
}
// now grab the locks
err = transaction.MustCommit(lockCtx, fixture.Client.KV())
if err != nil {
errCh <- err
return
}
// now confirm the checkLockedCtx can be committed. we have to copy it first because you can't commit the same transaction twice
checkLockedCtx, checkLockedCtxCancel = transaction.New(checkLockedCtx)
defer checkLockedCtxCancel()
err = transaction.MustCommit(checkLockedCtx, fixture.Client.KV())
if err != nil {
errCh <- err
return
}
// now unlock, but we have to copy the transaction first because you can't commit the same one twice
unlockCtx, unlockCtxCancel = transaction.New(unlockCtx)
defer unlockCtxCancel()
err = transaction.MustCommit(unlockCtx, fixture.Client.KV())
if err != nil {
errCh <- err
return
}
// now confirm that the check locked txn fails again
checkLockedCtx, checkLockedCtxCancel = transaction.New(checkLockedCtx)
defer checkLockedCtxCancel()
ok, _, err = transaction.Commit(checkLockedCtx, fixture.Client.KV())
if err != nil {
errCh <- err
return
}
if ok {
errCh <- util.Errorf("checkLockedCtx transaction should have been rolled back since the locks were released")
return
}
}()
select {
case err := <-renewalErrCh:
t.Fatal(err)
case err, ok := <-errCh:
if ok {
t.Fatal(err)
}
}
}
|
package whatlanggo
import (
"unicode"
)
type trigram struct {
trigram string
count int
}
//convert punctuations and digits to space.
func toTrigramChar(ch rune) rune {
if isStopChar(ch) {
return ' '
}
return ch
}
func count(text string) map[string]int {
var r1, r2, r3 rune
trigrams := map[string]int{}
var txt []rune
for _, r := range text {
txt = append(txt, unicode.ToLower(toTrigramChar(r)))
}
txt = append(txt, ' ')
r1 = ' '
r2 = txt[0]
for i := 1; i < len(txt); i++ {
r3 = txt[i]
if !(r2 == ' ' && (r1 == ' ' || r3 == ' ')) {
trigram := []rune{}
trigram = append(trigram, r1)
trigram = append(trigram, r2)
trigram = append(trigram, r3)
if trigrams[string(trigram)] == 0 {
trigrams[string(trigram)] = 1
} else {
trigrams[string(trigram)]++
}
}
r1 = r2
r2 = r3
}
return trigrams
}
|
package true_git
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5"
"github.com/werf/werf/pkg/util"
)
func UpwardLookupAndVerifyWorkTree(lookupPath string) (bool, string, error) {
lookupPath = util.GetAbsoluteFilepath(lookupPath)
for {
dotGitPath := filepath.Join(lookupPath, git.GitDirName)
if _, err := os.Stat(dotGitPath); os.IsNotExist(err) {
if lookupPath != filepath.Dir(lookupPath) {
lookupPath = filepath.Dir(lookupPath)
continue
}
} else if err != nil {
return false, "", fmt.Errorf("error accessing %q: %s", dotGitPath, err)
} else if isValid, err := IsValidGitDir(dotGitPath); err != nil {
return false, "", err
} else if isValid {
return true, lookupPath, nil
}
break
}
return false, "", nil
}
func IsValidWorkTree(workTree string) (bool, error) {
return IsValidGitDir(filepath.Join(workTree, git.GitDirName))
}
func IsValidGitDir(gitDir string) (bool, error) {
gitArgs := append(getCommonGitOptions(), []string{"--git-dir", gitDir, "rev-parse"}...)
cmd := exec.Command("git", gitArgs...)
output, err := cmd.CombinedOutput()
if err != nil {
if strings.HasPrefix(string(output), "fatal: not a git repository: ") {
return false, nil
}
return false, fmt.Errorf("%v failed: %s:\n%s", strings.Join(append([]string{"git"}, gitArgs...), " "), err, output)
}
return true, nil
}
|
package api
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
stdlog "log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/dollarshaveclub/acyl/pkg/ghapp"
"github.com/dollarshaveclub/acyl/pkg/ghclient"
nitroerrors "github.com/dollarshaveclub/acyl/pkg/nitro/errors"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/dollarshaveclub/acyl/pkg/config"
"github.com/dollarshaveclub/acyl/pkg/eventlogger"
"github.com/dollarshaveclub/acyl/pkg/ghevent"
"github.com/dollarshaveclub/acyl/pkg/models"
ncontext "github.com/dollarshaveclub/acyl/pkg/nitro/context"
"github.com/dollarshaveclub/acyl/pkg/persistence"
"github.com/dollarshaveclub/acyl/pkg/spawner"
muxtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/gorilla/mux"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
// API output schema
type v0QAEnvironment struct {
Name string `json:"name"`
Created time.Time `json:"created"`
RawEvents []string `json:"-"`
Events []models.QAEnvironmentEvent `json:"events"`
Hostname string `json:"hostname"`
QAType string `json:"qa_type"`
User string `json:"user"`
Repo string `json:"repo"`
PullRequest uint `json:"pull_request"`
SourceSHA string `json:"source_sha"`
BaseSHA string `json:"base_sha"`
SourceBranch string `json:"source_branch"`
BaseBranch string `json:"base_branch"`
RawStatus string `json:"status"`
Status models.EnvironmentStatus `json:"status_int"`
RefMap models.RefMap `json:"ref_map"`
AminoServiceToPort map[string]int64 `json:"amino_service_to_port"`
AminoKubernetesNamespace string `json:"amino_kubernetes_namespace"`
AminoEnvironmentID int `json:"amino_environment_id"`
}
func v0QAEnvironmentFromQAEnvironment(qae *models.QAEnvironment) *v0QAEnvironment {
return &v0QAEnvironment{
Name: qae.Name,
Created: qae.Created,
RawEvents: qae.RawEvents,
Events: qae.Events,
Hostname: qae.Hostname,
QAType: qae.QAType,
User: qae.User,
Repo: qae.Repo,
PullRequest: qae.PullRequest,
SourceSHA: qae.SourceSHA,
BaseSHA: qae.BaseSHA,
SourceBranch: qae.SourceBranch,
BaseBranch: qae.BaseBranch,
RawStatus: qae.RawStatus,
Status: qae.Status,
RefMap: qae.RefMap,
AminoServiceToPort: qae.AminoServiceToPort,
AminoKubernetesNamespace: qae.AminoKubernetesNamespace,
AminoEnvironmentID: qae.AminoEnvironmentID,
}
}
type v0api struct {
apiBase
dl persistence.DataLayer
ge *ghevent.GitHubEventWebhook
es spawner.EnvironmentSpawner
sc config.ServerConfig
gha *ghapp.GitHubApp
rc ghclient.RepoClient
}
func newV0API(dl persistence.DataLayer, ge *ghevent.GitHubEventWebhook, es spawner.EnvironmentSpawner, rc ghclient.RepoClient, ghc config.GithubConfig, sc config.ServerConfig, logger *stdlog.Logger) (*v0api, error) {
api := &v0api{
apiBase: apiBase{
logger: logger,
},
dl: dl,
ge: ge,
es: es,
sc: sc,
rc: rc,
}
gha, err := ghapp.NewGitHubApp(ghc.PrivateKeyPEM, ghc.AppID, ghc.AppHookSecret, []string{"opened", "reopened", "closed", "synchronize"}, api.processWebhook, dl)
if err != nil {
return nil, errors.Wrap(err, "error creating GitHub app")
}
api.gha = gha
return api, nil
}
func (api *v0api) register(r *muxtrace.Router) error {
if r == nil {
return fmt.Errorf("router is nil")
}
// non-versioned routes
r.HandleFunc("/spawn", middlewareChain(api.legacyGithubWebhookHandler, waitMiddleware.waitOnRequest)).Methods("POST")
r.HandleFunc("/webhook", middlewareChain(api.legacyGithubWebhookHandler, waitMiddleware.waitOnRequest)).Methods("POST")
r.HandleFunc("/envs/_search", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorize(api.envSearchHandler), models.ReadOnlyPermission))).Methods("GET")
r.HandleFunc("/envs/{name}", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorizeEnv(api.envDetailHandler), models.ReadOnlyPermission))).Methods("GET")
r.HandleFunc("/envs/{name}", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorizeEnv(api.envDestroyHandler), models.AdminPermission), waitMiddleware.waitOnRequest)).Methods("DELETE")
ghahandler := api.gha.Handler()
r.HandleFunc("/ghapp/webhook", middlewareChain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// allow request logging by bundling a zerolog logger into the request context
logger := zerolog.New(os.Stdout)
r = r.Clone(logger.WithContext(r.Context()))
ghahandler.ServeHTTP(w, r)
}), waitMiddleware.waitOnRequest)).Methods("POST")
// DEPRECATED: no longer supported, please use /envs/_search
r.HandleFunc("/envs", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorize(api.envListHandler), models.ReadOnlyPermission))).Methods("GET")
r.HandleFunc("/envs/", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorize(api.envListHandler), models.ReadOnlyPermission))).Methods("GET")
// v0 routes
r.HandleFunc("/v0/spawn", middlewareChain(api.legacyGithubWebhookHandler, waitMiddleware.waitOnRequest)).Methods("POST")
r.HandleFunc("/v0/webhook", middlewareChain(api.legacyGithubWebhookHandler, waitMiddleware.waitOnRequest)).Methods("POST")
r.HandleFunc("/v0/envs/_search", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorize(api.envSearchHandler), models.ReadOnlyPermission))).Methods("GET")
r.HandleFunc("/v0/envs/{name}", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorizeEnv(api.envDetailHandler), models.ReadOnlyPermission))).Methods("GET")
r.HandleFunc("/v0/envs/{name}", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorizeEnv(api.envDestroyHandler), models.AdminPermission), waitMiddleware.waitOnRequest)).Methods("DELETE")
// DEPRECATED: no longer supported, please use /v0/envs/_search
r.HandleFunc("/v0/envs", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorize(api.envListHandler), models.ReadOnlyPermission))).Methods("GET")
r.HandleFunc("/v0/envs/", middlewareChain(authMiddleware.tokenAuth(authMiddleware.authorize(api.envListHandler), models.ReadOnlyPermission))).Methods("GET")
return nil
}
// MaxAsyncActionTimeout is the maximum amount of time an asynchronous action can take before it's forcibly cancelled
// This is mainly a failsafe against leaking goroutines, additional more strict timeout logic is implemented by environment operations code.
// If this timeout occurs, no notifications will be sent to the user.
var MaxAsyncActionTimeout = 32 * time.Minute
func setTagsForGithubWebhookHandler(span tracer.Span, rd models.RepoRevisionData) {
span.SetTag("base_branch", rd.BaseBranch)
span.SetTag("base_sha", rd.BaseSHA)
span.SetTag("pull_request", rd.PullRequest)
span.SetTag("repo", rd.Repo)
span.SetTag("source_branch", rd.SourceBranch)
span.SetTag("source_ref", rd.SourceRef)
span.SetTag("source_sha", rd.SourceSHA)
span.SetTag("user", rd.User)
}
func (api *v0api) processWebhook(ctx context.Context, action string, rrd models.RepoRevisionData) error {
// As of 03/13/2019, Datadog seems to only allow monitors to be setup based
// off the root level span of a trace.
// While we could connect this with span found in r.Context(), this would
// prevent us from making usable monitors in Datadog, since we respond with
// 200 ok even though the async action may fail.
span := tracer.StartSpan("webhook_processor")
// We need to set this sampling priority tag in order to allow distributed tracing to work.
// This only needs to be done for the root level span as the value is propagated down.
// https://docs.datadoghq.com/tracing/getting_further/trace_sampling_and_storage/#priority-sampling-for-distributed-tracing
span.SetTag(ext.SamplingPriority, ext.PriorityUserKeep)
// new context for async actions since ctx will cancel when the webhook request connection is closed
ctx2 := context.Background()
// embed the eventlogger & github client from original context
ctx2 = ghapp.CloneGitHubClientContext(ctx2, ctx)
ctx2 = eventlogger.NewEventLoggerContext(ctx2, eventlogger.GetLogger(ctx))
// embed the cancel func for later cancellation and overwrite the initial context bc we don't need it any longer
ctx = ncontext.NewCancelFuncContext(context.WithCancel(ctx2))
// enforce an unknown status stub before proceeding with action
eventlogger.GetLogger(ctx).SetNewStatus(models.UnknownEventStatusType, "<undefined>", rrd)
log := eventlogger.GetLogger(ctx).Printf
// Events may be received for repos that have the github app installed but do not themselves contain an acyl.yml
// (eg, repos that are dependencies of other repos that do contain acyl.yml)
// therefore if acyl.yml is not found, ignore the event and return nil error so we don't set an error commit status on that repo
log("checking for triggering repo acyl.yml in %v@%v", rrd.Repo, rrd.SourceSHA)
if _, err := api.rc.GetFileContents(ctx, rrd.Repo, "acyl.yml", rrd.SourceSHA); err != nil {
if strings.Contains(err.Error(), "404 Not Found") { // this is also returned if permissions are incorrect
log("acyl.yml is missing for repo, ignoring event")
return nil
}
log("error checking existence of acyl.yml: %v", err)
return errors.Wrap(err, "error checking existence of acyl.yml")
}
log("acyl.yml found, continuing to process event")
setTagsForGithubWebhookHandler(span, rrd)
ctx = tracer.ContextWithSpan(ctx, span)
var err error
finishWithError := func() {
if nitroerrors.IsCancelledError(err) {
err = nil
}
span.Finish(tracer.WithError(err))
}
switch action {
case "reopened":
fallthrough
case "opened":
log("starting async processing for %v", action)
api.wg.Add(1)
go func() {
defer finishWithError()
defer api.wg.Done()
ctx, cf := context.WithTimeout(ctx, MaxAsyncActionTimeout)
defer cf() // guarantee that any goroutines created with the ctx are cancelled
name, err := api.es.Create(ctx, rrd)
if err != nil {
log("finished processing create with error: %v", err)
return
}
log("success processing create event (env: %q); done", name)
}()
case "synchronize":
log("starting async processing for %v", action)
api.wg.Add(1)
go func() {
defer finishWithError()
defer api.wg.Done()
ctx, cf := context.WithTimeout(ctx, MaxAsyncActionTimeout)
defer cf() // guarantee that any goroutines created with the ctx are cancelled
name, err := api.es.Update(ctx, rrd)
if err != nil {
log("finished processing update with error: %v", err)
return
}
log("success processing update event (env: %q); done", name)
}()
case "closed":
log("starting async processing for %v", action)
api.wg.Add(1)
go func() {
defer finishWithError()
defer api.wg.Done()
ctx, cf := context.WithTimeout(ctx, MaxAsyncActionTimeout)
defer cf() // guarantee that any goroutines created with the ctx are cancelled
err = api.es.Destroy(ctx, rrd, models.DestroyApiRequest)
if err != nil {
log("finished processing destroy with error: %v", err)
return
}
log("success processing destroy event; done")
}()
default:
log("unknown action type: %v", action)
err = fmt.Errorf("unknown action type: %v (event_log_id: %v)", action, eventlogger.GetLogger(ctx).ID.String())
finishWithError()
return err
}
return nil
}
// legacyGithubWebhookHandler serves the legacy (manually set up) GitHook webhook endpoint
func (api *v0api) legacyGithubWebhookHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
span := tracer.StartSpan("legacy_github_webhook_handler")
var err error
defer func() {
span.Finish(tracer.WithError(err))
if err != nil {
api.logger.Printf("webhook handler error: %v", err)
}
}()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
api.badRequestError(w, err)
return
}
sig := r.Header.Get("X-Hub-Signature")
if sig == "" {
err = errors.New("X-Hub-Signature-Missing")
api.forbiddenError(w, err.Error())
return
}
did, err := uuid.Parse(r.Header.Get("X-GitHub-Delivery"))
if err != nil {
// Ignore invalid or missing Delivery ID
did = uuid.Nil
}
out, err := api.ge.New(b, did, sig)
if err != nil {
_, bsok := err.(ghevent.BadSignature)
if bsok {
api.forbiddenError(w, "invalid hub signature")
} else {
api.badRequestError(w, err)
}
return
}
log := out.Logger.Printf
ctx := eventlogger.NewEventLoggerContext(context.Background(), out.Logger)
accepted := func() {
w.WriteHeader(http.StatusAccepted)
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"event_log_id": "%v"}`, out.Logger.ID.String())))
}
if out.Action == ghevent.NotRelevant {
log("event not relevant: %v", out.Action)
accepted()
return
}
if out.RRD == nil {
log("repo data is nil")
api.internalError(w, fmt.Errorf("RepoData is nil (event_log_id: %v)", out.Logger.ID.String()))
return
}
if out.RRD.SourceBranch == "" && out.Action != ghevent.NotRelevant {
api.internalError(w, fmt.Errorf("RepoData.SourceBranch has no value (event_log_id: %v)", out.Logger.ID.String()))
return
}
var action string
switch out.Action {
case ghevent.CreateNew:
action = "opened"
case ghevent.Update:
action = "synchronize"
case ghevent.Destroy:
action = "closed"
default:
action = "unknown"
}
err = api.processWebhook(ctx, action, *out.RRD)
if err != nil {
api.internalError(w, err)
return
}
accepted()
}
// DEPRECATED: no longer supported, please use /env/_search, or /v0/env/_search
func (api *v0api) envListHandler(w http.ResponseWriter, r *http.Request) {
apikey, ok := r.Context().Value(apiKeyCtxKey).(models.APIKey)
if !ok {
api.internalError(w, fmt.Errorf("unexpected api key type from context: %T", apikey))
return
}
envs := []models.QAEnvironment{}
var err error
if apikey.PermissionLevel == models.AdminPermission {
envs, err = api.dl.GetQAEnvironments(r.Context())
} else {
envs, err = api.dl.GetQAEnvironmentsByUser(r.Context(), apikey.GitHubUser)
}
if err != nil {
api.internalError(w, fmt.Errorf("error getting environments: %v", err))
return
}
var fullDetails bool
if val, ok := r.URL.Query()["full_details"]; ok {
for _, v := range val {
if v == "true" {
fullDetails = true
}
}
}
var j []byte
if fullDetails {
output := []v0QAEnvironment{}
for _, e := range envs {
output = append(output, *v0QAEnvironmentFromQAEnvironment(&e))
}
j, err = json.Marshal(output)
if err != nil {
api.internalError(w, fmt.Errorf("error marshaling environments: %v", err))
return
}
} else {
nl := []string{}
for _, e := range envs {
nl = append(nl, e.Name)
}
j, err = json.Marshal(nl)
if err != nil {
api.internalError(w, fmt.Errorf("error marshaling environments: %v", err))
return
}
}
w.Header().Add("Content-Type", "application/json")
w.Write(j)
}
func (api *v0api) envDetailHandler(w http.ResponseWriter, r *http.Request) {
qa, ok := r.Context().Value(qaEnvCtxKey).(models.QAEnvironment)
if !ok {
api.internalError(w, fmt.Errorf("unexpected qa env type from context: %T", qa))
return
}
output := v0QAEnvironmentFromQAEnvironment(&qa)
j, err := json.Marshal(output)
if err != nil {
api.internalError(w, fmt.Errorf("error marshaling environment: %v", err))
return
}
w.Header().Add("Content-Type", "application/json")
w.Write(j)
}
func (api *v0api) envDestroyHandler(w http.ResponseWriter, r *http.Request) {
qa, ok := r.Context().Value(qaEnvCtxKey).(models.QAEnvironment)
if !ok {
api.internalError(w, fmt.Errorf("unexpected qa env type from context: %T", qa))
return
}
go func() {
err := api.es.DestroyExplicitly(context.Background(), &qa, models.DestroyApiRequest)
if err != nil {
api.logger.Printf("error destroying QA: %v: %v", qa.Name, err)
}
}()
w.WriteHeader(http.StatusNoContent)
}
func (api *v0api) envSearchHandler(w http.ResponseWriter, r *http.Request) {
apikey, ok := r.Context().Value(apiKeyCtxKey).(models.APIKey)
if !ok {
api.internalError(w, fmt.Errorf("unexpected api key type from context: %T", apikey))
return
}
qvars := r.URL.Query()
if _, ok := qvars["pr"]; ok {
if _, ok := qvars["repo"]; !ok {
api.badRequestError(w, fmt.Errorf("search by PR requires repo name"))
return
}
}
if status, ok := qvars["status"]; ok {
if status[0] == "destroyed" && len(qvars) == 1 {
api.badRequestError(w, fmt.Errorf("'destroyed' status searches require at least one other search parameter"))
return
}
}
if len(qvars) == 0 {
api.badRequestError(w, fmt.Errorf("at least one search parameter is required"))
return
}
ops := models.EnvSearchParameters{}
for k, vs := range qvars {
if len(vs) != 1 {
api.badRequestError(w, fmt.Errorf("unexpected value for %v: %v", k, vs))
return
}
v := vs[0]
switch k {
case "repo":
ops.Repo = v
case "pr":
pr, err := strconv.Atoi(v)
if err != nil || pr < 1 {
api.badRequestError(w, fmt.Errorf("bad PR number"))
return
}
ops.Pr = uint(pr)
case "source_sha":
ops.SourceSHA = v
case "source_branch":
ops.SourceBranch = v
case "user":
ops.User = v
case "status":
s, err := models.EnvironmentStatusFromString(v)
if err != nil {
api.badRequestError(w, fmt.Errorf("unknown status"))
return
}
ops.Status = s
}
}
qas := []models.QAEnvironment{}
var err error
if apikey.PermissionLevel == models.AdminPermission {
qas, err = api.dl.Search(r.Context(), ops)
} else {
qas, err = api.dl.SearchEnvsForUser(r.Context(), apikey.GitHubUser, ops)
}
if err != nil {
api.internalError(w, fmt.Errorf("error searching in DB: %v", err))
return
}
w.Header().Add("Content-Type", "application/json")
if len(qas) == 0 {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[]`))
return
}
output := []v0QAEnvironment{}
for _, e := range qas {
output = append(output, *v0QAEnvironmentFromQAEnvironment(&e))
}
j, err := json.Marshal(output)
if err != nil {
api.internalError(w, fmt.Errorf("error marshaling environments: %v", err))
return
}
w.Write(j)
}
|
package api
import (
"context"
"github.com/gremlinsapps/avocado_server/api/model"
"github.com/gremlinsapps/avocado_server/dal/model"
"github.com/gremlinsapps/avocado_server/dal/sql"
)
func (r *queryResolver) Ingredients(ctx context.Context, filter *apimodel.ResultsFilter) ([]apimodel.Ingredient, error) {
repo, err := sql.CreateIngredientRepo(r)
if err != nil {
return []apimodel.Ingredient{}, err
}
ingredients, err := repo.GetIngredients(filter)
if err != nil {
return []apimodel.Ingredient{}, err
}
return convertIngredients(ingredients), nil
}
func (r *mutationResolver) CreateIngredient(ctx context.Context, input apimodel.NewIngredient) (*apimodel.Ingredient, error) {
repo, err := sql.CreateIngredientRepo(r)
if err != nil {
return nil, err
}
ingredient := dalmodel.Ingredient{
Name: input.Name,
}
err = repo.CreateIngredient(ctx, &ingredient)
if err != nil {
return nil, err
}
return convertIngredient(&ingredient), nil
}
func (r *mutationResolver) UpdateIngredient(ctx context.Context, input apimodel.UpdateIngredient) (*apimodel.Result, error) {
repo, err := sql.CreateIngredientRepo(r)
if err != nil {
return apimodel.CreateFailureResult(err)
}
uid := input.ID
data := make(map[string]interface{})
if input.Name != nil {
data["Name"] = *input.Name
}
if input.Calories != nil {
data["Calories"] = *input.Calories
}
// TODO: fill
if len(data) > 0 {
err = repo.UpdateUser(ctx, uid, data)
if err != nil {
return nil, err
}
}
if input.Hashtags != nil {
hashtagRepo, err := sql.CreateHashtagRepo(r)
if err != nil {
return nil, err
}
err = hashtagRepo.UpdateUserHashtags(uid, input.Hashtags)
if err != nil {
return nil, err
}
}
return apimodel.CreateSuccessResult()
}
func (r *mutationResolver) DeleteIngredient(ctx context.Context, id int) (*apimodel.Result, error) {
return apimodel.CreateSuccessResult()
}
func convertIngredients(ingredients []dalmodel.Ingredient) []apimodel.Ingredient {
var results []apimodel.Ingredient
for _, ingredient := range ingredients {
results = append(results, *convertIngredient(&ingredient))
}
return results
}
func convertIngredient(ingredient *dalmodel.Ingredient) *apimodel.Ingredient {
return &apimodel.Ingredient{
ID: int(ingredient.ID),
}
}
|
/*
* @lc app=leetcode.cn id=1929 lang=golang
*
* [1929] 数组串联
*/
package main
// @lc code=start
func getConcatenation(nums []int) []int {
ret := make([]int, len(nums)*2)
for i := 0; i < len(nums); i++ {
ret[i] = nums[i]
ret[i+len(nums)] = ret[i]
}
return ret
}
// @lc code=end
|
// +build dcap
package main
/*
#cgo CFLAGS: -DRATLS_ECDSA=1
#cgo LDFLAGS: -L../build/lib -Llib -lra-tls-server -l:libcurl-wolfssl.a -l:libwolfssl.a -lsgx_uae_service -lsgx_urts -lz -lm
#cgo LDFLAGS: -lsgx_dcap_ql
extern int ra_tls_server_startup(int sockfd);
*/
import "C"
func ratlsServerStartup(fd uintptr) {
C.ra_tls_server_startup(C.int(fd))
}
|
package main
import (
"fmt"
"time"
)
func sendChan(ch chan<- int) {
count := 0
for count < 10 {
ch <- count
count++
}
}
func receiveChan(ch <-chan int) {
for {
fmt.Println(<-ch)
}
}
func main() {
ch := make(chan int, 1)
go sendChan(ch)
go receiveChan(ch)
time.Sleep(1e9)
}
|
package serializer
func EncodeWithZlib(v interface{}) ([]byte, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
return Compress(data)
}
func DecodeWithZlib(data []byte, v interface{}) error {
decodedData, err := Decompress(data)
if err != nil {
return err
}
return json.Unmarshal(decodedData, v)
}
|
package testrunner
import (
tmv1beta1 "github.com/gardener/test-infra/pkg/apis/testmachinery/v1beta1"
)
const (
AnnotationLandscape = "testrunner.testmachinery.sapcloud.io/landscape"
AnnotationK8sVersion = "testrunner.testmachinery.sapcloud.io/k8sVersion"
AnnotationCloudProvider = "testrunner.testmachinery.sapcloud.io/cloudprovider"
)
func (m *Metadata) CreateAnnotations() map[string]string {
return map[string]string{
AnnotationLandscape: m.Landscape,
AnnotationK8sVersion: m.KubernetesVersion,
AnnotationCloudProvider: m.CloudProvider,
}
}
func MetadataFromTestrun(tr *tmv1beta1.Testrun) *Metadata {
return &Metadata{
Landscape: tr.Annotations[AnnotationLandscape],
KubernetesVersion: tr.Annotations[AnnotationK8sVersion],
CloudProvider: tr.Annotations[AnnotationCloudProvider],
Testrun: TestrunMetadata{
ID: tr.Name,
},
}
}
|
package main
import (
"image"
"math"
)
type scene struct {
objects []object
lights []light
fov float64
camera ray
}
func (s *scene) calculateCameraToWorld() {
}
// intersec returns object, point of intersection and its normale if ray intersects something
// if there is no intersection, then obj == nil
func (s *scene) intersec(origin, dir vector) (intersection, normale vector, obj object) {
minDist := math.MaxFloat64
for i := range s.objects {
if dist, intersects := s.objects[i].rayIntersect(origin, dir); intersects && dist < minDist {
minDist = dist
obj = s.objects[i]
}
}
if obj != nil {
intersection = origin.Add(dir.Multiply(minDist))
normale = obj.getNormale(intersection)
}
return intersection, normale, obj
}
// isShadowed returns true if light l is visible in direction dir from intersection
func (s *scene) isShadowed(l light, dir, intersection, normale vector) bool {
lightDist := l.position.Sub(intersection).Length()
// rise intersection point above the surface a bit
// to make sure we won't intersect with itself
shadowOrig := intersection.Offset(dir, normale, 1e-3)
if shadowPoint, _, o := s.intersec(shadowOrig, dir); o != nil {
return shadowPoint.Sub(shadowOrig).Length() < lightDist
}
return false
}
// castRay casts ray from origin to dir and returns resulting color
func (s *scene) castRay(origin, dir vector, ttl int) vector {
if ttl <= 0 {
return backgroundColor
}
intersection, normale, obj := s.intersec(origin, dir)
if obj == nil {
return backgroundColor
}
m := obj.getMaterial()
reflectDir := dir.Reflect(normale)
reflectOrig := intersection.Offset(reflectDir, normale, 1e-3)
reflectColor := s.castRay(reflectOrig, reflectDir, ttl-1)
reflectIntensity := m.specularRef.EntrywiseProduct(reflectColor)
var refractDir, refractOrig, refractColor, refractIntensity vector
refractDir = dir.Refract(normale, m.refractiveIndex).Normalize()
if !refractDir.IsZero() {
refractOrig = intersection.Offset(refractDir, normale, 1e-3)
refractColor = s.castRay(refractOrig, refractDir, ttl-1)
refractIntensity = m.transparency.EntrywiseProduct(refractColor)
}
var diffuseIntensity, specularIntensity vector
var diffuseFactor, specularFactor float64
for i := range s.lights {
lightDir := s.lights[i].position.Sub(intersection).Normalize()
if s.isShadowed(s.lights[i], lightDir, intersection, normale) {
continue
}
diffuseFactor = s.lights[i].intensity * math.Max(0.0, lightDir.DotProduct(normale))
specularFactor = s.lights[i].intensity * math.Pow(
math.Max(0.0, lightDir.Reflect(normale).DotProduct(dir)),
m.specularExp,
)
// calculate lighting from i-th light for each component and color channel
diffuseIntensity = diffuseIntensity.Add(m.diffuseRef.Multiply(diffuseFactor))
specularIntensity = specularIntensity.Add(m.diffuseRef.Multiply(specularFactor))
}
return specularIntensity.Add(diffuseIntensity).Add(reflectIntensity).Add(refractIntensity)
}
func (s *scene) render(img *image.NRGBA64) {
ft := math.Tan(s.fov / 2.0)
w := float64(RESX)
h := float64(RESY)
bounds := img.Bounds()
for y := float64(bounds.Min.Y); y < float64(bounds.Max.Y); y++ {
for x := float64(bounds.Min.X); x < float64(bounds.Max.X); x++ {
dx := (2*(x+0.5)/w - 1.0) * ft * w/h
dy := -(2*(y+0.5)/h - 1.0) * ft
camDir := vector{dx, dy, -1}.Normalize()
worldDir := camDir.TransformDir(s.camera.transformMatrix).Normalize()
img.Set(int(x), int(y), s.castRay(s.camera.origin, worldDir, _ttl).toNRGBA64())
}
}
}
|
// Hot Data Status
package consts
|
package storage
import (
"fmt"
"strconv"
"sync"
"github.com/mauleyzaola/challenge/domain"
)
type Memory struct {
sync.Mutex
nextId int64
items map[string]interface{}
}
func (this *Memory) Init() {
this.nextId = 0
this.items = make(map[string]interface{})
}
func (this *Memory) List() []string {
this.Lock()
defer this.Unlock()
var results []string
for k := range this.items {
results = append(results, k)
}
return results
}
func (this *Memory) Load(id string) (*domain.Basket, error) {
this.Lock()
defer this.Unlock()
val, ok := this.items[id]
if !ok {
return nil, fmt.Errorf("no matching id found:%s", id)
}
basket, ok := val.(*domain.Basket)
if !ok {
return nil, fmt.Errorf("cannot cast to basket:%#v", basket)
}
return basket, nil
}
func (this *Memory) Create() (*domain.Basket, error) {
this.Lock()
defer this.Unlock()
// mocked id just for tests
this.nextId++
id := strconv.FormatInt(this.nextId, 10)
basket := &domain.Basket{
Id: id,
Items: []domain.BasketItem{},
}
this.items[id] = basket
return basket, nil
}
func (this *Memory) Save(basket *domain.Basket) error {
this.Lock()
defer this.Unlock()
_, ok := this.items[basket.Id]
if !ok {
return fmt.Errorf("basket with id:%s does not exist", basket.Id)
}
this.items[basket.Id] = basket
return nil
}
func (this *Memory) Remove(id string) error {
this.Lock()
defer this.Unlock()
_, ok := this.items[id]
if !ok {
return fmt.Errorf("basket with id:%s does not exist", id)
}
delete(this.items, id)
return nil
}
|
package main
import "fmt"
func main() {
// n = 0
TestRoutine(0)
// สร้างการทำงานซ้อน ฟังก์ชัน TestRoutine(n int)
// สร้างตัวแปร input เก็บค่า string
var input string
fmt.Scanln(&input)
}
// Routine คือ ฟังก์ชันที่สามารถเรียกใช้งาน ฟังก์ชันอื่นได้ในขณะที่มีการทำงานอยู่
func TestRoutine(n int) {
// n คือ พารามิเตอร์
// i = 1 แต่ไม่เกิน 10
for i := 1; i <= 10; i++ {
fmt.Println("index", ":", i)
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package helpers
import (
"encoding/json"
"strings"
"testing"
)
func TestKubernetesAllowedSizes(t *testing.T) {
sizes := GetKubernetesAllowedVMSKUs()
if len(sizes) == 0 {
t.Errorf("expected GetKubernetesAllowedVMSKUs to return a non empty string")
}
expectedSizes := []string{
"Standard_A0",
"Standard_A1",
"Standard_A10",
"Standard_A11",
"Standard_A1_v2",
"Standard_A2",
"Standard_A2_v2",
"Standard_A2m_v2",
"Standard_A3",
"Standard_A4",
"Standard_A4_v2",
"Standard_A4m_v2",
"Standard_A5",
"Standard_A6",
"Standard_A7",
"Standard_A8",
"Standard_A8_v2",
"Standard_A8m_v2",
"Standard_A9",
"Standard_B1ls",
"Standard_B1ms",
"Standard_B1s",
"Standard_B2ms",
"Standard_B2s",
"Standard_B4ms",
"Standard_B8ms",
"Standard_D1",
"Standard_D11",
"Standard_D11_v2",
"Standard_D11_v2_Promo",
"Standard_D12",
"Standard_D12_v2",
"Standard_D12_v2_Promo",
"Standard_D13",
"Standard_D13_v2",
"Standard_D13_v2_Promo",
"Standard_D14",
"Standard_D14_v2",
"Standard_D14_v2_Promo",
"Standard_D15_v2",
"Standard_D16_v3",
"Standard_D16s_v3",
"Standard_D1_v2",
"Standard_D2",
"Standard_D2_v2",
"Standard_D2_v2_Promo",
"Standard_D2_v3",
"Standard_D2s_v3",
"Standard_D3",
"Standard_D32_v3",
"Standard_D32s_v3",
"Standard_D3_v2",
"Standard_D3_v2_Promo",
"Standard_D4",
"Standard_D4_v2",
"Standard_D4_v2_Promo",
"Standard_D4_v3",
"Standard_D4s_v3",
"Standard_D5_v2",
"Standard_D5_v2_Promo",
"Standard_D64_v3",
"Standard_D64s_v3",
"Standard_D8_v3",
"Standard_D8s_v3",
"Standard_DC2s",
"Standard_DC4s",
"Standard_DS1",
"Standard_DS11",
"Standard_DS11-1_v2",
"Standard_DS11_v2",
"Standard_DS11_v2_Promo",
"Standard_DS12",
"Standard_DS12-1_v2",
"Standard_DS12-2_v2",
"Standard_DS12_v2",
"Standard_DS12_v2_Promo",
"Standard_DS13",
"Standard_DS13-2_v2",
"Standard_DS13-4_v2",
"Standard_DS13_v2",
"Standard_DS13_v2_Promo",
"Standard_DS14",
"Standard_DS14-4_v2",
"Standard_DS14-8_v2",
"Standard_DS14_v2",
"Standard_DS14_v2_Promo",
"Standard_DS15_v2",
"Standard_DS1_v2",
"Standard_DS2",
"Standard_DS2_v2",
"Standard_DS2_v2_Promo",
"Standard_DS3",
"Standard_DS3_v2",
"Standard_DS3_v2_Promo",
"Standard_DS4",
"Standard_DS4_v2",
"Standard_DS4_v2_Promo",
"Standard_DS5_v2",
"Standard_DS5_v2_Promo",
"Standard_E16-4s_v3",
"Standard_E16-8s_v3",
"Standard_E16_v3",
"Standard_E16s_v3",
"Standard_E20_v3",
"Standard_E20s_v3",
"Standard_E2_v3",
"Standard_E2s_v3",
"Standard_E32-16s_v3",
"Standard_E32-8s_v3",
"Standard_E32_v3",
"Standard_E32s_v3",
"Standard_E4-2s_v3",
"Standard_E4_v3",
"Standard_E4s_v3",
"Standard_E64-16s_v3",
"Standard_E64-32s_v3",
"Standard_E64_v3",
"Standard_E64i_v3",
"Standard_E64is_v3",
"Standard_E64s_v3",
"Standard_E8-2s_v3",
"Standard_E8-4s_v3",
"Standard_E8_v3",
"Standard_E8s_v3",
"Standard_F1",
"Standard_F16",
"Standard_F16s",
"Standard_F16s_v2",
"Standard_F1s",
"Standard_F2",
"Standard_F2s",
"Standard_F2s_v2",
"Standard_F32s_v2",
"Standard_F4",
"Standard_F4s",
"Standard_F4s_v2",
"Standard_F64s_v2",
"Standard_F72s_v2",
"Standard_F8",
"Standard_F8s",
"Standard_F8s_v2",
"Standard_G1",
"Standard_G2",
"Standard_G3",
"Standard_G4",
"Standard_G5",
"Standard_GS1",
"Standard_GS2",
"Standard_GS3",
"Standard_GS4",
"Standard_GS4-4",
"Standard_GS4-8",
"Standard_GS5",
"Standard_GS5-16",
"Standard_GS5-8",
"Standard_H16",
"Standard_H16m",
"Standard_H16mr",
"Standard_H16r",
"Standard_H8",
"Standard_H8m",
"Standard_HB60rs",
"Standard_HC44rs",
"Standard_L16s",
"Standard_L16s_v2",
"Standard_L32s",
"Standard_L32s_v2",
"Standard_L4s",
"Standard_L64s_v2",
"Standard_L80s_v2",
"Standard_L8s",
"Standard_L8s_v2",
"Standard_M128",
"Standard_M128-32ms",
"Standard_M128-64ms",
"Standard_M128m",
"Standard_M128ms",
"Standard_M128s",
"Standard_M16-4ms",
"Standard_M16-8ms",
"Standard_M16ms",
"Standard_M32-16ms",
"Standard_M32-8ms",
"Standard_M32ls",
"Standard_M32ms",
"Standard_M32ts",
"Standard_M64",
"Standard_M64-16ms",
"Standard_M64-32ms",
"Standard_M64ls",
"Standard_M64m",
"Standard_M64ms",
"Standard_M64s",
"Standard_M8-2ms",
"Standard_M8-4ms",
"Standard_M8ms",
"Standard_NC12",
"Standard_NC12s_v2",
"Standard_NC12s_v3",
"Standard_NC24",
"Standard_NC24r",
"Standard_NC24rs_v2",
"Standard_NC24rs_v3",
"Standard_NC24s_v2",
"Standard_NC24s_v3",
"Standard_NC6",
"Standard_NC6s_v2",
"Standard_NC6s_v3",
"Standard_ND12s",
"Standard_ND24rs",
"Standard_ND24s",
"Standard_ND6s",
"Standard_NV12",
"Standard_NV12s_v2",
"Standard_NV24",
"Standard_NV24s_v2",
"Standard_NV6",
"Standard_NV6s_v2",
"Standard_PB12s",
"Standard_PB24s",
"Standard_PB6s",
}
for _, expectedSize := range expectedSizes {
if !strings.Contains(sizes, expectedSize) {
t.Errorf("expected %s to be present in the list of allowedValues", expectedSize)
}
}
}
func TestGetSizeMap(t *testing.T) {
expectedSizeMap := map[string]interface{}{
"Standard_A0": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A1": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A10": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A11": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A1_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A2_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A2m_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A4": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A4_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A4m_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A5": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A6": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A7": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A8": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A8_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A8m_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_A9": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_B1ls": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_B1ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_B1s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_B2ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_B2s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_B4ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_B8ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_D1": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D11": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D11_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D11_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D12": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D12_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D12_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D13": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D13_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D13_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D14": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D14_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D14_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D15_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D16_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D16s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_D1_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D2_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D2_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D2_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D2s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_D3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D32_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D32s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_D3_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D3_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D4": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D4_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D4_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D4_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D4s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_D5_v2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D5_v2_Promo": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D64_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D64s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_D8_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_D8s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DC2s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DC4s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS1": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS11": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS11-1_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS11_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS11_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS12": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS12-1_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS12-2_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS12_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS12_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS13": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS13-2_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS13-4_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS13_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS13_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS14": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS14-4_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS14-8_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS14_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS14_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS15_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS1_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS2_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS2_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS3_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS3_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS4": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS4_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS4_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS5_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_DS5_v2_Promo": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E16-4s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E16-8s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E16_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E16s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E20_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E20s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E2_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E2s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E32-16s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E32-8s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E32_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E32s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E4-2s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E4_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E4s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E64-16s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E64-32s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E64_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E64i_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E64is_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E64s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E8-2s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E8-4s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_E8_v3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_E8s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F1": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_F16": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_F16s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F16s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F1s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_F2s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F2s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F32s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F4": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_F4s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F4s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F64s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F72s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F8": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_F8s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_F8s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_G1": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_G2": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_G3": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_G4": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_G5": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_GS1": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS4": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS4-4": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS4-8": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS5": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS5-16": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_GS5-8": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_H16": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_H16m": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_H16mr": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_H16r": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_H8": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_H8m": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_HB60rs": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_HC44rs": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_L16s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L16s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L32s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L32s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L4s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L64s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L80s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L8s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_L8s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M128": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_M128-32ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M128-64ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M128m": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_M128ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M128s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M16-4ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M16-8ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M16ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M32-16ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M32-8ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M32ls": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M32ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M32ts": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M64": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_M64-16ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M64-32ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M64ls": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M64m": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_M64ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M64s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M8-2ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M8-4ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_M8ms": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC12": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NC12s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC12s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC24": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NC24r": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NC24rs_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC24rs_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC24s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC24s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC6": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NC6s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NC6s_v3": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_ND12s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_ND24rs": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_ND24s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_ND6s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NV12": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NV12s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NV24": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NV24s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_NV6": map[string]string{
"storageAccountType": "Standard_LRS",
},
"Standard_NV6s_v2": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_PB12s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_PB24s": map[string]string{
"storageAccountType": "Premium_LRS",
},
"Standard_PB6s": map[string]string{
"storageAccountType": "Premium_LRS",
},
}
actualSizeStr := "{" + GetSizeMap() + "}"
var actualVMSizesJSON map[string]interface{}
err := json.Unmarshal([]byte(actualSizeStr), &actualVMSizesJSON)
if err != nil {
t.Errorf("unexpected error while trying to unmarshal the SizeMap JSON : %s", err.Error())
}
vmSizesMap := actualVMSizesJSON["vmSizesMap"].(map[string]interface{})
for expectedSize := range expectedSizeMap {
if _, ok := vmSizesMap[expectedSize]; !ok {
t.Errorf("unexpected VM size %s found in map", expectedSize)
}
}
}
|
package main
import "fmt"
func main() {
sum, n := 0, 0
for {
var idade int
fmt.Scanf("%d", &idade)
if idade < 0 {
break
}
sum += idade
n++
}
fmt.Printf("%.2f\n", float32(sum)/float32(n))
}
|
// Copyright 2018 Simon Pasquier
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"io"
"log"
"math"
"math/rand"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/simonpasquier/instrumented_app/version"
)
var (
stages = []string{"validation", "payment", "shipping"}
// (fake) business metrics
sessions = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "user_sessions",
Help: "Current number of user sessions.",
})
errOrders = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "order_errors_total",
Help: "Total number of order errors (slow moving counter).",
},
[]string{"stage"},
)
orders = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "orders_total",
Help: "Total number of orders (fast moving counter).",
},
)
// HTTP handler metrics
reqDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Histogram of latencies for HTTP requests.",
Buckets: []float64{.05, .1, .5, 1, 2.5, 5, 10},
},
[]string{"handler", "method", "code"},
)
reqSize = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_size_bytes",
Help: "Histogram of response sizes for HTTP requests.",
Buckets: []float64{1024, 2048, 4096, 16384, 65536, 131072},
},
[]string{"handler", "method", "code"},
)
)
func init() {
prometheus.MustRegister(errOrders)
prometheus.MustRegister(orders)
prometheus.MustRegister(sessions)
prometheus.MustRegister(reqDuration)
prometheus.MustRegister(reqSize)
if version.BuildDate != "" && version.Revision != "" {
version := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "instrumented_app_info",
Help: "Information about the app version.",
ConstLabels: prometheus.Labels{"build_date": version.BuildDate, "version": version.Revision},
})
version.Set(1)
prometheus.MustRegister(version)
}
}
type server struct {
username string
password string
}
func updateMetrics(d time.Duration, done chan struct{}) {
t := time.NewTimer(d)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
select {
case <-t.C:
sessions.Set(float64(r.Intn(100)))
orders.Add(float64(r.Intn(5)))
for _, s := range stages {
errOrders.WithLabelValues(s).Add(math.Floor(float64(r.Intn(100)) / 97))
}
t.Reset(d)
case <-done:
return
}
}
}
func (s *server) auth(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if s.username != "" && s.password != "" && (user != s.username || pass != s.password || !ok) {
http.Error(w, "Unauthorized.", 401)
return
}
fn(w, r)
}
}
func (s *server) readyHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Ready")
}
func (s *server) healthyHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Healthy")
}
func (s *server) helloHandler(w http.ResponseWriter, _ *http.Request) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
time.Sleep(time.Duration(int64(r.Intn(1000))) * time.Millisecond)
io.WriteString(w, "Hello!")
}
func registerHandler(handleFunc func(pattern string, handler http.Handler), name string, handler http.HandlerFunc) {
handleFunc(name, promhttp.InstrumentHandlerDuration(
reqDuration.MustCurryWith(prometheus.Labels{"handler": name}),
promhttp.InstrumentHandlerResponseSize(
reqSize.MustCurryWith(prometheus.Labels{"handler": name}),
handler,
),
))
}
func main() {
app := kingpin.New(filepath.Base(os.Args[0]), "Demo application for Prometheus instrumentation.")
app.Version(version.Revision)
app.HelpFlag.Short('h')
var listen = app.Flag("listen", "Listen address").Default("127.0.0.1:8080").String()
var listenm = app.Flag("listen-metrics", "Listen address for exposing metrics (default to 'listen' if blank)").Default("").String()
var auth = app.Flag("basic-auth", "Basic authentication (eg <user>:<password>)").Default("").String()
_, err := app.Parse(os.Args[1:])
if err != nil {
log.Fatalf("%s, try --help", err)
}
var s *server
userpass := strings.SplitN(*auth, ":", 2)
if len(userpass) == 2 {
log.Println("Basic authentication enabled")
s = &server{username: userpass[0], password: userpass[1]}
} else {
s = &server{}
}
var wg sync.WaitGroup
done := make(chan struct{})
go func() {
wg.Add(1)
defer wg.Done()
updateMetrics(time.Duration(time.Second), done)
}()
registerHandler(http.Handle, "/-/healthy", http.HandlerFunc(s.readyHandler))
registerHandler(http.Handle, "/-/ready", http.HandlerFunc(s.readyHandler))
registerHandler(http.Handle, "/", s.auth(http.HandlerFunc(s.helloHandler)))
if *listenm != "" {
mux := http.NewServeMux()
registerHandler(mux.Handle, "/metrics", s.auth(promhttp.Handler().ServeHTTP))
go func() {
wg.Add(1)
defer wg.Done()
log.Println("Listening on", *listenm, "(metrics only)")
log.Fatal(http.ListenAndServe(*listenm, mux))
}()
} else {
log.Println("Registering /metrics")
registerHandler(http.Handle, "/metrics", s.auth(promhttp.Handler().ServeHTTP))
}
go func() {
wg.Add(1)
defer wg.Done()
log.Println("Listening on", *listen)
log.Fatal(http.ListenAndServe(*listen, nil))
}()
wg.Wait()
}
|
package main
import (
"bufio"
b64 "encoding/base64"
"encoding/json"
"flag"
"fmt"
"log"
_ "net/http/pprof"
"os"
"strings"
"time"
"github.com/ckin-it/minedive/minedive"
)
var lineChan chan string
var bootstrap string
var mineClient *minedive.Client
var avoid []string
func init() {
lineChan = make(chan string)
flag.StringVar(&bootstrap, "bootstrap", "ws://localhost:6501/ws", "bootstrapserver")
}
//cli, encMsg.Key, m.Query, m.Lang, encMsg.Key, encMsg.Nonce
func s(m *minedive.Client, peer string, q string, lang string, key string, nonce string) {
msg := minedive.L2Msg{
Type: "respv2",
Query: q,
Text: []string{"I AM NOT A BROWSER", "https://example.com", "http://example.com/", "https://example.com/", "https://nlnet.nl/", "https://quitelongexampleurlusefulfortesting.com/sdjioasjg/asjpdaihj90arfau0094/shdga9ohfgaufhahoigdfa/"},
}
b, err := json.Marshal(msg)
if err != nil {
log.Println("HandleL2 Resp Marshal:", err)
return
}
_ = b
m.ReplyCircuit(string(b), key, nonce)
}
func r(c *minedive.Client, a string) {
var res minedive.L2Msg
json.Unmarshal([]byte(a), &res)
for _, v := range res.Text {
fmt.Println(">", v)
}
}
func cmdDispatcher(c chan<- string) {
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
if err != nil {
c <- fmt.Sprintf("err %s", err)
} else {
c <- line
}
}
}
func cmdLoop(c <-chan string) {
for {
fmt.Print("> ")
select {
case line := <-c:
line = strings.Trim(line, " \n")
cmd := strings.Split(line, " ")
if len(cmd[0]) > 0 {
switch cmd[0] {
case "err":
fmt.Println(cmd[1:])
case "avoid":
avoid = append(avoid, cmd[1])
case "init":
mineClient = minedive.Dial(bootstrap)
mineClient.Verbose = true
for mineClient.GetNPeers() < 2 {
mineClient.SingleCmd("getpeers")
time.Sleep(3 * time.Second)
if len(avoid) > 0 {
for _, p := range avoid {
mineClient.DeletePeer(p)
}
}
}
mineClient.Verbose = false
case "search":
lang := "en_US"
if mineClient == nil {
return
}
if len(cmd) > 2 {
lang = cmd[2]
}
mineClient.SearchL2(cmd[1], lang)
case "verbose":
if mineClient != nil {
mineClient.Verbose = true
}
case "silence":
if mineClient != nil {
mineClient.Verbose = false
}
case "join":
mineClient = minedive.Dial(bootstrap)
fmt.Println(b64.StdEncoding.EncodeToString(mineClient.PK[:]))
mineClient.Searcher = s
var cell minedive.Cell
cell.Type = "pubk"
cell.D0 = b64.StdEncoding.EncodeToString(mineClient.PK[:])
minedive.JSONSuccessSend(mineClient, cell)
go mineClient.KeepAlive(20 * time.Second)
case "wsping":
mineClient.SingleCmd("ping")
case "cmd":
if cmd[1] != "" {
mineClient.SingleCmd(cmd[1])
}
case "getk":
if cmd[1] != "" {
var cell minedive.Cell
cell.Type = "getk"
cell.D0 = cmd[1]
minedive.JSONSuccessSend(mineClient, cell)
}
case "getspd":
if len(cmd) > 1 {
mineClient = minedive.Dial(bootstrap)
mineClient.Responder = r
fmt.Println(b64.StdEncoding.EncodeToString(mineClient.PK[:]))
p := mineClient.NewL1Peer(cmd[1], "", true, false)
time.Sleep(3 * time.Second)
fmt.Println(p.SDP)
} else {
fmt.Println("no")
}
case "wsraw":
if cmd[1] != "" {
mineClient.JCell(cmd[1])
}
case "circuit":
fmt.Println("circuit invoked with cmd:", len(cmd))
if len(cmd) == 4 {
var err error
circuit, err := mineClient.NewCircuit()
if err != nil {
log.Println(err)
} else {
fmt.Println("invoking setup circuit")
circuit.SetupCircuit(cmd[1], cmd[2], cmd[3])
}
}
case "testcirc":
mineClient = minedive.Dial(bootstrap)
mineClient.Responder = r
fmt.Println(b64.StdEncoding.EncodeToString(mineClient.PK[:]))
_, err := mineClient.NewCircuit()
if err != nil {
log.Println(err)
}
time.Sleep(1 * time.Second)
mineClient.Circuits[0].Send("{\"type\":\"test\"}")
go mineClient.KeepAlive(20 * time.Second)
case "testcirc2":
mineClient.Circuits[0].Send("{\"type\":\"test\"}")
case "searchv2":
if len(cmd) == 2 {
msg := fmt.Sprintf("{\"type\":\"search\",\"q\":\"%s\",\"lang\":\"it\"}", cmd[1])
mineClient.Circuits[0].Send(msg)
}
case "raw":
if cmd[1] != "" && cmd[2] != "" {
p, ok := mineClient.GetPeer(cmd[1])
if ok {
p.Msg(cmd[2])
}
}
case "list":
mineClient.ListL1Peers()
case "getpeers":
mineClient.SingleCmd("getpeers")
case "quit":
os.Exit(1)
default:
}
}
}
}
}
func main() {
flag.Parse()
go func() {
//log.Println(http.ListenAndServe("localhost:6600", nil))
}()
go cmdDispatcher(lineChan)
cmdLoop(lineChan)
}
|
package cmd
import (
"fmt"
"github.com/juliabiro/expander/pkg/abbreviator"
"github.com/juliabiro/expander/pkg/utils"
"github.com/spf13/cobra"
)
var dryRun bool
var clear bool
func printOutput(data *utils.ExpanderData, configfile string) {
// format output
out := utils.MakeSortedString(data.GeneratedConfig)
// print output
fmt.Println("Generated Abbreviations:")
fmt.Println(out)
if dryRun {
fmt.Println("Mapping not saved. To save, use the --dry-run=false flag.")
} else {
utils.WriteToFile(data, configfile)
}
}
var mapCmd = &cobra.Command{
Use: "map",
Short: "generate abbreviations for available kubernetes contexts",
Long: "Map available kubernetes contexts, and print the abbreviations. These will be available for expansion in future runs.",
Args: func(cmd *cobra.Command, args []string) error {
return nil
},
Run: func(cmd *cobra.Command, args []string) {
// get parameters
expressions, err := ParseInput(args)
if err != nil {
fmt.Printf("%s", err)
return
}
// get config
data := ParseConfigData(configfile, abbreviator.ValidateData)
if data == nil {
return
}
//perform logic
if clear == true {
data.GeneratedConfig = make(map[string]string)
}
err = abbreviator.AbbreviateExpressions(expressions, data)
if err != nil {
fmt.Println(err)
return
}
//print output
printOutput(data, configfile)
},
}
func init() {
mapCmd.PersistentFlags().BoolVar(&dryRun, "dry-run", true, "toggles dry-run mode. When False, the generated abbreviations are saved to the config file. Default is true")
mapCmd.PersistentFlags().BoolVar(&clear, "clear-existing-conf", false, "When true, the mapping replaces the exisiting generated conf. When false, it just adds to it (also overwrites it). Default is false")
rootCmd.AddCommand(mapCmd)
}
|
package main
import (
"context"
"flag"
"fmt"
pb "ziyun/auth-service/pb"
r "ziyun/auth-service/svc/client/http"
)
func main() {
flag.Parse()
ctx := context.Background()
authCli, _ := r.New("192.168.73.3:5150")
AToke := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEzODc0OTIsImlzcyI6IlN5c3RlbSIsIkNsaWVudCI6eyJDbGllbnRJZCI6IkNsaWVudElkIiwiQ2xpZW50U2VjcmV0IjoiIiwiQWNjZXNzVG9rZW5WYWxpZGl0eVNlY29uZHMiOjg2NDAwLCJSZWZyZXNoVG9rZW5WYWxpZGl0eVNlY29uZHMiOjI1OTIwMDAsIlJlZ2lzdGVyZWRSZWRpcmVjdFVyaSI6IiIsIkF1dGhvcml6ZWRHcmFudFR5cGVzIjpudWxsfSwiVXNlciI6eyJVc2VySWQiOiJVc2VySWQiLCJVc2VybmFtZSI6IlVzZXJuYW1lIiwiUGFzc3dvcmQiOiIiLCJBdXRob3JpdGllcyI6bnVsbH19.MimM5RSYzDwgDAtVPOVXZYd8zbSRkZ5dHAR3nAJ6CLQ"
result, err := authCli.Auth(ctx, &pb.AuthRequest{"Check_Token", "", "", "", "", AToke, ""})
if err != nil {
fmt.Println("Check error", err.Error())
}
fmt.Println("result=", result)
}
|
package main
import (
"encoding/base64"
"encoding/binary"
"fmt"
)
func main() {
var num int64 = 6285777273663
// convert int64 to []byte
buf := make([]byte, binary.MaxVarintLen64)
_ = binary.PutVarint(buf, num)
// convert []byte to int64
x, n := binary.Varint(buf)
fmt.Printf("x is: %v, %s, n is: %v\n", x, base64.StdEncoding.EncodeToString(buf), n)
}
|
package main
import (
"math/rand"
"time"
)
type point struct {
x float64
y float64
bias float64
label int
}
func f(x float64) float64 {
return 3*x + 2
}
func newPoint() point {
src := rand.NewSource(time.Now().UnixNano())
r := rand.New(src)
p := point{
x: (r.Float64() * 20) - 10,
y: (r.Float64() * 20) - 10,
}
if f(p.x) > p.y {
p.label = -1
} else {
p.label = 1
}
return p
}
|
package queue
import (
"github.com/carney520/go-algorithm/data-structure/list"
)
// Queue 表示队列类型
type Queue struct {
list *list.List
}
// Enqueue 插入队列
func (q *Queue) Enqueue(data interface{}) {
q.list.Append(data)
}
// Dequeue 出队列
func (q *Queue) Dequeue() interface{} {
head := q.list.Head()
if head != nil {
q.list.Remove(head)
return head.Data
}
return nil
}
// Peek 获取队头数据, 但不出队列
func (q *Queue) Peek() interface{} {
head := q.list.Head()
if head != nil {
return head.Data
}
return nil
}
// Len 队列长度
func (q *Queue) Len() int {
return q.list.Len()
}
// New 创建一个队列
func New() *Queue {
return &Queue{
list: list.New(),
}
}
|
package brawlstars
import (
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"sync/atomic"
"time"
)
// BaseURL is the base API URL all requests go to
const BaseURL = "https://api.brawlapi.cf/v1/"
// New creates a new instance of a Brawl Stars client with an empty http.Client{}
func New(token string) *Client {
return &Client{
HTTP: http.DefaultClient,
Token: token,
Compress: true,
ratelimit: Ratelimit{
Remaining: new(int32),
},
}
}
// Client is an API client. To avoid accepting GZIP encoded response bodies, set Compress to false
type Client struct {
HTTP *http.Client // the HTTP client used to create all requests
Token string // the authentication token used to authorize requests
Compress bool // whether the client should accept gzip encoding from the API
ratelimit Ratelimit
}
// GetPlayer returns a Player instance from the provided player tag
func (c *Client) GetPlayer(tag string) (p *Player, err error) {
tag, ok := ValidateTag(tag)
if !ok {
err = errors.New("invalid tag provided")
return
}
err = c.doJSON(http.MethodGet, "player?tag="+tag, &p)
return
}
// SearchPlayer returns a slice of Players matching the provided query
func (c *Client) SearchPlayer(query string) (p []*PlayerSearch, err error) {
err = c.doJSON(http.MethodGet, "player/search?name="+query, &p)
return
}
// GetClub returns a Club instance from the provided club tag
func (c *Client) GetClub(tag string) (club *Club, err error) {
tag, ok := ValidateTag(tag)
if !ok {
err = errors.New("invalid tag provided")
return
}
err = c.doJSON(http.MethodGet, "club?tag="+tag, &club)
return
}
// SearchClub returns a slice of Clubs matching the provided query
func (c *Client) SearchClub(query string) (clubs []*ClubSearch, err error) {
err = c.doJSON(http.MethodGet, "club/search?name="+query, &clubs)
return
}
// GetEvents retrieves the current and upcoming events
// parameters:
// - type: The type of events to return (current/upcoming/all)
func (c *Client) GetEvents(evtType string) (events *Events, err error) {
err = c.doJSON(http.MethodGet, "events?type="+evtType, &events)
return
}
// TopClubs returns the top <count> clubs in the leaderboard
func (c *Client) TopClubs(count uint) (clubs []*TopClub, err error) {
err = c.doJSON(http.MethodGet, fmt.Sprint("leaderboards/clubs?count=", count), &clubs)
return
}
// TopPlayers returns the top <count> players in the leaderboard
func (c *Client) TopPlayers(count uint) (players []*TopPlayer, err error) {
err = c.doJSON(http.MethodGet, fmt.Sprint("leaderboards/players?count=", count), &players)
return
}
// TopPlayersByBrawler returns the top <count> players in the <brawler> leaderboard
func (c *Client) TopPlayersByBrawler(brawler string, count uint) (players []*TopPlayer, err error) {
err = c.doJSON(http.MethodGet, fmt.Sprint("leaderboards/players?count=", count, "&brawler=", brawler), &players)
return
}
// doJSON creates an http request to the Brawl API and decodes the response body into a JSON object
func (c *Client) doJSON(method, path string, respBody interface{}) error {
// if we can't do any more requests, wait until we can
remaining := atomic.LoadInt32(c.ratelimit.Remaining)
if remaining <= 0 { // this shouldn't be less than 0, but possible edge case
wait := time.Until(c.ratelimit.Reset)
time.Sleep(wait)
}
req, _ := http.NewRequest(method, BaseURL+path, nil)
req.Header.Set("Authorization", c.Token)
req.Header.Set("User-Agent", "brawlstars-go (https://github.com/Soumil07/brawlstars-go)")
if c.Compress {
req.Header.Set("Accept-Encoding", "gzip")
}
response, err := c.HTTP.Do(req)
if err != nil {
return fmt.Errorf("http request error: %v", err)
}
defer response.Body.Close()
// handle status codes
switch {
case response.StatusCode >= 200 && response.StatusCode <= 300:
// decompress gzip body if set to true
var body = response.Body
if c.Compress {
body, err = gzip.NewReader(body)
if err != nil {
return fmt.Errorf("gzip compress error: %v", err)
}
defer body.Close()
}
// update ratelimit headers
remaining, _ := strconv.Atoi(req.Header.Get("X-Ratelimit-Remaining"))
reset, _ := strconv.ParseInt(req.Header.Get("X-Ratelimit-Reset"), 10, 64)
c.ratelimit.Reset = time.Unix(reset, 0)
atomic.StoreInt32(c.ratelimit.Remaining, int32(remaining))
// decode JSON body
return json.NewDecoder(body).Decode(respBody)
default:
return fmt.Errorf("unexpected status code: %s", response.Status)
}
}
|
package red_black_tree
import (
"fmt"
"math"
)
// 1. 每个节点都是红色或黑色
// 2. 根节点必须为黑色
// 3. 叶子节点必须为黑色
// 4. 双亲节点为红色时, 叶子节点必须为黑色
// 5. 任意根所有路径的黑色节点数量相同
type Node struct {
k int
v interface{}
color Color
parent, left, right *Node
}
type Color string
const Red Color = "RED"
const Black Color = "BLACK"
func (n *Node) Add(k int, v interface{}, parent *Node) *Node {
if n == nil {
color := Red
if parent == nil {
color = Black
}
return &Node{
k: k,
v: v,
color: color,
parent: parent,
}
}
if k == n.k {
tmp := &Node{
k: n.k,
v: n.v,
color: n.color,
parent: parent,
}
n.v = v
return tmp
}
if k < n.k {
n.left = n.left.Add(k, v, n)
}
if k > n.k {
n.right = n.right.Add(k, v, n)
}
return n
}
func (n *Node) Height() int {
if n == nil {
return 0
}
return int(math.Max(float64(n.left.Height()), float64(n.right.Height()))) + 1
}
func (n *Node) InOrder() {
if n == nil {
return
}
n.left.InOrder()
fmt.Println(n.k)
n.right.InOrder()
}
|
package apps
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"testing"
)
type User struct {
ID uint `gorm:"primarykey"`
Email string `gorm:"uniqueIndex"`
FirstName string
}
// An app to manage users
type UserApp struct{}
func (a *UserApp) Name() string {
return "users"
}
func (a *UserApp) Migrations() []GormMigration {
return []GormMigration{
InlineGormMigration{
ID: "0001_add_user",
OnUp: func(db *gorm.DB) error {
// Here we are not using db.Migrator().CreateTable(&User{}) because when resetting
// migrations to zero, it will create field which would not have existed before
if err := db.Exec("CREATE TABLE `users` (`id` integer,`email` text,PRIMARY KEY (`id`))").Error; err != nil {
return err
}
if err := db.Exec("CREATE UNIQUE INDEX `idx_users_email` ON `users`(`email`)").Error; err != nil {
return err
}
return nil
},
OnDown: func(db *gorm.DB) error {
return db.Migrator().DropTable(&User{})
},
},
InlineGormMigration{
ID: "0002_add_user_first_name",
OnUp: func(db *gorm.DB) error {
return db.Migrator().AddColumn(&User{}, "FirstName")
},
OnDown: func(db *gorm.DB) error {
return db.Migrator().DropColumn(&User{}, "FirstName")
},
},
}
}
func TestMigrate(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
t.Error(err)
}
app := &UserApp{}
if s, err := Migrate(db.Debug(), app); err != nil {
t.Error(err)
} else {
s.Print()
}
if s, err := MigrateTo(db.Debug(), app, "zero"); err != nil {
t.Error(err)
} else {
s.Print()
}
}
|
package accesscontrol
import (
"net/http"
"github.com/danielsomerfield/authful/server/service/oauth"
"github.com/danielsomerfield/authful/server/wire/authentication"
)
type ClientAccessControlFn func(request http.Request) (bool, error)
func NewClientAccessControlFn(clientLookup oauth.ClientLookupFn) ClientAccessControlFn {
return NewClientAccessControlFnWithScopes(clientLookup, "")
}
func NewClientAccessControlFnWithScopes(clientLookup oauth.ClientLookupFn, requiredScope string) ClientAccessControlFn {
return func(request http.Request) (bool, error) {
//TODO: This will need to support two auth methods: client credentials and token
//TODO: Implement client credentials first (token can come later)
//Get the credentials from the request
credentials, err := authentication.ParseClientCredentialsBasicHeader(request)
if credentials != nil {
client, err := clientLookup(credentials.ClientId)
if client != nil {
return client.CheckSecret(credentials.ClientSecret) &&
(requiredScope == "" || HasScope(client, requiredScope)), err
}
}
return false, err //TODO: NYI
}
}
func HasScope(client oauth.Client, scope string) bool {
if scope == "" {
return true
}
scopes := client.GetScopes()
for i := range scopes {
if scopes[i] == scope {
return true
}
}
return false
}
|
package main
import (
"log"
"math/rand"
"os"
"strconv"
"time"
)
func SayGreetings(greeting string, times int) {
for i := 0; i < times; i++ {
log.Println(greeting + " " + strconv.Itoa(i))
dur := time.Second * time.Duration(rand.Intn(5)) / 2
time.Sleep(dur) // 睡眠片刻
}
}
func main() {
rand.Seed(time.Now().UnixNano())
log.SetFlags(0)
cnt, _ := strconv.Atoi(os.Args[1])
for i := 0; i < cnt; i++ {
go SayGreetings("Hi"+strconv.Itoa(i), 1000)
}
log.Println("the main over!!!")
time.Sleep(time.Second * 1000000)
}
|
package main
// Testing the new GitHub Desktop application
// Testing two
// Git Branch test
// Testing four five six
import "fmt"
var (
sum int = 0
)
func main() {
for i := 0; i < 1000; i++ {
if i%3 == 0 || i%5 == 0 {
sum = sum + i
}
}
fmt.Println(sum)
}
|
package personages
import (
"core/positions"
)
type Personage struct {
Id int64
AccountId int64
Name string
PositionId int64
}
type PersonageResponse struct {
Id int64 `json:"id"`
Name string `json:"name"`
Position positions.Position `json:"position"`
}
type PersonageRequest struct {
Name string `json:"name"`
}
//function to convert types
func (pers Personage) toResponse() PersonageResponse {
return PersonageResponse{
Id: pers.Id,
Name: pers.Name,
Position: *positions.GetPositionById(pers.PositionId),
}
}
|
package dcp
import (
"reflect"
"testing"
)
func Test_maxValueSubArray(t *testing.T) {
type args struct {
arr []int
k int
}
tests := []struct {
name string
args args
want []int
}{
{"1", args{arr: []int{10, 5, 2, 7, 8, 7}, k: 3}, []int{10, 7, 8, 8}},
{"2", args{arr: []int{1, 2, 3, 1, 4, 5, 2, 3, 6}, k: 3}, []int{3, 3, 4, 5, 5, 5, 6}},
{"3", args{arr: []int{8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k: 4}, []int{10, 10, 10, 15, 15, 90, 90}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := maxValueSubArray(tt.args.arr, tt.args.k); !reflect.DeepEqual(got, tt.want) {
t.Errorf("maxValueSubArray() = %v, want %v", got, tt.want)
}
})
}
}
func Test_dpMaxValueSubArray(t *testing.T) {
type args struct {
arr []int
k int
}
tests := []struct {
name string
args args
want []int
}{
{"1", args{arr: []int{10, 5, 2, 7, 8, 7}, k: 3}, []int{10, 7, 8, 8}},
{"2", args{arr: []int{1, 2, 3, 1, 4, 5, 2, 3, 6}, k: 3}, []int{3, 3, 4, 5, 5, 5, 6}},
{"3", args{arr: []int{8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k: 4}, []int{10, 10, 10, 15, 15, 90, 90}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := deqMaxValueSubArray(tt.args.arr, tt.args.k); !reflect.DeepEqual(got, tt.want) {
t.Errorf("deqMaxValueSubArray() = %v, want %v", got, tt.want)
}
})
}
}
|
package data
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"time"
)
//关注专题
func SubjectFocus_(grbfs, ckege, uiksh string) string {
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
_, err = Db.Exec("insert into rsubfocus (Ksid,Saccount) values (?,?)", grbfs, ckege)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "插入失败")
}
_, err = Db.Exec("update hsubject set Scountfocus = Scountfocus + 1 where Usid = ?", grbfs)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
// timestamp := time.Now().Unix()
// tm := time.Unix(timestamp, 0)
// time := tm.Format("2006-01-02 15:04")
// _, err = Db.Exec("insert into hmesslike (Ireceiver,Varticle,Ssender,Wdate) values (?,?,?,?)", iv, rwhcs, uwhgc, time)
// if err != nil {
// log.Println(err)
// conn.Rollback()
// return SuccessFail_("0", "Insert err")
// }
symbols := strings.Split(uiksh, "|")
for index := 0; index < len(symbols); index++ {
symbol, _ := strconv.Atoi(symbols[index])
rows, err := Db.Query("select * from vuserlabel where Xaccount = ? and Qlabel = ? and Otype = 1", ckege, symbol)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
if rows.Next() {
_, err = Db.Exec("Update vuserlabel set Lvalue = Lvalue + 6 where Xaccount = ? and Qlabel = ? and Otype = 1 and Lvalue <= ?", ckege, symbol, MaxLabel-6)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
_, err = Db.Exec("Update vuserlabel set Lvalue = ? where Xaccount = ? and Qlabel = ? and Otype = 1 and Lvalue > ?", MaxLabel, ckege, symbol, MaxLabel-6)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
} else {
_, err = Db.Exec("Insert into vuserlabel(Xaccount,Qlabel,Lvalue,Otype) values(?,?,6,1)", ckege, symbol)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "插入失败")
}
}
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "XXX操作成功,具体说明到时候再议")
}
//取消关注专题
func SubjectCancleFocus_(grbfs, ckege, uiksh string) string {
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
_, err = Db.Exec("delete from rsubfocus where Ksid = ? and Saccount = ?", grbfs, ckege)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "删除失败")
}
_, err = Db.Exec("update hsubject set Scountfocus = Scountfocus - 1 where Usid = ?", grbfs)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
symbols := strings.Split(uiksh, "|")
for index := 0; index < len(symbols); index++ {
symbol, _ := strconv.Atoi(symbols[index])
rows, err := Db.Query("select * from vuserlabel where Xaccount = ? and Qlabel = ? and Otype = 1", ckege, symbol)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
if rows.Next() {
_, err = Db.Exec("Update vuserlabel set Lvalue = Lvalue - 6 where Xaccount = ? and Qlabel = ? and Otype = 1 and Lvalue >= 6", ckege, symbol)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
_, err = Db.Exec("Update vuserlabel set Lvalue = 0 where Xaccount = ? and Qlabel = ? and Otype = 1 and Lvalue < 6", ckege, symbol)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
}
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "XXX操作成功,具体说明到时候再议")
}
//新建专题标签
func SubjectUploadSymbol_(tjnsv string) string {
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
var post SubjectUploadSymbol
rows, err := Db.Query("select Tslid from ysubjectlabel where Rname = ?", tjnsv)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
if rows.Next() {
var Tslid int
rows.Scan(&Tslid)
post.Msg = string(Tslid)
} else {
_, err = Db.Exec("insert into ysubjectlabel(Rname) values (?)", tjnsv)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "删除失败")
}
newrows, err := Db.Query("select Tslid from ysubjectlabel where Rname = ?", tjnsv)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
newrows.Close()
if newrows.Next() {
var Tslid int
newrows.Scan(&Tslid)
post.Msg = string(Tslid)
} else {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "插入失败")
}
}
conn.Commit()
Mutex.Unlock()
post.Code = "1"
post.Msg = "XXX操作成功,具体说明到时候再议"
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
//获取关注专题列表(complete)
func SubjectListFocus_(budhs string, tehsc string) string {
limit, err := strconv.Atoi(tehsc)
if err != nil {
log.Println(err)
return SuccessFail_("0", "字符串转字符失败")
}
Mutex.Lock()
rows, err := Db.Query("select id,name,brief,thumbnail,countArticle,countFocus from view_subject_focus where account = ? limit ?,10", budhs, limit)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post SubjectListFocus
post.Data = make([]DataSubjectListFocus, 0)
for rows.Next() {
var name, brief, thumbnail string
var id, countArticle, countFocus int
err = rows.Scan(&id, &name, &brief, &thumbnail, &countArticle, &countFocus)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
data := DataSubjectListFocus{
Id: id,
Name: name,
Brief: brief,
Thumbnail: thumbnail,
CountArticle: countArticle,
CountFocus: countFocus,
}
post.Data = append(post.Data, data)
}
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
//获取专题列表(complete)
func SubjectListTime(wyejs string) string {
Mutex.Lock()
rows, err := Db.Query("select id ,name, nickname,thumbnail,countArticle,countFocus,date from view_subject where date < ? order by date desc limit 9", wyejs)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post SubjectList
post.Data = make([]DataSubjectList, 0)
for rows.Next() {
var id, name, nickname, thumbnail, date string
var countArticle, countFocus int
err = rows.Scan(&id, &name, &nickname, &thumbnail, &countArticle, &countFocus, &date)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
data := DataSubjectList{
Id: id,
Name: name,
Thumbnail: thumbnail,
Nickname: nickname,
CountArticle: countArticle,
CountFocus: countFocus,
Date: date,
}
post.Data = append(post.Data, data)
}
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
func SubjectListNum(wyejs string) string {
limit, err := strconv.Atoi(wyejs)
if err != nil {
log.Println(err)
return SuccessFail_("0", "字符串转字符失败")
}
Mutex.Lock()
rows, err := Db.Query("select id ,name, nickname,thumbnail,countArticle,countFocus,date from view_subject order by countFocus desc limit ?,9", limit)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post SubjectList
post.Data = make([]DataSubjectList, 0)
for rows.Next() {
var id, name, nickname, thumbnail, date string
var countArticle, countFocus int
err = rows.Scan(&id, &name, &nickname, &thumbnail, &countArticle, &countFocus, &date)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
data := DataSubjectList{
Id: id,
Name: name,
Nickname: nickname,
Thumbnail: thumbnail,
CountArticle: countArticle,
CountFocus: countFocus,
Date: date,
}
post.Data = append(post.Data, data)
}
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
func SubjectListAccount(kvjed string) string {
Mutex.Lock()
rows, err := Db.Query("select id ,name, nickname,thumbnail,countArticle,countFocus,date from view_subject where owner = ?", kvjed)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post SubjectList
post.Data = make([]DataSubjectList, 0)
for rows.Next() {
var id, name, nickname, thumbnail, date string
var countArticle, countFocus int
err = rows.Scan(&id, &name, &nickname, &thumbnail, &countArticle, &countFocus, &date)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
data := DataSubjectList{
Id: id,
Name: name,
Nickname: nickname,
Thumbnail: thumbnail,
CountArticle: countArticle,
CountFocus: countFocus,
Date: date,
}
post.Data = append(post.Data, data)
}
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
//获取专题详情
func SubjectListDetails_(grbfs, ckege string) string {
Mutex.Lock()
rows, err := Db.Query("select id,name,brief,thumbnail,owner,nickname,countArticle,countFocus,label from view_subject where id = ?", grbfs)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post SubjectDetails
if rows.Next() {
var countArticle, countFocus int
var id, name, brief, thumbnail, owner, nickname, label string
err = rows.Scan(&id, &name, &brief, &thumbnail, &owner, &nickname, &countArticle, &countFocus, &label)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
newrows, err := Db.Query("select * from rsubfocus where Saccount = ? and Ksid = ?", ckege, grbfs)
if err != nil {
log.Println(err)
return SuccessFail_("0", "查询失败")
}
if newrows.Next() {
post.Data.IsFocused = true
} else {
post.Data.IsFocused = false
}
if owner == ckege {
post.Data.IsOwned = true
} else {
post.Data.IsOwned = false
}
data := DataSubjectDetailsInfo{
Id: id,
Name: name,
Brief: brief,
Thumbnail: thumbnail,
Owner: owner,
Nickname: nickname,
CountArticle: countArticle,
CountFocus: countFocus,
Label: label,
}
post.Data.Info = data
}
//缺少没有返回结果(没有数据)的判断和
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
//新建专题
func SubjectAdd_(ythcs, utyeh, ertqh, oiyhx, vjmsk string) string {
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
rows, err := Db.Query("select * from hsubject where Ebelong = ?", ythcs)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
record := 0
for rows.Next() {
record++
}
if record >= 3 {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "数量达到上限")
}
timestamp := time.Now().Unix()
tm := time.Unix(timestamp, 0)
time := tm.Format("2006-01-02 15:04")
_, err = Db.Exec("insert into hsubject(Yname,Kbrief,Uthumbnail,Ebelong,Hcountarticle,Scountfocus,Ydate,Blabel) values (?,?,?,?,?,?,?,?)", utyeh, ertqh, oiyhx, ythcs, 0, 0, time, vjmsk)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "新建失败")
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "新建专题成功!")
}
//删除专题(!complete)
func SubjectDelete_(rejcs string) string {
id, err := strconv.Atoi(rejcs)
if err != nil {
log.Println(err)
return SuccessFail_("0", "Atoi er")
}
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
_, err = Db.Exec("update larticle set psid = 0 where psid = ?", id)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
_, err = Db.Exec("delete from hsubject where Usid = ?", id)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
//存在没有该数据,也能删除成功的情况,返回0行,未解决
return SuccessFail_("0", "删除失败")
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "删除专题成功!")
}
//文章投稿(complete)
func ArticleContribute_(ychsw, hsyce, anscj, rywjc string) string {
timestamp := time.Now().Unix()
tm := time.Unix(timestamp, 0)
time := tm.Format("2006-01-02 15:04")
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
_, err = Db.Exec("insert into jexamine(Caid,Usid,Gaccount,Edate) values (?,?,?,?)", ychsw, hsyce, anscj, time)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
_, err = Db.Exec("insert into umesssubject(Wsender,Qreceiver,Ydate,Carticle,Isubject) values (?,?,?,?,?)", anscj, rywjc, time, ychsw, hsyce)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "投稿申请已发送,请等待管理员审核")
}
//获取未投稿文章(complete)
func ArticleNotContribute_(hskcu string) string {
Mutex.Lock()
rows, err := Db.Query("select title from view_article where account = ?", hskcu)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post ArticleNotContribute
for rows.Next() {
var title string
err = rows.Scan(&title)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
data := DataArticleNotContribute{
Title: title,
}
post.Data = append(post.Data, data)
}
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
//获取待审核文章
func ArticleNotExamine_(ueysj string) string {
Mutex.Lock()
rows, err := Db.Query("select id,aid,title,nickname,account,head,date from view_examine")
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
Mutex.Unlock()
var post ArticleNotExamine
for rows.Next() {
var id int
var aid, title, nickname, account, head, date string
err = rows.Scan(&id, &aid, &title, &nickname, &account, &head, &date)
if err != nil {
log.Println(err)
return SuccessFail_("0", "赋值失败")
}
data := DataArticleNotExamine{
Id: id,
Aid: aid,
Title: title,
Nickname: nickname,
Account: account,
Head: head,
Date: date,
}
post.Data = append(post.Data, data)
}
rows.Close()
post.Code = "1"
post.Msg = ""
result, err := json.MarshalIndent(post, "", " ")
if err != nil {
return FailMarshalIndent(err)
}
return string(result)
}
//管理待审核文章
func ArticleExamine_ac(eshhd, twrch, imvah, tafvm, uehst string) string {
//接受
examineId, err := strconv.Atoi(eshhd)
if err != nil {
log.Println(err)
return SuccessFail_("0", "字符串转字符失败")
}
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
rows, err := Db.Query("select Caid,Usid,Gaccount from jexamine where Rid = ?", examineId)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
var articleId, subjectId, author string
for rows.Next() {
err = rows.Scan(&articleId, &subjectId, &author)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "赋值失败")
}
fmt.Println(articleId, subjectId, author)
}
_, err = Db.Exec("update larticle set Psid = ? where Xaid = ?", subjectId, articleId)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
_, err = Db.Exec("delete from jexamine where Rid = ?", examineId)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "删除失败")
}
_, err = Db.Exec("update hsubject set Hcountarticle = Hcountarticle + 1 where Usid = ?", subjectId)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "更新失败")
}
timestamp := time.Now().Unix()
tm := time.Unix(timestamp, 0)
time := tm.Format("2006-01-02 15:04")
content := "管理员:" + tafvm + "通过了您的投稿"
fmt.Println(time, content)
_, err = Db.Exec("insert into smessage(Esender,Rdate,Pcontent,Oreceiver,GisRead) values (?,?,?,?,0)", imvah, time, content, author)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "插入失败")
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "通过XXX待审核文章成功!")
}
func ArticleExamine_fa(eshhd, twrch, imvah, tafvm, uehst string) string {
//拒绝
examineId, err := strconv.Atoi(eshhd)
if err != nil {
log.Println(err)
return SuccessFail_("0", "字符串转字符失败")
}
Mutex.Lock()
conn, err := Db.Begin()
if err != nil {
log.Println("事物开启失败")
Mutex.Unlock()
return SuccessFail_("0", "事物开启失败")
}
rows, err := Db.Query("select Gaccount from jexamine where Rid = ?", examineId)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "查询失败")
}
defer rows.Close()
var author string
err = rows.Scan(&author)
if err != nil {
log.Println(err)
Mutex.Unlock()
return SuccessFail_("0", "赋值失败")
}
_, err = Db.Exec("delete from jexamine where Rid = ?", examineId)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "删除失败")
}
timestamp := time.Now().Unix()
tm := time.Unix(timestamp, 0)
time := tm.Format("2006-01-02 15:04")
content := "管理员:" + tafvm + "拒绝了您的投稿"
_, err = Db.Exec("insert into smessage(Esender,Rdate,Pcontent,Oreceiver,GisRead) values (?,?,?,?,0)", imvah, time, content, author)
if err != nil {
log.Println(err)
conn.Rollback()
Mutex.Unlock()
return SuccessFail_("0", "插入失败")
}
conn.Commit()
Mutex.Unlock()
return SuccessFail_("1", "拒绝XXX待审核文章成功!")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.