text
stringlengths
11
4.05M
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/12/5 9:08 上午 # @File : offer09_栈实现队列.go # @Description : # @Attention : */ package offer2 // 关键: 一个栈push,一个栈pop type CQueue struct { push []int pop []int } func Constructor() CQueue { return CQueue{} } func (this *CQueue) AppendTail(value int) { this.p...
package functions_demo import "fmt" /* 函数可以接收0或多个参数 当连续两个或多个函数的已命名形参类型相同时,除最后一个类型以外,其它都可以省略 */ func FuncArgs(x, y int) { fmt.Println(x + y) }
package main import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sns" "flag" "fmt" "os" ) func main() { emailPtr := flag.String("e", "", "The email address of the user subscribing to the topic") topicPtr := flag.String("t", "", "The ARN of the topic t...
package main import ( "database/sql" "fmt" "log" "time" "github.com/nitohu/err" ) // Transaction model // TODO: Implement Forecasted and Booked in database type Transaction struct { // Database fields ID int64 Name string Description string Active bool TransactionDate ...
package aggregate var v1Tov2MetricsConversion = map[string]string{ "replica*app.pegasus*get_qps": "get_qps", "replica*app.pegasus*multi_get_qps": "multi_get_qps", "replica*app.pegasus*put_qps": "put_qps", "replica*app.pega...
/* This is a simple challenge. The task is to write code that outputs a 448*448 square image with 100% transparency. The output should follow the standard image rules. */ package main import ( "flag" "image" "image/png" "os" ) func main() { var w, h int flag.IntVar(&w, "width", 448, "window width") flag.In...
package main import ( "fmt" "house365.com/studyGo/lagagent/kafka" "house365.com/studyGo/lagagent/taillog" "math/rand" "os" "strings" "time" ) func run() { // 1 读取日志 for { select { case line := <-taillog.ReadChan(): // 2 发送到kafka kafka.SendToKafka("web_log", line.Text) default: time.Sleep(time....
package api import ( "errors" "fmt" "net/http" "regexp" "strconv" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/golang/glog" backend "github.com/zalando/chimp/backend" "github.com/zalando/chimp/conf" . "github.com/zalando/chimp/types" "github.com/zalando/chimp/validators" ) //...
package agents import gophercloud "github.com/zhuqinghua/gophercloud" func listURL(c *gophercloud.ServiceClient) string { return c.ServiceURL("agents") } func listDHCPNetworksURL(client *gophercloud.ServiceClient, id string) string { return client.ServiceURL("agents", id, "dhcp-networks") }
package main import ( "encoding/json" "fmt" "net/http" ) func main() { serverURL, serverPort, queryParamA, queryParamB := getInputValues() numbersArr, err := sendReqToServer(serverURL, serverPort, queryParamA, queryParamB) if err != nil { fmt.Println(err) return } fmt.Println(addArray(numbersArr)) } fu...
package dft type DataFileType int const ( CARCOLS DataFileType = iota + 1 CARVARIATIONS CONTENTUNLOCKS HANDLING VEHICLELAYOUTS VEHICLEMODELSETS VEHICLES WEAPONSFILE INVALID ) func (d DataFileType) String() string { return [...]string{"CARCOLS", "CARVARIATIONS", "CONTENTUNLOCKS", "HANDLING", "VEHICLELAYOUTS...
package compute import ( "bufio" "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "os/exec" "path/filepath" "sort" "strings" "sync" "github.com/BurntSushi/toml" "github.com/Masterminds/semver/v3" "github.com/fastly/cli/pkg/api" "github.com/fastly/cli/pkg/common" "github.com/fastly/cli/...
package main import ( "github.com/g-xianhui/op/server/pb" "github.com/golang/protobuf/proto" ) func toRoleBasic(r *RoleBasic) *pb.RoleBasic { b := &pb.RoleBasic{} b.Id = proto.Uint32(r.id) b.Occupation = proto.Uint32(r.occupation) b.Level = proto.Uint32(r.level) b.Name = proto.String(r.name) return b } func ...
package main import ( "encoding/xml" "fmt" ) func main() { type Email struct { Where string `xml:"where,attr"` Addr string } type Address struct { City, State string } type Result struct { XMLName xml.Name `xml:"Person"` Name string `xml:"FullName"` T []string `xml:"Thing>one"` T2 ...
package main import ( "encoding/json" "fmt" gen "github.com/youknowbopu/attack_map_server/generator" "log" "math/rand" "net/http" "path/filepath" "time" "golang.org/x/net/websocket" ) const bind = "127.0.0.1:9999" const workerNumber = 3 var wsConns []*websocket.Conn func dataHandler(ws *websocket.Conn) { ...
package mysqldb import ( "path/filepath" "strconv" "testing" "time" "math/rand" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" context "golang.org/x/net/context" ) const UserRegisterTypeLegacy = "LEGACY" // UserTestSuite 是 User 的 testSuite type UserTestSuite struct { suite.Suite ...
/* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
package main import ( "fmt" "unicode/utf8" ) func main() { str := "abc一二三🌚" strByte := []byte(str) for i := 0; i < len(str); { c, size := utf8.DecodeRune(strByte[i:]) fmt.Printf("---%d--%c---\n", i, c) i += size } }
// Copyright (C) 2020 Cisco Systems 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 agr...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-25 18:35 * Description: *****************************************************************/ package xhttpServer import ( "github.com/gorilla/mux" ...
// +build ignore package frclient import ( "fmt" "time" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance" "github.com/iotaledger/wasp/client/chainclient" "github.com/iotaledger/wasp/packages/coretypes" "github.com/io...
package project import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) //NewHandler handle project requests func NewHandler() sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { fmt.Println("In Project Handler: *****************************************************") return sdk.Result{} ...
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package test import ( "context" "github.com/diegobernardes/flare" ) // Trigger is a mock of the subscription.Trigger, this is used by tests. type Trigger ...
package sysinit /* 符号 含义 示例 * 表示任何时刻 , 表示分割 如第三段里:2,4,表示 2 点和 4 点执行 - 表示一个段 如第三端里: 1-5,就表示 1 到 5 点 /n 表示每个n的单位执行一次 如第三段里,1, 就表示每隔 1 个小时执行一次命令。也可以写成1-23/1 示例 详细含义 0/30 * * * * * 每 30 秒 执行 0 43 21 * * * 21:43 执行 0 0 17 * * 1 每周一的 17:00 执行 0 0,10 17 * * 0,2,3 每周日,周二,周三的 17:00和 17:10 执行 0 0 21 * ...
package main import ( "context" "database/sql" "fmt" "github.com/alexliesenfeld/health" _ "github.com/mattn/go-sqlite3" "log" "net/http" "time" ) // This is an example configuration that shows how Kubernetes liveness and readiness checks can be created with this // library (for more info, please visit // http...
package main import ( "fmt" "os" "github.com/philippklemmer/discordbotoverview-service/bot" "github.com/philippklemmer/discordbotoverview-service/config" ) func main() { err := config.ReadConfig() if err != nil { fmt.Println(err.Error()) os.Exit(0) } bot.Start() <-make(chan struct{}) return }
// Copyright © 2020. All rights reserved. // Author: Ilya Stroy. // Contacts: qioalice@gmail.com, https://github.com/qioalice // License: https://opensource.org/licenses/MIT package privet import ( "strings" ) type ( /* Locale is a storage of all translated phrases for one language. Getting locale by Client.LC(...
package main import( "fmt" "net/http" "io/ioutil" ) func main() { urls := []string{ "http://python.org", "http://golang.org"} responses := make(chan string) for _, url := range urls { go func(url string) { re...
package main import ( //"github.com/zhoujiagen/ProgrammingInGo/examples/hello" "github.com/zhoujiagen/ProgrammingInGo/examples/bigdigits" ) func main() { //hello.HelloWorld() }
package main import ( "github.com/igm/sockjs-go/sockjs" ) type ClientSessionTransport interface { Send(string) error Recv() (string, error) } type SockjsClientSessionTransport struct { ClientSessionTransport sock sockjs.Session } func (s *SockjsClientSessionTransport) Send(str string) error { return s.so...
package jqer import ( "context" "encoding/json" "fmt" "reflect" "sort" "strings" "time" "github.com/bbuck/go-lexer" "github.com/dop251/goja" "github.com/itchyny/gojq" ) var ( StringQueryRequiresWrappings bool TrimWhitespaceOnQueryStrings bool SearchInStrings bool WrappingBegin = "" WrappingIncr...
package routing_table import ( "errors" "github.com/cloudfoundry-incubator/runtime-schema/models" ) type RoutesByProcessGuid map[string][]string type ContainersByProcessGuid map[string][]Container func RoutesByProcessGuidFromDesireds(desireds []models.DesiredLRP) RoutesByProcessGuid { routes := RoutesByProcessGu...
package main import ( "fmt" "github.com/rossifedericoe/bootcamp/calculadora" ) func main() { var resultado int resultado = calculadora.Sumar(1, 2) fmt.Println(resultado) resultado = calculadora.SumarConConstante(1, 2) fmt.Println(resultado) }
package mempool import ( "errors" "fmt" "sync" "sync/atomic" "time" "github.com/meshplus/bitxhub-kit/storage" "github.com/meshplus/bitxhub-kit/types" "github.com/meshplus/bitxhub-model/pb" raftproto "github.com/meshplus/bitxhub/pkg/order/etcdraft/proto" "github.com/meshplus/bitxhub/pkg/peermgr" "github.co...
package paillier type PaillierConfig struct { Enable bool `yaml:"enable"` }
package middlewares import ( "github.com/golang-jwt/jwt" "github.com/labstack/echo/v4" ) func JWTSuccessHandler(c echo.Context) { user := c.Get("user").(*jwt.Token).Claims.(jwt.MapClaims) userId := uint(user["id"].(float64)) c.Set("userId", userId) }
package algorithm import "fmt" type BiTree interface{ SetValue(data int) SetLeft(v int) SetRight(v int) PreBiTree() PostBiTree() InBiTree() Layers() int GetLeft()*BiTreeNode BreathTraverse() DepthTraverse() } type BiTreeNode struct{ data int left, right *BiTreeNode } func NewBiTree() BiTree{ return &B...
package main import ( "fmt" "github.com/gin-contrib/cors" // Why do we need this package? "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" // If you want to use mysql or any other db, replace this line ) var db *gorm.DB ...
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func GetOrderCoupon(orderId int64) (*model.Coupon, error) { order, err := factories.FindOrderById(orderId) if order == nil { return nil, errors.New("order does not exists") } if ...
package geoserver import ( // "encoding/json" ) const ( GeoWorkSpace = "titangrm" ) type Workspaces struct { Workspaces *NameObject `json:"workspace"` } type DataStores struct { DataStore *DataStore `json:"dataStore"` } type DataStore struct { Name string `json:"name"` Connectio...
package quizzee import "strings" type Answer struct { Text string `json:"text"` CroppedText string `json:"cropped_text"` Words []string `json:"words"` Keys []string `json:"keys"` } func NewAnswer(text string) *Answer { return &Answer{ Text: text, } } func (a *Answer) Parse() error { ...
package main import ( "fmt" "github.com/jackytck/projecteuler/tools" ) func solve() int { low := 2 up := 354294 // 9**5 * 6 var sum int for i := low; i <= up; i++ { if int(tools.DigitSum(i, 5).Int64()) == i { sum += i } } return sum } func main() { fmt.Println(solve()) } // Sum of all the numbers t...
package san_test import ( "net" "testing" "github.com/IPA-CyberLab/kmgm/san" ) func TestAdd(t *testing.T) { var ns san.Names if err := ns.Add("192.168.0.1"); err != nil { t.Fatalf("unexpected err: %v", err) } if len(ns.IPAddrs) != 1 { t.Fatalf("unexpected") } if err := ns.Add("example.com"); err != ni...
package responses type ( UserResponse struct { Name string `json:"name"` AvatarURL string `json:"avatar_url"` } ) func NewUserResponse(name, avatarURL string) UserResponse { return UserResponse{ Name: name, AvatarURL: avatarURL, } }
package main import ( "fmt" "log" "net/http" ) func Root(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "") } func Health(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "{\"result\": \"OK\"}") } func main() { http.HandleFunc("/", Root) http.HandleFunc("/health", Health) log.Fatal(http.Li...
package main import ( "log" "net/http" "github.com/michaldziurowski/tech-challenge-time/server/timetracking/infrastructure" ) func corsHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Con...
package protocol type PingCmd struct { *Cmd } func (c *PingCmd) Deal() []byte { return Pong } func (c *PingCmd) paramInit() { }
package dbi import ( "database/sql" "fmt" "log" "strings" "time" "github.com/bingoohuang/pump/util" "github.com/bingoohuang/gou/str" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) // Batcher ... type Batcher interface { // GetBatchNum returns the batch num GetBatchNum() int // AddRow adds a r...
package main import ( "strings" "bufio" "os" "fmt" ) const inputPath = "input.txt" func main() { //import puzzle input into a 2d slice g := makeGrid(1001) tmp := parseInput(inputPath) //padding for i,j := (len(g)/2 - len(tmp)/2),0; j < len(tmp);i,j = i+1,j+1 { for k,l := (len(g)/2 - len(tmp)/2),0; l < len...
// Copyright 2020 Ant Group. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package tests import ( "fmt" "os" "os/exec" "testing" "time" "github.com/stretchr/testify/assert" ) var registryPort = 5051 func run(t *testing.T, cmd string, ignoreStatus bool) { _cmd := exec.Command("sh", "-c", cmd...
package main import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/tasks", ListTasks) router.POST("/tasks", NewTask) router.PUT("/tasks/:id", UpdateTask) router.Use(cors.Default()) router.Run(":9999") }
package main import ( "errors" "github.com/pkgz/logg" "github.com/spf13/cobra" "log" "os" "strings" ) var out string var link string var debug bool var rootCmd = &cobra.Command{ Use: "AOSDownloader", Short: "Apple OpenSource download tool", Version: "0.0.1", PreRunE: func(cmd *cobra.Command, args []s...
package charts import ( "github.com/go-echarts/go-echarts/v2/opts" "github.com/go-echarts/go-echarts/v2/render" "github.com/go-echarts/go-echarts/v2/types" ) // Bar3D represents a 3D bar chart. type Bar3D struct { Chart3D } // Type returns the chart type. func (*Bar3D) Type() string { return types.ChartBar3D } ...
package main func main() { } var ( dx = []int{1, 0, 0, -1} dy = []int{0, 1, -1, 0} ) func floodFill(image [][]int, sr int, sc int, newColor int) [][]int { currColor := image[sr][sc] if currColor != newColor { dfs(image, sr, sc, currColor, newColor) } return image } func dfs(image [][]int, x, y, color, newC...
package main import ( "encoding/json" "mysql_byroad/model" log "github.com/Sirupsen/logrus" "github.com/nsqio/go-nsq" ) type MessageHandler struct { } func (h *MessageHandler) HandleMessage(msg *nsq.Message) error { log.Debug(string(msg.Body)) evt := new(model.NotifyEvent) err := json.Unmarshal(msg.Body, evt...
package binance import ( "testing" "github.com/stretchr/testify/suite" ) type tickerServiceTestSuite struct { baseTestSuite } func TestTickerService(t *testing.T) { suite.Run(t, new(tickerServiceTestSuite)) } func (s *tickerServiceTestSuite) TestListBookTickers() { data := []byte(`[ { "sym...
package main import ( "log" "net/http" "golang.org/x/time/rate" ) func main() { limiter := rate.NewLimiter(1, 3) http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { if !limiter.Allow() { writer.WriteHeader(http.StatusTooManyRequests) writer.Write([]byte("too many request")) ...
package abstractfactory // SportMoterbike Concreate Implemenation of SportBike type SportMoterbike struct {} // NumWheels returns total number of wheels of SportMoterbike func (m *SportMoterbike) NumWheels() int { return 2 } // NumSeats returns total num of seats in SportMoterbike func (m *SportMoterbike) NumSeats(...
package main import ( "errors" "fmt" ) type Employee struct { ID int FirstName string LastName string Address string } func main() { employee, err := getInformation(1001) if errors.Is(err, ErrNotFound) { fmt.Printf("NOT FOUND: %v\n", err) } else { fmt.Print(employee) } } var ErrNotFound = er...
package kpatch import ( "bytes" "encoding/gob" "io" "os" "github.com/spf13/afero" ) var Fs = afero.NewOsFs() func init() { gob.Register(map[interface{}]interface{}{}) gob.Register([]interface{}{}) } func deepCopy(m map[interface{}]interface{}) (map[interface{}]interface{}, error) { var buf bytes.Buffer va...
package entity import "time" type Task struct { } type TaskResult struct { UUID int `json:"uuid"` Type int `json:"type"` Result interface{} `json:"result"` Time time.Time `json:"time"` }
package main import ( "fmt" "io" "io/ioutil" "net" "path" "strconv" "strings" "github.com/3Blades/go-sdk/client/projects" cssh "golang.org/x/crypto/ssh" ) // CreateSSHTunnels creates defined in db ssh tunnels func CreateSSHTunnels(args *Args) error { sshKeyAuth, err := getSSHKeyAuthMethod(args.ResourceDir)...
/* Consider you have a hash function H which takes strings of length 2n and returns strings of length n and has the nice property that it is collision resistant, i.e. it is hard to find two different strings s≠s′ with the same hash H(s)=H(s′). You would now like to build a new hash function H′ which takes strings of ...
// Package client provides common operations for files in cloud storage /* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * */ package client import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "math/rand" "net" "net/http" "strings" "sync" "time" "github.com/NVIDI...
package crypto import ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "strconv" "github.com/NavenduDuari/goinfo/crypto/utils" ) type coinData struct { Id string `json:"id"` Name string `json:"name"` Price string `json:"price"` Rank string `json:"rank"` OneDay oneDay `json:"1D"` } type oneDa...
/* * @lc app=leetcode.cn id=1941 lang=golang * * [1941] 检查是否所有字符出现次数相同 */ package main // @lc code=start func areOccurrencesEqual(s string) bool { counter := make([]int, 26) for i := 0; i < len(s); i++ { counter[s[i]-'a']++ } count := counter[s[0]-'a'] for _, c := range counter { if c != 0 && c != count {...
package geo import ( "math" ) const ( EarthRadiusMi = 3959 EarthRadiusKm = 6371 ) // Calculate Haversine distance between two lat/lon points on Earth. // Takes parameters in radians // Returns result in meters func Haversine(startLat, startLon, endLat, endLon float64) float64 { dLat := endLat - startLat dLon :=...
package main import ( "fmt" "strings" ) func main() { fmt.Println("****Pointers****") i, j := 42, 2701 p := &i // p = address of i fmt.Println(p) fmt.Println(*p) // print value referenced by p *p = 21 //value referenced by p = 21 fmt.Println(i) p = &j // p = address of j *p = *p / 37 // valu...
package lily import ( "fmt" "log" "runtime" "runtime/debug" ) func ErrPanic(err error, msg ...string) { if err != nil { if len(msg) > 0 { log.Panicln(err, msg[0]) } else { log.Panicln(err) } } } func ErrPanicSilent(err error) { if err != nil { panic(err) } } func ErrPanicWS(err error, msg ...s...
package irc import ( "container/ring" "fmt" log "github.com/Sirupsen/logrus" "github.com/fluffle/goirc/client" "github.com/fluffle/goirc/state" "go-chat-relay/src/globals" "go-chat-relay/src/helpers" "go-chat-relay/src/plug" "go-chat-relay/src/plug/config" "go-chat-relay/src/plugs" "runtime" "time" ) cons...
package gosnowth import ( "bytes" "context" "encoding/json" "fmt" "path" "strconv" "time" ) // NumericAllValueResponse values represent numeric data responses from IRONdb. type NumericAllValueResponse struct { Data []NumericAllValue } // UnmarshalJSON decodes a JSON format byte slice into a // NumericAllValu...
package config import ( "github.com/spf13/cobra" "github.com/wish/ctl/cmd/util/config" "github.com/wish/ctl/pkg/client" ) func fetchCmd(c *client.Client) *cobra.Command { return &cobra.Command{ Use: "fetch", Short: "Update extensions", Run: func(cmd *cobra.Command, args []string) { config.WriteCtlExt(c...
package leetcode /*Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign...
package main import ( qclReader "github.com/kf8a/qclreader" ) type qcl struct { connections map[*connection]bool register chan *connection unregister chan *connection host string } func newQcl(hostName string) *qcl { return &qcl{ connections: make(map[*connection]bool), register: make(chan *c...
package main import "fmt" type A interface { Foo() } type B interface { A Bar() } type T struct { } func (t T) Foo() { fmt.Println("Call Foo function form interface A") } func (t T) Bar() { fmt.Println("Call Bar function form interface B") } func main() { var t = T{} var a A = t a.Foo() var b B = t b....
package myeth import ( "bytes" "encoding/json" "errors" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/ethclient" "github.com/golang/glog" "io/ioutil" "runtime" "strings" ) /* 1.accountKey 对应的是要获取的账户地址的私钥信息,在节点的keysto...
package myhttp import ( "fmt" "runtime" "sync" ) func Start(limit int, urls []string) (err error) { // make available the maximum number possible of available cpu to execute go routine simultaneously runtime.GOMAXPROCS(runtime.NumCPU()) // create wait group that waits until go routines finish requesting urls ...
/* * @lc app=leetcode.cn id=32 lang=golang * * [32] 最长有效括号 */ package main import ( "fmt" ) /* 栈 func longestValidParentheses(s string) int { stack := []int{} maxLen := 0 // 方便求差 stack = append(stack, -1) for i, v := range s { if v == '(' { stack = append(stack, i) } else { stack = stack[:len(stac...
package dht import ( "context" "fmt" "testing" "time" tu "github.com/libp2p/go-libp2p-testing/etc" "github.com/stretchr/testify/require" ) // TODO Debug test failures due to timing issue on windows // Tests are timing dependent as can be seen in the 2 seconds timed context that we use in "tu.WaitFor". // Whi...
package main import ( "fmt" "math" ) type Point3 struct{ x,y,z float64} func (p *Point3) Abs() float64{ return math.Sqrt(p.x*p.x+p.y*p.y+p.z*p.z) } func main(){ t :=new(Point3) // 实例化 t.x=3 //选择器 t.y=4 t.z=5 fmt.Println(t.Abs()) k :=&Point3{8,9,10} //实例化,并初始化值 fmt.Println(k.Abs())...
package oiio import ( "testing" ) func TestNewROIEmpty(t *testing.T) { roi := NewROI() if roi.Defined() { t.Error("Expected empty ROI to returned Defined=false") } } func TestNewROIRegion2D(t *testing.T) { roi := NewROIRegion2D(100, 500, 50, 600) if !roi.Defined() { t.Error("Expected ROI to have a defined ...
package relax import ( "io/ioutil" "math" "github.com/mccoyst/vorbis" ) type Track struct { SampleRate int slider *VolumeSlider data []int16 curIdx int playing bool } func TrackFromOGGData(raw []byte) *Track { data, _, sr, err := vorbis.Decode(raw) if err != nil { panic(err) } track ...
package mdb import ( crand "crypto/rand" "io/ioutil" "math/rand" "os" "testing" ) // repeatedly put (overwrite) keys. func BenchmarkTxnPut(b *testing.B) { initRandSource(b) env, path := setupBenchDB(b) defer teardownBenchDB(b, env, path) dbi := openBenchDBI(b, env) var ps [][]byte rc := newRandSourceCur...
package example import "fmt" func (e *Element) print() { if e == nil { return } fmt.Println("Id:\t\t", e.Id) fmt.Println("Name:\t\t", e.Name) fmt.Println("Age:\t\t", e.Age) fmt.Println("Statue:\t\t", e.Status) fmt.Println("CreateAt:\t", e.CreatedAt) fmt.Println("UpdateAt:\t", e.CreatedAt) } func (es *Eleme...
package pkg import ( "testing" "time" "github.com/kyma-incubator/milv/cli" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewFileConfig(t *testing.T) { trueBool := true falseBool := false t.Run("Check if links to ignore are merged", func(t *testing.T) { //GIVEN comm...
package v1 import ( "context" "github.com/asecurityteam/nexpose-vuln-hydrator/pkg/domain" ) // DependencyCheckHandler takes in a domain.DependencyChecker, which // contains procedures that checks external dependencies type DependencyCheckHandler struct { DependencyChecker domain.DependencyChecker } // Handle cal...
package gatekeeper import ( "io" "io/ioutil" "net/http" ) type ResponseType uint const ( OkResponse ResponseType = iota + 1 RedirectResponse UserErrorResponse InternalErrorResponse ) var responseTypeMapping = map[ResponseType]string{ OkResponse: "2xx: ok", RedirectResponse: "3xx: redirect",...
// Copyright 2018 PingCAP, 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 i...
package main import ( "fmt" "sort" ) type IntSlice []int64 func (c IntSlice) Len() int { return len(c) } func (c IntSlice) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c IntSlice) Less(i, j int) bool { return c[i] < c[j] } func main() { var n int var l int64 var a IntSlice fmt.Scanf("%d %d\n",&n,&l) ...
package testfixtures const TomlConfigPath string = "testfixtures/testconfig.toml" const TestAppPath string = "testfixtures/postapp" var TestAppConfigPath = map[string]string{ "app": "config.toml", "route": "routes.toml", "middleware": "middlewares.toml", }
package main import ( "bufio" "container/list" "fmt" "os" ) type LRU struct { Len int Map map[int]*list.Element //哈希 link *list.List //双向队列,自带的 } type Elem struct { key int value interface{} } func NewLRU(Len int) *LRU { //实例化 return &LRU{ Len: Len, Map: map[int]*list.Element{}, li...
package mock //RepositoryMock ... type RepositoryMock struct{} const ConnectMock = 66 //ConnectName ... func (r RepositoryMock) ConnectName() int { return ConnectMock }
package failuredetector import ( "time" ) // EvtFailureDetector represents a Eventually Perfect Failure Detector as // described at page 53 in: // Christian Cachin, Rachid Guerraoui, and Luís Rodrigues: "Introduction to // Reliable and Secure Distributed Programming" Springer, 2nd edition, 2011. type EvtFailureDetec...
package generate const CONTROLLER_TEMPLATE = `package no.fint.consumer.models.{{ modelPkg .Package }}{{ ToLower .Name }}; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableMap; import io.swagger.annotations.Api; i...
package playfair import "strings" func Decrypt(cipher, key string) (string, error) { table := GenerateTable(key) var result []rune for i := 0; i < len(cipher); i += 2 { a, b := rune(cipher[i]), rune(cipher[i+1]) // shifts characters pos1, err := table.Find(a) if err != nil { return "", err } pos2,...
package SIMPLE type Environment map[string]Operand func CopyEnvironment(environment Environment) Environment { result := make(Environment, len(environment)) for key, value := range environment { result[key] = value } return result }
package systems import ( c "arkanoid/components" "github.com/ByteArena/ecs" ) // Views contains references to all views type Views struct { SpriteView *ecs.View } // InitViews initializes views func InitViews(manager *ecs.Manager, components *c.Components) *Views { return &Views{ SpriteView: manager.CreateVie...
package main import "fmt" func removeDuplicates(nums []int) int { n := len(nums) if n < 2 { return n } c, i := 0, 1 for i < n { if nums[c] != nums[i] { c++ nums[c] = nums[i] } i++ } return c + 1 } func main() { nums := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4} // nums is passed in by reference. (i....
package equinix import ( "context" "fmt" "log" "testing" "github.com/equinix/ne-go" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) const ( networkDeviceMetroEnvVar ...
package controllers import ( "dispatch/utils" "encoding/json" "fmt" "strings" "github.com/astaxie/beego" ) type DubboPostBody struct { Host string `json:"host"` Env string `json:"env"` Weight int `json:"weight"` Disable bool `json:"disable"` } type DubboController struct { beego.Controller } ...