text stringlengths 11 4.05M |
|---|
// Copyright 2019 The OpenSDS 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 eternus
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
"testing"
. "github.com/sodafoundation/dock/contrib/drivers/utils/config"
"github.com/sodafoundation/dock/pkg/model"
pb "github.com/sodafoundation/dock/pkg/model/proto"
uuid "github.com/satori/go.uuid"
mock "github.com/stretchr/testify/mock"
)
func checkArg(actual string, expected string) bool {
actualArr := deleteEmptyStr(strings.Split(actual, " "))
expectedArr := deleteEmptyStr(strings.Split(expected, " "))
// same number of element
if len(actualArr) != len(expectedArr) {
return false
}
// same command and args
for i := 0; i < len(actualArr); i = i + 2 {
match := false
for k := 0; k < len(expectedArr); k = k + 2 {
if actualArr[i] == expectedArr[k] &&
actualArr[i+1] == expectedArr[k+1] {
match = true
break
}
}
if match {
continue
}
return false
}
return true
}
func deleteEmptyStr(arr []string) []string {
ret := []string{}
for _, v := range arr {
if v != "" && v != "\n" {
ret = append(ret, v)
}
}
return ret
}
func TestListPools(t *testing.T) {
execCmd := "show thin-pro-pools\n"
outStr := "\r\nCLI> show thin-pro-pools\r\n"
outStr += "00\r\n"
outStr += "00000000\r\n"
outStr += "0004\r\n"
outStr += "0011\tosdstest\t01\t00\t04\t0010\t00000000666FC000\t0000000000000000\t01\t5A\t4B\t00\t00\t00\t0000000000200000\t00000001\tFF\t01\r\n"
outStr += "0012\tpoolname\t01\t00\t04\t0010\t00000000666FC000\t0000000000000000\t01\t5A\t4B\t00\t00\t00\t0000000000200000\t00000001\tFF\t01\r\n"
outStr += "0013\tpoolname2\t01\t00\t04\t0010\t0000000019000000\t0000000018000000\t01\t5A\t4B\t00\t00\t00\t0000000000200000\t00000001\tFF\t01\r\n"
outStr += "0014\tpoolname3\t01\t00\t04\t0010\t0000000000000000\t0000000000000000\t01\t5A\t4B\t00\t00\t00\t0000000000200000\t00000001\tFF\t01\r\n"
outStr += "CLI> "
client := createIOMock(execCmd, outStr)
d := &Driver{
conf: &EternusConfig{
AuthOptions: AuthOptions{
Endpoint: "1.2.3.4",
},
Pool: map[string]PoolProperties{
"poolname": PoolProperties{
Extras: model.StoragePoolExtraSpec{
DataStorage: model.DataStorageLoS{
ProvisioningPolicy: "Thin",
},
},
StorageType: "block",
AvailabilityZone: "az-test",
},
"poolname2": PoolProperties{
Extras: model.StoragePoolExtraSpec{
DataStorage: model.DataStorageLoS{
ProvisioningPolicy: "Thin",
},
},
StorageType: "block",
},
},
},
client: client,
}
ret, err := d.ListPools()
if err != nil {
t.Error("Test ListPools failed")
}
if len(ret) != 2 {
t.Error("Test ListPools failed")
}
host, _ := os.Hostname()
name := fmt.Sprintf("%s:%s:%s", host, d.conf.Endpoint, "18")
id := uuid.NewV5(uuid.NamespaceOID, name).String()
if ret[0].BaseModel.Id != id || ret[0].Name != "poolname" ||
ret[0].TotalCapacity != 819 || ret[0].FreeCapacity != 819 ||
ret[0].StorageType != "block" || ret[0].AvailabilityZone != "az-test" ||
ret[0].Extras.DataStorage.ProvisioningPolicy != "Thin" {
t.Error("Test ListPools failed")
}
name = fmt.Sprintf("%s:%s:%s", host, d.conf.Endpoint, "19")
id = uuid.NewV5(uuid.NamespaceOID, name).String()
if ret[1].BaseModel.Id != id || ret[1].Name != "poolname2" ||
ret[1].TotalCapacity != 200 || ret[1].FreeCapacity != 8 ||
ret[1].StorageType != "block" || ret[1].AvailabilityZone != "default" ||
ret[1].Extras.DataStorage.ProvisioningPolicy != "Thin" {
t.Error("Test ListPools failed")
}
}
func TestCreateVolume(t *testing.T) {
id := "volumeid"
size := "1"
sizeInt, _ := strconv.ParseInt(size, 10, 64)
hashname := GetFnvHash(id)
poolname := "poolname"
opt := &pb.CreateVolumeOpts{
Id: id,
Name: "volumename",
Size: sizeInt,
Description: "test description",
AvailabilityZone: "default",
PoolId: "poolid",
PoolName: poolname,
Metadata: map[string]string{},
DriverName: "drivername",
Context: "",
}
execCmd := "create volume -name " + hashname
execCmd += " -size " + size + "gb"
execCmd += " -pool-name " + poolname
execCmd += " -type tpv -allocation thin \n"
outStr := "\r\nCLI> " + execCmd + " \r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "11\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmd)
}),
).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser := new(MockReadCloser)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
Pool: map[string]PoolProperties{
"poolname": PoolProperties{
Extras: model.StoragePoolExtraSpec{
DataStorage: model.DataStorageLoS{
ProvisioningPolicy: "Thin",
},
},
},
},
},
client: client,
}
ret, err := d.CreateVolume(opt)
if err != nil {
t.Error("Test CreateVolume failed")
}
if ret.BaseModel.Id != id || ret.Name != opt.Name ||
ret.Size != sizeInt || ret.Description != opt.Description ||
ret.AvailabilityZone != opt.AvailabilityZone ||
ret.Metadata[KLunId] != "17" {
t.Error("Test CreateVolume failed")
}
}
func TestDeleteVolume(t *testing.T) {
opt := &pb.DeleteVolumeOpts{
Id: "id",
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
}
execCmd := "delete volume -volume-number 21 \n"
outStr := "\r\nCLI> " + execCmd + " \r\n"
outStr += "00\r\n"
outStr += "CLI> "
client := createIOMock(execCmd, outStr)
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
err := d.DeleteVolume(opt)
if err != nil {
t.Error("Test DeleteVolume failed")
}
}
func TestExtendVolume(t *testing.T) {
id := "volumeid"
lunid := "21"
size := "2"
sizeInt, _ := strconv.ParseInt(size, 10, 64)
poolname := "poolname"
opt := &pb.ExtendVolumeOpts{
Id: id,
Name: "volumename",
Size: sizeInt,
Description: "test description",
AvailabilityZone: "default",
PoolId: "poolid",
PoolName: poolname,
Metadata: map[string]string{
KLunId: lunid,
},
DriverName: "drivername",
Context: "",
}
execCmd := "expand volume -volume-number " + lunid
execCmd += " -size " + size + "gb \n"
outStr := "\r\nCLI> " + execCmd + " \r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmd)
}),
).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser := new(MockReadCloser)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
ret, err := d.ExtendVolume(opt)
if err != nil {
t.Error("Test ExtendVolume failed")
}
if ret.BaseModel.Id != id || ret.Name != opt.Name ||
ret.Size != opt.Size || ret.Description != opt.Description ||
ret.AvailabilityZone != opt.AvailabilityZone {
t.Error("Test ExtendVolume failed")
}
}
func TestInitializeConnection_IscsiNoPort(t *testing.T) {
opt := &pb.CreateVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
DoLocalAttach: false,
MultiPath: false,
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: "hostname",
Ip: "1.1.1.1",
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: "iscsi",
PortName: "iqn.testtest",
},
},
},
Metadata: map[string]string{
KLunId: "1",
},
DriverName: "drivername",
Context: "",
AccessProtocol: "iscsi",
}
execCmd := "show iscsi-parameters\n"
outStr := "CLI> show iscsi-parameters\r\n"
outStr += "00\r\n"
outStr += "04\r\n"
outStr += "50\t00\t01\t00\tiqn.eternus-dx1\t\tFF\tDefault\t01\t00\t192.168.1.1\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0001\t00\tFFFF\t0514\t0000\t\t::\t::\t::\tFF\tFF\t80000000\tFF\tFF\r\n"
outStr += "50\t01\t00\t01\tiqn.eternus-dx2\t\tFF\tDefault\t01\t00\t192.166.1.2\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0000\t00\tFFFF\t0514\t0000\t\t::\t::\t::\t00\t00\t80000000\t00\tFF\r\n"
outStr += "51\t00\t04\t01\tiqn.eternus-dx3\t\t00\tDefault\t01\t00\t192.168.1.2\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0000\t00\tFFFF\t0514\t0000\t\t::\t::\t::\tFF\tFF\t80000000\tFF\tFF\r\n"
outStr += "51\t01\t01\t01\tiqn.eternus-dx4\t\tFF\tDefault\t01\t00\t192.166.1.4\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0000\t00\tFFFF\t0514\t0000\t\t::\t::\t::\t00\t00\t80000000\t00\tFF\r\n"
outStr += "CLI> "
client := createIOMock(execCmd, outStr)
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
_, err := d.InitializeConnection(opt)
if err == nil {
t.Error("Test NewClient failed")
}
}
func TestInitializeConnection_Iscsi(t *testing.T) {
initiator := "iqn.testtest"
hostname := "hostname"
ipAddr := "1.1.1.1"
hashhostname := GetFnvHash(initiator + ipAddr)
opt := &pb.CreateVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
DoLocalAttach: false,
MultiPath: false,
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: hostname,
Ip: ipAddr,
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: "iscsi",
PortName: initiator,
},
},
},
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
AccessProtocol: ISCSIProtocol,
}
// Get iscsi port
execCmd := "show iscsi-parameters\n"
outStr := "CLI> show iscsi-parameters\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "50\t00\t00\t00\tiqn.eternus-dx1\t\tFF\tDefault\t01\t00\t192.168.1.1\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0001\t00\tFFFF\t0514\t0000\t\t::\t::\t::\tFF\tFF\t80000000\tFF\tFF\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get iscsi host
execCmd = "show host-iscsi-names\n"
outStr = "\r\nCLI> show host-iscsi-names\r\n"
outStr += "00\r\n"
outStr += "0003\r\n"
outStr += "0000\tHOST_NAME#0\t00\tDefault\t7F000001\tiqn.testtesttest\t00\r\n"
outStr += "0001\tHOST_NAME#1\t00\tDefault\t7F000001\tiqn.testtesttesttest\t00\r\n"
outStr += "0002\ttest_0\t00\tDefault\t02020202\tiqn.test\t00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(3, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(4, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Create iscsi host
execCmdCreateHost := "create host-iscsi-name"
execCmdCreateHost += " -name " + hashhostname
execCmdCreateHost += " -ip " + ipAddr + " -ip-version ipv4"
execCmdCreateHost += " -iscsi-name " + initiator + " \n"
outStr = "\r\nCLI> create host-iscsi-name\r\n"
outStr += "00\r\n"
outStr += "11\r\n"
outStr += "01\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdCreateHost)
}),
).Return(5, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(6, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get Lun group
execCmd = "show lun-groups\n"
outStr = "\r\nCLI> show lun-groups\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(7, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(8, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Create Lun group
execCmdCreateLunGrp := "create lun-group"
execCmdCreateLunGrp += " -name " + hashhostname
execCmdCreateLunGrp += " -volume-number 21 -lun 0 \n"
outStr = "\r\nCLI> create lun-group\r\n"
outStr += "00\r\n"
outStr += "12\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdCreateLunGrp)
}),
).Return(9, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(10, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Add host affinity
execCmdSetHostAffinity := "set host-affinity \n"
execCmdSetHostAffinity += " -port 010"
execCmdSetHostAffinity += " -lg-number 18"
execCmdSetHostAffinity += " -host-number 17 \n"
outStr = "\r\nCLI> set host-affinity\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdSetHostAffinity)
}),
).Return(11, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get host lun
execCmd = "show lun-group -lg-number 18 \n"
outStr = "\r\nCLI> show lun-group -lg-number 18\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "0003\r\n"
outStr += "0000\t0014\tvolname1\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "0015\t0015\tvolname2\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "0002\t0016\tvolname3\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(13, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(14, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
ret, err := d.InitializeConnection(opt)
if err != nil {
t.Error("Test InitializeConnection failed")
}
connData := ret.ConnectionData
if !reflect.DeepEqual(connData["targetIQN"], []string{"iqn.eternus-dx1"}) ||
!reflect.DeepEqual(connData["targetPortal"], []string{"192.168.1.1:3260"}) ||
connData["targetLun"] != 21 {
t.Error("Test InitializeConnection failed")
}
}
func TestInitializeConnection_FC(t *testing.T) {
initiator := "AAAAAAAAAAAAAAAA"
hostname := "hostname"
ipAddr := "1.1.1.1"
hashhostname := GetFnvHash(initiator)
opt := &pb.CreateVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
DoLocalAttach: false,
MultiPath: false,
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: hostname,
Ip: ipAddr,
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: FCProtocol,
PortName: initiator,
},
},
},
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
AccessProtocol: FCProtocol,
}
// Get iscsi port
execCmd := "show fc-parameters\n"
outStr := "CLI> show fc-parameters\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "40\t00\t04\t01\tFF\tFF\t00\t0800\t00\tFF\t\t01\t00\t00\t00\t00\tFF\t0000000000000001\t0000000000000000\tFF\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get iscsi host
execCmd = "show host-wwn-names\n"
outStr = "\r\nCLI> show host-wwn-names\r\n"
outStr += "00\r\n"
outStr += "0003\r\n"
outStr += "0000\tHOST_NAME#0\t1234567890123456\t0000\tDefault\r\n"
outStr += "0001\tHOST_NAME#1\t1234567890123457\t0000\tDefault\r\n"
outStr += "0002\tHOST_NAME#2\t1234567890123458\t0000\tDefault\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(3, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(4, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Create iscsi host
execCmdCreateHost := "create host-wwn-name"
execCmdCreateHost += " -name " + hashhostname
execCmdCreateHost += " -wwn " + initiator + " \n"
outStr = "\r\nCLI> create host-wwn-name\r\n"
outStr += "00\r\n"
outStr += "11\r\n"
outStr += "01\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdCreateHost)
}),
).Return(5, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(6, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get Lun group
execCmd = "show lun-groups\n"
outStr = "\r\nCLI> show lun-groups\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(7, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(8, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Create Lun group
execCmdCreateLunGrp := "create lun-group"
execCmdCreateLunGrp += " -name " + hashhostname
execCmdCreateLunGrp += " -volume-number 21 -lun 0 \n"
outStr = "\r\nCLI> create lun-group\r\n"
outStr += "00\r\n"
outStr += "12\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdCreateLunGrp)
}),
).Return(9, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(10, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Add host affinity
execCmdSetHostAffinity := "set host-affinity \n"
execCmdSetHostAffinity += " -port 000"
execCmdSetHostAffinity += " -lg-number 18"
execCmdSetHostAffinity += " -host-number 17 \n"
outStr = "\r\nCLI> set host-affinity\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdSetHostAffinity)
}),
).Return(11, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get host lun
execCmd = "show lun-group -lg-number 18 \n"
outStr = "\r\nCLI> show lun-group -lg-number 18\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "0003\r\n"
outStr += "0000\t0014\tvolname1\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "0015\t0015\tvolname2\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "0002\t0016\tvolname3\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(13, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(14, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
ret, err := d.InitializeConnection(opt)
if err != nil {
t.Error("Test InitializeConnection failed")
}
connData := ret.ConnectionData
if !reflect.DeepEqual(connData["targetWWNs"], []string{"0000000000000001"}) ||
connData["hostName"] != hostname ||
connData["targetLun"] != 21 {
t.Error("Test InitializeConnection failed")
}
}
func TestInitializeConnection_FCNoInitiator(t *testing.T) {
initiator := ""
hostname := "hostname"
ipAddr := "1.1.1.1"
opt := &pb.CreateVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
DoLocalAttach: false,
MultiPath: false,
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: hostname,
Ip: ipAddr,
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: FCProtocol,
PortName: initiator,
},
},
},
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
AccessProtocol: FCProtocol,
}
// Get iscsi port
execCmd := "show fc-parameters\n"
outStr := "CLI> show fc-parameters\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "40\t00\t04\t01\tFF\tFF\t00\t0800\t01\tFF\t\t01\t00\t00\t00\t00\tFF\t0000000000000001\t0000000000000000\tFF\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Show mapping
execCmd = "show mapping -port 000 \n"
outStr = "\r\nCLI> show mapping -port 000\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "11005100\t00\r\n"
outStr += "0001\r\n"
outStr += "0000\t0001\tosds-643e8232-1b\tA000\t20\t0000000000200000\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Add mapping
execCmdSetMapping := "set mapping"
execCmdSetMapping += " -port 000"
execCmdSetMapping += " -volume-number 21"
execCmdSetMapping += " -lun 1 \n"
outStr = "\r\nCLI> set mapping\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdSetMapping)
}),
).Return(11, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
ret, err := d.InitializeConnection(opt)
if err != nil {
t.Error("Test InitializeConnection failed")
}
connData := ret.ConnectionData
if !reflect.DeepEqual(connData["targetWWNs"], []string{"0000000000000001"}) ||
connData["hostName"] != hostname ||
connData["targetLun"] != 1 {
t.Error("Test InitializeConnection failed")
}
}
func TestTerminateConnection_Iscsi(t *testing.T) {
initiator := "iqn.testtest"
hostname := "hostname"
ipAddr := "1.1.1.1"
hashhostname := GetFnvHash(initiator + ipAddr)
opt := &pb.DeleteVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: hostname,
Ip: ipAddr,
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: "iscsi",
PortName: initiator,
},
},
},
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
AccessProtocol: ISCSIProtocol,
}
// Get iscsi port
execCmd := "show iscsi-parameters\n"
outStr := "CLI> show iscsi-parameters\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "50\t00\t00\t00\tiqn.eternus-dx1\t\tFF\tDefault\t01\t00\t192.168.1.1\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0001\t00\tFFFF\t0514\t0000\t\t::\t::\t::\tFF\tFF\t80000000\tFF\tFF\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get host lun
execCmd = "show lun-group -lg-name " + hashhostname + " \n"
outStr = "\r\nCLI> show lun-group -lg-name " + hashhostname + "\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "0003\r\n"
outStr += "0000\t0014\tvolname1\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "0015\t0015\tvolname2\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "0002\t0016\tvolname3\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Remove volume from lun group
execCmd = "delete lun-group -lg-name " + hashhostname + " -lun 21 \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmd)
}),
).Return(3, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(4, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
err := d.TerminateConnection(opt)
if err != nil {
t.Error("Test TerminateConnection failed")
}
}
func TestTerminateConnection_IscsiDLunGroup(t *testing.T) {
initiator := "iqn.testtest"
hostname := "hostname"
ipAddr := "1.1.1.1"
hashhostname := GetFnvHash(initiator + ipAddr)
opt := &pb.DeleteVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: hostname,
Ip: ipAddr,
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: "iscsi",
PortName: initiator,
},
},
},
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
AccessProtocol: ISCSIProtocol,
}
// Get iscsi port
execCmd := "show iscsi-parameters\n"
outStr := "CLI> show iscsi-parameters\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "50\t00\t00\t00\tiqn.eternus-dx1\t\tFF\tDefault\t01\t00\t192.168.1.1\t255.255.255.0\t0.0.0.0\t000000000000\t0CBC\t02\t00000000\t0000\t0.0.0.0\t0C85\t\t00\t00\t00\t0001\t00\tFFFF\t0514\t0000\t\t::\t::\t::\tFF\tFF\t80000000\tFF\tFF\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get host lun
execCmd = "show lun-group -lg-name " + hashhostname + " \n"
outStr = "\r\nCLI> show lun-group -lg-name " + hashhostname + "\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "0001\r\n"
outStr += "0015\t0015\tvolname2\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Remove volume from lun group
execCmdReleaseHostAffinity := "release host-affinity -port 010"
execCmdReleaseHostAffinity += " -host-name " + hashhostname + " -mode all \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdReleaseHostAffinity)
}),
).Return(3, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(4, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Delete lun group
execCmd = "delete lun-group -lg-name " + hashhostname + " \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(6, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Delete host
execCmd = "delete host-iscsi-name -host-name " + hashhostname + " \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(6, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
err := d.TerminateConnection(opt)
if err != nil {
t.Error("Test TerminateConnection failed")
}
}
func TestTerminateConnection_FcDLunGroup(t *testing.T) {
initiator := "AAAAAAAAAAAAAAAA"
hostname := "hostname"
ipAddr := "1.1.1.1"
hashhostname := GetFnvHash(initiator)
opt := &pb.DeleteVolumeAttachmentOpts{
Id: "id",
VolumeId: "volumeid",
HostInfo: &pb.HostInfo{
Platform: "linux",
OsType: "ubuntu",
Host: hostname,
Ip: ipAddr,
Initiators: []*pb.Initiator{
&pb.Initiator{
Protocol: FCProtocol,
PortName: initiator,
},
},
},
Metadata: map[string]string{
KLunId: "21",
},
DriverName: "drivername",
Context: "",
AccessProtocol: FCProtocol,
}
// Get iscsi port
execCmd := "show fc-parameters\n"
outStr := "CLI> show fc-parameters\r\n"
outStr += "00\r\n"
outStr += "01\r\n"
outStr += "40\t00\t04\t01\tFF\tFF\t00\t0800\t00\tFF\t\t01\t00\t00\t00\t00\tFF\t0000000000000001\t0000000000000000\tFF\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Get host lun
execCmd = "show lun-group -lg-name " + hashhostname + " \n"
outStr = "\r\nCLI> show lun-group -lg-name " + hashhostname + "\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "0000\ttest\tFFFF\tFFFF\r\n"
outStr += "0001\r\n"
outStr += "0015\t0015\tvolname2\tA000\t20\t0000000000000000\t00000000000000000000000000000000\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Remove volume from lun group
execCmdReleaseHostAffinity := "release host-affinity -port 000"
execCmdReleaseHostAffinity += " -host-name " + hashhostname + " -mode all \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdReleaseHostAffinity)
}),
).Return(3, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(4, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Delete lun group
execCmd = "delete lun-group -lg-name " + hashhostname + " \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(6, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Delete host
execCmd = "delete host-wwn-name -host-name " + hashhostname + " \n"
outStr = "\r\nCLI> " + execCmd + "\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(6, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
err := d.TerminateConnection(opt)
if err != nil {
t.Error("Test TerminateConnection failed")
}
}
func TestAddMapping(t *testing.T) {
// Show mapping
execCmd := "show mapping -port 000 \n"
outStr := "\r\nCLI> show mapping -port 000\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "11005100\t00\r\n"
outStr += "0003\r\n"
outStr += "0000\t0001\tvol1\tA000\t20\t0000000000200000\r\n"
outStr += "0001\t0002\tvol2\tA000\t20\t0000000000200000\r\n"
outStr += "0003\t0002\tvol2\tA000\t20\t0000000000200000\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Add mapping
execCmdSetMapping := "set mapping"
execCmdSetMapping += " -port 000"
execCmdSetMapping += " -volume-number 21"
execCmdSetMapping += " -lun 2 \n"
outStr = "\r\nCLI> set mapping\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdSetMapping)
}),
).Return(11, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
ret, err := d.addMapping("000", "21")
if err != nil {
t.Error("Test addMapping failed")
}
if ret != "2" {
t.Error("Test addMapping failed")
}
}
func TestAddMapping_Max(t *testing.T) {
// Show mapping
execCmd := "show mapping -port 000 \n"
outStr := "\r\nCLI> show mapping -port 000\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "11005100\t00\r\n"
outStr += "0400\r\n"
for i := 0; i < 1024; i++ {
outStr += strconv.Itoa(i) + "\t0001\tvol1\tA000\t20\t0000000000200000\r\n"
}
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
_, err := d.addMapping("000", "21")
if err == nil {
t.Error("Test addMapping failed")
}
}
func TestDeleteMapping(t *testing.T) {
// Show mapping
execCmd := "show mapping -port 000 \n"
outStr := "\r\nCLI> show mapping -port 000\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "11005100\t00\r\n"
outStr += "0003\r\n"
outStr += "0000\t0001\tvol1\tA000\t20\t0000000000200000\r\n"
outStr += "0001\t0002\tvol2\tA000\t20\t0000000000200000\r\n"
outStr += "0003\t0011\tvol2\tA000\t20\t0000000000200000\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
// Delete mapping
execCmdSetMapping := "release mapping"
execCmdSetMapping += " -port 000"
execCmdSetMapping += " -lun 3 \n"
outStr = "\r\nCLI> release mapping\r\n"
outStr += "00\r\n"
outStr += "CLI> "
mockWriteCloser.On("Write",
mock.MatchedBy(
func(cmd []byte) bool {
return checkArg(string(cmd), execCmdSetMapping)
}),
).Return(11, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(12, nil).Once()
buff = make([]byte, 65535)
out = []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
err := d.deleteMapping("000", "17")
if err != nil {
t.Error("Test deleteMapping failed")
}
}
func TestDeleteMapping_Deleted(t *testing.T) {
// Show mapping
execCmd := "show mapping -port 000 \n"
outStr := "\r\nCLI> show mapping -port 000\r\n"
outStr += "00\r\n"
outStr += "0001\r\n"
outStr += "11005100\t00\r\n"
outStr += "0003\r\n"
outStr += "0000\t0001\tvol1\tA000\t20\t0000000000200000\r\n"
outStr += "0001\t0002\tvol2\tA000\t20\t0000000000200000\r\n"
outStr += "0003\t0010\tvol2\tA000\t20\t0000000000200000\r\n"
outStr += "CLI> "
mockWriteCloser := new(MockWriteCloser)
mockWriteCloser.On("Write", []byte(execCmd)).Return(1, nil).Once()
mockWriteCloser.On("Write", []byte("\n")).Return(2, nil).Once()
mockReadCloser := new(MockReadCloser)
buff := make([]byte, 65535)
out := []byte(outStr)
mockReadCloser.On("Read", buff).Return(len(out), nil, out).Once()
client := &EternusClient{
stdin: mockWriteCloser,
stdout: mockReadCloser,
cliConfPath: "./config/cli_response.yml",
}
d := &Driver{
conf: &EternusConfig{
CeSupport: false,
},
client: client,
}
err := d.deleteMapping("000", "17")
if err != nil {
t.Error("Test deleteMapping failed")
}
}
|
package types
import (
"fmt"
"reflect"
"strings"
"github.com/docker/docker/api/types"
"github.com/globalsign/mgo/bson"
"github.com/portainer/libcompose/config"
yaml "gopkg.in/yaml.v3"
)
// GroupLight data
type GroupLight struct {
ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
Name string `json:"name" bson:"name" validate:"required"`
Description string `json:"description" bson:"description"`
Daemon bson.ObjectId `json:"daemon_id,omitempty" bson:"daemon_id,omitempty"`
Admins []string `json:"admins" bson:"admins"`
Users []string `json:"users" bson:"users"`
}
// Group data
type Group struct {
GroupLight `bson:",inline"`
Services []GroupService `json:"services" bson:"services"`
GroupDocker `bson:",inline"`
}
// GroupDocker data
type GroupDocker struct {
Subnet string `json:"subnet" bson:"subnet"`
MinPort uint16 `json:"min_port" bson:"min_port"`
MaxPort uint16 `json:"max_port" bson:"max_port"`
Containers []types.ContainerJSON `json:"containers" bson:"containers"`
}
// GroupService data
type GroupService struct {
SubServiceID bson.ObjectId `json:"sub_service_id,omitempty" bson:"sub_service_id,omitempty"`
Name string `json:"name" bson:"name" validate:"required"`
File []byte `json:"file,omitempty" bson:"file" validate:"required"`
Variables []ServiceVariable `json:"variables" bson:"variables"`
URL string `json:"url" bson:"url" validate:"required"`
AutoUpdate bool `json:"auto_update" bson:"auto_update"`
Ports []uint16 `json:"ports" bson:"ports"`
}
// Groups data
type Groups []Group
// GroupsLight data
type GroupsLight []GroupLight
// IsAdmin check if a user is admin in this group
func (g *Group) IsAdmin(u *User) bool {
if u.IsAdmin() {
return true
}
for _, admin := range g.Admins {
if admin == u.Username {
return true
}
}
return false
}
// IsMyGroup check if this is a group of the user
func (g *Group) IsMyGroup(u *User) bool {
if g.IsAdmin(u) {
return true
}
for _, user := range g.Users {
if user == u.Username {
return true
}
}
return false
}
// GetFreePort return the first available port
func (g *Group) GetFreePort() uint16 {
var ports []uint16
/*
for _, s := range g.Services {
ports = append(ports, s.Ports...)
}
*/
for i := g.MinPort; i < g.MaxPort; i++ {
if !findPort(i, ports) {
return i
}
}
return 0
}
func findPort(port uint16, ports []uint16) bool {
for _, p := range ports {
if port == p {
return true
}
}
return false
}
// FindServiceByName return the service by name (unique)
func (g *Group) FindServiceByName(name string) *GroupService {
for _, service := range g.Services {
if service.Name == name {
return &service
}
}
return nil
}
// FindContainersByNameOrID return the group containers by id or name and keep the array key
func (g *GroupDocker) FindContainersByNameOrID(containers []string) (cont []types.ContainerJSON) {
cont = make([]types.ContainerJSON, len(g.Containers))
for _, container := range containers {
for key, c := range g.Containers {
if c.ID == container || c.Name == container {
cont[key] = c
break
}
}
}
return
}
// AppendOrUpdate append container if doesn't exist or update it by name
func (g *GroupDocker) AppendOrUpdate(containers []types.ContainerJSON) {
for _, container := range containers {
exist := false
for key, c := range g.Containers {
if c.Name == container.Name {
exist = true
g.Containers[key] = container
break
}
}
if !exist {
g.Containers = append(g.Containers, container)
}
}
}
// FindSubServiceByID return the subservice by string id
func (g *Group) FindSubServiceByID(subServiceID string) *GroupService {
for _, s := range g.Services {
if s.SubServiceID.Hex() == subServiceID {
return &s
}
}
return nil
}
// ConvertToGroupService this function convert a sub service to a service group
func (ss *SubService) ConvertToGroupService(serviceName string, daemon Daemon, service Service, group Group, autoUpdate bool, extraHosts []string) (groupService GroupService, err error) {
groupService.Name = serviceName
groupService.Variables = ss.Variables
groupService.SubServiceID = ss.ID
groupService.URL = computeServiceURL(serviceName, group.Name, daemon.Host)
variables := map[string]interface{}{
"Group": group,
"Daemon": daemon,
"Service": service,
"ServiceName": serviceName,
}
// Copy of variables
for _, v := range ss.Variables {
variables[v.Name] = v.Value
}
serv, err := ss.ConvertSubService(variables)
if err != nil {
return groupService, fmt.Errorf("Error when converting sub service: %s", err)
}
var config config.Config
if err = yaml.Unmarshal(serv, &config); err != nil {
return groupService, fmt.Errorf("Error when unmarshal service: %s", err)
}
addLabel(&config, SERVICE_NAME_LABEL, serviceName)
// Use https://github.com/v2tec/watchtower
addLabel(&config, WATCHTOWER_LABEL, fmt.Sprintf("%v", autoUpdate))
groupService.AutoUpdate = autoUpdate
for service := range config.Services {
// Find main service in the compose file (the one that has container_name in the template)
containerName := reflect.ValueOf(config.Services[service]["container_name"])
if containerName.IsValid() {
addExtraHosts(&config, service, extraHosts)
}
}
groupService.File, err = yaml.Marshal(config)
if err != nil {
return groupService, fmt.Errorf("Error when marshal config: %s", err)
}
return groupService, nil
}
// Obfuscate hides compose file and secret variables
func (g *Group) Obfuscate() {
for i, s := range g.Services {
g.Services[i].File = []byte{}
for j, v := range s.Variables {
if v.Secret {
g.Services[i].Variables[j].Value = SECRET_VARIABLE
}
}
}
}
func addLabel(config *config.Config, label string, value string) {
for key := range config.Services {
labels := reflect.ValueOf(config.Services[key]["labels"])
if !labels.IsValid() {
labels = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(label), reflect.TypeOf(value)))
}
labels.SetMapIndex(reflect.ValueOf(label), reflect.ValueOf(value))
config.Services[key]["labels"] = labels.Interface()
}
}
func addExtraHosts(config *config.Config, service string, hosts []string) {
if len(hosts) == 0 {
return
}
extraHosts := reflect.ValueOf(config.Services[service]["extra_hosts"])
if !extraHosts.IsValid() {
extraHosts = reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(hosts[0])), len(hosts), len(hosts))
}
for i, host := range hosts {
extraHosts.Index(i).SetString(host)
}
config.Services[service]["extra_hosts"] = extraHosts.Interface()
}
func computeServiceURL(serviceName, groupName, host string) string {
service := strings.ReplaceAll(serviceName, "[_-]", "")
service = strings.ToLower(service)
group := strings.ReplaceAll(groupName, "_", "-")
group = strings.ToLower(group)
return fmt.Sprintf("https://%s.%s.%s/", service, group, host)
}
|
package cmd
import (
"adminbot/framework"
"adminbot/config"
"fmt"
"encoding/json"
"io/ioutil"
"strconv"
"time"
"strings"
)
func KickCommand(ctx framework.Context) {
// TODO [!] In progress
if !HasRole(ctx.Discord, ctx.User.ID, "admin"){
return
}
if len(ctx.Args) == 0{
ctx.Reply("Choose number of days : <days>")
return
}
days, _ := strconv.Atoi( ctx.Args[0] )
//failsafe
if days < 60{
ctx.Reply("Numbers of days should be more than 60")
return
}
dryrun := true
if len(ctx.Args) > 1{
if strings.Contains(ctx.Args[1], "-confirm"){
dryrun = false
}
}
logdata := make(map[string]int64)
byteValue, err := ioutil.ReadFile("logdata.json")
if err != nil{
fmt.Println("[!] Error Logging, cannot read logdata.json")
return
}
json.Unmarshal(byteValue, &logdata)
ctx.Reply("----- list -----")
for userid, timestamp := range logdata {
time_days := (time.Now().Unix() - int64(days * 24*60*60) )
// check number of days since last message
if timestamp < time_days {
if !IsMemberOfTeam(ctx.Discord, userid) && !HasRole(ctx.Discord, userid, "bot"){
member, err := ctx.Discord.GuildMember(config.Discord.GuildID, userid)
if err == nil{
// kicking user
ctx.Reply( fmt.Sprintf("Kicking user %s (last message was in %s)", member.User.Username, time.Unix(timestamp, 0)) )
if dryrun == false{
err2 := ctx.Discord.GuildMemberDeleteWithReason(config.Discord.GuildID, userid, "inactivity")
if err2 != nil{
fmt.Println("Error kick : ", err)
ctx.Reply( fmt.Sprintf("Error kicking user %s ...", member.User.Username) )
return
}
}
}
}
}
}
ctx.Reply("--- end list ---")
return
} |
package set_monitor
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
)
func SetURLToMonitorAll(address, name, url string) {
cfg := clientv3.Config{Endpoints: []string{address}}
c, err := clientv3.New(cfg)
defer c.Close()
if err != nil {
fmt.Println(c)
fmt.Println("err: ", err)
}
fmt.Println("Check 1")
kapi := clientv3.NewKV(c)
fmt.Println("Check 2")
resp, err := kapi.Put(context.Background(), name, url)
fmt.Println(resp, err)
return
}
|
package keepalive
/*
#include <stdlib.h>
struct Thing {
long long *ptr;
int len;
};
struct Thing* newThing(long long * arr, int len)
{
struct Thing* t = (struct Thing*)malloc(sizeof(struct Thing));;
t->ptr = arr;
t->len = len;
return t;
}
long long doIt(struct Thing *t)
{
long long sum = 0;
for(int i = 0; i < t->len; i++){
sum += t->ptr[i];
}
return sum;
}
*/
import "C"
import (
"math/rand"
"runtime"
"time"
"unsafe"
)
func init() {
rand.Seed(time.Now().Unix())
}
// DoIt fills a slice of int with values 0 to len(s)-1.
//
// It uses cgo, for reasons.
func DoIt(s []int64) int64 {
modified := doIt(s)
return modified
}
// DoItKeepAlive is like DoIt, but uses a call to runtime.KeepAlive.
func DoItKeepAlive(s []int64) int64 {
modified := doIt(s)
runtime.KeepAlive(s)
return modified
}
func doIt(s []int64) int64 {
cThing := C.newThing(
// Pointer to first element in the slice's underlying array
// (passing Go allocated memory to C)
(*C.longlong)(unsafe.Pointer(&s[0])),
// Length of the slice
C.int(len(s)),
)
// Make sure we free our cThing
defer C.free(unsafe.Pointer(cThing))
// Simulate some work causing GC to run
runtime.GC()
other := make([]int, rand.Intn(10000))
for i := range other {
other[i] = rand.Int()
}
// Return the result of our complex C function
return int64(C.doIt(cThing))
}
|
package main
import (
"fmt"
)
type ListCommand struct{}
func (l *ListCommand) Execute(args []string) error {
triggers, err := getTriggers(options.APIHost, options.Dataset, options.WriteKey)
if err != nil {
fmt.Println("Failed to list triggers: ", err)
return err
}
for _, trigger := range triggers {
fmt.Println(trigger.Name)
}
return nil
}
|
package windows
import "syscall"
const (
errnoERROR_IO_PENDING = 997
)
var (
errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
)
const (
EVENT_MIN uint32 = 0x00000001
EVENT_MAX uint32 = 0x7FFFFFFF
EVENT_SYSTEM_FOREGROUND uint32 = 0x0003
WINEVENT_SKIPOWNPROCESS uint32 = 2
)
const (
// Virtual-Key Codes
VKBACK = 0x08
VKTAB = 0x09
VKCLEAR = 0x0C
VKRETURN = 0x0D
VKSHIFT = 0x10
VKCONTROL = 0x11
VKMENU = 0x12
VKPAUSE = 0x13
VKCAPITAL = 0x14
VKESCAPE = 0x1B
VKSPACE = 0x20
VKPRIOR = 0x21
VKNEXT = 0x22
VKEND = 0x23
VKHOME = 0x24
VKLEFT = 0x25
VKUP = 0x26
VKRIGHT = 0x27
VKDOWN = 0x28
VKSELECT = 0x29
VKPRINT = 0x2A
VKEXECUTE = 0x2B
VKSNAPSHOT = 0x2C
VKINSERT = 0x2D
VKDELETE = 0x2E
VKLWIN = 0x5B
VKRWIN = 0x5C
VKAPPS = 0x5D
VKSLEEP = 0x5F
VKNUMPAD0 = 0x60
VKNUMPAD1 = 0x61
VKNUMPAD2 = 0x62
VKNUMPAD3 = 0x63
VKNUMPAD4 = 0x64
VKNUMPAD5 = 0x65
VKNUMPAD6 = 0x66
VKNUMPAD7 = 0x67
VKNUMPAD8 = 0x68
VKNUMPAD9 = 0x69
VKMULTIPLY = 0x6A
VKADD = 0x6B
VKSEPARATOR = 0x6C
VKSUBTRACT = 0x6D
VKDECIMAL = 0x6E
VKDIVIDE = 0x6F
VKF1 = 0x70
VKF2 = 0x71
VKF3 = 0x72
VKF4 = 0x73
VKF5 = 0x74
VKF6 = 0x75
VKF7 = 0x76
VKF8 = 0x77
VKF9 = 0x78
VKF10 = 0x79
VKF11 = 0x7A
VKF12 = 0x7B
VKNUMLOCK = 0x90
VKSCROLL = 0x91
VKLSHIFT = 0xA0
VKRSHIFT = 0xA1
VKLCONTROL = 0xA2
VKRCONTROL = 0xA3
VKLMENU = 0xA4
VKRMENU = 0xA5
VKOEM1 = 0xBA
VKOEMPLUS = 0xBB
VKOEMCOMMA = 0xBC
VKOEMMINUS = 0xBD
VKOEMPERIOD = 0xBE
VKOEM2 = 0xBF
VKOEM3 = 0xC0
VKOEM4 = 0xDB
VKOEM5 = 0xDC
VKOEM6 = 0xDD
VKOEM7 = 0xDE
VKOEM8 = 0xDF
)
const (
FILE_ATTRIBUTE_READONLY = 0x00000001
FILE_ATTRIBUTE_HIDDEN = 0x00000002
FILE_ATTRIBUTE_SYSTEM = 0x00000004
FILE_ATTRIBUTE_DIRECTORY = 0x00000010
FILE_ATTRIBUTE_ARCHIVE = 0x00000020
FILE_ATTRIBUTE_DEVICE = 0x00000040
FILE_ATTRIBUTE_NORMAL = 0x00000080
FILE_ATTRIBUTE_TEMPORARY = 0x00000100
FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200
FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
FILE_ATTRIBUTE_COMPRESSED = 0x00000800
FILE_ATTRIBUTE_OFFLINE = 0x00001000
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000
FILE_ATTRIBUTE_ENCRYPTED = 0x00004000
FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x00008000
FILE_ATTRIBUTE_VIRTUAL = 0x00010000
FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x00020000
FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x00040000
FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000
)
|
package main
import "bufio"
//import "flag" // can't use, doesn't allow repeated options (--enable vrr --enable irnr)
import "fmt"
//import "log"
import "io"
import "os"
import "strings"
import "voteutil"
// from countvotes.c
/*
countvotes [--dump][--debug][--preindexed]\n"
"\t[--full-html|--no-full-html|--no-html-head]\n"
"\t[--disable-all][--enable-all][--seats n]\n"
"\t[--rankings][--help|-h|--list][--explain]\n"
"\t[-o filename|--out filenam]\n"
"\t[--enable|--disable hist|irnr|vrr|raw|irv|stv]\n"
"\t[input file name|-i votesfile|-igz gzipped-votesfile]\n"
"\t[--test]
*/
type ElectionMethodConstructor func() voteutil.ElectionMethod;
var classByShortname map[string]ElectionMethodConstructor
func init() {
classByShortname = map[string]ElectionMethodConstructor {
"vrr": voteutil.NewVRR,
"raw": voteutil.NewRawSummation,
"irnr": voteutil.NewIRNR,
}
}
// Map String to List of Strings - Get
// If the key isn't in the map, put an empty slice there and return that.
func msls_get(it map[string] []string, key string) []string {
sl, ok := it[key]
if ok {
return sl
}
sl = make([]string, 0, 1)
it[key] = sl
return sl
}
// Probably takes os.Args[1:]
// argnums is map from --?(option name) [some number of arguments for option, probably 0 or 1]
// --?(option name)=(.*) is always interpreted as one argument
// "--" stops parsing and all further args go to the list of non-option program arguments at out[""]
func ParseArgs(args []string, argnums map[string]int) (map[string] []string, error) {
out := make(map[string] []string)
pos := 0
for pos < len(args) {
ostr := args[pos]
if ostr == "--" {
sl := msls_get(out, "")
sl = append(sl, args[pos+1:]...)
out[""] = sl
break
}
if ostr[0] == '-' {
var argname string
var eqpart string
eqpos := strings.IndexRune(ostr, '=')
if eqpos < 0 {
eqpos = len(ostr)
} else {
eqpart = ostr[eqpos+1:]
}
if ostr[1] == '-' {
argname = ostr[2:eqpos]
} else {
argname = ostr[1:eqpos]
}
argnum, ok := argnums[argname]
if !ok {
return nil, fmt.Errorf("unknown arg: %#v", ostr)
}
sl := msls_get(out, argname)
if eqpos < len(ostr) {
if argnum != 1 {
return nil, fmt.Errorf("got =part which is only valid for args which take one value, $#v takes %d values", argname, argnum)
}
sl = append(sl, eqpart)
} else {
for argnum > 0 {
pos++
argnum--
if pos >= len(args) {
return nil, fmt.Errorf("missing argument to %#v", ostr)
}
sl = append(sl, args[pos])
}
}
out[argname] = sl
} else {
sl := msls_get(out, "")
sl = append(sl, ostr)
out[""] = sl
}
pos++;
}
return out, nil
}
// Get args by multiple names.
// e.g. ["i", "input"] gets things passed to -i or --input (or --i or -input)
func GetArgs(args map[string] []string, names []string) []string {
out := []string{}
for _, name := range(names) {
values, ok := args[name]
if ok {
out = append(out, values...)
}
}
return out
}
func ReadLine(f *bufio.Reader) (string, error) {
pdata, isPrefix, err := f.ReadLine()
if ! isPrefix {
return string(pdata), err
}
data := make([]byte, len(pdata))
copy(data, pdata)
for isPrefix {
pdata, isPrefix, err = f.ReadLine()
data = append(data, pdata...)
}
return string(data), err
}
type VoteSource interface {
// Return (vote, nil) normally, (nil, nil) on EOF.
GetVote() (*voteutil.NameVote, error)
}
type FileVoteSource struct {
rawReader io.Reader
bReader *bufio.Reader
}
func OpenFileVoteSource(path string) (*FileVoteSource, error) {
rawin, err := os.Open(path)
if err != nil {
return nil, err
}
return &FileVoteSource{rawin, bufio.NewReader(rawin)}, nil
}
func (it *FileVoteSource) GetVote() (*voteutil.NameVote, error) {
// TODO: check EOF and return (nil, nil)
line, err := ReadLine(it.bReader)
if err != nil {
return nil, err
}
return voteutil.UrlToNameVote(line)
}
/*
test output format:
{{system name}}: {{winner name}}[, {{winner name}}]\n
*/
type Election struct {
methods []voteutil.ElectionMethod
}
func (it *Election) Vote(vote *voteutil.NameVote) {
for _, m := range(it.methods) {
m.Vote(*vote)
}
}
func (it *Election) VoteAll(source VoteSource) error {
for true {
vote, err := source.GetVote()
if err != nil {
return err
}
if vote == nil {
return nil
}
it.Vote(vote)
}
return nil
}
func doenable(methodEnabled map[string]bool, enstr string, endis bool) {
comma := strings.IndexRune(enstr, ',')
if comma != -1 {
doenable(methodEnabled, enstr[:comma], endis)
doenable(methodEnabled, enstr[comma+1:], endis)
} else {
_, ok := classByShortname[enstr]
if !ok {
var verb string
if endis {
verb = "enable"
} else {
verb = "disable"
}
fmt.Fprintf(os.Stderr, "cannot %s unknown method %#v", verb, enstr)
os.Exit(1)
return
}
methodEnabled[enstr] = endis
}
}
func main() {
//flag.Parse()
//var rawin io.Reader
var err error
argnums := map[string]int{
"o": 1,
"out": 1,
"test": 0,
"i": 1,
"enable": 1,
"disable": 1,
"explain": 0,
"enable-all": 0,
"disable-all": 0,
/*
TODO: implement
"full-html": 0,
"no-full-html": 0,
"no-html-head": 0,
"dump": 0,
"debug": 0,
*/
}
methodEnabled := map[string]bool {
"vrr": true,
"irnr": true,
"raw": true,
}
args, err := ParseArgs(os.Args[1:], argnums)
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
return
}
outNames := GetArgs(args, []string{"o", "out"})
if len(outNames) > 1 {
fmt.Fprintf(os.Stderr, "error: can accept at most one output file name, got %#v", outNames)
os.Exit(1)
return
}
outw := os.Stdout
if len(outNames) == 1 {
path := outNames[0]
if path == "-" {
// already writing to stdout
} else {
outw, err = os.Create(path)
if err != nil {
fmt.Fprintf(os.Stderr, "%#v: cannot be opened for output\n", path)
os.Exit(1)
return
}
}
}
inNames := GetArgs(args, []string{"i", ""})
_, enableAll := args["enable-all"]
if enableAll {
for enkey, _ := range(methodEnabled) {
methodEnabled[enkey] = true
}
}
_, disableAll := args["disable-all"]
if disableAll {
for enkey, _ := range(methodEnabled) {
methodEnabled[enkey] = false
}
}
enableStrs, hasEnables := args["enable"]
if hasEnables {
for _, enstr := range(enableStrs) {
doenable(methodEnabled, enstr, true)
}
}
disableStrs, hasDisables := args["disable"]
if hasDisables {
for _, enstr := range(disableStrs) {
doenable(methodEnabled, enstr, false)
}
}
_, testMode := args["test"]
_, showExplain := args["explain"]
methods := make([]voteutil.ElectionMethod, 0)
for methodShort, isEnabled := range(methodEnabled) {
if isEnabled {
methods = append(methods, classByShortname[methodShort]())
}
}
election := Election{methods}
for _, path := range(inNames) {
vs, err := OpenFileVoteSource(path)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", path, err)
break
}
election.VoteAll(vs)
}
for _, em := range methods {
result, winners := em.GetResult()
if testMode {
fmt.Fprintf(outw, "%s: ", em.ShortName())
for i, res := range(*result) {
if i > 0 {
fmt.Fprint(outw, ", ")
}
fmt.Fprint(outw, res.Name)
}
fmt.Fprint(outw, "\n")
} else if showExplain {
fmt.Fprint(outw, em.HtmlExplaination())
} else {
fmt.Fprintf(outw, "winners:\n")
fmt.Fprint(outw, result, winners)
}
}
}
|
package leetcode
/*A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i]=[3,8] means the seat located in row 3 and labelled with 8 is already reserved.
Return the maximum number of four-person families you can allocate on the cinema seats. A four-person family occupies fours seats in one row, that are next to each other. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be next to each other, however, It is permissible for the four-person family to be separated by an aisle, but in that case, exactly two people have to sit on each side of the aisle.*/
func maxNumberOfFamilies(n int, reservedSeats [][]int) int {
reserved := make(map[int][]int, 0)
res := 0
for i := 0; i < len(reservedSeats); i++ {
row, ok := reserved[reservedSeats[i][0]]
if !ok {
data := make([]int, 10)
data[reservedSeats[i][1]-1] = 1
reserved[reservedSeats[i][0]] = data
} else {
row[reservedSeats[i][1]-1] = 1
}
}
res += (n - len(reserved)) * 2
for _, row := range reserved {
left, mid := false, false
if row[1] == 0 && row[2] == 0 && row[3] == 0 && row[4] == 0 {
res++
left = true
}
if !left && row[3] == 0 && row[4] == 0 && row[5] == 0 && row[6] == 0 {
res++
mid = true
}
if !mid && row[5] == 0 && row[6] == 0 && row[7] == 0 && row[8] == 0 {
res++
}
}
return res
}
|
package models
import "go.mongodb.org/mongo-driver/bson/primitive"
type Article struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Id string `json:"id,omitempty" bson:"id,omitempty"`
Title string `json:"title" bson:"title,omitempty"`
SubTitle string `json:"Stitle" bson:"Stitle,omitempty"`
Content string `json:"content" bson:"content,omitempty"`
}
var Articles []Article
|
package service
import (
"fmt"
"github.com/jdcloud-cmw/jdsf-demo-go/jdsf-demo-client/jdsfapi"
"github.com/jdcloud-cmw/jdsf-demo-go/jdsf-demo-client/sling"
"github.com/opentracing/opentracing-go"
"io/ioutil"
"net/http"
)
func RegistryCheck(w http.ResponseWriter, r *http.Request) {
t1 := opentracing.GlobalTracer()
fmt.Println(t1)
paramMap := make(map[string]string)
paramMap["gameid"] = "123123"
t := opentracing.GlobalTracer()
fmt.Println(t)
req, err :=sling.New().Get("http://db-service:8090/db/gameinfo/getgameinfo?gameid=123123").EnableTrace(r.Context()).Request()
if err != nil {
fmt.Println(err)
}
client := &http.Client{Transport: &jdsfapi.Transport{}}
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
writeJsonResponse(w, http.StatusOK, body)
}
|
// +build hosted
package router
import (
"regexp"
"strings"
)
var hostedDomainPattern *regexp.Regexp
func init() {
hostedDomainPattern = regexp.MustCompile("(eventgateway([a-z-]*)?.io|slsgateway.com)")
}
func extractPath(host, path string) string {
if hostedDomainPattern.Copy().MatchString(host) {
subdomain := strings.Split(host, ".")[0]
return basePath + subdomain + path
}
return path
}
func systemPathFromSpace(space string) string {
return basePath + space + "/"
}
// systemPathFromURL constructs system event path based on hostname and path
// on which the event was emitted. Helpful for "event.received" system event.
func systemPathFromURL(host, path string) string {
if hostedDomainPattern.Copy().MatchString(host) {
segment := strings.Split(path, "/")[1]
return basePath + segment + "/"
}
return basePath
}
|
package main
import (
"fmt"
"io"
"os"
"github.com/mitchellh/cli"
"github.com/romantomjak/b2/command"
"github.com/romantomjak/b2/version"
)
func main() {
os.Exit(Run(os.Stdin, os.Stdout, os.Stdout, os.Args[1:]))
}
func Run(stdin io.Reader, stdout, stderr io.Writer, args []string) int {
ui := &cli.BasicUi{
Reader: stdin,
Writer: stdout,
ErrorWriter: stderr,
}
c := cli.NewCLI("b2", version.Version)
c.Args = args
c.Commands = command.Commands(ui)
exitCode, err := c.Run()
if err != nil {
fmt.Fprintf(stderr, "Error executing CLI: %s\n", err.Error())
return 1
}
return exitCode
}
|
package provider
import (
"github.com/hashicorp/terraform/helper/schema"
"github.com/mrparkers/terraform-provider-keycloak/keycloak"
)
func resourceKeycloakRole() *schema.Resource {
return &schema.Resource{
Create: resourceKeycloakRoleCreate,
Read: resourceKeycloakRoleRead,
Delete: resourceKeycloakRoleDelete,
Update: resourceKeycloakRoleUpdate,
// This resource can be imported using {{realm}}/{{group_id}}. The Group ID is displayed in the URL when editing it from the GUI
/*Importer: &schema.ResourceImporter{
State: resourceKeycloakRoleImport,
},*/
Schema: map[string]*schema.Schema{
"realm_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func mapFromDataToRole(data *schema.ResourceData) *keycloak.Role {
role := &keycloak.Role{
Id: data.Id(),
RealmId: data.Get("realm_id").(string),
Name: data.Get("name").(string),
}
return role
}
func mapFromRoleToData(data *schema.ResourceData, role *keycloak.Role) {
data.SetId(role.Id)
data.Set("realm_id", role.RealmId)
data.Set("name", role.Name)
}
func resourceKeycloakRoleCreate(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)
role := mapFromDataToRole(data)
err := keycloakClient.NewRole(role)
if err != nil {
return err
}
mapFromRoleToData(data, role)
return resourceKeycloakRoleRead(data, meta)
}
func resourceKeycloakRoleRead(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)
realmId := data.Get("realm_id").(string)
id := data.Id()
roleName := data.Get("name").(string)
role, err := keycloakClient.GetRole(realmId, id, roleName)
if err != nil {
return handleNotFoundError(err, data)
}
mapFromRoleToData(data, role)
return nil
}
func resourceKeycloakRoleUpdate(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)
role := mapFromDataToRole(data)
err := keycloakClient.UpdateRole(role)
if err != nil {
return err
}
mapFromRoleToData(data, role)
return nil
}
func resourceKeycloakRoleDelete(data *schema.ResourceData, meta interface{}) error {
keycloakClient := meta.(*keycloak.KeycloakClient)
realmId := data.Get("realm_id").(string)
id := data.Id()
roleName := data.Get("name").(string)
return keycloakClient.DeleteRole(realmId, id, roleName)
}
|
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00800102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.008.001.02 Document"`
Message *AcceptorCancellationAdviceResponseV02 `xml:"AccptrCxlAdvcRspn"`
}
func (d *Document00800102) AddMessage() *AcceptorCancellationAdviceResponseV02 {
d.Message = new(AcceptorCancellationAdviceResponseV02)
return d.Message
}
// The AcceptorCancellationAdviceResponse message is sent by the acquirer (or its agent) to acknowledge the acceptor (or its agent) about the notification of the payment cancellation.
type AcceptorCancellationAdviceResponseV02 struct {
// Cancellation advice response message management information.
Header *iso20022.Header2 `xml:"Hdr"`
// Information related to the cancellation advice response.
CancellationAdviceResponse *iso20022.AcceptorCancellationAdviceResponse2 `xml:"CxlAdvcRspn"`
// Trailer of the message containing a MAC.
SecurityTrailer *iso20022.ContentInformationType6 `xml:"SctyTrlr"`
}
func (a *AcceptorCancellationAdviceResponseV02) AddHeader() *iso20022.Header2 {
a.Header = new(iso20022.Header2)
return a.Header
}
func (a *AcceptorCancellationAdviceResponseV02) AddCancellationAdviceResponse() *iso20022.AcceptorCancellationAdviceResponse2 {
a.CancellationAdviceResponse = new(iso20022.AcceptorCancellationAdviceResponse2)
return a.CancellationAdviceResponse
}
func (a *AcceptorCancellationAdviceResponseV02) AddSecurityTrailer() *iso20022.ContentInformationType6 {
a.SecurityTrailer = new(iso20022.ContentInformationType6)
return a.SecurityTrailer
}
|
package p08
func largeGroupPositions(S string) [][]int {
ret := make([][]int, 0)
curChar := S[0]
startIndex := 0
endIndex := 0
for i := 1; i < len(S); i++ {
if S[i] == curChar {
endIndex = i
if i == len(S)-1 {
l := endIndex - startIndex + 1
if l >= 3 {
ret = append(ret, []int{startIndex, endIndex})
}
}
} else {
l := endIndex - startIndex + 1
if l >= 3 {
ret = append(ret, []int{startIndex, endIndex})
}
startIndex = i
endIndex = i
curChar = S[i]
}
}
return ret
}
|
package riverntorch
var _ RiverCrosser = (*fastestBearerApproach)(nil)
var _ RiverCrosser = (*clubSlowestApproach)(nil)
type RiverCrosser interface {
//get name of the approach been used
GetName() string
//cross all people from SideA to SideB.
//gives back solution object, with details about the process.
Cross() Solution
}
//
// GetRiverCrosser used to get instance of RiverCrosser.
//
func GetRiverCrosser(people RiverCrossers) RiverCrosser {
fbApproach := NewFastestBearerApproach(people)
csApproach := NewClubSlowestApproach(people)
// No. of passers are 3 or less, both approach works same.
// So, lets use fbApproach for such a scenario.
if fbApproach.noOfcrossers <= 3 {
return fbApproach
}
// Test which approach to use, beforing applying.
// Use ClubSlowestApproach, if the time saved by clubbing is greater than
// time lost by not using fastest torchbearer always.
// Else, use the FastestBearerApproach
//extra time spent by ClubSlowestApproach during Backward Journey.
extraTime := csApproach.timeSpentInBckwrdJrny() - fbApproach.timeSpentInBckwrdJrny()
//time saved by clubbing slower members together.
timeSaved := csApproach.timeSavedByClubbing()
if timeSaved > extraTime {
return csApproach
}
return fbApproach
}
|
// Copyright 2021 Tamás Gulácsi. All rights reserved.
package main
import (
"io"
"log"
"os"
plsqlparser "github.com/UNO-SOFT/plsql-parser"
)
func main() {
if err := Main(); err != nil {
log.Fatalf("ERROR: %+v", err)
}
}
func Main() error {
text, _ := io.ReadAll(os.Stdin)
return plsqlparser.ChromaParse(string(text))
}
|
/* SPDX-License-Identifier: Apache-2.0
* Copyright (c) 2019-2020 Intel Corporation
*/
package ngcnef
import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
"strings"
//"strconv"
"github.com/gorilla/mux"
)
func createNewSub(nefCtx *nefContext, afID string,
ti TrafficInfluSub) (loc string, rsp nefSBRspData, err error) {
var af *afData
nef := &nefCtx.nef
af, err = nef.nefGetAf(afID)
if err != nil {
log.Err("NO AF PRESENT CREATE AF")
af, err = nef.nefAddAf(nefCtx, afID)
if err != nil {
return loc, rsp, err
}
} else {
log.Infoln("AF PRESENT")
}
loc, rsp, err = af.afAddSubscription(nefCtx, ti)
if err != nil {
return loc, rsp, err
}
return loc, rsp, nil
}
// ReadAllTrafficInfluenceSubscription : API to read all the subscritions
func ReadAllTrafficInfluenceSubscription(w http.ResponseWriter,
r *http.Request) {
var subslist []TrafficInfluSub
var rsp nefSBRspData
var err error
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
nef := &nefCtx.nef
vars := mux.Vars(r)
log.Infof(" AFID : %s", vars["afId"])
af, err := nef.nefGetAf(vars["afId"])
if err != nil {
/* Failure in getting AF with afId received. In this case no
* subscription data will be returned to AF */
log.Infoln(err)
} else {
rsp, subslist, err = af.afGetSubscriptionList(nefCtx)
if err != nil {
log.Err(err)
sendErrorResponseToAF(w, rsp)
return
}
}
mdata, err2 := json.Marshal(subslist)
if err2 != nil {
sendCustomeErrorRspToAF(w, 400, "Failed to MARSHAL Subscription data ")
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
//Send Success response to Network
_, err = w.Write(mdata)
if err != nil {
log.Errf("Write Failed: %v", err)
return
}
log.Infof("HTTP Response sent: %d", http.StatusOK)
}
// CreateTrafficInfluenceSubscription : Handles the traffic influence requested
// by AF
func CreateTrafficInfluenceSubscription(w http.ResponseWriter,
r *http.Request) {
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
vars := mux.Vars(r)
log.Infof(" AFID : %s", vars["afId"])
b, err := ioutil.ReadAll(r.Body)
defer closeReqBody(r)
if err != nil {
sendCustomeErrorRspToAF(w, 400, "Failed to read HTTP POST Body")
return
}
//Traffic Influence data
trInBody := TrafficInfluSub{}
//Convert the json Traffic Influence data into struct
err1 := json.Unmarshal(b, &trInBody)
if err1 != nil {
log.Err(err1)
sendCustomeErrorRspToAF(w, 400, "Failed UnMarshal POST data")
return
}
//validate the mandatory parameters
resRsp, status := validateAFTrafficInfluenceData(trInBody)
if !status {
log.Err(resRsp.pd.Title)
sendErrorResponseToAF(w, resRsp)
return
}
loc, rsp, err3 := createNewSub(nefCtx, vars["afId"], trInBody)
if err3 != nil {
log.Err(err3)
// we return bad request here since we have reached the max
rsp.errorCode = 400
sendErrorResponseToAF(w, rsp)
return
}
log.Infoln(loc)
trInBody.Self = Link(loc)
//Martshal data and send into the body
mdata, err2 := json.Marshal(trInBody)
if err2 != nil {
log.Err(err2)
sendCustomeErrorRspToAF(w, 400, "Failed to Marshal GET response data")
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Location", loc)
// Response should be 201 Created as per 3GPP 29.522
w.WriteHeader(http.StatusCreated)
log.Infof("CreateTrafficInfluenceSubscription responses => %d",
http.StatusCreated)
_, err = w.Write(mdata)
if err != nil {
log.Errf("Write Failed: %v", err)
return
}
nef := &nefCtx.nef
logNef(nef)
}
// ReadTrafficInfluenceSubscription : Read a particular subscription details
func ReadTrafficInfluenceSubscription(w http.ResponseWriter, r *http.Request) {
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
nef := &nefCtx.nef
vars := mux.Vars(r)
log.Infof(" AFID : %s", vars["afId"])
log.Infof(" SUBSCRIPTION ID : %s", vars["subscriptionId"])
af, ok := nef.nefGetAf(vars["afId"])
if ok != nil {
sendCustomeErrorRspToAF(w, 404, "Failed to find AF records")
return
}
rsp, sub, err := af.afGetSubscription(nefCtx, vars["subscriptionId"])
if err != nil {
log.Err(err)
sendErrorResponseToAF(w, rsp)
return
}
mdata, err2 := json.Marshal(sub)
if err2 != nil {
log.Err(err2)
sendCustomeErrorRspToAF(w, 400, "Failed to Marshal GET response data")
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
_, err = w.Write(mdata)
if err != nil {
log.Errf("Write Failed: %v", err)
return
}
log.Infof("HTTP Response sent: %d", http.StatusOK)
}
// UpdatePutTrafficInfluenceSubscription : Updates a traffic influence created
// earlier (PUT Req)
func UpdatePutTrafficInfluenceSubscription(w http.ResponseWriter,
r *http.Request) {
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
nef := &nefCtx.nef
vars := mux.Vars(r)
log.Infof(" AFID : %s", vars["afId"])
log.Infof(" SUBSCRIPTION ID : %s", vars["subscriptionId"])
af, ok := nef.nefGetAf(vars["afId"])
if ok == nil {
b, err := ioutil.ReadAll(r.Body)
defer closeReqBody(r)
if err != nil {
log.Err(err)
sendCustomeErrorRspToAF(w, 400, "Failed to read HTTP PUT Body")
return
}
//Traffic Influence data
trInBody := TrafficInfluSub{}
//Convert the json Traffic Influence data into struct
err1 := json.Unmarshal(b, &trInBody)
if err1 != nil {
log.Err(err1)
sendCustomeErrorRspToAF(w, 400, "Failed UnMarshal PUT data")
return
}
rsp, newTI, err := af.afUpdateSubscription(nefCtx,
vars["subscriptionId"], trInBody)
if err != nil {
sendErrorResponseToAF(w, rsp)
return
}
mdata, err2 := json.Marshal(newTI)
if err2 != nil {
log.Err(err2)
sendCustomeErrorRspToAF(w, 400, "Failed to Marshal PUT"+
"response data")
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
_, err = w.Write(mdata)
if err != nil {
log.Errf("Write Failed: %v", err)
}
return
}
log.Infoln(ok)
sendCustomeErrorRspToAF(w, 404, "Failed to find AF records")
}
// UpdatePatchTrafficInfluenceSubscription : Updates a traffic influence created
// earlier (PATCH Req)
func UpdatePatchTrafficInfluenceSubscription(w http.ResponseWriter,
r *http.Request) {
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
nef := &nefCtx.nef
vars := mux.Vars(r)
log.Infof(" AFID : %s", vars["afId"])
log.Infof(" SUBSCRIPTION ID : %s", vars["subscriptionId"])
af, ok := nef.nefGetAf(vars["afId"])
if ok == nil {
b, err := ioutil.ReadAll(r.Body)
defer closeReqBody(r)
if err != nil {
log.Err(err)
sendCustomeErrorRspToAF(w, 400, "Failed to read HTTP PATCH Body")
return
}
//Traffic Influence Sub Patch data
TrInSPBody := TrafficInfluSubPatch{}
//Convert the json Traffic Influence data into struct
err1 := json.Unmarshal(b, &TrInSPBody)
if err1 != nil {
log.Err(err1)
sendCustomeErrorRspToAF(w, 400, "Failed UnMarshal PATCH data")
return
}
rsp, ti, err := af.afPartialUpdateSubscription(nefCtx,
vars["subscriptionId"], TrInSPBody)
if err != nil {
sendErrorResponseToAF(w, rsp)
return
}
mdata, err2 := json.Marshal(ti)
if err2 != nil {
log.Err(err2)
sendCustomeErrorRspToAF(w, 400,
"Failed to Marshal PATCH response data")
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
_, err = w.Write(mdata)
if err != nil {
log.Errf("Write Failed: %v", err)
}
return
}
log.Infoln(ok)
sendCustomeErrorRspToAF(w, 404, "Failed to find AF records")
}
// DeleteTrafficInfluenceSubscription : Deletes a traffic influence created by
// AF
func DeleteTrafficInfluenceSubscription(w http.ResponseWriter,
r *http.Request) {
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
nef := &nefCtx.nef
vars := mux.Vars(r)
log.Infof(" AFID : %s", vars["afId"])
log.Infof(" SUBSCRIPTION ID : %s", vars["subscriptionId"])
af, err := nef.nefGetAf(vars["afId"])
if err != nil {
log.Err(err)
sendCustomeErrorRspToAF(w, 404, "Failed to find AF entry")
return
}
rsp, err := af.afDeleteSubscription(nefCtx, vars["subscriptionId"])
if err != nil {
log.Err(err)
sendErrorResponseToAF(w, rsp)
return
}
// Response should be 204 as per 3GPP 29.522
w.WriteHeader(http.StatusNoContent)
log.Infof("HTTP Response sent: %d", http.StatusNoContent)
if af.afGetSubCount() == 0 {
_ = nef.nefDeleteAf(vars["afId"])
}
logNef(nef)
}
// NotifySmfUPFEvent : Handles the SMF notification for UPF event
func NotifySmfUPFEvent(w http.ResponseWriter,
r *http.Request) {
var (
smfEv NsmfEventExposureNotification
ev EventNotification
afURL URI
nsmEvNo NsmEventNotification
i int
upfFound bool
)
if r.Body == nil {
log.Errf("NotifySmfUPFEvent Empty Body")
w.WriteHeader(http.StatusBadRequest)
return
}
// Retrieve the event notification information from the request
if err := json.NewDecoder(r.Body).Decode(&smfEv); err != nil {
log.Errf("NotifySmfUPFEvent body parse: %s", err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
// Validate the content of the NsmfEventExposureNotification
// Check if notification id is present
if smfEv.NotifID == "" {
log.Errf("NotifySmfUPFEvent missing notif id")
w.WriteHeader(http.StatusBadRequest)
return
}
// Check if notification events with UP_PATH_CH is present
if len(smfEv.EventNotifs) == 0 {
log.Errf("NotifySmfUPFEvent missing event notifications")
w.WriteHeader(http.StatusBadRequest)
return
}
for i, nsmEvNo = range smfEv.EventNotifs {
if nsmEvNo.Event == "UP_PATH_CH" {
log.Infof("NotifySmfUPFEvent found an entry for UP_PATH_CH"+
"at index: %d", i)
upfFound = true
break
}
}
if !upfFound {
log.Errf("NotifySmfUPFEvent missing event with UP_PATH_CH")
w.WriteHeader(http.StatusBadRequest)
return
}
// Map the content of NsmfEventExposureNotification to EventNotificaiton
nefCtx := r.Context().Value(nefCtxKey("nefCtx")).(*nefContext)
afSubs, err1 := getSubFromCorrID(nefCtx, smfEv.NotifID)
if err1 != nil {
log.Errf("NotifySmfUPFEvent getSubFromCorrId [%s]: %s",
smfEv.NotifID, err1.Error())
w.WriteHeader(http.StatusNotFound)
return
}
log.Infof("NotifySmfUPFEvent [NotifID, TransId, URL] => [%s,%s,%s",
smfEv.NotifID, afSubs.ti.AfTransID,
afSubs.ti.NotificationDestination)
ev.AfTransID = afSubs.ti.AfTransID
afURL = URI(afSubs.ti.NotificationDestination)
ev.Gpsi = nsmEvNo.Gpsi
ev.DnaiChgType = nsmEvNo.DnaiChgType
ev.SrcUeIpv4Addr = nsmEvNo.SourceUeIpv4Addr
ev.SrcUeIpv6Prefix = nsmEvNo.SourceUeIpv6Prefix
ev.TgtUeIpv4Addr = nsmEvNo.TargetUeIpv4Addr
ev.TgtUeIpv6Prefix = nsmEvNo.TargetUeIpv6Prefix
ev.UeMac = nsmEvNo.UeMac
ev.SourceTrafficRoute = nsmEvNo.SourceTraRouting
ev.SubscribedEvent = SubscribedEvent("UP_PATH_CHANGE")
ev.TargetTrafficRoute = nsmEvNo.TargetTraRouting
w.WriteHeader(http.StatusOK)
// Send the request towards AF
var afClient AfNotification = NewAfClient(&nefCtx.cfg)
err := afClient.AfNotificationUpfEvent(r.Context(), afURL, ev)
if err != nil {
log.Errf("NotifySmfUPFEvent sending to AF failed : %s",
err.Error())
}
}
func getSubFromCorrID(nefCtx *nefContext, corrID string) (sub *afSubscription,
err error) {
nef := &nefCtx.nef
/*Search across all the AF registered */
for _, value := range nef.afs {
/*Search across all the Subscription*/
for _, vs := range value.subs {
if vs.NotifCorreID == corrID {
/*Match found return sub handle*/
return vs, nil
}
}
}
return sub, errors.New("Subscription Not Found")
}
//validateAFTrafficInfluenceData: Function to validate mandatory parameters of
//TrafficInfluence received from AF
func validateAFTrafficInfluenceData(ti TrafficInfluSub) (rsp nefSBRspData,
status bool) {
if len(ti.AfTransID) == 0 {
rsp.errorCode = 400
rsp.pd.Title = "Missing AfTransID atttribute"
return rsp, false
}
//In case AfServiceID is not present then DNN has to be included in TI
if len(ti.AfServiceID) == 0 && len(ti.Dnn) == 0 {
rsp.errorCode = 400
rsp.pd.Title = "Missing afServiceId atttribute"
return rsp, false
}
if len(ti.AfAppID) == 0 && ti.TrafficFilters == nil &&
ti.EthTrafficFilters == nil {
rsp.errorCode = 400
rsp.pd.Title = "missing one of afAppId, trafficFilters," +
"ethTrafficFilters"
return rsp, false
}
return rsp, true
}
//Creates a new subscription
func (af *afData) afAddSubscription(nefCtx *nefContext,
ti TrafficInfluSub) (loc string, rsp nefSBRspData, err error) {
/*Check if max subscription reached */
if len(af.subs) >= nefCtx.cfg.MaxSubSupport {
rsp.errorCode = 400
rsp.pd.Title = "MAX Subscription Reached"
return "", rsp, errors.New("MAX SUBS Created")
}
//Generate a unique subscription ID string
subIDStr := strconv.Itoa(af.subIDnum)
af.subIDnum++
//Create Subscription data
afsub := afSubscription{subid: subIDStr, ti: ti, appSessionID: "",
NotifCorreID: "", iid: ""}
if len(ti.Gpsi) > 0 || len(ti.Ipv4Addr) > 0 || len(ti.Ipv6Addr) > 0 {
//Applicable to single UE, PCF case
rsp, err = nefSBPCFPost(&afsub, nefCtx, ti)
if err != nil {
//Return error failed to create subscription
return "", rsp, err
}
//Store Notification Destination URI
afsub.afNotificationDestination = ti.NotificationDestination
afsub.NEFSBGet = nefSBPCFGet
afsub.NEFSBPut = nefSBPCFPut
afsub.NEFSBPatch = nefSBPCFPatch
afsub.NEFSBDelete = nefSBPCFDelete
} else if len(ti.ExternalGroupID) > 0 || ti.AnyUeInd {
//Applicable to Any UE, UDR case
rsp, err = nefSBUDRPost(&afsub, nefCtx, ti)
if err != nil {
//Return error
return "", rsp, err
}
//Store Notification Destination URI
afsub.afNotificationDestination = ti.NotificationDestination
afsub.NEFSBGet = nefSBUDRGet
afsub.NEFSBPut = nefSBUDRPut
afsub.NEFSBPatch = nefSBUDRPatch
afsub.NEFSBDelete = nefSBUDRDelete
} else {
//Invalid case. Return Error
rsp.errorCode = 400
rsp.pd.Title = "Invalid Request"
return "", rsp, errors.New("Invalid AF Request")
}
//Link the subscription with the AF
af.subs[subIDStr] = &afsub
//Create Location URI
loc = nefCtx.nef.locationURLPrefix + af.afID + "/subscriptions/" +
subIDStr
afsub.ti.Self = Link(loc)
log.Infoln(" NEW AF Subscription added " + subIDStr)
return loc, rsp, nil
}
func (af *afData) afUpdateSubscription(nefCtx *nefContext, subID string,
ti TrafficInfluSub) (rsp nefSBRspData, updtTI TrafficInfluSub, err error) {
sub, ok := af.subs[subID]
if !ok {
rsp.errorCode = 400
rsp.pd.Title = subNotFound
return rsp, updtTI, errors.New(subNotFound)
}
rsp, err = sub.NEFSBPut(sub, nefCtx, ti)
if err != nil {
log.Err("Failed to Update Subscription")
return rsp, updtTI, err
}
updtTI = ti
updtTI.Self = sub.ti.Self
sub.ti = updtTI
log.Infoln("Update Subscription Successful")
return rsp, updtTI, err
}
func updateTiFromTisp(ti *TrafficInfluSub, tisp TrafficInfluSubPatch) {
if tisp.AppReloInd != ti.AppReloInd {
log.Infoln("Updating AppReloInd...")
ti.AppReloInd = tisp.AppReloInd
}
if tisp.TrafficFilters != nil {
log.Infoln("Updating TrafficFilters...")
ti.TrafficFilters = tisp.TrafficFilters
}
if tisp.EthTrafficFilters != nil {
log.Infoln("Updating EthTrafficFilters")
ti.EthTrafficFilters = tisp.EthTrafficFilters
}
if tisp.TrafficRoutes != nil {
log.Infoln("Updating TrafficRoutes")
ti.TrafficRoutes = tisp.TrafficRoutes
}
if tisp.TempValidities != nil {
log.Infoln("Updating TempValidities")
ti.TempValidities = tisp.TempValidities
}
if tisp.ValidGeoZoneIDs != nil {
log.Infoln("Updating ValidGeoZoneIDs")
ti.ValidGeoZoneIDs = tisp.ValidGeoZoneIDs
}
}
func (af *afData) afPartialUpdateSubscription(nefCtx *nefContext, subID string,
tisp TrafficInfluSubPatch) (rsp nefSBRspData, ti TrafficInfluSub,
err error) {
sub, ok := af.subs[subID]
if !ok {
rsp.errorCode = 400
rsp.pd.Title = subNotFound
return rsp, ti, errors.New(subNotFound)
}
rsp, err = sub.NEFSBPatch(sub, nefCtx, tisp)
if err != nil {
log.Err("Failed to Patch Subscription")
return rsp, ti, err
}
updateTiFromTisp(&sub.ti, tisp)
return rsp, sub.ti, err
}
func (af *afData) afGetSubscription(nefCtx *nefContext,
subID string) (rsp nefSBRspData, ti TrafficInfluSub, err error) {
sub, ok := af.subs[subID]
if !ok {
rsp.errorCode = 404
rsp.pd.Title = subNotFound
return rsp, ti, errors.New(subNotFound)
}
//ti, rsp, err = sub.NEFSBGet(sub, nefCtx)
/*
if err != nil {
log.Infoln("Failed to Get Subscription")
return rsp, ti, err
}
return rsp, ti, err
*/
//Return locally
return rsp, sub.ti, err
}
func (af *afData) afGetSubscriptionList(nefCtx *nefContext) (rsp nefSBRspData,
subsList []TrafficInfluSub, err error) {
var ti TrafficInfluSub
if len(af.subs) > 0 {
for key := range af.subs {
rsp, ti, err = af.afGetSubscription(nefCtx, key)
if err != nil {
return rsp, subsList, err
}
subsList = append(subsList, ti)
}
}
return rsp, subsList, err
}
func (af *afData) afDeleteSubscription(nefCtx *nefContext,
subID string) (rsp nefSBRspData, err error) {
//Check if AF is already present
sub, ok := af.subs[subID]
if !ok {
rsp.errorCode = 404
rsp.pd.Title = subNotFound
return rsp, errors.New(subNotFound)
}
rsp, err = sub.NEFSBDelete(sub, nefCtx)
if err != nil {
log.Err("Failed to Delete Subscription")
return rsp, err
}
//Delete local entry in map
delete(af.subs, subID)
//af.subIDnum--
return rsp, err
}
func (af *afData) afGetSubCount() (afCount int) {
return len(af.subs)
}
/* unused function
func (af *afData) afDestroy(afid string) error {
//Todo delete all subscriptions, needed in go ??
//Needed for gracefully disconnecting
return errors.New("AF data cleaned")
}
*/
// Generate the notification uri to be provided to PCF/UDR
func getNefNotificationURI(cfg *Config) URI {
var uri string
// If http2 port is configured use it else http port
if cfg.HTTP2Config.Endpoint != "" {
uri = "https://" + cfg.NefAPIRoot +
cfg.HTTP2Config.Endpoint
} else {
uri = "http://" + cfg.NefAPIRoot +
cfg.HTTPConfig.Endpoint
}
uri += cfg.UpfNotificationResURIPath
return URI(uri)
}
func getNefLocationURLPrefix(cfg *Config) string {
var uri string
// If http2 port is configured use it else http port
if cfg.HTTP2Config.Endpoint != "" {
uri = "https://" + cfg.NefAPIRoot +
cfg.HTTP2Config.Endpoint
} else {
uri = "http://" + cfg.NefAPIRoot +
cfg.HTTPConfig.Endpoint
}
uri += cfg.LocationPrefix
return uri
}
// nefSBPCFPost : This function sends HTTP POST Request to PCF to create Policy
// Authorization.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// - ti: This is Traffic Influence Subscription Data.
// Output Args:
// - rsp: This is Policy Authorization Create Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBPCFPost(pcfSub *afSubscription, nefCtx *nefContext,
ti TrafficInfluSub) (rsp nefSBRspData, err error) {
var appSessID AppSessionID
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
pcfSub.NotifCorreID = strconv.Itoa(int(nef.corrID))
nef.corrID++
appSessCtx := AppSessionContext{}
pcfPolicyResp := PcfPolicyResponse{}
//Populating App Session Context Data Req
appSessCtx.AscReqData.AfAppID = AfAppID(ti.AfAppID)
appSessCtx.AscReqData.AfRoutReq.AppReloc = ti.AppReloInd
//Populating UP Path Chnage Subbscription Data in App Session Context
appSessCtx.AscReqData.AfRoutReq.UpPathChgSub.DnaiChgType = ti.DnaiChgType
// If http2 port is configured use it else http port
if nefCtx.cfg.HTTP2Config.Endpoint != "" {
appSessCtx.AscReqData.AfRoutReq.UpPathChgSub.NotificationURI =
URI("https://" + nefCtx.cfg.NefAPIRoot +
nefCtx.cfg.HTTP2Config.Endpoint)
} else {
appSessCtx.AscReqData.AfRoutReq.UpPathChgSub.NotificationURI =
URI("http://" + nefCtx.cfg.NefAPIRoot +
nefCtx.cfg.HTTPConfig.Endpoint)
}
/*+ nefCtx.cfg.UpfNotificationResUriPath*/
appSessCtx.AscReqData.AfRoutReq.UpPathChgSub.NotifCorreID =
pcfSub.NotifCorreID
//Populating Traffic Routes in App Session Context
appSessCtx.AscReqData.AfRoutReq.RouteToLocs = make([]RouteToLocation,
len(ti.TrafficRoutes))
_ = copy(appSessCtx.AscReqData.AfRoutReq.RouteToLocs, ti.TrafficRoutes)
//Populating Temporal Validity in App Session Context
appSessCtx.AscReqData.AfRoutReq.TempVals = make([]TemporalValidity,
len(ti.TempValidities))
_ = copy(appSessCtx.AscReqData.AfRoutReq.TempVals, ti.TempValidities)
//Populating Spatial Validity in App Session Context
_ = getSpatialValidityData(cliCtx, nefCtx,
&appSessCtx.AscReqData.AfRoutReq.SpVal)
//Populating IP and Mac Addresses in App Session Context
appSessCtx.AscReqData.UeIpv4 = ti.Ipv4Addr
appSessCtx.AscReqData.UeIpv6 = ti.Ipv6Addr
appSessCtx.AscReqData.UeMac = ti.MacAddr
//Populating DNN and NW Slice Info and SUPI in App Session Context
for _, afServIdcounter := range nefCtx.cfg.AfServiceIDs {
afServiceID := afServIdcounter.(map[string]interface{})
if 0 == strings.Compare(ti.AfServiceID, afServiceID["id"].(string)) {
appSessCtx.AscReqData.Dnn = Dnn(afServiceID["dnn"].(string))
appSessCtx.AscReqData.SliceInfo.Sd = afServiceID["snssai"].(string)
appSessCtx.AscReqData.SliceInfo.Sst =
uint8(len(appSessCtx.AscReqData.SliceInfo.Sd))
}
}
//Populating SUPI in App Session Context
_ = getSupiData(cliCtx, nefCtx, &appSessCtx.AscReqData.Supi)
appSessID, pcfPolicyResp, err =
nef.pcfClient.PolicyAuthorizationCreate(cliCtx, appSessCtx)
if err != nil {
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Create Failure. Response Code: %d",
rsp.errorCode)
return rsp, err
}
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Create Failure. Response Code: %d",
rsp.errorCode)
} else {
pcfSub.appSessionID = appSessID
log.Infof("PCF Policy Authorization Create Success. Response Code: %d",
rsp.errorCode)
}
return rsp, err
}
// nefSBPCFGet : This function sends HTTP GET Request to PCF to fetch Policy
// Authorization using App Session Context Key.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// Output Args:
// - sub: This is Traffic Influence Subscription Data.
// - rsp: This is Policy Authorization Get Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBPCFGet(pcfSub *afSubscription, nefCtx *nefContext) (
sub TrafficInfluSub, rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
pcfPolicyResp, err :=
nef.pcfClient.PolicyAuthorizationGet(cliCtx, pcfSub.appSessionID)
if err != nil {
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Get Failure. Response Code: %d",
rsp.errorCode)
return sub, rsp, err
}
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Get Failure. Response Code: %d",
rsp.errorCode)
} else {
sub = pcfSub.ti
log.Infof("PCF Policy Authorization Get Success. Response Code: %d",
rsp.errorCode)
}
return sub, rsp, err
}
// nefSBPCFPut : This function returns error as HTTP PUT Request to PCF is not
// supported.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// - ti: This is Traffic Influence Subscription Data.
// Output Args:
// - rsp: This is Policy Authorization Put Response Data
// - error: retruns error .
func nefSBPCFPut(pcfSub *afSubscription, nefCtx *nefContext,
ti TrafficInfluSub) (rsp nefSBRspData, err error) {
err = errors.New("PUT Method Not Supported")
log.Errf("PCF Policy Authorization Put Not Supported")
return rsp, err
}
// nefSBPCFPatch : This function sends HTTP PATCH Request to PCF to update
// Policy Authorization using App Session Context Key.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// - tisp: This is Traffic Influence Subscription Patch Data.
// Output Args:
// - rsp: This is Policy Authorization Patch Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBPCFPatch(pcfSub *afSubscription, nefCtx *nefContext,
tisp TrafficInfluSubPatch) (rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
appSessCtxUpdtData := AppSessionContextUpdateData{}
//Populating App Session Context Data Req
//TODO: appSessCtxUpdtData.AfAppID = ti.AfAppID
appSessCtxUpdtData.AfRoutReq.AppReloc = tisp.AppReloInd
//Populating UP Path Chnage Subbscription Data in App Session Context
appSessCtxUpdtData.AfRoutReq.UpPathChgSub.NotificationURI =
nefCtx.nef.upfNotificationURL
appSessCtxUpdtData.AfRoutReq.UpPathChgSub.NotifCorreID =
pcfSub.NotifCorreID
//Populating Traffic Routes in App Session Context
appSessCtxUpdtData.AfRoutReq.RouteToLocs = make([]RouteToLocation,
len(tisp.TrafficRoutes))
_ = copy(appSessCtxUpdtData.AfRoutReq.RouteToLocs, tisp.TrafficRoutes)
//Populating Temporal Validity in App Session Context
appSessCtxUpdtData.AfRoutReq.TempVals = make([]TemporalValidity,
len(tisp.TempValidities))
_ = copy(appSessCtxUpdtData.AfRoutReq.TempVals, tisp.TempValidities)
//Populating Spatial Validity in App Session Context
_ = getSpatialValidityData(cliCtx, nefCtx,
&appSessCtxUpdtData.AfRoutReq.SpVal)
pcfPolicyResp, err := nef.pcfClient.PolicyAuthorizationUpdate(cliCtx,
appSessCtxUpdtData, pcfSub.appSessionID)
if err != nil {
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Update Failure. Response Code: %d",
rsp.errorCode)
return rsp, err
}
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Update Failure. Response Code: %d",
rsp.errorCode)
} else {
log.Infof("PCF Policy Authorization Update Success. Response Code: %d",
rsp.errorCode)
}
return rsp, err
}
// nefSBPCFDelete : This function sends HTTP DELETE Request to PCF to delete
// Policy Authorization using App Session Context Key.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// Output Args:
// - rsp: This is Policy Authorization Delete Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBPCFDelete(pcfSub *afSubscription, nefCtx *nefContext) (
rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
pcfPolicyResp, err :=
nef.pcfClient.PolicyAuthorizationDelete(cliCtx, pcfSub.appSessionID)
if err != nil {
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Delete Failure. Response Code: %d",
rsp.errorCode)
return rsp, err
}
rsp.errorCode = int(pcfPolicyResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if pcfPolicyResp.Pd != nil {
rsp.pd = *pcfPolicyResp.Pd
}
log.Errf("PCF Policy Authorization Delete Failure. Response Code: %d",
rsp.errorCode)
} else {
log.Infof("PCF Policy Authorization Delete Success. Response Code: %d",
rsp.errorCode)
}
return rsp, err
}
// nefSBUDRPost : HTTP POST Request to UDR is to trigger Put
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// - ti: This is Traffic Influence Subscription Data.
// Output Args:
// - rsp: This is Traffic Influence Data Put Response Data
// - error: retruns error .
func nefSBUDRPost(udrSub *afSubscription, nefCtx *nefContext,
ti TrafficInfluSub) (rsp nefSBRspData, err error) {
rsp, err = nefSBUDRPut(udrSub, nefCtx, ti)
return rsp, err
}
// nefSBUDRGet : This function sends HTTP GET Request to UDR to fetch
// Traffic Influence Data.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// Output Args:
// - sub: This is Traffic Influence Subscription Data.
// - rsp: This is Traffic Influence Data Delete Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBUDRGet(udrSub *afSubscription, nefCtx *nefContext) (
sub TrafficInfluSub, rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
udrInfluenceResp, err := nef.udrClient.UdrInfluenceDataGet(cliCtx)
if err != nil {
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Get Failure. Response Code: %d",
rsp.errorCode)
return sub, rsp, err
}
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Get Failure. Response Code: %d",
rsp.errorCode)
} else {
sub = udrSub.ti
log.Infof("UDR Traffic Influence Data Get Success. Response Code: %d",
rsp.errorCode)
}
return sub, rsp, err
}
// nefSBUDRPut : This function sends HTTP PUT Request to UDR to create Traffic
// Influence Data.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// - ti: This is Traffic Influence Subscription Data.
// Output Args:
// - rsp: This is Traffic Influence Data Create Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBUDRPut(udrSub *afSubscription, nefCtx *nefContext,
ti TrafficInfluSub) (rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
trafficInfluData := TrafficInfluData{}
//Populating Traffic Influence Data
trafficInfluData.AfAppID = ti.AfAppID
//Populating DNN and NW Slice Info in Traffic Influence Data
for _, afServIdcounter := range nefCtx.cfg.AfServiceIDs {
afServiceID := afServIdcounter.(map[string]interface{})
if 0 == strings.Compare(ti.AfServiceID, afServiceID["id"].(string)) {
trafficInfluData.Dnn = Dnn(afServiceID["dnn"].(string))
trafficInfluData.Snssai.Sd = afServiceID["snssai"].(string)
trafficInfluData.Snssai.Sst = uint8(len(trafficInfluData.Snssai.Sd))
}
}
trafficInfluData.AppReloInd = ti.AppReloInd
trafficInfluData.InterGroupID = string(ti.ExternalGroupID)
//Populating UP Path Chnage Subbscription Data in Traffic Influence Data
trafficInfluData.UpPathChgNotifURI = nefCtx.nef.upfNotificationURL
if len(ti.SubscribedEvents) > 0 &&
0 == strings.Compare(string(ti.SubscribedEvents[0]), "UP_PATH_CHANGE") {
udrSub.NotifCorreID = strconv.Itoa(int(nef.corrID))
nef.corrID++
trafficInfluData.UpPathChgNotifCorreID = udrSub.NotifCorreID
}
//Populating Traffic Filters in Traffic Influence Data
trafficInfluData.TrafficFilters = make([]FlowInfo,
len(ti.TrafficFilters))
_ = copy(trafficInfluData.TrafficFilters, ti.TrafficFilters)
//Populating Eth Traffic Filters in Traffic Influence Data
trafficInfluData.EthTrafficFilters = make([]EthFlowDescription,
len(ti.EthTrafficFilters))
_ = copy(trafficInfluData.EthTrafficFilters, ti.EthTrafficFilters)
//Populating Traffic Routes in Traffic Influence Data
trafficInfluData.TrafficRoutes = make([]RouteToLocation,
len(ti.TrafficRoutes))
_ = copy(trafficInfluData.TrafficRoutes, ti.TrafficRoutes)
//Populating Temporal Validity in Traffic Influence Data
if 0 < len(ti.TempValidities) {
trafficInfluData.ValidStartTime =
DateTime(ti.TempValidities[0].StartTime)
trafficInfluData.ValidEndTime =
DateTime(ti.TempValidities[0].StopTime)
}
//Populating Spatial Validity in Traffic Influence Data
_ = getNetworkAreaInfo(cliCtx, nefCtx, &trafficInfluData.NwAreaInfo)
udrInfluenceResp, err := nef.udrClient.UdrInfluenceDataCreate(
cliCtx, trafficInfluData, udrSub.iid)
if err != nil {
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Put Failure. Response Code: %d",
rsp.errorCode)
return rsp, err
}
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Put Failure. Response Code: %d",
rsp.errorCode)
} else {
log.Infof("UDR Traffic Influence Data Put Success. Response Code: %d",
rsp.errorCode)
}
return rsp, err
}
// nefSBUDRPatch : This function sends HTTP PATCH Request to UDR to update
// Traffic Influence Data.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// - tisp: This is Traffic Influence Subscription Patch Data.
// Output Args:
// - rsp: This is Traffic Influence Data Update Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBUDRPatch(udrSub *afSubscription, nefCtx *nefContext,
tisp TrafficInfluSubPatch) (rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
trafficInfluDataPatch := TrafficInfluDataPatch{}
trafficInfluDataPatch.AppReloInd = tisp.AppReloInd
//Populating Traffic Filters in Traffic Influence Data
trafficInfluDataPatch.TrafficFilters = make([]FlowInfo,
len(tisp.TrafficFilters))
_ = copy(trafficInfluDataPatch.TrafficFilters, tisp.TrafficFilters)
//Populating Eth Traffic Filters in Traffic Influence Data
trafficInfluDataPatch.EthTrafficFilters = make([]EthFlowDescription,
len(tisp.EthTrafficFilters))
_ = copy(trafficInfluDataPatch.EthTrafficFilters, tisp.EthTrafficFilters)
//Populating Traffic Routes in Traffic Influence Data
trafficInfluDataPatch.TrafficRoutes = make([]RouteToLocation,
len(tisp.TrafficRoutes))
_ = copy(trafficInfluDataPatch.TrafficRoutes, tisp.TrafficRoutes)
//Populating Temporal Validity in Traffic Influence Data
if 0 < len(tisp.TempValidities) {
trafficInfluDataPatch.ValidStartTime =
DateTime(tisp.TempValidities[0].StartTime)
trafficInfluDataPatch.ValidEndTime =
DateTime(tisp.TempValidities[0].StopTime)
}
udrInfluenceResp, err := nef.udrClient.UdrInfluenceDataUpdate(
cliCtx, trafficInfluDataPatch, udrSub.iid)
if err != nil {
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Update Failure. Response Code: %d",
rsp.errorCode)
return rsp, err
}
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Update Failure. Response Code: %d",
rsp.errorCode)
} else {
log.Infof("UDR Traffic Influence Data Update Success.Response Code: %d",
rsp.errorCode)
}
return rsp, err
}
// nefSBUDRDelete : This function sends HTTP DELETE Request to UDR to delete
// Traffic Influence Data.
// Input Args:
// - nefCtx: This is NEF Module Context. This contains the NEF Module Data.
// Output Args:
// - rsp: This is Traffic Influence Data Delete Response Data
// - error: retruns error in case there is failure happened in sending the
// request or any failure response is received.
func nefSBUDRDelete(udrSub *afSubscription, nefCtx *nefContext) (
rsp nefSBRspData, err error) {
nef := &nefCtx.nef
cliCtx, cancel := context.WithCancel(nef.ctx)
defer cancel()
udrInfluenceResp, err := nef.udrClient.UdrInfluenceDataDelete(cliCtx,
udrSub.iid)
if err != nil {
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Delete Failure. Response Code: %d",
rsp.errorCode)
return rsp, err
}
rsp.errorCode = int(udrInfluenceResp.ResponseCode)
if rsp.errorCode >= 300 && rsp.errorCode < 700 {
if udrInfluenceResp.Pd != nil {
rsp.pd = *udrInfluenceResp.Pd
}
log.Errf("UDR Traffic Influence Data Delete Failure. Response Code: %d",
rsp.errorCode)
} else {
log.Infof("UDR Traffic Influence Data Delete Success."+
"Response Code: %d", rsp.errorCode)
}
return rsp, err
}
func getSpatialValidityData(cliCtx context.Context, nefCtx *nefContext,
spVal *SpatialValidity) error {
_ = cliCtx
_ = nefCtx
spVal.PresenceInfoList.PraID = "PRA_01"
spVal.PresenceInfoList.PresenceState = "IN_AREA"
spVal.PresenceInfoList.EcgiList = make([]Ecgi, 1)
spVal.PresenceInfoList.EcgiList[0].EutraCellID = "EUTRACELL_01"
spVal.PresenceInfoList.EcgiList[0].PlmnID.Mcc = "634"
spVal.PresenceInfoList.EcgiList[0].PlmnID.Mnc = "635"
spVal.PresenceInfoList.NcgiList = make([]Ncgi, 1)
spVal.PresenceInfoList.NcgiList[0].NrCellID = "NRCELL_01"
spVal.PresenceInfoList.NcgiList[0].PlmnID.Mcc = "834"
spVal.PresenceInfoList.NcgiList[0].PlmnID.Mnc = "835"
spVal.PresenceInfoList.GlobalRanNodeIDList = make([]GlobalRanNodeID, 1)
spVal.PresenceInfoList.GlobalRanNodeIDList[0].PlmnID.Mcc = "934"
spVal.PresenceInfoList.GlobalRanNodeIDList[0].PlmnID.Mnc = "935"
spVal.PresenceInfoList.GlobalRanNodeIDList[0].N3IwfID = "IWF_01"
spVal.PresenceInfoList.GlobalRanNodeIDList[0].GNbID.BitLength = 48
spVal.PresenceInfoList.GlobalRanNodeIDList[0].GNbID.GNBValue = "GNB_01"
spVal.PresenceInfoList.GlobalRanNodeIDList[0].NgeNbID = "NB_01"
return nil
}
func getSupiData(cliCtx context.Context, nefCtx *nefContext,
supi *Supi) error {
_ = cliCtx
_ = nefCtx
*supi = "imsi-8"
return nil
}
func getNetworkAreaInfo(cliCtx context.Context, nefCtx *nefContext,
nwAreaInfo *NetworkAreaInfo) error {
_ = cliCtx
_ = nefCtx
nwAreaInfo.Ecgis = make([]Ecgi, 1)
nwAreaInfo.Ecgis[0].EutraCellID = "EUTRACELL_01"
nwAreaInfo.Ecgis[0].PlmnID.Mcc = "634"
nwAreaInfo.Ecgis[0].PlmnID.Mnc = "635"
nwAreaInfo.Ncgis = make([]Ncgi, 1)
nwAreaInfo.Ncgis[0].NrCellID = "NRCELL_01"
nwAreaInfo.Ncgis[0].PlmnID.Mcc = "834"
nwAreaInfo.Ncgis[0].PlmnID.Mnc = "835"
nwAreaInfo.GRanNodeIds = make([]GlobalRanNodeID, 1)
nwAreaInfo.GRanNodeIds[0].PlmnID.Mcc = "934"
nwAreaInfo.GRanNodeIds[0].PlmnID.Mnc = "935"
nwAreaInfo.GRanNodeIds[0].N3IwfID = "IWF_01"
nwAreaInfo.GRanNodeIds[0].GNbID.BitLength = 48
nwAreaInfo.GRanNodeIds[0].GNbID.GNBValue = "GNB_01"
nwAreaInfo.GRanNodeIds[0].NgeNbID = "NB_01"
nwAreaInfo.Tais = make([]Tai, 1)
nwAreaInfo.Tais[0].PlmnID.Mcc = "734"
nwAreaInfo.Tais[0].PlmnID.Mnc = "735"
nwAreaInfo.Tais[0].Tac = "TAC_01"
return nil
}
|
package main
import (
"bytes"
"context"
"crypto/md5"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"regexp"
"strconv"
"time"
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/gomodule/redigo/redis"
"gopkg.in/olivere/elastic.v7"
)
var newsSummary map[string][]StdNews
var newsContent map[string][][]string
//create a mapping for es data storing
const mapping = `
{
"mappings": {
"properties": {
"id": {
"type": "long"
},
"title": {
"type": "text"
},
"source": {
"type": "keyword"
}
}
}
}`
/////数据归一化/////
//ZongHeNewsRaw contains raw material from API
type ZongHeNewsRaw struct {
Code int `json:"code"`
Msg string `json:"msg"`
Newslist []struct {
Ctime string `json:"ctime"`
Title string `json:"title"`
Description string `json:"description"`
PicURL string `json:"picUrl"`
URL string `json:"url"`
} `json:"newslist"`
}
//TouTiaoNewsRaw contains a raw material form API
type TouTiaoNewsRaw struct {
Code int `json:"code"`
Msg string `json:"msg"`
Newslist []struct {
Ctime string `json:"ctime"`
Title string `json:"title"`
Description string `json:"description"`
PicURL string `json:"picUrl"`
URL string `json:"url"`
Source string `json:"source"`
} `json:"newslist"`
}
//WangYiNewsRaw contains a raw material form API
type WangYiNewsRaw map[string][]struct {
LiveInfo interface{} `json:"liveInfo"`
Docid string `json:"docid"`
Source string `json:"source"`
Title string `json:"title"`
Priority int `json:"priority"`
HasImg int `json:"hasImg"`
URL string `json:"url"`
CommentCount int `json:"commentCount"`
Imgsrc3Gtype string `json:"imgsrc3gtype"`
Stitle string `json:"stitle"`
Digest string `json:"digest"`
Imgsrc string `json:"imgsrc"`
Ptime string `json:"ptime"`
Imgextra []struct {
Imgsrc string `json:"imgsrc"`
} `json:"imgextra,omitempty"`
}
//StdNews object is in standard format
type StdNews struct {
Timestamp string `json:"timestamp`
Source string `json:"source"`
Title string `json:"title"`
Body string `json:"body"`
PicURL string `json:"picurl`
URL string `json:"url"`
Types []string `json:"types"`
Keywords []string `json:keywords"`
}
//ZHToStd changes raw news to standard format
func ZHToStd(news ZongHeNewsRaw) {
for _, each := range news.Newslist {
var item StdNews
item.Timestamp = time.Now().Format("2006-01-02 15:04:05")
item.Source = "ZongHeNews"
item.Title = each.Title
item.Body = each.Description
item.URL = each.URL
item.PicURL = each.PicURL
newsSummary["ZHNews"] = append(newsSummary["ZHNews"], item)
}
}
//TTToStd changes raw news to standard format
func TTToStd(news TouTiaoNewsRaw) {
for _, each := range news.Newslist {
var item StdNews
item.Timestamp = time.Now().Format("2006-01-02 15:04:05")
item.Source = each.Source
item.Title = each.Title
item.Body = each.Description
item.URL = each.URL
item.PicURL = each.PicURL
newsSummary["TTNews"] = append(newsSummary["TTNews"], item)
}
}
//WYToStd changes raw news to standard format
func WYToStd(news WangYiNewsRaw) {
var key string
for k := range news {
key = k
}
for _, each := range news[key] {
var item StdNews
item.Timestamp = time.Now().Format("2006-01-02 15:04:05")
item.Source = each.Source
item.Title = each.Title
item.Body = each.Digest
item.URL = each.URL
item.PicURL = each.Imgsrc
newsSummary["WYNews"] = append(newsSummary["WYNews"], item)
}
}
func checkError(msg string, err error) {
if err != nil {
fmt.Println(msg, err)
os.Exit(1)
}
}
/////数据接入/////
//GetZongHeNews set-up in [zhNewsSummary] and [zhNewsContent]
func GetZongHeNews() {
url := "http://api.tianapi.com/generalnews/index?key=d9455e812137a7cd7c9ab10229c34ec6" //ZHNews url
resp, err := http.Get(url) //接口接入、get返回示例
checkError("Failed to fetch news", err)
body, err := ioutil.ReadAll(resp.Body) //转成可读形式(json)
resp.Body.Close() //断开连接
checkError("Failed to read news", err)
/////格式转换/////
var zongheNews ZongHeNewsRaw //创造object
err = json.Unmarshal([]byte(body), &zongheNews) //json转换到go
checkError("Failed to unmarshal json", err)
ZHToStd(zongheNews) //转换到标准格式
/////正文爬取/////
GetNewsContent(newsSummary["ZHNews"], 1)
}
//GetTouTiaoNews set-up in [ttNewsSummary] and [ttNewsContent]
func GetTouTiaoNews() {
url := "http://api.tianapi.com/topnews/index?key=d9455e812137a7cd7c9ab10229c34ec6"
resp, err := http.Get(url) //接口接入、get返回示例
checkError("Failed to fetch news", err)
body, err := ioutil.ReadAll(resp.Body) //转成可读形式
resp.Body.Close() //断开连接
checkError("Failed to read news", err)
/////格式转换/////
var toutiaoNews TouTiaoNewsRaw //创造object
err = json.Unmarshal([]byte(body), &toutiaoNews)
checkError("Failed to unmarshal json", err)
TTToStd(toutiaoNews) //转换到标准格式
/////正文爬取/////
GetNewsContent(newsSummary["TTNews"], 3)
}
//GetWangYiNews set-up in [wyNewsSummary] and [wyNewsContent]
func GetWangYiNews() {
//网易新闻API接口{“游戏”,“教育”,“新闻”,“娱乐”,“体育”,“财经”,“军事”,“科技”,“手机”,“数码”,“时尚”,“健康”,“旅游”}
urls := []string{"https://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BA8FF5PRwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BBM54PGAwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BA10TA81wangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BA8E6OEOwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BA8EE5GMwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BAI67OGGwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BA8D4A3Rwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BAI6I0O5wangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BAI6JOD9wangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BA8F6ICNwangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BDC4QSV3wangning/0-10.html",
"https://3g.163.com/touch/reconstruct/article/list/BEO4GINLwangning/0-10.html"}
for _, url := range urls {
resp, err := http.Get(url) //接口接入、get返回示例
checkError("Failed to fetch news", err)
body, err := ioutil.ReadAll(resp.Body) //转成可读形式(json)
resp.Body.Close() //断开连接
bodyStr := string(body)
bodyCut := bodyStr[9 : len(bodyStr)-1]
bodyJSON := []byte(bodyCut)
checkError("Failed to read news", err)
/////格式转换/////
var wangyiNews WangYiNewsRaw //创造object
err = json.Unmarshal([]byte(bodyJSON), &wangyiNews) //json转换到go
checkError("Failed to unmarshal json", err)
WYToStd(wangyiNews) //转换到标准格式
}
/////正文爬取/////
//GetNewsContent(newsSummary["WYNews"], 2)
}
func WangYiTest() {
url := "https://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-10.html"
resp, err := http.Get(url) //接口接入、get返回示例
checkError("Failed to fetch news", err)
body, err := ioutil.ReadAll(resp.Body) //转成可读形式(json)
resp.Body.Close() //断开连接
bodyStr := string(body)
bodyCut := bodyStr[9 : len(bodyStr)-1]
bodyJSON := []byte(bodyCut)
checkError("Failed to read news", err)
/////格式转换/////
var wangyiNews WangYiNewsRaw //创造object
err = json.Unmarshal([]byte(bodyJSON), &wangyiNews) //json转换到go
checkError("Failed to unmarshal json", err)
WYToStd(wangyiNews) //转换到标准格式
}
//GetNewsContent extracts all the chinese content in string form
func GetNewsContent(news []StdNews, id int) {
chineseRegExp := regexp.MustCompile("[\\p{Han}]+") //正则匹配中文格式
for _, each := range news {
url := each.URL
resp, err := http.Get(url) //access news article through url
if err == nil {
body, _ := ioutil.ReadAll(resp.Body) //get html body
resp.Body.Close()
chineseContent := chineseRegExp.FindAllString(string(body), -1) //find all the chinese content
if id == 1 {
newsContent["ZHNews"] = append(newsContent["ZHNews"], chineseContent)
WriteToFile(each, chineseContent) //write news info and content into file
} else if id == 2 {
newsContent["WYNews"] = append(newsContent["WYNews"], chineseContent)
WriteToFile(each, chineseContent) //write news info and content into file
} else {
newsContent["WYNews"] = append(newsContent["WYNews"], []string{each.Body})
WriteToFile(each, []string{each.Body}) //write news info and content into file
}
}
}
}
//WriteToFile stores data from API into "backUp.txt"
func WriteToFile(news StdNews, content []string) {
f, _ := os.OpenFile("newsData.txt", os.O_WRONLY|os.O_APPEND, 0600)
data, err := json.Marshal(news)
checkError("Failed to marshal news", err)
f.Write(data) //write marshaled news info in json format
f.WriteString("\n")
for _, s := range content {
f.WriteString(s)
}
f.WriteString("\n\n")
f.Close()
}
///kafka数据发送与接收/////
//DeliverMsgToKafka sends message to brokers with distinct topics
func DeliverMsgToKafka(topic string) {
//access data stored in [newsContent]
//data := newsContent[topic]
data := [][]string{[]string{topic}}
//initiate a new producer
producer, err := kafka.NewProducer(&kafka.ConfigMap{"bootstrap.servers": "127.0.0.1:9092"})
//check for successful creation of producer before proceeding
checkError("Failed to create producer: %s\n", err)
/////WRITES MESSAGE/////
//produce message
for _, news := range data {
producer.Produce(&kafka.Message{
TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny},
Value: []byte(news[0]),
}, nil)
}
//prints out message
fmt.Println("Produced message, waiting for delivery response.")
/////CHECK MESSAGE DELIVERY/////
//check delivery reponse with another goroutine
go func() {
//event used to listen for the result of send
for e := range producer.Events() {
switch ev := e.(type) {
case *kafka.Message:
if ev.TopicPartition.Error != nil {
fmt.Printf("Delivery failed: %v\n", ev.TopicPartition.Error)
} else {
fmt.Printf("Delivery message to topic %s [%d] at offset %v\n",
topic, ev.TopicPartition.Partition, ev.TopicPartition.Offset)
}
}
}
}()
//wait for message deliveries before shutting down
producer.Flush(15 * 1000)
}
//ConsumeMsgFromKafka consumes messages in the kafka brokers with distinct topics
func ConsumeMsgFromKafka(topic string) {
//initiate a new consumer
consumer, err := kafka.NewConsumer(&kafka.ConfigMap{
"bootstrap.servers": "127.0.0.1:9092",
"group.id": "myNews",
"auto.offset.reset": "earliest",
})
checkError("Failed to create consumer: %s\n", err)
//controls topic fetched
consumer.SubscribeTopics([]string{topic, "^aRegex.*[Tt]opic"}, nil)
//connect to redis
conn, err := redis.Dial("tcp", "127.0.0.1:6379")
checkError("Failed to connect to redis", err)
for {
//consumer poll message
msg, err := consumer.ReadMessage(-1)
if err != nil {
fmt.Printf("Consumer error: %v (%v)\n", err, msg)
} else {
value := string(msg.Value)
ProcessMsg(value, conn)
fmt.Printf("Message on %s: %s\n", msg.TopicPartition, value)
}
}
consumer.Close()
conn.Close()
}
//ProcessMsg 使用 redis 对新闻内容实现了去重
func ProcessMsg(msg string, conn redis.Conn) {
fmt.Println("checking")
data := md5.Sum([]byte(msg)) //convert according to md5
keyP := fmt.Sprintf("%x", data) //key to be set in redis
ret, err := conn.Do("EXISTS", keyP) //check if [keyP] exists
checkError("Failed to check key", err)
if exist, ok := ret.(int64); ok && exist == 1 {
return
}
_, err = conn.Do("SET", keyP, "")
checkError("Failed to set key "+keyP, err)
fmt.Println(redis.Strings(conn.Do("KEYS", "*")))
return
}
//StoreInES stores data in elasticsearch
func StoreInES(indexName string) {
/////initiate a new es client/////
ctx := context.Background() //create a context object for API calls
client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL([]string{"http://localhost:9200/"}...)) //instantiate a new es client object instance
checkError("Failed to initiate elasticsearch client", err)
exists, err := client.IndexExists(indexName).Do(ctx) //check whether given index exists
checkError("Index name already exists", err)
if !exists {
_, err := client.CreateIndex(indexName).BodyString(mapping).Do(ctx) //create if non-existent
checkError("Failed to create index", err)
}
/////writes in data/////
data := newsSummary["WYNews"]
for id, content := range data {
doc, _ := client.Index().
Index(indexName). //writes in index name
Id(strconv.Itoa(id)). //writes in id
BodyJson(content). //writes in data content
Refresh("wait_for").
Do(ctx) //executes
fmt.Printf("Indexed with id=%v, type=%s\n", doc.Id, doc.Type)
/////check for successful store/////
result, err := client.Get().
Index(indexName).
Id(strconv.Itoa(id)).
Do(ctx)
if err != nil {
panic(err)
}
if result.Found {
fmt.Printf("Got document %v (version=%d, index=%s, type=%s)\n",
result.Id, result.Version, result.Index, result.Type)
err := json.Unmarshal(result.Source, &content)
if err != nil {
panic(err)
}
fmt.Println(id, content.Source, content.Title)
}
}
MatchQuery(ctx, client, "网易游戏频道") //search through client on MatchQuery
fmt.Println("****")
}
//MatchQuery search through client on MatchQuery
func MatchQuery(ctx context.Context, client *elastic.Client, source string) {
fmt.Printf("Search: %s ", source)
// Term搜索
matchQuery := elastic.NewMatchQuery("source", source)
searchResult, err := client.Search().
Index("wy_news2").
Query(matchQuery).
//Sort("source", true). // 按id升序排序
From(0).Size(10). // 拿前10个结果
Pretty(true).
Do(ctx) // 执行
if err != nil {
panic(err)
}
total := searchResult.TotalHits()
fmt.Printf("Found %d subjects\n", total)
var std StdNews
if total > 0 {
for _, item := range searchResult.Each(reflect.TypeOf(std)) {
if t, ok := item.(StdNews); ok {
fmt.Printf("Found: Subject(source=%d, title=%s)\n", t.Source, t.Title)
}
}
} else {
fmt.Println("Not found!")
}
}
//QuerySearch search through QueryDSL
func QuerySearch() {
url := "http://localhost:9200/wy_news/_search"
query := `{
"query":{
"match" : {
"source": "网易游戏"
}
}
}`
resp, err := http.Post(url, "application/json", bytes.NewBuffer([]byte(query)))
checkError("Failed to fetch data", err)
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
checkError("Failed to read news", err)
fmt.Println(string(body))
}
func sayhelloName(w http.ResponseWriter, r *http.Request) {
WangYiTest()
}
func main() {
newsSummary = make(map[string][]StdNews) //initiate [newsSummary]
newsContent = make(map[string][][]string) //initiate [newsContent]
http.HandleFunc("/crawlnews", sayhelloName) //设置访问的路由
err := http.ListenAndServe(":9090", nil) //设置监听的端口
checkError("Failed to request http service", err)
//set up news
//GetZongHeNews()
//GetTouTiaoNews()
//GetWangYiNews()
//WangYiTest()
//deliver msg
//DeliverMsgToKafka("ZHNews")
//DeliverMsgToKafka("TTNews")
//DeliverMsgToKafka("WYNews")
//fetch msg
//ConsumeMsgFromKafka("ZHNews")
//ConsumeMsgFromKafka("TTNews")
//go ConsumeMsgFromKafka("WYNews")
//store data in ES
//StoreInES("wy_news2")
//QuerySearch() //search through QueryDSL
// fmt.Printf("%+v\n", GetZongHeNews())
// fmt.Printf("\n")
// fmt.Printf("%+v\n", GetTouTiaoNews())
}
|
package cli
import (
"io"
"os"
"strings"
"unicode"
"github.com/alecthomas/kong"
"github.com/gotidy/app/pkg/scope"
)
type LoggingFormat string
func (l LoggingFormat) AfterApply(scope *scope.Scope, writer *ConsoleWriter) error {
format := ColoredTextFormat
switch strings.ToLower(string(l)) {
case "coloredtext":
format = ColoredTextFormat
case "text":
format = TextFormat
case "json":
format = JSONFormat
}
*scope = scope.WithLogger(scope.Logger.Output(writer.Format(format)))
return nil
}
type LoggingLevel string
func (l LoggingLevel) BeforeApply(scope *scope.Scope) error {
level := InfoLevel
switch l {
case "debug":
level = DebugLevel
case "info":
level = InfoLevel
case "warn":
level = WarnLevel
case "error":
level = ErrorLevel
case "fatal":
level = FatalLevel
case "panic":
level = PanicLevel
case "trace":
level = TraceLevel
}
*scope = scope.WithLogger(scope.Logger.Level(level))
return nil
}
type LoggingOutput string
func (l LoggingOutput) AfterApply(scope *scope.Scope, writer *ConsoleWriter) (err error) {
// out := string(ctx.FlagValue(trace.Flag).(LoggingOutput))
out := string(l)
var w io.Writer
switch strings.ToUpper(string(out)) {
case "", "STDERR":
w = os.Stderr
case "STDOUT":
w = os.Stdout
default:
if w, err = os.OpenFile(string(out), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil {
return err
}
}
*scope = scope.WithLogger(scope.Logger.Output(writer.Out(w)))
return nil
}
type Cli struct {
// Common flags.
LoggingFormat LoggingFormat `help:"Logging format (${enum}). Default value: \"${default}\"" enum:"json,text,coloredtext" default:"coloredtext"`
LoggingLevel LoggingLevel `help:"Logging level (${enum})." enum:"debug,info,warn,error,fatal,panic,trace" default:"info"`
LoggingOutput LoggingOutput `help:"Logging output (stderr,stdout,<path>)." default:"stderr"`
// if the flag --config=<path> is defined, then config will be loaded
Config kong.ConfigFlag `type:"path" help:"Config path."`
// Used for showing version if defined --version flag
Version kong.VersionFlag
}
type Option func() kong.Option
// Name sets application name.
func Name(name string) Option {
return func() kong.Option { return kong.Name(name) }
}
// Version sets application version. It outputs when --version flag is defined.
func Version(version string) Option {
return func() kong.Option { return kong.Vars{"version": version} }
}
// Path sets configuration pathes.
func Paths(paths ...string) Option {
return func() kong.Option { return kong.Configuration(JSON, paths...) }
}
// Env inits environment names for flags.
// For example:
// --some.value -> PREFIX_SOME_VALUE
func Env(prefix string) Option {
processFlag := func(flag *kong.Flag) {
switch env := flag.Env; {
case flag.Name == "help":
return
case env == "-":
flag.Env = ""
return
case env != "":
return
}
replacer := strings.NewReplacer("-", "_", ".", "_")
name := replacer.Replace(flag.Name)
// Split by upper chars "SomeOne" -> ["Some", "One"]
var names []string
if prefix != "" {
names = []string{prefix}
}
for {
i := strings.IndexFunc(name, unicode.IsUpper)
if i < 0 {
names = append(names, strings.Trim(name, "_"))
break
}
names = append(names, strings.Trim(name[:i], "_"))
name = name[i:]
}
name = strings.ToUpper(strings.Join(names, "_"))
flag.Env = name
flag.Value.Tag.Env = name
}
var processNode func(node *kong.Node)
processNode = func(node *kong.Node) {
for _, flag := range node.Flags {
processFlag(flag)
}
for _, node := range node.Children {
processNode(node)
}
}
return func() kong.Option {
return kong.PostBuild(func(k *kong.Kong) error {
processNode(k.Model.Node)
return nil
})
}
}
// Run executes the Run() method on the selected command, which must exist.
func Run(cli interface{}, scope scope.Scope, options ...Option) {
root, err := CombineStructs(Cli{}, cli)
if err != nil {
ApplicationStartFailed(scope.Logger, err)
}
kongOptions := make([]kong.Option, 0, len(options))
for _, option := range options {
kongOptions = append(kongOptions, option())
}
kongOptions = append(kongOptions, kong.Bind(&scope), kong.Bind(NewConsoleWriter()), kong.Resolvers())
kongCtx := kong.Parse(root, kongOptions...)
if err = CopyStruct(root, cli); err != nil {
ApplicationStartFailed(scope.Logger, err)
}
err = kongCtx.Run(scope)
if err != nil {
ApplicationStartFailed(scope.Logger, err)
}
scope.WaitGroup.Wait()
ApplicationSuccessfulStopped(scope.Logger)
}
|
package v1
import (
"github.com/seaung/Go-Scaffolding/api/v1"
"github.com/gin-gonic/gin"
)
func InitUserRouters(router *gin.RouterGroup) {
router.GET("/demon", v1.Demon)
}
|
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-26 17:00
* Description:
*****************************************************************/
package regcenter
import (
"fmt"
"github.com/go-xe2/x/os/xfile"
"github.com/go-xe2/x/os/xfileNotify"
"github.com/go-xe2/x/sync/xsafeMap"
"github.com/go-xe2/xthrift/pdl"
"sync/atomic"
)
type THostStoreChangedEventFun func(store *THostStore, fileId int)
type HostStore interface {
SetOnChanged(fun THostStoreChangedEventFun)
GetSavePath() string
GetEnableFileWatch() bool
Load() error
AddHostWithProject(proj *pdl.FileProject, host string, port int, ext ...int)
AddHost(project string, svcFullNae string, host string, port int, ext ...int)
HasProject(project string) bool
RemoveHost(host string, port int) error
RemoveProject(project string) error
RemoveFile(fileName string)
Save() error
AllHosts() map[string][]*THostStoreToken
FileHosts(fileId int) map[string][]*THostStoreToken
FileHostsByName(fileName string) map[string][]*THostStoreToken
AllFileID() map[string]int
AllFileMd5() map[string]string
GetSvcHosts(fullSvcName string) []*THostStoreToken
EnableFileWatch() (err error)
DisableFileWatch()
IsFileWatch() bool
}
type THostStore struct {
// 当前最大文件id
maxFileId int
// 文件路径名称与id映射关系
fileIds map[string]int
filesMd5 *xsafeMap.TStrStrMap
fileWatcher *xfileNotify.TWatcher
watchCallback *xfileNotify.Callback
nDisableWatch int32
watchLayout int
savePath string
fileExt string
items map[string]map[string]*THostStoreToken
enableFileWatch bool
OnChanged THostStoreChangedEventFun
}
var _ HostStore = (*THostStore)(nil)
func NewHostStore(savePath string, fileExt string, enableFileWatch bool) *THostStore {
inst := &THostStore{
savePath: savePath,
fileExt: fileExt,
watchLayout: 0,
watchCallback: nil,
fileWatcher: nil,
enableFileWatch: enableFileWatch,
filesMd5: xsafeMap.NewStrStrMap(),
fileIds: make(map[string]int),
items: make(map[string]map[string]*THostStoreToken),
}
atomic.StoreInt32(&inst.nDisableWatch, 1)
return inst
}
func (p *THostStore) SetOnChanged(fun THostStoreChangedEventFun) {
p.OnChanged = fun
}
func (p *THostStore) HostFilePath() string {
fileName := xfile.Join(p.savePath)
return fileName
}
func (p *THostStore) MakeHostFileName(projectId string) string {
return xfile.Join(p.savePath, fmt.Sprintf("%s.%s", projectId, p.fileExt))
}
func (p *THostStore) GetSavePath() string {
return p.savePath
}
func (p *THostStore) GetEnableFileWatch() bool {
return p.enableFileWatch
}
|
package bag01
// New 创建01背包问题
func New(itemsW []int, w int) *Bag01 {
n := len(itemsW)
if n == 0 || w == 0 {
panic("error params")
}
// 初始化状态数组
status := make([][]bool, n)
for i := 0; i < n; i++ {
status[i] = make([]bool, w+1)
}
return &Bag01{itemsW, w, status}
}
// Bag01 01背包问题
// 固定物品范围的前提下,求背包可放物品最大重量
type Bag01 struct {
// 可放物品的重量
itemsW []int
// 背包承重能力
wCap int
// 状态数组 [层数][重量]
status [][]bool
}
// MaxWeight 动态规划求解
func (b *Bag01) MaxWeight() int {
n := len(b.itemsW)
// 赋值 第一层状态数组
b.status[0][0] = true
b.status[0][b.itemsW[0]] = true
// 求解 其他层状态数组
for i := 1; i < n; i++ {
for j := 0; j <= b.wCap; j++ {
// 上一层存在此重量
if b.status[i-1][j] {
b.status[i][j] = true
if j+b.itemsW[i] <= b.wCap {
b.status[i][j+b.itemsW[i]] = true
}
}
}
}
// 求解 最大重量
for j := b.wCap; j >= 0; j-- {
if b.status[n-1][j] {
return j
}
}
return 0
}
// MaxWeightItems 满足条件的物品
func (b *Bag01) MaxWeightItems() []int {
res := []int{}
j := b.MaxWeight()
if j == 0 {
return res
}
for i := len(b.status) - 1; i > 0; i-- {
if j-b.itemsW[i] >= 0 && b.status[i-1][j-b.itemsW[i]] {
res = append(res, i)
j = j - b.itemsW[i]
}
}
if j > 0 {
res = append(res, 0)
}
return res
}
|
package converter
import (
"github.com/stretchr/testify/assert"
"testing"
)
// Test case with incorrect input string with all digit cases
func TestInvalidInputStringWithDigits(t *testing.T) {
inputStrings := []string{
"4abc",
"4563",
}
for _, input := range inputStrings {
converter := NewStringConverter(input)
out, err := converter.Do()
assert.Empty(t, out)
assert.Error(t, err)
}
}
// Test case with incorrect input string with all Backslash cases
func TestInvalidInputStringWithBackslash(t *testing.T) {
inputStrings := []string{
"\\",
"\\abc",
"abc\\",
"344\\",
}
for _, input := range inputStrings {
converter := NewStringConverter(input)
out, err := converter.Do()
assert.Empty(t, out)
assert.Error(t, err)
}
}
// Test case with correct input string with all digit cases
func TestValidInputStringWithDigits(t *testing.T) {
testData := []struct {
in string
out string
}{
{"abed", "abed"},
{"a4bc2d5e", "aaaabccddddde"},
}
for _, data := range testData {
converter := NewStringConverter(data.in)
out, err := converter.Do()
assert.Nil(t, err)
assert.Equal(t, out, data.out)
}
}
// Test case with correct input string with all Backslash cases
func TestValidInputStringWithBackslash(t *testing.T) {
testData := []struct {
in string
out string
}{
{"qwe\\4\\5", "qwe\\\\\\\\\\\\\\\\\\"},
{"qwe\\4", "qwe\\\\\\\\"},
}
for _, data := range testData {
converter := NewStringConverter(data.in)
out, err := converter.Do()
assert.Nil(t, err)
assert.Equal(t, out, data.out)
}
}
|
package service
import (
entity "github.com/Surafeljava/Court-Case-Management-System/Entity"
"github.com/Surafeljava/Court-Case-Management-System/caseUse"
)
type OpponentServiceImpl struct {
oppoRepo caseUse.OpponentRepository
}
func NewOpponentServiceImpl(opRepo caseUse.OpponentRepository) *OpponentServiceImpl {
return &OpponentServiceImpl{oppoRepo: opRepo}
}
func (osi *OpponentServiceImpl) Opponents() ([]entity.Opponent, error) {
opps, errs := osi.oppoRepo.Opponents()
return opps, errs
}
func (osi *OpponentServiceImpl) Opponent(id int) (*entity.Opponent, []error) {
opp, errs := osi.oppoRepo.Opponent(id)
if len(errs) > 0 {
return nil, errs
}
return opp, nil
}
func (osi *OpponentServiceImpl) CreateOpponent(case_num string, opp *entity.Opponent) (*entity.Opponent, []error) {
opp, err1 := osi.oppoRepo.CreateOpponent(case_num, opp)
if len(err1) > 0 {
panic(err1)
}
return opp, err1
}
func (osi *OpponentServiceImpl) CheckOpponentRelation(case_num string, opType string) bool {
return osi.oppoRepo.CheckOpponentRelation(case_num, opType)
}
|
package web_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
account "williamfeng323/mooncake-duty/src/domains/account"
"williamfeng323/mooncake-duty/src/domains/project"
repoimpl "williamfeng323/mooncake-duty/src/infrastructure/db/repo_impl"
"williamfeng323/mooncake-duty/src/infrastructure/middlewares"
webInterface "williamfeng323/mooncake-duty/src/interfaces/web"
"github.com/gin-gonic/gin"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func TestProjectRouter(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Project Router Suite")
}
var _ = Describe("ProjectRouter", func() {
var router *gin.Engine
var testRecorder *httptest.ResponseRecorder
testProjectName := "TestBigProject"
testProjectDescription := "Test Big Project!!"
BeforeEach(func() {
router = gin.Default()
router.Use(middlewares.Logger())
webInterface.RegisterProjectRoute(router)
testRecorder = httptest.NewRecorder()
})
AfterEach(func() {
repoimpl.GetProjectRepo().DeleteOne(context.Background(), bson.M{"name": testProjectName})
})
Describe("GET /", func() {
BeforeEach(func() {
req, _ := http.NewRequest("PUT", "/projects",
bytes.NewReader([]byte(fmt.Sprintf(`{"name": "%s", "description": "%s"}`, testProjectName, testProjectDescription))))
router.ServeHTTP(httptest.NewRecorder(), req)
})
It("should return 200 if project name provided properly", func() {
req, _ := http.NewRequest("GET", fmt.Sprintf(`/projects?name=%s`, testProjectName), nil)
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(200))
})
It("should return 404 if project name cannot be found", func() {
req, _ := http.NewRequest("GET", `/projects?name=NotEvenAProject`, nil)
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(404))
})
})
Describe("PUT /", func() {
It("should return 400 if no name and description provided", func() {
req, _ := http.NewRequest("PUT", "/projects", bytes.NewReader([]byte(`{}`)))
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(400))
})
It("should return 400 if provided member but member does not exist", func() {
req, _ := http.NewRequest("PUT", "/projects", bytes.NewReader([]byte(
fmt.Sprintf(`{"name": "%s", "description": "%s", "members": [{"memberId": "123456789012345678901234"}]}`, testProjectName, testProjectDescription))))
router.ServeHTTP(testRecorder, req)
rsp := make(map[string]interface{})
json.Unmarshal(testRecorder.Body.Bytes(), &rsp)
Expect(testRecorder.Code).To(Equal(400))
Expect(rsp["error"]).To(Equal("Invalid member account"))
})
It("should return 200 and create project if name and description provided", func() {
req, _ := http.NewRequest("PUT", "/projects",
bytes.NewReader([]byte(fmt.Sprintf(`{"name": "%s", "description": "%s"}`, testProjectName, testProjectDescription))))
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(200))
rsp := make(map[string]project.Project)
json.Unmarshal(testRecorder.Body.Bytes(), &rsp)
Expect(rsp["project"].Name).To(Equal(testProjectName))
Expect(rsp["project"].Description).To(Equal(testProjectDescription))
})
})
Describe("GET /:id", func() {
prj := project.NewProject(testProjectName, testProjectDescription)
BeforeEach(func() {
prj.Create()
})
AfterEach(func() {
repoimpl.GetProjectRepo().DeleteOne(context.Background(), bson.M{"_id": prj.ID})
})
It("Should return 200 and the corresponding project details if the id is correct", func() {
req, _ := http.NewRequest("GET", fmt.Sprintf(`/projects/%s`, prj.ID.Hex()), nil)
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(200))
rst := map[string]project.Project{}
json.Unmarshal(testRecorder.Body.Bytes(), &rst)
Expect(rst["project"].Name).To(Equal(testProjectName))
Expect(rst["project"].Description).To(Equal(testProjectDescription))
})
It("Should return 404 if the id is invalid", func() {
req, _ := http.NewRequest("GET", `/projects/123456789012345678901234`, nil)
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(404))
})
It("Should return 400 if the id is not objectID format", func() {
req, _ := http.NewRequest("GET", `/projects/12345678`, nil)
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(400))
})
})
Describe("POST /:id", func() {
prj := project.NewProject("ProjectTestService", "This is a test project", project.Member{MemberID: primitive.NewObjectID(), IsAdmin: true})
prjService := &project.Service{}
prjService.SetRepo(repoimpl.GetProjectRepo())
acct1, _ := account.NewAccount("Test1@test.com", "Testaccount1")
acct2, _ := account.NewAccount("Test2@test.com", "Testaccount1")
BeforeEach(func() {
prj.Create()
acct1.Save(false)
acct2.Save(false)
})
AfterEach(func() {
repoimpl.GetAccountRepo().DeleteOne(context.Background(), bson.M{"_id": acct1.ID})
repoimpl.GetAccountRepo().DeleteOne(context.Background(), bson.M{"_id": acct2.ID})
repoimpl.GetProjectRepo().DeleteOne(context.Background(), bson.M{"_id": prj.ID})
})
It("Should return 404 if project id incorrect", func() {
req, _ := http.NewRequest("POST", fmt.Sprintf(`/projects/%s`, primitive.NewObjectID().Hex()), bytes.NewReader([]byte(`{"name":"test"}`)))
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(404))
})
It("Should return 400 if no data in body", func() {
req, _ := http.NewRequest("POST", fmt.Sprintf(`/projects/%s`, prj.ID.Hex()), bytes.NewReader([]byte(`{}`)))
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(400))
})
It("Should return 200 if name or description updated", func() {
req, _ := http.NewRequest("POST", fmt.Sprintf(`/projects/%s`, prj.ID.Hex()), bytes.NewReader([]byte(`{"name": "newTestName"}`)))
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(200))
})
It("Should return 200 if member updated", func() {
req, _ := http.NewRequest("POST", fmt.Sprintf(`/projects/%s`, prj.ID.Hex()),
bytes.NewReader([]byte(fmt.Sprintf(`{"members": [{"memberId": "%s", "isAdmin":true}]}`, acct1.ID.Hex()))))
router.ServeHTTP(testRecorder, req)
Expect(testRecorder.Code).To(Equal(200))
})
})
})
|
/*
A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid.
Each of these will hit (True):
.....
...O.
.....
...^.
.....
>O.
...
v....
O....
...........
...........
O.........<
...........
These will miss (False):
......
......
.^..O.
......
.....>
O.....
......
......
.O.
...
.v.
.....<.
..O....
Input: A rectangular grid of ., sized at least 2x2, with exactly one target O and one laser that's one of <>^v. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.
Output: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.
I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put (no regex) after the language name, your answer will appear separately in the leaderboard.
*/
package main
func main() {
assert(hit([]string{
".....",
"...O.",
".....",
"...^.",
".....",
}) == true)
assert(hit([]string{
">O.",
"...",
}) == true)
assert(hit([]string{
"v....",
"O....",
}) == true)
assert(hit([]string{
"...........",
"...........",
"O.........<",
"...........",
}) == true)
assert(hit([]string{
"......",
"......",
".^..O.",
}) == false)
assert(hit([]string{
"......",
".....>",
"O.....",
"......",
"......",
}) == false)
assert(hit([]string{
".O.",
"...",
".v.",
}) == false)
assert(hit([]string{
".....<.",
"..O....",
}) == false)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func hit(m []string) bool {
var (
l = vec2{-1, -1}
o = vec2{-1, -1}
t byte
)
for y := range m {
for x := range m[y] {
switch m[y][x] {
case 'O':
o = vec2{x, y}
case '<', '>', '^', 'v':
l = vec2{x, y}
t = m[y][x]
}
}
}
switch t {
case '<':
return l.x >= o.x && l.y == o.y
case '>':
return l.x <= o.x && l.y == o.y
case '^':
return l.x == o.x && l.y >= o.y
case 'v':
return l.x == o.x && l.y <= o.y
default:
return false
}
}
type vec2 struct {
x, y int
}
|
package router
import (
"fmt"
"log"
"github.com/nedp/command"
"github.com/nedp/command/sequence"
)
const defaultRoutesCapacity = 6
type Router struct {
routes map[string]func() Route
slots chan *slots
}
type Interface interface {
RouteFor(string) (Route, error)
SequenceFor(string) (sequence.RunAller, error)
AddRoute(name string, newSeq func(Params) sequence.RunAller, newPs func() Params)
OutputFor(req string) (<-chan string, error)
}
func (r Router) RouteFor(request string) (Route, error) {
return RouteFor(request, r.routes)
}
func (r Router) SequenceFor(request string) (sequence.RunAller, error) {
return SequenceFor(request, r.routes)
}
func (r *Router) AddRoute(name string, newSeq func(Params) sequence.RunAller,
newPs func() Params,
) {
r.routes[name] = func() Route {
return Route{
name,
newSeq,
newPs(), // Not called until after a route is retrieved from the map!
}
}
}
// New creates and returns a new Router,
// with a command pool of the specified size.
//
// nSlots is only used as an initial number of slots to
// make allocation more efficient.
// More slots will be allocated if needed, to a maximum of
// maxNSlots.
func New(nSlots int, maxNSlots int) Interface {
r := &Router{
make(map[string]func() Route, defaultRoutesCapacity),
make(chan *slots, 1),
}
r.slots <- newSlots(nSlots, maxNSlots)
r.AddRoute("status", NewStatusSequence, NewStatusParams(r))
r.AddRoute("pause", NewPauseSequence, NewPauseParams(r))
r.AddRoute("cont", NewContSequence, NewContParams(r))
r.AddRoute("stop", NewStopSequence, NewStopParams(r))
return r
}
// OutputFor routes a request, generating its sequence,
// then creating and running a new command for it.
//
// If there are currently no free slots for commands,
// more will be created.
//
// The request is routed using the routes already registered
// with the Router.
// A new output channel is created, passed to the command,
// and returned to the caller.
//
// Returns
// (the output channel, nil) if the routing succeeds; and
// (nil, an error) if the routing fails.
func (cr *Router) OutputFor(req string) (<-chan string, error) {
// Resolve the route
rt, err := cr.RouteFor(req)
if err != nil {
return nil, err
}
seq := rt.Sequence()
// Make the command
if err != nil {
return nil, fmt.Errorf("couldn't route the request: %s", err.Error())
}
s := <-cr.slots
defer func() { cr.slots <- s }()
cmd := command.New(seq, rt.Name)
// Put the command in a slot.
iSlot, err := s.Add(cmd)
if err != nil {
return nil, fmt.Errorf("couldn't add a new command: %s", err.Error())
}
outCh := make(chan string, 1)
// Run and free the command in a new thread.
go runThenFree(cr.slots, iSlot, outCh, rt.Name)
return outCh, nil
}
func runThenFree(sCh chan *slots, iSlot int, outCh chan<- string, name string) {
// TODO error handling other than printing logs and crashing.
// Get the command in the specified slot.
s := <-sCh
cmd := s.commands[iSlot]
sCh <- s
// Run the command.
log.Printf("running command `%s` in slot %d", name, iSlot)
outCh <- fmt.Sprintf("command `%s` running in slot %d with the following output:\n",
name, iSlot)
if cmd.Run(outCh) {
log.Printf("command `%s` in slot %d completed successfully", name, iSlot)
} else {
log.Printf("command `%s` in slot %d failed", name, iSlot)
}
// Free the slot.
s = <-sCh
err := s.Free(iSlot)
sCh <- s
if err != nil {
log.Printf("couldn't free slot %d: %s", iSlot, err.Error())
}
}
|
package common
import (
"fmt"
"os"
"os/user"
log "github.com/yugabyte/yugabyte-db/managed/yba-installer/logging"
)
/*
* Utility methods that allow us to log common actions
* like making dirs, copying files, etc
*/
func MkdirAll(path string, perm os.FileMode) error {
log.Debug(fmt.Sprintf("Creating dir %s", path))
return os.MkdirAll(path, perm)
}
func RenameOrFail(src string, dst string) {
log.Debug(fmt.Sprintf("Moving file from %s -> %s", src, dst))
err := os.Rename(src, dst)
if err != nil {
log.Fatal("Error: " + err.Error() + ".")
}
}
// MkdirAllOrFail creates a directory according to the given permissions, logging an error if necessary.
func MkdirAllOrFail(dir string, perm os.FileMode) {
err := MkdirAll(dir, perm)
if err != nil && !os.IsExist(err) {
log.Fatal(fmt.Sprintf("Error creating %s. Failed with %s", dir, err.Error()))
}
}
// CopyFile copies src file to dst.
// Assumes both src/dst are valid absolute paths and dst file parent directory is already created.
func CopyFile(src string, dst string) {
log.Debug("Copying from " + src + " -> " + dst)
bytesRead, errSrc := os.ReadFile(src)
if errSrc != nil {
log.Fatal("Error: " + errSrc.Error() + ".")
}
errDst := os.WriteFile(dst, bytesRead, 0644)
if errDst != nil {
log.Fatal("Error: " + errDst.Error() + ".")
}
}
func RemoveAll(path string) error {
log.Debug(fmt.Sprintf("Removing directory %s", path))
return os.RemoveAll(path)
}
func GetCurrentUser() string {
user, err := user.Current()
if err != nil {
log.Fatal(fmt.Sprintf("Error %s getting current user", err.Error()))
}
return user.Username
}
|
package main
import "fmt"
func main() {
ii := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
n := foo(ii...)
fmt.Println(n)
ii1 := []int{11, 22, 33, 44, 55}
n2 := bar(ii1)
fmt.Println(n2)
}
func foo(xi ...int) int {
total := 0
for _, v := range xi {
total += v
}
return total
}
func bar(x []int) int {
total := 0
for _, v := range x {
total += v
}
return total
}
|
package postgres
import (
"database/sql"
"github.com/idena-network/idena-indexer/explorer/types"
)
const (
identityQuery = "identity.sql"
identityAgeQuery = "identityAge.sql"
identityAnswerPointsQuery = "identityAnswerPoints.sql"
identityCurrentFlipsQuery = "identityCurrentFlips.sql"
identityEpochsCountQuery = "identityEpochsCount.sql"
identityEpochsQuery = "identityEpochs.sql"
identityFlipStatesQuery = "identityFlipStates.sql"
identityFlipRightAnswersQuery = "identityFlipRightAnswers.sql"
identityInvitesCountQuery = "identityInvitesCount.sql"
identityInvitesQuery = "identityInvites.sql"
identityTxsCountQuery = "identityTxsCount.sql"
identityTxsQuery = "identityTxs.sql"
identityRewardsCountQuery = "identityRewardsCount.sql"
identityRewardsQuery = "identityRewards.sql"
identityEpochRewardsCountQuery = "identityEpochRewardsCount.sql"
identityEpochRewardsQuery = "identityEpochRewards.sql"
identityFlipsCountQuery = "identityFlipsCount.sql"
identityFlipsQuery = "identityFlips.sql"
)
func (a *postgresAccessor) Identity(address string) (types.Identity, error) {
identity := types.Identity{}
err := a.db.QueryRow(a.getQuery(identityQuery), address).Scan(&identity.State)
if err == sql.ErrNoRows {
err = NoDataFound
}
if err != nil {
return types.Identity{}, err
}
identity.Address = address
if identity.ShortAnswers, identity.TotalShortAnswers, identity.LongAnswers, err = a.identityAnswerPoints(address); err != nil {
return types.Identity{}, err
}
return identity, nil
}
func (a *postgresAccessor) identityAnswerPoints(address string) (short, totalShort, long types.IdentityAnswersSummary, err error) {
rows, err := a.db.Query(a.getQuery(identityAnswerPointsQuery), address)
if err != nil {
return
}
defer rows.Close()
if !rows.Next() {
return
}
err = rows.Scan(&short.Point, &short.FlipsCount, &totalShort.Point, &totalShort.FlipsCount, &long.Point, &long.FlipsCount)
return
}
func (a *postgresAccessor) IdentityAge(address string) (uint64, error) {
var res uint64
err := a.db.QueryRow(a.getQuery(identityAgeQuery), address).Scan(&res)
if err == sql.ErrNoRows {
err = NoDataFound
}
if err != nil {
return 0, err
}
return res, nil
}
func (a *postgresAccessor) IdentityCurrentFlipCids(address string) ([]string, error) {
rows, err := a.db.Query(a.getQuery(identityCurrentFlipsQuery), address)
if err != nil {
return nil, err
}
defer rows.Close()
var res []string
for rows.Next() {
var item string
err = rows.Scan(&item)
if err != nil {
return nil, err
}
res = append(res, item)
}
return res, nil
}
func (a *postgresAccessor) IdentityEpochsCount(address string) (uint64, error) {
return a.count(identityEpochsCountQuery, address)
}
func (a *postgresAccessor) IdentityEpochs(address string, startIndex uint64, count uint64) ([]types.EpochIdentitySummary, error) {
rows, err := a.db.Query(a.getQuery(identityEpochsQuery), address, startIndex, count)
if err != nil {
return nil, err
}
return readEpochIdentitySummaries(rows)
}
func (a *postgresAccessor) IdentityFlipStates(address string) ([]types.StrValueCount, error) {
rows, err := a.db.Query(a.getQuery(identityFlipStatesQuery), address)
if err != nil {
return nil, err
}
return readStrValueCounts(rows)
}
func (a *postgresAccessor) IdentityFlipQualifiedAnswers(address string) ([]types.StrValueCount, error) {
rows, err := a.db.Query(a.getQuery(identityFlipRightAnswersQuery), address)
if err != nil {
return nil, err
}
return readStrValueCounts(rows)
}
func (a *postgresAccessor) IdentityInvitesCount(address string) (uint64, error) {
return a.count(identityInvitesCountQuery, address)
}
func (a *postgresAccessor) IdentityInvites(address string, startIndex uint64, count uint64) ([]types.Invite, error) {
rows, err := a.db.Query(a.getQuery(identityInvitesQuery), address, startIndex, count)
if err != nil {
return nil, err
}
return readInvites(rows)
}
func (a *postgresAccessor) IdentityTxsCount(address string) (uint64, error) {
return a.count(identityTxsCountQuery, address)
}
func (a *postgresAccessor) IdentityTxs(address string, startIndex uint64, count uint64) ([]types.TransactionSummary, error) {
rows, err := a.db.Query(a.getQuery(identityTxsQuery), address, startIndex, count)
if err != nil {
return nil, err
}
return readTxs(rows)
}
func (a *postgresAccessor) IdentityRewardsCount(address string) (uint64, error) {
return a.count(identityRewardsCountQuery, address)
}
func (a *postgresAccessor) IdentityRewards(address string, startIndex uint64, count uint64) ([]types.Reward, error) {
return a.rewards(identityRewardsQuery, address, startIndex, count)
}
func (a *postgresAccessor) IdentityEpochRewardsCount(address string) (uint64, error) {
return a.count(identityEpochRewardsCountQuery, address)
}
func (a *postgresAccessor) IdentityEpochRewards(address string, startIndex uint64, count uint64) ([]types.Rewards, error) {
rows, err := a.db.Query(a.getQuery(identityEpochRewardsQuery), address, startIndex, count)
if err != nil {
return nil, err
}
defer rows.Close()
var res []types.Rewards
var item *types.Rewards
for rows.Next() {
reward := types.Reward{}
var epoch uint64
var prevState, state string
var age uint16
if err := rows.Scan(&epoch, &reward.Balance, &reward.Stake, &reward.Type, &prevState, &state, &age); err != nil {
return nil, err
}
if item == nil || item.Epoch != epoch {
if item != nil {
res = append(res, *item)
}
item = &types.Rewards{
Epoch: epoch,
PrevState: prevState,
State: state,
Age: age,
}
}
item.Rewards = append(item.Rewards, reward)
}
if item != nil {
res = append(res, *item)
}
return res, nil
}
func (a *postgresAccessor) IdentityFlipsCount(address string) (uint64, error) {
return a.count(identityFlipsCountQuery, address)
}
func (a *postgresAccessor) IdentityFlips(address string, startIndex uint64, count uint64) ([]types.FlipSummary, error) {
return a.flips(identityFlipsQuery, address, startIndex, count)
}
|
package dbtool
type (
// Config config for postgres tool
Config struct {
DBName string
DBUser string
DBPass string
Host string
Port string
}
// Configurer return config
Configurer interface {
Config() *Config
}
)
|
package controller
import (
"encoding/json"
"fmt"
"main/model"
"main/structs"
"main/utils"
"net/http"
"strconv"
database "g.ghn.vn/scte-common/godal"
"github.com/labstack/echo/v4"
)
var (
EMP_DEP string = "emp_dep"
)
func AddEmployeeToDepartment(c echo.Context) error {
var err error
// get data from request, bind to EmpDep struct
dataReq := new(structs.EmpDep)
if err = c.Bind(dataReq); err != nil {
fmt.Println(err)
return ApiResult(c, http.StatusBadRequest, err)
}
//parse request data to map[string]interface{}
jsonData, err := json.Marshal(dataReq)
var newData map[string]interface{}
err = json.Unmarshal([]byte(jsonData), &newData)
fmt.Println(newData)
dbType := utils.Global[utils.POSTGRES_ENTITY].(database.Postgres)
// // get latest effect day
// result, err := model.GetLatestEffectDay(dbType, int(newData["employee_id"].(float64)))
// fmt.Printf("res: %+v", result)
// if err != nil {
// fmt.Println(err)
// return ApiResult(c, http.StatusBadRequest, err)
// }
// // t := time.Now()
// latestDay := result.(map[string]interface{})["effect_from"].(time.Time)
// inputDay := newData["effect_from"].(time.Time)
// diff := latestDay.Sub(inputDay)
// if diff > 0 {
// fmt.Println(diff)
// return ApiResult(c, http.StatusBadRequest, "invalid effect day")
// }
delete(newData, "id")
_, err = model.AddEmployeeToDeparmentWithMap(dbType, newData)
if err != nil {
fmt.Println("res error: ", err)
return ApiResult(c, http.StatusBadRequest, err)
}
return ApiResult(c, http.StatusOK, "success")
}
func UpdateEffectFromDate(c echo.Context) error {
var err error
// get data from request, bind to EmpDep struct
dataReq := new(structs.EmpDep)
if err = c.Bind(dataReq); err != nil {
return ApiResult(c, http.StatusBadRequest, err)
}
//parse request data to map[string]interface{}
jsonData, err := json.Marshal(dataReq)
var newData map[string]interface{}
err = json.Unmarshal([]byte(jsonData), &newData)
dbType := utils.Global[utils.POSTGRES_ENTITY].(database.Postgres)
_, err = model.Update(dbType, EMP_DEP, newData, map[string]interface{}{"id": dataReq.Id})
if err != nil {
return ApiResult(c, http.StatusBadRequest, err)
}
return ApiResult(c, http.StatusOK, "success")
}
func GetLatestEffectDayByEmpId(c echo.Context) error {
var employeeId int
var err error
if employeeId, err = strconv.Atoi(c.QueryParam("employeeid")); err != nil {
return ApiResult(c, http.StatusBadRequest, err)
}
dbType := utils.Global[utils.POSTGRES_ENTITY].(database.Postgres)
rs, err := model.GetLatestEffectDay(dbType, employeeId)
if err != nil {
return ApiResult(c, http.StatusBadRequest, err)
}
return ApiResult(c, http.StatusOK, rs)
}
|
package services
import (
"fmt"
"github.com/CS-SI/SafeScale/utils"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"io"
"os"
)
func init() {
log.SetFormatter(&utils.MyFormatter{ TextFormatter: log.TextFormatter{ForceColors:true, TimestampFormat : "2006-01-02 15:04:05", FullTimestamp:true, DisableLevelTruncation:true}})
log.SetLevel(log.DebugLevel)
// Log as JSON instead of the default ASCII formatter.
// log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
_ = os.MkdirAll(utils.AbsPathify("$HOME/.safescale"), 0777)
file, err := os.OpenFile(utils.AbsPathify("$HOME/.safescale/brokerd-session.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
log.SetOutput(io.MultiWriter(os.Stdout, file))
}
func infraErr(err error) error {
if err == nil {
return nil
}
tbr := errors.WithStack(err)
log.Errorf("%+v", err)
return tbr
}
func infraErrf(err error, message string, a ...interface{}) error {
if err == nil {
return nil
}
tbr := errors.WithStack(err)
tbr = errors.WithMessage(tbr, fmt.Sprintf(message, a...))
log.Errorf("%+v", err)
return tbr
}
func logicErr(err error) error {
if err == nil {
return nil
}
log.Errorf("%+v", err)
return err
}
func logicErrf(err error, message string, a ...interface{}) error {
if err == nil {
return nil
}
tbr := errors.Wrap(err, fmt.Sprintf(message, a...))
log.Errorf("%+v", tbr)
return tbr
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package api
import (
"strconv"
"strings"
"github.com/Azure/aks-engine/pkg/api/common"
)
func (cs *ContainerService) setCloudControllerManagerConfig() {
o := cs.Properties.OrchestratorProfile
isAzureCNIDualStack := cs.Properties.IsAzureCNIDualStack()
clusterCidr := o.KubernetesConfig.ClusterSubnet
if isAzureCNIDualStack {
clusterSubnets := strings.Split(clusterCidr, ",")
if len(clusterSubnets) > 1 {
clusterCidr = clusterSubnets[1]
}
}
staticCloudControllerManagerConfig := map[string]string{
"--allocate-node-cidrs": strconv.FormatBool(!o.IsAzureCNI() || isAzureCNIDualStack),
"--configure-cloud-routes": strconv.FormatBool(cs.Properties.RequireRouteTable()),
"--cloud-provider": "azure",
"--cloud-config": "/etc/kubernetes/azure.json",
"--cluster-cidr": clusterCidr,
"--kubeconfig": "/var/lib/kubelet/kubeconfig",
"--leader-elect": "true",
"--route-reconciliation-period": "10s",
"--v": "2",
}
// Disable cloud-node controller
staticCloudControllerManagerConfig["--controllers"] = "*,-cloud-node"
// Set --cluster-name based on appropriate DNS prefix
if cs.Properties.MasterProfile != nil {
staticCloudControllerManagerConfig["--cluster-name"] = cs.Properties.MasterProfile.DNSPrefix
}
// Default cloud-controller-manager config
defaultCloudControllerManagerConfig := map[string]string{
"--route-reconciliation-period": DefaultKubernetesCtrlMgrRouteReconciliationPeriod,
}
// If no user-configurable cloud-controller-manager config values exists, use the defaults
if o.KubernetesConfig.CloudControllerManagerConfig == nil {
o.KubernetesConfig.CloudControllerManagerConfig = defaultCloudControllerManagerConfig
} else {
for key, val := range defaultCloudControllerManagerConfig {
// If we don't have a user-configurable cloud-controller-manager config for each option
if _, ok := o.KubernetesConfig.CloudControllerManagerConfig[key]; !ok {
// then assign the default value
o.KubernetesConfig.CloudControllerManagerConfig[key] = val
}
}
}
// We don't support user-configurable values for the following,
// so any of the value assignments below will override user-provided values
for key, val := range staticCloudControllerManagerConfig {
o.KubernetesConfig.CloudControllerManagerConfig[key] = val
}
invalidFeatureGates := []string{}
// Remove --feature-gate VolumeSnapshotDataSource starting with 1.22
if common.IsKubernetesVersionGe(o.OrchestratorVersion, "1.22.0-alpha.1") {
invalidFeatureGates = append(invalidFeatureGates, "VolumeSnapshotDataSource")
}
removeInvalidFeatureGates(o.KubernetesConfig.CloudControllerManagerConfig, invalidFeatureGates)
// TODO add RBAC support
/*if *o.KubernetesConfig.EnableRbac {
o.KubernetesConfig.CloudControllerManagerConfig["--use-service-account-credentials"] = "true"
}*/
}
|
package exportAsciinemaJson
import (
"encoding/json"
tsm "github.com/stbuehler/go-termrecording/libtsm"
"github.com/stbuehler/go-termrecording/rawrecording"
"io"
)
type FilmFrame struct {
Delay float64
Diff interface{}
}
type FilmMaker struct {
FirstFrameOffset float64
LastFrameOffset float64
PreviousFrame *Frame
Frames []FilmFrame
}
func (filmFrame FilmFrame) MarshalJSON() ([]byte, error) {
return json.Marshal([]interface{}{filmFrame.Delay, filmFrame.Diff})
}
func (film FilmMaker) MarshalJSON() ([]byte, error) {
return json.Marshal(film.Frames)
}
func (film *FilmMaker) AddFrame(timeOffset float64, screen tsm.Screen) {
frame := MakeFrame(screen)
frameDiff := frame.Diff(film.PreviousFrame)
if frameDiff != nil {
delay := timeOffset - film.LastFrameOffset
if len(film.Frames) == 0 {
delay = 0 // first frame always starts at offset 0
film.FirstFrameOffset = timeOffset
}
film.Frames = append(film.Frames, FilmFrame{
Delay: delay,
Diff: frameDiff,
})
film.PreviousFrame = &frame
film.LastFrameOffset = timeOffset
}
}
func MakeFilm(jsonFileName string, jsonFile io.Writer, htmlFile io.Writer, fileReader *io.SectionReader) error {
reader, err := rawrecording.NewReaderFromSectionReader(fileReader)
if err != nil {
return err
}
film := FilmMaker{}
screen, err := tsm.NewScreen()
if err != nil {
return err
}
if err := screen.Resize(uint(reader.Meta.MaxTerminalSize.Columns), uint(reader.Meta.MaxTerminalSize.Rows)); err != nil {
return err
}
vte, err := tsm.NewVte(screen, nil)
if err != nil {
return err
}
// println(Stringify(reader.Meta))
for {
frame, _ := reader.ReadFrame()
if nil == frame {
break
}
vte.InputBytes(frame.Data)
// println(Stringify(frame))
film.AddFrame(frame.Offset, screen)
}
totalTime := film.LastFrameOffset - film.FirstFrameOffset
filmJson, err := json.Marshal(film)
if err != nil {
return err
}
if _, err := jsonFile.Write(filmJson); err != nil {
return err
}
snapshot := MakeFrame(screen)
err = WriteHTML(htmlFile, reader.Meta.MaxTerminalSize, &snapshot, jsonFileName, totalTime)
return err
}
|
package ssh
import (
"fmt"
"io/ioutil"
"os"
"sort"
"time"
)
// реализация сортировки hosts, необходимо чтобы вниз сваливались пофейленные
type sortHostStates struct {
slice []*hostState
}
func (h sortHostStates) Len() int {
return len(h.slice)
}
func (h sortHostStates) Swap(i, j int) {
h.slice[i], h.slice[j] = h.slice[j], h.slice[i]
}
func (h sortHostStates) Less(i, j int) bool {
hostI := h.slice[i]
hostJ := h.slice[j]
if hostI.err != nil && hostJ.err == nil {
return false
}
if hostI.err != nil && hostJ.err != nil {
return hostI.err.Error() < hostJ.err.Error()
}
return true
}
// отчет по запуску
func report(hosts []*hostState) {
time.Sleep(1 * time.Second)
fmt.Fprintf(os.Stderr, "--- Report --------------------------------\n")
sortedHostStates := &sortHostStates{slice: hosts}
sort.Sort(sortedHostStates)
// подсчет
var count, succ, notStarted, connFailed, execFailed int
badHosts := ""
for _, h := range sortedHostStates.slice {
count++
if h.startedAt == nil {
notStarted++
fmt.Fprintf(os.Stderr, "%s\t\t%v\n", h.visibleHostName, "< not started >")
badHosts += h.connectionAddress + "\n"
continue
}
if h.connectedAt == nil {
connFailed++
fmt.Fprintf(os.Stderr, "%s\t\t%v\t%v\n", h.visibleHostName, h.err, "< not connected >")
badHosts += h.connectionAddress + "\n"
continue
}
if h.endedAt == nil {
execFailed++
fmt.Fprintf(os.Stderr, "%s\t\t%v,\t< time %v >\n", h.visibleHostName, h.err, h.connectedAt.Sub(*h.startedAt))
badHosts += h.connectionAddress + "\n"
continue
}
if h.err == nil {
fmt.Fprintf(os.Stderr, "%s\t\t%v,\t< time %v >\n", h.visibleHostName, "< successfully completed >", h.endedAt.Sub(*h.startedAt))
succ++
} else {
fmt.Fprintf(os.Stderr, "%s\t\t%v,\t< time: %v >\n", h.visibleHostName, h.err, h.endedAt.Sub(*h.startedAt))
badHosts += h.connectionAddress + "\n"
}
}
// подвал
fmt.Fprintf(os.Stderr, "--------------------------------\n")
if notStarted == 0 && connFailed == 0 && execFailed == 0 {
fmt.Fprintf(os.Stderr, "Total: %v Success: %v\n", count, succ)
} else {
fmt.Fprintf(os.Stderr, "Total: %d Success: %d Connect failed: %d Execute failed: %d\n", count, succ, connFailed+notStarted, execFailed)
if file, err := ioutil.TempFile(os.TempDir(), "knife-sh-"); err == nil {
file.WriteString(badHosts)
fmt.Fprintf(os.Stderr, "File with bad hosts: %s\n", file.Name())
file.Sync()
file.Close()
}
os.Exit(count - succ)
}
}
|
package main
import (
"fmt"
"grpc/proto"
"context"
"net"
"google.golang.org/grpc"
)
type Message struct {}
func main() {
lis, err := net.Listen("tcp", ":4040")
if err != nil {
fmt.Println(err)
}
grpcServer := grpc.NewServer()
proto.RegisterMessageServiceServer(grpcServer, &Message{})
if e := grpcServer.Serve(lis); e != nil {
fmt.Println(e)
}
}
func (m *Message) GetMessage(ctx context.Context, message *proto.ClientMessage) (*proto.ClientMessage, error) {
fmt.Println("message from client", message.Message )
responseMessage := &proto.ClientMessage{
Message: "Hello from server",
}
return responseMessage, nil
}
func (m *Message) GetMessageStream(r *proto.ClientMessage, stream proto.MessageService_GetMessageStreamServer) error {
for i := 0; i< 5; i++ {
resp := proto.ClientMessage{ Message: "Hi from server" }
if err := stream.Send(&resp); err != nil {
return err;
}
}
return nil
} |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-07 12:15
* Description:
*****************************************************************/
package netstream
import (
"io"
"net/http"
)
type StreamWriterFlusher interface {
io.Writer
http.Flusher
}
|
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type ResTarget struct {
Name *string
Indirection *ast.List
Val ast.Node
Location int
}
func (n *ResTarget) Pos() int {
return n.Location
}
|
package Problem0350
func intersect(a1, a2 []int) []int {
res := []int{}
m1 := getInts(a1)
m2 := getInts(a2)
if len(m1) > len(m2) {
m1, m2 = m2, m1
}
// m1 是较短的字典,会快一些
for n := range m1 {
m1[n] = min(m1[n], m2[n])
}
for n, size := range m1 {
for i := 0; i < size; i++ {
res = append(res, n)
}
}
return res
}
// 清理重复的值,也便于查询
func getInts(a []int) map[int]int {
res := make(map[int]int, len(a))
for i := range a {
res[a[i]]++
}
return res
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
|
package main
import (
"fmt"
"net"
"os"
"strings"
)
type User struct {
Name string
ChatConn *net.UDPConn
}
var ErrorCode = 1
//监听的端口 && 地址
var ServerPort = ":1212"
var LocalHost = "127.0.0.1"
//
var isOnline = make(map[string]*net.UDPConn)
var userSlice = make([]User, 0)
//心跳包检查,检测用户是否在线
func HeartCheck() {
}
func UdpHandle(udpListener *net.UDPConn) {
buff := make([]byte, 128)
readLen, udpAddr, err := udpListener.ReadFromUDP(buff) //得到udp数据包,就是那个用户的
CheckError(err)
connClient, err := net.DialUDP("udp", nil, udpAddr)
CheckError(err)
if readLen > 0 {
request := parseBuffer(buff, readLen)
switch request[0] {
case "add":
isOnline[request[1]] = connClient
fmt.Println(udpAddr, " 上线了")
userSlice = append(userSlice, User{request[1], nil})
case "show":
for _, value := range userSlice {
sendMessage(value.Name+" online", connClient)
}
case "chat":
_, ok := isOnline[request[1]]
if !ok {
sendMessage("user "+request[1]+" off line", connClient)
break
}
context := ""
for i := 2; i < len(request); i++ {
context += request[i]
}
sendMessage(context, isOnline[request[1]])
}
}
}
func sendMessage(context string, conn *net.UDPConn) {
conn.Write([]byte(context))
}
// 把请求翻译出来
func parseBuffer(buff []byte, readLen int) []string {
buffString := string(buff[:readLen])
request := strings.Split(buffString, " ")
return request
}
func main() {
udpAddr, err := net.ResolveUDPAddr("udp", LocalHost+ServerPort)
CheckError(err)
udpListener, err := net.ListenUDP("udp", udpAddr)
CheckError(err)
defer udpListener.Close()
go HeartCheck()
fmt.Println("开始监听")
for {
UdpHandle(udpListener)
}
}
func CheckError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(ErrorCode)
}
}
|
func oddEvenList(head *ListNode) *ListNode {
i := 0
if head == nil || head.Next == nil {
return head
}
node := head
pre := node
pre1 := node.Next
for node != nil {
if i != 0 && i%2 == 0 {
pnext := pre.Next
nnext := node.Next
pre.Next = node
pre1.Next = nnext
node.Next = pnext
node = pre1
pre = pre.Next
pre1 = pre1.Next
}
i = i + 1
node = node.Next
}
return head
}
|
package blockchain
import (
"bytes"
"encoding/gob"
"log"
"time"
)
type Block struct {
Timestamp int64
Hash []byte // current hash
Transactions []*Transaction // transactions on block. needs to have at least 1 transaction. can have many different transactions as well
PrevHash []byte // last blocks hash
Nonce int
Height int
}
// proof of work algorithm must consider transactions stored in block, instead of just hashing the previous data field
func (b *Block) HashTransactions() []byte {
var txHashes [][]byte
for _, tx := range b.Transactions { // iterate through all transactions and append to 2d slice of bytes
txHashes = append(txHashes, tx.Serialize())
}
// generate a merkle tree using all transactions on this block. this can be used to quickly detect if a transaction belongs to a block??
tree := NewMerkleTree(txHashes)
// returns the merkle root
return tree.RootNode.Data
}
func CreateBlock(txs []*Transaction, prevHash []byte, height int) *Block {
block := &Block{time.Now().Unix(), []byte{}, txs, prevHash, 0, height} // returns memory address of this block
pow := NewProof(block) // create proof of work for this block
nonce, hash := pow.Run() // try to solve the proof of work here
block.Hash = hash[:] // set hash for the block
block.Nonce = nonce // set solved nonce for the block. to easily validate the block
return block
}
func Genesis(coinbase *Transaction) *Block { // first block in blockchain
return CreateBlock([]*Transaction{coinbase}, []byte{}, 0) // 0 since first block in blockchain
}
// serialize for database storage
func (b *Block) Serialize() []byte {
var res bytes.Buffer
encoder := gob.NewEncoder(&res)
err := encoder.Encode(b)
Handle(err)
return res.Bytes()
}
// deserialize when grabbing bytes from database
func Deserialize(data []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&block)
Handle(err)
return &block
}
func Handle(err error) {
if err != nil {
log.Panic(err)
}
}
|
/*
Copyright 2019 The Kubernetes 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 v1alpha3
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// BareMetalMachineTemplateSpec defines the desired state of BareMetalMachineTemplate
type BareMetalMachineTemplateSpec struct {
Template BareMetalMachineTemplateResource `json:"template"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:resource:path=baremetalmachinetemplates,scope=Namespaced,categories=cluster-api
// +kubebuilder:storageversion
// BareMetalMachineTemplate is the Schema for the baremetalmachinetemplates API
type BareMetalMachineTemplate struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec BareMetalMachineTemplateSpec `json:"spec,omitempty"`
}
// +kubebuilder:object:root=true
// BareMetalMachineTemplateList contains a list of BareMetalMachineTemplate
type BareMetalMachineTemplateList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []BareMetalMachineTemplate `json:"items"`
}
func init() {
SchemeBuilder.Register(&BareMetalMachineTemplate{}, &BareMetalMachineTemplateList{})
}
// BareMetalMachineTemplateResource describes the data needed to create a BareMetalMachine from a template
type BareMetalMachineTemplateResource struct {
// Spec is the specification of the desired behavior of the machine.
Spec BareMetalMachineSpec `json:"spec"`
}
|
package block
import (
"bytes"
"crypto/sha256"
"fmt"
"math/big"
)
//共识算法管理文件
//实现POW实例以及相关功能
//目标难度值
const targetBit = 16
//工作量证明的结构
type ProofOfWork struct {
// 需要共识验证的区块
Block *Block
// 目标难度的哈希
target *big.Int
}
//创建一个POW对象
func NewProofOfWork(block *Block) *ProofOfWork {
target := big.NewInt(1)
//数据长度为8位
//需求:需要满足前两位为0,才能解决问题
target = target.Lsh(target,256-targetBit)
return &ProofOfWork{block,target}
}
//执行POW,比较哈希
//返回哈希值,以及碰撞次数
func (proofOfWork *ProofOfWork) Run() ([]byte, int){
//碰撞次数
var nonce = 0
var hashInt big.Int
var hash [32]byte
//无线循环,生成符合条件的哈希值
for{
//生成准备数据
databyte := proofOfWork.prepareData(int64(nonce))
hash = sha256.Sum256(databyte)
//tmpInt := big.Int{}
hashInt.SetBytes(hash[:])
//检测生成的哈希值是否符合条件
if proofOfWork.target.Cmp(&hashInt) == 1 {
//找到了符合条件的哈希值,中断循环
break
}
nonce++
}
fmt.Printf("\n碰撞次数: %d\n",nonce)
return hash[:],nonce
}
//生成准备数据
func (pow *ProofOfWork) prepareData(nonce int64) []byte {
var data []byte
timeStampBytes := IntToHex(pow.Block.Timestamp)
heightBytes := IntToHex(pow.Block.Height)
data = bytes.Join([][]byte{
heightBytes,
timeStampBytes,
pow.Block.PrevBlockHash,
pow.Block.Data,
IntToHex(nonce),
IntToHex(targetBit),
}, []byte{})
return data
} |
package merkletree
import "hash"
type LeafHasherz interface {
HashLeaf(leaf []byte) []byte
}
type NodeHasher interface {
HashNode(l, r []byte) []byte
}
type TreeHasher interface {
LeafHasherz
NodeHasher
}
var _ TreeHasher = &DefaultTreeHasher{}
type DefaultTreeHasher struct {
h hash.Hash
}
func NewDefaultHasher(h hash.Hash) *DefaultTreeHasher {
return &DefaultTreeHasher{h}
}
func (d *DefaultTreeHasher) HashLeaf(leaf []byte) []byte {
return sum(d.h, leafHashPrefix, leaf)
}
func (d *DefaultTreeHasher) HashNode(l, r []byte) []byte {
return sum(d.h, nodeHashPrefix, l, r)
}
|
package virtualbox
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"github.com/Cloud-Foundations/Dominator/lib/format"
)
type headerType struct {
Header [0x40]byte
Signature uint32
VersionMajor uint16
VersionMinor uint16
HeaderSize uint32
ImageType uint32
ImageFlags uint32
Description [0x100]byte
OffsetBocks uint32
OffsetData uint32
Cylinders uint32
Heads uint32
Sectors uint32
SectorSize uint32
Unused [4]byte
DiscSize uint64
BlockSize uint32
BlockExtraData uint32
BlocksInHDD uint32
BlocksAllocated uint32
UuidImage uint64
UuidLastSnap uint64
UuidLink uint64
UuidParent uint64
}
func newReader(rawReader io.Reader) (*Reader, error) {
r := bufio.NewReaderSize(rawReader, 1<<20)
var header headerType
if err := binary.Read(r, binary.LittleEndian, &header); err != nil {
return nil, fmt.Errorf("error reading VDI header: %s", err)
}
if header.Signature != 0xbeda107f {
return nil, fmt.Errorf("%x not a VDI signature", header.Signature)
}
if header.VersionMajor < 1 {
return nil,
fmt.Errorf("VDI major version: %d not supported",
header.VersionMajor)
}
if header.ImageType != 1 {
return nil, fmt.Errorf("VDI image type: %d not supported",
header.ImageType)
}
if header.BlockSize != 1<<20 {
return nil, fmt.Errorf("VDI block size: 0x%x (%s) not supported",
header.BlockSize, format.FormatBytes(uint64(header.BlockSize)))
}
mul := uint64(header.BlockSize) * uint64(header.BlocksInHDD)
if mul != header.DiscSize {
return nil, fmt.Errorf("blockSize*blocksInHdd: %d != discSize: %d",
mul, header.DiscSize)
}
r.Reset(rawReader) // Discard until 1 MiB boundary.
lastPointer := int32(-1)
blockMap := make(map[uint32]struct{}, header.BlocksInHDD)
for index := uint32(0); index < header.BlocksInHDD; index++ {
var pointer int32
if err := binary.Read(r, binary.LittleEndian, &pointer); err != nil {
return nil,
fmt.Errorf("error reading block pointer: %d: %s", index, err)
}
if pointer >= 0 {
if pointer <= lastPointer {
return nil,
fmt.Errorf("VDI pointer: %d not greater than last: %d",
pointer, lastPointer)
}
blockMap[index] = struct{}{}
}
lastPointer = pointer
}
r.Reset(rawReader) // Discard until 1 MiB boundary.
return &Reader{
Description: string(header.Description[:]),
Header: string(header.Header[:]),
MajorVersion: header.VersionMajor,
MinorVersion: header.VersionMinor,
Size: header.DiscSize,
blockMap: blockMap,
blockSize: header.BlockSize,
blocksInHDD: header.BlocksInHDD,
reader: r,
}, nil
}
func (r *Reader) read(p []byte) (int, error) {
if r.blockIndex >= r.blocksInHDD {
return 0, io.EOF
}
blockIndex := r.blockIndex
if maxLength := r.blockSize - r.blockOffset; uint32(len(p)) >= maxLength {
p = p[:maxLength]
r.blockIndex++
r.blockOffset = 0
} else {
r.blockOffset += uint32(len(p))
}
if _, ok := r.blockMap[blockIndex]; !ok {
for index := range p {
p[index] = 0
}
return len(p), nil
}
return io.ReadFull(r.reader, p)
}
|
// +build acceptance networking
package v2
import (
"testing"
"github.com/gophercloud/gophercloud/acceptance/clients"
"github.com/gophercloud/gophercloud/acceptance/tools"
"github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
)
func TestPortsList(t *testing.T) {
client, err := clients.NewNetworkV2Client()
if err != nil {
t.Fatalf("Unable to create a network client: %v", err)
}
allPages, err := ports.List(client, nil).AllPages()
if err != nil {
t.Fatalf("Unable to list ports: %v", err)
}
allPorts, err := ports.ExtractPorts(allPages)
if err != nil {
t.Fatalf("Unable to extract ports: %v", err)
}
for _, port := range allPorts {
PrintPort(t, &port)
}
}
func TestPortsCRUD(t *testing.T) {
client, err := clients.NewNetworkV2Client()
if err != nil {
t.Fatalf("Unable to create a network client: %v", err)
}
// Create Network
network, err := CreateNetwork(t, client)
if err != nil {
t.Fatalf("Unable to create network: %v", err)
}
defer DeleteNetwork(t, client, network.ID)
// Create Subnet
subnet, err := CreateSubnet(t, client, network.ID)
if err != nil {
t.Fatalf("Unable to create subnet: %v", err)
}
defer DeleteSubnet(t, client, subnet.ID)
// Create port
port, err := CreatePort(t, client, network.ID, subnet.ID)
if err != nil {
t.Fatalf("Unable to create port: %v", err)
}
defer DeletePort(t, client, port.ID)
PrintPort(t, port)
// Update port
newPortName := tools.RandomString("TESTACC-", 8)
updateOpts := ports.UpdateOpts{
Name: newPortName,
}
newPort, err := ports.Update(client, port.ID, updateOpts).Extract()
if err != nil {
t.Fatalf("Could not update port: %v", err)
}
PrintPort(t, newPort)
}
|
package main
// oauth.go contains utility functions for managing oauth connections.
// Credit to the Go examples, from which this is mostly copied:
// https://code.google.com/p/google-api-go-client/source/browse/examples
// and which are Copyright (c) 2011 Google Inc. All rights reserved.
import (
"encoding/gob"
"errors"
"flag"
"fmt"
"hash/fnv"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"time"
"code.google.com/p/goauth2/oauth"
)
const (
defaultClientId string = "902751591868-ghc6jn2vquj6s8n5v5np2i66h3dh5pqq.apps.googleusercontent.com"
defaultSecret string = "LLsUuv2NoLglNKx14t5dA9SC"
)
var (
clientId = flag.String("clientid", "", "OAuth Client ID")
secret = flag.String("secret", "", "OAuth Client Secret")
cacheToken = flag.Bool("cachetoken", true, "cache the OAuth token")
httpDebug = flag.Bool("http.debug", false, "show HTTP traffic")
)
func tokenCacheFile(config *oauth.Config) string {
hash := fnv.New32a()
hash.Write([]byte(config.ClientId))
hash.Write([]byte(config.ClientSecret))
hash.Write([]byte(config.Scope))
fn := fmt.Sprintf("fuse-gdrive-token-%v", hash.Sum32())
return filepath.Join(osDataDir(), url.QueryEscape(fn))
}
func tokenFromFile(file string) (*oauth.Token, error) {
if !*cacheToken {
return nil, errors.New("--cachetoken is false")
}
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := new(oauth.Token)
err = gob.NewDecoder(f).Decode(t)
return t, err
}
func saveToken(file string, token *oauth.Token) {
dataDir := osDataDir()
_, err := os.Stat(dataDir)
if os.IsNotExist(err) {
if err := os.MkdirAll(dataDir, 0700); err != nil {
log.Printf("Warning: failed to cache oauth token: cache dir does not exist, could not create it: %v", err)
return
}
}
f, err := os.Create(file)
if err != nil {
log.Printf("Warning: failed to cache oauth token: %v", err)
return
}
defer f.Close()
gob.NewEncoder(f).Encode(token)
}
func tokenFromWeb(config *oauth.Config) *oauth.Token {
ch := make(chan string)
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
http.HandleFunc("/auth", func(rw http.ResponseWriter, req *http.Request) {
if req.FormValue("state") != randState {
log.Printf("State doesn't match: req = %#v", req)
http.Error(rw, "", 500)
return
}
if code := req.FormValue("code"); code != "" {
fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
rw.(http.Flusher).Flush()
ch <- code
return
}
log.Printf("no code")
http.Error(rw, "", 500)
})
config.RedirectURL = fmt.Sprintf("http://localhost:%s/auth", *port)
authUrl := config.AuthCodeURL(randState)
go openUrl(authUrl)
log.Printf("Authorize this app at: %s", authUrl)
code := <-ch
log.Printf("Got code: %s", code)
t := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
_, err := t.Exchange(code)
if err != nil {
log.Fatalf("Token exchange error: %v", err)
}
return t.Token
}
func openUrl(url string) {
try := []string{"xdg-open", "google-chrome", "open"}
for _, bin := range try {
err := exec.Command(bin, url).Run()
if err == nil {
return
}
}
log.Printf("Error opening URL in browser.")
}
func getOAuthClient(scope string) *http.Client {
// TODO: offer to cache clientid & secret if provided by flag
c := defaultClientId
s := defaultSecret
if *clientId != "" && *secret != "" {
c = *clientId
s = *secret
}
var config = &oauth.Config{
ClientId: c,
ClientSecret: s,
Scope: scope, // of access requested (drive, gmail, etc)
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
cacheFile := tokenCacheFile(config)
token, err := tokenFromFile(cacheFile)
if err != nil {
token = tokenFromWeb(config)
saveToken(cacheFile, token)
} else {
log.Printf("Using cached token %#v from %q", token, cacheFile)
}
t := &oauth.Transport{
Token: token,
Config: config,
Transport: http.DefaultTransport,
}
return t.Client()
}
// This is a terrible but simple hack. The better fix is coming.
func tokenKicker(client *http.Client, interval time.Duration) {
transport, ok := client.Transport.(*oauth.Transport)
if !ok {
log.Println("tokenKicker client must be an oauth client!")
return
}
log.Printf("access token expires: %s\n", transport.Token.Expiry)
for {
time.Sleep(interval)
if err := transport.Refresh(); err != nil {
log.Println("access token refresh failure: ", err)
} else {
log.Printf("access token refreshed! expires: %s\n", transport.Token.Expiry)
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Package engine takes an AKS cluster model and generates the corresponding template.
package engine
|
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
const (
addCommandUse = "add"
shortAddCommand = "Add pair key-value to cache"
longAddCommand = "Add pair key-value to cache with expiress time"
)
// NewAddCommand return new add command
func NewAddCommand() *cobra.Command {
addCmd := &cobra.Command{
Use: addCommandUse,
Short: shortAddCommand,
Long: longAddCommand,
Args: cobra.MinimumNArgs(2),
Run: addCommandFunc,
}
addCmd.Flags().StringVarP(&key, "key", "k", "", "cache key")
addCmd.Flags().StringVarP(&value, "value", "v", "", "cache value")
addCmd.Flags().StringVarP(&expiressTime, "expiress", "e", "", "key expiress time")
return addCmd
}
func addCommandFunc(cmd *cobra.Command, args []string) {
fmt.Printf("Add key: %s, value: %s, expiress: %s\n", key, value, expiressTime)
}
|
func longestCommonPrefix(strs []string) string {
size := len(strs)
if size == 0 {
return ""
}
result := strs[0]
for i := 0; i < size; i++ {
curr := strs[i]
result = comparePrefix(result, curr)
}
return result
}
func min(i1, i2 int) int {
if i1 > i2 {
return i2
}
return i1
}
func comparePrefix(str1, str2 string) string {
length := min(len(str1), len(str2))
prefix := ""
for i := 0; i < length; i++ {
if str1[i] == str2[i] {
prefix += string(str1[i])
} else {
return prefix
}
}
return prefix
} |
package efclient
import (
"bytes"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"sync"
"time"
"syreclabs.com/go/faker"
"syreclabs.com/go/faker/locales"
)
// ProductCategories ...
type ProductCategories = []ProductCategory
// ProductCategory ...
type ProductCategory struct {
ID int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
ParentProductCategory json.RawMessage `json:"parent_product_category"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Products []Product `json:"products"`
ChildrenProductCategories []ProductCategory `json:"children_product_categories"`
}
// ProductCategoryData ...
type ProductCategoryData struct {
Title string `json:"title"`
Description string `json:"description"`
ParentProductCategory int `json:"parent_product_category"`
}
// GetProductCategories ...
func (c *Client) GetProductCategories() (*ProductCategories, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/product-categories", c.BaseURL), nil)
if err != nil {
return nil, err
}
var res ProductCategories
if err := c.SendRequest(req, &res); err != nil {
return nil, err
}
return &res, nil
}
// CreateProductCategory ...
func (c *Client) CreateProductCategory(productCategoryData *ProductCategoryData) (*ProductCategory, error) {
requestData := map[string]interface{}{
"title": &productCategoryData.Title,
"description": &productCategoryData.Description,
"parent_product_category": &productCategoryData.ParentProductCategory,
}
requestBody, err := json.Marshal(requestData)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/product-categories", c.BaseURL), bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
var res ProductCategory
if err := c.SendRequest(req, &res); err != nil {
return nil, err
}
return &res, nil
}
// CreateFakeProductCategories ...
func (c *Client) CreateFakeProductCategories(wg *sync.WaitGroup, count int, firstParentID int, lastParentID int) int {
faker.Locale = locales.Ru
ch := make(chan int, count)
ch <- 0
for i := 0; i < count; i++ {
wg.Add(1)
time.Sleep(time.Millisecond * 50)
go func(wg *sync.WaitGroup) {
defer wg.Done()
parentID := 0
if firstParentID > 0 {
rand.Seed(time.Now().UnixNano())
parentID = rand.Intn(lastParentID-firstParentID+1) + firstParentID
}
fakeProductCategory := ProductCategoryData{
Title: faker.Commerce().Department(),
Description: faker.Lorem().Sentence(10),
ParentProductCategory: parentID,
}
log.Println(fakeProductCategory)
_, err := c.CreateProductCategory(&fakeProductCategory)
if err != nil {
log.Print(fmt.Errorf("%v", err))
// log.Fatal(err)
} else {
counter := <-ch
ch <- counter + 1
}
}(wg)
}
wg.Wait()
close(ch)
return <-ch
}
|
package main
import (
mlocswuc "leetcode/maxlengthofconcatstrwithuniquechars"
"log"
"time"
)
func main() {
start := time.Now()
uniques := mlocswuc.MaxLength([]string{"cha", "r", "act", "ers"})
elapsed := time.Since(start)
log.Println(elapsed)
log.Println(uniques)
}
|
package main
import (
"testing"
)
var (
root string
patterns []string
args = []string{"/opt/local", "e"}
)
func init() {
root, patterns = parseArgs(args)
}
func BenchmarkParseArgs(b *testing.B) {
for n := 0; n < b.N; n++ {
parseArgs(args)
}
}
func BenchmarkWalk(b *testing.B) {
for n := 0; n < b.N; n++ {
walk(root, patterns)
}
}
|
package flow
import (
"sync"
"testing"
)
// Starter component fires the network
// by sending a number given in its constructor
// to its output port.
type starter struct {
Component
Start <-chan float64
Out chan<- int
}
func (s *starter) OnStart(num float64) {
s.Out <- int(num)
}
func newStarter() interface{} {
s := new(starter)
return s
}
func init() {
Register("starter", newStarter)
}
// SequenceGenerator generates a sequence of integers
// from 0 to a number passed to its input.
type sequenceGenerator struct {
Component
Num <-chan int
Sequence chan<- int
}
func (s *sequenceGenerator) OnNum(n int) {
for i := 1; i <= n; i++ {
s.Sequence <- i
}
}
func newSequenceGenerator() interface{} {
return new(sequenceGenerator)
}
func init() {
Register("sequenceGenerator", newSequenceGenerator)
}
// Summarizer component sums all its input packets and
// produces a sum output just before shutdown
type summarizer struct {
Component
In <-chan int
// Flush <-chan bool
Sum chan<- int
StateLock *sync.Mutex
current int
}
func newSummarizer() interface{} {
s := new(summarizer)
s.Component.Mode = ComponentModeSync
return s
}
func init() {
Register("summarizer", newSummarizer)
}
func (s *summarizer) OnIn(i int) {
s.current += i
}
func (s *summarizer) Finish() {
s.Sum <- s.current
}
var runtimeNetworkJSON = `{
"properties": {
"name": "runtimeNetwork"
},
"processes": {
"starter": {
"component": "starter"
},
"generator": {
"component": "sequenceGenerator"
},
"doubler": {
"component": "doubler"
},
"sum": {
"component": "summarizer"
}
},
"connections": [
{
"data": 10,
"tgt": {
"process": "starter",
"port": "Start"
}
},
{
"src": {
"process": "starter",
"port": "Out"
},
"tgt": {
"process": "generator",
"port": "Num"
}
},
{
"src": {
"process": "generator",
"port": "Sequence"
},
"tgt": {
"process": "doubler",
"port": "In"
}
},
{
"src": {
"process": "doubler",
"port": "Out"
},
"tgt": {
"process": "sum",
"port": "In"
}
}
],
"exports": [
{
"private": "starter.Start",
"public": "Start"
},
{
"private": "sum.Sum",
"public": "Out"
}
]
}`
func TestRuntimeNetwork(t *testing.T) {
net, err := ParseJSON([]byte(runtimeNetworkJSON))
if err != nil {
t.Fatal(err)
}
start := make(chan float64)
out := make(chan int)
net.SetInPort("Start", start)
net.SetOutPort("Out", out)
RunNet(net)
// Wait for the network setup
<-net.Ready()
// Close start to halt it normally
close(start)
i := <-out
if i != 110 {
t.Errorf("Wrong result: %d != 110", i)
}
<-net.Wait()
}
|
package assembler
import (
"testing"
"log"
)
func init() {
var a float32 = 2
x := []float32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
y := []float32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
//log.Printf("avx %f", SaxpyAvx(a, x, y))
if useAVX {
SaxpyAvx(a, x, y)
}
log.Printf("x %v", x)
//log.Printf("sse4 %f", SaxpySSE4(a, x, y))
//log.Printf("generic %F", saxpy(a, x, y))
}
func saxpy(a float32, X []float32, Y []float32) {
for i := range X {
Y[i] += a * X[i]
}
}
func TestSaxpySSE4(t *testing.T) {
if useSSE4 {
funcScalarVectorVectorTest(SaxpySSE4, saxpy, t)
}
}
func TestSaxpyAvx(t *testing.T) {
if useAVX {
funcScalarVectorVectorTest(SaxpyAvx, saxpy, t)
}
}
func BenchmarkSaxpy(b *testing.B) { //benchmark function starts with "Benchmark" and takes a pointer to type testing.B
funcScalarVectorVectorBench(saxpy, b)
}
func BenchmarkSaxpySSE4Optimized(b *testing.B) { //benchmark function starts with "Benchmark" and takes a pointer to type testing.B
if useSSE4 {
funcScalarVectorVectorBench(SaxpySSE4, b)
}
}
func BenchmarkSaxpyAvxOptimized(b *testing.B) { //benchmark function starts with "Benchmark" and takes a pointer to type testing.B
if useAVX {
funcScalarVectorVectorBench(SaxpyAvx, b)
}
}
|
package main
import (
"fmt"
"math"
)
type Abser interface {
Abs() float64
}
func main() {
var a, b Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // MyFloat implements Abser
b = &v // *Vertex implements Abser
fmt.Println(b.Abs()) // 5
fmt.Println(a.Abs()) // 1.4142
// var c Abser
// c = v // Vertex does not implement Abser // panic
// fmt.Println(c.Abs()) // cannot work
}
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
|
package collector
import (
"github.com/prometheus/client_golang/prometheus"
)
func init() {
registerCollector("tcp", true, NewTCPCollector)
}
const (
tcpCollectorSubsystem = "tcp"
)
var (
tcpPacketsReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(namespace, tcpCollectorSubsystem, "tcp_packets_received_total"),
"tcp received total",
[]string{"tcp"}, nil,
)
tcpPacketsSentTotal = prometheus.NewDesc(
prometheus.BuildFQName(namespace, tcpCollectorSubsystem, "tcp_packets_sent_total"),
"tcp sent total idle",
[]string{"tcp"}, nil,
)
tcpPacketsErrorrTotal = prometheus.NewDesc(
prometheus.BuildFQName(namespace, tcpCollectorSubsystem, "tcp_packet_errors_total"),
"tcp error total",
[]string{"tcp"}, nil,
)
selectTCP = "SELECT @@pack_received tcp_packets_received_total, @@pack_sent tcp_packets_sent_total,@@packet_errors tcp_packet_errors_total"
)
type tcpCollector struct {
tcpReceived *prometheus.Desc
tcpSend *prometheus.Desc
tcpError *prometheus.Desc
}
func NewTCPCollector() (Collector, error) {
return &tcpCollector{
tcpReceived: tcpPacketsReceivedTotal,
tcpSend: tcpPacketsSentTotal,
tcpError: tcpPacketsSentTotal,
}, nil
}
func (c *tcpCollector) Update(ch chan<- prometheus.Metric) error {
if err := c.updateTCP(ch); err != nil {
return err
}
return nil
}
func (c *tcpCollector) updateTCP(ch chan<- prometheus.Metric) error {
rows, err := DB.Query(selectTCP)
if err != nil {
return err
}
var receved, send, errors float64
for rows.Next() {
rows.Scan(&receved, &send, &errors)
}
ch <- prometheus.MustNewConstMetric(
c.tcpReceived,
prometheus.GaugeValue,
receved,
"packets_received_total",
)
ch <- prometheus.MustNewConstMetric(
c.tcpSend,
prometheus.GaugeValue,
send,
"packets_send_total",
)
ch <- prometheus.MustNewConstMetric(
c.tcpError,
prometheus.GaugeValue,
errors,
"packets_error_total",
)
return nil
} |
//
// Copyright 2020 IBM 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 v1alpha1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// AuditLoggingSpec defines the desired state of AuditLogging
type AuditLoggingSpec struct {
// Fluentd defines the desired state of Fluentd
Fluentd AuditLoggingSpecFluentd `json:"fluentd,omitempty"`
// PolicyController has been deprecated.
PolicyController AuditLoggingSpecPolicyController `json:"policyController,omitempty"`
}
// AuditLoggingSpecFluentd defines the desired state of Fluentd
type AuditLoggingSpecFluentd struct {
EnableAuditLoggingForwarding bool `json:"enabled,omitempty"`
ImageRegistry string `json:"imageRegistry,omitempty"`
// ImageTag no longer supported. Define image sha or tag in operator.yaml
ImageTag string `json:"imageTag,omitempty"`
PullPolicy string `json:"pullPolicy,omitempty"`
// ClusterIssuer deprecated, use Issuer
ClusterIssuer string `json:"clusterIssuer,omitempty"`
Issuer string `json:"issuer,omitempty"`
Resources corev1.ResourceRequirements `json:"resources,omitempty"`
}
// AuditLoggingSpecPolicyController defines the policy controller configuration in the the audit logging spec.
type AuditLoggingSpecPolicyController struct {
// +kubebuilder:validation:Pattern=^(true|false)?$
EnableAuditPolicy string `json:"enabled,omitempty"`
ImageRegistry string `json:"imageRegistry,omitempty"`
ImageTag string `json:"imageTag,omitempty"`
PullPolicy string `json:"pullPolicy,omitempty"`
Verbosity string `json:"verbosity,omitempty"`
Frequency string `json:"frequency,omitempty"`
}
// StatusVersion defines the Operator versions
type StatusVersion struct {
Reconciled string `json:"reconciled"`
}
// AuditLoggingStatus defines the observed state of AuditLogging
type AuditLoggingStatus struct {
// Nodes defines the names of the audit pods
Nodes []string `json:"nodes"`
Versions StatusVersion `json:"versions,omitempty"`
}
// +kubebuilder:object:root=true
// AuditLogging is the Schema for the auditloggings API
// +kubebuilder:subresource:status
// +kubebuilder:resource:path=auditloggings,scope=Cluster
type AuditLogging struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec AuditLoggingSpec `json:"spec,omitempty"`
Status AuditLoggingStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// AuditLoggingList contains a list of AuditLogging
type AuditLoggingList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []AuditLogging `json:"items"`
}
func init() {
SchemeBuilder.Register(&AuditLogging{}, &AuditLoggingList{})
}
|
package main
import (
"fmt"
)
func main() {
messagesChan := make(chan string)
signalsChan := make(chan bool)
// non-blocking receive. If there is no one sends through channel, do what in the "default"
select {
case msgStr := <-messagesChan:
fmt.Println("received: ", msgStr)
default:
fmt.Println("no message received")
}
// non-blocking send. channel has no buffer and no receiver, so it cannot send to the channel
msg := "hi"
select {
case messagesChan <- msg:
fmt.Println("sent message: ", msg)
default:
fmt.Println("no message sent")
}
select {
case msg := <-messagesChan:
fmt.Println("received message", msg)
case sig := <-signalsChan:
fmt.Println("received signal", sig)
default:
fmt.Println("no activity")
}
}
|
package main
import "testing"
func TestPalindrome(t *testing.T) {
tables := []struct {
input string
result bool
}{
{"abba", true},
{"abbba", true},
{"aabba", false},
{"ababba", false},
{"ababa", true},
}
for _, table := range tables {
result := Palindrome(table.input)
if result != table.result {
t.Errorf(
"Palindrome('%s') - expected: %v, got: %v",
table.input,
table.result,
result,
)
}
}
}
|
package handler
import (
"log"
"net/http"
. "github.com/patrickmn/go-cache"
"github.com/go-openapi/runtime/middleware"
"github.com/gorilla/mux"
)
func Routes(c *Cache) *mux.Router {
// Register handler functions.
r := mux.NewRouter()
r.Use(loggingMiddleware)
r.HandleFunc("/", NothingToDoHandler).Methods("GET")
r.HandleFunc("/topsecret/", func(w http.ResponseWriter, r *http.Request) {
TopSecretHandler(w, r, c)
}).Methods("POST")
r.HandleFunc("/topsecret_split/", func(w http.ResponseWriter, r *http.Request) {
TopSecretSplitGetHandler(w, r, c)
}).Methods("GET")
r.HandleFunc("/topsecret_split/{name}", func(w http.ResponseWriter, r *http.Request) {
TopSecretSplitPushSingleHandler(w, r, c)
}).Methods("POST")
// handler for documentation
opts := middleware.RedocOpts{SpecURL: "../../swagger.yaml"}
sh := middleware.Redoc(opts, nil)
r.Handle("/docs", sh)
r.Handle("/swagger.yaml", http.FileServer(http.Dir("../../")))
return r
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.RequestURI)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
|
package database
import (
"context"
"ctipo/pkg/models"
"strings"
"github.com/georgysavva/scany/pgxscan"
"github.com/prometheus/common/log"
)
const getPacienteQuery = "SELECT nome,cpf, prontuario, data_nascimento,sexo, id_endereco FROM Paciente where prontuario = $1"
const buscaPacientesQuery = "SELECT nome,cpf, prontuario, data_nascimento,sexo, id_endereco FROM Paciente WHERE LOWER(nome) LIKE CONCAT('%', LOWER($1), '%') OR prontuario LIKE CONCAT('%', $1, '%')"
func GetPaciente(prontuario string) *models.Paciente {
dbConnection := GetDBConnection()
var pacientes []*models.Paciente
if err := pgxscan.Select(context.Background(), dbConnection, &pacientes, getPacienteQuery, prontuario); err != nil {
log.Warnf("Failed on retrieving prices for backtest from the database. %v", err.Error())
return nil
}
return pacientes[0]
}
//BuscarPacientes procura por todos os pacientes que possuem a queryBusca similar ao prontuario ou nome
//espacos podem ser representados pelo sinal +
func BuscarPacientes(queryBusca string) []*models.Paciente {
dbConnection := GetDBConnection()
queryBusca = strings.Replace(queryBusca, "+", " ", -1)
var pacientes []*models.Paciente
if err := pgxscan.Select(context.Background(), dbConnection, &pacientes, buscaPacientesQuery, queryBusca); err != nil {
log.Warnf("Failed on retrieving prices for backtest from the database. %v", err.Error())
return nil
}
return pacientes
}
|
package main
import (
"fmt"
)
func main() {
c := make(chan int, 10)
c <- 0
fmt.Printf("%#v, len: %v, cap: %v\n", c, len(c), cap(c))
}
|
package main
import (
"fmt"
"time"
)
func sendMessages(receiver chan string) {
// Create a slice of some strings to send.
messages := []string{
"ping",
"pong",
"pinggg",
}
// Send the 3 messages to the receiver
for _, m := range messages {
fmt.Println("sendMessages is sending:", m)
receiver <- m
}
}
func main() {
// Create a channel for sending and receiving strings.
messages := make(chan string)
// Start a new goroutine that will send some messages.
go sendMessages(messages)
// Receive the 3 messages sent by the goroutine.
for i := 0; i < 3; i++ {
// Wait 1s between each receive.
time.Sleep(1 * time.Second)
receivedMessage := <-messages
fmt.Println("Main has received:", receivedMessage)
}
// ? Question 1b -
// ? Only 2 messags are receieved
fmt.Println("===== [Question 1b] =====")
// go sendMessages(messages)
for i := 0; i < 2; i++ {
// time.Sleep(1 * time.Second)
// receivedMessage := <-messages
// fmt.Println("Main has received:", receivedMessage)
}
// * The goroutine still sends the third message but
// * it is not received
<- messages // get rid of the last message for the next exercise
// ? Question 1c -
// ? Try to receieve 4 messages
fmt.Println("===== [Question 1c] =====")
go sendMessages(messages)
for i := 0; i < 4; i++ {
time.Sleep(1 * time.Second)
receivedMessage := <- messages
fmt.Println("Main has received:", receivedMessage)
}
// * The goroutine has no more messages to send
// * so it fails to produce an output
}
|
package main
/**
和为K的子数组
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1:
```
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
```
说明 :
- 数组的长度为 [1, 20,000]。
- 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
*/
/**
太晚了,今天过了吧
*/
func SubarraySum(nums []int, k int) int {
return -1
}
|
package blevebench
import (
"encoding/json"
"io/ioutil"
"log"
"github.com/blevesearch/bleve"
)
type BenchConfig struct {
IndexType string `json:"index_type"`
KVStore string `json:"kvstore"`
KVConfig map[string]interface{} `json:"kvconfig"`
}
func LoadConfigFile(path string) *BenchConfig {
benchConfig := BenchConfig{
IndexType: bleve.Config.DefaultIndexType,
KVStore: bleve.Config.DefaultKVStore,
KVConfig: map[string]interface{}{},
}
if path != "" {
configBytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(configBytes, &benchConfig)
if err != nil {
log.Fatal(err)
}
}
return &benchConfig
}
|
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
func main() {
//在服务器启动etcd
// nohup ./etcd --listen-client-urls 'http://0.0.0.0:2379' --advertise-client-urls 'http://0.0.0.0:2379' &
config := clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"}, //集群列表
DialTimeout: 5 * time.Second,
}
//建立一个客户端
client, err := clientv3.New(config)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("链接成功")
//申请一个lease(租约)
lease := clientv3.NewLease(client)
//10s的租约
leaseGrantResp, err := lease.Grant(context.TODO(), 10)
if err != nil {
fmt.Println(err)
return
}
leaseId := leaseGrantResp.ID
//超时
//ctx,_ := context.WithTimeout(context.TODO(),5*time.Second)
//自动续租约
keepAliveChan, err := lease.KeepAlive(context.TODO(), leaseId)
if err != nil {
fmt.Println(err)
return
}
//启动一个协程,接收keepAlive的信息
go func() {
for {
select {
case keepResp := <-keepAliveChan:
if keepAliveChan == nil {
fmt.Println("租约已经失效了")
goto END
} else if keepResp != nil {
//每秒会续租一次,所以就会受到一次应答
fmt.Println("收到自动续租应答", keepResp.ID)
}
}
}
END:
fmt.Println("结束接收应答的协程")
}()
//用于读写etcd的键值对
kv := clientv3.NewKV(client)
//put一个kv,让它与租约关联起来,从而实现10s后自动过期
//opt with-lease
putResp, err := kv.Put(context.TODO(), "/cron/lock/job1", "", clientv3.WithLease(leaseId))
if err != nil {
fmt.Println(err)
return
}
fmt.Println("写入成功:", putResp.Header.Revision)
//定时看一下key过期与否
for {
getResp, err := kv.Get(context.TODO(), "/cron/lock/job1")
if err != nil {
return
}
if getResp.Count == 0 {
fmt.Println("kv过期了")
break
}
fmt.Println("kv还没过期", getResp.Kvs)
time.Sleep(2 * time.Second)
}
}
|
package main
import (
"fmt"
)
// in return we don't have to write variable names if return values are defined as follows
func addSub(x int, y int) (add int, sub int) {
add = x + y
sub = x - y
return
}
func main() {
add, sub := addSub(14, 7)
fmt.Println(add, sub)
}
|
package child
import (
"gopkg.in/mgo.v2/bson"
"time"
mgo "gopkg.in/mgo.v2"
)
type ChildRepo struct {
Collection *mgo.Collection
}
//MONGO FUNCTIONS
func (repo ChildRepo) create(member *Child) error {
//check the family
query := bson.M{
"family_id": member.Family,
"name": member.Name,
}
exist, err := repo.exist(query)
if !exist && err != nil {
member.Created = time.Now()
member.Updated = time.Now()
err = repo.update(member)
return err
}
return err
}
func (r ChildRepo) exist(query bson.M) (bool, error) {
query_response, error := r.Collection.Find(query).Count()
return query_response < 1, error
}
func (r ChildRepo) update(item *Child) (err error) {
var id bson.ObjectId
if item.Id.Hex() == "" {
id = bson.NewObjectId()
} else {
id = item.Id
}
item.Updated = time.Now()
_, err = r.Collection.UpsertId(id, item)
return
}
func (r ChildRepo) all() (items []Child, err error) {
err = r.Collection.Find(bson.M{}).All(&items)
return
}
func (r ChildRepo) destroy(id string) (err error) {
bid := bson.ObjectIdHex(id)
err = r.Collection.RemoveId(bid)
return
}
|
package inspect
import (
"testing"
"github.com/makkes/gitlab-cli/mock"
)
func TestSubCommands(t *testing.T) {
cmd := NewCommand(mock.Client{})
subCmds := cmd.Commands()
if len(subCmds) != 3 {
t.Errorf("Expected 1 sub-command but got %d", len(subCmds))
}
if cmd.UseLine() != "inspect" {
t.Errorf("Unexpected usage line '%s'", cmd.UseLine())
}
}
|
package realm
import (
"encoding/json"
"fmt"
"net/http"
"github.com/10gen/realm-cli/internal/utils/api"
)
// Routes for functions
const (
FunctionsPattern = appPathPattern + "/functions"
AppDebugExecuteFunctionPattern = appPathPattern + "/debug/execute_function"
)
type stats struct {
ExecutionTime string `json:"execution_time,omitempty"`
}
// ExecutionResults contains the details around a function execution
type ExecutionResults struct {
Result interface{} `json:"result,omitempty"`
Logs []string `json:"logs,omitempty"`
ErrorLogs []string `json:"error_logs,omitempty"`
Stats stats `json:"stats,omitempty"`
}
// Function is a realm Function
type Function struct {
ID string `json:"_id"`
Name string `json:"name"`
}
func (c *client) AppDebugExecuteFunction(groupID, appID, userID, name string, args []interface{}) (ExecutionResults, error) {
query := map[string]string{}
if userID == "" {
query["run_as_system"] = "true"
} else {
query["user_id"] = userID
}
res, err := c.doJSON(
http.MethodPost,
fmt.Sprintf(AppDebugExecuteFunctionPattern, groupID, appID),
map[string]interface{}{
"name": name,
"arguments": args,
},
api.RequestOptions{Query: query},
)
if err != nil {
return ExecutionResults{}, err
}
if res.StatusCode != http.StatusOK {
return ExecutionResults{}, api.ErrUnexpectedStatusCode{"debug execute function", res.StatusCode}
}
defer res.Body.Close()
var response ExecutionResults
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return ExecutionResults{}, err
}
return response, nil
}
func (c *client) Functions(groupID, appID string) ([]Function, error) {
res, err := c.do(
http.MethodGet,
fmt.Sprintf(FunctionsPattern, groupID, appID),
api.RequestOptions{},
)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, api.ErrUnexpectedStatusCode{"list functions", res.StatusCode}
}
defer res.Body.Close()
var result []Function
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
|
package routers
import (
"github.com/gorilla/mux"
"github.com/ismayilmalik/avengers-api/controllers"
)
func InitUserRoutes(r *mux.Router) *mux.Router {
controller := controllers.UserController{}
router := mux.NewRouter()
router.HandleFunc("/users", controller.Create).Methods("POST")
router.HandleFunc("/users/login", controller.Login).Methods("POST")
return router
}
|
package server
import (
"github.com/gin-gonic/gin"
"gopkg.in/mgo.v2"
"net/http"
)
func NewServer(session *DatabaseSession) *gin.Engine {
s := gin.Default()
s.Use(session.Database())
s.GET("/persons", func(c *gin.Context) {
db := c.MustGet("db").(*mgo.Database)
c.JSON(http.StatusOK, fetchAllPersons(db))
})
s.POST("/persons", func(c *gin.Context) {
var json Person
if c.BindJSON(&json) == nil {
db := c.MustGet("db").(*mgo.Database)
err := db.C("persons").Insert(json)
if err == nil {
c.JSON(201, json)
} else {
c.JSON(400, gin.H{"error": err.Error()})
}
}
})
return s
}
|
package main
import (
"CaculatorAPI/router"
"github.com/Sirupsen/logrus"
"net/http"
"os"
)
func main() {
rCors := router.CompleteRouterSetup()
port := os.Getenv("PORT")
port = "8080"
if port == "" {
logrus.Error("$Cannot get #PORT value from system and port value has been set to 8080")
port = "8080"
}
logrus.Info("Listening and servering on port: "+port)
err := http.ListenAndServe(":"+port, rCors)
logrus.Error(err)
}
|
package amazon
import ec2 "github.com/aws/aws-sdk-go/service/ec2"
import mock "github.com/stretchr/testify/mock"
// mockClient is an autogenerated mock type for the client type
type mockClient struct {
mock.Mock
}
// AssociateAddress provides a mock function with given fields: _a0
func (_m *mockClient) AssociateAddress(_a0 *ec2.AssociateAddressInput) (*ec2.AssociateAddressOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.AssociateAddressOutput
if rf, ok := ret.Get(0).(func(*ec2.AssociateAddressInput) *ec2.AssociateAddressOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.AssociateAddressOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.AssociateAddressInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// AuthorizeSecurityGroupIngress provides a mock function with given fields: _a0
func (_m *mockClient) AuthorizeSecurityGroupIngress(_a0 *ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.AuthorizeSecurityGroupIngressOutput
if rf, ok := ret.Get(0).(func(*ec2.AuthorizeSecurityGroupIngressInput) *ec2.AuthorizeSecurityGroupIngressOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.AuthorizeSecurityGroupIngressOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.AuthorizeSecurityGroupIngressInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CancelSpotInstanceRequests provides a mock function with given fields: _a0
func (_m *mockClient) CancelSpotInstanceRequests(_a0 *ec2.CancelSpotInstanceRequestsInput) (*ec2.CancelSpotInstanceRequestsOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.CancelSpotInstanceRequestsOutput
if rf, ok := ret.Get(0).(func(*ec2.CancelSpotInstanceRequestsInput) *ec2.CancelSpotInstanceRequestsOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.CancelSpotInstanceRequestsOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.CancelSpotInstanceRequestsInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateSecurityGroup provides a mock function with given fields: _a0
func (_m *mockClient) CreateSecurityGroup(_a0 *ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.CreateSecurityGroupOutput
if rf, ok := ret.Get(0).(func(*ec2.CreateSecurityGroupInput) *ec2.CreateSecurityGroupOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.CreateSecurityGroupOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.CreateSecurityGroupInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateTags provides a mock function with given fields: _a0
func (_m *mockClient) CreateTags(_a0 *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.CreateTagsOutput
if rf, ok := ret.Get(0).(func(*ec2.CreateTagsInput) *ec2.CreateTagsOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.CreateTagsOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.CreateTagsInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DescribeAddresses provides a mock function with given fields: _a0
func (_m *mockClient) DescribeAddresses(_a0 *ec2.DescribeAddressesInput) (*ec2.DescribeAddressesOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.DescribeAddressesOutput
if rf, ok := ret.Get(0).(func(*ec2.DescribeAddressesInput) *ec2.DescribeAddressesOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.DescribeAddressesOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.DescribeAddressesInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DescribeInstances provides a mock function with given fields: _a0
func (_m *mockClient) DescribeInstances(_a0 *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.DescribeInstancesOutput
if rf, ok := ret.Get(0).(func(*ec2.DescribeInstancesInput) *ec2.DescribeInstancesOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.DescribeInstancesOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.DescribeInstancesInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DescribeSecurityGroups provides a mock function with given fields: _a0
func (_m *mockClient) DescribeSecurityGroups(_a0 *ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.DescribeSecurityGroupsOutput
if rf, ok := ret.Get(0).(func(*ec2.DescribeSecurityGroupsInput) *ec2.DescribeSecurityGroupsOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.DescribeSecurityGroupsOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.DescribeSecurityGroupsInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DescribeSpotInstanceRequests provides a mock function with given fields: _a0
func (_m *mockClient) DescribeSpotInstanceRequests(_a0 *ec2.DescribeSpotInstanceRequestsInput) (*ec2.DescribeSpotInstanceRequestsOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.DescribeSpotInstanceRequestsOutput
if rf, ok := ret.Get(0).(func(*ec2.DescribeSpotInstanceRequestsInput) *ec2.DescribeSpotInstanceRequestsOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.DescribeSpotInstanceRequestsOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.DescribeSpotInstanceRequestsInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DescribeVolumes provides a mock function with given fields: _a0
func (_m *mockClient) DescribeVolumes(_a0 *ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.DescribeVolumesOutput
if rf, ok := ret.Get(0).(func(*ec2.DescribeVolumesInput) *ec2.DescribeVolumesOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.DescribeVolumesOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.DescribeVolumesInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DisassociateAddress provides a mock function with given fields: _a0
func (_m *mockClient) DisassociateAddress(_a0 *ec2.DisassociateAddressInput) (*ec2.DisassociateAddressOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.DisassociateAddressOutput
if rf, ok := ret.Get(0).(func(*ec2.DisassociateAddressInput) *ec2.DisassociateAddressOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.DisassociateAddressOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.DisassociateAddressInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// RequestSpotInstances provides a mock function with given fields: _a0
func (_m *mockClient) RequestSpotInstances(_a0 *ec2.RequestSpotInstancesInput) (*ec2.RequestSpotInstancesOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.RequestSpotInstancesOutput
if rf, ok := ret.Get(0).(func(*ec2.RequestSpotInstancesInput) *ec2.RequestSpotInstancesOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.RequestSpotInstancesOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.RequestSpotInstancesInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// RevokeSecurityGroupIngress provides a mock function with given fields: _a0
func (_m *mockClient) RevokeSecurityGroupIngress(_a0 *ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.RevokeSecurityGroupIngressOutput
if rf, ok := ret.Get(0).(func(*ec2.RevokeSecurityGroupIngressInput) *ec2.RevokeSecurityGroupIngressOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.RevokeSecurityGroupIngressOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.RevokeSecurityGroupIngressInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// TerminateInstances provides a mock function with given fields: _a0
func (_m *mockClient) TerminateInstances(_a0 *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error) {
ret := _m.Called(_a0)
var r0 *ec2.TerminateInstancesOutput
if rf, ok := ret.Get(0).(func(*ec2.TerminateInstancesInput) *ec2.TerminateInstancesOutput); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ec2.TerminateInstancesOutput)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ec2.TerminateInstancesInput) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
var _ client = (*mockClient)(nil)
|
/*
* @lc app=leetcode.cn id=1275 lang=golang
*
* [1275] 找出井字棋的获胜者
*/
package main
// @lc code=start
func tictactoe(moves [][]int) string {
board := make([][3]int, 3)
for i := 0; i < len(moves); i++ {
board[moves[i][0]][moves[i][1]] = i%2 + 1
}
for i := 0; i < 3; i++ {
if board[i][0] != 0 && board[i][0] == board[i][1] && board[i][1] == board[i][2]{
if board[i][0] == 1{
return "A"
}else {
return "B"
}
}
if board[0][i] != 0 && board[0][i] == board[1][i] && board[1][i] == board[2][i]{
if board[0][i] == 1{
return "A"
}else {
return "B"
}
}
}
if board[0][0] != 0 && board[0][0] == board[1][1] && board[1][1] == board[2][2]{
if board[1][1] == 1{
return "A"
}else {
return "B"
}
}
if board[0][2] != 0 && board[0][2] == board[1][1] && board[1][1] == board[2][0]{
if board[1][1] == 1{
return "A"
}else {
return "B"
}
}
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if board[i][j] == 0{
return "Pending"
}
}
}
return "Draw"
}
// @lc code=end
|
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
_ "github.com/mattn/go-sqlite3"
)
type Tx struct {
FromAddress string `json:"fromAddress"`
TxHash string `json:"txHash"`
}
func main() {
if _, err := os.Stat("txdb.db"); os.IsNotExist(err) {
file, err := os.Create("txdb.db")
if err != nil {
log.Fatal(err.Error())
}
file.Close()
}
http.HandleFunc("/savetx", Handler)
log.Fatal(http.ListenAndServe(":5050", nil))
}
func Handler(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
db, _ := sql.Open("sqlite3", "txdb.db")
defer db.Close()
createTable(db)
var tx Tx
err := json.NewDecoder(r.Body).Decode(&tx)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
insertTransaction(db, tx)
fmt.Fprint(w, true)
}
func createTable(db *sql.DB) {
sql := "CREATE TABLE IF NOT EXISTS txStore (id integer NOT NULL PRIMARY KEY AUTOINCREMENT, txHash TEXT, fromAddress TEXT)"
statement, _ := db.Prepare(sql)
statement.Exec()
}
func insertTransaction(db *sql.DB, tx Tx) {
sql := "INSERT INTO txStore(txHash, fromAddress) VALUES (?, ?)"
statement, _ := db.Prepare(sql)
statement.Exec(tx.TxHash, tx.FromAddress)
}
|
package api
import (
"fmt"
"os"
"github.com/arxdsilva/olist/storage"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
type Server struct {
Storage storage.Storage
Port string
}
func New() *Server {
return &Server{Port: port()}
}
func (s *Server) Listen() {
e := echo.New()
e.Use(middleware.Logger())
e.POST("/records", s.SaveRecord)
e.GET("/bills/:subscriber", s.Bill)
e.GET("/", s.HealthCheck)
e.Logger.Fatal(e.Start(s.Port))
}
func port() (p string) {
if p = os.Getenv("PORT"); p != "" {
return fmt.Sprintf(":%s", p)
}
return ":8080"
}
// Healthcheck is a simple handler that provides the API live status
// Response:
// 200 OK
func (s *Server) HealthCheck(c echo.Context) (err error) {
return c.HTML(200, "OK")
}
|
package profiling
import (
"fmt"
httpProf "net/http/pprof"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/spf13/pflag"
)
// Profiler helps setup and manage profiling
type Profiler struct {
// Dir, if set, is the path where profiling data will be written to.
//
// Can also be configured with "-profile-output-dir" flag.
Dir string
// ProfileCPU, if true, indicates that the profiler should profile the CPU.
//
// Requires Dir to be set, since it's where the profiler output is dumped.
//
// Can also be set with "-profile-cpu".
ProfileCPU bool
// ProfileHeap, if true, indicates that the profiler should profile heap
// allocations.
//
// Requires Dir to be set, since it's where the profiler output is dumped.
//
// Can also be set with "-profile-heap".
ProfileHeap bool
// profilingCPU is true if 'Start' successfully launched CPU profiling.
profilingCPU bool
mu sync.Mutex
counter uint64
}
// AddFlags adds command line flags to common Profiler fields.
func (p *Profiler) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&p.Dir, "profile-output-dir", "",
"If specified, allow generation of profiling artifacts, which will be written here.")
fs.BoolVar(&p.ProfileCPU, "profile-cpu", false, "If specified, enables CPU profiling.")
fs.BoolVar(&p.ProfileHeap, "profile-heap", false, "If specified, enables heap profiling.")
}
// Start starts the Profiler's configured operations. On success, returns a
// function that can be called to shutdown the profiling server.
//
// Calling Stop is not necessary, but will enable end-of-operation profiling
// to be gathered.
func (p *Profiler) Start() error {
if p.Dir == "" {
if p.ProfileCPU {
return errors.New("-profile-cpu requires -profile-output-dir to be set")
}
if p.ProfileHeap {
return errors.New("-profile-heap requires -profile-output-dir to be set")
}
}
if p.ProfileCPU {
out, err := os.Create(p.generateOutPath("cpu"))
if err != nil {
return errors.Wrap(err, "failed to create CPU profile output file")
}
if err := pprof.StartCPUProfile(out); err != nil {
return errors.Wrap(err, "start CPU profile")
}
p.profilingCPU = true
}
return nil
}
// AddHTTP adds HTTP proiling endpoints to the provided Router.
func (p *Profiler) AddHTTP(r *mux.Router) {
// Register paths: https://golang.org/src/net/http/pprof/pprof.go
r.HandleFunc("/debug/pprof", httpProf.Index).Methods("GET")
r.HandleFunc("/debug/pprof/", httpProf.Index).Methods("GET")
r.HandleFunc("/debug/pprof/cmdline", httpProf.Cmdline).Methods("GET")
r.HandleFunc("/debug/pprof/profile", httpProf.Profile).Methods("GET")
r.HandleFunc("/debug/pprof/symbol", httpProf.Symbol).Methods("GET")
r.HandleFunc("/debug/pprof/trace", httpProf.Trace).Methods("GET")
for _, p := range pprof.Profiles() {
name := p.Name()
r.Handle(fmt.Sprintf("/debug/%s", name), httpProf.Handler(name)).Methods("GET")
}
}
// Stop stops the Profiler's operations.
func (p *Profiler) Stop() {
if p.profilingCPU {
pprof.StopCPUProfile()
p.profilingCPU = false
}
// Take one final snapshot.
_ = p.DumpSnapshot()
}
// DumpSnapshot dumps a profile snapshot to the configured output directory. If
// no output directory is configured, nothing will happen.
func (p *Profiler) DumpSnapshot() error {
if p.Dir == "" {
return nil
}
if p.ProfileHeap {
if err := p.dumpHeapProfile(); err != nil {
return errors.Wrap(err, "failed to dump heap profile")
}
}
return nil
}
func (p *Profiler) dumpHeapProfile() (err error) {
fd, err := os.Create(p.generateOutPath("memory"))
if err != nil {
return errors.Wrap(err, "failed to create output file")
}
defer func() {
// If we could not close this file, propagate that error to the user.
if cerr := fd.Close(); cerr != nil && err == nil {
err = cerr
}
}()
// Get up-to-date statistics.
runtime.GC()
if err := pprof.WriteHeapProfile(fd); err != nil {
return errors.Wrap(err, "failed to write heap profile")
}
return nil
}
func (p *Profiler) generateOutPath(base string) string {
now := time.Now()
counter := p.uniqueCounter()
return filepath.Join(p.Dir, fmt.Sprintf("%s_%d_%d.prof", base, now.Unix(), counter))
}
func (p *Profiler) uniqueCounter() (v uint64) {
p.mu.Lock()
defer p.mu.Unlock()
v, p.counter = p.counter, p.counter+1
return
}
|
package common
import (
_"time"
_"fmt"
"encoding/json"
_"sysmonitor/profile"
)
func JsonMarshal(Network interface{}) string {
b, err := json.Marshal(Network)
if err != nil {
return ""
} else {
return string(b)
}
}
/*
func GetLocalTime() string {
local, err := time.LoadLocation("Local")
if err != nil {
fmt.Println("error")
}
TimeZone := time.Now().In(local)
fmt.Println(TimeZone)
return TimeZone
}
*/
|
//import "github.com/solomonooo/mercury"
//author : solomonooo
//create time : 2016-09-08
package mercury
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
const (
CONFIG_FILE = "mercury.conf"
DEFAULT_LISTEN_IP = "0.0.0.0"
DEFAULT_LISTEN_PORT = 7531
DEFAULT_RECV_BUFF_SIZE = 32 * 1024
DEFAULT_RECV_TIMEOUT = 1000
DEFAULT_SEND_TIMEOUT = 1000
DEFAULT_STDERR_2_FILE = false
)
type MercuryConfig struct {
Ip string
Port uint32
LogDir string
LogLevel string
RecvBuffSize uint32
RecvTimeout uint32
SendTimeout uint32
StdErr2File bool
StatusCycle uint32
reserved map[string]string
}
func NewConfig() *MercuryConfig {
return &MercuryConfig{
Ip: DEFAULT_LISTEN_IP,
Port: DEFAULT_LISTEN_PORT,
LogDir: DEFAULT_LOG_DIR,
LogLevel: DEFAULT_LOG_LEVEL,
RecvBuffSize: DEFAULT_RECV_BUFF_SIZE,
RecvTimeout: DEFAULT_RECV_TIMEOUT,
SendTimeout: DEFAULT_SEND_TIMEOUT,
StatusCycle: DEFAULT_STATUS_CYCLE,
StdErr2File: DEFAULT_STDERR_2_FILE,
}
}
func (config *MercuryConfig) Init(configPath string) error {
err := config.ParseConfig(configPath)
if err != nil {
return err
}
//load server config
if config.Find("server", "ip") {
config.Ip, _ = config.Get("server", "ip")
}
if config.Find("server", "port") {
config.Port, _ = config.GetUInt32("server", "port")
}
if config.Find("server", "log_dir") {
config.LogDir, _ = config.Get("server", "log_dir")
}
if config.Find("server", "log_level") {
config.LogLevel, _ = config.Get("server", "log_level")
}
if config.Find("server", "buffer_size") {
config.RecvBuffSize, _ = config.GetUInt32("server", "buffer_size")
}
if config.Find("server", "recv_timeout") {
config.RecvTimeout, _ = config.GetUInt32("server", "recv_timeout")
}
if config.Find("server", "send_timeout") {
config.SendTimeout, _ = config.GetUInt32("server", "send_timeout")
}
if config.Find("server", "status_cycle") {
config.StatusCycle, _ = config.GetUInt32("server", "status_cycle")
}
if config.Find("server", "stderr2file") {
config.StdErr2File, _ = config.GetBool("server", "stderr2file")
}
return nil
}
func (config *MercuryConfig) ParseConfig(configPath string) error {
handler, err := os.Open(configPath)
if err != nil {
Fatal("open mercury.conf failed, conf=%s", configPath)
return err
}
defer handler.Close()
config.reserved = make(map[string]string)
buf := bufio.NewReader(handler)
section := ""
line := ""
for err != io.EOF {
line, err = buf.ReadString('\n')
if err != nil && err != io.EOF {
Fatal("read conf from mercury.conf failed, err=%s", err.Error())
return err
}
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
section = line[1 : len(line)-1]
} else {
idx := strings.Index(line, "=")
if idx == -1 {
config.reserved[section+"."+line] = ""
} else {
config.reserved[section+"."+strings.TrimSpace(line[0:idx])] = strings.TrimSpace(line[idx+1:])
}
}
}
return nil
}
func (config MercuryConfig) Find(section string, name string) bool {
if config.reserved == nil {
return false
}
realname := section + "." + name
_, ok := config.reserved[realname]
return ok
}
func (config MercuryConfig) Get(section string, name string) (string, error) {
if config.reserved == nil {
return "", fmt.Errorf("%s.%s not exist", section, name)
}
realname := section + "." + name
value, ok := config.reserved[realname]
if false == ok {
return "", fmt.Errorf("%s.%s not exist", section, name)
}
return value, nil
}
func (config MercuryConfig) GetInt64(section string, name string) (int64, error) {
str, err := config.Get(section, name)
if err != nil {
return 0, err
}
return strconv.ParseInt(str, 10, 64)
}
func (config MercuryConfig) GetUInt64(section string, name string) (uint64, error) {
str, err := config.Get(section, name)
if err != nil {
return 0, err
}
return strconv.ParseUint(str, 10, 64)
}
func (config MercuryConfig) GetUInt32(section string, name string) (uint32, error) {
v, err := config.GetUInt64(section, name)
return uint32(v), err
}
func (config MercuryConfig) GetInt32(section string, name string) (int32, error) {
v, err := config.GetInt64(section, name)
return int32(v), err
}
func (config MercuryConfig) GetInt(section string, name string) (int, error) {
v, err := config.GetInt64(section, name)
return int(v), err
}
func (config MercuryConfig) GetBool(section string, name string) (bool, error) {
str, err := config.Get(section, name)
if err != nil {
return false, err
}
return strconv.ParseBool(str)
}
//////////////////////
func SetConfig(configPath string) error {
err := mercury.config.Init(configPath)
if err != nil {
panic(err)
}
return err
}
func GetConfig(section string, name string) (string, error) {
return mercury.config.Get(section, name)
}
func GetConfigInt32(section string, name string) (int32, error) {
return mercury.config.GetInt32(section, name)
}
func GetConfigUInt32(section string, name string) (uint32, error) {
return mercury.config.GetUInt32(section, name)
}
func GetConfigInt(section string, name string) (int, error) {
return mercury.config.GetInt(section, name)
}
func GetConfigBool(section string, name string) (bool, error) {
return mercury.config.GetBool(section, name)
}
|
package ierr
const (
Success = 0
// 请求相关
BindDataError = 10001
InvalidEmailOrPassword = 10002
InvalidRequestPhone = 10003
InvalidRequestParams = 10004
UnexpectedError = 10010
// 用户
InvalidUserId = 20001
InvalidToken = 20002
InvalidPassword = 20003
InvalidUsername = 20004
InvalidRoleId = 20005
InvalidRoleName = 20006
InvalidUsernameOrPassword = 20007
CannotDeleteYourself = 20008
InvalidOpenId = 20009
// 数据库错误
CreateDataFail = 30001
UpdateDataFail = 30002
QueryDataFail = 30003
DeleteDataFail = 30004
CountFail = 30005
PipeDataError = 30006
NothingToUpdate = 30009
UnexpectDBError = 30010
// 游戏相关
InvalidGameCode = 40001
GameTimesLimit = 40002
InvalidPrizeName = 40003
// 微信相关
WxOauthFail = 50001
WxConfigError = 50002
)
var ErrorMessage = map[int]string{
Success: "Success",
BindDataError: "解析body数据错误",
InvalidEmailOrPassword: "无效的邮箱或者密码",
InvalidRequestPhone: "无效的电话号码",
InvalidRequestParams: "无效的请求参数",
UnexpectedError: "未知的错误",
// 用户
InvalidUserId: "无效的用户id",
InvalidToken: "无效的token",
InvalidPassword: "无效的密码",
InvalidUsername: "无效的用户名",
InvalidRoleId: "无效的角色id",
InvalidRoleName: "无效的角色名称",
InvalidUsernameOrPassword: "无效的用户名或密码",
CannotDeleteYourself: "不能删除自己",
InvalidOpenId: "无效的OpenId",
CreateDataFail: "创建数据失败",
UpdateDataFail: "更新数据失败",
QueryDataFail: "查询数据失败",
DeleteDataFail: "删除数据失败",
CountFail: "统计数据失败",
PipeDataError: "管道查询失败",
NothingToUpdate: "没有数据需要更新",
UnexpectDBError: "未知的数据库错误",
InvalidGameCode: "无效的游戏中奖码",
GameTimesLimit: "游戏次数限制",
InvalidPrizeName: "无效的奖品名字",
WxOauthFail: "微信授权失败",
WxConfigError: "微信配置错误",
}
|
package jws
type ClaimSet struct {
Iss string `json:"iss"`
Sub string `json:"sub,omitempty"`
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package main
import (
"errors"
"fmt"
"github.com/kr/pretty"
"github.com/luci/luci-go/client/swarming"
"github.com/maruel/subcommands"
)
var cmdRequestShow = &subcommands.Command{
UsageLine: "request-show <task_id>",
ShortDesc: "returns properties of a request",
LongDesc: "Returns the properties, what, when, by who, about a request on the Swarming server.",
CommandRun: func() subcommands.CommandRun {
r := &requestShowRun{}
r.Init()
return r
},
}
type requestShowRun struct {
commonFlags
}
func (r *requestShowRun) Parse(a subcommands.Application, args []string) error {
if err := r.commonFlags.Parse(a); err != nil {
return err
}
if len(args) != 1 {
return errors.New("must only provide a task id.")
}
return nil
}
func (c *requestShowRun) main(a subcommands.Application, taskid string) error {
s, err := swarming.New(c.serverURL)
if err != nil {
return err
}
r, err := s.FetchRequest(swarming.TaskID(taskid))
if err != nil {
return fmt.Errorf("failed to load task %s: %s", taskid, err)
}
_, _ = pretty.Println(r)
return err
}
func (c *requestShowRun) Run(a subcommands.Application, args []string) int {
if err := c.Parse(a, args); err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
cl, err := c.defaultFlags.StartTracing()
if err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
defer cl.Close()
if err := c.main(a, args[0]); err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
return 0
}
|
package popcount
// pc[i] is the population count of i (number of set bits)
var pc [256]byte
func init() {
for i := range pc {
// i = (i / 2) * 2 + i % 2
// to double a binary number shift left (last bit is 0)
// so the popcount of i is popcount of i / 2 plus 1 if i % 2 == 1
pc[i] = pc[i/2] + byte(i&1)
// fmt.Printf("pc[%d] is %d\n", i, pc[i])
}
}
// Popcount returns the population count of x
func PopCount(x uint64) int {
return int(pc[byte(x>>(0*8))] +
pc[byte(x>>(1*8))] +
pc[byte(x>>(2*8))] +
pc[byte(x>>(3*8))] +
pc[byte(x>>(4*8))] +
pc[byte(x>>(5*8))] +
pc[byte(x>>(6*8))] +
pc[byte(x>>(7*8))])
}
|
package main
const (
MessageCardSelected = "MessageCardSelected"
MessageCardDeselected = "MessageCardDeselected"
MessageCardResizeCompleted = "MessageCardResizeCompleted"
MessageCardResizeStart = "MessageCardResizeStart"
MessageCardDeleted = "MessageCardDeleted"
MessageCardRestored = "MessageCardRestored"
MessageCardMoveStack = "MessageCardMoveStack"
MessageContentSwitched = "MessageContentSwitched"
MessageThemeChange = "MessageThemeChange"
MessageUndoRedo = "MessageUndoRedo"
MessageVolumeChange = "MessageVolumeChange"
MessageStacksUpdated = "MessageStacksUpdated"
MessageCollisionGridResized = "MessageCollisionGridResized"
MessageLinkCreated = "MessageLinkCreated"
MessageLinkDeleted = "MessageLinkDeleted"
MessagePageChanged = "MessagePageChanged"
MessageRenderTextureRefresh = "MessageRenderTextureRefresh"
MessageProjectLoadingAllCardsCreated = "MessageProjectLoadingAllCardsCreated"
MessageProjectLoaded = "MessageProjectLoaded"
// MessageCardDeserialized = "MessageCardDeserialized"
)
type Message struct {
Type string
ID interface{}
Data interface{}
}
func NewMessage(messageType string, id interface{}, data interface{}) *Message {
return &Message{
Type: messageType,
ID: id,
Data: data,
}
}
// Dispatcher simply calls functions when any project (not just the current one) changes; this is used to do things only when necessary, rather than constantly.
type Dispatcher struct {
Functions []func()
}
func NewDispatcher() *Dispatcher {
return &Dispatcher{
Functions: []func(){},
}
}
func (md *Dispatcher) Run() {
for _, f := range md.Functions {
f()
}
}
func (md *Dispatcher) Register(function func()) {
md.Functions = append(md.Functions, function)
}
|
package main
import "fmt"
func main() {
ids := []int{12, 26, 35, 4, 54, 6, 73}
fmt.Println(ids)
// range
for i, id := range ids {
fmt.Printf("%d - ID: %d\n", i, id)
}
// not using index
for _, id := range ids {
fmt.Printf("ID: %d\n", id)
}
// add ids together
sum := 0
for _, id := range ids {
sum += id
}
fmt.Println("Sum:", sum)
// range with map
emails := map[string]string{"Bob": "bob@gmail.com", "Truong": "Truong@gmail.com"}
emails["Mike"] = "mike@gmail.com"
for k, v := range emails {
fmt.Printf("%s: %s\n", k, v)
}
for k := range emails {
fmt.Println("Name:", k)
}
}
|
package controller
import (
"Seaman/config"
"Seaman/model"
"Seaman/service"
"Seaman/utils"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/sessions"
"strconv"
"time"
)
/**
* 项目控制器结构体:用来实现处理项目模块的接口的请求,并返回给客户端
*/
type ProjectController struct {
//上下文对象
Ctx iris.Context
//project service
ProjectService service.ProjectService
//session对象
Session *sessions.Session
}
func (uc *ProjectController) BeforeActivation(a mvc.BeforeActivation) {
//添加项目
a.Handle("POST", "/", "PostAddProject")
//删除项目
a.Handle("DELETE", "/{id}", "DeleteProject")
//查询项目
a.Handle("GET", "single/{id}", "GetProject")
//查询项目数量
a.Handle("GET", "/count", "GetCount")
//所有项目列表
a.Handle("GET", "/list", "GetList")
//带参数查询项目分页
a.Handle("GET", "/pageList", "GetPageList")
//修改项目
a.Handle("PUT", "/", "UpdateProject")
}
/**
* url: /project/addproject
* type:post
* descs:添加项目
*/
func (uc *ProjectController) PostAddProject() mvc.Result {
var project model.SmProjectT
err := uc.Ctx.ReadJSON(&project)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_PARAM,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_PARAM),
},
}
}
initConfig := config.InitConfig()
currentUserId, sessionErr := uc.Session.GetInt64(initConfig.Session.CurrentUserId)
//解析失败
if sessionErr != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_UNLOGIN,
"type": utils.EEROR_UNLOGIN,
"message": utils.Recode2Text(utils.EEROR_UNLOGIN),
},
}
}
newProject := &model.SmProjectT{
ProjectCode: project.ProjectCode,
ProjectName: project.ProjectName,
ProjectDesc: project.ProjectDesc,
Status: project.Status,
TenantId: project.TenantId,
AppName: project.AppName,
AppScope: project.AppScope,
CreateDate: time.Now(),
LastUpdateDate: time.Now(),
CreateUserId: strconv.Itoa(int(currentUserId)),
LastUpdateUserId: strconv.Itoa(int(currentUserId)),
Revision: 1,
}
isSuccess := uc.ProjectService.AddProject(newProject)
if !isSuccess {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_ADD,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_ADD),
},
}
}
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_OK,
"success": utils.Recode2Text(utils.RESPMSG_SUCCESS_ADD),
},
}
}
/**
* 删除项目
*/
func (uc *ProjectController) DeleteProject() mvc.Result {
id := uc.Ctx.Params().Get("id")
projectId, err := strconv.Atoi(id)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_PARAM,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_PARAM),
},
}
}
delete := uc.ProjectService.DeleteProject(projectId)
if !delete {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_DELETE,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_DELETE),
},
}
} else {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_OK,
"type": utils.RESPMSG_SUCCESS_DELETE,
"message": utils.Recode2Text(utils.RESPMSG_SUCCESS_DELETE),
},
}
}
}
/**
* 获取项目
* 请求类型:Get
*/
func (uc *ProjectController) GetProject() mvc.Result {
id := uc.Ctx.Params().Get("id")
projectId, err := strconv.Atoi(id)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_PARAM,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_PARAM),
},
}
}
project, err := uc.ProjectService.GetProject(projectId)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_QUERY,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_QUERY),
},
}
}
//返回项目
return mvc.Response{
Object: project.ProjectTToRespDesc(),
}
}
/**
* 获取项目数量
* 请求类型:Get
*/
func (uc *ProjectController) GetCount() mvc.Result {
//获取页面参数
name := uc.Ctx.FormValue("name")
projectParam := &model.SmProjectT{
ProjectName: name,
}
//项目总数
total, err := uc.ProjectService.GetProjectTotalCount(projectParam)
//请求出现错误
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"count": 0,
},
}
}
//正常情况的返回值
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_OK,
"count": total,
},
}
}
/**
* 获取项目列表
* 请求类型:Get
*/
func (uc *ProjectController) GetList() mvc.Result {
var project model.SmProjectT
err := uc.Ctx.ReadJSON(&project)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_UPDATE,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_UPDATE),
},
}
}
newProject := &model.SmProjectT{
Id: project.Id,
ProjectName: project.ProjectName,
ProjectCode: project.ProjectCode,
ProjectDesc: project.ProjectDesc,
LastUpdateDate: time.Now(),
}
projectList := uc.ProjectService.GetProjectList(newProject)
if len(projectList) == 0 {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_QUERY,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_QUERY),
},
}
}
//将查询到的项目数据进行转换成前端需要的内容
var respList []interface{}
for _, project := range projectList {
respList = append(respList, project.ProjectTToRespDesc())
}
//返回项目列表
return mvc.Response{
Object: &respList,
}
}
/**
* 获取项目带参数分页查询
* 请求类型:Get
*/
func (uc *ProjectController) GetPageList() mvc.Result {
offsetStr := uc.Ctx.FormValue("current")
limitStr := uc.Ctx.FormValue("pageSize")
var offset int
var limit int
//判断offset和limit两个变量任意一个都不能为""
if offsetStr == "" || limitStr == "" {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_PARAM,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_PARAM),
},
}
}
offset, err := strconv.Atoi(offsetStr)
limit, err = strconv.Atoi(limitStr)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_PARAM,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_PARAM),
},
}
}
//做页数的限制检查
if offset <= 0 {
offset = 0
} else {
offset--
}
//做最大的限制
if limit > MaxLimit {
limit = MaxLimit
}
//获取页面参数
projectName := uc.Ctx.FormValue("projectName")
projectCode := uc.Ctx.FormValue("projectCode")
status := uc.Ctx.FormValue("status")
projectParam := &model.SmProjectT{
ProjectName: projectName,
ProjectCode: projectCode,
Status: status,
}
projectList := uc.ProjectService.GetProjectPageList(projectParam, offset, limit)
total, _ := uc.ProjectService.GetProjectTotalCount(projectParam)
if len(projectList) == 0 {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_QUERY,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_QUERY),
},
}
}
//将查询到的项目数据进行转换成前端需要的内容
var respList []interface{}
for _, project := range projectList {
respList = append(respList, project.ProjectTToRespDesc())
}
//返回项目列表
return mvc.Response{
Object: map[string]interface{}{
"data": respList,
"total": total,
"success": true,
"pageSize": limit,
"current": offset,
},
}
}
/**
* type:put
* descs:修改项目
*/
func (uc *ProjectController) UpdateProject() mvc.Result {
var project model.SmProjectT
err := uc.Ctx.ReadJSON(&project)
if err != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_ADD,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_ADD),
},
}
}
initConfig := config.InitConfig()
currentUserId, sessionErr := uc.Session.GetInt64(initConfig.Session.CurrentUserId)
//解析失败
if sessionErr != nil {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_UNLOGIN,
"type": utils.EEROR_UNLOGIN,
"message": utils.Recode2Text(utils.EEROR_UNLOGIN),
},
}
}
newProject := &model.SmProjectT{
Id: project.Id,
ProjectName: project.ProjectName,
ProjectCode: project.ProjectCode,
ProjectDesc: project.ProjectDesc,
Status: project.Status,
LastUpdateDate: time.Now(),
LastUpdateUserId: strconv.Itoa(int(currentUserId)),
}
isSuccess := uc.ProjectService.UpdateProject(newProject)
if !isSuccess {
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_FAIL,
"type": utils.RESPMSG_ERROR_ADD,
"message": utils.Recode2Text(utils.RESPMSG_ERROR_UPDATE),
},
}
}
return mvc.Response{
Object: map[string]interface{}{
"status": utils.RECODE_OK,
"success": utils.Recode2Text(utils.RESPMSG_SUCCESS_UPDATE),
},
}
}
|
package assembler
import (
"math/rand"
"testing"
"time"
)
func init(){
rand.Seed(time.Now().Unix())
}
func TestSaxpy(t *testing.T) {
for j := 0; j < 100; j++ {
X := make([]float32, j)
Y := make([]float32, j)
Y1 := make([]float32, j)
for i := range X {
X[i] = rand.Float32()*0.2 - 0.1
Y[i] = rand.Float32()*0.2 - 0.1
}
for i, y := range Y {
Y1[i] = y
}
r := rand.Float32()*0.2 - 0.1
saxpy(r, X, Y)
//fmt.Println(Y1)
Saxpy(r, X, Y1)
//fmt.Println(Y1)
for i := range Y {
if Y[i] != Y1[i] {
t.Fatalf("sums do not match want %f got %f in vector of length %d\n", Y[i], Y1[i], len(Y))
}
}
}
}
func TestSaxplusbysetz(t *testing.T) {
x := make([]float32, 10000)
y := make([]float32, 10000)
z1 := make([]float32, 10000)
z2 := make([]float32, 10000)
a := rand.Float32()
b := rand.Float32()
for i := range x {
x[i] = rand.Float32()
y[i] = rand.Float32()
}
for i := 1; i < 10000; i++ {
saxplusbysetz(a, x[:i], b, y[:i], z1[:i])
Saxplusbysetz(a, x[:i], b, y[:i], z2[:i])
for j := 0; j < i; j++ {
if z1[j] != z2[j] {
t.Fatalf("Experiment %d values do not match want %f got %f in vector of length %d\n", i, z1[j], z2[j], len(z2[:i]))
}
}
}
}
func TestSaxplusbyplusz(t *testing.T) {
x := make([]float32, 10000)
y := make([]float32, 10000)
z1 := make([]float32, 10000)
z2 := make([]float32, 10000)
a := rand.Float32()
b := rand.Float32()
for i := range x {
x[i] = rand.Float32()
y[i] = rand.Float32()
}
for i := 1; i < 10000; i++ {
saxplusbyplusz(a, x[:i], b, y[:i], z1[:i])
Saxplusbyplusz(a, x[:i], b, y[:i], z2[:i])
for j := 0; j < i; j++ {
if z1[j] != z2[j] {
t.Fatalf("Experiment %d values do not match want %f got %f in vector of length %d\n", i, z1[j], z2[j], len(z2[:i]))
}
}
}
}
func TestSaxplusbyvsetz(t *testing.T) {
x := make([]float32, 10000)
y := make([]float32, 10000)
v := make([]float32, 10000)
z1 := make([]float32, 10000)
z2 := make([]float32, 10000)
a := rand.Float32()
b := rand.Float32()
for i := range x {
x[i] = rand.Float32()
y[i] = rand.Float32()
v[i] = rand.Float32()
}
for i := 1; i < 10000; i++ {
saxplusbyvsetz(a, x[:i], b, y[:i], v[:i], z1[:i])
Saxplusbyvsetz(a, x[:i], b, y[:i], v[:i], z2[:i])
for j := 0; j < i; j++ {
if z1[j] != z2[j] {
t.Fatalf("Experiment %d values do not match want %f got %f in vector of length %d\n",
i, z1[j], z2[j], len(z2[:i]))
}
}
}
}
func TestSaxdivsqrteyplusz(t *testing.T) {
x := make([]float32, 10000)
y := make([]float32, 10000)
a := rand.Float32()
b := rand.Float32() + 1e-1
for i := range x {
x[i] = rand.Float32()
y[i] = Abs(rand.Float32())
}
for i := 1; i < 10000; i++ {
z1 := make([]float32, i)
z2 := make([]float32, i)
for i := range z1 {
z1[i] = rand.Float32()
z2[i] = z1[i]
}
saxdivsqrteyplusz(a, x[:i], b, y[:i], z1[:i])
Saxdivsqrteyplusz(a, x[:i], b, y[:i], z2[:i])
for j := 0; j < i; j++ {
if z1[j] != z2[j] {
t.Fatalf("Experiment %d values do not match want %f got %f in vector of length %d\n",
i, z1[j], z2[j], len(z2[:i]))
}
}
}
}
func TestSigmoidbackprop(t *testing.T) {
x := make([]float32, 10000)
y := make([]float32, 10000)
for i := range x {
x[i] = rand.Float32()
y[i] = Abs(rand.Float32())
}
for i := 1; i < 10000; i++ {
z1 := make([]float32, i)
z2 := make([]float32, i)
for i := range z1 {
z1[i] = rand.Float32()
z2[i] = z1[i]
}
sigmoidbackprop(1, x[:i], y[:i], z1[:i])
Sigmoidbackprop(1, x[:i], y[:i], z2[:i])
for j := 0; j < i; j++ {
if z1[j] != z2[j] {
t.Fatalf("Experiment %d values do not match want %f got %f in vector of length %d\n",
i, z1[j], z2[j], len(z2[:i]))
}
}
}
}
|
package main
import (
"fmt"
goredislib "github.com/go-redis/redis/v8"
"github.com/go-redsync/redsync/v4"
"github.com/go-redsync/redsync/v4/redis/goredis/v8"
"time"
)
func main() {
// Create a pool with go-redis (or redigo) which is the pool redisync will
// use while communicating with Redis. This can also be any pool that
// implements the `redis.Pool` interface.
client := goredislib.NewClient(&goredislib.Options{
Addr: "192.168.1.234:6379",
})
pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)
// Create an instance of redisync to be used to obtain a mutual exclusion
// lock.
rs := redsync.New(pool)
// Obtain a new mutex by using the same name for all instances wanting the
// same lock.
key := "hello-test-for-lock"
val := "b"
mutex := rs.NewMutex(key, redsync.WithExpiry(200*time.Second), redsync.WithGenValueFunc(func() (string, error) {
return val, nil
}))
// Obtain a lock for our given mutex. After this is successful, no one else
// can obtain the same lock (the same mutex name) until we unlock it.
if err := mutex.Lock(); err != nil {
fmt.Println(err)
}
h := 323
fmt.Print(h)
// Do your work that requires the lock.
// Release the lock so other processes or threads can obtain a lock.
if ok, err := mutex.Unlock(); !ok || err != nil {
panic("unlock failed")
}
}
|
package post
import (
"github.com/gofiber/fiber"
)
func RegisterURLs(app *fiber.App) {
router := app.Group("/posts")
router.Get("/submit", publish)
router.Get("/:id", get)
router.Post("/", post)
}
func get(c *fiber.Ctx) {
context := fiber.Map{
"id": c.Params("id"),
}
err := c.Render("post/post", context, "layout")
if err != nil {
c.Next(err)
}
}
func publish(c *fiber.Ctx) {
err := c.Render("post/publish", fiber.Map{}, "layout")
if err != nil {
c.Next(err)
}
}
func post(c *fiber.Ctx) {
}
|
package main
import "fmt"
const g_s string = "the global constant"
func main() {
fmt.Println(g_s)
const l_s = "the local constant"
fmt.Println(l_s)
}
|
package jarvisbot
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"path"
"github.com/boltdb/bolt"
"github.com/kardianos/osext"
"github.com/tucnak/telebot"
)
// jokes.go contain joke functions. Not part of jarvisbot's default funcmap
// SendLaugh returns Jon's laugh. Thx, @jhowtan
func (j *JarvisBot) SendLaugh(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingAudio)
fn, err := j.sendFileWrapper("data/laugh.ogg", "ogg")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// NeverForget returns the Barisan Socialis flag. Thx, @shawntan
func (j *JarvisBot) NeverForget(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
fn, err := j.sendFileWrapper("data/barisan.jpg", "photo")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// SendLogic returns Tuan's logical meme, based on when Ian called him
// illogical.
func (j *JarvisBot) SendLogic(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
fn, err := j.sendFileWrapper("data/logic.jpg", "photo")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// SendKid sends Tin's kid meme.
func (j *JarvisBot) SendKid(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
fn, err := j.sendFileWrapper("data/thiskid.jpg", "photo")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// Yank returns a gif of @jellykaya being yanked off-stage by @vishnup
func (j *JarvisBot) Yank(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
fn, err := j.sendFileWrapper("data/yank.gif", "gif")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// Hanar returns a picture of a Hanar. Thx, @shawntan
// Context: 'hanar, hanar, hanar' means 'yeah I get it, stop nagging'
// in Singaporean Hokkien. The picture sent is a picture of a creature in
// Mass Effect called a Hanar.
func (j *JarvisBot) Hanar(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
fn, err := j.sendFileWrapper("data/hanar.jpg", "photo")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// TellThatTo returns a picture of Kanjiklub
func (j *JarvisBot) TellThatTo(msg *message) {
j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
fn, err := j.sendFileWrapper("data/kanjiklub.jpg", "photo")
if err != nil {
j.log.Printf("error sending file: %s", err)
return
}
fn(msg)
}
// Touch allows Jarvis to be touched. Thx, @rahulg
func (j *JarvisBot) Touch(msg *message) {
messages := []string{
"Why, thank you!",
"Stop touching me!",
"Ooh, that feels *so* good.",
"\U0001f60a",
"AAAAAHHHHHHHH!!!!!\n\nOh, frightened me for a moment, there.",
"Ouch! Watch it!",
"Noice!\nhttps://www.youtube.com/watch?v=rQnYi3z56RE",
}
n := rand.Intn(len(messages))
j.SendMessage(msg.Chat, messages[n], nil)
}
// sendFileWrapper checks if the file exists and writes it before returning the response function.
func (j *JarvisBot) sendFileWrapper(assetName string, filetype string) (ResponseFunc, error) {
fileId, err := j.getCachedFileID(assetName)
if err != nil {
j.log.Printf("error retreiving cached file_id for %s", assetName)
}
if fileId != "" {
file := telebot.File{FileID: fileId}
return func(msg *message) {
if filetype == "ogg" {
audio := telebot.Audio{File: file, Mime: "audio/ogg"}
j.bot.SendAudio(msg.Chat, &audio, nil)
} else if filetype == "photo" {
photo := telebot.Photo{File: file}
j.bot.SendPhoto(msg.Chat, &photo, nil)
} else if filetype == "gif" {
doc := telebot.Document{File: file, Mime: "image/gif"}
j.bot.SendDocument(msg.Chat, &doc, nil)
}
}, nil
} else {
pwd, err := osext.ExecutableFolder()
if err != nil {
j.log.Printf("error retrieving pwd: %s", err)
}
_, filename := path.Split(assetName)
filePath := path.Join(pwd, tempDir, filename)
// Check if file exists, if it doesn't exist, create it
if _, err := os.Stat(filePath); os.IsNotExist(err) {
fileData, err := Asset(assetName)
if err != nil {
err = fmt.Errorf("error retrieving asset %s: %s", assetName, err)
return nil, err
}
err = ioutil.WriteFile(filePath, fileData, 0775)
if err != nil {
err = fmt.Errorf("error creating %s: %s", assetName, err)
return nil, err
}
}
return func(msg *message) {
file, err := telebot.NewFile(filePath)
if err != nil {
j.log.Printf("error reading %s: %s", filePath, err)
return
}
var newFileId string
if filetype == "ogg" {
audio := telebot.Audio{File: file, Mime: "audio/ogg"}
j.bot.SendAudio(msg.Chat, &audio, nil)
newFileId = audio.FileID
} else if filetype == "photo" {
photo := telebot.Photo{File: file, Thumbnail: telebot.Thumbnail{File: file}}
j.bot.SendPhoto(msg.Chat, &photo, nil)
newFileId = photo.FileID
} else if filetype == "gif" {
doc := telebot.Document{File: file, Preview: telebot.Thumbnail{File: file}, Mime: "image/gif"}
j.bot.SendDocument(msg.Chat, &doc, nil)
newFileId = doc.FileID
}
err = j.cacheFileID(assetName, newFileId)
if err != nil {
j.log.Println("error caching file_id '%s' for '%s': %s", fileId, assetName, err)
}
}, nil
}
}
func (j *JarvisBot) cacheFileID(assetName string, fileId string) error {
err := j.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(file_cache_bucket_name)
err := b.Put([]byte(assetName), []byte(fileId))
if err != nil {
return err
}
return nil
})
return err
}
func (j *JarvisBot) getCachedFileID(assetName string) (string, error) {
var fileId string
err := j.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(file_cache_bucket_name)
v := b.Get([]byte(assetName))
fileId = string(v[:])
return nil
})
if err != nil {
return "", err
}
return fileId, nil
}
// Returns pictures of keyword.
// Used for joke functions, e.g. /ducks, because I like to say that
func (j *JarvisBot) SendImage(keyword string) ResponseFunc {
return func(msg *message) {
msg.Args = []string{keyword}
j.ImageSearch(msg)
}
}
|
package propertiesRepository
import (
"github.com/button-tech/BNBTextWallet/data"
"github.com/button-tech/BNBTextWallet/services/redisService"
"time"
)
const propertiesLifetime = 24 * 30 * time.Hour
func Read(identifier string) (data.PropertiesStamp, error) {
return redisService.ReadProperties(identifier)
}
func CreateOrUpdate(identifier string, propertiesDictionary map[string]interface{}) error {
stamp := data.PropertiesStamp{
Value: propertiesDictionary,
}
return redisService.CreateOrUpdateProperties(identifier, stamp, propertiesLifetime)
}
func Delete(identifier string) error {
return redisService.DeleteProperties(identifier)
}
|
package commands
import (
"os"
"code.cloudfoundry.org/garden"
)
type Attach struct {
Process string `short:"p" long:"pid" description:"process id to connect to" required:"true"`
}
func (command *Attach) Execute(maybeHandle []string) error {
handle := handle(maybeHandle)
container, err := globalClient().Lookup(handle)
failIf(err)
process, err := container.Attach(command.Process, garden.ProcessIO{
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
})
failIf(err)
_, err = process.Wait()
failIf(err)
return nil
}
|
package main
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"log"
"github.com/jinzhu/gorm"
"fmt"
)
type Place struct {
gorm.Model
Name string
Town Town // `gorm:"ForeignKey:TownID"`
TownID int //Place belongs to Town
}
type Town struct {
gorm.Model
Name string
}
func main() {
db,err:=gorm.Open("mysql","root:password@/gorm_db?charset=utf8&parseTime=True&loc=Local")
//db,err:=gorm.Open("postgres","user=aman password=password dbname=test1 sslmode=disable")
if err!=nil{
log.Fatal(err)
}
defer db.Close()
err = db.DB().Ping()
if err != nil {
log.Fatal(err)
}else{
fmt.Println("connected")
}
db.SingularTable(true)
db.DropTableIfExists(&Place{},&Town{})
db.CreateTable(&Place{},&Town{})
place:=Place{Name:"NOIDA",Town:Town{Name:"GBN"}}
db.Create(&place)
place1:=Place{Name:"DELHI",Town:Town{Name:"shahadra"}}
db.Create(&place1)
/*town:=Town{Name:"gbn"}
db.Create(&town)
town1:=Town{Name:"shahadra"}
db.Create(&town1)*/
//var user2 User
//db.Find(&user2)
//for i, _ := range user2 {
//db.Model(&user).Related(&profile)
//}
var places []Place
db.Debug().Preload("Town").Find(&places)
//db.Debug().Model(&user).Related(&profile)
//db.Debug().Raw("SELECT place.name, town.name FROM place INNER JOIN town ON town.id = place.town_id").Scan(&places)
fmt.Println(places)
//db.Model(&)
/*var p []Student
db.Debug().Find(&p,"first_name=?","Aman") // remember Normal MySQL
for _,v:=range p{
fmt.Println(v)
}*/
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.