text
stringlengths 11
4.05M
|
|---|
package gofizzbuzz
import (
"fmt"
"math"
)
// GoFizzBuzz returns a string
// based on a set of simple rules
func GoFizzBuzz(i int) (w string) {
f := float64(i)
switch {
case math.Mod(f, 15) == 0:
return "fizzbuzz"
case math.Mod(f, 5) == 0:
return "buzz"
case math.Mod(f, 3) == 0:
return "fizz"
}
return fmt.Sprintf("%d", i)
}
|
package piscine
func BasicAtoi2(s string) int {
var afterZero, count int
for _, i := range s {
if i < '0' || i > '9' {
return 0
}
for j := '0'; j < i; j++ {
count++
}
afterZero = afterZero*10 + count
count = 0
}
return afterZero
}
|
//go:build !adalnk && windows
// +build !adalnk,windows
/*
* 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 adabas
import (
"fmt"
"syscall"
"unsafe"
"github.com/SoftwareAG/adabas-go-api/adatypes"
)
var (
adaLibrary = syscall.NewLazyDLL("adalnkx.dll")
adabasCallFunc = adaLibrary.NewProc("adabasx")
adabasIdFunc = adaLibrary.NewProc("lnk_set_adabas_id")
adabasPwdFunc = adaLibrary.NewProc("lnk_set_uid_pw")
)
var disableInterface = false
// setAdabasID set the Adabas ID Windows API Call to call
func setAdabasID(id *ID) error {
ret, _, errno := adabasIdFunc.Call(
uintptr(unsafe.Pointer(id.AdaID)))
adatypes.Central.Log.Debugf("Adabas set ID returns %d", ret)
if ret != 0 {
return fmt.Errorf("Errno: (%d) %v", ret, errno)
}
return nil
}
// CallAdabas uses the Adabas Windows API Call to call
func callAdabas(acbx *Acbx, abd []*Buffer) error {
for _, ab := range abd {
if len(ab.buffer) > 0 {
ab.abd.Abdaddr = uint64(uintptr(unsafe.Pointer(&ab.buffer[0])))
}
}
nrAbd := len(abd)
var abds uintptr
if nrAbd > 0 {
abds = uintptr(unsafe.Pointer(&abd[0]))
}
ret, _, errno := adabasCallFunc.Call(
uintptr(unsafe.Pointer(acbx)),
uintptr(nrAbd),
abds,
)
adatypes.Central.Log.Debugf("Adabas call returns %d: %v", int(ret), errno)
/*if ret == -1 {
return fmt.Errorf("Error calling Adabas interface")
}
if ret != 0 {
return fmt.Errorf("Error calling Adabas API")
}*/
return nil
}
type AdaIPC struct {
}
func NewAdaIPC(URL *URL, ID *ID) *AdaIPC {
return &AdaIPC{}
}
// Send Send the TCP/IP request to remote Adabas database
func (ipc *AdaIPC) Send(adabas *Adabas) (err error) {
if disableInterface {
return fmt.Errorf("IPC interface not present")
}
adatypes.Central.Log.Debugf("Call Adabas using dynamic native link")
err = adabasCallFunc.Find()
if err != nil {
disableInterface = true
adatypes.Central.Log.Debugf("Disable interface because not available")
return err
}
err = setAdabasID(adabas.ID)
if err != nil {
return err
}
/* For OP calls, initialize the security layer setting the password. The corresponding
* Security buffer (Z-Buffer) are generated inside the Adabas client layer.
* Under the hood the Z-Buffer will generate one time passwords send with the next call
* after OP. */
if adabas.ID.pwd != "" && adabas.Acbx.Acbxcmd == op.code() {
adatypes.Central.Log.Debugf("Set user %s password credentials", adabas.ID.user)
ret, _, errno := adabasIdFunc.Call(uintptr(unsafe.Pointer(&adabas.Acbx.Acbxdbid)),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(adabas.ID.user))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(adabas.ID.pwd))))
adatypes.Central.Log.Debugf("Set user pwd for %s: %d %v", adabas.ID.user, ret, errno)
}
// Call Adabas call to database
err = callAdabas(adabas.Acbx, adabas.AdabasBuffers)
if err != nil {
return err
}
adatypes.Central.Log.Debugf("Return call adabas")
return nil
}
func (ipc *AdaIPC) Connect(adabas *Adabas) (err error) {
return nil
}
// Disconnect disconnect remote TCP/IP Adabas nucleus
func (ipc *AdaIPC) Disconnect() (err error) {
return nil
}
|
package core
import (
"fmt"
"os"
)
const (
defaultDbName = "data.db"
)
var (
snippetStore *SnippetDatabase
)
func init() {
defaultDataDir, err := defaultAppDataDir()
if err != nil {
panic(fmt.Errorf("Failed to initialize database: %s", err))
}
if _, err := os.Stat(defaultDataDir); os.IsNotExist(err) {
err = os.MkdirAll(defaultDataDir, 0744)
if err != nil {
panic(fmt.Errorf("Failed to initialize database: %s", err))
}
}
fullDataPath := defaultDataDir + "/" + defaultDbName
sd, err := NewSnippetDatabase(fullDataPath)
if err != nil {
panic(fmt.Errorf("Failed to initialize database: %s", err))
}
snippetStore = sd
}
func GetSnippet(title string) (Snippet, error) {
s, e := snippetStore.GetSnippet(title)
return s, e
}
func AddSnippet(title, description, body string) error {
s := NewSnippet(title, description, body)
return snippetStore.AddSnippet(*s)
}
func RenameSnippet(oldTitle, newTitle string) error {
s, err := GetSnippet(oldTitle)
if err != nil {
return fmt.Errorf("Unable to get snippet with title %s: %s", oldTitle, err)
}
s.Title = newTitle
snippetStore.UpdateSnippet(s)
return err
}
func ChangeSnippetDescription(title, newDescription string) error {
s, err := GetSnippet(title)
if err != nil {
return fmt.Errorf("Unable to get snippet with title %s: %s", title, err)
}
s.Description = newDescription
snippetStore.UpdateSnippet(s)
return err
}
func EditSnippet(title, newBody string) error {
s, err := GetSnippet(title)
if err != nil {
return fmt.Errorf("Unable to get snippet with title %s: %s", title, err)
}
s.Body = newBody
snippetStore.UpdateSnippet(s)
return err
}
func AllSnippets() ([]Snippet, error) {
return snippetStore.AllSnippets()
}
func DeleteSnippet(title string) error {
return snippetStore.DeleteSnippet(title)
}
|
package state
import (
"fmt"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/s-matyukevich/capture-criminal-tg-bot/src/common"
dbpkg "github.com/s-matyukevich/capture-criminal-tg-bot/src/db"
)
type Show struct {
bot *tgbotapi.BotAPI
db *dbpkg.DB
}
func (s *Show) Process(update tgbotapi.Update) (string, error) {
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
if update.Message.Location == nil {
msg.Text = "Пожалуйста, укажите Ваше местоложение"
msg.ReplyMarkup = common.GetLocationKeyboard
_, err := s.bot.Send(msg)
return "", err
}
num := 10
reports, err := s.db.GetClosestReports(update.Message.Chat.ID, update.Message.Location, num)
if err != nil {
return "", err
}
if len(reports) == 0 {
msg.Text = "В течение получаса мне не поступало репортов в радиусе 10 км от Вас"
} else if len(reports) < num {
msg.Text = fmt.Sprintf("Найдено %d объектов в радиусе 10 км от Вас", len(reports))
} else {
msg.Text = fmt.Sprintf("Пересылаю %d ближайших объектов", len(reports))
}
msg.ReplyMarkup = common.MainKeyboard
_, err = s.bot.Send(msg)
if err != nil {
return "start", err
}
for _, r := range reports {
msgL := tgbotapi.NewLocation(update.Message.Chat.ID, r.Latitude, r.Longitude)
_, err := s.bot.Send(msgL)
if err != nil {
return "start", err
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
msg.Text = fmt.Sprintf(`Отправлено: %d минут(ы) назад
Расстояние: %s м
Метка: %s
Сообщение: %s`, int(time.Now().Sub(r.Timestamp).Minutes()), r.Dist, common.ReportTypes[r.Type], r.Message)
_, err = s.bot.Send(msg)
if err != nil {
return "start", err
}
if r.PhotoId != "" {
msg := tgbotapi.NewPhotoShare(update.Message.Chat.ID, r.PhotoId)
msg.Caption = r.PhotoCaption
_, err = s.bot.Send(msg)
if err != nil {
return "start", err
}
}
}
return "start", nil
}
|
package main
import (
"database/sql"
"log"
"github.com/nvm-academy/go-102-packages/repository"
"github.com/nvm-academy/go-102-packages/server"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// open a connection pool to the database and bum out
// if an error is encountered
db, err := sql.Open("mysql", "root:root@/routing")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// create an instance of the interaction property
// repository, passing in a pointer to the database
// connection pool
ipRepo := repository.NewInteractionPropertyMySqlRepository(db)
// create and start the web server
s := server.NewServer(ipRepo)
log.Fatal(s.Run(":1234"))
}
|
package util
import (
"reflect"
"testing"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
pvcToPodsCache = NewPVCToPodsCache()
pod1 = &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test",
Name: "pod1",
},
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "pvc1",
},
},
},
},
},
}
)
func TestPVCToPodsCache_AddPod(t *testing.T) {
type args struct {
pod *v1.Pod
}
tests := []struct {
name string
args args
pvcName string
want PodSet
}{
{
name: "case1",
args: args{
pod: pod1,
},
pvcName: "pvc1",
want: PodSet{
pod1.Namespace + "/" + pod1.Name: pod1,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pvcToPodsCache.AddPod(tt.args.pod)
got := pvcToPodsCache.GetPodsByPVC(pod1.Namespace, tt.pvcName)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("PVCToPodCache.AddPod() = %v, want %v", got, tt.want)
}
})
}
}
func TestPVCToPodsCache_DeletePod(t *testing.T) {
type args struct {
pod *v1.Pod
}
var w PodSet
tests := []struct {
name string
args args
want PodSet
pvcName string
}{
{
name: "case1",
args: args{
pod: pod1,
},
want: w,
pvcName: "pvc1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pvcToPodsCache.DeletePod(tt.args.pod)
got := pvcToPodsCache.GetPodsByPVC(pod1.Namespace, tt.pvcName)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("PVCToPodCache.DeletePod() = %v, want %v", got, tt.want)
}
})
}
}
|
package main
func goNorth(square int, value int) int {
return (square + value) % GRID_SIZE
}
func goEast(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
if square < GRID_WIDTH*GRID_EDGE {
dest = square + GRID_WIDTH
} else {
dest = square + 1 - (GRID_WIDTH * GRID_EDGE)
}
}
return dest
}
func goSouth(square int, value int) int {
return (square - value) % GRID_SIZE
}
func goWest(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
if square > GRID_WIDTH {
dest = square - GRID_WIDTH
} else {
dest = square - 1 + (GRID_WIDTH * GRID_EDGE)
}
}
return dest
}
func goNorthEast(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
dest = goNorth(square, 1)
dest = goEast(square, 1)
}
return dest
}
func goSouthEast(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
dest = goSouth(square, 1)
dest = goEast(square, 1)
}
return dest
}
func goSouthWest(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
dest = goSouth(square, 1)
dest = goWest(square, 1)
}
return dest
}
func goNorthWest(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
dest = goNorth(square, 1)
dest = goWest(square, 1)
}
return dest
}
func takePiece(piecesPos []int, own int, newSquare int) {
for i := 0; i < 12; i++ {
if i != own && piecesPos[i] == newSquare {
piecesPos[i] = -1
}
}
}
func doWhitePawn(piecesPos []int, grid []int) {
square := piecesPos[0]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goNorth(square, 1)
} else {
newSquare = goNorth(square, value)
}
piecesPos[0] = newSquare
takePiece(piecesPos, 0, newSquare)
}
func doWhiteKnight(piecesPos []int, grid []int) {
square := piecesPos[1]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goEast(square, 2)
newSquare = goNorth(square, 1)
} else {
for i := 0; i < value; i++ {
newSquare = goEast(square, 2)
newSquare = goNorth(square, 1)
}
}
piecesPos[1] = newSquare
takePiece(piecesPos, 1, newSquare)
}
func doWhiteBishop(piecesPos []int, grid []int) {
square := piecesPos[2]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goNorthEast(square, 1)
} else {
newSquare = goNorthEast(square, value)
}
piecesPos[2] = newSquare
takePiece(piecesPos, 2, newSquare)
}
func doWhiteRook(piecesPos []int, grid []int) {
square := piecesPos[3]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goEast(square, 1)
} else {
newSquare = goEast(square, value)
}
piecesPos[3] = newSquare
takePiece(piecesPos, 3, newSquare)
}
func doWhiteQueen(piecesPos []int, grid []int) {
square := piecesPos[4]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goNorthWest(square, 1)
} else {
newSquare = goNorthWest(square, value)
}
piecesPos[4] = newSquare
takePiece(piecesPos, 4, newSquare)
}
func doWhiteKing(piecesPos []int, grid []int) {
square := piecesPos[5]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goWest(square, 1)
} else {
newSquare = goWest(square, value)
}
piecesPos[5] = newSquare
takePiece(piecesPos, 5, newSquare)
}
func doBlackPawn(piecesPos []int, grid []int) {
square := piecesPos[6]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goSouth(square, 1)
} else {
newSquare = goSouth(square, value)
}
piecesPos[6] = newSquare
takePiece(piecesPos, 6, newSquare)
}
func doBlackKnight(piecesPos []int, grid []int) {
square := piecesPos[7]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goWest(square, 2)
newSquare = goSouth(square, 1)
} else {
for i := 0; i < value; i++ {
newSquare = goWest(square, 2)
newSquare = goSouth(square, 1)
}
}
piecesPos[7] = newSquare
takePiece(piecesPos, 7, newSquare)
}
func doBlackBishop(piecesPos []int, grid []int) {
square := piecesPos[8]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goSouthWest(square, 1)
} else {
newSquare = goSouthWest(square, value)
}
piecesPos[8] = newSquare
takePiece(piecesPos, 8, newSquare)
}
func doBlackRook(piecesPos []int, grid []int) {
square := piecesPos[9]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goWest(square, 1)
} else {
newSquare = goWest(square, value)
}
piecesPos[9] = newSquare
takePiece(piecesPos, 9, newSquare)
}
func doBlackQueen(piecesPos []int, grid []int) {
square := piecesPos[10]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goSouthEast(square, 1)
} else {
newSquare = goSouthEast(square, value)
}
piecesPos[10] = newSquare
takePiece(piecesPos, 10, newSquare)
}
func doBlackKing(piecesPos []int, grid []int) {
square := piecesPos[11]
value := grid[square]
var newSquare int
if value == 0 {
newSquare = goEast(square, 1)
} else {
newSquare = goEast(square, value)
}
piecesPos[11] = newSquare
takePiece(piecesPos, 11, newSquare)
}
|
package main
import (
"io/ioutil"
"os"
"testing"
"github.com/boltdb/bolt"
)
func TestCreateDirs(t *testing.T) {
pwd, err := os.Getwd()
if err != nil {
t.Errorf("Unable to get current working directory: %s", err)
}
config := conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, DistroNames: []string{"stable"}, Sections: []string{"main", "blah"}, EnableSSL: false}
// sanity check...
if config.RootRepoPath != pwd+"/testing" {
t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing")
}
t.Log("creating temp dirs in ", config.RootRepoPath)
if err := createDirs(config); err != nil {
t.Errorf("createDirs() failed ")
}
for _, distName := range config.DistroNames {
for _, section := range config.Sections {
for _, archDir := range config.SupportArch {
if _, err := os.Stat(config.RootRepoPath + "/dists/" + distName + "/" + section + "/binary-" + archDir); err != nil {
if os.IsNotExist(err) {
t.Errorf("Directory for %s does not exist", archDir)
}
}
}
}
}
// cleanup
if err := os.RemoveAll(config.RootRepoPath); err != nil {
t.Errorf("error cleaning up after createDirs(): %s", err)
}
// create temp file
tempFile, err := os.Create(pwd + "/tempFile")
if err != nil {
t.Fatalf("create %s: %s", pwd+"/tempFile", err)
}
defer tempFile.Close()
config.RootRepoPath = pwd + "/tempFile"
// Can't make directory named after file.
if err := createDirs(config); err == nil {
t.Errorf("createDirs() should have failed but did not")
}
// cleanup
if err := os.RemoveAll(pwd + "/tempFile"); err != nil {
t.Errorf("error cleaning up after createDirs(): %s", err)
}
}
func TestCreateAPIkey(t *testing.T) {
// create temp db
db, err := bolt.Open(tempfile(), 0666, nil)
if err != nil {
t.Fatalf("error creating tempdb: %s", err)
}
defer db.Close()
// should fail
_, err = createAPIkey(db)
if err == nil {
t.Errorf("createAPIkey should have failed but didn't")
}
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("APIkeys"))
if err != nil {
//return log.Fatal("unable to create DB bucket: ", err)
return err
}
return nil
})
if err != nil {
t.Fatalf("error creating db bucket: %s", err)
}
_, err = createAPIkey(db)
if err != nil {
t.Errorf("error creating API key: %s", err)
}
}
// tempfile returns a temporary file path.
func tempfile() string {
f, err := ioutil.TempFile("", "bolt-")
if err != nil {
panic(err)
}
if err := f.Close(); err != nil {
panic(err)
}
if err := os.Remove(f.Name()); err != nil {
panic(err)
}
return f.Name()
}
|
package golist
import "fmt"
type node struct {
data int
next *node
}
type list struct {
head *node
tail *node
}
func NewList() list {
return list{head: nil, tail: nil}
}
func (l *list) AppendToTail(d int) {
tmp := &node{data: d, next: nil}
if l.head == nil {
l.head = tmp
l.tail = tmp
} else {
l.tail.next = tmp
l.tail = tmp
}
}
func (l *list) RemoveFromTail() {
if l.head == l.tail {
l.head = nil
l.tail = nil
return
}
p := l.head
for p.next != l.tail {
p = p.next
}
l.tail = p
p.next = nil
}
func (l *list) RemoveFromHead() {
l.head = l.head.next
}
func (l *list) AppendToHead(d int) {
tmp := &node{data: d, next: l.head}
if l.head == nil {
l.head = tmp
l.tail = tmp
} else {
l.head = tmp
}
}
func (l *list) PrintList() {
p := l.head
if p == nil {
return
}
for p != l.tail {
fmt.Printf("%d, ", p.data)
p = p.next
}
fmt.Printf("%d\n", l.tail.data)
}
|
package handler
import (
"context"
"github.com/valyala/fasthttp"
elastic "gopkg.in/olivere/elastic.v5"
)
type GeoQueryHandler struct {
ElasticClient *elastic.Client
Context context.Context
}
// request handler in net/http style, i.e. method bound to MyCustomHandler struct.
func (h *GeoQueryHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("text/plain; charset=utf8")
switch string(ctx.Path()) {
case "/shape":
shapeQueryHandlerFunc(ctx, h.ElasticClient, h.Context)
case "/point":
pointQueryHandlerFunc(ctx, h.ElasticClient, h.Context)
case "/circle":
circleQueryHandlerFunc(ctx, h.ElasticClient, h.Context)
default:
ctx.Error("Not Found", fasthttp.StatusNotFound)
}
}
|
package main
import (
"ewallet/database"
"ewallet/routes"
"fmt"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/spf13/viper"
"log"
"net/http"
)
func GetEnvironmentVariable(key string) string {
viper.SetConfigFile(".env")
err := viper.ReadInConfig()
if err != nil {
log.Fatalf("Error while reading config file %s", err)
}
value, ok := viper.Get(key).(string)
if !ok {
log.Fatalf("Invalid type assertion")
}
return value
}
func main() {
//Inisialisasi Koneksi Database
connection := database.DBConnection(
GetEnvironmentVariable("USER"),
GetEnvironmentVariable("PASSWORD"),
GetEnvironmentVariable("HOST"),
GetEnvironmentVariable("DATABASE"),
)
//migrasi database
database.Migrate(connection)
//melakukan seed untuk data awal di database
database.Seed(connection)
routes := routes.GetRoutes(connection)
http.Handle("/", routes)
PORT := GetEnvironmentVariable("PORT")
fmt.Println(fmt.Sprintf("server started at localhost:%s", PORT))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", PORT), nil))
defer connection.Close()
}
|
package controllers
import (
"github.com/astaxie/beego/httplib"
"time"
)
type MainController struct {
BaseController
}
func (c *MainController) Get() {
headers := []string{"x-request-id",
"x-b3-traceid",
"x-b3-spanid",
"x-b3-parentspanid",
"x-b3-sampled",
"x-b3-flags",
"x-ot-span-context"}
req := httplib.Get("http://three-service:1234").SetTimeout(5*time.Second, 5*time.Second)
for i := 0; i < len(headers); i++ {
req.Header(headers[i], c.Ctx.Input.Header(headers[i]))
}
s, err := req.String()
if err != nil {
c.ReturnData(-1, err.Error(), nil)
} else {
c.ReturnData(0, "success", s)
}
}
|
package group
import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/proto/group"
"context"
)
func (s *groupServer) GroupApplicationResponse(_ context.Context, pb *group.GroupApplicationResponseReq) (*group.GroupApplicationResponseResp, error) {
log.Info("", "", "rpc GroupApplicationResponse call start..., [pb: %s]", pb.String())
reply, err := im_mysql_model.GroupApplicationResponse(pb)
if err != nil {
log.Error("", "", "rpc GroupApplicationResponse call..., im_mysql_model.GroupApplicationResponse fail [pb: %s] [err: %s]", pb.String(), err.Error())
return &group.GroupApplicationResponseResp{ErrCode: 702, ErrMsg: "rpc GroupApplicationResponse failed"}, nil
}
if pb.HandleResult == 1 {
if pb.ToUserID == "0" {
err = db.DB.AddGroupMember(pb.GroupID, pb.FromUserID)
if err != nil {
log.Error("", "", "rpc GroupApplicationResponse call..., db.DB.AddGroupMember fail [pb: %s] [err: %s]", pb.String(), err.Error())
return nil, err
}
} else {
err = db.DB.AddGroupMember(pb.GroupID, pb.ToUserID)
if err != nil {
log.Error("", "", "rpc GroupApplicationResponse call..., db.DB.AddGroupMember fail [pb: %s] [err: %s]", pb.String(), err.Error())
return nil, err
}
}
}
log.Info("", "", "rpc GroupApplicationResponse call..., im_mysql_model.GroupApplicationResponse")
return reply, nil
}
|
package conf
import (
"krpc/codec"
"time"
)
const MagicNumber = 0x3bef5b
// Option Client tell Server, what kind of CodeType to use, then use this type to decode/encode.
type Option struct {
MagicNumber int // marks this is a krpc request
CodeType codec.CodeType // client may choose different Codec to encode body
ConnectionTimeout time.Duration
HandleTimeout time.Duration
}
var DefaultOption = &Option{
MagicNumber: MagicNumber,
CodeType: codec.GobType,
ConnectionTimeout: time.Second * 10,
}
|
package monitors
import (
"github.com/lixiangzhong/dnsutil"
)
func dnsMonitor(address string, expectation string) bool {
var dig dnsutil.Dig
dig.SetDNS(address)
a, err := dig.A(expectation)
if err != nil {
return false
}
if len(a) <= 0 {
return false
}
return true
}
|
package credentials
import (
"testing"
"github.com/Mindslave/skade/backend/pkg/generate"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)
func TestPassword(t* testing.T) {
password := generate.RandomString(8)
wrongPassword := generate.RandomString(8)
hash, err := CreateHash(password)
require.NoError(t, err)
require.NotEmpty(t, hash)
err = CheckPassword(hash, password)
require.NoError(t, err)
err = CheckPassword(hash, wrongPassword)
require.EqualError(t, err, bcrypt.ErrMismatchedHashAndPassword.Error())
}
|
package isocket
/*
封包数据和拆包数据
直接面向TCP连接中的数据流,为传输数据添加头部信息,用于处理TCP粘包问题。
*/
type IDataPack interface {
GetHeadLen() uint32 //获取包头长度方法
Pack(data []byte) ([]byte, error) //封包方法
Unpack(binaryData []byte) (IMessage, error) //拆包方法
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"syscall"
)
//Awstoken struct to hold content of system generated json file in ~/.aws/cli/cashe/<filename.json>
type Awstoken struct {
AssumedRoleUser AssumedRoleUser
Credentials Credentials
ResponseMetadata ResponseMetadata
}
type AssumedRoleUser struct {
AssumedRoleId string `json:"AssumedRoleId"`
Arn string `json:"Arn"`
}
type Credentials struct {
SecretAccessKey string `json:"SecretAccessKey"`
SessionToken string `json:"SessionToken"`
Expiration string `json:"Expiration"`
AccessKeyId string `json:"AccessKeyId"`
}
type ResponseMetadata struct {
RetryAttempts string `json:"RetryAttempts"`
HTTPStatusCode int `json:"HTTPStatusCode"`
RequestId string `json:"RequestId"`
HTTPHeaders HTTPHeaders
}
type HTTPHeaders struct {
xamznrequestid string `json:"x-amzn-requestid"`
date string `json:"date"`
contentlength string `json:"content-length"`
contenttype string `json:"content-type"`
}
var a Awstoken
func main() {
handleRequests()
}
func handleRequests() {
http.HandleFunc("/", Env)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func Env(w http.ResponseWriter, r *http.Request) {
content, err := ioutil.ReadFile(os.Getenv("myjsonfile")) //file in ~/.aws/cli/cache
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
json.Unmarshal(content, &a)
os.Setenv("AWS_ACCESS_KEY_ID", a.Credentials.AccessKeyId)
os.Setenv("AWS_SECRET_ACCESS_KEY", a.Credentials.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", a.Credentials.SessionToken)
//f, err := os.OpenFile("/", os.O_APPEND, 0666)
file := os.Getenv("myprofilefile")
f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
n, err := f.WriteString("\n export AWS_ACCESS_KEY_ID=" + a.Credentials.AccessKeyId)
m, err := f.WriteString("\n export AWS_SECRET_ACCESS_KEY=" + a.Credentials.SecretAccessKey)
h, err := f.WriteString("\n export AWS_SESSION_TOKEN=" + a.Credentials.SessionToken)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
f.Close()
fmt.Fprintln(os.Stdout, n, m, h)
fmt.Fprintf(w, " values are set \n AccessKeyId %s\n SecretAccessKey %s\n SessionToken %s\n", os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"), os.Getenv("AWS_SESSION_TOKEN"))
exec.Command("source", file)
//replace go shell with new shell with env values - note go run exists
syscall.Exec(os.Getenv("SHELL"), []string{os.Getenv("SHELL")}, syscall.Environ())
fmt.Fprintf(w, " values are set \n AccessKeyId %s\n SecretAccessKey %s\n SessionToken %s\n", os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"), os.Getenv("AWS_SESSION_TOKEN"))
//json.NewEncoder(w).Encode(a)
}
|
package dao
import (
"github.com/therudite/api/models/feedback"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Feedback struct {
Mongo *mgo.Database
}
func (this *Feedback) InsertFeedback(feedback *models.Feedback) (bool, error) {
err := this.Mongo.C("feedback").Insert(feedback)
if err != nil {
return false, err
}
return true, nil
}
func (this *Feedback) FeedbackExists(id string, userId int64) (bool, error) {
count, err := this.Mongo.C("feedback").Find(bson.M{"id": id, "user_id": userId}).Count()
if err != nil {
return false, err
}
if count > 0 {
return true, nil
}
return false, nil
}
func (this *Feedback) FeedbackUpdate(feedback *models.Feedback) (bool, error) {
feedbackExists, err := this.FeedbackExists(feedback.Id, feedback.UserId)
if feedbackExists {
query := bson.M{"id": feedback.Id, "user_id": feedback.UserId}
updatedBSON := bson.M{"$set": bson.M{"values": feedback.Values, "comments": feedback.Comments}}
err = this.Mongo.C("feedback").Update(query, updatedBSON)
if err != nil {
return false, err
}
return true, nil
} else {
return this.InsertFeedback(feedback)
}
}
|
package http_handlers
import (
"github.com/go-martini/martini"
"net/http"
)
func Routes() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return HttpHandler(
[]string{},
func(h *Http) {
routes := make([]map[string]interface{}, 0)
for _, route := range Router.All() {
routes = append(
routes,
map[string]interface{}{
"name": route.GetName(),
"url": route.Pattern(),
"method": route.Method(),
},
)
}
h.SetResponse(
routes,
)
},
)
}
|
package v3
import (
envoy_cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
envoy_endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
envoy_listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
envoy_route "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
envoy_auth "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
envoy_types "github.com/envoyproxy/go-control-plane/pkg/cache/types"
envoy_cache "github.com/envoyproxy/go-control-plane/pkg/cache/v3"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
mesh_proto "github.com/kumahq/kuma/api/mesh/v1alpha1"
core_mesh "github.com/kumahq/kuma/pkg/core/resources/apis/mesh"
xds_model "github.com/kumahq/kuma/pkg/core/xds"
test_model "github.com/kumahq/kuma/pkg/test/resources/model"
xds_context "github.com/kumahq/kuma/pkg/xds/context"
)
var _ = Describe("Reconcile", func() {
Describe("reconciler", func() {
var xdsContext XdsContext
BeforeEach(func() {
xdsContext = NewXdsContext()
})
snapshot := envoy_cache.Snapshot{
Resources: [envoy_types.UnknownType]envoy_cache.Resources{
envoy_types.Listener: {
Items: map[string]envoy_types.ResourceWithTtl{
"listener": {
Resource: &envoy_listener.Listener{},
},
},
},
envoy_types.Route: {
Items: map[string]envoy_types.ResourceWithTtl{
"route": {
Resource: &envoy_route.RouteConfiguration{},
},
},
},
envoy_types.Cluster: {
Items: map[string]envoy_types.ResourceWithTtl{
"cluster": {
Resource: &envoy_cluster.Cluster{},
},
},
},
envoy_types.Endpoint: {
Items: map[string]envoy_types.ResourceWithTtl{
"endpoint": {
Resource: &envoy_endpoint.ClusterLoadAssignment{},
},
},
},
envoy_types.Secret: {
Items: map[string]envoy_types.ResourceWithTtl{
"secret": {
Resource: &envoy_auth.Secret{},
},
},
},
},
}
It("should generate a Snapshot per Envoy Node", func() {
// given
snapshots := make(chan envoy_cache.Snapshot, 3)
snapshots <- snapshot // initial Dataplane configuration
snapshots <- snapshot // same Dataplane configuration
snapshots <- envoy_cache.Snapshot{} // new Dataplane configuration
// setup
r := &reconciler{
snapshotGeneratorFunc(func(ctx xds_context.Context, proxy *xds_model.Proxy) (envoy_cache.Snapshot, error) {
return <-snapshots, nil
}),
&simpleSnapshotCacher{xdsContext.Hasher(), xdsContext.Cache()},
}
// given
dataplane := &core_mesh.DataplaneResource{
Meta: &test_model.ResourceMeta{
Mesh: "demo",
Name: "example",
Version: "abcdefg",
},
Spec: &mesh_proto.Dataplane{},
}
By("simulating discovery event")
// when
proxy := &xds_model.Proxy{
Id: *xds_model.BuildProxyId("demo", "example"),
Dataplane: dataplane,
}
err := r.Reconcile(xds_context.Context{}, proxy)
// then
Expect(err).ToNot(HaveOccurred())
Expect(snapshot.Resources[envoy_types.Listener].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Route].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Cluster].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Endpoint].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Secret].Version).To(BeEmpty())
By("verifying that snapshot versions were auto-generated")
// when
snapshot, err := xdsContext.Cache().GetSnapshot("demo.example")
// then
Expect(err).ToNot(HaveOccurred())
Expect(snapshot).ToNot(BeZero())
// and
listenerV1 := snapshot.Resources[envoy_types.Listener].Version
routeV1 := snapshot.Resources[envoy_types.Route].Version
clusterV1 := snapshot.Resources[envoy_types.Cluster].Version
endpointV1 := snapshot.Resources[envoy_types.Endpoint].Version
secretV1 := snapshot.Resources[envoy_types.Secret].Version
Expect(listenerV1).ToNot(BeEmpty())
Expect(routeV1).ToNot(BeEmpty())
Expect(clusterV1).ToNot(BeEmpty())
Expect(endpointV1).ToNot(BeEmpty())
Expect(secretV1).ToNot(BeEmpty())
By("simulating discovery event (Dataplane watchdog triggers refresh)")
// when
err = r.Reconcile(xds_context.Context{}, proxy)
// then
Expect(err).ToNot(HaveOccurred())
By("verifying that snapshot versions remain the same")
// when
snapshot, err = xdsContext.Cache().GetSnapshot("demo.example")
// then
Expect(err).ToNot(HaveOccurred())
Expect(snapshot).ToNot(BeZero())
// and
Expect(snapshot.Resources[envoy_types.Listener].Version).To(Equal(listenerV1))
Expect(snapshot.Resources[envoy_types.Route].Version).To(Equal(routeV1))
Expect(snapshot.Resources[envoy_types.Cluster].Version).To(Equal(clusterV1))
Expect(snapshot.Resources[envoy_types.Endpoint].Version).To(Equal(endpointV1))
Expect(snapshot.Resources[envoy_types.Secret].Version).To(Equal(secretV1))
By("simulating discovery event (Dataplane gets changed)")
// when
err = r.Reconcile(xds_context.Context{}, proxy)
// then
Expect(err).ToNot(HaveOccurred())
By("verifying that snapshot versions are new")
// when
snapshot, err = xdsContext.Cache().GetSnapshot("demo.example")
// then
Expect(err).ToNot(HaveOccurred())
Expect(snapshot).ToNot(BeZero())
// and
Expect(snapshot.Resources[envoy_types.Listener].Version).To(SatisfyAll(
Not(Equal(listenerV1)),
Not(BeEmpty()),
))
Expect(snapshot.Resources[envoy_types.Route].Version).To(SatisfyAll(
Not(Equal(routeV1)),
Not(BeEmpty()),
))
Expect(snapshot.Resources[envoy_types.Cluster].Version).To(SatisfyAll(
Not(Equal(clusterV1)),
Not(BeEmpty()),
))
Expect(snapshot.Resources[envoy_types.Endpoint].Version).To(SatisfyAll(
Not(Equal(endpointV1)),
Not(BeEmpty()),
))
Expect(snapshot.Resources[envoy_types.Secret].Version).To(SatisfyAll(
Not(Equal(secretV1)),
Not(BeEmpty()),
))
By("simulating clear")
// when
err = r.Clear(&proxy.Id)
Expect(err).ToNot(HaveOccurred())
snapshot, err = xdsContext.Cache().GetSnapshot("demo.example")
// then
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("no snapshot found"))
Expect(snapshot.Resources[envoy_types.Listener].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Route].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Cluster].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Endpoint].Version).To(BeEmpty())
Expect(snapshot.Resources[envoy_types.Secret].Version).To(BeEmpty())
})
})
})
type snapshotGeneratorFunc func(ctx xds_context.Context, proxy *xds_model.Proxy) (envoy_cache.Snapshot, error)
func (f snapshotGeneratorFunc) GenerateSnapshot(ctx xds_context.Context, proxy *xds_model.Proxy) (envoy_cache.Snapshot, error) {
return f(ctx, proxy)
}
|
package cri
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"github.com/caos/orbos/internal/operator/nodeagent/dep"
)
func (c *criDep) ensureCentOS(runtime string, version string) error {
errBuf := new(bytes.Buffer)
defer errBuf.Reset()
cmd := exec.Command("yum", "--assumeyes", "remove", "docker",
"docker-client",
"docker-client-latest",
"docker-common",
"docker-latest",
"docker-latest-logrotate",
"docker-logrotate",
"docker-engine")
cmd.Stderr = errBuf
if c.monitor.IsVerbose() {
fmt.Println(strings.Join(cmd.Args, " "))
cmd.Stdout = os.Stdout
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("removing older docker versions failed with stderr %s: %w", errBuf.String(), err)
}
for _, pkg := range []string{"device-mapper-persistent-data", "lvm2"} {
if err := c.manager.Install(&dep.Software{Package: pkg}); err != nil {
c.monitor.Error(fmt.Errorf("installing docker dependency failed: %w", err))
}
}
return c.run(runtime, version, "https://download.docker.com/linux/centos/docker-ce.repo", "", "")
}
func (c *criDep) ensureUbuntu(runtime string, version string) error {
errBuf := new(bytes.Buffer)
defer errBuf.Reset()
buf := new(bytes.Buffer)
defer buf.Reset()
var versionLine string
cmd := exec.Command("apt-cache", "madison", runtime)
cmd.Stderr = errBuf
cmd.Stdout = buf
if err := cmd.Run(); err != nil {
return fmt.Errorf("running apt-cache madison %s failed with stderr %s: %w", runtime, errBuf.String(), err)
}
errBuf.Reset()
if c.monitor.IsVerbose() {
fmt.Println(strings.Join(cmd.Args, " "))
}
var err error
for err == nil {
versionLine, err = buf.ReadString('\n')
if c.monitor.IsVerbose() {
fmt.Println(versionLine)
}
if strings.Contains(versionLine, version) {
break
}
}
buf.Reset()
if err != nil && versionLine == "" {
return fmt.Errorf("finding line containing desired container runtime version \"%s\" failed: %w", version, err)
}
return c.run(
runtime,
strings.TrimSpace(strings.Split(versionLine, "|")[1]),
fmt.Sprintf("deb [arch=amd64] https://download.docker.com/linux/ubuntu %s stable", c.os.Version),
"https://download.docker.com/linux/ubuntu/gpg",
"0EBFCD88",
)
}
func (c *criDep) run(runtime, version, repoURL, keyURL, keyFingerprint string) error {
try := func() error {
// Obviously, docker doesn't care about the exact containerd version, so neighter should ORBITER
// https://docs.docker.com/engine/install/centos/
// https://docs.docker.com/engine/install/ubuntu/
if err := c.manager.Install(&dep.Software{
Package: "containerd.io",
Version: containerdVersion,
}); err != nil {
return err
}
err := c.manager.Install(&dep.Software{
Package: runtime,
Version: version,
})
return err
}
if err := try(); err != nil {
swmonitor := c.monitor.WithField("software", "docker")
swmonitor.Error(fmt.Errorf("installing software from existing repo failed, trying again after adding repo: %w", err))
if err := c.manager.Add(&dep.Repository{
Repository: repoURL,
KeyURL: keyURL,
KeyFingerprint: keyFingerprint,
}); err != nil {
return err
}
swmonitor.WithField("url", repoURL).Info("repo added")
if err := try(); err != nil {
swmonitor.Error(fmt.Errorf("installing software from %s failed: %w", repoURL, err))
return err
}
}
if err := c.systemd.Enable("docker"); err != nil {
return err
}
return c.systemd.Start("docker")
}
|
package controllers
import "github.com/robfig/revel"
type Application struct {
*rev.Controller
}
func (c Application) Index() rev.Result {
greeting := "Hello World!"
return c.Render(greeting)
}
func (c Application) Hello(myName string) rev.Result {
return c.Render(myName)
}
|
package main
// Package strings adalah package yang berisikan function function untuk memanipulasi tipe data string
import (
"fmt"
"strings"
)
func main() {
// mengecek apakah string di params1 mengandung string yg di params2
fmt.Println(strings.Contains("Muhammad Zhuhry", "Zhuhry"))
fmt.Println(strings.Contains("Muhammad Zhuhry", "Budi"))
// Split -> memotong string berdasarkan seperator menjadi slice
fmt.Println(strings.Split("Muhammad Zhuhry", " "))
// ToLower -> membuat semua karakter string menjadi lower case
fmt.Println(strings.ToLower("Muhammad Zhuhry"))
// ToUpper -> membuat semua karakter string menjadi upper case
fmt.Println(strings.ToUpper("Muhammad Zhuhry"))
// Trim -> memotong cutset di awal dan akhir string
fmt.Println(strings.Trim(" Muhammad Athallah Zhuhry ", " "))
// ReplaceAll -> mengubah semua string dari from ke to
fmt.Println(strings.ReplaceAll("Zuhri Zuhri Zuhri Athallah Zuhri", "Athallah", "Budi"))
}
|
package models
import (
"encoding/json"
"html/template"
"io/ioutil"
"log"
"time"
)
const FILENAME = "blog.csv"
type Blog struct {
ID int64 `json:"id"`
Title string `json:"title,omitempty"`
Details string `json:"details,omitempty"`
Comment int `json:"comment"`
View int `json:"view"`
Date time.Time `json:"date"`
Comments map[int64]Comment `json:"comments"`
}
type Message struct {
Message string `json:"message"`
Data Blogs `json:"data"`
Color string `json:"color"`
Post Blog `json:"post"`
}
type Blogs struct {
Blogs []Blog `json:"blogs"`
}
var t *template.Template
func init() {
loadFile()
t = template.Must(template.ParseGlob("frontend/*"))
}
func loadFile() {
res, err := ioutil.ReadFile("blog.csv")
if err != nil {
log.Printf(err.Error())
} else {
_ = json.Unmarshal(res, &blogs)
}
}
func (b Blogs) addToFile() error {
res, err := json.MarshalIndent(b, "", "\t")
if err != nil {
return err
}
err = ioutil.WriteFile("blog.csv", res, 0666)
return err
}
|
package test_helpers
import (
"fmt"
. "github.com/onsi/gomega"
"net/http"
)
func RegisterCache(
session_key string,
headers http.Header,
) (
cache_map map[string]interface{},
request *Request,
) {
header_cloned := CloneHeaders(headers)
header_cloned.Set(
"Authorization",
fmt.Sprintf(
"SessionKey %s", session_key,
),
)
url, err := MakeUrl(
GLOBAL_SERVER_URL,
"RegisterCache",
[]string{},
map[string]string{},
)
request = &Request{}
err = request.Post(
url.String(),
header_cloned,
make(map[string]interface{}),
)
Expect(err).NotTo(HaveOccurred())
Expect(request.Response.StatusCode).To(Equal(201))
mapped, ok := request.ResponsePlain.(map[string]interface{})
Expect(ok).To(BeTrue())
Expect(mapped["id"]).To(HaveLen(36))
Expect(mapped["id"]).To(BeAssignableToTypeOf(""))
return mapped, request
}
func GetCache(
session_key string,
cache_key string,
headers http.Header,
) (
cache_mapped map[string]interface{},
request *Request,
) {
header_cloned := CloneHeaders(headers)
header_cloned.Set(
"Authorization",
fmt.Sprintf(
"SessionKey %s", session_key,
),
)
url, err := MakeUrl(
GLOBAL_SERVER_URL,
"GetCache",
[]string{
cache_key,
},
map[string]string{},
)
request = &Request{}
err = request.Get(
url.String(),
header_cloned,
)
Expect(err).NotTo(HaveOccurred())
Expect(request.Response.StatusCode).To(Equal(200))
mapped, ok := request.ResponsePlain.(map[string]interface{})
Expect(ok).To(BeTrue())
return mapped, request
}
func GetCaches(
session_key string,
headers http.Header,
) (
caches_mapped map[string]interface{},
request *Request,
) {
header_cloned := CloneHeaders(headers)
header_cloned.Set(
"Authorization",
fmt.Sprintf(
"SessionKey %s", session_key,
),
)
url, err := MakeUrl(
GLOBAL_SERVER_URL,
"GetCaches",
[]string{},
map[string]string{},
)
request = &Request{}
err = request.Get(
url.String(),
header_cloned,
)
Expect(err).NotTo(HaveOccurred())
Expect(request.Response.StatusCode).To(Equal(200))
mapped, ok := request.ResponsePlain.(map[string]interface{})
Expect(ok).To(BeTrue())
return mapped, request
}
|
// Package xmlsec is a wrapper around the xmlsec1 command
// https://www.aleksey.com/xmlsec/index.html
package xmlsec
import (
"bufio"
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
)
const (
attrNameResponse = `urn:oasis:names:tc:SAML:2.0:protocol:Response`
attrNameAssertion = `urn:oasis:names:tc:SAML:2.0:assertion:Assertion`
attrNameAuthnRequest = `urn:oasis:names:tc:SAML:2.0:protocol:AuthnRequest`
)
type ValidationOptions struct {
DTDFile string
EnableIDAttrHack bool
IDAttrs []string
}
// ErrSelfSignedCertificate is a typed error returned when xmlsec1 detects a
// self-signed certificate.
type ErrSelfSignedCertificate struct {
err error
}
// Error returns the underlying error reported by xmlsec1.
func (e ErrSelfSignedCertificate) Error() string {
return e.err.Error()
}
// ErrUnknownIssuer is a typed error returned when xmlsec1 detects a
// "unknown issuer" error.
type ErrUnknownIssuer struct {
err error
}
// Error returns the underlying error reported by xmlsec1.
func (e ErrUnknownIssuer) Error() string {
return e.err.Error()
}
// ErrValidityError is a typed error returned when xmlsec1 detects a
// "unknown issuer" error.
type ErrValidityError struct {
err error
}
// Error returns the underlying error reported by xmlsec1.
func (e ErrValidityError) Error() string {
return e.err.Error()
}
// Encrypt encrypts a byte sequence into an EncryptedData template using the
// given certificate and encryption method.
func Encrypt(template *EncryptedData, in []byte, publicCertPath string, method string) ([]byte, error) {
// Writing template.
fp, err := ioutil.TempFile("/tmp", "xmlsec")
if err != nil {
return nil, err
}
defer os.Remove(fp.Name())
out, err := xml.MarshalIndent(template, "", "\t")
if err != nil {
return nil, err
}
_, err = fp.Write(out)
if err != nil {
return nil, err
}
if err := fp.Close(); err != nil {
return nil, err
}
// Executing command.
cmd := exec.Command("xmlsec1", "--encrypt",
"--session-key", method,
"--pubkey-cert-pem", publicCertPath,
"--output", "/dev/stdout",
"--xml-data", "/dev/stdin",
fp.Name(),
)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
outbr := bufio.NewReader(stdout)
errbr := bufio.NewReader(stderr)
if err := cmd.Start(); err != nil {
return nil, err
}
if _, err := stdin.Write(in); err != nil {
return nil, err
}
if err := stdin.Close(); err != nil {
return nil, err
}
res, err := ioutil.ReadAll(outbr)
if err != nil {
return nil, err
}
resErr, err := ioutil.ReadAll(errbr)
if err != nil {
return nil, err
}
if err := cmd.Wait(); err != nil {
if len(resErr) > 0 {
return res, xmlsecErr(string(resErr))
}
return nil, err
}
return res, nil
}
// Decrypt takes an encrypted XML document and decrypts it using the given
// private key.
func Decrypt(in []byte, privateKeyPath string) ([]byte, error) {
// Executing command.
cmd := exec.Command("xmlsec1", "--decrypt",
"--privkey-pem", privateKeyPath,
"--output", "/dev/stdout",
"/dev/stdin",
)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
outbr := bufio.NewReader(stdout)
errbr := bufio.NewReader(stderr)
if err := cmd.Start(); err != nil {
return nil, err
}
if _, err := stdin.Write(in); err != nil {
return nil, err
}
if err := stdin.Close(); err != nil {
return nil, err
}
res, err := ioutil.ReadAll(outbr)
if err != nil {
return nil, err
}
resErr, err := ioutil.ReadAll(errbr)
if err != nil {
return nil, err
}
if err := cmd.Wait(); err != nil {
if len(resErr) > 0 {
return res, xmlsecErr(string(resErr))
}
return nil, err
}
return res, nil
}
// Verify takes a signed XML document and validates its signature.
func Verify(in []byte, publicCertPath string, opts *ValidationOptions) error {
args := []string{
"xmlsec1", "--verify",
"--pubkey-cert-pem", publicCertPath,
// Security: Don't ever use --enabled-reference-uris "local" value,
// since it'd allow potential attackers to read local files using
// <Reference URI="file:///etc/passwd"> hack!
"--enabled-reference-uris", "empty,same-doc",
}
applyOptions(&args, opts)
args = append(args, "/dev/stdin")
cmd := exec.Command(args[0], args[1:]...)
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
outbr := bufio.NewReader(stdout)
errbr := bufio.NewReader(stderr)
if err := cmd.Start(); err != nil {
return err
}
if _, err := stdin.Write(in); err != nil {
return err
}
if err := stdin.Close(); err != nil {
return err
}
res, err := ioutil.ReadAll(outbr)
if err != nil {
return err
}
resErr, err := ioutil.ReadAll(errbr)
if err != nil {
return err
}
if err := cmd.Wait(); err != nil || isValidityError(resErr) {
if len(resErr) > 0 {
return xmlsecErr(string(res) + "\n" + string(resErr))
}
return err
}
return nil
}
// Sign takes a XML document and produces a signature.
func Sign(in []byte, privateKeyPath string, opts *ValidationOptions) (out []byte, err error) {
args := []string{
"xmlsec1", "--sign",
"--privkey-pem", privateKeyPath,
"--enabled-reference-uris", "empty,same-doc",
}
applyOptions(&args, opts)
args = append(args,
"--output", "/dev/stdout",
"/dev/stdin",
)
cmd := exec.Command(args[0], args[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
outbr := bufio.NewReader(stdout)
errbr := bufio.NewReader(stderr)
if err := cmd.Start(); err != nil {
return nil, err
}
if _, err := stdin.Write(in); err != nil {
return nil, err
}
if err := stdin.Close(); err != nil {
return nil, err
}
res, err := ioutil.ReadAll(outbr)
if err != nil {
return nil, err
}
resErr, err := ioutil.ReadAll(errbr)
if err != nil {
return nil, err
}
if err := cmd.Wait(); err != nil || isValidityError(resErr) {
if len(resErr) > 0 {
return res, xmlsecErr(string(res) + "\n" + string(resErr))
}
return nil, err
}
return res, nil
}
func xmlsecErr(s string) error {
err := fmt.Errorf("xmlsec: %s", strings.TrimSpace(s))
if strings.HasPrefix(s, "OK") {
return nil
}
if strings.Contains(err.Error(), "signature failed") {
return err
}
if strings.Contains(err.Error(), "validity error") {
return ErrValidityError{err}
}
if strings.Contains(err.Error(), "msg=self signed certificate") {
return ErrSelfSignedCertificate{err}
}
if strings.Contains(err.Error(), "msg=unable to get local issuer certificate") {
return ErrUnknownIssuer{err}
}
return err
}
func isValidityError(output []byte) bool {
return bytes.Contains(output, []byte("validity error"))
}
func applyOptions(args *[]string, opts *ValidationOptions) {
if opts == nil {
return
}
if opts.DTDFile != "" {
*args = append(*args, "--dtd-file", opts.DTDFile)
}
if opts.EnableIDAttrHack {
*args = append(*args,
"--id-attr:ID", attrNameResponse,
"--id-attr:ID", attrNameAssertion,
"--id-attr:ID", attrNameAuthnRequest,
)
for _, v := range opts.IDAttrs {
*args = append(*args, "--id-attr:ID", v)
}
}
}
|
package textbox
import (
"sync"
)
type Dependencies struct {
sync.RWMutex
m map[*Box]map[*Box]struct{}
}
func NewDependencies() *Dependencies {
return &Dependencies{
m: make(map[*Box]map[*Box]struct{}),
}
}
func (d *Dependencies) Add(box, depend *Box) {
d.Lock()
defer d.Unlock()
m, ok := d.m[depend]
if !ok {
m = make(map[*Box]struct{})
d.m[depend] = m
}
m[box] = struct{}{}
}
func (d *Dependencies) Iter(from *Box, fn func(*Box)) {
d.RLock()
defer d.RUnlock()
itered := make(map[*Box]struct{})
d.iter(from, fn, itered)
}
func (d *Dependencies) iter(from *Box, fn func(*Box), itered map[*Box]struct{}) {
if _, ok := itered[from]; ok {
return
}
fn(from)
itered[from] = struct{}{}
for next := range d.m[from] {
d.iter(next, fn, itered)
}
}
|
/*
Intro
A friend posed this question today in a slightly different way - "Can a single [Python] command determine the largest of some integers AND that they aren't equal?".
While we didn't find a way to do this within reasonable definitions of "a single command", I thought it might be a fun problem to golf.
Challenge
"Return the largest of a list of integers if-and-only-if they are not all equal."
More specifically:
Given a string containing only a comma-separated list of integers:
If they are all equal, return/output nothing
Else, return/output the largest
Rules
The input must be a string containing only a comma-separated list of integers
The output must be either nothing (no output of any kind), or else the largest element from the input, represented as it is in the input
Entries may be a full program or just a function, provided you provide some way to test them!
Assumptions
Assume input list elements may be more than one digit but no larger than ( 232 − 1 )
Assume the input list has no more than a million elements
Assume the input will not include negative values
Assume the input will never be empty
For the avoidance of doubt, the explanation of the challenge given just after "More specifically" shall supersede the statement of the challenge above it ("Return the largest...").
Examples
(1) All equal:
Input: 1,1
Output:
(2) Dissimilar:
Input: 1,2
Output: 2
(3) Zero!:
Input: 0,0,0,0,0,0,0,1,0,0
Output: 1
(4) Random:
Input: 7,3,8,4,8,3,9,4,6,1,3,7,5
Output: 9
(5) Larger numbers, larger list:
Input: 627,3894,863,5195,7789,5269,8887,3262,1448,3192
Output: 8887
Additional examples:
(6) All equal, larger list:
Input: 7,7,7,7,7,7,7,7,7
Output:
(7) All equal, larger list, larger numbers:
Input: 61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976
Output:
(8) Not equal, larger list, larger numbers:
Input: 96185,482754,96185,96185,96185,96185,96185,96185,7,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,961185,96185,96185,96185
Output: 961185
Scoring
This is code-golf, so the code with the shortest number of bytes wins!
*/
package main
import "fmt"
func main() {
test([]int{1, 1}, false)
test([]int{1, 2}, 2)
test([]int{0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, 1)
test([]int{7, 3, 8, 4, 8, 3, 9, 4, 6, 1, 3, 7, 5}, 9)
test([]int{627, 3894, 863, 5195, 7789, 5269, 8887, 3262, 1448, 3192}, 8887)
test([]int{7, 7, 7, 7, 7, 7, 7, 7, 7}, false)
test([]int{61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976, 61976}, false)
test([]int{96185, 482754, 96185, 96185, 96185, 96185, 96185, 96185, 7, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 96185, 961185, 96185, 96185, 96185}, 961185)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(a []int, r any) {
v, ok := maxne(a)
fmt.Println(v, ok)
switch r := r.(type) {
case bool:
assert(ok == r)
case int:
assert(v == r)
}
}
func maxne(a []int) (int, bool) {
if len(a) == 0 {
return 0, false
}
m, c := a[0], 0
for _, v := range a[1:] {
if m < v {
m, c = v, 0
} else if m == v {
c++
}
}
return m, c == 0
}
|
package main
import (
"github.com/azer/logger"
"errors"
"time"
)
var log = logger.New("e-mail")
func main() {
log.Info("Sending an e-mail", logger.Attrs{
"from": "foo@bar.com",
"to": "qux@corge.com",
})
err := errors.New("Too busy")
log.Error("Failed to send e-mail. Error: %s", err, logger.Attrs{
"from": "foo@bar.com",
"to": "qux@corge.com",
})
timer := log.Timer()
time.Sleep(time.Millisecond * 500)
timer.End("Created a new %s image", "bike", logger.Attrs{
"id": 123456,
"model": "bmx",
"frame": "purple",
"year": 2014,
})
}
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"github.com/TheAndruu/git-leaderboard/models"
)
func main() {
repoStats := getRepoOriginsFromGit()
repoStats.Commits = getRepoCommits()
submitRepoStats(&repoStats)
// TODO: Show URL of the leaderboard UI
}
/** Queries git to determine the name and remote url of the repo */
func getRepoOriginsFromGit() models.RepoStats {
// could also use basename here, but fear it wouldn't be on everyone's machine
repoNameOut, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
if err != nil {
fmt.Fprintln(os.Stderr, "Please run this command from within an existing git repository")
fmt.Fprintln(os.Stderr, "And ensure you have git installed")
fmt.Fprintln(os.Stderr, "There was an error running the git command: ", err)
os.Exit(1)
}
// lob off everything up to and including the last slash
repoNameStr := strings.TrimSpace(string(repoNameOut))
var splitName []string
if runtime.GOOS == "windows" {
splitName = strings.Split(repoNameStr, "\\")
} else {
splitName = strings.Split(repoNameStr, "/")
}
repoNameStr = splitName[len(splitName)-1]
//Now get and supply repoUrl
repoURLOut, err := exec.Command("git", "remote", "get-url", "--push", "origin").Output()
if err != nil {
fmt.Fprintln(os.Stderr, "Please ensure the git repo has an upstream origin")
fmt.Fprintln(os.Stderr, "There was an issue getting the remote git URL: ", err)
os.Exit(2)
}
repoURLStr := strings.TrimSpace(string(repoURLOut))
stats := models.RepoStats{RepoName: repoNameStr, RepoURL: repoURLStr}
return stats
}
func getRepoCommits() []models.CommitCount {
cmdOut, err := exec.Command("git", "shortlog", "master", "--summary", "--numbered").Output()
if err != nil {
fmt.Fprintln(os.Stderr, "There was an error checking the commit stats: ", err)
os.Exit(3)
}
shortLogString := string(cmdOut)
fmt.Println(fmt.Sprintf("Stats from the git repo, nice job! \n%s", shortLogString))
var commitLines []string
if runtime.GOOS == "windows" {
commitLines = strings.Split(shortLogString, "\r\n")
} else {
commitLines = strings.Split(shortLogString, "\n")
}
var commitCounts []models.CommitCount
for _, element := range commitLines {
if len(element) < 1 {
// Any line without a report in it (separator, last line)
continue
}
commitLine := strings.Split(element, "\t")
author := strings.TrimSpace(commitLine[1])
numCommits, err := strconv.Atoi(strings.TrimSpace(commitLine[0]))
if err != nil {
fmt.Fprintln(os.Stderr, "Trouble parsing the number of commits for author: ", author, err)
os.Exit(4)
}
authorCommit := models.CommitCount{Author: author, NumCommits: numCommits}
commitCounts = append(commitCounts, authorCommit)
}
return commitCounts
}
func submitRepoStats(repoStats *models.RepoStats) {
fmt.Println("Submitting stats to leaderboard")
fmt.Println("Project name: " + repoStats.RepoName)
fmt.Println("Remote push origin: " + repoStats.RepoURL)
url := "https://backend-gl.appspot.com/repostats"
//url := "http://localhost:8080/repostats"
jsonValue, _ := json.Marshal(repoStats)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Trouble sending stats to the remote leaderboard ", err)
fmt.Fprintln(os.Stderr, "Perhaps there is an issue with the internet connection.")
fmt.Fprintln(os.Stderr, "")
os.Exit(5)
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var rehydrated map[string]string
err = json.Unmarshal(body, &rehydrated)
if err != nil {
fmt.Fprintln(os.Stderr, "Couldn't read the response from the server ", err)
os.Exit(6)
}
if resp.Status == "201 Created" {
fmt.Println("")
fmt.Println("Successfully submitted the git stats!")
fmt.Println(rehydrated["message"])
fmt.Println("Check out your standings at https://backend-gl.appspot.com")
fmt.Println("")
} else {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Trouble sending git stats to the leaderboard.")
fmt.Fprintln(os.Stderr, rehydrated["message"])
fmt.Fprintln(os.Stderr, "Response:", string(body))
fmt.Fprintln(os.Stderr, "")
os.Exit(7)
}
}
|
package main
import (
"container/list"
)
//拓扑排序判断是否有环,重点是建立图的邻接表,里面保存每个节点的入度
//首先将所有入度为0的节点放入队列,然后对该节点的邻接节点减1,如果减到0
//也放入队列,循环至队列为空,若所有节点都进入队列,则说明无环返回true
//否则即说明有些节点因为有环而无法放进队列,此时numCourses就不为0
func canFinish(numCourses int, prerequisites [][]int) bool {
type GraphNode struct {
val int //node的值
count int //入度
neighbors []int //邻接node
}
graph := make([]GraphNode, numCourses)
for i := 0; i < len(prerequisites); i++ {
first := prerequisites[i][0]
second := prerequisites[i][1]
graph[first].count++
graph[second].neighbors = append(graph[second].neighbors, first)
}
l := list.New()
for i := 0; i < numCourses; i++ {
if graph[i].count == 0 {
l.PushBack(graph[i])
}
}
for l.Len() != 0 {
top := l.Front().Value.(GraphNode)
l.Remove(l.Front())
numCourses--
node := top.neighbors
for _, v := range node {
graph[v].count--
if graph[v].count == 0 {
l.PushBack(graph[v])
}
}
}
if numCourses == 0 {
return true
}
return false
}
|
package common
import (
"net"
)
var (
SendAmount = "SEND AMOUNT"
GetBalance = "BALANCE"
SendMessage = "SEND MESSAGE"
// Transaction status
TxnIncorrect = "INCORRECT"
TxnSuccess = "SUCCESS"
)
var ClientPortMap = map[int]int{
1: 8000,
2: 8001,
3: 8002,
}
type Block struct {
EventSourceId int `json:"event_source_id"`
FromId int `json:"from_id"`
ToId int `json:"to_id"`
Amount float64 `json:"amount"`
Message string `json:"message,omitempty"`
Clock *LamportClock `json:"clock"`
TxnType string `json:"txn_type"`
}
type Peer struct {
ClientId int
Conn net.Conn
}
type ClientMessage struct {
FromId int `json:"from_id"`
ToId int `json:"to_id"`
Log []*Block `json:"log"`
Message string `json:"message"`
Clock *LamportClock `json:"clock"`
TwoDTT [][]int `json:"time_table"`
}
type LogMessage struct {
}
type Log struct {
LogList []*LogMessage
}
type Txn struct {
FromClient int `json:"from_client"`
ToClient int `json:"to_client"`
Type string `json:"txn_type"`
Amount float64 `json:"amount,omitempty"`
BalanceOf int `json:"balance_of,omitempty"`
Message string `json:"message,omitempty"`
Clock *LamportClock `json:"clock"`
}
type LamportClock struct {
PID int `json:"pid"`
Clock int `json:"clock"`
}
|
package states
import (
"context"
b64 "encoding/base64"
"encoding/json"
"errors"
"fmt"
derrors "github.com/direktiv/direktiv/pkg/flow/errors"
"github.com/direktiv/direktiv/pkg/model"
"github.com/direktiv/direktiv/pkg/util"
)
func init() {
RegisterState(model.StateTypeSetter, Setter)
}
type setterLogic struct {
*model.SetterState
Instance
}
func Setter(instance Instance, state model.State) (Logic, error) {
setter, ok := state.(*model.SetterState)
if !ok {
return nil, derrors.NewInternalError(errors.New("bad state object"))
}
sl := new(setterLogic)
sl.Instance = instance
sl.SetterState = setter
return sl, nil
}
func (logic *setterLogic) Run(ctx context.Context, wakedata []byte) (*Transition, error) {
err := scheduleOnce(logic, wakedata)
if err != nil {
return nil, err
}
setters := make([]VariableSetter, 0)
for idx, v := range logic.Variables {
var x interface{}
key := ""
mimeType := ""
x, err = jqOne(logic.GetInstanceData(), v.Key)
if err != nil {
return nil, err
}
if x != nil {
if str, ok := x.(string); ok {
key = str
}
}
if key == "" {
return nil, derrors.NewCatchableError(ErrCodeJQNotString, "failed to evaluate key as a string for variable at index [%v]", idx)
}
if ok := util.MatchesVarRegex(key); !ok {
return nil, derrors.NewCatchableError(ErrCodeInvalidVariableKey, "variable key must match regex: %s (got: %s)", util.RegexPattern, key)
}
if v.MimeType != nil {
x, err = jqOne(logic.GetInstanceData(), v.MimeType)
if err != nil {
return nil, err
}
if x != nil {
if str, ok := x.(string); ok {
mimeType = str
}
}
}
x, err = jqOne(logic.GetInstanceData(), v.Value)
if err != nil {
return nil, err
}
var data []byte
if encodedData, ok := x.(string); ok && v.MimeType == "application/octet-stream" {
decodedData, decodeErr := b64.StdEncoding.DecodeString(encodedData)
if decodeErr != nil {
return nil, derrors.NewInternalError(fmt.Errorf("could not decode variable '%s' base64 string %w", v.Key, err))
}
data = decodedData
} else if v.MimeType == "text/plain; charset=utf-8" || v.MimeType == "text/plain" {
data = []byte(fmt.Sprint(x))
} else {
data, err = json.Marshal(x)
if err != nil {
return nil, derrors.NewInternalError(err)
}
}
setters = append(setters, VariableSetter{
Scope: v.Scope,
Key: key,
MIMEType: mimeType,
Data: data,
})
}
err = logic.SetVariables(ctx, setters)
if err != nil {
return nil, err
}
return &Transition{
Transform: logic.Transform,
NextState: logic.Transition,
}, nil
}
|
package shared
import "math/big"
type DoormanUpdater struct {
Id string `json:"id"`
Timestamp int64 `json:"timestamp"`
Probabilities []*big.Rat `json:"probabilities"`
}
type UpdateHandlerFunc func(m *DoormanUpdater) error
|
// Copyright 2020. Akamai Technologies, Inc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"encoding/json"
"fmt"
"net"
"net/url"
"os"
"github.com/spf13/cobra"
)
var headersFlag []string
var edgeIPflag string
// debugUrlCmd represents the debugUrl command
var debugUrlCmd = &cobra.Command{
Use: debugUrlUse,
Aliases: []string{"debugUrl", "debugurl"},
Args: cobra.ExactArgs(1),
Short: debugUrlShortDescription,
Long: debugUrlLongDescription,
Run: func(cmd *cobra.Command, args []string) {
Url, _ := url.Parse("/diagnostic-tools/v2/url-debug")
parameters := url.Values{}
if !checkAbsoluteURL(args[0]) {
printWarning("URL is invalid, e.g., http://www.example.com")
os.Exit(1)
}
parameters.Add("url", args[0])
for _, hv := range headersFlag {
parameters.Add("header", hv)
}
if edgeIPflag != "" {
if ip := net.ParseIP(edgeIPflag); ip == nil {
printWarning("Edge IP address is invalid")
os.Exit(1)
}
parameters.Add("edgeIp", edgeIPflag)
}
parameters.Add(clientTypeKey, clientTypeValue)
Url.RawQuery = parameters.Encode()
resp, byt := doHTTPRequest("GET", Url.String(), nil)
if resp.StatusCode == 200 {
var responseStruct Wrapper
var responseStructJson DebugUrlJson
err := json.Unmarshal(*byt, &responseStruct)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if jsonString {
responseStructJson.Url = args[0]
responseStructJson.EdgeIP = edgeIPflag
responseStructJson.Headers = headersFlag
responseStructJson.ReportedTime = getReportedTime()
responseStructJson.DebugUrl = responseStruct.URLDebug
resJson, _ := json.MarshalIndent(responseStructJson, "", " ")
resJson = getDecodedResponse(resJson)
fmt.Println(string(resJson))
return
}
printDebugUrlResults(responseStruct.URLDebug)
} else {
printResponseError(byt)
}
},
}
func init() {
debugUrlCmd.Flags().StringSliceVar(&headersFlag, "header", []string{}, headerFlagDescription)
debugUrlCmd.Flags().StringVar(&edgeIPflag, "edge-ip", "", edgeIpFlagDescription)
rootCmd.AddCommand(debugUrlCmd)
}
|
package cfg
// RemoteVPS contains parameters for the VPS
type RemoteVPS struct {
Name string `toml:"name"`
IP string `toml:"IP"`
User string `toml:"user"`
PEM string `toml:"pemfile"`
Branch string `toml:"branch"`
SSHPort string `toml:"ssh_port"`
Daemon *DaemonConfig `toml:"daemon"`
}
// DaemonConfig contains parameters for the Daemon
type DaemonConfig struct {
Port string `toml:"port"`
Token string `toml:"token"`
WebHookSecret string `toml:"webhook_secret"`
}
// GetHost creates the user@IP string.
func (remote *RemoteVPS) GetHost() string {
return remote.User + "@" + remote.IP
}
// GetIPAndPort creates the IP:Port string.
func (remote *RemoteVPS) GetIPAndPort() string {
return remote.IP + ":" + remote.Daemon.Port
}
|
package types
import "strings"
// SurveyAnswer holds survey answer.
type SurveyAnswer struct {
Device string `survey:"mfa-device"`
Code string `survey:"mfa-code"`
}
// CleanAnswers cleans answers.
func (s *SurveyAnswer) CleanAnswers() {
if strings.Contains(s.Device, ": ") {
s.Device = strings.Split(s.Device, ": ")[1]
}
}
|
package service
import (
"context"
"os/exec"
"path"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/epyphite/html2pdf/pkg/models"
)
//HTML2PDF Main service structure
type HTML2PDF struct {
Config models.Config
}
//Setup Will setup basic directories
func (H2 *HTML2PDF) Setup(config models.Config) {
H2.Config = config
_, err := os.Stat(H2.Config.DestinationFolder)
if err != nil {
os.IsNotExist(err)
}
err = os.Mkdir(H2.Config.DestinationFolder, 0770)
if err != nil {
log.Println(err)
}
}
//GetURLFromFile Will get url from the specified format file
func (H2 *HTML2PDF) GetURLFromFile() ([]string, error) {
var returnURLs []string
var err error
if H2.Config.SourceType == "XLS" {
f, err := excelize.OpenFile(H2.Config.SourceFolder + H2.Config.SourceName)
if err != nil {
fmt.Println(err)
return returnURLs, err
}
// Get value from cell by given worksheet name and axis.
rows, err := f.GetRows(H2.Config.TabName)
for _, row := range rows {
for i, colCell := range row {
col, err := strconv.Atoi(H2.Config.ColumnNumber)
if err != nil {
log.Println(err)
}
if i == col {
returnURLs = append(returnURLs, colCell)
}
}
}
}
return returnURLs, err
}
//GetURL gets the desire url and converts it into a PDF saving it to the destination folder
func (H2 *HTML2PDF) GetURL(url string) {
fmt.Println("Getting URL ", url)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
fname := H2.Config.DestinationFolder + "/" + path.Base(url) + ".pdf"
cmd := exec.CommandContext(
ctx,
"latest/chrome",
"--disable-gpu",
"--headless",
fmt.Sprintf("--print-to-pdf=%s", fname),
fmt.Sprintf(
"%s", url),
)
err := cmd.Run()
if err != nil {
log.Println(err)
}
}
|
package gsettings_test
import (
"testing"
gsettings "github.com/9glt/go-gsettings"
)
func TestExternal(t *testing.T) {
gsettings.Reset()
value, err := gsettings.Get("key")
if err == nil {
t.Fatal()
}
if value != "" {
t.Fatal()
}
gsettings.Set("key", "value")
value, err = gsettings.Get("key")
if err != nil {
t.Fatal()
}
if value != "value" {
t.Fatal()
}
}
|
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/ONSdigital/florence/config"
"github.com/ONSdigital/florence/service"
"github.com/ONSdigital/log.go/log"
"github.com/pkg/errors"
)
const serviceName = "florence"
var (
// BuildTime represents the time in which the service was built
BuildTime string
// GitCommit represents the commit (SHA-1) hash of the service that is running
GitCommit string
// Version represents the version of the service that is running
Version string
)
func main() {
log.Namespace = serviceName
ctx := context.Background()
if err := run(ctx); err != nil {
log.Event(ctx, "fatal runtime error", log.Error(err), log.FATAL)
os.Exit(1)
}
}
func run(ctx context.Context) error {
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
// Create service initialiser and an error channel for fatal errors
svcErrors := make(chan error, 1)
svcList := service.NewServiceList(&service.Init{})
log.Event(ctx, "florence version", log.INFO, log.Data{"version": Version})
// Read config
cfg, err := config.Get()
if err != nil {
log.Event(ctx, "error getting configuration", log.FATAL, log.Error(err))
os.Exit(1)
}
log.Event(ctx, "got service configuration", log.INFO, log.Data{"config": cfg})
// Start service
svc, err := service.Run(ctx, cfg, svcList, BuildTime, GitCommit, Version, svcErrors)
if err != nil {
return errors.Wrap(err, "running service failed")
}
// blocks until an os interrupt or a fatal error occurs
select {
case err := <-svcErrors:
log.Event(ctx, "service error received", log.ERROR, log.Error(err))
case sig := <-signals:
log.Event(ctx, "os signal received", log.Data{"signal": sig}, log.INFO)
}
return svc.Close(ctx)
}
|
package gosdk
import (
"github.com/dgrijalva/jwt-go"
"net/http"
)
type server struct {
token *jwt.Token
tokenExist bool
}
var serverInstance = &server{tokenExist: false}
var tokenData map[string]interface{}
func GetServerInstance(header http.Header) *server {
token1 := GetBearerToken(header)
if token1 != "" {
serverInstance.token, _ = jwt.Parse(token1, func(token *jwt.Token) (i interface{}, e error) {
return token, nil
})
if _, ok := serverInstance.token.Claims.(jwt.MapClaims); ok {
serverInstance.tokenExist = true
}
}
return serverInstance
}
func (server *server) GetTokenData() map[string]interface{} {
if server.token != nil {
return nil
}
if tokenData == nil {
tokenData = make(map[string]interface{})
claims, err := server.token.Claims.(jwt.MapClaims)
if err {
for key, value := range claims {
tokenData[key] = value
}
}
}
return tokenData
}
func (server *server) GetAppkey() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[TO_APPKEY_KEY].(string)
}
return ""
}
func (server *server) GetChannel() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[TO_CHANNEL].(string)
}
return ""
}
func (server *server) GetAccountId() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[ACCOUNT_ID_KEY].(string)
}
return ""
}
func (server *server) GetSubOrgKey() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[SUB_ORG_KEY_KEY].(string)
}
return ""
}
func (server *server) GetUserInfo() map[string]string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[USER_INFO_KEY].(map[string]string)
}
return nil
}
func (server *server) GetFromAppkey() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[FROM_APPKEY_KEY].(string)
}
return ""
}
func (server *server) GetFromChannel() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[FROM_CHANNEL_KEY].(string)
}
return ""
}
func (server *server) GetFromAppid() string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[FROM_APPID_KEY].(string)
}
return ""
}
func (server *server) GetCallStack() []map[string]string {
if server.token != nil {
return server.token.Claims.(jwt.MapClaims)[CALL_STACK_KEY].([]map[string]string)
}
return nil
}
|
package common
const (
letterA = 65
letterZ = 90
lettera = 97
letterz = 122
)
// Cleaner is an interface to clean objects
type Cleaner interface {
Clean(a string) string
}
// NewWordCleaner returns new WordCleaner instance
func NewWordCleaner() *WordCleaner {
return &WordCleaner{}
}
// WordCleaner implements Cleaner interface to clean words
type WordCleaner struct{}
// Clean keeps only lowercase a->z and uppercase A->Z
func (wc *WordCleaner) Clean(word string) string {
oldWord := []rune(word)
newWord := make([]rune, 0)
for _, letter := range oldWord {
if letter >= letterA && letter <= letterZ {
newWord = append(newWord, letter+32)
} else if letter >= lettera && letter <= letterz {
newWord = append(newWord, letter)
}
}
return string(newWord)
}
|
package devices
import (
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/cheynewallace/tabby"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/foundriesio/fioctl/client"
"github.com/foundriesio/fioctl/subcommands"
)
var (
deviceNoShared bool
deviceByTag string
deviceByFactory string
deviceByGroup string
deviceInactiveHours int
deviceUuid string
showColumns []string
showPage int
paginationLimit int
paginationLimits []int
)
type column struct {
Formatter func(d *client.Device) string
}
func statusFormatter(d *client.Device) string {
status := "OK"
if len(d.Status) > 0 {
status = d.Status
}
if len(d.LastSeen) > 0 && !d.Online(deviceInactiveHours) {
status = "OFFLINE"
}
return status
}
var ownerCache = make(map[string]string)
func ownerFormatter(d *client.Device) string {
name, ok := ownerCache[d.Owner]
if ok {
return name
}
logrus.Debugf("Looking up user %s in factory %s", d.Owner, d.Factory)
users, err := api.UsersList(d.Factory)
if err != nil {
logrus.Errorf("Unable to look up users: %s", err)
return "???"
}
id := "<not in factory: " + d.Factory + ">"
for _, user := range users {
ownerCache[user.PolisId] = user.Name
if user.PolisId == d.Owner {
id = user.Name
}
}
return id
}
var Columns = map[string]column{
"name": {func(d *client.Device) string { return d.Name }},
"uuid": {func(d *client.Device) string { return d.Uuid }},
"factory": {func(d *client.Device) string { return d.Factory }},
"owner": {ownerFormatter},
"device-group": {func(d *client.Device) string { return d.GroupName }},
"target": {func(d *client.Device) string { return d.TargetName }},
"status": {statusFormatter},
"apps": {func(d *client.Device) string { return strings.Join(d.DockerApps, ",") }},
"up-to-date": {func(d *client.Device) string { return fmt.Sprintf("%v", d.UpToDate) }},
"tag": {func(d *client.Device) string { return d.Tag }},
"created-at": {func(d *client.Device) string { return d.CreatedAt }},
"last-seen": {func(d *client.Device) string { return d.LastSeen }},
"ostree-hash": {func(d *client.Device) string { return d.OstreeHash }},
"curent-update": {func(d *client.Device) string { return d.CurrentUpdate }},
"is-prod": {func(d *client.Device) string { return fmt.Sprintf("%v", d.IsProd) }},
"is-wave": {func(d *client.Device) string { return fmt.Sprintf("%v", d.IsWave) }},
}
func init() {
var defCols = []string{
"name", "factory", "target", "status", "apps", "up-to-date", "is-prod",
}
paginationLimits = []int{10, 20, 30, 40, 50, 100, 200, 500, 1000}
limitsStr := ""
for i, limit := range paginationLimits {
if i > 0 {
limitsStr += ","
}
limitsStr += strconv.Itoa(limit)
}
allCols := make([]string, 0, len(Columns))
for k := range Columns {
allCols = append(allCols, k)
}
sort.Strings(allCols)
listCmd := &cobra.Command{
Use: "list [pattern]",
Short: "List devices registered to factories. Optionally include filepath style patterns to limit to device names. eg device-*",
Run: doList,
Args: cobra.MaximumNArgs(1),
Long: "Available columns for display:\n\n * " + strings.Join(allCols, "\n * "),
}
cmd.AddCommand(listCmd)
listCmd.Flags().BoolVarP(&deviceNoShared, "just-mine", "", false, "Only include devices owned by you")
listCmd.Flags().StringVarP(&deviceByTag, "by-tag", "", "", "Only list devices configured with the given tag")
listCmd.Flags().StringVarP(&deviceByFactory, "by-factory", "f", "", "Only list devices belonging to this factory")
listCmd.Flags().StringVarP(&deviceByGroup, "by-group", "g", "", "Only list devices belonging to this group (factory is mandatory)")
listCmd.Flags().IntVarP(&deviceInactiveHours, "offline-threshold", "", 4, "List the device as 'OFFLINE' if not seen in the last X hours")
listCmd.Flags().StringVarP(&deviceUuid, "uuid", "", "", "Find device with the given UUID")
listCmd.Flags().StringSliceVarP(&showColumns, "columns", "", defCols, "Specify which columns to display")
listCmd.Flags().IntVarP(&showPage, "page", "p", 1, "Page of devices to display when pagination is needed")
listCmd.Flags().IntVarP(&paginationLimit, "limit", "n", 500, "Number of devices to paginate by. Allowed values: "+limitsStr)
}
// We allow pattern matching using filepath.Match type * and ?
// ie * matches everything and ? matches a single character.
// In sql we need * and ? to maps to % and _ respectively
// Since _ is a special character we need to escape that. And
//
// Soo... a pattern like: H?st_b* would become: H_st\_b%
// and would match stuff like host_b and hast_FOOO
func sqlLikeIfy(filePathLike string) string {
// %25 = urlencode("%")
sql := strings.Replace(filePathLike, "*", "%25", -1)
sql = strings.Replace(sql, "_", "\\_", -1)
sql = strings.Replace(sql, "?", "_", -1)
logrus.Debugf("Converted query(%s) -> %s", filePathLike, sql)
return sql
}
func assertPagination() {
// hack until: https://github.com/spf13/pflag/issues/236
for _, x := range paginationLimits {
if x == paginationLimit {
return
}
}
subcommands.DieNotNil(fmt.Errorf("Invalid limit: %d", paginationLimit))
}
func doList(cmd *cobra.Command, args []string) {
logrus.Debug("Listing registered devices")
assertPagination()
t := tabby.New()
var cols = make([]interface{}, len(showColumns))
for idx, c := range showColumns {
if _, ok := Columns[c]; !ok {
fmt.Println("ERROR: Invalid column name:", c)
os.Exit(1)
}
cols[idx] = strings.ToUpper(c)
}
t.AddHeader(cols...)
name_ilike := ""
if len(args) == 1 {
name_ilike = sqlLikeIfy(args[0])
}
if len(deviceByFactory) > 0 {
deviceNoShared = true
} else if len(deviceByGroup) > 0 {
deviceByFactory = viper.GetString("factory")
if len(deviceByFactory) == 0 {
subcommands.DieNotNil(fmt.Errorf("A factory is mandatory to filter by group"))
}
}
dl, err := api.DeviceList(!deviceNoShared, deviceByTag, deviceByFactory, deviceByGroup, name_ilike, deviceUuid, showPage, paginationLimit)
subcommands.DieNotNil(err)
row := make([]interface{}, len(showColumns))
for _, device := range dl.Devices {
if len(device.TargetName) == 0 {
device.TargetName = "???"
}
for idx, col := range showColumns {
col := Columns[col]
row[idx] = col.Formatter(&device)
}
t.AddLine(row...)
}
t.Print()
if dl.Next != nil {
fmt.Print("\nNext page of devices can be viewed with: ")
found := false
for i := 0; i < len(os.Args); i++ {
arg := os.Args[i]
if len(arg) > 2 && arg[:2] == "-p" {
fmt.Printf("-p%d ", showPage+1)
found = true
} else if len(arg) == 6 && arg[:6] == "--page" {
fmt.Printf("-p%d ", showPage+1)
found = true
i++
} else {
fmt.Print(os.Args[i], " ")
}
}
if !found {
fmt.Print("-p", showPage+1)
}
fmt.Println()
}
}
|
package object
import (
"strconv"
"testing"
)
func TestStringMapKey(t *testing.T) {
testCases := []struct {
val1 Mappable
val2 Mappable
diff1 Mappable
diff2 Mappable
}{
{
val1: &String{Value: "Hello World"},
val2: &String{Value: "Hello World"},
diff1: &String{Value: "My name is johnny"},
diff2: &String{Value: "My name is johnny"},
},
{
val1: &Integer{Value: 1},
val2: &Integer{Value: 1},
diff1: &Integer{Value: 10},
diff2: &Integer{Value: 10},
},
{
val1: &Boolean{Value: true},
val2: &Boolean{Value: true},
diff1: &Boolean{Value: false},
diff2: &Boolean{Value: false},
},
}
for i, tc := range testCases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
if tc.val1.MapKey() != tc.val2.MapKey() {
t.Errorf("Case %d: Variables with same content have different hash keys", i)
}
if tc.diff1.MapKey() != tc.diff2.MapKey() {
t.Errorf("Case %d: Variables with same content have different hash keys", i)
}
if tc.val1.MapKey() == tc.diff1.MapKey() {
t.Errorf("Case %d: Variables with different content have same hash keys", i)
}
})
}
}
|
package main
import (
"fmt"
"math"
)
// https://leetcode-cn.com/problems/string-to-integer-atoi/
func myAtoi(s string) int {
N, i := len(s), 0
if N == 0 {
return 0
}
for ; i < N && s[i] == ' '; i++ {
}
if i >= N || s[i] != '-' && s[i] != '+' && (s[i] < '0' || s[i] > '9') {
return 0
}
res, sign := int64(0), int64(1)
if s[i] == '-' || s[i] == '+' {
if s[i] == '-' {
sign = -1
}
i++
}
if i >= N || s[i] < '0' || s[i] > '9' {
return 0
}
for ; i < N && s[i] <= '9' && s[i] >= '0'; i++ {
res = res*10 + int64(s[i]-'0')
if sign*res > math.MaxInt32 {
return math.MaxInt32
}
if sign*res < math.MinInt32 {
return math.MinInt32
}
}
return int(res * sign)
}
func main() {
cases := []string{
"42",
}
realCase := cases[0:]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(myAtoi(c))
}
}
|
package config
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMetricsManager(t *testing.T) {
ctx := context.Background()
src := NewStaticSource(&Config{
Options: &Options{
MetricsAddr: "ADDRESS",
},
})
mgr := NewMetricsManager(ctx, src)
srv1 := httptest.NewServer(mgr)
defer srv1.Close()
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "ERROR", http.StatusInternalServerError)
}))
defer srv2.Close()
getStatusCode := func(addr string) int {
res, err := http.Get(fmt.Sprintf("%s/metrics", addr))
require.NoError(t, err)
return res.StatusCode
}
assert.Equal(t, 200, getStatusCode(srv1.URL))
assert.Equal(t, 500, getStatusCode(srv2.URL))
}
func TestMetricsManagerBasicAuth(t *testing.T) {
src := NewStaticSource(&Config{
Options: &Options{
MetricsAddr: "ADDRESS",
MetricsBasicAuth: base64.StdEncoding.EncodeToString([]byte("x:y")),
},
})
mgr := NewMetricsManager(context.Background(), src)
srv1 := httptest.NewServer(mgr)
defer srv1.Close()
res, err := http.Get(fmt.Sprintf("%s/metrics", srv1.URL))
assert.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/metrics", srv1.URL), nil)
require.NoError(t, err)
req.SetBasicAuth("x", "y")
res, err = http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
}
|
package main
import (
"time"
)
func init() {}
type Configuration struct {
Database struct {
Server string `json:"server"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
Database string `json:"database"`
} `json:"database"`
Port int `json:"port"`
Log string `json:"log"`
}
type ResponseConsent struct {
Consent Consent `json:"consent"`
Customer Customer `json:"customer"`
}
type RequestCustomer struct {
Siret string `json:"siret"`
}
type Stock struct {
Reference string `json:reference`
Designation string `json:designation`
Famille string `json:famille`
Gencod string `json:gencod`
Quantite float64 `json:quantite`
}
type YTMPBPC struct {
YLIN_0 string `json:"YLIN_0"`
BCGCOD_0 string `json:"BCGCOD_0"`
BPCNUM_0 string `json:"BPCNUM_0"`
BPCSTA_0 string `json:"BPCSTA_0"`
BPRNAM_0 string `json:"BPRNAM_0"`
BPRNAM_1 string `json:"BPRNAM_1"`
BPRSHO_0 string `json:"BPRSHO_0"`
BPRLOG_0 string `json:"BPRLOG_0"`
CRN_0 string `json:"CRN_0"`
NAF_0 string `json:"NAF_0"`
CRY_0 string `json:"CRY_0"`
CUR_0 string `json:"CUR_0"`
VACBPR_0 string `json:"VACBPR_0"`
PTE_0 string `json:"PTE_0"`
ACCCOD_0 string `json:"ACCCOD_0 "`
TSCCOD_0 string `json:"TSCCOD_0"`
TSCCOD_1 string `json:"TSCCOD_1"`
OSTAUZ_0 string `json:"OSTAUZ_0"`
REP_0 string `json:"REP_0"`
REP_1 string `json:"REP_1"`
YBCG_COMPT_0 string `json:"YBCG_COMPT_0"`
YBPC_RECOUVR_0 string `json:"YBPC_RECOUVR_0"`
YCATCPT_0 string `json:"YCATCPT_0"`
YSCATCPT_0 string `json:"YSCATCPT_0"`
BPAADD_0 string `json:"BPAADD_0"`
BPADES_0 string `json:"BPADES_0"`
BPAADDLIG_0 string `json:"BPAADDLIG_0"`
BPAADDLIG_1 string `json:"BPAADDLIG_1"`
BPAADDLIG_2 string `json:"BPAADDLIG_2"`
POSCOD_0 string `json:"POSCOD_0"`
CTY_0 string `json:"CTY_0"`
BCRY_0 string `json:"BCRY_0"`
TEL_0 string `json:"TEL_0"`
TEL_1 string `json:"TEL_1 "`
WEB_0 string `json:"WEB_0"`
}
type Customer struct {
Reference string `json:"Reference"`
Name string `json:"Name"`
Raison string `json:"-"`
Sigle string `json:"-"`
Identity string `json:"Identity"`
Street string `json:"Street"`
Address string `json:"Address"`
Postcod string `json:"Postcod"`
Town string `json:"Town"`
Country string `json:"Country"`
Phone string `json:"Phone"`
Email string `json:"Email"`
}
type CustomerConsent struct {
Customer Customer `json:"customer"`
Siret string `json:"Siret"`
UsingGeneralConditions bool `json:"UsingGeneralConditions"`
Newsletters bool `json:"Newsletters"`
CommercialOffersByMail bool `json:"CommercialOffersByMail"`
CommercialOffersBySms bool `json:"CommercialOffersBySms"`
CommercialOffersByPost bool `json:"CommercialOffersByPost"`
Signature string `json:"Signature"`
CreatedAt time.Time `json:"CreatedAt"`
}
func (c *CustomerConsent) CreatedCustomer() bool {
if len(c.Customer.Name) > 0 {
return true
} else {
return false
}
}
type Consent struct {
Siret string `json:"Siret"`
UsingGeneralConditions bool `json:"UsingGeneralConditions"`
Newsletters bool `json:"Newsletters"`
CommercialOffersByMail bool `json:"CommercialOffersByMail"`
CommercialOffersBySms bool `json:"CommercialOffersBySms"`
CommercialOffersByPost bool `json:"CommercialOffersByPost"`
Signature string `json:"Signature"`
//CreatedAt time.Time `json:"CreatedAt"`
}
|
package main
import (
"reflect"
"testing"
)
var die = Die{0}
func TestRollDie(t *testing.T) {
die.rollDie()
firstRoll := die.getValue()
die.rollDie()
secondRoll := die.getValue()
if firstRoll == secondRoll {
t.Error("roll die function should not give you the same values ")
}
}
func TestDisplay(t *testing.T) {
die.display()
}
func TestGetValue(t *testing.T) {
die.rollDie()
value := die.getValue()
if reflect.TypeOf(value).String() != "int" {
t.Error("getValue() result should be type of int ")
}
}
|
package main
import "fmt"
func main() {
foo()
defer foo1()
foo2()
}
func foo() {
fmt.Println("Hello1")
}
func foo1() {
fmt.Println("Hello2")
}
func foo2() {
fmt.Println("Hello3")
}
|
package main
import (
"net"
"bufio"
"fmt"
"strconv"
)
//Constants
const PORT = 8080
// define new structure corresponding to each session
type session struct {
// Registered connections.
connections [] net.Conn
// Corresponding names of registered connections
names [] string
}
// define new structure corresponding to each session
type server struct {
currentSession session
}
//global variables
var newSession session
func main() {
server, _ := net.Listen("tcp", ":" + strconv.Itoa(PORT))
if server == nil {
panic("couldn't start listening....")
}
newSession = session {
connections: []net.Conn{},
names : []string{},
}
conns := clientConns(server)
for {
go handleConnection(<-conns)
}
}
/*
* This function is called by the main
* The function listen for client connections, accept them
*/
func clientConns(listener net.Listener) chan net.Conn {
channel := make(chan net.Conn)
go func() {
for {
client, _ := listener.Accept()
if client == nil {
fmt.Printf("couldn't accept client connection")
continue
}
channel <- client
}
}()
return channel
}
/*
* This function is called by the main to handle the chat functionality of new connection
* The function reads the user name and saves it, then waits for user messages and broadcast them
*/
func handleConnection(client net.Conn) {
reader := bufio.NewReader(client)
//receive the user name
buff := make([]byte, 512)
clientNameb, _ := client.Read(buff)
clientName := string(buff[0:clientNameb])
newSession.names = append(newSession.names, clientName)
newSession.connections = append(newSession.connections, client)
for {
//receive the user message
line, err := reader.ReadBytes('\n')
if err != nil {
break
}
//broadcast client message
message := clientName + ":" + string(line)
for _, currentClient := range newSession.connections {
if(currentClient != nil) {
currentClient.Write([]byte(message))
}
}
}
}
|
package testutils
import (
"context"
"testing"
"github.com/multiformats/go-multiaddr"
)
func Test_NewPrivateKey(t *testing.T) {
if pk := NewPrivateKey(t); pk == nil {
t.Fatal("should not be nil")
}
}
func Test_NewSecret(t *testing.T) {
if secret := NewSecret(t); secret == nil {
t.Fatal("should not be nil")
}
}
func Test_NewPeerstore(t *testing.T) {
if peerstore := NewPeerstore(t); peerstore == nil {
t.Fatal("should not be nil")
}
}
func Test_NewDatastore(t *testing.T) {
if datastore := NewDatastore(t); datastore == nil {
t.Fatal("should not be nil")
}
}
func Test_NewMultiaddr(t *testing.T) {
if addr := NewMultiaddr(t); addr == nil {
t.Fatal("should not be nil")
}
}
func Test_NewKeystore(t *testing.T) {
if keystore := NewKeystore(t); keystore == nil {
t.Fatal("should not be nil")
}
}
func Test_NewLibp2pHostAndDHT(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
logger := NewLogger(t)
ds := NewDatastore(t)
ps := NewPeerstore(t)
pk := NewPrivateKey(t)
addrs := []multiaddr.Multiaddr{NewMultiaddr(t)}
host, dht := NewLibp2pHostAndDHT(
ctx, t, logger.Desugar(), ds, ps, pk, addrs, NewSecret(t),
)
dht.Close()
host.Close()
}
|
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package dochandler performs document operation processing and document resolution.
//
// During operation processing it will use configured validator to validate document operation and then it will call
// batch writer to add it to the batch.
//
// Document resolution is based on ID or encoded original document.
// 1) ID - the latest document will be returned if found.
//
// 2) Encoded original document - The encoded document is hashed using the current supported hashing algorithm to
// compute ID, after which the resolution is done against the computed ID. If a document cannot be found,
// the supplied document is used directly to generate and return a resolved document. In this case the supplied document
// is subject to the same validation as an original document in a create operation.
package dochandler
import (
"errors"
"fmt"
"strings"
"github.com/trustbloc/edge-core/pkg/log"
"github.com/trustbloc/sidetree-core-go/pkg/api/operation"
"github.com/trustbloc/sidetree-core-go/pkg/api/protocol"
"github.com/trustbloc/sidetree-core-go/pkg/canonicalizer"
"github.com/trustbloc/sidetree-core-go/pkg/document"
"github.com/trustbloc/sidetree-core-go/pkg/docutil"
)
var logger = log.New("sidetree-core-dochandler")
const (
keyID = "id"
badRequest = "bad request"
)
// DocumentHandler implements document handler.
type DocumentHandler struct {
protocol protocol.Client
processor OperationProcessor
writer BatchWriter
transformer DocumentTransformer
namespace string
aliases []string // namespace aliases
}
// OperationProcessor is an interface which resolves the document based on the ID.
type OperationProcessor interface {
Resolve(uniqueSuffix string) (*document.ResolutionResult, error)
}
// BatchWriter is an interface to add an operation to the batch.
type BatchWriter interface {
Add(operation *operation.QueuedOperation, protocolGenesisTime uint64) error
}
// DocumentTransformer transforms a document from internal to external form.
type DocumentTransformer interface {
TransformDocument(doc document.Document) (*document.ResolutionResult, error)
}
// New creates a new requestHandler with the context.
func New(namespace string, aliases []string, pc protocol.Client, transformer DocumentTransformer, writer BatchWriter, processor OperationProcessor) *DocumentHandler {
return &DocumentHandler{
protocol: pc,
processor: processor,
writer: writer,
transformer: transformer,
namespace: namespace,
aliases: aliases,
}
}
// Namespace returns the namespace of the document handler.
func (r *DocumentHandler) Namespace() string {
return r.namespace
}
// ProcessOperation validates operation and adds it to the batch.
func (r *DocumentHandler) ProcessOperation(operationBuffer []byte, protocolGenesisTime uint64) (*document.ResolutionResult, error) {
pv, err := r.protocol.Get(protocolGenesisTime)
if err != nil {
return nil, err
}
op, err := pv.OperationParser().Parse(r.namespace, operationBuffer)
if err != nil {
return nil, fmt.Errorf("%s: %s", badRequest, err.Error())
}
// perform validation for operation request
if err := r.validateOperation(op, pv); err != nil {
logger.Warnf("Failed to validate operation: %s", err.Error())
return nil, err
}
// validated operation will be added to the batch
if err := r.addToBatch(op, pv.Protocol().GenesisTime); err != nil {
logger.Errorf("Failed to add operation to batch: %s", err.Error())
return nil, err
}
logger.Infof("[%s] operation added to the batch", op.ID)
// create operation will also return document
if op.Type == operation.TypeCreate {
return r.getCreateResponse(op, pv)
}
return nil, nil
}
func (r *DocumentHandler) getCreateResult(op *operation.Operation, pv protocol.Version) (*protocol.ResolutionModel, error) {
// we can use operation applier to generate create response even though operation is not anchored yet
anchored := &operation.AnchoredOperation{
Type: op.Type,
UniqueSuffix: op.UniqueSuffix,
OperationBuffer: op.OperationBuffer,
}
rm := &protocol.ResolutionModel{}
rm, err := pv.OperationApplier().Apply(anchored, rm)
if err != nil {
return nil, err
}
return rm, nil
}
func (r *DocumentHandler) getCreateResponse(op *operation.Operation, pv protocol.Version) (*document.ResolutionResult, error) {
rm, err := r.getCreateResult(op, pv)
if err != nil {
return nil, err
}
externalResult, err := r.transformToExternalDoc(rm.Doc, op.ID)
if err != nil {
return nil, err
}
externalResult.MethodMetadata.Published = false
externalResult.MethodMetadata.RecoveryCommitment = rm.RecoveryCommitment
externalResult.MethodMetadata.UpdateCommitment = rm.UpdateCommitment
return externalResult, nil
}
// ResolveDocument fetches the latest DID Document of a DID. Two forms of string can be passed in the URI:
//
// 1. Standard DID format: did:METHOD:<did-suffix>
//
// 2. Long Form DID format:
// did:METHOD:<did-suffix>:Base64url(JCS({suffix-data-object, delta-object}))
//
// Standard resolution is performed if the DID is found to be registered on the blockchain.
// If the DID Document cannot be found, the <suffix-data-object> and <delta-object> are used
// to generate and return resolved DID Document. In this case the supplied delta and suffix objects
// are subject to the same validation as during processing create operation.
func (r *DocumentHandler) ResolveDocument(shortOrLongFormDID string) (*document.ResolutionResult, error) {
ns, err := r.getNamespace(shortOrLongFormDID)
if err != nil {
return nil, fmt.Errorf("%s: %s", badRequest, err.Error())
}
pv, err := r.protocol.Current()
if err != nil {
return nil, err
}
// extract did and optional initial document value
shortFormDID, createReq, err := pv.OperationParser().ParseDID(ns, shortOrLongFormDID)
if err != nil {
return nil, fmt.Errorf("%s: %s", badRequest, err.Error())
}
uniquePortion, err := getSuffix(ns, shortFormDID)
if err != nil {
return nil, fmt.Errorf("%s: %s", badRequest, err.Error())
}
// resolve document from the blockchain
doc, err := r.resolveRequestWithID(ns, uniquePortion)
if err == nil {
return doc, nil
}
// if document was not found on the blockchain and initial value has been provided resolve using initial value
if createReq != nil && strings.Contains(err.Error(), "not found") {
return r.resolveRequestWithInitialState(uniquePortion, shortOrLongFormDID, createReq, pv)
}
return nil, err
}
func (r *DocumentHandler) getNamespace(shortOrLongFormDID string) (string, error) {
// check namespace
if strings.HasPrefix(shortOrLongFormDID, r.namespace+docutil.NamespaceDelimiter) {
return r.namespace, nil
}
// check aliases
for _, ns := range r.aliases {
if strings.HasPrefix(shortOrLongFormDID, ns+docutil.NamespaceDelimiter) {
return ns, nil
}
}
return "", fmt.Errorf("did must start with configured namespace[%s] or aliases%v", r.namespace, r.aliases)
}
func (r *DocumentHandler) resolveRequestWithID(namespace, uniquePortion string) (*document.ResolutionResult, error) {
internalResult, err := r.processor.Resolve(uniquePortion)
if err != nil {
logger.Errorf("Failed to resolve uniquePortion[%s]: %s", uniquePortion, err.Error())
return nil, err
}
externalResult, err := r.transformToExternalDoc(internalResult.Document, namespace+docutil.NamespaceDelimiter+uniquePortion)
if err != nil {
return nil, err
}
if r.namespace != namespace {
// we got here using alias; suggest using namespace
externalResult.MethodMetadata.CanonicalID = r.namespace + docutil.NamespaceDelimiter + uniquePortion
}
externalResult.MethodMetadata.Published = true
externalResult.MethodMetadata.RecoveryCommitment = internalResult.MethodMetadata.RecoveryCommitment
externalResult.MethodMetadata.UpdateCommitment = internalResult.MethodMetadata.UpdateCommitment
return externalResult, nil
}
func (r *DocumentHandler) resolveRequestWithInitialState(uniqueSuffix, longFormDID string, initialBytes []byte, pv protocol.Version) (*document.ResolutionResult, error) {
// verify size of create request does not exceed the maximum allowed limit
if len(initialBytes) > int(pv.Protocol().MaxOperationSize) {
return nil, fmt.Errorf("%s: operation byte size exceeds protocol max operation byte size", badRequest)
}
op, err := pv.OperationParser().Parse(r.namespace, initialBytes)
if err != nil {
return nil, fmt.Errorf("%s: %s", badRequest, err.Error())
}
if uniqueSuffix != op.UniqueSuffix {
return nil, fmt.Errorf("%s: provided did doesn't match did created from initial state", badRequest)
}
rm, err := r.getCreateResult(op, pv)
if err != nil {
return nil, err
}
docBytes, err := canonicalizer.MarshalCanonical(rm.Doc)
if err != nil {
return nil, err
}
err = pv.DocumentValidator().IsValidOriginalDocument(docBytes)
if err != nil {
return nil, fmt.Errorf("%s: validate initial document: %s", badRequest, err.Error())
}
externalResult, err := r.transformToExternalDoc(rm.Doc, longFormDID)
if err != nil {
return nil, fmt.Errorf("failed to transform create with initial state to external document: %s", err.Error())
}
externalResult.MethodMetadata.Published = false
externalResult.MethodMetadata.RecoveryCommitment = rm.RecoveryCommitment
externalResult.MethodMetadata.UpdateCommitment = rm.UpdateCommitment
return externalResult, nil
}
// helper function to transform internal into external document and return resolution result.
func (r *DocumentHandler) transformToExternalDoc(internal document.Document, id string) (*document.ResolutionResult, error) {
if internal == nil {
return nil, errors.New("internal document is nil")
}
// apply id to document so it can be added to all keys and services
internal[keyID] = id
return r.transformer.TransformDocument(internal)
}
// helper for adding operations to the batch.
func (r *DocumentHandler) addToBatch(op *operation.Operation, genesisTime uint64) error {
return r.writer.Add(
&operation.QueuedOperation{
Namespace: r.namespace,
UniqueSuffix: op.UniqueSuffix,
OperationBuffer: op.OperationBuffer,
}, genesisTime)
}
func (r *DocumentHandler) validateOperation(op *operation.Operation, pv protocol.Version) error {
// check maximum operation size against protocol
if len(op.OperationBuffer) > int(pv.Protocol().MaxOperationSize) {
return errors.New("operation byte size exceeds protocol max operation byte size")
}
if op.Type == operation.TypeCreate {
return r.validateCreateDocument(op, pv)
}
// TODO: Change interface for IsValidPayload to batch.Operation (impacts fabric)
return pv.DocumentValidator().IsValidPayload(op.OperationBuffer)
}
func (r *DocumentHandler) validateCreateDocument(op *operation.Operation, pv protocol.Version) error {
rm, err := r.getCreateResult(op, pv)
if err != nil {
return err
}
docBytes, err := canonicalizer.MarshalCanonical(rm.Doc)
if err != nil {
return err
}
return pv.DocumentValidator().IsValidOriginalDocument(docBytes)
}
// getSuffix fetches unique portion of ID which is string after namespace.
func getSuffix(namespace, idOrDocument string) (string, error) {
ns := namespace + docutil.NamespaceDelimiter
pos := strings.Index(idOrDocument, ns)
if pos == -1 {
return "", errors.New("did must start with configured namespace")
}
adjustedPos := pos + len(ns)
if adjustedPos >= len(idOrDocument) {
return "", errors.New("did suffix is empty")
}
return idOrDocument[adjustedPos:], nil
}
|
package validate
import "reflect"
// FilterRule definition
type FilterRule struct {
// fields to filter
fields []string
// filter name list
filters []string
// filter args. { index: "args" }
filterArgs map[int]string
}
type funcMeta struct {
fv reflect.Value
name string
// readonly cache
numIn int
numOut int
// is internal built in validator
isInternal bool
// last arg is like "... interface{}"
isVariadic bool
}
|
package main
import (
"log"
"net"
"tag-service/server"
"google.golang.org/grpc/reflection"
pb "tag-service/proto"
grpc "google.golang.org/grpc"
)
func main() {
port := "8888"
s := grpc.NewServer()
pb.RegisterTagServiceServer(s, server.NewTagServer())
reflection.Register(s)
lis, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatalf("net.Listen err: %v", err)
}
err = s.Serve(lis)
if err != nil {
log.Fatalf("server.Serve err: %v", err)
}
}
|
package shortener
import (
"bytes"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestGetURL(t *testing.T) {
db, path := setupDatabase(t)
shortServer := ShortServer{DB: db, URL: "easy.xyz"}
defer db.Close()
defer os.RemoveAll(path)
t.Run("Getting the given URLs", func(t *testing.T) {
request, _ := http.NewRequest(http.MethodGet, "/test", nil)
response := httptest.NewRecorder()
shortServer.GetURL(response, request)
actual := response.Result().StatusCode
expected := http.StatusPermanentRedirect // redirect status code
assert.Equal(t, expected, actual)
})
t.Run("Requesting a non-existing shortcut", func(t *testing.T) {
request, _ := http.NewRequest(http.MethodGet, "/unknown", nil)
response := httptest.NewRecorder()
shortServer.GetURL(response, request)
actual := response.Result().StatusCode
expected := http.StatusNotFound
assert.Equal(t, expected, actual)
})
}
func TestLookup(t *testing.T) {
db, path := setupDatabase(t)
shortServer := ShortServer{DB: db, URL: "easy.xyz"}
defer db.Close()
defer os.RemoveAll(path)
t.Run("Lookup and find", func(t *testing.T) {
expected := "https://test.local/"
actual, err := shortServer.Lookup("/test")
assert.Equal(t, expected, actual)
assert.NoError(t, err)
})
t.Run("Lookup non existing key", func(t *testing.T) {
url := "unknown"
_, err := shortServer.Lookup(url)
expected := fmt.Sprintf("could not find the proper URL for %s (unknown)", url)
assert.Error(t, err)
assert.Equal(t, err.Error(), expected)
})
}
func TestAddURL(t *testing.T) {
db, path := setupDatabase(t)
shortServer := ShortServer{DB: db, URL: "easy.xyz"}
defer db.Close()
defer os.RemoveAll(path)
t.Run("Adding an URL", func(t *testing.T) {
urlPair := URLPair{Shorthand: "foo", Target: "https://bar.local/"}
jsonPair, err := json.Marshal(urlPair)
assert.NoError(t, err)
request, err := http.NewRequest(http.MethodPost, "/add", bytes.NewBuffer(jsonPair))
response := httptest.NewRecorder()
assert.NoError(t, err)
shortServer.AddURL(response, request)
assert.NoError(t, err)
expected := http.StatusOK
actual := response.Result().StatusCode
assert.Equal(t, expected, actual)
})
t.Run("Adding an existing URL", func(t *testing.T) {
urlPair := URLPair{Shorthand: "test", Target: "https://test.local/"}
jsonPair, err := json.Marshal(urlPair)
assert.NoError(t, err)
request, err := http.NewRequest(http.MethodPost, "/add", bytes.NewBuffer(jsonPair))
response := httptest.NewRecorder()
assert.NoError(t, err)
shortServer.AddURL(response, request)
expected := http.StatusConflict
actual := response.Result().StatusCode
assert.Equal(t, expected, actual)
})
t.Run("Empty fields", func(t *testing.T) {
})
}
func TestAdd(t *testing.T) {
db, path := setupDatabase(t)
shortServer := ShortServer{DB: db, URL: "easy.xyz"}
defer db.Close()
defer os.RemoveAll(path)
t.Run("Adding a new Pair", func(t *testing.T) {
urlPair := URLPair{Shorthand: "foo", Target: "https://bar.local/"}
err := shortServer.Add(urlPair)
assert.NoError(t, err)
actual, err := shortServer.Lookup(urlPair.Shorthand)
assert.NoError(t, err)
assert.Equal(t, urlPair.Target, actual)
})
t.Run("Adding an existing Pair", func(t *testing.T) {
urlPair := URLPair{Shorthand: "test", Target: "https://test.local/"}
err := shortServer.Add(urlPair)
assert.Error(t, err)
})
}
func setupDatabase(t *testing.T) (*bolt.DB, string) {
t.Helper()
// using tmp files for integration testing
dir, err := ioutil.TempDir("", "database")
assert.NoError(t, err)
tmpDB := filepath.Join(dir, "test.db")
db, err := bolt.Open(tmpDB, 0600, nil)
assert.NoError(t, err)
err = db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("urls"))
if err != nil {
return err
}
err = bucket.Put([]byte("test"), []byte("https://test.local/"))
if err != nil {
return err
}
return nil
})
assert.NoError(t, err)
return db, dir
}
|
package main
import "fmt"
type Stack struct {
top *Element
size int
}
type Element struct {
value interface{}
next *Element
}
// стекийн урт
func (s *Stack) Len() int {
return s.size
}
// стекийн оройд элемент нэмэх
func (s *Stack) Push(value interface{}) {
s.top = &Element{value, s.top}
s.size++
}
// стекийн оройгоос элемент авах
func (s *Stack) Pop() (value interface{}) {
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
return
}
return nil
}
func main() {
stack := new(Stack)
stack.Push("Things")
stack.Push("and")
stack.Push("Stuff")
for stack.Len() > 0 {
fmt.Printf("%s ", stack.Pop().(string))
}
fmt.Println()
}
|
package login
//cv propiedades tipo clave: valor
type cv map[string]string
var usuarios = make(map[string]map[string]string)
func init() {
usuarios = map[string]map[string]string{
"juan": cv{"pwd": "123", "nvl": "1"},
"maria": cv{"pwd": "123", "nvl": "1"},
"luis": cv{"pwd": "123", "nvl": "2"},
}
}
//me modelos end point (rutas) staticas del sistema
func me() *map[string]map[string]string {
//ejemplo de rutas
e := map[string]map[string]string{
"hora": cv{"nvl": "1"},
"paciente": cv{"nvl": "2"},
}
return &e
}
|
/*
Copyright 2017 The Kubernetes Authors.
SPDX-License-Identifier: Apache-2.0
*/
package oimcsidriver
import (
"context"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/container-storage-interface/spec/lib/go/csi"
)
func (od *oimDriver) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {
name := req.GetName()
caps := req.GetVolumeCapabilities()
if name == "" {
return nil, status.Error(codes.InvalidArgument, "Name missing in request")
}
if caps == nil {
return nil, status.Error(codes.InvalidArgument, "Volume Capabilities missing in request")
}
for _, cap := range caps {
if cap.GetBlock() != nil {
return nil, status.Error(codes.Unimplemented, "Block Volume not supported")
}
switch cap.GetAccessMode().GetMode() {
case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER: // okay
case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY: // okay
case csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY: // okay
case csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER:
// While in theory writing blocks on one node and reading them on others could work,
// in practice caching effects might break that. Better don't allow it.
return nil, status.Error(codes.Unimplemented, "multi-node reader, single writer not supported")
case csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER:
return nil, status.Error(codes.Unimplemented, "multi-node reader, multi-node writer not supported")
default:
return nil, status.Error(codes.Unimplemented, fmt.Sprintf("%s not supported", cap.GetAccessMode().GetMode()))
}
}
if req.GetVolumeContentSource() != nil {
return nil, status.Error(codes.Unimplemented, "snapshots not supported")
}
// Serialize operations per volume by name.
if name == "" {
return nil, status.Error(codes.InvalidArgument, "empty name")
}
volumeNameMutex.LockKey(name)
defer volumeNameMutex.UnlockKey(name)
actualBytes, err := od.backend.createVolume(ctx, name, req.GetCapacityRange().GetRequiredBytes())
if err != nil {
return nil, err
}
return &csi.CreateVolumeResponse{
Volume: &csi.Volume{
// We use the unique name also as ID.
VolumeId: name,
CapacityBytes: actualBytes,
},
}, nil
}
func (od *oimDriver) DeleteVolume(ctx context.Context, req *csi.DeleteVolumeRequest) (*csi.DeleteVolumeResponse, error) {
// Check arguments
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request")
}
// Volume ID is the same as the volume name in CreateVolume. Serialize by that.
name := req.GetVolumeId()
if name == "" {
return nil, status.Error(codes.InvalidArgument, "empty volume ID")
}
volumeNameMutex.LockKey(name)
defer volumeNameMutex.UnlockKey(name)
if err := od.backend.deleteVolume(ctx, name); err != nil {
return nil, err
}
return &csi.DeleteVolumeResponse{}, nil
}
func (od *oimDriver) ControllerPublishVolume(ctx context.Context, req *csi.ControllerPublishVolumeRequest) (*csi.ControllerPublishVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (od *oimDriver) ControllerUnpublishVolume(ctx context.Context, req *csi.ControllerUnpublishVolumeRequest) (*csi.ControllerUnpublishVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (od *oimDriver) ValidateVolumeCapabilities(ctx context.Context, req *csi.ValidateVolumeCapabilitiesRequest) (*csi.ValidateVolumeCapabilitiesResponse, error) {
// Check arguments
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request")
}
if req.GetVolumeCapabilities() == nil {
return nil, status.Error(codes.InvalidArgument, "Volume capabilities missing in request")
}
// Volume ID is the same as the volume name in CreateVolume. Serialize by that.
name := req.GetVolumeId()
if name == "" {
return nil, status.Error(codes.InvalidArgument, "empty volume ID")
}
volumeNameMutex.LockKey(name)
defer volumeNameMutex.UnlockKey(name)
// Check that volume exists.
if err := od.backend.checkVolumeExists(ctx, req.GetVolumeId()); err != nil {
return nil, err
}
confirmed := &csi.ValidateVolumeCapabilitiesResponse_Confirmed{
// We don't actually do any validation of these (don't even use them!).
// It's also unclear from the spec what a CO would do with the validated
// values, because both are opaque to the CO.
VolumeContext: req.VolumeContext,
Parameters: req.Parameters,
}
for _, cap := range req.VolumeCapabilities {
if cap.GetBlock() != nil {
/* Known unsupported mode. Fail the validation. */
return &csi.ValidateVolumeCapabilitiesResponse{Message: "Block Volume not supported"}, nil
}
if cap.GetMount() == nil {
/* Must be something else, an unknown mode. Ignore it. */
continue
}
// We could check fs type and mount flags for MountVolume, but let's assume that they are okay.
// Now check the access mode.
switch cap.GetAccessMode().GetMode() {
case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER: // okay
case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY: // okay
case csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY: // okay
case csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER:
// While in theory writing blocks on one node and reading them on others could work,
// in practice caching effects might break that. Better don't allow it.
return &csi.ValidateVolumeCapabilitiesResponse{Message: "multi-node reader, single writer not supported"}, nil
case csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER:
return &csi.ValidateVolumeCapabilitiesResponse{Message: "multi-node reader, multi-node writer not supported"}, nil
default:
/* unknown, not supported */
continue
}
confirmed.VolumeCapabilities = append(confirmed.VolumeCapabilities, cap)
}
return &csi.ValidateVolumeCapabilitiesResponse{Confirmed: confirmed}, nil
}
func (od *oimDriver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (od *oimDriver) GetCapacity(ctx context.Context, req *csi.GetCapacityRequest) (*csi.GetCapacityResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ControllerGetCapabilities implements the default GRPC callout.
// Default supports all capabilities
func (od *oimDriver) ControllerGetCapabilities(ctx context.Context, req *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) {
return &csi.ControllerGetCapabilitiesResponse{
Capabilities: od.cap,
}, nil
}
func (od *oimDriver) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (od *oimDriver) DeleteSnapshot(ctx context.Context, req *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (od *oimDriver) ListSnapshots(ctx context.Context, req *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
|
package testrail
import (
"fmt"
"net/url"
)
// Run represents a Run
type Run struct {
AssignedToID int `json:"assignedto_id"`
BlockedCount int `json:"blocked_count"`
CompletedOn int `json:"completed_on"`
Config string `json:"config"`
ConfigIDs []int `json:"config_ids"`
CreatedBy int `json:"created_by"`
CreatedOn int `json:"created_on"`
Description string `json:"description"`
EntryID string `json:"entry_id"`
EntryIndex int `json:"entry_index"`
FailedCount int `json:"failed_count"`
ID int `json:"id"`
IncludeAll bool `json:"include_all"`
IsCompleted bool `json:"is_completed"`
MilestoneID int `json:"milestone_id"`
Name string `json:"name"`
PassedCount int `json:"passed_count"`
PlanID int `json:"plan_id"`
ProjectID int `json:"project_id"`
RetestCount int `json:"retest_count"`
SuiteID int `json:"suite_id"`
UntestedCount int `json:"untested_count"`
URL string `json:"url"`
}
// RequestFilterForRun represents the filters
// usable to get the run
type RequestFilterForRun struct {
CreatedAfter string `json:"created_after,omitempty"`
CreatedBefore string `json:"created_before,omitempty"`
CreatedBy IntList `json:"created_by,omitempty"`
IsCompleted *bool `json:"is_completed,omitempty"`
Limit *int `json:"limit,omitempty"`
Offset *int `json:"offset,omitempty"`
MilestoneID IntList `json:"milestone_id,omitempty"`
SuiteID IntList `json:"suite_id,omitempty"`
}
// SendableRun represents a Run
// that can be created via the api
type SendableRun struct {
SuiteID int `json:"suite_id"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
MilestoneID int `json:"milestone_id,omitempty"`
AssignedToID int `json:"assignedto_id,omitempty"`
IncludeAll *bool `json:"include_all,omitempty"`
CaseIDs []int `json:"case_id,omitempty"`
}
// UpdatableRun represents a Run
// that can be updated via the api
type UpdatableRun struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
MilestoneID int `json:"milestone_id,omitempty"`
IncludeAll *bool `json:"include_all,omitempty"`
CaseIDs []int `json:"case_id,omitempty"`
}
// GetRun returns the run runID
func (c *Client) GetRun(runID int) (run Run, err error) {
err = c.sendRequest("GET", fmt.Sprintf("get_run/%d", runID), nil, &run)
return
}
// GetRuns returns the list of runs of projectID
// validating the filters
func (c *Client) GetRuns(projectID int, filters ...RequestFilterForRun) (runs []Run, err error) {
vals := make(url.Values)
loadOptionalFilters(vals, filters)
err = c.sendRequest("GET", fmt.Sprintf("get_runs/%d?%s", projectID, vals.Encode()), nil, &runs)
return
}
// AddRun creates a new run on projectID and returns it
func (c *Client) AddRun(projectID int, newRun SendableRun) (run Run, err error) {
err = c.sendRequest("POST", fmt.Sprintf("add_run/%d", projectID), newRun, &run)
return
}
// UpdateRun updates the run runID and returns it
func (c *Client) UpdateRun(runID int, update UpdatableRun) (run Run, err error) {
err = c.sendRequest("POST", fmt.Sprintf("update_run/%d", runID), update, &run)
return
}
// CloseRun closes the run runID,
// archives its tests and results
// and returns it
func (c *Client) CloseRun(runID int) (run Run, err error) {
err = c.sendRequest("POST", fmt.Sprintf("close_run/%d", runID), nil, &run)
return
}
// DeleteRun delete the run runID
func (c *Client) DeleteRun(runID int) error {
return c.sendRequest("POST", fmt.Sprintf("delete_run/%d", runID), nil, nil)
}
|
package main
//region Usings
import "github.com/ravendb/ravendb-go-client"
//endregion
var globalDocumentStore *ravendb.DocumentStore
func main() {
createDocumentStore()
createDatabase()
enableRevisions("collection1","collection2")
globalDocumentStore.Close()
}
func createDocumentStore() (*ravendb.DocumentStore, error) {
if globalDocumentStore != nil {
return globalDocumentStore, nil
}
urls := []string{"http://localhost:8080"}
store := ravendb.NewDocumentStore(urls, "testGO")
err := store.Initialize()
if err != nil {
return nil, err
}
globalDocumentStore = store
return globalDocumentStore, nil
}
func createDatabase() {
databaseRecord := ravendb.NewDatabaseRecord()
databaseRecord.DatabaseName = "testGO"
createDatabaseOperation := ravendb.NewCreateDatabaseOperation(databaseRecord, 1)
var err = globalDocumentStore.Maintenance().Server().Send(createDatabaseOperation)
if err != nil {
fmt.Printf("d.store.Maintenance().Server().Send(createDatabaseOperation) failed with %s\n", err)
}
}
//region Demo
func enableRevisions(collection1, collection2 string) error {
//region Step_1
dur := ravendb.Duration(time.Hour * 24 * 14)
defaultConfig := &ravendb.RevisionsCollectionConfiguration{
Disabled: false,
PurgeOnDelete: false,
MinimumRevisionsToKeep: 5,
MinimumRevisionAgeToKeep: &dur,
}
//endregion
//region Step_2
collectionConfig1 := &ravendb.RevisionsCollectionConfiguration{
Disabled: true,
}
collectionConfig2 := &ravendb.RevisionsCollectionConfiguration{
PurgeOnDelete: true,
}
collections := map[string]*ravendb.RevisionsCollectionConfiguration{
collection1: collectionConfig1,
collection2: collectionConfig2,
}
//endregion
//region Step_3
myRevisionsConfiguration := &ravendb.RevisionsConfiguration{
DefaultConfig: defaultConfig,
Collections: collections,
}
//endregion
//region Step_4
revisionsConfigurationOperation := ravendb.NewConfigureRevisionsOperation(myRevisionsConfiguration)
return globalDocumentStore.Maintenance().Send(revisionsConfigurationOperation)
//endregion
}
//endregion
|
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gluang/GenBook/docs"
)
var (
version string
commit string
date string
)
func main() {
args := os.Args
if len(args) == 2 && (args[1] == "--version" || args[1] == "-v") {
fmt.Printf("Release version : %s\n", version)
fmt.Printf("Git commit : %s\n", commit)
fmt.Println("Author : gluang")
fmt.Printf("Build date : %s\n", date)
return
}
var port string = "12300"
if len(args) == 3 && (args[1] == "--port" || args[1] == "-p") {
port = args[2]
}
fileServer := http.FileServer(http.FS(docs.StaticFs))
var srv = &http.Server{
Addr: ":" + port,
Handler: fileServer,
}
go func() {
log.Println("Serving on http://localhost:" + port)
err := srv.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatalf("Listen:%s\n", err)
}
}()
listenSignal(srv)
}
func listenSignal(srv *http.Server) {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
<-ctx.Done()
stop()
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(timeoutCtx); err != nil {
log.Fatalf("Shutdown:%s\n", err)
}
fmt.Println()
log.Println("✔️ close service successfully")
}
|
package main
import "fmt"
func main() {
// x := 8
// fmt.Println("My first variable, well not really but whatever", x)
// var (
// x = 10
// y = 12
// z = 15
// )
fmt.Println("Let me multiply convert C => F for you")
var celciusInput float64
fmt.Scanf("%f", &celciusInput)
output := (celciusInput * (9.0 / 5.0)) + 32
fmt.Println(output)
}
// variables are pretty straight forward, im not sure when i should use var
// use const for static variables
|
package inmemory
import (
"github.com/Tanibox/tania-core/src/assets/query"
"github.com/Tanibox/tania-core/src/assets/storage"
"github.com/gofrs/uuid"
)
type ReservoirReadQueryInMemory struct {
Storage *storage.ReservoirReadStorage
}
func NewReservoirReadQueryInMemory(s *storage.ReservoirReadStorage) query.ReservoirReadQuery {
return ReservoirReadQueryInMemory{Storage: s}
}
func (s ReservoirReadQueryInMemory) FindByID(uid uuid.UUID) <-chan query.QueryResult {
result := make(chan query.QueryResult)
go func() {
s.Storage.Lock.RLock()
defer s.Storage.Lock.RUnlock()
reservoir := storage.ReservoirRead{}
for _, val := range s.Storage.ReservoirReadMap {
if val.UID == uid {
reservoir = val
}
}
result <- query.QueryResult{Result: reservoir}
close(result)
}()
return result
}
func (s ReservoirReadQueryInMemory) FindAllByFarm(farmUID uuid.UUID) <-chan query.QueryResult {
result := make(chan query.QueryResult)
go func() {
s.Storage.Lock.RLock()
defer s.Storage.Lock.RUnlock()
reservoirs := []storage.ReservoirRead{}
for _, val := range s.Storage.ReservoirReadMap {
if val.Farm.UID == farmUID {
reservoirs = append(reservoirs, val)
}
}
result <- query.QueryResult{Result: reservoirs}
close(result)
}()
return result
}
|
// Copyright (C) 2019 Cisco Systems Inc.
// Copyright (C) 2016-2017 Nippon Telegraph and Telephone Corporation.
//
// 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 routing
import (
"fmt"
"net"
bgpapi "github.com/osrg/gobgp/v3/api"
bgpserver "github.com/osrg/gobgp/v3/pkg/server"
"github.com/pkg/errors"
calicov3 "github.com/projectcalico/api/pkg/apis/projectcalico/v3"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/net/context"
"gopkg.in/tomb.v2"
"github.com/projectcalico/vpp-dataplane/v3/calico-vpp-agent/common"
"github.com/projectcalico/vpp-dataplane/v3/calico-vpp-agent/watchers"
"github.com/projectcalico/vpp-dataplane/v3/vpplink"
)
const (
RTPROT_GOBGP = 0x11
)
type localAddress struct {
ipNet *net.IPNet
vni uint32
}
type Server struct {
log *logrus.Entry
vpp *vpplink.VppLink
localAddressMap map[string]localAddress
ShouldStop bool
BGPConf *calicov3.BGPConfigurationSpec
BGPServer *bgpserver.BgpServer
bgpFilters map[string]*calicov3.BGPFilter
bgpPeers map[string]*watchers.LocalBGPPeer
routingServerEventChan chan common.CalicoVppEvent
nodeBGPSpec *common.LocalNodeSpec
}
func (s *Server) SetBGPConf(bgpConf *calicov3.BGPConfigurationSpec) {
s.BGPConf = bgpConf
logLevel, err := logrus.ParseLevel(s.getLogSeverityScreen())
if err != nil {
s.log.WithError(err).Errorf("Failed to parse loglevel: %s, defaulting to info", s.getLogSeverityScreen())
} else {
logrus.SetLevel(logLevel)
}
}
func (s *Server) SetOurBGPSpec(nodeBGPSpec *common.LocalNodeSpec) {
s.nodeBGPSpec = nodeBGPSpec
}
func NewRoutingServer(vpp *vpplink.VppLink, bgpServer *bgpserver.BgpServer, log *logrus.Entry) *Server {
server := Server{
log: log,
vpp: vpp,
BGPServer: bgpServer,
localAddressMap: make(map[string]localAddress),
routingServerEventChan: make(chan common.CalicoVppEvent, common.ChanSize),
bgpFilters: make(map[string]*calicov3.BGPFilter),
bgpPeers: make(map[string]*watchers.LocalBGPPeer),
}
reg := common.RegisterHandler(server.routingServerEventChan, "routing server events")
reg.ExpectEvents(
common.LocalPodAddressAdded,
common.LocalPodAddressDeleted,
common.BGPPathAdded,
common.BGPPathDeleted,
common.BGPDefinedSetAdded,
common.BGPDefinedSetDeleted,
common.BGPPeerAdded,
common.BGPPeerDeleted,
common.BGPPeerUpdated,
common.BGPFilterAddedOrUpdated,
common.BGPFilterDeleted,
)
return &server
}
func (s *Server) ServeRouting(t *tomb.Tomb) (err error) {
s.log.Infof("Routing server started")
err = s.configureLocalNodeSnat()
if err != nil {
return errors.Wrap(err, "cannot configure node snat")
}
for t.Alive() {
globalConfig, err := s.getGoBGPGlobalConfig()
if err != nil {
return fmt.Errorf("cannot get global configuration: %v", err)
}
err = s.BGPServer.StartBgp(context.Background(), &bgpapi.StartBgpRequest{Global: globalConfig})
if err != nil {
return errors.Wrap(err, "failed to start BGP server")
}
nodeIP4, nodeIP6 := common.GetBGPSpecAddresses(s.nodeBGPSpec)
if nodeIP4 != nil {
err = s.initialPolicySetting(false /* isv6 */)
if err != nil {
return errors.Wrap(err, "error configuring initial policies")
}
}
if nodeIP6 != nil {
err = s.initialPolicySetting(true /* isv6 */)
if err != nil {
return errors.Wrap(err, "error configuring initial policies")
}
}
/* Restore the previous config in case we restarted */
s.RestoreLocalAddresses()
s.log.Infof("Routing server is running ")
/* Start watching goBGP */
err = s.WatchBGPPath(t)
if err != nil {
s.log.Error(err)
return err
}
/* watch returned, we shall restart */
err = s.cleanUpRoutes()
if err != nil {
return errors.Wrap(err, "also failed to clean up routes which we injected")
}
err = s.BGPServer.StopBgp(context.Background(), &bgpapi.StopBgpRequest{})
if err != nil {
s.log.Errorf("failed to stop BGP server: %s", err)
}
s.log.Infof("Routing server stopped")
}
s.log.Warn("Routing Server returned")
return nil
}
func (s *Server) getListenPort() uint16 {
return s.BGPConf.ListenPort
}
func (s *Server) getLogSeverityScreen() string {
return s.BGPConf.LogSeverityScreen
}
func (s *Server) getGoBGPGlobalConfig() (*bgpapi.Global, error) {
var routerId string
var listenAddresses []string = make([]string, 0)
asn := s.nodeBGPSpec.ASNumber
if asn == nil {
asn = s.BGPConf.ASNumber
}
nodeIP4, nodeIP6 := common.GetBGPSpecAddresses(s.nodeBGPSpec)
if nodeIP6 != nil {
routerId = nodeIP6.String()
listenAddresses = append(listenAddresses, routerId)
}
if nodeIP4 != nil {
routerId = nodeIP4.String() // Override v6 ID if v4 is available
listenAddresses = append(listenAddresses, routerId)
}
if routerId == "" {
return nil, fmt.Errorf("No IPs to make a router ID")
}
return &bgpapi.Global{
Asn: uint32(*asn),
RouterId: routerId,
ListenPort: int32(s.getListenPort()),
ListenAddresses: listenAddresses,
}, nil
}
func (s *Server) cleanUpRoutes() error {
s.log.Tracef("Clean up injected routes")
filter := &netlink.Route{
Protocol: RTPROT_GOBGP,
}
list4, err := netlink.RouteListFiltered(netlink.FAMILY_V4, filter, netlink.RT_FILTER_PROTOCOL)
if err != nil {
return err
}
list6, err := netlink.RouteListFiltered(netlink.FAMILY_V6, filter, netlink.RT_FILTER_PROTOCOL)
if err != nil {
return err
}
for _, route := range append(list4, list6...) {
err = netlink.RouteDel(&route)
if err != nil {
return err
}
}
return nil
}
func (s *Server) announceLocalAddress(addr *net.IPNet, vni uint32) error {
s.log.Debugf("Announcing prefix %s in BGP", addr.String())
nodeIP4, nodeIP6 := common.GetBGPSpecAddresses(s.nodeBGPSpec)
path, err := common.MakePath(addr.String(), false /* isWithdrawal */, nodeIP4, nodeIP6, vni, uint32(*s.BGPConf.ASNumber))
if err != nil {
return errors.Wrap(err, "error making path to announce")
}
s.localAddressMap[addr.String()] = localAddress{ipNet: addr, vni: vni}
_, err = s.BGPServer.AddPath(context.Background(), &bgpapi.AddPathRequest{
TableType: bgpapi.TableType_GLOBAL,
Path: path,
})
return errors.Wrap(err, "error announcing local address")
}
func (s *Server) withdrawLocalAddress(addr *net.IPNet, vni uint32) error {
s.log.Debugf("Withdrawing prefix %s from BGP", addr.String())
nodeIP4, nodeIP6 := common.GetBGPSpecAddresses(s.nodeBGPSpec)
path, err := common.MakePath(addr.String(), true /* isWithdrawal */, nodeIP4, nodeIP6, vni, uint32(*s.BGPConf.ASNumber))
if err != nil {
return errors.Wrap(err, "error making path to withdraw")
}
delete(s.localAddressMap, addr.String())
err = s.BGPServer.DeletePath(context.Background(), &bgpapi.DeletePathRequest{
TableType: bgpapi.TableType_GLOBAL,
Path: path,
})
return errors.Wrap(err, "error withdrawing local address")
}
func (s *Server) RestoreLocalAddresses() {
for _, localAddr := range s.localAddressMap {
err := s.announceLocalAddress(localAddr.ipNet, localAddr.vni)
if err != nil {
s.log.Errorf("Local address %s restore failed : %+v", localAddr.ipNet.String(), err)
}
}
}
|
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package envbinding
import (
"encoding/json"
"regexp"
"strings"
"github.com/imdario/mergo"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/oam/util"
"github.com/oam-dev/kubevela/pkg/policy/utils"
errors2 "github.com/oam-dev/kubevela/pkg/utils/errors"
)
// MergeRawExtension merge two raw extension
func MergeRawExtension(base *runtime.RawExtension, patch *runtime.RawExtension) (*runtime.RawExtension, error) {
patchParameter, err := util.RawExtension2Map(patch)
if err != nil {
return nil, errors.Wrapf(err, "failed to convert patch parameters to map")
}
baseParameter, err := util.RawExtension2Map(base)
if err != nil {
return nil, errors.Wrapf(err, "failed to convert base parameters to map")
}
if baseParameter == nil {
baseParameter = make(map[string]interface{})
}
err = mergo.Merge(&baseParameter, patchParameter, mergo.WithOverride)
if err != nil {
return nil, errors.Wrapf(err, "failed to do merge with override")
}
bs, err := json.Marshal(baseParameter)
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal merged properties")
}
return &runtime.RawExtension{Raw: bs}, nil
}
// MergeComponent merge two component, it will first merge their properties and then merge their traits
func MergeComponent(base *common.ApplicationComponent, patch *v1alpha1.EnvComponentPatch) (*common.ApplicationComponent, error) {
newComponent := base.DeepCopy()
var err error
// merge component properties
newComponent.Properties, err = MergeRawExtension(base.Properties, patch.Properties)
if err != nil {
return nil, errors.Wrapf(err, "failed to merge component properties")
}
// merge component external revision
if patch.ExternalRevision != "" {
newComponent.ExternalRevision = patch.ExternalRevision
}
// prepare traits
traitMaps := map[string]*common.ApplicationTrait{}
var traitOrders []string
for _, trait := range base.Traits {
traitMaps[trait.Type] = trait.DeepCopy()
traitOrders = append(traitOrders, trait.Type)
}
// patch traits
var errs errors2.ErrorList
for _, trait := range patch.Traits {
if baseTrait, exists := traitMaps[trait.Type]; exists {
if trait.Disable {
delete(traitMaps, trait.Type)
continue
}
baseTrait.Properties, err = MergeRawExtension(baseTrait.Properties, trait.Properties)
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to merge trait %s", trait.Type))
}
} else {
if trait.Disable {
continue
}
traitMaps[trait.Type] = trait.ToApplicationTrait()
traitOrders = append(traitOrders, trait.Type)
}
}
if errs.HasError() {
return nil, errors.Wrapf(err, "failed to merge component traits")
}
// fill in traits
newComponent.Traits = []common.ApplicationTrait{}
for _, traitType := range traitOrders {
if _, exists := traitMaps[traitType]; exists {
newComponent.Traits = append(newComponent.Traits, *traitMaps[traitType])
}
}
return newComponent, nil
}
// PatchApplication patch base application with patch and selector
func PatchApplication(base *v1beta1.Application, patch *v1alpha1.EnvPatch, selector *v1alpha1.EnvSelector) (*v1beta1.Application, error) {
newApp := base.DeepCopy()
var err error
var compSelector []string
if selector != nil {
compSelector = selector.Components
}
var compPatch []v1alpha1.EnvComponentPatch
if patch != nil {
compPatch = patch.Components
}
newApp.Spec.Components, err = PatchComponents(base.Spec.Components, compPatch, compSelector)
return newApp, err
}
// PatchComponents patch base components with patch and selector
func PatchComponents(baseComponents []common.ApplicationComponent, patchComponents []v1alpha1.EnvComponentPatch, selector []string) ([]common.ApplicationComponent, error) {
// init components
compMaps := map[string]*common.ApplicationComponent{}
var compOrders []string
for _, comp := range baseComponents {
compMaps[comp.Name] = comp.DeepCopy()
compOrders = append(compOrders, comp.Name)
}
// patch components
var errs errors2.ErrorList
var err error
for _, comp := range patchComponents {
if comp.Name == "" {
// when no component name specified in the patch
// 1. if no type name specified in the patch, it will merge all components
// 2. if type name specified, it will merge components with the specified type
for compName, baseComp := range compMaps {
if comp.Type == "" || comp.Type == baseComp.Type {
compMaps[compName], err = MergeComponent(baseComp, comp.DeepCopy())
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to merge component %s", compName))
}
}
}
} else {
// when component name (pattern) specified in the patch, it will find the component with the matched name
// 1. if the component type is not specified in the patch, the matched component will be merged with the patch
// 2. if the matched component uses the same type, the matched component will be merged with the patch
// 3. if the matched component uses a different type, the matched component will be overridden by the patch
// 4. if no component matches, and the component name is a valid kubernetes name, a new component will be added
addComponent := regexp.MustCompile("[a-z]([a-z-]{0,61}[a-z])?").MatchString(comp.Name)
if re, err := regexp.Compile(strings.ReplaceAll(comp.Name, "*", ".*")); err == nil {
for compName, baseComp := range compMaps {
if re.MatchString(compName) {
addComponent = false
if baseComp.Type != comp.Type && comp.Type != "" {
compMaps[compName] = comp.ToApplicationComponent()
} else {
compMaps[compName], err = MergeComponent(baseComp, comp.DeepCopy())
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to merge component %s", comp.Name))
}
}
}
}
}
if addComponent {
compMaps[comp.Name] = comp.ToApplicationComponent()
compOrders = append(compOrders, comp.Name)
}
}
}
if errs.HasError() {
return nil, errors.Wrapf(err, "failed to merge application components")
}
// if selector is enabled, filter
compOrders = utils.FilterComponents(compOrders, selector)
// fill in new application
newComponents := []common.ApplicationComponent{}
for _, compName := range compOrders {
newComponents = append(newComponents, *compMaps[compName])
}
return newComponents, nil
}
|
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"fmt"
"io"
)
func main() {
h256 := sha256.New()
io.WriteString(h256, "anziguoer")
fmt.Printf("anziguoer => sha256: %x \n", h256.Sum(nil))
h1 := sha1.New()
io.WriteString(h1, "anziguoer")
fmt.Printf("anziguoer => sha1: %x \n", h1.Sum(nil))
m5 := md5.New()
io.WriteString(m5, "anziguoer")
fmt.Printf("anziguoer => md5: %x \n", m5.Sum(nil))
}
|
package gameencoder
// crc表
var crcTable = [...]uint32{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d,
}
func doOneByte(crc *uint32, data byte) {
*crc = crcTable[(*crc^uint32(data))&0xff] ^ (*crc >> 8)
}
// CRC32 : 剑一游戏使用的CRC32编码
func CRC32(crc uint32, data []byte) uint32 {
dataLen := uint32(len(data))
if dataLen <= 0 {
return 0
}
crc = crc ^ 0xffffffff
cur := 0
for dataLen >= 8 {
doOneByte(&crc, data[cur]) // 0
cur++
doOneByte(&crc, data[cur]) // 1
cur++
doOneByte(&crc, data[cur]) // 2
cur++
doOneByte(&crc, data[cur]) // 3
cur++
doOneByte(&crc, data[cur]) // 4
cur++
doOneByte(&crc, data[cur]) // 5
cur++
doOneByte(&crc, data[cur]) // 6
cur++
doOneByte(&crc, data[cur]) // 7
cur++
dataLen -= 8
}
for dataLen > 0 {
doOneByte(&crc, data[cur])
cur++
dataLen--
}
return crc ^ 0xffffffff
}
|
// Declarando variavel com package scope.
// Toda variavel
package main
import "fmt"
var nome string
var idade int
var peso float64
var solteiro bool
func main() {
fmt.Printf("%v, %T\n", nome, nome)
fmt.Printf("%v, %T\n", idade, idade)
fmt.Printf("%v, %T\n", peso, peso)
fmt.Printf("%v, %T\n", solteiro, solteiro)
nome := "Douglas"
if !solteiro {
fmt.Println(nome, "esta compromissado atualmente!")
}
}
|
package integration_test
import (
"fmt"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"time"
"github.com/blang/semver"
"github.com/cloudfoundry/libbuildpack/cutlass"
"github.com/cloudfoundry/libbuildpack/packager"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("deploy a staticfile app", func() {
var app *cutlass.App
AfterEach(func() {
if app != nil {
app.Destroy()
}
app = nil
})
BeforeEach(func() {
app = cutlass.New(Fixtures("staticfile_app"))
app.Buildpacks = []string{"staticfile_buildpack"}
app.SetEnv("BP_DEBUG", "1")
})
It("succeeds", func() {
PushAppAndConfirm(app)
Expect(app.Stdout.String()).To(ContainSubstring("HOOKS 1: BeforeCompile"))
Expect(app.Stdout.String()).To(ContainSubstring("HOOKS 2: AfterCompile"))
Expect(app.Stdout.String()).To(MatchRegexp("nginx -p .*/nginx -c .*/nginx/conf/nginx.conf"))
Expect(app.GetBody("/")).To(ContainSubstring("This is an example app for Cloud Foundry that is only static HTML/JS/CSS assets."))
_, headers, err := app.Get("/fixture.json", map[string]string{})
Expect(err).To(BeNil())
Expect(headers["Content-Type"]).To(Equal([]string{"application/json"}))
_, headers, err = app.Get("/lots_of.js", map[string]string{"Accept-Encoding": "gzip"})
Expect(err).To(BeNil())
Expect(headers).To(HaveKeyWithValue("Content-Encoding", []string{"gzip"}))
By("requesting a non-compressed version of a compressed file", func() {
By("with a client that can handle receiving compressed content", func() {
By("returns and handles the file", func() {
url, err := app.GetUrl("/war_and_peace.txt")
Expect(err).To(BeNil())
command := exec.Command("curl", "-s", "--compressed", url)
Expect(command.Output()).To(ContainSubstring("Leo Tolstoy"))
})
})
By("with a client that cannot handle receiving compressed content", func() {
By("returns and handles the file", func() {
url, err := app.GetUrl("/war_and_peace.txt")
Expect(err).To(BeNil())
command := exec.Command("curl", "-s", url)
Expect(command.Output()).To(ContainSubstring("Leo Tolstoy"))
})
})
})
apiVersionString, err := cutlass.ApiVersion()
Expect(err).To(BeNil())
apiVersion, err := semver.Make(apiVersionString)
Expect(err).To(BeNil())
apiHasTask, err := semver.ParseRange("> 2.75.0")
Expect(err).To(BeNil())
if apiHasTask(apiVersion) {
By("running a task", func() {
By("exits", func() {
command := exec.Command("cf", "run-task", app.Name, "wc -l public/index.html")
_, err := command.Output()
Expect(err).To(BeNil())
Eventually(func() string {
output, err := exec.Command("cf", "tasks", app.Name).Output()
Expect(err).To(BeNil())
return string(output)
}, "30s").Should(MatchRegexp("SUCCEEDED.*wc.*index.html"))
})
})
}
if cutlass.Cached {
By("with a cached buildpack", func() {
By("logs the files it downloads", func() {
Expect(app.Stdout.String()).To(ContainSubstring("Copy [/"))
})
})
} else {
By("with a uncached buildpack", func() {
By("logs the files it downloads", func() {
Expect(app.Stdout.String()).To(ContainSubstring("Download [https://"))
})
})
}
})
Describe("internet", func() {
var bpFile string
buildBpFile := func() {
var err error
localVersion := fmt.Sprintf("%s.%s", buildpackVersion, time.Now().Format("20060102150405"))
bpFile, err = packager.Package(bpDir, packager.CacheDir, localVersion, os.Getenv("CF_STACK"), cutlass.Cached)
Expect(err).To(BeNil())
}
AfterEach(func() { os.Remove(bpFile) })
Context("with a cached buildpack", func() {
BeforeEach(func() {
if !cutlass.Cached {
Skip("Running uncached tests")
}
buildBpFile()
})
It("does not call out over the internet", func() {
traffic, _, _, err := cutlass.InternetTraffic(
Fixtures("staticfile_app"),
bpFile,
[]string{},
)
Expect(err).To(BeNil())
Expect(traffic).To(HaveLen(0))
})
})
Context("with a uncached buildpack", func() {
var proxy *httptest.Server
BeforeEach(func() {
var err error
if cutlass.Cached {
Skip("Running cached tests")
}
buildBpFile()
proxy, err = cutlass.NewProxy()
Expect(err).To(BeNil())
})
AfterEach(func() {
os.Remove(bpFile)
proxy.Close()
})
It("uses a proxy during staging if present", func() {
traffic, _, _, err := cutlass.InternetTraffic(
Fixtures("staticfile_app"),
bpFile,
[]string{"HTTP_PROXY=" + proxy.URL, "HTTPS_PROXY=" + proxy.URL},
)
Expect(err).To(BeNil())
destUrl, err := url.Parse(proxy.URL)
Expect(err).To(BeNil())
Expect(cutlass.UniqueDestination(
traffic, fmt.Sprintf("%s.%s", destUrl.Hostname(), destUrl.Port()),
)).To(BeNil())
})
})
})
})
|
package entity
type Herd struct {
LabYaks []LabYak `xml:"labyak"`
}
type HerdPayload struct {
Herd []LabYakPayload `json:"herd"`
}
|
package frida_go
type ScriptOptions struct {
Name string
Runtime FridaScriptRuntime
}
|
/*
以 Unix 风格给出一个文件的绝对路径,你需要简化它。或者换句话说,将其转换为规范路径。
在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。更多信息请参阅:Linux / Unix中的绝对路径 vs 相对路径
请注意,返回的规范路径必须始终以斜杠 / 开头,并且两个目录名之间必须只有一个斜杠 /。最后一个目录名(如果存在)不能以 / 结尾。此外,规范路径必须是表示绝对路径的最短字符串。
示例 1:
输入:"/home/"
输出:"/home"
解释:注意,最后一个目录名后面没有斜杠。
示例 2:
输入:"/../"
输出:"/"
解释:从根目录向上一级是不可行的,因为根是你可以到达的最高级。
示例 3:
输入:"/home//foo/"
输出:"/home/foo"
解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。
示例 4:
输入:"/a/./b/../../c/"
输出:"/c"
示例 5:
输入:"/a/../../b/../c//.//"
输出:"/c"
示例 6:
输入:"/a//b////c/d//././/.."
输出:"/a/b/c"
*/
func simplifyPath(path string) string {
ans:=make([]string,1, len(path)/2+1) //栈
ans[0]=""
strslice:=strings.Split(path,"/")
for _,str:=range strslice{
if str==".." {
if(len(ans)-1<=0){ //检查,防止index out of range
continue
} else{
ans=ans[:len(ans)-1] //pop
}
}else if str=="."||str==""{ //如果前后都有"/",Split会在前后分出两个空串
continue
}else{ //push
ans=append(ans,str) //append需要一个接收者
}
}
if len(ans)==1{
return "/"
}
return strings.Join(ans,"/") //低空间复杂度的函数
}
|
// Using already Existing Slice
/*
For creating a slice from the given slice first you need to
specify the lower and upper bound, which means slice can take
elements from the given slice starting from the lower bound to
the upper bound. It does not include the elements above from the upper bound.
*/
package main
import "fmt"
func main() {
// Creating s slice
orignal_slice := []int{90, 60, 40, 50,
34, 49, 30}
// Creating slices from the given slice
var my_slice_1 = orignal_slice[1:5]
my_slice_2 := orignal_slice[0:]
my_slice_3 := orignal_slice[:6]
my_slice_4 := orignal_slice[:]
my_slice_5 := my_slice_3[2:4]
// Display the result
fmt.Println("Original Slice:", orignal_slice)
fmt.Println("New Slice 1:", my_slice_1)
fmt.Println("New Slice 2:", my_slice_2)
fmt.Println("New Slice 3:", my_slice_3)
fmt.Println("New Slice 4:", my_slice_4)
fmt.Println("New Slice 5:", my_slice_5)
}
// The default value of the lower bound is 0 and the default value of the upper bound
// is the total number of the elements present in the given slice.
|
package models
type User struct {
Model
Firstname string `json:"firstname`
Lastname string `json: "lastname"`
}
func (u *User) TableName() string {
return "user"
}
|
package deal
var publicKey = `-----BEGIN Pubkey-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk+89V7vpOj1rG6bTAKYM
56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xb
UAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCW
eItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331
hWRB4DlYy8qFUmDsyvvExe4NjZWblXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDi
aMD+Qt2Yp+Vvbz6hUiqIWSIH1BoHJer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvr
MQIDAQAB
-----END Pubkey-----
`
var Pirvatekey = `-----BEGIN Pirvatekey-----
MIIEpAIBAAKCAQEAk+89V7vpOj1rG6bTAKYM56qmFLwNCBVDJ3MltVVtxVUUByqc
5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xbUAEZuA3EjlPHIaFIVIz04RaW10+1
xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCWeItu1kNQ3MGdcuqKjke+LKhQ7nWP
RCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331hWRB4DlYy8qFUmDsyvvExe4NjZWb
lXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDiaMD+Qt2Yp+Vvbz6hUiqIWSIH1BoH
Jer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvrMQIDAQABAoIBAQCCbxZvHMfvCeg+
YUD5+W63dMcq0QPMdLLZPbWpxMEclH8sMm5UQ2SRueGY5UBNg0WkC/R64BzRIS6p
jkcrZQu95rp+heUgeM3C4SmdIwtmyzwEa8uiSY7Fhbkiq/Rly6aN5eB0kmJpZfa1
6S9kTszdTFNVp9TMUAo7IIE6IheT1x0WcX7aOWVqp9MDXBHV5T0Tvt8vFrPTldFg
IuK45t3tr83tDcx53uC8cL5Ui8leWQjPh4BgdhJ3/MGTDWg+LW2vlAb4x+aLcDJM
CH6Rcb1b8hs9iLTDkdVw9KirYQH5mbACXZyDEaqj1I2KamJIU2qDuTnKxNoc96HY
2XMuSndhAoGBAMPwJuPuZqioJfNyS99x++ZTcVVwGRAbEvTvh6jPSGA0k3cYKgWR
NnssMkHBzZa0p3/NmSwWc7LiL8whEFUDAp2ntvfPVJ19Xvm71gNUyCQ/hojqIAXy
tsNT1gBUTCMtFZmAkUsjqdM/hUnJMM9zH+w4lt5QM2y/YkCThoI65BVbAoGBAMFI
GsIbnJDNhVap7HfWcYmGOlWgEEEchG6Uq6Lbai9T8c7xMSFc6DQiNMmQUAlgDaMV
b6izPK4KGQaXMFt5h7hekZgkbxCKBd9xsLM72bWhM/nd/HkZdHQqrNAPFhY6/S8C
IjRnRfdhsjBIA8K73yiUCsQlHAauGfPzdHET8ktjAoGAQdxeZi1DapuirhMUN9Zr
kr8nkE1uz0AafiRpmC+cp2Hk05pWvapTAtIXTo0jWu38g3QLcYtWdqGa6WWPxNOP
NIkkcmXJjmqO2yjtRg9gevazdSAlhXpRPpTWkSPEt+o2oXNa40PomK54UhYDhyeu
akuXQsD4mCw4jXZJN0suUZMCgYAgzpBcKjulCH19fFI69RdIdJQqPIUFyEViT7Hi
bsPTTLham+3u78oqLzQukmRDcx5ddCIDzIicMfKVf8whertivAqSfHytnf/pMW8A
vUPy5G3iF5/nHj76CNRUbHsfQtv+wqnzoyPpHZgVQeQBhcoXJSm+qV3cdGjLU6OM
HgqeaQKBgQCnmL5SX7GSAeB0rSNugPp2GezAQj0H4OCc8kNrHK8RUvXIU9B2zKA2
z/QUKFb1gIGcKxYr+LqQ25/+TGvINjuf6P3fVkHL0U8jOG0IqpPJXO3Vl9B8ewWL
cFQVB/nQfmaMa4ChK0QEUe+Mqi++MwgYbRHx1lIOXEfUJO+PXrMekw==
-----END Pirvatekey-----
`
|
package main
import (
"fmt"
)
func makeEvenGenerator() func() int {
i := 0
return func() int {
i += 2
return i
}
}
func appendStr() func(string) string {
h := "Hello"
g := func(m string) string {
h = h + " " + m
return h
}
return g
}
func main() {
nextEven := makeEvenGenerator()
fmt.Println("initial state ", nextEven())
fmt.Println(nextEven())
fmt.Println(nextEven())
nextEven = makeEvenGenerator()
fmt.Println("back to initial state ", nextEven(), " \n ") // initial state
a := appendStr()
b := appendStr()
fmt.Println(a("World"))
fmt.Println(b("Everyone"))
fmt.Println(a("Gopher"))
fmt.Println(b("!"))
}
// closure more example : https://www.calhoun.io/5-useful-ways-to-use-closures-in-go/
|
package imageProcess
import (
"fmt"
"github.com/mojocn/primitive/primitive"
"github.com/nfnt/resize"
"log"
"math/rand"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"time"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
//ProccessImage
//mode 0=combo 1=triangle 2=rect 3=ellipse 4=circle 5=rotatedrect 6=beziers 7=rotatedellipse 8=polygon
//frameCount
func ProccessImage(inputImgPath, outputImagePath string, mode, shapeCount, frameCount, outputSize int) {
// seed random number generator
rand.Seed(time.Now().UTC().UnixNano())
// determine worker count
// read input image
input, _ := primitive.LoadImage(inputImgPath)
// scale down input image if needed
size := uint(outputSize)
if size > 0 {
input = resize.Thumbnail(size, size, input, resize.Bilinear)
}
// determine background color
bg := primitive.MakeColor(primitive.AverageImageColor(input))
// run algorithm
model := primitive.NewModel(input, bg, outputSize, runtime.NumCPU())
ext := strings.ToLower(filepath.Ext(outputImagePath))
percent := strings.Contains(outputImagePath, "%")
frameDelta := shapeCount / frameCount
frameDeltaBegin := shapeCount % frameCount
//fmt.Println(frameDelta,"/n")
start := time.Now()
for i := 0; i < shapeCount; i++ {
t := time.Now()
// write output image(s)
n := model.Step(primitive.ShapeType(mode), 0, 0)
nps := primitive.NumberString(float64(n) / time.Since(t).Seconds())
elapsed := time.Since(start).Seconds()
fmt.Printf("%d: t=%.3f, score=%.6f, n=%d, n/s=%s\n", i, elapsed, model.Score, n, nps)
isSaveFrame := percent && ext != ".gif"
isSaveFrame = isSaveFrame && (i+1)%frameDelta == frameDeltaBegin
isLastFrame := i == (shapeCount - 1)
if isSaveFrame || isLastFrame {
//设置output frame 函数
path := outputImagePath
if percent {
path = fmt.Sprintf(outputImagePath, i/frameDelta+1)
}
switch ext {
default:
check(fmt.Errorf("unrecognized file extension: %s", ext))
case ".png":
check(primitive.SavePNG(path, model.Context.Image()))
case ".jpg", ".jpeg":
check(primitive.SaveJPG(path, model.Context.Image(), 95))
case ".svg":
check(primitive.SaveFile(path, model.SVG()))
case ".gif":
frames := model.FramesForGif(frameCount)
fmt.Printf("%d,frames count", len(model.Shapes))
check(primitive.SaveGIFImageMagick(path, frames, 50, 250))
case ".mp4":
frames := model.Frames(0.0001)
check(primitive.SaveMp4(path, frames))
}
}
}
}
//ffmpeg -framerate 30 -i input_%05d.png -c:v libx264 -crf 23 -pix_fmt yuv420p output.mp4
//https://stackoverflow.com/questions/13163106/ffmpeg-converting-image-sequence-to-video-results-in-blank-video
//https://github.com/leafo/gifserver/blob/master/gifserver/gif.go
// ffmpeg -i "$pattern" -pix_fmt yuv420p -vf 'scale=trunc(in_w/2)*2:trunc(in_h/2)*2' "${out_base}.mp4"
func ConvertPngFramesToMP4(dir, imageNamePatern string) (string, error) {
fmt.Print("Encoding ", dir, " to mp4")
outFname := "out.mp4"
cmd := exec.Command("ffmpeg",
"-i", imageNamePatern,
"-pix_fmt", "yuv420p",
"-vf", "scale=trunc(in_w/2)*2:trunc(in_h/2)*2",
outFname)
cmd.Dir = dir
err := cmd.Run()
if err != nil {
return "", err
}
return path.Join(dir, outFname), nil
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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.
// Code generated from the elasticsearch-specification DO NOT EDIT.
// https://github.com/elastic/elasticsearch-specification/tree/33e8a1c9cad22a5946ac735c4fba31af2da2cec2
package types
import (
"bytes"
"encoding/json"
"errors"
"io"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/followerindexstatus"
)
// FollowerIndex type.
//
// https://github.com/elastic/elasticsearch-specification/blob/33e8a1c9cad22a5946ac735c4fba31af2da2cec2/specification/ccr/follow_info/types.ts#L22-L28
type FollowerIndex struct {
FollowerIndex string `json:"follower_index"`
LeaderIndex string `json:"leader_index"`
Parameters *FollowerIndexParameters `json:"parameters,omitempty"`
RemoteCluster string `json:"remote_cluster"`
Status followerindexstatus.FollowerIndexStatus `json:"status"`
}
func (s *FollowerIndex) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
for {
t, err := dec.Token()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
switch t {
case "follower_index":
if err := dec.Decode(&s.FollowerIndex); err != nil {
return err
}
case "leader_index":
if err := dec.Decode(&s.LeaderIndex); err != nil {
return err
}
case "parameters":
if err := dec.Decode(&s.Parameters); err != nil {
return err
}
case "remote_cluster":
if err := dec.Decode(&s.RemoteCluster); err != nil {
return err
}
case "status":
if err := dec.Decode(&s.Status); err != nil {
return err
}
}
}
return nil
}
// NewFollowerIndex returns a FollowerIndex.
func NewFollowerIndex() *FollowerIndex {
r := &FollowerIndex{}
return r
}
|
package main
import (
"flag"
"net/http"
"github.com/golang/glog"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/danielfm/crypto-exporter/collector"
)
var (
// VERSION set by build script
VERSION = "UNKNOWN"
addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
metricsEndpoint = flag.String("endpoint", "/metrics", "Path under which to expose metrics.")
metricsNamespace = flag.String("namespace", "crypto", "Metrics namespace.")
)
func init() {
flag.Parse()
// TODO: always log to stderr for now
flag.Set("logtostderr", "true")
}
func main() {
glog.Infof("Crypto Exporter v%s started, listening on %s.", VERSION, *addr)
glog.Infof("Parameters: endpoint=%s, namespace=%s", *metricsEndpoint, *metricsNamespace)
metrics := collector.NewCryptoExchangeMetrics(*metricsNamespace)
// Registers collectors for each supported exchange
bitcointradeCollector := collector.NewBitcointradeCollector(metrics)
prometheus.Register(bitcointradeCollector)
// Stream metrics from each supported exchange in background
go bitcointradeCollector.Connect()
http.Handle(*metricsEndpoint, promhttp.Handler())
glog.Fatal(http.ListenAndServe(*addr, nil))
}
|
package controllers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"github.com/shimastripe/gouserapi/db"
"github.com/shimastripe/gouserapi/models"
"github.com/shimastripe/gouserapi/server"
"testing"
)
var uuid string
func TestGetUsers(t *testing.T) {
response := httptest.NewRecorder()
database := db.Connect()
s := server.Setup(database)
req, err := http.NewRequest("GET", "http://localhost:8080/api/users", nil)
if err != nil {
t.Error(err)
}
s.ServeHTTP(response, req)
if response.Code != http.StatusOK {
t.Errorf("Got error for GET request to /api/users")
}
}
func TestCreateUser(t *testing.T) {
response := httptest.NewRecorder()
database := db.Connect()
s := server.Setup(database)
requestParams := `{
"name": "NAME",
"account_name": "ACCOUNTNAME",
"email": "EMAIL"
}`
req, err := http.NewRequest("POST", "http://localhost:8080/api/users", bytes.NewBuffer([]byte(requestParams)))
if err != nil {
t.Error(err)
}
// Content-Type 設定
req.Header.Set("Content-Type", "application/json")
s.ServeHTTP(response, req)
if response.Code != http.StatusCreated {
t.Errorf("Got error for POST request to /api/users")
}
body := json.NewDecoder(response.Body)
var user models.User
body.Decode(&user)
if user.Name != "NAME" ||
user.AccountName != "ACCOUNTNAME" ||
user.Email != "EMAIL" {
t.Errorf("Create build failed.\nGot: %v", user)
}
uuid = strconv.Itoa(int(user.ID))
}
func TestGetUser(t *testing.T) {
response := httptest.NewRecorder()
database := db.Connect()
s := server.Setup(database)
req, err := http.NewRequest("GET", "http://localhost:8080/api/users/"+uuid, nil)
if err != nil {
t.Error(err)
}
s.ServeHTTP(response, req)
if response.Code != http.StatusOK {
t.Errorf("Got error for GET request to /api/users/" + uuid)
}
body := json.NewDecoder(response.Body)
var user models.User
body.Decode(&user)
if user.Name != "NAME" ||
user.AccountName != "ACCOUNTNAME" ||
user.Email != "EMAIL" {
t.Errorf("Show build failed.\nGot: %v", user)
}
}
func TestUpdateUser(t *testing.T) {
response := httptest.NewRecorder()
database := db.Connect()
s := server.Setup(database)
requestParams := `{
"name": "NAME_2",
"account_name": "ACCOUNTNAME_2",
"email": "EMAIL_2"
}`
req, err := http.NewRequest("PUT", "http://localhost:8080/api/users/"+uuid, bytes.NewBuffer([]byte(requestParams)))
if err != nil {
t.Error(err)
}
// Content-Type 設定
req.Header.Set("Content-Type", "application/json")
s.ServeHTTP(response, req)
if response.Code != http.StatusOK {
t.Errorf("Got error for PUT request to /api/users/" + uuid)
}
body := json.NewDecoder(response.Body)
var user models.User
body.Decode(&user)
if user.Name != "NAME_2" ||
user.AccountName != "ACCOUNTNAME_2" ||
user.Email != "EMAIL_2" {
t.Errorf("Update build failed.\nGot: %v", user)
}
}
func TestDeleteUser(t *testing.T) {
response := httptest.NewRecorder()
database := db.Connect()
s := server.Setup(database)
req, err := http.NewRequest("DELETE", "http://localhost:8080/api/users/"+uuid, nil)
if err != nil {
t.Error(err)
}
s.ServeHTTP(response, req)
if response.Code != http.StatusNoContent {
t.Errorf("Got error for DELETE request to /api/users/" + uuid)
}
}
|
package logger
import "testing"
func TestInfo(t *testing.T) {
Info("test")
}
|
package models
import (
"encoding/hex"
"errors"
"math/big"
"github.com/appditto/pippin_nano_wallet/libs/utils"
"github.com/appditto/pippin_nano_wallet/libs/utils/ed25519"
"golang.org/x/crypto/blake2b"
)
// StateBlock is a block from the nano protocol
type StateBlock struct {
Type string `json:"type" mapstructure:"type"`
Hash string `json:"hash" mapstructure:"hash"`
Account string `json:"account" mapstructure:"account"`
Previous string `json:"previous" mapstructure:"previous"`
Representative string `json:"representative" mapstructure:"representative"`
Balance string `json:"balance" mapstructure:"balance"`
Link string `json:"link" mapstructure:"link"`
LinkAsAccount string `json:"link_as_account,omitempty" mapstructure:"link_as_account,omitempty"`
Work string `json:"work" mapstructure:"work"`
Signature string `json:"signature" mapstructure:"signature"`
Banano bool `json:"-"`
}
func (b *StateBlock) computeHash() error {
h, err := blake2b.New256(nil)
if err != nil {
return err
}
h.Write(make([]byte, 31))
h.Write([]byte{6})
pubkey, err := utils.AddressToPub(b.Account, b.Banano)
if err != nil {
return err
}
h.Write(pubkey)
previous, err := hex.DecodeString(b.Previous)
if err != nil {
return err
}
h.Write(previous)
pubkey, err = utils.AddressToPub(b.Representative, b.Banano)
if err != nil {
return err
}
h.Write(pubkey)
// COnvert balance to big int
balance, ok := big.NewInt(0).SetString(b.Balance, 10)
if !ok {
return errors.New("Invalid balance")
}
h.Write(balance.FillBytes(make([]byte, 16)))
link, err := hex.DecodeString(b.Link)
if err != nil {
return err
}
h.Write(link)
b.Hash = hex.EncodeToString(h.Sum(nil))
return nil
}
func (b *StateBlock) Sign(privateKey ed25519.PrivateKey) error {
if err := b.computeHash(); err != nil {
return err
}
hash, err := hex.DecodeString(b.Hash)
if err != nil {
return err
}
sig := ed25519.Sign(privateKey, hash)
b.Signature = hex.EncodeToString(sig)
return nil
}
|
package util
import (
"gin_example/src/gin-blog/pkg/logging"
"github.com/astaxie/beego/validation"
)
/** 输出 valid Error */
func PrintValidError(errs []*validation.Error) {
for _, err := range errs {
logging.Info(err.Key, err.Message)
}
}
|
package main
import (
"fmt"
"io"
"os"
)
func main() {
args := os.Args
index := len(args) - 1
fileToOpen := args[index]
if index == 0 || index > 1 {
fmt.Println("Program only accepts one and only one argument. Check your command and try again.")
os.Exit(1)
}
//Easy way to do things:
/*
bs, err := ioutil.ReadFile(fileToOpen)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println(string(bs))
*/
file, err := os.Open(fileToOpen) // For read access.
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
io.Copy(os.Stdout, file)
}
|
package knob
import (
"fmt"
"reflect"
)
func PrintKnobs(e interface{}) error {
// e must be a pointer to struct.
ptr := reflect.ValueOf(e)
if ptr.Kind() != reflect.Ptr {
return fmt.Errorf("knob: expected a pointer to struct but was %v", reflect.TypeOf(e))
}
v := ptr.Elem()
if v.Kind() != reflect.Struct {
return fmt.Errorf("knob: expected a pointer to struct but was %v", reflect.TypeOf(e))
}
t := v.Type()
for i := 0; i < v.NumField(); i++ {
vf := reflect.Indirect(v.Field(i))
tf := t.Field(i)
if tf.PkgPath != "" {
continue
}
switch vf.Kind() {
case reflect.Struct:
err := PrintKnobs(vf.Addr().Interface())
if err != nil {
return err
}
case reflect.Slice:
fallthrough
case reflect.Array:
for j := 0; j < vf.Len(); j++ {
err := PrintKnobs(reflect.Indirect(vf.Index(j)).Addr().Interface())
if err != nil {
return err
}
}
default:
if tf.Tag.Get("knob") != "" {
fmt.Println(tf.Name, tf.Type, vf.Kind(), tf.Tag.Get("knob"))
}
}
}
return nil
}
|
package middleware
import (
"fmt"
"net/http"
"os"
"github.com/44t4nk1/jwt-go/api/models"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var mySigningKey = []byte(os.Getenv("ACCESS_SECRET"))
func IsAuthorised(endpoint func(c *gin.Context)) gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) {
if c.GetHeader("Token") != "" {
token, err := jwt.Parse(c.GetHeader("Token"), func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("there was an Error")
}
return mySigningKey, nil
})
if err != nil {
var Response = models.Response{
Error: true,
Message: "Invalid Signature",
}
c.JSON(http.StatusUnauthorized, Response)
}
if token.Valid {
endpoint(c)
}
} else {
var Response = models.Response{
Error: true,
Message: "No token provided",
}
c.JSON(http.StatusUnauthorized, Response)
}
})
}
|
package main
import (
"context"
"fmt"
"log"
multipb "github.com/golang-grpc-snippet/drill_exercise_1/multiplication/protobuf"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("Error : %v", err)
}
c := multipb.NewMultiServiceClient(conn)
doUnary(c)
}
func doUnary(c multipb.MultiServiceClient) {
nilai := &multipb.MultiRequest{
Num: &multipb.Number{
First: 30,
Second: 3,
},
}
res, err := c.Multiplication(context.Background(), nilai)
if err != nil {
log.Fatalf("Error : %v", err)
}
fmt.Println("Hasil : ", res.GetResult())
}
|
/*
File describe gateway for working with vehicle data in database.
Author: Igor Kuznetsov
Email: me@swe-notes.ru
(c) Copyright by Igor Kuznetsov.
*/
package models
type VehicleGateway interface {
GetVehicleDict() (Vehicles, error)
AddVehicle(VehicleRec) error
}
type VehicleRec struct {
GpsID int `json:"gps_id"`
GosNumber string `json:"gos_number"`
}
type Vehicles []VehicleRec
func (db *DB) GetVehicleDict() (Vehicles, error) {
result := Vehicles{}
rows, err := db.Query(`select gps_code, gos_number from vehicle`)
if err != nil {
return result, err
}
defer rows.Close()
for rows.Next() {
r := VehicleRec{}
if err := rows.Scan(&r.GpsID, &r.GosNumber); err != nil {
return result, err
}
result = append(result, r)
}
err = rows.Err()
return result, err
}
func (db *DB) AddVehicle(v VehicleRec) error {
_, err := db.Exec(`insert into vehicle (gos_number, gps_code) values ($1, $2)`, v.GosNumber, v.GpsID)
return err
}
|
package main
import (
"fmt"
"github.com/gudongkun/single_common"
"github.com/gudongkun/single_common/custom_gorm"
"github.com/gudongkun/single_common/jaeger"
"github.com/gudongkun/single_ucenter/enlight_ucenter_client"
"github.com/gudongkun/single_ucenter/enlight_ucenter_client/proto/user"
"github.com/gudongkun/single_ucenter/global"
"github.com/gudongkun/single_ucenter/handler"
"github.com/gudongkun/single_ucenter/subscriber"
log "github.com/micro/go-micro/v2/logger"
)
func main() {
//初始化gorm
custom_gorm.InitEngine(global.Conf.Dsn)
//初始化casbin
global.InitCasbin(global.Conf.CasbinDsn)
//初始化xorm
//custom_xorm.InitEngine( "root:123456@(localhost:3306)/single?charset=utf8mb4")
//初始化jaeger
jaeger.NewJaegerTracer(global.Conf.Service, global.Conf.Jaeger)
//初始化 用户服务
enlight_ucenter_client.InitService(global.Conf.Service,global.Conf.Consul,global.Conf.ServiceAddr)
enlight_ucenter_client.UCenterService.Init()
// 注册服务处理程序
user.RegisterUserHandler(enlight_ucenter_client.UCenterService.Server(), new(handler.User))
// broker方式 注册消息处理
pubSub := enlight_ucenter_client.UCenterService.Server().Options().Broker
if err := pubSub.Connect(); err != nil {
log.Fatal(err)
}
suber, _ := pubSub.Subscribe("sayHello", subscriber.SayHelloBroker)
defer func() {
fmt.Println("client close conn and Unsubscribe")
pubSub.Disconnect() //关闭链接
suber.Unsubscribe() //取消订阅
}()
// broker方式 注册消息处理结束
go single_common.PrometheusBoot(8050)
// Run service
if err := enlight_ucenter_client.UCenterService.Run(); err != nil {
log.Fatal(err)
}
}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package gkehub includes all of the code for gkehub.
package alpha
import (
"bytes"
"context"
"strings"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl/operations"
)
func expandHubReferenceLink(_ *Client, val *string, _ *Membership) (interface{}, error) {
if val == nil {
return nil, nil
}
v := *val
if strings.HasPrefix(v, "https:") {
return strings.Replace(strings.Replace(strings.Replace(*val, "https:", "", 1), "v1/", "", 1), "v1beta1/", "", 1), nil
} else if strings.HasPrefix(v, "//container.googleapis.com") {
return v, nil
}
return "//container.googleapis.com/" + v, nil
}
func flattenHubReferenceLink(_ *Client, config interface{}, _ *Membership) *string {
v, ok := config.(string)
if !ok {
return nil
}
v = strings.Replace(v, "//container.googleapis.com/", "", 1)
return &v
}
// Feature has custom url methods because it uses v1beta endpoints instead of v1beta1.
func (r *Feature) getURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
"name": dcl.ValueOrEmptyString(nr.Name),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/features/{{name}}", "https://gkehub.googleapis.com/v1beta/", userBasePath, params), nil
}
func (r *Feature) listURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/features", "https://gkehub.googleapis.com/v1beta/", userBasePath, params), nil
}
func (r *Feature) createURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"name": dcl.ValueOrEmptyString(nr.Name),
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/features?featureId={{name}}", "https://gkehub.googleapis.com/v1beta/", userBasePath, params), nil
}
func (r *Feature) deleteURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"name": dcl.ValueOrEmptyString(nr.Name),
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/features/{{name}}", "https://gkehub.googleapis.com/v1beta/", userBasePath, params), nil
}
func (op *updateFeatureUpdateFeatureOperation) do(ctx context.Context, r *Feature, c *Client) error {
_, err := c.GetFeature(ctx, r)
if err != nil {
return err
}
u, err := r.updateURL(c.Config.BasePath, "UpdateFeature")
if err != nil {
return err
}
u = strings.Replace(u, "v1beta1", "v1beta", 1)
u, err = dcl.AddQueryParams(u, map[string]string{"updateMask": "labels,spec"})
if err != nil {
return err
}
req, err := newUpdateFeatureUpdateFeatureRequest(ctx, r, c)
if err != nil {
return err
}
c.Config.Logger.Infof("Created update: %#v", req)
body, err := marshalUpdateFeatureUpdateFeatureRequest(c, req)
if err != nil {
return err
}
resp, err := dcl.SendRequest(ctx, c.Config, "PATCH", u, bytes.NewBuffer(body), c.Config.RetryProvider)
if err != nil {
return err
}
var o operations.StandardGCPOperation
if err := dcl.ParseResponse(resp.Response, &o); err != nil {
return err
}
err = o.Wait(ctx, c.Config, "https://gkehub.googleapis.com/v1beta/", "GET")
if err != nil {
return err
}
return nil
}
|
// test-syncMap project main.go
package main
import (
"fmt"
"sync"
)
func main() {
fmt.Println("Hello World!")
var scene sync.Map
scene.Store("")
}
|
package core
import (
"strconv"
)
//operation
type Operation interface {
Run()
}
//simplest operation
type operation func()
func (o operation) Run() {
o()
}
//task
type Task struct {
Done chan bool
Operation Operation
}
func NewFuncTask(f func()) *Task {
return NewTask(operation(f))
}
//new simplest task
func NewTask(o Operation) *Task {
t := &Task{}
t.Done = make(chan bool, 1)
t.Operation = o
return t
}
//task queue is chan
type TaskQueue chan *Task
//interface method
func (tq TaskQueue) run(size int) {
for i := 0; i < size; i++ {
go func() {
for {
t := <-tq
t.Operation.Run()
t.Done <- true
}
}()
}
}
func NewTaskQueue(size int, cacheSize int) TaskQueue {
if size <= int(0) {
panic("task queue size should more than zero " + strconv.Itoa(size))
}
if cacheSize < int(0) {
panic("cache task size should no less than zero " + strconv.Itoa(size))
}
tempOp := TaskQueue(make(chan *Task, cacheSize))
tempOp.run(size)
return tempOp
}
|
package webservice
import (
"encoding/json"
"io/ioutil"
)
// 程序配置
type Config struct {
BackServiceTls bool `json:"backServiceTls"`
WsPort int `json:"wsPort"`
WsReadTimeout int `json:"wsReadTimeout"`
WsWriteTimeout int `json:"wsWriteTimeout"`
WsInChannelSize int `json:"wsInChannelSize"`
WsOutChannelSize int `json:"wsOutChannelSize"`
WsHeartbeatInterval int `json:"wsHeartbeatInterval"`
ServicePort int `json:"servicePort"`
ServiceReadTimeout int `json:"serviceReadTimeout"`
ServiceWriteTimeout int `json:"serviceWriteTimeout"`
MaxJoinRoom int `json:"maxJoinRoom"`
ServerPem string `json:"serverPem"`
ServerKey string `json:"serverKey"`
}
var (
G_config *Config
)
func defaultConfig() {
G_config = &Config{
WsPort: 123,
WsReadTimeout: 2000,
WsWriteTimeout: 2000,
WsInChannelSize: 1000,
WsOutChannelSize: 1000,
WsHeartbeatInterval: 60,
ServicePort: 456,
ServiceReadTimeout: 2000,
ServiceWriteTimeout: 2000,
MaxJoinRoom: 5,
BackServiceTls: false,
}
}
func init() {
var (
content []byte
conf Config
err error
)
if content, err = ioutil.ReadFile("application.json"); err != nil {
defaultConfig()
return
}
if err = json.Unmarshal(content, &conf); err == nil {
G_config = &conf
}
return
}
|
package main
func main() {}
func search(x []int, k int) int {
i := 0
basePos := 0
for i < len(x)-1 {
if x[i]-x[basePos] < k {
} else if x[i]-x[basePos] == k {
} else {
}
}
return -1
}
|
/*
* Copyright (C) 2019 Rohith Jayawardene <gambol99@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package namespaceclaim
import (
"context"
kubev1 "github.com/appvia/kube-operator/pkg/apis/kube/v1"
corev1 "github.com/appvia/hub-apis/pkg/apis/core/v1"
"github.com/appvia/hub-apiserver/pkg/hub"
"github.com/gambol99/hub-utils/pkg/finalizers"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Delete is responsible for removig the namespace claim any remote configuration
func (r *ReconcileNamespaceClaim) Delete(
ctx context.Context,
cl client.Client,
client kubernetes.Interface,
resource *kubev1.NamespaceClaim) error {
phase := resource.Status.Phase
rlog := log.WithValues(
"namespace.name", resource.Spec.Name,
"resource.name", resource.Name,
"resource.namespace", resource.Namespace,
"resource.team", resource.GetLabels()[hub.Label("team")],
"resource.workspace", resource.GetLabels()[hub.Label("workspace")],
)
// @step: check if we are the current finalizer
finalizer := finalizers.NewFinalizer(cl, FinalizerName)
if !finalizer.IsDeletionCandidate(resource) {
rlog.WithValues(
"finalizers", resource.GetFinalizers(),
).Info("skipping finalization until others have cleaned up")
return nil
}
err := func() error {
// @step: check the current phase of the claim and if not 'CREATED' we can forgo
if phase != PhaseInstalled {
log.Info("skipping the finalizer as the resource was never installed")
return nil
}
log.Info("deleting the namespaceclaim from the cluster")
// @step: delete the namespace
if err := client.CoreV1().Namespaces().Delete(resource.Spec.Name, &metav1.DeleteOptions{}); err != nil {
if kerrors.IsNotFound(err) {
// @logic - cool we having nothing to do then
resource.Status.Status = metav1.StatusSuccess
return nil
}
resource.Status.Conditions = []corev1.Condition{{Message: "failed to delete the namespace in cluster"}}
return err
}
return nil
}()
if err != nil {
resource.Status.Status = corev1.FailureStatus
resource.Status.Conditions = []corev1.Condition{{
Detail: err.Error(),
Message: "failed to delete namespaceclaim",
}}
return err
}
// @step: remove the finalizer if one and allow the resource it be deleted
if err := finalizer.Remove(resource); err != nil {
resource.Status.Status = corev1.FailureStatus
resource.Status.Conditions = []corev1.Condition{{
Detail: err.Error(),
Message: "failed to remove the finalizer",
}}
return err
}
return nil
}
|
package guard
import (
"testing"
"time"
floc "gopkg.in/workanator/go-floc.v1"
"gopkg.in/workanator/go-floc.v1/run"
)
func TestTimeout(t *testing.T) {
const ID int = 1
f := floc.NewFlow()
s := floc.NewState(nil)
// Make timeout in 1 seconds with the job which should finish prior
// the timeout
job := run.Sequence(
Timeout(ConstTimeout(time.Second), ID, func(floc.Flow, floc.State, floc.Update) {}),
Complete(nil),
)
floc.Run(f, s, nil, job)
result, _ := f.Result()
if !result.IsCompleted() {
t.Fatalf("%s expects result to be %s but has %s", t.Name(), floc.Completed.String(), result)
}
}
func TestTimeoutWithDefaultBehavior(t *testing.T) {
const ID int = 2
f := floc.NewFlow()
s := floc.NewState(nil)
// Make timeout in 50 milliseconds while job start is delayed by
// 200 milliseconds so the timeout should fire first
job := Timeout(ConstTimeout(50*time.Millisecond), ID,
run.Delay(200*time.Millisecond, Complete(nil)),
)
floc.Run(f, s, nil, job)
result, _ := f.Result()
if !result.IsCanceled() {
t.Fatalf("%s expects result to be %s but has %s", t.Name(), floc.Canceled.String(), result)
}
}
func TestTimeoutWithTrigger(t *testing.T) {
const ID int = 3
f := floc.NewFlow()
s := floc.NewState(nil)
// Make deadline 50 milliseconds in the future and with the job which should
// run with the delay in 200 milliseconds so the trigger should be invoked
job := TimeoutWithTrigger(
ConstTimeout(50*time.Millisecond),
ID,
run.Delay(200*time.Millisecond, Complete(nil)),
func(flow floc.Flow, state floc.State, id interface{}) {
ident, ok := id.(int)
if !ok {
t.Fatalf("%s expects data to be int but has %T", t.Name(), ident)
}
if id != ID {
t.Fatalf("%s expects ID to be %d but has %d", t.Name(), ID, id)
}
flow.Cancel(nil)
},
)
floc.Run(f, s, nil, job)
result, _ := f.Result()
if !result.IsCanceled() {
t.Fatalf("%s expects result to be %s but has %s", t.Name(), floc.Canceled.String(), result)
}
}
|
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func test() {
filename := "/tmp/fstab"
open, err := os.Open(filename)
if err != nil {
panic(err)
}
r := bufio.NewReader(open)
for {
readString, err := r.ReadString('\n')
if err == io.EOF {
return
}
if err != nil {
panic(err)
}
if strings.Index(readString, "UUID") != -1 {
fmt.Printf(readString)
}
}
}
func main() {
test()
}
|
// 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 (
"fmt"
"os"
"github.com/scaleway/scaleway-cli/pkg/config"
)
// LogoutArgs are flags for the `RunLogout` function
type LogoutArgs struct{}
// RunLogout is the handler for 'scw logout'
func RunLogout(ctx CommandContext, args LogoutArgs) error {
// FIXME: ask if we need to remove the local ssh key on the account
scwrcPath, err := config.GetConfigFilePath()
if err != nil {
return fmt.Errorf("unable to get scwrc config file path: %v", err)
}
if _, err = os.Stat(scwrcPath); err == nil {
err = os.Remove(scwrcPath)
if err != nil {
return fmt.Errorf("unable to remove scwrc config file: %v", err)
}
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.