text
stringlengths
11
4.05M
package problem0142 import "testing" func TestSolve(t *testing.T) { t.Log(detectCycle(buildCicleList([]int{3, 2, 0, -4}, 1))) t.Log(detectCycleTwoPointer(buildCicleList([]int{3, 2, 0, -4}, 1))) } func buildCicleList(nums []int, pos int) *ListNode { if len(nums) == 0 { return nil } head := &ListNode{Val: nums[0]} cur := head for i := 1; i < len(nums); i++ { cur.Next = &ListNode{Val: nums[i]} cur = cur.Next } if pos < 0 { return head } ptr := head for pos > 0 { ptr = ptr.Next pos-- } cur.Next = ptr return head }
package main import ( "fmt" "os" ) //学生管理系统 1.数据-->结构体字段 2.功能--->方法 type student struct{ id int64 name string } //学生的管理者 type studentMgr struct{ allStudent map[int64]student } func showMenu(){ fmt.Println("welcome to sms") fmt.Println(` 1.查看学生 2.添加学生 3.修改学生 4.删除学生 5.退出 `) } //查看学生 func (s studentMgr) showStudent(){ for _,stu:=range s.allStudent{ fmt.Printf("学号:%d 姓名:%s\n",stu.id,stu.name) } } //添加学生 func (s studentMgr) addStudent(){ var ( newId int64 newName string ) fmt.Print("请输入新加学生的学号:") fmt.Scanln(&newId) fmt.Print("请输入学生的姓名:") fmt.Scanln(&newName) newStu:=student{ id:newId, name:newName, } s.allStudent[newStu.id]=newStu fmt.Println("添加成功") } //修改学生 func (s studentMgr) editStudent(){ } //删除学生 func (s studentMgr) deleteStudent(){ } var smg studentMgr func main(){ smg=studentMgr{ allStudent: make(map[int64]student), } for{ showMenu() var choice int64 fmt.Print("请输入您的选项:") fmt.Scanln(&choice) fmt.Printf("您选择的序列是:%d\n",choice) switch choice { case 1: smg.showStudent() case 2: smg.addStudent() case 3: smg.editStudent() case 4: smg.deleteStudent() case 5: os.Exit(1) default: fmt.Println("your Enter is error") } } }
package entity // APIResponse export type APIResponse struct { Success bool `json:"success"` Fail bool `json:"fail"` Data interface{} `json:"data"` } // NewAPIResponse export func NewAPIResponse(data interface{}, err error) *APIResponse { if err != nil { return &APIResponse{ Fail: true, Data: map[string]string{ "reason": err.Error(), }, } } return &APIResponse{ Success: true, Data: data, } }
package calc import "testing" func TestDotProd(t *testing.T) { exp := 3.0 vecA := Vec([]float64{1.0, 3.0, -5.0}) vecB := Vec([]float64{4.0, -2.0, -1.0}) act := vecA.DotProd(vecB) if exp != act { t.Error("Expected", exp, "got", act) } }
/* Copyright 2019 Packet Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package machine import ( "context" "errors" "fmt" "strings" "time" "github.com/google/uuid" "github.com/packethost/cluster-api-provider-packet/pkg/cloud/packet" "github.com/packethost/cluster-api-provider-packet/pkg/cloud/packet/actuators/machine/machineconfig" "github.com/packethost/cluster-api-provider-packet/pkg/cloud/packet/deployer" "github.com/packethost/cluster-api-provider-packet/pkg/cloud/packet/util" "github.com/packethost/packngo" "k8s.io/klog" clusterv1 "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" client "sigs.k8s.io/cluster-api/pkg/client/clientset_generated/clientset/typed/cluster/v1alpha1" capiutil "sigs.k8s.io/cluster-api/pkg/util" ) const ( ProviderName = "packet" retryIntervalMachineReady = 10 * time.Second timeoutMachineReady = 10 * time.Minute ) // Add RBAC rules to access cluster-api resources //+kubebuilder:rbac:groups=cluster.k8s.io,resources=machines;machines/status;machinedeployments;machinedeployments/status;machinesets;machinesets/status;machineclasses,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=cluster.k8s.io,resources=clusters;clusters/status,verbs=get;list;watch //+kubebuilder:rbac:groups="",resources=nodes;events,verbs=get;list;watch;create;update;patch;delete // Actuator is responsible for performing machine reconciliation type Actuator struct { machinesGetter client.MachinesGetter packetClient *packet.PacketClient machineConfigGetter machineconfig.Getter deployer *deployer.Deployer controlPort int } // ActuatorParams holds parameter information for Actuator type ActuatorParams struct { MachinesGetter client.MachinesGetter MachineConfigGetter machineconfig.Getter Client *packet.PacketClient Deployer *deployer.Deployer ControlPort int } // NewActuator creates a new Actuator func NewActuator(params ActuatorParams) (*Actuator, error) { return &Actuator{ machinesGetter: params.MachinesGetter, packetClient: params.Client, machineConfigGetter: params.MachineConfigGetter, deployer: params.Deployer, controlPort: params.ControlPort, }, nil } // Create creates a machine and is invoked by the Machine Controller func (a *Actuator) Create(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error { if cluster == nil { return fmt.Errorf("cannot create machine in nil cluster") } if machine == nil { return fmt.Errorf("cannot create nil machine") } var msg string klog.Infof("Create machine %s", machine.Name) machineConfig, err := util.MachineProviderFromProviderConfig(machine.Spec.ProviderSpec) if err != nil { msg = fmt.Sprintf("Unable to read providerSpec from machine config: %v", err) klog.Info(msg) return errors.New(msg) } clusterConfig, err := util.ClusterProviderFromProviderConfig(cluster.Spec.ProviderSpec) if err != nil { msg = fmt.Sprintf("Error reading cluster provider config: %v", err) klog.Info(msg) return errors.New(msg) } // generate a unique UID that will survive pivot, i.e. is not tied to the cluster itself mUID := uuid.New().String() tags := []string{ util.GenerateMachineTag(mUID), util.GenerateClusterTag(string(cluster.Name)), } // generate userdata from the template // first we need to find the correct userdata userdataTmpl, containerRuntime, err := a.machineConfigGetter.GetUserdata(machineConfig.OS, machine.Spec.Versions) if err != nil { msg = fmt.Sprintf("Unable to read userdata: %v", err) klog.Info(msg) return errors.New(msg) } var ( token = "" role = "node" caCert []byte caKey []byte ) if machine.Spec.Versions.ControlPlane != "" { klog.Infof("building master controlplane node: %s", machine.Name) role = "master" caCert = clusterConfig.CAKeyPair.Cert caKey = clusterConfig.CAKeyPair.Key if len(caCert) == 0 { msg = fmt.Sprintf("CA Certificate not yet created for cluster %s when building machine: %s", cluster.Name, machine.Name) klog.Info(msg) return errors.New(msg) } if len(caKey) == 0 { msg = fmt.Sprintf("CA Key not yet created for cluster %s when building machine: %s", cluster.Name, machine.Name) klog.Info(msg) return errors.New(msg) } tags = append(tags, util.MasterTag) } else { klog.Infof("building worker controlplane node: %s", machine.Name) token, err = a.deployer.NewBootstrapToken(cluster) if err != nil { msg = fmt.Sprintf("failed to create and save token for cluster %q: %v", cluster.Name, err) klog.Info(msg) return errors.New(msg) } tags = append(tags, util.WorkerTag) } userdata, err := parseUserdata(userdataTmpl, role, cluster, machine, machineConfig.OS, token, caCert, caKey, a.controlPort, containerRuntime) if err != nil { msg = fmt.Sprintf("Unable to generate userdata for machine %s: %v", machine.Name, err) klog.Info(msg) return errors.New(msg) } klog.Infof("Creating machine %v for cluster %v.", machine.Name, cluster.Name) serverCreateOpts := &packngo.DeviceCreateRequest{ Hostname: machine.Name, UserData: userdata, ProjectID: machineConfig.ProjectID, Facility: machineConfig.Facilities, BillingCycle: machineConfig.BillingCycle, Plan: machineConfig.InstanceType, OS: machineConfig.OS, Tags: tags, } device, _, err := a.packetClient.Devices.Create(serverCreateOpts) if err != nil { msg = fmt.Sprintf("failed to create machine %s: %v", machine.Name, err) klog.Info(msg) return errors.New(msg) } // we need to loop here until the device exists and has an IP address klog.Infof("Created device %s, waiting for it to be ready", machine.Name) a.waitForMachineReady(device) // add the annotations so that cluster-api knows it is there (also, because it is useful to have) if machine.Annotations == nil { machine.Annotations = map[string]string{} } machine.Annotations["cluster-api-provider-packet"] = "true" machine.Annotations["cluster.k8s.io/machine"] = cluster.Name machine.Annotations[util.AnnotationUID] = mUID if _, err = a.updateMachine(cluster, machine); err != nil { return fmt.Errorf("error updating Machine object with annotations: %v", err) } msg = fmt.Sprintf("machine successfully created and annotated %s", machine.Name) klog.Info(msg) return nil } // Delete deletes a machine and is invoked by the Machine Controller func (a *Actuator) Delete(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error { if cluster == nil { return fmt.Errorf("cannot delete machine in nil cluster") } if machine == nil { return fmt.Errorf("cannot delete nil machine") } klog.Infof("Deleting machine %v for cluster %v.", machine.Name, cluster.Name) device, err := a.packetClient.GetDevice(machine) if err != nil { return fmt.Errorf("error retrieving machine status %s: %v", machine.Name, err) } if device == nil { return fmt.Errorf("machine does not exist: %s", machine.Name) } _, err = a.packetClient.Devices.Delete(device.ID) if err != nil { return fmt.Errorf("failed to delete the machine: %v", err) } return nil } // Update updates a machine and is invoked by the Machine Controller func (a *Actuator) Update(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error { if cluster == nil { return fmt.Errorf("cannot update machine in nil cluster") } if machine == nil { return fmt.Errorf("cannot update nil machine") } c, err := util.ClusterProviderFromProviderConfig(cluster.Spec.ProviderSpec) if err != nil { return fmt.Errorf("unable to unpack cluster provider: %v", err) } klog.Infof("Updating machine %v for cluster %v.", machine.Name, cluster.Name) // how to update the machine: // - get the current parameters of the machine from the API // - check if anything immutable has changed, in which case we return an error // - check if anything mutable has changed, in which case we update the instance device, err := a.packetClient.GetDevice(machine) if err != nil { return fmt.Errorf("error retrieving machine status %s: %v", machine.Name, err) } if device == nil { return fmt.Errorf("received nil machine") } // check immutable if err := changedImmutable(c.ProjectID, device, machine); err != nil { return err } // check mutable update, err := changedMutable(c.ProjectID, device, machine) if err != nil { return fmt.Errorf("error checking changed mutable information: %v", err) } if update != nil { _, _, err := a.packetClient.Devices.Update(device.ID, update) if err != nil { return fmt.Errorf("failed to update device %s: %v", device.Hostname, err) } } return nil } // Exists test for the existance of a machine and is invoked by the Machine Controller func (a *Actuator) Exists(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) (bool, error) { if cluster == nil { return false, fmt.Errorf("cannot check if machine exists in nil cluster") } if machine == nil { return false, fmt.Errorf("cannot check if nil machine exists") } var msg string klog.Infof("Checking if machine %v for cluster %v exists.", machine.Name, cluster.Name) device, err := a.packetClient.GetDevice(machine) if err != nil { msg = fmt.Sprintf("error retrieving machine status %s: %v", machine.Name, err) klog.Info(msg) return false, errors.New(msg) } if device == nil { msg = fmt.Sprintf("machine not found %s", machine.Name) klog.Info(msg) return false, nil } msg = fmt.Sprintf("machine found %s: %s", machine.Name, device.ID) klog.Info(msg) return true, nil } func (a *Actuator) get(machine *clusterv1.Machine) (*packngo.Device, error) { device, err := a.packetClient.GetDevice(machine) if err != nil { return nil, err } if device != nil { return device, nil } return nil, fmt.Errorf("Device %s not found", machine.Name) } func (a *Actuator) updateMachine(cluster *clusterv1.Cluster, machine *clusterv1.Machine) (*clusterv1.Machine, error) { var ( machineClient client.MachineInterface updatedMachine *clusterv1.Machine err error ) if a.machinesGetter != nil { machineClient = a.machinesGetter.Machines(cluster.Namespace) } if updatedMachine, err = machineClient.Update(machine); err != nil { return nil, err } return updatedMachine, nil } func (a *Actuator) waitForMachineReady(device *packngo.Device) error { err := capiutil.PollImmediate(retryIntervalMachineReady, timeoutMachineReady, func() (bool, error) { klog.Infof("Waiting for device %v to become ready...", device.ID) dev, _, err := a.packetClient.Devices.Get(device.ID, nil) if err != nil { return false, nil } ready := dev.Network == nil || len(dev.Network) == 0 || dev.Network[0].Address == "" return ready, nil }) return err } func changedImmutable(projectID string, device *packngo.Device, machine *clusterv1.Machine) error { errors := []string{} machineConfig, err := util.MachineProviderFromProviderConfig(machine.Spec.ProviderSpec) if err != nil { return fmt.Errorf("Unable to read providerSpec from machine config: %v", err) } // immutable: Facility, MachineType, ProjectID, OS, BillingCycle facility := device.Facility.Code if !util.ItemInList(machineConfig.Facilities, facility) { errors = append(errors, "Facility") } if device.Plan.Name != machineConfig.InstanceType { errors = append(errors, "MachineType") } if projectID != machineConfig.ProjectID { errors = append(errors, "ProjectID") } // it could be indicated in one of several ways if device.OS.Slug != machineConfig.OS && device.OS.Name != machineConfig.OS { errors = append(errors, "OS") } if device.BillingCycle != machineConfig.BillingCycle { errors = append(errors, "BillingCycle") } if len(errors) > 0 { return fmt.Errorf("attempted to change immutable characteristics: %s", strings.Join(errors, ",")) } return nil } func changedMutable(projectID string, device *packngo.Device, machine *clusterv1.Machine) (*packngo.DeviceUpdateRequest, error) { update := packngo.DeviceUpdateRequest{} updated := false // mutable: Hostname (machine.Name), Roles, SshKeys if device.Hostname != machine.Name { // copy it to get a clean pointer newName := machine.Name update.Hostname = &newName updated = true } if updated { return &update, nil } // Roles and SshKeys affect the userdata, which we would update // TODO: Update userdata based on Roles and SshKeys return nil, nil }
/* You are playing a Billiards-like game on an N×N table, which has its four corners at the points {(0,0),(0,N),(N,0), and (N,N)}. You start from a coordinate (x,y), (0<x<N,0<y<N) and shoot the ball at an angle 45∘ with the horizontal. On hitting the sides, the ball continues to move with the same velocity and ensuring that the angle of incidence is equal to the angle of reflection with the normal, i.e, it is reflected with zero frictional loss. On hitting either of the four corners, the ball stops there and doesn’t move any further. Find the coordinates of the point of collision, when the ball hits the sides for the Kth time. If the ball stops before hitting the sides K times, find the coordinates of the corner point where the ball stopped instead. Input: The first line of the input contains an integer T, the number of testcases. Each testcase contains a single line of input, which has four space separated integers - N, K, x, y, denoting the size of the board, the number of collisions to report the answer for, and the starting coordinates. Output: For each testcase, print the coordinates of the ball when it hits the sides for the Kth time, or the coordinates of the corner point if it stopped earlier. Constraints 1≤T≤10^5 2≤N≤10^9 1≤K≤10^9 */ package main func main() { assert(collision(5, 5, 4, 4) == [2]int{5, 5}) assert(collision(5, 2, 3, 1) == [2]int{3, 5}) } func assert(x bool) { if !x { panic("assertion failed") } } func collision(n, k, x, y int) [2]int { if x == y { return [2]int{n, n} } p := [][2]int{ {n, y + n - x}, {y + n - x, n}, {0, x - y}, {x - y, 0}, } if x < y { x, y = y, x p = [][2]int{ {y + n - x, n}, {n, y + n - x}, {x - y, 0}, {0, x - y}, } } i := mod(k-1, 4) return p[i] } func mod(x, m int) int { x %= m if x < 0 { x += m } return x }
// Copyright 2018 Andrew Bates // // 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 insteon import ( "reflect" "testing" "time" ) func newTestNetwork(bufSize int) (*Network, chan *PacketRequest, chan []byte) { sendCh := make(chan *PacketRequest, bufSize) recvCh := make(chan []byte, bufSize) return New(sendCh, recvCh, time.Millisecond), sendCh, recvCh } /*func TestNetworkProcess(t *testing.T) { connection := make(chan *Message, 1) network, _, recvCh := newTestNetwork(0) network.connectCh <- connection buf, _ := TestMessagePingAck.MarshalBinary() recvCh <- buf select { case <-connection: case <-time.After(time.Millisecond): t.Errorf("Expected connection to receive a message") } network.disconnectCh <- connection network.Close() if len(network.connections) != 0 { t.Errorf("Expected connnection queue to be empty, got %d", len(network.connections)) } }*/ func TestNetworkReceive(t *testing.T) { tests := []struct { input *Message expectedUpdates []string }{ {TestMessageSetButtonPressedController, []string{"FirmwareVersion", "DevCat"}}, {TestMessageEngineVersionAck, []string{"EngineVersion"}}, } for i, test := range tests { recvCh := make(chan []byte, 1) testDb := newTestProductDB() connection := make(chan *Message, 1) network := &Network{ recvCh: recvCh, DB: testDb, connections: []chan<- *Message{connection}, } buf, _ := test.input.MarshalBinary() recvCh <- buf close(recvCh) network.process() for _, update := range test.expectedUpdates { if !testDb.WasUpdated(update) { t.Errorf("tests[%d] expected %v to be updated in the database", i, update) } } if len(connection) != 1 { t.Errorf("tests[%d] expected connection to have received the message", i) } } } func TestNetworkSendMessage(t *testing.T) { tests := []struct { input *Message err error deviceInfo *DeviceInfo bufUpdated bool }{ {TestProductDataResponse, nil, &DeviceInfo{EngineVersion: VerI1}, false}, {TestProductDataResponse, nil, &DeviceInfo{EngineVersion: VerI2Cs}, true}, {TestProductDataResponse, ErrReadTimeout, nil, false}, } for i, test := range tests { sendCh := make(chan *PacketRequest, 1) testDb := newTestProductDB() testDb.deviceInfo = test.deviceInfo network := &Network{ DB: testDb, sendCh: sendCh, } go func(i int) { request := <-sendCh if test.bufUpdated && request.Payload[len(request.Payload)-1] == 0x00 { t.Errorf("tests[%d] expected checksum to be set", i) } request.Err = test.err request.DoneCh <- request }(i) err := network.sendMessage(test.input) if err != test.err { t.Errorf("tests[%d] expected %v got %v", i, test.err, err) } } } func TestNetworkEngineVersion(t *testing.T) { tests := []struct { returnedAck *Message returnedErr error expectedVersion EngineVersion }{ {TestMessageEngineVersionAck, nil, 1}, {TestMessageEngineVersionAck, nil, 2}, {TestMessageEngineVersionAck, nil, 3}, {TestMessageEngineVersionAck, ErrReadTimeout, 0}, } for i, test := range tests { sendCh := make(chan *PacketRequest, 1) recvCh := make(chan []byte, 1) network := New(sendCh, recvCh, time.Millisecond) go func() { request := <-sendCh if test.returnedErr == nil { ack := *test.returnedAck ack.Src = testDstAddr ack.Command = Command{0x00, ack.Command[1], byte(test.expectedVersion)} buf, _ := ack.MarshalBinary() recvCh <- buf } else { request.Err = test.returnedErr } request.DoneCh <- request }() version, err := network.EngineVersion(testDstAddr) if err != test.returnedErr { t.Errorf("tests[%d] expected %v got %v", i, test.returnedErr, err) } if version != test.expectedVersion { t.Errorf("tests[%d] expected %v got %v", i, test.expectedVersion, version) } network.Close() } } func TestNetworkIDRequest(t *testing.T) { tests := []struct { timeout bool returnedErr error expectedErr error expectedDevCat DevCat expectedFirmware FirmwareVersion }{ {false, ErrReadTimeout, ErrReadTimeout, DevCat{0, 0}, 0}, {false, nil, nil, DevCat{1, 2}, 3}, {false, nil, nil, DevCat{2, 3}, 4}, {true, nil, ErrReadTimeout, DevCat{0, 0}, 0}, } for i, test := range tests { sendCh := make(chan *PacketRequest, 1) recvCh := make(chan []byte, 1) network := New(sendCh, recvCh, time.Millisecond) go func() { request := <-sendCh if test.returnedErr == nil { // the test has to send an ACK, since the device would ack the set button pressed // command before sending a broadcast response ack := &Message{} ack.UnmarshalBinary(request.Payload) src := ack.Dst ack.Dst = ack.Src ack.Src = src ack.Flags = StandardDirectAck buf, _ := ack.MarshalBinary() recvCh <- buf if !test.timeout { // send the broadcast msg := *TestMessageSetButtonPressedController msg.Src = src msg.Dst = Address{test.expectedDevCat[0], test.expectedDevCat[1], byte(test.expectedFirmware)} buf, _ = msg.MarshalBinary() recvCh <- buf } } else { request.Err = test.returnedErr } request.DoneCh <- request }() info, err := network.IDRequest(testDstAddr) if err != test.expectedErr { t.Errorf("tests[%d] expected %v got %v", i, test.returnedErr, err) } if info.FirmwareVersion != test.expectedFirmware { t.Errorf("tests[%d] expected %v got %v", i, test.expectedFirmware, info.FirmwareVersion) } if info.DevCat != test.expectedDevCat { t.Errorf("tests[%d] expected %v got %v", i, test.expectedDevCat, info.DevCat) } network.Close() } } func TestNetworkDial(t *testing.T) { tests := []struct { deviceInfo *DeviceInfo engineVersion byte sendError error expectedErr error expected interface{} }{ {&DeviceInfo{EngineVersion: VerI1}, 0, nil, nil, &I1Device{}}, {&DeviceInfo{EngineVersion: VerI2}, 0, nil, nil, &I2Device{}}, {&DeviceInfo{EngineVersion: VerI2Cs}, 0, nil, nil, &I2CsDevice{}}, {nil, 0, nil, nil, &I1Device{}}, {nil, 1, nil, nil, &I2Device{}}, {nil, 2, nil, nil, &I2CsDevice{}}, {nil, 3, nil, ErrVersion, nil}, {nil, 0, ErrNotLinked, ErrNotLinked, &I2CsDevice{}}, } for i, test := range tests { testDb := newTestProductDB() network, sendCh, recvCh := newTestNetwork(1) network.DB = testDb if test.deviceInfo == nil { go func() { request := <-sendCh if test.sendError == nil { msg := *TestMessageEngineVersionAck msg.Src = Address{1, 2, 3} msg.Command = Command{0x00, msg.Command[1], byte(test.engineVersion)} buf, _ := msg.MarshalBinary() recvCh <- buf request.DoneCh <- request } else { request.Err = test.sendError request.DoneCh <- request } }() } else { testDb.deviceInfo = test.deviceInfo } device, err := network.Dial(Address{1, 2, 3}) if err != test.expectedErr { t.Errorf("tests[%d] Expected error %v got %v", i, test.expectedErr, err) } else if reflect.TypeOf(device) != reflect.TypeOf(test.expected) { t.Fatalf("tests[%d] expected type %T got type %T", i, test.expected, device) } network.Close() } } func TestNetworkClose(t *testing.T) { network, _, _ := newTestNetwork(1) network.Close() select { case _, open := <-network.closeCh: if open { t.Errorf("Expected closeCh to be closed") } default: t.Errorf("Expected read from closeCh to indicate a closed channel") } } /* func TestNetworkConnect(t *testing.T) { tests := []struct { deviceInfo *DeviceInfo engineVersion EngineVersion dst Address expected Device }{ {&DeviceInfo{DevCat: DevCat{42, 2}}, VerI1, Address{}, &I2Device{}}, {nil, VerI1, Address{42, 2, 3}, &I2Device{}}, } for i, test := range tests { var category Category testDb := newTestProductDB() bridge := &testBridge{} if test.deviceInfo == nil { msg := *TestMessageEngineVersionAck msg.Command[1] = byte(test.engineVersion) msg = *TestMessageSetButtonPressedController msg.Dst = test.dst category = Category(test.dst[0]) } else { testDb.deviceInfo = test.deviceInfo category = test.deviceInfo.DevCat.Category() } Devices.Register(category, func(Device, DeviceInfo) Device { return test.expected }) network := &NetworkImpl{ db: testDb, bridge: bridge, } device, _ := network.Connect(Address{1, 2, 3}) if device != test.expected { t.Fatalf("tests[%d] expected %v got %v", i, test.expected, device) } Devices.Delete(category) } }*/
package files import ( "crypto/md5" "encoding/hex" "io/ioutil" "log" ) type File struct { Path string Name string Hash string Size int } func (file *File) computeHash(done chan *File) { bytes, readError := ioutil.ReadFile(file.Path) if readError != nil { log.Printf("Encountered an error reading the file '%v' to calculate the Hash. Error: %v\n", file.Path, readError) } hash := md5.New() hash.Write(bytes) file.Size = len(bytes) file.Hash = hex.EncodeToString(hash.Sum(nil)) done <- file }
// Copyright (c) 2020 Chair of Applied Cryptography, Technische Universität // Darmstadt, Germany. All rights reserved. This file is part of go-perun. Use // of this source code is governed by a MIT-style license that can be found in // the LICENSE file. // Package test contains generic tests for channel backend implementations and // random generators of Params, States etc. for tests. package test // import "perun.network/go-perun/channel/test"
package main import ( "fmt" "github.com/Wan-Mi/RPCDemos/thriftDemo/hello" "git.apache.org/thrift.git/lib/go/thrift" ) type HelloServer struct { } func (e *HelloServer)SayHello(userName string, userAge int32) (r *hello.User, err error){ usr := hello.User{ Name:userName, Age:userAge, } fmt.Println(usr) return &usr,nil } func main() { transport, err := thrift.NewTServerSocket(":8988") if err != nil { panic(err) } handler := &HelloServer{} processor := hello.NewHelloServiceProcessor(handler) transportFactory := thrift.NewTBufferedTransportFactory(8192) protocolFactory := thrift.NewTCompactProtocolFactory() server := thrift.NewTSimpleServer4( processor, transport, transportFactory, protocolFactory, ) fmt.Println("server start") if err := server.Serve(); err != nil { panic(err) } }
// ///////////////////////////////////////////////////////////////////////////// // gate 服务器 package main import ( "github.com/zpab123/world" // world 库 ) // 主入口 func main() { // 创建代理 ad := NewAppDelegate() // 创建 app app := world.CreateApp("gate", ad) // 运行 app app.Run() }
package main import "github.com/davecgh/go-spew/spew" // 105. 从前序与中序遍历序列构造二叉树 // 根据一棵树的前序遍历与中序遍历构造二叉树。 // 注意: // 你可以假设树中没有重复的元素。 // https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ func main() { spew.Dump(buildTree([]int{3, 9, 20, 15, 7}, []int{9, 3, 15, 20, 7})) } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 前序遍历为:中-左-右 // 中序遍历为:左-中-右 // 参考106.从中序与后序遍历序列构造二叉树 直接写出优化后的方案 func buildTree(preorder []int, inorder []int) *TreeNode { n := len(inorder) if n == 0 { return nil } inorderMap := make(map[int]int, n) for i := 0; i < n; i++ { inorderMap[inorder[i]] = i } rootIndex := 0 return buildTreeHelper(preorder, &rootIndex, inorder, 0, n-1, inorderMap) } func buildTreeHelper(preorder []int, rootIndex *int, inorder []int, left, right int, inorderMap map[int]int) *TreeNode { if left > right { return nil } root := &TreeNode{ Val: preorder[*rootIndex], } (*rootIndex)++ root.Left = buildTreeHelper(preorder, rootIndex, inorder, left, inorderMap[root.Val]-1, inorderMap) root.Right = buildTreeHelper(preorder, rootIndex, inorder, inorderMap[root.Val]+1, right, inorderMap) return root }
package goftp import ( "crypto/tls" "fmt" "os" "testing" ) //import "fmt" var goodServer string var uglyServer string var badServer string func init() { //ProFTPD 1.3.5 Server (Debian) goodServer = "bo.mirror.garr.it:21" //Symantec EMEA FTP Server badServer = "ftp.packardbell.com:21" //Unknown server uglyServer = "ftp.musicbrainz.org:21" } func standard(host string) (msg string) { var err error var connection *FTP if connection, err = Connect(host); err != nil { return "Can't connect ->" + err.Error() } if err = connection.Login("anonymous", "anonymous"); err != nil { return "Can't login ->" + err.Error() } if _, err = connection.List(""); err != nil { return "Can't list ->" + err.Error() } connection.Close() return "" } func TestLogin_good(t *testing.T) { str := standard(goodServer) if len(str) > 0 { t.Error(str) } } func TestLogin_bad(t *testing.T) { str := standard(badServer) if len(str) > 0 { t.Error(str) } } func TestLogin_ugly(t *testing.T) { str := standard(uglyServer) if len(str) > 0 { t.Error(str) } } func TestLoginAuthTLS(t *testing.T) { host := os.Getenv("TEST_FTPES_HOST") port := os.Getenv("TEST_FTPES_PORT") username := os.Getenv("TEST_FTPES_USERNAME") password := os.Getenv("TEST_FTPES_PASSWORD") connection, err := ConnectDbg(fmt.Sprintf("%s:%s", host, port)) if err != nil { t.Fatal(err) } config := &tls.Config{ ServerName: host, MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, ClientSessionCache: tls.NewLRUClientSessionCache(32), ClientAuth: tls.RequestClientCert, } if err = connection.LoginAuthTLS(config, username, password); err != nil { t.Fatal(err) } if _, err = connection.List("/"); err != nil { t.Fatal(err) } connection.Close() return }
/* Copyright 2019 The MayaData 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 https://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 generic import ( "testing" "github.com/pkg/errors" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/json" "openebs.io/metac/apis/metacontroller/v1alpha1" "openebs.io/metac/controller/generic" "openebs.io/metac/test/integration/framework" ) // TestInstallUninstallCRD will verify if GenericController can be // used to implement install & uninstall of CustomResourceDefinition // given install & uninstall of a namespace. // // This function will try to get a CRD installed when a target namespace // gets installed. GenericController should also automatically uninstall // this CRD when this target namespace is deleted. func TestInstallUninstallCRD(t *testing.T) { // if testing.Short() { // t.Skip("Skipping TestApplyDeleteCRD in short mode") // } // namespace to setup GenericController ctlNSNamePrefix := "gctl-test" // name of the GenericController ctlName := "install-un-crd-ctrl" // name of the target namespace which is watched by GenericController targetNSName := "install-un-ns" // name of the target CRD which is reconciled by GenericController targetCRDName := "storages.dao.amitd.io" f := framework.NewFixture(t) defer f.TearDown() // create namespace to setup GenericController resources ctlNS := f.CreateNamespaceGen(ctlNSNamePrefix) // ------------------------------------------------------------------------- // Define the "reconcile logic" for sync i.e. create/update events of watch // ------------------------------------------------------------------------- // // NOTE: // Sync ensures creation of target CRD via attachments sHook := f.ServeWebhook(func(body []byte) ([]byte, error) { req := generic.SyncHookRequest{} if uerr := json.Unmarshal(body, &req); uerr != nil { return nil, uerr } // initialize the hook response resp := generic.SyncHookResponse{} // we desire this CRD object crd := framework.BuildUnstructuredObjFromJSON( "apiextensions.k8s.io/v1beta1", "CustomResourceDefinition", targetCRDName, `{ "spec": { "group": "dao.amitd.io", "version": "v1alpha1", "scope": "Namespaced", "names": { "plural": "storages", "singular": "storage", "kind": "Storage", "shortNames": ["stor"] }, "additionalPrinterColumns": [ { "JSONPath": ".spec.capacity", "name": "Capacity", "description": "Capacity of the storage", "type": "string" }, { "JSONPath": ".spec.nodeName", "name": "NodeName", "description": "Node where the storage gets attached", "type": "string" }, { "JSONPath": ".status.phase", "name": "Status", "description": "Identifies the current status of the storage", "type": "string" } ] } }`, ) // add CRD to attachments to let GenericController // sync i.e. create resp.Attachments = append(resp.Attachments, crd) return json.Marshal(resp) }) // --------------------------------------------------------------------- // Define the "reconcile logic" for finalize i.e. delete event of watch // --------------------------------------------------------------------- // // NOTE: // Finalize ensures deletion of target CRD via attachments // isFinalized helps in determining if the CRD was deleted // and is no longer a part of attachment. var isFinalized bool fHook := f.ServeWebhook(func(body []byte) ([]byte, error) { req := generic.SyncHookRequest{} if uerr := json.Unmarshal(body, &req); uerr != nil { return nil, uerr } // initialize the hook response resp := generic.SyncHookResponse{} if req.Watch.GetDeletionTimestamp() == nil { resp.ResyncAfterSeconds = 2 // no need to reconcile the attachments since // watch is not marked for deletion resp.SkipReconcile = true } else { // set attachments to nil to let GenericController // finalize i.e. delete CRD resp.Attachments = nil // finalize hook should be executed till its request // has attachments if req.Attachments.IsEmpty() { // since all attachments are deleted from cluster // indicate GenericController to mark completion // of finalize hook resp.Finalized = true } else { // if there are still attachments seen in the request // keep resyncing the watch resp.ResyncAfterSeconds = 2 } } // Set this to help in verifing this test case outside // of this finalize block isFinalized = resp.Finalized t.Logf("Finalize: Req.Attachments.Len=%d", req.Attachments.Len()) return json.Marshal(resp) }) // --------------------------------------------------------- // Define & Apply a GenericController i.e. a Meta Controller // --------------------------------------------------------- // This is one of the meta controller that is defined as // a Kubernetes custom resource. It listens to the resource // specified in the watch field and acts against the resources // specified in the attachments field. f.CreateGenericController( ctlName, ctlNS.Name, // set 'sync' as well as 'finalize' hooks generic.WithWebhookSyncURL(&sHook.URL), generic.WithWebhookFinalizeURL(&fHook.URL), // Namespace is the watched resource generic.WithWatch( &v1alpha1.GenericControllerResource{ ResourceRule: v1alpha1.ResourceRule{ APIVersion: "v1", Resource: "namespaces", }, // We are interested only for the target namespace only NameSelector: []string{targetNSName}, }, ), // CRDs are the attachments // // This is done so as to implement create & delete of CRD // when above watch resource i.e. namespce is created & deleted. generic.WithAttachments( []*v1alpha1.GenericControllerAttachment{ // We want the target CRD only i.e. storages.dao.amitd.io &v1alpha1.GenericControllerAttachment{ GenericControllerResource: v1alpha1.GenericControllerResource{ ResourceRule: v1alpha1.ResourceRule{ APIVersion: "apiextensions.k8s.io/v1beta1", Resource: "customresourcedefinitions", }, NameSelector: []string{targetCRDName}, }, }, }, ), ) var err error // --------------------------------------------------- // Create the target namespace i.e. target under test // --------------------------------------------------- // // NOTE: // This triggers reconciliation _, err = f.GetTypedClientset().CoreV1().Namespaces().Create( &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: targetNSName, }, }, ) if err != nil { t.Fatal(err) } // Need to wait & see if our controller works as expected // Make sure the specified attachments i.e. CRD is created t.Logf("Wait for creation of CRD %s", targetCRDName) crdCreateErr := f.Wait(func() (bool, error) { // ------------------------------------------------ // verify if target CRD is created i.e. reconciled // ------------------------------------------------ crdCreateObj, createErr := f.GetCRDClient().CustomResourceDefinitions().Get(targetCRDName, metav1.GetOptions{}) if createErr != nil { return false, createErr } if crdCreateObj == nil { return false, errors.Errorf("CRD %s is not created", targetCRDName) } // condition passed return true, nil }) if crdCreateErr != nil { t.Fatalf("CRD %s wasn't created: %v", targetCRDName, crdCreateErr) } // Wait till target namespace is assigned with GenericController's // finalizer // // NOTE: // GenericController automatically updates the watch with // its own finalizer if it finds a finalize hook in its // specifications. nsWithFErr := f.Wait(func() (bool, error) { nsWithF, err := f.GetTypedClientset().CoreV1().Namespaces().Get(targetNSName, metav1.GetOptions{}) if err != nil { return false, err } for _, finalizer := range nsWithF.GetFinalizers() { if finalizer == "protect.gctl.metac.openebs.io/"+ctlNS.GetName()+"-"+ctlName { return true, nil } } return false, errors.Errorf("Namespace %s is not set with gctl finalizer", targetNSName) }) if nsWithFErr != nil { // we wait till timeout & panic if condition is not met t.Fatal(nsWithFErr) } // ------------------------------------------------------ // Trigger finalize by deleting the target namespace // ------------------------------------------------------ err = f.GetTypedClientset().CoreV1().Namespaces().Delete(targetNSName, &metav1.DeleteOptions{}) if err != nil { t.Fatal(err) } // Need to wait & see if our controller works as expected // Make sure the specified attachments i.e. CRD is deleted t.Logf("Wait for deletion of CRD %s", targetCRDName) crdDelErr := f.Wait(func() (bool, error) { var getErr error // ------------------------------------------------ // verify if target CRD is deleted i.e. reconciled // ------------------------------------------------ if isFinalized { t.Logf("CRD %s should have been deleted: IsFinalized %t", targetCRDName, isFinalized) return true, nil } crdObj, getErr := f.GetCRDClient().CustomResourceDefinitions().Get(targetCRDName, metav1.GetOptions{}) if getErr != nil && !apierrors.IsNotFound(getErr) { return false, getErr } if crdObj != nil && crdObj.GetDeletionTimestamp() == nil { return false, errors.Errorf("CRD %s is not marked for deletion", targetCRDName) } // condition passed return true, nil }) if crdDelErr != nil { t.Fatalf("CRD %s wasn't deleted: %v", targetCRDName, crdDelErr) } t.Logf("Test Install Uninstall CRD %s passed", targetCRDName) }
package sarchivos import ( "FileSystem-LWH/disco/acciones" "fmt" "sort" "strconv" ) // Mount Estructura de las particiones montadas type Mount struct { Ruta string Nombre string ID string Numero int IDent string } var particionesMontadas []Mount var post int = 0 var abc = []string{"a", "b", "c", "d", "e", "g", "h", "i", "j", "k", "l", "m"} // Montar agrega al arreglo la particion func Montar(path string, name string) { acciones.LeerMBR(path) acciones.BuscarParticionCreada(name, path) sort.SliceStable(particionesMontadas, func(i, j int) bool { return particionesMontadas[i].Numero > particionesMontadas[j].Numero }) if buscarParticion(name) { panic(">> LA PARTICION FUE MONTADA PREVIAMENTE") } for _, partition := range particionesMontadas { if partition.Ruta == path { num := partition.Numero + 1 particionesMontadas = append(particionesMontadas, Mount{ Ruta: path, Nombre: name, ID: "vd" + partition.IDent + strconv.Itoa(num), Numero: partition.Numero + 1, IDent: partition.IDent, }) return } } particionesMontadas = append(particionesMontadas, Mount{ Ruta: path, Nombre: name, ID: "vd" + abc[post] + "1", Numero: 1, IDent: abc[post], }) post++ sort.SliceStable(particionesMontadas, func(i, j int) bool { return particionesMontadas[i].ID < particionesMontadas[j].ID }) } // MostrarMount imprime todas las particiones montadas en memoria func MostrarMount() { for _, partition := range particionesMontadas { fmt.Println(">> -id->"+partition.ID, "-path->\""+partition.Ruta+ "\" -name->\""+partition.Nombre+"\"") } } // Desmontar quita la particion de memoria func Desmontar(name string) { sort.SliceStable(particionesMontadas, func(i, j int) bool { return particionesMontadas[i].Numero > particionesMontadas[j].Numero }) for _, partition := range particionesMontadas { if partition.ID == name { particionesMontadas = removeIt(partition, particionesMontadas) return } } panic(">> NO SE ENCONTRO LA PARTICION") } func removeIt(ss Mount, ssSlice []Mount) []Mount { for idx, v := range ssSlice { if v == ss { return append(ssSlice[0:idx], ssSlice[idx+1:]...) } } return ssSlice } func buscarParticion(name string) bool { for _, partition := range particionesMontadas { if partition.Nombre == name { return true } } return false } // ObtenerPath regresa la path de una particion func ObtenerPath(id string) string { for _, partition := range particionesMontadas { if partition.ID == id { return partition.Ruta } } panic(">> NO SE ENCONTRO LA PARTICION") }
/* Package ast defines the Abstract Syntax Tree for RiveScript. The tree looks like this (in JSON-style syntax): { "Begin": { "Global": {}, // Global vars "Var": {}, // Bot variables "Sub": {}, // Substitution map "Person": {}, // Person substitution map "Array": {}, // Arrays }, "Topics": {}, "Objects": [], } */ package ast // Root represents the root of the AST tree. type Root struct { Begin Begin `json:"begin"` Topics map[string]*Topic `json:"topics"` Objects []*Object `json:"objects"` } // Begin represents the "begin block" style data (configuration). type Begin struct { Global map[string]string `json:"global"` Var map[string]string `json:"var"` Sub map[string]string `json:"sub"` Person map[string]string `json:"person"` Array map[string][]string `json:"array"` // Map of string (names) to arrays-of-strings } // Topic represents a topic of conversation. type Topic struct { Triggers []*Trigger `json:"triggers"` Includes map[string]bool `json:"includes"` Inherits map[string]bool `json:"inherits"` } // Trigger has a trigger pattern and all the subsequent handlers for it. type Trigger struct { Trigger string `json:"trigger"` Reply []string `json:"reply"` Condition []string `json:"condition"` Redirect string `json:"redirect"` Previous string `json:"previous"` } // Object contains source code of dynamically parsed object macros. type Object struct { Name string `json:"name"` Language string `json:"language"` Code []string `json:"code"` } // New creates a new, empty, abstract syntax tree. func New() *Root { ast := &Root{ // Initialize all the structures. Begin: Begin{ Global: map[string]string{}, Var: map[string]string{}, Sub: map[string]string{}, Person: map[string]string{}, Array: map[string][]string{}, }, Topics: map[string]*Topic{}, Objects: []*Object{}, } // Initialize the 'random' topic. ast.AddTopic("random") return ast } // AddTopic sets up the AST tree for a new topic and gets it ready for // triggers to be added. func (ast *Root) AddTopic(name string) { ast.Topics[name] = new(Topic) ast.Topics[name].Triggers = []*Trigger{} ast.Topics[name].Includes = map[string]bool{} ast.Topics[name].Inherits = map[string]bool{} }
package dushengchen func findKthLargest(nums []int, k int) int { return 0 }
package matchers import ( "archive/zip" "bytes" "path/filepath" ) func Xlsx(in []byte) bool { return checkMsOfficex(in, "xl") } func Docx(in []byte) bool { return checkMsOfficex(in, "word") } func Pptx(in []byte) bool { return checkMsOfficex(in, "ppt") } // TODO func Doc(in []byte) bool { return false } func Ppt(in []byte) bool { return false } func Xls(in []byte) bool { return false } func checkMsOfficex(in []byte, folder string) bool { reader := bytes.NewReader(in) zipr, err := zip.NewReader(reader, reader.Size()) if err != nil { return false } return zipHasFile(zipr, "[Content_Types].xml") && zipHasFolder(zipr, folder) } func zipHasFolder(r *zip.Reader, folder string) bool { for _, f := range r.File { if filepath.Dir(f.Name) == folder { return true } } return false } func zipHasFile(r *zip.Reader, file string) bool { for _, f := range r.File { if f.Name == file { return true } } return false }
package simplemath import ( "testing" ) func TestGCD(t *testing.T) { if GCD(3, 9) != 3 { t.Fatalf("expected GCD to be 3\n") } if GCD(7, 19) != 1 { t.Fatalf("expected GCD to be 1\n") } if GCD(500, 5, 1000) != 5 { t.Fatalf("expected GCD to be 5\n") } if GCD(9, 27, 900, 27000) != 9 { t.Fatalf("expected GCD to be 9\n") } }
// +build e2e package e2e import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" "github.com/argoproj/argo/test/e2e/fixtures" ) type SmokeSuite struct { fixtures.E2ESuite } func (s *SmokeSuite) TestBasicWorkflow() { s.Given(). Workflow("@smoke/basic.yaml"). When(). SubmitWorkflow(). WaitForWorkflow(). Then(). ExpectWorkflow(func(t *testing.T, _ *metav1.ObjectMeta, status *wfv1.WorkflowStatus) { assert.Equal(t, wfv1.NodeSucceeded, status.Phase) assert.NotEmpty(t, status.Nodes) assert.NotEmpty(t, status.ResourcesDuration) }) } func (s *SmokeSuite) TestArtifactPassing() { s.Given(). Workflow("@smoke/artifact-passing.yaml"). When(). SubmitWorkflow(). WaitForWorkflow(). Then(). ExpectWorkflow(func(t *testing.T, _ *metav1.ObjectMeta, status *wfv1.WorkflowStatus) { assert.Equal(t, wfv1.NodeSucceeded, status.Phase) }) } func (s *SmokeSuite) TestWorkflowTemplateBasic() { s.Given(). WorkflowTemplate("@smoke/workflow-template-whalesay-template.yaml"). Workflow("@smoke/hello-world-workflow-tmpl.yaml"). When(). CreateWorkflowTemplates(). SubmitWorkflow(). WaitForWorkflow(60 * time.Second). Then(). ExpectWorkflow(func(t *testing.T, _ *metav1.ObjectMeta, status *wfv1.WorkflowStatus) { assert.Equal(t, wfv1.NodeSucceeded, status.Phase) }) } func TestSmokeSuite(t *testing.T) { suite.Run(t, new(SmokeSuite)) }
package unique import ( "sort" ) // RemoveDuplicates . // Filter for unique values and remove duplicates func RemoveDuplicates(data []int) []int { var result = []int{} for _, v := range data { var ok = true for _, e := range result { if v == e { ok = false } } if ok { result = append(result, v) } } return result } // RemoveDuplicates2 . func RemoveDuplicates2(elements []int) []int { encountered := map[int]bool{} result := []int{} for _, v := range elements { if encountered[v] == true { continue } encountered[v] = true result = append(result, v) } return result } // RemoveDuplicates3 . func RemoveDuplicates3(data []int) []int { if len(data) < 2 { return data } sort.Ints(data) var result = []int{data[0]} for i := 1; i < len(data); i++ { if data[i] != data[i-1] { result = append(result, data[i]) } } return result }
package main import ( "archive/zip" "io" "os" "testing" ) func TestCompressing(t *testing.T) { w := createZipWriter(createZipFile("done.zip")) defer w.Close() fileName := "config.json" fileToZip, err := os.Open(fileName) defer fileToZip.Close() if err != nil { panic(err) } info, err := fileToZip.Stat() if err != nil { panic(err) } header, err := zip.FileInfoHeader(info) if err != nil { panic(err) } header.Name = fileName header.Method = zip.Deflate fileWriter, err := w.CreateHeader(header) if err != nil { panic(err) } _, err = io.Copy(fileWriter, fileToZip) if err != nil { panic(err) } } func TestGenerateFileName(t *testing.T) { result := generateZipFileName() if result == "" { t.Fail() } else { t.Log(result) } } func TestGenerateFileName2(t *testing.T) { os.Open("C:\\Users\\Gabriel\\Documents\\Nekrotus\\ORDEM_DAS_POCOES.TXT") select {} }
package suite_init type SuiteData struct { *StubsData *SynchronizedSuiteCallbacksData *WerfBinaryData *ProjectNameData *K8sDockerRegistryData *TmpDirData *ContainerRegistryPerImplementationData } func (data *SuiteData) SetupStubs(setupData *StubsData) bool { data.StubsData = setupData return true } func (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool { data.SynchronizedSuiteCallbacksData = setupData return true } func (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool { data.WerfBinaryData = setupData return true } func (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool { data.ProjectNameData = setupData return true } func (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool { data.K8sDockerRegistryData = setupData return true } func (data *SuiteData) SetupTmp(setupData *TmpDirData) bool { data.TmpDirData = setupData return true } func (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool { data.ContainerRegistryPerImplementationData = setupData return true }
package main import "net/http" func handler(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", "application/json") w.Write([]byte(`{"message": "hello world"}`)) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8001", nil) }
//+build integration package queue_test import ( "context" "math/rand" "strconv" "sync" "testing" "time" "github.com/stretchr/testify/require" "github.com/rwool/saas-interview-challenge1/pkg/service/internal/redistest" "github.com/rwool/saas-interview-challenge1/pkg/service/queue" "github.com/stretchr/testify/assert" "golang.org/x/sync/errgroup" ) var seedOnce sync.Once func randString() string { seedOnce.Do(func() { rand.Seed(time.Now().UnixNano()) }) i := rand.Int() return strconv.Itoa(i) } func TestRedisConnection(t *testing.T) { t.Parallel() client := redistest.Connect(t) assert.NoError(t, client.Ping().Err(), "Should be no error with Redis connection.") } func TestQueue(t *testing.T) { //t.Parallel() client := redistest.Connect(t) adapter := queue.NewRedisAdapter(client) id := randString() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() group, ctx := errgroup.WithContext(ctx) // Wait on a channel to "burst" all requests as fast as possible. var ready sync.WaitGroup ready.Add(11) start := make(chan struct{}) found := make(map[string]struct{}) var foundMu sync.Mutex group.Go(func() error { ready.Done() <-start for i := 0; i < 10; i++ { err := adapter.Push(ctx, id, [][]byte{ []byte(strconv.Itoa(i)), }) if err != nil { return err } } return nil }) for i := 0; i < 10; i++ { group.Go(func() error { ready.Done() <-start data, err := adapter.Pull(ctx, id) if err != nil { return err } foundMu.Lock() found[string(data)] = struct{}{} foundMu.Unlock() return nil }) } ready.Wait() close(start) err := group.Wait() require.NoError(t, err, "Sending and receiving messages should not error.") for i := 0; i < 10; i++ { iStr := strconv.Itoa(i) _, ok := found[iStr] require.True(t, ok, "Missing value %s in found set", iStr) } } // TODO: Add tests for multi-send, tests with mocks for error handling tests, // large payloads, empty payloads, etc.
package handler import ( "encoding/json" "fmt" "log" "net/http" "strconv" "github.com/RamVellanki/habittracker/app/services" "github.com/gin-gonic/gin" ) // func PostHabits(c *gin.Context) { // log.Print(c.Request.Body) // c.IndentedJSON(http.StatusOK, string("K")) // } // GetHabits godoc // @Summary Get all active/all habits // @Description get's active or all habits based on query // @Tags root // @Param status query string default "set to all to get all habits (active/inactive)" // @Produce json // @Success 200 // @Router /habits [get] func GetHabits(c *gin.Context) { status := c.DefaultQuery("status", "") log.Print("status: " + status) getAll := false if status == "all" { getAll = true } data, err := json.Marshal(*services.GetHabits(getAll)) if err != nil { fmt.Print(err) c.IndentedJSON(http.StatusInternalServerError, gin.H{"Error": err}) return } c.Writer.Header().Set("Content-Type", "application/json") c.IndentedJSON(http.StatusOK, string(data)) } // GetHabitsById godoc // @Summary Get all habits by Id // @Description get's all habits based on input Id // @Tags root // @Param id path string true "use the id of the habit that you wish to get" // @Produce json // @Success 200 // @Router /habits/{id} [get] func GetHabitsById(c *gin.Context) { log.Print(c.Param("id")) id, err := strconv.Atoi(c.Param("id")) if err != nil { log.Print(err) c.String(http.StatusBadRequest, "error: use valid integer id") return } log.Printf("ID Requested: %d", id) data, err := services.GetHabitsById(id) if err != nil { log.Print(err) c.IndentedJSON(http.StatusInternalServerError, gin.H{"Error": err}) return } datajson, err := json.Marshal(data) if err != nil { log.Print(err) c.IndentedJSON(http.StatusInternalServerError, gin.H{"Error": err}) return } c.Writer.Header().Set("Content-Type", "application/json") c.IndentedJSON(http.StatusOK, string(datajson)) }
// Copyright (C) 2019 Kevin L. Mitchell <klmitch@mit.edu> // // 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 object import ( "testing" "github.com/stretchr/testify/assert" ) func TestObjTypeString(t *testing.T) { a := assert.New(t) result := BLOCK.String() a.Equal(result, "BLOCK") } func TestMetaBase(t *testing.T) { a := assert.New(t) result := Meta(BLOCK, 0) a.Equal(result, ObjMeta(0)) } func TestMetaAlt(t *testing.T) { a := assert.New(t) result := Meta(DIRECTORY, COMPRESSED|ENCRYPTED) a.Equal(result, ObjMeta(0xc2)) } func TestObjMetaCompressed(t *testing.T) { a := assert.New(t) a.False(Meta(BLOCK, 0).Compressed()) a.True(Meta(BLOCK, COMPRESSED).Compressed()) a.False(Meta(BLOCK, ENCRYPTED).Compressed()) a.True(Meta(BLOCK, COMPRESSED|ENCRYPTED).Compressed()) } func TestObjMetaSetCompressed(t *testing.T) { a := assert.New(t) obj := Meta(BLOCK, 0) result := obj.SetCompressed() a.Equal(obj, result) a.True(result.Compressed()) } func TestObjMetaEncrypted(t *testing.T) { a := assert.New(t) a.False(Meta(BLOCK, 0).Encrypted()) a.False(Meta(BLOCK, COMPRESSED).Encrypted()) a.True(Meta(BLOCK, ENCRYPTED).Encrypted()) a.True(Meta(BLOCK, COMPRESSED|ENCRYPTED).Encrypted()) } func TestObjMetaSetEncrypted(t *testing.T) { a := assert.New(t) obj := Meta(BLOCK, 0) result := obj.SetEncrypted() a.Equal(obj, result) a.True(result.Encrypted()) } func TestObjMetaType(t *testing.T) { a := assert.New(t) a.Equal(Meta(BLOCK, 0).Type(), BLOCK) a.Equal(Meta(FILE, COMPRESSED).Type(), FILE) a.Equal(Meta(DIRECTORY, ENCRYPTED).Type(), DIRECTORY) a.Equal(Meta(SNAPSHOT, COMPRESSED|ENCRYPTED).Type(), SNAPSHOT) }
package common type DataFormat struct { Status int `json:"status"` Message string `json:"message"` Data interface{} `json:"data"` } func Format(status int, message string, data interface{}) DataFormat { return DataFormat{ Status: status, Message: message, Data: data, } }
package common import ( "regexp" ) const ( Namespace = "TitanGRM" FilePre = "File:" NginxPre = "Nginx:" GisPre = "Gis:" RasterPre = "Raster:" OfficePre = "Office:" FileUpload = "file" Base64Upload = "base64" OmitArg = "omit" DataLoading = "loading" DataNormal = "normal" DataObsoleted = "obsoleted" ) const ( DBType = "DB" // 数据库 NFSType = "NFS" // 网络文件系统 DFSType = "DFS" // 分布式文件系统 ) const ( POSTGRESQL = "PostgreSQL" // pg数据库 MONGODB = "MongoDB" // MongoDB ) const bitsPerWord = 32 << uint(^uint(0)>>63) // Implementation-specific size of int and uint in bits. const BitsPerWord = bitsPerWord // either 32 or 64 // Implementation-specific integer limit values. const ( MaxInt = 1<<(BitsPerWord-1) - 1 // either 1<<31 - 1 or 1<<63 - 1 MinInt = -MaxInt - 1 // either -1 << 31 or -1 << 63 MaxUint = 1<<BitsPerWord - 1 // either 1<<32 - 1 or 1<<64 - 1 ) var ( // enforceIndexRegex is a regular expression which extracts the enforcement error EnforceIndexRegex = regexp.MustCompile(`\((Enforcing job modify index.*)\)`) TileBlankPNG = []byte{137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 1, 0, 0, 0, 1, 0, 1, 3, 0, 0, 0, 102, 188, 58, 37, 0, 0, 0, 3, 80, 76, 84, 69, 0, 0, 0, 167, 122, 61, 218, 0, 0, 0, 1, 116, 82, 78, 83, 0, 64, 230, 216, 102, 0, 0, 0, 31, 73, 68, 65, 84, 104, 222, 237, 193, 1, 13, 0, 0, 0, 194, 32, 251, 167, 54, 199, 55, 96, 0, 0, 0, 0, 0, 0, 0, 0, 113, 7, 33, 0, 0, 1, 167, 87, 41, 215, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130} )
// This file was generated for SObject DatacloudContact, API Version v43.0 at 2018-07-30 03:48:11.604019131 -0400 EDT m=+57.948799959 package sobjects import ( "fmt" "strings" ) type DatacloudContact struct { BaseSObject City string `force:",omitempty"` CompanyId string `force:",omitempty"` CompanyName string `force:",omitempty"` ContactId string `force:",omitempty"` Country string `force:",omitempty"` Department string `force:",omitempty"` Email string `force:",omitempty"` ExternalId string `force:",omitempty"` FirstName string `force:",omitempty"` Id string `force:",omitempty"` IsInCrm bool `force:",omitempty"` IsInactive bool `force:",omitempty"` IsOwned bool `force:",omitempty"` LastName string `force:",omitempty"` Level string `force:",omitempty"` Phone string `force:",omitempty"` State string `force:",omitempty"` Street string `force:",omitempty"` Title string `force:",omitempty"` UpdatedDate string `force:",omitempty"` Zip string `force:",omitempty"` } func (t *DatacloudContact) ApiName() string { return "DatacloudContact" } func (t *DatacloudContact) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("DatacloudContact #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tCity: %v\n", t.City)) builder.WriteString(fmt.Sprintf("\tCompanyId: %v\n", t.CompanyId)) builder.WriteString(fmt.Sprintf("\tCompanyName: %v\n", t.CompanyName)) builder.WriteString(fmt.Sprintf("\tContactId: %v\n", t.ContactId)) builder.WriteString(fmt.Sprintf("\tCountry: %v\n", t.Country)) builder.WriteString(fmt.Sprintf("\tDepartment: %v\n", t.Department)) builder.WriteString(fmt.Sprintf("\tEmail: %v\n", t.Email)) builder.WriteString(fmt.Sprintf("\tExternalId: %v\n", t.ExternalId)) builder.WriteString(fmt.Sprintf("\tFirstName: %v\n", t.FirstName)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tIsInCrm: %v\n", t.IsInCrm)) builder.WriteString(fmt.Sprintf("\tIsInactive: %v\n", t.IsInactive)) builder.WriteString(fmt.Sprintf("\tIsOwned: %v\n", t.IsOwned)) builder.WriteString(fmt.Sprintf("\tLastName: %v\n", t.LastName)) builder.WriteString(fmt.Sprintf("\tLevel: %v\n", t.Level)) builder.WriteString(fmt.Sprintf("\tPhone: %v\n", t.Phone)) builder.WriteString(fmt.Sprintf("\tState: %v\n", t.State)) builder.WriteString(fmt.Sprintf("\tStreet: %v\n", t.Street)) builder.WriteString(fmt.Sprintf("\tTitle: %v\n", t.Title)) builder.WriteString(fmt.Sprintf("\tUpdatedDate: %v\n", t.UpdatedDate)) builder.WriteString(fmt.Sprintf("\tZip: %v\n", t.Zip)) return builder.String() } type DatacloudContactQueryResponse struct { BaseQuery Records []DatacloudContact `json:"Records" force:"records"` }
package cmd import ( "fmt" "github.com/spf13/cobra" "log" ) var versionName = 0.1 var rootCmd = &cobra.Command{ Use: "gorse", Short: "gorse: Go Recommender System Engine", Long: "gorse is an offline recommender system backend based on collaborative filtering written in Go.", Run: func(cmd *cobra.Command, args []string) { if len(args) == 0 { cmd.Help() } }, } var versionCmd = &cobra.Command{ Use: "version", Short: "Check the version", Run: func(cmd *cobra.Command, args []string) { fmt.Println(versionName) }, } // Main is the main entry of gorse. func Main() { rootCmd.AddCommand(commandTest) rootCmd.AddCommand(commandImportFeedback) rootCmd.AddCommand(commandImportItems) rootCmd.AddCommand(commandExportFeedback) rootCmd.AddCommand(commandExportItems) rootCmd.AddCommand(commandServe) rootCmd.AddCommand(versionCmd) if err := rootCmd.Execute(); err != nil { log.Fatal(err) } }
package main import ( "fmt" "github.com/nbgucer/advent-of-code-2018/utils" "log" "strconv" ) func main() { sum := 0 result := 0 found := false seenFrequencies := make(map[int]int) seenFrequencies[0] = 1 fileName := "days\\day-1\\input" stringSlice := utils.GetInputAsSlice(fileName) // Calculate sum for found == false { for i, item := range stringSlice { intItem, err := strconv.Atoi(item) if err == nil { sum += intItem _, ok := seenFrequencies[sum] if ok { result = sum found = true break } else { seenFrequencies[sum] = 1 } } else if len(item) == 0 { //Empty string, skip log.Printf("Empty string. Skipping at line %d \n", i) } else { log.Printf("Unable to convert %s to int. at line %d \n", item, i) } } } // Print result fmt.Printf("Result is %d \n", result) }
package main import ( "fmt" "strings" ) type Passwords interface { GetMasterPassword() string } type SimonsPasswords struct{} type PasswordsProxy struct { user string userPasswords SimonsPasswords } func NewPasswordsProxy(user string) PasswordsProxy { proxy := PasswordsProxy{ user, SimonsPasswords{}, } return proxy } func (passwords SimonsPasswords) GetMasterPassword() string { return "Wubba lubba dub dub" } func (proxy PasswordsProxy) GetMasterPassword() string { password := proxy.userPasswords.GetMasterPassword() if strings.ToLower(proxy.user) == "simon" { return password } return strings.Repeat("*", len(password)) } func main() { var proxy Passwords proxy = NewPasswordsProxy("Bob") fmt.Println(proxy.GetMasterPassword()) // ******************* proxy = NewPasswordsProxy("Simon") fmt.Println(proxy.GetMasterPassword()) // Wubba lubba dub dub }
package main import ( "bytes" "github.com/stretchr/testify/assert" "io/ioutil" "math" "net/http" "net/http/httptest" "net/url" "strconv" "testing" ) const ( URL_AUTHENTICATE = "/auth" URL_AUTHENTICATE_FAILING = "/auth_fail" URL_CREATE_NEW_APP = "/new_app" URL_CREATE_NEW_APP_FAILING = "/new_app_fail" URL_CREATE_NEW_MEETING = "/new_meeting" URL_PERFORM_DISCOVERY = "/discovery" URL_RESPONSE_WITH_AUTH_HEADER = "/response_with_auth_header" URL_RESPONSE_WITHOUT_AUTH_HEADER = "/response_without_auth_header" URL_READ_USER_RESOURCE = "/user" URL_INVALID = "invalid://u r l" TEST_TOKEN = "testtoken" TEST_MY_ONLINE_MEETINGS_URL = "/ucwa/oauth/v1/applications/123/onlineMeetings/myOnlineMeetings" TEST_ONLINE_MEETING_ID = "FRA03I2T" TEST_JOIN_URL = "https://test.com/testcompany/testuser/FRA03I2T" TEST_USER_URL = "https://dc2.testcompany.com/Autodiscover/AutodiscoverService.svc/root/oauth/user" TEST_APPLICATIONS_URL = "https://dc2.testcompany.com/ucwa/oauth/v1/applications" TEST_AUTH_HEADER = "test_auth_header" ) var ( server *httptest.Server ) func TestClient(t *testing.T) { setupTestServer(t) defer teardown() client := NewClient() t.Run("test authenticate", func(t *testing.T) { r, err := client.authenticate(server.URL+URL_AUTHENTICATE, url.Values{}) assert.Nil(t, err) assert.NotNil(t, r) assert.Equal(t, TEST_TOKEN, r.Access_token) r, err = client.authenticate(URL_INVALID, url.Values{}) assert.NotNil(t, err) assert.Nil(t, r) r, err = client.authenticate(server.URL+URL_AUTHENTICATE_FAILING, url.Values{}) assert.NotNil(t, err) assert.Nil(t, r) }) t.Run("test createNewApplication", func(t *testing.T) { r, err := client.createNewApplication(server.URL+URL_CREATE_NEW_APP, &NewApplicationRequest{}, TEST_TOKEN) assert.Nil(t, err) assert.NotNil(t, r) assert.Equal(t, TEST_MY_ONLINE_MEETINGS_URL, r.Embedded.OnlineMeetings.OnlineMeetingsLinks.MyOnlineMeetings.Href) r, err = client.createNewApplication(URL_INVALID, nil, TEST_TOKEN) assert.NotNil(t, err) assert.Nil(t, r) r, err = client.createNewApplication("", nil, TEST_TOKEN) assert.NotNil(t, err) assert.Equal(t, "", r.Embedded.OnlineMeetings.OnlineMeetingsLinks.MyOnlineMeetings.Href) r, err = client.createNewApplication(server.URL+URL_CREATE_NEW_APP_FAILING, nil, TEST_TOKEN) assert.NotNil(t, err) assert.Equal(t, "", r.Embedded.OnlineMeetings.OnlineMeetingsLinks.MyOnlineMeetings.Href) }) t.Run("test createNewMeeting", func(t *testing.T) { r, err := client.createNewMeeting(server.URL+URL_CREATE_NEW_MEETING, &NewMeetingRequest{}, TEST_TOKEN) assert.Nil(t, err) assert.NotNil(t, r) assert.Equal(t, TEST_ONLINE_MEETING_ID, r.MeetingId) assert.Equal(t, TEST_JOIN_URL, r.JoinUrl) r, err = client.createNewMeeting(URL_INVALID, math.Inf(1), TEST_TOKEN) assert.NotNil(t, err) assert.Nil(t, r) }) t.Run("test performDiscovery", func(t *testing.T) { r, err := client.performDiscovery(server.URL + URL_PERFORM_DISCOVERY) assert.Nil(t, err) assert.NotNil(t, r) assert.Equal(t, TEST_USER_URL, r.Links.User.Href) r, err = client.performDiscovery(URL_INVALID) assert.NotNil(t, err) assert.Nil(t, r) }) t.Run("test performRequestAndGetAuthHeader", func(t *testing.T) { r, err := client.performRequestAndGetAuthHeader(server.URL + URL_RESPONSE_WITH_AUTH_HEADER) assert.Nil(t, err) assert.NotNil(t, r) assert.Equal(t, TEST_AUTH_HEADER, *r) r, err = client.performRequestAndGetAuthHeader(URL_INVALID) assert.NotNil(t, err) assert.Nil(t, r) r, err = client.performRequestAndGetAuthHeader("") assert.NotNil(t, err) assert.Nil(t, r) r, err = client.performRequestAndGetAuthHeader(server.URL + URL_RESPONSE_WITHOUT_AUTH_HEADER) assert.NotNil(t, err) assert.Equal(t, "Response doesn't have WWW-AUTHENTICATE header!", err.Error()) assert.Nil(t, r) }) t.Run("test readUserResource", func(t *testing.T) { r, err := client.readUserResource(server.URL+URL_READ_USER_RESOURCE, TEST_TOKEN) assert.Nil(t, err) assert.NotNil(t, r) assert.Equal(t, TEST_APPLICATIONS_URL, r.Links.Applications.Href) r, err = client.readUserResource(URL_INVALID, TEST_TOKEN) assert.NotNil(t, err) assert.Nil(t, r) }) t.Run("test validateResponse", func(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, } err := client.validateResponse(resp) assert.NoError(t, err) resp = &http.Response{ StatusCode: http.StatusCreated, } err = client.validateResponse(resp) assert.NoError(t, err) resp = &http.Response{ Status: strconv.Itoa(http.StatusInternalServerError) + " " + http.StatusText(http.StatusInternalServerError), StatusCode: http.StatusInternalServerError, Body: ioutil.NopCloser(bytes.NewBufferString("test body")), } err = client.validateResponse(resp) assert.Equal( t, "Bad response received. Status: 500 Internal Server Error. Doesn't have X-Ms-Diagnostics header. "+ "Response body: test body. ", err.Error()) resp = &http.Response{ Status: strconv.Itoa(http.StatusInternalServerError) + " " + http.StatusText(http.StatusInternalServerError), StatusCode: http.StatusInternalServerError, Body: ioutil.NopCloser(bytes.NewBufferString("")), } err = client.validateResponse(resp) assert.Equal( t, "Bad response received. Status: 500 Internal Server Error. Doesn't have X-Ms-Diagnostics header. "+ "Doesn't have body. ", err.Error()) }) } func setupTestServer(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc(URL_AUTHENTICATE, func(writer http.ResponseWriter, request *http.Request) { writeResponse(t, writer, `{"access_token": "`+TEST_TOKEN+`"}`) }) mux.HandleFunc(URL_AUTHENTICATE_FAILING, func(writer http.ResponseWriter, request *http.Request) { writer.Header().Set("X-Ms-Diagnostics", "wrong credentials") writer.WriteHeader(http.StatusForbidden) }) mux.HandleFunc(URL_CREATE_NEW_APP, func(writer http.ResponseWriter, request *http.Request) { writeResponse(t, writer, ` { "_embedded": { "onlineMeetings": { "_links": { "myOnlineMeetings": { "href": "`+TEST_MY_ONLINE_MEETINGS_URL+`" } } } } } `) }) mux.HandleFunc(URL_CREATE_NEW_APP_FAILING, func(writer http.ResponseWriter, request *http.Request) { writer.Header().Set("X-Ms-Diagnostics", "something went wrong") writer.WriteHeader(http.StatusInternalServerError) }) mux.HandleFunc(URL_CREATE_NEW_MEETING, func(writer http.ResponseWriter, request *http.Request) { writeResponse(t, writer, ` { "onlineMeetingId": "`+TEST_ONLINE_MEETING_ID+`", "joinUrl": "`+TEST_JOIN_URL+`" } `) }) mux.HandleFunc(URL_PERFORM_DISCOVERY, func(writer http.ResponseWriter, request *http.Request) { writeResponse(t, writer, ` { "_links": { "user": { "href": "`+TEST_USER_URL+`" } } } `) }) mux.HandleFunc(URL_RESPONSE_WITH_AUTH_HEADER, func(writer http.ResponseWriter, request *http.Request) { writer.Header().Set("WWW-AUTHENTICATE", TEST_AUTH_HEADER) writer.WriteHeader(http.StatusOK) }) mux.HandleFunc(URL_RESPONSE_WITHOUT_AUTH_HEADER, func(writer http.ResponseWriter, request *http.Request) { writer.WriteHeader(http.StatusOK) }) mux.HandleFunc(URL_READ_USER_RESOURCE, func(writer http.ResponseWriter, request *http.Request) { writeResponse(t, writer, ` { "_links": { "applications": { "href": "`+TEST_APPLICATIONS_URL+`", "revision": "2" } } } `) }) apiHandler := http.NewServeMux() apiHandler.Handle("/", mux) server = httptest.NewServer(apiHandler) } func writeResponse(t *testing.T, writer http.ResponseWriter, response string) { writer.WriteHeader(http.StatusOK) _, err := writer.Write([]byte(response)) if err != nil { t.Fatal(err) } } func teardown() { server.Close() }
package parser import "testing" var omegaResults01 = []string{ " ETA1 ETA2", "", " ETA1", "+ 1.23E-01", "", " ETA2", "+ 0.00E+00 1.54E-01", } var omegaResults01Parsed = []string{ "1.23E-01", "0.00E+00", "1.54E-01", } func TestParseOmegaResultsBlock(t *testing.T) { parsedData := ParseOmegaResults(omegaResults01) for i, val := range parsedData { if val != omegaResults01Parsed[i] { t.Log("GOT: ", val, " EXPECTED: ", omegaResults01Parsed[i]) t.Fail() } } }
package server import ( "context" "log" "net/http" "time" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/rbonnat/blockchain-in-go/server/controller" "github.com/rbonnat/blockchain-in-go/service" ) // Run Initialize router and launch http server func Run(ctx context.Context, port string) error { r := chi.NewRouter() // Middleware r.Use(middleware.RequestID) r.Use(middleware.Logger) r.Use(middleware.Recoverer) // Initialize services s := service.New(ctx, time.Now) // Initialize routes r.Get("/", controller.HandleGetBlockchain(s)) r.Post("/", controller.HandleWriteBlock(s)) // Launch http server log.Printf("Server listening on port: '%s'", port) err := http.ListenAndServe(":"+port, r) if err != nil { log.Printf("Cannot launch http server: '%v'", err) } return err }
package relay import ( "fmt" "github.com/karalabe/hid" "runtime" ) const ( OFF = iota ON ) type IoStatus int const ( C1 = iota + 1 C2 C3 C4 C5 C6 C7 C8 ALL ) type ChannelNumber int type ChannelStatus struct { Channel_1 IoStatus Channel_2 IoStatus Channel_3 IoStatus Channel_4 IoStatus Channel_5 IoStatus Channel_6 IoStatus Channel_7 IoStatus Channel_8 IoStatus } type Relay struct { info *hid.DeviceInfo dev *hid.Device } func List() []*Relay { list := make([]*Relay, 0, 5) relayInfos := hid.Enumerate(0x16C0, 0x05DF) if len(relayInfos) <= 0 { return list } for i, info := range relayInfos { relay, err := info.Open() if err == nil { list = append(list, &Relay{info: &relayInfos[i]}) relay.Close() } } return list } func (this *Relay) Open() error { dev, err := this.info.Open() if err == nil { this.dev = dev } return err } func (this *Relay) Close() error { return this.dev.Close() } func (this *Relay) setIO(s IoStatus, no ChannelNumber) error { cmd := make([]byte, 9) cmd[0] = 0x0 if no < C1 && no > ALL { return fmt.Errorf("channel number (%d) is illegal", no) } if no == ALL { if s == ON { cmd[1] = 0xFE } else { cmd[1] = 0xFC } } else { if s == ON { cmd[1] = 0xFF } else { cmd[1] = 0xFD } cmd[2] = byte(no) } _, err := this.dev.SendFeatureReport(cmd) return err } func (this *Relay) GetStatus() (*ChannelStatus, error) { cmd := make([]byte, 9) _, err := this.dev.GetFeatureReport(cmd) if err != nil { return nil, err } // Remove HID report ID on Windows, others OSes don't need it. if runtime.GOOS == "windows" { cmd = cmd[1:] } status := &ChannelStatus{} status.Channel_1 = IoStatus(cmd[7] >> 0 & 0x01) status.Channel_2 = IoStatus(cmd[7] >> 1 & 0x01) status.Channel_3 = IoStatus(cmd[7] >> 2 & 0x01) status.Channel_4 = IoStatus(cmd[7] >> 3 & 0x01) status.Channel_5 = IoStatus(cmd[7] >> 4 & 0x01) status.Channel_6 = IoStatus(cmd[7] >> 5 & 0x01) status.Channel_7 = IoStatus(cmd[7] >> 6 & 0x01) status.Channel_8 = IoStatus(cmd[7] >> 7 & 0x01) return status, err } func (this *Relay) TurnOn(num ChannelNumber) error { return this.setIO(ON, num) } func (this *Relay) TurnOff(num ChannelNumber) error { return this.setIO(OFF, num) } func (this *Relay) TurnAllOn() error { return this.setIO(ON, ALL) } func (this *Relay) TurnAllOff() error { return this.setIO(OFF, ALL) } func (this *Relay) SetSN(sn string) error { if len(sn) > 5 { return fmt.Errorf("The length of `%s` is large than 5 bytes.", sn) } cmd := make([]byte, 9) cmd[0] = 0x00 cmd[1] = 0xFA copy(cmd[2:], sn) _, err := this.dev.SendFeatureReport(cmd) if err != nil { return err } return err } func (this *Relay) GetSN() (string, error) { cmd := make([]byte, 9) _, err := this.dev.GetFeatureReport(cmd) var sn string if err != nil { sn = "" } else { // Remove HID report ID on Windows, others OSes don't need it. if runtime.GOOS == "windows" { cmd = cmd[1:] } sn = string(cmd[:5]) } return sn, err }
package main import ( "fmt" "html/template" "net/http" "github.com/julienschmidt/httprouter" "github.com/paulsumit5555/gowebdevlopment/mvc/controller" "gopkg.in/mgo.v2" ) var tpl *template.Template func init() { tpl = template.Must(template.ParseGlob("view/*")) } func main() { router := httprouter.New() uc := controller.GetUserController(tpl, getSession()) fmt.Println(uc) router.GET("/home", uc.Home) router.GET("/add", uc.Add) router.POST("/submit", uc.Submit) err := http.ListenAndServe("localhost:9090", router) if err != nil { fmt.Println(err) } } func getSession() *mgo.Session { s, err := mgo.Dial("mongodb://localhost") if err != nil { fmt.Println("error while creating connection ", err) panic(err) } return s }
package main import ( "flag" "fmt" "io/ioutil" "os" "strconv" "strings" ) const ( PrintColor = "\033[38;5;%dm%s\033[39;49m" ) func main() { if len(os.Args) < 2 { fmt.Println("Expected argument(you can set it's color and colored indexes or letters)") os.Exit(1) } else { str := os.Args[1] var indexArr []int var argColor *string indexOfColoredLetter := "" if len(os.Args) >= 3 && os.Args[2][:7] == "--color" { argCmd := flag.NewFlagSet(str, flag.ExitOnError) argColor = argCmd.String("color", "white", "color in string") argCmd.Parse(os.Args[2:]) if len(os.Args) >= 4 { indexOfColoredLetter = argCmd.Arg(0) } if indexOfColoredLetter == "" { for i := range str { indexArr = append(indexArr, i) } } else { indexArr = IndexOfColoredLetter(str, indexOfColoredLetter) if indexArr == nil { os.Exit(1) } } //fmt.Println(*argColor) //fmt.Println(indexOfColoredLetter) //fmt.Println(indexArr) //return } // "\n" handling splittwo := string(byte(92)) + string(byte(110)) words := strings.Split(str, splittwo) // read from file fileName := "standard.txt" file, err := os.Open(fileName) if err != nil { fmt.Println(err.Error()) os.Exit(0) } defer file.Close() rawBytes, err := ioutil.ReadAll(file) if err != nil { panic(err) } lines := strings.Split(string(rawBytes), "\n") //print string to terminal for _, word := range words { for h := 0; h < 9; h++ { for indexLetter, l := range []byte(word) { flagPrint := false if indexArr != nil { for _, indx := range indexArr { if indx == indexLetter { flagPrint = true } } for i, line := range lines { if i == (int(l)-32)*9+h { if flagPrint == true { fmt.Printf(PrintColor, Color(*argColor), line) } else { fmt.Printf(PrintColor, 7, line) } } } } } fmt.Println() } } if Color(*argColor) == 7 { fmt.Printf("Please use this colors:\n") fmt.Printf(PrintColor, 1, "red\n") fmt.Printf(PrintColor, 2, "green\n") fmt.Printf(PrintColor, 3, "yellow\n") fmt.Printf(PrintColor, 4, "blue\n") fmt.Printf(PrintColor, 5, "purple\n") fmt.Printf(PrintColor, 6, "magenta\n") fmt.Printf(PrintColor, 7, "white\n") fmt.Printf(PrintColor, 130, "orange\n") } } } func IndexOfColoredLetter(s string, colorStr string) []int { flagWord := false var indexArr []int for i, letter := range []byte(s) { if letter == colorStr[0] { lenColor := 0 j := i for _, l := range []byte(colorStr) { if s[j] == l { lenColor++ } j++ } if lenColor == len(colorStr) { flagWord = true for k := i; k < i+len(colorStr); k++ { indexArr = append(indexArr, k) } return indexArr } } } if flagWord == false { indexStart := 0 indexEnd := len(s) - 1 index, err := strconv.Atoi(colorStr) if err == nil { indexArr = append(indexArr, index) } else { flagFormat := false for i, l := range colorStr { if l == ':' { flagFormat = true if i-1 < 0 && i+1 < len(colorStr) { indexEnd1, err2 := strconv.Atoi(colorStr[i+1:]) indexEnd = indexEnd1 if err2 != nil { fmt.Printf("Parse error: Please provide with last index of letters to be colored in format: \":number\"") return indexArr } } else if i-1 >= 0 && i+1 >= len(colorStr) { indexStart1, err1 := strconv.Atoi(colorStr[:i]) indexStart = indexStart1 if err1 != nil { fmt.Printf("Parse error: Please provide with first index of letters to be colored in format: \"number:\"\n") return indexArr } } else if i-1 >= 0 && i+1 < len(colorStr) { indexStart1, err1 := strconv.Atoi(colorStr[:i]) indexEnd1, err2 := strconv.Atoi(colorStr[i+1:]) indexStart = indexStart1 indexEnd = indexEnd1 if err1 != nil || err2 != nil { fmt.Printf("Parse error: Please provide with first and last indexes of letters to be colored in format: \"number:number\"\n") return indexArr } } else { fmt.Printf("Parse error: Please provide with first or/and last indexes of letters to be colored in format: \"number:number\"\n") return indexArr } for i := indexStart; i <= indexEnd; i++ { indexArr = append(indexArr, i) } break } else if l == ',' { flagFormat = true indexes := strings.Split(colorStr, ",") for _, v := range indexes { i, err := strconv.Atoi(v) if err == nil { indexArr = append(indexArr, i) } else { fmt.Printf("Parse error: Please provide with indexes of letters to be colored in format: \"number,number,number...\"\n") return indexArr } } break } } if flagFormat == false { fmt.Printf("Error format: Please provide letters or indexes as in exapmle: 4:6; 1:; :5; 5,6,4,2; 11, etc.\n") return indexArr } } } return indexArr } func Color(s string) int { switch s { case "blue": return 4 case "green": return 2 case "red": return 1 case "yellow": return 3 case "purple": return 5 case "magenta": return 6 case "orange": return 130 default: num, err := strconv.Atoi(s) if err != nil { return 7 } return num } }
package main import ( "context" "flag" "fmt" "github.com/jackc/pgx/v4/pgxpool" "github.com/teploff/otus/calendar/config" "github.com/teploff/otus/calendar/infrastructure/logger" "github.com/teploff/otus/calendar/internal" "go.uber.org/zap" "os" "os/signal" "syscall" ) var ( configFile = flag.String("config", "./init/config_dev.yaml", "configuration file path") dev = flag.Bool("dev", true, "dev mode") ) func main() { flag.Parse() cfg, err := config.LoadFromFile(*configFile) if err != nil { panic(err) } zapLogger := logger.New(*dev, &cfg.Logger) dsn := fmt.Sprintf("user=%s password=%s host=%s port=%d dbname=%s sslmode=%s pool_max_conns=%d", cfg.Db.Username, cfg.Db.Password, cfg.Db.Host, cfg.Db.Port, cfg.Db.Name, cfg.Db.SSLMode, cfg.Db.MaxConn) pool, err := pgxpool.Connect(context.Background(), dsn) if err != nil { zapLogger.Fatal("postgres connection error: ", zap.Error(err)) } defer pool.Close() app := internal.NewApp(cfg, internal.WithLogger(zapLogger), internal.WithConnPool(pool), ) go app.Run() done := make(chan os.Signal, 1) signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-done app.Stop() }
package main import ( "database/sql" "fmt" // this is needed because init() function needs to be called in pq package _ "github.com/lib/pq" ) const ( host = "localhost" port = 5432 user = "postgres" password = "testtest" dbName = "postgres" ) func main() { var dbConnection string dbConnection = fmt.Sprintf("host=%v port=%v user=%v password=%v dbname=%v sslmode=disable", host, port, user, password, dbName) db, err := sql.Open("postgres", dbConnection) if err != nil { panic(err) } defer db.Close() //_, err = db.Exec(`INSERT INTO USERS(age, email, first_name, last_name) VALUES (30, 'domen@skamlic.com', 'Domen', 'Skamlic');`) //if err != nil { // panic(err) //} var id int err = db.QueryRow(`SELECT id FROM users WHERE email = $1 AND age > $2;`, "domen@skamlic.com", 16).Scan(&id) if err != nil { panic(err) } fmt.Println(id) rows, err := db.Query(`SELECT id FROM users WHERE email = $1 AND age > $2;`, "domen@skamlic.com", 16) if err != nil { panic(err) } fmt.Println(rows) }
package rancher import ( "errors" "fmt" "io" "strings" "sync" "golang.org/x/net/context" "github.com/sirupsen/logrus" "github.com/docker/docker/api/types/container" "github.com/docker/libcompose/config" "github.com/docker/libcompose/docker/service" "github.com/docker/libcompose/labels" "github.com/docker/libcompose/project" "github.com/docker/libcompose/project/events" "github.com/docker/libcompose/project/options" "github.com/gorilla/websocket" "github.com/rancher/go-rancher/hostaccess" "github.com/rancher/go-rancher/v2" rUtils "github.com/ouzklcn/rancher-compose/utils" ) type Link struct { ServiceName, Alias string } type IsDone func(*client.Resource) (bool, error) type ContainerInspect struct { Name string Config *container.Config HostConfig *container.HostConfig } type RancherService struct { name string serviceConfig *config.ServiceConfig context *Context } func (r *RancherService) Name() string { return r.name } func (r *RancherService) Config() *config.ServiceConfig { return r.serviceConfig } func (r *RancherService) Context() *Context { return r.context } func (r *RancherService) RancherConfig() RancherConfig { if config, ok := r.context.RancherConfig[r.name]; ok { return config } return RancherConfig{} } func NewService(name string, config *config.ServiceConfig, context *Context) *RancherService { return &RancherService{ name: name, serviceConfig: config, context: context, } } func (r *RancherService) RancherService() (*client.Service, error) { return r.FindExisting(r.name) } func (r *RancherService) Create(ctx context.Context, options options.Create) error { service, err := r.FindExisting(r.name) if err == nil && service == nil { service, err = r.createService() } else if err == nil && service != nil { err = r.setupLinks(service, service.State == "inactive") } return err } func (r *RancherService) Start(ctx context.Context) error { return r.up(false) } func (r *RancherService) Up(ctx context.Context, options options.Up) error { return r.up(true) } func (r *RancherService) Build(ctx context.Context, buildOptions options.Build) error { return nil } func (r *RancherService) up(create bool) error { service, err := r.FindExisting(r.name) if err != nil { return err } if r.Context().Rollback { if service == nil { return nil } _, err := r.rollback(service) return err } if service != nil && create && r.shouldUpgrade(service) { if r.context.Pull { if err := r.Pull(context.Background()); err != nil { return err } } if service.State == "upgraded" { service, err = r.context.Client.Service.ActionFinishupgrade(service) if err != nil { return err } err = r.Wait(service) if err != nil { return err } } service, err = r.upgrade(service, r.context.ForceUpgrade, r.context.Args) if err != nil { return err } } if service == nil && !create { return nil } if service == nil { service, err = r.createService() } else { err = r.setupLinks(service, true) } if err != nil { return err } if service.State == "upgraded" && r.context.ConfirmUpgrade { service, err = r.context.Client.Service.ActionFinishupgrade(service) if err != nil { return err } err = r.Wait(service) if err != nil { return err } } if service.State == "active" { return nil } if service.Actions["activate"] != "" { service, err = r.context.Client.Service.ActionActivate(service) err = r.Wait(service) } return err } func (r *RancherService) Stop(ctx context.Context, timeout int) error { service, err := r.FindExisting(r.name) if err == nil && service == nil { return nil } if err != nil { return err } if service.State == "inactive" { return nil } service, err = r.context.Client.Service.ActionDeactivate(service) return r.Wait(service) } func (r *RancherService) Delete(ctx context.Context, options options.Delete) error { service, err := r.FindExisting(r.name) if err == nil && service == nil { return nil } if err != nil { return err } if service.Removed != "" || service.State == "removing" || service.State == "removed" { return nil } err = r.context.Client.Service.Delete(service) if err != nil { return err } return r.Wait(service) } func (r *RancherService) resolveServiceAndStackId(name string) (string, string, error) { parts := strings.SplitN(name, "/", 2) if len(parts) == 1 { return name, r.context.Stack.Id, nil } stacks, err := r.context.Client.Stack.List(&client.ListOpts{ Filters: map[string]interface{}{ "name": parts[0], "removed_null": nil, }, }) if err != nil { return "", "", err } if len(stacks.Data) == 0 { return "", "", fmt.Errorf("Failed to find stack: %s", parts[0]) } return parts[1], stacks.Data[0].Id, nil } func (r *RancherService) FindExisting(name string) (*client.Service, error) { logrus.Debugf("Finding service %s", name) name, stackId, err := r.resolveServiceAndStackId(name) if err != nil { return nil, err } services, err := r.context.Client.Service.List(&client.ListOpts{ Filters: map[string]interface{}{ "stackId": stackId, "name": name, "removed_null": nil, }, }) if err != nil { return nil, err } if len(services.Data) == 0 { return nil, nil } logrus.Debugf("Found service %s", name) return &services.Data[0], nil } func (r *RancherService) Metadata() map[string]interface{} { if config, ok := r.context.RancherConfig[r.name]; ok { return rUtils.NestedMapsToMapInterface(config.Metadata) } return map[string]interface{}{} } func (r *RancherService) HealthCheck(service string) *client.InstanceHealthCheck { if service == "" { service = r.name } if config, ok := r.context.RancherConfig[service]; ok { return config.HealthCheck } return nil } func (r *RancherService) getConfiguredScale() int { scale := 1 if config, ok := r.context.RancherConfig[r.name]; ok { if config.Scale > 0 { scale = int(config.Scale) } } return scale } func (r *RancherService) createService() (*client.Service, error) { logrus.Infof("Creating service %s", r.name) factory, err := GetFactory(r) if err != nil { return nil, err } if err := factory.Create(r); err != nil { return nil, err } service, err := r.FindExisting(r.name) if err != nil { return nil, err } if err := r.setupLinks(service, true); err != nil { return nil, err } err = r.Wait(service) return service, err } func (r *RancherService) setupLinks(service *client.Service, update bool) error { // Don't modify links for selector based linking, don't want to conflict // Don't modify links for load balancers, they're created by cattle if service.SelectorLink != "" || FindServiceType(r) == ExternalServiceType || FindServiceType(r) == LbServiceType { return nil } existingLinks, err := r.context.Client.ServiceConsumeMap.List(&client.ListOpts{ Filters: map[string]interface{}{ "serviceId": service.Id, }, }) if err != nil { return err } if len(existingLinks.Data) > 0 && !update { return nil } links, err := r.getServiceLinks() _, err = r.context.Client.Service.ActionSetservicelinks(service, &client.SetServiceLinksInput{ ServiceLinks: links, }) return err } func (r *RancherService) SelectorContainer() string { return r.serviceConfig.Labels["io.rancher.service.selector.container"] } func (r *RancherService) SelectorLink() string { return r.serviceConfig.Labels["io.rancher.service.selector.link"] } func (r *RancherService) getServiceLinks() ([]client.ServiceLink, error) { links, err := r.getLinks() if err != nil { return nil, err } result := []client.ServiceLink{} for link, id := range links { result = append(result, client.ServiceLink{ Name: link.Alias, ServiceId: id, }) } return result, nil } func (r *RancherService) getLinks() (map[Link]string, error) { result := map[Link]string{} for _, link := range append(r.serviceConfig.Links, r.serviceConfig.ExternalLinks...) { parts := strings.SplitN(link, ":", 2) name := parts[0] alias := "" if len(parts) == 2 { alias = parts[1] } name = strings.TrimSpace(name) alias = strings.TrimSpace(alias) linkedService, err := r.FindExisting(name) if err != nil { return nil, err } if linkedService == nil { if _, ok := r.context.Project.ServiceConfigs.Get(name); !ok { logrus.Warnf("Failed to find service %s to link to", name) } } else { result[Link{ ServiceName: name, Alias: alias, }] = linkedService.Id } } return result, nil } func (r *RancherService) Scale(ctx context.Context, count int, timeout int) error { service, err := r.FindExisting(r.name) if err != nil { return err } if service == nil { return fmt.Errorf("Failed to find %s to scale", r.name) } service, err = r.context.Client.Service.Update(service, map[string]interface{}{ "scale": count, }) if err != nil { return err } return r.Wait(service) } func (r *RancherService) Containers(ctx context.Context) ([]project.Container, error) { result := []project.Container{} containers, err := r.containers() if err != nil { return nil, err } for _, c := range containers { name := c.Name if name == "" { name = c.Uuid } result = append(result, NewContainer(c.Id, name)) } return result, nil } func (r *RancherService) containers() ([]client.Container, error) { service, err := r.FindExisting(r.name) if err != nil { return nil, err } var instances client.ContainerCollection err = r.context.Client.GetLink(service.Resource, "instances", &instances) if err != nil { return nil, err } return instances.Data, nil } func (r *RancherService) Restart(ctx context.Context, timeout int) error { service, err := r.FindExisting(r.name) if err != nil { return err } if service == nil { return fmt.Errorf("Failed to find %s to restart", r.name) } service, err = r.context.Client.Service.ActionRestart(service, &client.ServiceRestart{ RollingRestartStrategy: client.RollingRestartStrategy{ BatchSize: r.context.BatchSize, IntervalMillis: r.context.Interval, }, }) if err != nil { logrus.Errorf("Failed to restart %s: %v", r.Name(), err) return err } return r.Wait(service) } func (r *RancherService) Log(ctx context.Context, follow bool) error { service, err := r.FindExisting(r.name) if err != nil || service == nil { return err } if service.Type != "service" { return nil } containers, err := r.containers() if err != nil { logrus.Errorf("Failed to list containers to log: %v", err) return err } for _, container := range containers { websocketClient := (*hostaccess.RancherWebsocketClient)(r.context.Client) conn, err := websocketClient.GetHostAccess(container.Resource, "logs", nil) if err != nil { logrus.Errorf("Failed to get logs for %s: %v", container.Name, err) continue } go r.pipeLogs(&container, conn) } return nil } func (r *RancherService) pipeLogs(container *client.Container, conn *websocket.Conn) { defer conn.Close() log_name := strings.TrimPrefix(container.Name, r.context.ProjectName+"_") logger := r.context.LoggerFactory.CreateContainerLogger(log_name) for { messageType, bytes, err := conn.ReadMessage() if err == io.EOF { return } else if err != nil { logrus.Errorf("Failed to read log: %v", err) return } if messageType != websocket.TextMessage || len(bytes) <= 3 { continue } if bytes[len(bytes)-1] != '\n' { bytes = append(bytes, '\n') } message := bytes[3:] if "01" == string(bytes[:2]) { logger.Out(message) } else { logger.Err(message) } } } func (r *RancherService) DependentServices() []project.ServiceRelationship { result := []project.ServiceRelationship{} for _, rel := range service.DefaultDependentServices(r.context.Project, r) { if rel.Type == project.RelTypeLink { rel.Optional = true result = append(result, rel) } } // Load balancers should depend on non-external target services lbConfig := r.RancherConfig().LbConfig if lbConfig != nil { for _, portRule := range lbConfig.PortRules { if portRule.Service != "" && !strings.Contains(portRule.Service, "/") { result = append(result, project.NewServiceRelationship(portRule.Service, project.RelTypeLink)) } } } return result } func (r *RancherService) Client() *client.RancherClient { return r.context.Client } func (r *RancherService) Kill(ctx context.Context, signal string) error { return project.ErrUnsupported } func (r *RancherService) Info(ctx context.Context) (project.InfoSet, error) { return project.InfoSet{}, project.ErrUnsupported } func (r *RancherService) pullImage(image string, labels map[string]string) error { taskOpts := &client.PullTask{ Mode: "all", Labels: rUtils.ToMapInterface(labels), Image: image, } if r.context.PullCached { taskOpts.Mode = "cached" } task, err := r.context.Client.PullTask.Create(taskOpts) if err != nil { return err } printed := map[string]string{} lastMessage := "" r.WaitFor(&task.Resource, task, func() string { if task.TransitioningMessage != "" && task.TransitioningMessage != "In Progress" && task.TransitioningMessage != lastMessage { printStatus(task.Image, printed, task.Status) lastMessage = task.TransitioningMessage } return task.Transitioning }) if task.Transitioning == "error" { return errors.New(task.TransitioningMessage) } if !printStatus(task.Image, printed, task.Status) { return errors.New("Pull failed on one of the hosts") } logrus.Infof("Finished pulling %s", task.Image) return nil } func (r *RancherService) Pull(ctx context.Context) (err error) { config := r.Config() if config.Image == "" || FindServiceType(r) != RancherType { return } toPull := map[string]bool{config.Image: true} labels := config.Labels if secondaries, ok := r.context.SidekickInfo.primariesToSidekicks[r.name]; ok { for _, secondaryName := range secondaries { serviceConfig, ok := r.context.Project.ServiceConfigs.Get(secondaryName) if !ok { continue } labels = rUtils.MapUnion(labels, serviceConfig.Labels) if serviceConfig.Image != "" { toPull[serviceConfig.Image] = true } } } wg := sync.WaitGroup{} for image := range toPull { wg.Add(1) go func(image string) { if pErr := r.pullImage(image, labels); pErr != nil { err = pErr } wg.Done() }(image) } wg.Wait() return } func (r *RancherService) Pause(ctx context.Context) error { return project.ErrUnsupported } func (r *RancherService) Unpause(ctx context.Context) error { return project.ErrUnsupported } func (r *RancherService) Down() error { return project.ErrUnsupported } func (r *RancherService) Events(ctx context.Context, messages chan events.ContainerEvent) error { return project.ErrUnsupported } func (r *RancherService) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) { return 0, project.ErrUnsupported } func (r *RancherService) RemoveImage(ctx context.Context, imageType options.ImageType) error { return project.ErrUnsupported } func appendHash(service *RancherService, existingLabels map[string]interface{}) (map[string]interface{}, error) { ret := map[string]interface{}{} for k, v := range existingLabels { ret[k] = v } hashValue := "" //, err := hash(service) //if err != nil { //return nil, err //} ret[labels.HASH.Str()] = hashValue return ret, nil } func printStatus(image string, printed map[string]string, current map[string]interface{}) bool { good := true for host, objStatus := range current { status, ok := objStatus.(string) if !ok { continue } v := printed[host] if status != "Done" { good = false } if v == "" { logrus.Infof("Checking for %s on %s...", image, host) v = "start" } else if printed[host] == "start" && status == "Done" { logrus.Infof("Finished %s on %s", image, host) v = "done" } else if printed[host] == "start" && status != "Pulling" && status != v { logrus.Infof("Checking for %s on %s: %s", image, host, status) v = status } printed[host] = v } return good }
package main import ( "fmt" "log" "net/http" ) func helloHandler2(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, web 2") } func main() { mux := http.NewServeMux() // 输入地址为:http://localhost:8080/ mux.Handle("/", &myHandle2{}) // 输入地址为:http://localhost:8080/hello mux.HandleFunc("/hello", helloHandler2) log.Println("Start server and listen on 8080") if err := http.ListenAndServe(":8080", mux); err != nil { log.Fatal(err) } } type myHandle2 struct{} func (*myHandle2) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Welcome Server 2: "+r.URL.String()) }
package controller import ( "github.com/Masterminds/semver" "github.com/kyma-project/helm-broker/internal" "github.com/kyma-project/helm-broker/internal/addon" "github.com/kyma-project/helm-broker/internal/addon/provider" "k8s.io/helm/pkg/proto/hapi/chart" ) //go:generate mockery -name=addonStorage -output=automock -outpkg=automock -case=underscore type addonStorage interface { Get(internal.Namespace, internal.AddonName, semver.Version) (*internal.Addon, error) Upsert(internal.Namespace, *internal.Addon) (replace bool, err error) Remove(internal.Namespace, internal.AddonName, semver.Version) error FindAll(internal.Namespace) ([]*internal.Addon, error) } //go:generate mockery -name=chartStorage -output=automock -outpkg=automock -case=underscore type chartStorage interface { Upsert(internal.Namespace, *chart.Chart) (replace bool, err error) Remove(internal.Namespace, internal.ChartName, semver.Version) error } //go:generate mockery -name=addonGetterFactory -output=automock -outpkg=automock -case=underscore type addonGetterFactory interface { NewGetter(rawURL, instPath string) (provider.AddonClient, error) } //go:generate mockery -name=addonGetter -output=automock -outpkg=automock -case=underscore type addonGetter interface { Cleanup() error GetCompleteAddon(entry addon.EntryDTO) (addon.CompleteAddon, error) GetIndex() (*addon.IndexDTO, error) } //go:generate mockery -name=brokerFacade -output=automock -outpkg=automock -case=underscore type brokerFacade interface { Create(ns string) error Exist(ns string) (bool, error) Delete(ns string) error } //go:generate mockery -name=docsProvider -output=automock -outpkg=automock -case=underscore type docsProvider interface { EnsureDocsTopic(addon *internal.Addon, namespace string) error EnsureDocsTopicRemoved(id string, namespace string) error } //go:generate mockery -name=brokerSyncer -output=automock -outpkg=automock -case=underscore type brokerSyncer interface { SyncServiceBroker(namespace string) error } //go:generate mockery -name=clusterBrokerFacade -output=automock -outpkg=automock -case=underscore type clusterBrokerFacade interface { Create() error Exist() (bool, error) Delete() error } //go:generate mockery -name=clusterDocsProvider -output=automock -outpkg=automock -case=underscore type clusterDocsProvider interface { EnsureClusterDocsTopic(addon *internal.Addon) error EnsureClusterDocsTopicRemoved(id string) error } //go:generate mockery -name=clusterBrokerSyncer -output=automock -outpkg=automock -case=underscore type clusterBrokerSyncer interface { Sync() error } type docsFacade interface { clusterDocsProvider docsProvider }
/* Copyright 2022 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mods import ( "context" "fmt" "os" "strings" "time" "github.com/kubevela/pkg/util/singleton" "github.com/oam-dev/kubevela/apis/types" "github.com/oam-dev/kubevela/pkg/utils/common" "github.com/oam-dev/kubevela/references/docgen" ) const ( // ComponentDefRefPath is the target path for kubevela.io component ref docs ComponentDefRefPath = "../kubevela.io/docs/end-user/components/references.md" // ComponentDefRefPathZh is the target path for kubevela.io component ref docs in Chinese ComponentDefRefPathZh = "../kubevela.io/i18n/zh/docusaurus-plugin-content-docs/current/end-user/components/references.md" ) // ComponentDefDirs store inner CUE definition var ComponentDefDirs = []string{"./vela-templates/definitions/internal/component/"} // CustomComponentHeaderEN . var CustomComponentHeaderEN = `--- title: Built-in ParsedComponents Type --- This documentation will walk through all the built-in component types sorted alphabetically. ` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339)) // CustomComponentHeaderZH . var CustomComponentHeaderZH = `--- title: 内置组件列表 --- 本文档将**按字典序**展示所有内置组件的参数列表。 ` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc)自动生成,请勿手动修改,上次更新于 %s。\n\n", time.Now().Format(time.RFC3339)) // ComponentDef generate component def reference doc func ComponentDef(ctx context.Context, c common.Args, opt Options) { if len(opt.DefDirs) == 0 { opt.DefDirs = ComponentDefDirs } ref := &docgen.MarkdownReference{ AllInOne: true, ForceExample: opt.ForceExamples, Filter: func(capability types.Capability) bool { if capability.Type != types.TypeComponentDefinition || capability.Category != types.CUECategory { return false } if capability.Labels != nil && (capability.Labels[types.LabelDefinitionHidden] == "true" || capability.Labels[types.LabelDefinitionDeprecated] == "true") { return false } // only print capability which contained in cue def for _, dir := range opt.DefDirs { files, err := os.ReadDir(dir) if err != nil { fmt.Println("read dir err", opt.DefDirs, err) return false } for _, f := range files { if strings.Contains(f.Name(), capability.Name) { return true } } } return false }, CustomDocHeader: CustomComponentHeaderEN, } ref.Local = &docgen.FromLocal{Paths: ComponentDefDirs} ref.Client = singleton.KubeClient.Get() if opt.Path != "" { ref.I18N = &docgen.En if strings.Contains(opt.Location, "zh") || strings.Contains(opt.Location, "chinese") { ref.I18N = &docgen.Zh ref.CustomDocHeader = CustomComponentHeaderZH } if err := ref.GenerateReferenceDocs(ctx, c, opt.Path); err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("component reference docs (%s) successfully generated in %s \n", ref.I18N.Language(), opt.Path) return } if opt.Location == "" || opt.Location == "en" { ref.I18N = &docgen.En if err := ref.GenerateReferenceDocs(ctx, c, ComponentDefRefPath); err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("component reference docs (%s) successfully generated in %s \n", ref.I18N.Language(), ComponentDefRefPath) } if opt.Location == "" || opt.Location == "zh" { ref.I18N = &docgen.Zh ref.CustomDocHeader = CustomComponentHeaderZH if err := ref.GenerateReferenceDocs(ctx, c, ComponentDefRefPathZh); err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("component reference docs (%s) successfully generated in %s \n", ref.I18N.Language(), ComponentDefRefPathZh) } }
package vm func ParseDescriptor(desc string) (string, []string) { i := 0 if desc[i] != '(' { panic("Invalid descriptor: " + desc) } i++; args := make([]string, 0) for desc[i] != ')' { switch (desc[i]) { case 'I': args = append(args, "I") default: panic("Unimplemented arg descriptor symbol: " + desc) } i++; } if desc[i] != ')' { panic("Invlaid descriptor " + desc) } i++; switch (desc[i]) { case 'I': return "I", args default: panic("Unimpelmented return descriptor symbol: " + desc) } }
package xl import "go.uber.org/zap" var Logger *zap.Logger const LogPath = "/var/log/8x8.log" func init() { var err error c := zap.NewProductionConfig() c.OutputPaths = []string{LogPath} c.ErrorOutputPaths = []string{LogPath} c.DisableStacktrace = true c.Level.SetLevel(zap.DebugLevel) Logger, err = c.Build( zap.WithCaller(false), ) if err != nil { panic(err) } } // Info logs info func Info(msg string, f ...zap.Field) { Logger.Info(msg, f...) } func Debug(msg string, f ...zap.Field) { Logger.Debug(msg, f...) } func Error(err error, msg string, f ...zap.Field) { Logger.Error(msg, append(f, zap.String("error", err.Error()))...) }
//author xinbing //time 2018/8/28 14:21 package utilities import ( "testing" "fmt" "math" "math/rand" "time" "strconv" ) func TestRound(t *testing.T) { fmt.Println(Round(3.1334, 2)) fmt.Println(Floor(3.9456, 2)) fmt.Println(Ceil(3.123, 2)) fmt.Println(Round(3.9-0.00001, 6)) fmt.Println(Round(0.999 /10000000,10)) fmt.Println(math.Floor(3.123)) } func TestRound2(t *testing.T) { r := rand.New(rand.NewSource(time.Now().UnixNano())) for { f1 := r.NormFloat64() f1 = math.Abs(f1 / 100.0) f1 = Round(f1 , 6) s := strconv.FormatFloat(f1,'f', -1, 64) if len(s) > 8 { fmt.Println(s) break } } } func TestRound3(t *testing.T) { r := rand.New(rand.NewSource(time.Now().UnixNano())) for { f1 := r.NormFloat64() f1 = math.Abs(f1 / 100.0) s := strconv.FormatFloat(f1, 'f', -1, 64) //ret, _ := strconv.ParseFloat(s, 64) if len(s) > 7 { fmt.Println(s) break } } } func TestCompare(t *testing.T) { fmt.Println(CompareWithScale(0.11,0.11,2)) }
package checkers // Checkers/Draughts var Symbols = map[string]map[string]string{ "black": map[string]string{ "one": "⛀", "two": "⛁", }, "white": map[string]string{ "one": "⛂", "two": "⛃", }, }
package o3e import ( "sync/atomic" "errors" "fmt" ) type wrapperResult uint8 type EmptyType struct{} var Empty = EmptyType{} const ( wrapperSuccess wrapperResult = iota wrapperWait wrapperError ) type Task interface { DepFactors() map[int]EmptyType // memoization may improve performance. Execute() error // TODO Commit // TODO Rollback() } type taskWrapper struct { Task blockCount int32 successCh chan bool } func newTaskWrapper(t Task) *taskWrapper { deps := t.DepFactors() result := &taskWrapper{ t, int32(len(deps)), make(chan bool, 1), } return result } func (w *taskWrapper) execute() (result wrapperResult, err error) { defer func() { rec := recover() if rec != nil { result = wrapperError err = errors.New(fmt.Sprint(rec)) return } }() if atomic.AddInt32(&w.blockCount, -1) == 0 { err = w.Execute() if err != nil { return wrapperError, err } else { return wrapperSuccess, nil } } else { return wrapperWait, nil } }
package web import ( "time" "github.com/dgrijalva/jwt-go" "github.com/gofiber/fiber/v2" "github.com/google/uuid" ) func CreateToken(c *fiber.Ctx, userID uuid.UUID, secret []byte) (string, error) { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["id"] = userID exp := time.Now().Add(time.Hour * 24).Unix() claims["exp"] = exp t, err := token.SignedString(secret) if err != nil { return "", err } c.Cookie(&fiber.Cookie{ Name: "forum-Token", Value: t, Secure: false, HTTPOnly: true, }) return t, nil } func Login(c *fiber.Ctx, userID uuid.UUID, secret []byte) (string, error) { store := sessions.Get(c) store.Set("user_id", userID) token, err := CreateToken(c, userID, []byte("SECRET_KEY")) if err == nil { store.Set("user_token", token) } store.Save() return token, err } func DeleteToken(c *fiber.Ctx) { c.ClearCookie("forum-Token") }
/* * @lc app=leetcode.cn id=226 lang=golang * * [226] 翻转二叉树 */ package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // @lc code=start func invertTree(root *TreeNode) *TreeNode { if root == nil || (root.Left == nil && root.Right == nil) { return root } root.Left = invertTree(root.Left) root.Right = invertTree(root.Right) tmp := root.Left root.Left = root.Right root.Right = tmp return root } // @lc code=end func main() { fmt.Println(invertTree(nil)) }
package skeleton import ( "crypto/ecdsa" "crypto/rand" "testing" "time" "github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/ethereum/go-ethereum/p2p" ) func TestSimulation(t *testing.T) { key, _ := ecdsa.GenerateKey(secp256k1.S256(), rand.Reader) key2, _ := ecdsa.GenerateKey(secp256k1.S256(), rand.Reader) srv1 := SubProtocol{} server1P2P := &p2p.Server{ Config: p2p.Config{ Name: "test1", MaxPeers: 10, ListenAddr: ":8080", PrivateKey: key, Protocols: srv1.Protocol(), }, } if err := server1P2P.Start(); err != nil { t.Fatalf("Could not start server: %v", err) } srv2 := SubProtocol{} server2P2P := &p2p.Server{ Config: p2p.Config{ Name: "test2", MaxPeers: 10, ListenAddr: ":8081", PrivateKey: key2, Protocols: srv2.Protocol(), }, } if err := server2P2P.Start(); err != nil { t.Fatalf("Could not start server: %v", err) } server1P2P.AddPeer(server2P2P.Self()) time.Sleep(time.Second * 10) }
package mailer import ( "bytes" "embed" "html/template" "time" "github.com/go-mail/mail/v2" ) //go:embed "templates" var templateFS embed.FS type Mailer struct { dialer *mail.Dialer sender string } func New(host string, port int, username, password, sender string) Mailer { dialer := mail.NewDialer(host, port, username, password) dialer.Timeout = 5 * time.Second return Mailer{ dialer: dialer, sender: sender, } } func (m Mailer) Send(recipient, templateFile string, data interface{}) error { tmpl, err := template.New("email").ParseFS(templateFS, "templates/"+templateFile) if err != nil { return err } subject := new(bytes.Buffer) err = tmpl.ExecuteTemplate(subject, "subject", data) if err != nil { return err } plainBody := new(bytes.Buffer) err = tmpl.ExecuteTemplate(plainBody, "plainBody", data) if err != nil { return err } htmlBody := new(bytes.Buffer) err = tmpl.ExecuteTemplate(htmlBody, "htmlBody", data) if err != nil { return err } msg := mail.NewMessage() msg.SetHeader("To", recipient) msg.SetHeader("From", m.sender) msg.SetHeader("Subject", subject.String()) msg.SetBody("text/plain", plainBody.String()) msg.AddAlternative("text/html", htmlBody.String()) err = m.dialer.DialAndSend(msg) if err != nil { return err } return nil }
package track import "time" type Delayes interface { Delay() time.Duration }
package dao import ( "fmt" "gf-init/app/model" "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" _ "github.com/lib/pq" ) var DB gdb.DB func GetUsers() { var user model.Users DB = g.DB("default") DB.Table("users").Where("nickname = ?", "1").Scan(&user) fmt.Println(user) }
package atlas import ( "encoding/json" "net/http" "github.com/10gen/realm-cli/internal/utils/api" ) const ( groupsPath = publicAPI + "/groups" ) // Group is an Atlas group type Group struct { ID string `json:"id"` Name string `json:"name"` } type groupResponse struct { Results []Group `json:"results"` } func (c *client) Groups() ([]Group, error) { res, resErr := c.do( http.MethodGet, groupsPath, api.RequestOptions{}, ) if resErr != nil { return nil, resErr } if res.StatusCode != http.StatusOK { return nil, api.ErrUnexpectedStatusCode{"get groups", res.StatusCode} } defer res.Body.Close() var groupRes groupResponse if err := json.NewDecoder(res.Body).Decode(&groupRes); err != nil { return nil, err } return groupRes.Results, nil }
package tests import ( "context" "math/big" "testing" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/ethclient" ) var globalAccountForTesting accounts.Account func TestNewAccount(t *testing.T) { ks := keystore.NewKeyStore("../.geth/keystore", keystore.StandardScryptN, keystore.StandardScryptP) account, err := ks.NewAccount("123456") if err != nil { t.Errorf("Failed to create a new account: %v", err) } _, err = ks.Export(account, "123456", "123456") if err != nil { t.Errorf("Failed to export a new account: %v", err) } t.Logf("Successed created account: %v", account.Address.Hex()) client, err := ethclient.Dial("../.geth/geth.ipc") if err != nil { t.Errorf("Failed to connect to ethereum: %v", err) } balance, err := client.BalanceAt(context.TODO(), account.Address, nil) if err != nil { t.Errorf("Failed to get balance of account: %v", err) } if balance.Cmp(big.NewInt(0)) != 0 { t.Errorf("Exception of BalanceAt address: %v", account.Address.Hex()) } t.Logf("Successed get balance at address: %v\r\n", account.Address.Hex()) }
package gcp_test import ( "errors" "fmt" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/gcp" compute "google.golang.org/api/compute/v1" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Client", func() { var ( computeClient *fakes.GCPComputeClient client gcp.Client ) Describe("ValidateSafeToDelete", func() { BeforeEach(func() { computeClient = &fakes.GCPComputeClient{} client = gcp.NewClientWithInjectedComputeClient(computeClient, "some-project-id", "some-zone") }) Context("when the bosh director is the only vm on the network", func() { var networkName string BeforeEach(func() { networkName = "some-network" directorName := "some-bosh-director" boshString := "bosh" boshInitString := "bosh-init" computeClient.ListInstancesCall.Returns.InstanceList = &compute.InstanceList{ Items: []*compute.Instance{ { Name: directorName, NetworkInterfaces: []*compute.NetworkInterface{ { Network: "some-other-network", }, { Network: fmt.Sprintf("http://some-host/%s", networkName), }, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{ { Key: "deployment", Value: &boshString, }, { Key: "director", Value: &boshInitString, }, }, }, }, { Name: "other-network-vm", NetworkInterfaces: []*compute.NetworkInterface{ { Network: "some-other-network", }, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{}, }, }, }, } }) It("does not return an error ", func() { err := client.ValidateSafeToDelete(networkName, "some-env-id") Expect(err).NotTo(HaveOccurred()) }) }) Context("when instances other than bosh director exist in network", func() { var ( networkName string vmName string deploymentName string nonBOSHVMName string ) BeforeEach(func() { networkName = "some-network" directorName := "some-bosh-director" deploymentName = "some-deployment" vmName = "some-vm" nonBOSHVMName = "some-non-bosh-vm" boshString := "bosh" boshInitString := "bosh-init" computeClient.ListInstancesCall.Returns.InstanceList = &compute.InstanceList{ Items: []*compute.Instance{ { Name: directorName, NetworkInterfaces: []*compute.NetworkInterface{ { Network: "some-other-network", }, { Network: fmt.Sprintf("http://some-host/%s", networkName), }, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{ { Key: "deployment", Value: &boshString, }, { Key: "director", Value: &boshInitString, }, }, }, }, { Name: vmName, NetworkInterfaces: []*compute.NetworkInterface{ { Network: "some-other-network", }, { Network: fmt.Sprintf("http://some-host/%s", networkName), }, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{ { Key: "deployment", Value: &deploymentName, }, { Key: "director", Value: &directorName, }, }, }, }, { Name: nonBOSHVMName, NetworkInterfaces: []*compute.NetworkInterface{ { Network: "some-other-network", }, { Network: fmt.Sprintf("http://some-host/%s", networkName), }, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{}, }, }, { Name: "other-network-vm", NetworkInterfaces: []*compute.NetworkInterface{ { Network: "some-other-network", }, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{}, }, }, }, } }) It("returns a helpful error message", func() { err := client.ValidateSafeToDelete(networkName, "some-env-id") Expect(err).To(MatchError(fmt.Sprintf(`bbl environment is not safe to delete; vms still exist in network: %s (deployment: %s) %s (not managed by bosh)`, vmName, deploymentName, nonBOSHVMName))) }) }) Context("failure cases", func() { Context("when gcp client list instances fails", func() { BeforeEach(func() { computeClient.ListInstancesCall.Returns.Error = errors.New("fails to list instances") }) It("returns an error", func() { err := client.ValidateSafeToDelete("some-network", "some-env-id") Expect(err).To(MatchError("fails to list instances")) }) }) }) }) })
/* * @lc app=leetcode.cn id=14 lang=golang * * [14] 最长公共前缀 * * https://leetcode-cn.com/problems/longest-common-prefix/description/ * * algorithms * Easy (34.42%) * Likes: 651 * Dislikes: 0 * Total Accepted: 108.3K * Total Submissions: 314.8K * Testcase Example: '["flower","flow","flight"]' * * 编写一个函数来查找字符串数组中的最长公共前缀。 * * 如果不存在公共前缀,返回空字符串 ""。 * * 示例 1: * * 输入: ["flower","flow","flight"] * 输出: "fl" * * * 示例 2: * * 输入: ["dog","racecar","car"] * 输出: "" * 解释: 输入不存在公共前缀。 * * * 说明: * * 所有输入只包含小写字母 a-z 。 * */ func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } lengthmin := len(strs[0]) var min string for _, i := range strs { if len(i) <= lengthmin { lengthmin = len(i) min = i } } var minstring []string for i := len(min); i > 0; i-- { minstring = append(minstring, min[0:i]) } for _, i := range minstring { flag := 0 for _, j := range strs { if i != j[0:len(i)] { flag = 1 break } } if flag == 0 { return i } } return "" }
package main import ( "fmt" "math" ) func main() { fmt.Println("Máximo = ", math.Max(float64(5), float64(6))) fmt.Println("Mínimo = ", math.Min(float64(5), float64(6))) fmt.Println("Potência = ", math.Pow(3, 2)) }
// Programas executáveis iniciam pelo pacote main package main /* Os programas em GO são organizados em pacotes e pada utiliza-los é necessário declarar um ou vários imports */ import "fmt" // A porta de entrada de um programa Go é a função main func main() { fmt.Print("Primeiro") fmt.Print(" Programa") }
/* This! is an RGB colour grid... Basic RGB grid Basically it's a 2-dimensional matrix in which: The first row, and the first column, are red. The second row, and the second column, are green. The third row, and the third column, are blue. Here are the colours described graphically, using the letters R, G, and B. row and column diagram Here's how we calculate the colour of each space on the grid is calculated. Red + Red = Red (#FF0000) Green + Green = Green (#00FF00) Blue + Blue = Blue (#0000FF) Red + Green = Yellow (#FFFF00) Red + Blue = Purple (#FF00FF) Green + Blue = Teal (#00FFFF) The Challenge Write code to generate an RGB colour grid. It's code golf, so attempt to do so in the smallest number of bytes. Use any programming language or markup language to generate your grid. Things I care about: The result should graphically display an RGB grid with the defined colours. Things I don't care about: If the output is an image, HTML, SVG or other markup. The size or shape of the colour blocks. Borders, spacing etc between or around the blocks. It definitely doesn't have to have labels telling you what the row and column colours should be. */ package main import ( "image" "image/color" "image/draw" "image/png" "os" ) func main() { m := gen(600, 600) png.Encode(os.Stdout, m) } func gen(w, h int) *image.RGBA { tab := [3][3]color.RGBA{ {red, yellow, purple}, {yellow, green, teal}, {purple, teal, blue}, } s := min(w, h) / 3 m := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < 3; y++ { for x := 0; x < 3; x++ { r := image.Rect(x*s, y*s, (x+1)*s, (y+1)*s) draw.Draw(m, r, image.NewUniform(color.Black), image.ZP, draw.Src) r = r.Inset(2) draw.Draw(m, r, image.NewUniform(tab[y][x]), image.ZP, draw.Src) } } return m } func min(a, b int) int { if a < b { return a } return b } var ( red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} yellow = color.RGBA{255, 255, 0, 255} purple = color.RGBA{255, 0, 255, 255} teal = color.RGBA{0, 255, 255, 255} )
package types type Login struct { User string `json:"user"` Password string `json:"password"` } type Member struct { Name string Age int Active bool }
package handler import ( "encoding/json" "net/http" "github.com/krostar/httpw" "github.com/krostar/logger" "github.com/krostar/logger/logmid" ) // DeployFromGithub deploies a r10k environment from a github trigger. func DeployFromGithub(log logger.Logger, usecase DeployUsecases) httpw.HandlerFunc { return func(r *http.Request) (*httpw.R, error) { var ( ctx = r.Context() payload struct { Ref string `json:"ref"` } ) if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { return nil, &httpw.E{ Status: http.StatusBadRequest, Err: err, } } environment := getEnvironmentFromGITRef(payload.Ref) logmid.AddFieldInContext(ctx, "environment", environment) if environment == "" { return &httpw.Response{Status: http.StatusNoContent}, nil } usecase.DeployR10KEnvAsync(ctx, environment, nil, func(environment string, err error) { // called on error log. WithField("environment", environment). WithError(err). Error("r10k deployment failed") }, ) return &httpw.R{Status: http.StatusAccepted}, nil } }
package main import "net/http" func newApiServer() (a *apiServer) { a = &apiServer{ router: http.NewServeMux(), } a.routes() return }
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package types import ( "bytes" "github.com/reed/common/byteutil/byteconv" "github.com/reed/crypto" "github.com/reed/errors" "github.com/reed/vm/vmcommon" ) type TxOutput struct { ID Hash `json:"-"` IsCoinBase bool `json:"isCoinBase"` Address []byte `json:"address"` Amount uint64 `json:"amount"` ScriptPk []byte `json:"scriptPK"` } var ( outpuErr = errors.New("transaction output error") ) func NewTxOutput(isCoinBase bool, address []byte, amount uint64) *TxOutput { o := &TxOutput{ IsCoinBase: isCoinBase, Address: address, Amount: amount, } o.ScriptPk = o.GenerateLockingScript() o.ID = o.GenerateID() return o } func (o *TxOutput) GenerateID() Hash { split := []byte(":") data := bytes.Join([][]byte{ byteconv.BoolToByte(o.IsCoinBase), split, o.Address, split, byteconv.Uint64ToByte(o.Amount), split, o.ScriptPk, }, []byte{}) return BytesToHash(crypto.Sha256(data)) } func (o *TxOutput) GenerateLockingScript() []byte { return vmcommon.BuildP2PKHScript(crypto.Sha256(o.Address)) } func (o *TxOutput) ValidateID() error { expect := o.GenerateID() if !o.ID.HashEqual(expect) { return errors.Wrapf(outpuErr, "ID not equal. expect %x. actual %x.", expect, o.ID) } return nil }
// Package regexp is a basic regexp library. // // The library was implemented to explore regexp parsing and NFA representation. package regexp // Regexp is a compiled regular expression. type Regexp struct { start, term node pattern string } // Compile compiles a pattern into Regexp. func Compile(pattern string) (r *Regexp, err error) { r = &Regexp{pattern: pattern} if r.start, r.term, err = parse(pattern); err != nil { return nil, err } return } // MustCompile invokes Compile and panics if an error is returned. func MustCompile(pattern string) *Regexp { r, err := Compile(pattern) if err != nil { panic(err) } return r } // MatchString returns true if the the passed input matches the pattern. func (r *Regexp) MatchString(input string) bool { cur, next := nodeSet{}, nodeSet{} cur.add(r.start) for _, r := range input { for n := range cur { if m, ok := n.(matchNode); ok && m.matches(r) { next.add(m.next()) } } if len(next) == 0 { return false } cur.clear() cur, next = next, cur } _, hasTerminal := cur[r.term] return hasTerminal } //////////////////////////////////////////////////////////////////////////////// // nodeSet //////////////////////////////////////////////////////////////////////////////// // nodeSet is used to evaluate the NFA type nodeSet map[node]struct{} func (s nodeSet) add(n node) { if _, exists := s[n]; exists { return } s[n] = struct{}{} for _, e := range n.epsilons() { s.add(e) } } func (s nodeSet) clear() { for n := range s { delete(s, n) } }
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "regexp" "strings" "sync" ) var ( linkReg = regexp.MustCompile(`href='(.+?)'[\s\S]*?>([\s\S]+?)<`) articleReg = regexp.MustCompile(`<P>[\s\S]+</P>`) ) //SideBar type type SideBar struct { Docs Docs `json:"docs"` } //Docs type type Docs struct { Chapters []string } // Chapter type type Chapter struct { id string url string title string content []byte } func (c *Chapter) writeToFile() { filename := `docs/` + c.title + `.md` ioutil.WriteFile(filename, c.content, 0644) } func main() { nav := `<ol> <li><a href='introduction-why-lisp.html'>Introduction: Why Lisp?</a></li> <li><a href='lather-rinse-repeat-a-tour-of-the-repl.html'>Lather, Rinse, Repeat: A Tour of the REPL</a></li> <li><a href='practical-a-simple-database.html'>Practical: A Simple Database</a></li> <li><a href='syntax-and-semantics.html'>Syntax and Semantics</a></li> <li><a href='functions.html'>Functions</a></li> <li><a href='variables.html'>Variables</a></li> <li><a href='macros-standard-control-constructs.html'>Macros: Standard Control Constructs</a></li> <li><a href='macros-defining-your-own.html'>Macros: Defining Your Own</a></li> <li><a href='practical-building-a-unit-test-framework.html'>Practical: Building a Unit Test Framework</a></li> <li><a href='numbers-characters-and-strings.html'>Numbers, Characters, and Strings</a></li> <li><a href='collections.html'>Collections</a></li> <li><a href='they-called-it-lisp-for-a-reason-list-processing.html'>They Called It LISP for a Reason: List Processing</a></li> <li><a href='beyond-lists-other-uses-for-cons-cells.html'>Beyond Lists: Other Uses for Cons Cells</a></li> <li><a href='files-and-file-io.html'>Files and File I/O</a></li> <li><a href='practical-a-portable-pathname-library.html'>Practical: A Portable Pathname Library</a></li> <li><a href='object-reorientation-generic-functions.html'>Object Reorientation: Generic Functions</a></li> <li><a href='object-reorientation-classes.html'>Object Reorientation: Classes</a></li> <li><a href='a-few-format-recipes.html'>A Few FORMAT Recipes</a></li> <li><a href='beyond-exception-handling-conditions-and-restarts.html'>Beyond Exception Handling: Conditions and Restarts</a></li> <li><a href='the-special-operators.html'>The Special Operators</a></li> <li><a href='programming-in-the-large-packages-and-symbols.html'>Programming in the Large: Packages and Symbols</a></li> <li><a href='loop-for-black-belts.html'>LOOP for Black Belts</a></li> <li><a href='practical-a-spam-filter.html'>Practical: A Spam Filter</a></li> <li><a href='practical-parsing-binary-files.html'>Practical: Parsing Binary Files</a></li> <li><a href='practical-an-id3-parser.html'>Practical: An ID3 Parser</a></li> <li><a href='practical-web-programming-with-allegroserve.html'>Practical: Web Programming with AllegroServe</a></li> <li><a href='practical-an-mp3-database.html'>Practical: An MP3 Database</a></li> <li><a href='practical-a-shoutcast-server.html'>Practical: A Shoutcast Server</a></li> <li><a href='practical-an-mp3-browser.html'>Practical: An MP3 Browser</a></li> <li><a href='practical-an-html-generation-library-the-interpreter.html'>Practical: An HTML Generation Library, the Interpreter</a></li> <li><a href='practical-an-html-generation-library-the-compiler.html'>Practical: An HTML Generation Library, the Compiler</a></li> <li><a href='conclusion-whats-next.html'>Conclusion: What's Next?</a></li> </ol>` var wg sync.WaitGroup client := &http.Client{} sidebars := &SideBar{} docList := &Docs{} links := linkReg.FindAllStringSubmatch(nav, -1) for _, link := range links { url, title := link[1], link[2] id := buildID(title) docList.Chapters = append(docList.Chapters, id) chapter := Chapter{ id, `http://www.gigamonkeys.com/book/` + url, title, []byte{}, } wg.Add(1) go func() { defer wg.Done() fetchChapter(client, &chapter) }() } wg.Wait() sidebars.Docs = *docList sidebarsJSON, _ := json.Marshal(sidebars) err := ioutil.WriteFile("website/sidebars.json", sidebarsJSON, 0644) if err != nil { fmt.Println(err) } fmt.Println("Done") } func fetchChapter(client *http.Client, chapter *Chapter) error { r, err := client.Get(chapter.url) if err != nil { fmt.Println(err) return err } defer r.Body.Close() b, _ := ioutil.ReadAll(r.Body) s := articleReg.FindStringSubmatch(string(b))[0] chapter.content = []byte(buildMD(chapter, s)) chapter.writeToFile() fmt.Println(`Done ` + chapter.title) return nil } var ( aReg = regexp.MustCompile(`<A[\s\S]+?><H2>([\s\S]+?)</H2></A>`) bReg = regexp.MustCompile(`<B>([\s\S]+?)</B>`) iReg = regexp.MustCompile(`<I>([\s\S]+?)</I>`) pReg = regexp.MustCompile(`<P>([\s\S]+?)</P>`) divReg = regexp.MustCompile(`<DIV[\s\S]+?>`) codeReg = regexp.MustCompile(`<CODE>([\s\S]+?)</CODE>`) preReg = regexp.MustCompile(`<PRE>([\s\S]+?)</PRE>`) ) func replaceHTML(s string) string { s = pReg.ReplaceAllString(s, "\n\n$1\n\n") s = bReg.ReplaceAllString(s, "$1") s = iReg.ReplaceAllString(s, "$1") s = codeReg.ReplaceAllString(s, "`$1`") s = preReg.ReplaceAllString(s, "\n```lisp\n$1\n```\n") s = aReg.ReplaceAllString(s, "\n## $1\n") s = divReg.ReplaceAllString(s, "") s = strings.Replace(s, "&quot;", `"`, -1) s = strings.Replace(s, "&amp;", `&`, -1) s = strings.Replace(s, "&lt;", `<`, -1) s = strings.Replace(s, "&gt;", `>`, -1) return s } func buildMD(c *Chapter, article string) string { title := fmt.Sprintf(`--- id: %s title: "%s" ---`, buildID(c.title), c.title, ) return title + replaceHTML(article) } var ( special = regexp.MustCompile(`[\?\(\)\/\., :]`) hyphens = regexp.MustCompile(`--+`) tailing = regexp.MustCompile(`-$`) ) func buildID(s string) string { s = strings.ToLower(s) s = special.ReplaceAllString(s, "-") s = hyphens.ReplaceAllString(s, "-") s = tailing.ReplaceAllString(s, "") return s }
package controllers import ( "github.com/canghai908/zbxtable/models" ) //TriggersController funct type TriggersController struct { BaseController } //TriggersRes resp var TriggersRes models.TriggersRes //URLMapping beego func (c *TriggersController) URLMapping() { c.Mapping("Get", c.GetInfo) } // GetInfo 获取未恢复告警 // @Title 获取未恢复告警据 // @Description 获取未恢复告警 // @Param X-Token header string true "x-token in header" // @Success 200 {object} models.Triggers // @Failure 403 :id is empty // @router / [get] func (c *TriggersController) GetInfo() { b, cnt, err := models.GetTriggers() if err != nil { TriggersRes.Code = 500 TriggersRes.Message = err.Error() } else { TriggersRes.Code = 200 TriggersRes.Message = "获取成功" TriggersRes.Data.Items = b TriggersRes.Data.Total = cnt } c.Data["json"] = TriggersRes c.ServeJSON() }
package resource import ( "os" "github.com/chronojam/aws-pricing-api/types/schema" "github.com/olekukonko/tablewriter" ) func GetVPC() { vpc := &schema.AmazonVPC{} err := vpc.Refresh() if err != nil { panic(err) } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Description", "USD", "Unit"}) table.SetRowLine(true) data := []*schema.AmazonVPC_Product{} for _, price := range vpc.Products { data = append(data, price) } for _, p := range data { for _, term := range vpc.Terms { if term.Sku == p.Sku { for _, priceData := range term.PriceDimensions { x := []string{} v := append(x, priceData.Description, priceData.PricePerUnit.USD, priceData.Unit) table.Append(v) } } } } table.Render() }
package repowatch import ( "encoding/json" "errors" "fmt" "sync" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/secretsmanager" ) var ( awsSecretsManagerLock sync.Mutex awsSecretsManagerMetadataClient *ec2metadata.EC2Metadata awsSecretsManagerMetadataClientError error ) func getMetadataClient() (*ec2metadata.EC2Metadata, error) { awsSecretsManagerLock.Lock() defer awsSecretsManagerLock.Unlock() if awsSecretsManagerMetadataClient != nil { return awsSecretsManagerMetadataClient, nil } if awsSecretsManagerMetadataClientError != nil { return nil, awsSecretsManagerMetadataClientError } metadataClient := ec2metadata.New(session.New()) if !metadataClient.Available() { awsSecretsManagerMetadataClientError = errors.New( "not running on AWS or metadata is not available") return nil, awsSecretsManagerMetadataClientError } awsSecretsManagerMetadataClient = metadataClient return awsSecretsManagerMetadataClient, nil } func getAwsSecret(metadataClient *ec2metadata.EC2Metadata, secretId string) (map[string]string, error) { var region string if arn, err := arn.Parse(secretId); err == nil { region = arn.Region } else { region, err = metadataClient.Region() if err != nil { return nil, err } } awsSession, err := session.NewSession(&aws.Config{ Region: aws.String(region), }) if err != nil { return nil, fmt.Errorf("error creating session: %s", err) } if awsSession == nil { return nil, errors.New("awsSession == nil") } awsService := secretsmanager.New(awsSession) input := secretsmanager.GetSecretValueInput{SecretId: aws.String(secretId)} output, err := awsService.GetSecretValue(&input) if err != nil { return nil, fmt.Errorf("error calling secretsmanager:GetSecretValue: %s", err) } if output.SecretString == nil { return nil, errors.New("no SecretString in secret") } secret := []byte(*output.SecretString) var secrets map[string]string if err := json.Unmarshal(secret, &secrets); err != nil { return nil, fmt.Errorf("error unmarshaling secret: %s", err) } return secrets, nil }
package logdata import "encoding/base64" // Payload is the struct describing the logged data packets' payload when supported type Payload struct { Content string `json:"content"` Base64 string `json:"base64"` Truncated bool `json:"truncated"` } // NewPayloadLogData is used to create a new Payload struct func NewPayloadLogData(data []byte, maxLength uint64) Payload { var pl = Payload{} if uint64(len(data)) > maxLength { data = data[:maxLength] pl.Truncated = true } pl.Content = string(data) pl.Base64 = base64.StdEncoding.EncodeToString(data) return pl }
package main import ( "fmt" ) type Differ struct { ceiling int } func (d Differ) SquareOfSums() int { sum := 0 for i := 1; i <= d.ceiling; i++ { sum += i } return sum * sum } func (d Differ) SumOfSquares() int { sum := 0 for i := 1; i <= d.ceiling; i++ { sum += i * i } return sum } func main() { differ := Differ{100} fmt.Println("Square of sums up to", differ.ceiling, ": ", differ.SquareOfSums()) fmt.Println("Sum of squares up to", differ.ceiling, ": ", differ.SumOfSquares()) fmt.Println("Difference:", differ.SquareOfSums()-differ.SumOfSquares()) }
// chan3 project main.go package main import ( "fmt" ) func main() { ch := make(chan int) fmt.Println("1") ch <- 3 fmt.Println("oo", <-ch) fmt.Println(2) fmt.Println("Hello World!") }
package main import "fmt" // Go has built-in support for multiple return values. This feature is // used often in idiomatic Go, for example to retunr both result and // error values from a function. // Vals - the (int, int) in this function signature shows that the // function returns 2 ints. func vals() (int, int) { return 3, 7 } func main() { // Here we use the 2 different return values from the call with // multiple assignment a, b := vals() fmt.Println(a) fmt.Println(b) // If you only want a subset of the returned values, use the blank // identifier _. _, c := vals() fmt.Println(c) }
/* Objective: The objective is to calculate e^N for some real or imaginary N (e.g. 2, -3i, 0.7, 2.5i, but not 3+2i). This is code golf, so, shortest code (in bytes) wins. So, for example: N = 3, e^N = 20.0855392 N = -2i, e^N = -0.416146837 - 0.9092974268i The letter i shouldn't be capitalized (since in math it is lowercase) If your language supports raising numbers to complex numbers, you can't use that. You may use built-in real exponentiation. For any answer where b (in a + bi) is negative, it is OK to have both the plus and minus sign (e.g. 2 + -3i), since that is understood to be (2 - 3i) Bonus (-15 bytes): Solve this for N is a any complex number (e.g. 5 + 7i). If you are going for the bonus, you can assume that both components will always be given (even for the standard objective) */ package main import ( "fmt" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(3)) fmt.Println(cmplx.Exp(-2i)) }
package api import ( "as/pkg/app" "as/pkg/errcode" "github.com/gin-gonic/gin" ) type Admin struct{} // Login 用户登录 // @Summary 用户登录 func (Admin) Login(c *gin.Context) { var userName struct { UserName string `form:"username" binding:"max=20,min=6,required"` Password string `form:"password" binding:"max=20,min=6,required"` } err := c.ShouldBind(&userName) if err != nil { app.NewResponse(c).ToErrorResponse(errcode.InvilidParams.WithDetails(err.Error())) return } app.NewResponse(c).ToResponse("憨批一个") return } // Logout // @Summary 用户登录 // @Produce json // @Param name body string true "用户名" // @param password body string true "密码" // @Success 200 {object} errcode.Error "请求成功" // @Failure 400 {object} errcode.Error "请求失败" // @Failure 500 {object} errcode.Error "内部错误" // @Router /api/api/admin/logout [get] func (Admin) Logout(c *gin.Context) { app.NewResponse(c).ToResponse("sfa") } // Fresh 刷新token func (Admin) Fresh(c *gin.Context) { } // GetInfo 获取用户信息 func (Admin) GetInfo(c *gin.Context) { } func NewAdmin() Admin { return Admin{} }
package main import ( "os" "github.com/golang/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" "github.com/batchcorp/plumber/test-assets/protobuf-any/sample" ) func main() { inner, err := anypb.New(&sample.Message{ Name: "Mark", Age: 39, }) if err != nil { panic(err) } m := &sample.Envelope{ Message: "Plumber supports google.protobuf.Any", Details: inner, } data, err := proto.Marshal(m) if err != nil { panic(err) } os.WriteFile("payload.bin", data, 0644) println("write data to payload.bin") }
package docsonnet import ( "fmt" "log" "strings" ) // load docsonnet // // Data assumptions: // - only map[string]interface{} and fields // - fields (#...) coming first func fastLoad(d ds) Package { pkg := d.Package() pkg.API = make(Fields) pkg.Sub = make(map[string]Package) for k, v := range d { if k == "#" { continue } f := v.(map[string]interface{}) // field name := strings.TrimPrefix(k, "#") if strings.HasPrefix(k, "#") { pkg.API[name] = loadField(name, f, d) continue } // non-docsonnet // subpackage? if _, ok := f["#"]; ok { p := fastLoad(ds(f)) pkg.Sub[p.Name] = p continue } // non-annotated nested? // try to load, but skip when already loaded as annotated above if nested, ok := loadNested(name, f); ok && !fieldsHas(pkg.API, name) { pkg.API[name] = *nested continue } } return pkg } func fieldsHas(f Fields, key string) bool { _, b := f[key] return b } func loadNested(name string, msi map[string]interface{}) (*Field, bool) { out := Object{ Name: name, Fields: make(Fields), } ok := false for k, v := range msi { f := v.(map[string]interface{}) n := strings.TrimPrefix(k, "#") if !strings.HasPrefix(k, "#") { if l, ok := loadNested(k, f); ok { out.Fields[n] = *l } continue } ok = true l := loadField(n, f, msi) out.Fields[n] = l } if !ok { return nil, false } return &Field{Object: &out}, true } func loadField(name string, field map[string]interface{}, parent map[string]interface{}) Field { if ifn, ok := field["function"]; ok { return loadFn(name, ifn.(map[string]interface{})) } if iobj, ok := field["object"]; ok { return loadObj(name, iobj.(map[string]interface{}), parent) } if vobj, ok := field["value"]; ok { return loadValue(name, vobj.(map[string]interface{})) } panic(fmt.Sprintf("field %s lacking {function | object | value}", name)) } func loadValue(name string, msi map[string]interface{}) Field { h, ok := msi["help"].(string) if !ok { h = "" } t, ok := msi["type"].(string) if !ok { panic(fmt.Sprintf("value %s lacking type information", name)) } v := Value{ Name: name, Help: h, Type: Type(t), Default: msi["default"], } return Field{Value: &v} } func loadFn(name string, msi map[string]interface{}) Field { h, ok := msi["help"].(string) if !ok { h = "" } fn := Function{ Name: name, Help: h, } if args, ok := msi["args"]; ok { fn.Args = loadArgs(args.([]interface{})) } return Field{Function: &fn} } func loadArgs(is []interface{}) []Argument { args := make([]Argument, len(is)) for i := range is { arg := is[i].(map[string]interface{}) args[i] = Argument{ Name: arg["name"].(string), Type: Type(arg["type"].(string)), Default: arg["default"], } } return args } func fieldNames(msi map[string]interface{}) []string { out := make([]string, 0, len(msi)) for k := range msi { out = append(out, k) } return out } func loadObj(name string, msi map[string]interface{}, parent map[string]interface{}) Field { obj := Object{ Name: name, Help: msi["help"].(string), Fields: make(Fields), } // look for children in same key without # var iChilds interface{} var ok bool if iChilds, ok = parent[name]; !ok { fmt.Println("aborting, no", name, strings.Join(fieldNames(parent), ", ")) return Field{Object: &obj} } childs := iChilds.(map[string]interface{}) for k, v := range childs { name := strings.TrimPrefix(k, "#") f := v.(map[string]interface{}) if !strings.HasPrefix(k, "#") { if l, ok := loadNested(k, f); ok { obj.Fields[name] = *l } continue } obj.Fields[name] = loadField(name, f, childs) } return Field{Object: &obj} } type ds map[string]interface{} func (d ds) Package() Package { hash, ok := d["#"] if !ok { log.Fatalln("Package declaration missing") } pkg := hash.(map[string]interface{}) return Package{ Help: pkg["help"].(string), Name: pkg["name"].(string), Import: pkg["import"].(string), } }
// Copyright 2016 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // Sample buckets creates a bucket, lists buckets and deletes a bucket // using the Google Storage API. More documentation is available at // https://cloud.google.com/storage/docs/json_api/v1/. package main import ( "fmt" "log" "os" "time" "golang.org/x/net/context" "cloud.google.com/go/storage" "google.golang.org/api/iterator" ) func main() { ctx := context.Background() projectID := os.Getenv("GOOGLE_CLOUD_PROJECT") if projectID == "" { fmt.Fprintf(os.Stderr, "GOOGLE_CLOUD_PROJECT environment variable must be set.\n") os.Exit(1) } // [START setup] client, err := storage.NewClient(ctx) if err != nil { log.Fatal(err) } // [END setup] // Give the bucket a unique name. name := fmt.Sprintf("golang-example-buckets-%d", time.Now().Unix()) if err := create(client, projectID, name); err != nil { log.Fatal(err) } fmt.Printf("created bucket: %v\n", name) // list buckets from the project buckets, err := list(client, projectID) if err != nil { log.Fatal(err) } fmt.Printf("buckets: %+v\n", buckets) // delete the bucket if err := delete(client, name); err != nil { log.Fatal(err) } fmt.Printf("deleted bucket: %v\n", name) } func create(client *storage.Client, projectID, bucketName string) error { ctx := context.Background() // [START create_bucket] if err := client.Bucket(bucketName).Create(ctx, projectID, nil); err != nil { return err } // [END create_bucket] return nil } func list(client *storage.Client, projectID string) ([]string, error) { ctx := context.Background() // [START list_buckets] var buckets []string it := client.Buckets(ctx, projectID) for { battrs, err := it.Next() if err == iterator.Done { break } if err != nil { return nil, err } buckets = append(buckets, battrs.Name) } // [END list_buckets] return buckets, nil } func delete(client *storage.Client, bucketName string) error { ctx := context.Background() // [START delete_bucket] if err := client.Bucket(bucketName).Delete(ctx); err != nil { return err } // [END delete_bucket] return nil }
package leetcode import ( "testing" ) func TestPrintNumbers(t *testing.T) { n := 2 PrintNumbers2(n) }
package responses import ( "Pinjem/businesses/deposits" "time" ) type DepositResponse struct { ID uint `json:"id"` UserId uint `json:"user_id"` Amount uint `json:"amount"` UsedAmount uint `json:"used_amount"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } func FromDomain(domain deposits.Domain) DepositResponse { return DepositResponse{ ID: domain.Id, UserId: domain.UserId, Amount: domain.Amount, UsedAmount: domain.UsedAmount, CreatedAt: domain.CreatedAt, UpdatedAt: domain.UpdatedAt, } }
package types import ( "fmt" "strings" ) // Symbol represents a tradable asset pair type Symbol struct { base string quote string } // NewSymbol creates a Symbol instance func NewSymbol(baseAsset string, quoteAsset string) Symbol { return Symbol{ base: strings.ToUpper(baseAsset), quote: strings.ToUpper(quoteAsset), } } // NewSymbolFromString creates a Symbol instance from a string // The string format should be: // base/quote func NewSymbolFromString(in string) (sym Symbol, err error) { var parts []string parts = strings.Split(in, "/") if len(parts) != 2 { err = fmt.Errorf("Invalid symbol string") return } sym = Symbol{ base: strings.ToUpper(parts[0]), quote: strings.ToUpper(parts[1]), } return } // Base returns the base asset func (s Symbol) Base() string { return s.base } // Quote returns the quote asset func (s Symbol) Quote() string { return s.quote } // String returns the string version of the symbol func (s Symbol) String() string { return fmt.Sprintf("%s/%s", s.base, s.quote) }
package main import ( "aoc/day1" "aoc/day2" "flag" ) var day int func init() { flag.IntVar(&day, "day", 1, "Which day would you to run") flag.Parse() } func main() { switch day { case 1: day1.Run() case 2: day2.Run() } }
package printer import ( "fmt" "strings" "sync" "time" "github.com/fatih/color" "github.com/mszostok/codeowners-validator/internal/check" ) type TTYPrinter struct { m sync.RWMutex } func (tty *TTYPrinter) PrintCheckResult(checkName string, duration time.Duration, checkOut check.Output) { tty.m.Lock() defer tty.m.Unlock() header := color.New(color.Bold).PrintfFunc() issueBody := color.New(color.FgWhite).PrintfFunc() okCheck := color.New(color.FgGreen).PrintlnFunc() header("==> Executing %s (%v)\n", checkName, duration) for _, i := range checkOut.Issues { issueSeverity := tty.severityPrintfFunc(i.Severity) issueSeverity(" [%s]", strings.ToLower(i.Severity.String()[:3])) if i.LineNo != nil { issueBody(" line %d:", *i.LineNo) } issueBody(" %s\n", i.Message) } if len(checkOut.Issues) == 0 { okCheck(" Check OK") } } func (*TTYPrinter) severityPrintfFunc(severity check.SeverityType) func(format string, a ...interface{}) { p := color.New() switch severity { case check.Warning: p.Add(color.FgYellow) case check.Error: p.Add(color.FgRed) } return p.PrintfFunc() } func (*TTYPrinter) PrintSummary(allCheck, failedChecks int) { failures := "no" if failedChecks > 0 { failures = fmt.Sprintf("%d", failedChecks) } fmt.Printf("\n%d check(s) executed, %s failure(s)\n", allCheck, failures) }
// +k8s:deepcopy-gen=package,register // +groupName=simple.io.example // Package api is the internal version of the API. package simple
package main import ( "encoding/json" "fmt" "log" "net/http" "gopkg.in/mgo.v2/bson" "gopkg.in/mgo.v2" "github.com/gorilla/mux" ) /* var movies = Movies{ Movie{"Sin Limites", 2013, "Desconocido"}, Movie{"Batman Begins", 1999, "Scorsese"}, Movie{"A todo gas", 2005, "Pizzi"}, } */ // Crear variable global var collection = getSession().DB("curso_go").C("movies") func getSession() *mgo.Session { session, err := mgo.Dial("mongodb://localhost") if err != nil { panic(err) } return session } func responseMovie(w http.ResponseWriter, status int, results Movie) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(results) } func responseMovies(w http.ResponseWriter, status int, results []Movie) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(results) } func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hola mundo desde mi servidor web con GO") } /* func Contact(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Esta es la pagina de contacto") } */ func MovieList(w http.ResponseWriter, r *http.Request) { var results []Movie err := collection.Find(nil).Sort("-_id").All(&results) if err != nil { log.Fatal(err) } else { fmt.Println("Resultados: ", results) } responseMovies(w, 200, results) } func MovieShow(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) movie_id := params["id"] //fmt.Println(movie_id) //fmt.Fprintf(w, "Has cargado la pelicula numero %s", movie_id) // Comprobar que el ID es un ID hexadecimal if !bson.IsObjectIdHex(movie_id) { w.WriteHeader(404) return } oid := bson.ObjectIdHex(movie_id) //fmt.Println(oid) results := Movie{} err := collection.FindId(oid).One(&results) //fmt.Println(results) if err != nil { w.WriteHeader(404) return } responseMovie(w, 200, results) } // Recibir un reponseWriter y una request func MovieAdd(w http.ResponseWriter, r *http.Request) { // Recogemos los datos del Body que nos llega en la request // Lo decodificamos con JSON decoder := json.NewDecoder(r.Body) // Creamos una variable para los datos que recogemos var movie_data Movie // &: Indicar que es una variable que no tiene nada err := decoder.Decode(&movie_data) if err != nil { panic(err) } // Cerrar la lectura de algo (body) defer r.Body.Close() //log.Println(movie_data) //movies = append(movies, movie_data) // Guardar los datos en la base de datos // movie_data es el objeto que estamos recibiendo por el body err = collection.Insert(movie_data) if err != nil { w.WriteHeader(500) return } responseMovie(w, 200, movie_data) } func MovieUpdate(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) movie_id := params["id"] if !bson.IsObjectIdHex(movie_id) { w.WriteHeader(404) return } oid := bson.ObjectIdHex(movie_id) // Recoger el objeto JSON que nos llega por el BODY decoder := json.NewDecoder(r.Body) var movie_data Movie // Decodificar los datos y bindearlos en la variable movie_data err := decoder.Decode(&movie_data) if err != nil { panic(err) w.WriteHeader(500) return } // Cerrar la lectura de algo (body) defer r.Body.Close() // Hacer el update en la base de datos document := bson.M{"_id": oid} change := bson.M{"$set": movie_data} err = collection.Update(document, change) if err != nil { w.WriteHeader(404) return } responseMovie(w, 200, movie_data) } type Message struct { Status string `json:"status"` Message string `json:"message"` } // *: Ya no es una copia, es un puntero func (this *Message) setStatus(data string) { this.Status = data } // *: Ya no es una copia, es un puntero func (this *Message) setMessage(data string) { this.Message = data } func MovieRemove(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) movie_id := params["id"] // Comprobar que el ID es un ID hexadecimal if !bson.IsObjectIdHex(movie_id) { w.WriteHeader(404) return } oid := bson.ObjectIdHex(movie_id) err := collection.RemoveId(oid) if err != nil { w.WriteHeader(404) return } message := new(Message) message.setStatus("Success") message.setMessage("La pelicula con ID " + movie_id + " ha sido borrada correctamente") results := message //results := Message{"success", "La pelicula con ID " + movie_id + " ha sido borrada correctamente"} w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) json.NewEncoder(w).Encode(results) }
package tstune import ( "bytes" "fmt" "strings" "testing" ) type testPrinter struct { statementCalls uint64 statements []string promptCalls uint64 prompts []string successCalls uint64 successes []string errorCalls uint64 errors []string } func (p *testPrinter) Statement(format string, args ...interface{}) { p.statementCalls++ p.statements = append(p.statements, fmt.Sprintf(format, args...)) } func (p *testPrinter) Prompt(format string, args ...interface{}) { p.promptCalls++ p.prompts = append(p.prompts, fmt.Sprintf(format, args...)) } func (p *testPrinter) Success(format string, args ...interface{}) { p.successCalls++ p.successes = append(p.successes, fmt.Sprintf(format, args...)) } func (p *testPrinter) Error(label string, format string, args ...interface{}) { p.errorCalls++ p.errors = append(p.errors, fmt.Sprintf(label+": "+format, args...)) } const whiteBoldSeq = "\x1b[37;1m" const purpleBoldSeq = "\x1b[35;1m" const greenBoldSeq = "\x1b[32;1m" const redBoldSeq = "\x1b[31;1m" const resetSeq = "\x1b[0m" func TestColorPrinterStatement(t *testing.T) { var buf bytes.Buffer p := &colorPrinter{&buf} stmt := "This is a statement with %d" p.Statement(stmt, 1) want := whiteBoldSeq + fmt.Sprintf(stmt+"\n", 1) + resetSeq if got := string(buf.Bytes()); got != want { t.Errorf("incorrect statement: got\n%s\nwant\n%s", got, want) } } func TestColorPrinterPrompt(t *testing.T) { var buf bytes.Buffer p := &colorPrinter{&buf} stmt := "This is a prompt with %d" p.Prompt(stmt, 1) want := purpleBoldSeq + fmt.Sprintf(stmt, 1) + resetSeq if got := string(buf.Bytes()); got != want { t.Errorf("incorrect prompt: got\n%s\nwant\n%s", got, want) } } func TestColorPrinterSuccess(t *testing.T) { var buf bytes.Buffer p := &colorPrinter{&buf} stmt := "This is a success with %d" p.Success(stmt, 1) want := greenBoldSeq + successLabel + resetSeq + fmt.Sprintf(stmt+"\n", 1) if got := string(buf.Bytes()); got != want { t.Errorf("incorrect success: got\n%s\nwant\n%s", got, want) } } func TestColorPrinterError(t *testing.T) { var buf bytes.Buffer p := &colorPrinter{&buf} stmt := "This is a error with %d" label := "yikes" p.Error(label, stmt, 1) want := redBoldSeq + label + ": " + resetSeq + fmt.Sprintf(stmt+"\n", 1) if got := string(buf.Bytes()); got != want { t.Errorf("incorrect error: got\n%s\nwant\n%s", got, want) } } func TestNoColorPrinterStatement(t *testing.T) { var buf bytes.Buffer p := &noColorPrinter{&buf} stmt := "This is a statement with %d" p.Statement(stmt, 1) want := noColorPrefixStatement + fmt.Sprintf(stmt+"\n", 1) if got := string(buf.Bytes()); got != want { t.Errorf("incorrect statement: got\n%s\nwant\n%s", got, want) } } func TestNoColorPrinterPrompt(t *testing.T) { var buf bytes.Buffer p := &noColorPrinter{&buf} stmt := "This is a prompt with %d" p.Prompt(stmt, 1) want := noColorPrefixPrompt + fmt.Sprintf(stmt, 1) if got := string(buf.Bytes()); got != want { t.Errorf("incorrect prompt: got\n%s\nwant\n%s", got, want) } } func TestNoColorPrinterSuccess(t *testing.T) { var buf bytes.Buffer p := &noColorPrinter{&buf} stmt := "This is a success with %d" p.Success(stmt, 1) want := strings.ToUpper(successLabel) + fmt.Sprintf(stmt+"\n", 1) if got := string(buf.Bytes()); got != want { t.Errorf("incorrect success: got\n%s\nwant\n%s", got, want) } } func TestNoColorPrinterError(t *testing.T) { var buf bytes.Buffer p := &noColorPrinter{&buf} stmt := "This is a error with %d" label := "yikes" p.Error(label, stmt, 1) want := strings.ToUpper(label) + ": " + fmt.Sprintf(stmt+"\n", 1) if got := string(buf.Bytes()); got != want { t.Errorf("incorrect error: got\n%s\nwant\n%s", got, want) } }
package main import ( "database/sql" "flag" "fmt" _ "github.com/mattn/go-oci8" "log" "os" "strings" ) var conn string func main() { flag.Parse() if flag.NArg() >= 1 { conn = flag.Arg(0) } else { conn = "system/123456@XE" } db, err := sql.Open("oci8", conn) if err != nil { fmt.Println("can't connect ", conn, err) return } if err = test_conn(db); err != nil { fmt.Println("can't connect ", conn, err) return } var in string var sqlquery string fmt.Print("> ") for { fmt.Scan(&in) if in == "q;" { break } if in[len(in)-1] != ';' { sqlquery += in + " " } else { sqlquery += in[:len(in)-1] rows, err := db.Query(sqlquery) if err != nil { fmt.Println("can't run ", sqlquery, "\n", err) fmt.Print("> ") sqlquery = "" continue } cols, err := rows.Columns() if err != nil { log.Fatal(err) } fmt.Println(strings.Join(cols, "\t")) var result = make([]string, len(cols)) var s = make([]interface{}, len(result)) for i, _ := range result { s[i] = &result[i] } for rows.Next() { rows.Scan(s...) fmt.Println(strings.Join(result, "\t")) } rows.Close() fmt.Print("> ") sqlquery = "" } } db.Close() } func test_conn(db *sql.DB) (err error) { query := "select * from dual" _, err = db.Query(query) return err }
package main import ( "bufio" "encoding/csv" "fmt" "os" "strconv" "strings" "time" ) func readQuestions(fpath string) (*[]string, *[]int) { csvfile, err := os.Open(fpath) if err != nil { fmt.Println("Couldn't open the csv file", err) } r := csv.NewReader(csvfile) records, err := r.ReadAll() if err != nil { fmt.Println(err) } questions := make([]string, len(records)) answers := make([]int, len(records)) for idx := range records { questions[idx] = records[idx][0] ans, err := strconv.Atoi(records[idx][1]) if err != nil { fmt.Println("answer sheet should be an integer.", err) os.Exit(1) } answers[idx] = ans } return &questions, &answers } func calcScore(userAns, examAns *[]int) int { score := 0 for idx, user := range *userAns { if user == (*examAns)[idx] { score++ } } return score } func readUserInput() int { stdinReader := bufio.NewReader(os.Stdin) ret := 0 for { text, err := stdinReader.ReadString('\n') if err != nil { fmt.Println("something went wrong... ", err) } text = strings.Replace(text, "\r\n", "", -1) ans, err := strconv.Atoi(text) if err == nil { ret = ans break } else { fmt.Println("your input isn't a number, please try again.") } } return ret } func quickQnA(signal chan<- bool, questions *[]string, userAns *[]int) { for idx, qs := range *questions { fmt.Printf("Q%v: %v = ", idx+1, qs) ans := readUserInput() (*userAns)[idx] = ans } signal <- true } func main() { // parse argument argsWithoutProg := os.Args[1:] if len(argsWithoutProg) != 1 { fmt.Println("error: one positional argument is required for parsing the question.") os.Exit(1) } // prepare questions, answers, user input container questions, answers := readQuestions(argsWithoutProg[0]) fmt.Println(questions) fmt.Println(answers) userAns := make([]int, len(*questions)) // ready go fmt.Println("You have 30 seconds to finish this exam, the exam will begin after 3 sec.") time.Sleep(3 * time.Second) fmt.Println("Start!") signal := make(chan bool, 1) go quickQnA(signal, questions, &userAns) select { case <-signal: fmt.Println("Congrats! You finish the exam on time!") case <-time.After(time.Second * 3): fmt.Println() fmt.Println("Time's up! So sad! you aren't complete the exam on time!") } // compute the score score := calcScore(&userAns, answers) fmt.Printf("Total score: %v/%v \n", score, len(*questions)) }
//author xinbing //time 2018/9/4 17:55 package db import "github.com/pkg/errors" type DBConfig struct { DBAddr string AutoCreateTables []interface{} //自动创建的表 MaxIdleConns int MaxOpenConns int LogMode bool } func (p *DBConfig) check() error { if p.DBAddr == "" { return errors.New("empty sql addr") } if p.MaxIdleConns <= 0 { p.MaxIdleConns = 10 } if p.MaxOpenConns <= 0 { p.MaxOpenConns = 100 } return nil }
// Package runner provides common interface for program runner together with // common types including Result, Limit, Size and Status. // // Status // // Status defines the program running result status including // Normal // Program Error // Resource Limit Exceeded (Time / Memory / Output) // Unauthorized Access (Disallowed Syscall) // Runtime Error (Signaled / Nonzero Exit Status) // Program Runner Error // // Size // // Size defines size in bytes, underlying type is uint64 so it // is effective to store up to EiB of size // // Limit // // Limit defines Time & Memory restriction on program runner // // Result // // Result defines program running result including // Status, ExitStatus, Detailed Error, Time, Memory, // SetupTime and RunningTime (in real clock) // // Runner // // General interface to run a program, including a context // for canclation package runner
package xeninvoice import ( xinvoice "github.com/xendit/xendit-go/invoice" "github.com/imrenagi/go-payment/invoice" ) func NewBRIVA(inv *invoice.Invoice) (*xinvoice.CreateParams, error) { return newBuilder(inv). AddPaymentMethod("BRI"). Build() }
package main import ( "ms/sun/shared/x" "ms/sun/shared/helper" "ms/sun/shared/dbs" ) func main() { p := x.PostCdb{ PostId: helper.NextRowsSeqId(), UserId: 0, PostTypeEnum: 0, PostCategoryEnum: 0, MediaId: 0, PostKey: "", Text: helper.FactRandStrEmoji(10,true), RichText: "", MediaCount: 0, SharedTo: 0, DisableComment: 0, Source: 0, HasTag: 0, Seq: 0, CommentsCount: 0, LikesCount: 0, ViewsCount: 0, EditedTime: 0, CreatedTime: 0, ReSharedPostId: 0, } err := p.Save(dbs.DB_PG) helper.NoErr(err) }
package str_test import ( "fmt" "testing" "github.com/piniondb/str" ) func intStr(val uint) string { return str.Delimit(fmt.Sprintf("%d", val), ",", 3) } func Example_quantity() { for _, val := range []uint{0, 5, 15, 121, 4320, 70123, 999321, 4032500, 50100438, 100000054} { fmt.Printf("[%14s : %s]\n", intStr(val), str.Quantity(val)) } // Output: // [ 0 : zero] // [ 5 : five] // [ 15 : fifteen] // [ 121 : one hundred twenty one] // [ 4,320 : four thousand three hundred twenty] // [ 70,123 : seventy thousand one hundred twenty three] // [ 999,321 : nine hundred ninety nine thousand three hundred twenty one] // [ 4,032,500 : four million thirty two thousand five hundred] // [ 50,100,438 : fifty million one hundred thousand four hundred thirty eight] // [ 100,000,054 : one hundred million fifty four] } func Example_quantityEncode() { var sl []byte var err error for _, val := range []uint{0, 5, 15, 121, 4320, 70123, 999321, 4032500, 50100438, 100000054} { if err == nil { sl, err = str.QuantityEncode(val) fmt.Printf("[%14s : %s]\n", intStr(val), str.QuantityDecode(sl)) } } if err != nil { fmt.Println(err) } // Output: // [ 0 : zero] // [ 5 : five] // [ 15 : fifteen] // [ 121 : one hundred twenty one] // [ 4,320 : four thousand three hundred twenty] // [ 70,123 : seventy thousand one hundred twenty three] // [ 999,321 : nine hundred ninety nine thousand three hundred twenty one] // [ 4,032,500 : four million thirty two thousand five hundred] // [ 50,100,438 : fifty million one hundred thousand four hundred thirty eight] // [ 100,000,054 : one hundred million fifty four] } func quantityExpect(t *testing.T, val uint, expStr string) { valStr := str.Quantity(val) if valStr != expStr { t.Fatalf("expecting \"%s\", got \"%s\"", expStr, valStr) } } // Test return value of Quantity func TestQuantity(t *testing.T) { quantityExpect(t, 35, "thirty five") quantityExpect(t, 100000000, "one hundred million") quantityExpect(t, 2100200300, "2100200300") } // Test return value of Quantity func TestQuantityEncode(t *testing.T) { var err error _, err = str.QuantityEncode(35) if err != nil { t.Fatal(err) } _, err = str.QuantityEncode(2100200300) if err == nil { t.Fatalf("expecting over-limit error") } }
package divide_conquer import "strconv" func diffWaysToCompute(input string) []int { var res []int for i := 0; i < len(input); i++ { if input[i] == '+' || input[i] == '-' || input[i] == '*' { part1 := input[:i] part2 := input[i+1:] res1 := diffWaysToCompute(part1) res2 := diffWaysToCompute(part2) for _, r := range res1 { for _, r2 := range res2 { c := 0 switch input[i] { case '+': c = r + r2 case '-': c = r - r2 case '*': c = r * r2 } res = append(res, c) } } } } if len(res) == 0 { c, _ := strconv.Atoi(input) res = append(res, c) } return res }
package main import ( "database/sql" "fmt" "github.com/cayleygraph/cayley" "github.com/cayleygraph/cayley/graph" _ "github.com/aselus-hub/cayley/graph/sql" "github.com/cayleygraph/cayley/quad" "github.com/satori/go.uuid" "log" "math/rand" "sync" "time" ) const insecureCdbPath = "postgresql://root@127.0.0.1:26257/" const ( runTime = 1*time.Second reportEvery = 5*time.Second batchSize = 15 NumRoutines = 4 ) type node struct { parent string child string id string } func generateAndSendAGraph(wg *sync.WaitGroup, sumChan chan uint64, quit chan struct{}) { defer wg.Done() var numProccessed uint64 lastReport := time.Now() if store, err := InitCayley(insecureCdbPath + "cayley?sslmode=disable&binary_parameters"); err != nil { fmt.Printf("Could not initialize cayley, %s\n", err.Error()) return } else { defer store.Close() tx := cayley.NewTransaction() for { select { case <-quit: tx = commitTx(store, tx, true) sumChan <- numProccessed return default: if time.Since(lastReport) > reportEvery { sumChan <- numProccessed numProccessed = 0 lastReport = time.Now() } nodes := generateGraph(store) for _, n := range nodes { n = n addNquadsForNode(n, tx) tx = commitTx(store, tx, false) numProccessed++ } } } } } func generateGraph(store *cayley.Handle) []node { // create a lineage for connecting A through link to B, etc. numItems := 2 + rand.Intn(10) // permutations := rand.Perm(numItems) // create a list of nodes, with number of true items and number of links. nodes := make([]node, numItems, numItems) currentUUID := "" for index := range nodes { newUuid := uuid.NewV4().String() nodes[index] = node{parent: currentUUID, id: uuid.NewV4().String(), child: currentUUID} currentUUID = newUuid } return nodes } func addNquadsForNode(n node, tx *graph.Transaction) { if n.parent != "" { tx.AddQuad(quad.Make(n.parent, "related_through", n.id, nil)) } if n.child != "" { tx.AddQuad(quad.Make(n.id, "related_through", n.child, nil)) } } func commitTx(store *cayley.Handle, tx *graph.Transaction, force bool) *graph.Transaction { if len(tx.Deltas) > batchSize || force { err := store.ApplyTransaction(tx) if err != nil { panic(err.Error()) } return cayley.NewTransaction() } else { return tx } } func main() { rand.Seed(time.Now().UTC().UnixNano()) SetupCayleyInCdb() termination := sync.WaitGroup{} termination.Add(NumRoutines) var trueEnd time.Duration var totalSum uint64 processedNodes := make(chan uint64, NumRoutines) quit := make(chan struct{}) start := time.Now() for i := 0; i < NumRoutines; i++ { go generateAndSendAGraph(&termination, processedNodes, quit) } var curSum uint64 var numSum int lastUpdate := time.Now() for { select { case <-time.After(time.Second): case subSum := <-processedNodes: curSum += subSum fmt.Printf("node sum: %d\n", subSum) numSum++ if numSum == NumRoutines { fmt.Printf("\trunning sum: %d [%v/sec]\n", curSum, float64(curSum) / time.Since(lastUpdate).Seconds()) lastUpdate = time.Now() totalSum += curSum curSum = 0 numSum = 0 } } if time.Since(start) > runTime { close(quit) break } } termination.Wait() trueEnd = time.Since(start) outerFor: for { select { case subSum := <-processedNodes: totalSum += subSum default: break outerFor } } fmt.Printf("time elapsed: %v\n", trueEnd) fmt.Printf("total processed: %v\n", totalSum+curSum) fmt.Printf("sets/second: %v\n", float64(totalSum) / trueEnd.Seconds()) } func SetupCayleyInCdb() { db, err := sql.Open("postgres", insecureCdbPath+"system?sslmode=disable") if err != nil { log.Fatalf("Unable to initialize cockroach: %s", err.Error()) } defer db.Close() _, err = db.Exec("CREATE DATABASE IF NOT EXISTS cayley") if err != nil { log.Fatalf("Unable to initialize cockroach: %s", err.Error()) } if err = graph.InitQuadStore("sql", insecureCdbPath+"cayley?sslmode=disable", graph.Options{"flavor": "cockroach"}); err != nil { if err != graph.ErrDatabaseExists { panic(err.Error()) } } } func InitCayley(pathToCockroachDB string) (store *cayley.Handle, err error) { store, err = cayley.NewGraph("sql", pathToCockroachDB, graph.Options{"flavor": "cockroach"}) if err != nil { return } return }
package conference import "time" //CallForPapers represents a call for papers/requests done by conference organisers in order to get talks type CallForPapers struct { ConferenceName string ConferenceID string URL string Deadline time.Time Description string Starts time.Time }
/* Copyright © 2019 Sven Wilhelm <refnode@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "io/ioutil" "testing" "github.com/spf13/cobra" ) func emptyRun(*cobra.Command, []string) {} func TestRootCmd(t *testing.T) { tests := []struct { name string args []string }{ { name: "defaults", args: []string{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd := NewRootCmd(tt.args) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tt.args) cmd.Run = emptyRun if err := cmd.Execute(); err != nil { t.Errorf("unexpected error: %s", err) } }) } }